// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The Apple 3.5-inch drive, and the eight hundred kilobytes on the disk in it. //! //! A Disk II drive is four magnets and a motor, and everything clever about it //! is in the card. The 3.5-inch drive is the other way round. The card is gone //! — the IWM is the whole of it — and what is on the end of the cable is a //! mechanism with opinions: it steps its own head one track at a time when //! told to, it turns its own spindle when told to, it knows whether there is a //! disk in it and whether somebody has pressed the eject button, and it will //! answer any of fifteen questions about itself. //! //! It answers them down a single wire. The four lines that walked a Disk II's //! head — CA0, CA1, CA2 and the strobe — stop being magnets and become an //! address, and a fourth bit joins them from `$c031` to make sixteen. Set the //! address and read the IWM's status register, and bit 7 is that one //! question's answer; set the address and pulse the strobe, and the drive does //! that one thing. So a program that wants to know whether the disk is write //! protected does not read a write-protect line: it names register 6 and reads //! the sense line, which is the same wire that would have carried the answer //! to any of the other fourteen. //! //! The address is not laid out the way the lines are named, and the order was //! taken from the machine rather than from a table. The firmware's own routine //! for setting it up shifts the parameter right one bit at a time and sends //! the bits to CA2, then SEL, then CA0, then CA1, which makes the address //! //! CA1 CA0 SEL CA2 //! //! and that is `addressed` below. Both of the manual's tables agree with it //! once you notice they are printing the same four bits in two different //! column orders. //! //! Nearly every answer is upside down: a zero means yes. Zero on register 2 //! means there *is* a disk, zero on register 6 means it *is* write protected, //! zero on register 15 means a drive *is* connected. That is not a quirk of //! this model; it is how the drive drives the wire, and a program reading it //! branches on the sign bit being clear. //! //! ## The disk //! //! Eight hundred kilobytes on eighty tracks, two sides, and — the interesting //! part — a varying number of sectors per track. A disk turns at one speed on //! an Apple II, so the outer tracks, which are longer, hold exactly as much as //! the inner ones and most of the surface is wasted. A 3.5-inch drive changes //! the *speed* instead, five times across the disk, so that the surface goes //! past the head at the same rate wherever the head is. That buys four extra //! sectors on the outermost sixteen tracks and one fewer on each zone inward, //! which is where 800K rather than 640K comes from. //! //! The encoding is the same six-and-two the Disk II uses, over the same //! sixty-four patterns, because it is the same constraint: no more than two //! zeroes in a row and the top bit always set. What differs is what is done //! before the encoding, and it is not simple. Three bytes go to four: the low //! six bits of each, and a fourth holding the three pairs of top bits. And //! running through it are three checksums that are not checksums of the data //! but of each other's running totals, each byte leaving as itself exclusive //! ORed with one of them, with a carry chained from one to the next and the //! third rotating a bit round every three bytes. Apple patented it (US //! 4,564,941) on the grounds that the rotation stops an error in one byte //! cancelling an error in another. The algorithm here is the one Apple prints //! in the SWIM Chip User's Reference (Apple Computer, Inc., 1988), in the form //! given there for *reading*, because that is the form the firmware runs and //! this has to agree with it byte for byte or nothing will read. //! //! References: the Hardware Reference, chapter 7, for the disk port (Apple //! Computer, Inc., 1989); Neil Parker's "Controlling the 3.5 Drive Hardware //! on the Apple IIGS" for the fifteen registers, which no Apple manual sets out //! (Parker, 1994); and the SWIM Chip User's Reference for the track layout and //! the nibblising (Apple Computer, Inc., 1988). const std = @import("std"); const disk2 = @import("disk2.zig"); /// Eighty tracks, and both sides of every one of them. pub const tracks_per_side = 80; pub const sides = 2; /// Five hundred and twelve bytes to a sector, which is a ProDOS block: this /// disk arrived after ProDOS did and is not pretending to be a 5.25. pub const bytes_per_sector = 512; /// And twelve more that the operating system may use for its own purposes. /// The Macintosh filing system kept file numbers and block numbers in them so /// that a crashed disk could be pieced back together. ProDOS uses them for /// nothing and writes zeroes, which is what a disk made here holds. pub const tag_bytes = 12; /// What a whole sector is once the tags are counted, and what goes through the /// nibbliser. pub const sector_bytes = tag_bytes + bytes_per_sector; pub const blocks_per_disk = 1600; pub const image_size = blocks_per_disk * bytes_per_sector; /// How many sectors are on a track, which is the whole trick of the format. /// /// Sixteen tracks to a zone and one sector fewer in each zone inward: twelve, /// eleven, ten, nine, eight (Apple Computer, Inc., 1988, "GCR Track Format"). pub fn sectorsOn(track: u8) u8 { return 12 - @as(u8, @intCast(@min(track, tracks_per_side - 1) / 16)); } /// How many sectors there are on one side of everything before this track. pub fn sectorsBefore(track: u8) u16 { var total: u16 = 0; for (0..track) |earlier| total += sectorsOn(@intCast(earlier)); return total; } /// Where a ProDOS block sits on the disk. /// /// Blocks fill a track's first side and then its second before moving inward, /// which is why the two sides of a track are next to each other in an image /// file and the two halves of the disk are not. pub const Where = struct { track: u8, side: u1, sector: u8 }; pub fn locate(block: u16) Where { var track: u8 = 0; var remaining = block; while (track < tracks_per_side) : (track += 1) { const on_track = @as(u16, sectorsOn(track)) * sides; if (remaining < on_track) break; remaining -= on_track; } const per_side = sectorsOn(track); return .{ .track = track, .side = if (remaining >= per_side) 1 else 0, .sector = @intCast(remaining % per_side), }; } /// Which block is at a place, which is the question above asked backwards. pub fn blockAt(track: u8, side: u1, sector: u8) u16 { return sectorsBefore(track) * sides + @as(u16, side) * sectorsOn(track) + sector; } /// How many encoded bytes one sector takes up on the surface. /// /// The fields themselves come to 727 bytes, and a formatter leaves the rest as /// filler so that the sectors are evenly spaced round the track. /// /// This was 770 for a long while, worked out from the drive's nominal figures: /// the bits go past at about 489.6 kilobits a second whatever zone the head is /// in, and a twelve-sector track turns at about 398 revolutions a minute, /// which is 9,230 bytes to share between twelve sectors. That is the right /// arithmetic on numbers that are only ever quoted as "about", and it is /// twenty-five bytes a sector short of what the machine actually does. /// /// The firmware settled it, as it usually does. Watching a IIgs format a disk /// and looking at where it put the address marks gives 714, 1509, 2304, 3099 /// and so on: **795 apart**, twelve of them, 9,540 to the track. With a /// seven-hundred-and-seventy byte slot the twelfth sector wrapped onto the /// first and the verify that follows found eleven address marks where it had /// written twelve. An eight-sector track is the same 795 a sector, which is /// the point of varying the speed at all. pub const nibbles_per_sector = 795; /// The whole surface, both sides, laid out sector slot by sector slot in the /// order the blocks are numbered. A track's slots are contiguous, which is /// what `trackAt` hands back. pub const nibbles_per_disk = blocks_per_disk * nibbles_per_sector; /// The interleave a IIgs writes when it formats a disk for itself. /// /// Consecutive blocks are not next to each other on the track: four slots /// apart, so that a driver has time to deal with one sector before the next /// one it wants comes round. A Macintosh formats the same disk two apart, /// which is the other value the format byte can carry. pub const interleave = 4; /// The format byte in every address field, which says how the disk was laid /// out. Bit 5 set is the drive telling the firmware there are two sides; /// the low bits are the interleave above. `$22` is a Macintosh's; `$24` is /// what a IIgs writes and so is what is written here. pub const format_byte: u8 = 0x24; /// The marks. They are the three patterns deliberately left out of the /// six-and-two table, so they cannot occur in data and can be searched for. /// The address mark is the Disk II's; the data mark is not, which is how a /// drive reading the wrong kind of disk finds nothing rather than nonsense. const address_prologue = [_]u8{ 0xd5, 0xaa, 0x96 }; const data_prologue = [_]u8{ 0xd5, 0xaa, 0xad }; const epilogue = [_]u8{ 0xde, 0xaa }; const sync: u8 = 0xff; /// How many encoded bytes the data field's payload comes to. /// /// Five hundred and twenty-four bytes in groups of three, and 524 does not /// divide by three: a hundred and seventy-four whole groups make 696 bytes and /// the two left over make three more. Then the three checksums, which are one /// more group of three and so four bytes. pub const data_nibbles = 699; pub const checksum_nibbles = 4; /// Where a physical slot's fields begin, measured from the start of the slot. /// Everything before this is filler, and there is more of it than the six /// self-sync bytes the manual's diagram shows because the slack between /// sectors has to go somewhere. const fixed_nibbles = 3 + 5 + epilogue.len + 1 + 6 + 3 + 1 + data_nibbles + checksum_nibbles + epilogue.len + 1; const leading_sync = nibbles_per_sector - fixed_nibbles; comptime { // A slot has to be long enough to hold what goes in it, with room left // over for the filler that spaces the sectors out. std.debug.assert(leading_sync >= 6); } /// One disk: every track of both sides, encoded as a drive would find them. pub const Floppy = struct { nibbles: [nibbles_per_disk]u8 = undefined, /// Whether the shutter is over the write-protect hole. A drive can tell, /// and the firmware asks before it writes. write_protected: bool = true, /// Whether anything has been written since it was loaded. dirty: bool = false, pub const LoadError = error{WrongSize}; /// Lays out a whole disk image as a drive would find it. /// /// The image is eight hundred kilobytes of blocks laid end to end, which /// is what a `.po` file holds and what is inside a `.2mg` file, and the /// header on one of those is stepped over here rather than by the caller, /// since it is the only wrapper these disks come in. pub fn load(self: *Floppy, image: []const u8) LoadError!void { const blocks = try unwrap(image); self.dirty = false; @memset(&self.nibbles, sync); var block: u16 = 0; while (block < blocks_per_disk) : (block += 1) { const where = locate(block); const from = blocks[@as(usize, block) * bytes_per_sector ..][0..bytes_per_sector]; self.writeSector(where, from); } } /// Puts the disk back into the plain form a file holds. /// /// Every sector is found again by reading round the track for its 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 whose checksums /// do not come out, is left as it was in the image handed in. pub fn save(self: *const Floppy, image: []u8) LoadError!void { if (image.len != image_size) return error.WrongSize; var block: u16 = 0; while (block < blocks_per_disk) : (block += 1) { const where = locate(block); const into = image[@as(usize, block) * bytes_per_sector ..][0..bytes_per_sector]; self.readSector(where, into); } } /// One track of one side, as a run of bytes going past the head. pub fn trackAt(self: *Floppy, track: u8, side: u1) []u8 { const first = blockAt(track, side, 0); const count = sectorsOn(track); return self.nibbles[@as(usize, first) * nibbles_per_sector ..][0 .. @as(usize, count) * nibbles_per_sector]; } fn constTrackAt(self: *const Floppy, track: u8, side: u1) []const u8 { const first = blockAt(track, side, 0); const count = sectorsOn(track); return self.nibbles[@as(usize, first) * nibbles_per_sector ..][0 .. @as(usize, count) * nibbles_per_sector]; } /// How long a track is, which depends on which zone it is in. pub fn trackLength(track: u8) u16 { return @as(u16, sectorsOn(track)) * nibbles_per_sector; } /// The byte under the head. pub fn byteAt(self: *const Floppy, track: u8, side: u1, position: u16) u8 { const surface = self.constTrackAt(track, side); return surface[position % surface.len]; } /// And what goes down under it, if the shutter allows. pub fn writeAt(self: *Floppy, track: u8, side: u1, position: u16, value: u8) void { if (self.write_protected) return; const surface = self.trackAt(track, side); surface[position % surface.len] = value; self.dirty = true; } fn writeSector(self: *Floppy, where: Where, from: *const [bytes_per_sector]u8) void { const surface = self.trackAt(where.track, where.side); const slot = physicalSlot(sectorsOn(where.track), where.sector); const into = surface[@as(usize, slot) * nibbles_per_sector ..][0..nibbles_per_sector]; @memset(into, sync); var at: usize = leading_sync; @memcpy(into[at..][0..3], &address_prologue); at += 3; // The track number is eleven bits split across two of the five: the // low six here and the top five in the side byte, which also carries // which side this is. Eighty tracks needs seven of the eleven; the // rest are there because the Macintosh's drives were the same drives. const low: u8 = where.track & 0x3f; const side: u8 = @as(u8, where.side) << 5 | where.track >> 6; const address = [_]u8{ low, where.sector, side, format_byte }; var check: u8 = 0; for (address) |byte| { into[at] = disk2.write_table[byte & 0x3f]; check ^= byte; at += 1; } into[at] = disk2.write_table[check & 0x3f]; at += 1; @memcpy(into[at..][0..epilogue.len], &epilogue); at += epilogue.len + 1 + 6; @memcpy(into[at..][0..3], &data_prologue); at += 3; into[at] = disk2.write_table[where.sector & 0x3f]; at += 1; // Twelve tag bytes, which nothing here has anything to put in, and // then the block itself. var payload: [sector_bytes]u8 = @splat(0); @memcpy(payload[tag_bytes..], from); nibblise(&payload, into[at..][0 .. data_nibbles + checksum_nibbles]); at += data_nibbles + checksum_nibbles; @memcpy(into[at..][0..epilogue.len], &epilogue); } fn readSector(self: *const Floppy, where: Where, into: *[bytes_per_sector]u8) void { const surface = self.constTrackAt(where.track, where.side); var at: usize = 0; while (at < surface.len) : (at += 1) { if (!matches(surface, at, &address_prologue)) continue; var field: [5]u8 = undefined; var bad = false; for (&field, 0..) |*byte, i| { const value = disk2.read_table[peek(surface, at + 3 + i)]; if (value == disk2.invalid) bad = true; byte.* = value; } if (bad) continue; if (field[0] ^ field[1] ^ field[2] ^ field[3] != field[4]) continue; if (field[1] != where.sector) continue; // The data field follows within a sector's worth of bytes, and // finding it is a matter of reading forward for its own mark. var from = at + 3 + 5 + epilogue.len; const limit = at + nibbles_per_sector; while (from < limit and !matches(surface, from, &data_prologue)) from += 1; if (from >= limit) return; from += 3 + 1; var payload: [sector_bytes]u8 = undefined; var encoded: [data_nibbles + checksum_nibbles]u8 = undefined; for (&encoded, 0..) |*byte, i| byte.* = peek(surface, from + i); if (denibblise(&encoded, &payload)) { @memcpy(into, payload[tag_bytes..]); } return; } } }; /// Steps over a `.2mg` header, if there is one, and checks the size. /// /// A `.2mg` file is the blocks with a sixty-four byte preamble in front of /// them saying what they are, and it is the form an 800K disk is usually kept /// in, because a bare `.po` of this size is indistinguishable from a hard disk /// image of the same size. fn unwrap(image: []const u8) Floppy.LoadError![]const u8 { if (image.len == image_size) return image; if (image.len > 64 and std.mem.eql(u8, image[0..4], "2IMG")) { const offset = std.mem.readInt(u32, image[32..36], .little); const length = std.mem.readInt(u32, image[36..40], .little); if (length != image_size or offset + length > image.len) return error.WrongSize; return image[offset..][0..image_size]; } return error.WrongSize; } /// Which physical slot round the track a logical sector was written into. /// /// The rule is the one a formatter follows: walk round the track dropping /// sectors in order, stepping `interleave` slots between each and taking the /// next free slot when the one landed on is taken. On a twelve-sector track /// that gives 0 3 6 9 1 4 7 10 2 5 8 11, which is what a IIgs writes. pub fn physicalSlot(count: u8, sector: u8) u8 { var taken: [12]bool = @splat(false); var slot: u8 = 0; var next: u8 = 0; for (0..count) |logical| { while (taken[next]) next = (next + 1) % count; taken[next] = true; if (logical == sector) slot = next; next = (next + interleave) % count; } return slot; } fn peek(surface: []const u8, at: usize) u8 { return surface[at % surface.len]; } fn matches(surface: []const u8, at: usize, pattern: []const u8) bool { for (pattern, 0..) |byte, i| if (peek(surface, at + i) != byte) return false; return true; } /// Adds with a carry in and a carry out, which is what the checksums are /// chained together by and what a processor does in one instruction. fn addCarrying(total: u8, byte: u8, carry_in: u1) struct { u8, u1 } { const sum = @as(u16, total) + byte + carry_in; return .{ @truncate(sum), @truncate(sum >> 8) }; } /// Turns 524 bytes into 703 that a drive can write, and works out the three /// checksums on the way. /// /// The algorithm is Apple's, from the SWIM Chip User's Reference (Apple /// Computer, Inc., 1988), and it is the *reading* form of it because that is /// the form the firmware runs: rotate the third checksum, then for each of the /// three bytes in turn exclusive-OR it with one of the checksums and add it /// into another, carrying from one addition to the next. Written this way round /// the encoder is the exact inverse of the decoder, which is the only property /// that matters — the two have to agree about the last group, which has two /// bytes in it rather than three, and about how many times the rotation has /// happened by the end. fn nibblise(source: *const [sector_bytes]u8, into: []u8) void { var sum_a: u8 = 0; var sum_b: u8 = 0; var sum_c: u8 = 0; var carry: u1 = 0; var at: usize = 0; var i: usize = 0; while (i < source.len) : (i += 3) { carry = @truncate(sum_c >> 7); sum_c = sum_c << 1 | sum_c >> 7; const plain_a = source[i]; const a = plain_a ^ sum_c; sum_a, carry = addCarrying(sum_a, plain_a, carry); const plain_b = source[i + 1]; const b = plain_b ^ sum_a; sum_b, carry = addCarrying(sum_b, plain_b, carry); // The last group is two bytes rather than three, since 524 does not // divide by three, and it writes three bytes rather than four. const whole = i + 2 < source.len; var c: u8 = 0; if (whole) { const plain_c = source[i + 2]; c = plain_c ^ sum_b; sum_c, carry = addCarrying(sum_c, plain_c, carry); } into[at] = disk2.write_table[gathered(a, b, c)]; into[at + 1] = disk2.write_table[a & 0x3f]; into[at + 2] = disk2.write_table[b & 0x3f]; at += 3; if (whole) { into[at] = disk2.write_table[c & 0x3f]; at += 1; } } // And the three checksums, as one more group of three, with nothing // further done to them. into[at] = disk2.write_table[gathered(sum_a, sum_b, sum_c)]; into[at + 1] = disk2.write_table[sum_a & 0x3f]; into[at + 2] = disk2.write_table[sum_b & 0x3f]; into[at + 3] = disk2.write_table[sum_c & 0x3f]; } /// The fourth byte of a group: the two top bits of each of the three, which /// are the bits that will not fit in six. fn gathered(a: u8, b: u8, c: u8) u8 { return (a >> 6) << 4 | (b >> 6) << 2 | c >> 6; } /// The same in reverse, answering whether the checksums came out. fn denibblise(encoded: *const [data_nibbles + checksum_nibbles]u8, into: *[sector_bytes]u8) bool { var sum_a: u8 = 0; var sum_b: u8 = 0; var sum_c: u8 = 0; var carry: u1 = 0; var at: usize = 0; var i: usize = 0; while (i < into.len) : (i += 3) { carry = @truncate(sum_c >> 7); sum_c = sum_c << 1 | sum_c >> 7; const whole = i + 2 < into.len; const top = disk2.read_table[encoded[at]]; const six_a = disk2.read_table[encoded[at + 1]]; const six_b = disk2.read_table[encoded[at + 2]]; const six_c = if (whole) disk2.read_table[encoded[at + 3]] else 0; if (top == disk2.invalid or six_a == disk2.invalid or six_b == disk2.invalid or six_c == disk2.invalid) return false; at += if (whole) 4 else 3; const plain_a = (six_a | (top >> 4 & 0x03) << 6) ^ sum_c; into[i] = plain_a; sum_a, carry = addCarrying(sum_a, plain_a, carry); const plain_b = (six_b | (top >> 2 & 0x03) << 6) ^ sum_a; into[i + 1] = plain_b; sum_b, carry = addCarrying(sum_b, plain_b, carry); if (whole) { const plain_c = (six_c | (top & 0x03) << 6) ^ sum_b; into[i + 2] = plain_c; sum_c, carry = addCarrying(sum_c, plain_c, carry); } } const top = disk2.read_table[encoded[at]]; const check_a = disk2.read_table[encoded[at + 1]]; const check_b = disk2.read_table[encoded[at + 2]]; const check_c = disk2.read_table[encoded[at + 3]]; if (top == disk2.invalid or check_a == disk2.invalid or check_b == disk2.invalid or check_c == disk2.invalid) return false; return sum_a == check_a | (top >> 4 & 0x03) << 6 and sum_b == check_b | (top >> 2 & 0x03) << 6 and sum_c == check_c | (top & 0x03) << 6; } /// How many of the machine's cycles one encoded byte takes to pass the head. /// /// A 3.5-inch drive does its I/O twice as fast as a 5.25: two microseconds to /// the bit rather than four, so sixteen to the byte rather than thirty-two. /// The default is in an Apple II's cycles, the same unit `disk2` counts in, /// and a machine with a faster clock scales it — see `Controller.turning`. pub const cycles_per_nibble = 16; /// How long the head takes to move one track, which the manual gives as about /// twelve milliseconds and which a program is expected to wait out by asking /// the drive whether it has finished. pub const cycles_per_step = 12_000; /// How long the spindle takes to come up to speed. Half a second is what the /// mechanism wants, and the firmware waits for the drive to say it is ready /// rather than counting, which is what makes this worth modelling at all. pub const cycles_per_spinup = 500_000; /// Which of the sixteen registers the lines are naming. The order is the /// firmware's — see the header. pub const Register = enum(u4) { /// Reading: which way the head will step. Strobing: set it to step inward. direction_in = 0x0, /// Reading: one bit of what is going past the lower head, and the drive /// starts using that head. Strobing: set the direction outward. lower_head = 0x1, /// Reading: whether the drive is empty. disk_in_place = 0x2, /// Reading: the upper head, and the drive starts using it. Strobing: /// forget that the disk was ever taken out. upper_head = 0x3, /// Reading: whether the head has stopped moving. Strobing: move it one /// track in whichever direction was set. step = 0x4, /// Reading: whether the disk can be written to. write_protect = 0x6, /// Reading: whether the spindle is turning. Strobing: start it. motor_on = 0x8, /// Reading: whether the drive has two heads. Strobing: stop the spindle. motor_off = 0x9, /// Reading: whether the head is at track zero. track_zero = 0xa, /// Reading: whether the drive is ready to be read from. ready = 0xb, /// Reading: whether somebody has pressed the eject button. switched = 0xc, /// Strobing: eject the disk. eject = 0xd, /// Reading: sixty pulses a revolution, which is how a drive's speed is /// measured. tachometer = 0xe, /// Reading: whether there is a drive on the end of the cable at all. installed = 0xf, _, /// What to call it. Three of the sixteen have no documented meaning and /// the firmware never asks for them, so they have no name here either. pub fn name(self: Register) []const u8 { inline for (@typeInfo(Register).@"enum".fields) |field| { if (@intFromEnum(self) == field.value) return field.name; } return "undocumented"; } }; /// One 3.5-inch drive: what is in it, where its head is, and what it is doing. pub const Drive = struct { floppy: ?*Floppy = null, /// Whether there is a drive on this connector at all. Unlike a Disk II's /// two, which a card cannot tell apart from empty ones, a 3.5-inch drive /// answers a register to say it is there — so an absent one is a thing /// software can find out about, and has to be modelled as absent rather /// than as present and empty. fitted: bool = true, /// Which of the eighty tracks the head is over. There are no half tracks: /// the drive steps whole ones when it is told to, and nothing outside it /// knows how that is done. track: u8 = 0, /// How far round the disk has turned, as a position in the encoded track. position: u16 = 0, /// Whether the spindle is running. On a Disk II the enable line and the /// motor are the same thing; here they are not, and a drive can be /// selected, lit up and holding the disk with the disk standing still. spindle: bool = false, /// Which way the next step goes. Inward is toward the higher-numbered /// tracks, which on this disk are the ones nearer the middle. outward: bool = false, /// When the head stops moving, and when the spindle is up to speed. settled_at: u64 = 0, ready_at: u64 = 0, /// Whether the disk has been taken out since anything last asked. It is /// cleared by a control function rather than by reading it, so that a /// program which was in the middle of something finds out that the disk /// under it changed. switched: bool = false, pub fn eject(self: *Drive) ?*Floppy { const out = self.floppy; self.floppy = null; if (out != null) self.switched = true; return out; } }; /// The disk port's 3.5-inch half: two drives and the lines that reach them. /// /// The four lines and the enable and select latches are the IWM's, not the /// drive's, and the IWM hands them down here on the way to whichever drive is /// listening. What is kept here is the state they leave behind. pub const Controller = struct { drives: [2]Drive = .{ .{}, .{} }, selected: u1 = 0, /// The enable line: the light, the disk held in place, and the drive /// listening. Not the spindle, which is a control function. enabled: bool = false, /// CA0, CA1, CA2 and the strobe, in that order, which is the order the /// four addresses at `$c0e0` to `$c0e7` come in. lines: [4]bool = @splat(false), /// The fourth address bit, which does not live in the chip at all: it is /// bit 7 of the Disk Interface register at `$c031`, and the firmware sets /// it in the middle of setting the other three. sel: bool = false, /// The cycle the disk was last turned to. turned_at: u64 = 0, /// The three times above, in whatever cycles the machine counts. turning: u64 = cycles_per_nibble, stepping: u64 = cycles_per_step, spinning_up: u64 = cycles_per_spinup, /// How many bytes have gone past the head, how many have gone down under /// it, and how many things the drive has been told to do. None of them is /// anything the hardware keeps; they are /// here so that something outside can tell a drive that was used from one /// that was merely plugged in, which with a port this quiet is otherwise /// difficult to see. read: u64 = 0, written: u64 = 0, commanded: u64 = 0, pub fn drive(self: *Controller, which: u1) *Drive { return &self.drives[which]; } pub fn current(self: *Controller) *Drive { return &self.drives[self.selected]; } pub fn insert(self: *Controller, which: u1, floppy: *Floppy) void { self.drives[which].floppy = floppy; self.drives[which].switched = true; } pub fn eject(self: *Controller, which: u1) ?*Floppy { return self.drives[which].eject(); } /// Which register the lines are naming: CA1, CA0, SEL, CA2, high bit /// first. See the header for where that order comes from. pub fn addressed(self: *const Controller) Register { const ca0: u4 = @intFromBool(self.lines[0]); const ca1: u4 = @intFromBool(self.lines[1]); const ca2: u4 = @intFromBool(self.lines[2]); const sel: u4 = @intFromBool(self.sel); return @enumFromInt(ca1 << 3 | ca0 << 2 | sel << 1 | ca2); } /// Sets one of the four lines, and does the thing if it was the strobe. /// /// A control function happens when the strobe goes up, and the three /// lines and SEL have been set to name it beforehand. Nothing happens when /// it goes down again, which is why the firmware's routine for this is two /// instructions: strobe on, strobe off. pub fn line(self: *Controller, which: u2, on: bool, cycles: u64) void { const rising = which == 3 and on and !self.lines[3]; self.lines[which] = on; if (rising) self.strobe(cycles); } /// What the drive does when the strobe goes up. fn strobe(self: *Controller, cycles: u64) void { if (!self.enabled) return; const disk = self.current(); if (!disk.fitted) return; self.commanded += 1; switch (self.addressed()) { .direction_in => disk.outward = false, .lower_head => disk.outward = true, .upper_head => disk.switched = false, .step => { if (disk.outward) { if (disk.track > 0) disk.track -= 1; } else { if (disk.track + 1 < tracks_per_side) disk.track += 1; } disk.settled_at = cycles + self.stepping; }, .motor_on => { disk.spindle = true; disk.ready_at = cycles + self.spinning_up; // Nothing has been turning while the spindle was off, so // where the disk had got to is no longer a measure of // anything. self.turned_at = cycles; }, .motor_off => disk.spindle = false, .eject => { _ = disk.eject(); // The manual says this takes about half a second and that the // drive may ignore further commands until it is done. Nothing // waits on that, so nothing here counts it. }, else => {}, } } /// The sense line: the answer to whichever of the fifteen questions the /// lines are naming. /// /// Nearly all of them read the wrong way up, a zero meaning yes, which is /// what the drive does with the wire and not a mistake here. pub fn sense(self: *Controller, cycles: u64) bool { const disk = self.current(); // A connector with nothing on it says so, and says nothing else. if (!disk.fitted) return true; return switch (self.addressed()) { .direction_in => disk.outward, // These two are not a choice but a place to look: they are the // same signal off the two heads, and which one the lines are // naming is which head SEL has already picked. What comes back is // a bit of the raw stream, and every byte that can be written to // a disk has its top bit set. See `head`. .lower_head, .upper_head => true, .disk_in_place => disk.floppy == null, .step => cycles >= disk.settled_at, .write_protect => !self.writeProtected(), .motor_on => !disk.spindle, // Every 3.5-inch drive an Apple II could have had was double // sided; the single-sided 400K one was a Macintosh's. .motor_off => true, .track_zero => disk.track != 0, .ready => !self.ready(cycles), // The one that is not upside down, which took finding. Parker // is the only writer to describe this register and has it the // other way about — "0 = user ejected disk by pressing the eject // button, 1 = disk not ejected" — but he marks it as used by the // IIgs ROM and documented in no publication available to him, and // says only that he is "fairly certain" of it. The ROM settles // it against him. At `$ff/5f3b` it walks a three-entry table at // `$ff/5f75`, `06 02 0c`, reading each register through STAT35 at // `$ff/5fa4` and rotating each answer's bit 7 into `$68`; three // rotations leave register 12's bit at bit 5. Then `$ff/5f5b` // does `AND #$20` and, when that comes back set, strobes register // 3 to clear the latch and loads `#$2e` — ProDOS's disk-switched // error. A one there is the disk having been switched. // // The same routine reads registers 2 and 6 in the polarity Parker // gives them, so this is not a house convention misread: it is // one register he had upside down, and it is the one he hedged. .switched => disk.switched, .tachometer => self.tachometer(cycles), .installed => false, // Three of the sixteen are not documented anywhere and the // firmware does not ask for them. They answer no, which is what // an undriven line pulled up reads as. else => true, }; } /// Whether the drive will let anything be read off it yet: the spindle up /// to speed and the head no longer moving. The firmware waits for this /// before it goes looking for an address field, and a drive that said yes /// while the head was still travelling would have it reading the wrong /// track. pub fn ready(self: *Controller, cycles: u64) bool { const disk = self.current(); if (disk.floppy == null or !disk.spindle) return false; return cycles >= disk.settled_at and cycles >= disk.ready_at; } /// 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; } /// Sixty pulses a revolution, which is how the drive tells whoever is /// asking how fast it is turning. Reading it repeatedly and counting the /// edges against the clock is how the speed of a zone gets measured. /// /// The number is Apple's own: "the TACH line produces 60 pulses for each /// rotation of the drive motor", in the disk chapter of Inside Macintosh /// (Apple Computer, Inc., 1985c), which is the same Sony mechanism this /// drive is. A pulse is a high and a low, so a revolution is a hundred and /// twenty half-periods. fn tachometer(self: *Controller, cycles: u64) bool { const disk = self.current(); if (!disk.spindle) return false; _ = cycles; const length = Floppy.trackLength(disk.track); return (@as(u32, disk.position) * 120 / length) & 1 == 1; } /// Which of the two heads is against the surface, which is SEL and /// nothing else. /// /// SEL is not one of the phase lines: it is a latched output of the host — /// bit 7 of `$c031` on a IIgs, `HDSEL` out of the glue chip on a IIc Plus, /// VIA1 PA5 on a Macintosh, where the disk chip's own `HDSEL` pin is left /// unconnected and the VIA's line goes to the drive instead (Apple /// Computer, Inc., 1990, Figures 9-10 and 9-13, pp. 351 and 354). The /// firmware sets it, holds it for as long as it is working on that side, /// and the drive connects that head to the read amplifier and the write /// driver alike. /// /// It is *also* the fourth bit of the register address, which is what made /// this look like a latch: registers 1 and 3 differ in nothing else, and /// Apple names them "RDDATA0, read data, lower head" and "RDDATA1, read /// data, upper head" (Apple Computer, Inc., 1985c, p. III-35). Modelling /// that as a read that *sets* the head is a stronger claim than the table /// makes, and it is wrong in a way only writing shows: over a IIc Plus's /// format the firmware holds SEL still for a whole track at a time and /// changes it exactly twice per track, but sense reads on register 1 /// land in the middle of every one of those runs. Latching pulled the head /// back to the lower side before each byte went down and half the disk was /// never written. Nothing in either the read table or the write table /// needs a latch: every control register is written with SEL low (p. /// III-35), so SEL is never spent on addressing one and is free to be the /// head select the whole time. pub fn head(self: *const Controller) u1 { return @intFromBool(self.sel); } /// One byte past the head, reading. pub fn readNibble(self: *Controller, cycles: u64) u8 { self.spin(cycles); const disk = self.current(); if (!disk.spindle) return 0; const floppy = disk.floppy orelse return 0; self.read += 1; return floppy.byteAt(disk.track, self.head(), disk.position); } /// And one byte going down under it. pub fn writeNibble(self: *Controller, cycles: u64, value: u8) void { self.spin(cycles); const disk = self.current(); if (!disk.spindle) return; const floppy = disk.floppy orelse return; self.written += 1; floppy.writeAt(disk.track, self.head(), disk.position, value); } /// Turns the disk by however much time has gone by, and never by nothing: /// handing back the same byte twice because no time had passed would give /// a read loop the same byte twice over. fn spin(self: *Controller, cycles: u64) void { const elapsed = cycles -| self.turned_at; self.turned_at = cycles; const disk = self.current(); if (!disk.spindle) return; const by = @max(1, elapsed / self.turning); const length = Floppy.trackLength(disk.track); disk.position = @intCast((disk.position + by) % length); } /// What the reset line does. The lines and the latches are the chip's and /// the bus clears them; the spindle stops with them, since the line that /// would keep it running is gone. 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.enabled = false; self.lines = @splat(false); self.sel = false; for (&self.drives) |*disk| disk.spindle = false; } }; const snapshot = @import("snapshot.zig"); const testing = std.testing; test "the zones put eight hundred sectors on a side" { var total: u16 = 0; for (0..tracks_per_side) |track| total += sectorsOn(@intCast(track)); try testing.expectEqual(@as(u16, 800), total); try testing.expectEqual(@as(u16, 1600), total * sides); // Sixteen tracks to a zone, one sector fewer in each zone inward. try testing.expectEqual(@as(u8, 12), sectorsOn(0)); try testing.expectEqual(@as(u8, 12), sectorsOn(15)); try testing.expectEqual(@as(u8, 11), sectorsOn(16)); try testing.expectEqual(@as(u8, 9), sectorsOn(63)); try testing.expectEqual(@as(u8, 8), sectorsOn(64)); try testing.expectEqual(@as(u8, 8), sectorsOn(79)); } test "a block knows where it is and a place knows which block it is" { // Both sides of a track before the head moves inward. try testing.expectEqual(Where{ .track = 0, .side = 0, .sector = 0 }, locate(0)); try testing.expectEqual(Where{ .track = 0, .side = 0, .sector = 11 }, locate(11)); try testing.expectEqual(Where{ .track = 0, .side = 1, .sector = 0 }, locate(12)); try testing.expectEqual(Where{ .track = 1, .side = 0, .sector = 0 }, locate(24)); // And across a zone boundary, where the tracks get shorter. try testing.expectEqual(Where{ .track = 16, .side = 0, .sector = 0 }, locate(384)); try testing.expectEqual(Where{ .track = 79, .side = 1, .sector = 7 }, locate(1599)); var block: u16 = 0; while (block < blocks_per_disk) : (block += 1) { const where = locate(block); try testing.expectEqual(block, blockAt(where.track, where.side, where.sector)); } } test "the interleave puts consecutive sectors four slots apart" { // Which is what a IIgs writes, and gives 0 3 6 9 1 4 7 10 2 5 8 11 round // a twelve-sector track. const expected = [12]u8{ 0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11 }; for (expected, 0..) |slot, sector| { try testing.expectEqual(slot, physicalSlot(12, @intCast(sector))); } // Every sector lands somewhere, and no two land in the same place. for ([_]u8{ 8, 9, 10, 11, 12 }) |count| { var seen: [12]bool = @splat(false); for (0..count) |sector| { const slot = physicalSlot(count, @intCast(sector)); try testing.expect(slot < count); try testing.expect(!seen[slot]); seen[slot] = true; } } } test "a sector survives being nibblised and read back" { var payload: [sector_bytes]u8 = undefined; for (&payload, 0..) |*byte, i| byte.* = @truncate(i * 7 + i / 3); var encoded: [data_nibbles + checksum_nibbles]u8 = undefined; nibblise(&payload, &encoded); // Everything written is a pattern the surface can hold. for (encoded) |nibble| try testing.expect(disk2.read_table[nibble] != disk2.invalid); var back: [sector_bytes]u8 = undefined; try testing.expect(denibblise(&encoded, &back)); try testing.expectEqualSlices(u8, &payload, &back); // And a single byte gone wrong is caught, which is what the three // checksums are for. encoded[100] = disk2.write_table[(disk2.read_table[encoded[100]] + 1) & 0x3f]; try testing.expect(!denibblise(&encoded, &back)); } test "a whole disk survives being laid out and saved back" { const gpa = testing.allocator; const image = try gpa.alloc(u8, image_size); defer gpa.free(image); for (image, 0..) |*byte, i| byte.* = @truncate(i * 31 + i / 512); const floppy = try gpa.create(Floppy); defer gpa.destroy(floppy); floppy.* = .{}; try floppy.load(image); const back = try gpa.alloc(u8, image_size); defer gpa.free(back); @memset(back, 0); try floppy.save(back); try testing.expectEqualSlices(u8, image, back); } test "the register is CA1, CA0, SEL and CA2 in that order" { // The firmware's own routine shifts its parameter right one bit at a time // into CA2, then SEL, then CA0, then CA1, which is what fixes this. var controller: Controller = .{}; try testing.expectEqual(Register.direction_in, controller.addressed()); controller.lines[2] = true; // CA2 try testing.expectEqual(Register.lower_head, controller.addressed()); controller.lines[2] = false; controller.sel = true; try testing.expectEqual(Register.disk_in_place, controller.addressed()); controller.sel = false; controller.lines[0] = true; // CA0 try testing.expectEqual(Register.step, controller.addressed()); controller.lines[0] = false; controller.lines[1] = true; // CA1 try testing.expectEqual(Register.motor_on, controller.addressed()); // And the eject command, which is CA1 and CA0 with CA2. controller.lines[0] = true; controller.lines[2] = true; try testing.expectEqual(Register.eject, controller.addressed()); } /// Names a register on the lines the way the firmware's routine does, so the /// tests below read like the code that drives a real one. fn select(controller: *Controller, register: Register) void { const bits: u4 = @intFromEnum(register); controller.lines[2] = bits & 0x01 != 0; controller.sel = bits & 0x02 != 0; controller.lines[0] = bits & 0x04 != 0; controller.lines[1] = bits & 0x08 != 0; } test "the drive answers its fifteen questions, and all but one upside down" { var floppy: Floppy = .{}; var controller: Controller = .{}; controller.enabled = true; // An empty drive: no disk, at track zero, write protected because there // is nothing in it to write on, and the spindle stopped. select(&controller, .installed); try testing.expect(!controller.sense(0)); // zero: a drive is connected select(&controller, .disk_in_place); try testing.expect(controller.sense(0)); // one: it is empty select(&controller, .track_zero); try testing.expect(!controller.sense(0)); // zero: at track zero select(&controller, .write_protect); try testing.expect(!controller.sense(0)); // zero: cannot be written select(&controller, .motor_on); try testing.expect(controller.sense(0)); // one: not turning select(&controller, .motor_off); try testing.expect(controller.sense(0)); // one: two heads // Put a disk in and the answers change. controller.insert(0, &floppy); select(&controller, .disk_in_place); try testing.expect(!controller.sense(0)); select(&controller, .switched); try testing.expect(controller.sense(0)); // one: the disk changed floppy.write_protected = false; select(&controller, .write_protect); try testing.expect(controller.sense(0)); // one: it can be written // A connector with nothing on it says so and says nothing else. controller.selected = 1; controller.drives[1].fitted = false; select(&controller, .installed); try testing.expect(controller.sense(0)); select(&controller, .disk_in_place); try testing.expect(controller.sense(0)); } test "the strobe is what makes the drive do something" { var controller: Controller = .{}; controller.enabled = true; const disk = controller.drive(0); // Naming a register and reading it does nothing; naming it and pulsing // the strobe does. select(&controller, .motor_on); try testing.expect(!disk.spindle); controller.line(3, true, 0); controller.line(3, false, 0); try testing.expect(disk.spindle); // Stepping: set the direction, then step, and the head takes time about // it. The direction lives in the drive between commands. select(&controller, .direction_in); controller.line(3, true, 100); controller.line(3, false, 100); try testing.expect(!disk.outward); select(&controller, .step); controller.line(3, true, 100); controller.line(3, false, 100); try testing.expectEqual(@as(u8, 1), disk.track); try testing.expect(!controller.sense(100)); // zero: still moving try testing.expect(controller.sense(100 + cycles_per_step)); // one: arrived // And out again, which is the other value of the same line. select(&controller, .lower_head); // strobing this sets the direction out controller.line(3, true, 0); controller.line(3, false, 0); try testing.expect(disk.outward); select(&controller, .step); controller.line(3, true, 0); controller.line(3, false, 0); try testing.expectEqual(@as(u8, 0), disk.track); // The head does not walk off either end of the disk. for (0..200) |_| { controller.line(3, true, 0); controller.line(3, false, 0); } try testing.expectEqual(@as(u8, 0), disk.track); select(&controller, .motor_off); controller.line(3, true, 0); controller.line(3, false, 0); try testing.expect(!disk.spindle); } test "SEL is what chooses a head, and asking which head is reading does not" { var controller: Controller = .{}; controller.enabled = true; // SEL is the whole of it, and it is the same line whether the machine is // about to read or about to write. try testing.expectEqual(@as(u1, 0), controller.head()); controller.sel = true; try testing.expectEqual(@as(u1, 1), controller.head()); controller.sel = false; try testing.expectEqual(@as(u1, 0), controller.head()); // Naming register 1 or register 3 moves SEL, because SEL is that // register's fourth address bit -- but the *read* changes nothing, which // is the difference. A firmware holding the upper head and asking a // question about the lower one keeps the upper head. select(&controller, .upper_head); try testing.expectEqual(@as(u1, 1), controller.head()); _ = controller.sense(0); try testing.expectEqual(@as(u1, 1), controller.head()); } test "the disk turns only when the spindle does, and the head reads it" { const gpa = testing.allocator; const floppy = try gpa.create(Floppy); defer gpa.destroy(floppy); floppy.* = .{}; const image = try gpa.alloc(u8, image_size); defer gpa.free(image); @memset(image, 0); try floppy.load(image); var controller: Controller = .{}; controller.enabled = true; controller.insert(0, floppy); // Nothing goes past the head with the spindle stopped. try testing.expectEqual(@as(u8, 0), controller.readNibble(1000)); select(&controller, .motor_on); controller.line(3, true, 1000); controller.line(3, false, 1000); // Read round a whole track and the address mark of every one of the // twelve sectors goes past, in the interleaved order they were written. var found: u16 = 0; var cycles: u64 = 1000; var previous: [3]u8 = @splat(0); for (0..Floppy.trackLength(0) + 3) |_| { cycles += controller.turning; previous = .{ previous[1], previous[2], controller.readNibble(cycles) }; if (std.mem.eql(u8, &previous, &address_prologue)) found += 1; } try testing.expectEqual(@as(u16, 12), found); // The drive is not ready until the spindle is up to speed. try testing.expect(!controller.ready(1000)); try testing.expect(controller.ready(1000 + cycles_per_spinup)); } test "the sectors are spaced as the machine's own firmware spaces them" { // 795 apart, twelve to a twelve-sector track, which is what a IIgs writes // when it formats a disk. It was 770 for a while, worked out from the // drive's nominal speed and data rate, and twenty-five short: the twelfth // sector wrapped onto the first and the verify found eleven where it had // written twelve. try testing.expectEqual(@as(u16, 795), nibbles_per_sector); try testing.expectEqual(@as(u16, 12 * 795), Floppy.trackLength(0)); try testing.expectEqual(@as(u16, 8 * 795), Floppy.trackLength(79)); // And a slot is still long enough to hold what goes in it, with the rest // left as the filler that spaces them out. try testing.expect(leading_sync >= 6); } test "a track written a nibble at a time reads back as what went down" { // Which is the whole of what formatting asks of a drive: the firmware // lays a track out from nothing, one byte at a time at the rate the disk // turns, and then reads it back to see that it took. Sector writes never // exercise this, because they put bytes back where the track already has // room for them. var floppy: Floppy = .{}; var image: [image_size]u8 = @splat(0); try floppy.load(&image); floppy.write_protected = false; var controller: Controller = .{}; controller.enabled = true; controller.insert(0, &floppy); select(&controller, .motor_on); controller.line(3, true, 1000); controller.line(3, false, 1000); // A whole track of a pattern that could not be mistaken for what was // there, written at the rate the head passes over the surface. const length = Floppy.trackLength(0); var cycles: u64 = 1000; for (0..length) |i| { cycles += controller.turning; controller.writeNibble(cycles, @intCast(0x80 | (i % 0x40))); } // And read back round the same track. var wrong: usize = 0; var first_wrong: usize = length; for (0..length) |i| { cycles += controller.turning; const want: u8 = @intCast(0x80 | (i % 0x40)); const got = controller.readNibble(cycles); if (got != want) { if (wrong == 0) first_wrong = i; wrong += 1; } } if (wrong != 0) std.debug.print( "{d} of {d} nibbles came back wrong, from {d}\n", .{ wrong, length, first_wrong }, ); try testing.expectEqual(@as(usize, 0), wrong); } test "a 3.5-inch floppy round-trips through a snapshot" { const alloc = testing.allocator; 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); original.write_protected = false; original.dirty = true; const bytes = try snapshot.save(alloc, &original); defer alloc.free(bytes); var restored: Floppy = .{}; try snapshot.load(alloc, bytes, &restored); try testing.expectEqualSlices(u8, &original.nibbles, &restored.nibbles); try testing.expect(!restored.write_protected); try testing.expect(restored.dirty); }