// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The MM58167, National Semiconductor's real time clock: the chip on an //! Apple III's board, at `$C070`, that SOS asks the date and time of. //! //! It keeps "an addressable real time counter, 56 bits of RAM, and two //! interrupt outputs" (National Semiconductor, 1995, p. 1). The counter runs //! from milliseconds to months in BCD, "divided into 4-bit digits with 2 //! digits being accessed during any read or write cycle" (p. 3), and there //! is no year: SOS keeps that in two of the RAM digits, in the bits the //! comparator ignores. The register map is Table III (p. 4), the digit layout //! Table I (p. 3), the interrupt register Figure 1 (p. 5). //! //! Its five address lines are, on a III, the low five bits of the zero-page //! register — the D VIA's port B — so SOS selects a register by moving its //! zero page and puts it back afterwards; that is the machine's business, //! and the chip here only sees a register number. const std = @import("std"); const clockcard = @import("clockcard.zig"); pub const Register = enum(u5) { milliseconds = 0x00, hundredths = 0x01, seconds = 0x02, minutes = 0x03, hours = 0x04, weekday = 0x05, day = 0x06, month = 0x07, ram_milliseconds = 0x08, ram_hundredths = 0x09, ram_seconds = 0x0a, ram_minutes = 0x0b, ram_hours = 0x0c, ram_weekday = 0x0d, ram_day = 0x0e, ram_month = 0x0f, interrupt_status = 0x10, interrupt_control = 0x11, counters_reset = 0x12, ram_reset = 0x13, status = 0x14, go = 0x15, standby_interrupt = 0x16, test_mode = 0x1f, _, }; /// The bits of the interrupt control and status registers, from Figure 1: /// each is a counter's "rollover to its reset state", or the comparator. pub const irq_compare: u8 = 0x01; pub const irq_tenth: u8 = 0x02; pub const irq_second: u8 = 0x04; pub const irq_minute: u8 = 0x08; pub const irq_hour: u8 = 0x10; pub const irq_day: u8 = 0x20; pub const irq_week: u8 = 0x40; pub const irq_month: u8 = 0x80; pub const Mm58167 = struct { /// Whether there is a chip in the socket. Apple took it out of the first /// machines and put it back for the III Plus; SOS reads the status /// register to find out — "DOES CLOCK EXIST?" — and takes a set top bit, /// which an empty socket's floating bus gives, as no. Answering for the /// chip when it is not fitted is the machine's business, not this. fitted: bool = false, /// How fast the count it is handed runs. The chip has its own 32,768 Hz /// crystal; what it is given here is the processor's cycles, and this is /// how many make a second. cycles_per_second: u64, // The counter, a digit at a time as the chip keeps it. milliseconds: u16 = 0, seconds: u8 = 0, minutes: u8 = 0, hours: u8 = 0, /// One to seven. The chip does not say which day is one; SOS makes /// Sunday one, and works the day out from the date when it sets the clock. weekday: u8 = 1, day: u8 = 1, month: u8 = 1, /// The RAM, one byte to a counter, "formatted the same as the real time /// counter, 4 bits per digit, 14 digits, however there are no unused /// bits" (p. 3). ram: [8]u8 = @splat(0), control: u8 = 0, status: u8 = 0, standby_enabled: bool = false, /// The rollover status bit and whether it is watching: "the status bit is /// set if this 1 kHz clock occurs during or after any counter read" /// (p. 5), so a counter read arms it and the tick sets it, and reading /// the status register takes both down. rollover: bool = false, rollover_armed: bool = false, /// The cycle the counter was last brought up to, and the cycles since /// that did not yet make a millisecond. at: u64 = 0, remainder: u64 = 0, /// Sets the clock to a moment, as an owner did with the utilities' "set /// Time and date". The year, which the chip has no counter for, goes /// where SOS keeps it: in the day and month RAM digits, the low two bits /// of the year in the day's and the next two in the month's, with the /// other bits set to make the comparator ignore them — `ORA #$CC ;STUFF /// YEAR INTO DAY AND MONTH LATCHES` (Apple Computer, Inc., 1982b, p. 328). /// Two digits of it, since "GET.TIME ALWAYS SETS THE CENTURY TO 19". pub fn set(self: *Mm58167, when: clockcard.Time, cycles: u64) void { self.milliseconds = 0; self.seconds = when.second; self.minutes = when.minute; self.hours = when.hour; self.weekday = @as(u8, when.weekday()) + 1; self.day = when.day; self.month = when.month; const year = toBcd(@intCast(when.year % 100)); self.ram[6] = year | 0xcc; self.ram[7] = (year >> 2) | 0xcc; self.at = cycles; self.remainder = 0; } /// Brings the counter up to the cycle, raising whatever rolled over. pub fn catchUp(self: *Mm58167, cycles: u64) void { if (cycles <= self.at) return; const per_millisecond = self.cycles_per_second / 1000; const total = self.remainder + (cycles - self.at); self.at = cycles; self.remainder = total % per_millisecond; const ticks = total / per_millisecond; if (ticks == 0) return; if (self.rollover_armed) self.rollover = true; self.advance(ticks); } /// Counts forward so many milliseconds, carrying up the digits and /// noting each counter that rolled over to its reset state. fn advance(self: *Mm58167, ticks: u64) void { var millis = @as(u64, self.milliseconds) + ticks; if (millis / 100 != self.milliseconds / 100) self.status |= irq_tenth; const secs = millis / 1000; millis %= 1000; self.milliseconds = @intCast(millis); if (secs == 0) return; self.status |= irq_second; var s = @as(u64, self.seconds) + secs; const mins = s / 60; s %= 60; self.seconds = @intCast(s); if (mins == 0) return; self.status |= irq_minute; var m = @as(u64, self.minutes) + mins; const hrs = m / 60; m %= 60; self.minutes = @intCast(m); if (hrs == 0) return; self.status |= irq_hour; var h = @as(u64, self.hours) + hrs; var days = h / 24; h %= 24; self.hours = @intCast(h); while (days > 0) : (days -= 1) { self.status |= irq_day; self.weekday = if (self.weekday >= 7) 1 else self.weekday + 1; if (self.weekday == 1) self.status |= irq_week; // The chip knows the months' lengths but not the year, so // February is always twenty-eight days: the clock "must be reset // ... on 29 February in leap years" (Apple Computer, Inc., // 1982b, p. 327). if (self.day >= daysInMonth(self.month)) { self.day = 1; self.month = if (self.month >= 12) 1 else self.month + 1; self.status |= irq_month; } else { self.day += 1; } } } fn daysInMonth(month: u8) u8 { return switch (month) { 2 => 28, 4, 6, 9, 11 => 30, else => 31, }; } /// Whether the interrupt output is up: a status bit whose control bit is /// set. "Once one or more bits have been set in the interrupt control /// register, the corresponding counter's rollover to its reset state /// will clock the interrupt status register and cause the interrupt /// output to go high" (p. 3). pub fn interrupting(self: *const Mm58167) bool { return self.status & self.control != 0; } pub fn read(self: *Mm58167, register: Register, cycles: u64) u8 { self.catchUp(cycles); return switch (register) { // Table I: the milliseconds register carries only the // thousandths digit, in its high nibble; the next the // hundredths and tenths. .milliseconds => self.counterRead(toBcd(@intCast(self.milliseconds % 10)) << 4), .hundredths => self.counterRead(toBcd(@intCast(self.milliseconds / 10))), .seconds => self.counterRead(toBcd(self.seconds)), .minutes => self.counterRead(toBcd(self.minutes)), .hours => self.counterRead(toBcd(self.hours)), .weekday => self.counterRead(self.weekday), .day => self.counterRead(toBcd(self.day)), .month => self.counterRead(toBcd(self.month)), .ram_milliseconds, .ram_hundredths, .ram_seconds, .ram_minutes, .ram_hours, .ram_weekday, .ram_day, .ram_month => self.ram[@intFromEnum(register) - 8], // "To reset the interrupt and to identify which frequency caused // the interrupt, the interrupt status register is read ... // Removing the read will reset the interrupt" (p. 3). .interrupt_status => taken: { const was = self.status; self.status = 0; break :taken was; }, .interrupt_control => self.control, // "The status bit appears on D0 when address 14H is read. All the // other data lines will zero ... The trailing edge of the read at // address 14H will reset the status bit" (p. 5). .status => taken: { const was: u8 = @intFromBool(self.rollover); self.rollover = false; self.rollover_armed = false; break :taken was; }, .standby_interrupt => @intFromBool(self.standby_enabled), else => 0, }; } /// A counter read arms the rollover bit for the tick that may follow. fn counterRead(self: *Mm58167, value: u8) u8 { self.rollover_armed = true; return value; } pub fn write(self: *Mm58167, register: Register, value: u8, cycles: u64) void { self.catchUp(cycles); switch (register) { // "Any unused bits are ... ignored during a write" (p. 3), so // each digit is masked to what the counter has room for. .milliseconds => self.milliseconds = (self.milliseconds / 10) * 10 + @min(9, value >> 4), .hundredths => self.milliseconds = self.milliseconds % 10 + @as(u16, fromBcd(value)) * 10, .seconds => self.seconds = fromBcd(value & 0x7f), .minutes => self.minutes = fromBcd(value & 0x7f), .hours => self.hours = fromBcd(value & 0x3f), .weekday => self.weekday = value & 0x07, .day => self.day = fromBcd(value & 0x3f), .month => self.month = fromBcd(value & 0x1f), .ram_milliseconds, .ram_hundredths, .ram_seconds, .ram_minutes, .ram_hours, .ram_weekday, .ram_day, .ram_month => self.ram[@intFromEnum(register) - 8] = value, .interrupt_control => self.control = value, // "The counters and RAM can be reset by writing all 1's (FF) at // address 12H or 13H respectively" (p. 5). .counters_reset => if (value == 0xff) { self.milliseconds = 0; self.seconds = 0; self.minutes = 0; self.hours = 0; self.weekday = 0; self.day = 0; self.month = 0; }, .ram_reset => if (value == 0xff) { self.ram = @splat(0); }, // "A write pulse at address 15H will reset the thousandths, // hundredths, tenths, units, and tens of seconds counters ... // If the seconds counter is at a value greater than 39 when the // GO is issued, the minute counter will increment" (p. 5). .go => { if (self.seconds > 39) self.minutes = if (self.minutes >= 59) 0 else self.minutes + 1; self.seconds = 0; self.milliseconds = 0; self.remainder = 0; }, .standby_interrupt => self.standby_enabled = value & 1 != 0, else => {}, } } /// The counter as a moment, for whoever wants to check it. The year is /// the one SOS left in the RAM, if it left one; otherwise 1900. pub fn now(self: *Mm58167, cycles: u64) clockcard.Time { self.catchUp(cycles); const year: u16 = if (self.ram[6] & 0xcc == 0xcc and self.ram[7] & 0xcc == 0xcc) 1900 + @as(u16, fromBcd((self.ram[6] & 0x33) | (self.ram[7] & 0x33) << 2)) else 1900; return .{ .year = year, .month = @intCast(@max(1, @min(12, self.month))), .day = @intCast(@max(1, @min(31, self.day))), .hour = @intCast(@min(23, self.hours)), .minute = @intCast(@min(59, self.minutes)), .second = @intCast(@min(59, self.seconds)), }; } }; fn toBcd(value: u8) u8 { return (value / 10) << 4 | (value % 10); } fn fromBcd(value: u8) u8 { return (value >> 4) * 10 + (value & 0x0f); } const testing = std.testing; test "the counter runs in BCD from milliseconds to months, and carries the way a calendar does" { var chip: Mm58167 = .{ .cycles_per_second = 2_000_000, .fitted = true }; // Set as SOS sets it: 23:59:58 on Sunday the 31st of January. chip.set(.{ .year = 1988, .month = 1, .day = 31, .hour = 23, .minute = 59, .second = 58 }, 0); try testing.expectEqual(@as(u8, 0x58), chip.read(.seconds, 0)); try testing.expectEqual(@as(u8, 0x59), chip.read(.minutes, 0)); try testing.expectEqual(@as(u8, 0x23), chip.read(.hours, 0)); try testing.expectEqual(@as(u8, 0x31), chip.read(.day, 0)); try testing.expectEqual(@as(u8, 0x01), chip.read(.month, 0)); // The 31st of January 1988 was a Sunday, which SOS counts as one. try testing.expectEqual(@as(u8, 1), chip.read(.weekday, 0)); // A tenth of a second on, the hundredths register shows it. try testing.expectEqual(@as(u8, 0x10), chip.read(.hundredths, 200_000)); // Two seconds on it is midnight on Monday the first of February. const two_seconds = 2 * 2_000_000; try testing.expectEqual(@as(u8, 0x00), chip.read(.seconds, two_seconds)); try testing.expectEqual(@as(u8, 0x00), chip.read(.minutes, two_seconds)); try testing.expectEqual(@as(u8, 0x00), chip.read(.hours, two_seconds)); try testing.expectEqual(@as(u8, 0x01), chip.read(.day, two_seconds)); try testing.expectEqual(@as(u8, 0x02), chip.read(.month, two_seconds)); try testing.expectEqual(@as(u8, 2), chip.read(.weekday, two_seconds)); // Every counter but the week rolled over on the way. try testing.expectEqual(irq_tenth | irq_second | irq_minute | irq_hour | irq_day | irq_month, chip.read(.interrupt_status, two_seconds)); try testing.expectEqual(@as(u8, 0), chip.read(.interrupt_status, two_seconds)); // February has twenty-eight days, whatever the year. const march = two_seconds + 28 * 24 * 60 * 60 * @as(u64, 2_000_000); try testing.expectEqual(@as(u8, 0x01), chip.read(.day, march)); try testing.expectEqual(@as(u8, 0x03), chip.read(.month, march)); } test "the rollover status bit says a tick came after a counter was read" { var chip: Mm58167 = .{ .cycles_per_second = 2_000_000, .fitted = true }; chip.set(.{ .year = 1988, .month = 6, .day = 15 }, 0); // A read and the status straight after: nothing rolled. _ = chip.read(.seconds, 100); try testing.expectEqual(@as(u8, 0), chip.read(.status, 200)); // A read, a millisecond, then the status: it did, and asking took it down. _ = chip.read(.seconds, 300); try testing.expectEqual(@as(u8, 1), chip.read(.status, 300 + 2000)); try testing.expectEqual(@as(u8, 0), chip.read(.status, 300 + 2000)); // A tick with no counter read outstanding sets nothing. try testing.expectEqual(@as(u8, 0), chip.read(.status, 300 + 6000)); } test "the resets, the GO command and the year in the RAM" { var chip: Mm58167 = .{ .cycles_per_second = 2_000_000, .fitted = true }; chip.set(.{ .year = 1987, .month = 12, .day = 25, .hour = 10, .minute = 20, .second = 45 }, 0); // The year is in the RAM the way SOS reads it back: `LDA $0F; SEC; ROL; // ROL; AND $0E`. const high = chip.read(.ram_month, 0); const low = chip.read(.ram_day, 0); try testing.expectEqual(@as(u8, 0x87), (high << 2 | 0x03) & low); try testing.expectEqual(@as(u16, 1987), chip.now(0).year); // GO at forty-five seconds: the seconds go, the minute rounds up. chip.write(.go, 0, 0); try testing.expectEqual(@as(u8, 0x00), chip.read(.seconds, 0)); try testing.expectEqual(@as(u8, 0x21), chip.read(.minutes, 0)); // Only all ones resets the counters; and it takes the RAM with it only // at its own address. chip.write(.counters_reset, 0x00, 0); try testing.expectEqual(@as(u8, 0x25), chip.read(.day, 0)); chip.write(.counters_reset, 0xff, 0); try testing.expectEqual(@as(u8, 0x00), chip.read(.day, 0)); try testing.expectEqual(@as(u8, 0x00), chip.read(.month, 0)); try testing.expectEqual(low, chip.read(.ram_day, 0)); chip.write(.ram_reset, 0xff, 0); try testing.expectEqual(@as(u8, 0), chip.read(.ram_day, 0)); // SOS's own way in: reset, then each counter written in BCD. chip.write(.seconds, 0x30, 0); chip.write(.minutes, 0x15, 0); chip.write(.hours, 0x09, 0); chip.write(.weekday, 0x04, 0); chip.write(.day, 0x07, 0); chip.write(.month, 0x11, 0); const then = chip.now(0); try testing.expectEqual(@as(u5, 7), then.day); try testing.expectEqual(@as(u4, 11), then.month); try testing.expectEqual(@as(u6, 30), then.second); } test "an interrupt is a rollover whose bit is enabled, and reading the status takes it down" { var chip: Mm58167 = .{ .cycles_per_second = 2_000_000, .fitted = true }; chip.set(.{ .year = 1988 }, 0); chip.write(.interrupt_control, irq_second, 0); try testing.expect(!chip.interrupting()); chip.catchUp(2_000_000); try testing.expect(chip.interrupting()); _ = chip.read(.interrupt_status, 2_000_000); try testing.expect(!chip.interrupting()); // A tenth-of-a-second rollover is not wanted, so it does not interrupt. chip.catchUp(2_200_000); try testing.expect(!chip.interrupting()); }