// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The Motorola MC6840 Programmable Timer Module, the timer chip on a Passport //! MIDI card. //! //! Three sixteen-bit down-counters share one eight-register window. Each has //! its own control register — CR1, CR2, CR3 — and its own interrupt flag, and //! the whole of using one is loading a latch with a count, letting it run, and //! taking the interrupt it raises when the count reaches zero. On a Passport //! that is how a sequencer measures out the time between MIDI events: a timer //! loaded for the delay, its interrupt enabled, and the handler sending the //! next byte when the timer times out. //! //! The three control registers do not each get an address. CR2 is written at //! RS=1 and reached on its own; CR1 and CR3 share RS=0, and which one a write //! lands in is CR2's low bit — set for CR1, clear for CR3 (Bethke & Borowicz, //! 1985, §4.4, Table #1). Three low bits are special to their register: CR1's //! is an internal reset that holds every counter; CR2's is that address //! selector; CR3's prescales Timer #3 by eight. The rest of each control //! register configures its own timer — clock source, sixteen-bit or dual //! eight-bit, the operating mode, and the interrupt enable (Table #3). //! //! The chip's clock is the ENABLE pin, which on the Apple bus is φ2, so one //! timer tick is one machine cycle and a latch of N times out every N+1 ticks. //! The manual does not give the Passport's external-clock frequency, and the //! card's own timing software is written against whatever the bus runs at, so //! this models both the internal and the external clock source at φ2 rather //! than inventing a crystal the manual never names. //! //! Only the continuous and single-shot modes are modeled to time out on their //! own; the frequency- and pulse-width-comparison modes gate on an external //! input the card does not wire, so they raise no interrupt here (Table #4). //! //! The register map is the MC6840 data sheet's as the Passport manual reprints //! it (Bethke & Borowicz, 1985, §4.4); the addresses are §4.1's. const std = @import("std"); /// The eight the chip answers at, selected by the three address lines RS2–RS0. /// A read and a write of the same select reach different registers, the way /// the whole family does. pub const Register = enum(u3) { /// Write CR1 (when CR2 bit 0 = 1) or CR3 (when it is 0); a read does /// nothing. control_1_or_3 = 0b000, /// Write CR2; read the status register. control_2_status = 0b001, /// Write the shared MSB buffer; read Timer #1's counter. timer1_counter = 0b010, /// Write Timer #1's latches (MSB from the buffer, LSB here); read the LSB /// buffer left by a counter read. timer1_latch = 0b011, timer2_counter = 0b100, timer2_latch = 0b101, timer3_counter = 0b110, timer3_latch = 0b111, }; /// The bits of a control register that mean the same thing in all three /// (Bethke & Borowicz, 1985, §4.4, Table #3). const clock_internal: u8 = 0b0000_0010; // bit 1: 1 = internal clock, 0 = external const dual_8_bit: u8 = 0b0000_0100; // bit 2: 1 = two 8-bit counters, 0 = one 16-bit const comparison_mode: u8 = 0b0000_1000; // bit 3: 1 = frequency/pulse-width comparison const single_shot: u8 = 0b0010_0000; // bit 5, when bit 3 = 0: 1 = single-shot, 0 = continuous const irq_enabled: u8 = 0b0100_0000; // bit 6: 1 = this timer's interrupt reaches the line /// One of the three timers. What is stored is the latch and enough about when /// it started to work the counter and the flag out as pure functions of the /// current cycle, the same lazy trick `mc6850.zig` plays with its byte time. const Timer = struct { /// The timer's control register. control: u8 = 0, /// The count loaded from the latches, which the counter reloads from. latch: u16 = 0, /// The cycle the counter was last initialized — loaded from the latch and /// set running. epoch: u64 = 0, /// The cycle through which the interrupt flag has been cleared. A timeout /// later than this is what sets the flag; clearing it moves this forward. cleared_at: u64 = 0, /// Whether the counter is running. False while the chip is held in its /// internal reset. counting: bool = false, /// Whether the status register has been read since this flag was last set, /// which is what arms a counter read to clear it. clear_armed: bool = false, /// The low byte of the counter from the last counter read, handed back by /// the next read of the latch address. lsb_buffer: u8 = 0, /// Whether Timer #3's divide-by-eight prescaler is in. Only Timer #3 has /// one; it stays false on the other two. prescale: bool = false, fn singleShot(self: Timer) bool { return self.control & single_shot != 0; } /// The number of clock ticks between one timeout and the next, or zero when /// the timer is configured for a mode that does not time out on its own. /// Sixteen-bit is N+1; dual eight-bit is (low+1)(high+1); Timer #3's /// prescaler multiplies by eight. fn periodTicks(self: Timer) u64 { if (self.control & comparison_mode != 0) return 0; var ticks: u64 = if (self.control & dual_8_bit != 0) blk: { const low: u64 = self.latch & 0xff; const high: u64 = self.latch >> 8; break :blk (low + 1) * (high + 1); } else @as(u64, self.latch) + 1; if (self.prescale) ticks *= 8; return ticks; } /// Whether the interrupt flag is set at `cycle`. A running timer sets it /// at the first timeout after `cleared_at`; a single-shot leaves it set /// after its one timeout, a continuous one sets it again every period. fn flagSet(self: Timer, cycle: u64) bool { if (!self.counting) return false; const period = self.periodTicks(); if (period == 0) return false; if (cycle < self.epoch + period) return false; if (self.singleShot()) return self.epoch + period > self.cleared_at; // The latest timeout at or before now, which for a continuous timer is // the one whose flag would still be standing. const last = self.epoch + (cycle - self.epoch) / period * period; return last > self.cleared_at; } /// The value the counter shows now, counting down from the latch. Exact for /// the sixteen-bit modes the Passport uses; for dual eight-bit it is the /// reload value, since that mode's two counters are not read back here. fn counter(self: Timer, cycle: u64) u16 { if (!self.counting or self.control & dual_8_bit != 0) return self.latch; const period = self.periodTicks(); if (period == 0) return self.latch; const into: u64 = (cycle - self.epoch) % period; return @intCast(self.latch - @min(self.latch, into)); } }; pub const Ptm = struct { timers: [3]Timer = .{ .{}, .{}, .{} }, /// The shared MSB buffer: one register behind three addresses, holding the /// high byte until the low byte completes a latch write (§4.4, "Counter /// Latch Initialization" — the processor must write the MSB first). msb_buffer: u8 = 0, /// Whether CR1's internal-reset bit is currently holding the counters. held: bool = false, /// CR2's low bit routes an RS=0 write: set sends it to CR1, clear to CR3. fn writeToCR1(self: Ptm) bool { return self.timers[1].control & 0x01 != 0; } pub fn read(self: *Ptm, register: Register, cycle: u64) u8 { return switch (register) { .control_1_or_3 => 0, // reading here does nothing .control_2_status => self.status(cycle), .timer1_counter => self.readCounter(0, cycle), .timer2_counter => self.readCounter(1, cycle), .timer3_counter => self.readCounter(2, cycle), .timer1_latch => self.timers[0].lsb_buffer, .timer2_latch => self.timers[1].lsb_buffer, .timer3_latch => self.timers[2].lsb_buffer, }; } pub fn write(self: *Ptm, register: Register, value: u8, cycle: u64) void { switch (register) { .control_1_or_3 => if (self.writeToCR1()) self.writeControl(0, value, cycle) else self.writeControl(2, value, cycle), .control_2_status => self.writeControl(1, value, cycle), .timer1_counter, .timer2_counter, .timer3_counter => self.msb_buffer = value, .timer1_latch => self.writeLatch(0, value, cycle), .timer2_latch => self.writeLatch(1, value, cycle), .timer3_latch => self.writeLatch(2, value, cycle), } } fn writeControl(self: *Ptm, i: usize, value: u8, cycle: u64) void { self.timers[i].control = value; if (i == 2) self.timers[2].prescale = value & 0x01 != 0; if (i == 0) { // CR1's low bit is the internal reset for every counter. const now_held = value & 0x01 != 0; if (now_held and !self.held) { for (&self.timers) |*t| { t.counting = false; t.cleared_at = cycle; t.clear_armed = false; t.epoch = cycle; } } else if (!now_held and self.held) { // Releasing the reset initializes every counter at once. for (&self.timers) |*t| { t.epoch = cycle; t.cleared_at = cycle; t.clear_armed = false; t.counting = true; } } self.held = now_held; } } fn writeLatch(self: *Ptm, i: usize, low: u8, cycle: u64) void { self.timers[i].latch = (@as(u16, self.msb_buffer) << 8) | low; // Writing the latch initializes the counter and clears this timer's // own flag, unless the chip is held in its internal reset. if (!self.held) { self.timers[i].epoch = cycle; self.timers[i].cleared_at = cycle; self.timers[i].clear_armed = false; self.timers[i].counting = true; } } fn readCounter(self: *Ptm, i: usize, cycle: u64) u8 { const value = self.timers[i].counter(cycle); self.timers[i].lsb_buffer = @truncate(value); // The flag clears on a counter read only if the status register was // read while it was set (§4.4, "Status Register"). if (self.timers[i].clear_armed) { self.timers[i].cleared_at = cycle; self.timers[i].clear_armed = false; } return @truncate(value >> 8); } /// The status register: one flag per timer in the low three bits, and a /// composite in bit 7. Reading it arms each set flag to be cleared by a /// following counter read. pub fn status(self: *Ptm, cycle: u64) u8 { var out: u8 = 0; for (&self.timers, 0..) |*t, i| { if (t.flagSet(cycle)) { out |= @as(u8, 1) << @intCast(i); t.clear_armed = true; } } if (self.interrupting(cycle)) out |= 0x80; return out; } /// Whether any timer is pulling the interrupt line: its flag set and its /// own interrupt-enable bit in. Pure, so it can be polled every cycle /// without disturbing the clear handshake. pub fn interrupting(self: *Ptm, cycle: u64) bool { for (&self.timers) |*t| { if (t.control & irq_enabled != 0 and t.flagSet(cycle)) return true; } return false; } pub fn reset(self: *Ptm) void { self.* = .{}; } }; const testing = std.testing; test "a continuous 16-bit timer times out every N+1 ticks and re-arms" { var ptm: Ptm = .{}; // CR2 low bit set so RS=0 reaches CR1; enable Timer #1's interrupt, // internal clock, 16-bit continuous. ptm.write(.control_2_status, 0x01, 0); // CR2: address bit for CR1 ptm.write(.control_1_or_3, clock_internal | irq_enabled, 0); // CR1 // Load Timer #1 with 99: MSB first, then LSB completes the write. ptm.write(.timer1_counter, 0x00, 0); // MSB buffer ptm.write(.timer1_latch, 99, 0); // latch = 99, counter initialized at cycle 0 // No timeout before N+1 = 100 ticks; the flag stands at 100. try testing.expect(!ptm.interrupting(99)); try testing.expect(ptm.interrupting(100)); try testing.expect(ptm.status(100) & 0x01 != 0); // Timer #1 flag try testing.expect(ptm.status(100) & 0x80 != 0); // composite // Clearing needs the status read (done above) then a counter read. _ = ptm.read(.timer1_counter, 101); try testing.expect(!ptm.interrupting(101)); // Continuous, so it fires again a period later. try testing.expect(ptm.interrupting(200)); } test "a single-shot timer fires once and stays put" { var ptm: Ptm = .{}; ptm.write(.control_2_status, 0x01, 0); ptm.write(.control_1_or_3, clock_internal | irq_enabled | single_shot, 0); ptm.write(.timer1_counter, 0x00, 0); ptm.write(.timer1_latch, 9, 0); // times out at 10 try testing.expect(!ptm.interrupting(9)); try testing.expect(ptm.interrupting(10)); // Well past a second period, still just the one timeout standing. try testing.expect(ptm.interrupting(1000)); _ = ptm.status(1000); _ = ptm.read(.timer1_counter, 1000); try testing.expect(!ptm.interrupting(2000)); } test "the interrupt-enable bit gates the line but not the flag" { var ptm: Ptm = .{}; ptm.write(.control_2_status, 0x01, 0); // Internal clock, continuous, interrupt masked. ptm.write(.control_1_or_3, clock_internal, 0); ptm.write(.timer1_counter, 0x00, 0); ptm.write(.timer1_latch, 9, 0); // The flag sets in the status register, but the line stays quiet. try testing.expect(ptm.status(10) & 0x01 != 0); try testing.expect(!ptm.interrupting(10)); try testing.expect(ptm.status(10) & 0x80 == 0); } test "a counter read clears the flag only after the status register is read" { var ptm: Ptm = .{}; ptm.write(.control_2_status, 0x01, 0); ptm.write(.control_1_or_3, clock_internal | irq_enabled, 0); ptm.write(.timer1_counter, 0x00, 0); ptm.write(.timer1_latch, 9, 0); // A counter read with no prior status read does not clear it. _ = ptm.read(.timer1_counter, 20); try testing.expect(ptm.interrupting(20)); // Read status, then the counter: now it clears. _ = ptm.status(20); _ = ptm.read(.timer1_counter, 20); try testing.expect(!ptm.interrupting(20)); } test "the internal reset holds the counters and clears the flags" { var ptm: Ptm = .{}; ptm.write(.control_2_status, 0x01, 0); ptm.write(.control_1_or_3, clock_internal | irq_enabled, 0); ptm.write(.timer1_counter, 0x00, 0); ptm.write(.timer1_latch, 9, 0); try testing.expect(ptm.interrupting(10)); // $43 = internal reset, internal clock, interrupt enabled: holds it. ptm.write(.control_1_or_3, 0x43, 15); try testing.expect(!ptm.interrupting(100)); // Releasing the reset starts the count over from the release cycle. ptm.write(.control_1_or_3, clock_internal | irq_enabled, 20); try testing.expect(!ptm.interrupting(29)); try testing.expect(ptm.interrupting(30)); } test "CR2's low bit routes an RS=0 write to CR1 or CR3" { var ptm: Ptm = .{}; // With CR2 low bit clear, RS=0 writes CR3 — Timer #3's control. ptm.write(.control_2_status, 0x00, 0); ptm.write(.control_1_or_3, clock_internal | irq_enabled | 0x01, 0); // CR3, prescale on try testing.expect(ptm.timers[2].prescale); try testing.expectEqual(@as(u8, 0), ptm.timers[0].control); // With it set, the same address reaches CR1. ptm.write(.control_2_status, 0x01, 0); ptm.write(.control_1_or_3, clock_internal, 0); try testing.expectEqual(clock_internal, ptm.timers[0].control); // Timer #3's prescaler stretches its period to 8*(N+1). ptm.write(.timer3_counter, 0x00, 0); ptm.write(.timer3_latch, 9, 0); // 8 * 10 = 80 ticks try testing.expect(!ptm.interrupting(79)); try testing.expect(ptm.interrupting(80)); }