// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! An Apple IIgs. It has come a fair way from its first version — it has its //! memory, its video and the registers behind them — but it is not a complete //! machine, and its gaps are still found the same way. //! //! There is no corpus for a machine. What there is instead is the ROM: it runs //! a self-test when the power comes on, and if the machine is honest about //! what it has not got, the ROM will say what it wanted and in what order. //! So this model implements the memory and keeps a tally of every soft switch //! it does not understand, and the tally is the list of what to do next. //! //! What is here: //! //! - Fast RAM from bank `$00` up, and slow RAM in `$e0` and `$e1`; the first //! two fast banks with the two slow ones are the 256K a IIgs came with. //! - The ROM, in whichever top banks the image turns out to hold, found by //! `iigsrom.identify` because the file does not say. //! - The language card window, `$d000` to `$ffff` in banks `$00` and `$01`, //! reading from ROM at power-on. That is the whole reason the machine //! starts at all: the reset vector is read from `$00fffc`, and it has to //! come from the ROM through this window. //! //! And the registers the firmware asked for that the Hardware Reference (Apple //! Computer, Inc., 1989) answers plainly, which is most of them. Many are kept //! and read back rather than acted on — a register that remembers what was //! written to it is a great deal better than one that reads zero, since //! firmware writes a configuration and then checks it took — but a growing //! number do their work: the video controller, shadowing, the speed and state //! registers, and vertical blanking and the VGC's timers, which are drawn from //! the clock. //! //! And a Mega II, and its memory. Banks `$e0` and `$e1` of a IIgs are an Apple //! IIe's 128K, `memory/apple2e.zig` is an Apple IIe, and the `host` option on //! that model exists so that one can be part of a larger machine rather than //! the whole of one. Both its switch page — `$c000` to `$c0ff`, the keyboard, //! the eighty-column and character-set switches, the slot ROM switches, the //! speaker — and its 128K are wired, and the second is what makes the video //! real: the display is drawn out of that memory, Super Hi-Res from the VGC //! (`superhires.zig`) and the legacy IIe modes through the shared `video.zig`. //! Which half a bank address reaches is bit 0 of the New-Video register: set, //! the low bit of the address picks main or auxiliary directly; clear, the //! IIe's own switches decide. See `vgc` below. //! //! Shadowing (`$c035`), the speed register (`$c036`) and the state register //! (`$c068`) are modelled too, where an earlier version of this only counted //! them, and fast RAM runs on past the first 256K — a IIgs board holds banks //! `$00` to `$7f`, eight megabytes, and an expansion card carries it further. //! //! What is not: //! //! - PAL timing. The frame stays the 262-line NTSC one whatever the PAL bit //! says; the bit only reads back (`vgc.zig`). //! - The IIgs floating bus. A `$c0xx` this does not model reads zero rather //! than whatever the bus was last carrying. //! - Whatever the ROM is still asking for that the tally of unknown soft //! switches has not been read off yet — which is the whole reason the //! tally is kept. const std = @import("std"); const bus_log = @import("bus.zig"); const snapshot = @import("../snapshot.zig"); const iigsrom = @import("../iigsrom.zig"); const apple2e = @import("../memory8/apple2e.zig"); const adb_module = @import("../adb.zig"); const blockdevice = @import("../blockdevice.zig"); const rtc_module = @import("../rtc.zig"); const iwm_module = @import("../iwm.zig"); const slot_module = @import("../slots.zig"); const w5100 = @import("../w5100.zig"); const cs8900 = @import("../cs8900.zig"); const disk35 = @import("../disk35.zig"); const superhires = @import("../superhires.zig"); const video = @import("../video.zig"); const ensoniq = @import("../ensoniq.zig"); const vgc_module = @import("../vgc.zig"); const scc_module = @import("../scc.zig"); const languagecard = @import("../languagecard.zig"); const disk2 = @import("../disk2.zig"); pub const Options = bus_log.Options; pub const Cycle = bus_log.Cycle; /// A bank is sixty-four kilobytes, as everywhere else. pub const bank_size = 0x10000; /// The banks the Mega II answers for: its main 64K and its auxiliary 64K. pub const slow_bank: u8 = 0xe0; /// How much of the address space the soft switches take up, in every bank /// that has them. const io_from: u16 = 0xc000; const io_to: u16 = 0xd000; /// Where the hard disk goes, and what it answers at. /// /// Slot 7, which is where a IIgs leaves the Slot register pointing at /// power-on: the firmware writes `$80` to `$c02d`, so every slot is the /// machine's own built-in firmware except the seventh, which is a card's. A /// IIgs has no built-in seventh anything — 1 is the printer port, 2 the /// modem, 3 the eighty-column firmware, 4 the desktop bus, 5 the 3.5-inch /// drives and 6 the 5.25-inch — so seven is the slot left over, and it is /// where a hard disk went on a real one. Nothing has to be changed in the /// Control Panel first. const block_slot = 7; const block_rom_base: u16 = 0xc000 + block_slot * 0x100; const block_switch_base: u8 = 0x80 + block_slot * 0x10; /// The card's own firmware, which is ours: what a ProDOS block device has to /// answer to is published, so there is no ROM to find. See blockdevice.zig. const block_firmware = blockdevice.firmware(block_slot); /// A cycle of the Mega II's clock, in cycles of the processor's. /// /// The processor runs at 2.8 MHz and the Mega II at 1.024, and anything /// reaching across to the slow side has to wait for it. The Hardware Reference /// (Apple Computer, Inc., 1989a) puts a synchronised slow access at "nearly /// three fast cycles", and three is what is used here — everywhere, including /// for the video's own timing, so that the two sides of the machine agree with /// each other. The true ratio is 2.73, and using the rounder number in one /// place and the exact one in another would leave the display and the processor /// disagreeing about how long a frame is, which is a worse error than being /// nine per cent slow in absolute terms. Nothing here measures absolute time /// yet. /// /// A slow access is *not* always this long, and that is modelled: see /// `slowAccess`. pub const slow_cycle = 3; /// An Apple IIgs. pub fn AppleIIgs(comptime options: Options) fn (type) type { return struct { fn model(comptime CPU: type) type { return struct { const Self = @This(); pub const Access = bus_log.Access; /// The Mega II, which is an Apple IIe and is where every soft /// switch older than this machine answers. pub const Mega2 = apple2e.AppleIIe(.{ .host = .given })(CPU); /// The video controller's type, so that a test can name its /// bits without reaching into another file for them. pub const Vgc = vgc_module.Vgc; /// The switch page. Everything from `$c000` to `$c0ff`, in any /// bank that has I/O, is the Mega II's to answer. /// /// The four kilobytes above it are not: `$c100` to `$cfff` is /// slot ROM space, and on this machine it comes from this /// machine's own ROM rather than from a IIe's. const switches_from: u16 = 0xc000; const switches_to: u16 = 0xc100; /// The interrupt ROM: fifteen bytes of the machine's own ROM /// inside the switch page, which the Monitor's interrupt /// handler jumps into. /// /// They are there whatever else the bank is configured to do, /// and the Hardware Reference says so twice (Apple Computer, /// Inc., 1989). Its speed table has them as ROM reads that do /// not slow the system down; its interrupt chapter says the /// code "is available when shadowing is enabled to inhibit I/O /// and language-card operation", and that "the SETINTCXROM and /// CLRINTCXROM switches do not affect interrupt ROM accesses". /// /// What is in them is four doors into the same handler. At /// `$ffc071` the ROM has `SEP #$40` and at `$ffc074` `CLV`, /// and both fall into a `JML $e10010`; at `$ffc079` `SEC` and /// at `$ffc07b` `CLC`, both falling into a `JML $ffb7b4`. /// Which door was used is carried out in the flag, which is /// how the handler on the far side tells an interrupt from a /// BRK without anything having to be written down. /// /// Only reads. A write to this part of the page is the paddle /// trigger's, as it is on a IIe, and the speed table agrees: /// fast to read and slow to write. const interrupt_rom_from: u16 = 0xc071; const interrupt_rom_to: u16 = 0xc080; /// Bit 0 of the New-Video register: the bank latch, named /// where the register it belongs to is. const bank_latch = vgc_module.Vgc.bank_latch; /// The Shadow register's bits. Every one of them is an /// *inhibit*: set disables and clear enables, so a register of /// zeroes — which is what a reset leaves — shadows everything. const inhibit_text_1: u8 = 0x01; const inhibit_hires_1: u8 = 0x02; const inhibit_hires_2: u8 = 0x04; const inhibit_super_hires: u8 = 0x08; const inhibit_auxiliary_hires: u8 = 0x10; const inhibit_text_2: u8 = 0x20; /// Bit 6, which is not about shadowing at all. It decides /// whether the `$c000` to `$cfff` range in banks `$00` and /// `$01` is I/O or RAM, and with it whether those banks have a /// language card. Clear -- which is what a reset leaves -- and /// the I/O space is there and the RAM behind it becomes a /// second `$dxxx` bank; set, and the bank is sixty-four /// kilobytes of contiguous RAM with neither. /// /// It never applies to banks `$e0` and `$e1`, where the I/O /// space and the language card are always there. const inhibit_io_language_card: u8 = 0x40; /// The size of the doubly-banked window at `$d000`, which is /// also the distance from it down to the four kilobytes hidden /// behind the I/O space. const bank_window: u16 = 0x1000; /// Where the seven slot pages stop and the shared expansion /// ROM begins. const expansion_from: u16 = 0xc800; /// Bit 4 of the Speed register: shadow every RAM bank rather /// than only the first two. The manual says not to, in as many /// words — firmware running in another bank is corrupted by it /// and the machine crashes — but the bit exists and this /// answers it. const shadow_every_bank: u8 = 0x10; /// The display buffers, at the addresses they have had since /// 1977, and the Shadow register bit that turns each one off. const text_1_from: u16 = 0x0400; const text_1_to: u16 = 0x0800; const text_2_to: u16 = 0x0c00; const hires_1_from: u16 = 0x2000; const hires_1_to: u16 = 0x4000; const hires_2_to: u16 = 0x6000; /// The Super Hi-Res buffer is a single 32K span in the /// auxiliary bank, from $2000 to $9fff, and the two Hi-Res /// pages sit underneath its lower half. const super_hires_to: u16 = 0xa000; /// Bit 7 of the Speed register: 2.8 MHz when set, and the /// Mega II's 1.024 MHz when clear. const speed_fast: u8 = 0x80; /// Bit 6: whether the machine was started with the power switch /// rather than by a reset. The Hardware Reference (Apple /// Computer, Inc., 1989) is exact about the difference — "the /// Speed register is cleared on reset or power up, except for /// bit 6, which on power up is set", and "a boot initiated by /// any key combination will not alter this bit" — so it is the /// one bit that tells a cold start from a warm one, and the one /// bit a reset leaves alone. /// /// Which also settles what the register holds at power-on, and /// it is not what was assumed here. The guess was $80, reasoned /// from the Firmware Reference's "system firmware, running in /// ROM, runs at the full 2.8 MHz" (Apple Computer, Inc., 1987a) /// — but a machine does not /// *start* fast, it is *made* fast, and making it so is one of /// the first things the firmware does. Starting it fast hid /// that instruction rather than obeying it. const speed_power_on: u8 = 0x40; /// Bits 0 to 3: the motor-on detectors for slots 4 to 7, in /// that order. const motor_detect_bits: u8 = 0x0f; /// How many unanswered accesses to keep. Enough to see the /// shape of a loop and what went into it. pub const trace_length = 48; /// The machine's own interrupts: which are enabled, and /// which have happened and not yet been owned up to. /// /// Two registers, and they line up bit for bit, which is the /// whole convenience of them. `$c041` enables and `$c046` /// reports, and bit 4 is the quarter-second tick in both, bit /// 3 vertical blanking, bit 2 the Mega II's mouse button and /// bit 1 its movement. /// /// The quarter-second one is not really a quarter of a second. /// The Firmware Reference (Apple Computer, Inc., 1987a) names /// `$c047` "clear the VBL/3.75Hz interrupt flags", and 3.75 Hz /// is exactly sixty divided by sixteen — so it is the frame /// counter with its low four bits masked off, and comes out at /// 0.267 seconds. Deriving it from the video rather than from a /// made-up cycle count is both simpler and what the hardware /// does. pub const Interrupts = struct { /// `$c041`. The top three bits must be written as zero. enable: u8 = 0, quarter_second: bool = false, vbl: bool = false, mouse_switch: bool = false, mouse_move: bool = false, pub const quarter_second_bit: u8 = 0x10; pub const vbl_bit: u8 = 0x08; pub const mouse_switch_bit: u8 = 0x04; pub const mouse_move_bit: u8 = 0x02; /// Bit 0 of `$c041` enables the Mega II's mouse at all, /// rather than enabling an interrupt from it. pub const mouse_bit: u8 = 0x01; /// Which of the four have happened, in the positions /// `$c046` reports them in — the same positions `$c041` /// enables them in. pub fn pending(self: *const Interrupts) u8 { var value: u8 = 0; if (self.quarter_second) value |= quarter_second_bit; if (self.vbl) value |= vbl_bit; if (self.mouse_switch) value |= mouse_switch_bit; if (self.mouse_move) value |= mouse_move_bit; return value; } /// Whether any interrupt that is both enabled and pending /// is asking for the line. pub fn asking(self: *const Interrupts) bool { return self.enable & self.pending() != 0; } }; /// One unanswered access. pub const Trace = struct { address: u16, value: u8, write: bool, }; bus: bus_log.Log(options.bus_log) = .{}, gpa: std.mem.Allocator, /// Banks `$00` and `$01`: the fast side, which the processor /// reaches at full speed. fast: []u8, /// The ROM image, and what was worked out about how it is laid /// out. Empty until one is loaded, and then the machine can /// start. rom: []u8, rom_image: ?iigsrom.Image, /// The same ROM as a table of bank bases, so that the hottest /// question the decoder answers — this bank is ROM, here is /// the byte — is one load and one branch. Half of everything /// a IIgs executes is in banks `$fe` and `$ff`, and asking /// the image for a bank each time meant a division and a /// switch on the image's layout for every one of them. rom_banks: [256]?[*]const u8 = @splat(null), /// The firmware bank's base, for the places bank zero shows /// the ROM: the language card window, the interrupt ROM, the /// slot pages and the vectors. firmware_rom: ?[*]const u8 = null, mega2: Mega2, /// The Apple Desktop Bus, which is how this machine has a /// keyboard and a mouse at all. adb: adb_module.Adb, /// The hard disk in slot 7: a ProDOS block device, built in /// behind the seventh slot, so it answers there when no card is /// fitted to it. hard_disk: blockdevice.Card, /// The seven expansion slots, reached through the same /// apparatus the eight-bit machines use. Which slots answer as /// cards rather than as the machine's own built-in devices is /// the Slot register's business, asked in `cardAnswers`. The /// hard disk above stays the slot-7 built-in, answering behind /// an empty seventh slot. slots: slot_module.Slots = .{}, /// The clock chip, and the border colour that shares its /// control register. rtc: rtc_module.Rtc, /// The disk port, which is an IWM where a IIe had a card. iwm: iwm_module.Iwm, /// The two serial ports, which are one chip: the printer port /// is its channel A and the modem port its channel B. scc: scc_module.Scc, /// The sound chip, and the sixty-four kilobytes of waveform /// storage that belong to it and to nothing else. doc: ensoniq.Doc, /// Where the sound is being written down, if it is. The front /// end owns it; this is only somewhere for the machine to find /// it, because the only place the chip can be sampled at the /// rate a file wants is where the chip is wound forward. sound: ?*ensoniq.Recorder = null, /// The video controller: the New-Video register at `$c029`, /// the monochrome bit at `$c021`, the text and background /// colours at `$c022` and the character generator's language /// at `$c02b`. /// /// Bit 0 of the New-Video register is the one that matters /// most here, and it is not about video at all. It is the /// *bank latch*, and it decides the seam between this machine /// and the Mega II inside it: set, the low bit of the bank /// address picks the Mega II's main or auxiliary 64K directly, /// so `$e1xxxx` is the auxiliary bank whatever the old soft /// switches say; clear, the Mega II ignores the bank bit and /// the switches decide, as on a IIe. /// /// Which makes it a satisfying thing to have found: it is the /// exact question left open when this model was written, and /// it is also the first register the firmware asks for. vgc: vgc_module.Vgc, /// The Shadow register, `$c035`. Every bit is an *inhibit*: /// one disables, zero enables. Bit 6 inhibits the I/O and /// language-card space in banks `$00` and `$01` — never in /// `$e0` and `$e1`, where they are always there — and bits 5 /// to 0 inhibit shadowing of text page 2, the auxiliary /// Hi-Res pages, the Super Hi-Res buffer, Hi-Res page 2, /// Hi-Res page 1 and text page 1. shadow: u8, /// The Speed register, `$c036`. Bit 7 is the processor speed, /// bit 6 the power-on status, bit 4 enables shadowing in every /// RAM bank rather than just the first two, and the low four /// are the motor-on detects for slots 7, 6, 5 and 4. speed: u8, /// What the four motor-on detectors have detected, one bit a /// slot in the same order as the Speed register's low four: /// "the motor-on detectors change the system speed to 1.024 /// MHz whenever a Disk II motor-on address is detected. When /// the disk motor-off address is accessed, the system speed /// increases to 2.8 MHz again" (Apple Computer, Inc., 1989a, /// Table 2-2). They are address detectors, not motor sensors: /// what they watch is the bus, so the drive's own second of /// turning after it is told to stop does not keep the machine /// slow, and a detector whose enable bit is clear is watching /// to no effect. motor_detected: u8, /// Bit 1 of the State register, which is the only one of the /// eight that is not a switch this machine has: it says which /// half of the ROM shows in the language card window, and the /// Hardware Reference (Apple Computer, Inc., 1989a) says /// outright "this bit must always be 0 ... do not modify this /// bit". It is kept so that a program reading the register and /// writing it back gets what it had. rom_bank: bool, /// Which interrupts are enabled and which have happened. interrupts: Interrupts, /// Where the beam has got to, counted in scan lines since the /// machine started, so that the lines it has crossed since /// anything last looked can be walked. scan_lines: u64 = 0, /// The cycle at which the line after `scan_lines` begins, /// which is the next moment anything `updateVideo` keeps can /// change: blanking, the frame count and the scan-line /// interrupt all move on line boundaries, since a line is the /// unit every one of those constants is a multiple of. An /// access inside the line already counted has nothing to do. next_line: u64 = 0, /// Whether the beam is off the bottom of the screen. blanked: bool, /// How many vertical blanking intervals have begun since the /// machine started. Every timed interrupt it has is counted in /// frames, so this is where they all come from. frames: u64, /// The Slot register, `$c02d`, and which of two devices /// answers for each of the seven slots. /// /// A IIgs has the cards a IIe had built into it — a printer /// port, a modem port, a mouse, two disk drives and AppleTalk /// — and each sits at the slot its card would have gone in. /// A bit clear here means the built-in one answers and its /// driver comes from the system ROM; a bit set means the slot /// itself does, and `$Cn00` to `$CnFF` comes from a card. Bits /// 3 and 0 are reserved, and slot 3 is missing from the list /// altogether: its ROM space is still governed by the IIe's /// own `SETSLOTC3ROM` and `SETINTC3ROM`, for compatibility /// with the eighty-column card that used to live there. /// /// An Apple II card fitted to `slots` answers a slot whose bit /// is set, through the same apparatus the eight-bit machines /// use; a slot with nothing fitted and its bit set points the /// processor at a card that is not there and gets nothing, which /// is why the manual's advice is not to touch this register. slot_rom: u8, /// How many times each soft switch was touched and never /// understood. This is the to-do list, written by the ROM. unimplemented: [0x100]u32, /// And the first address the machine asked for that this could /// not answer at all, which is usually more use than the tally. first_unimplemented: ?u16, /// The last few unanswered accesses, in order, with what was /// written and whether it was a write. /// /// The tally says what the firmware wants; this says what it /// is *doing*, which is a different question and often the /// more useful one. A switch asked for fifteen thousand times /// is a spin loop, and what a spin loop is waiting for can /// only be read off the sequence around it — which command /// went out, which register is being watched, and what it is /// being watched for. trace: [trace_length]Trace, traced: usize, /// The CPU this belongs to, recovered from the field it is /// embedded in. pub inline fn getCPU(self: *Self) *CPU { return @alignCast(@fieldParentPtr("memory", self)); } /// How many banks of RAM a IIgs can have: `$00` to `$7f`, /// which is eight megabytes. Above that is where the expansion /// ROM, the Mega II and the machine's own ROM live, so it is /// not a limit anybody chose — it is where the address space /// stops being memory. pub const max_banks = 0x80; /// How many banks are on the board of a machine with no card /// in it. A ROM 01 IIgs shipped with these two and nothing /// else, which is 256K counting the Mega II's. pub const stock_banks = 2; /// Fits a memory expansion card, or takes one out. /// /// `banks` is how much fast RAM the machine has altogether, in /// sixty-four kilobyte banks, counting the two on the board. /// Nothing has to be told about it: the firmware sizes memory /// at power-on by writing to each bank in turn and reading it /// back, so RAM that answers is RAM the machine finds, and RAM /// that does not is where it stops looking. That is why there /// is no register here — a real card had none either. pub fn expand(self: *Self, wanted_banks: u16) !void { const wanted = @max(stock_banks, @min(max_banks, wanted_banks)); if (wanted == self.fast.len / bank_size) return; const fast = try self.gpa.alloc(u8, @as(usize, wanted) * bank_size); @memset(fast, 0); // What was there stays there: this is fitting a card, and // the machine's own memory does not change when one goes // in. @memcpy(fast[0..@min(fast.len, self.fast.len)], self.fast[0..@min(fast.len, self.fast.len)]); self.gpa.free(self.fast); self.fast = fast; } /// How many banks of fast RAM the machine has. pub fn banks(self: *const Self) u16 { return @intCast(self.fast.len / bank_size); } pub fn init(self: *Self, gpa: std.mem.Allocator) !void { const fast = try gpa.alloc(u8, 2 * bank_size); @memset(fast, 0); // The sound chip's RAM is its own and is reached only // through its four registers: it is not part of the // address space at all. const sound = try gpa.alloc(u8, bank_size); @memset(sound, 0); self.* = .{ .gpa = gpa, .fast = fast, .mega2 = undefined, .adb = .{}, .rtc = .{ // The machine's own idea of a second, which is // what the one-second interrupt counts in too, so // that the two agree about how fast time goes. .cycles_per_second = cycles_per_second, }, .iwm = .{ .drives = .{ // A disk turns at the speed a disk turns at, and // this machine counts its cycles nearly three // times as fast as the one the drive was designed // for. See disk2.Controller.turning. .turning = disk2.cycles_per_nibble * slow_cycle, }, // And the same for the other kind of drive, whose // bits go past twice as fast again and whose head // and spindle take a mechanical amount of time to // do anything. .disks35 = .{ .turning = disk35.cycles_per_nibble * slow_cycle, .stepping = disk35.cycles_per_step * slow_cycle, .spinning_up = disk35.cycles_per_spinup * slow_cycle, }, }, .scc = .{}, .doc = .{ .ram = sound }, .rom = &.{}, .rom_image = null, .vgc = .{}, .shadow = 0, .speed = speed_power_on, .motor_detected = 0, .rom_bank = false, .slot_rom = 0, .hard_disk = .{}, .interrupts = .{}, .blanked = false, .frames = 0, .unimplemented = @splat(0), .first_unimplemented = null, .trace = @splat(.{ .address = 0, .value = 0, .write = false }), .traced = 0, }; // The Mega II is a part of this machine rather than the // whole of one, so it cannot find the processor by walking // back from where it sits and has to be told. It is safe // to take the pointer here: the model is already the // processor's `memory` field, which is what getCPU walks // back to. self.mega2.init(null); self.mega2.setHost(self.getCPU()); } pub fn deinit(self: *Self) void { self.gpa.free(self.fast); self.gpa.free(self.doc.ram); if (self.rom.len != 0) self.gpa.free(self.rom); self.* = undefined; } /// Puts the switches back. RAM keeps what it held, as it does /// on any machine: that is what makes a reset a reset rather /// than a power cycle. pub fn reset(self: *Self) void { self.mega2.reset(); self.adb.reset(); self.rtc.reset(); self.iwm.reset(); self.scc.reset(); self.doc.reset(); self.vgc.reset(); self.shadow = 0; // Every bit but the power-on one, which says how the // machine was started and so must survive being reset. self.speed &= speed_power_on; self.motor_detected = 0; self.rom_bank = false; self.slot_rom = 0; self.slots.reset(self.getCPU().clock.cycles); // The interrupts go, but the frame does not: the video // keeps drawing across a reset because the beam does not // care what the processor is doing. self.interrupts = .{}; self.getCPU().irq = false; self.unimplemented = @splat(0); self.first_unimplemented = null; self.traced = 0; } /// How long the Mega II's video takes, which is where the /// vertical blanking interval comes from. /// /// The same 65 cycles a line and 262 lines a frame as every /// machine in the family, because it is the same video: the /// Mega II *is* an Apple IIe. They are the Mega II's cycles /// though, and the clock counts the processor's, so each one /// is worth `slow_cycle` of them. Getting that wrong is what /// made every timed wait in the firmware three times too /// short. pub const cycles_per_line = 65 * slow_cycle; pub const lines_per_frame = 262; pub const displayed_lines = 192; pub const cycles_per_frame = cycles_per_line * lines_per_frame; /// How long the beam spends off the bottom of the screen, /// which is the last seventy of the frame's 262 lines. pub const blanking_cycles = cycles_per_line * (lines_per_frame - displayed_lines); /// How many frames between quarter-second interrupts, and /// between the video controller's one-second ones. Sixty /// divided by sixteen is 3.75 Hz, which is the rate the /// Firmware Reference gives the first of them (Apple Computer, /// Inc., 1987). const frames_per_quarter_second = 16; const frames_per_second = 60; /// How many of the machine's cycles make a second, which is /// what anything measuring real time against the clock needs: /// the real-time clock, and the sound chip's scan rate. pub const cycles_per_second = cycles_per_frame * frames_per_second; /// Whether the video is in the vertical blanking interval. /// /// There is one notion of where the beam is rather than two /// that can disagree, and this brings it up to date before /// answering rather than keeping its own sum. That matters for /// more than tidiness: an access spends its cycles *before* /// the soft switch is answered, so a `$c019` read that sampled /// the state at the start of the access would report the beam /// up to three cycles behind where it is when the byte is /// actually put on the bus. pub fn blanking(self: *Self) bool { self.updateVideo(); return self.blanked; } /// Brings the frame and the interrupt line up to date with the /// clock. /// /// Called on every access, which is often enough for the same /// reason it is on a IIe: a processor cannot notice an /// interrupt without fetching an opcode, and fetching one is an /// access. So this is on the hottest path there is, and does no /// arithmetic it can avoid. inline fn updateVideo(self: *Self) void { const now = self.getCPU().clock.read(); // Still inside the line last counted: nothing the slow // half keeps can have changed, and this is the whole of // the work on nearly every access. The lower bound is // there so that a clock that has gone backwards — a // reset, a test — falls through and is counted afresh // rather than skipped until it catches up. if (now < self.next_line and now >= self.next_line -| cycles_per_line) return; self.countVideo(now); } /// The slow half of `updateVideo`: a new scan line has begun. fn countVideo(self: *Self, now: u64) void { const into = now % cycles_per_frame; self.blanked = into >= cycles_per_frame - blanking_cycles; // How many blanking intervals have *begun*, counted rather // than caught as an edge. Each frame's begins // `blanking_cycles` before the frame ends, so shifting the // clock forward by that much and dividing gives the count // outright. // // Counting beats catching here. The first version watched // for the edge, which is fine while the clock crawls // forward a cycle or three at a time and wrong the moment // anything moves it further: sixty frames' worth in one // step counted as one frame, and the interrupts that are // measured in frames came out sixty times too slow. // The scan-line interrupt, which is the only interrupt in // this machine whose source is a byte in memory rather than // a register. Each of the two hundred Super Hi-Res lines // has a control byte, and bit 6 of it asks for an interrupt // as the beam reaches that line — so what interrupts and // when is part of the picture, and a program can change it // by drawing. // // Counted the same way the frames below are, and for the // same reason. Walking back further than one frame would be // walking over lines already looked at. const reached = now / cycles_per_line; self.next_line = (reached + 1) * cycles_per_line; if (self.vgc.new_video & vgc_module.Vgc.super_hires != 0) { var line = @max(self.scan_lines, reached -| lines_per_frame); while (line < reached) : (line += 1) { const y: u16 = @intCast(line % lines_per_frame); if (superhires.interruptsOn(&self.mega2, y)) self.vgc.scan_line = true; } } // And the sound chip, brought up to date on the same // count. A frame would be too coarse a tick for it: the // machine's own note synthesiser runs an oscillator round // a 256-byte buffer as a clock, which at eight oscillators // is an interrupt every three milliseconds or so, and the // interrupt register can only hold one at a time — caught // up once a frame, five of them would arrive as one and // every envelope in the machine would move six times too // slowly. A line is 64 microseconds, which is finer than // anything the chip does, and this is the hot path, so it // is done on the line boundaries the video has counted // already rather than on every access. // // Unless somebody is recording, in which case the recorder // winds it forward instead, one output sample at a time. // That is finer again, and it has to be: a recorder handed // a chip that had already been wound forward a whole line // would get one sample's worth of sound per line and hold // the level in between, so a file that said 44.1 kHz would // really be at 15.7. if (reached != self.scan_lines) { if (self.sound) |recorder| recorder.pump(&self.doc, now) else self.doc.advance(now, cycles_per_second); } self.scan_lines = reached; const begun = (now + blanking_cycles) / cycles_per_frame; while (self.frames < begun) { self.frames += 1; self.interrupts.vbl = true; // The microcontroller asks the mouse what it has // counted. It does that on its own schedule and not // the video's, but a frame is the tick this model // already has and it is the right order of magnitude // — and counting it in frames means a machine run // faster or slower than life still moves its pointer // by the same amount per frame drawn. self.adb.pollMouse(); if (self.frames % frames_per_quarter_second == 0) self.interrupts.quarter_second = true; if (self.frames % frames_per_second == 0) self.vgc.one_second = true; } } /// Puts the interrupt line where the machine's state says it /// should be. /// /// On the hardware this is a wire and not an event: it follows /// the enables and the flags continuously, so enabling an /// interrupt that has already happened raises it *now* rather /// than at the next frame, and owning up to the last one drops /// it before the instruction has finished. So it is set at the /// end of every access rather than the beginning — the first /// version did it at the beginning, and then a write to the /// enable register was a whole access late taking effect. pub inline fn updateInterrupt(self: *Self) void { // The serial chip keeps its own time, and a byte arriving // on the network is an interrupt whether or not anything // touched the chip, so it is brought up to the clock // before it is asked. That is one compare when nothing // is due, which is nearly always. self.scc.advance(self.getCPU().clock.cycles); self.getCPU().irq = self.interrupts.asking() or self.vgc.interrupting() or self.doc.interrupting() or self.scc.interrupting() or self.adb.interrupting(self.mega2.keyWaiting()); } /// What the card was asked to do, done by the card. Both of /// its interfaces come out here: the one ProDOS calls and the /// SmartPort one beside it, which is the same card answering /// two different sets of questions about the same disks. fn runBlockCommand(self: *Self) u8 { return blockdevice.run(&self.hard_disk, self); } fn runSmartPort(self: *Self) u8 { return blockdevice.smartPort(&self.hard_disk, self); } /// One byte in or out of the machine's memory on the card's /// behalf. /// /// Bank nought, because that is the only address a ProDOS /// block device is given: the buffer is two bytes in the zero /// page and there is nowhere to put a bank. Shadowing is /// honoured, so a program reading a block into the text or /// graphics pages sees it appear on the screen, which it would /// not if only the fast copy were written. pub fn blockPut(self: *Self, at: u16, byte: u8) void { switch (self.decode(at, true)) { .ram => |target| { target.* = byte; self.shadowWrite(0, at, byte); }, .mega => |where| self.mega2.write(u8, where, byte), .rom, .soft, .nothing => {}, } } pub fn blockGet(self: *Self, at: u16) u8 { return switch (self.decode(at, false)) { .ram => |source| source.*, .rom => |byte| byte, .mega => |where| self.mega2.read(u8, where), .soft, .nothing => 0, }; } /// Puts a volume in the hard disk, or takes it out. A slot /// with nothing in it is a slot with no card in it: the page /// reads as nothing and the boot scan goes past. pub fn insertVolume(self: *Self, which: u1, volume: ?*blockdevice.Volume) void { self.hard_disk.volumes[which] = volume; } /// Fits a system ROM, working out for itself how the image is /// laid out because the file does not say. See iigsrom.zig. pub fn loadROM(self: *Self, image: []const u8) !void { const identified = try iigsrom.identify(image); const copy = try self.gpa.alloc(u8, image.len); @memcpy(copy, image); if (self.rom.len != 0) self.gpa.free(self.rom); self.rom = copy; self.rom_image = .{ .bytes = copy, .order = identified.order, .lowest_bank = identified.lowest_bank, }; self.rom_banks = @splat(null); for (identified.lowest_bank..0x100) |bank| { if (self.rom_image.?.bank(@intCast(bank))) |bytes| self.rom_banks[bank] = bytes.ptr; } self.firmware_rom = self.rom_image.?.firmware().ptr; } /// Copies bytes straight into memory without the processor /// being involved, for setting a machine up. pub fn loadProgram(self: *Self, location: u24, program: []const u8) !void { for (program, 0..) |byte, i| self.poke(location +% @as(u24, @intCast(i)), byte); } /// Where an address lands. const Where = union(enum) { /// Ordinary memory, and which byte of it. ram: *u8, /// Read-only memory. rom: u8, /// A soft switch this machine answers itself, and which /// one. soft: u8, /// A soft switch the Mega II answers, at the sixteen-bit /// address it knows it by. mega: u16, /// Nothing at all: a bank with nothing in it, which reads /// as whatever was last on the bus. Zero will do until /// there is something better to give it. nothing, }; /// The language card in banks `$00` and `$01`, which is the /// fast side's RAM behind the ROM, switched by the same three /// switches as the Mega II's card in banks `$e0` and `$e1`. /// /// There is one set of switches and not two. The Hardware /// Reference (Apple Computer, Inc., 1989a) says the State /// register, which carries the read-ROM and bank bits, is one /// of "two registers ... that exist in both the FPI and the /// Mega II ICs" and is "written at 1.024 MHz", which is to say /// written to both chips; and every `$c08x` access is an I/O /// cycle both chips see. GS/OS depends on it: its loader /// throws `$c08b` from bank `$00`, block-moves its code into /// `$e0/d000`, and then runs it there. This model kept a /// separate card for the fast side for a long while, and the /// ROM's interrupt manager, which writes the State register on /// every interrupt, moved the Mega II's card without moving /// this one — so GS/OS read the ROM where it had just put its /// code. The reason the two were ever separated is written up /// in `src/languagecard.zig`. fn languageCard(self: *Self, base: usize, within: u16, writing: bool) Where { if (!self.mega2.card_switches.reaches(writing)) { // The window is showing ROM, or it is a write the card // is not taking; either way the RAM is not reached and // this machine's own firmware is what is there. if (self.firmware_rom) |rom| return .{ .rom = rom[within] }; return .nothing; } if (within >= io_to + bank_window) return .{ .ram = &self.fast[base + within] }; const offset: u16 = if (self.mega2.card_switches.bank2) within - bank_window else within; return .{ .ram = &self.fast[base + offset] }; } /// What a fitted card answers in the slot ROM space, or null /// when no card there does and this machine's own firmware /// should. /// /// The seven pages from `$c100` to `$c7ff` are one slot each, /// gated by the Slot register through `cardAnswers`. Above /// them, `$c800` to `$cfff` is the shared *expansion* window, /// which belongs to whichever slot last claimed it — and only /// while that slot is still pointed at a card. Slot 0 is not a /// slot and slot 3 is not in the Slot register (the IIe's /// `SETSLOTC3ROM` governs it); `cardAnswers` excludes both. /// /// The window's writable half — a SCSI card's RAM buffer, an /// eighty-column card's screen — comes back as `.ram` so a /// write lands on it; everything else a card drives is `.rom`. fn slotCard(self: *Self, within: u16) ?Where { if (within < expansion_from) { if (!self.cardAnswers(within)) return null; return cardWhere(self.slots.page(within)); } _ = self.slots.expansion orelse return null; if (self.slots.windowTarget(within)) |ptr| return .{ .ram = ptr }; return cardWhere(self.slots.page(within)); } /// Turns a slot's `Answer` into this machine's `Where`: a ROM /// byte is a byte; a card whose page is registers rather than /// ROM floats, since its registers are among the device selects /// and not here; and nothing means the machine's own firmware /// answers instead. fn cardWhere(answer: slot_module.Answer) ?Where { return switch (answer) { .rom => |b| .{ .rom = b.* }, .registers => .nothing, .none => null, }; } pub fn fitScsi(self: *Self, slot: u3, firmware: []const u8) !void { if (firmware.len != slot_module.Card.Scsi.rom_size) return error.WrongSize; try self.slots.fit(slot, .{ .scsi = .{ .rom = firmware[0..slot_module.Card.Scsi.rom_size] } }); // The bus holds pointers into the card, and `fit` moved it // by value, so the pointers are fixed up where it landed. self.slots.cards[slot].scsi.rewire(); } pub fn scsiCard(self: *Self, slot: u3) ?*slot_module.Card.Scsi { if (self.slots.cards[slot] == .scsi) return &self.slots.cards[slot].scsi; return null; } /// Fits an Uthernet II, the WIZnet W5100 Ethernet card. A IIgs /// runs Marinetti over one exactly as a IIe runs IP65. pub fn fitUthernet(self: *Self, slot: u3) void { self.slots.fit(slot, .{ .uthernet = .{} }) catch {}; } /// The Uthernet II's W5100, for the session's host end to drive. pub inline fn ethernetChip(self: *Self) ?*w5100.W5100 { const slot = self.slots.first(.uthernet) orelse return null; return &self.slots.cards[slot].uthernet.chip; } pub fn fitCs8900(self: *Self, slot: u3) void { self.slots.fit(slot, .{ .cs8900 = .{} }) catch {}; } pub inline fn cs8900Chip(self: *Self) ?*cs8900.CS8900 { const slot = self.slots.first(.cs8900) orelse return null; return &self.slots.cards[slot].cs8900.chip; } fn claimWindow(self: *Self, bank: u8, within: u16) void { // Only accesses in the banks that can see the slot pages // claim the window; everywhere else those addresses are RAM. if (bank != 0x00 and bank != 0x01 and bank != slow_bank and bank != slow_bank + 1) return; // Only a card's page claims the window. A slot the Slot // register points at this machine's own firmware is internal // ROM with no card behind it to assert I/O SELECT, so // touching it must not steal the window from a card that has // it -- which is what `cardAnswers` decides, per slot. The // one thing an internal page must still do is release the // window at $cfff, so that is allowed through too. self.slots.claim(within, self.cardAnswers(within) or within == 0xcfff, false); } fn cardAnswers(self: *const Self, within: u16) bool { if (within >= expansion_from) return false; const slot: u3 = @truncate(within >> 8); if (slot == 0 or slot == 3) return false; return self.slot_rom & (@as(u8, 1) << slot) != 0; } /// What the built-in hard disk answers with in slot 7's page, /// behind an empty seventh slot. /// /// This runs after `slotCard`: a card fitted to slot 7 answers /// first, and only when none is does the machine's own block /// device — its page here, its registers below, and its /// firmware ours rather than Apple's, because what a ProDOS /// block device answers to is published. /// /// An empty slot is still empty. Without a volume the page /// reads as nothing, which is what a slot with no card in it /// gives, and the boot scan passes over it. fn cardPage(self: *const Self, within: u16) Where { if (!self.hard_disk.fitted()) return .nothing; if (within < block_rom_base or within >= block_rom_base + 0x100) return .nothing; return .{ .rom = block_firmware[@as(u8, @truncate(within))] }; } /// Which of the Mega II's two halves an access reaches. /// /// With the bank latch set — bit 0 of the New-Video register — /// the low bit of the bank address says which, and the old /// soft switches have no vote. With it clear the Mega II /// ignores the bank bit entirely and its own switches decide, /// exactly as on a IIe. /// /// The Hardware Reference (Apple Computer, Inc., 1989a) states /// the rule once and applies it to both ways of reaching the /// slow side: "if shadowing is enabled or the software is /// addressing bank $E0 or $E1, an odd-numbered bank address /// will access the Mega II auxiliary memory automatically, /// without using the soft switches ... otherwise, the Mega II /// ignores the bank bit". So one function serves the direct /// banks and the shadowed writes alike, which is the point of /// having it. /// /// Note how carefully that sentence is worded: it says what an /// *odd* bank does and claims nothing about an even one. The /// first version here read it as a rule about the bank's low /// bit either way, so with the latch set, bank `$00` was the /// main half whatever the switches said — and eighty-column /// text became impossible, because the firmware writes it by /// toggling `PAGE2` between halves while writing to `$0400` in /// bank `$00`. The machine gave it away: nine hundred and /// seventy-four characters in the main half and not one in the /// auxiliary, which is a whole screen of eighty-column text /// with every other column thrown away. fn megaHalf(self: *Self, bank: u8, within: u16, writing: bool) bool { // An *odd* bank, with the latch set, is the auxiliary half // outright. That is the whole of what the latch does, and // the manual is careful to claim no more than that. if (bank & 1 != 0 and self.vgc.new_video & bank_latch != 0) return true; // Everything else asks the Mega II's own switches, exactly // as a IIe would: an even bank always, and an odd one when // the latch is clear. return self.mega2.auxiliaryFor(within, writing); } /// Whether a write here is duplicated into the Mega II. /// /// Reads are not: the Hardware Reference is explicit that "read /// instructions access the high-speed shadowed bank" (Apple /// Computer, Inc., 1989), and that only writes pay for the /// trip. Shadowing exists so that a program written for a IIe /// can keep putting its display in bank $00 and still be seen, /// while everything it reads back comes at full speed from the /// fast side. fn shadowed(self: *const Self, bank: u8, within: u16) bool { // Banks $00 and $01 are always shadow-enabled. The rest // are only when the Speed register says every bank is. if (bank > 0x01 and self.speed & shadow_every_bank == 0) return false; // The odd bank is the auxiliary one — the manual writes // "all auxiliary (odd) banks" — and this is the FPI's // decision, made from the bank number it can see, rather // than the Mega II's about which half to land in. const odd = bank & 1 != 0; const inhibit = self.shadow; // Bit 4 takes the Hi-Res pages away from the odd banks // alone and leaves the even banks' alone. const hires_here = !odd or inhibit & inhibit_auxiliary_hires == 0; // Under $6000 the Super Hi-Res buffer lies over the two // Hi-Res pages, and the two paths are separate: either one // enabled is enough to shadow the write. const super_here = odd and inhibit & inhibit_super_hires == 0; return switch (within) { // Text page 1, which is not only for old programs: // the Control Panel writes here too. text_1_from...text_1_to - 1 => inhibit & inhibit_text_1 == 0, // Text page 2, which the original machine could not // shadow at all — the bit is on the 1 MB board only. text_1_to...text_2_to - 1 => inhibit & inhibit_text_2 == 0, hires_1_from...hires_1_to - 1 => super_here or (hires_here and inhibit & inhibit_hires_1 == 0), hires_1_to...hires_2_to - 1 => super_here or (hires_here and inhibit & inhibit_hires_2 == 0), // The top two-thirds of the Super Hi-Res buffer, with // no Hi-Res page underneath it. hires_2_to...super_hires_to - 1 => super_here, else => false, }; } /// Puts a shadowed write through to the Mega II as well. /// /// Every program written before this machine existed puts its /// display in bank $00, and the screen is in bank $e0; this is /// the wire between them. Without it a IIgs shows nothing at /// all, which is exactly how the want of it was found — the /// firmware wrote its startup text into bank $00 and the screen /// stayed empty through eight million instructions. fn shadowWrite(self: *Self, bank: u8, within: u16, value: u8) void { if (!self.shadowed(bank, within)) return; const auxiliary = self.megaHalf(bank, within, true); if (self.mega2.halfTarget(auxiliary, within, true)) |byte| byte.* = value; } /// Works out where an address lands, without touching /// anything: `peek`, `read` and `write` all go through this so /// that there is one map rather than three. fn decode(self: *Self, address: u24, writing: bool) Where { const bank: u8 = @truncate(address >> 16); const within: u16 = @truncate(address); // The ROM, in whichever banks the image turned out to // hold. if (self.rom_banks[bank]) |base| return .{ .rom = base[within] }; switch (bank) { // The fast side. Soft switches answer in the same // place they do on a IIe, and above them is the // language card window, which at power-on is the ROM — // which is how the reset vector is found at all. 0x00, 0x01 => { // Which of the two fast banks the access really // reaches, which is not always the one the address // names. // // "For standard Apple II programs, banks $00 and // $01 take on the features of the main and // auxiliary banks", says the Hardware Reference // (Apple Computer, Inc., 1989a), and lists text // Page 1 and Page 2 and the Hi-Res pages as being // "of both banks". It has to work that way: a // program written for a IIe reaches the auxiliary // sixty-four kilobytes by setting RAMRD or RAMWRT // and then addressing bank nought, and there is // nowhere else for that to land. So an even bank // asks the same switches a IIe would — RAMRD, // RAMWRT, ALTZP, and 80STORE with PAGE2 over the // display pages — and this is the Mega II's own // answer to that question, because there should be // one rule and not two. // // An odd bank is the auxiliary one outright. It has // to be: native software is handed bank $01 by the // Memory Manager and uses it as ordinary memory, // with the old switches in whatever state whatever // ran last left them. // // This was missing for a long time and nothing // noticed, because everything that had been run // either stayed in one bank or only wrote to the // display, where shadowing was already picking the // right half of the Mega II. What found it was // ProDOS 8 counting its memory: it turns on write // to auxiliary, puts a byte at $0800 and reads it // back, and with the switches ignored that byte // landed on top of the code it had just loaded. const auxiliary = bank & 1 != 0 or self.mega2.auxiliaryFor(within, writing); const base: usize = if (auxiliary) bank_size else 0; // The interrupt ROM comes first, because it is // there whatever the rest of the bank is doing — // which is the whole point of it. Without it the // machine's own interrupt handler jumps into the // switch page and reads the paddle trigger as an // instruction, and the first thing that ever asked // it to was the mouse. if (!writing and within >= interrupt_rom_from and within < interrupt_rom_to) { if (self.firmware_rom) |rom| return .{ .rom = rom[within] }; } // With the I/O and language-card space inhibited // the bank is sixty-four kilobytes of RAM and // nothing else, which is what bit 6 of the Shadow // register is for. if (self.shadow & inhibit_io_language_card != 0) return .{ .ram = &self.fast[base + within] }; if (within < switches_from) return .{ .ram = &self.fast[base + within] }; if (within < switches_to) return switchPage(@truncate(within)); // $c100 to $cfff is slot ROM and comes from this // machine's own ROM unless a card is selected. // // The slot pages used to fall through to the soft // switch case below, where truncating the address // to eight bits turned $c123 into switch $23 and // quietly corrupted the tally that the whole of // this model's progress is measured by. if (within < io_to) { if (self.slotCard(within)) |w| return w; if (self.cardAnswers(within)) return self.cardPage(within); if (self.firmware_rom) |rom| return .{ .rom = rom[within] }; return .nothing; } return self.languageCard(base, within, writing); }, // The Mega II's own two banks: its 128K, its video, // its language card, and the switch page. // // Which of its two halves an address reaches is the // bank latch's business — bit 0 of the New-Video // register. Set, the low bit of the bank address says // which, and RAMRD and the rest have no say. Clear, // the Mega II ignores the bank bit and its own // switches decide, which is `.mega`: its ordinary read // and write, exactly as a IIe would do it. slow_bank, slow_bank + 1 => { if (within >= switches_from and within < switches_to) return switchPage(@truncate(within)); // Slot ROM, from this machine's own ROM. if (within >= switches_to and within < io_to) { if (self.slotCard(within)) |w| return w; if (self.cardAnswers(within)) return self.cardPage(within); if (self.firmware_rom) |rom| return .{ .rom = rom[within] }; return .nothing; } // Which half, and this is the whole of the seam. const auxiliary = self.megaHalf(bank, within, writing); if (self.mega2.halfTarget(auxiliary, within, writing)) |byte| return .{ .ram = byte }; // Not RAM at the moment: the language card is // reading ROM, and on this machine that is this // machine's ROM. if (within >= io_to) { if (self.firmware_rom) |rom| return .{ .rom = rom[within] }; } return .nothing; }, // A machine with a memory expansion card has fast RAM // up here, and one without has nothing. else => { const at = @as(usize, bank) * bank_size + within; if (at < self.fast.len) return .{ .ram = &self.fast[at] }; return .nothing; }, } } /// Who answers a given switch: this machine, the Mega II /// inside it, or nobody yet. /// /// The list is of what to *send* to the Mega II rather than /// what to keep from it, and deliberately so. The switch page /// is not divided neatly between old and new: a IIgs took a /// good many addresses a IIe was not using and gave them to /// hardware a IIe never had, so `$c027` is the keyboard /// microcontroller here and nothing at all there, and `$c034` /// is the border colour. Handing those to a IIe would get an /// answer, and a made-up one, which is worse than getting /// none: an unanswered switch is counted and shows up in the /// report as work to do, while a wrong answer is silent. /// /// So only the ranges a IIe really owns go across, and /// everything else stays on the list until it is built. fn megaAnswers(which: u8) bool { return switch (which) { // The keyboard, the switch reads, and the eighty // column and character set flags. Everything a IIe // reads at $c000 to $c01f, minus vertical blanking, // which this machine answers below — the two agree, // but the reason they agree is worth keeping written // down where the IIgs registers are. 0x00...0x18, 0x1a...0x1f => true, // The speaker. Its neighbours are not a IIe's: $c031 // is the disk interface here, $c033 and $c034 the // clock and the border, $c035 to $c037 the shadow, // speed and DMA registers. 0x30 => true, // The video mode switches, the buttons and paddles and // their timer, and the language card. A IIgs left all // of these where they were. 0x50...0x5f, 0x60...0x67, 0x70...0x7f, 0x80...0x8f => true, else => false, }; } /// Where a soft switch is answered, which is not always the /// same chip. /// /// Everything a IIe had is the Mega II's wherever it is /// touched, the language card's sixteen switches included: /// there is one card state, and `$c083` thrown in bank `$00` /// moves it exactly as `$c083` thrown in bank `$e1` does. The /// rest of the page is this machine's own. fn switchPage(which: u8) Where { if (megaAnswers(which)) return .{ .mega = switches_from | @as(u16, which) }; return .{ .soft = which }; } /// Answers a soft switch, or writes down that it could not. /// /// The ones here are the ones the Hardware Reference (Apple /// Computer, Inc., 1989) sets out plainly and the firmware /// asked for first. Most are kept rather than acted on: a /// register that remembers what was written is not the /// hardware, but it is what a program checking that its /// configuration took will accept, and it is a great deal /// closer than zero. The State register at `$c068`: the IIe's /// memory switches gathered into one byte, so that a program /// can save and restore the lot without touching eight /// addresses. From the top: ALTZP, PAGE2, RAMRD, RAMWRT, RDROM, /// LCBNK2, ROMBANK, INTCXROM (Apple Computer, Inc., 1989a, /// Table 3-2). /// /// These are the switches themselves and not a copy of them. /// It was a stored byte for a long while, which read back what /// had been written and moved nothing — harmless only for as /// long as nothing in banks $00 and $01 looked at the switches /// at all. The ROM's own AUXMOVE is what found it: on this /// machine that routine does not shuffle switches a byte at a /// time the way a IIe's does, it uses the 65816's block move /// between banks $00 and $01 — and before it does, it reads /// this register, clears RAMRD and RAMWRT with `AND #$cf`, /// writes it back, and puts it as it was afterwards. It has to: /// with the auxiliary bank read-enabled the move would take its /// source from the bank it was meant to be filling. A register /// that remembers instead of acting leaves those two switches /// where they were, and AUXMOVE quietly copies a bank onto /// itself. const state_altzp: u8 = 0x80; const state_page2: u8 = 0x40; const state_ramrd: u8 = 0x20; const state_ramwrt: u8 = 0x10; const state_read_rom: u8 = 0x08; const state_bank2: u8 = 0x04; const state_rom_bank: u8 = 0x02; const state_internal_rom: u8 = 0x01; pub fn state(self: *const Self) u8 { const mega2 = &self.mega2; var value: u8 = 0; if (mega2.altzp) value |= state_altzp; if (mega2.page2) value |= state_page2; if (mega2.ramrd) value |= state_ramrd; if (mega2.ramwrt) value |= state_ramwrt; // The language card the other way up: this bit is set when // the window is reading *ROM*, which is when the card is // not reading its own RAM. if (!mega2.card_switches.read_ram) value |= state_read_rom; if (mega2.card_switches.bank2) value |= state_bank2; if (self.rom_bank) value |= state_rom_bank; if (mega2.intcxrom) value |= state_internal_rom; return value; } fn setState(self: *Self, value: u8) void { const mega2 = &self.mega2; mega2.altzp = value & state_altzp != 0; mega2.page2 = value & state_page2 != 0; mega2.ramrd = value & state_ramrd != 0; mega2.ramwrt = value & state_ramwrt != 0; mega2.card_switches.read_ram = value & state_read_rom == 0; mega2.card_switches.bank2 = value & state_bank2 != 0; self.rom_bank = value & state_rom_bank != 0; mega2.intcxrom = value & state_internal_rom != 0; } /// What the Interrupt Flag register at `$c046` reads. /// /// From the top: the mouse button now, the mouse button as it /// was on the last read, the state of AN3, and then five /// flags — a quarter-second tick, vertical blanking, the Mega /// II's mouse switch and its movement, and whether the system /// IRQ line is asserted at all. /// /// The four in the middle are this machine's own, and are /// reported in exactly the positions `$c041` enables them in. /// /// The two mouse-button bits are the Mega II's, and they read /// as clear. The mouse this machine has is on the desktop bus /// and is answered for at `$c024` and `$c027`, which is where /// the firmware looks for it: the handler at `$feb948` masks /// what it reads here down to the quarter-second tick and /// vertical blanking and never dispatches on the Mega II's /// mouse at all. Setting bits nothing owns up to would be an /// interrupt that could not be cleared. /// /// AN3 comes off the Mega II, which is a real Apple IIe and /// tracks the annunciator like one. Which way round the bit /// reads took some settling, because the two manuals name the /// same two addresses in opposite ways — the IIe Technical /// Reference's assembler listing (Apple Computer, Inc., 1985b) /// has `SETAN3 EQU $C05E` and the IIgs Hardware Reference's /// annunciator table (Apple Computer, Inc., 1989a) has `$C05E` /// as `CLRAN3`. Three things agree against the IIe listing. The /// other three annunciators are all set at the odd address and /// cleared at the even one, so `$c05f` setting AN3 is the /// pattern rather than the exception. The IIgs manual, which is /// the one that documents *this* register, says so. And both /// machines' firmware touches `$c05f` while starting up, which /// is a machine putting the annunciator in the state it wants — /// and the state it wants is not double resolution. /// /// So AN3 is asserted when double resolution is *off*, which /// is why this reads the Mega II's flag inverted. /// Bit 5 of the Interrupt Flag register: not an interrupt at /// all, but the state of the third annunciator, which is where /// this machine keeps it. const an3_bit: u8 = 0x20; /// Tells the Mega II what colours to draw the text in. /// /// A IIe's text has no colour of its own: it is dots, and what a /// composite monitor makes of them. A IIgs's does -- "the /// capability of colored text on a colored background on an RGB /// monitor". "The Screen Color register is an 8-bit /// dual-function register. First, the most significant 4 bits /// determine the text color. Second, the least significant 4 /// bits determine the background color" (Apple Computer, Inc., /// 1989a, p. 81, and Table 4-11), and the Control Panel's colour /// settings are this register, written from battery RAM on the /// way up: white on medium blue, which is what a IIgs looks /// like. /// /// The register is the VGC's and the text is the Mega II's, so /// this is called whenever either register changes and hands /// the pair across -- or nothing, when bit 7 of the /// Monochrome/Color register says "video displays in /// black-and-white" (Table 4-12, p. 83), since no colour is what /// black and white means and the text then falls back to dots. fn giveTextColours(self: *Self) void { self.mega2.given_text_colours = if (self.vgc.monochrome) null else .{ .foreground = self.vgc.text_colour, .background = self.vgc.background_colour, }; } /// What colour the border round the display is, as a dot. /// /// The low four bits of `$c034` "determine the border color" /// and the high four are the clock's control bits (Apple /// Computer, Inc., 1989a, Table 4-12, p. 82), which is why the /// value lives on the clock: one register, two things, and a /// program setting either must not disturb the other -- which /// is what the manual's warning to use only a read-modify-write /// on this register is about. /// /// The sixteen are the machine's own, the same set text and /// low resolution draw in, rather than an entry in a Super /// Hi-Res palette: a palette is per scan line and belongs to /// the picture, and the border is not in the picture. pub fn borderColour(self: *const Self) video.Rgb { return video.palette[self.rtc.border]; } fn interruptFlags(self: *Self) u8 { var value = self.interrupts.pending(); if (!self.mega2.double_hires) value |= an3_bit; if (self.getCPU().irq) value |= 0x01; return value; } /// The Speed register's motor-on address detectors, which /// watch every access to the slot switches for a Disk II /// motor being turned on or off: `$c0n9` and `$c0n8` for the /// slot's sixteen at `$c0n0`, "for example, when bit 1 is 1, /// the FPI switches to 1.024 MHz when address $C0D9 is /// accessed, and returns to 2.8 MHz following a $C0D8 access" /// (Apple Computer, Inc., 1989a, Table 2-2). Whether the slot /// holds a Disk II is not the detector's business; whether /// the machine slows for it is the register's. fn detectMotor(self: *Self, which: u8) void { switch (which) { 0xc8, 0xc9, 0xd8, 0xd9, 0xe8, 0xe9, 0xf8, 0xf9 => {}, else => return, } const slot: u3 = @intCast((which >> 4) - 0x0c); const bit = @as(u8, 1) << slot; if (which & 1 != 0) { self.motor_detected |= bit; } else { self.motor_detected &= ~bit; } } fn softSwitch(self: *Self, which: u8, value: ?u8) u8 { self.detectMotor(which); // A card's sixteen device selects are $C080 + slot*16 and // up, so $c090-$c0ff belong to slots 1 to 7. A fitted card // whose slot the Slot register points at a card takes them, // ahead of whatever built-in of this machine's shares the // range (the disk port at slot 6, the hard disk at slot 7). // With the register at its power-on $80 only slot 7 is a // card, so every built-in keeps answering as it did. if (which >= 0x90) { const slot: u3 = @truncate(which >> 4); if (slot != 3 and self.slot_rom & (@as(u8, 1) << slot) != 0 and self.slots.cards[slot] != .empty) return self.slots.access(self, which, value != null, value orelse 0) orelse 0; } switch (which) { // The Apple Desktop Bus. The mouse register hands over // one coordinate at a time; the modifier keys are the // keys held down at this instant rather than a latch; // the command register takes commands and gives back // whatever the microcontroller has to say, which is // nothing yet; and the status register answers for all // of them, with the keyboard's bit coming from the // Mega II, because that is where the keyboard is. // The hard disk's registers. Reading the first of // them is what makes the transfer happen: the card // moves the five hundred and twelve bytes itself, as // a real one does with its own hardware, rather than // the processor copying them a byte at a time. block_switch_base...block_switch_base + 7 => { if (!self.hard_disk.fitted()) return 0; const register: blockdevice.Register = @enumFromInt(which - block_switch_base); if (value) |v| { self.hard_disk.write(register, v); return v; } switch (register) { .execute => return self.runBlockCommand(), .smartport => return self.runSmartPort(), else => return self.hard_disk.read(register), } }, 0x24 => if (value == null) return self.adb.mouseByte(), 0x25 => if (value) |v| { self.adb.modifiers = v; return v; } else return self.adb.modifiers, 0x26 => if (value) |v| { self.adb.command(v); return v; } else return self.adb.response(), 0x27 => if (value) |v| { self.adb.setStatus(v); return v; } else return self.adb.status(self.mega2.keyWaiting()), // The sound chip, through the four registers its // glue presents. Its sixty-four kilobytes are not part // of the address space: they are reached a byte at a // time through $c03d, and reads of that lag by one. 0x3c => if (value) |v| { self.doc.setControl(v); return v; } else return self.doc.control(), 0x3d => if (value) |v| { self.doc.writeData(v); return v; } else return self.doc.readData(), 0x3e => if (value) |v| { self.doc.setPointerLow(v); return v; } else return self.doc.pointerLow(), 0x3f => if (value) |v| { self.doc.setPointerHigh(v); return v; } else return self.doc.pointerHigh(), // The disk port. Every one of its sixteen addresses // throws a switch, and which register the access then // reaches is decided by two of those switches. 0xe0...0xef => return self.iwm.access( @truncate(which), value != null, value orelse 0, self.getCPU().clock.read(), ), // The serial ports, which are two channels of one // Zilog 8530. Four addresses reach thirty-one // registers, and the two bits below are the chip's own // select pins: the low one picks the channel and the // one above it picks data over command. 0x38...0x3b => return self.scc.access( @truncate(which), value != null, value orelse 0, self.getCPU().clock.cycles, ), // The clock chip: one byte at a time through a data // register and a control register, with the border // colour sharing the low nibble of the control one // because that is where the hardware put it. 0x33 => if (value) |v| { self.rtc.data = v; return v; } else return self.rtc.data, 0x34 => if (value) |v| { // Bring the clock up to date before it is asked // anything, since it counts the machine's own // cycles and nothing else has moved it. self.rtc.tick(self.getCPU().clock.read()); self.rtc.setControl(v); return v; } else return self.rtc.control(), // Read vertical blanking, and the bar in RDVBLBAR is // the whole of it: the bit is set while the beam is // drawing and clear while it is not. The same way // round as a IIe and the opposite of a IIc. 0x19 => if (value == null) return if (self.blanking()) 0x00 else 0x80, // The video controller's registers. Writing one here // stores it and reads it back, which is what the // firmware's self-test and the Control Panel need; the // monochrome and screen-colour registers below are also // handed to the Mega II, so its text draws in the right // colours. The drawing itself is elsewhere: Super // Hi-Res and the legacy modes are rendered from video // memory in `superhires.zig` and `video.zig`. 0x21 => if (value) |v| { self.vgc.setMonochromeRegister(v); self.giveTextColours(); return v; } else return self.vgc.monochromeRegister(), 0x22 => if (value) |v| { self.vgc.setScreenColour(v); self.giveTextColours(); return v; } else return self.vgc.screenColour(), // The byte above the New-Video register is nobody's. // The Firmware Reference's soft-switch listing (Apple // Computer, Inc., 1987, Appendix E) has `$c02a` as // "Reserved for future system expansion", the Hardware // Reference does not mention it, and no ROM names it. // What reaches it is GS/OS, which reads and writes // `$c029` with a sixteen-bit accumulator — `LDA $C029` // at `$00/74f7`, `STA $C029` at `$00/7564` — so that // this byte comes along as the high half: read, // pushed, pulled, and written back as it was, around a // routine that turns on linear addressing to draw into // the Super Hi-Res buffer. A real machine has nothing // here and puts the floating bus on the read, which // GS/OS then writes straight back. So it is answered // rather than counted as a switch this machine lacks, // because the machine never had one. 0x2a => return 0, 0x29 => if (value) |v| { self.vgc.new_video = v; return v; } else return self.vgc.new_video, 0x2b => if (value) |v| { self.vgc.setLanguageSelect(v); return v; } else return self.vgc.languageSelect(), // The video controller's two interrupts. Reading gives // both status bits and both enables; writing reaches // the enables alone, the status bits being the // hardware's to set. 0x23 => if (value) |v| { self.vgc.setInterruptRegister(v); return v; } else return self.vgc.interruptRegister(), // And clearing them, which is a *different* address and // takes a zero in the bit rather than a one. 0x32 => if (value) |v| { self.vgc.clearInterrupts(v); return v; }, 0x35 => if (value) |v| { self.shadow = v; return v; } else return self.shadow, 0x36 => if (value) |v| { self.speed = v; return v; } else return self.speed, 0x68 => if (value) |v| { self.setState(v); return v; } else return self.state(), 0x2d => if (value) |v| { self.slot_rom = v; return v; } else return self.slot_rom, // The Disk Interface register, which is a register of // the machine rather than of the chip but configures // the chip, so it is kept with it. 0x31 => if (value) |v| { self.iwm.setDiskRegister(v); return v; } else return self.iwm.diskRegister(), // Which interrupts are allowed to ask for the line. 0x41 => if (value) |v| { self.interrupts.enable = v; return v; } else return self.interrupts.enable, // The Interrupt Flag register: what has happened. // Writing to it does nothing, because owning up to an // interrupt is done at the two addresses below rather // than by putting a bit back here. 0x46 => if (value == null) return self.interruptFlags(), // Owning up. The first takes away the frame-timed pair // — vertical blanking and the quarter-second tick, // which the Firmware Reference (Apple Computer, Inc., // 1987) clears together because they are the same // counter — and the second the Mega II mouse's two. 0x47 => { self.interrupts.vbl = false; self.interrupts.quarter_second = false; return 0; }, 0x48 => { self.interrupts.mouse_switch = false; self.interrupts.mouse_move = false; return 0; }, else => {}, } self.unimplemented[which] +|= 1; if (self.first_unimplemented == null) self.first_unimplemented = io_from | @as(u16, which); self.trace[self.traced % trace_length] = .{ .address = io_from | @as(u16, which), .value = value orelse 0, .write = value != null, }; self.traced +|= 1; // What a real machine puts on the bus for an address // nothing answers is whatever went past last. Zero is a // placeholder, and a wrong one, but it is a placeholder // for something this does not have rather than a guess at // something it does. return 0; } /// Reads a byte without the processor being involved: no cycle /// spent, nothing logged, no switch thrown. pub fn peek(self: *const Self, address: u24) u8 { // Casting away const: `decode` does not modify anything, // but it hands back a pointer that `write` needs to be // able to write through. const mutable: *Self = @constCast(self); return switch (mutable.decode(address, false)) { .ram => |byte| byte.*, .rom => |byte| byte, // Peeking must never throw a switch, so it reports // nothing rather than asking — of either machine. .soft, .mega, .nothing => 0, }; } /// Where an interrupt vector comes from, which is not always /// where a data read of the same address would go. /// /// The processor pulls every vector from bank zero, and the /// top of bank zero is the language card, which an operating /// system switches to RAM. The Firmware Reference (Apple /// Computer, Inc., 1987, Chapter 8) says what the machine does /// about that: "If I/O shadowing is on, the vectors contained /// in ROM are always used by the 65C816, regardless of the /// language-card settings. This allows you to run native-mode /// code with interrupts enabled in old applications." With /// shadowing off "RAM will be addressed in the memory space of /// bank $00 in the area of $FFE0-$FFFF", and whoever turned it /// off "must copy the ROM vectors from $FFEE to $FFFF and the /// code from $C071 to $C07F into RAM at the same locations /// before enabling interrupts." /// /// The 65816 marks the two cycles with its VPB line, which is /// what lets the FPI tell a vector from a data read at the /// same address, and is why the memory model is told the kind /// of cycle at all. GS/OS is what found it: its loader /// switches the language card to RAM with interrupts enabled /// and block-moves into banks $e0 and $e1, and a vertical /// blanking interrupt in the middle of the move pulled its /// vector from RAM nothing had written yet and the machine /// went to $00/0000. fn decodeVector(self: *Self, address: u24) Where { const bank: u8 = @truncate(address >> 16); const within: u16 = @truncate(address); if (bank == 0 and self.shadow & inhibit_io_language_card == 0) { if (self.firmware_rom) |rom| return .{ .rom = rom[within] }; } return self.decode(address, false); } /// Writes a byte without the processor being involved. pub fn poke(self: *Self, address: u24, value: u8) void { switch (self.decode(address, true)) { .ram => |byte| byte.* = value, .rom, .soft, .mega, .nothing => {}, } } /// How many of the processor's cycles an access costs. /// /// One, unless it has to reach across to the slow side, and /// then three. The Hardware Reference (Apple Computer, Inc., /// 1989) is precise about which is which, and the exceptions /// are the interesting part: /// /// - Everything in banks `$e0` and `$e1` is the Mega II's /// and is slow. /// - The I/O space is slow, and so is fetching from the slot /// ROM at `$c100` to `$cfff`. /// - But the three registers inside the FPI itself — the /// shadow, speed and DMA registers — are fast, because the /// processor never leaves its own side of the machine to /// reach them. /// - And reading the interrupt ROM at `$c071` to `$c07f` /// does not slow the system either. /// - The state register and the slot ROM select register /// live in both chips at once, and so are written slowly /// and read quickly. /// /// With the speed register asking for 1.024 MHz, the whole /// machine is slow and all of this is moot — and so it is /// while a motor-on detector the register has enabled has seen /// its drive turned on, which is how a Disk II and the /// software written for its speed are kept working: Table 2-2 /// of the Hardware Reference has it that "drives designed for /// previous Apple II computers will function as Apple IIGS /// peripherals only if the system speed is changed to 1.024 /// MHz before disk access is attempted". /// What one access to the slow side of the machine costs, /// which is not a constant. /// /// "If a single (8-bit) slow I/O read or write cycle is /// perfectly synchronized, it takes nearly three fast cycles /// to complete... If either a single or double slow cycle is /// not synchronized, the maximum delay for synchronization is /// one extra slow cycle, adding the equivalent of three fast /// cycles to the count" (Apple Computer, Inc., 1989a, p. 25). /// /// The mechanism behind that sentence is simply that the /// processor is held until the Mega II is ready to begin a /// cycle: an access that arrives on a boundary pays for the /// slow cycle and nothing else, and one that arrives in the /// middle of one waits out the rest of it first. So the cost /// is the distance to the next boundary plus a slow cycle, /// which is between three and five fast cycles here. /// /// **The phase is discrete here and continuous on a real /// machine**, and that is worth being plain about. A IIgs runs /// 2.8 MHz against 1.024, a ratio of 2.73, so its phase drifts /// through every value; this model uses a whole 3 so that the /// processor and the video agree about how long a frame is -- /// see `slow_cycle` -- and a whole 3 gives the phase only /// three values. What comes out is the *shape* of the /// variation, an access costing three, four or five cycles /// depending on when it arrives, rather than the exact /// sequence a particular machine would produce. Apple's own /// worst case is a round +3, being "up to one slow cycle" /// stated conservatively; the largest wait an integer 3:1 /// ratio can produce is 2. fn slowAccess(self: *Self) u8 { const now = self.getCPU().clock.cycles; const into: u8 = @intCast(now % slow_cycle); const wait: u8 = if (into == 0) 0 else slow_cycle - into; return wait + slow_cycle; } fn cost(self: *Self, address: u24, writing: bool) u8 { if (self.speed & speed_fast == 0) return slow_cycle; if (self.motor_detected & self.speed & motor_detect_bits != 0) return slow_cycle; const bank: u8 = @truncate(address >> 16); const within: u16 = @truncate(address); if (bank == slow_bank or bank == slow_bank + 1) return self.slowAccess(); // A shadowed write has to be made twice, and the second // one is on the far side of the machine. The manual says // so outright: "only write instructions to the video // locations require the system to operate at 1.024 MHz". if (writing and self.shadowed(bank, within)) return self.slowAccess(); if (bank != 0x00 and bank != 0x01) return 1; if (within < io_from or within >= io_to) return 1; // And with the I/O space inhibited there is nothing slow // in this bank at all: it is RAM from end to end. if (self.shadow & inhibit_io_language_card != 0) return 1; return switch (@as(u8, @truncate(within))) { // The FPI's own registers, on the fast side of the // machine. Only meaningful below $c100, which the // range check above has already established. 0x35, 0x36, 0x37 => if (within < switches_to) 1 else self.slowAccess(), // The interrupt ROM, fast to read and slow to write. 0x71...0x7f => if (within < switches_to and !writing) 1 else self.slowAccess(), // In both chips: written slowly, read quickly. 0x2d, 0x68 => if (within < switches_to and !writing) 1 else self.slowAccess(), else => self.slowAccess(), }; } /// The lines the processor drives, which the log records /// alongside the address. inline fn lines(self: *Self) struct { e: bool, m: bool, x: bool, mlb: bool } { const cpu = self.getCPU(); return .{ .e = cpu.flags.emulation, .m = cpu.flags.isSet(.M), .x = cpu.flags.isSet(.X), .mlb = cpu.locked, }; } fn record(self: *Self, address: u24, value: u8, direction: Access.Direction, comptime cycle: Cycle) void { const l = self.lines(); self.bus.record(.{ .address = address, .value = value, .direction = direction, .cycle = cycle, .e = l.e, .m = l.m, .x = l.x, .mlb = l.mlb, }); } pub fn read(self: *Self, address: u24, comptime cycle: Cycle) u8 { if (comptime !cycle.transfers()) @compileError("an internal cycle transfers nothing: call `internal`"); self.updateVideo(); self.claimWindow(@truncate(address >> 16), @truncate(address)); // Whoever answers spends the cycle, and only one of them // does: the Mega II's own read spends one against the same // clock, so this must not spend a second. const spend = self.cost(address, false); const decoded = if (comptime cycle == .vector) self.decodeVector(address) else self.decode(address, false); const value = switch (decoded) { .mega => |at| blk: { // The Mega II spends one against the same clock, // so only the difference is owed. const byte = self.mega2.read(u8, at); self.getCPU().clock.sleep(spend - 1); break :blk byte; }, else => |where| blk: { self.getCPU().clock.sleep(spend); break :blk switch (where) { .ram => |byte| byte.*, .rom => |byte| byte, .soft => |which| self.softSwitch(which, null), .nothing => 0, .mega => unreachable, }; }, }; self.record(address, value, .read, cycle); self.updateInterrupt(); return value; } pub fn write(self: *Self, address: u24, value: u8, comptime cycle: Cycle) void { if (comptime !cycle.transfers()) @compileError("an internal cycle transfers nothing: call `internal`"); self.updateVideo(); self.claimWindow(@truncate(address >> 16), @truncate(address)); self.record(address, value, .write, cycle); const spend = self.cost(address, true); switch (self.decode(address, true)) { .mega => |at| { self.mega2.write(u8, at, value); self.getCPU().clock.sleep(spend - 1); }, else => |where| { self.getCPU().clock.sleep(spend); switch (where) { .ram => |byte| { byte.* = value; self.shadowWrite( @truncate(address >> 16), @truncate(address), value, ); }, // The cycle is spent and the bus carries the // access either way; ROM simply declines to // latch it. .rom, .nothing => {}, .soft => |which| _ = self.softSwitch(which, value), .mega => unreachable, } }, } self.updateInterrupt(); } /// A cycle the processor spends on itself, with the address /// bus still holding something. pub fn internal(self: *Self, address: u24) void { self.getCPU().clock.sleep(1); self.record(address, 0, .read, .internal); } /// The middle cycle of a read-modify-write. pub fn internalWrite(self: *Self, address: u24, value: u8) void { self.getCPU().clock.sleep(1); self.record(address, value, .write, .internal_write); } /// A cycle in which the processor is not driving the bus. pub fn letGo(self: *Self) void { self.getCPU().clock.sleep(1); self.record(0, 0, .read, .stopped); } /// Writes out what the machine asked for and did not get, most /// wanted first. This is the whole point of the model as it /// stands: run the ROM, read this, and it says what to build. /// Whether the video controller has the memory to itself and /// is drawing Super Hi-Res rather than the Mega II drawing an /// Apple II's screen. pub fn superHiRes(self: *const Self) bool { return self.vgc.new_video & vgc_module.Vgc.super_hires != 0; } pub fn report(self: *const Self, writer: *std.Io.Writer) !void { var total: u64 = 0; var kinds: usize = 0; for (self.unimplemented) |count| { total += count; if (count != 0) kinds += 1; } if (total == 0) { try writer.writeAll("every address the machine asked for was answered\n"); return; } try writer.print( "{d} accesses to {d} soft switches this machine has not got", .{ total, kinds }, ); if (self.first_unimplemented) |first| try writer.print(", the first at ${x:0>4}", .{first}); try writer.writeAll("\n"); // Most asked for first, which is the order worth working // in: whatever the ROM is stuck in a loop on is at the top. var order: [0x100]u8 = undefined; for (0..0x100) |i| order[i] = @intCast(i); std.mem.sort(u8, &order, self, struct { fn less(context: *const Self, a: u8, b: u8) bool { return context.unimplemented[a] > context.unimplemented[b]; } }.less); for (order) |which| { const count = self.unimplemented[which]; if (count == 0) break; try writer.print(" ${x:0>4} {d}\n", .{ io_from | @as(u16, which), count }); } // And the shape of it, which the tally cannot show. const kept = @min(self.traced, trace_length); if (kept == 0) return; try writer.print("\nthe last {d} of them, in order:\n ", .{kept}); const first = self.traced - kept; for (0..kept) |i| { const entry = self.trace[(first + i) % trace_length]; if (entry.write) try writer.print(" W${x:0>4}={x:0>2}", .{ entry.address, entry.value }) else try writer.print(" R${x:0>4}", .{entry.address}); if (i % 8 == 7) try writer.writeAll("\n "); } try writer.writeAll("\n"); } }; } }.model; } const testing = std.testing; const TestCPU = @import("../cpu16.zig").Chip( .{}, @import("../clock.zig").FakeClock, AppleIIgs(.{}), ); /// The model itself, for the tests that want to name one of its constants /// rather than write the bit out as a number. const TestMemory = @FieldType(TestCPU, "memory"); /// A ROM image with nothing in it but the marks that say which bank is which, /// and a reset vector pointing somewhere a test can recognise. fn testRom(gpa: std.mem.Allocator, comptime order: iigsrom.Order) ![]u8 { const bytes = try gpa.alloc(u8, 2 * bank_size); @memset(bytes, 0); const firmware = switch (order) { .ascending => bytes[bank_size..], .descending => bytes[0..bank_size], }; firmware[0xfffc] = 0x00; firmware[0xfffd] = 0x30; firmware[0xfbb3] = 0x06; firmware[0xfbc0] = 0xe0; @memcpy(firmware[0xfded..0xfdf0], &[_]u8{ 0x6c, 0x36, 0x00 }); // The reset vector has to look like the firmware's, or identify will not // recognise the bank at all. firmware[0xfffc] = 0x62; firmware[0xfffd] = 0xfa; return bytes; } test "the machine starts from the vector in the ROM, whichever way round the image is" { // The whole reason the language card window is here: at power-on, bank // zero's high memory is the ROM, and that is where the reset vector is // read from. Both layouts, because both exist. inline for (.{ iigsrom.Order.ascending, iigsrom.Order.descending }) |order| { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, order); defer testing.allocator.free(rom); try cpu.memory.loadROM(rom); cpu.reset(); try testing.expectEqual(@as(u16, 0xfa62), cpu.program_counter.value); // And a reset starts it in emulation mode in bank zero, which is what // lets a IIgs run software that has never heard of one. try testing.expect(cpu.flags.emulation); try testing.expectEqual(@as(u8, 0x00), cpu.registers.program_bank); } } test "the interrupt ROM is in the switch page whatever else the bank is doing" { // Fifteen bytes at $c071 that read the machine's own ROM in banks $00 and // $01. It is where the Monitor's interrupt handler jumps, and without it // the machine reads the paddle trigger as an instruction — which nothing // noticed until the mouse became the first thing to ask for an interrupt. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .descending); defer testing.allocator.free(rom); // The firmware bank comes first in a descending image; put something // recognisable in the fifteen bytes. for (0xc071..0xc080) |at| rom[at] = @intCast(at & 0xff); try cpu.memory.loadROM(rom); for (0xc071..0xc080) |at| { const want: u8 = @intCast(at & 0xff); try testing.expectEqual(want, cpu.memory.peek(@intCast(at))); try testing.expectEqual(want, cpu.memory.peek(0x010000 + @as(u24, @intCast(at)))); } // Its neighbours on both sides are still switches, which answer a peek // with nothing rather than with a byte of ROM. try testing.expectEqual(@as(u8, 0), cpu.memory.peek(0x00c070)); try testing.expectEqual(@as(u8, 0), cpu.memory.peek(0x00c080)); // And it is still there with the I/O and language-card space inhibited, // which is the configuration the Hardware Reference (Apple Computer, Inc., // 1989) names when it says the interrupt ROM code is available at all: // the rest of the bank has become sixty-four kilobytes of RAM and these // fifteen bytes have not. cpu.memory.shadow |= 0x40; try testing.expectEqual(@as(u8, 0x71), cpu.memory.peek(0x00c071)); try testing.expectEqual(@as(u8, 0x7f), cpu.memory.peek(0x00c07f)); // The Mega II's banks have no such thing: the interrupt ROM is the FPI's, // and over there $c071 is the paddle trigger's neighbour as always. try testing.expectEqual(@as(u8, 0), cpu.memory.peek(0xe0c071)); } test "a hard disk in slot 7 is the one card this machine can be given" { // A IIgs has its cards built in, and the Slot register says for each of // them whether the machine's own firmware answers or a card does. Slot 7 // is the one with nothing built into it, which is why the firmware leaves // the register pointing there and why the hard disk goes in it. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); rom[bank_size + 0xc700] = 0xa7; // something recognisable in slot 7's page try cpu.memory.loadROM(rom); var image: [blockdevice.block_size * 4]u8 = undefined; for (0..4) |block| @memset(image[block * blockdevice.block_size ..][0..blockdevice.block_size], @intCast(block + 1)); var volume: blockdevice.Volume = .{ .image = &image, .write_protected = false }; // With the register clear the page is the machine's own, card or no card. cpu.memory.insertVolume(0, &volume); try testing.expectEqual(@as(u8, 0xa7), cpu.memory.read(0x00c700, .data)); // The firmware points the seventh slot at a card, and now the card's own // page answers — the four bytes ProDOS reads to know it is a block device // and not a Disk II, and the two at the end that say what it can do and // where to call it. cpu.memory.write(0x00c02d, 0x80, .data); try testing.expectEqual(@as(u8, 0x20), cpu.memory.read(0x00c701, .data)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c703, .data)); try testing.expectEqual(@as(u8, 0x03), cpu.memory.read(0x00c705, .data)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c707, .data)); try testing.expectEqual(@as(u8, 0x17), cpu.memory.read(0x00c7fe, .data)); try testing.expectEqual(@as(u8, 0x0b), cpu.memory.read(0x00c7ff, .data)); // And in the Mega II's banks too, where a IIe would look for it. try testing.expectEqual(@as(u8, 0x20), cpu.memory.read(0xe0c701, .data)); // An empty slot is an empty slot: with nothing in either drive the page // reads as nothing and the boot scan goes past. cpu.memory.insertVolume(0, null); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c701, .data)); cpu.memory.insertVolume(0, &volume); // The registers are the sixteen the slot answers at. Reading the first of // them does the transfer, and the card moves the bytes itself. const io: u24 = 0x00c0f0; cpu.memory.write(io + 2, 1, .data); // read cpu.memory.write(io + 3, 0x70, .data); // slot 7, drive 1 cpu.memory.write(io + 4, 0x00, .data); // to $2000 cpu.memory.write(io + 5, 0x20, .data); cpu.memory.write(io + 6, 2, .data); // block 2 cpu.memory.write(io + 7, 0, .data); try testing.expectEqual(@as(u8, 0), cpu.memory.read(io, .data)); try testing.expectEqual(@as(u8, 3), cpu.memory.peek(0x002000)); try testing.expectEqual(@as(u8, 3), cpu.memory.peek(0x0021ff)); // And it went through shadowing, so the Mega II has it too — which is what // lets a program read a block straight onto the screen. try testing.expectEqual(@as(u8, 3), cpu.memory.peek(0xe02000)); // The other drive is empty, and says so rather than answering with this // one's blocks. cpu.memory.write(io + 3, 0xf0, .data); try testing.expectEqual( @intFromEnum(blockdevice.Failure.offline), cpu.memory.read(io, .data), ); // Writing goes the other way, and marks the image as needing saving. cpu.memory.write(io + 3, 0x70, .data); cpu.memory.poke(0x002000, 0x5a); cpu.memory.write(io + 2, 2, .data); // write try testing.expectEqual(@as(u8, 0), cpu.memory.read(io, .data)); try testing.expectEqual(@as(u8, 0x5a), image[2 * blockdevice.block_size]); try testing.expect(volume.dirty); // A status call answers with how many blocks there are, which is how // ProDOS learns the size of the volume. cpu.memory.write(io + 2, 0, .data); try testing.expectEqual(@as(u8, 0), cpu.memory.read(io, .data)); try testing.expectEqual(@as(u8, 4), cpu.memory.read(io + 6, .data)); try testing.expectEqual(@as(u8, 0), cpu.memory.read(io + 7, .data)); } test "banks $00 and $01 are the main and auxiliary a IIe program expects" { // "For standard Apple II programs, banks $00 and $01 take on the features // of the main and auxiliary banks", says the Hardware Reference (Apple // Computer, Inc., 1989). It has to be so: a program written for a IIe // reaches the auxiliary sixty-four kilobytes by setting RAMRD or RAMWRT and // then addressing bank nought, and there is nowhere else for that to land. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); try cpu.memory.loadROM(rom); // Write to auxiliary. The byte goes to bank $01 and bank $00 is untouched, // which is exactly what ProDOS 8 counting its memory depends on: it puts a // byte at $0800 to see whether there is another sixty-four kilobytes // there, and if that lands in bank $00 it lands on its own code. cpu.memory.write(0x00c005, 0, .data); cpu.memory.write(0x000800, 0xee, .data); try testing.expectEqual(@as(u8, 0xee), cpu.memory.fast[bank_size + 0x0800]); try testing.expectEqual(@as(u8, 0x00), cpu.memory.fast[0x0800]); // Reading is a separate switch, so it still comes from the main bank. cpu.memory.fast[0x0800] = 0x11; try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(0x000800, .data)); cpu.memory.write(0x00c003, 0, .data); try testing.expectEqual(@as(u8, 0xee), cpu.memory.read(0x000800, .data)); // An odd bank is the auxiliary one outright, whatever the switches say: // native software is handed bank $01 by the Memory Manager and uses it as // ordinary memory, with the old switches in whatever state it found them. cpu.memory.write(0x00c002, 0, .data); // read main again cpu.memory.write(0x00c004, 0, .data); // and write to it cpu.memory.write(0x010800, 0x5a, .data); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.fast[bank_size + 0x0800]); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(0x010800, .data)); // And an even one is the main one again. cpu.memory.write(0x000800, 0x33, .data); try testing.expectEqual(@as(u8, 0x33), cpu.memory.fast[0x0800]); // The display pages have their own rule on top: with 80STORE on it is // PAGE2 that says which half text Page 1 lands in, and RAMWRT has no vote. cpu.memory.write(0x00c001, 0, .data); // 80STORE on cpu.memory.write(0x00c055, 0, .data); // PAGE2 cpu.memory.write(0x000400, 0x77, .data); try testing.expectEqual(@as(u8, 0x77), cpu.memory.fast[bank_size + 0x0400]); cpu.memory.write(0x00c054, 0, .data); // PAGE1 cpu.memory.write(0x000400, 0x88, .data); try testing.expectEqual(@as(u8, 0x88), cpu.memory.fast[0x0400]); // And the zero page and the stack follow ALTZP rather than either of them. cpu.memory.write(0x00c000 + 0x09, 0, .data); // ALTZP on cpu.memory.write(0x000050, 0xa5, .data); try testing.expectEqual(@as(u8, 0xa5), cpu.memory.fast[bank_size + 0x0050]); cpu.memory.write(0x00c000 + 0x08, 0, .data); // and off cpu.memory.write(0x000050, 0x5a, .data); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.fast[0x0050]); } test "the State register moves the switches rather than remembering them" { // Eight of the IIe's switches in one byte, so that a program can save and // restore the lot without touching eight addresses. It was a stored byte // for a long while, which read back what had been written and moved // nothing — harmless only for as long as nothing in banks $00 and $01 // looked at the switches at all. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); try cpu.memory.loadROM(rom); // From the top: ALTZP, PAGE2, RAMRD, RAMWRT, RDROM, LCBNK2, ROMBANK, // INTCXROM (Apple Computer, Inc., 1989a, Table 3-2). cpu.memory.write(0x00c068, 0xf9, .data); try testing.expect(cpu.memory.mega2.altzp); try testing.expect(cpu.memory.mega2.page2); try testing.expect(cpu.memory.mega2.ramrd); try testing.expect(cpu.memory.mega2.ramwrt); // The language card the other way up: the bit is set when the window is // reading ROM, which is when the card is not reading its own RAM. try testing.expect(!cpu.memory.mega2.card_switches.read_ram); try testing.expect(cpu.memory.mega2.intcxrom); try testing.expectEqual(@as(u8, 0xf9), cpu.memory.read(0x00c068, .data)); cpu.memory.write(0x00c068, 0x04, .data); try testing.expect(!cpu.memory.mega2.altzp); try testing.expect(!cpu.memory.mega2.ramrd); try testing.expect(cpu.memory.mega2.card_switches.read_ram); try testing.expect(cpu.memory.mega2.card_switches.bank2); try testing.expectEqual(@as(u8, 0x04), cpu.memory.read(0x00c068, .data)); // Which is what the ROM's own AUXMOVE depends on. It does not shuffle // switches a byte at a time the way a IIe's does: it uses the 65816's // block move between banks $00 and $01, and before it does it reads this // register, clears RAMRD and RAMWRT with AND #$cf, and writes it back — // because with the auxiliary bank read-enabled the move would take its // source from the bank it was meant to be filling. cpu.memory.write(0x00c068, 0x30, .data); // read and write auxiliary cpu.memory.write(0x000810, 0x5a, .data); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.fast[bank_size + 0x0810]); try testing.expectEqual(@as(u8, 0x00), cpu.memory.fast[0x0810]); const saved = cpu.memory.read(0x00c068, .data); cpu.memory.write(0x00c068, saved & 0xcf, .data); cpu.memory.write(0x000810, 0xa5, .data); try testing.expectEqual(@as(u8, 0xa5), cpu.memory.fast[0x0810]); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.fast[bank_size + 0x0810]); // And putting it back leaves the machine as it was found. cpu.memory.write(0x00c068, saved, .data); try testing.expectEqual(saved, cpu.memory.read(0x00c068, .data)); try testing.expect(cpu.memory.mega2.ramrd and cpu.memory.mega2.ramwrt); } test "the fast side and the Mega II are different memory" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.poke(0x000400, 0x11); cpu.memory.poke(0xe00400, 0x22); try testing.expectEqual(@as(u8, 0x11), cpu.memory.peek(0x000400)); try testing.expectEqual(@as(u8, 0x22), cpu.memory.peek(0xe00400)); // And the Mega II's is the Mega II's: the same byte, reached the way a // program running inside it would. try testing.expectEqual(@as(u8, 0x22), cpu.memory.mega2.peek(0x0400)); } test "the serial ports carry bytes, and each carries its own" { // $c03a and $c03b are the two data registers, B and A, which is the modem // port and the printer port. What a program writes there goes out of that // port and nowhere else. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c03b, 'A', .data); cpu.memory.write(0x00c03a, 'B', .data); try testing.expectEqualStrings("A", cpu.memory.scc.channelOf(.a).sent()); try testing.expectEqualStrings("B", cpu.memory.scc.channelOf(.b).sent()); // A byte arriving from outside shows in that channel's status and comes // back from its data register, and the other channel knows nothing of it. try testing.expect(cpu.memory.scc.channelOf(.b).receive('Z')); cpu.memory.write(0x00c039, 0, .data); // point at RR0 on channel A try testing.expectEqual(@as(u8, 0), cpu.memory.read(0x00c039, .data) & 0x01); cpu.memory.write(0x00c038, 0, .data); // and on channel B try testing.expect(cpu.memory.read(0x00c038, .data) & 0x01 != 0); try testing.expectEqual(@as(u8, 'Z'), cpu.memory.read(0x00c03a, .data)); // Taken, so the next look says nothing is waiting. cpu.memory.write(0x00c038, 0, .data); try testing.expectEqual(@as(u8, 0), cpu.memory.read(0x00c038, .data) & 0x01); } test "the bank latch decides whether $e1 is a bank of its own" { // The seam, and the thing the Hardware Reference (Apple Computer, Inc., // 1989) settled. With the latch clear the Mega II ignores the bank bit // altogether and its own switches choose the half, so $e0 and $e1 are the // same memory. With it set the bank address chooses, and they are not. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Clear, which is how the machine comes up. cpu.memory.poke(0xe00400, 0x11); cpu.memory.poke(0xe10400, 0x22); try testing.expectEqual(@as(u8, 0x22), cpu.memory.peek(0xe00400)); try testing.expectEqual(@as(u8, 0x22), cpu.memory.peek(0xe10400)); // Set bit 0 of the New-Video register and they part company. cpu.memory.write(0x00c029, 0x01, .data); cpu.memory.poke(0xe00400, 0x33); cpu.memory.poke(0xe10400, 0x44); try testing.expectEqual(@as(u8, 0x33), cpu.memory.peek(0xe00400)); try testing.expectEqual(@as(u8, 0x44), cpu.memory.peek(0xe10400)); // $e1 is the auxiliary half, which is where Super Hi-Res lives. try testing.expectEqual(@as(u8, 0x44), cpu.memory.mega2.halfTarget(true, 0x0400, false).?.*); try testing.expectEqual(@as(u8, 0x33), cpu.memory.mega2.halfTarget(false, 0x0400, false).?.*); // And with the latch clear again, RAMRD is what picks the half — for both // bank addresses alike, which is the part that makes them alias. cpu.memory.write(0x00c029, 0x00, .data); cpu.memory.write(0x00c003, 0, .data); // RAMRD on: reads come from auxiliary try testing.expectEqual(@as(u8, 0x44), cpu.memory.peek(0xe00400)); } test "a bank with nothing in it reads as nothing and keeps nothing" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.poke(0x420000, 0x55); try testing.expectEqual(@as(u8, 0x00), cpu.memory.peek(0x420000)); } test "the switches it has not got are counted rather than guessed at" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); try testing.expectEqual(@as(?u16, null), cpu.memory.first_unimplemented); // Whichever address this model does not answer today, found rather than // named. Naming one meant rewriting this test every time a register was // implemented, which happened twice; and what is being tested is the // counting, not any particular register. The machine's own ROM now asks // for nothing this cannot answer, so whatever turns up here is something // the firmware never reaches. var found: ?u8 = null; for (0..0x100) |i| { const which: u8 = @intCast(i); _ = cpu.memory.read(io_from | @as(u24, which), .data); if (cpu.memory.unimplemented[which] != 0) { found = which; break; } } // If every address in the page were answered there would be nothing to // count and nothing to test, which would be a good problem to have. const missing = found orelse return error.SkipZigTest; // The scan threw a great many switches on its way through; start the // count again now that there is an address to count. cpu.memory.unimplemented = @splat(0); cpu.memory.first_unimplemented = null; cpu.memory.traced = 0; _ = cpu.memory.read(io_from | @as(u24, missing), .data); _ = cpu.memory.read(io_from | @as(u24, missing), .data); // The same switches answer in the Mega II's banks as in the fast ones. _ = cpu.memory.read(@as(u24, slow_bank) << 16 | io_from | @as(u24, missing), .data); try testing.expectEqual( @as(?u16, io_from | @as(u16, missing)), cpu.memory.first_unimplemented, ); try testing.expectEqual(@as(u32, 3), cpu.memory.unimplemented[missing]); var buffer: std.Io.Writer.Allocating = .init(testing.allocator); defer buffer.deinit(); try cpu.memory.report(&buffer.writer); const text = buffer.written(); var wanted: [16]u8 = undefined; try testing.expect(std.mem.indexOf( u8, text, try std.fmt.bufPrint(&wanted, "$c0{x:0>2} 3", .{missing}), ) != null); var first: [32]u8 = undefined; try testing.expect(std.mem.indexOf( u8, text, try std.fmt.bufPrint(&first, "the first at $c0{x:0>2}", .{missing}), ) != null); } test "the registers the manual sets out are kept and read back" { // Not the hardware — none of these does anything yet — but firmware that // writes a configuration and reads it back to check will be satisfied, // and that is most of what the self-test is doing. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // The registers that keep every bit they are given. for ([_]u24{ 0x00c021, // Monochrome/Color, whose reserved bits are still kept 0x00c022, // Screen Color 0x00c029, // New-Video 0x00c035, // Shadow 0x00c036, // Speed 0x00c068, // State }) |at| { cpu.memory.write(at, 0xa5, .data); try testing.expectEqual(@as(u8, 0xa5), cpu.memory.read(at, .data)); // And none of them was counted as missing. try testing.expectEqual(@as(u32, 0), cpu.memory.unimplemented[at & 0xff]); } // Language Select is the exception, and deliberately: its low three bits // must be written as zero, so they are not kept and read back as zero. // That is the hardware declining to store bits it has not got, not this // model losing them. cpu.memory.write(0x00c02b, 0xa5, .data); try testing.expectEqual(@as(u8, 0xa0), cpu.memory.read(0x00c02b, .data)); try testing.expectEqual(@as(u32, 0), cpu.memory.unimplemented[0x2b]); // A reset puts them all back, as the power-on does. cpu.reset(); try testing.expectEqual(@as(u8, 0), cpu.memory.vgc.new_video); try testing.expectEqual(@as(u8, 0), cpu.memory.vgc.screenColour()); try testing.expectEqual(@as(u8, 0), cpu.memory.shadow); } test "vertical blanking is the bar in RDVBLBAR" { // Set while the beam is drawing and clear while it is not, which is the // way round a IIe has it and the opposite of a IIc. The Hardware // Reference puts it in four words: "1 = not VBL". var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const Memory = @TypeOf(cpu.memory); cpu.clock.cycles = 0; try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0x00c019, .data)); // Into the blanking interval, which starts after the 192nd line. cpu.clock.cycles = Memory.cycles_per_line * Memory.displayed_lines; try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c019, .data)); // And out the other side into the next frame. cpu.clock.cycles = Memory.cycles_per_frame; try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0x00c019, .data)); } test "peeking never throws a switch" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); _ = cpu.memory.peek(0x00c035); cpu.memory.poke(0x00c035, 0); try testing.expectEqual(@as(u32, 0), cpu.memory.unimplemented[0x35]); } test "the switches a IIe owns are answered by a IIe" { // Not by a stub, and not by this model pretending: the Mega II inside a // IIgs is an Apple IIe, and these are the same switches doing the same // thing they have always done. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // 80COL off, so RD80VID reads clear. cpu.memory.write(0x00c00c, 0, .data); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c01f, .data) & 0x80); // And on. cpu.memory.write(0x00c00d, 0, .data); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0x00c01f, .data) & 0x80); // The same switches answer in the Mega II's own banks, which is where a // program that has not been told about the fast side will look. cpu.memory.write(0xe0c00c, 0, .data); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0xe0c01f, .data) & 0x80); // None of it was counted as missing. try testing.expectEqual(@as(u32, 0), cpu.memory.unimplemented[0x0c]); try testing.expectEqual(@as(u32, 0), cpu.memory.unimplemented[0x1f]); } test "a switch the IIe never had is not handed to one" { // The IIgs took addresses a IIe was not using and gave them to hardware a // IIe never had. Asking a IIe about those would get an answer, and a // made-up one — worse than getting none, because an unanswered switch is // counted and turns up in the report as work to do while a wrong answer // says nothing at all. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Each of these is decoded as this machine's own, whether or not it is // answered yet. What matters is that none of them is passed through. for ([_]u24{ 0x00c021, // Monochrome/Color 0x00c022, // Screen Color 0x00c02b, // Language Select 0x00c02d, // the Slot register 0x00c031, // the Disk Interface register 0x00c039, // the serial chip, which is not answered yet 0x00c046, // the Interrupt Flag register }) |at| { try testing.expect(cpu.memory.decode(at, false) == .soft); try testing.expect(cpu.memory.decode(at | 0xe00000, false) == .soft); } // Whereas a switch that really is a IIe's goes to the IIe, which is the // other half of the same claim: the allow-list has to let those through. try testing.expect(cpu.memory.decode(0x00c010, false) == .mega); try testing.expect(cpu.memory.decode(0x00c000, false) == .mega); } test "an access costs what the side of the machine it reaches costs" { // One cycle on the fast side, three on the slow, and only one machine ever // charges for it: both models sleep against the same clock, so a delegated // access must not be paid for twice. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // A machine comes up at 1.024 MHz and is *made* fast, which is one of the // first things the firmware does; do it here too, or there is no fast side // to measure against the slow one. cpu.memory.write(0x00c036, TestMemory.speed_fast, .data); // Fast RAM. cpu.clock.cycles = 0; _ = cpu.memory.read(0x000400, .data); try testing.expectEqual(@as(u64, 1), cpu.clock.cycles); // The Mega II's memory is on the slow side. cpu.clock.cycles = 0; _ = cpu.memory.read(0xe00400, .data); try testing.expectEqual(@as(u64, slow_cycle), cpu.clock.cycles); // A soft switch is slow, wherever it is answered from. cpu.clock.cycles = 0; _ = cpu.memory.read(0x00c01f, .data); // the Mega II's try testing.expectEqual(@as(u64, slow_cycle), cpu.clock.cycles); cpu.clock.cycles = 0; _ = cpu.memory.read(0x00c029, .data); // this machine's try testing.expectEqual(@as(u64, slow_cycle), cpu.clock.cycles); // But the three registers inside the FPI are not: the processor never // leaves its own side of the machine to reach them. for ([_]u24{ 0x00c035, 0x00c036, 0x00c037 }) |at| { cpu.clock.cycles = 0; _ = cpu.memory.read(at, .data); try testing.expectEqual(@as(u64, 1), cpu.clock.cycles); } // The state register lives in both chips: read fast, written slow. cpu.clock.cycles = 0; _ = cpu.memory.read(0x00c068, .data); try testing.expectEqual(@as(u64, 1), cpu.clock.cycles); cpu.clock.cycles = 0; cpu.memory.write(0x00c068, 0, .data); try testing.expectEqual(@as(u64, slow_cycle), cpu.clock.cycles); // And asking for 1.024 MHz makes the whole machine slow. cpu.memory.write(0x00c036, 0x00, .data); cpu.clock.cycles = 0; _ = cpu.memory.read(0x000400, .data); try testing.expectEqual(@as(u64, slow_cycle), cpu.clock.cycles); } test "the desktop bus reports the Mega II's keyboard, not one of its own" { // An Apple IIgs does not read its own keyboard: a microcontroller does, // and feeds the same $c000 an Apple II has always had. So there is one // latch, the Mega II's, and the bus reports it rather than keeping a copy // that could disagree. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Nothing typed: the keyboard bit clear, and $c000 says so too. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c027, .data) & 0x08); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c000, .data) & 0x80); cpu.memory.mega2.pressKey('A'); try testing.expectEqual(@as(u8, 0x08), cpu.memory.read(0x00c027, .data) & 0x08); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.read(0x00c000, .data)); // Clearing the strobe the way any Apple II program does clears the bus's // bit with it, because it is the same bit. _ = cpu.memory.read(0x00c010, .data); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c027, .data) & 0x08); } test "the desktop bus takes commands and admits it has no answer" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // The shape the firmware uses: a command byte, then the status polled to // see the microcontroller has taken it. cpu.memory.write(0x00c026, 0x07, .data); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c027, .data) & 0x01); try testing.expectEqual(@as(u32, 1), cpu.memory.adb.commands); // And no reply is claimed, because nothing here knows what $07 means. The // status says nothing is waiting rather than leaving the machine to wait // for something that is not coming. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c027, .data) & 0x20); // The interrupt enables are writable and the rest of the register is not. cpu.memory.write(0x00c027, 0xff, .data); try testing.expectEqual(@as(u8, 0x54), cpu.memory.read(0x00c027, .data)); } test "the clock is reached a byte at a time, and the border rides along" { // The handshake the Hardware Reference (Apple Computer, Inc., 1989a) sets // out: put the byte in, start the transfer, and poll bit 7 until the chip // says it is done. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c033, 0x24, .data); cpu.memory.write(0x00c034, 0xa0, .data); // start, writing, last byte try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c034, .data) & 0x80); try testing.expectEqual(@as(u32, 1), cpu.memory.rtc.transfers); try testing.expectEqual(@as(u8, 0x24), cpu.memory.rtc.trace[0].value); // The border colour is the low nibble of the same register, and setting // it is not a transfer. cpu.memory.write(0x00c034, 0x0c, .data); try testing.expectEqual(@as(u4, 12), cpu.memory.rtc.border); try testing.expectEqual(@as(u32, 1), cpu.memory.rtc.transfers); // Neither register is on the missing list any more. try testing.expectEqual(@as(u32, 0), cpu.memory.unimplemented[0x33]); try testing.expectEqual(@as(u32, 0), cpu.memory.unimplemented[0x34]); } test "a write to the old display in bank zero is shadowed onto the screen" { // The whole reason shadowing exists. A program written for a IIe puts a // character in text page 1 of bank $00; the screen is the Mega II's, in // bank $e0; and this is the only thing that carries the one to the other. // Without it the firmware's own startup message goes nowhere, which is how // the want of this was noticed. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x000400, 0xc1, .data); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.peek(0x000400)); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.mega2.peek(0x0400)); // And a reset leaves the register at zero, which shadows everything: both // Hi-Res pages as well. cpu.memory.write(0x002000, 0x3c, .data); cpu.memory.write(0x004000, 0x5a, .data); try testing.expectEqual(@as(u8, 0x3c), cpu.memory.mega2.peek(0x2000)); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.mega2.peek(0x4000)); // Memory outside the display buffers is not shadowed, and stays on the // fast side where it belongs. cpu.memory.write(0x001000, 0x99, .data); try testing.expectEqual(@as(u8, 0x99), cpu.memory.peek(0x001000)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.mega2.peek(0x1000)); } test "every bit of the Shadow register is an inhibit" { // Set means off, which is the opposite way round from how the name reads, // and is why a register of zeroes shadows the lot. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c035, 0x01, .data); // text page 1 inhibited cpu.memory.write(0x000400, 0x11, .data); try testing.expectEqual(@as(u8, 0x11), cpu.memory.peek(0x000400)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.mega2.peek(0x0400)); // Hi-Res page 1 is still shadowed, its own bit being clear. cpu.memory.write(0x002000, 0x22, .data); try testing.expectEqual(@as(u8, 0x22), cpu.memory.mega2.peek(0x2000)); // And clearing the bit again lets text through. cpu.memory.write(0x00c035, 0x00, .data); cpu.memory.write(0x000401, 0x33, .data); try testing.expectEqual(@as(u8, 0x33), cpu.memory.mega2.peek(0x0401)); } test "the auxiliary Hi-Res bit takes the odd bank's pages and leaves the even one's" { // Bit 4 is the odd one out: it does not name a buffer, it names the banks // the other bits apply to. "Shadowing of Hi-Res graphics pages in the main // bank remains unaffected." var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // With the latch set, bank $01 is the auxiliary half outright. cpu.memory.write(0x00c029, 0x01, .data); // Bit 4 set, and bit 3 too, so that the Super Hi-Res path does not carry // the write instead. cpu.memory.write(0x00c035, 0x18, .data); cpu.memory.write(0x012000, 0xaa, .data); cpu.memory.write(0x002000, 0xbb, .data); try testing.expectEqual(@as(u8, 0x00), cpu.memory.peek(0xe12000)); try testing.expectEqual(@as(u8, 0xbb), cpu.memory.peek(0xe02000)); } test "the Super Hi-Res buffer is the odd bank's alone, and lies over the Hi-Res pages" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c029, 0x01, .data); // the bank latch // Above $6000 there is no Hi-Res page underneath, so only bit 3 answers // for it — and only in the odd bank. cpu.memory.write(0x016000, 0x77, .data); cpu.memory.write(0x006000, 0x88, .data); try testing.expectEqual(@as(u8, 0x77), cpu.memory.peek(0xe16000)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.peek(0xe06000)); // Under $6000 the two paths overlap and either one is enough: with the // Hi-Res pages inhibited in the odd bank, the Super Hi-Res bit still // carries the write. cpu.memory.write(0x00c035, TestMemory.inhibit_auxiliary_hires, .data); cpu.memory.write(0x013000, 0x99, .data); try testing.expectEqual(@as(u8, 0x99), cpu.memory.peek(0xe13000)); // Inhibit that as well and nothing gets through. cpu.memory.write( 0x00c035, TestMemory.inhibit_auxiliary_hires | TestMemory.inhibit_super_hires, .data, ); cpu.memory.write(0x013001, 0x9a, .data); try testing.expectEqual(@as(u8, 0x00), cpu.memory.peek(0xe13001)); } test "banks above the first two are shadowed only when the Speed register says so" { // There is no fast RAM up there on this machine yet, so this asks the // decision rather than the memory. The manual's advice is not to. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); try testing.expect(cpu.memory.shadowed(0x00, 0x0400)); try testing.expect(cpu.memory.shadowed(0x01, 0x0400)); try testing.expect(!cpu.memory.shadowed(0x02, 0x0400)); cpu.memory.write(0x00c036, cpu.memory.speed | TestMemory.shadow_every_bank, .data); try testing.expect(cpu.memory.shadowed(0x02, 0x0400)); } test "a shadowed write is slow and a read of the same place is fast" { // "Only write instructions to the video locations require the system to // operate at 1.024 MHz." Reads come from the fast side, which is the whole // point of shadowing rather than simply putting the display in $e0. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c036, TestMemory.speed_fast, .data); const before = cpu.clock.read(); _ = cpu.memory.read(0x000400, .data); const reading = cpu.clock.read() - before; cpu.memory.write(0x000400, 0x00, .data); const writing = cpu.clock.read() - before - reading; try testing.expectEqual(@as(u64, 1), reading); // A slow cycle, plus however much of one was left to wait out: the fast // read above has taken the processor out of step with the Mega II, which // is exactly the case the Hardware Reference gives a worst case for. See // `slowAccess`. try testing.expect(writing >= slow_cycle and writing <= 2 * slow_cycle - 1); // With the shadowing turned off the write is as fast as the read: there is // no second trip to make. cpu.memory.write(0x00c035, 0x3f, .data); const quiet = cpu.clock.read(); cpu.memory.write(0x000400, 0x00, .data); try testing.expectEqual(@as(u64, 1), cpu.clock.read() - quiet); } test "the power-on bit is the one thing a reset leaves alone" { // "The Speed register is cleared on reset or power up, except for bit 6, // which on power up is set", and "a boot initiated by any key combination // will not alter this bit". So it is how firmware tells a cold start from // a warm one, and the whole register otherwise starts at zero — which // means a machine comes up at 1.024 MHz and is made fast rather than // starting that way. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); try testing.expectEqual(TestMemory.speed_power_on, cpu.memory.speed); try testing.expectEqual(@as(u8, 0), cpu.memory.speed & TestMemory.speed_fast); // The firmware turns the speed up and sets a few other bits. cpu.memory.write(0x00c036, TestMemory.speed_fast | 0x0f, .data); try testing.expectEqual(@as(u8, 0x8f), cpu.memory.read(0x00c036, .data)); // A reset takes all of that away and leaves the power-on bit behind — but // it was cleared by that write, so there is nothing left to keep. cpu.memory.reset(); try testing.expectEqual(@as(u8, 0x00), cpu.memory.speed); // Whereas a machine that still has it keeps it across a reset. cpu.memory.write(0x00c036, TestMemory.speed_power_on | TestMemory.speed_fast, .data); cpu.memory.reset(); try testing.expectEqual(TestMemory.speed_power_on, cpu.memory.speed); } test "a motor-on detector slows the machine to 1.024 MHz until the motor-off address is touched" { // "The motor-on detectors change the system speed to 1.024 MHz whenever a // Disk II motor-on address is detected. When the disk motor-off address // is accessed, the system speed increases to 2.8 MHz again" (Apple // Computer, Inc., 1989, Table 2-2). This is what keeps a 5.25-inch disk // and the software written for a 1 MHz Apple II readable on a IIgs. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Fast, with the slot 6 detector enabled, as the firmware leaves it. cpu.memory.write(0x00c036, TestMemory.speed_fast | 0x04, .data); cpu.clock.cycles = 0; _ = cpu.memory.read(0x000400, .data); try testing.expectEqual(@as(u64, 1), cpu.clock.cycles); // The drive's motor on: the whole machine is slow. _ = cpu.memory.read(0x00c0e9, .data); cpu.clock.cycles = 0; _ = cpu.memory.read(0x000400, .data); try testing.expectEqual(@as(u64, slow_cycle), cpu.clock.cycles); // A detector the register has not enabled changes nothing: slot 5's. _ = cpu.memory.read(0x00c0e8, .data); _ = cpu.memory.read(0x00c0d9, .data); cpu.clock.cycles = 0; _ = cpu.memory.read(0x000400, .data); try testing.expectEqual(@as(u64, 1), cpu.clock.cycles); // And the detector is an address detector: the motor-off address ends // it at once, a second before the drive itself stops turning. _ = cpu.memory.read(0x00c0e9, .data); _ = cpu.memory.read(0x00c0e8, .data); cpu.clock.cycles = 0; _ = cpu.memory.read(0x000400, .data); try testing.expectEqual(@as(u64, 1), cpu.clock.cycles); // A reset clears what was detected along with the register. _ = cpu.memory.read(0x00c0e9, .data); cpu.memory.reset(); try testing.expectEqual(@as(u8, 0), cpu.memory.motor_detected); } test "the Slot register chooses between a card and the machine's own firmware" { // A IIgs has the cards a IIe had built into it, and each answers at the // slot its card would have gone in. A bit clear means the built-in one and // its driver in the system ROM; set means the slot, and nothing is fitted // to any slot of this machine, so what a set bit gets is what a real // machine with an empty slot gets. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); // Something recognisable in each slot's page of the firmware. for (1..8) |slot| { rom[bank_size + 0xc000 + slot * 0x100] = @intCast(0xa0 + slot); } try cpu.memory.loadROM(rom); // With the register clear, every slot's page comes from the system ROM. for (1..8) |slot| { const at: u24 = @intCast(0xc000 + slot * 0x100); try testing.expectEqual(@as(u8, @intCast(0xa0 + slot)), cpu.memory.read(at, .data)); } // Point slots 1, 2 and 6 at cards that are not there. cpu.memory.write(0x00c02d, 0x46, .data); try testing.expectEqual(@as(u8, 0x46), cpu.memory.read(0x00c02d, .data)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c100, .data)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c200, .data)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c600, .data)); // And the slots left alone still answer from the ROM. try testing.expectEqual(@as(u8, 0xa4), cpu.memory.read(0x00c400, .data)); try testing.expectEqual(@as(u8, 0xa7), cpu.memory.read(0x00c700, .data)); // Slot 3 is not in this register at all — the IIe's own SETSLOTC3ROM // still governs it — so setting bit 3, which is reserved, changes nothing. cpu.memory.write(0x00c02d, 0xff, .data); try testing.expectEqual(@as(u8, 0xa3), cpu.memory.read(0x00c300, .data)); // The same holds in the Mega II's banks, where the slot ROM also comes // from this machine's ROM rather than from a IIe's. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0xe0c100, .data)); try testing.expectEqual(@as(u8, 0xa3), cpu.memory.read(0xe0c300, .data)); } test "a frame arriving on the network pulls the interrupt line" { // The serial chip is on the interrupt line with everything else, and // keeps its own time: a frame handed to its wire arrives byte by byte // whether or not the processor touches the chip, and the first byte is // what the AppleTalk firmware asked to be interrupted for. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const scc = &cpu.memory.scc; // The firmware's own programming of the printer port for LocalTalk, // then the master interrupt enable and the receiver. const table = [_]u8{ 0x04, 0x20, 0x01, 0x08, 0x09, 0x0a, 0x0c, 0x06, 0x0d, 0x00, 0x03, 0xdd }; for (table) |byte| cpu.memory.write(0x00c039, byte, .data); try testing.expect(!cpu.irq); try testing.expect(scc.receiveFrame(.a, &.{ 0xff, 0x02, 0x81 }, true, cpu.clock.cycles)); // Not yet: the opening flag and the first byte take sixteen bit times. _ = cpu.memory.read(0x001000, .data); try testing.expect(!cpu.irq); cpu.clock.cycles += 16 * scc.a.cyclesPerBit(scc.cycles_per_second) + 1; _ = cpu.memory.read(0x001000, .data); try testing.expect(cpu.irq); // Taking the byte takes the interrupt with it. try testing.expectEqual(@as(u8, 0xff), cpu.memory.read(0x00c03b, .data)); try testing.expect(!cpu.irq); } test "the byte above the New-Video register is nobody's, and is not missed" { // GS/OS reaches $c02a as the high half of a sixteen-bit access to $c029 // (see softSwitch); the Firmware Reference (Apple Computer, Inc., 1987a, // Appendix E) has it "Reserved for future system expansion". Nothing is // there, so a read is the floating bus and a write is nothing, and neither // is a switch the machine has not got. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); _ = cpu.memory.read(0x00c02a, .data); cpu.memory.write(0x00c02a, 0x00, .data); try testing.expectEqual(@as(u32, 0), cpu.memory.unimplemented[0x2a]); try testing.expectEqual(@as(?u16, null), cpu.memory.first_unimplemented); } test "the Interrupt Flag register says what has interrupted, which is nothing" { // Every bit of it is gathered from elsewhere rather than stored, so what // it answers is a fact about the machine and not a default: there is no // mouse, so its button is not down, and nothing here raises an interrupt, // so nothing has interrupted. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Bit 5 is not an interrupt at all. It is the third annunciator, which // starts where the firmware leaves it — asserted, which is the state that // is *not* double resolution. try testing.expectEqual(@as(u8, 0x20), cpu.memory.read(0x00c046, .data)); try testing.expectEqual(@as(u32, 0), cpu.memory.unimplemented[0x46]); try testing.expect(!cpu.irq); // And it follows the switch, which the Mega II owns because a IIgs left // the annunciators where a IIe had them. _ = cpu.memory.read(0x00c05e, .data); try testing.expect(cpu.memory.mega2.double_hires); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c046, .data)); _ = cpu.memory.read(0x00c05f, .data); try testing.expectEqual(@as(u8, 0x20), cpu.memory.read(0x00c046, .data)); } const Memory16 = @TypeOf(@as(TestCPU, undefined).memory); test "vertical blanking interrupts once a frame, and only when it is allowed to" { // The beam reaching the bottom of the screen is the one event this machine // keeps time by, and every interrupt it has that is not a chip asking for // attention is counted in frames from here. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Run the clock to just inside the blanking interval of the first frame. cpu.clock.cycles = Memory16.cycles_per_frame - Memory16.blanking_cycles; _ = cpu.memory.read(0x000000, .data); try testing.expect(cpu.memory.blanking()); try testing.expect(cpu.memory.interrupts.vbl); // But nothing has asked for the line, because nothing enabled it. try testing.expect(!cpu.irq); // Enable it and the line comes up. cpu.memory.write(0x00c041, TestMemory.Interrupts.vbl_bit, .data); try testing.expect(cpu.irq); try testing.expectEqual( TestMemory.Interrupts.vbl_bit, cpu.memory.read(0x00c046, .data) & TestMemory.Interrupts.vbl_bit, ); // And bit 0 of the flag register says the line is asserted. try testing.expectEqual(@as(u8, 0x01), cpu.memory.read(0x00c046, .data) & 0x01); // Owning up at $c047 takes it away and drops the line. Bit 5 stays: it is // the annunciator rather than an interrupt, and owning up to an interrupt // does not move an annunciator. _ = cpu.memory.read(0x00c047, .data); try testing.expect(!cpu.memory.interrupts.vbl); try testing.expect(!cpu.irq); try testing.expectEqual(@as(u8, 0x20), cpu.memory.read(0x00c046, .data)); } test "the quarter-second interrupt is the frame counter, and is not a quarter of a second" { // The Firmware Reference (Apple Computer, Inc., 1987a) calls $c047 "clear // the VBL/3.75Hz interrupt flags", and 3.75 Hz is sixty divided by sixteen // exactly. So the quarter-second tick is the frame counter with its low // four bits masked off, and comes out at 0.267 seconds -- which is where // its other name came from and why the two are cleared together. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c041, TestMemory.Interrupts.quarter_second_bit, .data); // Fifteen frames go by without one. for (1..16) |frame| { cpu.clock.cycles = Memory16.cycles_per_frame * frame - Memory16.blanking_cycles; _ = cpu.memory.read(0x000000, .data); try testing.expect(cpu.memory.interrupts.vbl); // which does happen every frame try testing.expect(!cpu.memory.interrupts.quarter_second); try testing.expect(!cpu.irq); // and vertical blanking is not enabled } // And the sixteenth brings one. cpu.clock.cycles = Memory16.cycles_per_frame * 16 - Memory16.blanking_cycles; _ = cpu.memory.read(0x000000, .data); try testing.expect(cpu.memory.interrupts.quarter_second); try testing.expect(cpu.irq); // The same address clears both, because they are the same counter. _ = cpu.memory.read(0x00c047, .data); try testing.expect(!cpu.memory.interrupts.quarter_second); try testing.expect(!cpu.memory.interrupts.vbl); try testing.expect(!cpu.irq); } test "the video controller's interrupt register is cleared somewhere else, with a zero" { // Which is the other way round from everything near it: the status bits // live at $c023 and are cleared at $c032, by writing a bit that is *down*. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Writing $c023 reaches the two enable bits and nothing else -- a program // cannot set a status bit by hand. cpu.memory.write(0x00c023, 0xff, .data); try testing.expectEqual( @as(u8, TestMemory.Vgc.one_second_enable | TestMemory.Vgc.scan_line_enable), cpu.memory.read(0x00c023, .data), ); // A second of frames brings the one-second interrupt, and with it the // line and bit 7 of the register. cpu.clock.cycles = Memory16.cycles_per_frame * 60 - Memory16.blanking_cycles; _ = cpu.memory.read(0x000000, .data); try testing.expect(cpu.memory.vgc.one_second); try testing.expect(cpu.irq); const status = cpu.memory.read(0x00c023, .data); try testing.expectEqual(TestMemory.Vgc.interrupting_bit, status & TestMemory.Vgc.interrupting_bit); try testing.expectEqual(TestMemory.Vgc.one_second_status, status & TestMemory.Vgc.one_second_status); // Writing a *one* into its position at $c032 does nothing at all. cpu.memory.write(0x00c032, 0xff, .data); try testing.expect(cpu.memory.vgc.one_second); // And a zero takes it away. cpu.memory.write(0x00c032, 0xff & ~TestMemory.Vgc.one_second_status, .data); try testing.expect(!cpu.memory.vgc.one_second); try testing.expect(!cpu.irq); } test "the disk interface register reaches the disk port" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c031, 0xc0, .data); try testing.expect(cpu.memory.iwm.three_and_a_half); try testing.expect(cpu.memory.iwm.disks35.sel); // Bits 5 to 0 read back as zero whatever was written, which is what the // Hardware Reference says (Apple Computer, Inc., 1989a) and why it tells // you to use a read-modify-write. cpu.memory.write(0x00c031, 0x3f, .data); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c031, .data)); } test "the language card is one card, whichever bank its switches are thrown from" { // One set of switches held in two chips: the State register exists "in // both the FPI and the Mega II ICs" (Apple Computer, Inc., 1989a), and // GS/OS relies on the pairing — its loader throws $c08b from bank $00 and // then runs the code it block-moved into $e0/d000. Two independent cards // had it reading the ROM there instead. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); try cpu.memory.loadROM(rom); cpu.reset(); // Everything comes up reading ROM, which is how the reset vector is found. try testing.expect(!cpu.memory.mega2.card_switches.read_ram); try testing.expectEqual(cpu.memory.read(0x00d123, .data), cpu.memory.read(0xe0d123, .data)); // Thrown from bank $00: read RAM, bank 1, writes on — and bank $e0's card // RAM is what a read of $e0/d000 reaches now. _ = cpu.memory.read(0x00c08b, .data); _ = cpu.memory.read(0x00c08b, .data); try testing.expect(cpu.memory.mega2.card_switches.read_ram); try testing.expect(!cpu.memory.mega2.card_switches.bank2); cpu.memory.write(0xe0d000, 0x5a, .data); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(0xe0d000, .data)); // The two banks' cards are the same switches over different RAM. cpu.memory.write(0x00d000, 0xa5, .data); try testing.expectEqual(@as(u8, 0xa5), cpu.memory.read(0x00d000, .data)); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(0xe0d000, .data)); // Thrown from bank $e1, as the ROM does at $ff/1df7: bank 2 for all four. _ = cpu.memory.read(0xe1c083, .data); _ = cpu.memory.read(0xe1c083, .data); try testing.expect(cpu.memory.mega2.card_switches.bank2); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0x00c011, .data) & 0x80); // And the State register, which the ROM's interrupt manager writes on // every interrupt with RDROM set, puts all four banks back on the ROM. cpu.memory.write(0x00c068, 0x08, .data); try testing.expect(!cpu.memory.mega2.card_switches.read_ram); try testing.expectEqual(cpu.memory.read(0x00d123, .data), cpu.memory.read(0xe0d123, .data)); } test "the fast side's high memory is ROM until the card says otherwise" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); rom[bank_size + 0xf8b0] = 0x60; // something recognisable in the firmware try cpu.memory.loadROM(rom); // With the card reading ROM -- which is how a machine comes up -- bank // $00's high memory is this machine's own firmware. That is the whole // trick: emulation-mode code runs at $00:f8b0 and finds the same bytes it // would at $ff:f8b0. try testing.expectEqual(@as(u8, 0x60), cpu.memory.read(0x00f8b0, .data)); // Writing still reaches the RAM behind it, because write enabling survives // a reset and reading ROM does not stop it. cpu.memory.write(0x00f8b0, 0xa5, .data); try testing.expectEqual(@as(u8, 0x60), cpu.memory.read(0x00f8b0, .data)); // Switch the card to read RAM and the byte written comes back. _ = cpu.memory.read(0x00c083, .data); _ = cpu.memory.read(0x00c083, .data); try testing.expectEqual(@as(u8, 0xa5), cpu.memory.read(0x00f8b0, .data)); // And bank $01's card is bank $01's RAM, not bank $00's: the banks are // addressed directly here, so there is no ALTZP to ask. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x01f8b0, .data)); } test "the $d000 window is two banks, and the second is the one behind the I/O space" { // Which of the two four-kilobyte blocks is which is settled twice by the // Hardware Reference (Apple Computer, Inc., 1989a), and observably: with // the I/O space inhibited, $c000 to $cfff is plain RAM, and it is the same // block the $c080 switches put in the $d000 window. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Read RAM, write RAM, and bit 3 clear: the block at $c000. _ = cpu.memory.read(0x00c083, .data); _ = cpu.memory.read(0x00c083, .data); try testing.expect(cpu.memory.mega2.card_switches.bank2); cpu.memory.write(0x00d000, 0x11, .data); // The other bank, bit 3 set, is the block at $d000 and is different memory. _ = cpu.memory.read(0x00c08b, .data); _ = cpu.memory.read(0x00c08b, .data); try testing.expect(!cpu.memory.mega2.card_switches.bank2); cpu.memory.write(0x00d000, 0x22, .data); try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(0x00d000, .data)); // Now inhibit the I/O space, and $c000 is contiguous RAM. What is there is // the first byte written, which proves which block that switch chose. cpu.memory.write(0x00c035, TestMemory.inhibit_io_language_card, .data); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(0x00c000, .data)); try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(0x00d000, .data)); } test "inhibiting the I/O space makes the bank sixty-four kilobytes of RAM" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); rom[bank_size + 0xc100] = 0x5a; // slot ROM try cpu.memory.loadROM(rom); // With it enabled -- the state a reset leaves -- $c100 is slot ROM and // $c010 is a soft switch the Mega II answers. try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(0x00c100, .data)); try testing.expect(cpu.memory.decode(0x00c010, false) == .mega); // Inhibited, there is neither: RAM from $0000 to $ffff, and it is fast. cpu.memory.write(0x00c035, TestMemory.inhibit_io_language_card, .data); cpu.memory.write(0x00c100, 0x77, .data); try testing.expectEqual(@as(u8, 0x77), cpu.memory.read(0x00c100, .data)); try testing.expect(cpu.memory.decode(0x00c010, false) == .ram); try testing.expect(cpu.memory.decode(0x00f000, false) == .ram); // And the Mega II's own I/O space is never affected by this bit. try testing.expect(cpu.memory.decode(0xe0c010, false) == .mega); } test "the seven slot pages are slots and the expansion ROM is not" { // $c100 to $c7ff is one page per slot; $c800 to $cfff is the expansion // ROM, which is shared between whichever card was last selected and is // this machine's own firmware when no card was. Asking the slot question // of an address up there is how this went wrong: truncating $cf00's page // to three bits gives slot 7, so pointing slot 7 at a card that is not // there made the whole of $cf00 to $cfff read as nothing -- and the // firmware, which runs from up there, ran off into it. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); rom[bank_size + 0xc700] = 0x77; // slot 7's page rom[bank_size + 0xcf00] = 0xcf; // and the expansion ROM try cpu.memory.loadROM(rom); // Point every slot at a card, and there are no cards. cpu.memory.write(0x00c02d, 0xff, .data); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c700, .data)); // But the expansion ROM is not a slot and is still there. try testing.expectEqual(@as(u8, 0xcf), cpu.memory.read(0x00cf00, .data)); try testing.expectEqual(@as(u8, 0xcf), cpu.memory.read(0xe0cf00, .data)); } test "any Apple II card goes in a slot, and the Slot register gates it" { // The seven slots hold Apple II cards through the same apparatus the // eight-bit machines use, not only the SCSI card that was the first one // this machine could be given. A Disk II controller stands in for the // rest — a card with no built-in of this machine's behind it. It answers // at its page and its device selects when the Slot register points slot 5 // at a card, and the machine's own firmware answers when it does not. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); // A byte in slot 5's own firmware page, so "the machine answers" shows. rom[bank_size + 0xc500] = 0x55; try cpu.memory.loadROM(rom); // A controller with a recognisable boot PROM, unlike anything in the ROM. var prom: [0x100]u8 = @splat(0); prom[0x00] = 0xa2; prom[0xff] = 0x5c; try cpu.memory.slots.fit(5, .{ .disk = .{ .rom = &prom } }); // Slot 5 pointed at the card: its page is the card's, and its device // selects reach the controller — $c0d9 is slot 5's motor-on, and the // controller notices, which is the whole of the device-select path. cpu.memory.write(0x00c02d, @as(u8, 1) << 5, .data); try testing.expectEqual(@as(u8, 0xa2), cpu.memory.read(0x00c500, .data)); try testing.expectEqual(@as(u8, 0x5c), cpu.memory.read(0x00c5ff, .data)); try testing.expect(!cpu.memory.slots.cards[5].disk.drives.motor); _ = cpu.memory.read(0x00c0d9, .data); try testing.expect(cpu.memory.slots.cards[5].disk.drives.motor); // Slot 5 pointed back at the machine's own firmware: the card is silent // and this machine's ROM answers the page. cpu.memory.write(0x00c02d, 0x00, .data); try testing.expectEqual(@as(u8, 0x55), cpu.memory.read(0x00c500, .data)); } test "the card's status reads say the same thing from every bank" { // $c011 and $c012 say which bank the window is showing and whether it is // showing RAM. There is one card, so they say the same thing whichever // bank they are read in and whichever bank moved it — which is what the // ROM routine that saves the State register from bank $e1 and restores it // from bank $00 needs them to. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Thrown from the Mega II's bank: bank 1, reading RAM. _ = cpu.memory.read(0xe1c08b, .data); _ = cpu.memory.read(0xe1c08b, .data); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0xe1c011, .data) & 0x80); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0xe1c012, .data) & 0x80); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00c011, .data) & 0x80); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0x00c012, .data) & 0x80); // Thrown from bank $00: bank 2, reading RAM, and both banks say so. _ = cpu.memory.read(0x00c083, .data); _ = cpu.memory.read(0x00c083, .data); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0x00c011, .data) & 0x80); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0x00c012, .data) & 0x80); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0xe1c011, .data) & 0x80); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(0xe1c012, .data) & 0x80); } test "the latch speaks for odd banks, and an even one still asks the switches" { // The Hardware Reference's sentence is careful (Apple Computer, Inc., // 1989): with the latch set, an // *odd* bank address reaches the Mega II's auxiliary memory "without using // the soft switches". It claims nothing about an even one. // // Reading it as a rule about the bank's low bit either way makes // eighty-column text impossible, because the firmware writes it by // toggling PAGE2 between halves while writing to $0400 in bank $00. The // machine gave that away exactly: nine hundred and seventy-four characters // in the main half and not one in the auxiliary. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c029, TestMemory.bank_latch, .data); // the latch cpu.memory.write(0x00c001, 0, .data); // 80STORE on // With PAGE2 clear, a shadowed write to bank $00 lands in the main half. _ = cpu.memory.read(0x00c054, .data); cpu.memory.write(0x000400, 0xc1, .data); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.mega2.halfTarget(false, 0x0400, false).?.*); try testing.expectEqual(@as(u8, 0x00), cpu.memory.mega2.halfTarget(true, 0x0400, false).?.*); // With PAGE2 set it lands in the auxiliary half -- from the same bank and // the same address, which is the whole of how eighty columns are written. _ = cpu.memory.read(0x00c055, .data); cpu.memory.write(0x000400, 0xc2, .data); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.mega2.halfTarget(false, 0x0400, false).?.*); try testing.expectEqual(@as(u8, 0xc2), cpu.memory.mega2.halfTarget(true, 0x0400, false).?.*); // Whereas the odd bank is the auxiliary half whatever PAGE2 says, which is // what the latch is for. _ = cpu.memory.read(0x00c054, .data); // PAGE2 clear again cpu.memory.write(0x010400, 0xc3, .data); try testing.expectEqual(@as(u8, 0xc3), cpu.memory.mega2.halfTarget(true, 0x0400, false).?.*); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.mega2.halfTarget(false, 0x0400, false).?.*); // And the same holds for reaching the Mega II's banks directly. try testing.expectEqual(@as(u8, 0xc3), cpu.memory.read(0xe10400, .data)); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.read(0xe00400, .data)); } test "an enabled interrupt is one the processor actually takes" { // The line going up is half of it; the other half is the processor // noticing. This runs the machine rather than reading the register, which // is the only way to tell the two apart. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); // An emulation-mode interrupt vectors through $fffe, and this machine // reads that from its own ROM at power-on. rom[bank_size + 0xfffe] = 0x00; rom[bank_size + 0xffff] = 0x40; try cpu.memory.loadROM(rom); cpu.reset(); // A program that does nothing, at a place a test can recognise. cpu.registers.program_bank = 0; cpu.program_counter.value = 0x0300; for (0..64) |i| cpu.memory.poke(@intCast(0x000300 + i), 0xea); // NOP cpu.flags.clear(.I); cpu.memory.write(0x00c041, TestMemory.Interrupts.vbl_bit, .data); // Put the beam a few cycles from the bottom of the screen. A frame is // fifty thousand cycles and a NOP is two, so without this the machine // would have to run for a quarter of a million of them to reach one. cpu.clock.cycles = Memory16.cycles_per_frame - Memory16.blanking_cycles - 4; // Run until the beam reaches the bottom of the screen, which on this // machine is what asks for the line. var steps: usize = 0; while (steps < 64 and cpu.program_counter.value < 0x4000) : (steps += 1) { try cpu.executeInstruction(); } // It vectored, and the flag says why. try testing.expectEqual(@as(u16, 0x4000), cpu.program_counter.value); try testing.expect(cpu.memory.interrupts.vbl); try testing.expect(cpu.irq); // The handler owns up, and the line goes down before the next instruction. _ = cpu.memory.read(0x00c047, .data); try testing.expect(!cpu.irq); } test "interrupt vectors come from the ROM whatever the language card is doing" { // The Firmware Reference (Apple Computer, Inc., 1987a, Chapter 8): "If I/O // shadowing is on, the vectors contained in ROM are always used by the // 65C816, regardless of the language-card settings." GS/OS relies on it. // Its loader switches the language card to RAM with interrupts enabled and // block-moves into banks $e0 and $e1, and a vertical blanking interrupt in // the middle of the move went to $00/0000 through a vector read from RAM // that nothing had written yet. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); rom[bank_size + 0xfffe] = 0x00; rom[bank_size + 0xffff] = 0x40; try cpu.memory.loadROM(rom); cpu.reset(); // Switch the language card to RAM, reading and writing, the way GS/OS // does, and leave that RAM holding what it holds — which is nothing. _ = cpu.memory.read(0x00c08b, .data); _ = cpu.memory.read(0x00c08b, .data); try testing.expect(cpu.memory.mega2.card_switches.read_ram); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00ffff, .data)); // A vector pull is a different kind of cycle, and it reaches the ROM. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(0x00fffe, .vector)); try testing.expectEqual(@as(u8, 0x40), cpu.memory.read(0x00ffff, .vector)); // With I/O shadowing off the bank is RAM from end to end, vectors // included: the operating system "must copy the ROM vectors from $FFEE to // $FFFF and the code from $C071 to $C07F into RAM at the same locations // before enabling interrupts." cpu.memory.write(0x00c035, TestMemory.inhibit_io_language_card, .data); cpu.memory.write(0x00fffe, 0x00, .data); cpu.memory.write(0x00ffff, 0x50, .data); try testing.expectEqual(@as(u8, 0x50), cpu.memory.read(0x00ffff, .vector)); } test "a scan line interrupts when its control byte says to" { // The one interrupt in this machine whose source is a byte in memory // rather than a register: each of the two hundred Super Hi-Res lines has // a control byte, and bit 6 of it asks for an interrupt as the beam // reaches that line. So what interrupts, and when, is part of the picture. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // The bank latch first, or nothing written to bank $e1 lands there: with // it clear the old soft switches decide which half of the Mega II an odd // bank reaches, and they point at the main one. Software that uses this // display sets the latch, and the machine's own firmware comes up with it // set. It is the same seam as ever, and it catches everything once. const showing = vgc_module.Vgc.super_hires | vgc_module.Vgc.bank_latch; cpu.memory.write(0x00c029, vgc_module.Vgc.bank_latch, .data); // Line 100 asks; nothing else does. cpu.memory.write(0xe10000 + superhires.control_bytes + 100, 0x40, .data); cpu.memory.write(0x00c023, TestMemory.Vgc.scan_line_enable, .data); // With the old video on the screen the control bytes are just memory: // the controller has not got the buffer and is drawing nothing. cpu.clock.cycles = Memory16.cycles_per_frame; _ = cpu.memory.read(0x000000, .data); try testing.expect(!cpu.memory.vgc.scan_line); try testing.expect(!cpu.irq); // Hand it the memory and the same frame raises it. cpu.memory.write(0x00c029, showing, .data); try testing.expect(cpu.memory.superHiRes()); cpu.clock.cycles += Memory16.cycles_per_frame; _ = cpu.memory.read(0x000000, .data); try testing.expect(cpu.memory.vgc.scan_line); try testing.expect(cpu.irq); // It is cleared where every other video interrupt is, by writing a zero // into its bit at $c032, and the line goes down with it. cpu.memory.write(0x00c032, 0xff & ~TestMemory.Vgc.scan_line_status, .data); try testing.expect(!cpu.memory.vgc.scan_line); try testing.expect(!cpu.irq); // And a line that does not ask does not raise it, however many go by. cpu.memory.write(0xe10000 + superhires.control_bytes + 100, 0x00, .data); cpu.clock.cycles += Memory16.cycles_per_frame * 10; _ = cpu.memory.read(0x000000, .data); try testing.expect(!cpu.memory.vgc.scan_line); } test "the beam is not walked further back than one frame" { // A clock that jumps a long way must not cost a walk proportional to the // jump: every line has been crossed already, and looking at them again // says nothing new. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c029, vgc_module.Vgc.super_hires | vgc_module.Vgc.bank_latch, .data); cpu.memory.write(0xe10000 + superhires.control_bytes + 5, 0x40, .data); // A thousand frames in one step still finds it, exactly once. cpu.clock.cycles = Memory16.cycles_per_frame * 1000; _ = cpu.memory.read(0x000000, .data); try testing.expect(cpu.memory.vgc.scan_line); try testing.expectEqual( cpu.clock.cycles / Memory16.cycles_per_line, cpu.memory.scan_lines, ); } test "a waveform written through the four registers is a waveform that plays" { // The whole sound path from the processor's side: the only way to reach // the Ensoniq is through $c03c to $c03f, so a test that pokes the chip // directly proves nothing about the machine. This writes a waveform into // the chip's own RAM and starts an oscillator on it exactly as a program // would, then runs the machine and listens. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); const rom = try testRom(testing.allocator, .ascending); defer testing.allocator.free(rom); try cpu.memory.loadROM(rom); cpu.reset(); const control = 0x00c03c; const data = 0x00c03d; const pointer_low = 0x00c03e; const pointer_high = 0x00c03f; // A page of the sound RAM, filled with a square wave well clear of zero, // since a zero byte is what stops an oscillator. Bit 6 set is the RAM and // bit 5 is auto-incrementing, which is what makes this a loop and not 256 // pointer writes. cpu.memory.write(control, 0x60, .data); cpu.memory.write(pointer_low, 0x00, .data); cpu.memory.write(pointer_high, 0x10, .data); for (0..256) |i| cpu.memory.write(data, if (i < 128) 0xe0 else 0x20, .data); // Then the oscillator's registers, which are the chip's own and so are // reached with bit 6 clear. cpu.memory.write(control, 0x20, .data); cpu.memory.write(pointer_high, 0x00, .data); const set = struct { fn reg(memory: anytype, which: u8, value: u8) void { memory.write(pointer_low, which, .data); memory.write(data, value, .data); } }.reg; // Auto-incrementing would walk on after each write, so the pointer is set // for every register. cpu.memory.write(control, 0x00, .data); set(&cpu.memory, 0xe1, 1 << 1); // one oscillator running set(&cpu.memory, 0x80, 0x10); // the page the waveform is on set(&cpu.memory, 0xc0, 0x00); // 256 bytes, address bus resolution nought set(&cpu.memory, 0x40, 0xff); // full volume set(&cpu.memory, 0x00, 0x00); // and a frequency of 512, which is a byte set(&cpu.memory, 0x20, 0x02); // of the table for every pass set(&cpu.memory, 0xa0, 0x00); // free running, and not halted // A program that does nothing, round and round, so that the machine's // clock moves and the chip is wound forward by the accesses rather than by // the test. cpu.registers.program_bank = 0; cpu.program_counter.value = 0x0300; for (0..0xfd) |i| cpu.memory.poke(@intCast(0x000300 + i), 0xea); // NOP cpu.memory.poke(0x0003fd, 0x4c); // JMP $0300 cpu.memory.poke(0x0003fe, 0x00); cpu.memory.poke(0x0003ff, 0x03); cpu.flags.set(.I); // Long enough to get well past the middle of the table, where the square // wave changes sides. A pass of the chip is about ten of the machine's // cycles and a NOP is two, so half a table is some six hundred and fifty // instructions; this is several times round. var loudest: i16 = 0; var quietest: i16 = 0; for (0..8_000) |_| { try cpu.executeInstruction(); const sample = cpu.memory.doc.take(); loudest = @max(loudest, sample); quietest = @min(quietest, sample); } // It swung both ways, which a square wave does and silence does not. try testing.expect(loudest > 1_000); try testing.expect(quietest < -1_000); // And the oscillator is still going: nothing in a table of $e0 and $20 can // halt it, so a halted one would mean the end of the table was found where // there is none. try testing.expectEqual( @as(u8, 0), cpu.memory.doc.reg(.control, 0) & ensoniq.control_halt, ); } test "a machine with nothing in its expansion slot has nothing above bank one" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); try testing.expectEqual(@as(u16, TestMemory.stock_banks), cpu.memory.banks()); // Bank $02 is where a card's memory would start. Without one, writing // there goes nowhere and reading it gives nothing back — which is exactly // what the firmware's memory sizing is looking for when it decides how // much RAM the machine has. cpu.memory.write(0x02_0000, 0xa5, .data); try testing.expectEqual(@as(u8, 0), cpu.memory.read(0x02_0000, .data)); } test "a memory expansion card is RAM that answers, and nothing else" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); // Sixteen banks altogether, which is a megabyte of fast RAM. try cpu.memory.expand(16); try testing.expectEqual(@as(u16, 16), cpu.memory.banks()); // Every bank of it holds what is put in it, and holds it separately: a // card that mirrored one bank into all of them would look like memory to a // program writing and reading one address, and like nothing at all to the // firmware sizing it. for (2..16) |bank| { const at: u24 = @intCast(bank << 16 | 0x1234); cpu.memory.write(at, @intCast(bank), .data); } for (2..16) |bank| { const at: u24 = @intCast(bank << 16 | 0x1234); try testing.expectEqual(@as(u8, @intCast(bank)), cpu.memory.read(at, .data)); } // And it stops where the card stops. Bank $10 is one past the end. cpu.memory.write(0x10_0000, 0x5a, .data); try testing.expectEqual(@as(u8, 0), cpu.memory.read(0x10_0000, .data)); } test "expansion memory is plain memory: no switches, no shadowing" { // Everything that makes banks $00 and $01 complicated — the language card, // the soft switches, the auxiliary rule, shadowing into the Mega II — is // about those two banks. A card's banks are sixty-four kilobytes of RAM // with nothing in the way, including where the I/O space would be. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); try cpu.memory.expand(4); for ([_]u16{ 0x0000, 0x0400, 0xc000, 0xc030, 0xd000, 0xffff }) |within| { const at: u24 = @as(u24, 0x02) << 16 | within; cpu.memory.write(at, 0x77, .data); try testing.expectEqual(@as(u8, 0x77), cpu.memory.read(at, .data)); } // $c030 in bank $02 being memory rather than the speaker is the case worth // stating outright: the same address in bank $00 is a soft switch, and // writing it there stores nothing at all. cpu.memory.write(0x00_c030, 0x77, .data); try testing.expect(cpu.memory.read(0x00_c030, .data) != 0x77); } test "fitting a card leaves what was already in memory alone" { var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00_0800, 0x11, .data); cpu.memory.write(0x01_0800, 0x22, .data); try cpu.memory.expand(8); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(0x00_0800, .data)); try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(0x01_0800, .data)); // And a card cannot be smaller than the machine's own memory, nor bigger // than the address space: asking for either gives what is possible. try cpu.memory.expand(0); try testing.expectEqual(@as(u16, TestMemory.stock_banks), cpu.memory.banks()); try cpu.memory.expand(1000); try testing.expectEqual(@as(u16, TestMemory.max_banks), cpu.memory.banks()); } test "the border colour is the low nibble of $c034 and the clock keeps the rest" { const gpa = testing.allocator; const cpu = try gpa.create(TestCPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit(); // "Bits 3-0: border color", "bits 7-4: real-time clock control bits: do // not modify bits 7-4 when changing bits 3-0" (Apple Computer, Inc., // 1989a, Table 4-12, p. 82). One register, two things. cpu.memory.write(0x00c034, 0x06, .data); try testing.expectEqual(@as(u4, 6), cpu.memory.rtc.border); try testing.expectEqual(video.palette[6], cpu.memory.borderColour()); // The sixteen are the machine's own, not a Super Hi-Res palette entry: a // palette is per scan line and belongs to the picture, and the border is // not in the picture. Black and white are the two ends of that table. cpu.memory.write(0x00c034, 0x00, .data); try testing.expectEqual(video.palette[0], cpu.memory.borderColour()); cpu.memory.write(0x00c034, 0x0f, .data); try testing.expectEqual(video.palette[15], cpu.memory.borderColour()); // And it reads back where it was written, with the clock's bits beside it // rather than instead of it. try testing.expectEqual(@as(u8, 0x0f), cpu.memory.read(0x00c034, .data) & 0x0f); } test "a slow access costs a slow cycle plus however much of one was left" { // "If a single (8-bit) slow I/O read or write cycle is perfectly // synchronized, it takes nearly three fast cycles to complete... If either // a single or double slow cycle is not synchronized, the maximum delay for // synchronization is one extra slow cycle" (Apple Computer, Inc., 1989a, // p. 25). The mechanism is that the processor is held until the Mega II // will begin a cycle, so what it costs is the distance to that boundary // plus the cycle itself. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c036, TestMemory.speed_fast, .data); // Arriving on a boundary is the synchronised case, and costs the slow // cycle and nothing more. for (0..slow_cycle) |phase| { cpu.clock.cycles = 300 + phase; const before = cpu.clock.read(); _ = cpu.memory.read(0x00c000, .data); // the keyboard, on the slow side const spent = cpu.clock.read() - before; const expected: u64 = if (phase == 0) slow_cycle else slow_cycle + (slow_cycle - phase); try testing.expectEqual(expected, spent); // Never less than a slow cycle and never more than two, which is the // manual's best and worst case. try testing.expect(spent >= slow_cycle and spent < 2 * slow_cycle); } // And a run of them stays in step, because each one lands the clock back // on a boundary. This is why an instruction that is all slow accesses // costs what the manual's synchronised case says and no more. cpu.clock.cycles = 0; for (0..4) |_| { const before = cpu.clock.read(); _ = cpu.memory.read(0x00c000, .data); try testing.expectEqual(@as(u64, slow_cycle), cpu.clock.read() - before); } // A fast access is what knocks it out of step, and the next slow one pays // for it. Fast RAM in bank 2, which nothing shadows. cpu.clock.cycles = 0; _ = cpu.memory.read(0x020000, .data); try testing.expectEqual(@as(u64, 1), cpu.clock.read()); const before = cpu.clock.read(); _ = cpu.memory.read(0x00c000, .data); try testing.expectEqual(@as(u64, slow_cycle + slow_cycle - 1), cpu.clock.read() - before); } test "a machine held at 1.024 MHz has no synchronising to do" { // With the speed register asking for the slow clock the whole machine is // the Mega II's, so there is no boundary to wait for: every access is one // slow cycle whenever it arrives. var cpu: TestCPU = undefined; try cpu.init(testing.allocator, null); defer cpu.deinit(); cpu.memory.write(0x00c036, 0x00, .data); // slow for (0..slow_cycle) |phase| { cpu.clock.cycles = 500 + phase; const before = cpu.clock.read(); _ = cpu.memory.read(0x00c000, .data); try testing.expectEqual(@as(u64, slow_cycle), cpu.clock.read() - before); } } test "a IIgs draws its text in the Screen Color register's colours, unless it is in black and white" { const gpa = testing.allocator; const cpu = try gpa.create(TestCPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit(); // "The most significant 4 bits determine the text color. Second, the // least significant 4 bits determine the background color" (Apple // Computer, Inc., 1989a, p. 81, and Table 4-11). White on medium blue is // what the firmware writes here on the way up, and what a IIgs looks like. cpu.memory.write(0x00c022, 0xf6, .data); const colours = cpu.memory.mega2.textColour(40, 0x400, 0).?; try testing.expectEqual(@as(u4, 15), colours.foreground); try testing.expectEqual(@as(u4, 6), colours.background); // One pair for the whole screen: the arguments do not matter. const elsewhere = cpu.memory.mega2.textColour(80, 0x800, 39).?; try testing.expectEqual(colours.foreground, elsewhere.foreground); // Bit 7 of the Monochrome/Color register: "video displays in // black-and-white" (Table 4-12, p. 83), so there is no colour to give and // the text falls back to dots. cpu.memory.write(0x00c021, 0x80, .data); try testing.expect(cpu.memory.mega2.textColour(40, 0x400, 0) == null); cpu.memory.write(0x00c021, 0x00, .data); try testing.expect(cpu.memory.mega2.textColour(40, 0x400, 0) != null); } test "a IIgs round-trips through a snapshot, Mega II and all" { const alloc = testing.allocator; var cpu: TestCPU = undefined; try cpu.init(alloc, null); defer cpu.deinit(); // A byte of fast RAM, a byte of the Mega II's slow RAM through the same // machine, a soft switch, and the processor. cpu.memory.fast[0x012345] = 0x9a; cpu.memory.mega2.main.ram[0x0400] = 0x3c; cpu.memory.vgc.new_video = 0x41; cpu.registers.set(.A, 0x1234); cpu.clock.cycles = 555_000; const saved = try snapshot.save(alloc, &cpu); defer alloc.free(saved); cpu.memory.fast[0x012345] = 0; cpu.memory.mega2.main.ram[0x0400] = 0; cpu.memory.vgc.new_video = 0; cpu.registers.set(.A, 0); cpu.clock.cycles = 0; try snapshot.load(alloc, saved, &cpu); try testing.expectEqual(@as(u8, 0x9a), cpu.memory.fast[0x012345]); try testing.expectEqual(@as(u8, 0x3c), cpu.memory.mega2.main.ram[0x0400]); try testing.expectEqual(@as(u8, 0x41), cpu.memory.vgc.new_video); try testing.expectEqual(@as(u16, 0x1234), cpu.registers.get(.A)); try testing.expectEqual(@as(u64, 555_000), cpu.clock.cycles); // The Mega II still points back at this very machine — the pointer was // left live rather than restored to a stale address. try testing.expectEqual(&cpu, cpu.memory.mega2.host); }