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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! An Applied Engineering RamFactor: a megabyte in a slot, reached through//! four addresses.//!//! A memory expansion card of this kind is not memory the processor can see.//! An Apple II has sixteen address lines and every one of them is spoken for,//! so a card carrying more memory than the whole machine can address has to//! be looked at through a window: three registers hold a twenty-four bit//! address and a fourth is the byte at it, and the address steps on by itself//! every time that fourth register is touched. A program moves a block by//! setting the address once and then reading the same address five hundred//! and twelve times.//!//! What comes out of that is a disk. The card's own firmware presents it to//! ProDOS as a block device, so the machine sees `/RAM5` and not a megabyte,//! and that is the whole point of the card: it was sold as a RAMdisk, and the//! reason to want one was that AppleWorks would load itself into it.//!//! ## The five registers//!//! The manual sets them out (Applied Engineering, n.d.-a, Chapter 6, "RamFactor//! Hardware")://!//! > The RamFactor card has five addressable registers, which are addressed//! > according to the slot number the card is in://! >//! > $C080+slot * 16 low byte of RAM address//! > $C081+slot * 16 middle byte of RAM address//! > $C082+slot * 16 high byte of RAM address//! > $C083+slot * 16 data at addressed location//! > $C08F+slot * 16 Firmware Bank Select//!//! Three of the four things worth knowing about them are surprising, and all//! three are in the same paragraph.//!//! **The address registers can be read back, and the high one lies.** "The//! three address bytes can be both written into and read from. If the card//! has one Megabyte or less, reading the high address byte will always return//! a value in the range $F0-FF. The top nybble can be any value when you//! write it, but it will always be 'F' when you read it." A megabyte needs//! twenty address lines, so four of the high byte's eight are not wired to//! anything, and what is not driven reads as ones. That is not a detail to//! model for completeness: it is how the firmware tells a card of a megabyte//! or less from a larger one, by writing nought to the high byte and seeing//! whether nought comes back.//!//! **Touching the data register moves the address on.** "When you read or//! write the data byte, the address automatically increments." Every access//! counts, which is why the manual goes on to warn that "some 6502 address//! modes cause two accesses at the same location, which in this case can//! cause double incrementing" — a read-modify-write instruction reads and//! then writes, and the card cannot tell that from two separate touches.//!//! **The counter ripples rather than adds.** "Whenever the lower or middle//! address byte changes from a value with bit 7 = 1 to one with bit 7 = 0,//! the next higher byte is automatically incremented." The three bytes are//! three counters wired in a chain, and the chain does not know the//! difference between a count and a write: storing `$00` over a low byte that//! held `$80` carries into the middle byte exactly as counting past `$ff`//! would. This is why the manual says to "always load the bytes in the order//! low-middle-high, and always load all three of them" — done in that order//! the spurious carries land in bytes that are about to be overwritten//! anyway, and done in any other order they do not.//!//! **The registers are asleep until the firmware page is touched.** "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//! $Cs00-CsFF." Nothing that goes about the card properly ever notices, since//! the firmware is reached through that page; what it protects against is a//! stray write to the slot's I/O quietly rewriting a megabyte.//!//! ## The firmware//!//! Eight kilobytes of ROM in two four-kilobyte banks, and the card decodes it//! with the twelve low address lines and the bank bit: `$Cs00` reads at//! `bank * $1000 + s * $100` and the shared expansion window at `$c800-$cfff`//! reads at `bank * $1000 + $800`. That one rule explains the whole of the//! image. Its first two hundred and fifty-six bytes are unreachable — they//! would be `$c000`, which is not a slot — so Applied Engineering put their//! copyright and the names of the two people who wrote it there; the seven//! pages after that are the seven slots' firmware pages, assembled seven//! times over because a `JMP` inside one has to name the slot it is in; and//! the two kilobytes above that are the expansion ROM. Bank nought holds the//! resident firmware, and bank one holds a program the resident firmware//! copies into main memory at `$0a00` and runs, which is the partition//! manager.//!//! The two banks differ only above `$800`, so the slot pages are the same in//! both, which is what makes it safe for the code that does the copying to//! run out of its own `$Cs00` page while the other bank is selected.//!//! ## What is and is not here//!//! This is the card: RAM, five registers and a socket for the firmware. The//! RAMdisk, the partition manager, the ProDOS driver, the SmartPort interface//! and the DOS 3.3 and Pascal support are all in that firmware, which is//! Applied Engineering's and is not here, exactly as the Disk II's boot PROM//! and the Videoterm's firmware are not. Given the ROM, everything above//! works because the card underneath behaves; given no ROM there is no card.//!//! The card is register-compatible with Apple's own Apple II Memory Expansion//! Card — "RamFactor was designed to be totally compatible with virtually all//! software written for the Apple II Memory Expansion Card" — which is why//! software of the period calls a card at these addresses a Slinky whichever//! one it is. What Apple's card does not have is the second ROM bank and the//! partition manager in it.
const std = @import("std");
/// The firmware ROM: eight kilobytes, in two banks of four.pub const rom_size = 8192;pub const bank_size = rom_size / 2;
/// One block of memory chips: eight 256K by 1 bit dynamic RAMs, which is/// 256K bytes. "The RamFactor card can contain up to 1024K (1 Megabyte) of/// Random Access Memory. This memory is organized into four 256K blocks, each/// block consisting of eight 256K RAM chips" (Applied Engineering, n.d.-a,/// Chapter 6).pub const block_size = 256 * 1024;
/// And how many of them the card holds. They are filled in order — "if blocks/// A and B are populated, fill C not D" — so a part-filled card is a/// contiguous run of memory from nought upward and everything above it is/// sockets.pub const max_blocks = 4;pub const max_ram = block_size * max_blocks;
/// What a data line nobody is driving reads as.////// The manual says this of the high address byte on a card of a megabyte or/// less, whose top four bits go nowhere: they "will always be 'F' when you/// read it". The same answer is given here for the other two places nothing/// is driving the bus — a register read before the card has been woken up,/// and a data read from an address with no chip behind it — because it is the/// same undriven lines in each case, and because the second of them is what/// the firmware's own memory sizing depends on being able to tell from a/// value it wrote.pub const undriven: u8 = 0xff;
/// The five addresses the card answers at, counted from `$C080 + slot * 16`.pub const Register = enum(u4) { address_low = 0, address_middle = 1, address_high = 2, /// The byte at the address, and touching it moves the address on. data = 3, /// Which four kilobytes of the firmware ROM answers at `$c800`. bank = 0xf, _,};
/// The card: some memory chips, a twenty-four bit counter pointed at them,/// and a bank bit for the ROM.pub const Card = struct { /// Whether there is a card in the slot at all, which here means whether /// its firmware has been supplied: the RAMdisk, the driver and everything /// else a program can see are in that ROM, and a card without it does /// nothing a machine could find. fitted: bool = false,
/// The chips, from the first block up. Not owned: the card is handed /// however much memory somebody fitted it with, which is why a card with /// a battery on it can be handed the same array a previous run left /// behind. ram: []u8 = &.{},
/// Whether the registers are answering yet. Cleared by reset, set by any /// access to the card's firmware page. enabled: bool = false,
/// The address, as the three counters the card really has rather than as /// the number they add up to. They are kept apart because the carry /// between them is a property of each one and not of the sum: see /// `setLow`. low: u8 = 0, middle: u8 = 0, /// The top four bits of the address. The other four of the byte are not /// wired to anything on a card of a megabyte or less, which every real /// RamFactor is, and reading the register gives them back as ones. high: u4 = 0,
/// Which bank of the firmware ROM is in the `$c800` window. bank: u1 = 0,
/// Whether the machine has written to the memory since it was handed /// over, which is what a battery-backed card needs to know to be worth /// saving. dirty: bool = false,
/// Puts the card where a power-on or a Control-Reset leaves it. /// /// The registers stop answering, and the ROM comes back to its first /// bank. Only the first of those is the manual's; the second is not /// something a program can tell, because the two banks are identical /// where the reset vector's machine will look. pub fn reset(self: *Card) void { self.enabled = false; self.bank = 0; }
/// Wakes the registers, which is what an access to `$Cs00-$CsFF` does. pub fn touchFirmware(self: *Card) void { self.enabled = true; }
/// How many 256K blocks of chips are fitted, which is what the firmware /// works out for itself by writing to the top of the address space and /// seeing what comes back. pub fn blocks(self: Card) u8 { return @intCast(self.ram.len / block_size); }
/// Where the counter is pointing. pub fn address(self: Card) u32 { return @as(u32, self.high) << 16 | @as(u32, self.middle) << 8 | self.low; }
/// One touch of one of the five registers. /// /// Every access is one of these, reads and writes alike, because on this /// card the two are not symmetrical: reading the data register has the /// same side effect as writing it, and reading the high address byte does /// not give back what was written to it. pub fn access(self: *Card, register: u4, is_write: bool, value: u8) u8 { // A card nobody has woken up is a card with nothing driving the bus. if (!self.fitted or !self.enabled) return undriven; switch (@as(Register, @enumFromInt(register))) { .address_low => { if (is_write) self.setLow(value); return self.low; }, .address_middle => { if (is_write) self.setMiddle(value); return self.middle; }, .address_high => { // Only the bottom four bits are stored, and the top four read // back as ones however they were written. if (is_write) self.high = @truncate(value); return 0xf0 | @as(u8, self.high); }, .data => { const at = self.address(); // Past the last chip there is nothing to write to and nothing // driving the lines on the way back, which is exactly what // the firmware's sizing routine looks for. var byte: u8 = undriven; if (at < self.ram.len) { if (is_write) { self.ram[at] = value; self.dirty = true; } byte = self.ram[at]; } // Whether or not there was a chip there. The counter is on // the card and does not ask the memory anything. self.setLow(self.low +% 1); return byte; }, .bank => { if (is_write) self.bank = @truncate(value); return self.bank; }, // The other eleven addresses of the slot's sixteen, which the // card does not decode. _ => return undriven, } }
/// Puts a value in the low counter, carrying if it has just gone past its /// top. /// /// "Whenever the lower or middle address byte changes from a value with /// bit 7 = 1 to one with bit 7 = 0, the next higher byte is automatically /// incremented" (Applied Engineering, n.d.-a, Chapter 6). That is a ripple /// carry out of a counter's top bit, and the thing to notice is that a /// *write* trips it as readily as a count does: the chain sees a bit fall /// and cannot tell where the new value came from. Storing `$00` over a /// low byte holding `$80` therefore steps the middle byte, which is why /// the manual insists that all three be loaded, lowest first. fn setLow(self: *Card, value: u8) void { const carried = self.low & 0x80 != 0 and value & 0x80 == 0; self.low = value; if (carried) self.setMiddle(self.middle +% 1); }
fn setMiddle(self: *Card, value: u8) void { const carried = self.middle & 0x80 != 0 and value & 0x80 == 0; self.middle = value; // And the high counter is four bits wide and carries into nothing. if (carried) self.high +%= 1; }};
/// Where in the ROM image an address in the card's two windows reads from.////// The card decodes the twelve low address lines and the bank bit and nothing/// else, so this one line covers both the slot's page and the shared/// expansion window: `$c500` on a card in slot 5 is `$500` into the bank, and/// `$c800` is `$800` into it. It also explains what is at the front of the/// image, which is a copyright notice rather than code: `$c000` is not a slot,/// so nothing can ever read the first page.pub fn romAt(bank: u1, address: u16) usize { return @as(usize, bank) * bank_size + (address & 0x0fff);}
const testing = std.testing;
/// A card with a megabyte in it, woken up, for the tests below.fn card(ram: []u8) Card { return .{ .fitted = true, .ram = ram, .enabled = true };}
test "the registers say nothing until the firmware page is touched" { // The manual: after power up or Control-Reset the registers are disabled, // and addressing any byte of $Cs00-$CsFF is what enables them. Until then // a write must not reach the memory, which is the whole point of it. var ram: [block_size]u8 = @splat(0); var subject: Card = .{ .fitted = true, .ram = &ram }; subject.reset();
_ = subject.access(@intFromEnum(Register.data), true, 0x5a); try testing.expectEqual(@as(u8, 0), ram[0]); try testing.expectEqual(undriven, subject.access(@intFromEnum(Register.address_low), false, 0)); try testing.expectEqual(@as(u8, 0), subject.low);
subject.touchFirmware(); _ = subject.access(@intFromEnum(Register.data), true, 0x5a); try testing.expectEqual(@as(u8, 0x5a), ram[0]);
// And a reset puts it back to sleep, as the manual says Control-Reset // does. subject.reset(); _ = subject.access(@intFromEnum(Register.data), true, 0x11); try testing.expectEqual(@as(u8, 0x5a), ram[0]);}
test "the high address byte reads back with its top nybble set" { // Four of its eight bits are not wired to anything on a card of a // megabyte or less, and undriven lines read as ones. This is how the // firmware tells such a card from a larger one: it writes nought and // looks at what comes back. var ram: [block_size]u8 = @splat(0); var subject = card(&ram);
try testing.expectEqual(@as(u8, 0xf0), subject.access(@intFromEnum(Register.address_high), true, 0x00)); try testing.expectEqual(@as(u4, 0), subject.high); // The top nybble may be anything on the way in and is not kept. try testing.expectEqual(@as(u8, 0xfc), subject.access(@intFromEnum(Register.address_high), true, 0x9c)); try testing.expectEqual(@as(u4, 0x0c), subject.high);
// The other two are ordinary registers and read back what was put in // them, which is what makes the firmware's `DEC` of the low byte — its // way of undoing an automatic increment — work at all. try testing.expectEqual(@as(u8, 0x34), subject.access(@intFromEnum(Register.address_low), true, 0x34)); try testing.expectEqual(@as(u8, 0x12), subject.access(@intFromEnum(Register.address_middle), true, 0x12)); try testing.expectEqual(@as(u32, 0x0c1234), subject.address());}
test "touching the data register moves the address on, whichever way the byte went" { var ram: [block_size]u8 = @splat(0); for (ram[0..4], 0..) |*byte, i| byte.* = @intCast(0x10 + i); var subject = card(&ram);
try testing.expectEqual(@as(u8, 0x10), subject.access(@intFromEnum(Register.data), false, 0)); try testing.expectEqual(@as(u8, 0x11), subject.access(@intFromEnum(Register.data), false, 0)); try testing.expectEqual(@as(u32, 2), subject.address());
// A write steps it too, so a block goes out the way it came in: set the // address once and touch the one register five hundred and twelve times. _ = subject.access(@intFromEnum(Register.data), true, 0xaa); _ = subject.access(@intFromEnum(Register.data), true, 0xbb); try testing.expectEqual(@as(u8, 0xaa), ram[2]); try testing.expectEqual(@as(u8, 0xbb), ram[3]); try testing.expectEqual(@as(u32, 4), subject.address());}
test "the address is three counters in a chain rather than a number" { // The manual: the next higher byte is incremented whenever the one below // it changes from a value with bit 7 set to one without. Counting past // $ff is the case that looks like arithmetic. var ram: [max_ram]u8 = @splat(0); var subject = card(&ram); subject.low = 0xff; subject.middle = 0xff; subject.high = 0x00; _ = subject.access(@intFromEnum(Register.data), false, 0); try testing.expectEqual(@as(u32, 0x010000), subject.address());
// And this is the case that does not. Storing $00 over a low byte holding // $80 has gone from a value with bit 7 set to one without, so it carries, // even though nothing has been counted and the address has gone *down*. subject.low = 0x80; subject.middle = 0x00; subject.high = 0x00; _ = subject.access(@intFromEnum(Register.address_low), true, 0x00); try testing.expectEqual(@as(u32, 0x000100), subject.address());
// Which is why the manual says to load all three, lowest first: done in // that order every spurious carry lands in a byte that has not been // written yet. subject.low = 0xff; subject.middle = 0xff; subject.high = 0x0f; _ = subject.access(@intFromEnum(Register.address_low), true, 0x00); _ = subject.access(@intFromEnum(Register.address_middle), true, 0x20); _ = subject.access(@intFromEnum(Register.address_high), true, 0x03); try testing.expectEqual(@as(u32, 0x032000), subject.address());}
test "past the last chip there is nothing to read and nowhere to write" { // A card with two of its four blocks fitted answers for half a megabyte // and no more. The addresses above that are not another copy of the // memory lower down — they are sockets — and the difference is what the // firmware's memory sizing rests on. var ram: [block_size * 2]u8 = @splat(0); var subject = card(&ram); try testing.expectEqual(@as(u8, 2), subject.blocks());
subject.high = 0x08; // $080000, the first byte of the third block _ = subject.access(@intFromEnum(Register.data), true, 0x5a); subject.high = 0x08; subject.low = 0; try testing.expectEqual(undriven, subject.access(@intFromEnum(Register.data), false, 0)); // And nothing lower down was written instead of it. try testing.expectEqual(@as(u8, 0), ram[0]);
// The counter itself does not care whether there was a chip there. subject.high = 0x08; subject.low = 0x40; _ = subject.access(@intFromEnum(Register.data), false, 0); try testing.expectEqual(@as(u32, 0x080041), subject.address());}
test "the firmware finds the size of a card by writing to it" { // This is the routine in the card's own ROM at $cafd, done here in Zig: // write a marker equal to the high address byte at the foot of each 256K // block, descending, and then read them back ascending. A block that is // not there fails to hold what was written, and the last one that did is // the top of the card. // // It is worth doing because it is the one piece of the firmware that // depends on the hardware being wrong in the right way, and because it is // what decides how big a RAMdisk the machine is told about. for ([_]usize{ 1, 2, 3, 4 }) |fitted| { var ram: [max_ram]u8 = @splat(0); var subject = card(ram[0 .. fitted * block_size]);
const marks = [_]u4{ 0x0c, 0x08, 0x04, 0x00 }; for (marks) |mark| { subject.high = mark; subject.middle = 0; subject.low = 0; _ = subject.access(@intFromEnum(Register.data), true, mark); } var found: u4 = 0; for ([_]u4{ 0x00, 0x04, 0x08, 0x0c }) |mark| { subject.high = mark; subject.middle = 0; subject.low = 0; if (subject.access(@intFromEnum(Register.data), false, 0) != mark) break; found = mark; } // What the firmware then does with it: the high byte of the top // working address, halved and with two added, is the size in units of // 128K. const units = @as(usize, found) / 2 + 2; try testing.expectEqual(fitted * block_size, units * 128 * 1024); }}
test "the ROM is decoded from twelve address lines and the bank bit" { // The slot's page and the shared expansion window come out of the same // rule, which is what lets the seven slot pages and the two banks all sit // in one eight kilobyte image. try testing.expectEqual(@as(usize, 0x0500), romAt(0, 0xc500)); try testing.expectEqual(@as(usize, 0x1500), romAt(1, 0xc500)); try testing.expectEqual(@as(usize, 0x0800), romAt(0, 0xc800)); try testing.expectEqual(@as(usize, 0x1fff), romAt(1, 0xcfff)); // Every byte of the image is reachable except the first page, which would // be $c000 and is not a slot. That is where the copyright notice is. try testing.expectEqual(@as(usize, 0x0100), romAt(0, 0xc100));}
test "the bank bit is the whole of the bank select register" { var ram: [block_size]u8 = @splat(0); var subject = card(&ram); // The firmware selects the second bank by storing $ff and comes back to // the first with an ASL, which reads whatever is there and writes it // shifted. ASL always leaves bit 0 clear, so it selects bank nought // whatever it read — which is the reason to believe bit 0 is the bit. _ = subject.access(@intFromEnum(Register.bank), true, 0xff); try testing.expectEqual(@as(u1, 1), subject.bank); const read = subject.access(@intFromEnum(Register.bank), false, 0); _ = subject.access(@intFromEnum(Register.bank), true, read << 1); try testing.expectEqual(@as(u1, 0), subject.bank);}