garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /pfs/src/lib.rs

raw

//! Pinnacle's file system over 4 KiB blocks: files read and written whole or
//! a range at a time, which a power cut at any moment leaves as they were
//! before or after.
//!
//! The layout: block 0 is the superblock; then a bitmap of used blocks;
//! then the inodes, 128 bytes each (a kind, a size, the time it last
//! changed, and where its blocks are: twelve direct, then three trees of
//! block tables, one, two and three tables deep, for files up to 4 TiB);
//! then the journal, [`JOURNAL`] blocks; then data. Block number 0 in a
//! file is a hole, read as zeros and taking no room: a file written at an
//! offset past its end has one, and a table that would hold only holes is
//! not there at all. A directory's data is 64-byte entries (inode, kind,
//! name); an entry of inode 0 is a free slot. Inode 1 is the root; inode 0
//! is no file, and its record names the first inode being let go (below).
//! The superblock carries a label, which is how the kernel tells its disks
//! apart.
//!
//! **Power cuts.** Every change (a file written, a directory made, one
//! removed) is a transaction. Contents, of files and of directories, and
//! the block tables never overwrite a block in use: they go to free blocks
//! (a block the transaction itself took is changed in place), and the
//! blocks they replace are freed only once the transaction commits. What does change in
//! place, the inode table and the bitmap, is gathered in memory and goes
//! through the journal: copies of those blocks are written to it, then its
//! header, which commits them, then the blocks to their places, then the
//! header is cleared. Mounting a disk whose journal holds a whole
//! transaction writes it again ([`Fs::recovered`]); a torn one, whose
//! checksum does not match, never committed, and nothing points at what it
//! wrote. [`Disk::flush`] keeps each step behind the one before. A change
//! that fails (the disk is full) leaves nothing behind. [`Fs::check`] proves
//! the result whole.
//!
//! **Letting go of a large file.** Freeing a block changes its bitmap
//! block, one per 128 MiB of disk, and the journal holds a few dozen: a
//! file of gigabytes cannot be freed in one transaction. Removing or
//! replacing one frees what fits; the rest moves, in the same transaction,
//! to an inode of its own that no directory names, *dying*, on a list that
//! starts in inode 0's record. Transactions of their own then free it from
//! its end down, each leaving it whole and a little shorter, until it is
//! gone: the change is done when the first commits, and the space follows.
//! A power cut part way leaves the list, which mounting finishes.
//!
//! The kernel and the host tools use the same code, over [`Disk`].

#![no_std]

extern crate alloc;

use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::format;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;

pub const BLOCK: usize = 4096;
/// The superblock's mark. `PFS2` is the same layout without three-deep
/// trees or dying inodes; a disk so marked mounts, and is marked again.
const MAGIC: &[u8; 4] = b"PFS3";
const MAGIC_2: &[u8; 4] = b"PFS2";
const JOURNAL_MAGIC: &[u8; 4] = b"PFSJ";
/// The journal's blocks: its header, and room for as many blocks as one
/// transaction changes in place (a few inode-table and bitmap blocks).
pub const JOURNAL: u32 = 64;
const INODE: usize = 128;
const INODES_PER_BLOCK: usize = BLOCK / INODE;
const DIRECT: usize = 12;
/// Block numbers in a table block.
const POINTERS: u64 = (BLOCK / 4) as u64;
/// The trees of tables an inode has: one, two and three tables deep.
const TREES: usize = 3;
/// A file's blocks at most: direct, then through each tree.
const MAX_BLOCKS: u64 = DIRECT as u64 + POINTERS + POINTERS * POINTERS + POINTERS * POINTERS * POINTERS;
pub const MAX_FILE: u64 = MAX_BLOCKS * BLOCK as u64;
const ENTRY: usize = 64;
const NAME_MAX: usize = ENTRY - 6;
const ROOT: u32 = 1;
/// An inode's kind while it is let go, on the list inode 0 starts.
const DYING: u8 = 3;
/// Blocks a bitmap block marks.
const BITMAP_SPAN: u32 = BLOCK as u32 * 8;
/// Bitmap blocks freeing may change in one transaction: half the journal,
/// the rest left for the inode table and what else the transaction does.
const SHED_BITMAP: usize = 32;
/// Blocks one transaction frees of a file at most: 256 MiB, a list of a
/// quarter MiB in memory. The tests take a few, so that letting go of a
/// small file takes several transactions.
const SHED_BLOCKS: usize = if cfg!(test) { 40 } else { 1 << 16 };

/// Blocks a tree's table `depth` levels above the data spans.
const fn span(depth: u32) -> u64 {
    POINTERS.pow(depth)
}

/// A file's first block numbered through tree `k`.
const fn tree_start(k: usize) -> u64 {
    let mut start = DIRECT as u64;
    let mut i = 0;
    while i < k {
        start += span(i as u32 + 1);
        i += 1;
    }
    start
}

/// Where a file's block `i` is numbered.
enum Route {
    Direct(usize),
    /// In tree `k` (`k + 1` tables deep), its `j`th block.
    Tree(usize, u64),
}

fn route(i: u64) -> Route {
    if i < DIRECT as u64 {
        return Route::Direct(i as usize);
    }
    let mut j = i - DIRECT as u64;
    for k in 0..TREES {
        if j < span(k as u32 + 1) {
            return Route::Tree(k, j);
        }
        j -= span(k as u32 + 1);
    }
    unreachable!("a block past the largest file")
}

/// The slot block `j` of a tree has in its table `level` levels above
/// the data (0: the table that numbers the block itself).
fn slot(j: u64, level: u32) -> usize {
    ((j / span(level)) % POINTERS) as usize
}

/// Blocks a file of `size` bytes spans.
fn blocks_of(size: u64) -> u64 {
    size.div_ceil(BLOCK as u64)
}

/// Something with numbered 4 KiB blocks.
pub trait Disk {
    fn read(&mut self, block: u32, into: &mut [u8; BLOCK]);
    fn write(&mut self, block: u32, from: &[u8; BLOCK]);
    fn blocks(&self) -> u32;
    /// Returns once every write before it is on the medium, not only in a
    /// cache on the way. A disk that writes through needs nothing.
    fn flush(&mut self) {}
    /// Reads several blocks: `into[i]` gets block `blocks[i]`. A disk that
    /// can have requests in flight together does better than one at a time.
    fn read_many(&mut self, blocks: &[u32], into: &mut [[u8; BLOCK]]) {
        for (block, buffer) in blocks.iter().zip(into) {
            self.read(*block, buffer);
        }
    }
    /// Writes several blocks: block `blocks[i]` gets `from[i]`.
    fn write_many(&mut self, blocks: &[u32], from: &[[u8; BLOCK]]) {
        for (block, buffer) in blocks.iter().zip(from) {
            self.write(*block, buffer);
        }
    }
}

