Keep the content directory's large records as content-defined chunks, each shared run once
NVIDIA's pipeline cache data (620.70.06, an RTX 3090) held one 1,851,552-byte section, the same bytes, in 3,565 of um790's records: its 11,853 NVIDIA records were 8,061 MB. A read-only measure of that node's 42,860 records (cut as below, averages of 16, 32 and 64 KiB) stores them in 296 MB at 32 KiB (NVIDIA's in 180 MB, 2.2%); 64 KiB keeps each shared run's end chunks apart (634 MB), 16 KiB doubles the files a read opens for 1.3x the bytes. shader_cache/chunks.rs (new), store.rs, driver.rs: - A content record of 256 KiB or more is cut by a gear rolling hash (FastCDC's normalized cut, 8 KiB to 128 KiB around 32 KiB): boundaries from the bytes alone, nothing of any driver's format read. Each chunk is kept once at <root>/chunks/<2 hex>/<SHA-256>, outside <root>/v1, so a build whose scans know nothing of chunks never removes one. The record's file is a manifest (M2VCHNK1, length, count, each chunk's SHA-256 and length, its own SHA-256); a read joins the chunks and the record's decoder checks it end to end as before (a driver record's checksum, a library's content hash). A missing or short chunk is a miss; the next write brings it back, and a chunk whose bytes are not its digest's is written again. Smaller records stay whole. - Crash-safe: every chunk (temporary + rename) before the manifest's rename. An advisory lock (std File::lock, <root>/chunks/lock): writers hold it shared from their first chunk look to their manifest's rename; the cleanup takes it exclusively with try_lock and removes only chunks no manifest names. Neither waits: a writer that meets a cleanup writes its record whole. - Bounded cleanup, in the scans the store makes already: the sweep at device creation where no cleanup ran yet or the chunks grew past 110% of what the last kept, and after a cap scan that freed chunks. It reads each content record's first 8 bytes (a manifest whole) and lists the chunks once. The chunks count against the cap; a removed manifest frees the chunks only it named. - Upgrade: driver::VERSION 3 -> 4, its frame's magic M2VPPLC -> M2VPPL4 (an older build names and frames otherwise, never misreads one). The old records are removed by Store::sweep -> Chunks::due (no state yet) -> Chunks::cleanup -> Chunks::manifests, which removes each content record whose magic is in driver::RETIRED. Each family pays one cold making after the upgrade. The validation lanes read the new magic. - Linux reads: every chunk opened first and posix_fadvise(WILLNEED) on each, so cold chunks are read together. Tests (tests::shader_cache_chunks, 8): round trip and the 256 KiB bound; a shared 1.5 MiB run kept once (the second record wrote 95,310 of 1,580,864 bytes); no manifest when its chunks cannot be written; a missing or damaged chunk; the sweep removing a synthetic v3 tree (four M2VPPLC records, one of 2 MiB), unnamed chunks and a dead writer's temporary; a writer's shared lock putting the cleanup off; a cleanup's lock making a writer write whole; the cap evicting the older record with its own chunks. Verified on msi (m3-max-24179, at this tree's code): clippy -D warnings all features, rustdoc, shader_cache tests 44 passed, the runtime suite 1512 passed. Load time, release mode on um790 (NVMe), a store load with a SHA-256 decode in both (m3-max-24178; the SHA-256 of 1.85 MB alone is 0.80 ms), median of 20 cold (every file dropped from the page cache) and 200 warm: - 1.7 MB, 40 chunks (NVIDIA p90): cold 1.56 ms whole, 1.47 ms chunked; warm 0.77 / 0.95 ms. - 2.5 MB, 67 chunks (worst): cold 2.07 / 2.62 ms (+0.55 ms; one of 20 at 12.1 ms); warm 1.12 / 1.44 ms (+0.32 ms). - 20 families sharing the section, all cold, in turn: per family median 0.86 ms whole, 1.13 ms chunked (first 0.94 / 1.65 ms); whole's slowest 138.6 ms, chunked's 1.18 ms. A family's later makings on the device use its live cache and read nothing.
This commit is contained in:
1 parent
020b04a13c
commit
8bc2e7e1ac
9 files changed
+887
-50
No files matched your search
@@ -0,0 +1,449 @@
|
||||
//! The content directory's large records, kept as chunks (`store.rs`): one copy of each run of
|
||||
//! bytes the records share.
|
||||
//!
|
||||
//! ```text
|
||||
//! <root>/chunks/<first byte of digest, hex>/<digest, hex>
|
||||
//! <root>/chunks/lock
|
||||
//! <root>/chunks/state
|
||||
//! ```
|
||||
//!
|
||||
//! - **Why.** The pipeline cache data of NVIDIA's driver (620.70.06, an RTX 3090) held one
|
||||
//! 1,851,552-byte section, the same bytes, in 3,565 of one node's records, each record a copy
|
||||
//! of it: that node's 11,853 NVIDIA records of 8,061 MB are 180 MB once each run of bytes they
|
||||
//! share is kept once (a measure of its records at the average below).
|
||||
//! - **Content-defined chunks.** A record of [`WHOLE`] bytes or more is cut where a rolling hash
|
||||
//! of its bytes ([`ends`]: a gear hash, FastCDC's normalized cut between [`MIN`] and [`MAX`]
|
||||
//! around an [`AVERAGE`]) meets a mask, so a run two records share is cut alike in both
|
||||
//! wherever it lies in each, and each chunk is kept once, named by its SHA-256. The cuts read
|
||||
//! the bytes alone: nothing of any driver's format. A smaller record stays whole.
|
||||
//! - **The manifest** is the record's file, at its path: [`MAGIC`], the record's length, the
|
||||
//! chunks' count, each chunk's SHA-256 and length, and the SHA-256 of every byte before. A read
|
||||
//! joins the chunks back into the record's bytes, which its decoder checks end to end as it
|
||||
//! checks a whole record's (a driver record's checksum, a library's content hash), so a chunk
|
||||
//! is not hashed again as it is read. A chunk that is not there, or of another length, makes
|
||||
//! the read a miss, and a making writes the record again.
|
||||
//! - **A manifest never names a chunk that is not there.** A write writes each chunk, a
|
||||
//! temporary file renamed over it, before the manifest's own rename; a crash leaves chunks no
|
||||
//! manifest names, never a manifest without its chunks. A chunk already there is read and
|
||||
//! checked against its digest first, and written again where it does not match. The cleanup
|
||||
//! removes only chunks no manifest names: writers hold [`LOCK`] shared from their first look at
|
||||
//! a chunk to their manifest's rename, and the cleanup holds it exclusively (`File::lock`, an
|
||||
//! advisory lock on the file: other processes' writers and cleanups included). Neither waits:
|
||||
//! the cleanup takes it with `try_lock` and is left to a later scan while a writer writes, and a
|
||||
//! writer that meets a cleanup writes its record whole.
|
||||
//! - **Outside the layout directory.** The chunks live beside `<root>/v1`, not in it, so a build
|
||||
//! whose scans know nothing of them (they remove a build's directory unused for 30 days and the
|
||||
//! least recently used files they find) never removes one.
|
||||
//! - **A bounded cleanup** ([`Chunks::cleanup`]), in the scans `store.rs` makes already: at the
|
||||
//! sweep at a device's creation where none ran yet ([`STATE`] missing) or the chunks hold more
|
||||
//! than [`GROWTH`] percent of what the last one kept, and after a scan past the cap removed a
|
||||
//! record. It reads the first bytes of each content record (a manifest whole: 36 bytes a
|
||||
//! chunk) and lists the chunks once. It also removes the content directory's records of a
|
||||
//! retired frame (`driver::RETIRED`: the driver data of an older `driver::VERSION`, which no
|
||||
//! build of this one names), so an upgrade does not leave the old records beside the new.
|
||||
|
||||
use super::store::{create_private_dir_all, hex, new_private_file, unique};
|
||||
use metal2vulkan::cache::Hash256;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
/// The least record kept as chunks; a smaller one stays whole.
|
||||
pub(crate) const WHOLE: usize = 256 << 10;
|
||||
/// The chunks' average length. Of the averages measured on the node's records (16, 32 and
|
||||
/// 64 KiB), the least stored: 64 KiB keeps the chunk across each end of a shared run apart in
|
||||
/// every record, 16 KiB doubles the files a read opens for 1.3 times the bytes.
|
||||
pub(crate) const AVERAGE: usize = 32 << 10;
|
||||
/// The shortest chunk but a record's last.
|
||||
const MIN: usize = AVERAGE / 4;
|
||||
/// The longest chunk.
|
||||
const MAX: usize = AVERAGE * 4;
|
||||
/// The first bytes of a manifest.
|
||||
pub(crate) const MAGIC: [u8; 8] = *b"M2VCHNK1";
|
||||
/// A manifest's bytes before its chunks: the magic, the record's length (u64) and the count
|
||||
/// (u32).
|
||||
const HEAD: usize = 8 + 8 + 4;
|
||||
/// A chunk's bytes in a manifest: its SHA-256 and its length (u32).
|
||||
const ENTRY: usize = 32 + 4;
|
||||
/// A manifest's bytes after its chunks: the SHA-256 of every byte before.
|
||||
const CHECKSUM: usize = 32;
|
||||
/// The lock file writers hold shared and the cleanup exclusively.
|
||||
const LOCK: &str = "lock";
|
||||
/// The file the last cleanup left the bytes it kept in (u64).
|
||||
const STATE: &str = "state";
|
||||
/// The share (percent) of the last cleanup's kept bytes past which the chunks bring the sweep's
|
||||
/// cleanup.
|
||||
const GROWTH: u64 = 110;
|
||||
|
||||
/// The gear hash's table: a value per byte, from SplitMix64.
|
||||
const GEAR: [u64; 256] = gear();
|
||||
|
||||
const fn gear() -> [u64; 256] {
|
||||
let mut table = [0u64; 256];
|
||||
let mut state = 0x9e37_79b9_7f4a_7c15u64;
|
||||
let mut at = 0;
|
||||
while at < 256 {
|
||||
state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
let mut z = state;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
table[at] = z ^ (z >> 31);
|
||||
at += 1;
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
/// The ends of `data`'s chunks, in order (the module docs): each cut where the gear hash of the
|
||||
/// bytes since the chunk's [`MIN`]th meets the harder mask before [`AVERAGE`] and the easier one
|
||||
/// after it, else at [`MAX`]; the last chunk ends with the data.
|
||||
pub(crate) fn ends(data: &[u8]) -> Vec<usize> {
|
||||
let bits = AVERAGE.trailing_zeros();
|
||||
// The masks take the hash's bits from the 16th on, which the 16 bytes before a byte reach too.
|
||||
let hard = ((1u64 << (bits + 1)) - 1) << 16;
|
||||
let easy = ((1u64 << (bits - 1)) - 1) << 16;
|
||||
let mut ends = Vec::with_capacity(data.len() / AVERAGE + 1);
|
||||
let mut start = 0;
|
||||
while start < data.len() {
|
||||
let rest = &data[start..];
|
||||
start += match rest.len() <= MIN {
|
||||
true => rest.len(),
|
||||
false => cut(rest, hard, easy),
|
||||
};
|
||||
ends.push(start);
|
||||
}
|
||||
ends
|
||||
}
|
||||
|
||||
/// The length of the chunk `rest` begins with ([`ends`]).
|
||||
fn cut(rest: &[u8], hard: u64, easy: u64) -> usize {
|
||||
let limit = rest.len().min(MAX);
|
||||
let normal = rest.len().min(AVERAGE);
|
||||
let mut hash = 0u64;
|
||||
for (at, &byte) in rest.iter().enumerate().take(limit).skip(MIN) {
|
||||
hash = (hash << 1).wrapping_add(GEAR[usize::from(byte)]);
|
||||
let mask = if at < normal { hard } else { easy };
|
||||
if hash & mask == 0 {
|
||||
return at + 1;
|
||||
}
|
||||
}
|
||||
limit
|
||||
}
|
||||
|
||||
/// A record's chunks, as its manifest lists them: each one's SHA-256 and length.
|
||||
pub(crate) type Listed = Vec<(Hash256, u32)>;
|
||||
|
||||
/// The manifest of a record of `length` bytes cut into `listed`.
|
||||
fn manifest(length: u64, listed: &[(Hash256, u32)]) -> Vec<u8> {
|
||||
let mut bytes = Vec::with_capacity(HEAD + ENTRY * listed.len() + CHECKSUM);
|
||||
bytes.extend_from_slice(&MAGIC);
|
||||
bytes.extend_from_slice(&length.to_le_bytes());
|
||||
bytes.extend_from_slice(&(listed.len() as u32).to_le_bytes());
|
||||
for (digest, chunk) in listed {
|
||||
bytes.extend_from_slice(digest);
|
||||
bytes.extend_from_slice(&chunk.to_le_bytes());
|
||||
}
|
||||
let checksum: Hash256 = Sha256::digest(&bytes).into();
|
||||
bytes.extend_from_slice(&checksum);
|
||||
bytes
|
||||
}
|
||||
|
||||
/// The record's length and chunks a manifest's `bytes` list, where they are one whole: its magic,
|
||||
/// its checksum, its count and the chunks' lengths summing to the record's.
|
||||
pub(crate) fn listed(bytes: &[u8]) -> Option<(u64, Listed)> {
|
||||
if bytes.get(..8)? != MAGIC || bytes.len() < HEAD + CHECKSUM {
|
||||
return None;
|
||||
}
|
||||
let body = bytes.len() - CHECKSUM;
|
||||
let checksum: Hash256 = Sha256::digest(&bytes[..body]).into();
|
||||
if bytes[body..] != checksum {
|
||||
return None;
|
||||
}
|
||||
let length = u64::from_le_bytes(bytes[8..16].try_into().ok()?);
|
||||
let count = u32::from_le_bytes(bytes[16..HEAD].try_into().ok()?) as usize;
|
||||
if body != HEAD + count.checked_mul(ENTRY)? {
|
||||
return None;
|
||||
}
|
||||
let (entries, _) = bytes[HEAD..body].as_chunks::<ENTRY>();
|
||||
let listed: Listed = entries
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let digest: Hash256 = entry[..32].try_into().expect("32 bytes");
|
||||
let chunk = u32::from_le_bytes(entry[32..].try_into().expect("4 bytes"));
|
||||
(digest, chunk)
|
||||
})
|
||||
.collect();
|
||||
let sum: u64 = listed.iter().map(|(_, chunk)| u64::from(*chunk)).sum();
|
||||
(sum == length).then_some((length, listed))
|
||||
}
|
||||
|
||||
/// The chunk directory of a cache root (the module docs).
|
||||
pub(crate) struct Chunks {
|
||||
dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Chunks {
|
||||
/// The chunks of the cache directory `root`.
|
||||
pub(crate) fn of(root: &Path) -> Chunks {
|
||||
Chunks {
|
||||
dir: root.join("chunks"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of the chunk of SHA-256 `digest`.
|
||||
fn path(&self, digest: &Hash256) -> PathBuf {
|
||||
let name = hex(digest);
|
||||
self.dir.join(&name[..2]).join(name)
|
||||
}
|
||||
|
||||
/// The lock file, opened (made where missing).
|
||||
fn lock(&self) -> io::Result<fs::File> {
|
||||
create_private_dir_all(&self.dir)?;
|
||||
fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(self.dir.join(LOCK))
|
||||
}
|
||||
|
||||
/// Write `bytes`, a record, as chunks and then its manifest, which `put` writes in its place
|
||||
/// (a temporary file renamed over it), holding the lock shared throughout (the module docs);
|
||||
/// while a cleanup holds it, `put` writes the record whole instead, so no write waits. The
|
||||
/// bytes written: the chunks not there before, and the manifest.
|
||||
pub(crate) fn write(
|
||||
&self,
|
||||
bytes: &[u8],
|
||||
put: impl FnOnce(&[u8]) -> io::Result<u64>,
|
||||
) -> io::Result<u64> {
|
||||
let lock = self.lock()?;
|
||||
match lock.try_lock_shared() {
|
||||
Ok(()) => {}
|
||||
Err(fs::TryLockError::WouldBlock) => return put(bytes),
|
||||
Err(fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let mut listed = Vec::new();
|
||||
let mut written = 0u64;
|
||||
let mut start = 0;
|
||||
for end in ends(bytes) {
|
||||
let chunk = &bytes[start..end];
|
||||
start = end;
|
||||
let digest: Hash256 = Sha256::digest(chunk).into();
|
||||
let path = self.path(&digest);
|
||||
if !holds(&path, &digest) {
|
||||
write_chunk(&path, chunk)?;
|
||||
written += chunk.len() as u64;
|
||||
}
|
||||
listed.push((digest, chunk.len() as u32));
|
||||
}
|
||||
let put = put(&manifest(bytes.len() as u64, &listed))?;
|
||||
drop(lock);
|
||||
Ok(written + put)
|
||||
}
|
||||
|
||||
/// The record `manifest` lists, its chunks joined; `None` where it is no manifest, lists a
|
||||
/// record past `limit` bytes, or names a chunk that is not there or of another length.
|
||||
pub(crate) fn read(&self, manifest: &[u8], limit: u64) -> Option<Vec<u8>> {
|
||||
let (length, listed) = listed(manifest)?;
|
||||
if length > limit {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(usize::try_from(length).ok()?);
|
||||
// Every chunk opened first, and on Linux the kernel asked to read each ahead, so the reads
|
||||
// of those not in the page cache run together rather than one after another.
|
||||
let files: Vec<(fs::File, u32)> = (listed.into_iter())
|
||||
.map(|(digest, chunk)| Some((fs::File::open(self.path(&digest)).ok()?, chunk)))
|
||||
.collect::<Option<_>>()?;
|
||||
#[cfg(target_os = "linux")]
|
||||
for (file, _) in &files {
|
||||
use std::os::fd::AsRawFd;
|
||||
// SAFETY: a file descriptor of an open file, the whole of it (a length of 0); the
|
||||
// advice changes no contents.
|
||||
unsafe { libc::posix_fadvise(file.as_raw_fd(), 0, 0, libc::POSIX_FADV_WILLNEED) };
|
||||
}
|
||||
for (file, chunk) in files {
|
||||
let before = bytes.len();
|
||||
file.take(u64::from(chunk) + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.ok()?;
|
||||
if bytes.len() - before != chunk as usize {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
/// The bytes the chunks hold, by a listing.
|
||||
pub(crate) fn bytes(&self) -> u64 {
|
||||
let mut bytes = 0;
|
||||
each_chunk(&self.dir, |_, metadata| bytes += metadata.len());
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Whether the sweep's cleanup is due: none left its state yet, or the chunks hold more than
|
||||
/// [`GROWTH`] percent of what the last one kept.
|
||||
pub(crate) fn due(&self) -> bool {
|
||||
let kept = fs::read(self.dir.join(STATE))
|
||||
.ok()
|
||||
.and_then(|bytes| bytes.try_into().ok())
|
||||
.map(u64::from_le_bytes);
|
||||
match kept {
|
||||
None => true,
|
||||
Some(kept) => self.bytes() > kept.saturating_mul(GROWTH) / 100,
|
||||
}
|
||||
}
|
||||
|
||||
/// The manifests among the records of the content directory `content`, by path, with the
|
||||
/// chunks each lists, the records of a `retired` frame removed on the way; `None` where
|
||||
/// `stop` was set before every record was read.
|
||||
pub(crate) fn manifests(
|
||||
&self,
|
||||
content: &Path,
|
||||
retired: &[[u8; 8]],
|
||||
stop: &AtomicBool,
|
||||
) -> Option<HashMap<PathBuf, Listed>> {
|
||||
let mut manifests = HashMap::new();
|
||||
let groups = match fs::read_dir(content) {
|
||||
Ok(groups) => groups,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Some(manifests),
|
||||
Err(_) => return None,
|
||||
};
|
||||
for group in groups.flatten() {
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let Ok(files) = fs::read_dir(group.path()) else {
|
||||
continue;
|
||||
};
|
||||
for file in files.flatten() {
|
||||
let temporary = file
|
||||
.file_name()
|
||||
.to_str()
|
||||
.is_some_and(|n| n.starts_with('.'));
|
||||
if temporary {
|
||||
continue;
|
||||
}
|
||||
let path = file.path();
|
||||
let Ok(mut opened) = fs::File::open(&path) else {
|
||||
continue;
|
||||
};
|
||||
let mut head = [0u8; 8];
|
||||
if opened.read_exact(&mut head).is_err() {
|
||||
continue;
|
||||
}
|
||||
if retired.contains(&head) {
|
||||
let _ = fs::remove_file(&path);
|
||||
continue;
|
||||
}
|
||||
if head != MAGIC {
|
||||
continue;
|
||||
}
|
||||
let mut bytes = head.to_vec();
|
||||
if opened.read_to_end(&mut bytes).is_err() {
|
||||
// A manifest not read whole names chunks that stay: the cleanup gives up.
|
||||
return None;
|
||||
}
|
||||
if let Some((_, listed)) = listed(&bytes) {
|
||||
manifests.insert(path, listed);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(manifests)
|
||||
}
|
||||
|
||||
/// Remove the chunks no manifest of the content directory `content` names, and the
|
||||
/// temporary files of writers that died, and the content records of a `retired` frame,
|
||||
/// holding the lock exclusively; the bytes the chunks kept hold, left as [`STATE`]. `None`
|
||||
/// where a writer holds the lock (nothing is done), or `stop` was set first.
|
||||
pub(crate) fn cleanup(
|
||||
&self,
|
||||
content: &Path,
|
||||
retired: &[[u8; 8]],
|
||||
stop: &AtomicBool,
|
||||
) -> Option<u64> {
|
||||
let lock = self.lock().ok()?;
|
||||
lock.try_lock().ok()?;
|
||||
let manifests = self.manifests(content, retired, stop)?;
|
||||
let named: HashSet<&Hash256> = (manifests.values().flatten())
|
||||
.map(|(digest, _)| digest)
|
||||
.collect();
|
||||
let mut kept = 0;
|
||||
each_chunk(&self.dir, |path, metadata| {
|
||||
let name = path.file_name().and_then(|name| name.to_str());
|
||||
// A temporary file: the writer that made it holds no lock, so it died.
|
||||
let temporary = name.is_none_or(|name| name.starts_with('.'));
|
||||
let digest = name.and_then(unhex);
|
||||
match digest.filter(|digest| named.contains(digest)) {
|
||||
Some(_) if !temporary => kept += metadata.len(),
|
||||
_ => {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
});
|
||||
let _ = fs::write(self.dir.join(STATE), kept.to_le_bytes());
|
||||
drop(lock);
|
||||
Some(kept)
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` over each file in a group directory of `dir` (the chunks and their temporary files).
|
||||
fn each_chunk(dir: &Path, mut f: impl FnMut(&Path, &fs::Metadata)) {
|
||||
let Ok(groups) = fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for group in groups.flatten() {
|
||||
if !group.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(files) = fs::read_dir(group.path()) else {
|
||||
continue;
|
||||
};
|
||||
for file in files.flatten() {
|
||||
if let Ok(metadata) = file.metadata() {
|
||||
if metadata.is_file() {
|
||||
f(&file.path(), &metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The digest a chunk's file name spells, in hex.
|
||||
fn unhex(name: &str) -> Option<Hash256> {
|
||||
if name.len() != 64 {
|
||||
return None;
|
||||
}
|
||||
let mut digest = [0u8; 32];
|
||||
for (at, byte) in digest.iter_mut().enumerate() {
|
||||
*byte = u8::from_str_radix(name.get(2 * at..2 * at + 2)?, 16).ok()?;
|
||||
}
|
||||
Some(digest)
|
||||
}
|
||||
|
||||
/// Whether the chunk at `path` is there and holds the bytes of SHA-256 `digest`.
|
||||
fn holds(path: &Path, digest: &Hash256) -> bool {
|
||||
fs::read(path).is_ok_and(|bytes| Sha256::digest(&bytes)[..] == digest[..])
|
||||
}
|
||||
|
||||
/// Write `chunk` at `path`: a temporary file beside it, renamed over it.
|
||||
fn write_chunk(path: &Path, chunk: &[u8]) -> io::Result<()> {
|
||||
let parent = path.parent().expect("a chunk has a group directory");
|
||||
create_private_dir_all(parent)?;
|
||||
let name = path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("chunk");
|
||||
let temporary = parent.join(format!(".{name}.{}.tmp", unique()));
|
||||
let written = (|| {
|
||||
let mut file = new_private_file(&temporary)?;
|
||||
file.write_all(chunk)?;
|
||||
drop(file);
|
||||
fs::rename(&temporary, path)
|
||||
})();
|
||||
if written.is_err() {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
}
|
||||
written
|
||||
}
|
||||
@@ -59,7 +59,10 @@
|
||||
//! Records live in the content directory, which no build owns (`store.rs`): a new build of the
|
||||
//! runtime or the translator that leaves a pipeline's SPIR-V and state as they were finds its
|
||||
//! record. The driver keys each pipeline by everything its creation reads, so a description
|
||||
//! that covers a making loosely costs a compile, never a wrong pipeline.
|
||||
//! that covers a making loosely costs a compile, never a wrong pipeline. A record of 256 KiB
|
||||
//! or more is kept as a manifest over content-defined chunks that every record shares where
|
||||
//! their bytes do (`chunks.rs`: NVIDIA's data repeats one 1.85 MB section across families),
|
||||
//! and read whole again; the frame below is what a read gives back.
|
||||
//! - **No figure of the driver's to meet.** A record holds one family's data (an Xgc pipeline's
|
||||
//! 1.7 MB on an RTX 3090), so how much of a large cache's initial data a
|
||||
//! driver keeps does not decide which pipelines are kept. The shader cache's cap and its scans,
|
||||
@@ -85,7 +88,7 @@
|
||||
//! off (NVIDIA's `__GL_SHADER_DISK_CACHE=0`, Mesa's `MESA_SHADER_CACHE_DISABLE=true`).
|
||||
//!
|
||||
//! ```text
|
||||
//! magic 8 bytes "M2VPPLC\0"
|
||||
//! magic 8 bytes "M2VPPL4\0"
|
||||
//! identity 28 bytes vendorID, deviceID, driverVersion (u32 each), pipelineCacheUUID
|
||||
//! data length u64
|
||||
//! data vkGetPipelineCacheData's bytes
|
||||
@@ -112,12 +115,17 @@ use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
const MAGIC: [u8; 8] = *b"M2VPPLC\0";
|
||||
const MAGIC: [u8; 8] = *b"M2VPPL4\0";
|
||||
/// The magics of the records of older versions, which no build of this one names: the store's
|
||||
/// cleanup removes them from the content directory (`chunks.rs`), so an upgrade does not keep
|
||||
/// them beside the records that replace them.
|
||||
pub(crate) const RETIRED: [[u8; 8]; 1] = [*b"M2VPPLC\0"];
|
||||
/// The version of what a record's name covers and how a record is framed: a change to either
|
||||
/// bumps it, so no build opens a record another build names or frames otherwise. A record of an
|
||||
/// older version is named otherwise, so it is never found and never read: a bump costs a family
|
||||
/// its records, never a misread.
|
||||
pub(crate) const VERSION: u32 = 3;
|
||||
/// bumps it, and the frame's magic with it ([`RETIRED`] takes the old one), so no build opens a
|
||||
/// record another build names or frames otherwise. A record of an older version is named
|
||||
/// otherwise, so it is never found and never read: a bump costs a family its records, never a
|
||||
/// misread. Version 4 keeps a large record's data as chunks (`chunks.rs`).
|
||||
pub(crate) const VERSION: u32 = 4;
|
||||
|
||||
/// The most `VkPipelineCache`es a device keeps live, one per record name. Past it a making of a
|
||||
/// further name is handed a cache of its own, destroyed once the making returned, so a program
|
||||
|
||||
@@ -58,6 +58,7 @@
|
||||
//! variant's link asks once per stage; the answer is kept under exactly that key (`held.rs`),
|
||||
//! so a sweep of pipeline states over one function pair asks it once rather than once a state.
|
||||
|
||||
mod chunks;
|
||||
mod creation;
|
||||
mod libraries;
|
||||
/// The name of a creation's record under a runtime version, which `tests::shader_cache` reads.
|
||||
|
||||
@@ -10,7 +10,11 @@
|
||||
//! owns, named by the content they describe: the driver's pipeline cache data (It was the
|
||||
//! build's; one record per pipeline making), named by what each making reads and read as an entry
|
||||
//! is, with its counts (`driver.rs`), and the libraries pipeline records name, by their content
|
||||
//! hash (`libraries.rs`); the scans bound them with the rest.
|
||||
//! hash (`libraries.rs`); the scans bound them with the rest. A record of `chunks::WHOLE` bytes
|
||||
//! or more is kept as a manifest over content-defined chunks in `<root>/chunks`, outside the
|
||||
//! layout directory, each run of bytes the records share kept once, and read as its chunks
|
||||
//! joined (`chunks.rs`); the chunks count against the cap, and a cleanup in the scans removes
|
||||
//! those no manifest names.
|
||||
//! - An entry's name is the SHA-256 of a domain tag, the build, the entry's kind, its key and the
|
||||
//! profile fingerprint ([`entry_name`]). The decoder the caller hands to [`Store::load`] checks
|
||||
//! the contents against the request byte for byte; contents it refuses are removed.
|
||||
@@ -33,11 +37,13 @@
|
||||
//! creation the scan also removes other builds' directories that nothing used for
|
||||
//! [`UNUSED_BUILD`].
|
||||
|
||||
use super::chunks::{self, Chunks};
|
||||
use super::worker::{Asked, Write as Queued, QUEUED_BYTES};
|
||||
use super::EntryKind;
|
||||
use crate::{DebugMessage, Degradation, DegradeNotice, MessageKind, MessageSeverity, MessageSink};
|
||||
use metal2vulkan::cache::Hash256;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -129,10 +135,23 @@ impl Directory {
|
||||
|
||||
/// The path of the record named `name` in the content directory.
|
||||
pub(crate) fn record_path(&self, name: &str) -> PathBuf {
|
||||
self.layout_dir()
|
||||
.join(hex(&content()))
|
||||
.join(&name[..2])
|
||||
.join(name)
|
||||
self.content_dir().join(&name[..2]).join(name)
|
||||
}
|
||||
|
||||
/// `<root>/v1/<content>`: the content directory ([`content`]).
|
||||
fn content_dir(&self) -> PathBuf {
|
||||
self.layout_dir().join(hex(&content()))
|
||||
}
|
||||
|
||||
/// Whether `path` is a record's in the content directory, which a large one's write keeps
|
||||
/// as chunks (`chunks.rs`).
|
||||
fn is_record(&self, path: &Path) -> bool {
|
||||
path.parent().and_then(Path::parent) == Some(self.content_dir().as_path())
|
||||
}
|
||||
|
||||
/// The chunks the content directory's large records are kept as (`chunks.rs`).
|
||||
fn chunks(&self) -> Chunks {
|
||||
Chunks::of(&self.root)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -586,6 +605,14 @@ impl Store {
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
|
||||
match (&file).take(limit + 1).read_to_end(&mut bytes) {
|
||||
// A record kept as chunks is read as its chunks joined; one that names a chunk
|
||||
// not there is a miss, which a making writes again (`chunks.rs`).
|
||||
Ok(_) if bytes.starts_with(&chunks::MAGIC) && self.directory.is_record(path) => {
|
||||
match self.directory.chunks().read(&bytes, limit) {
|
||||
Some(joined) => Found::Bytes(joined, file),
|
||||
None => Found::Absent,
|
||||
}
|
||||
}
|
||||
Ok(_) if bytes.len() as u64 <= limit => Found::Bytes(bytes, file),
|
||||
Ok(_) => {
|
||||
remove(path);
|
||||
@@ -646,33 +673,25 @@ impl Store {
|
||||
}
|
||||
|
||||
/// Write `bytes` as the entry at `path`, named `name`, on the calling thread: a temporary
|
||||
/// file beside it, flushed and renamed over it. The bytes written, or the failure (the
|
||||
/// temporary file is removed). An entry larger than [`Store::entry_limit`] fails.
|
||||
/// file beside it, flushed and renamed over it; a content record of [`chunks::WHOLE`] bytes
|
||||
/// or more as its chunks and then its manifest there (`chunks.rs`). The bytes written, or the
|
||||
/// failure (the temporary file is removed). An entry larger than [`Store::entry_limit`]
|
||||
/// fails.
|
||||
fn write_at(&self, path: &Path, name: &str, bytes: &[u8]) -> io::Result<u64> {
|
||||
let length = bytes.len() as u64;
|
||||
if length > self.entry_limit() {
|
||||
if bytes.len() as u64 > self.entry_limit() {
|
||||
return Err(io::Error::other("the entry is larger than the cache takes"));
|
||||
}
|
||||
let parent = path.parent().expect("an entry has a directory");
|
||||
create_private_dir_all(parent)?;
|
||||
let temporary = parent.join(format!(".{name}.{}.tmp", unique()));
|
||||
let written = (|| {
|
||||
let mut file = new_private_file(&temporary)?;
|
||||
file.write_all(bytes)?;
|
||||
drop(file);
|
||||
fs::rename(&temporary, path)?;
|
||||
Ok(length)
|
||||
})();
|
||||
match &written {
|
||||
Ok(bytes) => {
|
||||
self.used.fetch_add(*bytes, Ordering::Relaxed);
|
||||
self.counters
|
||||
.written_bytes
|
||||
.fetch_add(*bytes, Ordering::Relaxed);
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
let written = match bytes.len() >= chunks::WHOLE && self.directory.is_record(path) {
|
||||
true => {
|
||||
(self.directory.chunks()).write(bytes, |manifest| write_file(path, name, manifest))
|
||||
}
|
||||
false => write_file(path, name, bytes),
|
||||
};
|
||||
if let Ok(bytes) = &written {
|
||||
self.used.fetch_add(*bytes, Ordering::Relaxed);
|
||||
self.counters
|
||||
.written_bytes
|
||||
.fetch_add(*bytes, Ordering::Relaxed);
|
||||
}
|
||||
written
|
||||
}
|
||||
@@ -701,9 +720,18 @@ impl Store {
|
||||
fn scan(&self, stop: &AtomicBool, unused_builds: bool) {
|
||||
let now = SystemTime::now();
|
||||
let own = hex(&self.directory.build);
|
||||
let chunks = self.directory.chunks();
|
||||
let content = self.directory.content_dir();
|
||||
let retired = &super::driver::RETIRED;
|
||||
// The sweep's cleanup of the chunks where it is due (`chunks.rs`), first: it removes the
|
||||
// content records of a retired frame, which the survey would count.
|
||||
if unused_builds && chunks.due() {
|
||||
chunks.cleanup(&content, retired, stop);
|
||||
}
|
||||
let Ok(builds) = fs::read_dir(self.directory.layout_dir()) else {
|
||||
return;
|
||||
};
|
||||
let mut content_removed = false;
|
||||
let mut entries = Vec::new();
|
||||
for build in builds.flatten() {
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
@@ -718,27 +746,58 @@ impl Store {
|
||||
let unused = now.duration_since(newest).unwrap_or_default() >= UNUSED_BUILD;
|
||||
if unused_builds && unused && build.file_name().to_str() != Some(own.as_str()) {
|
||||
entries.truncate(start);
|
||||
content_removed |= path == content;
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
}
|
||||
}
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let total: u64 = entries.iter().map(|entry| entry.bytes).sum();
|
||||
let remaining = if total > self.directory.capacity {
|
||||
self.remove_oldest(entries, total)
|
||||
} else {
|
||||
total
|
||||
// The chunks count against the cap with the entries; a removed manifest frees the bytes
|
||||
// of the chunks no other names, which the cleanup after removes.
|
||||
let chunk_bytes = chunks.bytes();
|
||||
let total: u64 = entries.iter().map(|entry| entry.bytes).sum::<u64>() + chunk_bytes;
|
||||
let mut freed_chunks = content_removed && chunk_bytes > 0;
|
||||
let remaining = match total > self.directory.capacity {
|
||||
true => match chunks.manifests(&content, retired, stop) {
|
||||
Some(manifests) => {
|
||||
let (remaining, freed) =
|
||||
self.remove_oldest(entries, total, (&manifests, chunk_bytes));
|
||||
freed_chunks |= freed;
|
||||
remaining
|
||||
}
|
||||
None => return,
|
||||
},
|
||||
false => total,
|
||||
};
|
||||
if freed_chunks {
|
||||
chunks.cleanup(&content, retired, stop);
|
||||
}
|
||||
// Writes since the scan began may be counted twice: the next scan corrects it.
|
||||
self.used.store(remaining, Ordering::Relaxed);
|
||||
self.scanned.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Remove the least recently used of `entries` (holding `total` bytes) until what remains
|
||||
/// is at most [`LOW_WATER`] of the cap; the bytes that remain.
|
||||
fn remove_oldest(&self, mut entries: Vec<Entry>, mut total: u64) -> u64 {
|
||||
/// Remove the least recently used of `entries` (holding `total` bytes, of which the chunks
|
||||
/// `chunk_bytes`, which `manifests` name) until what remains is at most [`LOW_WATER`] of the
|
||||
/// cap: the bytes that remain, counting the chunks no remaining manifest names as freed, and
|
||||
/// whether any are, which the cleanup after removes (`chunks.rs`).
|
||||
fn remove_oldest(
|
||||
&self,
|
||||
mut entries: Vec<Entry>,
|
||||
mut total: u64,
|
||||
(manifests, chunk_bytes): (&HashMap<PathBuf, chunks::Listed>, u64),
|
||||
) -> (u64, bool) {
|
||||
let target = self.directory.capacity / 100 * LOW_WATER;
|
||||
// Each chunk's manifests and length; the bytes of chunks none names go at the cleanup.
|
||||
let mut named: HashMap<&Hash256, (usize, u64)> = HashMap::new();
|
||||
for (digest, length) in manifests.values().flatten() {
|
||||
named.entry(digest).or_insert((0, u64::from(*length))).0 += 1;
|
||||
}
|
||||
let held: u64 = named.values().map(|(_, length)| length).sum();
|
||||
let unnamed = chunk_bytes.saturating_sub(held);
|
||||
total = total.saturating_sub(unnamed);
|
||||
let mut freed = unnamed > 0;
|
||||
entries.sort_by_key(|entry| entry.used);
|
||||
for entry in entries {
|
||||
if total <= target {
|
||||
@@ -765,11 +824,39 @@ impl Store {
|
||||
}
|
||||
}
|
||||
total = total.saturating_sub(entry.bytes);
|
||||
for (digest, _) in manifests.get(&entry.path).into_iter().flatten() {
|
||||
if let Some((count, length)) = named.get_mut(digest) {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
total = total.saturating_sub(*length);
|
||||
freed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
total
|
||||
(total, freed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `bytes` as the file at `path`, named `name`: a temporary file beside it, flushed and
|
||||
/// renamed over it. Their length, or the failure (the temporary file is removed).
|
||||
fn write_file(path: &Path, name: &str, bytes: &[u8]) -> io::Result<u64> {
|
||||
let parent = path.parent().expect("an entry has a directory");
|
||||
create_private_dir_all(parent)?;
|
||||
let temporary = parent.join(format!(".{name}.{}.tmp", unique()));
|
||||
let written = (|| {
|
||||
let mut file = new_private_file(&temporary)?;
|
||||
file.write_all(bytes)?;
|
||||
drop(file);
|
||||
fs::rename(&temporary, path)?;
|
||||
Ok(bytes.len() as u64)
|
||||
})();
|
||||
if written.is_err() {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
/// Remove the file at `path` (another process may have removed it first).
|
||||
fn remove(path: &Path) {
|
||||
let _ = fs::remove_file(path);
|
||||
@@ -854,7 +941,7 @@ fn touch(file: &fs::File) {
|
||||
}
|
||||
|
||||
/// A name no other writer uses: this process's id, a per-process sequence number, and the time.
|
||||
fn unique() -> String {
|
||||
pub(super) fn unique() -> String {
|
||||
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
@@ -879,7 +966,7 @@ pub(super) fn create_private_dir_all(dir: &Path) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// Create the new file `path`, which only its owner may read; fails if it exists.
|
||||
fn new_private_file(path: &Path) -> io::Result<fs::File> {
|
||||
pub(super) fn new_private_file(path: &Path) -> io::Result<fs::File> {
|
||||
let mut options = fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -586,6 +586,7 @@ mod self_read_storage;
|
||||
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
||||
mod set_zero_at_offsets;
|
||||
mod shader_cache;
|
||||
mod shader_cache_chunks;
|
||||
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
||||
mod shader_cache_off_thread;
|
||||
mod shader_cache_queue;
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
//! The content directory's large records kept as chunks (`shader_cache/chunks.rs`): written as
|
||||
//! chunks and a manifest after them, read back whole, a run two records share kept once, a
|
||||
//! missing or damaged chunk, the sweep's cleanup (unnamed chunks, dead writers' temporaries, the
|
||||
//! records of a retired frame), a writer's lock putting it off, a cleanup's lock making a writer
|
||||
//! write whole, and the cap. Each test owns an
|
||||
//! empty directory ([`Scratch`]) and a store with no cache thread, so its writes are the calling
|
||||
//! thread's; the records are opaque bytes, which a decoder of the bytes themselves reads back.
|
||||
|
||||
use super::shader_cache::{store, Scratch, BUILD};
|
||||
use crate::shader_cache::store::{content, hex, Lookup, Store, LAYOUT};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
/// The first bytes of a manifest (`chunks::MAGIC`).
|
||||
const MANIFEST: &[u8; 8] = b"M2VCHNK1";
|
||||
/// The least record kept as chunks (`chunks::WHOLE`).
|
||||
const WHOLE: usize = 256 << 10;
|
||||
/// The longest chunk (`chunks::MAX`).
|
||||
const MAX: usize = 128 << 10;
|
||||
|
||||
/// `length` bytes of a generator seeded with `seed`.
|
||||
fn noise(seed: u64, length: usize) -> Vec<u8> {
|
||||
let mut state = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1;
|
||||
(0..length)
|
||||
.map(|_| {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 24) as u8
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The name of record `n`.
|
||||
fn name(n: u32) -> String {
|
||||
hex(&Sha256::digest(n.to_le_bytes()).into())
|
||||
}
|
||||
|
||||
/// The path of the record named `name` under `root`.
|
||||
fn record_path(root: &Path, name: &str) -> PathBuf {
|
||||
root.join(LAYOUT)
|
||||
.join(hex(&content()))
|
||||
.join(&name[..2])
|
||||
.join(name)
|
||||
}
|
||||
|
||||
/// The chunk directory under `root`.
|
||||
fn chunk_dir(root: &Path) -> PathBuf {
|
||||
root.join("chunks")
|
||||
}
|
||||
|
||||
/// The files of the chunk directory's groups under `root`, with their lengths.
|
||||
fn chunk_files(root: &Path) -> Vec<(PathBuf, u64)> {
|
||||
let mut files = Vec::new();
|
||||
let Ok(groups) = fs::read_dir(chunk_dir(root)) else {
|
||||
return files;
|
||||
};
|
||||
for group in groups.flatten() {
|
||||
if !group.path().is_dir() {
|
||||
continue;
|
||||
}
|
||||
for file in fs::read_dir(group.path()).unwrap().flatten() {
|
||||
files.push((file.path(), file.metadata().unwrap().len()));
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
/// The bytes of the chunks under `root`.
|
||||
fn chunk_bytes(root: &Path) -> u64 {
|
||||
chunk_files(root).iter().map(|(_, length)| length).sum()
|
||||
}
|
||||
|
||||
/// The record `name` of `store`, its bytes as read.
|
||||
fn get(store: &Store, name: &str) -> Option<Vec<u8>> {
|
||||
match store.load_content(name, Some) {
|
||||
Lookup::Hit(bytes) => Some(bytes),
|
||||
Lookup::Absent | Lookup::Unreadable | Lookup::Rejected => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A record of `WHOLE` bytes or more is a small manifest at its path over chunks that hold its
|
||||
/// bytes, and reads back whole; a smaller one stays whole.
|
||||
#[test]
|
||||
fn a_large_record_is_kept_as_chunks_and_read_back_whole() {
|
||||
let scratch = Scratch::new();
|
||||
let store = store(scratch.path(), BUILD, 1 << 30);
|
||||
let record = noise(1, 1 << 20);
|
||||
store.write_record_soon(&name(1), record.clone()).unwrap();
|
||||
let manifest = fs::read(record_path(scratch.path(), &name(1))).unwrap();
|
||||
assert_eq!(&manifest[..8], MANIFEST);
|
||||
assert!(
|
||||
manifest.len() < 4096,
|
||||
"a manifest of {} bytes",
|
||||
manifest.len()
|
||||
);
|
||||
let files = chunk_files(scratch.path());
|
||||
assert!(files.len() >= 8, "{} chunks of 1 MiB", files.len());
|
||||
assert!(files.iter().all(|(_, length)| *length as usize <= MAX));
|
||||
assert_eq!(chunk_bytes(scratch.path()), record.len() as u64);
|
||||
assert_eq!(get(&store, &name(1)).as_deref(), Some(&record[..]));
|
||||
let small = noise(2, WHOLE - 1);
|
||||
store.write_record_soon(&name(2), small.clone()).unwrap();
|
||||
assert_eq!(
|
||||
fs::read(record_path(scratch.path(), &name(2))).unwrap(),
|
||||
small
|
||||
);
|
||||
assert_eq!(chunk_bytes(scratch.path()), record.len() as u64);
|
||||
}
|
||||
|
||||
/// Two records that share a run of 1.5 MiB at other offsets keep it once: the second writes its
|
||||
/// own bytes and the few chunks across each end of the run alone.
|
||||
#[test]
|
||||
fn records_that_share_a_run_keep_it_once() {
|
||||
let scratch = Scratch::new();
|
||||
let store = store(scratch.path(), BUILD, 1 << 30);
|
||||
let shared = noise(3, 3 << 19);
|
||||
let a = [noise(4, 3000), shared.clone(), noise(5, 5000)].concat();
|
||||
let b = [noise(6, 7000), shared.clone(), noise(7, 1000)].concat();
|
||||
store.write_record_soon(&name(1), a.clone()).unwrap();
|
||||
let after_a = chunk_bytes(scratch.path());
|
||||
let written = store.counters.written_bytes.load(Ordering::Relaxed);
|
||||
store.write_record_soon(&name(2), b.clone()).unwrap();
|
||||
let b_wrote = store.counters.written_bytes.load(Ordering::Relaxed) - written;
|
||||
let added = chunk_bytes(scratch.path()) - after_a;
|
||||
eprintln!(
|
||||
"CHUNKS a {} bytes, b wrote {b_wrote} of {} bytes",
|
||||
a.len(),
|
||||
b.len()
|
||||
);
|
||||
assert!(added <= 3 * MAX as u64 + 8000, "{added} bytes added for b");
|
||||
assert!(b_wrote < added + 4096, "{b_wrote} bytes written for b");
|
||||
assert_eq!(get(&store, &name(1)).as_deref(), Some(&a[..]));
|
||||
assert_eq!(get(&store, &name(2)).as_deref(), Some(&b[..]));
|
||||
}
|
||||
|
||||
/// A record whose chunks cannot be written leaves no manifest: the manifest's rename comes after
|
||||
/// every chunk's.
|
||||
#[test]
|
||||
fn a_manifest_is_written_only_after_its_chunks() {
|
||||
let scratch = Scratch::new();
|
||||
let store = store(scratch.path(), BUILD, 1 << 30);
|
||||
// A file where the chunk directory goes: no chunk can be written.
|
||||
fs::write(chunk_dir(scratch.path()), b"in the way").unwrap();
|
||||
assert!(store
|
||||
.write_record_soon(&name(1), noise(1, 1 << 20))
|
||||
.is_err());
|
||||
assert!(!record_path(scratch.path(), &name(1)).exists());
|
||||
assert_eq!(get(&store, &name(1)), None);
|
||||
}
|
||||
|
||||
/// A manifest whose chunk is gone reads as a miss, and the record's next write brings the chunk
|
||||
/// back; a chunk whose bytes are not its digest's is written again too.
|
||||
#[test]
|
||||
fn a_record_naming_a_chunk_not_there_is_a_miss_until_written_again() {
|
||||
let scratch = Scratch::new();
|
||||
let store = store(scratch.path(), BUILD, 1 << 30);
|
||||
let record = noise(1, 1 << 20);
|
||||
store.write_record_soon(&name(1), record.clone()).unwrap();
|
||||
let files = chunk_files(scratch.path());
|
||||
fs::remove_file(&files[0].0).unwrap();
|
||||
assert_eq!(get(&store, &name(1)), None);
|
||||
assert!(record_path(scratch.path(), &name(1)).exists());
|
||||
store.write_record_soon(&name(1), record.clone()).unwrap();
|
||||
assert_eq!(get(&store, &name(1)).as_deref(), Some(&record[..]));
|
||||
// Damaged in place, at its length: the next write puts it right.
|
||||
let (path, length) = &files[1];
|
||||
fs::write(path, vec![0u8; *length as usize]).unwrap();
|
||||
store.write_record_soon(&name(1), record.clone()).unwrap();
|
||||
assert_eq!(get(&store, &name(1)).as_deref(), Some(&record[..]));
|
||||
}
|
||||
|
||||
/// The sweep at creation, where no cleanup ran yet: the content records of a retired frame (an
|
||||
/// older version's driver data, `driver::RETIRED`) go, with the chunks no manifest names and a
|
||||
/// dead writer's temporary file; every record a manifest stands for still reads whole.
|
||||
#[test]
|
||||
fn the_sweep_removes_retired_records_and_unnamed_chunks() {
|
||||
let scratch = Scratch::new();
|
||||
let store = store(scratch.path(), BUILD, 1 << 30);
|
||||
// A tree of the version before: whole records, one of them past the chunks' bound.
|
||||
let mut retired = Vec::new();
|
||||
for n in 100..104u32 {
|
||||
let length = if n == 100 { 2 << 20 } else { 4096 };
|
||||
let bytes = [&b"M2VPPLC\0"[..], &noise(u64::from(n), length)].concat();
|
||||
let path = record_path(scratch.path(), &name(n));
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(&path, bytes).unwrap();
|
||||
retired.push(path);
|
||||
}
|
||||
let a = noise(1, 1 << 20);
|
||||
let b = noise(2, 1 << 20);
|
||||
store.write_record_soon(&name(1), a).unwrap();
|
||||
store.write_record_soon(&name(2), b.clone()).unwrap();
|
||||
// The record written again over other bytes: its first chunks are named by no manifest.
|
||||
let again = noise(3, 1 << 20);
|
||||
store.write_record_soon(&name(1), again.clone()).unwrap();
|
||||
let dead = chunk_files(scratch.path())[0]
|
||||
.0
|
||||
.with_file_name(".dead.1.2.3.tmp");
|
||||
fs::write(&dead, b"a writer that died").unwrap();
|
||||
assert_eq!(chunk_bytes(scratch.path()), (3 << 20) + 18);
|
||||
store.sweep(&AtomicBool::new(false));
|
||||
assert!(
|
||||
retired.iter().all(|path| !path.exists()),
|
||||
"a retired record stayed"
|
||||
);
|
||||
assert!(!dead.exists());
|
||||
assert_eq!(chunk_bytes(scratch.path()), 2 << 20);
|
||||
assert!(chunk_dir(scratch.path()).join("state").exists());
|
||||
assert_eq!(get(&store, &name(1)).as_deref(), Some(&again[..]));
|
||||
assert_eq!(get(&store, &name(2)).as_deref(), Some(&b[..]));
|
||||
}
|
||||
|
||||
/// A writer that holds the chunks' lock shared, here in another open file as another process's
|
||||
/// would be, puts the sweep's cleanup off: nothing is removed, and the next sweep, the lock free,
|
||||
/// cleans up.
|
||||
#[test]
|
||||
fn a_writer_holding_the_lock_puts_the_cleanup_off() {
|
||||
let scratch = Scratch::new();
|
||||
let store = store(scratch.path(), BUILD, 1 << 30);
|
||||
store
|
||||
.write_record_soon(&name(1), noise(1, 1 << 20))
|
||||
.unwrap();
|
||||
store
|
||||
.write_record_soon(&name(1), noise(2, 1 << 20))
|
||||
.unwrap();
|
||||
assert_eq!(chunk_bytes(scratch.path()), 2 << 20);
|
||||
let lock = fs::File::open(chunk_dir(scratch.path()).join("lock")).unwrap();
|
||||
lock.lock_shared().unwrap();
|
||||
store.sweep(&AtomicBool::new(false));
|
||||
assert_eq!(chunk_bytes(scratch.path()), 2 << 20);
|
||||
lock.unlock().unwrap();
|
||||
store.sweep(&AtomicBool::new(false));
|
||||
assert_eq!(chunk_bytes(scratch.path()), 1 << 20);
|
||||
}
|
||||
|
||||
/// A writer that meets a cleanup holding the lock, here another open file's exclusive lock,
|
||||
/// writes its record whole rather than wait, and the record reads back.
|
||||
#[test]
|
||||
fn a_writer_meeting_a_cleanup_writes_its_record_whole() {
|
||||
let scratch = Scratch::new();
|
||||
let store = store(scratch.path(), BUILD, 1 << 30);
|
||||
store
|
||||
.write_record_soon(&name(1), noise(1, 1 << 20))
|
||||
.unwrap();
|
||||
let lock = fs::File::open(chunk_dir(scratch.path()).join("lock")).unwrap();
|
||||
lock.lock().unwrap();
|
||||
let record = noise(2, 1 << 20);
|
||||
store.write_record_soon(&name(2), record.clone()).unwrap();
|
||||
lock.unlock().unwrap();
|
||||
assert_eq!(
|
||||
fs::read(record_path(scratch.path(), &name(2))).unwrap(),
|
||||
record
|
||||
);
|
||||
assert_eq!(chunk_bytes(scratch.path()), 1 << 20);
|
||||
assert_eq!(get(&store, &name(2)).as_deref(), Some(&record[..]));
|
||||
}
|
||||
|
||||
/// Set the access and modification times of the file at `path`.
|
||||
fn set_times(path: &Path, when: SystemTime) {
|
||||
let file = fs::File::options().write(true).open(path).unwrap();
|
||||
file.set_times(fs::FileTimes::new().set_accessed(when).set_modified(when))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// The chunks count against the cap: past it, the least recently used record's manifest goes,
|
||||
/// and the chunks only it named with it; the other record stays whole.
|
||||
#[test]
|
||||
fn the_cap_counts_chunks_and_an_evicted_record_takes_its_own() {
|
||||
let scratch = Scratch::new();
|
||||
let store = store(scratch.path(), BUILD, 5 << 19);
|
||||
let a = noise(1, 3 << 19);
|
||||
let b = noise(2, 3 << 19);
|
||||
store.write_record_soon(&name(1), a).unwrap();
|
||||
store.write_record_soon(&name(2), b.clone()).unwrap();
|
||||
let old = SystemTime::now() - Duration::from_secs(3600);
|
||||
set_times(&record_path(scratch.path(), &name(1)), old);
|
||||
store.evict(&AtomicBool::new(false));
|
||||
assert!(!record_path(scratch.path(), &name(1)).exists());
|
||||
assert_eq!(chunk_bytes(scratch.path()), 3 << 19);
|
||||
assert_eq!(get(&store, &name(2)).as_deref(), Some(&b[..]));
|
||||
assert_eq!(store.counters.evictions.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
@@ -72,7 +72,7 @@ struct CacheRun {
|
||||
run: Duration,
|
||||
}
|
||||
|
||||
/// The makings' pipeline cache records (`M2VPPLC\0`, `shader_cache/driver.rs`) under `cache`'s
|
||||
/// The makings' pipeline cache records (`M2VPPL4\0`, `shader_cache/driver.rs`) under `cache`'s
|
||||
/// layout directory, by path, with their bytes (It counted them).
|
||||
fn driver_records(cache: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
|
||||
let mut found = BTreeMap::new();
|
||||
@@ -84,7 +84,7 @@ fn driver_records(cache: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
|
||||
for entry in std::fs::read_dir(group.unwrap().path()).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
if bytes.starts_with(b"M2VPPLC\0") {
|
||||
if bytes.starts_with(b"M2VPPL4\0") {
|
||||
found.insert(path, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ use std::process::Command;
|
||||
/// The render target's side.
|
||||
const SIDE: u64 = 8;
|
||||
/// The magic a making's record begins with (`shader_cache/driver.rs`).
|
||||
const RECORD_MAGIC: &[u8] = b"M2VPPLC\0";
|
||||
const RECORD_MAGIC: &[u8] = b"M2VPPL4\0";
|
||||
/// The environment variable that names the cache directory to [`record_maker_process`].
|
||||
const MAKER_DIR: &str = "M2V_LANE_PIPELINE_RECORDS_DIR";
|
||||
/// The line [`record_maker_process`] reports on.
|
||||
@@ -167,7 +167,7 @@ impl Makings {
|
||||
}
|
||||
}
|
||||
|
||||
/// The records (`M2VPPLC\0`) under `cache`'s layout directory, by their paths under it, with
|
||||
/// The records (`M2VPPL4\0`) under `cache`'s layout directory, by their paths under it, with
|
||||
/// their bytes.
|
||||
fn records(cache: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
|
||||
let mut found = BTreeMap::new();
|
||||
|
||||
@@ -108,6 +108,11 @@ second process does not translate it again. It cannot be turned off.
|
||||
more record names than that makes the rest a cache for the one making, as every making once had.
|
||||
On drivers that report `pipelineBinaryInternalCacheControl` (NVIDIA's), a device the runtime
|
||||
makes turns the driver's own internal cache off; an adopted device keeps what its creator chose.
|
||||
A record of 256 KiB or more is kept as chunks cut by its content, in `chunks` beside the
|
||||
layout's directory, so a run of bytes several records hold is on disk once (NVIDIA's data
|
||||
repeats a 1.85 MB section across records: one node's 8,061 MB of its records are 180 MB so);
|
||||
the chunks count against `capacity`, and the sweep at a device's creation removes those no
|
||||
record names any more, and the records of an older record version.
|
||||
- **Written in the background.** A creation hands its entries to the device's cache thread and
|
||||
does not wait for the directory: the same bytes under the same name, committed by the same
|
||||
rename, after the call returns. An entry still queued answers that device's own lookups, and the
|
||||
|
||||
Reference in new issue
Block a user