Batch the development-fast round: tessellation without tessellationShader, primitive ids, mesh tooling, color groups, the vk12 floor, runtime timing and teardown fixes
One commit of the 247 on development-fast (720ef1ce9a..9f46fdf80d), squashed at the user's request. Translator: - Tessellation on a device without tessellationShader: Metal's tessellator emitted as SPIR-V, a one-workgroup scan placing each patch's triangles in Metal's order, and the post-tessellation function as a plain vertex stage (EmulatedTessellationDraws; SEMANTICS 1739, ARTIFACT_FORMAT 419). - [[primitive_id]] on a device without geometry or tessellation shaders, as a flat varying the vertex function writes; indexed lists, lines and points drawn de-indexed (RuntimeGap::PrimitiveIdIndices). - Fragment functions of more colors than the device draws at once, compiled in color groups (PrecisionNote::ColorAttachmentGroups). - Object functions' threadgroup memory from the render encoder; a kernel's mesh draws from an indirect command buffer; mesh payload sizing. - The Vulkan 1.2 floor profile (vk12-floor) and the gates it needs; Metal 27.0.1 answers as the M3 Max. - Overflow tests in the runtime-built modules by the product's high word (NVIDIA's compiler fails the division form), guarded crate-wide by tests::owned_divisions. Runtime: - Color-group passes replayed per group over twin depth/stencil; snapshot and copy-back cost cuts. - Command buffers finish on the queue waiter that saw them; the waiter holds no device handle, so a program's drop after its wait is the device's last. - Every object an encoder was handed held until its command buffer completes; deallocator order and announcements. - Driver defects recorded and announced: ANV counts a visibility sample once per color output (visibility-count-per-color); MoltenVK fails pending work when memory that held a device-address buffer is freed, so freed memory waits for the work in flight (host-deallocator-delayed). - RenderCommandEncoder::set_object_threadgroup_memory_length; Visibility::counting(). Validation: mesh tooling (object, mesh and ICB-mesh cases on both executors), the authoring census closed, the queue storm judged in Metal's unit, load-robust exits and indirect-census bounds, and the golden hashes, printouts, fixture inventory and authored compile census blessed. Docs: FAST-PATHS.md trimmed to a ledger of what is true now; API.md's catalogue and accepted differences, REFUSALS.md and METAL-COVERAGE.md current. Verified on development-fast before the squash: the full suites on the RTX 5080, RTX 3090, RX 7900 XTX, Radeon 780M, Iris Xe, lavapipe and the M3 (MoltenVK and the Metal oracle), lint in every configuration, rustdoc, doc tests, packaging and public case qualification; the timing and teardown lanes x5 on every venue; the authoring-capability census 16656/16656 with 0 unresolved, the vk12-floor translation census at 6139 translated with the slowest row 794 ms and peak 126 MiB. The tree is development-fast's at 9f46fdf80d.
This commit is contained in:
1 parent
720ef1ce9a
commit
0175289314
1298 files changed
+107683
-20507
No files matched your search
+37
-6
@@ -14,12 +14,43 @@ filter = 'test(/::soak_/)'
|
||||
slow-timeout = { period = "300s", terminate-after = 24 }
|
||||
|
||||
# The exit lanes' timing checks each run alone. Each measures a child process's exit, from its
|
||||
# last line to its end, against 1.5 s: below the exit hook's own bound, so a hook that waited it
|
||||
# out fails. That time holds the driver's device destruction and process teardown, which the
|
||||
# runtime does not set: on an RTX 3090 (NVIDIA 615.71.09) `vkDestroyDevice` took 54 ms alone (63
|
||||
# devices, at most 57 ms) and up to 2 s while other lane processes used the GPU (over 500 ms for
|
||||
# 39 of 72 beside `runtime_lane::framebuffer_fetch`); exits that took 87 to 97 ms alone took 0.3
|
||||
# to 3.1 s beside other lanes there, and 1.8 to 2 s in an RTX 5080 Laptop GPU's whole suite.
|
||||
# last line to the end of its exit handlers, less the exiting thread's wait for a CPU, against
|
||||
# 1.5 s: below the exit hook's own bound, so a hook that waited it out fails. That time holds the
|
||||
# driver's device destruction, which the runtime does not set: on an RTX 3090 (NVIDIA 615.71.09)
|
||||
# `vkDestroyDevice` took 54 ms alone (63 devices, at most 57 ms) and up to 2 s while other lane
|
||||
# processes used the GPU (over 500 ms for 39 of 72 beside `runtime_lane::framebuffer_fetch`);
|
||||
# exits that took 87 to 97 ms alone took 0.3 to 3.1 s beside other lanes there, and 1.8 to 2 s in
|
||||
# an RTX 5080 Laptop GPU's whole suite.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(metal2vulkan-validation) & test(/^runtime_lane::exits::(pending_work_stays_pending_at_exit|exits_from_the_runtime_s_threads_are_clean|an_exit_while_a_host_step_waits_is_clean|an_exit_waits_for_a_cpu_device_s_work|an_exit_while_submitting_is_clean|exits_right_after_learning_of_completion_are_clean)$/)'
|
||||
threads-required = 'num-test-threads'
|
||||
|
||||
# The lanes that fault the GPU on purpose (a GPU write into read-only host pages; they make GPU work
|
||||
# on MoltenVK alone) run alone on macOS. Metal's recovery from a GPU fault fails command buffers of
|
||||
# other processes the GPU runs then, as `MTLCommandBufferErrorInternal` ("Discarded (victim of GPU
|
||||
# error/recovery) (00000005:kIOGPUCommandBufferCallbackErrorInnocentVictim)", the encoder
|
||||
# `Affected`), and completes some with wrong results and no error: a plain Metal probe on the M3
|
||||
# Max (macOS 27.0.1), the lane's texture round in one process beside processes that each fault
|
||||
# once, failed 19 of 52,592 rounds beside 160 faults that way and completed 4 more with wrong
|
||||
# bytes, and none of 12,270 rounds alone. `runtime_lane::host_copied_textures` failed with `Execution(1)` in 4 batches,
|
||||
# each beside `a_gpu_fault_fails_its_command_buffer_and_the_queue_runs_on`; in 100 runs alone and
|
||||
# 100 beside the other `host_*` lanes it never failed.
|
||||
[[profile.default.overrides]]
|
||||
platform = 'cfg(target_os = "macos")'
|
||||
filter = 'package(metal2vulkan-validation) & test(/^runtime_lane::host_memory::(a_gpu_fault_fails_its_command_buffer_and_the_queue_runs_on|a_lost_device_s_command_buffers_let_go_of_their_pools_after_the_driver_s_completion)$/)'
|
||||
threads-required = 'num-test-threads'
|
||||
|
||||
# The queue storm runs alone on macOS. Beside the runtime lane's other tests on the M3 Max (macOS
|
||||
# 27.0.1, MoltenVK 1.4.1, load average 18 to 24) the runtime passed 1 storm of 4: its light bursts'
|
||||
# 99th percentile was 1.6 to 5.6 busy command buffers above Metal's under MoltenVK's fences, against
|
||||
# a margin of 1, and its median within 0.1. That tail is MoltenVK's completion path into the
|
||||
# runtime's queue waiter: from a burst's submission to its completion as the runtime saw it, 25.9
|
||||
# to 73.4 ms at the 99th percentile, where Metal's to its GPU end took 8.5 to 18.1 ms. The
|
||||
# runtime's wake from there, 6.0 to 30.0 ms, was at or below Metal's 13.4 to 45.9 ms in every
|
||||
# storm. Alone it still catches the runtime's own delays: it passed 5 storms of 5 on a quiet host,
|
||||
# and failed 3 of 3 with 10 ms spun in each of the runtime's completion turns (a probe build), its
|
||||
# bursts' median 3.53 busy command buffers against 2.03.
|
||||
[[profile.default.overrides]]
|
||||
platform = 'cfg(target_os = "macos")'
|
||||
filter = 'package(metal2vulkan-validation) & test(/^runtime_lane::queue_storms::four_queues_storm_as_metal_s_do$/)'
|
||||
threads-required = 'num-test-threads'
|
||||
+8
-4
@@ -83,7 +83,11 @@ cargo build --release -p metal2vulkan --features cli
|
||||
## Golden output hashes and `SEMANTICS_VERSION`
|
||||
|
||||
`src/tests/golden_hashes.rs` pins a hash of the final SPIR-V (or the refusal class) of every public
|
||||
fixture entry point on every committed profile, in `crates/metal2vulkan/tests/golden_hashes.tsv`.
|
||||
fixture entry point on every committed profile, in `crates/metal2vulkan/tests/golden_hashes.tsv`,
|
||||
and of every fixture that samples, gathers or computes a level of detail under every exact form
|
||||
(Metal's sampler emulated and `DevicePolicy::exact_answers`), in
|
||||
`crates/metal2vulkan/tests/golden_hashes_exact.tsv`: the default policy samples natively, so only
|
||||
that table holds the sampler's emulation.
|
||||
`cache::SEMANTICS_VERSION` is part of every cache key, so a change that moves a cell while its
|
||||
fixture and profile are unchanged must bump `SEMANTICS_VERSION`
|
||||
(`crates/metal2vulkan/src/cache/mod.rs`) in the same change. New, removed or edited fixtures and
|
||||
@@ -91,15 +95,15 @@ profiles need only the bless. The table records cells only, no version: a `SEMAN
|
||||
alone leaves it unchanged, and the bless on `development` refuses a cell that moved under an
|
||||
unchanged fixture and profile when `SEMANTICS_VERSION` is still its value at the table's last bless.
|
||||
|
||||
The table is re-blessed on `development` after merges, so a change need not carry its own bless. To
|
||||
bless by hand (on macOS, which has `xcrun metal-as`):
|
||||
The tables are re-blessed on `development` after merges, so a change need not carry its own bless.
|
||||
One command blesses both (on macOS, which has `xcrun metal-as`):
|
||||
|
||||
```sh
|
||||
PATH=/opt/homebrew/opt/llvm/bin:$PATH cargo nextest run -p metal2vulkan --all-features \
|
||||
--run-ignored ignored-only -E 'test(bless_golden_hashes)'
|
||||
```
|
||||
|
||||
Never merge the table by hand: after a merge take `development`'s table and bless again. The other
|
||||
Never merge a table by hand: after a merge take `development`'s tables and bless again. The other
|
||||
versions move the same way when their behavior changes: `ARTIFACT_FORMAT_VERSION` (the artifact
|
||||
encoding) and `RUNTIME_VERSION` (what the runtime does with an unchanged artifact).
|
||||
|
||||
|
||||
@@ -82,7 +82,8 @@ metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json
|
||||
examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK.
|
||||
- Without `--function` it compiles the library's only kernel or vertex function. A kernel with
|
||||
`--color-format` compiles as a tile pipeline. A post-tessellation vertex function adds
|
||||
`.tesc.spv` and `.tese.spv` modules.
|
||||
`.tesc.spv` and `.tese.spv` modules on a device with `tessellationShader`; on one without, it is
|
||||
the `.vert.spv` module itself, which draws the tessellator's triangles.
|
||||
- A compile that needs a pipeline input fails naming it and the option that supplies it:
|
||||
`--constant ID:TYPE:VALUE` for a function constant, `--stage-input FILE` or
|
||||
`--vertex-descriptor FILE` for a stage-input or vertex descriptor (as JSON).
|
||||
|
||||
@@ -42,7 +42,10 @@
|
||||
//! declaration that stays is a post-tessellation entry's control-point fetch
|
||||
//! (`air.patch_control_point_function`, whose body Metal synthesizes from the vertex descriptor)
|
||||
//! with the entry's control-point input as its pointer operand; `lower::tessellation` lowers it.
|
||||
//! 9. **Rasterization-rate maps**: each `float2` `air.map_*_coordinates` call becomes Apple's GPU
|
||||
//! 9. **Arm speculation**: a branch whose short arms Metal's backend runs in every lane of the
|
||||
//! branch's block, and whose arms hold a group operation that answers differently there,
|
||||
//! becomes a jump into its arms with a `select` for each value they join with (`speculate`).
|
||||
//! **Rasterization-rate maps**: each `float2` `air.map_*_coordinates` call becomes Apple's GPU
|
||||
//! decoder of Metal's parameter data (`rate_map_data`) in plain AIR: word loads through the
|
||||
//! call's map pointer and Apple's arithmetic. **AIR 2.7 simdgroup-matrix block loads and
|
||||
//! stores** take their AIR 2.8 form, their extent, stride and origin built from the elements per
|
||||
@@ -92,6 +95,9 @@ mod renumber;
|
||||
mod rewrite;
|
||||
mod routine;
|
||||
mod sccp;
|
||||
mod speculate;
|
||||
#[cfg(test)]
|
||||
mod speculate_tests;
|
||||
mod static_init;
|
||||
mod table_copy;
|
||||
#[cfg(test)]
|
||||
@@ -592,6 +598,18 @@ pub fn specialize_dynamic(
|
||||
};
|
||||
matmul2d::refuse_left(&body, &parts, &ep.stage, &name, m)?;
|
||||
post_check(&body, &parts, &stubs, &name, &control_points(ep), m)?;
|
||||
// A branch's short arms that Metal's backend speculates, where a group operation in them
|
||||
// answers over the lanes of the branch's block.
|
||||
let body = {
|
||||
let f = parts
|
||||
.funcs
|
||||
.get(func)
|
||||
.ok_or_else(|| invariant("entry out of range"))?;
|
||||
let Some(Type::Function { params: tys, .. }) = parts.types.get(f.ty) else {
|
||||
return Err(invariant("the entry's type is not a function"));
|
||||
};
|
||||
speculate::expand(body, (&parts.types, &parts.consts), (tys, &f.params), m)?
|
||||
};
|
||||
// Rasterization-rate maps: each `float2` map call becomes Apple's GPU decoder of the parameter
|
||||
// data, word loads through its own map pointer.
|
||||
let body = rate_map::expand(body, &mut parts, m)?;
|
||||
|
||||
@@ -82,9 +82,10 @@
|
||||
//! ("Compute pipeline exceeds available stack space"): the refusal is
|
||||
//! `LimitExceeded(CallStackBytes)`, also for linked functions that do not recurse. The stacks are
|
||||
//! the thread's Function storage, allocas like its others: selection holds the entry's private
|
||||
//! memory to what the device holds correctly (`ProfileFields::function_storage`), and refuses a
|
||||
//! recursion past it as `Unsupported{Recursion}` needing more, since past it a driver can answer
|
||||
//! wrongly or hang with no error.
|
||||
//! memory to what the device holds correctly (`ProfileFields::function_storage`; a vertex or
|
||||
//! fragment function on a device not measured to Metal's 192 KiB, noted), and refuses a recursion
|
||||
//! past it as `Unsupported{Recursion}` needing more, since past it a driver can answer wrongly or
|
||||
//! hang with no error.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ pub(super) struct BodyEdit {
|
||||
/// order. The pass guarantees that every operand still dominates the new place and that the
|
||||
/// new place dominates every use.
|
||||
pub moved: BTreeMap<InstId, BlockId>,
|
||||
/// Instructions whose rewritten operation (`rewrite`) has another type than the old one.
|
||||
pub retype: BTreeMap<InstId, TypeId>,
|
||||
}
|
||||
|
||||
impl BodyEdit {
|
||||
@@ -44,6 +46,7 @@ impl BodyEdit {
|
||||
keep: filled(m, held, body.blocks.len(), true)?,
|
||||
delete: filled(m, held, body.insts.len(), false)?,
|
||||
moved: BTreeMap::new(),
|
||||
retype: BTreeMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -247,7 +250,8 @@ fn apply_in(
|
||||
if let Some(e) = failed {
|
||||
return Err(e);
|
||||
}
|
||||
out.push_inst(Inst { ty: old.ty, kind }, m)?;
|
||||
let ty = edit.retype.get(&i).copied().unwrap_or(old.ty);
|
||||
out.push_inst(Inst { ty, kind }, m)?;
|
||||
}
|
||||
let end = InstId::new(u32::try_from(out.insts.len()).map_err(|_| invariant("ids"))?);
|
||||
out.blocks.push(
|
||||
|
||||
@@ -0,0 +1,870 @@
|
||||
//! A branch's short arms, which Metal's backend speculates.
|
||||
//!
|
||||
//! Metal's backend runs a branch's arms of plain computation in every lane that reaches the
|
||||
//! branch, and picks each result the arms join with by the branch's condition (if-conversion).
|
||||
//! A group operation in such an arm then runs in every lane of the branch's block: Metal's
|
||||
//! `quad_broadcast_first` in `if (t % 3 != 0) r = quad_broadcast_first(10 t + 1);` answers with
|
||||
//! the quad's lane 0 whether it takes the arm or not, where the AIR's branch would give the quad's
|
||||
//! first lane that takes it.
|
||||
//!
|
||||
//! **What Metal does** (the Apple M3 Max, macOS 27.0.1, runtime-compiled MSL 64-thread kernels
|
||||
//! whose arms the condition `t % 3 != 0` takes, read in their AIR (`xcrun metal -S -emit-llvm`)):
|
||||
//! - **The operations.** An arm holding a quad shuffle, broadcast, vote (`all`, `any`,
|
||||
//! `ballot`, `is_first`, `active_threads_mask`) or `quad_broadcast_first`, a simdgroup shuffle
|
||||
//! (not `simd_broadcast`) or `simd_is_first` is speculated: each answers over the lanes of the
|
||||
//! branch's block. One holding a quad reduction or scan, `simd_broadcast`,
|
||||
//! `simd_broadcast_first`, a simdgroup reduction, scan or vote other than `is_first` is not, and
|
||||
//! the arm's other operations then keep the arm's lanes too (all 52 measured, each beside a
|
||||
//! `quad_broadcast_first`).
|
||||
//! - **The rest of the arm.** Integer and float arithmetic (a division too), conversions,
|
||||
//! `freeze`, `select`, `sqrt`, and a load through a `constant` reference parameter are
|
||||
//! speculated; a device, threadgroup or texture read, an atomic, a store, a loop, or a second
|
||||
//! exit are not. A store that repeats the branch's block's last store to the same pointer is
|
||||
//! speculated as a store of the chosen value (`out[t] = 7777; if (c) out[t] = ...;`); a store
|
||||
//! to another pointer is not.
|
||||
//! - **The size.** One arm (a triangle): speculated up to 25 instructions (a sunk store and the
|
||||
//! branch not counted), not from 26, for arms of 32-bit integer arithmetic (chains with and
|
||||
//! without multiplications, divisions, one or two results), comparisons and selects of values,
|
||||
//! `freeze`s and up to eight quad broadcasts. An arm holding another kind is not known to follow
|
||||
//! that budget: one of quad votes, 16-bit masks, casts and selects of constants is speculated at
|
||||
//! 21 instructions and not at 25 (`r = quad_is_first() | quad_active_threads_mask() << 1 |
|
||||
//! quad_all(...) << 5 | ...;`, with its `%` replaced by a mask too). Two arms (a diamond):
|
||||
//! speculated up to 25 in both together, not from 26; and where the arm the condition's true
|
||||
//! edge takes holds at most 3 instructions and no call, whenever the other arm holds at most 25
|
||||
//! (up to 28 in both measured). An arm of at most 3 instructions with a call on the false edge
|
||||
//! is not exempt (1 + 25 and 3 + 25 not speculated).
|
||||
//! - **Nesting.** A short branch inside an arm is speculated first and counts with the arm it
|
||||
//! joins (`if (c) { if (d) x = ...; r = op(x); }`); a branch inside a loop is speculated alike.
|
||||
//!
|
||||
//! [`expand`] speculates each outermost branch Metal speculates whose arms hold a group operation
|
||||
//! that answers differently there (the operations above): the branch becomes a jump into its arm
|
||||
//! (a diamond's arms run one after the other), each value the arms join with becomes a `select`
|
||||
//! on the condition, and a sunk store stores the chosen value where the arms join. A branch whose
|
||||
//! arms hold no such operation is left as it is, as is one whose arms hold an instruction no
|
||||
//! measurement covers (a vector or aggregate operation, an address computation, a math function
|
||||
//! other than `sqrt`, a call outside the families above, a load other than a `constant`
|
||||
//! reference's), that join with more than two values or with a pointer, that divide integers by a
|
||||
//! value (speculated, a division by zero where the condition guarded it is undefined in SPIR-V),
|
||||
//! that hold 22 to 25 instructions with one of a kind the budget was not measured with
|
||||
//! ([`OFF_EDGE`]), or of one of the two diamond shapes no probe covers (a small arm without a call
|
||||
//! on the false edge, or with one on the true edge, past 25 together): those keep the AIR's lanes,
|
||||
//! a known gap.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::budget::Meter;
|
||||
use crate::error::Error;
|
||||
use crate::graph::Cfg;
|
||||
use crate::intrinsics::{AirIntrinsic, GroupOp, GroupScope, Math, MathFn, TexOp};
|
||||
use crate::ir::{AddrSpace, BinOp, BlockId, Body, Callee, FastMath, Idx, InstId, InstKind};
|
||||
use crate::ir::{ConstTable, TypeId, TypeTable, Value};
|
||||
use crate::ir::{Param, Type};
|
||||
|
||||
use super::rewrite::{apply, scoped, BodyEdit};
|
||||
|
||||
/// The most instructions Metal's backend speculates in a branch's arms, measured with arms of
|
||||
/// 32-bit integer arithmetic, comparisons and selects of values, `freeze`s and quad broadcasts.
|
||||
const BUDGET: usize = 25;
|
||||
|
||||
/// The most instructions Metal was measured to speculate in arms holding another kind (a vote, a
|
||||
/// cast, a 16-bit operation, a select of a constant): 21 speculated, 25 of the same kinds not. Such
|
||||
/// an arm of 22 to [`BUDGET`] instructions is unknown.
|
||||
const OFF_EDGE: usize = 21;
|
||||
|
||||
/// The most instructions of a diamond's arm on the condition's true edge, without a call, that
|
||||
/// Metal speculates beside a whole budget in the other arm.
|
||||
const SMALL: usize = 3;
|
||||
|
||||
/// The instructions before a branch searched for the store a sunk store repeats: LLVM's
|
||||
/// SimplifyCFG window (the measured store lies three back).
|
||||
const LOOKBACK: usize = 9;
|
||||
|
||||
/// The deepest nesting of branches inside an arm the walk follows.
|
||||
const DEPTH: usize = 8;
|
||||
|
||||
/// The most blocks one arm's walk takes.
|
||||
const ARM_BLOCKS: usize = 64;
|
||||
|
||||
/// What Metal does with a branch's arms.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Decision {
|
||||
/// Speculated: the arms run in every lane of the branch's block.
|
||||
Speculated,
|
||||
/// Kept: a measured reason keeps the branch.
|
||||
Kept,
|
||||
/// No measurement covers the arms.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// What an arm holds.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct Content {
|
||||
/// The instructions Metal counts.
|
||||
cost: usize,
|
||||
/// A group operation that answers over the branch's block's lanes when speculated.
|
||||
group: bool,
|
||||
/// Something Metal never speculates.
|
||||
blocker: bool,
|
||||
/// Something no measurement covers.
|
||||
unmeasured: bool,
|
||||
/// A call.
|
||||
calls: bool,
|
||||
/// An instruction of a kind the budget was not measured with ([`OFF_EDGE`]).
|
||||
off_edge: bool,
|
||||
}
|
||||
|
||||
impl Content {
|
||||
fn add(&mut self, o: Content) {
|
||||
self.cost = self.cost.saturating_add(o.cost);
|
||||
self.group |= o.group;
|
||||
self.blocker |= o.blocker;
|
||||
self.unmeasured |= o.unmeasured;
|
||||
self.calls |= o.calls;
|
||||
self.off_edge |= o.off_edge;
|
||||
}
|
||||
}
|
||||
|
||||
/// One arm: the blocks from `first` to `last`, entered from the branch's block alone.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Arm {
|
||||
first: BlockId,
|
||||
last: BlockId,
|
||||
/// The arm the condition's true edge takes.
|
||||
on_true: bool,
|
||||
blocks: Vec<BlockId>,
|
||||
content: Content,
|
||||
/// The branches nested in the arm.
|
||||
inner: Vec<Fold>,
|
||||
}
|
||||
|
||||
/// A branch whose arms rejoin at `join`: one arm (a triangle) or two (a diamond).
|
||||
#[derive(Clone, Debug)]
|
||||
struct Fold {
|
||||
head: BlockId,
|
||||
cond: Value,
|
||||
arms: Vec<Arm>,
|
||||
join: BlockId,
|
||||
/// A sunk store: the branch's block's store and the arm's store to the same pointer.
|
||||
sunk: Option<(InstId, InstId)>,
|
||||
content: Content,
|
||||
decision: Decision,
|
||||
}
|
||||
|
||||
/// What the walk reads.
|
||||
struct Cx<'a> {
|
||||
body: &'a Body,
|
||||
cfg: &'a Cfg<BlockId>,
|
||||
types: &'a TypeTable,
|
||||
consts: &'a ConstTable,
|
||||
/// The entry's parameter types and attributes.
|
||||
param_tys: &'a [TypeId],
|
||||
params: &'a [Param],
|
||||
}
|
||||
|
||||
impl Cx<'_> {
|
||||
fn preds(&self, b: BlockId) -> Vec<BlockId> {
|
||||
self.cfg.predecessors(b).collect()
|
||||
}
|
||||
|
||||
fn value_ty(&self, v: Value) -> Option<TypeId> {
|
||||
value_ty(self.body, self.consts, self.param_tys, v)
|
||||
}
|
||||
|
||||
fn is_pointer(&self, v: Value) -> bool {
|
||||
self.value_ty(v)
|
||||
.and_then(|t| self.types.get(t))
|
||||
.is_some_and(|t| matches!(t, Type::Ptr { .. }))
|
||||
}
|
||||
|
||||
fn space(&self, v: Value) -> Option<AddrSpace> {
|
||||
match self.types.get(self.value_ty(v)?)? {
|
||||
Type::Ptr { space } => Some(*space),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `v` is a 32-bit integer.
|
||||
fn word(&self, v: Value) -> bool {
|
||||
self.value_ty(v)
|
||||
.and_then(|t| self.types.get(t))
|
||||
.is_some_and(|t| *t == Type::Int(32))
|
||||
}
|
||||
|
||||
/// Whether an instruction of kind `kind` is of a kind the budget was measured with: 32-bit
|
||||
/// integer arithmetic, a comparison of 32-bit integers, a select of two values that are not
|
||||
/// constants, a `freeze`, or a broadcast or shuffle of a group (`BUDGET`).
|
||||
fn on_edge(&self, kind: &InstKind) -> bool {
|
||||
match kind {
|
||||
InstKind::BinOp { a, b, .. } => self.word(*a) && self.word(*b),
|
||||
InstKind::ICmp { a, b, .. } => self.word(*a) && self.word(*b),
|
||||
InstKind::Select { t, f, .. } => {
|
||||
!matches!(t, Value::Const(_)) && !matches!(f, Value::Const(_)) && self.word(*t)
|
||||
}
|
||||
InstKind::Freeze(_) => true,
|
||||
InstKind::Call(c) => match &c.callee {
|
||||
Callee::Air {
|
||||
op: AirIntrinsic::Group(g),
|
||||
..
|
||||
} => !matches!(
|
||||
g.op,
|
||||
GroupOp::IsFirst
|
||||
| GroupOp::All
|
||||
| GroupOp::Any
|
||||
| GroupOp::Ballot
|
||||
| GroupOp::ActiveThreadsMask
|
||||
),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The content of instruction `kind` in an arm (a store is the caller's).
|
||||
fn class(&self, kind: &InstKind) -> Content {
|
||||
let c = self.cost_class(kind);
|
||||
Content {
|
||||
off_edge: !self.on_edge(kind),
|
||||
..c
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Cx::class`] but whether its kind is on the budget's edge.
|
||||
fn cost_class(&self, kind: &InstKind) -> Content {
|
||||
let plain = Content {
|
||||
cost: 1,
|
||||
..Content::default()
|
||||
};
|
||||
let blocker = Content {
|
||||
blocker: true,
|
||||
..plain
|
||||
};
|
||||
let unmeasured = Content {
|
||||
unmeasured: true,
|
||||
..plain
|
||||
};
|
||||
match kind {
|
||||
// An integer division by a value the arm's condition may guard: speculated, it would
|
||||
// divide by zero in a lane that takes no arm, which SPIR-V leaves undefined, where
|
||||
// Metal's division answers (a division was measured speculated).
|
||||
InstKind::BinOp {
|
||||
op: BinOp::UDiv | BinOp::SDiv | BinOp::URem | BinOp::SRem,
|
||||
b,
|
||||
..
|
||||
} if !matches!(b, Value::Const(_)) => unmeasured,
|
||||
InstKind::BinOp { .. }
|
||||
| InstKind::FNeg { .. }
|
||||
| InstKind::Cast { .. }
|
||||
| InstKind::ICmp { .. }
|
||||
| InstKind::FCmp { .. }
|
||||
| InstKind::Select { .. }
|
||||
| InstKind::Freeze(_) => plain,
|
||||
InstKind::Load {
|
||||
ptr,
|
||||
volatile: false,
|
||||
atomic: None,
|
||||
..
|
||||
} => match (*ptr, self.space(*ptr)) {
|
||||
(Value::Arg(n), Some(AddrSpace::Constant))
|
||||
if self
|
||||
.params
|
||||
.get(n.index())
|
||||
.is_some_and(|p| p.attrs.dereferenceable.is_some()) =>
|
||||
{
|
||||
plain
|
||||
}
|
||||
(_, Some(AddrSpace::Device | AddrSpace::Threadgroup)) => blocker,
|
||||
_ => unmeasured,
|
||||
},
|
||||
InstKind::Load { .. }
|
||||
| InstKind::Store { .. }
|
||||
| InstKind::AtomicRmw { .. }
|
||||
| InstKind::CmpXchg { .. }
|
||||
| InstKind::Fence(_) => blocker,
|
||||
InstKind::Call(c) => {
|
||||
let call = Content {
|
||||
calls: true,
|
||||
..plain
|
||||
};
|
||||
match &c.callee {
|
||||
Callee::Air { op, .. } => match op {
|
||||
AirIntrinsic::Group(g) => match speculated(g.scope, g.op) {
|
||||
true => Content {
|
||||
group: true,
|
||||
..call
|
||||
},
|
||||
false => Content {
|
||||
blocker: true,
|
||||
..call
|
||||
},
|
||||
},
|
||||
// The measured calls: `sqrt` and a conversion.
|
||||
AirIntrinsic::Math(Math {
|
||||
f: MathFn::Sqrt, ..
|
||||
})
|
||||
| AirIntrinsic::Convert(_)
|
||||
if !c.args.iter().any(|&a| self.is_pointer(a)) =>
|
||||
{
|
||||
call
|
||||
}
|
||||
AirIntrinsic::Atomic(_) => Content {
|
||||
blocker: true,
|
||||
..call
|
||||
},
|
||||
AirIntrinsic::Texture(t) if t.op == TexOp::Read => Content {
|
||||
blocker: true,
|
||||
..call
|
||||
},
|
||||
_ => Content {
|
||||
unmeasured: true,
|
||||
..call
|
||||
},
|
||||
},
|
||||
_ => Content {
|
||||
unmeasured: true,
|
||||
..call
|
||||
},
|
||||
}
|
||||
}
|
||||
_ => unmeasured,
|
||||
}
|
||||
}
|
||||
|
||||
/// The content of block `b`'s instructions but its terminator, its PHIs counted as the
|
||||
/// selects they become where `joined` (a nested branch's join).
|
||||
fn block(&self, b: BlockId, joined: bool) -> Content {
|
||||
let mut c = Content::default();
|
||||
for (_, i) in self.body.block_insts(b) {
|
||||
match &i.kind {
|
||||
k if k.is_terminator() => {}
|
||||
InstKind::Phi { .. } if joined => c.cost = c.cost.saturating_add(1),
|
||||
InstKind::Phi { .. } => c.unmeasured = true,
|
||||
k => c.add(self.class(k)),
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// Walk an arm from `first`, entered from `from` alone: the blocks it runs through, nested
|
||||
/// branches folded, to the first block it reaches that more than its last block enters.
|
||||
/// `None` where it is no arm (a second entry, a loop, a return or switch).
|
||||
fn walk(
|
||||
&self,
|
||||
first: BlockId,
|
||||
from: BlockId,
|
||||
depth: usize,
|
||||
m: &mut Meter,
|
||||
) -> Result<Option<(Arm, BlockId)>, Error> {
|
||||
if self.preds(first) != [from] {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut arm = Arm {
|
||||
first,
|
||||
last: first,
|
||||
on_true: false,
|
||||
blocks: Vec::new(),
|
||||
content: Content::default(),
|
||||
inner: Vec::new(),
|
||||
};
|
||||
let mut b = first;
|
||||
let mut joined = false;
|
||||
loop {
|
||||
m.tick(1)?;
|
||||
if arm.blocks.len() >= ARM_BLOCKS {
|
||||
return Ok(None);
|
||||
}
|
||||
arm.blocks.push(b);
|
||||
arm.content.add(self.block(b, joined));
|
||||
arm.last = b;
|
||||
match self.body.terminator(b).map(|t| &t.kind) {
|
||||
Some(InstKind::Br { dest, .. }) => {
|
||||
if self.preds(*dest) == [b] && *dest != first {
|
||||
b = *dest;
|
||||
joined = false;
|
||||
continue;
|
||||
}
|
||||
return Ok(Some((arm, *dest)));
|
||||
}
|
||||
Some(InstKind::CondBr { .. }) if depth < DEPTH => {
|
||||
let Some(inner) = self.fold(b, depth + 1, m)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
for a in &inner.arms {
|
||||
arm.blocks.extend(a.blocks.iter().copied());
|
||||
arm.content.add(a.content);
|
||||
}
|
||||
let join = inner.join;
|
||||
if arm.blocks.contains(&join) {
|
||||
return Ok(None);
|
||||
}
|
||||
arm.inner.push(inner);
|
||||
b = join;
|
||||
joined = true;
|
||||
}
|
||||
_ => return Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The branch ending block `head` as Metal's backend folds it, when its arms rejoin.
|
||||
fn fold(&self, head: BlockId, depth: usize, m: &mut Meter) -> Result<Option<Fold>, Error> {
|
||||
let Some(InstKind::CondBr { c, t, f, .. }) = self.body.terminator(head).map(|i| &i.kind)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (c, t, f) = (*c, *t, *f);
|
||||
if t == f || t == head || f == head {
|
||||
return Ok(None);
|
||||
}
|
||||
let wt = self.walk(t, head, depth, m)?;
|
||||
let wf = self.walk(f, head, depth, m)?;
|
||||
let joins = |j: BlockId, a: BlockId, b: BlockId| {
|
||||
let mut p = self.preds(j);
|
||||
p.sort();
|
||||
let mut want = vec![a, b];
|
||||
want.sort();
|
||||
p == want
|
||||
};
|
||||
let (arms, join) = match (wt, wf) {
|
||||
(Some((mut a, exit)), _) if exit == f && joins(f, head, a.last) => {
|
||||
a.on_true = true;
|
||||
(vec![a], f)
|
||||
}
|
||||
(_, Some((a, exit))) if exit == t && joins(t, head, a.last) => (vec![a], t),
|
||||
(Some((mut a, ea)), Some((b, eb))) if ea == eb && joins(ea, a.last, b.last) => {
|
||||
a.on_true = true;
|
||||
(vec![a, b], ea)
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let mut content = Content::default();
|
||||
let mut sunk = None;
|
||||
for a in &arms {
|
||||
content.add(a.content);
|
||||
}
|
||||
// The values the arms join with: one or two measured, each a `select` the lowering takes
|
||||
// (a pointer's is not one).
|
||||
let joined: Vec<TypeId> = self
|
||||
.body
|
||||
.block_insts(join)
|
||||
.filter(|(_, i)| matches!(i.kind, InstKind::Phi { .. }))
|
||||
.map(|(_, i)| i.ty)
|
||||
.collect();
|
||||
content.unmeasured |= joined.len() > 2
|
||||
|| joined
|
||||
.iter()
|
||||
.any(|&t| matches!(self.types.get(t), Some(Type::Ptr { .. })));
|
||||
// A store in the arms: speculated only as one arm's single store repeating the branch's
|
||||
// block's last store to its pointer.
|
||||
let stores: Vec<(InstId, BlockId)> = arms
|
||||
.iter()
|
||||
.flat_map(|a| a.blocks.iter().copied())
|
||||
.flat_map(|b| {
|
||||
self.body
|
||||
.block_insts(b)
|
||||
.filter(|(_, i)| matches!(i.kind, InstKind::Store { .. }))
|
||||
.map(move |(id, _)| (id, b))
|
||||
})
|
||||
.collect();
|
||||
match (&arms[..], &stores[..]) {
|
||||
(_, []) => {}
|
||||
([a], [(s, b)]) if a.blocks.len() == 1 && *b == a.first => {
|
||||
match self.repeated(head, *s) {
|
||||
// Not counted, and no blocker. The branch's block's store moves to where the
|
||||
// arms join: a read after it in that block would read past it (unmeasured).
|
||||
Some(h) => {
|
||||
sunk = Some((h, *s));
|
||||
content.blocker = self.blocked_but(a.first, *s);
|
||||
content.cost = content.cost.saturating_sub(1);
|
||||
content.unmeasured |= self.read_after(head, h);
|
||||
}
|
||||
None => content.blocker = true,
|
||||
}
|
||||
}
|
||||
_ => content.blocker = true,
|
||||
}
|
||||
let decision = decide(&arms, content);
|
||||
Ok(Some(Fold {
|
||||
head,
|
||||
cond: c,
|
||||
arms,
|
||||
join,
|
||||
sunk,
|
||||
content,
|
||||
decision,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether block `b` holds a blocker other than its store `store`.
|
||||
fn blocked_but(&self, b: BlockId, store: InstId) -> bool {
|
||||
self.body
|
||||
.block_insts(b)
|
||||
.filter(|&(id, i)| id != store && !i.kind.is_terminator())
|
||||
.any(|(_, i)| self.class(&i.kind).blocker)
|
||||
}
|
||||
|
||||
/// Whether an instruction of block `head` after `store` but its terminator reads memory.
|
||||
fn read_after(&self, head: BlockId, store: InstId) -> bool {
|
||||
self.body
|
||||
.block_insts(head)
|
||||
.skip_while(|&(id, _)| id != store)
|
||||
.skip(1)
|
||||
.filter(|(_, i)| !i.kind.is_terminator())
|
||||
.any(|(_, i)| match &i.kind {
|
||||
InstKind::Load { .. } => true,
|
||||
InstKind::Call(_) => self.class(&i.kind).unmeasured || self.class(&i.kind).blocker,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The store of block `head` that arm store `store` repeats: the last instruction before the
|
||||
/// branch that writes memory, within [`LOOKBACK`], a plain store of the same type to the same
|
||||
/// pointer.
|
||||
fn repeated(&self, head: BlockId, store: InstId) -> Option<InstId> {
|
||||
let InstKind::Store {
|
||||
val,
|
||||
ptr,
|
||||
volatile: false,
|
||||
atomic: None,
|
||||
..
|
||||
} = self.body.insts.get(store)?.kind
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let ty = self.value_ty(val);
|
||||
let insts: Vec<(InstId, &InstKind)> = self
|
||||
.body
|
||||
.block_insts(head)
|
||||
.map(|(id, i)| (id, &i.kind))
|
||||
.collect();
|
||||
for &(id, kind) in insts.iter().rev().take(LOOKBACK) {
|
||||
match kind {
|
||||
InstKind::Store {
|
||||
val: v,
|
||||
ptr: p,
|
||||
volatile: false,
|
||||
atomic: None,
|
||||
..
|
||||
} => return (*p == ptr && self.value_ty(*v) == ty).then_some(id),
|
||||
k if writes(k) => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of value `v` of `body`, of the entry of parameter types `param_tys`.
|
||||
fn value_ty(body: &Body, consts: &ConstTable, param_tys: &[TypeId], v: Value) -> Option<TypeId> {
|
||||
match v {
|
||||
Value::Inst(i) => body.insts.get(i).map(|n| n.ty),
|
||||
Value::Arg(n) => param_tys.get(n.index()).copied(),
|
||||
Value::Const(k) => consts.ty(k),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `kind` may write memory.
|
||||
fn writes(kind: &InstKind) -> bool {
|
||||
match kind {
|
||||
InstKind::Store { .. }
|
||||
| InstKind::AtomicRmw { .. }
|
||||
| InstKind::CmpXchg { .. }
|
||||
| InstKind::Fence(_) => true,
|
||||
InstKind::Call(c) => match &c.callee {
|
||||
Callee::Air { op, .. } => match op {
|
||||
AirIntrinsic::Math(_) | AirIntrinsic::Convert(_) | AirIntrinsic::Group(_) => false,
|
||||
AirIntrinsic::Texture(t) => !matches!(
|
||||
t.op,
|
||||
TexOp::Read
|
||||
| TexOp::Sample { .. }
|
||||
| TexOp::SampleGrad { .. }
|
||||
| TexOp::Gather { .. }
|
||||
),
|
||||
_ => true,
|
||||
},
|
||||
_ => true,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Metal's backend speculates an arm holding group operation `op` of `scope` (the
|
||||
/// module docs).
|
||||
fn speculated(scope: GroupScope, op: GroupOp) -> bool {
|
||||
use GroupOp as G;
|
||||
match op {
|
||||
G::Shuffle
|
||||
| G::ShuffleUp
|
||||
| G::ShuffleDown
|
||||
| G::ShuffleXor
|
||||
| G::ShuffleRotateDown
|
||||
| G::ShuffleRotateUp
|
||||
| G::ShuffleAndFillUp
|
||||
| G::ShuffleAndFillDown
|
||||
| G::IsFirst => true,
|
||||
G::Broadcast | G::BroadcastFirst | G::All | G::Any | G::Ballot | G::ActiveThreadsMask => {
|
||||
scope == GroupScope::Quad
|
||||
}
|
||||
G::Sum
|
||||
| G::Min
|
||||
| G::Max
|
||||
| G::And
|
||||
| G::Or
|
||||
| G::Xor
|
||||
| G::Product
|
||||
| G::PrefixExclusiveSum
|
||||
| G::PrefixInclusiveSum
|
||||
| G::PrefixExclusiveProduct
|
||||
| G::PrefixInclusiveProduct => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What Metal does with arms `arms` of content `content` (the module docs).
|
||||
fn decide(arms: &[Arm], content: Content) -> Decision {
|
||||
let inner = arms.iter().flat_map(|a| a.inner.iter());
|
||||
let mut unknown = false;
|
||||
for i in inner {
|
||||
match i.decision {
|
||||
Decision::Speculated => {}
|
||||
Decision::Kept => return Decision::Kept,
|
||||
Decision::Unknown => unknown = true,
|
||||
}
|
||||
}
|
||||
if content.blocker {
|
||||
return Decision::Kept;
|
||||
}
|
||||
if unknown || content.unmeasured {
|
||||
return Decision::Unknown;
|
||||
}
|
||||
let within = |n: usize| n <= BUDGET;
|
||||
// Within the budget, an arm of a kind it was not measured with is known speculated only up to
|
||||
// `OFF_EDGE`.
|
||||
let measured = match !content.off_edge || content.cost <= OFF_EDGE {
|
||||
true => Decision::Speculated,
|
||||
false => Decision::Unknown,
|
||||
};
|
||||
match arms {
|
||||
[_] => match within(content.cost) {
|
||||
true => measured,
|
||||
false => Decision::Kept,
|
||||
},
|
||||
[a, b] => {
|
||||
let (t, f) = match a.on_true {
|
||||
true => (a.content, b.content),
|
||||
false => (b.content, a.content),
|
||||
};
|
||||
let small = |c: Content| c.cost <= SMALL;
|
||||
if within(content.cost) || (small(t) && !t.calls && within(f.cost)) {
|
||||
measured
|
||||
} else if (small(f) && !f.calls && within(t.cost))
|
||||
|| (small(t) && t.calls && within(f.cost))
|
||||
{
|
||||
Decision::Unknown
|
||||
} else {
|
||||
Decision::Kept
|
||||
}
|
||||
}
|
||||
_ => Decision::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// Record in `edit` the speculation of `fold` and of the branches nested in its arms.
|
||||
fn flatten(
|
||||
body: &Body,
|
||||
fold: &Fold,
|
||||
edit: &mut BodyEdit,
|
||||
value_ty: &dyn Fn(Value) -> Option<TypeId>,
|
||||
) {
|
||||
let c = fold.cond;
|
||||
let term = |b: BlockId| body.blocks.get(b).and_then(|k| k.last());
|
||||
let Some(head_term) = term(fold.head) else {
|
||||
return;
|
||||
};
|
||||
match &fold.arms[..] {
|
||||
[a] => {
|
||||
edit.rewrite.insert(
|
||||
head_term,
|
||||
InstKind::Br {
|
||||
dest: a.first,
|
||||
hints: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
[a, b] => {
|
||||
edit.rewrite.insert(
|
||||
head_term,
|
||||
InstKind::Br {
|
||||
dest: a.first,
|
||||
hints: None,
|
||||
},
|
||||
);
|
||||
if let Some(last) = term(a.last) {
|
||||
edit.rewrite.insert(
|
||||
last,
|
||||
InstKind::Br {
|
||||
dest: b.first,
|
||||
hints: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
// Each value the arms join with: the true edge's value where the condition holds.
|
||||
for (id, i) in body.block_insts(fold.join) {
|
||||
let InstKind::Phi { incoming, fmf } = &i.kind else {
|
||||
continue;
|
||||
};
|
||||
let from = |b: BlockId| incoming.iter().find(|&&(_, p)| p == b).map(|&(v, _)| v);
|
||||
let (on_true, on_false) = match &fold.arms[..] {
|
||||
[a] => match a.on_true {
|
||||
true => (from(a.last), from(fold.head)),
|
||||
false => (from(fold.head), from(a.last)),
|
||||
},
|
||||
[a, b] => match a.on_true {
|
||||
true => (from(a.last), from(b.last)),
|
||||
false => (from(b.last), from(a.last)),
|
||||
},
|
||||
_ => (None, None),
|
||||
};
|
||||
if let (Some(t), Some(f)) = (on_true, on_false) {
|
||||
edit.rewrite
|
||||
.insert(id, InstKind::Select { c, t, f, fmf: *fmf });
|
||||
}
|
||||
}
|
||||
// A sunk store: the arm's store becomes the chosen value, which the branch's block's store,
|
||||
// moved to where the arms join, stores.
|
||||
if let (Some((h, s)), [a]) = (fold.sunk, &fold.arms[..]) {
|
||||
if let (
|
||||
Some(InstKind::Store {
|
||||
val: v0,
|
||||
ptr,
|
||||
align,
|
||||
..
|
||||
}),
|
||||
Some(InstKind::Store { val: v1, .. }),
|
||||
) = (
|
||||
body.insts.get(h).map(|i| &i.kind),
|
||||
body.insts.get(s).map(|i| &i.kind),
|
||||
) {
|
||||
let (t, f) = match a.on_true {
|
||||
true => (*v1, *v0),
|
||||
false => (*v0, *v1),
|
||||
};
|
||||
if let Some(ty) = value_ty(*v0) {
|
||||
edit.rewrite.insert(
|
||||
s,
|
||||
InstKind::Select {
|
||||
c,
|
||||
t,
|
||||
f,
|
||||
fmf: FastMath::NONE,
|
||||
},
|
||||
);
|
||||
edit.retype.insert(s, ty);
|
||||
edit.rewrite.insert(
|
||||
h,
|
||||
InstKind::Store {
|
||||
val: Value::Inst(s),
|
||||
ptr: *ptr,
|
||||
align: *align,
|
||||
volatile: false,
|
||||
atomic: None,
|
||||
},
|
||||
);
|
||||
edit.moved.insert(h, fold.join);
|
||||
}
|
||||
}
|
||||
}
|
||||
for a in &fold.arms {
|
||||
for inner in &a.inner {
|
||||
flatten(body, inner, edit, value_ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The branches of `cx`'s body as Metal's backend folds them, by the block ending in each.
|
||||
fn folds(cx: &Cx<'_>, m: &mut Meter) -> Result<BTreeMap<BlockId, Fold>, Error> {
|
||||
let mut out = BTreeMap::new();
|
||||
for (b, _) in cx.body.blocks.iter() {
|
||||
m.tick(1)?;
|
||||
if let Some(fold) = cx.fold(b, 0, m)? {
|
||||
out.insert(b, fold);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What Metal's backend does with each branch of `body` whose arms rejoin, by the block ending
|
||||
/// in it.
|
||||
#[cfg(test)]
|
||||
pub(super) fn decisions(
|
||||
body: &Body,
|
||||
(types, consts): (&TypeTable, &ConstTable),
|
||||
(param_tys, params): (&[TypeId], &[Param]),
|
||||
m: &mut Meter,
|
||||
) -> Result<BTreeMap<BlockId, Decision>, Error> {
|
||||
let found = analysed(body, (types, consts), (param_tys, params), m)?;
|
||||
Ok(found.into_iter().map(|(b, f)| (b, f.decision)).collect())
|
||||
}
|
||||
|
||||
/// The branches of `body` as Metal's backend folds them ([`folds`]), its CFG built and returned.
|
||||
fn analysed(
|
||||
body: &Body,
|
||||
(types, consts): (&TypeTable, &ConstTable),
|
||||
(param_tys, params): (&[TypeId], &[Param]),
|
||||
m: &mut Meter,
|
||||
) -> Result<BTreeMap<BlockId, Fold>, Error> {
|
||||
let cfg = Cfg::build(body, m)?;
|
||||
let found = {
|
||||
let cx = Cx {
|
||||
body,
|
||||
cfg: &cfg,
|
||||
types,
|
||||
consts,
|
||||
param_tys,
|
||||
params,
|
||||
};
|
||||
folds(&cx, m)
|
||||
};
|
||||
m.release(cfg.ledger_bytes());
|
||||
found
|
||||
}
|
||||
|
||||
/// Speculate each outermost branch of `body` that Metal's backend speculates and whose arms hold
|
||||
/// a group operation that answers over the branch's block's lanes there (the module docs), in the
|
||||
/// entry of parameter types `param_tys` and parameters `params`.
|
||||
pub(super) fn expand(
|
||||
body: Body,
|
||||
(types, consts): (&TypeTable, &ConstTable),
|
||||
(param_tys, params): (&[TypeId], &[Param]),
|
||||
m: &mut Meter,
|
||||
) -> Result<Body, Error> {
|
||||
let found = analysed(&body, (types, consts), (param_tys, params), m)?;
|
||||
let speculated: Vec<&Fold> = found
|
||||
.values()
|
||||
.filter(|f| f.decision == Decision::Speculated && f.content.group)
|
||||
.collect();
|
||||
// The outermost: no other speculated branch's arms hold its block.
|
||||
let outermost: Vec<&Fold> = speculated
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|f| {
|
||||
!speculated
|
||||
.iter()
|
||||
.any(|o| o.head != f.head && o.arms.iter().any(|a| a.blocks.contains(&f.head)))
|
||||
})
|
||||
.collect();
|
||||
if outermost.is_empty() {
|
||||
return Ok(body);
|
||||
}
|
||||
let value_ty = |v: Value| value_ty(&body, consts, param_tys, v);
|
||||
let next = scoped(m, |m, held| {
|
||||
let mut edit = BodyEdit::keep_all(&body, m, held)?;
|
||||
for f in &outermost {
|
||||
flatten(&body, f, &mut edit, &value_ty);
|
||||
}
|
||||
apply(&body, &edit, &|c| c, m)
|
||||
})?;
|
||||
body.release(m);
|
||||
Ok(next)
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
//! The branches Metal's backend speculates, over bodies built with the typed test builder: the
|
||||
//! shapes measured on the M3 Max (macOS 27.0.1), and what `expand` makes of them.
|
||||
|
||||
use super::speculate::{decisions, expand, Decision};
|
||||
use crate::budget::{Budget, Meter};
|
||||
use crate::graph::{Cfg, DomTree};
|
||||
use crate::intrinsics::AirIntrinsic;
|
||||
use crate::ir::build::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::ir::{
|
||||
AddrSpace, BinOp, BlockId, Body, Call, Callee, ConstTable, FastMath, InstId, InstKind,
|
||||
IntPredicate, Param, TailKind, Type, TypeId, TypeTable, Value,
|
||||
};
|
||||
|
||||
fn meter() -> Meter {
|
||||
Meter::new(&Budget::default())
|
||||
}
|
||||
|
||||
/// The types a body uses.
|
||||
struct Types {
|
||||
void: TypeId,
|
||||
i1: TypeId,
|
||||
i32t: TypeId,
|
||||
}
|
||||
|
||||
/// A body of `fn(i32 t, ptr addrspace(1) out)` that `build` writes, with its type table and
|
||||
/// parameter types.
|
||||
struct Built {
|
||||
body: Body,
|
||||
types: TypeTable,
|
||||
consts: ConstTable,
|
||||
param_tys: Vec<TypeId>,
|
||||
}
|
||||
|
||||
impl Built {
|
||||
fn decisions(&self) -> Vec<Decision> {
|
||||
let mut m = meter();
|
||||
let params = vec![Param::default(); self.param_tys.len()];
|
||||
decisions(
|
||||
&self.body,
|
||||
(&self.types, &self.consts),
|
||||
(&self.param_tys, ¶ms),
|
||||
&mut m,
|
||||
)
|
||||
.unwrap()
|
||||
.into_values()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn expanded(self) -> Body {
|
||||
let mut m = meter();
|
||||
let params = vec![Param::default(); self.param_tys.len()];
|
||||
expand(
|
||||
self.body,
|
||||
(&self.types, &self.consts),
|
||||
(&self.param_tys, ¶ms),
|
||||
&mut m,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn built(build: impl FnOnce(&mut FunctionBuilder<'_>, &Types)) -> Built {
|
||||
let mut m = ModuleBuilder::new();
|
||||
let types = Types {
|
||||
void: m.void(),
|
||||
i1: m.int(1),
|
||||
i32t: m.int(32),
|
||||
};
|
||||
let dev = m.ptr(AddrSpace::Device);
|
||||
let fty = m.fn_ty(types.void, &[types.i32t, dev]);
|
||||
let mut f = m.define("f", fty);
|
||||
build(&mut f, &types);
|
||||
let id = f.finish();
|
||||
let parts = m.finish_parts().expect("body");
|
||||
let body = parts
|
||||
.funcs
|
||||
.get(id)
|
||||
.and_then(|func| func.body.clone())
|
||||
.expect("a defined body");
|
||||
let fty = parts.funcs.get(id).map(|f| f.ty).expect("the function");
|
||||
let Some(Type::Function { params, .. }) = parts.types.get(fty) else {
|
||||
panic!("a function type");
|
||||
};
|
||||
let param_tys = params.to_vec();
|
||||
Built {
|
||||
body,
|
||||
types: parts.types,
|
||||
consts: parts.consts,
|
||||
param_tys,
|
||||
}
|
||||
}
|
||||
|
||||
/// A call of the `air.*` intrinsic `name` of type `ret(params)`.
|
||||
fn air_call(
|
||||
f: &mut FunctionBuilder<'_>,
|
||||
name: &str,
|
||||
ret: TypeId,
|
||||
params: &[TypeId],
|
||||
args: &[Value],
|
||||
) -> Value {
|
||||
let ty = f.module().fn_ty(ret, params);
|
||||
let decl = f.module().declare(name, ty);
|
||||
let op = AirIntrinsic::parse(name).unwrap_or_else(|| panic!("{name}"));
|
||||
f.push(
|
||||
ret,
|
||||
InstKind::Call(Box::new(Call {
|
||||
callee: Callee::Air { decl, op },
|
||||
args: args.into(),
|
||||
fmf: FastMath::NONE,
|
||||
tail: TailKind::None,
|
||||
attrs: None,
|
||||
range: None,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
fn first(f: &mut FunctionBuilder<'_>, t: &Types, x: Value) -> Value {
|
||||
air_call(f, "air.quad_broadcast_first.u.i32", t.i32t, &[t.i32t], &[x])
|
||||
}
|
||||
|
||||
fn quad_sum(f: &mut FunctionBuilder<'_>, t: &Types, x: Value) -> Value {
|
||||
air_call(f, "air.quad_sum.u.i32", t.i32t, &[t.i32t], &[x])
|
||||
}
|
||||
|
||||
/// `t % 3 == 0`.
|
||||
fn skips(f: &mut FunctionBuilder<'_>, t: &Types) -> Value {
|
||||
let three = f.module().const_int(t.i32t, 3);
|
||||
let zero = f.module().const_int(t.i32t, 0);
|
||||
let r = f.bin(BinOp::URem, f.arg(0), three);
|
||||
f.push(
|
||||
t.i1,
|
||||
InstKind::ICmp {
|
||||
pred: IntPredicate::Eq,
|
||||
a: r,
|
||||
b: zero,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// `10 t + 1` then `n` more instructions (alternately `^ t` and `+ t`): `n + 2` in all.
|
||||
fn chain(f: &mut FunctionBuilder<'_>, t: &Types, n: usize) -> Value {
|
||||
let ten = f.module().const_int(t.i32t, 10);
|
||||
let one = f.module().const_int(t.i32t, 1);
|
||||
let x = f.bin(BinOp::Mul, f.arg(0), ten);
|
||||
let mut x = f.bin(BinOp::Or, x, one);
|
||||
for k in 0..n {
|
||||
let op = match k % 2 {
|
||||
0 => BinOp::Xor,
|
||||
_ => BinOp::Add,
|
||||
};
|
||||
x = f.bin(op, x, f.arg(0));
|
||||
}
|
||||
x
|
||||
}
|
||||
|
||||
fn phi(f: &mut FunctionBuilder<'_>, t: &Types, incoming: &[(Value, BlockId)]) -> Value {
|
||||
f.push(
|
||||
t.i32t,
|
||||
InstKind::Phi {
|
||||
incoming: incoming.into(),
|
||||
fmf: FastMath::NONE,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// `out[t] = v`.
|
||||
fn store_out(f: &mut FunctionBuilder<'_>, t: &Types, v: Value) {
|
||||
let p = gep_out(f, t);
|
||||
f.push_void(InstKind::Store {
|
||||
val: v,
|
||||
ptr: p,
|
||||
align: None,
|
||||
volatile: false,
|
||||
atomic: None,
|
||||
});
|
||||
}
|
||||
|
||||
fn gep_out(f: &mut FunctionBuilder<'_>, t: &Types) -> Value {
|
||||
let dev = f.module().ptr(AddrSpace::Device);
|
||||
f.push(
|
||||
dev,
|
||||
InstKind::Gep {
|
||||
src_ty: t.i32t,
|
||||
base: f.arg(1),
|
||||
indices: Box::new([f.arg(0)]),
|
||||
inbounds: true,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// `r = 7777; if (t % 3 != 0) r = arm(); out[t] = r;`, the arm a block of its own.
|
||||
fn triangle(arm: impl FnOnce(&mut FunctionBuilder<'_>, &Types) -> Value) -> Built {
|
||||
built(|f, t| {
|
||||
let entry = BlockId::new(0);
|
||||
let a = f.block();
|
||||
let join = f.block();
|
||||
let c = skips(f, t);
|
||||
f.cond_br(c, join, a);
|
||||
f.switch_to(a);
|
||||
let v = arm(f, t);
|
||||
f.br(join);
|
||||
f.switch_to(join);
|
||||
let k = f.module().const_int(t.i32t, 7777);
|
||||
let r = phi(f, t, &[(v, a), (k, entry)]);
|
||||
store_out(f, t, r);
|
||||
f.ret(None);
|
||||
})
|
||||
}
|
||||
|
||||
/// `if (t % 3 != 0) r = arm_false(); else r = arm_true(); out[t] = r;`
|
||||
fn diamond(
|
||||
on_true: impl FnOnce(&mut FunctionBuilder<'_>, &Types) -> Value,
|
||||
on_false: impl FnOnce(&mut FunctionBuilder<'_>, &Types) -> Value,
|
||||
) -> Built {
|
||||
built(|f, t| {
|
||||
let a = f.block();
|
||||
let b = f.block();
|
||||
let join = f.block();
|
||||
let c = skips(f, t);
|
||||
f.cond_br(c, a, b);
|
||||
f.switch_to(a);
|
||||
let va = on_true(f, t);
|
||||
f.br(join);
|
||||
f.switch_to(b);
|
||||
let vb = on_false(f, t);
|
||||
f.br(join);
|
||||
f.switch_to(join);
|
||||
let r = phi(f, t, &[(va, a), (vb, b)]);
|
||||
store_out(f, t, r);
|
||||
f.ret(None);
|
||||
})
|
||||
}
|
||||
|
||||
/// The kinds of `body`'s terminators that branch on a condition.
|
||||
fn conditional_branches(body: &Body) -> usize {
|
||||
body.blocks
|
||||
.iter()
|
||||
.filter(|&(b, _)| {
|
||||
matches!(
|
||||
body.terminator(b).map(|i| &i.kind),
|
||||
Some(InstKind::CondBr { .. })
|
||||
)
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// The number of `body`'s PHIs and selects.
|
||||
fn phis_and_selects(body: &Body) -> (usize, usize) {
|
||||
let mut out = (0, 0);
|
||||
for (_, i) in body.insts.iter() {
|
||||
match i.kind {
|
||||
InstKind::Phi { .. } => out.0 += 1,
|
||||
InstKind::Select { .. } => out.1 += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every operand is defined where its use runs: in a block that dominates the use's (a PHI's
|
||||
/// entry: its incoming block), earlier in the same block.
|
||||
fn assert_defined_at_uses(body: &Body) {
|
||||
let mut m = meter();
|
||||
let cfg = Cfg::build(body, &mut m).unwrap();
|
||||
let dom = DomTree::compute(&cfg, &mut m).unwrap();
|
||||
let block_of = |id: InstId| {
|
||||
body.blocks
|
||||
.iter()
|
||||
.find(|(b, _)| body.block_insts(*b).any(|(i, _)| i == id))
|
||||
.map(|(b, _)| b)
|
||||
.expect("an instruction in a block")
|
||||
};
|
||||
for (b, _) in body.blocks.iter() {
|
||||
for (id, inst) in body.block_insts(b) {
|
||||
let check = |v: Value, at: BlockId, same_block: bool| {
|
||||
if let Value::Inst(d) = v {
|
||||
let db = block_of(d);
|
||||
assert!(dom.dominates(db, at), "{d:?} does not dominate {id:?}");
|
||||
if same_block && db == at {
|
||||
assert!(d.raw() < id.raw(), "{d:?} follows its use {id:?}");
|
||||
}
|
||||
}
|
||||
};
|
||||
match &inst.kind {
|
||||
InstKind::Phi { incoming, .. } => {
|
||||
for &(v, from) in incoming {
|
||||
check(v, from, false);
|
||||
}
|
||||
}
|
||||
kind => kind.for_each_value(|v| check(v, b, true)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The authored kernel's shape: `quad_broadcast_first` of `10 t + 1` in an arm that joins
|
||||
/// through a PHI. Metal runs the arm in every lane of the branch's block: the branch becomes a
|
||||
/// jump into the arm, and the PHI a select on the condition, the arm's value where it is false.
|
||||
#[test]
|
||||
fn a_quad_broadcast_first_in_a_short_arm_runs_in_every_lane_of_the_branch() {
|
||||
let b = triangle(|f, t| {
|
||||
let x = chain(f, t, 0);
|
||||
first(f, t, x)
|
||||
});
|
||||
assert_eq!(b.decisions(), [Decision::Speculated]);
|
||||
let body = b.expanded();
|
||||
assert_eq!(conditional_branches(&body), 0);
|
||||
assert_eq!(phis_and_selects(&body), (0, 1));
|
||||
let select = body
|
||||
.insts
|
||||
.iter()
|
||||
.find_map(|(_, i)| match i.kind {
|
||||
InstKind::Select { t, f, .. } => Some((t, f)),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a select");
|
||||
assert!(matches!(select.0, Value::Const(_)), "{select:?}");
|
||||
assert!(matches!(select.1, Value::Inst(_)), "{select:?}");
|
||||
assert_defined_at_uses(&body);
|
||||
}
|
||||
|
||||
/// A quad reduction keeps its arm (and the arm's other operations keep its lanes too): the body
|
||||
/// is left as it is.
|
||||
#[test]
|
||||
fn a_quad_reduction_keeps_its_arm() {
|
||||
let b = triangle(|f, t| {
|
||||
let x = chain(f, t, 0);
|
||||
let y = first(f, t, x);
|
||||
let s = quad_sum(f, t, x);
|
||||
f.bin(BinOp::Add, y, s)
|
||||
});
|
||||
assert_eq!(b.decisions(), [Decision::Kept]);
|
||||
let body = b.expanded();
|
||||
assert_eq!(conditional_branches(&body), 1);
|
||||
assert_eq!(phis_and_selects(&body), (1, 0));
|
||||
}
|
||||
|
||||
/// A device read keeps its arm.
|
||||
#[test]
|
||||
fn a_device_read_keeps_its_arm() {
|
||||
let b = triangle(|f, t| {
|
||||
let p = gep_out(f, t);
|
||||
let x = f.push(
|
||||
t.i32t,
|
||||
InstKind::Load {
|
||||
ptr: p,
|
||||
align: None,
|
||||
volatile: false,
|
||||
atomic: None,
|
||||
range: None,
|
||||
},
|
||||
);
|
||||
first(f, t, x)
|
||||
});
|
||||
assert_eq!(b.decisions(), [Decision::Kept]);
|
||||
assert_eq!(conditional_branches(&b.expanded()), 1);
|
||||
}
|
||||
|
||||
/// One arm: up to 25 instructions speculated, 26 not.
|
||||
#[test]
|
||||
fn one_arm_speculates_up_to_twenty_five_instructions() {
|
||||
for (n, decision) in [(25, Decision::Speculated), (26, Decision::Kept)] {
|
||||
// `chain` makes `k + 2`, and the call one more.
|
||||
let b = triangle(|f, t| {
|
||||
let x = chain(f, t, n - 3);
|
||||
first(f, t, x)
|
||||
});
|
||||
assert_eq!(b.decisions(), [decision], "{n}");
|
||||
let branches = b.expanded();
|
||||
assert_eq!(
|
||||
conditional_branches(&branches),
|
||||
usize::from(decision == Decision::Kept),
|
||||
"{n}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// An arm holding a kind the budget was not measured with (here a quad vote and a select of a
|
||||
/// constant) is speculated up to 21 instructions, as the M3 Max speculates such an arm of 21 (a
|
||||
/// divergent arm of quad votes, 16-bit masks and casts); from 22 to 25 it is unknown and left (the
|
||||
/// M3 Max keeps such an arm of 25, `a3_quad_votes_divergent`'s), and past 25 it is kept. An arm of
|
||||
/// the budget's own kinds is speculated up to 25.
|
||||
#[test]
|
||||
fn an_arm_of_other_kinds_is_known_speculated_up_to_twenty_one() {
|
||||
// `chain` makes `k + 2`; the comparison, the vote and the select three more.
|
||||
let voting = |n: usize| {
|
||||
triangle(move |f, t| {
|
||||
let x = chain(f, t, n - 5);
|
||||
let nine = f.module().const_int(t.i32t, 9);
|
||||
let c = f.push(
|
||||
t.i1,
|
||||
InstKind::ICmp {
|
||||
pred: IntPredicate::Ne,
|
||||
a: x,
|
||||
b: nine,
|
||||
},
|
||||
);
|
||||
let v = air_call(f, "air.quad_all", t.i1, &[t.i1], &[c]);
|
||||
let seven = f.module().const_int(t.i32t, 7);
|
||||
f.push(
|
||||
t.i32t,
|
||||
InstKind::Select {
|
||||
c: v,
|
||||
t: x,
|
||||
f: seven,
|
||||
fmf: FastMath::NONE,
|
||||
},
|
||||
)
|
||||
})
|
||||
};
|
||||
for (n, decision) in [
|
||||
(21, Decision::Speculated),
|
||||
(22, Decision::Unknown),
|
||||
(25, Decision::Unknown),
|
||||
(26, Decision::Kept),
|
||||
] {
|
||||
let b = voting(n);
|
||||
assert_eq!(b.decisions(), [decision], "{n}");
|
||||
assert_eq!(
|
||||
conditional_branches(&b.expanded()),
|
||||
usize::from(decision != Decision::Speculated),
|
||||
"{n}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two arms: up to 25 together; beside an arm on the condition's true edge of at most 3
|
||||
/// instructions and no call, up to 25 in the other; an arm of at most 3 with a call on the false
|
||||
/// edge is not exempt; the two shapes no probe covers are unknown and left.
|
||||
#[test]
|
||||
fn two_arms_count_together_but_a_small_true_arm() {
|
||||
let plain = |n: usize| {
|
||||
move |f: &mut FunctionBuilder<'_>, t: &Types| {
|
||||
let seven = f.module().const_int(t.i32t, 7000);
|
||||
let mut y = f.bin(BinOp::Add, f.arg(0), seven);
|
||||
for k in 1..n {
|
||||
let op = match k % 2 {
|
||||
0 => BinOp::Add,
|
||||
_ => BinOp::Xor,
|
||||
};
|
||||
y = f.bin(op, y, f.arg(0));
|
||||
}
|
||||
y
|
||||
}
|
||||
};
|
||||
let op = |n: usize| {
|
||||
move |f: &mut FunctionBuilder<'_>, t: &Types| {
|
||||
let x = chain(f, t, n - 3);
|
||||
first(f, t, x)
|
||||
}
|
||||
};
|
||||
let only = |n: usize| {
|
||||
move |f: &mut FunctionBuilder<'_>, t: &Types| {
|
||||
let _ = n;
|
||||
first(f, t, f.arg(0))
|
||||
}
|
||||
};
|
||||
// (the true edge's arm, the false edge's arm): measured.
|
||||
assert_eq!(
|
||||
diamond(plain(10), op(13)).decisions(),
|
||||
[Decision::Speculated]
|
||||
);
|
||||
assert_eq!(
|
||||
diamond(plain(16), op(9)).decisions(),
|
||||
[Decision::Speculated]
|
||||
);
|
||||
assert_eq!(diamond(plain(13), op(13)).decisions(), [Decision::Kept]);
|
||||
assert_eq!(diamond(plain(4), op(22)).decisions(), [Decision::Kept]);
|
||||
assert_eq!(
|
||||
diamond(plain(3), op(25)).decisions(),
|
||||
[Decision::Speculated]
|
||||
);
|
||||
assert_eq!(
|
||||
diamond(plain(1), op(25)).decisions(),
|
||||
[Decision::Speculated]
|
||||
);
|
||||
assert_eq!(diamond(plain(3), op(26)).decisions(), [Decision::Kept]);
|
||||
assert_eq!(diamond(plain(25), only(1)).decisions(), [Decision::Kept]);
|
||||
assert_eq!(
|
||||
diamond(plain(24), only(1)).decisions(),
|
||||
[Decision::Speculated]
|
||||
);
|
||||
// Unmeasured: a small arm without a call on the false edge, past 25 together.
|
||||
let unknown = diamond(op(25), plain(3));
|
||||
assert_eq!(unknown.decisions(), [Decision::Unknown]);
|
||||
assert_eq!(conditional_branches(&unknown.expanded()), 1);
|
||||
// Speculated: the arms run one after the other, the true edge's first.
|
||||
let body = diamond(plain(3), op(25)).expanded();
|
||||
assert_eq!(conditional_branches(&body), 0);
|
||||
assert_eq!(phis_and_selects(&body), (0, 1));
|
||||
assert_defined_at_uses(&body);
|
||||
}
|
||||
|
||||
/// `out[t] = 7777; if (t % 3 != 0) out[t] = quad_broadcast_first(10 t + 1);`: the arm's store
|
||||
/// repeats the branch's block's last store to its pointer. Metal speculates it: the arm's store
|
||||
/// becomes the chosen value, which the branch's block's store, moved to where the arms join,
|
||||
/// stores.
|
||||
#[test]
|
||||
fn a_store_repeating_the_branchs_store_stores_the_chosen_value() {
|
||||
let b = built(|f, t| {
|
||||
let a = f.block();
|
||||
let join = f.block();
|
||||
let p = gep_out(f, t);
|
||||
let k = f.module().const_int(t.i32t, 7777);
|
||||
f.push_void(InstKind::Store {
|
||||
val: k,
|
||||
ptr: p,
|
||||
align: None,
|
||||
volatile: false,
|
||||
atomic: None,
|
||||
});
|
||||
let c = skips(f, t);
|
||||
f.cond_br(c, join, a);
|
||||
f.switch_to(a);
|
||||
let x = chain(f, t, 0);
|
||||
let v = first(f, t, x);
|
||||
f.push_void(InstKind::Store {
|
||||
val: v,
|
||||
ptr: p,
|
||||
align: None,
|
||||
volatile: false,
|
||||
atomic: None,
|
||||
});
|
||||
f.br(join);
|
||||
f.switch_to(join);
|
||||
f.ret(None);
|
||||
});
|
||||
assert_eq!(b.decisions(), [Decision::Speculated]);
|
||||
let body = b.expanded();
|
||||
assert_eq!(conditional_branches(&body), 0);
|
||||
let stores: Vec<(BlockId, Value)> = body
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|(blk, _)| {
|
||||
body.block_insts(blk)
|
||||
.filter_map(move |(_, i)| match i.kind {
|
||||
InstKind::Store { val, .. } => Some((blk, val)),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(stores.len(), 1, "{stores:?}");
|
||||
let Value::Inst(chosen) = stores[0].1 else {
|
||||
panic!("{stores:?}");
|
||||
};
|
||||
let chosen = body.insts.get(chosen).expect("the chosen value");
|
||||
let InstKind::Select {
|
||||
f: Value::Inst(arm),
|
||||
..
|
||||
} = chosen.kind
|
||||
else {
|
||||
panic!("{chosen:?}");
|
||||
};
|
||||
assert_eq!(body.insts.get(arm).map(|i| i.ty), Some(chosen.ty));
|
||||
assert_defined_at_uses(&body);
|
||||
}
|
||||
|
||||
/// A store to another pointer keeps its arm.
|
||||
#[test]
|
||||
fn a_store_to_another_pointer_keeps_its_arm() {
|
||||
let b = built(|f, t| {
|
||||
let a = f.block();
|
||||
let join = f.block();
|
||||
let c = skips(f, t);
|
||||
f.cond_br(c, join, a);
|
||||
f.switch_to(a);
|
||||
let x = chain(f, t, 0);
|
||||
let v = first(f, t, x);
|
||||
store_out(f, t, v);
|
||||
f.br(join);
|
||||
f.switch_to(join);
|
||||
f.ret(None);
|
||||
});
|
||||
assert_eq!(b.decisions(), [Decision::Kept]);
|
||||
}
|
||||
|
||||
/// A short branch inside an arm folds first and counts with the arm it joins: both become jumps.
|
||||
#[test]
|
||||
fn a_short_branch_inside_an_arm_folds_with_it() {
|
||||
let b = built(|f, t| {
|
||||
let entry = BlockId::new(0);
|
||||
let outer = f.block();
|
||||
let inner = f.block();
|
||||
let rejoin = f.block();
|
||||
let join = f.block();
|
||||
let c = skips(f, t);
|
||||
f.cond_br(c, join, outer);
|
||||
f.switch_to(outer);
|
||||
let three = f.module().const_int(t.i32t, 3);
|
||||
let zero = f.module().const_int(t.i32t, 0);
|
||||
let q = f.bin(BinOp::And, f.arg(0), three);
|
||||
let d = f.push(
|
||||
t.i1,
|
||||
InstKind::ICmp {
|
||||
pred: IntPredicate::Eq,
|
||||
a: q,
|
||||
b: zero,
|
||||
},
|
||||
);
|
||||
f.cond_br(d, rejoin, inner);
|
||||
f.switch_to(inner);
|
||||
let w = f.bin(BinOp::Mul, q, q);
|
||||
f.br(rejoin);
|
||||
f.switch_to(rejoin);
|
||||
let s = phi(f, t, &[(zero, outer), (w, inner)]);
|
||||
let x = chain(f, t, 0);
|
||||
let x = f.bin(BinOp::Add, x, s);
|
||||
let v = first(f, t, x);
|
||||
f.br(join);
|
||||
f.switch_to(join);
|
||||
let k = f.module().const_int(t.i32t, 7777);
|
||||
let r = phi(f, t, &[(v, rejoin), (k, entry)]);
|
||||
store_out(f, t, r);
|
||||
f.ret(None);
|
||||
});
|
||||
let mut d = b.decisions();
|
||||
d.sort_by_key(|d| *d as u8);
|
||||
assert_eq!(d, [Decision::Speculated, Decision::Speculated]);
|
||||
let body = b.expanded();
|
||||
assert_eq!(conditional_branches(&body), 0);
|
||||
assert_eq!(phis_and_selects(&body), (0, 2));
|
||||
assert_defined_at_uses(&body);
|
||||
}
|
||||
|
||||
/// An arm without a group operation that answers differently is left as it is, speculated or
|
||||
/// not: only the operations Metal's speculation changes move.
|
||||
#[test]
|
||||
fn an_arm_without_such_an_operation_is_left() {
|
||||
let b = triangle(|f, t| chain(f, t, 3));
|
||||
assert_eq!(b.decisions(), [Decision::Speculated]);
|
||||
assert_eq!(conditional_branches(&b.expanded()), 1);
|
||||
}
|
||||
|
||||
/// An address computation in the arm: no measurement covers its count, so the arm is left.
|
||||
#[test]
|
||||
fn an_unmeasured_instruction_leaves_the_arm() {
|
||||
let b = triangle(|f, t| {
|
||||
gep_out(f, t);
|
||||
let x = chain(f, t, 0);
|
||||
first(f, t, x)
|
||||
});
|
||||
assert_eq!(b.decisions(), [Decision::Unknown]);
|
||||
assert_eq!(conditional_branches(&b.expanded()), 1);
|
||||
}
|
||||
|
||||
/// An integer division by a variable in the arm: speculated, it would divide by zero where the
|
||||
/// condition guarded it, which SPIR-V leaves undefined, so the arm is left.
|
||||
#[test]
|
||||
fn a_division_by_a_variable_leaves_the_arm() {
|
||||
let b = triangle(|f, t| {
|
||||
let x = chain(f, t, 0);
|
||||
let q = f.bin(BinOp::UDiv, x, f.arg(0));
|
||||
first(f, t, q)
|
||||
});
|
||||
assert_eq!(b.decisions(), [Decision::Unknown]);
|
||||
assert_eq!(conditional_branches(&b.expanded()), 1);
|
||||
}
|
||||
@@ -2975,8 +2975,9 @@ fn refusal(r: Result<Entry, Error>) -> Unsupported {
|
||||
|
||||
/// A surviving call is refused at its location in the inlined entry, naming its callee, as its
|
||||
/// typed feature (not implemented yet): binding an intersection function table (an undecoded
|
||||
/// `air.set_intersection_function_table.*` intrinsic, by its family), a call to link, and an
|
||||
/// indirect call; another unknown intrinsic is `UnknownIntrinsic`.
|
||||
/// `air.set_intersection_function_table.*` intrinsic, by its family), a multisample imageblock's
|
||||
/// operation (imageblocks), a call to link, and an indirect call; another unknown intrinsic is
|
||||
/// `UnknownIntrinsic`.
|
||||
#[test]
|
||||
fn surviving_calls_are_refused_by_family_naming_the_callee() {
|
||||
let at = Location::function(DiagName::new("k"), Some(0), Some(0));
|
||||
@@ -2990,6 +2991,17 @@ fn surviving_calls_are_refused_by_family_naming_the_callee() {
|
||||
Some(DiagName::new("air.set_intersection_function_table.p1i8"))
|
||||
);
|
||||
|
||||
// A multisample imageblock's operation is imageblocks, naming the operation.
|
||||
let u = refusal(specialize_call(|m, fty| {
|
||||
Callee::UnknownIntrinsic(m.declare("air.get_imageblock_num_colors", fty))
|
||||
}));
|
||||
assert_eq!(u.feature, Feature::Imageblocks);
|
||||
assert_eq!(u.location, Some(at.clone()));
|
||||
assert_eq!(
|
||||
u.symbol,
|
||||
Some(DiagName::new("air.get_imageblock_num_colors"))
|
||||
);
|
||||
|
||||
let u = refusal(specialize_call(|m, fty| {
|
||||
Callee::UnknownIntrinsic(m.declare("air.some_future_op", fty))
|
||||
}));
|
||||
|
||||
@@ -786,6 +786,10 @@ pub enum Feature {
|
||||
Tensors,
|
||||
/// An undecoded indirect-command-buffer encoding intrinsic.
|
||||
GpuEncodedIndirectCommands,
|
||||
/// A multisample imageblock's operation, which does not decode: its sample count, the colors
|
||||
/// its pixel holds or a color's coverage mask, or a store to the samples of a coverage mask.
|
||||
/// Tile functions and fragment imageblocks run on single-sample passes only.
|
||||
Imageblocks,
|
||||
/// A program-scope buffer binding of MSL 3.2 (macOS 15 and later), `constant T* constant p
|
||||
/// [[buffer(n)]];` in Apple's `!air.global_bindings` list, valid AIR this version does not
|
||||
/// implement yet.
|
||||
|
||||
@@ -2521,6 +2521,12 @@ fn known_families_decode_or_are_listed() {
|
||||
"air.convert.f.f32.f.f8e4m3",
|
||||
"air.convert.s.i32.f.f8e4m3fn",
|
||||
"air.convert.u.i8.f.f8e5m2",
|
||||
// A multisample imageblock's operations: listed, not decoded (the single-sample ones
|
||||
// above, its size and the implicit loads and stores, decode).
|
||||
"air.get_imageblock_samples",
|
||||
"air.get_imageblock_num_colors",
|
||||
"air.get_color_coverage_mask",
|
||||
"air.store.implicit_imageblock.mask.v4f16",
|
||||
];
|
||||
for name in names {
|
||||
let listed = undecoded_family(name).is_some();
|
||||
@@ -2541,9 +2547,11 @@ fn known_families_decode_or_are_listed() {
|
||||
}
|
||||
|
||||
/// The typed undecoded families are undecoded `air.*` families, classified by their ABI prefix.
|
||||
/// Binding an intersection function table is a function table (dynamic call). Decoded siblings of
|
||||
/// these families (and ray intersection, decoded, and the render commands' barriers and object and
|
||||
/// mesh setters, decoded) and other undecoded names are not classified here.
|
||||
/// Binding an intersection function table is a function table (dynamic call), and a multisample
|
||||
/// imageblock's operations are imageblocks. Decoded siblings of these families (and ray
|
||||
/// intersection, decoded, the single-sample imageblock operations, and the render commands'
|
||||
/// barriers and object and mesh setters, decoded) and other undecoded names are not classified
|
||||
/// here.
|
||||
#[test]
|
||||
fn undecoded_features_are_undecoded_prefixes() {
|
||||
for (prefix, _) in UNDECODED_FEATURES {
|
||||
@@ -2560,8 +2568,27 @@ fn undecoded_features_are_undecoded_prefixes() {
|
||||
Some(Feature::IntersectionFunctionTable),
|
||||
"{name}"
|
||||
);
|
||||
// A multisample imageblock's operations, as Apple's compiler declares them, are imageblocks.
|
||||
for name in [
|
||||
"air.get_imageblock_samples",
|
||||
"air.get_imageblock_num_colors",
|
||||
"air.get_color_coverage_mask",
|
||||
"air.store.implicit_imageblock.mask.f32",
|
||||
"air.store.implicit_imageblock.mask.v4f16",
|
||||
] {
|
||||
assert_eq!(classify_self(name), DeclClass::Unknown, "{name}");
|
||||
assert_eq!(
|
||||
undecoded_feature(name.as_bytes()),
|
||||
Some(Feature::Imageblocks),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
// Decoded members of these families are refused by lowering, not classified here.
|
||||
for name in [
|
||||
"air.get_imageblock_width",
|
||||
"air.get_imageblock_height",
|
||||
"air.load.implicit_imageblock.f32",
|
||||
"air.store.implicit_imageblock.v4f16",
|
||||
"air.intersect",
|
||||
"air.intersect.instancing.triangle_data",
|
||||
"air.get_null_intersection_function_table",
|
||||
|
||||
@@ -290,8 +290,24 @@ pub const UNDECODED: &[(&str, &str)] = &[
|
||||
("air.convert.f.f8e4m3.", FP8_NARROWING),
|
||||
("air.convert.f.f8e4m3fn.", FP8_NARROWING),
|
||||
("air.convert.f.f8e5m2.", FP8_NARROWING),
|
||||
// A multisample imageblock's operations: its sample count (`get_num_samples`), the colors its
|
||||
// pixel holds and each one's coverage mask (`get_num_colors`, `get_color_coverage_mask`), and
|
||||
// a store to the samples a coverage mask names. Typed as [`UNDECODED_FEATURES`].
|
||||
("air.get_imageblock_samples", MULTISAMPLE_IMAGEBLOCK),
|
||||
("air.get_imageblock_num_colors", MULTISAMPLE_IMAGEBLOCK),
|
||||
("air.get_color_coverage_mask", MULTISAMPLE_IMAGEBLOCK),
|
||||
(
|
||||
"air.store.implicit_imageblock.mask.",
|
||||
MULTISAMPLE_IMAGEBLOCK,
|
||||
),
|
||||
];
|
||||
|
||||
/// The reason a multisample imageblock's operations are [`UNDECODED`].
|
||||
const MULTISAMPLE_IMAGEBLOCK: &str = "a multisample imageblock's sample count, colors, coverage \
|
||||
masks and masked stores: tile functions and fragment \
|
||||
imageblocks run on single-sample passes only, and how many \
|
||||
colors Metal keeps for a pixel is not probed";
|
||||
|
||||
/// The reason the conversions to an 8-bit float are [`UNDECODED`].
|
||||
const FP8_NARROWING: &str = "Metal on M3 (AGXMetalG15X, macOS 26.7) does not compile a float \
|
||||
source (XPC interruption), and for an integer source returns bytes \
|
||||
@@ -318,6 +334,11 @@ pub const UNDECODED_FEATURES: &[(&str, Feature)] = &[
|
||||
"air.set_intersection_function_table.",
|
||||
Feature::IntersectionFunctionTable,
|
||||
),
|
||||
// A multisample imageblock's operations: imageblocks, on a single-sample pass only.
|
||||
("air.get_imageblock_samples", Feature::Imageblocks),
|
||||
("air.get_imageblock_num_colors", Feature::Imageblocks),
|
||||
("air.get_color_coverage_mask", Feature::Imageblocks),
|
||||
("air.store.implicit_imageblock.mask.", Feature::Imageblocks),
|
||||
];
|
||||
|
||||
/// The typed feature of the undecoded intrinsic `name` ([`UNDECODED_FEATURES`]), if it belongs
|
||||
|
||||
@@ -260,7 +260,7 @@ fn the_table_matches_the_source() {
|
||||
assert!(
|
||||
only_table.is_empty() && only_source.is_empty(),
|
||||
"the public surface of metal2vulkan-air changed: update air/tests/api_surface.txt (a \
|
||||
removed or changed line is a breaking change, DESIGN D337 item 2)\nin the table, not \
|
||||
removed or changed line is a breaking change)\nin the table, not \
|
||||
the source:\n {}\nin the source, not the table:\n {}",
|
||||
only_table
|
||||
.iter()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# The public surface of metal2vulkan-air (DESIGN D337 item 2), one line per item:
|
||||
# "<module> <name> <kind>", read from source by tests/api_surface.rs, which explains the kinds.
|
||||
# A removed or changed line is a breaking change, released as a minor version with metal2vulkan.
|
||||
# The public surface of metal2vulkan-air, one line per item: "<module> <name> <kind>", read from
|
||||
# source by tests/api_surface.rs, which explains the kinds. A removed or changed line is a breaking
|
||||
# change, released as a minor version with metal2vulkan.
|
||||
abi AbiHandle enum(E)
|
||||
abi AbiInt enum(E)
|
||||
abi AccelerationStructureKind enum(E)
|
||||
|
||||
@@ -157,8 +157,9 @@ the runtime made.
|
||||
- `Device::raw()` gives the entry, instance, physical device, `ash::Device` and queue family.
|
||||
`CommandQueue::with_vk_queue` lends a queue's `VkQueue` under the runtime's lock.
|
||||
- `Texture::vk_image`, `Buffer::vk_buffer` and `SharedEvent::vk_semaphore` give an object's handle.
|
||||
A texture over a buffer's bytes that aliases them gives a linear image, which over a no-copy
|
||||
buffer's or dma-buf host pages may be of `VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT`
|
||||
A texture over a buffer's bytes that aliases them gives a linear image (the same one for textures
|
||||
of one image over the same bytes of one import of host pages, which share it), which over a
|
||||
no-copy buffer's or dma-buf host pages may be of `VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT`
|
||||
(`DRM_FORMAT_MOD_LINEAR`, its one memory plane at the texture's `bytes_per_row`): ask its layout
|
||||
of memory plane 0.
|
||||
- `CommandBuffer::encode_wait_for_vk_semaphore` and `encode_signal_vk_semaphore` order a command
|
||||
@@ -185,9 +186,15 @@ the runtime made.
|
||||
memory, given as a `HostMemory`, through `VK_EXT_external_memory_host`; memory the device cannot
|
||||
import exactly is refused. `unsafe Device::new_heap_with_bytes_no_copy` is its heap twin.
|
||||
`Buffer::rebind_bytes_no_copy` and `Heap::rebind_bytes_no_copy` move either to another range,
|
||||
keeping the objects, addresses and IDs. Where a driver refuses the pointer (RADV refuses shared
|
||||
mappings, a `memfd`'s among them), memory made with `HostMemory::with_dma_buf` is imported from
|
||||
dma-bufs of its pages instead ([HOWTO](../../docs/HOWTO.md#6-host-memory-a-driver-refuses)).
|
||||
keeping the objects, addresses and IDs. A rebind is refused (`RebindProblem::EncodedUses`) while
|
||||
a command buffer not yet committed, or an open encoder, used the bytes; a render encoder whose
|
||||
attachment lies in them uses them from its open. Where a driver refuses the pointer (RADV
|
||||
refuses shared mappings, a `memfd`'s among them), memory made with `HostMemory::with_dma_buf` is
|
||||
imported from dma-bufs of its pages instead
|
||||
([HOWTO](../../docs/HOWTO.md#6-host-memory-a-driver-refuses)). A no-copy buffer's import of such
|
||||
dma-bufs that only blits have read may be released while idle and imported again at its next
|
||||
blit, which then costs time: RADV lists every import in every submission. Nothing of Metal's
|
||||
observes it.
|
||||
`CommandBuffer::used_resources` lists what a command buffer uses until it completes, so a
|
||||
program knows when it may take memory away.
|
||||
- **Hazards** are tracked as Metal tracks them. A heap's resources are untracked by default, so
|
||||
@@ -199,7 +206,10 @@ the runtime made.
|
||||
bytes widened to 16-byte granules from the device's offset alignment, so it reports hazards
|
||||
between commands whose bytes are apart, as it does between untracked uses Metal leaves to the
|
||||
program; no order of either changes a result.
|
||||
- **Textures over buffers** share the buffer's bytes. The runtime keeps a copy and announces it
|
||||
- **Textures over buffers** share the buffer's bytes. An image over a no-copy buffer's host pages
|
||||
starts `UNDEFINED`, as Vulkan makes an image for host allocations; the host keeps the bytes it
|
||||
is bound to across its first move, reading them before and writing them back after
|
||||
(`WorkCounts::first_move_keeps`). The runtime keeps a copy and announces it
|
||||
(`shadowed-texture`) where the device's linear images cannot hold Metal's layout, and where the
|
||||
rows lie with bytes between them and the texture renders or a shader writes it (or it only
|
||||
reads, under `PaddedReadsPolicy::Shadow`).
|
||||
|
||||
@@ -67,6 +67,7 @@
|
||||
use super::device::lock;
|
||||
use super::error::{internal, Error, MemoryKind};
|
||||
use super::exit_guard;
|
||||
use super::program_objects::ProgramObject;
|
||||
use super::range::RangeAllocator;
|
||||
use super::resource_ids::Pool;
|
||||
use metal2vulkan::bind::indirect_commands::{
|
||||
@@ -160,12 +161,12 @@ impl From<AddressPlacement> for Place {
|
||||
/// buffer that only names it in an argument buffer still runs (an Apple M4, EV XRB-tok1-m4).
|
||||
pub type RangeToken = Box<dyn std::any::Any + Send + Sync>;
|
||||
|
||||
/// Where a resource keeps its caller's [`RangeToken`]: set once as the resource is made
|
||||
/// ([`keep`](Self::keep)), and dropped by [`release`](Self::release), which the resource's
|
||||
/// Where a resource keeps its caller's [`RangeToken`], held as the program's object
|
||||
/// (`program_objects.rs`): set once as the resource is made ([`keep`](Self::keep)), and dropped by [`release`](Self::release), which the resource's
|
||||
/// teardown calls once its range is free. Never dropped otherwise: a resource the runtime leaves
|
||||
/// to the process's exit leaks its token with it (`ManuallyDrop`).
|
||||
#[derive(Default)]
|
||||
pub(super) struct KeptToken(ManuallyDrop<Mutex<Option<RangeToken>>>);
|
||||
pub(super) struct KeptToken(ManuallyDrop<Mutex<Option<ProgramObject<RangeToken>>>>);
|
||||
|
||||
impl KeptToken {
|
||||
/// Keep `token`. Internal where one is kept already: no creator gives two.
|
||||
@@ -174,7 +175,7 @@ impl KeptToken {
|
||||
if kept.is_some() {
|
||||
return Err(internal("a resource's range token kept twice"));
|
||||
}
|
||||
*kept = Some(token);
|
||||
*kept = Some(ProgramObject::new(token));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -189,7 +190,7 @@ impl KeptToken {
|
||||
}
|
||||
let token = lock(&self.0).take();
|
||||
if let Some(token) = token {
|
||||
exit_guard::program(move || drop(token));
|
||||
exit_guard::program_release(move || drop(token));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
//!
|
||||
//! The binder takes them as `BindState::vertex_amplification` and plans the draws' views
|
||||
//! (`bind::ViewSetup`): Vulkan multiview over the pass's layers from the one the first mapping
|
||||
//! names, or without multiview into that one layer, or, where multiview does not draw them as
|
||||
//! Metal does, one draw per amplification (`render.rs`). Metal's validation stops a draw whose
|
||||
//! count is 0 or above its pipeline's `maxVertexAmplificationCount`, not the setter (RT6 Metal
|
||||
//! probe 13: "Vertex Amplification Count (3) must be between (inclusive) 1 and the maximum vertex
|
||||
//! names, or without multiview into that one layer, or, where multiview does not draw them as Metal
|
||||
//! does, one draw per amplification (`render.rs`). Metal's validation stops a draw whose count is 0
|
||||
//! or above its pipeline's `maxVertexAmplificationCount`, not the setter (a Metal probe on an M4:
|
||||
//! "Vertex Amplification Count (3) must be between (inclusive) 1 and the maximum vertex
|
||||
//! amplification count specified in the pipeline state (2)"), so the encoder holds any count. A
|
||||
//! draw of a count of 0 draws nothing, as plain Metal draws it (probe 13 `amp0`). One above a
|
||||
//! pipeline's maximum of 2 or more, up to Metal's 8, draws that many amplifications, as plain Metal
|
||||
|
||||
@@ -10,8 +10,18 @@
|
||||
//!
|
||||
//! What a bound texture's usage allows, and what a sampler's clamps sample, is checked at the
|
||||
//! command that uses the slot, against the function's use of it; binding checks only the index
|
||||
//! range, the object's device, a buffer offset against the buffer's length, and that a texture
|
||||
//! is not memoryless (Metal's validation stops binding one, RT6 probes 6b and 6c).
|
||||
//! range, the object's device, a buffer offset against the buffer's length, and that a texture is
|
||||
//! not memoryless (Metal's validation stops binding one; a Metal probe on an M4).
|
||||
//!
|
||||
//! Every object a table binds is held until its encoder's command buffer completes, as Metal (with
|
||||
//! retained references) holds what an encoder was handed: a no-copy buffer bound, then released by
|
||||
//! the program, ran its deallocator only after its command buffer completed, whether a command used
|
||||
//! it, it was replaced before any did, or it was bound after the last (the M3 Max under macOS
|
||||
//! 27.0.1, probes `dealloc-probe` and `dealloc-probe2`, compute and render encoders). A command
|
||||
//! that uses the table retains what it binds (`ArgumentTable::retain`); an object replaced or
|
||||
//! unbound that no such command retained at its slot, and one still bound as the encoder ends, is
|
||||
//! retained then (`ArgumentTable::let_go`, `ArgumentTable::let_go_all`). So a bind before each
|
||||
//! draw retains nothing of its own: it looks its slot up among what the last retain held.
|
||||
//!
|
||||
//! A compute encoder's table differs in two answers, as plain Metal's compute encoder gave them
|
||||
//! on an M4 (EV `SWP-misuse1-m4`) where its API validation asserts: it holds a buffer bound past
|
||||
@@ -36,8 +46,9 @@ use metal2vulkan::pipeline::{
|
||||
BufferKind, PipelineInterface, SlotClass, SlotInterface, SlotRef, Stage,
|
||||
};
|
||||
use std::any::Any;
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
/// Entries of a buffer table (`setBuffer:offset:atIndex:` and its stage forms).
|
||||
pub(super) const BUFFER_SLOTS: u32 = 31;
|
||||
@@ -179,15 +190,58 @@ fn attribute_stride(stride: u64) -> Option<u32> {
|
||||
(stride != ATTRIBUTE_STRIDE_STATIC).then_some(stride as u32)
|
||||
}
|
||||
|
||||
/// Bind `value` at `index` of `table`, or unbind the index when `value` is `None`.
|
||||
fn set_entry<T>(table: &mut BTreeMap<u32, T>, index: u32, value: Option<T>) {
|
||||
/// Bind `value` at `index` of `table`, or unbind the index when `value` is `None`: what was
|
||||
/// bound there before.
|
||||
fn set_entry<T>(table: &mut BTreeMap<u32, T>, index: u32, value: Option<T>) -> Option<T> {
|
||||
match value {
|
||||
Some(value) => {
|
||||
table.insert(index, value);
|
||||
}
|
||||
None => {
|
||||
table.remove(&index);
|
||||
}
|
||||
Some(value) => table.insert(index, value),
|
||||
None => table.remove(&index),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind the handle `value` at `index` of `table` with `with` (its offset, its clamps), or unbind
|
||||
/// the index when `value` is `None`: the handle it replaced or unbound, another object than
|
||||
/// `value` ([`ArgumentTable::let_go`]). The handle already bound there (the same object) keeps
|
||||
/// its hold and takes `with` alone: binding it again takes no new reference, whose count the
|
||||
/// threads that release the encoder's holds share.
|
||||
fn set_handle<T: Clone + PartialEq, W>(
|
||||
table: &mut BTreeMap<u32, (T, W)>,
|
||||
index: u32,
|
||||
value: Option<&T>,
|
||||
with: W,
|
||||
) -> Option<T> {
|
||||
match value {
|
||||
Some(value) => match table.entry(index) {
|
||||
Entry::Occupied(mut bound) if bound.get().0 == *value => {
|
||||
bound.get_mut().1 = with;
|
||||
None
|
||||
}
|
||||
Entry::Occupied(mut bound) => Some(bound.insert((value.clone(), with)).0),
|
||||
Entry::Vacant(slot) => {
|
||||
slot.insert((value.clone(), with));
|
||||
None
|
||||
}
|
||||
},
|
||||
None => table.remove(&index).map(|(handle, _)| handle),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`set_handle`] for a table of handles alone.
|
||||
fn set_bare_handle<T: Clone + PartialEq>(
|
||||
table: &mut BTreeMap<u32, T>,
|
||||
index: u32,
|
||||
value: Option<&T>,
|
||||
) -> Option<T> {
|
||||
match value {
|
||||
Some(value) => match table.entry(index) {
|
||||
Entry::Occupied(bound) if bound.get() == value => None,
|
||||
Entry::Occupied(mut bound) => Some(bound.insert(value.clone())),
|
||||
Entry::Vacant(slot) => {
|
||||
slot.insert(value.clone());
|
||||
None
|
||||
}
|
||||
},
|
||||
None => table.remove(&index),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,7 +334,7 @@ impl ArgumentTable {
|
||||
/// another device, and in a render stage's table an offset past the buffer's length.
|
||||
pub(super) fn set_buffer(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
buffer: Option<&Buffer>,
|
||||
offset: u64,
|
||||
@@ -294,7 +348,7 @@ impl ArgumentTable {
|
||||
/// [`set_buffer`](Self::set_buffer) is.
|
||||
pub(super) fn set_buffer_with_stride(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
buffer: Option<&Buffer>,
|
||||
offset: u64,
|
||||
@@ -303,19 +357,17 @@ impl ArgumentTable {
|
||||
) -> Result<(), Error> {
|
||||
check_index(call, index, BUFFER_SLOTS)?;
|
||||
let stride = attribute_stride(stride);
|
||||
match buffer {
|
||||
Some(buffer) => {
|
||||
self.check_buffer(core, call, buffer, offset)?;
|
||||
self.buffers.insert(index, (buffer.clone(), offset));
|
||||
}
|
||||
None => {
|
||||
self.buffers.remove(&index);
|
||||
}
|
||||
if let Some(buffer) = buffer {
|
||||
self.check_buffer(core, call, buffer, offset)?;
|
||||
}
|
||||
let replaced = set_handle(&mut self.buffers, index, buffer, offset);
|
||||
set_entry(&mut self.attribute_strides, index, stride);
|
||||
self.function_tables.remove(&index);
|
||||
self.null_tables.remove(&index);
|
||||
self.bytes.remove(&index);
|
||||
if let Some(replaced) = replaced {
|
||||
self.let_go(core, (SlotClass::Buffer, index), Bound::Buffer(&replaced));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -324,7 +376,7 @@ impl ArgumentTable {
|
||||
/// and when the slices' lengths differ; a refusal binds none of them.
|
||||
pub(super) fn set_buffers(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
buffers: &[Option<&Buffer>],
|
||||
offsets: &[u64],
|
||||
@@ -338,7 +390,7 @@ impl ArgumentTable {
|
||||
/// `set_buffers` is.
|
||||
pub(super) fn set_buffers_with_strides(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
buffers: &[Option<&Buffer>],
|
||||
offsets: &[u64],
|
||||
@@ -358,15 +410,14 @@ impl ArgumentTable {
|
||||
for (((buffer, &offset), stride), index) in
|
||||
buffers.iter().zip(offsets).zip(strides).zip(first..)
|
||||
{
|
||||
set_entry(
|
||||
&mut self.buffers,
|
||||
index,
|
||||
buffer.map(|buffer| (buffer.clone(), offset)),
|
||||
);
|
||||
let replaced = set_handle(&mut self.buffers, index, *buffer, offset);
|
||||
set_entry(&mut self.attribute_strides, index, stride);
|
||||
self.function_tables.remove(&index);
|
||||
self.null_tables.remove(&index);
|
||||
self.bytes.remove(&index);
|
||||
if let Some(replaced) = replaced {
|
||||
self.let_go(core, (SlotClass::Buffer, index), Bound::Buffer(&replaced));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -387,7 +438,7 @@ impl ArgumentTable {
|
||||
/// none keeps no offset), and in a render stage's table an offset past the buffer's length.
|
||||
pub(super) fn set_buffer_offset(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
offset: u64,
|
||||
index: u32,
|
||||
@@ -400,7 +451,7 @@ impl ArgumentTable {
|
||||
/// [`set_buffer_offset`](Self::set_buffer_offset) is.
|
||||
pub(super) fn set_buffer_offset_with_stride(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
offset: u64,
|
||||
stride: u64,
|
||||
@@ -432,9 +483,12 @@ impl ArgumentTable {
|
||||
}
|
||||
if self.function_tables.remove(&index).is_some() {
|
||||
// The table reads as the null table until the index is bound again.
|
||||
self.buffers.remove(&index);
|
||||
let words = self.buffers.remove(&index);
|
||||
self.attribute_strides.remove(&index);
|
||||
self.null_tables.insert(index);
|
||||
if let Some((words, _)) = words {
|
||||
self.let_go(core, (SlotClass::Buffer, index), Bound::Buffer(&words));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let compute = self.compute;
|
||||
@@ -462,7 +516,7 @@ impl ArgumentTable {
|
||||
/// index past the table, and more than [`INLINE_BYTES_LIMIT`] bytes.
|
||||
pub(super) fn set_bytes(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
bytes: &[u8],
|
||||
stride: Option<u64>,
|
||||
@@ -486,10 +540,13 @@ impl ArgumentTable {
|
||||
.state()
|
||||
.uploads
|
||||
.upload(core.device(), bytes, padded)?;
|
||||
self.buffers.remove(&index);
|
||||
let replaced = self.buffers.remove(&index);
|
||||
self.attribute_strides.remove(&index);
|
||||
self.function_tables.remove(&index);
|
||||
self.null_tables.remove(&index);
|
||||
if let Some((replaced, _)) = replaced {
|
||||
self.let_go(core, (SlotClass::Buffer, index), Bound::Buffer(&replaced));
|
||||
}
|
||||
self.bytes.insert(
|
||||
index,
|
||||
InlineBytes {
|
||||
@@ -509,7 +566,7 @@ impl ArgumentTable {
|
||||
/// binds none of them.
|
||||
pub(super) fn set_textures(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
textures: &[Option<&Texture>],
|
||||
first: u32,
|
||||
@@ -520,7 +577,9 @@ impl ArgumentTable {
|
||||
texture.check_not_memoryless(call)?;
|
||||
}
|
||||
for (texture, index) in textures.iter().zip(first..) {
|
||||
set_entry(&mut self.textures, index, texture.cloned());
|
||||
if let Some(replaced) = set_bare_handle(&mut self.textures, index, *texture) {
|
||||
self.let_go(core, (SlotClass::Texture, index), Bound::Texture(&replaced));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -531,7 +590,7 @@ impl ArgumentTable {
|
||||
/// inverted is refused at the command that samples through it.
|
||||
pub(super) fn set_samplers(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
samplers: &[Option<&SamplerState>],
|
||||
clamps: Option<(&[f32], &[f32])>,
|
||||
@@ -548,11 +607,9 @@ impl ArgumentTable {
|
||||
}
|
||||
for (i, (sampler, index)) in samplers.iter().zip(first..).enumerate() {
|
||||
let clamp = clamps.map(|(min, max)| [min[i], max[i]]);
|
||||
set_entry(
|
||||
&mut self.samplers,
|
||||
index,
|
||||
sampler.map(|sampler| (sampler.clone(), clamp)),
|
||||
);
|
||||
if let Some(replaced) = set_handle(&mut self.samplers, index, *sampler, clamp) {
|
||||
self.let_go(core, (SlotClass::Sampler, index), Bound::Sampler(&replaced));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -563,7 +620,7 @@ impl ArgumentTable {
|
||||
/// index past the buffer table, a table of another device; a refusal binds none of them.
|
||||
pub(super) fn set_function_tables(
|
||||
&mut self,
|
||||
core: &EncoderCore,
|
||||
core: &mut EncoderCore,
|
||||
call: &'static str,
|
||||
tables: &[Option<&VisibleFunctionTable>],
|
||||
first: u32,
|
||||
@@ -573,7 +630,7 @@ impl ArgumentTable {
|
||||
core.check_device(call, table.device())?;
|
||||
}
|
||||
for (table, index) in tables.iter().zip(first..) {
|
||||
set_entry(
|
||||
let replaced = set_entry(
|
||||
&mut self.buffers,
|
||||
index,
|
||||
table.map(|table| (table.words().clone(), 0)),
|
||||
@@ -582,6 +639,15 @@ impl ArgumentTable {
|
||||
self.attribute_strides.remove(&index);
|
||||
self.null_tables.remove(&index);
|
||||
self.bytes.remove(&index);
|
||||
// A table's words bound again at its index are the same object, held by the table.
|
||||
if let Some((replaced, _)) = replaced.filter(|(replaced, _)| {
|
||||
!self
|
||||
.buffers
|
||||
.get(&index)
|
||||
.is_some_and(|(bound, _)| bound == replaced)
|
||||
}) {
|
||||
self.let_go(core, (SlotClass::Buffer, index), Bound::Buffer(&replaced));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -903,19 +969,7 @@ impl ArgumentTable {
|
||||
/// Each object bound, by slot, in the table's order: its buffers, then its textures, then
|
||||
/// its sampler states, each by index.
|
||||
fn bound(&self) -> impl DoubleEndedIterator<Item = ((SlotClass, u32), Bound<'_>)> {
|
||||
let buffers = self
|
||||
.buffers
|
||||
.iter()
|
||||
.map(|(&index, (buffer, _))| ((SlotClass::Buffer, index), Bound::Buffer(buffer)));
|
||||
let textures = self
|
||||
.textures
|
||||
.iter()
|
||||
.map(|(&index, texture)| ((SlotClass::Texture, index), Bound::Texture(texture)));
|
||||
let samplers = self
|
||||
.samplers
|
||||
.iter()
|
||||
.map(|(&index, (sampler, _))| ((SlotClass::Sampler, index), Bound::Sampler(sampler)));
|
||||
buffers.chain(textures).chain(samplers)
|
||||
bound_in(&self.buffers, &self.textures, &self.samplers)
|
||||
}
|
||||
|
||||
/// Hold everything bound until `core`'s command buffer completes: a command uses it, and
|
||||
@@ -928,27 +982,94 @@ impl ArgumentTable {
|
||||
/// the table's order, as one hold of them all went.
|
||||
pub(super) fn retain(&self, core: &mut EncoderCore) {
|
||||
let mut retained = lock(&self.retained.0);
|
||||
let RetainedBy { core: by, bound } = &mut *retained;
|
||||
let same_core = *by == Some(core.id());
|
||||
let now = self.bound().map(|(slot, object)| (slot, object.address()));
|
||||
if same_core && bound.iter().copied().eq(now) {
|
||||
if retained.core == Some(core.id()) && retained.bound.iter().copied().eq(now) {
|
||||
return;
|
||||
}
|
||||
let keys = self.buffers.values().map(|(b, _)| b.identity().key);
|
||||
let texture_keys = self.textures.values().map(Texture::use_key);
|
||||
core.touch_keys(keys.chain(texture_keys));
|
||||
for (slot, object) in self.bound().rev() {
|
||||
let held = same_core
|
||||
&& bound
|
||||
.binary_search_by_key(&slot, |&(slot, _)| slot)
|
||||
.is_ok_and(|at| bound[at].1 == object.address());
|
||||
if !held {
|
||||
if !retained.holds(core, slot, object) {
|
||||
core.retain_shared(object.held());
|
||||
}
|
||||
}
|
||||
let RetainedBy { core: by, bound } = &mut *retained;
|
||||
bound.clear();
|
||||
bound.extend(self.bound().map(|(slot, object)| (slot, object.address())));
|
||||
*by = Some(core.id());
|
||||
core.device().shared().counts.argument_table_retained();
|
||||
}
|
||||
|
||||
/// Let go of `object`, which the table bound at `slot` until a call replaced or unbound it:
|
||||
/// `core` holds it until its command buffer completes, as Metal holds every object an encoder
|
||||
/// was handed, a binding replaced before any command used it included (the M3 Max under macOS
|
||||
/// 27.0.1, probes `dealloc-probe` and `dealloc-probe2`: a no-copy buffer so bound, then
|
||||
/// released, ran its deallocator only after the command buffer completed). Nothing is retained
|
||||
/// where `core` holds it already, from a command that used the table with it at `slot`
|
||||
/// ([`retain`](Self::retain)): a bind before each draw retains nothing here.
|
||||
fn let_go(&mut self, core: &mut EncoderCore, slot: (SlotClass, u32), object: Bound<'_>) {
|
||||
let retained = self
|
||||
.retained
|
||||
.0
|
||||
.get_mut()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if !retained.holds(core, slot, object) {
|
||||
core.retain_shared(object.held());
|
||||
}
|
||||
}
|
||||
|
||||
/// Let go of everything the table binds, as its encoder ends or its state is set back:
|
||||
/// [`let_go`](Self::let_go) of each object, the last first, so they go in the table's order.
|
||||
/// Metal holds what an encoder was handed until its command buffer completes, a binding no
|
||||
/// command used included (probe `dealloc-probe2`: a buffer or texture bound after the last
|
||||
/// draw or dispatch).
|
||||
pub(super) fn let_go_all(&mut self, core: &mut EncoderCore) {
|
||||
let ArgumentTable {
|
||||
buffers,
|
||||
textures,
|
||||
samplers,
|
||||
retained,
|
||||
..
|
||||
} = self;
|
||||
// A stage the encoder bound nothing to (most often its object, mesh and tile stages').
|
||||
if buffers.is_empty() && textures.is_empty() && samplers.is_empty() {
|
||||
return;
|
||||
}
|
||||
let retained = retained.0.get_mut().unwrap_or_else(PoisonError::into_inner);
|
||||
for (slot, object) in bound_in(buffers, textures, samplers).rev() {
|
||||
if !retained.holds(core, slot, object) {
|
||||
core.retain_shared(object.held());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects a table's `buffers`, `textures` and `samplers` bind, by slot, in the table's order
|
||||
/// ([`ArgumentTable::bound`]).
|
||||
fn bound_in<'a>(
|
||||
buffers: &'a BTreeMap<u32, (Buffer, u64)>,
|
||||
textures: &'a BTreeMap<u32, Texture>,
|
||||
samplers: &'a BTreeMap<u32, (SamplerState, Option<[f32; 2]>)>,
|
||||
) -> impl DoubleEndedIterator<Item = ((SlotClass, u32), Bound<'a>)> {
|
||||
let buffers = buffers
|
||||
.iter()
|
||||
.map(|(&index, (buffer, _))| ((SlotClass::Buffer, index), Bound::Buffer(buffer)));
|
||||
let textures = textures
|
||||
.iter()
|
||||
.map(|(&index, texture)| ((SlotClass::Texture, index), Bound::Texture(texture)));
|
||||
let samplers = samplers
|
||||
.iter()
|
||||
.map(|(&index, (sampler, _))| ((SlotClass::Sampler, index), Bound::Sampler(sampler)));
|
||||
buffers.chain(textures).chain(samplers)
|
||||
}
|
||||
|
||||
impl RetainedBy {
|
||||
/// Whether `core` holds `object`, bound at `slot`, from the table's last retain into it.
|
||||
fn holds(&self, core: &EncoderCore, slot: (SlotClass, u32), object: Bound<'_>) -> bool {
|
||||
self.core == Some(core.id())
|
||||
&& (self.bound)
|
||||
.binary_search_by_key(&slot, |&(slot, _)| slot)
|
||||
.is_ok_and(|at| self.bound[at].1 == object.address())
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,12 @@
|
||||
//! image is linear over the buffer's bytes: Metal leaves the buffer's bytes, so the pass renders
|
||||
//! it through the image its texture keeps, copied into where the pass loads it (`Load`), and
|
||||
//! never back (`kept_bytes.rs`).
|
||||
//! - **A render target's depth that may hold a negative value or a NaN**
|
||||
//! (`texture/signed_depth.rs`), which a pass loads: it renders over its magnitude stand-in, the
|
||||
//! image its texture keeps for the queue (`kept_backing`), whose words the pass writes from the
|
||||
//! depth's before it and merges back after it where it stores the depth and may have written
|
||||
//! it: its depth test is Metal's, and so is what it keeps, but for the merge's corner, which
|
||||
//! `signed-depth-test` names.
|
||||
//! - **A pass's hidden depth and stencil**. In a pass without a depth/stencil attachment, plain
|
||||
//! Metal tests a draw whose state uses depth or the stencil against a hidden depth of `float`,
|
||||
//! 1.0 at the pass's start, and a stencil of 0, kept per sample through the pass. Such a draw
|
||||
@@ -90,6 +96,7 @@ use super::texture_descriptor::TextureDescriptor;
|
||||
use super::tracker::{Access, Barrier, Use};
|
||||
use super::values::ResourceOptions;
|
||||
use super::Device;
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::device::FormatUsage;
|
||||
use metal2vulkan::metal::format::{aspects, FormatMapping};
|
||||
@@ -138,6 +145,11 @@ pub(super) enum Cause {
|
||||
/// buffer keeps its bytes (`kept_bytes.rs`, which announces it, `dont-care-stand-in`): copied
|
||||
/// into where the pass loads it, and never back.
|
||||
KeptBytes,
|
||||
/// A render target's 32-bit float depth that may hold a negative value or a NaN, which the
|
||||
/// pass loads: it renders over the magnitude stand-in its texture keeps for the queue, written
|
||||
/// from the depth before the pass and merged back after it (`texture/signed_depth.rs`), not
|
||||
/// by the stand-in's own copies.
|
||||
Magnitude,
|
||||
}
|
||||
|
||||
impl StandIn {
|
||||
@@ -658,7 +670,7 @@ impl StandInCopies {
|
||||
///
|
||||
/// `command_buffer` is recording outside a render pass, and only the caller records it; the
|
||||
/// images are live until it completes and rest in `GENERAL`.
|
||||
pub(super) unsafe fn record_in(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer) {
|
||||
pub(super) unsafe fn record_in(&self, raw: &Vk, command_buffer: vk::CommandBuffer) {
|
||||
let general = vk::ImageLayout::GENERAL;
|
||||
// SAFETY: the caller's contract; every image has the transfer usage its copy needs
|
||||
// (checked when the stand-in was made), and each region lies in both images.
|
||||
|
||||
@@ -3,17 +3,17 @@
|
||||
//! destroyed with the device. Every encoder of a pass without attachments records its draws against
|
||||
//! its sample count's kept pass, makes its pipelines against it, and begins it.
|
||||
//!
|
||||
//! Such a pass rasterizes at its `defaultRasterSampleCount` (RT6 Metal probe 8), the sample count
|
||||
//! the encoder checks each pipeline's `rasterSampleCount` against (`render.rs`). A Vulkan subpass
|
||||
//! without attachments rasterizes at its pipelines' `rasterizationSamples`, but MoltenVK takes
|
||||
//! the count from its subpass's default sample count, which only creating a pipeline against that
|
||||
//! very `VkRenderPass` sets (`MVKGraphicsPipeline` in MoltenVK 1.4.1's `MVKPipeline.mm`; a
|
||||
//! Such a pass rasterizes at its `defaultRasterSampleCount` (a Metal probe on an M4), the sample
|
||||
//! count the encoder checks each pipeline's `rasterSampleCount` against (`render.rs`). A Vulkan
|
||||
//! subpass without attachments rasterizes at its pipelines' `rasterizationSamples`, but MoltenVK
|
||||
//! takes the count from its subpass's default sample count, which only creating a pipeline against
|
||||
//! that very `VkRenderPass` sets (`MVKGraphicsPipeline` in MoltenVK 1.4.1's `MVKPipeline.mm`; a
|
||||
//! `MVKRenderSubpass` begins with 1). A pass made per encoder, after the pipelines it draws were
|
||||
//! made against another, compatible one, rasterized one sample: at 2x each pixel held sample 0
|
||||
//! alone (EV `RT6-atl-gpu-mvk`). The kept pass is the one its pipelines were made against, on
|
||||
//! every device, so it is the one its subpass's default was set on; the others rasterize the
|
||||
//! pipelines' count either way. A pass of no attachments has no load or store operation, so the
|
||||
//! one pass serves both as the compatible pass and as the pass begun.
|
||||
//! alone (EV `RT6-atl-gpu-mvk`). The kept pass is the one its pipelines were made against, on every
|
||||
//! device, so it is the one its subpass's default was set on; the others rasterize the pipelines'
|
||||
//! count either way. A pass of no attachments has no load or store operation, so the one pass
|
||||
//! serves both as the compatible pass and as the pass begun.
|
||||
//!
|
||||
//! A pass whose subpass leaves out attachments the pass still describes (the sample planes', with
|
||||
//! their anchor, `render_target.rs`) is no pass without attachments here: only a shape with no
|
||||
|
||||
@@ -171,7 +171,7 @@ impl BinaryArchive {
|
||||
)?;
|
||||
let profile = self.profile();
|
||||
let keys = metal_key::render(&profile, descriptor);
|
||||
let kind = if state.base().graphics.tessellation.is_some() {
|
||||
let kind = if crate::tessellation::patches(&state.base().graphics).is_some() {
|
||||
VertexKind::Patch
|
||||
} else {
|
||||
VertexKind::Plain
|
||||
|
||||
@@ -16,11 +16,12 @@
|
||||
//! (`Tables::region_record`) in its `ReplayRegionAddress` hole.
|
||||
//! - **Textures** a slot binds take the `VkImageView` the plan's view asks for (the texture's,
|
||||
//! made at its first bind, `binding_view.rs`), in the `GENERAL` layout every runtime image
|
||||
//! rests in. **Samplers** take the `VkSampler` of their state for the write's use and the
|
||||
//! bind's LOD clamps (`bind::sampler_desc`, `sampler.rs`), its address modes mapped where the
|
||||
//! slot samples a texture of an address-mode map (`address_map.rs`); a combined write checks the
|
||||
//! view format's filtering against it. A slot with nothing bound takes the device's neutral image
|
||||
//! or sampler (`neutral.rs`).
|
||||
//! rests in; a draw's sampled binding of a texture its render pass instance renders takes the
|
||||
//! texture's copy (`texture/attached_reads.rs`). **Samplers** take the `VkSampler` of their
|
||||
//! state for the write's use and the bind's LOD clamps (`bind::sampler_desc`, `sampler.rs`), its
|
||||
//! address modes mapped where the slot samples a texture of an address-mode map
|
||||
//! (`address_map.rs`); a combined write checks the view format's filtering against it. A slot
|
||||
//! with nothing bound takes the device's neutral image or sampler (`neutral.rs`).
|
||||
//! - **Texture buffers** a slot binds take a texel buffer view of their buffer's bytes in the
|
||||
//! format the plan names, over the range it gives (`buffer_texture.rs`); an unbound slot takes
|
||||
//! the device's neutral texel buffer.
|
||||
@@ -51,6 +52,7 @@ use super::command_buffer::{NotedTable, State};
|
||||
use super::error::{internal, Error, RuntimeGap};
|
||||
use super::function_table::{self, TableSnapshot, VisibleFunctionTable};
|
||||
use super::heap_sets::{Keeper, TextureTable, HEAP_SET};
|
||||
use super::key_hash::KeyMap;
|
||||
use super::render_pass::{PassLayout, Target};
|
||||
use super::render_target;
|
||||
use super::residency::{Residency, Used};
|
||||
@@ -67,9 +69,9 @@ use metal2vulkan::bind::{
|
||||
NeutralResource, PushConstantWrite, PushHole, ResourceUse, RootTable, SamplerDescriptor,
|
||||
SamplerSource, UseTarget, ViewSetup, WriteSource,
|
||||
};
|
||||
use metal2vulkan::metal::sampler::OpaqueBlackBorder;
|
||||
use metal2vulkan::metal::sampler::{OpaqueBlackBorder, SamplerUse};
|
||||
use metal2vulkan::pipeline::{HandleClass, SlotClass, SlotRef, Stage, StorageAttachmentView};
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::collections::BTreeSet;
|
||||
use std::ops::Deref;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
@@ -82,6 +84,10 @@ pub(super) struct Tables<'a> {
|
||||
/// A render encoder's pass, whose attachments a draw's input and storage attachments read,
|
||||
/// and the draw's views of its layers (`render_target::viewed`).
|
||||
pass: Option<(&'a PassLayout, ViewSetup)>,
|
||||
/// A draw's render pass instance's attachments: a sampled slot binding of a texture that
|
||||
/// presents one of its color attachments takes the texture's copy
|
||||
/// (`texture/attached_reads.rs`).
|
||||
attached: Option<&'a PassLayout>,
|
||||
/// The sampler states the bind state lists as argument samplers, in its order.
|
||||
argument_samplers: &'a [SamplerState],
|
||||
/// Where the plan's heap writes go, when the command writes a heap.
|
||||
@@ -128,6 +134,19 @@ pub(super) struct Tables<'a> {
|
||||
/// first index where it is indexed. Its `PushHole::CaptureAddress` and
|
||||
/// `PushHole::CaptureIndexAddress` take them.
|
||||
capture: Option<(u64, Option<u64>)>,
|
||||
/// A de-indexed draw's first index's address (`VariantKey::primitive_id_indices`): its
|
||||
/// `PushHole::CaptureIndexAddress` takes it.
|
||||
indices: Option<u64>,
|
||||
/// A draw's slots read through snapshots (`render/snapshot.rs`): each binds its own texture,
|
||||
/// not a copy, in the feedback loop layout, and its snapshot at `WriteSource::SnapshotTexels`.
|
||||
snapshots: Option<&'a SnapshotViews>,
|
||||
}
|
||||
|
||||
/// The fragment texture slots a draw reads through snapshots, and the storage view of each one's
|
||||
/// snapshot (`render/snapshot.rs`, `Texture::snapshot_texels`).
|
||||
pub(super) struct SnapshotViews {
|
||||
pub(super) slots: BTreeSet<u32>,
|
||||
pub(super) views: Vec<(u32, vk::ImageView)>,
|
||||
}
|
||||
|
||||
impl<'a> Tables<'a> {
|
||||
@@ -137,6 +156,7 @@ impl<'a> Tables<'a> {
|
||||
stages,
|
||||
residency: None,
|
||||
pass: None,
|
||||
attached: None,
|
||||
argument_samplers: &[],
|
||||
heap: None,
|
||||
texture_table: None,
|
||||
@@ -153,9 +173,30 @@ impl<'a> Tables<'a> {
|
||||
tile_memory: None,
|
||||
sampler_maps: SamplerMaps::default(),
|
||||
capture: None,
|
||||
indices: None,
|
||||
snapshots: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tables, with a draw's slots read through snapshots and their snapshots' views
|
||||
/// (`render/snapshot.rs`).
|
||||
pub(super) fn with_snapshots(self, snapshots: &'a SnapshotViews) -> Tables<'a> {
|
||||
Tables {
|
||||
snapshots: Some(snapshots),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `slot` is one a draw reads through a snapshot: its binding takes the texture
|
||||
/// itself, in the feedback loop layout, never its copy.
|
||||
fn snapshot_slot(&self, slot: SlotRef) -> bool {
|
||||
slot.stage == Stage::Fragment
|
||||
&& slot.class == SlotClass::Texture
|
||||
&& self
|
||||
.snapshots
|
||||
.is_some_and(|s| s.slots.contains(&slot.index))
|
||||
}
|
||||
|
||||
/// The tables, with a capture draw's addresses: of its first capture `records`, and of its
|
||||
/// first index (`indices`) where it is indexed (`render/capture.rs`).
|
||||
pub(super) fn with_capture(self, records: u64, indices: Option<u64>) -> Tables<'a> {
|
||||
@@ -165,6 +206,14 @@ impl<'a> Tables<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tables, with a de-indexed draw's first index's address (`Tables::indices`).
|
||||
pub(super) fn with_indices(self, address: u64) -> Tables<'a> {
|
||||
Tables {
|
||||
indices: Some(address),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// The tables, with the address-mode maps the command's runtime samplers are bound with,
|
||||
/// the bind state's (`address_map::sampler_maps`).
|
||||
pub(super) fn with_sampler_maps(self, maps: SamplerMaps) -> Tables<'a> {
|
||||
@@ -190,6 +239,26 @@ impl<'a> Tables<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tables, with a draw's render pass instance of `instance`'s attachments: a sampled slot
|
||||
/// binding of a texture that presents one of its color attachments takes the texture's copy
|
||||
/// (`texture/attached_reads.rs`).
|
||||
pub(super) fn with_attachments(self, instance: &'a PassLayout) -> Tables<'a> {
|
||||
Tables {
|
||||
attached: Some(instance),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a slot binding of `texture` of the kind `storage` reads it where the draw's
|
||||
/// instance renders it: a sampled one of a texture that presents one of its color
|
||||
/// attachments (`texture/attached_reads.rs`).
|
||||
fn attached(&self, texture: &Texture, storage: bool) -> bool {
|
||||
!storage
|
||||
&& self
|
||||
.attached
|
||||
.is_some_and(|instance| texture.attached_in(instance))
|
||||
}
|
||||
|
||||
/// The tables, with the storage view of the shader-side stencil's `shadow`.
|
||||
pub(super) fn with_shadow(self, shadow: vk::ImageView) -> Tables<'a> {
|
||||
Tables {
|
||||
@@ -327,10 +396,13 @@ pub(super) struct Command<'a> {
|
||||
/// An emulated mesh draw's work buffer and records, for its `MeshWork` and `MeshRecords`
|
||||
/// writes.
|
||||
pub(super) mesh: Option<MeshRegions>,
|
||||
/// An emulated tessellation draw's work buffer and records, for its `TessellationWork` and
|
||||
/// `TessellationRecords` writes.
|
||||
pub(super) tessellation: Option<MeshRegions>,
|
||||
}
|
||||
|
||||
/// Where an emulated mesh draw's work buffer and records lie (`render/mesh.rs`), each bound
|
||||
/// whole.
|
||||
/// Where an emulated mesh or tessellation draw's work buffer and records lie (`render/mesh.rs`,
|
||||
/// `render/tessellation_scan.rs`), each bound whole.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct MeshRegions {
|
||||
pub(super) work: vk::DescriptorBufferInfo,
|
||||
@@ -584,8 +656,17 @@ pub(super) fn bind(
|
||||
address: tables
|
||||
.capture
|
||||
.and_then(|(_, indices)| indices)
|
||||
.or(tables.indices)
|
||||
.ok_or_else(|| internal("a capture index hole without capture indices"))?,
|
||||
},
|
||||
// Which of a snapshot variant's draws runs: 0 in the plan's bytes, the drawing draw's,
|
||||
// and set before each draw as it records (`render/snapshot.rs`).
|
||||
PushHole::SnapshotPhase { .. } if tables.snapshots.is_some() => continue,
|
||||
PushHole::SnapshotPhase { .. } => {
|
||||
return Err(internal(
|
||||
"a snapshot phase hole the runtime did not ask for",
|
||||
));
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(Bound {
|
||||
@@ -639,6 +720,7 @@ pub(super) fn argument_sampler_writes(
|
||||
index,
|
||||
compare,
|
||||
integer,
|
||||
cube_gradient,
|
||||
} = write.source
|
||||
else {
|
||||
continue;
|
||||
@@ -654,8 +736,7 @@ pub(super) fn argument_sampler_writes(
|
||||
let desc = metal2vulkan::bind::sampler_desc(
|
||||
device.compile_device(),
|
||||
state.descriptor(),
|
||||
compare,
|
||||
integer,
|
||||
SamplerUse::new(compare, integer).with_cube_gradient(cube_gradient),
|
||||
OpaqueBlackBorder::Stated,
|
||||
None,
|
||||
)
|
||||
@@ -865,8 +946,9 @@ const KEPT_VIEWS: usize = 256;
|
||||
/// moves.
|
||||
/// - **A sampler's description** (`sampler_desc`'s answer) for a sampler slot is a function of
|
||||
/// the descriptor the bind maps the slot's state to (its LOD clamps and the address modes its
|
||||
/// textures map), the four facts `sampler_desc` takes beside the device (a comparison, an integer
|
||||
/// texture, the opaque black border, the image's format) and the device. The bind still asks the
|
||||
/// textures map), the facts `sampler_desc` takes beside the device (the use: a comparison, an
|
||||
/// integer texture, a cube's explicit gradients; the opaque black border; the image's format)
|
||||
/// and the device. The bind still asks the
|
||||
/// state for its `VkSampler` of the description (`SamplerState::vk_sampler`), so the state keeps
|
||||
/// and forgets its samplers as before.
|
||||
///
|
||||
@@ -876,13 +958,14 @@ const KEPT_VIEWS: usize = 256;
|
||||
pub(super) struct BindMemo {
|
||||
/// The views epoch the views were kept under.
|
||||
epoch: u64,
|
||||
views: HashMap<ViewKey, vk::ImageView>,
|
||||
views: KeyMap<ViewKey, vk::ImageView>,
|
||||
samplers: Vec<KeptSampler>,
|
||||
}
|
||||
|
||||
/// What a view a bind made or found is a function of ([`BindMemo`]): a binding of the texture as
|
||||
/// the view, a storage one where the flag is set.
|
||||
type ViewKey = (Texture, ImageViewDesc, bool);
|
||||
/// the view, a storage one where the first flag is set, of a texture the draw's instance renders
|
||||
/// where the second is (`Tables::attached`).
|
||||
type ViewKey = (Texture, ImageViewDesc, bool, bool);
|
||||
|
||||
/// A sampler description a bind worked out ([`BindMemo`]): `descriptor`'s under `facts`.
|
||||
struct KeptSampler {
|
||||
@@ -894,8 +977,7 @@ struct KeptSampler {
|
||||
/// What `sampler_desc` takes of a binding beside its descriptor and the device.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
struct SamplerFacts {
|
||||
compare: bool,
|
||||
integer: bool,
|
||||
use_: SamplerUse,
|
||||
opaque_black: OpaqueBlackBorder,
|
||||
format: Option<metal2vulkan::vk::Format>,
|
||||
}
|
||||
@@ -931,6 +1013,16 @@ fn image_descriptor(
|
||||
.image_view(view)
|
||||
.image_layout(vk::ImageLayout::GENERAL)
|
||||
};
|
||||
// A slot a draw reads through a snapshot samples its texture's subresource that the
|
||||
// instance's color attachment holds in the feedback loop layout, the layout its accesses
|
||||
// there name (`render_target::feedback_barriers`; "This layout is valid only for image
|
||||
// subresources of images created with the VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT
|
||||
// usage flag set", which `Texture::snapshot_color` checked).
|
||||
let in_feedback =
|
||||
|slot: SlotRef, info: vk::DescriptorImageInfo| match tables.snapshot_slot(slot) {
|
||||
true => info.image_layout(vk::ImageLayout::ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT),
|
||||
false => info,
|
||||
};
|
||||
// The kept views are dropped once an image of the device let its views go.
|
||||
let (mut kept_views, mut kept_samplers) = match memo {
|
||||
Some(memo) => {
|
||||
@@ -948,21 +1040,22 @@ fn image_descriptor(
|
||||
let mut texture_view = |slot: SlotRef, view: &ImageViewDesc, storage: bool| {
|
||||
let texture = slot_texture(tables, slot)
|
||||
.ok_or_else(|| internal("the plan binds an unbound texture slot"))?;
|
||||
let attached = tables.attached(texture, storage) && !tables.snapshot_slot(slot);
|
||||
let Some(kept_views) = kept_views.as_deref_mut() else {
|
||||
return texture.slot_view(call, view, storage);
|
||||
return texture.slot_view(call, view, storage, attached);
|
||||
};
|
||||
let key = (texture.clone(), *view, storage);
|
||||
let key = (texture.clone(), *view, storage, attached);
|
||||
if let Some(raw) = kept_views.get(&key) {
|
||||
return Ok(*raw);
|
||||
}
|
||||
let raw = texture.slot_view(call, view, storage)?;
|
||||
let raw = texture.slot_view(call, view, storage, attached)?;
|
||||
if kept_views.len() == KEPT_VIEWS {
|
||||
kept_views.clear();
|
||||
}
|
||||
kept_views.insert(key, raw);
|
||||
Ok::<_, Error>(raw)
|
||||
};
|
||||
let mut sampler = |slot: SlotRef, (compare, integer): (bool, bool), opaque_black, format| {
|
||||
let mut sampler = |slot: SlotRef, use_: SamplerUse, opaque_black, format| {
|
||||
let (state, clamps) = slot_sampler(tables, slot)
|
||||
.ok_or_else(|| internal("the plan binds an unbound sampler slot"))?;
|
||||
// Its address modes as the textures it samples map them.
|
||||
@@ -970,8 +1063,7 @@ fn image_descriptor(
|
||||
.sampler_maps
|
||||
.sampler(slot, bound_sampler(state, *clamps));
|
||||
let facts = SamplerFacts {
|
||||
compare,
|
||||
integer,
|
||||
use_,
|
||||
opaque_black,
|
||||
format,
|
||||
};
|
||||
@@ -985,8 +1077,7 @@ fn image_descriptor(
|
||||
let desc = metal2vulkan::bind::sampler_desc(
|
||||
device.compile_device(),
|
||||
&descriptor,
|
||||
compare,
|
||||
integer,
|
||||
use_,
|
||||
opaque_black,
|
||||
format,
|
||||
)
|
||||
@@ -1012,41 +1103,56 @@ fn image_descriptor(
|
||||
_ => Err(internal("a neutral sampler of a kind that is no sampler")),
|
||||
};
|
||||
Ok(match &write.source {
|
||||
WriteSource::Texture { slot, view } => image(texture_view(
|
||||
WriteSource::Texture { slot, view } => in_feedback(
|
||||
*slot,
|
||||
view,
|
||||
ty == vk::DescriptorType::STORAGE_IMAGE,
|
||||
)?),
|
||||
image(texture_view(
|
||||
*slot,
|
||||
view,
|
||||
ty == vk::DescriptorType::STORAGE_IMAGE,
|
||||
)?),
|
||||
),
|
||||
WriteSource::CombinedImageSampler {
|
||||
image: source,
|
||||
sampler: sampler_source,
|
||||
} => {
|
||||
let (view, format) = match source {
|
||||
ImageSource::Texture { slot, view } => {
|
||||
(texture_view(*slot, view, false)?, Some(view.format))
|
||||
}
|
||||
ImageSource::Neutral(kind) => (device.neutral_view(*kind)?, kind.format()),
|
||||
let (view, format, slot) = match source {
|
||||
ImageSource::Texture { slot, view } => (
|
||||
texture_view(*slot, view, false)?,
|
||||
Some(view.format),
|
||||
Some(*slot),
|
||||
),
|
||||
ImageSource::Neutral(kind) => (device.neutral_view(*kind)?, kind.format(), None),
|
||||
};
|
||||
let raw = match sampler_source {
|
||||
SamplerSource::Slot {
|
||||
slot,
|
||||
compare,
|
||||
integer,
|
||||
cube_gradient,
|
||||
opaque_black,
|
||||
} => sampler(*slot, (*compare, *integer), *opaque_black, format)?,
|
||||
} => sampler(
|
||||
*slot,
|
||||
SamplerUse::new(*compare, *integer).with_cube_gradient(*cube_gradient),
|
||||
*opaque_black,
|
||||
format,
|
||||
)?,
|
||||
SamplerSource::Immutable => vk::Sampler::null(),
|
||||
SamplerSource::Neutral(kind) => neutral_sampler(kind)?,
|
||||
};
|
||||
image(view).sampler(raw)
|
||||
match slot {
|
||||
Some(slot) => in_feedback(slot, image(view).sampler(raw)),
|
||||
None => image(view).sampler(raw),
|
||||
}
|
||||
}
|
||||
WriteSource::Sampler {
|
||||
slot,
|
||||
compare,
|
||||
integer,
|
||||
cube_gradient,
|
||||
opaque_black,
|
||||
} => vk::DescriptorImageInfo::default().sampler(sampler(
|
||||
*slot,
|
||||
(*compare, *integer),
|
||||
SamplerUse::new(*compare, *integer).with_cube_gradient(*cube_gradient),
|
||||
*opaque_black,
|
||||
None,
|
||||
)?),
|
||||
@@ -1150,6 +1256,17 @@ fn image_descriptor(
|
||||
None => return Err(internal("an extended-range color's shadow the pass lacks")),
|
||||
}
|
||||
}
|
||||
// A slot's snapshot, which the encoder made before the draw, in `GENERAL`.
|
||||
WriteSource::SnapshotTexels { slot } if ty == vk::DescriptorType::STORAGE_IMAGE => {
|
||||
let view = tables
|
||||
.snapshots
|
||||
.and_then(|s| s.views.iter().find(|(at, _)| at == slot))
|
||||
.map(|&(_, view)| view);
|
||||
match view {
|
||||
Some(view) => image(view),
|
||||
None => return Err(internal("a snapshot the draw did not take")),
|
||||
}
|
||||
}
|
||||
// The pass's fragment imageblock storage, which the encoder made before the draw.
|
||||
WriteSource::Imageblock if ty == vk::DescriptorType::STORAGE_IMAGE => {
|
||||
match tables.imageblock {
|
||||
@@ -1161,13 +1278,13 @@ fn image_descriptor(
|
||||
index,
|
||||
compare,
|
||||
integer,
|
||||
cube_gradient,
|
||||
} => match tables.argument_samplers.get(*index as usize) {
|
||||
Some(state) => {
|
||||
let desc = metal2vulkan::bind::sampler_desc(
|
||||
device.compile_device(),
|
||||
state.descriptor(),
|
||||
*compare,
|
||||
*integer,
|
||||
SamplerUse::new(*compare, *integer).with_cube_gradient(*cube_gradient),
|
||||
OpaqueBlackBorder::Stated,
|
||||
None,
|
||||
)
|
||||
@@ -1291,6 +1408,20 @@ fn descriptor(
|
||||
.ok_or_else(|| internal("a mesh work write without the draw's dispatch"))?
|
||||
.work
|
||||
}
|
||||
// An emulated tessellation draw's records and work buffer, whole: the draw's own
|
||||
// regions, or the command buffer's records pool (`render/tessellation_scan.rs`).
|
||||
WriteSource::TessellationRecords => {
|
||||
command
|
||||
.tessellation
|
||||
.ok_or_else(|| internal("a tessellation records write without the draw's scan"))?
|
||||
.records
|
||||
}
|
||||
WriteSource::TessellationWork => {
|
||||
command
|
||||
.tessellation
|
||||
.ok_or_else(|| internal("a tessellation work write without the draw's scan"))?
|
||||
.work
|
||||
}
|
||||
// An indexed patch draw's control-point index buffer.
|
||||
WriteSource::ControlPointIndices => {
|
||||
let (buffer, _) = tables.control_point_indices.ok_or_else(|| {
|
||||
@@ -1492,15 +1623,21 @@ pub(super) fn command_uses(
|
||||
},
|
||||
SlotClass::Texture => {
|
||||
// An unbound slot takes a neutral image; a texture whose image and usage
|
||||
// lack the binding's usage, its shadow (`texture/usage_shadow.rs`).
|
||||
// lack the binding's usage, its shadow (`texture/usage_shadow.rs`), as does
|
||||
// a draw's sampled one its instance renders (`texture/attached_reads.rs`).
|
||||
if let Some(texture) = slot_texture(tables, slot) {
|
||||
let (read, write) = image_access(resource.class)?;
|
||||
let storage = resource.class == AccessClass::StorageImage;
|
||||
let attached =
|
||||
tables.attached(texture, storage) && !tables.snapshot_slot(slot);
|
||||
let used = texture.slot_use(
|
||||
call,
|
||||
storage,
|
||||
access(read, resource.access.read),
|
||||
access(write, resource.access.write),
|
||||
attached,
|
||||
(
|
||||
access(read, resource.access.read),
|
||||
access(write, resource.access.write),
|
||||
),
|
||||
)?;
|
||||
name(&mut named, &reached, used.key);
|
||||
uses.push(used);
|
||||
|
||||
@@ -32,6 +32,7 @@ use super::texture::Texture;
|
||||
use super::tracker::{Access, Use, UseRange};
|
||||
use super::used_resources::EncoderKind;
|
||||
use super::values::{ResourceOptions, StorageMode};
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
@@ -160,7 +161,8 @@ impl CommandBuffer {
|
||||
core: EncoderCore::open(self, "blit_command_encoder", true)?,
|
||||
pattern: None,
|
||||
shadows: Vec::new(),
|
||||
log: self.device().shared().rebinds.any().then(CallLog::new),
|
||||
log: (self.device().shared().rebinds.any())
|
||||
.then(|| self.device().shared().scheduler.spare_logs().blit()),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -224,7 +226,7 @@ impl BlitCommandEncoder {
|
||||
pub(super) fn command(
|
||||
&mut self,
|
||||
uses: &[Use<ResourceKey>],
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) -> Result<(), Error> {
|
||||
self.command_in(TRANSFER, uses, record)
|
||||
}
|
||||
@@ -235,7 +237,7 @@ impl BlitCommandEncoder {
|
||||
&mut self,
|
||||
stages: vk::PipelineStageFlags2,
|
||||
uses: &[Use<ResourceKey>],
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) -> Result<(), Error> {
|
||||
self.command_in_reading(stages, uses, &[], record)
|
||||
}
|
||||
@@ -247,7 +249,7 @@ impl BlitCommandEncoder {
|
||||
&mut self,
|
||||
uses: &[Use<ResourceKey>],
|
||||
reads: &[FreshRead],
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) -> Result<(), Error> {
|
||||
self.command_in_reading(TRANSFER, uses, reads, record)
|
||||
}
|
||||
@@ -259,13 +261,13 @@ impl BlitCommandEncoder {
|
||||
stages: vk::PipelineStageFlags2,
|
||||
uses: &[Use<ResourceKey>],
|
||||
reads: &[FreshRead],
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) -> Result<(), Error> {
|
||||
let shadows = shadow::copies_used(self.shadows.iter(), uses);
|
||||
let copies = self.core.plan_shadows(&shadows, uses)?;
|
||||
self.core.shadow_copies(&copies);
|
||||
self.core.command_reading(stages, uses, reads, record);
|
||||
self.core.shadows_used(&shadows, uses);
|
||||
self.core.shadows_used(&shadows, uses, &[]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -327,8 +329,11 @@ impl BlitCommandEncoder {
|
||||
let from = bytes_in(CALL, source_offset, size, source_buffer.copy_reach())
|
||||
.map_err(|_| out_of_bounds(CALL, source_offset, size, source_buffer.length()))?;
|
||||
let to = bytes_in(CALL, destination_offset, size, destination_buffer.length())?;
|
||||
let (source, source_at) = source_buffer.at(source_offset);
|
||||
let (destination, destination_at) = destination_buffer.at(destination_offset);
|
||||
// Read as a blit's: a no-copy buffer's import released while idle is imported again
|
||||
// (`host_residency.rs`).
|
||||
let (source, source_at) = self.core.blit_at(source_buffer, source_offset)?;
|
||||
let (destination, destination_at) =
|
||||
self.core.blit_at(destination_buffer, destination_offset)?;
|
||||
// One buffer's bytes, or two no-copy buffers' made over the same bytes, which lie in one
|
||||
// import (`host_aliases.rs`): one `VkBuffer` from one byte 0.
|
||||
let one_bytes = source == destination
|
||||
@@ -432,8 +437,8 @@ impl BlitCommandEncoder {
|
||||
let range = bytes_in(CALL, range.start, size, buffer.length())?;
|
||||
let metal = (range.start, range.end);
|
||||
// The words and ends are the `VkBuffer`'s: a no-copy buffer's start in it need not be a
|
||||
// multiple of 4 (`Buffer::base`).
|
||||
let (destination, start) = buffer.at(range.start);
|
||||
// multiple of 4 (`Buffer::base`). Read as a blit's (`host_residency.rs`).
|
||||
let (destination, start) = self.core.blit_at(buffer, range.start)?;
|
||||
let pieces = fill_pieces(start..start + size);
|
||||
let mut uses = vec![writes(buffer, range)];
|
||||
let pattern = if pieces.head.is_empty() && pieces.tail.is_empty() {
|
||||
|
||||
@@ -337,12 +337,14 @@ impl BlitCommandEncoder {
|
||||
.collect();
|
||||
let staging = self.staged(&bytes)?;
|
||||
let (source, from) = staging.at(0);
|
||||
let (destination, _) = buffer.at(range.start);
|
||||
// Read as a blit's (`host_residency.rs`): where the range starts in the `VkBuffer`, and
|
||||
// each byte past it as far on.
|
||||
let (destination, origin) = self.core().blit_at(buffer, range.start)?;
|
||||
let mut regions = Vec::new();
|
||||
if head > 0 {
|
||||
regions.push(vk::BufferCopy {
|
||||
src_offset: from,
|
||||
dst_offset: buffer.at(range.start).1,
|
||||
dst_offset: origin,
|
||||
size: head,
|
||||
});
|
||||
}
|
||||
@@ -351,7 +353,7 @@ impl BlitCommandEncoder {
|
||||
let size = (range.end - at).min(chunk);
|
||||
regions.push(vk::BufferCopy {
|
||||
src_offset: from + head,
|
||||
dst_offset: buffer.at(at).1,
|
||||
dst_offset: origin + (at - range.start),
|
||||
size,
|
||||
});
|
||||
at += size;
|
||||
|
||||
@@ -722,8 +722,8 @@ impl RowsCopy {
|
||||
}
|
||||
|
||||
/// Whether a source row and a destination row share a byte, for a copy within one buffer:
|
||||
/// Vulkan's copy forbids it, where Metal moves the bytes as a copy through a temporary does
|
||||
/// (TOB probe 1).
|
||||
/// Vulkan's copy forbids it, where Metal moves the bytes as a copy through a temporary does (a
|
||||
/// Metal probe on the M3 Max and an M4).
|
||||
pub(super) fn meets(&self) -> bool {
|
||||
let mut src: Vec<Range<u64>> = self.rows.iter().map(|r| r.src..r.src + r.size).collect();
|
||||
let mut dst: Vec<Range<u64>> = self.rows.iter().map(|r| r.dst..r.dst + r.size).collect();
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! axis 0, or of no slices or levels, copies nothing while the encoder's other commands run, as
|
||||
//! plain Metal does (its validation stops each). A copy to or from a memoryless texture, and its
|
||||
//! mipmaps, are refused (`StorageMode`), as Metal's validation refuses them; the
|
||||
//! `optimize_contents_*` hints take one, as Metal's do (RT6 probes 6b and 6f).
|
||||
//! `optimize_contents_*` hints take one, as Metal's do (a Metal probe on an M4).
|
||||
//! - **Recording.** Each copy is one command of the encoder with what it reads and writes: a
|
||||
//! texture's uses name its image's levels and layers (every aspect), so the encoder's order and
|
||||
//! the commit's barriers cover views and their textures as one resource. A buffer layout
|
||||
@@ -69,6 +69,7 @@ use super::deferred::Deferred;
|
||||
use super::degradation::Degradation;
|
||||
use super::error::{internal, invalid, Error, Problem, RuntimeGap};
|
||||
use super::fresh_unwritten::FreshUnwritten;
|
||||
use super::image_plan::copies_between;
|
||||
use super::mipmap::record_blit;
|
||||
use super::mipmap_plan::{leaves_as_is, not_implemented, plan_mipmaps, MipmapPlan, MipmapRefusal};
|
||||
use super::nan_clear;
|
||||
@@ -83,6 +84,7 @@ use super::tracker::Access;
|
||||
use super::two_planes;
|
||||
use super::values::{Origin, Region, ResourceOptions, Size, StorageMode};
|
||||
use super::Buffer;
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::error::{Feature, Unsupported};
|
||||
use metal2vulkan::metal::format::{aspects, is_depth_stencil};
|
||||
@@ -276,7 +278,7 @@ fn plan_copy(
|
||||
} else {
|
||||
buffer.length()
|
||||
};
|
||||
let base = buffer.at(0).1;
|
||||
let base = buffer.start();
|
||||
if is_pvrtc(texture.pixel_format()) && layout.bytes_per_row == 0 {
|
||||
return plan_block_order_copy(record, region, unit, layout, buffer_length, base)
|
||||
.map_err(|problem| invalid(call, Problem::Copy(problem)));
|
||||
@@ -447,7 +449,7 @@ impl BlitCommandEncoder {
|
||||
destination_slice,
|
||||
)?;
|
||||
let region = multisampled_region(CALL, destination_texture, region)?;
|
||||
let (raw_buffer, base) = source_buffer.at(0);
|
||||
let (raw_buffer, base) = self.core().blit_at(source_buffer, 0)?;
|
||||
let aspect = multisampled_aspect(CALL, destination_texture, options)?;
|
||||
let planned = sample_interleave::InterleaveCopy::plan(
|
||||
self.core().command_buffer(),
|
||||
@@ -469,8 +471,8 @@ impl BlitCommandEncoder {
|
||||
unsafe { copy.record(device, raw) };
|
||||
})?;
|
||||
// A depth written as the single-sample path writes one announces as it does.
|
||||
destination_texture.degrade_depth_upload(CALL, aspect);
|
||||
destination_texture.degrade_depth_denormals(CALL, aspect, false);
|
||||
destination_texture.degrade_depth_upload(CALL, aspect, true, true);
|
||||
destination_texture.degrade_depth_denormals(CALL, aspect, false, true);
|
||||
copy.announce(self.core().device(), CALL, destination_texture);
|
||||
self.core().retain(copy);
|
||||
// Every sample of the region written, as the single-sample path's.
|
||||
@@ -519,8 +521,8 @@ impl BlitCommandEncoder {
|
||||
let plan = plan_copy(CALL, texture, ®ion, &unit, &layout, source_buffer, true)?;
|
||||
let written: Vec<ImageRegion> = plan.regions.iter().map(|r| r.image).collect();
|
||||
self.buffer_texture_copy(source_buffer, texture, plan, true)?;
|
||||
texture.degrade_depth_upload(CALL, unit.aspect);
|
||||
texture.degrade_depth_denormals(CALL, unit.aspect, false);
|
||||
texture.degrade_depth_upload(CALL, unit.aspect, true, true);
|
||||
texture.degrade_depth_denormals(CALL, unit.aspect, false, true);
|
||||
// Into a texture Metal keeps compressed: the texels its blit writes.
|
||||
if let Some(rule) = rule_of(texture) {
|
||||
self.compressed_image(texture, &written, &[rule])?;
|
||||
@@ -604,7 +606,7 @@ impl BlitCommandEncoder {
|
||||
}
|
||||
let region = region(CALL, source_origin, size, source_level, source_slice)?;
|
||||
let region = multisampled_region(CALL, source_texture, region)?;
|
||||
let (raw_buffer, base) = destination_buffer.at(0);
|
||||
let (raw_buffer, base) = self.core().blit_at(destination_buffer, 0)?;
|
||||
let planned = sample_interleave::InterleaveCopy::plan(
|
||||
self.core().command_buffer(),
|
||||
raw_buffer,
|
||||
@@ -773,8 +775,9 @@ impl BlitCommandEncoder {
|
||||
let fresh_reads = FreshUnwritten::reads(self.core().device(), texture, &boxes)?;
|
||||
// The plan's offsets are the `VkBuffer`'s (`plan_buffer_copy`'s base), its regions in the
|
||||
// texture's texels, which a 2-bit PVRTC texture's carrier halves across
|
||||
// (`pvrtc::image_buffer_region`).
|
||||
let ((raw_buffer, _), image) = (buffer.at(0), texture.raw_image()?);
|
||||
// (`pvrtc::image_buffer_region`). Read as a blit's (`host_residency.rs`).
|
||||
let (raw_buffer, _) = self.core().blit_at(buffer, 0)?;
|
||||
let image = texture.raw_image()?;
|
||||
let image_plan = texture.image_plan()?;
|
||||
let regions: Vec<vk::BufferImageCopy> = plan
|
||||
.regions
|
||||
@@ -846,7 +849,7 @@ impl BlitCommandEncoder {
|
||||
};
|
||||
staging.rows.iter().map(|r| buffer_copy(&back(r))).collect()
|
||||
};
|
||||
let move_rows = |device: &ash::Device, raw: vk::CommandBuffer| {
|
||||
let move_rows = |device: &Vk, raw: vk::CommandBuffer| {
|
||||
let (src, dst) = if into_texture {
|
||||
(raw_buffer, through)
|
||||
} else {
|
||||
@@ -855,7 +858,7 @@ impl BlitCommandEncoder {
|
||||
// SAFETY: as below; the rows lie in both buffers (checked by the plan).
|
||||
unsafe { device.cmd_copy_buffer(raw, src, dst, &rows) };
|
||||
};
|
||||
let copy_image = |device: &ash::Device, raw: vk::CommandBuffer| {
|
||||
let copy_image = |device: &Vk, raw: vk::CommandBuffer| {
|
||||
// SAFETY: the encoder's command buffer is recording; the scratch buffer and
|
||||
// the image are live and retained until it completes, the image is in the
|
||||
// `GENERAL` layout, and the region lies in both.
|
||||
@@ -1289,6 +1292,10 @@ impl BlitCommandEncoder {
|
||||
if !regions.is_empty() {
|
||||
let regions: Vec<vk::ImageCopy> = regions.iter().map(image_copy).collect();
|
||||
direct.push((from.image, to.image, regions));
|
||||
// A depth that may hold a negative value or a NaN, copied as it is.
|
||||
if to.aspect == ImageAspectFlags::DEPTH && source.may_hold_signed_depth() {
|
||||
destination.degrade_signed_depth(call, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => staged.push(*to),
|
||||
@@ -1339,8 +1346,8 @@ impl BlitCommandEncoder {
|
||||
)?;
|
||||
uses.extend(copy.uses.iter().cloned());
|
||||
stages |= copy.stages;
|
||||
destination.degrade_depth_upload(call, to.aspect);
|
||||
destination.degrade_depth_denormals(call, to.aspect, false);
|
||||
destination.degrade_depth_upload(call, to.aspect, true, true);
|
||||
destination.degrade_depth_denormals(call, to.aspect, false, true);
|
||||
planned.push(copy);
|
||||
}
|
||||
self.command_in_reading(stages, &uses, &fresh_reads, |device, raw| {
|
||||
@@ -1422,8 +1429,9 @@ impl BlitCommandEncoder {
|
||||
})?;
|
||||
uses.push(reads(&scratch, 0..length));
|
||||
for (to, _) in &staging.into {
|
||||
destination.degrade_depth_upload(call, to.aspect);
|
||||
destination.degrade_depth_denormals(call, to.aspect, false);
|
||||
let signed = source.may_hold_signed_depth();
|
||||
destination.degrade_depth_upload(call, to.aspect, signed, true);
|
||||
destination.degrade_depth_denormals(call, to.aspect, false, true);
|
||||
}
|
||||
Some((scratch, through))
|
||||
}
|
||||
@@ -1552,8 +1560,8 @@ impl BlitCommandEncoder {
|
||||
)
|
||||
.map_err(copy_problem)?;
|
||||
if into_texture {
|
||||
texture.degrade_depth_upload(call, image_unit.aspect);
|
||||
texture.degrade_depth_denormals(call, image_unit.aspect, false);
|
||||
texture.degrade_depth_upload(call, image_unit.aspect, true, true);
|
||||
texture.degrade_depth_denormals(call, image_unit.aspect, false, true);
|
||||
}
|
||||
self.buffer_texture_copy(buffer, texture, plan, into_texture)?;
|
||||
}
|
||||
@@ -1656,11 +1664,14 @@ impl BlitCommandEncoder {
|
||||
/// Every colour format Metal filters but `B5G6R5Unorm` and `BGR5A1Unorm`, extended range
|
||||
/// included, is computed as Metal's filter computes it, on every device with `shaderInt64`
|
||||
/// and without a blit (`mipmap_filter.rs`): a scratch buffer of the levels, one compute
|
||||
/// dispatch per level, and copies in and out. The first computed level, and every level of a 3D
|
||||
/// texture, is an Apple M3 Max's answer; below the first level of a 2D chain, an array or a
|
||||
/// cube an Apple M4's stands in, announced once per device (`mipmaps-as-apple-m4`), as for the
|
||||
/// formats an M3 Max converts through a half (`ABGR4Unorm`, `A1BGR5Unorm`, extended range) and,
|
||||
/// in 3D, those summed as half floats.
|
||||
/// dispatch per level, and copies in and out, by the rule of the device's Metal level
|
||||
/// ([`MetalLevel::mipmap_rule`](crate::MetalLevel::mipmap_rule)). Under macOS 27.0.1 every
|
||||
/// level is an Apple M3 Max's filter of the level above. Under macOS 26.7 the first computed
|
||||
/// level, and every level of a 3D texture, is an Apple M3 Max's answer; below the first level
|
||||
/// of a 2D chain, an array or a cube whose M3 Max passes are not known an Apple M4's stands in,
|
||||
/// announced once per device (`mipmaps-as-apple-m4`), as for the formats an M3 Max converts
|
||||
/// through a half (`ABGR4Unorm`, `A1BGR5Unorm`, extended range) and, in 3D, those summed as
|
||||
/// half floats.
|
||||
///
|
||||
/// Elsewhere (those two formats, a device without `shaderInt64`, limits that do not fit the
|
||||
/// chain) Metal's answers differ between Apple GPUs, so the runtime checks this device's
|
||||
@@ -1692,6 +1703,17 @@ impl BlitCommandEncoder {
|
||||
/// [`Device::mipmap_generation`]: super::Device::mipmap_generation
|
||||
pub fn generate_mipmaps(&mut self, texture: &Texture) -> Result<(), Error> {
|
||||
self.log(|_| BlitCall::GenerateMipmaps(texture.clone()));
|
||||
// A view that reads its image in the image's own format generates them as a texture of
|
||||
// that format over the same levels: the same bits, filtered alike
|
||||
// (`bind::mipmap_filter`'s layouts pair the formats `metal::format::swizzle_over` pairs).
|
||||
match texture.bound_twin() {
|
||||
Some(twin) => self.mipmaps(&twin),
|
||||
None => self.mipmaps(texture),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`generate_mipmaps`](Self::generate_mipmaps) of `texture`, logged.
|
||||
fn mipmaps(&mut self, texture: &Texture) -> Result<(), Error> {
|
||||
const CALL: &str = "generate_mipmaps";
|
||||
// One level, of any format, or a depth or stencil texture: Metal's plain call leaves the
|
||||
// texture as it is, over a buffer or not, and its API validation asserts. Every texture
|
||||
@@ -1907,10 +1929,15 @@ struct Held {
|
||||
|
||||
impl Held {
|
||||
/// Whether Vulkan copies this image's texels into `to`'s: both in colour (formats of one
|
||||
/// size, checked by the plan), or in the same depth or stencil aspects of one format.
|
||||
/// size, checked by the plan, both alpha formats or neither, `image_plan::copies_between`:
|
||||
/// an `A8Unorm` view's image is its `R8Unorm` texture's), or in the same depth or stencil
|
||||
/// aspects of one format.
|
||||
fn copies_into(&self, to: &Held) -> bool {
|
||||
self.aspect == to.aspect
|
||||
&& (self.aspect == ImageAspectFlags::COLOR || self.format == to.format)
|
||||
&& match self.aspect == ImageAspectFlags::COLOR {
|
||||
true => copies_between(self.format, to.format),
|
||||
false => self.format == to.format,
|
||||
}
|
||||
}
|
||||
|
||||
/// `copy` from this image to `to`, each in its aspect.
|
||||
|
||||
@@ -31,10 +31,14 @@ use super::generated_commands::PREPROCESS_BUFFER;
|
||||
use super::heap::{Heap, HeapType};
|
||||
use super::host_aliases::Alias;
|
||||
use super::host_memory::{KeepAlive, Release};
|
||||
use super::memory::{MemoryClass, Placement, BLOCK_BYTES};
|
||||
#[cfg(unix)]
|
||||
use super::host_residency::{Again, Imported, Residency};
|
||||
use super::memory::{Mapped, MemoryClass, Placement, BLOCK_BYTES};
|
||||
use super::program_objects::ProgramObject;
|
||||
use super::rebind::Unexact;
|
||||
use super::resource::{Identity, ObjectId, ResourceKey};
|
||||
use super::texture::first_move::Filled;
|
||||
use super::texture::shared_alias::SharedImages;
|
||||
use super::texture::AliasWatch;
|
||||
use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode};
|
||||
use super::Device;
|
||||
@@ -145,6 +149,9 @@ pub(super) struct HostCell {
|
||||
/// and in it), which a detach makes present stand-ins (`detach.rs`), and the textures being
|
||||
/// made over them, which a detach refuses while one is.
|
||||
textures: Mutex<TexturesOver>,
|
||||
/// The buffer's Metal address was handed out (`Buffer::gpu_address`): its import is kept
|
||||
/// imported for good (`host_residency.rs`), and the call need not look again.
|
||||
exposed: AtomicBool,
|
||||
}
|
||||
|
||||
/// The textures over a buffer's host pages ([`HostCell`]): their images, which a detach makes
|
||||
@@ -279,7 +286,7 @@ impl Detached {
|
||||
let Bytes::Own(own) = &stand_in.0.bytes else {
|
||||
return Err(internal("a detached buffer's stand-in placed in a heap"));
|
||||
};
|
||||
let old = &from.import.pages;
|
||||
let old = from.import.shape;
|
||||
let pages = own.with(|pages| {
|
||||
let placement = &pages.memory.placement;
|
||||
Pages {
|
||||
@@ -327,10 +334,10 @@ impl HostCell {
|
||||
pub(super) fn host_range(&self) -> Option<std::ops::Range<usize>> {
|
||||
match self.lying() {
|
||||
Lying::In(pages) => {
|
||||
let pages = &pages.import.pages;
|
||||
let mapped = pages.memory.placement.mapped?;
|
||||
let start = (mapped.as_ptr() as usize).checked_add(pages.offset as usize)?;
|
||||
Some(start..start.checked_add(pages.reach as usize)?)
|
||||
let shape = pages.import.shape;
|
||||
let mapped = shape.mapped?;
|
||||
let start = (mapped.as_ptr() as usize).checked_add(shape.offset as usize)?;
|
||||
Some(start..start.checked_add(shape.reach as usize)?)
|
||||
}
|
||||
Lying::Detached(_) => None,
|
||||
}
|
||||
@@ -404,7 +411,31 @@ impl HostCell {
|
||||
#[derive(Clone)]
|
||||
pub(super) enum PagesHold {
|
||||
Fixed { _pages: Arc<FixedPages> },
|
||||
Host { _pages: Arc<HostPages> },
|
||||
Host { _pages: ListedPages },
|
||||
}
|
||||
|
||||
/// A live buffers' table's hold on host pages (`PagesHold::Host`), counted
|
||||
/// (`HostPages::listed`): one left as the buffer is released is a table a command buffer that may
|
||||
/// reach the pages unnamed holds, past Metal's release (`HostPages::announce_listed`).
|
||||
pub(super) struct ListedPages(Arc<HostPages>);
|
||||
|
||||
impl ListedPages {
|
||||
fn new(pages: Arc<HostPages>) -> ListedPages {
|
||||
pages.listed.fetch_add(1, Ordering::AcqRel);
|
||||
ListedPages(pages)
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for ListedPages {
|
||||
fn clone(&self) -> ListedPages {
|
||||
ListedPages::new(Arc::clone(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ListedPages {
|
||||
fn drop(&mut self) {
|
||||
self.0.listed.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
/// A hold on the memory a buffer's bytes lie in now, and on nothing else of the buffer
|
||||
@@ -460,13 +491,17 @@ impl Drop for FixedPages {
|
||||
/// The import may outlive them: a texture over the pages whose image a command buffer submitted
|
||||
/// before the texture's release may still read through its resource ID holds it (`heap_sets.rs`).
|
||||
/// Vulkan requires the pages to stay mapped while imported, so the deallocator runs as they go only
|
||||
/// where the caller's keep-alive keeps the pages mapped (the import drops it once freed), or
|
||||
/// where the caller's keep-alive keeps the pages mapped (the import keeps it until freed), or
|
||||
/// another buffer lies in the import, whose contract keeps them mapped; else it runs once the
|
||||
/// import is freed, at once where nothing else holds it, and announced where something does
|
||||
/// (`host-deallocator-delayed`).
|
||||
/// (`host-deallocator-delayed`). A keep-alive goes as they go where the import's pages stay mapped
|
||||
/// without it: another buffer lies in the import, or the import keeps another's keep-alive already
|
||||
/// (every buffer in it was made over the same bytes, `host_aliases.rs`). So an import keeps one
|
||||
/// keep-alive at most, however many buffers come and go over its bytes while it lives.
|
||||
pub(super) struct HostPages {
|
||||
/// The images and views over them a rebind replaced (a no-copy heap's textures', texel
|
||||
/// buffer views), which commands recorded before it may use: destroyed with them, first.
|
||||
/// The images and views over them a rebind or a detach replaced (a no-copy heap's textures',
|
||||
/// texel buffer views), which commands recorded before it may use: destroyed with them,
|
||||
/// first.
|
||||
parked: Mutex<Vec<Box<dyn Any + Send + Sync>>>,
|
||||
/// Their `VkBuffer` and its memory, which no-copy buffers made over the same bytes share
|
||||
/// (`host_aliases.rs`).
|
||||
@@ -474,16 +509,22 @@ pub(super) struct HostPages {
|
||||
/// Their release to the caller's deallocator and keep-alive, set once they are the buffer's
|
||||
/// (a refused rebind drops its pages without it, and the deallocator unrun).
|
||||
release: OnceLock<Release>,
|
||||
/// The live buffers' tables' holds on them ([`ListedPages`]).
|
||||
listed: AtomicUsize,
|
||||
}
|
||||
|
||||
impl HostPages {
|
||||
/// New pages lying in `import`, with no release yet.
|
||||
fn new(import: Arc<HostImport>) -> HostPages {
|
||||
import.lying.fetch_add(1, Ordering::AcqRel);
|
||||
if import.lying.fetch_add(1, Ordering::AcqRel) > 0 {
|
||||
// Another buffer lies in it: imported for good (`host_residency.rs`).
|
||||
import.expose();
|
||||
}
|
||||
HostPages {
|
||||
parked: Mutex::new(Vec::new()),
|
||||
import,
|
||||
release: OnceLock::new(),
|
||||
listed: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -492,40 +533,75 @@ impl HostPages {
|
||||
lock(&self.parked).push(Box::new(objects));
|
||||
}
|
||||
|
||||
/// Their memory and where the bytes start in it (a heap's textures bind images there).
|
||||
/// Their memory and where the bytes start in it (a heap's textures bind images there): a
|
||||
/// read that keeps the import imported for good (`host_residency.rs`).
|
||||
pub(super) fn memory(&self) -> (vk::DeviceMemory, u64) {
|
||||
let pages = &self.import.pages;
|
||||
let pages = self.import.pages();
|
||||
let placement = &pages.memory.placement;
|
||||
(placement.memory, placement.offset + pages.offset)
|
||||
}
|
||||
|
||||
/// Where the bytes start in their first imported page.
|
||||
pub(super) fn offset(&self) -> u64 {
|
||||
self.import.pages.offset
|
||||
self.import.shape.offset
|
||||
}
|
||||
|
||||
/// The host address of the byte `from_base` bytes past their bytes' start
|
||||
/// ([`HostPages::memory`]): where an image bound there lies for the host. `None` where the
|
||||
/// import is not mapped.
|
||||
pub(super) fn host_at(&self, from_base: u64) -> Option<Mapped> {
|
||||
let shape = &self.import.shape;
|
||||
Some(shape.mapped?.add(shape.offset + from_base))
|
||||
}
|
||||
|
||||
/// The index of their memory's type.
|
||||
pub(super) fn type_index(&self) -> u32 {
|
||||
self.import.pages.memory.placement.type_index()
|
||||
self.import.shape.type_index
|
||||
}
|
||||
|
||||
/// Whether they were imported as dma-bufs (`dma_buf.rs`), not by their pointer.
|
||||
pub(super) fn over_dma_buf(&self) -> bool {
|
||||
self.import.pages.memory.placement.over_dma_buf()
|
||||
self.import.shape.over_dma_buf
|
||||
}
|
||||
|
||||
/// Where they lie as dma-bufs (`dma_buf.rs`): the imports, with the caller's source; the host
|
||||
/// address where their bytes start (from which an image over them reckons its texels'); and
|
||||
/// the imports' memory type. `None` for pages imported by their pointer.
|
||||
/// the imports' memory type. `None` for pages imported by their pointer. A read that keeps
|
||||
/// the import imported for good (`host_residency.rs`).
|
||||
#[cfg(unix)]
|
||||
pub(super) fn dma_buf(&self) -> Option<(&Arc<crate::dma_buf::DmaBufPages>, u64, u32)> {
|
||||
let pages = &self.import.pages;
|
||||
pub(super) fn dma_buf(&self) -> Option<(Arc<crate::dma_buf::DmaBufPages>, u64, u32)> {
|
||||
let pages = self.import.pages();
|
||||
let placement = &pages.memory.placement;
|
||||
let imports = placement.dma_buf_pages()?;
|
||||
let imports = Arc::clone(placement.dma_buf_pages()?);
|
||||
let start = (placement.mapped?.as_ptr() as u64).checked_add(pages.offset)?;
|
||||
Some((imports, start, placement.type_index()))
|
||||
}
|
||||
|
||||
/// As the buffer that lies in them is released (`BufferShared`'s drop, a no-copy heap's own
|
||||
/// buffer's included), its listing let go of: a live buffers' table that still lists them is a
|
||||
/// command buffer's, one that may reach them unnamed (its first submission's, a host step's,
|
||||
/// or one a root table recorded before its first submission holds, `live_buffers.rs`), and
|
||||
/// the pages stay, their deallocator waiting, until it lets go of it, where Metal's runs at
|
||||
/// the release. Announced once per device (`Degradation::HostDeallocatorDelayed`).
|
||||
fn announce_listed(&self, device: &Device) {
|
||||
let Some(release) = self.release.get() else {
|
||||
return;
|
||||
};
|
||||
if !release.deallocates() || self.listed.load(Ordering::Acquire) == 0 {
|
||||
return;
|
||||
}
|
||||
device.shared().counts.host_deallocator_delayed();
|
||||
let length = release.length();
|
||||
device.degrade_once(Degradation::HostDeallocatorDelayed, || {
|
||||
(
|
||||
format!("a no-copy buffer of {length} bytes"),
|
||||
"a command buffer that may reach its pages unnamed (a live buffers' table it \
|
||||
holds lists them) holds them as it is released"
|
||||
.to_owned(),
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
/// Release the pages to `release` when they go.
|
||||
pub(super) fn release_to(&self, release: Release) {
|
||||
// A refused set leaves the deallocator unrun, as a refused call does: never reached,
|
||||
@@ -543,17 +619,113 @@ impl HostPages {
|
||||
/// memory imported from them. Every no-copy buffer made over the same bytes as a live one, of
|
||||
/// its memory class, lies in its import (`host_aliases.rs`): one resource to the driver, as one
|
||||
/// IOSurface's memory is to Metal. The last hold on it destroys the `VkBuffer` and frees the
|
||||
/// import.
|
||||
/// import, but for a releasable one's, which the command buffers that read them hold too
|
||||
/// (`host_residency.rs`).
|
||||
pub(super) struct HostImport {
|
||||
device: Device,
|
||||
pages: Pages,
|
||||
/// Where the bytes lie in its `VkBuffer` and memory: the same in each import of them again.
|
||||
shape: Shape,
|
||||
/// Its `VkBuffer` and memory.
|
||||
objects: Objects,
|
||||
/// The [`HostPages`] lying in it.
|
||||
lying: AtomicUsize,
|
||||
/// The keep-alives of pages that went while it lived, dropped once it is freed.
|
||||
kept: Mutex<Vec<KeepAlive>>,
|
||||
/// The keep-alive of the pages that went while it lived with none other lying in it, dropped
|
||||
/// once it is freed: it keeps the bytes mapped for every buffer made over them, since all were
|
||||
/// made over the same bytes, so a later one's keep-alive is dropped as its pages go
|
||||
/// ([`HostPages`]).
|
||||
kept: Mutex<Option<ProgramObject<KeepAlive>>>,
|
||||
/// The releases of pages that went while it lived with no keep-alive: their deallocators
|
||||
/// run once it is freed.
|
||||
after_free: Mutex<Vec<Release>>,
|
||||
/// The `VkImage`s textures of one image over the same bytes of it share
|
||||
/// (`texture/shared_alias.rs`), held while it lives, and dropped before its memory is freed.
|
||||
shared: SharedImages,
|
||||
}
|
||||
|
||||
/// Where a host import's bytes lie in its `VkBuffer` and memory, which reading needs no
|
||||
/// `VkBuffer`: the same in each import of them again (`host_residency.rs`).
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Shape {
|
||||
/// Where the bytes start in the first imported page.
|
||||
pub(super) offset: u64,
|
||||
/// Where the buffer's byte 0 lies in its `VkBuffer`.
|
||||
pub(super) base: u64,
|
||||
/// The bytes from byte 0 a copy reads ([`Buffer::copy_reach`]).
|
||||
pub(super) reach: u64,
|
||||
/// The host address of the first imported byte.
|
||||
pub(super) mapped: Option<Mapped>,
|
||||
/// The index of the memory's type.
|
||||
pub(super) type_index: u32,
|
||||
/// The pages were imported as dma-bufs (`dma_buf.rs`), not by their pointer.
|
||||
pub(super) over_dma_buf: bool,
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
/// The shape of `pages`.
|
||||
pub(super) fn of(pages: &Pages) -> Shape {
|
||||
let placement = &pages.memory.placement;
|
||||
Shape {
|
||||
offset: pages.offset,
|
||||
base: pages.base,
|
||||
reach: pages.reach,
|
||||
mapped: placement.mapped,
|
||||
type_index: placement.type_index(),
|
||||
over_dma_buf: placement.over_dma_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `other` lays the bytes as this does: an import again of them as their first.
|
||||
pub(super) fn same(&self, other: &Shape) -> bool {
|
||||
let at = |shape: &Shape| shape.mapped.map(Mapped::as_ptr);
|
||||
(
|
||||
self.offset,
|
||||
self.base,
|
||||
self.reach,
|
||||
self.type_index,
|
||||
self.over_dma_buf,
|
||||
) == (
|
||||
other.offset,
|
||||
other.base,
|
||||
other.reach,
|
||||
other.type_index,
|
||||
other.over_dma_buf,
|
||||
) && at(self) == at(other)
|
||||
}
|
||||
}
|
||||
|
||||
/// A host import's `VkBuffer` and memory.
|
||||
enum Objects {
|
||||
/// Imported until the import goes.
|
||||
Fixed(Pages),
|
||||
/// Released while idle, and imported again at the next read (`host_residency.rs`).
|
||||
#[cfg(unix)]
|
||||
Releasable(Residency),
|
||||
}
|
||||
|
||||
/// A host import's `VkBuffer` and memory as one read takes them: borrowed from an import that
|
||||
/// keeps them, or held, from one that may release them, for as long as the read lasts.
|
||||
pub(super) enum ImportPages<'a> {
|
||||
Fixed(&'a Pages),
|
||||
#[cfg(unix)]
|
||||
Held(Arc<Imported>),
|
||||
/// The device's stand-in, which a read of a released import takes where the device cannot
|
||||
/// import it again ([`HostImport::pages`]).
|
||||
#[cfg(unix)]
|
||||
StandIn(Arc<FixedPages>),
|
||||
}
|
||||
|
||||
impl std::ops::Deref for ImportPages<'_> {
|
||||
type Target = Pages;
|
||||
|
||||
fn deref(&self) -> &Pages {
|
||||
match self {
|
||||
ImportPages::Fixed(pages) => pages,
|
||||
#[cfg(unix)]
|
||||
ImportPages::Held(imported) => &imported.pages,
|
||||
#[cfg(unix)]
|
||||
ImportPages::StandIn(stand_in) => &stand_in.pages,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HostImport {
|
||||
@@ -561,12 +733,105 @@ impl HostImport {
|
||||
fn new(device: &Device, pages: Pages) -> HostImport {
|
||||
HostImport {
|
||||
device: device.clone(),
|
||||
pages,
|
||||
shape: Shape::of(&pages),
|
||||
objects: Objects::Fixed(pages),
|
||||
lying: AtomicUsize::new(0),
|
||||
kept: Mutex::new(Vec::new()),
|
||||
kept: Mutex::new(None),
|
||||
after_free: Mutex::new(Vec::new()),
|
||||
shared: SharedImages::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The import of `pages`, no pages lying in it yet, which the device releases while idle and
|
||||
/// `again` imports again (`host_residency.rs`).
|
||||
#[cfg(unix)]
|
||||
fn releasable(
|
||||
device: &Device,
|
||||
pages: Pages,
|
||||
again: Again,
|
||||
stand_in: Arc<FixedPages>,
|
||||
) -> HostImport {
|
||||
HostImport {
|
||||
device: device.clone(),
|
||||
shape: Shape::of(&pages),
|
||||
objects: Objects::Releasable(Residency::new(device, pages, again, stand_in)),
|
||||
lying: AtomicUsize::new(0),
|
||||
kept: Mutex::new(None),
|
||||
after_free: Mutex::new(Vec::new()),
|
||||
shared: SharedImages::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Its residency, where the device may release it while idle.
|
||||
#[cfg(unix)]
|
||||
pub(super) fn residency(&self) -> Option<&Residency> {
|
||||
match &self.objects {
|
||||
Objects::Fixed(_) => None,
|
||||
Objects::Releasable(residency) => Some(residency),
|
||||
}
|
||||
}
|
||||
|
||||
/// Its `VkBuffer` and memory for a read other than a blit's, which keeps a releasable import
|
||||
/// imported for good from then on (`host_residency.rs`). Released, it is imported again
|
||||
/// first; where the device cannot, the device is lost (its work no longer runs) and the read
|
||||
/// takes the device's stand-in.
|
||||
pub(super) fn pages(&self) -> ImportPages<'_> {
|
||||
match &self.objects {
|
||||
Objects::Fixed(pages) => ImportPages::Fixed(pages),
|
||||
#[cfg(unix)]
|
||||
Objects::Releasable(residency) => match residency.exposed() {
|
||||
Some(held) => ImportPages::Held(held),
|
||||
None => {
|
||||
// No work that read it runs on a lost device.
|
||||
self.device.mark_lost();
|
||||
self.device.shared().counts.host_import_lost();
|
||||
ImportPages::StandIn(residency.stand_in())
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Its `VkBuffer` and memory for a blit's command (`Buffer::blit_at`), imported again where
|
||||
/// released, with what the command buffer holds of them until it completed: nothing of an
|
||||
/// import that keeps them. Refused where the device cannot import them again.
|
||||
pub(super) fn blit_pages(
|
||||
&self,
|
||||
) -> Result<(ImportPages<'_>, Option<Arc<dyn Any + Send + Sync>>), Error> {
|
||||
match &self.objects {
|
||||
Objects::Fixed(pages) => Ok((ImportPages::Fixed(pages), None)),
|
||||
#[cfg(unix)]
|
||||
Objects::Releasable(residency) => {
|
||||
let held = residency.for_blit()?;
|
||||
let hold: Arc<dyn Any + Send + Sync> = Arc::clone(&held) as _;
|
||||
Ok((ImportPages::Held(held), Some(hold)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Its `VkBuffer` and memory for a live-table listing (`live_buffers.rs`), which reads them
|
||||
/// without exposing them: `None` while a releasable import is released.
|
||||
fn listing(&self) -> Option<ImportPages<'_>> {
|
||||
match &self.objects {
|
||||
Objects::Fixed(pages) => Some(ImportPages::Fixed(pages)),
|
||||
#[cfg(unix)]
|
||||
Objects::Releasable(residency) => residency.listing().map(ImportPages::Held),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep it imported for good from now on (`host_residency.rs`): whether it was ever
|
||||
/// released, so a range of it noted before may be stale.
|
||||
pub(super) fn expose(&self) -> bool {
|
||||
match &self.objects {
|
||||
Objects::Fixed(_) => false,
|
||||
#[cfg(unix)]
|
||||
Objects::Releasable(residency) => residency.expose(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared images of textures over its bytes (`texture/shared_alias.rs`).
|
||||
pub(super) fn shared_images(&self) -> &SharedImages {
|
||||
&self.shared
|
||||
}
|
||||
}
|
||||
|
||||
impl Device {
|
||||
@@ -574,7 +839,7 @@ impl Device {
|
||||
/// device's message sink (`Verbose`, id name `metal2vulkan-host-import-freed`) for a host
|
||||
/// import of `bytes` freed: MoltenVK removes its buffer from the set and commits the set at
|
||||
/// once, with the submissions in flight on the device's queues it names. Elsewhere nothing.
|
||||
fn note_import_freed(&self, bytes: u64) {
|
||||
pub(super) fn note_import_freed(&self, bytes: u64) {
|
||||
let facts = super::device::argument_buffers::Facts::of(&self.properties().description);
|
||||
if !facts.keeps_residency_set() {
|
||||
return;
|
||||
@@ -614,32 +879,92 @@ impl Drop for HostImport {
|
||||
for release in lock(&self.after_free).iter() {
|
||||
release.keep();
|
||||
}
|
||||
for kept in lock(&self.kept).drain(..) {
|
||||
if let Some(kept) = lock(&self.kept).take() {
|
||||
std::mem::forget(kept);
|
||||
}
|
||||
return;
|
||||
};
|
||||
// Its shared images go before the memory they are bound in is freed: nothing else holds
|
||||
// one, as every holder of one holds the import.
|
||||
self.shared.clear();
|
||||
let shared = self.device.shared();
|
||||
// A submission that used the pages waited for their sparse binding: waited for here
|
||||
// where none did.
|
||||
self.pages.memory.placement.settle();
|
||||
// SAFETY: no pending command buffer uses the pages: one whose commands used them holds
|
||||
// them until it completed (`rebind.rs`), one that may read a texture's image over them
|
||||
// holds the image, which holds the import (`heap_sets.rs`), and every buffer over them
|
||||
// let go of them; their binding completed.
|
||||
unsafe { release::object(shared.vk(), self.pages.raw) };
|
||||
lock(&shared.memory).free(shared.vk(), &self.pages.memory.placement);
|
||||
drop(busy);
|
||||
self.device
|
||||
.note_import_freed(self.pages.memory.placement.size());
|
||||
// Freed: the keep-alives go, and the deallocators that waited for the free run, each
|
||||
// panic caught.
|
||||
let kept: Vec<KeepAlive> = lock(&self.kept).drain(..).collect();
|
||||
for keep_alive in kept {
|
||||
exit_guard::program(move || drop(keep_alive));
|
||||
// Once freed, the keep-alive goes, and the deallocators that waited for the free run.
|
||||
let kept = lock(&self.kept).take();
|
||||
if kept.is_some() {
|
||||
shared.counts.host_keep_alive_freed();
|
||||
}
|
||||
let after_free: Vec<Release> = lock(&self.after_free).drain(..).collect();
|
||||
for release in &after_free {
|
||||
let releases: Vec<Release> = lock(&self.after_free).drain(..).collect();
|
||||
let delayed = releases.iter().find(|release| release.deallocates());
|
||||
let length = delayed.map(Release::length);
|
||||
let after = AfterFree { kept, releases };
|
||||
let freed = match &self.objects {
|
||||
// SAFETY: no pending command buffer uses the pages: one whose commands used them
|
||||
// holds them until it completed (`rebind.rs`), one that may read a texture's image
|
||||
// over them holds the image, which holds the import (`heap_sets.rs`), and every
|
||||
// buffer over them let go of them.
|
||||
Objects::Fixed(pages) => unsafe {
|
||||
pages.release_import(&self.device, Some(Box::new(after)))
|
||||
},
|
||||
// Its objects go now, or with the last command buffer that read them, which
|
||||
// completes before the buffers over it let go (each holds its buffer too).
|
||||
#[cfg(unix)]
|
||||
Objects::Releasable(residency) => {
|
||||
residency.let_go();
|
||||
Some(Box::new(after) as Box<dyn Send>)
|
||||
}
|
||||
};
|
||||
match (freed, length) {
|
||||
// Freed now: what waited goes here.
|
||||
(Some(after), _) => drop(after),
|
||||
// Its memory waits for the batches in flight (`freed_memory.rs`), and a deallocator
|
||||
// with it, past Metal's release.
|
||||
(None, Some(length)) => {
|
||||
shared.counts.host_deallocator_delayed();
|
||||
self.device
|
||||
.degrade_once(Degradation::HostDeallocatorDelayed, || {
|
||||
(
|
||||
format!("a no-copy buffer of {length} bytes"),
|
||||
"its pages' import, freed, waits for the batches submitted before \
|
||||
its release: the device's driver fails pending work whose \
|
||||
pipelines read device addresses where such memory is freed, and \
|
||||
the caller gave no keep-alive"
|
||||
.to_owned(),
|
||||
)
|
||||
});
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What goes once a host import's memory is freed: the keep-alive of the pages that went while it
|
||||
/// lived, and the deallocators that waited for the free, each panic caught. It waits with the
|
||||
/// memory where that waits for the batches in flight (`freed_memory.rs`).
|
||||
struct AfterFree {
|
||||
kept: Option<ProgramObject<KeepAlive>>,
|
||||
releases: Vec<Release>,
|
||||
}
|
||||
|
||||
impl Drop for AfterFree {
|
||||
fn drop(&mut self) {
|
||||
let kept = self.kept.take();
|
||||
let Some(busy) = exit_guard::enter() else {
|
||||
// The process is exiting: the pages stay imported to its end (`exit_guard`), so no
|
||||
// deallocator runs and no keep-alive goes.
|
||||
for release in &self.releases {
|
||||
release.keep();
|
||||
}
|
||||
if let Some(kept) = kept {
|
||||
std::mem::forget(kept);
|
||||
}
|
||||
return;
|
||||
};
|
||||
drop(busy);
|
||||
if let Some(keep_alive) = kept {
|
||||
exit_guard::program_release(move || drop(keep_alive));
|
||||
}
|
||||
for release in &self.releases {
|
||||
release.run();
|
||||
}
|
||||
}
|
||||
@@ -647,7 +972,7 @@ impl Drop for HostImport {
|
||||
|
||||
impl Drop for HostPages {
|
||||
fn drop(&mut self) {
|
||||
// The images and views a rebind parked go first: they may hold the import.
|
||||
// The images and views a rebind or a detach parked go first: they may hold the import.
|
||||
lock(&self.parked).clear();
|
||||
let others = self.import.lying.fetch_sub(1, Ordering::AcqRel) > 1;
|
||||
let Some(release) = self.release.take() else {
|
||||
@@ -663,10 +988,28 @@ impl Drop for HostPages {
|
||||
let import = &self.import;
|
||||
match release.keep_alive() {
|
||||
// The caller's keep-alive keeps the pages mapped until the import is freed: the
|
||||
// deallocator runs now, at Metal's moment.
|
||||
// deallocator runs now, at Metal's moment. Where another buffer lies in the import,
|
||||
// or the import keeps another's keep-alive, that keeps the same bytes mapped until it
|
||||
// is freed: this one goes now too, after the deallocator, which may read the bytes.
|
||||
Some(keep_alive) => {
|
||||
lock(&import.kept).push(keep_alive);
|
||||
let counts = &import.device.shared().counts;
|
||||
let covered = {
|
||||
let mut kept = lock(&import.kept);
|
||||
match others || kept.is_some() {
|
||||
true => Some(keep_alive),
|
||||
false => {
|
||||
// Counted before the free can take it.
|
||||
counts.host_keep_alive_kept();
|
||||
*kept = Some(keep_alive);
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
release.run();
|
||||
if let Some(keep_alive) = covered {
|
||||
counts.host_keep_alive_covered();
|
||||
exit_guard::program_release(move || drop(keep_alive));
|
||||
}
|
||||
}
|
||||
// Another buffer lies in the import, whose contract keeps the pages mapped: the
|
||||
// deallocator runs now, as with an import of its own (`host_aliases.rs`).
|
||||
@@ -696,6 +1039,38 @@ impl Drop for HostPages {
|
||||
}
|
||||
}
|
||||
|
||||
impl Pages {
|
||||
/// Destroy the `VkBuffer` of a host import's pages and free their memory, on `device`, once
|
||||
/// their sparse binding completed, and note it (`Device::note_import_freed`): an import's
|
||||
/// last hold lets go. Left to the process's end while it exits. `after` goes once the memory
|
||||
/// is freed: given back for the caller to let go of, unless it waits with the memory for the
|
||||
/// batches in flight (`freed_memory.rs`).
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No pending command buffer uses the pages, and nothing else frees them.
|
||||
pub(super) unsafe fn release_import(
|
||||
&self,
|
||||
device: &Device,
|
||||
after: Option<Box<dyn Send>>,
|
||||
) -> Option<Box<dyn Send>> {
|
||||
// The Vulkan teardown is a section of the exit guard.
|
||||
let Some(busy) = exit_guard::enter() else {
|
||||
return after;
|
||||
};
|
||||
let shared = device.shared();
|
||||
// A submission that used the pages waited for their sparse binding: waited for here where
|
||||
// none did.
|
||||
self.memory.placement.settle();
|
||||
// SAFETY: the caller's.
|
||||
unsafe { release::object(shared.vk(), self.raw) };
|
||||
let after = lock(&shared.memory).free_then(shared.vk(), &self.memory.placement, after);
|
||||
drop(busy);
|
||||
device.note_import_freed(self.memory.placement.size());
|
||||
after
|
||||
}
|
||||
}
|
||||
|
||||
/// A buffer's bound memory: its placement, and its Vulkan device address where the device
|
||||
/// enables `bufferDeviceAddress`.
|
||||
pub(super) struct Bound {
|
||||
@@ -704,16 +1079,30 @@ pub(super) struct Bound {
|
||||
}
|
||||
|
||||
impl OwnBytes {
|
||||
/// `f` of the pages the buffer lies in now: a detached buffer's stand-in (`Detached`).
|
||||
/// `f` of the pages the buffer lies in now: a detached buffer's stand-in (`Detached`). A
|
||||
/// read of a no-copy buffer's import other than a blit's, which keeps it imported for good
|
||||
/// (`HostImport::pages`).
|
||||
fn with<R>(&self, f: impl FnOnce(&Pages) -> R) -> R {
|
||||
match &self.lie {
|
||||
Lie::Fixed(fixed) => f(&fixed.pages),
|
||||
Lie::Host(cell) => match cell.lying() {
|
||||
Lying::In(pages) => f(&pages.import.pages),
|
||||
Lying::In(pages) => f(&pages.import.pages()),
|
||||
Lying::Detached(detached) => f(&detached.pages),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the bytes lie in the pages the buffer lies in now ([`Shape`]), read without their
|
||||
/// `VkBuffer`.
|
||||
fn shape(&self) -> Shape {
|
||||
match &self.lie {
|
||||
Lie::Fixed(fixed) => Shape::of(&fixed.pages),
|
||||
Lie::Host(cell) => match cell.lying() {
|
||||
Lying::In(pages) => pages.import.shape,
|
||||
Lying::Detached(detached) => Shape::of(&detached.pages),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Managed` buffer's host copy on a device without unified memory (`managed.rs`): a
|
||||
@@ -834,6 +1223,11 @@ impl Drop for BufferShared {
|
||||
// The range is free and no lock is held: the caller's token goes, so a creation at the
|
||||
// range from its drop on succeeds.
|
||||
own.range_token.release();
|
||||
if let Lie::Host(cell) = &own.lie {
|
||||
if let Lying::In(pages) = cell.lying() {
|
||||
pages.announce_listed(&self.device);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -870,6 +1264,10 @@ pub(super) struct BufferParts {
|
||||
pub(super) of_heap: bool,
|
||||
/// A `Managed` buffer's host copy, on a device without unified memory.
|
||||
pub(super) mirror: Option<Arc<Mirror>>,
|
||||
/// What imports a no-copy buffer's dma-bufs again, where the device may release its import
|
||||
/// while idle (`host_residency.rs`).
|
||||
#[cfg(unix)]
|
||||
pub(super) again: Option<Again>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Buffer {
|
||||
@@ -1192,6 +1590,8 @@ impl Device {
|
||||
release: None,
|
||||
of_heap,
|
||||
mirror,
|
||||
#[cfg(unix)]
|
||||
again: None,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1312,6 +1712,8 @@ impl Device {
|
||||
release: None,
|
||||
of_heap: false,
|
||||
mirror: None,
|
||||
#[cfg(unix)]
|
||||
again: None,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1331,12 +1733,17 @@ impl Device {
|
||||
release,
|
||||
of_heap,
|
||||
mirror,
|
||||
#[cfg(unix)]
|
||||
again,
|
||||
} = parts;
|
||||
let pages = self.pages_of(raw, memory, offset, base, reach);
|
||||
let identity = Identity::new(modes.hazard, of_heap);
|
||||
let lie = match owner {
|
||||
// A no-copy buffer's pages are its until a rebind (`rebind.rs`).
|
||||
Owner::Caller => {
|
||||
#[cfg(unix)]
|
||||
let import = self.host_import(pages, again);
|
||||
#[cfg(not(unix))]
|
||||
let import = Arc::new(HostImport::new(self, pages));
|
||||
self.host_lie(identity.key, import, release)
|
||||
}
|
||||
@@ -1357,6 +1764,25 @@ impl Device {
|
||||
self.buffer_lying(own, length, modes, address)
|
||||
}
|
||||
|
||||
/// The import of a no-copy buffer's `pages`: one the device releases while idle where
|
||||
/// `again` imports them again and the device keeps a stand-in for it and a thread to release
|
||||
/// it (`host_residency.rs`), else one it keeps.
|
||||
#[cfg(unix)]
|
||||
fn host_import(&self, pages: Pages, again: Option<Again>) -> Arc<HostImport> {
|
||||
let stand_in = again.as_ref().and_then(|_| self.detach_stand_in().ok());
|
||||
let (Some(again), Some(stand_in)) =
|
||||
(again, stand_in.as_ref().and_then(Buffer::fixed_pages))
|
||||
else {
|
||||
return Arc::new(HostImport::new(self, pages));
|
||||
};
|
||||
let import = Arc::new(HostImport::releasable(self, pages, again, stand_in));
|
||||
if !self.shared().residency.note(&import) {
|
||||
// No thread releases it: kept imported.
|
||||
import.expose();
|
||||
}
|
||||
import
|
||||
}
|
||||
|
||||
/// A no-copy buffer of `length` bytes lying in `import`, the import of the same bytes a live
|
||||
/// no-copy buffer lies in (`host_aliases.rs`), at `address`, released to `release` once
|
||||
/// nothing holds it. Dropping the result releases every part but the import, which the last
|
||||
@@ -1393,6 +1819,7 @@ impl Device {
|
||||
texels: Mutex::new(Vec::new()),
|
||||
aliases: Mutex::new(Vec::new()),
|
||||
textures: Mutex::new(TexturesOver::default()),
|
||||
exposed: AtomicBool::new(false),
|
||||
});
|
||||
self.shared().rebinds.register(key, &cell);
|
||||
Lie::Host(cell)
|
||||
@@ -1420,7 +1847,7 @@ impl Device {
|
||||
|
||||
/// The pages of a buffer `raw` in `memory`, its bytes `offset` bytes into its placement and
|
||||
/// `base` bytes into `raw`, `reach` bytes from byte 0 copied out.
|
||||
fn pages_of(
|
||||
pub(super) fn pages_of(
|
||||
&self,
|
||||
raw: vk::Buffer,
|
||||
placement: Placement,
|
||||
@@ -1707,7 +2134,7 @@ impl Buffer {
|
||||
/// written past the length, or another resource's: refused (`Invalid`).
|
||||
pub(super) fn copy_reach(&self) -> u64 {
|
||||
match &self.0.bytes {
|
||||
Bytes::Own(own) => own.with(|pages| pages.reach),
|
||||
Bytes::Own(own) => own.shape().reach,
|
||||
Bytes::Heap(_) => self.0.length,
|
||||
}
|
||||
}
|
||||
@@ -1722,6 +2149,16 @@ impl Buffer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the buffer's byte 0 lies in its `VkBuffer` ([`Buffer::at`]'s offset of byte 0), read
|
||||
/// without the `VkBuffer`: a no-copy buffer's [`Buffer::base`], a heap buffer's offset in its
|
||||
/// heap's.
|
||||
pub(super) fn start(&self) -> u64 {
|
||||
match &self.0.bytes {
|
||||
Bytes::Own(own) => own.shape().base,
|
||||
Bytes::Heap(bytes) => bytes.bytes.start() + bytes.offset,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `VkBuffer`, and where the space the bind layer states the buffer in starts in it:
|
||||
/// 0 for a buffer of its own, a heap buffer's offset in its heap's. The bind layer's offsets
|
||||
/// (`ArgumentTable::stage_table`) count from there, [`Buffer::base`] bytes before byte 0.
|
||||
@@ -1736,7 +2173,7 @@ impl Buffer {
|
||||
/// below it). An alignment Vulkan asks of an offset holds of `base` plus Metal's offset.
|
||||
pub(super) fn base(&self) -> u64 {
|
||||
match &self.0.bytes {
|
||||
Bytes::Own(own) => own.with(|pages| pages.base),
|
||||
Bytes::Own(own) => own.shape().base,
|
||||
Bytes::Heap(_) => 0,
|
||||
}
|
||||
}
|
||||
@@ -1907,9 +2344,18 @@ impl Buffer {
|
||||
_pages: Arc::clone(fixed),
|
||||
},
|
||||
)),
|
||||
// A releasable import released is listed without a range: no shader reaches it
|
||||
// unnamed (`host_residency.rs`).
|
||||
Lie::Host(cell) => {
|
||||
let host = cell.current()?;
|
||||
Some((range(&host.import.pages)?, PagesHold::Host { _pages: host }))
|
||||
let listing = host.import.listing()?;
|
||||
let listed = range(&listing)?;
|
||||
Some((
|
||||
listed,
|
||||
PagesHold::Host {
|
||||
_pages: ListedPages::new(host),
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1964,6 +2410,19 @@ impl Buffer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pages a buffer of its own lies in for good (the runtime's memory, or the caller's
|
||||
/// `VkBuffer`); `None` for a no-copy buffer and a heap's.
|
||||
#[cfg(unix)]
|
||||
fn fixed_pages(&self) -> Option<Arc<FixedPages>> {
|
||||
match &self.0.bytes {
|
||||
Bytes::Own(OwnBytes {
|
||||
lie: Lie::Fixed(fixed),
|
||||
..
|
||||
}) => Some(Arc::clone(fixed)),
|
||||
Bytes::Own(_) | Bytes::Heap(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffer's hold on its host pages: a no-copy buffer's, or a no-copy heap's own
|
||||
/// buffer's; `None` for any other buffer, a heap's buffer among them.
|
||||
pub(super) fn host_cell(&self) -> Option<&Arc<HostCell>> {
|
||||
@@ -2003,6 +2462,52 @@ impl Buffer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffer's Metal address, read for the runtime's own bookkeeping (a live-table key, a
|
||||
/// lookup), which hands it out to no one: [`Buffer::gpu_address`] without its exposure.
|
||||
pub(super) fn metal_address(&self) -> GpuAddress {
|
||||
self.0.address
|
||||
}
|
||||
|
||||
/// Keep a no-copy buffer's import imported for good from now on, its Metal address handed
|
||||
/// out (`host_residency.rs`): imported again now where the device released it, and its
|
||||
/// live-table range read again where one was noted before a release.
|
||||
fn expose(&self) {
|
||||
let Some(cell) = self.host_cell() else {
|
||||
return;
|
||||
};
|
||||
if cell.exposed.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
if let Some(pages) = cell.current() {
|
||||
if pages.import.expose() {
|
||||
self.device().shared().live_buffers.refresh(self);
|
||||
}
|
||||
}
|
||||
cell.exposed.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
/// [`Buffer::at`] for a blit's command, which reads the `VkBuffer` without exposing the
|
||||
/// buffer: a no-copy buffer's import the device released while idle is imported again first
|
||||
/// (`host_residency.rs`). With what the command buffer holds until it completed: the
|
||||
/// import's objects, where the device may release them. Refused where the device cannot
|
||||
/// import them again.
|
||||
pub(super) fn blit_at(
|
||||
&self,
|
||||
offset: u64,
|
||||
) -> Result<((vk::Buffer, u64), Option<Arc<dyn Any + Send + Sync>>), Error> {
|
||||
if let Bytes::Own(OwnBytes {
|
||||
lie: Lie::Host(cell),
|
||||
..
|
||||
}) = &self.0.bytes
|
||||
{
|
||||
if let Lying::In(pages) = cell.lying() {
|
||||
let (held, hold) = pages.import.blit_pages()?;
|
||||
return Ok(((held.raw, held.base + offset), hold));
|
||||
}
|
||||
}
|
||||
Ok((self.at(offset), None))
|
||||
}
|
||||
|
||||
/// The host pages the buffer's bytes lie in now ([`Buffer::pages_cell`]): a no-copy
|
||||
/// buffer's, or a no-copy heap's for a buffer of the heap; `None` for any other buffer, and
|
||||
/// while they are detached.
|
||||
@@ -2113,10 +2618,11 @@ impl Buffer {
|
||||
.mapped
|
||||
.and_then(|mapped| NonNull::new(mapped.as_ptr())),
|
||||
// The offset is inside the placement, which the mapping covers.
|
||||
Bytes::Own(own) => own.with(|pages| {
|
||||
let mapped = pages.memory.placement.mapped?;
|
||||
NonNull::new(mapped.as_ptr().wrapping_add(pages.offset as usize))
|
||||
}),
|
||||
Bytes::Own(own) => {
|
||||
let shape = own.shape();
|
||||
let mapped = shape.mapped?;
|
||||
NonNull::new(mapped.as_ptr().wrapping_add(shape.offset as usize))
|
||||
}
|
||||
// The heap's storage mode is the buffer's, and the offset lies inside the heap.
|
||||
Bytes::Heap(bytes) => bytes.bytes.contents().and_then(|contents| {
|
||||
NonNull::new(contents.as_ptr().wrapping_add(bytes.offset as usize))
|
||||
@@ -2133,7 +2639,13 @@ impl Buffer {
|
||||
|
||||
/// `gpuAddress`: the buffer's address in the device's Metal address space. A heap buffer's
|
||||
/// is its heap's plus its offset there (`Heap::gpu_address`).
|
||||
///
|
||||
/// A no-copy buffer whose import the device may release while idle and import again at its
|
||||
/// next blit (an import of dma-bufs: a runtime-internal residency, which nothing of Metal's
|
||||
/// observes) is kept imported for good from this call on: a command may reach it unnamed by
|
||||
/// this address.
|
||||
pub fn gpu_address(&self) -> GpuAddress {
|
||||
self.expose();
|
||||
self.0.address
|
||||
}
|
||||
|
||||
|
||||
@@ -230,10 +230,7 @@ impl Device {
|
||||
memory,
|
||||
length,
|
||||
resource_options,
|
||||
HostRelease {
|
||||
deallocator,
|
||||
keep_alive,
|
||||
},
|
||||
HostRelease::new(deallocator, keep_alive),
|
||||
place,
|
||||
false,
|
||||
)
|
||||
@@ -263,8 +260,10 @@ impl Device {
|
||||
/// `newBufferWithBytesNoCopy:length:options:deallocator:`, its pointer wrapped in `memory`
|
||||
/// ([`HostMemory`]): a buffer whose bytes are the caller's `length` bytes at
|
||||
/// `memory.pointer()` (module docs of `host_memory.rs`). `deallocator` runs once, with the
|
||||
/// pointer and `length`, when the buffer's last reference goes: on a runtime thread when that
|
||||
/// is a command buffer completing. A refused call never runs it.
|
||||
/// pointer and `length`, when the buffer's last reference goes: where that is a command
|
||||
/// buffer's, in its release on its queue's handler thread, after its completed handlers, where
|
||||
/// a wait in it for that command buffer returns at once, as Metal's does. A refused call never
|
||||
/// runs it.
|
||||
///
|
||||
/// The pages are imported here, as Metal wires them when it makes the buffer: the GPU uses
|
||||
/// the pages mapped at the pointer now, and memory the device cannot import is refused here,
|
||||
@@ -305,10 +304,7 @@ impl Device {
|
||||
memory,
|
||||
length,
|
||||
options,
|
||||
HostRelease {
|
||||
deallocator,
|
||||
keep_alive: None,
|
||||
},
|
||||
HostRelease::new(deallocator, None),
|
||||
AddressPlacement::Any.into(),
|
||||
false,
|
||||
)
|
||||
@@ -462,12 +458,18 @@ impl Device {
|
||||
// SAFETY: the window lies in the pages of the caller's bytes, which stay mapped
|
||||
// (`HostMemory::new`), and the source's pieces hold them (`HostMemory::with_dma_buf`). No
|
||||
// lock of the runtime's is held.
|
||||
let (buffer, memory) =
|
||||
// A no-copy buffer's own import of dma-bufs keeps them, so the device may release it
|
||||
// while idle and import them again (`host_residency.rs`); a heap's keeps none.
|
||||
let (buffer, memory, again) =
|
||||
match unsafe { self.import_by_pointer(importer, pointer, length, host, class) }? {
|
||||
Ok(made) => made,
|
||||
Ok((buffer, memory)) => (buffer, memory, None),
|
||||
// SAFETY: as above.
|
||||
Err(source) => unsafe {
|
||||
self.import_from_source(call, importer, pointer, length, &window, source, class)
|
||||
let keep = !of_heap;
|
||||
let window = &window;
|
||||
self.import_from_source(
|
||||
call, importer, pointer, length, window, source, class, keep,
|
||||
)
|
||||
}?,
|
||||
};
|
||||
let (address, reserved) = match self.place_window(placement, &window, length) {
|
||||
@@ -491,6 +493,8 @@ impl Device {
|
||||
release,
|
||||
of_heap,
|
||||
mirror: None,
|
||||
#[cfg(unix)]
|
||||
again,
|
||||
});
|
||||
// A buffer over the bytes another no-copy buffer covers joins it (`host_aliases.rs`), and
|
||||
// a later one lies in its import.
|
||||
@@ -576,43 +580,45 @@ impl Device {
|
||||
};
|
||||
// SAFETY: the window lies in the pages of the caller's bytes, which stay mapped
|
||||
// (`HostMemory::new`, `HostMemory::with_dma_buf`).
|
||||
let (host, placement, remade) = match unsafe {
|
||||
self.import_by_pointer(importer, pointer, length, host, class)
|
||||
}? {
|
||||
Ok((host, placement)) => (host, placement, Remade::default()),
|
||||
// The source is called with no lock of the runtime's held (`dma_buf.rs`): the
|
||||
// textures over detached bytes are let go of meanwhile, and must be settled again
|
||||
// after it.
|
||||
Err(source) => {
|
||||
let was_settled = settled.take().is_some();
|
||||
// SAFETY: as above, and the source's pieces hold the pages
|
||||
// (`HostMemory::with_dma_buf`).
|
||||
let (host, placement) = unsafe {
|
||||
self.import_from_source(call, importer, pointer, length, &window, source, class)
|
||||
}?;
|
||||
// The aliasing images of the textures over the bytes, made over dma-bufs of their
|
||||
// own pages, each of which the source makes: still with no lock held.
|
||||
let again = self.dma_buf_images_again(&aliases, heap, &placement, pointer);
|
||||
let remade = match again {
|
||||
Ok(remade) => remade,
|
||||
Err(error) => {
|
||||
self.discard_import(host, placement);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
if was_settled {
|
||||
match cell.settled() {
|
||||
Some(again) => settled = Some(again),
|
||||
None => {
|
||||
drop(remade);
|
||||
let (host, placement, remade) =
|
||||
match unsafe { self.import_by_pointer(importer, pointer, length, host, class) }? {
|
||||
Ok((host, placement)) => (host, placement, Remade::default()),
|
||||
// The source is called with no lock of the runtime's held (`dma_buf.rs`): the
|
||||
// textures over detached bytes are let go of meanwhile, and must be settled again
|
||||
// after it.
|
||||
Err(source) => {
|
||||
let was_settled = settled.take().is_some();
|
||||
// SAFETY: as above, and the source's pieces hold the pages
|
||||
// (`HostMemory::with_dma_buf`).
|
||||
let (host, placement, _) = unsafe {
|
||||
let window = &window;
|
||||
self.import_from_source(
|
||||
call, importer, pointer, length, window, source, class, false,
|
||||
)
|
||||
}?;
|
||||
// The aliasing images of the textures over the bytes, made over dma-bufs of their
|
||||
// own pages, each of which the source makes: still with no lock held.
|
||||
let again = self.dma_buf_images_again(&aliases, heap, &placement, pointer);
|
||||
let remade = match again {
|
||||
Ok(remade) => remade,
|
||||
Err(error) => {
|
||||
self.discard_import(host, placement);
|
||||
return Err(detached_textures());
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
if was_settled {
|
||||
match cell.settled() {
|
||||
Some(again) => settled = Some(again),
|
||||
None => {
|
||||
drop(remade);
|
||||
self.discard_import(host, placement);
|
||||
return Err(detached_textures());
|
||||
}
|
||||
}
|
||||
}
|
||||
(host, placement, remade)
|
||||
}
|
||||
(host, placement, remade)
|
||||
}
|
||||
};
|
||||
};
|
||||
let pages = self.host_pages(
|
||||
host.raw,
|
||||
placement,
|
||||
@@ -846,7 +852,8 @@ impl Device {
|
||||
_window: &ImportWindow,
|
||||
source: Source,
|
||||
_class: MemoryClass,
|
||||
) -> Result<(HostBuffer, Placement), Error> {
|
||||
_keep: bool,
|
||||
) -> Result<(HostBuffer, Placement, Option<std::convert::Infallible>), Error> {
|
||||
match source {}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ use super::device::lock;
|
||||
use super::error::{internal, invalid, nil, vulkan, Error, Problem, RuntimeGap};
|
||||
use super::exit_guard;
|
||||
use super::image_plan::check_own_memory;
|
||||
use super::key_hash::KeyMap;
|
||||
use super::linear_plan::{
|
||||
is_linear, plan_buffer_texture, BufferFacts, BufferLayout, BufferRefusal, BufferTexture,
|
||||
BufferTextureCall, BufferTextureProblem, Placed, LINEAR_ALIGNMENT,
|
||||
@@ -39,6 +40,7 @@ use super::linear_plan::{
|
||||
use super::resource::{Identity, ResourceKey};
|
||||
use super::rotated::{self, Frame, RotatedCopies};
|
||||
use super::shadow::{ShadowBuffer, ShadowCopies, ShadowSource, ShadowStaging, ShadowTarget};
|
||||
use super::shadow_copy_back::WordView;
|
||||
use super::texture::surface_two_planes;
|
||||
use super::texture::{IdUse, Texture};
|
||||
use super::texture_descriptor::{
|
||||
@@ -107,7 +109,7 @@ pub(super) struct Texels {
|
||||
/// with those pages (`rebind.rs`), and the next bind makes them again over the new ones.
|
||||
pub(super) struct TexelViews {
|
||||
device: Device,
|
||||
views: Mutex<HashMap<(Format, bool, u64, u64), vk::BufferView>>,
|
||||
views: Mutex<KeyMap<(Format, bool, u64, u64), vk::BufferView>>,
|
||||
}
|
||||
|
||||
impl TexelViews {
|
||||
@@ -1056,7 +1058,7 @@ impl Texels {
|
||||
) -> Texels {
|
||||
let views = Arc::new(TexelViews {
|
||||
device: buffer.device().clone(),
|
||||
views: Mutex::new(HashMap::new()),
|
||||
views: Mutex::new(KeyMap::default()),
|
||||
});
|
||||
// A rebind of the buffer's host pages empties the views (`rebind.rs`).
|
||||
buffer.watch_views(&views);
|
||||
@@ -1190,13 +1192,16 @@ impl Texels {
|
||||
/// of `identity`, with `aspects`: one region per slice, the slice's rows of texels. Where
|
||||
/// the texels start in the buffer's `VkBuffer` at an offset that is not a multiple of their
|
||||
/// size, which Vulkan copies texels at (a no-copy buffer's bytes need not start at one), the
|
||||
/// copies go through a staging buffer of the texture's ([`ShadowStaging`]). Refused as
|
||||
/// `new_buffer` refuses the staging buffer.
|
||||
/// copies go through a staging buffer of the texture's ([`ShadowStaging`]). Its copies back
|
||||
/// dispatch through `words`, its image's integer view, where given and its one slice is
|
||||
/// copied in place (`shadow_copy_back.rs`). Refused as `new_buffer` refuses the staging
|
||||
/// buffer.
|
||||
pub(super) fn shadow_copies(
|
||||
&self,
|
||||
image: vk::Image,
|
||||
identity: Identity,
|
||||
aspects: vk::ImageAspectFlags,
|
||||
words: Option<WordView>,
|
||||
) -> Result<ShadowCopies, Error> {
|
||||
let layout = &self.layout;
|
||||
let (buffer, at) = self.buffer.at(layout.offset);
|
||||
@@ -1245,6 +1250,8 @@ impl Texels {
|
||||
key: bytes.key,
|
||||
bytes: tracked,
|
||||
target: ShadowTarget::Image {
|
||||
// A copy back dispatches over one region copied in place alone.
|
||||
words: words.filter(|_| slices == 1 && staging.is_none()),
|
||||
image,
|
||||
regions,
|
||||
staging,
|
||||
|
||||
@@ -47,10 +47,10 @@ use std::collections::BTreeSet;
|
||||
pub(super) const RATE_MAP_LAYERS: u64 = 2;
|
||||
|
||||
/// The largest vertex amplification count Metal supports: `supportsVertexAmplificationCount:`
|
||||
/// answers yes from 1 to 8 and no from 9 to 16 (AMP Metal probe 1: the M3 Max with macOS 26.7
|
||||
/// and an M4 with macOS 27.0.1, alike), and yes for 0 (EVs API-props1-m3 and API-props1-m4, alike).
|
||||
/// A device with `multiview` draws every such count: as views where multiview draws them as Metal
|
||||
/// does, else one amplification at a time.
|
||||
/// answers yes from 1 to 8 and no from 9 to 16 (a Metal probe: the M3 Max with macOS 26.7 and an M4
|
||||
/// with macOS 27.0.1, alike), and yes for 0 (EVs API-props1-m3 and API-props1-m4, alike). A device
|
||||
/// with `multiview` draws every such count: as views where multiview draws them as Metal does, else
|
||||
/// one amplification at a time.
|
||||
pub(super) const MAX_VERTEX_AMPLIFICATION: u64 = 8;
|
||||
|
||||
/// A device's identity and Metal's public device queries, as the runtime answers them on the
|
||||
|
||||
@@ -337,6 +337,21 @@ impl DrawnArea {
|
||||
})
|
||||
}
|
||||
|
||||
/// Add `other`'s rectangles: anywhere where it bounds nothing.
|
||||
pub(super) fn join(&mut self, other: &DrawnArea) {
|
||||
if other.whole {
|
||||
self.everywhere();
|
||||
return;
|
||||
}
|
||||
if self.whole {
|
||||
return;
|
||||
}
|
||||
self.rects.extend(other.rects.iter().copied());
|
||||
if self.rects.len() > MOST_RECTS {
|
||||
self.everywhere();
|
||||
}
|
||||
}
|
||||
|
||||
/// Bound nothing: the draws may write anywhere in the render area.
|
||||
pub(super) fn everywhere(&mut self) {
|
||||
self.whole = true;
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! texels.
|
||||
//!
|
||||
//! Metal takes a clear color as four doubles, a clear depth as a double and a clear stencil as a
|
||||
//! 32-bit value. Its conversion to each format was measured on an Apple M4 (macOS 27.0.1; RT6
|
||||
//! probes 1 and 2), and is copied here channel by channel:
|
||||
//! 32-bit value. Its conversion to each format was measured on an Apple M4 (macOS 27.0.1, by our
|
||||
//! Metal probes), and is copied here channel by channel:
|
||||
//!
|
||||
//! - **Normalized** channels go through `float` (round to nearest even), then NaN is 0, the value
|
||||
//! is clamped to `[0, 1]` (`[-1, 1]` signed), and scaled to the nearest integer: 0.5/255 is 1
|
||||
@@ -25,18 +25,18 @@
|
||||
//! clear depth outside `[0, 1]` (the caller's check). **Stencil** keeps the low 8 bits.
|
||||
//!
|
||||
//! Vulkan converts a clear value to the format as its own rules say, which leave rounding to the
|
||||
//! implementation. So each clear value here is one the conversion maps exactly: the integer
|
||||
//! itself for integer formats, `k / m` for a normalized integer `k` (whose exact product with `m`
|
||||
//! is within a hair of `k`), the decoded sRGB value for an sRGB channel, and the exact `float`
|
||||
//! value of a `half`, small-float or shared-exponent result. A `Depth16Unorm` clear is
|
||||
//! `(k + 1/4) / m`, a quarter step above the stored integer `k` (or 1.0 for the largest), which
|
||||
//! rounding to nearest and truncating both map to `k`: MoltenVK hands the value to Metal, which
|
||||
//! truncates, and `k / m` lies a hair below `k` for some `k` (1/65535 stored 0 there). A NaN of a
|
||||
//! `half` or small-float channel has no such value: Vulkan leaves its bits to the device, and
|
||||
//! RADV and lavapipe write other NaNs than Metal's canonical quiet one (RRS probe 14, the M3 Max
|
||||
//! and an M4 alike: `0x7e00`, and `0x7e0` and `0x3f0` for `RG11B10Float`, the sign dropped).
|
||||
//! [`nan_texel`] gives such a texel's bits, which `nan_clear.rs` writes before the pass. A `float`
|
||||
//! NaN keeps its sign (`0x7fc00000`, `0xffc00000`), which every device measured writes.
|
||||
//! implementation. So each clear value here is one the conversion maps exactly: the integer itself
|
||||
//! for integer formats, `k / m` for a normalized integer `k` (whose exact product with `m` is
|
||||
//! within a hair of `k`), the decoded sRGB value for an sRGB channel, and the exact `float` value
|
||||
//! of a `half`, small-float or shared-exponent result. A `Depth16Unorm` clear is `(k + 1/4) / m`, a
|
||||
//! quarter step above the stored integer `k` (or 1.0 for the largest), which rounding to nearest
|
||||
//! and truncating both map to `k`: MoltenVK hands the value to Metal, which truncates, and `k / m`
|
||||
//! lies a hair below `k` for some `k` (1/65535 stored 0 there). A NaN of a `half` or small-float
|
||||
//! channel has no such value: Vulkan leaves its bits to the device, and RADV and lavapipe write
|
||||
//! other NaNs than Metal's canonical quiet one (a Metal probe, the M3 Max and an M4 alike:
|
||||
//! `0x7e00`, and `0x7e0` and `0x3f0` for `RG11B10Float`, the sign dropped). [`nan_texel`] gives
|
||||
//! such a texel's bits, which `nan_clear.rs` writes before the pass. A `float` NaN keeps its sign
|
||||
//! (`0x7fc00000`, `0xffc00000`), which every device measured writes.
|
||||
//!
|
||||
//! An **extended-range** attachment holds its raw texels in an unsigned integer format, so its
|
||||
//! clear value is the raw texel Metal stores (`ExtendedRange::clear_texel`): each channel goes
|
||||
@@ -398,9 +398,9 @@ pub(crate) fn uint_texel(texel: &[u8]) -> Option<(Format, vk::ClearColorValue)>
|
||||
Some((format, vk::ClearColorValue { uint32 }))
|
||||
}
|
||||
|
||||
/// The bits of a small unsigned float of `mantissa` bits (and a 5-bit exponent) holding `v`,
|
||||
/// which is one exactly ([`ufloat_value`]'s result): NaN is the canonical quiet NaN (the top
|
||||
/// mantissa bit), as Metal writes it (RRS probe 14).
|
||||
/// The bits of a small unsigned float of `mantissa` bits (and a 5-bit exponent) holding `v`, which
|
||||
/// is one exactly ([`ufloat_value`]'s result): NaN is the canonical quiet NaN (the top mantissa
|
||||
/// bit), as Metal writes it (a Metal probe on the M3 Max and an M4).
|
||||
fn ufloat_bits(v: f32, mantissa: u32) -> u64 {
|
||||
if v.is_nan() {
|
||||
return (31 << mantissa) | (1 << (mantissa - 1));
|
||||
@@ -739,8 +739,8 @@ pub(crate) mod tests {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
/// Every clear the M4 measured (RT6 probes 1 and 2; the NaNs, RRS probe 14 on an M4 and the
|
||||
/// M3 Max alike), as the bytes it wrote.
|
||||
/// Every clear the M4 measured (our Metal probes; the NaNs on an M4 and the M3 Max alike), as
|
||||
/// the bytes it wrote.
|
||||
#[test]
|
||||
fn metal_clears_are_reproduced() {
|
||||
let n = f64::NAN;
|
||||
@@ -923,8 +923,8 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A clear of a `half` or small-float NaN writes Metal's texel through an integer format of
|
||||
/// its size (RRS probe 14's bytes), and no other clear does.
|
||||
/// A clear of a `half` or small-float NaN writes Metal's texel through an integer format of its
|
||||
/// size (the bytes Metal wrote on the M3 Max and an M4), and no other clear does.
|
||||
#[test]
|
||||
fn nan_texels_are_metals() {
|
||||
let n = f64::NAN;
|
||||
|
||||
@@ -4,12 +4,13 @@
|
||||
//! device, and of the drivers measured only MoltenVK's from 1.4.1 on Apple's GPUs writes Metal's
|
||||
//! answer (`DriverFact::ColorResolveAverageIsMetals`, measured at 2 and 4 samples). Every other
|
||||
//! device resolves a color attachment whose format has Metal's closed rule at its count
|
||||
//! (`bind::ColorResolveFormat::of` and `resolves`: unorm, snorm, sRGB and 32-bit float formats,
|
||||
//! and 16-bit float ones at 2 samples) by the crate-owned exact resolve
|
||||
//! (`bind::color_resolve_modules`), and so does every device at more than 4 samples, where Apple's
|
||||
//! GPUs have no texture and the rules measured at 2 and 4 are applied unmeasured. A format without
|
||||
//! a closed rule at its count (half floats past 2 samples, packed 16-bit, `RG11B10Float`,
|
||||
//! `RGB9E5Float`) resolves by the device's average: Metal's own resolve where the fact holds
|
||||
//! (`bind::ColorResolveFormat::of` and `resolves`: unorm, snorm, sRGB, 32-bit float and packed
|
||||
//! 16-bit unorm formats at every count, and 16-bit float, `RG11B10Float` and `RGB9E5Float` ones at
|
||||
//! 2 and 4 samples) by the crate-owned exact resolve (`bind::color_resolve_modules`), and so does
|
||||
//! every device at more than 4 samples, where Apple's GPUs have no texture and the integer rules
|
||||
//! measured at 2 and 4 are applied unmeasured. A format without a closed rule at its count (the
|
||||
//! 16-bit float, `RG11B10Float` and `RGB9E5Float` formats past 4 samples, and a format no rule
|
||||
//! covers) resolves by the device's average: Metal's own resolve where the fact holds
|
||||
//! ([`average_is_metals`]: MoltenVK resolves every such format by Metal's multisample resolve store
|
||||
//! action), elsewhere a recorded near-equivalent.
|
||||
//!
|
||||
@@ -31,10 +32,20 @@
|
||||
//! - **From the attachment** otherwise: its level and layer as the resolve pass's input
|
||||
//! attachment 0, loaded and stored. Its image needs input attachment usage, which a
|
||||
//! multisampled color render target the runtime makes takes where the device may resolve it so
|
||||
//! and the usage costs the image nothing (`framebuffer_fetch.rs`), as does a stand-in
|
||||
//! (`attachment_stand_in.rs`); an attachment whose image lacks it (a caller's image without it,
|
||||
//! or a device where it would change the image's memory requirements) resolves by the device's
|
||||
//! average, announced as `device-rounded-resolve`.
|
||||
//! and the usage costs the image nothing, and a memoryless one wherever the device makes the
|
||||
//! image (`framebuffer_fetch.rs`), as does a stand-in (`attachment_stand_in.rs`).
|
||||
//! - **From a copy of the attachment's samples** where its image lacks that usage (a caller's
|
||||
//! image without it, or a device where it would change the image's memory requirements) but
|
||||
//! takes transfer reads ([`copied`]): its level and the pass's layers over the render area are
|
||||
//! copied (`vkCmdCopyImage`, one format and sample count) into a scratch image of its format and
|
||||
//! samples that has the usage, held by the command buffer until it completes, and the resolve
|
||||
//! reads the scratch as it reads an attachment. The copy moves each sample's bits; the one
|
||||
//! device measured to change them, RADV, writes a 16-bit float NaN as `0xfe00`
|
||||
//! (`RuntimeDriverDefect::MultisampledCopiesConvertFloatNans`), which the resolve counts as 0
|
||||
//! whatever its bits. A caller's image has the transfer usage the runtime's texture of its
|
||||
//! descriptor has (`texture/wrapped.rs`), so only an image of a format the device copies no
|
||||
//! image of has neither usage: it resolves by the device's average, announced as
|
||||
//! `device-rounded-resolve`.
|
||||
//!
|
||||
//! A layered pass (`renderTargetArrayLength` 2 or more) resolves each of its layers in a render
|
||||
//! pass instance of its own, through views of that layer. Its resolve from the sample planes, which
|
||||
@@ -42,12 +53,16 @@
|
||||
//!
|
||||
//! The resolve's pipelines and passes are made once per device, format, sample count and source,
|
||||
//! at the first pass that needs them, and destroyed with the device; each pass's descriptor sets
|
||||
//! and framebuffers are held by its command buffer until it completes. Each resolve runs between
|
||||
//! barriers from everything before and to everything after. The runtime announces
|
||||
//! `shader-resolve` (performance) for the extra pass, and `unmeasured-resolve` (precision) at
|
||||
//! more than 4 samples.
|
||||
//! and framebuffers are held by its command buffer until it completes, and, where every resolve of
|
||||
//! the pass reads its attachment through the attachment's own views, kept by the image it first
|
||||
//! resolves into for its next pass of the same views ([`KeptResolves`]). Each resolve runs between
|
||||
//! barriers from everything before and to everything after, as does each copy before them. The
|
||||
//! runtime announces `shader-resolve` (performance) for the extra pass (naming the copy where the
|
||||
//! resolve reads one), and `unmeasured-resolve` (precision) at more than 4 samples.
|
||||
|
||||
use super::binding_view::VkView;
|
||||
use super::blit::TRANSFER;
|
||||
use super::command_buffer::CommandBuffer;
|
||||
use super::device::{device_error, lock};
|
||||
use super::encoder::EncoderCore;
|
||||
use super::error::{internal, vulkan, Error, RuntimeGap};
|
||||
@@ -56,6 +71,7 @@ use super::image_plan::ImagePlan;
|
||||
use super::release;
|
||||
use super::render_pass::{PassLayout, Target};
|
||||
use super::render_target::{takes_input, ATTACHMENT_STAGES};
|
||||
use super::resolve;
|
||||
use super::resource::ResourceKey;
|
||||
use super::sample_planes::{pipeline_layout, set_layout, shader_module};
|
||||
use super::tracker::{Access, Barrier, Use};
|
||||
@@ -66,8 +82,10 @@ use metal2vulkan::bind::{color_resolve_modules, ColorResolveFormat, PlanesCopy,
|
||||
use metal2vulkan::device::DriverFact;
|
||||
use metal2vulkan::error::Feature;
|
||||
use metal2vulkan::vk::{
|
||||
ComponentMapping, Format, ImageAspectFlags, ImageUsageFlags, ImageViewType,
|
||||
ComponentMapping, Format, FormatFeatureFlags2, ImageAspectFlags, ImageUsageFlags, ImageViewType,
|
||||
};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// The most samples of a texture on Apple's GPUs, so the most whose resolve Metal measures.
|
||||
pub(super) const METAL_SAMPLES: u32 = 4;
|
||||
@@ -76,7 +94,7 @@ pub(super) const METAL_SAMPLES: u32 = 4;
|
||||
/// format's rules where the format has them and the device's average is not measured to be
|
||||
/// Metal's at that count (the module docs). `None` where the device resolves it in the pass.
|
||||
pub(super) fn exact(device: &Device, format: Format, samples: u32) -> Option<ColorResolveFormat> {
|
||||
// Rules that hold at that count: a half's at 2 samples only.
|
||||
// Rules that hold at that count: the float formats' at 2 and 4 samples only.
|
||||
let rules = ColorResolveFormat::of(format).filter(|rules| rules.resolves(samples))?;
|
||||
(samples > 1 && !average_is_metals(device, samples)).then_some(rules)
|
||||
}
|
||||
@@ -93,18 +111,36 @@ pub(super) fn average_is_metals(device: &Device, samples: u32) -> bool {
|
||||
}
|
||||
|
||||
/// The exact resolve of the color attachment `source`, where the runtime resolves it so: [`exact`]
|
||||
/// of its format and samples, where its image takes input attachment usage, through which the
|
||||
/// resolve reads its samples unless its sample planes hold them (the module docs).
|
||||
/// of its format and samples, where the resolve may read its samples: through its image's input
|
||||
/// attachment usage, or from a copy of them into a scratch image that has it ([`copied`]), unless
|
||||
/// its sample planes hold them (the module docs).
|
||||
pub(super) fn of_attachment(
|
||||
device: &Device,
|
||||
source: &Target,
|
||||
) -> Result<Option<ColorResolveFormat>, Error> {
|
||||
match exact(device, source.format, source.samples) {
|
||||
Some(rules) if takes_input(source)? => Ok(Some(rules)),
|
||||
Some(rules) if takes_input(source)? || copied(device, source)? => Ok(Some(rules)),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the exact resolve may read the color attachment `source`, whose image takes no input
|
||||
/// attachment usage, from a copy of its samples (the module docs): its image takes transfer reads,
|
||||
/// and the device copies images of its format both ways, which the scratch image the copy writes
|
||||
/// needs.
|
||||
fn copied(device: &Device, source: &Target) -> Result<bool, Error> {
|
||||
let usage = source.texture.image_plan()?.usage;
|
||||
let profile = device.compile_device().profile();
|
||||
let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST;
|
||||
Ok(usage.contains(ImageUsageFlags::TRANSFER_SRC)
|
||||
&& device
|
||||
.shared()
|
||||
.textures
|
||||
.facts(profile)
|
||||
.optimal(source.format)
|
||||
.contains(copies))
|
||||
}
|
||||
|
||||
/// Whether a multisampled color attachment of `format` at `samples` that the sample planes may
|
||||
/// hold as a pass ends resolves from them by the exact resolve whatever its device's average: its
|
||||
/// format has Metal's rules at that count. Its pass is of one subpass, whose resolve references
|
||||
@@ -408,12 +444,14 @@ fn resolve_pipeline(
|
||||
.ok_or_else(|| internal("the driver made no pipeline"))
|
||||
}
|
||||
|
||||
/// The objects one pass's resolves hold until its command buffer completes: their descriptor
|
||||
/// sets' pool and their framebuffers.
|
||||
/// The objects one pass's resolves hold until its command buffer completes, and, kept
|
||||
/// ([`KeptResolves`]), until the image keeping them lets them go and every command buffer that
|
||||
/// took them completed: their descriptor sets' pool and, for each resolve and layer, its
|
||||
/// framebuffer and set.
|
||||
struct PassObjects {
|
||||
device: Device,
|
||||
pool: vk::DescriptorPool,
|
||||
framebuffers: Vec<vk::Framebuffer>,
|
||||
resolves: Vec<Planned>,
|
||||
}
|
||||
|
||||
impl Drop for PassObjects {
|
||||
@@ -424,10 +462,17 @@ impl Drop for PassObjects {
|
||||
};
|
||||
let raw = self.device.shared().vk();
|
||||
// SAFETY: no pending command uses them (a command buffer retains them until it completes);
|
||||
// the sets are freed with their pool, and a null handle is a no-op.
|
||||
// the sets are freed with their pool, and a null handle is a no-op. The views they were
|
||||
// made of may have gone first: an object is destroyed in any order but after its children,
|
||||
// and its destruction accesses no other object (the Vulkan specification's object
|
||||
// lifetime: "Applications can: free or destroy objects in any order, except that parent
|
||||
// objects must: be freed only after all child objects are freed", the parent being the
|
||||
// first object of the child's creation, here the device; "When destroying or freeing an
|
||||
// object, implementations must: not access any memory or other objects that may:
|
||||
// otherwise be accessed when the object is accessed").
|
||||
unsafe {
|
||||
for &framebuffer in &self.framebuffers {
|
||||
release::object(raw, framebuffer);
|
||||
for resolve in &self.resolves {
|
||||
release::object(raw, resolve.framebuffer);
|
||||
}
|
||||
release::object(raw, self.pool);
|
||||
}
|
||||
@@ -443,10 +488,262 @@ struct Planned {
|
||||
|
||||
/// A pass's exact color resolves, planned before the pass records and recorded after it.
|
||||
pub(super) struct ShaderResolves {
|
||||
resolves: Vec<Planned>,
|
||||
extent: [u32; 2],
|
||||
uses: Vec<Use<ResourceKey>>,
|
||||
objects: PassObjects,
|
||||
/// The copies of the attachments the resolves read from a scratch image ([`copied`]):
|
||||
/// `(attachment, scratch, region)` each, and their uses.
|
||||
copies: Vec<(vk::Image, vk::Image, vk::ImageCopy)>,
|
||||
copy_uses: Vec<Use<ResourceKey>>,
|
||||
objects: Arc<PassObjects>,
|
||||
}
|
||||
|
||||
/// The most passes' resolve objects an image keeps ([`KeptResolves`]).
|
||||
const KEPT_PASSES: usize = 4;
|
||||
|
||||
/// The resolve objects of the passes that resolved into one image ([`ShaderResolves::plan`]),
|
||||
/// kept for its next pass of the same views, and the image's key in the passes' keys.
|
||||
///
|
||||
/// A pass whose every resolve reads its attachment through the attachment's own views (not the
|
||||
/// sample planes, nor a copy of its samples, whose views are the pass's own) is kept by the image
|
||||
/// it first resolves into, by everything its objects are made of ([`PassKey`]), and a later pass
|
||||
/// of the same key binds the kept sets and begins the kept framebuffers instead of making its
|
||||
/// own: the same descriptors of the same views, never written again. A set or framebuffer serves
|
||||
/// several pending command buffers at once: neither is mutated by the commands that use it (the
|
||||
/// Vulkan specification: "Any object parameters that are not labeled as externally synchronized
|
||||
/// are either not mutated by the command or are internally synchronized"; `vkCmdBindDescriptorSets`
|
||||
/// and `vkCmdBeginRenderPass` label only their command buffer), and a set's contents must only not
|
||||
/// be altered while a command that bound it may consume them ("Once all pending uses have
|
||||
/// completed, it is legal to update and reuse a descriptor set").
|
||||
///
|
||||
/// A key names each image by one no other image had or will have ([`KeptResolves::new`]), so a
|
||||
/// view of an image that dropped is never taken for a view of another, whatever handle the
|
||||
/// driver gave either. A view an image lets go while it lives (a rebind's or a storage form's new
|
||||
/// `VkImage`, a detach's stand-in, a reattach) moves the device's views epoch
|
||||
/// (`DeviceShared::views_epoch`): a pass kept under an older epoch is never taken, and an image's
|
||||
/// kept passes all go at its next pass after the epoch moved. A kept pass's objects go once the
|
||||
/// image lets go of them (as it drops, before its views; as the epoch moves; as a newer pass
|
||||
/// takes the place of the oldest past [`KEPT_PASSES`]) and every command buffer that took them
|
||||
/// completed.
|
||||
pub(super) struct KeptResolves {
|
||||
image: ResourceKey,
|
||||
passes: Mutex<Kept<PassObjects>>,
|
||||
}
|
||||
|
||||
impl KeptResolves {
|
||||
/// No passes kept yet, for an image made now.
|
||||
pub(super) fn new() -> KeptResolves {
|
||||
KeptResolves {
|
||||
image: ResourceKey::new(),
|
||||
passes: Mutex::new(Kept::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Let every kept pass go.
|
||||
pub(super) fn clear(&self) {
|
||||
lock(&self.passes).values.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// What a kept pass's objects are made of ([`KeptResolves`]): the pass's extent and, for each
|
||||
/// resolve and layer in the pass's order, the resolve's pipeline (format, samples and source),
|
||||
/// the view it reads and the view it writes, each as its image's key and the view's description.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct PassKey {
|
||||
extent: [u32; 2],
|
||||
resolves: Vec<ResolveKey>,
|
||||
}
|
||||
|
||||
/// One resolve and layer of a [`PassKey`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct ResolveKey {
|
||||
pipeline: (ColorResolveFormat, u32, Source),
|
||||
read: (ResourceKey, VkView),
|
||||
written: (ResourceKey, VkView),
|
||||
}
|
||||
|
||||
/// Values kept by key, each under the views epoch it was made in: at most [`KEPT_PASSES`], the
|
||||
/// newest first, all of one epoch.
|
||||
struct Kept<T> {
|
||||
epoch: u64,
|
||||
values: Vec<(PassKey, Arc<T>)>,
|
||||
}
|
||||
|
||||
impl<T> Default for Kept<T> {
|
||||
fn default() -> Kept<T> {
|
||||
Kept {
|
||||
epoch: 0,
|
||||
values: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Kept<T> {
|
||||
/// The value kept for `key`, where the views epoch is `epoch` as it was when the value was
|
||||
/// made; a newer epoch lets every kept value go.
|
||||
fn find(&mut self, epoch: u64, key: &PassKey) -> Option<Arc<T>> {
|
||||
self.at(epoch);
|
||||
if epoch != self.epoch {
|
||||
return None;
|
||||
}
|
||||
self.values
|
||||
.iter()
|
||||
.find(|(kept, _)| kept == key)
|
||||
.map(|(_, value)| Arc::clone(value))
|
||||
}
|
||||
|
||||
/// Keep `value` for `key`, made under views epoch `epoch`: not where the epoch moved since,
|
||||
/// and letting the oldest go past [`KEPT_PASSES`].
|
||||
fn keep(&mut self, epoch: u64, key: PassKey, value: Arc<T>) {
|
||||
self.at(epoch);
|
||||
if epoch != self.epoch {
|
||||
return;
|
||||
}
|
||||
if self.values.len() == KEPT_PASSES {
|
||||
self.values.pop();
|
||||
}
|
||||
self.values.insert(0, (key, value));
|
||||
}
|
||||
|
||||
/// Let every kept value go where `epoch` is newer than theirs.
|
||||
fn at(&mut self, epoch: u64) {
|
||||
if epoch > self.epoch {
|
||||
self.values.clear();
|
||||
self.epoch = epoch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The key of a pass resolving each of `wanted` (its attachment, its resolve attachment, its
|
||||
/// format's rules and its source) over `extent` in `layers` layers ([`KeptResolves`]); `None`
|
||||
/// where a resolve reads the sample planes or a copy of its samples, or its targets have other
|
||||
/// layers than the pass (which [`ShaderResolves::plan`] refuses).
|
||||
fn pass_key<'a>(
|
||||
wanted: impl Iterator<Item = (&'a Target, &'a Target, ColorResolveFormat, Source)>,
|
||||
extent: [u32; 2],
|
||||
layers: u32,
|
||||
) -> Result<Option<PassKey>, Error> {
|
||||
let mut resolves = Vec::new();
|
||||
for (attachment, into, format, source) in wanted {
|
||||
let own_views = source == Source::Attachment
|
||||
&& attachment.layers == layers
|
||||
&& into.layers == layers
|
||||
&& takes_input(attachment)?;
|
||||
if !own_views {
|
||||
return Ok(None);
|
||||
}
|
||||
let read = attachment.texture.kept_resolves()?.image;
|
||||
let written = into.texture.kept_resolves()?.image;
|
||||
for layer in 0..layers {
|
||||
resolves.push(ResolveKey {
|
||||
pipeline: (format, attachment.samples, source),
|
||||
read: (read, view_of(attachment, layer, attachment.format, INPUT)?),
|
||||
written: (written, view_of(into, layer, into.format, WRITTEN)?),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Some(PassKey { extent, resolves }))
|
||||
}
|
||||
|
||||
/// The usage of a resolve's view of the samples it reads as its input attachment.
|
||||
const INPUT: ImageUsageFlags = ImageUsageFlags::INPUT_ATTACHMENT;
|
||||
/// The usage of a resolve's view of the attachment it writes.
|
||||
const WRITTEN: ImageUsageFlags = ImageUsageFlags::COLOR_ATTACHMENT;
|
||||
|
||||
/// The use of `samples`' level and `layers` layers by a resolve that reads them as its input
|
||||
/// attachment.
|
||||
fn read_use(samples: &Target, layers: u32) -> Result<Use<ResourceKey>, Error> {
|
||||
samples.texture.image_use(
|
||||
samples.level..samples.level + 1,
|
||||
samples.layer..samples.layer + layers,
|
||||
Access::new(
|
||||
vk::PipelineStageFlags2::FRAGMENT_SHADER
|
||||
| vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT,
|
||||
vk::AccessFlags2::INPUT_ATTACHMENT_READ
|
||||
| vk::AccessFlags2::COLOR_ATTACHMENT_READ
|
||||
| vk::AccessFlags2::COLOR_ATTACHMENT_WRITE,
|
||||
),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
/// The use of `into`'s level and `layers` layers by the resolve that writes them.
|
||||
fn written_use(into: &Target, layers: u32) -> Result<Use<ResourceKey>, Error> {
|
||||
into.texture.image_use(
|
||||
into.level..into.level + 1,
|
||||
into.layer..into.layer + layers,
|
||||
Access::new(
|
||||
vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT,
|
||||
vk::AccessFlags2::COLOR_ATTACHMENT_WRITE,
|
||||
),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
/// The copy of `samples`' level and `layers` layers over the render area `extent` into a scratch
|
||||
/// image of its format and samples that the exact resolve reads as its input attachment
|
||||
/// ([`copied`]): the scratch, the copy, and its uses (the read of the attachment and the write of
|
||||
/// the scratch). The scratch is `maker`'s, held until it completes.
|
||||
fn copy_out(
|
||||
maker: &CommandBuffer,
|
||||
samples: &Target,
|
||||
layers: u32,
|
||||
extent: [u32; 2],
|
||||
) -> Result<
|
||||
(
|
||||
Target,
|
||||
(vk::Image, vk::Image, vk::ImageCopy),
|
||||
[Use<ResourceKey>; 2],
|
||||
),
|
||||
Error,
|
||||
> {
|
||||
let usage = ImageUsageFlags::COLOR_ATTACHMENT
|
||||
| ImageUsageFlags::INPUT_ATTACHMENT
|
||||
| ImageUsageFlags::TRANSFER_DST;
|
||||
let area = Target {
|
||||
extent,
|
||||
..samples.clone()
|
||||
};
|
||||
let scratch = resolve::scratch(maker, &area, usage, samples.samples)?;
|
||||
let at = |t: &Target| vk::ImageSubresourceLayers {
|
||||
aspect_mask: vk::ImageAspectFlags::COLOR,
|
||||
mip_level: t.level,
|
||||
base_array_layer: t.layer,
|
||||
layer_count: layers,
|
||||
};
|
||||
let [width, height] = extent;
|
||||
let region = vk::ImageCopy {
|
||||
src_subresource: at(samples),
|
||||
src_offset: vk::Offset3D::default(),
|
||||
dst_subresource: at(&scratch),
|
||||
dst_offset: vk::Offset3D::default(),
|
||||
extent: vk::Extent3D {
|
||||
width,
|
||||
height,
|
||||
depth: 1,
|
||||
},
|
||||
};
|
||||
let level = |t: &Target| t.level..t.level + 1;
|
||||
let on = |t: &Target| t.layer..t.layer + layers;
|
||||
let uses = [
|
||||
samples.texture.image_use(
|
||||
level(samples),
|
||||
on(samples),
|
||||
Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ),
|
||||
false,
|
||||
)?,
|
||||
scratch.texture.image_use(
|
||||
level(&scratch),
|
||||
on(&scratch),
|
||||
Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE),
|
||||
true,
|
||||
)?,
|
||||
];
|
||||
let copy = (
|
||||
samples.texture.raw_image()?,
|
||||
scratch.texture.raw_image()?,
|
||||
region,
|
||||
);
|
||||
Ok((scratch, copy, uses))
|
||||
}
|
||||
|
||||
/// The single-level view of `target`'s layer `layer` (counted from its first) in `format`,
|
||||
@@ -457,12 +754,24 @@ fn view(
|
||||
format: Format,
|
||||
usage: ImageUsageFlags,
|
||||
) -> Result<vk::ImageView, Error> {
|
||||
target
|
||||
.texture
|
||||
.image_view(&view_of(target, layer, format, usage)?)
|
||||
}
|
||||
|
||||
/// The description of [`view`]'s view.
|
||||
fn view_of(
|
||||
target: &Target,
|
||||
layer: u32,
|
||||
format: Format,
|
||||
usage: ImageUsageFlags,
|
||||
) -> Result<VkView, Error> {
|
||||
// A 1D image's layer is a 1D view (a 3D image's planes take 2D ones).
|
||||
let view_type = match target.texture.image_plan()?.image_type {
|
||||
metal2vulkan::vk::ImageType::TYPE_1D => ImageViewType::TYPE_1D,
|
||||
_ => ImageViewType::TYPE_2D,
|
||||
};
|
||||
target.texture.image_view(&VkView {
|
||||
Ok(VkView {
|
||||
view_type,
|
||||
format,
|
||||
components: ComponentMapping::IDENTITY,
|
||||
@@ -478,13 +787,15 @@ fn view(
|
||||
impl ShaderResolves {
|
||||
/// The exact resolves of `layout`'s color attachments (its final layout) whose last render
|
||||
/// pass instance leaves `last_storage` out of its draws' subpass: each from its sample
|
||||
/// planes where they hold its samples, else from the attachment (the module docs). `None`
|
||||
/// where no attachment resolves so.
|
||||
/// planes where they hold its samples, else from the attachment, or from a copy of its
|
||||
/// samples where its image takes no input attachment usage (the module docs). `None` where
|
||||
/// no attachment resolves so. Scratch images are `maker`'s.
|
||||
pub(super) fn plan(
|
||||
device: &Device,
|
||||
maker: &CommandBuffer,
|
||||
layout: &PassLayout,
|
||||
last_storage: &[u32],
|
||||
) -> Result<Option<ShaderResolves>, Error> {
|
||||
let device = maker.device();
|
||||
let mut wanted = Vec::new();
|
||||
for (index, color) in layout.colors.iter().enumerate() {
|
||||
let Some(color) = color else {
|
||||
@@ -516,12 +827,41 @@ impl ShaderResolves {
|
||||
if layers > 1 && wanted.iter().any(|w| w.3 != Source::Attachment) {
|
||||
return Err(Error::NotImplemented(RuntimeGap::LayeredPass));
|
||||
}
|
||||
// A pass whose resolves read their attachments through their own views takes the objects
|
||||
// the image it first resolves into keeps for a pass of the same key, or keeps the ones it
|
||||
// makes ([`KeptResolves`]). The views epoch is read before any view is taken, so a pass is
|
||||
// kept under an epoch no newer than its views'.
|
||||
let epoch = device.shared().views_epoch.load(Ordering::Acquire);
|
||||
let targets = wanted
|
||||
.iter()
|
||||
.map(|w| (&w.0.target, &w.1.attachment, w.2, w.3));
|
||||
let kept = match pass_key(targets, layout.extent, layers)? {
|
||||
Some(key) => Some((wanted[0].1.attachment.texture.kept_resolves()?, key)),
|
||||
None => None,
|
||||
};
|
||||
if let Some((memo, key)) = &kept {
|
||||
if let Some(objects) = lock(&memo.passes).find(epoch, key) {
|
||||
let mut uses = Vec::with_capacity(2 * wanted.len());
|
||||
for (color, resolve, ..) in &wanted {
|
||||
uses.push(read_use(&color.target, layers)?);
|
||||
uses.push(written_use(&resolve.attachment, layers)?);
|
||||
}
|
||||
device.shared().counts.color_resolve_pass_kept();
|
||||
return Ok(Some(ShaderResolves {
|
||||
extent: layout.extent,
|
||||
uses,
|
||||
copies: Vec::new(),
|
||||
copy_uses: Vec::new(),
|
||||
objects,
|
||||
}));
|
||||
}
|
||||
}
|
||||
let raw = device.shared().vk();
|
||||
let count = wanted.len() as u32 * layers;
|
||||
let mut objects = PassObjects {
|
||||
device: device.clone(),
|
||||
pool: vk::DescriptorPool::null(),
|
||||
framebuffers: Vec::new(),
|
||||
resolves: Vec::with_capacity(count as usize),
|
||||
};
|
||||
let inputs = wanted.iter().filter(|w| w.3 == Source::Attachment).count() as u32 * layers;
|
||||
let mut sizes = Vec::new();
|
||||
@@ -540,15 +880,33 @@ impl ShaderResolves {
|
||||
objects.pool = unsafe { raw.create_descriptor_pool(&info, None) }.map_err(vulkan)?;
|
||||
let general = vk::ImageLayout::GENERAL;
|
||||
let mut uses = Vec::new();
|
||||
let mut resolves = Vec::with_capacity(wanted.len());
|
||||
let mut copies = Vec::new();
|
||||
let mut copy_uses = Vec::new();
|
||||
for (color, resolve, format, source, planes) in wanted {
|
||||
let samples = &color.target;
|
||||
let attachment = &color.target;
|
||||
let into = &resolve.attachment;
|
||||
if samples.layers != layers || into.layers != layers {
|
||||
if attachment.layers != layers || into.layers != layers {
|
||||
return Err(internal("an exact resolve of other layers than its pass"));
|
||||
}
|
||||
// An attachment whose image takes no input attachment usage is read from a copy of
|
||||
// its samples ([`copied`]).
|
||||
let read_copy = source == Source::Attachment && !takes_input(attachment)?;
|
||||
let scratch = match read_copy {
|
||||
true if copied(device, attachment)? => {
|
||||
let (scratch, copy, used) = copy_out(maker, attachment, layers, layout.extent)?;
|
||||
copies.push(copy);
|
||||
copy_uses.extend(used);
|
||||
Some(scratch)
|
||||
}
|
||||
true => {
|
||||
return Err(internal(
|
||||
"an exact resolve of an attachment it can neither read nor copy",
|
||||
))
|
||||
}
|
||||
false => None,
|
||||
};
|
||||
let samples = scratch.as_ref().unwrap_or(attachment);
|
||||
let pipeline = device.color_resolve_pipeline(format, samples.samples, source)?;
|
||||
let all = |t: &Target| (t.level..t.level + 1, t.layer..t.layer + layers);
|
||||
match (source, planes) {
|
||||
(Source::Planes(_), Some(planes)) => uses.push(planes.image_use(
|
||||
Access::new(
|
||||
@@ -557,40 +915,12 @@ impl ShaderResolves {
|
||||
),
|
||||
false,
|
||||
)?),
|
||||
(Source::Attachment, _) => {
|
||||
if !takes_input(samples)? {
|
||||
return Err(internal(
|
||||
"an exact resolve of an attachment without input attachment usage",
|
||||
));
|
||||
}
|
||||
let (levels, on) = all(samples);
|
||||
uses.push(samples.texture.image_use(
|
||||
levels,
|
||||
on,
|
||||
Access::new(
|
||||
vk::PipelineStageFlags2::FRAGMENT_SHADER
|
||||
| vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT,
|
||||
vk::AccessFlags2::INPUT_ATTACHMENT_READ
|
||||
| vk::AccessFlags2::COLOR_ATTACHMENT_READ
|
||||
| vk::AccessFlags2::COLOR_ATTACHMENT_WRITE,
|
||||
),
|
||||
true,
|
||||
)?);
|
||||
}
|
||||
(Source::Attachment, _) => uses.push(read_use(samples, layers)?),
|
||||
(Source::Planes(_), None) => {
|
||||
return Err(internal("a planes resolve without planes"))
|
||||
}
|
||||
}
|
||||
let (levels, on) = all(into);
|
||||
uses.push(into.texture.image_use(
|
||||
levels,
|
||||
on,
|
||||
Access::new(
|
||||
vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT,
|
||||
vk::AccessFlags2::COLOR_ATTACHMENT_WRITE,
|
||||
),
|
||||
true,
|
||||
)?);
|
||||
uses.push(written_use(into, layers)?);
|
||||
// Each layer of the pass: one set and framebuffer of that layer's views.
|
||||
for layer in 0..layers {
|
||||
let layouts = [pipeline.set_layout];
|
||||
@@ -604,19 +934,14 @@ impl ShaderResolves {
|
||||
.first()
|
||||
.copied()
|
||||
.ok_or_else(|| internal("the driver allocated no set"))?;
|
||||
let written = view(into, layer, into.format, ImageUsageFlags::COLOR_ATTACHMENT)?;
|
||||
let written = view(into, layer, into.format, WRITTEN)?;
|
||||
let (read, attachments) = match (source, planes) {
|
||||
(Source::Planes(copy), Some(planes)) => {
|
||||
let read = planes.view(copy.format(), ImageUsageFlags::SAMPLED)?;
|
||||
(read, vec![written])
|
||||
}
|
||||
(Source::Attachment, _) => {
|
||||
let read = view(
|
||||
samples,
|
||||
layer,
|
||||
samples.format,
|
||||
ImageUsageFlags::INPUT_ATTACHMENT,
|
||||
)?;
|
||||
let read = view(samples, layer, samples.format, INPUT)?;
|
||||
(read, vec![read, written])
|
||||
}
|
||||
(Source::Planes(_), None) => {
|
||||
@@ -647,30 +972,36 @@ impl ShaderResolves {
|
||||
.layers(1);
|
||||
// SAFETY: `info` and its array are live for the call; the views are live.
|
||||
let framebuffer = unsafe { crate::creation::framebuffer(raw, &info) }?;
|
||||
objects.framebuffers.push(framebuffer);
|
||||
resolves.push(Planned {
|
||||
objects.resolves.push(Planned {
|
||||
pipeline,
|
||||
framebuffer,
|
||||
set,
|
||||
});
|
||||
}
|
||||
}
|
||||
device.shared().counts.color_resolve_pass_made();
|
||||
let objects = Arc::new(objects);
|
||||
if let Some((memo, key)) = kept {
|
||||
lock(&memo.passes).keep(epoch, key, Arc::clone(&objects));
|
||||
}
|
||||
Ok(Some(ShaderResolves {
|
||||
resolves,
|
||||
extent: layout.extent,
|
||||
uses,
|
||||
copies,
|
||||
copy_uses,
|
||||
objects,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Record the resolves in `core`'s command buffer after the pass, between barriers from
|
||||
/// everything before and to everything after, and hold their objects until the command
|
||||
/// buffer completes.
|
||||
/// everything before and to everything after, each copy of an attachment's samples first,
|
||||
/// between barriers too, and hold their objects until the command buffer completes.
|
||||
pub(super) fn record(self, core: &mut EncoderCore) {
|
||||
let ShaderResolves {
|
||||
resolves,
|
||||
extent,
|
||||
uses,
|
||||
copies,
|
||||
copy_uses,
|
||||
objects,
|
||||
} = self;
|
||||
let [width, height] = extent;
|
||||
@@ -687,8 +1018,24 @@ impl ShaderResolves {
|
||||
max_depth: 1.0,
|
||||
};
|
||||
core.barrier(Barrier::everything());
|
||||
if !copies.is_empty() {
|
||||
core.command(TRANSFER, ©_uses, |raw, command_buffer| {
|
||||
let general = vk::ImageLayout::GENERAL;
|
||||
for &(from, to, region) in &copies {
|
||||
// SAFETY: the encoder's command buffer is recording outside a render pass;
|
||||
// both images are live until it completes (the encoder retains the
|
||||
// attachment's texture, and the command buffer the scratch's) and rest in
|
||||
// `GENERAL`; the region is the attachment's level and the pass's layers over
|
||||
// the render area, in both images, of one format and sample count.
|
||||
unsafe {
|
||||
raw.cmd_copy_image(command_buffer, from, general, to, general, &[region])
|
||||
};
|
||||
}
|
||||
});
|
||||
core.barrier(Barrier::everything());
|
||||
}
|
||||
core.command(ATTACHMENT_STAGES, &uses, |raw, command_buffer| {
|
||||
for resolve in &resolves {
|
||||
for resolve in &objects.resolves {
|
||||
let begin = vk::RenderPassBeginInfo::default()
|
||||
.render_pass(resolve.pipeline.render_pass)
|
||||
.framebuffer(resolve.framebuffer)
|
||||
@@ -696,7 +1043,8 @@ impl ShaderResolves {
|
||||
// SAFETY: the encoder's command buffer is recording outside a render pass; the
|
||||
// pipeline, framebuffer, set and the images they view are live until it completes
|
||||
// (the device keeps the pipeline, this the framebuffer and set, the encoder the
|
||||
// textures and planes); every image rests in `GENERAL`.
|
||||
// textures and planes); every image rests in `GENERAL`. A kept framebuffer and
|
||||
// set are of views the textures still present ([`KeptResolves`]).
|
||||
unsafe {
|
||||
raw.cmd_begin_render_pass(command_buffer, &begin, vk::SubpassContents::INLINE);
|
||||
raw.cmd_bind_pipeline(
|
||||
@@ -723,3 +1071,96 @@ impl ShaderResolves {
|
||||
core.retain(objects);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A pass resolving a view of image `read` into one of image `written`, the same views but
|
||||
/// for their images.
|
||||
fn key(read: ResourceKey, written: ResourceKey) -> PassKey {
|
||||
let view = VkView {
|
||||
view_type: ImageViewType::TYPE_2D,
|
||||
format: Format::R8G8B8A8_UNORM,
|
||||
components: ComponentMapping::IDENTITY,
|
||||
aspect: ImageAspectFlags::COLOR,
|
||||
base_level: 0,
|
||||
level_count: 1,
|
||||
base_layer: 0,
|
||||
layer_count: 1,
|
||||
usage: INPUT,
|
||||
};
|
||||
let format = ColorResolveFormat::of(Format::R8G8B8A8_UNORM).expect("RGBA8's rules");
|
||||
PassKey {
|
||||
extent: [4, 4],
|
||||
resolves: vec![ResolveKey {
|
||||
pipeline: (format, 4, Source::Attachment),
|
||||
read: (read, view),
|
||||
written: (
|
||||
written,
|
||||
VkView {
|
||||
usage: WRITTEN,
|
||||
..view
|
||||
},
|
||||
),
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// A pass kept of a view of an image that dropped is never taken for the same view of an
|
||||
/// image made after it, whatever handle the driver gives the new view (it may give the
|
||||
/// dropped one's again): a key names an image by a key no other image had, and no handle.
|
||||
#[test]
|
||||
fn a_new_image_s_view_never_takes_a_dropped_image_s_kept_pass() {
|
||||
let written = KeptResolves::new();
|
||||
let dropped = KeptResolves::new();
|
||||
let dropped_key = dropped.image;
|
||||
let mut kept = Kept::default();
|
||||
kept.keep(1, key(dropped_key, written.image), Arc::new(()));
|
||||
assert!(kept.find(1, &key(dropped_key, written.image)).is_some());
|
||||
drop(dropped);
|
||||
let made_after = KeptResolves::new();
|
||||
assert_ne!(made_after.image, dropped_key);
|
||||
assert!(kept
|
||||
.find(1, &key(made_after.image, written.image))
|
||||
.is_none());
|
||||
}
|
||||
|
||||
/// Once an image let views go (the views epoch moved), a kept pass is never taken but made
|
||||
/// again, every kept one is let go, and one made under the older epoch is not kept.
|
||||
#[test]
|
||||
fn a_moved_views_epoch_makes_the_pass_again() {
|
||||
let (read, written) = (KeptResolves::new().image, KeptResolves::new().image);
|
||||
let objects = Arc::new(());
|
||||
let mut kept = Kept::default();
|
||||
kept.keep(3, key(read, written), Arc::clone(&objects));
|
||||
assert!(kept.find(3, &key(read, written)).is_some());
|
||||
assert!(kept.find(4, &key(read, written)).is_none());
|
||||
assert_eq!(
|
||||
Arc::strong_count(&objects),
|
||||
1,
|
||||
"the kept pass was not let go"
|
||||
);
|
||||
kept.keep(3, key(read, written), Arc::clone(&objects));
|
||||
assert!(kept.find(4, &key(read, written)).is_none());
|
||||
kept.keep(4, key(read, written), Arc::clone(&objects));
|
||||
assert!(kept.find(4, &key(read, written)).is_some());
|
||||
}
|
||||
|
||||
/// An image keeps at most `KEPT_PASSES` passes, letting the oldest go first.
|
||||
#[test]
|
||||
fn an_image_keeps_its_newest_passes() {
|
||||
let written = KeptResolves::new().image;
|
||||
let reads: Vec<_> = (0..=KEPT_PASSES)
|
||||
.map(|_| KeptResolves::new().image)
|
||||
.collect();
|
||||
let mut kept = Kept::default();
|
||||
for &read in &reads {
|
||||
kept.keep(0, key(read, written), Arc::new(()));
|
||||
}
|
||||
assert!(kept.find(0, &key(reads[0], written)).is_none());
|
||||
for &read in &reads[1..] {
|
||||
assert!(kept.find(0, &key(read, written)).is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,12 +51,9 @@ use std::sync::Arc;
|
||||
/// whose memory was taken away, as Metal fails it).
|
||||
///
|
||||
/// It runs with no lock of the runtime's held, and holds back the scheduler thread's submissions
|
||||
/// while it runs. A commit made meanwhile has its ready batches submitted, by itself or by the
|
||||
/// pass of another commit's thread it finds under way; where that pass is the last that thread
|
||||
/// makes for others, which leaves what it is left to the scheduler's thread
|
||||
/// (`scheduler/inbox.rs`), they wait for this check to end, unless a later commit takes them in
|
||||
/// first. It must not wait for GPU work, a command buffer or a handler, and should be quick. It
|
||||
/// may call the runtime otherwise.
|
||||
/// while it runs: a commit made meanwhile returns at once, and its batches wait in the inbox for
|
||||
/// the thread's next pass, after this check (`scheduler/inbox.rs`). It must not wait for GPU work,
|
||||
/// a command buffer or a handler, and should be quick. It may call the runtime otherwise.
|
||||
pub type SubmissionCheck = Arc<dyn Fn(&Submission<'_>) -> Option<NonZeroU64> + Send + Sync>;
|
||||
|
||||
/// The `MTLCommandBufferError` code a submission whose check panicked fails with: `Internal`.
|
||||
|
||||
@@ -1,18 +1,39 @@
|
||||
//! The completion thread: one per device, it finishes each submitted batch once its queue's
|
||||
//! timeline reached the batch's value, which one waiter thread per `VkQueue` watches.
|
||||
//! The device's completion: each submitted batch finishes once its queue's timeline reached the
|
||||
//! batch's value, which one waiter thread per `VkQueue` watches, and the waiter that sees the
|
||||
//! value reached finishes it ([`turns`]).
|
||||
//!
|
||||
//! - **In each queue's order.** A `VkQueue`'s batches signal its timeline with rising values, and
|
||||
//! Vulkan's signal operation order makes them complete in that order, so each queue's batches
|
||||
//! wait in one line, and a value reached finishes every batch up to it.
|
||||
//! - **What a finished batch does.** Its queue's completed value is published for the tracker
|
||||
//! (the host saw it before any later submission), the events it signaled are reached, and the
|
||||
//! batch that ends a command buffer posts its transition to `Completed` to its queue's context
|
||||
//! ([`contexts`](crate::contexts)), once the thread read the command buffer's GPU
|
||||
//! timestamps and gave their slot back (`gpu_time.rs`). The thread runs no handler.
|
||||
//! batch that ends a command buffer finishes it, once the turn read the command buffer's GPU
|
||||
//! timestamps and gave their slot back (`gpu_time.rs`): the turn runs its transition to
|
||||
//! `Completed` itself where that runs none of the program's code, else posts it to its queue's
|
||||
//! context ([`contexts`](crate::contexts)). A turn runs no handler.
|
||||
//! - **Finished where seen.** Metal's completion wakes a thread waiting for a command buffer with
|
||||
//! no completed handler from the thread that saw it complete, and orders it after its queue's
|
||||
//! earlier completed handlers. Measured on the Apple M3 Max (macOS 27.0.1), 40 runs each: with
|
||||
//! no handler, the status read `Completed` 91 to 137 us after `GPUEndTime` and
|
||||
//! `waitUntilCompleted` returned 3 to 10 us after the status; with a completed handler of 20 ms,
|
||||
//! the status read `Completed` before the handler began (within 10 us) and in it, and the wait
|
||||
//! returned 10 to 23 us after it ended; a command buffer with no handler behind an earlier one of
|
||||
//! its queue whose handler ran 20 ms read `Completed`, and its wait returned, 3 to 23 us after
|
||||
//! that handler ended, 21 to 30 ms after its own `GPUEndTime`. So the turn runs a command
|
||||
//! buffer's transition itself (`CommandBufferShared::finish_here`) where it is plain (no
|
||||
//! completed handler, none being added after the commit, and no notice), its queue's context
|
||||
//! runs on no handler thread and holds only plain transitions, which the turn runs first, in
|
||||
//! order, and the runtime holds none of the program's objects a release drops or runs
|
||||
//! (`program_objects.rs`): its status, release and gate then come from the waiter, which wakes
|
||||
//! the program's waiting thread itself. Everywhere else it is posted, as before. Beside the
|
||||
//! runtime lane's tests on the M3 Max at the utility clamp, the handler thread's wake between
|
||||
//! the turn and the program's thread took up to 13 to 55 ms at a light burst's 99th percentile
|
||||
//! of the queue storm (`runtime_lane::queue_storms`), over Metal's one wake from its completion;
|
||||
//! counted (`WorkCounts::completed_where_seen`).
|
||||
//! - **A command buffer finishes at its fence, where it has one.** Where the driver still reads
|
||||
//! a command buffer's objects after the value (MoltenVK 1.4.1), the batch that ends it also
|
||||
//! signals a fence ([`fences`](super::fences)), which the driver signals after those reads: the
|
||||
//! thread posts the transition, after which what the command buffer used is released, only once
|
||||
//! turn posts the transition, after which what the command buffer used is released, only once
|
||||
//! the fence is signaled too, and then resets the fence and gives it back. A wait for fences
|
||||
//! holds up the other queues' batches by as long. Elsewhere Vulkan's value is enough, and the
|
||||
//! batch has no fence.
|
||||
@@ -20,25 +41,57 @@
|
||||
//! timelines). Each `VkQueue`'s waiter thread waits for its queue's first pending batch past the
|
||||
//! value it saw reached: for the batch's fence where it has one, else for its queue's timeline to
|
||||
//! reach the batch's value, a wait of that one fence or that one semaphore (`poll`). Then it
|
||||
//! reads the timeline, publishes it, and hands the value to the completion thread; a signaled
|
||||
//! fence's batch reached its value whatever the read shows (lavapipe can show it later). A batch
|
||||
//! reads the timeline and publishes it; a signaled fence's batch reached its value whatever the
|
||||
//! read shows (lavapipe can show it later). A batch
|
||||
//! submitted to an idle `VkQueue` is waited for by that queue's own waiter, so it completes when
|
||||
//! its work does, not when another queue's does. No wait names several objects: MoltenVK 1.4.1's
|
||||
//! wait for any of several timelines (`vkWaitSemaphores` with `VK_SEMAPHORE_WAIT_ANY_BIT`,
|
||||
//! `mvkWaitSemaphores`) loses a signal that lands while it is still registering a later timeline,
|
||||
//! so the thread saw the batch only when its 100 ms wait ran out (the consumer's guest presented
|
||||
//! so the waiter saw the batch only when its 100 ms wait ran out (the consumer's guest presented
|
||||
//! at about a quarter of Metal's rate); its wait for any of several fences has the same flaw. A
|
||||
//! wait for one timeline or one fence counts its one signal under a lock, and loses none. The
|
||||
//! value is read again after every wait, so the waiter relies on no wake for the value, only for
|
||||
//! its timing.
|
||||
//! - **Finished by the waiter that saw it, one turn at a time** ([`turns`]). A waiter whose wait
|
||||
//! returned with its queue's value reached, or with a failure, makes the turn itself where none
|
||||
//! is under way: it takes every queue's batches their waiters saw reached (or the failure) and
|
||||
//! finishes them, and looks again until a look finds none. One turn runs at a time on the device:
|
||||
//! a waiter that finds one under way leaves what it saw to it, under the lock that turn's last
|
||||
//! look takes, so nothing is left behind. So a turn keeps every ordering across the queues:
|
||||
//! events reached before the scheduler is woken, fences settled before the transitions, each
|
||||
//! queue's batches in value order, and the failure drain over every queue, whose errors so never
|
||||
//! pass a queue's earlier completions (Metal runs a queue's completed handlers in commit order).
|
||||
//! No thread is woken between a batch's wait and its transition's run or post: on an Apple M3 Max (macOS
|
||||
//! 27.0.1, MoltenVK 1.4.1) beside 24 processes spinning at the utility clamp, a separate thread
|
||||
//! that the waiters woke for their batches took them 8.8 to 15.1 ms after the wake in 4 runs of 6
|
||||
//! (22 us at the median), and since a turn finishes every queue's batches, each such wait put
|
||||
//! every light queue's burst of the queue storm (`runtime_lane::queue_storms`) into its tail.
|
||||
//! While its waiter makes a turn, a queue's next batch waits for that turn to end before its wait
|
||||
//! begins; its fence and value stay signaled meanwhile.
|
||||
//! - **Published once a host wait returned for it** ([`seen`]). The host sees a batch's writes
|
||||
//! once the batch completed: its last command buffer makes them available to the host
|
||||
//! (`Barrier::to_host`), before its signal in submission order, and the host's reads come after
|
||||
//! a host wait for that signal. Vulkan orders host operations after a signal only through a
|
||||
//! wait: "signal operations happening before host operations that wait on them"
|
||||
//! system-synchronize-with them (the memory model), and a fence's "execution dependency is
|
||||
//! defined by waiting for a fence to become signaled, either via `vkWaitForFences` or by
|
||||
//! polling on `vkGetFenceStatus`". It gives `vkGetSemaphoreCounterValue` no such dependency (its
|
||||
//! value "may immediately be out of date"). So a value the read shows past the one a wait
|
||||
//! returned for (later batches that completed meanwhile, or the front's after a wait that ran
|
||||
//! out) is waited for in turn, a wait that returns at once ("If the condition is satisfied when
|
||||
//! `vkWaitSemaphores` is called, then `vkWaitSemaphores` returns immediately"), before it is
|
||||
//! published: one call more, and only where the read ran ahead.
|
||||
//! - **Waits are bounded.** A waiter waits at most [`WAIT_SLICE`] at a time, so a stop is seen
|
||||
//! promptly and a lost device is reported by the next wait.
|
||||
//! promptly and a lost device is reported by the next wait. A wait that ran out its slice
|
||||
//! although its fence or value was signaled when the waiter looked again is a wake it missed (or
|
||||
//! a signal in the slice's last moment), counted (`WorkCounts::missed_completion_wakes`), which
|
||||
//! the completion test holds to none.
|
||||
//! - **Exit.** Each wait is a section of the exit guard ([`exit_guard`]), so an exit waits at most
|
||||
//! one slice for it; once the process is exiting, the threads end.
|
||||
//! one slice for it; once the process is exiting, the waiters end.
|
||||
//! - **A drain waits for the waiters.** A failed wait or read finishes every pending batch, which
|
||||
//! may destroy their fences (`let_go`); the batches are taken only once no waiter is waiting,
|
||||
//! and none arms until they are.
|
||||
//! - **Let go before the waiters return.** The thread holds a command buffer through a [`Hold`],
|
||||
//! - **Let go before the waiters return.** A turn holds a command buffer through a [`Hold`],
|
||||
//! and lets go of everything it holds for a batch (its events, then the command buffer, or
|
||||
//! hands the hold to the transition it posts) before the next; the command buffer's waiters
|
||||
//! return once no hold is left ([`gate`](super::gate)). It reaches the device through a pending
|
||||
@@ -47,8 +100,8 @@
|
||||
//! go of what they used, once the device's queues were drained (`Device::drain_queues`): MoltenVK
|
||||
//! 1.4.1 reports a lost device from the first completed handler of a failed Metal command buffer,
|
||||
//! while later ones still read the command buffers' pools.
|
||||
//! - **No self-join.** The thread's drop of a command buffer's last reference can drop the
|
||||
//! device's last handle on this thread; stopping from the thread itself then only asks it to
|
||||
//! - **No self-join.** A turn's drop of a command buffer's last reference can drop the device's
|
||||
//! last handle on its waiter; stopping from a waiter then joins the others and only asks it to
|
||||
//! end.
|
||||
|
||||
use super::gate::Hold;
|
||||
@@ -69,16 +122,16 @@ use std::time::Duration;
|
||||
/// How long one wait on the timelines lasts.
|
||||
const WAIT_SLICE: Duration = Duration::from_millis(100);
|
||||
|
||||
/// One device's completion thread and its `VkQueue`s' waiters.
|
||||
/// One device's `VkQueue`s' waiters, which finish its batches.
|
||||
pub(crate) struct Completion {
|
||||
watch: Arc<Watch>,
|
||||
threads: Mutex<Vec<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
/// What the threads and the scheduler share.
|
||||
/// What the waiters and the scheduler share.
|
||||
struct Watch {
|
||||
pending: Mutex<Pending>,
|
||||
/// Notified on every change a thread waits for: a batch watched, a value reached, a wait
|
||||
/// Notified on every change a waiter waits for: a batch watched, a value reached, a wait
|
||||
/// ended, batches finished or taken, a failure, a stop, an exit.
|
||||
wake: Condvar,
|
||||
}
|
||||
@@ -94,12 +147,14 @@ struct Pending {
|
||||
failed: Option<CommandBufferError>,
|
||||
/// The pending batches are being taken (`take_pending`): no waiter arms.
|
||||
holding: bool,
|
||||
/// The process is exiting: every thread ends, and what is pending stays pending.
|
||||
/// A waiter makes a turn ([`turns`]): another leaves what it saw to that turn.
|
||||
turning: bool,
|
||||
/// The process is exiting: every waiter ends, and what is pending stays pending.
|
||||
exiting: bool,
|
||||
stopping: bool,
|
||||
}
|
||||
|
||||
/// A submitted batch the thread waits for.
|
||||
/// A submitted batch its queue's waiter waits for.
|
||||
pub(crate) struct Submitted {
|
||||
/// The value its queue's timeline reaches once it completed.
|
||||
pub(crate) value: u64,
|
||||
@@ -115,8 +170,8 @@ pub(crate) struct Submitted {
|
||||
}
|
||||
|
||||
impl Completion {
|
||||
/// Start the threads of a device with `queues` `VkQueue`s: the completion thread and one
|
||||
/// waiter per `VkQueue`; refused when the host cannot start one.
|
||||
/// Start the waiters of a device with `queues` `VkQueue`s, one per `VkQueue`; refused when the
|
||||
/// host cannot start one.
|
||||
pub(crate) fn start(queues: usize) -> Result<Completion, Error> {
|
||||
let watch = Arc::new(Watch {
|
||||
pending: Mutex::new(Pending {
|
||||
@@ -125,6 +180,7 @@ impl Completion {
|
||||
waiting: vec![false; queues],
|
||||
failed: None,
|
||||
holding: false,
|
||||
turning: false,
|
||||
exiting: false,
|
||||
stopping: false,
|
||||
}),
|
||||
@@ -135,14 +191,6 @@ impl Completion {
|
||||
threads: Mutex::new(Vec::new()),
|
||||
};
|
||||
let spawned: std::io::Result<()> = (|| {
|
||||
let thread = {
|
||||
let watch = Arc::clone(&watch);
|
||||
exit_guard::spawn_user_interactive(
|
||||
std::thread::Builder::new().name("metal2vulkan-completion".into()),
|
||||
move || run(&watch),
|
||||
)?
|
||||
};
|
||||
lock(&completion.threads).push(thread);
|
||||
for queue in 0..queues {
|
||||
let watch = Arc::clone(&watch);
|
||||
let waiter = exit_guard::spawn_user_interactive(
|
||||
@@ -169,8 +217,8 @@ impl Completion {
|
||||
self.watch.wake.notify_all();
|
||||
}
|
||||
|
||||
/// Ask the threads to end once nothing is pending, and wait for each but this one (the
|
||||
/// device's last handle can drop on one of them).
|
||||
/// Ask the waiters to end once nothing is pending, and wait for each but this one (the
|
||||
/// device's last handle can drop on one of them, in its turn).
|
||||
pub(crate) fn stop(&self) {
|
||||
lock(&self.watch.pending).stopping = true;
|
||||
self.watch.wake.notify_all();
|
||||
@@ -184,8 +232,7 @@ impl Completion {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the completion thread found: batches whose values their queues reached, or a waiter's
|
||||
/// failure.
|
||||
/// What a turn's look found: batches whose values their queues reached, or a waiter's failure.
|
||||
enum Turn {
|
||||
Finished(Vec<(usize, Submitted)>),
|
||||
Failed(CommandBufferError),
|
||||
@@ -203,113 +250,124 @@ fn wait<'a>(
|
||||
.0
|
||||
}
|
||||
|
||||
/// The process is exiting: every thread ends.
|
||||
/// The process is exiting: every waiter ends.
|
||||
fn exit(watch: &Watch) {
|
||||
lock(&watch.pending).exiting = true;
|
||||
watch.wake.notify_all();
|
||||
}
|
||||
|
||||
/// The completion thread's loop.
|
||||
fn run(watch: &Watch) {
|
||||
/// Turns, made by the waiter that called this once it set `turning` (the module docs): each looks
|
||||
/// for the batches the queues' waiters saw reached, or a waiter's failure, and finishes them
|
||||
/// ([`finish`]), or finishes every pending batch with the failure ([`fail`]); until a look finds
|
||||
/// nothing, which clears `turning` under the lock it took: a waiter that saw a value reached while
|
||||
/// `turning` was set left it to that look. `lists` is the waiter's own, kept from turn to turn: a
|
||||
/// turn fills them again within the room the earlier ones left, so in a steady state it allocates
|
||||
/// none. False once the process is exiting.
|
||||
fn turns(watch: &Watch, lists: &mut FenceLists) -> bool {
|
||||
loop {
|
||||
// The batches whose values their queues' waiters saw reached, or a waiter's failure.
|
||||
let turn = {
|
||||
let mut pending = lock(&watch.pending);
|
||||
loop {
|
||||
if pending.exiting {
|
||||
return;
|
||||
}
|
||||
if let Some(error) = pending.failed.take() {
|
||||
// No waiter arms until the pending batches are taken (`fail`).
|
||||
pending.holding = true;
|
||||
break Turn::Failed(error);
|
||||
}
|
||||
if pending.exiting {
|
||||
return false;
|
||||
}
|
||||
if let Some(error) = pending.failed.take() {
|
||||
// No waiter arms until the pending batches are taken (`fail`).
|
||||
pending.holding = true;
|
||||
Turn::Failed(error)
|
||||
} else {
|
||||
let finished = reached(&mut pending);
|
||||
if !finished.is_empty() {
|
||||
break Turn::Finished(finished);
|
||||
if finished.is_empty() {
|
||||
pending.turning = false;
|
||||
return true;
|
||||
}
|
||||
if pending.stopping && pending.queues.iter().all(VecDeque::is_empty) {
|
||||
return;
|
||||
}
|
||||
pending = wait(watch, pending);
|
||||
Turn::Finished(finished)
|
||||
}
|
||||
};
|
||||
// A waiter whose front finished may arm for its queue's next.
|
||||
watch.wake.notify_all();
|
||||
let finished = match turn {
|
||||
Turn::Finished(finished) => finished,
|
||||
Turn::Failed(error) => {
|
||||
fail(watch, Vec::new(), error);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// The host time the batches were seen complete: an uncalibrated command buffer's GPU end
|
||||
// (`gpu_time.rs`).
|
||||
let seen = gpu_time::host_nanos();
|
||||
// The device, held while the batches finish (each holds it meanwhile).
|
||||
let Some(device) = finished
|
||||
.first()
|
||||
.map(|(_, batch)| batch.buffer.device().clone())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// Their event signals are seen before the scheduler looks again: a batch whose submission
|
||||
// checks wait for a GPU signal to land may now go.
|
||||
for (_, batch) in &finished {
|
||||
for (event, index) in &batch.signals {
|
||||
event.reached(*index);
|
||||
}
|
||||
}
|
||||
// A batch held at its gate, or for a GPU signal to land, may now go (`scheduler`).
|
||||
device.shared().scheduler.completions();
|
||||
// Every finished batch's fence is waited for: where a queue's failures are relayed each
|
||||
// batch has one (`device/relay.rs`), signaled after the driver reported its failure.
|
||||
let mut ending = Vec::new();
|
||||
let mut fences = Vec::new();
|
||||
for (queue, batch) in finished {
|
||||
let Submitted {
|
||||
buffer,
|
||||
last,
|
||||
fence,
|
||||
..
|
||||
} = batch;
|
||||
fences.extend(fence.map(|fence| (queue, fence)));
|
||||
if last {
|
||||
lock(&buffer.state).times.completed = seen;
|
||||
ending.push(buffer);
|
||||
}
|
||||
}
|
||||
let settled = settle(&device, &fences);
|
||||
// Their GPU times' timestamps are read, and their slots given back, and their GPU times
|
||||
// placed among their queues' in order, before their transitions are posted: a completed
|
||||
// handler reads the times. A section, as each poll.
|
||||
if let Settled::Signaled = settled {
|
||||
let Some(_busy) = exit_guard::enter() else {
|
||||
exit(watch);
|
||||
return;
|
||||
};
|
||||
for buffer in &ending {
|
||||
buffer.read_stamps();
|
||||
buffer.place_gpu_times();
|
||||
}
|
||||
}
|
||||
drop(device);
|
||||
match settled {
|
||||
Settled::Signaled => {
|
||||
for buffer in ending {
|
||||
CommandBufferShared::post_finished(buffer, Ok(()));
|
||||
match turn {
|
||||
Turn::Finished(finished) => {
|
||||
if !finish(watch, lists, finished) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// What is pending stays pending, as Metal's does.
|
||||
Settled::Exiting => {
|
||||
exit(watch);
|
||||
return;
|
||||
}
|
||||
Settled::Failed(error) => fail(watch, ending, error),
|
||||
Turn::Failed(error) => fail(watch, Vec::new(), error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finish `finished`, the batches a turn took, each queue's in its value order: their events
|
||||
/// reached, the scheduler told, their fences settled, then, for each that ends its command buffer,
|
||||
/// its timestamps read and its GPU times placed, and its transition posted. False once the
|
||||
/// process is exiting.
|
||||
fn finish(watch: &Watch, lists: &mut FenceLists, finished: Vec<(usize, Submitted)>) -> bool {
|
||||
// The host time the batches were seen complete: an uncalibrated command buffer's GPU end
|
||||
// (`gpu_time.rs`).
|
||||
let seen = gpu_time::host_nanos();
|
||||
// The device, held while the batches finish (each holds it meanwhile).
|
||||
let Some(device) = finished
|
||||
.first()
|
||||
.map(|(_, batch)| batch.buffer.device().clone())
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
// Their event signals are seen before the scheduler looks again: a batch whose submission
|
||||
// checks wait for a GPU signal to land may now go.
|
||||
for (_, batch) in &finished {
|
||||
for (event, index) in &batch.signals {
|
||||
event.reached(*index);
|
||||
}
|
||||
}
|
||||
// A batch held at its gate, or for a GPU signal to land, may now go (`scheduler`).
|
||||
device.shared().scheduler.completions();
|
||||
// Every finished batch's fence is waited for: where a queue's failures are relayed each
|
||||
// batch has one (`device/relay.rs`), signaled after the driver reported its failure.
|
||||
let mut ending = Vec::new();
|
||||
lists.gathered.clear();
|
||||
for (queue, batch) in finished {
|
||||
let Submitted {
|
||||
buffer,
|
||||
last,
|
||||
fence,
|
||||
..
|
||||
} = batch;
|
||||
lists.gathered.extend(fence.map(|fence| (queue, fence)));
|
||||
if last {
|
||||
lock(&buffer.state).times.completed = seen;
|
||||
ending.push(buffer);
|
||||
}
|
||||
}
|
||||
let settled = settle(&device, lists);
|
||||
// Their GPU times' timestamps are read, and their slots given back, and their GPU times
|
||||
// placed among their queues' in order, before their transitions are posted: a completed
|
||||
// handler reads the times. A section, as each poll.
|
||||
if let Settled::Signaled = settled {
|
||||
let Some(_busy) = exit_guard::enter() else {
|
||||
exit(watch);
|
||||
return false;
|
||||
};
|
||||
for buffer in &ending {
|
||||
buffer.read_stamps();
|
||||
buffer.place_gpu_times();
|
||||
}
|
||||
}
|
||||
drop(device);
|
||||
match settled {
|
||||
Settled::Signaled => {
|
||||
for buffer in ending {
|
||||
CommandBufferShared::finish_here(buffer, Ok(()));
|
||||
}
|
||||
}
|
||||
// What is pending stays pending, as Metal's does.
|
||||
Settled::Exiting => {
|
||||
exit(watch);
|
||||
return false;
|
||||
}
|
||||
Settled::Failed(error) => fail(watch, ending, error),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Every pending batch, and the command buffers `ending` whose work completed (their fences let
|
||||
/// go of already), finish with `error`: a wait or a read failed. The pending batches' fences are
|
||||
/// let go of ([`let_go`]).
|
||||
@@ -366,22 +424,40 @@ fn let_go(device: &Device, queue: usize, fence: vk::Fence) {
|
||||
enum Settled {
|
||||
/// Each is signaled, reset and given back.
|
||||
Signaled,
|
||||
/// The process is exiting: the thread ends.
|
||||
/// The process is exiting: the waiters end.
|
||||
Exiting,
|
||||
/// A wait or a reset failed: the command buffers finish with this error, and the fences are
|
||||
/// let go of ([`let_go`]).
|
||||
Failed(CommandBufferError),
|
||||
}
|
||||
|
||||
/// Wait for `fences` of `device` (each of a `VkQueue`) to be signaled, a slice at a time, each
|
||||
/// wait a section of the exit guard; then reset them and give them back to the device's idle
|
||||
/// fences, with the marks before them where the queue's failures are relayed
|
||||
/// (`device/relay.rs`), which leave its submissions in flight first.
|
||||
fn settle(device: &Device, fences: &[(usize, vk::Fence)]) -> Settled {
|
||||
if fences.is_empty() {
|
||||
/// A turn's fences, in lists each waiter keeps from turn to turn ([`turns`]).
|
||||
#[derive(Default)]
|
||||
struct FenceLists {
|
||||
/// The fences of the batches the turn finished, each with its `VkQueue`.
|
||||
gathered: Vec<(usize, vk::Fence)>,
|
||||
/// Those the turn waits for, then resets and gives back, the relayed queues' marks with them.
|
||||
waited: Vec<vk::Fence>,
|
||||
/// One relayed queue's of `gathered`.
|
||||
queue: Vec<vk::Fence>,
|
||||
}
|
||||
|
||||
/// Wait for `lists.gathered`'s fences of `device` (each of a `VkQueue`) to be signaled, a slice at
|
||||
/// a time, each wait a section of the exit guard; then reset them and give them back to the
|
||||
/// device's idle fences, with the marks before them where the queue's failures are relayed
|
||||
/// (`device/relay.rs`), which leave its submissions in flight first. `lists.waited` and
|
||||
/// `lists.queue` are filled here.
|
||||
fn settle(device: &Device, lists: &mut FenceLists) -> Settled {
|
||||
let FenceLists {
|
||||
gathered,
|
||||
waited,
|
||||
queue: ours,
|
||||
} = lists;
|
||||
if gathered.is_empty() {
|
||||
return Settled::Signaled;
|
||||
}
|
||||
let waited_for: Vec<vk::Fence> = fences.iter().map(|&(_, fence)| fence).collect();
|
||||
waited.clear();
|
||||
waited.extend(gathered.iter().map(|&(_, fence)| fence));
|
||||
loop {
|
||||
let Some(_busy) = exit_guard::enter() else {
|
||||
return Settled::Exiting;
|
||||
@@ -389,30 +465,29 @@ fn settle(device: &Device, fences: &[(usize, vk::Fence)]) -> Settled {
|
||||
let shared = device.shared();
|
||||
let raw = shared.vk();
|
||||
// SAFETY: the fences are the device's, each signaled by a submission made.
|
||||
let waited =
|
||||
unsafe { raw.wait_for_fences(&waited_for, true, WAIT_SLICE.as_nanos() as u64) };
|
||||
let signaled = unsafe { raw.wait_for_fences(waited, true, WAIT_SLICE.as_nanos() as u64) };
|
||||
exit_guard::called(Call::WaitForFences);
|
||||
let error = match waited {
|
||||
let error = match signaled {
|
||||
Ok(()) => {
|
||||
// Out of the queues' submissions in flight before they go back: every
|
||||
// submission before a signaled fence's completed too.
|
||||
let mut all = waited_for.clone();
|
||||
for (queue, flights) in shared.relayed_queues() {
|
||||
let ours: Vec<vk::Fence> = fences
|
||||
.iter()
|
||||
.filter(|&&(q, _)| q == queue)
|
||||
.map(|&(_, fence)| fence)
|
||||
.collect();
|
||||
all.extend(flights.settled(&ours));
|
||||
ours.clear();
|
||||
ours.extend(
|
||||
(gathered.iter())
|
||||
.filter(|&&(q, _)| q == queue)
|
||||
.map(|&(_, fence)| fence),
|
||||
);
|
||||
flights.settled(ours, waited);
|
||||
}
|
||||
// SAFETY: each fence is signaled and its submission completed.
|
||||
let reset = unsafe { raw.reset_fences(&all) };
|
||||
let reset = unsafe { raw.reset_fences(waited) };
|
||||
exit_guard::called(Call::ResetFences);
|
||||
match reset {
|
||||
Ok(()) => {
|
||||
// SAFETY: each fence is unsignaled and in no pending submission; inside
|
||||
// a section.
|
||||
unsafe { shared.fences.give(raw, all) };
|
||||
unsafe { shared.fences.give(raw, waited) };
|
||||
return Settled::Signaled;
|
||||
}
|
||||
Err(error) => error,
|
||||
@@ -422,7 +497,7 @@ fn settle(device: &Device, fences: &[(usize, vk::Fence)]) -> Settled {
|
||||
Err(error) => error,
|
||||
};
|
||||
let failed = failure(device, error);
|
||||
for &(queue, fence) in fences {
|
||||
for &(queue, fence) in gathered.iter() {
|
||||
let_go(device, queue, fence);
|
||||
}
|
||||
return Settled::Failed(failed);
|
||||
@@ -477,17 +552,28 @@ struct Front {
|
||||
}
|
||||
|
||||
/// `VkQueue` `queue`'s waiter (the module docs): it waits for its queue's first pending batch
|
||||
/// past the value it saw reached, a slice at a time, and hands what the timeline reached, or a
|
||||
/// failure, to the completion thread.
|
||||
/// past the value it saw reached, a slice at a time, and makes the turn that finishes what its
|
||||
/// queue reached, or a failure, where no turn is under way ([`turns`]); else it leaves them to the
|
||||
/// turn under way.
|
||||
fn wait_for_queue(watch: &Watch, queue: usize) {
|
||||
exit_guard::serves_completion();
|
||||
// The fence lists of the turns it makes.
|
||||
let mut lists = FenceLists::default();
|
||||
loop {
|
||||
// The front to wait for, and the device, reached through it (held only for the wait).
|
||||
let (front, device) = {
|
||||
// The front to wait for, and the device, reached through it (held only for the wait); or
|
||||
// none, for a turn: its queue holds batches it reached that no turn took yet (a failed
|
||||
// command buffer's end, watched at a value its queue reached), or a waiter failed, and no
|
||||
// turn is under way.
|
||||
let armed = {
|
||||
let mut pending = lock(&watch.pending);
|
||||
loop {
|
||||
if pending.exiting {
|
||||
return;
|
||||
}
|
||||
if !pending.turning && due(&pending, queue) {
|
||||
pending.turning = true;
|
||||
break None;
|
||||
}
|
||||
let armable = !pending.holding && pending.failed.is_none();
|
||||
let armed = match pending.queues[queue].front() {
|
||||
Some(batch) if armable && batch.value > pending.reached[queue] => {
|
||||
@@ -502,12 +588,18 @@ fn wait_for_queue(watch: &Watch, queue: usize) {
|
||||
};
|
||||
if let Some(armed) = armed {
|
||||
pending.waiting[queue] = true;
|
||||
break armed;
|
||||
break Some(armed);
|
||||
}
|
||||
pending = wait(watch, pending);
|
||||
}
|
||||
};
|
||||
// The wait is a section of the exit guard; once the process is exiting the threads end,
|
||||
let Some((front, device)) = armed else {
|
||||
if !turns(watch, &mut lists) {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
};
|
||||
// The wait is a section of the exit guard; once the process is exiting the waiters end,
|
||||
// and what is pending stays pending, as Metal's does.
|
||||
let polled = match exit_guard::enter() {
|
||||
Some(busy) => {
|
||||
@@ -538,16 +630,33 @@ fn wait_for_queue(watch: &Watch, queue: usize) {
|
||||
pending.failed.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
// This waiter finishes what it saw, where no turn is under way; the one under way takes
|
||||
// it at its next look, which takes this lock.
|
||||
let turn = !pending.turning && due(&pending, queue);
|
||||
pending.turning |= turn;
|
||||
drop(pending);
|
||||
watch.wake.notify_all();
|
||||
if turn && !turns(watch, &mut lists) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a turn has work that `queue`'s waiter sees: a waiter's failure, or its queue's first
|
||||
/// pending batch reached.
|
||||
fn due(pending: &Pending, queue: usize) -> bool {
|
||||
pending.failed.is_some()
|
||||
|| pending.queues[queue]
|
||||
.front()
|
||||
.is_some_and(|batch| batch.value <= pending.reached[queue])
|
||||
}
|
||||
|
||||
/// Wait up to one slice for `front`, the first pending batch of `device`'s `VkQueue` `queue`: for
|
||||
/// its fence where it has one, else for the queue's timeline to reach its value, a
|
||||
/// wait of that one object (the module docs). Then read the timeline and publish it: the value it
|
||||
/// reached, at least the front's where its fence was signaled. A failed wait or read is the error
|
||||
/// every pending command buffer finishes with.
|
||||
/// wait of that one object (the module docs). Then read the timeline and publish what a host wait
|
||||
/// returned for ([`seen`]): the front's where its wait returned, and the value read where a wait
|
||||
/// for it returned too. A failed wait or read is the error every pending command buffer finishes
|
||||
/// with.
|
||||
///
|
||||
/// MoltenVK signals a fence from its Metal command buffer's completion handler, where it wakes a
|
||||
/// timeline wait from a shared event's listener (MoltenVK's `MVKSync.mm`; 6 to 11 us later).
|
||||
@@ -561,7 +670,23 @@ fn poll(device: &Device, queue: usize, front: Front) -> Result<u64, CommandBuffe
|
||||
let shared = device.shared();
|
||||
let raw = shared.vk();
|
||||
let slot = &shared.queues[queue];
|
||||
let signaled = match front.fence {
|
||||
// A wait of up to one slice for the queue's timeline to reach `value`: whether it did.
|
||||
let reaches = |value: u64| {
|
||||
let semaphores = [slot.timeline];
|
||||
let values = [value];
|
||||
let info = vk::SemaphoreWaitInfo::default()
|
||||
.semaphores(&semaphores)
|
||||
.values(&values);
|
||||
// SAFETY: the semaphore is the device's timeline, live while the device is (held here).
|
||||
let waited = unsafe { raw.wait_semaphores(&info, WAIT_SLICE.as_nanos() as u64) };
|
||||
exit_guard::called(Call::WaitSemaphores);
|
||||
match waited {
|
||||
Ok(()) => Ok(true),
|
||||
Err(vk::Result::TIMEOUT) => Ok(false),
|
||||
Err(error) => Err(failure(device, error)),
|
||||
}
|
||||
};
|
||||
let waited = match front.fence {
|
||||
Some(fence) => {
|
||||
// SAFETY: the fence is the device's, in a submission made and not yet reset (its
|
||||
// batch is pending, and is not taken while this waits: `take_pending`), live while
|
||||
@@ -576,34 +701,70 @@ fn poll(device: &Device, queue: usize, front: Front) -> Result<u64, CommandBuffe
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let semaphores = [slot.timeline];
|
||||
let values = [front.value];
|
||||
let info = vk::SemaphoreWaitInfo::default()
|
||||
.semaphores(&semaphores)
|
||||
.values(&values);
|
||||
// SAFETY: the semaphore is the device's timeline, live while the device is (held
|
||||
// here).
|
||||
let waited = unsafe { raw.wait_semaphores(&info, WAIT_SLICE.as_nanos() as u64) };
|
||||
exit_guard::called(Call::WaitSemaphores);
|
||||
shared.counts.timeline_wait();
|
||||
match waited {
|
||||
Ok(()) | Err(vk::Result::TIMEOUT) => false,
|
||||
Err(error) => return Err(failure(device, error)),
|
||||
}
|
||||
reaches(front.value)?
|
||||
}
|
||||
};
|
||||
// SAFETY: the semaphore is the device's timeline, live while the device is (held here).
|
||||
let value = unsafe { raw.get_semaphore_counter_value(slot.timeline) };
|
||||
let read = unsafe { raw.get_semaphore_counter_value(slot.timeline) };
|
||||
exit_guard::called(Call::GetSemaphoreCounterValue);
|
||||
let value = value.map_err(|error| failure(device, error))?;
|
||||
let value = match signaled {
|
||||
true => value.max(front.value),
|
||||
false => value,
|
||||
};
|
||||
let read = read.map_err(|error| failure(device, error))?;
|
||||
// A wait that ran out its slice although what it waited for was signaled by now: a wake it
|
||||
// missed, counted (`WorkCounts::missed_completion_wakes`). A timeline is looked at by its
|
||||
// read; a fence by a wait of no time: "If timeout is zero, then vkWaitForFences does not
|
||||
// wait, but simply returns the current state of the fences".
|
||||
if !waited {
|
||||
let signaled = match front.fence {
|
||||
Some(fence) => {
|
||||
// SAFETY: as the wait's above.
|
||||
let looked = unsafe { raw.wait_for_fences(&[fence], true, 0) };
|
||||
exit_guard::called(Call::WaitForFences);
|
||||
looked.is_ok()
|
||||
}
|
||||
None => read >= front.value,
|
||||
};
|
||||
if signaled {
|
||||
shared.counts.missed_completion_wake();
|
||||
}
|
||||
}
|
||||
let value = seen(
|
||||
slot.completed_value(),
|
||||
waited.then_some(front.value),
|
||||
read,
|
||||
reaches,
|
||||
)?;
|
||||
slot.completed(value);
|
||||
// Freed memory that waits for the batches in flight goes once they completed, on a handler
|
||||
// thread (`freed_memory.rs`).
|
||||
if let Some(parking) = shared.parking.get() {
|
||||
parking.completed(queue, value);
|
||||
parking.after_completion(device);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// The value of a queue's timeline the host may publish as reached (the module docs): `known`,
|
||||
/// the one it published before; `waited`, the one a wait just returned for (a timeline's wait,
|
||||
/// or the front's fence, whose signal follows its timeline's in signal operation order, whatever
|
||||
/// the read shows); `read`, the timeline's read after that wait. A read past both is a value
|
||||
/// no host wait returned for yet: `reaches` waits for it, which returns at once where the read
|
||||
/// was right, and it is published only where that wait returned.
|
||||
pub(crate) fn seen<E>(
|
||||
known: u64,
|
||||
waited: Option<u64>,
|
||||
read: u64,
|
||||
reaches: impl FnOnce(u64) -> Result<bool, E>,
|
||||
) -> Result<u64, E> {
|
||||
let confirmed = waited.map_or(known, |waited| waited.max(known));
|
||||
if read <= confirmed {
|
||||
return Ok(confirmed);
|
||||
}
|
||||
Ok(match reaches(read)? {
|
||||
true => read,
|
||||
false => confirmed,
|
||||
})
|
||||
}
|
||||
|
||||
/// The command-buffer error of a failed wait, recording a lost device.
|
||||
fn failure(device: &Device, error: vk::Result) -> CommandBufferError {
|
||||
match error {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The fences that end command buffers, where the driver needs them: the batch that ends a command
|
||||
//! buffer signals one with its submission, and the completion thread finishes the command buffer
|
||||
//! buffer signals one with its submission, and the completion turn finishes the command buffer
|
||||
//! only once both its queue's timeline reached the batch's value and the fence is signaled
|
||||
//! ([`completion`](super::completion)).
|
||||
//!
|
||||
@@ -18,11 +18,11 @@
|
||||
//! failures are relayed (`device/relay.rs`) still takes one for every batch, which its log of
|
||||
//! submissions in flight needs.
|
||||
//! - **Pooled, and bounded.** A fence is taken when the last batch is submitted (made only when
|
||||
//! none is idle) and given back, reset, once the completion thread saw it signaled. At most
|
||||
//! none is idle) and given back, reset, once a completion turn saw it signaled. At most
|
||||
//! [`IDLE`] wait idle; the ones beyond are released. So the fences live are the command buffers
|
||||
//! in flight plus at most [`IDLE`], whatever the number of command buffers committed.
|
||||
//! - **The exit guard's doors.** Making one is the scheduler's (inside its section), waiting for
|
||||
//! and resetting them the completion thread's (inside its sections), and every release goes
|
||||
//! and resetting them the queues' waiters' (inside their sections), and every release goes
|
||||
//! through `release.rs`; each entry point is in the guard's table and primed
|
||||
//! (`exit_guard`, `device/prime.rs`).
|
||||
|
||||
@@ -78,17 +78,15 @@ impl Fences {
|
||||
}
|
||||
|
||||
/// Give back `fences` of `device`, each unsignaled (reset, or never submitted) and in no
|
||||
/// pending submission: kept idle up to [`IDLE`], the rest released.
|
||||
/// pending submission: kept idle up to [`IDLE`], the rest released. `fences` is left empty,
|
||||
/// its room kept for the caller's next ones.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// As above.
|
||||
pub(crate) unsafe fn give(
|
||||
&self,
|
||||
device: &ash::Device,
|
||||
fences: impl IntoIterator<Item = vk::Fence>,
|
||||
) {
|
||||
for fence in self.keep(fences) {
|
||||
pub(crate) unsafe fn give(&self, device: &ash::Device, fences: &mut Vec<vk::Fence>) {
|
||||
self.keep(fences);
|
||||
for fence in fences.drain(..) {
|
||||
// SAFETY: the caller's: no pending submission uses it.
|
||||
unsafe { release::object(device, fence) };
|
||||
}
|
||||
@@ -112,17 +110,11 @@ impl Fences {
|
||||
lock(&self.idle).pop()
|
||||
}
|
||||
|
||||
/// Keep `fences` idle up to [`IDLE`]; the ones beyond, for the caller to release.
|
||||
pub(crate) fn keep(&self, fences: impl IntoIterator<Item = vk::Fence>) -> Vec<vk::Fence> {
|
||||
/// Keep `fences` idle up to [`IDLE`], the first of them first; the ones beyond stay in
|
||||
/// `fences`, for the caller to release.
|
||||
pub(crate) fn keep(&self, fences: &mut Vec<vk::Fence>) {
|
||||
let mut idle = lock(&self.idle);
|
||||
let mut over = Vec::new();
|
||||
for fence in fences {
|
||||
if idle.len() < IDLE {
|
||||
idle.push(fence);
|
||||
} else {
|
||||
over.push(fence);
|
||||
}
|
||||
}
|
||||
over
|
||||
let kept = IDLE.saturating_sub(idle.len()).min(fences.len());
|
||||
idle.extend(fences.drain(..kept));
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,14 @@
|
||||
//! lets the pages go, their deallocator run, where no submitted command buffer holds them
|
||||
//! (the question, answered without revoking anything). From the first submission on it holds them
|
||||
//! until it completes, so a submitted command buffer keeps the pages it took, as Metal's does
|
||||
//! (table 3: a submitted command buffer never sees the new pages).
|
||||
//! (table 3: a submitted command buffer never sees the new pages). A root table recorded
|
||||
//! before then, by a rebind's encoding again (`reencode.rs`) or a host step, holds the table
|
||||
//! (`State::hold_live`) until the first submission, which lets go of it where the list changed
|
||||
//! meanwhile: at once, as Metal lets a released buffer go, but on a handler thread
|
||||
//! (`Device::let_go_elsewhere`), as its last hold of a released buffer's pages runs that
|
||||
//! buffer's deallocator, which may not run on the scheduler's thread under its locks. The
|
||||
//! deallocator's wait from the release until then, past Metal's, is announced
|
||||
//! (`host-deallocator-delayed`).
|
||||
//! - **Resolved again where the list changed.** Where the live buffers' list changed since the
|
||||
//! commit (a buffer made or gone, a rebind), the submission lists again what the commit listed
|
||||
//! (`LiveBuffers::reach`, a rebind having ended its use), makes its resident set again of the
|
||||
@@ -176,8 +183,11 @@ impl State {
|
||||
..
|
||||
}) => {
|
||||
// The list unchanged, the device keeps the table: the upgrade is not its last
|
||||
// hold.
|
||||
if let Some(table) = table.upgrade().filter(|_| *generation == now) {
|
||||
// hold. Changed, the table is not upgraded at all: an upgrade let go of here,
|
||||
// under the scheduler's lock and this state's, could be the last hold of a gone
|
||||
// buffer's pages, whose release runs the program's code.
|
||||
let kept = (*generation == now).then(|| table.upgrade()).flatten();
|
||||
if let Some(table) = kept {
|
||||
if let Some(resident) = &mut self.resident {
|
||||
resident.live = Live::Held(table);
|
||||
}
|
||||
@@ -203,7 +213,8 @@ impl State {
|
||||
}
|
||||
|
||||
/// Its resident set made again of the live buffers as they stand now and `fresh`, what its
|
||||
/// encoders made resident as it lies now, and every noted root table pointed at it.
|
||||
/// encoders made resident as it lies now, and every noted root table pointed at it. A table
|
||||
/// it held goes at once, on a handler thread.
|
||||
fn remake_resident(&mut self, device: &Device, fresh: &[ResidentRange]) -> Result<(), Error> {
|
||||
let live = device.shared().live_buffers.table(device)?;
|
||||
let set = live.set();
|
||||
@@ -234,12 +245,24 @@ impl State {
|
||||
count,
|
||||
)?;
|
||||
}
|
||||
self.resident = Some(Resident {
|
||||
let replaced = self.resident.replace(Resident {
|
||||
live: Live::Held(live),
|
||||
merged,
|
||||
address,
|
||||
count,
|
||||
});
|
||||
// A table held already, made of the list before it changed, may hold a gone buffer's
|
||||
// pages last, whose release runs the program's code (a deallocator), which may not run
|
||||
// here: on the scheduler's thread, under its lock and this state's. It goes at once all
|
||||
// the same, as Metal lets go of a buffer no submitted command buffer holds, on a handler
|
||||
// thread.
|
||||
if let Some(Resident {
|
||||
live: Live::Held(table),
|
||||
..
|
||||
}) = replaced
|
||||
{
|
||||
device.let_go_elsewhere(Box::new(table));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -253,8 +276,8 @@ impl State {
|
||||
/// `Ok(false)`, changing nothing, while a rebind since its commit has encoders of it, which
|
||||
/// `buffer`'s rebinds mark, to encode again (`reencode.rs`): read under the lock its rebinds
|
||||
/// mark them under, so a rebind comes either before this submission (which waits for them)
|
||||
/// or after it (which keeps the old pages). From here it waits for no rebind's replay, and
|
||||
/// its encoders' logs go with this batch's submission (`Submission::logs`).
|
||||
/// or after it (which keeps the old pages). From here it waits for no rebind's replay; its
|
||||
/// encoders' logs stay until its release (`CommandBufferShared::complete`).
|
||||
pub(super) fn first_submission(
|
||||
&mut self,
|
||||
device: &Device,
|
||||
@@ -308,6 +331,12 @@ impl State {
|
||||
}
|
||||
}
|
||||
self.hold_live(device)?;
|
||||
// The tables host steps before now resolved against go at once, off this thread, under
|
||||
// whose locks the last hold of a released buffer's pages may not go
|
||||
// (`State::keep_stepped_table`).
|
||||
for earlier in self.stepped_tables.drain(..) {
|
||||
device.let_go_elsewhere(Box::new(earlier));
|
||||
}
|
||||
// A replay's resident set holds where every range of it lies as it did at the commit.
|
||||
if replays {
|
||||
let live = shared.live_buffers.table(device)?;
|
||||
|
||||
@@ -8,6 +8,18 @@
|
||||
//! 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, a capture's translation), 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.
|
||||
@@ -127,7 +139,7 @@ impl Gate {
|
||||
}
|
||||
}
|
||||
|
||||
/// A reference a runtime thread holds (the scheduler's, the completion thread's, a queue
|
||||
/// 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> {
|
||||
@@ -158,6 +170,30 @@ impl<T> Hold<T> {
|
||||
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> {
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
//! A batch's barrier command buffers, recorded once and submitted again.
|
||||
//!
|
||||
//! Every batch with encoders submits a command buffer of barriers alone before its first encoder
|
||||
//! (`Barrier::after_completed`, with the barrier the tracker planned for that encoder) and one
|
||||
//! after its last (`Barrier::to_host`), and one before each later encoder the tracker planned a
|
||||
//! barrier for (`submit.rs`): batch after batch, the same few lists of barriers. Each list's
|
||||
//! command buffer is recorded once, kept by the scheduler, and submitted again by a later batch
|
||||
//! once the batch that last carried it completed, its queue's timeline at that batch's value as
|
||||
//! the host saw it: the same commands, in the same place of the same submission, and no command
|
||||
//! buffer begun for them as a batch is submitted. ANV clears a command buffer's state as its pool
|
||||
//! resets it and again as it begins it (Mesa 26.2.4, `anv_cmd_state_init`), for each of a
|
||||
//! window server frame's 67 or more batches.
|
||||
//! A batch with encoders submits a command buffer of barriers before each encoder the tracker
|
||||
//! planned a barrier for (before its first, whatever was planned, where the driver's submissions
|
||||
//! stall on semaphore operations: `Barrier::after_completed`, `submit.rs`), and, where its end
|
||||
//! did not go into its last encoder's command buffer, one after its last (`Barrier::to_host`;
|
||||
//! `submit.rs`): batch after batch, the same few lists of barriers. A timed command buffer's
|
||||
//! first batch also resets its slot of the device's timestamp
|
||||
//! pools and writes the start timestamp first, in a command buffer before its first encoder (of
|
||||
//! the barrier planned for it, or of none), and its last batch writes the end timestamp in its
|
||||
//! end (`gpu_time.rs`). Each list's command buffer is recorded once, kept by the scheduler, and
|
||||
//! submitted again by a later batch once the batch that last carried it completed, its queue's
|
||||
//! timeline at that batch's value as the host saw it: the same commands, in the same place of the
|
||||
//! same submission, and no command buffer begun for them as a batch is submitted. ANV clears a
|
||||
//! command buffer's state as its pool resets it and again as it begins it (Mesa 26.2.4,
|
||||
//! `anv_cmd_state_init`, 62,776 bytes), and packs the standard sample pattern at each primary
|
||||
//! one's begin where `VK_EXT_sample_locations` is enabled (`genX(BeginCommandBuffer)`): on ms01's
|
||||
//! Iris Xe those begins were 53% of the scheduler thread's user time, two a command buffer.
|
||||
//!
|
||||
//! - **Never pending twice.** A kept command buffer is recorded without
|
||||
//! `VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT` and goes to one batch at a time: ANV chains a
|
||||
@@ -18,22 +24,35 @@
|
||||
//! takes one marks it with its own timeline value before it is submitted: a batch whose
|
||||
//! submission fails leaves that value to the queue's next batch, so the command buffer waits
|
||||
//! for that one instead.
|
||||
//! - **Timestamps, per slot.** A command buffer that writes timestamps writes them into one slot's
|
||||
//! two queries, so it is kept for its slot ([`SlotStamps`]): one per slot and list, taken again
|
||||
//! only by a batch of a later holding of that slot (`gpu_time::Slot::lease`), once the batch
|
||||
//! that last took it completed. A slot is taken again only once given back, which its command
|
||||
//! buffer does after the completion turn read its timestamps (`read_stamps`): so a kept
|
||||
//! command buffer resets the slot's queries and writes them again only after the results the
|
||||
//! last holding wrote were read. The start's reset of the slot's two queries stays in the kept
|
||||
//! command buffer, before its start timestamp. Vulkan (`vkCmdResetQueryPool`): "When executed
|
||||
//! on a queue, this command sets the status of query indices [firstQuery, firstQuery +
|
||||
//! queryCount - 1] to unavailable": at each submission of the kept command buffer again.
|
||||
//! - **Where.** On every `VkQueue` but one whose command buffers end at a fence
|
||||
//! (`fences::ends_at_fence`): MoltenVK reads a command buffer after its timeline signal and
|
||||
//! refuses one submitted again before its completed handler ran. A barrier command buffer that
|
||||
//! writes timestamps or moves the caller's images is recorded by its batch, as before.
|
||||
//! - **Bounded.** At most [`LISTS`] lists of barriers per `VkQueue`, each with at most [`KEPT`]
|
||||
//! command buffers, as many as its batches in flight at once needed: past them a batch records
|
||||
//! its own into its command buffer's pool. They live in a command pool of the queue's family,
|
||||
//! made at the first, and go with the device once its queues are idle.
|
||||
//! - **Lists that went out of use give way.** A list met while [`LISTS`] are kept replaces the
|
||||
//! one taken least lately among those no batch took in the last [`STALE`] values of the queue's
|
||||
//! timeline and whose command buffers all completed, so the lists a program's first batches met
|
||||
//! do not hold the places for its life. Its command buffers are kept for the lists' later
|
||||
//! recordings, each recorded again from the start (the pool resets one at its begin,
|
||||
//! `VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT`). Lists all in use in turn, more than
|
||||
//! [`LISTS`] of them, replace none: the first kept stay kept and the rest are recorded by their
|
||||
//! batches, where replacing one at each use would record every list at each of its uses.
|
||||
//! moves the caller's images is recorded by its batch, as before.
|
||||
//! - **Bounded.** At most [`LISTS`] lists of barriers alone per `VkQueue`, each with at most
|
||||
//! [`KEPT`] command buffers, as many as its batches in flight at once needed, and as many lists
|
||||
//! that write timestamps, each with at most [`KEPT`] slots' command buffers: past them a batch
|
||||
//! records its own into its command buffer's pool. They live in a command pool of the queue's
|
||||
//! family, made at the first, and go with the device once its queues are idle.
|
||||
//! - **Lists that went out of use give way.** A list met while [`LISTS`] of its kind are kept
|
||||
//! replaces the one taken least lately among those no batch took in the last [`STALE`] values
|
||||
//! of the queue's timeline and whose command buffers all completed, so the lists a program's
|
||||
//! first batches met do not hold the places for its life. Its command buffers are kept for the
|
||||
//! lists' later recordings, each recorded again from the start (the pool resets one at its
|
||||
//! begin, `VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT`). Lists all in use in turn, more
|
||||
//! than [`LISTS`] of them, replace none: the first kept stay kept and the rest are recorded by
|
||||
//! their batches, where replacing one at each use would record every list at each of its uses.
|
||||
//! - **Counted.** `WorkCounts::barrier_buffers_kept` and `WorkCounts::stamped_buffers_kept` count
|
||||
//! the recordings to keep, `WorkCounts::stamped_buffers_reused` the stamped ones taken again.
|
||||
//! - **Inside the scheduler's section**: every call is in the exit guard's table.
|
||||
|
||||
use crate::error::{vulkan, Error};
|
||||
@@ -60,12 +79,34 @@ pub(crate) struct KeptBarriers {
|
||||
queues: Vec<QueueKept>,
|
||||
}
|
||||
|
||||
/// The timestamps a barrier command buffer writes into a timed command buffer's slot of the
|
||||
/// device's timestamp pools (`gpu_time::Slot`): with `start`, the slot reset before its barriers
|
||||
/// and the start timestamp before them at the top of the pipe, or with `after` after them at the
|
||||
/// bottom of the pipe; with `end`, the end timestamp after them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct SlotStamps {
|
||||
/// The slot's timestamp pool.
|
||||
pub(crate) queries: vk::QueryPool,
|
||||
/// Its first query, the start; the end is the next.
|
||||
pub(crate) first: u32,
|
||||
/// The holding of the slot the batch is of (`gpu_time::Slot::lease`).
|
||||
pub(crate) lease: u64,
|
||||
pub(crate) start: bool,
|
||||
/// The start written after the barriers, once every command before them completed
|
||||
/// (`command_buffer/submit.rs`).
|
||||
pub(crate) after: bool,
|
||||
pub(crate) end: bool,
|
||||
}
|
||||
|
||||
/// One `VkQueue`'s.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct QueueKept {
|
||||
/// The pool they are made from; null until the first.
|
||||
pool: vk::CommandPool,
|
||||
/// Lists of barriers alone.
|
||||
lists: Vec<KeptList>,
|
||||
/// Lists that also write a slot's timestamps, kept per slot.
|
||||
stamped: Vec<KeptList>,
|
||||
/// The command buffers of the lists replaced, each completed, for later recordings.
|
||||
spare: Vec<vk::CommandBuffer>,
|
||||
}
|
||||
@@ -85,6 +126,9 @@ pub(crate) enum Take {
|
||||
/// The command buffers of one list of barriers, in the order of the batches that last took them.
|
||||
struct KeptList {
|
||||
barriers: Vec<Barrier>,
|
||||
/// Which timestamps its command buffers write, `(start, after, end)` as [`SlotStamps`]
|
||||
/// says: none for barriers alone.
|
||||
stamps: Option<(bool, bool, bool)>,
|
||||
buffers: VecDeque<Kept>,
|
||||
}
|
||||
|
||||
@@ -92,64 +136,104 @@ struct KeptList {
|
||||
struct Kept {
|
||||
raw: vk::CommandBuffer,
|
||||
after: u64,
|
||||
/// Where it writes timestamps: the slot's pool and first query, and the lease of the holding
|
||||
/// whose batch last took it.
|
||||
slot: Option<(vk::QueryPool, u32, u64)>,
|
||||
}
|
||||
|
||||
impl KeptList {
|
||||
/// The last batch that took one of its command buffers; every one completed with it.
|
||||
fn last(&self) -> u64 {
|
||||
self.buffers.back().map_or(0, |kept| kept.after)
|
||||
}
|
||||
}
|
||||
|
||||
impl QueueKept {
|
||||
/// What the batch that signals `at` takes for `barriers`, its queue's timeline completed
|
||||
/// through `completed`.
|
||||
pub(crate) fn take(&mut self, barriers: &[Barrier], at: u64, completed: u64) -> Take {
|
||||
let index = match self.lists.iter().position(|list| list.barriers == barriers) {
|
||||
/// What the batch that signals `at` takes for `barriers`, writing `stamps` where given, its
|
||||
/// queue's timeline completed through `completed`.
|
||||
pub(crate) fn take(
|
||||
&mut self,
|
||||
barriers: &[Barrier],
|
||||
stamps: Option<SlotStamps>,
|
||||
at: u64,
|
||||
completed: u64,
|
||||
) -> Take {
|
||||
let kind = stamps.map(|stamps| (stamps.start, stamps.after, stamps.end));
|
||||
let lists = match stamps {
|
||||
Some(_) => &mut self.stamped,
|
||||
None => &mut self.lists,
|
||||
};
|
||||
let found = lists
|
||||
.iter()
|
||||
.position(|list| list.barriers == barriers && list.stamps == kind);
|
||||
let index = match found {
|
||||
Some(index) => index,
|
||||
None if self.lists.len() < LISTS => {
|
||||
self.lists.push(KeptList {
|
||||
None if lists.len() < LISTS => {
|
||||
lists.push(KeptList {
|
||||
barriers: barriers.to_vec(),
|
||||
stamps: kind,
|
||||
buffers: VecDeque::new(),
|
||||
});
|
||||
self.lists.len() - 1
|
||||
lists.len() - 1
|
||||
}
|
||||
None => match self.out_of_use(at, completed) {
|
||||
None => match out_of_use(lists, at, completed) {
|
||||
Some(index) => {
|
||||
let list = &mut self.lists[index];
|
||||
let list = &mut lists[index];
|
||||
self.spare
|
||||
.extend(list.buffers.drain(..).map(|kept| kept.raw));
|
||||
list.barriers.clear();
|
||||
list.barriers.extend_from_slice(barriers);
|
||||
list.stamps = kind;
|
||||
index
|
||||
}
|
||||
None => return Take::Past,
|
||||
},
|
||||
};
|
||||
let list = &mut self.lists[index];
|
||||
// The batches that took them did so in their timeline values' order: the first is the
|
||||
// one that may have completed.
|
||||
if list.buffers.front().is_some_and(|k| k.after <= completed) {
|
||||
if let Some(mut taken) = list.buffers.pop_front() {
|
||||
let list = &mut lists[index];
|
||||
let Some(stamps) = stamps else {
|
||||
// The batches that took them did so in their timeline values' order: the first is
|
||||
// the one that may have completed.
|
||||
if list.buffers.front().is_some_and(|k| k.after <= completed) {
|
||||
if let Some(mut taken) = list.buffers.pop_front() {
|
||||
taken.after = at;
|
||||
let raw = taken.raw;
|
||||
list.buffers.push_back(taken);
|
||||
return Take::Kept(raw);
|
||||
}
|
||||
}
|
||||
if list.buffers.len() >= KEPT {
|
||||
return Take::Past;
|
||||
}
|
||||
return Take::Record(index);
|
||||
};
|
||||
// The slot's own: taken again by a later holding of the slot, once it completed. One
|
||||
// that is not (pending, or this holding's already) leaves the batch to record its own.
|
||||
let of_slot = list.buffers.iter().position(|kept| {
|
||||
kept.slot.is_some_and(|(queries, first, _)| {
|
||||
queries == stamps.queries && first == stamps.first
|
||||
})
|
||||
});
|
||||
match of_slot {
|
||||
Some(at_index) => {
|
||||
let ready = list.buffers[at_index].after <= completed
|
||||
&& list.buffers[at_index]
|
||||
.slot
|
||||
.is_some_and(|(_, _, lease)| lease < stamps.lease);
|
||||
if !ready {
|
||||
return Take::Past;
|
||||
}
|
||||
let Some(mut taken) = list.buffers.remove(at_index) else {
|
||||
return Take::Past;
|
||||
};
|
||||
taken.after = at;
|
||||
taken.slot = Some((stamps.queries, stamps.first, stamps.lease));
|
||||
let raw = taken.raw;
|
||||
list.buffers.push_back(taken);
|
||||
return Take::Kept(raw);
|
||||
Take::Kept(raw)
|
||||
}
|
||||
None if list.buffers.len() >= KEPT => Take::Past,
|
||||
None => Take::Record(index),
|
||||
}
|
||||
if list.buffers.len() >= KEPT {
|
||||
return Take::Past;
|
||||
}
|
||||
Take::Record(index)
|
||||
}
|
||||
|
||||
/// The list a new one replaces, its timeline at `at` and completed through `completed`: of
|
||||
/// those no batch took since `at - STALE` and whose command buffers all completed, the one
|
||||
/// taken least lately.
|
||||
fn out_of_use(&self, at: u64, completed: u64) -> Option<usize> {
|
||||
self.lists
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, list)| {
|
||||
// The last batch that took one; the list's every buffer completed with it.
|
||||
let last = list.buffers.back().map_or(0, |kept| kept.after);
|
||||
(last <= completed && last.saturating_add(STALE) <= at).then_some((last, index))
|
||||
})
|
||||
.min()
|
||||
.map(|(_, index)| index)
|
||||
}
|
||||
|
||||
/// A spare command buffer to record, where a replaced list left one.
|
||||
@@ -157,13 +241,28 @@ impl QueueKept {
|
||||
self.spare.pop()
|
||||
}
|
||||
|
||||
/// `raw`, recorded for the list at `list` ([`Take::Record`]), taken by the batch that signals
|
||||
/// `at`.
|
||||
pub(crate) fn recorded(&mut self, list: usize, raw: vk::CommandBuffer, at: u64) {
|
||||
self.lists[list].buffers.push_back(Kept { raw, after: at });
|
||||
/// `raw`, recorded for the list at `list` ([`Take::Record`]) of the kind `stamps` gives,
|
||||
/// taken by the batch that signals `at`.
|
||||
pub(crate) fn recorded(
|
||||
&mut self,
|
||||
list: usize,
|
||||
raw: vk::CommandBuffer,
|
||||
at: u64,
|
||||
stamps: Option<SlotStamps>,
|
||||
) {
|
||||
let lists = match stamps {
|
||||
Some(_) => &mut self.stamped,
|
||||
None => &mut self.lists,
|
||||
};
|
||||
lists[list].buffers.push_back(Kept {
|
||||
raw,
|
||||
after: at,
|
||||
slot: stamps.map(|stamps| (stamps.queries, stamps.first, stamps.lease)),
|
||||
});
|
||||
}
|
||||
|
||||
/// Each list's barriers and its command buffers in order, with the spare ones.
|
||||
/// Each list's barriers and its command buffers in order, those of barriers alone then those
|
||||
/// that write timestamps, with the spare ones.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn lists(
|
||||
&self,
|
||||
@@ -174,6 +273,7 @@ impl QueueKept {
|
||||
let lists = self
|
||||
.lists
|
||||
.iter()
|
||||
.chain(&self.stamped)
|
||||
.map(|list| {
|
||||
let buffers = list.buffers.iter().map(|kept| kept.raw).collect();
|
||||
(list.barriers.clone(), buffers)
|
||||
@@ -183,16 +283,33 @@ impl QueueKept {
|
||||
}
|
||||
}
|
||||
|
||||
/// The list of `lists` a new one replaces, its queue's timeline at `at` and completed through
|
||||
/// `completed`: of those no batch took since `at - STALE` and whose command buffers all
|
||||
/// completed, the one taken least lately.
|
||||
fn out_of_use(lists: &[KeptList], at: u64, completed: u64) -> Option<usize> {
|
||||
lists
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, list)| {
|
||||
let last = list.last();
|
||||
(last <= completed && last.saturating_add(STALE) <= at).then_some((last, index))
|
||||
})
|
||||
.min()
|
||||
.map(|(_, index)| index)
|
||||
}
|
||||
|
||||
impl KeptBarriers {
|
||||
/// A command buffer of `device`'s `VkQueue` `queue` holding only `barriers` (each recorded
|
||||
/// as [`Barrier::record`] records it), for the batch that signals `at` on that queue's
|
||||
/// timeline: a kept one whose last batch completed, else one recorded now and kept. `None`
|
||||
/// past the bounds (the module docs), where the batch records its own.
|
||||
/// as [`Barrier::record`] records it), between the timestamps `stamps` gives, for the batch
|
||||
/// that signals `at` on that queue's timeline: a kept one whose last batch completed (and,
|
||||
/// with timestamps, of an earlier holding of the slot), else one recorded now and kept.
|
||||
/// `None` past the bounds (the module docs), where the batch records its own.
|
||||
pub(crate) fn take(
|
||||
&mut self,
|
||||
device: &Device,
|
||||
queue: usize,
|
||||
barriers: &[Barrier],
|
||||
stamps: Option<SlotStamps>,
|
||||
at: u64,
|
||||
) -> Result<Option<vk::CommandBuffer>, Error> {
|
||||
let shared = device.shared();
|
||||
@@ -201,8 +318,13 @@ impl KeptBarriers {
|
||||
self.queues.resize_with(queue + 1, QueueKept::default);
|
||||
}
|
||||
let kept = &mut self.queues[queue];
|
||||
let list = match kept.take(barriers, at, completed) {
|
||||
Take::Kept(raw) => return Ok(Some(raw)),
|
||||
let list = match kept.take(barriers, stamps, at, completed) {
|
||||
Take::Kept(raw) => {
|
||||
if stamps.is_some() {
|
||||
shared.counts.stamped_buffer_reused();
|
||||
}
|
||||
return Ok(Some(raw));
|
||||
}
|
||||
Take::Past => return Ok(None),
|
||||
Take::Record(list) => list,
|
||||
};
|
||||
@@ -231,22 +353,45 @@ impl KeptBarriers {
|
||||
let begin = vk::CommandBufferBeginInfo::default();
|
||||
// SAFETY: the command buffer is the scheduler pool's, used under its lock, and only this
|
||||
// call records it: just allocated, or a spare one, whose every batch completed (none is
|
||||
// pending), which its begin resets (the pool's `RESET_COMMAND_BUFFER`).
|
||||
// pending), which its begin resets (the pool's `RESET_COMMAND_BUFFER`). The slot's
|
||||
// queries are the timestamp pool's, live while the device is.
|
||||
unsafe {
|
||||
let begun = raw.begin_command_buffer(buffer, &begin);
|
||||
exit_guard::called(Call::BeginCommandBuffer);
|
||||
begun.map_err(vulkan)?;
|
||||
shared.counts.command_buffer_begun();
|
||||
if let Some(stamps) = stamps.filter(|stamps| stamps.start) {
|
||||
raw.cmd_reset_query_pool(buffer, stamps.queries, stamps.first, 2);
|
||||
exit_guard::called(Call::CmdResetQueryPool);
|
||||
if !stamps.after {
|
||||
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
|
||||
raw.cmd_write_timestamp(buffer, top, stamps.queries, stamps.first);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
}
|
||||
}
|
||||
for barrier in barriers {
|
||||
barrier.record(raw, buffer);
|
||||
exit_guard::called(Call::CmdPipelineBarrier);
|
||||
}
|
||||
if let Some(stamps) = stamps.filter(|stamps| stamps.start && stamps.after) {
|
||||
let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE;
|
||||
raw.cmd_write_timestamp(buffer, bottom, stamps.queries, stamps.first);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
}
|
||||
if let Some(stamps) = stamps.filter(|stamps| stamps.end) {
|
||||
let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE;
|
||||
raw.cmd_write_timestamp(buffer, bottom, stamps.queries, stamps.first + 1);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
}
|
||||
let ended = raw.end_command_buffer(buffer);
|
||||
exit_guard::called(Call::EndCommandBuffer);
|
||||
ended.map_err(vulkan)?;
|
||||
}
|
||||
shared.counts.barrier_buffer_kept();
|
||||
self.queues[queue].recorded(list, buffer, at);
|
||||
match stamps {
|
||||
Some(_) => shared.counts.stamped_buffer_kept(),
|
||||
None => shared.counts.barrier_buffer_kept(),
|
||||
}
|
||||
self.queues[queue].recorded(list, buffer, at, stamps);
|
||||
Ok(Some(buffer))
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -79,13 +79,16 @@ impl CommandBuffer {
|
||||
device.give_up_switch(switch, prepared);
|
||||
return false;
|
||||
};
|
||||
state.end_encoder(Recorded {
|
||||
encoder,
|
||||
raws: vec![recorded.raw],
|
||||
segments: Vec::new(),
|
||||
summary: recorded.summary,
|
||||
sparse: Vec::new(),
|
||||
});
|
||||
state.end_encoder(
|
||||
self,
|
||||
Recorded {
|
||||
encoder,
|
||||
raws: recorded.raws,
|
||||
segments: Vec::new(),
|
||||
summary: recorded.summary,
|
||||
sparse: Vec::new(),
|
||||
},
|
||||
);
|
||||
state.retained.extend(recorded.retained.into_entry());
|
||||
// What its commands took is the encoder's, as the switch's commands are.
|
||||
if let Some(record) = state.ended.get_mut(encoder) {
|
||||
|
||||
@@ -5,18 +5,70 @@
|
||||
//! 1. The work: the batch's waits, Vulkan waits for its events' signal indices, for the caller's
|
||||
//! binary semaphores and the tracker's waits for other `VkQueue`s' timelines, then its encoders'
|
||||
//! `VkCommandBuffer`s (an encoder's segments among its own), each encoder after the barrier the
|
||||
//! tracker planned for it. The first barrier also makes what completed batches wrote visible
|
||||
//! ([`Barrier::after_completed`]).
|
||||
//! tracker planned for it. What completed work wrote is made visible by a wait or a barrier,
|
||||
//! see below.
|
||||
//! 2. The end: the barrier that makes every write visible to the host ([`Barrier::to_host`]),
|
||||
//! then the signals: the events' kept signal indices, the caller's binary semaphores and the
|
||||
//! queue's timeline value. When an event's previous kept signal is pending on another
|
||||
//! `VkQueue`, this part waits for it, so the event's semaphore is signaled in index order
|
||||
//! without holding back the work.
|
||||
//!
|
||||
//! **What completed work wrote.** The tracker forgets a batch once the host saw its queue's
|
||||
//! timeline pass it, and the device's own submissions outside the batches (`device/submit.rs`,
|
||||
//! `device/staging.rs`) it never tracks: their writes are ordered before a later batch by their
|
||||
//! completion alone. The work waits for each such timeline, each `VkQueue`'s and the device's two
|
||||
//! own, at the value the host saw it reach, where a batch of its `VkQueue` did not wait for that
|
||||
//! value already: a wait that is satisfied as it is submitted. The signal made the writes
|
||||
//! available ("The first access scope includes all memory access performed by the device",
|
||||
//! semaphore signaling), and the wait makes them visible: the submission's "second
|
||||
//! synchronization scope of each semaphore wait operation defined by this command includes every
|
||||
//! command in the same batch that the wait operation is defined in, and all commands that occur
|
||||
//! later in submission order", and the wait's "second access scope includes all memory access
|
||||
//! performed by the device" (`vkQueueSubmit`, semaphore waiting). So one wait per value serves
|
||||
//! every later batch of its `VkQueue`. A batch with nothing planned before its first encoder then
|
||||
//! needs no command buffer before it, a timed command buffer's first batch included where its
|
||||
//! first encoder wrote the start (**GPU times**, below): on an RTX 5080 and a Radeon 780M, nearly
|
||||
//! every batch of a frame of draws, and of command buffers committed from several threads. A wait costs CPU in `vkQueueSubmit`: about
|
||||
//! 1.1 us on ms01's Iris Xe (ANV), 1.6 us on a Radeon 780M (RADV) and 0.5 us on an RTX 5080,
|
||||
//! where a command buffer of barriers cost about 12 us of the Iris Xe's GPU. Counted:
|
||||
//! `WorkCounts::completed_waits`, `WorkCounts::bare_starts` (the batches with work that began
|
||||
//! with no command buffer of barriers).
|
||||
//!
|
||||
//! A driver measured to stall its submissions on semaphore operations
|
||||
//! (`DriverFact::SemaphoreOperationsStallSubmits`: NVIDIA's 615.71.09 on the RTX 5080 Laptop GPU
|
||||
//! 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.
|
||||
//! Where every batch waited, about twice as many of its submissions took that long as where
|
||||
//! batches only signal.
|
||||
//!
|
||||
//! Each barrier goes in a command buffer of barriers alone, which the scheduler records once per
|
||||
//! list of barriers and submits again once the batch that last carried it completed
|
||||
//! ([`kept_barriers`](super::kept_barriers)); one that also writes timestamps or moves the caller's
|
||||
//! images is recorded by its batch.
|
||||
//! ([`kept_barriers`](super::kept_barriers)); one that also writes a command buffer's timestamps
|
||||
//! once per list and slot, submitted again only by a later holding of the slot; one that moves
|
||||
//! the caller's images is recorded by its batch.
|
||||
//!
|
||||
//! **The end in the work's last command buffer.** An encoder's last `VkCommandBuffer` stays
|
||||
//! recording after the encoder ended, as its command buffer's tail, until an encoder after it
|
||||
//! joins its batch, its batch ends at encode time, or the command buffer commits
|
||||
//! (`CommandBufferShared::close_tail`). Where its batch ended there, the end goes into it before
|
||||
//! it ends: the barrier to the host, then, in the last batch of a timed command buffer, the end
|
||||
//! timestamp, as the end's own command buffer holds them. Only where the batch signals no event
|
||||
//! (a kept signal may need the end after a wait for another `VkQueue`'s, above), leaves its
|
||||
//! submission no segment or sparse update (recorded at the submission, among or before the
|
||||
//! work's command buffers), and names no texture over the caller's image that moves between
|
||||
//! layouts (its move back is planned at the submission, before the end). The batch's submission
|
||||
//! then has no end of its own, and the signals join the work's `VkSubmitInfo`: "The first
|
||||
//! synchronization scope of each semaphore signal operation defined by this command includes
|
||||
//! every command in the same batch that the signal operation is defined in, and all commands that
|
||||
//! occur earlier in submission order" (`vkQueueSubmit`). Where that command buffer does not go
|
||||
//! to the queue as recorded (its encoder runs nothing, or a rebind encoded it again), the end is
|
||||
//! a command buffer of its own, as every other batch's. Each command buffer a submission holds
|
||||
//! costs GPU time of its own: a probe of one 1x1 copy took 42.6 us of GPU time as three primary
|
||||
//! command buffers (a start, the copy, an end) and 25.6 us as one on ms01's Iris Xe (ANV), 19.6
|
||||
//! and 13.6 cold on a Radeon 780M (RADV), 15.4 to 17.4 and 7.9 to 9.0 on an RTX 5080. Counted:
|
||||
//! `WorkCounts::finales_folded`, `WorkCounts::finales_apart`.
|
||||
//!
|
||||
//! A batch with no work is one `VkSubmitInfo` of every wait, the end and the signals: a wait
|
||||
//! orders only its own `VkSubmitInfo`'s commands, and a signal follows commands, not waits
|
||||
@@ -56,18 +108,33 @@
|
||||
//! where its driver reads the command buffer's objects after its value
|
||||
//! ([`fences`](super::fences)), at which the command buffer then finishes.
|
||||
//!
|
||||
//! **GPU times** (`gpu_time.rs`). In a timed command buffer, the first command buffer of its
|
||||
//! first batch resets its slot of the device's timestamp pools and writes the start timestamp at
|
||||
//! the top of the pipe, before every barrier and encoder; the end of its last batch writes the
|
||||
//! end timestamp at the bottom of the pipe, after its barriers. The scheduler's host times as it begins the first
|
||||
//! batch and ends the last submission are the kernel times.
|
||||
//! **GPU times** (`gpu_time.rs`). In a timed command buffer, the start timestamp is written at
|
||||
//! the top of the pipe, before every barrier and encoder of its first batch: by its first
|
||||
//! encoder's first command buffer, which wrote it into its slot's third query as it opened, where
|
||||
//! the batch plans nothing before that encoder (no barrier, no image moved, and no
|
||||
//! [`Barrier::after_completed`] where the driver stalls on semaphore operations) and the command
|
||||
//! buffer goes to the queue as recorded first (`WorkCounts::prefixed_starts`); else by the
|
||||
//! batch's first command buffer, a command buffer of barriers, which resets the slot's first two
|
||||
//! queries first. Where the batch plans a barrier before its first encoder for earlier work (the
|
||||
//! encoder's own, or the one before the images it moves), the start is written after that
|
||||
//! barrier instead, at the bottom of the pipe: once every command submitted before it on the
|
||||
//! queue completed. Vulkan (`vkCmdWriteTimestamp`): its "first synchronization scope includes
|
||||
//! all commands that occur earlier in submission order", and `VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT`
|
||||
//! "is equivalent to `VK_PIPELINE_STAGE_ALL_COMMANDS_BIT` with `VkAccessFlags` set to `0` when
|
||||
//! specified in the first synchronization scope". So a command buffer whose first encoder depends
|
||||
//! on work still running starts after that work ended, as Metal's does: on an M3 Max under macOS
|
||||
//! 27.0.1, a fill committed behind a running fill of the same bytes started 0.5 to 0.9 us after
|
||||
//! the first's `GPUEndTime` (10 of 10), and one of other bytes while the first ran (probe
|
||||
//! `gpustart`). The end of its last batch writes the end timestamp at the bottom of the pipe,
|
||||
//! after its barriers. The scheduler's host times as it begins the first batch and ends the last
|
||||
//! submission are the kernel times.
|
||||
//!
|
||||
//! The tracker keeps the plan, and the events their kept signals, only once the submission is
|
||||
//! made; a batch that is not submitted changes neither.
|
||||
//!
|
||||
//! The submission is a section of the exit guard ([`exit_guard`]). What it did is published
|
||||
//! ([`CommandBufferShared::publish`]: the transition to `Scheduled`, which runs the scheduled
|
||||
//! handlers and ends waits for scheduling, and the completion thread's watch) only after that
|
||||
//! handlers and ends waits for scheduling, and the queue waiter's watch) only after that
|
||||
//! section ended. A section ends by registering the exit hook again when its calls may have
|
||||
//! registered destructors, so an exit the program makes once it learned of the submission runs
|
||||
//! the hook before them.
|
||||
@@ -76,17 +143,16 @@
|
||||
//! thread, once the scheduler's lock is free; its transition to `Scheduled` waits for them.
|
||||
|
||||
use super::completion::Submitted;
|
||||
use super::kept_barriers::KeptBarriers;
|
||||
use super::kept_barriers::{KeptBarriers, SlotStamps};
|
||||
use super::{lock, recording_error, submission_error, CommandBufferShared, State};
|
||||
use crate::deferred::Deferred;
|
||||
use crate::encoder::RecordedSegment;
|
||||
use crate::error::CommandBufferError;
|
||||
use crate::error::Error;
|
||||
use crate::error::{internal, Error};
|
||||
use crate::event_timeline::Signal;
|
||||
use crate::exit_guard::{self, Call};
|
||||
use crate::gpu_time;
|
||||
use crate::release;
|
||||
use crate::replay::Replay;
|
||||
use crate::retained::Retained;
|
||||
use crate::scheduler;
|
||||
use crate::sparse::bind::{bind_batch, BindFailure, Bound};
|
||||
@@ -98,6 +164,28 @@ use ash::vk;
|
||||
use metal2vulkan::bind::ReplayFaults;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The lists a batch's submission fills and empties, kept in the scheduler's state from batch to
|
||||
/// batch with their room, so that a submission allocates none of them once they have room for
|
||||
/// what it puts in them ([`CommandBufferShared::submit_batch`]).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct BatchLists {
|
||||
/// What each timeline whose writes the tracker forgets completed through as the host saw
|
||||
/// it, each `VkQueue`'s, then the device's own: none where it is at 0.
|
||||
reached: Vec<Option<(vk::Semaphore, u64)>>,
|
||||
/// The work's waits.
|
||||
waits: BatchWaits,
|
||||
/// Of `reached`, the timelines (by place) and values the work waits for.
|
||||
waited: Vec<(usize, u64)>,
|
||||
}
|
||||
|
||||
/// A `VkSubmitInfo`'s waits: the semaphores, their values and their stages.
|
||||
#[derive(Default)]
|
||||
struct BatchWaits {
|
||||
semaphores: Vec<vk::Semaphore>,
|
||||
values: Vec<u64>,
|
||||
stages: Vec<vk::PipelineStageFlags>,
|
||||
}
|
||||
|
||||
/// A batch submitted, which nothing has seen yet: for the scheduler to
|
||||
/// [`publish`](CommandBufferShared::publish).
|
||||
#[must_use = "a batch not published never finishes its command buffer"]
|
||||
@@ -105,19 +193,16 @@ pub(crate) struct Submission {
|
||||
/// Its `VkQueue`.
|
||||
queue: usize,
|
||||
batch: Submitted,
|
||||
/// It ends a command buffer with submission handlers, which the submitting thread runs once
|
||||
/// the scheduler's lock is free ([`Submission::runs_handlers`]).
|
||||
/// It ends a command buffer with submission handlers, or with a switch of storage forms riding
|
||||
/// on it, which the submitting thread runs or ends once the scheduler's lock is free
|
||||
/// ([`Submission::runs_handlers`]).
|
||||
handlers: bool,
|
||||
/// The logs its command buffer's first submission ended (`replay.rs`), which
|
||||
/// [`publish`](CommandBufferShared::publish) hands back for the scheduler to let go of
|
||||
/// without its lock: what they hold may be a no-copy buffer's last handle.
|
||||
logs: Vec<Arc<Replay>>,
|
||||
}
|
||||
|
||||
impl Submission {
|
||||
/// Whether the submitting thread runs its command buffer's submission handlers
|
||||
/// ([`CommandBufferShared::run_submission_handlers`]) once it holds no lock: its transition
|
||||
/// to `Scheduled` waits for them.
|
||||
/// ([`CommandBufferShared::run_submission_handlers`]) once it holds no lock, after it ended
|
||||
/// the switch of storage forms riding on it: its transition to `Scheduled` waits for them.
|
||||
pub(crate) fn runs_handlers(&self) -> bool {
|
||||
self.handlers
|
||||
}
|
||||
@@ -151,8 +236,7 @@ impl CommandBufferShared {
|
||||
}
|
||||
// Its first submission resolves what its commands reach as Metal's does, before any of
|
||||
// its batches goes to the `VkQueue` (`first_submission.rs`).
|
||||
let first_batch = !state.submitted;
|
||||
if first_batch {
|
||||
if !state.submitted {
|
||||
let first = state
|
||||
.first_submission(device, self)
|
||||
.map_err(|error| recording_error(device, error))?;
|
||||
@@ -228,11 +312,21 @@ impl CommandBufferShared {
|
||||
queue,
|
||||
value: scheduler.values[queue] + 1,
|
||||
};
|
||||
// What each timeline whose writes the tracker forgets completed through as the host saw
|
||||
// it, each `VkQueue`'s, then the device's own (the module docs): read once, for the
|
||||
// tracker and for the work's waits alike.
|
||||
let BatchLists {
|
||||
reached,
|
||||
waits,
|
||||
waited,
|
||||
} = &mut scheduler.lists;
|
||||
reached.clear();
|
||||
for (slot, vk_queue) in shared.queues.iter().enumerate() {
|
||||
scheduler
|
||||
.tracker
|
||||
.completed(slot, vk_queue.completed_value());
|
||||
let value = vk_queue.completed_value();
|
||||
scheduler.tracker.completed(slot, value);
|
||||
reached.push((value > 0).then_some((vk_queue.timeline, value)));
|
||||
}
|
||||
reached.extend(device.own_completed());
|
||||
if index == 0 {
|
||||
state.times.kernel_start = gpu_time::host_nanos();
|
||||
}
|
||||
@@ -240,10 +334,10 @@ impl CommandBufferShared {
|
||||
.times
|
||||
.slot
|
||||
.as_ref()
|
||||
.map(|slot| (slot.queries(), slot.first()));
|
||||
.map(|slot| (slot.queries(), slot.first(), slot.lease()));
|
||||
// The start timestamp goes into the first command buffer of the first batch, a barrier
|
||||
// one (its first barrier makes what completed batches wrote visible), or into its end
|
||||
// when it has no work.
|
||||
// one (with the barrier planned before its first encoder, if any), or into its end when
|
||||
// it has no work, unless its first encoder wrote it (below).
|
||||
let mut start_stamp = slot.filter(|_| index == 0);
|
||||
let batches = state.batches.all();
|
||||
let (start, end) = (range.start, range.end);
|
||||
@@ -289,6 +383,20 @@ impl CommandBufferShared {
|
||||
exit_uses.push(image.transition_use());
|
||||
}
|
||||
}
|
||||
// The new resources' first work, before every command (`texture/first_move.rs`), given
|
||||
// back if the submission is not made. A batch's commands may reach every texture
|
||||
// unnamed, so it takes every move, those of images bound to host pages among them, whose
|
||||
// pages it then holds. The moves that keep the bytes their images are bound to the host
|
||||
// makes first, once every submission before completed (`Device::keep_on_host`); one
|
||||
// registered meanwhile too.
|
||||
let firsts = &shared.textures.first_moves;
|
||||
let first_work = loop {
|
||||
(device.keep_on_host(|_| true)).map_err(|error| recording_error(device, error))?;
|
||||
let work = firsts.take(|_| true);
|
||||
if !work.has_keeps() {
|
||||
break work;
|
||||
}
|
||||
};
|
||||
let entry = (!entries.is_empty()).then(|| Summary::outside_encoders(entry_uses));
|
||||
let exit = (!exits.is_empty()).then(|| Summary::outside_encoders(exit_uses));
|
||||
let plan = scheduler.tracker.plan(
|
||||
@@ -310,21 +418,68 @@ impl CommandBufferShared {
|
||||
exit_barrier = last;
|
||||
barriers = rest;
|
||||
}
|
||||
let mut lead = Some(Barrier::after_completed());
|
||||
// Where the driver's submissions stall on semaphore operations, the first command buffer
|
||||
// of barriers makes what completed work wrote visible, in place of the work's waits (the
|
||||
// module docs).
|
||||
let by_barrier = shared.completed_by_barrier;
|
||||
let mut completed_barrier = by_barrier.then(Barrier::after_completed);
|
||||
// The first encoder's prefix wrote the start where the batch plans nothing before that
|
||||
// encoder (no barrier, no image moved, no barrier for completed work) and its first
|
||||
// command buffer goes to the queue as recorded (`gpu_time.rs`): then no command buffer of
|
||||
// barriers starts the batch for the timestamp's sake.
|
||||
let prefix = state.prefix;
|
||||
let prefixed = start_stamp.is_some()
|
||||
&& completed_barrier.is_none()
|
||||
&& entry.is_none()
|
||||
&& barriers.first().is_some_and(Option::is_none)
|
||||
&& prefix.is_some_and(|raw| {
|
||||
state
|
||||
.recorded
|
||||
.get(start)
|
||||
.and_then(|first| first.raws.first())
|
||||
== Some(&raw)
|
||||
});
|
||||
if prefixed {
|
||||
start_stamp = None;
|
||||
}
|
||||
if index == 0 {
|
||||
state.times.prefixed = prefixed;
|
||||
}
|
||||
let mut work = Vec::with_capacity(2 * (end - start) + 1);
|
||||
// Whether a command buffer of barriers goes before the first encoder.
|
||||
let mut started = false;
|
||||
// A barrier planned before the first encoder, for earlier work that may still run: the
|
||||
// start goes after the last such barrier, once every command before it completed (the
|
||||
// module docs).
|
||||
let encoder_behind = barriers.first().is_some_and(Option::is_some);
|
||||
if entry.is_some() {
|
||||
let globals: Vec<Barrier> = lead.take().into_iter().chain(entry_barrier).collect();
|
||||
started = true;
|
||||
let globals: Vec<Barrier> = completed_barrier
|
||||
.take()
|
||||
.into_iter()
|
||||
.chain(entry_barrier)
|
||||
.collect();
|
||||
let stamps = Stamps {
|
||||
start: start_stamp.take(),
|
||||
start: start_stamp.filter(|_| !encoder_behind),
|
||||
after: entry_barrier.is_some(),
|
||||
end: None,
|
||||
};
|
||||
if stamps.start.is_some() {
|
||||
start_stamp = None;
|
||||
}
|
||||
work.push(self.record_barriers(&mut state, &globals, &entries, stamps)?);
|
||||
}
|
||||
for (offset, barrier) in barriers.iter().enumerate() {
|
||||
let globals: Vec<Barrier> = lead.take().into_iter().chain(*barrier).collect();
|
||||
if !globals.is_empty() {
|
||||
let globals: Vec<Barrier> = completed_barrier
|
||||
.take()
|
||||
.into_iter()
|
||||
.chain(*barrier)
|
||||
.collect();
|
||||
if !globals.is_empty() || start_stamp.is_some() {
|
||||
started |= offset == 0;
|
||||
let stamps = Stamps {
|
||||
start: start_stamp.take(),
|
||||
after: barrier.is_some(),
|
||||
end: None,
|
||||
};
|
||||
let kept = &mut scheduler.kept;
|
||||
@@ -332,17 +487,6 @@ impl CommandBufferShared {
|
||||
}
|
||||
work.extend(&state.recorded[start + offset].raws);
|
||||
}
|
||||
// The new resources' first work, before every command (`texture/first_move.rs`), given
|
||||
// back if the submission is not made. A move of an image bound to host pages goes only
|
||||
// with a batch whose encoders name its key, and so hold its pages.
|
||||
let firsts = &shared.textures.first_moves;
|
||||
let first_work = firsts.take(|key| {
|
||||
state.recorded[start..end].iter().any(|recorded| {
|
||||
recorded.summary.keys().any(|named| named == key)
|
||||
|| (state.ended.get(recorded.encoder))
|
||||
.is_some_and(|ended| ended.keys.contains(&key))
|
||||
})
|
||||
});
|
||||
// The first work goes in a `VkSubmitInfo` of its own just before the batch's, in its
|
||||
// `vkQueueSubmit` (the module docs). Host calls' staged copies go at the batch's start.
|
||||
let lead = match first_work.has_first() {
|
||||
@@ -350,7 +494,7 @@ impl CommandBufferShared {
|
||||
// SAFETY: the command buffer is recording, outside a render pass; it is
|
||||
// submitted just before the batch, before any later one, and every batch on
|
||||
// another `VkQueue` waits for the batch (`FirstMoves::waits`).
|
||||
unsafe { first_work.record(raw, buffer) };
|
||||
unsafe { first_work.record(raw, buffer, shared.queue_flags_of(queue)) };
|
||||
Ok(())
|
||||
})?),
|
||||
false => None,
|
||||
@@ -364,9 +508,14 @@ impl CommandBufferShared {
|
||||
})?;
|
||||
work.insert(0, staged);
|
||||
}
|
||||
let mut wait_semaphores = Vec::new();
|
||||
let mut wait_values = Vec::new();
|
||||
let mut wait_stages = Vec::new();
|
||||
let BatchWaits {
|
||||
semaphores: wait_semaphores,
|
||||
values: wait_values,
|
||||
stages: wait_stages,
|
||||
} = waits;
|
||||
wait_semaphores.clear();
|
||||
wait_values.clear();
|
||||
wait_stages.clear();
|
||||
if let Some(value) = bound {
|
||||
// The bind waited for the batch's waits; the work waits for the bind.
|
||||
wait_semaphores.push(shared.queues[queue].timeline);
|
||||
@@ -426,8 +575,8 @@ impl CommandBufferShared {
|
||||
(Vec::new(), Vec::new(), Vec::new());
|
||||
for ((&semaphore, &value), &stage) in wait_semaphores
|
||||
.iter()
|
||||
.zip(&wait_values)
|
||||
.zip(&wait_stages)
|
||||
.zip(wait_values.iter())
|
||||
.zip(wait_stages.iter())
|
||||
.filter(|((semaphore, _), _)| !binary_waits.contains(semaphore))
|
||||
{
|
||||
lead_semaphores.push(semaphore);
|
||||
@@ -441,10 +590,47 @@ impl CommandBufferShared {
|
||||
// No work: every wait goes with the end, which it then orders.
|
||||
let single = work.is_empty();
|
||||
if single {
|
||||
order_semaphores.append(&mut wait_semaphores);
|
||||
order_values.append(&mut wait_values);
|
||||
order_stages.append(&mut wait_stages);
|
||||
order_semaphores.append(wait_semaphores);
|
||||
order_values.append(wait_values);
|
||||
order_stages.append(wait_stages);
|
||||
}
|
||||
// The work waits for what completed, where its `VkQueue` did not already and no barrier
|
||||
// made it visible (the module docs); the waits are taken as made once the submission is.
|
||||
waited.clear();
|
||||
if !single && !by_barrier {
|
||||
for (source, &timeline) in reached.iter().enumerate() {
|
||||
let Some((semaphore, value)) = timeline else {
|
||||
continue;
|
||||
};
|
||||
if value > scheduler.waited[queue][source] {
|
||||
wait_semaphores.push(semaphore);
|
||||
wait_values.push(value);
|
||||
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
|
||||
waited.push((source, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
// The end went into the work's last command buffer as the batch ended (the module docs),
|
||||
// where that command buffer goes to the queue as recorded: then the batch has no end of
|
||||
// its own. One that does not go (its encoder runs nothing, or was encoded again) leaves
|
||||
// the end to its own command buffer, as every other batch's.
|
||||
let folded = match state.fold(index).filter(|(raw, _)| work.contains(raw)) {
|
||||
None => false,
|
||||
Some((raw, stamped)) => {
|
||||
let ends = work.last() == Some(&raw)
|
||||
&& exit_barrier.is_none()
|
||||
&& exits.is_empty()
|
||||
&& order_semaphores.is_empty()
|
||||
&& start_stamp.is_none()
|
||||
&& stamped == (last && slot.is_some());
|
||||
debug_assert!(ends, "a batch's end recorded where the batch does not end");
|
||||
if !ends {
|
||||
let error = internal("a batch's end recorded where the batch does not end");
|
||||
return Err(recording_error(device, error));
|
||||
}
|
||||
true
|
||||
}
|
||||
};
|
||||
// The end, where the batch has something to end. A batch with no work, no wait, no image
|
||||
// to move back and no timestamp records none: none of its commands wrote anything, every
|
||||
// batch before it on any `VkQueue` made its own writes visible to the host before its
|
||||
@@ -452,6 +638,7 @@ impl CommandBufferShared {
|
||||
// a wait orders the commands of its batch, and a signal follows those, not the wait.
|
||||
let stamps = Stamps {
|
||||
start: start_stamp.take(),
|
||||
after: false,
|
||||
end: slot.filter(|_| last),
|
||||
};
|
||||
let ends = !single
|
||||
@@ -460,7 +647,7 @@ impl CommandBufferShared {
|
||||
|| !exits.is_empty()
|
||||
|| stamps.start.is_some()
|
||||
|| stamps.end.is_some();
|
||||
let finale: Vec<vk::CommandBuffer> = match ends {
|
||||
let finale: Vec<vk::CommandBuffer> = match ends && !folded {
|
||||
true => {
|
||||
let finale_barriers: Vec<Barrier> = exit_barrier
|
||||
.into_iter()
|
||||
@@ -483,12 +670,19 @@ impl CommandBufferShared {
|
||||
.chain(binary_signals.iter().map(|_| 0))
|
||||
.chain([at.value])
|
||||
.collect();
|
||||
let mut work_timeline =
|
||||
vk::TimelineSemaphoreSubmitInfo::default().wait_semaphore_values(&wait_values);
|
||||
// A batch whose end its work holds signals with its work.
|
||||
let (work_signals, work_signal_values) = match folded {
|
||||
true => (&signal_semaphores[..], &signal_values[..]),
|
||||
false => (&[][..], &[][..]),
|
||||
};
|
||||
let mut work_timeline = vk::TimelineSemaphoreSubmitInfo::default()
|
||||
.wait_semaphore_values(wait_values)
|
||||
.signal_semaphore_values(work_signal_values);
|
||||
let first = vk::SubmitInfo::default()
|
||||
.wait_semaphores(&wait_semaphores)
|
||||
.wait_dst_stage_mask(&wait_stages)
|
||||
.wait_semaphores(wait_semaphores)
|
||||
.wait_dst_stage_mask(wait_stages)
|
||||
.command_buffers(&work)
|
||||
.signal_semaphores(work_signals)
|
||||
.push_next(&mut work_timeline);
|
||||
// The fence the last batch signals where the driver reads a command buffer's objects
|
||||
// after its value, and every batch where the queue's failures are relayed
|
||||
@@ -515,7 +709,11 @@ impl CommandBufferShared {
|
||||
.signal_semaphores(&signal_semaphores)
|
||||
.push_next(&mut end_timeline);
|
||||
let infos = [first, second];
|
||||
let infos = &infos[usize::from(single)..];
|
||||
let infos = match (single, folded) {
|
||||
(true, _) => &infos[1..],
|
||||
(false, true) => &infos[..1],
|
||||
(false, false) => &infos[..],
|
||||
};
|
||||
let lead_buffers: Vec<vk::CommandBuffer> = lead.into_iter().collect();
|
||||
let mut lead_timeline =
|
||||
vk::TimelineSemaphoreSubmitInfo::default().wait_semaphore_values(&lead_values);
|
||||
@@ -548,10 +746,15 @@ impl CommandBufferShared {
|
||||
// transition is of a live image of the caller's in the layout it is in (its contract,
|
||||
// `new_texture_with_vk_image`); the fence is unsignaled and in no pending submission;
|
||||
// the `VkQueue` is used under its lock.
|
||||
let submitted = shared.submit_logged(queue, fence, &self.relayed, |vk_queue| unsafe {
|
||||
shared.counts.queue_submitted(buffers);
|
||||
raw.queue_submit(vk_queue, &submits, fence.unwrap_or(vk::Fence::null()))
|
||||
});
|
||||
let submitted = shared.submit_logged(
|
||||
(queue, Some(at.value)),
|
||||
fence,
|
||||
&self.relayed,
|
||||
|vk_queue| unsafe {
|
||||
shared.counts.queue_submitted(buffers);
|
||||
raw.queue_submit(vk_queue, &submits, fence.unwrap_or(vk::Fence::null()))
|
||||
},
|
||||
);
|
||||
exit_guard::called(Call::QueueSubmit);
|
||||
if let Err(error) = submitted {
|
||||
if let Some(fence) = fence {
|
||||
@@ -573,9 +776,26 @@ impl CommandBufferShared {
|
||||
if last {
|
||||
state.times.kernel_end = gpu_time::host_nanos();
|
||||
}
|
||||
// Its submission handlers run on this thread once the scheduler's lock is free; its
|
||||
if !single {
|
||||
match folded {
|
||||
true => shared.counts.finale_folded(),
|
||||
false => shared.counts.finale_apart(),
|
||||
}
|
||||
}
|
||||
for &(source, value) in waited.iter() {
|
||||
scheduler.waited[queue][source] = value;
|
||||
}
|
||||
shared.counts.completed_waited(waited.len());
|
||||
if !single && !started {
|
||||
shared.counts.bare_start();
|
||||
}
|
||||
if prefixed {
|
||||
shared.counts.prefixed_start();
|
||||
}
|
||||
// Its submission handlers run on this thread once the scheduler's lock is free, and a
|
||||
// switch of storage forms riding on it ends there first (`scheduler/mod.rs`); its
|
||||
// transition to `Scheduled`, posted as it is published, waits for them.
|
||||
let handlers = last && !state.submission.is_empty();
|
||||
let handlers = last && (!state.submission.is_empty() || state.storage_form.is_some());
|
||||
state.submitting = handlers;
|
||||
scheduler.tracker.apply(plan);
|
||||
let several = shared.queues.len() > 1;
|
||||
@@ -584,7 +804,6 @@ impl CommandBufferShared {
|
||||
state.retained.push(Box::new(held));
|
||||
}
|
||||
scheduler.values[queue] = at.value;
|
||||
shared.queues[queue].submitted(at.value);
|
||||
for image in &images {
|
||||
image.submitted();
|
||||
// One that rests in `GENERAL` from now on (an encode-time image after its first
|
||||
@@ -599,17 +818,6 @@ impl CommandBufferShared {
|
||||
// Its commands may reach every texture through its resource ID where one bound a heap
|
||||
// set: the stale-reach degrade's trigger decides (`detach.rs`).
|
||||
let reaches = state.heaps.bound();
|
||||
// No rebind encodes its encoders again once it was first submitted: their logs go with
|
||||
// this batch, for the scheduler to drop without its lock. A failure before here leaves
|
||||
// them to go with the command buffer.
|
||||
let logs: Vec<Arc<Replay>> = match first_batch {
|
||||
true => state
|
||||
.ended
|
||||
.iter_mut()
|
||||
.filter_map(|record| record.replay.take())
|
||||
.collect(),
|
||||
false => Vec::new(),
|
||||
};
|
||||
drop(state);
|
||||
if rebound {
|
||||
device.degrade_encoded_use_rebound();
|
||||
@@ -628,26 +836,23 @@ impl CommandBufferShared {
|
||||
.collect(),
|
||||
},
|
||||
handlers,
|
||||
logs,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Publish a batch [`submit_batch`](Self::submit_batch) submitted, after the section that
|
||||
/// submitted it ended: when it ends the command buffer, its transition to `Scheduled`, then
|
||||
/// the completion thread's watch for it.
|
||||
/// The logs the command buffer's first submission ended come back, for the caller to let go
|
||||
/// of without its lock.
|
||||
pub(crate) fn publish(self: &Arc<Self>, submission: Submission) -> Vec<Arc<Replay>> {
|
||||
let Submission {
|
||||
queue, batch, logs, ..
|
||||
} = submission;
|
||||
/// its queue waiter's watch for it. From the watch on, the command buffer may complete
|
||||
/// and run its release on its queue's handler thread before the caller lets go of anything
|
||||
/// it took, so the caller holds nothing of what its commands or encoders took
|
||||
/// (`scheduler::Spent`).
|
||||
pub(crate) fn publish(self: &Arc<Self>, submission: Submission) {
|
||||
let Submission { queue, batch, .. } = submission;
|
||||
if batch.last {
|
||||
// Before the completion thread can see it finish, so the queue's context runs its
|
||||
// Before a completion turn can see it finish, so the queue's context runs its
|
||||
// transition to `Scheduled` first.
|
||||
self.post_scheduled();
|
||||
}
|
||||
self.device.shared().completion.watch(queue, batch);
|
||||
logs
|
||||
}
|
||||
|
||||
/// A command buffer of this command buffer's pool holding what `record` records into it,
|
||||
@@ -672,7 +877,7 @@ impl CommandBufferShared {
|
||||
device.shared().counts.command_buffer_begun();
|
||||
record(state, buffer).map_err(|error| recording_error(device, error))?;
|
||||
// SAFETY: as above.
|
||||
let ended = unsafe { raw.end_command_buffer(buffer) };
|
||||
let ended = unsafe { self.end_raw(buffer) };
|
||||
exit_guard::called(Call::EndCommandBuffer);
|
||||
ended.map_err(|error| submission_error(device, error))?;
|
||||
Ok(buffer)
|
||||
@@ -701,7 +906,7 @@ impl CommandBufferShared {
|
||||
unsafe { scrub.record(device.shared().vk(), buffer) }
|
||||
})?;
|
||||
state.recorded[encoder].segments[at].recorded = Some(RecordedSegment {
|
||||
raw,
|
||||
raws: vec![raw],
|
||||
summary: EncoderUses::new(true).finish(),
|
||||
retained: Retained::default(),
|
||||
executions: Vec::new(),
|
||||
@@ -715,11 +920,11 @@ impl CommandBufferShared {
|
||||
}
|
||||
|
||||
/// A command buffer holding only `barriers`, in order, then `transitions` of the caller's
|
||||
/// images, between the `stamps` it writes, for the batch that signals `at`: where it holds
|
||||
/// barriers alone, one the scheduler keeps (`kept_barriers.rs`) on a queue whose command
|
||||
/// buffers end at their timeline's value (`fences::ends_at_fence`), and else, or past the
|
||||
/// kept ones' bounds, one recorded into this command buffer's pool
|
||||
/// ([`record_barriers`](Self::record_barriers)).
|
||||
/// images, between the `stamps` it writes, for the batch that signals `at`: where it moves no
|
||||
/// image, one the scheduler keeps (`kept_barriers.rs`; one that writes timestamps, kept for
|
||||
/// their slot) on a queue whose command buffers end at their timeline's value
|
||||
/// (`fences::ends_at_fence`), and else, or past the kept ones' bounds, one recorded into this
|
||||
/// command buffer's pool ([`record_barriers`](Self::record_barriers)).
|
||||
fn barrier_buffer(
|
||||
&self,
|
||||
state: &mut State,
|
||||
@@ -730,10 +935,9 @@ impl CommandBufferShared {
|
||||
stamps: Stamps,
|
||||
) -> Result<vk::CommandBuffer, CommandBufferError> {
|
||||
let device = &self.device;
|
||||
let alone = transitions.is_empty() && stamps.start.is_none() && stamps.end.is_none();
|
||||
if alone && !super::fences::ends_at_fence(device, at.queue) {
|
||||
if transitions.is_empty() && !super::fences::ends_at_fence(device, at.queue) {
|
||||
let taken = kept
|
||||
.take(device, at.queue, barriers, at.value)
|
||||
.take(device, at.queue, barriers, stamps.kept(), at.value)
|
||||
.map_err(|error| recording_error(device, error))?;
|
||||
if let Some(buffer) = taken {
|
||||
return Ok(buffer);
|
||||
@@ -766,20 +970,24 @@ impl CommandBufferShared {
|
||||
exit_guard::called(Call::BeginCommandBuffer);
|
||||
begun.map_err(|error| submission_error(device, error))?;
|
||||
device.shared().counts.command_buffer_begun();
|
||||
if let Some((queries, first)) = stamps.start {
|
||||
if let Some((queries, first, _)) = stamps.start {
|
||||
raw.cmd_reset_query_pool(buffer, queries, first, 2);
|
||||
exit_guard::called(Call::CmdResetQueryPool);
|
||||
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
|
||||
raw.cmd_write_timestamp(buffer, top, queries, first);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
if !stamps.after {
|
||||
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
|
||||
raw.cmd_write_timestamp(buffer, top, queries, first);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
}
|
||||
}
|
||||
for barrier in barriers {
|
||||
barrier.record(raw, buffer);
|
||||
exit_guard::called(Call::CmdPipelineBarrier);
|
||||
}
|
||||
if !transitions.is_empty() {
|
||||
let images: Vec<vk::ImageMemoryBarrier<'_>> =
|
||||
transitions.iter().map(Transition::barrier).collect();
|
||||
let family = device.shared().queue_flags_of(self.queue.vk_queue());
|
||||
let images: Vec<vk::ImageMemoryBarrier<'_>> = (transitions.iter())
|
||||
.map(|transition| transition.barrier(family))
|
||||
.collect();
|
||||
let all = vk::PipelineStageFlags::ALL_COMMANDS;
|
||||
raw.cmd_pipeline_barrier(
|
||||
buffer,
|
||||
@@ -792,12 +1000,17 @@ impl CommandBufferShared {
|
||||
);
|
||||
exit_guard::called(Call::CmdPipelineBarrier);
|
||||
}
|
||||
if let Some((queries, first)) = stamps.end {
|
||||
if let Some((queries, first, _)) = stamps.start.filter(|_| stamps.after) {
|
||||
let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE;
|
||||
raw.cmd_write_timestamp(buffer, bottom, queries, first);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
}
|
||||
if let Some((queries, first, _)) = stamps.end {
|
||||
let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE;
|
||||
raw.cmd_write_timestamp(buffer, bottom, queries, first + 1);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
}
|
||||
let ended = raw.end_command_buffer(buffer);
|
||||
let ended = self.end_raw(buffer);
|
||||
exit_guard::called(Call::EndCommandBuffer);
|
||||
ended.map_err(|error| submission_error(device, error))?;
|
||||
}
|
||||
@@ -816,10 +1029,28 @@ fn bind_error(device: &crate::Device, failure: BindFailure) -> CommandBufferErro
|
||||
}
|
||||
|
||||
/// The timestamps a barrier command buffer writes into its command buffer's slot of the device's
|
||||
/// timestamp pools, each the slot's pool and its first query: the start (after resetting the
|
||||
/// slot) before its barriers, the end after them.
|
||||
/// timestamp pools, each the slot's pool, its first query and the holding's lease
|
||||
/// (`gpu_time::Slot::lease`): the start (after resetting the slot) before its barriers at the top
|
||||
/// of the pipe, or with `after` after them at the bottom of the pipe; the end after them.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Stamps {
|
||||
start: Option<(vk::QueryPool, u32)>,
|
||||
end: Option<(vk::QueryPool, u32)>,
|
||||
start: Option<(vk::QueryPool, u32, u64)>,
|
||||
after: bool,
|
||||
end: Option<(vk::QueryPool, u32, u64)>,
|
||||
}
|
||||
|
||||
impl Stamps {
|
||||
/// What a kept command buffer writes for these (`kept_barriers.rs`): `None` where they are
|
||||
/// none.
|
||||
fn kept(self) -> Option<SlotStamps> {
|
||||
let (queries, first, lease) = self.start.or(self.end)?;
|
||||
Some(SlotStamps {
|
||||
queries,
|
||||
first,
|
||||
lease,
|
||||
start: self.start.is_some(),
|
||||
after: self.after,
|
||||
end: self.end.is_some(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@ use super::texture_descriptor::{TextureDescriptor, TextureLayout};
|
||||
use super::tracker::{Access, Barrier};
|
||||
use super::values::{ResourceOptions, StorageMode};
|
||||
use super::{Buffer, Device, MetalLevel};
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::bind::{CompressedBlit, CompressedBlitModule};
|
||||
use metal2vulkan::error::RuntimeDriverDefect;
|
||||
@@ -403,7 +404,7 @@ impl Rewrite {
|
||||
///
|
||||
/// `raw` is recording outside a render pass, and the scratch and the sets live until it
|
||||
/// completes.
|
||||
unsafe fn record(&self, device: &ash::Device, raw: vk::CommandBuffer) {
|
||||
unsafe fn record(&self, device: &Vk, raw: vk::CommandBuffer) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe {
|
||||
for pass in &self.passes {
|
||||
|
||||
@@ -143,7 +143,9 @@ pub(super) fn imageblock_size(width: u64, height: u64) -> Result<ImageblockSize,
|
||||
}
|
||||
|
||||
/// A compute encoder (`MTLComputeCommandEncoder`): `Send`, not `Sync`; `end_encoding` consumes
|
||||
/// it.
|
||||
/// it. Each object a call binds is held until its command buffer completes (or, never committed,
|
||||
/// is released), as Metal holds what an encoder was handed: one a later call replaced or unbound
|
||||
/// before any dispatch used it, and one bound after the last dispatch, too.
|
||||
pub struct ComputeCommandEncoder {
|
||||
core: EncoderCore,
|
||||
dispatch_type: DispatchType,
|
||||
@@ -226,7 +228,8 @@ impl CommandBuffer {
|
||||
indirect_stage_in: None,
|
||||
residency: self.inherited_residency(false),
|
||||
captures: Captures::default(),
|
||||
log: self.device().shared().rebinds.any().then(CallLog::new),
|
||||
log: (self.device().shared().rebinds.any())
|
||||
.then(|| self.device().shared().scheduler.spare_logs().compute()),
|
||||
dispatches: 0,
|
||||
})
|
||||
}
|
||||
@@ -259,7 +262,8 @@ impl ComputeCommandEncoder {
|
||||
|
||||
/// End an encoder made by [`replaying`](Self::replaying): what it recorded, and what it made
|
||||
/// resident.
|
||||
pub(super) fn finish_replay(self) -> Result<(Replayed, Option<Residency>), Error> {
|
||||
pub(super) fn finish_replay(mut self) -> Result<(Replayed, Option<Residency>), Error> {
|
||||
self.table.let_go_all(&mut self.core);
|
||||
let replayed = self.core.finish_replay()?;
|
||||
Ok((replayed, Some(self.residency)))
|
||||
}
|
||||
@@ -353,7 +357,7 @@ impl ComputeCommandEncoder {
|
||||
) -> Result<(), Error> {
|
||||
self.log(|_| ComputeCall::Buffer(buffer.cloned(), offset, index));
|
||||
self.table
|
||||
.set_buffer(&self.core, "set_buffer", buffer, offset, index)
|
||||
.set_buffer(&mut self.core, "set_buffer", buffer, offset, index)
|
||||
}
|
||||
|
||||
/// `setBuffers:offsets:withRange:`: `buffers[i]` at offset `offsets[i]` at index
|
||||
@@ -369,7 +373,7 @@ impl ComputeCommandEncoder {
|
||||
ComputeCall::Buffers(log.buffer_span(buffers), log.word_span(offsets), first)
|
||||
});
|
||||
self.table
|
||||
.set_buffers(&self.core, "set_buffers", buffers, offsets, first)
|
||||
.set_buffers(&mut self.core, "set_buffers", buffers, offsets, first)
|
||||
}
|
||||
|
||||
/// `setBufferOffset:atIndex:`, which clears the index's attribute stride
|
||||
@@ -384,7 +388,7 @@ impl ComputeCommandEncoder {
|
||||
pub fn set_buffer_offset(&mut self, offset: u64, index: u32) -> Result<(), Error> {
|
||||
self.log(|_| ComputeCall::BufferOffset(offset, index));
|
||||
self.table
|
||||
.set_buffer_offset(&self.core, "set_buffer_offset", offset, index)
|
||||
.set_buffer_offset(&mut self.core, "set_buffer_offset", offset, index)
|
||||
}
|
||||
|
||||
/// `setBuffer:offset:attributeStride:atIndex:`: as [`set_buffer`](Self::set_buffer), the
|
||||
@@ -403,7 +407,7 @@ impl ComputeCommandEncoder {
|
||||
) -> Result<(), Error> {
|
||||
self.log(|_| ComputeCall::BufferWithStride(buffer.cloned(), offset, stride, index));
|
||||
self.table.set_buffer_with_stride(
|
||||
&self.core,
|
||||
&mut self.core,
|
||||
"set_buffer_with_stride",
|
||||
buffer,
|
||||
offset,
|
||||
@@ -428,7 +432,7 @@ impl ComputeCommandEncoder {
|
||||
ComputeCall::BuffersWithStrides(buffers, offsets, log.word_span(strides), first)
|
||||
});
|
||||
self.table.set_buffers_with_strides(
|
||||
&self.core,
|
||||
&mut self.core,
|
||||
"set_buffers_with_strides",
|
||||
buffers,
|
||||
offsets,
|
||||
@@ -449,7 +453,7 @@ impl ComputeCommandEncoder {
|
||||
) -> Result<(), Error> {
|
||||
self.log(|_| ComputeCall::BufferOffsetWithStride(offset, stride, index));
|
||||
self.table.set_buffer_offset_with_stride(
|
||||
&self.core,
|
||||
&mut self.core,
|
||||
"set_buffer_offset_with_stride",
|
||||
offset,
|
||||
stride,
|
||||
@@ -468,7 +472,7 @@ impl ComputeCommandEncoder {
|
||||
pub fn set_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> {
|
||||
self.log(|log| ComputeCall::Bytes(log.byte_span(bytes), index));
|
||||
self.table
|
||||
.set_bytes(&self.core, "set_bytes", bytes, None, index)
|
||||
.set_bytes(&mut self.core, "set_bytes", bytes, None, index)
|
||||
}
|
||||
|
||||
/// `setBytes:length:attributeStride:atIndex:`: as [`set_bytes`](Self::set_bytes), the
|
||||
@@ -484,7 +488,7 @@ impl ComputeCommandEncoder {
|
||||
) -> Result<(), Error> {
|
||||
self.log(|log| ComputeCall::BytesWithStride(log.byte_span(bytes), stride, index));
|
||||
self.table.set_bytes(
|
||||
&self.core,
|
||||
&mut self.core,
|
||||
"set_bytes_with_stride",
|
||||
bytes,
|
||||
Some(stride),
|
||||
@@ -503,8 +507,12 @@ impl ComputeCommandEncoder {
|
||||
index: u32,
|
||||
) -> Result<(), Error> {
|
||||
self.log(|_| ComputeCall::FunctionTable(table.cloned(), index));
|
||||
self.table
|
||||
.set_function_tables(&self.core, "set_visible_function_table", &[table], index)
|
||||
self.table.set_function_tables(
|
||||
&mut self.core,
|
||||
"set_visible_function_table",
|
||||
&[table],
|
||||
index,
|
||||
)
|
||||
}
|
||||
|
||||
/// `setVisibleFunctionTables:withBufferRange:`: `tables[i]` at buffer index `first + i`.
|
||||
@@ -519,7 +527,7 @@ impl ComputeCommandEncoder {
|
||||
ComputeCall::FunctionTables(tables.iter().map(|table| table.cloned()).collect(), first)
|
||||
});
|
||||
self.table
|
||||
.set_function_tables(&self.core, "set_visible_function_tables", tables, first)
|
||||
.set_function_tables(&mut self.core, "set_visible_function_tables", tables, first)
|
||||
}
|
||||
|
||||
/// `setTexture:atIndex:` (`None` unbinds the index). Refused: an index past the table, a
|
||||
@@ -528,7 +536,7 @@ impl ComputeCommandEncoder {
|
||||
pub fn set_texture(&mut self, texture: Option<&Texture>, index: u32) -> Result<(), Error> {
|
||||
self.log(|_| ComputeCall::Texture(texture.cloned(), index));
|
||||
self.table
|
||||
.set_textures(&self.core, "set_texture", &[texture], index)
|
||||
.set_textures(&mut self.core, "set_texture", &[texture], index)
|
||||
}
|
||||
|
||||
/// `setTextures:withRange:`: `textures[i]` at index `first + i`. Refused as
|
||||
@@ -536,7 +544,7 @@ impl ComputeCommandEncoder {
|
||||
pub fn set_textures(&mut self, textures: &[Option<&Texture>], first: u32) -> Result<(), Error> {
|
||||
self.log(|log| ComputeCall::Textures(log.texture_span(textures), first));
|
||||
self.table
|
||||
.set_textures(&self.core, "set_textures", textures, first)
|
||||
.set_textures(&mut self.core, "set_textures", textures, first)
|
||||
}
|
||||
|
||||
/// `setSamplerState:atIndex:` (`None` unbinds the index). Refused: an index past the table, a
|
||||
@@ -548,7 +556,7 @@ impl ComputeCommandEncoder {
|
||||
) -> Result<(), Error> {
|
||||
self.log(|_| ComputeCall::Sampler(sampler.cloned(), index));
|
||||
self.table
|
||||
.set_samplers(&self.core, "set_sampler_state", &[sampler], None, index)
|
||||
.set_samplers(&mut self.core, "set_sampler_state", &[sampler], None, index)
|
||||
}
|
||||
|
||||
/// `setSamplerStates:withRange:`: `samplers[i]` at index `first + i`. Refused as
|
||||
@@ -565,7 +573,7 @@ impl ComputeCommandEncoder {
|
||||
)
|
||||
});
|
||||
self.table
|
||||
.set_samplers(&self.core, "set_sampler_states", samplers, None, first)
|
||||
.set_samplers(&mut self.core, "set_sampler_states", samplers, None, first)
|
||||
}
|
||||
|
||||
/// `setSamplerState:lodMinClamp:lodMaxClamp:atIndex:`: the state with its LOD clamps
|
||||
@@ -584,7 +592,7 @@ impl ComputeCommandEncoder {
|
||||
ComputeCall::SamplerWithLodClamps(sampler.cloned(), lod_min_clamp, lod_max_clamp, index)
|
||||
});
|
||||
self.table.set_samplers(
|
||||
&self.core,
|
||||
&mut self.core,
|
||||
"set_sampler_state_with_lod_clamps",
|
||||
&[sampler],
|
||||
Some((&[lod_min_clamp], &[lod_max_clamp])),
|
||||
@@ -612,7 +620,7 @@ impl ComputeCommandEncoder {
|
||||
}))
|
||||
});
|
||||
self.table.set_samplers(
|
||||
&self.core,
|
||||
&mut self.core,
|
||||
"set_sampler_states_with_lod_clamps",
|
||||
samplers,
|
||||
Some((lod_min_clamps, lod_max_clamps)),
|
||||
@@ -1179,8 +1187,10 @@ impl ComputeCommandEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the encoder's state back to `state`.
|
||||
/// Set the encoder's state back to `state`: what the table it replaces binds is held until
|
||||
/// the command buffer completes (`ArgumentTable::let_go_all`).
|
||||
pub(super) fn restore_state(&mut self, state: EncoderState) {
|
||||
self.table.let_go_all(&mut self.core);
|
||||
self.pipeline = state.pipeline;
|
||||
self.table = state.table;
|
||||
self.threadgroup_lengths = state.threadgroup_lengths;
|
||||
@@ -1194,8 +1204,10 @@ impl ComputeCommandEncoder {
|
||||
&mut self.captures
|
||||
}
|
||||
|
||||
/// `endEncoding`.
|
||||
pub fn end_encoding(self) -> Result<(), Error> {
|
||||
/// `endEncoding`. What it binds is held until the command buffer completes, as Metal holds
|
||||
/// what an encoder was handed.
|
||||
pub fn end_encoding(mut self) -> Result<(), Error> {
|
||||
self.table.let_go_all(&mut self.core);
|
||||
// Its log, which its command buffer keeps where a rebind may need it (`replay.rs`).
|
||||
let replay = self.log.map(|log| Replay::Compute {
|
||||
dispatch_type: self.dispatch_type,
|
||||
@@ -1560,6 +1572,7 @@ fn record(
|
||||
.map(|blob| (Stage::Kernel, blob))
|
||||
.collect(),
|
||||
mesh: None,
|
||||
tessellation: None,
|
||||
};
|
||||
let mut uses = binding::command_uses(call, &plan, &command, &bound_tables, None, None)?;
|
||||
if let Some((call, _)) = &flat {
|
||||
@@ -1721,7 +1734,7 @@ fn record(
|
||||
};
|
||||
core.pend(next, pending)?;
|
||||
}
|
||||
core.shadows_used(&shadows, &uses);
|
||||
core.shadows_used(&shadows, &uses, &[]);
|
||||
if let Some(creation) = creation {
|
||||
core.executed(|| {
|
||||
Execution::made_later(
|
||||
@@ -1740,7 +1753,7 @@ fn record(
|
||||
// below), and the pipelines are the variant's, one per region.
|
||||
unsafe { recording.record(raw, command_buffer, made) }
|
||||
});
|
||||
core.shadows_used(&shadows, &uses);
|
||||
core.shadows_used(&shadows, &uses, &[]);
|
||||
core.executed(|| {
|
||||
Execution::new(
|
||||
ExecutedPipeline::Compute(Arc::clone(variant.shared_pipeline())),
|
||||
|
||||
@@ -71,6 +71,38 @@ impl<I> Lines<I> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Take `queue`'s line for the calling thread, where no thread runs it and `plain` holds for
|
||||
/// each item it holds: those items, in order, which the caller runs before anything it runs
|
||||
/// in the line itself; the line is running until [`Lines::done`]. `None` otherwise, changing
|
||||
/// nothing.
|
||||
pub(crate) fn take_plain(
|
||||
&mut self,
|
||||
queue: u64,
|
||||
plain: impl Fn(&I) -> bool,
|
||||
) -> Option<VecDeque<I>> {
|
||||
if let Some(line) = self.lines.get(&queue) {
|
||||
if line.running || !line.items.iter().all(plain) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let items = self
|
||||
.lines
|
||||
.remove(&queue)
|
||||
.map_or_else(VecDeque::new, |line| line.items);
|
||||
if !items.is_empty() {
|
||||
// A line that holds an item and runs on no thread is ready, once.
|
||||
self.ready.retain(|ready| *ready != queue);
|
||||
}
|
||||
self.lines.insert(
|
||||
queue,
|
||||
Line {
|
||||
items: VecDeque::new(),
|
||||
running: true,
|
||||
},
|
||||
);
|
||||
Some(items)
|
||||
}
|
||||
|
||||
/// How many lines are ready.
|
||||
pub(crate) fn ready(&self) -> usize {
|
||||
self.ready.len()
|
||||
|
||||
@@ -3,10 +3,14 @@
|
||||
//!
|
||||
//! - **What a context runs.** In its queue's order, each command buffer's transitions: to
|
||||
//! `Scheduled` with its scheduled handlers, and to `Completed` (or `Error`) with its completed
|
||||
//! handlers and the release of what it retained. The scheduler and the completion thread only
|
||||
//! post them ([`Contexts::post`]); they run no such handler. (A transition to `Scheduled` waits
|
||||
//! for its command buffer's submission handlers, which the thread that submitted its last batch
|
||||
//! runs.)
|
||||
//! handlers and the release of what it retained. The scheduler posts them ([`Contexts::post`]),
|
||||
//! and so does a completion turn, but for a transition that runs none of the program's code,
|
||||
//! which the turn runs itself where the context runs on no thread and holds only such
|
||||
//! transitions, in order after them ([`Contexts::run_here`], `command_buffer/completion.rs`);
|
||||
//! neither runs a handler. (A transition to `Scheduled` waits for its command buffer's
|
||||
//! submission handlers, which the thread that submitted its last batch runs.) A release the
|
||||
//! scheduler's thread hands off (`Device::let_go_elsewhere`) runs in a context of its own,
|
||||
//! behind no queue's handlers.
|
||||
//! - **Metal's order** (measured on an M4, macOS 27.0.1, EV `RT4-metal-order`): while one of a
|
||||
//! queue's handlers blocks, the queue's later transitions wait, even of a command buffer whose
|
||||
//! work already ran; another queue's transitions and handlers go on, on another thread. Metal
|
||||
@@ -19,9 +23,10 @@
|
||||
//! buffer blocks its thread. It is refused when it would close a cycle of such waits (across
|
||||
//! every device) or leave the device's pool with no thread that is not blocked so; then at least
|
||||
//! one thread can always run the contexts the blocked waits wait for.
|
||||
//! - **Stopping.** The device's drop stops the threads once none runs an item (every item holds
|
||||
//! its command buffer, which holds the device). A drop on one of the threads (its item held the
|
||||
//! last reference) does not wait for itself.
|
||||
//! - **Stopping.** The device's drop stops the threads, which end once no item is left: a
|
||||
//! transition holds its command buffer, which holds the device, so none is left by then; a
|
||||
//! release may hold nothing of the device, and runs before its thread ends. A drop on one of the
|
||||
//! threads (its item held the last reference) does not wait for itself.
|
||||
//!
|
||||
//! Locks: a pool's state, then its census; the waits' graph, then a census. No call made under
|
||||
//! either takes the state again.
|
||||
@@ -47,10 +52,17 @@ pub(crate) const STACK: usize = 512 * 1024;
|
||||
/// How long a thread other than the first finds nothing to run before it ends.
|
||||
const IDLE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// An item of a queue's context: run once, on one of the device's handler threads.
|
||||
/// An item of a queue's context: run once, on one of the device's handler threads, or on the
|
||||
/// thread that runs the context itself ([`Contexts::run_here`]).
|
||||
pub(crate) trait Run: Send + 'static {
|
||||
/// Run the item; dropping it lets go of what it holds.
|
||||
fn run(self);
|
||||
|
||||
/// Whether the item runs none of the program's code (no handler, no notice, no release of
|
||||
/// the program's), so that a thread that may run none can run it: none by default.
|
||||
fn plain(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// One device's handler threads. A clone is another handle of the same pool, which holds nothing
|
||||
@@ -134,6 +146,34 @@ impl<I: Run> Contexts<I> {
|
||||
pub(crate) fn post(&self, queue: u64, item: I) {
|
||||
let mut state = lock(&self.shared.state);
|
||||
state.lines.push(queue, item);
|
||||
self.serve(state);
|
||||
}
|
||||
|
||||
/// Run `item` in the context of logical queue `queue` on this thread, after the items that
|
||||
/// context holds, where no thread runs that context and those items and `item` are all
|
||||
/// [`plain`](Run::plain): the context runs on this thread meanwhile, so the items posted to
|
||||
/// it wait for `item`, then run on the pool's threads. Else give `item` back, changing
|
||||
/// nothing.
|
||||
pub(crate) fn run_here(&self, queue: u64, item: I) -> Result<(), I> {
|
||||
if !item.plain() {
|
||||
return Err(item);
|
||||
}
|
||||
let Some(before) = lock(&self.shared.state).lines.take_plain(queue, I::plain) else {
|
||||
return Err(item);
|
||||
};
|
||||
for earlier in before {
|
||||
earlier.run();
|
||||
}
|
||||
item.run();
|
||||
let mut state = lock(&self.shared.state);
|
||||
state.lines.done(queue);
|
||||
self.serve(state);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start a thread where a context is ready that no free thread will take, below the cap, and
|
||||
/// wake one: `state` was just changed.
|
||||
fn serve(&self, mut state: std::sync::MutexGuard<'_, State<I>>) {
|
||||
if state.lines.ready() > state.free {
|
||||
let start = {
|
||||
let mut count = lock(&self.shared.census.count);
|
||||
@@ -159,8 +199,8 @@ impl<I: Run> Contexts<I> {
|
||||
self.shared.wake.notify_one();
|
||||
}
|
||||
|
||||
/// Stop the threads and wait for them to end, but for this one when it is one of them. The
|
||||
/// device is being dropped, so no item is left.
|
||||
/// Stop the threads and wait for them to end, but for this one when it is one of them: each
|
||||
/// runs the items left first. The device is being dropped, so no transition is left.
|
||||
pub(crate) fn stop(&self) {
|
||||
lock(&self.shared.state).stopping = true;
|
||||
self.shared.wake.notify_all();
|
||||
@@ -235,6 +275,11 @@ fn run<I: Run>(shared: &Shared<I>, first: bool) {
|
||||
shared.census.gone.notify_all();
|
||||
}
|
||||
|
||||
/// Whether this thread is one of a pool's handler threads.
|
||||
pub(crate) fn on_handler_thread() -> bool {
|
||||
POOL.with(|pool| pool.borrow().is_some())
|
||||
}
|
||||
|
||||
/// A handler thread's wait for another queue's context, counted until dropped.
|
||||
pub(crate) struct Blocked {
|
||||
census: Arc<Census>,
|
||||
|
||||
@@ -510,6 +510,34 @@ impl HostLayout {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the host bytes `host` of 32-bit float texels (a depth's) hold a negative value other
|
||||
/// than a zero or a denormal, or a NaN of either sign, in a row.
|
||||
pub(super) fn holds_negative_or_nan(&self, host: &[u8]) -> bool {
|
||||
let n = self.row_bytes as usize;
|
||||
self.rows().any(|(h, _)| {
|
||||
host[h..h + n].as_chunks::<4>().0.iter().any(|word| {
|
||||
let bits = u32::from_le_bytes(*word);
|
||||
let exponent = bits & 0x7f80_0000;
|
||||
let nan = exponent == 0x7f80_0000 && bits & 0x007f_ffff != 0;
|
||||
nan || (bits & 0x8000_0000 != 0 && exponent != 0)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the host bytes `host` of 32-bit float texels (a depth's) hold, in a row, a word
|
||||
/// whose magnitude stand-in (`bind::DepthMagnitudeModule::stand_in`, a denormal's the smallest
|
||||
/// normal where `flush`) is not itself: a negative value, -0 included, a NaN, or where `flush`
|
||||
/// a denormal; a depth test of the device's compares such a value otherwise than Metal's.
|
||||
pub(super) fn holds_unlike_its_stand_in(&self, host: &[u8], flush: bool) -> bool {
|
||||
let n = self.row_bytes as usize;
|
||||
self.rows().any(|(h, _)| {
|
||||
host[h..h + n].as_chunks::<4>().0.iter().any(|word| {
|
||||
let bits = u32::from_le_bytes(*word);
|
||||
metal2vulkan::bind::DepthMagnitudeModule::stand_in(bits, flush) != bits
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Unpacks `packed` into the host bytes `host`, leaving the bytes between rows untouched;
|
||||
/// rows that overlap are written in order, image by image and row by row, so the later
|
||||
/// row's bytes stay.
|
||||
|
||||
@@ -67,7 +67,7 @@ use super::texture_descriptor::TextureDescriptor;
|
||||
use super::values::ResourceOptions;
|
||||
use metal2vulkan::bind::PlanDiagnostic;
|
||||
use metal2vulkan::cache::SpecializationKey;
|
||||
use metal2vulkan::device::{DriverFact, Requirements, VkProperty};
|
||||
use metal2vulkan::device::{DriverFact, FunctionStorage, Requirements, VkProperty};
|
||||
use metal2vulkan::metal::PixelFormat;
|
||||
use metal2vulkan::pipeline::{PrecisionNote, Reconvergence, SlotRef, SpecKey, StageModule};
|
||||
use metal2vulkan::vk::{ImageAspectFlags, ShaderStage};
|
||||
@@ -284,18 +284,39 @@ degradations! {
|
||||
"they are copied into a buffer of the command buffer before the pass, between two \
|
||||
barriers, and the draw reads the bytes from before the write, which Metal's draw \
|
||||
read in every run measured";
|
||||
/// A draw biases a `Depth16Unorm` depth by a constant on a device whose driver is not
|
||||
/// measured to store Metal's codes so (`DriverFact::UnormDepthBiasIsMetals`,
|
||||
/// `render_state.rs`).
|
||||
/// A draw biases a `Depth16Unorm` depth by a constant, or by a slope alone, which brings
|
||||
/// Metal's constant unit, on a device whose driver is not measured to store Metal's codes
|
||||
/// so (`DriverDeviation::MetalDepth16BiasedStores`, `render_state.rs`), through a
|
||||
/// pipeline whose fragment stage does not add the bias itself (more than one sample,
|
||||
/// early fragment tests, the draw's tests run in the shader, a function that returns its
|
||||
/// depth or reads its position's depth).
|
||||
UnormDepthBias = "unorm-depth-bias", Precision,
|
||||
"a biased depth can store a code next to Metal's: the device rounds the biased sum \
|
||||
its own way, and without depthBiasExact counts the bias in its own unit";
|
||||
/// A draw tests or writes a `Depth16Unorm` depth on a device whose driver is not measured
|
||||
/// to convert a depth to Metal's code (`DriverFact::Depth16UnormStoresMetals`,
|
||||
/// `render_state.rs`).
|
||||
/// to convert a depth to Metal's code (`DriverDeviation::MetalDepth16Stores`,
|
||||
/// `render_state.rs`), through a pipeline whose fragment stage cannot write the code
|
||||
/// itself (more than one sample, early fragment tests, the draw's tests run in the shader,
|
||||
/// a function that reads its position's depth and returns none), or through one that
|
||||
/// does, in depth clamp mode, whose range the device clamps the depth to.
|
||||
UnormDepthRounding = "unorm-depth-rounding", Precision,
|
||||
"a depth near a code's midpoint can store the code below Metal's: the device converts \
|
||||
the depth to the 16-bit code its own way, where Metal rounds to nearest, a tie up";
|
||||
/// A draw tests or writes a `Depth16Unorm` depth through a fragment stage that writes each
|
||||
/// depth as Metal's code, on a device whose driver is not measured to store Metal's codes
|
||||
/// (`DriverDeviation::MetalDepth16Stores`, or for a biased draw
|
||||
/// `DriverDeviation::MetalDepth16BiasedStores`; `RuntimeFact::Depth16Codes`,
|
||||
/// `render_state.rs`); a pipeline without a fragment function draws through a fragment
|
||||
/// stage of its own.
|
||||
ShaderUnormDepth = "shader-unorm-depth", Performance,
|
||||
"the fragment stage writes each depth as Metal's code, about 50 more instructions \
|
||||
per fragment, which keeps the device from testing the depth before the stage runs";
|
||||
/// A draw biases a `Depth16Unorm` depth by a slope through a fragment stage that adds
|
||||
/// Metal's bias itself (`RuntimeFact::Depth16Codes`, `render_state.rs`).
|
||||
UnormDepthSlope = "unorm-depth-slope", Precision,
|
||||
"the fragment stage takes the depth's slope from the depths of its 2x2 quad, where \
|
||||
Metal takes the triangle's own: a biased depth near a code's midpoint can store \
|
||||
the code next to Metal's";
|
||||
/// A draw of points keeps Vulkan's clipping of points, where Metal's guard band cannot be
|
||||
/// emulated: in a rate-mapped pass, on a device without `shaderClipDistance` or with too
|
||||
/// few clip distances beside the vertex function's own, or through a viewport whose
|
||||
@@ -390,6 +411,26 @@ degradations! {
|
||||
threadgroups the GPU decides is scanned first and reserves its records in the \
|
||||
command buffer's records pool (a sixty-fourth of the device's largest device-local \
|
||||
heap), and a draw the pool cannot hold fails the command buffer";
|
||||
/// A tessellation pipeline's patch draws on a device without `tessellationShader`
|
||||
/// (`render/tessellation_scan.rs`).
|
||||
EmulatedTessellationDraws = "emulated-tessellation-draws", Performance,
|
||||
"each patch draw runs a scan dispatch before the pass, between barriers: one \
|
||||
workgroup that processes the draw's patches, instance by instance, into records in \
|
||||
order, so its GPU time grows with the draw's patches times its instances, apart \
|
||||
from its draw; the draw then draws the tessellator's triangles with the \
|
||||
post-tessellation vertex function as a plain vertex function, up to 2^30 triangles \
|
||||
per indirect draw; an indirect draw reserves its records in the command buffer's \
|
||||
records pool (a sixty-fourth of the device's largest device-local heap), and a draw \
|
||||
the pool cannot hold fails the command buffer";
|
||||
/// A render pipeline state whose draws run a synthesized geometry stage
|
||||
/// (`RuntimeFact::SynthesizedGeometry`): its fragment function reads
|
||||
/// `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric`, or its vertex
|
||||
/// function selects its primitive's render target slice or viewport on a device that
|
||||
/// cannot store `Layer` or `ViewportIndex` from a vertex function.
|
||||
SynthesizedGeometryStage = "synthesized-geometry-stage", Performance,
|
||||
"each draw runs a geometry stage of its topology class between the vertex and \
|
||||
fragment stages, which emits each primitive's vertices with the barycentric weights \
|
||||
or the first vertex's slice and viewport";
|
||||
/// Visibility results start where Vulkan writes no query result.
|
||||
LandedVisibilityResults = "landed-visibility-results", Performance,
|
||||
"they land in an upload region and are copied on into the buffer after the pass";
|
||||
@@ -449,7 +490,8 @@ degradations! {
|
||||
ShaderResolve = "shader-resolve", Performance,
|
||||
"one more render pass instance after the pass reads the stored samples (or the \
|
||||
sample planes) and writes the resolve texture, where the device would resolve in \
|
||||
the pass";
|
||||
the pass; where the attachment's image takes no input attachment usage, a copy of \
|
||||
its samples over the render area into a scratch image first";
|
||||
/// A fragment function writes a float to a normalized, sRGB or half-float color
|
||||
/// attachment on a device whose own conversion is not Metal's
|
||||
/// (`StageModule::rounded_colors`).
|
||||
@@ -514,6 +556,9 @@ degradations! {
|
||||
/// made again with `STORAGE` and its texels copied in once, at the commit of the device's
|
||||
/// only uncommitted command buffer (`texture/storage_form.rs`); with a submission check,
|
||||
/// once that command buffer's checks ran at its submission and every encoder of it ran.
|
||||
/// Announced once per device, whatever `DeviceOptions::announce_each` says, before that
|
||||
/// command buffer is scheduled: on the scheduler's thread once it submitted it, outside any
|
||||
/// program call or host step, or in the call that makes a command buffer meanwhile.
|
||||
FetchedTargetStorage = "fetched-target-storage", Performance,
|
||||
"the texture's image laid out as one with `STORAGE` usage from then on (on MoltenVK \
|
||||
`ShaderWrite`, without lossless compression), and one copy of its texels, where \
|
||||
@@ -584,7 +629,9 @@ degradations! {
|
||||
/// A command buffer's GPU times on a device that calibrates its timestamps against no
|
||||
/// host clock the runtime reads (no `VK_KHR_calibrated_timestamps` or
|
||||
/// `VK_EXT_calibrated_timestamps` with the device's time domain and a monotonic host
|
||||
/// one), or whose calibration failed at the commit (`gpu_time.rs`).
|
||||
/// one), whose calibration failed at the commit, or whose calibration placed them outside
|
||||
/// the command buffer's life (before its first submission, after its completion) by more
|
||||
/// than its stated deviation and the clocks' drift allow (`gpu_time.rs`).
|
||||
UncalibratedGpuTimes = "uncalibrated-gpu-times", Precision,
|
||||
"the end is the host time the runtime saw the command buffer complete, late by that \
|
||||
latency, and the start the GPU's exact duration before it";
|
||||
@@ -613,11 +660,11 @@ degradations! {
|
||||
/// A multisample color resolve averages through Vulkan's `AVERAGE` mode, which leaves
|
||||
/// the rounding of the average (and the sRGB encoding) to the device, on a device not
|
||||
/// measured to round as Metal does: a format without Metal's closed rule at its count
|
||||
/// (half floats past 2 samples, packed 16-bit, `RG11B10Float`, `RGB9E5Float`), or an
|
||||
/// attachment whose image the
|
||||
/// exact resolve cannot read (`color_resolve.rs`). Not where
|
||||
/// `DriverFact::ColorResolveAverageIsMetals` holds, for any format: MoltenVK's resolve is
|
||||
/// Metal's own.
|
||||
/// (the 16-bit float, `RG11B10Float` and `RGB9E5Float` formats past 4 samples, and a
|
||||
/// format no rule covers), or an attachment whose image the exact resolve can neither read
|
||||
/// nor copy: an image without input attachment usage of a format the device does not copy
|
||||
/// (`color_resolve.rs`). Not where `DriverFact::ColorResolveAverageIsMetals` holds, for
|
||||
/// any format: MoltenVK's resolve is Metal's own.
|
||||
/// The device also decides what a NaN or infinite sample makes of the average, where
|
||||
/// Metal's resolve counts a NaN of a `half` or small-float channel as 0 and an infinite
|
||||
/// `half` as 65536 of its sign, and makes any NaN of a 32-bit float channel `0x7fc00000`
|
||||
@@ -710,7 +757,8 @@ degradations! {
|
||||
/// texture's depth image, on a device without `VK_EXT_depth_range_unrestricted` enabled,
|
||||
/// where Vulkan leaves a value outside `[0, 1]` undefined, whose driver is not measured to
|
||||
/// keep one (`DriverFact::DepthImageKeepsValuesOutsideUnitRange`): a texture without a
|
||||
/// twin.
|
||||
/// twin. And a render pass's NaN clear depth on such a device, which Metal stores as
|
||||
/// `0x7fc00000`, cleared to 1.0 (`nan_clear.rs`).
|
||||
RestrictedDepthUpload = "restricted-depth-upload", Precision,
|
||||
"a value outside [0, 1] may be stored clamped to [0, 1], where Metal's keeps it, so \
|
||||
reads, samples, comparisons and depth tests of it can differ";
|
||||
@@ -814,6 +862,10 @@ degradations! {
|
||||
/// without `imageViewFormatReinterpretation`, or an adopted device whose consumer did not
|
||||
/// say it enabled it), or a view of another format than the texture's own and its sRGB
|
||||
/// twin's of a texture made without `PixelFormatView` usage (`texture/view_shadow.rs`).
|
||||
/// A view in other channels of its image's bits (an `A8Unorm` view of an `R8Unorm`
|
||||
/// texture) is the image itself to its bindings, through a swizzle, and takes a shadow
|
||||
/// only for a pass that renders into it: Vulkan views the image in no format of the
|
||||
/// view's.
|
||||
ShadowedTextureView = "shadowed-texture-view", Performance,
|
||||
"its texels are copied from its texture's image before each use and back after each \
|
||||
write";
|
||||
@@ -822,7 +874,8 @@ degradations! {
|
||||
/// texture, array or cube of three levels or more whose M3 Max passes are not known (a
|
||||
/// compressed texture's pass from a level more than 128 times wider than tall or taller
|
||||
/// than wide), an `A1BGR5Unorm` 2D texture, an `ABGR4Unorm` one of three levels or more, or
|
||||
/// a 3D texture of a format summed as half floats.
|
||||
/// a 3D texture of a format summed as half floats, under macOS 26.7's rule
|
||||
/// (`MipmapRule::AppleM3MaxPasses`). Under macOS 27.0.1's every level is the M3 Max's.
|
||||
MipmapsAsAppleM4 = "mipmaps-as-apple-m4", Precision,
|
||||
"each level is the Apple M3 Max's but where its answer is not known: below the first \
|
||||
level of a 2D chain whose M3 Max passes are not known an Apple M4's filter, and a \
|
||||
@@ -844,7 +897,8 @@ degradations! {
|
||||
/// made as without it, and reports its options without it, as Metal's does.
|
||||
PrivateResourceOption = "private-resource-option", Precision,
|
||||
"the private option has no effect here: on Metal a no-copy buffer made with it kept \
|
||||
the GPU's writes from the CPU (RT4 probe nc_bit24), where the runtime's reach it";
|
||||
the GPU's writes from the CPU (Metal probe nc_bit24 on an M4), where the runtime's \
|
||||
reach it";
|
||||
/// A depth or stencil texture with `allowGPUOptimizedContents` off sized or made, outside
|
||||
/// memoryless storage, on a device whose driver keeps depth and stencil images
|
||||
/// GPU-optimized whatever their create info
|
||||
@@ -1088,8 +1142,8 @@ degradations! {
|
||||
/// encoder the rebind could not encode again (A resource state encoder, which logs no
|
||||
/// calls; a command predication's command buffer; a render pass recorded later or whose end
|
||||
/// captured its draws' tile reach; a call refused again; `replay.rs`). Announced once, as
|
||||
/// the first such submission is made, on the thread that makes it (the committing thread,
|
||||
/// or the scheduler's): `DeviceOptions::announce_each` does not repeat it, as no program
|
||||
/// the first such submission is made, on the scheduler's thread, which makes it:
|
||||
/// `DeviceOptions::announce_each` does not repeat it, as no program
|
||||
/// call or host step meets it.
|
||||
EncodedUseRebound = "encoded-use-rebound", Precision,
|
||||
"each of Metal's submissions of the command buffer holding such a command runs \
|
||||
@@ -1228,12 +1282,13 @@ degradations! {
|
||||
/// rounding the chain does not fit at sums a hair from a rounding boundary
|
||||
/// (`MipmapFilterChain::near_ties`): a texture of a format with an 8-bit sRGB colour
|
||||
/// channel (`R8Unorm_sRGB`, `RG8Unorm_sRGB`, `RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB`), whose
|
||||
/// filtered levels take it; of an extended-range sRGB format (`BGR10_XR_sRGB`,
|
||||
/// `BGRA10_XR_sRGB`), whose filtered levels and levels read from kept values take it; or of
|
||||
/// a 16-bit float format (`R16Float`, `RG16Float`, `RGBA16Float`) with a level read from
|
||||
/// the level above's kept values (a 2D chain's even level below a square of a power of two,
|
||||
/// a pass's second level). `RGB10A2Unorm`, `BGR10A2Unorm`, `BGR10_XR`, `BGRA10_XR`,
|
||||
/// `ABGR4Unorm` and `A1BGR5Unorm` are exact.
|
||||
/// filtered levels take it; under macOS 26.7's rule (`MipmapRule::AppleM3MaxPasses`), of an
|
||||
/// extended-range sRGB format (`BGR10_XR_sRGB`, `BGRA10_XR_sRGB`), whose filtered levels
|
||||
/// and levels read from kept values take it; or of a 16-bit float format (`R16Float`,
|
||||
/// `RG16Float`, `RGBA16Float`) with a level read from the level above's kept values (a 2D
|
||||
/// chain's even level below a square of a power of two, a pass's second level).
|
||||
/// `RGB10A2Unorm`, `BGR10A2Unorm`, `BGR10_XR`, `BGRA10_XR`, `ABGR4Unorm` and `A1BGR5Unorm`
|
||||
/// are exact.
|
||||
MipmapTieRounding = "mipmap-tie-rounding", Precision,
|
||||
"each level is Metal's but at a value whose sum lies a hair from a rounding boundary, \
|
||||
which may be one unit off: an 8-bit sRGB colour code of a filtered level (1 of \
|
||||
@@ -1427,19 +1482,35 @@ degradations! {
|
||||
"an image of the attachment's size, which its texture keeps for the queue, renders the \
|
||||
pass; a `Load` copies the buffer's texels over the render area into it before the \
|
||||
pass, and nothing is copied back";
|
||||
/// A no-copy buffer or heap released with a deallocator and no keep-alive
|
||||
/// ([`KeepAlive`](crate::KeepAlive)) while the device's import of its pages is still held:
|
||||
/// a command buffer submitted before a texture over them was released may still read
|
||||
/// that texture through its resource ID, and its image holds the import until the
|
||||
/// command buffer completes (`heap_sets.rs`). The deallocator runs once the import is
|
||||
/// freed (`buffer.rs`), as Vulkan requires the pages to stay mapped while imported.
|
||||
/// A no-copy buffer or heap released with a deallocator while a command buffer that may
|
||||
/// still reach its pages holds them. Metal runs the deallocator at the release, even while
|
||||
/// a command buffer in flight reaches the buffer unnamed, and that command buffer's later
|
||||
/// accesses reach nothing (the M3 Max under macOS 27.0.1, probe `dealloc-probe4`: through a
|
||||
/// loaded pointer, and through an indirect command the GPU encoded with the buffer's
|
||||
/// address). Vulkan frees no memory that submitted commands may still use
|
||||
/// (`VUID-vkFreeMemory-memory-00677`: all submitted commands that refer to memory must
|
||||
/// have completed execution), and keeps imported pages mapped while imported, so the pages
|
||||
/// stay, and the deallocator runs once they go (`buffer.rs`):
|
||||
/// - with no keep-alive ([`KeepAlive`](crate::KeepAlive)), while the device's import of
|
||||
/// them is held: a command buffer submitted before a texture over them was released may
|
||||
/// still read that texture through its resource ID, and its image holds the import until
|
||||
/// the command buffer completes (`heap_sets.rs`);
|
||||
/// - with or without one, while a live buffers' table that lists them is held: a command
|
||||
/// buffer whose commands may reach the buffer unnamed holds its first submission's table
|
||||
/// and its host steps' until it completes, and one a rebind encoded again, or a host
|
||||
/// step recorded, before its first submission until then (`live_buffers.rs`);
|
||||
/// - with no keep-alive, on a device whose driver fails pending work where memory a
|
||||
/// device-address buffer lay in is freed
|
||||
/// (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`: MoltenVK), while the
|
||||
/// batches submitted before the import's memory went are in flight (`freed_memory.rs`).
|
||||
///
|
||||
/// Announced once per device, on the thread that lets go of the buffer last, whatever
|
||||
/// `DeviceOptions::announce_each` says: that may be a runtime thread, as a command
|
||||
/// buffer that used the buffer completes, outside any program call or host step.
|
||||
HostDeallocatorDelayed = "host-deallocator-delayed", Precision,
|
||||
"the deallocator runs once every command buffer submitted before the texture's \
|
||||
release completed, where Metal's runs at the release; the pages stay mapped until \
|
||||
then";
|
||||
"the deallocator runs once every command buffer that may still reach the pages \
|
||||
(through a texture over them, or a table of the live buffers it holds) lets go of \
|
||||
them, where Metal's runs at the release; the pages stay mapped until then";
|
||||
/// In a build without debug assertions, a notice announced where the runtime's rule
|
||||
/// announces none ([`DegradeNotice::misplaced`] names its kind and [`NoticePlace`]):
|
||||
/// inside a pipeline pool's piece, or, for a kind announced at every occurrence, outside
|
||||
@@ -1458,12 +1529,59 @@ degradations! {
|
||||
/// ANV; a host copy keeps it) or whose depth test compares one otherwise than Metal's (no
|
||||
/// `DriverFact::DepthTestKeepsDenormals`: every driver measured but MoltenVK on an Apple
|
||||
/// M4). Metal's texel keeps it, and its depth test compares a positive one above zero and
|
||||
/// a negative one not below zero. A draw at a denormal depth stores zero on Metal too,
|
||||
/// and announces nothing.
|
||||
/// a negative one not below zero. Where the driver stores it and only its depth test
|
||||
/// differs, a single-sample `Depth32Float` render target's passes test the smallest normal
|
||||
/// in its place (`texture/signed_depth.rs`): Metal's answer but for a fragment at exactly
|
||||
/// 2^-126, which passes `Equal` and fails `Greater` against it, where Metal's fails and
|
||||
/// passes; the payload says so. A draw at a denormal depth stores zero on Metal too, and
|
||||
/// announces nothing.
|
||||
DepthDenormals = "depth-denormals", Precision,
|
||||
"a denormal depth may read, sample and copy out as a zero, or the depth test may \
|
||||
compare it as zero (a positive one) or below zero (a negative one), where Metal \
|
||||
keeps it and compares a positive one above zero and a negative one not below it";
|
||||
keeps it and compares a positive one above zero and a negative one not below it; a \
|
||||
render target whose passes test the smallest normal in its place differs only for a \
|
||||
fragment at exactly 2^-126";
|
||||
/// A depth test that may compare a negative value or a NaN stored in the 32-bit float depth
|
||||
/// of a render target as it is, or a pass with depth writes that may store such a value
|
||||
/// with its sign. Metal's depth test compares the fragment's depth with the stored value's
|
||||
/// magnitude, as the integers of their low 31 bits: a stored -0.5 passes `Equal` for a
|
||||
/// fragment at 0.5, and a stored NaN orders above +inf (probe `depthkeep`, the M3 Max under
|
||||
/// macOS 27.0.1: 270 of 270 outcomes); and a pass that sets a depth/stencil state with
|
||||
/// depth writes stores each texel no fragment wrote without its sign (probe `depthstore`).
|
||||
/// Vulkan's compares the stored value as it is, and its pass keeps it. A single-sample
|
||||
/// `Depth32Float` render target that a write may give such a value renders the passes that
|
||||
/// load its depth over its magnitude stand-in (`texture/signed_depth.rs`), whose tests and
|
||||
/// stores are Metal's, and announces only the corners: a pass that writes its depth over
|
||||
/// the stand-in, whose merge keeps a stored NaN where a draw wrote exactly +inf, its
|
||||
/// stand-in, over it; a pass that loads it through another image (separate depth and
|
||||
/// stencil textures' scratch image, a stand-in for custom sample positions); and a write
|
||||
/// that switches it on while another command buffer is uncommitted, whose passes encoded
|
||||
/// before it test and store the value as it is. A multisampled or `Depth32Float_Stencil8`
|
||||
/// target takes no stand-in: its words are stripped of their signs after a pass with depth
|
||||
/// writes, Metal's stores, and its test, which compares the value as it is, is announced
|
||||
/// at the write (a blit's copy into its depth), on a device that keeps such a value there
|
||||
/// (`VK_EXT_depth_range_unrestricted` enabled, or
|
||||
/// `DriverFact::DepthImageKeepsValuesOutsideUnitRange`; elsewhere `restricted-depth-upload`
|
||||
/// is announced), as is a strip the device does not make. A denormal tested over the
|
||||
/// smallest normal is `depth-denormals`'. A device whose depth test compares magnitudes as
|
||||
/// Metal's (`DriverFact::DepthTestComparesMagnitudes`: MoltenVK, whose test and store are
|
||||
/// the GPU's own Metal ones) renders every target's depth in place, strips a switched-on
|
||||
/// depth's signs after a pass that sets a state with depth writes but draws under none,
|
||||
/// which its pass leaves signed, and announces it only for a switch while another command
|
||||
/// buffer is uncommitted. A render pass's NaN clear depth, which Metal stores as
|
||||
/// `0x7fc00000` and tests above every value, is written into the depth before the pass and
|
||||
/// loaded (`nan_clear.rs`); where the device writes no such word (a memoryless depth, a
|
||||
/// multisampled one without maintenance8's colour copies or an exact `FragDepth`, a pass
|
||||
/// that does not store it on a device that keeps the earlier texels there), it is cleared
|
||||
/// to 1.0, announced here.
|
||||
SignedDepthTest = "signed-depth-test", Precision,
|
||||
"a depth test against the stored value, or the value a pass with depth writes stores, \
|
||||
can differ from Metal's in the pass or target named: the device compares a negative \
|
||||
value below zero and a NaN by its own rule and keeps the value's sign, or a pass's \
|
||||
merge keeps a stored NaN where a draw wrote +inf over it, where Metal compares the \
|
||||
value's magnitude, orders a NaN above every value, stores the value without its sign \
|
||||
and stores the draw's; or a NaN clear depth is stored and tested as 1.0, where Metal \
|
||||
stores 0x7fc00000";
|
||||
/// The device's first sparse texture made (`Heap::new_texture` in a sparse heap) on a
|
||||
/// device whose driver's first sparse resource waits for the work submitted before it on
|
||||
/// every queue (`DriverFact::FirstSparseResourceWaitsForQueues`: ANV through TR-TT, Mesa
|
||||
@@ -1521,6 +1639,14 @@ degradations! {
|
||||
"the points rasterize nothing, the vertex function run for each, where what Metal \
|
||||
draws is undefined: most of its draws draw nothing, and some a few of the points \
|
||||
or a box";
|
||||
/// A draw counted by a `Counting` visibility result whose fragment variant writes more
|
||||
/// than one color attachment, on a device whose driver counts each sample once per color
|
||||
/// output ([`metal2vulkan::error::RuntimeDriverDefect::OcclusionCountPerColorOutput`]:
|
||||
/// ANV). Announced at the draw's call, or where the runtime records an execution's
|
||||
/// command; the payload names the draw and its colors.
|
||||
VisibilityCountPerColor = "visibility-count-per-color", Precision,
|
||||
"the result is Metal's count multiplied by the colors the draw writes; a `Boolean` \
|
||||
result is Metal's";
|
||||
}
|
||||
notes {
|
||||
F16FmaDoubleRounding = "f16-fma-double-rounding";
|
||||
@@ -1677,6 +1803,11 @@ degradations! {
|
||||
/// (1 - t)| + |y * t|)` of Metal's; a `half` one within `3 * 2^-10 * (|x * (1 - t)| + |y *
|
||||
/// t|) + 2^-23`.
|
||||
NativeMix = "native-mix";
|
||||
/// A render pipeline whose color attachments the device draws in more than one group:
|
||||
/// each draw runs once per group, each group's variant over its own copy of the pass's
|
||||
/// depth and stencil. Recorded bound: groups past the first may differ at discard or
|
||||
/// depth edges if the driver compiles the variants differently; nothing broader.
|
||||
ColorAttachmentGroups = "color-attachment-groups";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1964,6 +2095,25 @@ impl Announced {
|
||||
}
|
||||
}
|
||||
|
||||
/// `recorded`, the reason of a stage that records `PrecisionNote::FunctionStorageAssumed`, with
|
||||
/// the private memory a thread of the stage keeps, `private_bytes`, and the Function storage the
|
||||
/// device holds, `held`, measured or the floor of a device not measured: numbers only.
|
||||
pub(crate) fn function_storage_reason(
|
||||
recorded: &str,
|
||||
private_bytes: u64,
|
||||
held: FunctionStorage,
|
||||
) -> String {
|
||||
let evidence = match held {
|
||||
FunctionStorage::Measured(_) => "measured on this device",
|
||||
_ => "the floor of a device whose Function storage is not measured",
|
||||
};
|
||||
format!(
|
||||
"{recorded}: it keeps {private_bytes} bytes of private memory a thread, past the {} bytes \
|
||||
a thread {evidence}",
|
||||
held.bytes()
|
||||
)
|
||||
}
|
||||
|
||||
/// Kinds of degradation, a bit each: those a variant's making may announce
|
||||
/// (`VariantObjects::kinds`), which a bind of the variant tests against the kinds the device
|
||||
/// announces at every occurrence before it announces any.
|
||||
@@ -2385,7 +2535,7 @@ impl Device {
|
||||
continue;
|
||||
}
|
||||
self.degrade_at(at, Degradation::from_precision_note(note), || {
|
||||
(object(), self.note_reason(note))
|
||||
(object(), self.stage_note_reason(note, stage))
|
||||
});
|
||||
}
|
||||
if !stage.half_bit_colors.is_empty() {
|
||||
@@ -2476,6 +2626,49 @@ impl Device {
|
||||
});
|
||||
}
|
||||
|
||||
/// Announce, once, a render pipeline state `object` whose `dependencies` state that its draws
|
||||
/// run a synthesized geometry stage ([`Degradation::SynthesizedGeometryStage`]), naming why:
|
||||
/// the barycentric weights its fragment function reads, or the slice or viewport its vertex
|
||||
/// function selects.
|
||||
pub(super) fn degrade_synthesized_geometry(
|
||||
&self,
|
||||
dependencies: &[metal2vulkan::pipeline::RuntimeDependency],
|
||||
object: impl FnOnce() -> String,
|
||||
) {
|
||||
let Some((weights, layer, viewport)) = dependencies.iter().find_map(|d| match d.fact {
|
||||
metal2vulkan::pipeline::RuntimeFact::SynthesizedGeometry {
|
||||
weights,
|
||||
layer,
|
||||
viewport,
|
||||
} => Some((weights, layer, viewport)),
|
||||
_ => None,
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
self.degrade(Degradation::SynthesizedGeometryStage, || {
|
||||
let mut why = Vec::new();
|
||||
if weights {
|
||||
why.push(
|
||||
"its fragment function reads [[barycentric_coord]] on a device without \
|
||||
fragmentShaderBarycentric",
|
||||
);
|
||||
}
|
||||
if layer {
|
||||
why.push(
|
||||
"its vertex function selects its primitive's render target slice on a device \
|
||||
that cannot store Layer from a vertex function",
|
||||
);
|
||||
}
|
||||
if viewport {
|
||||
why.push(
|
||||
"its vertex function selects its primitive's viewport on a device that cannot \
|
||||
store ViewportIndex from a vertex function",
|
||||
);
|
||||
}
|
||||
(object(), why.join(", and "))
|
||||
});
|
||||
}
|
||||
|
||||
/// Announce `PrecisionNote::DeviceNanEncoding` at a draw or dispatch of a pipeline of
|
||||
/// `dependencies` whose `half` texel writes to a texture slot read whether its texture's
|
||||
/// channels are 16-bit floats (`RuntimeFact::StorageTextureHalfChannels`: the slot's storage
|
||||
@@ -2624,6 +2817,19 @@ impl Device {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a note of `stages` has a clause that tests a value its function reads as data
|
||||
/// (`SpecClause::tests_bound_values`): where none has,
|
||||
/// [`degrade_bound_values`](Self::degrade_bound_values) tests no clause, announces nothing
|
||||
/// and answers quiet, so a caller may leave it out.
|
||||
pub(crate) fn tests_bound_values(stages: &[StageModule]) -> bool {
|
||||
stages.iter().any(|stage| {
|
||||
stage
|
||||
.specialized_notes
|
||||
.iter()
|
||||
.any(|s| s.when.iter().any(|c| c.tests_bound_values()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Announce, at a draw or dispatch that binds a pipeline of `stages` made under
|
||||
/// `specialization`, each specialized note one of whose clauses tests a value its function
|
||||
/// reads as data (`SpecClause::tests_bound_values`: a bound texture's format class) and
|
||||
@@ -2902,6 +3108,19 @@ impl Device {
|
||||
});
|
||||
}
|
||||
|
||||
/// Why `stage`, which records `note`, degrades: [`note_reason`](Self::note_reason)'s, and for
|
||||
/// `PrecisionNote::FunctionStorageAssumed` the private memory a thread of the stage keeps and
|
||||
/// the Function storage the device's profile holds, measured or the floor of a device not
|
||||
/// measured, in bytes.
|
||||
fn stage_note_reason(&self, note: PrecisionNote, stage: &StageModule) -> String {
|
||||
let recorded = self.note_reason(note);
|
||||
if note != PrecisionNote::FunctionStorageAssumed {
|
||||
return recorded;
|
||||
}
|
||||
let held = self.compile_device().profile().function_storage();
|
||||
function_storage_reason(&recorded, stage.private_bytes, held)
|
||||
}
|
||||
|
||||
/// Why a stage that records `note` degrades: the note, and for
|
||||
/// `PrecisionNote::BeyondMeasuredDeviation` each deviation the device's profile takes past
|
||||
/// its measurement, with the last release measured.
|
||||
@@ -3045,6 +3264,10 @@ impl Device {
|
||||
.find(|color| color.resolve.as_ref().is_some_and(|r| r.shader.is_some()));
|
||||
if let Some(color) = exact {
|
||||
self.degrade(Degradation::ShaderResolve, || {
|
||||
// An attachment whose image takes no input attachment usage is resolved from a
|
||||
// copy of its samples (`color_resolve.rs`).
|
||||
let copied = color.planes.is_none()
|
||||
&& matches!(render_target::takes_input(&color.target), Ok(false));
|
||||
(
|
||||
format!(
|
||||
"a resolve of a {:?} color attachment of {} samples",
|
||||
@@ -3053,8 +3276,16 @@ impl Device {
|
||||
),
|
||||
format!(
|
||||
"the device's `AVERAGE` resolve of {:?} at {} samples is not measured to \
|
||||
be Metal's",
|
||||
color.target.format, color.target.samples
|
||||
be Metal's{}",
|
||||
color.target.format,
|
||||
color.target.samples,
|
||||
match copied {
|
||||
true => {
|
||||
"; the attachment's image takes no input attachment usage, so its \
|
||||
samples are first copied into a scratch image that has it"
|
||||
}
|
||||
false => "",
|
||||
}
|
||||
),
|
||||
)
|
||||
});
|
||||
@@ -3652,8 +3883,13 @@ impl Device {
|
||||
),
|
||||
)
|
||||
});
|
||||
} else if matches!(stand_in.cause, Cause::Linear | Cause::KeptBytes) {
|
||||
// Announced where `linear_attachment.rs` or `kept_bytes.rs` chose the kept image.
|
||||
} else if matches!(
|
||||
stand_in.cause,
|
||||
Cause::Linear | Cause::KeptBytes | Cause::Magnitude
|
||||
) {
|
||||
// Announced where `linear_attachment.rs` or `kept_bytes.rs` chose the kept image; a
|
||||
// magnitude stand-in's pass tests and keeps the depth as Metal's
|
||||
// (`texture/signed_depth.rs`, which announces what it does not).
|
||||
} else if memoryless
|
||||
&& (index.is_some_and(fetched) || (index.is_none() && shadow) || !chosen)
|
||||
{
|
||||
|
||||
@@ -34,6 +34,13 @@
|
||||
//! above. The `FragDepth` draw also reads its depth from such a colour image (`R32_SFLOAT`,
|
||||
//! [`DepthDraw::from_colour`]).
|
||||
//!
|
||||
//! - **The magnitude draws** ([`DepthDraw::magnitude`], [`DepthDraw::magnitude_bits`]): a
|
||||
//! multisampled depth stored without its signs after a pass with depth writes
|
||||
//! (`texture/signed_depth.rs`): the `FragDepth` draw of [`DepthStencilCopy::DepthMagnitude`],
|
||||
//! from a sampled copy of the depth, exact or announced as the draw above is; or the bits draw of
|
||||
//! [`DepthStencilCopy::MagnitudeBits`], between two `R32_UINT` colour images of the depth's
|
||||
//! bits that maintenance8's copies move to and from it, exact.
|
||||
//!
|
||||
//! - **The depth stand-in's copies** (`depth_stand_in.rs`): a pass's depth samples into an
|
||||
//! `R32_SFLOAT` stand-in, multisampled or sample planes, by a dispatch of
|
||||
//! `bind::depth_split_module` ([`DepthSplit`]), and back by the `FragDepth` draw of
|
||||
@@ -356,7 +363,9 @@ impl Device {
|
||||
};
|
||||
let colour = matches!(
|
||||
copy,
|
||||
DepthStencilCopy::DepthBits | DepthStencilCopy::StencilBits
|
||||
DepthStencilCopy::DepthBits
|
||||
| DepthStencilCopy::StencilBits
|
||||
| DepthStencilCopy::MagnitudeBits
|
||||
);
|
||||
let result = (|| {
|
||||
made.render_pass = match colour {
|
||||
@@ -831,6 +840,64 @@ impl DepthDraw {
|
||||
DepthDraw::of_view(device, copy, view, destination, area, feature)
|
||||
}
|
||||
|
||||
/// The draw that writes the depth `source`'s depth aspect holds at each pixel and sample of
|
||||
/// `area`, without its sign ([`DepthStencilCopy::DepthMagnitude`]), into `destination`'s
|
||||
/// depth there: a multisampled depth's strip by draws (`texture/signed_depth.rs`).
|
||||
pub(super) fn magnitude(
|
||||
device: &Device,
|
||||
source: &Target,
|
||||
destination: &Target,
|
||||
area: DrawArea,
|
||||
feature: &Feature,
|
||||
) -> Result<DepthDraw, Error> {
|
||||
let depth =
|
||||
|target: &Target| image_aspects(target.format).contains(ImageAspectFlags::DEPTH);
|
||||
if source.samples != destination.samples || !depth(source) || !depth(destination) {
|
||||
return Err(internal(
|
||||
"a depth's magnitude between targets of other samples or without depth",
|
||||
));
|
||||
}
|
||||
let view = aspect_view(source, ImageAspectFlags::DEPTH)?;
|
||||
DepthDraw::of_view(
|
||||
device,
|
||||
DepthStencilCopy::DepthMagnitude,
|
||||
view,
|
||||
destination,
|
||||
area,
|
||||
feature,
|
||||
)
|
||||
}
|
||||
|
||||
/// The bits draw that writes the bits `source`, a multisampled `R32_UINT` colour target of a
|
||||
/// 32-bit float depth's bits, holds at each pixel and sample of `area` without the sign bit
|
||||
/// ([`DepthStencilCopy::MagnitudeBits`]) into `destination`, another, there: a multisampled
|
||||
/// depth's strip through colour copies (`texture/signed_depth.rs`).
|
||||
pub(super) fn magnitude_bits(
|
||||
device: &Device,
|
||||
source: &Target,
|
||||
destination: &Target,
|
||||
area: DrawArea,
|
||||
feature: &Feature,
|
||||
) -> Result<DepthDraw, Error> {
|
||||
if source.samples != destination.samples
|
||||
|| source.format != Format::R32_UINT
|
||||
|| destination.format != Format::R32_UINT
|
||||
{
|
||||
return Err(internal(
|
||||
"a magnitude bits copy between targets of other samples or formats",
|
||||
));
|
||||
}
|
||||
let view = aspect_view(source, ImageAspectFlags::COLOR)?;
|
||||
DepthDraw::of_view(
|
||||
device,
|
||||
DepthStencilCopy::MagnitudeBits,
|
||||
view,
|
||||
destination,
|
||||
area,
|
||||
feature,
|
||||
)
|
||||
}
|
||||
|
||||
/// The draw of `copy` reading `view` into `destination` over `area`.
|
||||
fn of_view(
|
||||
device: &Device,
|
||||
|
||||
@@ -57,6 +57,7 @@ use super::texture_descriptor::TextureDescriptor;
|
||||
use super::tracker::{Access, Barrier, Use};
|
||||
use super::values::ResourceOptions;
|
||||
use super::Device;
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::bind::DepthStandInForm;
|
||||
use metal2vulkan::device::VkProperty;
|
||||
@@ -495,12 +496,7 @@ impl StandInCopies {
|
||||
/// encoder records; the stand-in, its staging buffer, the depth's image and the copies'
|
||||
/// objects live until it completes and rest in `GENERAL`; the encoder refused every draw
|
||||
/// whose instance needs a copy in that cannot run ([`DepthStandIn::check_filled`]).
|
||||
pub(super) unsafe fn record_in(
|
||||
&self,
|
||||
device: &ash::Device,
|
||||
raw: vk::CommandBuffer,
|
||||
first: bool,
|
||||
) {
|
||||
pub(super) unsafe fn record_in(&self, device: &Vk, raw: vk::CommandBuffer, first: bool) {
|
||||
let fill = match first {
|
||||
true => self.fill,
|
||||
false => FirstFill::Copy,
|
||||
@@ -538,7 +534,7 @@ impl StandInCopies {
|
||||
/// # Safety
|
||||
///
|
||||
/// As for [`StandInCopies::record_in`].
|
||||
pub(super) unsafe fn record_out(&self, device: &ash::Device, raw: vk::CommandBuffer) {
|
||||
pub(super) unsafe fn record_out(&self, device: &Vk, raw: vk::CommandBuffer) {
|
||||
Barrier::everything().record(device, raw);
|
||||
match &self.back {
|
||||
Some(back) => back.record(device, raw),
|
||||
@@ -553,7 +549,7 @@ impl StandInCopies {
|
||||
/// # Safety
|
||||
///
|
||||
/// As for [`StandInCopies::record_in`].
|
||||
unsafe fn copy(&self, device: &ash::Device, raw: vk::CommandBuffer, inward: bool) {
|
||||
unsafe fn copy(&self, device: &Vk, raw: vk::CommandBuffer, inward: bool) {
|
||||
let general = vk::ImageLayout::GENERAL;
|
||||
let stand_in_layers = vk::ImageSubresourceLayers {
|
||||
aspect_mask: vk::ImageAspectFlags::COLOR,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! `DepthStencilState` (`MTLDepthStencilState`) and `Device::new_depth_stencil_state`
|
||||
//! (step 6's second part).
|
||||
//!
|
||||
//! A depth/stencil state is its descriptor (the compile layer's [`DepthStencilDescriptor`],
|
||||
//! Metal's properties) and the Vulkan depth/stencil state it stands for
|
||||
//! A depth/stencil state is its descriptor (the compile layer's [`DepthStencilDescriptor`], Metal's
|
||||
//! properties) and the Vulkan depth/stencil state it stands for
|
||||
//! ([`metal2vulkan::metal::state::depth_stencil_state`]): a render encoder's draws take it as the
|
||||
//! pipeline's static depth/stencil state, or as dynamic state where the pipeline makes it dynamic
|
||||
//! (`render.rs`). Metal makes a state of any descriptor, masks wider than the 8-bit stencil
|
||||
//! included (measured, RT6 probe 4), so creation refuses nothing.
|
||||
//! included (measured on an M4), so creation refuses nothing.
|
||||
//!
|
||||
//! A state's `gpuResourceID` is Apple10's: below it Metal's API validation stops the call
|
||||
//! ("Obtaining the resourceID of a DepthStencilState object requires support for
|
||||
@@ -92,9 +92,9 @@ impl DepthStencilState {
|
||||
self.0.vulkan
|
||||
}
|
||||
|
||||
/// What the state does with depth in a pass without a depth attachment (RT6 probes 4 and
|
||||
/// 4b): Metal's validation stops a draw that writes depth or compares other than `Always`
|
||||
/// and `Never`, which plain Metal tests against the pass's hidden depth. Under `Never` every
|
||||
/// What the state does with depth in a pass without a depth attachment (measured on an M4):
|
||||
/// Metal's validation stops a draw that writes depth or compares other than `Always` and
|
||||
/// `Never`, which plain Metal tests against the pass's hidden depth. Under `Never` every
|
||||
/// fragment fails, where Vulkan, with no attachment to test, would pass it
|
||||
/// ([`DepthStencilState::failing_depth`]).
|
||||
pub(super) fn depth_without_attachment(&self) -> DepthUse {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Separate depth and stencil textures in one pass (step 6's second part).
|
||||
//!
|
||||
//! Metal renders a pass whose depth and stencil attachments are two textures: measured on an M4
|
||||
//! (RT6 probe 4c), `Depth32Float` with `Stencil8` and `Depth16Unorm` with `Stencil8` both test
|
||||
//! and store each aspect in its own texture. A Vulkan subpass has one depth/stencil attachment,
|
||||
//! so such a pass renders into a scratch image of the combined format whose depth aspect holds
|
||||
//! the depth texture's bits: `D32_SFLOAT_S8_UINT` for 32-bit float depth, `D16_UNORM_S8_UINT`
|
||||
//! for 16-bit, `D24_UNORM_S8_UINT` for 24-bit. Stencil is 8 bits in every format.
|
||||
//! (macOS 27.0.1), `Depth32Float` with `Stencil8` and `Depth16Unorm` with `Stencil8` both test and
|
||||
//! store each aspect in its own texture. A Vulkan subpass has one depth/stencil attachment, so such
|
||||
//! a pass renders into a scratch image of the combined format whose depth aspect holds the depth
|
||||
//! texture's bits: `D32_SFLOAT_S8_UINT` for 32-bit float depth, `D16_UNORM_S8_UINT` for 16-bit,
|
||||
//! `D24_UNORM_S8_UINT` for 24-bit. Stencil is 8 bits in every format.
|
||||
//!
|
||||
//! - **Before the pass**, each aspect loaded with `Load` is copied from its texture into the
|
||||
//! scratch image; `Clear` and `DontCare` load as the scratch's own operations.
|
||||
@@ -39,13 +39,13 @@
|
||||
//! - **Textures of different sizes**, which Metal's validation stops ("When both depth (8 x 8) and
|
||||
//! stencil (4 x 4) are used from separate textures, they must have identical dimensions") and
|
||||
//! plain Metal renders over the smaller (EV RRS-probe-1-m4, an M4 with macOS 27.0.1, one sample,
|
||||
//! without draws; RT6 probe 4b's `separate_sizes`, with one): the scratch image is the smaller,
|
||||
//! the render area at most that, and its copies move the render area. Metal's clear of the larger
|
||||
//! reaches past the render area to the end of its tiles, by 32 pixels a side for `Depth32Float`
|
||||
//! and 16 for `Stencil8` (a 64x64 depth cleared at 0..31, a 64x64 stencil at 0..15, an 8x8 depth
|
||||
//! whole, each beside a 4x4 texture; and 32 alike under 16x16 tiles). A texture that ends inside
|
||||
//! those tiles, cleared and stored, is cleared whole before the copies back
|
||||
//! (`cleared_whole`); one past them, of another format, or of more samples, unmeasured, is
|
||||
//! without draws; Metal probe `separate_sizes` on an M4, with one): the scratch image is the
|
||||
//! smaller, the render area at most that, and its copies move the render area. Metal's clear of
|
||||
//! the larger reaches past the render area to the end of its tiles, by 32 pixels a side for
|
||||
//! `Depth32Float` and 16 for `Stencil8` (a 64x64 depth cleared at 0..31, a 64x64 stencil at
|
||||
//! 0..15, an 8x8 depth whole, each beside a 4x4 texture; and 32 alike under 16x16 tiles). A
|
||||
//! texture that ends inside those tiles, cleared and stored, is cleared whole before the copies
|
||||
//! back (`cleared_whole`); one past them, of another format, or of more samples, unmeasured, is
|
||||
//! `NotImplemented(Render)` (`check_sizes`).
|
||||
//! - **A layered pass** (`renderTargetArrayLength` 2 or more) renders through a scratch image of
|
||||
//! its layers, each texture's from its slice, and the copies move every layer; the copies' draws,
|
||||
|
||||
@@ -11,14 +11,15 @@
|
||||
//! heap's buffers included), or through what it made resident (`use_resource`, `use_heap`).
|
||||
//! Then a buffer's call blocks until each such command buffer completed and answers `false`,
|
||||
//! detaching nothing; a heap's answers `false` at once. A lost device ends the wait
|
||||
//! (`Err(DeviceLost)`). The wait holds no lock of the runtime's: the completion thread lets go
|
||||
//! (`Err(DeviceLost)`). The wait holds no lock of the runtime's: a completion turn lets go
|
||||
//! of each command buffer's holds without one (`rebind::SubmittedHolds`).
|
||||
//! - **Pending work.** A command buffer whose first submission comes after the detach and whose
|
||||
//! commands named the buffer or made it resident, encoded before the detach or after it, fails
|
||||
//! at that submission with `CommandBufferError::DetachedBacking` (Metal's code 8) and runs
|
||||
//! nothing of it; one that only reaches the bytes unnamed reads zeros there (`live_buffers.rs`
|
||||
//! no longer lists them) and runs. A rebind before that submission gives a command encoded
|
||||
//! while detached `EncodedUseRebound` instead, the gap until encoded uses resolve at submission.
|
||||
//! commands named the buffer or made it resident (a render pass whose attachment lies in the
|
||||
//! bytes names them from its open), encoded before the detach or after it, fails at that
|
||||
//! submission with `CommandBufferError::DetachedBacking` (Metal's code 8) and runs nothing of it;
|
||||
//! one that only reaches the bytes unnamed reads zeros there (`live_buffers.rs` no longer lists
|
||||
//! them) and runs. A rebind before that submission gives a command encoded while detached
|
||||
//! `EncodedUseRebound` instead, the gap until encoded uses resolve at submission.
|
||||
//! - **No memory.** A detached buffer takes the device's stand-in, a small buffer of the
|
||||
//! runtime's own shared by every detached buffer (`buffer::Detached`), never memory of its
|
||||
//! size. No command that takes the stand-in runs: an encoder whose command names a detached
|
||||
@@ -28,9 +29,12 @@
|
||||
//! in the heap) stays, and presents a stand-in of its image's plan while they are detached
|
||||
//! (`texture/stand_in.rs`): its size and level queries answer its own, an unnamed read reads zero
|
||||
//! bytes and an unnamed write lands where nothing reads. Its images bound to the old pages and
|
||||
//! its views go with them; a command that names it fails as one naming the buffer does. A texture
|
||||
//! being made over the bytes refuses the detach (`NotImplemented(DetachTextures)`), and no
|
||||
//! texture is made over detached bytes yet.
|
||||
//! its views go with them, once nothing holds the pages: an open encoder that named them (a
|
||||
//! render pass over them from its open, whose first instance may have recorded with those
|
||||
//! images, `render/inline_first.rs`) and a submitted command buffer hold them. A command that
|
||||
//! names it fails as one naming the buffer does. A texture being made over the bytes refuses
|
||||
//! the detach (`NotImplemented(DetachTextures)`), and no texture is made over detached bytes
|
||||
//! yet.
|
||||
//! - **Attaching again.** `rebind_bytes_no_copy` gives a detached buffer or heap pages again.
|
||||
|
||||
use super::buffer::{Buffer, Detached, HostCell, Lying};
|
||||
@@ -57,13 +61,14 @@ impl Buffer {
|
||||
/// detached (at once, or it was already). Where a command buffer submitted and not yet
|
||||
/// complete took the buffer, the call blocks until each such command buffer completed and
|
||||
/// answers `false`, detaching nothing. The old memory's deallocator runs once every command
|
||||
/// buffer submitted before the call that used it completed (in the call, where none holds
|
||||
/// it). The buffer, its `gpu_address` and its options stay; `contents` answers `None` while
|
||||
/// it is detached.
|
||||
/// buffer submitted before the call that used it completed, and every open encoder that named
|
||||
/// it was committed or dropped (in the call, where none holds it). The buffer, its
|
||||
/// `gpu_address` and its options stay; `contents` answers `None` while it is detached.
|
||||
///
|
||||
/// A command buffer first submitted after the call whose commands named the buffer or made
|
||||
/// it resident fails there, `CommandBufferError::DetachedBacking`, and runs nothing of it;
|
||||
/// one that reaches the buffer only by its address reads zeros there.
|
||||
/// it resident (a render pass whose attachment lies over it names it from its open) fails
|
||||
/// there, `CommandBufferError::DetachedBacking`, and runs nothing of it; one that reaches the
|
||||
/// buffer only by its address reads zeros there.
|
||||
///
|
||||
/// A texture over the buffer's bytes stays, and presents a stand-in until the buffer lies in
|
||||
/// pages again: its queries answer its own descriptor, an unnamed read reads zeros, and a
|
||||
@@ -189,12 +194,19 @@ impl Device {
|
||||
lock(&shared.resource_ids).renew_textures();
|
||||
super::heap_sets::renew(self);
|
||||
}
|
||||
// What lay in the old pages goes with them, as a rebind's swapped images do: once the
|
||||
// command buffers that may read them through the heap sets completed, and once nothing
|
||||
// holds the pages: an open encoder that took them (a render pass's attachments from its
|
||||
// open, whose first instance may have recorded with their images,
|
||||
// `render/inline_first.rs`), and a submitted command buffer until it completes.
|
||||
if !gone.is_empty() {
|
||||
let pages = match &old {
|
||||
Lying::In(pages) => Some(Arc::clone(pages)),
|
||||
Lying::Detached(_) => None,
|
||||
};
|
||||
super::heap_sets::retire(self, Box::new((gone, pages)));
|
||||
match &old {
|
||||
Lying::In(pages) => {
|
||||
pages.park(gone);
|
||||
super::heap_sets::retire(self, Box::new(Arc::clone(pages)));
|
||||
}
|
||||
Lying::Detached(_) => super::heap_sets::retire(self, Box::new(gone)),
|
||||
}
|
||||
}
|
||||
// The old pages go now where no command buffer holds them, their deallocator with them.
|
||||
drop(old);
|
||||
@@ -203,7 +215,7 @@ impl Device {
|
||||
|
||||
/// The device's stand-in, which detached buffers take (`buffer::Detached`): made once
|
||||
/// while one is detached, and again once every one let go of it.
|
||||
fn detach_stand_in(&self) -> Result<Buffer, Error> {
|
||||
pub(super) fn detach_stand_in(&self) -> Result<Buffer, Error> {
|
||||
let mut stand_in = lock(&self.shared().rebinds.stand_in);
|
||||
if let Some(buffer) = stand_in.as_ref().and_then(|weak| weak.upgrade()) {
|
||||
return Ok(buffer);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
use super::{device_error, Device, InstanceShared, Parts};
|
||||
use crate::error::Error;
|
||||
use crate::gpu_time;
|
||||
use crate::image_barrier::MemoryReads;
|
||||
use crate::loader_word::LoaderWord;
|
||||
use crate::metal_level::{choose, Host};
|
||||
use crate::shader_cache::{CacheSetup, ShaderCacheOptions};
|
||||
@@ -17,7 +18,7 @@ use crate::sparse::device::SparseFeatures;
|
||||
use ash::vk;
|
||||
use metal2vulkan::device::{DeviceDescription, DevicePolicy, EnableSet, VkExtension};
|
||||
use std::collections::BTreeSet;
|
||||
use std::ffi::CString;
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The consumer's Vulkan objects a runtime device adopts ([`Device::from_raw`]). No Metal
|
||||
@@ -232,6 +233,21 @@ impl Device {
|
||||
super::create::graphics_pipeline_library_supported(&instance, raw.physical_device)
|
||||
}
|
||||
});
|
||||
// The reads its global memory barriers name: those of the family the runtime submits to,
|
||||
// which supports graphics and compute work, with every extension the consumer enabled
|
||||
// that the description or the consumer names.
|
||||
// SAFETY: the caller's contract: the physical device was enumerated from the instance.
|
||||
let families =
|
||||
unsafe { instance.get_physical_device_queue_family_properties(raw.physical_device) };
|
||||
let family = (families.get(raw.queue_family as usize)).map_or(
|
||||
vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE,
|
||||
|family| family.queue_flags,
|
||||
);
|
||||
let mut named: Vec<&CStr> = (raw.enabled.extensions.iter())
|
||||
.flat_map(|&extension| crate::enables::names_of(extension))
|
||||
.collect();
|
||||
named.extend(raw.device_extensions.iter().map(CString::as_c_str));
|
||||
let memory_reads = MemoryReads::of(family, named);
|
||||
let parts = Parts {
|
||||
instance: Arc::new(InstanceShared {
|
||||
entry,
|
||||
@@ -273,6 +289,7 @@ impl Device {
|
||||
linear_color_attachment,
|
||||
graphics_pipeline_library,
|
||||
sparse_features: raw.sparse_features.features(),
|
||||
memory_reads,
|
||||
owned: false,
|
||||
cache,
|
||||
metal_level,
|
||||
|
||||
@@ -37,6 +37,7 @@ use crate::degradation::{Degradation, DegradeNotice};
|
||||
use crate::enables::{host_image_copy_names, listed_reported, listed_structures, Enables};
|
||||
use crate::error::{vulkan, Error, InstanceApiVersion, LoaderNotFound};
|
||||
use crate::gpu_time;
|
||||
use crate::image_barrier::MemoryReads;
|
||||
use crate::loader_word::LoaderWord;
|
||||
use crate::metal_level::{choose, Chosen, Host};
|
||||
use crate::release;
|
||||
@@ -1232,6 +1233,11 @@ fn create_on(
|
||||
.map_err(vulkan)?;
|
||||
// SAFETY: the device was just created: its word is the loader's.
|
||||
let loader_word = unsafe { LoaderWord::of_device(raw.handle()) };
|
||||
let primary = families.get(queue_family as usize);
|
||||
let memory_reads = MemoryReads::of(
|
||||
primary.map_or(vk::QueueFlags::empty(), |family| family.queue_flags),
|
||||
enables.names(),
|
||||
);
|
||||
let parts = Parts {
|
||||
instance: Arc::clone(instance),
|
||||
physical,
|
||||
@@ -1258,6 +1264,7 @@ fn create_on(
|
||||
dma_buf: dma_buf.is_some(),
|
||||
dma_buf_images: dma_buf_images.is_some(),
|
||||
sparse_features,
|
||||
memory_reads,
|
||||
owned: true,
|
||||
cache: cache.clone(),
|
||||
metal_level: level,
|
||||
|
||||
@@ -6,16 +6,52 @@
|
||||
//! that calls an entry point outside the table therefore fails the lane that reaches it, so the
|
||||
//! table holds every entry point a section calls, and priming, which makes each before the exit
|
||||
//! hook is registered (`prime.rs`), covers them all. Other builds hand out every function.
|
||||
//!
|
||||
//! Each is a [`Vk`]: the `ash::Device`, which it dereferences to, and the reads the commands of the
|
||||
//! device's queue family for encoders make, which the runtime's global memory barriers name in
|
||||
//! their destination (`tracker::Barrier::record`, `image_barrier::MemoryReads`).
|
||||
|
||||
use crate::exit_guard::{self, Call};
|
||||
use crate::image_barrier::MemoryReads;
|
||||
use ash::vk;
|
||||
use std::ffi::{c_void, CStr};
|
||||
use std::ops::Deref;
|
||||
|
||||
/// A device's functions as the runtime records commands with them: the `ash::Device`, and the
|
||||
/// reads a global memory barrier recorded into a command buffer of the device's queue family for
|
||||
/// encoders names in place of `MEMORY_READ` (the module docs).
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Vk {
|
||||
device: ash::Device,
|
||||
reads: MemoryReads,
|
||||
}
|
||||
|
||||
impl Vk {
|
||||
/// `device`'s functions, whose global memory barriers name `reads`: for the work the runtime
|
||||
/// records before the device's functions are made (`prime.rs`).
|
||||
pub(super) fn new(device: ash::Device, reads: MemoryReads) -> Vk {
|
||||
Vk { device, reads }
|
||||
}
|
||||
|
||||
/// The reads a global memory barrier's destination names.
|
||||
pub(crate) fn reads(&self) -> MemoryReads {
|
||||
self.reads
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Vk {
|
||||
type Target = ash::Device;
|
||||
|
||||
fn deref(&self) -> &ash::Device {
|
||||
&self.device
|
||||
}
|
||||
}
|
||||
|
||||
/// A device's functions: all of them, and the exit guard's table alone.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Functions {
|
||||
all: ash::Device,
|
||||
sectioned: ash::Device,
|
||||
all: Vk,
|
||||
sectioned: Vk,
|
||||
/// The address of each device-level entry point of the table, in its order (0 for an
|
||||
/// instance-level one, or one the device has not): the topmost layer's where layers run,
|
||||
/// else the driver's.
|
||||
@@ -23,13 +59,18 @@ pub(crate) struct Functions {
|
||||
}
|
||||
|
||||
impl Functions {
|
||||
/// The functions of `all`'s device, made from `instance`.
|
||||
/// The functions of `all`'s device, made from `instance`, whose global memory barriers name
|
||||
/// `reads`.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `all` is a live device of `instance`, routed (`compiles::route`), and the loader serves
|
||||
/// `vkGetDeviceProcAddr` for it (its loader word is in place).
|
||||
pub(super) unsafe fn new(instance: &ash::Instance, all: ash::Device) -> Functions {
|
||||
pub(super) unsafe fn new(
|
||||
instance: &ash::Instance,
|
||||
all: ash::Device,
|
||||
reads: MemoryReads,
|
||||
) -> Functions {
|
||||
let handle = all.handle();
|
||||
let get = instance.fp_v1_0().get_device_proc_addr;
|
||||
// SAFETY: the caller's contract; a missing function is null, as ash loads it.
|
||||
@@ -54,8 +95,8 @@ impl Functions {
|
||||
// SAFETY: as above: each pointer is the device's function of that name, or null.
|
||||
let sectioned = unsafe { ash::Device::load_with(load, handle) };
|
||||
Functions {
|
||||
all,
|
||||
sectioned,
|
||||
all: Vk::new(all, reads),
|
||||
sectioned: Vk::new(sectioned, reads),
|
||||
entry_points,
|
||||
}
|
||||
}
|
||||
@@ -66,7 +107,7 @@ impl Functions {
|
||||
}
|
||||
|
||||
/// The device's functions for this thread now (see the module).
|
||||
pub(crate) fn get(&self) -> &ash::Device {
|
||||
pub(crate) fn get(&self) -> &Vk {
|
||||
exit_guard::check();
|
||||
if cfg!(debug_assertions) && exit_guard::in_section() {
|
||||
&self.sectioned
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! A runtime device owns or adopts the Vulkan instance, physical device, `VkDevice` and its
|
||||
//! queue, and holds what every object made from it shares: the compile-and-plan layer's
|
||||
//! [`metal2vulkan::device::Device`] (built from the description restricted to what was actually
|
||||
//! enabled), the memory sub-allocator, the Metal address space, the scheduler, the completion
|
||||
//! thread, and the handler threads.
|
||||
//! enabled), the memory sub-allocator, the Metal address space, the scheduler, the queues'
|
||||
//! waiters, and the handler threads.
|
||||
//!
|
||||
//! - **Create** ([`Device::system_default`], [`Device::all`], `create.rs`) makes the instance and
|
||||
//! one device per physical device with the description's recommended enables, then adopts
|
||||
@@ -27,7 +27,7 @@ pub(super) mod prime;
|
||||
pub(super) mod properties;
|
||||
pub(crate) mod relay;
|
||||
mod staging;
|
||||
mod submit;
|
||||
pub(super) mod submit;
|
||||
|
||||
pub use adopt::RawDevice;
|
||||
pub use create::{
|
||||
@@ -42,15 +42,16 @@ use super::attachmentless::KeptPasses;
|
||||
use super::capabilities::DeviceProperties;
|
||||
use super::color_resolve::ColorResolveObjects;
|
||||
use super::command_buffer::fences::Fences;
|
||||
use super::command_buffer::{Completion, Transition};
|
||||
use super::command_buffer::{Completion, Item};
|
||||
use super::contexts::{Contexts, THREADS};
|
||||
use super::degradation::{Announced, Degradation};
|
||||
use super::depth_copy::DepthCopyObjects;
|
||||
use super::depth_stencil_resolve::DepthStencilResolveObjects;
|
||||
use super::draw_source::{sized_index_bind, SizedIndexBind};
|
||||
use super::dynamic_state::ExtendedDynamicState;
|
||||
use super::dynamic_state::{ColorWriteMasks, ExtendedDynamicState};
|
||||
use super::error::{vulkan, Error};
|
||||
use super::exit_guard::{self, Call};
|
||||
use super::freed_memory::Parking;
|
||||
use super::function_table::TableShared;
|
||||
use super::generated_commands::Commands;
|
||||
use super::gpu_pools::GpuPools;
|
||||
@@ -75,18 +76,20 @@ use super::sparse::device::SparseDevice;
|
||||
use super::stencil_copy::StencilCopyObjects;
|
||||
use super::texture::TextureState;
|
||||
use super::unique_identifier::UniqueIdentifiers;
|
||||
use crate::image_barrier::MemoryReads;
|
||||
use crate::release;
|
||||
use ash::vk::{self, Handle};
|
||||
use functions::Functions;
|
||||
use functions::{Functions, Vk};
|
||||
use metal2vulkan::bind::RegionLimits;
|
||||
use metal2vulkan::device::{DeviceDescription, EnableSet};
|
||||
use metal2vulkan::error::RuntimeDriverDefect;
|
||||
use metal2vulkan::vk::DriverId;
|
||||
use relay::Flights;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak};
|
||||
use std::time::Instant;
|
||||
use submit::Internal;
|
||||
use submit::{Internal, OwnTimeline};
|
||||
|
||||
/// A Metal device (`MTLDevice`) on a Vulkan device. Cheap to clone (a retain); `Send + Sync`.
|
||||
#[derive(Clone)]
|
||||
@@ -168,7 +171,8 @@ pub(super) struct DeviceShared {
|
||||
/// The families of those queues, the primary first, each once: what the device's buffers and
|
||||
/// images are shared among (`sharing.rs`).
|
||||
pub(super) queue_families: Vec<u32>,
|
||||
/// The identity the next logical queue takes.
|
||||
/// The identity the next logical queue takes, or the next release's context of its own
|
||||
/// ([`Device::let_go_elsewhere`]).
|
||||
next_queue: AtomicU64,
|
||||
/// How many of `queues`, the first, logical queues share round robin; the rest are reserved
|
||||
/// for presenting queues.
|
||||
@@ -223,6 +227,15 @@ pub(super) struct DeviceShared {
|
||||
/// a dispatch of the state that made it (`function_table.rs`).
|
||||
pub(super) function_tables: Mutex<BTreeMap<u64, Weak<TableShared>>>,
|
||||
internal: Mutex<Option<Internal>>,
|
||||
/// The internal submissions' timeline as the host saw it complete (`submit.rs`).
|
||||
internal_done: OwnTimeline,
|
||||
/// The staging copies' timeline as the host saw it complete (`staging.rs`).
|
||||
staging_done: OwnTimeline,
|
||||
/// Each batch with work makes what completed work wrote visible by a command buffer of
|
||||
/// barriers that starts it, and waits for no timeline the host saw complete: the driver's
|
||||
/// submissions stall on semaphore operations (`DriverFact::SemaphoreOperationsStallSubmits`,
|
||||
/// `command_buffer/submit.rs`).
|
||||
pub(super) completed_by_barrier: bool,
|
||||
/// The last sparse binding of a no-copy buffer's dma-bufs (`dma_buf.rs`) the host has not
|
||||
/// seen complete: the internal timeline and the value it signals, which every later
|
||||
/// submission that may use the buffer waits for (`submit.rs`).
|
||||
@@ -233,8 +246,10 @@ pub(super) struct DeviceShared {
|
||||
pub(super) completion: Completion,
|
||||
/// The idle fences the batches that end command buffers signal (`command_buffer/fences.rs`).
|
||||
pub(super) fences: Fences,
|
||||
/// The queues' serial contexts: every command buffer's transitions and handlers run there.
|
||||
pub(super) contexts: Contexts<Transition>,
|
||||
/// The queues' serial contexts: every command buffer's transitions and handlers run there,
|
||||
/// and the releases handed off a thread that may run none of the program's code
|
||||
/// ([`Device::let_go_elsewhere`]).
|
||||
pub(super) contexts: Contexts<Item>,
|
||||
loader_word: LoaderWord,
|
||||
/// The runtime created the `VkDevice` and destroys it.
|
||||
owned: bool,
|
||||
@@ -257,6 +272,15 @@ pub(super) struct DeviceShared {
|
||||
pub(super) depth_bias_command: Option<DepthBiasCommand>,
|
||||
/// The mesh draw commands, where the device enabled `meshShader` (`render/mesh.rs`).
|
||||
pub(super) mesh_draws: Option<ash::ext::mesh_shader::Device>,
|
||||
/// The command that sets a draw's color write masks, where the device enabled everything a
|
||||
/// draw that reads its own pass's texture through a snapshot takes (`render/snapshot.rs`).
|
||||
pub(super) color_write_masks: Option<ColorWriteMasks>,
|
||||
/// The reasons a draw that reads its pass's texture took the split that the device said
|
||||
/// already, where `METAL2VULKAN_LOG_PIPELINES` is set (`render/snapshot.rs`).
|
||||
pub(super) snapshot_fallbacks: Mutex<Vec<&'static str>>,
|
||||
/// The draws the area rule weighed, by size, where `METAL2VULKAN_LOG_PIPELINES` is set
|
||||
/// (`render/snapshot.rs`, `reader_sizes.rs`).
|
||||
pub(super) reader_sizes: Mutex<crate::reader_sizes::ReaderSizes>,
|
||||
/// The command buffers' index and mesh records pools: their bytes and spare blocks
|
||||
/// (`gpu_pools.rs`).
|
||||
pub(super) gpu_pools: GpuPools,
|
||||
@@ -289,6 +313,9 @@ pub(super) struct DeviceShared {
|
||||
/// The variants' shader modules by their exact SPIR-V, shared device-wide
|
||||
/// (`pipeline/content_keyed.rs`).
|
||||
pub(super) shader_modules: Mutex<crate::pipeline::ShaderModules>,
|
||||
/// The variants' makings in the air, by their compile, which a twin's waits for to land
|
||||
/// (`pipeline/flight.rs`).
|
||||
pub(crate) flights: crate::pipeline::flight::Flights,
|
||||
/// The exact color resolve's pipelines and passes, made on first use (`color_resolve.rs`).
|
||||
pub(super) color_resolves: Mutex<ColorResolveObjects>,
|
||||
/// The multisampled stencil's copies without colour copies: the split kernel and the plane
|
||||
@@ -321,6 +348,10 @@ pub(super) struct DeviceShared {
|
||||
pub(super) owners: super::used_resources::Owners,
|
||||
/// The program's live buffers of their own, and their resident set (`live_buffers.rs`).
|
||||
pub(super) live_buffers: super::live_buffers::LiveBuffers,
|
||||
/// The imports of the caller's dma-bufs it releases while idle, and the thread that releases
|
||||
/// them (`host_residency.rs`).
|
||||
#[cfg(unix)]
|
||||
pub(super) residency: super::host_residency::Sweeper,
|
||||
/// How its command buffers are timed on the GPU (`gpu_time.rs`).
|
||||
pub(super) timing: Timing,
|
||||
/// Its Vulkan views may present an image in another component layout: it has no portability
|
||||
@@ -349,6 +380,9 @@ pub(super) struct DeviceShared {
|
||||
pub(super) spares: Spares,
|
||||
/// Counts of its commit path's work, for the lanes (`work_counts.rs`).
|
||||
pub(super) counts: super::work_counts::Counters,
|
||||
/// Where the driver fails pending work as memory a device-address buffer lay in is freed,
|
||||
/// the record of its batches the memory's blocks that go wait by (`freed_memory.rs`).
|
||||
pub(crate) parking: OnceLock<Arc<Parking>>,
|
||||
/// Its command buffers made and not committed, over all its queues (`queue.rs`).
|
||||
pub(super) uncommitted: Arc<super::queue::Uncommitted>,
|
||||
/// The threads that make `VkPipeline`s ahead of the draws that record them
|
||||
@@ -357,6 +391,9 @@ pub(super) struct DeviceShared {
|
||||
/// The thread that lets go of what a released state's pool pieces gave back as they ended
|
||||
/// (`pipeline/reaper.rs`).
|
||||
pub(super) reaper: crate::pipeline::reaper::Reaper,
|
||||
/// The trails its threads open between a signal and their last let-go of what they held for
|
||||
/// the work, which a command buffer's waiters wait for (`trails.rs`).
|
||||
pub(crate) trails: Arc<crate::trails::Trails>,
|
||||
/// Its graphics pipeline libraries, by part and content, where it links its render
|
||||
/// pipelines from libraries (`pipeline/libraries.rs`, `create.rs`); `None` where it makes
|
||||
/// each whole.
|
||||
@@ -389,10 +426,26 @@ impl DeviceShared {
|
||||
/// the exit guard, or while they run the program's code, and a section reaches only the exit
|
||||
/// guard's table of entry points; builds with debug assertions end the process otherwise
|
||||
/// (`functions.rs`).
|
||||
pub(crate) fn vk(&self) -> &ash::Device {
|
||||
pub(crate) fn vk(&self) -> &Vk {
|
||||
self.functions.get()
|
||||
}
|
||||
|
||||
/// `vkAllocateCommandBuffers` of `info`: the loader serves it and reads the device's loader
|
||||
/// word first ([`LoaderWord`]).
|
||||
pub(super) fn allocate_command_buffers(
|
||||
&self,
|
||||
info: &vk::CommandBufferAllocateInfo<'_>,
|
||||
) -> Result<Vec<vk::CommandBuffer>, Error> {
|
||||
// SAFETY: the device is live; `info` names one of its pools, which the caller holds
|
||||
// exclusively.
|
||||
let allocated = unsafe {
|
||||
self.loader_word.restore();
|
||||
self.vk().allocate_command_buffers(info)
|
||||
};
|
||||
exit_guard::called(Call::AllocateCommandBuffers);
|
||||
allocated.map_err(super::error::vulkan)
|
||||
}
|
||||
|
||||
/// How the device's buffers and images are shared among its queue families (`sharing.rs`).
|
||||
pub(crate) fn sharing(&self) -> Sharing<'_> {
|
||||
Sharing::new(&self.queue_families)
|
||||
@@ -404,6 +457,11 @@ impl DeviceShared {
|
||||
self.queues[index].family
|
||||
}
|
||||
|
||||
/// The queue flags of the family of the device's `VkQueue` at `index`.
|
||||
pub(crate) fn queue_flags_of(&self, index: usize) -> vk::QueueFlags {
|
||||
self.queues[index].flags
|
||||
}
|
||||
|
||||
/// A Vulkan sampler of `info`, counted against the device's `maxSamplerAllocationCount`
|
||||
/// (`SamplerCount`): refused, `Error::SamplerLimit`, where that many are live. Whoever
|
||||
/// destroys it gives the count back (`DeviceShared::sampler_destroyed`).
|
||||
@@ -440,6 +498,11 @@ impl Drop for DeviceShared {
|
||||
let Some(_busy) = exit_guard::enter() else {
|
||||
return;
|
||||
};
|
||||
// The draws the snapshot's area rule weighed since the last line (`reader_sizes.rs`).
|
||||
if let Some(text) = lock(&self.reader_sizes).last_line() {
|
||||
let sink = self.instance.sink();
|
||||
crate::driver_facts::inform_through(sink, "metal2vulkan-snapshot-readers", text);
|
||||
}
|
||||
// Nothing of the device is in flight: its failures are no longer relayed.
|
||||
if let Some(relay) = self.instance.relay() {
|
||||
relay.forget(&self.lost);
|
||||
@@ -452,6 +515,9 @@ impl Drop for DeviceShared {
|
||||
// What the reaper is handed holds the device: none is left, and it only stops, unless
|
||||
// this teardown runs on its thread.
|
||||
self.reaper.stop();
|
||||
// What the residency thread releases holds the device: none is left.
|
||||
#[cfg(unix)]
|
||||
self.residency.stop();
|
||||
self.completion.stop();
|
||||
self.contexts.stop();
|
||||
// SAFETY: the device is live; waiting for idle covers any work the consumer of an
|
||||
@@ -519,7 +585,10 @@ impl Drop for DeviceShared {
|
||||
// Every other pipeline was destroyed with its state (each holds this device); the cache
|
||||
// thread stops.
|
||||
self.shader_cache.close();
|
||||
lock(&self.memory).destroy(self.vk());
|
||||
// What waited with blocks of its memory (a host import's deallocators) goes once they are
|
||||
// freed, with no lock held.
|
||||
let after = lock(&self.memory).destroy(self.vk());
|
||||
drop(after);
|
||||
// The device's record of pipeline makings goes, before `vkDestroyDevice`: in builds with
|
||||
// debug assertions, no making is in progress (`compiles.rs`).
|
||||
compiles::unregister(self.vk().handle());
|
||||
@@ -540,6 +609,9 @@ pub(super) struct QueueSlot {
|
||||
raw: Mutex<vk::Queue>,
|
||||
/// The queue's family, which the command pools of what it runs are made for.
|
||||
pub(super) family: u32,
|
||||
/// The family's queue flags: the commands it runs, and so the accesses a barrier recorded
|
||||
/// for it may name (`image_barrier.rs`).
|
||||
flags: vk::QueueFlags,
|
||||
/// The queue's loader word, which MoltenVK overwrites where a message names the queue
|
||||
/// (`relay.rs`): put back before each use.
|
||||
word: LoaderWord,
|
||||
@@ -655,7 +727,7 @@ impl Device {
|
||||
}
|
||||
|
||||
/// Wait for the work submitted to each of the device's queues to end, each queue under its
|
||||
/// lock, the waits one section of the exit guard: what the completion thread does after a
|
||||
/// lock, the waits one section of the exit guard: what a completion turn does after a
|
||||
/// failed wait, before that wait's command buffers let go of what they used
|
||||
/// (`command_buffer/completion.rs`). Once the process is exiting it waits for nothing, and
|
||||
/// the releases that follow make no Vulkan call.
|
||||
@@ -685,6 +757,24 @@ impl Device {
|
||||
shared.counts.queue_drain();
|
||||
}
|
||||
|
||||
/// Let go of `held` at once on one of the device's handler threads, in a context of its own
|
||||
/// (an identity no logical queue takes, so it waits behind no queue's handlers): what the
|
||||
/// scheduler's thread lets go of under its locks where its drop may run the program's code,
|
||||
/// which may not run there (`exit_guard::program_release`). Its drop runs there as on the
|
||||
/// program's own thread, with no command buffer's step marked.
|
||||
pub(crate) fn let_go_elsewhere(&self, held: Box<dyn Send>) {
|
||||
let (contexts, context) = self.elsewhere();
|
||||
contexts.post(context, Item::Release(held));
|
||||
}
|
||||
|
||||
/// Where [`let_go_elsewhere`](Self::let_go_elsewhere) posts: the device's handler threads,
|
||||
/// and a context of its own. The handle of the pool holds nothing of the device, so what holds
|
||||
/// the device can be posted with no handle of it taken here.
|
||||
pub(crate) fn elsewhere(&self) -> (Contexts<Item>, u64) {
|
||||
let context = self.0.next_queue.fetch_add(1, Ordering::Relaxed);
|
||||
(self.0.contexts.clone(), context)
|
||||
}
|
||||
|
||||
/// A new logical queue's identity, and the index of the `VkQueue` it submits to: round
|
||||
/// robin over the device's queues that are not reserved for presenting.
|
||||
pub(super) fn next_queue(&self) -> (u64, usize) {
|
||||
@@ -705,20 +795,12 @@ impl Device {
|
||||
Some((id, self.0.round_robin + (made % reserved as u64) as usize))
|
||||
}
|
||||
|
||||
/// `vkAllocateCommandBuffers` of `info`: the loader serves it and reads the device's loader
|
||||
/// word first ([`LoaderWord`]).
|
||||
/// `vkAllocateCommandBuffers` of `info` (`DeviceShared::allocate_command_buffers`).
|
||||
pub(super) fn allocate_command_buffers(
|
||||
&self,
|
||||
info: &vk::CommandBufferAllocateInfo<'_>,
|
||||
) -> Result<Vec<vk::CommandBuffer>, Error> {
|
||||
// SAFETY: the device is live; `info` names one of its pools, which the caller holds
|
||||
// exclusively.
|
||||
let allocated = unsafe {
|
||||
self.0.loader_word.restore();
|
||||
self.0.vk().allocate_command_buffers(info)
|
||||
};
|
||||
exit_guard::called(Call::AllocateCommandBuffers);
|
||||
allocated.map_err(super::error::vulkan)
|
||||
self.0.allocate_command_buffers(info)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -785,6 +867,9 @@ pub(super) struct Parts {
|
||||
/// The sparse members of the core features it enables, outside `enabled`'s vocabulary
|
||||
/// (`sparse/device.rs`).
|
||||
pub(super) sparse_features: vk::PhysicalDeviceFeatures,
|
||||
/// The reads its global memory barriers name (`image_barrier::MemoryReads`): those of the
|
||||
/// primary queue family's commands with the extensions it enables.
|
||||
pub(super) memory_reads: MemoryReads,
|
||||
pub(super) owned: bool,
|
||||
/// The shader cache, its directory opened before any Vulkan object was made.
|
||||
pub(super) cache: CacheSetup,
|
||||
@@ -828,6 +913,7 @@ impl Device {
|
||||
dma_buf,
|
||||
dma_buf_images,
|
||||
sparse_features,
|
||||
memory_reads,
|
||||
owned,
|
||||
cache,
|
||||
metal_level,
|
||||
@@ -889,6 +975,15 @@ impl Device {
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
// SAFETY: `physical` belongs to `instance`.
|
||||
let families = unsafe {
|
||||
instance
|
||||
.raw
|
||||
.get_physical_device_queue_family_properties(physical)
|
||||
};
|
||||
let flags_of = |family: u32| {
|
||||
(families.get(family as usize)).map_or(vk::QueueFlags::empty(), |p| p.queue_flags)
|
||||
};
|
||||
let queues: Vec<QueueSlot> = queue_places
|
||||
.iter()
|
||||
.zip(&timelines)
|
||||
@@ -902,6 +997,7 @@ impl Device {
|
||||
QueueSlot {
|
||||
raw: Mutex::new(queue),
|
||||
family,
|
||||
flags: flags_of(family),
|
||||
// SAFETY: the queue was just returned, its word the loader's.
|
||||
word: unsafe { LoaderWord::of_handle(queue.as_raw()) },
|
||||
flights: OnceLock::new(),
|
||||
@@ -923,18 +1019,10 @@ impl Device {
|
||||
unsafe {
|
||||
loader_word.restore();
|
||||
let queue = raw.get_device_queue(family, index);
|
||||
staging::StagingQueue::new(family, queue, &queue_families)
|
||||
staging::StagingQueue::new(family, flags_of(family), queue, &queue_families)
|
||||
}
|
||||
});
|
||||
// SAFETY: `physical` belongs to `instance`.
|
||||
let family = unsafe {
|
||||
instance
|
||||
.raw
|
||||
.get_physical_device_queue_family_properties(physical)
|
||||
}
|
||||
.get(queue_family as usize)
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
let family = (families.get(queue_family as usize).copied()).unwrap_or_default();
|
||||
let timestamp_bits = family.timestamp_valid_bits;
|
||||
// SAFETY: as above.
|
||||
let sparse_properties =
|
||||
@@ -966,7 +1054,7 @@ impl Device {
|
||||
prime::prime(
|
||||
&instance.raw,
|
||||
physical,
|
||||
&raw,
|
||||
&Vk::new(raw.clone(), memory_reads),
|
||||
&loader_word,
|
||||
queue_family,
|
||||
&queues,
|
||||
@@ -995,12 +1083,18 @@ impl Device {
|
||||
// SAFETY: as above.
|
||||
let memory_properties =
|
||||
unsafe { instance.raw.get_physical_device_memory_properties(physical) };
|
||||
// Freed memory waits for the batches in flight where the driver fails pending work as
|
||||
// memory a device-address buffer lay in is freed (`freed_memory.rs`).
|
||||
let parking = (properties.driver_defects)
|
||||
.contains(&RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork)
|
||||
.then(|| Arc::new(Parking::new(queues.len())));
|
||||
let memory = Memory::new(
|
||||
&memory_properties,
|
||||
max_allocation,
|
||||
device_address,
|
||||
properties.has_unified_memory,
|
||||
queue_families.clone(),
|
||||
parking.clone(),
|
||||
);
|
||||
// SAFETY: as above.
|
||||
let physical_properties = unsafe { instance.raw.get_physical_device_properties(physical) };
|
||||
@@ -1078,6 +1172,11 @@ impl Device {
|
||||
})
|
||||
})
|
||||
});
|
||||
// SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back.
|
||||
let color_write_masks = unsafe {
|
||||
loader_word.restore();
|
||||
ColorWriteMasks::load(&instance.raw, &raw, &enabled)
|
||||
};
|
||||
// The mesh draw commands, which exist where `meshShader` is enabled (it needs
|
||||
// `VK_EXT_mesh_shader`).
|
||||
let mesh_draws = if enabled
|
||||
@@ -1116,6 +1215,12 @@ impl Device {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// What completed work wrote is made visible to a batch by a barrier where semaphore
|
||||
// operations stall the driver's submissions, else by waits (`command_buffer/submit.rs`).
|
||||
let completed_by_barrier = properties
|
||||
.description
|
||||
.driver_facts()
|
||||
.contains(&metal2vulkan::device::DriverFact::SemaphoreOperationsStallSubmits);
|
||||
// One timestamp pool at most where each is one of Metal's scarce counter sample buffers.
|
||||
let scarce_pools = properties
|
||||
.description
|
||||
@@ -1135,12 +1240,15 @@ impl Device {
|
||||
calibration,
|
||||
from_host,
|
||||
scarce_pools,
|
||||
// A command buffer's first encoder writes its start where its first batch can
|
||||
// begin with no command buffer of barriers (`gpu_time.rs`).
|
||||
!completed_by_barrier,
|
||||
)
|
||||
};
|
||||
// SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back.
|
||||
let functions = unsafe {
|
||||
loader_word.restore();
|
||||
Functions::new(&instance.raw, raw.clone())
|
||||
Functions::new(&instance.raw, raw.clone(), memory_reads)
|
||||
};
|
||||
let shader_cache = match ShaderCache::start(
|
||||
cache,
|
||||
@@ -1221,6 +1329,9 @@ impl Device {
|
||||
heap_nan_residue: NanResidue::default(),
|
||||
function_tables: Mutex::default(),
|
||||
internal: Mutex::new(None),
|
||||
internal_done: OwnTimeline::default(),
|
||||
staging_done: OwnTimeline::default(),
|
||||
completed_by_barrier,
|
||||
bound_at: Mutex::new(None),
|
||||
staging,
|
||||
scheduler,
|
||||
@@ -1237,6 +1348,9 @@ impl Device {
|
||||
sized_index_bind,
|
||||
depth_bias_command,
|
||||
mesh_draws,
|
||||
color_write_masks,
|
||||
snapshot_fallbacks: Mutex::new(Vec::new()),
|
||||
reader_sizes: Mutex::new(Default::default()),
|
||||
gpu_pools,
|
||||
max_framebuffer: [
|
||||
limits.max_framebuffer_width,
|
||||
@@ -1255,6 +1369,7 @@ impl Device {
|
||||
interleave: Mutex::default(),
|
||||
kept: Mutex::default(),
|
||||
shader_modules: Mutex::default(),
|
||||
flights: crate::pipeline::flight::Flights::default(),
|
||||
color_resolves: Mutex::new(ColorResolveObjects::default()),
|
||||
stencil_copies: Mutex::new(StencilCopyObjects::default()),
|
||||
depth_copies: Mutex::new(DepthCopyObjects::default()),
|
||||
@@ -1268,6 +1383,8 @@ impl Device {
|
||||
fresh: Default::default(),
|
||||
owners: Default::default(),
|
||||
live_buffers: Default::default(),
|
||||
#[cfg(unix)]
|
||||
residency: Default::default(),
|
||||
timing,
|
||||
view_reinterpretation,
|
||||
generated_commands,
|
||||
@@ -1276,9 +1393,11 @@ impl Device {
|
||||
sparse,
|
||||
spares: Spares::default(),
|
||||
counts: Default::default(),
|
||||
parking: parking.map_or_else(OnceLock::new, OnceLock::from),
|
||||
uncommitted: Arc::default(),
|
||||
pipeline_pool: Default::default(),
|
||||
reaper: Default::default(),
|
||||
trails: Arc::default(),
|
||||
libraries: graphics_pipeline_library.then(Default::default),
|
||||
});
|
||||
// A CPU device runs the work submitted to it on the process's own threads: the exit hook
|
||||
|
||||
@@ -15,27 +15,49 @@
|
||||
//! alone (`functions.rs`), and each priming checks, in builds with debug assertions, that it made
|
||||
//! every entry point of the table but [`UNPRIMED`]: an entry point added to the table and not made
|
||||
//! here fails every lane at its first device. The calls: a batch's (a command pool and a command
|
||||
//! buffer of it, begun, with the barriers every batch begins and ends with and, where the queue
|
||||
//! family writes timestamps, the reset and the two timestamps of a command buffer's GPU times
|
||||
//! buffer of it, begun, with the barrier every batch ends with and, where the queue family writes
|
||||
//! timestamps, the reset and the two timestamps of a command buffer's GPU times
|
||||
//! ([`TIMESTAMP_CALLS`], made only there), ended, submitted after each queue's timeline at 0 and
|
||||
//! signalling a timeline of its own and a new fence; the wait for the timeline, a read of every
|
||||
//! timeline, the wait for the fence and its reset, a wait for the queue to be idle (its drain after
|
||||
//! a failed wait), and the read of the two timestamps, as the completion thread makes them); a
|
||||
//! a failed wait), and the read of the two timestamps, as a completion turn makes them); a
|
||||
//! sampler, an occlusion query pool, a buffer in host-visible memory, mapped (and, where the device
|
||||
//! has device addresses, [`DEVICE_ADDRESS_CALLS`], its address read), and an image with their
|
||||
//! memory and views, a depth image, a render pass and a framebuffer, a descriptor set layout, a
|
||||
//! pipeline layout with a push constant range and a descriptor pool with a set written, and a
|
||||
//! compute pipeline made with a pipeline cache from a shader module, whose data is read; a command
|
||||
//! buffer, recorded and never submitted, with what a host step records: the pipeline and the set
|
||||
//! bound, a push constant, a dispatch and one from the buffer's arguments, a copy within the
|
||||
//! buffer, a copy from the buffer to the image and back with a barrier between them, a copy between
|
||||
//! the image's texels and the image's clear (a render host step's pass steps) and the depth image's
|
||||
//! (a batch's first work's), then a render host step's: a graphics pipeline that rasterizes nothing
|
||||
//! drawn in a secondary command buffer, directly and from the buffer's arguments, with a vertex
|
||||
//! buffer and the states a draw sets, inside a query of the occlusion pool, which the render pass's
|
||||
//! subpass executes; where the queues bind sparse memory, an empty `vkQueueBindSparse`
|
||||
//! ([`SPARSE_CALLS`]); a wait for the device to be idle; and the release of each object made.
|
||||
//! Nothing of it outlives the call.
|
||||
//! compute pipeline made with a pipeline cache from a shader module, its stage specialized as the
|
||||
//! runtime's makings are ([`SPECIALIZED`]), whose data is read; a command buffer, recorded and
|
||||
//! never submitted, with what a host step records: the pipeline and the set bound, a push
|
||||
//! constant, a dispatch and one from the buffer's arguments, a copy within the buffer, a copy from
|
||||
//! the buffer to the image and back with a barrier between them, a copy between the image's texels
|
||||
//! and the image's clear (a render host step's pass steps) and the depth image's (a batch's first
|
||||
//! work's), then a render host step's: a graphics pipeline that rasterizes nothing, its stage
|
||||
//! specialized too, drawn in a secondary command buffer, directly and from the buffer's arguments,
|
||||
//! with a vertex buffer and the states a draw sets, inside a query of the occlusion pool, which the
|
||||
//! render pass's subpass executes; where the queues bind sparse memory, an empty
|
||||
//! `vkQueueBindSparse` ([`SPARSE_CALLS`]); a wait for the device to be idle; and the release of
|
||||
//! each object made. Nothing of it outlives the call.
|
||||
//!
|
||||
//! **Specialized, with an extended instruction, as the runtime's makings are.** A stage with
|
||||
//! specialization constants takes paths of its own: in a driver's compiler, and in the Khronos
|
||||
//! validation layer's checks of the stage, which run `spirv-opt`'s passes and the SPIR-V validator
|
||||
//! over the module specialized at each pipeline's creation. A module the layer validated before, in
|
||||
//! any process, it skips at its creation (its validation cache, kept on disk), and priming's are
|
||||
//! the same in every process: so without a specialized stage, priming ran no validator at all, and
|
||||
//! the process's first making of a specialized pipeline made the validator's statics. And the
|
||||
//! validator makes one of them only at an operand naming an untyped definition made before it,
|
||||
//! such as an extended instruction's set: so priming's modules take `GLSL.std.450`'s `UMin` of
|
||||
//! their constant, as translated modules take that set's instructions. Measured on the M3 Max
|
||||
//! (macOS 27.0.1, MoltenVK 1.4.1, the layer and `spirv-tools` 1.4.357.0 from Homebrew), in a lane
|
||||
//! process that exited while a pool's making of a host step's variant was in progress: `SIGSEGV` at
|
||||
//! `0x50` inside `spvtools::val::InstructionCanHaveTypeOperand`, its function-local
|
||||
//! `std::unordered_set` already destroyed (`CoreChecks::ValidateShaderStage`, from
|
||||
//! `vkCreateComputePipelines` on the pool's thread, in its making section). A diagnostic interposer
|
||||
//! of the C library's exit handlers showed the validator's two such sets (that one and
|
||||
//! `InstructionRequiresTypeOperand`'s) made after the hook's first registration in each of 10 runs,
|
||||
//! the second after its last, by a making on the program's thread or the pool's; with priming
|
||||
//! specialized and taking the extended instruction, both made in priming, before the hook's first
|
||||
//! registration, in each of 10.
|
||||
//!
|
||||
//! Priming makes each entry point once, in the runtime's shapes; it cannot promise that a layer
|
||||
//! makes no new static on a code path a later call takes with other parameters. A section's
|
||||
@@ -57,6 +79,7 @@ use crate::tracker::Barrier;
|
||||
use ash::vk;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::functions::Vk;
|
||||
use super::QueueSlot;
|
||||
|
||||
/// The table's entry points priming cannot make before the hook is registered for the device it
|
||||
@@ -94,20 +117,29 @@ pub(crate) const SPARSE_CALLS: [Call; 1] = [Call::QueueBindSparse];
|
||||
/// The longest the priming submission is waited for: it holds two barriers.
|
||||
const LIMIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How long one wait lasts before it is repeated, as the completion thread's.
|
||||
/// How long one wait lasts before it is repeated, as a queue waiter's.
|
||||
const WAIT_SLICE: Duration = Duration::from_millis(100);
|
||||
|
||||
/// The smallest compute shader: `main`, of one invocation, returns (SPIR-V 1.0). Also the words
|
||||
/// of a host step's own module in `tests/teardown_threads.rs`.
|
||||
pub(crate) const SHADER: [u32; 35] = [
|
||||
/// The smallest compute shader with a specialization constant ([`SPECIALIZED`]) and an extended
|
||||
/// instruction: `main`, of one invocation, takes `GLSL.std.450`'s `UMin` of the constant and
|
||||
/// returns (SPIR-V 1.0). Also the words of a host step's own module in
|
||||
/// `tests/teardown_threads.rs`.
|
||||
pub(crate) const SHADER: [u32; 60] = [
|
||||
0x0723_0203,
|
||||
0x0001_0000,
|
||||
0,
|
||||
5,
|
||||
10,
|
||||
0,
|
||||
// OpCapability Shader
|
||||
0x0002_0011,
|
||||
1,
|
||||
// %8 = OpExtInstImport "GLSL.std.450"
|
||||
0x0006_000b,
|
||||
8,
|
||||
0x4c53_4c47,
|
||||
0x6474_732e,
|
||||
0x3035_342e,
|
||||
0,
|
||||
// OpMemoryModel Logical GLSL450
|
||||
0x0003_000e,
|
||||
0,
|
||||
@@ -125,13 +157,28 @@ pub(crate) const SHADER: [u32; 35] = [
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
// OpDecorate %5 SpecId 0
|
||||
0x0004_0047,
|
||||
5,
|
||||
1,
|
||||
0,
|
||||
// %2 = OpTypeVoid; %3 = OpTypeFunction %2
|
||||
0x0002_0013,
|
||||
2,
|
||||
0x0003_0021,
|
||||
3,
|
||||
2,
|
||||
// %1 = OpFunction %2 None %3; %4 = OpLabel; OpReturn; OpFunctionEnd
|
||||
// %6 = OpTypeInt 32 0; %5 = OpSpecConstant %6 0
|
||||
0x0004_0015,
|
||||
6,
|
||||
32,
|
||||
0,
|
||||
0x0004_0032,
|
||||
6,
|
||||
5,
|
||||
0,
|
||||
// %1 = OpFunction %2 None %3; %4 = OpLabel; %9 = OpExtInst %6 %8 UMin %5 %5; OpReturn;
|
||||
// OpFunctionEnd
|
||||
0x0005_0036,
|
||||
2,
|
||||
1,
|
||||
@@ -139,21 +186,36 @@ pub(crate) const SHADER: [u32; 35] = [
|
||||
3,
|
||||
0x0002_00f8,
|
||||
4,
|
||||
0x0007_000c,
|
||||
6,
|
||||
9,
|
||||
8,
|
||||
38,
|
||||
5,
|
||||
5,
|
||||
0x0001_00fd,
|
||||
0x0001_0038,
|
||||
];
|
||||
|
||||
/// The smallest vertex shader: `main` returns (SPIR-V 1.0), for a pipeline that rasterizes
|
||||
/// nothing.
|
||||
const VERTEX_SHADER: [u32; 29] = [
|
||||
/// The smallest vertex shader with a specialization constant ([`SPECIALIZED`]) and an extended
|
||||
/// instruction: `main` takes `GLSL.std.450`'s `UMin` of the constant and returns (SPIR-V 1.0), for
|
||||
/// a pipeline that rasterizes nothing.
|
||||
const VERTEX_SHADER: [u32; 54] = [
|
||||
0x0723_0203,
|
||||
0x0001_0000,
|
||||
0,
|
||||
5,
|
||||
10,
|
||||
0,
|
||||
// OpCapability Shader
|
||||
0x0002_0011,
|
||||
1,
|
||||
// %8 = OpExtInstImport "GLSL.std.450"
|
||||
0x0006_000b,
|
||||
8,
|
||||
0x4c53_4c47,
|
||||
0x6474_732e,
|
||||
0x3035_342e,
|
||||
0,
|
||||
// OpMemoryModel Logical GLSL450
|
||||
0x0003_000e,
|
||||
0,
|
||||
@@ -164,13 +226,28 @@ const VERTEX_SHADER: [u32; 29] = [
|
||||
1,
|
||||
0x6e69_616d,
|
||||
0,
|
||||
// OpDecorate %5 SpecId 0
|
||||
0x0004_0047,
|
||||
5,
|
||||
1,
|
||||
0,
|
||||
// %2 = OpTypeVoid; %3 = OpTypeFunction %2
|
||||
0x0002_0013,
|
||||
2,
|
||||
0x0003_0021,
|
||||
3,
|
||||
2,
|
||||
// %1 = OpFunction %2 None %3; %4 = OpLabel; OpReturn; OpFunctionEnd
|
||||
// %6 = OpTypeInt 32 0; %5 = OpSpecConstant %6 0
|
||||
0x0004_0015,
|
||||
6,
|
||||
32,
|
||||
0,
|
||||
0x0004_0032,
|
||||
6,
|
||||
5,
|
||||
0,
|
||||
// %1 = OpFunction %2 None %3; %4 = OpLabel; %9 = OpExtInst %6 %8 UMin %5 %5; OpReturn;
|
||||
// OpFunctionEnd
|
||||
0x0005_0036,
|
||||
2,
|
||||
1,
|
||||
@@ -178,10 +255,37 @@ const VERTEX_SHADER: [u32; 29] = [
|
||||
3,
|
||||
0x0002_00f8,
|
||||
4,
|
||||
0x0007_000c,
|
||||
6,
|
||||
9,
|
||||
8,
|
||||
38,
|
||||
5,
|
||||
5,
|
||||
0x0001_00fd,
|
||||
0x0001_0038,
|
||||
];
|
||||
|
||||
/// The constant [`SHADER`] and the vertex shader declare, specialized as the runtime's makings
|
||||
/// specialize their modules' (`pipeline/objects.rs`, `pipeline/graphics.rs`): a specialized stage
|
||||
/// takes paths of its own, in a driver's compiler and in a layer's checks of the stage, which a
|
||||
/// making then reaches first (the module docs).
|
||||
const SPECIALIZED: [vk::SpecializationMapEntry; 1] = [vk::SpecializationMapEntry {
|
||||
constant_id: 0,
|
||||
offset: 0,
|
||||
size: 4,
|
||||
}];
|
||||
|
||||
/// The value of [`SPECIALIZED`]'s constant.
|
||||
const SPECIALIZED_VALUE: [u8; 4] = 1u32.to_le_bytes();
|
||||
|
||||
/// The specialization of each priming stage: [`SPECIALIZED`] at [`SPECIALIZED_VALUE`].
|
||||
fn specialization() -> vk::SpecializationInfo<'static> {
|
||||
vk::SpecializationInfo::default()
|
||||
.map_entries(&SPECIALIZED)
|
||||
.data(&SPECIALIZED_VALUE)
|
||||
}
|
||||
|
||||
/// What the device primed has: a queue family that writes timestamps, device addresses,
|
||||
/// `VK_EXT_device_generated_commands`, and sparse binding on its queues.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -206,7 +310,7 @@ pub(crate) struct Has {
|
||||
pub(super) unsafe fn prime(
|
||||
instance: &ash::Instance,
|
||||
physical: vk::PhysicalDevice,
|
||||
device: &ash::Device,
|
||||
device: &Vk,
|
||||
loader_word: &LoaderWord,
|
||||
queue_family: u32,
|
||||
queues: &[QueueSlot],
|
||||
@@ -293,7 +397,7 @@ type Release = Box<dyn FnOnce(&ash::Device) -> Call>;
|
||||
|
||||
/// A priming in progress.
|
||||
struct Primer<'a> {
|
||||
device: &'a ash::Device,
|
||||
device: &'a Vk,
|
||||
/// The device's loader word, put back before each call the loader serves.
|
||||
loader_word: &'a LoaderWord,
|
||||
/// How the device's buffers and images are shared among its queue families.
|
||||
@@ -426,7 +530,6 @@ impl Primer<'_> {
|
||||
self.made(Call::CmdResetQueryPool);
|
||||
device.cmd_write_timestamp(buffer, vk::PipelineStageFlags::TOP_OF_PIPE, queries, 0);
|
||||
}
|
||||
Barrier::after_completed().record(device, buffer);
|
||||
Barrier::to_host().record(device, buffer);
|
||||
self.made(Call::CmdPipelineBarrier);
|
||||
if let Some(queries) = queries {
|
||||
@@ -501,7 +604,7 @@ impl Primer<'_> {
|
||||
// SAFETY: the fence is signaled and its submission completed.
|
||||
unsafe { device.reset_fences(&fences) }.map_err(vulkan)?;
|
||||
self.made(Call::ResetFences);
|
||||
// The completion thread's drain of the queues after a failed wait
|
||||
// A completion turn's drain of the queues after a failed wait
|
||||
// (`Device::drain_queues`).
|
||||
// SAFETY: the queue is used under its lock; its one submission completed.
|
||||
queues[0]
|
||||
@@ -566,10 +669,12 @@ impl Primer<'_> {
|
||||
self.hold(layout);
|
||||
let mut flags =
|
||||
vk::PipelineCreateFlags2CreateInfoKHR::default().flags(INDIRECT_BINDABLE);
|
||||
let specialization = specialization();
|
||||
let stage = vk::PipelineShaderStageCreateInfo::default()
|
||||
.stage(vk::ShaderStageFlags::COMPUTE)
|
||||
.module(module)
|
||||
.name(c"main");
|
||||
.name(c"main")
|
||||
.specialization_info(&specialization);
|
||||
let info = vk::ComputePipelineCreateInfo::default()
|
||||
.stage(stage)
|
||||
.layout(layout)
|
||||
@@ -853,10 +958,12 @@ impl Primer<'_> {
|
||||
.map_err(vulkan)?;
|
||||
self.made(Call::CreatePipelineCache);
|
||||
self.hold(cache);
|
||||
let specialization = specialization();
|
||||
let stage = vk::PipelineShaderStageCreateInfo::default()
|
||||
.stage(vk::ShaderStageFlags::COMPUTE)
|
||||
.module(module)
|
||||
.name(c"main");
|
||||
.name(c"main")
|
||||
.specialization_info(&specialization);
|
||||
let info = [vk::ComputePipelineCreateInfo::default()
|
||||
.stage(stage)
|
||||
.layout(layout)];
|
||||
@@ -1027,10 +1134,12 @@ impl Primer<'_> {
|
||||
let info = vk::ShaderModuleCreateInfo::default().code(&VERTEX_SHADER);
|
||||
let module = device.create_shader_module(&info, None).map_err(vulkan)?;
|
||||
self.hold(module);
|
||||
let specialization = specialization();
|
||||
let stages = [vk::PipelineShaderStageCreateInfo::default()
|
||||
.stage(vk::ShaderStageFlags::VERTEX)
|
||||
.module(module)
|
||||
.name(c"main")];
|
||||
.name(c"main")
|
||||
.specialization_info(&specialization)];
|
||||
let vertex_input = vk::PipelineVertexInputStateCreateInfo::default();
|
||||
// Triangles: a point list's vertex shader must write the point size where the device
|
||||
// does not enable `maintenance5`.
|
||||
|
||||
@@ -272,19 +272,21 @@ impl Flights {
|
||||
|
||||
/// The submissions through the one of the last of `fences` completed (their fences are
|
||||
/// signaled, and every earlier submission's): they leave the log. The fences of the ones not
|
||||
/// of a batch, for the caller to reset and give back (a batch's goes back with it).
|
||||
pub(crate) fn settled(&self, fences: &[vk::Fence]) -> Vec<vk::Fence> {
|
||||
/// of a batch go onto `marks`, for the caller to reset and give back (a batch's goes back with
|
||||
/// it).
|
||||
pub(crate) fn settled(&self, fences: &[vk::Fence], marks: &mut Vec<vk::Fence>) {
|
||||
let mut log = lock(&self.log);
|
||||
let Some(through) = log
|
||||
.iter()
|
||||
.rposition(|flight| fences.contains(&flight.fence))
|
||||
else {
|
||||
return Vec::new();
|
||||
return;
|
||||
};
|
||||
log.drain(..=through)
|
||||
.filter(|flight| !matches!(flight.by, By::Batch(_)))
|
||||
.map(|flight| flight.fence)
|
||||
.collect()
|
||||
marks.extend(
|
||||
log.drain(..=through)
|
||||
.filter(|flight| !matches!(flight.by, By::Batch(_)))
|
||||
.map(|flight| flight.fence),
|
||||
);
|
||||
}
|
||||
|
||||
/// How many of the queue's submissions are in the log: made, and not yet seen complete.
|
||||
@@ -376,23 +378,35 @@ impl super::DeviceShared {
|
||||
|
||||
/// Submit a batch of a command buffer's to `VkQueue` `queue` with `f`, under the queue's
|
||||
/// lock: where its failures are relayed, the submission of `fence` is logged first, its
|
||||
/// failure for `failed` ([`By::Batch`]), and dropped from the log again when `f` fails.
|
||||
/// failure for `failed` ([`By::Batch`]), and dropped from the log again when `f` fails. A
|
||||
/// batch that signals the queue's timeline to `value` notes it once submitted (the exit
|
||||
/// hook's value, and where freed memory waits for the batches in flight, theirs, under the
|
||||
/// gate's read lock: `freed_memory.rs`).
|
||||
pub(crate) fn submit_logged(
|
||||
&self,
|
||||
queue: usize,
|
||||
(queue, value): (usize, Option<u64>),
|
||||
fence: Option<vk::Fence>,
|
||||
failed: &Arc<Relayed>,
|
||||
f: impl FnOnce(vk::Queue) -> Result<(), vk::Result>,
|
||||
) -> Result<(), vk::Result> {
|
||||
let slot = &self.queues[queue];
|
||||
let logged = fence.zip(slot.flights.get());
|
||||
let parking = self.parking.get();
|
||||
slot.with(|vk_queue| {
|
||||
let _gate = parking.map(|parking| parking.submitting());
|
||||
if let Some((fence, flights)) = logged {
|
||||
flights.push(fence, By::Batch(Arc::clone(failed)));
|
||||
}
|
||||
let submitted = f(vk_queue);
|
||||
if let (Err(_), Some((fence, flights))) = (&submitted, logged) {
|
||||
flights.unpush(fence);
|
||||
match (&submitted, logged, value) {
|
||||
(Err(_), Some((fence, flights)), _) => flights.unpush(fence),
|
||||
(Ok(()), _, Some(value)) => {
|
||||
slot.submitted(value);
|
||||
if let Some(parking) = parking {
|
||||
parking.submitted(queue, value);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
submitted
|
||||
})
|
||||
@@ -411,15 +425,16 @@ impl super::DeviceShared {
|
||||
};
|
||||
let fence = exit_guard::enter().and_then(|_busy| {
|
||||
let raw = self.vk();
|
||||
let done = flights.done_marks();
|
||||
let mut done = flights.done_marks();
|
||||
if !done.is_empty() {
|
||||
// SAFETY: each is signaled, its submission completed, and out of the log.
|
||||
let reset = unsafe { raw.reset_fences(&done) };
|
||||
exit_guard::called(Call::ResetFences);
|
||||
for fence in reset
|
||||
.map(|()| self.fences.keep(done.iter().copied()))
|
||||
.unwrap_or(done)
|
||||
{
|
||||
// Kept idle where reset; the rest, and all where the reset failed, released.
|
||||
if reset.is_ok() {
|
||||
self.fences.keep(&mut done);
|
||||
}
|
||||
for fence in done {
|
||||
// SAFETY: as above.
|
||||
unsafe { crate::release::object(raw, fence) };
|
||||
}
|
||||
|
||||
@@ -18,6 +18,11 @@
|
||||
//! 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.
|
||||
//! - **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
|
||||
@@ -40,6 +45,8 @@ const WAIT_SLICE: Duration = Duration::from_millis(100);
|
||||
pub(super) struct StagingQueue {
|
||||
/// The queue's family: one of transfers alone.
|
||||
family: u32,
|
||||
/// The family's queue flags, which the barriers recorded for it follow (`image_barrier.rs`).
|
||||
flags: vk::QueueFlags,
|
||||
/// The device's families, then the queue's: those an image that copies here is shared
|
||||
/// among.
|
||||
families: Vec<u32>,
|
||||
@@ -55,22 +62,34 @@ struct Objects {
|
||||
made: Option<Made>,
|
||||
}
|
||||
|
||||
/// The command pool, command buffer and fence of the staging submissions, made on first use.
|
||||
/// The command pool, command buffer, fence 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<vk::Semaphore>,
|
||||
signalled: u64,
|
||||
}
|
||||
|
||||
impl StagingQueue {
|
||||
/// The staging queue `queue` of `family`, on a device that submits to `families`.
|
||||
/// The staging queue `queue` of `family`, whose queue flags are `flags`, on a device that
|
||||
/// submits to `families`.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `queue` was just returned by the device: its word is the loader's.
|
||||
pub(super) unsafe fn new(family: u32, queue: vk::Queue, families: &[u32]) -> StagingQueue {
|
||||
pub(super) unsafe fn new(
|
||||
family: u32,
|
||||
flags: vk::QueueFlags,
|
||||
queue: vk::Queue,
|
||||
families: &[u32],
|
||||
) -> StagingQueue {
|
||||
StagingQueue {
|
||||
family,
|
||||
flags,
|
||||
families: families.iter().copied().chain([family]).collect(),
|
||||
// SAFETY: the caller's contract.
|
||||
word: unsafe { LoaderWord::of_handle(queue.as_raw()) },
|
||||
@@ -84,6 +103,9 @@ impl StagingQueue {
|
||||
// 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.pool);
|
||||
}
|
||||
}
|
||||
@@ -110,10 +132,33 @@ impl Made {
|
||||
// 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 {
|
||||
pool,
|
||||
buffer,
|
||||
fence,
|
||||
timeline,
|
||||
signalled: 0,
|
||||
})
|
||||
})();
|
||||
if made.is_err() {
|
||||
@@ -139,11 +184,11 @@ impl Device {
|
||||
|
||||
/// 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: it
|
||||
/// records copies, fills and barriers, of color aspects alone.
|
||||
/// 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.
|
||||
pub(crate) fn submit_staging(
|
||||
&self,
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer, vk::QueueFlags),
|
||||
) -> Result<(), Error> {
|
||||
if self.is_lost() {
|
||||
return Err(Error::DeviceLost);
|
||||
@@ -157,7 +202,7 @@ impl Device {
|
||||
objects.made = Some(Made::new(self, staging.family)?);
|
||||
}
|
||||
let queue = objects.queue;
|
||||
let Some(made) = objects.made.as_ref() else {
|
||||
let Some(made) = objects.made.as_mut() else {
|
||||
unreachable!("made above");
|
||||
};
|
||||
let begin = vk::CommandBufferBeginInfo::default()
|
||||
@@ -166,7 +211,7 @@ impl Device {
|
||||
// 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();
|
||||
record(raw, made.buffer);
|
||||
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.
|
||||
@@ -179,16 +224,24 @@ impl Device {
|
||||
let wait_semaphores: Vec<vk::Semaphore> = completed.iter().map(|w| w.0).collect();
|
||||
let wait_values: Vec<u64> = completed.iter().map(|w| w.1).collect();
|
||||
let wait_stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; completed.len()];
|
||||
let mut timeline =
|
||||
vk::TimelineSemaphoreSubmitInfo::default().wait_semaphore_values(&wait_values);
|
||||
// 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<vk::Semaphore> = made.timeline.into_iter().collect();
|
||||
let signal_values: Vec<u64> = 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).
|
||||
// executable; every value waited for was signalled (the host saw it); the signal of the
|
||||
// timeline is above its value.
|
||||
shared.counts.queue_submitted(buffers.len());
|
||||
let submitted = unsafe {
|
||||
staging.word.restore();
|
||||
@@ -196,12 +249,18 @@ impl Device {
|
||||
};
|
||||
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(()) => return Ok(()),
|
||||
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)),
|
||||
}
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
//! The device's own synchronous submissions: work the runtime does for itself outside any
|
||||
//! command buffer (a host copy into or out of a texture, an explicit clear of a live buffer).
|
||||
//! Each runs alone on the device's first `VkQueue`, and the caller waits for it, so it completed
|
||||
//! (and the host saw it) before any batch that uses its result is submitted; every batch starts
|
||||
//! with the barrier that makes such writes visible. Each first does the new resources' first GPU
|
||||
//! work that waits (`texture/first_move.rs`), after the batches on other `VkQueue`s that did such
|
||||
//! work: no new resource waits for one, so making one waits for no GPU work. That work goes in a
|
||||
//! `VkSubmitInfo` of its own just before the work's, in its `vkQueueSubmit`, as a batch's does
|
||||
//! (`command_buffer/submit.rs`): one kernel submission on Mesa's drivers.
|
||||
//! (and the host saw it) before any batch that uses its result is submitted. Each signals the
|
||||
//! internal timeline, and every batch with work waits for that timeline at the value the host saw
|
||||
//! it reach ([`OwnTimeline`]), which makes such writes visible to the batch; where the driver's
|
||||
//! submissions stall on semaphore operations, the batch's first barrier makes them visible
|
||||
//! instead (`command_buffer/submit.rs`). Each first does the
|
||||
//! new resources' first GPU work that waits (`texture/first_move.rs`), after the batches on other
|
||||
//! `VkQueue`s that did such work: no new resource waits for one, so making one waits for no GPU
|
||||
//! work. That work goes in a `VkSubmitInfo` of its own just before the work's, in its
|
||||
//! `vkQueueSubmit`, as a batch's does (`command_buffer/submit.rs`): one kernel submission on
|
||||
//! Mesa's drivers.
|
||||
//!
|
||||
//! The one submission no one waits for is a no-copy buffer's sparse binding of its dma-bufs
|
||||
//! (`dma_buf.rs`), on the same queue and timeline: it would wait behind the queue's work in
|
||||
//! flight. Every submission after it, on every `VkQueue`, waits for it until the host saw it
|
||||
//! complete, and the buffer's release waits for it.
|
||||
|
||||
use super::functions::Vk;
|
||||
use super::relay::By;
|
||||
use super::{lock, Device};
|
||||
use crate::error::{vulkan, Error};
|
||||
@@ -20,11 +25,62 @@ use crate::exit_guard::{self, Call};
|
||||
use crate::release;
|
||||
use crate::resource::ResourceKey;
|
||||
use ash::vk;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
/// How long one wait for an internal submission lasts before it is repeated.
|
||||
const WAIT_SLICE: Duration = Duration::from_millis(100);
|
||||
|
||||
/// One wait of [`WAIT_SLICE`] on `info`'s timelines.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The timelines are `device`'s.
|
||||
unsafe fn raw_wait(
|
||||
device: &ash::Device,
|
||||
info: &vk::SemaphoreWaitInfo<'_>,
|
||||
) -> Result<(), vk::Result> {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { device.wait_semaphores(info, WAIT_SLICE.as_nanos() as u64) }
|
||||
}
|
||||
|
||||
/// A timeline the device's own submissions signal outside the batches (the internal ones here,
|
||||
/// the staging queue's copies, `staging.rs`), and the value through which the host saw them
|
||||
/// complete. Each batch with work waits for it at that value, once per value on its `VkQueue`
|
||||
/// (`command_buffer/submit.rs`), which makes what they wrote visible to the batch and to every
|
||||
/// later command there: the submission's "second synchronization scope of each semaphore wait
|
||||
/// operation defined by this command includes every command in the same batch that the wait
|
||||
/// operation is defined in, and all commands that occur later in submission order", and the
|
||||
/// wait's "second access scope includes all memory access performed by the device"
|
||||
/// (`vkQueueSubmit`, semaphore waiting).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct OwnTimeline {
|
||||
semaphore: OnceLock<vk::Semaphore>,
|
||||
completed: AtomicU64,
|
||||
}
|
||||
|
||||
impl OwnTimeline {
|
||||
/// The timeline and the value through which the host saw its submissions complete; `None`
|
||||
/// before the first completed.
|
||||
pub(crate) fn completed(&self) -> Option<(vk::Semaphore, u64)> {
|
||||
let value = self.completed.load(Ordering::Acquire);
|
||||
let semaphore = *self.semaphore.get()?;
|
||||
(value > 0).then_some((semaphore, value))
|
||||
}
|
||||
|
||||
/// The timeline was made: `semaphore`.
|
||||
pub(super) fn made(&self, semaphore: vk::Semaphore) {
|
||||
// A device makes each of its two own timelines once.
|
||||
let _ = self.semaphore.set(semaphore);
|
||||
}
|
||||
|
||||
/// The host saw the timeline reach `value`.
|
||||
pub(super) fn reached(&self, value: u64) {
|
||||
self.completed.fetch_max(value, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
/// The command pool, command buffers and fence of internal submissions, made on first use.
|
||||
pub(super) struct Internal {
|
||||
pool: vk::CommandPool,
|
||||
@@ -73,6 +129,7 @@ impl Internal {
|
||||
return Err(vulkan(error));
|
||||
}
|
||||
};
|
||||
device.shared().internal_done.made(timeline);
|
||||
Ok(Internal {
|
||||
pool,
|
||||
buffer,
|
||||
@@ -105,7 +162,7 @@ impl Device {
|
||||
/// it. Internal submissions are serialized by the internal lock.
|
||||
pub(crate) fn submit_internal(
|
||||
&self,
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) -> Result<(), Error> {
|
||||
self.submit_internal_naming(|_| false, record)
|
||||
}
|
||||
@@ -116,27 +173,34 @@ impl Device {
|
||||
pub(crate) fn submit_internal_naming(
|
||||
&self,
|
||||
named: impl Fn(ResourceKey) -> bool,
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) -> Result<(), Error> {
|
||||
if self.is_lost() {
|
||||
return Err(Error::DeviceLost);
|
||||
}
|
||||
let shared = self.shared();
|
||||
let raw = shared.vk();
|
||||
let mut internal = lock(&shared.internal);
|
||||
if internal.is_none() {
|
||||
*internal = Some(Internal::new(self)?);
|
||||
}
|
||||
let firsts = &shared.textures.first_moves;
|
||||
// The new resources' first work, given back if the submission is not made, after every
|
||||
// batch on another `VkQueue` that did some. Its place in the submissions' order is held
|
||||
// until it was made. The moves that keep the bytes their images are bound to the host
|
||||
// makes first ([`keep_on_host`](Self::keep_on_host)); one registered meanwhile too.
|
||||
let (mut internal, taken) = loop {
|
||||
self.keep_on_host(&named)?;
|
||||
let mut internal = lock(&shared.internal);
|
||||
if internal.is_none() {
|
||||
*internal = Some(Internal::new(self)?);
|
||||
}
|
||||
let taken = firsts.take(&named);
|
||||
if !taken.has_keeps() {
|
||||
break (internal, taken);
|
||||
}
|
||||
};
|
||||
let Some(objects) = internal.as_mut() else {
|
||||
unreachable!("made above");
|
||||
};
|
||||
let begin = vk::CommandBufferBeginInfo::default()
|
||||
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
|
||||
// The new resources' first work, given back if the submission is not made, after every
|
||||
// batch on another `VkQueue` that did some. Its place in the submissions' order is held
|
||||
// until it was made.
|
||||
let firsts = &shared.textures.first_moves;
|
||||
let taken = firsts.take(named);
|
||||
let waits = firsts.waits(0, |point| {
|
||||
shared.queues[point.queue].completed_value() >= point.value
|
||||
});
|
||||
@@ -152,7 +216,7 @@ impl Device {
|
||||
// SAFETY: recording, outside a render pass, for the queue family; it is submitted
|
||||
// just before the work's submission, which is waited for before anything that uses
|
||||
// the resources is submitted after it.
|
||||
unsafe { taken.record(raw, objects.first) };
|
||||
unsafe { taken.record(raw, objects.first, shared.queue_flags_of(0)) };
|
||||
// SAFETY: as above.
|
||||
unsafe { raw.end_command_buffer(objects.first) }.map_err(vulkan)?;
|
||||
}
|
||||
@@ -208,6 +272,9 @@ impl Device {
|
||||
.into_iter()
|
||||
.chain([submit])
|
||||
.collect();
|
||||
// Where freed memory waits for the work in flight, it waits for this until it completed
|
||||
// (`freed_memory.rs`).
|
||||
let _own = (shared.parking.get()).map(|parking| parking.own_submission(self));
|
||||
// SAFETY: the queue is used under its lock; the command buffers are executable; every
|
||||
// signal of the timeline is above its value. Where the queue's failures are relayed, a
|
||||
// failure of this submission loses the device (`relay.rs`).
|
||||
@@ -234,6 +301,7 @@ impl Device {
|
||||
} {
|
||||
Ok(()) => {
|
||||
firsts.internal_completed(value);
|
||||
shared.internal_done.reached(value);
|
||||
return Ok(());
|
||||
}
|
||||
Err(vk::Result::TIMEOUT) => continue,
|
||||
@@ -242,6 +310,131 @@ impl Device {
|
||||
}
|
||||
}
|
||||
|
||||
/// The new images' first moves that keep the bytes they are bound to (`texture/first_move.rs`'s
|
||||
/// `Keep`), of every resource but those bound to host pages whose key `named` does not name,
|
||||
/// made by the host before a submission takes the rest of the first work: once every
|
||||
/// submission made before on each `VkQueue` completed ([`drain_submitted`]), each image's
|
||||
/// bytes are read through the host pointer, the moves alone are submitted and waited for, and
|
||||
/// the bytes are written back, every one. Nothing where no such move waits. The bytes the
|
||||
/// move may write are its image's own: "Image layout transitions may perform read and write
|
||||
/// accesses on all memory bound to the image subresource range"; and a linear image's
|
||||
/// subresource in `GENERAL` is host-accessible, its memory "interpreted" as its subresource
|
||||
/// layout lays it, so the host's writes are what the image then holds.
|
||||
///
|
||||
/// [`drain_submitted`]: Self::drain_submitted
|
||||
pub(crate) fn keep_on_host(&self, named: impl Fn(ResourceKey) -> bool) -> Result<(), Error> {
|
||||
let shared = self.shared();
|
||||
let firsts = &shared.textures.first_moves;
|
||||
if !firsts.keeps_wait() {
|
||||
return Ok(());
|
||||
}
|
||||
if self.is_lost() {
|
||||
return Err(Error::DeviceLost);
|
||||
}
|
||||
let raw = shared.vk();
|
||||
let mut internal = lock(&shared.internal);
|
||||
if internal.is_none() {
|
||||
*internal = Some(Internal::new(self)?);
|
||||
}
|
||||
let Some(objects) = internal.as_mut() else {
|
||||
unreachable!("made above");
|
||||
};
|
||||
let taken = firsts.take_keeps(named);
|
||||
if !taken.has_keeps() {
|
||||
return Ok(());
|
||||
}
|
||||
// What every submission before wrote is in the bytes, available to the host (each
|
||||
// batch's last barrier, `tracker.rs`'s `to_host`).
|
||||
self.drain_submitted()?;
|
||||
let kept = taken.read_kept();
|
||||
let begin = vk::CommandBufferBeginInfo::default()
|
||||
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
|
||||
// SAFETY: the command buffer is not pending (every internal submission is waited for)
|
||||
// and the internal lock is held; beginning it resets it.
|
||||
unsafe { raw.begin_command_buffer(objects.first, &begin) }.map_err(vulkan)?;
|
||||
shared.counts.command_buffer_begun();
|
||||
// SAFETY: recording, outside a render pass, for the queue family; it is submitted alone
|
||||
// and waited for below, before any submission that uses the images.
|
||||
unsafe { taken.record(raw, objects.first, shared.queue_flags_of(0)) };
|
||||
// SAFETY: as above.
|
||||
unsafe { raw.end_command_buffer(objects.first) }.map_err(vulkan)?;
|
||||
// SAFETY: the fence is unsignaled or signaled and not pending.
|
||||
unsafe { raw.reset_fences(&[objects.fence]) }.map_err(vulkan)?;
|
||||
// After the last binding of a no-copy buffer's dma-bufs, until it completed.
|
||||
let (wait_semaphores, wait_values): (Vec<vk::Semaphore>, Vec<u64>) =
|
||||
self.binding_wait().into_iter().unzip();
|
||||
let wait_stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; wait_semaphores.len()];
|
||||
let value = objects.signalled + 1;
|
||||
let buffers = [objects.first];
|
||||
let signal_semaphores = [objects.timeline];
|
||||
let signal_values = [value];
|
||||
let mut timeline = vk::TimelineSemaphoreSubmitInfo::default()
|
||||
.wait_semaphore_values(&wait_values)
|
||||
.signal_semaphore_values(&signal_values);
|
||||
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);
|
||||
// As in `submit_internal_naming`.
|
||||
let _own = (shared.parking.get()).map(|parking| parking.own_submission(self));
|
||||
// SAFETY: as in `submit_internal_naming`.
|
||||
let made = shared.use_queue(0, By::Runtime, |queue| unsafe {
|
||||
shared.counts.queue_submitted(1);
|
||||
raw.queue_submit(queue, &[submit], objects.fence)
|
||||
});
|
||||
// A `vkQueueSubmit` that fails gives the moves back as `taken` drops.
|
||||
if let Err(error) = made {
|
||||
return Err(self.failed(error));
|
||||
}
|
||||
objects.signalled = value;
|
||||
shared.counts.internal_submission();
|
||||
shared.counts.first_move_kept(taken.kept());
|
||||
// The moves and the pages their bytes lie in, held until the bytes are written back.
|
||||
let held = taken.submitted_internally(objects.timeline, value);
|
||||
loop {
|
||||
// SAFETY: the fence was submitted just now.
|
||||
match unsafe {
|
||||
raw.wait_for_fences(&[objects.fence], true, WAIT_SLICE.as_nanos() as u64)
|
||||
} {
|
||||
Ok(()) => break,
|
||||
Err(vk::Result::TIMEOUT) => continue,
|
||||
Err(error) => return Err(self.failed(error)),
|
||||
}
|
||||
}
|
||||
firsts.internal_completed(value);
|
||||
shared.internal_done.reached(value);
|
||||
kept.write_back();
|
||||
drop(held);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wait until every batch submitted to each `VkQueue` before now completed.
|
||||
fn drain_submitted(&self) -> Result<(), Error> {
|
||||
let shared = self.shared();
|
||||
let (timelines, values): (Vec<vk::Semaphore>, Vec<u64>) = (shared.queues.iter())
|
||||
.map(|queue| (queue.timeline, queue.submitted_value()))
|
||||
.filter(|&(_, value)| value != 0)
|
||||
.unzip();
|
||||
if timelines.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let info = vk::SemaphoreWaitInfo::default()
|
||||
.semaphores(&timelines)
|
||||
.values(&values);
|
||||
loop {
|
||||
// SAFETY: the timelines are the device's; each value was submitted to be signalled,
|
||||
// and no batch submitted waits for a signal not submitted (`scheduler`).
|
||||
match unsafe { raw_wait(shared.vk(), &info) } {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(vk::Result::TIMEOUT) if !self.is_lost() => continue,
|
||||
Err(vk::Result::TIMEOUT) => return Err(Error::DeviceLost),
|
||||
Err(error) => return Err(self.failed(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind `binds` to `buffer`, a sparse buffer no command has used, with one
|
||||
/// `vkQueueBindSparse` on the device's first `VkQueue` that signals the internal timeline,
|
||||
/// and return without waiting for it: every submission made after it, on every `VkQueue`,
|
||||
@@ -291,16 +484,45 @@ impl Device {
|
||||
Ok((objects.timeline, value))
|
||||
}
|
||||
|
||||
/// The device's own timelines outside the batches, each at the value through which the host
|
||||
/// saw its submissions complete ([`OwnTimeline`]): the internal one, then the staging
|
||||
/// queue's.
|
||||
pub(crate) fn own_completed(&self) -> [Option<(vk::Semaphore, u64)>; 2] {
|
||||
let shared = self.shared();
|
||||
[
|
||||
shared.internal_done.completed(),
|
||||
shared.staging_done.completed(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The last binding of a no-copy buffer's dma-bufs ([`Device::bind_sparse_buffer`]) while
|
||||
/// the host has not seen it complete: what a submission waits for, as the buffer may be
|
||||
/// among what it uses.
|
||||
/// among what it uses. The host sees it complete once a wait returned for it
|
||||
/// ([`binding_seen`]), not from its timeline's read alone.
|
||||
pub(crate) fn binding_wait(&self) -> Option<(vk::Semaphore, u64)> {
|
||||
let shared = self.shared();
|
||||
let raw = shared.vk();
|
||||
let mut bound_at = lock(&shared.bound_at);
|
||||
let (timeline, value) = (*bound_at)?;
|
||||
// SAFETY: the timeline is the device's, live while the device is.
|
||||
let reached = unsafe { shared.vk().get_semaphore_counter_value(timeline) };
|
||||
if reached.is_ok_and(|reached| reached >= value) {
|
||||
let read = unsafe { raw.get_semaphore_counter_value(timeline) };
|
||||
exit_guard::called(Call::GetSemaphoreCounterValue);
|
||||
let reaches = |value: u64| {
|
||||
let semaphores = [timeline];
|
||||
let values = [value];
|
||||
let info = vk::SemaphoreWaitInfo::default()
|
||||
.semaphores(&semaphores)
|
||||
.values(&values);
|
||||
// SAFETY: as the read's above. "If timeout is zero, then vkWaitSemaphores does not
|
||||
// wait".
|
||||
let waited = unsafe { raw.wait_semaphores(&info, 0) };
|
||||
exit_guard::called(Call::WaitSemaphores);
|
||||
waited.map(|()| true).or_else(|error| match error {
|
||||
vk::Result::TIMEOUT => Ok(false),
|
||||
error => Err(error),
|
||||
})
|
||||
};
|
||||
if read.is_ok_and(|read| binding_seen(read, value, reaches)) {
|
||||
*bound_at = None;
|
||||
return None;
|
||||
}
|
||||
@@ -315,3 +537,19 @@ impl Device {
|
||||
vulkan(error)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the host saw a binding that signals `value` complete, its timeline read at `read`
|
||||
/// ([`Device::binding_wait`]): only once a wait for `value` returned (`reaches`, a wait of no
|
||||
/// time: "If the condition is satisfied when `vkWaitSemaphores` is called, then
|
||||
/// `vkWaitSemaphores` returns immediately"). Vulkan orders host operations after a signal only
|
||||
/// through a wait ("signal operations happening before host operations that wait on them"
|
||||
/// system-synchronize-with them, the memory model); `vkGetSemaphoreCounterValue`'s value "may
|
||||
/// immediately be out of date" and orders nothing (`command_buffer/completion.rs`). A read below
|
||||
/// `value` asks for no wait; a failed wait (a lost device) leaves the binding waited for.
|
||||
pub(crate) fn binding_seen<E>(
|
||||
read: u64,
|
||||
value: u64,
|
||||
reaches: impl FnOnce(u64) -> Result<bool, E>,
|
||||
) -> bool {
|
||||
read >= value && matches!(reaches(value), Ok(true))
|
||||
}
|
||||
@@ -88,17 +88,19 @@
|
||||
//! buffer whose alignment misses the granule asked. Counted: `WorkCounts::dma_buf_imports` (each
|
||||
//! chunk) and `WorkCounts::dma_buf_sparse_buffers`.
|
||||
|
||||
use super::buffer::usage;
|
||||
use super::buffer::{usage, Pages};
|
||||
use super::buffer_descriptor::HostBuffer;
|
||||
use super::device::lock;
|
||||
use super::error::{invalid, vulkan, Error, Problem};
|
||||
use super::error::{internal, invalid, vulkan, Error, MemoryKind, Problem};
|
||||
use super::exit_guard::{self, Call};
|
||||
use super::host_memory::{based_size, import_refused, not_importable, ImportWindow, Importer};
|
||||
use super::host_residency::Again;
|
||||
use super::image_plan::{ImageFacts, ImagePlan};
|
||||
use super::linear_plan::{
|
||||
check_linear_limits, tiling_lack, viewed_formats, BufferLayout, Holds, LinearLack,
|
||||
};
|
||||
use super::memory::{ImportFailure, MemoryClass, Placement};
|
||||
use super::program_objects::ProgramObject;
|
||||
use super::Device;
|
||||
use crate::release;
|
||||
use ash::vk;
|
||||
@@ -186,8 +188,12 @@ pub struct DmaBufChunk {
|
||||
pub(super) struct DmaBufPages {
|
||||
device: Device,
|
||||
memories: Vec<vk::DeviceMemory>,
|
||||
/// The caller's source; taken only as the pages drop.
|
||||
source: Option<DmaBufSource>,
|
||||
/// The imports are an image's dedicated one (`Device::dma_buf_image`), not a buffer's chunks:
|
||||
/// what the live gauges count them as (`WorkCounts::dma_buf_image_memories_live`).
|
||||
of_image: bool,
|
||||
/// The caller's source, held as the program's object (`program_objects.rs`); taken only as
|
||||
/// the pages drop.
|
||||
source: Option<ProgramObject<DmaBufSource>>,
|
||||
/// The host address of the first page, and the bytes of the pages: what the source made the
|
||||
/// imports of.
|
||||
start: u64,
|
||||
@@ -207,32 +213,48 @@ impl Drop for DmaBufPages {
|
||||
}
|
||||
return;
|
||||
};
|
||||
let raw_device = self.device.shared().vk();
|
||||
let shared = self.device.shared();
|
||||
let raw_device = shared.vk();
|
||||
for &memory in &self.memories {
|
||||
// SAFETY: nothing is bound to the imports any more and no command reads them (the
|
||||
// struct's docs).
|
||||
unsafe { release::object(raw_device, memory) };
|
||||
}
|
||||
(shared.counts).dma_buf_memories_freed(self.of_image, self.memories.len());
|
||||
drop(busy);
|
||||
if let Some(source) = self.source.take() {
|
||||
exit_guard::program(move || drop(source));
|
||||
exit_guard::program_release(move || drop(source));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DmaBufPages {
|
||||
/// The imports `source` made of the pages `request` asked for, none imported yet.
|
||||
fn new(device: &Device, source: DmaBufSource, request: DmaBufRequest) -> DmaBufPages {
|
||||
/// The imports `source` made of the pages `request` asked for, none imported yet: an image's
|
||||
/// dedicated one where `of_image`, else a buffer's chunks.
|
||||
fn new(
|
||||
device: &Device,
|
||||
source: DmaBufSource,
|
||||
request: DmaBufRequest,
|
||||
of_image: bool,
|
||||
) -> DmaBufPages {
|
||||
DmaBufPages {
|
||||
device: device.clone(),
|
||||
memories: Vec::new(),
|
||||
source: Some(source),
|
||||
of_image,
|
||||
source: Some(ProgramObject::new(source)),
|
||||
start: request.start.as_ptr() as u64,
|
||||
length: request.length,
|
||||
bound: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Hold `memory`, imported from one of the source's dma-bufs, until the pages go; counted
|
||||
/// live.
|
||||
fn hold(&mut self, memory: vk::DeviceMemory) {
|
||||
self.memories.push(memory);
|
||||
(self.device.shared().counts).dma_buf_memory_imported(self.of_image);
|
||||
}
|
||||
|
||||
/// Wait until the sparse binding of the buffer over the imports completed, where it may not
|
||||
/// have: before the buffer is destroyed (`buffer.rs`'s `HostImport`, or a buffer not made
|
||||
/// after all). A submission that used the buffer waited for it, so this waits only for a
|
||||
@@ -351,8 +373,10 @@ impl Device {
|
||||
/// bound in the imports of the chunks `source` makes of `window`'s pages, as memory of
|
||||
/// `class`, for `call`: the buffer and its placement, which keeps the imports and the source.
|
||||
/// The source is asked once the device is known to import dma-bufs for such a buffer, with
|
||||
/// no lock of the runtime's held, and never again here. Refused, everything made released,
|
||||
/// as the module says.
|
||||
/// no lock of the runtime's held, and never again here. Where `keep`, a descriptor of each
|
||||
/// dma-buf is kept too, which imports them again once the device released the import while
|
||||
/// idle (`host_residency.rs`): `None` where the host gives no descriptor more, or the device
|
||||
/// keeps as many as it may. Refused, everything made released, as the module says.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
@@ -368,7 +392,8 @@ impl Device {
|
||||
window: &ImportWindow,
|
||||
source: DmaBufSource,
|
||||
class: MemoryClass,
|
||||
) -> Result<(HostBuffer, Placement), Error> {
|
||||
keep: bool,
|
||||
) -> Result<(HostBuffer, Placement, Option<Again>), Error> {
|
||||
if !self.imports_dma_buf_buffers(vk::BufferCreateFlags::empty()) {
|
||||
return Err(not_importable());
|
||||
}
|
||||
@@ -388,7 +413,17 @@ impl Device {
|
||||
if !answers(&chunks, &request, importer.page) {
|
||||
return Err(invalid(call, Problem::DmaBuf));
|
||||
}
|
||||
let mut pages = DmaBufPages::new(self, source, request);
|
||||
// Duplicates of the descriptors, kept where the device may release the import: the
|
||||
// import takes the originals.
|
||||
let kept: Option<Vec<(OwnedFd, u64)>> = keep
|
||||
.then(|| {
|
||||
(chunks.iter())
|
||||
.map(|chunk| Some((chunk.fd.try_clone().ok()?, chunk.length)))
|
||||
.collect()
|
||||
})
|
||||
.flatten();
|
||||
let kept_source = kept.as_ref().map(|_| Arc::clone(&source));
|
||||
let mut pages = DmaBufPages::new(self, source, request, false);
|
||||
// SAFETY: the caller's.
|
||||
let (buffer, memory, type_index) =
|
||||
unsafe { self.chunks_buffer(importer, chunks, &mut pages, length, window, class) }?;
|
||||
@@ -398,7 +433,66 @@ impl Device {
|
||||
counts.dma_buf_sparse_buffer_made();
|
||||
}
|
||||
let placement = Placement::dma_buf(Arc::new(pages), memory, type_index, window.size, start);
|
||||
Ok((buffer, placement))
|
||||
let again = kept.zip(kept_source).and_then(|(chunks, source)| {
|
||||
Again::new(self, chunks, source, request, (length, *window, class))
|
||||
});
|
||||
Ok((buffer, placement, again))
|
||||
}
|
||||
|
||||
/// The pages of a released import made again from the dma-bufs `again` kept
|
||||
/// (`host_residency.rs`): a new `VkBuffer` made and bound as the first was, over imports of
|
||||
/// the same dma-bufs, so over the pages they hold whatever the address maps now, at the same
|
||||
/// offsets in the same memory type. Never calls the source. Refused (out of device memory, or
|
||||
/// the device lost) where the device cannot import them again, or lays them otherwise.
|
||||
pub(super) fn import_again(&self, again: &Again) -> Result<Pages, Error> {
|
||||
if self.is_lost() {
|
||||
return Err(Error::DeviceLost);
|
||||
}
|
||||
let refused = |_| Error::OutOfMemory(MemoryKind::Device);
|
||||
let shared = self.shared();
|
||||
let importer = shared
|
||||
.host_import
|
||||
.as_ref()
|
||||
.map_err(|_| internal("a dma-buf import made again on a device that imports none"))?;
|
||||
let chunks = (again.chunks.iter())
|
||||
.map(|(fd, length)| {
|
||||
let fd = fd
|
||||
.try_clone()
|
||||
.map_err(|_| Error::OutOfMemory(MemoryKind::Host))?;
|
||||
Ok(DmaBufChunk {
|
||||
fd,
|
||||
length: *length,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, Error>>()?;
|
||||
let mut pages = DmaBufPages::new(self, Arc::clone(&again.source), again.request, false);
|
||||
let window = &again.window;
|
||||
// SAFETY: the dma-bufs are those the first import took, which hold the pages it was
|
||||
// made over for as long as they are open (the import holds them).
|
||||
let (buffer, memory, type_index) = unsafe {
|
||||
self.chunks_buffer(
|
||||
importer,
|
||||
chunks,
|
||||
&mut pages,
|
||||
again.length,
|
||||
window,
|
||||
again.class,
|
||||
)
|
||||
}
|
||||
.map_err(|error| match error {
|
||||
Error::DeviceLost => Error::DeviceLost,
|
||||
other => refused(other),
|
||||
})?;
|
||||
let start = again.request.start;
|
||||
let placement = Placement::dma_buf(Arc::new(pages), memory, type_index, window.size, start);
|
||||
let made = self.pages_of(
|
||||
buffer.raw,
|
||||
placement,
|
||||
window.offset,
|
||||
buffer.base,
|
||||
buffer.size - buffer.base,
|
||||
);
|
||||
Ok(made)
|
||||
}
|
||||
|
||||
/// The `VkBuffer` of a no-copy buffer of `length` bytes over `window`'s pages from their
|
||||
@@ -533,7 +627,7 @@ impl Device {
|
||||
ImportFailure::NoMemoryType => not_importable(),
|
||||
ImportFailure::Vulkan(error) => import_refused(error),
|
||||
})?;
|
||||
pages.memories.push(memory);
|
||||
pages.hold(memory);
|
||||
imported.push((memory, type_index));
|
||||
}
|
||||
Ok(imported)
|
||||
@@ -836,8 +930,10 @@ impl Device {
|
||||
unsafe { release::object(raw_device, raw) };
|
||||
Ok(Err(why))
|
||||
};
|
||||
let (Ok(importer), Some(source)) = (shared.host_import.as_ref(), &texels.pages.source)
|
||||
else {
|
||||
let (Ok(importer), Some(source)) = (
|
||||
shared.host_import.as_ref(),
|
||||
texels.pages.source.as_ref().map(ProgramObject::get),
|
||||
) else {
|
||||
return refuse("the pages keep no source of dma-bufs".to_owned());
|
||||
};
|
||||
// The source is the program's code, called with no lock of the runtime's held.
|
||||
@@ -897,8 +993,8 @@ impl Device {
|
||||
return refuse(format!("the driver refuses to bind the import ({error:?})"));
|
||||
}
|
||||
shared.counts.dma_buf_image_made();
|
||||
let mut import = DmaBufPages::new(self, Arc::clone(source), request);
|
||||
import.memories.push(memory);
|
||||
let mut import = DmaBufPages::new(self, Arc::clone(source), request, true);
|
||||
import.hold(memory);
|
||||
Ok(Ok(DmaBufImage {
|
||||
raw,
|
||||
import: Arc::new(import),
|
||||
|
||||
@@ -68,6 +68,7 @@ use super::encoder::EncoderCore;
|
||||
use super::error::Error;
|
||||
use super::resource::ResourceKey;
|
||||
use super::tracker::{Barrier, Use};
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::device::{EnableSet, VkExtension, VkFeature};
|
||||
use std::ffi::CStr;
|
||||
@@ -490,7 +491,7 @@ impl CopySteps {
|
||||
///
|
||||
/// `command_buffer` is the encoder's, recording outside a render pass, and only the encoder
|
||||
/// records it.
|
||||
pub(super) unsafe fn record_in(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer) {
|
||||
pub(super) unsafe fn record_in(&self, raw: &Vk, command_buffer: vk::CommandBuffer) {
|
||||
// SAFETY: as the caller states.
|
||||
unsafe {
|
||||
Barrier::everything().record(raw, command_buffer);
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
//! and `deviceID`. A device's defects are in its properties
|
||||
//! ([`DeviceProperties::driver_defects`](super::DeviceProperties::driver_defects)), and what a
|
||||
//! defect breaks is taken another way where an exact one exists, else refused there, typed
|
||||
//! ([`Needs::RuntimeDriverDefect`]), never run wrong.
|
||||
//! ([`Needs::RuntimeDriverDefect`]), never run wrong unannounced: only where a refusal would
|
||||
//! withhold a feature of the families the device claims (a row of the feature table,
|
||||
//! `families/features.rs`) does it run, announced as a degradation.
|
||||
//!
|
||||
//! Each defect lists the drivers that have it and, for each, the measured identities a probe found
|
||||
//! clean: a GPU (`deviceID`) at one release, which the device layer measured
|
||||
@@ -208,6 +210,29 @@ pub(super) struct Affected {
|
||||
/// bits; gem10): known broken through 26.2.4; 26.0.8 unprobed. Nothing is refused: no such
|
||||
/// image of a height that is no multiple of 4 is made there (`dma_buf.rs`'s
|
||||
/// `explicit_plane_rows`), and the texture takes its shadow.
|
||||
///
|
||||
/// `OcclusionCountPerColorOutput`:
|
||||
/// - Mesa's ANV (`INTEL_OPEN_SOURCE_MESA`): a precise occlusion query counts each passing sample
|
||||
/// once per color output the fragment shader writes, where Vulkan's Sample Counting counts it
|
||||
/// once; write masks of 0, the query's command buffer and linked pipelines do not change it, and
|
||||
/// an imprecise query reads nonzero. Measured on 26.2.4 (driverVersion 0x6802004) on the Iris
|
||||
/// Xe (`deviceID` 0xa7a0; `runtime_lane::color_groups`): known broken through 26.2.4. Nothing
|
||||
/// is refused, since a refusal would withhold the Mac2 and Metal3 families: the draw runs,
|
||||
/// announced (`Degradation::VisibilityCountPerColor`).
|
||||
///
|
||||
/// `FreedAddressMemoryFailsPendingWork`:
|
||||
/// - MoltenVK (`MOLTENVK`): every encoder whose pipeline reads device addresses makes every buffer
|
||||
/// of `SHADER_DEVICE_ADDRESS` usage resident (`MVKDevice::encodeGPUAddressableBuffers`), in
|
||||
/// Metal command buffers that retain none of it (`retainedReferences` off where the device keeps
|
||||
/// its residency set), and `vkFreeMemory` lets go of the memory's Metal objects at once: a
|
||||
/// Metal command buffer encoded before and not yet run fails `Invalid Resource` (Metal's code
|
||||
/// 9), its device then lost. Destroying the buffer alone, its memory kept, fails nothing.
|
||||
/// Read in 1.4.1's source, and measured on 1.4.1 (driverVersion 10401) on an M3 Max with macOS
|
||||
/// 27.0.1: a bare-Vulkan program freeing an unused buffer's memory while a dispatch through a
|
||||
/// device address waits behind fills fails at once, and `runtime_lane::freed_memory`: known
|
||||
/// broken through 1.4.1. Nothing is refused: the runtime frees such memory once the batches
|
||||
/// submitted before it completed (`freed_memory.rs`). The program's own submissions through
|
||||
/// `CommandQueue::with_vk_queue` signal no timeline of the runtime's, so its frees wait for none.
|
||||
pub(super) const AFFECTED: &[Affected] = &[
|
||||
Affected {
|
||||
defect: RuntimeDriverDefect::MultisampledDepthStencilColourCopies,
|
||||
@@ -270,12 +295,22 @@ pub(super) const AFFECTED: &[Affected] = &[
|
||||
driver: DriverId::MESA_LLVMPIPE,
|
||||
clean: &[],
|
||||
},
|
||||
Affected {
|
||||
defect: RuntimeDriverDefect::OcclusionCountPerColorOutput,
|
||||
driver: DriverId::INTEL_OPEN_SOURCE_MESA,
|
||||
clean: &[],
|
||||
},
|
||||
Affected {
|
||||
defect: RuntimeDriverDefect::ImplicitPreprocessAfterExecutionSet,
|
||||
driver: DriverId::MESA_RADV,
|
||||
// The Radeon 780M at 26.2.4, measured clean.
|
||||
clean: &[(0x15bf, (26 << 22) | (2 << 12) | 4)],
|
||||
},
|
||||
Affected {
|
||||
defect: RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork,
|
||||
driver: DriverId::MOLTENVK,
|
||||
clean: &[],
|
||||
},
|
||||
];
|
||||
|
||||
/// The defects of the driver and device `description` names.
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
//! message from its sink ([`expecting`], [`withholds`]) and counts it
|
||||
//! (`WorkCounts::driver_diagnostics_withheld`).
|
||||
|
||||
use crate::{DebugMessage, MessageKind, MessageSeverity};
|
||||
use crate::{DebugMessage, MessageKind, MessageSeverity, MessageSink};
|
||||
use metal2vulkan::device::DriverDiagnostic;
|
||||
|
||||
impl super::Device {
|
||||
@@ -41,10 +41,15 @@ impl super::Device {
|
||||
/// Hand the informational message `text`, id name `id_name`, to the device's sink, else to
|
||||
/// stderr: what the runtime says that degrades nothing (the pipeline creation log).
|
||||
pub(crate) fn inform(&self, id_name: &str, text: String) {
|
||||
match self.shared().instance.sink() {
|
||||
Some(sink) => sink.deliver(&informational(id_name, text)),
|
||||
None => eprintln!("{text}"),
|
||||
}
|
||||
inform_through(self.shared().instance.sink(), id_name, text);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Device::inform`] through `sink`, else on stderr, where the device is ending.
|
||||
pub(crate) fn inform_through(sink: Option<&MessageSink>, id_name: &str, text: String) {
|
||||
match sink {
|
||||
Some(sink) => sink.deliver(&informational(id_name, text)),
|
||||
None => eprintln!("{text}"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! pipeline on a device without the commands is an internal error, never a guess.
|
||||
|
||||
use ash::vk;
|
||||
use metal2vulkan::device::{EnableSet, VkExtension};
|
||||
use metal2vulkan::device::{EnableSet, VkExtension, VkFeature};
|
||||
use metal2vulkan::vk::ApiVersion;
|
||||
|
||||
/// The extended dynamic state commands a device has.
|
||||
@@ -90,3 +90,44 @@ impl ExtendedDynamicState {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `VK_EXT_extended_dynamic_state3`'s `vkCmdSetColorWriteMaskEXT`, which a draw that reads a
|
||||
/// texture its pass renders through a snapshot records twice (`render/snapshot.rs`): loaded only
|
||||
/// where the device enabled everything that path takes, `attachmentFeedbackLoopLayout`,
|
||||
/// `extendedDynamicState3ColorWriteMask` and `fragmentShaderPixelInterlock`, so its presence is
|
||||
/// the device's answer to whether a draw may take it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct ColorWriteMasks(pub(super) vk::PFN_vkCmdSetColorWriteMaskEXT);
|
||||
|
||||
impl ColorWriteMasks {
|
||||
/// The command of a device with `enabled` enabled, where it enabled the three features.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `device` was made from `instance` with `enabled` enabled, and the loader serves
|
||||
/// `vkGetDeviceProcAddr` for it (its loader word is in place).
|
||||
pub(super) unsafe fn load(
|
||||
instance: &ash::Instance,
|
||||
device: &ash::Device,
|
||||
enabled: &EnableSet,
|
||||
) -> Option<ColorWriteMasks> {
|
||||
let needed = [
|
||||
VkFeature::AttachmentFeedbackLoopLayout,
|
||||
VkFeature::ExtendedDynamicState3ColorWriteMask,
|
||||
VkFeature::FragmentShaderPixelInterlock,
|
||||
];
|
||||
if !needed.iter().all(|f| enabled.features.contains(f)) {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the caller's; a command the device does not have is null.
|
||||
let command = unsafe {
|
||||
instance.get_device_proc_addr(device.handle(), c"vkCmdSetColorWriteMaskEXT".as_ptr())
|
||||
}?;
|
||||
// SAFETY: the device gave the command of this name, whose signature this is.
|
||||
Some(ColorWriteMasks(unsafe {
|
||||
std::mem::transmute::<unsafe extern "system" fn(), vk::PFN_vkCmdSetColorWriteMaskEXT>(
|
||||
command,
|
||||
)
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -376,6 +376,10 @@ pub(super) enum Structure {
|
||||
ExtendedDynamicState,
|
||||
/// `VkPhysicalDeviceExtendedDynamicState2FeaturesEXT`.
|
||||
ExtendedDynamicState2,
|
||||
/// `VkPhysicalDeviceExtendedDynamicState3FeaturesEXT`.
|
||||
ExtendedDynamicState3,
|
||||
/// `VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT`.
|
||||
FeedbackLoop,
|
||||
Robustness2,
|
||||
ImageRobustness,
|
||||
PortabilitySubset,
|
||||
@@ -463,6 +467,8 @@ impl Structure {
|
||||
| Structure::RayQuery
|
||||
| Structure::Acceleration
|
||||
| Structure::MeshShader
|
||||
| Structure::ExtendedDynamicState3
|
||||
| Structure::FeedbackLoop
|
||||
| Structure::Robustness2
|
||||
| Structure::PortabilitySubset
|
||||
| Structure::GeneratedCommands
|
||||
@@ -515,6 +521,8 @@ impl Structure {
|
||||
Structure::MeshShader => &[X::ExtMeshShader],
|
||||
Structure::ExtendedDynamicState => &[X::ExtExtendedDynamicState],
|
||||
Structure::ExtendedDynamicState2 => &[X::ExtExtendedDynamicState2],
|
||||
Structure::ExtendedDynamicState3 => &[X::ExtExtendedDynamicState3],
|
||||
Structure::FeedbackLoop => &[X::ExtAttachmentFeedbackLoopLayout],
|
||||
Structure::Robustness2 => &[X::ExtRobustness2],
|
||||
Structure::ImageRobustness => &[X::ExtImageRobustness],
|
||||
Structure::PortabilitySubset => &[X::KhrPortabilitySubset],
|
||||
@@ -573,6 +581,8 @@ struct FeatureChain {
|
||||
mesh_shader: vk::PhysicalDeviceMeshShaderFeaturesEXT<'static>,
|
||||
extended_dynamic_state: vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT<'static>,
|
||||
extended_dynamic_state2: vk::PhysicalDeviceExtendedDynamicState2FeaturesEXT<'static>,
|
||||
extended_dynamic_state3: vk::PhysicalDeviceExtendedDynamicState3FeaturesEXT<'static>,
|
||||
feedback_loop: vk::PhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT<'static>,
|
||||
robustness2: vk::PhysicalDeviceRobustness2FeaturesEXT<'static>,
|
||||
image_robustness: vk::PhysicalDeviceImageRobustnessFeatures<'static>,
|
||||
portability_subset: vk::PhysicalDevicePortabilitySubsetFeaturesKHR<'static>,
|
||||
@@ -648,12 +658,14 @@ members! {
|
||||
Core.core.multi_viewport => MultiViewport;
|
||||
Core.core.occlusion_query_precise => OcclusionQueryPrecise;
|
||||
Core.core.full_draw_index_uint32 => FullDrawIndexUint32;
|
||||
Core.core.shader_tessellation_and_geometry_point_size => ShaderTessellationAndGeometryPointSize;
|
||||
V11.v11.storage_buffer16_bit_access => StorageBuffer16BitAccess;
|
||||
V11.v11.uniform_and_storage_buffer16_bit_access => UniformAndStorageBuffer16BitAccess;
|
||||
V11.v11.storage_push_constant16 => StoragePushConstant16;
|
||||
V11.v11.storage_input_output16 => StorageInputOutput16;
|
||||
V11.v11.multiview => Multiview;
|
||||
V11.v11.multiview_tessellation_shader => MultiviewTessellationShader;
|
||||
V11.v11.multiview_geometry_shader => MultiviewGeometryShader;
|
||||
V11.v11.shader_draw_parameters => ShaderDrawParameters;
|
||||
V12.v12.sampler_mirror_clamp_to_edge => SamplerMirrorClampToEdge;
|
||||
V12.v12.storage_buffer8_bit_access => StorageBuffer8BitAccess;
|
||||
@@ -756,6 +768,8 @@ members! {
|
||||
MeshShader.mesh_shader.mesh_shader => MeshShader;
|
||||
ExtendedDynamicState.extended_dynamic_state.extended_dynamic_state => ExtendedDynamicState;
|
||||
ExtendedDynamicState2.extended_dynamic_state2.extended_dynamic_state2 => ExtendedDynamicState2;
|
||||
ExtendedDynamicState3.extended_dynamic_state3.extended_dynamic_state3_color_write_mask => ExtendedDynamicState3ColorWriteMask;
|
||||
FeedbackLoop.feedback_loop.attachment_feedback_loop_layout => AttachmentFeedbackLoopLayout;
|
||||
Robustness2.robustness2.robust_buffer_access2 => RobustBufferAccess2;
|
||||
Robustness2.robustness2.robust_image_access2 => RobustImageAccess2;
|
||||
Robustness2.robustness2.null_descriptor => NullDescriptor;
|
||||
@@ -895,6 +909,14 @@ const EXTENSIONS: &[(VkExtension, &CStr)] = {
|
||||
X::ExtExtendedDynamicState2,
|
||||
c"VK_EXT_extended_dynamic_state2",
|
||||
),
|
||||
(
|
||||
X::ExtExtendedDynamicState3,
|
||||
c"VK_EXT_extended_dynamic_state3",
|
||||
),
|
||||
(
|
||||
X::ExtAttachmentFeedbackLoopLayout,
|
||||
c"VK_EXT_attachment_feedback_loop_layout",
|
||||
),
|
||||
(X::KhrPushDescriptor, c"VK_KHR_push_descriptor"),
|
||||
(
|
||||
X::ExtTextureCompressionAstcHdr,
|
||||
@@ -1065,6 +1087,8 @@ macro_rules! link_extensions {
|
||||
MeshShader => mesh_shader,
|
||||
ExtendedDynamicState => extended_dynamic_state,
|
||||
ExtendedDynamicState2 => extended_dynamic_state2,
|
||||
ExtendedDynamicState3 => extended_dynamic_state3,
|
||||
FeedbackLoop => feedback_loop,
|
||||
Robustness2 => robustness2,
|
||||
ImageRobustness => image_robustness,
|
||||
PortabilitySubset => portability_subset,
|
||||
@@ -1280,6 +1304,11 @@ impl Enables {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The names of the extensions it enables.
|
||||
pub(super) fn names(&self) -> impl Iterator<Item = &CStr> {
|
||||
self.names.iter().map(CString::as_c_str)
|
||||
}
|
||||
|
||||
fn push_name(&mut self, name: CString) {
|
||||
if !self.names.contains(&name) {
|
||||
self.names.push(name);
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
//! - Encoders are `Send` but not `Sync`: every method takes `&mut self`, and the core holds a
|
||||
//! `!Sync` marker so no encoder is shared between threads by reference.
|
||||
|
||||
use super::buffer::Buffer;
|
||||
use super::command_buffer::CommandBuffer;
|
||||
use super::deferred::{Deferred, StepInputs};
|
||||
use super::error::{internal, invalid, vulkan, CommandBufferError, Error, Problem};
|
||||
@@ -39,12 +40,13 @@ use super::replay::Replay;
|
||||
use super::residency::Residency;
|
||||
use super::resource::ResourceKey;
|
||||
use super::retained::Retained;
|
||||
use super::shadow::{ShadowCopy, ShadowSync, ShadowUse, Step};
|
||||
use super::shadow::{ShadowCopy, ShadowSync, ShadowUse, Step, Within};
|
||||
use super::shadow_merge::ShadowMerge;
|
||||
use super::sparse::encoder::SparseUpdate;
|
||||
use super::tracker::{Barrier, EncoderUses, Summary, Use, UseRange};
|
||||
use super::used_resources::EncoderKind;
|
||||
use super::Device;
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::bind::{ReplayFaults, ResidentRange};
|
||||
use std::any::Any;
|
||||
@@ -139,9 +141,12 @@ impl Segment {
|
||||
/// ([`EncoderCore::continuation`]).
|
||||
pub(super) struct Continuation(vk::CommandBuffer);
|
||||
|
||||
/// A segment recorded: its `VkCommandBuffer`, ended, and what it used and ran.
|
||||
/// A segment recorded: its `VkCommandBuffer`s, ended, in order, and what it used and ran. One,
|
||||
/// but for a render pass that executes render commands whose first instance recorded inline
|
||||
/// (`render/executions.rs`): what the pass records before itself, the first instance's own, then
|
||||
/// the rest ([`cut_before`](EncoderCore::cut_before)).
|
||||
pub(super) struct RecordedSegment {
|
||||
pub(super) raw: vk::CommandBuffer,
|
||||
pub(super) raws: Vec<vk::CommandBuffer>,
|
||||
pub(super) summary: Summary<ResourceKey>,
|
||||
pub(super) retained: Retained,
|
||||
pub(super) executions: Vec<Execution>,
|
||||
@@ -160,7 +165,18 @@ pub(super) struct RecordedSegment {
|
||||
/// The state every open encoder carries.
|
||||
pub(super) struct EncoderCore {
|
||||
open: OpenGuard,
|
||||
/// The `VkCommandBuffer` its commands record into; null while a pass holds the one before
|
||||
/// (`pass`) and no command came since, which begins another ([`recording`](Self::recording)).
|
||||
raw: vk::CommandBuffer,
|
||||
/// Something recorded into `raw` that a command recorded before a pass must follow: any
|
||||
/// command of the encoder's, not the first encoder's start (`gpu_time.rs`), which a pass may
|
||||
/// hold the command buffer of ([`hold_pass`](Self::hold_pass)).
|
||||
recorded: bool,
|
||||
/// The `VkCommandBuffer` a render pass instance records its draws inline in, from the pass's
|
||||
/// first draw to its end (`render.rs`, [`hold_pass`](Self::hold_pass)): the encoder's
|
||||
/// commands meanwhile record into `raw`, which goes before it in submission order, as they go
|
||||
/// before a pass recorded at its end.
|
||||
pass: Option<vk::CommandBuffer>,
|
||||
/// The encoder's `VkCommandBuffer`s ended before a segment, in order.
|
||||
ended: Vec<vk::CommandBuffer>,
|
||||
/// The segments it left for commit, `executions_at` counting its own executions.
|
||||
@@ -257,7 +273,9 @@ impl EncoderCore {
|
||||
.device()
|
||||
.shared()
|
||||
.counts
|
||||
.command_buffer_begun();
|
||||
.encoder_command_buffer_begun();
|
||||
// The first encoder of a timed command buffer writes its start first (`gpu_time.rs`).
|
||||
command_buffer.open_start(&mut state, raw);
|
||||
state.encoder_open = true;
|
||||
drop(state);
|
||||
command_buffer
|
||||
@@ -271,6 +289,8 @@ impl EncoderCore {
|
||||
ended: false,
|
||||
},
|
||||
raw,
|
||||
recorded: false,
|
||||
pass: None,
|
||||
ended: Vec::new(),
|
||||
segments: Vec::new(),
|
||||
uses: EncoderUses::new(ordered),
|
||||
@@ -297,9 +317,10 @@ impl EncoderCore {
|
||||
command_buffer: &CommandBuffer,
|
||||
ordered: bool,
|
||||
) -> Result<EncoderCore, Error> {
|
||||
let core = EncoderCore::segment_raw(command_buffer, ordered)?;
|
||||
let mut core = EncoderCore::segment_raw(command_buffer, ordered)?;
|
||||
// SAFETY: the command buffer is recording, and only this core records it.
|
||||
unsafe { Barrier::everything().record(core.device().shared().vk(), core.raw) };
|
||||
core.recorded = true;
|
||||
Ok(core)
|
||||
}
|
||||
|
||||
@@ -333,13 +354,15 @@ impl EncoderCore {
|
||||
.device()
|
||||
.shared()
|
||||
.counts
|
||||
.command_buffer_begun();
|
||||
.encoder_command_buffer_begun();
|
||||
Ok(EncoderCore {
|
||||
open: OpenGuard {
|
||||
command_buffer: command_buffer.clone(),
|
||||
ended: true,
|
||||
},
|
||||
raw,
|
||||
recorded: false,
|
||||
pass: None,
|
||||
ended: Vec::new(),
|
||||
segments: Vec::new(),
|
||||
uses: EncoderUses::new(ordered),
|
||||
@@ -363,6 +386,12 @@ impl EncoderCore {
|
||||
self.open.command_buffer.device()
|
||||
}
|
||||
|
||||
/// The queue flags of the family its command buffer records for: its queue's `VkQueue`'s.
|
||||
pub(super) fn queue_flags(&self) -> vk::QueueFlags {
|
||||
let queue = self.open.command_buffer.command_queue().vk_queue();
|
||||
self.device().shared().queue_flags_of(queue)
|
||||
}
|
||||
|
||||
/// The core's own number, which no other core of the process has: what an argument table
|
||||
/// retained into it holds until it changes (`ArgumentTable::retain`).
|
||||
pub(super) fn id(&self) -> u64 {
|
||||
@@ -400,6 +429,22 @@ impl EncoderCore {
|
||||
self.retained.shared(object);
|
||||
}
|
||||
|
||||
/// `buffer`'s `VkBuffer`, and where its byte `offset` lies in it, for a blit's command
|
||||
/// ([`Buffer::blit_at`]): a no-copy buffer's import the device released while idle is
|
||||
/// imported again first, and what the command reads of it held until the command buffer
|
||||
/// completes (`host_residency.rs`). Refused where the device cannot import it again.
|
||||
pub(super) fn blit_at(
|
||||
&mut self,
|
||||
buffer: &Buffer,
|
||||
offset: u64,
|
||||
) -> Result<(vk::Buffer, u64), Error> {
|
||||
let (at, hold) = buffer.blit_at(offset)?;
|
||||
if let Some(hold) = hold {
|
||||
self.retain_shared(hold);
|
||||
}
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
/// Add a dispatch or draw the encoder took to the command buffer's execution record, as
|
||||
/// `execution` builds it. Only where the device keeps records
|
||||
/// ([`records_executions`](Self::records_executions)): elsewhere nothing is built.
|
||||
@@ -416,8 +461,122 @@ impl EncoderCore {
|
||||
|
||||
/// Record a barrier the program asked for (a compute encoder's memory barriers).
|
||||
pub(super) fn barrier(&mut self, barrier: Barrier) {
|
||||
let Some(raw) = self.recording() else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: the encoder's command buffer is recording, and only this encoder records it.
|
||||
unsafe { barrier.record(self.device().shared().vk(), self.raw) };
|
||||
unsafe { barrier.record(self.device().shared().vk(), raw) };
|
||||
}
|
||||
|
||||
/// The `VkCommandBuffer` the encoder's next command records into: `raw`, or where a pass
|
||||
/// holds the one before and no command came since, a new one of the command buffer's pool,
|
||||
/// begun, which goes before the pass's. `None` where none can be made, which abandons the
|
||||
/// command buffer (as a failure to end one does, [`defer`](Self::defer)).
|
||||
fn recording(&mut self) -> Option<vk::CommandBuffer> {
|
||||
if self.raw == vk::CommandBuffer::null() {
|
||||
match self.continuation() {
|
||||
Ok(next) => self.raw = next.0,
|
||||
Err(_) => {
|
||||
self.open.command_buffer.state().abandoned = true;
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.recorded = true;
|
||||
Some(self.raw)
|
||||
}
|
||||
|
||||
/// Hold a `VkCommandBuffer` for a render pass instance whose draws record inline in it from
|
||||
/// now to the pass's end (`render.rs`): the encoder's own where nothing recorded into it
|
||||
/// yet, else a new one of the pool, begun. Until [`release_pass`](Self::release_pass), the
|
||||
/// encoder's commands record into another, which goes before it in submission order: where
|
||||
/// they go before a pass recorded at its end. Refused where one is held, or none can be made.
|
||||
///
|
||||
/// The first encoder's own holds its command buffer's start, written first
|
||||
/// (`gpu_time.rs`): where a command then records before the pass, in a command buffer that
|
||||
/// goes before it, the batch's first command buffer is no longer the one that wrote it, and
|
||||
/// the batch reads the start its command buffer of barriers writes before everything instead
|
||||
/// (`command_buffer/submit.rs`, which compares the batch's first command buffer with the one
|
||||
/// that wrote the start).
|
||||
pub(super) fn hold_pass(&mut self) -> Result<vk::CommandBuffer, Error> {
|
||||
if self.pass.is_some() {
|
||||
return Err(internal("a render pass held twice"));
|
||||
}
|
||||
let held = match self.recorded {
|
||||
true => self.continuation()?.0,
|
||||
false => {
|
||||
let own = self.raw;
|
||||
self.raw = vk::CommandBuffer::null();
|
||||
own
|
||||
}
|
||||
};
|
||||
self.pass = Some(held);
|
||||
Ok(held)
|
||||
}
|
||||
|
||||
/// End the hold [`hold_pass`](Self::hold_pass) took: the render pass instance recorded in
|
||||
/// the held command buffer ends there, whatever the encoder's commands record from here on
|
||||
/// (a command that names a detached buffer records nothing, [`skips`](Self::skips)); the
|
||||
/// command buffer of the commands before the pass, where any recorded, ends and goes before
|
||||
/// it; and the encoder's commands record on into the pass's, after it. Refused only where
|
||||
/// that one does not end, which abandons the command buffer.
|
||||
pub(super) fn release_pass(&mut self) -> Result<(), Error> {
|
||||
let Some(pass) = self.pass.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
// SAFETY: the held command buffer is recording inside the render pass instance its pass
|
||||
// began, and only this encoder records it.
|
||||
unsafe { self.device().shared().vk().cmd_end_render_pass(pass) };
|
||||
if self.raw != vk::CommandBuffer::null() {
|
||||
// SAFETY: as in `barrier`.
|
||||
if let Err(error) = unsafe { self.open.command_buffer.end_raw(self.raw) } {
|
||||
self.open.command_buffer.state().abandoned = true;
|
||||
return Err(vulkan(error));
|
||||
}
|
||||
self.ended.push(self.raw);
|
||||
}
|
||||
self.raw = pass;
|
||||
self.recorded = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// After [`release_pass`](Self::release_pass), hand the pass's command buffer, where its first
|
||||
/// instance and what followed it recorded, over to the segment the pass records later in
|
||||
/// (`render/executions.rs`), ended: it goes between what the segment records before the pass
|
||||
/// and the pass's later instances ([`cut_before`](Self::cut_before)), so nothing the segment
|
||||
/// records before the pass at the commit runs after the first instance. The encoder's next
|
||||
/// command begins another command buffer. Refused only where it does not end, which abandons
|
||||
/// the command buffer.
|
||||
pub(super) fn hand_over_pass(&mut self) -> Result<vk::CommandBuffer, Error> {
|
||||
let pass = self.raw;
|
||||
if pass == vk::CommandBuffer::null() {
|
||||
return Err(internal(
|
||||
"a render pass handed over without its command buffer",
|
||||
));
|
||||
}
|
||||
// SAFETY: as in `barrier`.
|
||||
if let Err(error) = unsafe { self.open.command_buffer.end_raw(pass) } {
|
||||
self.open.command_buffer.state().abandoned = true;
|
||||
return Err(vulkan(error));
|
||||
}
|
||||
self.raw = vk::CommandBuffer::null();
|
||||
self.recorded = false;
|
||||
Ok(pass)
|
||||
}
|
||||
|
||||
/// In a [`segment`](Self::segment): place `before`, an ended command buffer handed over to it
|
||||
/// ([`hand_over_pass`](Self::hand_over_pass)), after what the segment recorded so far, between
|
||||
/// barriers from everything before and to everything after, and go on in a new command buffer.
|
||||
/// Refused where the current one does not end or the new one cannot be begun.
|
||||
pub(super) fn cut_before(&mut self, before: vk::CommandBuffer) -> Result<(), Error> {
|
||||
self.barrier(Barrier::everything());
|
||||
// SAFETY: as in `barrier`.
|
||||
unsafe { self.open.command_buffer.end_raw(self.raw) }.map_err(vulkan)?;
|
||||
self.ended.push(self.raw);
|
||||
self.ended.push(before);
|
||||
self.raw = self.continuation()?.0;
|
||||
self.barrier(Barrier::everything());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record one command that ran in `stages` with `uses`: the barrier the uses need after the
|
||||
@@ -427,7 +586,7 @@ impl EncoderCore {
|
||||
&mut self,
|
||||
stages: vk::PipelineStageFlags2,
|
||||
uses: &[Use<ResourceKey>],
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) {
|
||||
self.command_reaching(stages, uses, &BTreeSet::new(), record);
|
||||
}
|
||||
@@ -441,7 +600,7 @@ impl EncoderCore {
|
||||
stages: vk::PipelineStageFlags2,
|
||||
uses: &[Use<ResourceKey>],
|
||||
reads: &[FreshRead],
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) {
|
||||
self.command_observing(stages, uses, &BTreeSet::new(), reads, record);
|
||||
}
|
||||
@@ -454,7 +613,7 @@ impl EncoderCore {
|
||||
stages: vk::PipelineStageFlags2,
|
||||
uses: &[Use<ResourceKey>],
|
||||
resident: &BTreeSet<ResourceKey>,
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) {
|
||||
self.command_observing(stages, uses, resident, &[], record);
|
||||
}
|
||||
@@ -467,17 +626,20 @@ impl EncoderCore {
|
||||
uses: &[Use<ResourceKey>],
|
||||
resident: &BTreeSet<ResourceKey>,
|
||||
reads: &[FreshRead],
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
) {
|
||||
let Some(barrier) = self.track(stages, uses, resident, reads) else {
|
||||
return;
|
||||
};
|
||||
let Some(raw) = self.recording() else {
|
||||
return;
|
||||
};
|
||||
let device = self.open.command_buffer.device().shared().vk();
|
||||
if let Some(barrier) = barrier {
|
||||
// SAFETY: as in `barrier`.
|
||||
unsafe { barrier.record(device, self.raw) };
|
||||
unsafe { barrier.record(device, raw) };
|
||||
}
|
||||
record(device, self.raw);
|
||||
record(device, raw);
|
||||
}
|
||||
|
||||
/// [`command_reaching`](Self::command_reaching) of a command recorded later, into a segment
|
||||
@@ -603,6 +765,19 @@ impl EncoderCore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hold each buffer over host pages among `keys` from now on, as a command that names it
|
||||
/// does (`touch_keys`), without keeping the keys: the bytes a render pass's attachments lie
|
||||
/// in, which it holds from its open (`render.rs`). Free while the device has no buffer over
|
||||
/// host pages.
|
||||
pub(super) fn hold_bytes(&mut self, keys: impl IntoIterator<Item = ResourceKey>) {
|
||||
if !self.device().shared().rebinds.any() {
|
||||
return;
|
||||
}
|
||||
for key in keys {
|
||||
self.hold(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hold `key` where it names a buffer over host pages (`rebind.rs`).
|
||||
fn hold(&mut self, key: ResourceKey) {
|
||||
// Encoded again after the commit: nothing refuses a rebind for it.
|
||||
@@ -706,8 +881,7 @@ impl EncoderCore {
|
||||
let copies = self.shadows.before(shadows, uses, |copies| {
|
||||
ShadowMerge::new(&device, copies).map(Arc::new)
|
||||
})?;
|
||||
let texels = copies.iter().map(ShadowCopy::texels_back).sum();
|
||||
(device.shared().counts).shadow_copies_planned(copies.len(), texels);
|
||||
self.count_shadow_copies(&copies);
|
||||
for copy in &copies {
|
||||
if let Step::Keep(merge) = ©.step {
|
||||
self.retain(Arc::clone(merge));
|
||||
@@ -716,41 +890,130 @@ impl EncoderCore {
|
||||
Ok(copies)
|
||||
}
|
||||
|
||||
/// Note a recorded command that used the shadowed textures `shadows` and had `uses`.
|
||||
pub(super) fn shadows_used(&mut self, shadows: &[ShadowUse], uses: &[Use<ResourceKey>]) {
|
||||
/// Count shadowed textures' `copies` as planned (`WorkCounts::shadow_copies`), the texels
|
||||
/// their copies in and back of buffers' textures' images move, and those copies in of what
|
||||
/// changed within a rectangle alone (`WorkCounts::bounded_shadow_copies`).
|
||||
fn count_shadow_copies(&self, copies: &[ShadowCopy]) {
|
||||
let texels_in = copies.iter().map(ShadowCopy::texels_in).sum();
|
||||
let texels_back = copies.iter().map(ShadowCopy::texels_back).sum();
|
||||
let counts = &self.device().shared().counts;
|
||||
counts.shadow_copies_planned(copies.len(), texels_in, texels_back);
|
||||
let bounded = copies.iter().filter(|copy| copy.bounded).count();
|
||||
if bounded > 0 {
|
||||
counts.bounded_shadow_copies_planned(bounded);
|
||||
}
|
||||
}
|
||||
|
||||
/// Note a recorded command that used the shadowed textures `shadows` and had `uses`, and
|
||||
/// whose writes `within` change the bytes of a texture inside a rectangle of its texels alone
|
||||
/// (`shadow::Within`).
|
||||
pub(super) fn shadows_used(
|
||||
&mut self,
|
||||
shadows: &[ShadowUse],
|
||||
uses: &[Use<ResourceKey>],
|
||||
within: &[Within],
|
||||
) {
|
||||
let aliased = self.aliased(uses);
|
||||
let within: Vec<Within> = within
|
||||
.iter()
|
||||
.map(|part| Within {
|
||||
uses: self
|
||||
.aliased(&part.uses)
|
||||
.unwrap_or_else(|| part.uses.clone()),
|
||||
texels: part.texels.clone(),
|
||||
area: part.area,
|
||||
})
|
||||
.collect();
|
||||
self.shadows
|
||||
.after(shadows, aliased.as_deref().unwrap_or(uses));
|
||||
.after(shadows, aliased.as_deref().unwrap_or(uses), &within);
|
||||
}
|
||||
|
||||
/// Record shadowed textures' `copies` as commands of the encoder: ordered as any command
|
||||
/// is, in an encoder Metal orders; with a barrier from everything before and one to
|
||||
/// everything after each copy, in one whose commands Metal leaves unordered.
|
||||
/// everything after each copy, in one whose commands Metal leaves unordered. A copy back the
|
||||
/// device runs faster as a dispatch is that dispatch (`shadow_copy_back.rs`), which the
|
||||
/// command buffer retains until it completes.
|
||||
pub(super) fn shadow_copies(&mut self, copies: &[ShadowCopy]) {
|
||||
let device = self.device().clone();
|
||||
for copy in copies {
|
||||
let stages = copy.stages();
|
||||
let uses = copy.uses();
|
||||
// A shadow takes the view a dispatch reads on a device that dispatches alone.
|
||||
let dispatched = copy.dispatched(&device);
|
||||
let (stages, uses) = match &dispatched {
|
||||
Some(_) => (
|
||||
vk::PipelineStageFlags2::COMPUTE_SHADER,
|
||||
copy.dispatched_uses(),
|
||||
),
|
||||
None => (copy.stages(), copy.uses()),
|
||||
};
|
||||
let record = |device: &Vk, raw: vk::CommandBuffer| match &dispatched {
|
||||
// SAFETY: the encoder's command buffer is recording outside a render pass; its
|
||||
// commands retain the shadowed textures (and their views) and the dispatch until
|
||||
// it completes, and every image rests in the `GENERAL` layout.
|
||||
Some(back) => unsafe { back.record(device, raw) },
|
||||
// SAFETY: as above.
|
||||
None => unsafe { copy.record(device, raw) },
|
||||
};
|
||||
if self.uses.ordered() {
|
||||
self.command(stages, &uses, |device, raw| {
|
||||
// SAFETY: the encoder's command buffer is recording outside a render pass;
|
||||
// its commands retain the shadowed textures until it completes, and every
|
||||
// image rests in the `GENERAL` layout.
|
||||
unsafe { copy.record(device, raw) }
|
||||
});
|
||||
self.command(stages, &uses, record);
|
||||
} else {
|
||||
// A copy of a detached buffer's bytes records nothing, nor does what follows.
|
||||
if self.skips(uses.iter().map(|used| used.key)) {
|
||||
continue;
|
||||
}
|
||||
self.barrier(Barrier::everything());
|
||||
// SAFETY: as above.
|
||||
unsafe { copy.record(self.device().shared().vk(), self.raw) };
|
||||
let Some(raw) = self.recording() else {
|
||||
continue;
|
||||
};
|
||||
record(device.shared().vk(), raw);
|
||||
self.barrier(Barrier::everything());
|
||||
let aliased = self.aliased(&uses);
|
||||
self.uses
|
||||
.record(stages, aliased.as_deref().unwrap_or(&uses), None);
|
||||
self.touch(&uses);
|
||||
}
|
||||
if let Some(back) = dispatched {
|
||||
device.shared().counts.shadow_copy_back_dispatched();
|
||||
self.retain(back);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `VkCommandBuffer` a render pass holds ([`hold_pass`](Self::hold_pass)), until its
|
||||
/// release.
|
||||
pub(super) fn held_pass(&self) -> Option<vk::CommandBuffer> {
|
||||
self.pass
|
||||
}
|
||||
|
||||
/// Record shadowed textures' `copies` into the command buffer a render pass holds
|
||||
/// ([`hold_pass`](Self::hold_pass)), between two of its render pass instances, as the pass's
|
||||
/// end records them there (`render/inline_splits.rs`): each with a barrier from everything
|
||||
/// before and one to everything after, its uses the encoder's, an unordered one's. A copy of a
|
||||
/// detached buffer's bytes records nothing, nor does what follows ([`skips`](Self::skips)).
|
||||
/// Nothing where no pass holds one.
|
||||
pub(super) fn held_shadow_copies(&mut self, copies: &[ShadowCopy]) {
|
||||
let Some(held) = self.pass else {
|
||||
return;
|
||||
};
|
||||
let device = self.device().clone();
|
||||
let raw = device.shared().vk();
|
||||
for copy in copies {
|
||||
let uses = copy.uses();
|
||||
if self.skips(uses.iter().map(|used| used.key)) {
|
||||
continue;
|
||||
}
|
||||
// SAFETY: the held command buffer is recording outside a render pass instance (the
|
||||
// caller ended the one before), and only this encoder records it; its commands retain
|
||||
// the shadowed textures (and their views) until it completes, and every image rests
|
||||
// in the `GENERAL` layout.
|
||||
unsafe {
|
||||
Barrier::everything().record(raw, held);
|
||||
copy.record(raw, held);
|
||||
Barrier::everything().record(raw, held);
|
||||
}
|
||||
let aliased = self.aliased(&uses);
|
||||
self.uses
|
||||
.record(copy.stages(), aliased.as_deref().unwrap_or(&uses), None);
|
||||
self.touch(&uses);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -772,6 +1035,7 @@ impl EncoderCore {
|
||||
/// module's segments). Refused, changing nothing, when the new one cannot be made; a failure
|
||||
/// to end the current one abandons the command buffer.
|
||||
pub(super) fn defer(&mut self, work: Deferred) -> Result<(), Error> {
|
||||
self.release_pass()?;
|
||||
let next = self.continuation()?;
|
||||
self.defer_into(next, work)
|
||||
}
|
||||
@@ -796,7 +1060,7 @@ impl EncoderCore {
|
||||
.begin_command_buffer(next, &begin)
|
||||
}
|
||||
.map_err(vulkan)?;
|
||||
self.device().shared().counts.command_buffer_begun();
|
||||
self.device().shared().counts.encoder_command_buffer_begun();
|
||||
Ok(Continuation(next))
|
||||
}
|
||||
|
||||
@@ -807,13 +1071,18 @@ impl EncoderCore {
|
||||
let copies = self.shadows.leave();
|
||||
self.shadow_copies(&copies);
|
||||
}
|
||||
// SAFETY: as in `barrier`.
|
||||
if let Err(error) = unsafe { self.device().shared().vk().end_command_buffer(self.raw) } {
|
||||
self.open.command_buffer.state().abandoned = true;
|
||||
return Err(vulkan(error));
|
||||
// None where a pass handed its command buffer over to the work
|
||||
// ([`hand_over_pass`](Self::hand_over_pass)) and no command came since.
|
||||
if self.raw != vk::CommandBuffer::null() {
|
||||
// SAFETY: as in `barrier`.
|
||||
if let Err(error) = unsafe { self.open.command_buffer.end_raw(self.raw) } {
|
||||
self.open.command_buffer.state().abandoned = true;
|
||||
return Err(vulkan(error));
|
||||
}
|
||||
self.ended.push(self.raw);
|
||||
}
|
||||
self.ended.push(self.raw);
|
||||
self.raw = next.0;
|
||||
self.recorded = false;
|
||||
let host = work.gpu_written();
|
||||
if host {
|
||||
self.uses.split();
|
||||
@@ -870,19 +1139,25 @@ impl EncoderCore {
|
||||
residency: Option<Residency>,
|
||||
replay: Option<Replay>,
|
||||
) -> Result<(), Error> {
|
||||
let replay = replay.filter(|_| {
|
||||
self.segments.iter().all(Segment::pends)
|
||||
// A pass ended holds no command buffer (`render.rs`); this one ends here if one did.
|
||||
self.release_pass()?;
|
||||
// A log not kept goes back to the device's spares (`replay.rs`).
|
||||
let replay = replay.and_then(|log| {
|
||||
let keeps = self.segments.iter().all(Segment::pends)
|
||||
&& self.fails_command_buffer.is_none()
|
||||
&& !self.faults
|
||||
&& !self.taken.named_pins().is_empty()
|
||||
&& self.taken.names_a_pin();
|
||||
if !keeps {
|
||||
self.device().shared().scheduler.spare_logs().give(log);
|
||||
return None;
|
||||
}
|
||||
Some(log)
|
||||
});
|
||||
let copies = self.shadows.finish();
|
||||
let texels = copies.iter().map(ShadowCopy::texels_back).sum();
|
||||
let counts = &self.device().shared().counts;
|
||||
counts.shadow_copies_planned(copies.len(), texels);
|
||||
self.count_shadow_copies(&copies);
|
||||
self.shadow_copies(&copies);
|
||||
// SAFETY: as in `barrier`.
|
||||
unsafe { self.device().shared().vk().end_command_buffer(self.raw) }.map_err(vulkan)?;
|
||||
// Its last `VkCommandBuffer` stays recording, the command buffer's tail: its batch's end
|
||||
// may go into it (`CommandBufferShared::close_tail`).
|
||||
let EncoderCore {
|
||||
mut open,
|
||||
raw,
|
||||
@@ -952,21 +1227,28 @@ impl EncoderCore {
|
||||
if at > 0 {
|
||||
state.host_step();
|
||||
}
|
||||
state.end_encoder(Recorded {
|
||||
encoder,
|
||||
raws,
|
||||
segments,
|
||||
summary,
|
||||
sparse: Vec::new(),
|
||||
});
|
||||
state.end_encoder(
|
||||
&open.command_buffer,
|
||||
Recorded {
|
||||
encoder,
|
||||
raws,
|
||||
segments,
|
||||
summary,
|
||||
sparse: Vec::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
state.tail = Some(raw);
|
||||
state.retained.extend(retained.into_entry());
|
||||
state.executions.extend(executions);
|
||||
if !holds.is_empty() {
|
||||
state.holds.push(holds);
|
||||
}
|
||||
drop(state);
|
||||
drop(unkept);
|
||||
if let Some(log) = unkept {
|
||||
let device = open.command_buffer.device();
|
||||
device.shared().scheduler.spare_logs().give(log);
|
||||
}
|
||||
open.ended = true;
|
||||
Ok(())
|
||||
}
|
||||
@@ -978,12 +1260,10 @@ impl EncoderCore {
|
||||
/// buffer: its first encoding kept none of those, so its place stays as it was.
|
||||
pub(super) fn finish_replay(mut self) -> Result<Replayed, Error> {
|
||||
let copies = self.shadows.finish();
|
||||
let texels = copies.iter().map(ShadowCopy::texels_back).sum();
|
||||
let counts = &self.device().shared().counts;
|
||||
counts.shadow_copies_planned(copies.len(), texels);
|
||||
self.count_shadow_copies(&copies);
|
||||
self.shadow_copies(&copies);
|
||||
// SAFETY: as in `barrier`.
|
||||
unsafe { self.device().shared().vk().end_command_buffer(self.raw) }.map_err(vulkan)?;
|
||||
unsafe { self.open.command_buffer.end_raw(self.raw) }.map_err(vulkan)?;
|
||||
let EncoderCore {
|
||||
raw,
|
||||
mut ended,
|
||||
@@ -1028,14 +1308,14 @@ impl EncoderCore {
|
||||
/// so it uses nothing past its encoder's summary.
|
||||
pub(super) fn untracked_segment(
|
||||
command_buffer: &CommandBuffer,
|
||||
record: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
record: impl FnOnce(&Vk, vk::CommandBuffer),
|
||||
retained: Box<dyn Any + Send + Sync>,
|
||||
) -> Result<RecordedSegment, Error> {
|
||||
let mut core = EncoderCore::segment_raw(command_buffer, false)?;
|
||||
let device = core.device().shared().vk();
|
||||
record(device, core.raw);
|
||||
// SAFETY: as in `barrier`.
|
||||
unsafe { device.end_command_buffer(core.raw) }.map_err(vulkan)?;
|
||||
unsafe { core.open.command_buffer.end_raw(core.raw) }.map_err(vulkan)?;
|
||||
core.retained.boxed(retained);
|
||||
let EncoderCore {
|
||||
raw,
|
||||
@@ -1047,7 +1327,7 @@ impl EncoderCore {
|
||||
..
|
||||
} = core;
|
||||
Ok(RecordedSegment {
|
||||
raw,
|
||||
raws: vec![raw],
|
||||
summary: uses.finish(),
|
||||
retained,
|
||||
executions,
|
||||
@@ -1062,15 +1342,14 @@ impl EncoderCore {
|
||||
/// back are copied back, then a barrier to everything recorded after it.
|
||||
pub(super) fn end_segment(mut self) -> Result<RecordedSegment, Error> {
|
||||
let copies = self.shadows.finish();
|
||||
let texels = copies.iter().map(ShadowCopy::texels_back).sum();
|
||||
let counts = &self.device().shared().counts;
|
||||
counts.shadow_copies_planned(copies.len(), texels);
|
||||
self.count_shadow_copies(&copies);
|
||||
self.shadow_copies(&copies);
|
||||
self.barrier(Barrier::everything());
|
||||
// SAFETY: as in `barrier`.
|
||||
unsafe { self.device().shared().vk().end_command_buffer(self.raw) }.map_err(vulkan)?;
|
||||
unsafe { self.open.command_buffer.end_raw(self.raw) }.map_err(vulkan)?;
|
||||
let EncoderCore {
|
||||
raw,
|
||||
mut ended,
|
||||
uses,
|
||||
retained,
|
||||
executions,
|
||||
@@ -1078,8 +1357,9 @@ impl EncoderCore {
|
||||
taken,
|
||||
..
|
||||
} = self;
|
||||
ended.push(raw);
|
||||
Ok(RecordedSegment {
|
||||
raw,
|
||||
raws: ended,
|
||||
summary: uses.finish(),
|
||||
retained,
|
||||
executions,
|
||||
|
||||
@@ -1120,8 +1120,10 @@ pub enum RuntimeGap {
|
||||
/// The device's `max_buffer_length`.
|
||||
max_buffer_length: u64,
|
||||
},
|
||||
/// What indirect command buffers lack of their render commands: a descriptor of mesh draws,
|
||||
/// which the record format does not hold; an execution of a range a draw of the encoder before
|
||||
/// What indirect command buffers lack of their render commands: a command whose mesh draw's
|
||||
/// object function has threadgroup memory arguments, whose lengths (the command's
|
||||
/// `setObjectThreadgroupMemoryLength:atIndex:` or the encoder's) are not measured; an
|
||||
/// execution of a range a draw of the encoder before
|
||||
/// it may write, or of commands that need a render pass instance of their own (a fetched
|
||||
/// attachment, the shader-side stencil, views, a fragment imageblock, a texture whose shadow
|
||||
/// the pass does not hold, or a memoryless attachment the pass backs and reads past its
|
||||
@@ -1219,7 +1221,10 @@ pub enum RuntimeGap {
|
||||
/// multiview, or lacks `drawIndirectFirstInstance`, whose path is a prepass that writes what
|
||||
/// the draw needs. The runtime never reads arguments an earlier command may write. An index
|
||||
/// bounds pass whose arguments or indices a draw of the encoder wrote since its last memory
|
||||
/// barrier, which Metal does not order before the draw's fetch, is refused too.
|
||||
/// barrier, which Metal does not order before the draw's fetch, is refused too. So is an
|
||||
/// indirect patch draw whose post-tessellation function reads `[[base_instance]]` through the
|
||||
/// device's tessellation stages, which take it from push constants; on a device without
|
||||
/// `tessellationShader` the draw's tessellation scan reads it on the GPU, and none is refused.
|
||||
IndirectDrawArguments,
|
||||
/// A depth/stencil resolve no Vulkan resolve mode of the device states: a filter or pair of
|
||||
/// filters the device's `supportedDepthResolveModes`, `supportedStencilResolveModes` or
|
||||
@@ -1262,8 +1267,8 @@ pub enum RuntimeGap {
|
||||
/// A sparse texture's access counters (`getTextureAccessCounters:...` and
|
||||
/// `resetTextureAccessCounters:...` of a blit encoder). Not scheduled (orchestrator,
|
||||
/// 2026-10-06): Metal's counts are its texture hardware's units, not a count of accesses,
|
||||
/// nondeterministic for large dispatches and different on an M3 Max and an M4 (AMP sparse
|
||||
/// probe 1), so no exact answer exists, and Vulkan counts nothing of the kind.
|
||||
/// nondeterministic for large dispatches and different on an M3 Max and an M4 (a Metal sparse
|
||||
/// probe on both), so no exact answer exists, and Vulkan counts nothing of the kind.
|
||||
TextureAccessCounters,
|
||||
/// Fast resource loading: `MTLIOCommandQueue`, its command buffers and file handles. Not
|
||||
/// scheduled.
|
||||
@@ -1378,6 +1383,14 @@ pub enum RuntimeGap {
|
||||
/// barrier, which Metal does not order before the draw's fetch, read in place; and an
|
||||
/// argument or index range the binding layer cannot bind.
|
||||
RestartedStrip,
|
||||
/// An indexed draw (`drawIndexedPrimitives:`) of a pipeline whose fragment function reads
|
||||
/// `[[primitive_id]]` on a device whose fragment stage cannot declare it (neither
|
||||
/// `geometryShader` nor `tessellationShader`), which draws its indices as vertices from 0 in
|
||||
/// the de-indexed form, its vertex function reading the indices in place at their device
|
||||
/// address (`VariantKey::primitive_id_indices`): indices a draw of the encoder wrote since
|
||||
/// its last memory barrier, which Metal does not order before the draw's fetch and the draw
|
||||
/// would read as a copy, and indices without a device address.
|
||||
PrimitiveIdIndices,
|
||||
/// A rotated texture (`TextureDescriptor::rotation`) where the runtime does not build what
|
||||
/// Metal does: CPU access or a blit of a quarter-turned one whose rows, as those uses address
|
||||
/// them (the texture's `height` rows of `width` texels at the plane's `bytesPerRow`), run
|
||||
@@ -1490,6 +1503,21 @@ pub enum RuntimeGap {
|
||||
/// where previously the runtime recorded invalid Vulkan and some drivers hung instead of
|
||||
/// failing (the consumer's NVIDIA Xid 32 stall).
|
||||
MultisampledBufferCopy,
|
||||
/// What a render pass the device draws in color groups does not build: a pass of more color
|
||||
/// attachments with a texture than the lesser of the device's `maxColorAttachments` and
|
||||
/// `maxFragmentOutputAttachments` (four on a device at Vulkan's floor), or of one at an index
|
||||
/// at or past it, where Metal takes eight, draws each group's colors in a pass of its own
|
||||
/// (`render/color_groups.rs`). Refused there: a render pipeline state whose colors with a
|
||||
/// pixel format are not the pass's colors with a texture (or one the device draws in groups
|
||||
/// in a pass it draws in one), a tile pipeline's state, an execution of render commands in a
|
||||
/// pass of several groups, a depth or stencil the pass loads from a texture without the
|
||||
/// transfer usage its later groups' copy needs, and in a pass of several groups a draw that
|
||||
/// reads what another group writes (a color of another group, its own group's colors or the
|
||||
/// depth and stencil where it draws in a later group too, a resolve texture, the visibility
|
||||
/// result buffer, memory it reaches through a handle table, or a texture over a buffer's
|
||||
/// bytes it may reach through a root table), and a resolve target set on a texture a draw of
|
||||
/// the pass read.
|
||||
ColorAttachmentGroups,
|
||||
}
|
||||
|
||||
/// The kind of memory that ran out.
|
||||
@@ -1567,6 +1595,12 @@ pub enum CommandBufferError {
|
||||
/// runtime's pool is the device's budget, so nothing is drawn short silently. The first such
|
||||
/// draw, as its scan saw it.
|
||||
MeshRecordsOverflow(MeshRecordsOverflow),
|
||||
/// An emulated tessellation draw's records (an indirect patch draw's, on a device without
|
||||
/// `tessellationShader`) did not fit the rest of the command buffer's records pool, the one
|
||||
/// emulated mesh draws share: such draws drew nothing. Metal draws them; the runtime's pool is
|
||||
/// the device's budget, so nothing is drawn short silently. The first records fault of the
|
||||
/// command buffer, where it is a tessellation draw's, as its scan saw it.
|
||||
TessellationRecordsOverflow(TessellationRecordsOverflow),
|
||||
/// A host step refused a command it recorded from an indirect command buffer's records
|
||||
/// (`Degradation::HostReplayedIndirectCommands`): what `commit` refuses where the CPU wrote
|
||||
/// the records, such as a command's pipeline state of other color formats than the pass's.
|
||||
@@ -1792,7 +1826,7 @@ pub enum FailedState {
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct MeshRecordsOverflow {
|
||||
/// The draw's order among the command buffer's emulated mesh draws, from 0.
|
||||
/// The draw's order among the command buffer's emulated mesh and tessellation draws, from 0.
|
||||
pub draw: u32,
|
||||
/// Its object threadgroups (1 for a pipeline without an object function).
|
||||
pub object_threadgroups: u32,
|
||||
@@ -1802,15 +1836,28 @@ pub struct MeshRecordsOverflow {
|
||||
pub budget: u64,
|
||||
}
|
||||
|
||||
/// The first emulated tessellation draw of a command buffer whose records did not fit
|
||||
/// ([`CommandBufferError::TessellationRecordsOverflow`]).
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct TessellationRecordsOverflow {
|
||||
/// The draw's order among the command buffer's emulated mesh and tessellation draws, from 0.
|
||||
pub draw: u32,
|
||||
/// Its records, `patchCount · instanceCount`, saturated at `u32::MAX`.
|
||||
pub records: u32,
|
||||
/// The bytes of the command buffer's records pool, the device's budget.
|
||||
pub budget: u64,
|
||||
}
|
||||
|
||||
impl CommandBufferError {
|
||||
/// Metal's `MTLCommandBufferError` code for this error: `MTLCommandBufferErrorDeviceRemoved`
|
||||
/// (11) for a lost device, `OutOfMemory` (8) for the device's memory, the index pool's and
|
||||
/// the mesh records pool's, and a detached buffer's, `PageFault` (3), and `Internal` (1), also
|
||||
/// for the runtime's refusals (a cubic argument sampler's reach among them, a sampler state
|
||||
/// left out of an argument-sampler listing, a host step's object nothing made, a named use
|
||||
/// rebound before the submission, and a predicated loop past its copies); a command buffer
|
||||
/// committed as failed, the code the program chose; a pipeline's failed making, its cause's; a
|
||||
/// failure the driver relayed, Metal's.
|
||||
/// (11) for a lost device, `OutOfMemory` (8) for the device's memory, the index pool's and the
|
||||
/// records pool's (mesh and tessellation), and a detached buffer's, `PageFault` (3), and
|
||||
/// `Internal` (1), also for the runtime's refusals (a cubic argument sampler's reach among
|
||||
/// them, a sampler state left out of an argument-sampler listing, a host step's object nothing
|
||||
/// made, a named use rebound before the submission, and a predicated loop past its copies); a
|
||||
/// command buffer committed as failed, the code the program chose; a pipeline's failed making,
|
||||
/// its cause's; a failure the driver relayed, Metal's.
|
||||
///
|
||||
/// The code is Metal's answer only where [`origin`](Self::origin) is
|
||||
/// [`FailureOrigin::Metal`]. A [`FailureOrigin::Runtime`] error's code is the nearest of
|
||||
@@ -1822,6 +1869,7 @@ impl CommandBufferError {
|
||||
CommandBufferError::OutOfMemory
|
||||
| CommandBufferError::IndexPoolOverflow
|
||||
| CommandBufferError::MeshRecordsOverflow(_)
|
||||
| CommandBufferError::TessellationRecordsOverflow(_)
|
||||
| CommandBufferError::DetachedBacking => 8,
|
||||
CommandBufferError::Internal(_)
|
||||
| CommandBufferError::SparseHeapSplit
|
||||
@@ -1868,6 +1916,7 @@ impl CommandBufferError {
|
||||
| CommandBufferError::CubicArgumentSampler
|
||||
| CommandBufferError::UnlistedArgumentSampler
|
||||
| CommandBufferError::MeshRecordsOverflow(_)
|
||||
| CommandBufferError::TessellationRecordsOverflow(_)
|
||||
| CommandBufferError::Refused
|
||||
| CommandBufferError::PipelineCreation(_)
|
||||
| CommandBufferError::HostStepObject(_)
|
||||
|
||||
@@ -4,9 +4,18 @@
|
||||
//! - **One Vulkan object.** An event is a timeline semaphore. Its counter is a signal index that
|
||||
//! [`EventTimeline`] maps to Metal's values: only the GPU signals the scheduler keeps raise it,
|
||||
//! and a host set is a floor that never touches it.
|
||||
//! - **Who observes.** The completion thread sees each batch complete, and with it the event
|
||||
//! - **Who observes.** A completion turn sees each batch complete, and with it the event
|
||||
//! signals of the batch; reading the value reads the semaphore's counter too. Either one wakes
|
||||
//! the host's waits and posts the listeners' notifications that came due.
|
||||
//! - **A read is observed once a host wait returned for it.** The program may read what the
|
||||
//! signalling work wrote once it sees the value, and Vulkan orders host operations after a
|
||||
//! signal only through a wait ("signal operations happening before host operations that wait
|
||||
//! on them" system-synchronize-with them, the memory model): `vkGetSemaphoreCounterValue`'s
|
||||
//! value "may immediately be out of date" and orders nothing. So a counter the read shows past
|
||||
//! the index last seen is waited for first, a wait of no time ("If the condition is satisfied
|
||||
//! when `vkWaitSemaphores` is called, then `vkWaitSemaphores` returns immediately"), as the
|
||||
//! queues' waiters do (`command_buffer/completion.rs`): one call more, and only where the
|
||||
//! read ran ahead of the completion turns.
|
||||
//! - **Host waits** (`wait_until_signaled_value`) wait on the event's condition variable, which
|
||||
//! every rise signals, and read the counter again at least every [`POLL`]. Once the process is
|
||||
//! exiting they answer from the value last seen ([`exit_guard`]).
|
||||
@@ -191,22 +200,45 @@ impl EventShared {
|
||||
self.post(due);
|
||||
}
|
||||
|
||||
/// The value now, from the semaphore's counter and the host's floor. Once the process is
|
||||
/// exiting, the counter is not read (`exit_guard`): the value is the one last seen.
|
||||
/// The value now, from the semaphore's counter and the host's floor. A counter the read
|
||||
/// shows past the index last seen is waited for, a wait that returns at once, before it is
|
||||
/// observed (the module docs). Once the process is exiting, the counter is not read
|
||||
/// (`exit_guard`): the value is the one last seen.
|
||||
fn value(self: &Arc<Self>) -> u64 {
|
||||
if let Some(busy) = exit_guard::enter() {
|
||||
let raw = self.device.shared().vk();
|
||||
// SAFETY: the semaphore is the device's and live. A failure (a lost device) leaves
|
||||
// the value as last seen.
|
||||
let counter = unsafe {
|
||||
self.device
|
||||
.shared()
|
||||
.vk()
|
||||
.get_semaphore_counter_value(self.semaphore)
|
||||
};
|
||||
let counter = unsafe { raw.get_semaphore_counter_value(self.semaphore) };
|
||||
exit_guard::called(Call::GetSemaphoreCounterValue);
|
||||
drop(busy);
|
||||
if let Ok(counter) = counter {
|
||||
self.reached(counter);
|
||||
if let Ok(read) = counter {
|
||||
let reaches = |index: u64| {
|
||||
let semaphores = [self.semaphore];
|
||||
let values = [index];
|
||||
let info = vk::SemaphoreWaitInfo::default()
|
||||
.semaphores(&semaphores)
|
||||
.values(&values);
|
||||
// SAFETY: as the read's above. "If timeout is zero, then vkWaitSemaphores
|
||||
// does not wait"; a failure (a lost device) leaves the value as last seen.
|
||||
let waited = unsafe { raw.wait_semaphores(&info, 0) };
|
||||
exit_guard::called(Call::WaitSemaphores);
|
||||
waited.map(|()| true).or_else(|error| match error {
|
||||
vk::Result::TIMEOUT => Ok(false),
|
||||
error => Err(error),
|
||||
})
|
||||
};
|
||||
let due = {
|
||||
let mut state = lock(&self.state);
|
||||
match state.timeline.observe_read(read, reaches) {
|
||||
Ok(true) => {
|
||||
self.changed.notify_all();
|
||||
due(&mut state)
|
||||
}
|
||||
Ok(false) | Err(_) => Vec::new(),
|
||||
}
|
||||
};
|
||||
drop(busy);
|
||||
self.post(due);
|
||||
}
|
||||
}
|
||||
lock(&self.state).timeline.value()
|
||||
@@ -228,7 +260,7 @@ impl EventShared {
|
||||
}
|
||||
|
||||
/// Wait until the value reaches `value`, at most `timeout`. Once the process is exiting, it
|
||||
/// answers at once from the value last seen: neither the completion thread nor the counter
|
||||
/// answers at once from the value last seen: neither a completion turn nor the counter
|
||||
/// raises it any more (`exit_guard`).
|
||||
fn wait_until(self: &Arc<Self>, value: u64, timeout: Duration) -> bool {
|
||||
let deadline = Instant::now() + timeout;
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
//! early by a later host set above its value: it waits for that GPU signal, which was submitted
|
||||
//! before it and so comes. Metal releases it at the host set.
|
||||
|
||||
use crate::command_buffer::completion::seen;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
/// One kept GPU signal the semaphore has not been seen to reach.
|
||||
@@ -104,6 +105,19 @@ impl<Q: Copy + Eq> EventTimeline<Q> {
|
||||
self.value() > before
|
||||
}
|
||||
|
||||
/// The semaphore's counter read `read`: observed only up to the index a host wait returned
|
||||
/// for (`reaches`, the answer of `command_buffer/completion.rs`'s `seen`), as a read alone
|
||||
/// orders no host operation after the signal; a read past the index last seen is waited for
|
||||
/// first. Whether the value rose.
|
||||
pub(super) fn observe_read<E>(
|
||||
&mut self,
|
||||
read: u64,
|
||||
reaches: impl FnOnce(u64) -> Result<bool, E>,
|
||||
) -> Result<bool, E> {
|
||||
let index = seen(self.reached, None, read, reaches)?;
|
||||
Ok(self.observe(index))
|
||||
}
|
||||
|
||||
/// The host set `value`. Whether the value rose.
|
||||
pub(super) fn set(&mut self, value: u64) -> bool {
|
||||
let before = self.value();
|
||||
|
||||
@@ -31,7 +31,8 @@ pub enum Exactness {
|
||||
/// cannot hold draws nothing, and its command buffer fails with a [`CommandBufferError`] of
|
||||
/// [`FailureOrigin::Runtime`](crate::FailureOrigin::Runtime) where Metal draws it
|
||||
/// ([`CommandBufferError::IndexPoolOverflow`] for `indirect-index-bounds-pass`,
|
||||
/// [`CommandBufferError::MeshRecordsOverflow`] for `emulated-mesh-draws`).
|
||||
/// [`CommandBufferError::MeshRecordsOverflow`] for `emulated-mesh-draws`,
|
||||
/// [`CommandBufferError::TessellationRecordsOverflow`] for `emulated-tessellation-draws`).
|
||||
ExactWithinPool,
|
||||
/// A recorded near-equivalent of Metal's answer, or an answer where none of Metal's is
|
||||
/// measured.
|
||||
@@ -46,7 +47,9 @@ impl Degradation {
|
||||
use Degradation as D;
|
||||
match self.category() {
|
||||
DegradationCategory::Performance | DegradationCategory::Validity => match self {
|
||||
D::IndirectIndexBoundsPass | D::EmulatedMeshDraws => Exactness::ExactWithinPool,
|
||||
D::IndirectIndexBoundsPass
|
||||
| D::EmulatedMeshDraws
|
||||
| D::EmulatedTessellationDraws => Exactness::ExactWithinPool,
|
||||
_ => Exactness::Exact,
|
||||
},
|
||||
DegradationCategory::Precision => match self {
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
//! A process exits (`exit`, or the end of `main`) on one thread, which runs the exit handlers and
|
||||
//! the loaded libraries' destructors in the reverse order of their registration; every other
|
||||
//! thread keeps running meanwhile. A driver's or a layer's destructors free what a later Vulkan
|
||||
//! call needs: RADV ended a process with `SIGSEGV` when the completion thread destroyed a device
|
||||
//! call needs: RADV ended a process with `SIGSEGV` when a completing thread destroyed a device
|
||||
//! beside the validation layer's destructors.
|
||||
//!
|
||||
//! - **Sections.** Each Vulkan call the runtime makes on its own threads (the scheduler's
|
||||
//! submissions, the completion thread's polls), each release of a
|
||||
//! submissions, the queues' waiters' polls), each release of a
|
||||
//! Vulkan object (a drop, on whatever thread it runs), and each read of an event's counter runs
|
||||
//! inside a section ([`enter`]), which counts itself. A section runs none of the program's code
|
||||
//! (handlers, deallocators, notifications) except a device's message sink, which Vulkan calls
|
||||
@@ -21,7 +21,10 @@
|
||||
//! A source test fails when another file calls such an entry point;
|
||||
//! - every thread the runtime starts is started by [`spawn`], and every call of the program's
|
||||
//! code (handlers, notifications, deallocators, the message sink) goes through [`program`];
|
||||
//! source tests fail when a thread is started or a panic caught elsewhere;
|
||||
//! source tests fail when a thread is started or a panic caught elsewhere. A release of the
|
||||
//! program's (a deallocator, a keep-alive, a range token, a dma-buf source) goes through
|
||||
//! [`program_release`], which in builds with debug assertions ends the process on a thread
|
||||
//! command buffers' completion depends on;
|
||||
//! - the device's functions are reached only through checked accessors (`DeviceShared::vk`,
|
||||
//! private field), which in builds with debug assertions end the process
|
||||
//! when one of the runtime's threads reaches them outside a section and outside the
|
||||
@@ -75,14 +78,27 @@
|
||||
//! it ended, an exit the program makes once it learned of a section's work (from a handler, a
|
||||
//! wait, a status) comes after that section's registration. Measured: while the scheduler posted
|
||||
//! a command buffer's scheduling inside its section, an exit from a scheduled handler crashed the
|
||||
//! completion thread's poll on MoltenVK in 10 runs of 10. The hole left: a static first made by a
|
||||
//! completion's poll on MoltenVK in 10 runs of 10. The hole left: a static first made by a
|
||||
//! call after the hook's last registration (one in progress as the exit begins included), when
|
||||
//! the process exits before the next registration.
|
||||
//! - **Once closed.** The scheduler and the completion thread end at their next section, so what
|
||||
//! the process exits before the next registration. The program's own calls register nothing,
|
||||
//! so one of those may make it too: on the M3 Max (the validation layer 1.4.357.0 from
|
||||
//! Homebrew), the layer's descriptor set layouts' empty lists
|
||||
//! (`DescriptorSetLayoutDef::GetMutableTypes` and `GetImmutableSamplerCreateInfosFromIndex`),
|
||||
//! first made on the program's thread 3 to 11 ms before an exit in each of 20 runs; no section
|
||||
//! was seen to read them at exit. Not the guard's, at exit or before: under a layer on MoltenVK
|
||||
//! 1.4.1, a message that names the device leaves `ICD_LOADER_MAGIC` in its loader word, and the
|
||||
//! layer, which finds its state by that word, ends the process at its next call for the device
|
||||
//! (the validation layer: "The VkDevice dispatch handle was not found";
|
||||
//! `Device::with_loader_word`).
|
||||
//! - **Once closed.** The scheduler and the queues' waiters end at their next section, so what
|
||||
//! is pending stays pending, as Metal's does. A release skips its Vulkan calls (the process's
|
||||
//! end frees what they would), and a no-copy buffer released then keeps its deallocator unrun,
|
||||
//! with its pages imported. The handler threads, listeners and the shader cache's thread go on;
|
||||
//! a making that ends then saves no record (`shader_cache/driver.rs`).
|
||||
//! with its pages imported; a release inside a section in progress (a whole drop's, a pool
|
||||
//! piece's) runs, within the hook's wait. The handler threads, listeners and the shader cache's
|
||||
//! thread go on. A driver's making then calls the driver for its pipelines alone
|
||||
//! (`shader_cache/driver.rs`): one in progress (a pool piece's or a host step's section runs on
|
||||
//! past the close) neither reads its cache for a record nor releases it, and one begun after
|
||||
//! makes no cache.
|
||||
//! - **A CPU device's work.** A device whose queues run in this process (`DeviceKind::Cpu`:
|
||||
//! lavapipe, SwiftShader) runs what was submitted to it on the process's own threads, so the
|
||||
//! destructors would run under its execution. Once the sections ended, the hook waits for the
|
||||
@@ -299,7 +315,7 @@ calls! {
|
||||
// which an indirect sparse update's read in a host step can be.
|
||||
CreateSemaphore => c"vkCreateSemaphore",
|
||||
WaitForFences => c"vkWaitForFences",
|
||||
// The completion thread's drain of a device's queues after a failed wait
|
||||
// A completion turn's drain of a device's queues after a failed wait
|
||||
// (`Device::drain_queues`).
|
||||
QueueWaitIdle => c"vkQueueWaitIdle",
|
||||
ResetFences => c"vkResetFences",
|
||||
@@ -492,6 +508,8 @@ thread_local! {
|
||||
static BASE: Cell<usize> = const { Cell::new(0) };
|
||||
/// The host steps this thread is recording now ([`host_step`]).
|
||||
static HOST_STEPS: Cell<usize> = const { Cell::new(0) };
|
||||
/// Command buffers' completion depends on this thread ([`serves_completion`]).
|
||||
static SERVES_COMPLETION: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Whether this thread runs inside a call of the program's: one of the program's own threads,
|
||||
@@ -725,8 +743,8 @@ where
|
||||
/// Start one of the runtime's threads that take a command buffer from its commit to its handlers,
|
||||
/// running `f`, as [`spawn`] does, but at the user-interactive quality of service on macOS, and
|
||||
/// with the utilization floor at its top on Linux, from its start ([`run_at_user_interactive`]):
|
||||
/// the scheduler's (`scheduler/`), the completion thread
|
||||
/// and each `VkQueue`'s waiter (`command_buffer/completion.rs`), and every thread of the handler
|
||||
/// the scheduler's (`scheduler/`), each `VkQueue`'s waiter, which makes the completion turns
|
||||
/// (`command_buffer/completion.rs`), and every thread of the handler
|
||||
/// pool (`contexts/`). A thread one of them starts (the reaper a pipeline state's last release
|
||||
/// starts on a handler thread, a program's thread made in a handler) does not take either: it
|
||||
/// starts at the default class on macOS ([`spawn`]), and with no floor on Linux.
|
||||
@@ -945,6 +963,38 @@ pub(crate) fn in_section() -> bool {
|
||||
OWN.with(Cell::get) > BASE.with(Cell::get)
|
||||
}
|
||||
|
||||
/// Mark this thread, one of the runtime's own, as one that command buffers' completion depends on:
|
||||
/// the scheduler's, which submits them and holds each batch's command buffer until its pass ends,
|
||||
/// so its gate stays shut meanwhile (`command_buffer/gate.rs`); the queues' waiters, which see
|
||||
/// them complete and finish them. No release of the program's may run on it
|
||||
/// ([`program_release`]).
|
||||
pub(crate) fn serves_completion() {
|
||||
SERVES_COMPLETION.with(|serves| serves.set(true));
|
||||
}
|
||||
|
||||
/// Run `f`, the program's code a release runs (a no-copy buffer's deallocator, the drop of its
|
||||
/// keep-alive, of a range token or of a dma-buf source), as [`program`] runs it. In builds with
|
||||
/// debug assertions (every test run), end the process where this thread is one command buffers'
|
||||
/// completion depends on ([`serves_completion`]) and runs none of the program's code already (a
|
||||
/// submission handler's own drops are the program's): `f` may wait for such a command buffer,
|
||||
/// which would then never complete or never open its gate. What a command buffer's commands and
|
||||
/// encoders took goes in its release, on its queue's handler thread
|
||||
/// (`CommandBufferShared::complete`); what the scheduler's thread lets go of before then, on a
|
||||
/// handler thread in a context of its own (`Device::let_go_elsewhere`).
|
||||
pub(crate) fn program_release(f: impl FnOnce()) {
|
||||
if cfg!(debug_assertions) && SERVES_COMPLETION.with(Cell::get) && PROGRAM.with(Cell::get) == 0 {
|
||||
let name = std::thread::current().name().map(str::to_owned);
|
||||
eprintln!(
|
||||
"metal2vulkan: the runtime's thread {} ran a release of the program's (a deallocator, \
|
||||
a keep-alive, a range token or a dma-buf source), on which command buffers' \
|
||||
completion depends",
|
||||
name.as_deref().unwrap_or("(unnamed)")
|
||||
);
|
||||
std::process::abort();
|
||||
}
|
||||
program(f);
|
||||
}
|
||||
|
||||
/// Whether this thread may reach the device's functions now: the program's threads always (the
|
||||
/// program's calls are its own race with an exit), the runtime's own only inside a section or
|
||||
/// while they run the program's code.
|
||||
|
||||
@@ -1043,22 +1043,29 @@ impl FeatureRow {
|
||||
f.properties.are_programmable_sample_positions_supported(),
|
||||
Query::ProgrammableSamplePositions,
|
||||
)]),
|
||||
// `render_target_array_index` (`shaderOutputLayer`), and passes of more than one layer
|
||||
// `render_target_array_index`, stored from the vertex function (`shaderOutputLayer`) or
|
||||
// by the generated geometry stage (`geometryShader`), and passes of more than one layer
|
||||
// (`render_target_array_length`, `render_pass.rs`): built, an index at or past the
|
||||
// length included, and resolves, separate depth and stencil textures and stand-ins over
|
||||
// every layer; a tile dispatch in one is the tile shading row's.
|
||||
F::LayeredRendering => first([needs_features(
|
||||
F::LayeredRendering => first([needs_any(
|
||||
f,
|
||||
Feature::LayeredRendering,
|
||||
&[VkFeature::ShaderOutputLayer],
|
||||
&[
|
||||
&[VkFeature::ShaderOutputLayer],
|
||||
&[VkFeature::GeometryShader],
|
||||
],
|
||||
)]),
|
||||
// The same, into multisampled array textures, which a portability subset may withhold
|
||||
// (`multisampleArrayImage`).
|
||||
F::LayeredRenderingToMultisampleTextures => first([
|
||||
needs_features(
|
||||
needs_any(
|
||||
f,
|
||||
Feature::LayeredRendering,
|
||||
&[VkFeature::ShaderOutputLayer],
|
||||
&[
|
||||
&[VkFeature::ShaderOutputLayer],
|
||||
&[VkFeature::GeometryShader],
|
||||
],
|
||||
),
|
||||
withheld(
|
||||
f,
|
||||
@@ -1066,16 +1073,20 @@ impl FeatureRow {
|
||||
VkFeature::MultisampleArrayImage,
|
||||
),
|
||||
]),
|
||||
// `viewport_array_index` and `set_viewports`: `multiViewport` and
|
||||
// `shaderOutputViewportIndex`.
|
||||
F::MultipleViewports => first([needs_features(
|
||||
f,
|
||||
Feature::LayeredRendering,
|
||||
&[
|
||||
VkFeature::MultiViewport,
|
||||
VkFeature::ShaderOutputViewportIndex,
|
||||
],
|
||||
)]),
|
||||
// `viewport_array_index` and `set_viewports`: `multiViewport`, and the index stored
|
||||
// from the vertex function (`shaderOutputViewportIndex`) or by the generated geometry
|
||||
// stage (`geometryShader`).
|
||||
F::MultipleViewports => first([
|
||||
needs_features(f, Feature::LayeredRendering, &[VkFeature::MultiViewport]),
|
||||
needs_any(
|
||||
f,
|
||||
Feature::LayeredRendering,
|
||||
&[
|
||||
&[VkFeature::ShaderOutputViewportIndex],
|
||||
&[VkFeature::GeometryShader],
|
||||
],
|
||||
),
|
||||
]),
|
||||
// Dual-source blending: `dualSrcBlend`.
|
||||
F::DualSourceBlending => first([needs_features(
|
||||
f,
|
||||
@@ -1093,15 +1104,20 @@ impl FeatureRow {
|
||||
Capability::Extension(VkExtension::ExtShaderStencilExport),
|
||||
))
|
||||
})]),
|
||||
// `[[primitive_id]]` in a fragment function: the geometry or tessellation stage it
|
||||
// needs, which the compile layer lists where the device lacks both.
|
||||
F::PrimitiveId => first([listed(f, Feature::PrimitiveId)]),
|
||||
// `[[barycentric_coord]]`: `fragmentShaderBarycentric`.
|
||||
F::BarycentricCoordinates => first([needs_features(
|
||||
f,
|
||||
Feature::Barycentrics,
|
||||
&[VkFeature::FragmentShaderBarycentric],
|
||||
)]),
|
||||
// `[[primitive_id]]` in a fragment function: the builtin through the geometry or
|
||||
// tessellation capability; on a device with neither, a varying the vertex function
|
||||
// writes, which an indexed draw's shared vertices cannot carry: an indexed list or
|
||||
// point draw runs de-indexed where the device addresses buffers, and an indexed
|
||||
// strip or indirect indexed draw is refused (`NotImplemented(PrimitiveId)`).
|
||||
F::PrimitiveId => {
|
||||
let d = f.profile.fragment();
|
||||
first([(!d.geometry_shader && !d.tessellation_shader)
|
||||
.then(|| refused(Unsupported::not_implemented(Feature::PrimitiveId)))])
|
||||
}
|
||||
// `[[barycentric_coord]]`: `fragmentShaderBarycentric`, or the generated geometry
|
||||
// stage that writes the weights as varyings, which the compile layer lists where the
|
||||
// device lacks both.
|
||||
F::BarycentricCoordinates => first([listed(f, Feature::Barycentrics)]),
|
||||
// Raster order groups: the pixel interlock, which the compile layer lists where the
|
||||
// device lacks both interlocks, then the runtime's query, which answers yes where the
|
||||
// pixel interlock is enabled.
|
||||
@@ -1113,17 +1129,31 @@ impl FeatureRow {
|
||||
),
|
||||
]),
|
||||
// Vertex amplification: multiview, and for what multiview does not draw as Metal does
|
||||
// the layer and viewport index outputs of the variant that draws one amplification at a
|
||||
// time; then the runtime's query of two views; then a tessellation pipeline drawn so,
|
||||
// which the binder does not implement.
|
||||
// the variant that draws one amplification at a time, which stores the slice and the
|
||||
// viewport from the vertex function (the layer and viewport index outputs) or by the
|
||||
// generated geometry stage, the viewport among more than one (`multiViewport`); then
|
||||
// the runtime's query of two views; then a tessellation pipeline drawn so, which the
|
||||
// binder does not implement.
|
||||
F::VertexAmplification => first([
|
||||
needs_features(
|
||||
f,
|
||||
Feature::VertexAmplification,
|
||||
&[VkFeature::Multiview, VkFeature::MultiViewport],
|
||||
),
|
||||
needs_any(
|
||||
f,
|
||||
Feature::VertexAmplification,
|
||||
&[
|
||||
VkFeature::Multiview,
|
||||
VkFeature::ShaderOutputLayer,
|
||||
VkFeature::ShaderOutputViewportIndex,
|
||||
&[VkFeature::ShaderOutputLayer],
|
||||
&[VkFeature::GeometryShader],
|
||||
],
|
||||
),
|
||||
needs_any(
|
||||
f,
|
||||
Feature::VertexAmplification,
|
||||
&[
|
||||
&[VkFeature::ShaderOutputViewportIndex],
|
||||
&[VkFeature::GeometryShader],
|
||||
],
|
||||
),
|
||||
query(
|
||||
@@ -1153,15 +1183,15 @@ impl FeatureRow {
|
||||
F::TextureBarriers | F::VisibilityCountAccumulation | F::DepthBoundsTesting => {
|
||||
first([gap(G::Render)])
|
||||
}
|
||||
// Patch draws: `tessellationShader`; the runtime's patch draws, direct and indirect,
|
||||
// are built (`tessellation.rs`). The compile layer still refuses a post-tessellation
|
||||
// vertex function whose patch states no control-point count (`[[patch(kind)]]`), and
|
||||
// a fragment function behind one that reads `[[primitive_id]]`
|
||||
// (`NotImplemented(Tessellation)`).
|
||||
F::Tessellation | F::IndirectTessellationArguments => first([
|
||||
needs_features(f, Feature::Tessellation, &[VkFeature::TessellationShader]),
|
||||
not_implemented(Feature::Tessellation),
|
||||
]),
|
||||
// Patch draws: the runtime's patch draws, direct and indirect, are built
|
||||
// (`tessellation.rs`), through the device's tessellation stages where it enables
|
||||
// `tessellationShader` and emulated elsewhere (`render/tessellation_scan.rs`). The
|
||||
// compile layer still refuses a post-tessellation vertex function whose patch states
|
||||
// no control-point count (`[[patch(kind)]]`), and with the device's stages a fragment
|
||||
// function behind one that reads `[[primitive_id]]` (`NotImplemented(Tessellation)`).
|
||||
F::Tessellation | F::IndirectTessellationArguments => {
|
||||
first([not_implemented(Feature::Tessellation)])
|
||||
}
|
||||
// Coverage after the depth test (`[[post_depth_coverage]]`): not lowered.
|
||||
F::PostDepthCoverage => {
|
||||
first([not_implemented(Feature::Lowering(LowerFamily::Fragment))])
|
||||
@@ -1276,7 +1306,6 @@ impl FeatureRow {
|
||||
])
|
||||
}
|
||||
F::IcbTessellation => first([
|
||||
needs_features(f, Feature::Tessellation, &[VkFeature::TessellationShader]),
|
||||
addressed(f, Feature::GpuEncodedIndirectCommands),
|
||||
gap(G::IndirectRenderCommands),
|
||||
]),
|
||||
@@ -1489,6 +1518,20 @@ pub(super) fn needs_features(f: &Facts<'_>, feature: Feature, features: &[VkFeat
|
||||
(!missing.is_empty()).then(|| refused(Unsupported::needs_any_of(feature, vec![missing])))
|
||||
}
|
||||
|
||||
/// `feature`, refused where the device was created without every feature of each of
|
||||
/// `alternatives`.
|
||||
pub(super) fn needs_any(f: &Facts<'_>, feature: Feature, alternatives: &[&[VkFeature]]) -> Check {
|
||||
let has = |x: &VkFeature| f.properties.description.has(*x);
|
||||
if alternatives.iter().any(|a| a.iter().all(has)) {
|
||||
return None;
|
||||
}
|
||||
let needs = alternatives
|
||||
.iter()
|
||||
.map(|a| a.iter().map(|&x| Capability::Feature(x)).collect())
|
||||
.collect();
|
||||
Some(refused(Unsupported::needs_any_of(feature, needs)))
|
||||
}
|
||||
|
||||
/// `feature`, refused where the device's `VK_KHR_portability_subset` withholds `withheld`.
|
||||
fn withheld(f: &Facts<'_>, feature: Feature, withheld: VkFeature) -> Check {
|
||||
f.profile
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! have neither imageblocks nor tile shaders.
|
||||
|
||||
use super::features::{
|
||||
addressed, first, gap, listed, needs_features, query, ray_tracing, refused, Check,
|
||||
addressed, first, gap, listed, needs_any, needs_features, query, ray_tracing, refused, Check,
|
||||
};
|
||||
use super::{Column, Facts, FeatureRow, Refusal, RowState};
|
||||
use crate::capabilities::Query;
|
||||
@@ -801,16 +801,20 @@ impl LimitRow {
|
||||
l.max_vertex_output_components,
|
||||
),
|
||||
]),
|
||||
// Tessellation factors: `tessellationShader` and `maxTessellationGenerationLevel`.
|
||||
// The patch draws that read them are built (`tessellation.rs`); what the compile
|
||||
// layer still refuses of tessellation is the feature row's.
|
||||
// Tessellation factors: `maxTessellationGenerationLevel` on a device that enables
|
||||
// `tessellationShader`; elsewhere the emulation's tessellator takes Metal's every
|
||||
// factor (`render/tessellation_scan.rs`). The patch draws that read them are built
|
||||
// (`tessellation.rs`); what the compile layer still refuses of tessellation is the
|
||||
// feature row's.
|
||||
L::TessellationFactor => first([
|
||||
needs_features(f, Feature::Tessellation, &[VkFeature::TessellationShader]),
|
||||
at_least(
|
||||
Feature::Tessellation,
|
||||
VkLimit::MaxTessellationGenerationLevel,
|
||||
l.max_tessellation_generation_level,
|
||||
),
|
||||
match f.properties.description.has(VkFeature::TessellationShader) {
|
||||
true => at_least(
|
||||
Feature::Tessellation,
|
||||
VkLimit::MaxTessellationGenerationLevel,
|
||||
l.max_tessellation_generation_level,
|
||||
),
|
||||
false => None,
|
||||
},
|
||||
]),
|
||||
// One viewport on every device; more need `multiViewport`, whose devices take at least
|
||||
// 16 (Vulkan's required `maxViewports`).
|
||||
@@ -878,19 +882,17 @@ impl LimitRow {
|
||||
l.max_texel_buffer_elements,
|
||||
)]),
|
||||
// A pass's color attachments: `maxColorAttachments` and
|
||||
// `maxFragmentOutputAttachments`.
|
||||
L::ColorRenderTargets => first([
|
||||
at_least(
|
||||
Feature::InterfaceComponents,
|
||||
VkLimit::MaxColorAttachments,
|
||||
l.max_color_attachments,
|
||||
),
|
||||
at_least(
|
||||
Feature::InterfaceComponents,
|
||||
VkLimit::MaxFragmentOutputAttachments,
|
||||
l.max_fragment_output_attachments,
|
||||
),
|
||||
]),
|
||||
// `maxFragmentOutputAttachments`. Past the lesser, a pass draws its colors in groups
|
||||
// of that many (`render/color_groups.rs`), whose refusals keep the row a gap.
|
||||
L::ColorRenderTargets => {
|
||||
let width = l
|
||||
.max_color_attachments
|
||||
.min(l.max_fragment_output_attachments);
|
||||
first([match need {
|
||||
Need::AtLeast(n) if u64::from(width) < n => gap(G::ColorAttachmentGroups),
|
||||
_ => None,
|
||||
}])
|
||||
}
|
||||
// `[[point_size]]`: the device clamps a point to its `pointSizeRange`, whose upper
|
||||
// bound (in whole pixels, `Limits::max_point_size`) must reach Metal's largest point;
|
||||
// the translation stores a larger size as Metal's.
|
||||
@@ -904,18 +906,20 @@ impl LimitRow {
|
||||
// `framebufferDepthSampleCounts`.
|
||||
L::RenderPassSampleCount => first([sample_count(f, need)]),
|
||||
// Vertex amplification: multiview, whose views past `maxMultiviewViewCount` draw one
|
||||
// amplification at a time through the layer output, then the runtime's query (the
|
||||
// feature row holds the tessellation pipelines not implemented).
|
||||
// amplification at a time, storing the slice through the layer output or the
|
||||
// generated geometry stage, then the runtime's query (the feature row holds the
|
||||
// tessellation pipelines not implemented).
|
||||
L::VertexAmplificationCount => first([
|
||||
needs_features(f, Feature::VertexAmplification, &[VkFeature::Multiview]),
|
||||
match need {
|
||||
Need::AtLeast(n) if n > u64::from(l.max_multiview_view_count) => {
|
||||
needs_features(
|
||||
f,
|
||||
Feature::VertexAmplification,
|
||||
Need::AtLeast(n) if n > u64::from(l.max_multiview_view_count) => needs_any(
|
||||
f,
|
||||
Feature::VertexAmplification,
|
||||
&[
|
||||
&[VkFeature::ShaderOutputLayer],
|
||||
)
|
||||
}
|
||||
&[VkFeature::GeometryShader],
|
||||
],
|
||||
),
|
||||
_ => None,
|
||||
},
|
||||
match need {
|
||||
|
||||
@@ -18,10 +18,15 @@
|
||||
//! targets alone, from the fragment stage to the fragment stage, is one of those: the pixels a
|
||||
//! draw's fragments write as render targets are the pixels later fragments read as render
|
||||
//! targets (blending, the depth and stencil tests, framebuffer fetch), so it records inside the
|
||||
//! instance (`render_target::between_draws`). Any other (buffers or textures, which a fragment
|
||||
//! may write at any address and a draw may read at any stage) splits the pass: the next draw
|
||||
//! records into a new instance, after a barrier from everything before to everything after
|
||||
//! (`render.rs`, the `render-pass-split` degradation).
|
||||
//! instance (`render_target::between_draws`); a draw after it that samples an attachment's
|
||||
//! texture, at any pixel, records into a new instance (`texture/attached_reads.rs`). Any other
|
||||
//! (buffers or textures, which a fragment may write at any address and a draw may read at any
|
||||
//! stage) splits the pass: the next draw records into a new instance, after a barrier from
|
||||
//! everything before to everything after (`render.rs`, the `render-pass-split` degradation).
|
||||
//! - **Barriers over the render targets on Apple GPUs.** The Metal Feature Set Tables give that
|
||||
//! scope to Mac2 GPUs, not to Apple3 to Apple10 ones: on the M3 Max under macOS 27.0.1 (probe
|
||||
//! `rtbarrier`), a draw after one read its own pixel's texels from before the pass, as with no
|
||||
//! barrier. The runtime orders what each barrier names, as a Mac2 GPU does.
|
||||
//! - **Barriers after the fragment stage.** On an Apple GPU Metal's validation stops one
|
||||
//! ("afterStages (0x2) can not contain MTLRenderStageTile or MTLRenderStageFragment on this
|
||||
//! device", M4, EV `CFIT-metal-probe-3`), and Metal without it did not order a fragment's
|
||||
@@ -188,6 +193,12 @@ impl RenderCommandEncoder {
|
||||
self.log(|_| RenderCall::UpdateFence(fence.clone(), after_stages));
|
||||
// Every stage is ordered, a superset of the ones named.
|
||||
let _ = after_stages;
|
||||
// The update follows the encoder's work, its later color groups' passes too, which
|
||||
// record in its core after the first group's: their encoders' calls change nothing
|
||||
// (`render/color_groups.rs`).
|
||||
if self.later_group_encoder() {
|
||||
return Ok(());
|
||||
}
|
||||
self.core().update_fence("update_fence", fence)
|
||||
}
|
||||
|
||||
@@ -202,6 +213,11 @@ impl RenderCommandEncoder {
|
||||
self.log(|_| RenderCall::WaitForFence(fence.clone(), before_stages));
|
||||
// Every stage waits, a superset of the ones named.
|
||||
let _ = before_stages;
|
||||
// All of the encoder's work waits, its later color groups' passes too
|
||||
// (`render/color_groups.rs`).
|
||||
if self.later_group_encoder() {
|
||||
return Ok(());
|
||||
}
|
||||
self.core().wait_for_fence("wait_for_fence", fence)
|
||||
}
|
||||
|
||||
|
||||
@@ -154,6 +154,19 @@ pub(crate) fn views_in(plan: &ImagePlan, format: Format) -> bool {
|
||||
&& (plan.view_formats.is_empty() || plan.view_formats.contains(&format)))
|
||||
}
|
||||
|
||||
/// Whether a fetching draw in the interlock reads and writes an attachment that renders in
|
||||
/// `format` through a storage view of its image of `plan` ([`storage_view_format`]): the image is
|
||||
/// that format, or the attachment a view of it in a format `profile` stores, or the image takes
|
||||
/// the view ([`views_in`]).
|
||||
pub(crate) fn stores_in_place(profile: &DeviceProfile, format: Format, plan: &ImagePlan) -> bool {
|
||||
let view = storage_view_format(format);
|
||||
if view == format {
|
||||
format == plan.format || profile.supports_format(format, FormatUsage::StorageImage)
|
||||
} else {
|
||||
views_in(plan, view)
|
||||
}
|
||||
}
|
||||
|
||||
/// The image descriptions remembered at most: past this many, the oldest answer goes.
|
||||
const ANSWERS: usize = 64;
|
||||
|
||||
@@ -161,7 +174,9 @@ const ANSWERS: usize = 64;
|
||||
/// the usage costs a color render target's image nothing (the module docs): what a framebuffer
|
||||
/// fetch's form needs, `STORAGE` ([`storage_candidate`]) or what the sample planes' copies need
|
||||
/// ([`planes_candidate`]), and the input attachment usage the exact resolve reads through
|
||||
/// (`color_resolve::input_candidate`). Bounded: the oldest answer goes first.
|
||||
/// (`color_resolve::input_candidate`); for a memoryless attachment's input attachment usage,
|
||||
/// whether the device makes the image ([`Device::with_free_usage`]). Bounded: the oldest answer
|
||||
/// goes first.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct UsageAnswers(VecDeque<(ImagePlan, ImagePlan, bool)>);
|
||||
|
||||
@@ -288,11 +303,15 @@ impl Device {
|
||||
/// needs ([`fetch_candidate`]), or a multisampled depth/stencil attachment's copies without
|
||||
/// colour copies need (`depth_stencil_scratch::sampled_candidate`), then the unsigned-integer
|
||||
/// view a NaN clear writes a multisampled attachment through on a device whose copies
|
||||
/// convert its NaNs (`nan_clear::view_candidate`), and then the input attachment usage the
|
||||
/// convert its NaNs (`nan_clear::view_candidate`), then the input attachment usage the
|
||||
/// exact color resolve reads a multisampled color attachment through
|
||||
/// (`color_resolve::input_candidate`), each where it may take it and it costs the image
|
||||
/// (`color_resolve::input_candidate`), and then the feedback loop usage a draw that reads the
|
||||
/// texture its pass renders through a snapshot takes (`texture::feedback_candidate`), each
|
||||
/// where it may take it and it costs the image
|
||||
/// nothing: the image's memory requirements, size and alignment, are the same with it as
|
||||
/// without it (the module docs).
|
||||
/// without it (the module docs). A memoryless attachment takes the input attachment usage
|
||||
/// wherever the device makes the image: its image takes no copies, so the exact resolve reads
|
||||
/// it through that usage or not at all (`color_resolve.rs`).
|
||||
pub(crate) fn with_free_usage(
|
||||
&self,
|
||||
plan: ImagePlan,
|
||||
@@ -308,12 +327,41 @@ impl Device {
|
||||
Some(candidate) => self.if_free(plan, candidate, texture_type)?,
|
||||
None => plan,
|
||||
};
|
||||
match color_resolve::input_candidate(&plan, self) {
|
||||
let plan = match color_resolve::input_candidate(&plan, self) {
|
||||
Some(candidate) if plan.usage.contains(ImageUsageFlags::TRANSIENT_ATTACHMENT) => {
|
||||
self.if_made(plan, candidate, texture_type)?
|
||||
}
|
||||
Some(candidate) => self.if_free(plan, candidate, texture_type)?,
|
||||
None => plan,
|
||||
};
|
||||
match crate::texture::feedback_candidate(&plan, self) {
|
||||
Some(candidate) => self.if_free(plan, candidate, texture_type),
|
||||
None => Ok(plan),
|
||||
}
|
||||
}
|
||||
|
||||
/// `candidate`, `plan` with a usage added, where the device makes an image of it (its limits
|
||||
/// for the image take it, `Device::image_requirements`), else `plan`; remembered as
|
||||
/// [`Device::if_free`]'s answers are.
|
||||
fn if_made(
|
||||
&self,
|
||||
plan: ImagePlan,
|
||||
candidate: ImagePlan,
|
||||
texture_type: TextureType,
|
||||
) -> Result<ImagePlan, Error> {
|
||||
let answers = &self.shared().textures.usage_answers;
|
||||
let known = lock(answers).answer(&plan, &candidate);
|
||||
let made = match known {
|
||||
Some(made) => made,
|
||||
None => {
|
||||
let made = self.image_requirements(&candidate, texture_type)?.is_some();
|
||||
lock(answers).remember(plan.clone(), candidate.clone(), made);
|
||||
made
|
||||
}
|
||||
};
|
||||
Ok(if made { candidate } else { plan })
|
||||
}
|
||||
|
||||
/// `candidate`, `plan` with a usage added, where that costs the image nothing (as
|
||||
/// [`Device::with_free_usage`] says), else `plan`.
|
||||
pub(crate) fn if_free(
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
//! Freed memory that waits for the batches in flight, on a device whose driver fails pending work
|
||||
//! when memory a device-address buffer lay in is freed
|
||||
//! (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`: MoltenVK).
|
||||
//!
|
||||
//! - **The defect.** MoltenVK makes every `VkBuffer` of `SHADER_DEVICE_ADDRESS` usage resident
|
||||
//! (`useResource:`) in every encoder whose pipeline reads device addresses
|
||||
//! (`MVKDevice::encodeGPUAddressableBuffers`), in Metal command buffers that retain none of it,
|
||||
//! and lets go of the buffer's Metal memory as its `VkDeviceMemory` is freed: a Metal command
|
||||
//! buffer encoded before the free and not yet run fails (`Invalid Resource`, Metal's code 9).
|
||||
//! Vulkan allows the free, as no submitted command refers to the memory
|
||||
//! (VUID-vkFreeMemory-memory-00677). Destroying the buffer alone, its memory kept, fails
|
||||
//! nothing, and takes it out of the driver's list.
|
||||
//! - **The wait.** There a block of the runtime's memory that goes (`memory.rs`) has its buffer of
|
||||
//! addresses destroyed at once, and its memory waits, parked, until each `VkQueue`'s timeline
|
||||
//! reaches the value of the last batch submitted there as the block went. Vulkan's semaphore
|
||||
//! signal operations "defined by vkQueueSubmit or vkQueueSubmit2 additionally include all
|
||||
//! commands that occur earlier in submission order" in their first synchronization scope, so
|
||||
//! at that value every submission there before it completed. A host import's deallocator and
|
||||
//! keep-alive, which go after its memory is freed (`buffer.rs`), wait with it, the deallocator's
|
||||
//! wait announced (`host-deallocator-delayed`).
|
||||
//! - **Each batch noted.** A batch's `vkQueueSubmit` and the store of its value run under the
|
||||
//! gate's read lock, inside the queue's lock (`relay.rs`); a block's noting of the values, after
|
||||
//! its buffers were destroyed, under the write lock. So a batch whose encoding listed such a
|
||||
//! buffer, submitted before the buffer was destroyed, is noted, and a batch submitted after the
|
||||
//! noting lists none.
|
||||
//! - **And the device's own submissions.** Those that run command buffers outside the batches
|
||||
//! (`device/submit.rs`) signal no queue's timeline: each takes a number before its
|
||||
//! `vkQueueSubmit` and gives it back once its submitter saw it complete ([`OwnSubmission`]),
|
||||
//! and a block waits too for every one numbered before it went. Its sparse binds and the
|
||||
//! staging queue's copies run no pipeline, so no encoder of theirs lists a buffer. The
|
||||
//! program's own submissions (`CommandQueue::with_vk_queue`) are not waited for: the runtime
|
||||
//! sees neither what they list nor when they complete.
|
||||
//! - **Freed off the runtime's completion threads.** A queue's waiter that publishes a value while
|
||||
//! blocks wait posts their release to a handler thread (`Device::let_go_elsewhere`), which frees
|
||||
//! the blocks it reached and then lets go of what waited for them; a block whose values were
|
||||
//! reached as it went is freed at once, where it went. At the device's teardown, its queues
|
||||
//! idle, every block left is freed (`Memory::destroy`).
|
||||
|
||||
use crate::device::{lock, Device};
|
||||
use crate::exit_guard;
|
||||
use ash::vk;
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Mutex, RwLock, RwLockReadGuard};
|
||||
|
||||
/// A device's record of its batches for the blocks that wait (the module docs).
|
||||
pub(crate) struct Parking {
|
||||
/// Read around each batch's submission and the store of its value, written around a block's
|
||||
/// noting of the values.
|
||||
gate: RwLock<()>,
|
||||
/// Per `VkQueue`: the value of the last batch submitted there.
|
||||
submitted: Box<[AtomicU64]>,
|
||||
/// Per `VkQueue`: the value through which every batch submitted there completed, as the host
|
||||
/// saw.
|
||||
completed: Box<[AtomicU64]>,
|
||||
/// The blocks waiting (`Memory`'s, counted here so that a waiter reads it with no lock).
|
||||
waiting: AtomicUsize,
|
||||
/// A release is posted to a handler thread and has not begun: no other is posted.
|
||||
posted: AtomicBool,
|
||||
/// The device's own submissions: the next one's number, and those in flight.
|
||||
own: Mutex<Own>,
|
||||
}
|
||||
|
||||
/// The device's own submissions ([`OwnSubmission`]).
|
||||
#[derive(Default)]
|
||||
struct Own {
|
||||
/// The next one's number.
|
||||
next: u64,
|
||||
/// The numbers of those whose submitter has not yet seen them complete.
|
||||
in_flight: BTreeSet<u64>,
|
||||
}
|
||||
|
||||
/// What a block noted as it went: the value of each `VkQueue`'s last batch submitted, and the
|
||||
/// number the device's next own submission takes.
|
||||
pub(crate) struct Noted {
|
||||
values: Box<[u64]>,
|
||||
own: u64,
|
||||
}
|
||||
|
||||
impl Parking {
|
||||
/// The record of a device with `queues` `VkQueue`s, none submitted to.
|
||||
pub(crate) fn new(queues: usize) -> Parking {
|
||||
Parking {
|
||||
gate: RwLock::new(()),
|
||||
submitted: (0..queues).map(|_| AtomicU64::new(0)).collect(),
|
||||
completed: (0..queues).map(|_| AtomicU64::new(0)).collect(),
|
||||
waiting: AtomicUsize::new(0),
|
||||
posted: AtomicBool::new(false),
|
||||
own: Mutex::new(Own::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The gate's read lock, held around a batch's `vkQueueSubmit` and the store of its value
|
||||
/// ([`submitted`](Self::submitted)), inside the queue's lock.
|
||||
pub(crate) fn submitting(&self) -> RwLockReadGuard<'_, ()> {
|
||||
self.gate
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// A batch signalling `value` was submitted to `VkQueue` `queue`, under
|
||||
/// [`submitting`](Self::submitting)'s lock.
|
||||
pub(crate) fn submitted(&self, queue: usize, value: u64) {
|
||||
self.submitted[queue].fetch_max(value, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// The host saw `VkQueue` `queue`'s timeline reach `value`.
|
||||
pub(crate) fn completed(&self, queue: usize, value: u64) {
|
||||
self.completed[queue].fetch_max(value, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// The value of each `VkQueue`'s last batch submitted, under the gate's write lock, and the
|
||||
/// device's next own submission's number: called once the block's buffers were destroyed.
|
||||
pub(crate) fn note(&self) -> Noted {
|
||||
let _gate = self
|
||||
.gate
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let values = (self.submitted.iter())
|
||||
.map(|value| value.load(Ordering::SeqCst))
|
||||
.collect();
|
||||
Noted {
|
||||
values,
|
||||
own: lock(&self.own).next,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every `VkQueue`'s timeline reached the value `noted` holds for it, and every own
|
||||
/// submission numbered before `noted`'s completed.
|
||||
pub(crate) fn reached(&self, noted: &Noted) -> bool {
|
||||
let batches = (self.completed.iter())
|
||||
.zip(¬ed.values)
|
||||
.all(|(completed, noted)| completed.load(Ordering::SeqCst) >= *noted);
|
||||
batches
|
||||
&& lock(&self.own)
|
||||
.in_flight
|
||||
.first()
|
||||
.is_none_or(|first| *first >= noted.own)
|
||||
}
|
||||
|
||||
/// An own submission of `device`'s, from before its `vkQueueSubmit` until the guard drops,
|
||||
/// once its submitter saw it complete (or gave up on it).
|
||||
pub(crate) fn own_submission<'a>(&'a self, device: &'a Device) -> OwnSubmission<'a> {
|
||||
let mut own = lock(&self.own);
|
||||
let number = own.next;
|
||||
own.next += 1;
|
||||
own.in_flight.insert(number);
|
||||
OwnSubmission {
|
||||
parking: self,
|
||||
device,
|
||||
number,
|
||||
}
|
||||
}
|
||||
|
||||
/// One more block waits.
|
||||
pub(crate) fn waits(&self) {
|
||||
self.waiting.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// `count` blocks waited and are freed.
|
||||
pub(crate) fn freed(&self, count: usize) {
|
||||
self.waiting.fetch_sub(count, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// After the host saw a value of a queue's: where blocks wait and no release is posted, post
|
||||
/// one to a handler thread of `device`'s, which frees those whose values were reached.
|
||||
pub(crate) fn after_completion(&self, device: &Device) {
|
||||
if self.waiting.load(Ordering::SeqCst) == 0 || self.posted.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
device.let_go_elsewhere(Box::new(Unpark(device.clone())));
|
||||
}
|
||||
}
|
||||
|
||||
/// An own submission of the device's in flight ([`Parking::own_submission`]): as it drops, the
|
||||
/// blocks that waited for it alone may go, on a handler thread.
|
||||
pub(crate) struct OwnSubmission<'a> {
|
||||
parking: &'a Parking,
|
||||
device: &'a Device,
|
||||
number: u64,
|
||||
}
|
||||
|
||||
impl Drop for OwnSubmission<'_> {
|
||||
fn drop(&mut self) {
|
||||
lock(&self.parking.own).in_flight.remove(&self.number);
|
||||
self.parking.after_completion(self.device);
|
||||
}
|
||||
}
|
||||
|
||||
/// A block's memory waiting for the batches in flight as it went, and what goes after it.
|
||||
pub(crate) struct Parked {
|
||||
pub(crate) noted: Noted,
|
||||
pub(crate) memory: vk::DeviceMemory,
|
||||
/// What waits for the memory to be freed (a host import's deallocators and keep-alive).
|
||||
pub(crate) after: Option<Box<dyn Send>>,
|
||||
}
|
||||
|
||||
impl Parked {
|
||||
/// Free the memory: what waited for it, to let go of outside the exit guard's section the
|
||||
/// free runs in (it runs the program's code).
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The memory is `device`'s, nothing is placed in it, and every batch that may list it
|
||||
/// completed.
|
||||
pub(crate) unsafe fn release(self, device: &ash::Device) -> Option<Box<dyn Send>> {
|
||||
let Parked { memory, after, .. } = self;
|
||||
// SAFETY: the caller's.
|
||||
unsafe { crate::release::object(device, memory) };
|
||||
after
|
||||
}
|
||||
}
|
||||
|
||||
/// The release a queue's waiter posts ([`Parking::after_completion`]): on a handler thread, the
|
||||
/// blocks whose values were reached are freed, and what waited for them goes.
|
||||
struct Unpark(Device);
|
||||
|
||||
impl Drop for Unpark {
|
||||
fn drop(&mut self) {
|
||||
let shared = self.0.shared();
|
||||
let Some(parking) = shared.parking.get() else {
|
||||
return;
|
||||
};
|
||||
// Cleared first: a value published from here on posts another release.
|
||||
parking.posted.store(false, Ordering::SeqCst);
|
||||
// The frees are a section of the exit guard: while the process exits, the blocks stay
|
||||
// to its end (`exit_guard`).
|
||||
let Some(busy) = exit_guard::enter() else {
|
||||
return;
|
||||
};
|
||||
let reached = lock(&shared.memory).reached();
|
||||
let after: Vec<Box<dyn Send>> = (reached.into_iter())
|
||||
// SAFETY: its values were reached, so every batch that may list it completed.
|
||||
.filter_map(|parked| unsafe { parked.release(shared.vk()) })
|
||||
.collect();
|
||||
drop(busy);
|
||||
drop(after);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
impl Device {
|
||||
/// Let the memory's blocks that go from now on wait for the batches in flight, as where the
|
||||
/// driver has `FreedAddressMemoryFailsPendingWork`: the crate's tests' way to take that path
|
||||
/// on any device. Before the device's first batch.
|
||||
pub(crate) fn park_freed_memory(&self) {
|
||||
let shared = self.shared();
|
||||
let parking = shared
|
||||
.parking
|
||||
.get_or_init(|| std::sync::Arc::new(Parking::new(shared.queues.len())));
|
||||
lock(&shared.memory).park_by(std::sync::Arc::clone(parking));
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@
|
||||
|
||||
use super::device::lock;
|
||||
use super::error::Error;
|
||||
use super::key_hash::KeyMap;
|
||||
use super::render_pass::{AspectTarget, PassLayout, Target};
|
||||
use super::render_values::{LoadAction, StoreAction};
|
||||
use super::resolve::Resolve;
|
||||
@@ -62,7 +63,6 @@ use super::tracker::{Access, UseRange};
|
||||
use super::Device;
|
||||
use ash::vk::ImageAspectFlags;
|
||||
use metal2vulkan::vk::{Format, ImageType};
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Mutex;
|
||||
@@ -73,7 +73,7 @@ use std::sync::Mutex;
|
||||
pub(super) struct FreshUnwritten {
|
||||
/// Whether any texture is noted: without one, a command checks nothing.
|
||||
any: AtomicBool,
|
||||
textures: Mutex<HashMap<ResourceKey, Unwritten>>,
|
||||
textures: Mutex<KeyMap<ResourceKey, Unwritten>>,
|
||||
}
|
||||
|
||||
/// A noted texture: which texels of each aspect of its pattern levels' layers no write has
|
||||
@@ -568,6 +568,18 @@ fn pass_targets(
|
||||
(None, None) => None,
|
||||
};
|
||||
let by = |aspect: &Option<AspectTarget>, kept: bool, flag| match aspect {
|
||||
// A NaN clear depth written into the texture before the pass, which loads it
|
||||
// (`nan_clear.rs`), is the texture's clear.
|
||||
Some(a) if !kept && a.written_nan => {
|
||||
let aspect = Aspect {
|
||||
load: LoadAction::Clear,
|
||||
reaches: true,
|
||||
};
|
||||
match test(&aspect) {
|
||||
true => flag,
|
||||
false => ImageAspectFlags::empty(),
|
||||
}
|
||||
}
|
||||
Some(a) if !kept => {
|
||||
let aspect = Aspect {
|
||||
load: a.load,
|
||||
|
||||
@@ -559,6 +559,7 @@ fn record_total(
|
||||
uses: &[],
|
||||
blobs: Vec::new(),
|
||||
mesh: None,
|
||||
tessellation: None,
|
||||
};
|
||||
let mut uses = Vec::new();
|
||||
for p in &prepared {
|
||||
|
||||
@@ -6,35 +6,73 @@
|
||||
//! of Metal's times and `CACurrentMediaTime`; `CLOCK_MONOTONIC_RAW` elsewhere on Unix, its
|
||||
//! counterpart (monotonic, never slewed, stopped while the system sleeps). Other platforms count
|
||||
//! the runtime's own monotonic clock, which no device can calibrate against.
|
||||
//! - **GPU times.** The command buffer's first batch writes a timestamp at the top of its work,
|
||||
//! and its last batch one after the barrier that ends it (`command_buffer/submit.rs`), into a
|
||||
//! slot of two queries of one of the device's timestamp pools ([`Slot`]), which it takes at its
|
||||
//! commit.
|
||||
//! The completion thread reads the two once the command buffer completed, and gives the slot
|
||||
//! - **GPU times.** The command buffer's first batch writes a timestamp at the top of its work
|
||||
//! (after a barrier its first encoder waits behind for earlier work, once every command before
|
||||
//! it completed, where Metal's start follows such work's end), and its last batch one after the
|
||||
//! barrier that ends it (`command_buffer/submit.rs`), into a slot of one of the device's
|
||||
//! timestamp pools ([`Slot`]), which it takes as its first encoder opens where its slot holds
|
||||
//! the start that encoder writes (below), else at its commit.
|
||||
//! - **The start in the first encoder.** A slot holds three queries ([`PREFIXED`]) where the
|
||||
//! pools are not Metal counter sample buffers and the driver's submissions do not stall on
|
||||
//! semaphore operations: the start a command buffer of barriers writes, the end, and the start
|
||||
//! the first encoder's own command buffer writes as it opens, its first commands (its prefix:
|
||||
//! the reset of the end and that start, then the start at the top of the pipe). Where the batch
|
||||
//! plans no barrier before that encoder and its command buffer reaches the queue as recorded,
|
||||
//! the batch begins with no command buffer of its own, and the prefix's start is the command
|
||||
//! buffer's. It is the same place: either start is written at the top of the pipe, after every
|
||||
//! command submitted before the batch's work and before any of it. Elsewhere (a barrier planned
|
||||
//! there, a caller's image moved first, the encoder run again or not at all) a command buffer of
|
||||
//! barriers writes the first start before the barrier, as without a prefix, and that start is
|
||||
//! read; the prefix's is written after it and never read. A Metal counter sample buffer's slot
|
||||
//! holds the two alone ([`PLAIN`]), as does a slot where every batch with work starts with a
|
||||
//! command buffer of barriers anyway (`DriverFact::SemaphoreOperationsStallSubmits`,
|
||||
//! `command_buffer/submit.rs`), and its starts are the barriers'. The completion turn reads
|
||||
//! the start the batch took and the end once the command buffer completed, and gives the slot
|
||||
//! back. Their difference, in ticks of `timestampPeriod` nanoseconds, is exact on every device
|
||||
//! that writes timestamps.
|
||||
//! - **Pools made as needed**. Each pool holds [`SLOTS`] slots. The device makes its first at its
|
||||
//! first timed commit, and another whenever a command buffer is committed while every slot of the
|
||||
//! first timed command buffer, and another whenever one takes a slot while every slot of the
|
||||
//! ones it has is held, until the device refuses one: its own limit, which Vulkan states nowhere
|
||||
//! else (a pool is 4096 queries; the runtime bounds none, as Metal times every command buffer in
|
||||
//! flight). It releases them at its teardown. A commit asks the pool that gave the last slot
|
||||
//! first, and the others only when that one has none free: the pools are searched as one fills,
|
||||
//! not at every commit. On a driver whose pools are Metal counter sample buffers
|
||||
//! (`DriverFact::TimestampPoolsAreCounterSampleBuffers`: MoltenVK) it makes one, never more:
|
||||
//! Metal keeps at most 32 of those live per GPU, each of at most 4096 timestamps (measured
|
||||
//! through MoltenVK 1.4.1 on an M3 Max and an M4: the 33rd failed, as did a pool of 8192), so
|
||||
//! a pool per command buffer ran out with 32 command buffers in flight, and each pool more is
|
||||
//! one fewer for another device on the GPU. One pool of the most timestamps holds a slot for
|
||||
//! 2048 command buffers in flight. A command buffer committed while every slot is held and no
|
||||
//! pool more can be made has no timestamps: its GPU times are refused as on a device that
|
||||
//! writes none, and the device announces it once (`Degradation::UntimedCommandBuffer`).
|
||||
//! else (a pool is 6144 queries where a slot holds three, else 4096; the runtime bounds none,
|
||||
//! as Metal times every command buffer in flight). It releases them at its teardown. A slot is
|
||||
//! taken from the pool that gave the last one first, and the others only when that one has none
|
||||
//! free: the pools are searched as one fills, not for every slot. On a driver whose pools are Metal counter sample
|
||||
//! buffers (`DriverFact::TimestampPoolsAreCounterSampleBuffers`: MoltenVK) it makes one, of
|
||||
//! [`PLAIN`] queries a slot, never more: Metal keeps at most 32 of those live per GPU, each of
|
||||
//! at most 4096 timestamps (measured through MoltenVK 1.4.1 on an M3 Max and an M4: the 33rd
|
||||
//! failed, as did a pool of 8192), so a pool per command buffer ran out with 32 command buffers
|
||||
//! in flight, and each pool more is one fewer for another device on the GPU. One pool of the
|
||||
//! most timestamps holds a slot for 2048 command buffers in flight. A command buffer committed
|
||||
//! while every slot is held and no pool more can be made has no timestamps: its GPU times are
|
||||
//! refused as on a device that writes none, and the device announces it once
|
||||
//! (`Degradation::UntimedCommandBuffer`).
|
||||
//! Waiting for a slot instead could wait for work that needs the program to go on.
|
||||
//! - **Calibrated where the device can.** With `VK_KHR_calibrated_timestamps` (or its
|
||||
//! `VK_EXT_` form) and a host time domain the runtime can read (`CLOCK_MONOTONIC_RAW` or
|
||||
//! `CLOCK_MONOTONIC`), a pair of GPU and host readings taken at the commit places each
|
||||
//! timestamp on the host's clock, within the pair's stated deviation: Metal's answer. A domain
|
||||
//! that is not the host's clock is moved onto it by reading both clocks at once (MoltenVK's
|
||||
//! `CLOCK_MONOTONIC_RAW` is macOS's, which counts sleep; Metal's does not).
|
||||
//! `CLOCK_MONOTONIC_RAW` is macOS's, which counts sleep; Metal's does not). A pair is read again
|
||||
//! while each reading halves the deviation the one before it stated, [`READINGS`] at most, and
|
||||
//! the one of the smallest places the times ([`least_deviation`]). The specification leaves
|
||||
//! that to the application, which "can choose to re-issue the timestamp calibration call
|
||||
//! pursuing a lower deviation value" (`vkGetCalibratedTimestampsKHR`). A reading's two values
|
||||
//! may stand as far apart as it states. On an Iris Xe (ANV, Mesa 26.2.4, i915), the first
|
||||
//! reading after the GPU idled 100 ms stated 165 us at the median, and the device's timestamp
|
||||
//! in it was read that much after its host time: placed by it, every GPU time came 156 us early
|
||||
//! at the median (105 to 193 us over 200 readings). The reading after it stated 7.6 us and
|
||||
//! agreed with the next ones within 0.4 us.
|
||||
//! - **Checked against the command buffer's life.** A time the pair places is the GPU's, and the
|
||||
//! GPU ran the work between the first batch's submission (the kernel start) and the moment the
|
||||
//! completion turn saw it complete. A pair that places the start before that start, or the
|
||||
//! end after that completion, by more than its stated deviation and the clocks' drift since it
|
||||
//! ([`DRIFT_PPM`]) allow, disagrees with the device's own timestamps: the command buffer is
|
||||
//! placed as below, as on an uncalibrated device, counted
|
||||
//! (`WorkCounts::calibration_disagreements`) and announced once
|
||||
//! (`Degradation::UncalibratedGpuTimes`). A Radeon 780M (RADV PHOENIX, Mesa 26.0.8, Linux 7.0)
|
||||
//! after two MODE2 GPU resets wrote timestamp queries 65.15 s ahead of its own calibrated
|
||||
//! `DEVICE` domain, steadily, where an RX 7900 XTX beside it agreed within its deviation:
|
||||
//! placed by the pair, every GPU time came 65 s after its command buffer completed.
|
||||
//! - **Uncalibrated otherwise.** Without them, the end is placed at the host time the command
|
||||
//! buffer completed and the start the timestamps' difference before it: the duration exact,
|
||||
//! both times late by the completion's latency. The device announces it once
|
||||
@@ -51,7 +89,7 @@
|
||||
//! Max): on its own, a microsecond after its `kernelEndTime`; committed behind a 2.5-ms fill, 112
|
||||
//! us after the fill's `GPUEndTime`, 2.7 ms after its own `kernelEndTime`; waiting for an event
|
||||
//! the host signals, 7 us after the signal, its `kernelEndTime` 6 us after it. The completion
|
||||
//! thread places each command buffer as it completes, in its queue's order: each completed
|
||||
//! turn places each command buffer as it completes, in its queue's order: each completed
|
||||
//! command buffer moves its queue's latest GPU start and end. On MoltenVK the two timestamps cost
|
||||
//! such a command buffer about 150 us of latency (each is sampled in a blit pass of its own),
|
||||
//! against about 15 us without. One that waits keeps its timestamps: when the GPU passes a wait
|
||||
@@ -72,7 +110,7 @@
|
||||
//! `GPUEndTime` count on Apple's GPUs.
|
||||
//! 2. **Inside the command buffer's life.** Its commit <= `kernelStartTime` <= `kernelEndTime`
|
||||
//! <= `GPUStartTime` <= `GPUEndTime` <= the moment its completion is observable: the end is
|
||||
//! read on the completion thread before the command buffer's status becomes `Completed`
|
||||
//! read in the completion turn before the command buffer's status becomes `Completed`
|
||||
//! and before its completed handlers run, and the start is never later than the end.
|
||||
//! 3. **A serial queue.** In a queue's commit order, which is the order its command buffers
|
||||
//! complete and are placed in (`command_buffer/completion.rs`), each one's GPU start is at
|
||||
@@ -98,22 +136,41 @@
|
||||
|
||||
use super::device::lock;
|
||||
use super::release;
|
||||
use super::work_counts::Counters;
|
||||
use ash::vk;
|
||||
use std::collections::BTreeSet;
|
||||
use std::ffi::{c_char, CStr, CString};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The longest a device's calibration pair serves the commits after it.
|
||||
pub(crate) const REFRESH: Duration = Duration::from_millis(100);
|
||||
|
||||
/// The slots of each of a device's timestamp pools, two queries each: 4096 timestamps, the most
|
||||
/// one Metal counter sample buffer holds (the module documentation).
|
||||
/// The most readings one calibration pair takes ([`least_deviation`]).
|
||||
pub(crate) const READINGS: u32 = 4;
|
||||
|
||||
/// How far apart, in parts per million of the time since a pair, the GPU's clock and the host's
|
||||
/// may drift before a placed time counts as disagreeing with the command buffer's life (the module
|
||||
/// docs): above a crystal's tolerance, and NTP's own slew limit, so that a sound pair never trips
|
||||
/// the check, and far below a disagreement that places a time seconds away.
|
||||
pub(crate) const DRIFT_PPM: u64 = 500;
|
||||
|
||||
/// The slots of each of a device's timestamp pools: of [`PLAIN`] queries each where its pools are
|
||||
/// Metal counter sample buffers, 4096 timestamps, the most one holds (the module documentation).
|
||||
pub(crate) const SLOTS: u32 = 2048;
|
||||
|
||||
/// The queries of a slot where the pools are not Metal counter sample buffers: the start a
|
||||
/// command buffer of barriers writes, the end, and the start the first encoder writes (the module
|
||||
/// documentation).
|
||||
pub(crate) const PREFIXED: u32 = 3;
|
||||
|
||||
/// The queries of a slot where the pools are Metal counter sample buffers: the start and the end.
|
||||
pub(crate) const PLAIN: u32 = 2;
|
||||
|
||||
/// The most timestamps MoltenVK made one Metal counter sample buffer of, on an M3 Max and an M4.
|
||||
const SAMPLE_BUFFER_TIMESTAMPS: u32 = 4096;
|
||||
const _: () = assert!(2 * SLOTS <= SAMPLE_BUFFER_TIMESTAMPS);
|
||||
const _: () = assert!(PLAIN * SLOTS <= SAMPLE_BUFFER_TIMESTAMPS);
|
||||
|
||||
/// The host time now, in seconds of the clock the runtime's GPU and kernel times count (the
|
||||
/// module documentation): `CLOCK_UPTIME_RAW` on macOS, which `mach_absolute_time` and
|
||||
@@ -221,6 +278,60 @@ pub(crate) struct Pair {
|
||||
pub(crate) host: u64,
|
||||
}
|
||||
|
||||
/// A calibration reading: its pair, and how far apart, in nanoseconds, its two values may stand:
|
||||
/// the deviation the call stated, and for a host domain that is not the host's clock, the span
|
||||
/// of the host's readings around the domain's.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Reading {
|
||||
pub(crate) pair: Pair,
|
||||
pub(crate) deviation: u64,
|
||||
}
|
||||
|
||||
/// A command buffer's life on the host's clock, in nanoseconds: from the moment the scheduler
|
||||
/// began submitting its first batch to the moment a completion turn saw its last complete.
|
||||
/// Its GPU work ran inside it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Life {
|
||||
pub(crate) kernel_start: u64,
|
||||
pub(crate) completed: u64,
|
||||
}
|
||||
|
||||
/// How a command buffer's timestamps were placed on the host's clock ([`GpuClock::span`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Placement {
|
||||
/// By the device's calibration pair.
|
||||
Calibrated,
|
||||
/// By its completion: the device had no pair at its commit.
|
||||
Uncalibrated,
|
||||
/// By its completion: the pair placed a time outside its life by `by` nanoseconds, more than
|
||||
/// the pair's stated `deviation` and the clocks' drift allow (the module docs).
|
||||
Disagreed { by: u64, deviation: u64 },
|
||||
}
|
||||
|
||||
/// Of the readings `read` gives, the one of the smallest deviation, and how many `read` was
|
||||
/// called for: one more while the latest halved the deviation the one before it stated,
|
||||
/// [`READINGS`] at most (the module docs). `None` where the first fails; a later failure ends
|
||||
/// them.
|
||||
pub(crate) fn least_deviation(mut read: impl FnMut() -> Option<Reading>) -> Option<(Reading, u32)> {
|
||||
let mut least = read()?;
|
||||
let mut previous = least.deviation;
|
||||
let mut calls = 1;
|
||||
while calls < READINGS {
|
||||
calls += 1;
|
||||
let Some(next) = read() else {
|
||||
break;
|
||||
};
|
||||
if next.deviation < least.deviation {
|
||||
least = next;
|
||||
}
|
||||
if next.deviation.saturating_mul(2) > previous {
|
||||
break;
|
||||
}
|
||||
previous = next.deviation;
|
||||
}
|
||||
Some((least, calls))
|
||||
}
|
||||
|
||||
impl GpuClock {
|
||||
/// The clock of a queue family with `valid_bits` timestamp bits and `period` nanoseconds
|
||||
/// per tick; `None` where the family writes no timestamps.
|
||||
@@ -236,9 +347,15 @@ impl GpuClock {
|
||||
})
|
||||
}
|
||||
|
||||
/// A calibrated pair now, where the device has calibration and the readings succeed.
|
||||
pub(crate) fn pair(&self) -> Option<Pair> {
|
||||
/// A calibrated pair now, where the device has calibration and the readings succeed: the
|
||||
/// reading of the smallest deviation ([`least_deviation`]), and how many readings it took.
|
||||
pub(crate) fn pair(&self) -> Option<(Reading, u32)> {
|
||||
let calibration = self.calibration?;
|
||||
least_deviation(|| self.reading(calibration))
|
||||
}
|
||||
|
||||
/// One reading of `calibration`, where it succeeds.
|
||||
fn reading(&self, calibration: Calibration) -> Option<Reading> {
|
||||
let infos = [
|
||||
vk::CalibratedTimestampInfoKHR::default().time_domain(vk::TimeDomainKHR::DEVICE),
|
||||
vk::CalibratedTimestampInfoKHR::default().time_domain(calibration.domain),
|
||||
@@ -264,19 +381,23 @@ impl GpuClock {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
// The domain's clock onto the host's: both read at once, the host's around it.
|
||||
let host = if domain == BASE {
|
||||
values[1]
|
||||
let (host, around) = if domain == BASE {
|
||||
(values[1], 0)
|
||||
} else {
|
||||
let first = read_clock(BASE)?;
|
||||
let during = read_clock(domain)?;
|
||||
let last = read_clock(BASE)?;
|
||||
let middle = first + last.saturating_sub(first) / 2;
|
||||
let offset = i128::from(middle) - i128::from(during);
|
||||
u64::try_from(i128::from(values[1]) + offset).ok()?
|
||||
let host = u64::try_from(i128::from(values[1]) + offset).ok()?;
|
||||
(host, last.saturating_sub(first))
|
||||
};
|
||||
Some(Pair {
|
||||
ticks: values[0],
|
||||
host,
|
||||
Some(Reading {
|
||||
pair: Pair {
|
||||
ticks: values[0],
|
||||
host,
|
||||
},
|
||||
deviation: deviation.saturating_add(around),
|
||||
})
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
@@ -293,22 +414,38 @@ impl GpuClock {
|
||||
}
|
||||
|
||||
/// The host times, in nanoseconds of the host's clock, of a command buffer's timestamps
|
||||
/// `start` and `end`: placed by `pair` where calibrated, else ending at `completed`, the
|
||||
/// host time its completion was seen, and starting their duration before.
|
||||
/// `start` and `end`, and how they were placed: by `reading`'s pair where they lie inside the
|
||||
/// command buffer's `life` within the reading's deviation and the clocks' drift since it
|
||||
/// ([`DRIFT_PPM`]); else, and without a reading, ending where `life` ends, the host time its
|
||||
/// completion was seen, and starting their duration before (the module docs).
|
||||
pub(crate) fn span(
|
||||
&self,
|
||||
pair: Option<Pair>,
|
||||
reading: Option<Reading>,
|
||||
start: u64,
|
||||
end: u64,
|
||||
completed: u64,
|
||||
) -> (u64, u64) {
|
||||
match pair {
|
||||
Some(pair) => (self.place(pair, start), self.place(pair, end)),
|
||||
None => (
|
||||
completed.saturating_sub(self.duration(start, end)),
|
||||
completed,
|
||||
),
|
||||
life: Life,
|
||||
) -> ((u64, u64), Placement) {
|
||||
let by_completion = (
|
||||
life.completed.saturating_sub(self.duration(start, end)),
|
||||
life.completed,
|
||||
);
|
||||
let Some(Reading { pair, deviation }) = reading else {
|
||||
return (by_completion, Placement::Uncalibrated);
|
||||
};
|
||||
let placed = (self.place(pair, start), self.place(pair, end));
|
||||
// How far each may stand from the truth: the deviation the pair stated, and the drift
|
||||
// since the pair to the bound it is checked against.
|
||||
let allowed = |bound: u64| {
|
||||
let drift = bound.abs_diff(pair.host).saturating_mul(DRIFT_PPM) / 1_000_000;
|
||||
deviation.saturating_add(drift)
|
||||
};
|
||||
let early = life.kernel_start.saturating_sub(placed.0);
|
||||
let late = placed.1.saturating_sub(life.completed);
|
||||
if early > allowed(life.kernel_start) || late > allowed(life.completed) {
|
||||
let by = early.max(late);
|
||||
return (by_completion, Placement::Disagreed { by, deviation });
|
||||
}
|
||||
(placed, Placement::Calibrated)
|
||||
}
|
||||
|
||||
/// The nanoseconds from timestamp `start` to `end`.
|
||||
@@ -405,7 +542,9 @@ impl FromHost {
|
||||
pub(crate) struct Timing {
|
||||
clock: Option<GpuClock>,
|
||||
from_host: Option<FromHost>,
|
||||
latest: Mutex<Option<(Instant, Pair)>>,
|
||||
latest: Mutex<Option<(Instant, Reading)>>,
|
||||
/// Its slots hold the start the first encoder writes ([`PREFIXED`]).
|
||||
prefixed: bool,
|
||||
pools: Mutex<Pools>,
|
||||
}
|
||||
|
||||
@@ -418,23 +557,26 @@ pub(crate) struct Pools {
|
||||
/// One on a driver whose pools are Metal counter sample buffers; else none until the device
|
||||
/// refuses a pool, then the pools it made.
|
||||
most: Option<usize>,
|
||||
/// The queries of each slot: [`PREFIXED`] or [`PLAIN`].
|
||||
per_slot: u32,
|
||||
}
|
||||
|
||||
impl Pools {
|
||||
/// No pool yet, and at most `most` to be made where given.
|
||||
pub(crate) fn new(most: Option<usize>) -> Pools {
|
||||
/// No pool yet, and at most `most` to be made where given, each slot of `per_slot` queries.
|
||||
pub(crate) fn new(most: Option<usize>, per_slot: u32) -> Pools {
|
||||
Pools {
|
||||
made: Vec::new(),
|
||||
at: 0,
|
||||
most,
|
||||
per_slot,
|
||||
}
|
||||
}
|
||||
|
||||
/// A free slot of a pool made, the one that gave the last slot asked first, else of a pool
|
||||
/// `make` makes now where the device has made fewer than its most; `None` when every slot is
|
||||
/// held and no pool more can be made. A pool `make` cannot make (`None`) ends the making: the
|
||||
/// device makes no more.
|
||||
pub(crate) fn take(&mut self, make: impl FnOnce() -> Option<vk::QueryPool>) -> Option<Slot> {
|
||||
/// `make` makes now of the queries it is given where the device has made fewer than its most;
|
||||
/// `None` when every slot is held and no pool more can be made. A pool `make` cannot make
|
||||
/// (`None`) ends the making: the device makes no more.
|
||||
pub(crate) fn take(&mut self, make: impl FnOnce(u32) -> Option<vk::QueryPool>) -> Option<Slot> {
|
||||
let count = self.made.len();
|
||||
for step in 0..count {
|
||||
let at = (self.at + step) % count;
|
||||
@@ -446,11 +588,11 @@ impl Pools {
|
||||
if self.most.is_some_and(|most| count >= most) {
|
||||
return None;
|
||||
}
|
||||
let Some(queries) = make() else {
|
||||
let Some(queries) = make(self.per_slot * SLOTS) else {
|
||||
self.most = Some(count);
|
||||
return None;
|
||||
};
|
||||
self.made.push(Pool::new(queries, SLOTS));
|
||||
self.made.push(Pool::new(queries, SLOTS, self.per_slot));
|
||||
self.at = count;
|
||||
self.made.last()?.take()
|
||||
}
|
||||
@@ -471,15 +613,22 @@ impl Pools {
|
||||
pub(crate) struct Pool {
|
||||
queries: vk::QueryPool,
|
||||
free: Arc<Mutex<Vec<u32>>>,
|
||||
/// The slots taken so far: each take's lease is the count after it.
|
||||
leases: AtomicU64,
|
||||
/// The queries of each slot.
|
||||
per_slot: u32,
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
/// The `slots` slots of `queries`, a pool of `2 * slots` timestamp queries, every one free.
|
||||
pub(crate) fn new(queries: vk::QueryPool, slots: u32) -> Pool {
|
||||
/// The `slots` slots of `queries`, a pool of `per_slot * slots` timestamp queries, every one
|
||||
/// free.
|
||||
pub(crate) fn new(queries: vk::QueryPool, slots: u32, per_slot: u32) -> Pool {
|
||||
Pool {
|
||||
queries,
|
||||
// Popped from the end: slot 0 first.
|
||||
free: Arc::new(Mutex::new((0..slots).rev().collect())),
|
||||
leases: AtomicU64::new(0),
|
||||
per_slot,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -489,18 +638,27 @@ impl Pool {
|
||||
Some(Slot {
|
||||
queries: self.queries,
|
||||
index,
|
||||
per_slot: self.per_slot,
|
||||
lease: self.leases.fetch_add(1, Ordering::Relaxed) + 1,
|
||||
free: Arc::clone(&self.free),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A slot of one of its device's timestamp pools: two queries, a command buffer's start and end.
|
||||
/// The command buffer holds it from its commit until the completion thread read them; dropping
|
||||
/// it gives it back.
|
||||
/// A slot of one of its device's timestamp pools: a command buffer's start and end, and where it
|
||||
/// has three queries, the start its first encoder writes (the module docs). The command buffer
|
||||
/// holds it from its first encoder's opening, or its commit, until the completion turn read
|
||||
/// them; dropping it gives it back.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Slot {
|
||||
queries: vk::QueryPool,
|
||||
index: u32,
|
||||
per_slot: u32,
|
||||
/// This holding of the slot: above every earlier holding's of its pool. A slot is taken again
|
||||
/// only once given back, so a holding of a slot with a higher lease began after every lower
|
||||
/// one's command buffer had its timestamps read, or failed (`command_buffer/kept_barriers.rs`
|
||||
/// takes a kept command buffer that writes the slot's queries again only then).
|
||||
lease: u64,
|
||||
free: Arc<Mutex<Vec<u32>>>,
|
||||
}
|
||||
|
||||
@@ -510,9 +668,20 @@ impl Slot {
|
||||
self.queries
|
||||
}
|
||||
|
||||
/// Its first query, the start; the end is the next.
|
||||
/// Its first query, the start a command buffer of barriers writes; the end is the next.
|
||||
pub(crate) fn first(&self) -> u32 {
|
||||
self.index * 2
|
||||
self.index * self.per_slot
|
||||
}
|
||||
|
||||
/// The query of the start its command buffer's first encoder writes, where it has one (the
|
||||
/// module docs): after the end's.
|
||||
pub(crate) fn prefix(&self) -> Option<u32> {
|
||||
(self.per_slot == PREFIXED).then(|| self.first() + 2)
|
||||
}
|
||||
|
||||
/// This holding's lease (the field's docs).
|
||||
pub(crate) fn lease(&self) -> u64 {
|
||||
self.lease
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,7 +699,8 @@ impl Timing {
|
||||
/// times from the host and writes no timestamps (the module docs), for that reason. With
|
||||
/// `scarce_pools` (`DriverFact::TimestampPoolsAreCounterSampleBuffers`) it makes one
|
||||
/// timestamp pool at most, else as many as its command buffers in flight need until the
|
||||
/// device refuses one.
|
||||
/// device refuses one. With `prefixed`, a slot also holds the start its command buffer's
|
||||
/// first encoder writes ([`PREFIXED`] queries; else [`PLAIN`]); never with `scarce_pools`.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
@@ -546,6 +716,7 @@ impl Timing {
|
||||
extension: Option<Extension>,
|
||||
from_host: Option<FromHost>,
|
||||
scarce_pools: bool,
|
||||
prefixed: bool,
|
||||
) -> Timing {
|
||||
// SAFETY: the caller's.
|
||||
let calibration = extension.and_then(|extension| unsafe {
|
||||
@@ -555,11 +726,22 @@ impl Timing {
|
||||
clock: GpuClock::new(valid_bits, period, calibration),
|
||||
from_host,
|
||||
latest: Mutex::new(None),
|
||||
pools: Mutex::new(Pools::new(scarce_pools.then_some(1))),
|
||||
prefixed: prefixed && !scarce_pools,
|
||||
pools: Mutex::new(match (scarce_pools, prefixed) {
|
||||
(true, _) => Pools::new(Some(1), PLAIN),
|
||||
(false, true) => Pools::new(None, PREFIXED),
|
||||
(false, false) => Pools::new(None, PLAIN),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// A slot for a command buffer committed now, from the device's pools, a pool made where
|
||||
/// Whether its slots hold the start a command buffer's first encoder writes as it opens (the
|
||||
/// module docs): its command buffers take their slots then.
|
||||
pub(crate) fn prefixed(&self) -> bool {
|
||||
self.prefixed
|
||||
}
|
||||
|
||||
/// A slot for a timed command buffer, from the device's pools, a pool made where
|
||||
/// every slot of the ones made is held ([`Pools::take`]); `None` where the device writes no
|
||||
/// timestamps, or every slot is held and no pool more can be made.
|
||||
///
|
||||
@@ -568,10 +750,10 @@ impl Timing {
|
||||
/// `device` is the live device of this timing.
|
||||
pub(crate) unsafe fn slot(&self, device: &ash::Device) -> Option<Slot> {
|
||||
self.clock.as_ref()?;
|
||||
lock(&self.pools).take(|| {
|
||||
lock(&self.pools).take(|count| {
|
||||
let info = vk::QueryPoolCreateInfo::default()
|
||||
.query_type(vk::QueryType::TIMESTAMP)
|
||||
.query_count(2 * SLOTS);
|
||||
.query_count(count);
|
||||
// SAFETY: the caller's; `info` is valid.
|
||||
unsafe { device.create_query_pool(&info, None) }.ok()
|
||||
})
|
||||
@@ -610,20 +792,22 @@ impl Timing {
|
||||
self.from_host
|
||||
}
|
||||
|
||||
/// The device's latest calibration pair, taken now when the last is [`REFRESH`] old or
|
||||
/// there is none; `None` where the device has no calibration or the reading fails.
|
||||
pub(crate) fn pair(&self) -> Option<Pair> {
|
||||
/// The device's latest calibration reading, its pair and stated deviation, taken now when
|
||||
/// the last is [`REFRESH`] old or there is none, and counted in `counts`; `None` where the
|
||||
/// device has no calibration or the reading fails.
|
||||
pub(crate) fn pair(&self, counts: &Counters) -> Option<Reading> {
|
||||
let clock = self.clock.as_ref()?;
|
||||
clock.calibration?;
|
||||
let mut latest = lock(&self.latest);
|
||||
if let Some((at, pair)) = *latest {
|
||||
if let Some((at, reading)) = *latest {
|
||||
if at.elapsed() < REFRESH {
|
||||
return Some(pair);
|
||||
return Some(reading);
|
||||
}
|
||||
}
|
||||
let pair = clock.pair()?;
|
||||
*latest = Some((Instant::now(), pair));
|
||||
Some(pair)
|
||||
let (reading, readings) = clock.pair()?;
|
||||
counts.calibrated(readings, reading.deviation);
|
||||
*latest = Some((Instant::now(), reading));
|
||||
Some(reading)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -683,23 +867,26 @@ unsafe fn calibration(
|
||||
/// until known.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Times {
|
||||
/// Its slot of the device's timestamp pool, from its commit until the completion thread read
|
||||
/// its timestamps.
|
||||
/// Its slot of the device's timestamp pool, from its first encoder's opening (or its commit)
|
||||
/// until the completion turn read its timestamps.
|
||||
pub(crate) slot: Option<Slot>,
|
||||
/// Its first batch wrote the start into the slot's third query alone, the first encoder's
|
||||
/// prefix (the module docs): the start read is that one, not the first.
|
||||
pub(crate) prefixed: bool,
|
||||
/// What its timestamps gave.
|
||||
pub(crate) stamped: Stamped,
|
||||
/// The device's calibration pair at its commit, where the device has one.
|
||||
pub(crate) pair: Option<Pair>,
|
||||
/// The device's calibration reading at its commit, where the device has one.
|
||||
pub(crate) pair: Option<Reading>,
|
||||
/// The scheduler began submitting its first batch.
|
||||
pub(crate) kernel_start: u64,
|
||||
/// The scheduler finished submitting its last batch.
|
||||
pub(crate) kernel_end: u64,
|
||||
/// The completion thread saw its last batch complete.
|
||||
/// A completion turn saw its last batch complete.
|
||||
pub(crate) completed: u64,
|
||||
/// Its GPU start and end, once read.
|
||||
pub(crate) gpu: Option<(u64, u64)>,
|
||||
/// Its GPU start and end where it wrote no timestamps: placed among its queue's command
|
||||
/// buffers by the completion thread as it completed.
|
||||
/// buffers by the completion turn as it completed.
|
||||
pub(crate) placed: Option<(u64, u64)>,
|
||||
}
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ use super::buffer::{buffer_class, Buffer, Modes, WeakBuffer};
|
||||
use super::device::lock;
|
||||
use super::error::{invalid, nil, Error, MemoryKind, Problem, RuntimeGap};
|
||||
use super::host_memory::{Deallocator, HostMemory, HostRelease, KeepAlive};
|
||||
use super::key_hash::KeyMap;
|
||||
use super::range::RangeAllocator;
|
||||
use super::resource::{ObjectId, ResourceKey};
|
||||
use super::sparse::heap::SparseHeap;
|
||||
@@ -66,7 +67,6 @@ use super::texture::{Texture, TextureShared};
|
||||
use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode};
|
||||
use super::Device;
|
||||
use metal2vulkan::device::AllocationLimits;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
@@ -316,7 +316,7 @@ impl Drop for HeapShared {
|
||||
/// their uses' keys (`EncoderCore::end_with_replay`).
|
||||
#[derive(Default)]
|
||||
pub(super) struct HeapKeys {
|
||||
heaps: Mutex<HashMap<ResourceKey, Weak<HeapShared>>>,
|
||||
heaps: Mutex<KeyMap<ResourceKey, Weak<HeapShared>>>,
|
||||
}
|
||||
|
||||
impl HeapKeys {
|
||||
@@ -535,10 +535,7 @@ impl Device {
|
||||
deallocator: Option<Deallocator>,
|
||||
keep_alive: Option<KeepAlive>,
|
||||
) -> Result<Heap, Error> {
|
||||
let release = HostRelease {
|
||||
deallocator,
|
||||
keep_alive,
|
||||
};
|
||||
let release = HostRelease::new(deallocator, keep_alive);
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { self.no_copy_heap_with_token(memory, descriptor, release, None) }
|
||||
}
|
||||
@@ -558,10 +555,7 @@ impl Device {
|
||||
keep_alive: Option<KeepAlive>,
|
||||
token: RangeToken,
|
||||
) -> Result<Heap, Error> {
|
||||
let release = HostRelease {
|
||||
deallocator,
|
||||
keep_alive,
|
||||
};
|
||||
let release = HostRelease::new(deallocator, keep_alive);
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { self.no_copy_heap_with_token(memory, descriptor, release, Some(token)) }
|
||||
}
|
||||
@@ -952,8 +946,8 @@ impl Heap {
|
||||
/// `newBufferWithLength:options:offset:` of a placement heap: a buffer of `length` bytes
|
||||
/// `offset` bytes into the heap. Its bytes are the heap's as they are: a buffer over bytes
|
||||
/// another wrote reads them. A length of 0 makes a buffer of no bytes at `offset`, as plain
|
||||
/// Metal makes it where its validation stops it (RT7 heap probe `length_zero`: length and
|
||||
/// `allocatedSize` 0).
|
||||
/// Metal makes it where its validation stops it (Metal heap probe `length_zero` on an M4:
|
||||
/// length and `allocatedSize` 0).
|
||||
///
|
||||
/// Refused: a length past the device's `max_buffer_length` (`Problem::BufferLength`), an
|
||||
/// offset that is not a multiple of 256 (`HeapProblem::Offset`), bytes past the heap's end
|
||||
|
||||
@@ -27,8 +27,10 @@
|
||||
//! hold and release: a command buffer lists and holds, and marks reached unnamed
|
||||
//! (`live_buffers.rs`), the buffers its commands use, not their memory, as Metal marks them
|
||||
//! (EV `IOS-pairreach1-m4`); its deallocator runs once nothing holds its pages, as an import
|
||||
//! of its own would let it, while the import lives on in the buffers that still lie in it. Copies between two such buffers are copies within
|
||||
//! one `VkBuffer`, moved as within one buffer (`blit.rs`, `blit_texture.rs`).
|
||||
//! of its own would let it, while the import lives on in the buffers that still lie in it, and
|
||||
//! its keep-alive goes then too, since those buffers keep the same bytes mapped (`buffer.rs`'s
|
||||
//! `HostPages`). Copies between two such buffers are copies within one `VkBuffer`, moved as
|
||||
//! within one buffer (`blit.rs`, `blit_texture.rs`).
|
||||
//! - **Ownership stays the buffer's.** The added uses are hazard tracking's alone: what a command
|
||||
//! holds and lists (`EncoderCore::touch`, rebind holds, `used_resources`) is named by the
|
||||
//! command's own uses, each buffer by its own key.
|
||||
@@ -75,10 +77,11 @@
|
||||
|
||||
use super::buffer::HostImport;
|
||||
use super::device::lock;
|
||||
use super::key_hash::KeyMap;
|
||||
use super::memory::MemoryClass;
|
||||
use super::resource::ResourceKey;
|
||||
use super::tracker::{Use, UseRange};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
@@ -108,7 +111,7 @@ impl<I> Default for HostAliases<I> {
|
||||
crowded: AtomicBool::new(false),
|
||||
noted: AtomicUsize::new(0),
|
||||
inner: Mutex::new(Inner {
|
||||
made_over: HashMap::new(),
|
||||
made_over: KeyMap::default(),
|
||||
memories: Memories::default(),
|
||||
aliases: Arc::default(),
|
||||
serial: 0,
|
||||
@@ -120,12 +123,12 @@ impl<I> Default for HostAliases<I> {
|
||||
|
||||
struct Inner<I> {
|
||||
/// The memory each live buffer was made over, by its key, until it leaves it.
|
||||
made_over: HashMap<ResourceKey, Over>,
|
||||
made_over: KeyMap<ResourceKey, Over>,
|
||||
/// Each memory with a live buffer made over it, by its first byte's host address and its
|
||||
/// length.
|
||||
memories: Memories<Memory<I>>,
|
||||
/// The buffers that joined a memory, by their key: a snapshot each command reads.
|
||||
aliases: Arc<HashMap<ResourceKey, Alias>>,
|
||||
aliases: Arc<KeyMap<ResourceKey, Alias>>,
|
||||
/// The serial of the memory noted last.
|
||||
serial: u64,
|
||||
/// The bytes each buffer over host pages lies over now.
|
||||
@@ -324,7 +327,7 @@ fn release<I>(memories: &mut Memories<Memory<I>>, over: Over) {
|
||||
|
||||
/// [`HostAliases::augment`] over `aliases` and, where given, `placements`.
|
||||
pub(super) fn augmented(
|
||||
aliases: &HashMap<ResourceKey, Alias>,
|
||||
aliases: &KeyMap<ResourceKey, Alias>,
|
||||
placements: Option<&Placements>,
|
||||
uses: &[Use<ResourceKey>],
|
||||
) -> Option<Vec<Use<ResourceKey>>> {
|
||||
@@ -366,7 +369,7 @@ pub(super) fn augmented(
|
||||
#[derive(Default)]
|
||||
pub(super) struct Placements {
|
||||
/// Each placed key's bytes: their first byte's host address and their length.
|
||||
at: HashMap<ResourceKey, (u64, u64)>,
|
||||
at: KeyMap<ResourceKey, (u64, u64)>,
|
||||
/// Each range of bytes some key lies over, by its first byte's address and its length.
|
||||
ranges: Memories<Placed>,
|
||||
/// How many ranges are crowded ([`Placed::crowded`]).
|
||||
|
||||
@@ -52,8 +52,15 @@
|
||||
//! reference goes: after the imported memory is freed, on the thread that drops it. A committed
|
||||
//! command buffer holds the buffer until it completed and its completed handlers ran, so then it
|
||||
//! runs on one of the device's handler threads, in the command buffer's queue's context, after
|
||||
//! the GPU's last use, as Metal's runs on one of its threads. A
|
||||
//! refused call never runs it.
|
||||
//! the GPU's last use, as Metal's runs on one of its threads: what its commands retained and its
|
||||
//! encoders' logs (`replay.rs`) go in its release, and no thread that submits command buffers
|
||||
//! or sees them complete holds a handle past it (`exit_guard::program_release`). One released
|
||||
//! while only command buffers not yet submitted reach it unnamed goes at once, as Metal's does
|
||||
//! (it runs in the release, on the releasing thread, while such a command buffer waits
|
||||
//! committed: probe `dealloc-probe3`, the M3 Max under macOS 27.0.1): on the releasing thread,
|
||||
//! or, where such a command buffer's root table held it until its first submission (a rebind's
|
||||
//! encoding again), on a handler thread then (`command_buffer/first_submission.rs`). A refused
|
||||
//! call never runs it.
|
||||
//! - **A keep-alive** ([`KeepAlive`]). The import can outlive the buffer: a texture over the buffer
|
||||
//! that a command buffer submitted before its release may still read through its resource ID
|
||||
//! keeps its image, and the image the import, until that command buffer completes
|
||||
@@ -63,7 +70,13 @@
|
||||
//! deallocator runs at the release, as Metal's does, and the keep-alive is dropped once the
|
||||
//! import is freed: the pages must stay mapped until then. A buffer over the bytes another
|
||||
//! live buffer lies in shares its import (`host_aliases.rs`), whose pages that buffer's
|
||||
//! contract keeps mapped: its deallocator runs at its release either way.
|
||||
//! contract keeps mapped: its deallocator runs at its release either way, and so is its
|
||||
//! keep-alive dropped, after the deallocator. So is the keep-alive of a buffer whose import
|
||||
//! keeps another's already: every buffer in an import was made over the same bytes, so one
|
||||
//! keep-alive keeps them mapped for all, and an import keeps one at most, however many buffers
|
||||
//! come and go over its bytes while it lives (a consumer's buffer over a surface made at each
|
||||
//! present and released after the next one's). Counted: `WorkCounts::host_keep_alives_kept`
|
||||
//! (held now) and `WorkCounts::host_keep_alives_covered` (dropped at the release).
|
||||
|
||||
use super::device::lock;
|
||||
#[cfg(unix)]
|
||||
@@ -71,6 +84,7 @@ use super::dma_buf::DmaBufSource;
|
||||
use super::error::{vulkan, Error};
|
||||
use super::exit_guard;
|
||||
use super::loader_word::LoaderWord;
|
||||
use super::program_objects::ProgramObject;
|
||||
use ash::vk;
|
||||
use metal2vulkan::device::{EnableSet, VkExtension};
|
||||
use metal2vulkan::error::{Feature, Unsupported};
|
||||
@@ -159,6 +173,17 @@ impl HostMemory {
|
||||
/// refuses the pointer of `memfd` and other shared mappings and imports `udmabuf`s of their
|
||||
/// pages; NVIDIA and lavapipe import the pointer and never call the source.
|
||||
///
|
||||
/// A no-copy buffer's own import of the chunks (not a heap's or a rebind's) may be released
|
||||
/// while idle, because RADV lists every import in every submission. The release frees its
|
||||
/// `VkBuffer` and memory and keeps the chunks open: the runtime keeps a duplicate descriptor of
|
||||
/// each, within a quarter of the process's `RLIMIT_NOFILE` soft limit. The next blit imports
|
||||
/// them again, on the thread that encodes it, which costs time then. Only a buffer that blits
|
||||
/// alone have read is released. One whose `gpu_address` or `VkBuffer` was handed out, or with a
|
||||
/// texture over its bytes, stays imported. Nothing of Metal's observes the release: the bytes,
|
||||
/// the address and the pages stay, the CPU's writes made meanwhile are read, and the source is
|
||||
/// not called again. A blit that finds the device unable to import the chunks again (out of
|
||||
/// memory) is refused.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// [`HostMemory::new`]'s contract for the bytes at `pointer`, holding while the chunks are
|
||||
@@ -186,26 +211,40 @@ impl HostMemory {
|
||||
}
|
||||
|
||||
/// A no-copy buffer's deallocator (Metal's block): called once, with the pointer and the length,
|
||||
/// when the buffer is released. It may run on a runtime thread, as Metal's runs on any thread. A
|
||||
/// panic inside it is caught.
|
||||
/// when the buffer is released. It may run on a runtime thread, as Metal's runs on any thread: a
|
||||
/// command buffer's queue's handler thread, where that command buffer's release lets go of the
|
||||
/// buffer, never a thread that submits command buffers or sees them complete. A panic inside it
|
||||
/// is caught.
|
||||
pub type Deallocator = Box<dyn FnOnce(NonNull<u8>, u64) + Send + 'static>;
|
||||
|
||||
/// What keeps the caller's host memory mapped (a runtime extension: Metal has none): given with a
|
||||
/// no-copy buffer's or heap's memory, it is dropped once the device's import of the pages is
|
||||
/// freed, which may be after the deallocator ran. With one, the deallocator runs when the buffer
|
||||
/// freed, which may be after the deallocator ran, or at the buffer's release, after its
|
||||
/// deallocator, where the import's pages stay mapped without it: another buffer made over the
|
||||
/// same bytes lies in the import, or the import keeps such a buffer's keep-alive already (the
|
||||
/// module docs). With one, the deallocator runs when the buffer
|
||||
/// is released, as Metal's does, though a command buffer submitted before a texture over the
|
||||
/// pages was released may still hold the import; with none, the deallocator waits for the import
|
||||
/// (the module docs). Dropped on a runtime thread, possibly; a panic inside its drop is caught.
|
||||
/// Never dropped while the process exits: the pages stay imported to its end (`exit_guard`).
|
||||
pub type KeepAlive = Box<dyn Send + 'static>;
|
||||
|
||||
/// What the caller gives back with its host memory: the deallocator, and the keep-alive.
|
||||
/// What the caller gives back with its host memory: the deallocator, and the keep-alive, each
|
||||
/// held as the program's object (`program_objects.rs`).
|
||||
pub(super) struct HostRelease {
|
||||
pub(super) deallocator: Option<Deallocator>,
|
||||
pub(super) keep_alive: Option<KeepAlive>,
|
||||
deallocator: Option<ProgramObject<Deallocator>>,
|
||||
keep_alive: Option<ProgramObject<KeepAlive>>,
|
||||
}
|
||||
|
||||
impl HostRelease {
|
||||
/// Hold the caller's `deallocator` and `keep_alive`, at the call that gives them.
|
||||
pub(super) fn new(deallocator: Option<Deallocator>, keep_alive: Option<KeepAlive>) -> Self {
|
||||
HostRelease {
|
||||
deallocator: deallocator.map(ProgramObject::new),
|
||||
keep_alive: keep_alive.map(ProgramObject::new),
|
||||
}
|
||||
}
|
||||
|
||||
/// The release of `length` bytes at `pointer` to it, where it gives anything.
|
||||
pub(super) fn of(self, pointer: NonNull<u8>, length: u64) -> Option<Release> {
|
||||
let HostRelease {
|
||||
@@ -728,8 +767,8 @@ impl Importer {
|
||||
pub(super) struct Release {
|
||||
pointer: NonNull<u8>,
|
||||
length: u64,
|
||||
deallocator: Mutex<Option<Deallocator>>,
|
||||
keep_alive: Mutex<Option<KeepAlive>>,
|
||||
deallocator: Mutex<Option<ProgramObject<Deallocator>>>,
|
||||
keep_alive: Mutex<Option<ProgramObject<KeepAlive>>>,
|
||||
}
|
||||
|
||||
// SAFETY: the pointer is only handed to the deallocator, which is `Send`; the deallocator and
|
||||
@@ -750,8 +789,9 @@ impl Release {
|
||||
}
|
||||
}
|
||||
|
||||
/// Its keep-alive, for the import to drop once it is freed; `None` where the caller gave none.
|
||||
pub(super) fn keep_alive(&self) -> Option<KeepAlive> {
|
||||
/// Its keep-alive, for the import to keep until it is freed, or to drop at the release where
|
||||
/// the import's pages stay mapped without it (`buffer.rs`); `None` where the caller gave none.
|
||||
pub(super) fn keep_alive(&self) -> Option<ProgramObject<KeepAlive>> {
|
||||
lock(&self.keep_alive).take()
|
||||
}
|
||||
|
||||
@@ -770,7 +810,9 @@ impl Release {
|
||||
let deallocator = lock(&self.deallocator).take();
|
||||
if let Some(deallocator) = deallocator {
|
||||
let (pointer, length) = (self.pointer, self.length);
|
||||
exit_guard::program(move || deallocator(pointer, length));
|
||||
exit_guard::program_release(move || {
|
||||
deallocator.run(|deallocator| deallocator(pointer, length));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
//! Idle imports of the caller's dma-bufs, released and imported again at their next use: a
|
||||
//! runtime-internal residency, which nothing of Metal's observes.
|
||||
//!
|
||||
//! RADV lists every `VkDeviceMemory` its device imported in every kernel submission's
|
||||
//! buffer-object list. Mesa 26.2.4's `radv_alloc_memory` makes every memory but a WSI image's
|
||||
//! resident in the device's global list (`buffer_make_resident`), its amdgpu winsys keeps out of
|
||||
//! that list only memory neither imported nor exported (`radv_amdgpu_winsys_bo_make_resident`),
|
||||
//! and each submission's list is the whole global list (`radv_amdgpu_get_bo_list`). Linux 7.0's
|
||||
//! amdgpu works per entry at every submission (`amdgpu_cs.c`: lookup and sort, lock, validate,
|
||||
//! page-table update, fence sync and fence add), about 0.75 us an entry on a Radeon 780M (the
|
||||
//! consumer's measurement). So each import a device holds costs every submission, used or not:
|
||||
//! a consumer whose guest keeps hundreds of transfer buffers paid most of its submission thread's
|
||||
//! time for those idle. The runtime's own memory is pooled in few blocks, which RADV keeps out of
|
||||
//! the list.
|
||||
//!
|
||||
//! - **Which imports.** A no-copy buffer's own import of the dma-bufs its pages' source made
|
||||
//! (`dma_buf.rs`, where the device refused the pages' pointer): not a heap's, nor a rebind's,
|
||||
//! and only where the device kept a descriptor of each dma-buf ([`Again`]) within the
|
||||
//! descriptors the process's devices keep at most ([`kept_fds_limit`]); an import past them is
|
||||
//! made as any other and stays imported. Pages imported by their pointer stay
|
||||
//! imported: importing them again would read the pages mapped at the address then, which a
|
||||
//! remap may have replaced, and their exact form is the dma-buf's.
|
||||
//! - **Blits alone.** It stays releasable while every read of its `VkBuffer` and memory was a
|
||||
//! blit's (`Buffer::blit_at`: a copy or fill naming the buffer, a copy between it and a
|
||||
//! texture, `synchronize_resource`), which holds what it read until its command buffer
|
||||
//! completed ([`Imported`]). Any other read keeps it imported for good from then on, before the
|
||||
//! read returns: its Metal address handed out (`gpu_address`, so a binding, an argument
|
||||
//! buffer, an argument table, an indirect command buffer or `use_resource`), its `VkBuffer`
|
||||
//! handed out (`vk_buffer`), a texture or texel view over its bytes, or a second buffer lying in
|
||||
//! the import (`host_aliases.rs`). So no pointer, descriptor or image other than a blit's
|
||||
//! command ever holds a released import's objects.
|
||||
//! - **Released while idle** by the device's residency thread ([`Sweeper`]), every [`TICK`]: an
|
||||
//! import no command buffer holds (every one that read it completed) and that no blit took for
|
||||
//! its window, [`IDLE`] at first and doubled at each import again, up to [`IDLE_MOST`], so an
|
||||
//! import used now and then stays imported and an unused one goes. Its `VkBuffer` is destroyed
|
||||
//! and its memory freed; the buffer, its Metal address, its host pages, the dma-bufs and the
|
||||
//! caller's release stay. The crate's device tests release them at once, whatever their
|
||||
//! windows (`tests/host_residency.rs`).
|
||||
//! - **Imported again at the next blit,** on the encoding thread, before its command reads the
|
||||
//! `VkBuffer`: from the dma-bufs kept, never from the source again, so the buffer lies over the
|
||||
//! pages it was made over even where `host_range_remapped` told the device they were replaced
|
||||
//! since, as a buffer made before that call keeps its pages. A dma-buf holds its pages for as
|
||||
//! long as it is open, and adds nothing to a submission's list until it is imported. The new
|
||||
//! `VkBuffer` lies at the same offsets in the same memory type; its device address may differ,
|
||||
//! which no shader saw. Bytes the CPU wrote through `contents` meanwhile are in those pages, and
|
||||
//! so read. Counted (`WorkCounts::host_imports_reimported`); refused where the device cannot
|
||||
//! import them again (out of memory), which the blit's call returns.
|
||||
//! - **Exact.** What the buffer holds is its host pages, which a release never touches; its
|
||||
//! commands order by its key, as before; Metal's reach of it unnamed needs its Metal address,
|
||||
//! which a releasable buffer never handed out (`live_buffers.rs` holds its range only where
|
||||
//! it may be stale, and lists it again at its exposure). A read that keeps it imported finds it
|
||||
//! released only where its address was never handed out: it imports it again first.
|
||||
//! - **Counted.** `WorkCounts::host_imports_released`, `host_imports_reimported`,
|
||||
//! `host_imports_resident` (releasable imports holding their memory now) and
|
||||
//! `host_import_fds_kept`; the device's dma-buf memories (`dma_buf_memories_live`) fall as
|
||||
//! imports are released.
|
||||
|
||||
use super::buffer::{FixedPages, HostImport, Pages, Shape};
|
||||
use super::device::lock;
|
||||
use super::dma_buf::{DmaBufRequest, DmaBufSource};
|
||||
use super::error::{internal, Error};
|
||||
use super::exit_guard;
|
||||
use super::host_memory::ImportWindow;
|
||||
use super::memory::MemoryClass;
|
||||
use super::Device;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError, Weak};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long an import waits idle before its first release.
|
||||
pub(super) const IDLE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// The longest an import waits idle, its window doubled at each import again.
|
||||
pub(super) const IDLE_MOST: Duration = Duration::from_secs(64);
|
||||
|
||||
/// How often the residency thread looks for idle imports.
|
||||
pub(super) const TICK: Duration = Duration::from_millis(500);
|
||||
|
||||
/// The share of the process's descriptor limit (`RLIMIT_NOFILE`'s soft limit) the device's kept
|
||||
/// dma-bufs take at most: the rest stays the program's.
|
||||
const FD_SHARE: u64 = 4;
|
||||
|
||||
/// The descriptors of dma-bufs the process's devices keep at most for imports they may release
|
||||
/// ([`FD_SHARE`] of the process's soft limit): an import past them stays imported.
|
||||
pub(super) fn kept_fds_limit() -> u64 {
|
||||
static LIMIT: OnceLock<u64> = OnceLock::new();
|
||||
*LIMIT.get_or_init(|| {
|
||||
let mut limit = libc::rlimit {
|
||||
rlim_cur: 0,
|
||||
rlim_max: 0,
|
||||
};
|
||||
// SAFETY: `limit` is a valid `rlimit` to write.
|
||||
match unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } {
|
||||
0 => limit.rlim_cur / FD_SHARE,
|
||||
_ => 0,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The descriptors the process's devices keep now, within [`kept_fds_limit`].
|
||||
static KEPT_FDS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Keep `count` more descriptors within the process's [`kept_fds_limit`]: whether they fit
|
||||
/// (counted then).
|
||||
fn keep_fds(count: u64) -> bool {
|
||||
let limit = kept_fds_limit();
|
||||
let fits = |held: u64| held.checked_add(count).filter(|after| *after <= limit);
|
||||
KEPT_FDS
|
||||
.fetch_update(Ordering::AcqRel, Ordering::Acquire, fits)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Milliseconds of the residency's clock: since its first reading in the process.
|
||||
fn now_ms() -> u64 {
|
||||
static START: OnceLock<Instant> = OnceLock::new();
|
||||
START.get_or_init(Instant::now).elapsed().as_millis() as u64
|
||||
}
|
||||
|
||||
/// What imports a releasable import again: a descriptor of each dma-buf its source made, and
|
||||
/// what the import was made of. The source stays for the textures over its bytes, which ask it
|
||||
/// for dma-bufs of their own (`Device::dma_buf_image`), never for the import's again.
|
||||
pub(super) struct Again {
|
||||
device: Device,
|
||||
/// The dma-bufs, in order, with their lengths: duplicates of those the device imported.
|
||||
pub(super) chunks: Vec<(OwnedFd, u64)>,
|
||||
pub(super) source: DmaBufSource,
|
||||
pub(super) request: DmaBufRequest,
|
||||
/// The buffer's length, its window in the pages and its memory class.
|
||||
pub(super) length: u64,
|
||||
pub(super) window: ImportWindow,
|
||||
pub(super) class: MemoryClass,
|
||||
}
|
||||
|
||||
impl Again {
|
||||
/// `chunks` kept, counted against the process's [`kept_fds_limit`] and the device's cap
|
||||
/// (only the crate's device tests cap it): `None`, the descriptors closed, where they do not
|
||||
/// fit, so that the import stays imported.
|
||||
pub(super) fn new(
|
||||
device: &Device,
|
||||
chunks: Vec<(OwnedFd, u64)>,
|
||||
source: DmaBufSource,
|
||||
request: DmaBufRequest,
|
||||
(length, window, class): (u64, ImportWindow, MemoryClass),
|
||||
) -> Option<Again> {
|
||||
let shared = device.shared();
|
||||
let count = chunks.len() as u64;
|
||||
let cap = shared.residency.shared.fds_cap.load(Ordering::Relaxed);
|
||||
if !shared.counts.host_import_fds_keep(count, cap) {
|
||||
return None;
|
||||
}
|
||||
if !keep_fds(count) {
|
||||
shared.counts.host_import_fds_closed(count);
|
||||
return None;
|
||||
}
|
||||
Some(Again {
|
||||
device: device.clone(),
|
||||
chunks,
|
||||
source,
|
||||
request,
|
||||
length,
|
||||
window,
|
||||
class,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Again {
|
||||
fn drop(&mut self) {
|
||||
let count = self.chunks.len() as u64;
|
||||
self.device.shared().counts.host_import_fds_closed(count);
|
||||
KEPT_FDS.fetch_sub(count, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
/// A releasable import's `VkBuffer` and memory: held by the import while it is imported, and by
|
||||
/// each command buffer whose blit read them until it completed (`EncoderCore::blit_at`); the last
|
||||
/// lets go, which destroys the `VkBuffer` and frees the memory.
|
||||
pub(super) struct Imported {
|
||||
device: Device,
|
||||
pub(super) pages: Pages,
|
||||
}
|
||||
|
||||
impl Drop for Imported {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: no pending command buffer uses them: each that read them holds them until it
|
||||
// completed, and no other read reached a releasable import (the module docs).
|
||||
drop(unsafe { self.pages.release_import(&self.device, None) });
|
||||
}
|
||||
}
|
||||
|
||||
/// A releasable import's residency (the module docs).
|
||||
pub(super) struct Residency {
|
||||
device: Device,
|
||||
state: Mutex<State>,
|
||||
/// When a blit last took it, in [`now_ms`]'s milliseconds.
|
||||
used: AtomicU64,
|
||||
/// No read but a blit's took it yet: cleared for good by the first that did.
|
||||
releasable: AtomicBool,
|
||||
/// The pages of the device's stand-in (`detach.rs`), which a read takes where the device
|
||||
/// cannot import it again (`HostImport::pages`): kept from the start, so that read makes
|
||||
/// nothing.
|
||||
stand_in: Arc<FixedPages>,
|
||||
/// How its first import laid the bytes, which each import again matches.
|
||||
shape: Shape,
|
||||
}
|
||||
|
||||
struct State {
|
||||
/// Its `VkBuffer` and memory while it is imported.
|
||||
held: Option<Arc<Imported>>,
|
||||
/// What imports it again, while it may be released; dropped, its descriptors closed, once it
|
||||
/// is imported for good.
|
||||
again: Option<Again>,
|
||||
/// How long it waits idle before it is released, in milliseconds.
|
||||
window: u64,
|
||||
/// It was released once: its buffer's live-table range may be stale (`live_buffers.rs`).
|
||||
released_once: bool,
|
||||
}
|
||||
|
||||
impl Residency {
|
||||
/// The residency of an import of `pages`, imported now, which `again` imports again;
|
||||
/// `stand_in` the device's stand-in's pages.
|
||||
pub(super) fn new(
|
||||
device: &Device,
|
||||
pages: Pages,
|
||||
again: Again,
|
||||
stand_in: Arc<FixedPages>,
|
||||
) -> Residency {
|
||||
device.shared().counts.host_import_resident(true);
|
||||
Residency {
|
||||
shape: Shape::of(&pages),
|
||||
device: device.clone(),
|
||||
state: Mutex::new(State {
|
||||
held: Some(Arc::new(Imported {
|
||||
device: device.clone(),
|
||||
pages,
|
||||
})),
|
||||
again: Some(again),
|
||||
window: IDLE.as_millis() as u64,
|
||||
released_once: false,
|
||||
}),
|
||||
used: AtomicU64::new(now_ms()),
|
||||
releasable: AtomicBool::new(true),
|
||||
stand_in,
|
||||
}
|
||||
}
|
||||
|
||||
/// The device's stand-in's pages.
|
||||
pub(super) fn stand_in(&self) -> Arc<FixedPages> {
|
||||
Arc::clone(&self.stand_in)
|
||||
}
|
||||
|
||||
/// Its `VkBuffer` and memory for a blit's command, imported again where released: what the
|
||||
/// command buffer holds until it completed. Refused where the device cannot import them
|
||||
/// again.
|
||||
pub(super) fn for_blit(&self) -> Result<Arc<Imported>, Error> {
|
||||
let mut state = lock(&self.state);
|
||||
self.used.store(now_ms(), Ordering::Relaxed);
|
||||
if let Some(held) = &state.held {
|
||||
return Ok(Arc::clone(held));
|
||||
}
|
||||
self.import_again(&mut state)
|
||||
}
|
||||
|
||||
/// Its `VkBuffer` and memory for any other read, which keeps it imported for good from now
|
||||
/// on; imported again where released. `None` where the device cannot import them again.
|
||||
pub(super) fn exposed(&self) -> Option<Arc<Imported>> {
|
||||
let mut state = lock(&self.state);
|
||||
self.releasable.store(false, Ordering::Release);
|
||||
let held = match &state.held {
|
||||
Some(held) => Arc::clone(held),
|
||||
None => self.import_again(&mut state).ok()?,
|
||||
};
|
||||
// Never released again: its dma-bufs need not stay open.
|
||||
state.again = None;
|
||||
Some(held)
|
||||
}
|
||||
|
||||
/// Keep it imported for good from now on, imported again now where released (where the
|
||||
/// device cannot, the next read tries again): whether it was ever released, so a range of it
|
||||
/// noted before may be stale. A caller racing another's exposure waits for its import under
|
||||
/// the lock, and is told the same.
|
||||
pub(super) fn expose(&self) -> bool {
|
||||
let mut state = lock(&self.state);
|
||||
self.releasable.store(false, Ordering::Release);
|
||||
if state.held.is_none() && self.import_again(&mut state).is_err() {
|
||||
return state.released_once;
|
||||
}
|
||||
state.again = None;
|
||||
state.released_once
|
||||
}
|
||||
|
||||
/// Its `VkBuffer` and memory for a live-table listing (`live_buffers.rs`), which reads it
|
||||
/// without exposing it: `None` while a releasable import is released (its range is not
|
||||
/// listed then); else as [`Residency::exposed`].
|
||||
pub(super) fn listing(&self) -> Option<Arc<Imported>> {
|
||||
if !self.releasable.load(Ordering::Acquire) {
|
||||
return self.exposed();
|
||||
}
|
||||
lock(&self.state).held.as_ref().map(Arc::clone)
|
||||
}
|
||||
|
||||
/// Release it where it is releasable, imported, held by no command buffer, and idle for its
|
||||
/// window (`force`: whatever its window) at `now`: its objects, for the caller to let go of
|
||||
/// with no lock held.
|
||||
fn release_if_idle(&self, now: u64, force: bool) -> Option<Arc<Imported>> {
|
||||
if !self.releasable.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
let mut state = lock(&self.state);
|
||||
if !self.releasable.load(Ordering::Acquire) || state.again.is_none() {
|
||||
return None;
|
||||
}
|
||||
let held = state.held.as_ref()?;
|
||||
// A command buffer whose blit read it holds it until it completed; an exposing read
|
||||
// holds it while it reads, under this lock.
|
||||
if Arc::strong_count(held) > 1 {
|
||||
return None;
|
||||
}
|
||||
let idle = now.saturating_sub(self.used.load(Ordering::Relaxed));
|
||||
if !force && idle < state.window {
|
||||
return None;
|
||||
}
|
||||
state.released_once = true;
|
||||
let counts = &self.device.shared().counts;
|
||||
counts.host_import_released();
|
||||
counts.host_import_resident(false);
|
||||
state.held.take()
|
||||
}
|
||||
|
||||
/// Import it again from its dma-bufs (`Device::import_again`), under `state`'s lock, its
|
||||
/// window doubled: its objects. Refused where released for good, where the device cannot,
|
||||
/// and where it lays the bytes otherwise than the first import (an internal error: the same
|
||||
/// dma-bufs, length and window).
|
||||
fn import_again(&self, state: &mut State) -> Result<Arc<Imported>, Error> {
|
||||
let again = state
|
||||
.again
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal("an import released without its dma-bufs"))?;
|
||||
let pages = self.device.import_again(again)?;
|
||||
let laid = Shape::of(&pages);
|
||||
let held = Arc::new(Imported {
|
||||
device: self.device.clone(),
|
||||
pages,
|
||||
});
|
||||
if !laid.same(&self.shape) {
|
||||
// Freed at once: nothing read them.
|
||||
drop(held);
|
||||
return Err(internal("an import again laid its bytes otherwise"));
|
||||
}
|
||||
state.held = Some(Arc::clone(&held));
|
||||
state.window = (2 * state.window).min(IDLE_MOST.as_millis() as u64);
|
||||
let counts = &self.device.shared().counts;
|
||||
counts.host_import_reimported();
|
||||
counts.host_import_resident(true);
|
||||
Ok(held)
|
||||
}
|
||||
}
|
||||
|
||||
impl Residency {
|
||||
/// Let go of its objects, the import going: freed now, or with the last command buffer that
|
||||
/// read them.
|
||||
pub(super) fn let_go(&self) {
|
||||
let held = lock(&self.state).held.take();
|
||||
if held.is_some() {
|
||||
self.device.shared().counts.host_import_resident(false);
|
||||
}
|
||||
drop(held);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Residency {
|
||||
fn drop(&mut self) {
|
||||
if lock(&self.state).held.is_some() {
|
||||
self.device.shared().counts.host_import_resident(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The device's releasable imports and the thread that releases them while idle (the module
|
||||
/// docs): started by the first such import; holds nothing of the device.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Sweeper {
|
||||
shared: Arc<Shared>,
|
||||
thread: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
state: Mutex<Swept>,
|
||||
/// The thread is asked to stop.
|
||||
stop: Condvar,
|
||||
/// The descriptors the device keeps at most, within the process's [`kept_fds_limit`]:
|
||||
/// unbounded but in the crate's device tests (`tests/host_residency.rs`).
|
||||
fds_cap: AtomicU64,
|
||||
}
|
||||
|
||||
impl Default for Shared {
|
||||
fn default() -> Shared {
|
||||
Shared {
|
||||
state: Mutex::default(),
|
||||
stop: Condvar::new(),
|
||||
fds_cap: AtomicU64::new(u64::MAX),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Swept {
|
||||
/// The releasable imports, weakly: each goes with its buffer.
|
||||
imports: Vec<Weak<HostImport>>,
|
||||
stopping: bool,
|
||||
}
|
||||
|
||||
impl Sweeper {
|
||||
/// Note `import`, releasable, and start the thread unless it runs: `false` where the host
|
||||
/// cannot start one (the import then stays imported).
|
||||
pub(super) fn note(&self, import: &Arc<HostImport>) -> bool {
|
||||
let mut thread = lock(&self.thread);
|
||||
if thread.is_none() {
|
||||
let shared = Arc::clone(&self.shared);
|
||||
let spawned = exit_guard::spawn(
|
||||
std::thread::Builder::new().name("metal2vulkan-residency".into()),
|
||||
move || run(&shared),
|
||||
);
|
||||
match spawned {
|
||||
Ok(handle) => *thread = Some(handle),
|
||||
Err(_) => return false,
|
||||
}
|
||||
}
|
||||
lock(&self.shared.state)
|
||||
.imports
|
||||
.push(Arc::downgrade(import));
|
||||
true
|
||||
}
|
||||
|
||||
/// Release every releasable import idle now (`force`: whatever its window), on this thread:
|
||||
/// how many.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))]
|
||||
pub(super) fn sweep(&self, force: bool) -> usize {
|
||||
sweep(&self.shared, force)
|
||||
}
|
||||
|
||||
/// The device's teardown: the thread ends, joined unless this is it.
|
||||
pub(crate) fn stop(&self) {
|
||||
lock(&self.shared.state).stopping = true;
|
||||
self.shared.stop.notify_all();
|
||||
let mut thread = lock(&self.thread);
|
||||
let own = thread
|
||||
.as_ref()
|
||||
.is_some_and(|handle| handle.thread().id() == std::thread::current().id());
|
||||
if !own {
|
||||
if let Some(handle) = thread.take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The thread's loop: a sweep every [`TICK`] until stopped.
|
||||
fn run(shared: &Shared) {
|
||||
loop {
|
||||
{
|
||||
let state = lock(&shared.state);
|
||||
let (state, _) = shared
|
||||
.stop
|
||||
.wait_timeout(state, TICK)
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if state.stopping {
|
||||
return;
|
||||
}
|
||||
}
|
||||
sweep(shared, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Release the noted imports idle now (`force`: whatever their windows), forgetting those gone:
|
||||
/// how many. Each import and its objects are let go of with no lock held: either may be its
|
||||
/// device's last holder.
|
||||
fn sweep(shared: &Shared, force: bool) -> usize {
|
||||
let imports: Vec<Arc<HostImport>> = {
|
||||
let mut state = lock(&shared.state);
|
||||
state.imports.retain(|import| import.strong_count() > 0);
|
||||
state.imports.iter().filter_map(Weak::upgrade).collect()
|
||||
};
|
||||
let now = now_ms();
|
||||
let mut released = 0;
|
||||
for import in imports {
|
||||
let objects = import
|
||||
.residency()
|
||||
.and_then(|residency| residency.release_if_idle(now, force));
|
||||
released += usize::from(objects.is_some());
|
||||
drop(objects);
|
||||
drop(import);
|
||||
}
|
||||
released
|
||||
}
|
||||
|
||||
/// The crate's device tests' hooks (`tests/host_residency.rs`).
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))]
|
||||
impl Device {
|
||||
/// Release now every import of a no-copy buffer's dma-bufs that the device releases while
|
||||
/// idle, whatever its idle window: those no command buffer holds, whose Metal address was
|
||||
/// never handed out and whose bytes only blits read. Each is imported again at its next
|
||||
/// blit. How many it released.
|
||||
pub(crate) fn release_idle_host_imports(&self) -> usize {
|
||||
self.shared().residency.sweep(true)
|
||||
}
|
||||
|
||||
/// Keep at most `cap` descriptors of dma-bufs for the device's releasable imports from now
|
||||
/// on, within the process's own bound: a no-copy buffer made past it keeps its import
|
||||
/// imported, as one past the process's bound does.
|
||||
pub(crate) fn cap_kept_host_import_fds(&self, cap: u64) {
|
||||
let shared = &self.shared().residency.shared;
|
||||
shared.fds_cap.store(cap, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
//! The reads the runtime's barriers name in their destination, from one table of the reads a
|
||||
//! queue family's commands make ([`READS`], and [`EXTENSION_READS`] for what an enabled
|
||||
//! extension adds), never `MEMORY_READ` or `HOST_READ` where they can be named: an image memory
|
||||
//! barrier's, all made by [`image_barrier`] for the queue family that records them, whose
|
||||
//! destination accesses are an [`ImageDst`]; and a global memory barrier's
|
||||
//! ([`MemoryReads`], which `tracker::Barrier::record` names in place of `MEMORY_READ`).
|
||||
//!
|
||||
//! - **The device's accesses alone.** A command reads an image as a shader resource, an input,
|
||||
//! color or depth/stencil attachment, or a transfer's source; that is everything `MEMORY_READ`
|
||||
//! names after an image barrier whose destination stage is `ALL_COMMANDS` ("all read accesses ...
|
||||
//! valid where it is used"), and [`ImageDst::Every`] names exactly that. The host reaches no
|
||||
//! image's memory: it moves texels by copies, and a heap buffer's bytes reach the host through
|
||||
//! the global barrier that ends every batch (`tracker::Barrier::to_host`) or an internal
|
||||
//! submission (`texture::transfer_barrier`), which no image barrier stands for.
|
||||
//! - **The recording family's reads.** `ALL_COMMANDS` stands for the stages the recording queue
|
||||
//! family supports, and an access mask may name only accesses those stages make
|
||||
//! (VUID-vkCmdPipelineBarrier-pImageMemoryBarriers-02820). So [`ImageDst::Every`] is the reads
|
||||
//! of the family's commands: a transfer's read on a family of transfers alone (the staging
|
||||
//! queue's, `device/staging.rs`), and a shader's read too on one of compute, and the attachment
|
||||
//! reads too on one of graphics. That is exact: on a family of transfers alone the only reads of
|
||||
//! an image after the barrier are transfers. A later access on another queue is not this
|
||||
//! barrier's to order: a semaphore wait orders it, whose "second access scope includes all
|
||||
//! memory access performed by the device" (the Vulkan specification, Semaphore Waiting), or,
|
||||
//! after the staging queue's work, the host's wait for its fence before that access is
|
||||
//! submitted.
|
||||
//! - **Why not `MEMORY_READ`.** MoltenVK 1.4.1 takes `MEMORY_READ` or `HOST_READ` in the
|
||||
//! destination of a barrier into `GENERAL` of an optimal image bound to mapped host-coherent
|
||||
//! memory as a host read to come. Once the command buffer completes, a completed handler copies
|
||||
//! the texture into that memory (`getBytes`, `MVKImagePlane::pullFromDeviceOnCompletion`). A
|
||||
//! texture placed in its memory's `MTLHeap` lies in that same memory, so the copy writes its
|
||||
//! texels, laid out in rows, over its own storage, which the GPU lays out otherwise. The copy
|
||||
//! runs on the CPU while the GPU runs the submission's later command buffers. On an M3 Max,
|
||||
//! textures of a `Shared` placement heap read back permuted texels, or the heap's earlier bytes,
|
||||
//! where the copy came after the copies that wrote them (`runtime_lane::heap_textures`), with a
|
||||
//! texture's first move (`texture/first_move.rs`) asking for host reads. Every texture's first
|
||||
//! move, and every transition of a caller's image (`texture/wrapped.rs`), is such a barrier.
|
||||
//! - **Global memory barriers.** A global barrier orders every read of memory a later command
|
||||
//! makes at its destination stages: an image's reads above, and those of a buffer alone, an
|
||||
//! indirect command's, an index's, a vertex attribute's and a uniform's, at stages of the family
|
||||
//! that make them; and the reads an enabled extension makes valid there ([`EXTENSION_READS`]:
|
||||
//! each extension of the Vulkan registry, vk.xml of Vulkan-Headers `vulkan-sdk-1.4.341.0`, the
|
||||
//! registry `scripts/regen-vulkan-requirements` pins, that adds a read access type or a stage a
|
||||
//! read takes). Named one by one beside the barrier's destination stages ([`MemoryReads`]) they
|
||||
//! are `MEMORY_READ` exactly: it "is treated as equivalent to setting all READ access flags that
|
||||
//! are valid where it is used", where an access is valid beside a destination stage mask only
|
||||
//! if a stage in the mask supports it, as the table of supported access types specifies
|
||||
//! (`VUID-vkCmdPipelineBarrier-dstAccessMask-02816`), and `ALL_COMMANDS` "specifies all
|
||||
//! operations performed by all commands supported on the queue it is used with", while the host stage "is not invoked by any
|
||||
//! commands recorded in a command buffer" (the Vulkan specification, Access Types and Pipeline
|
||||
//! Stages), so `HOST_READ` is none of them. Where an enabled extension makes valid a read only `VkAccessFlags2` names, which no
|
||||
//! `VkAccessFlags` bit covers (the runtime's barriers are `vkCmdPipelineBarrier`'s), the barrier
|
||||
//! keeps `MEMORY_READ`, and so does one on a family of none of graphics, compute and transfers.
|
||||
//! The extensions are those the runtime knows the device enabled: its own, and an adopted
|
||||
//! device's `RawDevice::enabled` and `device_extensions`. They are every extension whose
|
||||
//! commands the runtime records, and its barriers order its own commands: a batch's work reaches
|
||||
//! other commands through its signals, whose semaphore's "second access scope includes all
|
||||
//! memory access performed by the device" (the Vulkan specification, Semaphore Waiting). The
|
||||
//! runtime's global barriers record on its queues for encoders and internal work, every one of
|
||||
//! a family of graphics and compute (`device/create.rs`'s `queue_plan`), so their reads are
|
||||
//! that family's.
|
||||
//! - **Why not `MEMORY_READ` there.** ANV (Mesa 26.2.4) takes `MEMORY_READ` in a barrier's
|
||||
//! destination as every invalidate it has, the aux-table invalidate among them; on the Iris Xe of
|
||||
//! RPL-P (Gfx12) that adds the render engine's idle sequence (a data cache, L3 fabric, render
|
||||
//! target and depth flush with a command streamer stall), a write of the aux-table invalidate
|
||||
//! register and a wait polling it clear, and the state and instruction caches' invalidates
|
||||
//! (`genX_cmd_buffer.c`'s `emit_apply_pipe_flushes` and `invalidate_aux_map`), at every such
|
||||
//! barrier. The named reads take none of them.
|
||||
|
||||
use ash::vk;
|
||||
use metal2vulkan::vk::PipelineStageFlags2 as Stage;
|
||||
use std::ffi::CStr;
|
||||
|
||||
/// The queue flags of the stages a read takes (vk.xml's `syncstage` queues).
|
||||
const GRAPHICS: vk::QueueFlags = vk::QueueFlags::GRAPHICS;
|
||||
const SHADERS: vk::QueueFlags =
|
||||
vk::QueueFlags::from_raw(vk::QueueFlags::GRAPHICS.as_raw() | vk::QueueFlags::COMPUTE.as_raw());
|
||||
const TRANSFERS: vk::QueueFlags =
|
||||
vk::QueueFlags::from_raw(SHADERS.as_raw() | vk::QueueFlags::TRANSFER.as_raw());
|
||||
|
||||
/// The bits of `stages`.
|
||||
const fn stages(stages: &[Stage]) -> u64 {
|
||||
let mut bits = 0;
|
||||
let mut i = 0;
|
||||
while i < stages.len() {
|
||||
bits |= stages[i].as_raw();
|
||||
i += 1;
|
||||
}
|
||||
bits
|
||||
}
|
||||
|
||||
/// Every shader stage: those `SHADER_READ` and `UNIFORM_READ` take, and the reads of descriptors
|
||||
/// and acceleration structures in shaders.
|
||||
const SHADER_STAGES: u64 = stages(&[
|
||||
Stage::VERTEX_SHADER,
|
||||
Stage::TESSELLATION_CONTROL_SHADER,
|
||||
Stage::TESSELLATION_EVALUATION_SHADER,
|
||||
Stage::GEOMETRY_SHADER,
|
||||
Stage::FRAGMENT_SHADER,
|
||||
Stage::COMPUTE_SHADER,
|
||||
Stage::RAY_TRACING_SHADER_KHR,
|
||||
Stage::TASK_SHADER_EXT,
|
||||
Stage::MESH_SHADER_EXT,
|
||||
Stage::SUBPASS_SHADER_HUAWEI,
|
||||
Stage::CLUSTER_CULLING_SHADER_HUAWEI,
|
||||
]);
|
||||
|
||||
/// The stages each stage that stands for others is "equivalent to" (vk.xml's `syncequivalent`).
|
||||
const EQUIVALENTS: [(Stage, u64); 4] = [
|
||||
(
|
||||
Stage::VERTEX_INPUT,
|
||||
stages(&[Stage::INDEX_INPUT, Stage::VERTEX_ATTRIBUTE_INPUT]),
|
||||
),
|
||||
(
|
||||
Stage::ALL_TRANSFER,
|
||||
stages(&[
|
||||
Stage::COPY,
|
||||
Stage::BLIT,
|
||||
Stage::RESOLVE,
|
||||
Stage::CLEAR,
|
||||
Stage::ACCELERATION_STRUCTURE_COPY_KHR,
|
||||
]),
|
||||
),
|
||||
(
|
||||
Stage::ALL_GRAPHICS,
|
||||
stages(&[
|
||||
Stage::DRAW_INDIRECT,
|
||||
Stage::COPY_INDIRECT_KHR,
|
||||
Stage::TASK_SHADER_EXT,
|
||||
Stage::MESH_SHADER_EXT,
|
||||
Stage::VERTEX_INPUT,
|
||||
Stage::INDEX_INPUT,
|
||||
Stage::VERTEX_ATTRIBUTE_INPUT,
|
||||
Stage::VERTEX_SHADER,
|
||||
Stage::TESSELLATION_CONTROL_SHADER,
|
||||
Stage::TESSELLATION_EVALUATION_SHADER,
|
||||
Stage::GEOMETRY_SHADER,
|
||||
Stage::FRAGMENT_SHADER,
|
||||
Stage::EARLY_FRAGMENT_TESTS,
|
||||
Stage::LATE_FRAGMENT_TESTS,
|
||||
Stage::COLOR_ATTACHMENT_OUTPUT,
|
||||
Stage::CONDITIONAL_RENDERING_EXT,
|
||||
Stage::TRANSFORM_FEEDBACK_EXT,
|
||||
Stage::FRAGMENT_SHADING_RATE_ATTACHMENT_KHR,
|
||||
Stage::FRAGMENT_DENSITY_PROCESS_EXT,
|
||||
Stage::SUBPASS_SHADER_HUAWEI,
|
||||
Stage::INVOCATION_MASK_HUAWEI,
|
||||
Stage::CLUSTER_CULLING_SHADER_HUAWEI,
|
||||
]),
|
||||
),
|
||||
(
|
||||
Stage::PRE_RASTERIZATION_SHADERS,
|
||||
stages(&[
|
||||
Stage::VERTEX_SHADER,
|
||||
Stage::TESSELLATION_CONTROL_SHADER,
|
||||
Stage::TESSELLATION_EVALUATION_SHADER,
|
||||
Stage::GEOMETRY_SHADER,
|
||||
Stage::TASK_SHADER_EXT,
|
||||
Stage::MESH_SHADER_EXT,
|
||||
Stage::CLUSTER_CULLING_SHADER_HUAWEI,
|
||||
]),
|
||||
),
|
||||
];
|
||||
|
||||
/// `stages` with each stage that stands for others widened to them.
|
||||
fn expanded(stages: u64) -> u64 {
|
||||
(EQUIVALENTS.iter())
|
||||
.filter(|(stage, _)| stages & stage.as_raw() != 0)
|
||||
.fold(stages, |all, (_, equivalent)| all | equivalent)
|
||||
}
|
||||
|
||||
/// One read access type a command may make: its bit, where `VkAccessFlags` has one (`None` where
|
||||
/// only `VkAccessFlags2` does); the queue flags of a family whose stages make it, any of which
|
||||
/// the family has; the stages that make it (vk.xml's `syncsupport`), as `VkPipelineStageFlags2`
|
||||
/// bits; and whether an image barrier names it ([`ImageDst::Every`]): a core read of an image.
|
||||
/// An image barrier names no read an extension adds; of those, only `VK_QCOM_tile_shading`'s
|
||||
/// reads an image (a tile attachment), which `SHADER_READ` covers.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Read {
|
||||
pub(crate) access: Option<vk::AccessFlags>,
|
||||
pub(crate) queues: vk::QueueFlags,
|
||||
pub(crate) stages: u64,
|
||||
pub(crate) image: bool,
|
||||
}
|
||||
|
||||
impl Read {
|
||||
/// Whether the commands of a family of `family`'s queue flags make it.
|
||||
pub(crate) fn held_by(self, family: vk::QueueFlags) -> bool {
|
||||
family.intersects(self.queues)
|
||||
}
|
||||
|
||||
/// Whether it is valid in a destination access mask beside the stages `dst` on a family of
|
||||
/// `family`'s queue flags: `ALL_COMMANDS` holds every stage the family runs; any other mask,
|
||||
/// which holds only stages the family runs and the device has
|
||||
/// (`VUID-vkCmdPipelineBarrier-dstStageMask-04098`, `-04090` and the like), those it names
|
||||
/// and those they stand for.
|
||||
fn valid_beside(self, dst: vk::PipelineStageFlags, family: vk::QueueFlags) -> bool {
|
||||
if dst.contains(vk::PipelineStageFlags::ALL_COMMANDS) {
|
||||
return self.held_by(family);
|
||||
}
|
||||
expanded(u64::from(dst.as_raw())) & self.stages != 0
|
||||
}
|
||||
}
|
||||
|
||||
const fn read(access: vk::AccessFlags, queues: vk::QueueFlags, stages: u64, image: bool) -> Read {
|
||||
Read {
|
||||
access: Some(access),
|
||||
queues,
|
||||
stages,
|
||||
image,
|
||||
}
|
||||
}
|
||||
|
||||
/// A read only `VkAccessFlags2` names, which no `VkAccessFlags` bit covers.
|
||||
const fn unnamed(queues: vk::QueueFlags, stages: u64) -> Read {
|
||||
Read {
|
||||
access: None,
|
||||
queues,
|
||||
stages,
|
||||
image: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every core read access type, the families whose stages make it and the stages (vk.xml's
|
||||
/// `sync` section, the Vulkan specification's "Supported access types" table): an extension's
|
||||
/// stage among them is one a mask holds only where the device has it. `SHADER_READ` "is
|
||||
/// equivalent to the logical OR of" the sampled, storage, shader binding table and tile
|
||||
/// attachment reads `VkAccessFlags2` names apart (the specification's `VkAccessFlagBits2`).
|
||||
pub(crate) const READS: [Read; 9] = [
|
||||
read(
|
||||
vk::AccessFlags::TRANSFER_READ,
|
||||
TRANSFERS,
|
||||
stages(&[
|
||||
Stage::ALL_TRANSFER,
|
||||
Stage::COPY,
|
||||
Stage::RESOLVE,
|
||||
Stage::BLIT,
|
||||
Stage::ACCELERATION_STRUCTURE_BUILD_KHR,
|
||||
Stage::ACCELERATION_STRUCTURE_COPY_KHR,
|
||||
Stage::MICROMAP_BUILD_EXT,
|
||||
Stage::CONVERT_COOPERATIVE_VECTOR_MATRIX_NV,
|
||||
]),
|
||||
true,
|
||||
),
|
||||
read(
|
||||
vk::AccessFlags::SHADER_READ,
|
||||
SHADERS,
|
||||
SHADER_STAGES
|
||||
| stages(&[
|
||||
Stage::ACCELERATION_STRUCTURE_BUILD_KHR,
|
||||
Stage::MICROMAP_BUILD_EXT,
|
||||
]),
|
||||
true,
|
||||
),
|
||||
read(vk::AccessFlags::UNIFORM_READ, SHADERS, SHADER_STAGES, false),
|
||||
read(
|
||||
vk::AccessFlags::INDIRECT_COMMAND_READ,
|
||||
SHADERS,
|
||||
stages(&[
|
||||
Stage::DRAW_INDIRECT,
|
||||
Stage::ACCELERATION_STRUCTURE_BUILD_KHR,
|
||||
]),
|
||||
false,
|
||||
),
|
||||
read(
|
||||
vk::AccessFlags::INPUT_ATTACHMENT_READ,
|
||||
GRAPHICS,
|
||||
stages(&[Stage::FRAGMENT_SHADER, Stage::SUBPASS_SHADER_HUAWEI]),
|
||||
true,
|
||||
),
|
||||
read(
|
||||
vk::AccessFlags::COLOR_ATTACHMENT_READ,
|
||||
GRAPHICS,
|
||||
stages(&[Stage::FRAGMENT_SHADER, Stage::COLOR_ATTACHMENT_OUTPUT]),
|
||||
true,
|
||||
),
|
||||
read(
|
||||
vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ,
|
||||
GRAPHICS,
|
||||
stages(&[
|
||||
Stage::FRAGMENT_SHADER,
|
||||
Stage::EARLY_FRAGMENT_TESTS,
|
||||
Stage::LATE_FRAGMENT_TESTS,
|
||||
]),
|
||||
true,
|
||||
),
|
||||
read(
|
||||
vk::AccessFlags::INDEX_READ,
|
||||
GRAPHICS,
|
||||
stages(&[Stage::VERTEX_INPUT, Stage::INDEX_INPUT]),
|
||||
false,
|
||||
),
|
||||
read(
|
||||
vk::AccessFlags::VERTEX_ATTRIBUTE_READ,
|
||||
GRAPHICS,
|
||||
stages(&[Stage::VERTEX_INPUT, Stage::VERTEX_ATTRIBUTE_INPUT]),
|
||||
false,
|
||||
),
|
||||
];
|
||||
|
||||
/// An acceleration structure's read in shaders and builds.
|
||||
const STRUCTURE_READ: Read = read(
|
||||
vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR,
|
||||
SHADERS,
|
||||
SHADER_STAGES | Stage::ACCELERATION_STRUCTURE_BUILD_KHR.as_raw(),
|
||||
false,
|
||||
);
|
||||
|
||||
/// Each extension of the Vulkan registry whose enabling makes a read access type valid with a
|
||||
/// stage where the core's is not (vk.xml of Vulkan-Headers `vulkan-sdk-1.4.341.0`, its `sync`
|
||||
/// section: a read it adds, or a stage it adds that a read takes), that read, and those stages.
|
||||
/// A read the sampled, storage, shader binding table or tile attachment read stands for is
|
||||
/// `SHADER_READ`'s, which [`READS`] names with every shader stage.
|
||||
pub(crate) const EXTENSION_READS: [(&CStr, Read); 21] = [
|
||||
(c"VK_KHR_acceleration_structure", STRUCTURE_READ),
|
||||
(c"VK_NV_ray_tracing", STRUCTURE_READ),
|
||||
// Its acceleration structure copy stage runs on families of transfers alone too; it requires
|
||||
// `VK_KHR_acceleration_structure`, whose read that is.
|
||||
(
|
||||
c"VK_KHR_ray_tracing_maintenance1",
|
||||
read(
|
||||
vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR,
|
||||
TRANSFERS,
|
||||
Stage::ACCELERATION_STRUCTURE_COPY_KHR.as_raw(),
|
||||
false,
|
||||
),
|
||||
),
|
||||
// Its indirect copy stage runs on families of transfers alone too.
|
||||
(
|
||||
c"VK_KHR_copy_memory_indirect",
|
||||
read(
|
||||
vk::AccessFlags::INDIRECT_COMMAND_READ,
|
||||
TRANSFERS,
|
||||
Stage::COPY_INDIRECT_KHR.as_raw(),
|
||||
false,
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_EXT_device_generated_commands",
|
||||
read(
|
||||
vk::AccessFlags::COMMAND_PREPROCESS_READ_NV,
|
||||
SHADERS,
|
||||
Stage::COMMAND_PREPROCESS_EXT.as_raw(),
|
||||
false,
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_NV_device_generated_commands",
|
||||
read(
|
||||
vk::AccessFlags::COMMAND_PREPROCESS_READ_NV,
|
||||
SHADERS,
|
||||
Stage::COMMAND_PREPROCESS_EXT.as_raw(),
|
||||
false,
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_EXT_conditional_rendering",
|
||||
read(
|
||||
vk::AccessFlags::CONDITIONAL_RENDERING_READ_EXT,
|
||||
SHADERS,
|
||||
Stage::CONDITIONAL_RENDERING_EXT.as_raw(),
|
||||
false,
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_EXT_transform_feedback",
|
||||
read(
|
||||
vk::AccessFlags::TRANSFORM_FEEDBACK_COUNTER_READ_EXT,
|
||||
SHADERS,
|
||||
stages(&[Stage::DRAW_INDIRECT, Stage::TRANSFORM_FEEDBACK_EXT]),
|
||||
false,
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_EXT_blend_operation_advanced",
|
||||
read(
|
||||
vk::AccessFlags::COLOR_ATTACHMENT_READ_NONCOHERENT_EXT,
|
||||
GRAPHICS,
|
||||
Stage::COLOR_ATTACHMENT_OUTPUT.as_raw(),
|
||||
false,
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_EXT_fragment_density_map",
|
||||
read(
|
||||
vk::AccessFlags::FRAGMENT_DENSITY_MAP_READ_EXT,
|
||||
GRAPHICS,
|
||||
Stage::FRAGMENT_DENSITY_PROCESS_EXT.as_raw(),
|
||||
false,
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_KHR_fragment_shading_rate",
|
||||
read(
|
||||
vk::AccessFlags::FRAGMENT_SHADING_RATE_ATTACHMENT_READ_KHR,
|
||||
GRAPHICS,
|
||||
Stage::FRAGMENT_SHADING_RATE_ATTACHMENT_KHR.as_raw(),
|
||||
false,
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_NV_shading_rate_image",
|
||||
read(
|
||||
vk::AccessFlags::FRAGMENT_SHADING_RATE_ATTACHMENT_READ_KHR,
|
||||
GRAPHICS,
|
||||
Stage::FRAGMENT_SHADING_RATE_ATTACHMENT_KHR.as_raw(),
|
||||
false,
|
||||
),
|
||||
),
|
||||
(c"VK_EXT_descriptor_buffer", unnamed(SHADERS, SHADER_STAGES)),
|
||||
(c"VK_EXT_descriptor_heap", unnamed(SHADERS, SHADER_STAGES)),
|
||||
(
|
||||
c"VK_EXT_opacity_micromap",
|
||||
unnamed(
|
||||
vk::QueueFlags::COMPUTE,
|
||||
stages(&[
|
||||
Stage::MICROMAP_BUILD_EXT,
|
||||
Stage::ACCELERATION_STRUCTURE_BUILD_KHR,
|
||||
]),
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_HUAWEI_invocation_mask",
|
||||
unnamed(GRAPHICS, Stage::INVOCATION_MASK_HUAWEI.as_raw()),
|
||||
),
|
||||
(
|
||||
c"VK_EXT_memory_decompression",
|
||||
unnamed(SHADERS, Stage::MEMORY_DECOMPRESSION_EXT.as_raw()),
|
||||
),
|
||||
(
|
||||
c"VK_KHR_video_decode_queue",
|
||||
unnamed(
|
||||
vk::QueueFlags::VIDEO_DECODE_KHR,
|
||||
Stage::VIDEO_DECODE_KHR.as_raw(),
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_KHR_video_encode_queue",
|
||||
unnamed(
|
||||
vk::QueueFlags::VIDEO_ENCODE_KHR,
|
||||
Stage::VIDEO_ENCODE_KHR.as_raw(),
|
||||
),
|
||||
),
|
||||
(
|
||||
c"VK_NV_optical_flow",
|
||||
unnamed(
|
||||
vk::QueueFlags::OPTICAL_FLOW_NV,
|
||||
Stage::OPTICAL_FLOW_NV.as_raw(),
|
||||
),
|
||||
),
|
||||
// `VK_QUEUE_DATA_GRAPH_BIT_ARM`, which `ash 0.38` predates.
|
||||
(
|
||||
c"VK_ARM_data_graph",
|
||||
unnamed(
|
||||
vk::QueueFlags::from_raw(0x400),
|
||||
Stage::DATA_GRAPH_ARM.as_raw(),
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
/// The reads of an image the commands of a family of `family`'s queue flags make.
|
||||
fn image_reads(family: vk::QueueFlags) -> vk::AccessFlags {
|
||||
(READS.iter())
|
||||
.filter(|read| read.image && read.held_by(family))
|
||||
.filter_map(|read| read.access)
|
||||
.fold(vk::AccessFlags::empty(), |reads, access| reads | access)
|
||||
}
|
||||
|
||||
/// What a global memory barrier's destination names in place of `MEMORY_READ` on a device's
|
||||
/// queue family for encoders (the module docs): its family, and which of [`EXTENSION_READS`] the
|
||||
/// device enabled.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct MemoryReads {
|
||||
family: vk::QueueFlags,
|
||||
/// Bit `i` for `EXTENSION_READS[i]`.
|
||||
enabled: u32,
|
||||
}
|
||||
|
||||
impl MemoryReads {
|
||||
/// The reads of a family of `family`'s queue flags on a device that enabled the extensions
|
||||
/// `enabled`.
|
||||
pub(crate) fn of<'a>(
|
||||
family: vk::QueueFlags,
|
||||
enabled: impl IntoIterator<Item = &'a CStr>,
|
||||
) -> MemoryReads {
|
||||
let mut rows = 0;
|
||||
for name in enabled {
|
||||
for (i, (extension, _)) in EXTENSION_READS.iter().enumerate() {
|
||||
if *extension == name {
|
||||
rows |= 1 << i;
|
||||
}
|
||||
}
|
||||
}
|
||||
MemoryReads {
|
||||
family,
|
||||
enabled: rows,
|
||||
}
|
||||
}
|
||||
|
||||
/// The destination access mask `dst` beside the destination stages `stages` with
|
||||
/// `MEMORY_READ` in it replaced by the reads it stands for there: every read valid beside
|
||||
/// those stages on the family, which the device has. `dst` itself where one of them has no
|
||||
/// `VkAccessFlags` bit, and on a family of none of graphics, compute and transfers.
|
||||
pub(crate) fn named(
|
||||
self,
|
||||
dst: vk::AccessFlags,
|
||||
stages: vk::PipelineStageFlags,
|
||||
) -> vk::AccessFlags {
|
||||
if !dst.contains(vk::AccessFlags::MEMORY_READ) || !self.family.intersects(TRANSFERS) {
|
||||
return dst;
|
||||
}
|
||||
let added = (EXTENSION_READS.iter().enumerate())
|
||||
.filter(|(i, _)| self.enabled & (1 << i) != 0)
|
||||
.map(|(_, (_, read))| read);
|
||||
let mut reads = vk::AccessFlags::empty();
|
||||
for read in READS.iter().chain(added) {
|
||||
if !read.valid_beside(stages, self.family) {
|
||||
continue;
|
||||
}
|
||||
match read.access {
|
||||
Some(access) => reads |= access,
|
||||
None => return dst,
|
||||
}
|
||||
}
|
||||
(dst & !vk::AccessFlags::MEMORY_READ) | reads
|
||||
}
|
||||
}
|
||||
|
||||
/// The accesses after an image barrier that it makes the image's earlier writes visible to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ImageDst {
|
||||
/// Every access a later command of the recording family may make of the image, its reads and
|
||||
/// its writes.
|
||||
Every,
|
||||
/// A transfer's read of it.
|
||||
TransferRead,
|
||||
/// A transfer's write of it.
|
||||
TransferWrite,
|
||||
}
|
||||
|
||||
impl ImageDst {
|
||||
/// Its access mask in a barrier recorded for a family of `family`'s queue flags.
|
||||
pub(crate) fn access(self, family: vk::QueueFlags) -> vk::AccessFlags {
|
||||
match self {
|
||||
ImageDst::Every => image_reads(family) | vk::AccessFlags::MEMORY_WRITE,
|
||||
ImageDst::TransferRead => vk::AccessFlags::TRANSFER_READ,
|
||||
ImageDst::TransferWrite => vk::AccessFlags::TRANSFER_WRITE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The barrier of `range` of `image` from `old` to `new` (the same layout for no move), after
|
||||
/// the `src` accesses before it and before the `dst` accesses after it, recorded for a queue
|
||||
/// family of `family`'s queue flags, of no queue family transfer.
|
||||
pub(crate) fn image_barrier(
|
||||
image: vk::Image,
|
||||
range: vk::ImageSubresourceRange,
|
||||
(old, new): (vk::ImageLayout, vk::ImageLayout),
|
||||
src: vk::AccessFlags,
|
||||
dst: ImageDst,
|
||||
family: vk::QueueFlags,
|
||||
) -> vk::ImageMemoryBarrier<'static> {
|
||||
vk::ImageMemoryBarrier::default()
|
||||
.src_access_mask(src)
|
||||
.dst_access_mask(dst.access(family))
|
||||
.old_layout(old)
|
||||
.new_layout(new)
|
||||
.src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
|
||||
.dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
|
||||
.image(image)
|
||||
.subresource_range(range)
|
||||
}
|
||||
@@ -79,8 +79,8 @@ use metal2vulkan::metal::format::{
|
||||
};
|
||||
use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage};
|
||||
use metal2vulkan::vk::{
|
||||
Format, FormatBlock, FormatFeatureFlags2, ImageCreateFlags, ImageType, ImageUsageFlags,
|
||||
NumericType, SampleCountFlags,
|
||||
ColorComponentFlags, Format, FormatBlock, FormatFeatureFlags2, ImageCreateFlags, ImageType,
|
||||
ImageUsageFlags, NumericType, SampleCountFlags,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
@@ -113,6 +113,10 @@ pub(super) struct DepthImageFacts {
|
||||
pub(super) outside_unit_range: bool,
|
||||
/// `DriverFact::DepthTestKeepsDenormals`.
|
||||
pub(super) test_denormals: bool,
|
||||
/// `DriverFact::DepthTestComparesMagnitudes`: the depth test is Metal's for every value a
|
||||
/// `D32_SFLOAT` image holds, so no target renders over a magnitude stand-in
|
||||
/// (`texture/signed_depth.rs`).
|
||||
pub(super) test_magnitudes: bool,
|
||||
}
|
||||
|
||||
impl DepthImageFacts {
|
||||
@@ -122,6 +126,7 @@ impl DepthImageFacts {
|
||||
denormals: facts.contains(&DriverFact::DepthImageKeepsDenormals),
|
||||
outside_unit_range: facts.contains(&DriverFact::DepthImageKeepsValuesOutsideUnitRange),
|
||||
test_denormals: facts.contains(&DriverFact::DepthTestKeepsDenormals),
|
||||
test_magnitudes: facts.contains(&DriverFact::DepthTestComparesMagnitudes),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -467,6 +472,21 @@ pub(super) fn compatible(image: Format, view: Format, family: bool) -> bool {
|
||||
!is_compressed(&a) || family
|
||||
}
|
||||
|
||||
/// Whether Vulkan copies texels between images of color formats `a` and `b` of one texel block
|
||||
/// size (`vkCmdCopyImage`, `VUID-vkCmdCopyImage-srcImage-01548`): "Color formats with the same
|
||||
/// texel block size are considered size-compatible as long as neither or both are alpha formats
|
||||
/// (e.g., VK_FORMAT_A8_UNORM)" (the Formats chapter's "Size Compatibility"). An alpha format's
|
||||
/// one component is alpha. Elsewhere the copy goes through a buffer, whose copies take each
|
||||
/// image's texel block size alone.
|
||||
pub(super) fn copies_between(a: Format, b: Format) -> bool {
|
||||
let alpha = |format: Format| {
|
||||
format
|
||||
.block()
|
||||
.is_some_and(|block| block.color_components == ColorComponentFlags::A)
|
||||
};
|
||||
alpha(a) == alpha(b)
|
||||
}
|
||||
|
||||
/// Whether a color format's block is a compressed block: more than one texel, or (Vulkan's
|
||||
/// registry counts a PVRTC block as one texel) components that share no width and pack into no
|
||||
/// word.
|
||||
@@ -569,9 +589,9 @@ fn plan_held(
|
||||
let samples = sample_count(layout.samples).ok_or_else(|| {
|
||||
ImageRefusal::Unsupported(Unsupported::not_representable(Feature::TextureSampleCount))
|
||||
})?;
|
||||
// Metal makes a multisample array, memoryless ones included (RT6 probe 6c); a device whose
|
||||
// portability subset withholds `multisampleArrayImage` makes no multisampled image of more
|
||||
// than one layer's type (`VUID-VkImageCreateInfo-multisampleArrayImage-04460`).
|
||||
// Metal makes a multisample array, memoryless ones included (a Metal probe on an M4); a device
|
||||
// whose portability subset withholds `multisampleArrayImage` makes no multisampled image of
|
||||
// more than one layer's type (`VUID-VkImageCreateInfo-multisampleArrayImage-04460`).
|
||||
if layout.texture_type == TextureType::Type2DMultisampleArray
|
||||
&& profile
|
||||
.enabled()
|
||||
|
||||
@@ -47,6 +47,7 @@ use super::owned_kernel::{OwnedKernel, OwnedModule, OwnedSets};
|
||||
use super::resource::ResourceKey;
|
||||
use super::tracker::{Access, Barrier, Use, UseRange};
|
||||
use super::upload::Upload;
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::bind::{
|
||||
ExecutionStatus, IndexBoundsFillModule, IndexBoundsPass, IndexBoundsPlanModule, IndexBufferRef,
|
||||
@@ -360,7 +361,7 @@ impl BoundsSteps {
|
||||
///
|
||||
/// `command_buffer` is the encoder's, recording outside a render pass, and only the encoder
|
||||
/// records it.
|
||||
pub(super) unsafe fn record_in(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer) {
|
||||
pub(super) unsafe fn record_in(&self, raw: &Vk, command_buffer: vk::CommandBuffer) {
|
||||
// SAFETY: as the caller states; barriers need nothing more.
|
||||
unsafe {
|
||||
Barrier::everything().record(raw, command_buffer);
|
||||
@@ -374,7 +375,7 @@ impl BoundsSteps {
|
||||
/// # Safety
|
||||
///
|
||||
/// `command_buffer` is recording outside a render pass, and only one encoder records it.
|
||||
unsafe fn dispatches(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer) {
|
||||
unsafe fn dispatches(&self, raw: &Vk, command_buffer: vk::CommandBuffer) {
|
||||
let bind = |kernel: &OwnedKernel, sets: &[vk::DescriptorSet]| {
|
||||
// SAFETY: as the caller states; the kernel is the device's, and its sets are live
|
||||
// until the command buffer completes (retained by `into_steps`).
|
||||
|
||||
@@ -42,6 +42,7 @@ use super::owned_kernel::{OwnedKernel, OwnedModule, OwnedSets};
|
||||
use super::resource::ResourceKey;
|
||||
use super::tracker::{Access, Barrier, Use, UseRange};
|
||||
use super::upload::Upload;
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::bind::{
|
||||
ExecutionStatus, IndexBufferRef, IndexRewriteModule, IndexRewritePass, IndirectRef,
|
||||
@@ -430,7 +431,7 @@ impl RewriteSteps {
|
||||
///
|
||||
/// `command_buffer` is the encoder's, recording outside a render pass, and only the encoder
|
||||
/// records it.
|
||||
pub(super) unsafe fn record_in(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer) {
|
||||
pub(super) unsafe fn record_in(&self, raw: &Vk, command_buffer: vk::CommandBuffer) {
|
||||
// SAFETY: as the caller states; barriers need nothing more.
|
||||
unsafe {
|
||||
Barrier::everything().record(raw, command_buffer);
|
||||
@@ -446,7 +447,7 @@ impl RewriteSteps {
|
||||
/// # Safety
|
||||
///
|
||||
/// `command_buffer` is recording outside a render pass, and only one encoder records it.
|
||||
unsafe fn dispatch(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer) {
|
||||
unsafe fn dispatch(&self, raw: &Vk, command_buffer: vk::CommandBuffer) {
|
||||
let phases = self.kernels.iter().zip(RewritePhase::ALL).zip(&self.sets);
|
||||
for (at, ((kernel, phase), sets)) in phases.enumerate() {
|
||||
// SAFETY: as the caller states; each kernel is the device's, its sets (whose layout
|
||||
|
||||
@@ -41,13 +41,14 @@
|
||||
//! draw with their own, both are `NotImplemented(IndirectRenderCommands)`. A buffer that supports
|
||||
//! color attachment mapping executes as any other in an encoder that maps none, the runtime's
|
||||
//! every encoder, as Metal's does. An object threadgroup length a render command sets is taken at
|
||||
//! any index, as plain Metal takes one past the descriptor's count, and kept by none: no pipeline
|
||||
//! the runtime makes reads one. Apple's private properties (EV APX2-spi1-m4, the same M4):
|
||||
//! stencil reference values, depth test bounds, scissor rectangles, viewports and the blend color
|
||||
//! left to the command are taken as the render states above (validation stops each "must be
|
||||
//! inherited on this device"; plain Metal draws with the encoder's viewport, scissor, cull mode
|
||||
//! and winding); the scissor rectangle and viewport counts and `allowOverrideRenderStates` are
|
||||
//! kept, and change nothing a command draws.
|
||||
//! any index, as plain Metal takes one past the descriptor's count, and kept by none: an executed
|
||||
//! command whose mesh draw's object function reads one is
|
||||
//! `NotImplemented(IndirectRenderCommands)`. Apple's private properties (EV APX2-spi1-m4, the
|
||||
//! same M4): stencil reference values, depth test bounds, scissor rectangles, viewports and the
|
||||
//! blend color left to the command are taken as the render states above (validation stops each
|
||||
//! "must be inherited on this device"; plain Metal draws with the encoder's viewport, scissor,
|
||||
//! cull mode and winding); the scissor rectangle and viewport counts and
|
||||
//! `allowOverrideRenderStates` are kept, and change nothing a command draws.
|
||||
//! - **Read-back.** [`IndirectCommandBuffer::commands`] decodes a range of records into typed
|
||||
//! commands, a runtime extension standing for Metal's private getters.
|
||||
//! - **Execution.** A compute encoder's `execute_commands_in_buffer` runs a range of the records
|
||||
@@ -3541,9 +3542,9 @@ impl IndirectRenderCommand {
|
||||
|
||||
/// `setObjectThreadgroupMemoryLength:atIndex:`: taken at any index, as plain Metal takes one
|
||||
/// at or past the descriptor's `max_object_threadgroup_memory_bind_count`, where its
|
||||
/// validation stops it, and runs the command as before (EV IRX-inh2-m4, an M4). No pipeline
|
||||
/// the runtime makes reads it: an object function's threadgroup memory is refused
|
||||
/// (`NotImplemented(MeshShading)`), so the command keeps none. Refused (`Invalid`): a command
|
||||
/// validation stops it, and runs the command as before (EV IRX-inh2-m4, an M4). The command
|
||||
/// keeps none: an executed command whose mesh draw's object function has threadgroup memory
|
||||
/// arguments is `NotImplemented(IndirectRenderCommands)`. Refused (`Invalid`): a command
|
||||
/// of a buffer whose command types hold no mesh draw (`ObjectThreadgroupMemory`), where
|
||||
/// Metal's process ends, and of a buffer of dispatches (`CommandKind`).
|
||||
pub fn set_object_threadgroup_memory_length(
|
||||
|
||||
@@ -87,6 +87,7 @@ use super::tracker::{Access, Barrier, Use, UseRange};
|
||||
use super::upload::Upload;
|
||||
use super::values::ResourceOptions;
|
||||
use super::Device;
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::bind::{
|
||||
Dispatch, FlatArguments, FlatDispatchModule, FlatIndirect, ImageblockSize, PredicationStep,
|
||||
@@ -470,7 +471,7 @@ impl FlatPreprocess {
|
||||
/// gate lies in the command buffer's arena.
|
||||
pub(super) unsafe fn record(
|
||||
&self,
|
||||
raw: &ash::Device,
|
||||
raw: &Vk,
|
||||
command_buffer: vk::CommandBuffer,
|
||||
gate: Option<&Upload>,
|
||||
) {
|
||||
|
||||
@@ -118,7 +118,8 @@ impl Texture {
|
||||
/// driver's own linear image lays its rows out otherwise than `bytes_per_row`
|
||||
/// (`WorkCounts::pitched_host_images` counts them). Ask such an image's layout of its memory
|
||||
/// plane (`VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT`, not the color aspect), and its modifier
|
||||
/// with `vkGetImageDrmFormatModifierPropertiesEXT`.
|
||||
/// with `vkGetImageDrmFormatModifierPropertiesEXT`. Textures of one image over the same bytes
|
||||
/// of one import of host pages give the same `VkImage`, which they share.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
@@ -173,7 +174,10 @@ impl CommandQueue {
|
||||
/// and presents (`vkQueuePresentKHR`) go there, externally synchronized as Vulkan requires.
|
||||
/// On MoltenVK, where the runtime relays the driver's command-buffer failures, it submits no
|
||||
/// work with a fence of its own after `f` under the same lock, so a failure of the caller's
|
||||
/// submissions stays the caller's.
|
||||
/// submissions stays the caller's. There the runtime's frees of its memory wait for its own
|
||||
/// work in flight, not for the caller's
|
||||
/// (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`): a submission of the caller's
|
||||
/// still pending whose pipelines read device addresses may fail.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
//! The hasher of the runtime's maps keyed by its own identities (`ResourceKey`, sequence numbers):
|
||||
//! a multiply-and-fold of each word, as the hazard tracker looks up every resource a batch uses
|
||||
//! as it plans the batch (`tracker.rs`).
|
||||
//! The hasher of the runtime's maps keyed by its own identities (`ResourceKey`, sequence numbers)
|
||||
//! and by the descriptions it looks its Vulkan objects up by (an image's views, a pass's
|
||||
//! compatible render pass): a multiply-and-fold of each word. Those maps are looked up on the
|
||||
//! encoding thread at every draw and command (the hazard tracker's uses, a buffer's host
|
||||
//! aliases, a draw's texture views, the buffers over host pages a command takes, `rebind.rs`),
|
||||
//! as each pass opens (a new texture's unwritten texels) and as each batch is planned
|
||||
//! (`tracker.rs`) or committed (the resources it reached, `used_resources.rs`).
|
||||
//!
|
||||
//! The standard maps' default hasher (SipHash-1-3 with random keys) resists inputs chosen to
|
||||
//! collide, which these keys, numbered by the runtime, are not, and costs its rounds at every
|
||||
//! lookup. The multiply spreads consecutive numbers over the high bits the map's control bytes
|
||||
//! read, and the fold brings them down to the low bits its buckets index by. Iteration order
|
||||
//! follows the hash, which none of these maps' users depends on.
|
||||
//! collide, and costs its rounds at every lookup. Identities are numbered by the runtime, so a
|
||||
//! program cannot choose them. A program does choose the descriptions behind a view or a pass,
|
||||
//! but each distinct one costs it a Vulkan object, or stays in a bounded memo (a render
|
||||
//! encoder's kept views, `binding.rs`). So keys made to collide would slow only that program's
|
||||
//! own lookups. The multiply spreads consecutive numbers over the high bits the map's control
|
||||
//! bytes read, and the fold brings them down to the low bits its buckets index by. Iteration order
|
||||
//! follows the hash. None of these maps' users depends on it; under the random keys it changed
|
||||
//! from map to map.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{BuildHasherDefault, Hasher};
|
||||
|
||||
/// A map keyed by the runtime's own identities ([`KeyHasher`]).
|
||||
/// A map keyed by the runtime's own identities or object descriptions ([`KeyHasher`]).
|
||||
pub(crate) type KeyMap<K, V> = HashMap<K, V, BuildHasherDefault<KeyHasher>>;
|
||||
|
||||
/// The module docs' hasher.
|
||||
|
||||
@@ -95,6 +95,7 @@ mod fetch_reach;
|
||||
mod fill_value;
|
||||
mod fragment_imageblock;
|
||||
mod framebuffer_fetch;
|
||||
mod freed_memory;
|
||||
mod fresh_unwritten;
|
||||
mod function_table;
|
||||
#[doc(hidden)]
|
||||
@@ -106,6 +107,9 @@ mod heap;
|
||||
mod heap_sets;
|
||||
mod host_aliases;
|
||||
mod host_memory;
|
||||
#[cfg(unix)]
|
||||
mod host_residency;
|
||||
mod image_barrier;
|
||||
mod image_plan;
|
||||
mod index_bounds;
|
||||
mod index_rewrite;
|
||||
@@ -141,11 +145,13 @@ mod pipeline;
|
||||
mod pixel_format_info;
|
||||
mod predication;
|
||||
mod private_properties;
|
||||
mod program_objects;
|
||||
mod pvrtc;
|
||||
mod queue;
|
||||
mod range;
|
||||
mod rate_map;
|
||||
mod rate_mapped_pass;
|
||||
mod reader_sizes;
|
||||
mod rebind;
|
||||
mod release;
|
||||
mod render;
|
||||
@@ -169,6 +175,7 @@ mod sampler_listing;
|
||||
mod scheduler;
|
||||
mod shader_cache;
|
||||
mod shadow;
|
||||
mod shadow_copy_back;
|
||||
mod shadow_merge;
|
||||
mod shadow_stencil;
|
||||
mod sharing;
|
||||
@@ -181,6 +188,7 @@ mod texture;
|
||||
mod texture_descriptor;
|
||||
mod tile_pass;
|
||||
mod tracker;
|
||||
mod trails;
|
||||
mod two_planes;
|
||||
mod unique_identifier;
|
||||
mod upload;
|
||||
@@ -234,8 +242,8 @@ pub use error::Unproven;
|
||||
pub use error::{
|
||||
ArchivedPipeline, BinaryArchiveError, BinaryArchiveMiss, CommandBufferError, DeadlockCause,
|
||||
DriverSetting, Error, InstanceApiVersion, Invalid, LoaderNotFound, MemoryKind,
|
||||
MeshRecordsOverflow, Problem, RuntimeGap, SamplerLimit, ShaderCacheError, TimedOut,
|
||||
VkResultCode,
|
||||
MeshRecordsOverflow, Problem, RuntimeGap, SamplerLimit, ShaderCacheError,
|
||||
TessellationRecordsOverflow, TimedOut, VkResultCode,
|
||||
};
|
||||
pub use error::{FailedPipeline, FailedState, PipelineCreationCause};
|
||||
pub use event::{
|
||||
|
||||
@@ -53,6 +53,7 @@ use super::render_pass::Target;
|
||||
use super::resource::ResourceKey;
|
||||
use super::tracker::{Access, Barrier, Use};
|
||||
use super::Device;
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
use metal2vulkan::bind::ShadowMergeModule;
|
||||
|
||||
@@ -319,7 +320,7 @@ impl LinearMerge {
|
||||
/// `command_buffer` is recording outside a render pass, and only the caller records it; the
|
||||
/// merge, the images and the scratch live until it completes, and every image rests in
|
||||
/// `GENERAL`.
|
||||
pub(super) unsafe fn reload_in(&self, device: &ash::Device, command_buffer: vk::CommandBuffer) {
|
||||
pub(super) unsafe fn reload_in(&self, device: &Vk, command_buffer: vk::CommandBuffer) {
|
||||
// SAFETY: the caller's contract; the copy's region lies in both images (the box, inside
|
||||
// the render area), whose transfer usage the copies in already take.
|
||||
unsafe {
|
||||
@@ -364,7 +365,7 @@ impl LinearMerge {
|
||||
/// # Safety
|
||||
///
|
||||
/// As for [`LinearMerge::reload_in`].
|
||||
unsafe fn merge_in(&self, device: &ash::Device, raw: vk::CommandBuffer) {
|
||||
unsafe fn merge_in(&self, device: &Vk, raw: vk::CommandBuffer) {
|
||||
let changed: Vec<vk::BufferImageCopy> = self
|
||||
.regions
|
||||
.iter()
|
||||
|
||||
@@ -239,12 +239,15 @@ fn backed(pf: PixelFormat) -> Result<(), BufferTextureProblem> {
|
||||
/// `pf`'s alignment in a buffer ([`LINEAR_ALIGNMENT`]) on a device answering at `level`, or why
|
||||
/// no buffer can back it: also a format the level describes none of
|
||||
/// ([`MetalLevel::describes`]), whose alignment queries Metal asserts on (EVs XRR2-pla1-m4 and
|
||||
/// XRR2-pla1-m3).
|
||||
/// XRR2-pla1-m3), and one it describes as a depth or a stencil format, `AnyDepth` and
|
||||
/// `AnyStencil` among them, which Vulkan has no format for ("Linear textures do not support
|
||||
/// depth/stencil pixel formats", EV M27-lin1-m3).
|
||||
pub(super) fn linear_alignment(
|
||||
pf: PixelFormat,
|
||||
level: MetalLevel,
|
||||
) -> Result<u64, BufferTextureProblem> {
|
||||
if !level.describes(pf) {
|
||||
let info = level.pixel_format_info(u64::from(pf.as_raw()));
|
||||
if !info.describes_a_format() || info.depth_or_stencil() {
|
||||
return Err(BufferTextureProblem::NotLinear { pixel_format: pf });
|
||||
}
|
||||
backed(pf).map(|()| LINEAR_ALIGNMENT)
|
||||
@@ -796,9 +799,10 @@ pub(super) fn only_reads(usage: TextureUsage) -> bool {
|
||||
/// memory locations"). So a texture that renders or writes is a shadow: a write back of what was
|
||||
/// read would undo the program's write of the bytes meanwhile, which Metal keeps, and lavapipe
|
||||
/// reads the bytes its 4-texel blocks reach past a row's texels and writes them back, a signaling
|
||||
/// NaN's bits quieted. A texture that only reads meets the bytes at its first move alone, which
|
||||
/// keeps them where the driver's move does (`docs/FAST-PATHS.md`'s known gap, which tight rows
|
||||
/// share): the policy's default aliases them, and `PaddedReadsPolicy::Shadow` keeps the shadow.
|
||||
/// NaN's bits quieted. A texture that only reads meets the bytes at its first move alone, across
|
||||
/// which the host keeps them (`texture/first_move.rs`'s `Keep`; a CPU write to them meanwhile is
|
||||
/// undone, `docs/FAST-PATHS.md`'s known gaps): the policy's default aliases them, and
|
||||
/// `PaddedReadsPolicy::Shadow` keeps the shadow.
|
||||
pub(super) fn holding(
|
||||
layout: &BufferLayout,
|
||||
usage: TextureUsage,
|
||||
|
||||
@@ -33,12 +33,20 @@
|
||||
//! every command buffer committed meanwhile. A command buffer holds it weakly from its commit
|
||||
//! to its first submission, which takes the table of the list then, the same one where the
|
||||
//! list is unchanged, and holds it, and with it each listed buffer's pages, until it completes
|
||||
//! (Metal resolves what a command buffer reaches as it submits it). So a buffer released while a
|
||||
//! submitted command buffer may reach it keeps its memory until that command buffer completed,
|
||||
//! and one released while only command buffers not yet submitted reach it goes at once, as
|
||||
//! Metal's does (the consumer's G344: a release after the commit lets the pages go, and the reach
|
||||
//! reads 0). A commit while the list is unchanged makes nothing (the cost, measured on an Apple
|
||||
//! M4 and a Radeon 780M).
|
||||
//! (Metal resolves what a command buffer reaches as it submits it). A host step after then
|
||||
//! resolves against the table current as it runs, which the command buffer holds from then on
|
||||
//! too (`CommandBuffer::residency`): the commands the step records may reach its buffers. So a
|
||||
//! buffer released while a submitted command buffer may reach it keeps its memory until that
|
||||
//! command buffer completed, announced (`host-deallocator-delayed`): Metal's deallocator runs at
|
||||
//! the release, and the command buffer's later accesses reach nothing (the M3 Max under macOS
|
||||
//! 27.0.1, probe `dealloc-probe4`), where Vulkan frees no memory that submitted commands may
|
||||
//! still use (`VUID-vkFreeMemory-memory-00677`). One the command buffer's commands name goes as
|
||||
//! it completes, where Metal's goes too, announced only where another submitted command buffer's
|
||||
//! table lists it: a command buffer lets go of its tables before what it retained
|
||||
//! (`CommandBufferShared::complete`). One released while only command buffers not
|
||||
//! yet submitted reach it goes at once, as Metal's does (the consumer's G344: a release after the
|
||||
//! commit lets the pages go, and the reach reads 0). A commit while the list is unchanged makes
|
||||
//! nothing (the cost, measured on an Apple M4 and a Radeon 780M).
|
||||
//! - **Kept as the list changes**. The device keeps the list sorted, each buffer with its range and
|
||||
//! a hold on its pages from its listing on, in chunks the tables share (`sorted_chunks.rs`): a
|
||||
//! buffer made or gone changes one chunk, and the next table copies none of the others, upgrades
|
||||
@@ -167,7 +175,7 @@ impl LiveBuffers {
|
||||
|
||||
/// List `buffer`, unless it is: a change of the list only where it was not.
|
||||
fn register(&self, buffer: &Buffer) {
|
||||
let key = (buffer.gpu_address().0, buffer.object_id());
|
||||
let key = (buffer.metal_address().0, buffer.object_id());
|
||||
if lock(&self.inner).listed.contains(&key) {
|
||||
return;
|
||||
}
|
||||
@@ -184,6 +192,17 @@ impl LiveBuffers {
|
||||
self.let_go(stale);
|
||||
}
|
||||
|
||||
/// `buffer`'s import was released while idle and imported again before its Metal address was
|
||||
/// handed out (`host_residency.rs`): where it is listed, its range is read again, its new
|
||||
/// `VkBuffer`'s, or none while it is released.
|
||||
pub(super) fn refresh(&self, buffer: &Buffer) {
|
||||
let (address, id) = (buffer.metal_address().0, buffer.object_id());
|
||||
if lock(&self.inner).listed.contains(&(address, id)) {
|
||||
self.forget(address, id);
|
||||
self.register(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffer `id` at Metal address `address` is gone.
|
||||
pub(super) fn forget(&self, address: u64, id: ObjectId) {
|
||||
let stale = {
|
||||
@@ -216,7 +235,7 @@ impl LiveBuffers {
|
||||
let mut inner = lock(&self.inner);
|
||||
let mut listed = Vec::new();
|
||||
for buffer in &gone {
|
||||
let key = (buffer.gpu_address().0, buffer.object_id());
|
||||
let key = (buffer.metal_address().0, buffer.object_id());
|
||||
listed.extend(inner.listed.remove(&key));
|
||||
}
|
||||
let mut stale = inner.change();
|
||||
|
||||
@@ -26,6 +26,11 @@
|
||||
//! buffers on an Apple M4, EV CPF-rset1-mvk4; MoltenVK's
|
||||
//! `MVKDevice::encodeGPUAddressableBuffers`).
|
||||
//!
|
||||
//! - **Freed after the batches in flight** where the driver fails pending work when memory a
|
||||
//! device-address buffer lay in is freed (`freed_memory.rs`): a block that goes has its buffer
|
||||
//! of addresses destroyed at once, and its memory waits, parked, until the batches and the
|
||||
//! device's own submissions made before it completed.
|
||||
//!
|
||||
//! - **Images apart**. An image the runtime places in memory of its own takes a block that holds
|
||||
//! images alone ([`Holds`], [`allocate_image`]): no buffer, a block's buffer of addresses among
|
||||
//! them, is bound into such a block, nor such an image into a buffers' block. An image over a
|
||||
@@ -38,15 +43,14 @@ use super::device::lock;
|
||||
#[cfg(unix)]
|
||||
use super::dma_buf::DmaBufPages;
|
||||
use super::error::{internal, vulkan, Error, MemoryKind};
|
||||
use super::freed_memory::{Parked, Parking};
|
||||
use super::range::RangeAllocator;
|
||||
use super::sharing::Sharing;
|
||||
use super::work_counts::Counters;
|
||||
use crate::release;
|
||||
use ash::vk;
|
||||
use std::ptr::NonNull;
|
||||
#[cfg(unix)]
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// The size of a pooled block, at most the device's `maxMemoryAllocationSize`.
|
||||
pub(super) const BLOCK_BYTES: u64 = 64 << 20;
|
||||
@@ -424,6 +428,12 @@ impl Mapped {
|
||||
pub(super) fn as_ptr(self) -> *mut u8 {
|
||||
self.0.as_ptr()
|
||||
}
|
||||
|
||||
/// The address `bytes` past this one, in the same mapping.
|
||||
pub(super) fn add(self, bytes: u64) -> Mapped {
|
||||
let bytes = usize::try_from(bytes).unwrap_or(usize::MAX);
|
||||
Mapped(NonNull::new(self.0.as_ptr().wrapping_add(bytes)).unwrap_or(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// One `VkDeviceMemory` block.
|
||||
@@ -456,12 +466,26 @@ impl Block {
|
||||
///
|
||||
/// Nothing is placed in the block any more, and no command that reads it is pending.
|
||||
unsafe fn release(self, device: &ash::Device) {
|
||||
if let Some(addresses) = self.addresses {
|
||||
// SAFETY: the caller's contract.
|
||||
let memory = unsafe { self.release_addresses(device) };
|
||||
// SAFETY: the caller's contract; freeing unmaps it.
|
||||
unsafe { release::object(device, memory) };
|
||||
}
|
||||
|
||||
/// Destroy the block's buffer of addresses: its memory, to free.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Nothing is placed in the block any more, and no command that reads the buffer is pending.
|
||||
unsafe fn release_addresses(self, device: &ash::Device) -> vk::DeviceMemory {
|
||||
let Block {
|
||||
memory, addresses, ..
|
||||
} = self;
|
||||
if let Some(addresses) = addresses {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { release::object(device, addresses.raw) };
|
||||
}
|
||||
// SAFETY: the caller's contract; freeing unmaps it.
|
||||
unsafe { release::object(device, self.memory) };
|
||||
memory
|
||||
}
|
||||
}
|
||||
|
||||
@@ -669,6 +693,13 @@ pub(super) struct Memory {
|
||||
families: Vec<u32>,
|
||||
/// The bytes of the blocks allocated so far ([`Memory::allocated`]).
|
||||
allocated: u64,
|
||||
/// Where the device's driver fails pending work when memory a device-address buffer lay in
|
||||
/// is freed, the record its blocks that go wait by (`freed_memory.rs`).
|
||||
parking: Option<Arc<Parking>>,
|
||||
/// The blocks that went and wait, their buffers of addresses destroyed.
|
||||
parked: Vec<Parked>,
|
||||
/// The blocks that waited so far ([`Memory::parked`]).
|
||||
parked_count: u64,
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
@@ -681,6 +712,7 @@ impl Memory {
|
||||
device_address: bool,
|
||||
unified: bool,
|
||||
families: Vec<u32>,
|
||||
parking: Option<Arc<Parking>>,
|
||||
) -> Memory {
|
||||
let count = properties.memory_type_count as usize;
|
||||
let types = properties.memory_types[..count.min(vk::MAX_MEMORY_TYPES)].to_vec();
|
||||
@@ -696,9 +728,25 @@ impl Memory {
|
||||
unified,
|
||||
families,
|
||||
allocated: 0,
|
||||
parking,
|
||||
parked: Vec::new(),
|
||||
parked_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The blocks that waited for the batches in flight as they went, so far, and those that
|
||||
/// wait now (`freed_memory.rs`).
|
||||
pub(super) fn parked(&self) -> (u64, u64) {
|
||||
(self.parked_count, self.parked.len() as u64)
|
||||
}
|
||||
|
||||
/// Let the blocks that go from now on wait by `parking` (`freed_memory.rs`), as where the
|
||||
/// device's driver has the defect: the crate's tests' way to take that path on any device.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(super) fn park_by(&mut self, parking: Arc<Parking>) {
|
||||
self.parking = Some(parking);
|
||||
}
|
||||
|
||||
/// The bytes of `VkDeviceMemory` allocated so far for blocks of the runtime's own memory,
|
||||
/// pooled or dedicated, whether freed since or not: host memory imported counts in none.
|
||||
pub(super) fn allocated(&self) -> u64 {
|
||||
@@ -792,7 +840,7 @@ impl Memory {
|
||||
};
|
||||
if let Some(counts) = addressed {
|
||||
if let Err(error) = self.address_block(device, type_index, block, counts) {
|
||||
self.release_range(device, (holds, type_index), block, offset, size);
|
||||
drop(self.release_range(device, (holds, type_index), block, offset, size, None));
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
@@ -945,7 +993,8 @@ impl Memory {
|
||||
}
|
||||
|
||||
/// Return `[offset, offset + size)` of block `block` of memory type `type_index`, freeing the
|
||||
/// block when it empties ([`Pool::release`]).
|
||||
/// block when it empties ([`Pool::release`]); `after` goes once it is freed. `after`, given
|
||||
/// back for the caller to let go of with no lock held, unless the block waits with it.
|
||||
fn release_range(
|
||||
&mut self,
|
||||
device: &ash::Device,
|
||||
@@ -953,13 +1002,71 @@ impl Memory {
|
||||
block: usize,
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) {
|
||||
if let Some(block) = self.pool(holds, type_index).release(block, offset, size) {
|
||||
after: Option<Box<dyn Send>>,
|
||||
) -> Option<Box<dyn Send>> {
|
||||
match self.pool(holds, type_index).release(block, offset, size) {
|
||||
// SAFETY: no resource is placed in the block any more.
|
||||
unsafe { block.release(device) };
|
||||
Some(block) => unsafe { self.let_go(device, block, after) },
|
||||
None => after,
|
||||
}
|
||||
}
|
||||
|
||||
/// Free `block`, or where the device parks freed memory (`freed_memory.rs`), destroy its
|
||||
/// buffer of addresses and let its memory wait, with `after`, for the batches submitted
|
||||
/// before now, unless they completed. `after`, given back where the memory was freed here.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Nothing is placed in the block any more, and no command that reads it is pending.
|
||||
unsafe fn let_go(
|
||||
&mut self,
|
||||
device: &ash::Device,
|
||||
block: Block,
|
||||
after: Option<Box<dyn Send>>,
|
||||
) -> Option<Box<dyn Send>> {
|
||||
let Some(parking) = &self.parking else {
|
||||
// SAFETY: the caller's.
|
||||
unsafe { block.release(device) };
|
||||
return after;
|
||||
};
|
||||
// Out of the driver's list first, then the batches that may list it noted.
|
||||
// SAFETY: the caller's.
|
||||
let memory = unsafe { block.release_addresses(device) };
|
||||
let noted = parking.note();
|
||||
if !parking.reached(¬ed) {
|
||||
parking.waits();
|
||||
// Checked again once counted: a waiter that published a value before the count did
|
||||
// not see it, so the value is seen here (both sequentially consistent).
|
||||
if !parking.reached(¬ed) {
|
||||
self.parked_count += 1;
|
||||
self.parked.push(Parked {
|
||||
noted,
|
||||
memory,
|
||||
after,
|
||||
});
|
||||
return None;
|
||||
}
|
||||
parking.freed(1);
|
||||
}
|
||||
// SAFETY: the caller's; every batch that may list it completed.
|
||||
unsafe { release::object(device, memory) };
|
||||
after
|
||||
}
|
||||
|
||||
/// The blocks that wait whose values were reached, out of the list, to free with no lock held
|
||||
/// (`freed_memory.rs`).
|
||||
pub(super) fn reached(&mut self) -> Vec<Parked> {
|
||||
let Some(parking) = &self.parking else {
|
||||
return Vec::new();
|
||||
};
|
||||
let reached: Vec<Parked> = self
|
||||
.parked
|
||||
.extract_if(.., |parked| parking.reached(&parked.noted))
|
||||
.collect();
|
||||
parking.freed(reached.len());
|
||||
reached
|
||||
}
|
||||
|
||||
/// Import the caller's host memory, `size` bytes at `pointer` (both multiples of the device's
|
||||
/// import alignment), as a dedicated block of the best memory type of `class` among
|
||||
/// `allowed` (the types both the pointer and the resource take): its placement at offset 0,
|
||||
@@ -1089,9 +1196,20 @@ impl Memory {
|
||||
|
||||
/// Return `placement`'s memory, freeing its block when it empties.
|
||||
pub(super) fn free(&mut self, device: &ash::Device, placement: &Placement) {
|
||||
drop(self.free_then(device, placement, None));
|
||||
}
|
||||
|
||||
/// [`free`](Self::free), and `after` goes once the block is freed: given back for the caller
|
||||
/// to let go of with no lock held, unless the block waits with it (`freed_memory.rs`).
|
||||
pub(super) fn free_then(
|
||||
&mut self,
|
||||
device: &ash::Device,
|
||||
placement: &Placement,
|
||||
after: Option<Box<dyn Send>>,
|
||||
) -> Option<Box<dyn Send>> {
|
||||
// The caller's memory is the caller's to free.
|
||||
let Some(index) = placement.block else {
|
||||
return;
|
||||
return after;
|
||||
};
|
||||
self.release_range(
|
||||
device,
|
||||
@@ -1099,17 +1217,26 @@ impl Memory {
|
||||
index,
|
||||
placement.offset,
|
||||
placement.size,
|
||||
);
|
||||
after,
|
||||
)
|
||||
}
|
||||
|
||||
/// Free every block: the device is being destroyed and no resource is left.
|
||||
pub(super) fn destroy(&mut self, device: &ash::Device) {
|
||||
/// Free every block, those that wait too: the device is being destroyed, its queues idle,
|
||||
/// and no resource is left. What waited with them, for the caller to let go of with no lock
|
||||
/// held.
|
||||
pub(super) fn destroy(&mut self, device: &ash::Device) -> Vec<Box<dyn Send>> {
|
||||
for pool in &mut self.pools {
|
||||
for block in pool.drain() {
|
||||
// SAFETY: no resource is left, and the device is idle.
|
||||
unsafe { block.release(device) };
|
||||
}
|
||||
}
|
||||
let mut after = Vec::new();
|
||||
for parked in self.parked.drain(..) {
|
||||
// SAFETY: nothing is placed in it, and the device is idle.
|
||||
after.extend(unsafe { parked.release(device) });
|
||||
}
|
||||
after
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
use crate::error::{Error, Problem, Unproven};
|
||||
use crate::texture::heap_tiled::{BlockFamily, BlockPlacement, GpuRows};
|
||||
use crate::Degradation;
|
||||
use metal2vulkan::bind::CompressedBlit;
|
||||
use metal2vulkan::bind::{CompressedBlit, MipmapRule};
|
||||
use metal2vulkan::metal::PixelFormat;
|
||||
use std::fmt;
|
||||
|
||||
@@ -34,8 +34,11 @@ pub enum MetalLevel {
|
||||
/// macOS 26.7 (build 25G229), measured on an Apple M3 Max (EVs XRR2-pfi1-m3 and
|
||||
/// XRR2-pla1-m3).
|
||||
MacOS26_7,
|
||||
/// macOS 27.0.1 (build 26A434), measured on an Apple M4 (EVs XRR2-pfi1-m4, XRR2-pf576b-m4
|
||||
/// and XRR2-pla1-m4).
|
||||
/// macOS 27.0.1 (build 26A434), measured on an Apple M3 Max (EVs M27-pfi1-m3, M27-lin1-m3,
|
||||
/// M27-heap1-m3, M27-props1-m3, M27-mips1-m3 to M27-mips4-m3 and M27-imp1-m3), and where no
|
||||
/// M3 Max probe has replaced it, on an Apple M4 (heap blocks and compressed blits). An M4's
|
||||
/// answers differ where both were measured in the formats from 630 to 645, which it describes,
|
||||
/// in `gpuCoreCount` and in `supportsComputeCompressedTextureWrite`.
|
||||
MacOS27_0_1,
|
||||
}
|
||||
|
||||
@@ -71,6 +74,13 @@ struct Row {
|
||||
/// through a losslessly compressed texture (`compressed_blit.rs`); where not, the runtime
|
||||
/// keeps the bytes, its device's answer.
|
||||
compressed_blits: bool,
|
||||
/// The alignment its `heapTextureSizeAndAlignWithDescriptor:` answers, with 0 bytes, for a
|
||||
/// texture of `Unspecialized`, `RGBA16Float_XR`, `AnyDepth` or `AnyStencil` of a type with
|
||||
/// layers, faces or depth: a 1D or 2D array, a cube, a cube array, a 3D texture or a 2D
|
||||
/// multisample array (`texture/heap.rs`'s `no_texture_alignment`).
|
||||
no_texture_stack_alignment: u64,
|
||||
/// How its Metal's `generateMipmapsForTexture:` makes each level after the first.
|
||||
mipmaps: MipmapRule,
|
||||
}
|
||||
|
||||
/// How a level's Metal places a block-compressed texture's blocks in its levels' tiles, per
|
||||
@@ -104,11 +114,16 @@ const MACOS_26_7: Row = Row {
|
||||
// The package share-cblit on the consumer's M3 Max (25G229): every line of the predicate,
|
||||
// the four rules and the clears identical to the M4's.
|
||||
compressed_blits: true,
|
||||
// EVs APX2-un2-m3 and TTG-nil2-m3, plain and validated, every usage and storage mode.
|
||||
no_texture_stack_alignment: 16 << 10,
|
||||
mipmaps: MipmapRule::AppleM3MaxPasses,
|
||||
};
|
||||
|
||||
/// macOS 27.0.1 on an Apple M4: its descriptor knows every value the runtime names (it describes
|
||||
/// none of the three-channel formats and the 12-bit `Uint` formats from 646 to 650; the table of
|
||||
/// `pixel_format_info`).
|
||||
/// macOS 27.0.1 on an Apple M3 Max: its descriptor knows every value the runtime names (it
|
||||
/// describes none from 630 on but `AnyDepth` and `AnyStencil`; the table of
|
||||
/// `pixel_format_info`). Its heap blocks and compressed blits are an Apple M4's at 27.0.1, which
|
||||
/// no M3 Max probe has replaced (`docs/FAST-PATHS.md`, known gaps); the heap shapes the M3 Max
|
||||
/// was asked of every format (22,856 answers) are the model's.
|
||||
const MACOS_27_0_1: Row = Row {
|
||||
macos: "27.0.1",
|
||||
version: [27, 0, 1],
|
||||
@@ -123,6 +138,13 @@ const MACOS_27_0_1: Row = Row {
|
||||
},
|
||||
// EVs FXR-fxr3-m4, FXR-fxr5-m4 and FXR-cblit-m4: every rule matched every texel.
|
||||
compressed_blits: true,
|
||||
// EV M27-heap1-m3 (and an Apple M4 alike, EVs APX2-un1-m4, TTG-nil1-m4 and TTG-nil4-m4):
|
||||
// every type but a texture buffer 128, private and shared storage, `ShaderRead` and
|
||||
// `ShaderWrite` usage.
|
||||
no_texture_stack_alignment: 128,
|
||||
// EVs M27-mips1-m3 to M27-mips4-m3 and M27-imp1-m3: every level the filter of the level
|
||||
// above (`bind::mipmap_filter`'s "By release").
|
||||
mipmaps: MipmapRule::Filter,
|
||||
};
|
||||
|
||||
impl MetalLevel {
|
||||
@@ -196,6 +218,21 @@ impl MetalLevel {
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// The alignment the release's `heapTextureSizeAndAlignWithDescriptor:` answers, with 0
|
||||
/// bytes, for a texture of `Unspecialized`, `RGBA16Float_XR`, `AnyDepth` or `AnyStencil` of
|
||||
/// a type with layers, faces or depth (`Row::no_texture_stack_alignment`).
|
||||
pub(crate) fn no_texture_stack_alignment(self) -> u64 {
|
||||
self.row().no_texture_stack_alignment
|
||||
}
|
||||
|
||||
/// How the release's `generateMipmapsForTexture:` makes each level of a chain after the
|
||||
/// first on its Apple GPU (`MipmapFilterChain::plan`'s rule), which the device's mipmaps
|
||||
/// answer ([`BlitCommandEncoder::generate_mipmaps`](crate::BlitCommandEncoder::generate_mipmaps)).
|
||||
/// No Metal counterpart: Metal makes its own release's.
|
||||
pub fn mipmap_rule(self) -> MipmapRule {
|
||||
self.row().mipmaps
|
||||
}
|
||||
|
||||
/// The newest level whose release is at or below macOS `version` (major, minor, patch), if
|
||||
/// any.
|
||||
pub(crate) fn at_or_below(version: [u32; 3]) -> Option<MetalLevel> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# generateMipmapsForTexture:'s answers, measured on an Apple M3 Max (macOS 26.7, 25G229) and an
|
||||
# Apple M4 (macOS 27.0.1, 26A434) by WP-RT5's probe 4 (DESIGN D305 item 18). Every run was
|
||||
# deterministic: two runs on each Mac gave the same bytes.
|
||||
# Apple M4 (macOS 27.0.1, 26A434) by our own probe. Every run was deterministic: two runs on each
|
||||
# Mac gave the same bytes.
|
||||
#
|
||||
# One block per pixel format:
|
||||
# format <Metal name> <bytes per texel> <field>...
|
||||
@@ -224,8 +224,8 @@ L2 60ff609f 60ff609f
|
||||
vol 4x4x4 7f7f777fb97f0119b188e17fff00ff00b5290167cd7f7fc8e04df6feffffffff975ef0bdff6a9d781c08f60aff00ffffff00ffff00ff0000ffffffffff00ff007f27d1ba012a2501d900fe64ff00fffffffe00c3fef3800084212301ff00ff003e7f40457f1a172f016e86fcff00ffff00ffffffff00ffffffff00ff000000ff09f67f0093a8f37f5bd0ea01ff00ffffbeecbe14ff8c37006aa8e50600ffffff80b9bfff19a7b0014000ff00ffff00ffffff0000ffff00000000000000ffff00ffff0000ffff000000ff0000ff0000000000ffff00ff00ff00ffff0000000000ff0000ff00ffff00ff00000000ffff00ffffffffff00ffffffff00ff000000ff
|
||||
L1 a77d4e69dd3fde7c8a6c9c95a34fafc08bc26d52588f9941b2ab8d8068806060 a77d4e69dd3fde7c8a6c9c95a34fafc08bc26d52588f9941b2ab8d8068806060
|
||||
L2 967e8d76 967e8d76
|
||||
# ARGB8Unorm (WP-TXN, DESIGN D398): RGBA8Unorm's inputs, measured by EVs TXN-mip-m3 (Apple M3 Max,
|
||||
# macOS 26.7) and TXN-mip-m4 (Apple M4, macOS 27.0.1), plain twice and under the validation layer.
|
||||
# ARGB8Unorm: RGBA8Unorm's inputs, measured by EVs TXN-mip-m3 (Apple M3 Max, macOS 26.7) and
|
||||
# TXN-mip-m4 (Apple M4, macOS 27.0.1), plain twice and under the validation layer.
|
||||
format MTLPixelFormatARGB8Unorm 4 unorm8 unorm8 unorm8 unorm8
|
||||
tie 8x8x1 00807f1800808033ff008000ff01810001ff00ff01fefffffe010001fe0200010080803b00807f8fff018100ff00800001feffff01ff00fffe020001fe0101017ffe78fe7fffcdfe807f7b7f8080187f0080008001810080ff00ff00feffff017fff50fe7ffee0fe8080977f807f9e7f0181008000800080feffff01ff00ff00010001ff020001fefe98fe01ffa6fe027fb17ffe80dd7fff8000807f81008080020001fe010101ffffb9fe02fea8fe0180e27fff7fb57ffe810080808000807f00ff0080ffff01810001ff000001feff11fe01004afe0200167ffe24667fff1cffff018100ff00800001feff0101ff00fcfe02009efe0101c57fff9b407ffef5
|
||||
L1 00808045ff01800001fe80fffe0200017ffe9dfe8080727f01800080fe80ff01020001fefea8fe0280c97ffe8000808080ff01800001fe807dfe0200607ffe74 00808045ff01800001fe80fffe0200017ffe9dfe8080727f01800080fe80ff01020001fefea8fe0280c97ffe8000808080ff01800001fe807dfe0200607ffe74
|
||||
|
||||
Loaded 100 of 1298 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user