/// Blocks a range is read or written in one go: 128 KiB in memory at most.
const BATCH: usize = 32;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Error {
    NotFound,
    NotADirectory,
    IsADirectory,
    Exists,
    Full,
    TooLarge,
    BadName,
    NotEmpty,
    NotPfs,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Kind {
    File = 1,
    Directory = 2,
}

#[derive(Clone, Copy)]
struct Super {
    blocks: u32,
    inodes: u32,
    bitmap_start: u32,
    bitmap_blocks: u32,
    inode_start: u32,
    journal_start: u32,
    data_start: u32,
}

#[derive(Clone)]
struct Inode {
    kind: u8,
    /// A dying inode's next on the list, or 0.
    next: u32,
    size: u64,
    direct: [u32; DIRECT],
    /// Its trees' top tables, or 0.
    trees: [u32; TREES],
    /// When it last changed, by the file system's clock.
    modified: u64,
}

/// Where in an inode's record each tree's top table is.
const TREE_AT: [usize; TREES] = [64, 68, 80];

impl Inode {
    fn empty(kind: Kind) -> Inode {
        Inode {
            kind: kind as u8,
            next: 0,
            size: 0,
            direct: [0; DIRECT],
            trees: [0; TREES],
            modified: 0,
        }
    }

    fn unused() -> Inode {
        Inode {
            kind: 0,
            ..Inode::empty(Kind::File)
        }
    }

    fn decode(r: &[u8]) -> Inode {
        let mut direct = [0; DIRECT];
        for (i, d) in direct.iter_mut().enumerate() {
            *d = u32_at(r, 16 + i * 4);
        }
        Inode {
            kind: r[0],
            next: u32_at(r, 4),
            size: u64::from_le_bytes(r[8..16].try_into().unwrap()),
            direct,
            trees: TREE_AT.map(|at| u32_at(r, at)),
            modified: u64::from_le_bytes(r[72..80].try_into().unwrap()),
        }
    }

    fn encode(&self, r: &mut [u8]) {
        r.fill(0);
        r[0] = self.kind;
        put_u32(r, 4, self.next);
        r[8..16].copy_from_slice(&self.size.to_le_bytes());
        for (i, d) in self.direct.iter().enumerate() {
            put_u32(r, 16 + i * 4, *d);
        }
        for (at, tree) in TREE_AT.into_iter().zip(self.trees) {
            put_u32(r, at, tree);
        }
        r[72..80].copy_from_slice(&self.modified.to_le_bytes());
    }

    /// Holds no blocks.
    fn clear(&mut self) {
        self.size = 0;
        self.direct = [0; DIRECT];
        self.trees = [0; TREES];
    }
}

/// What [`Fs::stat`] says of a file or directory.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Stat {
    pub kind: Kind,
    /// Bytes, holes counted.
    pub size: u64,
    /// When it last changed, by the clock [`Fs::set_clock`] gave.
    pub modified: u64,
}

/// What [`Fs::check`] found on a whole file system.
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
pub struct Usage {
    pub files: u32,
    pub directories: u32,
    /// Bytes in files.
    pub bytes: u64,
}

fn u32_at(b: &[u8], at: usize) -> u32 {
    u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
}

fn put_u32(b: &mut [u8], at: usize, v: u32) {
    b[at..at + 4].copy_from_slice(&v.to_le_bytes());
}

/// CRC-32 (IEEE), the journal's checksum: it tells a whole transaction
/// from one a power cut tore.
const CRC: [u32; 256] = {
    let mut table = [0u32; 256];
    let mut i = 0;
    while i < 256 {
        let mut c = i as u32;
        let mut k = 0;
        while k < 8 {
            c = if c & 1 != 0 {
                0xedb8_8320 ^ (c >> 1)
            } else {
                c >> 1
            };
            k += 1;
        }
        table[i] = c;
        i += 1;
    }
    table
};

fn crc(mut state: u32, bytes: &[u8]) -> u32 {
    for &b in bytes {
        state = CRC[((state ^ u32::from(b)) & 0xff) as usize] ^ (state >> 8);
    }
    state
}

/// A zeroed block, on the heap: a kernel stack (16 KiB) holds few blocks,
/// and a write nests several.
fn zeroed() -> Box<[u8; BLOCK]> {
    vec![0u8; BLOCK].into_boxed_slice().try_into().unwrap()
}

/// What one transaction may still free: blocks, and the bitmap blocks they
/// are marked in, so that the bitmap's changes fit in the journal.
struct Budget {
    blocks: usize,
    bitmap: BTreeSet<u32>,
}

impl Budget {
    /// Whether block `b` may be freed too; counts it when it may.
    fn take(&mut self, b: u32) -> bool {
        let marked_in = b / BITMAP_SPAN;
        if self.blocks == 0 || !self.bitmap.contains(&marked_in) && self.bitmap.len() >= SHED_BITMAP {
            return false;
        }
        self.bitmap.insert(marked_in);
        self.blocks -= 1;
        true
    }
}

/// A mounted file system.
pub struct Fs<D: Disk> {
    disk: D,
    sb: Super,
    pub label: String,
    /// Whether mounting it finished a transaction a power cut interrupted.
    pub recovered: bool,
    /// The used-block bitmap, as the transaction in progress sees it.
    bitmap: Vec<u8>,
    /// Free blocks in the bitmap as the transaction in progress sees it.
    free: u32,
    /// Where the search for a free block starts: past the one taken last,
    /// so a file written in one go lies in a run, and taking a block costs
    /// the same on a full disk as on an empty one.
    next_free: u32,
    /// The transaction in progress: the inode-table blocks it changed.
    changed: BTreeMap<u32, Box<[u8; BLOCK]>>,
    /// The bitmap's blocks it changed, counted from the bitmap's first.
    bitmap_changed: BTreeSet<u32>,
    /// Blocks it no longer uses: what is on the disk still points at them
    /// until it commits, so they are freed only then.
    freed: Vec<u32>,
    /// Blocks it took: nothing on the disk points at them yet, so it may
    /// change them in place.
    fresh: BTreeSet<u32>,
    /// The block tables it changed, all fresh: written before it commits.
    tables: BTreeMap<u32, Box<[u8; BLOCK]>>,
    /// The table blocks read last (one of each level a lookup through the
    /// deepest tree reads, and one more), the older first.
    cached: Vec<(u32, Box<[u8; BLOCK]>)>,
    /// Names looked up: (directory, name) → what it names, for each
    /// directory in `listed`, which holds every name of them. Emptied by
    /// any change to a directory and at every commit and abort (an inode
    /// freed may be taken again). A lookup read each directory on its path
    /// in full: Cartopolis's file calls spent 13 ms each that way, behind
    /// one lock per disk.
    names: BTreeMap<(u32, String), (u32, Kind)>,
    listed: BTreeSet<u32>,
    /// Blocks one transaction frees of a file at most ([`SHED_BLOCKS`]).
    shed_blocks: usize,
    /// What stamps a change's time ([`Stat::modified`]).
    clock: fn() -> u64,
}

