extern crate std; use super::*; use std::collections::BTreeMap as Map; #[derive(Clone)] struct Memory(Vec<[u8; BLOCK]>); impl Disk for Memory { fn read(&mut self, block: u32, into: &mut [u8; BLOCK]) { *into = self.0[block as usize]; } fn write(&mut self, block: u32, from: &[u8; BLOCK]) { self.0[block as usize] = *from; } fn blocks(&self) -> u32 { self.0.len() as u32 } } /// A disk whose power goes after `left` writes: every write after that is /// lost, as if the machine stopped there. Counts the writes it was given. /// The code still running reads what it wrote (`seen`), as it would have /// until the moment it stopped; `disk` is what a restart finds. struct Cut { disk: Memory, seen: Memory, left: usize, writes: usize, } impl Cut { fn new(disk: &Memory, left: usize) -> Cut { Cut { disk: disk.clone(), seen: disk.clone(), left, writes: 0, } } } impl Disk for Cut { fn read(&mut self, block: u32, into: &mut [u8; BLOCK]) { self.seen.read(block, into); } fn write(&mut self, block: u32, from: &[u8; BLOCK]) { self.writes += 1; self.seen.write(block, from); if self.left > 0 { self.left -= 1; self.disk.write(block, from); } } fn blocks(&self) -> u32 { self.disk.blocks() } } /// Every file and directory, with its contents (`None` for a directory). fn snapshot(fs: &mut Fs) -> Map>> { let mut out = Map::new(); let mut todo = vec![String::new()]; while let Some(dir) = todo.pop() { for name in fs.list(if dir.is_empty() { "/" } else { &dir }).unwrap() { let path = format!("{dir}/{}", name.trim_end_matches('/')); if name.ends_with('/') { out.insert(path.clone(), None); todo.push(path); } else { out.insert(path.clone(), Some(fs.read(&path).unwrap())); } } } out } fn bytes(n: u32, seed: u8) -> Vec { (0..n) .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)) .collect() } #[test] fn files_and_directories() { let mut fs = format(Memory(vec![[0; BLOCK]; 2048]), "system"); let free = fs.free(); fs.create_dir("/apps/clock").unwrap(); let big = bytes(200_000, 0); fs.write("/apps/clock/program", &big).unwrap(); fs.write("/apps/clock/manifest", b"title=Clock").unwrap(); assert_eq!(fs.read("/apps/clock/program").unwrap(), big); assert_eq!(fs.list("/apps").unwrap(), ["clock/"]); let mut names = fs.list("/apps/clock").unwrap(); names.sort(); assert_eq!(names, ["manifest", "program"]); fs.write("/apps/clock/manifest", b"title=Clock 2").unwrap(); assert_eq!(fs.read("/apps/clock/manifest").unwrap(), b"title=Clock 2"); assert_eq!( fs.check(), Ok(Usage { files: 2, directories: 3, bytes: 200_013 }) ); let disk = fs.disk; let mut fs = Fs::mount(disk).unwrap(); assert_eq!(fs.label, "system"); assert!(!fs.recovered, "a disk cleanly written has nothing to recover"); assert_eq!(fs.read("/apps/clock/program").unwrap(), big); fs.remove_all("/apps").unwrap(); assert_eq!(fs.read("/apps/clock/program"), Err(Error::NotFound)); assert_eq!(fs.free(), free, "removing gave every block back"); fs.check().unwrap(); } /// The steps the power-cut test takes, each one transaction: files with /// and without a block table, replaced larger and smaller, directories /// made and removed. #[derive(Clone, Copy)] enum Step { Dir(&'static str), Write(&'static str, u32, u8), Remove(&'static str), /// `len` bytes written into a file at an offset. WriteAt(&'static str, u64, u32, u8), } const STEPS: &[Step] = &[ Step::Dir("/apps/clock"), Step::Write("/apps/clock/program", 70_000, 1), Step::Write("/apps/clock/manifest", 11, 2), Step::Write("/apps/clock/program", 9_000, 3), Step::Dir("/notes"), Step::Write("/notes/today", 60_000, 4), Step::Remove("/apps/clock/manifest"), Step::Write("/notes/today", 7, 5), // Into the middle of a file, across blocks; then far past its end, // through the table of tables, leaving a hole. Step::WriteAt("/notes/today", 3, 9_000, 6), Step::WriteAt("/notes/today", 6 << 20, 5_000, 7), Step::WriteAt("/notes/today", 4_090, 10, 8), Step::Remove("/apps/clock/program"), Step::Remove("/apps/clock"), Step::Remove("/apps"), // Larger than one transaction frees ([`SHED_BLOCKS`] in a test): // replaced, its old blocks let go of after the change; then removed. Step::Write("/notes/big", 600_000, 9), Step::Write("/notes/big", 300_000, 10), Step::Remove("/notes/big"), ]; fn take(fs: &mut Fs, step: Step) -> Result<(), Error> { match step { Step::Dir(path) => fs.create_dir(path), Step::Write(path, len, seed) => fs.write(path, &bytes(len, seed)), Step::Remove(path) => fs.remove(path), Step::WriteAt(path, offset, len, seed) => fs.write_at(path, offset, &bytes(len, seed)), } } /// The power goes after every possible number of writes, from none to all /// that [`STEPS`] make. Mounted again, the disk always checks whole, holds /// exactly what it held before or after one of the steps, and takes new /// files. #[test] fn a_power_cut_at_any_write() { let empty = format(Memory(vec![[0; BLOCK]; 1024]), "system").disk; let mut fs = Fs::mount(Cut::new(&empty, usize::MAX)).unwrap(); let mut states = vec![snapshot(&mut fs)]; for &step in STEPS { take(&mut fs, step).unwrap(); states.push(snapshot(&mut fs)); } let writes = fs.disk.writes; let mut recovered = 0; for cut in 0..=writes { let mut fs = Fs::mount(Cut::new(&empty, cut)).unwrap(); for &step in STEPS { let _ = take(&mut fs, step); } let mut fs = Fs::mount(fs.disk.disk).unwrap(); recovered += usize::from(fs.recovered); if let Err(problem) = fs.check() { panic!("cut after {cut} of {writes} writes: {problem}"); } let now = snapshot(&mut fs); assert!( states.contains(&now), "cut after {cut} of {writes} writes: a state no step left: {:?}", now.keys().collect::>() ); fs.write("/after", b"still works").unwrap(); assert_eq!(fs.read("/after").unwrap(), b"still works"); fs.check().unwrap(); } assert!(recovered > 0, "no cut fell inside a commit"); } /// A change that cannot be finished changes nothing: the disk fills part /// way through a file, and what was there before is all there is. #[test] fn a_failed_change_leaves_nothing() { let mut fs = format(Memory(vec![[0; BLOCK]; 400]), "small"); fs.write("/keep", &bytes(100_000, 4)).unwrap(); let before = snapshot(&mut fs); let free = fs.free(); assert_eq!(fs.write("/huge", &bytes(2_000_000, 5)), Err(Error::Full)); assert_eq!(fs.write("/keep", &bytes(2_000_000, 6)), Err(Error::Full)); assert_eq!(snapshot(&mut fs), before); assert_eq!(fs.free(), free); fs.check().unwrap(); let mut fs = Fs::mount(fs.disk).unwrap(); assert_eq!(snapshot(&mut fs), before); fs.check().unwrap(); } /// The check finds what a broken disk has wrong. #[test] fn the_check_finds_damage() { let mut fs = format(Memory(vec![[0; BLOCK]; 1024]), "system"); fs.write("/a", &bytes(10_000, 7)).unwrap(); fs.write("/b", &bytes(10_000, 8)).unwrap(); let sb = fs.sb; let mut disk = fs.disk; // A block marked free that a file holds. let mut leaky = disk.clone(); leaky.0[sb.bitmap_start as usize] = [0; BLOCK]; let problem = Fs::mount(leaky).unwrap().check().unwrap_err(); assert!(problem.contains("marked free"), "{problem}"); // Two files sharing a block: /b's first block pointed at /a's. let mut inodes = disk.0[sb.inode_start as usize]; let a = Inode::decode(&inodes[2 * INODE..3 * INODE]).direct[0]; put_u32(&mut inodes[3 * INODE..], 16, a); disk.0[sb.inode_start as usize] = inodes; let problem = Fs::mount(disk).unwrap().check().unwrap_err(); assert!(problem.contains("belongs to something else"), "{problem}"); } /// Ranges written into files and read back against a plain copy of what /// each must hold: inside a block, across blocks, past the end (a hole), /// through the table and the table of tables. #[test] fn ranges_and_holes() { let mut fs = format(Memory(vec![[0; BLOCK]; 2048]), "system"); let free = fs.free(); let mut model: Vec = Vec::new(); let write = |fs: &mut Fs, model: &mut Vec, offset: usize, len: u32, seed: u8| { let data = bytes(len, seed); fs.write_at("/f", offset as u64, &data).unwrap(); if model.len() < offset + data.len() { model.resize(offset + data.len(), 0); } model[offset..offset + data.len()].copy_from_slice(&data); }; write(&mut fs, &mut model, 0, 10_000, 1); write(&mut fs, &mut model, 100, 50, 2); write(&mut fs, &mut model, 4_000, 300, 3); write(&mut fs, &mut model, 30_000, 20, 4); write(&mut fs, &mut model, 100_000, 8_000, 5); write(&mut fs, &mut model, 5 << 20, 4_200, 6); assert_eq!(fs.read("/f").unwrap(), model); for (offset, len) in [ (0, 1), (99, 52), (4_090, 20), (10_000, 30_000), (5 << 20, 1 << 20), ] { let end = (offset + len).min(model.len()); assert_eq!( fs.read_at("/f", offset as u64, len as u64).unwrap(), model[offset..end] ); } assert_eq!(fs.read_at("/f", 1 << 30, 10).unwrap(), b""); assert_eq!(fs.stat("/f").unwrap().size, model.len() as u64); fs.check().unwrap(); // The hole holds nothing: about 6 MiB of file in a few blocks. assert!( free - fs.free() < 20, "{} blocks for a file mostly hole", free - fs.free() ); let mut fs = Fs::mount(fs.disk).unwrap(); assert_eq!(fs.read("/f").unwrap(), model); fs.remove("/f").unwrap(); assert_eq!(fs.free(), free, "removing gave every block back"); fs.check().unwrap(); } /// A file near the largest there can be, almost all of it a hole: bytes /// written in each of its trees and either side of 4 GiB read back, a /// read in the hole is zeros, and the whole disk checks in a moment. #[test] fn a_file_of_four_tebibytes() { let mut fs = format(Memory(vec![[0; BLOCK]; 1024]), "system"); let free = fs.free(); let last = MAX_FILE - 5; const { assert!(MAX_FILE > 4 << 40) }; let places = [ (10, &b"direct"[..]), (100_000, b"one deep"), (100 << 20, b"two deep"), ((4 << 30) - 3, b"across 4 GiB"), (1 << 40, b"three deep"), (last, b"end!!"), ]; for (offset, data) in places { fs.write_at("/big", offset, data).unwrap(); } assert_eq!(fs.stat("/big").unwrap().size, MAX_FILE); let mut fs = Fs::mount(fs.disk).unwrap(); for (offset, data) in places { assert_eq!( fs.read_at("/big", offset, data.len() as u64 + 100).unwrap()[..data.len()], *data ); } assert_eq!(fs.read_at("/big", last, 100).unwrap(), b"end!!"); assert_eq!(fs.read_at("/big", 3 << 30, 4).unwrap(), [0; 4]); assert_eq!(fs.read_at("/big", 3 << 40, 4).unwrap(), [0; 4]); assert_eq!(fs.write_at("/big", MAX_FILE, b"x"), Err(Error::TooLarge)); fs.check().unwrap(); // A few blocks of data, and the tables to them: three to the last. assert!(free - fs.free() < 20, "{} blocks", free - fs.free()); fs.remove("/big").unwrap(); assert_eq!(fs.free(), free); fs.check().unwrap(); } /// A disk that stores only the blocks that are not all zeros, so a test /// can have one of terabytes. #[derive(Clone)] struct Sparse { blocks: u32, stored: BTreeMap>, } impl Sparse { fn new(blocks: u32) -> Sparse { Sparse { blocks, stored: BTreeMap::new(), } } } impl Disk for Sparse { fn read(&mut self, block: u32, into: &mut [u8; BLOCK]) { assert!(block < self.blocks, "block {block} is past the disk"); match self.stored.get(&block) { Some(b) => *into = **b, None => into.fill(0), } } fn write(&mut self, block: u32, from: &[u8; BLOCK]) { assert!(block < self.blocks, "block {block} is past the disk"); if from.iter().all(|&b| b == 0) { self.stored.remove(&block); } else { self.stored.insert(block, Box::new(*from)); } } fn blocks(&self) -> u32 { self.blocks } } /// A file whose blocks are marked in more bitmap blocks than a journal /// holds: one block in each of 80, each 128 MiB of disk from the next. /// Removing it, or writing it anew, could not be one transaction; the /// change is, and the blocks follow in more. #[test] fn letting_go_of_a_file_spread_over_the_disk() { let spread = 80; let mut fs = format(Sparse::new(spread * BITMAP_SPAN + 4096), "wide"); fs.shed_blocks = 1 << 16; let free = fs.free(); let start = fs.sb.data_start; let write_spread = |fs: &mut Fs, seed: u8| { for i in 0..spread { fs.next_free = start + i * BITMAP_SPAN; fs.write_at("/wide", u64::from(i) * BLOCK as u64, &[seed; BLOCK]) .unwrap(); } }; write_spread(&mut fs, 1); fs.check().unwrap(); let used = free - fs.free(); assert!(used >= spread, "{used}"); // Written anew, small: the old blocks go to a dying inode, which is // gone again by the time the write returns. fs.write("/wide", b"small now").unwrap(); assert_eq!(fs.read("/wide").unwrap(), b"small now"); assert_eq!(fs.dying(), 0); // Its one block, and the root directory's. assert_eq!(free - fs.free(), 2); fs.check().unwrap(); write_spread(&mut fs, 2); fs.remove("/wide").unwrap(); assert_eq!(fs.read("/wide"), Err(Error::NotFound)); assert_eq!(fs.free(), free, "removing gave every block back"); fs.check().unwrap(); } /// A power cut while a file is let go of leaves a dying inode, which the /// check counts as held, and the next mount frees. #[test] fn a_dying_file_is_finished_at_mount() { let mut fs = format(Memory(vec![[0; BLOCK]; 1024]), "system"); let free = fs.free(); fs.write("/a", &bytes(400_000, 3)).unwrap(); let disk = fs.disk.clone(); // Every write after the first transaction of the removal is lost. let mut probe = Fs::mount(Cut::new(&disk, usize::MAX)).unwrap(); let before = probe.disk.writes; probe.remove("/a").unwrap(); let mut first = None; for cut in 1..probe.disk.writes - before { let mut fs = Fs::mount(Cut::new(&disk, cut)).unwrap(); fs.remove("/a").unwrap(); let mut raw = Fs::new(fs.disk.disk.clone(), fs.sb, String::new(), false); raw.load_bitmap(); if raw.dying() != 0 && first.is_none() { first = Some(fs.disk.disk.clone()); } } let disk = first.expect("a cut that leaves a dying inode"); let mut raw = Fs::new(disk.clone(), fs.sb, String::new(), false); raw.load_bitmap(); assert!(raw.free() < free, "the dying file still holds its blocks"); raw.check().unwrap(); assert_eq!(raw.read("/a"), Err(Error::NotFound)); let mut fs = Fs::mount(disk).unwrap(); assert_eq!(fs.dying(), 0); assert_eq!(fs.free(), free); fs.check().unwrap(); } /// A disk made before files past 4 GiB mounts, and is marked as one this /// code wrote. #[test] fn a_pfs2_disk_mounts() { let mut fs = format(Memory(vec![[0; BLOCK]; 512]), "old"); fs.write("/kept", b"from before").unwrap(); let mut disk = fs.disk; disk.0[0][..4].copy_from_slice(b"PFS2"); let mut fs = Fs::mount(disk).unwrap(); assert_eq!(fs.read("/kept").unwrap(), b"from before"); fs.check().unwrap(); assert_eq!(&fs.disk.0[0][..4], b"PFS3"); } /// How long writing a large file takes, a range at a time as programs /// write: taking each block costs the same however full the disk is. /// `cargo test -p pinnacle-fs --release -- --ignored --nocapture`. #[test] #[ignore = "writes 9 GiB to a sparse disk: a minute in a debug build"] fn writing_and_removing_nine_gibibytes() { let size: u64 = 9 << 30; let blocks = (size / BLOCK as u64) as u32; let mut fs = format(Sparse::new(blocks + blocks / 16 + 8192), "big"); fs.shed_blocks = 1 << 16; let free = fs.free(); let piece = vec![0u8; 16 << 20]; let started = std::time::Instant::now(); for i in 0..size / piece.len() as u64 { fs.write_at("/big", i * piece.len() as u64, &piece).unwrap(); } let written = started.elapsed(); assert_eq!(fs.stat("/big").unwrap().size, size); let started = std::time::Instant::now(); fs.check().unwrap(); let checked = started.elapsed(); let started = std::time::Instant::now(); fs.remove("/big").unwrap(); let removed = started.elapsed(); assert_eq!(fs.free(), free); fs.check().unwrap(); std::println!("9 GiB: written in {written:?}, checked in {checked:?}, removed in {removed:?}"); } static NOW: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0); /// A change stamps the file with the clock's time; a read does not. #[test] fn times_of_change() { let mut fs = format(Memory(vec![[0; BLOCK]; 512]), "system"); fs.set_clock(|| NOW.load(core::sync::atomic::Ordering::Relaxed)); NOW.store(1_000, core::sync::atomic::Ordering::Relaxed); fs.write("/a", b"one").unwrap(); NOW.store(2_000, core::sync::atomic::Ordering::Relaxed); fs.read("/a").unwrap(); assert_eq!(fs.stat("/a").unwrap().modified, 1_000); fs.write_at("/a", 1, b"x").unwrap(); assert_eq!( fs.stat("/a").unwrap(), Stat { kind: Kind::File, size: 3, modified: 2_000 } ); assert_eq!(fs.stat("/").unwrap().kind, Kind::Directory); } /// A file system in a vault: what was written reads back through the /// passphrase, and nothing of it is on the disk in the clear. #[test] fn a_vault_keeps_files_unreadable_without_its_passphrase() { use crate::vault::{Error as VaultError, Vault, is_vault}; let disk = Memory(vec![[0; BLOCK]; 512]); let vault = Vault::create(disk, "correct horse battery", [1; 16], [2; 32]); let mut fs = format(vault, "data"); let secret = b"the plans for the lighthouse, page one".repeat(200); fs.create_dir("/notes").unwrap(); fs.write("/notes/plans", &secret).unwrap(); fs.check().unwrap(); let mut raw = fs.disk.into_inner(); assert!(is_vault(&mut raw)); let stored: Vec = raw.0.iter().flatten().copied().collect(); assert!( !stored.windows(14).any(|w| w == b"the lighthouse"), "the file is on the disk in the clear" ); assert!( !stored.windows(4).any(|w| w == b"PFS2"), "the file system's own marks show" ); let raw = match Vault::open(raw, "wrong horse battery") { Err((raw, error)) => { assert_eq!(error, VaultError::WrongPassphrase); raw } Ok(_) => panic!("a wrong passphrase opened the vault"), }; let mut vault = Vault::open(raw, "correct horse battery") .unwrap_or_else(|_| panic!("the passphrase did not open it")); // A new passphrase, and a key as hardware would hold it beside it. vault .change_passphrase("correct horse battery", "a new one, longer", [3; 16]) .unwrap(); vault.add_hardware_key(&[9; 32]).unwrap(); let raw = vault.into_inner(); let raw = Vault::open(raw, "correct horse battery") .err() .expect("the old passphrase still opened it") .0; let vault = Vault::open_with_key(raw, &[9; 32]).unwrap_or_else(|_| panic!("the hardware key did not open it")); let raw = vault.into_inner(); let vault = Vault::open(raw, "a new one, longer") .unwrap_or_else(|_| panic!("the new passphrase did not open it")); let mut fs = Fs::mount(vault).unwrap(); assert_eq!(fs.read("/notes/plans").unwrap(), secret); fs.check().unwrap(); } /// The cipher works on a block as a whole: one byte changed changes /// nearly every byte stored, and the same contents at another block are /// stored differently. #[test] fn a_vault_block_changes_as_a_whole() { use crate::vault::Vault; let mut vault = Vault::create(Memory(vec![[0; BLOCK]; 8]), "passphrase", [4; 16], [5; 32]); let mut block = [7u8; BLOCK]; vault.write(0, &block); block[2000] ^= 1; vault.write(1, &block); vault.write(2, &block); let raw = vault.into_inner(); let differ = |a: &[u8; BLOCK], b: &[u8; BLOCK]| a.iter().zip(b).filter(|(x, y)| x != y).count(); assert!( differ(&raw.0[1], &raw.0[2]) > BLOCK * 9 / 10, "one byte changed only part of the block" ); assert!( differ(&raw.0[2], &raw.0[3]) > BLOCK * 9 / 10, "the same contents look alike at two blocks" ); }