diff --git a/crates/metal2vulkan-rt/Cargo.toml b/crates/metal2vulkan-rt/Cargo.toml index 52fd6e97e..4657f9f04 100644 --- a/crates/metal2vulkan-rt/Cargo.toml +++ b/crates/metal2vulkan-rt/Cargo.toml @@ -22,8 +22,6 @@ 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 f3b8221b5..558e891d7 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -28,9 +28,10 @@ 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`, 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. + directory the device keeps its lowered functions and its pipeline cache in, + `pipeline_cache_dir`, and the most bytes the lowerings take, `pipeline_cache_cap` (see "The + cache directory"). With `None`, every boot lowers every function 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. @@ -42,9 +43,9 @@ 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 each new `VkPipeline`'s data to the cache directory. While an old generation of the -cache directory is removed, a thread of the store's own does it, and ends with the removal; no -teardown waits for it. +and makes the device's pipeline cache when it starts and writes it to the cache directory once +pipeline creation is quiet. While an old generation of the cache directory is removed, a thread of +the store's own does it, and ends with the removal; no teardown waits for it. 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 @@ -927,9 +928,17 @@ that touch blocks first. ### The cache directory -`DeviceOptions::pipeline_cache_dir` names a directory, made where it is missing, that the device -keeps two kinds of file in, for compute and render pipeline states: +Every `VkPipeline` of a device, compute or render, is made through one `VkPipelineCache` of the +device's, internally synchronized, which threads that create at once share. +`DeviceOptions::pipeline_cache_dir` names a directory, made where it is missing, that keeps it and +the lowerings from one device to the next: +- `pipelines-
`: the pipeline cache's blob, its data as `vkGetPipelineCacheData` gave it + after a magic, its length and its checksum, named by the hex of the first 16 bytes of the + pipeline cache header the device's driver writes (everything in it but the + `pipelineCacheUUID`, so a driver update replaces the blob rather than leaving it beside a new + one). One per kind of device: devices of one kind, in one process or several, start from it, + and each replaces it. - `translations/`: each function's lowering, a kernel's or a render pipeline's vertex or fragment function's, named by its `FunctionCompileKey`, which covers everything that changes the lowering: the function's AIR, entry, constants and linked functions, its lowering inputs (a @@ -937,63 +946,76 @@ keeps two kinds of file in, for compute and render pipeline states: 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 kernel variant the translator refused is kept too. -- `pipelines//`: one file per `VkPipeline`, named by a SHA-256 over everything - its creation takes (each module's SPIR-V and entry point, its stage's flags and required - subgroup size, its specialization and the runtime's pipeline layout; for a render pipeline also - its fixed-function state, its attachments' formats and its topology class). 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. -Both kinds live in two generations, `g/` (young) and `g/` (old), each holding at most half -of `DeviceOptions::pipeline_cache_cap` (128 MiB where it is `None`: half of it is about four times -the 15.4 MB a long recorded session's pipelines and lowerings fill). A lookup tries young, then +**The pipeline cache.** The reaper makes the cache first when it starts, from the blob where there +is one, so the read and the driver's parse run off the thread that made the device; a creation that +comes before the cache is made waits for it. A blob that does not check, whose data does not begin +with the device's pipeline cache header (whole, the `pipelineCacheUUID` a new driver version changes +included), or that the driver refuses, is removed, and the cache starts empty. Once pipeline +creation has been quiet for 20 ms (no creation running and none ending) after a creation, the reaper +reads the cache's size (`vkGetPipelineCacheData` with no buffer), and where it grew by more than an +eighth since the last write, writes the cache's data over the blob: a temporary file renamed over +it, never appended to. So it writes at most once a quiet period, a run that makes no new pipeline +writes nothing, and a device's writes over its life come to a few times the blob's final size. The +device's drop writes it once more where the size changed at all. A crash between writes loses only +the pipelines made since the last; no creation waits for a size query or a write. + +The cache holds at most 32 MiB when the reaper looks (about five times the 6.25 MB of pipeline data +a long recorded session made): one past it is replaced by a fresh, empty cache that creations take +from then on, and is destroyed once no creation holds it. The next write replaces the blob with +the fresh cache's data, so the blob holds at most 32 MiB too, with no second file and no +generations. `Gauges::pipeline_cache_bytes` is the cache's size at the reaper's last look, and is +zero once the device is torn down. With no directory the cache is the same, made empty, and +nothing is written. + +**The lowerings** live in two generations, `g/` (young) and `g/` (old), each holding at +most half of `DeviceOptions::pipeline_cache_cap` (128 MiB where it is `None`: half of it is about +seven times the 9.16 MB a long recorded session's 282 lowerings fill). A lookup tries young, then old, and a hit in old moves the file into young by a rename. A new file goes into young. The write that takes young past half the cap starts the next generation: young becomes old, and the old one is removed whole, by a thread the store starts for it. So a file stays for at least half the cap, and at most the whole cap, of files written or moved after its last use. Half the cap is what the -store is sure to keep: a set of pipelines used over and over that is larger than half the cap is -partly removed at each new generation and compiled again. On disk the store takes at most the -cap, and while a removal runs, also what is left of the generation it removes. A file larger than -half the cap is not kept. `Metrics::cache_bytes_written` counts the bytes the device wrote there. +store is sure to keep: a set of functions used over and over that is larger than half the cap is +partly removed at each new generation and lowered again. On disk the lowerings take at most the +cap, and while a removal runs, also what is left of the generation it removes; the blobs are +beside them. A file larger than half the cap is not kept. `Metrics::cache_bytes_written` counts +the bytes the device wrote there, lowerings and blobs. The bytes young holds are counted in `state`, a file of 24 bytes beside the generations, read and written under its lock, so devices open on one directory, in one process or several, share its files and one count; they should pass one cap, since each starts a generation at half its own. -Opening the directory reads `state` and checks for a generation a removal left unfinished, -which it then removes; it lists no directory and keeps nothing per file in memory. +Opening the directory reads `state` and checks for a generation a removal left unfinished, and for +the `pipelines/` directories under young and old in which an earlier version kept one file of +pipeline data per `VkPipeline`, which the store's thread then removes; it lists no directory and +keeps nothing per file in memory. The costs do not grow with the number of files. Measured with 100,000 and 1,000,000 files of 100 bytes (release build, btrfs on Linux / NTFS on Windows): opening the directory 10-11 µs / 106-129 -µs, with no resident growth on Linux; a hit in young 2 µs / 53-58 µs; a miss 4-5 µs / 33-37 µs; a -hit in old, which renames the file into young, 15-21 µs / 244-249 µs; a write 15-17 µs / 253-330 -µs. The store's own thread removes a dead generation of 49,800 / 499,800 files in 0.42 / 4.6 s on -btrfs and 4.0 / 43 s on NTFS. +µs, with no resident growth on Linux; a hit in young 1.8-2.0 µs / 49-50 µs; a miss 3.6-4.4 µs / +30-35 µs; a hit in old, which renames the file into young, 15-21 µs / 244-249 µs; a write 15-17 +µs / 253-330 µs. The store's own thread removes a dead generation of 49,800 / 499,800 files in +0.42 / 4.6 s on btrfs and 4.0 / 43 s on NTFS. 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, by a -crash or a power loss, is a miss and is removed: nothing unchecked reaches the driver. A failed -read or write, a full disk included, is a miss too, and never fails a call; in a directory the -device can read and not write, its hits stay where they are and it writes nothing. A `state` that -is missing or does not check is rebuilt from the generations' names, with young counted full. -With no directory, nothing is kept on disk, and each `VkPipeline` is made without a -`VkPipelineCache`. +translator's self-checking encoding, the blob's checksum), so a file cut short, by a crash or a +power loss, is a miss and is removed: nothing unchecked reaches the driver. A failed read or +write, a full disk included, is a miss too, and never fails a call; in a directory the device can +read and not write, its hits stay where they are and it writes nothing. A `state` that is missing +or does not check is rebuilt from the generations' names, with young counted full. ### 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, - from its file where there is one. + through the device's pipeline cache. - An image-only kernel's first dispatch over a grid more than one deep at a tile no state of its content has run makes that tile's `VkPipeline` on the calling thread, which waits for it - (`Metrics::first_use_waits`), from its file in the cache directory where there is one. In each of - the two recorded streams measured, on a device that holds 1,024 threads along `z`, that made 50 - pipelines, all in one frame: the frame where the stream's image-only dispatches over such grids - start (frame 224 of one stream and 312 of the other). The 50th, of tile 1x1x256, runs as one row, - so a device that holds 64 makes the same 50. + (`Metrics::first_use_waits`), through the device's pipeline cache. In each of the two recorded + streams measured, on a device that holds 1,024 threads along `z`, that made 50 pipelines, all in + one frame: the frame where the stream's image-only dispatches over such grids start (frame 224 + of one stream and 312 of the other). The 50th, of tile 1x1x256, runs as one row, so a device + that holds 64 makes the same 50. - 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 @@ -1141,9 +1163,8 @@ With no directory, nothing is kept on disk, and each `VkPipeline` is made withou attributes or layouts than `maxVertexInputAttributes` or `maxVertexInputBindings` (`VertexInputLayout`, with the limit where one is passed); - the per-patch and per-patch-control-point steps, with tessellation (`Tessellation`). -- The triangle class's `VkPipeline` is made with the state, through its file in the cache - directory where there is one; the line class's is made by the content's first draw of lines, - which waits for it (`Metrics::first_use_waits`). Of the two replay streams' 537 render contents +- The triangle class's `VkPipeline` is made with the state, through the device's pipeline + cache; the line class's is made by the content's first draw of lines, which waits for it (`Metrics::first_use_waits`). Of the two replay streams' 537 render contents drawn, 527 draw only triangles and 2 lines and triangles; a content drawn only as lines (8 of them) makes a triangle `VkPipeline` it never uses. diff --git a/crates/metal2vulkan-rt/src/cache.rs b/crates/metal2vulkan-rt/src/cache.rs index 14e87f358..f87c544f7 100644 --- a/crates/metal2vulkan-rt/src/cache.rs +++ b/crates/metal2vulkan-rt/src/cache.rs @@ -1,76 +1,102 @@ -//! The device's caches on disk, under [`DeviceOptions::pipeline_cache_dir`]: a kernel lowered and -//! a `VkPipeline` compiled in one run cost little in the next. Compute and render pipelines. +//! The device's caches: a kernel lowered and a `VkPipeline` compiled in one run cost little in +//! the next. Compute and render pipelines. //! -//! Two kinds of file, each under the generation it was last used in (below): +//! **The pipeline cache.** A device makes every `VkPipeline` through one `VkPipelineCache` of its +//! own, internally synchronized, which threads that create at once share. With a cache directory +//! ([`DeviceOptions::pipeline_cache_dir`]) the cache starts from the device's blob there: the +//! cache's data as `vkGetPipelineCacheData` gave it, after a magic, its length and its checksum, +//! named `pipelines-` and the hex of the first 16 bytes of the pipeline cache header the device's +//! driver writes (everything in the header but the `pipelineCacheUUID`, which a driver update +//! changes, so the update replaces the blob rather than leaving it beside a new one). The reaper +//! makes the cache first when it starts, off the thread that makes the device; a creation that +//! comes before it waits for it. A blob that does not check, whose data does not begin with the +//! device's header, or that the driver refuses, is removed, and the cache starts empty. //! -//! - `translations/`: one file per lowered function (a kernel, or a render pipeline's vertex or -//! fragment function), named by the hex of its `FunctionCompileKey`, which covers everything -//! that changes the lowering's output: the function's AIR, entry, constants and linked -//! functions, its lowering inputs, the device profile's 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. -//! - `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, framed with its length and checksum. 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. +//! The reaper writes the cache's data over the blob, a temporary file renamed over it and never +//! appended to, once creation is quiet (no creation running and none for [`QUIET_NANOS`]) after a +//! creation: at most once a quiet period, and only where the size the driver gives grew by more +//! than an eighth since the last write, so a run that makes nothing new writes nothing and a +//! device's writes over its life come to a few times the blob's size. The device's drop writes it +//! once more where the size changed at all. A crash between writes loses only the pipelines made +//! since the last. No guest call waits for a write or a size query. +//! +//! The cache holds at most [`PIPELINE_CACHE_BOUND`]: a cache past it when the reaper looks is +//! replaced by a fresh, empty one that creations take from then on, and destroyed once no creation +//! holds it; the next write replaces the blob with the fresh cache's data, so the blob holds at +//! most the bound too, with no second file. [`Gauges::pipeline_cache_bytes`] is the cache's size +//! at the reaper's last look. Without a directory the cache is the same, and nothing is on disk. +//! +//! **The lowerings.** The store keeps one file per lowered function (a kernel, or a render +//! pipeline's vertex or fragment function) under `translations/`, named by the hex of its +//! `FunctionCompileKey`, which covers everything that changes the lowering's output: the +//! function's AIR, entry, constants and linked functions, its lowering inputs, the device +//! profile's 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 live in two generations, `g/` (young) and `g/` (old), which the consumer's //! cap ([`DeviceOptions::pipeline_cache_cap`]) bounds at half of it each. A lookup tries young, -//! then old; a hit in old is renamed into young, which is its mark of use. A write goes into -//! young. The bytes young holds are counted in `state`, 24 bytes beside the generations: young's -//! number, its bytes and a checksum of both, read and written under a lock on the file, which -//! every store on the directory, in this process or another, holds open for its life. The write -//! that takes young past half the cap makes the next generation young: young becomes old, and the -//! old one is dead. A store keeps young's number as it last read or wrote the state, so a lookup -//! reads no state: a move another store made is seen at this store's next write, and until then -//! its lookups try the generations it knew, a miss at worst. A thread of the store's own removes -//! the dead generation and ends, so no thread that submits, waits for or completes work removes +//! then old; a hit in old is renamed into young, which is its mark of use. Generations start at +//! 1, and the first has no old: a lookup there tries young alone. A write goes into young. The +//! bytes young holds are counted in `state`, 24 bytes beside the generations: young's number, +//! its bytes and a checksum of both, read and written under a lock on the file, which every store +//! on the directory, in this process or another, holds open for its life. The write that takes +//! young past half the cap makes the next generation young: young becomes old, and the old one is +//! dead. A store keeps young's number as it last read or wrote the state, so a lookup reads no +//! state: a move another store made is seen at this store's next write, and until then its +//! lookups try the generations it knew, a miss at worst. A thread of the store's own removes the +//! dead generation and ends, so no thread that submits, waits for or completes work removes //! files. So a file stays at least half the cap and at most the cap of other writes and moves //! after its last use, opening reads one file whatever the store holds, and nothing per file is -//! kept in memory. +//! kept in memory. The same thread removes the `pipelines/` directories under young and old in +//! which an earlier version kept one file of pipeline data per `VkPipeline`; their bytes stay +//! counted in young until it moves on. //! //! Every write is a temporary file renamed over its name, counted before it is written and given //! back where it fails, so the count is never below what young holds. Every file checks itself -//! (the translator's encoding, the pipeline data's checksum): a file cut short, by a crash or a -//! power loss, is a miss and is removed, and nothing unchecked reaches the driver. A failed read -//! or write is a miss too: the caches never fail a call. A state file that does not check, or is -//! missing, is rebuilt from the generations' names, with young counted full, so the next write -//! moves on and the removal takes the rest. A removal cut short by the process's end is found by -//! the next open, which looks for the generation below old. +//! (the translator's encoding, the blob's checksum): a file cut short, by a crash or a power loss, +//! is a miss and is removed, and nothing unchecked reaches the driver. A failed read or write is +//! a miss too: the caches never fail a call. A state file that does not check, or is missing, is +//! rebuilt from the generations' names, with young counted full, so the next write moves on and +//! the removal takes the rest. A removal cut short by the process's end is found by the next +//! open, which looks for the generation below old. //! //! [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir //! [`DeviceOptions::pipeline_cache_cap`]: crate::DeviceOptions::pipeline_cache_cap +//! [`Gauges::pipeline_cache_bytes`]: crate::Gauges::pipeline_cache_bytes -use crate::counters::Counters; -use crate::device::lock; +use crate::counters::{Counters, Gauge}; +use crate::device::{lock, Core}; +use crate::memory::QUIET_NANOS; +use crate::times::host_time; use ash::vk; -use sha2::{Digest, Sha256}; use std::fs::{self, File}; use std::io::{self, ErrorKind, Read, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering::Relaxed, Ordering::SeqCst}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError}; use std::thread; +use std::time::Duration; -/// The cap of a cache directory where the consumer names none: half of it, what the store is sure -/// to keep, is about four times the 15.4 MB a long recorded session's pipelines and lowerings -/// fill (379 pipeline files, 6.25 MB; 282 lowerings, 9.16 MB). +/// The cap of the lowerings in a cache directory where the consumer names none: half of it, what +/// the store is sure to keep, is about seven times the 9.16 MB a long recorded session's 282 +/// lowerings fill. pub(crate) const DEFAULT_CAP: u64 = 128 << 20; -/// The most pipeline caches waiting for the reaper to write their data. -pub(crate) const PENDING: usize = 64; -/// The first bytes of a pipeline data file, before its length and its checksum. -const MAGIC: &[u8; 8] = b"m2vpipe1"; +/// The most bytes of data a device's `VkPipelineCache` holds when the reaper looks before it is +/// replaced by a fresh one, and so the most its blob holds: 32 MiB, about five times the 6.25 MB +/// of pipeline data a long recorded session made. +pub(crate) const PIPELINE_CACHE_BOUND: u64 = 32 << 20; +/// The first bytes of a blob, before its data's length and checksum. +const MAGIC: &[u8; 8] = b"m2vblob1"; +/// The start of a device's blob's name, under the cache directory. +const BLOB: &str = "pipelines"; /// 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 a generation. const TRANSLATIONS: &str = "translations"; -/// The pipelines' directory, under a generation: one directory per `pipelineCacheUUID`. +/// The directory, under a generation, an earlier version kept a file of pipeline data per +/// `VkPipeline` in: removed where it is found. const PIPELINES: &str = "pipelines"; /// The state file, under the cache directory. const STATE: &str = "state"; @@ -82,8 +108,8 @@ pub(crate) struct State { pub(crate) bytes: u64, } -/// The files of a cache directory, `translations/` and `pipelines//` under -/// two generations of at most half of `cap` bytes each (the module's doc). +/// The lowerings of a cache directory, `translations/` under two generations of at most +/// half of `cap` bytes each (the module's doc). pub(crate) struct Store { root: PathBuf, /// Half the cap: the most bytes young counts. @@ -110,7 +136,7 @@ pub(crate) struct Store { impl Store { /// The store in `root`, made where it is missing; it starts the removal of a generation a - /// removal before left. + /// removal before left, and of an earlier version's pipeline data. pub(crate) fn open(root: PathBuf, cap: u64) -> Arc { let _ = fs::create_dir_all(&root); let path = root.join(STATE); @@ -139,13 +165,28 @@ impl Store { }); if let Some(state) = store.current() { store.young.fetch_max(state.young, Relaxed); - if state.young >= 2 && store.generation(state.young - 2).exists() { + let young = state.young; + let dead = young >= 2 && store.generation(young - 2).exists(); + if dead || !store.pipeline_dirs(young).is_empty() { store.remove_dead(); } } store } + /// Whether the state file is open for writing: a read-only directory serves hits only. + pub(crate) fn writable(&self) -> bool { + self.writable + } + + /// The directories of an earlier version's pipeline data under young, `young`, and old. + fn pipeline_dirs(&self, young: u64) -> Vec { + (young.saturating_sub(1)..=young) + .map(|number| self.generation(number).join(PIPELINES)) + .filter(|dir| dir.exists()) + .collect() + } + /// What `decode` makes of the bytes of `file`, a path under a generation, where the /// directory holds it and they decode; bytes that do not are removed. A hit in old moves the /// file into young. @@ -176,7 +217,7 @@ impl Store { return false; }; if self - .place(young, file, |path| write_whole(path, bytes)) + .place(young, file, |path| write_whole(path, &[bytes])) .is_ok() { return true; @@ -355,7 +396,8 @@ impl Store { op(&path) } - /// Starts the removal thread, where none runs: it removes every generation below old. + /// Starts the removal thread, where none runs: it removes every generation below old, and an + /// earlier version's pipeline data. fn remove_dead(self: &Arc) { if !self.writable || self.removing.swap(true, SeqCst) { return; @@ -369,36 +411,39 @@ impl Store { } } - /// The removal thread: makes the state durable, then removes the dead generations, until a - /// pass finds none it did not try. + /// The removal thread: makes the state durable, then removes the dead generations and an + /// earlier version's pipeline data, until a pass finds none it did not try. fn remove(&self) { loop { if let Some(file) = &self.state { let _ = file.sync_all(); } let tried = self.dead(); - for &number in &tried { - let _ = fs::remove_dir_all(self.generation(number)); + for dir in &tried { + let _ = fs::remove_dir_all(dir); } self.removing.store(false, SeqCst); // A move to the next generation during the pass found the thread running and started // none: its dead generation is taken here. One the pass could not remove waits for // the next move or open. - let new = self.dead().iter().any(|number| !tried.contains(number)); + let new = self.dead().iter().any(|dir| !tried.contains(dir)); if !new || self.removing.swap(true, SeqCst) { return; } } } - /// The generations below old. - fn dead(&self) -> Vec { + /// The generations below old, and an earlier version's pipeline data under young and old. + fn dead(&self) -> Vec { let Some(young) = self.current().map(|state| state.young) else { return Vec::new(); }; - (generations(&self.root).into_iter()) + let mut dead: Vec = (generations(&self.root).into_iter()) .filter(|&number| number + 1 < young) - .collect() + .map(|number| self.generation(number)) + .collect(); + dead.extend(self.pipeline_dirs(young)); + dead } } @@ -489,9 +534,9 @@ pub(crate) fn hex(bytes: &[u8]) -> String { bytes.iter().map(|byte| format!("{byte:02x}")).collect() } -/// Writes `bytes` to `path` through a temporary file beside it, named for this process and this -/// write, then renamed over it. -fn write_whole(path: &Path, bytes: &[u8]) -> io::Result<()> { +/// Writes `parts`, one after another, to `path` through a temporary file beside it, named for this +/// process and this write, then renamed over it. +fn write_whole(path: &Path, parts: &[&[u8]]) -> io::Result<()> { static WRITES: AtomicU64 = AtomicU64::new(0); let mut temp = path.as_os_str().to_owned(); temp.push(format!( @@ -500,7 +545,8 @@ fn write_whole(path: &Path, bytes: &[u8]) -> io::Result<()> { WRITES.fetch_add(1, Relaxed) )); let temp = PathBuf::from(temp); - let written = File::create(&temp).and_then(|mut file| file.write_all(bytes)); + let written = File::create(&temp) + .and_then(|mut file| parts.iter().try_for_each(|part| file.write_all(part))); match written.and_then(|()| fs::rename(&temp, path)) { Ok(()) => Ok(()), Err(error) => { @@ -510,15 +556,26 @@ fn write_whole(path: &Path, bytes: &[u8]) -> io::Result<()> { } } -/// FNV-1a over `bytes`: the pipeline data file's check that it was written whole. -fn checksum(bytes: &[u8]) -> u64 { - bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, &byte| { - (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) - }) +/// A hash of `bytes`, eight at a time in four lanes, each step a bijection of its lane, so any one +/// changed word changes it: the state's and the blob's check that they were written whole, fast +/// enough to check a 32 MiB blob in a few milliseconds. Not a defence against a writer that means +/// harm. +pub(crate) fn checksum(bytes: &[u8]) -> u64 { + const K: u64 = 0x9e37_79b9_7f4a_7c15; + let step = |lane: u64, word: u64| (lane ^ word).wrapping_mul(K).rotate_left(29); + let mut lanes = [K, K ^ 1, K ^ 2, K ^ 3]; + let (chunks, tail) = bytes.as_chunks::<32>(); + for chunk in chunks { + for (lane, word) in lanes.iter_mut().zip(chunk.as_chunks::<8>().0) { + *lane = step(*lane, u64::from_le_bytes(*word)); + } + } + let hash = lanes.into_iter().fold(bytes.len() as u64, step); + tail.iter() + .fold(hash, |hash, &byte| step(hash, u64::from(byte))) } -/// The pipeline data a file holds: its bytes after the magic, their length and their checksum, -/// where all three check. +/// The blob's data, after its magic, its length and its checksum, where all three check. pub(crate) fn unframe(file: &[u8]) -> Option<&[u8]> { let (magic, rest) = file.split_first_chunk::<8>()?; let (len, rest) = rest.split_first_chunk::<8>()?; @@ -529,94 +586,193 @@ pub(crate) fn unframe(file: &[u8]) -> Option<&[u8]> { .then_some(data) } -/// `data` framed for its file. -pub(crate) fn frame(data: &[u8]) -> Vec { - let mut file = Vec::with_capacity(24 + data.len()); - file.extend_from_slice(MAGIC); - file.extend_from_slice(&(data.len() as u64).to_le_bytes()); - file.extend_from_slice(&checksum(data).to_le_bytes()); - file.extend_from_slice(data); - file +/// The bytes before `data` in its blob: the magic, its length and its checksum. +pub(crate) fn frame(data: &[u8]) -> [u8; 24] { + let mut head = [0; 24]; + head[..8].copy_from_slice(MAGIC); + head[8..16].copy_from_slice(&(data.len() as u64).to_le_bytes()); + head[16..].copy_from_slice(&checksum(data).to_le_bytes()); + head } -/// The key of a `VkPipeline`'s file: a SHA-256 over what its creation takes, `module` (a compute -/// module's digest, [`module_digest`], or a render content's, over its modules' digests and its -/// fixed-function state) and `values` (its specialization's, after a render pipeline's topology -/// class), 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() -} - -/// 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. +/// A device's caches: the lowerings in the store, and the `VkPipelineCache` every `VkPipeline` +/// is made through, with its blob. 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, + /// The cache directory, where there is one. + dir: Option, + /// The device's blob in it, named once the reaper has read the device's header. + blob: OnceLock, + pipelines: Mutex, + /// Signalled once the reaper made the cache. + made: Condvar, + /// Creations through the cache that have not ended. + creating: AtomicUsize, + /// When the last creation ended, in nanoseconds of [`host_time`]. + created: AtomicU64, + /// Set by a creation's end, cleared by the reaper's look at the cache. + grown: AtomicBool, + /// [`PIPELINE_CACHE_BOUND`], lower in a test. + bound: AtomicU64, + /// The reaper's looks at the cache. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + looks: AtomicUsize, + /// The blob's writes. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + writes: 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, +/// The `VkPipelineCache` creations take, and those a fresh one replaced. +struct Pipelines { + /// Whether the reaper made the cache, or found the driver makes none. + made: bool, + /// The cache creations take; none where the driver made none. + current: Option>, + /// The caches a fresh one replaced, each destroyed once no creation holds it. + retired: Vec>, + /// The size of the current cache's data when the blob was last written from it, or when it + /// was made: what the next write must grow past. + written: u64, +} + +/// A `VkPipelineCache` of the device's, held by each creation through it. +pub(crate) struct PipelineCache(vk::PipelineCache); + +/// A creation through the device's `VkPipelineCache`, from [`creation`] until it is dropped. +pub(crate) struct Creation<'a> { + core: &'a Core, + cache: Option>, +} + +impl Creation<'_> { + /// The cache to make the pipeline through; null where the driver made none. + pub(crate) fn handle(&self) -> vk::PipelineCache { + self.cache + .as_ref() + .map_or(vk::PipelineCache::null(), |cache| cache.0) + } +} + +impl Drop for Creation<'_> { + fn drop(&mut self) { + let caches = &self.core.caches; + caches.created.fetch_max(host_time(), Relaxed); + caches.creating.fetch_sub(1, SeqCst); + // The first creation since the reaper's last look tells it to look again once creation + // is quiet. + if !caches.grown.swap(true, SeqCst) { + self.core.reaper.poke(); + } + } +} + +/// A creation through `core`'s `VkPipelineCache`: where the reaper has not made the cache yet, +/// which it does first when it starts, the calling thread waits for it. +pub(crate) fn creation(core: &Core) -> Creation<'_> { + let caches = &core.caches; + caches.creating.fetch_add(1, SeqCst); + let mut pipelines = lock(&caches.pipelines); + while !pipelines.made { + pipelines = (caches.made.wait(pipelines)).unwrap_or_else(PoisonError::into_inner); + } + let cache = pipelines.current.clone(); + Creation { core, cache } +} + +/// A `VkPipelineCache` of `device` started from `data`, internally synchronized. +/// +/// # Safety +/// +/// `data` is empty, or what `vkGetPipelineCacheData` gave, whole. +unsafe fn make_cache(device: &ash::Device, data: &[u8]) -> Option { + let info = vk::PipelineCacheCreateInfo::default().initial_data(data); + // SAFETY: the caller's contract; data of another device or version is ignored by the driver, + // and a refusal is answered by the caller. + unsafe { device.create_pipeline_cache(&info, None) }.ok() +} + +/// The size of `cache`'s data, `vkGetPipelineCacheData` with no buffer; 0 where the driver +/// fails it. +/// +/// # Safety +/// +/// The cache is `device`'s. +unsafe fn data_size(device: &ash::Device, cache: vk::PipelineCache) -> u64 { + let mut size = 0; + // SAFETY: the caller's contract; no buffer is given, so only the size is written. + let result = unsafe { + (device.fp_v1_0().get_pipeline_cache_data)( + device.handle(), + cache, + &mut size, + std::ptr::null_mut(), + ) + }; + match result { + vk::Result::SUCCESS => size as u64, + _ => 0, + } } impl Caches { - /// The caches of a device whose pipeline data is keyed by `uuid`, in `dir` where there is - /// 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| Store::open(dir.to_owned(), cap)); + /// A device's caches, in `dir` where there is one, the lowerings at most `cap` bytes. + pub(crate) fn new(dir: Option<&Path>, cap: u64) -> Caches { Caches { - store, - pipelines, - pending: AtomicUsize::new(0), + store: dir.map(|dir| Store::open(dir.to_owned(), cap)), + dir: dir.map(Path::to_owned), + blob: OnceLock::new(), + pipelines: Mutex::new(Pipelines { + made: false, + current: None, + retired: Vec::new(), + written: 0, + }), + made: Condvar::new(), + creating: AtomicUsize::new(0), + created: AtomicU64::new(0), + grown: AtomicBool::new(false), + bound: AtomicU64::new(PIPELINE_CACHE_BOUND), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + looks: AtomicUsize::new(0), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + writes: AtomicUsize::new(0), } } - /// Whether the device has a cache directory. - pub(crate) fn on_disk(&self) -> bool { - self.store.is_some() + /// The device's blob, where it has a cache directory and the reaper has made the cache. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn blob(&self) -> Option<&Path> { + self.blob.get().map(PathBuf::as_path) + } + + /// Sets the cache's bound for a test. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn set_bound(&self, bytes: u64) { + self.bound.store(bytes, Relaxed); + } + + /// The caches a fresh one replaced and the reaper has not destroyed yet. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn retired(&self) -> usize { + lock(&self.pipelines).retired.len() + } + + /// Whether the reaper has made the cache. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn is_made(&self) -> bool { + lock(&self.pipelines).made + } + + /// The current cache, held as a creation holds it, without counting as one. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn hold(&self) -> Option> { + lock(&self.pipelines).current.clone() + } + + /// The reaper's looks at the cache, and the blob writes of its looks and of the drop. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn looks_and_writes(&self) -> (usize, usize) { + (self.looks.load(Relaxed), self.writes.load(Relaxed)) } fn translation_file(key: &[u8]) -> String { @@ -659,51 +815,205 @@ impl Caches { self.keep_translation(key, REFUSED, counters); } - fn pipeline_file(&self, key: &[u8; 32]) -> String { - format!("{}/{}", self.pipelines, hex(key)) - } - - /// 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.pipeline_file(key); - (self.store.as_ref()?).get(&file, |bytes| unframe(bytes).map(<[u8]>::to_vec)) - } - - /// 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 - .try_update(Relaxed, Relaxed, |pending| { - (pending < PENDING).then_some(pending + 1) - }) - .is_ok() - } - - /// 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. + /// On the reaper, first: makes the device's `VkPipelineCache`, from its blob where the blob + /// checks, its data begins with the header the device's driver writes and the driver takes + /// it; else empty, removing a blob that is not taken. Creations waiting for the cache go on. + /// + /// The blob is named by the hex of the header's first 16 bytes: everything in it but the + /// `pipelineCacheUUID`, so a driver update replaces a device's blob rather than leaving it + /// beside a new one. /// /// # Safety /// - /// 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, - ) { + /// `device` is the device of the caches. + pub(crate) unsafe fn seed(&self, device: &ash::Device, counters: &Counters) { + // SAFETY: no data. + let mut made = unsafe { make_cache(device, &[]) }; + let header = made.and_then(|empty| { + // SAFETY: the cache is the device's. + let data = unsafe { device.get_pipeline_cache_data(empty) }.ok()?; + data.first_chunk::<32>().copied() + }); + if let (Some(dir), Some(header)) = (&self.dir, header) { + let path = dir.join(format!("{BLOB}-{}", hex(&header[..16]))); + let file = read_whole(&path, None).ok().flatten(); + let data = (file.as_deref()) + .and_then(unframe) + .filter(|data| data.starts_with(&header)); + // SAFETY: the data is what `vkGetPipelineCacheData` gave for a device of this header, + // whole, as its length and checksum show. + let seeded = data.and_then(|data| unsafe { make_cache(device, data) }); + match seeded { + Some(seeded) => { + if let Some(empty) = made.replace(seeded) { + // SAFETY: the cache is the device's, and no creation has taken it. + unsafe { device.destroy_pipeline_cache(empty, None) }; + } + } + None if file.is_some() => { + let _ = fs::remove_file(&path); + } + None => {} + } + drop(file); + let _ = self.blob.set(path); + } + // SAFETY: the cache is the device's. + let size = made.map_or(0, |cache| unsafe { data_size(device, cache) }); + counters.set(Gauge::PipelineCacheBytes, size); + let mut pipelines = lock(&self.pipelines); + pipelines.current = made.map(|cache| Arc::new(PipelineCache(cache))); + pipelines.written = size; + pipelines.made = true; + drop(pipelines); + self.made.notify_all(); + } + + /// When the reaper is to look at the cache ([`Caches::look`]), at `now` in nanoseconds of + /// [`host_time`]: none where no creation ended since its last look; else once creation has + /// been quiet, no creation running and none ending, for [`QUIET_NANOS`], zero once it has. + pub(crate) fn look_in(&self, now: u64) -> Option { + if !self.grown.load(SeqCst) { + return None; + } + if self.creating.load(SeqCst) > 0 { + return Some(Duration::from_nanos(QUIET_NANOS)); + } + let quiet = self.created.load(Relaxed).saturating_add(QUIET_NANOS); + Some(Duration::from_nanos(quiet.saturating_sub(now))) + } + + /// On the reaper, creation quiet: destroys each replaced cache no creation holds, reads the + /// cache's size, and past the bound starts a fresh cache, else writes the blob where the + /// data grew by more than an eighth since the last write. + /// + /// # Safety + /// + /// `device` is the device of the caches. + pub(crate) unsafe fn look(&self, device: &ash::Device, counters: &Counters) { + self.grown.store(false, SeqCst); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + self.looks.fetch_add(1, Relaxed); // SAFETY: the caller's contract. - 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 { + let Some(current) = (unsafe { self.reap(device) }) 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); - } + // SAFETY: the cache is the device's. + let size = unsafe { data_size(device, current.0) }; + counters.set(Gauge::PipelineCacheBytes, size); + if size > self.bound.load(Relaxed) { + // SAFETY: no data. + let Some(fresh) = (unsafe { make_cache(device, &[]) }) else { + return; + }; + // SAFETY: the cache is the device's. + let fresh_size = unsafe { data_size(device, fresh) }; + let mut pipelines = lock(&self.pipelines); + let old = pipelines.current.replace(Arc::new(PipelineCache(fresh))); + pipelines.retired.extend(old); + pipelines.written = fresh_size; + drop(pipelines); + counters.set(Gauge::PipelineCacheBytes, fresh_size); + drop(current); + // SAFETY: the caller's contract. + unsafe { self.reap(device) }; + return; + } + let written = lock(&self.pipelines).written; + if size > written + written / 8 { + // SAFETY: the cache is the device's. + unsafe { self.write(device, ¤t, size, counters) }; } } + + /// Destroys each replaced cache no creation holds; the current cache. + /// + /// # Safety + /// + /// `device` is the device of the caches. + unsafe fn reap(&self, device: &ash::Device) -> Option> { + let mut pipelines = lock(&self.pipelines); + // A replaced cache is never handed out again: once the list holds its last reference, + // no creation holds it. + let (idle, held) = + (pipelines.retired.drain(..)).partition(|old| Arc::strong_count(old) == 1); + pipelines.retired = held; + let current = pipelines.current.clone(); + drop(pipelines); + // SAFETY: the caches are the device's, and no creation holds them. + unsafe { destroy(device, idle) }; + current + } + + /// Writes `cache`'s data, of size `size` as the driver last gave it, over the device's blob, + /// where the directory is writable and the data is within the bound. + /// + /// # Safety + /// + /// The cache is `device`'s. + unsafe fn write( + &self, + device: &ash::Device, + cache: &PipelineCache, + size: u64, + counters: &Counters, + ) { + let (Some(path), Some(store)) = (self.blob.get(), &self.store) else { + return; + }; + if !store.writable() { + return; + } + // SAFETY: the caller's contract; the cache is internally synchronized. + let Ok(data) = (unsafe { device.get_pipeline_cache_data(cache.0) }) else { + return; + }; + let len = data.len() as u64; + if len > self.bound.load(Relaxed) { + return; + } + if write_whole(path, &[&frame(&data), &data]).is_ok() { + counters.cache_written(24 + len); + lock(&self.pipelines).written = size; + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + self.writes.fetch_add(1, Relaxed); + } + } + + /// At the device's drop, no creation running: writes the blob where the cache's data changed + /// since the last write, then destroys every cache. + /// + /// # Safety + /// + /// `device` is the device of the caches, and no creation runs. + pub(crate) unsafe fn close(&self, device: &ash::Device, counters: &Counters) { + let (current, written) = { + let mut pipelines = lock(&self.pipelines); + (pipelines.current.take(), pipelines.written) + }; + if let Some(current) = ¤t { + // SAFETY: the cache is the device's. + let size = unsafe { data_size(device, current.0) }; + if size != written { + // SAFETY: the cache is the device's. + unsafe { self.write(device, current, size, counters) }; + } + } + let mut pipelines = lock(&self.pipelines); + // SAFETY: the caches are the device's, and no creation runs. + unsafe { destroy(device, pipelines.retired.drain(..).chain(current)) }; + counters.set(Gauge::PipelineCacheBytes, 0); + } +} + +/// Destroys `caches`. +/// +/// # Safety +/// +/// The caches are `device`'s, and no creation holds them. +unsafe fn destroy(device: &ash::Device, caches: impl IntoIterator>) { + for cache in caches { + // SAFETY: the caller's contract. + unsafe { device.destroy_pipeline_cache(cache.0, None) }; + } } diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index a50ad7d7b..6f3dd1afd 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -96,6 +96,8 @@ pub(crate) enum Gauge { StageEntries, /// [`Gauges::stage_entry_bytes`]. StageEntryBytes, + /// [`Gauges::pipeline_cache_bytes`]. + PipelineCacheBytes, } /// No Metal counterpart: a device's counters ([`Device::counters`](crate::Device::counters)). @@ -170,6 +172,7 @@ struct Atomics { staging_bytes: AtomicU64, stage_entries: AtomicU64, stage_entry_bytes: AtomicU64, + pipeline_cache_bytes: AtomicU64, /// Segment ends whose barrier reaches the host, for the tests. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] host_reaches: AtomicU64, @@ -376,6 +379,7 @@ impl Counters { Gauge::StagingBytes => &a.staging_bytes, Gauge::StageEntries => &a.stage_entries, Gauge::StageEntryBytes => &a.stage_entry_bytes, + Gauge::PipelineCacheBytes => &a.pipeline_cache_bytes, } } @@ -450,6 +454,7 @@ impl Counters { staging_bytes: a.staging_bytes.load(Relaxed), stage_entries: a.stage_entries.load(Relaxed), stage_entry_bytes: a.stage_entry_bytes.load(Relaxed), + pipeline_cache_bytes: a.pipeline_cache_bytes.load(Relaxed), } } } @@ -530,7 +535,9 @@ pub struct Metrics { /// 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. + /// kernels, and the device's pipeline cache blob each time it is written: once creation is + /// quiet where the cache grew by more than an eighth since the last write, and at the + /// device's drop where it changed. /// /// [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir pub cache_bytes_written: u64, @@ -671,4 +678,8 @@ pub struct Gauges { /// The bytes those entries and decodes hold, each counted as the ledger bytes making it held: /// at most 64 MiB of entries and 32 MiB of decodes. pub stage_entry_bytes: u64, + /// The size of the data in the device's `VkPipelineCache`, as `vkGetPipelineCacheData` gave + /// it when the reaper last looked, once creation was quiet: at most 32 MiB at a look, past + /// which the reaper replaces the cache with a fresh one, and this falls to the fresh one's. + pub pipeline_cache_bytes: u64, } diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index 85134f2b9..cfdcf592b 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -198,7 +198,8 @@ 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 and the pipelines' data on disk. + /// The lowered kernels on disk, and the `VkPipelineCache` every pipeline is made through with + /// its blob. pub(crate) caches: Caches, /// The compiled kernels by content, which every compute pipeline state of a content shares. pub(crate) kernels: KernelMap, @@ -243,25 +244,30 @@ 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 each `VkPipeline`'s - /// compiled data in, made where it is missing, so a later device on it, in this process or + /// The directory the device keeps the compute and render functions it lowered and its + /// pipeline cache 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 + /// ([`Metrics::translations_loaded`]). The lowerings take at most /// [`pipeline_cache_cap`](Self::pipeline_cache_cap) bytes, in two generations of half of it /// each: a file used again moves into the young one, and the old one is removed whole when - /// the young one fills. 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. + /// the young one fills. Beside them, one file per kind of device (named by its pipeline cache + /// header) holds the data of the `VkPipelineCache` every `VkPipeline` of the device is made through, + /// at most 32 MiB: the device's cache starts from it, and it is replaced, never appended to, + /// once pipeline creation has been quiet for 20 ms after the cache grew by more than an + /// eighth, and at the device's drop where the cache changed. 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 function 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 128 MiB. Half of it is what the - /// directory is sure to keep: a file stays for at least half the cap, and at most the cap, of - /// files written or used after its last use, and a file larger than half is not kept. Devices - /// on one directory, in one process or several, share its files and one count of their bytes, - /// and should pass one cap: each starts a new generation at half its own. + /// The most bytes the lowerings in [`pipeline_cache_dir`](Self::pipeline_cache_dir) take; + /// `None` is 128 MiB. The pipeline cache's file, at most 32 MiB per kind of device, is beside + /// them. Half of the cap is what the directory is sure to keep: a lowering stays for at least + /// half the cap, and at most the cap, of lowerings written or used after its last use, and + /// one larger than half is not kept. Devices on one directory, in one process or several, + /// share its files and one count of their bytes, and should pass one cap: each starts a new + /// generation at half its own. pub pipeline_cache_cap: Option, } @@ -385,7 +391,6 @@ impl Device { 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 @@ -1133,6 +1138,8 @@ impl Drop for Core { // it, which may give a texture block back to the pool), and then the pools of the queues // still alive. self.reaper.drain(self); + // SAFETY: the caches are the device's, and no creation runs: every handle is gone. + unsafe { self.caches.close(&self.device, &self.counters) }; if let Some(region) = self.work.take_capture_region() { self.counters .fall_by(Gauge::CaptureBytes, crate::capture::CAPTURE_LEN); diff --git a/crates/metal2vulkan-rt/src/memory.rs b/crates/metal2vulkan-rt/src/memory.rs index 751a10a77..50a7271b5 100644 --- a/crates/metal2vulkan-rt/src/memory.rs +++ b/crates/metal2vulkan-rt/src/memory.rs @@ -107,7 +107,7 @@ const WINDOW_SECS: u64 = 3; /// time, only in such a gap, and looks again after each; a submission that arrives during a free /// waits for the rest of it, and the quiet time starts again where that free ended, so the next /// free waits 20 ms past the held submission however long the hold. -const QUIET_NANOS: u64 = 20_000_000; +pub(crate) const QUIET_NANOS: u64 = 20_000_000; /// `MTLStorageMode` of a block, as the buffers in it see it. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index bd7fe5444..5f17d6b69 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -39,7 +39,7 @@ //! encoding thread. use crate::arrays::BINDINGS; -use crate::cache::{module_digest, pipeline_key, KeepPipeline}; +use crate::cache; use crate::counters::{Gauge, Metric}; use crate::device::{lock, Core}; use crate::error::{Error, Gap, Refusal}; @@ -262,8 +262,6 @@ 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>, @@ -712,63 +710,23 @@ pub(crate) fn lower( Ok(lowered) } -/// The one `VkPipeline` that `create` makes through the cache it is given: with a cache directory, -/// a `VkPipelineCache` of the pipeline's own, started from the file of `key` (the pipeline's -/// [`pipeline_key`]), which the reaper then writes the data of; else none. `call` names `create`'s -/// Vulkan call. Counted as made. +/// The one `VkPipeline` that `create` makes through the cache it is given: the device's one +/// `VkPipelineCache` (`crate::cache`), which a creation before the reaper made it waits for. +/// `call` names `create`'s Vulkan call. Counted as made. pub(crate) fn made_through_cache( core: &Core, call: &'static str, - key: impl FnOnce() -> [u8; 32], create: impl FnOnce(vk::PipelineCache) -> Result, (Vec, vk::Result)>, ) -> Result { - let device = &core.device; - let mut kept = None; - if core.caches.on_disk() { - let key = key(); - 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); - let made = create(cache); - 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 creation = cache::creation(core); + let made = create(creation.handle()); + drop(creation); let pipeline = made.map_err(|(_, result)| Error::Vulkan { call, result })?[0]; core.counters.count(Metric::PipelinesCreated); core.counters.rise(Gauge::Pipelines); Ok(pipeline) } -/// The words that describe the runtime's pipeline layout, which every pipeline takes: its push -/// window's bytes and its bindings, for a module's digest ([`module_digest`]). -pub(crate) fn layout_words() -> Vec { - std::iter::once(PUSH_BYTES) - .chain( - BINDINGS - .iter() - .flat_map(|&(binding, kind, count)| [binding, kind.as_raw() as u32, count]), - ) - .collect() -} - /// The runtime's view of the translator's kernel, or [`Gap::KernelInput`] where the kernel reads /// something the compute encoder does not supply. fn interface( @@ -1100,7 +1058,6 @@ impl ComputePipelineState { let whole = Kernel { module, entry: c"main".to_owned(), - digest: [0; 32], interface, variants: Mutex::new(Vec::new()), }; @@ -1237,23 +1194,11 @@ 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(); - module_digest( - &stage.spirv, - entry.as_bytes(), - interface.stage_flags, - interface.required_subgroup_size, - &ids, - &layout_words(), - ) - }); // 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()), }) @@ -1330,8 +1275,7 @@ impl Kernel { let info = vk::ComputePipelineCreateInfo::default() .stage(stage) .layout(core.layout); - let key = || pipeline_key(&self.digest, &values); - made_through_cache(core, "vkCreateComputePipelines", key, |cache| { + made_through_cache(core, "vkCreateComputePipelines", |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. unsafe { core.device.create_compute_pipelines(cache, &[info], None) } diff --git a/crates/metal2vulkan-rt/src/reaper.rs b/crates/metal2vulkan-rt/src/reaper.rs index 8da9dd3d4..2395c5869 100644 --- a/crates/metal2vulkan-rt/src/reaper.rs +++ b/crates/metal2vulkan-rt/src/reaper.rs @@ -1,14 +1,16 @@ -//! 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 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. +//! The reaper thread: it makes the device's `VkPipelineCache` from its blob first, then 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 looks at the pipeline cache once creation is quiet, writing its blob or +//! replacing it past its bound (`crate::cache`). 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; use crate::texture::Backing; +use crate::times::host_time; use ash::vk; use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak}; @@ -33,8 +35,6 @@ 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. @@ -121,20 +121,26 @@ impl Reaper { } } + /// Wakes the reaper to see when to look at the pipeline cache, after the first creation since + /// its last look. + pub(crate) fn poke(&self) { + let _state = 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, and writes the data of - /// the pipeline caches 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. 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 { match job { Job::Free(object) => free(core, object), - Job::KeepPipeline(kept) => keep(core, kept), Job::Teardown(_) => {} } } @@ -229,26 +235,21 @@ 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), + /// Look at the pipeline cache, creation being quiet. + Look, /// 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 reaper thread, until it is stopped and its queue is empty: the pipeline cache first. pub(crate) fn run(core: Arc) { + // SAFETY: the caches are the core's device's. + unsafe { core.caches.seed(&core.device, &core.counters) }; let reaper = &core.reaper; loop { let next = { @@ -263,16 +264,23 @@ pub(crate) fn run(core: Arc) { if let Some(lowering) = state.lowerings.pop_front() { break Next::Lower(lowering); } - state = reaper - .changed - .wait(state) - .unwrap_or_else(PoisonError::into_inner); + // A creation that ends after this read sets its mark and then pokes under the + // lock, which this thread holds until it waits. + state = match core.caches.look_in(host_time()) { + Some(due) if due.is_zero() => break Next::Look, + Some(due) => match reaper.changed.wait_timeout(state, due) { + Ok((state, _)) => state, + Err(poisoned) => poisoned.into_inner().0, + }, + None => (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), + // SAFETY: the caches are the core's device's. + Next::Look => unsafe { core.caches.look(&core.device, &core.counters) }, Next::Lower(lowering) => { if let Some(state) = lowering.upgrade() { state.lower_emulated(); diff --git a/crates/metal2vulkan-rt/src/render.rs b/crates/metal2vulkan-rt/src/render.rs index a949bfedb..cacfb319e 100644 --- a/crates/metal2vulkan-rt/src/render.rs +++ b/crates/metal2vulkan-rt/src/render.rs @@ -36,7 +36,6 @@ //! The cost: a content drawn only as lines or points makes a triangle `VkPipeline` it never uses //! (8 contents of the 537). The replay streams draw no points: a draw of points is refused. -use crate::cache::{module_digest, pipeline_key}; use crate::counters::Gauge; use crate::device::{lock, Core}; use crate::error::{Error, Gap, RenderPipelineKind}; @@ -44,8 +43,8 @@ use crate::hazard::Access; use crate::kernel_map::KernelKey; use crate::pass::Pass; use crate::pipeline::{ - access, layout_words, lower, made_through_cache, number_samplers, of_the_device, - texture_access, FieldValue, Numbered, PUSH_BYTES, + access, lower, made_through_cache, number_samplers, of_the_device, texture_access, FieldValue, + Numbered, PUSH_BYTES, }; use crate::reaper::{Free, Job}; use crate::times::host_time; @@ -58,7 +57,6 @@ use metal2vulkan::pipeline::{ SlotClass, SlotInterface, SlotRef, SpecKey, Stage, StageEntries, StageSource, VertexStride, }; use metal2vulkan::Budget; -use sha2::{Digest, Sha256}; use std::ffi::CString; use std::sync::{Arc, Mutex}; @@ -134,10 +132,6 @@ pub(crate) struct RenderCompiled { stages: Vec, /// The fixed-function state every `VkPipeline` of the content takes. fixed: Fixed, - /// With a cache directory, the digest of everything the content gives a `VkPipeline`'s - /// creation (its modules' digests and its fixed-function state), which with the topology - /// class and the specialization's values keys the pipeline's file; else zeros. - digest: [u8; 32], /// The triangle class's `VkPipeline`, made with the content. triangles: vk::Pipeline, /// The line class's, made by the first draw of lines; null until then. @@ -546,42 +540,6 @@ impl Fixed { }), } } - - /// Everything it gives a `VkPipeline`'s creation, with the dynamic states, as words. - fn words(&self) -> Vec { - let raw = |value: i32| value as u32; - let mut words = vec![self.bindings.len() as u32]; - for b in &self.bindings { - words.extend([b.binding, b.stride, raw(b.input_rate.as_raw())]); - } - words.push(self.attributes.len() as u32); - for a in &self.attributes { - words.extend([a.location, a.binding, raw(a.format.as_raw()), a.offset]); - } - words.extend([ - u32::from(self.discard), - self.samples.as_raw(), - u32::from(self.alpha_to_coverage), - ]); - words.push(self.blends.len() as u32); - for b in &self.blends { - words.extend([ - b.blend_enable, - raw(b.src_color_blend_factor.as_raw()), - raw(b.dst_color_blend_factor.as_raw()), - raw(b.color_blend_op.as_raw()), - raw(b.src_alpha_blend_factor.as_raw()), - raw(b.dst_alpha_blend_factor.as_raw()), - raw(b.alpha_blend_op.as_raw()), - b.color_write_mask.as_raw(), - ]); - } - words.push(self.colors.len() as u32); - words.extend(self.colors.iter().map(|format| raw(format.as_raw()))); - words.push(raw(self.stencil.as_raw())); - words.extend(DYNAMIC.iter().map(|state| raw(state.as_raw()))); - words - } } impl RenderCompiled { @@ -625,11 +583,6 @@ impl RenderCompiled { let samples = descriptor.raster_sample_count; let mut stages = Vec::new(); let mut notes = Vec::new(); - let mut digest = core.caches.on_disk().then(|| { - let mut hash = Sha256::new(); - hash.update((pipeline.stages.len() as u64).to_le_bytes()); - hash - }); for stage in &pipeline.stages { let mut constants = Vec::new(); let mut values = Vec::new(); @@ -660,18 +613,6 @@ impl RenderCompiled { }; let flags = vk::PipelineShaderStageCreateFlags::from_raw(stage.stage_flags.as_raw()); let kind = vk::ShaderStageFlags::from_raw(stage.stage.as_raw()); - if let Some(hash) = &mut digest { - let ids: Vec = constants.iter().map(|entry| entry.constant_id).collect(); - hash.update(kind.as_raw().to_le_bytes()); - hash.update(module_digest( - &stage.spirv, - entry.as_bytes(), - flags, - None, - &ids, - &layout_words(), - )); - } let info = vk::ShaderModuleCreateInfo::default().code(&stage.spirv); // SAFETY: the words are the translator's SPIR-V, for the features device creation // enabled. @@ -698,18 +639,11 @@ impl RenderCompiled { notes.sort_unstable(); notes.dedup(); let fixed = Fixed::of(&pipeline); - let digest: [u8; 32] = digest.map_or([0; 32], |mut hash| { - for word in fixed.words() { - hash.update(word.to_le_bytes()); - } - hash.finalize().into() - }); core.counters.rise(Gauge::RenderContents); let mut compiled = RenderCompiled { core: Arc::clone(core), stages, fixed, - digest, triangles: vk::Pipeline::null(), lines: Mutex::new(vk::Pipeline::null()), notes, @@ -813,16 +747,7 @@ impl RenderCompiled { if !fixed.discard { info = info.color_blend_state(&blend); } - // The topology's class and the stages' specialization values, beside the content's - // digest, key the pipeline's file. - let key = || { - let mut values = (topology.as_raw() as u32).to_le_bytes().to_vec(); - for stage in &self.stages { - values.extend(&stage.values); - } - pipeline_key(&self.digest, &values) - }; - made_through_cache(core, "vkCreateGraphicsPipelines", key, |cache| { + made_through_cache(core, "vkCreateGraphicsPipelines", |cache| { // SAFETY: the modules, the layout and the cache are the device's; each specialization // gives each of its stage's constants a 4-byte value; the formats are the // attachments' the translator maps for the device, for the features device creation diff --git a/crates/metal2vulkan-rt/src/tests/blit.rs b/crates/metal2vulkan-rt/src/tests/blit.rs index 3fe0ae9ae..df34b6273 100644 --- a/crates/metal2vulkan-rt/src/tests/blit.rs +++ b/crates/metal2vulkan-rt/src/tests/blit.rs @@ -1690,13 +1690,15 @@ pub(crate) mod on_device { }); } - /// Returns once the block-maker thread has nothing to make: it makes an allocation of a - /// class whose free bytes run low, which a count of a test's own work must not take in. + /// Returns once the block-maker thread has nothing to make (it makes an allocation of a + /// class whose free bytes run low, which a count of a test's own work must not take in), and + /// the reaper has made the pipeline cache, which sets its gauge. pub(crate) fn settled(device: &Device) { within("8 MiB free in each class", || { let pool = &device.core().pool; pool.stocked(MemoryClass::Private) && pool.stocked(MemoryClass::Shared) }); + within("the pipeline cache", || device.core().caches.is_made()); } /// `command_buffer` committed and complete with no error. diff --git a/crates/metal2vulkan-rt/src/tests/cache.rs b/crates/metal2vulkan-rt/src/tests/cache.rs index c2f3dfb68..f0c605a4f 100644 --- a/crates/metal2vulkan-rt/src/tests/cache.rs +++ b/crates/metal2vulkan-rt/src/tests/cache.rs @@ -1,10 +1,11 @@ //! The cache directory on the host: two generations under one cap, a hit in old moved into young, //! a lookup that reads no state, the state file read at open with no listing and rebuilt where it //! is torn or missing, a removal cut short (a process's exit in it included) finished by the next -//! open, torn files removed, and stores in threads and processes sharing one directory without -//! losing a count or reading a file another was writing. +//! open, an earlier version's pipeline data removed at open, torn files removed, a blob that does +//! not check refused, and stores in threads and processes sharing one directory without losing a +//! count or reading a file another was writing. -use crate::cache::{frame, unframe, State, Store}; +use crate::cache::{checksum, frame, unframe, State, Store}; use std::fs; use std::io::ErrorKind; use std::path::{Path, PathBuf}; @@ -54,12 +55,14 @@ fn bytes_under(dir: &Path) -> u64 { .sum() } -/// A file the store keeps: a lowering for even `n`, a pipeline's data for odd. +/// A file the store keeps: a lowering. fn name(n: u32) -> String { - match n % 2 { - 0 => format!("translations/{n:064x}"), - _ => format!("pipelines/{:032x}/{n:064x}", 7), - } + format!("translations/{n:064x}") +} + +/// `data` as its blob holds it, after its magic, length and checksum. +fn framed(data: &[u8]) -> Vec { + [&frame(data)[..], data].concat() } /// Every byte as it is. @@ -358,7 +361,7 @@ fn a_torn_file_is_a_miss_and_is_removed() { let scratch = Scratch::new("store-torn"); let store = Store::open(scratch.0.clone(), 1000); let data: Vec = (0..=255).collect(); - assert!(store.put(&name(1), &frame(&data))); + assert!(store.put(&name(1), &framed(&data))); let path = store.generation(1).join(name(1)); let held = fs::read(&path).expect("the file"); fs::write(&path, &held[..held.len() - 1]).expect("cut short"); @@ -396,16 +399,74 @@ fn stores_on_one_directory_share_its_files_and_its_count() { } #[test] -fn pipeline_data_that_does_not_check_is_a_miss() { +fn a_blob_that_does_not_check_is_a_miss() { let data: Vec = (0..=255).collect(); - let file = frame(&data); + let file = framed(&data); assert_eq!(unframe(&file), Some(&data[..])); assert_eq!(unframe(&file[..file.len() - 1]), None, "cut short"); let mut flipped = file.clone(); flipped[100] ^= 1; assert_eq!(unframe(&flipped), None, "a flipped bit"); + let mut zeroed = file.clone(); + zeroed[40..72].fill(0); + assert_eq!(unframe(&zeroed), None, "a zeroed run"); assert_eq!(unframe(&[]), None, "empty"); - assert_eq!(unframe(&frame(&[])), Some(&[][..]), "no data"); + assert_eq!(unframe(&framed(&[])), Some(&[][..]), "no data"); +} + +/// Every one bit flipped in a buffer changes its checksum, at every offset whole words and the +/// tail past them cover, and so does its length. +#[test] +fn the_checksum_changes_with_any_one_bit() { + let bytes: Vec = (0..77u32).map(|n| (n * 37 + 11) as u8).collect(); + let sum = checksum(&bytes); + for at in 0..bytes.len() { + for bit in 0..8 { + let mut flipped = bytes.clone(); + flipped[at] ^= 1 << bit; + assert_ne!(checksum(&flipped), sum, "byte {at} bit {bit}"); + } + } + assert_ne!(checksum(&bytes[..76]), sum, "one byte shorter"); + assert_ne!( + checksum(&[0; 64]), + checksum(&[0; 65]), + "zeros of two lengths" + ); +} + +/// The `pipelines/` directories an earlier version kept pipeline data in under young and old are +/// removed by the store's removal thread at open, and the lowerings stay. +#[test] +fn an_earlier_versions_pipeline_data_is_removed_at_open() { + let scratch = Scratch::new("store-earlier"); + let store = Store::open(scratch.0.clone(), 1000); + for n in 0..6 { + assert!(store.put(&name(n), &[n as u8; 100])); + } + assert_eq!(state(&store).young, 2); + drop(store); + let earlier: Vec = [1, 2] + .iter() + .map(|g| scratch.0.join(format!("g{g}/pipelines/{:032x}", 7))) + .collect(); + for dir in &earlier { + fs::create_dir_all(dir).expect("an earlier version's directory"); + fs::write(dir.join(format!("{:064x}", 1)), [1; 50]).expect("its file"); + } + let reopened = Store::open(scratch.0.clone(), 1000); + reopened.settle(); + for g in [1, 2] { + let dir = scratch.0.join(format!("g{g}/pipelines")); + assert!(!dir.exists(), "{} removed", dir.display()); + } + for n in 0..6 { + assert_eq!( + reopened.get(&name(n), whole), + Some(vec![n as u8; 100]), + "file {n}" + ); + } } /// The stress's cap: a generation of about twelve files, so the stores move on every few writes. @@ -415,7 +476,7 @@ const STRESS_DIR: &str = "M2V_RT_STORE_STRESS_DIR"; /// The bytes of key `k`'s file, framed: a length and content of the key's own. fn content(k: u32) -> Vec { - frame(&vec![k as u8; 40 + 13 * k as usize]) + framed(&vec![k as u8; 40 + 13 * k as usize]) } /// `rounds` lookups of keys a seeded generator picks, each written where it missed; the count of diff --git a/crates/metal2vulkan-rt/src/tests/render.rs b/crates/metal2vulkan-rt/src/tests/render.rs index 00a6c7309..b15c1957c 100644 --- a/crates/metal2vulkan-rt/src/tests/render.rs +++ b/crates/metal2vulkan-rt/src/tests/render.rs @@ -253,27 +253,14 @@ mod on_device { }); } - /// The pipelines' files under `dir`'s generations, by path, with their lengths and times. - fn pipeline_files(dir: &Path) -> Vec<(String, u64, SystemTime)> { + /// The pipeline cache blobs in `dir`, by name, with their lengths and times. + fn blobs(dir: &Path) -> Vec<(String, u64, SystemTime)> { let mut all = Vec::new(); - let Ok(generations) = std::fs::read_dir(dir) else { - return all; - }; - let pipelines = generations - .flatten() - .map(|generation| generation.path().join("pipelines")); - let uuids = - pipelines.flat_map(|pipelines| std::fs::read_dir(pipelines).into_iter().flatten()); - for uuid in uuids.flatten() { - for file in std::fs::read_dir(uuid.path()) - .expect("a directory") - .flatten() - { + for file in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let name = file.file_name().to_string_lossy().into_owned(); + if name.starts_with("pipelines-") { let meta = file.metadata().expect("its metadata"); - let path = file.path(); - let path = path.strip_prefix(dir).expect("under the root"); - let path = path.to_string_lossy().replace('\\', "/"); - all.push((path, meta.len(), meta.modified().expect("its time"))); + all.push((name, meta.len(), meta.modified().expect("its time"))); } } all.sort(); @@ -314,14 +301,14 @@ mod on_device { drop(device); // The teardown ends once the reaper wrote what it was given. within("the teardown", || counters.gauges() == Gauges::default()); - let files = pipeline_files(&dir); + let files = blobs(&dir); if round == 0 { - assert_eq!(files.len(), 1, "{name}: a file for the pipeline"); + assert_eq!(files.len(), 1, "{name}: the device's pipeline cache blob"); first = files; } else { let written = counters.metrics().cache_bytes_written; assert_eq!(written, 0, "{name}: the second device writes nothing"); - assert_eq!(files, first, "{name}: the pipeline's file as it was"); + assert_eq!(files, first, "{name}: the blob as it was"); } } let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/metal2vulkan-rt/src/tests/translate.rs b/crates/metal2vulkan-rt/src/tests/translate.rs index a39a3bd9e..2e46eebf1 100644 --- a/crates/metal2vulkan-rt/src/tests/translate.rs +++ b/crates/metal2vulkan-rt/src/tests/translate.rs @@ -1079,12 +1079,11 @@ mod on_device { all } - /// The pipelines' files among `files`. - fn pipeline_files(files: &[(String, u64, SystemTime)]) -> usize { - files - .iter() - .filter(|(file, ..)| file.contains("/pipelines/")) - .count() + /// The pipeline cache blobs among `files`. + fn blobs(files: &[(String, u64, SystemTime)]) -> Vec<&(String, u64, SystemTime)> { + (files.iter()) + .filter(|(file, ..)| file.starts_with("pipelines-")) + .collect() } /// A device on `dir`. @@ -1098,9 +1097,10 @@ mod on_device { /// 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 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. + /// the tile's `VkPipeline` is made through a pipeline cache started from the device's blob. + /// The first device's writes (`Metrics::cache_bytes_written`) are at least the files' bytes, + /// the blob among them (written once creation was quiet, and again at the drop where the + /// cache grew since); 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)) = ( @@ -1136,13 +1136,11 @@ mod on_device { 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" + assert!( + written >= bytes, + "{name}: {written} written, {bytes} in files" ); + assert_eq!(blobs(&files).len(), 1, "{name}: the device's blob"); first = files; } else { assert_eq!(written, 0, "{name}: the second device writes nothing"); @@ -1150,10 +1148,7 @@ mod on_device { } } let _ = std::fs::remove_dir_all(&dir); - println!( - "{name}: 3 lowerings and {} pipeline file(s) written, none by a second device", - pipeline_files(&first) - ); + println!("{name}: 3 lowerings and the blob written, nothing by a second device"); } } @@ -1163,8 +1158,8 @@ mod on_device { 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`. + /// device left there and writes none of its lowerings again; the kernel of its own adds its + /// lowering, and its `VkPipeline`'s data grows the blob, which the second process replaces. #[test] fn every_device_shares_the_cache_directory_with_a_second_process() { let Some(tiled) = descriptor("a1_bool_from_float") else { @@ -1192,7 +1187,10 @@ mod on_device { assert!(status.success(), "{name}: the second process"); let after = files(&dir); let _ = std::fs::remove_dir_all(&dir); - for file in &before { + let (blob, blob_after) = (blobs(&before), blobs(&after)); + assert_eq!((blob.len(), blob_after.len()), (1, 1), "{name}: one blob"); + assert!(blob_after[0].1 > blob[0].1, "{name}: the blob grew"); + for file in before.iter().filter(|file| !blob.contains(file)) { assert!( after.contains(file), "{name}: {} written again or gone", @@ -1200,12 +1198,15 @@ mod on_device { ); } let added: Vec<&String> = (after.iter()) - .filter(|file| !before.contains(file)) + .filter(|file| !before.contains(file) && !blob_after.contains(file)) .map(|(file, ..)| file) .collect(); - let pipelines = added.iter().filter(|file| file.contains("/pipelines/")); - assert_eq!(pipelines.count(), 1, "{name}: added {added:?}"); - println!("{name}: the second process added {added:?}, rewrote nothing"); + assert!(!added.is_empty(), "{name}: its own kernel's lowering"); + assert!( + added.iter().all(|file| file.contains("translations/")), + "{name}: added {added:?}" + ); + println!("{name}: the second process added {added:?}, grew the blob, rewrote nothing"); } } @@ -1248,6 +1249,159 @@ mod on_device { ); } + /// The length of the blob of `device`'s pipeline cache, 0 where there is none. + fn blob_len(device: &Device) -> u64 { + let blob = device.core().caches.blob().expect("a cache directory"); + std::fs::metadata(blob).map_or(0, |meta| meta.len()) + } + + /// Makes the state of `descriptor` on `device` and waits for the reaper's look at the pipeline + /// cache once creation is quiet after it. + fn state_and_look( + name: &str, + device: &Device, + descriptor: &ComputePipelineDescriptor, + ) -> ComputePipelineState { + let caches = &device.core().caches; + let looks = caches.looks_and_writes().0; + let made = state(name, device, descriptor); + within("the reaper's look", || caches.looks_and_writes().0 > looks); + made + } + + /// The pipeline cache filled past its bound: at the look after a creation takes it past, the + /// reaper replaces it with a fresh one, which the gauge falls to, keeps the old one while it is + /// held, and destroys it at the first look after it is let go; creations go on through the + /// fresh cache, and the next write replaces the blob with the fresh cache's data alone. + #[test] + fn every_device_replaces_its_pipeline_cache_past_its_bound() { + let (Some(first), Some(second), Some(third)) = ( + descriptor("a1_bool_from_float"), + descriptor("a1_sign_and_division"), + descriptor("icb_replay_grid_template"), + ) 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-bound-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let device = on_directory(name, physical, &dir); + let caches = &device.core().caches; + let counters = device.counters(); + let a = state_and_look(name, &device, &first); + let full = counters.gauges().pipeline_cache_bytes; + assert!(full > 0, "{name}: the cache's size read"); + let first_blob = blob_len(&device); + assert_eq!( + first_blob, + 24 + full, + "{name}: the blob written at the look" + ); + // Held as a creation holds it, across the next look. + let held = caches.hold(); + caches.set_bound(full - 1); + let b = state_and_look(name, &device, &second); + let fresh = counters.gauges().pipeline_cache_bytes; + assert!( + fresh < full, + "{name}: the gauge falls from {full} to {fresh}" + ); + assert_eq!(caches.retired(), 1, "{name}: the old cache kept while held"); + assert_eq!( + blob_len(&device), + first_blob, + "{name}: no write at the replacement" + ); + drop(held); + caches.set_bound(crate::cache::PIPELINE_CACHE_BOUND); + let c = state_and_look(name, &device, &third); + assert_eq!( + caches.retired(), + 0, + "{name}: the old cache destroyed once let go" + ); + let now = counters.gauges().pipeline_cache_bytes; + assert!(now > fresh, "{name}: the fresh cache grew to {now}"); + assert_eq!( + blob_len(&device), + 24 + now, + "{name}: the blob holds the fresh cache" + ); + drop((a, b, c)); + drop(device); + within("the teardown", || counters.gauges() == Gauges::default()); + let _ = std::fs::remove_dir_all(&dir); + println!( + "{name}: {full} bytes past a bound of {}, replaced by {fresh}, grown to {now}", + full - 1 + ); + } + } + + /// A blob the device cannot take, cut short or of another device's header, is removed when + /// the reaper makes the cache, which starts empty: creations go on, and the drop writes the + /// blob a next device takes. That device's look finds the cache no larger, so neither it nor + /// the drop writes. + #[test] + fn every_device_removes_a_blob_it_cannot_take() { + 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 other = { + let mut header = vec![0; 32]; + header[..4].copy_from_slice(&32u32.to_le_bytes()); + header[4..8].copy_from_slice(&1u32.to_le_bytes()); + header.extend([7; 64]); + [&crate::cache::frame(&header)[..], &header].concat() + }; + for (what, bytes) in [ + ("cut short", other[..other.len() - 1].to_vec()), + ("another device's", other), + ] { + let dir = + std::env::temp_dir().join(format!("m2v-rt-refuse-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let device = on_directory(name, physical, &dir); + within("the pipeline cache", || device.core().caches.is_made()); + let blob = device.core().caches.blob().expect("a blob").to_owned(); + drop(device); + assert!(!blob.exists(), "{name}: no creation, no blob"); + std::fs::write(&blob, &bytes).expect("a blob"); + let device = on_directory(name, physical, &dir); + within("the pipeline cache", || device.core().caches.is_made()); + assert!(!blob.exists(), "{name}: a blob {what} removed"); + drop(state(name, &device, &tiled)); + drop(device); + let written = std::fs::read(&blob).expect("the blob the drop wrote"); + assert_ne!(written, bytes, "{name}: replaced"); + let device = on_directory(name, physical, &dir); + let counters = device.counters(); + let made = state_and_look(name, &device, &tiled); + let caches = &device.core().caches; + let (looks, writes) = caches.looks_and_writes(); + assert!( + looks >= 1 && writes == 0, + "{name}: {looks} looks, {writes} writes" + ); + drop(made); + drop(device); + within("the teardown", || counters.gauges() == Gauges::default()); + let blob_written = counters.metrics().cache_bytes_written; + assert_eq!(blob_written, 0, "{name}: the next device writes nothing"); + assert_eq!(std::fs::read(&blob).expect("the blob"), written, "{name}"); + let _ = std::fs::remove_dir_all(&dir); + println!("{name}: a blob {what} removed, rewritten, then taken"); + } + } + } + /// `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 d15e7b3cb..bb4916c3e 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2297,6 +2297,7 @@ field metal2vulkan-rt::Gauges.events pub events: u64 field metal2vulkan-rt::Gauges.kernel_entries pub kernel_entries: u64 field metal2vulkan-rt::Gauges.kernels pub kernels: u64 field metal2vulkan-rt::Gauges.managed_spilled_bytes pub managed_spilled_bytes: u64 +field metal2vulkan-rt::Gauges.pipeline_cache_bytes pub pipeline_cache_bytes: u64 field metal2vulkan-rt::Gauges.pipelines pub pipelines: u64 field metal2vulkan-rt::Gauges.private_idle_bytes pub private_idle_bytes: u64 field metal2vulkan-rt::Gauges.render_contents pub render_contents: u64