/// Table blocks [`Fs::cached`] keeps.
const CACHED: usize = TREES + 1;
/// Names [`Fs::names`] keeps at most before it starts again.
const NAMES_KEPT: usize = 65_536;

/// Makes an empty file system with `label` on `disk`.
pub fn format<D: Disk>(mut disk: D, label: &str) -> Fs<D> {
    let blocks = disk.blocks();
    let inodes = (blocks / 4).clamp(64, 16384);
    let bitmap_blocks = (blocks as usize).div_ceil(BLOCK * 8) as u32;
    let inode_blocks = (inodes as usize).div_ceil(INODES_PER_BLOCK) as u32;
    let journal_start = 1 + bitmap_blocks + inode_blocks;
    let sb = Super {
        blocks,
        inodes,
        bitmap_start: 1,
        bitmap_blocks,
        inode_start: 1 + bitmap_blocks,
        journal_start,
        data_start: journal_start + JOURNAL,
    };
    assert!(sb.data_start < blocks, "a disk too small for a file system");
    let zero = zeroed();
    for block in 0..sb.data_start {
        disk.write(block, &zero);
    }
    let mut bitmap = vec![0u8; bitmap_blocks as usize * BLOCK];
    for b in 0..sb.data_start {
        bitmap[b as usize / 8] |= 1 << (b % 8);
    }
    for i in 0..bitmap_blocks as usize {
        let block: &[u8; BLOCK] = bitmap[i * BLOCK..(i + 1) * BLOCK].try_into().unwrap();
        disk.write(sb.bitmap_start + i as u32, block);
    }
    let mut block = zeroed();
    block[..4].copy_from_slice(MAGIC);
    let name = label.as_bytes();
    let n = name.len().min(16);
    block[4..4 + n].copy_from_slice(&name[..n]);
    for (i, v) in [
        sb.blocks,
        sb.inodes,
        sb.bitmap_start,
        sb.bitmap_blocks,
        sb.inode_start,
        sb.journal_start,
        sb.data_start,
    ]
    .into_iter()
    .enumerate()
    {
        put_u32(&mut block[..], 20 + i * 4, v);
    }
    // The superblock last: until it is written there is no file system.
    disk.flush();
    disk.write(0, &block);
    let mut fs = Fs::new(disk, sb, label.into(), false);
    fs.bitmap = bitmap;
    fs.free = sb.blocks - sb.data_start;
    fs.transaction(|fs| {
        fs.write_inode(ROOT, &Inode::empty(Kind::Directory));
        Ok(())
    })
    .expect("a new file system has room for its root");
    fs
}

/// Writes the transaction the journal holds to its places again, when it is
/// whole. Returns whether there was one.
fn replay<D: Disk>(disk: &mut D, sb: &Super) -> bool {
    let mut header = zeroed();
    disk.read(sb.journal_start, &mut header);
    if &header[..4] != JOURNAL_MAGIC {
        return false;
    }
    let count = u32_at(&header[..], 4);
    if count == 0 || count >= JOURNAL {
        return false;
    }
    let homes: Vec<u32> = (0..count as usize)
        .map(|i| u32_at(&header[..], 12 + i * 4))
        .collect();
    // Only the inode table and the bitmap ever go through the journal.
    if homes
        .iter()
        .any(|&h| h < sb.bitmap_start || h >= sb.journal_start)
    {
        return false;
    }
    let mut sum = crc(!0, &header[4..8]);
    sum = crc(sum, &header[12..12 + count as usize * 4]);
    let mut copies = Vec::with_capacity(count as usize);
    for i in 0..count {
        let mut copy = zeroed();
        disk.read(sb.journal_start + 1 + i, &mut copy);
        sum = crc(sum, &copy[..]);
        copies.push(copy);
    }
    if !sum != u32_at(&header[..], 8) {
        return false;
    }
    for (&home, copy) in homes.iter().zip(&copies) {
        disk.write(home, copy);
    }
    disk.flush();
    disk.write(sb.journal_start, &[0; BLOCK]);
    disk.flush();
    true
}

impl<D: Disk> Fs<D> {
    fn new(disk: D, sb: Super, label: String, recovered: bool) -> Fs<D> {
        Fs {
            disk,
            sb,
            label,
            recovered,
            bitmap: Vec::new(),
            free: 0,
            next_free: sb.data_start,
            changed: BTreeMap::new(),
            bitmap_changed: BTreeSet::new(),
            freed: Vec::new(),
            fresh: BTreeSet::new(),
            tables: BTreeMap::new(),
            cached: Vec::new(),
            names: BTreeMap::new(),
            listed: BTreeSet::new(),
            shed_blocks: SHED_BLOCKS,
            clock: || 0,
        }
    }

    /// The disk it is on, to reach what is beneath the file system (a
    /// vault's header).
    pub fn disk_mut(&mut self) -> &mut D {
        &mut self.disk
    }

    /// The disk it is on, the file system given up.
    pub fn into_disk(self) -> D {
        self.disk
    }

    /// What stamps each change's time from now on: seconds since 1970 on
    /// a device with a clock. Without one, every time is 0.
    pub fn set_clock(&mut self, clock: fn() -> u64) {
        self.clock = clock;
    }

    /// Mounts the file system on `disk`: finishes the transaction a power
    /// cut interrupted, and frees what was still being let go.
    pub fn mount(mut disk: D) -> Result<Fs<D>, Error> {
        let mut block = zeroed();
        disk.read(0, &mut block);
        let old = &block[..4] == MAGIC_2;
        if &block[..4] != MAGIC && !old {
            return Err(Error::NotPfs);
        }
        let label_len = block[4..20].iter().position(|&b| b == 0).unwrap_or(16);
        let label = String::from_utf8_lossy(&block[4..4 + label_len]).into();
        let v = |i: usize| u32_at(&block[..], 20 + i * 4);
        let sb = Super {
            blocks: v(0),
            inodes: v(1),
            bitmap_start: v(2),
            bitmap_blocks: v(3),
            inode_start: v(4),
            journal_start: v(5),
            data_start: v(6),
        };
        if sb.blocks > disk.blocks()
            || sb.data_start >= sb.blocks
            || sb.journal_start + JOURNAL != sb.data_start
        {
            return Err(Error::NotPfs);
        }
        let recovered = replay(&mut disk, &sb);
        if old {
            // What this code writes, an older one would misread: a file
            // past 4 GiB, a dying inode. One block, so a cut leaves either.
            block[..4].copy_from_slice(MAGIC);
            disk.write(0, &block);
            disk.flush();
        }
        let mut fs = Fs::new(disk, sb, label, recovered);
        fs.load_bitmap();
        fs.settle()?;
        Ok(fs)
    }

