// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The packets an Apple IIc with the 32K ROM sends to an intelligent drive, //! and the ones it expects back. //! //! A UniDisk 3.5 is not a drive the machine works directly. It has a processor //! of its own, and the IIc talks to it over the disk port in packets — what //! Apple's firmware calls the CBus. The firmware that does the talking is the //! Protocol Converter, which "always begins at address $C500 in the Apple IIc //! with 32K ROM" and which, "to ProDOS and Pascal 1.3, appears to be a block //! device" (Apple Computer, Inc., n.d.-b, p. 20). Above this the machine sees //! ordinary block reads and writes; below it, this. //! //! The protocol, in the firmware's own words: "1) Device signals ready for //! data. 2) Host signals data iminent. 3) Packet is transmitted (sync, command //! mark, ids, contents, checksum). 4) Device signals packet recieved. 5) Host //! finishes send data cycle." The bytes go "in slow mode (32 cycles/byte) and //! the timing is critical" (`SendOnePack`, printed p. 199). //! //! **Everything here is checked against the ROM rather than against the //! listing.** The listing is a scan and its hex columns are the worst case for //! OCR, so each constant below was found in the bytes of `Apple IIc ROM 00 - //! 342-0033-A - 1985.bin` at the address the listing gives it. Only the shape //! of the thing was read from the page. //! //! What this file is not is the wire: nothing here touches a shift register or //! counts a cycle. It turns a packet into the bytes that go across and back //! again, so that the part which does have to meet the timing has something //! already known to be right underneath it. const std = @import("std"); /// The mark that opens a packet: `packetbeg equ $C3` (Apple Computer, Inc., /// n.d.-b, printed p. 189). Verified in the ROM at bank 1 `$c9d6`, where it /// heads the sync table. pub const packet_begin: u8 = 0xc3; /// And the one that closes it: `packetend equ $C8`, verified as the `a9 c8` of /// `lda #packetend` at bank 1 `$c9ad`. pub const packet_end: u8 = 0xc8; /// The self-sync run that precedes the begin mark, in the order it goes out. /// /// The firmware sends `$ff` on its own and then walks its table backwards — /// `ldy #5`, `lda preamble,y`, `dey`, `bpl` — over the six bytes `$c3 $ff $fc /// $f3 $cf $3f`, so the `$c3` at the table's head is sent last and is the /// begin mark. The whole run is verified as those six bytes lying at bank 1 /// `$c9d6`. As a bit stream it is what the comment calls "groups of eight 1's /// separated by a 0". pub const sync = [_]u8{ 0xff, 0x3f, 0xcf, 0xf3, 0xfc, 0xff }; /// A packet's five header bytes, in the order the firmware sends them: the /// destination — "Send the desination ID", `lda Unit`, `ora #$80` — then the /// source, "that's us... we're an $80", then "the packet type (command or /// data)", then "the Auxilliary Type byte (an $80 from this rev PC)", then /// "the status byte (null for us)" (printed p. 193). /// /// Every one of them travels with bit seven set, which is what the `ora #$80` /// is for and what makes a byte on this bus distinguishable from the idle /// line. The values are the caller's: this only carries them. pub const Header = struct { destination: u8, source: u8, kind: u8, auxiliary: u8, status: u8, }; /// How many data bytes travel in a group. The firmware sends the leftovers /// first — "Now send the 'oddbytes' part of the packet contents" — and then /// "the groups of seven contents" (printed p. 194). pub const group = 7; /// The high bits of a group's seven bytes, gathered into one byte. /// /// The firmware builds it a bit at a time with `asl a` on the data byte /// followed by `rol topbits`, so each byte's top bit lands in bit zero and is /// carried left by the ones that follow: the first byte of the group ends at /// bit six and the last at bit zero. Bit seven is set, as every byte on this /// bus is. /// The high bits of up to seven bytes, first byte highest. fn gatherTop(bytes: []const u8) u8 { std.debug.assert(bytes.len <= group); var top: u8 = 0; for (bytes, 0..) |byte, i| { if (byte & 0x80 != 0) top |= @as(u8, 1) << @intCast(group - 1 - i); } return top | 0x80; } /// Hands a byte back its high bit from the group's gathered one. fn restoreTop(low: u8, top: u8, index: usize) u8 { std.debug.assert(index < group); const bit = (top >> @intCast(group - 1 - index)) & 1; return (low & 0x7f) | (bit << 7); } /// The checksum: the seven header bytes as they go out, and the contents as /// they were before any of the encoding was done to them. /// /// It is built in two places, which is why it is neither one thing nor the /// other. The routine at bank 1 `$cbb0` runs over the caller's buffer with /// `EOR ($54),Y` before a byte of it has been touched, so the contents go in /// **raw** — not with their high bits forced on, and not counting the bytes /// that carry those high bits. Then `SendByte` folds in each header byte after /// putting it on the wire (`eor checksum`, `sta checksum`, verified as the /// `45 40 85 40 60` at bank 1 `$ca5b`), so those go in **as sent**, top bits /// and all. /// /// The captured packet is what settles it. Its header exclusive-ors to `$82` /// and its contents to `$07`, and `$82 ^ $07` is `$85`, which is the value its /// two checksum bytes carry. Taking the whole packet as it appears on the wire /// gives `$05` instead, and would reject a packet a real machine sent. fn checksum(header_sent: []const u8, payload: []const u8) u8 { var sum: u8 = 0; for (header_sent) |byte| sum ^= byte; for (payload) |byte| sum ^= byte; return sum; } /// The checksum as it travels: two bytes, each carrying four of its bits with /// ones between them. /// /// "Now send the damn checksum as two FM bytes" — the first is `lda checksum`, /// `ora #$AA`, which the listing annotates `1 c6 1 c4 1 c2 1 c0`, and the /// second is the same shifted down by one, `1 c7 1 c5 1 c3 1 c1`. Verified as /// the `a5 40 09 aa` at bank 1 `$c999`. fn checksumBytes(sum: u8) [2]u8 { return .{ sum | 0xaa, (sum >> 1) | 0xaa }; } /// And back again, from the two bytes to the byte they carry. fn checksumFrom(pair: [2]u8) u8 { var sum: u8 = 0; for (0..4) |i| { const even = (pair[0] >> @intCast(2 * i)) & 1; const odd = (pair[1] >> @intCast(2 * i)) & 1; sum |= even << @intCast(2 * i); sum |= odd << @intCast(2 * i + 1); } return sum; } /// Everything that can be wrong with a packet coming the other way. pub const Error = error{ NoBeginMark, NoEndMark, Truncated, BadChecksum, TooLong, }; /// Writes a packet out, sync and marks and all, and answers what was written. /// /// The order is the firmware's: the header's five bytes, then the count of /// leftover bytes and the count of whole groups, then the leftovers behind /// their gathered high bits, then each group behind its own, then the checksum /// and the end mark. pub fn encode(header: Header, payload: []const u8, into: []u8) ![]u8 { const groups = payload.len / group; const odd = payload.len % group; if (groups > 0x7f or odd > 0x7f) return Error.TooLong; var out: std.Io.Writer = .fixed(into); // The sync and the begin mark are outside the checksum. try out.writeAll(&sync); try out.writeAll(&.{packet_begin}); const body_at = out.end; try out.writeAll(&.{ header.destination | 0x80, header.source | 0x80, header.kind | 0x80, header.auxiliary | 0x80, header.status | 0x80, @as(u8, @intCast(odd)) | 0x80, @as(u8, @intCast(groups)) | 0x80, }); if (odd != 0) { const leftovers = payload[0..odd]; try out.writeAll(&.{gatherTop(leftovers)}); for (leftovers) |byte| try out.writeAll(&.{byte | 0x80}); } for (0..groups) |g| { const seven = payload[odd + g * group ..][0..group]; try out.writeAll(&.{gatherTop(seven)}); for (seven) |byte| try out.writeAll(&.{byte | 0x80}); } const sum = checksum(into[body_at..][0..7], payload); try out.writeAll(&checksumBytes(sum)); try out.writeAll(&.{packet_end}); return into[0..out.end]; } /// What came back off the bus. pub const Packet = struct { header: Header, payload: []u8, }; /// Reads a packet, skipping whatever sync came before it, and puts the /// contents in `into`. pub fn decode(bytes: []const u8, into: []u8) Error!Packet { const begin = std.mem.indexOfScalar(u8, bytes, packet_begin) orelse return Error.NoBeginMark; var at = begin + 1; if (bytes.len < at + 7) return Error.Truncated; const body_at = at; const header: Header = .{ .destination = bytes[at], .source = bytes[at + 1], .kind = bytes[at + 2], .auxiliary = bytes[at + 3], .status = bytes[at + 4], }; const odd: usize = bytes[at + 5] & 0x7f; const groups: usize = bytes[at + 6] & 0x7f; at += 7; if (odd > group) return Error.Truncated; const total = odd + groups * group; if (into.len < total) return Error.TooLong; var wrote: usize = 0; if (odd != 0) { if (bytes.len < at + 1 + odd) return Error.Truncated; const top = bytes[at]; at += 1; for (0..odd) |i| into[i] = restoreTop(bytes[at + i], top, i); at += odd; wrote += odd; } for (0..groups) |g| { if (bytes.len < at + 1 + group) return Error.Truncated; const top = bytes[at]; at += 1; for (0..group) |i| into[odd + g * group + i] = restoreTop(bytes[at + i], top, i); at += group; wrote += group; } if (bytes.len < at + 3) return Error.Truncated; const sum = checksum(bytes[body_at..][0..7], into[0..wrote]); if (sum != checksumFrom(.{ bytes[at], bytes[at + 1] })) return Error.BadChecksum; if (bytes[at + 2] != packet_end) return Error.NoEndMark; return .{ .header = header, .payload = into[0..wrote] }; } const testing = std.testing; test "the marks and the sync run are the bytes the ROM has" { // Read off the page and then found in the ROM, which is the only one of // the two that can be trusted for a number. try testing.expectEqual(@as(u8, 0xc3), packet_begin); try testing.expectEqual(@as(u8, 0xc8), packet_end); try testing.expectEqualSlices(u8, &.{ 0xff, 0x3f, 0xcf, 0xf3, 0xfc, 0xff }, &sync); } test "every byte of a packet from the begin mark on has its high bit set" { // Which is what makes a byte on this bus tell itself apart from a line // nobody is driving. The payload here is deliberately full of bytes that // have no high bit of their own. // // The sync run in front is the exception, and not an accident: `$3f` has // no high bit because the run is not bytes at all but a bit pattern — // "groups of eight 1's separated by a 0" — laid down to put the receiver // in step before the first real byte arrives. So the rule starts at the // begin mark. var buffer: [128]u8 = undefined; const payload = [_]u8{ 0x00, 0x01, 0x02, 0x7f, 0x10 }; const packet = try encode(.{ .destination = 1, .source = 0, .kind = 0, .auxiliary = 0, .status = 0, }, &payload, &buffer); for (packet[sync.len..]) |byte| try testing.expect(byte & 0x80 != 0); // And the sync run really is the thing being excepted. try testing.expect(sync[1] & 0x80 == 0); } test "a packet begins and ends with its marks" { var buffer: [128]u8 = undefined; const packet = try encode(.{ .destination = 1, .source = 0, .kind = 0x80, .auxiliary = 0, .status = 0, }, &.{ 1, 2, 3 }, &buffer); try testing.expectEqualSlices(u8, &sync, packet[0..sync.len]); try testing.expectEqual(packet_begin, packet[sync.len]); try testing.expectEqual(packet_end, packet[packet.len - 1]); } test "the checksum rides in two bytes and comes back out of them" { // "Now send the damn checksum as two FM bytes": the even bits in one and // the odd in the other, ones in between, so that neither can be a byte // with its top bit clear. for (0..256) |i| { const sum: u8 = @intCast(i); const pair = checksumBytes(sum); try testing.expect(pair[0] & 0x80 != 0); try testing.expect(pair[1] & 0x80 != 0); try testing.expectEqual(sum, checksumFrom(pair)); } } test "what goes out comes back, at every length across a group boundary" { // Nought bytes, fewer than seven, exactly seven, and more than seven with // a remainder: the four shapes the leftovers-then-groups arrangement has. var payload: [40]u8 = undefined; for (&payload, 0..) |*byte, i| byte.* = @intCast((i * 37) & 0xff); for (0..payload.len) |length| { var wire: [256]u8 = undefined; var back: [64]u8 = undefined; const packet = try encode(.{ .destination = 0x41, .source = 0x00, .kind = 0x00, .auxiliary = 0x00, .status = 0x00, }, payload[0..length], &wire); const got = try decode(packet, &back); try testing.expectEqualSlices(u8, payload[0..length], got.payload); try testing.expectEqual(@as(u8, 0x41 | 0x80), got.header.destination); } } test "sync in front of a packet is skipped rather than read as contents" { var wire: [256]u8 = undefined; var back: [64]u8 = undefined; const packet = try encode(.{ .destination = 1, .source = 0, .kind = 0, .auxiliary = 0, .status = 0, }, &.{ 9, 8, 7 }, &wire); const got = try decode(packet, &back); try testing.expectEqualSlices(u8, &.{ 9, 8, 7 }, got.payload); } test "a packet with a byte changed under it does not read as good" { var wire: [256]u8 = undefined; var back: [64]u8 = undefined; const packet = try encode(.{ .destination = 1, .source = 0, .kind = 0, .auxiliary = 0, .status = 0, }, &.{ 1, 2, 3, 4, 5, 6, 7, 8 }, &wire); // A byte of the contents, not of the framing, so that what catches it is // the checksum and not a missing mark. packet[sync.len + 9] ^= 0x01; try testing.expectError(Error.BadChecksum, decode(packet, &back)); } test "a packet cut short says so rather than reading past its end" { var wire: [256]u8 = undefined; var back: [64]u8 = undefined; const packet = try encode(.{ .destination = 1, .source = 0, .kind = 0, .auxiliary = 0, .status = 0, }, &.{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, &wire); try testing.expectError(Error.Truncated, decode(packet[0 .. packet.len - 6], &back)); } test "the gathered high bits sit first-byte-highest, as the ROM rolls them" { // This is the one part of the encoding a round trip cannot vouch for: an // encoder and a decoder that agree with each other about the bit order // agree just as well when both are wrong, and every test above passes with // the order reversed. So it is pinned here against the ROM instead. // // The send loop at bank 1 `$c965` does, once per byte of a group: // // LDA ($56),Y ; the next byte of the caller's buffer // STA $51 ; stash it, to send on the following pass // ASL ; its top bit into the carry // ROL $41 ; and the carry into topbits, from the bottom // // Each `ROL` carries what is already there one place further up, so of the // seven bits gathered the first is the highest. Seven rolls of a byte // seeded with one leave that seed at bit seven, which is why the gathered // byte goes out without an `ORA #$80` of its own and still arrives with // its top bit set, as everything on this bus does. // // The other end of the firmware says the same thing, which is worth more // than the send side saying it twice. Receiving, at bank 1 `$ca39`, it // reads the gathered byte, does one `ASL` to throw the top bit away, and // then takes one `ASL $41` per data byte, the carry out of each being the // bit that byte is owed. The first byte therefore gets what was bit six, // and the seventh what was bit zero — the same order, arrived at from the // opposite direction. // // Only the first and last bytes of the group carry a high bit here, so the // wrong order would not merely move the bits but swap them, and the byte // expected below is one it cannot produce. var wire: [64]u8 = undefined; const payload = [_]u8{ 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; const packet = try encode(.{ .destination = 0, .source = 0, .kind = 0, .auxiliary = 0, .status = 0, }, &payload, &wire); // Past the sync, the begin mark and the seven header bytes lies the // group's gathered byte: bit seven set, bit six for the first byte of the // group, and nothing else. try testing.expectEqual(@as(u8, 0xc0), packet[sync.len + 1 + 7]); // And the seven that follow are the payload's low seven bits with the top // bit forced on, so first and last differ only where the gathered byte // says they do. try testing.expectEqualSlices( u8, &.{ 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81 }, packet[sync.len + 2 + 7 ..][0..7], ); } test "a packet an Apple IIc really sent decodes, checksum and all" { // Not a packet this file made: these are the bytes an Apple IIc with the // 32K ROM handed its data register, captured by running Apple's own // firmware from power-on and watching what it wrote. Every claim this // file makes about the shape of a packet is answerable to them. // // The framing reads straight off: the six sync bytes, the `$c3`, five // header bytes, a count of two leftover bytes and one whole group, the // gathered high bits and the two leftovers, the group's gathered byte and // its seven, the checksum's two, and `$c8`. // // And the contents say which end the leftovers belong at. The first byte // is `$05`, which is `InitCMD` — the very call the reset code makes, `jsr // MLIEntry` followed by `dfb InitCMD`, to force a reset of the bus as the // machine starts. A packet whose leftovers went at the end would have that // command byte in the middle of seven zeros instead, which is not a // command at all. const captured = [_]u8{ 0xff, 0x3f, 0xcf, 0xf3, 0xfc, 0xff, // sync 0xc3, // begin 0x81, 0x80, 0x80, 0x80, 0x80, // destination, source, type, aux, status 0x82, 0x81, // two odd bytes, one group 0x80, 0x85, 0x82, // their high bits, then the two 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // the group and its bits 0xaf, 0xea, // the checksum, in two 0xc8, // end }; var back: [32]u8 = undefined; const packet = try decode(&captured, &back); try testing.expectEqual(@as(u8, 0x81), packet.header.destination); try testing.expectEqual(@as(u8, 0x80), packet.header.source); try testing.expectEqualSlices( u8, &.{ 0x05, 0x02, 0, 0, 0, 0, 0, 0, 0 }, packet.payload, ); // And what this file writes for the same packet is what the machine wrote. var wire: [64]u8 = undefined; const again = try encode(.{ .destination = 0x01, .source = 0x00, .kind = 0x00, .auxiliary = 0x00, .status = 0x00, }, &.{ 0x05, 0x02, 0, 0, 0, 0, 0, 0, 0 }, &wire); try testing.expectEqualSlices(u8, &captured, again); }