// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The 6522, as much of it as a Mockingboard uses. //! //! There is one of these between the machine and each sound chip. Its two //! ports carry the chip's data bus and the three lines that say what to do //! with it, and its first timer is what the music runs on: a player sets the //! timer going, and every time it runs down it interrupts and the handler //! plays the next frame of the tune. That is the whole reason a sound card //! wanted a general purpose interface chip in front of it. //! //! The shift register is here now, in all eight of its modes, though nothing //! in an Apple is wired to it: a Mockingboard's sound chips are on ports A and //! B and its control lines go nowhere. What that means is that what is //! modelled is what a *program* can see of the chip -- the register's byte, //! the interrupt flag, and how long eight shifts take -- rather than anything //! arriving from outside, and what does arrive from outside is whatever a //! caller has put on CB2 with `setLine`. //! //! The control lines' output modes and the timers' other jobs are modelled //! too, though for the same reason nothing that plays through one of these //! exercises them: CA2 and CB2 answer the peripheral control register's //! handshake, pulse and manual output modes on the `lines`; the second timer //! counts negative pulses on PB6 when the auxiliary control register asks it //! to rather than counting cycles; and the first timer drives port B's pin 7 //! when it is told to, a single pulse in the one-shot mode and a square wave //! in the free run. What a program can ask this chip to do, it does. const std = @import("std"); const testing = std.testing; pub const Register = enum(u4) { /// The port a sound card drives the chip's control lines from. orb = 0x0, /// And the one that carries its data. ora = 0x1, ddrb = 0x2, ddra = 0x3, /// Reading the low half of the first timer is also how its interrupt is /// answered, which is a trap for anything that reads it to look. t1_low = 0x4, t1_high = 0x5, t1_latch_low = 0x6, t1_latch_high = 0x7, t2_low = 0x8, t2_high = 0x9, shift = 0xa, /// Whether the first timer runs once or over and over. acr = 0xb, pcr = 0xc, /// Which interrupts have happened, and which are wanted. ifr = 0xd, ier = 0xe, /// The data port again, without the handshaking this does not do anyway. ora_no_handshake = 0xf, }; /// Which bit of the flag and enable registers is which. Only the two timers /// are raised here; the rest are named so that a program writing to them is /// not silently misunderstood. pub const irq_ca2 = 0x01; pub const irq_ca1 = 0x02; pub const irq_shift = 0x04; pub const irq_cb2 = 0x08; pub const irq_cb1 = 0x10; pub const irq_t2 = 0x20; pub const irq_t1 = 0x40; /// The top bit of the flag register is not a flag: it says whether any flag /// that is wanted is set, and it is worked out rather than stored. pub const irq_any = 0x80; /// Whether the first timer starts again by itself, which is what a tune wants. pub const acr_t1_continuous = 0x40; /// Whether the first timer drives port B's pin 7: a single negative pulse in /// the one-shot mode, a square wave in the free-run mode (Western Design /// Center, 2010, §2.6-2.7, Table 2-8). It overrides that pin's data direction. pub const acr_t1_pb7 = 0x80; /// Whether the second timer counts negative pulses on PB6 rather than PHI2 /// cycles: "a single control bit within ACR5 is used to select between these /// two modes" (Western Design Center, 2010, §2.9, p. 19). pub const acr_t2_pulse_count = 0x20; /// The shift register's mode, which is bits 4, 3 and 2 of the auxiliary /// control register (Western Design Center, 2010, Table 2-10, p. 21). /// /// Three questions in three bits: whether it shifts at all, which way, and /// what clocks it. The eight combinations are named here rather than left as /// a number, because which of them is in force decides four separate things -- /// the direction, the rate, whether the eight-shift counter stops the shifting /// and whether it interrupts -- and a bare `acr >> 2 & 7` in four places is /// how those come apart. pub const ShiftMode = enum(u3) { /// "The SR is disabled from all operation. The microprocessor can read or /// write the SR, but shifting is disabled" (p. 21). The register is still /// a register; it just does not move. disabled = 0b000, in_t2 = 0b001, in_phi2 = 0b010, in_external = 0b011, /// The one mode that never stops and never interrupts: "since SR7 is /// recirculated back into SR0, the eight bits loaded into the SR will be /// clocked onto the CB2 line repetitively. In this mode, the SR Counter is /// disabled and IRQB is never set" (p. 23). out_free = 0b100, out_t2 = 0b101, out_phi2 = 0b110, out_external = 0b111, /// Whether bits are going out on CB2 or coming in from it. pub fn shiftsOut(self: ShiftMode) bool { return @intFromEnum(self) & 0b100 != 0; } /// Whether the chip makes its own shift pulses, or waits for somebody else /// to put them on CB1. An externally clocked mode does nothing as time /// passes; it moves when the line does. pub fn internallyClocked(self: ShiftMode) bool { return self != .disabled and @intFromEnum(self) & 0b011 != 0b011; } /// Whether the eight-shift counter stops the shifting when it runs out. /// /// The four internally clocked modes that are not the free run do: "after /// the eight shift pulses, the shifting is disabled, IFR2 is set" (p. 24), /// and the same for shifting in (p. 22). The free run does not, by /// definition. The two external modes do not either -- "the SR counter /// does not stop the shifting operation. Its function is simply that of a /// pulse counter" (p. 23). pub fn stopsAfterEight(self: ShiftMode) bool { return switch (self) { .in_t2, .in_phi2, .out_t2, .out_phi2 => true, else => false, }; } }; /// The four control lines, which are inputs here: an edge on one raises its /// flag, and the peripheral control register says which edge. Nothing in an /// Apple drives them as outputs. pub const Line = enum { ca1, ca2, cb1, cb2, fn flag(self: Line) u8 { return switch (self) { .ca1 => irq_ca1, .ca2 => irq_ca2, .cb1 => irq_cb1, .cb2 => irq_cb2, }; } }; pub const Via = struct { /// What the machine last wrote to each port, and which of their lines are /// outputs. A line that is not an output reads as whatever is on it, and /// with nothing wired to these but the sound chip that is what was written. port: [2]u8 = @splat(0), direction: [2]u8 = @splat(0), /// What is on the lines of each port from outside. A line that is an /// input reads this rather than what was written; one nothing drives /// floats high. inputs: [2]u8 = @splat(0xff), /// The first timer: what it was loaded with, and what it has counted down /// to. t1_latch: u16 = 0xffff, t1_counter: u16 = 0xffff, /// Whether running down will interrupt. /// /// Not whether the counter is *counting*: it always is. "After a time out, /// the T2 counters roll over to all 1's ($FFFF) and continues to /// decrement. This two's complement decrement allows the user to determine /// how long IFR5 has been set. Since the Interrupt Flag logic is disabled /// after the initial interrupt set (zero count), further interrupts cannot /// be set by a subsequent count to zero" (Western Design Center, 2010, /// p. 19). So it is the interrupt logic that a one shot disarms, and the /// counter carries on regardless — which is what lets a program tell a /// chip from an empty slot by reading a counter twice and looking at the /// difference, and what mb-audit does to find a Mockingboard. t1_armed: bool = false, /// Whether the counter is sitting on the one cycle of $ffff it spends /// between running down and reloading. It has to be said out loud rather /// than read off the counter, because $ffff is also an ordinary count and /// the two behave nothing alike: this one reloads on the next cycle, and /// the other has another sixty-five thousand to go. t1_rolled: bool = false, t2_latch: u16 = 0xffff, t2_counter: u16 = 0xffff, t2_armed: bool = false, /// The last level seen on port B's pin 6, so that its falling edge can be /// caught in the pulse-counting mode. It comes up high, as an input with /// nothing pulling it down does. pb6: bool = true, /// The level the first timer is driving onto port B's pin 7, when the /// auxiliary control register puts it there. It rests high, between pulses. pb7: bool = true, /// The shift register: eight bits that go out on CB2 or come in from it, /// a bit at a time, clocked by PHI2, by the second timer, or by whatever /// is putting pulses on CB1. /// /// Nothing in an Apple is wired to it. A Mockingboard's sound chips are on /// ports A and B and its control lines go nowhere, so what is modelled /// here is what a *program* can see of the chip -- the register's value, /// the interrupt flag, and how long eight shifts take -- rather than /// anything arriving from outside. What does arrive from outside is /// whatever a caller has put on CB2 with `setLine`. shift: u8 = 0, /// How many of the eight shifts are still to come before the counter runs /// out. It is a modulo-8 counter on the chip, so it reloads rather than /// stopping. shift_left: u8 = 8, /// Whether shifting is going on. The four modes that count out eight and /// stop clear this; reading or writing the register sets it again, which /// is what "shifting occurs by writing or reading the SR" means. shifting: bool = false, /// The cycle the shifter was last brought up to date at, in the same way /// and for the same reason as the two timers. shift_at: u64 = 0, acr: u8 = 0, pcr: u8 = 0, /// Which interrupts have happened, and which of them are wanted. ifr: u8 = 0, ier: u8 = 0, /// What is on the four control lines. lines: std.EnumArray(Line, bool) = .initFill(false), /// When a CA2/CB2 pulse output returns to rest, if one is low. In pulse /// mode the line goes low on a port access and back high one cycle later; /// this is that cycle, checked as the chip is brought up to date. ca2_pulse_at: ?u64 = null, cb2_pulse_at: ?u64 = null, /// The cycle each counter was last brought up to date at. They are not /// stepped one at a time: nothing can look at them without an access, and /// an access is where they are worked out. /// /// One apiece rather than one between them, because loading a counter /// moves only that one's mark. Writing the high byte of a counter starts /// it from the cycle *after* the write, so fifteen cycles between the /// store and a load of the low byte show fourteen decrements — which is /// the arithmetic mb-audit's T6522_3 is written around, counting the /// cycles of every instruction between the two. t1_at: u64 = 0, t2_at: u64 = 0, /// What the RES line does. /// /// "Reset clears all internal registers (except T1 and T2 counters and /// latches, and the SR)... Also, T1 and T2, SR and the interrupt logic are /// disabled from operation" (Western Design Center, 2010, p. 36). So the /// counters keep counting from wherever they had got to and the latches /// keep their values; what goes is everything that made the chip *do* /// anything — the ports, their directions, the control registers, and the /// interrupt enables, which is what takes a card that was asking for /// attention back off the line. pub fn reset(self: *Via, cycle: u64) void { const t1_latch = self.t1_latch; const t1_counter = self.t1_counter; const t2_latch = self.t2_latch; const t2_counter = self.t2_counter; // The shift register is named in that same list of what a reset does // not clear, so it keeps its byte -- but the shifting stops, because // the mode lives in the auxiliary control register and that does go. const shift = self.shift; self.* = .{ .t1_at = cycle, .t2_at = cycle, .shift_at = cycle }; self.t1_latch = t1_latch; self.t1_counter = t1_counter; self.t2_latch = t2_latch; self.t2_counter = t2_counter; self.shift = shift; } /// Which of the eight things the shift register is doing. pub fn shiftMode(self: *const Via) ShiftMode { return @enumFromInt(@as(u3, @truncate(self.acr >> 2))); } /// What a CA2 or CB2 line is doing, which the peripheral control register /// says: an interrupt input, or one of the four output modes (Western /// Design Center, 2010, §2.1, Tables 2-6 and 2-7). const Control = enum { input, handshake, pulse, low, high }; /// CA2's mode, from the control register's bits 3 to 1. Bit 3 makes it an /// output; the two below choose the kind. fn ca2Control(self: *const Via) Control { return switch (self.pcr & 0x0e) { 0x08 => .handshake, 0x0a => .pulse, 0x0c => .low, 0x0e => .high, else => .input, }; } /// CB2's mode, from bits 7 to 5 — except that the shift register owns CB2 /// whenever it is enabled, so the control register drives the line only /// with the shifter off. fn cb2Control(self: *const Via) Control { if (self.shiftMode() != .disabled) return .input; return switch (self.pcr & 0xe0) { 0x80 => .handshake, 0xa0 => .pulse, 0xc0 => .low, 0xe0 => .high, else => .input, }; } /// Puts CA2 and CB2 where the control register's output modes want them: /// the manual modes hold a level, and handshake and pulse rest the line /// high until a port access takes it low. Called when the register that /// decides this is written. fn applyControlOutputs(self: *Via) void { switch (self.ca2Control()) { .low => self.lines.set(.ca2, false), .high, .handshake, .pulse => self.lines.set(.ca2, true), .input => {}, } switch (self.cb2Control()) { .low => self.lines.set(.cb2, false), .high, .handshake, .pulse => self.lines.set(.cb2, true), .input => {}, } } /// The effective level on port B's pin 6, output or input. fn pb6Level(self: *const Via) bool { return self.pins(1) & 0x40 != 0; } /// Counts a negative pulse on PB6 for the second timer in its pulse- /// counting mode. "T2 counts a predetermined number of negative going /// pulses on PB6 ... when the T2 counter reaches a count of zero, IFR5 is /// set and the counter continues to decrement" (Western Design Center, /// 2010, §2.10, p. 20). As in the interval mode, the flag is raised on the /// count that carries the counter past zero, and reloading the high /// counter re-arms it. Called wherever PB6 can move. fn countPb6(self: *Via) void { const high = self.pb6Level(); defer self.pb6 = high; if (self.acr & acr_t2_pulse_count == 0) return; if (!self.pb6 or high) return; // only a high-to-low edge counts const before = self.t2_counter; self.t2_counter -%= 1; if (before == 0 and self.t2_armed) { self.ifr |= irq_t2; self.t2_armed = false; } } /// Returns a pulsed CA2/CB2 output to rest once its one cycle is up. fn restorePulses(self: *Via, cycle: u64) void { if (self.ca2_pulse_at) |at| { if (cycle >= at) { self.lines.set(.ca2, true); self.ca2_pulse_at = null; } } if (self.cb2_pulse_at) |at| { if (cycle >= at) { self.lines.set(.cb2, true); self.cb2_pulse_at = null; } } } /// Brings the timers up to the cycle given, raising whatever ran down on /// the way. pub fn catchUp(self: *Via, cycle: u64) void { self.catchUpT1(cycle); self.catchUpT2(cycle); self.catchUpShift(cycle); self.restorePulses(cycle); } /// How many cycles one bit takes, for a mode the chip clocks itself. /// /// Two for PHI2: the figures show the CB1 output toggling every cycle, so /// a whole shift clock period -- which is what one bit costs -- is two of /// them (Western Design Center, 2010, Figure 2-11, p. 24). /// /// And twice N+2 for the ones the second timer paces, N being the *low /// order* T2 latch: "the time between transitions of the CB1 output clock /// is determined by the PHI2 clock period and the contents of the low /// order T2 latch (N)" (p. 22), and Figure 2-10 marks each of those /// half-periods "N+2 CYCLES". Two transitions to the bit. fn shiftPeriod(self: *const Via) u64 { return switch (self.shiftMode()) { .in_phi2, .out_phi2 => 2, .in_t2, .out_t2, .out_free => 2 * (@as(u64, self.t2_latch & 0xff) + 2), else => 0, }; } /// Moves one bit, whichever way this mode moves them. /// /// "When shifting out, bit 7 is the first bit out and simultaneously is /// rotated back into bit 0. When shifting in, bits initially enter bit 0 /// and are shifted towards bit 7" (Western Design Center, 2010, Table /// 2-10, p. 21). So shifting out is a rotate and shifting in is a shift /// with whatever is on CB2 coming in at the bottom. fn shiftOnce(self: *Via) void { const mode = self.shiftMode(); if (mode.shiftsOut()) { const bit = self.shift >> 7; self.shift = self.shift << 1 | bit; // CB2 is an output in these modes, so it is put there directly // rather than through `setLine`: what the shifter drives is not an // edge arriving from outside and raises no flag. self.lines.set(.cb2, bit != 0); } else { self.shift = self.shift << 1 | @intFromBool(self.lines.get(.cb2)); } self.shift_left -= 1; if (self.shift_left != 0) return; self.shift_left = 8; // The free run is the one mode with no counter to speak of: "the SR // Counter is disabled and IRQB is never set". if (mode != .out_free) self.ifr |= irq_shift; if (mode.stopsAfterEight()) self.shifting = false; } /// What reading or writing the register does besides moving a byte. /// /// "Reading or writing the SR resets IFR2 and initializes the counter to /// count another eight pulses" (Western Design Center, 2010, p. 23). In /// the modes that stop after eight it is also what starts them again, and /// in the disabled mode it does none of it: there, the flag "is held low /// (disabled)" and the register is only a register. fn startShifting(self: *Via, cycle: u64) void { if (self.shiftMode() == .disabled) return; self.ifr &= ~@as(u8, irq_shift); self.shift_left = 8; self.shift_at = cycle; self.shifting = true; } /// Brings the shifter up to the cycle given, for the modes that clock /// themselves. The two that take their pulses from CB1 do nothing here: /// they move when the line moves, in `setLine`. fn catchUpShift(self: *Via, cycle: u64) void { if (cycle <= self.shift_at) return; const mode = self.shiftMode(); if (!self.shifting or !mode.internallyClocked()) { self.shift_at = cycle; return; } const period = self.shiftPeriod(); if (period == 0) { self.shift_at = cycle; return; } var due = (cycle - self.shift_at) / period; // Whatever is left over is not lost: the mark moves by whole bits, so // a shift that is part of the way through stays part of the way // through rather than being rounded away on every access. self.shift_at += due * period; while (due > 0) : (due -= 1) { self.shiftOnce(); // A mode that counts out eight and stops has stopped, and the // cycles after that are not shifts. if (!self.shifting) { self.shift_at = cycle; return; } } } fn catchUpT1(self: *Via, cycle: u64) void { // Never backwards. Loading a counter sets its mark to the cycle after // the write, and something else looking at the chip on that same cycle // must not drag the mark back and hand the load's own cycle to it as a // tick. if (cycle <= self.t1_at) return; var passed = cycle - self.t1_at; self.t1_at = cycle; // Coming off the $ffff step, which lasts exactly one cycle. if (self.t1_rolled) { self.t1_rolled = false; self.t1_counter = self.t1_latch; passed -= 1; if (passed == 0) return; } // Still counting down to nought. if (passed <= self.t1_counter) { self.t1_counter -= @intCast(passed); return; } // Past it. A one shot interrupts once and then stops asking; a free // run asks again every time round. if (self.t1_armed) { self.ifr |= irq_t1; if (self.acr & acr_t1_continuous == 0) self.t1_armed = false; } // And with the pin enabled, the time out drives it: the one shot's // single pulse ends by taking PB7 high, and the free run inverts it // each time the counter reaches zero, which makes the square wave. If // this catch-up spans several of those zeroes the inversions cancel in // pairs, so only their parity shows. if (self.acr & acr_t1_pb7 != 0) { if (self.acr & acr_t1_continuous == 0) { self.pb7 = true; } else { const period: u32 = @as(u32, self.t1_latch) + 2; const crossings = 1 + (passed - self.t1_counter - 1) / period; if (crossings & 1 != 0) self.pb7 = !self.pb7; } } // Where in the cycle it has got to. The counter does not go straight // from nought back to the latch: it spends one cycle at $ffff first, // and that is what makes a timer loaded with N repeat every N+2 rather // than every N+1. mb-audit's T6522_A is what pins this down — it loads // $0007 down to $0000 in turn, reads the low byte six cycles later // each time, and wants $01, $00, $FF, $04, $02, $00, $01, $00. The // third of those is the $ffff step showing through. // // Timer 1 reloads from its latch whichever mode it is in; the mode // decides only whether it interrupts again. The datasheet says as much // for the free run — "the counter does not continue to decrement after // reaching a zero count. Instead, the counter automatically transfers // to contents of the latch into the counter" — and its "however" reads // as though a one shot carries on decrementing instead. It does not: // mb-audit's T6522_9 loads $0280 in one-shot mode, waits for the // underflow four times over and requires the high byte to read back as // $02 each time. That test is run against real cards, so it is what is // implemented here. const period: u32 = @as(u32, self.t1_latch) + 2; const after_zero = passed - self.t1_counter; const q: u32 = @intCast((after_zero - 1) % period); if (q == 0) { self.t1_counter = 0xffff; self.t1_rolled = true; } else { self.t1_counter = self.t1_latch - @as(u16, @intCast(q - 1)); } } /// Timer 2 has no free running mode, so it only ever rolls over. fn catchUpT2(self: *Via, cycle: u64) void { // Never backwards. Loading a counter sets its mark to the cycle after // the write, and something else looking at the chip on that same cycle // must not drag the mark back and hand the load's own cycle to it as a // tick. if (cycle <= self.t2_at) return; const passed = cycle - self.t2_at; self.t2_at = cycle; // In the pulse-counting mode the cycles do not move the timer at all: // it counts edges on PB6 instead, in `countPb6`. if (self.acr & acr_t2_pulse_count != 0) return; if (passed > self.t2_counter and self.t2_armed) { self.ifr |= irq_t2; self.t2_armed = false; } self.t2_counter = @truncate(self.t2_counter -% @as(u16, @truncate(passed))); } /// Whether the chip is asking for attention, which is any flag that is /// also wanted. pub fn interrupting(self: *const Via) bool { return self.ifr & self.ier & 0x7f != 0; } /// How many cycles until the first timer next runs down, or nothing if it /// is not going to. A caller pacing itself can use this to know when the /// machine will next be interrupted. pub fn until(self: *const Via) ?u64 { if (!self.t1_armed) return null; return @as(u64, self.t1_counter) + 1; } /// Puts a level on a control line. The flag is raised on the edge the /// control register asks for: for CA1 and CB1 its bit 0 or 4 set means /// the rising edge; for CA2 and CB2 bits 3-1 or 7-5 are a mode, of which /// the four with the top bit clear are inputs, the middle bit picking the /// rising edge and the low bit making it "independent", so that reading /// the port does not clear it (Western Design Center, 2010, Table 2-5). pub fn setLine(self: *Via, line: Line, high: bool) void { if (self.lines.get(line) == high) return; self.lines.set(line, high); const rising = switch (line) { .ca1 => self.pcr & 0x01 != 0, .cb1 => self.pcr & 0x10 != 0, .ca2 => if (self.pcr & 0x08 != 0) return else self.pcr & 0x04 != 0, .cb2 => if (self.pcr & 0x80 != 0) return else self.pcr & 0x40 != 0, }; if (high == rising) self.ifr |= line.flag(); // A handshake output rests high again on the active edge of its port's // C1 line: "CA2 is set high ... by an active transition of the CA1 // signal" (Western Design Center, 2010, §2.1). The port access that // took it low is in `touched`. if (high == rising) { if (line == .ca1 and self.ca2Control() == .handshake) self.lines.set(.ca2, true); if (line == .cb1 and self.cb2Control() == .handshake) self.lines.set(.cb2, true); } // And CB1's rising edge is the shift pulse in the two modes that take // their clock from outside: "data is shifted during the first PHI2 // clock cycle following the positive going edge of the CB1 shift // pulse" (Western Design Center, 2010, p. 23). This happens whichever // edge the peripheral control register asked to be interrupted on, // since the shifter is not looking at that register -- and only on a // real edge, since a level that has not changed returns above. if (line == .cb1 and high and self.shifting) { const mode = self.shiftMode(); if (mode == .in_external or mode == .out_external) self.shiftOnce(); } } /// Touching a port answers the flags of the lines beside it: A clears /// CA1 and CA2, B clears CB1 and CB2, and a line in an independent mode /// is left alone (Western Design Center, 2010, Table 2-5, note). Port A without handshake, at /// register $F, clears nothing, which is what a program that only wants /// the data reads. fn touched(self: *Via, register: Register, cycle: u64) void { switch (register) { .ora => { self.ifr &= ~@as(u8, irq_ca1); if (self.pcr & 0x0a != 0x02) self.ifr &= ~@as(u8, irq_ca2); switch (self.ca2Control()) { // Handshake holds CA2 low until CA1's edge; pulse lets it // back up on the next cycle. .handshake => self.lines.set(.ca2, false), .pulse => { self.lines.set(.ca2, false); self.ca2_pulse_at = cycle + 1; }, else => {}, } }, .orb => { self.ifr &= ~@as(u8, irq_cb1); if (self.pcr & 0xa0 != 0x20) self.ifr &= ~@as(u8, irq_cb2); switch (self.cb2Control()) { .handshake => self.lines.set(.cb2, false), .pulse => { self.lines.set(.cb2, false); self.cb2_pulse_at = cycle + 1; }, else => {}, } }, else => {}, } } /// What a port's lines are at: the register on the outputs, the outside /// world on the inputs — "MPU reads output register bit" for a line /// whose direction bit is set, "MPU reads input level on PB pin" for one /// whose bit is clear (Western Design Center, 2010, Tables 2-2 and 2-3). /// Without the side effects of a read. pub fn pins(self: *const Via, port: u1) u8 { const level = (self.port[port] & self.direction[port]) | (self.inputs[port] & ~self.direction[port]); // The first timer takes port B's pin 7 when it is set to, whatever the // data direction register would otherwise make of it. if (port == 1 and self.acr & acr_t1_pb7 != 0) { return if (self.pb7) level | 0x80 else level & 0x7f; } return level; } /// Puts levels on some of a port's lines from outside. pub fn setInputs(self: *Via, port: u1, mask: u8, value: u8) void { self.inputs[port] = (self.inputs[port] & ~mask) | (value & mask); self.countPb6(); } pub fn read(self: *Via, register: Register, cycle: u64) u8 { self.catchUp(cycle); self.touched(register, cycle); return switch (register) { .orb => self.pins(1), .ora, .ora_no_handshake => self.pins(0), .ddrb => self.direction[1], .ddra => self.direction[0], .t1_low => low: { // Reading it answers the interrupt, which is how a handler // that has done its work says so. self.ifr &= ~@as(u8, irq_t1); break :low @truncate(self.t1_counter); }, .t1_high => @intCast(self.t1_counter >> 8), .t1_latch_low => @truncate(self.t1_latch), .t1_latch_high => @intCast(self.t1_latch >> 8), .t2_low => low: { self.ifr &= ~@as(u8, irq_t2); break :low @truncate(self.t2_counter); }, .t2_high => @intCast(self.t2_counter >> 8), .shift => shifted: { // "Shifting occurs by writing or reading the SR" -- a read is // not a look, it is what starts the next eight going. self.startShifting(cycle); break :shifted self.shift; }, .acr => self.acr, .pcr => self.pcr, .ifr => if (self.interrupting()) self.ifr | irq_any else self.ifr & 0x7f, .ier => self.ier | 0x80, }; } pub fn write(self: *Via, register: Register, value: u8, cycle: u64) void { self.catchUp(cycle); self.touched(register, cycle); switch (register) { .orb => { self.port[1] = value; self.countPb6(); }, .ora, .ora_no_handshake => self.port[0] = value, .ddrb => { self.direction[1] = value; self.countPb6(); }, .ddra => self.direction[0] = value, .t1_low, .t1_latch_low => self.t1_latch = self.t1_latch & 0xff00 | value, .t1_high => { self.t1_latch = self.t1_latch & 0x00ff | @as(u16, value) << 8; // Writing the high half is what starts it: the latch goes into // the counter and whatever it did before is forgotten. self.t1_counter = self.t1_latch; self.t1_armed = true; self.t1_rolled = false; // "The timer begins counting" from the cycle after the one // that loaded it, so the load itself is not a tick. self.t1_at = cycle + 1; self.ifr &= ~@as(u8, irq_t1); // With the pin enabled, the load drives PB7 low; the time out // is what brings it back (Western Design Center, 2010, §2.6). if (self.acr & acr_t1_pb7 != 0) self.pb7 = false; }, .t1_latch_high => { self.t1_latch = self.t1_latch & 0x00ff | @as(u16, value) << 8; self.ifr &= ~@as(u8, irq_t1); }, .t2_low => self.t2_latch = self.t2_latch & 0xff00 | value, .t2_high => { self.t2_latch = self.t2_latch & 0x00ff | @as(u16, value) << 8; self.t2_counter = self.t2_latch; self.t2_armed = true; self.t2_at = cycle + 1; self.ifr &= ~@as(u8, irq_t2); }, .shift => { self.shift = value; self.startShifting(cycle); }, .acr => { // The mode lives here, so changing it is what turns the // shifter on and off. Coming out of disabled leaves it stopped // until the register is touched, which is what starts a // transfer; going into disabled stops it and holds the flag // low. const was = self.shiftMode(); self.acr = value; const now = self.shiftMode(); if (now == .disabled) { self.shifting = false; self.ifr &= ~@as(u8, irq_shift); } else if (was != now) { self.shift_left = 8; self.shift_at = cycle; // The free run is the one that needs no invitation: it // clocks the same eight bits round for ever. self.shifting = now == .out_free; } }, .pcr => { self.pcr = value; self.applyControlOutputs(); }, // Writing to the flags clears the ones written, rather than // setting them, which is how a handler says it has dealt with one. .ifr => self.ifr &= ~(value & 0x7f), // And the top bit of what is written to the enables says whether // the rest are being turned on or off. .ier => if (value & 0x80 != 0) { self.ier |= value & 0x7f; } else { self.ier &= ~(value & 0x7f); }, } } }; test "the first timer runs down and asks for attention" { var chip: Via = .{}; // A thousand cycles, once, with its interrupt wanted. chip.write(.ier, 0x80 | irq_t1, 0); chip.write(.t1_low, 1000 & 0xff, 0); chip.write(.t1_high, 1000 >> 8, 0); try testing.expect(!chip.interrupting()); // Not yet. Five hundred and one rather than five hundred: the write // loaded the counter and it starts counting on the cycle after, so by // cycle 500 it has been decremented 499 times. chip.catchUp(500); try testing.expect(!chip.interrupting()); try testing.expectEqual(@as(u16, 501), chip.t1_counter); // Not quite yet either. A timer loaded with N runs for N+2 cycles, which // is the period mb-audit checks and what the one cycle above adds up to. chip.catchUp(1001); try testing.expect(!chip.interrupting()); // And now. chip.catchUp(1002); try testing.expect(chip.interrupting()); try testing.expect(chip.read(.ifr, 1002) & irq_any != 0); // Reading the low half of the counter is what answers it, which is the // trap in this chip: a handler that reads it to see where it has got to // has also told it the interrupt is dealt with. _ = chip.read(.t1_low, 1002); try testing.expect(!chip.interrupting()); // Once is once: a one shot does not come back. chip.catchUp(10_000); try testing.expect(!chip.interrupting()); } test "a timer told to keep going keeps going" { var chip: Via = .{}; chip.write(.acr, acr_t1_continuous, 0); chip.write(.ier, 0x80 | irq_t1, 0); chip.write(.t1_low, 100, 0); chip.write(.t1_high, 0, 0); // Running down raises it again each time round, and each time a handler // answers it, it comes back. var answered: usize = 0; var at: u64 = 0; while (at < 1000) : (at += 101) { chip.catchUp(at + 101); if (chip.interrupting()) { answered += 1; _ = chip.read(.t1_low, at + 101); } } try testing.expect(answered >= 8); // Leaping a long way forward is the same as walking there: what matters // is that it is still running and still asking, not how many were missed. var leaping: Via = .{}; leaping.write(.acr, acr_t1_continuous, 0); leaping.write(.ier, 0x80 | irq_t1, 0); leaping.write(.t1_low, 100, 0); leaping.write(.t1_high, 0, 0); leaping.catchUp(1_000_000); try testing.expect(leaping.interrupting()); try testing.expect(leaping.t1_counter <= 100); } test "the flags are answered by writing them, and wanted by enabling them" { var chip: Via = .{}; chip.write(.t1_low, 10, 0); chip.write(.t1_high, 0, 0); chip.catchUp(100); // It happened, but nobody asked to be told. try testing.expect(chip.ifr & irq_t1 != 0); try testing.expect(!chip.interrupting()); // Asking makes it ask. chip.write(.ier, 0x80 | irq_t1, 100); try testing.expect(chip.interrupting()); // Writing a one to a flag is what clears it, which is the other trap. chip.write(.ifr, irq_t1, 100); try testing.expect(!chip.interrupting()); try testing.expect(chip.ifr & irq_t1 == 0); // And the enables are turned off by writing them without the top bit. chip.write(.ier, 0x80 | irq_t2, 100); try testing.expect(chip.ier & irq_t2 != 0); chip.write(.ier, irq_t2, 100); try testing.expect(chip.ier & irq_t2 == 0); // Reading them back always has the top bit set, whatever was written. try testing.expect(chip.read(.ier, 100) & 0x80 != 0); } test "the ports keep what was written to them" { var chip: Via = .{}; chip.write(.ddra, 0xff, 0); chip.write(.ddrb, 0x07, 0); chip.write(.ora, 0x42, 0); chip.write(.orb, 0x07, 0); try testing.expectEqual(@as(u8, 0x42), chip.read(.ora, 0)); // Port B's top five lines are inputs with nothing on them, and read high. try testing.expectEqual(@as(u8, 0xff), chip.read(.orb, 0)); try testing.expectEqual(@as(u8, 0xff), chip.read(.ddra, 0)); // The same port again, at the address that does no handshaking. try testing.expectEqual(@as(u8, 0x42), chip.read(.ora_no_handshake, 0)); } test "an edge on a control line raises its flag, and only the edge the control register asks for" { var chip: Via = .{}; // Falling edges by default. chip.setLine(.cb2, true); try testing.expect(chip.ifr & irq_cb2 == 0); chip.setLine(.cb2, false); try testing.expect(chip.ifr & irq_cb2 != 0); // Rising edges when asked, on the same line. chip.write(.ifr, irq_cb2, 0); chip.write(.pcr, 0x40, 0); chip.setLine(.cb2, true); try testing.expect(chip.ifr & irq_cb2 != 0); chip.write(.ifr, irq_cb2, 0); chip.setLine(.cb2, false); try testing.expect(chip.ifr & irq_cb2 == 0); // The same level again is not an edge. chip.write(.pcr, 0x00, 0); chip.setLine(.cb2, false); try testing.expect(chip.ifr & irq_cb2 == 0); // A line in an output mode raises nothing. chip.write(.pcr, 0x80, 0); chip.setLine(.cb2, true); chip.setLine(.cb2, false); try testing.expect(chip.ifr & irq_cb2 == 0); // The flag asks for attention only when it is wanted. chip.write(.pcr, 0x00, 0); chip.setLine(.cb1, true); chip.setLine(.cb1, false); try testing.expect(!chip.interrupting()); chip.write(.ier, 0x80 | irq_cb1, 0); try testing.expect(chip.interrupting()); } test "reading a port answers the flags of the lines beside it, unless they are independent" { var chip: Via = .{}; chip.setLine(.ca1, true); chip.setLine(.ca1, false); chip.setLine(.ca2, true); chip.setLine(.ca2, false); try testing.expect(chip.ifr & (irq_ca1 | irq_ca2) == irq_ca1 | irq_ca2); // Port A without handshake leaves them, port A proper takes them. _ = chip.read(.ora_no_handshake, 0); try testing.expect(chip.ifr & (irq_ca1 | irq_ca2) == irq_ca1 | irq_ca2); _ = chip.read(.ora, 0); try testing.expect(chip.ifr & (irq_ca1 | irq_ca2) == 0); // Independent CA2: the port read takes CA1 and leaves CA2. chip.write(.pcr, 0x02, 0); chip.setLine(.ca1, true); chip.setLine(.ca1, false); chip.setLine(.ca2, true); chip.setLine(.ca2, false); _ = chip.read(.ora, 0); try testing.expect(chip.ifr & (irq_ca1 | irq_ca2) == irq_ca2); // And port B for the other pair. chip.setLine(.cb1, true); chip.setLine(.cb1, false); try testing.expect(chip.ifr & irq_cb1 != 0); chip.write(.orb, 0, 0); try testing.expect(chip.ifr & irq_cb1 == 0); } test "a port reads what was written on its outputs and what is outside on its inputs" { var chip: Via = .{}; chip.write(.ora, 0x0f, 0); // Nothing is an output yet, and nothing is driving the lines. try testing.expectEqual(@as(u8, 0xff), chip.read(.ora, 0)); chip.write(.ddra, 0x0f, 0); try testing.expectEqual(@as(u8, 0xff), chip.read(.ora, 0)); chip.write(.ora, 0x05, 0); try testing.expectEqual(@as(u8, 0xf5), chip.read(.ora, 0)); // Something outside pulls the top line low. chip.setInputs(0, 0x80, 0x00); try testing.expectEqual(@as(u8, 0x75), chip.read(.ora, 0)); // And has no say over an output. chip.setInputs(0, 0x01, 0x00); try testing.expectEqual(@as(u8, 0x75), chip.read(.ora, 0)); } test "a disabled shift register is a register and nothing more" { // "In the 000 mode, the SR is disabled from all operation. The // microprocessor can read or write the SR, but shifting is disabled... // The Shift Register Interrupt Flag (IFR2) is held low (disabled)" // (Western Design Center, 2010, p. 21). var chip: Via = .{}; try testing.expectEqual(ShiftMode.disabled, chip.shiftMode()); chip.write(.shift, 0xa5, 0); try testing.expectEqual(@as(u8, 0xa5), chip.read(.shift, 0)); // A thousand cycles later it is still that byte, and nothing has asked // for attention. try testing.expectEqual(@as(u8, 0xa5), chip.read(.shift, 1000)); try testing.expectEqual(@as(u8, 0), chip.ifr & irq_shift); } test "shifting out under the PHI2 clock takes two cycles a bit and eight bits a byte" { var chip: Via = .{}; chip.write(.acr, 0b110 << 2, 0); // shift out, PHI2 chip.write(.shift, 0b1000_0001, 0); // Bit 7 goes first and comes back round into bit 0, so the register is a // rotate rather than a shift: "when shifting out, bit 7 is the first bit // out and simultaneously is rotated back into bit 0" (Table 2-10, p. 21). // One bit every two cycles, which is what Figure 2-11 shows. chip.catchUp(2); try testing.expectEqual(@as(u8, 0b0000_0011), chip.shift); try testing.expect(chip.lines.get(.cb2)); // the one that went out chip.catchUp(4); try testing.expectEqual(@as(u8, 0b0000_0110), chip.shift); try testing.expect(!chip.lines.get(.cb2)); // Eight bits is sixteen cycles, and eight rotations of eight bits leave // the byte where it started. try testing.expectEqual(@as(u8, 0), chip.ifr & irq_shift); chip.catchUp(16); try testing.expectEqual(irq_shift, chip.ifr & irq_shift); try testing.expectEqual(@as(u8, 0b1000_0001), chip.shift); // "After the eight shift pulses, the shifting is disabled" -- so it stays // where it is however long is left to run. try testing.expect(!chip.shifting); chip.catchUp(1000); try testing.expectEqual(@as(u8, 0b1000_0001), chip.shift); // And touching the register clears the flag and starts another eight, // counted from the access rather than from wherever the last one ended: // "shifting occurs by writing or reading the SR". _ = chip.read(.shift, 1001); try testing.expectEqual(@as(u8, 0), chip.ifr & irq_shift); chip.catchUp(1002); try testing.expectEqual(@as(u8, 0b1000_0001), chip.shift); // not yet chip.catchUp(1003); try testing.expectEqual(@as(u8, 0b0000_0011), chip.shift); // two cycles on } test "the second timer's low latch sets the shift rate" { // "The time between transitions of the CB1 output clock is determined by // the PHI2 clock period and the contents of the low order T2 latch (N)" // (p. 22), and Figure 2-10 marks each half-period N+2 cycles. So a bit // costs twice that. var chip: Via = .{}; chip.write(.t2_low, 3, 0); // N = 3, so 2 * (3 + 2) = 10 cycles a bit chip.write(.acr, 0b101 << 2, 0); // shift out, T2 chip.write(.shift, 0b1000_0000, 0); chip.catchUp(9); try testing.expectEqual(@as(u8, 0b1000_0000), chip.shift); chip.catchUp(10); try testing.expectEqual(@as(u8, 0b0000_0001), chip.shift); // Eight of them, and then it asks for attention and stops. chip.catchUp(80); try testing.expectEqual(irq_shift, chip.ifr & irq_shift); try testing.expect(!chip.shifting); } test "the free running mode never stops and never interrupts" { // "Since SR7 is recirculated back into SR0, the eight bits loaded into the // SR will be clocked onto the CB2 line repetitively. In this mode, the SR // Counter is disabled and IRQB is never set" (p. 23). var chip: Via = .{}; chip.write(.t2_low, 0, 0); // 2 * (0 + 2) = 4 cycles a bit chip.write(.acr, 0b100 << 2, 0); chip.write(.shift, 0b1100_0000, 0); // It needs no invitation: unlike every other mode, it is running as soon // as the mode is chosen. chip.catchUp(4); try testing.expectEqual(@as(u8, 0b1000_0001), chip.shift); // Round and round, for as long as anybody watches, and never a flag. chip.catchUp(4 * 8 * 100); try testing.expect(chip.shifting); try testing.expectEqual(@as(u8, 0), chip.ifr & irq_shift); } test "shifting in takes what is on CB2, low bit first" { // "When shifting in, bits initially enter bit 0 and are shifted towards // bit 7" (Table 2-10, p. 21). Nothing in an Apple drives CB2, so what // comes in is whatever a caller has put there. var chip: Via = .{}; chip.write(.acr, 0b010 << 2, 0); // shift in, PHI2 chip.write(.shift, 0x00, 0); chip.setLine(.cb2, true); chip.catchUp(2); try testing.expectEqual(@as(u8, 0b0000_0001), chip.shift); chip.setLine(.cb2, false); chip.catchUp(4); try testing.expectEqual(@as(u8, 0b0000_0010), chip.shift); chip.setLine(.cb2, true); chip.catchUp(6); try testing.expectEqual(@as(u8, 0b0000_0101), chip.shift); // Eight of them and it says so. chip.catchUp(16); try testing.expectEqual(irq_shift, chip.ifr & irq_shift); } test "an externally clocked shift moves on CB1 and never stops on its own" { // "In this mode, CB1 serves as an input to the SR. In this way, an // external device can load the SR at its own pace... The SR counter does // not stop the shifting operation. Its function is simply that of a pulse // counter" (p. 23). var chip: Via = .{}; chip.write(.acr, 0b111 << 2, 0); // shift out, external clock chip.write(.shift, 0b1000_0000, 0); // Time alone does nothing at all: this one waits for the line. chip.catchUp(10_000); try testing.expectEqual(@as(u8, 0b1000_0000), chip.shift); // The rising edge is the pulse, and the falling one is not. chip.setLine(.cb1, true); try testing.expectEqual(@as(u8, 0b0000_0001), chip.shift); chip.setLine(.cb1, false); try testing.expectEqual(@as(u8, 0b0000_0001), chip.shift); // Eight pulses raise the flag, and the ninth still shifts, because the // counter here counts rather than gates. for (0..7) |_| { chip.setLine(.cb1, true); chip.setLine(.cb1, false); } try testing.expectEqual(irq_shift, chip.ifr & irq_shift); try testing.expect(chip.shifting); const before = chip.shift; chip.setLine(.cb1, true); try testing.expect(chip.shift != before); } test "a reset keeps the byte in the shift register and stops it moving" { // "Reset clears all internal registers (except T1 and T2 counters and // latches, and the SR)... Also, T1 and T2, SR and the interrupt logic are // disabled from operation" (p. 36). So the byte survives and the shifting // does not, because the mode is in the auxiliary control register and // that is cleared. var chip: Via = .{}; chip.write(.acr, 0b110 << 2, 0); chip.write(.shift, 0x3c, 0); chip.catchUp(4); const kept = chip.shift; chip.reset(100); try testing.expectEqual(kept, chip.shift); try testing.expectEqual(ShiftMode.disabled, chip.shiftMode()); try testing.expect(!chip.shifting); chip.catchUp(10_000); try testing.expectEqual(kept, chip.shift); } test "the second timer counts pulses on PB6 rather than cycles when told to" { const S = struct { // One negative pulse on PB6: high, then low. fn pulse(c: *Via) void { c.write(.orb, 0x40, 0); c.write(.orb, 0x00, 0); } }; var chip: Via = .{}; chip.write(.ddrb, 0x40, 0); // PB6 an output chip.write(.acr, acr_t2_pulse_count, 0); chip.write(.t2_low, 3, 0); chip.write(.t2_high, 0, 0); try testing.expectEqual(@as(u16, 3), chip.t2_counter); // Cycles do not move it in this mode. chip.catchUp(1000); try testing.expectEqual(@as(u16, 3), chip.t2_counter); try testing.expect(chip.ifr & irq_t2 == 0); // Each falling edge on PB6 is a count. S.pulse(&chip); try testing.expectEqual(@as(u16, 2), chip.t2_counter); S.pulse(&chip); S.pulse(&chip); // Reaching zero has not raised the flag yet. try testing.expectEqual(@as(u16, 0), chip.t2_counter); try testing.expect(chip.ifr & irq_t2 == 0); // The pulse that carries it past zero does. S.pulse(&chip); try testing.expectEqual(@as(u16, 0xffff), chip.t2_counter); try testing.expect(chip.ifr & irq_t2 != 0); // A further pulse does not raise it again while the counter runs on past // zero; only reloading the high counter re-arms the flag. chip.write(.ifr, irq_t2, 0); S.pulse(&chip); try testing.expect(chip.ifr & irq_t2 == 0); chip.write(.t2_high, 0, 0); // reload the three, and re-arm S.pulse(&chip); S.pulse(&chip); S.pulse(&chip); try testing.expect(chip.ifr & irq_t2 == 0); S.pulse(&chip); try testing.expect(chip.ifr & irq_t2 != 0); } test "the control register drives CA2 in its output modes" { var chip: Via = .{}; // Manual low and high put the line straight where the register says. chip.write(.pcr, 0x0c, 0); // CA2 manual low try testing.expect(!chip.lines.get(.ca2)); chip.write(.pcr, 0x0e, 0); // CA2 manual high try testing.expect(chip.lines.get(.ca2)); // Handshake: high at rest, low on a port access, high again on CA1's edge. chip.write(.pcr, 0x08, 0); // CA2 handshake, CA1 active on the falling edge try testing.expect(chip.lines.get(.ca2)); _ = chip.read(.ora, 0); try testing.expect(!chip.lines.get(.ca2)); chip.setLine(.ca1, true); chip.setLine(.ca1, false); // the active edge try testing.expect(chip.lines.get(.ca2)); // A write of the port takes it low as a read does, and a non-active CA1 // edge does not bring it back. chip.write(.ora, 0, 1); try testing.expect(!chip.lines.get(.ca2)); chip.setLine(.ca1, true); try testing.expect(!chip.lines.get(.ca2)); // Pulse: low for one cycle after a port access, then high. chip.write(.pcr, 0x0a, 2); // CA2 pulse _ = chip.read(.ora, 3); try testing.expect(!chip.lines.get(.ca2)); _ = chip.read(.ora_no_handshake, 4); // a cycle on, and not itself a pulse try testing.expect(chip.lines.get(.ca2)); } test "CB2's output mode yields to the shift register" { var chip: Via = .{}; // With the shifter off, the control register drives CB2. chip.write(.pcr, 0xc0, 0); // CB2 manual low try testing.expect(!chip.lines.get(.cb2)); try testing.expectEqual(Via.Control.low, chip.cb2Control()); // Enable a shift mode and CB2 is the shifter's: the control register does // not drive it. chip.write(.acr, 0x1c, 0); // out_free try testing.expectEqual(Via.Control.input, chip.cb2Control()); // CA2 is the control register's whatever the shifter does. chip.write(.pcr, 0x0c, 0); // CA2 manual low try testing.expect(!chip.lines.get(.ca2)); try testing.expectEqual(Via.Control.low, chip.ca2Control()); } test "the first timer drives PB7 when the control register puts it there" { // One-shot: the load takes PB7 low, and the single time out brings it back // high — a negative pulse, whatever the direction register says. var chip: Via = .{}; chip.write(.acr, acr_t1_pb7, 0); chip.write(.t1_low, 4, 0); chip.write(.t1_high, 0, 0); try testing.expect(chip.pins(1) & 0x80 == 0); chip.catchUp(3); // still counting down try testing.expect(chip.pins(1) & 0x80 == 0); chip.catchUp(6); // past the time out try testing.expect(chip.pins(1) & 0x80 != 0); chip.catchUp(1000); // and a one shot does not pulse again try testing.expect(chip.pins(1) & 0x80 != 0); // Free run: PB7 inverts each time the counter reaches zero, a square wave. var wave: Via = .{}; wave.write(.acr, acr_t1_pb7 | acr_t1_continuous, 0); wave.write(.t1_low, 4, 0); // a six-cycle period, N+2 wave.write(.t1_high, 0, 0); try testing.expect(wave.pins(1) & 0x80 == 0); wave.catchUp(6); // first zero try testing.expect(wave.pins(1) & 0x80 != 0); wave.catchUp(12); // second try testing.expect(wave.pins(1) & 0x80 == 0); wave.catchUp(18); // third try testing.expect(wave.pins(1) & 0x80 != 0); // A single catch-up spanning several zeroes shows only their parity: from // rest, four of them leaves it low again. var span: Via = .{}; span.write(.acr, acr_t1_pb7 | acr_t1_continuous, 0); span.write(.t1_low, 4, 0); span.write(.t1_high, 0, 0); span.catchUp(24); // four zeroes at 6, 12, 18, 24 try testing.expect(span.pins(1) & 0x80 == 0); }