    fn load_bitmap(&mut self) {
        let mut bitmap = vec![0u8; self.sb.bitmap_blocks as usize * BLOCK];
        for (i, chunk) in bitmap.as_chunks_mut::<BLOCK>().0.iter_mut().enumerate() {
            self.disk.read(self.sb.bitmap_start + i as u32, chunk);
        }
        let blocks = self.sb.blocks as usize;
        let mut used: u32 = bitmap[..blocks / 8].iter().map(|b| b.count_ones()).sum();
        if !blocks.is_multiple_of(8) {
            used += (bitmap[blocks / 8] & ((1 << (blocks % 8)) - 1)).count_ones();
        }
        self.free = self.sb.blocks - used;
        self.bitmap = bitmap;
    }

    /// Runs `change` as one transaction: committed when it succeeds, and
    /// undone, as if it never ran, when it fails.
    fn transaction<R>(&mut self, change: impl FnOnce(&mut Self) -> Result<R, Error>) -> Result<R, Error> {
        match change(self) {
            Ok(r) => self.commit().map(|()| r),
            Err(e) => {
                self.abort();
                Err(e)
            }
        }
    }

    /// Forgets the transaction in progress. What it wrote to free blocks
    /// stays there, pointed at by nothing.
    fn abort(&mut self) {
        self.forget_names();
        self.changed.clear();
        self.bitmap_changed.clear();
        self.freed.clear();
        self.fresh.clear();
        self.tables.clear();
        self.cached.clear();
        // The bitmap on the disk is the last committed one.
        self.load_bitmap();
    }

    fn commit(&mut self) -> Result<(), Error> {
        self.forget_names();
        // Fresh blocks, which nothing on the disk points at yet: written now,
        // before the flush that orders them ahead of the commit.
        for (block, table) in core::mem::take(&mut self.tables) {
            self.disk.write(block, &table);
        }
        self.fresh.clear();
        // A freed table block may be taken again, for something else.
        self.cached.clear();
        for b in core::mem::take(&mut self.freed) {
            let byte = &mut self.bitmap[b as usize / 8];
            if *byte & (1 << (b % 8)) != 0 {
                *byte &= !(1 << (b % 8));
                self.free += 1;
            }
            self.bitmap_changed.insert(b / BITMAP_SPAN);
        }
        for i in core::mem::take(&mut self.bitmap_changed) {
            let at = i as usize * BLOCK;
            let mut block = zeroed();
            block.copy_from_slice(&self.bitmap[at..at + BLOCK]);
            self.changed.insert(self.sb.bitmap_start + i, block);
        }
        if self.changed.is_empty() {
            return Ok(());
        }
        if self.changed.len() >= JOURNAL as usize {
            self.abort();
            return Err(Error::TooLarge);
        }
        let changed = core::mem::take(&mut self.changed);
        let start = self.sb.journal_start;
        // What the transaction wrote to free blocks is on the disk before
        // anything that points at it can be.
        self.disk.flush();
        let mut header = zeroed();
        header[..4].copy_from_slice(JOURNAL_MAGIC);
        put_u32(&mut header[..], 4, changed.len() as u32);
        for (i, (&home, copy)) in changed.iter().enumerate() {
            put_u32(&mut header[..], 12 + i * 4, home);
            self.disk.write(start + 1 + i as u32, copy);
        }
        let mut sum = crc(!0, &header[4..8]);
        sum = crc(sum, &header[12..12 + changed.len() * 4]);
        for copy in changed.values() {
            sum = crc(sum, &copy[..]);
        }
        put_u32(&mut header[..], 8, !sum);
        self.disk.flush();
        // The commit: from here on the transaction happened.
        self.disk.write(start, &header);
        self.disk.flush();
        for (&home, copy) in &changed {
            self.disk.write(home, copy);
        }
        self.disk.flush();
        // Replaying it again would change nothing; clearing it saves the
        // next mount the work. The next commit's first flush orders this.
        self.disk.write(start, &[0; BLOCK]);
        Ok(())
    }

    /// A block of the inode table, as the transaction in progress sees it.
    fn read_meta(&mut self, block: u32) -> Box<[u8; BLOCK]> {
        if let Some(changed) = self.changed.get(&block) {
            return changed.clone();
        }
        let mut b = zeroed();
        self.disk.read(block, &mut b);
        b
    }

    /// A free block, taken: the first from [`Fs::next_free`] on, round to
    /// the start of the data once.
    fn allocate(&mut self) -> Result<u32, Error> {
        if self.free == 0 {
            return Err(Error::Full);
        }
        let (start, end) = (self.sb.data_start, self.sb.blocks);
        let from = self.next_free.clamp(start, end - 1);
        for (mut b, stop) in [(from, end), (start, from)] {
            while b < stop {
                let byte = self.bitmap[b as usize / 8];
                // Eight used at once: past the bitmap's end they are not
                // marked, so a byte there is never skipped whole.
                if byte == 0xff && b.is_multiple_of(8) {
                    b += 8;
                    continue;
                }
                if byte & (1 << (b % 8)) == 0 {
                    self.bitmap[b as usize / 8] |= 1 << (b % 8);
                    self.bitmap_changed.insert(b / BITMAP_SPAN);
                    self.fresh.insert(b);
                    self.free -= 1;
                    self.next_free = b + 1;
                    return Ok(b);
                }
                b += 1;
            }
        }
        Err(Error::Full)
    }

    fn release(&mut self, b: u32) {
        self.freed.push(b);
    }

    /// Blocks for files and directories, used or free.
    pub fn capacity(&self) -> u32 {
        self.sb.blocks - self.sb.data_start
    }

    /// Free blocks.
    pub fn free(&self) -> u32 {
        self.free
    }

    fn inode_place(&self, n: u32) -> (u32, usize) {
        (
            self.sb.inode_start + n / INODES_PER_BLOCK as u32,
            (n as usize % INODES_PER_BLOCK) * INODE,
        )
    }

