Something went wrong. Try again.
A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! The seven expansion slots, and what is in them.//!//! An Apple II's slots are most of what the machine is: you put the cards you//! own where you want them, and software finds them by looking. This is that,//! as one thing rather than as a constant per card per memory model — which is//! what it used to be, and which meant a Mockingboard could only ever be in//! slot 4, a machine could never have two of anything, and the II Plus's copy//! of the apparatus could quietly disagree with the IIe's.//!//! What a slot answers is decided in three places, and they are three//! different questions://!//! - **`$Cn00-$CnFF`**, one page each. `page` answers it.//! - **`$C800-$CFFF`**, one kilobyte shared between all seven, held by//! whichever card's page was touched last. `page` answers that too, through//! `window`.//! - **`$C09n-$C0Fn`**, sixteen device select addresses each. `access` answers//! it. `$C080-$C08F` is *not* among them: slot 0 is not a slot and those//! sixteen are the language card's.//!//! Whether it is the slots answering at all is not asked here. On a machine//! with an MMU the motherboard can take the pages back — see `slotsAnswerAt`//! in `memory8/apple2e.zig` — and that is the machine's business, decided//! before any of this is reached.//!//! ## What a card needs from the machine//!//! Some of these want more than their own state, and take the machine as an//! `anytype` so that it monomorphises and inlines: this is the memory path.//! What is asked of it, in one list, the way `blockdevice.run` documents its//! own two://!//! - `getCPU().clock.cycles` — the Disk II, the clock card, the ACIA.//! - `updateInterrupt()` — the mouse and the ACIA, either of which can start//! or stop pulling the line.//! - `peek(at)` and `poke(at, byte)` — the mouse's screen holes.//! - `blockGet(at)` and `blockPut(at, byte)` — the block device and the//! Transporter, which move whole blocks in and out of the machine's memory.
const std = @import("std");
const blockdevice = @import("blockdevice.zig");const clockcard = @import("clockcard.zig");const cs8900 = @import("cs8900.zig");const disk2 = @import("disk2.zig");const mc6840 = @import("mc6840.zig");const mc6850 = @import("mc6850.zig");const mockingboard = @import("mockingboard.zig");const mouse = @import("mouse.zig");const console = @import("console.zig");const ncr5380 = @import("ncr5380.zig");const omninet = @import("omninet.zig");const parallel = @import("parallel.zig");const phasor = @import("phasor.zig");const ramfactor = @import("ramfactor.zig");const scsi_bus = @import("scsi.zig");const serial = @import("serial.zig");const soundspeech = @import("soundspeech.zig");const ultraterm = @import("ultraterm.zig");const videx = @import("videx.zig");const w5100 = @import("w5100.zig");
/// Where the shared kilobyte begins, and the two boundaries inside it that an/// eighty-column card's window sits between. These are absolute addresses and/// have nothing to do with which slot the card is in: the window is one/// kilobyte at one place, and a card only reaches it by holding it.pub const window_from = 0xc800;pub const screen_from = 0xcc00;pub const screen_to = 0xce00;
/// Which of the Super Serial Card's eight pages is its `$Cn00` page.const serial_slot_page = 0x700;
/// Where a SCSI card's half of the shared window stops being its RAM and/// starts being its ROM. Sixteen ROM banks are "mapped at $cc00", and the/// kilobyte below them is the card's own memory.const scsi_rom_from = 0xcc00;
/// What is in a slot.////// `.empty` is a state and not an absence: an empty slot answers nothing, and/// what the bus carries there is the machine's business rather than a card's.////// Each card holds its own state and *borrows* its firmware, where it has any./// The bytes belong to whoever read the file — this only points at them, and/// they have to outlive the machine. That saves carrying eight copies of an/// eight-kilobyte ROM around in every machine, and it is how `ramfactor.Card`/// has always taken the megabyte of RAM behind it.pub const Card = union(enum) { empty,
// Ours, and different in every slot. What a card of this sort has to do is // published, so none of Apple's code is needed to do it — but the card's // own addresses are assembled into its page, and which those are depends // on where it is. `firmwares` in each of these modules is that page for // all eight slots. parallel: parallel.Card, mouse: mouse.Card, clock: clockcard.Card, block: blockdevice.Card,
// A host console, for a program embedding the emulator: its own firmware // and the two device-select addresses its data port answers at, with a // host `std.Io.Writer` and `std.Io.Reader` on the other end. Not offered by // the interactive front ends, which own the terminal themselves. console: console.Card,
// The cards with no firmware at all. A Mockingboard's page *is* the two // 6522s, so it is the one whose page has to be an access rather than a // byte; a Passport MIDI interface has no page at all, only the sixteen // device-select addresses its 6840 and 6850 answer at. mockingboard: mockingboard.Card, phasor: phasor.Card, soundspeech: soundspeech.Card, passport: Passport, uthernet: Uthernet, cs8900: Cs8900,
// Somebody else's, and the same in every slot: each of these works out // where it is at run time from where its own code is executing, which is // what let one card be sold for seven slots. serial: Serial, disk: Disk, transporter: Transporter, videx: Videx, ramfactor: RamFactor, scsi: Scsi,
// Somebody else's, and carrying every slot's page at once: seven pages // that differ only in the addresses baked into each, and the slot picks. ultraterm: UltraTerm,
pub const Serial = struct { acia: serial.Acia = .{}, rom: *const [0x800]u8, /// Whether anything has read the status register, which is how a /// program says it is listening to this card. listening: bool = false, /// Whether the card's interrupt jumper is in. It normally is not: the /// chip comes up with its receiver interrupt enabled and no firmware /// puts a handler anywhere, so a card wired in pulls the line the /// moment a byte arrives and the machine goes to pieces. interrupts: bool = false, };
pub const Disk = struct { drives: disk2.Controller = .{}, rom: *const [0x100]u8, };
/// A Passport Designs MIDI interface: a 6840 timer and a 6850 ACIA on the /// slot bus, with no firmware of its own. The 6840 answers at the low eight /// device-select addresses and the 6850 at the next two; the last two set /// and clear the drum-sync output. (Bethke & Borowicz, 1985, §4.1.) pub const Passport = struct { ptm: mc6840.Ptm = .{}, acia: mc6850.Acia = .{}, /// Whether the status register has been read, which is how something /// feeding MIDI in knows the machine is listening — the same handshake /// the serial card uses. listening: bool = false, /// The drum-sync line, an analog output a program toggles — `$C0nE` /// raises it, `$C0nF` lowers it — to clock a drum machine that is not /// on MIDI. It is not part of the MIDI stream, and the manual leaves /// the two signals on the connector, START/STOP and CLOCK, for a /// program to make out of this one line as it sees fit: "drum /// synchronization is not automatic ... you will need to make provision /// for generating drum sync signals" (Bethke & Borowicz, 1985, §2.4). A /// terminal has no drum machine and there is no unambiguous way to /// write an analog click into a Standard MIDI File, so the write is /// acknowledged and the level kept — a consumer is not invented for it. drum_sync: bool = false,
/// Whether either chip is pulling the interrupt line. pub fn interrupting(self: *Passport, cycle: u64) bool { return self.ptm.interrupting(cycle) or self.acia.interrupting(cycle); } };
/// An Apple II SCSI Card: an NCR 5380, sixteen kilobytes of firmware in /// sixteen banks, and eight kilobytes of RAM in eight. /// /// The banking is the awkward part and it is the card's, not the chip's. /// The shared window is cut in half: `$c800-$cbff` is a kilobyte of the /// card's RAM and `$cc00-$cfff` is a kilobyte of its ROM, and which /// kilobyte of each is decided by one write-only register at `$c0na`. /// Bank 0 of the ROM is also shadowed at `$Cn00`, which is where a scan /// finds the card. /// /// **Bank 0 and bank 8 of the ROM are the same bank, almost.** They differ /// in their last four bytes and in nothing else, and that is a fault in /// the card rather than a feature: A13 of the ROM is not gated by IOSEL*, /// so which of the two answers at `$Cn00` depends on the last thing /// written to bit 3 of the bank register, and Apple's answer was to make /// both work. Modelling the bank bit rather than pinning bank 0 is what /// keeps that honest. pub const Scsi = struct { chip: ncr5380.Ncr5380 = .{}, /// The drives on the cable, one per identity the card is not using. /// /// Seven rather than one, because a SCSI bus is a bus: eight devices /// share it, the card is one of them, and the other seven are whatever /// the owner hung off the back. They live here rather than being /// pointed at from outside because a card and its chain are one thing /// as far as the machine is concerned -- the same arrangement as a /// Disk II controller and its two drives. /// /// An identity with no image in it is an empty place on the cable, not /// a drive with nothing in it, and `attached` is what tells them apart: /// nothing answers a selection there at all, which is how the card's /// firmware finds out what is on the bus. disks: [7]scsi_bus.Disk = @splat(.{}), attached: [7]bool = @splat(false), rom: *const [rom_size]u8, /// The card's own eight kilobytes, which the firmware uses for sector /// buffers and its own scratch. ram: [ram_size]u8 = @splat(0), /// The bank register at `$c0na`, write only. The low four bits are the /// ROM bank -- which is all this firmware ever writes, `and #$0f` in /// the bank-switch routine at `$cfcc` -- and the three above them are /// the RAM bank. That the RAM bank sits there is inferred from the /// shape rather than read from a manual: nothing in the firmware moves /// it, so nothing here can be checked against it. bank: u8 = 0, /// Which identity the card answers to on the bus, read back at /// `$c0n9`. Seven is the highest priority and is what a host takes. id: u3 = 7, /// Whether the firmware has turned pseudo-DMA on at `$c0nd`. pdma_enabled: bool = false,
pub const rom_size = 16 * 1024; pub const ram_size = 8 * 1024; /// A kilobyte of each is visible at a time. pub const window_bank = 1024;
/// Where in the sixteen kilobytes the visible ROM bank starts. pub fn romAt(self: *const Scsi, within: u16) usize { return (@as(usize, self.bank & 0x0f) * window_bank) + within; }
/// And where in the eight the visible RAM bank starts. pub fn ramAt(self: *const Scsi, within: u16) usize { return (@as(usize, (self.bank >> 4) & 0x07) * window_bank) + within; }
/// Puts every attached drive on the bus and takes the rest off. /// /// Called whenever what is on the cable changes, because the bus holds /// pointers into `disks` and those move with the card: a `Slots` is /// copied by value in places, and a pointer taken before the copy /// would point into the original. pub fn rewire(self: *Scsi) void { self.chip.bus.devices = @splat(null); for (&self.disks, 0..) |*disk, id| { if (self.attached[id]) self.chip.bus.devices[id] = disk; } }
/// The sixteen addresses a SCSI card decodes at its `$C0nX`: the NCR /// 5380's eight registers, then six of the card's own and two reserved. /// The names are the firmware disassembly's, which is the only place /// they are written down. pub fn access(self: *Scsi, offset: u4, is_write: bool, value: u8) ?u8 { return switch (offset) { // The NCR 5380 itself, where a read and a write are different // registers at four of the eight addresses. 0x0...0x7 => |which| blk: { const register: ncr5380.Register = @enumFromInt(@as(u3, @truncate(which))); if (is_write) { self.chip.write(register, value); break :blk 0; } break :blk self.chip.read(register); }, // Pseudo-DMA with the card supplying DACK. There is no DMA // controller on this card: the processor spends the cycles and // the card's decode does what a controller's handshake would, // which is the "pseudo DMA mode" the chip's manual describes // for exactly this case (NCR Corporation, 1986, §10.4, p. 25). 0x8 => self.chip.pseudoDma(if (is_write) value else null), // Which identity the card answers to, which on a real one is // set by a jumper block. 0x9 => @as(u8, 1) << self.id, // The bank register, write only. 0xa => blk: { if (is_write) self.bank = value; break :blk 0; }, // Resetting the chip, which is not the same as resetting the // bus: this is the RESET pin rather than the RST signal. 0xb => blk: { self.chip.reset(); break :blk 0; }, // Whether pseudo-DMA is enabled. Nothing here behaves // differently for it -- the handshake at $c0n8 does the same // work either way -- so it is kept and answered. 0xd => blk: { if (is_write) self.pdma_enabled = value & 0x80 != 0; break :blk if (self.pdma_enabled) 0x80 else 0; }, // DRQ, on bit 7, which is how the firmware waits for the chip // without going through the Bus and Status register. 0xe => if (self.chip.read(.bus_and_status) & ncr5380.bas_dma_request != 0) @as(u8, 0x80) else 0, 0xc, 0xf => null, }; } pub fn slotPageIndex(self: *const Scsi, within: u16) usize { return (@as(usize, self.bank & 0x08) * window_bank) + within; }
/// Hooks a drive up at one of the seven identities, given the image it /// holds. Nothing here owns that image. /// /// Six is where every Apple SCSI disk was jumpered and where this /// card's firmware looks first, which is why it is what `first` gives /// out before anything else. pub fn attach(self: *Scsi, id: u3, image: []u8, write_protected: bool) error{TakenByTheCard}!void { if (id == self.id) return error.TakenByTheCard; self.disks[id] = .{ .image = image, .write_protected = write_protected }; self.attached[id] = true; self.rewire(); }
/// And unhooks one, which is a device leaving the bus rather than a /// disk being taken out of a drive: there is no such thing as an empty /// SCSI drive as far as the bus is concerned. pub fn detach(self: *Scsi, id: u3) void { self.attached[id] = false; self.disks[id] = .{}; self.rewire(); }
/// The highest identity with nothing on it, which is where the next /// drive goes when nobody says. Counting down is the convention: six /// first, then five, and the card keeps seven. pub fn nextFree(self: *const Scsi) ?u3 { var id: u3 = 6; while (true) : (id -= 1) { if (id != self.id and !self.attached[id]) return id; if (id == 0) return null; } } };
pub const Transporter = struct { card: omninet.Card = .{}, rom: *const [0x100]u8, };
/// An a2RetroSystems Uthernet II: a WIZnet W5100 wired to four of the /// slot's device-select addresses, and no firmware at all. `$C0n0` is the /// chip's mode register, `$C0n1` and `$C0n2` the two bytes of the pointer /// into its internal memory, and `$C0n3` the data register that reads or /// writes the byte the pointer names. The whole card is the chip and the /// four ways in; the host end that gives its sockets somewhere to go lives /// in the session (`uthernet.zig`), not here. pub const Uthernet = struct { chip: w5100.W5100 = .{}, };
/// An a2RetroSystems Uthernet (the original): a Cirrus Logic CS8900A wired /// to the slot's sixteen device selects, and no firmware. Unlike the /// Uthernet II's W5100, the CS8900A is a raw Ethernet controller — the /// driver's own stack sits on top of it — so its host end is a length of /// virtual wire (`ethernet.zig`), not a set of sockets. pub const Cs8900 = struct { chip: cs8900.CS8900 = cs8900.CS8900.init(), };
pub const Videx = struct { card: videx.Card = .{ .fitted = true }, rom: *const [videx.firmware_size]u8, charset: *const [videx.charset_size]u8, /// A second character generator, for a card modified to take one. alternate: ?*const [videx.charset_size]u8 = null, };
pub const UltraTerm = struct { card: ultraterm.Card = .{ .fitted = true }, rom: *const [ultraterm.firmware_size]u8, charset: *const [ultraterm.charset_size]u8, };
pub const RamFactor = struct { card: ramfactor.Card, rom: *const [ramfactor.rom_size]u8, };
/// What to call it, for a message to somebody who is choosing one. pub fn name(self: Card) []const u8 { return switch (self) { .empty => "nothing", .parallel => "a parallel printer card", .console => "a host console card", .mouse => "a mouse card", .clock => "a clock card", .block => "a block device", .mockingboard => "a Mockingboard", .phasor => "a Phasor", .soundspeech => "a Sound/Speech Mockingboard", .passport => "a Passport MIDI interface", .uthernet => "an Uthernet II", .cs8900 => "an Uthernet", .serial => "a Super Serial Card", .disk => "a Disk II controller", .transporter => "a Corvus Transporter", .videx => "a Videx Videoterm", .ramfactor => "a RamFactor", .ultraterm => "a Videx UltraTerm", }; }};
/// What a slot says about an address in the pages that belong to it.pub const Answer = union(enum) { /// The card is driving the bus, with this byte. rom: *const u8, /// A card is there, but what is at this address is registers rather than /// memory. The access has to *be* an access, so the caller must go to /// `access` rather than reading a byte. Only a Mockingboard answers this /// way, and forgetting it is what kept one silent in a II Plus for as long /// as the card has been here. registers, /// Nothing in the slot answers. What the bus carries instead is the /// machine's business: its own ROM on a II Plus, a floating bus on a IIe. none,};
pub const Slots = struct { /// Indexed by slot number, so there are eight and the first is never a /// card: slot 0 is not a slot. cards: [8]Card = @splat(.empty),
/// Which slot's firmware is answering in the shared kilobyte, if any. /// /// A `u3` rather than the `u4` the address arithmetic hands over, because /// only `$c100-$c7ff` can claim it and that names 1 to 7. expansion: ?u3 = null,
/// What is in a slot, or null for a slot with nothing in it. Slot 0 is /// never a card and answers null too. pub fn at(self: *Slots, slot: u3) ?*Card { if (slot == 0) return null; if (self.cards[slot] == .empty) return null; return &self.cards[slot]; }
/// Puts a card in a slot, or says what is in the way. /// /// A slot holds one card. That used to be arranged by the order of a chain /// of `else if`s — a Mockingboard beat a mouse, a RamFactor beat a clock — /// which is not something a machine does. Two cards in one slot is a /// mistake somebody made, and this is where they are told. pub fn fit(self: *Slots, slot: u3, card: Card) error{ NotASlot, SlotTaken }!void { if (slot == 0) return error.NotASlot; if (self.cards[slot] != .empty) return error.SlotTaken; self.cards[slot] = card; }
/// Takes whatever is in a slot out, and hands it back. pub fn empty(self: *Slots, slot: u3) Card { const was = self.cards[slot]; self.cards[slot] = .empty; if (self.expansion == slot) self.expansion = null; return was; }
/// The lowest-numbered slot holding a card of this kind, which is what an /// unqualified switch on the command line means by "the disk controller". pub fn first(self: *const Slots, kind: std.meta.Tag(Card)) ?u3 { for (1..self.cards.len) |slot| { if (self.cards[slot] == kind) return @intCast(slot); } return null; }
/// How many cards of a kind are fitted. pub fn count(self: *const Slots, kind: std.meta.Tag(Card)) usize { var found: usize = 0; for (self.cards[1..]) |card| { if (card == kind) found += 1; } return found; }
/// The reset line reaches the cards, which is what stops a drive that was /// left turning and clears a Transporter's latch. pub fn reset(self: *Slots, cycles: u64) void { for (&self.cards) |*card| switch (card.*) { .disk => |*c| c.drives.reset(), .mockingboard => |*c| c.reset(cycles), .phasor => |*c| c.reset(cycles), .soundspeech => |*c| c.reset(cycles), .cs8900 => |*c| c.chip.reset(), .passport => |*c| { c.ptm.reset(); c.acia.reset(); }, .transporter => |*c| c.card.reset(), .ramfactor => |*c| c.card.reset(), .serial => |*c| c.acia.reset(), else => {}, }; }
/// What is at `$C100` to `$CFFF`. /// /// A pure function of the cards and the address, so it folds to a jump /// table on the tag. Whether the slots are what answers here at all is the /// machine's question and is asked before this. pub fn page(self: *Slots, address: u16) Answer { if (address >= window_from) return self.window(address); const slot: u3 = @truncate(address >> 8); const within: u8 = @truncate(address); return switch (self.cards[slot]) { .empty => .none, .mockingboard => .registers, .phasor => .registers, .soundspeech => .registers, // No firmware: the card lives entirely in its device-select // addresses, so its slot page reads as an undriven bus. .passport => .none, .uthernet => .none, .cs8900 => .none,
.parallel => .{ .rom = ¶llel.firmwares[slot][within] }, .console => .{ .rom = &console.firmwares[slot][within] }, .mouse => .{ .rom = &mouse.firmwares[slot][within] }, .clock => .{ .rom = &clockcard.firmwares[slot][within] }, // A card with no volume in it is a card with nothing to boot, and // the firmware is what a scan finds: an empty one must not claim // the slot. .block => |*c| if (c.fitted()) .{ .rom = &blockdevice.firmwares[slot][within] } else .none,
.serial => |*c| .{ .rom = &c.rom[serial_slot_page + @as(usize, within)] }, .disk => |*c| .{ .rom = &c.rom[within] }, .transporter => |*c| .{ .rom = &c.rom[within] }, .videx => |*c| .{ .rom = &c.rom[videx.slot_page_at + @as(usize, within)] }, // The bank bit and the twelve low address lines are the whole of // this card's decode, which is why its slot page and its window // are the same expression. .ramfactor => |*c| .{ .rom = &c.rom[ramfactor.romAt(c.card.bank, address)] },
// The slot page is ROM bank 0, except that A13 is not gated here, // so bit 3 of the bank register picks bank 0 or bank 8 -- which // Apple made almost identical for exactly that reason. .scsi => |*c| .{ .rom = &c.rom[c.slotPageIndex(within)] },
.ultraterm => |*c| .{ .rom = &c.rom[ultraterm.slotPageAt(slot) + @as(usize, within)] }, }; }
/// The shared kilobyte, which belongs to whoever claimed it last. fn window(self: *Slots, address: u16) Answer { const slot = self.expansion orelse return .none; return switch (self.cards[slot]) { .serial => |*c| .{ .rom = &c.rom[address - window_from] }, .ramfactor => |*c| .{ .rom = &c.rom[ramfactor.romAt(c.card.bank, address)] }, // The window is cut in half: a kilobyte of the card's RAM and // then a kilobyte of its ROM, each one bank of several. .scsi => |*c| if (address < scsi_rom_from) .{ .rom = &c.ram[c.ramAt(address - window_from)] } else .{ .rom = &c.rom[c.romAt(address - scsi_rom_from)] }, .videx => |*c| switch (address) { window_from...screen_from - 1 => .{ .rom = &c.rom[address - window_from] }, // The card's screen memory, five hundred and twelve bytes of // it at a time, which is what the window is for. screen_from...screen_to - 1 => .{ .rom = &c.card.ram[c.card.windowAt(@truncate(address - screen_from))], }, else => .none, }, .ultraterm => |*c| if (address >= screen_from and address < screen_to and c.card.windowReadsScreen()) .{ .rom = &c.card.ram[c.card.windowAt(@truncate(address - screen_from))] } else .{ .rom = &c.rom[ultraterm.code_at + (address - window_from)] }, else => .none, }; }
/// The one place in `$C100-$CFFF` a program writes to: an eighty-column /// card's window is its screen memory, and putting a character on that /// screen is a write to it. /// /// Null everywhere else, including where a card's firmware sits over the /// same window. A ROM gated onto the bus can only answer a read, and the /// RAM beside it still takes the write. pub fn windowTarget(self: *Slots, address: u16) ?*u8 { const slot = self.expansion orelse return null; // A SCSI card's window is half RAM, and that half is real memory the // firmware writes its sector buffers into -- so it takes writes across // the whole kilobyte rather than over an eighty-column card's screen. if (address >= window_from and address < scsi_rom_from) { if (self.cards[slot] == .scsi) { const card = &self.cards[slot].scsi; return &card.ram[card.ramAt(address - window_from)]; } } if (address < screen_from or address >= screen_to) return null; const offset: u9 = @truncate(address - screen_from); return switch (self.cards[slot]) { .videx => |*c| &c.card.ram[c.card.windowAt(offset)], .ultraterm => |*c| &c.card.ram[c.card.windowAt(offset)], else => null, }; }
/// A touch of one of the sixteen device select addresses a slot has, which /// are `$C080 + slot * 16` and up. /// /// Null when nothing in the slot drove the bus, which the machine turns /// into whatever an undriven bus reads as. `low` is the low byte of the /// address; `$80` to `$8f` must not reach here, being the language card's. pub fn access(self: *Slots, host: anytype, low: u8, is_write: bool, value: u8) ?u8 { const slot: u3 = @truncate(low >> 4); const offset: u4 = @truncate(low); return switch (self.cards[slot]) { .empty => null,
// One address of the sixteen, which is the card's latch. .parallel => |*c| { if (offset != 0) return null; if (is_write) c.send(value); return c.read(); },
// One address, the data port: a write sends the character to the // host at once, a read takes the next one from the host — blocking // until it is there, which is the console waiting on input the way // a real machine waits on a key. .console => |*c| { if (offset != 0) return null; if (is_write) { c.send(value); return value; } return c.receive(); },
.clock => |*c| { // Two of the sixteen: one to read a character of the string // out, one to write a command in. if (offset > 1) return null; return c.access(offset, is_write, value, host.getCPU().clock.cycles); },
.ramfactor => |*c| c.card.access(offset, is_write, value),
// The sixteen a SCSI card decodes; see `Card.Scsi.access`. .scsi => |*c| c.access(offset, is_write, value),
.mouse => |*c| { if (offset > 8) return null; const answer = runMouseCommand(c, host, slot, @enumFromInt(offset), is_write, value); host.updateInterrupt(); return answer; },
.disk => |*c| c.drives.access(offset, is_write, value, host.getCPU().clock.cycles),
.videx => |*c| c.card.access(offset, is_write, value), .ultraterm => |*c| c.card.access(offset, is_write, value),
.block => |*c| { if (offset > 7) return null; if (is_write) { c.write(@enumFromInt(@as(u3, @truncate(offset))), value); return 0; } return switch (@as(blockdevice.Register, @enumFromInt(@as(u3, @truncate(offset))))) { .execute => blockdevice.run(c, host), .smartport => blockdevice.smartPort(c, host), else => c.read(@enumFromInt(@as(u3, @truncate(offset)))), }; },
.transporter => |*c| { // The card answers at the first of its sixteen and nowhere // else, which is the address its own firmware computes for // itself out of where that firmware is running. if (offset != 0) return null; if (is_write) { c.card.write(host, value); return 0; } return c.card.status(); },
.serial => |*c| { // Four of the sixteen, at the top: the card's own switches are // in the eight below them. if (offset < 8 or offset > 11) return null; const register: serial.Register = @enumFromInt(@as(u2, @truncate(offset - 8))); const cycle = host.getCPU().clock.cycles; if (!is_write and register == .status) c.listening = true; const answer = if (is_write) answer: { c.acia.write(register, value, cycle); break :answer 0; } else c.acia.read(register, cycle); host.updateInterrupt(); return answer; },
.passport => |*c| blk: { const cycle = host.getCPU().clock.cycles; const answer: ?u8 = switch (offset) { // The 6840's eight registers: the register-select lines are // the low three of the offset. 0x0...0x7 => reg: { const register: mc6840.Register = @enumFromInt(@as(u3, @truncate(offset))); if (is_write) { c.ptm.write(register, value, cycle); break :reg 0; } break :reg c.ptm.read(register, cycle); }, // The 6850: $8 is control (write) and status (read), $9 the // data register. A status read is how the machine says it // is listening. 0x8, 0x9 => acia: { const register: mc6850.Register = @enumFromInt(@as(u1, @truncate(offset - 8))); if (!is_write and register == .control_status) c.listening = true; if (is_write) { c.acia.write(register, value, cycle); break :acia 0; } break :acia c.acia.read(register, cycle); }, // Drum sync: a touch of $E raises the line, $F lowers it. 0xe => sync: { c.drum_sync = true; break :sync 0; }, 0xf => sync: { c.drum_sync = false; break :sync 0; }, else => null, }; host.updateInterrupt(); break :blk answer; },
// Four of the sixteen: the W5100's indirect bus, mode register and // two-byte pointer and data register. Everything the card does is // reached through these, the pointer walking the chip's internal // memory. .uthernet => |*c| { if (offset > 3) return null; const register: u2 = @truncate(offset); if (is_write) { c.chip.write(register, value); return 0; } return c.chip.read(register); },
// All sixteen device selects are the CS8900A's I/O ports: the // receive/transmit data port, TxCMD, TxLength, the ISQ, and the // PacketPage pointer and data, each a sixteen-bit port over a pair // of byte addresses. .cs8900 => |*c| { if (is_write) { c.chip.write(offset, value); return 0; } return c.chip.read(offset); },
// Its sound chips and 6522s are in its `$Cn00` page; what is among // the switches is the mode latch, which any access to the card's // device selects sets — see `phasor.Card.selectMode`. .phasor => |*c| { c.selectMode(offset); return null; },
// Its registers are in its `$Cn00` page rather than among the // switches, which is what `Answer.registers` is for. .mockingboard => null, // Likewise the Sound/Speech card: its two 6522s are in the page. .soundspeech => null, }; }
/// Hands the shared kilobyte to whichever card's page was touched, and /// takes it back when `$CFFF` is. /// /// Only on a real access, never on a peek: looking at memory from outside /// the machine must not change which ROM the machine can see. /// /// `pages_are_the_slots` is false while the machine's own ROM is answering /// in the slot pages. What wakes a card is the slot's I/O SELECT line, and /// a motherboard holding that inactive means no card is being selected at /// all. `slot_three_takes_it` is the same question for slot 3 alone, which /// on a IIe is the page the machine keeps its eighty-column firmware in. A /// machine with no MMU passes true for both and all of this folds away. pub fn claim( self: *Slots, address: u16, pages_are_the_slots: bool, slot_three_takes_it: bool, ) void { if (!pages_are_the_slots) return; // A memory expansion card comes up with its registers disabled and any // access to its firmware page enables them, which is the card's // protection against a stray write to the slot's I/O reaching a // megabyte of RAM. if (address >= 0xc100 and address < window_from) { const slot: u3 = @truncate(address >> 8); if (self.cards[slot] == .ramfactor) self.cards[slot].ramfactor.card.touchFirmware(); } switch (address) { // "$C800-$CFFF will stay assigned to motherboard ROM until an // access is made to $CFFF or until the MMU detects a system reset" // (Sather, 1985, p. 5-28), and the same access is what takes the // window away from a card. So $cfff empties it both ways round. 0xcfff => self.expansion = null, // Slot 3's page is two different things depending on the switches, // and so is an access to it. With a card answering there it takes // the window as any slot's page does; with the machine's own // firmware there it takes the window away from whoever had it and // gives it to nobody. 0xc300...0xc3ff => self.expansion = if (slot_three_takes_it) 3 else null, 0xc100...0xc2ff, 0xc400...0xc7ff => self.expansion = @truncate(address >> 8), else => {}, } }};
/// One of the mouse card's nine commands.////// A real card has a processor of its own and leaves its answers in the screen/// holes, which is what this does: `$0478 + slot` and the five addresses like/// it, one set per slot. Taking the slot from where the card actually is/// rather than from a constant is what lets a mouse work anywhere — the holes/// are the *slot's*, and a mouse in slot 2 writing slot 4's would be writing/// over another card's.pub fn runMouseCommand( card: *mouse.Card, host: anytype, slot: u3, command: mouse.Command, is_write: bool, value: u8,) u8 { const mine: u16 = slot; switch (command) { .result => return card.result, .set => if (is_write) { card.setMode(value); host.poke(mouse.hole.mode + mine, value); }, .serve => card.serve(), .read => { const reported = card.readPosition(); host.poke(mouse.hole.x_low + mine, @as(u8, @truncate(@as(u16, @bitCast(card.x))))); host.poke(mouse.hole.x_high + mine, @as(u8, @intCast(@as(u16, @bitCast(card.x)) >> 8))); host.poke(mouse.hole.y_low + mine, @as(u8, @truncate(@as(u16, @bitCast(card.y))))); host.poke(mouse.hole.y_high + mine, @as(u8, @intCast(@as(u16, @bitCast(card.y)) >> 8))); host.poke(mouse.hole.status + mine, reported); }, .clear => card.clear(), .position => { const x = @as(u16, host.peek(mouse.hole.x_low + mine)) | @as(u16, host.peek(mouse.hole.x_high + mine)) << 8; const y = @as(u16, host.peek(mouse.hole.y_low + mine)) | @as(u16, host.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. Slot nought's, whichever slot // the card is in — it is a place to leave a parameter and not a // card's own memory. const low = @as(u16, host.peek(mouse.hole.x_low)) | @as(u16, host.peek(mouse.hole.x_high)) << 8; const high = @as(u16, host.peek(mouse.hole.y_low)) | @as(u16, host.peek(mouse.hole.y_high)) << 8; card.clamp(value, @bitCast(low), @bitCast(high)); }, .home => card.home(), .init => { card.initialise(); host.poke(mouse.hole.mode + mine, 0); host.poke(mouse.hole.status + mine, 0); }, else => {}, } return card.result;}
const testing = std.testing;
/// Just enough machine to answer what a card asks of one, so that these can be/// tested without a whole Apple around them — which nothing here has been able/// to be until now.const FakeHost = struct { memory: [0x10000]u8 = @splat(0), interrupts: usize = 0, cpu: struct { clock: struct { cycles: u64 = 0 } = .{} } = .{},
pub fn getCPU(self: *FakeHost) *@TypeOf(self.cpu) { return &self.cpu; } pub fn updateInterrupt(self: *FakeHost) void { self.interrupts += 1; } pub fn peek(self: *FakeHost, at: u16) u8 { return self.memory[at]; } pub fn poke(self: *FakeHost, at: u16, byte: u8) void { self.memory[at] = byte; } pub fn blockGet(self: *FakeHost, at: u16) u8 { return self.memory[at]; } pub fn blockPut(self: *FakeHost, at: u16, byte: u8) void { self.memory[at] = byte; }};
test "a slot holds one card, and says so rather than deciding for itself" { var slots: Slots = .{}; try slots.fit(4, .{ .mouse = .{ .fitted = true } }); try testing.expectError(error.SlotTaken, slots.fit(4, .{ .mockingboard = .{ .fitted = true } })); // And slot 0 is not a slot: those sixteen addresses are the language // card's, and its page is the machine's own. try testing.expectError(error.NotASlot, slots.fit(0, .{ .clock = .{} }));
try testing.expectEqual(@as(?u3, 4), slots.first(.mouse)); try testing.expectEqual(@as(?u3, null), slots.first(.clock)); _ = slots.empty(4); try testing.expectEqual(@as(?u3, null), slots.first(.mouse));}
test "a card answers in the slot it is in and not in any other" { // The whole point of the exercise: the same card, twice, in a slot no // Disk II controller has ever been in here. var prom: [0x100]u8 = @splat(0); prom[0x00] = 0xa2; // the first byte of Apple's own boot PROM var slots: Slots = .{}; try slots.fit(2, .{ .disk = .{ .rom = &prom } });
switch (slots.page(0xc200)) { .rom => |byte| try testing.expectEqual(@as(u8, 0xa2), byte.*), else => return error.TestUnexpectedResult, } // Slot 6, where one has always been, has nothing in it. try testing.expectEqual(Answer.none, slots.page(0xc600));
// And its sixteen switches are slot 2's, at $c0a0: turning the motor on is // the odd address of the first pair. var host: FakeHost = .{}; try testing.expect(!slots.cards[2].disk.drives.motor); _ = slots.access(&host, 0xa9, false, 0); try testing.expect(slots.cards[2].disk.drives.motor);}
test "an Uthernet II answers on four device selects and reaches the chip" { var slots: Slots = .{}; try slots.fit(3, .{ .uthernet = .{} }); var host: FakeHost = .{};
// The four addresses are $C0n0 through $C0n3, so for slot 3 that is // offsets 0x30 to 0x33: the mode register, the pointer's two bytes, and // the data register. Point the pointer at a byte of the chip's internal // memory and write it through the data register. _ = slots.access(&host, 0x30, true, 0x00); // mode: no auto-increment _ = slots.access(&host, 0x31, true, 0x00); // pointer high _ = slots.access(&host, 0x32, true, 0x30); // pointer low: internal $0030 _ = slots.access(&host, 0x33, true, 0xab); // data try testing.expectEqual(@as(u8, 0xab), slots.cards[3].uthernet.chip.memory[0x0030]); // And reading the data register back through the same pointer returns it. try testing.expectEqual(@as(?u8, 0xab), slots.access(&host, 0x33, false, 0));
// Only the four: the fifth device select is an undriven bus. try testing.expectEqual(@as(?u8, null), slots.access(&host, 0x34, false, 0));}
test "two controllers, and each has its own drives" { // A machine could never have two of anything before. Both are bootable, // and the machine's own scan is what decides which wins: it counts down // from slot 7, so the higher-numbered one is tried first. var prom: [0x100]u8 = @splat(0); var slots: Slots = .{}; try slots.fit(5, .{ .disk = .{ .rom = &prom } }); try slots.fit(6, .{ .disk = .{ .rom = &prom } });
var host: FakeHost = .{}; _ = slots.access(&host, 0xd9, false, 0); // slot 5's motor on try testing.expect(slots.cards[5].disk.drives.motor); try testing.expect(!slots.cards[6].disk.drives.motor); _ = slots.access(&host, 0xe9, false, 0); // and slot 6's try testing.expect(slots.cards[6].disk.drives.motor);}
test "a Mockingboard's page is registers rather than a byte" { // Which is the difference that kept one silent in a II Plus: a page that // answers with a byte is a page nothing further is asked about, and this // card's page has to reach `access` because the two 6522s *are* the page. var slots: Slots = .{}; try slots.fit(4, .{ .mockingboard = .{ .fitted = true } }); try testing.expectEqual(Answer.registers, slots.page(0xc400)); try testing.expectEqual(Answer.registers, slots.page(0xc4ff)); // And nothing among the switches, which is where every other card is. var host: FakeHost = .{}; try testing.expectEqual(@as(?u8, null), slots.access(&host, 0xc0, false, 0));}
test "the shared kilobyte goes to whichever page was touched, and $cfff empties it" { var rom: [0x800]u8 = @splat(0); rom[serial_slot_page] = 0x18; // the slot page rom[0x000] = 0xd8; // and the first byte of the window var slots: Slots = .{}; try slots.fit(2, .{ .serial = .{ .rom = &rom } });
// Nobody has it yet. try testing.expectEqual(Answer.none, slots.page(0xc800));
// Touching the card's page is what claims it. slots.claim(0xc200, true, true); try testing.expectEqual(@as(?u3, 2), slots.expansion); switch (slots.page(0xc800)) { .rom => |byte| try testing.expectEqual(@as(u8, 0xd8), byte.*), else => return error.TestUnexpectedResult, }
// And $cfff takes it back from everybody. slots.claim(0xcfff, true, true); try testing.expectEqual(@as(?u3, null), slots.expansion); try testing.expectEqual(Answer.none, slots.page(0xc800));
// A machine whose own ROM is answering in the slot pages hands out // nothing, because no card is being selected at all. slots.claim(0xc200, false, true); try testing.expectEqual(@as(?u3, null), slots.expansion);}
test "slot 3 takes the window only when slot 3 is what answers there" { var slots: Slots = .{}; var rom: [0x800]u8 = @splat(0); try slots.fit(3, .{ .serial = .{ .rom = &rom } });
slots.claim(0xc300, true, true); try testing.expectEqual(@as(?u3, 3), slots.expansion);
// With the machine's own firmware in that page instead, an access there // takes the window away from whoever had it and gives it to nobody. slots.claim(0xc300, true, false); try testing.expectEqual(@as(?u3, null), slots.expansion);}
test "an eighty-column card's window is written to as well as read" { var rom: [videx.firmware_size]u8 = @splat(0); var charset: [videx.charset_size]u8 = @splat(0); var slots: Slots = .{}; try slots.fit(3, .{ .videx = .{ .rom = &rom, .charset = &charset } }); slots.claim(0xc300, true, true);
const target = slots.windowTarget(screen_from) orelse return error.TestUnexpectedResult; target.* = 'V'; try testing.expectEqual(@as(u8, 'V'), slots.cards[3].videx.card.ram[0]);
// The firmware below the window is read only: a ROM gated onto the bus // takes no writes, and there is no RAM there to take them either. try testing.expectEqual(@as(?*u8, null), slots.windowTarget(window_from));}
test "a mouse writes the screen holes of the slot it is actually in" { // It used to write slot 4's whatever slot it was in, which was right only // because it could only be in slot 4. A mouse in slot 2 writing slot 4's // holes would be writing over whatever card is there. var slots: Slots = .{}; try slots.fit(2, .{ .mouse = .{ .fitted = true } }); var host: FakeHost = .{};
// `set` is the first of the nine, so slot 2's is $c0a0. _ = slots.access(&host, 0xa0, true, 0x0f); try testing.expectEqual(@as(u8, 0x0f), host.memory[mouse.hole.mode + 2]); try testing.expectEqual(@as(u8, 0), host.memory[mouse.hole.mode + 4]); // Touching a card is how a program says it has dealt with the line. try testing.expect(host.interrupts > 0);}
test "a card that is not there answers nothing, and neither does slot zero" { var slots: Slots = .{}; var host: FakeHost = .{}; try testing.expectEqual(Answer.none, slots.page(0xc100)); try testing.expectEqual(@as(?u8, null), slots.access(&host, 0x90, false, 0)); try testing.expectEqual(@as(?*Card, null), slots.at(0)); try testing.expectEqual(@as(?*Card, null), slots.at(5));}
test "a SCSI card answers the chip, its banks and its own six addresses" { const gpa = testing.allocator; const rom = try gpa.alloc(u8, Card.Scsi.rom_size); defer gpa.free(rom); // Each kilobyte bank filled with its own number, so that which one is // showing is readable off any byte of it. for (0..16) |bank| @memset(rom[bank * 1024 ..][0..1024], @intCast(bank));
var host: FakeHost = .{}; var slots: Slots = .{}; try slots.fit(4, .{ .scsi = .{ .rom = rom[0..Card.Scsi.rom_size] } });
// The slot page is bank 0, and it is where a scan looks. try testing.expectEqual(@as(u8, 0), slots.page(0xc400).rom.*);
// Bit 3 of the bank register is A13 of the ROM, and it is not gated by // IOSEL*, so it reaches the slot page too: setting it shows bank 8 there. // Apple's answer to that fault was to make banks 0 and 8 almost the same. _ = slots.access(&host, 0x4a, true, 0x08); try testing.expectEqual(@as(u8, 8), slots.page(0xc400).rom.*); _ = slots.access(&host, 0x4a, true, 0x00);
// The window is cut in half: the card's RAM below $cc00 and a bank of its // ROM above. slots.claim(0xc400, true, false); // touching the slot page claims the window try testing.expectEqual(@as(u8, 0), slots.page(0xcc00).rom.*); _ = slots.access(&host, 0x4a, true, 0x05); try testing.expectEqual(@as(u8, 5), slots.page(0xcc00).rom.*); try testing.expectEqual(@as(u8, 5), slots.page(0xcfff).rom.*);
// And the RAM half is real memory: it takes a write and gives it back. const target = slots.windowTarget(0xc900).?; target.* = 0xa5; try testing.expectEqual(@as(u8, 0xa5), slots.page(0xc900).rom.*); // A different RAM bank is a different kilobyte behind the same address. _ = slots.access(&host, 0x4a, true, 0x15); // RAM bank 1, ROM bank 5 try testing.expectEqual(@as(u8, 0x00), slots.page(0xc900).rom.*); _ = slots.access(&host, 0x4a, true, 0x05); try testing.expectEqual(@as(u8, 0xa5), slots.page(0xc900).rom.*);
// The card's identity reads back as a bit rather than a number, which is // how it goes on the data lines during arbitration. try testing.expectEqual(@as(u8, 0x80), slots.access(&host, 0x49, false, 0).?);
// And the chip is at the first eight. Writing the Output Data Register // and reading the Current SCSI Data Register back is the cheapest proof // the card reaches it: nothing else is driving the bus. _ = slots.access(&host, 0x41, true, ncr5380.icr_assert_data); _ = slots.access(&host, 0x40, true, 0x5a); try testing.expectEqual(@as(u8, 0x5a), slots.access(&host, 0x40, false, 0).?);
// Two of the sixteen are reserved and drive nothing at all. try testing.expect(slots.access(&host, 0x4c, false, 0) == null); try testing.expect(slots.access(&host, 0x4f, false, 0) == null);}
test "a SCSI bus holds seven drives, and only the ones hooked up answer" { const gpa = testing.allocator; const rom = try gpa.alloc(u8, Card.Scsi.rom_size); defer gpa.free(rom); @memset(rom, 0); const one = try gpa.alloc(u8, 4 * scsi_bus.block_size); defer gpa.free(one); const two = try gpa.alloc(u8, 8 * scsi_bus.block_size); defer gpa.free(two); @memset(one, 0x11); @memset(two, 0x22);
var slots: Slots = .{}; try slots.fit(4, .{ .scsi = .{ .rom = rom[0..Card.Scsi.rom_size] } }); const card = &slots.cards[4].scsi; card.rewire();
// An empty cable: nothing anywhere, which is not the same as seven drives // with nothing in them. Selecting an identity with no device on it has to // find nothing at all, since that is how the firmware learns what is // there. for (card.chip.bus.devices) |device| try testing.expect(device == null);
// Six is where the first one goes, which is where an owner would have // jumpered it and where this card's firmware looks first. try testing.expectEqual(@as(?u3, 6), card.nextFree()); try card.attach(6, one, false); try testing.expect(card.chip.bus.devices[6] != null); try testing.expectEqual(@as(u32, 4), card.disks[6].blocks());
// And the next goes below it, counting down. try testing.expectEqual(@as(?u3, 5), card.nextFree()); try card.attach(5, two, true); try testing.expectEqual(@as(u32, 8), card.disks[5].blocks()); try testing.expect(card.disks[5].write_protected); try testing.expect(!card.disks[6].write_protected);
// Seven is the card's own, and hooking a drive up there is refused rather // than quietly taking the card off its own bus. try testing.expectError(error.TakenByTheCard, card.attach(7, one, false));
// Unhooking one is a device leaving the bus, not a disk coming out of a // drive: there is no such thing as an empty SCSI drive down here. card.detach(6); try testing.expect(card.chip.bus.devices[6] == null); try testing.expect(card.chip.bus.devices[5] != null); try testing.expectEqual(@as(?u3, 6), card.nextFree());}