// 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; /// Where the address space stops being RAM. const disk2 = @import("../disk2.zig"); const disk35 = @import("../disk35.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 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 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); /// How fast the machine's own clock runs, which is what paces a tape being /// played in. pub const cycles_per_second = 1_020_500; /// Video timing, which this model needs only so that it can say where the /// video scanner is looking. A scan line is 65 cycles and a frame is 262 of /// them, the same as every other machine in the family. const cycles_per_line = 65; const lines_per_frame = 262; const cycles_per_frame = cycles_per_line * lines_per_frame; const ram_size = 0xc000; /// The ROM covers $c000 to $ffff. Nothing is ever read from the first page of /// it, since that is where the soft switches live, but keeping the array the /// full size means a ROM image can be laid down by its address rather than by /// an offset into it. const rom_size = 0x4000; /// Where the Disk II lives: slot 6, whose switches are the sixteen at $c0e0 /// and whose ROM is the page at $c600. /// 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, where a modem went. /// 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; const block_switch_base = 0x80 + block_slot * 0x10; /// The card's own firmware, which is ours rather than Apple's. const block_firmware = blockdevice.firmware(block_slot); const serial_slot = 2; const serial_rom_size = 0x800; 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. 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 an eighty column card goes: slot 3, which is the slot the Videoterm /// was sold for and the one `PR#3` reaches. It is also the only slot this /// machine has left, the other five having cards in them already. const videx_slot = 3; const videx_rom_base = 0xc000 + videx_slot * 0x100; const videx_switch_base = 0x80 + videx_slot * 0x10; /// Where the card's memory and firmware appear once it holds the shared /// window: a kilobyte of firmware, then the five hundred and twelve byte /// window into its screen memory, and then five hundred and twelve bytes the /// card does not answer at all (Videx, 1982, pp. 5-12). const videx_firmware_at = 0xc800; const videx_window_at = 0xcc00; const videx_unused_at = 0xce00; 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; /// The language card: two four kilobyte banks that both answer to $d000, and /// eight kilobytes that answers to $e000. const bank_size = 0x1000; const high_size = 0x2000; /// An Apple II Plus, with a language card fitted. /// /// Below $c000 is plain RAM. From $c000 to $c0ff are the soft switches, which /// are not memory at all: reading or writing one is how the machine is told to /// do something, and the value read back is mostly not meaningful. From $c100 /// to $cfff is where peripheral cards put their ROM. Above that is either the /// machine's own ROM or the language card's RAM, depending on how the bank /// switches have been left. /// /// See the Apple II Reference Manual and the Apple IIe Technical Reference /// Manual, which documents the same bank switches for the machine that /// inherited them (Apple Computer, Inc., 1978, Section D; Apple Computer, Inc., /// 1985, Table 4-6). pub fn AppleIIPlus(comptime options: Options) fn (type) type { return Machine(.ii_plus, options); } /// The Apple II of 1977, which is this same board with other chips in its /// sockets. /// /// "The only operational difference between the Apple II and the Apple II /// Plus is in firmware. The Apple II has Integer BASIC and the old Monitor in /// ROM, while the Apple II Plus has Applesoft BASIC and the Autostart Monitor /// in ROM" (Sather, 1983, Appendix G) — and the firmware comes from the ROM /// file, so the model itself differs in two other things the same appendix /// sets out. The board could be populated with 4K RAM chips as well as 16K, /// in the configurations the Reference Manual lists (Apple Computer, Inc., /// 1978, pp. 133–134), where a II Plus, which came out at Revision 4 or later /// with 16K plugs soldered in, could have 16K, 32K or 48K. And the earliest /// boards, Revision 0, lacked three things Revision 1 added: the colour-burst /// killer that makes text white, the half-dot delay that gives Hi-Res its blue /// and orange, and the power-up reset. See `Revision`. pub fn AppleII(comptime options: Options) fn (type) type { return Machine(.ii, options); } /// Which of the two, since the board is the same. pub const Kind = enum { ii, ii_plus, }; /// Which revision of the board. Sather (1983, Appendix G) lists what Revision /// 1 added: "1. Addition of a COLOR BURST killer circuit to remove colors from /// text. 2. Addition of power-up RESET circuitry. 3. Addition of the HIRES /// delayed video feature which gives the blue and orange colors." Every later /// revision kept all three, and the differences among them — sync widths, /// the character generator's socket, RFI shielding — are not things this model /// can show. So there are two revisions here: the first boards, and every /// board after them, which is also every Apple II Plus. pub const Revision = enum { zero, later, }; /// How the three rows of RAM were jumpered on a board that could take 4K /// chips. The Reference Manual (Apple Computer, Inc., 1978, p. 134) lists five /// standard sets of memory select blocks; the two twelve-kilobyte ones differ /// in where the third row goes. "Type 1 is a contiguous memory range for /// maximum BASIC program size. Type 2 is non-contiguous and allows 8K /// dedicated to HIRES screen memory with approximately 2K of user BASIC /// space." pub const Layout = enum { /// Every row after the first follows on: what type 1, 3, 4 and 5 give. contiguous, /// Type 2: 4K at $0000, and the other two rows at $2000 to $3fff so that /// the first Hi-Res page is there to draw on. hires, }; 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; bus: bus_log.Log(options.bus_log) = .{}, /// $0000 to $bfff. ram: [ram_size]u8 = undefined, /// $c000 to $ffff, of which only $c100 upwards is ever reached. rom: [rom_size]u8 = undefined, /// The seven expansion slots and what is in 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`. slots: slot_module.Slots = .{}, /// What `drives` answers with on a machine that has no disk /// controller in it at all. /// /// A front end asks about the drives whether or not there are /// any — to draw their lights, to know how many there are — /// and the answer for a machine with no card is a port with /// nothing on it, which is what this is. It is never reached /// through an address: no card, no page, no switches. absent_drives: disk2.Controller = .{ .fitted = 0 }, /// The language card. Two banks answer to $d000 and one block answers /// to $e000, which is why the first is stored twice over and the /// second only once. bank: [2][bank_size]u8 = undefined, high: [high_size]u8 = undefined, /// Which bank is answering, whether $d000 upwards reads the card /// or the ROM, whether writes reach it, and whether the first of /// the two reads that enable writing has happened. Every machine /// here with a language card has the same three switches and the /// same latch, so they are one type rather than three copies. card_switches: languagecard.LanguageCard = .{}, /// 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. 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 and gated the same way. phasor_log: phasor.Log(options.mockingboard_log) = .{}, /// And the Sound/Speech card's, gated the same way. soundspeech_log: soundspeech.Log(options.mockingboard_log) = .{}, /// The display switches. They do not move any memory around on a II /// Plus, but they are read and written at the same addresses as the /// ones that do, and something has to hold them. text: bool = true, mixed: bool = false, page2: bool = false, hires: bool = false, /// The four annunciators: one-bit outputs on the sixteen-pin /// game connector, meant for "indicator lights" and each a /// TTL output that has to be buffered to drive anything real /// (Apple Computer, Inc., 1978, p. 108). /// /// Nothing on the machine can read them back -- there is no /// soft switch that says what one is set to -- so they exist /// here for a program using this as a library, which stands /// where the lamp would. See `annunciator`. annunciators: [4]bool = @splat(false), /// Which of the twelve 4K blocks below `$c000` have RAM in /// them, bit 0 for `$0000`. A board came with anything from /// one row of 4K chips to three rows of 16K, and the memory /// select blocks said which addresses each row answered to /// (Apple Computer, Inc., 1978, pp. 133–134). An address with /// no row behind it is the floating bus to read and nothing /// to write. All twelve until `fitRam` says otherwise. ram_blocks: u12 = 0xfff, /// Which board this is. See `Revision`; an Apple II Plus is /// never Revision 0. revision: Revision = .later, /// 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, /// 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. /// /// A II Plus keyboard has no lowercase. The encoder could not send /// it and no program could ever see it, so it is folded away here, /// where the machine is described, rather than in whatever is doing /// the typing. pub fn pressKey(self: *Self, character: u8) void { const pressed = if (character >= 'a' and character <= 'z') character - 0x20 else character; self.keyboard = pressed & 0x7f; self.strobe = true; self.key_down = true; self.empty_polls = 0; } /// What the video circuitry reads. A II Plus has one bank of /// memory and forty columns, so there is nothing to choose /// between; the auxiliary argument is there so that whoever is /// drawing the screen can ask the same question of either /// machine. pub fn videoByte(self: *const Self, auxiliary: bool, address: u16) u8 { _ = auxiliary; return self.ram[address]; } /// Which of the two text pages the screen is drawn from. PAGE2 /// means only this on a machine with no auxiliary memory for it /// to mean anything else about. pub fn displayPage(self: *const Self) u16 { return if (self.page2) 0x0800 else 0x0400; } /// A II Plus draws forty columns and has no way to draw more. pub fn columns(self: *const Self) u16 { _ = self; return 40; } /// What the display is doing. There are three switches rather /// than the IIe's four: eighty columns came with the IIe. pub fn mode(self: *const Self) screen.Mode { if (self.text) return .text; if (self.hires) return if (self.mixed) .high_resolution_mixed else .high_resolution; return if (self.mixed) .low_resolution_mixed else .low_resolution; } /// Whether the colour burst is on the video signal, which is /// what lets a colour monitor colour anything at all. /// /// "In the oldest Apple IIs (Revision 0), the COLOR BURST was /// always present on the VIDEO signal. This resulted in /// distracting green and violet text characters. A Color /// Burst Killer was added in Revision 1 to eliminate the /// COLOR BURST in TEXT MODE. ... In MIXED mode, the four lines /// of text at the bottom of the screen are still green and /// violet because the COLOR BURST is present" (Sather, 1983, /// p. 8-5). So it is the TEXT switch and not the row being /// text that decides. pub fn colourBurst(self: *const Self) bool { return self.revision == .zero or !self.text; } /// Whether bit 7 of a Hi-Res byte delays its dots by half a /// dot. "This was the extent of HIRES patterns in the Revision /// 0 Apple II: 280 programmable dots per scan with violet, /// green, or white coloring. In Revision 1, the D7 delay /// option was added" (Sather, 1983, p. 8-19). pub fn delaysHires(self: *const Self) bool { return self.revision != .zero; } /// Whether an address below `$c000` has a row of RAM behind it. fn hasRam(self: *const Self, address: u16) bool { return self.ram_blocks >> @intCast(address >> 12) & 1 != 0; } /// How many bytes of RAM are fitted. pub fn ramFitted(self: *const Self) usize { return @as(usize, @popCount(self.ram_blocks)) * 0x1000; } /// Populates the board's three rows the way Apple did, or /// refuses. The sizes are the ones the Reference Manual's five /// standard sets of memory select blocks give (Apple Computer, /// Inc., 1978, p. 134): three rows of 4K chips for 4K, 8K and /// 12K; one row of 16K and two of 4K for 16K, 20K and 24K; two /// of 16K and one of 4K for 32K and 36K — the manual prints /// 30K, which two 16K rows cannot make — and three of 16K for /// 48K. A II Plus had 16K plugs soldered in (Sather, 1983, /// Appendix G), so it takes 16K, 32K or 48K only. The rule the /// manual states, "There MUST be RAM assigned to the zero /// block of addresses", every one of these keeps. pub fn fitRam(self: *Self, bytes: usize, layout: Layout) error{NotAConfiguration}!void { const blocks = bytes / 0x1000; if (blocks * 0x1000 != bytes) return error.NotAConfiguration; const allowed: []const usize = switch (kind) { .ii => &.{ 1, 2, 3, 4, 5, 6, 8, 9, 12 }, .ii_plus => &.{ 4, 8, 12 }, }; if (std.mem.indexOfScalar(usize, allowed, blocks) == null) return error.NotAConfiguration; if (layout == .hires) { // Only the third standard set is laid out this way: // three rows of 4K, one at the bottom and two under // the Hi-Res page. if (kind != .ii or blocks != 3) return error.NotAConfiguration; self.ram_blocks = 0b0000_0000_1101; return; } self.ram_blocks = @intCast((@as(u16, 1) << @intCast(blocks)) - 1); } /// A II Plus has one character set, and it flashes. pub fn alternateCharacters(self: *const Self) bool { _ = self; return false; } /// And it is the only one that was ever in the socket: sixty /// four shapes, uppercase and punctuation, with inverse and /// flashing done by an XOR gate rather than by the chip. pub fn characterSet(self: *const Self) font.Set { _ = self; return .apple2; } /// Which of the two Hi-Res pages the screen is drawn from. pub fn hiresPage(self: *const Self) u16 { return if (self.page2) 0x4000 else 0x2000; } /// 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); } /// 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); } /// 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 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 CPU this belongs to, recovered from the field it is embedded in. pub inline fn getCPU(self: *Self) *CPU { return @alignCast(@fieldParentPtr("memory", self)); } /// Zeroes the RAM and puts the bank switches where a power-on leaves /// them: reading the ROM, writing the card, second bank. pub fn init(self: *Self, _: ?usize) void { self.* = .{ .ram = @splat(0), .rom = @splat(0), .bank = @splat(@splat(0)), .high = @splat(0), }; } /// 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 — `fit` takes 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; }; /// The five-and-a-quarter drives, reached the same way on /// every machine that has any. A IIc puts an IWM in front of /// its pair and answers this from inside that; here the /// controller is the whole of the port, so this is simply it. /// /// The lowest-numbered controller, where there is more than /// one: an unqualified question has to mean something, and a /// machine with two of these is a machine whose owner will say /// which they meant. pub inline fn drives(self: *Self) *disk2.Controller { const slot = self.slots.first(.disk) orelse return &self.absent_drives; return &self.slots.cards[slot].disk.drives; } /// Which card of a kind is in the machine, or null for none. /// /// The same question `apple2e.zig` answers, and answered there /// and not here for as long as a II Plus could not be asked /// it: the front end's call is guarded by `hasDrives`, which a /// II Plus used to fail, so the branch that asks this never /// compiled for one. It does now. /// /// 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 { const slot = self.slots.first(tag) orelse return null; return &self.slots.cards[slot]; } /// 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. pub inline fn videxCard(self: *Self) ?*videx.Card { const slot = self.slots.first(.videx) orelse return null; return &self.slots.cards[slot].videx.card; } pub inline fn ultraTermCard(self: *Self) ?*ultraterm.Card { const slot = self.slots.first(.ultraterm) orelse return null; return &self.slots.cards[slot].ultraterm.card; } pub inline fn mouseCard(self: *Self) ?*mouse.Card { const slot = self.slots.first(.mouse) orelse return null; return &self.slots.cards[slot].mouse; } pub inline fn clockCard(self: *Self) ?*clockcard.Card { const slot = self.slots.first(.clock) orelse return null; return &self.slots.cards[slot].clock; } pub inline fn mockingboardCard(self: *Self) ?*mockingboard.Card { const slot = self.slots.first(.mockingboard) orelse return null; return &self.slots.cards[slot].mockingboard; } pub inline fn phasorCard(self: *Self) ?*phasor.Card { const slot = self.slots.first(.phasor) orelse return null; return &self.slots.cards[slot].phasor; } pub inline fn soundSpeechCard(self: *Self) ?*soundspeech.Card { const slot = self.slots.first(.soundspeech) orelse return null; return &self.slots.cards[slot].soundspeech; } pub inline fn memoryCard(self: *Self) ?*ramfactor.Card { const slot = self.slots.first(.ramfactor) orelse return null; return &self.slots.cards[slot].ramfactor.card; } pub inline fn blockCard(self: *Self) ?*blockdevice.Card { const slot = self.slots.first(.block) orelse return null; return &self.slots.cards[slot].block; } /// Takes the memory expansion card out, which is what the /// session does when it is giving back the memory behind it. pub fn ejectMemoryCard(self: *Self) void { const slot = self.slots.first(.ramfactor) orelse return; _ = self.slots.empty(slot); } /// The serial card's chip, and whether anything has listened to /// it yet — which is how something feeding the card knows the /// machine is ready for a byte. pub inline fn serialAcia(self: *Self) ?*serial.Acia { const slot = self.slots.first(.serial) orelse return null; return &self.slots.cards[slot].serial.acia; } pub inline fn serialListening(self: *const Self) bool { 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 { self.slots.fit(slot, .{ .parallel = .{ .fitted = true, .out = out } }) catch {}; } /// Fits a mouse card. pub fn fitMouse(self: *Self, slot: u3) void { self.slots.fit(slot, .{ .mouse = .{ .fitted = true } }) catch {}; } pub fn fitMockingboard(self: *Self, slot: u3, speech: bool) void { self.slots.fit(slot, .{ .mockingboard = .{ .fitted = true, .has_speech = speech } }) catch {}; } /// Fits a Phasor, the four-chip superset of the Mockingboard. pub fn fitPhasor(self: *Self, slot: u3) void { 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 { self.slots.fit(slot, .{ .soundspeech = .{ .fitted = true } }) catch {}; } /// Fits a Passport MIDI interface. pub fn fitPassport(self: *Self, slot: u3) void { self.slots.fit(slot, .{ .passport = .{} }) catch {}; } /// Fits an Uthernet II. pub fn fitUthernet(self: *Self, slot: u3) void { self.slots.fit(slot, .{ .uthernet = .{} }) catch {}; } /// The Uthernet II's W5100, for the session's host end to drive. /// Its presence is what tells a front end this machine can do /// Ethernet at all. pub inline fn ethernetChip(self: *Self) ?*w5100.W5100 { 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 { 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 { 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 can drive MIDI in and out the same way. pub inline fn midiAcia(self: *Self) ?*mc6850.Acia { const slot = self.slots.first(.passport) orelse return null; return &self.slots.cards[slot].passport.acia; } pub inline fn midiListening(self: *const Self) bool { 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: *const Self) []const u8 { const slot = self.slots.first(.passport) orelse return &.{}; return self.slots.cards[slot].passport.acia.sent(); } pub fn midiSentAt(self: *const Self) []const u64 { const slot = self.slots.first(.passport) orelse return &.{}; return self.slots.cards[slot].passport.acia.sentAt(); } pub fn midiConsume(self: *Self, count: usize) void { 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 { var card: clockcard.Card = .{ .fitted = true }; card.set(when, cycles); self.slots.fit(slot, .{ .clock = card }) catch {}; } /// No three-and-a-half inch drive: only a IIc Plus has one. /// Here so that a front end generic over every machine can ask. /// No intelligent drive here either; see `apple2e.zig`. pub inline fn unidisk(_: *Self) ?*@import("../unidisk.zig").Chain { return null; } pub inline fn disks35(_: *Self) ?*disk35.Controller { return null; } /// Puts the bank switches back but leaves memory alone, which is what /// the reset line does. On a II Plus reset did not touch the language /// card at all; this follows the IIe in resetting it, because leaving /// a half-configured card behind is a worse first impression than a /// predictable one. pub fn reset(self: *Self) void { // The reset line reaches the cards too: a Disk II clears // its latch, which stops the motor, and a memory expansion // card stops answering at its registers until its firmware // page is touched again. self.slots.reset(self.getCPU().clock.cycles); self.card_switches.reset(); } /// Lays a ROM image down so that its last byte falls at $ffff, which /// is where the processor looks for its vectors. pub fn loadROMAtEnd(self: *Self, image: []const u8) !void { // 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); } /// The cards, each in the slot it has always gone in, taking /// out whatever was there. /// /// These are the older way in and they *replace*: a machine /// told to fit a Videoterm and then an UltraTerm ends with an /// UltraTerm, because they go in the same slot and the second /// instruction is the one that meant something. The `fit*` /// pairs below take a slot and refuse one that is occupied, /// which is the right answer when somebody has named both. /// /// Fits the Disk II card by giving it its ROM: the 256 bytes of /// the P5 boot PROM. A II Plus has nothing of its own in the /// slot pages, so the card simply answers there. /// /// **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. That is what makes a slot cheap /// enough to have seven of, and it is the same arrangement the /// memory expansion card's megabyte has always been under. A /// front end hands its firmware to the session, which frees it /// when the machine goes. pub fn loadCardROM(self: *Self, image: []const u8) !void { _ = 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 (image.len != card_rom_size) return error.WrongSize; try self.slots.fit(slot, .{ .disk = .{ .rom = image[0..card_rom_size] } }); } /// Fits the Videoterm by giving it the parts out of its /// sockets: a kilobyte of firmware and a two kilobyte /// character generator, and a second generator if the card was /// modified to take one. pub fn loadVidexROM( self: *Self, firmware: []const u8, charset: []const u8, alternate: ?[]const u8, ) !void { _ = 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 (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, } }); } /// The card's character generators, for whatever is drawing /// its screen. The second is null unless one is fitted. pub fn videxCharsets(self: *const Self) struct { set: *const [videx.charset_size]u8, alternate: ?*const [videx.charset_size]u8, } { const slot = self.slots.first(.videx) orelse return .{ .set = &blank_charset, .alternate = null }; const card = &self.slots.cards[slot].videx; return .{ .set = card.charset, .alternate = card.alternate }; } /// Fits an UltraTerm, which goes where a Videoterm goes. /// /// Four kilobytes of firmware and four of character generator. /// The firmware is not four kilobytes of program: a page of /// copyright notice, seven `$Cn00` pages of which this machine /// uses one, and two kilobytes of code above them. pub fn loadUltraTermROM(self: *Self, firmware: []const u8, charset: []const u8) !void { _ = 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 (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], } }); } /// Fits a memory expansion card, 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 { _ = 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 (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], } }); } /// Fits the Super Serial Card by giving it the two kilobytes of /// its firmware. pub fn loadSerialROM(self: *Self, image: []const u8) !void { _ = 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 (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], } }); } /// 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 { try self.slots.fit(slot, .{ .block = .{} }); } pub fn setSerialInterrupts(self: *Self, connected: bool) void { const slot = self.slots.first(.serial) orelse return; self.slots.cards[slot].serial.interrupts = connected; self.updateInterrupt(); } pub fn serialReceive(self: *Self, byte: u8) bool { const acia = self.serialAcia() orelse return false; const room = acia.receive(byte); self.updateInterrupt(); return room; } pub fn serialSent(self: *const Self) []const u8 { const slot = self.slots.first(.serial) orelse return &.{}; return self.slots.cards[slot].serial.acia.sent(); } pub fn serialConsume(self: *Self, count: usize) void { const slot = self.slots.first(.serial) orelse return; self.slots.cards[slot].serial.acia.consume(count); } /// Whether anything is pulling the interrupt line, which on a /// II Plus can only be a card. /// /// Every slot is asked rather than three named cards, because /// any slot can now hold any of them 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. pub fn updateInterrupt(self: *Self) void { const cycles = self.getCPU().clock.cycles; 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) { self.getCPU().irq = true; return; } } self.getCPU().irq = false; } /// One byte in or out of the machine's memory on a card's /// behalf, without the processor spending a cycle on it. 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 /// card if there is not one, since a volume has to be in /// something. pub fn insertVolume(self: *Self, which: u1, volume: ?*blockdevice.Volume) void { 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. /// /// A II Plus has no MMU, so the slots always own their pages /// and both of the questions `claim` asks are answered yes. fn claimExpansion(self: *Self, address: u16) void { self.slots.claim(address, true, true); } /// Copies a program into RAM. Only reaches the first 48K, since that /// is all of it that is RAM. 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.ram[location..end], program); } /// Where the video scanner is looking this cycle, and the byte /// it fetched. /// /// The scanner reads a byte of RAM every cycle of every line, /// displayed or not, and that byte is the last thing to have /// been driven onto the data bus. Anything that does not drive /// the bus — an address with no RAM row behind it, a soft /// switch touched for its effect rather than read for an /// answer — leaves it there for the processor to find. /// /// The arithmetic is Sather's, and is set out at length beside /// `scannerAddress` in `apple2e.zig`: Table 5.1 for which /// scanner output drives which address line, the four-bit /// adder of p. 5-9 for the middle four, and Table 5.2 as the /// check on the result. The IIe did not change it — Sather /// says of the two books that where a feature works /// identically the text of both is identical — so the same /// code answers for both machines, less the switches this one /// does not have. fn scannerAddress(self: *Self) u16 { const into_frame = self.getCPU().clock.read() % cycles_per_frame; const line = into_frame / cycles_per_line; const cycle = into_frame % cycles_per_line; // H0-H5 read zero for the first two cycles of a line, so // the byte there is fetched twice. const h: u16 = if (cycle == 0) 0 else @intCast(cycle - 1); // $100-$1bf displayed, then $1c0-$1ff and $fa-$ff blanked. 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; const low: u16 = (h & 7) | (sum << 3) | (((v >> 3) & 7) << 7); 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; return if (scanning_hires) low | ((v & 7) << 10) | @as(u16, if (self.page2) 0x4000 else 0x2000) else low | @as(u16, if (self.page2) 0x800 else 0x400); } /// What an undriven data bus is carrying. /// Whether this machine has annunciator pins at all, which a /// II and a II Plus both do. The IIe's model carries the same /// constant and answers `false` for a IIc; see `apple2e.zig`. pub const has_annunciators = true; /// What one of the four annunciator pins is doing. /// /// The same shape as the IIe's, so that a front end can ask /// either machine without knowing which it has -- but a plain /// one, because a II Plus has no double resolution for the /// third of them to be doing at the same time. pub fn annunciator(self: *const Self, which: u2) bool { return self.annunciators[which]; } fn floatingBus(self: *Self) u8 { return self.ram[self.scannerAddress()]; } /// Which physical byte an address is currently reading from, or null /// when it is a soft switch and so not memory at all. fn readTarget(self: *Self, address: u16) ?*const u8 { return switch (address) { 0x0000...0xbfff => if (self.hasRam(address)) &self.ram[address] else null, 0xc000...0xc0ff => null, // The slot pages, and the kilobyte above them the // slots share. A II Plus has no MMU, so there is // nothing that can take these away from the cards: what // is here is whatever is plugged in, and the machine's // own ROM where nothing is. 0xc100...0xcfff => 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.rom[address - 0xc000], }, 0xd000...0xdfff => if (self.card_switches.read_ram) &self.bank[@intFromBool(self.card_switches.bank2)][address - 0xd000] else &self.rom[address - 0xc000], 0xe000...0xffff => if (self.card_switches.read_ram) &self.high[address - 0xe000] else &self.rom[address - 0xc000], }; } /// Which physical byte an address is currently writing to, or null /// when the write goes nowhere: a soft switch, or ROM, or a language /// card that is write protected. fn writeTarget(self: *Self, address: u16) ?*u8 { return switch (address) { 0x0000...0xbfff => if (self.hasRam(address)) &self.ram[address] else null, // Nothing between $c000 and $cfff 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 => self.slots.windowTarget(address), 0xd000...0xdfff => if (self.card_switches.write_ram) &self.bank[@intFromBool(self.card_switches.bank2)][address - 0xd000] else null, 0xe000...0xffff => if (self.card_switches.write_ram) &self.high[address - 0xe000] else null, }; } /// Reads a byte with the processor not involved: no cycle is spent, /// nothing joins the bus log, and no soft switch is disturbed. What a /// debugger wants, and the only safe way to look at $c0xx. pub fn peek(self: *Self, address: u16) u8 { const target = self.readTarget(address) orelse // A row with no RAM behind it, which reads as $ff. // Looking without the processor should see what the // processor would. return if (address < 0xc000) 0xff else 0; return target.*; } /// Writes a byte with the processor not involved, as `peek`. A write /// that would land on a soft switch or on write protected memory does /// nothing rather than throwing the switch. pub fn poke(self: *Self, address: u16, value: u8) void { const target = self.writeTarget(address) orelse return; target.* = value; } /// Acts on a touch of $c000 to $c0ff. Whether it was a read or a write /// matters: the language card counts consecutive reads, and most of /// the display switches are meant to be written. fn softSwitch(self: *Self, address: u16, is_write: bool, value: u8) u8 { // 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. if (address >= 0xc100 and self.slots.page(address) == .registers) { const slot: u3 = @truncate(address >> 8); 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; } switch (address & 0xff) { // The keyboard, and the location that clears its strobe. // Reading or writing the second does the clearing, and it does // not matter what is written. 0x00...0x0f => return self.keyboardByte(), 0x10...0x1f => { const pressed = self.anyKeyDown(); self.strobe = false; self.key_down = false; return pressed; }, // The cassette output: one bit, flipped by touching // it, which is the speaker over again. 0x20...0x2f => { self.cassette_out = !self.cassette_out; self.cassette_log.record(self.getCPU().clock.cycles); }, // The cassette input, whose top bit is which side of // zero the signal is on. 0x60 => return if (self.cassetteInput()) 0x80 else 0, // The three buttons on the game connector. Only the top // bit means anything. 0x61...0x63 => return if (self.buttons[@as(u8, @truncate(address)) - 0x61]) 0x80 else 0, // The paddles, which answer with the top bit set until // their timer runs down. 0x64...0x67 => { const elapsed = self.getCPU().clock.cycles -| self.paddle_started; return if (elapsed < self.paddleRuns(@as(u8, @truncate(address)) - 0x64)) 0x80 else 0; }, // Starting the paddle timers. 0x70...0x7f => self.paddle_started = self.getCPU().clock.cycles, // Display mode. Each pair is off then on. // 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 four annunciators, which are one-bit outputs on // the game connector and nothing else: "8 addresses // (C058-C05F) are assigned to selectively 'SET' or // 'CLEAR' these four 'ANNUNCIATOR' outputs. Envisioned // to control indicator lights" (Apple Computer, Inc., // 1978, p. 108). The even address of each pair clears // and the odd one sets, and a read does it as readily // as a write, because what drives the pin is the // address decode and the data bus is not involved at // all (Sather, 1983). 0x58...0x5f => { const low: u8 = @truncate(address); self.annunciators[@intCast((low - 0x58) >> 1)] = low & 1 == 1; }, // The bank switches. Bit 3 chooses which $d000 bank answers, // bit 0 asks for writing, and reading is enabled when bits 0 // and 1 agree. Table 4-6 lists the eight useful addresses; the // other eight repeat them. 0x80...0x8f => self.card_switches.switched(@truncate(address), is_write), // And 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. // // Nothing driving the bus reads as the floating bus, // the same as any other address here that answers // nothing. 0x90...0xff => return self.slots.access(self, @truncate(address), is_write, value) orelse self.floatingBus(), else => {}, } // Anything else on this page reads back as whatever the video // circuitry last put on the bus, which is the byte the // scanner fetched this cycle. return self.floatingBus(); } /// Reads memory, spending a cycle per byte and logging each one. A /// word is read low byte first. An access to $c0xx works the switch it /// names, which is the whole reason a discarded read has to be a real /// read. 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.claimExpansion(address); const value = if (self.readTarget(address)) |target| target.* else if (address < 0xc000) // A row with no RAM in it reads as $ff, and // not as the video scanner's byte: those are // two different mechanisms and only one of // them is the floating bus. // // RAM data reaches the processor through a // latch. For an address in RAM space the RAM // SELECT' line goes low and that latch is // gated onto the bus whatever is in it — and // with no row populated, "the RAM data output // is floating when RAS' rises, because CAS' // does not fall at any of the three rows of // Apple RAM... the floating RAM output is // interpreted as $FF by the latch" (Sather, // 1983, p. 5-25). // // The $c0xx side of the same page is where the // video byte comes through, because there RAM // SELECT' stays high, the bus itself floats, // and what it is holding is the scanner's last // fetch. See `floatingBus`. // // misterblack1's dead test ROM is what settled // this. It counts RAM by writing 0 to the top // of each 4K block and reading it back, on the // stated assumption that "reads from empty // locations return $FF regardless of what was // written there" — and with the video byte // answering instead it found 48K in a 4K // machine. 0xff 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. The /// cycle is spent whether or not anything is listening: the processor /// drives the bus and ROM simply declines to latch it. 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.claimExpansion(address); self.bus.record(address, value, .write); if (self.writeTarget(address)) |target| { target.* = value; } else if (address & 0xff00 == 0xc000 or self.slots.page(address) == .registers) { // A Mockingboard's page is the other way in, // and a player writes to it far more than it // reads. _ = 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, AppleIIPlus(.{})); fn machine() !TestCPU { var cpu: TestCPU = undefined; try cpu.init(null, null); return cpu; } test "a II Plus's four annunciators are set by the odd address and cleared by the even" { var cpu: TestCPU = undefined; try cpu.init(null, null); // "8 addresses (C058-C05F) are assigned to selectively 'SET' or 'CLEAR' // these four 'ANNUNCIATOR' outputs" (Apple Computer, Inc., 1978, p. 108), // and the manual's own table has the even address of each pair clearing // and the odd one setting. for (0..4) |which| try testing.expect(!cpu.memory.annunciator(@intCast(which))); 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 works them too, and the byte written is not looked at: the IOU // decodes the address and the data bus is not involved. cpu.memory.write(u8, 0xc05f, 0x00); try testing.expect(cpu.memory.annunciator(3)); cpu.memory.write(u8, 0xc05e, 0xff); try testing.expect(!cpu.memory.annunciator(3)); // Nothing on the machine can read one back. This is the pin as a lamp on // the game connector would see it, which is the only thing there is to // see: a II Plus has no double resolution for the third of them to be // asking for at the same time, so all four are plain outputs here. try testing.expect(!cpu.memory.annunciator(0)); } test "reads above $d000 come from ROM until the card is switched in" { var cpu = try machine(); // A ROM that fills $c000 to $ffff, so every ROM address is identifiable. var image: [rom_size]u8 = @splat(0xaa); try cpu.memory.loadROMAtEnd(&image); try testing.expectEqual(@as(u8, 0xaa), cpu.memory.read(u8, 0xd000)); try testing.expectEqual(@as(u8, 0xaa), cpu.memory.read(u8, 0xffff)); // $c080 reads the card, second bank, write protected. _ = cpu.memory.read(u8, 0xc080); 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); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xd000)); } test "write enabling the card takes two consecutive reads" { var cpu = try machine(); _ = cpu.memory.read(u8, 0xc080); // read RAM, write protected try testing.expect(!cpu.memory.card_switches.write_ram); // One read of an odd switch is not enough. _ = cpu.memory.read(u8, 0xc083); try testing.expect(!cpu.memory.card_switches.write_ram); // The second one does it. _ = cpu.memory.read(u8, 0xc083); try testing.expect(cpu.memory.card_switches.write_ram); cpu.memory.write(u8, 0xd000, 0x42); try testing.expectEqual(@as(u8, 0x42), cpu.memory.read(u8, 0xd000)); } test "a write to a bank switch does not count towards the pair" { var cpu = try machine(); // Power-on leaves the card write enabled, so protect it first or there is // nothing for the pair to earn. _ = cpu.memory.read(u8, 0xc082); try testing.expect(!cpu.memory.card_switches.write_ram); _ = cpu.memory.read(u8, 0xc083); cpu.memory.write(u8, 0xc083, 0); // breaks the run _ = cpu.memory.read(u8, 0xc083); try testing.expect(!cpu.memory.card_switches.write_ram); } test "the two $d000 banks are separate memory" { var cpu = try machine(); // Bank 2, readable and writable. _ = cpu.memory.read(u8, 0xc083); _ = cpu.memory.read(u8, 0xc083); cpu.memory.write(u8, 0xd000, 0x22); // Bank 1, likewise. _ = cpu.memory.read(u8, 0xc08b); _ = cpu.memory.read(u8, 0xc08b); try testing.expect(!cpu.memory.card_switches.bank2); cpu.memory.write(u8, 0xd000, 0x11); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0xd000)); // And bank 2 still has what it had. _ = cpu.memory.read(u8, 0xc083); _ = cpu.memory.read(u8, 0xc083); try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(u8, 0xd000)); // $e000 is one block, so it is the same either way. _ = cpu.memory.read(u8, 0xc08b); _ = cpu.memory.read(u8, 0xc08b); cpu.memory.write(u8, 0xe000, 0xee); _ = cpu.memory.read(u8, 0xc083); _ = cpu.memory.read(u8, 0xc083); try testing.expectEqual(@as(u8, 0xee), cpu.memory.read(u8, 0xe000)); } test "reading and writing the card are independent" { var cpu = try machine(); var image: [rom_size]u8 = @splat(0xaa); try cpu.memory.loadROMAtEnd(&image); // $c081 twice: read the ROM, write the card. _ = cpu.memory.read(u8, 0xc081); _ = cpu.memory.read(u8, 0xc081); try testing.expect(!cpu.memory.card_switches.read_ram); try testing.expect(cpu.memory.card_switches.write_ram); cpu.memory.write(u8, 0xd000, 0x5a); // Still reading the ROM, so the write is not visible yet. try testing.expectEqual(@as(u8, 0xaa), cpu.memory.read(u8, 0xd000)); // Switch reading to the card and there it is. _ = cpu.memory.read(u8, 0xc080); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(u8, 0xd000)); } test "a write to write-protected space is dropped but still costs a cycle" { var cpu = try machine(); _ = cpu.memory.read(u8, 0xc080); // read card, write protected const before = cpu.clock.cycles; cpu.memory.write(u8, 0xd000, 0xff); try testing.expectEqual(before + 1, cpu.clock.cycles); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xd000)); } const TestAppleII = @import("../cpu8.zig").CPU(@import("../clock.zig").FakeClock, AppleII(.{})); test "an Apple II takes the RAM configurations Apple sold, and a II Plus the later three" { // The Reference Manual's five standard sets of memory select blocks // (Apple Computer, Inc., 1978, p. 134): 4K, 8K, 12K; 16K, 20K, 24K; 32K, // 36K; 48K. A II Plus had 16K plugs soldered in. var ii: TestAppleII = undefined; try ii.init(null, null); for ([_]usize{ 4, 8, 12, 16, 20, 24, 32, 36, 48 }) |k| { try ii.memory.fitRam(k * 1024, .contiguous); try testing.expectEqual(k * 1024, ii.memory.ramFitted()); } for ([_]usize{ 28, 40, 44, 52, 64 }) |k| { try testing.expectError(error.NotAConfiguration, ii.memory.fitRam(k * 1024, .contiguous)); } var plus = try machine(); for ([_]usize{ 16, 32, 48 }) |k| try plus.memory.fitRam(k * 1024, .contiguous); for ([_]usize{ 4, 8, 12, 20, 24, 36 }) |k| { try testing.expectError(error.NotAConfiguration, plus.memory.fitRam(k * 1024, .contiguous)); } } test "the Hi-Res layout puts two rows under the picture and only fits twelve kilobytes" { // "Type 2 is non-contiguous and allows 8K dedicated to HIRES screen // memory with approximately 2K of user BASIC space" (Apple Computer, // Inc., 1978, p. 134): 4K at $0000, and $2000 to $3fff. var ii: TestAppleII = undefined; try ii.init(null, null); try ii.memory.fitRam(12 * 1024, .hires); try testing.expect(ii.memory.hasRam(0x0fff)); try testing.expect(!ii.memory.hasRam(0x1000)); try testing.expect(ii.memory.hasRam(0x2000)); try testing.expect(ii.memory.hasRam(0x3fff)); try testing.expect(!ii.memory.hasRam(0x4000)); try testing.expectError(error.NotAConfiguration, ii.memory.fitRam(16 * 1024, .hires)); } test "a row with no RAM in it takes no writes and reads as $ff" { // Which is what lets Integer BASIC find the top of memory by probing: a // write there goes nowhere and the read back does not agree with it. // // $ff rather than the video scanner's byte, and the difference is the // whole point. RAM reaches the processor through a latch, and for an // address in RAM space that latch is gated onto the bus whatever is in it; // with no row populated, "the floating RAM output is interpreted as $FF by // the latch" (Sather, 1983, p. 5-25). The video byte comes through at // $c0xx instead, where the bus itself is what floats. var ii: TestAppleII = undefined; try ii.init(null, null); try ii.memory.fitRam(16 * 1024, .contiguous); ii.memory.write(u8, 0x3fff, 0x5a); ii.memory.write(u8, 0x4000, 0x5a); try testing.expectEqual(@as(u8, 0x5a), ii.memory.read(u8, 0x3fff)); try testing.expectEqual(@as(u8, 0xff), ii.memory.read(u8, 0x4000)); try testing.expectEqual(@as(u8, 0xff), ii.memory.peek(0x4000)); // And it says $ff whatever is on the screen, which is what a program // counting RAM by writing and reading back depends on. ii.clock.cycles = 25; ii.memory.ram[ii.memory.scannerAddress()] = 0x33; ii.clock.cycles = 24; try testing.expectEqual(@as(u8, 0xff), ii.memory.read(u8, 0x4000)); } test "the colour burst is killed in TEXT mode from Revision 1, and never on Revision 0" { // Sather (1983, p. 8-5): the killer "eliminate[s] the COLOR BURST in TEXT // MODE", and "in MIXED mode, the four lines of text at the bottom of the // screen are still green and violet because the COLOR BURST is present". var ii: TestAppleII = undefined; try ii.init(null, null); try testing.expect(!ii.memory.colourBurst()); // text, as a reset leaves it _ = ii.memory.read(u8, 0xc050); // graphics try testing.expect(ii.memory.colourBurst()); _ = ii.memory.read(u8, 0xc053); // mixed: the text rows are coloured too try testing.expect(ii.memory.colourBurst()); _ = ii.memory.read(u8, 0xc051); // text again try testing.expect(!ii.memory.colourBurst()); ii.memory.revision = .zero; try testing.expect(ii.memory.colourBurst()); try testing.expect(!ii.memory.delaysHires()); ii.memory.revision = .later; try testing.expect(ii.memory.delaysHires()); // A II Plus is a later board, whatever it is told. var plus = try machine(); try testing.expect(!plus.memory.colourBurst()); try testing.expect(plus.memory.delaysHires()); } test "display switches are remembered" { var cpu = try machine(); try testing.expect(cpu.memory.text); _ = cpu.memory.read(u8, 0xc050); try testing.expect(!cpu.memory.text); cpu.memory.write(u8, 0xc057, 0); try testing.expect(cpu.memory.hires); cpu.memory.write(u8, 0xc054, 0); try testing.expect(!cpu.memory.page2); } test "peek does not disturb a soft switch" { var cpu = try machine(); const before = cpu.memory.card_switches.read_ram; _ = cpu.memory.peek(0xc080); _ = cpu.memory.peek(0xc080); try testing.expectEqual(before, cpu.memory.card_switches.read_ram); } 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); try testing.expectEqual(@as(u8, 0x4c), cpu.memory.peek(0xc100)); 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, AppleIIPlus(.{ .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, AppleIIPlus(.{}), ); 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 II Plus keyboard has no lowercase" { var cpu = try machine(); cpu.memory.pressKey('a'); try testing.expectEqual(@as(u8, 0xc1), cpu.memory.read(u8, 0xc000)); cpu.memory.pressKey('z'); try testing.expectEqual(@as(u8, 0xda), cpu.memory.read(u8, 0xc000)); // Everything else goes through untouched. cpu.memory.pressKey('1'); try testing.expectEqual(@as(u8, 0xb1), cpu.memory.read(u8, 0xc000)); } test "a II Plus clears the strobe across the whole range" { var cpu = try machine(); // Unlike a IIe, there is nothing else in $c010-$c01f to protect: the address // is decoded no more finely than this, so any of the sixteen clears it. for (0xc010..0xc020) |address| { cpu.memory.pressKey('K'); try testing.expect(cpu.memory.strobe); _ = cpu.memory.read(u8, @intCast(address)); try testing.expect(!cpu.memory.strobe); } } test "asking for a key and finding none is counted" { var cpu = try machine(); for (0..10) |_| _ = cpu.memory.read(u8, 0xc000); try testing.expectEqual(@as(u16, 10), cpu.memory.empty_polls); cpu.memory.pressKey('K'); try testing.expectEqual(@as(u16, 0), cpu.memory.empty_polls); } test "a II Plus has nothing of its own in the slot pages" { var cpu = try machine(); var card: [0x100]u8 = @splat(0); card[0] = 0xa2; try cpu.memory.loadCardROM(&card); // No INTCXROM to argue with: the card simply answers there. try testing.expectEqual(@as(u8, 0xa2), cpu.memory.read(u8, 0xc600)); 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); _ = cpu.memory.read(u8, 0xc0e9); try testing.expect(cpu.memory.drives().motor); // 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); } test "a II Plus reads back forty columns and knows only three modes" { var cpu = try machine(); cpu.memory.ram[0x0400] = 0xc8; // H cpu.memory.ram[0x0401] = 0xc9; // I var buffer: [screen.rows * 40]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try cpu.memory.writeText(&writer); const text = writer.buffered(); try testing.expectEqual(@as(usize, 24 * 40), text.len); try testing.expectEqualStrings("HI", text[0..2]); try testing.expectEqual(screen.Mode.text, cpu.memory.mode()); _ = cpu.memory.read(u8, 0xc050); try testing.expectEqual(screen.Mode.low_resolution, cpu.memory.mode()); _ = cpu.memory.read(u8, 0xc057); try testing.expectEqual(screen.Mode.high_resolution, cpu.memory.mode()); } 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)); } } /// 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)); } 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, AppleIIPlus(.{ .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 "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. _ = cpu.memory.read(u8, 0xc300); try testing.expectEqual(@as(?u3, 3), 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); // 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 Videoterm answers in slot 3, and its firmware and screen share the window" { var cpu = try machine(); var firmware: [videx.firmware_size]u8 = @splat(0); var charset: [videx.charset_size]u8 = @splat(0); firmware[0x000] = 0xad; // the first byte of the expansion ROM firmware[videx.slot_page_at] = 0x38; // and of the $Cn00 page, which is its top quarter firmware[videx.slot_page_at + 0xff] = 0x5a; try cpu.memory.loadVidexROM(&firmware, &charset, null); // The top quarter of the kilobyte is what answers in the slot, which is // where the machine looks for a Pascal 1.1 signature. try testing.expectEqual(@as(u8, 0x38), cpu.memory.read(u8, 0xc300)); try testing.expectEqual(@as(u8, 0x5a), cpu.memory.read(u8, 0xc3ff)); // Touching the page hands this card the shared window, and the firmware // is what the first kilobyte of it answers with. try testing.expectEqual(@as(?u3, 3), cpu.memory.slots.expansion); try testing.expectEqual(@as(u8, 0xad), cpu.memory.read(u8, 0xc800)); // $cc00 is not firmware: it is five hundred and twelve bytes of the card's // own screen memory, and writing there is how a character gets on screen. cpu.memory.write(u8, 0xcc00, 'H'); cpu.memory.write(u8, 0xcc01, 'I'); try testing.expectEqual(@as(u8, 'H'), cpu.memory.read(u8, 0xcc00)); try testing.expectEqual(@as(u8, 'H'), cpu.memory.videxCard().?.ram[0]); try testing.expectEqual(@as(u8, 'I'), cpu.memory.videxCard().?.ram[1]); // The other three quarters need a page selected first, and the address // that selects it is one of the card's sixteen. _ = cpu.memory.read(u8, 0xc0b8); // page two try testing.expectEqual(@as(u2, 2), cpu.memory.videxCard().?.page); cpu.memory.write(u8, 0xcc00, '!'); try testing.expectEqual(@as(u8, '!'), cpu.memory.videxCard().?.ram[1024]); // And what page zero held is still there, untouched. try testing.expectEqual(@as(u8, 'H'), cpu.memory.videxCard().?.ram[0]); // Another slot taking the window takes the screen memory with it, since // both are the one kilobyte-and-a-half a card gets. _ = cpu.memory.read(u8, 0xc200); try testing.expect(cpu.memory.read(u8, 0xc800) != 0xad); } test "the Videoterm's sixteen addresses are a 6845 and a page select at once" { var cpu = try machine(); var firmware: [videx.firmware_size]u8 = @splat(0); var charset: [videx.charset_size]u8 = @splat(0); try cpu.memory.loadVidexROM(&firmware, &charset, null); // What the firmware does on the way up: a register number to $c0b0 and // its value to $c0b1, sixteen times over. cpu.memory.write(u8, 0xc0b0, 1); // R1, the columns displayed cpu.memory.write(u8, 0xc0b1, 80); try testing.expectEqual(@as(u8, 80), cpu.memory.videxCard().?.crtc.register[1]); // R1 is write-only on the part, so asking gets nothing back rather than // the eighty that was written. try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc0b1)); // The cursor registers do read back, which is the difference that matters. cpu.memory.write(u8, 0xc0b0, 15); cpu.memory.write(u8, 0xc0b1, 0x25); try testing.expectEqual(@as(u8, 0x25), cpu.memory.read(u8, 0xc0b1)); // And every one of those accesses moved the window, because the same two // bits mean the page whatever else the address was for. try testing.expectEqual(@as(u2, 0), cpu.memory.videxCard().?.page); _ = cpu.memory.read(u8, 0xc0bc); try testing.expectEqual(@as(u2, 3), cpu.memory.videxCard().?.page); } test "an UltraTerm answers in the same slot, and takes it from a Videoterm" { var cpu = try machine(); var vfw: [videx.firmware_size]u8 = @splat(0); var vcs: [videx.charset_size]u8 = @splat(0); var ufw: [ultraterm.firmware_size]u8 = @splat(0); var ucs: [ultraterm.charset_size]u8 = @splat(0); // The slot page for slot 3, which is the fourth of the firmware's seven. ufw[ultraterm.slotPageAt(3)] = 0x2c; ufw[ultraterm.slotPageAt(3) + 0xff] = 0x99; // And the code, two kilobytes of it above the slot pages. ufw[ultraterm.code_at] = 0xad; // A slot holds one card. Fitting either takes the other out. try cpu.memory.loadVidexROM(&vfw, &vcs, null); try testing.expect(cpu.memory.videxCard() != null); try cpu.memory.loadUltraTermROM(&ufw, &ucs); try testing.expect(cpu.memory.ultraTermCard() != null); try testing.expect(cpu.memory.videxCard() == null); // The page for this slot is what answers, not the first of the seven. try testing.expectEqual(@as(u8, 0x2c), cpu.memory.read(u8, 0xc300)); try testing.expectEqual(@as(u8, 0x99), cpu.memory.read(u8, 0xc3ff)); try testing.expectEqual(@as(?u3, 3), cpu.memory.slots.expansion); try testing.expectEqual(@as(u8, 0xad), cpu.memory.read(u8, 0xc800)); // $cc00 is the screen memory, and a write always reaches it. ufw[ultraterm.code_at + (0xcc00 - 0xc800)] = 0x5b; try cpu.memory.loadUltraTermROM(&ufw, &ucs); _ = cpu.memory.read(u8, 0xc300); cpu.memory.write(u8, 0xcc00, 'U'); try testing.expectEqual(@as(u8, 'U'), cpu.memory.ultraTermCard().?.ram[0]); try testing.expectEqual(@as(u8, 'U'), cpu.memory.read(u8, 0xcc00)); // The bank bit overlays the second half of the firmware there, and it // changes what a *read* gives back and nothing else: the write below still // reaches the screen with the ROM sitting over it, which is exactly what // the card's own firmware does when it clears the screen. cpu.memory.write(u8, 0xc0b2, ultraterm.mode_bank); try testing.expectEqual(@as(u8, 0x5b), cpu.memory.read(u8, 0xcc00)); cpu.memory.write(u8, 0xcc00, 'V'); try testing.expectEqual(@as(u8, 'V'), cpu.memory.ultraTermCard().?.ram[0]); try testing.expectEqual(@as(u8, 0x5b), cpu.memory.read(u8, 0xcc00)); // And the pages the mode port reaches that blocks cannot. cpu.memory.write(u8, 0xc0b2, ultraterm.mode_bank | ultraterm.mode_paged | 0x0f); cpu.memory.write(u8, 0xcc00, 'Z'); try testing.expectEqual(@as(u8, 'Z'), cpu.memory.ultraTermCard().?.ram[0x0f00]); // A part that is the wrong size is not this card's either. try testing.expectError(error.WrongSize, cpu.memory.loadUltraTermROM(ufw[0..16], &ucs)); try testing.expectError(error.WrongSize, cpu.memory.loadUltraTermROM(&ufw, ucs[0..16])); } test "a machine with no eighty column card has ROM in slot 3" { var cpu = try machine(); try testing.expect(cpu.memory.videxCard() == null); // The slot answers from the machine's own ROM, and the window is nobody's. try testing.expectEqual(cpu.memory.rom[0x300], cpu.memory.read(u8, 0xc300)); cpu.memory.write(u8, 0xcc00, 'X'); try testing.expect(cpu.memory.read(u8, 0xcc00) != 'X'); // And a part that is the wrong size is not one of this card's. var firmware: [videx.firmware_size]u8 = @splat(0); var charset: [videx.charset_size]u8 = @splat(0); try testing.expectError(error.WrongSize, cpu.memory.loadVidexROM(firmware[0..16], &charset, null)); try testing.expectError(error.WrongSize, cpu.memory.loadVidexROM(&firmware, charset[0..16], null)); try testing.expectError(error.WrongSize, cpu.memory.loadVidexROM(&firmware, &charset, charset[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)); } test "a Mockingboard in a II Plus can be reached at all" { // It could not be, and had not been since the card was added. A II Plus's // slot pages answered from the machine's own ROM whenever no card had a // page there, and a Mockingboard has no page: its two 6522s *are* the // page, so the read has to fall through to the switches. It never did, // because `readTarget` handed back a pointer into the ROM and a read that // has a pointer never asks anything else. And a write never got there // either, because `write` only falls through for $c0xx. // // Both halves are the same bug seen from two directions, and the IIe has // always had both right. `main.zig` will fit one of these on a II Plus // perfectly happily, so what an owner got was a silent card. var cpu = try machine(); cpu.memory.fitMockingboard(4, false); // The same player the IIe's test runs: the ports set up, then a register // number on port A and the orders on port B, twice over. try cpu.memory.loadProgram(0x0300, &[_]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 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 0x02, // JAM }); 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)); // And read back, which is the other direction: pointing the chip at a // register and turning port A round puts what is there on its pins. try cpu.memory.loadProgram(0x0300, &[_]u8{ 0xa9, 0x00, 0x8d, 0x01, 0xc4, // LDA #$00 : STA $c401 register nought 0xa9, 0x07, 0x8d, 0x00, 0xc4, // LDA #$07 : STA $c400 latch it 0xa9, 0x00, 0x8d, 0x03, 0xc4, // LDA #$00 : STA $c403 port A all inputs 0xa9, 0x05, 0x8d, 0x00, 0xc4, // LDA #$05 : STA $c400 read 0xad, 0x01, 0xc4, // LDA $c401 and take it 0x02, // JAM }); cpu.program_counter.value = 0x0300; ran = 0; while (ran < 4000) : (ran += 1) cpu.executeInstruction() catch break; try testing.expectEqual(@as(u8, 0xfe), cpu.registers.get(.A)); } test "two Disk II controllers, in slots nobody has put one in before" { // The point of the whole exercise, on a whole machine rather than on a // bare `Slots`: two of a kind, in slots chosen rather than assumed, each // answering in its own page and at its own sixteen switches. var cpu = try machine(); var one: [card_rom_size]u8 = @splat(0); var two: [card_rom_size]u8 = @splat(0); one[0] = 0x11; two[0] = 0x22; try cpu.memory.fitDisk(4, &one); try cpu.memory.fitDisk(5, &two); // Each page is its own card's. try testing.expectEqual(@as(u8, 0x11), cpu.memory.peek(0xc400)); try testing.expectEqual(@as(u8, 0x22), cpu.memory.peek(0xc500)); // And slot 6, where a controller has always gone, has nothing in it. try testing.expectEqual(cpu.memory.rom[0x600], cpu.memory.peek(0xc600)); // The motors are separate: $c0c9 is slot 4's and $c0d9 slot 5's. _ = cpu.memory.read(u8, 0xc0c9); try testing.expect(cpu.memory.slots.cards[4].disk.drives.motor); try testing.expect(!cpu.memory.slots.cards[5].disk.drives.motor); _ = cpu.memory.read(u8, 0xc0d9); try testing.expect(cpu.memory.slots.cards[5].disk.drives.motor); // A third in a slot that is taken is refused rather than replacing what is // there. It used to be an `else if` that quietly decided for you. try testing.expectError(error.SlotTaken, cpu.memory.fitDisk(5, &one)); } test "a card answers nowhere but its own slot" { // A clock card in slot 2, which is where a serial card usually goes and // where nothing has ever looked for a clock. ProDOS finds one by scanning // every slot for the signature, so this is a machine it would still find. var cpu = try machine(); var card: clockcard.Card = .{ .fitted = true }; card.set(.fromEpoch(0), 0); try cpu.memory.slots.fit(2, .{ .clock = card }); try testing.expectEqual(clockcard.signature[0], cpu.memory.peek(0xc200)); // And slot 5, which is where it used to be soldered, is the machine's own // ROM again. try testing.expectEqual(cpu.memory.rom[0x500], cpu.memory.peek(0xc500)); }