    fn read_inode(&mut self, n: u32) -> Inode {
        let (block, at) = self.inode_place(n);
        let b = self.read_meta(block);
        Inode::decode(&b[at..at + INODE])
    }

    fn write_inode(&mut self, n: u32, inode: &Inode) {
        let (block, at) = self.inode_place(n);
        let mut b = self.read_meta(block);
        inode.encode(&mut b[at..at + INODE]);
        self.changed.insert(block, b);
    }

    /// A free inode, taken for `kind`: its table read a block at a time.
    fn claim_inode(&mut self, kind: u8) -> Result<u32, Error> {
        for first in (0..self.sb.inodes).step_by(INODES_PER_BLOCK) {
            let block = self.read_meta(self.inode_place(first).0);
            let found = (0..INODES_PER_BLOCK as u32)
                .map(|i| first + i)
                .find(|&n| n > ROOT && n < self.sb.inodes && block[self.inode_place(n).1] == 0);
            if let Some(n) = found {
                let inode = Inode {
                    kind,
                    modified: (self.clock)(),
                    ..Inode::unused()
                };
                self.write_inode(n, &inode);
                return Ok(n);
            }
        }
        Err(Error::Full)
    }

    /// The first dying inode, or 0: kept in inode 0's record.
    fn dying(&mut self) -> u32 {
        let block = self.read_meta(self.sb.inode_start);
        u32_at(&block[..], 4)
    }

    fn set_dying(&mut self, n: u32) {
        let mut block = self.read_meta(self.sb.inode_start);
        put_u32(&mut block[..], 4, n);
        self.changed.insert(self.sb.inode_start, block);
    }

    /// Slot `slot` of table block `table` (0, a table not there: 0).
    fn entry(&mut self, table: u32, slot: usize) -> u32 {
        if table == 0 {
            return 0;
        }
        if let Some(changed) = self.tables.get(&table) {
            return u32_at(&changed[..], slot * 4);
        }
        if let Some((_, block)) = self.cached.iter().find(|(b, _)| *b == table) {
            return u32_at(&block[..], slot * 4);
        }
        let mut block = zeroed();
        self.disk.read(table, &mut block);
        let value = u32_at(&block[..], slot * 4);
        if self.cached.len() == CACHED {
            self.cached.remove(0);
        }
        self.cached.push((table, block));
        value
    }

    /// The block holding a file's block `i`, or 0 for a hole.
    fn block_at(&mut self, inode: &Inode, i: u64) -> u32 {
        match route(i) {
            Route::Direct(d) => inode.direct[d],
            Route::Tree(k, j) => {
                let mut at = inode.trees[k];
                for level in (0..=k as u32).rev() {
                    at = self.entry(at, slot(j, level));
                }
                at
            }
        }
    }

    /// Table block `table` (0: none yet) as one this transaction may change:
    /// itself when the transaction took it, else a new block with its
    /// contents, the old one freed at commit.
    fn own_table(&mut self, table: u32) -> Result<u32, Error> {
        if table != 0 && self.tables.contains_key(&table) {
            return Ok(table);
        }
        let new = self.allocate()?;
        let mut contents = zeroed();
        if table != 0 {
            self.disk.read(table, &mut contents);
            self.release(table);
        }
        self.tables.insert(new, contents);
        Ok(new)
    }

    fn set_entry(&mut self, table: u32, slot: usize, value: u32) {
        let changed = self
            .tables
            .get_mut(&table)
            .expect("a table this transaction owns");
        put_u32(&mut changed[..], slot * 4, value);
    }

    /// Points a file's block `i` at `block`, making the tables on the way
    /// the transaction's own.
    fn set_block_at(&mut self, inode: &mut Inode, i: u64, block: u32) -> Result<(), Error> {
        match route(i) {
            Route::Direct(d) => inode.direct[d] = block,
            Route::Tree(k, j) => {
                inode.trees[k] = self.own_table(inode.trees[k])?;
                let mut table = inode.trees[k];
                for level in (1..=k as u32).rev() {
                    let below = self.entry(table, slot(j, level));
                    let below = self.own_table(below)?;
                    self.set_entry(table, slot(j, level), below);
                    table = below;
                }
                self.set_entry(table, slot(j, 0), block);
            }
        }
        Ok(())
    }

    /// Calls `seen` with every block a file holds, each table before what
    /// it numbers. Tables are walked only as far as the file reaches, so a
    /// hole costs nothing however large, and nothing past its end counts.
    fn walk(&mut self, inode: &Inode, seen: &mut dyn FnMut(u32) -> Result<(), String>) -> Result<(), String> {
        let count = blocks_of(inode.size);
        for &b in inode.direct.iter().take(count.min(DIRECT as u64) as usize) {
            if b != 0 {
                seen(b)?;
            }
        }
        for (k, &tree) in inode.trees.iter().enumerate() {
            if tree != 0 && count > tree_start(k) {
                self.walk_table(tree, k as u32 + 1, tree_start(k), count, seen)?;
            }
        }
        Ok(())
    }

    /// [`Fs::walk`] through `table`, `depth` levels above the data, whose
    /// first block is the file's block `base`.
    fn walk_table(
        &mut self,
        table: u32,
        depth: u32,
        base: u64,
        count: u64,
        seen: &mut dyn FnMut(u32) -> Result<(), String>,
    ) -> Result<(), String> {
        // Told first, so that a table outside the disk is never read.
        seen(table)?;
        let each = span(depth - 1);
        for s in 0..(count - base).div_ceil(each).min(POINTERS) {
            let below = self.entry(table, s as usize);
            if below == 0 {
                continue;
            }
            if depth == 1 {
                seen(below)?;
            } else {
                self.walk_table(below, depth - 1, base + s * each, count, seen)?;
            }
        }
        Ok(())
    }

    fn budget(&self) -> Budget {
        Budget {
            blocks: self.shed_blocks,
            bitmap: BTreeSet::new(),
        }
    }

    /// Frees a file's blocks from its end down, as many as `budget` lets
    /// this transaction, lowering its size past them. Returns whether it
    /// freed them all. Changes no table, so it never takes a block: what a
    /// table numbers past the new end is never read again.
    fn shed(&mut self, inode: &mut Inode, budget: &mut Budget) -> bool {
        let mut count = blocks_of(inode.size);
        for k in (0..TREES).rev() {
            let start = tree_start(k);
            if count > start && inode.trees[k] != 0 {
                let done = self.shed_table(inode.trees[k], k as u32 + 1, start, &mut count, budget);
                inode.size = inode.size.min(count * BLOCK as u64);
                if !done {
                    return false;
                }
                inode.trees[k] = 0;
            }
            count = count.min(start);
        }
        while count > 0 {
            let b = inode.direct[count as usize - 1];
            if b != 0 {
                if !budget.take(b) {
                    inode.size = inode.size.min(count * BLOCK as u64);
                    return false;
                }
                self.release(b);
                inode.direct[count as usize - 1] = 0;
            }
            count -= 1;
        }
        inode.clear();
        true
    }

