Validation: the executor runs every case on its own context, without the old runtime
The old runtime goes at the cutover, so validation stops depending on it. What this removes: the engine executor's runtime path (candidate/engine/runtime_run, candidate/runtime_case, runtime_samples, the route between the two) and the code only it used: the runtime's bounded command-buffer waits, the library loader (air_library) and its scratch test, the imageblock helper test, and the runtime's degrade notices on a candidate row (observation's runtime_degrades and announced_degradations, c3's reading of them and its test). Every case now runs on the executor's own Vulkan context. What only the runtime path ran becomes an unsupported requirement in the one vocabulary: - mesh_render_pipeline: an object or mesh case. The executor-contract check raises it from the case's reflected stage, so classification and the checker see it. The requirement qualifies on Metal: the checker still admits the 15 committed object and mesh cases with no candidate (Metal-qualified, Vulkan side unsupported), so their Metal evidence stays. - replayed_template_resources: a replayed pipeline template that binds more than the context replays. The executor raises it as it prepares the case (replay_templates), as it raises depth_outside_unit_range, so no committed case is deleted. Moved into validation, as tooling: the VK_EXT_device_generated_commands entry points the device replay records (candidate/platform/generated_commands.rs; the commands layout is always made for explicit preprocessing, which runs right on every driver), the loader's ignored-driver reports (candidate/platform/ignored_drivers.rs), and makes_layouts_past_support (MoltenVK's driver id). program_instance_made and the profiles layer's runtime settings go. The runtime guard no longer hashes the old runtime's sources (build.rs walks the binder alone), and the product fingerprint no longer walks the old runtime's crate; their tests and the pinned runtime-sources.sha256 follow. The unused m2v_system_alloc cfg goes with the lanes that set it. Versions: RUNTIME_VERSION 2540, ENGINE_EXECUTOR_ABI vulkan-engine-v184, the structural-triage analyzer v83. The census is re-closed on development after the landing. Verified: the compile gate (fmt, clippy plain and under both device cfgs, workspace Rustdoc, validation's suite on lavapipe) runs on this commit; the landing note names its job and codes.
This commit is contained in:
1 parent
4f7a49c36e
commit
d7e8149521
56 files changed
+893
-10734
No files matched your search
@@ -30,7 +30,6 @@ metal2vulkan = { path = "../metal2vulkan", features = ["serde", "ash", "cli"] }
|
||||
# The AIR front end the product pins exactly: the same crate the product
|
||||
# builds, which validation decodes, canonicalizes, and audits AIR through.
|
||||
metal2vulkan-air = { path = "../metal2vulkan-air" }
|
||||
metal2vulkan-runtime = { path = "../metal2vulkan-runtime" }
|
||||
metal2vulkan-rt = { path = "../metal2vulkan-rt" }
|
||||
metal2vulkan-devtools = { path = "../metal2vulkan-devtools" }
|
||||
base64 = "0.22"
|
||||
@@ -55,10 +54,9 @@ ash = { workspace = true, features = ["loaded"] }
|
||||
|
||||
# Device-executing tests are gated on non-default cfgs rather than features, because the ordinary
|
||||
# gate builds with `--all-features`: `--cfg m2v_gpu` (a real GPU) and `--cfg m2v_cpu_icd` (a CPU
|
||||
# Vulkan ICD such as lavapipe). See docs/VALIDATION.md. `--cfg m2v_system_alloc` keeps the system
|
||||
# allocator in the lib test binary for the runtime lanes' cost measurements (worker/alloc.rs).
|
||||
# Vulkan ICD such as lavapipe). See docs/VALIDATION.md.
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(m2v_gpu)", "cfg(m2v_cpu_icd)", "cfg(m2v_gpu_hazards)", "cfg(m2v_system_alloc)"] }
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(m2v_gpu)", "cfg(m2v_cpu_icd)", "cfg(m2v_gpu_hazards)"] }
|
||||
|
||||
[build-dependencies]
|
||||
sha2.workspace = true
|
||||
|
||||
@@ -7,9 +7,8 @@ use build_support::hash_files;
|
||||
use product_fingerprint::{collect_files, product_fingerprint};
|
||||
|
||||
fn main() {
|
||||
// The product fingerprint (`product_fingerprint.rs`): the translator's, the runtime's, and the
|
||||
// dev-tools crate's sources beside this crate in the workspace's crates/, and nothing of this
|
||||
// crate.
|
||||
// The product fingerprint (`product_fingerprint.rs`): the translator's and the dev-tools
|
||||
// crate's sources beside this crate in the workspace's crates/, and nothing of this crate.
|
||||
println!(
|
||||
"cargo:rustc-env=METAL2VULKAN_PRODUCT_FINGERPRINT={}",
|
||||
product_fingerprint(Path::new(".."))
|
||||
@@ -106,17 +105,15 @@ fn main() {
|
||||
// the sRGB steps the ASTC and PVRTC decoders read (`src/lower/arith/srgb.rs`), the sRGB
|
||||
// transfer and half conversions the mipmap filter takes from `air.pack`'s lowering
|
||||
// (`src/lower/arith/pack.rs`), the blend color an
|
||||
// extended-range blend reads (`src/lower/arith/extended_range/blend_color.rs`), half-float
|
||||
// conversion, and the Metal-like runtime (`metal2vulkan-runtime/src`, with the measured answers
|
||||
// it reads), through which the executor runs the families that have moved onto it. The
|
||||
// translator's paths above are below its crate (`metal2vulkan/src/...`). Each path is a product
|
||||
// file below the workspace's crates/ directory, this crate's parent: those listed here, the
|
||||
// binder's Rust sources under `metal2vulkan/src/bind/`, and every file under
|
||||
// `metal2vulkan-runtime/src/`, test modules aside (`runtime_files`, so a file added under
|
||||
// either joins), all sorted as strings. The guard test in `candidate::engine::artifact`
|
||||
// requires this hash to be the one validation pins (`runtime-sources.sha256`), and the inputs
|
||||
// to be closed over the module files their non-test code reaches (each is an input, or listed
|
||||
// there with why a run does not depend on it beyond the artifact digest).
|
||||
// extended-range blend reads (`src/lower/arith/extended_range/blend_color.rs`), and half-float
|
||||
// conversion. The translator's paths above are below its crate (`metal2vulkan/src/...`). Each
|
||||
// path is a product file below the workspace's crates/ directory, this crate's parent: those
|
||||
// listed here and the binder's Rust sources under `metal2vulkan/src/bind/`, test modules aside
|
||||
// (`runtime_files`, so a file added there joins), all sorted as strings. The guard test in
|
||||
// `candidate::engine::artifact` requires this hash to be the one validation pins
|
||||
// (`runtime-sources.sha256`), and the inputs to be closed over the module files their non-test
|
||||
// code reaches (each is an input, or listed there with why a run does not depend on it beyond
|
||||
// the artifact digest).
|
||||
let listed = [
|
||||
"metal2vulkan-air/src/canon/function_table.rs",
|
||||
"metal2vulkan-air/src/canon/rate_map_data.rs",
|
||||
@@ -183,13 +180,6 @@ fn main() {
|
||||
runtime_files(
|
||||
&product,
|
||||
Path::new("metal2vulkan/src/bind"),
|
||||
Walk::Sources,
|
||||
&mut runtime_inputs,
|
||||
);
|
||||
runtime_files(
|
||||
&product,
|
||||
Path::new("metal2vulkan-runtime/src"),
|
||||
Walk::Files,
|
||||
&mut runtime_inputs,
|
||||
);
|
||||
runtime_inputs.sort();
|
||||
@@ -223,21 +213,12 @@ fn crate_files(root: &Path) -> Vec<PathBuf> {
|
||||
files
|
||||
}
|
||||
|
||||
/// What a walked directory gives the runtime's inputs.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Walk {
|
||||
/// Every file: the runtime crate's sources and the measured answers they read.
|
||||
Files,
|
||||
/// The Rust sources alone: the binder (`metal2vulkan/src/bind/`), whose non-test code reads no data file
|
||||
/// (its `.txt` files are its tests' measured answers).
|
||||
Sources,
|
||||
}
|
||||
|
||||
/// Every file below `relative` under `product` that `walk` takes, but test modules (a `tests`
|
||||
/// directory, a `tests.rs` or `*_tests.rs` file) and hidden files, pushed as paths relative to
|
||||
/// `product` with `/` separators. Cargo reruns this script when anything under the directory
|
||||
/// changes, so a file added there joins the runtime's inputs.
|
||||
fn runtime_files(product: &Path, relative: &Path, walk: Walk, output: &mut Vec<String>) {
|
||||
/// Every Rust source below `relative` under `product` but test modules (a `tests` directory, a
|
||||
/// `tests.rs` or `*_tests.rs` file) and hidden files, pushed as paths relative to `product` with
|
||||
/// `/` separators: the binder's (`metal2vulkan/src/bind/`), whose non-test code reads no data file
|
||||
/// (its `.txt` files are its tests' measured answers). Cargo reruns this script when anything
|
||||
/// under the directory changes, so a file added there joins the runtime's inputs.
|
||||
fn runtime_files(product: &Path, relative: &Path, output: &mut Vec<String>) {
|
||||
let directory = product.join(relative);
|
||||
println!("cargo:rerun-if-changed={}", directory.display());
|
||||
let entries = fs::read_dir(&directory)
|
||||
@@ -251,12 +232,9 @@ fn runtime_files(product: &Path, relative: &Path, walk: Walk, output: &mut Vec<S
|
||||
let path = relative.join(&name);
|
||||
if entry.path().is_dir() {
|
||||
if name != "tests" {
|
||||
runtime_files(product, &path, walk, output);
|
||||
runtime_files(product, &path, output);
|
||||
}
|
||||
} else if name != "tests.rs"
|
||||
&& !name.ends_with("_tests.rs")
|
||||
&& (walk == Walk::Files || name.ends_with(".rs"))
|
||||
{
|
||||
} else if name != "tests.rs" && !name.ends_with("_tests.rs") && name.ends_with(".rs") {
|
||||
output.push(path.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,38 +2,25 @@
|
||||
//! translation-census keys, and of the structural-triage analyzer key, which add only versioned
|
||||
//! validation semantics to it. `build.rs` sets `METAL2VULKAN_PRODUCT_FINGERPRINT` from
|
||||
//! [`product_fingerprint`], and the crate's tests take the same function over synthetic
|
||||
//! repositories: one definition, so the build and the tests cannot walk different trees (they did
|
||||
//! when the runtime left the translator for its own crate).
|
||||
//! repositories: one definition, so the build and the tests cannot walk different trees.
|
||||
|
||||
use crate::build_support::{hash_files, product_files, product_hash};
|
||||
use crate::build_support::{hash_files, product_hash};
|
||||
use sha2::Digest;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The product fingerprint of the workspace's crates directory `crates`, as hex: the translator's
|
||||
/// own sources (`metal2vulkan/`, `build_support::product_hash`: exactly the files it can compile or
|
||||
/// read, the AIR front end's crate and the workspace's manifest with them), then the runtime
|
||||
/// crate's (`metal2vulkan-runtime/`: its manifest and the files its module tree compiles or
|
||||
/// reads), then the dev-tools crate's (`metal2vulkan-devtools/`: its manifest and every
|
||||
/// read, the AIR front end's crate and the workspace's manifest with them), then the dev-tools
|
||||
/// crate's (`metal2vulkan-devtools/`: its manifest and every
|
||||
/// file under its `src/`), whose assemblers give the public rows and cases their bitcode, and
|
||||
/// nothing of `metal2vulkan-validation/`.
|
||||
pub fn product_fingerprint(crates: &Path) -> String {
|
||||
let mut hash = product_hash(&crates.join("metal2vulkan"));
|
||||
hash_files(&mut hash, crates, &runtime_crate_files(crates));
|
||||
hash_files(&mut hash, crates, &devtools_files(crates));
|
||||
hex(&hash.finalize())
|
||||
}
|
||||
|
||||
/// The runtime crate's manifest and the files its module tree compiles or reads
|
||||
/// (`build_support::product_files`), sorted.
|
||||
fn runtime_crate_files(crates: &Path) -> Vec<PathBuf> {
|
||||
let runtime = crates.join("metal2vulkan-runtime");
|
||||
let mut files = vec![runtime.join("Cargo.toml")];
|
||||
files.extend(product_files(&runtime));
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// The dev-tools crate's manifest and every file under its `src/`, sorted.
|
||||
fn devtools_files(crates: &Path) -> Vec<PathBuf> {
|
||||
let devtools = crates.join("metal2vulkan-devtools");
|
||||
|
||||
@@ -1 +1 @@
|
||||
ada64eb2f6d77187192b5bca791f98607b1598bc6882c23b1b38f11ab32e1001
|
||||
a5d1cbcfba2baf815b6fab4a7eb44ec2c0468e4a39bee65d8fc86fa02903a58a
|
||||
@@ -1,29 +0,0 @@
|
||||
//! Runtime libraries of the AIR bitcode the validation's cases and lanes hold.
|
||||
//!
|
||||
//! The runtime's `Device::new_library_with_data` takes a metallib alone, as Metal's
|
||||
//! `newLibraryWithData:error:` does. The cases are AIR bitcode, which `llvm-as` assembles from
|
||||
//! their LLVM text: the translator parses it, and the device takes the parsed library
|
||||
//! (`Device::new_library_with_compile_library`).
|
||||
|
||||
use metal2vulkan_runtime::{Device, Error, Library};
|
||||
|
||||
/// A device's library of AIR bitcode.
|
||||
pub trait AirLibrary {
|
||||
/// The library of `bytes`: AIR bitcode, raw or wrapped, as the translator parses it
|
||||
/// (`metal2vulkan::library::Library::parse`, which takes a metallib too). A refusal is the
|
||||
/// translator's, as the runtime reports it (`Error::Unsupported` or `Error::Compile`).
|
||||
fn new_library_with_air(&self, bytes: &[u8]) -> Result<Library, Error>;
|
||||
}
|
||||
|
||||
impl AirLibrary for Device {
|
||||
fn new_library_with_air(&self, bytes: &[u8]) -> Result<Library, Error> {
|
||||
let library =
|
||||
metal2vulkan::library::Library::parse(bytes).map_err(|error| match error {
|
||||
metal2vulkan::error::Error::Unsupported(unsupported) => {
|
||||
Error::Unsupported(unsupported)
|
||||
}
|
||||
other => Error::Compile(other),
|
||||
})?;
|
||||
Ok(self.new_library_with_compile_library(library))
|
||||
}
|
||||
}
|
||||
@@ -418,8 +418,8 @@ fn the_product_fingerprint_covers_the_front_end_crate_by_path() {
|
||||
}
|
||||
|
||||
/// This build's product fingerprint is the walk over this workspace's translator, then the
|
||||
/// runtime's and the dev-tools crates (`product_fingerprint.rs`, which `build.rs` shares), each in
|
||||
/// its directory beside this crate, and the walk leaves out each crate's test-only modules: no file
|
||||
/// dev-tools crate (`product_fingerprint.rs`, which `build.rs` shares), each in its directory
|
||||
/// beside this crate, and the walk leaves out each crate's test-only modules: no file
|
||||
/// it lists is declared only under `#[cfg(test)]`.
|
||||
#[test]
|
||||
fn this_builds_product_fingerprint_is_the_walk_over_the_product() {
|
||||
@@ -437,10 +437,6 @@ fn this_builds_product_fingerprint_is_the_walk_over_the_product() {
|
||||
assert!(product.contains(Path::new("src/indirect_commands/host.rs")));
|
||||
assert!(!product.contains(Path::new("src/pipeline/testing.rs")));
|
||||
assert!(!product.contains(Path::new("src/pipeline/api_tests.rs")));
|
||||
// The runtime's crate by its module tree, its tests left out.
|
||||
let runtime = files(&crates.join("metal2vulkan-runtime"));
|
||||
assert!(runtime.contains(Path::new("src/lib.rs")));
|
||||
assert!(!runtime.iter().any(|file| file.starts_with("src/tests")));
|
||||
// The front end's crate by its module tree, its test-only modules left out, named through the
|
||||
// translator's manifest path (`../metal2vulkan-air`).
|
||||
let inputs = product_inputs(&root);
|
||||
|
||||
@@ -907,23 +907,14 @@ fn near_equivalent_bound(note: PrecisionNote) -> &'static str {
|
||||
}
|
||||
|
||||
/// The deferred near-equivalent `row` ran, if it records one: in its comparison class, which its
|
||||
/// executed modules' precision notes derive, or as a degradation its run announced whose kind is
|
||||
/// the note's ([`CandidateObservation::announced_degradations`], `Degradation::precision_note`). A
|
||||
/// rate-mapped pass the runtime draws records its map only so: the runtime makes the map and
|
||||
/// announces `rasterization-rate-map`, and no executed module's notes name it. An announced kind
|
||||
/// that is no deferred note's (a cost, or another precision note) notes nothing.
|
||||
/// executed modules' precision notes derive.
|
||||
fn deferred_note(row: &CandidateObservation) -> Option<PrecisionNote> {
|
||||
let class = match &row.comparison {
|
||||
ComparisonClass::Unbounded(notes) => Some(notes),
|
||||
_ => None,
|
||||
let ComparisonClass::Unbounded(notes) = &row.comparison else {
|
||||
return None;
|
||||
};
|
||||
let announced = row
|
||||
.announced_degradations()
|
||||
.filter_map(|kind| kind.precision_note())
|
||||
.collect::<BTreeSet<_>>();
|
||||
DEFERRED_NEAR_EQUIVALENTS
|
||||
.into_iter()
|
||||
.find(|note| class.is_some_and(|notes| notes.contains(note)) || announced.contains(note))
|
||||
.find(|note| notes.contains(note))
|
||||
}
|
||||
|
||||
/// Why the product refuses one of `case`'s rasterization-rate maps (the render pass's, or a
|
||||
|
||||
@@ -3577,81 +3577,6 @@ fn a_deferred_near_equivalent_stays_open_with_its_reason() {
|
||||
assert_eq!((row.verdict, row.reason.clone()), (Verdict::Reviewed, None));
|
||||
}
|
||||
|
||||
/// A deferred near-equivalent the run announced as a degradation, which no executed module's notes
|
||||
/// record (the runtime makes a rate-mapped pass's map and announces it), keeps the row open with
|
||||
/// its reason, as a note its comparison class records does, even where the list holds a reading at
|
||||
/// it; a cost, a note C3 judges word by word, or a code the vocabulary does not know leaves an
|
||||
/// ordinary mismatch, which the list reviews.
|
||||
#[test]
|
||||
fn an_announced_deferred_near_equivalent_stays_open_with_its_reason() {
|
||||
use crate::observation::RUNTIME_DEGRADES;
|
||||
use metal2vulkan_runtime::Degradation;
|
||||
let drawn = case(1, "drawn");
|
||||
let row = new_row(&drawn, Backend::Vulkan, LAVAPIPE, &DEVICE, &METAL);
|
||||
assert_eq!(
|
||||
(row.comparison.clone(), row.census.is_none()),
|
||||
(ComparisonClass::Exact, true)
|
||||
);
|
||||
let announcing = |member: &str, codes: &[&str]| {
|
||||
let mut row = row.clone();
|
||||
row.environment[member] = serde_json::json!(codes);
|
||||
row
|
||||
};
|
||||
let judged = |row: CandidateObservation| {
|
||||
let input = C3Input {
|
||||
cases: vec![drawn.clone()],
|
||||
metals: vec![metal(&drawn, &METAL)],
|
||||
public_air: [drawn.air_sha256.clone()].into(),
|
||||
vulkan: vec![row.clone()],
|
||||
..C3Input::default()
|
||||
};
|
||||
let list = ReviewedList {
|
||||
readings: vec![reading(&drawn, vec![reviewed(&row, &METAL)])],
|
||||
old_mismatches: vec![],
|
||||
reference_gaps: vec![],
|
||||
answer_gaps: vec![],
|
||||
};
|
||||
let report = report_of(
|
||||
&input,
|
||||
&list,
|
||||
&C1List::default(),
|
||||
&venues(),
|
||||
&VenueKeys::default(),
|
||||
);
|
||||
slot(&report, LAVAPIPE, Leg::Stated)
|
||||
.rows
|
||||
.iter()
|
||||
.find(|judged| judged.case_id == drawn.case_id)
|
||||
.map(|judged| (judged.verdict, judged.reason.clone()))
|
||||
};
|
||||
let rate_map = Degradation::RasterizationRateMap.code();
|
||||
assert_eq!(rate_map, "metal2vulkan-degrade-rasterization-rate-map");
|
||||
let deferred = Some((
|
||||
Verdict::Mismatch,
|
||||
Some(OpenReason::NearEquivalent(
|
||||
PrecisionNote::RasterizationRateMap,
|
||||
)),
|
||||
));
|
||||
let cost = Degradation::ShadowedTexture.code();
|
||||
assert_eq!(
|
||||
judged(announcing(RUNTIME_DEGRADES, &[cost, rate_map])),
|
||||
deferred
|
||||
);
|
||||
let ordinary = Some((Verdict::Reviewed, None));
|
||||
assert_eq!(judged(row.clone()), ordinary);
|
||||
assert_eq!(
|
||||
judged(announcing(
|
||||
RUNTIME_DEGRADES,
|
||||
&[
|
||||
cost,
|
||||
Degradation::DeviceDenormals.code(),
|
||||
"metal2vulkan-degrade-no-such-kind",
|
||||
],
|
||||
)),
|
||||
ordinary
|
||||
);
|
||||
}
|
||||
|
||||
/// A run restricted to a profile the device cannot take is a current device-class refusal of the
|
||||
/// restricted slot (`not_supported{profile_exceeds_device}`, naming each member), judged by the
|
||||
/// rule a row is; C3 judges the venue's own slots, so it neither reads that slot's refusal as
|
||||
|
||||
@@ -141,7 +141,6 @@ pub fn requested_policy() -> DevicePolicy {
|
||||
/// this whole process (the engine device worker's setting).
|
||||
pub(crate) fn echo_validation_messages() {
|
||||
platform::echo_validation_messages();
|
||||
runtime_case::echo_messages();
|
||||
}
|
||||
|
||||
fn validate_backend_host(backend: Backend) -> Result<(), String> {
|
||||
@@ -159,26 +158,11 @@ fn validate_backend_host(backend: Backend) -> Result<(), String> {
|
||||
|
||||
pub(crate) mod device_facts;
|
||||
pub mod engine;
|
||||
pub mod runtime_case;
|
||||
pub mod runtime_samples;
|
||||
pub(crate) mod unadvertised_stage;
|
||||
pub(crate) mod unsupported_set;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
mod platform;
|
||||
pub(crate) use platform::{runtime_restriction, Restricting, RuntimeRestriction};
|
||||
|
||||
/// What the runtime path's second check of a profile restriction found on its device
|
||||
/// (`RuntimeRestriction::check`): the description the executor's context translates for under the
|
||||
/// profile, the members where the description the runtime read through the profiles layer differs
|
||||
/// from it (the kept ones, which the layer reads from the device), and the environment's
|
||||
/// `profiles_layer` record.
|
||||
pub(crate) struct RestrictedDevice {
|
||||
pub(crate) translated: metal2vulkan::device::DeviceDescription,
|
||||
pub(crate) kept: Vec<String>,
|
||||
pub(crate) record: serde_json::Value,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
|
||||
@@ -289,47 +273,4 @@ mod platform {
|
||||
) -> Result<crate::worker::compile::WorkerDevice, ExecutorError> {
|
||||
Err("candidate execution is supported only on Linux and macOS".into())
|
||||
}
|
||||
|
||||
/// No restriction runs here ([`restrict_devices_to`] refuses one).
|
||||
pub(crate) enum Restricting {
|
||||
Takes(Box<RuntimeRestriction>),
|
||||
Refused(Box<crate::candidate::engine::RunAttempt>),
|
||||
}
|
||||
|
||||
/// No value: no restriction runs here.
|
||||
pub(crate) enum RuntimeRestriction {}
|
||||
|
||||
impl RuntimeRestriction {
|
||||
pub(crate) fn stem(&self) -> &str {
|
||||
match *self {}
|
||||
}
|
||||
|
||||
pub(crate) fn restrict(
|
||||
&self,
|
||||
_options: &mut metal2vulkan_runtime::DeviceOptions,
|
||||
) -> Result<(), String> {
|
||||
match *self {}
|
||||
}
|
||||
|
||||
pub(crate) fn check(
|
||||
&self,
|
||||
_device: &metal2vulkan_runtime::Device,
|
||||
) -> Result<super::RestrictedDevice, String> {
|
||||
match *self {}
|
||||
}
|
||||
|
||||
pub(crate) fn refused_on(
|
||||
&self,
|
||||
_executor: &str,
|
||||
) -> Result<crate::worker::device::OpenedDevice, String> {
|
||||
match *self {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_restriction(
|
||||
_device_type: DeviceType,
|
||||
_executor: &str,
|
||||
) -> Result<Option<Restricting>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! What an engine row records of the Vulkan device that ran it: the device's identity and driver
|
||||
//! (`VkPhysicalDeviceProperties`, `VkPhysicalDeviceDriverProperties`), the tools active on it, and
|
||||
//! the facts the row's environment has always carried beside them. The executor's own context reads
|
||||
//! its tools here, and the runtime path reads all of it through the runtime device's raw handles.
|
||||
//! its tools here.
|
||||
|
||||
use crate::coverage::ExecutionClass;
|
||||
use ash::vk;
|
||||
|
||||
@@ -73,7 +73,7 @@ use crate::observation::{
|
||||
};
|
||||
use crate::observation_contract::ComparisonClass;
|
||||
use crate::refusal::{Refusal, RefusalObservation};
|
||||
use crate::requirement::Executor;
|
||||
use crate::requirement::{Executor, ToolingRequirement};
|
||||
use crate::store::CorpusStore;
|
||||
use crate::worker::compile::{
|
||||
compile_compute_request, compile_render_request, CompileWorker, NotCompiled, WorkerDevice,
|
||||
@@ -109,7 +109,6 @@ pub mod mesh;
|
||||
#[cfg(test)]
|
||||
mod public_cases;
|
||||
pub mod resources;
|
||||
pub mod runtime_run;
|
||||
pub mod tables;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
@@ -124,7 +123,7 @@ use tables::{function_tables, table_buffers, FunctionTable, TableBuffers};
|
||||
/// how it decides a match. A change no recorded row can observe (a case kind no earlier executor
|
||||
/// ran, or one it refused) needs no bump; its commit says why. The commit that bumps it says what
|
||||
/// changed; this comment keeps no history.
|
||||
pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v183";
|
||||
pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v184";
|
||||
|
||||
/// One kernel case in the terms the binder takes: what this executor supports of an
|
||||
/// [`AuthoredCase`] (buffers, device buffer arrays, argument-buffer buffers and textures, command
|
||||
@@ -144,8 +143,7 @@ pub struct ComputeCase {
|
||||
pub buffers: BTreeMap<u32, Vec<u8>>,
|
||||
/// Each bound buffer holding a rasterization-rate map's parameter data, by Metal buffer index:
|
||||
/// its bytes in [`ComputeCase::buffers`] are the product's data of the map, which the executor
|
||||
/// binds; the runtime path makes the map with the runtime and copies its data into the buffer,
|
||||
/// as the Metal oracle does with Metal's.
|
||||
/// binds.
|
||||
pub rate_maps: BTreeMap<u32, RateMapLiteral>,
|
||||
/// Initial bytes of each argument-buffer buffer, by `(owner Metal index, field offset)`:
|
||||
/// a buffer the owner's argument buffer points to (loaded pointers). The run writes its guest
|
||||
@@ -879,8 +877,7 @@ pub fn function_constants(
|
||||
/// slot ([`views_told_apart`]), so a uniform view's range starts at its bind offset in its plan
|
||||
/// (`SpecKey::RangeAtBindOffset`) on every device, as in the runtime's plan of the same binds: the
|
||||
/// runtime states its device's own alignment at the slots its pipeline reads through a uniform
|
||||
/// view, and the plans of the two are the same, so the runtime path's artifact digest is the
|
||||
/// executor's and the authored compile census's.
|
||||
/// view, and the plans of the two are the same.
|
||||
pub const VIEW_BASE_ALIGNMENT: u32 = 256;
|
||||
|
||||
/// `state` telling [`VIEW_BASE_ALIGNMENT`] apart at every buffer slot of each of its stages, and
|
||||
@@ -1223,9 +1220,8 @@ pub fn is_robustness_off_slot(environment_id: &str) -> bool {
|
||||
/// form and `profile`'s encodings) on a device that executes as `class`, or `None` for a case
|
||||
/// without targets: the run's out-of-bounds facts, before what its guards count
|
||||
/// (`TargetRun::escaped`, `TargetRun::past_end`). A target whose form the device leaves
|
||||
/// uncontained under that encoding refuses the run, so it is decided before anything is submitted:
|
||||
/// by the executor's own context before it executes, and by the runtime path before it commits
|
||||
/// (`runtime_run`).
|
||||
/// uncontained under that encoding refuses the run, so it is decided before anything is submitted,
|
||||
/// before the executor's context executes.
|
||||
pub(crate) fn out_of_bounds_run(
|
||||
class: Option<ExecutionClass>,
|
||||
profile: &DeviceProfile,
|
||||
@@ -1261,8 +1257,7 @@ pub(crate) fn out_of_bounds_run(
|
||||
|
||||
/// [`out_of_bounds_run`] for a render case's draw: how `pipeline`'s module that runs the Metal
|
||||
/// vertex function (`graphics::vertex_module`) contains each of `case`'s targets, its attributes
|
||||
/// fetched from `case`'s vertex buffers. The one decision the executor's own context and the
|
||||
/// runtime path (`runtime_run`) take for a draw.
|
||||
/// fetched from `case`'s vertex buffers.
|
||||
pub(crate) fn draw_out_of_bounds_run(
|
||||
class: Option<ExecutionClass>,
|
||||
profile: &DeviceProfile,
|
||||
@@ -1291,9 +1286,8 @@ pub(crate) fn draw_out_of_bounds_run(
|
||||
|
||||
/// Whether a draw that read `padding` index positions past where Metal's fetch stops reading its
|
||||
/// index buffer from a zero-padded copy of its indices contains them as `run`'s index buffer
|
||||
/// target states: the padded copy, of at least one such position. The executor's context and the
|
||||
/// runtime path (the draw's execution record) both hold the draw to it; a run without that target
|
||||
/// agrees with any draw.
|
||||
/// target states: the padded copy, of at least one such position. The executor's context holds
|
||||
/// the draw to it; a run without that target agrees with any draw.
|
||||
pub(crate) fn index_padding_agrees(
|
||||
run: Option<&OutOfBoundsRun>,
|
||||
padding: Option<u64>,
|
||||
@@ -2008,17 +2002,8 @@ pub struct PreparedCase {
|
||||
/// The libraries the case's own function links ([`linked_modules`]).
|
||||
linked: Vec<LinkedModule>,
|
||||
/// The template of each pipeline token the case's executed commands may run, as the
|
||||
/// executor's own context replays them ([`replay_templates`]), or why that context cannot: its
|
||||
/// refusal of the case, which the runtime's replay does not share.
|
||||
templates: Result<BTreeMap<u64, ReplayTemplate>, ExecutorError>,
|
||||
}
|
||||
|
||||
impl PreparedCase {
|
||||
/// The templates the executor's own context replays, or its refusal of the case: a case the
|
||||
/// runtime hands back to that context fails there.
|
||||
fn templates(&self) -> Result<&BTreeMap<u64, ReplayTemplate>, ExecutorError> {
|
||||
self.templates.as_ref().map_err(Clone::clone)
|
||||
}
|
||||
/// executor's context replays them ([`replay_templates`]).
|
||||
templates: BTreeMap<u64, ReplayTemplate>,
|
||||
}
|
||||
|
||||
/// A pipeline template an executed command may run: its checked case (by id in
|
||||
@@ -2072,10 +2057,10 @@ pub enum TemplateCase {
|
||||
/// family, so such a literal is no template here. A replayed compute template binds buffers and
|
||||
/// threadgroup memory only, and runs no stage input; a replayed render template is a
|
||||
/// rasterization-disabled vertex function (which the checker requires) that binds buffers only,
|
||||
/// with no vertex input. Every other resource of its own, and an object or mesh template, whose
|
||||
/// mesh draws only the runtime replays (`runtime_run::template_states`), is the refusal of the
|
||||
/// executor's context, before any device: of the case itself where it runs there, and kept for a
|
||||
/// run the runtime hands back where the runtime runs it (`PreparedCase::templates`).
|
||||
/// with no vertex input. A template with any other resource of its own refuses the case, before
|
||||
/// any device ([`ToolingRequirement::ReplayedTemplateResources`]), and so does an object or mesh
|
||||
/// template, whose mesh draw the executor does not draw
|
||||
/// ([`ToolingRequirement::MeshRenderPipeline`]).
|
||||
pub fn replay_templates(
|
||||
checked: &CheckedCase,
|
||||
) -> Result<BTreeMap<u64, ReplayTemplate>, ExecutorError> {
|
||||
@@ -2123,10 +2108,9 @@ pub fn replay_templates(
|
||||
&& mapped.imageblock.is_none()
|
||||
&& mapped.stage_input.is_none();
|
||||
if !replayable {
|
||||
return Err(NotSupported::NotImplemented(format!(
|
||||
"engine candidate: the replayed template {case_id} binds more than \
|
||||
buffers and threadgroup memory"
|
||||
))
|
||||
return Err(NotSupported::Requirements(
|
||||
[ToolingRequirement::ReplayedTemplateResources].into(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
TemplateCase::Compute(Box::new(mapped))
|
||||
@@ -2159,19 +2143,17 @@ pub fn replay_templates(
|
||||
&& resources.objects.is_empty()
|
||||
&& resources.command_buffers.is_empty();
|
||||
if !replayable {
|
||||
return Err(NotSupported::NotImplemented(format!(
|
||||
"engine candidate: the replayed template {case_id} is not a \
|
||||
rasterization-disabled vertex function that binds buffers only"
|
||||
))
|
||||
return Err(NotSupported::Requirements(
|
||||
[ToolingRequirement::ReplayedTemplateResources].into(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
TemplateCase::Render(Box::new(mapped))
|
||||
}
|
||||
Stage::Object | Stage::Mesh => {
|
||||
return Err(NotSupported::NotImplemented(format!(
|
||||
"engine candidate: the replayed template {case_id} is an object or mesh \
|
||||
function, whose mesh draws only the runtime replays"
|
||||
))
|
||||
return Err(NotSupported::Requirements(
|
||||
[ToolingRequirement::MeshRenderPipeline].into(),
|
||||
)
|
||||
.into())
|
||||
}
|
||||
};
|
||||
@@ -2418,23 +2400,14 @@ pub fn prepare_case(
|
||||
)?)),
|
||||
};
|
||||
let linked = linked_modules(&checked.primary.linked_functions)?;
|
||||
let templates = replay_templates(&checked);
|
||||
let prepared = PreparedCase {
|
||||
let templates = replay_templates(&checked)?;
|
||||
Ok(PreparedCase {
|
||||
device,
|
||||
checked,
|
||||
mapped,
|
||||
linked,
|
||||
templates,
|
||||
};
|
||||
// The runtime replays every template through its own pipeline states, so a template the
|
||||
// executor's context cannot replay refuses device-free only a case that runs on that context; a
|
||||
// case the runtime runs meets the refusal only if the runtime hands it back.
|
||||
if let (Err(refused), runtime_run::Route::Executor(_)) =
|
||||
(&prepared.templates, runtime_run::route(&prepared))
|
||||
{
|
||||
return Err(refused.clone());
|
||||
}
|
||||
Ok(prepared)
|
||||
})
|
||||
}
|
||||
|
||||
/// What one compile of [`case_compiles`] builds.
|
||||
@@ -2556,10 +2529,8 @@ pub struct CaseCompiles<'a> {
|
||||
/// device-free compile builds on this device: a render command buffer, whose host replay
|
||||
/// compiles each command's pipeline for the bind shape of the records the producer writes on
|
||||
/// the device, and whose draw replay (`platform::compute::draw_replay`) compiles its
|
||||
/// template's variant for the bind state of the execution's encoder, as the runtime path's
|
||||
/// record leaves both uncovered; and a compute one the host replay runs, where the product sets
|
||||
/// no device replay up or the case registers no variant (a case the runtime runs whose
|
||||
/// templates the executor's context does not replay registers none).
|
||||
/// template's variant for the bind state of the execution's encoder; and a compute one the host
|
||||
/// replay runs, where the product sets no device replay up or the case registers no variant.
|
||||
pub host_replayed: usize,
|
||||
}
|
||||
|
||||
@@ -2592,14 +2563,7 @@ pub fn case_compiles<'a>(
|
||||
let mut host_replayed = 0;
|
||||
match &prepared.mapped {
|
||||
Mapped::Compute(compute) => {
|
||||
// A case the runtime runs replays its templates through the runtime's own pipeline
|
||||
// states (`prepare_case`), so the executor's context's refusal of them is not that
|
||||
// run's: it registers no variant here, and each executed command buffer is uncovered.
|
||||
let registered = match prepared.templates() {
|
||||
Ok(templates) => replay_variants(compute, templates)?,
|
||||
Err(_) if runtime_run::route(prepared) == runtime_run::Route::Runtime => Vec::new(),
|
||||
Err(refused) => return Err(refused),
|
||||
};
|
||||
let registered = replay_variants(compute, &prepared.templates)?;
|
||||
let shape = compute_shape(compute, addressed, ranges).map_err(ExecutorError::Failed)?;
|
||||
let (request, libraries) = compute_request(&library, linked, compute, &shape);
|
||||
compiles.push(CaseCompile {
|
||||
@@ -2698,8 +2662,6 @@ pub fn case_compiles<'a>(
|
||||
.filter(|(_, command)| executed(command))
|
||||
.count();
|
||||
}
|
||||
// The pipeline the runtime compiles in the run itself (`runtime_run`), for its own
|
||||
// stage's resources.
|
||||
Mapped::Mesh(mesh) => {
|
||||
let shape = mesh::mesh_shape(mesh, addressed, ranges)?;
|
||||
let companion = mesh
|
||||
@@ -2757,7 +2719,7 @@ pub(crate) fn run_on_device(input: &DeviceInput) -> DeviceOutcome {
|
||||
match prepare_on_device(input) {
|
||||
Ok((prepared, worker)) => {
|
||||
let clock = crate::budgets::CreationClock::start();
|
||||
let attempt = run_prepared(&prepared, input.backend, &worker);
|
||||
let attempt = run_on_context(&prepared, input.backend, &worker);
|
||||
let timing = CaseTiming::of_one(clock.read());
|
||||
DeviceOutcome {
|
||||
result: attempt.result.map(|run| DeviceRun {
|
||||
@@ -2838,54 +2800,12 @@ fn prepare_on_device(input: &DeviceInput) -> Result<(PreparedCase, CompileWorker
|
||||
Ok((prepared, CompileWorker::current()?))
|
||||
}
|
||||
|
||||
/// Run one prepared case on its device by the path [`runtime_run::route`] gives it: through the
|
||||
/// runtime ([`runtime_run::run`]), or on the executor's own context ([`run_on_context`]) while the
|
||||
/// runtime path waits for prerequisites of the case's family, or when the runtime raised a typed
|
||||
/// gap before it committed (the bridge). A row or refusal of the executor's context records why the
|
||||
/// runtime did not run it.
|
||||
fn run_prepared(prepared: &PreparedCase, backend: Backend, worker: &CompileWorker) -> RunAttempt {
|
||||
let why = match runtime_run::route(prepared) {
|
||||
runtime_run::Route::Runtime => match runtime_run::run(prepared, backend) {
|
||||
runtime_run::RuntimeOutcome::Ran(attempt) => return *attempt,
|
||||
runtime_run::RuntimeOutcome::Gap(gap) => runtime_run::ExecutorRun::Gap(gap),
|
||||
},
|
||||
runtime_run::Route::Executor(prerequisites) => {
|
||||
runtime_run::ExecutorRun::WaitsFor(prerequisites)
|
||||
}
|
||||
};
|
||||
let mut attempt = run_on_context(prepared, backend, worker);
|
||||
let environments = attempt
|
||||
.result
|
||||
.as_mut()
|
||||
.ok()
|
||||
.map(|run| &mut run.environment)
|
||||
.into_iter()
|
||||
.chain(
|
||||
attempt
|
||||
.refused_on
|
||||
.as_mut()
|
||||
.map(|opened| &mut opened.environment),
|
||||
);
|
||||
for environment in environments {
|
||||
if let Some(object) = environment.as_object_mut() {
|
||||
for (key, value) in runtime_run::executor_members(&why) {
|
||||
object.insert(key.into(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
attempt
|
||||
}
|
||||
|
||||
/// Compile (in `worker`), bind, and execute one prepared case on the executor's own context: a
|
||||
/// Compile (in `worker`), bind, and execute one prepared case on the executor's context: a
|
||||
/// kernel case as one dispatch, a vertex or fragment case as one draw. The run's row or refusal
|
||||
/// records what it compiled, by content ([`artifact::CaseArtifact`]).
|
||||
fn run_on_context(prepared: &PreparedCase, backend: Backend, worker: &CompileWorker) -> RunAttempt {
|
||||
let case = &prepared.checked.primary.case;
|
||||
// A template this context cannot replay refuses the case here, before any device work.
|
||||
let templates = match prepared.templates() {
|
||||
Ok(templates) => templates,
|
||||
Err(refused) => return RunAttempt::of(Err(refused)),
|
||||
};
|
||||
let templates = &prepared.templates;
|
||||
// The worker assembles a row that retains no bitcode (a public fixture), and a companion.
|
||||
let library = RowSource::of_row(&prepared.checked.primary.source);
|
||||
let linked = &prepared.linked;
|
||||
@@ -2958,10 +2878,9 @@ fn run_on_context(prepared: &PreparedCase, backend: Backend, worker: &CompileWor
|
||||
backend,
|
||||
)
|
||||
}
|
||||
// Only the runtime path draws a mesh render pipeline; the executor's context runs a
|
||||
// mesh case only when the runtime handed it back (the bridge).
|
||||
Mapped::Mesh(_) => RunAttempt::of(Err(NotSupported::NotImplemented(
|
||||
"engine candidate: the executor's own context draws no mesh render pipeline".into(),
|
||||
// The checker's requirements refuse a mesh case before it maps (`prepare_case`).
|
||||
Mapped::Mesh(_) => RunAttempt::of(Err(NotSupported::Requirements(
|
||||
[ToolingRequirement::MeshRenderPipeline].into(),
|
||||
)
|
||||
.into())),
|
||||
};
|
||||
@@ -2978,8 +2897,7 @@ fn run_on_context(prepared: &PreparedCase, backend: Backend, worker: &CompileWor
|
||||
/// Record a compiled child in the run's artifact: a device-replay variant by its subject, with the
|
||||
/// preprocess module the device replay runs it under; a host replay's pipeline (for a record a
|
||||
/// producer wrote on the device) and a draw replay's variant (for the bind state of the execution's
|
||||
/// encoder) as ones the census cannot compile, as the runtime path records every pipeline its
|
||||
/// executed commands ran.
|
||||
/// encoder) as ones the census cannot compile.
|
||||
fn record_child(
|
||||
artifact: &mut artifact::CaseArtifact,
|
||||
target: &WorkerDevice,
|
||||
@@ -3018,7 +2936,7 @@ fn compile_child(
|
||||
target: &WorkerDevice,
|
||||
(token, shape, command): (u64, &BindShape, &ChildCommand),
|
||||
) -> Result<CompiledChild, ExecutorError> {
|
||||
let template = prepared.templates()?.get(&token).ok_or_else(|| {
|
||||
let template = prepared.templates.get(&token).ok_or_else(|| {
|
||||
ExecutorError::Failed(format!(
|
||||
"an executed command's pipeline token {token} names no template"
|
||||
))
|
||||
@@ -3108,7 +3026,7 @@ fn replay_variant_request<'a>(
|
||||
threads_per_group: [u32; 3],
|
||||
shape: &BindShape,
|
||||
) -> Result<VariantRequest<'a>, ExecutorError> {
|
||||
let template = prepared.templates()?.get(&token).ok_or_else(|| {
|
||||
let template = prepared.templates.get(&token).ok_or_else(|| {
|
||||
ExecutorError::Failed(format!(
|
||||
"an executed command's pipeline token {token} names no template"
|
||||
))
|
||||
|
||||
@@ -201,10 +201,9 @@ fn the_runtime_sources_are_the_committed_ones() {
|
||||
("metal2vulkan/src/spirv/verify/mod.rs", spirv),
|
||||
("metal2vulkan/src/spv.rs", "the SPIR-V grammar's opcodes and enumerants with their values, generated from Khronos's grammar: a value is fixed by the specification, and regenerating only adds or drops names, which no run can observe"),
|
||||
]);
|
||||
// The resolver the classifier's key test holds its inputs closed with, across the product,
|
||||
// the AIR front end's crate, which the product imports as `crate::air`, and the runtime's
|
||||
// crate, whose inputs reach the product through `metal2vulkan::`, each by its directory in the
|
||||
// workspace's crates/.
|
||||
// The resolver the classifier's key test holds its inputs closed with, across the product and
|
||||
// the AIR front end's crate, which the product imports as `crate::air`, each by its directory
|
||||
// in the workspace's crates/.
|
||||
let members = [
|
||||
crate::triage::classifier_inputs::Member {
|
||||
name: "metal2vulkan_air",
|
||||
@@ -214,10 +213,6 @@ fn the_runtime_sources_are_the_committed_ones() {
|
||||
name: "metal2vulkan",
|
||||
dir: "metal2vulkan",
|
||||
},
|
||||
crate::triage::classifier_inputs::Member {
|
||||
name: "metal2vulkan_runtime",
|
||||
dir: "metal2vulkan-runtime",
|
||||
},
|
||||
];
|
||||
let dependencies =
|
||||
crate::triage::classifier_inputs::dependencies(&product, &members, &inputs).unwrap();
|
||||
@@ -231,10 +226,12 @@ fn the_runtime_sources_are_the_committed_ones() {
|
||||
unlisted.is_empty(),
|
||||
"the runtime inputs reach files that are neither inputs nor listed: {unlisted:#?}"
|
||||
);
|
||||
for file in not_runtime.keys() {
|
||||
assert!(
|
||||
dependencies.contains_key(*file),
|
||||
"{file} is listed but no runtime input reaches it"
|
||||
);
|
||||
}
|
||||
let unreached = not_runtime
|
||||
.keys()
|
||||
.filter(|file| !dependencies.contains_key(**file))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
unreached.is_empty(),
|
||||
"listed, but no runtime input reaches them: {unreached:#?}"
|
||||
);
|
||||
}
|
||||
@@ -2753,98 +2753,6 @@ fn a_render_case_of_one_sample_draws_as_it_always_did() {
|
||||
assert!(text.contains("\"raster_sample_count\":4"), "{text}");
|
||||
}
|
||||
|
||||
/// The runtime path's generated initializer and resolver of each committed public fragment
|
||||
/// imageblock case (`runtime_case::imageblock::helpers_text`, from the checked reflection's master
|
||||
/// and the case's cells), each drawn as the oracle draws its own helpers (the case's vertex
|
||||
/// function, no vertex buffer, the case's attachments, three vertices), compile on lavapipe and
|
||||
/// moltenvk-m3 to the case pipeline's fragment imageblock: its master's fingerprint, its data size
|
||||
/// and its alignment. So the runtime draws them in one pass with the case, and their imageblock
|
||||
/// sample lengths are the case pipeline's, as the oracle requires of its helpers.
|
||||
#[test]
|
||||
fn the_imageblock_helpers_view_each_public_cases_master() {
|
||||
use crate::candidate::runtime_case::imageblock::{
|
||||
helpers_text, INITIALIZE_ENTRY, RESOLVE_ENTRY,
|
||||
};
|
||||
let root = metal2vulkan_devtools::validation_dir().join("corpus");
|
||||
let sources = public_sources().unwrap();
|
||||
let mut compared = 0;
|
||||
for case in CorpusStore::new(&root).read_all_cases().unwrap() {
|
||||
if case.fragment_imageblock.is_none() {
|
||||
continue;
|
||||
}
|
||||
let Some(row) = sources
|
||||
.iter()
|
||||
.find(|row| row.air_sha256 == case.air_sha256 && row.entry == case.entry)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let scratch = crate::ScratchDir::new("public-imageblock-helpers").unwrap();
|
||||
let ll = scratch.path().join("case.ll");
|
||||
std::fs::write(&ll, &row.air_ll).unwrap();
|
||||
let Some(bitcode) = assembled(&ll) else {
|
||||
return;
|
||||
};
|
||||
let name = &case.name;
|
||||
let checked = crate::check::check_case_against_source(&root, case.clone(), row)
|
||||
.unwrap_or_else(|errors| panic!("{name}: {errors:?}"));
|
||||
let master = checked.primary.reflection.fragment_imageblock.as_ref();
|
||||
let render = render_case(
|
||||
&case,
|
||||
&checked.primary.interface,
|
||||
&row.air_ll,
|
||||
checked.primary.companion.as_ref(),
|
||||
master,
|
||||
)
|
||||
.unwrap_or_else(|error| panic!("{name}: {error:?}"));
|
||||
let cells = render.imageblock.as_ref().expect("the case's cells");
|
||||
let text = helpers_text(master.expect("the reflected master"), cells)
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let helpers = crate::check::loop_free::assemble(&text)
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}\n{text}"));
|
||||
let companion = render.companion.as_ref().unwrap().opaque_bitcode().unwrap();
|
||||
let imageblock = |pipeline: &metal2vulkan::pipeline::RenderPipeline| {
|
||||
pipeline
|
||||
.graphics
|
||||
.fragment_imageblock
|
||||
.map(|state| (state.master, state.data_size, state.alignment))
|
||||
};
|
||||
for stem in ["lavapipe", "moltenvk-m3"] {
|
||||
let device = device(stem);
|
||||
let libraries = RenderLibraries {
|
||||
vertex: &companion,
|
||||
fragment: Some(&bitcode),
|
||||
};
|
||||
let shape = render_shape(&render, true, BufferRanges::default()).unwrap();
|
||||
let own = compile_in_process(&device, &render, libraries, &shape)
|
||||
.unwrap_or_else(|error| panic!("{name} on {stem}: {error}"));
|
||||
let expected = imageblock(&own);
|
||||
assert!(expected.is_some(), "{name} on {stem}: no imageblock state");
|
||||
for entry in [INITIALIZE_ENTRY, RESOLVE_ENTRY] {
|
||||
let mut helper = two_stage_case(
|
||||
&render.vertex.entry,
|
||||
entry,
|
||||
Vec::new(),
|
||||
render.color_targets.clone(),
|
||||
3,
|
||||
);
|
||||
helper.depth_stencil = render.depth_stencil.clone();
|
||||
let libraries = RenderLibraries {
|
||||
vertex: &companion,
|
||||
fragment: Some(&helpers),
|
||||
};
|
||||
let shape = render_shape(&helper, true, BufferRanges::default()).unwrap();
|
||||
let pipeline = compile_in_process(&device, &helper, libraries, &shape)
|
||||
.unwrap_or_else(|error| panic!("{name} {entry} on {stem}: {error}"));
|
||||
assert_eq!(imageblock(&pipeline), expected, "{name} {entry} on {stem}");
|
||||
}
|
||||
compared += 1;
|
||||
}
|
||||
}
|
||||
// As `public_fragment_imageblock_cases_plan_their_storage_image` plans them: twenty cases,
|
||||
// each on both profiles.
|
||||
assert_eq!(compared, 40);
|
||||
}
|
||||
|
||||
/// A vertex buffer of a dynamic layout: its layout's stride is `MTLBufferLayoutStrideDynamic`, so
|
||||
/// the fetch reads the stride the buffer is bound with; a fixed layout's is its stride.
|
||||
#[test]
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! The guards a candidate keeps around a case's out-of-bounds targets: where each guarded target
|
||||
//! ([`out_of_bounds::guarded`]) lies, how far its guard reaches, what a run changed there, and how
|
||||
//! those counts join the run's out-of-bounds facts. One copy, which the executor's own context
|
||||
//! (`platform`, each target in an allocation of its own) and the runtime path (`runtime_case`, each
|
||||
//! target in a heap of its own) share.
|
||||
//! those counts join the run's out-of-bounds facts, for the executor's own context (`platform`,
|
||||
//! each target in an allocation of its own).
|
||||
|
||||
use super::ComputeCase;
|
||||
use crate::case::out_of_bounds::{ContainmentForm, OutOfBoundsResource, OutOfBoundsTarget};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Mesh cases of the engine candidate: an object or mesh case's draw (`case::MeshDraw`) mapped for
|
||||
//! the runtime's mesh path (`runtime_case::encoded_mesh`), as the Metal oracle draws it
|
||||
//! (`metal::platform`).
|
||||
//! Mesh cases of the engine candidate: an object or mesh case's draw (`case::MeshDraw`) mapped as
|
||||
//! the Metal oracle draws it (`metal::platform`).
|
||||
//!
|
||||
//! The case's own function binds the case's resources, mapped as a render case's own stage's are
|
||||
//! ([`graphics::stage_resources`]); each partner its draw names is a function of the case's own
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1954,16 +1954,11 @@ fn checked_render_replay_cases_prepare_their_render_template() {
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(
|
||||
prepared
|
||||
.templates()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.copied()
|
||||
.collect::<Vec<_>>(),
|
||||
prepared.templates.keys().copied().collect::<Vec<_>>(),
|
||||
[1],
|
||||
"{name}"
|
||||
);
|
||||
let TemplateCase::Render(template) = &prepared.templates().unwrap()[&1].mapped else {
|
||||
let TemplateCase::Render(template) = &prepared.templates[&1].mapped else {
|
||||
panic!("{name}: the parent pipeline is a render template");
|
||||
};
|
||||
assert!(template.fragment.is_none(), "{name}");
|
||||
@@ -2039,7 +2034,7 @@ fn committed_compute_replay_cases_register_their_templates_variant() {
|
||||
panic!("a kernel case");
|
||||
};
|
||||
assert_eq!(
|
||||
replay_variants(compute, prepared_gpu.templates().unwrap()).unwrap(),
|
||||
replay_variants(compute, &prepared_gpu.templates).unwrap(),
|
||||
edges(1)
|
||||
);
|
||||
let name = "gpu-encoded-buffers-keep-the-host-encoded-dispatches";
|
||||
@@ -2048,7 +2043,7 @@ fn committed_compute_replay_cases_register_their_templates_variant() {
|
||||
panic!("{name}: a kernel case");
|
||||
};
|
||||
assert_eq!(
|
||||
replay_variants(compute, host.templates().unwrap()).unwrap(),
|
||||
replay_variants(compute, &host.templates).unwrap(),
|
||||
[variant(2, [8, 1, 1])],
|
||||
"{name}"
|
||||
);
|
||||
@@ -2075,7 +2070,7 @@ fn committed_compute_replay_cases_register_their_templates_variant() {
|
||||
expected.extend(edges(2));
|
||||
expected.sort_by_key(|v| v.threads_per_threadgroup);
|
||||
assert_eq!(
|
||||
replay_variants(&compute, prepared.templates.as_ref().unwrap()).unwrap(),
|
||||
replay_variants(&compute, &prepared.templates).unwrap(),
|
||||
expected,
|
||||
"a command whose action the producer encodes registers the template's edges"
|
||||
);
|
||||
@@ -2101,17 +2096,16 @@ fn committed_compute_replay_cases_register_their_templates_variant() {
|
||||
];
|
||||
expected.sort_by_key(|v| v.threads_per_threadgroup);
|
||||
assert_eq!(
|
||||
replay_variants(&compute, prepared.templates.as_ref().unwrap()).unwrap(),
|
||||
replay_variants(&compute, &prepared.templates).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
/// A template the executor's own context cannot replay refuses a case only on that context. The
|
||||
/// committed kernel case whose patch draws run a post-tessellation template prepares, routes to the
|
||||
/// runtime, which replays every template through its own pipeline states, and keeps the context's
|
||||
/// refusal for a run the runtime hands back.
|
||||
/// A template the executor's context cannot replay refuses its case as it is prepared, by the
|
||||
/// requirement the vocabulary names: the committed kernel case whose patch draws run a
|
||||
/// post-tessellation template.
|
||||
#[test]
|
||||
fn a_template_only_the_runtime_replays_refuses_only_on_the_executors_context() {
|
||||
fn a_template_the_context_cannot_replay_refuses_its_case_by_its_requirement() {
|
||||
let root = metal2vulkan_devtools::validation_dir().join("corpus");
|
||||
let name = "patch-draws-a-kernel-encodes-at-factor-scales-and-the-host-encodes";
|
||||
let case = CorpusStore::new(&root)
|
||||
@@ -2123,12 +2117,12 @@ fn a_template_only_the_runtime_replays_refuses_only_on_the_executors_context() {
|
||||
let device = DeviceType::Cpu;
|
||||
let admitted = admit(&root, case, ExecutionRequest::EngineCandidate { device })
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let prepared = prepare_case(device, admitted).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
assert_eq!(runtime_run::route(&prepared), runtime_run::Route::Runtime);
|
||||
let refused = prepared.templates().err().expect("the context's refusal");
|
||||
let refused = prepare_case(device, admitted)
|
||||
.err()
|
||||
.expect("the context's refusal");
|
||||
assert!(
|
||||
matches!(&refused, ExecutorError::NotSupported(NotSupported::NotImplemented(why))
|
||||
if why.contains("is not a rasterization-disabled vertex function")),
|
||||
matches!(&refused, ExecutorError::NotSupported(NotSupported::Requirements(requirements))
|
||||
if requirements.contains(&ToolingRequirement::ReplayedTemplateResources)),
|
||||
"{refused}"
|
||||
);
|
||||
}
|
||||
@@ -2210,7 +2204,7 @@ fn k14d_replay_cases_register_their_regions_variants() {
|
||||
let Mapped::Compute(compute) = &prepared.mapped else {
|
||||
panic!("{name}: a kernel case");
|
||||
};
|
||||
replay_variants(compute, prepared.templates().unwrap()).unwrap()
|
||||
replay_variants(compute, &prepared.templates).unwrap()
|
||||
};
|
||||
let variants = |length: u32, sizes: &[[u32; 3]]| -> Vec<ReplayVariant> {
|
||||
let mut lengths = [0u32; 31];
|
||||
@@ -2398,9 +2392,10 @@ fn replay_templates_map_only_the_families_executed_commands_run() {
|
||||
max_mesh_buffer_bind_count: 0,
|
||||
support_dynamic_attribute_stride: false,
|
||||
});
|
||||
let error = replay_templates(&checked).err().unwrap().to_string();
|
||||
let error = replay_templates(&checked).err().unwrap();
|
||||
assert!(
|
||||
error.contains("is not a rasterization-disabled vertex function"),
|
||||
matches!(&error, ExecutorError::NotSupported(NotSupported::Requirements(requirements))
|
||||
if requirements.contains(&ToolingRequirement::ReplayedTemplateResources)),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,9 @@ mod buffers;
|
||||
mod compute;
|
||||
mod device;
|
||||
mod enables;
|
||||
mod generated_commands;
|
||||
mod graphics_pipeline;
|
||||
mod ignored_drivers;
|
||||
mod loader_word;
|
||||
mod multisample;
|
||||
mod pipeline;
|
||||
@@ -21,7 +23,6 @@ pub use compute::execute_engine;
|
||||
pub use compute::opened_worker_device;
|
||||
pub use device::{capture_formats, echo_validation_messages, venue_check};
|
||||
pub use device::{requested_leg, run_robustness_off};
|
||||
pub(crate) use device::{runtime_restriction, Restricting, RuntimeRestriction};
|
||||
pub use profiles::{requested_restriction, restrict_devices_to};
|
||||
pub use render::execute_engine_render;
|
||||
pub use runtime_probe::probe_runtime;
|
||||
|
||||
+33
-46
@@ -15,22 +15,22 @@
|
||||
//! barrier (as K14c's between commands), the initial pipeline, zeroed push constants (the tokens
|
||||
//! write every byte), and `vkCmdExecuteGeneratedCommandsEXT` over its sequences with the count
|
||||
//! the preprocess wrote ([`record_executions`]);
|
||||
//! - where the driver's own preprocessing of an execution recorded after another runs the wrong
|
||||
//! shader, as the runtime decides it (`generated_commands::preprocess_apart`,
|
||||
//! `RuntimeDriverDefect::ImplicitPreprocessAfterExecutionSet`), the commands layout is made for
|
||||
//! explicit preprocessing, every command's execution is preprocessed
|
||||
//! (`vkCmdPreprocessGeneratedCommandsEXT`) before the first runs, a barrier orders those writes
|
||||
//! before the executions, and each runs preprocessed: no preprocessing follows an execution.
|
||||
//! - the commands layout is made for explicit preprocessing, every command's execution is
|
||||
//! preprocessed (`vkCmdPreprocessGeneratedCommandsEXT`) before the first runs, a barrier orders
|
||||
//! those writes before the executions, and each runs preprocessed: no preprocessing follows an
|
||||
//! execution, a form that runs right on every driver.
|
||||
|
||||
use super::*;
|
||||
use metal2vulkan::bind::GeneratedReplay;
|
||||
use metal2vulkan_runtime::generated_commands::{
|
||||
use crate::candidate::platform::generated_commands::{
|
||||
Commands, Execution, ExecutionSetCreateInfo, ExecutionSetPipelineInfo, ExecutionSetToken,
|
||||
GeneratedCommandsInfo, Handle, LayoutCreateInfo, LayoutToken, MemoryRequirementsInfo,
|
||||
PushConstantToken, WriteExecutionSetPipeline, EXECUTION_SET_PIPELINES, INDIRECT_BINDABLE,
|
||||
PREPROCESS_BUFFER, PREPROCESS_WRITE, TOKEN_DISPATCH, TOKEN_EXECUTION_SET, TOKEN_PUSH_CONSTANT,
|
||||
};
|
||||
pub(super) use metal2vulkan_runtime::generated_commands::{PREPROCESS_READ, PREPROCESS_STAGE};
|
||||
pub(super) use crate::candidate::platform::generated_commands::{
|
||||
PREPROCESS_READ, PREPROCESS_STAGE,
|
||||
};
|
||||
use metal2vulkan::bind::GeneratedReplay;
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -46,9 +46,6 @@ pub(super) struct Generated<'c> {
|
||||
pipelines: Vec<vk::Pipeline>,
|
||||
execution_set: Handle,
|
||||
commands_layout: Handle,
|
||||
/// Whether the commands layout is made for explicit preprocessing: every command's execution
|
||||
/// is preprocessed apart before the first runs ([`record_executions`]).
|
||||
explicit: bool,
|
||||
/// The preprocess memory's buffer and allocation ([`Generated::reserve_preprocess`]).
|
||||
preprocess: Option<(vk::Buffer, vk::DeviceMemory)>,
|
||||
/// Each command's preprocess memory, by slot: its address and size (`(0, 0)` where the
|
||||
@@ -117,7 +114,6 @@ impl<'c> Generated<'c> {
|
||||
pipelines: Vec::with_capacity(prepared.len()),
|
||||
execution_set: 0,
|
||||
commands_layout: 0,
|
||||
explicit: context.preprocesses_generated_commands_apart(),
|
||||
preprocess: None,
|
||||
reserved: Vec::new(),
|
||||
sets: Vec::new(),
|
||||
@@ -184,10 +180,6 @@ impl<'c> Generated<'c> {
|
||||
LayoutToken::new(TOKEN_DISPATCH, std::ptr::null(), layout.dispatch_offset()),
|
||||
];
|
||||
let info = LayoutCreateInfo::new(layout.stride, generated.layout.pipeline_layout, &tokens);
|
||||
let info = match generated.explicit {
|
||||
true => info.explicitly_preprocessed(),
|
||||
false => info,
|
||||
};
|
||||
// SAFETY: `info`, its tokens, and their data are live for the call.
|
||||
generated.commands_layout = unsafe { commands.create_commands_layout(&info) }
|
||||
.map_err(|error| fail(format!("create the indirect commands layout: {error}")))?;
|
||||
@@ -351,9 +343,9 @@ fn bindable_pipeline(
|
||||
/// initial pipeline, zeroed push constants (the tokens write every byte of them), and the
|
||||
/// command's `vkCmdExecuteGeneratedCommandsEXT` over its sequences in the scratch at
|
||||
/// `scratch_address`, with the count the preprocess wrote and its own preprocess memory. A
|
||||
/// command that starts no segment has the count 0: its execution runs nothing. Where the layout
|
||||
/// is made for explicit preprocessing ([`Generated::explicit`]), the initial pipeline and zeroed
|
||||
/// push constants are bound first, every command's execution is preprocessed
|
||||
/// command that starts no segment has the count 0: its execution runs nothing. The layout is made
|
||||
/// for explicit preprocessing: the initial pipeline and zeroed push constants are bound first,
|
||||
/// every command's execution is preprocessed
|
||||
/// (`vkCmdPreprocessGeneratedCommandsEXT`) with that state, a barrier orders the preprocessing's
|
||||
/// writes before the executions' preprocess and indirect reads, and each execution runs
|
||||
/// preprocessed. A range whose preprocess memory was not reserved for every command records
|
||||
@@ -425,30 +417,28 @@ pub(super) unsafe fn record_executions(
|
||||
&[],
|
||||
);
|
||||
}
|
||||
if generated.explicit {
|
||||
bind();
|
||||
for slot in 0..layout.slots {
|
||||
let execution = execution(slot);
|
||||
let info = GeneratedCommandsInfo::new(
|
||||
generated.execution_set,
|
||||
generated.commands_layout,
|
||||
&execution,
|
||||
);
|
||||
generated.commands.preprocess(command, &info);
|
||||
}
|
||||
let preprocessed = vk::MemoryBarrier::default()
|
||||
.src_access_mask(PREPROCESS_WRITE)
|
||||
.dst_access_mask(vk::AccessFlags::INDIRECT_COMMAND_READ | PREPROCESS_READ);
|
||||
device.cmd_pipeline_barrier(
|
||||
command,
|
||||
PREPROCESS_STAGE,
|
||||
vk::PipelineStageFlags::DRAW_INDIRECT | PREPROCESS_STAGE,
|
||||
vk::DependencyFlags::empty(),
|
||||
&[preprocessed],
|
||||
&[],
|
||||
&[],
|
||||
bind();
|
||||
for slot in 0..layout.slots {
|
||||
let execution = execution(slot);
|
||||
let info = GeneratedCommandsInfo::new(
|
||||
generated.execution_set,
|
||||
generated.commands_layout,
|
||||
&execution,
|
||||
);
|
||||
generated.commands.preprocess(command, &info);
|
||||
}
|
||||
let preprocessed = vk::MemoryBarrier::default()
|
||||
.src_access_mask(PREPROCESS_WRITE)
|
||||
.dst_access_mask(vk::AccessFlags::INDIRECT_COMMAND_READ | PREPROCESS_READ);
|
||||
device.cmd_pipeline_barrier(
|
||||
command,
|
||||
PREPROCESS_STAGE,
|
||||
vk::PipelineStageFlags::DRAW_INDIRECT | PREPROCESS_STAGE,
|
||||
vk::DependencyFlags::empty(),
|
||||
&[preprocessed],
|
||||
&[],
|
||||
&[],
|
||||
);
|
||||
for slot in 0..layout.slots {
|
||||
if slot > 0 {
|
||||
device.cmd_pipeline_barrier(
|
||||
@@ -468,10 +458,7 @@ pub(super) unsafe fn record_executions(
|
||||
generated.commands_layout,
|
||||
&execution,
|
||||
);
|
||||
match generated.explicit {
|
||||
true => generated.commands.execute_preprocessed(command, &info),
|
||||
false => generated.commands.execute(command, &info),
|
||||
}
|
||||
generated.commands.execute_preprocessed(command, &info);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -33,9 +33,8 @@
|
||||
//! variant's root-table holes, or the merged draw's two (`render::submit_replayed_draws`).
|
||||
//! - **After the wait**, the status: a replay fault refuses the row for the product's typed limits
|
||||
//! and fails it otherwise (`engine::replay_fault_verdict`), then the status verdict. The census
|
||||
//! holds the variant once per execution: the one draw of it the runtime's execution record holds.
|
||||
//! The artifact holds it as a pipeline the authored compile census does not compile, as the
|
||||
//! runtime path's holds every pipeline its executed commands ran.
|
||||
//! holds the variant once per execution. The artifact holds it as a pipeline the authored
|
||||
//! compile census does not compile.
|
||||
|
||||
use super::device_replay::{preprocess_objects, ReplayPath};
|
||||
use super::replay::{bound_table, require_enabled, Executed};
|
||||
|
||||
@@ -146,19 +146,16 @@ pub(in crate::candidate::platform) fn execute_commands<'c, K: Ord + Copy + std::
|
||||
))
|
||||
})?,
|
||||
},
|
||||
// The runtime path executes them (`runtime_case::encoded_execution`); the
|
||||
// executor's own context, which runs a case only where the runtime path has a gap,
|
||||
// draws no index or patch buffer a record names.
|
||||
// The executor's context draws no index or patch buffer a record names, and no
|
||||
// mesh draw.
|
||||
Action::DrawIndexedPrimitives { .. }
|
||||
| Action::DrawPatches { .. }
|
||||
| Action::DrawIndexedPatches { .. }
|
||||
| Action::DrawMeshThreadgroups { .. }
|
||||
| Action::DrawMeshThreads { .. } => {
|
||||
return Err(fail(
|
||||
"an indexed, patch or mesh draw, which only the runtime path executes"
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
| Action::DrawMeshThreads { .. } => return Err(fail(
|
||||
"an indexed, patch or mesh draw, which the executor's context does not replay"
|
||||
.into(),
|
||||
)),
|
||||
};
|
||||
let token = resolved
|
||||
.pipeline
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! Vulkan device creation, enabled capabilities, and per-thread context lifetime.
|
||||
|
||||
use super::enables::{self, Available, FeatureChain};
|
||||
use super::ignored_drivers::IgnoredDrivers;
|
||||
use super::loader_word::LoaderWord;
|
||||
use super::profiles::{
|
||||
self, ActiveTool, ProfileRestriction, ProfilesLayer, ProfilesSettings, RestrictionError,
|
||||
PROFILES_LAYER,
|
||||
};
|
||||
use crate::candidate::runtime_case::IgnoredDrivers;
|
||||
use crate::coverage::{ExecutionClass, Leg};
|
||||
use crate::gpu::wait::{self, SubmissionBackend};
|
||||
use crate::gpu::DeviceType;
|
||||
@@ -460,8 +460,7 @@ pub fn echo_validation_messages() {
|
||||
/// What the validation layer reported that fails a row: every `ERROR` message, and every
|
||||
/// `WARNING` of the validation type. Bounded so a flood cannot grow without limit. The loader's
|
||||
/// own reports, at `vkCreateInstance`, of the driver manifests it ignored are the host's listing
|
||||
/// of its drivers, not the run's work: they pass as the runtime lane's `Messages` passes them
|
||||
/// ([`MessageSink::take`]).
|
||||
/// of its drivers, not the run's work: they pass ([`MessageSink::take`]).
|
||||
///
|
||||
/// But for one message about the driver: on a context whose opened profile takes
|
||||
/// `DriverDeviation::MetalVertexSimdgroups` ([`MessageSink::unadvertised_vertex`]), the layer's
|
||||
@@ -485,12 +484,19 @@ pub(super) struct MessageSink {
|
||||
/// one of them fails no row; set once the opened description is known.
|
||||
making: OnceLock<Vec<metal2vulkan::device::DriverDiagnostic>>,
|
||||
/// Whether the opened device's driver runs the descriptor set layouts its
|
||||
/// `vkGetDescriptorSetLayoutSupport` refuses, as the runtime makes them there
|
||||
/// (`metal2vulkan_runtime::makes_layouts_past_support`: a heap's set 1 on MoltenVK), set once
|
||||
/// the opened description is known.
|
||||
/// `vkGetDescriptorSetLayoutSupport` refuses ([`makes_layouts_past_support`]: a heap's set 1
|
||||
/// on MoltenVK), set once the opened description is known.
|
||||
unsupported_sets: AtomicBool,
|
||||
}
|
||||
|
||||
/// Whether the driver of the device `description` names runs a descriptor set layout its
|
||||
/// `vkGetDescriptorSetLayoutSupport` refuses: MoltenVK's, which runs a heap's set 1 its query
|
||||
/// refuses. The executor makes its own heap sets so there, and its sink passes the validation
|
||||
/// layer's report of such a layout ([`MessageSink::unsupported_sets`]).
|
||||
fn makes_layouts_past_support(description: &DeviceDescription) -> bool {
|
||||
description.driver_id == Some(vk::DriverId::MOLTENVK)
|
||||
}
|
||||
|
||||
/// One message the sink kept: its id name and text, which tell the loader's reports apart
|
||||
/// ([`MessageSink::take`]), and the line a row reports.
|
||||
struct Recorded {
|
||||
@@ -531,7 +537,7 @@ impl MessageSink {
|
||||
|
||||
/// The lines kept since the last call, removed: all but the loader's own reports of the
|
||||
/// driver manifests it ignored (`IgnoredDrivers`), each printed as a line of its own
|
||||
/// (`LOADER-DRIVER`), as the runtime lane's `Messages` passes them.
|
||||
/// (`LOADER-DRIVER`).
|
||||
fn take(&self) -> Vec<String> {
|
||||
let recorded: Vec<Recorded> = {
|
||||
let mut messages = self.messages.lock().unwrap_or_else(|p| p.into_inner());
|
||||
@@ -1251,11 +1257,7 @@ fn create_instance(
|
||||
// SAFETY: every pointer in `info` outlives the call. A validated context's layer provides
|
||||
// the extensions it enables through it (`require_validation_layer`), and so does the
|
||||
// profiles layer of a restricted context or a probe (`require_profiles_layer`).
|
||||
let instance = unsafe { entry.create_instance(info, None) };
|
||||
// A layer registered an exit handler as the call began: the runtime's, where a runtime
|
||||
// device lives in this process (a lane's), registers again after it.
|
||||
metal2vulkan_runtime::program_instance_made();
|
||||
instance
|
||||
unsafe { entry.create_instance(info, None) }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1359,186 +1361,6 @@ pub(super) fn refused_restriction(
|
||||
}
|
||||
}
|
||||
|
||||
/// This process's restriction as the runtime path opens its device under it: the restricted
|
||||
/// context's steps before its device, on the device `device_type` selects.
|
||||
pub(crate) enum Restricting {
|
||||
/// The device takes P: what the runtime device's options and its second check need.
|
||||
Takes(Box<RuntimeRestriction>),
|
||||
/// The device lacks capabilities P states: the typed refusal, recorded as the executor's
|
||||
/// context records it ([`restriction_refusal`](super::compute::restriction_refusal)).
|
||||
Refused(Box<crate::candidate::engine::RunAttempt>),
|
||||
}
|
||||
|
||||
/// What a runtime device restricted to P is made with: P, the device as it is (read through the
|
||||
/// layer with its emulation off, which the second check compares the layer's kept members with)
|
||||
/// and its identity, and the extensions the layer presents for P that P does not list, which it
|
||||
/// hides.
|
||||
pub(crate) struct RuntimeRestriction {
|
||||
restriction: &'static ProfileRestriction,
|
||||
native: DeviceDescription,
|
||||
identity: serde_json::Value,
|
||||
hidden: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// The restricted context's steps before its device, for the runtime path's `executor`: `None`
|
||||
/// when this process runs unrestricted; else the first check ([`profiles::check_within`])
|
||||
/// decides between a typed refusal and a restriction the device takes, whose hidden extensions
|
||||
/// are read as a context reads them. Every other failure is an error, as in the context.
|
||||
pub(crate) fn runtime_restriction(
|
||||
device_type: DeviceType,
|
||||
executor: &str,
|
||||
) -> Result<Option<Restricting>, String> {
|
||||
let Some(restriction) = profiles::current_restriction() else {
|
||||
return Ok(None);
|
||||
};
|
||||
restricting(restriction, device_type, executor).map(Some)
|
||||
}
|
||||
|
||||
/// [`runtime_restriction`]'s steps for `restriction`: the first check decides between a typed
|
||||
/// refusal, recorded as `executor`'s context records it, and a restriction the device takes.
|
||||
fn restricting(
|
||||
restriction: &'static ProfileRestriction,
|
||||
device_type: DeviceType,
|
||||
executor: &str,
|
||||
) -> Result<Restricting, String> {
|
||||
Ok(match first_check(restriction, device_type)? {
|
||||
FirstCheck::Takes(restriction) => Restricting::Takes(restriction),
|
||||
FirstCheck::Lacks(refused) => Restricting::Refused(Box::new(
|
||||
super::compute::restriction_refusal(&refused, executor),
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The first check's ([`profiles::check_within`]) verdict on a restriction.
|
||||
enum FirstCheck {
|
||||
/// The device takes P.
|
||||
Takes(Box<RuntimeRestriction>),
|
||||
/// The device lacks capabilities P states: what a typed refusal of it records.
|
||||
Lacks(Box<RefusedRestriction>),
|
||||
}
|
||||
|
||||
/// The restricted context's steps before its device for `restriction`, on the device
|
||||
/// `device_type` selects: the first check ([`profiles::check_within`]) decides between a refusal
|
||||
/// and a restriction the device takes, whose hidden extensions are read as a context reads them.
|
||||
/// Every other failure is an error, as in the context.
|
||||
fn first_check(
|
||||
restriction: &'static ProfileRestriction,
|
||||
device_type: DeviceType,
|
||||
) -> Result<FirstCheck, String> {
|
||||
if device_type == DeviceType::Gpu {
|
||||
crate::gpu::tripwire::refuse_if_tripped()?;
|
||||
}
|
||||
let entry = load_entry()?;
|
||||
// SAFETY: a global command of a loaded entry.
|
||||
let available = unsafe { entry.enumerate_instance_extension_properties(None) }
|
||||
.map_err(|error| format!("enumerate Vulkan instance extensions: {error}"))?;
|
||||
let portability = available.iter().any(|extension| {
|
||||
extension_name(&extension.extension_name) == ash::khr::portability_enumeration::NAME
|
||||
});
|
||||
require_profiles_layer(&entry)?;
|
||||
let version = restriction.context_version();
|
||||
let (native, identity) = native_probe(&entry, device_type, portability, version)?;
|
||||
match profiles::check_within(restriction, &native, version) {
|
||||
Ok(()) => {}
|
||||
Err(RestrictionError::Exceeds { gaps, .. }) => {
|
||||
return Ok(FirstCheck::Lacks(Box::new(RefusedRestriction {
|
||||
restriction,
|
||||
gaps,
|
||||
native,
|
||||
identity,
|
||||
})));
|
||||
}
|
||||
Err(error) => return Err(error.to_string()),
|
||||
}
|
||||
let presented = presented_extensions(&entry, device_type, portability, restriction)?;
|
||||
let hidden = restriction.hidden(presented.iter().map(String::as_str));
|
||||
Ok(FirstCheck::Takes(Box::new(RuntimeRestriction {
|
||||
restriction,
|
||||
native,
|
||||
identity,
|
||||
hidden,
|
||||
})))
|
||||
}
|
||||
|
||||
impl RuntimeRestriction {
|
||||
/// The committed profile's stem.
|
||||
pub(crate) fn stem(&self) -> &str {
|
||||
&self.restriction.stem
|
||||
}
|
||||
|
||||
/// `options` restricted to P as a restricted context's instance is: the profiles layer below
|
||||
/// the validation layer (which `options` stacks first), configured with P and the hidden
|
||||
/// extensions, and the instance at P's version ([`ProfileRestriction::context_version`]).
|
||||
pub(crate) fn restrict(
|
||||
&self,
|
||||
options: &mut metal2vulkan_runtime::DeviceOptions,
|
||||
) -> Result<(), String> {
|
||||
let settings =
|
||||
ProfilesSettings::new(ProfilesLayer::Restrict(self.restriction, &self.hidden))?;
|
||||
options.layers.push(PROFILES_LAYER.to_owned());
|
||||
options.layer_settings.extend(settings.runtime_settings());
|
||||
options.instance_api_version = Some(self.restriction.context_version());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What `executor`'s typed refusal of the restricted device itself, before it opened (a
|
||||
/// device the runtime refuses at creation), records of the device as it is, with the
|
||||
/// restriction it was made under (`compute::native_refused_on`, as a refusal of the
|
||||
/// restriction records it).
|
||||
pub(crate) fn refused_on(
|
||||
&self,
|
||||
executor: &str,
|
||||
) -> Result<crate::candidate::engine::RefusedOn, String> {
|
||||
let layer = serde_json::json!({
|
||||
"profile": self.restriction.stem,
|
||||
"profile_name": self.restriction.profile_name,
|
||||
"profile_sha256": self.restriction.sha256,
|
||||
"hidden_extensions": self.hidden,
|
||||
});
|
||||
super::compute::native_refused_on(&self.native, &self.identity, executor, layer)
|
||||
}
|
||||
|
||||
/// The restricted context's second check ([`profiles::check_restricted`]) on `device`,
|
||||
/// opened with [`RuntimeRestriction::restrict`]'s options, read through its raw handles: the
|
||||
/// layer active, its kept members the native device's, and every other member P's.
|
||||
pub(crate) fn check(
|
||||
&self,
|
||||
device: &metal2vulkan_runtime::Device,
|
||||
) -> Result<crate::candidate::RestrictedDevice, String> {
|
||||
let version = self.restriction.context_version();
|
||||
// SAFETY: only physical-device queries of the device's own instance, created at P's
|
||||
// version; nothing is created, destroyed, or submitted, and the handles are not kept.
|
||||
let (tools, queried) = unsafe {
|
||||
let handles = device.raw();
|
||||
let tools =
|
||||
profiles::active_tools(handles.entry, handles.instance, handles.physical_device)?;
|
||||
let queried =
|
||||
DeviceDescription::query(handles.instance, handles.physical_device, version)
|
||||
.map_err(|error| format!("query the restricted device: {error}"))?;
|
||||
(tools, queried)
|
||||
};
|
||||
let translated =
|
||||
profiles::check_restricted(self.restriction, &self.native, &tools, &queried, version)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let record = serde_json::json!({
|
||||
"tool": profiles::profiles_tool(&tools),
|
||||
"profile": self.restriction.stem,
|
||||
"profile_name": self.restriction.profile_name,
|
||||
"profile_sha256": self.restriction.sha256,
|
||||
"hidden_extensions": self.hidden,
|
||||
});
|
||||
let kept = profiles::differences(&translated, &queried)
|
||||
.into_iter()
|
||||
.map(|difference| difference.path)
|
||||
.collect();
|
||||
Ok(crate::candidate::RestrictedDevice {
|
||||
translated,
|
||||
kept,
|
||||
record,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The device extensions the device `device_type` selects presents under `restriction`, read
|
||||
/// through an instance whose profiles layer restricts it and hides nothing, then destroyed: P's
|
||||
/// extensions and the ones the layer adds for P's version.
|
||||
@@ -1580,19 +1402,6 @@ impl VulkanContext {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the device replay's generated-commands executions are preprocessed apart, as the
|
||||
/// runtime's are on the driver that executes (`generated_commands::preprocess_apart` of its
|
||||
/// queried description, the device as it is, under a restriction too); also where the query
|
||||
/// failed, since preprocessing apart runs right on every driver.
|
||||
pub(super) fn preprocesses_generated_commands_apart(&self) -> bool {
|
||||
match &self.queried_description {
|
||||
Ok(description) => {
|
||||
metal2vulkan_runtime::generated_commands::preprocess_apart(description)
|
||||
}
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a device of `device_type` for `purpose`: the only Vulkan device creation in this crate,
|
||||
/// and with its probes the only caller of [`create_instance`].
|
||||
fn new(device_type: DeviceType, purpose: Purpose) -> Result<Self, String> {
|
||||
@@ -1849,10 +1658,9 @@ impl VulkanContext {
|
||||
})
|
||||
.collect();
|
||||
let _ = messages.making.set(making);
|
||||
messages.unsupported_sets.store(
|
||||
metal2vulkan_runtime::makes_layouts_past_support(description),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
messages
|
||||
.unsupported_sets
|
||||
.store(makes_layouts_past_support(description), Ordering::Relaxed);
|
||||
}
|
||||
let opened = opened_description
|
||||
.clone()
|
||||
@@ -1936,9 +1744,7 @@ impl VulkanContext {
|
||||
clippy::disallowed_methods,
|
||||
reason = "the one call site, after the loader word is put back"
|
||||
)]
|
||||
pub(super) fn generated_commands(
|
||||
&self,
|
||||
) -> Option<metal2vulkan_runtime::generated_commands::Commands> {
|
||||
pub(super) fn generated_commands(&self) -> Option<super::generated_commands::Commands> {
|
||||
if !self.generated_commands {
|
||||
return None;
|
||||
}
|
||||
@@ -1952,7 +1758,7 @@ impl VulkanContext {
|
||||
}
|
||||
};
|
||||
// SAFETY: each name is the extension's command of this device, which enabled it.
|
||||
unsafe { metal2vulkan_runtime::generated_commands::Commands::load(handle, load) }
|
||||
unsafe { super::generated_commands::Commands::load(handle, load) }
|
||||
}
|
||||
|
||||
/// `vkGetMemoryHostPointerPropertiesEXT` (`VK_EXT_external_memory_host`), loaded through the
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
//! `VK_EXT_device_generated_commands`, which `ash 0.38` (Vulkan 1.3.281) predates: the structures
|
||||
//! and commands the device replay's generated-commands path uses (`compute::device_replay`), laid
|
||||
//! out as the registry defines them (`vk.xml`, extension number 573: structure types
|
||||
//! `1000572000 + n`).
|
||||
//!
|
||||
//! The executor's context loads the commands only where it enabled the extension
|
||||
//! ([`Commands::load`]). Every commands layout is made for explicit preprocessing: each execution
|
||||
//! is preprocessed apart ([`Commands::preprocess`]) and runs preprocessed
|
||||
//! ([`Commands::execute_preprocessed`]), a form that runs right on every driver.
|
||||
|
||||
use ash::vk;
|
||||
use std::ffi::{c_void, CStr};
|
||||
|
||||
/// `VkIndirectExecutionSetEXT` and `VkIndirectCommandsLayoutEXT`: non-dispatchable handles.
|
||||
pub(crate) type Handle = u64;
|
||||
|
||||
const fn structure(n: i32) -> vk::StructureType {
|
||||
vk::StructureType::from_raw(1_000_572_000 + n)
|
||||
}
|
||||
|
||||
/// `VK_INDIRECT_EXECUTION_SET_INFO_TYPE_PIPELINES_EXT`.
|
||||
pub(crate) const EXECUTION_SET_PIPELINES: i32 = 0;
|
||||
/// `VK_INDIRECT_COMMANDS_TOKEN_TYPE_EXECUTION_SET_EXT`, `..._PUSH_CONSTANT_EXT`,
|
||||
/// `..._DISPATCH_EXT`.
|
||||
pub(crate) const TOKEN_EXECUTION_SET: i32 = 0;
|
||||
pub(crate) const TOKEN_PUSH_CONSTANT: i32 = 1;
|
||||
pub(crate) const TOKEN_DISPATCH: i32 = 9;
|
||||
/// `VK_PIPELINE_CREATE_2_INDIRECT_BINDABLE_BIT_EXT`.
|
||||
pub(crate) const INDIRECT_BINDABLE: vk::PipelineCreateFlags2KHR =
|
||||
vk::PipelineCreateFlags2KHR::from_raw(0x40_0000_0000);
|
||||
/// `VK_BUFFER_USAGE_2_PREPROCESS_BUFFER_BIT_EXT`.
|
||||
pub(crate) const PREPROCESS_BUFFER: vk::BufferUsageFlags2KHR =
|
||||
vk::BufferUsageFlags2KHR::from_raw(0x8000_0000);
|
||||
/// `VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EXPLICIT_PREPROCESS_BIT_EXT`: an execution of the layout
|
||||
/// is preprocessed apart (`vkCmdPreprocessGeneratedCommandsEXT`) before it runs.
|
||||
const LAYOUT_EXPLICIT_PREPROCESS: u32 = 0x1;
|
||||
/// `VK_PIPELINE_STAGE_COMMAND_PREPROCESS_BIT_EXT`, `VK_ACCESS_COMMAND_PREPROCESS_READ_BIT_EXT` and
|
||||
/// `VK_ACCESS_COMMAND_PREPROCESS_WRITE_BIT_EXT` (the values of the `NV` names `ash` has).
|
||||
pub(crate) const PREPROCESS_STAGE: vk::PipelineStageFlags =
|
||||
vk::PipelineStageFlags::COMMAND_PREPROCESS_NV;
|
||||
pub(crate) const PREPROCESS_READ: vk::AccessFlags = vk::AccessFlags::COMMAND_PREPROCESS_READ_NV;
|
||||
pub(crate) const PREPROCESS_WRITE: vk::AccessFlags = vk::AccessFlags::COMMAND_PREPROCESS_WRITE_NV;
|
||||
|
||||
/// `VkIndirectExecutionSetPipelineInfoEXT`.
|
||||
#[repr(C)]
|
||||
pub(crate) struct ExecutionSetPipelineInfo {
|
||||
s_type: vk::StructureType,
|
||||
p_next: *const c_void,
|
||||
initial_pipeline: vk::Pipeline,
|
||||
max_pipeline_count: u32,
|
||||
}
|
||||
|
||||
impl ExecutionSetPipelineInfo {
|
||||
pub(crate) fn new(initial_pipeline: vk::Pipeline, max_pipeline_count: u32) -> Self {
|
||||
ExecutionSetPipelineInfo {
|
||||
s_type: structure(10),
|
||||
p_next: std::ptr::null(),
|
||||
initial_pipeline,
|
||||
max_pipeline_count,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `VkIndirectExecutionSetCreateInfoEXT` of the pipelines type (its `info` union holds
|
||||
/// `pPipelineInfo`).
|
||||
#[repr(C)]
|
||||
pub(crate) struct ExecutionSetCreateInfo {
|
||||
s_type: vk::StructureType,
|
||||
p_next: *const c_void,
|
||||
kind: i32,
|
||||
pipeline_info: *const ExecutionSetPipelineInfo,
|
||||
}
|
||||
|
||||
impl ExecutionSetCreateInfo {
|
||||
pub(crate) fn new(pipeline_info: &ExecutionSetPipelineInfo) -> Self {
|
||||
ExecutionSetCreateInfo {
|
||||
s_type: structure(3),
|
||||
p_next: std::ptr::null(),
|
||||
kind: EXECUTION_SET_PIPELINES,
|
||||
pipeline_info,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `VkWriteIndirectExecutionSetPipelineEXT`.
|
||||
#[repr(C)]
|
||||
pub(crate) struct WriteExecutionSetPipeline {
|
||||
s_type: vk::StructureType,
|
||||
p_next: *const c_void,
|
||||
index: u32,
|
||||
pipeline: vk::Pipeline,
|
||||
}
|
||||
|
||||
impl WriteExecutionSetPipeline {
|
||||
pub(crate) fn new(index: u32, pipeline: vk::Pipeline) -> Self {
|
||||
WriteExecutionSetPipeline {
|
||||
s_type: structure(8),
|
||||
p_next: std::ptr::null(),
|
||||
index,
|
||||
pipeline,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `VkIndirectCommandsPushConstantTokenEXT`.
|
||||
#[repr(C)]
|
||||
pub(crate) struct PushConstantToken {
|
||||
pub(crate) update_range: vk::PushConstantRange,
|
||||
}
|
||||
|
||||
/// `VkIndirectCommandsExecutionSetTokenEXT`.
|
||||
#[repr(C)]
|
||||
pub(crate) struct ExecutionSetToken {
|
||||
pub(crate) kind: i32,
|
||||
pub(crate) shader_stages: vk::ShaderStageFlags,
|
||||
}
|
||||
|
||||
/// `VkIndirectCommandsLayoutTokenEXT` (its `data` union is one pointer).
|
||||
#[repr(C)]
|
||||
pub(crate) struct LayoutToken {
|
||||
s_type: vk::StructureType,
|
||||
p_next: *const c_void,
|
||||
kind: i32,
|
||||
data: *const c_void,
|
||||
offset: u32,
|
||||
}
|
||||
|
||||
impl LayoutToken {
|
||||
pub(crate) fn new(kind: i32, data: *const c_void, offset: u32) -> Self {
|
||||
LayoutToken {
|
||||
s_type: structure(7),
|
||||
p_next: std::ptr::null(),
|
||||
kind,
|
||||
data,
|
||||
offset,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `VkIndirectCommandsLayoutCreateInfoEXT`, made for explicit preprocessing
|
||||
/// (`VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EXPLICIT_PREPROCESS_BIT_EXT`): each of its executions is
|
||||
/// preprocessed apart ([`Commands::preprocess`]) and runs preprocessed
|
||||
/// ([`Commands::execute_preprocessed`]).
|
||||
#[repr(C)]
|
||||
pub(crate) struct LayoutCreateInfo {
|
||||
s_type: vk::StructureType,
|
||||
p_next: *const c_void,
|
||||
flags: u32,
|
||||
shader_stages: vk::ShaderStageFlags,
|
||||
indirect_stride: u32,
|
||||
pipeline_layout: vk::PipelineLayout,
|
||||
token_count: u32,
|
||||
tokens: *const LayoutToken,
|
||||
}
|
||||
|
||||
impl LayoutCreateInfo {
|
||||
pub(crate) fn new(
|
||||
indirect_stride: u32,
|
||||
pipeline_layout: vk::PipelineLayout,
|
||||
tokens: &[LayoutToken],
|
||||
) -> Self {
|
||||
LayoutCreateInfo {
|
||||
s_type: structure(6),
|
||||
p_next: std::ptr::null(),
|
||||
flags: LAYOUT_EXPLICIT_PREPROCESS,
|
||||
shader_stages: vk::ShaderStageFlags::COMPUTE,
|
||||
indirect_stride,
|
||||
pipeline_layout,
|
||||
token_count: tokens.len() as u32,
|
||||
tokens: tokens.as_ptr(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `VkGeneratedCommandsMemoryRequirementsInfoEXT`.
|
||||
#[repr(C)]
|
||||
pub(crate) struct MemoryRequirementsInfo {
|
||||
s_type: vk::StructureType,
|
||||
p_next: *const c_void,
|
||||
execution_set: Handle,
|
||||
commands_layout: Handle,
|
||||
max_sequence_count: u32,
|
||||
max_draw_count: u32,
|
||||
}
|
||||
|
||||
impl MemoryRequirementsInfo {
|
||||
pub(crate) fn new(execution_set: Handle, commands_layout: Handle, sequences: u32) -> Self {
|
||||
MemoryRequirementsInfo {
|
||||
s_type: structure(2),
|
||||
p_next: std::ptr::null(),
|
||||
execution_set,
|
||||
commands_layout,
|
||||
max_sequence_count: sequences,
|
||||
max_draw_count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `VkGeneratedCommandsInfoEXT`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct GeneratedCommandsInfo {
|
||||
s_type: vk::StructureType,
|
||||
p_next: *const c_void,
|
||||
shader_stages: vk::ShaderStageFlags,
|
||||
execution_set: Handle,
|
||||
commands_layout: Handle,
|
||||
indirect_address: vk::DeviceAddress,
|
||||
indirect_address_size: vk::DeviceSize,
|
||||
preprocess_address: vk::DeviceAddress,
|
||||
preprocess_size: vk::DeviceSize,
|
||||
max_sequence_count: u32,
|
||||
sequence_count_address: vk::DeviceAddress,
|
||||
max_draw_count: u32,
|
||||
}
|
||||
|
||||
/// One execution's addresses and sizes.
|
||||
pub(crate) struct Execution {
|
||||
pub(crate) indirect: (vk::DeviceAddress, vk::DeviceSize),
|
||||
pub(crate) preprocess: (vk::DeviceAddress, vk::DeviceSize),
|
||||
pub(crate) max_sequences: u32,
|
||||
pub(crate) count_address: vk::DeviceAddress,
|
||||
}
|
||||
|
||||
impl GeneratedCommandsInfo {
|
||||
pub(crate) fn new(execution_set: Handle, commands_layout: Handle, e: &Execution) -> Self {
|
||||
GeneratedCommandsInfo {
|
||||
s_type: structure(4),
|
||||
p_next: std::ptr::null(),
|
||||
shader_stages: vk::ShaderStageFlags::COMPUTE,
|
||||
execution_set,
|
||||
commands_layout,
|
||||
indirect_address: e.indirect.0,
|
||||
indirect_address_size: e.indirect.1,
|
||||
preprocess_address: e.preprocess.0,
|
||||
preprocess_size: e.preprocess.1,
|
||||
max_sequence_count: e.max_sequences,
|
||||
sequence_count_address: e.count_address,
|
||||
max_draw_count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type CreateExecutionSet = unsafe extern "system" fn(
|
||||
vk::Device,
|
||||
*const ExecutionSetCreateInfo,
|
||||
*const vk::AllocationCallbacks<'static>,
|
||||
*mut Handle,
|
||||
) -> vk::Result;
|
||||
type DestroyHandle =
|
||||
unsafe extern "system" fn(vk::Device, Handle, *const vk::AllocationCallbacks<'static>);
|
||||
type UpdateExecutionSetPipeline =
|
||||
unsafe extern "system" fn(vk::Device, Handle, u32, *const WriteExecutionSetPipeline);
|
||||
type CreateCommandsLayout = unsafe extern "system" fn(
|
||||
vk::Device,
|
||||
*const LayoutCreateInfo,
|
||||
*const vk::AllocationCallbacks<'static>,
|
||||
*mut Handle,
|
||||
) -> vk::Result;
|
||||
type MemoryRequirements = unsafe extern "system" fn(
|
||||
vk::Device,
|
||||
*const MemoryRequirementsInfo,
|
||||
*mut vk::MemoryRequirements2<'static>,
|
||||
);
|
||||
type Execute =
|
||||
unsafe extern "system" fn(vk::CommandBuffer, vk::Bool32, *const GeneratedCommandsInfo);
|
||||
type Preprocess =
|
||||
unsafe extern "system" fn(vk::CommandBuffer, *const GeneratedCommandsInfo, vk::CommandBuffer);
|
||||
|
||||
/// The extension's commands, loaded for one device.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Commands {
|
||||
device: vk::Device,
|
||||
create_execution_set: CreateExecutionSet,
|
||||
destroy_execution_set: DestroyHandle,
|
||||
update_execution_set_pipeline: UpdateExecutionSetPipeline,
|
||||
create_commands_layout: CreateCommandsLayout,
|
||||
destroy_commands_layout: DestroyHandle,
|
||||
memory_requirements: MemoryRequirements,
|
||||
execute: Execute,
|
||||
preprocess: Preprocess,
|
||||
}
|
||||
|
||||
impl Commands {
|
||||
/// The commands of `device`, each from `load` (`vkGetDeviceProcAddr`); `None` when one is
|
||||
/// missing.
|
||||
///
|
||||
/// # Safety
|
||||
/// `load` returns each name's command of `device`, which enabled the extension.
|
||||
pub(crate) unsafe fn load(
|
||||
device: vk::Device,
|
||||
load: impl Fn(&CStr) -> vk::PFN_vkVoidFunction,
|
||||
) -> Option<Commands> {
|
||||
macro_rules! command {
|
||||
($name:literal, $ty:ty) => {{
|
||||
let f = load($name)?;
|
||||
// SAFETY: the registry gives the command this signature.
|
||||
unsafe { std::mem::transmute::<unsafe extern "system" fn(), $ty>(f) }
|
||||
}};
|
||||
}
|
||||
Some(Commands {
|
||||
device,
|
||||
create_execution_set: command!(c"vkCreateIndirectExecutionSetEXT", CreateExecutionSet),
|
||||
destroy_execution_set: command!(c"vkDestroyIndirectExecutionSetEXT", DestroyHandle),
|
||||
update_execution_set_pipeline: command!(
|
||||
c"vkUpdateIndirectExecutionSetPipelineEXT",
|
||||
UpdateExecutionSetPipeline
|
||||
),
|
||||
create_commands_layout: command!(
|
||||
c"vkCreateIndirectCommandsLayoutEXT",
|
||||
CreateCommandsLayout
|
||||
),
|
||||
destroy_commands_layout: command!(c"vkDestroyIndirectCommandsLayoutEXT", DestroyHandle),
|
||||
memory_requirements: command!(
|
||||
c"vkGetGeneratedCommandsMemoryRequirementsEXT",
|
||||
MemoryRequirements
|
||||
),
|
||||
execute: command!(c"vkCmdExecuteGeneratedCommandsEXT", Execute),
|
||||
preprocess: command!(c"vkCmdPreprocessGeneratedCommandsEXT", Preprocess),
|
||||
})
|
||||
}
|
||||
|
||||
/// `vkCreateIndirectExecutionSetEXT`.
|
||||
///
|
||||
/// # Safety
|
||||
/// `info` and what it points at are valid for the call.
|
||||
pub(crate) unsafe fn create_execution_set(
|
||||
&self,
|
||||
info: &ExecutionSetCreateInfo,
|
||||
) -> Result<Handle, vk::Result> {
|
||||
let mut out = 0;
|
||||
// SAFETY: the caller's contract.
|
||||
match unsafe { (self.create_execution_set)(self.device, info, std::ptr::null(), &mut out) }
|
||||
{
|
||||
vk::Result::SUCCESS => Ok(out),
|
||||
error => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// `vkDestroyIndirectExecutionSetEXT`.
|
||||
///
|
||||
/// # Safety
|
||||
/// No pending work uses `set`.
|
||||
pub(crate) unsafe fn destroy_execution_set(&self, set: Handle) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { (self.destroy_execution_set)(self.device, set, std::ptr::null()) }
|
||||
}
|
||||
|
||||
/// `vkUpdateIndirectExecutionSetPipelineEXT`.
|
||||
///
|
||||
/// # Safety
|
||||
/// No submitted work references the written indices.
|
||||
pub(crate) unsafe fn update_execution_set(
|
||||
&self,
|
||||
set: Handle,
|
||||
writes: &[WriteExecutionSetPipeline],
|
||||
) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe {
|
||||
(self.update_execution_set_pipeline)(
|
||||
self.device,
|
||||
set,
|
||||
writes.len() as u32,
|
||||
writes.as_ptr(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// `vkCreateIndirectCommandsLayoutEXT`.
|
||||
///
|
||||
/// # Safety
|
||||
/// `info` and what it points at are valid for the call.
|
||||
pub(crate) unsafe fn create_commands_layout(
|
||||
&self,
|
||||
info: &LayoutCreateInfo,
|
||||
) -> Result<Handle, vk::Result> {
|
||||
let mut out = 0;
|
||||
// SAFETY: the caller's contract.
|
||||
match unsafe {
|
||||
(self.create_commands_layout)(self.device, info, std::ptr::null(), &mut out)
|
||||
} {
|
||||
vk::Result::SUCCESS => Ok(out),
|
||||
error => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// `vkDestroyIndirectCommandsLayoutEXT`.
|
||||
///
|
||||
/// # Safety
|
||||
/// No pending work uses `layout`.
|
||||
pub(crate) unsafe fn destroy_commands_layout(&self, layout: Handle) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { (self.destroy_commands_layout)(self.device, layout, std::ptr::null()) }
|
||||
}
|
||||
|
||||
/// `vkGetGeneratedCommandsMemoryRequirementsEXT`.
|
||||
///
|
||||
/// # Safety
|
||||
/// `info`'s handles are live.
|
||||
pub(crate) unsafe fn memory_requirements(
|
||||
&self,
|
||||
info: &MemoryRequirementsInfo,
|
||||
) -> vk::MemoryRequirements {
|
||||
let mut out = vk::MemoryRequirements2::default();
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { (self.memory_requirements)(self.device, info, &mut out) };
|
||||
out.memory_requirements
|
||||
}
|
||||
|
||||
/// `vkCmdPreprocessGeneratedCommandsEXT` of `info` into `command`, the state taken from
|
||||
/// `command` itself.
|
||||
///
|
||||
/// # Safety
|
||||
/// `command` is recording, with the execution set's initial pipeline bound; `info`'s handles
|
||||
/// and addresses are live until the work completes.
|
||||
pub(crate) unsafe fn preprocess(
|
||||
&self,
|
||||
command: vk::CommandBuffer,
|
||||
info: &GeneratedCommandsInfo,
|
||||
) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { (self.preprocess)(command, info, command) }
|
||||
}
|
||||
|
||||
/// `vkCmdExecuteGeneratedCommandsEXT` of commands [`preprocess`](Self::preprocess) wrote.
|
||||
///
|
||||
/// # Safety
|
||||
/// `command` is recording, with the execution set's initial pipeline bound; `info` was
|
||||
/// preprocessed in `command`, with the same contents and the same state bound, a barrier
|
||||
/// ordering that preprocessing's writes before this execution, and its handles and addresses
|
||||
/// are live until the work completes.
|
||||
pub(crate) unsafe fn execute_preprocessed(
|
||||
&self,
|
||||
command: vk::CommandBuffer,
|
||||
info: &GeneratedCommandsInfo,
|
||||
) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { (self.execute)(command, vk::TRUE, info) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! The loader's reports, at `vkCreateInstance`, of each driver manifest whose library it could not
|
||||
//! load, or that is no driver, and then ignores ([`IgnoredDrivers`]): the host's listing of its
|
||||
//! drivers (a vendor's manifest left behind by a driver no longer installed is common), whatever
|
||||
//! the device does, and nothing it did. The executor's sink passes those with a line of their own,
|
||||
//! each naming the library the loader said it ignored.
|
||||
|
||||
/// The id name the Vulkan loader gives the messages it reports itself.
|
||||
const LOADER_MESSAGE: &str = "Loader Message";
|
||||
|
||||
/// How the loader's message about a driver manifest whose library it could not load begins
|
||||
/// (`loader_icd_scan`, Vulkan-Loader `loader/loader.c`): the library the manifest names follows,
|
||||
/// then [`IGNORING`].
|
||||
const ICD_SCAN_FAILED: &str = "loader_icd_scan: Failed loading library associated with ICD JSON ";
|
||||
|
||||
/// How that message ends: the loader goes on without the manifest.
|
||||
const IGNORING: &str = ". Ignoring this JSON";
|
||||
|
||||
/// How the loader's message about a driver library that loaded and gave no `vkCreateInstance`
|
||||
/// begins (`loader_scanned_icd_add`): the library follows, and the message after it is
|
||||
/// [`ICD_SCAN_FAILED`]'s about the same library.
|
||||
const NO_CREATE_INSTANCE: &str = "loader_scanned_icd_add: Could not get 'vkCreateInstance' via \
|
||||
'vk_icdGetInstanceProcAddr' for ICD ";
|
||||
|
||||
/// How the loader's message about a library a driver manifest names that loaded and exports
|
||||
/// neither entry point a driver does begins (`loader_scanned_icd_add`): the library follows, then
|
||||
/// [`NO_ENTRY_POINT_END`]; the loader ignores the manifest with no other message.
|
||||
const NO_ENTRY_POINT: &str = "loader_scanned_icd_add: Attempt to retrieve either \
|
||||
'vkGetInstanceProcAddr' or 'vk_icdGetInstanceProcAddr' from ICD ";
|
||||
|
||||
/// How that message ends.
|
||||
const NO_ENTRY_POINT_END: &str = " failed.";
|
||||
|
||||
/// The loader's own reports, in one message list, of driver manifests it ignored: the libraries
|
||||
/// it said it ignored for failing to load them ([`ICD_SCAN_FAILED`]), which explain its messages
|
||||
/// about the same library alone.
|
||||
pub(crate) struct IgnoredDrivers(Vec<String>);
|
||||
|
||||
impl IgnoredDrivers {
|
||||
/// The libraries the loader said it ignored, among `messages`, each its id name and text.
|
||||
pub(crate) fn of<'a>(messages: impl IntoIterator<Item = (&'a str, &'a str)>) -> IgnoredDrivers {
|
||||
let libraries = (messages.into_iter())
|
||||
.filter(|&(id_name, _)| id_name == LOADER_MESSAGE)
|
||||
.filter_map(|(_, text)| {
|
||||
let library = text.strip_prefix(ICD_SCAN_FAILED)?;
|
||||
library
|
||||
.strip_suffix(IGNORING)
|
||||
.filter(|library| !library.is_empty())
|
||||
})
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
IgnoredDrivers(libraries)
|
||||
}
|
||||
|
||||
/// Whether a message with this id name and text is the loader's own report of a driver
|
||||
/// manifest it ignored, and nothing wider: its message that it ignored the library, the dynamic
|
||||
/// linker's error it forwards about that library (`<library>: <why>`), or its message that the
|
||||
/// library gave no `vkCreateInstance`; or its message that a library a manifest names is no
|
||||
/// driver, which names the library it ignored itself.
|
||||
pub(crate) fn explains(&self, id_name: &str, text: &str) -> bool {
|
||||
if id_name != LOADER_MESSAGE {
|
||||
return false;
|
||||
}
|
||||
let no_driver = (text.strip_prefix(NO_ENTRY_POINT))
|
||||
.and_then(|rest| rest.strip_suffix(NO_ENTRY_POINT_END))
|
||||
.is_some_and(|library| !library.is_empty());
|
||||
no_driver
|
||||
|| self.0.iter().any(|library| {
|
||||
let named = |prefix: &str, suffix: &str| {
|
||||
(text.strip_prefix(prefix))
|
||||
.and_then(|rest| rest.strip_suffix(suffix))
|
||||
.is_some_and(|named| named == library)
|
||||
};
|
||||
named(ICD_SCAN_FAILED, IGNORING)
|
||||
|| named(NO_CREATE_INSTANCE, "")
|
||||
|| (text.strip_prefix(library.as_str()))
|
||||
.is_some_and(|why| why.starts_with(": "))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::IgnoredDrivers;
|
||||
|
||||
/// The loader's messages about a driver manifest it ignored, as a host left them, each its id
|
||||
/// name and text: one whose library is missing (the dynamic linker's error, then the
|
||||
/// loader's), one whose library loaded and gave no `vkCreateInstance`, and one whose library
|
||||
/// is no driver.
|
||||
fn ignored_drivers() -> Vec<(&'static str, &'static str)> {
|
||||
[
|
||||
"/nonexistent/libstale_vulkan.so: cannot open shared object file: No such file or \
|
||||
directory",
|
||||
"loader_icd_scan: Failed loading library associated with ICD JSON \
|
||||
/nonexistent/libstale_vulkan.so. Ignoring this JSON",
|
||||
"loader_scanned_icd_add: Could not get 'vkCreateInstance' via \
|
||||
'vk_icdGetInstanceProcAddr' for ICD libGLX_nvidia.so.0",
|
||||
"loader_icd_scan: Failed loading library associated with ICD JSON libGLX_nvidia.so.0. \
|
||||
Ignoring this JSON",
|
||||
"loader_scanned_icd_add: Attempt to retrieve either 'vkGetInstanceProcAddr' or \
|
||||
'vk_icdGetInstanceProcAddr' from ICD /usr/lib/libz.so.1 failed.",
|
||||
]
|
||||
.map(|text| ("Loader Message", text))
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
/// The loader's reports of a driver manifest it ignored, each about the library it said it
|
||||
/// ignored, and nothing wider: the same words of another id name, a linker's error or a missing
|
||||
/// `vkCreateInstance` about a library it did not say it ignored, and its other messages.
|
||||
#[test]
|
||||
fn the_loader_s_reports_of_a_driver_manifest_it_ignored_are_matched_and_nothing_wider() {
|
||||
let reported = ignored_drivers();
|
||||
let ignored = IgnoredDrivers::of(reported.iter().copied());
|
||||
for &(id_name, text) in &reported {
|
||||
assert!(ignored.explains(id_name, text), "{text}");
|
||||
}
|
||||
for (id_name, text) in [
|
||||
// The same words from something that is not the loader.
|
||||
(
|
||||
"VUID-vkCreateInstance-None",
|
||||
"loader_icd_scan: Failed loading library associated with ICD JSON \
|
||||
/nonexistent/libstale_vulkan.so. Ignoring this JSON",
|
||||
),
|
||||
// A linker's error about a library the loader did not say it ignored.
|
||||
(
|
||||
"Loader Message",
|
||||
"/usr/lib/libvulkan_radeon.so: cannot open shared object file: No such file or \
|
||||
directory",
|
||||
),
|
||||
// No `vkCreateInstance` from a library the loader did not say it ignored.
|
||||
(
|
||||
"Loader Message",
|
||||
"loader_scanned_icd_add: Could not get 'vkCreateInstance' via \
|
||||
'vk_icdGetInstanceProcAddr' for ICD libvulkan_radeon.so",
|
||||
),
|
||||
// A manifest naming no library.
|
||||
(
|
||||
"Loader Message",
|
||||
"loader_icd_scan: Failed loading library associated with ICD JSON . Ignoring this \
|
||||
JSON",
|
||||
),
|
||||
// Another of the loader's messages.
|
||||
(
|
||||
"Loader Message",
|
||||
"terminator_CreateInstance: Failed to CreateInstance in ICD 0",
|
||||
),
|
||||
// The library named, in other words.
|
||||
(
|
||||
"Loader Message",
|
||||
"/nonexistent/libstale_vulkan.so was loaded",
|
||||
),
|
||||
] {
|
||||
assert!(!ignored.explains(id_name, text), "{id_name}: {text}");
|
||||
}
|
||||
// Without the loader's word that it ignored the library, its linker error and its missing
|
||||
// `vkCreateInstance` stand alone and fail.
|
||||
let alone = IgnoredDrivers::of(reported[..1].iter().copied());
|
||||
assert!(!alone.explains(reported[0].0, reported[0].1));
|
||||
assert!(!alone.explains(reported[2].0, reported[2].1));
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,6 @@
|
||||
use ash::vk;
|
||||
use metal2vulkan::device::ApiVersion;
|
||||
use metal2vulkan::device::{DeviceDescription, Independence};
|
||||
use metal2vulkan_runtime::{LayerSetting, LayerSettingValue};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeSet;
|
||||
use std::ffi::{c_char, CStr, CString};
|
||||
@@ -407,23 +406,6 @@ impl ProfilesSettings {
|
||||
Ok(ProfilesSettings { values })
|
||||
}
|
||||
|
||||
/// The settings as a runtime device's options take them (`DeviceOptions::layer_settings`),
|
||||
/// owned.
|
||||
pub(super) fn runtime_settings(&self) -> Vec<LayerSetting> {
|
||||
self.values
|
||||
.iter()
|
||||
.map(|(name, values)| {
|
||||
let value = match values {
|
||||
SettingValues::Bool(value) => LayerSettingValue::Bool(*value == vk::TRUE),
|
||||
SettingValues::Strings { owned, .. } => {
|
||||
LayerSettingValue::Strings(owned.clone())
|
||||
}
|
||||
};
|
||||
LayerSetting::new(PROFILES_LAYER.to_owned(), (*name).to_owned(), value)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The settings, pointing into `self`.
|
||||
pub(super) fn settings(&self) -> Vec<vk::LayerSettingEXT<'_>> {
|
||||
self.values
|
||||
@@ -439,9 +421,9 @@ impl ProfilesSettings {
|
||||
setting.value_count = 1;
|
||||
setting.p_values = std::ptr::from_ref(value).cast();
|
||||
}
|
||||
SettingValues::Strings { pointers, .. } => {
|
||||
SettingValues::Strings { owned, pointers } => {
|
||||
setting = setting.ty(vk::LayerSettingTypeEXT::STRING);
|
||||
setting.value_count = pointers.len() as u32;
|
||||
setting.value_count = owned.len() as u32;
|
||||
setting.p_values = pointers.as_ptr().cast();
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,599 +0,0 @@
|
||||
//! A case's indirect command buffers and pipeline states through the runtime, made and run as the
|
||||
//! Metal oracle makes and runs them (`metal::platform::indirect_commands`): a kernel's
|
||||
//! (`runtime_case::encoded_case`) and a draw's (`runtime_case::encoded_render`).
|
||||
//!
|
||||
//! Each authored command buffer is an `IndirectCommandBuffer` of the oracle's descriptor (compute
|
||||
//! commands' types from the authored dispatch kinds and their kernel buffer and
|
||||
//! threadgroup-length counts; render commands' `DRAW` and their vertex and fragment buffer
|
||||
//! counts; the authored inheritance), of the authored capacity, `Shared` where the host encodes
|
||||
//! commands and `Private` otherwise. Its argument-buffer field holds its `gpu_resource_id`, as the
|
||||
//! oracle's argument encoder writes it (`setIndirectCommandBuffer:atIndex:`), and a pipeline
|
||||
//! state's field the `gpu_resource_id` of the template's state, compute or render, made with
|
||||
//! `support_indirect_command_buffers` ([`CaseCommands::words`], [`TemplateState`]). The host's
|
||||
//! commands are encoded through their setters before the producer runs
|
||||
//! (`encode_host_commands`); the producer's encoder makes each command buffer resident for
|
||||
//! reading and writing. Once the producer completed, each command buffer's commands are read back
|
||||
//! as the runtime decodes them ([`CaseCommands::check_commands`], the host contract's check of what
|
||||
//! the producer wrote: a `Private` one through a blit copy into a `Shared` twin the producer's
|
||||
//! command buffer makes), and each command buffer the case executes runs in key order, each in a
|
||||
//! command buffer of its own committed after the one before it on the producer's queue
|
||||
//! ([`encoded_execution`]): compute commands in a compute encoder, render commands in a render
|
||||
//! encoder of the oracle's pass (its one attachment a 1x1 `R8Unorm` sink, neither loaded nor
|
||||
//! stored), with the parent's pipeline state and buffers, every case buffer and argument-buffer
|
||||
//! buffer resident for reading and writing, and `execute_commands_in_buffer` over the execution
|
||||
//! range.
|
||||
|
||||
use super::CaseError;
|
||||
use crate::case::indirect_commands::{
|
||||
metal_index_type, metal_primitive_type, CommandBufferResource, CommandDescriptor, HostAction,
|
||||
HostCommand,
|
||||
};
|
||||
use metal2vulkan::metal::{PixelFormat, RenderStages, ResourceUsage, TextureUsage};
|
||||
use metal2vulkan_runtime::{
|
||||
Buffer, CommandBuffer, CommandQueue, ComputePipelineState, Device, IndirectCommandBuffer,
|
||||
IndirectCommandBufferDescriptor, LoadAction, Region, RenderPassDescriptor, RenderPipelineState,
|
||||
ResourceId, ResourceOptions, ResourceRef, Size, StoreAction, TextureDescriptor,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The state of a pipeline template, made with `support_indirect_command_buffers`: a kernel's
|
||||
/// compute state, or a vertex or fragment case's render state.
|
||||
#[derive(Clone)]
|
||||
pub enum TemplateState {
|
||||
Compute(ComputePipelineState),
|
||||
Render(RenderPipelineState),
|
||||
}
|
||||
|
||||
impl TemplateState {
|
||||
/// What Metal's argument encoder writes at a pipeline state field for it.
|
||||
pub fn gpu_resource_id(&self) -> ResourceId {
|
||||
match self {
|
||||
TemplateState::Compute(state) => state.gpu_resource_id(),
|
||||
TemplateState::Render(state) => state.gpu_resource_id(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A case's indirect command buffers and the pipeline states its argument buffers hold, each by
|
||||
/// `(owner Metal index, field offset)`: a kernel's, or one stage's of a draw.
|
||||
#[derive(Default)]
|
||||
pub struct CaseCommands {
|
||||
/// Each command buffer.
|
||||
pub buffers: BTreeMap<(u32, u32), IndirectCommandBuffer>,
|
||||
/// The `Shared` twin of each `Private` command buffer, which the producer's command buffer
|
||||
/// copies it into after its dispatch or draw, so its commands read back
|
||||
/// ([`CaseCommands::check_commands`]).
|
||||
pub twins: BTreeMap<(u32, u32), IndirectCommandBuffer>,
|
||||
/// Each pipeline state an argument buffer holds: its token's template's state.
|
||||
pub states: BTreeMap<(u32, u32), TemplateState>,
|
||||
}
|
||||
|
||||
impl CaseCommands {
|
||||
/// `command_buffers` on `device`, as the oracle makes them, each with a twin where it is
|
||||
/// `Private`; no pipeline state (a caller sets [`CaseCommands::states`] from the templates it
|
||||
/// made, `pipeline_states`).
|
||||
pub fn of(
|
||||
device: &Device,
|
||||
command_buffers: &BTreeMap<(u32, u32), CommandBufferResource>,
|
||||
) -> Result<CaseCommands, CaseError> {
|
||||
let mut commands = CaseCommands::default();
|
||||
for (&key, resource) in command_buffers {
|
||||
let descriptor = descriptor(resource);
|
||||
let made = |options| {
|
||||
device
|
||||
.new_indirect_command_buffer(&descriptor, resource.capacity.into(), options)
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"command buffer {key:?}: new_indirect_command_buffer"
|
||||
)))
|
||||
};
|
||||
let options = if resource.commands.is_empty() {
|
||||
commands.twins.insert(key, made(ResourceOptions::shared())?);
|
||||
ResourceOptions::private()
|
||||
} else {
|
||||
ResourceOptions::shared()
|
||||
};
|
||||
commands.buffers.insert(key, made(options)?);
|
||||
}
|
||||
Ok(commands)
|
||||
}
|
||||
|
||||
/// The word each command buffer's and pipeline state's owner holds at its field, as Metal's
|
||||
/// argument encoder writes it: its `gpu_resource_id`.
|
||||
pub fn words(&self) -> impl Iterator<Item = ((u32, u32), u64)> + '_ {
|
||||
let buffers = self
|
||||
.buffers
|
||||
.iter()
|
||||
.map(|(&key, icb)| (key, icb.gpu_resource_id().0));
|
||||
let states = self
|
||||
.states
|
||||
.iter()
|
||||
.map(|(&key, state)| (key, state.gpu_resource_id().0));
|
||||
buffers.chain(states)
|
||||
}
|
||||
|
||||
/// Each command buffer, which the producer's encoder makes resident for reading and writing.
|
||||
pub fn resources(&self) -> impl Iterator<Item = ResourceRef<'_>> {
|
||||
self.buffers
|
||||
.values()
|
||||
.map(IndirectCommandBuffer::as_resource)
|
||||
}
|
||||
|
||||
/// The command buffer at `key`.
|
||||
fn buffer(&self, key: (u32, u32)) -> Result<&IndirectCommandBuffer, CaseError> {
|
||||
self.buffers
|
||||
.get(&key)
|
||||
.ok_or_else(|| format!("command buffer {key:?} was not made").into())
|
||||
}
|
||||
|
||||
/// Read back, once the producer completed, the commands of each command buffer as the runtime
|
||||
/// decodes them (a `Private` one's from its twin): the host contract's check of what the
|
||||
/// producer wrote, as the oracle's guard and the executor's decode check it.
|
||||
pub fn check_commands(&self) -> Result<(), CaseError> {
|
||||
for (key, icb) in &self.buffers {
|
||||
let readable = self.twins.get(key).unwrap_or(icb);
|
||||
readable
|
||||
.commands(0..readable.size())
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"command buffer {key:?}: commands"
|
||||
)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The pipeline state each of `objects`' fields (`(owner Metal index, field offset)` to token)
|
||||
/// holds: the state `templates` makes for its token, made with `support_indirect_command_buffers`.
|
||||
pub fn pipeline_states(
|
||||
objects: &BTreeMap<(u32, u32), u64>,
|
||||
templates: &BTreeMap<u64, TemplateState>,
|
||||
) -> Result<BTreeMap<(u32, u32), TemplateState>, CaseError> {
|
||||
objects
|
||||
.iter()
|
||||
.map(|(&key, token)| {
|
||||
let state = templates
|
||||
.get(token)
|
||||
.ok_or_else(|| format!("pipeline token {token} has no template"))?;
|
||||
Ok((key, state.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The runtime's descriptor of `resource`, as the oracle states its own
|
||||
/// (`metal::indirect_command_descriptor`): for compute commands no vertex or fragment buffers,
|
||||
/// the authored kernel counts, its command types the authored dispatch kinds; for render commands
|
||||
/// the authored draw kinds (`DRAW`, `DRAW_INDEXED`, `DRAW_PATCHES`, `DRAW_INDEXED_PATCHES`,
|
||||
/// `DRAW_MESH_THREADGROUPS`, `DRAW_MESH_THREADS`) and vertex, fragment, object and mesh buffer
|
||||
/// counts, no kernel buffers; and the authored inheritance.
|
||||
fn descriptor(resource: &CommandBufferResource) -> IndirectCommandBufferDescriptor {
|
||||
let mut descriptor = IndirectCommandBufferDescriptor::new();
|
||||
descriptor.command_types = resource.descriptor.command_types();
|
||||
match resource.descriptor {
|
||||
CommandDescriptor::Compute {
|
||||
max_buffer_bind_count,
|
||||
max_threadgroup_memory_bind_count,
|
||||
support_dynamic_attribute_stride,
|
||||
..
|
||||
} => {
|
||||
descriptor.max_kernel_buffer_bind_count = max_buffer_bind_count;
|
||||
descriptor.max_kernel_threadgroup_memory_bind_count = max_threadgroup_memory_bind_count;
|
||||
descriptor.support_dynamic_attribute_stride = support_dynamic_attribute_stride;
|
||||
}
|
||||
CommandDescriptor::Render {
|
||||
max_vertex_buffer_bind_count,
|
||||
max_fragment_buffer_bind_count,
|
||||
max_object_buffer_bind_count,
|
||||
max_mesh_buffer_bind_count,
|
||||
support_dynamic_attribute_stride,
|
||||
..
|
||||
} => {
|
||||
descriptor.max_vertex_buffer_bind_count = max_vertex_buffer_bind_count;
|
||||
descriptor.max_fragment_buffer_bind_count = max_fragment_buffer_bind_count;
|
||||
descriptor.max_object_buffer_bind_count = max_object_buffer_bind_count;
|
||||
descriptor.max_mesh_buffer_bind_count = max_mesh_buffer_bind_count;
|
||||
descriptor.support_dynamic_attribute_stride = support_dynamic_attribute_stride;
|
||||
}
|
||||
}
|
||||
descriptor.inherit_pipeline_state = resource.inherit_pipeline_state;
|
||||
descriptor.inherit_buffers = resource.inherit_buffers;
|
||||
descriptor
|
||||
}
|
||||
|
||||
/// The stages a render encoder makes the case's resources resident in for `resource`'s commands, as
|
||||
/// the oracle does: the vertex and fragment stages, and the object and mesh stages too where its
|
||||
/// descriptor allows mesh draws.
|
||||
fn render_stages(resource: &CommandBufferResource) -> RenderStages {
|
||||
let mesh = match resource.descriptor {
|
||||
CommandDescriptor::Render { draws, .. } => draws.mesh(),
|
||||
CommandDescriptor::Compute { .. } => false,
|
||||
};
|
||||
let stages = RenderStages::VERTEX | RenderStages::FRAGMENT;
|
||||
if mesh {
|
||||
stages | RenderStages::OBJECT | RenderStages::MESH
|
||||
} else {
|
||||
stages
|
||||
}
|
||||
}
|
||||
|
||||
/// The size of a grid or threadgroup.
|
||||
fn size([x, y, z]: [u32; 3]) -> Size {
|
||||
Size::new(x.into(), y.into(), z.into())
|
||||
}
|
||||
|
||||
/// The case's buffer `index` among `buffers`, which `what` binds.
|
||||
fn case_buffer<'a>(
|
||||
buffers: &'a BTreeMap<u32, Buffer>,
|
||||
index: u32,
|
||||
what: &str,
|
||||
) -> Result<&'a Buffer, CaseError> {
|
||||
buffers
|
||||
.get(&index)
|
||||
.ok_or_else(|| format!("{what} buffer {index} is not bound").into())
|
||||
}
|
||||
|
||||
/// The compute template state of `token` among `templates`.
|
||||
fn compute_template(
|
||||
templates: &BTreeMap<u64, TemplateState>,
|
||||
token: u64,
|
||||
) -> Result<&ComputePipelineState, CaseError> {
|
||||
match templates.get(&token) {
|
||||
Some(TemplateState::Compute(state)) => Ok(state),
|
||||
_ => Err(format!("pipeline token {token} has no compute template").into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The render template state of `token` among `templates`.
|
||||
fn render_template(
|
||||
templates: &BTreeMap<u64, TemplateState>,
|
||||
token: u64,
|
||||
) -> Result<&RenderPipelineState, CaseError> {
|
||||
match templates.get(&token) {
|
||||
Some(TemplateState::Render(state)) => Ok(state),
|
||||
_ => Err(format!("pipeline token {token} has no render template").into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode each host command of `command_buffers` (made as `commands`) through its setters, before
|
||||
/// the producer runs, as the oracle encodes them (`encode_host_commands`): its pipeline state (its
|
||||
/// token's template among `templates`), each buffer the case's buffer at its offset (among
|
||||
/// `buffers`), a compute command's threadgroup lengths, its dispatch or draw, and a compute
|
||||
/// command's barrier (the oracle models no render command's).
|
||||
pub fn encode_host_commands(
|
||||
command_buffers: &BTreeMap<(u32, u32), CommandBufferResource>,
|
||||
commands: &CaseCommands,
|
||||
buffers: &BTreeMap<u32, Buffer>,
|
||||
templates: &BTreeMap<u64, TemplateState>,
|
||||
) -> Result<(), CaseError> {
|
||||
for (&key, resource) in command_buffers {
|
||||
let icb = commands.buffer(key)?;
|
||||
for host in &resource.commands {
|
||||
let label = format!("command buffer {key:?} command {}", host.index);
|
||||
if resource.is_render() {
|
||||
encode_render_command(icb, host, &label, buffers, templates)?;
|
||||
} else {
|
||||
encode_compute_command(icb, host, &label, buffers, templates)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encode host command `host` of compute command buffer `icb` ([`encode_host_commands`]).
|
||||
fn encode_compute_command(
|
||||
icb: &IndirectCommandBuffer,
|
||||
host: &HostCommand,
|
||||
label: &str,
|
||||
buffers: &BTreeMap<u32, Buffer>,
|
||||
templates: &BTreeMap<u64, TemplateState>,
|
||||
) -> Result<(), CaseError> {
|
||||
let runtime = |call: &str| CaseError::runtime(format!("{label}: {call}"));
|
||||
let command = icb
|
||||
.indirect_compute_command_at(host.index.into())
|
||||
.map_err(runtime("indirect_compute_command_at"))?;
|
||||
if let Some(token) = host.pipeline {
|
||||
command
|
||||
.set_compute_pipeline_state(compute_template(templates, token)?)
|
||||
.map_err(runtime("set_compute_pipeline_state"))?;
|
||||
}
|
||||
for binding in &host.buffers {
|
||||
let buffer = case_buffer(buffers, binding.buffer, "a host command's")?;
|
||||
match binding.attribute_stride {
|
||||
Some(stride) => command
|
||||
.set_kernel_buffer_with_stride(
|
||||
Some(buffer),
|
||||
binding.offset.into(),
|
||||
stride.into(),
|
||||
binding.index,
|
||||
)
|
||||
.map_err(runtime("set_kernel_buffer_with_stride"))?,
|
||||
None => command
|
||||
.set_kernel_buffer(Some(buffer), binding.offset.into(), binding.index)
|
||||
.map_err(runtime("set_kernel_buffer"))?,
|
||||
}
|
||||
}
|
||||
if let Some(region) = host.stage_in_region {
|
||||
let [x, y, z] = region.origin.map(u64::from);
|
||||
let [width, height, depth] = region.size.map(u64::from);
|
||||
command
|
||||
.set_stage_in_region(Region::new_3d(x, y, z, width, height, depth))
|
||||
.map_err(runtime("set_stage_in_region"))?;
|
||||
}
|
||||
for memory in &host.threadgroup_memory_lengths {
|
||||
command
|
||||
.set_threadgroup_memory_length(memory.length, memory.index)
|
||||
.map_err(runtime("set_threadgroup_memory_length"))?;
|
||||
}
|
||||
match host.action {
|
||||
Some(HostAction::DispatchThreadgroups {
|
||||
grid,
|
||||
threads_per_threadgroup,
|
||||
}) => command
|
||||
.concurrent_dispatch_threadgroups(size(grid), size(threads_per_threadgroup))
|
||||
.map_err(runtime("concurrent_dispatch_threadgroups"))?,
|
||||
Some(HostAction::DispatchThreads {
|
||||
grid,
|
||||
threads_per_threadgroup,
|
||||
}) => command
|
||||
.concurrent_dispatch_threads(size(grid), size(threads_per_threadgroup))
|
||||
.map_err(runtime("concurrent_dispatch_threads"))?,
|
||||
Some(
|
||||
HostAction::DrawPrimitives { .. }
|
||||
| HostAction::DrawIndexedPrimitives { .. }
|
||||
| HostAction::DrawPatches { .. },
|
||||
) => return Err(format!("{label}: a compute command draws nothing").into()),
|
||||
None => {}
|
||||
}
|
||||
if host.barrier {
|
||||
command.set_barrier().map_err(runtime("set_barrier"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encode host command `host` of render command buffer `icb` ([`encode_host_commands`]): its
|
||||
/// render pipeline state, vertex and fragment buffers, and draw (of primitives, indexed from a
|
||||
/// case buffer at its offset, or of patches from case buffers at their offsets), as the oracle's
|
||||
/// `indirectRenderCommandAtIndex:` setters do.
|
||||
fn encode_render_command(
|
||||
icb: &IndirectCommandBuffer,
|
||||
host: &HostCommand,
|
||||
label: &str,
|
||||
buffers: &BTreeMap<u32, Buffer>,
|
||||
templates: &BTreeMap<u64, TemplateState>,
|
||||
) -> Result<(), CaseError> {
|
||||
let runtime = |call: &str| CaseError::runtime(format!("{label}: {call}"));
|
||||
let command = icb
|
||||
.indirect_render_command_at(host.index.into())
|
||||
.map_err(runtime("indirect_render_command_at"))?;
|
||||
if let Some(token) = host.pipeline {
|
||||
command
|
||||
.set_render_pipeline_state(render_template(templates, token)?)
|
||||
.map_err(runtime("set_render_pipeline_state"))?;
|
||||
}
|
||||
for binding in &host.vertex_buffers {
|
||||
let buffer = case_buffer(buffers, binding.buffer, "a host command's")?;
|
||||
match binding.attribute_stride {
|
||||
Some(stride) => command
|
||||
.set_vertex_buffer_with_stride(
|
||||
Some(buffer),
|
||||
binding.offset.into(),
|
||||
stride.into(),
|
||||
binding.index,
|
||||
)
|
||||
.map_err(runtime("set_vertex_buffer_with_stride"))?,
|
||||
None => command
|
||||
.set_vertex_buffer(Some(buffer), binding.offset.into(), binding.index)
|
||||
.map_err(runtime("set_vertex_buffer"))?,
|
||||
}
|
||||
}
|
||||
for binding in &host.fragment_buffers {
|
||||
command
|
||||
.set_fragment_buffer(
|
||||
Some(case_buffer(buffers, binding.buffer, "a host command's")?),
|
||||
binding.offset.into(),
|
||||
binding.index,
|
||||
)
|
||||
.map_err(runtime("set_fragment_buffer"))?;
|
||||
}
|
||||
match host.action {
|
||||
Some(HostAction::DrawPrimitives {
|
||||
primitive,
|
||||
vertex_start,
|
||||
vertex_count,
|
||||
instance_count,
|
||||
base_instance,
|
||||
}) => command
|
||||
.draw_primitives(
|
||||
metal_primitive_type(primitive),
|
||||
vertex_start.into(),
|
||||
vertex_count.into(),
|
||||
instance_count.into(),
|
||||
base_instance.into(),
|
||||
)
|
||||
.map_err(runtime("draw_primitives"))?,
|
||||
Some(HostAction::DrawIndexedPrimitives {
|
||||
primitive,
|
||||
index_count,
|
||||
index_type,
|
||||
index_buffer,
|
||||
index_buffer_offset,
|
||||
instance_count,
|
||||
base_vertex,
|
||||
base_instance,
|
||||
}) => command
|
||||
.draw_indexed_primitives(
|
||||
metal_primitive_type(primitive),
|
||||
index_count.into(),
|
||||
metal_index_type(index_type),
|
||||
case_buffer(buffers, index_buffer, "an indexed draw's index")?,
|
||||
index_buffer_offset.into(),
|
||||
instance_count.into(),
|
||||
base_vertex.into(),
|
||||
base_instance.into(),
|
||||
)
|
||||
.map_err(runtime("draw_indexed_primitives"))?,
|
||||
Some(HostAction::DrawPatches {
|
||||
control_points,
|
||||
patch_start,
|
||||
patch_count,
|
||||
patch_index_buffer,
|
||||
patch_index_buffer_offset,
|
||||
instance_count,
|
||||
base_instance,
|
||||
factor_buffer,
|
||||
factor_buffer_offset,
|
||||
factor_instance_stride,
|
||||
}) => command
|
||||
.draw_patches(
|
||||
control_points.into(),
|
||||
patch_start.into(),
|
||||
patch_count.into(),
|
||||
patch_index_buffer
|
||||
.map(|index| case_buffer(buffers, index, "a patch draw's patch index"))
|
||||
.transpose()?,
|
||||
patch_index_buffer_offset.into(),
|
||||
instance_count.into(),
|
||||
base_instance.into(),
|
||||
case_buffer(buffers, factor_buffer, "a patch draw's factor")?,
|
||||
factor_buffer_offset.into(),
|
||||
factor_instance_stride.into(),
|
||||
)
|
||||
.map_err(runtime("draw_patches"))?,
|
||||
Some(_) => return Err(format!("{label}: a render command dispatches nothing").into()),
|
||||
None => {}
|
||||
}
|
||||
if host.barrier {
|
||||
return Err(
|
||||
format!("{label}: a host-encoded render command's barrier is not modeled").into(),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encode on `command_buffer`, after the producer's dispatch or draw, the copy of each `Private`
|
||||
/// command buffer of `commands` into its `Shared` twin, so its commands read back once the
|
||||
/// producer completed ([`CaseCommands::check_commands`]).
|
||||
pub fn encode_twin_copies(
|
||||
command_buffer: &CommandBuffer,
|
||||
commands: &CaseCommands,
|
||||
) -> Result<(), CaseError> {
|
||||
if commands.twins.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut blit = command_buffer
|
||||
.blit_command_encoder()
|
||||
.map_err(CaseError::runtime("blit_command_encoder"))?;
|
||||
for (&key, twin) in &commands.twins {
|
||||
let icb = commands.buffer(key)?;
|
||||
blit.copy_indirect_command_buffer(icb, 0..icb.size(), twin, 0)
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"command buffer {key:?}: copy_indirect_command_buffer"
|
||||
)))?;
|
||||
}
|
||||
blit.end_encoding()
|
||||
.map_err(CaseError::runtime("end_encoding"))
|
||||
}
|
||||
|
||||
/// The case's command buffer at `key` that it executes (`resource`, whose `execute` is set, one of
|
||||
/// `commands`), encoded on a command buffer of `queue`, the producer's, and not committed, as the
|
||||
/// oracle runs it (`execute_host_commands`): a compute encoder for compute commands, and for render
|
||||
/// commands a render encoder of the oracle's pass, whose one attachment is a 1x1 `R8Unorm` sink
|
||||
/// neither loaded nor stored (`make_rasterization_sink`: the render templates draw nothing into
|
||||
/// it); the parent's pipeline state (its token's template among `templates`) and buffers (among
|
||||
/// `buffers`, the case's by Metal index), `resident` (every buffer of the case and every
|
||||
/// argument-buffer buffer) resident for reading and writing, in the vertex and fragment stages of
|
||||
/// a render encoder, and `execute_commands_in_buffer` over the execution range. Committed after
|
||||
/// the producer's command buffer, it runs once the producer completed, as the oracle's waits order
|
||||
/// it: the queue runs its command buffers in commit order, and commands the producer writes run
|
||||
/// once the work before them completed.
|
||||
pub fn encoded_execution(
|
||||
queue: &CommandQueue,
|
||||
(buffers, resident): (&BTreeMap<u32, Buffer>, &[ResourceRef<'_>]),
|
||||
commands: &CaseCommands,
|
||||
(key, resource): ((u32, u32), &CommandBufferResource),
|
||||
templates: &BTreeMap<u64, TemplateState>,
|
||||
) -> Result<CommandBuffer, CaseError> {
|
||||
let execution = resource
|
||||
.execute
|
||||
.as_ref()
|
||||
.ok_or_else(|| format!("command buffer {key:?} is not executed"))?;
|
||||
let icb = commands.buffer(key)?;
|
||||
let label = format!("command buffer {key:?}'s execution");
|
||||
let runtime = |call: &str| CaseError::runtime(format!("{label}: {call}"));
|
||||
let parent = |binding: &crate::case::indirect_commands::CommandBinding| {
|
||||
case_buffer(buffers, binding.buffer, "the parent's")
|
||||
};
|
||||
let command_buffer = queue.command_buffer().map_err(runtime("command_buffer"))?;
|
||||
let [start, end] = resource.execution_range;
|
||||
let range = u64::from(start)..u64::from(end);
|
||||
let usage = ResourceUsage::READ | ResourceUsage::WRITE;
|
||||
if resource.is_render() {
|
||||
let mut sink = TextureDescriptor::texture_2d(PixelFormat::R8Unorm, 1, 1, false);
|
||||
sink.usage = TextureUsage::RENDER_TARGET;
|
||||
sink.resource_options = ResourceOptions::shared();
|
||||
let sink = queue
|
||||
.device()
|
||||
.new_texture(&sink)
|
||||
.map_err(runtime("new_texture"))?;
|
||||
let mut pass = RenderPassDescriptor::new();
|
||||
let attachment = &mut pass.color_attachments[0];
|
||||
attachment.texture = Some(sink);
|
||||
attachment.load_action = LoadAction::DontCare;
|
||||
attachment.store_action = StoreAction::DontCare;
|
||||
let mut encoder = command_buffer
|
||||
.render_command_encoder(&pass)
|
||||
.map_err(runtime("render_command_encoder"))?;
|
||||
if let Some(parent) = &execution.pipeline {
|
||||
encoder
|
||||
.set_render_pipeline_state(render_template(templates, parent.token)?)
|
||||
.map_err(runtime("set_render_pipeline_state"))?;
|
||||
}
|
||||
for binding in &execution.vertex_buffers {
|
||||
encoder
|
||||
.set_vertex_buffer(Some(parent(binding)?), binding.offset.into(), binding.index)
|
||||
.map_err(runtime("set_vertex_buffer"))?;
|
||||
}
|
||||
for binding in &execution.fragment_buffers {
|
||||
encoder
|
||||
.set_fragment_buffer(Some(parent(binding)?), binding.offset.into(), binding.index)
|
||||
.map_err(runtime("set_fragment_buffer"))?;
|
||||
}
|
||||
for binding in &execution.object_buffers {
|
||||
encoder
|
||||
.set_object_buffer(Some(parent(binding)?), binding.offset.into(), binding.index)
|
||||
.map_err(runtime("set_object_buffer"))?;
|
||||
}
|
||||
for binding in &execution.mesh_buffers {
|
||||
encoder
|
||||
.set_mesh_buffer(Some(parent(binding)?), binding.offset.into(), binding.index)
|
||||
.map_err(runtime("set_mesh_buffer"))?;
|
||||
}
|
||||
encoder
|
||||
.use_resources(resident, usage, render_stages(resource))
|
||||
.map_err(runtime("use_resources"))?;
|
||||
encoder
|
||||
.execute_commands_in_buffer(icb, range)
|
||||
.map_err(runtime("execute_commands_in_buffer"))?;
|
||||
encoder.end_encoding().map_err(runtime("end_encoding"))?;
|
||||
} else {
|
||||
let mut encoder = command_buffer
|
||||
.compute_command_encoder()
|
||||
.map_err(runtime("compute_command_encoder"))?;
|
||||
if let Some(parent) = &execution.pipeline {
|
||||
encoder
|
||||
.set_compute_pipeline_state(compute_template(templates, parent.token)?)
|
||||
.map_err(runtime("set_compute_pipeline_state"))?;
|
||||
}
|
||||
for binding in &execution.buffers {
|
||||
encoder
|
||||
.set_buffer(Some(parent(binding)?), binding.offset.into(), binding.index)
|
||||
.map_err(runtime("set_buffer"))?;
|
||||
}
|
||||
encoder
|
||||
.use_resources(resident, usage)
|
||||
.map_err(runtime("use_resources"))?;
|
||||
encoder
|
||||
.execute_commands_in_buffer(icb, range)
|
||||
.map_err(runtime("execute_commands_in_buffer"))?;
|
||||
encoder.end_encoding().map_err(runtime("end_encoding"))?;
|
||||
}
|
||||
Ok(command_buffer)
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
//! The one validation-layer message a [`Messages`](super::Messages) sink lets pass: the layer's
|
||||
//! synchronization validation forgets a semaphore chain once the host waited on a timeline.
|
||||
//!
|
||||
//! The layer credits a host wait for a timeline semaphore (`vkGetSemaphoreCounterValue`, or a
|
||||
//! wait-all `vkWaitSemaphores`) only to the accesses of the queue that signalled it:
|
||||
//! `SyncValidator::WaitForSemaphore` calls `ApplyTaggedWait` with no queue sync tags, under
|
||||
//! "TODO: specify queue sync tags argument similar to WaitForFence" (Vulkan-ValidationLayers
|
||||
//! v1.4.357, commit e4786f7c, `layers/sync/sync_validation.cpp` line 280; v1.4.363, commit
|
||||
//! 2ea16de8, line 282, `WaitForSemaphore` and `ApplyTaggedWait` unchanged; still there in main
|
||||
//! 4f8ac9ce of 2026-10-05, line 282). That wait also drops the waited queue's writes from the
|
||||
//! batches a semaphore chain ran through. So when a batch on `VkQueue` A was ordered before a
|
||||
//! batch on B by a semaphore, the host read B's timeline past it, and A's next batch waits for
|
||||
//! B's, the layer finds A's earlier write ordered only by the barrier that ends A's batch for
|
||||
//! the host, and reports a `WRITE_AFTER_WRITE` between A's two batches. It prints that barrier
|
||||
//! as "allows 0", since the host's accesses are no queue's. Vulkan orders them through the
|
||||
//! chain, and the host's read orders them again.
|
||||
//!
|
||||
//! A standalone program shows it with no runtime code: two queues, three fills of one buffer,
|
||||
//! each command buffer ending with the barrier to the host the runtime's batches end with, the
|
||||
//! host waiting for the middle one (the RTX 5080 and the RTX 3090). Its control, the same chain
|
||||
//! without the host wait, gets no message.
|
||||
//!
|
||||
//! The runtime's queue waiters read the timelines while its scheduler submits, so on a
|
||||
//! device with several `VkQueue`s a lane test hits it at random: on the RTX 5080,
|
||||
//! `runtime_lane::exits::an_exit_while_submitting_is_clean` failed 4 to 12 runs in 30. A single
|
||||
//! `VkQueue` cannot hit it.
|
||||
//!
|
||||
//! [`shape`] matches that message and nothing wider. [`read`] keys the layer releases whose
|
||||
//! source was read with the TODO in place. On any other release, the message fails as before,
|
||||
//! marked "re-read WaitForSemaphore in layer X.Y.Z", so a fixed or changed layer is checked
|
||||
//! again rather than trusted.
|
||||
|
||||
use ash::vk;
|
||||
|
||||
/// `messageIdNumber` of `SYNC-HAZARD-WRITE-AFTER-WRITE`, as the layer hashes its name.
|
||||
const ID: i32 = 1544472022;
|
||||
|
||||
/// The id name of the hazard.
|
||||
const ID_NAME: &str = "SYNC-HAZARD-WRITE-AFTER-WRITE";
|
||||
|
||||
/// The call the layer reports the hazard at: a `vkQueueSubmit`, against a command buffer
|
||||
/// submitted earlier.
|
||||
const SUBMIT: &str = "vkQueueSubmit(): ";
|
||||
|
||||
/// The hazard, after the call, or after the command buffer's place in the submission where the
|
||||
/// layer names it (v1.4.363: `pSubmits[0].pCommandBuffers[1]`, `sync_submit.cpp` line 737,
|
||||
/// `submit_loc.dot(vvl::Field::pSubmits, batch_index)` then `.dot(vvl::Field::pCommandBuffers,
|
||||
/// index)`; v1.4.357 names none).
|
||||
const HAZARD: &str = "WRITE_AFTER_WRITE hazard detected. ";
|
||||
|
||||
/// What names the queue of the command buffer being submitted.
|
||||
const CURRENT_QUEUE: &str = " submitted on the current ";
|
||||
|
||||
/// What starts the earlier write.
|
||||
const PRIOR: &str = "which was previously written by another ";
|
||||
|
||||
/// What names the queue of the earlier write's command buffer.
|
||||
const PRIOR_QUEUE: &str = " submitted on ";
|
||||
|
||||
/// The earlier write's barriers: none a queue's access is in (`sync_reporting.cpp`,
|
||||
/// `FormatErrorMessage` and `FormatSyncAccesses`): the barrier for the host that ends a batch
|
||||
/// orders nothing later on a queue. A write with no barrier at all reads "No sufficient
|
||||
/// synchronization is present" instead, which no batch of the runtime's leaves.
|
||||
const NO_BARRIER: &str = "\nThe current synchronization allows 0, but to prevent this hazard";
|
||||
|
||||
/// The layer releases (`VkLayerProperties::specVersion` of `VK_LAYER_KHRONOS_validation`) whose
|
||||
/// `WaitForSemaphore` was read with the TODO in place: v1.4.357 (tag commit e4786f7c) and
|
||||
/// v1.4.363 (tag commit 2ea16de8), whose `WaitForSemaphore`, `ApplyTaggedWait` and the text the
|
||||
/// hazard's message is made of (`sync_error_messages.cpp`, `sync_reporting.cpp`,
|
||||
/// `FormatErrorMessage`) are those of v1.4.357.
|
||||
pub(super) const READ: &[u32] = &[
|
||||
vk::make_api_version(0, 1, 4, 357),
|
||||
vk::make_api_version(0, 1, 4, 363),
|
||||
];
|
||||
|
||||
/// Where the TODO is, for the line each message let pass prints.
|
||||
pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.357 (e4786f7c) \
|
||||
layers/sync/sync_validation.cpp:280 and v1.4.363 (2ea16de8) :282, \
|
||||
SyncValidator::WaitForSemaphore: \"TODO: specify queue \
|
||||
sync tags argument similar to WaitForFence\"";
|
||||
|
||||
/// Whether a message with this id, id name and text is the gap's: a `WRITE_AFTER_WRITE` found at
|
||||
/// a `vkQueueSubmit` against a write of a command buffer submitted earlier on the same
|
||||
/// `VkQueue`, which no barrier for a queue's later access ordered.
|
||||
pub(super) fn shape(id: i32, id_name: &str, text: &str) -> bool {
|
||||
if id != ID || id_name != ID_NAME {
|
||||
return false;
|
||||
}
|
||||
let Some(rest) = text.strip_prefix(SUBMIT) else {
|
||||
return false;
|
||||
};
|
||||
let Some(rest) = after_place(rest).strip_prefix(HAZARD) else {
|
||||
return false;
|
||||
};
|
||||
let Some(prior_at) = rest.find(PRIOR) else {
|
||||
return false;
|
||||
};
|
||||
let (current, prior) = rest.split_at(prior_at);
|
||||
let queue_after = |text: &str, marker: &str| -> Option<String> {
|
||||
let start = text.find(marker)? + marker.len();
|
||||
let end = start + text[start..].find(')')?;
|
||||
let queue = &text[start..end];
|
||||
queue.starts_with("VkQueue ").then(|| queue.to_owned())
|
||||
};
|
||||
let (Some(current_queue), Some(prior_queue)) = (
|
||||
queue_after(current, CURRENT_QUEUE),
|
||||
queue_after(prior, PRIOR_QUEUE),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
current_queue == prior_queue && prior.contains(NO_BARRIER)
|
||||
}
|
||||
|
||||
/// What follows a command buffer's place in a submission, `pSubmits[N].pCommandBuffers[M] `, that
|
||||
/// `text` begins with; `text` itself where it begins with none.
|
||||
fn after_place(text: &str) -> &str {
|
||||
let index = |text: &'static str, rest: &str| -> Option<usize> {
|
||||
let digits = rest.strip_prefix(text)?;
|
||||
let end = digits.find(|c: char| !c.is_ascii_digit())?;
|
||||
(end > 0 && digits[end..].starts_with(']')).then_some(text.len() + end + 1)
|
||||
};
|
||||
let Some(submit) = index("pSubmits[", text) else {
|
||||
return text;
|
||||
};
|
||||
let Some(buffer) = index(".pCommandBuffers[", &text[submit..]) else {
|
||||
return text;
|
||||
};
|
||||
text[submit + buffer..].strip_prefix(' ').unwrap_or(text)
|
||||
}
|
||||
|
||||
/// Whether the layer release `version` is one whose source was read with the gap in place.
|
||||
pub(super) fn read(version: u32) -> bool {
|
||||
READ.contains(&version)
|
||||
}
|
||||
|
||||
/// `version` as `X.Y.Z`.
|
||||
pub(super) fn release(version: u32) -> String {
|
||||
format!(
|
||||
"{}.{}.{}",
|
||||
vk::api_version_major(version),
|
||||
vk::api_version_minor(version),
|
||||
vk::api_version_patch(version)
|
||||
)
|
||||
}
|
||||
|
||||
/// The `specVersion` of the validation layer the loader `loader` (the system's default when
|
||||
/// `None`) offers; `None` when it cannot be read.
|
||||
pub(super) fn layer_version(loader: Option<&std::path::Path>) -> Option<u32> {
|
||||
// SAFETY: opening the loader library runs only its initializers.
|
||||
let entry = unsafe {
|
||||
match loader {
|
||||
Some(path) => ash::Entry::load_from(path),
|
||||
None => ash::Entry::load(),
|
||||
}
|
||||
}
|
||||
.ok()?;
|
||||
// SAFETY: a global command of a loaded entry, called with no instance.
|
||||
let layers = unsafe { entry.enumerate_instance_layer_properties() }.ok()?;
|
||||
layers
|
||||
.iter()
|
||||
.find(|layer| {
|
||||
layer
|
||||
.layer_name_as_c_str()
|
||||
.is_ok_and(|name| name == super::VALIDATION_LAYER)
|
||||
})
|
||||
.map(|layer| layer.spec_version)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The message the RTX 5080 reported (`runtime_lane::exits`, run 18).
|
||||
const SEEN: &str = "vkQueueSubmit(): WRITE_AFTER_WRITE hazard detected. vkCmdFillBuffer (from \
|
||||
VkCommandBuffer 0x7faa33f276b0 submitted on the current VkQueue 0x7faa30e9aab0) writes to \
|
||||
VkBuffer 0x1c000000001c, which was previously written by another vkCmdFillBuffer command \
|
||||
(from VkCommandBuffer 0x7faa33ebf730 submitted on VkQueue 0x7faa30e9aab0). \nThe current \
|
||||
synchronization allows 0, but to prevent this hazard, it must allow \
|
||||
VK_ACCESS_2_TRANSFER_WRITE_BIT accesses at VK_PIPELINE_STAGE_2_CLEAR_BIT.";
|
||||
|
||||
#[test]
|
||||
fn the_layer_s_message_is_the_gap() {
|
||||
assert!(shape(ID, ID_NAME, SEEN));
|
||||
// As v1.4.363 reports it: the command buffer's place in the submission after the call,
|
||||
// and the parameter before the resource.
|
||||
let placed = SEEN
|
||||
.replacen(
|
||||
"vkQueueSubmit(): ",
|
||||
"vkQueueSubmit(): pSubmits[0].pCommandBuffers[1] ",
|
||||
1,
|
||||
)
|
||||
.replacen("writes to VkBuffer", "writes to dstBuffer VkBuffer", 1);
|
||||
assert!(shape(ID, ID_NAME, &placed));
|
||||
// Another place, or a place the layer does not print so.
|
||||
let other = placed.replace(
|
||||
"pSubmits[0].pCommandBuffers[1]",
|
||||
"pSubmits[12].pCommandBuffers[3]",
|
||||
);
|
||||
assert!(shape(ID, ID_NAME, &other));
|
||||
for broken in [
|
||||
"pSubmits[].pCommandBuffers[1]",
|
||||
"pSubmits[0].pCommandBufferInfos[1]",
|
||||
"pSubmits[0]",
|
||||
] {
|
||||
let broken = placed.replace("pSubmits[0].pCommandBuffers[1]", broken);
|
||||
assert!(!shape(ID, ID_NAME, &broken), "{broken}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_hazard_is_not_the_gap() {
|
||||
let read_after_write = SEEN
|
||||
.replace("WRITE_AFTER_WRITE", "READ_AFTER_WRITE")
|
||||
.replace("writes to", "reads");
|
||||
assert!(!shape(
|
||||
-1,
|
||||
"SYNC-HAZARD-READ-AFTER-WRITE",
|
||||
&read_after_write
|
||||
));
|
||||
assert!(!shape(ID, "SYNC-HAZARD-READ-AFTER-WRITE", SEEN));
|
||||
assert!(!shape(-1, ID_NAME, SEEN));
|
||||
let write_after_read = "vkQueueSubmit(): WRITE_AFTER_READ hazard detected. \
|
||||
vkCmdFillBuffer (from VkCommandBuffer 0x2 submitted on the current VkQueue 0x1) \
|
||||
writes to VkBuffer 0x3, which was previously read by vkCmdCopyBuffer command (from \
|
||||
VkCommandBuffer 0x4 submitted on VkQueue 0x1). \nThe current synchronization defines \
|
||||
the destination stage mask as 0, but to prevent this hazard, it must include \
|
||||
VK_PIPELINE_STAGE_2_CLEAR_BIT.";
|
||||
assert!(!shape(ID, ID_NAME, write_after_read));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hazard_inside_one_command_buffer_is_not_the_gap() {
|
||||
let recorded = "vkCmdFillBuffer(): WRITE_AFTER_WRITE hazard detected. vkCmdFillBuffer \
|
||||
writes to VkBuffer 0x1c000000001c, which was previously written by another \
|
||||
vkCmdFillBuffer command. \nThe current synchronization allows 0, but to prevent this \
|
||||
hazard, it must allow VK_ACCESS_2_TRANSFER_WRITE_BIT accesses at \
|
||||
VK_PIPELINE_STAGE_2_CLEAR_BIT.";
|
||||
assert!(!shape(ID, ID_NAME, recorded));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_earlier_write_on_another_queue_is_not_the_gap() {
|
||||
let other = SEEN.replace(
|
||||
"submitted on VkQueue 0x7faa30e9aab0",
|
||||
"submitted on VkQueue 0x7faa30e9a000",
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &other));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_earlier_write_with_no_barrier_at_all_is_not_the_gap() {
|
||||
let start = SEEN.find("\nThe current").unwrap();
|
||||
let none = format!(
|
||||
"{}\nNo sufficient synchronization is present to ensure that a write \
|
||||
(VK_ACCESS_2_TRANSFER_WRITE_BIT) at VK_PIPELINE_STAGE_2_CLEAR_BIT does not conflict \
|
||||
with a prior write of the same type at the same stage.",
|
||||
&SEEN[..start]
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &none));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_earlier_write_with_a_barrier_is_not_the_gap() {
|
||||
let some = SEEN.replace(
|
||||
"allows 0,",
|
||||
"allows VK_ACCESS_2_TRANSFER_WRITE_BIT accesses at VK_PIPELINE_STAGE_2_COPY_BIT,",
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &some));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_releases_read_let_it_pass() {
|
||||
assert!(read(vk::make_api_version(0, 1, 4, 357)));
|
||||
assert!(read(vk::make_api_version(0, 1, 4, 363)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 4, 358)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 4, 364)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 4, 341)));
|
||||
assert_eq!(release(vk::make_api_version(0, 1, 4, 358)), "1.4.358");
|
||||
}
|
||||
}
|
||||
@@ -1,416 +0,0 @@
|
||||
//! A fragment case's explicit imageblock through the runtime: the Metal oracle's initializer and
|
||||
//! resolver, generated as AIR.
|
||||
//!
|
||||
//! The Metal oracle defines every cell of a fragment case's imageblock before the case's draw,
|
||||
//! and reads the selected member after it, with two helper fragment functions it compiles from
|
||||
//! MSL at run time (`metal::platform::imageblocks`), drawn in the case's pass with the case's
|
||||
//! vertex function, the pass's attachment formats and no color writes: its initializer writes each
|
||||
//! member of the master layout from its authored plane, and its resolver writes the selected
|
||||
//! member's plane into a buffer. The runtime compiles no MSL, so the runtime path draws the same
|
||||
//! two helpers generated as AIR ([`helpers_text`]) from the checked reflection's master, over the
|
||||
//! cells the executor's own context fills its storage with ([`Cells`]):
|
||||
//!
|
||||
//! - **The layout.** One struct of the master's members in declaration order, each of its
|
||||
//! reflected type (`half`, `half4`, `uchar4`, `ushort`, `float` or `uint`), whose natural offsets must
|
||||
//! be the reflected ones; its `air.struct_type_info` repeats the master's (each member's offset,
|
||||
//! size, type name, user key and raster order group), and its data size is the master's, so the
|
||||
//! product fingerprints it as the case's master (`FragmentImageblock::master`) and the runtime
|
||||
//! draws the helpers and the case in one pass. Its stated alignment is its largest member's.
|
||||
//! - **The initializer** reads pixel `(x, y)`'s cell from a buffer of the cells, at
|
||||
//! `(y * width + x) * cell_bytes` with each member at its offset, and returns it as its
|
||||
//! imageblock output, after the early fragment tests (so that link takes it beside a depth or
|
||||
//! stencil attachment; nothing is tested then, the encoder's state being Metal's default).
|
||||
//! - **The resolver** reads the cell as its imageblock input and writes each member into a buffer
|
||||
//! of cells laid out alike, whose selected member's plane is the output ([`Cells::select`]).
|
||||
//! The oracle's resolver writes only that plane: the bytes the output selects are the same.
|
||||
//!
|
||||
//! Both read the pixel from `[[position]]` (`air.convert` of its coordinates, as Metal's compiler
|
||||
//! spells `uint(position.x)`).
|
||||
|
||||
use super::{buffer_with, read_buffer, CaseError};
|
||||
use crate::air::reflect::FragmentImageblock;
|
||||
use crate::air_library::AirLibrary;
|
||||
use crate::candidate::engine::imageblock::Cells;
|
||||
use crate::case::FragmentImageblockFormat;
|
||||
use metal2vulkan::metal::{ColorWriteMask, PrimitiveType};
|
||||
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
|
||||
use metal2vulkan_runtime::{
|
||||
Buffer, Device, PipelineOptions, RenderCommandEncoder, RenderPassDescriptor,
|
||||
RenderPipelineState,
|
||||
};
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// The initializer's entry point.
|
||||
pub const INITIALIZE_ENTRY: &str = "metal2vulkan_imageblock_initialize";
|
||||
/// The resolver's entry point.
|
||||
pub const RESOLVE_ENTRY: &str = "metal2vulkan_imageblock_resolve";
|
||||
|
||||
const DATA_LAYOUT: &str = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-\
|
||||
f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-\
|
||||
v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32";
|
||||
const TRIPLE: &str = "air64_v28-apple-macosx26.0.0";
|
||||
/// The module's source name, so that two assemblies of the same helpers are the same bitcode.
|
||||
const SOURCE_FILENAME: &str = "metal2vulkan-imageblock-helpers";
|
||||
/// The struct of the master's members.
|
||||
const STRUCT: &str = "%struct.Metal2VulkanImageblock";
|
||||
|
||||
/// One member of the generated struct: its LLVM type, its natural alignment, and the alignment
|
||||
/// of its element, which each access to the cells' buffer states (a cell starts at a multiple of
|
||||
/// 4 bytes only).
|
||||
struct Field {
|
||||
ty: &'static str,
|
||||
align: u32,
|
||||
element: u32,
|
||||
}
|
||||
|
||||
/// The field of a member of `format`.
|
||||
fn field(format: FragmentImageblockFormat) -> Field {
|
||||
let (ty, align, element) = match format {
|
||||
FragmentImageblockFormat::Half => ("half", 2, 2),
|
||||
FragmentImageblockFormat::Half4 => ("<4 x half>", 8, 2),
|
||||
FragmentImageblockFormat::Uchar4 => ("<4 x i8>", 4, 1),
|
||||
FragmentImageblockFormat::Ushort => ("i16", 2, 2),
|
||||
FragmentImageblockFormat::Float => ("float", 4, 4),
|
||||
FragmentImageblockFormat::Uint => ("i32", 4, 4),
|
||||
};
|
||||
Field { ty, align, element }
|
||||
}
|
||||
|
||||
/// The AIR text (opaque pointers, for `llvm-as`) of the initializer and resolver of `master`, the
|
||||
/// checked reflection's master layout, over `cells` (their width and cell size), as the module
|
||||
/// docs state them. Refused: a member of a type the oracle's helpers do not take, and a master
|
||||
/// whose members do not lie at their natural offsets in declaration order.
|
||||
pub fn helpers_text(master: &FragmentImageblock, cells: &Cells) -> Result<String, String> {
|
||||
let mut fields = Vec::with_capacity(master.members.len());
|
||||
let mut end = 0u32;
|
||||
let mut alignment = 1u32;
|
||||
for member in &master.members {
|
||||
let format = FragmentImageblockFormat::from_air_type(&member.type_name, member.size)
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"imageblock member {} of type {} and size {}, which the helpers do not take",
|
||||
member.semantic, member.type_name, member.size
|
||||
)
|
||||
})?;
|
||||
let field = field(format);
|
||||
let at = end.next_multiple_of(field.align);
|
||||
if at != member.offset {
|
||||
return Err(format!(
|
||||
"imageblock member {} at {}, where a natural struct places it at {at}",
|
||||
member.semantic, member.offset
|
||||
));
|
||||
}
|
||||
end = at + member.size;
|
||||
alignment = alignment.max(field.align);
|
||||
fields.push((member, field));
|
||||
}
|
||||
if fields.is_empty() || end > cells.cell_bytes {
|
||||
return Err(format!(
|
||||
"an imageblock master of {} members ending at {end} over {}-byte cells",
|
||||
fields.len(),
|
||||
cells.cell_bytes
|
||||
));
|
||||
}
|
||||
let width = cells.dimensions[0];
|
||||
let cell_bytes = cells.cell_bytes;
|
||||
let types: Vec<&str> = fields.iter().map(|(_, field)| field.ty).collect();
|
||||
let mut text = format!(
|
||||
"; metal2vulkan generated imageblock helpers.\n\
|
||||
source_filename = \"{SOURCE_FILENAME}\"\n\
|
||||
target datalayout = \"{DATA_LAYOUT}\"\n\
|
||||
target triple = \"{TRIPLE}\"\n\n\
|
||||
{STRUCT} = type {{ {} }}\n\n",
|
||||
types.join(", ")
|
||||
);
|
||||
// The address of pixel `position`'s cell in the buffer `cells`.
|
||||
let address = |text: &mut String| {
|
||||
for line in [
|
||||
"%x = extractelement <4 x float> %position, i64 0".to_owned(),
|
||||
"%y = extractelement <4 x float> %position, i64 1".to_owned(),
|
||||
"%xi = tail call i32 @air.convert.u.i32.f.f32(float %x)".to_owned(),
|
||||
"%yi = tail call i32 @air.convert.u.i32.f.f32(float %y)".to_owned(),
|
||||
format!("%row = mul i32 %yi, {width}"),
|
||||
"%pixel = add i32 %row, %xi".to_owned(),
|
||||
format!("%start = mul i32 %pixel, {cell_bytes}"),
|
||||
"%start64 = zext i32 %start to i64".to_owned(),
|
||||
"%cell = getelementptr inbounds i8, ptr addrspace(1) %cells, i64 %start64".to_owned(),
|
||||
] {
|
||||
let _ = writeln!(text, " {line}");
|
||||
}
|
||||
for (index, (member, _)) in fields.iter().enumerate() {
|
||||
let _ = writeln!(
|
||||
text,
|
||||
" %p{index} = getelementptr inbounds i8, ptr addrspace(1) %cell, i64 {}",
|
||||
member.offset
|
||||
);
|
||||
}
|
||||
};
|
||||
let _ = writeln!(
|
||||
text,
|
||||
"define <{{ {STRUCT} }}> @{INITIALIZE_ENTRY}(<4 x float> noundef %position, \
|
||||
ptr addrspace(1) noundef readonly %cells) {{"
|
||||
);
|
||||
address(&mut text);
|
||||
let mut value = "poison".to_owned();
|
||||
for (index, (_, field)) in fields.iter().enumerate() {
|
||||
let _ = writeln!(
|
||||
text,
|
||||
" %v{index} = load {ty}, ptr addrspace(1) %p{index}, align {align}",
|
||||
ty = field.ty,
|
||||
align = field.element
|
||||
);
|
||||
let _ = writeln!(
|
||||
text,
|
||||
" %s{index} = insertvalue {STRUCT} {value}, {ty} %v{index}, {index}",
|
||||
ty = field.ty
|
||||
);
|
||||
value = format!("%s{index}");
|
||||
}
|
||||
let _ = writeln!(
|
||||
text,
|
||||
" %out = insertvalue <{{ {STRUCT} }}> undef, {STRUCT} {value}, 0\n \
|
||||
ret <{{ {STRUCT} }}> %out\n}}\n"
|
||||
);
|
||||
let _ = writeln!(
|
||||
text,
|
||||
"define void @{RESOLVE_ENTRY}({STRUCT} %data, <4 x float> noundef %position, \
|
||||
ptr addrspace(1) noundef %cells) {{"
|
||||
);
|
||||
address(&mut text);
|
||||
for (index, (_, field)) in fields.iter().enumerate() {
|
||||
let _ = writeln!(
|
||||
text,
|
||||
" %e{index} = extractvalue {STRUCT} %data, {index}\n \
|
||||
store {ty} %e{index}, ptr addrspace(1) %p{index}, align {align}",
|
||||
ty = field.ty,
|
||||
align = field.element
|
||||
);
|
||||
}
|
||||
text.push_str(" ret void\n}\n\ndeclare i32 @air.convert.u.i32.f.f32(float)\n\n");
|
||||
// The metadata: the master's layout, each entry's outputs and inputs, and the module's.
|
||||
let layout = fields
|
||||
.iter()
|
||||
.map(|(member, _)| {
|
||||
format!(
|
||||
"i32 {}, i32 {}, i32 0, !\"{}\", !\"{}\", !\"air.raster_order_group\", i32 {}",
|
||||
member.offset,
|
||||
member.size,
|
||||
member.type_name,
|
||||
member.semantic,
|
||||
member.raster_order_group
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let imageblock = format!(
|
||||
"!\"air.imageblock_data\", !\"air.imageblock_data_size\", i32 {}, \
|
||||
!\"air.struct_type_info\", !0, !\"air.arg_type_align_size\", i32 {alignment}, \
|
||||
!\"air.arg_type_name\", !\"Metal2VulkanImageblock\", !\"air.arg_name\", !\"data\"",
|
||||
master.sample_size
|
||||
);
|
||||
let position = |index: u32| {
|
||||
format!(
|
||||
"!{{i32 {index}, !\"air.position\", !\"air.center\", !\"air.no_perspective\", \
|
||||
!\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"position\"}}"
|
||||
)
|
||||
};
|
||||
let buffer = |index: u32, access: &str| {
|
||||
format!(
|
||||
"!{{i32 {index}, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, \
|
||||
!\"{access}\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 1, \
|
||||
!\"air.arg_type_align_size\", i32 1, !\"air.arg_type_name\", !\"uchar\", \
|
||||
!\"air.arg_name\", !\"cells\"}}"
|
||||
)
|
||||
};
|
||||
let nodes = [
|
||||
format!("!{{{layout}}}"),
|
||||
// The initializer: its output, its inputs, and its entry, after the early tests.
|
||||
format!("!{{!{{{imageblock}}}}}"),
|
||||
format!("!{{{}, {}}}", position(0), buffer(1, "air.read")),
|
||||
format!("!{{ptr @{INITIALIZE_ENTRY}, !1, !2, !\"early_fragment_tests\"}}"),
|
||||
// The resolver: no output, its inputs, and its entry.
|
||||
"!{}".to_owned(),
|
||||
format!(
|
||||
"!{{!{{i32 0, {imageblock}}}, {}, {}}}",
|
||||
position(1),
|
||||
buffer(2, "air.read_write")
|
||||
),
|
||||
format!("!{{ptr @{RESOLVE_ENTRY}, !4, !5}}"),
|
||||
"!{i32 7, !\"air.max_device_buffers\", i32 31}".to_owned(),
|
||||
"!{!\"air.compile.denorms_disable\"}".to_owned(),
|
||||
"!{!\"air.compile.fast_math_enable\"}".to_owned(),
|
||||
"!{!\"air.compile.framebuffer_fetch_enable\"}".to_owned(),
|
||||
"!{i32 2, i32 8, i32 0}".to_owned(),
|
||||
"!{!\"Metal\", i32 4, i32 0, i32 0}".to_owned(),
|
||||
];
|
||||
text.push_str(
|
||||
"!llvm.module.flags = !{!7}\n\
|
||||
!air.fragment = !{!3, !6}\n\
|
||||
!air.compile_options = !{!8, !9, !10}\n\
|
||||
!air.version = !{!11}\n\
|
||||
!air.language_version = !{!12}\n\n",
|
||||
);
|
||||
for (id, node) in nodes.iter().enumerate() {
|
||||
let _ = writeln!(text, "!{id} = {node}");
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// A fragment case's helpers on a device, as the Metal oracle draws them (the module docs): the
|
||||
/// initializer's state and the buffer of the cells it reads, and, where the case's output is an
|
||||
/// imageblock member, the resolver's state and the buffer it writes.
|
||||
pub(super) struct Helpers {
|
||||
initialize: RenderPipelineState,
|
||||
cells: Buffer,
|
||||
resolve: Option<(RenderPipelineState, Buffer)>,
|
||||
/// The cells' extent and cell size, which the resolver's buffer holds.
|
||||
dimensions: [u32; 2],
|
||||
cell_bytes: u32,
|
||||
}
|
||||
|
||||
impl Helpers {
|
||||
/// The helpers of `master` over `cells` on `device`, drawn with `case`'s vertex function and
|
||||
/// attachment formats (the case's descriptor), no color written; the resolver where
|
||||
/// `resolves`.
|
||||
pub(super) fn new(
|
||||
device: &Device,
|
||||
case: &RenderPipelineDescriptor,
|
||||
master: &FragmentImageblock,
|
||||
cells: &Cells,
|
||||
resolves: bool,
|
||||
) -> Result<Helpers, CaseError> {
|
||||
let text = helpers_text(master, cells)?;
|
||||
let bitcode = crate::check::loop_free::assemble(&text)?;
|
||||
let library = device
|
||||
.new_library_with_air(&bitcode)
|
||||
.map_err(CaseError::helper(
|
||||
"the imageblock helpers' new_library_with_air",
|
||||
))?;
|
||||
let state = |entry: &str| {
|
||||
let function = library
|
||||
.new_function_with_name(entry)
|
||||
.map_err(CaseError::helper(format!(
|
||||
"{entry}: new_function_with_name"
|
||||
)))?;
|
||||
let mut descriptor = RenderPipelineDescriptor::new(case.vertex.clone());
|
||||
descriptor.fragment = Some(StageSource::Function(function.function_descriptor()));
|
||||
for (helper, own) in descriptor
|
||||
.color_attachments
|
||||
.iter_mut()
|
||||
.zip(&case.color_attachments)
|
||||
{
|
||||
*helper = own.as_ref().map(|own| {
|
||||
let mut attachment = ColorAttachmentDescriptor::new(own.pixel_format);
|
||||
attachment.write_mask = ColorWriteMask::NONE;
|
||||
attachment
|
||||
});
|
||||
}
|
||||
descriptor.depth_format = case.depth_format;
|
||||
descriptor.stencil_format = case.stencil_format;
|
||||
device
|
||||
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
|
||||
.map_err(CaseError::helper(format!(
|
||||
"{entry}: new_render_pipeline_state"
|
||||
)))
|
||||
};
|
||||
let initialize = state(INITIALIZE_ENTRY)?;
|
||||
let resolve = if resolves {
|
||||
let resolved = buffer_with(device, &vec![0; cells.bytes.len()])?;
|
||||
Some((state(RESOLVE_ENTRY)?, resolved))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Helpers {
|
||||
initialize,
|
||||
cells: buffer_with(device, &cells.bytes)?,
|
||||
resolve,
|
||||
dimensions: cells.dimensions,
|
||||
cell_bytes: cells.cell_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Hold `pass` to the case's `pipeline` as the oracle does: its imageblock sample length the
|
||||
/// pipeline's, which each helper's must be ("generated and target fragment imageblock layouts
|
||||
/// disagree" otherwise), and a 16x16 tile.
|
||||
pub(super) fn prepare_pass(
|
||||
&self,
|
||||
pass: &mut RenderPassDescriptor,
|
||||
pipeline: &RenderPipelineState,
|
||||
) -> Result<(), CaseError> {
|
||||
let length = |state: &RenderPipelineState| {
|
||||
state
|
||||
.imageblock_sample_length()
|
||||
.map_err(CaseError::runtime("imageblock_sample_length"))
|
||||
};
|
||||
let sample_length = length(pipeline)?;
|
||||
let helpers =
|
||||
std::iter::once(&self.initialize).chain(self.resolve.as_ref().map(|(state, _)| state));
|
||||
for helper in helpers {
|
||||
let helper = length(helper)?;
|
||||
if helper != sample_length {
|
||||
return Err(format!(
|
||||
"generated and target fragment imageblock layouts disagree: the helper's \
|
||||
sample length is {helper}, the case's {sample_length}"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
pass.imageblock_sample_length = sample_length;
|
||||
pass.tile_width = 16;
|
||||
pass.tile_height = 16;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Draw the initializer: the fullscreen triangle of the case's vertex function, reading the
|
||||
/// cells at fragment buffer 0.
|
||||
pub(super) fn initialize(&self, encoder: &mut RenderCommandEncoder) -> Result<(), CaseError> {
|
||||
draw(encoder, &self.initialize, &self.cells)
|
||||
}
|
||||
|
||||
/// Draw the resolver, where the case has one, writing the cells at fragment buffer 0.
|
||||
pub(super) fn resolve(&self, encoder: &mut RenderCommandEncoder) -> Result<(), CaseError> {
|
||||
match &self.resolve {
|
||||
Some((state, resolved)) => draw(encoder, state, resolved),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The draws the helpers add to the case's, before it and after it.
|
||||
pub(super) fn draws(&self) -> (usize, usize) {
|
||||
(1, usize::from(self.resolve.is_some()))
|
||||
}
|
||||
|
||||
/// The cells the resolver wrote, once the command buffer completed.
|
||||
pub(super) fn resolved(&self) -> Result<Cells, CaseError> {
|
||||
let (_, buffer) = self
|
||||
.resolve
|
||||
.as_ref()
|
||||
.ok_or("an imageblock output without its resolver")?;
|
||||
Ok(Cells {
|
||||
dimensions: self.dimensions,
|
||||
cell_bytes: self.cell_bytes,
|
||||
bytes: read_buffer(buffer, 0, buffer.length())?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw `state`'s fullscreen triangle with `buffer` at fragment buffer 0.
|
||||
fn draw(
|
||||
encoder: &mut RenderCommandEncoder,
|
||||
state: &RenderPipelineState,
|
||||
buffer: &Buffer,
|
||||
) -> Result<(), CaseError> {
|
||||
encoder
|
||||
.set_render_pipeline_state(state)
|
||||
.map_err(CaseError::helper(
|
||||
"an imageblock helper's set_render_pipeline_state",
|
||||
))?;
|
||||
encoder
|
||||
.set_fragment_buffer(Some(buffer), 0, 0)
|
||||
.map_err(CaseError::helper(
|
||||
"an imageblock helper's set_fragment_buffer",
|
||||
))?;
|
||||
encoder
|
||||
.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)
|
||||
.map_err(CaseError::helper("an imageblock helper's draw_primitives"))
|
||||
}
|
||||
@@ -1,295 +0,0 @@
|
||||
//! A validation-layer gap a [`Messages`](super::Messages) sink lets pass: the layer's link-time
|
||||
//! check of a fragment shader's input attachments reads a pipeline made against a `VkRenderPass`
|
||||
//! as if it were made for dynamic rendering, and reports every input attachment it reads.
|
||||
//!
|
||||
//! `VUID-VkGraphicsPipelineCreateInfo-renderPass-09652` holds "If the pipeline is being created
|
||||
//! with fragment shader state and fragment output state, the value of renderPass is
|
||||
//! `VK_NULL_HANDLE`, and `VkRenderingInputAttachmentIndexInfo` is not included": it is a rule of
|
||||
//! dynamic rendering, where input attachment `i` is colour attachment `i`. In a subpass, input
|
||||
//! attachment `i` is `pInputAttachments[i]`, and the render pass is part of both states, so a
|
||||
//! pipeline linked from libraries made against one has it.
|
||||
//!
|
||||
//! In layer v1.4.357 (tag commit e4786f7c) the check runs only for dynamic rendering:
|
||||
//! `CoreChecks::ValidateShaderInputAttachment` (`layers/core_checks/cc_spirv.cpp` line 87) tests
|
||||
//! `rp_state->UsesDynamicRendering()` first. v1.4.363 (tag commit 2ea16de8) adds a second pass
|
||||
//! at link time, in `CoreChecks::ValidateInterfaceFragmentOutput`
|
||||
//! (`layers/core_checks/cc_shader_interface.cpp` line 221), for a pipeline that takes its
|
||||
//! fragment shader or fragment output state from a library, and that pass tests no such thing:
|
||||
//! it calls `ValidateShaderInputAttachmentDynamicRendering` with the libraries' render pass,
|
||||
//! whose `dynamic_pipeline_rendering_create_info` a `VkRenderPass` never sets
|
||||
//! (`layers/state_tracker/render_pass_state.cpp` lines 340 and 357), so it compares each index
|
||||
//! with a colour attachment count of 0. The layer's main branch adds the missing test in
|
||||
//! 65fdd118 of 2026-10-03, "layers: Fix 09652 false positive", after the v1.4.363 tag.
|
||||
//!
|
||||
//! The runtime makes every graphics pipeline against a `VkRenderPass`, and links one from
|
||||
//! libraries where the device enables `VK_EXT_graphics_pipeline_library` and links them fast
|
||||
//! (`runtime/src/pipeline/libraries.rs`), so on layer v1.4.363 every linked pipeline that fetches
|
||||
//! through an input attachment reports each one it reads (lavapipe links them). [`shape`]
|
||||
//! matches only the second pass's message, word for word but for its numbers: at the create
|
||||
//! info's location (the per-stage check reports at `pStages[i]`), against a count of 0. [`read`]
|
||||
//! keys the layer releases whose source was read with the gap in place. On any other release
|
||||
//! such a message fails, marked "re-read the link-time input attachment check in layer X.Y.Z",
|
||||
//! so a fixed or changed layer is checked again rather than trusted.
|
||||
|
||||
use ash::vk;
|
||||
|
||||
/// `messageIdNumber` of the valid usage, as the layer hashes its name.
|
||||
const ID: i32 = 454563899;
|
||||
|
||||
/// The id name of the valid usage.
|
||||
const ID_NAME: &str = "VUID-VkGraphicsPipelineCreateInfo-renderPass-09652";
|
||||
|
||||
/// The start of the message: the create info's location, the second pass's (`create_info_loc`).
|
||||
const CALL: &str = "vkCreateGraphicsPipelines(): pCreateInfos[";
|
||||
|
||||
/// What follows the create info's index: the fragment shader's input attachment
|
||||
/// (`DescribeInputAttachmentIndex`), its set and binding.
|
||||
const SHADER: &str = "] shader [VK_SHADER_STAGE_FRAGMENT_BIT] [Set ";
|
||||
|
||||
/// The end of the message's first line: compared with the colour attachment count a
|
||||
/// `VkRenderPass`'s state holds, 0.
|
||||
const COUNT: &str =
|
||||
" which is not less than VkPipelineRenderingCreateInfo::colorAttachmentCount (0)";
|
||||
|
||||
/// The rest of the message, after its first line, as layer v1.4.363 words it.
|
||||
const REST: &str = "If VkRenderingInputAttachmentIndexInfo is provided, the index can be set, \
|
||||
but without it, it uses the default index values.\nHint: If using Depth/Stencil attachments, \
|
||||
you should be omitting the input attachment index in the shader to access the depth/stencil \
|
||||
attachments.\nThe Vulkan spec states: If the pipeline is being created with fragment shader \
|
||||
state and fragment output state, the value of renderPass is VK_NULL_HANDLE, and \
|
||||
VkRenderingInputAttachmentIndexInfo is not included, the fragment shader must not contain any \
|
||||
input attachments with a InputAttachmentIndex greater than or equal to \
|
||||
VkPipelineRenderingCreateInfo::colorAttachmentCount \
|
||||
(https://docs.vulkan.org/spec/latest/chapters/pipelines.html\
|
||||
#VUID-VkGraphicsPipelineCreateInfo-renderPass-09652)";
|
||||
|
||||
/// The note the layer puts before a message it reports for the last time
|
||||
/// (`duplicate_message_limit`), around the count.
|
||||
const LAST_TIME: (&str, &str) = (
|
||||
"(Warning - This VUID has now been reported ",
|
||||
" times, which is the duplicate_message_limit value, this will be the last time reporting \
|
||||
it).\n",
|
||||
);
|
||||
|
||||
/// The layer releases (`VkLayerProperties::specVersion` of `VK_LAYER_KHRONOS_validation`) whose
|
||||
/// source was read with the gap in place: v1.4.363 (tag commit 2ea16de8).
|
||||
pub(super) const READ: &[u32] = &[vk::make_api_version(0, 1, 4, 363)];
|
||||
|
||||
/// Where the gap is, for the line each message let pass prints.
|
||||
pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.363 (2ea16de8) \
|
||||
layers/core_checks/cc_shader_interface.cpp:221, CoreChecks::ValidateInterfaceFragmentOutput: \
|
||||
the link-time input attachment pass does not test rp_state->UsesDynamicRendering() \
|
||||
(added in main 65fdd118, \"layers: Fix 09652 false positive\")";
|
||||
|
||||
/// Whether a message with this id, id name and text is the gap's: the link-time pass's report of
|
||||
/// a fragment shader's input attachment at the create info's location, against a colour
|
||||
/// attachment count of 0, word for word as layer v1.4.363 reports it but for its numbers.
|
||||
pub(super) fn shape(id: i32, id_name: &str, text: &str) -> bool {
|
||||
if id != ID || id_name != ID_NAME {
|
||||
return false;
|
||||
}
|
||||
// Before the message, nothing or the layer's last-time note.
|
||||
let text = match text.strip_prefix(LAST_TIME.0) {
|
||||
Some(note) => match number(note).and_then(|rest| rest.strip_prefix(LAST_TIME.1)) {
|
||||
Some(rest) => rest,
|
||||
None => return false,
|
||||
},
|
||||
None => text,
|
||||
};
|
||||
let Some((first, rest)) = text.split_once('\n') else {
|
||||
return false;
|
||||
};
|
||||
let Some(index) = first.strip_prefix(CALL).and_then(number) else {
|
||||
return false;
|
||||
};
|
||||
let Some(binding) = index.strip_prefix(SHADER).and_then(number) else {
|
||||
return false;
|
||||
};
|
||||
let Some(read) = binding
|
||||
.strip_prefix(", Binding ")
|
||||
.and_then(number)
|
||||
.and_then(|rest| rest.strip_prefix("] has an "))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
// The index the shader reads, or an array's element of one.
|
||||
let end = match read.strip_prefix("InputAttachmentIndex of ") {
|
||||
Some(rest) => number(rest),
|
||||
None => read
|
||||
.strip_prefix("effective InputAttachmentIndex of ")
|
||||
.and_then(number)
|
||||
.and_then(|rest| rest.strip_prefix(" (started at InputAttachmentIndex "))
|
||||
.and_then(number)
|
||||
.and_then(|rest| rest.strip_prefix(" plus index "))
|
||||
.and_then(number)
|
||||
.and_then(|rest| rest.strip_prefix(" into the array)")),
|
||||
};
|
||||
end == Some(COUNT) && rest == REST
|
||||
}
|
||||
|
||||
/// What follows the decimal digits `text` starts with; `None` without any.
|
||||
fn number(text: &str) -> Option<&str> {
|
||||
let digits = text.bytes().take_while(u8::is_ascii_digit).count();
|
||||
(digits > 0).then(|| &text[digits..])
|
||||
}
|
||||
|
||||
/// Whether the layer release `version` is one whose source was read with the gap in place.
|
||||
pub(super) fn read(version: u32) -> bool {
|
||||
READ.contains(&version)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The message as the lanes saw it on lavapipe (Mesa, LLVM 23.1.4) with the layer 1.4.363,
|
||||
/// word for word.
|
||||
fn seen() -> String {
|
||||
"vkCreateGraphicsPipelines(): pCreateInfos[0] shader [VK_SHADER_STAGE_FRAGMENT_BIT] \
|
||||
[Set 0, Binding 2] has an InputAttachmentIndex of 0 which is not less than \
|
||||
VkPipelineRenderingCreateInfo::colorAttachmentCount (0)\nIf \
|
||||
VkRenderingInputAttachmentIndexInfo is provided, the index can be set, but without it, \
|
||||
it uses the default index values.\nHint: If using Depth/Stencil attachments, you should \
|
||||
be omitting the input attachment index in the shader to access the depth/stencil \
|
||||
attachments.\nThe Vulkan spec states: If the pipeline is being created with fragment \
|
||||
shader state and fragment output state, the value of renderPass is VK_NULL_HANDLE, and \
|
||||
VkRenderingInputAttachmentIndexInfo is not included, the fragment shader must not \
|
||||
contain any input attachments with a InputAttachmentIndex greater than or equal to \
|
||||
VkPipelineRenderingCreateInfo::colorAttachmentCount \
|
||||
(https://docs.vulkan.org/spec/latest/chapters/pipelines.html\
|
||||
#VUID-VkGraphicsPipelineCreateInfo-renderPass-09652)"
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_link_time_report_of_an_input_attachment_is_the_gap() {
|
||||
assert!(shape(ID, ID_NAME, &seen()));
|
||||
let last = format!(
|
||||
"(Warning - This VUID has now been reported 10 times, which is the \
|
||||
duplicate_message_limit value, this will be the last time reporting it).\n{}",
|
||||
seen()
|
||||
);
|
||||
assert!(shape(ID, ID_NAME, &last));
|
||||
// Another create info, binding or index (an index the layer cannot resolve reads the
|
||||
// same), or an array's element.
|
||||
let other = seen()
|
||||
.replacen("pCreateInfos[0]", "pCreateInfos[12]", 1)
|
||||
.replacen(
|
||||
"Binding 2] has an InputAttachmentIndex of 0",
|
||||
"Binding 5] has an InputAttachmentIndex of 3",
|
||||
1,
|
||||
);
|
||||
assert!(shape(ID, ID_NAME, &other));
|
||||
let element = seen().replacen(
|
||||
"has an InputAttachmentIndex of 0",
|
||||
"has an effective InputAttachmentIndex of 1 (started at InputAttachmentIndex 0 plus \
|
||||
index 1 into the array)",
|
||||
1,
|
||||
);
|
||||
assert!(shape(ID, ID_NAME, &element));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_per_stage_check_and_a_real_colour_count_are_not_the_gap() {
|
||||
let text = seen();
|
||||
// The per-stage check, which runs only for dynamic rendering, reports at the stage.
|
||||
let stage = text.replacen(
|
||||
"pCreateInfos[0] shader",
|
||||
"pCreateInfos[0].pStages[1] shader",
|
||||
1,
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &stage), "at a stage");
|
||||
// A count of colour attachments a dynamic-rendering pipeline states.
|
||||
let counted = text.replacen(
|
||||
"colorAttachmentCount (0)\n",
|
||||
"colorAttachmentCount (2)\n",
|
||||
1,
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &counted), "a stated count");
|
||||
// Another call, stage, valid usage or message.
|
||||
let call = text.replacen("vkCreateGraphicsPipelines()", "vkCreateShadersEXT()", 1);
|
||||
assert!(!shape(ID, ID_NAME, &call), "another call");
|
||||
let vertex = text.replacen(
|
||||
"VK_SHADER_STAGE_FRAGMENT_BIT",
|
||||
"VK_SHADER_STAGE_VERTEX_BIT",
|
||||
1,
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &vertex), "another stage");
|
||||
assert!(!shape(
|
||||
ID,
|
||||
"VUID-VkGraphicsPipelineCreateInfo-renderPass-09531",
|
||||
&text
|
||||
));
|
||||
assert!(!shape(0, ID_NAME, &text));
|
||||
let unindexed = text.replacen("pCreateInfos[0]", "pCreateInfos[]", 1);
|
||||
assert!(!shape(ID, ID_NAME, &unindexed), "no index");
|
||||
let before = format!("Something else.\n{text}");
|
||||
assert!(!shape(ID, ID_NAME, &before), "another preface");
|
||||
let first = text.split_once('\n').unwrap().0.to_owned();
|
||||
assert!(!shape(ID, ID_NAME, &first), "the first line alone");
|
||||
let after = text.replacen("If VkRenderingInputAttachmentIndexInfo", "If something", 1);
|
||||
assert!(!shape(ID, ID_NAME, &after), "another second line");
|
||||
let longer = format!("{text} More.");
|
||||
assert!(!shape(ID, ID_NAME, &longer), "more after the message");
|
||||
let named = text.replacen("Binding 2]", "Binding 2, variable \"x\"]", 1);
|
||||
assert!(
|
||||
!shape(ID, ID_NAME, &named),
|
||||
"another descriptor's description"
|
||||
);
|
||||
let note = format!("{}{}{}", LAST_TIME.0, LAST_TIME.1, text);
|
||||
assert!(!shape(ID, ID_NAME, ¬e), "a note without its count");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_releases_read_pass() {
|
||||
assert!(read(vk::make_api_version(0, 1, 4, 363)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 4, 357)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 4, 364)));
|
||||
}
|
||||
|
||||
fn rust_sources(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
for entry in std::fs::read_dir(dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
rust_sources(&path, out);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The gap passes the message only because no pipeline the lanes validate is made for
|
||||
/// dynamic rendering, where the valid usage holds: neither the runtime nor this crate's
|
||||
/// executors name the structure such a pipeline is made with, or begin dynamic rendering.
|
||||
#[test]
|
||||
fn no_pipeline_here_is_made_for_dynamic_rendering() {
|
||||
let crates = metal2vulkan_devtools::workspace_dir().join("crates");
|
||||
let mut files = Vec::new();
|
||||
rust_sources(&crates.join("metal2vulkan-runtime/src"), &mut files);
|
||||
rust_sources(&crates.join("metal2vulkan-validation/src"), &mut files);
|
||||
assert!(files.len() > 100, "{} sources", files.len());
|
||||
let names = [
|
||||
concat!("PipelineRendering", "CreateInfo"),
|
||||
concat!("cmd_begin", "_rendering("),
|
||||
concat!("RenderingInfo", "::default()"),
|
||||
];
|
||||
// This module quotes the layer's message, which names the structure.
|
||||
let quoting =
|
||||
crates.join("metal2vulkan-validation/src/candidate/runtime_case/input_index_gap.rs");
|
||||
assert!(files.contains("ing));
|
||||
let found: Vec<String> = files
|
||||
.iter()
|
||||
.filter(|file| **file != quoting)
|
||||
.flat_map(|file| {
|
||||
let text = std::fs::read_to_string(file).unwrap();
|
||||
names
|
||||
.iter()
|
||||
.filter(|name| text.contains(**name))
|
||||
.map(|name| format!("{} names {name}", file.display()))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(found, Vec::<String>::new());
|
||||
}
|
||||
}
|
||||
@@ -1,801 +0,0 @@
|
||||
//! What a device validation makes through the runtime enabled of the instance layers it asked
|
||||
//! for, and what a claim that needs the validation layer therefore holds.
|
||||
//!
|
||||
//! A device opens although a layer its caller asked for is one the loader cannot provide: the
|
||||
//! runtime drops the whole layer list, creates the instance with none, and says as the device is
|
||||
//! made which layers it was made without ([`LAYERS_DROPPED`], an informational message, no degrade
|
||||
//! notice: the layers are diagnostics and nothing of Metal's answers differs). That is the right
|
||||
//! behaviour for a caller that asked for a device, and the wrong silence for a claim: a test that
|
||||
//! requires the validation layer to have reported nothing passes by reporting nothing at all.
|
||||
//!
|
||||
//! So the sink keeps that message instead of swallowing it ([`LayerFacts::heard`]), beside the
|
||||
//! layers its device asked for ([`LayerFacts::asked`]), and a layer-dependent claim is stated
|
||||
//! against the two ([`layer_reported_nothing`]): where the layer was enabled the claim holds over
|
||||
//! what the layer saw, and where it was dropped the claim says in its own output that it was not
|
||||
//! exercised here (`LANE-LAYER-ABSENT <test>`, and a count per message list as it goes), so an
|
||||
//! empty message list is never read as a clean run.
|
||||
//!
|
||||
//! The loader says so too, and first: it reports the layer it cannot provide through the messenger
|
||||
//! chained at `vkCreateInstance`, as an error of the general type, before the call answers
|
||||
//! `VK_ERROR_LAYER_NOT_PRESENT` ([`loader_layer_message`]). That message is the dropped layer and
|
||||
//! nothing else wrong, so it is held until the device says whether it was made without the layer
|
||||
//! ([`LayerFacts::hold`]): once the device says so, the held message passes with a line of its own,
|
||||
//! and where nothing says so it fails with the rest ([`LayerFacts::release`]). Without that, every
|
||||
//! claim on such a device fails on the loader's own message instead of running its own work.
|
||||
//!
|
||||
//! The decision is the instance's alone: the layers the device asked for, less those it announced
|
||||
//! it was made without. Never the host, the driver's name or an environment variable.
|
||||
//!
|
||||
//! The loader also reports, at `vkCreateInstance`, each driver manifest whose library it could not
|
||||
//! load, or that is no driver, and then ignores it ([`IgnoredDrivers`]): the host's listing of its
|
||||
//! drivers (a vendor's manifest left behind by a driver no longer installed is common), whatever
|
||||
//! the device does, and nothing it did. Those pass with a line of their own
|
||||
//! (`LANE-LOADER-DRIVER <test>`), each naming the library the loader said it ignored.
|
||||
|
||||
use super::Messages;
|
||||
use metal2vulkan_runtime::DebugMessage;
|
||||
use std::ffi::CString;
|
||||
|
||||
/// The id name the Vulkan loader gives the messages it reports itself.
|
||||
const LOADER_MESSAGE: &str = "Loader Message";
|
||||
|
||||
/// What the loader's message about a layer it cannot provide names: the check it failed, and what
|
||||
/// it found (`loader_validate_layers`, Vulkan-Loader `loader/loader.c`).
|
||||
const VALIDATE_LAYERS: &str = "loader_validate_layers";
|
||||
|
||||
/// The rest of that message: the layer is none the loader lists.
|
||||
const NOT_AVAILABLE: &str = "does not exist in the list of available layers";
|
||||
|
||||
/// Whether a message with this id name and text is the loader's own complaint about an instance
|
||||
/// layer it cannot provide, and nothing wider.
|
||||
pub(crate) fn loader_layer_message(id_name: &str, text: &str) -> bool {
|
||||
id_name == LOADER_MESSAGE && text.contains(VALIDATE_LAYERS) && text.contains(NOT_AVAILABLE)
|
||||
}
|
||||
|
||||
/// How the loader's message about a driver manifest whose library it could not load begins
|
||||
/// (`loader_icd_scan`, Vulkan-Loader `loader/loader.c`): the library the manifest names follows,
|
||||
/// then [`IGNORING`].
|
||||
const ICD_SCAN_FAILED: &str = "loader_icd_scan: Failed loading library associated with ICD JSON ";
|
||||
|
||||
/// How that message ends: the loader goes on without the manifest.
|
||||
const IGNORING: &str = ". Ignoring this JSON";
|
||||
|
||||
/// How the loader's message about a driver library that loaded and gave no `vkCreateInstance`
|
||||
/// begins (`loader_scanned_icd_add`): the library follows, and the message after it is
|
||||
/// [`ICD_SCAN_FAILED`]'s about the same library.
|
||||
const NO_CREATE_INSTANCE: &str = "loader_scanned_icd_add: Could not get 'vkCreateInstance' via \
|
||||
'vk_icdGetInstanceProcAddr' for ICD ";
|
||||
|
||||
/// How the loader's message about a library a driver manifest names that loaded and exports
|
||||
/// neither entry point a driver does begins (`loader_scanned_icd_add`): the library follows, then
|
||||
/// [`NO_ENTRY_POINT_END`]; the loader ignores the manifest with no other message.
|
||||
const NO_ENTRY_POINT: &str = "loader_scanned_icd_add: Attempt to retrieve either \
|
||||
'vkGetInstanceProcAddr' or 'vk_icdGetInstanceProcAddr' from ICD ";
|
||||
|
||||
/// How that message ends.
|
||||
const NO_ENTRY_POINT_END: &str = " failed.";
|
||||
|
||||
/// The loader's own reports, in one message list, of driver manifests it ignored: the libraries
|
||||
/// it said it ignored for failing to load them ([`ICD_SCAN_FAILED`]), which explain its messages
|
||||
/// about the same library alone.
|
||||
pub(crate) struct IgnoredDrivers(Vec<String>);
|
||||
|
||||
impl IgnoredDrivers {
|
||||
/// The libraries the loader said it ignored, among `messages`.
|
||||
pub(crate) fn of_messages(messages: &[DebugMessage]) -> IgnoredDrivers {
|
||||
IgnoredDrivers::of(
|
||||
(messages.iter()).map(|message| (message.id_name.as_str(), message.text.as_str())),
|
||||
)
|
||||
}
|
||||
|
||||
/// The libraries the loader said it ignored, among `messages`, each its id name and text.
|
||||
pub(crate) fn of<'a>(messages: impl IntoIterator<Item = (&'a str, &'a str)>) -> IgnoredDrivers {
|
||||
let libraries = (messages.into_iter())
|
||||
.filter(|&(id_name, _)| id_name == LOADER_MESSAGE)
|
||||
.filter_map(|(_, text)| {
|
||||
let library = text.strip_prefix(ICD_SCAN_FAILED)?;
|
||||
library
|
||||
.strip_suffix(IGNORING)
|
||||
.filter(|library| !library.is_empty())
|
||||
})
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
IgnoredDrivers(libraries)
|
||||
}
|
||||
|
||||
/// Whether a message with this id name and text is the loader's own report of a driver
|
||||
/// manifest it ignored, and nothing wider: its message that it ignored the library, the dynamic
|
||||
/// linker's error it forwards about that library (`<library>: <why>`), or its message that the
|
||||
/// library gave no `vkCreateInstance`; or its message that a library a manifest names is no
|
||||
/// driver, which names the library it ignored itself.
|
||||
pub(crate) fn explains(&self, id_name: &str, text: &str) -> bool {
|
||||
if id_name != LOADER_MESSAGE {
|
||||
return false;
|
||||
}
|
||||
let no_driver = (text.strip_prefix(NO_ENTRY_POINT))
|
||||
.and_then(|rest| rest.strip_suffix(NO_ENTRY_POINT_END))
|
||||
.is_some_and(|library| !library.is_empty());
|
||||
no_driver
|
||||
|| self.0.iter().any(|library| {
|
||||
let named = |prefix: &str, suffix: &str| {
|
||||
(text.strip_prefix(prefix))
|
||||
.and_then(|rest| rest.strip_suffix(suffix))
|
||||
.is_some_and(|named| named == library)
|
||||
};
|
||||
named(ICD_SCAN_FAILED, IGNORING)
|
||||
|| named(NO_CREATE_INSTANCE, "")
|
||||
|| (text.strip_prefix(library.as_str()))
|
||||
.is_some_and(|why| why.starts_with(": "))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// How the loader's message about an instance layer the host lists twice begins (two manifests of
|
||||
/// one layer name): it names the copy it removed, then the one it kept.
|
||||
#[cfg(test)]
|
||||
const REMOVING_LAYER: &str = "Removing layer ";
|
||||
|
||||
/// The rest of that message, between the two copies.
|
||||
#[cfg(test)]
|
||||
const DUPLICATE_OF: &str = " because it is a duplicate of ";
|
||||
|
||||
/// Whether a message with this id name and text is the loader's own warning that the host lists an
|
||||
/// instance layer twice, and which copy it removed: the host's listing of its layers, reported
|
||||
/// through the messenger chained at `vkCreateInstance` whichever layers a device asks for, and
|
||||
/// nothing a device said; nothing wider. The lane's sink fails on no warning of the general kind,
|
||||
/// so it reads this only where every message is checked (`runtime_lane::creation_heard_checked`).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn loader_duplicate_layer_message(id_name: &str, text: &str) -> bool {
|
||||
id_name == LOADER_MESSAGE && text.starts_with(REMOVING_LAYER) && text.contains(DUPLICATE_OF)
|
||||
}
|
||||
|
||||
/// The id name of the informational message a device sends as it is made where the loader could
|
||||
/// not provide the instance layers its caller asked for; the runtime's `device/create.rs` names it
|
||||
/// so.
|
||||
pub const LAYERS_DROPPED: &str = "metal2vulkan-instance-layers-dropped";
|
||||
|
||||
/// What the instance of the devices reporting to one message list enabled of the layers they asked
|
||||
/// for: the list asked for, and whether the loader could not provide it. The runtime drops the
|
||||
/// whole list on a miss and creates the instance with none, so the enabled set is either all of
|
||||
/// what was asked for or nothing.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct EnabledLayers {
|
||||
asked: Vec<CString>,
|
||||
dropped: bool,
|
||||
}
|
||||
|
||||
impl EnabledLayers {
|
||||
/// The instance layers the device asked for, in the order it asked for them.
|
||||
pub fn asked(&self) -> &[CString] {
|
||||
&self.asked
|
||||
}
|
||||
|
||||
/// The layers the instance enabled: those asked for, or none where the loader could not
|
||||
/// provide them.
|
||||
pub fn enabled(&self) -> &[CString] {
|
||||
match self.dropped {
|
||||
true => &[],
|
||||
false => &self.asked,
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers the loader could not provide, which the instance was created without.
|
||||
pub fn dropped(&self) -> &[CString] {
|
||||
match self.dropped {
|
||||
true => &self.asked,
|
||||
false => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the instance enabled `layer`.
|
||||
pub fn enabled_layer(&self, layer: &std::ffi::CStr) -> bool {
|
||||
self.enabled().iter().any(|name| name.as_c_str() == layer)
|
||||
}
|
||||
|
||||
/// Whether the instance enabled the validation layer, so that what it reported is evidence.
|
||||
pub fn validates(&self) -> bool {
|
||||
self.enabled_layer(super::VALIDATION_LAYER)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a claim that needs the validation layer holds, stated against what the instance enabled
|
||||
/// ([`layer_reported_nothing`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LayerClaim {
|
||||
/// The device enabled the validation layer, and it reported nothing: the claim holds over
|
||||
/// everything the layer checks.
|
||||
Held,
|
||||
/// The device asked for the validation layer and the loader could not provide it (the layers
|
||||
/// it was made without, as it announced them): there was nothing to report, so the claim was
|
||||
/// not exercised here. Printed as such, never a silent pass.
|
||||
NotExercised { dropped: Vec<String> },
|
||||
/// The device asked for no validation layer, so the claim is none of the layer's: a device a
|
||||
/// test makes without it, to time it.
|
||||
NoLayerAsked,
|
||||
}
|
||||
|
||||
impl LayerClaim {
|
||||
/// Whether the claim was exercised: the layer was there to report.
|
||||
pub fn exercised(&self) -> bool {
|
||||
matches!(self, LayerClaim::Held)
|
||||
}
|
||||
}
|
||||
|
||||
/// Require that the validation layer reported nothing of `claim` on the devices reporting to
|
||||
/// `messages`, and say what that holds.
|
||||
///
|
||||
/// Every message the layer reported fails here, as `assert_eq!(messages.take(), Vec::new())` did,
|
||||
/// and the messages are taken either way. What the claim then stands on is the instance's answer
|
||||
/// alone ([`EnabledLayers`]): [`LayerClaim::Held`] where the layer was enabled, else a claim that
|
||||
/// was not exercised, printed on stderr with the test's name.
|
||||
///
|
||||
/// For a claim no narrower than the layer's own silence, [`layer_reported_nothing_at_all`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Where the layer reported anything that fails a run.
|
||||
pub fn layer_reported_nothing(messages: &Messages, claim: &str) -> LayerClaim {
|
||||
stated(messages, claim, &format!("{claim}: "), LAYER)
|
||||
}
|
||||
|
||||
/// What a lane states where it names no claim narrower than the layer's own silence: that the
|
||||
/// validation layer reported nothing at all of the work the test did up to here. Named in the line
|
||||
/// a layerless device prints, where the test's own name says the rest ([`LayerFacts::claim`]).
|
||||
const NOTHING_AT_ALL: &str = "the validation layer reported nothing of the work so far";
|
||||
|
||||
/// Require that the validation layer reported nothing at all of the work the devices reporting to
|
||||
/// `messages` did, and say what that holds ([`layer_reported_nothing`] of the lane's widest
|
||||
/// claim).
|
||||
///
|
||||
/// The claim the lane states oftenest, and exactly what `assert!(messages.take().is_empty())`
|
||||
/// stated: whatever the layer checked of the work so far, it reported nothing of it. A test that
|
||||
/// holds something narrower names it ([`layer_reported_nothing`]); the claim's words change
|
||||
/// nothing of what fails, every message failing either way, and say which claim a layerless
|
||||
/// device could not exercise.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Where the layer reported anything that fails a run.
|
||||
pub fn layer_reported_nothing_at_all(messages: &Messages) -> LayerClaim {
|
||||
stated(messages, NOTHING_AT_ALL, "", LAYER)
|
||||
}
|
||||
|
||||
/// Require that the devices reporting to `messages` reported nothing of `claim` that fails, where
|
||||
/// they asked for no validation layer: a device a test makes without it, so that what reaches the
|
||||
/// list is the driver's own and the runtime's. The layer's absence takes nothing from such a
|
||||
/// claim, and the claim is [`LayerClaim::NoLayerAsked`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Where anything reported fails a run, and where such a device did ask for the validation layer:
|
||||
/// then the claim is the layer's after all, and [`layer_reported_nothing`] is how it is stated.
|
||||
pub fn nothing_reported_without_the_layer(messages: &Messages, claim: &str) -> LayerClaim {
|
||||
let asked = messages.enabled_layers();
|
||||
assert!(
|
||||
!asked
|
||||
.asked()
|
||||
.iter()
|
||||
.any(|name| name.as_c_str() == super::VALIDATION_LAYER),
|
||||
"{claim}: the device asked for the validation layer, so the claim is the layer's"
|
||||
);
|
||||
stated(messages, claim, &format!("{claim}: "), "the device")
|
||||
}
|
||||
|
||||
/// What a claim names as having reported nothing, where the validation layer is what would have.
|
||||
const LAYER: &str = "the validation layer";
|
||||
|
||||
/// Take what the devices reporting to `messages` reported, state `claim` against what their
|
||||
/// instance enabled, and fail on anything reported, the failure led by `lead` and naming
|
||||
/// `reporter` as what reported.
|
||||
fn stated(messages: &Messages, claim: &str, lead: &str, reporter: &str) -> LayerClaim {
|
||||
let reported = messages.take();
|
||||
let stated = messages.state_layer_claim(claim);
|
||||
assert!(
|
||||
reported.is_empty(),
|
||||
"{lead}{reporter} reported\n{reported:#?}"
|
||||
);
|
||||
stated
|
||||
}
|
||||
|
||||
/// What one message list knows of the layers of the devices reporting to it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(super) struct LayerFacts {
|
||||
/// The instance layers the device reporting here asked for, in order; empty until a device
|
||||
/// records them ([`LayerFacts::asked`]).
|
||||
asked: Vec<CString>,
|
||||
/// The text of [`LAYERS_DROPPED`], where such a device announced it was made without them.
|
||||
dropped: Option<String>,
|
||||
/// How many layer-dependent claims were stated here while the layers were dropped.
|
||||
unexercised: usize,
|
||||
/// Whether the absence was printed already, so one device's many claims print one line and a
|
||||
/// count.
|
||||
said: bool,
|
||||
/// The loader's own messages about a layer it cannot provide, held until the device says
|
||||
/// whether it was made without that layer ([`LayerFacts::hold`]).
|
||||
held: Vec<DebugMessage>,
|
||||
/// How many of them passed, the device having said so.
|
||||
passed: usize,
|
||||
}
|
||||
|
||||
/// The most of the loader's own messages one list holds: a flood is nothing it can explain.
|
||||
const MAX_HELD: usize = 8;
|
||||
|
||||
impl LayerFacts {
|
||||
/// A device reporting here asks for `layers`: what an earlier device of this list announced
|
||||
/// about its own layers is not the new one's.
|
||||
pub(super) fn asked(&mut self, layers: &[CString]) {
|
||||
self.asked = layers.to_vec();
|
||||
self.dropped = None;
|
||||
self.said = false;
|
||||
}
|
||||
|
||||
/// Take the message `id_name` with text `text` of the test `test`, where it is the one a
|
||||
/// device sends as it is made without the layers it asked for; whether it was taken.
|
||||
pub(super) fn heard(&mut self, test: &str, id_name: &str, text: &str) -> bool {
|
||||
if id_name != LAYERS_DROPPED {
|
||||
return false;
|
||||
}
|
||||
self.dropped = Some(text.to_owned());
|
||||
// The loader said the same thing first, about the same layers: the device's announcement
|
||||
// explains it, so it passes with a line of its own.
|
||||
for message in self.held.split_off(0) {
|
||||
self.passed += 1;
|
||||
eprintln!(
|
||||
"LANE-LAYER-ABSENT {}: passed, the loader's own message about the layer the \
|
||||
device was then made without: {} ({}): {}",
|
||||
test,
|
||||
message.id_name,
|
||||
message.id,
|
||||
message.text.replace('\n', " ")
|
||||
);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the loader's own complaint about a layer it cannot provide is held here rather
|
||||
/// than failed at once: only where this list's device asked for a layer at all (with none
|
||||
/// asked for, the loader's complaint is about nothing of ours), and only up to [`MAX_HELD`].
|
||||
pub(super) fn holds(&self) -> bool {
|
||||
!self.asked.is_empty() && self.held.len() < MAX_HELD
|
||||
}
|
||||
|
||||
/// Hold `message`, the loader's own complaint, until the device says whether it was made
|
||||
/// without that layer; whether it was held ([`LayerFacts::holds`]).
|
||||
pub(super) fn hold(&mut self, message: &DebugMessage) -> bool {
|
||||
if !self.holds() {
|
||||
return false;
|
||||
}
|
||||
self.held.push(message.clone());
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether a device of this list said it was made without the layers it asked for, which is
|
||||
/// what explains the loader's complaint.
|
||||
pub(super) fn explained(&self) -> bool {
|
||||
self.dropped.is_some()
|
||||
}
|
||||
|
||||
/// The held messages nothing explained, which fail with the rest: a loader that refused a
|
||||
/// layer where no device of this list says it was made without one.
|
||||
pub(super) fn release(&mut self) -> Vec<DebugMessage> {
|
||||
match self.explained() {
|
||||
true => Vec::new(),
|
||||
false => self.held.split_off(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the instance of the devices reporting here enabled of the layers they asked for.
|
||||
pub(super) fn enabled(&self) -> EnabledLayers {
|
||||
EnabledLayers {
|
||||
asked: self.asked.clone(),
|
||||
dropped: self.dropped.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of the message a device of this list sent as it was made without the layers it
|
||||
/// asked for.
|
||||
pub(super) fn dropped_message(&self) -> Option<&str> {
|
||||
self.dropped.as_deref()
|
||||
}
|
||||
|
||||
/// State `claim` of `test` against the layers the instance enabled, printing the first claim
|
||||
/// a layerless device cannot exercise.
|
||||
pub(super) fn claim(&mut self, test: &str, claim: &str) -> LayerClaim {
|
||||
let enabled = self.enabled();
|
||||
if enabled.validates() {
|
||||
return LayerClaim::Held;
|
||||
}
|
||||
let dropped: Vec<String> = enabled
|
||||
.dropped()
|
||||
.iter()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
if dropped.is_empty() {
|
||||
// A device that asked for no validation layer: the claim is none of the layer's.
|
||||
return LayerClaim::NoLayerAsked;
|
||||
}
|
||||
self.unexercised += 1;
|
||||
if !self.said {
|
||||
self.said = true;
|
||||
eprintln!(
|
||||
"LANE-LAYER-ABSENT {test}: the loader could not provide {}, so the validation \
|
||||
layer reported nothing at all; every claim of what it reported is not exercised \
|
||||
here. First: {claim}",
|
||||
dropped.join(", ")
|
||||
);
|
||||
}
|
||||
LayerClaim::NotExercised { dropped }
|
||||
}
|
||||
|
||||
/// The lines a message list prints as it goes: the claims no layer exercised, and the
|
||||
/// loader's own messages that the device's announcement explained.
|
||||
pub(super) fn report(&self, test: &str) {
|
||||
if self.unexercised != 0 {
|
||||
eprintln!(
|
||||
"LANE-LAYER-ABSENT count {test}: {} layer-dependent claim(s) stated with no \
|
||||
validation layer, so not exercised",
|
||||
self.unexercised
|
||||
);
|
||||
}
|
||||
if self.passed != 0 {
|
||||
eprintln!(
|
||||
"LANE-LAYER-ABSENT count {test}: {} message(s) of the loader's about the layer \
|
||||
the device was made without passed",
|
||||
self.passed
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
layer_reported_nothing, layer_reported_nothing_at_all, nothing_reported_without_the_layer,
|
||||
LayerClaim, LAYERS_DROPPED,
|
||||
};
|
||||
use crate::candidate::runtime_case::{Messages, VALIDATION_LAYER};
|
||||
use std::ffi::CString;
|
||||
|
||||
/// The message a device sends as it is made without the layers it asked for, as the runtime
|
||||
/// writes it (`device/create.rs`, `layers_dropped`): its id name is what the sink keys on, and
|
||||
/// the text is the device's own.
|
||||
fn dropped_message() -> String {
|
||||
format!(
|
||||
"metal2vulkan: the device on a device was made without the instance layer(s) {} \
|
||||
[{LAYERS_DROPPED}]",
|
||||
VALIDATION_LAYER.to_string_lossy()
|
||||
)
|
||||
}
|
||||
|
||||
/// A message list of a device that asked for the validation layer and was made without it,
|
||||
/// the loader having none to provide. Its own input: no device, no loader, no host.
|
||||
fn layerless() -> Messages {
|
||||
let messages = Messages::default();
|
||||
messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]);
|
||||
assert!(
|
||||
messages.heard_informational(LAYERS_DROPPED, &dropped_message()),
|
||||
"the sink keeps the message a device sends as it is made without its layers"
|
||||
);
|
||||
messages
|
||||
}
|
||||
|
||||
/// A claim of what the validation layer reported, stated on a list whose device was made
|
||||
/// without it, is not exercised: it names the layer that was dropped, and the message list is
|
||||
/// empty, so the claim the lane used to state (`messages.take() == Vec::new()`) passed on the
|
||||
/// same input. This test fails if [`layer_reported_nothing`] ever answers [`LayerClaim::Held`]
|
||||
/// with no layer present.
|
||||
#[test]
|
||||
fn a_claim_of_what_the_layer_reported_is_not_exercised_where_the_layer_was_dropped() {
|
||||
let messages = layerless();
|
||||
// What the instance enabled: nothing of what it asked for.
|
||||
let enabled = messages.enabled_layers();
|
||||
assert_eq!(enabled.asked(), [VALIDATION_LAYER.to_owned()]);
|
||||
assert_eq!(enabled.enabled(), [] as [CString; 0]);
|
||||
assert_eq!(enabled.dropped(), [VALIDATION_LAYER.to_owned()]);
|
||||
assert!(!enabled.validates());
|
||||
assert_eq!(messages.layers_dropped_message(), Some(dropped_message()));
|
||||
// The bad input the old claim passed on: nothing was reported, because nothing could be.
|
||||
assert_eq!(
|
||||
messages.take(),
|
||||
Vec::new(),
|
||||
"the layerless list reports nothing at all"
|
||||
);
|
||||
assert_eq!(
|
||||
layer_reported_nothing(&messages, "no Vulkan object leaked"),
|
||||
LayerClaim::NotExercised {
|
||||
dropped: vec![VALIDATION_LAYER.to_string_lossy().into_owned()],
|
||||
},
|
||||
"a claim with no layer present must say it was not exercised"
|
||||
);
|
||||
assert!(!layer_reported_nothing(&messages, "and again").exercised());
|
||||
}
|
||||
|
||||
/// The same claim on a list whose device enabled the layer it asked for holds: the layer was
|
||||
/// there to report, and reported nothing.
|
||||
#[test]
|
||||
fn a_claim_of_what_the_layer_reported_holds_where_the_layer_was_enabled() {
|
||||
let messages = Messages::default();
|
||||
messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]);
|
||||
let enabled = messages.enabled_layers();
|
||||
assert_eq!(enabled.enabled(), [VALIDATION_LAYER.to_owned()]);
|
||||
assert!(enabled.validates());
|
||||
assert_eq!(messages.layers_dropped_message(), None);
|
||||
let claim = layer_reported_nothing(&messages, "no Vulkan object leaked");
|
||||
assert_eq!(claim, LayerClaim::Held);
|
||||
assert!(claim.exercised());
|
||||
}
|
||||
|
||||
/// The widest claim, which no test names ([`layer_reported_nothing_at_all`], the one the lane
|
||||
/// states oftenest), is not exercised either where the layer was dropped: so the 300-odd lane
|
||||
/// sites that asserted `messages.take()` was empty and said no more now say so instead of
|
||||
/// passing on a list that could report nothing at all.
|
||||
#[test]
|
||||
fn the_widest_claim_is_not_exercised_where_the_layer_was_dropped() {
|
||||
let messages = layerless();
|
||||
assert_eq!(
|
||||
messages.take(),
|
||||
Vec::new(),
|
||||
"the layerless list reports nothing at all"
|
||||
);
|
||||
assert_eq!(
|
||||
layer_reported_nothing_at_all(&messages),
|
||||
LayerClaim::NotExercised {
|
||||
dropped: vec![VALIDATION_LAYER.to_string_lossy().into_owned()],
|
||||
},
|
||||
"the widest claim with no layer present must say it was not exercised"
|
||||
);
|
||||
assert!(!layer_reported_nothing_at_all(&messages).exercised());
|
||||
}
|
||||
|
||||
/// The same claim on a list whose device enabled the layer holds.
|
||||
#[test]
|
||||
fn the_widest_claim_holds_where_the_layer_was_enabled() {
|
||||
let messages = Messages::default();
|
||||
messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]);
|
||||
let claim = layer_reported_nothing_at_all(&messages);
|
||||
assert_eq!(claim, LayerClaim::Held);
|
||||
assert!(claim.exercised());
|
||||
}
|
||||
|
||||
/// A claim a test states of a device it made without the validation layer
|
||||
/// ([`nothing_reported_without_the_layer`]: the driver's own messages and the runtime's) is
|
||||
/// none of the layer's, and the layer's absence takes nothing from it.
|
||||
#[test]
|
||||
fn a_claim_of_what_a_layerless_device_reported_is_none_of_the_layer_s() {
|
||||
let messages = Messages::default();
|
||||
messages.device_asked_layers(&[]);
|
||||
assert_eq!(
|
||||
nothing_reported_without_the_layer(&messages, "nothing the driver said fails"),
|
||||
LayerClaim::NoLayerAsked
|
||||
);
|
||||
}
|
||||
|
||||
/// The same claim on a device that did ask for the validation layer fails: then what reaches
|
||||
/// the list is the layer's, and the claim is the layer's to state
|
||||
/// ([`layer_reported_nothing`]), so a test that stops clearing its device's layers cannot
|
||||
/// keep the weaker statement.
|
||||
#[test]
|
||||
#[should_panic(expected = "the device asked for the validation layer")]
|
||||
fn a_layerless_claim_on_a_device_that_asked_for_the_layer_fails() {
|
||||
let messages = Messages::default();
|
||||
messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]);
|
||||
nothing_reported_without_the_layer(&messages, "nothing the driver said fails");
|
||||
}
|
||||
|
||||
/// A device a test makes with no layer at all, to time it, states no claim of the layer's.
|
||||
#[test]
|
||||
fn a_device_that_asked_for_no_layer_states_no_claim_of_the_layer_s() {
|
||||
let messages = Messages::default();
|
||||
messages.device_asked_layers(&[]);
|
||||
assert!(!messages.enabled_layers().validates());
|
||||
let claim = layer_reported_nothing(&messages, "nothing of the layer's");
|
||||
assert_eq!(claim, LayerClaim::NoLayerAsked);
|
||||
assert!(!claim.exercised());
|
||||
}
|
||||
|
||||
/// A device made again on one list answers for itself: the layers an earlier device of the
|
||||
/// list was made without are not the new one's, which enabled every layer it asked for.
|
||||
#[test]
|
||||
fn a_later_device_on_one_list_answers_for_its_own_layers() {
|
||||
let messages = layerless();
|
||||
assert!(!messages.enabled_layers().validates());
|
||||
messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]);
|
||||
assert!(
|
||||
messages.enabled_layers().validates(),
|
||||
"the new device announced nothing, so it was made with the layer it asked for"
|
||||
);
|
||||
assert_eq!(messages.layers_dropped_message(), None);
|
||||
assert_eq!(
|
||||
layer_reported_nothing(&messages, "no Vulkan object leaked"),
|
||||
LayerClaim::Held
|
||||
);
|
||||
}
|
||||
|
||||
/// The loader's complaint is held only where this list's device asked for a layer, and it is
|
||||
/// explained only once a device said it was made without one: so a loader that refuses a
|
||||
/// layer no device accounts for still fails the run (`Messages::take` releases it).
|
||||
#[test]
|
||||
fn the_loader_s_message_is_held_for_a_device_that_asked_and_explained_by_its_answer() {
|
||||
use super::LayerFacts;
|
||||
let mut facts = LayerFacts::default();
|
||||
assert!(
|
||||
!facts.holds(),
|
||||
"with no layer asked for, the loader's complaint is about nothing of ours"
|
||||
);
|
||||
facts.asked(&[VALIDATION_LAYER.to_owned()]);
|
||||
assert!(
|
||||
facts.holds(),
|
||||
"a device that asked for a layer accounts for it"
|
||||
);
|
||||
assert!(
|
||||
!facts.explained(),
|
||||
"nothing explains it until a device says it was made without the layer"
|
||||
);
|
||||
assert!(facts.heard("a test", LAYERS_DROPPED, &dropped_message()));
|
||||
assert!(facts.explained());
|
||||
// A device made again asks afresh: its own answer explains its own loader messages.
|
||||
facts.asked(&[VALIDATION_LAYER.to_owned()]);
|
||||
assert!(!facts.explained());
|
||||
assert!(facts.release().is_empty(), "nothing was held");
|
||||
}
|
||||
|
||||
/// The loader's own complaint about the layer it cannot provide, and nothing wider.
|
||||
#[test]
|
||||
fn the_loader_s_message_about_a_layer_it_cannot_provide_is_matched_and_nothing_wider() {
|
||||
assert!(super::loader_layer_message(
|
||||
"Loader Message",
|
||||
"loader_validate_layers: Layer 0 does not exist in the list of available layers"
|
||||
));
|
||||
for (id_name, text) in [
|
||||
// Another of the loader's messages.
|
||||
(
|
||||
"Loader Message",
|
||||
"terminator_CreateInstance: Failed to CreateInstance in ICD 0",
|
||||
),
|
||||
// The same words from something that is not the loader.
|
||||
(
|
||||
"VUID-vkCreateInstance-ppEnabledLayerNames-01727",
|
||||
"loader_validate_layers: Layer 0 does not exist in the list of available layers",
|
||||
),
|
||||
// Half the words.
|
||||
("Loader Message", "loader_validate_layers: Layer 0 is fine"),
|
||||
] {
|
||||
assert!(
|
||||
!super::loader_layer_message(id_name, text),
|
||||
"{id_name}: {text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The loader's messages about a driver manifest it ignored, as a host left them, each its id
|
||||
/// name and text: one whose library is missing (the dynamic linker's error, then the
|
||||
/// loader's), one whose library loaded and gave no `vkCreateInstance`, and one whose library
|
||||
/// is no driver.
|
||||
fn ignored_drivers() -> Vec<(&'static str, &'static str)> {
|
||||
[
|
||||
"/nonexistent/libstale_vulkan.so: cannot open shared object file: No such file or \
|
||||
directory",
|
||||
"loader_icd_scan: Failed loading library associated with ICD JSON \
|
||||
/nonexistent/libstale_vulkan.so. Ignoring this JSON",
|
||||
"loader_scanned_icd_add: Could not get 'vkCreateInstance' via \
|
||||
'vk_icdGetInstanceProcAddr' for ICD libGLX_nvidia.so.0",
|
||||
"loader_icd_scan: Failed loading library associated with ICD JSON libGLX_nvidia.so.0. \
|
||||
Ignoring this JSON",
|
||||
"loader_scanned_icd_add: Attempt to retrieve either 'vkGetInstanceProcAddr' or \
|
||||
'vk_icdGetInstanceProcAddr' from ICD /usr/lib/libz.so.1 failed.",
|
||||
]
|
||||
.map(|text| ("Loader Message", text))
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
/// The loader's reports of a driver manifest it ignored, each about the library it said it
|
||||
/// ignored, and nothing wider: the same words of another id name, a linker's error or a missing
|
||||
/// `vkCreateInstance` about a library it did not say it ignored, and its other messages.
|
||||
#[test]
|
||||
fn the_loader_s_reports_of_a_driver_manifest_it_ignored_are_matched_and_nothing_wider() {
|
||||
let reported = ignored_drivers();
|
||||
let ignored = super::IgnoredDrivers::of(reported.iter().copied());
|
||||
for &(id_name, text) in &reported {
|
||||
assert!(ignored.explains(id_name, text), "{text}");
|
||||
}
|
||||
for (id_name, text) in [
|
||||
// The same words from something that is not the loader.
|
||||
(
|
||||
"VUID-vkCreateInstance-None",
|
||||
"loader_icd_scan: Failed loading library associated with ICD JSON \
|
||||
/nonexistent/libstale_vulkan.so. Ignoring this JSON",
|
||||
),
|
||||
// A linker's error about a library the loader did not say it ignored.
|
||||
(
|
||||
"Loader Message",
|
||||
"/usr/lib/libvulkan_radeon.so: cannot open shared object file: No such file or \
|
||||
directory",
|
||||
),
|
||||
// No `vkCreateInstance` from a library the loader did not say it ignored.
|
||||
(
|
||||
"Loader Message",
|
||||
"loader_scanned_icd_add: Could not get 'vkCreateInstance' via \
|
||||
'vk_icdGetInstanceProcAddr' for ICD libvulkan_radeon.so",
|
||||
),
|
||||
// A manifest naming no library.
|
||||
(
|
||||
"Loader Message",
|
||||
"loader_icd_scan: Failed loading library associated with ICD JSON . Ignoring this \
|
||||
JSON",
|
||||
),
|
||||
// Another of the loader's messages.
|
||||
(
|
||||
"Loader Message",
|
||||
"terminator_CreateInstance: Failed to CreateInstance in ICD 0",
|
||||
),
|
||||
// The library named, in other words.
|
||||
(
|
||||
"Loader Message",
|
||||
"/nonexistent/libstale_vulkan.so was loaded",
|
||||
),
|
||||
] {
|
||||
assert!(!ignored.explains(id_name, text), "{id_name}: {text}");
|
||||
}
|
||||
// Without the loader's word that it ignored the library, its linker error and its missing
|
||||
// `vkCreateInstance` stand alone and fail.
|
||||
let alone = super::IgnoredDrivers::of(reported[..1].iter().copied());
|
||||
assert!(!alone.explains(reported[0].0, reported[0].1));
|
||||
assert!(!alone.explains(reported[2].0, reported[2].1));
|
||||
}
|
||||
|
||||
/// The loader's warning that the host lists a layer twice, and nothing wider.
|
||||
#[test]
|
||||
fn the_loader_s_warning_about_a_layer_listed_twice_is_matched_and_nothing_wider() {
|
||||
assert!(super::loader_duplicate_layer_message(
|
||||
"Loader Message",
|
||||
"Removing layer VK_LAYER_KHRONOS_validation (/usr/share/vulkan/explicit_layer.d/\
|
||||
VkLayer_khronos_validation.json) because it is a duplicate of \
|
||||
VK_LAYER_KHRONOS_validation (/tmp/layers/VkLayer_khronos_validation.json)"
|
||||
));
|
||||
for (id_name, text) in [
|
||||
// The loader's message about a layer it cannot provide.
|
||||
(
|
||||
"Loader Message",
|
||||
"loader_validate_layers: Layer 0 does not exist in the list of available layers",
|
||||
),
|
||||
// The same words from something that is not the loader.
|
||||
(
|
||||
"VUID-vkCreateInstance-ppEnabledLayerNames-01727",
|
||||
"Removing layer VK_LAYER_A (a.json) because it is a duplicate of VK_LAYER_A (b.json)",
|
||||
),
|
||||
// Half the words.
|
||||
("Loader Message", "Removing layer VK_LAYER_A (a.json)"),
|
||||
// The words, not at the start.
|
||||
(
|
||||
"Loader Message",
|
||||
"Failed: Removing layer VK_LAYER_A (a.json) because it is a duplicate of \
|
||||
VK_LAYER_A (b.json)",
|
||||
),
|
||||
] {
|
||||
assert!(
|
||||
!super::loader_duplicate_layer_message(id_name, text),
|
||||
"{id_name}: {text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every other informational message is none of this list's layer facts: the sink keeps the
|
||||
/// one message and leaves the rest where they were.
|
||||
#[test]
|
||||
fn no_other_informational_message_is_taken_for_the_layers() {
|
||||
let messages = Messages::default();
|
||||
messages.device_asked_layers(&[VALIDATION_LAYER.to_owned()]);
|
||||
for id_name in [
|
||||
"metal2vulkan-driver-pipeline-cache-kept",
|
||||
"metal2vulkan-pipeline-creation",
|
||||
"",
|
||||
] {
|
||||
assert!(
|
||||
!messages.heard_informational(id_name, "a message"),
|
||||
"{id_name} is not the dropped-layer message"
|
||||
);
|
||||
}
|
||||
assert_eq!(messages.layers_dropped_message(), None);
|
||||
assert!(messages.enabled_layers().validates());
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
//! A validation-layer gap a [`Messages`](super::Messages) sink lets pass: the layer's check of
|
||||
//! `VUID-vkResetQueryPool-firstQuery-02741` reports a whole query pool in use where the spec
|
||||
//! speaks of the range reset.
|
||||
//!
|
||||
//! The valid usage reads: "Submitted commands that refer to the range specified by `firstQuery`
|
||||
//! and `queryCount` in `queryPool` must have completed execution" (`vkResetQueryPool`). The
|
||||
//! layer checks it so: for each query of the range, "if (query_state != QUERYSTATE_AVAILABLE &&
|
||||
//! query_state != QUERYSTATE_UNKNOWN)", it calls `ValidateObjectNotInUse(query_pool_state.get(),
|
||||
//! ...)`, under "Same idea as VUID-vkDestroyQueryPool-queryPool-00793" (Vulkan-ValidationLayers
|
||||
//! v1.4.363, tag commit 2ea16de8, and vulkan-sdk-1.4.363.1, 317cff06,
|
||||
//! `layers/core_checks/cc_query.cpp`, `CoreChecks::PreCallValidateResetQueryPool`). That reports
|
||||
//! the pool in use by any command buffer in flight that refers to any of its queries. A query
|
||||
//! whose command buffer completed stays out of the two states it accepts, so a reset of it while
|
||||
//! another range of the same pool is in flight is reported. Main later checks only a query still
|
||||
//! `QUERYSTATE_ENDED`, "only ENDED between the submission that wrote it and that submission
|
||||
//! completing (or its results being read)" (main of 2026-11-07); v1.4.357 has no check.
|
||||
//!
|
||||
//! The runtime's one host reset is a timestamp slot's (`runtime/src/gpu_time.rs`, `slot`): a
|
||||
//! slot's queries are reset as a command buffer takes it, and a slot is taken only once given
|
||||
//! back, after its last holding's command buffer completed and its timestamps were read, or was
|
||||
//! never submitted. Its pool holds other slots, which other command buffers in flight hold, so
|
||||
//! every lane that keeps two timed command buffers in flight at once meets the report: on
|
||||
//! lavapipe and on RADV (a Radeon 780M) with the layer 1.4.363,
|
||||
//! `runtime_lane::staging_batches::batches_after_one_that_waited_for_a_staging_copy_follow_its_wait`
|
||||
//! failed every run, and both `runtime_lane::replayed_frames` tests that keep a frame in flight
|
||||
//! failed some runs.
|
||||
//!
|
||||
//! [`shape`] matches that message for a `vkResetQueryPool` call and nothing wider; [`read`] keys
|
||||
//! the layer releases whose source was read with the whole-pool check in place. The message
|
||||
//! cannot tell the range's own use from another range's, so where it passes the reset is checked
|
||||
//! as by v1.4.357, which has no check. On any other release it fails, marked "re-read
|
||||
//! vkResetQueryPool in layer X.Y.Z", so a fixed or changed layer is checked again rather than
|
||||
//! trusted.
|
||||
|
||||
use ash::vk;
|
||||
|
||||
/// `messageIdNumber` of `VUID-vkResetQueryPool-firstQuery-02741`, as the layer hashes its name.
|
||||
const ID: i32 = 150880399;
|
||||
|
||||
/// The id name of the valid usage.
|
||||
const ID_NAME: &str = "VUID-vkResetQueryPool-firstQuery-02741";
|
||||
|
||||
/// The start of the message: the call, and the pool (`ValidateObjectNotInUse`).
|
||||
const CALL: &str = "vkResetQueryPool(): can't be called on VkQueryPool 0x";
|
||||
|
||||
/// What follows the pool: the command buffer in flight that holds it.
|
||||
const IN_USE: &str = " that is currently in use by VkCommandBuffer 0x";
|
||||
|
||||
/// The end of the message: the valid usage's text, as the layer 1.4.363 quotes it.
|
||||
const STATES: &str = "\nThe Vulkan spec states: Submitted commands that refer to the range \
|
||||
specified by firstQuery and queryCount in queryPool must have completed execution \
|
||||
(https://docs.vulkan.org/spec/latest/chapters/queries.html#VUID-vkResetQueryPool-firstQuery-02741)";
|
||||
|
||||
/// The note the layer puts before a message it reports for the last time
|
||||
/// (`duplicate_message_limit`).
|
||||
const LAST_TIME: &str = "(Warning - This VUID has now been reported ";
|
||||
|
||||
/// The end of that note.
|
||||
const LAST_TIME_END: &str = ", this will be the last time reporting it).\n";
|
||||
|
||||
/// The layer releases (`VkLayerProperties::specVersion` of `VK_LAYER_KHRONOS_validation`) whose
|
||||
/// `PreCallValidateResetQueryPool` was read with the whole-pool check in place: v1.4.363 (tag
|
||||
/// commits 2ea16de8 and, for vulkan-sdk-1.4.363.1, 317cff06).
|
||||
pub(super) const READ: &[u32] = &[vk::make_api_version(0, 1, 4, 363)];
|
||||
|
||||
/// Where the gap is, for the line each message let pass prints.
|
||||
pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.363 (2ea16de8; \
|
||||
vulkan-sdk-1.4.363.1, 317cff06) layers/core_checks/cc_query.cpp, \
|
||||
CoreChecks::PreCallValidateResetQueryPool: a query of the range neither AVAILABLE nor UNKNOWN \
|
||||
calls ValidateObjectNotInUse on the whole pool (\"Same idea as \
|
||||
VUID-vkDestroyQueryPool-queryPool-00793\")";
|
||||
|
||||
/// Whether a message with this id, id name and text is the gap's: `vkResetQueryPool` reported
|
||||
/// for a pool in use by a command buffer, with the valid usage's text, and nothing else.
|
||||
pub(super) fn shape(id: i32, id_name: &str, text: &str) -> bool {
|
||||
if id != ID || id_name != ID_NAME {
|
||||
return false;
|
||||
}
|
||||
let text = match text.strip_prefix(LAST_TIME) {
|
||||
Some(note) => match note.find(LAST_TIME_END) {
|
||||
Some(end) if !note[..end].contains('\n') => ¬e[end + LAST_TIME_END.len()..],
|
||||
_ => return false,
|
||||
},
|
||||
None => text,
|
||||
};
|
||||
let Some(rest) = text.strip_prefix(CALL) else {
|
||||
return false;
|
||||
};
|
||||
let Some(rest) = after_handle(rest).and_then(|rest| rest.strip_prefix(IN_USE)) else {
|
||||
return false;
|
||||
};
|
||||
after_handle(rest) == Some(STATES)
|
||||
}
|
||||
|
||||
/// What follows the hexadecimal digits a handle begins `text` with, and the object's debug name
|
||||
/// in brackets where the layer prints one; `None` without any digit.
|
||||
fn after_handle(text: &str) -> Option<&str> {
|
||||
let end = text
|
||||
.find(|c: char| !c.is_ascii_hexdigit())
|
||||
.unwrap_or(text.len());
|
||||
if end == 0 {
|
||||
return None;
|
||||
}
|
||||
let rest = &text[end..];
|
||||
match rest.strip_prefix('[') {
|
||||
Some(named) => {
|
||||
let close = named.find(']')?;
|
||||
(!named[..close].contains('\n')).then(|| &named[close + 1..])
|
||||
}
|
||||
None => Some(rest),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the layer release `version` is one whose source was read with the gap in place.
|
||||
pub(super) fn read(version: u32) -> bool {
|
||||
READ.contains(&version)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The message as the lanes saw it on lavapipe (Mesa 26.2.6, LLVM 23.1.4) and RADV with the
|
||||
/// layer 1.4.363.
|
||||
fn seen() -> String {
|
||||
format!(
|
||||
"vkResetQueryPool(): can't be called on VkQueryPool 0x340000000034 that is currently \
|
||||
in use by VkCommandBuffer 0x7f28f5e85630{STATES}"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_layer_s_report_of_a_pool_in_use_at_a_host_reset_is_the_gap() {
|
||||
assert!(shape(ID, ID_NAME, &seen()));
|
||||
let last = format!(
|
||||
"{LAST_TIME}10 times, which is the duplicate_message_limit value{LAST_TIME_END}{}",
|
||||
seen()
|
||||
);
|
||||
assert!(shape(ID, ID_NAME, &last));
|
||||
// A command buffer, or the pool, with a debug name.
|
||||
let named = seen().replace("0x7f28f5e85630", "0x7f28f5e85630[a label]");
|
||||
assert!(shape(ID, ID_NAME, &named), "a named command buffer");
|
||||
let pool = seen().replace("0x340000000034", "0x340000000034[timestamps]");
|
||||
assert!(shape(ID, ID_NAME, &pool), "a named pool");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_messages_are_not_the_gap() {
|
||||
let text = seen();
|
||||
assert!(!shape(0, ID_NAME, &text));
|
||||
assert!(!shape(ID, "VUID-vkResetQueryPool-firstQuery-09436", &text));
|
||||
// Another call, another object, another holder.
|
||||
let destroy = text.replacen("vkResetQueryPool(): ", "vkDestroyQueryPool(): ", 1);
|
||||
assert!(!shape(ID, ID_NAME, &destroy), "another call");
|
||||
let buffer = text.replace("VkQueryPool 0x", "VkBuffer 0x");
|
||||
assert!(!shape(ID, ID_NAME, &buffer), "another object");
|
||||
let queue = text.replace("VkCommandBuffer 0x", "VkQueue 0x");
|
||||
assert!(!shape(ID, ID_NAME, &queue), "another holder");
|
||||
// No handle, another valid usage's text, or more after it.
|
||||
let unhandled = text.replace("0x340000000034", "0x");
|
||||
assert!(!shape(ID, ID_NAME, &unhandled), "no handle");
|
||||
let other = text.replace("must have completed execution", "must not be in use");
|
||||
assert!(!shape(ID, ID_NAME, &other), "another text");
|
||||
let more = format!("{text}\nSomething else.");
|
||||
assert!(!shape(ID, ID_NAME, &more), "more after it");
|
||||
// Anything else before the call.
|
||||
let before = format!("Something else.\n{text}");
|
||||
assert!(!shape(ID, ID_NAME, &before), "another preface");
|
||||
let broken = format!("{LAST_TIME}10 times\nand more{LAST_TIME_END}{text}");
|
||||
assert!(!shape(ID, ID_NAME, &broken), "a note over two lines");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_releases_read_pass() {
|
||||
assert!(read(vk::make_api_version(0, 1, 4, 363)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 4, 357)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 4, 364)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 5, 0)));
|
||||
}
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
//! The third validation-layer gap a [`Messages`](super::Messages) sink lets pass: the layer's
|
||||
//! synchronization validation does not read rasterization-order attachment access, and reports
|
||||
//! an input attachment read that it orders as a hazard against an earlier draw's color write.
|
||||
//!
|
||||
//! A pipeline made with
|
||||
//! `VK_PIPELINE_COLOR_BLEND_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_ACCESS_BIT_EXT` "forms a
|
||||
//! framebuffer-local memory dependency for each fragment generated by draw commands for that
|
||||
//! pipeline": its first synchronization scope "includes the
|
||||
//! `VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT` pipeline stage executed by all previous
|
||||
//! fragments (as defined by primitive order) in the corresponding framebuffer regions including
|
||||
//! those generated by the same draw command", its second the fragment's
|
||||
//! `VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT`, and its access scopes "all writes to color
|
||||
//! attachments" and "all reads from input attachments" (the Framebuffer chapter,
|
||||
//! `VkPipelineColorBlendStateCreateFlagBits`). The layer's synchronization code never reads that
|
||||
//! flag: nothing in `layers/sync` names it, and `AccessState::DetectHazard` orders an input
|
||||
//! attachment read only after a load op, "Input attachment is ordered against load op but not
|
||||
//! against regular draws (requires subpass barrier)" (Vulkan-ValidationLayers v1.4.357, commit
|
||||
//! e4786f7c, `layers/sync/sync_access_state.cpp` line 115; the same line in v1.4.363, commit
|
||||
//! 2ea16de8; unchanged in main aea761f of 2026-10-18). So every fetch through an input attachment after an earlier draw wrote the pixel
|
||||
//! reports a `READ_AFTER_WRITE`.
|
||||
//!
|
||||
//! The runtime fetches through input attachments where the device has
|
||||
//! `rasterizationOrderColorAttachmentAccess` (`runtime/src/framebuffer_fetch.rs`), every pipeline
|
||||
//! of such a pass made with that flag, and names each such pipeline [`NAME`] where its instance
|
||||
//! reports messages (`runtime/src/pipeline/graphics.rs`, `RASTER_ORDER_PIPELINE`). [`shape`]
|
||||
//! matches exactly that hazard, an input attachment read at the fragment shader after a color
|
||||
//! attachment write by an earlier draw with no barrier between, and only when the pipeline it
|
||||
//! names bears that name; [`read`] keys the layer releases whose source was read with the gap in
|
||||
//! place. On any other release such a message fails, marked "re-read the input attachment
|
||||
//! ordering in layer X.Y.Z", so a fixed or changed layer is checked again rather than trusted.
|
||||
|
||||
use ash::vk;
|
||||
|
||||
/// `messageIdNumber` of `SYNC-HAZARD-READ-AFTER-WRITE`, as the layer hashes its name.
|
||||
const ID: i32 = -455515022;
|
||||
|
||||
/// The id name of the hazard.
|
||||
const ID_NAME: &str = "SYNC-HAZARD-READ-AFTER-WRITE";
|
||||
|
||||
/// What follows the draw command the layer reports at: a read of an image view by the fragment
|
||||
/// shader (`sync_reporting.cpp`, `FormatErrorMessage`, with `ImageDescriptorError`'s initiator).
|
||||
const HAZARD: &str = "(): READ_AFTER_WRITE hazard detected. Shader stage \
|
||||
VK_SHADER_STAGE_FRAGMENT_BIT reads VkImageView 0x";
|
||||
|
||||
/// What follows the image view: the earlier write's command.
|
||||
const PRIOR: &str = ", which was previously written by ";
|
||||
|
||||
/// What every draw command's name starts with.
|
||||
const DRAW: &str = "vkCmdDraw";
|
||||
|
||||
/// The descriptor the view is read through (`PrepareCommonDescriptorMessage`).
|
||||
const INPUT: &str = " (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)";
|
||||
|
||||
/// What names the bound pipeline, after the descriptor set.
|
||||
const PIPELINE: &str = ", VkPipeline 0x";
|
||||
|
||||
/// What follows the pipeline.
|
||||
const LAYOUT: &str = ", image layout ";
|
||||
|
||||
/// The end of the message: the read and the earlier write, with no barrier between them.
|
||||
const ACCESSES: &str = "No sufficient synchronization is present to ensure that a read \
|
||||
(VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT) at VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT does not \
|
||||
conflict with a prior write (VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT) at \
|
||||
VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT.";
|
||||
|
||||
/// The note the layer puts before a message it reports for the last time
|
||||
/// (`duplicate_message_limit`).
|
||||
const LAST_TIME: &str = "(Warning - This VUID has now been reported ";
|
||||
|
||||
/// The runtime's name for a pipeline made with the flag (`runtime/src/pipeline/graphics.rs`,
|
||||
/// `RASTER_ORDER_PIPELINE`), which the layer prints after the pipeline's handle.
|
||||
pub(super) const NAME: &str =
|
||||
"metal2vulkan: a pipeline reading its input attachments in rasterization order";
|
||||
|
||||
/// The layer releases (`VkLayerProperties::specVersion` of `VK_LAYER_KHRONOS_validation`) whose
|
||||
/// synchronization code was read with the gap in place: v1.4.357 (tag commit e4786f7c) and
|
||||
/// v1.4.363 (tag commit 2ea16de8). In v1.4.363 the descriptor check moved
|
||||
/// (`sync_command_buffer.cpp` line 589 to `sync_command.cpp` line 1335,
|
||||
/// `ShaderAccessCommand::ValidateImageShaderAccess`) with its test unchanged: an input attachment
|
||||
/// read is still found by `DetectAttachmentHazard` with `SyncOrdering::kRaster`, ordered by
|
||||
/// `AccessState::DetectHazard` only after a load op (line 115), and no file of `layers/sync`
|
||||
/// names the rasterization-order flags; the record-time message is made of the same text. What
|
||||
/// v1.4.363 adds, the same hazard reported again at a submission's replay ("Shader stage ... in
|
||||
/// vkCmdDraw... (from VkCommandBuffer ... submitted on the current VkQueue ...)"), is another
|
||||
/// message, which [`shape`] does not take.
|
||||
pub(super) const READ: &[u32] = &[
|
||||
vk::make_api_version(0, 1, 4, 357),
|
||||
vk::make_api_version(0, 1, 4, 363),
|
||||
];
|
||||
|
||||
/// Where the gap is, for the line each message let pass prints.
|
||||
pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.357 (e4786f7c) and v1.4.363 \
|
||||
(2ea16de8) layers/sync/sync_access_state.cpp:115, AccessState::DetectHazard: \"Input attachment is \
|
||||
ordered against load op but not against regular draws (requires subpass barrier).\"; \
|
||||
layers/sync never reads the rasterization-order attachment access flags";
|
||||
|
||||
/// Whether a message with this id, id name and text is the gap's: a `READ_AFTER_WRITE` found at
|
||||
/// a draw, the fragment shader's read of an input attachment after a color attachment write by
|
||||
/// an earlier draw, with no barrier between, through a pipeline the runtime named [`NAME`].
|
||||
pub(super) fn shape(id: i32, id_name: &str, text: &str) -> bool {
|
||||
if id != ID || id_name != ID_NAME {
|
||||
return false;
|
||||
}
|
||||
let Some(at) = text.find(HAZARD) else {
|
||||
return false;
|
||||
};
|
||||
// The draw command, alone on its line; before it, nothing or the layer's last-time note.
|
||||
let line = text[..at].rfind('\n').map_or(0, |end| end + 1);
|
||||
let command = &text[line..at];
|
||||
if !command.starts_with(DRAW) || !command.bytes().all(|b| b.is_ascii_alphanumeric()) {
|
||||
return false;
|
||||
}
|
||||
if line != 0 && !text.starts_with(LAST_TIME) {
|
||||
return false;
|
||||
}
|
||||
// The view, then the earlier write: a draw's (the same command's, "another" one).
|
||||
let Some(rest) = after_handle(&text[at + HAZARD.len()..]) else {
|
||||
return false;
|
||||
};
|
||||
let Some(rest) = rest.strip_prefix(PRIOR) else {
|
||||
return false;
|
||||
};
|
||||
let rest = rest.strip_prefix("another ").unwrap_or(rest);
|
||||
if !rest.starts_with(DRAW) {
|
||||
return false;
|
||||
}
|
||||
let Some(input_at) = rest.find(INPUT) else {
|
||||
return false;
|
||||
};
|
||||
let rest = &rest[input_at + INPUT.len()..];
|
||||
let Some(pipeline_at) = rest.find(PIPELINE) else {
|
||||
return false;
|
||||
};
|
||||
let Some(rest) = after_handle(&rest[pipeline_at + PIPELINE.len()..]) else {
|
||||
return false;
|
||||
};
|
||||
let named = format!("[{NAME}]{LAYOUT}");
|
||||
rest.starts_with(&named) && rest.trim_end().ends_with(ACCESSES)
|
||||
}
|
||||
|
||||
/// What follows the hexadecimal digits a handle begins `text` with; `None` without any.
|
||||
fn after_handle(text: &str) -> Option<&str> {
|
||||
let end = text
|
||||
.find(|c: char| !c.is_ascii_hexdigit())
|
||||
.unwrap_or(text.len());
|
||||
(end > 0).then(|| &text[end..])
|
||||
}
|
||||
|
||||
/// Whether the layer release `version` is one whose source was read with the gap in place.
|
||||
pub(super) fn read(version: u32) -> bool {
|
||||
READ.contains(&version)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The message as the lanes saw it on lavapipe (Mesa, LLVM 23.1.1) with the layer 1.4.357,
|
||||
/// the runtime's name after the pipeline's handle (the layer prints an object's debug name
|
||||
/// there).
|
||||
fn seen() -> String {
|
||||
format!(
|
||||
"vkCmdDraw(): READ_AFTER_WRITE hazard detected. Shader stage \
|
||||
VK_SHADER_STAGE_FRAGMENT_BIT reads VkImageView 0x3d000000003d, which was previously \
|
||||
written by another vkCmdDraw command. \nThe image is referenced by descriptor \
|
||||
binding 1 (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) from descriptor set 0 \
|
||||
(VkDescriptorSet 0x0), VkPipeline 0x370000000037[{NAME}], image layout \
|
||||
VK_IMAGE_LAYOUT_GENERAL.\nNo sufficient synchronization is present to ensure that a \
|
||||
read (VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT) at \
|
||||
VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT does not conflict with a prior write \
|
||||
(VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT) at \
|
||||
VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT."
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_layer_s_report_of_a_named_pipeline_s_input_attachment_read_is_the_gap() {
|
||||
assert!(shape(ID, ID_NAME, &seen()));
|
||||
// Reported for the last time, after the layer's note.
|
||||
let last = format!(
|
||||
"{LAST_TIME}10 times, which is the duplicate_message_limit value, this will be the \
|
||||
last time reporting it).\n{}",
|
||||
seen()
|
||||
);
|
||||
assert!(shape(ID, ID_NAME, &last));
|
||||
// Another draw command, at either end.
|
||||
let indexed = seen().replacen("vkCmdDraw(): ", "vkCmdDrawIndexed(): ", 1);
|
||||
let indexed = indexed.replace("another vkCmdDraw command", "vkCmdDraw");
|
||||
assert!(shape(ID, ID_NAME, &indexed));
|
||||
// Another binding, or an array element of one.
|
||||
let element = seen().replace(
|
||||
"binding 1 (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)",
|
||||
"binding 2 (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT), array element 1",
|
||||
);
|
||||
assert!(shape(ID, ID_NAME, &element));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pipeline_without_the_name_is_not_the_gap() {
|
||||
let text = seen();
|
||||
let unnamed = text.replace(&format!("[{NAME}]"), "");
|
||||
assert!(!shape(ID, ID_NAME, &unnamed), "unnamed");
|
||||
let other = text.replace(NAME, "another pipeline");
|
||||
assert!(!shape(ID, ID_NAME, &other), "another name");
|
||||
let wider = text.replace(NAME, &format!("{NAME} and more"));
|
||||
assert!(!shape(ID, ID_NAME, &wider), "a wider name");
|
||||
// The name on the view, the pipeline unnamed.
|
||||
let elsewhere = unnamed.replace(
|
||||
"VkImageView 0x3d000000003d",
|
||||
&format!("VkImageView 0x3d000000003d[{NAME}]"),
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &elsewhere), "the name on the view");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_hazards_are_not_the_gap() {
|
||||
let text = seen();
|
||||
assert!(!shape(1544472022, "SYNC-HAZARD-WRITE-AFTER-WRITE", &text));
|
||||
assert!(!shape(ID, "SYNC-HAZARD-WRITE-AFTER-READ", &text));
|
||||
assert!(!shape(0, ID_NAME, &text));
|
||||
// Another descriptor: a sampled image or a storage image.
|
||||
for kind in [
|
||||
"VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE",
|
||||
"VK_DESCRIPTOR_TYPE_STORAGE_IMAGE",
|
||||
"VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER",
|
||||
] {
|
||||
let other = text.replace("VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT", kind);
|
||||
assert!(!shape(ID, ID_NAME, &other), "{kind}");
|
||||
}
|
||||
// An earlier write by no draw: a load op, a store op, a clear, a copy.
|
||||
for prior in [
|
||||
"at the beginning of subpass 0 (vkCmdBeginRenderPass) by the attachment loadOp",
|
||||
"at the end of the render pass instance (vkCmdEndRenderPass) by the attachment storeOp",
|
||||
"by vkCmdClearAttachments",
|
||||
"by vkCmdCopyBufferToImage",
|
||||
] {
|
||||
let other = text.replace("by another vkCmdDraw command", prior);
|
||||
assert!(!shape(ID, ID_NAME, &other), "{prior}");
|
||||
}
|
||||
// Another read or write, or a barrier that orders part of them.
|
||||
let storage = text.replace(
|
||||
"a prior write (VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT) at \
|
||||
VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT",
|
||||
"a prior write (VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT) at \
|
||||
VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT",
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &storage), "a storage write");
|
||||
let sampled = text.replace(
|
||||
"a read (VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT)",
|
||||
"a read (VK_ACCESS_2_SHADER_SAMPLED_READ_BIT)",
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &sampled), "a sampled read");
|
||||
let at = text.find("No sufficient").unwrap();
|
||||
let partial = format!(
|
||||
"{}The current synchronization allows COLOR_ATTACHMENT_WRITE accesses at \
|
||||
COLOR_ATTACHMENT_OUTPUT, but to prevent this hazard, it must allow \
|
||||
VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT accesses at \
|
||||
VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT.",
|
||||
&text[..at]
|
||||
);
|
||||
assert!(!shape(ID, ID_NAME, &partial), "a partial barrier");
|
||||
// Found at a dispatch, a copy, or the shader's read of another stage.
|
||||
let dispatch = text.replacen("vkCmdDraw(): ", "vkCmdDispatch(): ", 1);
|
||||
assert!(!shape(ID, ID_NAME, &dispatch), "a dispatch");
|
||||
let vertex = text.replace("VK_SHADER_STAGE_FRAGMENT_BIT", "VK_SHADER_STAGE_VERTEX_BIT");
|
||||
assert!(!shape(ID, ID_NAME, &vertex), "the vertex stage");
|
||||
// Anything else before the command's line.
|
||||
let before = format!("Something else.\n{text}");
|
||||
assert!(!shape(ID, ID_NAME, &before), "another preface");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_releases_read_pass() {
|
||||
assert!(read(vk::make_api_version(0, 1, 4, 357)));
|
||||
assert!(read(vk::make_api_version(0, 1, 4, 363)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 4, 356)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 4, 358)));
|
||||
assert!(!read(vk::make_api_version(0, 1, 5, 0)));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,232 +0,0 @@
|
||||
//! An object or mesh case's draw through the Metal-like runtime, as the Metal oracle draws it
|
||||
//! (`metal::platform::mesh`): a library of the case's AIR, the function of each stage its draw has
|
||||
//! (its own and the partners it names) specialized with the case's constant values, the generated
|
||||
//! stages of a case that states an observation or an object launch from a library of the
|
||||
//! companion's AIR, a mesh render pipeline state of the oracle's descriptor (its color formats, or
|
||||
//! the one-pixel sink where it does not rasterize, and its rasterization), its color targets loaded
|
||||
//! and stored, its own stage's
|
||||
//! resources made and bound as a render case's stage's are ([`StageContext::bound`],
|
||||
//! [`bind_stages`]: buffers, argument buffers and their members, textures and sampler states,
|
||||
//! through that stage's `setObject*` or `setMesh*` setters), and its one `draw_mesh_threadgroups`
|
||||
//! or `draw_mesh_threads`. A device without `VK_EXT_mesh_shader` draws through the runtime's
|
||||
//! emulation, which announces `emulated-mesh-draws`.
|
||||
|
||||
use super::*;
|
||||
use crate::candidate::engine::mesh::MeshCase;
|
||||
use crate::case::MeshGrid;
|
||||
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, MeshPipelineDescriptor, StageSource};
|
||||
use metal2vulkan_runtime::Size;
|
||||
|
||||
/// What an object or mesh case's draw needs: the authored case, its mesh mapping, its AIR bitcode,
|
||||
/// its generated companion's (the generated stages of a case that states an observation or an
|
||||
/// object launch), the
|
||||
/// usage the Metal oracle gives each of its own textures (`runtime_case::texture_usage`), and its
|
||||
/// own function's AIR interface, whose argument-buffer members give each argument-buffer texture's
|
||||
/// usage.
|
||||
pub struct MeshInputs<'a> {
|
||||
pub case: &'a AuthoredCase,
|
||||
pub mesh: &'a MeshCase,
|
||||
pub bitcode: &'a [u8],
|
||||
pub companion: Option<&'a [u8]>,
|
||||
pub texture_usage: &'a BTreeMap<u32, TextureUsage>,
|
||||
pub interface: &'a AirInterface,
|
||||
}
|
||||
|
||||
/// The mesh render pipeline state of `mesh`'s draw on `device`, of the oracle's descriptor: the
|
||||
/// function of each stage its draw has from a library of `bitcode`, its AIR, or of `companion`, the
|
||||
/// generated companion's, for the generated stages, specialized with the case's constant values;
|
||||
/// its color formats (or the one-pixel sink's where it does not rasterize) and its rasterization;
|
||||
/// and `support_indirect_command_buffers` where `indirect`, as a pipeline template's state.
|
||||
pub fn mesh_pipeline_state(
|
||||
device: &Device,
|
||||
mesh: &MeshCase,
|
||||
(bitcode, companion): (&[u8], Option<&[u8]>),
|
||||
indirect: bool,
|
||||
) -> Result<RenderPipelineState, CaseError> {
|
||||
let library = device
|
||||
.new_library_with_air(bitcode)
|
||||
.map_err(CaseError::runtime("new_library_with_air"))?;
|
||||
// The generated stages' library, which a draw that states an observation or an object launch
|
||||
// has.
|
||||
let generated = match (companion, mesh.generated.is_empty()) {
|
||||
(Some(bitcode), false) => Some(
|
||||
device
|
||||
.new_library_with_air(bitcode)
|
||||
.map_err(CaseError::runtime("new_library_with_air"))?,
|
||||
),
|
||||
(None, true) => None,
|
||||
_ => return Err("a generated companion without its library, or its stages".into()),
|
||||
};
|
||||
let function = |stage: ShaderStage, function: &RenderFunction| {
|
||||
let (library, what) = match &generated {
|
||||
Some(generated) if mesh.generated.contains(&stage) => {
|
||||
(generated, "the generated companion's ")
|
||||
}
|
||||
_ => (&library, ""),
|
||||
};
|
||||
library
|
||||
.new_function_with_name_constant_values(&function.entry, &function.constants)
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"{what}function {}: new_function_with_name_constant_values",
|
||||
function.entry
|
||||
)))
|
||||
};
|
||||
let source = |function: Function| StageSource::Function(function.function_descriptor());
|
||||
let mut descriptor =
|
||||
MeshPipelineDescriptor::new(source(function(ShaderStage::Mesh, &mesh.mesh)?));
|
||||
descriptor.object = mesh
|
||||
.object
|
||||
.as_ref()
|
||||
.map(|object| function(ShaderStage::Object, object))
|
||||
.transpose()?
|
||||
.map(source);
|
||||
descriptor.fragment = mesh
|
||||
.fragment
|
||||
.as_ref()
|
||||
.map(|fragment| function(ShaderStage::Fragment, fragment))
|
||||
.transpose()?
|
||||
.map(source);
|
||||
descriptor.rasterization_enabled = mesh.rasterization;
|
||||
for (&index, target) in &mesh.color_targets {
|
||||
let attachment = descriptor
|
||||
.color_attachments
|
||||
.get_mut(index as usize)
|
||||
.ok_or_else(|| format!("color target {index} is past the descriptor's attachments"))?;
|
||||
*attachment = Some(ColorAttachmentDescriptor::new(pixel_format(target.format)));
|
||||
}
|
||||
descriptor.support_indirect_command_buffers = indirect;
|
||||
device
|
||||
.new_mesh_render_pipeline_state(&descriptor, &PipelineOptions::default())
|
||||
.map_err(CaseError::runtime("new_mesh_render_pipeline_state"))
|
||||
}
|
||||
|
||||
/// Encode `inputs`' draw on `device`: its pipeline state ([`mesh_pipeline_state`]), color targets,
|
||||
/// its own stage's resources, one command buffer with the fills its textures need, and one render
|
||||
/// encoder with its one draw, ended. Committed ([`EncodedRender::commit`]), its output is read by
|
||||
/// [`CommittedRender::mesh_output`].
|
||||
pub fn encoded_mesh(device: &Device, inputs: &MeshInputs<'_>) -> Result<EncodedRender, CaseError> {
|
||||
let mesh = inputs.mesh;
|
||||
let pipeline = mesh_pipeline_state(device, mesh, (inputs.bitcode, inputs.companion), false)?;
|
||||
let mut prep = Vec::new();
|
||||
let targets = mesh
|
||||
.color_targets
|
||||
.iter()
|
||||
.map(|(&index, target)| Ok((index, target_with(device, target, false, &mut prep)?)))
|
||||
.collect::<Result<BTreeMap<_, _>, CaseError>>()?;
|
||||
let mut pass = RenderPassDescriptor::new();
|
||||
for (&index, texture) in &targets {
|
||||
let attachment = &mut pass.color_attachments[index as usize];
|
||||
attachment.texture = Some(texture.clone());
|
||||
attachment.load_action = LoadAction::Load;
|
||||
attachment.store_action = StoreAction::Store;
|
||||
}
|
||||
// The case's own function links nothing: the schema refuses an object or mesh case's
|
||||
// visible-function references and tables.
|
||||
let own = mesh
|
||||
.function(mesh.stage)
|
||||
.ok_or("the case's own stage has no function")?;
|
||||
let linked = linked_functions(device, &[], &own.constants)?;
|
||||
let templates = BTreeMap::new();
|
||||
let context = StageContext {
|
||||
case: inputs.case,
|
||||
texture_usage: inputs.texture_usage,
|
||||
interface: inputs.interface,
|
||||
templates: &templates,
|
||||
pipeline: &pipeline,
|
||||
linked: &linked,
|
||||
};
|
||||
let mut bound: BTreeMap<ShaderStage, StageBound> = BTreeMap::new();
|
||||
let mut samplers = Vec::new();
|
||||
let mut tables = TableBuffers::new();
|
||||
for (stage, function) in mesh.stages() {
|
||||
let made = context.bound(device, stage, function, &mut prep)?;
|
||||
tables.extend(made.words);
|
||||
samplers.extend(
|
||||
made.samplers
|
||||
.into_iter()
|
||||
.map(|(slot, state)| (stage, slot, state)),
|
||||
);
|
||||
bound.insert(stage, made.bound);
|
||||
}
|
||||
let queue = device
|
||||
.new_command_queue()
|
||||
.map_err(CaseError::runtime("new_command_queue"))?;
|
||||
let command_buffer = queue
|
||||
.command_buffer()
|
||||
.map_err(CaseError::runtime("command_buffer"))?;
|
||||
for work in &prep {
|
||||
work.encode(&command_buffer)?;
|
||||
}
|
||||
// The case's own execution, after its preparation's.
|
||||
let prepared = command_buffer.executions().len();
|
||||
let mut encoder = command_buffer
|
||||
.render_command_encoder(&pass)
|
||||
.map_err(CaseError::runtime("render_command_encoder"))?;
|
||||
encoder
|
||||
.set_render_pipeline_state(&pipeline)
|
||||
.map_err(CaseError::runtime("set_render_pipeline_state"))?;
|
||||
// The argument buffers' members, resident for reading and writing in the case's own stage, as
|
||||
// the oracle's `useResource:usage:stages:` makes them.
|
||||
let members: Vec<ResourceRef<'_>> = bound.values().flat_map(StageBound::members).collect();
|
||||
if !members.is_empty() {
|
||||
encoder
|
||||
.use_resources(
|
||||
&members,
|
||||
ResourceUsage::READ | ResourceUsage::WRITE,
|
||||
render_stage(mesh.stage),
|
||||
)
|
||||
.map_err(CaseError::runtime("use_resources"))?;
|
||||
}
|
||||
bind_stages(&mut encoder, &bound, &samplers)?;
|
||||
// An object function's threadgroup memory, as the oracle sets it; the case schema refuses a
|
||||
// mesh case's.
|
||||
if inputs.case.stage == crate::case::Stage::Object {
|
||||
for resource in &inputs.case.threadgroup_memory {
|
||||
encoder
|
||||
.set_object_threadgroup_memory_length(resource.length, resource.binding)
|
||||
.map_err(CaseError::runtime("set_object_threadgroup_memory_length"))?;
|
||||
}
|
||||
}
|
||||
let size = |[x, y, z]: [u32; 3]| Size::new(x.into(), y.into(), z.into());
|
||||
let (object, threads) = (
|
||||
size(mesh.threads_per_object_threadgroup),
|
||||
size(mesh.threads_per_mesh_threadgroup),
|
||||
);
|
||||
match mesh.grid {
|
||||
MeshGrid::Threadgroups(groups) => {
|
||||
encoder.draw_mesh_threadgroups(size(groups), object, threads)
|
||||
}
|
||||
MeshGrid::Threads(grid) => encoder.draw_mesh_threads(size(grid), object, threads),
|
||||
}
|
||||
.map_err(CaseError::runtime("draw_mesh_*"))?;
|
||||
encoder
|
||||
.end_encoding()
|
||||
.map_err(CaseError::runtime("end_encoding"))?;
|
||||
let executions = command_buffer.executions().split_off(prepared);
|
||||
Ok(EncodedRender {
|
||||
command_buffer,
|
||||
executions,
|
||||
tables,
|
||||
drawn: Drawn {
|
||||
targets,
|
||||
depth: None,
|
||||
stencil: None,
|
||||
bound,
|
||||
readback: None,
|
||||
guarded: BTreeMap::new(),
|
||||
imageblock: None,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
impl CommittedRender {
|
||||
/// The bytes `mesh`'s output selects, once the command buffer completed: a resource of its own
|
||||
/// stage, or a region of a render target.
|
||||
pub fn mesh_output(&self, mesh: &MeshCase) -> Result<Vec<u8>, CaseError> {
|
||||
self.drawn.read(
|
||||
&mesh.output,
|
||||
|stage| mesh.function(stage),
|
||||
&mesh.color_targets,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
//! A case's sparse texture through the runtime: made as the Metal oracle makes it, from a sparse
|
||||
//! heap of 16-KiB pages, its mappings mapped before the work by a resource state encoder, and only
|
||||
//! the authored bytes of its mapped texels uploaded.
|
||||
//!
|
||||
//! A mapping names texels; the runtime maps Metal's tiles, so a region that is not a whole number
|
||||
//! of them (its origin a multiple of the tile, its end one or the level's edge) does not run
|
||||
//! (`CaseError::Case`), as every executor refuses one of its own tiles. A slice's mip tail is its
|
||||
//! level from Metal's `firstMipmapInTail`: the tail where Metal keeps the case's one level in
|
||||
//! one, and that level's tiles where it does not. A tile maps alone on every device that makes
|
||||
//! the texture, whatever its blocks.
|
||||
|
||||
use super::{texture_descriptor, CaseError};
|
||||
use crate::case::sparse::{SparseMapping, SparseTextureResource};
|
||||
use crate::literal::LiteralTexture;
|
||||
use metal2vulkan::bind::TileMapping;
|
||||
use metal2vulkan::metal::TextureUsage;
|
||||
use metal2vulkan_runtime::{
|
||||
BlitOption, Device, HeapDescriptor, HeapType, Origin, Region, ResourceOptions, Size, Texture,
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
/// The longest the mapping and upload may take.
|
||||
const WAIT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// The sparse texture of `literal`, whose mappings `sparse` lists, with `usage`.
|
||||
pub(super) fn texture_with(
|
||||
device: &Device,
|
||||
literal: &LiteralTexture,
|
||||
sparse: &SparseTextureResource,
|
||||
usage: TextureUsage,
|
||||
) -> Result<Texture, CaseError> {
|
||||
let label = format!("sparse texture {}", literal.binding);
|
||||
let mut descriptor = texture_descriptor(literal, usage)?;
|
||||
descriptor.resource_options = ResourceOptions::private();
|
||||
// Room for every tile of each slice, whatever its rows waste, and a tail each.
|
||||
let room = (literal.bytes.len() as u64 * 4)
|
||||
.max(1 << 20)
|
||||
.next_multiple_of(16384);
|
||||
let heap = device
|
||||
.new_heap(&HeapDescriptor::new(
|
||||
HeapType::Sparse,
|
||||
room,
|
||||
ResourceOptions::private(),
|
||||
))
|
||||
.map_err(CaseError::runtime(format!("{label}: new_heap")))?;
|
||||
let texture = heap
|
||||
.new_texture(&descriptor)
|
||||
.map_err(CaseError::runtime(format!("{label}: new_texture")))?;
|
||||
let tile = device.sparse_tile_size(descriptor.texture_type, descriptor.pixel_format, 1);
|
||||
let tile = [tile.width, tile.height, tile.depth];
|
||||
let extent = [descriptor.width, descriptor.height, descriptor.depth];
|
||||
let first_tail = texture.first_mipmap_in_tail().unwrap_or(1);
|
||||
// Each mapping as Metal's tiles of level 0 and the texels it uploads.
|
||||
let mut updates = Vec::new();
|
||||
for (index, mapping) in sparse.mappings.iter().enumerate() {
|
||||
let (slice, origin, size) = match *mapping {
|
||||
SparseMapping::Region {
|
||||
slice,
|
||||
origin,
|
||||
size,
|
||||
..
|
||||
} => (slice, origin.map(u64::from), size.map(u64::from)),
|
||||
SparseMapping::MipTail { slice } => (slice, [0; 3], extent),
|
||||
};
|
||||
let whole = (0..3).all(|axis| {
|
||||
let end = origin[axis] + size[axis];
|
||||
origin[axis] % tile[axis] == 0 && (end % tile[axis] == 0 || end == extent[axis])
|
||||
});
|
||||
if !whole {
|
||||
return Err(format!(
|
||||
"{label} mapping {index}: texels {origin:?} + {size:?} are not whole tiles of \
|
||||
{tile:?}"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let tiles = Region::new_3d(
|
||||
origin[0] / tile[0],
|
||||
origin[1] / tile[1],
|
||||
origin[2] / tile[2],
|
||||
(origin[0] + size[0]).div_ceil(tile[0]) - origin[0] / tile[0],
|
||||
(origin[1] + size[1]).div_ceil(tile[1]) - origin[1] / tile[1],
|
||||
(origin[2] + size[2]).div_ceil(tile[2]) - origin[2] / tile[2],
|
||||
);
|
||||
// Metal keeps the level whole in its tail: the tail's update, for the whole level only.
|
||||
let tiles = if first_tail == 0 {
|
||||
if origin != [0; 3] || size != extent {
|
||||
return Err(format!(
|
||||
"{label} mapping {index}: texels {origin:?} + {size:?} are part of a level \
|
||||
Metal keeps in its mip tail"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Region::new_2d(0, 0, 0, 0)
|
||||
} else {
|
||||
tiles
|
||||
};
|
||||
updates.push((u64::from(slice), tiles, origin, size));
|
||||
}
|
||||
let queue = device
|
||||
.new_command_queue()
|
||||
.map_err(CaseError::runtime(format!("{label}: new_command_queue")))?;
|
||||
let command_buffer = queue
|
||||
.command_buffer()
|
||||
.map_err(CaseError::runtime(format!("{label}: command_buffer")))?;
|
||||
let mut encoder =
|
||||
command_buffer
|
||||
.resource_state_command_encoder()
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"{label}: resource_state_command_encoder"
|
||||
)))?;
|
||||
for &(slice, tiles, ..) in &updates {
|
||||
encoder
|
||||
.update_texture_mapping(&texture, TileMapping::Map, tiles, 0, slice)
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"{label}: update_texture_mapping"
|
||||
)))?;
|
||||
}
|
||||
encoder
|
||||
.end_encoding()
|
||||
.map_err(CaseError::runtime(format!("{label}: end_encoding")))?;
|
||||
// The mapped texels' authored bytes, rows tightly packed as the literal holds them.
|
||||
let texel = literal.format.bytes_per_pixel() as u64;
|
||||
let row = extent[0] * texel;
|
||||
let image = row * extent[1];
|
||||
let slice_bytes = image * extent[2];
|
||||
let source = device
|
||||
.new_buffer(
|
||||
(literal.bytes.len() as u64).max(1),
|
||||
ResourceOptions::shared(),
|
||||
)
|
||||
.map_err(CaseError::runtime(format!("{label}: new_buffer")))?;
|
||||
let contents = source
|
||||
.contents()
|
||||
.ok_or_else(|| format!("{label}: a Shared buffer without host bytes"))?;
|
||||
// SAFETY: the buffer holds the literal's bytes, and no command uses it yet.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(
|
||||
literal.bytes.as_ptr(),
|
||||
contents.as_ptr(),
|
||||
literal.bytes.len(),
|
||||
)
|
||||
};
|
||||
let mut blit = command_buffer
|
||||
.blit_command_encoder()
|
||||
.map_err(CaseError::runtime(format!("{label}: blit_command_encoder")))?;
|
||||
for &(slice, _, origin, size) in &updates {
|
||||
let offset = slice * slice_bytes + origin[2] * image + origin[1] * row + origin[0] * texel;
|
||||
let per_image = if extent[2] > 1 { image } else { 0 };
|
||||
blit.copy_from_buffer_to_texture(
|
||||
&source,
|
||||
offset,
|
||||
row,
|
||||
per_image,
|
||||
Size::new(size[0], size[1], size[2]),
|
||||
&texture,
|
||||
slice,
|
||||
0,
|
||||
Origin::new(origin[0], origin[1], origin[2]),
|
||||
BlitOption::None,
|
||||
)
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"{label}: copy_from_buffer_to_texture"
|
||||
)))?;
|
||||
}
|
||||
blit.end_encoding()
|
||||
.map_err(CaseError::runtime(format!("{label}: end_encoding")))?;
|
||||
command_buffer
|
||||
.commit()
|
||||
.map_err(CaseError::runtime(format!("{label}: commit")))?;
|
||||
command_buffer
|
||||
.wait_until_completed_for(WAIT)
|
||||
.map_err(|_| format!("{label}: the mapping did not complete in {WAIT:?}"))?;
|
||||
if let Some(error) = command_buffer.error() {
|
||||
return Err(format!("{label}: the mapping failed: {error:?}").into());
|
||||
}
|
||||
Ok(texture)
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
//! A tile kernel's dispatch through the Metal-like runtime, as the Metal oracle dispatches it
|
||||
//! (`metal::platform::tile`): the one copy the runtime lane's tile census
|
||||
//! (`runtime_lane::tile_dispatches`) and the engine executor's runtime path (`runtime_run`)
|
||||
//! share.
|
||||
//!
|
||||
//! A tile pipeline state of the oracle's descriptor ([`tile_descriptor`]: the tile function, the
|
||||
//! functions it links, the pass's attachments' formats, one sample), the pass's attachments, each
|
||||
//! a `Shared` 2D render target of its authored format, extent and contents that loads and stores,
|
||||
//! in a pass of the case's area whose tile is the case's imageblock and whose
|
||||
//! `imageblockSampleLength` is the state's, as the oracle asks it; the case's buffers, textures,
|
||||
//! sampler states and visible-function tables set on the encoder's tile stage, one
|
||||
//! `dispatch_threads_per_tile` of the case's threads per tile, and the output read back after the
|
||||
//! command buffer completed. Its argument buffers are made as a compute dispatch's are
|
||||
//! (`runtime_case::bound_buffers`), their buffers and textures resident for reading and writing
|
||||
//! in the tile stage, as the oracle's `useResource:usage:stages:` makes them; its tables are made
|
||||
//! by the tile state for the tile stage ([`tile_tables`]).
|
||||
//!
|
||||
//! The oracle draws a triangle over the pass first, whose fragment writes no color, so that
|
||||
//! Metal's imageblock holds every pixel (`ImplicitImageblockCoverage::FullSingleSample`); it
|
||||
//! changes no pixel, so the runtime path draws none. The oracle's threadgroup memory lengths are
|
||||
//! not set: the compile layer refuses a tile function's threadgroup memory, so the state's creation
|
||||
//! refuses a case whose function reads one. A tile dispatch's command buffers and the pipeline
|
||||
//! states its argument buffers hold are refused as a [`CaseError::Case`] naming "a later runtime
|
||||
//! step"; the executor's route sends no such case here (`runtime_run::kernel_prerequisites`).
|
||||
|
||||
use super::{
|
||||
bound_buffers, tables_of, texture_with, CaseError, CaseResources, CaseTables, Encoded,
|
||||
LinkedSet,
|
||||
};
|
||||
use crate::candidate::engine::{ComputeCase, TilePass};
|
||||
use metal2vulkan::bind::Dispatch;
|
||||
use metal2vulkan::metal::{RenderStages, ResourceUsage, TextureUsage};
|
||||
use metal2vulkan::pipeline::{
|
||||
LinkedFunctions, Stage as ShaderStage, StageSource, TileRenderPipelineDescriptor,
|
||||
};
|
||||
use metal2vulkan_runtime::{
|
||||
Buffer, Device, Function, LoadAction, RenderPassDescriptor, RenderPipelineState, ResourceRef,
|
||||
Size, StoreAction, Texture, VisibleFunctionTable,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The descriptor of a tile kernel's pipeline state over `pass`, as the Metal oracle states it:
|
||||
/// its tile `function` (made with the case's constant values) linking `linked`, each attachment's
|
||||
/// pixel format at its color index, one sample, and `threadgroupSizeMatchesTileSize` off. The
|
||||
/// oracle's `requiredThreadsPerThreadgroup` sizes Metal's pipeline for the case's threads; the
|
||||
/// runtime's tile pipeline runs every measured threadgroup up to 32 by 32, so the descriptor states
|
||||
/// none.
|
||||
pub fn tile_descriptor(
|
||||
function: &Function,
|
||||
linked: LinkedFunctions,
|
||||
pass: &TilePass,
|
||||
) -> TileRenderPipelineDescriptor {
|
||||
let mut descriptor = TileRenderPipelineDescriptor::new(StageSource::Function(
|
||||
function.function_descriptor().with_linked(linked),
|
||||
));
|
||||
for (index, format) in pass.formats() {
|
||||
if let Some(slot) = descriptor.color_attachment_formats.get_mut(index as usize) {
|
||||
*slot = Some(format);
|
||||
}
|
||||
}
|
||||
descriptor
|
||||
}
|
||||
|
||||
/// The visible-function tables of tile kernel `case` for its tile state `pipeline`, as
|
||||
/// `runtime_case::visible_function_tables` makes a kernel's: each made by the state for the tile
|
||||
/// stage and each entry the handle the state gives the function it holds among `linked` for that
|
||||
/// stage, as the oracle makes them (`newVisibleFunctionTableWithDescriptor:stage:`); the bytes
|
||||
/// keyed by the kernel stage, as the executor keys a tile kernel's.
|
||||
pub fn tile_tables(
|
||||
pipeline: &RenderPipelineState,
|
||||
case: &ComputeCase,
|
||||
linked: &LinkedSet,
|
||||
) -> Result<CaseTables, CaseError> {
|
||||
tables_of(
|
||||
(ShaderStage::Kernel, &case.function_tables),
|
||||
linked,
|
||||
|descriptor| pipeline.new_visible_function_table(descriptor, RenderStages::TILE),
|
||||
|function| pipeline.function_handle(function, RenderStages::TILE),
|
||||
)
|
||||
}
|
||||
|
||||
/// Encode tile kernel `case`'s dispatch on `device` with `pipeline` (the tile pipeline state of
|
||||
/// its entry, [`tile_descriptor`]), its visible-function `tables` ([`tile_tables`]), and the
|
||||
/// textures' `usage` and `argument_usage` ([`CaseResources::of`]): its resources holding their
|
||||
/// bytes, its pass's attachments holding theirs, one command buffer with the fills of its
|
||||
/// multisampled textures, then one render encoder of the pass and its one tile dispatch (the
|
||||
/// module's rule), ended. [`Encoded::commit`] runs it.
|
||||
pub fn encoded_tile(
|
||||
device: &Device,
|
||||
case: &ComputeCase,
|
||||
usage: &BTreeMap<u32, TextureUsage>,
|
||||
argument_usage: &BTreeMap<(u32, u32), TextureUsage>,
|
||||
pipeline: &RenderPipelineState,
|
||||
tables: BTreeMap<u32, VisibleFunctionTable>,
|
||||
) -> Result<Encoded, CaseError> {
|
||||
let pass = case.tile.as_ref().ok_or("the case runs in no tile pass")?;
|
||||
if !case.command_buffers.is_empty() || !case.objects.is_empty() {
|
||||
return Err(CaseError::Case(
|
||||
"a tile dispatch's command buffers and pipeline states: a later runtime step"
|
||||
.to_owned(),
|
||||
));
|
||||
}
|
||||
let Dispatch::Threadgroups {
|
||||
threads_per_group, ..
|
||||
} = case.dispatch
|
||||
else {
|
||||
return Err(format!("a tile pass's dispatch {:?}", case.dispatch).into());
|
||||
};
|
||||
let [tile_width, tile_height] = case.imageblock.ok_or("a tile pass without a tile size")?;
|
||||
let mut resources = CaseResources::of(device, case, usage, argument_usage)?;
|
||||
resources.tables = tables;
|
||||
let buffers = bound_buffers(device, case, &resources)?;
|
||||
let attachments = pass
|
||||
.attachments
|
||||
.iter()
|
||||
.map(|(&index, literal)| {
|
||||
Ok((
|
||||
index,
|
||||
texture_with(device, literal, TextureUsage::RENDER_TARGET)?,
|
||||
))
|
||||
})
|
||||
.collect::<Result<BTreeMap<_, _>, CaseError>>()?;
|
||||
let mut descriptor = RenderPassDescriptor::new();
|
||||
for (&index, texture) in &attachments {
|
||||
let attachment = descriptor
|
||||
.color_attachments
|
||||
.get_mut(index as usize)
|
||||
.ok_or_else(|| format!("a tile pass's attachment {index}"))?;
|
||||
attachment.texture = Some(texture.clone());
|
||||
attachment.load_action = LoadAction::Load;
|
||||
attachment.store_action = StoreAction::Store;
|
||||
}
|
||||
descriptor.tile_width = tile_width.into();
|
||||
descriptor.tile_height = tile_height.into();
|
||||
descriptor.imageblock_sample_length = pipeline
|
||||
.imageblock_sample_length()
|
||||
.map_err(CaseError::runtime("imageblock_sample_length"))?;
|
||||
descriptor.render_target_width = pass.area[0].into();
|
||||
descriptor.render_target_height = pass.area[1].into();
|
||||
let queue = device
|
||||
.new_command_queue()
|
||||
.map_err(CaseError::runtime("new_command_queue"))?;
|
||||
let command_buffer = queue
|
||||
.command_buffer()
|
||||
.map_err(CaseError::runtime("command_buffer"))?;
|
||||
for fill in &resources.fills {
|
||||
fill.encode(&command_buffer)?;
|
||||
}
|
||||
let filled = command_buffer.executions().len();
|
||||
let mut encoder = command_buffer
|
||||
.render_command_encoder(&descriptor)
|
||||
.map_err(CaseError::runtime("render_command_encoder"))?;
|
||||
encoder
|
||||
.set_render_pipeline_state(pipeline)
|
||||
.map_err(CaseError::runtime("set_render_pipeline_state"))?;
|
||||
for (&index, buffer) in &buffers {
|
||||
encoder
|
||||
.set_tile_buffer(Some(buffer), 0, index)
|
||||
.map_err(CaseError::runtime(format!("set_tile_buffer {index}")))?;
|
||||
}
|
||||
for (&index, table) in &resources.tables {
|
||||
encoder
|
||||
.set_tile_visible_function_table(Some(table), index)
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"set_tile_visible_function_table {index}"
|
||||
)))?;
|
||||
}
|
||||
// The argument buffers' members, resident for reading and writing in the tile stage, as the
|
||||
// oracle's `useResource:usage:stages:` makes them.
|
||||
let members: Vec<ResourceRef<'_>> = resources
|
||||
.argument_buffers
|
||||
.values()
|
||||
.map(Buffer::as_resource)
|
||||
.chain(
|
||||
resources
|
||||
.argument_textures
|
||||
.values()
|
||||
.map(Texture::as_resource),
|
||||
)
|
||||
.collect();
|
||||
if !members.is_empty() {
|
||||
encoder
|
||||
.use_resources(
|
||||
&members,
|
||||
ResourceUsage::READ | ResourceUsage::WRITE,
|
||||
RenderStages::TILE,
|
||||
)
|
||||
.map_err(CaseError::runtime("use_resources"))?;
|
||||
}
|
||||
for (&index, texture) in &resources.textures {
|
||||
encoder
|
||||
.set_tile_texture(Some(texture), index)
|
||||
.map_err(CaseError::runtime(format!("set_tile_texture {index}")))?;
|
||||
}
|
||||
for (&index, sampler) in &resources.samplers {
|
||||
encoder
|
||||
.set_tile_sampler_state(Some(sampler), index)
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"set_tile_sampler_state {index}"
|
||||
)))?;
|
||||
}
|
||||
let [width, height, depth] = threads_per_group.map(u64::from);
|
||||
encoder
|
||||
.dispatch_threads_per_tile(Size::new(width, height, depth))
|
||||
.map_err(CaseError::runtime("dispatch_threads_per_tile"))?;
|
||||
encoder
|
||||
.end_encoding()
|
||||
.map_err(CaseError::runtime("end_encoding"))?;
|
||||
// Each ended encoder's executions join the command buffer's in encoding order.
|
||||
let executions = command_buffer.executions().split_off(filled);
|
||||
Ok(Encoded {
|
||||
command_buffer,
|
||||
buffers,
|
||||
resources,
|
||||
attachments,
|
||||
executions,
|
||||
})
|
||||
}
|
||||
@@ -1,484 +0,0 @@
|
||||
//! A multisampled texture filled sample by sample through the Metal-like runtime, as the Metal
|
||||
//! oracle fills one (`metal::platform::textures`'s multisample initializer): Metal writes no
|
||||
//! multisampled texture from the CPU, so a render pass per slice draws the fullscreen triangle at
|
||||
//! sample rate and each invocation writes its own sample's value from a buffer of every pixel's
|
||||
//! samples in order. The functions are the owned fixture `rt6_samples`'s (the oracle's source with
|
||||
//! the extent's width and the sample count read from a buffer, where the oracle writes them into
|
||||
//! its source), one fragment function per format the oracle fills.
|
||||
//!
|
||||
//! A fill is encoded into the command buffer whose work reads the texture, ahead of that work
|
||||
//! ([`SampleFill::encode`]): Metal runs a command buffer's passes in order, so nothing waits on
|
||||
//! the fill alone and one wait covers it.
|
||||
//!
|
||||
//! A multisampled attachment is read back sample by sample the same way ([`encode`], as the
|
||||
//! oracle's `metal::platform` `sample_readback` reads one): Metal copies no multisampled texture
|
||||
//! to a buffer, so a dispatch of one thread per sample (threadgroups of one, the grid the pixels
|
||||
//! by the samples) reads each sample and writes the texel's words at its place in the
|
||||
//! sample-minor layout, with the fixture's kernels. A `Depth32Float` attachment is read as its
|
||||
//! bits, a `Stencil8` one as its first component. A color one is read through an unsigned view
|
||||
//! with its own components and bits (`color_view`), whose kernel packs them into the words the
|
||||
//! oracle's view of the texel size gives: the bytes are the oracle's, and no device needs
|
||||
//! Vulkan's `imageViewFormatReinterpretation` (MoltenVK withholds it). Nothing is resolved.
|
||||
|
||||
use super::engine::resources::pixel_format;
|
||||
use super::runtime_case::{buffer_with, read_buffer, texture_descriptor, CaseError};
|
||||
use crate::air_library::AirLibrary;
|
||||
use crate::case::TextureFormat;
|
||||
use crate::executor_contract::multisample::{readback_bytes, unpack_words, SampleRead};
|
||||
use crate::literal::{LiteralTexture, TextureLayout};
|
||||
use metal2vulkan::metal::state::DepthStencilDescriptor;
|
||||
use metal2vulkan::metal::{CompareFunction, PixelFormat, PrimitiveType, TextureUsage};
|
||||
use metal2vulkan::pipeline::FunctionDescriptor;
|
||||
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
|
||||
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
|
||||
use metal2vulkan_runtime::{
|
||||
Buffer, CommandBuffer, DepthStencilState, Device, Library, LoadAction, PipelineOptions,
|
||||
RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, Texture,
|
||||
};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// The owned fixture's opaque-pointer text.
|
||||
const FIXTURE: &str = "rt6_samples.ll";
|
||||
|
||||
/// The fixture's vertex function: the oracle's fullscreen triangle.
|
||||
const VERTEX: &str = "rt6_fill_vertex";
|
||||
|
||||
/// The fixture's library on `device`, its bitcode assembled once per process.
|
||||
pub fn library(device: &Device) -> Result<Library, CaseError> {
|
||||
static BITCODE: OnceLock<Result<Vec<u8>, String>> = OnceLock::new();
|
||||
let bitcode = BITCODE
|
||||
.get_or_init(|| {
|
||||
llvm_assemble(&engine_dir().join(FIXTURE))
|
||||
.map_err(|error| format!("llvm-as of {FIXTURE}: {error:?}"))
|
||||
})
|
||||
.as_ref()
|
||||
.map_err(|error| CaseError::from(error.clone()))?;
|
||||
device
|
||||
.new_library_with_air(bitcode)
|
||||
.map_err(CaseError::helper(format!(
|
||||
"{FIXTURE}: new_library_with_air"
|
||||
)))
|
||||
}
|
||||
|
||||
/// A buffer of the shape the fixture's functions read: the extent's `width` and the `samples` of
|
||||
/// each pixel.
|
||||
pub fn shape(device: &Device, width: u32, samples: u32) -> Result<Buffer, CaseError> {
|
||||
let mut bytes = width.to_le_bytes().to_vec();
|
||||
bytes.extend_from_slice(&samples.to_le_bytes());
|
||||
buffer_with(device, &bytes)
|
||||
}
|
||||
|
||||
/// The fixture's fragment function that fills a texture of `format`, as the oracle's
|
||||
/// initializer fills it: a sampled-only format and the 64-bit one are no multisampled texture's.
|
||||
fn fill_function(format: TextureFormat) -> Result<&'static str, String> {
|
||||
Ok(match format {
|
||||
TextureFormat::R8Unorm => "rt6_fill_r8unorm",
|
||||
TextureFormat::Rgba8Unorm => "rt6_fill_rgba8unorm",
|
||||
TextureFormat::Rgba8Uint => "rt6_fill_rgba8uint",
|
||||
TextureFormat::Rgba8Sint => "rt6_fill_rgba8sint",
|
||||
TextureFormat::R16Float => "rt6_fill_r16float",
|
||||
TextureFormat::R16Uint => "rt6_fill_r16uint",
|
||||
TextureFormat::Rg16Float => "rt6_fill_rg16float",
|
||||
TextureFormat::Rg32Float => "rt6_fill_rg32float",
|
||||
TextureFormat::Rgba16Float => "rt6_fill_rgba16float",
|
||||
TextureFormat::Rgba16Uint => "rt6_fill_rgba16uint",
|
||||
TextureFormat::Rgba16Sint => "rt6_fill_rgba16sint",
|
||||
TextureFormat::R32Uint => "rt6_fill_r32uint",
|
||||
TextureFormat::R32Sint => "rt6_fill_r32sint",
|
||||
TextureFormat::R32Float => "rt6_fill_r32float",
|
||||
TextureFormat::Rgba32Uint => "rt6_fill_rgba32uint",
|
||||
TextureFormat::Rgba32Sint => "rt6_fill_rgba32sint",
|
||||
TextureFormat::Rgba32Float => "rt6_fill_rgba32float",
|
||||
TextureFormat::Depth32Float => "rt6_fill_depth32float",
|
||||
TextureFormat::R8Snorm
|
||||
| TextureFormat::Rgba8Snorm
|
||||
| TextureFormat::R16Unorm
|
||||
| TextureFormat::Rgba16Unorm
|
||||
| TextureFormat::R16Snorm
|
||||
| TextureFormat::Rg16Snorm
|
||||
| TextureFormat::Rgba16Snorm
|
||||
| TextureFormat::Rgba8UnormSrgb
|
||||
| TextureFormat::Bgra8Unorm
|
||||
| TextureFormat::Bgra8UnormSrgb
|
||||
| TextureFormat::R8UnormSrgb
|
||||
| TextureFormat::Rg8Unorm
|
||||
| TextureFormat::Rg8UnormSrgb
|
||||
| TextureFormat::Rg8Snorm
|
||||
| TextureFormat::Rg16Unorm
|
||||
| TextureFormat::A8Unorm
|
||||
| TextureFormat::B5g6r5Unorm
|
||||
| TextureFormat::A1bgr5Unorm
|
||||
| TextureFormat::Abgr4Unorm
|
||||
| TextureFormat::Bgr5a1Unorm
|
||||
| TextureFormat::Rgb10a2Unorm
|
||||
| TextureFormat::Bgr10a2Unorm
|
||||
| TextureFormat::Rg11b10Float
|
||||
| TextureFormat::Rgb9e5Float => {
|
||||
return Err(format!(
|
||||
"{format:?} is a sampled-only format, which no case multisamples"
|
||||
))
|
||||
}
|
||||
TextureFormat::Rg32Uint => {
|
||||
return Err(format!(
|
||||
"{format:?} is the ulong texture format, which no case multisamples"
|
||||
))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The fixture's function `name` on `device`.
|
||||
fn entry(device: &Device, name: &str) -> Result<FunctionDescriptor, CaseError> {
|
||||
library(device)?
|
||||
.new_function_with_name(name)
|
||||
.map(|f| f.function_descriptor())
|
||||
.map_err(CaseError::helper(format!("{FIXTURE}: function {name}")))
|
||||
}
|
||||
|
||||
/// The render pipeline [`SampleFill::new`] makes the state of its fill of a texture of `format`
|
||||
/// and `samples` of, for a test that expects what the making announces.
|
||||
pub fn fill_descriptor(
|
||||
device: &Device,
|
||||
format: TextureFormat,
|
||||
samples: u32,
|
||||
) -> Result<RenderPipelineDescriptor, CaseError> {
|
||||
let function = fill_function(format)?;
|
||||
let mut descriptor =
|
||||
RenderPipelineDescriptor::new(StageSource::Function(entry(device, VERTEX)?));
|
||||
descriptor.fragment = Some(StageSource::Function(entry(device, function)?));
|
||||
if format == TextureFormat::Depth32Float {
|
||||
descriptor.depth_format = Some(PixelFormat::Depth32Float);
|
||||
} else {
|
||||
descriptor.color_attachments[0] =
|
||||
Some(ColorAttachmentDescriptor::new(pixel_format(format)));
|
||||
}
|
||||
descriptor.raster_sample_count = samples;
|
||||
Ok(descriptor)
|
||||
}
|
||||
|
||||
/// The kernel [`encode`] reads a texture of `format` as `read` with, for a test that expects
|
||||
/// what the making of its state announces.
|
||||
pub fn read_function(
|
||||
device: &Device,
|
||||
format: PixelFormat,
|
||||
read: SampleRead,
|
||||
) -> Result<FunctionDescriptor, CaseError> {
|
||||
let kernel = match read {
|
||||
SampleRead::Color(_) => color_view(format)?.1,
|
||||
SampleRead::Depth => "rt6_read_depth",
|
||||
SampleRead::Stencil => "rt6_read_stencil",
|
||||
};
|
||||
entry(device, kernel)
|
||||
}
|
||||
|
||||
/// The view [`encode`] reads a color texture of `format` through: an unsigned format of its
|
||||
/// components and bits, which is `format` itself for an unsigned one. A texture made without
|
||||
/// `PixelFormatView` usage holds a view of another format apart (`shadowed-texture-view`).
|
||||
pub fn read_view(format: PixelFormat) -> Result<PixelFormat, CaseError> {
|
||||
Ok(color_view(format)?.0)
|
||||
}
|
||||
|
||||
/// The fill of one multisampled texture: its pipeline, the buffers it reads, and the slices it
|
||||
/// writes ([`SampleFill::new`]).
|
||||
pub struct SampleFill {
|
||||
texture: Texture,
|
||||
pipeline: RenderPipelineState,
|
||||
/// A depth texture's state: every sample written, whatever it held (`Always`).
|
||||
depth_state: Option<DepthStencilState>,
|
||||
values: Buffer,
|
||||
shape: Buffer,
|
||||
layers: u32,
|
||||
layer_bytes: u64,
|
||||
}
|
||||
|
||||
impl SampleFill {
|
||||
/// The fill of `texture`, a multisampled render target of `format` and `layout`, with
|
||||
/// `bytes`: each slice's pixels, rows in order, each pixel's samples in order.
|
||||
pub fn new(
|
||||
device: &Device,
|
||||
texture: &Texture,
|
||||
format: TextureFormat,
|
||||
layout: TextureLayout,
|
||||
bytes: &[u8],
|
||||
) -> Result<SampleFill, CaseError> {
|
||||
let function = fill_function(format)?;
|
||||
let depth = format == TextureFormat::Depth32Float;
|
||||
let descriptor = fill_descriptor(device, format, layout.sample_count)?;
|
||||
let pipeline = device
|
||||
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
|
||||
.map_err(CaseError::helper(format!(
|
||||
"{function}: new_render_pipeline_state"
|
||||
)))?;
|
||||
let depth_state = depth
|
||||
.then(|| {
|
||||
let mut state = DepthStencilDescriptor::default();
|
||||
state.depth_compare_function = CompareFunction::Always;
|
||||
state.depth_write_enabled = true;
|
||||
device
|
||||
.new_depth_stencil_state(&state)
|
||||
.map_err(CaseError::runtime("new_depth_stencil_state"))
|
||||
})
|
||||
.transpose()?;
|
||||
let layer_bytes = [
|
||||
layout.width,
|
||||
layout.height,
|
||||
layout.sample_count,
|
||||
format.bytes_per_pixel() as u32,
|
||||
]
|
||||
.into_iter()
|
||||
.try_fold(1u64, |n, f| n.checked_mul(u64::from(f)))
|
||||
.ok_or("a multisampled texture's slice size overflows")?;
|
||||
let needed = layer_bytes * u64::from(layout.array_layers);
|
||||
if (bytes.len() as u64) < needed || needed == 0 {
|
||||
return Err(format!(
|
||||
"a multisampled texture supplies {} bytes but its extent needs {needed}",
|
||||
bytes.len()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(SampleFill {
|
||||
texture: texture.clone(),
|
||||
pipeline,
|
||||
depth_state,
|
||||
values: buffer_with(device, bytes)?,
|
||||
shape: shape(device, layout.width, layout.sample_count)?,
|
||||
layers: layout.array_layers,
|
||||
layer_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode the fill into `command_buffer`: per slice, a render pass that loads nothing and
|
||||
/// stores every sample, drawing the fullscreen triangle once.
|
||||
pub fn encode(&self, command_buffer: &CommandBuffer) -> Result<(), CaseError> {
|
||||
self.encode_into(command_buffer, None)
|
||||
}
|
||||
|
||||
/// [`SampleFill::encode`] of a color texture whose passes also resolve each slice into the
|
||||
/// same slice of `resolve` (`StoreAndMultisampleResolve`): a draw's samples resolved by the
|
||||
/// store action of the pass that wrote them.
|
||||
pub fn encode_resolving(
|
||||
&self,
|
||||
command_buffer: &CommandBuffer,
|
||||
resolve: &Texture,
|
||||
) -> Result<(), CaseError> {
|
||||
self.encode_into(command_buffer, Some(resolve))
|
||||
}
|
||||
|
||||
/// The fill's passes, each resolving its color slice into `resolve` where given.
|
||||
fn encode_into(
|
||||
&self,
|
||||
command_buffer: &CommandBuffer,
|
||||
resolve: Option<&Texture>,
|
||||
) -> Result<(), CaseError> {
|
||||
for layer in 0..self.layers {
|
||||
let mut pass = RenderPassDescriptor::new();
|
||||
let texture = Some(self.texture.clone());
|
||||
if self.depth_state.is_some() {
|
||||
let attachment = &mut pass.depth_attachment;
|
||||
attachment.texture = texture;
|
||||
attachment.slice = layer.into();
|
||||
attachment.load_action = LoadAction::DontCare;
|
||||
attachment.store_action = StoreAction::Store;
|
||||
} else {
|
||||
let attachment = &mut pass.color_attachments[0];
|
||||
attachment.texture = texture;
|
||||
attachment.slice = layer.into();
|
||||
attachment.load_action = LoadAction::DontCare;
|
||||
attachment.store_action = StoreAction::Store;
|
||||
if let Some(resolve) = resolve {
|
||||
attachment.resolve_texture = Some(resolve.clone());
|
||||
attachment.resolve_slice = layer.into();
|
||||
attachment.store_action = StoreAction::StoreAndMultisampleResolve;
|
||||
}
|
||||
}
|
||||
let mut encoder =
|
||||
command_buffer
|
||||
.render_command_encoder(&pass)
|
||||
.map_err(CaseError::runtime(
|
||||
"the sample fill's render_command_encoder",
|
||||
))?;
|
||||
let fill = CaseError::runtime;
|
||||
encoder
|
||||
.set_render_pipeline_state(&self.pipeline)
|
||||
.map_err(fill("the sample fill's set_render_pipeline_state"))?;
|
||||
if let Some(state) = &self.depth_state {
|
||||
encoder
|
||||
.set_depth_stencil_state(state)
|
||||
.map_err(fill("the sample fill's set_depth_stencil_state"))?;
|
||||
}
|
||||
encoder
|
||||
.set_fragment_buffer(Some(&self.values), u64::from(layer) * self.layer_bytes, 0)
|
||||
.map_err(fill("the sample fill's set_fragment_buffer"))?;
|
||||
encoder
|
||||
.set_fragment_buffer(Some(&self.shape), 0, 1)
|
||||
.map_err(fill("the sample fill's set_fragment_buffer"))?;
|
||||
encoder
|
||||
.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)
|
||||
.map_err(fill("the sample fill's draw_primitives"))?;
|
||||
encoder
|
||||
.end_encoding()
|
||||
.map_err(fill("the sample fill's end_encoding"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The multisampled texture of `literal` on `device`, made as the Metal oracle makes it: its
|
||||
/// type, pixel format, extent and samples, `Private` (Metal keeps no multisampled texture in
|
||||
/// shared memory), `usage` and `RenderTarget`; with the fill that writes the literal's bytes into
|
||||
/// it, for the command buffer that reads it.
|
||||
pub fn multisampled_texture_with(
|
||||
device: &Device,
|
||||
literal: &LiteralTexture,
|
||||
usage: TextureUsage,
|
||||
) -> Result<(Texture, SampleFill), CaseError> {
|
||||
let layout = literal.layout()?;
|
||||
let mut descriptor = texture_descriptor(literal, usage | TextureUsage::RENDER_TARGET)?;
|
||||
descriptor.sample_count = layout.sample_count.into();
|
||||
descriptor.resource_options = ResourceOptions::private();
|
||||
let texture = device
|
||||
.new_texture(&descriptor)
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"texture {}: new_texture",
|
||||
literal.binding
|
||||
)))?;
|
||||
let fill = SampleFill::new(device, &texture, literal.format, layout, &literal.bytes)?;
|
||||
Ok((texture, fill))
|
||||
}
|
||||
|
||||
/// One attachment's readback, encoded: the words its dispatch writes, read once the command
|
||||
/// buffer completed ([`SampleReadback::bytes`]).
|
||||
pub struct SampleReadback {
|
||||
words: Buffer,
|
||||
read: SampleRead,
|
||||
extent: [u32; 2],
|
||||
samples: u32,
|
||||
}
|
||||
|
||||
/// The unsigned view of a color attachment of `format` with the same components and bits, the
|
||||
/// fixture's kernel that packs a texel of it into words, and how many words it writes. Only the
|
||||
/// formats the fill writes ([`fill_function`]) are read.
|
||||
fn color_view(format: PixelFormat) -> Result<(PixelFormat, &'static str, usize), String> {
|
||||
use PixelFormat as P;
|
||||
Ok(match format {
|
||||
P::R8Unorm => (P::R8Uint, "rt6_read_words1", 1),
|
||||
P::RGBA8Unorm | P::RGBA8Uint | P::RGBA8Sint => (P::RGBA8Uint, "rt6_read_bytes4", 1),
|
||||
P::R16Float | P::R16Uint => (P::R16Uint, "rt6_read_words1", 1),
|
||||
P::RG16Float => (P::RG16Uint, "rt6_read_halves2", 1),
|
||||
P::RGBA16Float | P::RGBA16Uint | P::RGBA16Sint => (P::RGBA16Uint, "rt6_read_halves4", 2),
|
||||
P::R32Float | P::R32Uint | P::R32Sint => (P::R32Uint, "rt6_read_words1", 1),
|
||||
P::RG32Float => (P::RG32Uint, "rt6_read_words2", 2),
|
||||
P::RGBA32Float | P::RGBA32Uint | P::RGBA32Sint => (P::RGBA32Uint, "rt6_read_words4", 4),
|
||||
other => {
|
||||
return Err(format!(
|
||||
"a multisampled {other:?} attachment, which nothing fills"
|
||||
))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode into `command_buffer` the readback of every sample of `texture`, a multisampled
|
||||
/// attachment of `extent` and `samples`, read as `read`.
|
||||
pub fn encode(
|
||||
device: &Device,
|
||||
command_buffer: &CommandBuffer,
|
||||
texture: &Texture,
|
||||
read: SampleRead,
|
||||
extent: [u32; 2],
|
||||
samples: u32,
|
||||
) -> Result<SampleReadback, CaseError> {
|
||||
let (source, kernel) = match read {
|
||||
SampleRead::Color(_) => {
|
||||
let (view, kernel, words) = color_view(texture.pixel_format())?;
|
||||
if words != read.words() {
|
||||
return Err(format!(
|
||||
"{kernel} writes {words} words of a texel, the oracle's view {}",
|
||||
read.words()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let view = texture
|
||||
.new_texture_view(view)
|
||||
.map_err(CaseError::runtime(format!("{kernel}: new_texture_view")))?;
|
||||
(view, kernel)
|
||||
}
|
||||
SampleRead::Depth => (texture.clone(), "rt6_read_depth"),
|
||||
SampleRead::Stencil => (texture.clone(), "rt6_read_stencil"),
|
||||
};
|
||||
encode_through(
|
||||
device,
|
||||
command_buffer,
|
||||
&source,
|
||||
kernel,
|
||||
read,
|
||||
extent,
|
||||
samples,
|
||||
)
|
||||
}
|
||||
|
||||
/// Encode into `command_buffer` the readback of every sample of `source`, a multisampled texture
|
||||
/// or a view of one, of `extent` and `samples`, by the fixture's kernel `name`, which writes the
|
||||
/// words of `read`.
|
||||
pub fn encode_through(
|
||||
device: &Device,
|
||||
command_buffer: &CommandBuffer,
|
||||
source: &Texture,
|
||||
name: &'static str,
|
||||
read: SampleRead,
|
||||
extent: [u32; 2],
|
||||
samples: u32,
|
||||
) -> Result<SampleReadback, CaseError> {
|
||||
let function = library(device)?
|
||||
.new_function_with_name(name)
|
||||
.map_err(CaseError::helper(format!("function {name}")))?;
|
||||
let pipeline = device
|
||||
.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())
|
||||
.map_err(CaseError::helper(format!(
|
||||
"{name}: new_compute_pipeline_state"
|
||||
)))?;
|
||||
let length = readback_bytes(extent, samples, read)? as u64;
|
||||
let words = device
|
||||
.new_buffer(length, ResourceOptions::shared())
|
||||
.map_err(CaseError::runtime(format!("{name}: new_buffer")))?;
|
||||
let shape = shape(device, extent[0], samples)?;
|
||||
let mut encoder = command_buffer
|
||||
.compute_command_encoder()
|
||||
.map_err(CaseError::runtime(format!(
|
||||
"{name}: compute_command_encoder"
|
||||
)))?;
|
||||
let call = |what: &str| CaseError::runtime(format!("{name}: {what}"));
|
||||
encoder
|
||||
.set_compute_pipeline_state(&pipeline)
|
||||
.map_err(call("set_compute_pipeline_state"))?;
|
||||
encoder
|
||||
.set_texture(Some(source), 0)
|
||||
.map_err(call("set_texture"))?;
|
||||
encoder
|
||||
.set_buffer(Some(&words), 0, 0)
|
||||
.map_err(call("set_buffer"))?;
|
||||
encoder
|
||||
.set_buffer(Some(&shape), 0, 1)
|
||||
.map_err(call("set_buffer"))?;
|
||||
// One thread per sample, one per threadgroup: no grid edge to guard.
|
||||
encoder
|
||||
.dispatch_threadgroups(
|
||||
Size::new(extent[0].into(), extent[1].into(), samples.into()),
|
||||
Size::new(1, 1, 1),
|
||||
)
|
||||
.map_err(call("dispatch_threadgroups"))?;
|
||||
encoder.end_encoding().map_err(call("end_encoding"))?;
|
||||
Ok(SampleReadback {
|
||||
words,
|
||||
read,
|
||||
extent,
|
||||
samples,
|
||||
})
|
||||
}
|
||||
|
||||
impl SampleReadback {
|
||||
/// Every sample's bytes in the attachment layout, once the command buffer completed.
|
||||
pub fn bytes(&self) -> Result<Vec<u8>, CaseError> {
|
||||
let length = readback_bytes(self.extent, self.samples, self.read)? as u64;
|
||||
let words = read_buffer(&self.words, 0, length)?;
|
||||
Ok(unpack_words(&words, self.extent, self.samples, self.read)?)
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,9 @@
|
||||
//! "`<opcode>` is used in `<stages>` which is not supported in subgroupSupportedStages
|
||||
//! (`<stages>`).", read in Vulkan-ValidationLayers v1.4.357 (its library's strings), with the
|
||||
//! stages `[VK_SHADER_STAGE_VERTEX_BIT]` at `vkCreateShaderModule`, as the lanes saw it, or
|
||||
//! `VK_SHADER_STAGE_VERTEX_BIT`. A sink passes it only where the device's profile takes the
|
||||
//! deviation: the runtime lanes' sink once the runtime announced
|
||||
//! `Degradation::UnadvertisedVertexSimdgroups` (`runtime_case.rs`), the executor's context where
|
||||
//! the profile it opened takes the deviation (`platform/device.rs`). Every other subgroup-stage
|
||||
//! message, and this one anywhere else, still fails.
|
||||
//! `VK_SHADER_STAGE_VERTEX_BIT`. The executor's context's sink passes it only where the profile it
|
||||
//! opened takes the deviation (`platform/device.rs`). Every other subgroup-stage message, and this
|
||||
//! one anywhere else, still fails.
|
||||
|
||||
/// The message's id name.
|
||||
pub(crate) const ID_NAME: &str = "VUID-RuntimeSpirv-None-06343";
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
//! MoltenVK answers the query `sum of descriptorCount < maxPerSetDescriptors` (1212 on Apple's
|
||||
//! GPUs), though it encodes an update-after-bind set in a Metal argument buffer and runs one of
|
||||
//! 65536 elements and more as Metal runs the argument buffer
|
||||
//! (`RuntimeDriverDefect::SetLayoutSupportUnderstated`). The runtime makes a heap's set 1 there
|
||||
//! past that answer, announced (`Degradation::SetPastLayoutSupport`). The layer asks the query for
|
||||
//! (`RuntimeDriverDefect::SetLayoutSupportUnderstated`). The executor's context makes a heap's
|
||||
//! set 1 there past that answer (`platform/device.rs`). The layer asks the query for
|
||||
//! every layout past `maxPerSetDescriptors` and reports one it refuses, as Vulkan says it must
|
||||
//! (`VUID-vkCreateDescriptorSetLayout-support-09582`, "If the descriptor layout exceeds the limits
|
||||
//! reported through the physical device limits, then vkGetDescriptorSetLayoutSupport must have
|
||||
@@ -17,9 +17,9 @@
|
||||
//! vkGetDescriptorSetLayoutSupport which reported this layout is not supported", read in
|
||||
//! Vulkan-ValidationLayers 1.4.363 (`CoreChecks::ValidateDescriptorSetLayoutSupport`), at
|
||||
//! `vkCreateDescriptorSetLayout`, as the lanes saw it on MoltenVK 1.4.2, alone or after the
|
||||
//! layer's note on its last report (`duplicate_message_limit`). The runtime lanes' sink
|
||||
//! passes it only once the runtime announced `Degradation::SetPastLayoutSupport`
|
||||
//! (`runtime_case.rs`). Every other message, and this one before the notice, still fails.
|
||||
//! layer's note on its last report (`duplicate_message_limit`). The executor's context's sink
|
||||
//! passes it only on a device whose driver runs such a layout (`platform/device.rs`). Every other
|
||||
//! message, and this one anywhere else, still fails.
|
||||
|
||||
/// The message's id name.
|
||||
pub(crate) const ID_NAME: &str = "VUID-vkCreateDescriptorSetLayout-support-09582";
|
||||
|
||||
@@ -685,6 +685,7 @@ pub fn unsupported_source_requirements(
|
||||
) -> BTreeSet<ToolingRequirement> {
|
||||
let mut requirements = unsupported_reflection_requirements(reflection);
|
||||
requirements.extend(engine_source_requirements(reflection));
|
||||
requirements.extend(mesh::mesh_pipeline_requirement(reflection));
|
||||
requirements.extend(rate_map::rate_map_placement_requirement(
|
||||
source_ll, reflection,
|
||||
));
|
||||
@@ -843,7 +844,9 @@ pub fn checked_requirements(
|
||||
|
||||
/// Why the executor pair cannot evidence a case with `requirements`, or `None`: one that stops the
|
||||
/// Metal oracle leaves no observation to compare with, and one that stops the candidate leaves
|
||||
/// nothing to compare. A case both run is checkable. A requirement whose limit is Metal's own is
|
||||
/// nothing to compare, but for a requirement whose cases stay Metal-qualified
|
||||
/// ([`ToolingRequirement::qualifies_on_metal`]): such a case is checkable on Metal alone, and the
|
||||
/// candidate refuses it. A case both run is checkable. A requirement whose limit is Metal's own is
|
||||
/// named as such: no tooling can give the oracle that case.
|
||||
pub fn evidence_gap(requirements: &BTreeSet<ToolingRequirement>) -> Option<String> {
|
||||
fn joined(requirements: impl IntoIterator<Item = ToolingRequirement>) -> String {
|
||||
@@ -853,12 +856,6 @@ pub fn evidence_gap(requirements: &BTreeSet<ToolingRequirement>) -> Option<Strin
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
let names = |executor| {
|
||||
joined(ToolingRequirement::stopping(
|
||||
requirements.iter().copied(),
|
||||
executor,
|
||||
))
|
||||
};
|
||||
let (metal_limit, tooling): (Vec<_>, Vec<_>) =
|
||||
ToolingRequirement::stopping(requirements.iter().copied(), Executor::MetalOracle)
|
||||
.into_iter()
|
||||
@@ -880,7 +877,11 @@ pub fn evidence_gap(requirements: &BTreeSet<ToolingRequirement>) -> Option<Strin
|
||||
return Some(metal.join("; "));
|
||||
}
|
||||
let candidate = Executor::EngineCandidate;
|
||||
let stopped = names(candidate);
|
||||
let stopped = joined(
|
||||
ToolingRequirement::stopping(requirements.iter().copied(), candidate)
|
||||
.into_iter()
|
||||
.filter(|requirement| !requirement.qualifies_on_metal()),
|
||||
);
|
||||
(!stopped.is_empty()).then(|| format!("{candidate}: {stopped} (the candidate is stopped)"))
|
||||
}
|
||||
|
||||
@@ -2976,6 +2977,19 @@ entry:
|
||||
)
|
||||
);
|
||||
|
||||
// A mesh render pipeline's case stays Metal-qualified: the checker takes it, and the
|
||||
// candidate refuses it. Beside a requirement that stops the candidate outright, only that
|
||||
// one is named.
|
||||
assert_eq!(evidence_gap(&set(&[R::MeshRenderPipeline])), None);
|
||||
assert_eq!(
|
||||
evidence_gap(&set(&[R::MeshRenderPipeline, R::RenderDeviceBufferArray])).as_deref(),
|
||||
Some("engine_candidate: render_device_buffer_array (the candidate is stopped)")
|
||||
);
|
||||
assert_eq!(
|
||||
require_executor(&set(&[R::MeshRenderPipeline]), Executor::EngineCandidate),
|
||||
Err(set(&[R::MeshRenderPipeline]))
|
||||
);
|
||||
|
||||
let requirements = set(&[R::RenderDeviceBufferArray]);
|
||||
assert_eq!(
|
||||
require_executor(&requirements, Executor::EngineCandidate),
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
//! or case needs that the executors do not supply, decided from its reflected structure
|
||||
//! ([`ShaderInterface::mesh_stage`], its bindings) and, for a case, the stages its draw names
|
||||
//! ([`MeshDraw`]). Classification and the case checker read the one function,
|
||||
//! [`mesh_requirements`]. Both executors draw a mesh render pipeline: the Metal oracle
|
||||
//! (`metal::platform`) and the engine's candidate through the runtime (`runtime_case`).
|
||||
//! [`mesh_requirements`]. The Metal oracle draws a mesh render pipeline (`metal::platform`); the
|
||||
//! engine's candidate draws none ([`mesh_pipeline_requirement`]).
|
||||
//!
|
||||
//! - [`ToolingRequirement::MeshRenderPipeline`]: every object or mesh function's row or case, which
|
||||
//! the engine's candidate does not draw. Its cases stay Metal-qualified.
|
||||
//!
|
||||
//! - [`ToolingRequirement::MeshCompanion`]: a stage the pipeline needs that nothing supplies.
|
||||
//! Metal links a mesh render pipeline from an object function (optional), a mesh function, and a
|
||||
@@ -209,6 +212,15 @@ pub fn sets_mesh_outputs(source_ll: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// [`ToolingRequirement::MeshRenderPipeline`] for a row or case whose entry's reflection is
|
||||
/// `reflection`, where it is an object or mesh function: the engine's candidate draws no mesh
|
||||
/// render pipeline. Classification and the case checker read it with the source's other
|
||||
/// requirements (`executor_contract::unsupported_source_requirements`).
|
||||
pub fn mesh_pipeline_requirement(reflection: &ShaderInterface) -> Option<ToolingRequirement> {
|
||||
matches!(reflection.stage, ShaderStage::Object | ShaderStage::Mesh)
|
||||
.then_some(ToolingRequirement::MeshRenderPipeline)
|
||||
}
|
||||
|
||||
/// The mesh requirements of a row or case (`draw` `None` for a row) whose entry's reflection is
|
||||
/// `reflection`: [`ToolingRequirement::MeshCompanion`] where [`missing_stages`] names a stage.
|
||||
/// Empty for any other stage. An object function's threadgroup memory needs nothing: both
|
||||
@@ -550,5 +562,17 @@ mod tests {
|
||||
let reflection = inspect(&kernel, Stage::Kernel, "copy_word", &[]).unwrap();
|
||||
assert_eq!(reflection.mesh_stage, None);
|
||||
assert!(mesh_requirements(&kernel, &reflection, None).is_empty());
|
||||
assert_eq!(mesh_pipeline_requirement(&reflection), None);
|
||||
for (stage, entry) in [
|
||||
(Stage::Object, "mesh_draws_object"),
|
||||
(Stage::Mesh, "mesh_draws_mesh"),
|
||||
] {
|
||||
let (_, reflection) = reflected(&module, stage, entry);
|
||||
assert_eq!(
|
||||
mesh_pipeline_requirement(&reflection),
|
||||
Some(ToolingRequirement::MeshRenderPipeline),
|
||||
"{entry}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,11 +46,10 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Every device open goes through one of the functions that check the hang tripwire first:
|
||||
/// validation's Vulkan context, the Metal platform, the device validation makes through the
|
||||
/// runtime (`candidate::runtime_case::open_device`, the executor's runtime path's), and the new
|
||||
/// runtime's device in the player and in the replay tests, each after the tripwire check in its
|
||||
/// own file. A new raw open anywhere else in the crate fails here, before it can run, and so
|
||||
/// does a new-runtime open ahead of its check.
|
||||
/// validation's Vulkan context, the Metal platform, and the new runtime's device in the player
|
||||
/// and in the replay tests, each after the tripwire check in its own file. A new raw open
|
||||
/// anywhere else in the crate fails here, before it can run, and so does a new-runtime open
|
||||
/// ahead of its check.
|
||||
#[test]
|
||||
fn device_opens_exist_only_behind_the_tripwire_check() {
|
||||
let root = metal2vulkan_devtools::validation_dir();
|
||||
@@ -64,9 +63,6 @@ mod tests {
|
||||
concat!(".create_", "instance("),
|
||||
concat!(".enumerate_", "physical_devices("),
|
||||
concat!(".create_", "device("),
|
||||
// The runtime's own device creation (`metal2vulkan_runtime`).
|
||||
concat!("::system_", "default"),
|
||||
concat!("Device::", "all"),
|
||||
// The new runtime's device creation (`metal2vulkan_rt`).
|
||||
concat!("metal2vulkan_rt::Device", "::new("),
|
||||
];
|
||||
@@ -75,14 +71,12 @@ mod tests {
|
||||
("src/candidate/platform/device.rs", opens[3], 1),
|
||||
("src/candidate/platform/device.rs", opens[4], 1),
|
||||
("src/metal/platform.rs", opens[0], 1),
|
||||
("src/candidate/runtime_case.rs", opens[5], 1),
|
||||
("src/candidate/runtime_case.rs", opens[6], 1),
|
||||
// The new runtime's device: the player's and the replay tests'.
|
||||
("src/bin/command-replay.rs", opens[7], 1),
|
||||
("src/replay/rt_replay.rs", opens[7], 1),
|
||||
("src/bin/command-replay.rs", opens[5], 1),
|
||||
("src/replay/rt_replay.rs", opens[5], 1),
|
||||
];
|
||||
let checked = concat!("refuse_if", "_tripped(");
|
||||
for (file, open, _) in allowed.iter().filter(|(_, open, _)| *open == opens[7]) {
|
||||
for (file, open, _) in allowed.iter().filter(|(_, open, _)| *open == opens[5]) {
|
||||
let text = std::fs::read_to_string(root.join(file)).unwrap();
|
||||
let check = text.find(checked);
|
||||
assert!(
|
||||
|
||||
@@ -321,47 +321,6 @@ pub(crate) mod vulkan {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded waits on the Metal-like runtime's command buffers (`metal2vulkan_runtime`): the
|
||||
/// engine executor's runtime path.
|
||||
pub(crate) mod runtime {
|
||||
use super::{settle, CompletionSource, SubmissionBackend, WaitOutcome};
|
||||
use metal2vulkan_runtime::{CommandBuffer, CommandBufferError, CommandBufferStatus};
|
||||
use std::time::Duration;
|
||||
|
||||
struct Committed<'a>(&'a CommandBuffer);
|
||||
|
||||
impl CompletionSource for Committed<'_> {
|
||||
fn wait(&mut self, timeout: Duration) -> WaitOutcome {
|
||||
if self
|
||||
.0
|
||||
.wait_until_completed_for(timeout.min(super::MAX_WAIT_TIMEOUT))
|
||||
.is_err()
|
||||
{
|
||||
return WaitOutcome::TimedOut;
|
||||
}
|
||||
match (self.0.status(), self.0.error()) {
|
||||
(CommandBufferStatus::Completed, _) => WaitOutcome::Completed,
|
||||
(_, Some(CommandBufferError::DeviceLost)) => {
|
||||
WaitOutcome::SuspectedFault("the command buffer lost its device".into())
|
||||
}
|
||||
(status, error) => {
|
||||
WaitOutcome::Failed(format!("the command buffer ended {status:?}: {error:?}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for `command_buffer`, committed by `operation`, under the hang protocol. Returns
|
||||
/// only once its work is no longer in flight.
|
||||
pub(crate) fn wait_for_command_buffer(
|
||||
command_buffer: &CommandBuffer,
|
||||
backend: SubmissionBackend,
|
||||
operation: &str,
|
||||
) -> Result<(), String> {
|
||||
settle(&mut Committed(command_buffer), backend, operation)
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded waits on the new runtime's command buffers (`metal2vulkan_rt`): the replay player's
|
||||
/// backend over it. The runtime's own wait has no bound, so the wait is on the command buffer's
|
||||
/// completed handler, after the queue's wait hint has sent it. How the command buffer ended is the
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
pub mod acceptance;
|
||||
pub mod air;
|
||||
pub mod air_library;
|
||||
pub mod air_writer;
|
||||
pub mod authored_compile;
|
||||
pub mod bitcode_audit;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Object and mesh cases over the owned fixtures `engine/mesh_draws.ll` and
|
||||
//! `engine/mesh_barrier.ll`, each with what Metal drew for it: the words of Metal's own probe of
|
||||
//! the same functions (`runtime_lane::mesh_draws`'s answers, measured on the M3 Max and an M4
|
||||
//! alike), each mesh threadgroup covering one pixel of an 8x8 pass of two `RGBA32Uint` targets
|
||||
//! the same functions (measured on the M3 Max and an M4 alike), each mesh threadgroup covering one pixel of an 8x8 pass of two `RGBA32Uint` targets
|
||||
//! with the builtins it read, and the device write the M3 Max measured with rasterization off. A
|
||||
//! mesh case observed through the generated observer fragment reads what the fixture's own
|
||||
//! fragment function writes to its first target, so Metal's answer is the same words. An object
|
||||
@@ -9,8 +8,7 @@
|
||||
//! ([`crate::case::MeshObservation::Launch`]), and a mesh case under a generated object function
|
||||
//! draws the payload that function writes ([`crate::case::ObjectLaunch`]): those words follow from
|
||||
//! the fixture's source, and the Metal executor's test holds them to what the M3 Max drew.
|
||||
//! The Metal executor's tests (`metal::tests::mesh_draws`) hold the oracle to them, and the engine
|
||||
//! candidate's (`candidate::engine::runtime_run::tests`) hold the runtime's mesh path to them.
|
||||
//! The Metal executor's tests (`metal::tests::mesh_draws`) hold the oracle to them.
|
||||
|
||||
use crate::case::{AuthoredCase, Stage};
|
||||
use crate::source::SourceRow;
|
||||
|
||||
@@ -5,11 +5,10 @@ use crate::executor_contract::out_of_bounds::OutOfBoundsRun;
|
||||
use crate::hash::sha256_bytes;
|
||||
use crate::observation_contract::ComparisonClass;
|
||||
use base64::Engine as _;
|
||||
use metal2vulkan_runtime::Degradation;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The product's source fingerprint (`validation/product_fingerprint.rs`: the translator's sources,
|
||||
/// then the runtime crate's, and the dev-tools crate's, which assemble the public cases' bitcode).
|
||||
/// then the dev-tools crate's, which assemble the public cases' bitcode).
|
||||
/// Every candidate row's translator fingerprint is derived from it
|
||||
/// (`candidate::engine::engine_fingerprint`), so a row is current only for this product.
|
||||
pub const TRANSLATOR_FINGERPRINT: &str = env!("METAL2VULKAN_PRODUCT_FINGERPRINT");
|
||||
@@ -177,10 +176,6 @@ impl ReferenceGap {
|
||||
}
|
||||
}
|
||||
|
||||
/// The member of a candidate row's `environment` that holds the codes of the degrade notices its
|
||||
/// runtime device delivered ([`Degradation::code`]): a run through `metal2vulkan_runtime`.
|
||||
pub const RUNTIME_DEGRADES: &str = "runtime_degrades";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CandidateObservation {
|
||||
@@ -562,18 +557,6 @@ impl CandidateObservation {
|
||||
.decode(&dependencies.metal.output_b64)
|
||||
.is_ok_and(|golden| self.status_holds(dependencies.case, &golden))
|
||||
}
|
||||
|
||||
/// The degradations the row's run announced ([`RUNTIME_DEGRADES`]), read through the
|
||||
/// runtime's closed vocabulary ([`Degradation::from_code`]): a code it does not know (a
|
||||
/// retired kind's) is none of them.
|
||||
pub fn announced_degradations(&self) -> impl Iterator<Item = Degradation> + '_ {
|
||||
self.environment
|
||||
.get(RUNTIME_DEGRADES)
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|code| Degradation::from_code(code.as_str()?))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_hash(field: &str, value: &str) -> Result<(), String> {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The stream format, the address map and the player's order, on a backend that only keeps what it
|
||||
//! is asked (no device). The runtime backends' tests are device tests (`runtime_lane`).
|
||||
//! is asked (no device). The runtime backend's tests are device tests (`replay::rt_replay`).
|
||||
|
||||
use super::addresses::AddressMap;
|
||||
use super::compare::{compare_plays, shown_differences};
|
||||
|
||||
@@ -123,6 +123,16 @@ pub enum ToolingRequirement {
|
||||
/// Metal holds them and stops there; on a device with it, it runs. A case's data on the
|
||||
/// executing device raises it, never a source's structure, so no census row carries it.
|
||||
DepthOutsideUnitRange,
|
||||
/// An object or mesh function's row or case (`executor_contract::mesh`), or a case that runs a
|
||||
/// pipeline template of one: the engine's candidate draws no mesh render pipeline. The Metal
|
||||
/// oracle draws it, so a case of it stays Metal-qualified ([`Self::qualifies_on_metal`]).
|
||||
MeshRenderPipeline,
|
||||
/// A replayed pipeline template the engine's candidate does not replay
|
||||
/// (`candidate::engine::replay_templates`): a compute template that binds more than buffers
|
||||
/// and threadgroup memory or runs a stage input, or a render template that is not a
|
||||
/// rasterization-disabled vertex function binding buffers only. A case's templates raise it,
|
||||
/// never a source's structure, so no census row carries it.
|
||||
ReplayedTemplateResources,
|
||||
}
|
||||
|
||||
/// Every executor (the requirement leaves no case to author, or none to observe).
|
||||
@@ -130,7 +140,7 @@ const AUTHORING: &[Executor] = &Executor::ALL;
|
||||
const ENGINE: &[Executor] = &[Executor::EngineCandidate];
|
||||
|
||||
impl ToolingRequirement {
|
||||
pub const ALL: [Self; 23] = [
|
||||
pub const ALL: [Self; 25] = [
|
||||
Self::FunctionConstantLiteral,
|
||||
Self::VertexAttributeLiteral,
|
||||
Self::TessellationAttributeLiteral,
|
||||
@@ -154,6 +164,8 @@ impl ToolingRequirement {
|
||||
Self::KernelMinLodClamp,
|
||||
Self::MeshCompanion,
|
||||
Self::DepthOutsideUnitRange,
|
||||
Self::MeshRenderPipeline,
|
||||
Self::ReplayedTemplateResources,
|
||||
];
|
||||
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
@@ -183,6 +195,8 @@ impl ToolingRequirement {
|
||||
Self::KernelMinLodClamp => "kernel_min_lod_clamp",
|
||||
Self::MeshCompanion => "mesh_companion",
|
||||
Self::DepthOutsideUnitRange => "depth_outside_unit_range",
|
||||
Self::MeshRenderPipeline => "mesh_render_pipeline",
|
||||
Self::ReplayedTemplateResources => "replayed_template_resources",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +215,9 @@ impl ToolingRequirement {
|
||||
/// implementation's private layout where the engine's module decodes this crate's, and a
|
||||
/// depth outside `[0, 1]` a case gives a depth image, which its executor raises only on a
|
||||
/// device without `VK_EXT_depth_range_unrestricted`
|
||||
/// ([`ToolingRequirement::DepthOutsideUnitRange`]).
|
||||
/// ([`ToolingRequirement::DepthOutsideUnitRange`]), and a mesh render pipeline or a replayed
|
||||
/// template it does not draw or replay ([`ToolingRequirement::MeshRenderPipeline`],
|
||||
/// [`ToolingRequirement::ReplayedTemplateResources`]).
|
||||
///
|
||||
/// The requirements that stopped only the old engine's candidate were retired with it.
|
||||
pub const fn stops(self) -> &'static [Executor] {
|
||||
@@ -228,10 +244,21 @@ impl ToolingRequirement {
|
||||
| Self::VertexDepthStencilAttachment
|
||||
| Self::RasterizationDisabledRenderTarget
|
||||
| Self::RasterizationRateMapPlacement
|
||||
| Self::DepthOutsideUnitRange => ENGINE,
|
||||
| Self::DepthOutsideUnitRange
|
||||
| Self::MeshRenderPipeline
|
||||
| Self::ReplayedTemplateResources => ENGINE,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a case carrying this requirement is still a case to keep: the Metal oracle runs it
|
||||
/// and its observation is evidence for a candidate that runs the family again, so the checker
|
||||
/// accepts it with no candidate (`executor_contract::evidence_gap`), and the engine's candidate
|
||||
/// refuses it, typed. Only [`ToolingRequirement::MeshRenderPipeline`]: its cases are qualified
|
||||
/// on Metal.
|
||||
pub const fn qualifies_on_metal(self) -> bool {
|
||||
matches!(self, Self::MeshRenderPipeline)
|
||||
}
|
||||
|
||||
/// Whose limit this requirement records. Every requirement is this crate's tooling's except
|
||||
/// [`ToolingRequirement::KernelMinLodClamp`], which Apple's compiler cannot build a pipeline
|
||||
/// for.
|
||||
@@ -363,15 +390,28 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The mesh render pipeline's requirement: both executors draw one, an object function's
|
||||
/// threadgroup memory among it, so only a stage nothing generates stops them
|
||||
/// (`mesh_companion`), this crate's gap, never Metal's, which keeps the census open.
|
||||
/// The mesh render pipeline's requirements: a stage nothing generates stops both executors
|
||||
/// (`mesh_companion`), and the engine's candidate draws none (`mesh_render_pipeline`), whose
|
||||
/// cases stay Metal-qualified. Both are this crate's gaps, never Metal's, which keep the census
|
||||
/// open.
|
||||
#[test]
|
||||
fn mesh_requirements_stop_the_executors_that_do_not_draw_them_yet() {
|
||||
let requirement = ToolingRequirement::MeshCompanion;
|
||||
assert_eq!(requirement.stops(), Executor::ALL);
|
||||
assert_eq!(requirement.limit(), Limit::Tooling, "{requirement}");
|
||||
assert!(requirement.blocks_closure(), "{requirement}");
|
||||
assert!(!requirement.qualifies_on_metal(), "{requirement}");
|
||||
let requirement = ToolingRequirement::MeshRenderPipeline;
|
||||
assert_eq!(requirement.stops(), [Executor::EngineCandidate]);
|
||||
assert!(requirement.blocks_closure(), "{requirement}");
|
||||
assert!(requirement.qualifies_on_metal(), "{requirement}");
|
||||
assert_eq!(
|
||||
ToolingRequirement::ALL
|
||||
.into_iter()
|
||||
.filter(|requirement| requirement.qualifies_on_metal())
|
||||
.collect::<Vec<_>>(),
|
||||
[ToolingRequirement::MeshRenderPipeline]
|
||||
);
|
||||
}
|
||||
|
||||
/// Every requirement stops some executor, and an executor's name is as stable as a
|
||||
|
||||
@@ -19,8 +19,7 @@ use std::sync::OnceLock;
|
||||
|
||||
/// The product's source fingerprint (`validation/product_fingerprint.rs`): the translator's
|
||||
/// manifest, build inputs, and exactly the files it can compile or read (`build_support::
|
||||
/// product_hash`; a test-only module is not one), then the runtime crate's the same way, then the
|
||||
/// dev-tools crate's sources, whose `llvm-as` assembler gives a public row its bitcode. No file
|
||||
/// product_hash`; a test-only module is not one), then the dev-tools crate's sources, whose `llvm-as` assembler gives a public row its bitcode. No file
|
||||
/// under `validation/` feeds it.
|
||||
const PRODUCT_FINGERPRINT: &str = env!("METAL2VULKAN_PRODUCT_FINGERPRINT");
|
||||
|
||||
@@ -761,11 +760,6 @@ mod tests {
|
||||
write("metal2vulkan/build.rs", "fn main() {}\n");
|
||||
write("metal2vulkan/build_support.rs", "// fingerprint inputs\n");
|
||||
write("metal2vulkan/src/lib.rs", "pub fn translate() {}\n");
|
||||
write(
|
||||
"metal2vulkan-runtime/Cargo.toml",
|
||||
"[package]\nname = \"runtime\"\n",
|
||||
);
|
||||
write("metal2vulkan-runtime/src/lib.rs", "pub fn submit() {}\n");
|
||||
write(
|
||||
"metal2vulkan-devtools/Cargo.toml",
|
||||
"[package]\nname = \"devtools\"\n",
|
||||
@@ -850,17 +844,6 @@ mod tests {
|
||||
);
|
||||
write("metal2vulkan-devtools/src/lib.rs", "pub fn assemble() {}\n");
|
||||
assert_eq!(key(product()).fingerprint(), before.fingerprint());
|
||||
write(
|
||||
"metal2vulkan-runtime/src/lib.rs",
|
||||
"pub fn submit() { /* edited */ }\n",
|
||||
);
|
||||
assert_ne!(
|
||||
key(product()).fingerprint(),
|
||||
before.fingerprint(),
|
||||
"a runtime edit is an input"
|
||||
);
|
||||
write("metal2vulkan-runtime/src/lib.rs", "pub fn submit() {}\n");
|
||||
assert_eq!(key(product()).fingerprint(), before.fingerprint());
|
||||
write(
|
||||
"metal2vulkan/src/lib.rs",
|
||||
"pub fn translate() { /* edited */ }\n",
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::path::Path;
|
||||
/// bumps it says what changed; this comment keeps no history.
|
||||
macro_rules! analyzer_version {
|
||||
() => {
|
||||
"structural-triage-v82"
|
||||
"structural-triage-v83"
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1947,8 +1947,6 @@ entry:
|
||||
write("metal2vulkan/build.rs", "fn main() {}\n");
|
||||
write("metal2vulkan/build_support.rs", "\n");
|
||||
write("metal2vulkan/src/lib.rs", "pub fn translate() {}\n");
|
||||
write("metal2vulkan-runtime/Cargo.toml", "[package]\n");
|
||||
write("metal2vulkan-runtime/src/lib.rs", "pub fn submit() {}\n");
|
||||
write("metal2vulkan-devtools/Cargo.toml", "[package]\n");
|
||||
write("metal2vulkan-devtools/src/lib.rs", "pub fn assemble() {}\n");
|
||||
for input in &inputs {
|
||||
@@ -2004,17 +2002,6 @@ entry:
|
||||
);
|
||||
write("metal2vulkan-devtools/src/lib.rs", "pub fn assemble() {}\n");
|
||||
assert_eq!(key(analyzer_version!()), current);
|
||||
write(
|
||||
"metal2vulkan-runtime/src/lib.rs",
|
||||
"pub fn submit() { /* edited */ }\n",
|
||||
);
|
||||
assert_ne!(
|
||||
key(analyzer_version!()),
|
||||
current,
|
||||
"a runtime edit invalidates"
|
||||
);
|
||||
write("metal2vulkan-runtime/src/lib.rs", "pub fn submit() {}\n");
|
||||
assert_eq!(key(analyzer_version!()), current);
|
||||
write(
|
||||
"metal2vulkan/src/lib.rs",
|
||||
"pub fn translate() { /* edited */ }\n",
|
||||
@@ -2259,6 +2246,11 @@ define void @{name}(ptr addrspace(2) %ab, ptr addrspace(1) %out) {{
|
||||
.contains(&ToolingRequirement::MeshCompanion);
|
||||
let draw = classified.mesh_draw.expect("a mesh draw");
|
||||
assert_eq!(unresolved, !draw.missing.is_empty(), "{entry}");
|
||||
// The engine's candidate draws no mesh render pipeline.
|
||||
assert!(
|
||||
(classified.tooling_requirements).contains(&ToolingRequirement::MeshRenderPipeline),
|
||||
"{entry}"
|
||||
);
|
||||
draw
|
||||
};
|
||||
assert_eq!(
|
||||
@@ -2290,6 +2282,7 @@ define void @{name}(ptr addrspace(2) %ab, ptr addrspace(1) %out) {{
|
||||
);
|
||||
let fragment = classify(&entry_of("engine/mesh_draws.ll", "mesh_draws_fragment")).unwrap();
|
||||
assert_eq!(fragment.mesh_draw, None);
|
||||
assert!(!(fragment.tooling_requirements).contains(&ToolingRequirement::MeshRenderPipeline));
|
||||
}
|
||||
|
||||
/// A vertex function whose only effect is the indexed draw it encodes is observed by executing
|
||||
|
||||
@@ -231,12 +231,7 @@ pub fn release_free_memory() {
|
||||
}
|
||||
}
|
||||
|
||||
// Built with `--cfg m2v_system_alloc`, the lib test binary keeps the system allocator, as a
|
||||
// consumer's process does, so the runtime lanes' cost measurements (`draw_costs`, `commit_costs`,
|
||||
// `frame_costs`) pay no counting: each counted allocation takes a compare-and-swap loop and two
|
||||
// shared atomic maxima, 17% of the draw path's samples. Its counting tests are
|
||||
// left out there.
|
||||
#[cfg(all(test, not(m2v_system_alloc)))]
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -42,5 +42,4 @@ mod public_entry_rows;
|
||||
mod published_crates;
|
||||
mod replay_completion_mark;
|
||||
mod replay_range;
|
||||
mod swept_scratch;
|
||||
mod translation_l3_stage;
|
||||
@@ -1,47 +0,0 @@
|
||||
//! Where a lane's shader cache lives, and why that is the whole of the fix.
|
||||
//!
|
||||
//! A [`ScratchCache`] is removed when it drops, which covers a return and an unwind and covers
|
||||
//! neither a kill nor an exit that runs no destructor -- and lane processes are killed: a run gets
|
||||
//! cancelled, and the memory cap kills a worker and its whole process group. The caches used to be
|
||||
//! `$TMPDIR/m2v-lane-shader-cache-<pid>-<n>-<nanos>`, named for a process and recognisable to
|
||||
//! nothing, so each one a killed lane left stayed there for good: 900 to 2200 of them on a host.
|
||||
//!
|
||||
//! The fix is not a second removal somewhere; it is the path. A cache in the project's scratch
|
||||
//! root carries a lock the kernel releases when its owner dies, so the next run of any suite
|
||||
//! removes it, and removes no live run's
|
||||
//! ([`metal2vulkan_devtools::scratch`], whose own tests hold the sweep itself).
|
||||
|
||||
use metal2vulkan_validation::candidate::runtime_case::ScratchCache;
|
||||
|
||||
/// **A lane's shader cache is a path the next run can recognise**: in the scratch root, with a
|
||||
/// lock beside it. Put it back under the OS temp directory on its own and this test fails naming
|
||||
/// the directory it finds there, because nothing could ever sweep it.
|
||||
#[test]
|
||||
fn a_lane_shader_cache_lies_in_the_swept_scratch_root() {
|
||||
let root = metal2vulkan_devtools::scratch::root();
|
||||
let cache = ScratchCache::new().expect("a shader cache path");
|
||||
|
||||
assert_eq!(
|
||||
cache.path().parent(),
|
||||
Some(root.as_path()),
|
||||
"the lane's shader cache {} is not in the scratch root {}, so no run can sweep it after \
|
||||
this one is killed",
|
||||
cache.path().display(),
|
||||
root.display()
|
||||
);
|
||||
|
||||
let mut lock = cache.path().as_os_str().to_owned();
|
||||
lock.push(".lock");
|
||||
assert!(
|
||||
std::path::Path::new(&lock).is_file(),
|
||||
"{} has no lock beside it, so a sweep cannot tell its owner from a dead one",
|
||||
cache.path().display()
|
||||
);
|
||||
|
||||
// The device makes it, so the path is a path and nothing else until then.
|
||||
assert!(
|
||||
!cache.path().exists(),
|
||||
"{} was created, so it is not the empty cache a lane measures against",
|
||||
cache.path().display()
|
||||
);
|
||||
}
|
||||
Vendored
+1
-1
@@ -95,7 +95,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 556;
|
||||
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
|
||||
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
|
||||
/// keeps no history.
|
||||
pub const RUNTIME_VERSION: u32 = 2539;
|
||||
pub const RUNTIME_VERSION: u32 = 2540;
|
||||
|
||||
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
|
||||
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
|
||||
|
||||
Reference in new issue
Block a user