Where the data ends on a raw card¶
A raw medium, such as an SD card without a file system, has no end of file. When a recorder writes onto a card used before, the blocks of the earlier recording stay valid behind the new ones. A reader must find where today's recording ends, and read it past stale data, gaps and duplicates.
ww_tape on a raw card serves a recorder with a host-class processor and RAM. Its writer keeps the index of the open piece in memory. Firmware that writes an SD card or a flash chip directly takes logring instead. That store needs no standard library, no heap and little RAM. Tapes and logring compares the two.
In the example, the drive's run goes onto an SD card that still holds an earlier hour of the same board. The power fails at minute 37 in the middle of a block, so good blocks of the earlier run lie right behind the torn one.
Sessions and stale data¶
In a file, the data ends where the file ends. A raw medium has no such end. A reused card holds an older recording behind the current one, and its blocks are as valid as the new ones. A reader tells them apart by their session.
A session is one writer's unbroken append, such as a producer's start or a device's boot. Every block of a session carries the same 32-bit session tag in its header, and its sequence numbers count up from zero. A tag is never zero nor FFFFFFFFh, so an erased header never names a session. A writer gets its tag in one of three ways:
SessionTag::randompicks it at random, as a device without stored state does;SessionTag::from_seedderives it from a seed;SessionTag::of_piecederives it from the piece's id, so the same input gives the same bytes.
The drive's recording takes the third way. The earlier run on the card is another chain of the board, so its pieces have other ids and other session tags.
Where a new session may start¶
A reader keeps to one session at a time. A good block of another session is stale data, unless a new session may
start at that block. Where one may start depends on the medium, a Medium value the reader is opened with:
| Medium | A new session may start at |
|---|---|
a file (Medium::File) |
a records block that starts with a definition, where another producer appended; any piece head, where files were joined |
a raw medium (Medium::Raw) |
only a piece head that names the session just ended as its previous one |
On the card, today's run ends at the torn block, and the earlier run's blocks follow. They carry another session tag, and none of them is a piece head naming today's session. A reader of the raw card therefore takes them as stale data and ends today's run at the torn block. A reader judges a block by its session before its format version. Stale data that an older firmware wrote in another format thus ends the data too.
Reading forward, never from the end¶
A reader of a file finds the newest piece from the end, by its tail. On a raw medium the end holds stale data or
nothing, and a stale tail there would pass for the newest piece. A reader of a raw medium therefore walks forward, from
the start or from a hint the medium layer gives (OpenOptions::start).
The drive's card shows the difference. It holds about 116 MB, and today's run wrote about 72 MB of it before the power failed. Read as a raw medium, the card gives today's 3 pieces, the last one ending at the torn block. The earlier run's other 43 MB or so stay behind as stale data. Read as a file, the card gives 4 pieces, and the fourth is the earlier run's last piece, found by its tail.
cargo run -p example_drive prints these numbers, and this doctest reads the same card at 1/1000 of its data:
use ww_tape::{Medium, OpenOptions, TapeReader};
use example_drive::{Drive, EARLIER_CHAIN};
let today = Drive::scaled(1000).expect("1000 divides the rates").on_sd_card();
let earlier = today.chain(EARLIER_CHAIN).record().expect("the earlier run records");
let run = today.record().expect("the run records");
let crashed = today.crash(run.story_crash_byte().expect("minute 37")).expect("the crash");
let card = crashed.on_card(&earlier).expect("the earlier run fills the card");
let raw = OpenOptions { medium: Medium::Raw, ..OpenOptions::default() };
let on_card = TapeReader::open_with(&card.bytes[..], raw).expect("the card opens");
// Today's two closed pieces and the torn one; the earlier run is stale data.
assert_eq!(on_card.pieces().len(), 3);
let as_file = TapeReader::open(&card.bytes[..]).expect("the card opens as a file");
// Read as a file, the earlier run's last piece passes for the newest.
assert_eq!(as_file.pieces().len(), 4);
Writing a tape onto a card¶
A tape on a raw medium is written by the same writer as a file, with two differences. The layout says how far a
reader looks past a bad stretch, and every piece is one session. The drive's recorder for the card sets the
layout with Layout::on_sd_card, and Drive::on_sd_card in example_drive does the same.
A piece on a raw medium is one session, since a new session may start only at a piece head. The writer's next piece of a
chain starts with a piece head that names the session of the piece before it. A reader thus goes on from one piece into
the next. A writer that relays another producer's blocks onto a card passes them with TapeWriter::adopt_block, which
renumbers each block into the writer's own session. A jump in the producer's sequence numbers stays a jump, so a reader
still sees that blocks were lost on the way.
Each piece also carries what a reader that starts at its head needs. Right after the head come the definitions of the chain's tracks and each state track's newest item. A walk that starts at a piece head, from a hint of the medium layer, therefore reads that piece alone, the mode in force included.
On a raw medium too, a closed piece ends on a multiple of 4 KiB. A piece that starts on a 4 KiB boundary thus ends on one. The next piece then starts where a reader looks for it after a bad stretch.
Blank space and gaps¶
Blank bytes are all 0x00 or all 0xFF: what an erased or preallocated medium reads, depending on its kind. No block starts with either value, so blank space that runs to the end of the medium is the end of the data. A blank or damaged stretch in the middle is not always the end. A writer on raw NAND flash whose page program failed moves on to the next erase block. A writer that pads a NAND page at a sync leaves 0xFF behind.
The layout says how far a writer may skip and where it goes on, at a multiple of its resume alignment:
| Medium | Longest gap (gap_max) |
Goes on at a multiple of (resume_align) |
|---|---|---|
a file (Layout::UNALIGNED) |
0: the first bad stretch is the end | 1 byte |
an SD card or eMMC device (Layout::on_sd_card) |
4 MiB | 512 bytes, a sector |
raw NAND (Layout::on_raw_nand) |
two erase blocks | one page |
A reader learns these rules from the layout definition after the piece head. The writer copies that definition
about 1 MiB on and puts it again past near, as it does a track's definition. A medium layer that knows the medium
can give them from the start (OpenOptions::layout). A walk that starts past lost first sectors needs them there,
since until the copy nothing in the piece says them.
Past a blank or bad stretch, a reader reads one block header at the first non-blank byte and one at each resume place
within gap_max. A good block of the current session there goes on with the data. It makes the stretch a gap, which
the reader reports with its length (FileError::Gap) before it reads on. When no such block follows, the stretch is
the end of the data.
On the drive's card the torn block is such a stretch. Within 4 MiB after it, the reader finds only the earlier run's blocks, which are stale. Today's data therefore ends at the torn block, and the reader reads nothing further.
The format bounds what a gap costs a reader. It reads a header per resume place and checks only a few blocks whole. It
reads no further than blank space longer than gap_max, so an erased 64 GB card costs one gap's worth of reads. The
format reference lists the bounds.
Duplicates¶
A writer that retried a write may leave the same block twice. The same session and sequence number twice is a
duplicate, not a new block. A reader in Recovery::Prefix drops a second copy with the same bytes. It takes a
copy with other bytes in place of the first, and reports the replacement (FileError::Replaced).
Recovery::Resync reports a pair with other bytes as a conflict instead, as
When bytes go bad explains. In damaged bytes it cannot tell a copy from a rewrite, so
it takes neither for the other.
Lessons from tape and flash names the tape drives and flash file systems that solved these problems first, and what the format takes from each.
TapeReader.TapeWriter.pub enum Medium {
/// A file: any records block that starts with a track-0 record (another producer session appended) or piece head
/// (concatenated pieces) may start a new session. A reader finds pieces from the end of the file.
#[default]
File,
/// A raw medium (SD card, NAND, a partition) that may hold stale blocks of earlier lives behind the end of data:
/// a new session starts only at a piece head naming the session just ended ([crate::PieceHead::prev_session]),
/// and a reader walks forward from the start or a hint, never from the medium's end.
Raw,
}
What a tape's bytes are kept on: says where a reader takes a new session.
pub start: u64,
Where a Medium::Raw walk starts: the medium's start, or a hint the medium layer gives (its own superblock).
pub const fn on_sd_card(self) -> Self {
Self {
gap_max: Bytes::new(SD_GAP_MAX),
resume_align: Bytes::new(SD_RESUME_ALIGN),
..self
}
}
This layout on an SD card or eMMC: gaps up to SD_GAP_MAX, resumed on sectors.
pub const fn on_sd_card(self) -> Self {
Self {
layout: self.layout.on_sd_card(),
..self
}
}
The same run written onto a raw SD card (ww_tape::Layout::on_sd_card) instead of into files.
pub fn adopt_block(
&mut self,
defs: &Definitions,
block: &[u8],
) -> Result<Option<Placed>, WriteError<S::Error>>
Append a block of any session as the writer's own: renumbered into the writer's session and next seq (crate::set_id), then as Self::write_block.
mode; the writer keeps its items near their uses.pub layout: Option<Layout>,
The gap rules of a Medium::Raw from its start, before the definitions say them; None: none until then.
Gap {
offset: u64,
len: u64,
},
A blank or bad stretch of len bytes at offset that the session's data goes on after, within the layout's
gap: a writer could not go on there (a failed program, a bad block, a torn unit,
page padding). The walk goes on after it.
Prefix,
The longest valid prefix: stop at the first block with a bad magic, length or CRC, a cut one, one of a session that may not start there, or a seq that goes backwards, and report where (FileError::Cut).
Replaced {
offset: u64,
session: SessionTag,
seq: u64,
},
[Recovery::Prefix]: a good block at offset with the session and seq of the block before it but other bytes:
the later copy wins (a writer that retried a write), it comes next. (A copy with the same bytes is dropped
silently.)
Resync,
Salvage: report a bad block and read on at the next block magic one byte after its start (FileError::Bad); no seq check, but a data block with the session and seq of one handed out before (of the last RESYNC_SEQS_MAX) and other bytes is a conflict (FileError::Conflict): it comes only in the report, which names both (a copy with the same bytes is no conflict).
pub fn random() -> Self {
use std::hash::{BuildHasher, Hasher};
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
h.write_u128(now);
h.write_u32(std::process::id());
Self::from_seed(&h.finish().to_le_bytes())
}
A random tag, from the OS random source (the keys of std's RandomState), the time and the process id.
pub fn from_seed(seed: &[u8]) -> Self {
let mut h = blake3::Hasher::new_derive_key("ww_tape run tag");
h.update(seed);
let mut out = [0u8; 4];
h.finalize_xof().fill(&mut out);
Self::writable(u32::from_le_bytes(out))
}
A tag from seed (a device's unique id, a free-running timer at boot, an ADC noise read; or anything that
names the session, for a deterministic writer): the first 4 bytes of BLAKE3 in key derivation mode
("ww_tape run tag") over it, made writable. The same seed gives the same tag.
pub fn of_piece(id: &crate::PieceId) -> Self {
Self::from_seed(&id.0)
}
The tag of the session that starts a piece chain at the piece with id: Self::from_seed over the id, so a
deterministic writer gives the same bytes for the same input.
File,
A file: any records block that starts with a track-0 record (another producer session appended) or piece head (concatenated pieces) may start a new session. A reader finds pieces from the end of the file.
Raw,
A raw medium (SD card, NAND, a partition) that may hold stale blocks of earlier lives behind the end of data: a new session starts only at a piece head naming the session just ended (crate::PieceHead::prev_session), and a reader walks forward from the start or a hint, never from the medium's end.
pub const UNALIGNED: Self = Self {
alignment: Bytes::new(0),
gap_max: Bytes::new(0),
resume_align: Bytes::new(1),
definitions: StatePolicy::DEFAULT,
};
Not aligned, a file: no gaps.
pub const fn on_raw_nand(self, erase_block: u32, page: u32) -> Self {
Self {
gap_max: Bytes::new(erase_block.saturating_mul(2)),
resume_align: Bytes::new(page),
..self
}
}
This layout on raw NAND with erase blocks of erase_block and pages of page bytes: gaps up to two erase
blocks, resumed on pages (ONFI 6.0 §3.1).