    /// [`Fs::shed`] through `table`, `depth` levels above the data, whose
    /// first block is the file's block `base`: what it numbers below
    /// `*count`, then itself. `*count` comes down past each block freed.
    fn shed_table(
        &mut self,
        table: u32,
        depth: u32,
        base: u64,
        count: &mut u64,
        budget: &mut Budget,
    ) -> bool {
        // Counted before what it numbers, so that once they are freed it
        // always may be: a table left with nothing it reaches would leak.
        if !budget.take(table) {
            return false;
        }
        let each = span(depth - 1);
        for s in (0..(*count - base).div_ceil(each).min(POINTERS)).rev() {
            let below = self.entry(table, s as usize);
            let first = base + s * each;
            if below != 0 {
                if depth == 1 {
                    if !budget.take(below) {
                        return false;
                    }
                    self.release(below);
                } else if !self.shed_table(below, depth - 1, first, count, budget) {
                    return false;
                }
            }
            *count = first;
        }
        self.release(table);
        true
    }

    /// Up to `len` bytes of a file from `offset`, no further than its end;
    /// holes read as zeros.
    fn read_range(&mut self, inode: &Inode, offset: u64, len: u64) -> Vec<u8> {
        let end = offset.saturating_add(len).min(inode.size);
        let mut out = Vec::with_capacity(end.saturating_sub(offset) as usize);
        if end <= offset {
            return out;
        }
        let (first, last) = (offset / BLOCK as u64, (end - 1) / BLOCK as u64);
        let mut i = first;
        while i <= last {
            // The file's next blocks, read from the disk in one go.
            let count = ((last - i + 1) as usize).min(BATCH);
            let numbers: Vec<u32> = (i..i + count as u64).map(|j| self.block_at(inode, j)).collect();
            let wanted: Vec<u32> = numbers.iter().copied().filter(|&b| b != 0).collect();
            let mut blocks = vec![[0u8; BLOCK]; wanted.len()];
            self.disk.read_many(&wanted, &mut blocks);
            let mut read = blocks.iter();
            for (j, &b) in numbers.iter().enumerate() {
                let start = (i + j as u64) * BLOCK as u64;
                let from = (offset.max(start) - start) as usize;
                let to = (end.min(start + BLOCK as u64) - start) as usize;
                match b {
                    0 => out.resize(out.len() + to - from, 0),
                    _ => out.extend_from_slice(&read.next().unwrap()[from..to]),
                }
            }
            i += count as u64;
        }
        out
    }

    /// Writes `data` into a file at `offset`, growing it (with a hole up to
    /// `offset` when that is past its end). A block in use is never written
    /// over: the new contents go to a free block, the old one freed at commit.
    fn write_range(&mut self, inode: &mut Inode, offset: u64, data: &[u8]) -> Result<(), Error> {
        let end = offset.checked_add(data.len() as u64).ok_or(Error::TooLarge)?;
        if end > MAX_FILE {
            return Err(Error::TooLarge);
        }
        // New blocks go to the disk a batch at a time. Each block of the file
        // is visited once here, so none read below is still waiting in one.
        let mut numbers = Vec::new();
        let mut blocks: Vec<[u8; BLOCK]> = Vec::new();
        let mut at = offset;
        while at < end {
            let i = at / BLOCK as u64;
            let within = (at % BLOCK as u64) as usize;
            let take = (BLOCK - within).min((end - at) as usize);
            let old = self.block_at(inode, i);
            let mut block = zeroed();
            if take < BLOCK && old != 0 {
                self.disk.read(old, &mut block);
            }
            let from = (at - offset) as usize;
            block[within..within + take].copy_from_slice(&data[from..from + take]);
            let new = if old != 0 && self.fresh.contains(&old) {
                old
            } else {
                self.allocate()?
            };
            numbers.push(new);
            blocks.push(*block);
            if numbers.len() == BATCH {
                self.disk.write_many(&numbers, &blocks);
                numbers.clear();
                blocks.clear();
            }
            if new != old {
                if old != 0 {
                    self.release(old);
                }
                self.set_block_at(inode, i, new)?;
            }
            at += take as u64;
        }
        if !numbers.is_empty() {
            self.disk.write_many(&numbers, &blocks);
        }
        inode.size = inode.size.max(end);
        inode.modified = (self.clock)();
        Ok(())
    }

    fn read_data(&mut self, inode: &Inode) -> Vec<u8> {
        self.read_range(inode, 0, inode.size)
    }

    /// Empties a file. What this transaction cannot free moves to a new
    /// dying inode, which [`Fs::settle`] frees after it commits.
    fn empty_out(&mut self, inode: &mut Inode) -> Result<(), Error> {
        let mut budget = self.budget();
        if !self.shed(inode, &mut budget) {
            let rest = Inode {
                kind: DYING,
                next: self.dying(),
                ..inode.clone()
            };
            let d = self.claim_inode(DYING)?;
            self.write_inode(d, &rest);
            self.set_dying(d);
            inode.clear();
        }
        Ok(())
    }

    /// Lets go of inode `n` and what it holds: freed now when it fits in
    /// this transaction, else put on the dying list.
    fn let_go(&mut self, n: u32) {
        let mut inode = self.read_inode(n);
        let mut budget = self.budget();
        if self.shed(&mut inode, &mut budget) {
            self.write_inode(n, &Inode::unused());
        } else {
            inode.kind = DYING;
            inode.next = self.dying();
            self.write_inode(n, &inode);
            self.set_dying(n);
        }
    }

    /// Frees what dying inodes hold, a transaction a budget's worth, until
    /// there are none.
    fn settle(&mut self) -> Result<(), Error> {
        while self.dying() != 0 {
            self.transaction(|fs| {
                let n = fs.dying();
                let mut inode = fs.read_inode(n);
                let mut budget = fs.budget();
                if fs.shed(&mut inode, &mut budget) {
                    fs.set_dying(inode.next);
                    fs.write_inode(n, &Inode::unused());
                } else {
                    fs.write_inode(n, &inode);
                }
                Ok(())
            })?;
        }
        Ok(())
    }

    /// Replaces an inode's data with `data`.
    fn write_data(&mut self, n: u32, data: &[u8]) -> Result<(), Error> {
        let mut inode = self.read_inode(n);
        self.empty_out(&mut inode)?;
        self.write_range(&mut inode, 0, data)?;
        inode.modified = (self.clock)();
        self.write_inode(n, &inode);
        Ok(())
    }

