// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The Zilog 8530, which is an Apple IIgs's two serial ports — and its //! network, which is the same chip in a different mode. //! //! A IIgs has a printer port and a modem port where a IIe had two cards, and //! both are channels of one chip. Four addresses reach it, and the two bits //! that pick between them are the chip's own two select pins: //! //! | address | `A//B` | `D//C` | what it is | //! | ------- | ------ | ------ | --------------------------- | //! | `$c038` | B | command | channel B's command register | //! | `$c039` | A | command | channel A's command register | //! | `$c03a` | B | data | channel B's data register | //! | `$c03b` | A | data | channel A's data register | //! //! Four addresses for thirty-one registers, which is the whole difficulty and //! the reason this is a chip rather than a register. The Hardware Reference //! (Apple Computer, Inc., 1989a) declines to explain it and points at Zilog's //! manual, so that is where this comes from, and it states the protocol exactly //! (ZiLOG, 2001, Section 2.3.4): //! //! - The registers are reached in **two steps**. A write to the command //! register while the pointer is zero is a write to WR0, and the low three //! bits of what is written become the pointer. The *next* access to a //! command register then reaches the register the pointer names. //! - **At the conclusion of that access the pointer resets to zero**, so the //! one after it is a WR0 write again. Which means WR0 and RR0 need no //! pointer written first, and are reachable in a single cycle. //! - There is **one pointer for the whole chip**, not one per channel: "the //! pointer bits may be written in either channel because only one set //! exists". Which channel is reached is decided by the address of the //! *second* access, not the first. //! - Registers 8 to 15 need the **Point High** command written alongside the //! pointer bits, which is command code `001` in bits 5 to 3. That is why a //! command cannot be issued at the same time as pointing high. //! - The data register is reached directly, whatever the pointer says, and //! **does not disturb it**. //! //! And one consequence of all that is worth spelling out, because it is what //! the firmware in this machine's ROM is doing with the only two accesses it //! makes to any of these addresses when nothing is plugged in: "if, for some //! reason, the state of the pointer bits is unknown they may be reset to 0 by //! performing a read cycle". Two reads of `$c039` are a machine putting a chip //! into a known state before it starts, and the model has to answer them the //! same way twice. //! //! ## The ports themselves //! //! Each channel has a byte on the way in and a queue on the way out, and what //! is on the far end of either is somebody else's business — a file, a pipe, //! whatever the program embedding this hands over. A channel nobody has //! attached anything to still answers correctly, and answers it as an empty //! port rather than a broken one: the transmit buffer is empty because it is, //! and no character is waiting because none arrived. //! //! A byte takes time to go, and that is modelled rather than skipped, for the //! same reason the Super Serial Card models it: software that drives a serial //! port by counting is written against the rate it asked for, and a chip that //! hands bytes over the instant they are asked for runs those programs at the //! wrong speed. The rate comes out of the chip the way the manual says to put //! it in — "Time Constant = Clock Frequency / (2 x (Desired Rate) x (BR Clock //! Period)) - 2" (ZiLOG, 2001, § 5.2.15) — read backwards, with the time //! constant out of WR12 and WR13 and the clock period out of WR4. //! //! The transmitter is two registers deep, as the chip's is: a buffer the //! processor writes and a shift register the wire is fed from. A byte written //! to an idle transmitter goes straight through to the shifter and the buffer //! is empty again at once; one written while another is still going out waits //! in the buffer, and the Transmit Buffer Empty bit stays down until the //! shifter takes it. That is the bit a program polls between bytes, and it is //! why writing two bytes back to back and then polling is a wait of one byte //! time and not two (ZiLOG, 2001, § 2.4.8.1). //! //! ## The network //! //! LocalTalk is SDLC on the same chip: bit-oriented synchronous frames at //! 230,400 bits a second, FM0 encoded, with the receive clock recovered from //! the data by the chip's own phase-locked loop (ZiLOG, 2001, § 4.4; § 3.4). //! This machine's firmware sets that up exactly the way Zilog's own LocalTalk //! application note does (ZiLOG, 2001, Chapter 6, "Technical Considerations //! When Implementing LocalTalk Link Access Protocol"): WR4 for SDLC, WR10 for //! FM0 with the CRC preset to ones, WR11 to clock the transmitter from the //! baud rate generator and the receiver from the DPLL, a time constant of six, //! and the DPLL put into FM mode and then search mode through WR14. The time //! constant is what says what the crystal on the chip's `/RTxC` pin is, since //! nothing else here does: six gives 230,400 only from 3.6864 MHz. //! //! What the chip does with a frame is what the manual says it does (ZiLOG, //! 2001, § 4.4.1, § 4.4.2): //! //! - Sending: the processor resets the CRC generator, writes the bytes one //! at a time as the transmit buffer empties, and resets the Tx //! Underrun/EOM latch after the first. When the last byte has left the //! shift register and nothing is waiting, the transmitter *underruns*, //! and with the latch reset it "sends the accumulated CRC followed by //! flags" — sixteen bits of check and an eight-bit closing flag, while //! the latch goes back up and the Transmit Buffer Empty bit stays down //! for the CRC's duration. The frame on the wire is the bytes, the CRC //! and the flag, and that is what comes out of here. //! - Receiving: the receiver hunts for an opening flag, then feeds every //! byte between it and the closing flag into a three-byte FIFO, the two //! CRC bytes included, and marks the last of them End of Frame in RR1 //! with the result of the CRC check beside it. Address search mode drops //! frames whose first byte is neither the address in WR6 nor `$ff`. After //! a LocalTalk frame the sender holds the line at ones, which the receiver //! reads as an abort and answers by going back to hunting. //! //! The wire is frames, not bits: whatever is on the far end hands in whole //! frames and takes whole frames away, and the chip's business is the timing //! of the bytes inside them and the status bits around them. Each byte still //! takes its eight bit times to arrive, which is what lets the machine's //! interrupt handler find the second byte of a frame already waiting behind //! the first when it gets there, as it expects to. //! //! The two lines that come in from the far end of the wire are here: carrier //! detect and clear to send, driven by `setDcd` and `setCts`, latched and //! interrupting exactly as the manual describes -- "if the DCD IE is reset, //! this bit merely reports the current, unlatched state of the /DCD pin", and //! with it set, a transition latches the pin and raises an External/Status //! interrupt. Nothing *inside* the machine drives them: they are what a modem, //! a printer or a null-modem cable does, so a caller sets them, and with //! nobody on the far end they read as nobody on the far end, which is what a //! IIgs with an empty port sees. //! //! What is still not here is a modem to be on the other end of them. const std = @import("std"); /// The chip: two channels, a pointer they share, and the two registers that /// are shared as well. pub const Scc = struct { /// The register pointer. One for the whole chip, and zero after every /// access that used it. pointer: u4 = 0, /// The two channels. A is the printer port and B the modem port, which is /// also the order their addresses go in: the odd address is A. The /// Firmware Reference (Apple Computer, Inc., 1987a) has it the same way /// round in its table of interrupt sources, "serial input #1 IRQ (SCC /// channel A)" and "#2 (SCC channel B)", and port 1 is the printer port. a: Channel = .{}, b: Channel = .{}, /// WR2, the interrupt vector, and WR9, the master interrupt and reset /// control. The register map shows both without a channel: there is one of /// each in the chip and either channel's address reaches it. interrupt_vector: u8 = 0, master_interrupt: u8 = 0, /// How fast the machine runs, which is what turns a rate into cycles. A /// IIgs's fast side, since that is the side the chip is on. cycles_per_second: u64 = 2_800_000, /// The cycle the machine is on, handed in with each access so that a byte /// on its way out can take the time it takes. now: u64 = 0, /// The next cycle at which anything in either channel happens on its /// own — a byte leaving the shifter, a check sequence ending, a byte /// arriving — or the end of time if nothing will. The machine asks after /// the chip on every memory access, and this is what makes that free. next_event: u64 = std.math.maxInt(u64), /// The last few register accesses, and how many there have been. For /// whoever comes to read what a firmware says to this chip: the Hardware /// Reference does not, and the sequence is the specification. trace: [trace_length]Exchange = undefined, traced: usize = 0, /// The trace is a debug ring buffer left `undefined` until something is /// logged into it, so it is not written to a snapshot — reading its /// uninitialised bytes as the `Exchange` fields they will one day hold is /// not something a save state can do. pub const snapshot_skip_fields = [_][]const u8{"trace"}; pub const trace_length = 4096; /// One access, after the pointer has been resolved: which register of /// which channel, and what went by. pub const Exchange = struct { channel: Which, /// The register, or the data register when `data` is set. register: u4, data: bool, reading: bool, value: u8, cycle: u64, }; fn record(self: *Scc, exchange: Exchange) void { self.trace[self.traced % trace_length] = exchange; self.traced += 1; } /// Which channel an access is for. pub const Which = enum(u1) { b = 0, a = 1 }; /// A frame on the wire, as the chip sends and receives it: the bytes the /// processor wrote or will read, with the two bytes of frame check /// sequence on the end. Flags and zero insertion are the chip's own /// business and never appear. pub const Frame = struct { bytes: [longest]u8 = undefined, len: usize = 0, /// Whether the check sequence agrees with the bytes. A frame the chip /// sent always agrees; a frame handed in from outside agrees unless /// whoever handed it in said otherwise. good: bool = true, /// The largest frame LocalTalk allows plus its check: three bytes of /// header, up to six hundred of data, and two of CRC. pub const longest = 3 + 600 + 2; pub fn slice(self: *const Frame) []const u8 { return self.bytes[0..self.len]; } /// The bytes without the check sequence. pub fn payload(self: *const Frame) []const u8 { return self.bytes[0..self.len -| 2]; } }; /// The frame check sequence SDLC carries, and the SCC computes: CRC-CCITT /// over the bits in the order they go down the wire, preset to ones, /// sent inverted (ZiLOG, 2001, § 4.4, "the transmitter in the SCC /// automatically inverts the CRC before transmission"). Least significant /// bit of each byte first, which makes it the reflected form of the /// polynomial; the two bytes go out low byte first. /// /// A receiver running the same check over the bytes *and* the two check /// bytes gets a fixed remainder rather than zero, which is the /// `0001110100001111` the manual says the chip compares against (ZiLOG, /// 2001, § 4.4.2); in the reflected form it comes out as `$f0b8`, and /// after the final inversion `$0f47`. pub fn fcs(bytes: []const u8) u16 { var crc: u16 = 0xffff; for (bytes) |byte| { crc ^= byte; for (0..8) |_| { crc = if (crc & 1 != 0) (crc >> 1) ^ 0x8408 else crc >> 1; } } return ~crc; } /// The remainder a good frame leaves behind when the check is run over /// its bytes and its check sequence together. pub const fcs_good: u16 = 0x0f47; /// Whether a frame's last two bytes are the check sequence of what comes /// before them. pub fn fcsAgrees(frame: []const u8) bool { if (frame.len < 2) return false; return fcs(frame) == fcs_good; } /// One byte in the receive FIFO, with the status that travels beside it: /// the chip keeps an error FIFO alongside the data FIFO, and "the act of /// reading the data pops both" (ZiLOG, 2001, § 2.4.7). pub const Received = struct { byte: u8, /// The last byte of an SDLC frame, which is the second CRC byte. end_of_frame: bool = false, /// Valid only with `end_of_frame`: whether the check disagreed. crc_error: bool = false, /// This byte was written over by one that arrived with the FIFO full. overrun: bool = false, }; /// A frame handed in from outside, waiting to arrive. const Incoming = struct { frame: Frame, /// The cycle its opening flag reaches the receiver. begins: u64, }; /// One channel: fourteen write registers, a receiver, a transmitter, and /// the two ends of a wire. WR0 is not among the registers — it is the /// pointer and the commands, and holds nothing — and WR2 and WR9 are the /// chip's rather than a channel's. pub const Channel = struct { /// The receive and transmit queues are ring buffers left `undefined` /// past what their length fields say is in them, so they are not /// written to a snapshot: only the bytes a queue's own length vouches /// for are real, and a save state cannot know that from the array /// alone. In-flight frames are not part of a snapshot, which for the /// serial and AppleTalk chip is a moment nobody saves at. pub const snapshot_skip_fields = [_][]const u8{ "fifo", "incoming", "frames" }; /// The write registers. Zero after a reset but for WR4's bit 2, which /// "is always set to 1 by a channel or hardware reset to ensure that /// the /SYNC pin is in a known state after a reset" (ZiLOG, 2001, /// § 5.2.5) — and which, being the one-stop-bit code, is what makes a /// reset chip an asynchronous one rather than a synchronous one in /// Hunt. registers: [16]u8 = registers_at_reset, // ------------------------------------------------------------------ // The receiver. /// The receive FIFO, oldest first. "The 8530's receive FIFO is three /// deep", and RR0's Rx Character Available "bit is set if there is at /// least one byte available". fifo: [fifo_depth]Received = undefined, fifo_len: usize = 0, /// The receive overrun error, RR1 bit 5, which is latched: "when that /// character is read, the Error condition is latched until reset by /// the Error Reset command" (ZiLOG, 2001, § 5.3.2). overrun: bool = false, /// The status of the last byte taken out of the FIFO, which is what /// RR1 keeps reporting after the byte has gone: the End of Frame bit /// "is reset by issuing the Error Reset command. It is also updated /// by the first character of the following frame". last_status: Received = .{ .byte = 0 }, /// The two lines that come in from whatever is on the other end of /// the wire: carrier detect and clear to send. /// /// True is *asserted*, which on the connector is a low voltage -- the /// pins are `/DCD` and `/CTS` -- in the same way as everything else /// here and in `scsi.zig`: a model that carried voltages would have /// every comparison written inside out for no gain. /// /// Nothing inside the machine drives these. They are what a modem, a /// printer or a null-modem cable on the far end does, so a caller sets /// them; with nobody there they read as nothing there, which is what a /// IIgs with an empty port sees. Setting one is `Scc.setDcd` and /// `Scc.setCts`, which is where the interrupt on a change is raised. dcd_line: bool = false, cts_line: bool = false, /// Whether the receiver is hunting for a flag, which is RR0's /// Sync/Hunt bit in SDLC mode: "initially set by the Enter Hunt Mode /// command or when the receiver is disabled. It is reset when the /// opening flag of the first frame is detected." hunt: bool = true, /// Whether the line is at seven or more ones, which is RR0's /// Break/Abort bit in SDLC mode, and what every LocalTalk frame ends /// with. abort: bool = false, /// Frames handed in from outside and not yet wholly arrived, oldest /// first, and how far through the oldest the receiver has got. incoming: [incoming_depth]Incoming = undefined, incoming_len: usize = 0, /// How many bytes of the oldest incoming frame have reached the FIFO. arrived: usize = 0, /// Whether the receiver interrupt on the next character is armed, /// which in the Receive Interrupt on First Character mode is the /// state after the receiver is enabled and after the Enable Interrupt /// on Next Rx Character command. first_armed: bool = false, // ------------------------------------------------------------------ // The transmitter. /// The byte in the transmit buffer waiting for the shift register, /// if there is one. Transmit Buffer Empty is this being null. buffered: ?u8 = null, /// The cycle the byte in the shift register will have wholly left it. shifter_until: u64 = 0, /// While the CRC and closing flag are going out: the cycle the CRC /// finishes, during which the transmit buffer reads as full, and the /// cycle the flag after it finishes. crc_until: u64 = 0, flag_until: u64 = 0, /// Bytes the machine has sent asynchronously, oldest first, waiting /// for whatever is on the far end to take them. sending: [capacity]u8 = undefined, sending_len: usize = 0, /// The frame being assembled, from the Reset Tx CRC Generator command /// to the underrun that closes it. frame: Frame = .{}, in_frame: bool = false, /// Whether the line driver was on when the frame began, which is /// whether it reaches the wire at all. frame_driven: bool = false, /// Frames sent, oldest first, waiting for the far end. frames: [frame_queue]Frame = undefined, frames_len: usize = 0, /// Frames that were finished with the driver off, and so went nowhere; /// and frames that ran past what a frame can hold. frames_undriven: u32 = 0, frames_overlong: u32 = 0, /// The Tx Underrun/EOM latch, RR0 bit 6. Set by reset, by the /// transmitter being disabled, by Send Abort, and by the transmitter /// underrunning; reset only by the command. eom_latch: bool = true, /// Whether the transmit buffer was written since the transmitter was /// last idle, which is what makes the next emptying an interrupt: "the /// transmit buffer must be full before the TxIP can be set". tx_written: bool = false, /// `/RTS`, which on this machine is what turns the line driver on: the /// firmware raises it with the transmitter off for the network's /// synchronisation pulse, lowers it, and raises it again with the /// transmitter for the frame, exactly the sequence Zilog's LocalTalk /// note gives for driving an RS-422 transceiver's enable from the pin /// (ZiLOG, 2001, Chapter 6). rts: bool = false, // ------------------------------------------------------------------ // Interrupts. /// The three interrupt pending bits this channel contributes to RR3. rx_ip: bool = false, tx_ip: bool = false, ext_ip: bool = false, /// The external/status latches: when closed, what RR0 read when they /// closed, for the bits whose interrupts are enabled in WR15 (ZiLOG, /// 2001, § 2.4.9). latched_status: ?u8 = null, /// The enabled status bits as they were last seen, for telling a /// change from a repeat. previous_status: u8 = 0, /// When the DPLL's missing-clock latches were last reset, for RR10. missing_clock_reset_at: u64 = 0, pub const fifo_depth = 3; pub const incoming_depth = 8; pub const frame_queue = 8; const registers_at_reset: [16]u8 = blk: { var all: [16]u8 = @splat(0); all[4] = 0x04; break :blk all; }; // ------------------------------------------------------------------ // What the registers say. /// SDLC mode: WR4 bits 3 and 2 clear select synchronous, and bits 5 /// and 4 at `10` select SDLC among the synchronous modes. pub fn sdlc(self: *const Channel) bool { return self.registers[4] & 0x3c == 0x20; } /// Any synchronous mode: stop bits of zero. pub fn synchronous(self: *const Channel) bool { return self.registers[4] & 0x0c == 0; } pub fn receiverEnabled(self: *const Channel) bool { return self.registers[3] & 0x01 != 0; } pub fn transmitterEnabled(self: *const Channel) bool { return self.registers[5] & 0x08 != 0; } /// WR3 bit 2, which in SDLC mode drops frames not addressed to WR6 /// or to everyone. fn addressSearch(self: *const Channel) bool { return self.registers[3] & 0x04 != 0; } /// The rate this channel is set to, in bits a second. /// /// The manual's formula, turned round: "Time Constant = Clock /// Frequency / (2 x (Desired Rate) x (BR Clock Period)) - 2" (ZiLOG, /// 2001, § 5.2.15), so the rate is the clock over twice the time /// constant plus two, over the clock period. WR12 is the low byte of /// the constant and WR13 the high; the period is WR4's top two bits, /// which are the by-one, by-sixteen, by-thirty-two and by-sixty-four /// modes — except in the synchronous modes, where "the 1X mode is /// forced internally and these bits are ignored" (§ 5.2.5). pub fn rate(self: *const Channel) u32 { const constant: u32 = (@as(u32, self.registers[13]) << 8) | self.registers[12]; const period: u32 = if (self.synchronous()) 1 else switch (@as(u2, @truncate(self.registers[4] >> 6))) { 0b00 => 1, 0b01 => 16, 0b10 => 32, 0b11 => 64, }; const divisor = 2 * (constant + 2) * period; const answer = clock_hz / divisor; // A chip nobody has programmed has a time constant of zero, which // by the formula is a great deal faster than any wire ever ran. // Nothing is on the far end to care, and clamping keeps a caller // from dividing by it. return @max(1, answer); } /// How many bit times a byte takes: the data bits, a start bit, the /// stop bits and a parity bit if one was asked for. In the /// synchronous modes there is no framing and a byte is its bits. /// /// WR3 bits 7 and 6 are the receiver's word length and WR5 bits 6 and /// 5 the transmitter's; this is the transmitter's, since this is about /// how long a byte takes to leave. WR4's bits 3 and 2 are the stop /// bits and bit 0 is the parity enable. pub fn bitsPerByte(self: *const Channel) u32 { const data: u32 = switch (@as(u2, @truncate(self.registers[5] >> 5))) { 0b00 => 5, 0b01 => 7, 0b10 => 6, 0b11 => 8, }; if (self.synchronous()) return data; // One stop bit, one and a half, or two. The half is counted up, // since a byte cannot take a fraction of a cycle here. const stop: u32 = switch (@as(u2, @truncate(self.registers[4] >> 2))) { // Nought here means a synchronous mode, and `synchronous()` -- // which is defined as exactly this field being nought -- has // returned above. So this arm is dead, but it is dead by an // invariant two functions apart rather than by construction, // and `unreachable` is undefined behaviour in the optimised // build the moment somebody edits either one. One stop bit is // the least a frame can have, and costs nothing to say. 0b00 => 1, 0b01 => 1, 0b10 => 2, // one and a half, rounded up 0b11 => 2, }; const parity: u32 = @intFromBool(self.registers[4] & 0x01 != 0); return 1 + data + parity + stop; } /// How long a bit takes, in the machine's own cycles. pub fn cyclesPerBit(self: *const Channel, cycles_per_second: u64) u64 { return @max(1, cycles_per_second / self.rate()); } /// How long a byte takes, in the machine's own cycles. pub fn cyclesPerByte(self: *const Channel, cycles_per_second: u64) u64 { return cycles_per_second * self.bitsPerByte() / self.rate(); } // ------------------------------------------------------------------ // The transmitter, as the wire's end sees it. /// Whether the transmit buffer is empty, which is RR0's bit 2: set /// once the shifter has taken what was written, "reset while the CRC /// is sent in a synchronous or SDLC mode and while the transmit /// buffer is full" (ZiLOG, 2001, § 5.3.1). pub fn ready(self: *const Channel, cycle: u64) bool { if (self.buffered != null) return false; return cycle >= self.crc_until; } /// Whether everything written has wholly left the chip. pub fn allSent(self: *const Channel, cycle: u64) bool { return self.buffered == null and cycle >= self.shifter_until and cycle >= self.flag_until; } /// Whether the transmitter is putting anything on the line now: a /// byte, a check sequence or a closing flag. pub fn transmitting(self: *const Channel, cycle: u64) bool { return self.buffered != null or cycle < self.shifter_until or cycle < self.flag_until; } /// What the machine has sent asynchronously, oldest first. pub fn sent(self: *const Channel) []const u8 { return self.sending[0..self.sending_len]; } /// Drops the first `count` of those. pub fn consume(self: *Channel, count: usize) void { const taking = @min(count, self.sending_len); std.mem.copyForwards( u8, self.sending[0 .. self.sending_len - taking], self.sending[taking..self.sending_len], ); self.sending_len -= taking; } /// The frames the machine has sent and nobody has taken yet, oldest /// first. pub fn sentFrames(self: *const Channel) []const Frame { return self.frames[0..self.frames_len]; } /// Drops the first `count` of those. pub fn consumeFrames(self: *Channel, count: usize) void { const taking = @min(count, self.frames_len); std.mem.copyForwards( Frame, self.frames[0 .. self.frames_len - taking], self.frames[taking..self.frames_len], ); self.frames_len -= taking; } // ------------------------------------------------------------------ // The receiver, as the wire's end sees it. /// Hands the machine a byte from outside, as a serial line would. /// Says whether there was room; a byte with none is the overrun the /// chip reports, and it writes over the newest byte waiting, since /// "only the character that has been written over is flagged with /// this error". pub fn receive(self: *Channel, byte: u8) bool { return self.push(.{ .byte = byte }); } /// Whether there is room for another byte from outside. pub fn receiving(self: *const Channel) bool { return self.fifo_len < fifo_depth; } /// Hands the machine a whole frame from the network, to arrive at /// `cycle` or as soon after it as the line is free: the bytes without /// their check sequence, which the chip computes and delivers itself, /// and whether the check is to come out right. Says whether there was /// room to queue it. fn receiveFrame(self: *Channel, bytes: []const u8, good: bool, cycle: u64) bool { if (self.incoming_len == incoming_depth) return false; if (bytes.len + 2 > Frame.longest) return false; var frame: Frame = .{ .good = good }; @memcpy(frame.bytes[0..bytes.len], bytes); const check = fcs(bytes); frame.bytes[bytes.len] = @truncate(check); frame.bytes[bytes.len + 1] = @truncate(check >> 8); frame.len = bytes.len + 2; self.incoming[self.incoming_len] = .{ .frame = frame, .begins = cycle }; self.incoming_len += 1; return true; } /// Whether a frame from outside is still on its way in. pub fn frameArriving(self: *const Channel) bool { return self.incoming_len != 0; } /// Whether anything is on the line: this end sending, or a frame /// arriving. What a node listens for before it sends. pub fn lineBusy(self: *const Channel, cycle: u64) bool { return self.transmitting(cycle) or self.frameArriving(); } fn push(self: *Channel, received: Received) bool { if (self.fifo_len < fifo_depth) { self.fifo[self.fifo_len] = received; self.fifo_len += 1; return true; } var written_over = received; written_over.overrun = true; self.fifo[fifo_depth - 1] = written_over; return false; } /// Takes the oldest byte out of the FIFO, which is what a read of /// the data register or RR8 does. fn pop(self: *Channel) ?Received { if (self.fifo_len == 0) return null; const taken = self.fifo[0]; std.mem.copyForwards(Received, self.fifo[0 .. self.fifo_len - 1], self.fifo[1..self.fifo_len]); self.fifo_len -= 1; return taken; } fn reset(self: *Channel) void { self.* = .{}; } }; /// How many bytes a channel will hold on the way out before dropping /// them. Not a property of the chip, which holds one: this is the room /// between one look by whatever is emptying it and the next. pub const capacity = 256; /// What clocks the baud rate generators, in hertz. /// /// The crystal across the chip's `/RTxC` and `/SYNC` pins, which the /// firmware enables with WR11's top bit and clocks both the generator and /// the DPLL from. Its frequency is not written down in either of Apple's /// references, but the firmware says it: the AppleTalk driver in ROM 01 /// and ROM 3 loads a time constant of six into WR12 and WR13 for /// LocalTalk's 230,400 bits a second, and by the manual's formula that /// rate comes out of six only from 3.6864 MHz — which is also the crystal /// that makes the ordinary asynchronous rates exact, ten for 9600 and 382 /// for 300. pub const clock_hz: u32 = 3_686_400; /// Command codes, bits 5 to 3 of WR0. const point_high: u3 = 0b001; const reset_external_status: u3 = 0b010; const send_abort: u3 = 0b011; const enable_interrupt_on_next_character: u3 = 0b100; const reset_transmit_interrupt_pending: u3 = 0b101; const error_reset: u3 = 0b110; const reset_highest_ius: u3 = 0b111; /// The CRC reset codes, bits 7 and 6 of WR0. const reset_receive_crc: u2 = 0b01; const reset_transmit_crc: u2 = 0b10; const reset_underrun_eom_latch: u2 = 0b11; /// The bits of RR0. /// /// Bit 6, Transmit Underrun/EOM: "this bit is set by a channel or hardware /// reset when the transmitter is disabled", and "this bit is always 1 in /// Asynchronous mode". Bit 2, Transmit Buffer Empty: "this bit is always in /// the set condition after a hardware or channel reset". /// /// Bits 5 and 3 report the `/CTS` and `/DCD` pins, and nothing drives /// them, so they stay clear. Bit 1 is the baud rate generator's zero /// count, which is forced to zero while its interrupt is not enabled. pub const rx_available: u8 = 0x01; pub const zero_count: u8 = 0x02; pub const tx_buffer_empty: u8 = 0x04; pub const dcd: u8 = 0x08; pub const sync_hunt: u8 = 0x10; pub const cts: u8 = 0x20; pub const tx_underrun_eom: u8 = 0x40; pub const break_abort: u8 = 0x80; /// The bits of RR1. pub const all_sent: u8 = 0x01; pub const residue_mask: u8 = 0x0e; pub const parity_error: u8 = 0x10; pub const rx_overrun: u8 = 0x20; pub const crc_framing_error: u8 = 0x40; pub const end_of_frame: u8 = 0x80; /// The residue code for a frame whose data ends on a byte boundary, and /// the state the code is forced to by a reset: "this field is set to 011 /// by a channel or hardware reset" (ZiLOG, 2001, § 5.3.2), which Table /// 5-12 gives as "no residue" at eight bits a character. pub const residue_none: u8 = 0b011 << 1; /// The bits of RR3, the interrupt pending register. pub const b_ext_ip: u8 = 0x01; pub const b_tx_ip: u8 = 0x02; pub const b_rx_ip: u8 = 0x04; pub const a_ext_ip: u8 = 0x08; pub const a_tx_ip: u8 = 0x10; pub const a_rx_ip: u8 = 0x20; /// The bits of RR10: the DPLL's two missing-clock latches. pub const two_clocks_missing: u8 = 0x40; pub const one_clock_missing: u8 = 0x80; /// The bits of WR1. const ext_int_enable: u8 = 0x01; const tx_int_enable: u8 = 0x02; const rx_int_mode: u8 = 0x18; const rx_int_disabled: u8 = 0x00; const rx_int_first_or_special: u8 = 0x08; const rx_int_all_or_special: u8 = 0x10; const rx_int_special_only: u8 = 0x18; /// The bits of WR9. const master_interrupt_enable: u8 = 0x08; const status_high: u8 = 0x10; /// The bits of WR15 that enable an external/status interrupt: the six /// sources, in the positions RR0 reports them in. const ext_status_mask: u8 = break_abort | tx_underrun_eom | cts | sync_hunt | dcd | zero_count; /// The number of bit times on the wire after a LocalTalk frame's closing /// flag before the sender turns its driver off: "12 to 18 ones" (ZiLOG, /// 2001, Chapter 6), which the receiver sees as an abort. const trailing_ones: u64 = 12; /// Throws whichever of the four addresses this is, and answers it. /// /// `which` is the low two bits of the address: bit 0 picks the channel, and /// bit 1 picks the data register over the command register. pub fn access(self: *Scc, which: u2, writing: bool, value: u8, cycle: u64) u8 { self.advance(cycle); const channel: Which = @enumFromInt(@as(u1, @truncate(which))); const data = which & 0b10 != 0; defer self.touched(); if (data) { // Straight to the transmit or receive FIFO, and the pointer is // not touched by either. if (writing) { self.record(.{ .channel = channel, .register = 8, .data = true, .reading = false, .value = value, .cycle = cycle }); self.transmit(channel, value); return 0; } const taken = self.takeReceived(channel); self.record(.{ .channel = channel, .register = 8, .data = true, .reading = true, .value = taken, .cycle = cycle }); return taken; } if (writing) { self.writeCommand(channel, value); return 0; } return self.readCommand(channel); } /// Hands a channel a frame from the network, as `Channel.receiveFrame` /// does, and lets the chip know there is now something to wait for. pub fn receiveFrame(self: *Scc, channel: Which, bytes: []const u8, good: bool, cycle: u64) bool { self.advance(cycle); const queued = self.channelOf(channel).receiveFrame(bytes, good, cycle); self.touched(); return queued; } /// A read of a command register: the register the pointer names, and then /// the pointer goes back to zero. pub fn readCommand(self: *Scc, channel: Which) u8 { const at = self.pointer; self.pointer = 0; const value = self.readRegister(channel, at); self.record(.{ .channel = channel, .register = at, .data = false, .reading = true, .value = value, .cycle = self.now }); return value; } /// A write to a command register. /// /// With the pointer at zero this *is* WR0, and what is written is a /// pointer and a command rather than data; with the pointer anywhere else /// it is the register the pointer names, and afterwards the pointer is /// zero again. pub fn writeCommand(self: *Scc, channel: Which, value: u8) void { if (self.pointer != 0) { const at = self.pointer; self.pointer = 0; self.record(.{ .channel = channel, .register = at, .data = false, .reading = false, .value = value, .cycle = self.now }); self.writeRegister(channel, at, value); return; } self.record(.{ .channel = channel, .register = 0, .data = false, .reading = false, .value = value, .cycle = self.now }); var next: u4 = @truncate(value & 0x07); const command: u3 = @truncate(value >> 3); // Point High is not a command that does something; it is three bits // that mean "and add eight to that pointer", which is why it cannot be // issued alongside a real command. if (command == point_high) next |= 0x08; self.pointer = next; const port = self.channelOf(channel); switch (command) { 0, point_high => {}, // "After an External/Status interrupt (a change on a modem line or // a break condition, for example), the status bits in RR0 are // latched. This command re-enables the bits and allows interrupts // to occur again as a result of a status change." reset_external_status => { port.latched_status = null; port.ext_ip = false; port.previous_status = self.liveStatus(channel) & port.registers[15] & ext_status_mask; }, // "This command is used in SDLC mode to transmit a sequence of // eight to thirteen 1s. This command always empties the transmit // buffer and sets Tx Underrun/EOM bit in Read Register 0." A // frame in progress never gets its closing flag, so it is not a // frame, and nothing goes to the wire. send_abort => { port.buffered = null; port.in_frame = false; port.frame.len = 0; self.setEomLatch(channel, true); }, // "If the interrupt on First Received Character mode is selected, // this command is used to reactivate that mode after each message // is received." enable_interrupt_on_next_character => port.first_armed = true, reset_transmit_interrupt_pending => port.tx_ip = false, // "This command resets the error bits in RR1", and unlocks a FIFO // a special condition locked. error_reset => { port.overrun = false; port.last_status = .{ .byte = 0 }; if (port.registers[1] & rx_int_mode != rx_int_all_or_special) port.rx_ip = false; }, // The Interrupt Under Service bits are set only by an interrupt // acknowledge cycle, and nothing in this machine performs one: // the IIgs reads RR3 and RR2 instead. So there is never a highest // IUS to reset, and the command is a null one. reset_highest_ius => {}, } switch (@as(u2, @truncate(value >> 6))) { 0 => {}, // The receive checker is preset by the chip itself in SDLC mode, // "whenever the receiver is in Hunt mode or whenever a flag is // received", and there is nothing to preset here in any case. reset_receive_crc => {}, // "This command initializes the CRC generator. It is usually // issued in the initialization routine and after the CRC has been // transmitted." A frame begins here: what is written from now on // is the frame, until the underrun that closes it. reset_transmit_crc => if (port.sdlc()) { port.frame.len = 0; port.in_frame = true; port.frame_driven = port.rts; }, reset_underrun_eom_latch => self.setEomLatch(channel, false), } } /// One of the two ports. Public because whatever is on the far end of a /// wire has to be able to reach the end of it that is in here. pub fn channelOf(self: *Scc, which: Which) *Channel { return switch (which) { .a => &self.a, .b => &self.b, }; } fn channelOfConst(self: *const Scc, which: Which) *const Channel { return switch (which) { .a => &self.a, .b => &self.b, }; } // ---------------------------------------------------------------------- // Time. /// Brings both channels up to the cycle: bytes that have finished going /// out, frames that have closed, bytes that have arrived. Called with /// every access the machine makes, so until the next event is due it is /// two compares and nothing else. /// /// `next_event` can be trusted because everything that changes a /// channel's timing goes through one of three doors and each works it out /// afresh on the way out: `access` (its deferred `touched`), `receiveFrame` /// (the same), and the advancing below. The first version recomputed it /// here on every call to be safe, which was two walks over both channels /// per memory access and a fifth of the whole machine's time. pub fn advance(self: *Scc, cycle: u64) void { // Equal is let through: a register write can make an event due at // the very cycle of the write, and the machine asks again at that // same cycle on its way out of the access. if (cycle < self.now) return; self.now = cycle; if (cycle < self.next_event) return; self.advanceChannel(.a); self.advanceChannel(.b); self.next_event = @min(self.nextEventOf(.a), self.nextEventOf(.b)); } /// When the channel next does something without being asked. fn nextEventOf(self: *const Scc, channel: Which) u64 { const port = self.channelOfConst(channel); var next: u64 = std.math.maxInt(u64); if (port.buffered != null or (port.in_frame and port.frame.len != 0)) next = @min(next, port.shifter_until); if (port.crc_until != 0) next = @min(next, port.crc_until); if (port.incoming_len != 0) { const bit = port.cyclesPerBit(self.cycles_per_second); const frame = &port.incoming[0]; const begins = @max(frame.begins, @max(port.shifter_until, port.flag_until)); const flag_end = begins + 8 * bit; // The opening flag, then each byte, then the closing flag and // the ones after it. const due = if (port.arrived == 0) flag_end else if (port.arrived < frame.frame.len) flag_end + (port.arrived + 1) * 8 * bit else flag_end + (frame.frame.len + 1) * 8 * bit + trailing_ones * bit; next = @min(next, due); } return next; } /// Something was written that may have started a clock: after any /// register write the next event is worked out afresh. fn touched(self: *Scc) void { self.next_event = @min(self.nextEventOf(.a), self.nextEventOf(.b)); } fn advanceChannel(self: *Scc, channel: Which) void { const port = self.channelOf(channel); const now = self.now; const bit = port.cyclesPerBit(self.cycles_per_second); const byte_cycles = port.cyclesPerByte(self.cycles_per_second); // The transmitter: a buffered byte moves into the shifter as soon as // the shifter is free, and an SDLC frame with nothing more to send // underruns. while (now >= port.shifter_until) { if (port.buffered) |byte| { port.buffered = null; // It moved the moment the shifter emptied, whenever that was. self.shift(channel, byte, port.shifter_until, byte_cycles); if (port.registers[1] & tx_int_enable != 0 and port.tx_written) port.tx_ip = true; continue; } if (port.in_frame and port.frame.len != 0 and port.sdlc() and port.transmitterEnabled() and port.shifter_until != 0) { self.underrun(channel, bit); continue; } break; } // The end of the CRC and flag, which is when the flag is loaded and // the second transmit interrupt of a frame comes: "when the last bit // of the CRC has cleared the Transmit Shift Register and the flag or // sync character is loaded into the Transmit Shift Register, the // NMOS/CMOS version sets the TxIP and TBE bit." if (port.crc_until != 0 and now >= port.crc_until) { if (port.registers[1] & tx_int_enable != 0 and port.tx_written) port.tx_ip = true; port.crc_until = 0; } // The receiver: bytes of the oldest incoming frame that have had time // to arrive go into the FIFO, and the frame after it waits its turn. while (port.incoming_len != 0) { const frame = &port.incoming[0]; // A frame cannot start while this end is still transmitting, or // before it was handed in; it waits for the line. const line_free_at = @max(port.shifter_until, port.flag_until); if (frame.begins < line_free_at) frame.begins = line_free_at; // The opening flag first, then each byte eight bit times after // the one before. const flag_end = frame.begins + 8 * bit; if (now < flag_end) break; if (port.arrived == 0) self.openingFlag(channel, frame); while (port.arrived < frame.frame.len) { const due = flag_end + (port.arrived + 1) * 8 * bit; if (now < due) break; self.arriveByte(channel, frame, port.arrived); port.arrived += 1; } if (port.arrived < frame.frame.len) break; // The closing flag and then the ones the sender leaves the line // at before it lets go. const closed = flag_end + (frame.frame.len + 1) * 8 * bit; const let_go = closed + trailing_ones * bit; if (now < let_go) break; self.closingFlag(channel); self.dropIncoming(channel); } } /// Loads the shift register with a byte for `byte_cycles`. An /// asynchronous byte goes out to whoever is listening at once; a frame's /// byte goes into the frame. fn shift(self: *Scc, channel: Which, byte: u8, from: u64, byte_cycles: u64) void { const port = self.channelOf(channel); port.shifter_until = from + byte_cycles; if (port.sdlc()) { if (port.in_frame) { if (port.frame.len < Frame.longest - 2) { port.frame.bytes[port.frame.len] = byte; port.frame.len += 1; } else { port.frames_overlong += 1; } } return; } if (port.sending_len < capacity) { port.sending[port.sending_len] = byte; port.sending_len += 1; } } /// The transmitter has run out of bytes with a frame open. With the /// latch reset, "the transmitter sends either the accumulated CRC /// followed by flags, or an abort followed by flags, depending on the /// state of the Abort/Flag on the Underrun bit in the WR10" — the abort /// case being an error on the wire either way, and a frame that never /// closes here. With the latch set, "the transmitter sends flags without /// sending the CRC", and the frame is simply over without a check, which /// no receiver would accept. fn underrun(self: *Scc, channel: Which, bit: u64) void { const port = self.channelOf(channel); const started = port.shifter_until; const abort_on_underrun = port.registers[10] & 0x04 != 0; port.in_frame = false; if (!port.eom_latch and !abort_on_underrun) { port.crc_until = started + 16 * bit; port.flag_until = port.crc_until + 8 * bit; port.shifter_until = port.flag_until; const check = fcs(port.frame.slice()); port.frame.bytes[port.frame.len] = @truncate(check); port.frame.bytes[port.frame.len + 1] = @truncate(check >> 8); port.frame.len += 2; port.frame.good = true; if (port.frame_driven) { if (port.frames_len < Channel.frame_queue) { port.frames[port.frames_len] = port.frame; port.frames_len += 1; } } else { port.frames_undriven += 1; } } else { // A flag, or an abort and a flag: eight bits either way before // the line is idling, and nothing anyone could receive. port.flag_until = started + 8 * bit; port.shifter_until = port.flag_until; } port.frame.len = 0; // "The SCC sets the Tx Underrun/EOM latch when the CRC or abort is // loaded into the shift register for transmission." self.setEomLatch(channel, true); } /// The receiver has found a frame's opening flag: it leaves Hunt, and /// the abort before it is over. fn openingFlag(self: *Scc, channel: Which, frame: *const Incoming) void { const port = self.channelOf(channel); port.abort = false; // A frame not for this station is not received at all in address // search mode; the receiver sees the flag and goes on hunting. if (!port.receiverEnabled() or !port.sdlc()) return; if (port.addressSearch() and frame.frame.len != 0) { const address = frame.frame.bytes[0]; if (address != port.registers[6] and address != 0xff) return; } port.hunt = false; self.noteExternalStatus(channel); } /// A byte of the incoming frame has reached the receive FIFO. fn arriveByte(self: *Scc, channel: Which, frame: *const Incoming, index: usize) void { const port = self.channelOf(channel); // A receiver that is hunting is not receiving: the frame was not // for it, or it was disabled, or it is in the wrong mode. if (port.hunt or !port.receiverEnabled()) return; const last = index == frame.frame.len - 1; const received: Received = .{ .byte = frame.frame.bytes[index], .end_of_frame = last, .crc_error = last and !frame.frame.good, }; const had_room = port.push(received); if (!had_room) port.overrun = true; self.noteReceived(channel); } /// The closing flag has gone by, and after it the sender's ones: the /// receiver sees an abort and goes back to hunting, and both are /// external/status conditions. fn closingFlag(self: *Scc, channel: Which) void { const port = self.channelOf(channel); if (!port.receiverEnabled() or !port.sdlc()) return; port.abort = true; port.hunt = true; self.noteExternalStatus(channel); } fn dropIncoming(self: *Scc, channel: Which) void { const port = self.channelOf(channel); std.mem.copyForwards(Incoming, port.incoming[0 .. port.incoming_len - 1], port.incoming[1..port.incoming_len]); port.incoming_len -= 1; port.arrived = 0; } /// A byte has reached the FIFO, and the receive interrupt modes decide /// what that means (ZiLOG, 2001, § 2.4.7). fn noteReceived(self: *Scc, channel: Which) void { const port = self.channelOf(channel); const top = port.fifo[0]; const special = top.end_of_frame or top.overrun; switch (port.registers[1] & rx_int_mode) { rx_int_disabled => {}, // "The receiver requests an interrupt in this mode on the first // available character (or stored FIFO character) or on a special // condition." The special condition's interrupt comes when its // byte is read, not now. rx_int_first_or_special => if (port.first_armed) { port.rx_ip = true; port.first_armed = false; }, // "This mode allows an interrupt for every character received (or // character in the Receive FIFO)". rx_int_all_or_special => port.rx_ip = true, rx_int_special_only => if (port.fifo_len == 1 and special) { port.rx_ip = true; }, // A two-bit field with all four values named above, so nothing // reaches here; but `unreachable` is undefined behaviour in the // optimised build and doing nothing is free. else => {}, } } /// Reading the data register, which pops the FIFO and settles the /// interrupt the byte raised. fn takeReceived(self: *Scc, channel: Which) u8 { const port = self.channelOf(channel); const taken = port.pop() orelse return 0; port.last_status = taken; switch (port.registers[1] & rx_int_mode) { rx_int_disabled => {}, // "A special receive condition interrupt ... is guaranteed to // occur after the character having the special condition has // been read", and locks the FIFO's exit until the Error Reset // command. rx_int_first_or_special, rx_int_special_only => { if (taken.end_of_frame or taken.overrun) port.rx_ip = true else if (port.registers[1] & rx_int_mode == rx_int_first_or_special) port.rx_ip = false; }, // "In this mode of operation the IP is reset when the character is // removed from the FIFO", and set again by the next one. rx_int_all_or_special => port.rx_ip = port.fifo_len != 0, else => {}, // all four values named above; see `noteReceived` } return taken.byte; } /// A byte written to the data register: into the shifter if it is free, /// into the buffer if not, and dropped if the buffer is full too, which /// is what the chip does with a byte it has nowhere to put. fn transmit(self: *Scc, channel: Which, byte: u8) void { const port = self.channelOf(channel); port.tx_ip = false; port.tx_written = true; if (port.sdlc() and !port.transmitterEnabled()) return; if (self.now >= port.shifter_until and port.buffered == null) { self.shift(channel, byte, self.now, port.cyclesPerByte(self.cycles_per_second)); // The shifter took it at once, so the buffer is empty again at // once — and that is an interrupt, since the buffer was full for // the moment it took. if (port.registers[1] & tx_int_enable != 0) port.tx_ip = true; return; } if (port.buffered == null) port.buffered = byte; } fn setEomLatch(self: *Scc, channel: Which, value: bool) void { const port = self.channelOf(channel); const was = port.eom_latch; port.eom_latch = value; // "Only the 0-to-1 transition of this bit causes an interrupt." if (value and !was) self.noteExternalStatus(channel); } /// Puts a level on the carrier detect line of one channel. /// /// "Any transition on the /DCD pin, while no interrupt is pending, latches /// the state of the /DCD pin and generates an External/Status interrupt" /// (ZiLOG, 2001, § 5.3.1). Both halves of that are in /// `noteExternalStatus`: it does nothing unless the bit's own interrupt is /// enabled in WR15, and nothing while a latch is already closed. /// /// A level rather than an edge, because that is what a wire has. Setting /// it to what it already is is not a transition and raises nothing. pub fn setDcd(self: *Scc, channel: Which, on: bool) void { const port = self.channelOf(channel); if (port.dcd_line == on) return; port.dcd_line = on; self.noteExternalStatus(channel); } /// And clear to send, which the manual describes in the same words: "if /// the CTS IE bit is reset, it merely reports the current unlatched state /// of the /CTS pin". pub fn setCts(self: *Scc, channel: Which, on: bool) void { const port = self.channelOf(channel); if (port.cts_line == on) return; port.cts_line = on; self.noteExternalStatus(channel); } /// An external/status condition may have changed: if one whose interrupt /// is enabled did, and the latches are open, they close on the current /// status and the channel asks for an interrupt (ZiLOG, 2001, § 2.4.9). fn noteExternalStatus(self: *Scc, channel: Which) void { const port = self.channelOf(channel); const enabled = port.registers[15] & ext_status_mask; const live = self.liveStatus(channel) & enabled; if (live == port.previous_status) return; port.previous_status = live; if (port.latched_status != null) return; port.latched_status = self.liveStatus(channel); if (port.registers[1] & ext_int_enable != 0) port.ext_ip = true; } /// RR0 as it is at this instant, with no latches in the way. fn liveStatus(self: *const Scc, channel: Which) u8 { const port = self.channelOfConst(channel); var byte: u8 = 0; if (port.fifo_len != 0) byte |= rx_available; if (port.ready(self.now)) byte |= tx_buffer_empty; // The two lines from outside. "If the DCD IE bit in WR15 is set, this // bit indicates the state of the /DCD pin the last time the Enabled // External/Status bits changed... If the DCD IE is reset, this bit // merely reports the current, unlatched state of the /DCD pin" (ZiLOG, // 2001, § 5.3.1) -- and the latching half of that is the caller's // business rather than this function's: `readRegister` puts the // latched value in front of the live one for the bits whose interrupt // is enabled, which is the same sentence read from the other end. if (port.dcd_line) byte |= dcd; if (port.cts_line) byte |= cts; if (port.synchronous()) { if (port.hunt) byte |= sync_hunt; if (port.eom_latch) byte |= tx_underrun_eom; if (port.abort) byte |= break_abort; } else { // "This bit is always 1 in Asynchronous mode." byte |= tx_underrun_eom; } return byte; } /// Whether the chip is pulling its interrupt line: some source is both /// pending and enabled, and the master enable is on. "The MIE bit, WR9 /// D3, must be set for any interrupt to occur." pub fn interrupting(self: *const Scc) bool { if (self.master_interrupt & master_interrupt_enable == 0) return false; return self.pending() != 0; } /// RR3: the six interrupt pending bits, channel A's above channel B's. pub fn pending(self: *const Scc) u8 { var byte: u8 = 0; if (self.a.rx_ip) byte |= a_rx_ip; if (self.a.tx_ip) byte |= a_tx_ip; if (self.a.ext_ip) byte |= a_ext_ip; if (self.b.rx_ip) byte |= b_rx_ip; if (self.b.tx_ip) byte |= b_tx_ip; if (self.b.ext_ip) byte |= b_ext_ip; return byte; } /// What a read of register `at` gives back. /// /// The 8530 has nine read registers and sixteen places to look for them, so /// six of the sixteen are aliases of others. The pairings are Zilog's /// register map for a part with the status FIFO off, which is the part /// Apple fitted: the Hardware Reference (Apple Computer, Inc., 1989a) /// lists exactly nine read registers, and they are the nine below. pub fn readRegister(self: *Scc, channel: Which, at: u4) u8 { return switch (at) { // RR0, the transmit and receive buffer status, and the six // external status bits — the latter through the latches, for the // bits whose interrupts are enabled, while the latches are closed. 0, 4 => report: { const port = self.channelOf(channel); const live = self.liveStatus(channel); if (port.latched_status) |latched| { const enabled = port.registers[15] & ext_status_mask; break :report (live & ~enabled) | (latched & enabled); } break :report live; }, // RR1. Bit 0 is All Sent: "this bit is set when all characters // have completely cleared the transmitter pins", and "always set // in synchronous and SDLC modes". Above it the residue code, and // the errors that travel with the byte at the exit of the FIFO — // or with the last byte taken out of it, which is what the chip // keeps reporting until the next byte or an Error Reset. 1, 5 => report: { const port = self.channelOf(channel); var byte: u8 = residue_none; if (port.synchronous() or port.allSent(self.now)) byte |= all_sent; const status = if (port.fifo_len != 0) port.fifo[0] else port.last_status; if (status.end_of_frame) byte |= end_of_frame; if (status.end_of_frame and status.crc_error) byte |= crc_framing_error; if (port.overrun or status.overrun) byte |= rx_overrun; break :report byte; }, // RR2, the interrupt vector, which channel B modifies. 2, 6 => self.vector(channel), // RR3, the interrupt pending register. It exists only in channel // A, and "if this register is accessed in Channel B, all 0s are // returned". 3, 7 => if (channel == .a) self.pending() else 0, // RR8 is the receive FIFO by another name: "the receive data // register is also accessed as RR8", so reading it here takes the // byte away exactly as reading the data register does. 8 => self.takeReceived(channel), // RR10, the transmit and receive status: the loop bits, which // are about SDLC loop mode and this machine never enters it, and // the DPLL's missing-clock latches, which are what a LocalTalk // node reads to know whether the line is quiet. 10 => self.missingClocks(channel), // The baud rate generator's time constant, which reads back what // was written to WR12 and WR13. Pointing at 9 reaches RR13. 9, 13 => self.channelOf(channel).registers[13], 12 => self.channelOf(channel).registers[12], // The external status interrupt control, which reads back WR15. // Pointing at 11 reaches it too. 11, 15 => self.channelOf(channel).registers[15], // The 8530 has no RR14 — the nine read registers are 0, 1, 2, 3, // 8, 10, 12, 13 and 15, and 14 is not among them. 14 => 0, }; } /// RR10's missing-clock bits. In FM mode the DPLL expects a transition /// in every bit cell, and "if the DPLL does not see an edge between the /// middle of count 12 and the middle of count 19 in two successive 0 to /// 31 count cycles, a line error condition is assumed ... the Two Clocks /// Missing bit in RR10 is set to 1 and latched" (ZiLOG, 2001, § 3.4.2), /// until a Reset Missing Clock or Enter Search Mode command. A LocalTalk /// line between frames has no transitions on it at all, so an idle line /// is two missing clocks two bit cells after the latches were last reset /// — and a frame arriving is a line with a clock on it. fn missingClocks(self: *const Scc, channel: Which) u8 { const port = self.channelOfConst(channel); const fm = port.registers[14] & 0xe0 == 0xc0 or port.registers[10] & 0x60 == 0x60; if (!fm or port.frameArriving()) return 0; const bit = port.cyclesPerBit(self.cycles_per_second); if (self.now < port.missing_clock_reset_at + 2 * bit) return 0; return one_clock_missing | two_clocks_missing; } /// RR2, which is one register read two ways. /// /// Channel A gives back the vector exactly as it was written. Channel B /// gives it back with three of its bits replaced by the reason for the /// highest-priority interrupt, so that a program can read one byte and /// know what happened. Which three depends on WR9's Status High/Status Low /// bit: set, and the chip modifies bits 6 to 4; clear, and it modifies bits /// 3 to 1. The codes are Table 5-6's, and for nothing pending the manual /// gives it outright: "if no interrupts are pending, the status is /// V3,V2,V1 = 011, or V6,V5,V4 = 110". pub fn vector(self: *const Scc, channel: Which) u8 { if (channel == .a) return self.interrupt_vector; const code: u3 = self.highestPending(); const high = self.master_interrupt & status_high != 0; if (high) { // Bits 6 to 4 carry the code with its bits reversed, so that 011 // there is 110. const reversed: u3 = @bitReverse(code); return (self.interrupt_vector & ~@as(u8, 0x70)) | (@as(u8, reversed) << 4); } return (self.interrupt_vector & ~@as(u8, 0x0e)) | (@as(u8, code) << 1); } /// The status code for the highest-priority pending interrupt, in the /// order Table 5-6 gives: channel A above B, and within a channel the /// receiver's special condition, then its character, then the /// transmitter, then external/status. fn highestPending(self: *const Scc) u3 { inline for (.{ Which.a, Which.b }) |which| { const port = self.channelOfConst(which); const base: u3 = if (which == .a) 0b100 else 0b000; if (port.rx_ip) { const status = if (port.fifo_len != 0) port.fifo[0] else port.last_status; if (status.end_of_frame or status.overrun) return base | 0b011; return base | 0b010; } if (port.tx_ip) return base | 0b000; if (port.ext_ip) return base | 0b001; } return 0b011; } fn writeRegister(self: *Scc, channel: Which, at: u4, value: u8) void { const port = self.channelOf(channel); switch (at) { // The two the chip has one of. 2 => self.interrupt_vector = value, 9 => { self.master_interrupt = value; // Bits 7 and 6 are not stored state but a reset command: 01 // resets channel B, 10 resets channel A, and 11 is a hardware // reset of the whole chip. switch (@as(u2, @truncate(value >> 6))) { 0b00 => {}, 0b01 => self.b.reset(), 0b10 => self.a.reset(), 0b11 => self.reset(), } }, 3 => { const was_enabled = port.receiverEnabled(); port.registers[3] = value; // "The receiver is in Hunt mode when it is enabled", and the // Enter Hunt Mode bit "is a command, and writing a 0 to it // has no effect." if (port.receiverEnabled() and !was_enabled) { port.hunt = true; port.first_armed = true; port.fifo_len = 0; } else if (!port.receiverEnabled() and was_enabled) { port.hunt = true; } if (value & 0x10 != 0) port.hunt = true; self.noteExternalStatus(channel); }, 5 => { const was_enabled = port.transmitterEnabled(); port.registers[5] = value; port.rts = value & 0x02 != 0; if (!port.transmitterEnabled() and was_enabled) { // "If the transmitter is disabled during the transmission // of a character, that character will be 'completely // sent'"; what waits in the buffer is not. port.buffered = null; port.in_frame = false; port.frame.len = 0; port.tx_written = false; self.setEomLatch(channel, true); } }, 14 => { port.registers[14] = value; // The DPLL commands in the top three bits: Reset Missing // Clock (010), Disable DPLL (011) and Enter Search Mode (001) // all reset the missing-clock latches. switch (@as(u3, @truncate(value >> 5))) { 0b001, 0b010, 0b011 => port.missing_clock_reset_at = self.now, else => {}, } }, 15 => { port.registers[15] = value; port.previous_status = self.liveStatus(channel) & value & ext_status_mask; }, else => port.registers[at] = value, } } /// What the reset line does, and what a Force Hardware Reset written to /// WR9 does: both channels, both shared registers, and the pointer. pub fn reset(self: *Scc) void { const rate_ = self.cycles_per_second; const now = self.now; self.* = .{}; self.cycles_per_second = rate_; self.now = now; } }; const testing = std.testing; /// The four addresses as the machine sees them, by the low two bits. const b_command: u2 = 0b00; const a_command: u2 = 0b01; const b_data: u2 = 0b10; const a_data: u2 = 0b11; test "a register is reached in two steps and the pointer falls back to zero" { // The whole protocol in one test. Write the pointer to WR0; the next // command access reaches that register; and the one after that is a WR0 // write again, because the pointer reset itself. var scc: Scc = .{}; _ = scc.access(a_command, true, 12, 0); // point at WR12 try testing.expectEqual(@as(u4, 12), scc.pointer); _ = scc.access(a_command, true, 0x5a, 0); // and write it try testing.expectEqual(@as(u4, 0), scc.pointer); try testing.expectEqual(@as(u8, 0x5a), scc.a.registers[12]); // Reading it back takes two steps as well. _ = scc.access(a_command, true, 12, 0); try testing.expectEqual(@as(u8, 0x5a), scc.access(a_command, false, 0, 0)); try testing.expectEqual(@as(u4, 0), scc.pointer); // And with the pointer at zero, a read is a read of RR0 in a single cycle, // which is what the manual says it is for. try testing.expectEqual( @as(u8, Scc.tx_underrun_eom | Scc.tx_buffer_empty), scc.access(a_command, false, 0, 0), ); } test "there is one pointer for the whole chip, not one per channel" { // "The pointer bits may be written in either channel because only one set // exists in the Z85X30." So which channel is reached is decided by the // address of the second access, and the first has no say. var scc: Scc = .{}; _ = scc.access(b_command, true, 12, 0); // point at WR12 from channel B _ = scc.access(a_command, true, 0x11, 0); // and land in channel A try testing.expectEqual(@as(u8, 0x11), scc.a.registers[12]); try testing.expectEqual(@as(u8, 0x00), scc.b.registers[12]); _ = scc.access(a_command, true, 12, 0); // and the other way about _ = scc.access(b_command, true, 0x22, 0); try testing.expectEqual(@as(u8, 0x22), scc.b.registers[12]); try testing.expectEqual(@as(u8, 0x11), scc.a.registers[12]); } test "the registers above seven need the Point High command with them" { // Three pointer bits reach eight registers; the other eight need the // command code 001 written alongside, which is why a real command cannot // be issued at the same time as pointing high. var scc: Scc = .{}; _ = scc.access(a_command, true, 0x05, 0); // pointer 5, no command try testing.expectEqual(@as(u4, 5), scc.pointer); _ = scc.access(a_command, false, 0, 0); // spend it _ = scc.access(a_command, true, 0x0d, 0); // pointer 5, Point High try testing.expectEqual(@as(u4, 13), scc.pointer); _ = scc.access(a_command, true, 0x77, 0); try testing.expectEqual(@as(u8, 0x77), scc.a.registers[13]); // And a command that is not Point High leaves the pointer in the low half. _ = scc.access(a_command, true, 0x35, 0); // pointer 5, Error Reset try testing.expectEqual(@as(u4, 5), scc.pointer); } test "the data register does not disturb the pointer" { // "A read or write with D//C High accesses the data registers directly, // and independently of the state of the pointer bits." var scc: Scc = .{}; _ = scc.access(a_command, true, 12, 0); // point at WR12 _ = scc.access(a_data, true, 0x99, 0); // transmit a byte into the void try testing.expectEqual(@as(u4, 12), scc.pointer); _ = scc.access(b_data, false, 0, 0); // and receive one that never arrived try testing.expectEqual(@as(u4, 12), scc.pointer); // The pointer is still good, so the next command access lands in WR12. _ = scc.access(a_command, true, 0x44, 0); try testing.expectEqual(@as(u8, 0x44), scc.a.registers[12]); } test "a read of the command register puts the pointer back to a known state" { // Which is exactly what this machine's firmware does with the only two // accesses it makes to any of these addresses: "if, for some reason, the // state of the pointer bits is unknown they may be reset to 0 by // performing a read cycle". Two reads must answer the same thing twice. var scc: Scc = .{}; scc.pointer = 9; // whatever it was left at // The first read is the one that does the resetting, and what it gives // back is whatever the stale pointer was aimed at — here RR13, the baud // rate constant. That byte is not the status and a program cannot use it, // which is why the sequence is two reads and not one. _ = scc.access(a_command, false, 0, 0); try testing.expectEqual(@as(u4, 0), scc.pointer); // From there on every read is RR0, and answers the same thing each time. const second = scc.access(a_command, false, 0, 0); const third = scc.access(a_command, false, 0, 0); try testing.expectEqual(@as(u4, 0), scc.pointer); try testing.expectEqual(second, third); try testing.expectEqual(@as(u8, Scc.tx_underrun_eom | Scc.tx_buffer_empty), second); } test "the status register says a port with nothing plugged into it" { // The transmit buffer is empty because it is; nothing is waiting because // nothing arrived; no modem is raising a line because there is no modem. // Every one of those is the truth rather than a placeholder. var scc: Scc = .{}; const rr0 = scc.readRegister(.a, 0); try testing.expectEqual(@as(u8, 0x04), rr0 & 0x04); // transmit buffer empty try testing.expectEqual(@as(u8, 0x40), rr0 & 0x40); // and nothing underran try testing.expectEqual(@as(u8, 0x00), rr0 & 0x01); // no character waiting try testing.expectEqual(@as(u8, 0x00), rr0 & 0x08); // no carrier detected try testing.expectEqual(@as(u8, 0x00), rr0 & 0x20); // nothing clear to send try testing.expectEqual(@as(u8, 0x00), rr0 & 0x80); // and no break // Register 4 is an alias of it, which is how the chip fits nine read // registers into sixteen places to look. try testing.expectEqual(rr0, scc.readRegister(.a, 4)); } test "channel B's interrupt vector says why, and there is no why" { var scc: Scc = .{}; _ = scc.access(a_command, true, 2, 0); // point at WR2 _ = scc.access(a_command, true, 0xf0, 0); // the vector // WR2 is the chip's rather than a channel's, so it is the same one. try testing.expectEqual(@as(u8, 0xf0), scc.interrupt_vector); // Channel A gives it back untouched. try testing.expectEqual(@as(u8, 0xf0), scc.vector(.a)); // Channel B replaces bits 3 to 1 with the no-interrupt-pending code, 011. try testing.expectEqual(@as(u8, 0xf6), scc.vector(.b)); // With WR9's Status High bit set it modifies bits 6 to 4 instead, and the // code there is 110. _ = scc.access(a_command, true, 9, 0); _ = scc.access(a_command, true, 0x10, 0); try testing.expectEqual(@as(u8, 0xe0), scc.vector(.b)); try testing.expectEqual(@as(u8, 0xf0), scc.vector(.a)); } test "WR9's top two bits are a reset rather than a value" { var scc: Scc = .{}; _ = scc.access(a_command, true, 12, 0); _ = scc.access(a_command, true, 0xaa, 0); _ = scc.access(b_command, true, 12, 0); _ = scc.access(b_command, true, 0xbb, 0); // Reset channel B alone. _ = scc.access(a_command, true, 9, 0); _ = scc.access(a_command, true, 0x40, 0); try testing.expectEqual(@as(u8, 0x00), scc.b.registers[12]); try testing.expectEqual(@as(u8, 0xaa), scc.a.registers[12]); // And then the whole chip, which takes the shared registers with it. _ = scc.access(a_command, true, 9, 0); _ = scc.access(a_command, true, 0xc0, 0); try testing.expectEqual(@as(u8, 0x00), scc.a.registers[12]); try testing.expectEqual(@as(u8, 0x00), scc.master_interrupt); try testing.expectEqual(@as(u4, 0), scc.pointer); } /// A channel set up the way the IIgs firmware sets up a serial port: 9600 /// baud, eight bits, one stop bit, no parity. fn asyncPort(scc: *Scc, which: Scc.Which) *Scc.Channel { const port = scc.channelOf(which); port.registers[4] = 0b0100_0100; // by sixteen, one stop bit, no parity port.registers[5] = 0b0110_1000; // eight bits, transmitter on port.registers[12] = 10; port.registers[13] = 0; return port; } test "a byte written to the data register goes out and takes time doing it" { var scc: Scc = .{}; // 9600 baud, eight bits, one stop bit, no parity: the by-sixteen clock in // WR4's top bits with a time constant of ten, which is what the manual's // formula gives for that rate at 3.6864 MHz. const port = asyncPort(&scc, .a); try testing.expectEqual(@as(u32, 9600), port.rate()); try testing.expectEqual(@as(u32, 10), port.bitsPerByte()); // Channel A's data register is $c03b, which is the two low bits 0b11. _ = scc.access(0b11, true, 'H', 0); _ = scc.access(0b11, true, 'i', 0); try testing.expectEqualStrings("H", port.sent()); // The first byte went straight into the shifter, and the second is // waiting behind it: the transmit buffer is not empty, and will not be // for a byte time, which at 9600 baud on a 2.8 MHz machine is a little // under three thousand cycles. try testing.expect(!port.ready(0)); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.tx_buffer_empty); scc.advance(port.shifter_until); try testing.expectEqualStrings("Hi", port.sent()); try testing.expect(port.ready(port.shifter_until)); try testing.expect(scc.readRegister(.a, 0) & Scc.tx_buffer_empty != 0); // Whatever is on the far end takes them, and then there is nothing to take. port.consume(2); try testing.expectEqual(@as(usize, 0), port.sent().len); } test "the transmitter is two bytes deep, so one byte empties the buffer at once" { // "Transmit Buffer Empty ... is reset when a character is loaded into the // transmit buffer" and set when the shifter takes it — which, with the // shifter idle, is immediately. A program that writes one byte and polls // finds the buffer empty; one that writes two waits. var scc: Scc = .{}; const port = asyncPort(&scc, .a); _ = scc.access(a_data, true, 'x', 1000); try testing.expect(scc.readRegister(.a, 0) & Scc.tx_buffer_empty != 0); // All Sent, though, waits for the byte to have left the pins. try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 1) & Scc.all_sent); scc.advance(port.shifter_until); try testing.expect(scc.readRegister(.a, 1) & Scc.all_sent != 0); } test "a byte from outside shows in the status and is taken by reading" { var scc: Scc = .{}; const port = scc.channelOf(.b); // Nothing has arrived, so nothing is available. try testing.expectEqual(@as(u8, 0), scc.readRegister(.b, 0) & Scc.rx_available); try testing.expect(port.receiving()); // One does, and RR0 says so. try testing.expect(port.receive('Z')); try testing.expect(scc.readRegister(.b, 0) & Scc.rx_available != 0); // Reading channel B's data register — $c03a, the low bits 0b10 — takes it // away, and then there is room for another. try testing.expectEqual(@as(u8, 'Z'), scc.access(0b10, false, 0, 0)); try testing.expectEqual(@as(u8, 0), scc.readRegister(.b, 0) & Scc.rx_available); try testing.expect(port.receiving()); // RR8 is the same register by another name and takes the byte the same way. try testing.expect(port.receive('Q')); try testing.expectEqual(@as(u8, 'Q'), scc.readRegister(.b, 8)); try testing.expect(port.receiving()); } test "the receive FIFO is three deep and a fourth byte is an overrun" { // "The 8530's receive FIFO is three deep": three bytes wait in order, // and a fourth with nowhere to go writes over the newest, which is the // one the chip flags, and the overrun stays in RR1 until an Error Reset. var scc: Scc = .{}; const port = scc.channelOf(.b); try testing.expect(port.receive('1')); try testing.expect(port.receive('2')); try testing.expect(port.receive('3')); try testing.expect(!port.receiving()); try testing.expect(!port.receive('4')); try testing.expectEqual(@as(u8, '1'), scc.access(b_data, false, 0, 0)); try testing.expectEqual(@as(u8, '2'), scc.access(b_data, false, 0, 0)); // The written-over byte carries the error, and reading it latches it. try testing.expect(scc.readRegister(.b, 1) & Scc.rx_overrun != 0); try testing.expectEqual(@as(u8, '4'), scc.access(b_data, false, 0, 0)); try testing.expect(scc.readRegister(.b, 1) & Scc.rx_overrun != 0); _ = scc.access(b_command, true, 0x30, 0); // Error Reset try testing.expectEqual(@as(u8, 0), scc.readRegister(.b, 1) & Scc.rx_overrun); } test "the two channels are two ports and do not hear each other" { var scc: Scc = .{}; _ = asyncPort(&scc, .a); _ = asyncPort(&scc, .b); _ = scc.access(0b11, true, 'A', 0); // channel A's data register _ = scc.access(0b10, true, 'B', 0); // channel B's try testing.expectEqualStrings("A", scc.channelOf(.a).sent()); try testing.expectEqualStrings("B", scc.channelOf(.b).sent()); try testing.expect(scc.channelOf(.a).receive('x')); try testing.expectEqual(@as(u8, 0), scc.readRegister(.b, 0) & Scc.rx_available); try testing.expect(scc.readRegister(.a, 0) & Scc.rx_available != 0); } test "the rate comes out of the time constant the way the manual puts it in" { var scc: Scc = .{}; const port = scc.channelOf(.a); port.registers[4] = 0b0100_0100; // the by-sixteen clock // The manual's formula run forwards: a constant of ten is 9600, and one of // 382 is 300. Both come out whole, which is what the clock is chosen for. port.registers[12] = 10; try testing.expectEqual(@as(u32, 9600), port.rate()); port.registers[12] = 382 & 0xff; port.registers[13] = 382 >> 8; try testing.expectEqual(@as(u32, 300), port.rate()); // The clock period is WR4's top two bits, and by one is sixteen times the // rate of by sixteen. port.registers[4] = 0b0000_0100; try testing.expectEqual(@as(u32, 4800), port.rate()); } // --------------------------------------------------------------------------- // The network. test "the frame check is CRC-CCITT the way the wire carries it" { // The reflected CRC-CCITT with a preset of ones and the result // inverted, which is the check X.25 and HDLC put on a frame: its // catalogued check value for the digits one to nine is $906e, and a // frame carrying its own check leaves the constant remainder behind. try testing.expectEqual(@as(u16, 0x906e), Scc.fcs("123456789")); const check = Scc.fcs("123456789"); const framed = "123456789" ++ [_]u8{ @truncate(check), @truncate(check >> 8) }; try testing.expect(Scc.fcsAgrees(framed)); try testing.expectEqual(Scc.fcs_good, Scc.fcs(framed)); // Change a bit and the remainder is something else. var damaged = framed.*; damaged[3] ^= 0x10; try testing.expect(!Scc.fcsAgrees(&damaged)); } /// Programs a channel the way the IIgs firmware programs it for LocalTalk, /// register by register from the table at `$ff/2beb` in ROM 01: SDLC, eight /// bits, FM0 with the CRC preset to ones and flags on idle, the transmitter /// clocked from the baud rate generator and the receiver from the DPLL, a /// time constant of six, the DPLL in FM mode and searching, and the /// receiver interrupting on the first character of a frame. fn localtalkPort(scc: *Scc, which: Scc.Which) *Scc.Channel { const command: u2 = if (which == .a) a_command else b_command; const table = [_]u8{ 0x01, 0x00, 0x0f, 0x00, 0x04, 0x20, 0x03, 0xd0, 0x05, 0xe9, 0xc0, 0x80, 0x05, 0xe1, 0x07, 0x7e, 0x0a, 0xe0, 0x0b, 0xf2, 0x0c, 0x06, 0x0d, 0x00, 0x0e, 0xc1, 0x0e, 0x21, 0x01, 0x08, }; for (table) |byte| _ = scc.access(command, true, byte, 0); return scc.channelOf(which); } /// Sends a frame the way the firmware's routine at `$ff/3220` does: the /// synchronisation pulse on RTS, the transmitter on, two flags' worth of /// waiting, the CRC generator reset, the first byte, the EOM latch reset, /// then each byte as the buffer empties, and after the last the wait for the /// EOM bit and the buffer, and the driver off. fn sendFrame(scc: *Scc, which: Scc.Which, bytes: []const u8, from: u64) u64 { const command: u2 = if (which == .a) a_command else b_command; const data: u2 = if (which == .a) a_data else b_data; var now = from; _ = scc.access(command, true, 0x05, now); _ = scc.access(command, true, 0xe3, now); // RTS on, transmitter off: the pulse now += 40; _ = scc.access(command, true, 0x05, now); _ = scc.access(command, true, 0xe1, now); // RTS off now += 40; _ = scc.access(command, true, 0x05, now); _ = scc.access(command, true, 0xeb, now); // transmitter and RTS on now += 200; _ = scc.access(command, true, 0x80, now); // Reset Tx CRC _ = scc.access(data, true, bytes[0], now); _ = scc.access(command, true, 0xc0, now); // Reset Tx Underrun/EOM latch for (bytes[1..]) |byte| { while (scc.access(command, false, 0, now) & Scc.tx_buffer_empty == 0) now += 12; _ = scc.access(data, true, byte, now); } while (scc.access(command, false, 0, now) & Scc.tx_underrun_eom == 0) now += 12; while (scc.access(command, false, 0, now) & Scc.tx_buffer_empty == 0) now += 12; now += 100; _ = scc.access(command, true, 0x05, now); _ = scc.access(command, true, 0xe3, now); // transmitter off now += 300; _ = scc.access(command, true, 0x05, now); _ = scc.access(command, true, 0xe1, now); // driver off return now; } test "the firmware's table puts the chip in SDLC at LocalTalk's rate" { var scc: Scc = .{}; const port = localtalkPort(&scc, .a); try testing.expect(port.sdlc()); // A time constant of six from a 3.6864 MHz crystal, and the synchronous // modes force the by-one clock whatever WR4's top bits say. try testing.expectEqual(@as(u32, 230_400), port.rate()); try testing.expectEqual(@as(u32, 8), port.bitsPerByte()); // Thirty-five microseconds a byte, near enough, at 2.8 MHz. try testing.expectEqual(@as(u64, 97), port.cyclesPerByte(2_800_000)); // The receiver is off until the firmware wants it, hunting, and set to // interrupt on the first character of a frame. try testing.expect(!port.receiverEnabled()); try testing.expect(scc.readRegister(.a, 0) & Scc.sync_hunt != 0); try testing.expectEqual(@as(u8, 0x08), port.registers[1]); } test "an enquiry frame goes out as its bytes, its check and its flag" { // The lapENQ the firmware sends when it comes up: the node number it is // trying, twice, and the type $81 — with the check sequence the chip // appends after it, which a receiver running the same check accepts. var scc: Scc = .{}; const port = localtalkPort(&scc, .a); const finished = sendFrame(&scc, .a, &.{ 0x01, 0x01, 0x81 }, 10_000); try testing.expectEqual(@as(usize, 1), port.sentFrames().len); const frame = port.sentFrames()[0]; try testing.expectEqual(@as(usize, 5), frame.len); try testing.expectEqualSlices(u8, &.{ 0x01, 0x01, 0x81 }, frame.payload()); try testing.expect(Scc.fcsAgrees(frame.slice())); // Three bytes, two of check and a flag: forty-eight bit times on the // wire after the first byte went in, which is what the firmware waited // for before it turned the driver off. try testing.expect(finished - 10_000 > 48 * 12); try testing.expect(port.allSent(finished)); port.consumeFrames(1); try testing.expectEqual(@as(usize, 0), port.sentFrames().len); } test "the underrun bit is down from the latch reset until the check goes out" { // Which is what the firmware waits on after the last byte: "the SCC sets // the Tx Underrun/EOM latch when the CRC or abort is loaded into the // shift register", and until then the bit reads clear. A model that had // it always set would let the driver be turned off with the check still // to come. var scc: Scc = .{}; const port = localtalkPort(&scc, .a); _ = scc.access(a_command, true, 0x05, 1000); _ = scc.access(a_command, true, 0xeb, 1000); _ = scc.access(a_command, true, 0x80, 1200); _ = scc.access(a_data, true, 0xff, 1200); _ = scc.access(a_command, true, 0xc0, 1200); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.tx_underrun_eom); // The second byte waits in the buffer behind the first, and goes into // the shifter the moment the first has left it; the third waits behind // the second in the same way. _ = scc.access(a_data, true, 0x01, 1250); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.tx_buffer_empty); scc.advance(port.shifter_until); try testing.expect(scc.readRegister(.a, 0) & Scc.tx_buffer_empty != 0); _ = scc.access(a_data, true, 0x84, scc.now); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.tx_buffer_empty); // The last byte is in the shifter; the buffer is empty and the latch // still down. scc.advance(port.shifter_until); try testing.expect(scc.readRegister(.a, 0) & Scc.tx_buffer_empty != 0); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.tx_underrun_eom); // Then the shifter empties, the check starts, and the latch goes up // while the buffer reads full for the check's sixteen bits. scc.advance(port.shifter_until + 1); try testing.expect(scc.readRegister(.a, 0) & Scc.tx_underrun_eom != 0); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.tx_buffer_empty); scc.advance(port.crc_until); try testing.expect(scc.readRegister(.a, 0) & Scc.tx_buffer_empty != 0); try testing.expectEqual(@as(usize, 1), port.sentFrames().len); } test "a frame sent with the driver off goes nowhere" { // RTS is the line driver's enable on this machine. A frame the // transmitter sends while it is down is a frame nobody on the wire can // hear, and it is counted rather than delivered. var scc: Scc = .{}; const port = localtalkPort(&scc, .a); _ = scc.access(a_command, true, 0x05, 1000); _ = scc.access(a_command, true, 0xe9, 1000); // transmitter on, RTS off _ = scc.access(a_command, true, 0x80, 1000); _ = scc.access(a_data, true, 0xff, 1000); _ = scc.access(a_command, true, 0xc0, 1000); scc.advance(1000 + 10 * port.cyclesPerByte(2_800_000)); try testing.expectEqual(@as(usize, 0), port.sentFrames().len); try testing.expectEqual(@as(u32, 1), port.frames_undriven); } test "a frame arriving is bytes in the FIFO with the end of frame on the last" { // What the receiver does with a lapACK from node 1, the way the // firmware reads it: a byte every eight bit times after the opening // flag, RR0 saying one is there, RR1 saying whether it is the last, and // the two check bytes after the data with End of Frame on the second. var scc: Scc = .{}; const port = localtalkPort(&scc, .a); _ = scc.access(a_command, true, 0x06, 0); _ = scc.access(a_command, true, 0x01, 0); // this is node 1 _ = scc.access(a_command, true, 0x03, 0); _ = scc.access(a_command, true, 0xdd, 0); // receiver on, address search const bit = port.cyclesPerBit(2_800_000); try testing.expect(scc.receiveFrame(.a, &.{ 0x01, 0x02, 0x82 }, true, 5000)); // Not yet: the opening flag takes eight bit times, and the first byte // eight more. scc.advance(5000 + 8 * bit); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.rx_available); // The flag has been seen, though, and the receiver has left Hunt. try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.sync_hunt); scc.advance(5000 + 16 * bit + 1); try testing.expect(scc.readRegister(.a, 0) & Scc.rx_available != 0); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 1) & Scc.end_of_frame); try testing.expectEqual(@as(u8, 0x01), scc.access(a_data, false, 0, 5000 + 16 * bit + 1)); // Two more bytes and then the check, all in their own time: each is // there eight bit times after the one before, and not before. scc.advance(5000 + 16 * bit + 2 * 8 * bit + 1); try testing.expectEqual(@as(u8, 0x02), scc.access(a_data, false, 0, scc.now)); try testing.expectEqual(@as(u8, 0x82), scc.access(a_data, false, 0, scc.now)); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.rx_available); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 1) & Scc.end_of_frame); scc.advance(scc.now + 8 * bit); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 1) & Scc.end_of_frame); _ = scc.access(a_data, false, 0, scc.now); // the first check byte scc.advance(scc.now + 8 * bit); // The last byte carries End of Frame, and the check agreed. try testing.expect(scc.readRegister(.a, 1) & Scc.end_of_frame != 0); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 1) & Scc.crc_framing_error); _ = scc.access(a_data, false, 0, scc.now); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.rx_available); // After the frame the sender leaves the line at ones, which the // receiver reports as an abort, and it is hunting again. scc.advance(scc.now + 40 * bit); try testing.expect(scc.readRegister(.a, 0) & Scc.break_abort != 0); try testing.expect(scc.readRegister(.a, 0) & Scc.sync_hunt != 0); try testing.expect(!port.frameArriving()); } test "a frame for another node is not received in address search mode" { var scc: Scc = .{}; const port = localtalkPort(&scc, .a); _ = scc.access(a_command, true, 0x06, 0); _ = scc.access(a_command, true, 0x07, 0); // this is node 7 _ = scc.access(a_command, true, 0x03, 0); _ = scc.access(a_command, true, 0xdd, 0); const bit = port.cyclesPerBit(2_800_000); // To node 1: nothing arrives. try testing.expect(scc.receiveFrame(.a, &.{ 0x01, 0x02, 0x82 }, true, 1000)); scc.advance(1000 + 100 * bit); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.rx_available); // To everyone: it does. try testing.expect(scc.receiveFrame(.a, &.{ 0xff, 0x02, 0x81 }, true, scc.now)); scc.advance(scc.now + 100 * bit); try testing.expect(scc.readRegister(.a, 0) & Scc.rx_available != 0); } test "the first byte of a frame interrupts, and the second is behind it" { // The firmware's handler reads the data register twice before it hands // over to the link layer, for the destination and the source, and it can // because the interrupt comes with the first byte and the handler takes // longer to get there than a byte takes to arrive. var scc: Scc = .{}; const port = localtalkPort(&scc, .a); _ = scc.access(a_command, true, 0x09, 0); _ = scc.access(a_command, true, 0x0a, 0); // master interrupt enable, no vector _ = scc.access(a_command, true, 0x03, 0); _ = scc.access(a_command, true, 0xdd, 0); const bit = port.cyclesPerBit(2_800_000); try testing.expect(!scc.interrupting()); try testing.expect(scc.receiveFrame(.a, &.{ 0xff, 0x02, 0x81 }, true, 0)); scc.advance(16 * bit + 1); try testing.expect(scc.interrupting()); try testing.expectEqual(Scc.a_rx_ip, scc.readRegister(.a, 3)); // Some time later the handler arrives, and both bytes are there. scc.advance(30 * bit); try testing.expectEqual(@as(u8, 0xff), scc.access(a_data, false, 0, scc.now)); try testing.expectEqual(@as(u8, 0x02), scc.access(a_data, false, 0, scc.now)); // Taking the first byte took the interrupt with it, and the mode is // first character only: the rest of the frame does not interrupt until // its end, and the firmware polls for it. try testing.expect(!scc.interrupting()); scc.advance(scc.now + 8 * bit); try testing.expect(!scc.interrupting()); try testing.expect(scc.readRegister(.a, 0) & Scc.rx_available != 0); } test "RR3 exists only in channel A" { var scc: Scc = .{}; scc.b.tx_ip = true; try testing.expectEqual(Scc.b_tx_ip, scc.readRegister(.a, 3)); try testing.expectEqual(@as(u8, 0), scc.readRegister(.b, 3)); } test "the line is quiet when nothing is on it, which RR10 says two bit cells after asking" { // Carrier sense the way Zilog's LocalTalk note does it: reset the // missing-clock latches, wait, and read RR10. An idle FM line has no // clock on it, so both latches are set; a frame arriving is a clock. var scc: Scc = .{}; const port = localtalkPort(&scc, .a); const bit = port.cyclesPerBit(2_800_000); _ = scc.access(a_command, true, 0x0e, 1000); _ = scc.access(a_command, true, 0x41, 1000); // Reset Missing Clock, BRG on _ = scc.access(a_command, true, 0x0a, 1000); try testing.expectEqual(@as(u8, 0), scc.access(a_command, false, 0, 1000)); _ = scc.access(a_command, true, 0x0a, 1000 + 3 * bit); try testing.expectEqual( Scc.one_clock_missing | Scc.two_clocks_missing, scc.access(a_command, false, 0, 1000 + 3 * bit), ); try testing.expect(scc.receiveFrame(.a, &.{ 0xff, 0x02, 0x81 }, true, scc.now)); _ = scc.access(a_command, true, 0x0a, scc.now); try testing.expectEqual(@as(u8, 0), scc.access(a_command, false, 0, scc.now)); } test "carrier detect and clear to send read as the pins, and latch when their interrupt is on" { var scc: Scc = .{}; // Nothing on the far end reads as nothing on the far end, which is what a // IIgs with an empty port sees. try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & (Scc.dcd | Scc.cts)); // "If the DCD IE is reset, this bit merely reports the current, unlatched // state of the /DCD pin" (ZiLOG, 2001, § 5.3.1). No enable, so no latch: // the bit follows the wire. scc.setDcd(.a, true); try testing.expectEqual(Scc.dcd, scc.readRegister(.a, 0) & Scc.dcd); scc.setDcd(.a, false); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.dcd); try testing.expect(!scc.a.ext_ip); // The two lines are their own, and one channel's are not the other's. scc.setCts(.b, true); try testing.expectEqual(Scc.cts, scc.readRegister(.b, 0) & Scc.cts); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.cts); } test "a transition on carrier detect raises an external status interrupt" { var scc: Scc = .{}; // The master enable, the channel's external/status interrupt, and then // DCD's own bit in WR15 -- all three, because the chip wants all three. scc.writeRegister(.a, 9, Scc.master_interrupt_enable); scc.writeRegister(.a, 1, Scc.ext_int_enable); scc.writeRegister(.a, 15, Scc.dcd); try testing.expect(!scc.a.ext_ip); scc.setDcd(.a, true); try testing.expect(scc.a.ext_ip); try testing.expect(scc.interrupting()); try testing.expectEqual(Scc.dcd, scc.readRegister(.a, 0) & Scc.dcd); // "Any transition on the /DCD pin, while no interrupt is pending, latches // the state of the /DCD pin" -- so with one pending, the line moving back // does not change what RR0 says. The latch is holding the value from when // it closed. scc.setDcd(.a, false); try testing.expectEqual(Scc.dcd, scc.readRegister(.a, 0) & Scc.dcd); // Resetting the latches opens them again, and then RR0 is the wire. scc.writeCommand(.a, @as(u8, Scc.reset_external_status) << 3); try testing.expectEqual(@as(u8, 0), scc.readRegister(.a, 0) & Scc.dcd); } test "setting a line to what it already is is not a transition" { var scc: Scc = .{}; scc.writeRegister(.a, 9, Scc.master_interrupt_enable); scc.writeRegister(.a, 1, Scc.ext_int_enable); scc.writeRegister(.a, 15, Scc.cts); scc.setCts(.a, true); try testing.expect(scc.a.ext_ip); scc.writeCommand(.a, @as(u8, Scc.reset_external_status) << 3); scc.a.ext_ip = false; // A level rather than an edge: a wire held where it was has not moved, and // the chip interrupts on transitions. scc.setCts(.a, true); try testing.expect(!scc.a.ext_ip); }