// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The Disk II: its controller card, the drives on it, and the floppies. //! //! The drive is a remarkably bare piece of hardware. It has no idea what a //! sector is, or a track; it turns a motor, moves a head in and out by //! energising four magnets in turn, and hands over a stream of bits as they //! pass under the head. Everything else — where a sector starts, which sector //! it is, whether it read back cleanly — is done in software, by the card's //! own ROM to get started and by DOS after that. That is why so little of //! this file is about the card and so much is about the shape of the data on //! the disk. //! //! What is stored on the disk is not the bytes a program wrote. A floppy can //! only be relied on to hold a bit pattern with no more than one zero bit in //! a row and the high bit set, so eight bits of data will not fit in eight //! bits on the surface. The scheme this uses is called six and two: the data //! is cut into six-bit pieces and each is looked up in a table of sixty-four //! byte patterns the surface can hold. A 256 byte sector becomes 342 of those //! plus a checksum, and a `.dsk` file, which holds the plain bytes, has to be //! put through that before a drive can read it back. //! //! References: //! //! - Beneath Apple DOS, chapter 3, which is where the track and sector //! layout below comes from (Worth & Lechner, 1981). //! - The Disk II reference in the Apple II Reference Manual, for the card's //! addresses (Apple Computer, Inc., 1978). const std = @import("std"); const snapshot = @import("snapshot.zig"); const woz = @import("woz.zig"); const testing = std.testing; /// A 5.25 inch disk as the Apple wrote it: 35 tracks of 16 sectors of 256 /// bytes, which is the 143,360 bytes a `.dsk` file holds and nothing more. /// The file has no header and no room for anything the format does not /// already imply, which is why the size alone identifies it. pub const tracks_per_disk = 35; pub const sectors_per_track = 16; pub const bytes_per_sector = 256; pub const bytes_per_track = sectors_per_track * bytes_per_sector; pub const image_size = tracks_per_disk * bytes_per_track; /// How many nibbles a track is held as when it is a file of nibbles, and how /// big a buffer is that reads one back. /// /// This is the `.nib` format's figure, not the drive's. A revolution holds /// about 6,400 nibbles — see `bits_per_track` — and 6,656 is what nibble /// images settled on: a buffer a little longer than a revolution, so that a /// track copied off a real disk fits whatever the drive's speed was when it /// was written. A buffer this long therefore always holds a whole revolution /// of anything laid out here, with room to spare that the reader fills with /// sync bytes. pub const nibbles_per_track = 6656; /// How many processor cycles one encoded byte takes to pass the head. Four /// microseconds a bit, eight bits, and a cycle just under a microsecond. /// /// That "just under a microsecond" is the Apple II's own clock, and a machine /// with a faster one counts more of them in the same time. A disk turns at the /// speed it turns at whatever the processor is doing, so a controller on a /// faster clock has to be told the rate in *its* cycles — see the field of the /// same name on the controller below. pub const cycles_per_nibble = 32; /// How many cycles one *bit* takes to pass the head, which is what the drive /// actually deals in: four microseconds, and eight of them to a byte. /// /// The byte figure above is this times eight, and both are here because the /// controller counts bits and everything that talks to it counts bytes. pub const cycles_per_bit = cycles_per_nibble / 8; /// How many quarter-track positions a head can be put at. /// /// The four magnets place it in half tracks, and a real drive can be coaxed /// between two of those by leaving two magnets on at once, which some copy /// protection uses. A disk is stored at this resolution whether or not the head /// can be put there, because a WOZ says what is at each of them. pub const quarter_tracks = 160; /// How many distinct tracks a disk can hold. /// /// Thirty-five for anything laid out here, and up to thirty-six in the WOZ /// reference images — a disk with a half track on it. Forty-eight is room to /// spare without making a floppy larger than it needs to be. pub const max_tracks = 48; /// How long a track can be, in bytes of bit stream. A 5.25-inch track is about /// fifty thousand bits, and the longest in the reference images is 51,483. pub const max_track_bytes = 14 * 512; /// How many bits go past the head in one revolution of a disk laid out here, /// which is to say how long a track is and how fast the disk turns. /// /// A Disk II turns at 300 rpm, so a revolution is 200 milliseconds. A bit /// cell is eight of the controller's 2 MHz clocks, which is four of the /// processor's — `cycles_per_bit` — so at 1.023 MHz a revolution is 204,600 /// cycles, or 51,150 bits. The WOZ specification's figure for a track of /// unknown length is 51,200 bits (Morris, 2018), the length a real drive /// within a hair of 300 rpm gives, and it is used here so that a disk laid /// out from a sector image turns at the speed a recorded one does: 6,400 /// nibbles, 204,800 cycles, 299.7 rpm. /// /// It used to be the nibble file's 6,656 bytes times eight, which made every /// disk laid out here turn at 288 rpm and every load from one run four per /// cent long — three quarters of a second of Wizardry's twenty. pub const bits_per_track = empty_track_bits; /// What a quarter-track position holds when it holds no track at all, which is /// the ordinary state of the gap between two tracks. pub const nothing_there: u8 = 0xff; /// How long a position with no track on it is taken to be, in bits. /// /// It has to be something: the head is somewhere on a disk that is turning, and /// moving off an empty position onto a real one has to land somewhere sensible. /// The WOZ reference names this figure (Morris, 2018), and it is about a /// revolution's worth. pub const empty_track_bits: u32 = 51_200; /// How long a bit cell is, in units of 125 nanoseconds: thirty-two of them is /// four microseconds, which is what a 5.25-inch drive does and what every /// account of the format says. /// /// It is a property of the *disk* rather than of the drive, which is not /// obvious and is the whole reason WOZ carries the number. The rule was four /// microseconds, so people broke it on purpose: slow the drive down before /// writing and the bits come off a normal drive faster than they went on, and /// a bit copier that writes everything back at four microseconds produces a /// disk that reads differently from the one it copied. pub const standard_bit_timing: u8 = 32; /// How long the drive keeps turning after software says stop, measured in /// nibbles because that is the one unit here that does not depend on how fast /// the machine's clock runs. /// /// One second: a nibble is eight four-microsecond bits, so there are 31,250 of /// them in a second. Sather (1985, Chapter 9): "The drive off/on signal is /// routed through one half of an NE556 timer. The effect of this timer is to /// delay drive turn-off until one second after a reference to `$c088,x`. This /// gives the drive apparent momentum, keeping it running after it is turned /// off." pub const coasting_nibbles = 31_250; /// How long a finished byte stays in the register before the sequencer takes /// it away, in eighths of a microsecond — the same units `bit_timing` counts /// a bit cell in, so that the hold stays seven microseconds whatever speed /// the disk in the drive was written at. /// /// Seven, because that is what it was built for. Sather (1985, Chapter 9): /// "When QA becomes set, the sequencer holds the data register long enough for /// a 6502 program to detect the valid byte with a seven MPU cycle polling loop. /// Then the data register is cleared and the next byte is shifted in from the /// disk." The loop it is measured against is `lda $c08c,x` and `bpl`, which is /// four cycles and three. pub const holding_eighths: u16 = 7 * 8; /// Which order the sectors of a track appear in inside the file. /// /// Sectors are not laid down one after another on the track. Reading is much /// faster if the next sector wanted is a little way round rather than the one /// just missed, so the numbering is skewed, and the two operating systems /// skewed it differently. A file holds sectors in its own order and says /// nothing about which, so the extension is all there is to go on: `.dsk` and /// `.do` are DOS order, `.po` is ProDOS order. pub const Order = enum { dos, prodos, /// Which sector of the file belongs at a given place on the track. (Worth & /// Lechner, 1981, Table 3.1) pub fn logical(self: Order, physical: u8) u8 { return switch (self) { .dos => ([_]u8{ 0x0, 0x7, 0xe, 0x6, 0xd, 0x5, 0xc, 0x4, 0xb, 0x3, 0xa, 0x2, 0x9, 0x1, 0x8, 0xf })[physical], .prodos => ([_]u8{ 0x0, 0x8, 0x1, 0x9, 0x2, 0xa, 0x3, 0xb, 0x4, 0xc, 0x5, 0xd, 0x6, 0xe, 0x7, 0xf })[physical], }; } /// Picks the order from a file name, since nothing inside the file says. pub fn fromPath(path: []const u8) Order { return if (std.ascii.endsWithIgnoreCase(path, ".po")) .prodos else .dos; } }; /// The sixty-four byte patterns a surface can hold, in order of the six bit /// value each stands for. /// /// Every one has its high bit set and no two zero bits in a row, which is /// what the drive electronics need in order to stay in step with the bits /// going past. There are exactly sixty-four such patterns above $96 once the /// ones reserved for marking the start of a field are left out, which is why /// six bits at a time and not seven. pub const write_table = [64]u8{ 0x96, 0x97, 0x9a, 0x9b, 0x9d, 0x9e, 0x9f, 0xa6, 0xa7, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xcb, 0xcd, 0xce, 0xcf, 0xd3, 0xd6, 0xd7, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe5, 0xe6, 0xe7, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, }; /// The same table the other way round, built once at compile time. Anything /// that is not one of the sixty-four is marked, because reading one means the /// data is not what it claims to be. pub const invalid = 0xff; pub const read_table = blk: { var table: [256]u8 = @splat(invalid); for (write_table, 0..) |pattern, value| table[pattern] = value; break :blk table; }; /// The bytes that mark where a field begins and ends. They are the patterns /// deliberately left out of the table above, so they cannot occur in data and /// can be searched for. const address_prologue = [_]u8{ 0xd5, 0xaa, 0x96 }; const data_prologue = [_]u8{ 0xd5, 0xaa, 0xad }; const epilogue = [_]u8{ 0xde, 0xaa, 0xeb }; /// The filler between fields. It is written with an extra couple of bits that /// nothing here models, since that only matters to a drive trying to find the /// start of a byte, and this hands over whole bytes already. const sync = 0xff; /// How long a self-sync byte is, in bits. /// /// Ten rather than eight, and this is the one thing about a track that a file /// of bytes cannot hold. A gap is written as `$ff` with two extra zero bits /// after it, so a reader that has lost its place — which every reader has, at /// the start — collects nonsense for a byte or two and is then back in step /// with the disk, because the extra zeros push its shifter along by less than /// a whole byte each time. Without them nothing would ever line up: a shifter /// that started mid-byte would stay mid-byte for ever, and every field on the /// disk would read as a smear of two. const self_sync_bits = 10; /// How the gaps are sized. The fixed parts of a sector come to 363 bytes of /// data and 2,904 bits, so sixteen of them and the gaps have to come to about /// a track: fifty-odd thousand bits, which is what goes past the head in one /// revolution. const leading_sync = 48; const address_to_data_sync = 6; const fixed_bytes = address_prologue.len + 8 + epilogue.len + data_prologue.len + 343 + epilogue.len; const sector_fixed = fixed_bytes + address_to_data_sync; const trailing_sync = (bits_per_track - leading_sync * self_sync_bits - sectors_per_track * (fixed_bytes * 8 + address_to_data_sync * self_sync_bits)) / (sectors_per_track * self_sync_bits); /// How long a track laid out here comes to, in bits. const laid_out_bits = leading_sync * self_sync_bits + sectors_per_track * (fixed_bytes * 8 + (address_to_data_sync + trailing_sync) * self_sync_bits); comptime { // It has to fit in a track, with the self-sync bytes costing a quarter // more than they would as plain bytes. std.debug.assert(laid_out_bits <= max_track_bytes * 8); } /// The volume number written into every address field. DOS puts 254 on a disk /// it initialises unless told otherwise, and nothing in a plain image records /// what it was, so 254 it is. const default_volume = 254; /// Reverses a pair of bits, which is how the two low bits of a byte are /// stored. There is no deep reason for it; it is what the encoding does. fn swapPair(value: u8) u8 { return ((value & 1) << 1) | ((value & 2) >> 1); } /// Writes a byte as two, in the scheme used for everything in an address /// field. The odd bits go in one byte and the even bits in the other, both /// padded with ones, so that each half is a pattern the surface can hold /// without needing the six and two table. fn writeFourAndFour(into: []u8, value: u8) void { into[0] = (value >> 1) | 0xaa; into[1] = value | 0xaa; } fn readFourAndFour(odd: u8, even: u8) u8 { return ((odd << 1) | 1) & even; } /// Turns one 256 byte sector into the 343 bytes that go on the track. /// /// The six low bits of each byte are written as they are, and the two left /// over are gathered three sectors' worth at a time into the 86 bytes that go /// in front. Each byte written is exclusive ored with the one before it, so /// that reading the last one back and carrying the same running value gives /// zero if nothing was misread; that value is the checksum on the end. fn encodeSector(sector: *const [bytes_per_sector]u8, into: *[343]u8) void { var pieces: [342]u8 = @splat(0); for (0..86) |i| { var value = swapPair(sector[i] & 3) | (swapPair(sector[i + 86] & 3) << 2); // The last two of the eighty-six have only two contributors: three // times eighty-six is more than a sector holds. if (i + 172 < bytes_per_sector) value |= swapPair(sector[i + 172] & 3) << 4; pieces[i] = value; } for (0..bytes_per_sector) |i| pieces[86 + i] = sector[i] >> 2; var previous: u8 = 0; for (pieces, 0..) |piece, i| { into[i] = write_table[piece ^ previous]; previous = piece; } into[342] = write_table[previous]; } const DecodeError = error{ BadNibble, BadChecksum }; fn decodeSector(from: *const [343]u8, into: *[bytes_per_sector]u8) DecodeError!void { var pieces: [342]u8 = undefined; var previous: u8 = 0; for (from[0..342], 0..) |nibble, i| { const decoded = read_table[nibble]; if (decoded == invalid) return error.BadNibble; pieces[i] = decoded ^ previous; previous = pieces[i]; } const checksum = read_table[from[342]]; if (checksum == invalid) return error.BadNibble; if (checksum != previous) return error.BadChecksum; for (0..bytes_per_sector) |i| { const group = i % 86; const shift: u3 = @intCast(2 * (i / 86)); into[i] = (pieces[86 + i] << 2) | swapPair((pieces[group] >> shift) & 3); } } /// Puts an image into a different sector order. /// /// A file says nothing about which order it holds, so the same disk turns up /// both ways: a ProDOS volume on a 5.25 inch disk is `.po` when its blocks lie /// end to end and `.dsk` when its sectors are interleaved as DOS numbered /// them. The sectors themselves are the same either way, so this is a /// shuffle: whatever sits at a physical place on the track under one order is /// put where the other order keeps it. pub fn reorder(image: []const u8, into: []u8, from: Order, to: Order) Floppy.LoadError!void { if (image.len != image_size or into.len != image_size) return error.WrongSize; for (0..tracks_per_disk) |track| { const base = track * bytes_per_track; for (0..sectors_per_track) |physical| { const source = base + @as(usize, from.logical(@intCast(physical))) * bytes_per_sector; const target = base + @as(usize, to.logical(@intCast(physical))) * bytes_per_sector; @memcpy(into[target..][0..bytes_per_sector], image[source..][0..bytes_per_sector]); } } } /// Whether a byte is one the surface can carry. /// /// The high bit set, and no two zero bits in a row: that is the whole of the /// rule, and it is why there are only sixty-four of them rather than 256. A /// drive reading a disk that was laid out properly sees nothing else. pub fn legal(value: u8) bool { for (write_table) |pattern| { if (pattern == value) return true; } return false; } /// A floppy, held the way the drive sees it rather than the way the file does. /// /// This is deliberately large — a third of a megabyte — and deliberately not /// part of the machine: whoever owns the emulator allocates it and hands it /// over, so that a machine with no drives costs nothing and swapping a disk is /// a matter of handing over a different one. /// One track, as the bits that go past the head. /// /// Bits and not bytes, because a track is not a whole number of bytes and the /// difference is what copy protection is made of. A self-sync byte is ten bits /// long, so a reader that has lost its place finds it again a byte or two /// later; a track holds however many bits went past in one revolution, which /// depends on how fast the disk was turning; and a disk laid out by hand has /// nothing to say about any of that. Storing bytes throws all of it away. pub const Track = struct { /// Packed high bit first, which is the order they go past the head. bits: [max_track_bytes]u8 = @splat(0), /// How many of those bits are the track. Zero means nothing is recorded /// here, which is not the same as a track of zeroes. count: u32 = 0, /// The bit at `at`, counting round the track. pub fn bit(self: *const Track, at: u32) u1 { if (self.count == 0) return 0; const which = at % self.count; return @truncate(self.bits[which / 8] >> @intCast(7 - (which % 8))); } pub fn setBit(self: *Track, at: u32, value: u1) void { if (self.count == 0) return; const which = at % self.count; const mask = @as(u8, 0x80) >> @intCast(which % 8); if (value == 1) self.bits[which / 8] |= mask else self.bits[which / 8] &= ~mask; } }; pub const Floppy = struct { /// How long a bit cell is on this disk, in units of 125 nanoseconds. Only /// a WOZ says; everything else is the standard four microseconds, because /// everything else has no way to be anything but. bit_timing: u8 = standard_bit_timing, /// Which recorded track the head finds at each quarter-track position, or /// `nothing_there`. A disk laid out here puts the same track at all four /// quarters of its position, which is what the drive used to do when it /// simply divided by two; a WOZ brings its own map and is more particular. map: [quarter_tracks]u8 = @splat(nothing_there), tracks: [max_tracks]Track = @splat(.{}), /// Whether the tab is over the notch. A drive can tell, and DOS asks /// before it writes. write_protected: bool = true, /// Whether anything has been written since it was loaded, so that a /// caller knows whether saving it back is worth doing. dirty: bool = false, order: Order = .dos, pub const LoadError = error{WrongSize}; /// Lays out a whole disk image as a drive would find it, one encoded /// track after another. pub fn load(self: *Floppy, image: []const u8, order: Order) LoadError!void { if (image.len != image_size) return error.WrongSize; self.order = order; self.dirty = false; self.bit_timing = standard_bit_timing; self.describe(tracks_per_disk); for (0..tracks_per_disk) |track| { const from = image[track * bytes_per_track ..][0..bytes_per_track]; encodeTrack(from, &self.tracks[track], @intCast(track), order); } } /// Lays out the quarter-track map for a disk of `count` whole tracks. /// /// All four quarters of a position read the same track, which is what the /// drive did when it simply divided the half-track count by two. It is not /// what a real disk does — the gap between two tracks holds nothing — but /// it is what a disk described rather than recorded can honestly say, and /// changing it would make a half-track step read silence on disks that have /// always worked. fn describe(self: *Floppy, count: u8) void { self.map = @splat(nothing_there); for (0..count) |track| { for (0..4) |quarter| { const at = track * 4 + quarter; if (at < quarter_tracks) self.map[at] = @intCast(track); } } } /// Writes a nibble file's track into it, eight bits to the nibble: the /// file's 6,656 nibbles, all of them, since a file of nibbles does not /// say where its revolution ends. fn putNibbles(self: *Floppy, track: u8, nibbles: *const [nibbles_per_track]u8) void { const into = &self.tracks[track]; @memcpy(into.bits[0..nibbles_per_track], nibbles); into.count = nibbles_per_track * 8; } /// The bit cell a nibble file's track is read at, in the units /// `bit_timing` uses. /// /// The file holds 6,656 nibbles a track and a revolution at 300 rpm holds /// about 6,400, so taken literally the file describes a disk written on a /// drive turning four per cent slow. Put in a drive turning at speed, the /// bits on such a disk come off four per cent faster — which is exactly /// what `bit_timing` is for, and what a protected disk written on a /// slowed drive does on purpose. The nearest the unit allows is 31 /// eighths of a microsecond rather than 32, which makes the revolution /// 201.7 milliseconds: the disk turns at speed and the track is the /// file's, both as near as can be had. pub const nibble_bit_timing: u8 = @intCast((@as(u32, standard_bit_timing) * bits_per_track + (nibbles_per_track * 8) / 2) / (nibbles_per_track * 8)); /// Reads a track back as nibbles, by running the shifter over it the way /// the controller does. /// /// For a disk laid out here this gives back exactly what went in. For one /// that was recorded it gives what a drive would read on one pass, which /// is the best a file of nibbles can hold. fn takeNibbles(self: *const Floppy, track: u8, nibbles: *[nibbles_per_track]u8) void { self.readTrack(track, nibbles, null); } /// The same, and where each nibble began. /// /// The second half of that is what anything wanting to put a nibble back /// needs. A nibble is not at a fixed place in a track: a self-sync byte is /// ten bits long, so everything after one is pushed along by two, and the /// nth nibble is simply wherever the shifter had got to. pub fn readTrack( self: *const Floppy, track: u8, nibbles: *[nibbles_per_track]u8, offsets: ?*[nibbles_per_track]u32, ) void { const from = &self.tracks[track]; if (from.count == 0) { @memset(nibbles, sync); return; } var latch: u8 = 0; var at: u32 = 0; var out: usize = 0; // One revolution and no more. A file of nibbles holds a track once, // and going round twice would put the beginning of it in the buffer a // second time — which anything reading the file would see as a // seventeenth sector that stops in the middle. var began: u32 = 0; while (out < nibbles.len and at < from.count) : (at += 1) { if (latch == 0) began = at; latch = (latch << 1) | from.bit(at); if (latch & 0x80 != 0) { nibbles[out] = latch; if (offsets) |where| where[out] = began; out += 1; latch = 0; } } while (out < nibbles.len) : (out += 1) { nibbles[out] = sync; if (offsets) |where| where[out] = 0; } } /// One nibble of a track whose bytes are byte aligned, which is what a /// disk read out of a file of nibbles is. A track laid out here is not: /// its gaps are ten bits long. pub fn nibbleAt(self: *const Floppy, track: u8, at: usize) u8 { return self.tracks[track].bits[at % nibbles_per_track]; } /// Lays a byte down at a bit position, high bit first, which is what the /// machine does when it writes. pub fn writeNibbleAt(self: *Floppy, track: u8, at: u32, value: u8) void { const into = &self.tracks[track]; for (0..8) |i| into.setBit(at + @as(u32, @intCast(i)), @truncate(value >> @intCast(7 - i))); } /// How big a file of raw nibbles is: every track as the drive holds it, /// one after another and nothing else. pub const nibble_size = tracks_per_disk * nibbles_per_track; /// Takes a disk that was recorded rather than described. /// /// A `.nib` file is this structure written out: thirty-five tracks of /// 6,656 nibbles, which is what came off a real drive's head rather than /// what a sector editor thinks is on the disk. So loading one is a copy, /// and that is the whole reason the format exists. /// /// It exists because a `.dsk` cannot hold a disk that was protected. Every /// scheme worth the name did something a sixteen-sector-per-track file has /// no way to write down: address fields with the wrong prologue, sectors /// with no address field at all, a thirteenth sector hidden in the gaps, a /// track with two copies of sector 3 that read differently. A file of /// nibbles keeps whatever was there, because it does not know what any of /// it means. /// /// What it does not keep is timing. The drive's head sees a stream of bits /// at a rate the disk's rotation sets, and a nibble file has already had /// that turned into bytes — so a scheme that counts on where the bit cells /// fall, or on a track being longer or shorter than the standard, is still /// out of reach here. That is what `.woz` was invented for. pub fn loadNibbles(self: *Floppy, image: []const u8) LoadError!void { if (image.len != nibble_size) return error.WrongSize; // The order matters only to `save`, which cannot put a nibble disk // back into a sectored file anyway. Recorded, not described. self.order = .prodos; self.dirty = false; self.bit_timing = nibble_bit_timing; self.describe(tracks_per_disk); for (0..tracks_per_disk) |track| { self.putNibbles( @intCast(track), image[track * nibbles_per_track ..][0..nibbles_per_track], ); } } /// Takes a disk recorded as the bits that went past the head. /// /// This is the one format that keeps a track's own length and its own /// alignment, so it is the one that goes in without being turned into /// anything: the bits are copied and the map comes along with them. pub fn loadWoz(self: *Floppy, image: woz.Image) !void { self.order = .prodos; self.dirty = false; self.write_protected = image.info.write_protected; // A version 1 WOZ does not carry the field and is always four // microseconds; a version 2 that carries a zero is not saying either. self.bit_timing = if (image.info.bit_timing == 0) standard_bit_timing else image.info.bit_timing; self.map = @splat(nothing_there); self.tracks = @splat(.{}); // The file's own map, position for position. Which recorded track is // at each quarter is the file's business and not this one's: that is // where a track between two tracks, or one track two tracks wide, // lives. var mapping: [woz.positions]u8 = @splat(nothing_there); var used: u8 = 0; for (0..@min(quarter_tracks, woz.positions)) |position| { // The flux map first, because the format says so where a file is // careless enough to name a position in both. const flux = image.fluxAt(@intCast(position)); const which = flux orelse image.at(@intCast(position)) orelse continue; if (mapping[which] == nothing_there) { if (used >= max_tracks) return error.TooManyTracks; const track = try image.track(which); if (track.count == 0) continue; mapping[which] = used; if (flux != null) { // A flux track is not bits at all. It is what the head saw, // in gaps of 125 nanoseconds, and its count is a count of // bytes rather than of bits — so the drive's data separator // has to be run over it before there is a track here. const stream = track.bits[0..@min(track.bits.len, track.count)]; self.tracks[used].count = woz.fluxToBits( stream, self.bit_timing, &self.tracks[used].bits, ) catch return error.TrackTooLong; if (self.tracks[used].count == 0) return error.NoTracks; } else { if ((track.count + 7) / 8 > max_track_bytes) return error.TrackTooLong; self.tracks[used].count = track.count; @memcpy( self.tracks[used].bits[0 .. (track.count + 7) / 8], track.bits[0 .. (track.count + 7) / 8], ); } used += 1; } self.map[position] = mapping[which]; } if (used == 0) return error.NoTracks; } /// The live bit surface under a quarter-track position, or null when /// nothing is recorded there. /// /// This is what a WOZ is saved back from: the buffer the machine has been /// writing to, exactly the bytes that a bit count of `count` fills. A WOZ /// loaded here keeps its own quarter-track map, so a caller walks the same /// positions the file records and hands each one straight back. pub fn bitsAt(self: *const Floppy, position: u8) ?[]const u8 { if (position >= self.map.len) return null; const which = self.map[position]; if (which == nothing_there) return null; const found = &self.tracks[which]; if (found.count == 0) return null; return found.bits[0 .. (found.count + 7) / 8]; } /// Writes the disk out as raw nibbles, which is the one form that can hold /// whatever the machine actually wrote — including a track it formatted /// itself in a shape no sectored file could describe. pub fn saveNibbles(self: *const Floppy, image: []u8) LoadError!void { if (image.len != nibble_size) return error.WrongSize; for (0..tracks_per_disk) |track| { self.takeNibbles(@intCast(track), image[track * nibbles_per_track ..][0..nibbles_per_track]); } } /// Puts the disk back into the plain form a file holds. /// /// Every sector has to be found again by reading round the track for the /// marks, because what is being saved may have been written by the machine /// rather than laid out here. A sector that cannot be found or does not /// read back cleanly is left as it was in the image handed in, which for a /// disk being saved over itself means it keeps what it had. pub fn save(self: *const Floppy, image: []u8) LoadError!void { if (image.len != image_size) return error.WrongSize; var nibbles: [nibbles_per_track]u8 = undefined; for (0..tracks_per_disk) |track| { self.takeNibbles(@intCast(track), &nibbles); decodeTrack(&nibbles, image[track * bytes_per_track ..][0..bytes_per_track], self.order); } } }; /// Writes one track: a run of filler, then each sector in turn as an address /// field saying where it is and a data field holding it. fn encodeTrack( from: *const [bytes_per_track]u8, into: *Track, track: u8, order: Order, ) void { var head: Layer = .{ .track = into }; into.count = laid_out_bits; @memset(&into.bits, 0); head.sync(leading_sync); var field: [343]u8 = undefined; for (0..sectors_per_track) |physical| { const sector: u8 = @intCast(physical); head.all(&address_prologue); var four: [2]u8 = undefined; for ([_]u8{ default_volume, track, sector, default_volume ^ track ^ sector }) |value| { writeFourAndFour(&four, value); head.all(&four); } head.all(&epilogue); head.sync(address_to_data_sync); head.all(&data_prologue); const logical: usize = order.logical(sector); encodeSector(from[logical * bytes_per_sector ..][0..bytes_per_sector], &field); head.all(&field); head.all(&epilogue); head.sync(trailing_sync); } } /// Lays bytes down on a track, high bit first, as the head would. const Layer = struct { track: *Track, at: u32 = 0, fn bit(self: *Layer, value: u1) void { if (value == 1) self.track.bits[self.at / 8] |= @as(u8, 0x80) >> @intCast(self.at % 8); self.at += 1; } fn byte(self: *Layer, value: u8) void { for (0..8) |i| self.bit(@truncate(value >> @intCast(7 - i))); } fn all(self: *Layer, values: []const u8) void { for (values) |value| self.byte(value); } /// A gap: `$ff` and then two bits of nothing, which is what puts a reader /// back in step. fn sync(self: *Layer, count: usize) void { for (0..count) |_| { self.byte(0xff); self.bit(0); self.bit(0); } } }; /// Reads a track back, by going round it looking for the marks. fn decodeTrack(from: *const [nibbles_per_track]u8, into: *[bytes_per_track]u8, order: Order) void { var at: usize = 0; // Twice round, because a sector may straddle the point the buffer starts // at and its two halves are only adjacent going round. const limit = nibbles_per_track * 2; while (at + address_prologue.len < limit) { if (!matches(from, at, &address_prologue)) { at += 1; continue; } at += address_prologue.len; const sector = readFourAndFour(peek(from, at + 4), peek(from, at + 5)); at += 8; // The data field follows within a gap's worth of bytes, and nothing // else can produce its mark. var search = at; const data_limit = @min(at + 64, limit); while (search + data_prologue.len < data_limit and !matches(from, search, &data_prologue)) search += 1; if (search + data_prologue.len >= data_limit) continue; search += data_prologue.len; var field: [343]u8 = undefined; for (&field, 0..) |*byte, i| byte.* = peek(from, search + i); var sector_bytes: [bytes_per_sector]u8 = undefined; decodeSector(&field, §or_bytes) catch { at = search; continue; }; if (sector < sectors_per_track) { const logical: usize = order.logical(sector); @memcpy(into[logical * bytes_per_sector ..][0..bytes_per_sector], §or_bytes); } at = search + 343; } } fn peek(track: *const [nibbles_per_track]u8, at: usize) u8 { return track[at % nibbles_per_track]; } fn matches(track: *const [nibbles_per_track]u8, at: usize, pattern: []const u8) bool { for (pattern, 0..) |byte, i| if (peek(track, at + i) != byte) return false; return true; } /// One drive: what is in it, where its head is, and where the disk has turned /// to. pub const Drive = struct { floppy: ?*Floppy = null, /// Where the head is, counted in quarter tracks. /// /// The four magnets sit a half track apart, so one of them on its own can /// only place the head on a half track. Leaving two adjacent ones on at /// once pulls it to the point between them — the quarter — and that is /// not an accident of the mechanism but a thing copy protection was /// written for: data laid down between two tracks is data an ordinary /// copier, which steps in whole tracks, never sees. quarter_track: u8 = 0, /// Which magnets are energised. Which one comes on next is what says /// whether the head is going in or out. phases: [4]bool = @splat(false), /// How far round the disk has turned, as a bit position in the track under /// the head. Bits, because that is what goes past it. position: u32 = 0, /// The read shifter: bits go in at the bottom and a byte is finished when /// the top one is set, which is the whole of how a nibble is recognised. /// /// It never stops. A zero shifted into an empty shifter leaves it empty, /// so a run of zeroes costs nothing and the next one bit starts a byte — /// which is why every legal nibble has its high bit set, and why a /// self-sync byte's two extra zeroes put a lost reader back in step. latch: u8 = 0, /// The byte the processor reads, which is the last one the shifter /// finished. /// /// Keeping it apart from the shifter is what lets the head go on turning /// while a byte waits to be collected. The shifter starts the next byte at /// the boundary the last one ended on, so nothing can knock it out of step; /// a processor too slow to keep up loses the byte, which is what a real one /// does, rather than losing its place, which a real one does not. /// /// Reading it does not empty it. What empties it is the sequencer, once it /// has held the byte long enough to be collected, and holding is the whole /// of how a read loop is given time to notice. data: u8 = 0, /// What is left of the hold on a finished byte, in eighths of a /// microsecond. Zero when the register is not holding anything. holding: u16 = 0, /// The last four bits off the surface, for spotting the runs of nothing a /// cleaned image leaves behind. window: u8 = 0, /// Where the random bits over unrecorded surface come from. Seeded from /// nothing in particular, because what matters is that they are not the /// same every revolution. noise: u32 = 0x2545f491, pub fn track(self: *const Drive) u8 { return self.quarter_track / 4; } /// Which quarter-track position the head is at. pub fn quarter(self: *const Drive) u8 { return self.quarter_track; } /// Which way a magnet pulls the head, and how far, in quarter tracks. /// /// The magnets are a half track — two quarters — apart and there are four /// of them, so each one holds every eighth quarter starting at twice its /// own number, and it pulls the head to whichever of those is nearest. /// /// A magnet exactly opposite the head is the case worth naming: it is the /// same distance either way round, so it pulls both ways at once and the /// head does not move. Software does not usually energise opposing /// magnets, but a model that let one of them win would step the head half /// a track for no reason at all. fn pullOf(phase: u2, here: i32) i32 { const base: i32 = @as(i32, phase) * 2; var delta = @mod(base - here, 8); if (delta > 4) delta -= 8; return if (delta == 4) 0 else delta; } /// The track under the head, or nothing if there is none there. pub fn under(self: *const Drive) ?*Track { const floppy = self.floppy orelse return null; const which = floppy.map[self.quarter()]; if (which == nothing_there) return null; return &floppy.tracks[which]; } /// One bit off the surface. /// /// A cleaned image has had the noise a drive makes over unrecorded surface /// taken out and left as a run of zero bits, and a reader has to put it /// back or the disk reads as something no drive ever saw. The WOZ reference /// gives the rule outright (Morris, 2018): keep the last four bits, and if /// all four are zero — which is to say more than two zeroes in a row, which /// no real recording contains — hand back noise instead, about three times /// in ten. fn nextBit(self: *Drive, from: *const Track) u1 { self.window = (self.window << 1) | from.bit(self.position); if (self.window & 0x0f != 0) return @truncate(self.window >> 1); return self.fakeBit(); } /// Throws away the part-built byte and starts again from here. /// /// What the write-protect sense does to the register it shares, and the /// only way a program has of reading the surface out of step with the /// bytes written on it. fn restart(self: *Drive) void { self.latch = 0; self.data = 0; self.holding = 0; } /// A bit out of nothing: what the amplifier makes of unrecorded surface. /// /// About three in ten come out set, which is the figure the WOZ reference /// gives (Morris, 2018) and which matters more than it looks: all ones /// would read as a stream of `$ff` and all zeroes as nothing at all, and /// what a drive actually produces over blank surface is neither. fn fakeBit(self: *Drive) u1 { self.noise = self.noise *% 1664525 +% 1013904223; return if ((self.noise >> 16) % 10 < 3) 1 else 0; } /// Energises or releases one magnet, and moves the head if the one coming /// on is next door to where the head already is. Turning one off never /// moves anything. fn setPhase(self: *Drive, phase: u2, on: bool) void { self.phases[phase] = on; // Where the energised magnets want the head. Each pulls it to the // nearest position belonging to it, so one on its own moves it a half // track at most; two adjacent ones pull equally and it settles between // them, which is the quarter track. Turning them all off leaves it // where it is, because nothing is pulling. var sum: i32 = 0; var count: i32 = 0; const here: i32 = self.quarter_track; for (self.phases, 0..) |energised, which| { if (!energised) continue; sum += pullOf(@intCast(which), here); count += 1; } if (count == 0) return; // Two magnets pulling opposite ways cancel and the head stays put, // which is what `@divTrunc` of their sum comes to and what the // mechanism does. const moved = here + @divTrunc(sum, count); const limit: i32 = quarter_tracks - 1; const settled: u8 = @intCast(@max(0, @min(limit, moved))); if (settled == self.quarter_track) return; const before: u32 = if (self.under()) |t| t.count else 0; self.quarter_track = settled; // The head moves; the disk does not stop turning. Where it now is on // the new track is where it would have been had it always been there, // which matters because a track is not the same length as its // neighbour and a disk written in one pass has the two lined up. That // alignment is what a cross-track check looks at. const after: u32 = if (self.under()) |t| t.count else 0; if (before != 0 and after != 0) { self.position = @intCast(@as(u64, self.position) * after / before); } else if (after != 0) { self.position %= after; } self.latch = 0; } /// Turns the disk by however many bits have gone past, shifting each one /// into the read shifter on its way. /// /// The shifter stops taking bits once it holds a whole byte: the disk goes /// on turning, and what goes past while the processor has not collected the /// last byte is gone. That is what a drive does, and it is why the firmware /// has to come back for each byte inside thirty-two cycles. fn turn(self: *Drive, bits: usize, timing: u16) void { // Between two tracks, or over one that was never recorded, the head // hears the amplifier's own noise. That is noise and not silence, and // the difference matters: a program reading there gets a stream of // bytes that are never the same twice and never mean anything, rather // than a data register that stays at zero for ever. The WOZ reference // says as much (Morris, 2018) — an empty position is "a synthetic // length of 51,200 bits" that "continuously output[s] random data" — // and a protection that steps between two tracks to see what is there // is reading for exactly that difference. const from = self.under(); const length: u32 = if (from) |t| t.count else empty_track_bits; for (0..bits) |_| { const value = if (from) |t| self.nextBit(t) else self.fakeBit(); self.position = (self.position + 1) % @max(1, length); // The shifter never stops, whether or not anyone is reading. self.latch = (self.latch << 1) | value; if (self.holding > 0) { self.holding -|= timing; // A byte is not taken away while there is nothing to replace // it with. An empty shifter means the surface is giving // zeroes, which is a gap rather than the start of the next // byte, so the hold is put back rather than counted down — // and a program reading a long gap keeps seeing the last real // byte, which is what a real drive gives it. if (self.latch == 0) self.holding += timing; } if (self.holding == 0) { // Not holding: the register follows the shifter, so a program // reading between bytes sees a part-built one with its top bit // clear, which is what a read loop waits on. self.data = self.latch; if (self.latch & 0x80 != 0) { // Finished. The sequencer holds it long enough to be // collected, and the shifter starts the next byte exactly // on the boundary. self.holding = holding_eighths; self.latch = 0; } } } } }; /// The controller card, with its two drives. /// /// The card has no state worth the name: four magnets, a motor, which drive is /// listening, and two flip flops that between them say whether it is reading, /// writing, or being asked whether the disk can be written to at all. pub const Controller = struct { drives: [2]Drive = .{ .{}, .{} }, /// How many drives are actually plugged into the card. The card always /// has two connectors and software cannot tell whether anything is on the /// end of one, so this only decides whether selecting the second reaches /// a drive that could hold a disk. fitted: u2 = 2, selected: u1 = 0, /// Whether software has asked for the motor. Not the same question as /// whether the disk is turning, which is `turningAt`. motor: bool = false, /// The cycle the drive coasts to a stop at, once software has said stop. /// Null when the drive is either running or long since stopped. stops_at: ?u64 = null, /// The two flip flops, in the names the card's own documentation uses. q6: bool = false, q7: bool = false, /// The byte on its way in or out. latch: u8 = 0, /// The cycle the disk was last turned to, so that it turns by the right /// amount rather than by one byte per read. turned_at: u64 = 0, /// How many of the clock's cycles one encoded byte takes to pass the head. /// /// The default is an Apple II's, whose clock is the one the constant above /// is measured in. An Apple IIgs counts its cycles nearly three times as /// fast, so its disk port sets this to match — otherwise the disk turns /// three times too quickly, the boot PROM's read loop sees every third /// byte, and a perfectly good disk looks unreadable. Which is exactly what /// it did: thirty-three thousand times round the loop looking for an /// address mark that was going past too fast to catch. turning: u64 = cycles_per_nibble, /// What was left of a bit when the disk was last turned, in the units the /// sum above works in. Kept so that a great many short steps come to the /// same as one long one. left_over: u64 = 0, /// What the reset line does to the card. /// /// The motor, the four magnets and the two flip flops are one addressable /// latch on the card, and the bus clears it on reset. So a machine reset /// stops the drive: reset out of a boot that is going nowhere and the /// light goes out, rather than the drive turning for ever afterwards. It /// also means a reset in the middle of writing does not leave the card in /// write mode with the head still down. /// /// Stopping the drive here means stopping it, not letting it coast for the /// second it would have had. Sather again (1985, Chapter 9): "The 1-second /// turn off delay does not apply to turning off the drive via a RESET. /// Pressing RESET causes the delay timer to clear and turns off the drive /// almost immediately." /// /// Where the head is left is mechanical and stays where it is, and so does /// whatever is in the drives. pub fn reset(self: *Controller) void { self.motor = false; self.stops_at = null; self.q6 = false; self.q7 = false; for (&self.drives) |*disk| disk.phases = @splat(false); } pub fn drive(self: *Controller, which: u1) *Drive { return &self.drives[which]; } pub fn current(self: *Controller) *Drive { return &self.drives[self.selected]; } /// Whether the disk is going round, which is not the same as whether /// software has asked for the motor: for a second after it says stop, it /// is still going round. That second is why the light on a real drive /// lingers after a `CATALOG` has already finished printing. pub fn turningAt(self: *Controller, cycles: u64) bool { if (self.motor) return true; return cycles < (self.stops_at orelse return false); } /// How long the drive coasts for, in this machine's cycles. A IIgs counts /// its cycles nearly three times as fast as an Apple II, and a second is /// still a second, so the answer is scaled by the same thing that scales /// how fast the disk turns. fn coasting(self: *Controller) u64 { return coasting_nibbles * self.turning; } /// Ask for the motor, or ask it to stop. /// /// Stopping is not stopping at once unless it is asked to be. A Disk II /// card always gives the drive its second, because the timer that grants /// it is soldered to the card; a IIgs has the same second under software /// control, so its disk port passes on what the IWM's mode register says. /// Either way the disk is brought up to date first, so that a stop and a /// start inside the same second leave it where it coasted to rather than /// where it was when software said stop. pub fn setMotor(self: *Controller, on: bool, coasts: bool, cycles: u64) void { self.spin(cycles); if (on) { self.motor = true; self.stops_at = null; } else if (self.motor) { // A drive that is already stopped stays stopped: the timer is // fired by the motor going off, and a motor that was off does not // go off again. It is momentum, and there is none to keep if the // disk was not moving. self.motor = false; self.stops_at = if (coasts) cycles + self.coasting() else cycles; } } /// Whether the motor is turning a drive that has something in it. pub fn spinningAt(self: *Controller, cycles: u64) bool { return self.turningAt(cycles) and self.current().floppy != null; } pub fn insert(self: *Controller, which: u1, floppy: *Floppy) void { self.drives[which].floppy = floppy; } pub fn eject(self: *Controller, which: u1) ?*Floppy { const floppy = self.drives[which].floppy; self.drives[which].floppy = null; return floppy; } /// Everything the card does, which is one of sixteen addresses being /// touched. Reading and writing do the same thing at nearly all of them: /// the card decodes the address and pays no attention to what the /// processor thought it was doing, which is why so much of the ROM is /// `LDA` at addresses nothing is being loaded from. /// /// The last four are the data register, and what it does depends on the /// two flip flops rather than on the address: reading the disk, writing to /// it, or answering whether it can be written to at all. Setting a flip /// flop and then reading the register is how the ROM asks, which is why /// touching $c0ee gives back the write protect answer that $c0ed set up. /// /// The cycle count is how the disk knows how far to turn. Handing back the /// same byte twice because no time had passed would stall a read loop, so /// a read always turns it at least one byte on. pub fn access(self: *Controller, offset: u4, is_write: bool, value: u8, cycles: u64) u8 { switch (offset) { // The four magnets, released at the even address and energised at // the odd one. 0x0...0x7 => { self.current().setPhase(@truncate(offset >> 1), offset & 1 == 1); return 0; }, 0x8 => { self.setMotor(false, true, cycles); return 0; }, 0x9 => { self.setMotor(true, true, cycles); return 0; }, 0xa => { self.selected = 0; return 0; }, 0xb => { // A card always has two connectors whether or not there is a // drive on the end of the second, and nothing in software can // tell the difference. self.selected = if (self.fitted > 1) 1 else 0; return 0; }, 0xc => { self.q6 = false; return self.shift(cycles); }, 0xd => { self.q6 = true; if (is_write) { self.latch = value; } else if (!self.q7) { // Asking whether the disk can be written to is asking the // same register that has been assembling a byte, and the // answer goes into it: whatever the shifter had is gone, // and the next byte begins wherever the head is now rather // than on the boundary the last one ended at. // // That is not a side effect nobody wanted. A program that // wants to read a stream out of step with the bytes on the // disk does exactly this, part way through a nibble, and // the timing bits between nibbles then come through as // data. The head has to be brought up to date first, or // the phase it starts again from is the one it had // whenever it was last looked at. self.spin(cycles); self.current().restart(); } }, 0xe => self.q7 = false, 0xf => { self.q7 = true; if (is_write) self.latch = value; }, } // Reading the register with the first flip flop set and the second // clear is the question about the write protect tab. if (self.q6 and !self.q7) return self.protection(); return self.latch; } /// $c0ec: one byte past the head, in whichever direction the second flip /// flop says. fn shift(self: *Controller, cycles: u64) u8 { if (self.q7) { self.writeNibble(cycles, self.latch); return 0; } return self.readNibble(cycles); } /// Energises or releases one of the four magnets on the selected drive. /// /// This and the three below are the mechanism rather than the card, which /// is why they are reachable without going through `access`: an Apple IIgs /// has the same drives on the end of an IWM instead of a card, and the /// IWM's own three registers sit on top of exactly this. pub fn phase(self: *Controller, which: u2, on: bool) void { self.current().setPhase(which, on); } /// One byte past the head, reading. /// /// A drive with nothing in it is not silent. The head hears the /// amplifier's own noise, which is the same thing it hears over a track /// that was never recorded, and `turn` already makes that out of /// `fakeBit`. What comes back is a stream of bytes that never mean /// anything rather than a register stuck at zero, and the difference is /// load-bearing: the Apple IIc with the 32K ROM keeps a counter of tries /// at its built-in drive (`DEC $03` at `$c644`, bank 0) and hands over to /// the Protocol Converter when it runs out — but that counter only comes /// round when the read loop above it finds a byte at all. Given silence /// the loop never lets go, and the machine can never reach the drive on /// its port. Apple describes what should happen instead: "it attempts to /// boot from the built-in disk drive. If this fails, it attempts to boot /// from the first device attached to the Protocol Converter" (Apple /// Computer, Inc., n.d.-b, p. 4). pub fn readNibble(self: *Controller, cycles: u64) u8 { self.spin(cycles); const disk = self.current(); // Taking the byte does not empty the register. The reference set is // explicit that it should not — "when a program reads data from the // data latch, the implementation should not be clearing the latch" — // and what gives a read loop something to wait on instead is the hold // running out, after which the register follows the shifter and shows // a part-built byte with its top bit clear. const value = disk.data; self.latch = value; return value; } /// One byte past the head, writing. What is written goes down where the /// head is, unless the tab says it cannot. pub fn writeNibble(self: *Controller, cycles: u64, value: u8) void { // The head does not stop moving between one nibble and the next, and // the write current is on the whole time: what lands on the surface is // the byte, high bit first, over the cells it takes to shift out, and // then zeroes over any cells left before the next byte is loaded — // which is exactly the two trailing zeroes that make a self-sync byte // ten bits wide rather than eight. So the head is turned by however // much time has gone by and the byte written over the cells it passed, // rather than eight cells written on top of the eight the disk had // already turned through, which is twice as many and leaves every // other cell as it was. const step = self.turned(cycles); const disk = self.current(); const floppy = disk.floppy orelse return; const which = floppy.map[disk.quarter()]; if (which == nothing_there) return; const into = &floppy.tracks[which]; var register = value; for (0..step.bits) |i| { const bit: u1 = if (i < 8) @truncate(register >> 7) else 0; if (!floppy.write_protected) into.setBit(disk.position, bit); register <<= 1; disk.position = (disk.position + 1) % @max(1, into.count); } disk.latch = 0; if (!floppy.write_protected and step.bits > 0) floppy.dirty = true; } /// Whether the disk in the selected drive cannot be written to. An empty /// drive answers the same way: there is nothing there to write to either. pub fn writeProtected(self: *Controller) bool { const floppy = self.current().floppy orelse return true; return floppy.write_protected; } /// Whether the disk in the selected drive can be written to. The high bit /// is set when it cannot, and an empty drive answers the same way. fn protection(self: *Controller) u8 { return if (self.writeProtected()) 0x80 else 0; } /// Turns the disk by however much time has gone by. /// /// In bits, and with the remainder kept. The remainder is not tidiness: a /// bit is about four of the machine's cycles and the read loop comes back /// every seven, so throwing away what is left over each time would lose a /// bit in every two or three and the disk would read as though it were /// turning half again too slowly. /// /// How long a bit is comes from the disk and not from here. Four /// microseconds is the rule, and `bit_timing` is what the disk in the drive /// says instead — 3.5 microseconds on one written by a drive that had been /// slowed down on purpose, which is a protection: a bit copier that wrote /// it back at four would produce something that reads differently. /// How many bit cells have passed the head since the disk was last turned, /// and how long each of its cells is. Updates the clock and the remainder, /// so calling it is turning the disk: whether those cells are then read or /// written is the caller's, since the head does one or the other but the /// disk turns the same either way. fn turned(self: *Controller, cycles: u64) struct { bits: u64, timing: u16 } { // A disk that is coasting turns up to the moment it stops and no // further, however long after that this is asked. const until = if (self.motor) cycles else @min(cycles, self.stops_at orelse 0); const elapsed = until -| self.turned_at; self.turned_at = cycles; const disk = self.current(); const timing: u64 = if (disk.floppy) |floppy| floppy.bit_timing else standard_bit_timing; // `turning` is the cycles a byte takes at the standard rate, so a bit // is an eighth of that, scaled by how this disk's cells compare with // the standard ones. const per_bit = self.turning * timing; if (per_bit == 0 or elapsed == 0) return .{ .bits = 0, .timing = @intCast(timing) }; const numerator = elapsed * 8 * standard_bit_timing + self.left_over; self.left_over = numerator % per_bit; return .{ .bits = numerator / per_bit, .timing = @intCast(timing) }; } fn spin(self: *Controller, cycles: u64) void { const step = self.turned(cycles); if (step.bits == 0) return; self.current().turn(step.bits, step.timing); } }; test "every pattern the surface can hold is legal and distinct" { var seen: [256]bool = @splat(false); var previous: u8 = 0; for (write_table) |pattern| { try testing.expect(!seen[pattern]); seen[pattern] = true; // The table is in order of the value it stands for, which is also // ascending, so a transposed pair would show up here. try testing.expect(pattern > previous); previous = pattern; // What the drive electronics need in order to stay in step with the // bits going past: the high bit set, never more than two zeroes in a // row, and at least two ones in a row somewhere. try testing.expect(pattern & 0x80 != 0); var zeroes: u8 = 0; var ones: u8 = 0; var longest_ones: u8 = 0; var bit: u4 = 8; while (bit > 0) { bit -= 1; if (pattern >> @intCast(bit) & 1 == 0) { zeroes += 1; ones = 0; try testing.expect(zeroes <= 2); } else { zeroes = 0; ones += 1; longest_ones = @max(longest_ones, ones); } } try testing.expect(longest_ones >= 2); // And none of them can be mistaken for a mark, which is what makes // the start of a field findable at all. try testing.expect(pattern != 0xd5 and pattern != 0xaa); } } test "a sector survives being encoded and read back" { var sector: [bytes_per_sector]u8 = undefined; for (§or, 0..) |*byte, i| byte.* = @truncate(i * 7 + i / 3); var encoded: [343]u8 = undefined; encodeSector(§or, &encoded); // Everything written is a pattern the surface can hold. for (encoded) |nibble| try testing.expect(read_table[nibble] != invalid); var back: [bytes_per_sector]u8 = undefined; try decodeSector(&encoded, &back); try testing.expectEqualSlices(u8, §or, &back); } test "a misread byte is caught by the checksum" { var sector: [bytes_per_sector]u8 = @splat(0x42); var encoded: [343]u8 = undefined; encodeSector(§or, &encoded); encoded[100] = write_table[(read_table[encoded[100]] + 1) % 64]; var back: [bytes_per_sector]u8 = undefined; try testing.expectError(error.BadChecksum, decodeSector(&encoded, &back)); } test "four and four holds a byte in two" { for (0..256) |value| { var pair: [2]u8 = undefined; writeFourAndFour(&pair, @intCast(value)); try testing.expectEqual(@as(u8, @intCast(value)), readFourAndFour(pair[0], pair[1])); } } test "a whole disk survives being laid out and read back" { const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); for (image, 0..) |*byte, i| byte.* = @truncate(i * 31 + i / 257); const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; try floppy.load(image, .dos); const back = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(back); @memset(back, 0); try floppy.save(back); try testing.expectEqualSlices(u8, image, back); } test "the sector order is the one the file was written in" { const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); // Mark every sector of track 0 with its own number. for (0..sectors_per_track) |sector| @memset(image[sector * bytes_per_sector ..][0..bytes_per_sector], @intCast(sector)); const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; try floppy.load(image, .dos); // Read the track back by hand: the sector the address field names is a // place on the track, and what is in it is the file's sector. var laid: [nibbles_per_track]u8 = undefined; floppy.takeNibbles(0, &laid); var at: usize = 0; var found: usize = 0; while (at < nibbles_per_track) : (at += 1) { if (!matches(&laid, at, &address_prologue)) continue; const physical = readFourAndFour(peek(&laid, at + 7), peek(&laid, at + 8)); var search = at + 11; while (!matches(&laid, search, &data_prologue)) search += 1; var field: [343]u8 = undefined; for (&field, 0..) |*byte, i| byte.* = peek(&laid, search + 3 + i); var sector: [bytes_per_sector]u8 = undefined; try decodeSector(&field, §or); try testing.expectEqual(Order.dos.logical(physical), sector[0]); found += 1; } try testing.expectEqual(@as(usize, sectors_per_track), found); } test "the head moves a half track at a time, and a quarter when two magnets pull" { var controller: Controller = .{}; const drive = controller.drive(0); try testing.expectEqual(@as(u8, 0), drive.track()); // Energising the magnets in turn walks the head inwards. The head starts // sitting at the first magnet, so the first one to move it is the second: // energising the one it is already at does nothing, which is exactly how // the ROM parks the head against the stop without counting anything. const step = struct { fn in(c: *Controller, phase: u4) void { _ = c.access(phase * 2 + 1, false, 0, 0); _ = c.access(phase * 2, false, 0, 0); } }; for (0..8) |i| step.in(&controller, @intCast((i + 1) % 4)); try testing.expectEqual(@as(u8, 16), drive.quarter_track); try testing.expectEqual(@as(u8, 4), drive.track()); // Energising the one it is already at leaves it where it is. step.in(&controller, @intCast((drive.quarter_track / 2) % 4)); try testing.expectEqual(@as(u8, 16), drive.quarter_track); // And the other way round walks it back out, no further than the edge. for (0..20) |i| step.in(&controller, @intCast((7 - i % 4) % 4)); try testing.expectEqual(@as(u8, 0), drive.quarter_track); // Nor can it be driven off the end of what a head can reach. A real drive // can be stepped some way past the last track anybody records on — it // stops when the carriage meets the stop, with the ROM's forty steps at // power-on doing exactly that — and what it finds out there is nothing, // which the disk says for itself rather than the head being stopped short. for (0..200) |i| step.in(&controller, @intCast((i + 1) % 4)); try testing.expectEqual(@as(u8, quarter_tracks - 1), drive.quarter_track); } test "reading turns the disk and hands back what goes past" { const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0x5a); try floppy.load(image, .dos); var controller: Controller = .{}; controller.insert(0, floppy); _ = controller.access(0x9, false, 0, 0); // motor on // Reading round the track hands back bytes the surface could hold, and // brings the head back to where it started. // // Not "the same byte after so many reads", which is not a thing that can // be counted: a gap is written as self-sync, ten bits to the byte rather // than eight, so how many bytes a track holds depends on how much of it is // gap — and a head that has just been put down is not in step with the // disk until a gap has gone past, so the first byte or two are two // neighbours smeared together. Both are the format working, not failing. var cycles: u64 = 100; var whole: usize = 0; var legal_bytes: usize = 0; var wrapped = false; var previous: u32 = 0; for (0..nibbles_per_track * 2) |_| { cycles += cycles_per_nibble; const value = controller.access(0xc, false, 0, cycles); const at = controller.drive(0).position; if (at < previous) wrapped = true; previous = at; if (value & 0x80 == 0) continue; whole += 1; if (legal(value)) legal_bytes += 1; } // A lap and more, so the head has been round. try testing.expect(wrapped); // Rather fewer whole bytes than reads, and that is the register working. // A finished byte is held for seven microseconds and a byte time is // thirty-two, so a sample taken once a byte time lands inside the hold // about a quarter of the time and otherwise catches the register part way // through building the next one. A real read loop comes round every seven // cycles and so misses nothing; this is sampling, not reading. try testing.expect(whole > 3000); // And what came off it is the disk rather than noise. Not every byte: the // first few after the head came down are a smear, and so is the first // after each time the processor was slow to collect one. try testing.expect(legal_bytes * 100 / whole > 95); } test "a drive with nothing in it hands back noise, not silence" { // This test used to say the opposite, and was wrong. A drive with no disk // in it is not quiet: the head hears the amplifier, which is the same // thing it hears over surface that was never recorded, and the WOZ // reference describes that as a position that "continuously output[s] // random data" (Morris, 2018). Silence is what a *disconnected* drive // gives. // // The difference is load-bearing rather than cosmetic. An Apple IIc with // the 32K ROM counts its tries at the built-in drive and hands over to the // Protocol Converter when the count runs out, but the counter only comes // round when the read loop above it finds a byte at all — so with silence // the machine can never reach a drive on its port, which is not what Apple // describes it doing (Apple Computer, Inc., n.d.-b, p. 4). var controller: Controller = .{}; _ = controller.access(0x9, false, 0, 0); // Read a while and something with its top bit set comes past, which is // what any read loop is waiting for. Bytes off blank surface are not all // the same, either, so this is not a register stuck at one value. var finished: usize = 0; var different: usize = 0; var previous: u8 = 0; for (1..64) |i| { const byte = controller.access(0xc, false, 0, i * 32); if (byte & 0x80 != 0) finished += 1; if (byte != previous) different += 1; previous = byte; } try testing.expect(finished > 0); try testing.expect(different > 1); // And it still says it cannot be written to, which is what an empty drive // reports and is decided by the tab rather than by the surface. try testing.expectEqual(@as(u8, 0x80), controller.access(0xd, false, 0, 4096) & 0x80); } test "the write protect tab is what decides whether writing lands" { const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); try floppy.load(image, .dos); var controller: Controller = .{}; controller.insert(0, floppy); _ = controller.access(0x9, false, 0, 0); // motor on // Asking is the pair the ROM uses: set the first flip flop, clear the // second, and read what comes back. _ = controller.access(0xd, false, 0, 0); try testing.expectEqual(@as(u8, 0x80), controller.access(0xe, false, 0, 0)); // Protected, so what is written goes nowhere at all. A byte is written // the way the drive writes one: the byte is loaded, and it lands over the // cells that pass the head while it shifts out, which is a byte's worth of // time — thirty-two cycles for the eight bits. var before: [nibbles_per_track]u8 = undefined; floppy.takeNibbles(0, &before); _ = controller.access(0xf, false, 0, 0); // write mode _ = controller.access(0xd, true, 0x96, 0); // load the latch _ = controller.access(0xc, false, 0, 8 * cycles_per_bit); // eight cells pass var after: [nibbles_per_track]u8 = undefined; floppy.takeNibbles(0, &after); try testing.expectEqualSlices(u8, &before, &after); try testing.expect(!floppy.dirty); // With the tab off the notch it lands, and the disk is marked as changed // so that whoever owns it knows saving it is worth doing. floppy.write_protected = false; _ = controller.access(0xd, false, 0, 8 * cycles_per_bit); _ = controller.access(0xe, false, 0, 8 * cycles_per_bit); try testing.expectEqual(@as(u8, 0), controller.access(0xe, false, 0, 8 * cycles_per_bit)); const drive = controller.drive(0); const before_position = drive.position; _ = controller.access(0xf, false, 0, 8 * cycles_per_bit); _ = controller.access(0xd, true, 0x96, 8 * cycles_per_bit); // load the byte _ = controller.access(0xc, false, 0, 16 * cycles_per_bit); // eight cells pass, it shifts out // The eight bits landed over the cells the head passed, high bit first, // starting where it was when the byte was loaded. const track = drive.under().?; var written: u8 = 0; for (0..8) |i| { written = (written << 1) | track.bit((before_position + @as(u32, @intCast(i))) % track.count); } try testing.expectEqual(@as(u8, 0x96), written); try testing.expect(floppy.dirty); } test "a second drive is only reachable when one is fitted" { var controller: Controller = .{ .fitted = 1 }; _ = controller.access(0xb, false, 0, 0); try testing.expectEqual(@as(u1, 0), controller.selected); controller.fitted = 2; _ = controller.access(0xb, false, 0, 0); try testing.expectEqual(@as(u1, 1), controller.selected); _ = controller.access(0xa, false, 0, 0); try testing.expectEqual(@as(u1, 0), controller.selected); } test "a sector written on the disk turns up in the right place in the file" { const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); // Every sector of track 3 marked with its own number, so that anything // landing in the wrong one is obvious. for (0..sectors_per_track) |sector| { @memset(image[3 * bytes_per_track + sector * bytes_per_sector ..][0..bytes_per_sector], @intCast(sector)); } const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; try floppy.load(image, .dos); // Overwrite one sector on the surface, which is what the machine does // when it writes: it finds the sector by its address field and lays a new // data field down after it. const physical = 5; var replacement: [bytes_per_sector]u8 = undefined; for (&replacement, 0..) |*byte, i| byte.* = @truncate(0xa0 + i); var three: [nibbles_per_track]u8 = undefined; var where: [nibbles_per_track]u32 = undefined; floppy.readTrack(3, &three, &where); var at: usize = 0; const found = while (at < nibbles_per_track) : (at += 1) { if (!matches(&three, at, &address_prologue)) continue; if (readFourAndFour(peek(&three, at + 7), peek(&three, at + 8)) != physical) continue; var search = at + 11; while (!matches(&three, search, &data_prologue)) search += 1; break search + data_prologue.len; } else null; var field: [343]u8 = undefined; encodeSector(&replacement, &field); for (field, 0..) |nibble, i| floppy.writeNibbleAt(3, where[found.? + i], nibble); // Saving reads the surface back, so the new bytes land in the file at the // sector the skew says that place on the track belongs to. try floppy.save(image); const logical: usize = Order.dos.logical(physical); try testing.expectEqualSlices( u8, &replacement, image[3 * bytes_per_track + logical * bytes_per_sector ..][0..bytes_per_sector], ); // And nothing else moved. for (0..sectors_per_track) |sector| { if (sector == logical) continue; const stored = image[3 * bytes_per_track + sector * bytes_per_sector ..][0..bytes_per_sector]; for (stored) |byte| try testing.expectEqual(@as(u8, @intCast(sector)), byte); } } test "a track the machine has scribbled over keeps what could still be read" { const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); for (image, 0..) |*byte, i| byte.* = @truncate(i); const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; try floppy.load(image, .dos); // Wipe a stretch of the track, as a half finished write would. @memset(floppy.tracks[7].bits[0..2000], 0xff); const saved = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(saved); @memcpy(saved, image); try floppy.save(saved); // The sectors that survived read back as they were, and the ones that did // not keep whatever the file already held rather than becoming holes. try testing.expectEqualSlices(u8, image, saved); } test "reading the register does not empty it" { const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); for (image, 0..) |*byte, i| byte.* = @truncate(i); try floppy.load(image, .dos); var controller: Controller = .{}; controller.insert(0, floppy); var cycles: u64 = 0; _ = controller.access(0x9, false, 0, cycles); // motor on // Find a whole byte, the way a read loop does. var byte: u8 = 0; while (byte & 0x80 == 0) { cycles += 7; byte = controller.access(0xc, false, 0, cycles); } // Asking again inside the seven microseconds it is held for is handed the // same byte, not a hole where it used to be. The reference set is explicit // about this: "when a program reads data from the data latch, the // implementation should not be clearing the latch." try testing.expectEqual(byte, controller.access(0xc, false, 0, cycles)); try testing.expectEqual(byte, controller.access(0xc, false, 0, cycles + 1)); // And once the hold has run out the register follows the shifter again, so // a loop that comes back later sees a part-built byte with its top bit // clear rather than the old one for ever. cycles += holding_eighths / 8 + cycles_per_bit; try testing.expectEqual(0, controller.access(0xc, false, 0, cycles) & 0x80); } test "a byte is held while the surface has nothing to replace it with" { const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; // A self-sync byte: eight ones and then the two extra zeroes that make it // ten bits long rather than eight, which is what a gap is written from. floppy.map[0] = 0; floppy.tracks[0].count = 100; @memset(&floppy.tracks[0].bits, 0); for (0..8) |i| floppy.tracks[0].setBit(@intCast(i), 1); // And then the first two bits of whatever comes after the gap. floppy.tracks[0].setBit(10, 1); floppy.tracks[0].setBit(11, 1); var drive: Drive = .{ .floppy = floppy }; // Nine rather than eight: the amplifier's window is a bit behind the // surface, so the first turn brings up a bit that is not out yet. drive.turn(9, standard_bit_timing); try testing.expectEqual(@as(u8, 0xff), drive.data); try testing.expectEqual(holding_eighths, drive.holding); // The two zeroes that follow are a gap rather than the start of the next // byte, so they do not count against the hold: there is nothing coming to // replace what the register has, and it goes on offering it. drive.turn(1, standard_bit_timing); try testing.expectEqual(@as(u8, 0xff), drive.data); try testing.expectEqual(holding_eighths, drive.holding); drive.turn(1, standard_bit_timing); try testing.expectEqual(@as(u8, 0xff), drive.data); try testing.expectEqual(holding_eighths, drive.holding); // The one bit that begins the next byte is something to replace it with, // and from there the hold runs down: seven microseconds against a four // microsecond bit is two bits and no more. drive.turn(1, standard_bit_timing); try testing.expectEqual(@as(u8, 0xff), drive.data); try testing.expect(drive.holding < holding_eighths); drive.turn(1, standard_bit_timing); try testing.expectEqual(@as(u16, 0), drive.holding); // And now the register is following the shifter again: two bits in, top // bit clear, which is what a read loop waits to stop seeing. try testing.expectEqual(@as(u8, 0b11), drive.data); } test "the drive keeps turning for a second after software says stop" { const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); for (image, 0..) |*byte, i| byte.* = @truncate(i); try floppy.load(image, .dos); var controller: Controller = .{}; controller.insert(0, floppy); var cycles: u64 = 0; _ = controller.access(0x9, false, 0, cycles); // motor on _ = controller.access(0xc, false, 0, cycles); // read mode // Somewhere in the middle of the track, so that what comes next is data // rather than the gap the head starts in. for (0..64) |_| { cycles += cycles_per_nibble; _ = controller.access(0xc, false, 0, cycles); } _ = controller.access(0x8, false, 0, cycles); // motor off try testing.expect(!controller.motor); // A second later it is still going round, and bytes still come. const second = coasting_nibbles * cycles_per_nibble; var seen: usize = 0; for (0..coasting_nibbles - 1) |_| { cycles += cycles_per_nibble; try testing.expect(controller.turningAt(cycles)); if (controller.access(0xc, false, 0, cycles) != 0) seen += 1; } try testing.expect(seen > coasting_nibbles / 2); // And it stops on the cycle the timer says, not the one after. try testing.expect(!controller.turningAt(cycles + cycles_per_nibble)); // Past the second it has stopped, and then nothing changes however long the // machine waits: no further byte arrives because nothing is going past the // head, and the one already in the register stays there. Sather on what the // card does when the drive is off (1985, Chapter 9): "DRIVES OFF forces the // data register to hold its present state." cycles += second; try testing.expect(!controller.turningAt(cycles)); const stopped = controller.access(0xc, false, 0, cycles); for (0..64) |_| { cycles += second; try testing.expectEqual(stopped, controller.access(0xc, false, 0, cycles)); } } test "a reset does not leave the drive coasting" { const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); for (image, 0..) |*byte, i| byte.* = @truncate(i); try floppy.load(image, .dos); var controller: Controller = .{}; controller.insert(0, floppy); _ = controller.access(0x9, false, 0, 0); // motor on try testing.expect(controller.turningAt(0)); // Reset clears the timer rather than starting it, so the drive stops now // and not a second from now. controller.reset(); try testing.expect(!controller.turningAt(0)); try testing.expect(!controller.turningAt(coasting_nibbles * cycles_per_nibble)); } test "a reset stops the drive but leaves the disk where it is" { const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); try floppy.load(image, .dos); var controller: Controller = .{}; controller.insert(0, floppy); _ = controller.access(0x9, false, 0, 0); // motor on _ = controller.access(0xf, false, 0, 0); // write mode _ = controller.access(0x3, false, 0, 0); // a magnet energised, head moved try testing.expect(controller.motor); try testing.expect(controller.q7); try testing.expectEqual(@as(u8, 2), controller.drive(0).quarter_track); controller.reset(); try testing.expect(!controller.motor); try testing.expect(!controller.q6); try testing.expect(!controller.q7); for (controller.drive(0).phases) |energised| try testing.expect(!energised); // The head does not move: where it is left is a mechanical matter, and // the disk is still in the drive. try testing.expectEqual(@as(u8, 2), controller.drive(0).quarter_track); try testing.expectEqual(floppy, controller.drive(0).floppy.?); } test "a disk put into the other order comes back when it is put back" { const original = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(original); for (original, 0..) |*byte, i| byte.* = @truncate(i / bytes_per_sector); const other = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(other); try reorder(original, other, .dos, .prodos); // The first sector of a track is where it was; the rest have moved. try testing.expectEqualSlices(u8, original[0..bytes_per_sector], other[0..bytes_per_sector]); try testing.expect(!std.mem.eql(u8, original, other)); const back = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(back); try reorder(other, back, .prodos, .dos); try testing.expectEqualSlices(u8, original, back); try testing.expectError(error.WrongSize, reorder(original, back[0 .. image_size - 1], .dos, .prodos)); } test "a recording of the surface goes in as it stands and comes back the same" { // The whole point of the format: nothing here understands what is on the // disk, so nothing here can lose any of it. var floppy: Floppy = .{}; var image: [Floppy.nibble_size]u8 = undefined; for (&image, 0..) |*byte, i| { // Nibbles are bytes with the high bit set and no two zero bits in a // row, but this does not check that and should not: a disk that was // protected is protected precisely by holding what a drive would not // normally write. byte.* = @intCast(0x80 | (i % 0x80)); } try floppy.loadNibbles(&image); try testing.expectEqual(image[0], floppy.nibbleAt(0, 0)); try testing.expectEqual( image[nibbles_per_track * 34 + 100], floppy.nibbleAt(34, 100), ); var back: [Floppy.nibble_size]u8 = undefined; try floppy.saveNibbles(&back); try testing.expectEqualSlices(u8, &image, &back); } test "a nibble image a drive can actually read" { // Laid out as a real disk, written out as nibbles, and read back in as a // recording: what the drive finds has to be the same disk, because that is // what a `.nib` of an unprotected disk is. var sectors: [image_size]u8 = undefined; for (§ors, 0..) |*byte, i| byte.* = @truncate(i *% 31); var described: Floppy = .{}; try described.load(§ors, .dos); var nibbles: [Floppy.nibble_size]u8 = undefined; try described.saveNibbles(&nibbles); var recorded: Floppy = .{}; try recorded.loadNibbles(&nibbles); var a: [nibbles_per_track]u8 = undefined; var b: [nibbles_per_track]u8 = undefined; described.takeNibbles(17, &a); recorded.takeNibbles(17, &b); try testing.expectEqualSlices(u8, &a, &b); // And it decodes back to the sectors it started as, which is the drive's // own decoder finding the address and data fields in what came off the // recording rather than in anything this laid out. var out: [image_size]u8 = @splat(0); recorded.order = .dos; try recorded.save(&out); try testing.expectEqualSlices(u8, §ors, &out); } test "a file that is not a whole recording is refused" { var floppy: Floppy = .{}; var short: [Floppy.nibble_size - 1]u8 = @splat(0xff); try testing.expectError(error.WrongSize, floppy.loadNibbles(&short)); var small: [16]u8 = undefined; try testing.expectError(error.WrongSize, floppy.saveNibbles(&small)); // The size is the one thing that says what a `.nib` is, so it has to be // exact: thirty-five tracks of 6,656 nibbles. try testing.expectEqual(@as(usize, 35 * 6656), Floppy.nibble_size); try testing.expectEqual(@as(usize, 232_960), Floppy.nibble_size); } test "a disk laid out here turns at three hundred revolutions a minute" { // 200 milliseconds a revolution at 1.023 MHz is 204,600 cycles; the track // is the WOZ standard's 51,200 bits at four cycles each, which is within // a tenth of a per cent of that. It used to be 6,656 nibbles, and 288 rpm. const cycles_per_revolution = @as(u64, bits_per_track) * cycles_per_bit; const want: u64 = 1_023_000 / 5; try testing.expect(cycles_per_revolution > want - want / 500); try testing.expect(cycles_per_revolution < want + want / 500); // And a disk loaded from sectors is laid out to fill exactly one // revolution, gaps and all. const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; try floppy.load(image, .dos); try testing.expect(floppy.tracks[0].count <= bits_per_track); try testing.expect(floppy.tracks[0].count > bits_per_track - 16 * self_sync_bits); try testing.expectEqual(standard_bit_timing, floppy.bit_timing); } test "a nibble file's longer track is read with a shorter bit cell, so the disk still turns at speed" { // 6,656 nibbles is a track written on a drive turning slow; on one turning // at 300 rpm its bits come off faster, which `bit_timing` is for. const image = try testing.allocator.alloc(u8, Floppy.nibble_size); defer testing.allocator.free(image); @memset(image, sync); var floppy: Floppy = .{}; try floppy.loadNibbles(image); try testing.expectEqual(@as(u8, 31), floppy.bit_timing); try testing.expectEqual(@as(u32, nibbles_per_track * 8), floppy.tracks[0].count); // The revolution that gives: within one per cent of 200 milliseconds. const cycles = @as(u64, floppy.tracks[0].count) * cycles_per_bit * floppy.bit_timing / standard_bit_timing; const want: u64 = 1_023_000 / 5; try testing.expect(cycles > want - want / 100); try testing.expect(cycles < want + want / 100); // A sector image loaded afterwards puts the timing back. const plain = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(plain); @memset(plain, 0); try floppy.load(plain, .dos); try testing.expectEqual(standard_bit_timing, floppy.bit_timing); } test "a track laid out here is longer in bits than its bytes would suggest" { // Because the gaps are self-sync: `$ff` and two bits of nothing, ten bits // to the byte. A track of the same bytes written eight bits each would be // shorter, and would be unreadable by anything that had lost its place. const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; try floppy.load(image, .dos); const track = &floppy.tracks[0]; var nibbles: [nibbles_per_track]u8 = undefined; floppy.takeNibbles(0, &nibbles); // Count the bytes the shifter got back, and compare with the bits it took // to deliver them. More than eight bits apiece means self-sync is there. var real: usize = nibbles_per_track; while (real > 0 and nibbles[real - 1] == sync) real -= 1; try testing.expect(track.count > real * 8); } test "a reader that has lost its place is put back by the gaps" { // The whole point of a self-sync byte. Start the shifter one bit late — // which is what a head being put down in the middle of a byte does — and // it should come back into step, because the extra zero bits in a gap // push it along by less than a whole byte at a time. const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; try floppy.load(image, .dos); const track = &floppy.tracks[0]; var latch: u8 = 0; var recent: [3]u8 = @splat(0); var marks: usize = 0; // Deliberately off by one bit, and round twice so that the first sector // comes past after the head has had a gap to find itself in. var at: u32 = 1; while (at < track.count * 2 + 1) : (at += 1) { latch = (latch << 1) | track.bit(at); if (latch & 0x80 == 0) continue; recent = .{ recent[1], recent[2], latch }; latch = 0; if (std.mem.eql(u8, &recent, &address_prologue)) marks += 1; } // All sixteen sectors turn up, which they could not if the reader had // stayed a bit out of step. try testing.expect(marks >= sectors_per_track); } test "a WOZ keeps its own track lengths and its own map" { // Which is the whole reason for the format: a track is however many bits // went past in one revolution, and what is at a quarter-track position is // the file's business rather than a matter of dividing by two. var file: [4096]u8 = undefined; @memset(&file, 0); @memcpy(file[0..8], &woz.woz2_magic); @memcpy(file[12..16], "INFO"); std.mem.writeInt(u32, file[16..20], 60, .little); file[20] = 2; file[21] = 1; // 5.25-inch @memcpy(file[80..84], "TMAP"); std.mem.writeInt(u32, file[84..88], woz.positions, .little); @memset(file[88..][0..woz.positions], woz.no_track); file[88] = 0; // track 0.00 only; everything else is empty @memcpy(file[248..252], "TRKS"); std.mem.writeInt(u32, file[252..256], 1280 + 512, .little); std.mem.writeInt(u16, file[256..258], 3, .little); std.mem.writeInt(u16, file[258..260], 1, .little); std.mem.writeInt(u32, file[260..264], 3000, .little); // an odd length on purpose @memset(file[1536..][0..512], 0xa5); std.mem.writeInt(u32, file[8..12], std.hash.Crc32.hash(file[woz.header_size..2048]), .little); const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; try floppy.loadWoz(try woz.open(file[0..2048])); // The track is three thousand bits, not a round number of bytes and not // padded out to one. try testing.expectEqual(@as(u32, 3000), floppy.tracks[0].count); try testing.expectEqual(@as(u8, 0), floppy.map[0]); // And the gap between tracks is empty, which is what the file says and // what a described disk cannot say at all. try testing.expectEqual(nothing_there, floppy.map[2]); try testing.expectEqual(nothing_there, floppy.map[4]); } test "a head over nothing hears noise, not silence" { // Between two tracks there is no recording, and the amplifier hears itself. // That is noise and not silence, and the difference is the whole point: a // program that steps between two tracks to see what is there gets a stream // of bytes that never mean anything, rather than a data register stuck at // zero. The WOZ reference is explicit about it (Morris, 2018). var floppy: Floppy = .{}; floppy.map = @splat(nothing_there); var controller: Controller = .{}; controller.fitted = 1; controller.insert(0, &floppy); controller.motor = true; var recent: [3]u8 = @splat(0); var marks: usize = 0; var whole: usize = 0; var seen: [256]bool = @splat(false); var cycles: u64 = 0; for (0..40_000) |_| { cycles += 4; const value = controller.readNibble(cycles); if (value & 0x80 == 0) continue; whole += 1; seen[value] = true; recent = .{ recent[1], recent[2], value }; if (std.mem.eql(u8, &recent, &address_prologue)) marks += 1; } // Bytes do come out, and they are not all the same byte: a head over // nothing that read as a stream of `$ff`, or as nothing at all, would be // something a program could recognise, and blank surface is not. try testing.expect(whole > 100); var distinct: usize = 0; for (seen) |was| { if (was) distinct += 1; } try testing.expect(distinct > 8); // And none of it is a sector: there is nothing there to find. try testing.expectEqual(@as(usize, 0), marks); } test "two magnets at once put the head between two tracks" { // Which is what a quarter track is, and what an ordinary copier — which // steps in whole tracks — can never see. var controller: Controller = .{}; const drive = controller.drive(0); // Phase 1 alone takes it to the half track between 0 and 1. _ = controller.access(0x3, false, 0, 0); try testing.expectEqual(@as(u8, 2), drive.quarter_track); // Phase 2 as well, without letting go of phase 1, and the two pull // equally: the head settles between them. _ = controller.access(0x5, false, 0, 0); try testing.expectEqual(@as(u8, 3), drive.quarter_track); // Letting go of phase 1 leaves phase 2 pulling alone, and the head // finishes the step. _ = controller.access(0x2, false, 0, 0); try testing.expectEqual(@as(u8, 4), drive.quarter_track); try testing.expectEqual(@as(u8, 1), drive.track()); } test "magnets pulling opposite ways leave the head where it is" { // A magnet exactly opposite is the same distance either way round, so it // pulls both ways at once. A model that let one direction win would step // the head for no reason. var controller: Controller = .{}; const drive = controller.drive(0); _ = controller.access(0x1, false, 0, 0); // phase 0, where it already is try testing.expectEqual(@as(u8, 0), drive.quarter_track); _ = controller.access(0x5, false, 0, 0); // and phase 2, opposite it try testing.expectEqual(@as(u8, 0), drive.quarter_track); // And with nothing energised at all it stays put, because nothing is // pulling: where a head is left is a mechanical matter. _ = controller.access(0x0, false, 0, 0); _ = controller.access(0x4, false, 0, 0); try testing.expectEqual(@as(u8, 0), drive.quarter_track); } test "asking about the write protect tab loses the byte being read" { // The two share a register, so the answer goes where the part-built byte // was. That is how a program reads the surface out of step with the bytes // written on it: ask mid-nibble, and what comes back afterwards starts // wherever the head is rather than on the boundary the last byte ended at. const floppy = try testing.allocator.create(Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); try floppy.load(image, .dos); var controller: Controller = .{}; controller.fitted = 1; controller.insert(0, floppy); _ = controller.access(0x9, false, 0, 0); // motor on _ = controller.access(0xe, false, 0, 0); // and reading // Let a byte assemble. var cycles: u64 = 0; while (true) { cycles += cycles_per_nibble; if (controller.access(0xc, false, 0, cycles) & 0x80 != 0) break; } // Part way into the next one, ask about the tab. cycles += cycles_per_nibble / 2; _ = controller.access(0xd, false, 0, cycles); // The shifter was cleared, so nothing is waiting. try testing.expectEqual(@as(u8, 0), controller.drive(0).data); try testing.expectEqual(@as(u8, 0), controller.drive(0).latch); // And reading again picks the stream up from where the head now is, which // is what makes the bytes come out shifted. _ = controller.access(0xc, false, 0, cycles); var whole: usize = 0; for (0..2000) |_| { cycles += 7; if (controller.access(0xc, false, 0, cycles) & 0x80 != 0) whole += 1; } try testing.expect(whole > 100); } test "a floppy round-trips through a snapshot, surface and all" { const alloc = testing.allocator; // A disk with recognisable bytes on a couple of its tracks. const image = try alloc.alloc(u8, image_size); defer alloc.free(image); @memset(image, 0); @memcpy(image[0..5], "HELLO"); @memcpy(image[image_size - 5 ..], "WORLD"); var original: Floppy = .{}; try original.load(image, .dos); original.write_protected = false; original.dirty = true; // Snapshot it, then read it back into a fresh drive's floppy. const bytes = try snapshot.save(alloc, &original); defer alloc.free(bytes); var restored: Floppy = .{}; try snapshot.load(alloc, bytes, &restored); // The surface is the same, bit for bit, and the flags came across. try testing.expectEqualSlices(u8, &original.tracks[0].bits, &restored.tracks[0].bits); try testing.expectEqual(original.map, restored.map); try testing.expect(!restored.write_protected); try testing.expect(restored.dirty); }