From 5ba7afd9d407fd4bd3a67369da07178c1cc0a6b0 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 15 Nov 2026 09:10:25 -0800 Subject: [PATCH] RUNTIME 2360: Shader cache: no default directory makes a memory-only device, never a failed one With no caller directory and no home (USERPROFILE on Windows, HOME elsewhere), default_directory answered Err and CacheSetup::of turned it, and any failure to open the default path, into Error::ShaderCache, so every device creation and adoption failed. Metal never fails device creation over its shader cache, and the default is the runtime's choice, not the caller's (owner rule 2). - The Windows default is %LOCALAPPDATA%\metal2vulkan (the local application data folder, read from the environment; no new dependency). XDG_CACHE_HOME and USERPROFILE are no longer read there. - default_directory takes its environment as a closure (CacheSetup::of_in), so a test feeds its own without touching the process's. - Where the caller names no directory and the default does not exist or cannot be made or written, the device keeps its cache in memory alone: the Store has no directory, every lookup is absent, every write is refused with no filesystem call, the scans do nothing, and writers ask has_directory first so nothing is encoded for it (a translated function still is: its encoded length weighs it in the memo). The device says so once as it is made, as the existing degrade notice ShaderCacheEntryNotWritten naming why; each entry it does not write counts in write_failures. The driver's pipeline cache data is not read back, and the device checks' verdicts are not encoded. - A directory the caller names that cannot be used is still Error::ShaderCache. - Device::shader_cache_directory answers Option<&Path>: None for such a device. Docs: the shader_cache module docs, ShaderCacheOptions::directory, write_failures, Error::ShaderCache, the degradation's declaration and its docs/API.md entry, the runtime README (Windows default, error table), HOWTO, create.rs's list of environment variables. api_signatures re-blessed; docs/REFUSALS.md regenerated (a refusal's site function renamed). Tests: tests::shader_cache's default-directory and no-directory-store unit tests (plain gate), and the lavapipe/GPU device test shader_cache_no_directory: a device made with an empty environment and no caller directory is made, has no directory, makes four render states with two functions translated once, writes nothing, and its notice is heard once. Verified (msi): m3-max-32796 clippy plain 0, 67/67 shader_cache and degradation tests, api_signatures 0, clippy x86_64-pc-windows-gnullvm 0; m3-max-32797 (lavapipe) clippy m2v_cpu_icd 0, 61/61 shader_cache and in_place_check, including the no-directory device test. --- crates/metal2vulkan-runtime/README.md | 9 +- .../metal2vulkan-runtime/src/degradation.rs | 8 +- .../metal2vulkan-runtime/src/device/create.rs | 16 +- .../metal2vulkan-runtime/src/device/line.rs | 5 +- crates/metal2vulkan-runtime/src/error.rs | 9 +- .../src/in_place_check.rs | 13 +- .../src/pipeline/sources.rs | 13 +- .../src/queue_switch_check.rs | 8 +- .../src/shader_cache/creation.rs | 40 +-- .../src/shader_cache/driver.rs | 5 + .../src/shader_cache/libraries.rs | 5 +- .../src/shader_cache/mod.rs | 177 ++++++++--- .../src/shader_cache/store.rs | 287 ++++++++++++------ .../src/shader_cache/warm_refusals.rs | 5 +- .../metal2vulkan-runtime/src/submit_check.rs | 6 +- .../src/tests/in_place_check.rs | 1 + crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/shader_cache.rs | 156 +++++++++- .../src/tests/shader_cache_no_directory.rs | 101 ++++++ .../src/texture/linear_alignment.rs | 4 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 2 +- docs/API.md | 6 +- docs/HOWTO.md | 16 +- docs/REFUSALS.md | 4 +- 25 files changed, 690 insertions(+), 210 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/shader_cache_no_directory.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index ac0f64e59..8bc65eb95 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -86,9 +86,10 @@ macOS, it asks Win32 on Windows: `VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR`. - Thread CPU times come from `GetThreadTimes`, and the runtime's exit handler is registered with the C runtime's `atexit`. -- The default shader cache directory is `%XDG_CACHE_HOME%\metal2vulkan`, or - `%USERPROFILE%\.cache\metal2vulkan`. Its directories and files take the access control list - they inherit; the runtime sets no permissions of its own there. +- The default shader cache directory is `%LOCALAPPDATA%\metal2vulkan`; where `LOCALAPPDATA` is + unset or not absolute, a device keeps its shader cache in memory alone and says so + ([HOWTO](../../docs/HOWTO.md#the-runtimes-shader-cache)). Its directories and files take the + access control list they inherit; the runtime sets no permissions of its own there. The items that take or hand out file descriptors do not exist on Windows (they are absent at compile time), and nothing stands in for them with Win32 handles: @@ -893,7 +894,7 @@ message text. The ones a consumer meets most: | `DriverSetting(DriverSetting)` | A driver setting the runtime cannot run under, such as MoltenVK with `MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS` off. | | `DeviceRefused(DeviceRefused)` | The driver refused to make the device for want of its resources (`VK_ERROR_TOO_MANY_OBJECTS`, `VK_ERROR_INITIALIZATION_FAILED`, `VK_ERROR_OUT_OF_DEVICE_MEMORY` or `VK_ERROR_OUT_OF_HOST_MEMORY`), with its queue plan's `VkQueue`s and then with its least plan's; `attempts` names each. Other devices of the GPU, in any process, hold what it lacks; once fewer are live it may be made. | | `WaitWouldDeadlock(DeadlockCause)` | A command buffer wait that would deadlock, refused at once instead of hanging. | -| `ShaderCache(...)` | The shader cache directory cannot be made or written. | +| `ShaderCache(...)` | The shader cache directory `ShaderCacheOptions::directory` names cannot be made or written. | ```rust,ignore match device.new_render_pipeline_state(&descriptor, &PipelineOptions::default()) { diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 1760f31e9..3680cebe6 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2610,8 +2610,12 @@ degradations! { /// 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 + /// cap no entry fits in, or a write another process won. Or the device has no directory + /// to write to: its options named none and the platform's default does not exist (the + /// variable it is found by is unset or not absolute) or takes no write, so it keeps its + /// cache in memory alone (`shader_cache/mod.rs`); that is announced as the device is made, + /// the payload naming the default directory and why. 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 diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index cc9671e97..39f568095 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -26,8 +26,9 @@ //! extensions, recommended features and extensions to withhold, where debug-utils messages go, //! which loader opens, which kind of physical device qualifies, and the shader cache directory. //! Nothing is read from the environment, except where the platform keeps the default shader cache -//! directory (`HOME`, and `XDG_CACHE_HOME` off macOS) and, on macOS, where the Vulkan SDK is -//! (`VULKAN_SDK`), one of the places the default loader is looked for (`default_loaders`). +//! directory (`LOCALAPPDATA` on Windows, `HOME` on macOS, `XDG_CACHE_HOME` and `HOME` elsewhere) +//! and, on macOS, where the Vulkan SDK is (`VULKAN_SDK`), one of the places the default loader is +//! looked for (`default_loaders`). use super::instance_requirements::instance_requirements_met; use super::keeper::keep_drivers_loaded; @@ -2888,11 +2889,20 @@ impl Device { /// last device and load them again for the next, which some drivers cannot do indefinitely. pub fn system_default_with(options: &DeviceOptions) -> Result { let cache = CacheSetup::of(&options.shader_cache, "system_default_with")?; + Device::system_default_set_up(options, &cache) + } + + /// [`Device::system_default_with`] with its shader cache set up already as `cache`, which a + /// test sets up from an environment of its own (`tests::shader_cache_no_directory`). + pub(crate) fn system_default_set_up( + options: &DeviceOptions, + cache: &CacheSetup, + ) -> Result { let mut made = lock(&MADE); let (at, instance) = group(&mut made, options)?; let mut refusal = None; for physical in ranked(&instance, options)? { - match device_of(&mut made[at], &instance, physical, options, &cache) { + match device_of(&mut made[at], &instance, physical, options, cache) { Ok(device) => return Ok(device), Err(error) => { refusal.get_or_insert(error); diff --git a/crates/metal2vulkan-runtime/src/device/line.rs b/crates/metal2vulkan-runtime/src/device/line.rs index b8c5d9d74..2fdd9641a 100644 --- a/crates/metal2vulkan-runtime/src/device/line.rs +++ b/crates/metal2vulkan-runtime/src/device/line.rs @@ -87,8 +87,9 @@ pub(crate) struct Invariant { pub(crate) compile: metal2vulkan::device::Device, pub(crate) enabled: EnableSet, pub(crate) extensions: Vec, - /// The shader cache's directory (`Device::shader_cache_directory`). - pub(crate) cache_directory: PathBuf, + /// The shader cache's directory (`Device::shader_cache_directory`); `None` where it keeps + /// none. + pub(crate) cache_directory: Option, } /// How the line makes its next `VkDevice`: what the first was made of (`create.rs`). None for a diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 12a9c2758..fbabeeded 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -92,8 +92,11 @@ pub enum Error { /// [`AppleOnly::gap`](crate::AppleOnly::gap) says why, whether Metal's answer is not measured /// or the runtime has not built it. Each is the runtime's own gap, not a device's. AppleOnly(AppleOnly), - /// The shader cache directory cannot be used: only device creation and adoption fail so; later, - /// a failed read or write is a counted miss. + /// The shader cache directory the options name (`ShaderCacheOptions::directory`) cannot be + /// used: only device creation and adoption fail so; later, a failed read or write is a counted + /// miss. A platform default that does not exist or cannot be used fails nothing: the device + /// keeps its cache in memory alone and says so. No Metal counterpart: Metal keeps its shader + /// cache to itself. ShaderCache(ShaderCacheError), /// A binary archive that cannot be loaded or serialized (`MTLBinaryArchiveError`). BinaryArchive(BinaryArchiveError), @@ -1265,7 +1268,7 @@ pub struct SamplerLimit { #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] pub struct ShaderCacheError { - /// The directory, or `None` when there is no default one (no home directory). + /// The directory. The runtime always names it; `None` only in a value made with `None`. pub path: Option, /// The I/O error's kind. pub kind: std::io::ErrorKind, diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index ed0d1566e..f50d6cac9 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -632,13 +632,12 @@ fn run(weak: crate::device::WeakDevice) { for at in unmeasured { recorded[at] = Verdict::Pending; } - let bytes = encode(&identity, recorded); - // A failed write leaves the verdicts to the device's life alone. - let _ = device - .shared() - .shader_cache - .content_store() - .write_record_soon(&record_name(&identity), bytes); + // A failed write, or a store with no directory, leaves the verdicts to the device's life + // alone. + let store = device.shared().shader_cache.content_store(); + if store.has_directory() { + let _ = store.write_record_soon(&record_name(&identity), encode(&identity, recorded)); + } } // The shadows made before the verdicts that pass wait for a switch before a call waiting for // the verdicts wakes: its next quiet commit moves them (`texture/storage_form.rs`). diff --git a/crates/metal2vulkan-runtime/src/pipeline/sources.rs b/crates/metal2vulkan-runtime/src/pipeline/sources.rs index b42c7e00b..455b287b2 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/sources.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/sources.rs @@ -297,12 +297,17 @@ impl<'a> Sources<'a> { && stage_keys .iter() .all(|key| cache.holds_function(compile, key)); - let weight = match functions_held { - true => pipeline.footprint(), - false => { + let encoded = match functions_held { + true => None, + false => cache.store_render_pipeline(compile, &pipeline), + }; + // Weighed at its encoding's length where the directory took it, else at what it retains. + let weight = match encoded { + Some(length) => { note_render_artifact_encoded(); - cache.store_render_pipeline(compile, &pipeline) + length } + None => pipeline.footprint(), }; cache.memo.keep_render(&pipeline, weight); self.note(Artifact::Render(Arc::clone(&pipeline))); diff --git a/crates/metal2vulkan-runtime/src/queue_switch_check.rs b/crates/metal2vulkan-runtime/src/queue_switch_check.rs index 89aa60d7d..466c4c6c1 100644 --- a/crates/metal2vulkan-runtime/src/queue_switch_check.rs +++ b/crates/metal2vulkan-runtime/src/queue_switch_check.rs @@ -355,9 +355,11 @@ fn run(parts: &Parts, made: Option>) { false => Verdict::DoesNotIdle, }; let identity = &parts.identity; - // A failed write leaves the verdict to the device's life alone. - let _ = - (parts.store).write_record_soon(&record_name(identity), encode(identity, verdict, cost)); + // A failed write, or a store with no directory, leaves the verdict to the device's life alone. + if parts.store.has_directory() { + let bytes = encode(identity, verdict, cost); + let _ = (parts.store).write_record_soon(&record_name(identity), bytes); + } parts.settle(verdict, cost, took); } diff --git a/crates/metal2vulkan-runtime/src/shader_cache/creation.rs b/crates/metal2vulkan-runtime/src/shader_cache/creation.rs index 6d55748c1..4c88dd5c0 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/creation.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/creation.rs @@ -162,9 +162,10 @@ impl ShaderCache { key: &PipelineKey, answers: LinkedUseAnswers, ) { - let bytes = answers.to_bytes(key, compile); + self.keep_answer(EntryKind::LinkedAnswers, key.digest(), compile, || { + answers.to_bytes(key, compile) + }); lock(&self.creation.linked).insert(*key, answers, 1); - self.keep_answer(EntryKind::LinkedAnswers, key.digest(), compile, bytes); } /// The keys of the variant of the render descriptor of `key` on `compile` under `variant`, @@ -228,12 +229,9 @@ impl ShaderCache { ) { let name = variant_name(key, variant); note_variant_record_written(); - self.keep_answer( - EntryKind::VariantPipeline, - &name, - compile, - variant_record(&name, stages), - ); + self.keep_answer(EntryKind::VariantPipeline, &name, compile, || { + variant_record(&name, stages) + }); } /// The reflection of the render descriptor of `key` on `compile`: the memo's, else the @@ -293,31 +291,37 @@ impl ShaderCache { key: &PipelineKey, reflection: RenderPipelineReflection, ) -> RenderPipelineReflection { - let bytes = reflection.to_bytes(key, compile); + self.keep_answer(EntryKind::RenderReflection, key.digest(), compile, || { + reflection.to_bytes(key, compile) + }); lock(&self.creation.reflections).insert(*key, reflection.clone(), 1); - self.keep_answer(EntryKind::RenderReflection, key.digest(), compile, bytes); reflection } - /// Write `bytes` as the directory's entry of `kind` under `key` for `compile`'s profile, as - /// 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. + /// Write what `encode` encodes as the directory's entry of `kind` under `key` for + /// `compile`'s profile, as 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. A device with + /// no directory encodes nothing and counts it as not written (the module docs). pub(super) fn keep_answer( &self, kind: EntryKind, key: &Hash256, compile: &CompileDevice, - bytes: Vec, + encode: impl FnOnce() -> Vec, ) { + if !self.store.has_directory() { + self.store.write_failed(); + return; + } let name = record_name( - self.store.directory().build(), + self.store.build(), kind, key, &compile.profile_fingerprint(), metal2vulkan::cache::RUNTIME_VERSION, ); - if self.store.write_soon(&name, bytes).is_err() { + if self.store.write_soon(&name, encode()).is_err() { self.store.write_failed(); } if self.store.over_capacity() { @@ -336,7 +340,7 @@ impl ShaderCache { decode: impl FnOnce(&[u8]) -> Result, ) -> Option { let name = record_name( - self.store.directory().build(), + self.store.build(), kind, key, &compile.profile_fingerprint(), diff --git a/crates/metal2vulkan-runtime/src/shader_cache/driver.rs b/crates/metal2vulkan-runtime/src/shader_cache/driver.rs index c8183edab..e986d768f 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/driver.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/driver.rs @@ -554,6 +554,11 @@ pub(crate) fn make( /// making from the same cache. The per-record lock below is held only over the comparison and the /// write, so two makings of one record never write the same bytes twice. fn keep(store: &Store, identity: &Identity, raw: &ash::Device, live: &Live) { + // A store with no directory keeps no record, so the data is not read (the module docs of + // `shader_cache/mod.rs`). + if !store.has_directory() { + return; + } let Some(busy) = exit_guard::enter() else { return; }; diff --git a/crates/metal2vulkan-runtime/src/shader_cache/libraries.rs b/crates/metal2vulkan-runtime/src/shader_cache/libraries.rs index 29b196552..961cb9a6b 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/libraries.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/libraries.rs @@ -70,7 +70,10 @@ impl ShaderCache { } } let name = name(&hash); - if !self.store.holds_record(&name) { + if !self.store.has_directory() { + // A device with no directory encodes nothing for it (the module docs). + self.store.write_failed(); + } else if !self.store.holds_record(&name) { let mut bytes = Vec::with_capacity(HEAD + library.bytes().len()); bytes.extend_from_slice(MAGIC); bytes.extend_from_slice(&hash); diff --git a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs index 8346a54be..12b7b5f35 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs @@ -2,12 +2,22 @@ //! what the first already did, as Metal programs get from the OS. //! //! - **The directory.** [`ShaderCacheOptions::directory`], or the platform's per-user cache -//! directory: `~/Library/Caches/metal2vulkan` on macOS, `$XDG_CACHE_HOME/metal2vulkan` -//! elsewhere, or `~/.cache/metal2vulkan` when that is unset or not absolute. Never the OS temp -//! directory. Creating or adopting a device makes it (owner-only) and checks that it takes a -//! write; if not, the call fails with [`Error::ShaderCache`], naming the path and the I/O error. -//! After that, a failed read or write is a miss the [statistics](ShaderCacheStatistics) count, -//! never an error. +//! directory: `%LOCALAPPDATA%\metal2vulkan` on Windows, `~/Library/Caches/metal2vulkan` on +//! macOS, `$XDG_CACHE_HOME/metal2vulkan` elsewhere, or `~/.cache/metal2vulkan` when that is +//! unset or not absolute. Never the OS temp directory. Creating or adopting a device makes it +//! (owner-only) and checks that it takes a write. A directory the caller named that does not +//! fails the call with [`Error::ShaderCache`], naming the path and the I/O error: the caller's +//! own choice. The default is the runtime's, and Metal makes its device whatever its shader +//! cache does: where the caller named none and the default does not exist (the variable it is +//! found by unset or not absolute) or takes no write, the device keeps its cache in memory +//! alone ([`Device::shader_cache_directory`] is `None`). It reads and writes no directory, +//! encodes no entry for one but a translated function (whose encoding weighs it in the memo), +//! counts each entry it does not write in +//! [`write_failures`](ShaderCacheStatistics::write_failures), and says so once as it is made, +//! as the degrade notice +//! [`Degradation::ShaderCacheEntryNotWritten`](crate::Degradation::ShaderCacheEntryNotWritten) +//! naming why. After that, a failed read or write is a miss the +//! [statistics](ShaderCacheStatistics) count, never an error. //! - **What it holds.** The compile layer's artifacts in their self-checking envelope: translated //! functions under their [`FunctionCompileKey`] and render pipelines under their //! [`PipelineKey`] (a compute pipeline is linked from its function, never kept, @@ -87,6 +97,7 @@ use metal2vulkan::cache::{Hash256, PipelineArtifact, PipelineKey}; use metal2vulkan::library::{CompiledFunction, FunctionCompileKey}; use metal2vulkan::pipeline::RenderPipeline; use sha2::{Digest, Sha256}; +use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::sync::atomic::Ordering; use std::sync::Arc; @@ -105,7 +116,10 @@ pub const DEFAULT_MEMORY_CAPACITY: u64 = 256 << 20; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ShaderCacheOptions { /// The cache directory; `None` is the platform's per-user cache directory (the module's - /// documentation names it). Devices of different processes and builds may share one. + /// documentation names it), and where that does not exist or takes no write, no directory: + /// the device keeps its cache in memory alone and says so. A directory named here that cannot + /// be made or written fails the device's creation ([`Error::ShaderCache`]). Devices of + /// different processes and builds may share one. pub directory: Option, /// The most bytes the directory holds, every build's entries together; past it the least /// recently used entries are removed, the device's first removal said once as a warning. @@ -234,7 +248,9 @@ pub struct ShaderCacheStatistics { /// 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. + /// Entries that could not be written, by whichever thread wrote them. On a device with no + /// directory (the module docs), each translated function, render pipeline, creation answer + /// and library its creations would have given the directory. pub write_failures: u64, /// Entries removed to keep the directory under its cap. pub evictions: u64, @@ -326,61 +342,102 @@ pub(crate) fn this_build() -> Hash256 { hash.finalize().into() } -/// The platform's per-user cache directory for this crate. -fn default_directory() -> Result { +/// The platform's per-user cache directory for this crate, from the variables `environment` +/// reads (`std::env::var_os` for a device, a test's own for a test): `%LOCALAPPDATA%\metal2vulkan` +/// on Windows, `~/Library/Caches/metal2vulkan` on macOS, `$XDG_CACHE_HOME/metal2vulkan` +/// elsewhere, or `~/.cache/metal2vulkan` when that is unset or not absolute. `None` where the +/// variable it is found by is unset or not absolute ([`NO_DEFAULT`]). +pub(super) fn default_directory(environment: impl Fn(&str) -> Option) -> Option { let absolute = |name: &str| { - std::env::var_os(name) + environment(name) .map(PathBuf::from) .filter(|path| path.is_absolute()) }; - let home = || { - absolute(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).ok_or_else(|| { - ShaderCacheError::new( - None, - std::io::ErrorKind::NotFound, - "no home directory for the default shader cache directory", - ) - }) - }; + if cfg!(windows) { + return absolute("LOCALAPPDATA").map(|base| base.join("metal2vulkan")); + } if cfg!(target_os = "macos") { - return Ok(home()?.join("Library/Caches/metal2vulkan")); + return absolute("HOME").map(|home| home.join("Library/Caches/metal2vulkan")); } match absolute("XDG_CACHE_HOME") { - Some(base) => Ok(base.join("metal2vulkan")), - None => Ok(home()?.join(".cache/metal2vulkan")), + Some(base) => Some(base.join("metal2vulkan")), + None => absolute("HOME").map(|home| home.join(".cache/metal2vulkan")), } } +/// Why [`default_directory`] finds none, as its device's notice says it. +const NO_DEFAULT: &str = if cfg!(windows) { + "`LOCALAPPDATA` is unset or not an absolute path" +} else if cfg!(target_os = "macos") { + "`HOME` is unset or not an absolute path" +} else { + "neither `XDG_CACHE_HOME` nor `HOME` is an absolute path" +}; + /// A device's shader cache as its options set it up, before the device is made: the directory -/// opened for this build, and the memo's cap. +/// opened for this build, or why it keeps none, and the memo's cap. #[derive(Clone, Debug)] pub(super) struct CacheSetup { - directory: Directory, + directory: Result, memory_capacity: u64, } +/// Why a device keeps no shader cache directory (the module docs), which its creation announces +/// ([`Store::announce_no_directory`]). +#[derive(Clone, Debug)] +struct Unkept { + /// The directory it does not have: the default one, by its path where there is one. + object: String, + /// Why. + reason: String, +} + impl CacheSetup { - /// The cache `options` describe: its directory opened for this build. `call` names the - /// creating call. + /// The cache `options` describe: its directory opened for this build, the platform's default + /// found in the process's environment. `call` names the creating call. pub(super) fn of( options: &ShaderCacheOptions, call: &'static str, + ) -> Result { + CacheSetup::of_in(options, call, |name| std::env::var_os(name)) + } + + /// [`CacheSetup::of`], the platform's default directory found by the variables `environment` + /// reads ([`default_directory`]). A directory `options` name that cannot be used fails it; + /// where they name none and the default does not exist or cannot be used, the cache has no + /// directory (the module docs). + pub(super) fn of_in( + options: &ShaderCacheOptions, + call: &'static str, + environment: impl Fn(&str) -> Option, ) -> Result { if options.capacity == 0 || options.memory_capacity == 0 { return Err(invalid(call, Problem::ShaderCacheCapacity)); } - let root = match &options.directory { - Some(directory) => directory.clone(), - None => default_directory().map_err(Error::ShaderCache)?, - }; - let directory = - Directory::open(root, this_build(), options.capacity).map_err(|failed| { + let open = |root: PathBuf| Directory::open(root, this_build(), options.capacity); + let directory = match &options.directory { + Some(directory) => Ok(open(directory.clone()).map_err(|failed| { Error::ShaderCache(ShaderCacheError::new( Some(failed.path), failed.error.kind(), &failed.error.to_string(), )) - })?; + })?), + None => match default_directory(environment) { + Some(root) => open(root.clone()).map_err(|failed| Unkept { + object: format!("the default shader cache directory {}", root.display()), + reason: format!( + "{} cannot be made or written: {}", + failed.path.display(), + failed.error + ), + }), + None => Err(Unkept { + object: "the default shader cache directory".to_owned(), + reason: format!("there is none: {NO_DEFAULT}"), + }), + }, + }; Ok(CacheSetup { directory, memory_capacity: options.memory_capacity, @@ -434,7 +491,15 @@ impl ShaderCache { memory_capacity, } = setup; let asked = Arc::new(Asked::new()); - let store = Arc::new(Store::new(directory, sink, Some(Arc::clone(&asked)))); + let store = match directory { + Ok(directory) => Store::new(directory, sink, Some(Arc::clone(&asked))), + Err(unkept) => { + let store = Store::without_directory(this_build(), sink); + store.announce_no_directory(unkept.object, &unkept.reason); + store + } + }; + let store = Arc::new(store); let worker = Worker::start(Arc::clone(&store), asked)?; Ok(ShaderCache { memo: PipelineMemo::new(memory_capacity), @@ -584,11 +649,14 @@ impl ShaderCache { compile: &metal2vulkan::device::Device, key: &FunctionCompileKey, ) -> bool { + if !self.store.has_directory() { + return false; + } let profile = compile.profile_fingerprint(); self.held .holds((key.digest(), &profile), self.store.removals(), || { let name = entry_name( - self.store.directory().build(), + self.store.build(), EntryKind::Function, key.digest(), &profile, @@ -597,7 +665,9 @@ impl ShaderCache { }) } - /// Keep `function`, which `compile` compiled; its encoded length. + /// Keep `function`, which `compile` compiled; its encoded length, which weighs it in the memo + /// whether or not the directory takes it (encoded on a device with no directory too, which + /// counts it as not written). pub(super) fn store_function( &self, compile: &metal2vulkan::device::Device, @@ -623,18 +693,23 @@ impl ShaderCache { }) } - /// Keep `pipeline`, which `compile` compiled; its encoded length. + /// Keep `pipeline`, which `compile` compiled; its encoded length. `None` on a device with no + /// directory, which encodes nothing and counts it as not written. pub(super) fn store_render_pipeline( &self, compile: &metal2vulkan::device::Device, pipeline: &RenderPipeline, - ) -> u64 { - self.store( + ) -> Option { + if !self.store.has_directory() { + self.store.write_failed(); + return None; + } + Some(self.store( EntryKind::RenderPipeline, pipeline.key().digest(), compile, pipeline.to_bytes(), - ) + )) } /// The entry of `looked`'s kind under `key` for `compile`'s profile, as `decode` accepts it, @@ -649,7 +724,7 @@ impl ShaderCache { ) -> Option<(T, u64)> { let counters = &self.store.counters; let name = entry_name( - self.store.directory().build(), + self.store.build(), looked.kind(), key, &compile.profile_fingerprint(), @@ -680,7 +755,7 @@ impl ShaderCache { ) -> u64 { let counters = &self.store.counters; let name = entry_name( - self.store.directory().build(), + self.store.build(), kind, key, &compile.profile_fingerprint(), @@ -697,9 +772,9 @@ impl ShaderCache { } /// The directory's root, which every generation of the device's line shares - /// (`device/line.rs`, `Device::shader_cache_directory`). - pub(super) fn directory_root(&self) -> std::path::PathBuf { - self.store.directory().root().to_owned() + /// (`device/line.rs`, `Device::shader_cache_directory`); `None` where it keeps none. + pub(super) fn directory_root(&self) -> Option { + (self.store.directory()).map(|directory| directory.root().to_owned()) } /// What the directory cost this device: its time, the asking threads' apart from the cache @@ -759,9 +834,11 @@ impl Device { self.shared().shader_cache.statistics() } - /// The device's shader cache directory, the same through its GPU's recoveries. No Metal - /// counterpart. - pub fn shader_cache_directory(&self) -> &Path { - &self.line().invariant.cache_directory + /// The device's shader cache directory, the same through its GPU's recoveries; `None` where + /// the device keeps its cache in memory alone: its options named no directory and the + /// platform's default ([`ShaderCacheOptions::directory`]) does not exist or takes no write, as + /// its creation announced. No Metal counterpart: Metal keeps its shader cache to itself. + pub fn shader_cache_directory(&self) -> Option<&Path> { + self.line().invariant.cache_directory.as_deref() } } diff --git a/crates/metal2vulkan-runtime/src/shader_cache/store.rs b/crates/metal2vulkan-runtime/src/shader_cache/store.rs index 1e93c114b..9c0e80dc5 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/store.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/store.rs @@ -5,7 +5,7 @@ //! /v1/// //! ``` //! -//! - `` names the build ([`Directory::build`]); a build reads only its own directory. +//! - `` names the build ([`Store::build`]); a build reads only its own directory. //! - One directory beside the builds', the content directory ([`content`]), holds records no build //! owns, named by the content they describe: the driver's pipeline cache data (It was the //! build's; one record per pipeline making), named by what each making reads and read as an entry @@ -26,6 +26,11 @@ //! 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. +//! - **A store may have no directory** ([`Store::without_directory`]): that of a device whose +//! default directory does not exist or takes no write, which keeps its cache in memory alone +//! (`shader_cache/mod.rs`). Every lookup in it finds nothing and every write is refused, each +//! with no filesystem call, and it scans nothing; a writer asks [`Store::has_directory`] first, +//! so it encodes nothing the store would refuse. //! - **The directory's time is counted**, in three figures the asking thread's are apart from the //! cache thread's: the reads ([`Counters::read_nanos`]), the writes a thread that asked made //! itself ([`Counters::write_nanos`]), and everything the device's cache thread did here @@ -113,9 +118,9 @@ impl Directory { &self.root } - /// The build this directory serves. - pub(super) fn build(&self) -> &Hash256 { - &self.build + /// The largest entry this directory takes. + fn entry_limit(&self) -> u64 { + MAX_ENTRY.min(self.capacity) } /// `/v1`. @@ -337,7 +342,10 @@ pub(super) fn count(counter: &AtomicU64) { /// One device's view of the directory: reads, writes, and the scans that bound it. pub(crate) struct Store { - directory: Directory, + /// The directory; `None` in a store with no directory (the module docs). + directory: Option, + /// The build whose entries the store names ([`entry_name`]): the directory's, where it has one. + build: Hash256, pub(crate) counters: Counters, /// The bytes this process takes the directory to hold: the last scan's total plus what it /// wrote since. Other processes' writes show at the next scan. @@ -372,9 +380,29 @@ impl Store { directory: Directory, sink: Option, asked: Option>, + ) -> Store { + let build = directory.build; + Store::of(Some(directory), build, sink, asked) + } + + /// The store of a device that keeps no directory, naming the entries of `build`, whose + /// warnings go to `sink`, else on stderr: every lookup finds nothing and every write is + /// refused, with no filesystem call (the module docs). Its device says so + /// ([`Store::announce_no_directory`]). + pub(crate) fn without_directory(build: Hash256, sink: Option) -> Store { + Store::of(None, build, sink, None) + } + + /// The store of `directory`, or of none, for `build` ([`Store::new`]). + fn of( + directory: Option, + build: Hash256, + sink: Option, + asked: Option>, ) -> Store { Store { directory, + build, counters: Counters::default(), used: AtomicU64::new(0), scanned: AtomicBool::new(false), @@ -390,39 +418,69 @@ impl Store { /// 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. + /// A store with no directory counts it alone: its device said so as it was made + /// ([`Store::announce_no_directory`]). pub(crate) fn write_failed(&self) { count(&self.counters.write_failures); + let Some(directory) = &self.directory else { + return; + }; if !self.warnings.write_failed.swap(true, Ordering::Relaxed) { - let degradation = Degradation::ShaderCacheEntryNotWritten; - let root = self.directory.root().display(); + let root = 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(), + directory.capacity, + directory.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, - command_buffer: None, - }), - format!( - "metal2vulkan: an entry of the shader cache directory {root} was not \ - written: {reason} {}", - degradation.cost(), - ), + self.say_not_written( + format!("the shader cache directory {root}"), + reason, + &format!("an entry of the shader cache directory {root} was not written"), ); } } + /// Announce, as [`Degradation::ShaderCacheEntryNotWritten`], that this store has no + /// directory: `object` names the directory it does not have, and `why` why. Said once, by the + /// device's creation; the entries it does not write are counted alone + /// (`ShaderCacheStatistics::write_failures`). + pub(crate) fn announce_no_directory(&self, object: String, why: &str) { + let reason = format!( + "{why}. This device keeps its shader cache in memory alone \ + (`ShaderCacheOptions::memory_capacity`) and writes no entry, each counted alone \ + (`ShaderCacheStatistics::write_failures`); `ShaderCacheOptions::directory` names a \ + directory." + ); + self.say_not_written( + object, + reason, + "no entry of this device's shader cache is written", + ); + } + + /// Say [`Degradation::ShaderCacheEntryNotWritten`] of `object` for `reason`, its text led by + /// `what`. + fn say_not_written(&self, object: String, reason: String, what: &str) { + let degradation = Degradation::ShaderCacheEntryNotWritten; + let text = format!("metal2vulkan: {what}: {reason} {}", degradation.cost()); + self.say( + degradation.code(), + Some(DegradeNotice { + degradation, + object, + reason, + cost: degradation.cost(), + object_id: None, + misplaced: None, + call: None, + command_buffer: None, + }), + text, + ); + } + /// 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 @@ -445,13 +503,20 @@ impl Store { } } - pub(crate) fn directory(&self) -> &Directory { - &self.directory + /// The directory, where the store has one. + pub(crate) fn directory(&self) -> Option<&Directory> { + self.directory.as_ref() } - /// The largest entry this directory takes. - fn entry_limit(&self) -> u64 { - MAX_ENTRY.min(self.directory.capacity) + /// Whether the store has a directory, so a write can take: a writer asks first, and encodes + /// nothing where it has none (the module docs). + pub(crate) fn has_directory(&self) -> bool { + self.directory.is_some() + } + + /// The build whose entries the store names. + pub(crate) fn build(&self) -> &Hash256 { + &self.build } /// Whether the entry named `name` is there to be read: its file is in place and of a length @@ -459,23 +524,25 @@ impl Store { /// happened yet. Reads no contents and counts in no hit or miss -- it is a question about the /// directory, not a lookup of an entry -- but its `stat` is in [`Counters::read_nanos`]. pub(crate) fn holds(&self, name: &str) -> bool { - self.holds_at(&self.directory.entry_path(name)) + (self.directory.as_ref()) + .is_some_and(|directory| self.holds_at(directory, &directory.entry_path(name))) } /// [`Store::holds`] of the record named `name` in the content directory: a library a pipeline /// record names (`shader_cache/libraries.rs`). pub(crate) fn holds_record(&self, name: &str) -> bool { - self.holds_at(&self.directory.record_path(name)) + (self.directory.as_ref()) + .is_some_and(|directory| self.holds_at(directory, &directory.record_path(name))) } - /// [`Store::holds`] of the file at `path`. - fn holds_at(&self, path: &Path) -> bool { + /// [`Store::holds`] of the file at `path` in `directory`. + fn holds_at(&self, directory: &Directory, path: &Path) -> bool { if self.asked.as_ref().is_some_and(|asked| asked.holds(path)) { return true; } count(&self.counters.holds_questions); timed(&self.counters.read_nanos, || { - fs::metadata(path).is_ok_and(|metadata| metadata.len() <= self.entry_limit()) + fs::metadata(path).is_ok_and(|metadata| metadata.len() <= directory.entry_limit()) }) } @@ -495,7 +562,10 @@ impl Store { name: &str, decode: impl FnOnce(&[u8]) -> Result, ) -> Lookup { - self.load_at(&self.directory.entry_path(name), decode) + match &self.directory { + Some(directory) => self.load_at(directory, &directory.entry_path(name), decode), + None => Lookup::Absent, + } } /// The entry named `name` in the content directory, read and counted as [`Store::load`] @@ -506,8 +576,11 @@ impl Store { name: &str, decode: impl FnOnce(Vec) -> Option, ) -> Lookup { - let path = self.directory.record_path(name); - let (bytes, file) = match self.read(&path) { + let Some(directory) = &self.directory else { + return Lookup::Absent; + }; + let path = directory.record_path(name); + let (bytes, file) = match self.read(directory, &path) { Found::Absent => return Lookup::Absent, Found::Failed => { count(&self.counters.read_failures); @@ -528,9 +601,14 @@ impl Store { } } - /// [`Store::load`] of the file at `path`. - fn load_at(&self, path: &Path, decode: impl FnOnce(&[u8]) -> Result) -> Lookup { - let (bytes, file) = match self.read(path) { + /// [`Store::load`] of the file at `path` in `directory`. + fn load_at( + &self, + directory: &Directory, + path: &Path, + decode: impl FnOnce(&[u8]) -> Result, + ) -> Lookup { + let (bytes, file) = match self.read(directory, path) { Found::Absent => return Lookup::Absent, Found::Failed => { count(&self.counters.read_failures); @@ -575,13 +653,16 @@ impl Store { /// the bytes the directory holds and, where this thread writes it itself, the time /// ([`Counters::write_nanos`]). pub(crate) fn write_record_soon(&self, name: &str, bytes: Vec) -> io::Result { - self.write_soon_at(self.directory.record_path(name), name, bytes) + let Some(directory) = &self.directory else { + return Err(no_directory()); + }; + self.write_soon_at(directory, 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 { + /// Read the file at `path` in `directory`, 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, directory: &Directory, path: &Path) -> Found { if let Some(bytes) = self.asked.as_ref().and_then(|asked| asked.pending(path)) { return Found::Queued(bytes); } @@ -595,7 +676,7 @@ impl Store { let Ok(length) = file.metadata().map(|metadata| metadata.len()) else { return Found::Failed; }; - let limit = self.entry_limit(); + let limit = directory.entry_limit(); if length > limit { remove(path); return Found::Absent; @@ -604,8 +685,8 @@ impl Store { match (&file).take(limit + 1).read_to_end(&mut bytes) { // A record kept as chunks is read as its chunks joined; one that names a chunk // not there is a miss, which a making writes again (`chunks.rs`). - Ok(_) if bytes.starts_with(&chunks::MAGIC) && self.directory.is_record(path) => { - match self.directory.chunks().read(&bytes, limit) { + Ok(_) if bytes.starts_with(&chunks::MAGIC) && directory.is_record(path) => { + match directory.chunks().read(&bytes, limit) { Some(joined) => Found::Bytes(joined, file), None => Found::Absent, } @@ -623,20 +704,30 @@ impl Store { /// 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. + /// failure of a queued write is counted when the thread meets it, not here. A store with no + /// directory refuses it, with no filesystem call. pub(crate) fn write_soon(&self, name: &str, bytes: Vec) -> io::Result { - self.write_soon_at(self.directory.entry_path(name), name, bytes) + let Some(directory) = &self.directory else { + return Err(no_directory()); + }; + self.write_soon_at(directory, directory.entry_path(name), name, bytes) } - /// [`Store::write_soon`] of the file at `path`, named `name`. - fn write_soon_at(&self, path: PathBuf, name: &str, bytes: Vec) -> io::Result { + /// [`Store::write_soon`] of the file at `path` in `directory`, named `name`. + fn write_soon_at( + &self, + directory: &Directory, + 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 takeable = length <= QUEUED_BYTES && length <= directory.entry_limit(); let Some(asked) = self.asked.as_ref().filter(|_| takeable) else { count(&self.counters.writes_on_thread); return timed(&self.counters.write_nanos, || { - self.write_at(&path, name, &bytes) + self.write_at(directory, &path, name, &bytes) }); }; match asked.queue(Queued::new(path, bytes)) { @@ -647,7 +738,7 @@ impl Store { Some(write) => { count(&self.counters.writes_on_thread); timed(&self.counters.write_nanos, || { - self.write_at(&write.path, name, &write.bytes) + self.write_at(directory, &write.path, name, &write.bytes) }) } } @@ -661,27 +752,34 @@ impl Store { .file_name() .and_then(|name| name.to_str()) .unwrap_or("entry"); - let written = timed(&self.counters.off_thread_nanos, || { - self.write_at(path, name, bytes) - }); + let written = match &self.directory { + Some(directory) => timed(&self.counters.off_thread_nanos, || { + self.write_at(directory, path, name, bytes) + }), + None => Err(no_directory()), + }; if written.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; a content record of [`chunks::WHOLE`] bytes - /// or more as its chunks and then its manifest there (`chunks.rs`). 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 { - if bytes.len() as u64 > self.entry_limit() { + /// Write `bytes` as the entry at `path` in `directory`, named `name`, on the calling thread: + /// a temporary file beside it, flushed and renamed over it; a content record of + /// [`chunks::WHOLE`] bytes or more as its chunks and then its manifest there (`chunks.rs`). + /// The bytes written, or the failure (the temporary file is removed). An entry larger than + /// [`Directory::entry_limit`] fails. + fn write_at( + &self, + directory: &Directory, + path: &Path, + name: &str, + bytes: &[u8], + ) -> io::Result { + if bytes.len() as u64 > directory.entry_limit() { return Err(io::Error::other("the entry is larger than the cache takes")); } - let written = match bytes.len() >= chunks::WHOLE && self.directory.is_record(path) { - true => { - (self.directory.chunks()).write(bytes, |manifest| write_file(path, name, manifest)) - } + let written = match bytes.len() >= chunks::WHOLE && directory.is_record(path) { + true => (directory.chunks()).write(bytes, |manifest| write_file(path, name, manifest)), false => write_file(path, name, bytes), }; if let Ok(bytes) = &written { @@ -695,8 +793,10 @@ impl Store { /// Whether the bytes this process counts are past the cap (judged only after a scan). pub(crate) fn over_capacity(&self) -> bool { - self.scanned.load(Ordering::Acquire) - && self.used.load(Ordering::Relaxed) > self.directory.capacity + self.directory.as_ref().is_some_and(|directory| { + self.scanned.load(Ordering::Acquire) + && self.used.load(Ordering::Relaxed) > directory.capacity + }) } /// The scan at device creation: remove other builds' directories nothing used for @@ -713,19 +813,23 @@ impl Store { timed(&self.counters.off_thread_nanos, || self.scan(stop, false)); } - /// [`Store::sweep`] (with `unused_builds`) or [`Store::evict`]. + /// [`Store::sweep`] (with `unused_builds`) or [`Store::evict`]; nothing in a store with no + /// directory. fn scan(&self, stop: &AtomicBool, unused_builds: bool) { + let Some(directory) = &self.directory else { + return; + }; let now = SystemTime::now(); - let own = hex(&self.directory.build); - let chunks = self.directory.chunks(); - let content = self.directory.content_dir(); + let own = hex(&directory.build); + let chunks = directory.chunks(); + let content = directory.content_dir(); let retired = &super::driver::RETIRED; // The sweep's cleanup of the chunks where it is due (`chunks.rs`), first: it removes the // content records of a retired frame, which the survey would count. if unused_builds && chunks.due() { chunks.cleanup(&content, retired, stop); } - let Ok(builds) = fs::read_dir(self.directory.layout_dir()) else { + let Ok(builds) = fs::read_dir(directory.layout_dir()) else { return; }; let mut content_removed = false; @@ -755,11 +859,11 @@ impl Store { let chunk_bytes = chunks.bytes(); let total: u64 = entries.iter().map(|entry| entry.bytes).sum::() + chunk_bytes; let mut freed_chunks = content_removed && chunk_bytes > 0; - let remaining = match total > self.directory.capacity { + let remaining = match total > directory.capacity { true => match chunks.manifests(&content, retired, stop) { Some(manifests) => { let (remaining, freed) = - self.remove_oldest(entries, total, (&manifests, chunk_bytes)); + self.remove_oldest(directory, entries, total, (&manifests, chunk_bytes)); freed_chunks |= freed; remaining } @@ -775,17 +879,18 @@ impl Store { self.scanned.store(true, Ordering::Release); } - /// Remove the least recently used of `entries` (holding `total` bytes, of which the chunks - /// `chunk_bytes`, which `manifests` name) until what remains is at most [`LOW_WATER`] of the - /// cap: the bytes that remain, counting the chunks no remaining manifest names as freed, and - /// whether any are, which the cleanup after removes (`chunks.rs`). + /// Remove the least recently used of `entries` in `directory` (holding `total` bytes, of which + /// the chunks `chunk_bytes`, which `manifests` name) until what remains is at most + /// [`LOW_WATER`] of the cap: the bytes that remain, counting the chunks no remaining manifest + /// names as freed, and whether any are, which the cleanup after removes (`chunks.rs`). fn remove_oldest( &self, + directory: &Directory, mut entries: Vec, mut total: u64, (manifests, chunk_bytes): (&HashMap, u64), ) -> (u64, bool) { - let target = self.directory.capacity / 100 * LOW_WATER; + let target = directory.capacity / 100 * LOW_WATER; // Each chunk's manifests and length; the bytes of chunks none names go at the cleanup. let mut named: HashMap<&Hash256, (usize, u64)> = HashMap::new(); for (digest, length) in manifests.values().flatten() { @@ -813,8 +918,8 @@ impl Store { (translations, driver pipeline data) is made again when \ next needed. A larger cap keeps them. This device's later removals \ are counted alone (`ShaderCacheStatistics::evictions`).", - self.directory.root().display(), - self.directory.capacity, + directory.root().display(), + directory.capacity, LOW_WATER, ), ); @@ -854,6 +959,14 @@ fn write_file(path: &Path, name: &str, bytes: &[u8]) -> io::Result { written } +/// The refusal of a write by a store with no directory. +fn no_directory() -> io::Error { + io::Error::new( + io::ErrorKind::NotFound, + "the device keeps no shader cache directory", + ) +} + /// Remove the file at `path` (another process may have removed it first). fn remove(path: &Path) { let _ = fs::remove_file(path); diff --git a/crates/metal2vulkan-runtime/src/shader_cache/warm_refusals.rs b/crates/metal2vulkan-runtime/src/shader_cache/warm_refusals.rs index 414229589..dd0725d2c 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/warm_refusals.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/warm_refusals.rs @@ -108,8 +108,9 @@ impl ShaderCache { /// device, driver, profile and build, for a later warm pass to answer the record with. pub(crate) fn keep_warm_refusal(&self, compile: &CompileDevice, record: &[u8], kind: &str) { let name = refusal_name(&self.records.identity, record); - let bytes = refusal_record(&name, kind); - self.keep_answer(EntryKind::WarmRefusal, &name, compile, bytes); + self.keep_answer(EntryKind::WarmRefusal, &name, compile, || { + refusal_record(&name, kind) + }); } } diff --git a/crates/metal2vulkan-runtime/src/submit_check.rs b/crates/metal2vulkan-runtime/src/submit_check.rs index 46db418a3..a9302653e 100644 --- a/crates/metal2vulkan-runtime/src/submit_check.rs +++ b/crates/metal2vulkan-runtime/src/submit_check.rs @@ -1261,10 +1261,12 @@ fn run(parts: &Parts, made: Made) { checks.set_measured(measured); parts.counts.submit_checks_ran(); let verdicts = Check::ALL.map(|check| checks.verdict(check)); - if kept && !checks.merge_assumed && !verdicts.contains(&Verdict::Pending) { + // A failed write, or a store with no directory, leaves the verdicts to the device's life + // alone. + let recorded = !checks.merge_assumed && !verdicts.contains(&Verdict::Pending); + if kept && recorded && parts.store.has_directory() { let identity = &parts.identity; let bytes = encode(identity, verdicts, measured); - // A failed write leaves the verdicts to the device's life alone. let _ = parts.store.write_record_soon(&record_name(identity), bytes); } checks.settle(Some(started.elapsed())); diff --git a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs index 310186c77..5ad09ad24 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs @@ -65,6 +65,7 @@ impl AnswersRecord { let probe = device(&scratch.0); let identity = probe.driver_identity(); let path = (probe.shared().shader_cache.content_store().directory()) + .expect("a device over a cache of its own") .record_path(&record_name(&identity)); let under = path.strip_prefix(&scratch.0).unwrap().to_owned(); AnswersRecord { diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 9b07ca044..8ce8166e7 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -694,6 +694,8 @@ mod set_zero_at_offsets; mod shader_cache; mod shader_cache_chunks; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod shader_cache_no_directory; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod shader_cache_off_thread; mod shader_cache_queue; mod shader_cache_time; diff --git a/crates/metal2vulkan-runtime/src/tests/shader_cache.rs b/crates/metal2vulkan-runtime/src/tests/shader_cache.rs index 9f57e573d..c6a34f992 100644 --- a/crates/metal2vulkan-runtime/src/tests/shader_cache.rs +++ b/crates/metal2vulkan-runtime/src/tests/shader_cache.rs @@ -255,7 +255,7 @@ fn an_entry_holding_another_keys_contents_is_a_miss_and_removed() { let store = store(scratch.path(), BUILD, 1 << 20); let wanted = name(&BUILD, 1); put(&store, &wanted, 2, b"device two's data"); - let path = store.directory().entry_path(&wanted); + let path = store.directory().unwrap().entry_path(&wanted); assert!(path.is_file()); assert_eq!(get(&store, &wanted, 1), Lookup::Rejected); assert!(!path.exists()); @@ -269,7 +269,7 @@ fn corrupt_and_truncated_entries_are_misses_and_removed() { let scratch = Scratch::new(); let store = store(scratch.path(), BUILD, 1 << 20); let wanted = name(&BUILD, 1); - let path = store.directory().entry_path(&wanted); + let path = store.directory().unwrap().entry_path(&wanted); for damage in ["flip", "truncate", "empty"] { put(&store, &wanted, 1, b"some pipeline data"); let mut bytes = fs::read(&path).unwrap(); @@ -295,7 +295,7 @@ fn a_hit_refreshes_the_access_time() { let store = store(scratch.path(), BUILD, 1 << 20); let wanted = name(&BUILD, 1); put(&store, &wanted, 1, b"data"); - let path = store.directory().entry_path(&wanted); + let path = store.directory().unwrap().entry_path(&wanted); let old = SystemTime::now() - Duration::from_secs(10 * 24 * 60 * 60); set_times(&path, old); assert!(matches!(get(&store, &wanted, 1), Lookup::Hit(_))); @@ -331,7 +331,7 @@ fn the_cap_removes_the_least_recently_used_entries() { }; let wanted = name(build, n); put(store, &wanted, n, &payload); - let path = store.directory().entry_path(&wanted); + let path = store.directory().unwrap().entry_path(&wanted); // Entry n was last used n minutes after entry 0. set_times( &path, @@ -367,10 +367,10 @@ fn the_cap_removes_the_least_recently_used_records_with_the_entries() { // Even ones are makings' records, odd ones the build's entries. let path = if n % 2 == 0 { store.write_record_soon(&wanted, framed).expect("a write"); - store.directory().record_path(&wanted) + store.directory().unwrap().record_path(&wanted) } else { put(&store, &wanted, n, &payload); - store.directory().entry_path(&wanted) + store.directory().unwrap().entry_path(&wanted) }; // Each was last used n minutes after the first. set_times( @@ -455,7 +455,7 @@ fn the_sweep_removes_other_builds_unused_for_thirty_days() { let store = store(scratch.path(), *build, 1 << 20); let wanted = name(build, 1); put(&store, &wanted, 1, b"data"); - let path = store.directory().entry_path(&wanted); + let path = store.directory().unwrap().entry_path(&wanted); set_times(&path, when); set_dir_times(path.parent().unwrap(), when); set_dir_times(path.parent().unwrap().parent().unwrap(), when); @@ -465,7 +465,7 @@ fn the_sweep_removes_other_builds_unused_for_thirty_days() { let own = store(scratch.path(), BUILD, 1 << 20); let wanted = name(&BUILD, 1); put(&own, &wanted, 1, b"data"); - let own_path = own.directory().entry_path(&wanted); + let own_path = own.directory().unwrap().entry_path(&wanted); set_times(&own_path, long_ago); // A crashed writer's temporary file, an hour and more old: removed. let temporary = own_path.with_file_name(format!(".{wanted}.1.2.3.tmp")); @@ -520,6 +520,140 @@ fn an_unusable_directory_is_a_typed_error() { } } +/// An environment holding `variables` alone, as `default_directory` reads one. +fn environment(variables: &[(&str, &Path)]) -> impl Fn(&str) -> Option { + let variables: Vec<(String, std::ffi::OsString)> = (variables.iter()) + .map(|(name, value)| ((*name).to_owned(), value.as_os_str().to_owned())) + .collect(); + move |name| { + (variables.iter()) + .find(|(variable, _)| variable == name) + .map(|(_, value)| value.clone()) + } +} + +/// The platform's default directory is found by its variables alone, and is none where they are +/// unset or not absolute. Where the caller names no directory and the default does not exist or +/// takes no write, the setup keeps no directory rather than failing the device; a directory the +/// caller names that takes no write still fails it (`an_unusable_directory_is_a_typed_error`). +#[test] +fn a_missing_or_unusable_default_directory_is_no_directory_and_no_error() { + use crate::shader_cache::default_directory; + let scratch = Scratch::new(); + fs::create_dir_all(scratch.path()).unwrap(); + let base = scratch.path().join("base"); + let (variable, default) = if cfg!(windows) { + ("LOCALAPPDATA", base.join("metal2vulkan")) + } else if cfg!(target_os = "macos") { + ("HOME", base.join("Library/Caches/metal2vulkan")) + } else { + ("HOME", base.join(".cache/metal2vulkan")) + }; + assert_eq!(default_directory(|_| None), None); + assert_eq!( + default_directory(environment(&[(variable, &base)])), + Some(default) + ); + let relative = Path::new("relative"); + assert_eq!( + default_directory(environment(&[(variable, relative)])), + None + ); + if cfg!(windows) { + // Windows' default is the local application data folder alone, never under the profile. + assert_eq!( + default_directory(environment(&[("USERPROFILE", &base)])), + None + ); + } else if !cfg!(target_os = "macos") { + let xdg = scratch.path().join("xdg"); + let both = environment(&[("XDG_CACHE_HOME", &xdg), ("HOME", &base)]); + assert_eq!(default_directory(both), Some(xdg.join("metal2vulkan"))); + let relative_xdg = environment(&[("XDG_CACHE_HOME", relative), ("HOME", &base)]); + assert_eq!( + default_directory(relative_xdg), + Some(base.join(".cache/metal2vulkan")) + ); + } + let options = ShaderCacheOptions::default(); + let kept_none = |setup: Result| { + let setup = setup.expect("a default directory's absence fails nothing"); + format!("{setup:?}").contains("Err(Unkept") + }; + assert!(kept_none(CacheSetup::of_in( + &options, + "system_default_with", + |_| None + ))); + // A default below a file cannot be made. + let file = scratch.path().join("a-file"); + fs::write(&file, b"not a directory").unwrap(); + let below_a_file = environment(&[(variable, &file)]); + assert!(kept_none(CacheSetup::of_in( + &options, + "from_raw", + below_a_file + ))); + // A usable default is the directory. + let usable = CacheSetup::of_in(&options, "all_with", environment(&[(variable, &base)])); + assert!(!kept_none(usable)); +} + +/// A store with no directory finds nothing, holds nothing and refuses every write, with no +/// filesystem call; its device's one notice is the one it says as it is made, and each entry not +/// written after it is counted alone. +#[test] +fn a_store_with_no_directory_reads_and_writes_nothing_and_says_so_once() { + use crate::{DebugMessage, Degradation, MessageSink}; + use std::sync::{Arc, Mutex}; + let said: Arc>> = Arc::default(); + let heard = Arc::clone(&said); + let sink = MessageSink::new(move |message: &DebugMessage| { + heard.lock().unwrap().push(message.clone()); + }); + let store = Store::without_directory(BUILD, Some(sink)); + assert!(!store.has_directory() && store.directory().is_none()); + store.announce_no_directory( + "the default shader cache directory".to_owned(), + "there is none", + ); + let wanted = name(&BUILD, 1); + assert!(!store.holds(&wanted) && !store.holds_record(&wanted)); + assert!(store.write_soon(&wanted, vec![1; 64]).is_err()); + assert!(store.write_record_soon(&wanted, vec![1; 64]).is_err()); + let decode = |bytes: &[u8]| Ok::<_, ()>(bytes.to_vec()); + assert_eq!(store.load(&wanted, decode), Lookup::Absent); + assert_eq!(store.load_content(&wanted, Some), Lookup::Absent); + store.write_failed(); + store.write_failed(); + store.evict(&AtomicBool::new(false)); + assert!(!store.over_capacity()); + let counters = &store.counters; + assert_eq!(counters.write_failures.load(Ordering::Relaxed), 2); + for touched in [ + &counters.holds_questions, + &counters.entry_reads, + &counters.written_bytes, + &counters.writes_on_thread, + ] { + assert_eq!(touched.load(Ordering::Relaxed), 0); + } + let said = said.lock().unwrap(); + assert_eq!(said.len(), 1, "one notice: {said:?}"); + let notice = said[0].degradation.as_ref().expect("a degrade notice"); + assert_eq!(notice.degradation, Degradation::ShaderCacheEntryNotWritten); + assert_eq!(notice.object, "the default shader cache directory"); + assert!( + notice.reason.starts_with("there is none."), + "{}", + notice.reason + ); + assert_eq!( + said[0].id_name, + Degradation::ShaderCacheEntryNotWritten.code() + ); +} + /// The directory and its build directory are made only their owner may enter. #[cfg(unix)] #[test] @@ -529,7 +663,7 @@ fn the_directory_is_owner_only() { let store = store(&scratch.path().join("made"), BUILD, 1 << 20); let wanted = name(&BUILD, 1); put(&store, &wanted, 1, b"data"); - let entry = store.directory().entry_path(&wanted); + let entry = store.directory().unwrap().entry_path(&wanted); let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777; assert_eq!(mode(&scratch.path().join("made")), 0o700); assert_eq!(mode(entry.parent().unwrap()), 0o700); @@ -607,7 +741,7 @@ fn writers_in_several_processes_leave_whole_entries() { Lookup::Hit(data(n, b"own")) ); } - let build_dir = reader.directory().entry_path(&name(&BUILD, 0)); + let build_dir = reader.directory().unwrap().entry_path(&name(&BUILD, 0)); let build_dir = build_dir.parent().unwrap().parent().unwrap(); for group in fs::read_dir(build_dir).unwrap() { for file in fs::read_dir(group.unwrap().path()).unwrap() { @@ -767,7 +901,7 @@ fn a_record_of_another_device_is_refused_and_removed() { let one = identity(1); let store = store(scratch.path(), BUILD, 1 << 20); let name = name(&BUILD, 1); - let path = store.directory().record_path(&name); + let path = store.directory().unwrap().record_path(&name); for framed in [ seal(&identity(2), &data(2, b"payload")), seal(&one, &data(2, b"payload")), diff --git a/crates/metal2vulkan-runtime/src/tests/shader_cache_no_directory.rs b/crates/metal2vulkan-runtime/src/tests/shader_cache_no_directory.rs new file mode 100644 index 000000000..40a2025d6 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/shader_cache_no_directory.rs @@ -0,0 +1,101 @@ +//! A device whose options name no shader cache directory, where the platform's default does not +//! exist (no variable it is found by is set), is made all the same, as Metal makes its device +//! whatever its shader cache does: its cache is in memory alone. It says so once, as it is made, +//! as the degrade notice `ShaderCacheEntryNotWritten`, and never again however many entries go +//! unwritten; its pipeline states are made, each function translated once and found in the memo +//! after; nothing reaches a directory, and each entry it would have written is counted as not +//! written. +//! +//! The environment the default is looked up in is the test's own, empty +//! (`CacheSetup::of_in`), so the process's environment, which other tests share, is untouched. +//! +//! 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::options; +use super::descriptor_key_once::descriptor; +use crate::shader_cache::CacheSetup; +use crate::{Degradation, DegradeNotice, Device, MessageSink, PipelineOptions, ShaderCacheOptions}; +use metal2vulkan::metal::BlendFactor; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +/// The compiled functions every state is of: one vertex and one fragment. +const STAGES: u64 = 2; + +#[test] +fn a_device_with_no_default_directory_keeps_its_cache_in_memory_and_says_so_once() { + let heard: Arc>> = Arc::default(); + let hearing = Arc::clone(&heard); + let mut options = options(Path::new("unused")); + options.shader_cache = ShaderCacheOptions::default(); + options.messages = Some(MessageSink::new(move |message| { + if let Some(notice) = &message.degradation { + if notice.degradation == Degradation::ShaderCacheEntryNotWritten { + hearing.lock().unwrap().push(notice.clone()); + } + } + })); + let cache = CacheSetup::of_in(&options.shader_cache, "system_default_with", |_| None) + .expect("no default directory fails nothing"); + let device = Device::system_default_set_up(&options, &cache).expect("the device is made"); + assert_eq!(device.shader_cache_directory(), None); + let base = descriptor(&device); + let factors = [ + BlendFactor::Zero, + BlendFactor::One, + BlendFactor::SourceColor, + BlendFactor::SourceAlpha, + ]; + let mut kept = Vec::with_capacity(factors.len()); + for factor in factors { + 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 = factor; + kept.push( + device + .new_render_pipeline_state(&d, &PipelineOptions::default()) + .expect("a state made with its cache in memory alone"), + ); + } + let statistics = device.shader_cache_statistics(); + let translated = device.work_counts().functions_translated; + println!( + "NO DIRECTORY {}: {} states, {translated} functions translated, {statistics:?}", + device.properties().name, + kept.len(), + ); + // Each function is translated once and found in the memo by every later state. + assert_eq!(translated, STAGES); + // Nothing reached a directory: no entry given, queued, written or read, no driver record. + assert_eq!(statistics.writes, 0); + assert_eq!(statistics.writes_queued, 0); + assert_eq!(statistics.writes_on_thread, 0); + assert_eq!(statistics.written_bytes, 0); + assert_eq!(statistics.hits, 0); + assert_eq!(statistics.read_failures, 0); + assert_eq!(statistics.driver_saves, 0); + // Each entry it would have written is counted as not written: the two functions at least. + assert!( + statistics.write_failures >= STAGES, + "entries counted as not written: {statistics:?}" + ); + let heard = heard.lock().unwrap(); + assert_eq!( + heard.len(), + 1, + "said once, as the device was made: {heard:?}" + ); + assert_eq!(heard[0].object, "the default shader cache directory"); + assert!( + heard[0].reason.starts_with("there is none: "), + "{}", + heard[0].reason + ); + drop(kept); + drop(device); +} diff --git a/crates/metal2vulkan-runtime/src/texture/linear_alignment.rs b/crates/metal2vulkan-runtime/src/texture/linear_alignment.rs index 9c18b13e3..99b3a867d 100644 --- a/crates/metal2vulkan-runtime/src/texture/linear_alignment.rs +++ b/crates/metal2vulkan-runtime/src/texture/linear_alignment.rs @@ -348,8 +348,8 @@ impl Device { }); answers.insert(pf, answer); } - if whole { - // A failed write leaves the answers this device's alone. + // A failed write, or a store with no directory, leaves the answers this device's alone. + if whole && store.has_directory() { let _ = store.write_record_soon(&name, encode(&identity, &answers)); } answers diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 5cda96007..15fee1914 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// 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 = 2359; +pub const RUNTIME_VERSION: u32 = 2360; /// 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/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 050d2b769..2c98e14b8 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -8790,7 +8790,7 @@ method metal2vulkan-runtime::Device::sampler_ids_live pub fn sampler_ids_live(&s method metal2vulkan-runtime::Device::settle_in_place_checks pub fn settle_in_place_checks(&self, timeout: Duration) -> bool method metal2vulkan-runtime::Device::settle_queue_switch_check pub fn settle_queue_switch_check(&self, timeout: Duration) -> bool method metal2vulkan-runtime::Device::settle_submit_checks pub fn settle_submit_checks(&self, timeout: Duration) -> bool -method metal2vulkan-runtime::Device::shader_cache_directory pub fn shader_cache_directory(&self) -> &Path +method metal2vulkan-runtime::Device::shader_cache_directory pub fn shader_cache_directory(&self) -> Option<&Path> method metal2vulkan-runtime::Device::shader_cache_statistics pub fn shader_cache_statistics(&self) -> ShaderCacheStatistics method metal2vulkan-runtime::Device::shares_vk_queues pub fn shares_vk_queues(&self) -> bool method metal2vulkan-runtime::Device::sparse_tile_size pub fn sparse_tile_size(&self, texture_type: TextureType, pixel_format: PixelFormat, sample_count: u64) -> Size diff --git a/docs/API.md b/docs/API.md index bd361dd76..ebbf57192 100644 --- a/docs/API.md +++ b/docs/API.md @@ -4320,7 +4320,11 @@ bound. `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 + directory, a cap no entry fits in, or a write another process won. Or the device has no + directory: its `ShaderCacheOptions` named none and the platform's default does not exist (the + variable it is found by is unset or not absolute) or takes no write, so the device keeps its + cache in memory alone (`Device::shader_cache_directory` is `None`); that is announced as the + device is made, naming the default directory and why. 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 diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 09a8ddd6f..e4af09fd2 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -86,10 +86,12 @@ The translator keeps no cache; it gives you keys and encodings to keep one ### The runtime's shader cache The runtime keeps every shader it translates on disk, as Metal programs get from the OS, so a -second process does not translate it again. It cannot be turned off. +second process does not translate it again. It cannot be turned off; only a device with no +directory to keep it in (below, "Failures") keeps it in memory alone. -- **Where.** By default `~/Library/Caches/metal2vulkan` on macOS, `$XDG_CACHE_HOME/metal2vulkan` - elsewhere, or `~/.cache/metal2vulkan` when `XDG_CACHE_HOME` is unset. `ShaderCacheOptions` +- **Where.** By default `%LOCALAPPDATA%\metal2vulkan` on Windows, `~/Library/Caches/metal2vulkan` + on macOS, `$XDG_CACHE_HOME/metal2vulkan` elsewhere, or `~/.cache/metal2vulkan` when + `XDG_CACHE_HOME` is unset or not absolute. `ShaderCacheOptions` (in `DeviceOptions`, or `RawDevice` for an adopted device) names another directory. Several processes and builds may share it; a build reads only the translations of its own translator (its version, `SEMANTICS_VERSION`, `ARTIFACT_FORMAT_VERSION` and translator sources), so an @@ -161,7 +163,13 @@ second process does not translate it again. It cannot be turned off. 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. + `ShaderCacheOptions` names cannot be made or written. Where it names none and the default does + not exist (`LOCALAPPDATA` on Windows, `HOME` on macOS, both `XDG_CACHE_HOME` and `HOME` + elsewhere unset or not absolute) or cannot be made or written, the device is made with its + cache in memory alone: `Device::shader_cache_directory` is `None`, nothing is read from or + written to disk, and the device says so once as it is made, as the degrade notice + `metal2vulkan-degrade-shader-cache-entry-not-written` naming why; the entries it does not write + are counted in `write_failures`. 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 driver's own shader cache off (`__GL_SHADER_DISK_CACHE=0` for NVIDIA, `MESA_SHADER_CACHE_DISABLE=true` for Mesa). Give each test its own directory. diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index e2d5eba55..9f4e2868c 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -366,7 +366,7 @@ Columns: | `ExportedNoCopy` | A buffer descriptor that makes the buffer's memory exportable (`BufferDescriptor::exported_as`) with `NoCopy` contents | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal exports no buffer's memory | 1: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (new_buffer_with_descriptor_now)` | `-` | | `LongTextureBufferFillPattern` | A texture buffer's fill given a pattern of more than 32752 bytes (`fillTexture:...:bytes:length:`) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: Metal's process ends in the call | 1: `crates/metal2vulkan-runtime/src/blit_fill.rs (check_pattern)` | `-` | | `RangeOutOfBounds` | `offset..offset + size` runs past a resource of `length` bytes | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max, macOS 27.0.1: didModifyRange of 0+512 and of 240+64 on a buffer of 256 bytes both return; Metal's API validation alone refuses them | 4: `crates/metal2vulkan-runtime/src/argument_encoder.rs (target_offset)`, `crates/metal2vulkan-runtime/src/blit.rs (out_of_bounds)` (+2) | `-` | -| `ShaderCacheCapacity` | A shader cache capacity, on disk or in memory, of zero | every device (a public call's own check of its arguments) | `ours`: this crate's shader caches: Metal exposes no capacity | 1: `crates/metal2vulkan-runtime/src/shader_cache/mod.rs (of)` | `-` | +| `ShaderCacheCapacity` | A shader cache capacity, on disk or in memory, of zero | every device (a public call's own check of its arguments) | `ours`: this crate's shader caches: Metal exposes no capacity | 1: `crates/metal2vulkan-runtime/src/shader_cache/mod.rs (of_in)` | `-` | | `MaxCommandBufferCount` | A command queue's `maxCommandBufferCount` of zero | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max: Metal's command queue creation asserts "invalid descriptor.maxCommandBufferCount value 0", with and without API validation | 2: `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue_unshared_now)`, `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue_with_max_command_buffer_count_now)` | `-` | | `Texture` | A texture descriptor Metal stops (`Invalid`), or plain Metal answers nil for (`Nil`) | every device (a public call's own check of its arguments) | `delegated`: TextureProblem, section 9 | 7: `crates/metal2vulkan-runtime/src/buffer_texture.rs (shape_over)`, `crates/metal2vulkan-runtime/src/texture.rs (image_error)` (+3) | `-` | | `TextureView` | A texture view Metal stops, or a use of a texture its usage does not allow | every device (a public call's own check of its arguments) | `delegated`: ViewProblem, section 9 | 6: `crates/metal2vulkan-runtime/src/texture.rs (subview, 2 sites)`, `crates/metal2vulkan-runtime/src/texture.rs (view_as, 2 sites)` (+1) | `-` | @@ -867,7 +867,7 @@ Each refusal's sites, with the function that builds it. - `invalid::ExportedNoCopy`: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (new_buffer_with_descriptor_now)` - `invalid::LongTextureBufferFillPattern`: `crates/metal2vulkan-runtime/src/blit_fill.rs (check_pattern)` - `invalid::RangeOutOfBounds`: `crates/metal2vulkan-runtime/src/argument_encoder.rs (target_offset)`; `crates/metal2vulkan-runtime/src/blit.rs (out_of_bounds)`; `crates/metal2vulkan-runtime/src/managed.rs (did_modify_range)`; `crates/metal2vulkan-runtime/src/rate_map.rs (copy_parameter_data_to_buffer)` -- `invalid::ShaderCacheCapacity`: `crates/metal2vulkan-runtime/src/shader_cache/mod.rs (of)` +- `invalid::ShaderCacheCapacity`: `crates/metal2vulkan-runtime/src/shader_cache/mod.rs (of_in)` - `invalid::MaxCommandBufferCount`: `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue_unshared_now)`; `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue_with_max_command_buffer_count_now)` - `invalid::Texture`: `crates/metal2vulkan-runtime/src/buffer_texture.rs (shape_over)`; `crates/metal2vulkan-runtime/src/texture.rs (image_error)`; `crates/metal2vulkan-runtime/src/texture.rs (texture_as)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (planned_heap_texture, 2 sites)`; `crates/metal2vulkan-runtime/src/texture_descriptor.rs (error, 2 sites)` - `invalid::TextureView`: `crates/metal2vulkan-runtime/src/texture.rs (subview, 2 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (view_as, 2 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (view_error, 2 sites)`