// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT const std = @import("std"); const bus_log = @import("bus.zig"); const Options = bus_log.Options; const disk2 = @import("../disk2.zig"); const disk35 = @import("../disk35.zig"); const unidisk_device = @import("../unidisk.zig"); const languagecard = @import("../languagecard.zig"); const font = @import("../font.zig"); const screen = @import("../screen.zig"); const speaker = @import("../speaker.zig"); const cassette = @import("../cassette.zig"); const mc6840 = @import("../mc6840.zig"); const mc6850 = @import("../mc6850.zig"); const w5100 = @import("../w5100.zig"); const cs8900 = @import("../cs8900.zig"); const serial = @import("../serial.zig"); const snapshot = @import("../snapshot.zig"); const blockdevice = @import("../blockdevice.zig"); const clockcard = @import("../clockcard.zig"); const parallel = @import("../parallel.zig"); const mouse = @import("../mouse.zig"); const mockingboard = @import("../mockingboard.zig"); const phasor = @import("../phasor.zig"); const soundspeech = @import("../soundspeech.zig"); const sc01 = @import("../sc01.zig"); const omninet = @import("../omninet.zig"); const videx = @import("../videx.zig"); const ultraterm = @import("../ultraterm.zig"); const ramfactor = @import("../ramfactor.zig"); const slot_module = @import("../slots.zig"); /// What `videxCharsets` answers with when there is no eighty-column card: a /// generator with nothing in it, so that a caller drawing a screen that is not /// there draws blanks rather than reading past the end of nothing. const blank_charset: [videx.charset_size]u8 = @splat(0); const iwm = @import("../iwm.zig"); const mig_chip = @import("../mig.zig"); /// Video timing. The IIe draws a scan line every 65 cycles and a frame every /// 262 lines, which is where the machine's 1.0205MHz clock and its 59.94Hz /// frame rate both come from. Lines 0 to 191 are displayed and 192 to 261 are /// the vertical blanking interval. /// How fast the machine's own clock runs. A IIe's crystal gives 1.0205MHz, /// which is what paces a tape being played in. pub const cycles_per_second = 1_020_500; const cycles_per_line = 65; const lines_per_frame = 262; const displayed_lines = 192; const cycles_per_frame = cycles_per_line * lines_per_frame; const blanking_cycles = cycles_per_line * (lines_per_frame - displayed_lines); const ram_size = 0xc000; const rom_size = 0x4000; /// Where the Disk II lives. Slot 6 by convention and by almost universal /// practice: its switches are the sixteen at $c0e0 and its ROM is the page at /// $c600, which is the one the machine looks in first for something to start /// from. /// How long a paddle's timer runs, in cycles for each unit of its position. /// /// The Monitor reads a paddle by starting the timer and counting round an /// eleven cycle loop until it runs down, so eleven cycles is one unit. The ten /// on the end is the ten cycles that go by between the trigger and the loop's /// first look, and putting it in is what makes the machine read back the /// number that was set rather than one less than it. /// /// The Apple IIe Technical Reference Manual and the Monitor's PREAD (Apple /// Computer, Inc., 1985, Chapter 2). const paddle_cycles_per_unit = 11; const paddle_cycles_before_first_look = 10; /// Where the Super Serial Card lives. Slot 2 by convention: that is where a /// modem went, and where software looks for one. /// Where the block device lives: slot 7, which is where ProDOS looks for a /// hard disk and the slot the machine tries first when it starts. const block_slot = 7; const block_rom_base = 0xc000 + block_slot * 0x100; /// Where a Corvus Omninet Transporter goes, which is the same slot as the /// block device above: "The network interface card should be in slot 7, as /// described in Chapter 1" (Corvus Systems, 1987). Only one card fits in a /// slot, so fitting either takes the other out. const transporter_slot = block_slot; const transporter_rom_base = block_rom_base; const transporter_switch_base = 0x80 + transporter_slot * 0x10; /// The card's `$Cn00` PROM, which is Corvus's code and so is loaded rather /// than built here. const transporter_rom_size = 0x100; const block_switch_base = 0x80 + block_slot * 0x10; /// The card's own firmware, which is ours rather than Apple's: the protocol is /// published, so nothing has to be supplied for this card to work. const block_firmware = blockdevice.firmware(block_slot); /// The IIc's other serial port, where slot 1's card would have been: the one /// marked with a printer. Its four registers sit at $c098, the same place a /// card in that slot would have put them. const printer_slot = 1; const printer_switch_base = 0x80 + printer_slot * 0x10; const serial_slot = 2; const serial_rom_size = 0x800; /// Which page of the card's two kilobytes answers at $c200. The rest of it is /// the expansion ROM at $c800, and the last page of it is the one the machine /// finds when it looks in the slot. const serial_rom_page = 0x700; const serial_rom_base = 0xc000 + serial_slot * 0x100; const serial_switch_base = 0x80 + serial_slot * 0x10; /// Where the mouse lives: slot 4, which is where the card went and where the /// software that uses one looks for it. /// Slot 3, which on a IIe is not an ordinary slot. The machine's own /// eighty-column firmware lives in its page, and SLOTC3ROM decides which of /// the two answers there — an arrangement the II Plus had no need of, its /// slot 3 being empty and its machine having no eighty-column anything. /// /// This is a property of the *page* and not of whatever is plugged into slot /// 3: any card there is subject to it, and an eighty-column card somewhere /// else is not. `slotsAnswerAt` is where that is decided, and this is the one /// address it names. const internal_slot_three = 0xc000 + 3 * 0x100; /// And where an eighty-column card happens to go, which is the same slot /// because that is where the software looks for one. const videx_slot = 3; const videx_rom_base = 0xc000 + videx_slot * 0x100; const videx_switch_base = 0x80 + videx_slot * 0x10; const videx_firmware_at = 0xc800; const videx_window_at = 0xcc00; const videx_unused_at = 0xce00; const mouse_slot = 4; const mouse_rom_base = 0xc000 + mouse_slot * 0x100; const mouse_switch_base = 0x80 + mouse_slot * 0x10; /// Ours again: what a mouse card answers to is published. const mouse_firmware = mouse.firmware(mouse_slot); /// The Mockingboard goes in slot 4 as well, which is where the software that /// plays through one looks for it. A slot holds one card, so a machine has /// either this or the mouse and not both, exactly as a real one would. const mockingboard_rom_base = mouse_rom_base; /// Where the clock lives. Any slot will do — ProDOS looks through all of /// them — so it takes slot 5, which is the free one: 2 is the serial card, 4 /// is where a mouse goes, 6 is the disk and 7 the hard disk. /// Where a parallel printer card goes: slot 1, which is the slot the card /// went in and the slot `PR#1` reaches. Its latch is at `$c090`, which is the /// `$C080 + N*16` the card's manual gives. const parallel_slot = 1; const parallel_rom_base = 0xc000 + parallel_slot * 0x100; const parallel_switch_base = 0x80 + parallel_slot * 0x10; /// Ours, like the clock's: the card is a latch and eight wires, and what the /// firmware in front of it has to do is published. const parallel_firmware = parallel.firmware(parallel_slot); const clock_slot = 5; const clock_rom_base = 0xc000 + clock_slot * 0x100; const clock_switch_base = 0x80 + clock_slot * 0x10; /// Ours, like the block device's: what a clock card has to do is published. const clock_firmware = clockcard.firmware(clock_slot); /// And where a memory expansion card goes, which is the same slot: a slot /// holds one card, so a machine has either the clock or the megabyte and not /// both, exactly as a real one would. /// /// Slot 5 because the card's own manual leaves the choice open and then /// narrows it — insert it "in any expansion slot except slot 3", and "if you /// will be using Pascal 1.3, install the RamFactor in slots 4, 5, or 6" /// (Applied Engineering, n.d.-a, Chapter 1) — and because slot 5 is /// the one this machine has nothing else it must be: 2 is the serial card, 3 /// the eighty column card, 4 the mouse, 6 the disk and 7 the hard disk. It is /// also what makes the volume `/RAM5`, which is what the card was called on /// the machines that had one. const memory_card_slot = clock_slot; const memory_card_rom_base = clock_rom_base; /// Where a IIc's memory expansion card answers instead, which is not a slot /// at all: the card goes in the connector inside the case, and its registers /// are fixed where a slot 4 card's would be. "The memory expansion card has a /// 20-bit address register and a 1-byte data register. The data register is /// used to read or write data at the location pointed to by the address /// register. Because the address register automatically increments after each /// access of the data register... The memory expansion card's registers are: /// $C0C0 low byte of the address register; $C0C1 middle byte; $C0C2 high /// nibble (D3-D0) of the address register; $C0C3 data register" (Apple /// Computer, Inc., 1987b, p. 7). /// /// Four registers and not sixteen, and no firmware page above them: the /// driver that works the card is in the machine's own ROM, in the second bank /// that `$C028` switches in, rather than on the card. That is the whole /// difference between this and the RamFactor above, which is a card in a slot /// with eight kilobytes of its own. const memory_expansion_switch_base = 0x80 + 4 * 0x10; /// The most a twenty-bit address counter can reach, which is the ceiling the /// card's own sizing routine works up to: it reports `256K`, `512K`, `768K` /// or `1 MEG` and nothing above. const max_memory_expansion = 1024 * 1024; const disk_slot = 6; const card_rom_size = 0x100; const card_rom_base = 0xc000 + disk_slot * card_rom_size; const card_switch_base = 0x80 + disk_slot * 0x10; const bank_size = 0x1000; const high_size = 0x2000; /// One 64K half of the machine's memory: the 48K everything below $c000 comes /// from, and the language card that answers above $d000. There are two of /// these, main and auxiliary, and the switches decide which one any given /// address is talking to. const Half = struct { ram: [ram_size]u8 = undefined, bank: [2][bank_size]u8 = undefined, high: [high_size]u8 = undefined, fn clear(self: *Half) void { self.* = .{ .ram = @splat(0), .bank = @splat(@splat(0)), .high = @splat(0) }; } }; /// One auxiliary memory bank, which is the 64K a RamWorks card adds one of at /// a time. Exposed so that a caller can allocate the banks `fitRamWorks` wants: /// the card's storage belongs to whoever builds the machine, the way a disk /// does, so a machine with no card costs nothing. pub const AuxiliaryBank = Half; /// An Apple IIe with the extended 80-column card fitted, which is to say with /// 128K. /// /// The IIe keeps everything the II Plus did and adds a second 64K behind it. /// Which half an address reaches depends on where it falls and on five /// switches: /// /// - ALTZP moves the zero page, the stack and the language card. /// - RAMRD and RAMWRT move $0200 to $bfff, separately for reading and /// writing, so a program running in one half can store into the other. /// - 80STORE, with PAGE2, moves the text page on its own, and with HIRES /// the high-resolution page as well. It overrides RAMRD and RAMWRT for /// just those windows, which is what makes 80-column text possible. /// /// Cards answer in their own pages between $c100 and $cfff — a parallel /// printer card, a serial card, an eighty-column card, a mouse or a /// Mockingboard, a clock, a Disk II and a block device — and the internal ROM /// answers everywhere else. /// /// Slot 3 is the one that is not like the others, and both of the switches /// this machine has for its I/O space bear on it. INTCXROM takes the whole of /// $c100 to $c7ff away from the slots, "including the $C300 space"; SLOTC3ROM /// decides slot 3 by itself, and a IIe comes up with it off because it always /// has the extended eighty-column card in its auxiliary slot. So the machine's /// own eighty-column firmware is what answers at $c300 until a program asks at /// $c00b for the card instead — which is what software written for a Videoterm /// does, and why a IIe can have one even though it has the columns already. /// /// See the Apple IIe Technical Reference Manual (Apple Computer, Inc., 1985b, /// Tables 4-6 and 4-7). pub fn AppleIIe(comptime options: Options) fn (type) type { return Machine(.iie, options); } /// An Apple IIc, which is this same machine with everything soldered down. /// /// There are no slots: the two serial ports, the mouse, the eighty column /// firmware and the disk drive are all built in, and answer at the addresses /// the cards for them would have answered at. There is no cassette either, and /// the socket its input used is a switch on the keyboard instead. Everything /// else — the banking, the video, the language card, the auxiliary memory — is /// the machine above, which is why they are one piece of code with the /// differences named rather than two that drift apart. /// /// The Apple IIc Technical Reference Manual (Apple Computer, Inc., 1984a) is /// where the differences come from, and the ROM is the thing that decides /// whether they are right. pub fn AppleIIc(comptime options: Options) fn (type) type { return Machine(.iic, options); } /// Which of the two, since almost everything they do is the same. pub const Kind = enum { iie, iic, /// Whether it has slots to put a card in. The IIc has none, so every /// address in $c100 to $cfff answers from its own firmware. pub fn slotted(self: Kind) bool { return self == .iie; } }; /// Which IIe firmware is in the sockets, as its identification byte says. /// A text colour and the background it sits on, each one of the sixteen. pub const TextColours = struct { foreground: u4, background: u4 }; pub const Firmware = enum { /// The 1983 CD and EF ROMs, 342-0135 and 342-0134: `$EA` at `$fbc0`. original, /// The 1985 enhancement's, 342-0303 and 342-0304: `$E0` at `$fbc0`, with /// the 65C02 and the MouseText character generator that came with them. enhanced, /// Anything else: a IIc's ROM, or an image that is not Apple's. unknown, }; /// Where the firmware says which machine it is: `$FBB3` is `$06` on every IIe /// and IIc, and this byte tells the IIe's two firmwares apart (Apple Computer, /// Inc., 1985b, p. xxix). pub const identification: u16 = 0xfbc0; /// Where a IIc's ROM keeps its version number: `$FF` on the original, `$00` on /// the UniDisk 3.5 revision, `$03`/`$04` on the memory-expansion ones, `$05` on /// the IIc Plus (Apple Computer, Inc., 1985e, Appendix F.1). pub const iic_version: u16 = 0xfbbf; /// What that byte reads on the IIc Plus, which is the machine with the /// multidrive interface glue in it. pub const iic_plus_version: u8 = 0x05; fn Machine(comptime kind: Kind, 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; /// What sits between the processor and the five-and-a-quarter /// mechanism: a Disk II card on a IIe, an IWM on a IIc. The two /// answer the same sixteen switches with the same signature, so /// everything that only throws a switch is written once. pub const DiskPort = if (kind == .iic) iwm.Iwm else disk2.Controller; /// Whether this machine has the memory expansion connector /// inside its case, which only a IIc does. A IIe takes a card /// in a slot instead, and that is a different thing with its /// own firmware on it. pub const has_memory_expansion = kind == .iic; /// The multidrive interface glue, which only the IIc Plus has. /// Whether this machine is one is not known until its ROM is /// loaded — the version byte says — so the chip is here on /// every IIc and answers only when `mig_fitted` says it is /// there. See `mig.zig`. mig: if (kind == .iic) mig_chip.Mig else void = if (kind == .iic) .{} else {}, mig_fitted: bool = false, bus: bus_log.Log(options.bus_log) = .{}, /// The processor, when this model is not embedded in one. Not /// a field at all in the ordinary case, so nothing is carried /// and nothing is dereferenced that was not before. host: if (options.host == .given) ?*CPU else void = if (options.host == .given) null else {}, main: Half = undefined, aux: Half = undefined, /// A RamWorks card's extra auxiliary banks — banks one and up, /// bank zero being `aux` above, the motherboard's own auxiliary /// 64K. Empty until `fitRamWorks` hands over storage the caller /// owns, so a IIe with no card has none and costs nothing. Only /// a IIe takes one: RamWorks is the auxiliary slot's card, and a /// IIc has that slot soldered over. ramworks: if (kind == .iie) []Half else void = if (kind == .iie) &.{} else {}, /// Which auxiliary bank the RamWorks bank register at $C073 last /// chose. Zero is `aux`; a bank past what is fitted reads back /// as zero, the way the card decodes only the banks it has. aux_bank: if (kind == .iie) u8 else void = if (kind == .iie) 0 else {}, // The internal ROM. One 16K bank on most of these machines; a // IIc past the first revision has two, the 32K selected a 16K // half at a time by $C028 (see `softSwitch`). rom: [if (kind == .iic) 2 * rom_size else rom_size]u8 = undefined, /// Which 16K half of a 32K IIc ROM is mapped at $c100-$ffff. /// Zero at reset, so the machine comes up on the main firmware, /// and only ever nonzero on a IIc whose ROM has a second bank. rom_bank: u1 = 0, /// Whether $C028 has a second bank to switch to: true only for a /// IIc given a 32K ROM. On the original 16K IIc the switch is /// reserved and does nothing. banked: bool = false, /// The IIc ROM's version byte at $FBBF — $FF original, $00 /// UniDisk 3.5, $03/$04 memory expansion, $05 the IIc Plus — kept /// so the later variants can gate their firmware's hardware on it. rom_version: u8 = 0xff, /// A IIc's built-in modem port, which is not a card: the same /// 6551 the Super Serial Card had, at the addresses a card in /// slot 2 would have put it, because that is where the /// machine's own firmware looks. A IIe has no such thing and /// takes the card instead — see `slots`. acia: if (kind == .iic) serial.Acia else void = if (kind == .iic) .{ .cycles_per_second = cycles_per_second } else {}, /// Whether the machine has looked to see if anything has come /// in yet. /// /// Nothing here uses it. It is for whoever is feeding the card /// from outside: a byte handed over before the firmware has /// opened the port is thrown away by the programmed reset the /// firmware does on its way in, so something sending a file /// wants to wait until the machine is listening, which is the /// moment it first reads the status register. serial_listening: bool = false, /// Whether the card's interrupt line is connected. /// /// On a real card that is a jumper, and it is normally out. /// The chip comes up with its receiver interrupt enabled, so a /// card wired in by default would pull the line the moment the /// first byte arrived, and the firmware does not put an /// interrupt handler anywhere: the machine would vector /// through whatever happened to be at $fffe and go to pieces, /// which is exactly what it does if this is on. serial_interrupts: bool = false, /// Which slot's ROM is answering at $c800, if any. /// /// There is one two kilobyte window and seven slots that might /// want it, so a card takes it by having its own page touched /// and gives it up when anything touches $cfff. A card's /// firmware does that on its way in and out. /// INTC8ROM: whether the machine's own ROM has taken the /// $c800 window, which is the other way it can be occupied. /// /// Sather calls it "an unreadable soft switch, set by access /// to $C3XX with SLOTC3ROM reset, and reset by access to $CFFF /// or an MMU reset" (Sather, 1985, p. 5-28), and notes that /// "you will find no reference to the INTC8ROM soft switch in /// Apple literature". It is what lets the eighty-column /// firmware at $c300 reach its own code at $c800 without /// setting INTCXROM and taking the whole of $c100-$cfff away /// from the slots to do it. /// /// It is a separate thing from `expansion` being null, and /// keeping them apart is the whole point: a window nobody has /// claimed is not the machine's ROM, it is a floating bus. /// /// Table 5.4 on p. 5-22 lists this switch's set and reset /// conditions in the opposite columns to the sentence above. /// The sentence is what is implemented, because $cfff /// releasing the window is the I/O STROBE' protocol every /// card's firmware relies on and the table would have it /// claim the window instead. intc8rom: bool = false, /// Where `withoutCard` puts the floating bus's byte so that it /// has an address to hand back, `readTarget` dealing in /// pointers rather than values. It is not memory the machine /// has: it is this cycle's answer, and the next read overwrites /// it. bus_latch: u8 = 0, /// The mouse on a IIc, which is not a card and not much /// hardware either. /// /// Two lines say it has moved and two say which way. Every /// edge of the movement lines interrupts, and the handler in /// the machine's own ROM has to read the direction line /// within forty microseconds to find out which way that /// movement went. Everything a mouse card does for itself — /// counting, clamping, remembering where the pointer is — the /// firmware does here, out of a stream of interrupts. So what /// is emulated is the four lines and the interrupt, and the /// ROM does the rest. iic_mouse: struct { /// Movement the host has asked for and the machine has /// not been told about yet, in steps. pending_x: i32 = 0, pending_y: i32 = 0, /// The direction lines, which are what $c066 and $c067 /// read: set for one way, clear for the other. x_direction: bool = false, y_direction: bool = false, /// Whether a movement is waiting to be owned up to. x_interrupt: bool = false, y_interrupt: bool = false, /// Whether the machine wants to be told about movement at /// all, and the button, which reads the other way round /// from every other button on the machine. enabled: bool = false, button: bool = false, } = .{}, /// The IIc's printer port, which is the same chip as the one /// above with its own connector. A IIe has no such thing. printer: serial.Acia = .{}, printer_listening: bool = false, /// The seven expansion slots and what is in them, on the /// machine that has them. Which card is where used to be a /// constant per card; it is data now, and a machine can have /// two of a kind. See `slots.zig`. /// /// A IIc has none: every page from $c100 to $cfff is its own /// firmware and every one of the sixteen-address blocks below /// them is a port soldered to the board, which is what /// `builtInPort` answers. slots: if (kind.slotted()) slot_module.Slots else void = if (kind.slotted()) .{} else {}, /// What `drives` answers with on a machine that has no disk /// controller in it at all: a port with nothing on it. A front /// end asks about the drives whether or not there are any, and /// this is the answer when there are none. Never reached /// through an address — no card, no page, no switches. absent_drives: disk2.Controller = .{ .fitted = 0 }, /// A IIc's memory expansion connector, which is inside the /// case rather than in a slot: `fitMemoryExpansion` is what /// fills it, and its registers are at fixed addresses. A IIe /// takes a RamFactor in a slot, which is a different thing /// with its own firmware on it. memory_card: if (kind == .iic) ramfactor.Card else void = if (kind == .iic) .{} else {}, /// The Disk II card in slot 6, and whatever is in its drives. /// On a IIc this is the drive in the case and the port on the /// back, which are the same two the card had. /// /// The card is only present once its ROM has been loaded. An /// empty slot answers from the internal ROM, so without the /// card's own 256 bytes there is nothing for the machine to /// find when it goes looking for something to start from, which /// is exactly what an empty slot looks like. /// A IIe reaches its drives through a Disk II card, which is a /// controller and nothing else. A IIc reaches its through an /// Integrated Woz Machine soldered to the board — "the disk /// controller unit, also known as the Integrated Woz Machine /// (IWM)" (Apple Computer, Inc., 1985e, §11.5.5) — and that is a /// different chip, not a card with the same switches: it adds /// the status, mode and handshake registers a card never had, /// and the 32K firmware uses all three when it goes looking for /// a UniDisk 3.5 on the port. The five-and-a-quarter mechanism /// underneath is the same either way, and `drives()` is how /// anything that only wants that reaches it. disk: if (kind == .iic) iwm.Iwm else void = if (kind == .iic) .{} else {}, /// The colours a hosting Apple IIgs has told this to draw its /// text in, or null for text with no colour of its own -- which /// is every IIe and IIc, whose text is dots and what a monitor /// makes of them, and a IIgs that has been put in black and /// white. The Mega II inside a IIgs is this model, and it draws /// the text; the Screen Color register that says what colour is /// the VGC's, on the far side of the machine. So the VGC's /// owner pushes the pair over whenever it changes, which is how /// the real chips are wired too. See `textColour`. given_text_colours: ?TextColours = null, // The language card, exactly as on a II Plus — and the same // switches an Apple IIgs's fast side has its own copy of, // which is why they live in a type of their own rather than // being written out twice. card_switches: languagecard.LanguageCard = .{}, // What the IIe adds. altzp: bool = false, ramrd: bool = false, ramwrt: bool = false, store80: bool = false, intcxrom: bool = false, slotc3rom: bool = false, altchar: bool = false, col80: bool = false, /// Which character generator chip is in the socket. See /// `characterSet`. A IIe is given the chip that goes with its /// firmware when the ROM is loaded; a IIc only ever had the /// one with MouseText in it. character_set: font.Set = .apple2e_enhanced, /// Which IIe firmware the ROM turned out to be, read off its /// identification byte. See `loadROMAtEnd`. firmware: Firmware = .unknown, // Display switches. PAGE2 and HIRES also steer memory once 80STORE is // on, which is why they are not merely cosmetic here. text: bool = true, mixed: bool = false, page2: bool = false, hires: bool = false, /// The last key pressed, in the low seven bits. keyboard: u8 = 0, /// Set when a key is pressed and cleared by touching the clear-strobe /// location, which is how a program knows a key is waiting rather than /// merely that one was pressed at some point. strobe: bool = false, /// Whether a key is being held down. A terminal reports presses and /// never releases, so this is the best that can be known: it is true /// from the press until the program next looks, which is enough for /// the wait-for-release the Monitor does and not enough for auto /// repeat. key_down: bool = false, /// How many times running the machine has looked for a key and found /// none, counted since the last one was handed over. /// /// A real Apple has no type-ahead. The keyboard is a single latch, and /// a key put into it before the machine is ready to read one is simply /// gone: the firmware peeks at the keyboard while it is busy with other /// things, and clears the latch on its way in to reading a line. So one /// peek coming away empty says nothing. Sitting in a read loop asking /// over and over does, and that is the moment a key can be handed over /// and be sure of being seen. Something outside feeding keys in can /// watch this to pace itself; nothing in the machine reads it. empty_polls: u16 = 0, /// The speaker cone, out or in. Every access to $c030 flips it, and /// a program makes a tone by flipping it at the rate it wants to /// hear. speaker: bool = false, /// How many times the cone has moved audibly. Something outside can /// watch this to tell the machine is making a noise, which is as /// much as a terminal can act on. speaker_clicks: u64 = 0, /// The cassette output line: one bit, flipped by touching /// $c020, which is the speaker over again. A program writes to /// tape by flipping it in patterns, so the timing is the whole /// of what it says. /// Whether the switch on a IIc's keyboard is down, which is /// what tells its firmware to come up in eighty columns. There /// is no such switch on a IIe: that machine is told with a /// command. eighty_column_switch: bool = true, /// `IOUDis`, and it means what its name says: the IOU is /// *disabled* from answering at `$c058` to `$c05f` while it is /// on. A IIc has no annunciators for those addresses to be, so /// what they are instead is the mouse and the blanking /// interrupt, and this decides whether the IOU gets them. /// /// On, at `$c07e`: "Disable IOU access for addresses $C058 to /// $C05F; enable access to DHiRes switch". Off, at `$c07f`: /// "Enable IOU access for addresses $C058 to $C05F; disable /// access to DHiRes switch" (Apple Computer, Inc., 1989b, /// Table 9-2, p. 256). /// /// **It comes up on**, which is not a guess: "the IOUDis /// ($C07E) switch must be on to allow you to use locations /// $C05E and $C05F to change DHiRes. The firmware in fact /// leaves it on -- and your program should, too -- unless it /// wants to use locations $C05E and $C05F to change mouse /// values" (Table 6-9's text). So a IIc's ordinary state is /// the one where those two addresses are the video's, and the /// mouse is what a program has to ask for. ioudis: bool = true, /// Annunciators 0, 1 and 2: three of the four one-bit outputs /// on the game connector, "used to turn a lamp, a relay, or /// some similar electronic device on and off" (Apple Computer, /// Inc., 1985b, p. 40). /// /// The fourth is not here, because on a IIe it is not a /// separate thing: annunciator 3 is what asks for double /// resolution, so the latch is `double_hires` and `annunciator` /// is what reads the pin. One latch under two names is better /// than two fields that can come to disagree. /// /// A IIc has no annunciator outputs at all, so it has no field /// either: `void` rather than three booleans nothing is wired /// to. annunciators: if (kind == .iic) void else [3]bool = if (kind == .iic) {} else @splat(false), /// Which edge of each movement line was asked for, which is /// remembered and read back and nothing more. x_edge: bool = false, y_edge: bool = false, /// Whether double resolution graphics have been asked for. /// /// It is annunciator 3 that asks, at `$c05e` and `$c05f`, and /// the two manuals cannot agree on what to call either address. /// The IIe Technical Reference's own assembler listing (Apple /// Computer, Inc., 1985) has `SETAN3 EQU $C05E` and `CLRAN3 EQU /// $C05F`; the IIgs Hardware Reference's annunciator table /// (Apple Computer, Inc., 1989a) has them the other way round, /// and then says in its soft switch table that Hi-Res becomes /// Double Hi-Res "if SETAN3 is on", which only agrees with the /// first of those. The line is inverted somewhere between the /// switch and the chip and each manual named a different end of /// it. /// /// The firmware settles it. Both the IIe's and the IIgs's read /// `$c058 $c05a $c05d $c05f` while they are setting the /// machine up, and a machine being set up is not one that /// wants double resolution — so `$c05f` is the one that turns /// it off and `$c05e` is the one that turns it on, which is /// also what every program that draws in this mode does. /// /// The latch behind the annunciators is cleared by reset, but /// which of the two states that is cannot be read off either /// manual, and it makes no difference: 80COL is off at reset /// too, and it takes both. This starts where the firmware /// leaves it, which is where a machine is by the time anything /// can look. double_hires: bool = false, cassette_out: bool = false, cassette_log: speaker.Log(options.cassette_log) = .{}, /// What the cassette input line is at, for a caller setting it /// directly rather than playing a tape. cassette_in: bool = false, cassette_tape: ?cassette.Tape = null, /// Where the four paddles are, nought to 255. /// /// A paddle is a variable resistor and the machine cannot read /// one directly. It starts a timer whose length the resistance /// sets, and counts how long the timer takes to run down, so /// what is kept here is the position and what the machine sees /// is time. paddles: [4]u8 = @splat(0), /// The cycle the timers were last started on, by touching /// $c070. paddle_started: u64 = 0, /// The three buttons on the game connector. On a IIe the first /// two are also the Open Apple and Solid Apple keys, which is /// why so much software asks after them. buttons: [3]bool = @splat(false), /// When the cone moved, if anything asked for that to be kept. /// The cycle is the whole of it: see speaker.zig. speaker_log: speaker.Log(options.speaker_log) = .{}, /// And what was written to a Mockingboard, which is kept /// here rather than on the card: a log with room for four /// thousand writes is sixty-four kilobytes, and a machine /// whose every slot could hold one of these would pay for it /// seven times over. It is the same arrangement the speaker /// and the cassette already have. mockingboard_log: mockingboard.Log(options.mockingboard_log) = .{}, /// The Phasor's write log, kept here for the same reason and /// gated by the same build option: a machine records sound or /// it does not, whichever card is making it. phasor_log: phasor.Log(options.mockingboard_log) = .{}, /// And the Sound/Speech card's, gated the same way. soundspeech_log: soundspeech.Log(options.mockingboard_log) = .{}, /// Set when a vertical blanking interval begins and cleared by /// touching $c070-$c07f, which is also the paddle timer's trigger. /// The IOU holds this latch whether or not anything is listening to /// it. vbl_interrupt: bool = false, /// Whether the latch is allowed to pull the interrupt request line. /// /// A plain IIe cannot do this: vertical blanking is something it /// expects a program to poll at $c019, which is what the technical /// reference means by staying in step with the display. Routing it to /// an interrupt is an Apple IIc feature, and reaches a IIe only /// through a mouse card. It is off by default so that a IIe behaves /// like one, and is switched at the addresses the IIc uses. vbl_interrupt_enabled: bool = false, /// The cycle the current frame ends on, carried forward rather than /// worked out from the clock each time. Dividing by the frame length /// on every memory access cost more than the rest of the access put /// together: it is not a power of two, so it is a real division, and /// there were two of them. frame_end: u64 = cycles_per_frame, /// Whether this frame's latch has been set, so that it is set once per /// frame rather than once per access throughout the blanking interval. vbl_latched: bool = false, /// What $c000 reads: the last key, with the strobe above it. /// /// Coming away empty is counted, for the reason given on empty_polls. fn keyboardByte(self: *Self) u8 { if (!self.strobe) self.empty_polls +|= 1; return self.keyboard | @as(u8, if (self.strobe) 0x80 else 0); } /// What $c010 reads: the last key, with any-key-down above it. fn anyKeyDown(self: *const Self) u8 { return self.keyboard | @as(u8, if (self.key_down) 0x80 else 0); } /// Presses a key. The character goes in as it is; the machine's own /// character set is the caller's business. pub fn pressKey(self: *Self, character: u8) void { self.keyboard = character & 0x7f; self.strobe = true; self.key_down = true; self.empty_polls = 0; } /// How long one paddle's timer runs for, in cycles. fn paddleRuns(self: *const Self, which: usize) u64 { return @as(u64, self.paddles[which]) * paddle_cycles_per_unit + paddle_cycles_before_first_look; } /// What the cassette input line is at. /// /// A tape being played wins over a level set by hand, and where /// it has got to comes from the machine's clock rather than from /// the wall. fn cassetteInput(self: *Self) bool { const tape = self.cassette_tape orelse return self.cassette_in; return tape.levelAt(self.getCPU().clock.cycles -| tape.started, cycles_per_second); } /// Puts the cassette input line one way or the other, for a /// caller making its own signal rather than playing a tape. pub fn setCassetteInput(self: *Self, level: bool) void { self.cassette_in = level; } /// Starts playing a tape in, from this cycle. pub fn playTape(self: *Self, levels: []const u8, sample_rate: u32) void { self.cassette_tape = .{ .levels = levels, .sample_rate = sample_rate, .started = self.getCPU().clock.cycles, }; } /// Takes the tape off. pub fn stopTape(self: *Self) void { self.cassette_tape = null; } /// Puts a paddle somewhere between nought and 255, which is what /// the machine will read back from it. pub fn setPaddle(self: *Self, which: u2, position: u8) void { self.paddles[which] = position; } /// Presses or releases one of the three game buttons. On a IIe /// the first two are the Open Apple and Solid Apple keys. pub fn setButton(self: *Self, which: u2, down: bool) void { if (which < self.buttons.len) self.buttons[which] = down; } /// 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, without the processor spending a cycle on it. Where /// it lands follows the machine's switches, since that is what /// the card would be driving. pub fn blockPut(self: *Self, at: u16, byte: u8) void { if (self.writeTarget(at)) |target| target.* = byte; } pub fn blockGet(self: *Self, at: u16) u8 { return if (self.readTarget(at)) |source| source.* else 0; } /// Puts a volume in the block device, or takes it out. /// Fits the block device, whose firmware is ours and is built /// in, so it needs nothing but somewhere to be. pub fn fitBlockDevice(self: *Self, slot: u3) !void { if (comptime !kind.slotted()) return error.WrongSize; try self.slots.fit(slot, .{ .block = .{} }); } pub fn insertVolume(self: *Self, which: u1, volume: ?*blockdevice.Volume) void { if (comptime !kind.slotted()) return; // A volume has to be in something: fit the card if the // machine has not been given one. if (self.slots.first(.block) == null) { self.slots.fit(default_slot.block, .{ .block = .{} }) catch return; } const slot = self.slots.first(.block).?; self.slots.cards[slot].block.volumes[which] = volume; } /// Hands the $c800 window to whichever card's page was touched, /// and takes it back when $cfff is. /// /// Only on a real access, never on a peek: looking at memory /// from outside the machine must not change which ROM the /// machine can see. fn claimExpansion(self: *Self, address: u16) void { if (comptime !kind.slotted()) return; // The slot half of this is the same on every machine that // has slots and lives in `slots.zig`. What is a IIe's alone // is the MMU, and that is the two questions it is handed. // // A card is only woken by an access its slot's I/O SELECT // line reaches, and with INTCXROM set the MMU cannot be // asserting one: a card driving the bus at the same time as // the internal ROM would be two things answering one // address. That is an inference from the arrangement rather // than a sentence in the manual, and nothing here can tell // the difference, since the firmware is reached with the // switch the other way. self.slots.claim(address, !self.intcxrom, self.slotThreeIsCard()); // "The $C800-$CFFF range is assigned to motherboard ROM // (INTernal) anytime SLOTC3ROM is reset and an access is // made to $C3XX" (Sather, 1985, p. 5-28): the machine's own // firmware answering at $c300 takes the window for itself, // which is how the eighty-column code at $c300 reaches the // rest of itself at $c800. SLOTC3ROM alone decides it, and // INTCXROM does not come into it — the switch is "set by // access to $C3XX with SLOTC3ROM reset" and that is the // whole condition. $cfff clears it, and empties the window // both ways round. if (address & 0xff00 == internal_slot_three and !self.slotc3rom) self.intc8rom = true; if (address == 0xcfff) self.intc8rom = false; } /// Works out whether anything is pulling the interrupt line. /// /// More than one thing can, and they share one line, so it is /// worked out from all of them rather than set by whichever /// moved last: a card letting go must not quieten the blanking /// interrupt, or the other way about. /// Whether any card in any slot is pulling the interrupt line. /// /// Every slot is asked rather than three named cards, because /// any slot can hold any of them now and a machine can have two /// of a kind. The line is wired-or on the backplane: one card /// pulling it is the line down. fn slotsInterrupting(self: *Self, cycles: u64) bool { if (comptime !kind.slotted()) return false; for (&self.slots.cards) |*card| { const asking = switch (card.*) { .mockingboard => |*c| c.interrupting(cycles), .phasor => |*c| c.interrupting(cycles), .soundspeech => |*c| c.interrupting(cycles), .passport => |*c| c.interrupting(cycles), .mouse => |*c| c.interrupting(), .serial => |*c| c.interrupts and c.acia.interrupting(cycles), else => false, }; if (asking) return true; } return false; } pub fn updateInterrupt(self: *Self) void { const cycles = self.getCPU().clock.cycles; const from_video = self.vbl_interrupt_enabled and self.vbl_interrupt; const from_mouse = kind == .iic and self.iic_mouse.enabled and (self.iic_mouse.x_interrupt or self.iic_mouse.y_interrupt); self.getCPU().irq = from_video or from_mouse or self.slotsInterrupting(cycles); } /// What the mouse card's firmware asks for. The position and /// the buttons go in and out through the screen holes, which /// are the bytes of the text page no character is displayed /// from: one set for each slot, and slot nought's are where a /// caller leaves the clamps. fn runMouseCommand(self: *Self, command: mouse.Command, is_write: bool, value: u8) u8 { const card = &self.mouse_card; const mine: u16 = mouse_slot; switch (command) { .result => return card.result, .set => if (is_write) { card.setMode(value); self.poke(mouse.hole.mode + mine, value); }, .serve => card.serve(), .read => { const reported = card.readPosition(); self.poke(mouse.hole.x_low + mine, @truncate(@as(u16, @bitCast(card.x)))); self.poke(mouse.hole.x_high + mine, @intCast(@as(u16, @bitCast(card.x)) >> 8)); self.poke(mouse.hole.y_low + mine, @truncate(@as(u16, @bitCast(card.y)))); self.poke(mouse.hole.y_high + mine, @intCast(@as(u16, @bitCast(card.y)) >> 8)); self.poke(mouse.hole.status + mine, reported); }, .clear => card.clear(), .position => { const x = @as(u16, self.peek(mouse.hole.x_low + mine)) | @as(u16, self.peek(mouse.hole.x_high + mine)) << 8; const y = @as(u16, self.peek(mouse.hole.y_low + mine)) | @as(u16, self.peek(mouse.hole.y_high + mine)) << 8; card.positionTo(@bitCast(x), @bitCast(y)); }, .clamp => if (is_write) { // The caller leaves them in slot nought's holes: // the low end in the X pair, the high end in the Y. const low = @as(u16, self.peek(mouse.hole.x_low)) | @as(u16, self.peek(mouse.hole.x_high)) << 8; const high = @as(u16, self.peek(mouse.hole.y_low)) | @as(u16, self.peek(mouse.hole.y_high)) << 8; card.clamp(value, @bitCast(low), @bitCast(high)); }, .home => card.home(), .init => { card.initialise(); self.poke(mouse.hole.mode + mine, 0); self.poke(mouse.hole.status + mine, 0); }, else => {}, } self.updateInterrupt(); return card.result; } /// The processor this belongs to. /// /// Two ways of finding it, chosen when the machine is built. /// Embedded — the default, and what every machine here uses — /// walks back from the field it sits in, which the compiler /// turns into subtracting a constant. Given reads a pointer /// that was handed over, for a model that is a part of a /// larger machine and so is not the processor's `memory` /// field at all. See `bus.Host`. pub inline fn getCPU(self: *Self) *CPU { return switch (comptime options.host) { .embedded => @alignCast(@fieldParentPtr("memory", self)), // Null here means `setHost` was never called. It // cannot be checked at compile time, so it is a panic // on the first access rather than something subtler. .given => self.host.?, }; } /// Tells the model which processor it belongs to. /// /// Must be called after `init`, which clears every field. A /// model that finds its own way back ignores this, so a caller /// that does not know which kind it has may always call it. pub fn setHost(self: *Self, cpu: *CPU) void { switch (comptime options.host) { .embedded => {}, .given => self.host = cpu, } } /// Whether the video is in the vertical blanking interval, which is /// the last seventy of the frame's 262 lines. pub fn blanking(self: *Self) bool { return self.getCPU().clock.read() >= self.frame_end - blanking_cycles; } /// Hands the machine the next step of whatever movement the /// host has asked for. /// /// A real mouse puts out a square wave as it rolls, and the /// machine is interrupted on each edge of it. There is nothing /// here to roll, so a step is handed over whenever the last /// one has been owned up to and there is more to give, which /// is as fast as the handler will take them — which is what a /// mouse moved quickly does anyway. fn stepMouse(self: *Self) void { if (comptime kind != .iic) return; if (!self.iic_mouse.enabled) return; if (self.iic_mouse.x_interrupt or self.iic_mouse.y_interrupt) return; if (self.iic_mouse.pending_x != 0) { const forward = self.iic_mouse.pending_x > 0; self.iic_mouse.pending_x -= if (forward) 1 else -1; self.iic_mouse.x_direction = forward; self.iic_mouse.x_interrupt = true; } else if (self.iic_mouse.pending_y != 0) { const forward = self.iic_mouse.pending_y > 0; self.iic_mouse.pending_y -= if (forward) 1 else -1; // The two lines do not agree about which way is which: // the firmware inverts what it reads here before // counting it, so down the screen is the line low. self.iic_mouse.y_direction = !forward; self.iic_mouse.y_interrupt = true; } else { return; } self.updateInterrupt(); } /// Where the host says the mouse has moved to, in the steps the /// lines carry rather than in anything the program will see: /// what the pointer ends up at is the firmware's arithmetic. pub fn moveMouse(self: *Self, dx: i16, dy: i16) void { if (comptime kind != .iic) return; self.iic_mouse.pending_x += dx; self.iic_mouse.pending_y += dy; } pub fn setMouseButton(self: *Self, down: bool) void { if (comptime kind != .iic) return; self.iic_mouse.button = down; } /// Brings the vertical blanking latch and the interrupt line up to /// date with the clock. Called on every access, which is often enough: /// a processor cannot notice an interrupt without fetching an opcode, /// and fetching one is an access. So it is also on the hottest path /// there is, and does no arithmetic it can avoid. fn updateVideo(self: *Self) void { const now = self.getCPU().clock.read(); while (now >= self.frame_end) { self.frame_end += cycles_per_frame; self.vbl_latched = false; } if (!self.vbl_latched and now >= self.frame_end - blanking_cycles) { self.vbl_latched = true; self.vbl_interrupt = true; // The mouse is the other thing that wants telling when // a frame ends, if it has been asked to interrupt then. if (self.mouseCard()) |card| card.blanked(); } // And the IIc's own mouse is handed its next step whenever // the last one has been dealt with. if (comptime kind == .iic) { self.stepMouse(); } if ((self.vbl_interrupt_enabled and self.vbl_interrupt) or self.slotsInterrupting(now)) self.getCPU().irq = true; } /// Zeroes both halves and puts the switches where a power-on leaves /// them: main memory everywhere, reading the ROM, writing the card. pub fn init(self: *Self, _: ?usize) void { self.* = .{ .rom = @splat(0) }; self.main.clear(); self.aux.clear(); // A IIc comes with a drive in the case, which is not // something that can be left out of one. The socket on the // back takes a second, and whoever builds the machine says // whether there is one. if (comptime kind == .iic) self.drives().fitted = 1; } /// Whether the multidrive interface glue is what answers at /// this address rather than the ROM behind it. /// /// Only on a IIc Plus, and only in the second bank: the first /// bank has real firmware at `$ce00` and the second leaves the /// space empty for the chip, which is how the machine reaches /// both. See `mig.zig`. /// What the glue chip's latched outputs mean to the disk port, /// worked out again whenever either end of it moves. /// /// Two of the three go straight through. `HDSEL` is the fourth /// bit of the address naming a 3.5-inch drive's register, which /// a IIgs keeps in bit 7 of `$c031`; `INTEN*` is where the /// IWM's drive 2 select is pointed, at the drive in the case or /// out at the port. /// /// The third wants a sentence. `3.5DRIVE*` says what is on the /// far end of the cable, and it is "routed to the external /// connector only" — "in the IIc Plus, the internal 3.5-inch /// drive does not need the 3.5DRIVE signal asserted in order to /// operate" (MG, 2018). So the port is talking to a 3.5-inch /// drive when the line says so *or* when the drive being /// addressed is the one in the case, which is a 3.5-inch drive /// whatever any line says. fn syncDiskPort(self: *Self) void { if (comptime kind != .iic) return; if (!self.mig_fitted) return; self.disk.disks35.sel = self.mig.sel; self.disk.routing = if (self.mig.internal_enabled) .internal_on_two else .external_only; // "In the IIc Plus, the internal 3.5-inch drive does not // need the 3.5DRIVE signal asserted in order to operate" // (MG, 2018), so the drive in the case is a 3.5-inch drive // whatever the line says. The line decides the other end of // the cable, and nothing else. const internal = self.mig.internal_enabled and self.disk.selected == 1; self.disk.three_and_a_half = self.mig.external_35 or internal; } pub inline fn migAnswers(self: *const Self, address: u16) bool { if (comptime kind != .iic) return false; return self.mig_fitted and self.rom_bank == 1 and address >= mig_chip.base and address < mig_chip.base + mig_chip.size; } /// The five-and-a-quarter drives themselves, whichever port /// reaches them. An IWM keeps the same `disk2.Controller` a card /// is, so putting a disk in or asking whether the motor is /// turning is the same call on both machines. pub inline fn drives(self: *Self) *disk2.Controller { if (comptime kind == .iic) return &self.disk.drives; const card = self.cardIn(.disk) orelse return &self.absent_drives; return &card.disk.drives; } /// Where each kind of card goes when nobody says otherwise. /// /// These are the slots the software of the day looked in, which /// is why they were the slots people used: `PR#6` boots a disk, /// ProDOS scans for a clock, a mouse driver looks in 4. Nothing /// here insists on them any more — the `fit*` pairs take a slot /// — but a machine set up without being asked is set up like /// this. pub const default_slot = struct { pub const parallel = 1; pub const serial = 2; pub const eighty_column = 3; pub const mouse = 4; pub const sound = 4; pub const clock = 5; pub const memory = 5; pub const disk = 6; pub const block = 7; pub const transporter = 7; }; /// The cards, by kind, for anything outside the machine that /// wants one — a front end drawing an eighty-column screen, or /// rolling a mouse. /// /// Asked for rather than reached for, because where a card is /// and whether it is there at all are the machine's business. /// A front end that named the field instead would go on /// compiling when the field moved, and quietly find nothing. /// /// The lowest-numbered card of its kind, where there is more /// than one: an unqualified question has to mean something, and /// a machine with two of a thing is a machine whose owner will /// say which they meant. pub inline fn cardIn(self: *Self, comptime tag: std.meta.Tag(slot_module.Card)) ?*slot_module.Card { if (comptime !kind.slotted()) return null; const slot = self.slots.first(tag) orelse return null; return &self.slots.cards[slot]; } pub inline fn videxCard(self: *Self) ?*videx.Card { const card = self.cardIn(.videx) orelse return null; return &card.videx.card; } pub inline fn ultraTermCard(self: *Self) ?*ultraterm.Card { const card = self.cardIn(.ultraterm) orelse return null; return &card.ultraterm.card; } pub inline fn mouseCard(self: *Self) ?*mouse.Card { const card = self.cardIn(.mouse) orelse return null; return &card.mouse; } pub inline fn clockCard(self: *Self) ?*clockcard.Card { const card = self.cardIn(.clock) orelse return null; return &card.clock; } pub inline fn mockingboardCard(self: *Self) ?*mockingboard.Card { const card = self.cardIn(.mockingboard) orelse return null; return &card.mockingboard; } pub inline fn phasorCard(self: *Self) ?*phasor.Card { const card = self.cardIn(.phasor) orelse return null; return &card.phasor; } pub inline fn soundSpeechCard(self: *Self) ?*soundspeech.Card { const card = self.cardIn(.soundspeech) orelse return null; return &card.soundspeech; } pub inline fn blockCard(self: *Self) ?*blockdevice.Card { const card = self.cardIn(.block) orelse return null; return &card.block; } /// The memory expansion, which is two different things: a /// RamFactor in a slot on a IIe, and the connector inside a /// IIc's case. Both are the same chip's worth of registers, so /// both answer here. pub inline fn memoryCard(self: *Self) ?*ramfactor.Card { if (comptime kind == .iic) return if (self.memory_card.fitted) &self.memory_card else null; const card = self.cardIn(.ramfactor) orelse return null; return &card.ramfactor.card; } /// Takes it out, which is what the session does when it is /// giving back the memory behind it. pub fn ejectMemoryCard(self: *Self) void { if (comptime kind == .iic) { self.memory_card.fitted = false; self.memory_card.ram = &.{}; return; } const slot = self.slots.first(.ramfactor) orelse return; _ = self.slots.empty(slot); } /// The serial chip, and whether anything has listened to it yet /// — which is how something feeding it knows the machine is /// ready for a byte. /// /// A IIe's is on a Super Serial Card in a slot; a IIc's is /// soldered to the board at the addresses that card would have /// used, because that is where the machine's own firmware /// looks. pub inline fn serialAcia(self: *Self) ?*serial.Acia { if (comptime kind == .iic) return &self.acia; const card = self.cardIn(.serial) orelse return null; return &card.serial.acia; } pub inline fn serialListening(self: *const Self) bool { if (comptime kind == .iic) return self.serial_listening; if (comptime !kind.slotted()) return false; const slot = self.slots.first(.serial) orelse return false; return self.slots.cards[slot].serial.listening; } /// Fits a parallel printer card, with somewhere for what it /// prints to go. pub fn fitPrinter(self: *Self, slot: u3, out: ?*std.Io.Writer) void { if (comptime !kind.slotted()) return; self.slots.fit(slot, .{ .parallel = .{ .fitted = true, .out = out } }) catch {}; } /// Fits a mouse card. pub fn fitMouse(self: *Self, slot: u3) void { if (comptime !kind.slotted()) return; self.slots.fit(slot, .{ .mouse = .{ .fitted = true } }) catch {}; } pub fn fitMockingboard(self: *Self, slot: u3, speech: bool) void { if (comptime !kind.slotted()) return; self.slots.fit(slot, .{ .mockingboard = .{ .fitted = true, .has_speech = speech } }) catch {}; } /// Fits a Phasor, Applied Engineering's four-chip superset of /// the Mockingboard. pub fn fitPhasor(self: *Self, slot: u3) void { if (comptime !kind.slotted()) return; self.slots.fit(slot, .{ .phasor = .{ .fitted = true } }) catch {}; } /// Fits a Sound/Speech Mockingboard: an AY and a Votrax SC-01. pub fn fitSoundSpeech(self: *Self, slot: u3) void { if (comptime !kind.slotted()) return; self.slots.fit(slot, .{ .soundspeech = .{ .fitted = true } }) catch {}; } /// Fits a Passport MIDI interface. A IIc has no slots, so on one /// this does nothing. pub fn fitPassport(self: *Self, slot: u3) void { if (comptime !kind.slotted()) return; self.slots.fit(slot, .{ .passport = .{} }) catch {}; } /// Fits an Uthernet II, if this machine has slots to fit it in. pub fn fitUthernet(self: *Self, slot: u3) void { if (comptime !kind.slotted()) return; self.slots.fit(slot, .{ .uthernet = .{} }) catch {}; } /// The Uthernet II's W5100, for the session's host end to drive. /// Its presence is what tells a front end this machine can do /// Ethernet at all. pub inline fn ethernetChip(self: *Self) ?*w5100.W5100 { if (comptime !kind.slotted()) return null; const slot = self.slots.first(.uthernet) orelse return null; return &self.slots.cards[slot].uthernet.chip; } /// Fits an Uthernet (the original, its CS8900A). pub fn fitCs8900(self: *Self, slot: u3) void { if (comptime !kind.slotted()) return; self.slots.fit(slot, .{ .cs8900 = .{} }) catch {}; } /// The CS8900A on an Uthernet, for the session's wire to drive. pub inline fn cs8900Chip(self: *Self) ?*cs8900.CS8900 { if (comptime !kind.slotted()) return null; const slot = self.slots.first(.cs8900) orelse return null; return &self.slots.cards[slot].cs8900.chip; } /// The MIDI card's serial chip, and whether the machine has /// listened to it — the same pair the serial card exposes, so a /// front end drives MIDI in and out the same way. pub inline fn midiAcia(self: *Self) ?*mc6850.Acia { if (comptime !kind.slotted()) return null; const card = self.cardIn(.passport) orelse return null; return &card.passport.acia; } pub inline fn midiListening(self: *Self) bool { if (comptime !kind.slotted()) return false; const slot = self.slots.first(.passport) orelse return false; return self.slots.cards[slot].passport.listening; } pub fn midiReceive(self: *Self, byte: u8) bool { const acia = self.midiAcia() orelse return false; const room = acia.receive(byte); self.updateInterrupt(); return room; } pub fn midiSent(self: *Self) []const u8 { if (comptime !kind.slotted()) return &.{}; const slot = self.slots.first(.passport) orelse return &.{}; return self.slots.cards[slot].passport.acia.sent(); } pub fn midiSentAt(self: *Self) []const u64 { if (comptime !kind.slotted()) return &.{}; const slot = self.slots.first(.passport) orelse return &.{}; return self.slots.cards[slot].passport.acia.sentAt(); } pub fn midiConsume(self: *Self, count: usize) void { if (comptime !kind.slotted()) return; const slot = self.slots.first(.passport) orelse return; self.slots.cards[slot].passport.acia.consume(count); } /// And a clock card, set to a moment. Setting it is what fits /// it: a card nobody set is a card that does not know when it /// is, which is not a card anyone would have bought. pub fn fitClock(self: *Self, slot: u3, when: clockcard.Time, cycles: u64) void { if (comptime !kind.slotted()) return; var card: clockcard.Card = .{ .fitted = true }; card.set(when, cycles); self.slots.fit(slot, .{ .clock = card }) catch {}; } /// The three-and-a-half inch drive, on the one machine that has /// one. "The Apple IIc Plus has one internal 3.5-inch disk /// drive" (Apple Computer, Inc., 1989b, p. 86) and no earlier /// IIc has any, so this answers null everywhere else — which is /// also what tells a front end whether there is a drive to put /// a disk in. pub inline fn disks35(self: *Self) ?*disk35.Controller { if (comptime kind != .iic) return null; return if (self.mig_fitted) &self.disk.disks35 else null; } /// The intelligent drive on the disk port, on the machines /// that can have one. /// /// A UniDisk 3.5 is not a mechanism the machine works but a /// drive with a processor in it, reached in packets through /// the Protocol Converter — which is what the 32K ROM added /// and which the original sixteen-kilobyte machine has no /// firmware for. A IIc Plus is excluded for a different /// reason: its own 3.5-inch drives are on the second connector /// already, through the glue chip, and two things cannot both /// answer there. So this is the ROM 0, 3 and 4 machines, which /// are the ones the drive was sold for. pub inline fn unidisk(self: *Self) ?*unidisk_device.Chain { if (comptime kind != .iic) return null; return if (self.banked and !self.mig_fitted) &self.disk.unidisk else null; } /// Puts the switches back but leaves memory alone. The IIe, unlike the /// II Plus before it, does reset the bank switches. pub fn reset(self: *Self) void { // The reset line reaches the cards too: a Disk II clears // its latch, which stops the motor. if (comptime kind == .iic) self.disk.reset() else self.slots.reset(self.getCPU().clock.cycles); // The reset line reaches the glue too: its `IOSEL*` is // "tied to RESET*" (Apple Computer, Inc., 1989b, Table // 11-15, p. 328). if (comptime kind == .iic) { self.mig.reset(); // And the port comes back pointed at the drive in the // case, which on a IIc Plus is a 3.5-inch one: "The // Apple //c Plus has one internal 3.5-inch disk drive" // (Apple Computer, Inc., 1989b, p. 86). // // Which of the glue's latched outputs is `3.5 DRIVE*` // — "latched output bit to select 5.25-inch or // 3.5-inch drives" (Table 11-15, p. 328) — is not // settled. The firmware touches only five of the // chip's eight registers, and all five are accounted // for: three move the RAM window and two are SEL. So // what is modelled is the machine coming up pointed at // the drive it has, which is right for that drive and // is why a five-and-a-quarter drive on the back of a // IIc Plus is not reachable. See `mig.zig`. // // The *other* axis, inside against outside, is not // this latch and needs nothing here. A IIc Plus keeps // its internal and external 3.5-inch drives both on // port 5 and tells them apart by drive number (Apple // Computer, Inc., 1989b, p. 86), which is the IWM's // own selection; the glue's part is only `INTEN*` // against `ENB2`, one enable line each. self.disk.three_and_a_half = self.mig_fitted; // And on this machine the drive in the case answers to // the second select rather than the first. See // `internal_on_two` in `iwm.zig` for how that was // established, which was by asking ProDOS. self.disk.routing = if (self.mig_fitted) .internal_on_two else .direct; } // And a memory expansion card stops answering at its // registers until its firmware page is touched again — // except on a IIc, where there is no firmware page to // touch and the card is wired to answer always. A IIe's // RamFactor is a card in a slot, and `slots.reset` above // has already reached it. if (comptime kind == .iic) { self.memory_card.reset(); self.memory_card.enabled = true; // On a IIc Plus the expansion interface is on the // board, not on the card: the address counter answers // whether or not anybody fitted memory behind it, and // the firmware's two sizing loops prove it. The first // (`$da4e`) walks the counter up and leaves only when // the middle byte carries; the second (`$d9af`) walks // it down and leaves only when the high byte reaches // nought. No single value an undriven bus could give // satisfies both, so the counter cannot be absent. // Read out of the ROM 5 firmware at $da4e and $d9af. if (self.mig_fitted) self.memory_card.fitted = true; } // The reset line goes to every slot, and a 6522 that was // asking for attention stops: "T1 and T2, SR and the // interrupt logic are disabled from operation" (Western // Design Center, 2010, p. 36). Without this a Mockingboard // left with a timer running holds the interrupt line down // across the reset, which is the state mb-audit resets a // machine in on purpose to see what happens. That is // `slots.reset` above, which reaches every card there is. self.card_switches.reset(); self.altzp = false; self.ramrd = false; self.ramwrt = false; self.store80 = false; self.intcxrom = false; self.slotc3rom = false; self.intc8rom = false; self.vbl_interrupt = false; self.vbl_interrupt_enabled = false; // The ROM bank switch comes up on the main firmware, so reset // puts it back there — a IIc that reset while the extra 16K // was switched in would otherwise carry on in the wrong bank. if (comptime kind == .iic) self.rom_bank = 0; } /// What answers in the $c100-$cfff slot pages when the page /// belongs to the slots and the slot is empty. /// /// Not the machine's own ROM, which is what this model used to /// say and what a2audit's `E000B` was reporting. The $Cxxx /// range belongs to the slots, and three soft switches decide /// when the motherboard steals it back instead (Sather, 1985, /// p. 5-28): /// /// | INTCXROM | SLOTC3ROM | $C100-$C2FF, $C400-$CFFF | $C300-$C3FF | /// | --- | --- | --- | --- | /// | reset | reset | slot | internal | /// | reset | set | slot | slot | /// | set | reset | internal | internal | /// | set | set | internal | internal | /// /// with $c800-$cfff internal as well whenever INTC8ROM has /// been set, since "if INTCXROM OR INTC8ROM is configured for /// internal response, then access to $C800-$CFFF results in /// ROMEN1' low (active) and I/O STROBE' high (inactive)". /// /// Which of the two is answering is `slotsAnswerAt` below, /// asked once at the top of the slot pages rather than by /// every card for itself. This is only the other half: where /// the table says "slot" and the slot is empty, nothing drives /// the data bus and what the processor reads is the floating /// bus — the byte the video scanner last fetched. See /// `floatingBus`. fn withoutCard(self: *Self) *const u8 { self.bus_latch = self.floatingBus(); return &self.bus_latch; } /// Whether the slots are what answers at an address, or the /// machine's own ROM has taken the page back. /// /// The table above as one question asked once, which is how /// Sather puts it too — this is his sentence turned round: /// "CXXX will not go high if INTCXROM is set and $C100-$CFFF /// is addressed, if SLOTC3ROM is reset and $C3XX is /// addressed, or if INTC8ROM is set and $C800-$CFFF is /// addressed" (Sather, 1985, p. 7-2). CXXX is what enables /// the decoding that drives I/O SELECT' and I/O STROBE', and /// those are what let a card answer at all. /// /// It is the machine's answer and not a card's: which of the /// two is driving `$Cxxx` is settled by three soft switches /// and has nothing to do with what is plugged in, or with /// which slot it is plugged into. Slot 3 is the odd one only /// because the eighty-column firmware the machine keeps for /// itself lives in that page. /// /// The third clause is the one this model used to get wrong. /// A card holding the $c800 window answered there whatever /// INTC8ROM said, and INTC8ROM was consulted only once no /// card had: "I/O STROBE' thus drops low during access to /// $C800-$CFFF when INTCXROM and INTC8ROM are reset" (p. 7-2) /// — so with the switch set, no card answers in that window, /// whichever slot has claimed it. A program that wants the /// window back touches $cfff, which is what clears it. fn slotsAnswerAt(self: *const Self, address: u16) bool { if (self.intcxrom) return false; return switch (address) { internal_slot_three...internal_slot_three + 0xff => self.slotc3rom, 0xc800...0xcfff => !self.intc8rom, else => true, }; } /// Where the video scanner is looking this cycle. /// /// The scanner reads a byte of RAM every cycle, all 65 of a /// scan line and all 262 lines of a frame, whether or not the /// byte is going to be displayed. What it fetched is the last /// thing to have been driven onto the data bus, which is what /// makes the floating bus readable at all. /// /// Sather gives the address bit by bit in Table 5.1 /// (Sather, 1985, p. 5-8): /// /// | MPU | video scanner | /// | --- | --- | /// | A0-A2 | H0-H2 | /// | A3-A6 | SUM-A3 to SUM-A6 | /// | A7-A9 | V0-V2 | /// | A10-A12 | HIRES: VA-VC | /// | A10, A11 | TEXT/LORES: the page | /// | A13, A14 | HIRES: the page | /// /// where the four SUM bits come out of a four-bit adder in the /// IOU whose "equivalent adding circuit" is (p. 5-9): /// /// ``` /// 1 1 0 1 /// H5 H4 H3 /// + V4 V3 V4 V3 /// ----------------------------- /// SUM-A6 SUM-A5 SUM-A4 SUM-A3 /// ``` /// /// The constant is what makes the display start at a segment /// boundary: of the eight states of H5-H4-H3 only five are /// displayed, "000 through 010 are undisplayed and occur /// during the right margin, horizontal retrace, and left /// margin", and 011 is where the first byte of a 40-byte /// section is addressed. /// /// Table 5.2 on p. 5-19 is the check on all of it, and this /// reproduces it exactly: /// /// | | HBL | HBL' | /// | --- | --- | --- | /// | screen top | last 16 of THIRD 40 and UNUSED 8 | FIRST 40 | /// | screen middle | last 24 of FIRST 40 | SECOND 40 | /// | screen bottom | last 24 of SECOND 40 | THIRD 40 | /// | VBL | last 24 of THIRD 40 | UNUSED 8 and first 32 of FIRST 40 | fn scannerAddress(self: *Self) u16 { const now = self.getCPU().clock.read(); // Where the frame has got to. Taken the long way round // because `peek` does not advance the video first, so // `frame_end` can be a frame or more behind. const started = self.frame_end -% cycles_per_frame; const into_frame = (now -% started) % cycles_per_frame; const line = into_frame / cycles_per_line; const cycle = into_frame % cycles_per_line; // The horizontal counter holds 65 states because it counts // 0000000 and then 1000000 through 1111111, so H0-H5 read // zero for the first two cycles of every line and the byte // at that address is fetched twice. That is why Table 5.2's // horizontal blanking covers 24 addresses in 25 cycles. const h: u16 = if (cycle == 0) 0 else @intCast(cycle - 1); // The vertical counter runs $fa-$1ff rather than 0-261, so // that the 192 displayed lines are $100-$1bf and the 70 // blanked ones are $1c0-$1ff followed by $fa-$ff. Its low // three bits are VA-VC, the scan line within a row of // characters, and V0-V5 are the six above them. const v: u16 = if (line < 256) @intCast(0x100 + line) else @intCast(line - 6); const v3: u16 = (v >> 6) & 1; const v4: u16 = (v >> 7) & 1; const sum: u16 = (0b1101 + ((h >> 3) & 7) + ((v4 << 3) | (v3 << 2) | (v4 << 1) | v3)) & 0xf; // A0-A9, which HIRES and TEXT/LORES share. const low: u16 = (h & 7) | (sum << 3) | (((v >> 3) & 7) << 7); // "V4 . V2 identifies the last four lines of the TEXT // display", and "actually identifies scan lines 160 // through 191 and 224 through 261" (Sather, 1985, p. // 5-19) — so in mixed mode the scanner switches to text // addressing twice a frame, once where it shows and once // in the middle of the blanking where it does not. const v2: u16 = (v >> 5) & 1; const text_band = self.mixed and v4 == 1 and v2 == 1; const scanning_hires = self.hires and !self.text and !text_band; // A page 2 that 80STORE has taken away is not a page the // scanner follows: the switch hands $400-$7ff to the // auxiliary half instead, and PAGE2 stops meaning display. const page2 = self.page2 and !self.store80; return if (scanning_hires) low | ((v & 7) << 10) | @as(u16, if (page2) 0x4000 else 0x2000) else low | @as(u16, if (page2) 0x800 else 0x400); } /// What an undriven data bus is carrying: the byte the video /// scanner just fetched. /// /// "If an attempt to read auxiliary card RAM is made and no /// card is installed, the MPU will read the last value driven /// out of motherboard memory by the video scanner" (Sather, /// 1985, p. 5-38), and the same holds for every other address /// nothing answers at: an empty slot's pages, the $c800 window /// with no card in it, and the soft switches that are touched /// for their effect rather than read for an answer. /// /// Motherboard memory, so the main half whatever the switches /// say: the auxiliary half's byte goes to the eighty-column /// latch and never reaches this bus. fn floatingBus(self: *Self) u8 { return self.main.ram[self.scannerAddress()]; } /// The internal-ROM byte mapped at `address`, honouring the IIc's /// $C028 bank selection. On every other machine, and on a IIc with /// one 16K bank, this is simply the byte at `address - $c000`. inline fn romByte(self: *Self, address: u16) *u8 { // The switch is the 27256's A14: it selects a whole 16K half // of the ROM, so a IIc's two banks "both answer at $C000" // (Apple Computer, Inc., 1985e, Appendix F.2). Bank 1's entry // points are thunks that flip straight back for the Monitor, // which is how the same $d000-$ffff is reached from either. const bank: usize = if (comptime kind == .iic) @as(usize, self.rom_bank) * rom_size else 0; return &self.rom[bank + (address - 0xc000)]; } /// Lays a ROM image down so that its last byte falls at $ffff. pub fn loadROMAtEnd(self: *Self, image: []const u8) !void { if (comptime kind == .iic) { // A IIc's ROM is one 16K bank on the original machine and // two on every revision after it: the 32K holds a main // bank and "the extra 16K of ROM" that $C028 switches in // (Apple Computer, Inc., 1985e, Appendix F.2). A 32K image // is the two banks in order, main first; a 16K image is the // one bank, and $C028 is left with nothing to switch to. if (image.len == 2 * rom_size) { @memcpy(self.rom[0..], image[0 .. 2 * rom_size]); self.banked = true; } else { const tail = if (image.len > rom_size) image[image.len - rom_size ..] else image; @memcpy(self.rom[rom_size - tail.len .. rom_size], tail); self.banked = false; } self.rom_bank = 0; self.rom_version = self.rom[iic_version - 0xc000]; // Only the IIc Plus has the multidrive interface glue, // and its ROM is the one that leaves a hole at $ce00 // for the chip to answer in. See `mig.zig`. self.mig_fitted = self.rom_version == iic_plus_version; self.disk.three_and_a_half = self.mig_fitted; return; } // An image bigger than the space it is going into keeps its // tail, which is what "at end" means and what the common 32K IIe // dump wants. That image is two 16K banks differing only at // $c000-$cfff, and the second is the half with the firmware in // it; the first is filler. const tail = if (image.len > rom_size) image[image.len - rom_size ..] else image; @memcpy(self.rom[rom_size - tail.len ..], tail); // Which IIe this is, the ROM says: "The identification byte // at $FBC0 has been changed. In the original Apple IIe it was // $EA (decimal 234), in the enhanced Apple IIe it is $E0 // (decimal 224)" (Apple Computer, Inc., 1985b, p. xxix). The // enhancement was four chips fitted together — the 65C02, // the CD and EF ROMs, and "a new video ROM containing the // same MouseText characters found in the Apple IIc" (same // page) — so the firmware found in the socket says which // character generator is beside it. A IIc is not asked: it // has MouseText from the first one sold. if (comptime kind == .iie) { self.firmware = switch (self.rom[identification - 0xc000]) { 0xea => .original, 0xe0 => .enhanced, else => .unknown, }; switch (self.firmware) { .original => self.character_set = .apple2e, .enhanced => self.character_set = .apple2e_enhanced, .unknown => {}, } } } /// Puts a particular character generator in the socket, which /// is what an owner who changed the chip by itself did — the /// enhancement's four chips were sold together but went in /// one at a time. pub fn fitCharacterGenerator(self: *Self, set: font.Set) void { self.character_set = set; } /// Fits the Disk II card by giving it its ROM: the 256 bytes of /// the P5 boot PROM, which is what the machine runs when it /// starts from a disk. /// **The card keeps the bytes rather than a copy of them**, so /// whoever read the file has to hold on to it for as long as /// the machine is running — see `slots.zig`, and the session, /// which is what holds them. /// /// This and the other named loaders below put a card in the /// slot it has always gone in and take out whatever was there, /// because "fit a Videoterm, then an UltraTerm" plainly means /// the second. The `fit*` pairs beside them take a slot and /// refuse one that is occupied. pub fn loadCardROM(self: *Self, image: []const u8) !void { if (comptime !kind.slotted()) return error.WrongSize; _ = self.slots.empty(default_slot.disk); return self.fitDisk(default_slot.disk, image); } pub fn fitDisk(self: *Self, slot: u3, image: []const u8) !void { if (comptime !kind.slotted()) return error.WrongSize; if (image.len != card_rom_size) return error.WrongSize; try self.slots.fit(slot, .{ .disk = .{ .rom = image[0..card_rom_size] } }); } /// Fits a Videoterm in slot 3, taking out whatever was there. /// /// A card here answers only when SLOTC3ROM says so. A IIe /// comes up with it off — the manual: "if a card is installed /// in the auxiliary slot when you turn on the power or reset /// the Apple IIe, the SLOTC3ROM switch is turned off" — and /// every IIe here has the extended eighty-column card in that /// slot, so a program wanting the card in slot 3 has to ask /// for it at $c00b. pub fn loadVidexROM( self: *Self, firmware: []const u8, charset: []const u8, alternate: ?[]const u8, ) !void { if (comptime !kind.slotted()) return error.WrongSize; _ = self.slots.empty(default_slot.eighty_column); return self.fitVidex(default_slot.eighty_column, firmware, charset, alternate); } pub fn fitVidex( self: *Self, slot: u3, firmware: []const u8, charset: []const u8, alternate: ?[]const u8, ) !void { if (comptime !kind.slotted()) return error.WrongSize; if (firmware.len != videx.firmware_size) return error.WrongSize; if (charset.len != videx.charset_size) return error.WrongSize; if (alternate) |second| { if (second.len != videx.charset_size) return error.WrongSize; } try self.slots.fit(slot, .{ .videx = .{ .rom = firmware[0..videx.firmware_size], .charset = charset[0..videx.charset_size], .alternate = if (alternate) |second| second[0..videx.charset_size] else null, } }); } pub fn videxCharsets(self: *Self) struct { set: *const [videx.charset_size]u8, alternate: ?*const [videx.charset_size]u8, } { const card = self.cardIn(.videx) orelse return .{ .set = &blank_charset, .alternate = null }; return .{ .set = card.videx.charset, .alternate = card.videx.alternate }; } /// And an UltraTerm, on the same terms. pub fn loadUltraTermROM(self: *Self, firmware: []const u8, charset: []const u8) !void { if (comptime !kind.slotted()) return error.WrongSize; _ = self.slots.empty(default_slot.eighty_column); return self.fitUltraTerm(default_slot.eighty_column, firmware, charset); } pub fn fitUltraTerm(self: *Self, slot: u3, firmware: []const u8, charset: []const u8) !void { if (comptime !kind.slotted()) return error.WrongSize; if (firmware.len != ultraterm.firmware_size) return error.WrongSize; if (charset.len != ultraterm.charset_size) return error.WrongSize; try self.slots.fit(slot, .{ .ultraterm = .{ .rom = firmware[0..ultraterm.firmware_size], .charset = charset[0..ultraterm.charset_size], } }); } /// Puts a Corvus Omninet Transporter in the slot the network /// software expects it in, with the card's own `$Cn00` PROM. /// /// That firmware is Corvus's rather than something this can /// build, so it is handed in the way a machine's ROM is; two /// hundred and fifty-six bytes off the 63S281 at U15. `node` /// is the number the card answers `Who Am I` with, which on /// the real board is a DIP switch on it. /// /// One card to a slot: fitting this takes the block device /// out, since they would otherwise both be in slot seven and /// both answering at `$c0f0`. pub fn fitTransporter(self: *Self, firmware: []const u8, node: u8) !void { if (comptime !kind.slotted()) return error.WrongSize; _ = self.slots.empty(default_slot.transporter); return self.fitTransporterIn(default_slot.transporter, firmware, node); } pub fn fitTransporterIn(self: *Self, slot: u3, firmware: []const u8, node: u8) !void { if (comptime !kind.slotted()) return error.WrongSize; if (firmware.len != transporter_rom_size) return error.WrongSize; try self.slots.fit(slot, .{ .transporter = .{ .card = .{ .fitted = true, .node = node }, .rom = firmware[0..transporter_rom_size], } }); } /// Fits a memory expansion card in slot 5, taking out whatever /// was there. /// /// Both halves are needed and neither is ours. The firmware is /// Applied Engineering's eight kilobytes, which is where the /// RAMdisk, the ProDOS driver, the SmartPort interface and the /// partition manager all live; the memory is however many of /// the four 256K blocks somebody fitted, and is not owned here /// so that a card with the battery option on it can be handed /// back what a previous run left in it. pub fn fitMemoryCard(self: *Self, firmware: []const u8, ram: []u8) !void { if (comptime !kind.slotted()) return error.WrongSize; _ = self.slots.empty(default_slot.memory); return self.fitRamFactor(default_slot.memory, firmware, ram); } pub fn fitRamFactor(self: *Self, slot: u3, firmware: []const u8, ram: []u8) !void { if (comptime !kind.slotted()) return error.WrongSize; if (firmware.len != ramfactor.rom_size) return error.WrongSize; if (ram.len == 0 or ram.len % ramfactor.block_size != 0) return error.WrongSize; if (ram.len > ramfactor.max_ram) return error.WrongSize; var card: ramfactor.Card = .{ .fitted = true, .ram = ram }; card.reset(); try self.slots.fit(slot, .{ .ramfactor = .{ .card = card, .rom = firmware[0..ramfactor.rom_size], } }); } /// Puts an Apple II SCSI Card in a slot, given the card's own /// sixteen kilobytes of firmware. The disk on the bus is set /// afterwards through `scsiCard`, since the image is the /// caller's and this only fits the card. pub fn fitScsi(self: *Self, slot: u3, firmware: []const u8) !void { if (comptime !kind.slotted()) return error.WrongSize; 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], } }); // Nothing is on the cable yet: `attach` is what puts a // drive there, and the bus has to be rewired whenever the // card moves, since it holds pointers into the card. self.slots.cards[slot].scsi.rewire(); } /// The SCSI card in a slot, or null if there is not one there. pub fn scsiCard(self: *Self, slot: u3) ?*slot_module.Card.Scsi { if (comptime !kind.slotted()) return null; return switch (self.slots.cards[slot]) { .scsi => |*c| c, else => null, }; } /// Fits a RamWorks card in the auxiliary slot: its extra banks — /// banks one and up, bank zero being the motherboard's own /// auxiliary 64K — in storage the caller allocates and keeps /// alive for as long as the machine uses it, since a machine /// costs nothing until somebody hands it the memory. Forty-seven /// of them on top of the bank the machine already has is a /// RamWorks III's three megabytes. /// /// Called after `init`, which resets the field, and the banks /// are cleared here the way the machine's own memory is. It is a /// IIe part: a IIc has the auxiliary slot soldered over, and /// asking there does nothing. pub fn fitRamWorks(self: *Self, extra_banks: []Half) void { if (comptime kind == .iie) { for (extra_banks) |*bank| bank.clear(); self.ramworks = extra_banks; self.aux_bank = 0; } } /// Puts an Apple IIc Memory Expansion Card in the connector /// inside the case. /// /// Only the memory, because that is all the card is: the /// driver for it is in the machine's own ROM rather than on /// the card, which is why this wants no firmware where the /// RamFactor above wants eight kilobytes of it. A megabyte is /// the most the twenty-bit address counter can reach (Apple /// Computer, Inc., 1987b, p. 7), and the firmware works out /// how much is really there by writing past the top and /// seeing what comes back. /// /// Its registers answer from the start and go on answering /// through a reset: there is no firmware page to wake them, /// the way a card in a slot has. pub fn fitMemoryExpansion(self: *Self, ram: []u8) !void { if (comptime kind != .iic) @compileError("only a IIc has the memory expansion connector"); if (ram.len == 0 or ram.len % ramfactor.block_size != 0) return error.WrongSize; if (ram.len > max_memory_expansion) return error.WrongSize; self.memory_card.ram = ram; self.memory_card.fitted = true; self.memory_card.reset(); self.memory_card.enabled = true; } /// Whether a card in slot 3 is the thing answering there. /// /// Two switches decide it and both must agree. SLOTCXROM — the /// inverse of what is called `intcxrom` here — takes the whole /// of `$c100` to `$c7ff` away from the slots when it is off: /// "setting SLOTCXROM low enables built-in ROM in all of the /// I/O memory space (except the soft-switch area), including /// the $C300 space". And SLOTC3ROM decides slot 3 alone: "when /// SLOTC3ROM is on, the 256-byte ROM area at $C300 is /// available to a peripheral card in slot 3 ... turning /// SLOTC3ROM off disables peripheral-card ROM in slot 3 and /// enables the built-in 80-column firmware" (Apple Computer, /// Inc., 1985b, Chapter 6). pub fn slotThreeIsCard(self: *const Self) bool { return self.slotc3rom and !self.intcxrom; } /// Fits the Super Serial Card by giving it its firmware: the two /// kilobytes of 341-0065. The last page of it is what answers in /// the slot and the whole of it is the expansion ROM. pub fn loadSerialROM(self: *Self, image: []const u8) !void { if (comptime !kind.slotted()) return error.WrongSize; _ = self.slots.empty(default_slot.serial); return self.fitSerial(default_slot.serial, image); } pub fn fitSerial(self: *Self, slot: u3, image: []const u8) !void { if (comptime !kind.slotted()) return error.WrongSize; if (image.len != serial_rom_size) return error.WrongSize; try self.slots.fit(slot, .{ .serial = .{ .acia = .{ .cycles_per_second = cycles_per_second }, .rom = image[0..serial_rom_size], } }); } /// Puts the card's interrupt jumper in or out. Out is where it /// normally is, and where it starts. A IIc's port is soldered /// down and has no jumper, so this is the card's alone. pub fn setSerialInterrupts(self: *Self, connected: bool) void { if (comptime kind == .iic) { self.serial_interrupts = connected; } else { const slot = self.slots.first(.serial) orelse return; self.slots.cards[slot].serial.interrupts = connected; } self.updateInterrupt(); } /// Hands the chip a byte from outside. False if the machine has /// not read the last one, which is an overrun and loses one. pub fn serialReceive(self: *Self, byte: u8) bool { const acia = self.serialAcia() orelse return false; const room = acia.receive(byte); self.updateInterrupt(); return room; } /// What the machine has sent, oldest first, and dropping them. pub fn serialSent(self: *Self) []const u8 { const acia = self.serialAcia() orelse return &.{}; return acia.sent(); } pub fn serialConsume(self: *Self, count: usize) void { const acia = self.serialAcia() orelse return; acia.consume(count); } /// Copies a program into main RAM, whatever the switches say. Loading /// a program is not something the processor did, so it is not subject /// to the machine's current idea of where memory is. pub fn loadProgram(self: *Self, location: u16, program: []const u8) !void { const end = @as(usize, location) + program.len; if (end > ram_size) return error.Overflow; @memcpy(self.main.ram[location..end], program); } /// Which half the 48K space is talking to for this access. 80STORE /// carves two windows out of it that follow PAGE2 instead, and it /// wins over RAMRD and RAMWRT where it applies. fn half(self: *Self, address: u16, writing: bool) *Half { if (self.store80) { const text_page = address >= 0x0400 and address <= 0x07ff; const hires_page = self.hires and address >= 0x2000 and address <= 0x3fff; if (text_page or hires_page) return if (self.page2) self.auxHalf() else &self.main; } const auxiliary = if (writing) self.ramwrt else self.ramrd; return if (auxiliary) self.auxHalf() else &self.main; } /// The auxiliary half the *processor* reaches: bank zero is /// `aux`, the motherboard's own 64K, and banks one and up are /// the RamWorks card's, chosen by the register at $C073. A bank /// past what is fitted falls back to bank zero, the way a card /// decodes only the banks it has. Without a card, or on a IIc, /// this is always `aux`, which is what the machine had before /// RamWorks was a thing. /// /// The video scanner does not come through here: it always reads /// bank zero, whichever bank the processor has selected. See /// `videoByte`. fn auxHalf(self: *Self) *Half { if (comptime kind == .iie) { const bank = self.aux_bank; if (bank != 0 and bank <= self.ramworks.len) return &self.ramworks[bank - 1]; } return &self.aux; } /// What the video circuitry reads, which is not what the processor /// reads. /// /// The screen is drawn out of memory directly, and the switches /// that decide which half the processor is talking to have /// nothing to say about it. RAMRD can be pointing the processor /// at auxiliary memory while the screen carries on showing what /// is in main, and 80STORE moves the window the processor writes /// through rather than the one the display comes from. /// /// Eighty column text is two forty column pages side by side: /// the same address in each half, auxiliary supplying the even /// columns and main the odd ones. That is the whole of the /// trick, and it is why the eighty column card is memory rather /// than a display. Technical reference, chapter 2. /// A foreground and background for the whole text screen, for /// `video.scanLine`. A pair for the *whole* screen: the hook was /// shaped for an Apple III, whose colour text has a pair per /// character, so the arguments are taken and not looked at. pub fn textColour(self: *const Self, width: u16, base: u16, column: u16) ?TextColours { _ = width; _ = base; _ = column; return self.given_text_colours; } pub fn videoByte(self: *const Self, auxiliary: bool, address: u16) u8 { // Always bank zero, never a RamWorks bank. The card draws // the screen from bank zero whichever bank is selected: // "Only Bank 0 contains the video information ... This // feature, unique to RamWorks, eliminates a screen flicker // problem inherent with some other brands of memory cards // when they access other banks" (Applied Engineering, n.d.-b, // Chapter 7). So the display region a program *writes* // follows the selected bank, through `half`, but what the // scanner *reads* does not, which is why a program must be // in bank zero to put something on the visible screen. const from = if (auxiliary) &self.aux else &self.main; return from.ram[address]; } /// Which of the two text pages the screen is drawn from. /// /// PAGE2 normally chooses between them. With 80STORE on it stops /// meaning that at all and becomes the main-or-auxiliary switch /// for the processor's window into the first page, so the display /// stays where it is. Technical reference, table 2-6. pub fn displayPage(self: *const Self) u16 { return if (self.page2 and !self.store80) 0x0800 else 0x0400; } /// And which of the two Hi-Res pages, by exactly the same rule /// eight kilobytes further up. pub fn hiresPage(self: *const Self) u16 { return if (self.page2 and !self.store80) 0x4000 else 0x2000; } /// Which character generator is in the socket. /// /// A IIc only ever had the enhanced one, and so did a IIe from /// 1983 onwards; the original IIe's differs only at $40-$5F, /// where MouseText went. It is a field rather than a constant /// because it is a chip in a socket and somebody may want the /// other one. pub fn characterSet(self: *const Self) font.Set { return self.character_set; } /// The phase of the flash clock, counted from the machine's /// own cycles rather than from the wall. See font.flashing. pub fn flashing(self: *Self) bool { return font.flashing(self.getCPU().clock.cycles, cycles_per_second); } /// Whether the screen is showing eighty columns rather than forty. pub fn columns(self: *const Self) u16 { return if (self.col80) 80 else 40; } /// What the display is doing, which is the five switches read /// together. Technical reference, table 2-6. /// /// Doubling takes two of them: annunciator 3 to ask for it and /// 80COL to be on, because what doubles the resolution is the /// auxiliary half of memory reaching the screen, and it is the /// eighty-column circuit that fetches it. /// Whether the colour burst is on the video signal. "The /// COLOR BURST does not occur if the TEXT soft switch is set" /// (Sather, 1985, p. 8-4), which is the IIe keeping the killer /// the Apple II grew at Revision 1: white text in TEXT mode, /// coloured text under mixed graphics. The Mega II inside a /// IIgs is the exception. There the burst stays and the VGC's /// Monochrome/Color register is what takes the colour out of /// text, in text mode only (Apple Computer, Inc., 1989a, p. /// 83); with that register clear a IIgs's text is fringed, and /// it is not this chip's decision to make. pub fn colourBurst(self: *const Self) bool { if (comptime options.host == .given) return true; return !self.text; } /// A IIe delays Hi-Res dots on bit 7 as every board after the /// first Apple II did. pub fn delaysHires(self: *const Self) bool { _ = self; return true; } pub fn mode(self: *const Self) screen.Mode { if (self.text) return if (self.col80) .text_80 else .text; const doubled = self.col80 and self.double_hires; if (self.hires) return if (self.mixed) (if (doubled) .double_high_resolution_mixed else .high_resolution_mixed) else (if (doubled) .double_high_resolution else .high_resolution); return if (self.mixed) (if (doubled) .double_low_resolution_mixed else .low_resolution_mixed) else (if (doubled) .double_low_resolution else .low_resolution); } /// Whether the alternate character set is switched in, which /// decides whether the middle of the set flashes or is inverse. pub fn alternateCharacters(self: *const Self) bool { return self.altchar; } /// Writes what is on the text screen, row by row in reading /// order with nothing between the rows. See screen.write. pub fn writeText(self: *Self, writer: *std.Io.Writer) std.Io.Writer.Error!void { return screen.write(self, writer); } /// The zero page, the stack and the language card all follow ALTZP /// together, and none of them care about RAMRD or RAMWRT. fn zeroPageHalf(self: *Self) *Half { return if (self.altzp) self.auxHalf() else &self.main; } fn readTarget(self: *Self, address: u16) ?*const u8 { return switch (address) { 0x0000...0x01ff => &self.zeroPageHalf().ram[address], 0x0200...0xbfff => &self.half(address, false).ram[address], 0xc000...0xc0ff => null, // The slot pages. Which of the machine and the cards // is answering here is asked once, at the top, rather // than by every card for itself: it is a question // about three soft switches and not about what is // plugged in. Below this line a card that is fitted // answers, full stop. // // A IIc has no slots, so none of the card pages // below apply to it: every address from $c100 to // $cfff is its own firmware, which is where the // serial ports, the mouse, the eighty column code and // the disk driver all live. 0xc100...0xcfff => if (comptime !kind.slotted()) (if (self.migAnswers(address)) null else self.romByte(address)) else if (!self.slotsAnswerAt(address)) self.romByte(address) else switch (self.slots.page(address)) { .rom => |byte| byte, // A Mockingboard's page is its two 6522s, so the // read has to fall through to `softSwitch` and be // an access rather than a byte. .registers => null, .none => self.withoutCard(), }, 0xd000...0xdfff => if (self.card_switches.read_ram) &self.zeroPageHalf().bank[@intFromBool(self.card_switches.bank2)][address - 0xd000] else self.romByte(address), 0xe000...0xffff => if (self.card_switches.read_ram) &self.zeroPageHalf().high[address - 0xe000] else self.romByte(address), }; } /// Whether a key is waiting to be read, which is the strobe /// and not merely whether a key was ever pressed. /// /// For a machine with this one inside it that has to answer /// the same question somewhere else: an Apple IIgs reports it /// in bit 4 of the Apple Desktop Bus status register, and /// there should be one answer rather than two. pub fn keyWaiting(self: *const Self) bool { return self.strobe; } /// Which half the switches point at for a given address, /// which is what a machine with this one inside it needs when /// its bank latch is *not* set and the old switches are to /// decide after all. /// /// The same choice `readTarget` and `writeTarget` make, said /// out loud: the zero page, the stack and the language card /// follow ALTZP, and the rest follows 80STORE, RAMRD and /// RAMWRT. pub fn auxiliaryFor(self: *Self, address: u16, writing: bool) bool { const side = switch (address) { 0x0000...0x01ff, 0xd000...0xffff => self.zeroPageHalf(), 0x0200...0xbfff => self.half(address, writing), 0xc000...0xcfff => return false, }; // Anything that is not the main half is auxiliary, whichever // RamWorks bank it happens to be. return side != &self.main; } /// A byte of one half named outright, rather than of /// whichever half the switches happen to select. /// /// For a machine with this one inside it that addresses the /// two halves directly. An Apple IIgs does: its banks `$e0` /// and `$e1` are these two, and when the bank latch is set the /// bank address says which, with RAMRD, RAMWRT, ALTZP and /// 80STORE having no say in it at all. /// /// The language card switches do still apply, because in those /// banks the language card is always there — the Shadow /// register's inhibit bit reaches banks `$00` and `$01` and /// not these. Null means the address is not RAM at the moment: /// the switch page, or the language card window while it is /// reading ROM. What is at those addresses instead is the /// caller's business, since on a IIgs it is the IIgs's ROM /// rather than this machine's. pub fn halfTarget(self: *Self, auxiliary: bool, address: u16, writing: bool) ?*u8 { const side = if (auxiliary) &self.aux else &self.main; const card = if (writing) self.card_switches.write_ram else self.card_switches.read_ram; return switch (address) { 0x0000...0xbfff => &side.ram[address], 0xc000...0xcfff => null, 0xd000...0xdfff => if (card) &side.bank[@intFromBool(self.card_switches.bank2)][address - 0xd000] else null, 0xe000...0xffff => if (card) &side.high[address - 0xe000] else null, }; } fn writeTarget(self: *Self, address: u16) ?*u8 { return switch (address) { 0x0000...0x01ff => &self.zeroPageHalf().ram[address], 0x0200...0xbfff => &self.half(address, true).ram[address], // Nothing in the I/O space is memory a program writes // to, with one exception: an eighty-column card's // window is its screen memory, and putting a character // on that screen is a write to it. 0xc000...0xcfff => if (comptime !kind.slotted()) null else if (self.slotsAnswerAt(address)) self.slots.windowTarget(address) else null, 0xd000...0xdfff => if (self.card_switches.write_ram) &self.zeroPageHalf().bank[@intFromBool(self.card_switches.bank2)][address - 0xd000] else null, 0xe000...0xffff => if (self.card_switches.write_ram) &self.zeroPageHalf().high[address - 0xe000] else null, }; } /// Reads a byte with the processor not involved: no cycle, no bus log, /// and no soft switch disturbed. pub fn peek(self: *Self, address: u16) u8 { const target = self.readTarget(address) orelse return 0; return target.*; } /// Writes a byte with the processor not involved, as `peek`. pub fn poke(self: *Self, address: u16, value: u8) void { const target = self.writeTarget(address) orelse return; target.* = value; } /// A status read reports its answer in the high bit and leaves /// the rest as whatever the bus was carrying, which is the /// video scanner's last byte. Programs are supposed to test /// bit 7 and ignore the rest; the ones that do not are reading /// the screen through the side door, and now they get what the /// hardware gave them. /// Whether this machine has annunciator pins at all. A IIe /// has four on its game connector; a IIc has none, and puts /// the mouse and the blanking interrupt at their addresses /// instead. It is a constant rather than something to work out /// from the type, because both machines are this one file with /// a different `kind`, so a declaration exists either way and /// `@hasDecl` cannot tell them apart. pub const has_annunciators = kind != .iic; /// What one of the four annunciator pins is doing. /// /// Nothing on the machine can ask this. "There is no way to /// read the state of an annunciator" (Apple Computer, Inc., /// 1985b, p. 40), and there is no soft switch here that says /// otherwise -- this is for a program using this as a library, /// which is on the other side of the game connector and can /// see the pins the way a lamp would. /// /// The IIgs is the one machine where an annunciator *is* /// readable, and only the third: its Interrupt Flag register /// keeps AN3 in bit 5. That is the same latch as this, seen /// from the sixteen-bit side; see `apple2gs.zig`. /// /// Only three of the four are stored. The fourth is /// `double_hires` inverted, because clearing annunciator 3 is /// how double resolution is asked for -- `$c05e` clears the /// pin and turns the mode on, `$c05f` sets the pin and turns /// it off -- and keeping one latch under two names is what /// makes it impossible for them to disagree. pub fn annunciator(self: *const Self, which: u2) bool { if (comptime kind == .iic) @compileError("a IIc has no annunciator outputs"); return if (which == 3) !self.double_hires else self.annunciators[which]; } fn status(self: *Self, on: bool) u8 { return (if (on) @as(u8, 0x80) else 0) | (self.floatingBus() & 0x7f); } /// The four ports a IIc has soldered to its board, at the /// sixteen-address blocks the cards they replace would have /// used — which is where the machine's own firmware looks for /// them, and the whole reason they are at those addresses. /// /// A IIe reaches every one of these through `slots` instead. /// They were cases named after slots this machine does not /// have, which is what made that code hard to read: `$c0c0` is /// not "the mouse card's address, except on a IIc" — on a IIc /// it is the memory expansion connector and there is no slot 4. fn builtInPort(self: *Self, low: u8, is_write: bool, value: u8) u8 { if (comptime kind != .iic) return 0; return switch (low) { // The printer port, where slot 1's card would have been. printer_switch_base + 8...printer_switch_base + 11 => port: { const register: serial.Register = @enumFromInt(@as(u2, @truncate(low - (printer_switch_base + 8)))); const cycle = self.getCPU().clock.cycles; if (!is_write and register == .status) self.printer_listening = true; defer self.updateInterrupt(); if (is_write) { self.printer.write(register, value, cycle); break :port 0; } break :port self.printer.read(register, cycle); }, // And the modem port, where slot 2's card would have // been. `serial_listening` is the one thing outside // wants: a byte handed over before the firmware has // opened the port is thrown away by the reset it does // on its way in. serial_switch_base + 8...serial_switch_base + 11 => port: { const register: serial.Register = @enumFromInt(@as(u2, @truncate(low - (serial_switch_base + 8)))); const cycle = self.getCPU().clock.cycles; if (!is_write and register == .status) self.serial_listening = true; defer self.updateInterrupt(); if (is_write) { self.acia.write(register, value, cycle); break :port 0; } break :port self.acia.read(register, cycle); }, // The memory expansion connector inside the case, // whose first four addresses are its address counter // and its data register (Apple Computer, Inc., 1987b, // p. 7). The rest of the sixteen it does not decode, // which `access` answers for itself. memory_expansion_switch_base...memory_expansion_switch_base + 0x0f => port: { if (low > memory_expansion_switch_base + 3) break :port ramfactor.undriven; break :port self.memory_card.access(@truncate(low), is_write, value); }, // And the disk port, which is an Integrated Woz // Machine rather than a card: the same sixteen // switches with three registers a card never had. // // The glue chip sits between the two on a IIc Plus, so // what its latches say is worked out before the access // rather than after: choosing a drive is one of these // sixteen, and which drive that reaches is the chip's // answer. card_switch_base...card_switch_base + 0x0f => port: { self.syncDiskPort(); const answer = self.disk.access( @truncate(low), is_write, value, self.getCPU().clock.cycles, ); self.syncDiskPort(); break :port answer; }, else => 0, }; } /// Acts on a touch of $c000 to $c0ff. /// /// The IIe divides this page by what an access is for: writing to /// $c000-$c00f throws a switch, reading $c010-$c01f asks one what it /// is set to, and $c050 upwards responds to either. Table 4-7. fn softSwitch(self: *Self, address: u16, is_write: bool, value: u8) u8 { // Nor is the multidrive interface glue: it answers in a // page of its own at $ce00, not among the switches, so it // is dealt with before the low byte means what it means // below. See `mig.zig`. if (comptime kind == .iic) { if (self.migAnswers(address)) { const answer = self.mig.access(address, is_write, value); self.syncDiskPort(); return answer; } // And the strobes outside its page, which the ROM still // answers because the chip has no data bus pins: it // watches the bus and latches, and never drives a byte. // // Returning here matters. These are `$ccxx` addresses, // and the low byte of one is the low byte of a switch: // `$cc80` would fall through to the language card's // sixteen and `$ccc0` to the memory expansion's, which // wrecks the machine within a few hundred instructions. if (mig_chip.Mig.strobes(address)) { self.mig.strobe(address, is_write); // `IWMRES*` is a wire out of the glue chip and // into the disk chip's reset pin, so the pulse is // taken here rather than inside either of them. // Only the chip goes back: the drives are on the // other side of the cable, and which kind of drive // the port is talking to is the glue chip's own // line and not on this one. if (self.mig.takeIwmReset()) { self.disk.resetChip(self.getCPU().clock.cycles); } self.syncDiskPort(); return 0; } } // A Mockingboard is not among the switches: its two 6522s // are in the slot's own page, so it is dealt with before // the low byte of an address means what it means below. // `page` saying `.registers` is what says one is there, // and it is asked only where the slots are answering — with // INTCXROM set the machine's own ROM has the page and no // card is being selected at all. if (comptime kind.slotted()) if (address >= 0xc100 and self.slotsAnswerAt(address) and self.slots.page(address) == .registers) { const slot: u3 = @truncate(address >> 8); // Both a Mockingboard and a Phasor put their 6522s and // sound chips in this page, so `.registers` names either; // each keeps its own write log. const answer = switch (self.slots.cards[slot]) { .phasor => |*c| c.access( @truncate(address), is_write, value, &self.phasor_log, self.getCPU().clock.cycles, ), .soundspeech => |*c| c.access( @truncate(address), is_write, value, &self.soundspeech_log, self.getCPU().clock.cycles, ), else => self.slots.cards[slot].mockingboard.access( @truncate(address), is_write, value, &self.mockingboard_log, self.getCPU().clock.cycles, ), }; // Reading a timer is how a handler says it has dealt // with the interrupt, so the line is worked out again // rather than left where it was. self.updateInterrupt(); return answer; }; const low: u8 = @truncate(address); switch (low) { // Writing here throws a switch; reading returns the keyboard. 0x00...0x0f => { if (!is_write) return self.keyboardByte(); switch (low) { 0x00 => self.store80 = false, 0x01 => self.store80 = true, 0x02 => self.ramrd = false, 0x03 => self.ramrd = true, 0x04 => self.ramwrt = false, 0x05 => self.ramwrt = true, 0x06 => self.intcxrom = false, 0x07 => self.intcxrom = true, 0x08 => self.altzp = false, 0x09 => self.altzp = true, 0x0a => self.slotc3rom = false, 0x0b => self.slotc3rom = true, 0x0c => self.col80 = false, 0x0d => self.col80 = true, 0x0e => self.altchar = false, 0x0f => self.altchar = true, else => unreachable, } }, // Reading here asks a switch what it is set to. Writing clears // the keyboard strobe, whatever the address. 0x10...0x1f => { // Only $c010 clears the strobe on a read. The rest of this // range reads back the state of a switch, and a IIe reads // those constantly: the firmware asks after the display // and the blanking interval on its way through almost // everything. Clearing the keyboard on those reads, the way // a II Plus does because it decodes the address no more // finely than this, throws away every key within moments of // it being pressed. Table 2-11 lists these as read only. // // A write anywhere in the range still clears it, which is // the coarse decoding showing through on the other side. const any_key_down = self.anyKeyDown(); if (is_write or low == 0x10) { self.strobe = false; self.key_down = false; } if (is_write) return 0; return switch (low) { 0x10 => any_key_down, 0x11 => self.status(self.card_switches.bank2), 0x12 => self.status(self.card_switches.read_ram), 0x13 => self.status(self.ramrd), 0x14 => self.status(self.ramwrt), // A IIe says whether the internal ROM is // switched in. A IIc has no slots for it to be // switched in over, and says whether the mouse // has moved sideways instead. // // Reading does not clear it. The firmware in // the machine's own ROM reads this, then reads // it again to find out which of the two lines // it was, and clears both together at $c048 // once it has counted them. A read that // cleared would leave it looking at nothing // the second time and concluding the interrupt // was not its own. 0x15 => if (comptime kind == .iic) self.status(self.iic_mouse.x_interrupt) else self.status(self.intcxrom), 0x16 => self.status(self.altzp), // And the same for up and down. 0x17 => if (comptime kind == .iic) self.status(self.iic_mouse.y_interrupt) else self.status(self.slotc3rom), 0x18 => self.status(self.store80), // RDVBLBAR, and the bar matters: the bit is set while // the video is drawing and clear while it is blanking, // so a program waits for it to fall. // The IIe says whether the video is in the // blanking interval right now, with the bit // clear while it is. The IIc latches it // instead: the bit goes up when the interval // begins, the other way round from the IIe, // and stays up until this is read. 0x19 => switch (kind) { .iie => self.status(!self.blanking()), .iic => latched: { const was = self.vbl_interrupt; self.vbl_interrupt = false; self.updateInterrupt(); break :latched self.status(was); }, }, 0x1a => self.status(self.text), 0x1b => self.status(self.mixed), 0x1c => self.status(self.page2), 0x1d => self.status(self.hires), 0x1e => self.status(self.altchar), 0x1f => self.status(self.col80), else => any_key_down, }; }, // The speaker. Every access flips the cone, but a write // flips it twice in quick succession, and the manual is // clear that the cone cannot follow that: the pulse is too // short to make a sound and it ends where it started. Which // is why the manual says to toggle it with a read. 0x30...0x3f => { if (is_write) { self.speaker = !self.speaker; self.speaker = !self.speaker; } else { self.speaker = !self.speaker; self.speaker_clicks +%= 1; self.speaker_log.record(self.getCPU().clock.cycles); } }, 0x50 => self.text = false, 0x51 => self.text = true, 0x52 => self.mixed = false, 0x53 => self.mixed = true, 0x54 => self.page2 = false, 0x55 => self.page2 = true, 0x56 => self.hires = false, 0x57 => self.hires = true, // The cassette output, which is the speaker over // again: one bit, flipped by touching it, and a // program writes to tape by flipping it in patterns. // The IIc has no cassette port at all, and the // addresses do nothing there. 0x20...0x2f => if (comptime kind == .iie) { self.cassette_out = !self.cassette_out; self.cassette_log.record(self.getCPU().clock.cycles); } else if (comptime kind == .iic) { // "On the original Apple IIc, both reading from and // writing to these locations are reserved. The Apple // IIc with 32K of ROM uses $C028 to switch in or out // the extra 16K of ROM" — "to toggle between its two // 16K banks of memory" (Apple Computer, Inc., 1985e, // Appendix F.2, F.10). A toggle switch: each access // flips it (Section 2.4) — a cassette program "must // not access $C028" whether it reads or writes it // (Appendix F.10), so both arrive here. The original // machine has no second bank and `banked` leaves it // inert. if (low == 0x28 and self.banked) { self.rom_bank ^= 1; // The glue chip's reset line is not the // machine's: "Léon realized that this literally // means that ROM address 14 is tied to the // RESET line on the MIG… This means the MIG is // held reset whenever the ROM is in the main // bank" (MG, 2018, on pin 14). So switching // back to bank 0 puts every one of its latched // outputs back, and the firmware has to set // them again on its way in. It is also why // watching those pins on a real machine showed // only short pulses. if (comptime kind == .iic) { if (self.rom_bank == 0) self.mig.hold(); self.syncDiskPort(); } } }, // The cassette input, which is a zero crossing // detector: the top bit is which side of zero the // signal is on and there is nothing finer than that. // // On a IIc the socket is not there and the address is // the switch on the keyboard instead: down for eighty // columns, up for forty, which the firmware reads at // startup to decide which to come up in. 0x60 => return switch (kind) { .iie => if (self.cassetteInput()) 0x80 else 0, .iic => if (self.eighty_column_switch) 0x00 else 0x80, }, // The three buttons on the game connector, which on a // IIe are also the two Apple keys. Only the top bit // means anything; a real machine leaves the rest to // whatever the video circuitry last put on the bus. 0x61...0x63 => { // The third of them is the mouse button on a IIc, // and it is the one thing on the machine that // reads the other way round: the bit is up when // the button is not being pressed. if (comptime kind == .iic) { if (low == 0x63) return self.status(!self.iic_mouse.button); } return if (self.buttons[low - 0x61]) 0x80 else 0; }, // The paddles, which answer with the top bit set until // their timer runs down. How long that is is the whole // of what a paddle tells the machine. // // The last two of them are not paddles on a IIc: the // pins carry the mouse's direction lines, which say // which way the movement just announced went. The // handler has forty microseconds to read them. 0x64...0x67 => { if (comptime kind == .iic) { if (low == 0x66) return self.status(self.iic_mouse.x_direction); if (low == 0x67) return self.status(self.iic_mouse.y_direction); } const elapsed = self.getCPU().clock.cycles -| self.paddle_started; return if (elapsed < self.paddleRuns(low - 0x64)) 0x80 else 0; }, // Starting the paddle timers, which is what a program // does before counting how long they take. // // Touching here, either way round, also clears the // vertical blanking latch. Technical reference, table // 2-9, and the footnote that goes with it. 0x70...0x7f => { // The last two of these are not the timers on a // IIc: they say whether the addresses from $c058 // to $c05f work the video switches underneath the // annunciators or the annunciators themselves, // which is how double high resolution is turned // on. Nothing here draws that, but a program that // sets it can read it back. if (comptime kind == .iic) { switch (low) { 0x7e, 0x7f => { // These two work the IOU as well as // doing what all of $c07x does, which // is why the blanking flag is cleared // here too. if (is_write) self.ioudis = low == 0x7e; self.vbl_interrupt = false; self.updateInterrupt(); // Both read back **inverted**, which // is the manual being precise rather // than this being clever: "Read IOUDis // switch (1 = off)" and "Read DHiRes // switch (1 = off)" (Apple Computer, // Inc., 1989b, Table 9-2, p. 256, and // Table 6-9). A one is the switch not // being on. return if (low == 0x7e) self.status(!self.ioudis) else self.status(!self.double_hires); }, else => {}, } } // A RamWorks card in the auxiliary slot watches for // a write to $C073 and latches the low byte as the // bank number, on top of $C07x's own job of firing // the paddle timers: "Writing to the bank select // register will also trigger the paddle strobe" // (Applied Engineering, n.d.-b, Chapter 7). It is // write only -- "You cannot read the contents of the // bank select register" -- so nothing here answers a // read of it, and it is not cleared by a reset (the // card cannot see the RESET line; it comes up zero // only on power-on, which `init` does), which is why // reset below leaves `aux_bank` alone. if (comptime kind == .iie) { if (is_write and low == 0x73) self.aux_bank = value; } self.paddle_started = self.getCPU().clock.cycles; self.vbl_interrupt = false; self.getCPU().irq = false; }, // The eight addresses that are two things at once. // // On a IIe they are the four annunciators, plain: "any // reference to the first location of a pair turns the // corresponding annunciator off; a reference to the // second location turns the annunciator on" (Apple // Computer, Inc., 1985b, Table 2-11, p. 40). Both ways // round, because the IOU decodes the address and // ignores the data bus (Sather, 1985, p. 2-16). // // A IIc has no annunciator pins at all -- "the Apple // IIc family does not support the four annunciator // outputs" (Apple Computer, Inc., 1989b, Appendix D) // -- and puts the mouse and the blanking interrupt // here instead, behind `IOUDis`. Which of the two a // IIc is showing is the whole of what that switch is // for; see `ioudis`. 0x58...0x5f => { if (comptime kind == .iic) { // IOUDis **on** is the state the machine comes // up in and the state the firmware leaves it // in: the IOU is out of the way, `$c058` to // `$c05d` do nothing at all, and only the last // pair means anything. IOUDis **off** is what // a program turns on to reach the mouse. if (self.ioudis) { if (low >= 0x5e) self.double_hires = low == 0x5e; return 0; } switch (low) { // DisXY and EnbXY: the mask on the two // movement interrupts rather than a switch // that turns the mouse off, though nothing // here can tell the difference. 0x58, 0x59 => { self.iic_mouse.enabled = low == 0x59; if (!self.iic_mouse.enabled) { self.iic_mouse.x_interrupt = false; self.iic_mouse.y_interrupt = false; } self.updateInterrupt(); }, 0x5a => self.vbl_interrupt_enabled = false, 0x5b => self.vbl_interrupt_enabled = true, // Which edge of each movement line to // interrupt on. Nothing here counts edges // the mouse did not make, so which one is // chosen changes nothing but what reading // it back says. 0x5c, 0x5d => self.x_edge = low == 0x5d, 0x5e, 0x5f => self.y_edge = low == 0x5f, else => unreachable, } return 0; } // And a IIe, where all four are pins on the game // connector. The third of them is also what asks // for double resolution, so it is kept as // `double_hires` -- one latch under two names -- // and `annunciator` is what puts the two together. if (low >= 0x5e) self.double_hires = low == 0x5e else self.annunciators[(low - 0x58) >> 1] = low & 1 == 1; }, // Which movement is waiting to be owned up to. 0x40 => if (comptime kind == .iic) { var flags: u8 = 0; if (self.iic_mouse.x_interrupt) flags |= 0x80; if (self.iic_mouse.y_interrupt) flags |= 0x40; return flags; }, // And which edges were asked for. 0x42 => if (comptime kind == .iic) return self.status(self.x_edge), 0x43 => if (comptime kind == .iic) return self.status(self.y_edge), // Owning up: one line, the other, or both. 0x48 => if (comptime kind == .iic) { self.iic_mouse.x_interrupt = false; self.iic_mouse.y_interrupt = false; self.updateInterrupt(); }, 0x80...0x8f => self.card_switches.switched(@truncate(low), is_write), // The mouse's registers. Each one is a word with // the card, which does the work itself and leaves the // answer in the screen holes, as the processor on a // real card's own board does. // Every slot's sixteen device select addresses, which // used to be seven separate cases naming seven // constants. The slot is the address — $C080 + slot*16 // — so $c090 upwards is slot 1 and up, and the sixteen // below them are the language card's above. // // A IIc has no slots at all: what is in this range on // one is a port soldered to the board, at the addresses // the card it replaces would have used. See // `builtInPort`. 0x90...0xff => return if (comptime kind.slotted()) self.slots.access(self, low, is_write, value) orelse 0 else self.builtInPort(low, is_write, value), else => {}, } // Nothing here drove the bus, so what a read of it gets is // whatever was last on it. Touching $c050 to turn graphics // on is not a question with an answer, and the byte it // gives back is the video scanner's. return self.floatingBus(); } /// Reads memory, spending a cycle per byte and logging each one. pub fn read(self: *Self, comptime T: type, address: u16) T { const cpu = self.getCPU(); const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { cpu.clock.sleep(1); self.updateVideo(); self.claimExpansion(address); const value = if (self.readTarget(address)) |target| target.* else self.softSwitch(address, false, 0); self.bus.record(address, value, .read); return value; }, 16 => { const low = self.read(u8, address); const high = self.read(u8, address +% 1); return @as(u16, high) << 8 | low; }, else => @compileError("must be a u8 or a u16"), } } /// Writes memory, spending a cycle per byte and logging each one. pub fn write(self: *Self, comptime T: type, address: u16, value: T) void { const cpu = self.getCPU(); const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { cpu.clock.sleep(1); self.updateVideo(); self.claimExpansion(address); self.bus.record(address, value, .write); if (self.writeTarget(address)) |target| { target.* = value; } else if (address & 0xff00 == 0xc000 or (if (comptime kind.slotted()) self.slots.page(address) == .registers else false) or self.migAnswers(address) or (kind == .iic and mig_chip.Mig.strobes(address))) { _ = self.softSwitch(address, true, value); } }, 16 => { self.write(u8, address, @truncate(value)); self.write(u8, address +% 1, @truncate(value >> 8)); }, else => @compileError("must be a u8 or a u16"), } } }; } }.model; } const testing = std.testing; const TestCPU = @import("../cpu8.zig").CPU(@import("../clock.zig").FakeClock, AppleIIe(.{})); fn machine() !TestCPU { var cpu: TestCPU = undefined; try cpu.init(null, null); return cpu; } test "a IIe kills the colour burst in TEXT mode and keeps the Hi-Res delay" { // "The COLOR BURST does not occur if the TEXT soft switch is set" // (Sather, 1985, p. 8-4). var cpu: TestCPU = undefined; try cpu.init(null, null); try testing.expect(!cpu.memory.colourBurst()); _ = cpu.memory.read(u8, 0xc050); try testing.expect(cpu.memory.colourBurst()); _ = cpu.memory.read(u8, 0xc051); try testing.expect(!cpu.memory.colourBurst()); try testing.expect(cpu.memory.delaysHires()); } test "RAMRD and RAMWRT move the 48K space, and do it independently" { var cpu = try machine(); cpu.memory.write(u8, 0x2000, 0x11); // main cpu.memory.write(u8, 0xc005, 0); // RAMWRT on: writes go to aux cpu.memory.write(u8, 0x2000, 0x22); // Reading still comes from main, so the main byte is what is seen. try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x2000)); cpu.memory.write(u8, 0xc003, 0); // RAMRD on: reads come from aux try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(u8, 0x2000)); // And back again. cpu.memory.write(u8, 0xc002, 0); cpu.memory.write(u8, 0xc004, 0); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x2000)); } test "a RamWorks card banks the auxiliary memory, and $C073 chooses the bank" { var cpu = try machine(); // Three extra banks on top of the one the machine already has. A test // stands in for the caller that owns them; four banks is a quarter of a // megabyte, small enough for a stack. var extra: [3]Half = undefined; cpu.memory.fitRamWorks(&extra); // Reads and writes go to auxiliary memory throughout: RAMRD and RAMWRT on. cpu.memory.write(u8, 0xc005, 0); cpu.memory.write(u8, 0xc003, 0); // A distinct byte into $2000 of each of the four banks, chosen by $C073. for (0..4) |bank| { cpu.memory.write(u8, 0xc073, @intCast(bank)); // Each bank is its own fresh RAM, so what a later bank will hold is not // there yet. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0x2000)); cpu.memory.write(u8, 0x2000, @intCast(0xa0 + bank)); } // Each bank kept its own byte. for (0..4) |bank| { cpu.memory.write(u8, 0xc073, @intCast(bank)); try testing.expectEqual(@as(u8, @intCast(0xa0 + bank)), cpu.memory.read(u8, 0x2000)); } // Bank zero really is the motherboard's `aux`, and the extra banks are the // card's, in order. try testing.expectEqual(@as(u8, 0xa0), cpu.memory.aux.ram[0x2000]); try testing.expectEqual(@as(u8, 0xa1), extra[0].ram[0x2000]); try testing.expectEqual(@as(u8, 0xa3), extra[2].ram[0x2000]); // A bank past the three that are fitted reads back as bank zero, the way // the card decodes only the banks it has. cpu.memory.write(u8, 0xc073, 40); try testing.expectEqual(@as(u8, 0xa0), cpu.memory.read(u8, 0x2000)); // The video scanner reads bank zero whichever bank is selected -- the // card's anti-flicker feature, "Only Bank 0 contains the video // information" (Applied Engineering, n.d.-b, Chapter 7). A program writing // the display in bank one puts bytes where the screen is not drawn from; // the scanner still shows bank zero. It is why a program has to be in bank // zero to update the visible screen. cpu.memory.write(u8, 0xc073, 0); cpu.memory.write(u8, 0x0400, 0x40); // bank zero's text page cpu.memory.write(u8, 0xc073, 1); cpu.memory.write(u8, 0x0400, 0x41); // bank one's, not on screen try testing.expectEqual(@as(u8, 0x40), cpu.memory.videoByte(true, 0x0400)); cpu.memory.write(u8, 0xc073, 0); try testing.expectEqual(@as(u8, 0x40), cpu.memory.videoByte(true, 0x0400)); // And bank one really did take the write, through the processor's path. try testing.expectEqual(@as(u8, 0x41), extra[0].ram[0x0400]); // Main memory is untouched by any of the banking. cpu.memory.write(u8, 0xc002, 0); cpu.memory.write(u8, 0xc004, 0); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0x2000)); } test "ALTZP moves the zero page and the stack, and nothing else" { var cpu = try machine(); cpu.memory.write(u8, 0x0050, 0x11); cpu.memory.write(u8, 0x01ff, 0x22); cpu.memory.write(u8, 0x0800, 0x33); cpu.memory.write(u8, 0xc009, 0); // ALTZP on try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0x0050)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0x01ff)); // $0800 is not the zero page or the stack, so ALTZP leaves it alone. try testing.expectEqual(@as(u8, 0x33), cpu.memory.read(u8, 0x0800)); cpu.memory.write(u8, 0xc008, 0); // ALTZP off try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x0050)); try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(u8, 0x01ff)); } test "80STORE moves the text page on PAGE2, overriding RAMRD" { var cpu = try machine(); cpu.memory.write(u8, 0x0400, 0x11); // main text page cpu.memory.write(u8, 0xc001, 0); // 80STORE on cpu.memory.write(u8, 0xc055, 0); // PAGE2 on: the text page is now aux cpu.memory.write(u8, 0x0400, 0x22); try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(u8, 0x0400)); // Only the text page moved; its neighbours did not. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0x0800)); cpu.memory.write(u8, 0xc054, 0); // PAGE2 off try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x0400)); // 80STORE beats RAMRD over its window: RAMRD would say aux, but PAGE2 is // off so the text page still comes from main. cpu.memory.write(u8, 0xc003, 0); // RAMRD on try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x0400)); } test "80STORE only moves the hi-res page when HIRES is on" { var cpu = try machine(); cpu.memory.write(u8, 0x2000, 0x11); cpu.memory.write(u8, 0xc001, 0); // 80STORE cpu.memory.write(u8, 0xc055, 0); // PAGE2 // HIRES off: $2000 is not one of 80STORE's windows. try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x2000)); cpu.memory.write(u8, 0xc057, 0); // HIRES on try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0x2000)); cpu.memory.write(u8, 0x2000, 0x22); try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(u8, 0x2000)); cpu.memory.write(u8, 0xc054, 0); // PAGE2 off try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x2000)); } test "the language card follows ALTZP" { var cpu = try machine(); // Read and write the card, bank 2. _ = cpu.memory.read(u8, 0xc083); _ = cpu.memory.read(u8, 0xc083); cpu.memory.write(u8, 0xd000, 0x11); cpu.memory.write(u8, 0xe000, 0x11); cpu.memory.write(u8, 0xc009, 0); // ALTZP: the card moves too try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xd000)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xe000)); cpu.memory.write(u8, 0xd000, 0x22); cpu.memory.write(u8, 0xc008, 0); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0xd000)); } test "the bank switches behave as they do on a II Plus" { var cpu = try machine(); var image: [rom_size]u8 = @splat(0xaa); try cpu.memory.loadROMAtEnd(&image); try testing.expectEqual(@as(u8, 0xaa), cpu.memory.read(u8, 0xd000)); _ = cpu.memory.read(u8, 0xc082); // read ROM, write protect try testing.expect(!cpu.memory.card_switches.write_ram); _ = cpu.memory.read(u8, 0xc08b); // bank 1, and the first of a pair _ = cpu.memory.read(u8, 0xc08b); try testing.expect(cpu.memory.card_switches.read_ram); try testing.expect(!cpu.memory.card_switches.bank2); try testing.expect(cpu.memory.card_switches.write_ram); } test "status reads report the switches in the high bit" { var cpu = try machine(); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc013)); // RDRAMRD cpu.memory.write(u8, 0xc003, 0); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc013)); cpu.memory.write(u8, 0xc009, 0); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc016)); // RDALTZP cpu.memory.write(u8, 0xc001, 0); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc018)); // RD80STORE // The bank switches report themselves too. try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc011)); // RDBNK2 _ = cpu.memory.read(u8, 0xc08b); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc011)); } test "reading $c00x does not throw the switch that writing it would" { var cpu = try machine(); _ = cpu.memory.read(u8, 0xc003); // a read here is the keyboard, not RAMRD try testing.expect(!cpu.memory.ramrd); cpu.memory.write(u8, 0xc003, 0); try testing.expect(cpu.memory.ramrd); } test "peek does not disturb a soft switch" { var cpu = try machine(); _ = cpu.memory.peek(0xc083); _ = cpu.memory.peek(0xc083); try testing.expect(!cpu.memory.card_switches.read_ram); } test "$c019 reports the vertical blanking interval" { var cpu = try machine(); // The bar in RDVBLBAR: the bit is set while drawing, clear while blanking. try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc019)); // Run the clock into the blanking interval, which starts after line 191. cpu.clock.cycles = cycles_per_line * displayed_lines; try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc019)); // And out the other side, into the next frame. cpu.clock.cycles = cycles_per_frame; try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc019)); } test "the blanking latch is set once a frame and cleared by the paddle timer" { var cpu = try machine(); cpu.clock.cycles = cycles_per_line * displayed_lines; _ = cpu.memory.read(u8, 0x0000); // any access brings the video up to date try testing.expect(cpu.memory.vbl_interrupt); _ = cpu.memory.read(u8, 0xc070); try testing.expect(!cpu.memory.vbl_interrupt); // Still blanking, but this frame's latch has already been dealt with. _ = cpu.memory.read(u8, 0x0000); try testing.expect(!cpu.memory.vbl_interrupt); // The next frame sets it again. cpu.clock.cycles = cycles_per_frame + cycles_per_line * displayed_lines; _ = cpu.memory.read(u8, 0x0000); try testing.expect(cpu.memory.vbl_interrupt); } test "blanking only pulls the interrupt line when it is allowed to" { // A IIc, because this is a IIc feature. A IIe holds the same latch and // expects a program to poll it at $c019; there is no address on that // machine that routes it to the interrupt line, and $c05a and $c05b -- // the pair that do it here -- are annunciator 1 there. var cpu = try compact(); // As the machine comes up, IOUDis is on and those addresses are not the // IOU's at all, so this does nothing whatever. cpu.memory.write(u8, 0xc05b, 0); try testing.expect(!cpu.memory.vbl_interrupt_enabled); // Turned off, the IOU has them back and the switch works. cpu.memory.write(u8, 0xc07f, 0); cpu.memory.write(u8, 0xc05b, 0); try testing.expect(cpu.memory.vbl_interrupt_enabled); // Into the blanking interval: the latch is set and the line is pulled. cpu.clock.cycles = cycles_per_line * displayed_lines; _ = cpu.memory.read(u8, 0x0000); try testing.expect(cpu.memory.vbl_interrupt); try testing.expect(cpu.irq); // And the paddle timer lets it go again, which is the same address that // clears the latch. _ = cpu.memory.read(u8, 0xc070); try testing.expect(!cpu.irq); // Disabled, the next frame sets the latch and nothing listens to it. cpu.memory.write(u8, 0xc05a, 0); cpu.clock.cycles = cycles_per_frame + cycles_per_line * displayed_lines; _ = cpu.memory.read(u8, 0x0000); try testing.expect(cpu.memory.vbl_interrupt); try testing.expect(!cpu.irq); } test "an enabled blanking interrupt is actually taken" { var cpu = try compact(); var rom: [rom_size]u8 = @splat(0xea); rom[0x3ffe] = 0x00; // IRQ vector -> $d000, which is ROM here rom[0x3fff] = 0xd0; try cpu.memory.loadROMAtEnd(&rom); try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xea, 0xea }); cpu.program_counter.value = 0x0200; cpu.flags.clear(.I); cpu.memory.write(u8, 0xc07f, 0); // IOUDis off, so the IOU has $c05x cpu.memory.write(u8, 0xc05b, 0); // allow it // Still drawing: the instruction runs. try cpu.executeInstruction(); try testing.expectEqual(@as(u16, 0x0201), cpu.program_counter.value); // Into the blanking interval, and the next step is the handler instead. cpu.clock.cycles = cycles_per_line * displayed_lines; try cpu.executeInstruction(); // the access that notices try cpu.executeInstruction(); try testing.expectEqual(@as(u16, 0xd000), cpu.program_counter.value); try testing.expect(cpu.flags.isSet(.I)); } test "the keyboard latches a key and the strobe until it is read" { var cpu = try machine(); // Nothing pressed: no strobe. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc000) & 0x80); cpu.memory.pressKey('A'); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.read(u8, 0xc000)); // Reading the data does not clear the strobe; only $c010 does. try testing.expectEqual(@as(u8, 0xc1), cpu.memory.read(u8, 0xc000)); // $c010 reports any-key-down and clears the strobe. try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc010) & 0x80); try testing.expectEqual(@as(u8, 0x41), cpu.memory.read(u8, 0xc000)); // And the key is no longer held. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc010) & 0x80); } test "writing the clear-strobe location clears it too" { var cpu = try machine(); cpu.memory.pressKey('Z'); try testing.expect(cpu.memory.strobe); // It does not matter what is written, only that something was. cpu.memory.write(u8, 0xc010, 0x00); try testing.expect(!cpu.memory.strobe); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(u8, 0xc000)); } test "a program reads a keypress the way a real one would" { var cpu = try machine(); try cpu.memory.loadProgram(0x0300, &[_]u8{ 0xad, 0x00, 0xc0, // LDA $c000 the keyboard 0x10, 0xfb, // BPL -5 wait for the strobe 0x8d, 0x10, 0xc0, // STA $c010 clear it 0x29, 0x7f, // AND #$7f drop the strobe bit 0x8d, 0x00, 0x04, // STA $0400 onto the text page 0x00, // BRK }); cpu.program_counter.value = 0x0300; cpu.memory.pressKey('K'); var steps: usize = 0; while (steps < 20) : (steps += 1) { cpu.executeInstruction() catch |err| switch (err) { error.Break => break, else => return err, }; } try testing.expectEqual(@as(u8, 'K'), cpu.memory.peek(0x0400)); try testing.expect(!cpu.memory.strobe); } test "an oversized ROM image keeps its tail" { var cpu = try machine(); // The shape of a 32K IIe dump: two 16K banks whose $d000 upwards agree // and whose $c000-$cfff do not. Only the second is the machine's. var image: [rom_size * 2]u8 = @splat(0); image[rom_size + 0x0100] = 0x4c; // the firmware bank, at $c100 image[0x0100] = 0xa0; // the filler bank image[rom_size * 2 - 4] = 0x62; // reset vector -> $fa62 image[rom_size * 2 - 3] = 0xfa; try cpu.memory.loadROMAtEnd(&image); // $c100 belongs to slot 1, and the machine's own ROM only answers there // when INTCXROM says so; with the switch off an empty slot floats. This // test is about which half of the image was kept, so it asks the way a // program that wanted the internal ROM would have to. cpu.memory.intcxrom = true; try testing.expectEqual(@as(u8, 0x4c), cpu.memory.peek(0xc100)); cpu.memory.intcxrom = false; cpu.reset(); try testing.expectEqual(@as(u16, 0xfa62), cpu.program_counter.value); } test "the speaker flips on every access, but a write makes no sound" { var cpu = try machine(); try testing.expect(!cpu.memory.speaker); // A read moves the cone, and that is a click. _ = cpu.memory.read(u8, 0xc030); try testing.expect(cpu.memory.speaker); try testing.expectEqual(@as(u64, 1), cpu.memory.speaker_clicks); _ = cpu.memory.read(u8, 0xc030); try testing.expect(!cpu.memory.speaker); try testing.expectEqual(@as(u64, 2), cpu.memory.speaker_clicks); // A write flips it twice, too fast to hear: the cone ends where it began // and nothing was audible. cpu.memory.write(u8, 0xc030, 0); try testing.expect(!cpu.memory.speaker); try testing.expectEqual(@as(u64, 2), cpu.memory.speaker_clicks); // The whole of $c03x is the same switch. _ = cpu.memory.read(u8, 0xc03f); try testing.expectEqual(@as(u64, 3), cpu.memory.speaker_clicks); // And peeking at it does not touch the cone. _ = cpu.memory.peek(0xc030); try testing.expectEqual(@as(u64, 3), cpu.memory.speaker_clicks); } test "a program can make a tone the way the Monitor does" { var cpu = try machine(); // The bell is a loop that reads $c030 over and over. try cpu.memory.loadProgram(0x0300, &[_]u8{ 0xa2, 0x10, // LDX #$10 0xad, 0x30, 0xc0, // LDA $c030 0xca, // DEX 0xd0, 0xfa, // BNE -6 0x00, // BRK }); cpu.program_counter.value = 0x0300; var steps: usize = 0; while (steps < 200) : (steps += 1) { cpu.executeInstruction() catch |err| switch (err) { error.Break => break, else => return err, }; } try testing.expectEqual(@as(u64, 0x10), cpu.memory.speaker_clicks); } test "the cone's movements are kept with the cycle they happened on" { const CPU = @import("../cpu8.zig").CPU( @import("../clock.zig").FakeClock, AppleIIe(.{ .speaker_log = true }), ); var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); try testing.expectEqual(@as(usize, 0), cpu.memory.speaker_log.taken().len); _ = cpu.memory.read(u8, 0xc030); const first = cpu.clock.cycles; _ = cpu.memory.read(u8, 0xc030); const second = cpu.clock.cycles; // Two flips, each at the cycle the access spent. When they happened is the // whole of what a speaker carries, so it is the whole of what is kept. const flips = cpu.memory.speaker_log.taken(); try testing.expectEqual(@as(usize, 2), flips.len); try testing.expectEqual(first, flips[0]); try testing.expectEqual(second, flips[1]); try testing.expect(flips[1] > flips[0]); // A write flips it twice, too quickly to be heard, so it leaves nothing // to hear: the two cancel and neither is worth a place in the record. cpu.memory.speaker_log.clear(); cpu.memory.write(u8, 0xc030, 0); try testing.expectEqual(@as(usize, 0), cpu.memory.speaker_log.taken().len); } test "a machine nobody is listening to keeps nothing" { const CPU = @import("../cpu8.zig").CPU( @import("../clock.zig").FakeClock, AppleIIe(.{}), ); var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); _ = cpu.memory.read(u8, 0xc030); // The cone still moves, and can still be counted; it is only the record // of when that costs anything, so it is the only part switched off. try testing.expect(cpu.memory.speaker); try testing.expectEqual(@as(u64, 1), cpu.memory.speaker_clicks); try testing.expectEqual(@as(usize, 0), cpu.memory.speaker_log.taken().len); } test "a IIe keyboard has lowercase" { var cpu = try machine(); cpu.memory.pressKey('a'); try testing.expectEqual(@as(u8, 0xe1), cpu.memory.read(u8, 0xc000)); } test "reading a status switch leaves the keyboard alone" { var cpu = try machine(); cpu.memory.pressKey('K'); // $c011 upwards report the state of a switch and are read only. A IIe reads // them constantly, so clearing the strobe here, the way the coarser II Plus // decoding does, loses keys almost as fast as they arrive. for (0xc011..0xc020) |address| { _ = cpu.memory.read(u8, @intCast(address)); try testing.expect(cpu.memory.strobe); try testing.expectEqual(@as(u8, 0xcb), cpu.memory.read(u8, 0xc000)); } // $c010 is the one that clears it, and still does. _ = cpu.memory.read(u8, 0xc010); try testing.expect(!cpu.memory.strobe); } test "writing anywhere in the strobe range still clears it" { var cpu = try machine(); // The write side decodes no more finely than the range, so all sixteen do. for (0xc010..0xc020) |address| { cpu.memory.pressKey('K'); try testing.expect(cpu.memory.strobe); cpu.memory.write(u8, @intCast(address), 0); try testing.expect(!cpu.memory.strobe); } } test "asking for a key and finding none is counted" { var cpu = try machine(); try testing.expectEqual(@as(u16, 0), cpu.memory.empty_polls); for (0..10) |_| _ = cpu.memory.read(u8, 0xc000); try testing.expectEqual(@as(u16, 10), cpu.memory.empty_polls); // A key waiting is not an empty poll, and pressing one starts the count over. cpu.memory.pressKey('K'); try testing.expectEqual(@as(u16, 0), cpu.memory.empty_polls); _ = cpu.memory.read(u8, 0xc000); try testing.expectEqual(@as(u16, 0), cpu.memory.empty_polls); // Once the machine takes the key it is asking again. _ = cpu.memory.read(u8, 0xc010); _ = cpu.memory.read(u8, 0xc000); try testing.expectEqual(@as(u16, 1), cpu.memory.empty_polls); } test "the disk card answers in slot 6 only once it has a ROM" { var cpu = try machine(); // With no card, the slot page is the internal ROM, whatever INTCXROM says. try testing.expectEqual(cpu.memory.peek(0xc600), cpu.memory.rom[0x0600]); var card: [0x100]u8 = @splat(0); card[0] = 0xa2; card[1] = 0x20; card[0xff] = 0x5a; try cpu.memory.loadCardROM(&card); // INTCXROM is clear out of reset, so the card is what answers. try testing.expect(!cpu.memory.intcxrom); try testing.expectEqual(@as(u8, 0xa2), cpu.memory.read(u8, 0xc600)); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(u8, 0xc6ff)); // Switching the internal ROM in hides it again, and switching it back out // brings it back. These are written, not read: reading in this range is // the keyboard. cpu.memory.write(u8, 0xc007, 0); try testing.expectEqual(cpu.memory.rom[0x0600], cpu.memory.read(u8, 0xc600)); cpu.memory.write(u8, 0xc006, 0); try testing.expectEqual(@as(u8, 0xa2), cpu.memory.read(u8, 0xc600)); // Its neighbours are still the internal ROM either way. try testing.expectEqual(cpu.memory.rom[0x0500], cpu.memory.read(u8, 0xc500)); try testing.expectEqual(cpu.memory.rom[0x0700], cpu.memory.read(u8, 0xc700)); // A ROM that is not a page is not a Disk II ROM. try testing.expectError(error.WrongSize, cpu.memory.loadCardROM(card[0..8])); } test "the card's switches are the sixteen at $c0e0" { var cpu = try machine(); var card: [0x100]u8 = @splat(0); try cpu.memory.loadCardROM(&card); const floppy = try testing.allocator.create(disk2.Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; const image = try testing.allocator.alloc(u8, disk2.image_size); defer testing.allocator.free(image); @memset(image, 0); try floppy.load(image, .dos); cpu.memory.drives().insert(0, floppy); // The motor, and the magnets that walk the head in. try testing.expect(!cpu.memory.drives().motor); _ = cpu.memory.read(u8, 0xc0e9); try testing.expect(cpu.memory.drives().motor); for (0..8) |i| { const phase: u16 = @intCast((i + 1) % 4); _ = cpu.memory.read(u8, 0xc0e0 + phase * 2 + 1); _ = cpu.memory.read(u8, 0xc0e0 + phase * 2); } try testing.expectEqual(@as(u8, 4), cpu.memory.drives().drive(0).track()); // Reading the data register hands back the shifter, which holds a whole // byte only once the top bit has come round. Until then it is a partial // byte with that bit clear, which is precisely what the ROM's read loop // waits to stop seeing: `LDA $C08C,X` and `BPL` back to itself. // // What comes out is not all legal nibbles, and should not be. A head that // has just been put down is not in step with the disk, so the first bytes // it assembles are two neighbours smeared together — and then it meets a // gap, whose self-sync bytes are ten bits long, and the extra bits push it // back into step. So the thing to look for is not that every byte is // clean; it is that the marks a sector begins with turn up, which is what // the ROM is looking for too. _ = cpu.memory.read(u8, 0xc0ee); var recent: [3]u8 = @splat(0); var marks: usize = 0; for (0..200_000) |_| { const nibble = cpu.memory.read(u8, 0xc0ec); if (nibble & 0x80 == 0) continue; recent = .{ recent[1], recent[2], nibble }; if (std.mem.eql(u8, &recent, &[_]u8{ 0xd5, 0xaa, 0x96 })) marks += 1; // A finished byte is held for seven microseconds so that a read loop // has time to notice it, which means a loop that comes round faster // than that is handed the same byte again. The ROM never does: it has // the byte to compare before it comes back. So does this. cpu.clock.sleep(7); } try testing.expect(marks > 0); // And the write protect answer comes back the way the ROM asks for it. _ = cpu.memory.read(u8, 0xc0ed); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc0ee)); floppy.write_protected = false; _ = cpu.memory.read(u8, 0xc0ed); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc0ee)); } test "with no card fitted the slot addresses do nothing" { var cpu = try machine(); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc0ec)); _ = cpu.memory.read(u8, 0xc0e9); try testing.expect(!cpu.memory.drives().motor); } test "the screen is drawn from memory directly, not through the switches" { var cpu = try machine(); // The same address in each half, holding different characters. cpu.memory.main.ram[0x0400] = 0xc1; // A cpu.memory.aux.ram[0x0400] = 0xc2; // B try testing.expectEqual(@as(u8, 0xc1), cpu.memory.videoByte(false, 0x0400)); try testing.expectEqual(@as(u8, 0xc2), cpu.memory.videoByte(true, 0x0400)); // Pointing the processor at auxiliary memory does not move the screen: a // program can read and write the other half all it likes and what is // being displayed carries on being displayed. cpu.memory.write(u8, 0xc003, 0); // RAMRD on try testing.expectEqual(@as(u8, 0xc2), cpu.memory.read(u8, 0x0400)); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.videoByte(false, 0x0400)); cpu.memory.write(u8, 0xc001, 0); // 80STORE on try testing.expectEqual(@as(u8, 0xc1), cpu.memory.videoByte(false, 0x0400)); } test "which page is displayed depends on what PAGE2 currently means" { var cpu = try machine(); try testing.expectEqual(@as(u16, 0x0400), cpu.memory.displayPage()); // On its own, PAGE2 chooses the second page. _ = cpu.memory.read(u8, 0xc055); try testing.expectEqual(@as(u16, 0x0800), cpu.memory.displayPage()); // With 80STORE on it stops meaning that: it becomes the main or auxiliary // switch for the processor's window into the first page, and the display // stays where it is. cpu.memory.write(u8, 0xc001, 0); try testing.expectEqual(@as(u16, 0x0400), cpu.memory.displayPage()); // Which is exactly the window it now moves. cpu.memory.write(u8, 0x0400, 0xd5); try testing.expectEqual(@as(u8, 0xd5), cpu.memory.aux.ram[0x0400]); // And turning 80STORE off hands PAGE2 its old meaning back. cpu.memory.write(u8, 0xc000, 0); try testing.expectEqual(@as(u16, 0x0800), cpu.memory.displayPage()); } test "eighty columns is a switch like any other" { var cpu = try machine(); try testing.expectEqual(@as(u16, 40), cpu.memory.columns()); cpu.memory.write(u8, 0xc00d, 0); try testing.expectEqual(@as(u16, 80), cpu.memory.columns()); // And it reads back at $c01f, where the firmware asks. try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc01f) & 0x80); cpu.memory.write(u8, 0xc00c, 0); try testing.expectEqual(@as(u16, 40), cpu.memory.columns()); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc01f) & 0x80); // A reset leaves it alone. The reset line clears the switches that move // memory about, not the ones that decide what the screen looks like, // which is why open-apple reset on a real IIe comes back up still in // eighty columns rather than dropping to forty underneath the firmware. cpu.memory.write(u8, 0xc00d, 0); cpu.memory.reset(); try testing.expectEqual(@as(u16, 80), cpu.memory.columns()); } test "a machine reset stops the drive" { var cpu = try machine(); var card: [0x100]u8 = @splat(0); try cpu.memory.loadCardROM(&card); _ = cpu.memory.read(u8, 0xc0e9); try testing.expect(cpu.memory.drives().motor); // The reset line reaches the card, so a machine reset out of a boot that // is going nowhere leaves the drive stopped rather than turning for ever. cpu.memory.reset(); try testing.expect(!cpu.memory.drives().motor); } test "the text screen reads back as the characters on it" { var cpu = try machine(); // A cleared screen first, which is $a0 rather than zero: zero is an // inverse @, which is what an Apple shows before its firmware has been // round the page and why a machine coming up looks full of them. @memset(cpu.memory.main.ram[0x0400..0x0800], 0xa0); // "HI" in the top left, and a letter in the bottom right corner, written // the way a program writes them: normal video, high bit set. cpu.memory.main.ram[0x0400] = 0xc8; // H cpu.memory.main.ram[0x0401] = 0xc9; // I cpu.memory.main.ram[0x07d0 + 39] = 0xda; // Z, last column of the last row var buffer: [screen.rows * 80]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try cpu.memory.writeText(&writer); // Forty columns and twenty-four rows, run together with nothing between. const text = writer.buffered(); try testing.expectEqual(@as(usize, 24 * 40), text.len); try testing.expectEqualStrings("HI", text[0..2]); try testing.expectEqual(@as(u8, 'Z'), text[24 * 40 - 1]); // Everything the machine has not written is a space rather than a zero. try testing.expectEqual(@as(u8, ' '), text[2]); } test "eighty columns read back from both halves of memory" { var cpu = try machine(); cpu.memory.write(u8, 0xc00d, 0); // eighty columns // The auxiliary bank supplies the even columns and main the odd ones, so // the same address in the two halves is a pair of neighbours on screen. cpu.memory.aux.ram[0x0400] = 0xc1; // A, column 0 cpu.memory.main.ram[0x0400] = 0xc2; // B, column 1 cpu.memory.aux.ram[0x0401] = 0xc3; // C, column 2 cpu.memory.main.ram[0x0401] = 0xc4; // D, column 3 var buffer: [screen.rows * 80]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try cpu.memory.writeText(&writer); const text = writer.buffered(); try testing.expectEqual(@as(usize, 24 * 80), text.len); try testing.expectEqualStrings("ABCD", text[0..4]); } test "the mode says what the display is doing" { var cpu = try machine(); // Out of reset a IIe shows forty columns of text. try testing.expectEqual(screen.Mode.text, cpu.memory.mode()); try testing.expect(cpu.memory.mode().isText()); cpu.memory.write(u8, 0xc00d, 0); try testing.expectEqual(screen.Mode.text_80, cpu.memory.mode()); // Graphics, in the four shapes the switches can make. _ = cpu.memory.read(u8, 0xc050); // text off try testing.expectEqual(screen.Mode.low_resolution, cpu.memory.mode()); _ = cpu.memory.read(u8, 0xc053); // mixed on try testing.expectEqual(screen.Mode.low_resolution_mixed, cpu.memory.mode()); _ = cpu.memory.read(u8, 0xc057); // hires on try testing.expectEqual(screen.Mode.high_resolution_mixed, cpu.memory.mode()); _ = cpu.memory.read(u8, 0xc052); // mixed off try testing.expectEqual(screen.Mode.high_resolution, cpu.memory.mode()); try testing.expect(!cpu.memory.mode().isText()); // And nothing is written for a screen with no text on it. var buffer: [16]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try cpu.memory.writeText(&writer); try testing.expectEqual(@as(usize, 0), writer.buffered().len); } test "the second text page reads back when it is the one being shown" { var cpu = try machine(); cpu.memory.main.ram[0x0400] = 0xc1; // A on the first page cpu.memory.main.ram[0x0800] = 0xc2; // B on the second var first: [screen.rows * 40]u8 = undefined; var writer: std.Io.Writer = .fixed(&first); try cpu.memory.writeText(&writer); try testing.expectEqual(@as(u8, 'A'), writer.buffered()[0]); _ = cpu.memory.read(u8, 0xc055); // page two var second: [screen.rows * 40]u8 = undefined; writer = .fixed(&second); try cpu.memory.writeText(&writer); try testing.expectEqual(@as(u8, 'B'), writer.buffered()[0]); } test "the buttons read back in the top bit" { var cpu = try machine(); for (0..3) |which| { const address: u16 = @intCast(0xc061 + which); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, address) & 0x80); cpu.memory.setButton(@intCast(which), true); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, address) & 0x80); cpu.memory.setButton(@intCast(which), false); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, address) & 0x80); } // One button is not another. cpu.memory.setButton(1, true); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc061) & 0x80); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc062) & 0x80); } test "a paddle answers for as long as its position says" { var cpu = try machine(); cpu.memory.setPaddle(0, 100); cpu.memory.setPaddle(1, 0); _ = cpu.memory.read(u8, 0xc070); // start the timers const started = cpu.clock.cycles; // Both answer at first. Even a paddle at nought holds on for the handful // of cycles that go by before the Monitor's loop takes its first look, // which is what makes nought read back as nought rather than as one less. try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc064) & 0x80); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc065) & 0x80); // The one at nought is down as soon as that is past, and the one that was // set is still going. while (cpu.clock.cycles - started < paddle_cycles_before_first_look) _ = cpu.memory.read(u8, 0xc065); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc065) & 0x80); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc064) & 0x80); const runs_for = 100 * paddle_cycles_per_unit + paddle_cycles_before_first_look; while (cpu.clock.cycles - started < runs_for) _ = cpu.memory.read(u8, 0xc064); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc064) & 0x80); // And starting them again starts them again. _ = cpu.memory.read(u8, 0xc070); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc064) & 0x80); } test "the Monitor's own paddle routine reads back what was set" { // This is PREAD, the routine every program goes through to read a paddle. // It starts the timer and counts round an eleven cycle loop until the // timer runs down, so what it counts to is the paddle's position. Running // the real thing is the only way to know the timer is the right length: // the number it arrives at depends on the cycles the processor spends // going round, and those are the corpus's business rather than a // constant written here. const program = [_]u8{ 0xad, 0x70, 0xc0, // $0300 LDA $c070 start the timers 0xa0, 0x00, // $0303 LDY #$00 0xea, // $0305 NOP 0xea, // $0306 NOP 0xbd, 0x64, 0xc0, // $0307 LDA $c064,X the paddle 0x10, 0x04, // $030a BPL $0310 down already: done 0xc8, // $030c INY 0xd0, 0xf8, // $030d BNE $0307 0x88, // $030f DEY 0x02, // $0310 JAM somewhere to stop }; for ([_]u8{ 0, 1, 2, 42, 127, 200, 255 }) |position| { var cpu = try machine(); try cpu.memory.loadProgram(0x0300, &program); cpu.memory.setPaddle(0, position); cpu.registers.set(.X, 0); cpu.program_counter.value = 0x0300; var ran: usize = 0; while (ran < 4000) : (ran += 1) { cpu.executeInstruction() catch break; } try testing.expectEqual(position, cpu.registers.get(.Y)); } } /// What every Mockingboard player does: the ports set up, then for each /// register the number on port A and the orders on port B, twice over. Two /// tests run it — one for what reaches the chips, one for what reaches the /// log watching them. const mockingboard_player = [_]u8{ 0xa9, 0xff, 0x8d, 0x03, 0xc4, // LDA #$ff : STA $c403 port A outputs 0xa9, 0x04, 0x8d, 0x00, 0xc4, // LDA #$04 : STA $c400 nothing being said 0xa9, 0x07, 0x8d, 0x02, 0xc4, // LDA #$07 : STA $c402 three lines out // Point the chip at the channel A period and write it. 0xa9, 0x00, 0x8d, 0x01, 0xc4, // LDA #$00 : STA $c401 register nought 0xa9, 0x07, 0x8d, 0x00, 0xc4, // LDA #$07 : STA $c400 latch it 0xa9, 0x04, 0x8d, 0x00, 0xc4, // LDA #$04 : STA $c400 0xa9, 0xfe, 0x8d, 0x01, 0xc4, // LDA #$fe : STA $c401 the low half 0xa9, 0x06, 0x8d, 0x00, 0xc4, // LDA #$06 : STA $c400 write it 0xa9, 0x04, 0x8d, 0x00, 0xc4, // LDA #$04 : STA $c400 // And the level, on the second chip this time. 0xa9, 0x08, 0x8d, 0x81, 0xc4, // LDA #$08 : STA $c481 register eight 0xa9, 0xff, 0x8d, 0x83, 0xc4, // LDA #$ff : STA $c483 port A outputs 0xa9, 0x07, 0x8d, 0x82, 0xc4, // LDA #$07 : STA $c482 three lines out 0xa9, 0x07, 0x8d, 0x80, 0xc4, // LDA #$07 : STA $c480 latch it 0xa9, 0x04, 0x8d, 0x80, 0xc4, // LDA #$04 : STA $c480 0xa9, 0x0c, 0x8d, 0x81, 0xc4, // LDA #$0c : STA $c481 twelve 0xa9, 0x06, 0x8d, 0x80, 0xc4, // LDA #$06 : STA $c480 write it 0xa9, 0x04, 0x8d, 0x80, 0xc4, // LDA #$04 : STA $c480 0x02, // JAM }; test "a Mockingboard is written to the way a player writes to one" { var cpu = try machine(); cpu.memory.fitMockingboard(4, false); const program = mockingboard_player; try cpu.memory.loadProgram(0x0300, &program); cpu.program_counter.value = 0x0300; var ran: usize = 0; while (ran < 4000) : (ran += 1) cpu.executeInstruction() catch break; try testing.expectEqual(@as(u16, 0xfe), cpu.memory.mockingboardCard().?.halves[0].chip.period(0)); try testing.expectEqual(@as(u8, 0x0c), cpu.memory.mockingboardCard().?.halves[1].chip.registers[8]); // The other chip of each pair is untouched: they are two halves of a // stereo card and nothing crosses between them. try testing.expectEqual(@as(u16, 1), cpu.memory.mockingboardCard().?.halves[1].chip.period(0)); try testing.expectEqual(@as(u8, 0), cpu.memory.mockingboardCard().?.halves[0].chip.registers[8]); } test "a Mockingboard with speech answers at $C440 and polls A/R in bit seven" { var cpu = try machine(); cpu.memory.fitMockingboard(4, true); try testing.expect(cpu.memory.mockingboardCard().?.has_speech); // Drive the SSI 263A through the processor at $C440–$C447: out of standby, // the fastest rate, then a phoneme of the shortest duration. cpu.memory.write(u8, 0xc443, 0x00); // control cpu.memory.write(u8, 0xc442, 0xf0); // rate / inflection cpu.memory.write(u8, 0xc440, 0xc0); // duration / phoneme // While it is speaking, the poll at $C441 reads bit seven clear; run the // machine on by reading it, and once the phoneme is done bit seven sets to // ask for the next. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc441) & 0x80); var asked = false; for (0..6000) |_| { if (cpu.memory.read(u8, 0xc441) & 0x80 != 0) { asked = true; break; } } try testing.expect(asked); } test "a Phasor switches to native mode through its device selects and reaches all four chips" { var cpu = try machine(); cpu.memory.fitPhasor(4); // Select Phasor mode: an access to $C0CD (slot 4's device selects, offset // $D) latches it. Reading it is enough — the latch answers to any access. _ = cpu.memory.read(u8, 0xc0cd); try testing.expectEqual(phasor.Mode.phasor, cpu.memory.phasorCard().?.mode); // Drive the first 6522 in the slot page ($C400): port A all outputs, the // five port-B lines it uses as outputs, and both chip selects held low so a // write reaches both chips behind this 6522 at once. cpu.memory.write(u8, 0xc403, 0xff); // DDRA: port A all outputs cpu.memory.write(u8, 0xc402, 0x1f); // DDRB: reset, the two function lines, the two chip selects cpu.memory.write(u8, 0xc400, phasor.bus_inactive); // Latch register 0 (channel A fine period) with both chips selected — the // chip-select bits, active low, both left low — then write it a value. cpu.memory.write(u8, 0xc401, 0x00); // the register number on port A cpu.memory.write(u8, 0xc400, phasor.bus_latch); cpu.memory.write(u8, 0xc400, phasor.bus_inactive); cpu.memory.write(u8, 0xc401, 0x2a); // the value cpu.memory.write(u8, 0xc400, phasor.bus_write); cpu.memory.write(u8, 0xc400, phasor.bus_inactive); // Both of the first 6522's chips took it; the second 6522's did not. const card = cpu.memory.phasorCard().?; try testing.expectEqual(@as(u16, 0x2a), card.chips[0].period(0)); try testing.expectEqual(@as(u16, 0x2a), card.chips[1].period(0)); try testing.expectEqual(@as(u16, 1), card.chips[2].period(0)); try testing.expectEqual(@as(u16, 1), card.chips[3].period(0)); } test "a Sound/Speech card's SC-01 takes a phoneme strobed through its second 6522" { var cpu = try machine(); cpu.memory.fitSoundSpeech(4); // The speech 6522 is the top half of slot 4's page, at $C480: port B is the // phoneme byte, PCR drives CB2 (the strobe). Set CB2 high, put the phoneme // on port B, then drop CB2 — the falling edge loads the SC-01, the way a // driver strobes a phoneme in. cpu.memory.write(u8, 0xc48c, 0xe0); // PCR: CB2 manual-high cpu.memory.write(u8, 0xc482, 0xff); // DDRB: port B all outputs cpu.memory.write(u8, 0xc480, 0b01_101000); // inflection 1, phoneme 0x28 ("U", "move") cpu.memory.write(u8, 0xc48c, 0xc0); // PCR: CB2 manual-low — the strobe const card = cpu.memory.soundSpeechCard().?; try testing.expectEqual(@as(u6, 0x28), card.chip.phoneme); try testing.expectEqual(@as(u2, 0b01), card.chip.inflection); try testing.expectEqualStrings("U", sc01.phonemes[card.chip.phoneme].symbol); } test "what a player wrote reaches the log the machine keeps, not the card" { // The log is sixty-four kilobytes and lives on the machine beside the // speaker's and the cassette's, rather than inside the card, so that a // machine whose every slot could hold one of these does not pay for it // seven times. What that costs is a wire, and this is the test on the // wire: the card is handed the log on every access, and nothing else // here would notice if it stopped being. const Logged = @import("../cpu8.zig").CPU( @import("../clock.zig").FakeClock, AppleIIe(.{ .mockingboard_log = true }), ); var cpu: Logged = undefined; try cpu.init(null, null); cpu.memory.fitMockingboard(4, false); const program = mockingboard_player; try cpu.memory.loadProgram(0x0300, &program); cpu.program_counter.value = 0x0300; var ran: usize = 0; while (ran < 4000) : (ran += 1) cpu.executeInstruction() catch break; // Three things, in the order they happened: channel A's low period byte // to the first chip, then the second chip's reset, then its level. // // The reset is not noise and is worth asserting. Putting three lines of // port B under the card's control while the output register still holds // nought pulls the chip's reset low, because that line is low to reset — // so a player that sets its ports up in that order resets the chip it is // about to use, and the sound has to follow it. The first half of this // program happens to set the output register first and so does not. const written = cpu.memory.mockingboard_log.taken(); try testing.expectEqual(@as(usize, 3), written.len); try testing.expectEqual(@as(u1, 0), written[0].chip); try testing.expectEqual(@as(u8, 0xfe), written[0].value); try testing.expect(!written[0].reset); try testing.expectEqual(@as(u1, 1), written[1].chip); try testing.expect(written[1].reset); try testing.expectEqual(@as(u1, 1), written[2].chip); try testing.expectEqual(@as(u8, 0x0c), written[2].value); // And they happened when they happened rather than all at once, which is // the whole reason for keeping a log rather than reading the chips. try testing.expect(written[0].cycle < written[2].cycle); } test "a Mockingboard's timer interrupts the machine, which is what a tune runs on" { var cpu = try machine(); cpu.memory.fitMockingboard(4, false); cpu.flags.set(.I); // A player sets the first timer going and lets it interrupt every frame. const program = [_]u8{ 0xa9, 0x40, 0x8d, 0x0b, 0xc4, // LDA #$40 : STA $c40b keep going 0xa9, 0xc0, 0x8d, 0x0e, 0xc4, // LDA #$c0 : STA $c40e want the timer 0xa9, 0xe8, 0x8d, 0x04, 0xc4, // LDA #$e8 : STA $c404 a thousand 0xa9, 0x03, 0x8d, 0x05, 0xc4, // LDA #$03 : STA $c405 cycles of it 0x02, // JAM }; try cpu.memory.loadProgram(0x0300, &program); cpu.program_counter.value = 0x0300; var ran: usize = 0; while (ran < 100) : (ran += 1) cpu.executeInstruction() catch break; try testing.expect(!cpu.irq); // Running a thousand cycles is what it takes, and then the card is asking. const started = cpu.clock.cycles; while (cpu.clock.cycles < started + 1100) _ = cpu.memory.read(u8, 0xea); try testing.expect(cpu.irq); // A handler answers it by reading the timer, and it comes round again. _ = cpu.memory.read(u8, 0xc404); try testing.expect(!cpu.irq); const answered = cpu.clock.cycles; while (cpu.clock.cycles < answered + 1100) _ = cpu.memory.read(u8, 0xea); try testing.expect(cpu.irq); } test "a Passport MIDI card answers in slot two: it sends, receives, and interrupts" { var cpu = try machine(); cpu.memory.fitPassport(2); cpu.flags.set(.I); // The 6850 is at $C0A8 (control and status) and $C0A9 (data). Set it for // MIDI and clock out a note-on and its note number. cpu.memory.write(u8, 0xc0a8, 0x15); // divide by sixteen, eight bits cpu.memory.write(u8, 0xc0a9, 0x90); // a MIDI note-on status byte cpu.memory.write(u8, 0xc0a9, 0x3c); // middle C try testing.expectEqualSlices(u8, &.{ 0x90, 0x3c }, cpu.memory.midiSent()); // A byte handed in from a synthesizer is read back at the data register, // once the status register says one has arrived. try testing.expect(cpu.memory.midiReceive(0x7f)); try testing.expect(cpu.memory.read(u8, 0xc0a8) & 0x01 != 0); // receive full try testing.expectEqual(@as(u8, 0x7f), cpu.memory.read(u8, 0xc0a9)); try testing.expect(cpu.memory.read(u8, 0xc0a8) & 0x01 == 0); // and empty again // The 6840 at $C0A0-$C0A3 drives the interrupt line, which is what a // sequencer's clock runs on. CR2's low bit routes $C0A0 to CR1. cpu.memory.write(u8, 0xc0a1, 0x01); // CR2: the address bit cpu.memory.write(u8, 0xc0a0, 0x42); // CR1: internal clock, IRQ enabled, continuous cpu.memory.write(u8, 0xc0a2, 0x03); // Timer 1 high byte cpu.memory.write(u8, 0xc0a3, 0xe8); // and low: $03E8 is a thousand try testing.expect(!cpu.irq); // A thousand cycles on, it is asking. const started = cpu.clock.cycles; while (cpu.clock.cycles < started + 1100) _ = cpu.memory.read(u8, 0xea); try testing.expect(cpu.irq); // A handler answers it by reading the status and then the timer, and the // continuous timer comes round to ask again. _ = cpu.memory.read(u8, 0xc0a1); // status _ = cpu.memory.read(u8, 0xc0a2); // timer 1 counter try testing.expect(!cpu.irq); const answered = cpu.clock.cycles; while (cpu.clock.cycles < answered + 1100) _ = cpu.memory.read(u8, 0xea); try testing.expect(cpu.irq); } test "a machine with no Mockingboard has nothing in slot four" { var cpu = try machine(); // Without one, there is no card to write to and the page is the machine's // own ROM, so a write there does nothing at all. try testing.expectEqual(@as(?*mockingboard.Card, null), cpu.memory.mockingboardCard()); cpu.memory.write(u8, 0xc400, 0x07); try testing.expectEqual(@as(?*mockingboard.Card, null), cpu.memory.mockingboardCard()); } test "a slot holds one card, and the second one asked for is refused" { // This used to be decided by the order of a chain of `else if`s: a // Mockingboard beat a mouse because its branch came first, whichever of // them had been fitted and in whichever order. Nobody was told. // // Now the slot is occupied and says so. What is in it is what was put // there first, which is at least an answer somebody chose. var cpu = try machine(); cpu.memory.fitMouse(4); cpu.memory.fitMockingboard(4, false); try testing.expect(cpu.memory.mouseCard() != null); try testing.expectEqual(@as(?*mockingboard.Card, null), cpu.memory.mockingboardCard()); // And the mouse's firmware is what answers in the page, since the mouse is // what is in the slot. try testing.expectEqual(mouse.identifiers[0].byte, cpu.memory.peek(0xc405)); // The card that was refused goes somewhere else perfectly happily, which // is the whole point of the exercise. try cpu.memory.slots.fit(2, .{ .mockingboard = .{ .fitted = true } }); try testing.expect(cpu.memory.mockingboardCard() != null); } test "the mouse card's own firmware is called the way a program calls it" { var cpu = try machine(); cpu.memory.fitMouse(4); // A program finds the routines through the table in the card's page: each // byte in it is the low half of an address, and the page is the high half. const set = cpu.memory.peek(0xc400 + @as(u16, mouse.Entry.set.address())); const read = cpu.memory.peek(0xc400 + @as(u16, mouse.Entry.read.address())); const start = cpu.memory.peek(0xc400 + @as(u16, mouse.Entry.init.address())); // Starting the card up and switching the mouse on, keeping the carry each // call comes back with, which is how the firmware says it worked. const first = [_]u8{ 0xa2, 0xc4, // LDX #$c4 the slot, the way the card wants 0xa0, 0x40, // LDY #$40 it told 0x20, start, 0xc4, // JSR init 0xa9, mouse.mode_on, // LDA #$01 0x20, set, 0xc4, // JSR set 0xa9, 0x00, 0x2a, // LDA #$00 : ROL A the carry, as a number 0x8d, 0x00, 0x09, // STA $0900 0x02, // JAM }; try cpu.memory.loadProgram(0x0300, &first); cpu.program_counter.value = 0x0300; var ran: usize = 0; while (ran < 2000) : (ran += 1) cpu.executeInstruction() catch break; try testing.expectEqual(@as(u8, 0), cpu.memory.peek(0x0900)); try testing.expectEqual(mouse.mode_on, cpu.memory.mouseCard().?.mode); // The mode goes in the screen hole as well, where a program can see it. try testing.expectEqual(mouse.mode_on, cpu.memory.peek(mouse.hole.mode + 4)); // The mouse moves and a button goes down, which is the host's doing. cpu.memory.mouseCard().?.moveTo(300, 200); cpu.memory.mouseCard().?.setButton(0, true); const second = [_]u8{ 0xa2, 0xc4, // LDX #$c4 0xa0, 0x40, // LDY #$40 0x20, read, 0xc4, // JSR read 0xa9, 0x00, 0x2a, // LDA #$00 : ROL A 0x8d, 0x01, 0x09, // STA $0901 0x02, // JAM }; try cpu.memory.loadProgram(0x0300, &second); cpu.program_counter.value = 0x0300; ran = 0; while (ran < 2000) : (ran += 1) cpu.executeInstruction() catch break; try testing.expectEqual(@as(u8, 0), cpu.memory.peek(0x0901)); // Where the card leaves it: the position in four holes, low half and high // half apart, and the buttons in a fifth. try testing.expectEqual(@as(u8, 300 & 0xff), cpu.memory.peek(mouse.hole.x_low + 4)); try testing.expectEqual(@as(u8, 300 >> 8), cpu.memory.peek(mouse.hole.x_high + 4)); try testing.expectEqual(@as(u8, 200 & 0xff), cpu.memory.peek(mouse.hole.y_low + 4)); try testing.expectEqual(@as(u8, 200 >> 8), cpu.memory.peek(mouse.hole.y_high + 4)); const status = cpu.memory.peek(mouse.hole.status + 4); try testing.expect(status & mouse.status_button0_now != 0); try testing.expect(status & mouse.status_moved != 0); // And a mode the card does not know comes back with the carry set. const third = [_]u8{ 0xa2, 0xc4, // LDX #$c4 0xa0, 0x40, // LDY #$40 0xa9, 0xf0, // LDA #$f0 0x20, set, 0xc4, // JSR set 0xa9, 0x00, 0x2a, // LDA #$00 : ROL A 0x8d, 0x02, 0x09, // STA $0902 0x02, // JAM }; try cpu.memory.loadProgram(0x0300, &third); cpu.program_counter.value = 0x0300; ran = 0; while (ran < 2000) : (ran += 1) cpu.executeInstruction() catch break; try testing.expectEqual(@as(u8, 1), cpu.memory.peek(0x0902)); try testing.expectEqual(mouse.mode_on, cpu.memory.mouseCard().?.mode); } test "the mouse pulls the interrupt line, and lets go when asked" { var cpu = try machine(); cpu.memory.fitMouse(4); cpu.memory.mouseCard().?.setMode(mouse.mode_on | mouse.mode_move_interrupt); try testing.expect(!cpu.irq); cpu.memory.mouseCard().?.moveTo(10, 10); // The line is worked out on the next access, which is any access at all. _ = cpu.memory.read(u8, 0xc0c0); try testing.expect(cpu.irq); // Owning up through the firmware is what takes it off the line again. // The card asks to be called with interrupts disabled, and a handler // would be: without that the processor answers the interrupt before the // first instruction of this and never arrives. cpu.flags.set(.I); const serve = cpu.memory.peek(0xc400 + @as(u16, mouse.Entry.serve.address())); const program = [_]u8{ 0x20, serve, 0xc4, // JSR serve 0xa9, 0x00, 0x2a, // LDA #$00 : ROL A nought if it was this card 0x8d, 0x00, 0x09, // STA $0900 0x02, // JAM }; try cpu.memory.loadProgram(0x0300, &program); cpu.program_counter.value = 0x0300; var ran: usize = 0; while (ran < 2000) : (ran += 1) cpu.executeInstruction() catch break; try testing.expectEqual(@as(u8, 0), cpu.memory.peek(0x0900)); try testing.expect(!cpu.irq); } test "a machine with no mouse card has nothing in slot four" { var cpu = try machine(); try testing.expect(cpu.memory.peek(0xc405) != mouse.identifiers[0].byte); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc0c0)); cpu.memory.fitMouse(4); for (mouse.identifiers) |identifier| { try testing.expectEqual(identifier.byte, cpu.memory.peek(0xc400 + @as(u16, identifier.at))); } } test "the clock card's own firmware leaves the time where ProDOS reads it" { // What ProDOS does once it has found the signature: call the card at // $Cn08 and read the line buffer. Running the firmware is the only way to // know the card and the code in its ROM agree with one another. const program = [_]u8{ 0x20, 0x08, 0xc5, // $0300 JSR $c508 the card's read entry point 0x02, // $0303 JAM somewhere to stop }; var cpu = try machine(); cpu.memory.fitClock(5, .{ .year = 2026, .month = 9, .day = 1, .hour = 14, .minute = 30, .second = 5, }, cpu.clock.cycles); try cpu.memory.loadProgram(0x0300, &program); cpu.program_counter.value = 0x0300; var ran: usize = 0; while (ran < 2000) : (ran += 1) cpu.executeInstruction() catch break; // The month, the day of the week, the date, the hour, the minute and the // second, in the buffer the machine reads a typed line into. The first of // September 2026 was a Tuesday, which is the 02. var read: [clockcard.string_length]u8 = undefined; for (&read, 0..) |*into, i| into.* = cpu.memory.peek(@intCast(0x0200 + i)) & 0x7f; try testing.expectEqualStrings("09,02,01,14,30,05", &read); } test "a machine with no clock card has nothing in slot five" { var cpu = try machine(); // The ROM the machine answers with there is its own, not the card's. try testing.expect(cpu.memory.peek(0xc500) != clockcard.signature[0]); // And the registers do nothing. try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc0d0)); cpu.memory.fitClock(5, .fromEpoch(0), 0); try testing.expectEqual(clockcard.signature[0], cpu.memory.peek(0xc500)); try testing.expectEqual(clockcard.signature[1], cpu.memory.peek(0xc502)); try testing.expectEqual(clockcard.signature[2], cpu.memory.peek(0xc504)); try testing.expectEqual(clockcard.signature[3], cpu.memory.peek(0xc506)); // With the machine's own firmware switched in, the card is hidden, which // is what INTCXROM is for. It is written, not read: reading in this range // is the keyboard. cpu.memory.write(u8, 0xc007, 0); try testing.expect(cpu.memory.peek(0xc500) != clockcard.signature[0]); } /// A card's firmware, made up rather than Applied Engineering's, with a /// different byte at each of the four places the card's decode can reach: the /// slot page and the expansion window, in each of the two banks. fn memoryCardFirmware() [ramfactor.rom_size]u8 { var rom: [ramfactor.rom_size]u8 = @splat(0); rom[0x0500] = 0x11; // $c500, bank nought rom[0x1500] = 0x22; // $c500, bank one rom[0x0800] = 0x33; // $c800, bank nought rom[0x1800] = 0x44; // $c800, bank one return rom; } test "a memory expansion card shows one of its two banks at a time" { var cpu = try machine(); const rom = memoryCardFirmware(); const ram = try testing.allocator.alloc(u8, ramfactor.block_size); defer testing.allocator.free(ram); @memset(ram, 0); try cpu.memory.fitMemoryCard(&rom, ram); // Reading the slot's page is also what gives the card the $c800 window, // as it is for any card. try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0xc500)); try testing.expectEqual(@as(u8, 0x33), cpu.memory.read(u8, 0xc800)); // The bank register is the last of the slot's sixteen addresses, and bit // 0 of what is written to it is the bank. The card's own firmware selects // the second bank by storing $ff and comes back with an ASL, whose // result always has bit 0 clear. cpu.memory.write(u8, 0xc0df, 0xff); try testing.expectEqual(@as(u8, 0x44), cpu.memory.read(u8, 0xc800)); // The slot page moves with it, though the real card's image has the same // seven slot pages in both banks so that this cannot be noticed. try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(u8, 0xc500)); cpu.memory.write(u8, 0xc0df, 0xfe); try testing.expectEqual(@as(u8, 0x33), cpu.memory.read(u8, 0xc800)); // And another card's page takes the window away, as it does from any card. _ = cpu.memory.read(u8, 0xc200); try testing.expect(cpu.memory.read(u8, 0xc800) != 0x33); } test "the memory card's registers are asleep until its firmware page is touched" { var cpu = try machine(); const rom = memoryCardFirmware(); const ram = try testing.allocator.alloc(u8, ramfactor.block_size); defer testing.allocator.free(ram); @memset(ram, 0); try cpu.memory.fitMemoryCard(&rom, ram); // "After power up or Control-Reset, the registers on the card are all in // a disabled state. They will be enabled by addressing any address in the // firmware page" (Applied Engineering, n.d.-a, Chapter 6). So a write here // reaches nothing. cpu.memory.write(u8, 0xc0d3, 0x5a); try testing.expectEqual(@as(u8, 0), ram[0]); _ = cpu.memory.read(u8, 0xc500); cpu.memory.write(u8, 0xc0d3, 0x5a); try testing.expectEqual(@as(u8, 0x5a), ram[0]); // And the reset line puts them back to sleep. cpu.memory.reset(); cpu.memory.write(u8, 0xc0d3, 0x11); try testing.expectEqual(@as(u8, 0x5a), ram[0]); } test "a quarter of a megabyte goes in and out through one address" { var cpu = try machine(); const rom = memoryCardFirmware(); const ram = try testing.allocator.alloc(u8, ramfactor.block_size); defer testing.allocator.free(ram); @memset(ram, 0); try cpu.memory.fitMemoryCard(&rom, ram); _ = cpu.memory.read(u8, 0xc500); // The address goes in lowest byte first, which is what the card's manual // insists on and what the ripple carry between the three counters makes // necessary. cpu.memory.write(u8, 0xc0d0, 0xfe); cpu.memory.write(u8, 0xc0d1, 0xff); cpu.memory.write(u8, 0xc0d2, 0x02); // Two bytes at the top of the third 64K, and then the counter runs on // into the fourth. cpu.memory.write(u8, 0xc0d3, 0xaa); cpu.memory.write(u8, 0xc0d3, 0xbb); cpu.memory.write(u8, 0xc0d3, 0xcc); try testing.expectEqual(@as(u8, 0xaa), ram[0x02fffe]); try testing.expectEqual(@as(u8, 0xbb), ram[0x02ffff]); try testing.expectEqual(@as(u8, 0xcc), ram[0x030000]); cpu.memory.write(u8, 0xc0d0, 0xfe); cpu.memory.write(u8, 0xc0d1, 0xff); cpu.memory.write(u8, 0xc0d2, 0x02); try testing.expectEqual(@as(u8, 0xaa), cpu.memory.read(u8, 0xc0d3)); try testing.expectEqual(@as(u8, 0xbb), cpu.memory.read(u8, 0xc0d3)); try testing.expectEqual(@as(u8, 0xcc), cpu.memory.read(u8, 0xc0d3)); // And the high address byte reads back with its top nybble set, which is // how the firmware knows it is looking at a card of a megabyte or less. try testing.expectEqual(@as(u8, 0xf3), cpu.memory.read(u8, 0xc0d2)); } test "slot five holds the clock or the memory card and not both" { var cpu = try machine(); cpu.memory.fitClock(5, .fromEpoch(0), 0); try testing.expectEqual(clockcard.signature[0], cpu.memory.peek(0xc500)); const rom = memoryCardFirmware(); const ram = try testing.allocator.alloc(u8, ramfactor.block_size); defer testing.allocator.free(ram); @memset(ram, 0); try cpu.memory.fitMemoryCard(&rom, ram); try testing.expect(cpu.memory.clockCard() == null); try testing.expectEqual(@as(u8, 0x11), cpu.memory.peek(0xc500)); // A card's ROM is eight kilobytes and its memory some whole number of the // four blocks of chips it has sockets for; anything else is not a card. try testing.expectError(error.WrongSize, cpu.memory.fitMemoryCard(rom[0..16], ram)); try testing.expectError(error.WrongSize, cpu.memory.fitMemoryCard(&rom, ram[0..16])); } test "the cassette output flips on every touch, and its timing is kept" { const CPU = @import("../cpu8.zig").CPU( @import("../clock.zig").FakeClock, AppleIIe(.{ .cassette_log = true }), ); var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); try testing.expect(!cpu.memory.cassette_out); _ = cpu.memory.read(u8, 0xc020); try testing.expect(cpu.memory.cassette_out); const first = cpu.clock.cycles; cpu.memory.write(u8, 0xc020, 0); try testing.expect(!cpu.memory.cassette_out); // Written or read, it flips, and each flip is kept with the cycle it // happened on: that timing is the whole of what goes onto a tape. const flips = cpu.memory.cassette_log.taken(); try testing.expectEqual(@as(usize, 2), flips.len); try testing.expectEqual(first, flips[0]); try testing.expect(flips[1] > flips[0]); } test "the cassette input reads which side of zero the signal is on" { var cpu = try machine(); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc060) & 0x80); cpu.memory.setCassetteInput(true); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc060) & 0x80); cpu.memory.setCassetteInput(false); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc060) & 0x80); } test "a tape plays in at the machine's own pace" { var cpu = try machine(); // Half a second a sample, so the sides are far enough apart to watch the // machine's clock walk across them. const levels = [_]u8{ 1, 0, 1 }; cpu.memory.playTape(&levels, 2); const started = cpu.clock.cycles; try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc060) & 0x80); while (cpu.clock.cycles - started < cycles_per_second / 2) _ = cpu.memory.read(u8, 0xc060); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc060) & 0x80); while (cpu.clock.cycles - started < cycles_per_second) _ = cpu.memory.read(u8, 0xc060); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc060) & 0x80); // Taking the tape off leaves whatever was set by hand. cpu.memory.stopTape(); cpu.memory.setCassetteInput(false); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc060) & 0x80); } test "slot 3 is the machine's own firmware until SLOTC3ROM says otherwise" { var cpu = try machine(); var firmware: [videx.firmware_size]u8 = @splat(0); var charset: [videx.charset_size]u8 = @splat(0); firmware[videx.slot_page_at] = 0x2c; firmware[0x000] = 0xad; // the first byte of the expansion ROM try cpu.memory.loadVidexROM(&firmware, &charset, null); // A IIe comes up with SLOTC3ROM off, because it has the extended // eighty-column card in the auxiliary slot and always does. So the card in // slot 3 is fitted and is not what answers there. try testing.expect(cpu.memory.videxCard() != null); try testing.expect(!cpu.memory.slotc3rom); try testing.expect(!cpu.memory.slotThreeIsCard()); try testing.expectEqual(cpu.memory.rom[0x300], cpu.memory.read(u8, 0xc300)); // $c00b is the switch, and then it is. Written rather than read: on a IIe // the sixteen at $c000 are write-only, and reading one is reading the // keyboard. cpu.memory.write(u8, 0xc00b, 0); try testing.expect(cpu.memory.slotThreeIsCard()); try testing.expectEqual(@as(u8, 0x2c), cpu.memory.read(u8, 0xc300)); try testing.expectEqual(@as(?u3, 3), cpu.memory.slots.expansion); // The window is still the machine's, though, and the card cannot have it // back for the asking. Reading $c300 while SLOTC3ROM was reset — which // this test did four lines up — set INTC8ROM, and that switch locks every // card out of $c800-$cfff until something touches $cfff: "I/O STROBE' // thus drops low during access to $C800-$CFFF when INTCXROM and INTC8ROM // are reset" (Sather, 1985, p. 7-2), and I/O STROBE' is the line a card // answers on. Turning SLOTC3ROM on does not clear it. try testing.expect(cpu.memory.intc8rom); try testing.expectEqual(cpu.memory.rom[0x800], cpu.memory.read(u8, 0xc800)); // $cfff is what clears it, which is why the machine's own eighty-column // firmware touches that address before it hands the window over. _ = cpu.memory.read(u8, 0xcfff); try testing.expect(!cpu.memory.intc8rom); _ = cpu.memory.read(u8, 0xc300); // and the card takes the window again try testing.expectEqual(@as(u8, 0xad), cpu.memory.read(u8, 0xc800)); // And the card's screen memory is under the window, which is the whole // point of putting one in a IIe. cpu.memory.write(u8, 0xcc00, 'V'); try testing.expectEqual(@as(u8, 'V'), cpu.memory.videxCard().?.ram[0]); // INTCXROM overrides it: "setting SLOTCXROM low enables built-in ROM in // all of the I/O memory space ... including the $C300 space". cpu.memory.write(u8, 0xc007, 0); try testing.expect(cpu.memory.slotc3rom); try testing.expect(!cpu.memory.slotThreeIsCard()); try testing.expectEqual(cpu.memory.rom[0x300], cpu.memory.read(u8, 0xc300)); cpu.memory.write(u8, 0xc006, 0); try testing.expectEqual(@as(u8, 0x2c), cpu.memory.read(u8, 0xc300)); // The sixteen device select addresses are the card's whatever the ROM // switches say: "the bus and I/O signals are always available to a // peripheral card in slot 3, even when the 80-column hardware and firmware // are operating". cpu.memory.write(u8, 0xc00a, 0); // the card's page switched away again try testing.expect(!cpu.memory.slotThreeIsCard()); cpu.memory.write(u8, 0xc0b0, 1); cpu.memory.write(u8, 0xc0b1, 80); try testing.expectEqual(@as(u8, 80), cpu.memory.videxCard().?.crtc.register[1]); // Both switches read back where the manual says they do. try testing.expect(cpu.memory.read(u8, 0xc017) < 0x80); // SLOTC3ROM, now off cpu.memory.write(u8, 0xc00b, 0); try testing.expect(cpu.memory.read(u8, 0xc017) >= 0x80); } test "the serial card answers in its slot and shares the $c800 window" { var cpu = try machine(); var firmware: [0x800]u8 = @splat(0); firmware[0x700] = 0x2c; // the first byte of the card's page firmware[0x7ff] = 0x5a; // the last firmware[0x000] = 0xc8; // the first byte of the expansion ROM firmware[0x7fe] = 0xee; try cpu.memory.loadSerialROM(&firmware); // The last page of the two kilobytes is what answers in the slot. try testing.expectEqual(@as(u8, 0x2c), cpu.memory.read(u8, 0xc200)); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(u8, 0xc2ff)); // Touching that page hands the card the $c800 window, which is one window // shared between every slot. try testing.expectEqual(@as(?u3, 2), cpu.memory.slots.expansion); try testing.expectEqual(@as(u8, 0xc8), cpu.memory.read(u8, 0xc800)); // Another slot's page takes it away again, and $cfff gives it up. Slot 3 // is the one to do it with here, and it takes the window away without // giving it to anybody: with no card answering in that page, an access // there is an access to the machine's own ROM, and what comes in at $c800 // is the machine's own as well. _ = cpu.memory.read(u8, 0xc300); try testing.expectEqual(@as(?u3, null), cpu.memory.slots.expansion); try testing.expect(cpu.memory.read(u8, 0xc800) != 0xc8); _ = cpu.memory.read(u8, 0xc200); _ = cpu.memory.read(u8, 0xcfff); try testing.expectEqual(@as(?u3, null), cpu.memory.slots.expansion); // Looking from outside does not move it: a peek is not an access. _ = cpu.memory.read(u8, 0xc200); _ = cpu.memory.peek(0xc300); try testing.expectEqual(@as(?u3, 2), cpu.memory.slots.expansion); _ = cpu.memory.read(u8, 0xc400); try testing.expectEqual(@as(?u3, 4), cpu.memory.slots.expansion); // And a ROM that is not two kilobytes is not this card's. try testing.expectError(error.WrongSize, cpu.memory.loadSerialROM(firmware[0..16])); } test "the card's four registers are where the slot puts them" { var cpu = try machine(); var firmware: [0x800]u8 = @splat(0); try cpu.memory.loadSerialROM(&firmware); // Nine thousand six hundred, eight bits, no parity. cpu.memory.write(u8, 0xc0ab, 0b0001_1110); try testing.expectEqual(@as(u8, 0b0001_1110), cpu.memory.read(u8, 0xc0ab)); try testing.expectEqual(@as(u32, 9600), cpu.memory.serialAcia().?.baud()); // A byte written goes out, and the chip says it is busy until it has had // time to go. try testing.expect(cpu.memory.read(u8, 0xc0a9) & 0x10 != 0); cpu.memory.write(u8, 0xc0a8, 'H'); try testing.expect(cpu.memory.read(u8, 0xc0a9) & 0x10 == 0); try testing.expectEqualSlices(u8, "H", cpu.memory.serialSent()); cpu.memory.serialConsume(1); // A byte from outside is announced and then read. try testing.expect(cpu.memory.read(u8, 0xc0a9) & 0x08 == 0); try testing.expect(cpu.memory.serialReceive('k')); try testing.expect(cpu.memory.read(u8, 0xc0a9) & 0x08 != 0); try testing.expectEqual(@as(u8, 'k'), cpu.memory.read(u8, 0xc0a8)); try testing.expect(cpu.memory.read(u8, 0xc0a9) & 0x08 == 0); } test "the card's interrupt jumper is out, and says so" { var cpu = try machine(); var firmware: [0x800]u8 = @splat(0); try cpu.memory.loadSerialROM(&firmware); // The chip comes up with its receiver interrupt enabled, so a byte // arriving would pull the line if the jumper were in. It is not, and the // machine is left alone: no firmware puts a handler anywhere, so a card // wired in by default takes the machine to pieces on the first byte. try testing.expect(cpu.memory.serialReceive('!')); try testing.expect(!cpu.irq); // The chip still knows it wants attention, which is the chip rather than // the wiring, and says so in the status register's top bit. try testing.expect(cpu.memory.read(u8, 0xc0a9) & 0x80 != 0); // Put the jumper in and the line is pulled. cpu.memory.setSerialInterrupts(true); try testing.expect(cpu.irq); _ = cpu.memory.read(u8, 0xc0a8); try testing.expect(!cpu.irq); } test "with no card fitted the slot answers from the machine's own ROM" { var cpu = try machine(); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc0a8)); try testing.expectEqual(cpu.memory.rom[0x0200], cpu.memory.read(u8, 0xc200)); } test "the block device answers ProDOS through its own firmware" { var cpu = try machine(); // Four blocks, each filled with its own number so a misread is obvious. 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 }; cpu.memory.insertVolume(0, &volume); // The card's page is its firmware, and the last two bytes are what ProDOS // reads to find the driver. try testing.expectEqual(@as(u8, 0x20), cpu.memory.read(u8, 0xc701)); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc707)); try testing.expectEqual(@as(u8, 0x17), cpu.memory.read(u8, 0xc7fe)); const entry = cpu.memory.read(u8, 0xc7ff); try testing.expectEqual(@as(u8, 0x0b), entry); // Call it the way ProDOS does: the command in $42, the unit in $43, the // buffer in $44 and the block in $46, then JSR the entry point. const call = [_]u8{ 0x20, entry, 0xc7, 0x02 }; // JSR $c70b : JAM try cpu.memory.loadProgram(0x0300, &call); const run = struct { fn once(machine_cpu: anytype) void { machine_cpu.program_counter.value = 0x0300; for (0..100) |_| machine_cpu.executeInstruction() catch break; } }; // Read block 2 into $1000. cpu.memory.write(u8, 0x42, 1); // read cpu.memory.write(u8, 0x43, 0x70); // slot 7, drive 1 cpu.memory.write(u8, 0x44, 0x00); cpu.memory.write(u8, 0x45, 0x10); cpu.memory.write(u8, 0x46, 2); cpu.memory.write(u8, 0x47, 0); run.once(&cpu); try testing.expect(!cpu.flags.isSet(.C)); // carry clear: it worked try testing.expectEqual(@as(u8, 3), cpu.memory.read(u8, 0x1000)); try testing.expectEqual(@as(u8, 3), cpu.memory.read(u8, 0x11ff)); // And nothing beyond the block it was asked for. try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0x1200)); // Write it back somewhere else and read it again to see it landed. cpu.memory.write(u8, 0x1000, 0xaa); cpu.memory.write(u8, 0x42, 2); // write cpu.memory.write(u8, 0x46, 0); // block 0 run.once(&cpu); try testing.expect(!cpu.flags.isSet(.C)); try testing.expectEqual(@as(u8, 0xaa), image[0]); try testing.expect(volume.dirty); // A status call says how big it is, in X and Y. cpu.memory.write(u8, 0x42, 0); run.once(&cpu); try testing.expect(!cpu.flags.isSet(.C)); try testing.expectEqual(@as(u8, 4), cpu.registers.get(.X)); try testing.expectEqual(@as(u8, 0), cpu.registers.get(.Y)); // A block that is not there fails, with the carry set and an error in A. cpu.memory.write(u8, 0x42, 1); cpu.memory.write(u8, 0x46, 99); run.once(&cpu); try testing.expect(cpu.flags.isSet(.C)); try testing.expectEqual(@intFromEnum(blockdevice.Failure.io), cpu.registers.get(.A)); // A write protected volume refuses, and says why. volume.write_protected = true; cpu.memory.write(u8, 0x42, 2); cpu.memory.write(u8, 0x46, 1); run.once(&cpu); try testing.expect(cpu.flags.isSet(.C)); try testing.expectEqual(@intFromEnum(blockdevice.Failure.protected), cpu.registers.get(.A)); } test "booting the block device reads its first block and jumps into it" { var cpu = try machine(); var image: [blockdevice.block_size * 2]u8 = @splat(0); // A boot block that does nothing but stop, so the machine can be caught // in the act of having jumped into it. The code starts at the block's // second byte, since that is where a boot block is entered: $0801. image[0] = 0x01; // whatever a real one keeps here image[1] = 0xa9; // LDA #$5a at $0801 image[2] = 0x5a; image[3] = 0x02; // JAM var volume: blockdevice.Volume = .{ .image = &image }; cpu.memory.insertVolume(0, &volume); // Enter the card the way the machine does when it starts from it. cpu.program_counter.value = 0xc700; for (0..200) |_| cpu.executeInstruction() catch break; // The block is in memory, the slot is in X as a boot block expects, and // the processor went to $0801 and ran what was there. try testing.expectEqual(@as(u8, 0x01), cpu.memory.read(u8, 0x0800)); try testing.expectEqual(@as(u8, 0xa9), cpu.memory.read(u8, 0x0801)); try testing.expectEqual(@as(u8, 0x70), cpu.registers.get(.X)); try testing.expectEqual(@as(u8, 0x5a), cpu.registers.get(.A)); } /// A IIc to test with, since almost every test above is about the other one. fn compact() !@import("../cpu8.zig").CMOS(@import("../clock.zig").FakeClock, AppleIIc(.{})) { var cpu: @import("../cpu8.zig").CMOS(@import("../clock.zig").FakeClock, AppleIIc(.{})) = undefined; try cpu.init(null, null); return cpu; } test "a IIc has no slots to put a card in" { var cpu = try compact(); // Whatever is in the machine's own ROM is what answers everywhere from // $c100 to $cfff, and no switch changes that: there is nothing to switch // to. The firmware for the serial ports, the mouse, the eighty column // code and the disk all live in there. var rom: [rom_size]u8 = @splat(0); for (&rom, 0..) |*byte, i| byte.* = @truncate(i); try cpu.memory.loadROMAtEnd(&rom); inline for (.{ 0xc100, 0xc300, 0xc400, 0xc600, 0xc800, 0xcfff }) |address| { try testing.expectEqual(rom[address - 0xc000], cpu.memory.peek(address)); } // INTCXROM decides nothing here, since both answers are the same ROM. cpu.memory.write(u8, 0xc007, 0); try testing.expectEqual(rom[0x0600], cpu.memory.peek(0xc600)); cpu.memory.write(u8, 0xc006, 0); try testing.expectEqual(rom[0x0600], cpu.memory.peek(0xc600)); } test "a IIc has a keyboard switch where the cassette was" { var cpu = try compact(); // The socket is not on the case, and the address is the switch that says // which width to come up in: down for eighty columns. cpu.memory.eighty_column_switch = true; try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc060)); cpu.memory.eighty_column_switch = false; try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, 0xc060)); // And touching the cassette output does nothing, where a IIe would flip // the line and write it down. const before = cpu.memory.cassette_out; _ = cpu.memory.read(u8, 0xc020); try testing.expectEqual(before, cpu.memory.cassette_out); } test "a IIc latches the blanking interval the other way round" { var cpu = try compact(); // The IIe says whether the video is blanking now, with the bit clear // while it is. The IIc puts the bit up when the interval starts and // leaves it up until this is read. while (!cpu.memory.blanking()) _ = cpu.memory.read(u8, 0xea); try testing.expect(cpu.memory.read(u8, 0xc019) & 0x80 != 0); // Reading it is what clears it. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xc019) & 0x80); } test "a IIe's four annunciators are set by the odd address and cleared by the even" { var cpu = try machine(); // "Any reference to the first location of a pair turns the corresponding // annunciator off; a reference to the second location turns the // annunciator on" (Apple Computer, Inc., 1985b, Table 2-11, p. 40). // // All four come up clear, except the third, which is the one that is not // only an annunciator: clearing it is how double resolution is asked for, // so a machine with the mode off has that pin set. See `annunciator`. for (0..3) |which| try testing.expect(!cpu.memory.annunciator(@intCast(which))); try testing.expect(cpu.memory.annunciator(3)); // Odd sets, even clears, for every one of the four. for (0..4) |which| { const base: u16 = 0xc058 + @as(u16, @intCast(which)) * 2; _ = cpu.memory.read(u8, base + 1); try testing.expect(cpu.memory.annunciator(@intCast(which))); _ = cpu.memory.read(u8, base); try testing.expect(!cpu.memory.annunciator(@intCast(which))); } // A write does it as readily as a read: what drives the pin is the // address decode, and "the annunciators are on/off outputs which can be // brought high or low" without the data bus being involved at all // (Sather, 1985, p. 2-16). The byte written is not looked at. cpu.memory.write(u8, 0xc059, 0x00); try testing.expect(cpu.memory.annunciator(0)); cpu.memory.write(u8, 0xc058, 0xff); try testing.expect(!cpu.memory.annunciator(0)); // And each is its own latch: moving one leaves the others where they were. _ = cpu.memory.read(u8, 0xc05b); _ = cpu.memory.read(u8, 0xc05d); try testing.expect(!cpu.memory.annunciator(0)); try testing.expect(cpu.memory.annunciator(1)); try testing.expect(cpu.memory.annunciator(2)); } test "annunciator three and double resolution are one latch under two names" { var cpu = try machine(); // $c05e clears the pin, and clearing it is what asks for the mode; $c05f // sets the pin and takes the mode away. There is only one latch here, so // there is no arrangement of accesses that can make the two disagree. _ = cpu.memory.read(u8, 0xc05e); try testing.expect(cpu.memory.double_hires); try testing.expect(!cpu.memory.annunciator(3)); _ = cpu.memory.read(u8, 0xc05f); try testing.expect(!cpu.memory.double_hires); try testing.expect(cpu.memory.annunciator(3)); // It is the same latch a IIgs reads back in bit 5 of its Interrupt Flag // register, which is the one machine in the family where an annunciator // can be read at all; see `apple2gs.zig`. On this one it cannot: "there // is no way to read the state of an annunciator" (Apple Computer, Inc., // 1985b, p. 40), and nothing here offers a soft switch that says // otherwise. try testing.expectEqual(cpu.memory.double_hires, !cpu.memory.annunciator(3)); } test "a IIc can be asked for double high resolution, and say so" { var cpu = try compact(); // `IOUDis` decides which of two things the eight addresses from $c058 // are, and it is on when the machine comes up: "the IOUDis ($C07E) switch // must be on to allow you to use locations $C05E and $C05F to change // DHiRes. The firmware in fact leaves it on -- and your program should, // too -- unless it wants to use locations $C05E and $C05F to change mouse // values" (Apple Computer, Inc., 1989b, Table 6-9's text). // // So a program that wants double resolution has to do nothing at all. // Nothing here draws it; what is checked is that it can be set and read // back. // // **Both status reads are inverted**, which is the manual being precise: // "Read IOUDis switch (1 = off)" and "Read DHiRes switch (1 = off)" // (Table 9-2, p. 256). A one means the switch is *not* on, and reading // them the obvious way round is how this had them for a long time. try testing.expect(cpu.memory.read(u8, 0xc07e) & 0x80 == 0); // IOUDis on _ = cpu.memory.read(u8, 0xc05e); try testing.expect(cpu.memory.read(u8, 0xc07f) & 0x80 == 0); // DHiRes on _ = cpu.memory.read(u8, 0xc05f); try testing.expect(cpu.memory.read(u8, 0xc07f) & 0x80 != 0); // and off // With IOUDis turned off the IOU has those addresses back, they are the // mouse's edge selector, and they leave the video alone. cpu.memory.write(u8, 0xc07f, 0); try testing.expect(cpu.memory.read(u8, 0xc07e) & 0x80 != 0); // IOUDis off _ = cpu.memory.read(u8, 0xc05e); try testing.expect(cpu.memory.read(u8, 0xc07f) & 0x80 != 0); // still off try testing.expect(!cpu.memory.y_edge); } test "a IIc has its drive built in rather than fitted" { var cpu = try compact(); // A IIe answers at the drive's addresses only with a card in a slot. A // IIc has the controller soldered down and its driver in its own ROM, so // the addresses work with nothing fitted at all — and it has no slots to // fit anything in. try testing.expectEqual(void, @TypeOf(cpu.memory.slots)); // One drive in the case, and the socket on the back for another. try testing.expectEqual(@as(u2, 1), cpu.memory.drives().fitted); _ = cpu.memory.read(u8, 0xc0e9); // the motor on try testing.expect(cpu.memory.drives().motor); _ = cpu.memory.read(u8, 0xc0e8); // and off again try testing.expect(!cpu.memory.drives().motor); } test "only a IIc Plus has a three-and-a-half inch drive to put a disk in" { // The drive is the IIc Plus's alone: "The Apple IIc Plus has one internal // 3.5-inch disk drive" (Apple Computer, Inc., 1989b, p. 86), and no // earlier IIc has any. `disks35()` is how a front end asks, so it must // answer for the version byte rather than for the machine. var plus = try compact(); var rom: [2 * rom_size]u8 = @splat(0); rom[iic_version - 0xc000] = iic_plus_version; try plus.memory.loadROMAtEnd(&rom); try testing.expect(plus.memory.disks35() != null); // A memory-expansion IIc has the same two banks and no such drive. var earlier = try compact(); var older: [2 * rom_size]u8 = @splat(0); older[iic_version - 0xc000] = 0x04; try earlier.memory.loadROMAtEnd(&older); try testing.expect(earlier.memory.disks35() == null); } test "the intelligent drive is the 32K ROM machines' and nobody else's" { // The other side of the same question. A UniDisk 3.5 is reached through // the Protocol Converter, which is what the 32K ROM added, so the machine // with sixteen kilobytes of ROM has no firmware to talk to one and the // port answers for nothing. var original = try compact(); var small: [rom_size]u8 = @splat(0); small[iic_version - 0xc000] = 0xff; try original.memory.loadROMAtEnd(&small); try testing.expect(original.memory.unidisk() == null); // The machines it was sold for: memory expansion, and the UniDisk ROM // itself. for ([_]u8{ 0x00, 0x03, 0x04 }) |version| { var sold = try compact(); var rom: [2 * rom_size]u8 = @splat(0); rom[iic_version - 0xc000] = version; try sold.memory.loadROMAtEnd(&rom); try testing.expect(sold.memory.unidisk() != null); // And never both at once: the drive in a IIc Plus's case is already // on the connector this would have to answer at. try testing.expect(sold.memory.disks35() == null); } var plus = try compact(); var five: [2 * rom_size]u8 = @splat(0); five[iic_version - 0xc000] = iic_plus_version; try plus.memory.loadROMAtEnd(&five); try testing.expect(plus.memory.unidisk() == null); try testing.expect(plus.memory.disks35() != null); } test "a IIc with a 32K ROM switches its two banks with $C028" { var cpu = try compact(); // Two 16K banks, told apart by a marker in the $c100 firmware space, which // is where the switch reaches: the second holds the UniDisk 3.5 driver and // the diagnostics that the first has no room for. var rom: [2 * rom_size]u8 = @splat(0); rom[0x100] = 0xa0; // bank 0 at $c100 rom[rom_size + 0x100] = 0xb1; // bank 1 at $c100 try cpu.memory.loadROMAtEnd(&rom); // A 32K image comes up banked, on the main bank. try testing.expect(cpu.memory.banked); try testing.expectEqual(@as(u1, 0), cpu.memory.rom_bank); try testing.expectEqual(@as(u8, 0xa0), cpu.memory.read(u8, 0xc100)); // "$C028 to toggle between its two 16K banks of memory" (Apple Computer, // Inc., 1985e, Appendix F.10): each access flips it. _ = cpu.memory.read(u8, 0xc028); try testing.expectEqual(@as(u1, 1), cpu.memory.rom_bank); try testing.expectEqual(@as(u8, 0xb1), cpu.memory.read(u8, 0xc100)); _ = cpu.memory.read(u8, 0xc028); try testing.expectEqual(@as(u1, 0), cpu.memory.rom_bank); try testing.expectEqual(@as(u8, 0xa0), cpu.memory.read(u8, 0xc100)); // The Monitor and Applesoft above $d000 are the same whichever bank is in, // so a program in the second bank can still call them; only $c100-$cfff // switches. Reset comes up on the main bank wherever the switch was left. _ = cpu.memory.read(u8, 0xc028); try testing.expectEqual(@as(u1, 1), cpu.memory.rom_bank); cpu.memory.reset(); try testing.expectEqual(@as(u1, 0), cpu.memory.rom_bank); } test "a IIc with the original 16K ROM leaves $C028 reserved" { var cpu = try compact(); var rom: [rom_size]u8 = @splat(0); try cpu.memory.loadROMAtEnd(&rom); // "On the original Apple IIc, both reading from and writing to these // locations are reserved" (Apple Computer, Inc., 1985e, Appendix F.2): // with one bank of ROM there is nothing for the switch to reach. try testing.expect(!cpu.memory.banked); _ = cpu.memory.read(u8, 0xc028); try testing.expectEqual(@as(u1, 0), cpu.memory.rom_bank); } test "a IIc has two serial ports where the cards would have been" { var cpu = try compact(); // The one marked with a telephone is where slot two's card put its chip, // and the one marked with a printer where slot one's would have. Neither // is fitted or left out: they are the machine. inline for (.{ 0xc098, 0xc0a8 }) |port| { // The rate and the shape of a word, written and read back. cpu.memory.write(u8, port + 3, 0x1e); // 9600, eight bits, one stop try testing.expectEqual(@as(u8, 0x1e), cpu.memory.read(u8, port + 3)); cpu.memory.write(u8, port + 2, 0x0b); // no interrupts wanted try testing.expectEqual(@as(u8, 0x0b), cpu.memory.read(u8, port + 2)); // With nothing coming in, the status says nothing is waiting. try testing.expect(cpu.memory.read(u8, port + 1) & 0x08 == 0); } // And they are two chips, not one answering twice: setting one leaves // the other where it was. cpu.memory.write(u8, 0xc09b, 0x16); try testing.expectEqual(@as(u8, 0x16), cpu.memory.read(u8, 0xc09b)); try testing.expectEqual(@as(u8, 0x1e), cpu.memory.read(u8, 0xc0ab)); } test "a IIc's mouse is four lines and an interrupt" { var cpu = try compact(); // The button reads the other way round from every other button on the // machine: the bit is up when it is not being pressed. try testing.expect(cpu.memory.read(u8, 0xc063) & 0x80 != 0); cpu.memory.setMouseButton(true); try testing.expect(cpu.memory.read(u8, 0xc063) & 0x80 == 0); // Nothing is said about movement until the machine asks to be told. cpu.memory.moveMouse(2, 0); _ = cpu.memory.read(u8, 0xea); try testing.expect(!cpu.irq); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc040)); // Asking is $c059, and reaching it means turning IOUDis *off* so that the // IOU has those addresses: on, which is where the machine comes up, they // are the video's and $c059 does nothing. _ = cpu.memory.read(u8, 0xc059); _ = cpu.memory.read(u8, 0xea); try testing.expect(!cpu.irq); cpu.memory.write(u8, 0xc07f, 0); _ = cpu.memory.read(u8, 0xc059); _ = cpu.memory.read(u8, 0xea); try testing.expect(cpu.irq); // Which line moved, and which way. try testing.expect(cpu.memory.read(u8, 0xc040) & 0x80 != 0); try testing.expect(cpu.memory.read(u8, 0xc066) & 0x80 != 0); // Reading which line moved does not clear it. The firmware reads it // twice — once to see whether the interrupt was the mouse's at all and // once to see which of the two lines it was — and clears both together // when it has counted them. A read that cleared would leave it looking at // nothing the second time. try testing.expect(cpu.memory.read(u8, 0xc015) & 0x80 != 0); try testing.expect(cpu.memory.read(u8, 0xc015) & 0x80 != 0); try testing.expect(cpu.memory.read(u8, 0xc017) & 0x80 == 0); // Clearing is $c048, and then the next step follows. That it is cleared // cannot be seen by reading it: the read that looked would itself be the // access that hands the next step over, which is the hardware being // faster than a program can watch it. _ = cpu.memory.read(u8, 0xc048); try testing.expect(!cpu.irq); _ = cpu.memory.read(u8, 0xea); try testing.expect(cpu.irq); _ = cpu.memory.read(u8, 0xc048); // And with both given there is no third. _ = cpu.memory.read(u8, 0xea); try testing.expect(!cpu.irq); // Rolling the other way says so on the direction line. cpu.memory.moveMouse(-1, 0); _ = cpu.memory.read(u8, 0xea); try testing.expect(cpu.irq); try testing.expect(cpu.memory.read(u8, 0xc066) & 0x80 == 0); // Up and down is the other pair, and the two lines do not agree about // which way is which: the firmware inverts what it reads on this one // before counting it, so down the screen is the line low. _ = cpu.memory.read(u8, 0xc048); cpu.memory.moveMouse(0, 1); _ = cpu.memory.read(u8, 0xea); try testing.expect(cpu.memory.read(u8, 0xc040) & 0x40 != 0); try testing.expect(cpu.memory.read(u8, 0xc017) & 0x80 != 0); try testing.expect(cpu.memory.read(u8, 0xc067) & 0x80 == 0); // Told to stop, it stops. _ = cpu.memory.read(u8, 0xc058); try testing.expect(!cpu.irq); } test "a model can be handed its processor instead of working out where it is" { // The Apple IIgs case in miniature. Its slow side is a Mega II, which is // this machine, and there it would be a part of a larger model rather than // the processor's own `memory` field — so walking back one field would // land in the wrong place. Told where the processor is instead, everything // it needs from one still reaches it: the clock it spends cycles against, // and the line it pulls. const Given = @import("../cpu8.zig").CPU( @import("../clock.zig").FakeClock, AppleIIe(.{ .host = .given }), ); // Not returned by value from a helper, as the tests above do: a pointer // handed over here would go on pointing at the original. A model that // finds its own way back does not care where it is copied to, which is // one more reason to prefer that where it is possible. var cpu: Given = undefined; try cpu.init(null, null); cpu.memory.setHost(&cpu); // The clock is reached, which is the first of the two things it wants a // processor for: a byte read costs a cycle. try testing.expectEqual(@as(u64, 0), cpu.clock.cycles); cpu.memory.write(u8, 0x2000, 0x11); try testing.expectEqual(@as(u64, 1), cpu.clock.cycles); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x2000)); try testing.expectEqual(@as(u64, 2), cpu.clock.cycles); // And the machine is the same machine: the switches still move the memory // under it, which is all of the part that has nothing to do with a // processor. cpu.memory.write(u8, 0xc005, 0); // RAMWRT on: writes go to the other half cpu.memory.write(u8, 0x2000, 0x22); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x2000)); cpu.memory.write(u8, 0xc003, 0); // RAMRD on: and reads come from it try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(u8, 0x2000)); } test "an embedded model carries nothing for the processor it can already find" { // The ordinary machines must be exactly what they were: no pointer stored, // nothing dereferenced, the offset still a compile-time constant. The // field is `void` there, which is the compiler's way of saying it is not // there at all. const embedded = @TypeOf(@as(TestCPU.Memory, undefined).host); try testing.expectEqual(void, embedded); try testing.expectEqual(@as(usize, 0), @sizeOf(embedded)); } test "a half can be reached by name, whatever the switches say" { // What a machine with this one inside it needs: an Apple IIgs addressing // bank $e0 or $e1 means that half, and RAMRD has nothing to say about it. var cpu = try machine(); cpu.memory.halfTarget(false, 0x2000, true).?.* = 0x11; cpu.memory.halfTarget(true, 0x2000, true).?.* = 0x22; // Through the switches, RAMRD decides. try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x2000)); cpu.memory.write(u8, 0xc003, 0); // RAMRD on try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(u8, 0x2000)); // By name, it does not. try testing.expectEqual(@as(u8, 0x11), cpu.memory.halfTarget(false, 0x2000, false).?.*); try testing.expectEqual(@as(u8, 0x22), cpu.memory.halfTarget(true, 0x2000, false).?.*); } test "naming a half still leaves the language card where it is" { // The window above $d000 is RAM or ROM according to the language card // switches, and null is how this says "not RAM just now": what is there // instead is the caller's to supply, because on a IIgs it is the IIgs's // own ROM rather than this machine's. var cpu = try machine(); // A machine comes up reading ROM there. try testing.expectEqual(@as(?*u8, null), cpu.memory.halfTarget(false, 0xd000, false)); try testing.expectEqual(@as(?*u8, null), cpu.memory.halfTarget(false, 0xe000, false)); // And the switch page is never RAM. try testing.expectEqual(@as(?*u8, null), cpu.memory.halfTarget(false, 0xc030, false)); // Read and write the language card in — $c08b twice, since enabling the // write needs two reads of an odd address — and it is RAM again, in // whichever half was named rather than whichever ALTZP points at. _ = cpu.memory.read(u8, 0xc08b); _ = cpu.memory.read(u8, 0xc08b); cpu.memory.halfTarget(true, 0xd000, true).?.* = 0x5a; try testing.expectEqual(@as(u8, 0x5a), cpu.memory.halfTarget(true, 0xd000, false).?.*); try testing.expect(cpu.memory.halfTarget(false, 0xd000, false).?.* != 0x5a); } test "the ROM says which IIe it is, and the character generator follows the firmware" { // "The identification byte at $FBC0 has been changed. In the original // Apple IIe it was $EA (decimal 234), in the enhanced Apple IIe it is $E0 // (decimal 224)" (Apple Computer, Inc., 1985b, p. xxix). var cpu: TestCPU = undefined; try cpu.init(null, null); var rom: [rom_size]u8 = @splat(0xea); rom[identification - 0xc000] = 0xea; try cpu.memory.loadROMAtEnd(&rom); try testing.expectEqual(Firmware.original, cpu.memory.firmware); try testing.expectEqual(font.Set.apple2e, cpu.memory.characterSet()); rom[identification - 0xc000] = 0xe0; try cpu.memory.loadROMAtEnd(&rom); try testing.expectEqual(Firmware.enhanced, cpu.memory.firmware); try testing.expectEqual(font.Set.apple2e_enhanced, cpu.memory.characterSet()); // A ROM that is neither leaves the chip alone. rom[identification - 0xc000] = 0x00; try cpu.memory.loadROMAtEnd(&rom); try testing.expectEqual(Firmware.unknown, cpu.memory.firmware); try testing.expectEqual(font.Set.apple2e_enhanced, cpu.memory.characterSet()); // And an owner who swapped only the video ROM can say so. cpu.memory.fitCharacterGenerator(.apple2e); try testing.expectEqual(font.Set.apple2e, cpu.memory.characterSet()); } test "a IIc is not asked which firmware it has: it always had MouseText" { const IIcCPU = @import("../cpu8.zig").CMOS(@import("../clock.zig").FakeClock, AppleIIc(.{})); var cpu: IIcCPU = undefined; try cpu.init(null, null); var rom: [rom_size]u8 = @splat(0x00); rom[identification - 0xc000] = 0xea; // what would mean "original" on a IIe try cpu.memory.loadROMAtEnd(&rom); try testing.expectEqual(Firmware.unknown, cpu.memory.firmware); try testing.expectEqual(font.Set.apple2e_enhanced, cpu.memory.characterSet()); } test "a IIc's memory expansion card answers at $c0c0, where a IIe has its mouse" { var cpu = try compact(); const ram = try testing.allocator.alloc(u8, ramfactor.block_size); defer testing.allocator.free(ram); @memset(ram, 0); try cpu.memory.fitMemoryExpansion(ram); // "The memory expansion card's registers are: $C0C0 low byte of the // address register; $C0C1 middle byte; $C0C2 high nibble (D3-D0) of the // address register; $C0C3 data register" (Apple Computer, Inc., 1987b, // p. 7). The address goes in lowest byte first, as the ripple carry // between the counters requires. cpu.memory.write(u8, 0xc0c0, 0x02); cpu.memory.write(u8, 0xc0c1, 0x00); cpu.memory.write(u8, 0xc0c2, 0x00); cpu.memory.write(u8, 0xc0c3, 0x5a); try testing.expectEqual(@as(u8, 0x5a), ram[2]); // "the address register automatically increments after each access of the // data register", so the next write lands in the next byte without the // address being given again. cpu.memory.write(u8, 0xc0c3, 0xa5); try testing.expectEqual(@as(u8, 0xa5), ram[3]); // And it reads back the same way. cpu.memory.write(u8, 0xc0c0, 0x02); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(u8, 0xc0c3)); try testing.expectEqual(@as(u8, 0xa5), cpu.memory.read(u8, 0xc0c3)); // Only the low nibble of the high byte is stored, and the top four read // back as ones: that is what makes the counter twenty bits wide. cpu.memory.write(u8, 0xc0c2, 0xff); try testing.expectEqual(@as(u8, 0xff), cpu.memory.read(u8, 0xc0c2)); cpu.memory.write(u8, 0xc0c2, 0x00); // Past the last chip nothing drives the lines, which is how the firmware // sizes the card. cpu.memory.write(u8, 0xc0c0, 0x00); cpu.memory.write(u8, 0xc0c1, 0x00); cpu.memory.write(u8, 0xc0c2, 0x0f); try testing.expectEqual(ramfactor.undriven, cpu.memory.read(u8, 0xc0c3)); // The registers stay awake through a reset, because there is no firmware // page on this card to wake them with. cpu.memory.reset(); cpu.memory.write(u8, 0xc0c0, 0x07); cpu.memory.write(u8, 0xc0c1, 0x00); cpu.memory.write(u8, 0xc0c2, 0x00); cpu.memory.write(u8, 0xc0c3, 0x33); try testing.expectEqual(@as(u8, 0x33), ram[7]); // And the slot the RamFactor uses on a machine with slots is not this // card: on a IIc that is the clock's alone. cpu.memory.write(u8, 0xc0d0, 0x01); cpu.memory.write(u8, 0xc0d3, 0x99); try testing.expectEqual(@as(u8, 0x33), ram[7]); } test "a Transporter in slot seven answers where its firmware looks for it" { // The card's whole conversation with the machine, through the machine // rather than beside it: the PROM appears in slot seven's page, `$c0f0` // reads the READY line the firmware waits on, and three bytes written // there are a command vector address the card then goes and fetches out // of memory by itself. var cpu = try machine(); // Not Corvus's PROM — that is somebody else's code and lives in the ROM // catalogue, not in here. Any two hundred and fifty-six bytes prove the // page is wired; what is in them is the catalogue's business. var firmware: [transporter_rom_size]u8 = undefined; for (&firmware, 0..) |*byte, i| byte.* = @truncate(i); try cpu.memory.fitTransporter(&firmware, 0x2a); // The page is the card's now. try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, transporter_rom_base)); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, transporter_rom_base + 0x11)); // And the first of its addresses holds the READY line up, which is what // `BIT $c080,X` and a `BPL` back on itself are waiting for. const port: u16 = 0xc000 + transporter_switch_base; try testing.expect(cpu.memory.read(u8, port) & 0x80 != 0); // A `Who Am I` at $2000 with its result record at $3000. cpu.memory.write(u8, 0x2000, @intFromEnum(omninet.Command.who_am_i)); cpu.memory.write(u8, 0x2001, 0x00); cpu.memory.write(u8, 0x2002, 0x30); cpu.memory.write(u8, 0x2003, 0x00); cpu.memory.write(u8, 0x3000, omninet.pending); // Three bytes of the vector's address, most significant first, which is // exactly what the PROM's `STA $c080,X` does three times over. cpu.memory.write(u8, port, 0x00); cpu.memory.write(u8, port, 0x20); try testing.expectEqual(omninet.pending, cpu.memory.read(u8, 0x3000)); cpu.memory.write(u8, port, 0x00); // The card went and read the vector out of memory and left its answer // where the vector said to. Nothing copied it there but the card. try testing.expectEqual(@as(u8, 0x2a), cpu.memory.read(u8, 0x3000)); try testing.expectEqual(omninet.Command.who_am_i, cpu.memory.slots.cards[7].transporter.card.last.?); } test "one card to a slot: a Transporter takes the block device's place" { // They would otherwise both be in slot seven and both answering at // `$c0f0`, which is two cards in one connector. var cpu = try machine(); var volume: blockdevice.Volume = undefined; cpu.memory.insertVolume(0, &volume); try testing.expect(cpu.memory.blockCard().?.fitted()); var firmware: [transporter_rom_size]u8 = @splat(0); try cpu.memory.fitTransporter(&firmware, 0x01); try testing.expect(cpu.memory.slots.first(.transporter) != null); try testing.expect(cpu.memory.blockCard() == null); } test "a Transporter is refused firmware that is not the size of its PROM" { var cpu = try machine(); var wrong: [128]u8 = @splat(0); try testing.expectError(error.WrongSize, cpu.memory.fitTransporter(&wrong, 0)); try testing.expect(cpu.memory.slots.first(.transporter) == null); } test "an empty slot floats rather than answering from the machine's own ROM" { var cpu = try machine(); // Something recognisable in the internal ROM at $c100 and $c800, so that // ROM answering can be told from ROM not answering. cpu.memory.rom[0x0100] = 0x4c; cpu.memory.rom[0x0800] = 0x4c; // "reset / reset -> slot" for $c100-$c2ff and $c400-$cfff (Sather, 1985, // p. 5-28), and nothing is in slot 1, so nothing drives the bus. try testing.expect(!cpu.memory.intcxrom); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc100)); // INTCXROM is how a program takes the range back for the motherboard. It // is written rather than read: Table 5.4 gives its addresses as W$C006 and // W$C007 (Sather, 1985, p. 5-22), and reading there reads the keyboard. cpu.memory.write(u8, 0xc007, 0); try testing.expect(cpu.memory.intcxrom); try testing.expectEqual(@as(u8, 0x4c), cpu.memory.read(u8, 0xc100)); try testing.expectEqual(@as(u8, 0x4c), cpu.memory.read(u8, 0xc800)); } test "the machine's own $c800 firmware is taken by touching $c300, and given up at $cfff" { var cpu = try machine(); cpu.memory.rom[0x0800] = 0x4c; // Nobody has the window yet, so it floats: an unclaimed $c800 is not the // machine's ROM, which is the distinction INTC8ROM exists to draw. try testing.expect(!cpu.memory.intc8rom); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc800)); // "The $C800-$CFFF range is assigned to motherboard ROM (INTernal) anytime // SLOTC3ROM is reset and an access is made to $C3XX" (Sather, 1985, // p. 5-28). This is how the eighty-column firmware at $c300 reaches the // rest of itself. try testing.expect(!cpu.memory.slotc3rom); _ = cpu.memory.read(u8, 0xc300); try testing.expect(cpu.memory.intc8rom); try testing.expectEqual(@as(u8, 0x4c), cpu.memory.read(u8, 0xc800)); // "...until an access is made to $CFFF or until the MMU detects a system // reset", and $cfff is the one every card's firmware uses on its way out. _ = cpu.memory.read(u8, 0xcfff); try testing.expect(!cpu.memory.intc8rom); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc800)); } test "SLOTC3ROM alone decides whether $c3xx takes the $c800 window" { var cpu = try machine(); cpu.memory.rom[0x0800] = 0x4c; // With SLOTC3ROM set, $c3xx belongs to slot 3 and an access there is not // the motherboard claiming anything, whatever INTCXROM says. a2audit // checks exactly this sequence, and getting it wrong by folding INTCXROM // into the condition leaves $c800 reading as ROM when it should float. cpu.memory.write(u8, 0xc007, 0); // INTCXROM on cpu.memory.write(u8, 0xc00b, 0); // SLOTC3ROM on _ = cpu.memory.read(u8, 0xc300); try testing.expect(!cpu.memory.intc8rom); cpu.memory.write(u8, 0xc006, 0); // INTCXROM off again try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc800)); } test "slot three is the one empty slot the machine fills itself" { var cpu = try machine(); cpu.memory.rom[0x0300] = 0x4c; // "reset / reset -> internal" for $c300-$c3ff: the IIe answering there is // it "emulating an Apple II with 80-column card installed in Slot 3" // (Sather, 1985, p. 5-28). try testing.expectEqual(@as(u8, 0x4c), cpu.memory.read(u8, 0xc300)); // "reset / set -> slot", and slot 3 is empty, so this one floats where // every other combination gives ROM. cpu.memory.write(u8, 0xc00b, 0); try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc300)); } test "the video scanner reproduces Sather's screen memory scanning summary" { // Table 5.2 (Sather, 1985, p. 5-19) says what is scanned during and // outside horizontal blanking for each third of the screen and for the // vertical blanking interval. It is the whole check on the address // arithmetic, so it is checked whole. // // Each region is named by a line that falls in it, chosen so that V0-V2 // are zero and the address is simply $400 plus the offset into the // 128-byte segment. const Region = struct { what: []const u8, line: u64, /// The 24 distinct offsets scanned during the 25 cycles of HBL. blanking: [24]u16, /// The 40 scanned outside it, in order. displayed: [40]u16, }; const run = struct { fn from(first: u16) [40]u16 { var out: [40]u16 = undefined; for (&out, 0..) |*at, i| at.* = (first + @as(u16, @intCast(i))) & 0x7f; return out; } fn short(first: u16) [24]u16 { var out: [24]u16 = undefined; for (&out, 0..) |*at, i| at.* = (first + @as(u16, @intCast(i))) & 0x7f; return out; } }; const regions = [_]Region{ // "SCREEN TOP: last 16 of THIRD 40 and UNUSED 8 | FIRST 40" .{ .what = "top", .line = 0, .blanking = run.short(104), .displayed = run.from(0) }, // "SCREEN MIDDLE: last 24 of FIRST 40 | SECOND 40" .{ .what = "middle", .line = 64, .blanking = run.short(16), .displayed = run.from(40) }, // "SCREEN BOTTOM: last 24 of SECOND 40 | THIRD 40" .{ .what = "bottom", .line = 128, .blanking = run.short(56), .displayed = run.from(80) }, // "VBL: last 24 of THIRD 40 | UNUSED 8 and first 32 of FIRST 40", // which is the one that wraps round the segment. .{ .what = "vbl", .line = 192, .blanking = run.short(96), .displayed = run.from(120) }, }; for (regions) |region| { var cpu = try machine(); cpu.memory.text = true; // The 25 cycles of horizontal blanking cover 24 addresses, because // the horizontal counter holds 0 for the first two of them. var seen: [25]u16 = undefined; for (&seen, 0..) |*at, cycle| { cpu.clock.cycles = region.line * cycles_per_line + cycle; at.* = cpu.memory.scannerAddress(); } try testing.expectEqual(seen[0], seen[1]); for (region.blanking, seen[1..]) |want, got| { try testing.expectEqual(0x400 + want, got); } for (region.displayed, 0..) |want, i| { cpu.clock.cycles = region.line * cycles_per_line + 25 + i; try testing.expectEqual(0x400 + want, cpu.memory.scannerAddress()); } } } test "the scanner follows the display page and the Hi-Res interleave" { var cpu = try machine(); // Hi-Res puts VA-VC on A10-A12, so consecutive scan lines are $400 apart // and the first byte of line 1 is at $2400 rather than $2028. cpu.memory.text = false; cpu.memory.hires = true; cpu.memory.mixed = false; cpu.clock.cycles = 25; try testing.expectEqual(@as(u16, 0x2000), cpu.memory.scannerAddress()); cpu.clock.cycles = cycles_per_line + 25; try testing.expectEqual(@as(u16, 0x2400), cpu.memory.scannerAddress()); cpu.clock.cycles = 8 * cycles_per_line + 25; try testing.expectEqual(@as(u16, 0x2080), cpu.memory.scannerAddress()); // PAGE2 moves it to $4000, and text to $400 and $800. cpu.memory.page2 = true; cpu.clock.cycles = 25; try testing.expectEqual(@as(u16, 0x4000), cpu.memory.scannerAddress()); cpu.memory.text = true; try testing.expectEqual(@as(u16, 0x800), cpu.memory.scannerAddress()); // Except that 80STORE takes PAGE2 away from the display and gives it to // the auxiliary half, so the scanner goes back to page 1. cpu.memory.store80 = true; try testing.expectEqual(@as(u16, 0x400), cpu.memory.scannerAddress()); } test "in mixed mode the scanner switches to text twice a frame" { var cpu = try machine(); cpu.memory.text = false; cpu.memory.hires = true; cpu.memory.mixed = true; // "V4 . V2 actually identifies scan lines 160 through 191 and 224 through // 261" (Sather, 1985, p. 5-19). The second of those is inside the // blanking, where it cannot be seen and still decides what is scanned. const text_lines = [_]u64{ 160, 191, 224, 261 }; const graphics_lines = [_]u64{ 0, 159, 192, 223 }; for (text_lines) |line| { cpu.clock.cycles = line * cycles_per_line + 25; try testing.expect(cpu.memory.scannerAddress() < 0x800); } for (graphics_lines) |line| { cpu.clock.cycles = line * cycles_per_line + 25; try testing.expect(cpu.memory.scannerAddress() >= 0x2000); } } test "an undriven address reads the byte the video scanner last fetched" { var cpu = try machine(); cpu.memory.text = true; // Put something recognisable where the scanner will be looking on the // cycle the read happens, remembering that the read spends a cycle of its // own before the bus is sampled. cpu.clock.cycles = 25; const at = cpu.memory.scannerAddress(); // A value whose low seven bits differ from the whole, so that the status // read below is actually saying something. cpu.memory.main.ram[at] = 0x5a; cpu.clock.cycles = 24; // An empty slot's page, which used to answer from the machine's own ROM // and then answered zero. try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(u8, 0xc100)); // A soft switch touched for its effect rather than read for an answer. cpu.clock.cycles = 24; try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(u8, 0xc050)); // And a status read, which reports in bit 7 and leaves the other seven to // the bus. cpu.clock.cycles = 24; cpu.memory.text = true; try testing.expectEqual(@as(u8, 0xda), cpu.memory.read(u8, 0xc01a)); } test "a machine is written to a snapshot and read back to where it was" { const alloc = testing.allocator; var cpu = try machine(); // Put the machine somewhere distinctive: a byte in main RAM, one in the // auxiliary bank, a soft switch thrown, and the processor's own registers. cpu.memory.main.ram[0x1234] = 0xa5; cpu.memory.aux.ram[0x0400] = 0x5a; cpu.memory.col80 = true; cpu.memory.altzp = true; cpu.registers.set(.A, 0x42); cpu.program_counter.value = 0x0300; cpu.clock.cycles = 987_654; const saved = try snapshot.save(alloc, &cpu); defer alloc.free(saved); // Now move it somewhere else entirely. cpu.memory.main.ram[0x1234] = 0x00; cpu.memory.aux.ram[0x0400] = 0x00; cpu.memory.col80 = false; cpu.memory.altzp = false; cpu.registers.set(.A, 0xff); cpu.program_counter.value = 0xc600; cpu.clock.cycles = 0; // Reading the snapshot back puts every one of them where it was. try snapshot.load(alloc, saved, &cpu); try testing.expectEqual(@as(u8, 0xa5), cpu.memory.main.ram[0x1234]); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.aux.ram[0x0400]); try testing.expect(cpu.memory.col80); try testing.expect(cpu.memory.altzp); try testing.expectEqual(@as(u8, 0x42), cpu.registers.get(.A)); try testing.expectEqual(@as(u16, 0x0300), cpu.program_counter.value); try testing.expectEqual(@as(u64, 987_654), cpu.clock.cycles); }