diff --git a/crates/metal2vulkan-rt/Cargo.toml b/crates/metal2vulkan-rt/Cargo.toml index 4657f9f04..52fd6e97e 100644 --- a/crates/metal2vulkan-rt/Cargo.toml +++ b/crates/metal2vulkan-rt/Cargo.toml @@ -22,6 +22,8 @@ path = "src/lib.rs" ash = { workspace = true, features = ["std", "loaded"] } # The translator: Metal AIR to SPIR-V, through its public API only. metal2vulkan = { version = "0.2.0", path = "../metal2vulkan", features = ["ash"] } +# The keys of the pipelines' files in the cache directory. +sha2.workspace = true # The host clock of command buffer times on unix. [target.'cfg(unix)'.dependencies] diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 43a30b384..26866db0d 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -28,8 +28,9 @@ device against the floor below. floor's first. The consumer names an extension's dependencies too. It names the core Vulkan features its own work needs as `ConsumerFeature`s (`SamplerYcbcrConversion` for now): the device enables each one it reports, once, and `Device::features` lists those enabled. It names the - directory the device keeps its compiled kernels in, `pipeline_cache_dir` (see "The cache - directory"). + directory the device keeps its compiled kernels in, `pipeline_cache_dir`, and the most bytes + they take, `pipeline_cache_cap` (see "The cache directory"). With `None`, every boot lowers every + kernel and compiles every pipeline cold, so a consumer should pass a directory. - `Device::raw` gives the instance, physical device, device and queue family handles, and `Device::with_present_queue` runs the consumer's presents on the presenting queue under its lock. The runtime keeps owning every handle. @@ -41,7 +42,7 @@ The runtime runs four threads per device: the block-maker, the submit thread, th thread, and the reaper, which frees the semaphores and command pools the others give up, one at a time, so no driver free runs on the completion thread and a submission waits behind at most one, lowers the compute pipeline states' emulated-SIMD-group variants after their creation returned, -and writes the pipeline data to the cache directory when it is due. +and writes each new `VkPipeline`'s data to the cache directory. A device is torn down when its last handle, and the last handle of every object made from it, is dropped; a committed command buffer and the blocks the consumer holds do not keep it alive. Teardown stops the submit thread, which submits what is ready and ends what it holds with @@ -696,25 +697,35 @@ keeps two things in, for compute pipeline states: its lowering inputs (the variant), the device profile's fingerprint and the translator's semantics version. A state whose lowering is there reads it in place of lowering (`Metrics::translations_loaded`, beside `Metrics::translations`); a variant the translator - refused is kept too. The files take at most 256 MiB; past it the least recently used go. -- `pipelines-`: the `VkPipelineCache` data, which the driver keys by each - pipeline's module and specialization. Every `VkPipeline` is made through the device's - `VkPipelineCache`, which starts from this file. The reaper writes it once a `VkPipeline` was - made and 10 seconds have passed since the last write, and the device's end writes it a last - time. Data past 256 MiB is not written, and a file past it is not read: the cache starts empty. + refused is kept too. +- `pipelines//`: one file per `VkPipeline`, named by a SHA-256 over everything + its creation takes (the module's SPIR-V and entry point, its stage's flags and required subgroup + size, its specialization and the runtime's pipeline layout). A `VkPipeline` is made through a + `VkPipelineCache` of its own, started from its file where there is one. The reaper then reads + the cache's data and writes it as the file, unless the data is no longer than the file's (the + pipeline came from it), and destroys the cache, so a pipeline's creation writes nothing on the + calling thread. At most 64 caches wait for the reaper; past that a pipeline's data is not + written, and its next creation is a miss. + +The files of both kinds take at most `DeviceOptions::pipeline_cache_cap` bytes together (512 MiB +where it is `None`); past it the least recently used go first. A file's use is its time on disk, +moved forward when a use finds it more than an hour old, so the order holds across runs. +`Metrics::cache_bytes_written` counts the bytes the device wrote there. Each write is a temporary file renamed over its name, and each file checks itself (the translator's self-checking encoding, the pipeline data's checksum), so a file cut short is a -miss. A failed read or write is a miss too, and never fails a call. Devices open on one directory -share its files, each keeping the cap over the files it knows. With no directory, nothing is kept -on disk; the `VkPipelineCache` still serves the device's own pipelines. +miss. A failed read or write is a miss too, and never fails a call. Devices open on one +directory, in one process or several, share its files, each keeping the cap over the files it +knows: those there when it was made, and those it wrote or read since; a file another removed is +a miss. With no directory, nothing is kept on disk, and each `VkPipeline` is made without a +`VkPipelineCache`. ### Known gaps of pipeline states - No translation or `VkPipeline` compile runs ahead of the call or the dispatch that needs it, but the emulated-SIMD-group variant's lowering on the reaper: a state reads only its lowerings from the cache directory, and each `VkPipeline` past the first tile is made at its first dispatch, - through the pipeline data. + from its file where there is one. - A kernel that observes its threadgroup partition is lowered twice at creation (its variant and its plain module). For the observing kernel the device tests run, a grid template over threadgroup memory, the second lowering took 0.61 to 0.63 ms and the whole creation 2.7 to diff --git a/crates/metal2vulkan-rt/src/cache.rs b/crates/metal2vulkan-rt/src/cache.rs index 5ae0a2dbe..0ed038bfd 100644 --- a/crates/metal2vulkan-rt/src/cache.rs +++ b/crates/metal2vulkan-rt/src/cache.rs @@ -7,37 +7,46 @@ //! fingerprint and the translator's semantics version. The bytes are the translator's //! self-checking encoding (`CompiledFunction::to_bytes`), and bytes that do not decode for the //! key are a miss. A partial-threadgroups variant the translator refused is kept too, as a -//! marker. The files take at most [`TRANSLATION_BYTES`]; past it the least recently used -//! go. -//! - `pipelines-`: the device's `VkPipelineCache` data, which the driver keys by -//! each pipeline's module and specialization. It is loaded with the device, unless it is past -//! [`PIPELINE_BYTES`] or does not check, when the cache starts empty; it is written on the reaper -//! thread once a `VkPipeline` was made and [`SAVE_INTERVAL`] has passed since the last write, so -//! a run that is killed loses at most that, and at the device's end. +//! marker. +//! - `pipelines//`: one file per `VkPipeline`, named by the hex of a SHA-256 +//! over everything its creation takes ([`pipeline_key`]): the `VkPipelineCache` data of a cache +//! that made only that pipeline. A `VkPipeline` is made through a `VkPipelineCache` of its own, +//! started from its file where there is one; the reaper then reads the cache's data and writes +//! it as the file, unless the data is no longer than the file's (the pipeline came from it), +//! and destroys the cache. At most [`PENDING`] caches wait for the reaper: past it a pipeline's +//! cache is destroyed at once and its file not written, a miss at its next creation. //! -//! Every write is a temporary file renamed over its name, and every file checks itself (the -//! translator's encoding, the pipeline data's checksum), so a file cut short by a crash is a miss. -//! A failed read or write is a miss too: the caches never fail a call. Devices open on one -//! directory share its files, each keeping the cap over the files it knows. +//! Both kinds share one cap, the consumer's ([`DeviceOptions::pipeline_cache_cap`]): past it the +//! least recently used files go first. A file's use is its time on disk, moved forward at a use +//! when it is older than [`TOUCH`], so the order holds across runs and processes. Every write is +//! a temporary file renamed over its name, and every file checks itself (the translator's +//! encoding, the pipeline data's checksum), so a file cut short by a crash is a miss. A failed +//! read or write is a miss too: the caches never fail a call. Devices open on one directory, +//! in one process or several, share its files, each keeping the cap over the files it knows: +//! those there when it opened, and those it wrote or read since; a file another removed is a +//! miss. //! //! [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir +//! [`DeviceOptions::pipeline_cache_cap`]: crate::DeviceOptions::pipeline_cache_cap +use crate::counters::Counters; use crate::device::lock; use ash::vk; +use sha2::{Digest, Sha256}; use std::collections::BTreeMap; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; use std::sync::Mutex; -use std::time::{Duration, Instant, SystemTime}; +use std::time::{Duration, SystemTime}; -/// The most bytes of lowered kernels a cache directory keeps. -pub(crate) const TRANSLATION_BYTES: u64 = 256 << 20; -/// The most bytes of pipeline data loaded and written. -pub(crate) const PIPELINE_BYTES: u64 = 256 << 20; -/// The least time between two writes of the pipeline data. -pub(crate) const SAVE_INTERVAL: Duration = Duration::from_secs(10); +/// The cap of a cache directory where the consumer names none. +pub(crate) const DEFAULT_CAP: u64 = 512 << 20; +/// The most pipeline caches waiting for the reaper to write their data. +pub(crate) const PENDING: usize = 64; +/// How old a file's time is before a use moves it forward. +const TOUCH: Duration = Duration::from_secs(3600); /// How old a temporary file left by a run that ended mid-write is before it is removed. const STALE: Duration = Duration::from_secs(3600); /// The first bytes of a pipeline data file, before its length and its checksum. @@ -45,112 +54,151 @@ const MAGIC: &[u8; 8] = b"m2vpipe1"; /// What a translation file holds where the translator refused the lowering: bytes no lowering /// encodes to, and that a file cut short is not. const REFUSED: &[u8] = b"m2v-refused"; +/// The translations' directory, under the cache directory. +const TRANSLATIONS: &str = "translations"; +/// The pipelines' directory, under the cache directory: one directory per `pipelineCacheUUID`. +const PIPELINES: &str = "pipelines"; -/// A directory of files of at most `cap` bytes in all, the least recently used going first. +/// The files of a cache directory, `translations/` and `pipelines//`, at most +/// `cap` bytes in all, the least recently used going first. Its reads and writes run outside its +/// lock, which guards only what it knows of the files. pub(crate) struct Store { - dir: PathBuf, + root: PathBuf, cap: u64, - /// Each file by name: its length and when it was last used, in `clock`'s ticks. - files: BTreeMap, + known: Mutex, +} + +struct Known { + /// Each file by its path under the root: its length and when it was last used. + files: BTreeMap, total: u64, - clock: u64, } impl Store { - /// The store in `dir`, made where it is missing, with the files a run before left, the - /// least recently written first, evicted down to `cap`. - pub(crate) fn open(dir: PathBuf, cap: u64) -> Store { - let _ = fs::create_dir_all(&dir); - let now = SystemTime::now(); - let mut found = Vec::new(); - for entry in fs::read_dir(&dir).into_iter().flatten().flatten() { - let (Ok(meta), Ok(name)) = (entry.metadata(), entry.file_name().into_string()) else { - continue; - }; - let written = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH); - if !meta.is_file() { - continue; - } - if is_name(&name) { - found.push((written, name, meta.len())); - } else if now.duration_since(written).is_ok_and(|age| age > STALE) { - let _ = fs::remove_file(entry.path()); - } - } - found.sort(); - let mut store = Store { - dir, - cap, + /// The store in `root`, made where it is missing, with the files a run before left, each used + /// at its time on disk, evicted down to `cap`. + pub(crate) fn open(root: PathBuf, cap: u64) -> Store { + let _ = fs::create_dir_all(root.join(TRANSLATIONS)); + let _ = fs::create_dir_all(root.join(PIPELINES)); + let mut known = Known { files: BTreeMap::new(), total: 0, - clock: 0, }; - for (_, name, len) in found { - store.clock += 1; - store.total += len; - store.files.insert(name, (len, store.clock)); + let now = SystemTime::now(); + known.scan(&root, TRANSLATIONS, now); + let uuids = fs::read_dir(root.join(PIPELINES)).into_iter().flatten(); + for entry in uuids.flatten() { + let (Ok(kind), Ok(uuid)) = (entry.file_type(), entry.file_name().into_string()) else { + continue; + }; + if kind.is_dir() && is_uuid(&uuid) { + known.scan(&root, &format!("{PIPELINES}/{uuid}"), now); + } + } + known.evict(&root, cap); + Store { + root, + cap, + known: Mutex::new(known), } - store.evict(); - store } - /// The bytes of `name`, where the directory holds it: one this store wrote or found when it - /// opened, or one another device on the directory wrote since. - pub(crate) fn get(&mut self, name: &str) -> Option> { - let read = fs::read(self.dir.join(name)); - self.forget(name); - let bytes = read.ok()?; - self.clock += 1; - self.files - .insert(name.to_owned(), (bytes.len() as u64, self.clock)); - self.total += bytes.len() as u64; - self.evict(); + /// The bytes of `file`, a path under the root, where the directory holds it: one this store + /// wrote or found when it opened, or one another device on the directory wrote since. A use + /// moves an old file's time on disk forward. + pub(crate) fn get(&self, file: &str) -> Option> { + let path = self.root.join(file); + let Ok(bytes) = fs::read(&path) else { + lock(&self.known).forget(file); + return None; + }; + let now = SystemTime::now(); + let old = (fs::metadata(&path).and_then(|meta| meta.modified())) + .is_ok_and(|written| now.duration_since(written).is_ok_and(|age| age > TOUCH)); + if old { + let _ = fs::File::options() + .write(true) + .open(&path) + .and_then(|opened| opened.set_modified(now)); + } + lock(&self.known).used(&self.root, self.cap, file, bytes.len() as u64); Some(bytes) } - /// Keeps `bytes` as `name`, evicting the least recently used files past the cap. - pub(crate) fn put(&mut self, name: &str, bytes: &[u8]) { + /// Keeps `bytes` as `file`, evicting the least recently used files past the cap. False where + /// they were not written: past the cap alone, or a failed write. + pub(crate) fn put(&self, file: &str, bytes: &[u8]) -> bool { let len = bytes.len() as u64; - if len > self.cap || write_whole(&self.dir.join(name), bytes).is_err() { - return; + if len > self.cap || write_whole(&self.root.join(file), bytes).is_err() { + return false; } - self.forget(name); - self.clock += 1; - self.files.insert(name.to_owned(), (len, self.clock)); - self.total += len; - self.evict(); + lock(&self.known).used(&self.root, self.cap, file, len); + true } - /// Whether the directory holds `bytes` as `name`, reading the file only where its length is + /// Whether the directory holds `bytes` as `file`, reading it only where its length is /// theirs. - pub(crate) fn holds(&mut self, name: &str, bytes: &[u8]) -> bool { - fs::metadata(self.dir.join(name)).is_ok_and(|meta| meta.len() == bytes.len() as u64) - && self.get(name).is_some_and(|held| held == bytes) + pub(crate) fn holds(&self, file: &str, bytes: &[u8]) -> bool { + fs::metadata(self.root.join(file)).is_ok_and(|meta| meta.len() == bytes.len() as u64) + && self.get(file).is_some_and(|held| held == bytes) } /// The bytes the store holds. #[cfg(test)] pub(crate) fn total(&self) -> u64 { - self.total + lock(&self.known).total + } +} + +impl Known { + /// Notes the files of `dir`, a directory under `root`, and removes its stale temporary files. + fn scan(&mut self, root: &Path, dir: &str, now: SystemTime) { + for entry in fs::read_dir(root.join(dir)).into_iter().flatten().flatten() { + let (Ok(meta), Ok(name)) = (entry.metadata(), entry.file_name().into_string()) else { + continue; + }; + if !meta.is_file() { + continue; + } + let written = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH); + if is_name(&name) { + self.note(format!("{dir}/{name}"), meta.len(), written); + } else if now.duration_since(written).is_ok_and(|age| age > STALE) { + let _ = fs::remove_file(entry.path()); + } + } } - fn evict(&mut self) { - while self.total > self.cap { + /// Notes `file` used now, `len` bytes long, evicting the least recently used files past + /// `cap`. + fn used(&mut self, root: &Path, cap: u64, file: &str, len: u64) { + self.note(file.to_owned(), len, SystemTime::now()); + self.evict(root, cap); + } + + fn note(&mut self, file: String, len: u64, used: SystemTime) { + self.forget(&file); + self.total += len; + self.files.insert(file, (len, used)); + } + + fn evict(&mut self, root: &Path, cap: u64) { + while self.total > cap { let Some(oldest) = self .files .iter() .min_by_key(|(_, &(_, used))| used) - .map(|(name, _)| name.clone()) + .map(|(file, _)| file.clone()) else { break; }; - let _ = fs::remove_file(self.dir.join(&oldest)); + let _ = fs::remove_file(root.join(&oldest)); self.forget(&oldest); } } - fn forget(&mut self, name: &str) { - if let Some((len, _)) = self.files.remove(name) { + fn forget(&mut self, file: &str) { + if let Some((len, _)) = self.files.remove(file) { self.total -= len; } } @@ -158,10 +206,17 @@ impl Store { /// A file name the store keeps: 64 lowercase hex digits, a SHA-256's. fn is_name(name: &str) -> bool { - name.len() == 64 - && name - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + name.len() == 64 && is_hex(name) +} + +/// A pipelines directory's name: 32 lowercase hex digits, a `pipelineCacheUUID`'s. +fn is_uuid(name: &str) -> bool { + name.len() == 2 * vk::UUID_SIZE && is_hex(name) +} + +fn is_hex(name: &str) -> bool { + name.bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) } /// The lowercase hex of `bytes`. @@ -219,132 +274,163 @@ pub(crate) fn frame(data: &[u8]) -> Vec { file } -/// A device's caches. -pub(crate) struct Caches { - translations: Option>, - /// The pipeline data's file, where there is a directory. - pipelines: Option, - /// Every `VkPipeline` of the device is made through it. - pub(crate) pipeline_cache: vk::PipelineCache, - save: Mutex, +/// The key of a `VkPipeline`'s file: a SHA-256 over what its creation takes, `module` (the +/// module's digest, [`module_digest`]) and its specialization's `values`, so two creations with +/// one key make one pipeline. +pub(crate) fn pipeline_key(module: &[u8; 32], values: &[u8]) -> [u8; 32] { + let mut hash = Sha256::new(); + hash.update(module); + hash.update((values.len() as u64).to_le_bytes()); + hash.update(values); + hash.finalize().into() } -/// When the pipeline data was last written, and whether a `VkPipeline` was made since. -struct Save { - last: Instant, - made: bool, +/// The digest of a module's part of its pipelines' creation: its SPIR-V, its entry point, its +/// stage's flags and required subgroup size, the specialization's constant IDs, and the pipeline +/// layout's, which is the runtime's own (`layout`, the words that describe it). +pub(crate) fn module_digest( + spirv: &[u32], + entry: &[u8], + flags: vk::PipelineShaderStageCreateFlags, + subgroup: Option, + constant_ids: &[u32], + layout: &[u32], +) -> [u8; 32] { + let mut hash = Sha256::new(); + let words = |hash: &mut Sha256, words: &[u32]| { + hash.update((words.len() as u64).to_le_bytes()); + for word in words { + hash.update(word.to_le_bytes()); + } + }; + words(&mut hash, spirv); + hash.update((entry.len() as u64).to_le_bytes()); + hash.update(entry); + hash.update(flags.as_raw().to_le_bytes()); + hash.update(subgroup.map_or([0; 5], |size| { + let mut bytes = [1; 5]; + bytes[1..].copy_from_slice(&size.to_le_bytes()); + bytes + })); + words(&mut hash, constant_ids); + words(&mut hash, layout); + hash.finalize().into() +} + +/// A device's caches. +pub(crate) struct Caches { + store: Option, + /// The device's pipelines directory under the root: `pipelines/`. + pipelines: String, + /// The pipeline caches given to the reaper and not written yet. + pending: AtomicUsize, +} + +/// A `VkPipeline`'s cache, for the reaper to write the data of and destroy. +pub(crate) struct KeepPipeline { + pub(crate) cache: vk::PipelineCache, + /// The pipeline's key. + pub(crate) key: [u8; 32], + /// The length of the data the cache started from. + pub(crate) seeded: usize, } impl Caches { /// The caches of a device whose pipeline data is keyed by `uuid`, in `dir` where there is - /// one: its `VkPipelineCache` made from the data a run before wrote. - /// - /// # Safety - /// - /// `device` is live. - pub(crate) unsafe fn new( - device: &ash::Device, - dir: Option<&Path>, - uuid: [u8; vk::UUID_SIZE], - ) -> Result { - let translations = - dir.map(|dir| Mutex::new(Store::open(dir.join("translations"), TRANSLATION_BYTES))); - let pipelines = dir.map(|dir| dir.join(format!("pipelines-{}", hex(&uuid)))); - let loaded = pipelines - .as_ref() - .filter(|path| fs::metadata(path).is_ok_and(|meta| meta.len() <= PIPELINE_BYTES + 24)) - .and_then(|path| fs::read(path).ok()); - let data = loaded.as_deref().and_then(unframe).unwrap_or_default(); - let info = vk::PipelineCacheCreateInfo::default().initial_data(data); - // SAFETY: the caller's contract; `data` is empty or what `vkGetPipelineCacheData` gave, - // whole, as its checksum shows. - let pipeline_cache = unsafe { device.create_pipeline_cache(&info, None) }?; - Ok(Caches { - translations, + /// one, at most `cap` bytes in all. + pub(crate) fn new(dir: Option<&Path>, cap: u64, uuid: [u8; vk::UUID_SIZE]) -> Caches { + let pipelines = format!("{PIPELINES}/{}", hex(&uuid)); + let store = dir.map(|dir| { + let _ = fs::create_dir_all(dir.join(&pipelines)); + Store::open(dir.to_owned(), cap) + }); + Caches { + store, pipelines, - pipeline_cache, - save: Mutex::new(Save { - last: Instant::now(), - made: false, - }), - }) + pending: AtomicUsize::new(0), + } + } + + /// Whether the device has a cache directory. + pub(crate) fn on_disk(&self) -> bool { + self.store.is_some() + } + + fn translation_file(key: &[u8]) -> String { + format!("{TRANSLATIONS}/{}", hex(key)) } /// The bytes kept for a lowered kernel of key digest `key`. pub(crate) fn translation(&self, key: &[u8]) -> Option> { - lock(self.translations.as_ref()?).get(&hex(key)) + self.store.as_ref()?.get(&Caches::translation_file(key)) } /// Keeps the bytes of a lowered kernel of key digest `key`. - pub(crate) fn keep_translation(&self, key: &[u8], bytes: &[u8]) { - if let Some(store) = &self.translations { - lock(store).put(&hex(key), bytes); + pub(crate) fn keep_translation(&self, key: &[u8], bytes: &[u8], counters: &Counters) { + if let Some(store) = &self.store { + if store.put(&Caches::translation_file(key), bytes) { + counters.cache_written(bytes.len() as u64); + } } } /// Whether the translator refused the lowering of key digest `key` on a device before. pub(crate) fn refused(&self, key: &[u8]) -> bool { - self.translations + self.store .as_ref() - .is_some_and(|store| lock(store).holds(&hex(key), REFUSED)) + .is_some_and(|store| store.holds(&Caches::translation_file(key), REFUSED)) } /// Keeps the translator's refusal of the lowering of key digest `key`. - pub(crate) fn keep_refusal(&self, key: &[u8]) { - self.keep_translation(key, REFUSED); + pub(crate) fn keep_refusal(&self, key: &[u8], counters: &Counters) { + self.keep_translation(key, REFUSED, counters); } - /// Notes a `VkPipeline` made: true where it is the first since the pipeline data's last - /// write, when the reaper is to be woken to time the next. - pub(crate) fn made(&self) -> bool { - if self.pipelines.is_none() { - return false; - } - let mut save = lock(&self.save); - let first = !save.made; - save.made = true; - first + fn pipeline_file(&self, key: &[u8; 32]) -> String { + format!("{}/{}", self.pipelines, hex(key)) } - /// How long until the pipeline data is due, where a `VkPipeline` was made since its last - /// write. - pub(crate) fn due_in(&self) -> Option { - let save = lock(&self.save); - save.made - .then(|| SAVE_INTERVAL.saturating_sub(save.last.elapsed())) + /// The data kept for the `VkPipeline` of `key`, where its file checks. + pub(crate) fn pipeline_data(&self, key: &[u8; 32]) -> Option> { + let file = self.store.as_ref()?.get(&self.pipeline_file(key))?; + unframe(&file).map(<[u8]>::to_vec) } - /// Writes the pipeline data, where a `VkPipeline` was made since its last write. - pub(crate) fn save(&self, device: &ash::Device) { - let Some(path) = &self.pipelines else { - return; - }; - { - let mut save = lock(&self.save); - if !save.made { - return; - } - save.made = false; - save.last = Instant::now(); - } - // SAFETY: the cache is the device's, and stays until the device's end, which writes it - // last. - let Ok(data) = (unsafe { device.get_pipeline_cache_data(self.pipeline_cache) }) else { - return; - }; - if data.len() as u64 <= PIPELINE_BYTES { - let _ = write_whole(path, &frame(&data)); - } + /// Takes a place among the caches waiting for the reaper: false past [`PENDING`], when the + /// pipeline's cache is to be destroyed at once. + pub(crate) fn take_pending(&self) -> bool { + self.pending + .fetch_update(Relaxed, Relaxed, |pending| { + (pending < PENDING).then_some(pending + 1) + }) + .is_ok() } - /// Writes the pipeline data a last time and destroys the cache. + /// On the reaper: writes the data of `kept`'s cache as its pipeline's file where it is longer + /// than the data the cache started from, then destroys the cache. /// /// # Safety /// - /// No pipeline is being made from the cache, and none will be. - pub(crate) unsafe fn destroy(&self, device: &ash::Device) { - self.save(device); + /// The cache is the device's, and no pipeline is being made from it. + pub(crate) unsafe fn keep_pipeline( + &self, + device: &ash::Device, + kept: KeepPipeline, + counters: &Counters, + ) { // SAFETY: the caller's contract. - unsafe { device.destroy_pipeline_cache(self.pipeline_cache, None) }; + let data = unsafe { device.get_pipeline_cache_data(kept.cache) }; + // SAFETY: the caller's contract; the data is read. + unsafe { device.destroy_pipeline_cache(kept.cache, None) }; + self.pending.fetch_sub(1, Relaxed); + let (Some(store), Ok(data)) = (&self.store, data) else { + return; + }; + if data.len() > kept.seeded { + let file = frame(&data); + if store.put(&self.pipeline_file(&kept.key), &file) { + counters.cache_written(file.len() as u64); + } + } } } diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 925f31579..ffc9a5e57 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -80,6 +80,7 @@ struct Atomics { passes: AtomicU64, barriers: AtomicU64, bytes_copied: AtomicU64, + cache_bytes_written: AtomicU64, pipelines_created: AtomicU64, first_use_waits: AtomicU64, first_use_wait_nanos: AtomicU64, @@ -166,6 +167,11 @@ impl Counters { self.atomics.bytes_copied.fetch_add(bytes, Relaxed); } + /// `bytes` more written to the cache directory ([`Metrics::cache_bytes_written`]). + pub(crate) fn cache_written(&self, bytes: u64) { + self.atomics.cache_bytes_written.fetch_add(bytes, Relaxed); + } + /// One more segment end whose barrier reaches the host. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn reach_host(&self) { @@ -251,6 +257,7 @@ impl Counters { blocks_made: a.blocks_made.load(Relaxed), translations: a.translations.load(Relaxed), translations_loaded: a.translations_loaded.load(Relaxed), + cache_bytes_written: a.cache_bytes_written.load(Relaxed), ring_writes: a.ring_writes.load(Relaxed), upload_waits: a.upload_waits.load(Relaxed), synchronizations: a.synchronizations.load(Relaxed), @@ -321,6 +328,11 @@ pub struct Metrics { pub translations: u64, /// Lowered kernels a pipeline state took from the cache directory in place of a lowering. pub translations_loaded: u64, + /// Bytes written to the cache directory ([`DeviceOptions::pipeline_cache_dir`]): lowered + /// kernels, and each `VkPipeline`'s data where it did not come from its file. + /// + /// [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir + pub cache_bytes_written: u64, /// Writes into the parameter ring: a dispatch's parameter block, its fields past the push /// window (a kernel with more than 28 buffers), and each `set_bytes` copy. pub ring_writes: u64, diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index 2b1d4daaf..4e3367d53 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -2,7 +2,7 @@ //! its queues, its memory blocks, its threads, quiesce and teardown. use crate::arrays::Arrays; -use crate::cache::Caches; +use crate::cache::{self, Caches}; use crate::complete::{self, Done}; use crate::counters::{Counters, Gauge}; use crate::error::Error; @@ -194,7 +194,7 @@ pub(crate) struct Core { pub(crate) ids: Ids, /// The translator, for what device creation enables, under the identity domains. pub(crate) translator: metal2vulkan::device::Device, - /// The lowered kernels on disk and the `VkPipelineCache` every pipeline is made through. + /// The lowered kernels and the pipelines' data on disk. pub(crate) caches: Caches, /// The compiled kernels by content, which every compute pipeline state of a content shares. pub(crate) kernels: KernelMap, @@ -234,16 +234,23 @@ pub struct DeviceOptions { /// Vulkan features the consumer needs for its own raw Vulkan work, each enabled where the /// device reports it ([`Device::features`]). pub features: Vec, - /// The directory the device keeps compute kernels it lowered and its compiled pipeline data - /// in, made where it is missing, so a later device on it, in this run or the next, takes - /// them in place of lowering and compiling again ([`Metrics::translations_loaded`]). Each - /// kind is bounded at 256 MiB, the least recently used kernels going first past it; a file - /// that does not check, or a failed read or write, is a miss and never fails a call. `None` - /// keeps nothing on disk. Metal keeps its compiled shaders in a system cache the program does - /// not name. + /// The directory the device keeps compute kernels it lowered and each `VkPipeline`'s + /// compiled data in, made where it is missing, so a later device on it, in this process or + /// another, takes them in place of lowering and compiling again + /// ([`Metrics::translations_loaded`]). The files take at most + /// [`pipeline_cache_cap`](Self::pipeline_cache_cap) bytes, the least recently used going + /// first past it; a file that does not check, or a failed read or write, is a miss and never + /// fails a call. `None` keeps nothing on disk, so every boot lowers every kernel and compiles + /// every pipeline cold: a consumer should pass a directory. Metal keeps its compiled shaders + /// in a system cache the program does not name. /// /// [`Metrics::translations_loaded`]: crate::Metrics::translations_loaded pub pipeline_cache_dir: Option, + /// The most bytes the files in [`pipeline_cache_dir`](Self::pipeline_cache_dir) take, the + /// lowered kernels and the pipelines' data together; `None` is 512 MiB. Devices on one + /// directory share its files, each keeping the cap over the files it knows: those there when + /// it was made, and those it wrote or read since. + pub pipeline_cache_cap: Option, } /// Takes a lock. A panic while another thread held it leaves what it guards usable (a queue, the @@ -363,20 +370,11 @@ impl Device { answer(&mut properties.properties.limits); let max_allocations = properties.properties.limits.max_memory_allocation_count; let granularity = properties.properties.limits.buffer_image_granularity; - let directory = options.pipeline_cache_dir.as_deref(); - let uuid = properties.properties.pipeline_cache_uuid; - // SAFETY: the device is live. - let caches = match unsafe { Caches::new(&device, directory, uuid) } { - Ok(caches) => caches, - Err(result) => { - // SAFETY: nothing made from the device is left. - unsafe { device.destroy_device(None) }; - return Err(Error::Vulkan { - call: "vkCreatePipelineCache", - result, - }); - } - }; + let caches = Caches::new( + options.pipeline_cache_dir.as_deref(), + (options.pipeline_cache_cap).unwrap_or(cache::DEFAULT_CAP), + properties.properties.pipeline_cache_uuid, + ); let counters = Counters::new(); // SAFETY: the device was made from `raw` with `capabilities.features`, and the family is // its queues' family. @@ -384,12 +382,8 @@ impl Device { let (memory_types, filler, done, arrays, layout) = match made { Ok(made) => made, Err(error) => { - // SAFETY: nothing made from the device is left but the caches, which made no - // pipeline. - unsafe { - caches.destroy(&device); - device.destroy_device(None); - } + // SAFETY: nothing made from the device is left. + unsafe { device.destroy_device(None) }; return Err(error); } }; @@ -1124,10 +1118,8 @@ impl Drop for Core { for _ in 0..ring_blocks { self.counters.fall(Gauge::Blocks); } - // SAFETY: the device is idle, and nothing made from it is left but these objects; the - // caches write the pipeline data a last time. + // SAFETY: the device is idle, and nothing made from it is left but these objects. let zero_source = unsafe { - self.caches.destroy(&self.device); self.device.destroy_pipeline_layout(self.layout, None); self.arrays.destroy(&self.device, &self.counters); self.done.destroy(&self.device); diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index 0c32336ef..59990d59b 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -36,6 +36,7 @@ //! encoding thread. use crate::arrays::BINDINGS; +use crate::cache::{module_digest, pipeline_key, KeepPipeline}; use crate::counters::{Gauge, Metric}; use crate::device::{lock, Core}; use crate::error::{Error, Gap, Refusal}; @@ -235,6 +236,8 @@ pub(crate) struct Kernel { module: vk::ShaderModule, /// The module's entry point. entry: CString, + /// The digest of the module's part of its pipelines' keys in the cache directory. + digest: [u8; 32], pub(crate) interface: Interface, /// The `VkPipeline`s made so far, by their specialization. variants: Mutex>, @@ -405,8 +408,8 @@ impl crate::Device { /// `VkPipeline` is made here too, and twice for one that does (its partial-threadgroups /// variant and its plain module). Where the device has a cache directory /// ([`DeviceOptions::pipeline_cache_dir`]), a lowering a device made before is read from it - /// in place of lowering again, and every `VkPipeline` is made through the pipeline data it - /// keeps. The content's other `VkPipeline`s are made later, each by the first encoding call + /// in place of lowering again, and every `VkPipeline` is made from its file there where it + /// has one. The content's other `VkPipeline`s are made later, each by the first encoding call /// of any of its states that needs it ([`ComputePipelineState`]). For a kernel whose tier runs /// only whole SIMD groups, the reaper lowers its emulated-SIMD-group variant after this /// returns, through the cache directory too. @@ -502,7 +505,7 @@ impl Compiled { Err(TranslationError::Unsupported(refused)) if refused.feature == Feature::GpuEncodedIndirectCommands => { - core.caches.keep_refusal(&variant_key); + core.caches.keep_refusal(&variant_key, &core.counters); None } Err(error) => return Err(Error::Translation(error)), @@ -654,7 +657,7 @@ fn lower( core.counters.count(Metric::Translations); let lowered = translator.compile_function_from_entries(function, inputs, budget, entries)?; core.caches - .keep_translation(key.digest(), &lowered.to_bytes()); + .keep_translation(key.digest(), &lowered.to_bytes(), &core.counters); Ok(lowered) } @@ -1079,7 +1082,7 @@ impl Emulated { let compiled = match lower(core, &self.function, &self.inputs, &budget, &entries) { Ok(compiled) => compiled, Err(TranslationError::Unsupported(_)) => { - core.caches.keep_refusal(&key); + core.caches.keep_refusal(&key, &core.counters); return Lowered::Refused; } Err(_) => return Lowered::Refused, @@ -1115,11 +1118,30 @@ impl Kernel { let stage = pipeline.stage; // The translator's entry points hold no NUL; one that did would name no entry point. let entry = CString::new(stage.entry_point).map_err(|_| gap())?; + let digest = core.caches.on_disk().then(|| { + let ids: Vec = interface.constants.iter().map(|&(id, _)| id).collect(); + let layout: Vec = std::iter::once(PUSH_BYTES) + .chain( + BINDINGS + .iter() + .flat_map(|&(binding, kind, count)| [binding, kind.as_raw() as u32, count]), + ) + .collect(); + module_digest( + &stage.spirv, + entry.as_bytes(), + interface.stage_flags, + interface.required_subgroup_size, + &ids, + &layout, + ) + }); // SAFETY: the words are the translator's SPIR-V, for the features device creation enabled. let module = unsafe { Kernel::module(core, &stage.spirv) }?; Ok(Kernel { module, entry, + digest: digest.unwrap_or_default(), interface, variants: Mutex::new(Vec::new()), }) @@ -1196,19 +1218,43 @@ impl Kernel { .stage(stage) .layout(core.layout); let device = &core.device; - let cache = core.caches.pipeline_cache; + // With a cache directory, a cache of the pipeline's own, started from its file. + let mut kept = None; + if core.caches.on_disk() { + let key = pipeline_key(&self.digest, &values); + let seed = core.caches.pipeline_data(&key).unwrap_or_default(); + let cache_info = vk::PipelineCacheCreateInfo::default().initial_data(&seed); + // SAFETY: the data is empty or what `vkGetPipelineCacheData` gave for this device's + // `pipelineCacheUUID`, whole, as its checksum shows. A cache the driver refuses is a + // miss: the pipeline is made without one. + if let Ok(cache) = unsafe { device.create_pipeline_cache(&cache_info, None) } { + kept = Some(KeepPipeline { + cache, + key, + seeded: seed.len(), + }); + } + } + let cache = kept + .as_ref() + .map_or(vk::PipelineCache::null(), |kept| kept.cache); // SAFETY: the module, the layout and the cache are the device's, and the specialization // gives each of the kernel's constants a 4-byte value. let made = unsafe { device.create_compute_pipelines(cache, &[info], None) }; + if let Some(kept) = kept { + if made.is_ok() && core.caches.take_pending() { + core.reaper.give(Job::KeepPipeline(kept)); + } else { + // SAFETY: no pipeline is being made from the cache. + unsafe { device.destroy_pipeline_cache(kept.cache, None) }; + } + } let pipeline = made.map_err(|(_, result)| Error::Vulkan { call: "vkCreateComputePipelines", result, })?[0]; core.counters.count(Metric::PipelinesCreated); core.counters.rise(Gauge::Pipelines); - if core.caches.made() { - core.reaper.wake(); - } Ok(pipeline) } diff --git a/crates/metal2vulkan-rt/src/reaper.rs b/crates/metal2vulkan-rt/src/reaper.rs index 70b733b9d..cb87963b4 100644 --- a/crates/metal2vulkan-rt/src/reaper.rs +++ b/crates/metal2vulkan-rt/src/reaper.rs @@ -1,9 +1,10 @@ //! The reaper thread: it frees what the runtime's other threads give up, one object at a time, runs //! a teardown that starts on the completion thread, lowers the pipeline states' emulated-SIMD-group -//! variants after their creation returned, and writes the pipeline data to the cache directory -//! when it is due. No driver free runs on the completion thread, so no completion waits behind -//! one, and a submission on another thread waits behind at most one free. +//! variants after their creation returned, and writes each new `VkPipeline`'s data to the cache +//! directory. No driver free runs on the completion thread, so no completion waits behind one, and +//! a submission on another thread waits behind at most one free. +use crate::cache::KeepPipeline; use crate::counters::Gauge; use crate::device::{lock, Core}; use crate::pipeline::Compiled; @@ -32,6 +33,8 @@ pub(crate) enum Job { Free(Free), /// The device's teardown, after its last handle dropped on the completion thread. Teardown(Teardown), + /// A new `VkPipeline`'s cache, whose data goes to the cache directory. + KeepPipeline(KeepPipeline), } /// A teardown the reaper runs. @@ -116,26 +119,21 @@ impl Reaper { } } - /// Wakes the reaper to time the pipeline data's next write. - pub(crate) fn wake(&self) { - // Taken so the wake cannot fall between the reaper's look at the caches and its wait. - drop(lock(&self.state)); - self.changed.notify_one(); - } - /// Tells the reaper to end once its queue is empty. pub(crate) fn stop(&self) { lock(&self.state).stop = true; self.changed.notify_one(); } - /// At the core's drop, the reaper having ended: frees what is left. No teardown is left: one - /// holds blocks, and so the core. + /// At the core's drop, the reaper having ended: frees what is left, and writes the data of + /// the pipeline caches left. No teardown is left: one holds blocks, and so the core. pub(crate) fn drain(&self, core: &Core) { let jobs = std::mem::take(&mut lock(&self.state).jobs); for job in jobs { - if let Job::Free(object) = job { - free(core, object); + match job { + Job::Free(object) => free(core, object), + Job::KeepPipeline(kept) => keep(core, kept), + Job::Teardown(_) => {} } } } @@ -218,19 +216,25 @@ fn free(core: &Core, object: Free) { } } +/// Writes the data of a new `VkPipeline`'s cache and destroys it. +fn keep(core: &Core, kept: KeepPipeline) { + // SAFETY: the pipeline was made from the cache, which nothing else holds. + unsafe { + core.caches + .keep_pipeline(&core.device, kept, &core.counters) + }; +} + /// What the reaper does next. enum Next { Job(Job), /// Lower a state's emulated variant. Lower(Weak), - /// Write the pipeline data. - Save, /// End, after telling the states whose lowering is left that it will not run. End(VecDeque>), } -/// The reaper thread, until it is stopped and its queue is empty. The device's end writes the -/// pipeline data a last time. +/// The reaper thread, until it is stopped and its queue is empty. pub(crate) fn run(core: Arc) { let reaper = &core.reaper; loop { @@ -246,31 +250,21 @@ pub(crate) fn run(core: Arc) { if let Some(lowering) = state.lowerings.pop_front() { break Next::Lower(lowering); } - state = match core.caches.due_in() { - Some(wait) if wait.is_zero() => break Next::Save, - Some(wait) => { - reaper - .changed - .wait_timeout(state, wait) - .unwrap_or_else(PoisonError::into_inner) - .0 - } - None => reaper - .changed - .wait(state) - .unwrap_or_else(PoisonError::into_inner), - }; + state = reaper + .changed + .wait(state) + .unwrap_or_else(PoisonError::into_inner); } }; match next { Next::Job(Job::Free(object)) => free(&core, object), Next::Job(Job::Teardown(teardown)) => teardown(&core), + Next::Job(Job::KeepPipeline(kept)) => keep(&core, kept), Next::Lower(lowering) => { if let Some(state) = lowering.upgrade() { state.lower_emulated(); } } - Next::Save => core.caches.save(&core.device), Next::End(left) => { for state in left.iter().filter_map(Weak::upgrade) { state.quiesce_emulated(); diff --git a/crates/metal2vulkan-rt/src/tests/cache.rs b/crates/metal2vulkan-rt/src/tests/cache.rs index eb4c12742..6daee31ba 100644 --- a/crates/metal2vulkan-rt/src/tests/cache.rs +++ b/crates/metal2vulkan-rt/src/tests/cache.rs @@ -1,10 +1,12 @@ -//! The cache directory on the host: a store filled past its cap keeps the most recently used -//! files within it, devices on one directory share its files, and pipeline data that does not -//! check is a miss. +//! The cache directory on the host: lowered kernels and pipelines' data share one cap, past which +//! the least recently used files go, by their time on disk across stores; stores on one directory +//! share its files, a file another removed is a miss, and pipeline data that does not check is a +//! miss. use crate::cache::{frame, unframe, Store}; use std::fs; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime}; /// A directory of its own under the OS temp dir, removed when dropped. struct Scratch(PathBuf); @@ -16,18 +18,22 @@ impl Scratch { Scratch(dir) } - /// The bytes of every file in the directory. + /// The bytes of every file under the directory. fn bytes(&self) -> u64 { - fs::read_dir(&self.0) - .expect("the directory") - .map(|entry| { - entry - .expect("an entry") - .metadata() - .expect("its metadata") - .len() - }) - .sum() + fn under(dir: &Path) -> u64 { + fs::read_dir(dir) + .expect("the directory") + .map(|entry| { + let entry = entry.expect("an entry"); + let meta = entry.metadata().expect("its metadata"); + match meta.is_dir() { + true => under(&entry.path()), + false => meta.len(), + } + }) + .sum() + } + under(&self.0) } } @@ -37,22 +43,39 @@ impl Drop for Scratch { } } -/// A file name the store keeps: 64 hex digits. +/// A file the store keeps: a lowering for even `n`, a pipeline's data for odd. fn name(n: u8) -> String { - format!("{n:064x}") + match n % 2 { + 0 => format!("translations/{n:064x}"), + _ => format!("pipelines/{:032x}/{n:064x}", 7), + } +} + +/// Writes `bytes` as `file` under `root`, as another device would, with its time on disk +/// `age` ago. +fn written(root: &Path, file: &str, bytes: &[u8], age: Duration) { + let path = root.join(file); + fs::create_dir_all(path.parent().expect("a parent")).expect("the directory"); + fs::write(&path, bytes).expect("the file"); + let opened = fs::File::options().write(true).open(&path).expect("open"); + opened + .set_modified(SystemTime::now() - age) + .expect("its time"); } #[test] fn a_store_filled_past_its_cap_keeps_the_most_recently_used_within_it() { let scratch = Scratch::new("store-cap"); - let mut store = Store::open(scratch.0.clone(), 1000); + let store = Store::open(scratch.0.clone(), 1000); for n in 0..10 { - store.put(&name(n), &[n; 300]); + assert!(store.put(&name(n), &[n; 300]), "file {n} written"); // Read after every write, the first file stays the most recently used. assert_eq!(store.get(&name(0)), Some(vec![0; 300]), "file 0 after {n}"); assert!(store.total() <= 1000, "{} bytes after {n}", store.total()); assert_eq!(scratch.bytes(), store.total(), "the disk after {n}"); } + // Two lowerings (0, 8) and a pipeline's data (9) are the three most recent: both kinds share + // the cap. let kept: Vec = (0..10).map(|n| store.get(&name(n)).is_some()).collect(); let mut want = [false; 10]; for n in [0, 8, 9] { @@ -60,7 +83,7 @@ fn a_store_filled_past_its_cap_keeps_the_most_recently_used_within_it() { } assert_eq!(kept, want, "the files kept"); // A file past the cap alone is not kept, and evicts nothing. - store.put(&name(10), &[10; 1001]); + assert!(!store.put(&name(10), &[10; 1001])); assert_eq!(store.get(&name(10)), None); assert_eq!(store.total(), 900); // Reopened with a smaller cap, the store evicts down to it. @@ -70,17 +93,42 @@ fn a_store_filled_past_its_cap_keeps_the_most_recently_used_within_it() { assert_eq!(scratch.bytes(), 600); } +#[test] +fn a_store_opened_on_files_others_wrote_evicts_the_least_recently_used_on_disk() { + let scratch = Scratch::new("store-age"); + let hour = Duration::from_secs(3600); + // Four files of 100 bytes, written 5, 4, 3 and 2 hours ago by other devices. + for n in 0..4u8 { + written(&scratch.0, &name(n), &[n; 100], hour * u32::from(5 - n)); + } + // A use moves an hours-old file's time forward: file 0 becomes the most recent on disk. + let store = Store::open(scratch.0.clone(), 1000); + assert_eq!(store.total(), 400); + assert_eq!(store.get(&name(0)), Some(vec![0; 100])); + drop(store); + // Reopened with room for two, the store keeps file 0 and file 3, the latest used. + let reopened = Store::open(scratch.0.clone(), 200); + let kept: Vec = (0..4).map(|n| reopened.get(&name(n)).is_some()).collect(); + assert_eq!(kept, [true, false, false, true], "the files kept"); + assert_eq!(scratch.bytes(), 200); +} + #[test] fn stores_on_one_directory_share_its_files() { let scratch = Scratch::new("store-share"); - let mut first = Store::open(scratch.0.clone(), 1000); - let mut second = Store::open(scratch.0.clone(), 1000); - first.put(&name(1), b"lowered"); - assert_eq!(second.get(&name(1)), Some(b"lowered".to_vec())); + let first = Store::open(scratch.0.clone(), 1000); + let second = Store::open(scratch.0.clone(), 1000); + first.put(&name(1), b"compiled"); + assert_eq!(second.get(&name(1)), Some(b"compiled".to_vec())); + assert_eq!(second.total(), 8); + first.put(&name(2), b"lowered"); + assert!(second.holds(&name(2), b"lowered")); + assert!(!second.holds(&name(2), b"refused")); + assert!(!second.holds(&name(4), b"")); + // A file another removed is a miss, and leaves the store's count. + fs::remove_file(scratch.0.join(name(1))).expect("removed"); + assert_eq!(second.get(&name(1)), None); assert_eq!(second.total(), 7); - assert!(second.holds(&name(1), b"lowered")); - assert!(!second.holds(&name(1), b"refused")); - assert!(!second.holds(&name(2), b"")); } #[test] diff --git a/crates/metal2vulkan-rt/src/tests/translate.rs b/crates/metal2vulkan-rt/src/tests/translate.rs index bda22dd75..67c14d27d 100644 --- a/crates/metal2vulkan-rt/src/tests/translate.rs +++ b/crates/metal2vulkan-rt/src/tests/translate.rs @@ -24,6 +24,8 @@ mod on_device { use metal2vulkan::pipeline::{RuntimeFact, StageEntries}; use metal2vulkan::Budget; use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; + use std::path::{Path, PathBuf}; + use std::time::SystemTime; /// `float` patterns none of which is a NaN or a denormal (the fixture compiles with fast math). const FLOATS: [f32; 6] = [0.0, -0.0, 0.5, 2.0, 1.0, -3.0]; @@ -1031,9 +1033,49 @@ mod on_device { }); } + /// Every file under `dir`: its path under it, its length and its time on disk, in order. + fn files(dir: &Path) -> Vec<(String, u64, SystemTime)> { + fn under(root: &Path, dir: &Path, all: &mut Vec<(String, u64, SystemTime)>) { + for entry in std::fs::read_dir(dir).expect("the directory").flatten() { + let meta = entry.metadata().expect("its metadata"); + if meta.is_dir() { + under(root, &entry.path(), all); + } else { + let path = entry.path(); + let file = path.strip_prefix(root).expect("under the root"); + let file = file.to_string_lossy().replace('\\', "/"); + all.push((file, meta.len(), meta.modified().expect("its time"))); + } + } + } + let mut all = Vec::new(); + under(dir, dir, &mut all); + all.sort(); + all + } + + /// The pipelines' files among `files`. + fn pipeline_files(files: &[(String, u64, SystemTime)]) -> usize { + files + .iter() + .filter(|(file, ..)| file.starts_with("pipelines/")) + .count() + } + + /// A device on `dir`. + fn on_directory(name: &str, physical: &crate::PhysicalDevice, dir: &Path) -> Device { + let options = DeviceOptions { + pipeline_cache_dir: Some(dir.to_owned()), + ..DeviceOptions::default() + }; + Device::new(physical, options).unwrap_or_else(|error| panic!("{name}: {error}")) + } + /// A device on a cache directory a device before it used lowers nothing at creation: the /// tiling kernel's lowering and the observing kernel's two are read from the directory, and - /// the pipeline data the first device wrote at its end is there. + /// the tile's `VkPipeline` is made from its file. The first device's writes + /// (`Metrics::cache_bytes_written`) are the files' bytes, one file for each `VkPipeline` it + /// made; the second writes nothing and leaves every file as it was. #[test] fn every_device_takes_the_kernels_a_device_before_it_lowered_from_the_cache_directory() { let (Some(tiled), Some(observing)) = ( @@ -1048,13 +1090,9 @@ mod on_device { for (name, physical) in &devices { let dir = std::env::temp_dir().join(format!("m2v-rt-cache-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); + let mut first = Vec::new(); for round in 0..2 { - let options = DeviceOptions { - pipeline_cache_dir: Some(dir.clone()), - ..DeviceOptions::default() - }; - let device = Device::new(physical, options) - .unwrap_or_else(|error| panic!("{name}: {error}")); + let device = on_directory(name, physical, &dir); let counters = device.counters(); let states = [ state(name, &device, &tiled), @@ -1067,23 +1105,124 @@ mod on_device { assert_eq!(counted, want, "{name}: device {round} on the directory"); drop(states); drop(device); + // The teardown ends once the reaper wrote what it was given. within("the teardown", || counters.gauges() == Gauges::default()); + let written = counters.metrics().cache_bytes_written; + let files = files(&dir); + if round == 0 { + let bytes: u64 = files.iter().map(|&(_, len, _)| len).sum(); + assert_eq!(written, bytes, "{name}: the bytes written are the files'"); + let made = counters.metrics().pipelines_created; + assert_eq!( + pipeline_files(&files) as u64, + made, + "{name}: a file a pipeline" + ); + first = files; + } else { + assert_eq!(written, 0, "{name}: the second device writes nothing"); + assert_eq!(files, first, "{name}: every file as it was"); + } } - let written = std::fs::read_dir(&dir) - .expect("the cache directory") - .flatten() - .any(|entry| { - entry - .file_name() - .to_string_lossy() - .starts_with("pipelines-") - }); let _ = std::fs::remove_dir_all(&dir); - assert!(written, "{name}: the pipeline data"); - println!("{name}: 3 lowerings, none on a second device on the directory"); + println!( + "{name}: 3 lowerings and {} pipeline file(s) written, none by a second device", + pipeline_files(&first) + ); } } + /// The second process's part of + /// `every_device_shares_the_cache_directory_with_a_second_process`: on the device and + /// directory it names, the first process's kernel, then a kernel of its own. + const SECOND: &str = "tests::translate::on_device::second_process_on_a_cache_directory"; + + /// A second process on a cache directory: its device takes the kernel the first process's + /// device left there and writes none of its files again; the kernel of its own adds its + /// lowering and one file for its one `VkPipeline`. + #[test] + fn every_device_shares_the_cache_directory_with_a_second_process() { + let Some(tiled) = descriptor("a1_bool_from_float") else { + return; + }; + let instance = Instance::new(&[]).expect("an instance at the floor"); + let devices = devices_of_the_cfgs_kind(&instance); + assert!(!devices.is_empty(), "no device of this cfg's kind"); + for (name, physical) in &devices { + let dir = std::env::temp_dir().join(format!("m2v-rt-cache2-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let device = on_directory(name, physical, &dir); + let counters = device.counters(); + drop(state(name, &device, &tiled)); + drop(device); + within("the teardown", || counters.gauges() == Gauges::default()); + let before = files(&dir); + let test = std::env::current_exe().expect("the test binary"); + let status = std::process::Command::new(test) + .args(["--exact", SECOND, "--ignored", "--nocapture"]) + .env("M2V_TEST_CACHE_DIR", &dir) + .env("M2V_TEST_DEVICE", name) + .status() + .expect("the second process"); + assert!(status.success(), "{name}: the second process"); + let after = files(&dir); + let _ = std::fs::remove_dir_all(&dir); + for file in &before { + assert!( + after.contains(file), + "{name}: {} written again or gone", + file.0 + ); + } + let added: Vec<&String> = (after.iter()) + .filter(|file| !before.contains(file)) + .map(|(file, ..)| file) + .collect(); + let pipelines = added.iter().filter(|file| file.starts_with("pipelines/")); + assert_eq!(pipelines.count(), 1, "{name}: added {added:?}"); + println!("{name}: the second process added {added:?}, rewrote nothing"); + } + } + + /// Run only by `every_device_shares_the_cache_directory_with_a_second_process`, in a process + /// of its own: on the device `M2V_TEST_DEVICE` names, a device on the directory + /// `M2V_TEST_CACHE_DIR` names makes the first process's kernel, lowering nothing and writing + /// nothing, then a kernel of its own. + #[test] + #[ignore = "the second process of every_device_shares_the_cache_directory_with_a_second_process"] + fn second_process_on_a_cache_directory() { + let dir = PathBuf::from(std::env::var_os("M2V_TEST_CACHE_DIR").expect("the directory")); + let wanted = std::env::var("M2V_TEST_DEVICE").expect("the device"); + let (Some(tiled), Some(own)) = ( + descriptor("a1_bool_from_float"), + descriptor("a1_sign_and_division"), + ) else { + panic!("the kernels"); + }; + let instance = Instance::new(&[]).expect("an instance at the floor"); + let devices = devices_of_the_cfgs_kind(&instance); + let (name, physical) = (devices.iter()) + .find(|(name, _)| *name == wanted) + .expect("the first process's device"); + let device = on_directory(name, physical, &dir); + let counters = device.counters(); + let first = state(name, &device, &tiled); + let metrics = counters.metrics(); + assert_eq!( + metrics.translations, 0, + "{name}: the first process's kernel" + ); + let own = state(name, &device, &own); + drop((first, own)); + drop(device); + within("the teardown", || counters.gauges() == Gauges::default()); + assert_eq!( + counters.metrics().pipelines_created, + 2, + "{name}: two pipelines made" + ); + } + /// `vector_word_phases`'s kernels (`metal2vulkan_devtools::vector_word_phases`): with /// `vwp_words`'s two `uint` buffers bound at each word phase, 0, 4, 8 and 12, so its `uint4` /// and `float4` accesses through cast pointers land that far past a multiple of 16 whatever diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 241c6a9ad..80b0f5000 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2255,6 +2255,7 @@ field metal2vulkan-rt::ComputePipelineDescriptor.threadgroup_size_is_multiple_of field metal2vulkan-rt::DeviceOptions.block_mappings pub block_mappings: Option> field metal2vulkan-rt::DeviceOptions.extensions pub extensions: Vec field metal2vulkan-rt::DeviceOptions.features pub features: Vec +field metal2vulkan-rt::DeviceOptions.pipeline_cache_cap pub pipeline_cache_cap: Option field metal2vulkan-rt::DeviceOptions.pipeline_cache_dir pub pipeline_cache_dir: Option field metal2vulkan-rt::FunctionDescriptor.constants pub constants: FunctionConstantValues field metal2vulkan-rt::FunctionDescriptor.function pub function: Function @@ -2282,6 +2283,7 @@ field metal2vulkan-rt::IndexGrant.first pub first: u32 field metal2vulkan-rt::Metrics.barriers pub barriers: u64 field metal2vulkan-rt::Metrics.blocks_made pub blocks_made: u64 field metal2vulkan-rt::Metrics.bytes_copied pub bytes_copied: u64 +field metal2vulkan-rt::Metrics.cache_bytes_written pub cache_bytes_written: u64 field metal2vulkan-rt::Metrics.commit_lock_wait_max_nanos pub commit_lock_wait_max_nanos: u64 field metal2vulkan-rt::Metrics.commit_lock_wait_nanos pub commit_lock_wait_nanos: u64 field metal2vulkan-rt::Metrics.first_use_wait_max_nanos pub first_use_wait_max_nanos: u64