    /// A directory's entries, each with its slot.
    fn slots(&mut self, dir: u32) -> Result<Vec<(usize, String, u32, Kind)>, Error> {
        let inode = self.read_inode(dir);
        if inode.kind != Kind::Directory as u8 {
            return Err(Error::NotADirectory);
        }
        let data = self.read_data(&inode);
        Ok(data
            .as_chunks::<ENTRY>()
            .0
            .iter()
            .enumerate()
            .filter(|(_, e)| u32_at(&e[..], 0) != 0)
            .map(|(slot, e)| {
                let len = usize::from(e[5]).min(NAME_MAX);
                let kind = if e[4] == Kind::Directory as u8 {
                    Kind::Directory
                } else {
                    Kind::File
                };
                (
                    slot,
                    String::from_utf8_lossy(&e[6..6 + len]).into(),
                    u32_at(&e[..], 0),
                    kind,
                )
            })
            .collect())
    }

    fn entries(&mut self, dir: u32) -> Result<Vec<(String, u32, Kind)>, Error> {
        Ok(self
            .slots(dir)?
            .into_iter()
            .map(|(_, name, n, kind)| (name, n, kind))
            .collect())
    }

    /// Writes slot `slot` of directory `dir`: only the block it is in
    /// changes, however many entries the directory has.
    fn set_slot(&mut self, dir: u32, slot: usize, entry: &[u8; ENTRY]) -> Result<(), Error> {
        self.forget_names();
        let mut inode = self.read_inode(dir);
        self.write_range(&mut inode, (slot * ENTRY) as u64, entry)?;
        self.write_inode(dir, &inode);
        Ok(())
    }

    /// Adds `name` for inode `n` to directory `dir`, in the first free slot.
    fn add_entry(&mut self, dir: u32, name: &str, n: u32, kind: Kind) -> Result<(), Error> {
        let taken = self.slots(dir)?;
        let slot = (0..)
            .zip(&taken)
            .find(|(i, (s, ..))| i != s)
            .map_or(taken.len(), |(i, _)| i);
        let mut e = [0u8; ENTRY];
        put_u32(&mut e, 0, n);
        e[4] = kind as u8;
        e[5] = name.len() as u8;
        e[6..6 + name.len()].copy_from_slice(name.as_bytes());
        self.set_slot(dir, slot, &e)
    }

    /// The inode at `path` ("/apps/clock/program"), and its kind.
    fn lookup(&mut self, path: &str) -> Result<(u32, Kind), Error> {
        let mut at = (ROOT, Kind::Directory);
        for part in path.split('/').filter(|p| !p.is_empty()) {
            if at.1 != Kind::Directory {
                return Err(Error::NotADirectory);
            }
            if !self.listed.contains(&at.0) {
                if self.names.len() > NAMES_KEPT {
                    self.forget_names();
                }
                for (name, n, kind) in self.entries(at.0)? {
                    self.names.insert((at.0, name), (n, kind));
                }
                self.listed.insert(at.0);
            }
            at = *self.names.get(&(at.0, part.into())).ok_or(Error::NotFound)?;
        }
        Ok(at)
    }

    /// Empties the names looked up ([`Fs::names`]).
    fn forget_names(&mut self) {
        self.names.clear();
        self.listed.clear();
    }

