diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index afe92253e..6c8bd59d9 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2030,6 +2030,19 @@ degradations! { "the driver keeps its own cache of the device's pipelines beside the shader cache's \ records, with whatever it writes to disk and holds in memory for it; the pipelines \ made are the same"; + /// An entry of the device's shader cache directory was not written: the directory, a + /// temporary file in it or the rename over the entry failed, on the device's cache thread + /// or on the thread that handed the entry over past the queue's bound + /// (`shader_cache/store.rs`, `shader_cache/worker.rs`). A full or read-only directory, a + /// cap no entry fits in, or a write another process won. The work is never ended by it: + /// the pipeline state, the translation and the compile are the directory's regardless, and + /// the entry's absence costs only the next process that wants it. Announced once per + /// device; the payload names the directory, its cap and the largest entry it takes. Later + /// failures are counted alone + /// ([`ShaderCacheStatistics::write_failures`](crate::ShaderCacheStatistics::write_failures)). + ShaderCacheEntryNotWritten = "shader-cache-entry-not-written", Performance, + "what the entry would hold is made again by the next process that needs it; what this \ + process computes is unchanged"; /// A device made off macOS with no Metal level named: it answers as the newest measured /// release ([`MetalLevel::NEWEST`](crate::MetalLevel::NEWEST)), no release of the host's /// (`metal_level.rs`). Announced once, as the device is made; the payload names the level. diff --git a/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs b/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs index 283a535c0..4dc6ca5bd 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs @@ -197,7 +197,7 @@ impl Variant { .device .shared() .counts - .creation_pipeline_drawn(); + .creation_pipeline_drawn(crate::work_counts::Predicted::Dispatch); self.announce(key, formats); } } @@ -222,7 +222,10 @@ impl Variant { .pipeline(&key, Notices::FirstDraw) .map(|made| made.kept_at(&self.objects, kept::Place::Region(key.clone()))); if made.is_ok() { - device.shared().counts.creation_pipeline_made(); + device + .shared() + .counts + .creation_pipeline_made(crate::work_counts::Predicted::Dispatch); } drop(ticket.settle(made)); } diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 4ee3e2912..acb8b66f1 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -2847,7 +2847,7 @@ impl RenderVariant { .device .shared() .counts - .creation_pipeline_made(); + .creation_pipeline_made(crate::work_counts::Predicted::Render); } drop(ticket.settle(made)); })); @@ -2881,7 +2881,7 @@ impl RenderVariant { .device .shared() .counts - .creation_pipeline_drawn(); + .creation_pipeline_drawn(crate::work_counts::Predicted::Render); self.objects.device.degrade_specialized( &self.objects.specialized, specialization, diff --git a/crates/metal2vulkan-runtime/src/shader_cache/creation.rs b/crates/metal2vulkan-runtime/src/shader_cache/creation.rs index abdcf0d0a..257220f8d 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/creation.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/creation.rs @@ -24,7 +24,8 @@ //! `RenderPipelineReflection::to_bytes`: versions, kind, key, profile and checksum checked); a //! variant's pipeline key is a record of its own name and the key under a SHA-256 checksum. A //! lookup counts in no statistic but a refused or unreadable entry, and a write in none but a -//! failed one: they are not translations found, compiled or written. +//! failed one: they are not translations found, compiled or written. The write itself is the +//! device's cache thread's, as an artifact's is (`store.rs`, `worker.rs`). //! - **Bounded.** Each map keeps at most [`ENTRIES`] entries, the least recently used going first //! ([`Lru`]); the directory's entries go as every entry does, past its cap. They hold digests, //! small answers and reflections, and no AIR, library, or Vulkan object. @@ -108,7 +109,7 @@ impl ShaderCache { ) { let bytes = answers.to_bytes(key, compile); lock(&self.creation.linked).insert(*key, answers, 1); - self.keep_answer(EntryKind::LinkedAnswers, key.digest(), compile, &bytes); + self.keep_answer(EntryKind::LinkedAnswers, key.digest(), compile, bytes); } /// The key of the pipeline of the render descriptor of `key` on `compile` under `variant`, as @@ -153,7 +154,7 @@ impl ShaderCache { EntryKind::VariantPipeline, &name, compile, - &variant_record(&name, pipeline), + variant_record(&name, pipeline), ); } @@ -216,7 +217,7 @@ impl ShaderCache { ) -> RenderPipelineReflection { let bytes = reflection.to_bytes(key, compile); lock(&self.creation.reflections).insert(*key, reflection.clone(), 1); - self.keep_answer(EntryKind::RenderReflection, key.digest(), compile, &bytes); + self.keep_answer(EntryKind::RenderReflection, key.digest(), compile, bytes); reflection } @@ -224,14 +225,14 @@ impl ShaderCache { /// an artifact is written (the bytes counted against the directory's cap, the least recently /// used entries going past it), but counted as no entry written (it is no translation); a /// failed write is counted and said as an artifact's is. - fn keep_answer(&self, kind: EntryKind, key: &Hash256, compile: &CompileDevice, bytes: &[u8]) { + fn keep_answer(&self, kind: EntryKind, key: &Hash256, compile: &CompileDevice, bytes: Vec) { let name = entry_name( self.store.directory().build(), kind, key, &compile.profile_fingerprint(), ); - if self.store.write(&name, |out| out.write_all(bytes)).is_err() { + if self.store.write_soon(&name, bytes).is_err() { self.store.write_failed(); } if self.store.over_capacity() { diff --git a/crates/metal2vulkan-runtime/src/shader_cache/driver.rs b/crates/metal2vulkan-runtime/src/shader_cache/driver.rs index 5916ee29f..b37a710a8 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/driver.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/driver.rs @@ -39,9 +39,10 @@ //! when the cache is made (`RuntimeDriverDefect::PipelineCacheDataCompiledAtLoad`, MoltenVK) //! compiles from a record the making's own stages alone, which the making converts anyway without //! one; host steps and pool pieces load and save records as the program's threads do. -//! - **Makings at once.** A record is written to a temporary file renamed over it -//! (`Store::write_record`), so a reader reads the whole old record or the whole new one, never a -//! mix. Two processes, or two threads, making the same pipeline at once each write that +//! - **Makings at once.** A record is written to a temporary file renamed over it, by the +//! device's cache thread (`Store::write_record_soon`, `worker.rs`), so a reader reads the whole +//! old record or the whole new one, never a mix; a making that reads the record of one still +//! queued reads the queued bytes. Two processes, or two threads, making the same pipeline at once each write that //! pipeline's data from the same driver under the same name: the same bytes, or either one is //! fine. //! - **Cold on purpose.** A program that wants every pipeline compiled (a cold boot measured as @@ -392,7 +393,7 @@ fn keep( store.counters.refused(refusal); return; } - match store.write_record(name, &seal(identity, &data)) { + match store.write_record_soon(name, seal(identity, &data)) { Ok(_) => count(&store.counters.driver_saves), Err(_) => store.write_failed(), } diff --git a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs index 4b851742b..f3083eb73 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs @@ -28,8 +28,19 @@ //! recently used entries go first, and at device creation other builds' directories unused for //! 30 days go (`store.rs`, on the device's cache thread, `worker.rs`). A device's first removal //! past the cap and its first failed write are each said once as a warning -//! (`metal2vulkan-shader-cache-evicted`, `metal2vulkan-shader-cache-write-failed`) naming the -//! directory and its cap. +//! (`metal2vulkan-shader-cache-evicted`, and the degrade notice +//! [`Degradation::ShaderCacheEntryNotWritten`](crate::Degradation::ShaderCacheEntryNotWritten)) +//! naming the directory and its cap; neither ends any work. +//! - **Off the creating thread.** An entry's bytes are encoded by the creation that made it, +//! which needs their length for the memo's weighing, and the directory's write of them -- the +//! `mkdir`, the temporary file, the write and the `rename` -- is the device's cache thread's +//! (`worker.rs`). The queue is bounded at [`QUEUED_WRITES`](worker::QUEUED_WRITES) entries and +//! [`QUEUED_BYTES`](worker::QUEUED_BYTES) bytes; +//! a creation that meets either bound writes its entry itself, as every creation once did. A +//! queued entry answers this device's lookups from the queue, so nothing is compiled again for +//! want of a file not written yet, and what is queued when the device goes is written before its +//! drop returns. A process that ends without dropping its devices loses what is still queued: +//! at most the bound, and each of them an entry the next process compiles again. //! - **In memory first.** Before the directory, every lookup asks the device's memo //! (`pipeline/memo.rs`), which [`ShaderCacheOptions::memory_capacity`] bounds (256 MiB by //! default). An entry read or written here is kept there, weighed at its encoded length. @@ -37,7 +48,7 @@ mod creation; pub(crate) mod driver; pub(super) mod store; -mod worker; +pub(super) mod worker; use super::error::{invalid, Error, Problem, ShaderCacheError}; use super::pipeline::memo::PipelineMemo; @@ -54,7 +65,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::Ordering; use std::sync::Arc; use store::{count, entry_name, Directory, Lookup, Store}; -use worker::Worker; +use worker::{Asked, Worker}; /// The default cap of a cache directory, in bytes: 25 GiB. pub const DEFAULT_CAPACITY: u64 = 25 << 30; @@ -148,9 +159,26 @@ pub struct ShaderCacheStatistics { pub rejected: u64, /// Entries that could not be read. pub read_failures: u64, - /// Entries written. + /// Translations the directory was given: counted when a creation hands them over, which for + /// all but a write past the queue's bound is before the file exists. A write that then fails + /// counts in [`write_failures`](Self::write_failures) too. pub writes: u64, - /// Entries that could not be written. + /// Entries and records of every kind -- translations, a creation's answers, the driver's + /// pipeline cache data -- that the device's cache thread took, and the creating thread did + /// not write itself. + pub writes_queued: u64, + /// Those a thread of the program wrote itself, because the queue was at one of its bounds or + /// the entry was larger than the whole bound, or because the store has no cache thread. A + /// creation pays four journalled filesystem calls for each of these and none for a queued + /// one. + pub writes_on_thread: u64, + /// The bytes of every entry and record actually written, the driver's pipeline cache data + /// among them: what the directory was made to hold, whichever thread wrote it. + pub written_bytes: u64, + /// Lookups answered from an entry the cache thread had not written yet: a translation or + /// compile not run, counted in [`hits`](Self::hits) as a read of the file is. + pub queued_hits: u64, + /// Entries that could not be written, by whichever thread wrote them. pub write_failures: u64, /// Entries removed to keep the directory under its cap. pub evictions: u64, @@ -323,8 +351,9 @@ impl ShaderCache { directory, memory_capacity, } = setup; - let store = Arc::new(Store::new(directory, sink)); - let worker = Worker::start(Arc::clone(&store))?; + let asked = Arc::new(Asked::new()); + let store = Arc::new(Store::new(directory, sink, Some(Arc::clone(&asked)))); + let worker = Worker::start(Arc::clone(&store), asked)?; Ok(ShaderCache { memo: PipelineMemo::new(memory_capacity), creation: CreationMemo::new(), @@ -339,7 +368,7 @@ impl ShaderCache { }) } - /// Stop the cache thread: the device is going. + /// Stop the cache thread, which writes what is queued first: the device is going. pub(super) fn close(&self) { self.worker.stop(); } @@ -413,12 +442,11 @@ impl ShaderCache { compile: &metal2vulkan::device::Device, function: &CompiledFunction, ) -> u64 { - let bytes = function.to_bytes(); self.store( EntryKind::Function, function.key().digest(), compile, - &bytes, + function.to_bytes(), ) } @@ -440,12 +468,11 @@ impl ShaderCache { compile: &metal2vulkan::device::Device, pipeline: &ComputePipeline, ) -> u64 { - let bytes = pipeline.to_bytes(); self.store( EntryKind::ComputePipeline, pipeline.key().digest(), compile, - &bytes, + pipeline.to_bytes(), ) } @@ -467,12 +494,11 @@ impl ShaderCache { compile: &metal2vulkan::device::Device, pipeline: &RenderPipeline, ) -> u64 { - let bytes = pipeline.to_bytes(); self.store( EntryKind::RenderPipeline, pipeline.key().digest(), compile, - &bytes, + pipeline.to_bytes(), ) } @@ -506,13 +532,14 @@ impl ShaderCache { found } - /// Write `bytes` as the entry of `kind` under `key` for `compile`'s profile; their length. + /// Give `bytes` to the directory as the entry of `kind` under `key` for `compile`'s profile + /// (the cache thread writes it, `worker.rs`); their length. fn store( &self, kind: EntryKind, key: &Hash256, compile: &metal2vulkan::device::Device, - bytes: &[u8], + bytes: Vec, ) -> u64 { let counters = &self.store.counters; let name = entry_name( @@ -521,14 +548,15 @@ impl ShaderCache { key, &compile.profile_fingerprint(), ); - match self.store.write(&name, |out| out.write_all(bytes)) { + let length = bytes.len() as u64; + match self.store.write_soon(&name, bytes) { Ok(_) => count(&counters.writes), Err(_) => self.store.write_failed(), } if self.store.over_capacity() { self.worker.evict(); } - bytes.len() as u64 + length } /// The counts so far. @@ -541,6 +569,10 @@ impl ShaderCache { rejected: read(&counters.rejected), read_failures: read(&counters.read_failures), writes: read(&counters.writes), + writes_queued: read(&counters.writes_queued), + writes_on_thread: read(&counters.writes_on_thread), + written_bytes: read(&counters.written_bytes), + queued_hits: read(&counters.queued_hits), write_failures: read(&counters.write_failures), evictions: read(&counters.evictions), driver_loads: read(&counters.driver_loads), diff --git a/crates/metal2vulkan-runtime/src/shader_cache/store.rs b/crates/metal2vulkan-runtime/src/shader_cache/store.rs index 3bb89618b..1d49aa430 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/store.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/store.rs @@ -16,19 +16,26 @@ //! - A writer writes a temporary file beside the entry (named for the entry, the process and a //! sequence number), flushes it and renames it over the entry, so a reader never sees part of //! one. A temporary file a crashed writer left is removed by the next scan that finds it old. +//! - A device's writes go to its cache thread ([`Store::write_soon`], `worker.rs`): the same +//! bytes, the same temporary file and the same `rename`, off the creating thread. The queue is +//! bounded, an entry queued is visible to this device's lookups at once, and what is queued when +//! the device goes is written before its drop returns (`worker.rs` states the bound and what +//! happens at it). A store with no cache thread (the tests') writes on the calling thread. //! - Every scan that finds the directory past its cap removes the least recently used entries, //! by their access time, which a hit refreshes, down to [`LOW_WATER`] of the cap. At device //! creation the scan also removes other builds' directories that nothing used for //! [`UNUSED_BUILD`]. +use super::worker::{Asked, Write as Queued, QUEUED_BYTES}; use super::EntryKind; -use crate::{DebugMessage, MessageKind, MessageSeverity, MessageSink}; +use crate::{DebugMessage, Degradation, DegradeNotice, MessageKind, MessageSeverity, MessageSink}; use metal2vulkan::cache::Hash256; use sha2::{Digest, Sha256}; use std::fs; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::Arc; use std::time::{Duration, SystemTime}; /// The layout version of the directory's contents. @@ -147,7 +154,7 @@ pub(crate) fn entry_name( } /// `bytes` in lowercase hex. -pub(super) fn hex(bytes: &Hash256) -> String { +pub(crate) fn hex(bytes: &Hash256) -> String { use std::fmt::Write as _; let mut out = String::with_capacity(64); for byte in bytes { @@ -177,6 +184,8 @@ enum Found { Failed, /// The entry's bytes, and the open file (to refresh its access time on a hit). Bytes(Vec, fs::File), + /// The entry's bytes, from a write the cache thread has not made yet: no file to refresh. + Queued(Vec), } /// The counts behind [`ShaderCacheStatistics`](super::ShaderCacheStatistics). @@ -187,6 +196,10 @@ pub(crate) struct Counters { pub(crate) rejected: AtomicU64, pub(crate) read_failures: AtomicU64, pub(crate) writes: AtomicU64, + pub(crate) written_bytes: AtomicU64, + pub(crate) writes_queued: AtomicU64, + pub(crate) writes_on_thread: AtomicU64, + pub(crate) queued_hits: AtomicU64, pub(crate) write_failures: AtomicU64, pub(crate) evictions: AtomicU64, pub(crate) driver_loads: AtomicU64, @@ -225,11 +238,15 @@ pub(crate) struct Store { scanned: AtomicBool, /// The warnings said once each ([`Warnings`]). warnings: Warnings, + /// The device's cache thread, which writes the entries this store is given; `None` in a + /// store with no thread, which writes them on the calling thread. + asked: Option>, } /// What a device's store says once each, through its instance's message sink, else on stderr: /// its first removal of an entry past the cap ([`EVICTED`]), and its first entry not written -/// ([`WRITE_FAILED`]); later ones are counted alone. +/// (the degrade notice [`Degradation::ShaderCacheEntryNotWritten`]); later ones are counted +/// alone. struct Warnings { sink: Option, evicted: AtomicBool, @@ -239,12 +256,15 @@ struct Warnings { /// The id name of the warning of a store's first removal past its cap. const EVICTED: &str = "metal2vulkan-shader-cache-evicted"; -/// The id name of the warning of a store's first entry not written. -const WRITE_FAILED: &str = "metal2vulkan-shader-cache-write-failed"; - impl Store { - /// The store of `directory`, whose warnings go to `sink`, else on stderr. - pub(crate) fn new(directory: Directory, sink: Option) -> Store { + /// The store of `directory`, whose warnings go to `sink`, else on stderr, and whose writes + /// go to the cache thread `asked` asks (`worker.rs`); with no thread they are written on the + /// calling thread. + pub(crate) fn new( + directory: Directory, + sink: Option, + asked: Option>, + ) -> Store { Store { directory, counters: Counters::default(), @@ -255,31 +275,50 @@ impl Store { evicted: AtomicBool::new(false), write_failed: AtomicBool::new(false), }, + asked, } } - /// Count an entry not written (`ShaderCacheStatistics::write_failures`); the first is said - /// as a warning naming the directory and its cap. + /// Count an entry not written (`ShaderCacheStatistics::write_failures`); the first is + /// announced as [`Degradation::ShaderCacheEntryNotWritten`], naming the directory and its + /// cap. Never an error: the work the entry would have saved is the directory's regardless. pub(crate) fn write_failed(&self) { count(&self.counters.write_failures); if !self.warnings.write_failed.swap(true, Ordering::Relaxed) { - self.warn( - WRITE_FAILED, + let degradation = Degradation::ShaderCacheEntryNotWritten; + let root = self.directory.root().display(); + let reason = format!( + "the directory, a temporary file in it or the rename over the entry failed (cap \ + {} bytes, an entry at most {} bytes). This device's later failures are counted \ + alone (`ShaderCacheStatistics::write_failures`).", + self.directory.capacity, + self.entry_limit(), + ); + self.say( + degradation.code(), + Some(DegradeNotice { + degradation, + object: format!("the shader cache directory {root}"), + reason: reason.clone(), + cost: degradation.cost(), + object_id: None, + misplaced: None, + call: None, + }), format!( - "metal2vulkan: an entry of the shader cache directory {} (cap {} bytes, an \ - entry at most {} bytes) was not written: what it would hold is made again \ - by the next process. This device's later failures are counted alone \ - (`ShaderCacheStatistics::write_failures`).", - self.directory.root().display(), - self.directory.capacity, - self.entry_limit(), + "metal2vulkan: an entry of the shader cache directory {root} was not \ + written: {reason} {}", + degradation.cost(), ), ); } } - /// Say `text` as the warning `id_name`: through the sink, else on stderr. - fn warn(&self, id_name: &str, text: String) { + /// Say `text` as the notice `id_name`, carrying `degradation` where it announces one: through + /// the + /// sink, else on stderr. Called on a program's thread or on the cache thread; the sink runs + /// the program's code inside the exit guard's `program` either way. + fn say(&self, id_name: &str, degradation: Option, text: String) { let message = DebugMessage { severity: MessageSeverity::Warning, kind: MessageKind { @@ -289,7 +328,7 @@ impl Store { id_name: id_name.to_owned(), id: 0, text, - degradation: None, + degradation, }; match &self.warnings.sink { Some(sink) => sink.deliver(&message), @@ -325,58 +364,83 @@ impl Store { decode: impl FnOnce(Vec) -> Option, ) -> Lookup { let path = self.directory.record_path(name); - match self.read(&path) { - Found::Absent => Lookup::Absent, + let (bytes, file) = match self.read(&path) { + Found::Absent => return Lookup::Absent, Found::Failed => { count(&self.counters.read_failures); - Lookup::Unreadable + return Lookup::Unreadable; + } + Found::Bytes(bytes, file) => (bytes, Some(file)), + Found::Queued(bytes) => (bytes, None), + }; + match decode(bytes) { + Some(value) => { + self.accepted(file.as_ref()); + Lookup::Hit(value) + } + None => { + self.refused(&path); + Lookup::Rejected } - Found::Bytes(bytes, file) => match decode(bytes) { - Some(value) => { - touch(&file); - Lookup::Hit(value) - } - None => { - remove(&path); - count(&self.counters.rejected); - Lookup::Rejected - } - }, } } /// [`Store::load`] of the file at `path`. fn load_at(&self, path: &Path, decode: impl FnOnce(&[u8]) -> Result) -> Lookup { - match self.read(path) { - Found::Absent => Lookup::Absent, + let (bytes, file) = match self.read(path) { + Found::Absent => return Lookup::Absent, Found::Failed => { count(&self.counters.read_failures); - Lookup::Unreadable + return Lookup::Unreadable; + } + Found::Bytes(bytes, file) => (bytes, Some(file)), + Found::Queued(bytes) => (bytes, None), + }; + match decode(&bytes) { + Ok(value) => { + self.accepted(file.as_ref()); + Lookup::Hit(value) + } + Err(_) => { + self.refused(path); + Lookup::Rejected } - Found::Bytes(bytes, file) => match decode(&bytes) { - Ok(value) => { - touch(&file); - Lookup::Hit(value) - } - Err(_) => { - remove(path); - count(&self.counters.rejected); - Lookup::Rejected - } - }, } } - /// Write `bytes` as the record named `name` in the content directory, as an entry is - /// written, counted in no statistic but the bytes the directory holds. - pub(crate) fn write_record(&self, name: &str, bytes: &[u8]) -> io::Result { - self.write_at(&self.directory.record_path(name), name, |out| { - out.write_all(bytes) - }) + /// The contents a decoder accepted: a hit from `file` makes its entry the most recently used; + /// a hit from the queue (no file) is counted as one the directory had not written yet. + fn accepted(&self, file: Option<&fs::File>) { + match file { + Some(file) => touch(file), + None => count(&self.counters.queued_hits), + } } - /// Read the file at `path`. A file larger than any entry is removed and found absent. + /// The contents a decoder refused, at `path`: the entry is removed, and a write of it the + /// cache thread has not made is dropped rather than put in its place. + fn refused(&self, path: &Path) { + if let Some(asked) = &self.asked { + asked.discard(path); + } + remove(path); + count(&self.counters.rejected); + } + + /// Write `bytes` as the record named `name` in the content directory, as + /// [`Store::write_soon`] writes an entry: on the cache thread, counted in no statistic but + /// the bytes the directory holds. + pub(crate) fn write_record_soon(&self, name: &str, bytes: Vec) -> io::Result { + self.write_soon_at(self.directory.record_path(name), name, bytes) + } + + /// Read the file at `path`, or the bytes of a write of it the cache thread has not made yet + /// (`worker.rs`): its file is not in place until its `rename`, so the queue answers first. A + /// file larger than any entry is removed and found absent. fn read(&self, path: &Path) -> Found { + if let Some(bytes) = self.asked.as_ref().and_then(|asked| asked.pending(path)) { + return Found::Queued(bytes); + } let file = match fs::File::open(path) { Ok(file) => file, Err(error) if error.kind() == io::ErrorKind::NotFound => return Found::Absent, @@ -401,47 +465,71 @@ impl Store { } } - /// Write the entry named `name` from what `body` writes: a temporary file beside it, - /// flushed and renamed over it. The bytes written, or the failure (the temporary file is - /// removed). An entry larger than [`Store::entry_limit`] fails. - pub(crate) fn write( - &self, - name: &str, - body: impl FnOnce(&mut dyn Write) -> io::Result<()>, - ) -> io::Result { - self.write_at(&self.directory.entry_path(name), name, body) + /// Give `bytes` to the cache thread to write as the entry named `name` (`worker.rs`): the + /// same file and the same `rename`, off this thread. Their length, as a write of them gives + /// it; the failure of one this thread wrote itself, where the queue was at a bound. The + /// failure of a queued write is counted when the thread meets it, not here. + pub(crate) fn write_soon(&self, name: &str, bytes: Vec) -> io::Result { + self.write_soon_at(self.directory.entry_path(name), name, bytes) } - /// [`Store::write`] of the file at `path`, named `name`. - fn write_at( - &self, - path: &Path, - name: &str, - body: impl FnOnce(&mut dyn Write) -> io::Result<()>, - ) -> io::Result { + /// [`Store::write_soon`] of the file at `path`, named `name`. + fn write_soon_at(&self, path: PathBuf, name: &str, bytes: Vec) -> io::Result { + let length = bytes.len() as u64; + // An entry the queue could never hold whole is written here, as one past a bound is. + let takeable = length <= QUEUED_BYTES && length <= self.entry_limit(); + let Some(asked) = self.asked.as_ref().filter(|_| takeable) else { + count(&self.counters.writes_on_thread); + return self.write_at(&path, name, &bytes); + }; + match asked.queue(Queued::new(path, bytes)) { + None => { + count(&self.counters.writes_queued); + Ok(length) + } + Some(write) => { + count(&self.counters.writes_on_thread); + self.write_at(&write.path, name, &write.bytes) + } + } + } + + /// Write the entry at `path` that the cache thread took, counting a failure as the calling + /// thread's would be counted (`ShaderCacheStatistics::write_failures`). + pub(crate) fn write_queued(&self, path: &Path, bytes: &[u8]) { + let name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("entry"); + if self.write_at(path, name, bytes).is_err() { + self.write_failed(); + } + } + + /// Write `bytes` as the entry at `path`, named `name`, on the calling thread: a temporary + /// file beside it, flushed and renamed over it. The bytes written, or the failure (the + /// temporary file is removed). An entry larger than [`Store::entry_limit`] fails. + fn write_at(&self, path: &Path, name: &str, bytes: &[u8]) -> io::Result { + let length = bytes.len() as u64; + if length > self.entry_limit() { + return Err(io::Error::other("the entry is larger than the cache takes")); + } let parent = path.parent().expect("an entry has a directory"); create_private_dir_all(parent)?; let temporary = parent.join(format!(".{name}.{}.tmp", unique())); let written = (|| { - let file = new_private_file(&temporary)?; - let mut out = Limited { - inner: io::BufWriter::new(file), - written: 0, - limit: self.entry_limit(), - }; - body(&mut out)?; - let written = out.written; - let file = out - .inner - .into_inner() - .map_err(io::IntoInnerError::into_error)?; + let mut file = new_private_file(&temporary)?; + file.write_all(bytes)?; drop(file); fs::rename(&temporary, path)?; - Ok(written) + Ok(length) })(); match &written { Ok(bytes) => { self.used.fetch_add(*bytes, Ordering::Relaxed); + self.counters + .written_bytes + .fetch_add(*bytes, Ordering::Relaxed); } Err(_) => { let _ = fs::remove_file(&temporary); @@ -519,8 +607,9 @@ impl Store { if fs::remove_file(&entry.path).is_ok() { count(&self.counters.evictions); if !self.warnings.evicted.swap(true, Ordering::Relaxed) { - self.warn( + self.say( EVICTED, + None, format!( "metal2vulkan: the shader cache directory {} reached its cap of {} \ bytes (`ShaderCacheOptions::capacity`): its least recently used \ @@ -624,29 +713,6 @@ fn touch(file: &fs::File) { let _ = file.set_times(fs::FileTimes::new().set_accessed(SystemTime::now())); } -/// A writer that fails past `limit` bytes. -struct Limited { - inner: W, - written: u64, - limit: u64, -} - -impl Write for Limited { - fn write(&mut self, bytes: &[u8]) -> io::Result { - let after = self.written.saturating_add(bytes.len() as u64); - if after > self.limit { - return Err(io::Error::other("the entry is larger than the cache takes")); - } - let wrote = self.inner.write(bytes)?; - self.written += wrote as u64; - Ok(wrote) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} - /// A name no other writer uses: this process's id, a per-process sequence number, and the time. fn unique() -> String { static SEQUENCE: AtomicU64 = AtomicU64::new(0); diff --git a/crates/metal2vulkan-runtime/src/shader_cache/worker.rs b/crates/metal2vulkan-runtime/src/shader_cache/worker.rs index 735b5cb13..2c5c163f2 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/worker.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/worker.rs @@ -1,27 +1,65 @@ -//! The cache's background thread, one per device: the scan at device creation -//! ([`Store::sweep`]) and the scans that bring the directory back under its cap -//! ([`Store::evict`]), off every program's thread; nothing on a pipeline's or a command's path -//! waits for them. (The saves of the device's one driver cache it made, went with that cache; each -//! making now writes its own record, `driver.rs`.) +//! The cache's background thread, one per device: the entries the directory is given +//! ([`Store::write_queued`]), the scan at device creation ([`Store::sweep`]) and the scans that +//! bring the directory back under its cap ([`Store::evict`]), off every program's thread; nothing +//! on a pipeline's or a command's path waits for them. (The saves of the device's one driver cache +//! it made, went with that cache; each making now writes its own record, `driver.rs`.) +//! +//! - **What a creation hands over.** An entry's bytes are encoded on the creating thread, which +//! needs their length, and handed here as a [`Write`]: the `mkdir`, the temporary file, the +//! write and the `rename` are this thread's. The commit point is still the `rename`, so a reader +//! of another process reads the whole old entry or the whole new one. +//! - **Bounded.** The queue holds at most [`QUEUED_WRITES`] entries and [`QUEUED_BYTES`] bytes +//! together, the one being written included. A creation that meets either bound, or whose entry +//! is larger than the whole bound, writes it on its own thread, exactly as every creation did +//! before: the bound costs the creation its write, never the entry. +//! - **One write per name.** An entry queued again under a name already queued replaces its bytes +//! rather than queueing a second write, so two creations racing on one key leave one write and +//! one `rename`. +//! - **Visible at once.** A queued entry answers this device's lookups from the queue +//! ([`Asked::pending`]), so a lookup that would have read the file it has not written yet hits +//! rather than compiling again. +//! - **Drained when the device goes.** [`Worker::stop`] writes what is queued before the thread +//! ends, so an entry a creation handed over is on disk by the time the device's drop returns. +//! A process that ends without dropping its devices (`exit_guard`'s `end_at_once`) loses what is +//! still queued: at most the bound, each of them an entry the next process compiles again, as it +//! would have compiled anything this process had not reached yet. use super::store::Store; use crate::device::lock; use crate::error::{Error, MemoryKind}; use crate::exit_guard; +use std::collections::VecDeque; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::thread::JoinHandle; -/// The thread and what it is asked to do. -pub(super) struct Worker { - shared: Arc, - thread: Mutex>>, +/// The most entries the queue holds at once, the one being written included. +pub(crate) const QUEUED_WRITES: usize = 64; + +/// The most bytes the queue holds at once, the one being written included: 16 MiB. +pub(crate) const QUEUED_BYTES: u64 = 16 << 20; + +/// An entry to write: where it goes, and its bytes. +pub(crate) struct Write { + pub(crate) path: PathBuf, + pub(crate) bytes: Vec, } -struct Shared { +impl Write { + pub(crate) fn new(path: PathBuf, bytes: Vec) -> Write { + Write { path, bytes } + } +} + +/// What the cache thread is asked to do: the entries waiting to be written, and the scans. The +/// store holds it to queue writes and to answer lookups from the queue; the thread holds it to +/// take them. +pub(crate) struct Asked { work: Mutex, wake: Condvar, - /// Set when the device goes: a running scan stops early. + /// Set when the device goes: a running scan stops early. The queued writes are still + /// written. stop: AtomicBool, } @@ -29,64 +67,175 @@ struct Shared { struct Work { evict: bool, stopping: bool, + /// The entries queued, in the order they were handed over, at most [`QUEUED_WRITES`]. + queued: VecDeque>, + /// The one the thread is writing now, which lookups still see. + writing: Option>, + /// The bytes of `queued` and `writing` together, at most [`QUEUED_BYTES`]. + bytes: u64, } -impl Worker { - /// Start the thread over `store`. - pub(super) fn start(store: Arc) -> Result { - let shared = Arc::new(Shared { +impl Asked { + /// Nothing asked for yet. + pub(crate) fn new() -> Asked { + Asked { work: Mutex::new(Work::default()), wake: Condvar::new(), stop: AtomicBool::new(false), - }); + } + } + + /// Queue `write` for the thread, waking it; `Some(write)` where the queue is at a bound and + /// the caller writes it itself. An entry under a path already queued replaces its bytes. + pub(crate) fn queue(&self, write: Write) -> Option { + let length = write.bytes.len() as u64; + let mut work = lock(&self.work); + if let Some(at) = work + .queued + .iter() + .position(|queued| queued.path == write.path) + { + work.bytes = work.bytes - work.queued[at].bytes.len() as u64 + length; + work.queued[at] = Arc::new(write); + self.wake.notify_all(); + return None; + } + if work.queued.len() + usize::from(work.writing.is_some()) >= QUEUED_WRITES + || work.bytes + length > QUEUED_BYTES + { + return Some(write); + } + work.bytes += length; + work.queued.push_back(Arc::new(write)); + self.wake.notify_all(); + None + } + + /// The bytes of the entry queued for `path`, which the thread has not written yet: the one it + /// is writing now included, because its file is not in place until its `rename`. + pub(crate) fn pending(&self, path: &Path) -> Option> { + let work = lock(&self.work); + work.queued + .iter() + .rev() + .chain(work.writing.iter()) + .find(|write| write.path == path) + .map(|write| write.bytes.clone()) + } + + /// Drop the entry queued for `path`, where one is: its bytes are not the entry after all. + /// The one being written is past recall, and its file is removed by the caller. + pub(crate) fn discard(&self, path: &Path) { + let mut work = lock(&self.work); + if let Some(at) = work.queued.iter().position(|write| write.path == path) { + let gone = work.queued.remove(at).expect("the entry just found"); + work.bytes -= gone.bytes.len() as u64; + } + } + + /// The next entry to write, which stays visible to lookups until [`Asked::written`]. + fn take(&self) -> Option> { + let mut work = lock(&self.work); + let write = work.queued.pop_front()?; + work.writing = Some(Arc::clone(&write)); + Some(write) + } + + /// The entry the thread was writing is written (or failed): it is no longer the queue's. + fn written(&self) { + let mut work = lock(&self.work); + if let Some(done) = work.writing.take() { + work.bytes -= done.bytes.len() as u64; + } + } + + /// Ask for a scan that brings the directory under its cap. + fn evict(&self) { + lock(&self.work).evict = true; + self.wake.notify_all(); + } + + /// Ask the thread to end: it writes what is queued and returns. + pub(crate) fn stopping(&self) { + lock(&self.work).stopping = true; + self.wake.notify_all(); + } +} + +/// The thread and what it is asked to do. +pub(super) struct Worker { + asked: Arc, + thread: Mutex>>, +} + +impl Worker { + /// Start the thread over `store`, which was made with `asked`. + pub(super) fn start(store: Arc, asked: Arc) -> Result { let thread = { - let shared = Arc::clone(&shared); + let asked = Arc::clone(&asked); exit_guard::spawn( std::thread::Builder::new().name("metal2vulkan-shader-cache".into()), - move || run(&shared, &store), + move || run(&asked, &store), ) .map_err(|_| Error::OutOfMemory(MemoryKind::Host))? }; Ok(Worker { - shared, + asked, thread: Mutex::new(Some(thread)), }) } /// Ask for a scan that brings the directory under its cap. pub(super) fn evict(&self) { - lock(&self.shared.work).evict = true; - self.shared.wake.notify_all(); + self.asked.evict(); } - /// Stop the thread, and wait for it. + /// Stop the thread, and wait for it: the entries queued are written first. pub(super) fn stop(&self) { - self.shared.stop.store(true, Ordering::Relaxed); - lock(&self.shared.work).stopping = true; - self.shared.wake.notify_all(); + self.asked.stop.store(true, Ordering::Relaxed); + self.asked.stopping(); if let Some(handle) = lock(&self.thread).take() { let _ = handle.join(); } } } -/// The thread's loop. -fn run(shared: &Shared, store: &Store) { - store.sweep(&shared.stop); +/// Write every entry queued; whether the directory is past its cap after them. +pub(crate) fn drain(asked: &Asked, store: &Store) -> bool { + while let Some(write) = asked.take() { + store.write_queued(&write.path, &write.bytes); + asked.written(); + } + store.over_capacity() +} + +/// The thread's loop: the scan at creation, then the entries it is given and the scans it is +/// asked for, until [`Asked::stopping`], whose entries it writes before it returns. +pub(crate) fn run(asked: &Asked, store: &Store) { + store.sweep(&asked.stop); loop { + let asked_scan; { - let mut work = lock(&shared.work); - while !work.stopping && !work.evict { - work = shared + let mut work = lock(&asked.work); + while !work.stopping && !work.evict && work.queued.is_empty() { + work = asked .wake .wait(work) .unwrap_or_else(PoisonError::into_inner); } if work.stopping { + drop(work); + // The device is going: what a creation handed over is written before the drop + // that stops this thread returns. + drain(asked, store); break; } + asked_scan = work.evict; work.evict = false; } - store.evict(&shared.stop); + let over = drain(asked, store); + if asked_scan || over { + store.evict(&asked.stop); + } } } diff --git a/crates/metal2vulkan-runtime/src/tests/creation_prediction_kinds.rs b/crates/metal2vulkan-runtime/src/tests/creation_prediction_kinds.rs new file mode 100644 index 000000000..85c32c301 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/creation_prediction_kinds.rs @@ -0,0 +1,105 @@ +//! The two predictions a state's creation makes a `VkPipeline` for are counted apart: a render +//! state's predicted key (`pipeline/predicted.rs`) moves +//! `WorkCounts::creation_render_pipelines_made` alone, and a compute state's predicted region +//! (`pipeline/dispatch_making.rs`) moves `creation_dispatch_pipelines_made` alone. The whole +//! count is their sum. +//! +//! # Why this is a count +//! +//! The two predictions guess at very different things -- a render key the first draw will bind, +//! and a threadgroup the first dispatch will take -- and they are right at wildly different +//! rates. `creation_pipelines_made` and `creation_pipelines_drawn` cover both, so neither one's +//! hit rate can be read off them: a reading of 100 made and 60 drawn is as consistent with one +//! prediction always right and the other always wrong as with both being right three fifths of +//! the time. Splitting them makes each rate readable, and this holds the split to the kind of +//! state it belongs to. +//! +//! Both legs assert their own count moved before asserting the other's did not: a creation that +//! predicts nothing at all would read zero for both kinds and make the "the other kind did not +//! move" assertion vacuous. +//! +//! The assertion is a count, never a time: it is a fact of the structure, so it holds on any host +//! under any load. The device takes a shader cache directory of its own, empty, so no run reads a +//! pipeline an earlier run stored. +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are the owned fixtures +//! `validation/fixtures/public/engine/ubo_bind_offsets.ll` and +//! `validation/fixtures/public/examples/runtime_examples.ll` (`llvm-as`). + +use super::blit_holds::{device, Scratch}; +use super::descriptor_key_once::descriptor; +use crate::{PipelineOptions, WorkCounts}; +use std::path::Path; + +/// The two predictions' makings, and the whole count: render made, dispatch made, all made. +fn made(counts: &WorkCounts) -> [u64; 3] { + [ + counts.creation_render_pipelines_made, + counts.creation_dispatch_pipelines_made, + counts.creation_pipelines_made, + ] +} + +/// A render creation's predicted pipeline counts as the render prediction's and nothing else; a +/// compute creation's as the dispatch prediction's. The whole count is the two together. +#[test] +fn the_render_and_dispatch_predictions_are_counted_apart() { + let scratch = Scratch::new("creation-prediction-kinds"); + let device = device(&scratch.0); + let options = PipelineOptions::default(); + + let before = made(&device.work_counts()); + let _render = device + .new_render_pipeline_state(&descriptor(&device), &options) + .unwrap(); + let after_render = made(&device.work_counts()); + let moved = |from: [u64; 3], to: [u64; 3]| [to[0] - from[0], to[1] - from[1], to[2] - from[2]]; + let render = moved(before, after_render); + assert!( + render[0] > 0, + "a render creation must make its predicted pipeline at all, not {} times: a creation that \ + predicts nothing makes the dispatch count's zero below a vacuous zero", + render[0] + ); + assert_eq!( + render[1], 0, + "a render creation made {} pipeline(s) counted as a compute state's predicted region", + render[1] + ); + assert_eq!( + render[2], render[0], + "the whole count moved {} where the render prediction moved {}", + render[2], render[0] + ); + + let ll = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll"); + let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap(); + let function = device + .new_library_with_compile_library( + metal2vulkan::library::Library::from_air(&bitcode).unwrap(), + ) + .new_function_with_name("scale_and_offset") + .unwrap(); + let _compute = device + .new_compute_pipeline_state_with_function(&function, &options) + .unwrap(); + let after_compute = made(&device.work_counts()); + let compute = moved(after_render, after_compute); + assert!( + compute[1] > 0, + "a compute creation must make its predicted pipeline at all, not {} times", + compute[1] + ); + assert_eq!( + compute[0], 0, + "a compute creation made {} pipeline(s) counted as a render state's predicted key", + compute[0] + ); + assert_eq!( + compute[2], compute[1], + "the whole count moved {} where the dispatch prediction moved {}", + compute[2], compute[1] + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/degradation_codes.txt b/crates/metal2vulkan-runtime/src/tests/degradation_codes.txt index 7d2082f03..1948d73c3 100644 --- a/crates/metal2vulkan-runtime/src/tests/degradation_codes.txt +++ b/crates/metal2vulkan-runtime/src/tests/degradation_codes.txt @@ -178,6 +178,7 @@ metal2vulkan-degrade-sample-depth-clamp metal2vulkan-degrade-sample-planes metal2vulkan-degrade-separate-depth-stencil metal2vulkan-degrade-set-past-layout-support +metal2vulkan-degrade-shader-cache-entry-not-written metal2vulkan-degrade-shader-color-conversion metal2vulkan-degrade-shader-half-color-bits metal2vulkan-degrade-shader-resolve diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 622e4a22f..591d67611 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -48,6 +48,8 @@ mod copy_plan; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod cpu_copy_layouts; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod creation_prediction_kinds; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod deferred_calls; mod degradation; mod degradation_catalogue; @@ -212,6 +214,9 @@ mod sampler_cache_live; mod sampler_sets; mod scheduler; mod shader_cache; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod shader_cache_off_thread; +mod shader_cache_queue; mod shadow; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod shadow_host_writes; diff --git a/crates/metal2vulkan-runtime/src/tests/shader_cache.rs b/crates/metal2vulkan-runtime/src/tests/shader_cache.rs index 79ff8c529..201c10ac5 100644 --- a/crates/metal2vulkan-runtime/src/tests/shader_cache.rs +++ b/crates/metal2vulkan-runtime/src/tests/shader_cache.rs @@ -48,14 +48,36 @@ pub(super) const BUILD: [u8; 32] = [7; 32]; const OTHER_BUILD: [u8; 32] = [8; 32]; const NO_PROFILE: [u8; 32] = [0; 32]; -/// The store of `root` for `build`, with a cap of `capacity` bytes. +/// The store of `root` for `build`, with a cap of `capacity` bytes and no cache thread, so its +/// writes are the calling thread's. pub(super) fn store(root: &Path, build: [u8; 32], capacity: u64) -> Store { Store::new( Directory::open(root.to_path_buf(), build, capacity).expect("a usable directory"), None, + None, ) } +/// [`store`] with the queue `asked`, which nothing drains until a test does +/// (`tests::shader_cache_queue`). +pub(super) fn store_with_queue( + root: &Path, + build: [u8; 32], + capacity: u64, + asked: std::sync::Arc, +) -> Store { + Store::new( + Directory::open(root.to_path_buf(), build, capacity).expect("a usable directory"), + None, + Some(asked), + ) +} + +/// [`BUILD`] in the hex the directory names it by. +pub(super) fn hex_build() -> String { + crate::shader_cache::store::hex(&BUILD) +} + /// The identity of a made-up device `n`. fn identity(n: u32) -> Identity { Identity::new(0x1002, n, 7, [n as u8; 16]) @@ -81,9 +103,7 @@ fn name(build: &[u8; 32], n: u32) -> String { /// Write device `n`'s framed `payload` under `name`. fn put(store: &Store, name: &str, n: u32, payload: &[u8]) { let framed = seal(&identity(n), &data(n, payload)); - store - .write(name, |out| out.write_all(&framed)) - .expect("a write"); + store.write_soon(name, framed).expect("a write"); } /// Look up device `n`'s entry under `name`. @@ -267,7 +287,7 @@ fn the_cap_removes_the_least_recently_used_records_with_the_entries() { let framed = seal(&identity(n), &data(n, &payload)); // Even ones are makings' records, odd ones the build's entries. let path = if n % 2 == 0 { - store.write_record(&wanted, &framed).expect("a write"); + store.write_record_soon(&wanted, framed).expect("a write"); store.directory().record_path(&wanted) } else { put(&store, &wanted, n, &payload); @@ -311,12 +331,12 @@ fn the_first_eviction_and_the_first_failed_write_are_each_said_once() { }); let directory = Directory::open(scratch.path().to_path_buf(), BUILD, capacity).expect("a usable directory"); - let store = Store::new(directory, Some(sink)); + let store = Store::new(directory, Some(sink), None); for round in 0..2u32 { for n in 0..6u32 { let wanted = name(&BUILD, 10 * round + n); store - .write_record(&wanted, &seal(&identity(n), &data(n, &payload))) + .write_record_soon(&wanted, seal(&identity(n), &data(n, &payload))) .expect("a write"); } store.evict(&AtomicBool::new(false)); @@ -330,7 +350,7 @@ fn the_first_eviction_and_the_first_failed_write_are_each_said_once() { ids, [ "metal2vulkan-shader-cache-evicted", - "metal2vulkan-shader-cache-write-failed" + crate::Degradation::ShaderCacheEntryNotWritten.code() ] ); let root = scratch.path().display().to_string(); @@ -620,7 +640,7 @@ fn a_making_s_record_is_named_by_what_it_reads_and_crosses_builds() { let scratch = Scratch::new(); let one = identity(1); store(scratch.path(), BUILD, 1 << 20) - .write_record(&base, &seal(&one, &data(1, b"payload"))) + .write_record_soon(&base, seal(&one, &data(1, b"payload"))) .expect("a write"); let other = store(scratch.path(), OTHER_BUILD, 1 << 20); let found = other.load_content(&base, |bytes| { @@ -657,7 +677,7 @@ fn a_record_of_another_device_is_refused_and_removed() { seal(&identity(2), &data(2, b"payload")), seal(&one, &data(2, b"payload")), ] { - store.write_record(&name, &framed).expect("a write"); + store.write_record_soon(&name, framed).expect("a write"); let found = store.load_content(&name, |bytes| open(&one, &bytes).map(|_| ())); assert_eq!(found, Lookup::Rejected); assert!(!path.exists(), "the refused record was removed"); diff --git a/crates/metal2vulkan-runtime/src/tests/shader_cache_off_thread.rs b/crates/metal2vulkan-runtime/src/tests/shader_cache_off_thread.rs new file mode 100644 index 000000000..e5cdc6230 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/shader_cache_off_thread.rs @@ -0,0 +1,158 @@ +//! A render pipeline state's creation hands its cache entries to the device's cache thread and +//! writes no file itself, and the entries it handed over are on disk once the device has gone. +//! +//! # Why this is a count +//! +//! Every creation wrote two entries on its own thread: the pipeline artifact +//! (`store_render_pipeline`) and the record naming the pipeline key of its descriptor's variant +//! (`keep_variant_pipeline`). Each was a `mkdir`, a temporary file, a write and a `rename` -- +//! four journalled filesystem calls -- and over a sweep of states differing only in fixed-function +//! state, where every descriptor is distinct, nothing in the process ever reads either back. The +//! entries are still written, under the same names and committed by the same `rename`; the +//! creating thread no longer waits for them. +//! +//! The assertion is a count of writes, never a time: a count is a fact of the structure, so it +//! holds on any host under any load, and the figure this run would give for the time saved would +//! be a figure of this host's filesystem under this host's load. `writes` is the floor that keeps +//! a pass from being vacuous: a sweep that writes nothing at all would read zero queued writes and +//! zero writes of its own alike. +//! +//! The second test is the durability half, and it is what makes the move honest: a second device +//! over the first one's directory must find every entry the first one's creations handed over, so +//! `Worker::stop` writes what is queued before the cache thread ends. Without that drain a queued +//! entry would be lost whenever a device went while its thread was behind, and a cross-process +//! cache hit would turn into a silent miss. +//! +//! Each test owns an empty cache directory, removed first and removed again when dropped, so no +//! run reads what an earlier run left. +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are the owned fixture +//! `validation/fixtures/public/engine/ubo_bind_offsets.ll` (`llvm-as`). + +use super::blit_holds::device; +use super::descriptor_key_once::descriptor; +use crate::{PipelineOptions, ShaderCacheStatistics}; +use metal2vulkan::metal::{BlendFactor, BlendOperation}; +use std::path::{Path, PathBuf}; + +/// The states each sweep makes. +const SWEEP: u64 = 16; + +/// Blend factors no two of which make one pipeline: each state is its own descriptor, so each +/// writes its own entries. +const FACTORS: [BlendFactor; 8] = [ + BlendFactor::Zero, + BlendFactor::One, + BlendFactor::SourceColor, + BlendFactor::OneMinusSourceColor, + BlendFactor::SourceAlpha, + BlendFactor::OneMinusSourceAlpha, + BlendFactor::DestinationColor, + BlendFactor::DestinationAlpha, +]; + +/// An empty directory the test owns: removed before it is made, and when dropped. +struct Fresh(PathBuf); + +impl Fresh { + fn new(leg: &str) -> Fresh { + let path = + std::env::temp_dir().join(format!("m2v-cache-off-thread-{leg}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Fresh(path) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for Fresh { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Make [`SWEEP`] render states of one function pair on a device over `cache`, differing only in +/// their blend factors; the device's cache statistics once they are made. The device is gone when +/// this returns, so its cache thread has written what it was handed. +fn sweep(cache: &Path) -> ShaderCacheStatistics { + let device = device(cache); + let base = descriptor(&device); + let options = PipelineOptions::default(); + let mut kept = Vec::with_capacity(SWEEP as usize); + for i in 0..SWEEP { + let mut d = base.clone(); + let color = d.color_attachments[0] + .as_mut() + .expect("the fixture's target"); + color.blending_enabled = true; + color.source_rgb_blend_factor = FACTORS[(i % 8) as usize]; + color.destination_rgb_blend_factor = FACTORS[(i / 8 % 8) as usize]; + color.rgb_blend_operation = BlendOperation::Add; + kept.push(device.new_render_pipeline_state(&d, &options).unwrap()); + } + let made = device.shader_cache_statistics(); + drop(kept); + drop(device); + made +} + +/// Every cache entry a render sweep's creations hand over goes to the device's cache thread: the +/// creating thread makes no directory, no temporary file and no `rename`. +#[test] +fn a_render_sweep_writes_no_cache_file_on_its_creating_thread() { + let fresh = Fresh::new("sweep"); + let made = sweep(fresh.path()); + assert!( + made.writes_queued > 0, + "the sweep must hand cache entries over at all, not {}: a sweep that writes nothing reads \ + zero writes on its own thread for the same reason", + made.writes_queued + ); + assert_eq!( + (made.writes_on_thread, made.write_failures), + (0, 0), + "the entries the creating threads wrote themselves, and the failures: {made:?}" + ); + println!( + "shader cache off the creating thread: {SWEEP} render creations handed over {} entries \ + and records, {} of them translations, {} bytes written, {} written by a creating thread; \ + {} lookups hit, {} of them from the queue, {} missed", + made.writes_queued, + made.writes, + made.written_bytes, + made.writes_on_thread, + made.hits, + made.queued_hits, + made.misses + ); +} + +/// A second device over the first one's directory finds every artifact the first one's creations +/// handed to its cache thread: the thread writes what is queued before it ends, so a device going +/// while it is behind loses nothing. +#[test] +fn the_entries_a_device_handed_over_are_on_disk_once_it_has_gone() { + let fresh = Fresh::new("across-devices"); + let first = sweep(fresh.path()); + assert!( + first.writes > 0 && first.hits == 0 && first.writes_on_thread == 0, + "the first device must hand every artifact to its cache thread and read none: {first:?}" + ); + let second = sweep(fresh.path()); + assert_eq!( + (second.misses, second.writes, second.write_failures), + (0, 0, 0), + "the second device compiled or wrote something the first one had already stored: \ + {second:?}" + ); + assert_eq!( + (second.hits, second.queued_hits), + (SWEEP, 0), + "every state of the second device's sweep must find its pipeline in the first one's \ + directory, read from its file and not from a queue of its own: {second:?}" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/shader_cache_queue.rs b/crates/metal2vulkan-runtime/src/tests/shader_cache_queue.rs new file mode 100644 index 000000000..6edb16911 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/shader_cache_queue.rs @@ -0,0 +1,212 @@ +//! The shader cache's queue of writes (`shader_cache/worker.rs`): what a creation hands to the +//! device's cache thread, what the queue answers meanwhile, and what happens at its bounds. The +//! store here has the queue but no thread, so the test drains it itself and nothing depends on +//! when a thread would have run. +//! +//! The entries are the driver's pipeline cache frames, as `tests::shader_cache`'s are, and each +//! test owns an empty directory it removes. + +use super::shader_cache::{store_with_queue, Scratch, BUILD}; +use crate::shader_cache::store::{entry_name, Lookup, Store}; +use crate::shader_cache::worker::{drain, run, Asked, QUEUED_BYTES, QUEUED_WRITES}; +use crate::shader_cache::EntryKind; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering; +use std::sync::Arc; + +const NO_PROFILE: [u8; 32] = [0; 32]; + +/// The entry name of the made-up key `n`. +fn name(n: u32) -> String { + entry_name(&BUILD, EntryKind::PipelineData, &[n as u8; 32], &NO_PROFILE) +} + +/// `length` bytes whose first says which entry they are. +fn bytes(n: u32, length: usize) -> Vec { + let mut made = vec![0x5a; length]; + made[0] = n as u8; + made +} + +/// The entry named `name` under `root` for [`BUILD`]. +fn path(root: &Path, name: &str) -> PathBuf { + root.join("v1") + .join(super::shader_cache::hex_build()) + .join(&name[..2]) + .join(name) +} + +/// The store of `root` with a queue of its own, and the queue. +fn queued(root: &Path) -> (Store, Arc) { + let asked = Arc::new(Asked::new()); + ( + store_with_queue(root, BUILD, 1 << 30, Arc::clone(&asked)), + asked, + ) +} + +/// Every byte of the entry named `name`, read back as the store reads it. +fn read(store: &Store, name: &str) -> Option> { + match store.load(name, |read: &[u8]| Ok::, ()>(read.to_vec())) { + Lookup::Hit(found) => Some(found), + Lookup::Absent | Lookup::Unreadable | Lookup::Rejected => None, + } +} + +/// A queued entry is not on disk until the queue is drained, and the store's own lookup finds it +/// from the queue meanwhile: a creation whose entry is still queued never compiles it again. The +/// drain leaves the file and no temporary beside it. +#[test] +fn a_queued_entry_answers_lookups_before_its_file_exists() { + let scratch = Scratch::new(); + let (store, asked) = queued(scratch.path()); + let name = name(1); + let wanted = bytes(1, 512); + assert_eq!(store.write_soon(&name, wanted.clone()).unwrap(), 512); + let at = path(scratch.path(), &name); + assert!(!at.exists(), "the queued entry's file is not written yet"); + assert_eq!( + read(&store, &name).as_deref(), + Some(wanted.as_slice()), + "the queue answers the lookup" + ); + assert_eq!(store.counters.queued_hits.load(Ordering::Relaxed), 1); + assert_eq!(store.counters.writes_queued.load(Ordering::Relaxed), 1); + assert_eq!(store.counters.written_bytes.load(Ordering::Relaxed), 0); + drain(&asked, &store); + assert_eq!(fs::read(&at).unwrap(), wanted, "the drain wrote the entry"); + assert_eq!(store.counters.written_bytes.load(Ordering::Relaxed), 512); + let group: Vec = fs::read_dir(at.parent().unwrap()) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!( + group, + std::slice::from_ref(&name), + "the rename left no temporary file" + ); + // Drained, the lookup reads the file: no second queued hit. + assert_eq!(read(&store, &name).as_deref(), Some(wanted.as_slice())); + assert_eq!(store.counters.queued_hits.load(Ordering::Relaxed), 1); +} + +/// Two writes under one name leave one queued write, the later bytes: one drain writes the second +/// and the queue is then empty, where two queued writes would have left the first behind. Two +/// creations racing on one key therefore leave one file and one `rename`. +#[test] +fn a_second_write_under_one_name_replaces_the_queued_one() { + let scratch = Scratch::new(); + let (store, asked) = queued(scratch.path()); + let name = name(2); + store.write_soon(&name, bytes(2, 64)).unwrap(); + let second = bytes(3, 96); + store.write_soon(&name, second.clone()).unwrap(); + assert_eq!( + read(&store, &name).as_deref(), + Some(second.as_slice()), + "the queue holds the later bytes" + ); + drain(&asked, &store); + let at = path(scratch.path(), &name); + assert_eq!(fs::read(&at).unwrap(), second); + assert_eq!( + store.counters.written_bytes.load(Ordering::Relaxed), + 96, + "one write of the later bytes, not two" + ); +} + +/// Past the queue's count bound a creation writes its entry itself, at once, and so does one +/// whose entry is larger than the whole bound: the bound costs a creation its own write, never +/// the entry. +#[test] +fn a_creation_past_the_bound_writes_its_entry_itself() { + let scratch = Scratch::new(); + let (store, asked) = queued(scratch.path()); + for n in 0..QUEUED_WRITES as u32 { + let name = name(n); + store.write_soon(&name, bytes(n, 32)).unwrap(); + assert!(!path(scratch.path(), &name).exists(), "entry {n} is queued"); + } + let over = name(QUEUED_WRITES as u32); + store.write_soon(&over, bytes(7, 32)).unwrap(); + assert!( + path(scratch.path(), &over).exists(), + "the entry past the count bound is written by its own caller" + ); + assert_eq!( + store.counters.writes_queued.load(Ordering::Relaxed), + QUEUED_WRITES as u64 + ); + // A single entry larger than the whole byte bound is never queued either. + let (store, _asked) = queued(scratch.path()); + let large = name(200); + let length = usize::try_from(QUEUED_BYTES).unwrap() + 1; + store.write_soon(&large, bytes(200, length)).unwrap(); + assert!( + path(scratch.path(), &large).exists(), + "an entry larger than the queue's whole bound is written by its own caller" + ); + assert_eq!(store.counters.writes_queued.load(Ordering::Relaxed), 0); + drop(asked); +} + +/// A decoder that refuses a queued entry's bytes drops the queued write rather than letting the +/// cache thread put them in place: the drain writes nothing, and the lookup is a refusal. +#[test] +fn a_refused_queued_entry_is_never_written() { + let scratch = Scratch::new(); + let (store, asked) = queued(scratch.path()); + let name = name(4); + store.write_soon(&name, bytes(4, 128)).unwrap(); + let refused = store.load(&name, |_: &[u8]| Err::<(), ()>(())); + assert_eq!(refused, Lookup::Rejected); + drain(&asked, &store); + assert!( + !path(scratch.path(), &name).exists(), + "the refused bytes were never written" + ); + assert_eq!(store.counters.written_bytes.load(Ordering::Relaxed), 0); +} + +/// The cache thread writes what is queued before it ends, so an entry a creation handed over is on +/// disk once the device's drop has stopped the thread. Asked to stop before its loop ever waits, +/// the thread still writes every queued entry and leaves no temporary file. +/// +/// The stop is asked for before the loop runs, so nothing here depends on a thread keeping up or +/// falling behind: a loop that did not write at the stop would leave the files absent on every +/// host. (A device test cannot hold this: its cache thread drains the queue long before the device +/// goes, so the files are there whether or not the stop writes them.) +#[test] +fn the_thread_writes_what_is_queued_before_it_ends() { + let scratch = Scratch::new(); + let (store, asked) = queued(scratch.path()); + let names: Vec = (10..14).map(name).collect(); + for (n, name) in names.iter().enumerate() { + store.write_soon(name, bytes(n as u32, 256)).unwrap(); + assert!(!path(scratch.path(), name).exists(), "{name} is queued"); + } + asked.stopping(); + run(&asked, &store); + for (n, name) in names.iter().enumerate() { + let at = path(scratch.path(), name); + assert_eq!( + fs::read(&at).ok().as_deref(), + Some(bytes(n as u32, 256).as_slice()), + "the stop wrote {name}" + ); + let group: Vec = fs::read_dir(at.parent().unwrap()) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert!( + group.iter().all(|found| !found.starts_with('.')), + "the stop left a temporary file: {group:?}" + ); + } + assert_eq!( + store.counters.written_bytes.load(Ordering::Relaxed), + 256 * names.len() as u64 + ); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 684a9aac5..2df422add 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -22,6 +22,19 @@ use std::sync::Mutex; /// `shadow_texels_recopied_in_large_surfaces`): 2^20, which a 1920x1080 framebuffer's exceed. const LARGE_SURFACE_TEXELS: u64 = 1 << 20; +/// Which of the two predictions a `VkPipeline` a state's creation made belongs to +/// (`WorkCounts::creation_render_pipelines_made`, `creation_dispatch_pipelines_made`): the render +/// state's predicted key (`pipeline/predicted.rs`) or the compute state's predicted region +/// (`pipeline/dispatch_making.rs`). The two are counted apart because their hit rates differ by +/// orders of magnitude, and the whole count cannot tell them apart. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Predicted { + /// A render state's predicted key. + Render, + /// A compute state's predicted region. + Dispatch, +} + /// A device's counters (`DeviceShared::counts`), each only ever added to. #[derive(Default)] pub(crate) struct Counters { @@ -74,6 +87,10 @@ pub(crate) struct Counters { host_step_sampler_sets_made: AtomicU64, creation_pipelines_made: AtomicU64, creation_pipelines_drawn: AtomicU64, + creation_render_pipelines_made: AtomicU64, + creation_render_pipelines_drawn: AtomicU64, + creation_dispatch_pipelines_made: AtomicU64, + creation_dispatch_pipelines_drawn: AtomicU64, sampler_sets_made: AtomicU64, sampler_sets_shared: AtomicU64, sampler_sets_destroyed: AtomicU64, @@ -945,16 +962,27 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } - /// A state's creation made a `VkPipeline` (`pipeline/predicted.rs`, - /// `pipeline/dispatch_making.rs`). - pub(crate) fn creation_pipeline_made(&self) { + /// A state's creation made a `VkPipeline` of `predicted` (`pipeline/predicted.rs`, + /// `pipeline/dispatch_making.rs`): counted in both the whole count and its prediction's. + pub(crate) fn creation_pipeline_made(&self, predicted: Predicted) { self.creation_pipelines_made.fetch_add(1, Ordering::Relaxed); + match predicted { + Predicted::Render => &self.creation_render_pipelines_made, + Predicted::Dispatch => &self.creation_dispatch_pipelines_made, + } + .fetch_add(1, Ordering::Relaxed); } - /// A draw or dispatch took a `VkPipeline` a state's creation made, its first use. - pub(crate) fn creation_pipeline_drawn(&self) { + /// A draw or dispatch took a `VkPipeline` a state's creation made for `predicted`, its first + /// use: counted in both the whole count and its prediction's. + pub(crate) fn creation_pipeline_drawn(&self, predicted: Predicted) { self.creation_pipelines_drawn .fetch_add(1, Ordering::Relaxed); + match predicted { + Predicted::Render => &self.creation_render_pipelines_drawn, + Predicted::Dispatch => &self.creation_dispatch_pipelines_drawn, + } + .fetch_add(1, Ordering::Relaxed); } /// A variant made an immutable sampler set: the device's map's, or a host step's or a pool @@ -2683,6 +2711,18 @@ pub struct WorkCounts { /// Of those, the ones a draw or a dispatch took so far: the rest are makings no command has /// used yet, the speculative part of making at creation. pub creation_pipelines_drawn: u64, + /// Of [`creation_pipelines_made`](Self::creation_pipelines_made), the render states' predicted + /// keys (`pipeline/predicted.rs`). + pub creation_render_pipelines_made: u64, + /// Of [`creation_render_pipelines_made`](Self::creation_render_pipelines_made), the ones a + /// draw took so far. + pub creation_render_pipelines_drawn: u64, + /// Of [`creation_pipelines_made`](Self::creation_pipelines_made), the compute states' + /// predicted regions (`pipeline/dispatch_making.rs`). + pub creation_dispatch_pipelines_made: u64, + /// Of [`creation_dispatch_pipelines_made`](Self::creation_dispatch_pipelines_made), the ones a + /// dispatch took so far. + pub creation_dispatch_pipelines_drawn: u64, /// Immutable sampler sets variants made (the device's map's, and a host step's or a pool /// piece's own): none for a variant without immutable samplers. pub sampler_sets_made: u64, @@ -4211,6 +4251,18 @@ impl Device { .load(Ordering::Relaxed), creation_pipelines_made: counters.creation_pipelines_made.load(Ordering::Relaxed), creation_pipelines_drawn: counters.creation_pipelines_drawn.load(Ordering::Relaxed), + creation_render_pipelines_made: counters + .creation_render_pipelines_made + .load(Ordering::Relaxed), + creation_render_pipelines_drawn: counters + .creation_render_pipelines_drawn + .load(Ordering::Relaxed), + creation_dispatch_pipelines_made: counters + .creation_dispatch_pipelines_made + .load(Ordering::Relaxed), + creation_dispatch_pipelines_drawn: counters + .creation_dispatch_pipelines_drawn + .load(Ordering::Relaxed), sampler_sets_made: counters.sampler_sets_made.load(Ordering::Relaxed), sampler_sets_shared: counters.sampler_sets_shared.load(Ordering::Relaxed), sampler_sets_destroyed: counters.sampler_sets_destroyed.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/cache.rs b/crates/metal2vulkan-validation/src/runtime_lane/cache.rs index 1a48fa383..3ca2c440a 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/cache.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/cache.rs @@ -34,7 +34,7 @@ use metal2vulkan::library::Library; use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, Stage, StageSource}; use metal2vulkan::{Budget, CancelToken}; use metal2vulkan_runtime::{ - Error, PipelineOptions, ShaderCacheStatistics, DEFAULT_MEMORY_CAPACITY, + Degradation, Error, PipelineOptions, ShaderCacheStatistics, DEFAULT_MEMORY_CAPACITY, }; use std::cell::Cell; use std::collections::BTreeMap; @@ -560,6 +560,103 @@ fn makings_on_several_threads_each_read_their_own_cache() { ); } +/// The kind [`an_entry_that_cannot_be_written_is_announced_and_ends_nothing`] takes: the +/// directory's build directory is made unwritable after the device opened it, so the entries a +/// creation hands over cannot be written. +pub(super) const UNWRITTEN_ENTRY: [Degradation; 1] = [Degradation::ShaderCacheEntryNotWritten]; + +/// The mode that lets the build directory be read and listed but not written. +#[cfg(unix)] +const READ_ONLY_DIR: u32 = 0o500; + +/// The build directory under `cache`: `v1/`. +#[cfg(unix)] +fn build_dir(cache: &Path) -> PathBuf { + let mut builds: Vec = std::fs::read_dir(cache.join("v1")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.is_dir()) + .collect(); + builds.sort(); + builds.pop().expect("the device made its build's directory") +} + +/// Set `dir`'s permission bits to `mode`. +#[cfg(unix)] +fn set_mode(dir: &Path, mode: u32) { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(mode)).unwrap(); +} + +/// An entry the directory will not take is announced once as +/// [`Degradation::ShaderCacheEntryNotWritten`] and ends nothing: the pipeline state is made, it +/// runs to the same output as one whose entries were written, and the device counts the failures. +/// The announcement names the directory and its cap. +/// +/// The directory is made writable for the device to open (`Directory::open` checks that it takes +/// a write and fails the creation otherwise, which is the one shader-cache error there is), and +/// unwritable afterwards, which is the state a full disk or a directory someone else locked down +/// leaves. Unix only: it turns on the directory's mode bits. +#[cfg(unix)] +#[test] +fn an_entry_that_cannot_be_written_is_announced_and_ends_nothing() { + let case = public_case(CASE).unwrap(); + let writable = ScratchCache::new().unwrap(); + let expected = cache_run(writable.path(), CASE); + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let (statistics, output, notices) = { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let build = build_dir(cache.path()); + set_mode(&build, READ_ONLY_DIR); + let made = pipeline_state(&device, &case); + let state = match made { + Ok(state) => state, + Err(error) => { + set_mode(&build, 0o700); + panic!("a creation whose entries cannot be written must still make its state: {error:?}"); + } + }; + let run = run_with(&device, &case, &state); + set_mode(&build, 0o700); + let output = run + .expect("a run whose entries could not be written") + .output; + ( + device.shader_cache_statistics(), + output, + messages.take_notices(), + ) + }; + assert_eq!( + output, expected.output, + "the output of a creation whose entries could not be written" + ); + assert!( + statistics.write_failures > 0, + "the directory must have refused an entry at all: {statistics:?}" + ); + let kinds: Vec = notices + .iter() + .filter_map(|notice| notice.degradation.as_ref().map(|d| d.degradation)) + .collect(); + assert_eq!( + kinds, UNWRITTEN_ENTRY, + "the kinds a device whose cache entries could not be written announced" + ); + let notice = notices + .iter() + .find(|notice| notice.degradation.is_some()) + .expect("the notice"); + let root = cache.path().display().to_string(); + let cap = metal2vulkan_runtime::DEFAULT_CAPACITY.to_string(); + assert!( + notice.text.contains(&root) && notice.text.contains(&cap), + "the notice names the directory and its cap: {}", + notice.text + ); +} + /// The envelope kind of a translated function (`kind` is the `u32` at byte 16). const FUNCTION: u32 = 1; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index 419c3a494..f4814b377 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -163,6 +163,7 @@ use super::blits::SYSTEM_MEMORY; use super::buffer_texture_blits::{COLLIDING_ROWS, NARROW_ROWS, OVERLAPS}; use super::buffer_texture_order::USAGE_SHADOWS; use super::buffer_texture_renders::MERGES; +use super::cache::UNWRITTEN_ENTRY; use super::clear_reach::DONT_CARE_LOADS; use super::color_groups::PER_COLOR_COUNTS; use super::color_reformat::KEPT_COLORS; @@ -596,6 +597,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &XR_RESOLVE, &YCBCR_PASSES, &MEMORYLESS_TEXEL_BUFFERS, + &UNWRITTEN_ENTRY, ]; for kind in lists.into_iter().flatten().copied().chain(stage_kinds) { assert!(listed.insert(kind), "{kind:?} is listed twice"); diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 59d1930c0..5c62dab52 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 449; /// 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 = 1616; +pub const RUNTIME_VERSION: u32 = 1618; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/docs/API.md b/docs/API.md index f6c150209..0f2fa14f8 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2462,6 +2462,16 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. which the extension requires. Cost: the driver keeps its own cache of the device's pipelines beside the shader cache's records, with whatever it writes to disk and holds in memory for it; the pipelines made are the same. +- `metal2vulkan-degrade-shader-cache-entry-not-written` (performance). + `ShaderCacheEntryNotWritten`: an entry of the device's shader cache directory was not written -- + the directory, a temporary file in it or the rename over the entry failed, on the device's cache + thread or on the thread that handed the entry over past the queue's bound. A full or read-only + directory, a cap no entry fits in, or a write another process won. Nothing is ended by it: the + pipeline state, the translation and the compile are made regardless. Announced once per device, + naming the directory, its cap and the largest entry it takes; later failures are counted in + `ShaderCacheStatistics::write_failures`. Cost: what the entry would hold is made again by the + next process that needs it; what this process computes is unchanged. The entry is a translation, + a compiled pipeline, a creation's answers or the driver's pipeline cache data. - `metal2vulkan-degrade-metal-level-not-macos` (precision). `MetalLevelNotMacOS`: A device made off macOS with no Metal level named: it answers as the newest measured release (`MetalLevel::NEWEST`), no release of the host's. Cost: where Metal's answers differ by release (which pixel formats a diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 0324ce875..488c6ebbb 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -85,10 +85,21 @@ second process does not translate it again. It cannot be turned off. update starts empty. On drivers that report `pipelineBinaryInternalCacheControl` (NVIDIA's), a device the runtime makes turns the driver's own internal cache off; an adopted device keeps what its creator chose. +- **Written in the background.** A creation hands its entries to the device's cache thread and + does not wait for the directory: the same bytes under the same name, committed by the same + rename, after the call returns. An entry still queued answers that device's own lookups, and the + queue is written out before `Device`'s drop returns, so a second process finds everything the + first one's creations handed over. A process that ends without dropping its devices loses what + is still queued, which costs the next process those translations and nothing else. + `Device::shader_cache_statistics` counts the entries queued, those a creation wrote itself past + the queue's bound, and the bytes written. - **When it fills or a write fails.** Each device says so once, through its `MessageSink` (or on - stderr) as a `Warning` whose `id_name` is `metal2vulkan-shader-cache-evicted` or - `metal2vulkan-shader-cache-write-failed`. Match on `id_name`, never on the text. Later events are - counted in `Device::shader_cache_statistics`. + stderr) as a `Warning`: `id_name` `metal2vulkan-shader-cache-evicted` when the directory reaches + its cap, and the degrade notice + `metal2vulkan-degrade-shader-cache-entry-not-written` (`DebugMessage::degradation` + `Degradation::ShaderCacheEntryNotWritten`) when an entry cannot be written. Neither ends any + work. Match on `id_name`, never on the text. Later events are counted in + `Device::shader_cache_statistics`. - **Failures.** Making or adopting a device fails with `Error::ShaderCache` when the directory cannot be made or written. After that, a failed read or write only costs a translation. - **Cold runs.** To measure with nothing cached, give the device an empty directory, and turn the