    /// The parent directory's inode and the last name of `path`.
    fn parent<'p>(&mut self, path: &'p str) -> Result<(u32, &'p str), Error> {
        let path = path.trim_end_matches('/');
        let (dir, name) = path.rsplit_once('/').unwrap_or(("", path));
        if name.is_empty() || name.len() > NAME_MAX || name == "." || name == ".." {
            return Err(Error::BadName);
        }
        match self.lookup(dir)? {
            (n, Kind::Directory) => Ok((n, name)),
            _ => Err(Error::NotADirectory),
        }
    }

    pub fn read(&mut self, path: &str) -> Result<Vec<u8>, Error> {
        let n = self.file(path)?;
        let inode = self.read_inode(n);
        Ok(self.read_data(&inode))
    }

    /// Up to `len` bytes of the file at `path` from `offset`: fewer at its
    /// end, none past it.
    pub fn read_at(&mut self, path: &str, offset: u64, len: u64) -> Result<Vec<u8>, Error> {
        let n = self.file(path)?;
        let inode = self.read_inode(n);
        Ok(self.read_range(&inode, offset, len))
    }

    /// The kind, size and time of last change of what is at `path`.
    pub fn stat(&mut self, path: &str) -> Result<Stat, Error> {
        let (n, kind) = self.lookup(path)?;
        let inode = self.read_inode(n);
        Ok(Stat {
            kind,
            size: inode.size,
            modified: inode.modified,
        })
    }

    /// The file at `path`, which must be one.
    fn file(&mut self, path: &str) -> Result<u32, Error> {
        match self.lookup(path)? {
            (n, Kind::File) => Ok(n),
            _ => Err(Error::IsADirectory),
        }
    }

    /// The file at `path`, made empty when it is not there.
    fn file_or_new(&mut self, path: &str) -> Result<u32, Error> {
        let (dir, name) = self.parent(path)?;
        match self.entries(dir)?.into_iter().find(|(n, ..)| n == name) {
            Some((_, _, Kind::Directory)) => Err(Error::IsADirectory),
            Some((_, n, _)) => Ok(n),
            None => {
                let n = self.claim_inode(Kind::File as u8)?;
                self.add_entry(dir, name, n, Kind::File)?;
                Ok(n)
            }
        }
    }

    /// Creates or replaces the file at `path`.
    pub fn write(&mut self, path: &str, data: &[u8]) -> Result<(), Error> {
        self.transaction(|fs| {
            let n = fs.file_or_new(path)?;
            fs.write_data(n, data)
        })?;
        self.settle()
    }

    /// Writes `data` into the file at `path` from `offset`, creating it
    /// and growing it as needed; what it held elsewhere stays.
    pub fn write_at(&mut self, path: &str, offset: u64, data: &[u8]) -> Result<(), Error> {
        self.transaction(|fs| {
            let n = fs.file_or_new(path)?;
            let mut inode = fs.read_inode(n);
            fs.write_range(&mut inode, offset, data)?;
            fs.write_inode(n, &inode);
            Ok(())
        })
    }

    /// Makes the directory `path` and any missing above it.
    pub fn create_dir(&mut self, path: &str) -> Result<(), Error> {
        self.transaction(|fs| {
            let mut so_far = String::new();
            for part in path.split('/').filter(|p| !p.is_empty()) {
                so_far.push('/');
                so_far.push_str(part);
                match fs.lookup(&so_far) {
                    Ok((_, Kind::Directory)) => continue,
                    Ok(_) => return Err(Error::Exists),
                    Err(Error::NotFound) => {}
                    Err(e) => return Err(e),
                }
                let (dir, name) = fs.parent(&so_far)?;
                let n = fs.claim_inode(Kind::Directory as u8)?;
                fs.add_entry(dir, name, n, Kind::Directory)?;
            }
            Ok(())
        })
    }

    /// The names in directory `path`, directories with a trailing `/`.
    pub fn list(&mut self, path: &str) -> Result<Vec<String>, Error> {
        match self.lookup(path)? {
            (n, Kind::Directory) => Ok(self
                .entries(n)?
                .into_iter()
                .map(|(mut name, _, kind)| {
                    if kind == Kind::Directory {
                        name.push('/');
                    }
                    name
                })
                .collect()),
            _ => Err(Error::NotADirectory),
        }
    }

    /// Removes the file or empty directory at `path`. The change is done
    /// when it returns; a large file's space is freed after it, in
    /// transactions of their own.
    pub fn remove(&mut self, path: &str) -> Result<(), Error> {
        self.transaction(|fs| {
            let (dir, name) = fs.parent(path)?;
            let (slot, _, n, kind) = fs
                .slots(dir)?
                .into_iter()
                .find(|(_, n, ..)| n == name)
                .ok_or(Error::NotFound)?;
            if kind == Kind::Directory && !fs.entries(n)?.is_empty() {
                return Err(Error::NotEmpty);
            }
            fs.let_go(n);
            fs.set_slot(dir, slot, &[0; ENTRY])?;
            // A directory keeps the slots it had, but not once it is empty.
            if fs.slots(dir)?.is_empty() {
                let mut inode = fs.read_inode(dir);
                fs.empty_out(&mut inode)?;
                fs.write_inode(dir, &inode);
            }
            Ok(())
        })?;
        self.settle()
    }

    /// Removes `path` and everything under it, a transaction an entry: a
    /// power cut part way leaves part of it, every part whole.
    pub fn remove_all(&mut self, path: &str) -> Result<(), Error> {
        if let Ok((_, Kind::Directory)) = self.lookup(path) {
            for name in self.list(path)? {
                let child = format!("{}/{}", path.trim_end_matches('/'), name.trim_end_matches('/'));
                self.remove_all(&child)?;
            }
        }
        self.remove(path)
    }

    /// Checks the file system is whole, as a power cut must leave it: every
    /// inode in use is in exactly one directory, or on the dying list, and
    /// has the kind its entry says; every block of a file or directory is in
    /// the data area, belongs to it alone and is marked used; and no block
    /// or inode is marked used that nothing holds. Returns what it holds,
    /// or the first thing wrong.
    pub fn check(&mut self) -> Result<Usage, String> {
        let sb = self.sb;
        // A bit a block: a disk of 16 TiB in 512 MiB.
        let mut held = vec![0u64; (sb.blocks as usize).div_ceil(64)];
        let mut reached = vec![false; sb.inodes as usize];
        let mut usage = Usage::default();
        let mut todo = vec![(ROOT, Kind::Directory as u8, String::from("/"))];
        let mut dying = self.dying();
        while dying != 0 {
            let at = format!("dying inode {dying}");
            todo.push((dying, DYING, at));
            if dying >= sb.inodes || reached[dying as usize] {
                break;
            }
            reached[dying as usize] = true;
            dying = self.read_inode(dying).next;
        }
        reached.fill(false);
        while let Some((n, kind, path)) = todo.pop() {
            if n == 0 || n >= sb.inodes {
                return Err(format!("{path}: inode {n} is out of range"));
            }
            if core::mem::replace(&mut reached[n as usize], true) {
                return Err(format!("{path}: inode {n} is in two places"));
            }
            let inode = self.read_inode(n);
            if inode.kind != kind {
                return Err(format!(
                    "{path}: inode {n} is of kind {}, where it is named says {kind}",
                    inode.kind
                ));
            }
            if inode.size > MAX_FILE {
                return Err(format!("{path}: a size of {} bytes", inode.size));
            }
            let in_data = |b: u32| (sb.data_start..sb.blocks).contains(&b);
            let count = blocks_of(inode.size);
            for (k, &tree) in inode.trees.iter().enumerate() {
                if tree != 0 && count <= tree_start(k) {
                    return Err(format!("{path}: a block table it does not need"));
                }
            }
            self.walk(&inode, &mut |b| {
                if !in_data(b) {
                    return Err(format!("{path}: block {b} is outside the data area"));
                }
                let (word, bit) = (b as usize / 64, 1u64 << (b % 64));
                if held[word] & bit != 0 {
                    return Err(format!("{path}: block {b} also belongs to something else"));
                }
                held[word] |= bit;
                Ok(())
            })?;
            if kind == Kind::File as u8 {
                usage.files += 1;
                usage.bytes += inode.size;
            } else if kind == Kind::Directory as u8 {
                usage.directories += 1;
                if !inode.size.is_multiple_of(ENTRY as u64) {
                    return Err(format!("{path}: a directory of {} bytes", inode.size));
                }
                let entries = self.entries(n).map_err(|e| format!("{path}: {e:?}"))?;
                for (name, child, kind) in entries {
                    if name.is_empty() || name.contains('/') {
                        return Err(format!("{path}: an entry named {name:?}"));
                    }
                    let separator = if path.ends_with('/') { "" } else { "/" };
                    todo.push((child, kind as u8, format!("{path}{separator}{name}")));
                }
            }
        }
        for b in sb.data_start..sb.blocks {
            let marked = self.bitmap[b as usize / 8] & (1 << (b % 8)) != 0;
            match (marked, held[b as usize / 64] & (1 << (b % 64)) != 0) {
                (true, false) => return Err(format!("block {b} is marked used, and nothing holds it")),
                (false, true) => return Err(format!("block {b} is in use, and marked free")),
                _ => {}
            }
        }
        for first in (0..sb.inodes).step_by(INODES_PER_BLOCK) {
            let block = self.read_meta(self.inode_place(first).0);
            for (i, r) in block.as_chunks::<INODE>().0.iter().enumerate() {
                let n = first + i as u32;
                if n > ROOT && n < sb.inodes && r[0] != 0 && !reached[n as usize] {
                    return Err(format!("inode {n} is in use, and in no directory"));
                }
            }
        }
        Ok(usage)
    }
}

pub mod vault;

#[cfg(test)]
mod tests;