From 4dea62d156728faee9dffe88d02f6bf3e59fb4eb Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Tue, 8 Sep 2026 16:11:05 -0500 Subject: [PATCH] the Apple III's four slots hold cards, and the second card exists Two things, and the first is a correction. This had `pub const profile_slot: u8 = 4` compiled into it, on the reasoning that the ProFile's manual says slot 4 and every SOS.DRIVER that came to hand agrees. Both are true and neither makes it a fact about the machine: slot assignment on an Apple III is *software*. The System Configuration Program's Peripheral Slot Assignment "enables you to tell each device driver the slot number into which you" put its card, "a number from 1 to 4", and a driver for something built in shows n/a instead (Apple Computer, Inc., 1981b, p. 17). A SOS.DRIVER built with the ProFile assigned elsewhere expects the card elsewhere, and a model with the slot compiled in could not follow. Four is now the default and not the law. So the machine has four slots and an array saying what is in each. **Not `slots.zig`** -- that is the Apple II's seven, and its cards are Apple II cards; a Videoterm in an Apple III would be a card the machine has no driver for and no business holding. What the two share is the `$c080 + s0` convention and nothing else, so four entries is the whole of the apparatus. An empty slot now floats at its ports and its window. That was already true of slot 4 and not of slots 1 to 3, which fell through to a case answering nought. The second card is the **Universal Parallel Interface Card**, Apple's A3L0009, built from chapter 6 of its manual with the eight addresses read off the page images rather than the scan's text. Two output latches, an input port, a write-only control register setting the strobe width and three polarities, two status flip-flops with an interrupt apiece, and autostrobe -- which comes on when the card's ROM space is touched and off at CLEAR, being there for Apple II emulation. The far end is a file and a file is never busy, so the acknowledgement a printer would send comes back at once and a driver that waits for ACK never waits; that is `parallel.zig`'s choice for the same reason. The manual disagrees with itself once and the disagreement is kept rather than quietly resolved: DATARDY's own entry says it turns the DATA READY status off, where the STATUS entry and the address-decode table both say on. Two against one, and a table of what the hardware does outweighs a sentence about it. `--slot 2=block` moves the ProFile and `--slot 3=parallel` places the UPIC, which are the same names that mean the same cards on a IIe -- a III's ProFile interface *is* its block device and the UPIC *is* its parallel printer card. Only the defaults differ, because a III has no slot 7. Eleven tests: seven on the card, four on the machine, including both cards on the bus at once not answering for each other, and a volume being taken away taking its interface card off the bus with it. What is **not** shown is a byte printed by SOS end to end: no SOS.DRIVER in the disk catalogue is built for a parallel printer -- .PRINTER on the Business BASIC disk reaches neither this card nor the serial port -- and making one means driving the System Configuration Program, which is a job of its own. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01HyUnXWJRv6j7Pt6MBMxexh --- README.md | 41 ++++- src/main.zig | 50 +++++- src/memory8/apple3.zig | 261 +++++++++++++++++++++++++---- src/session8.zig | 6 +- src/upic.zig | 361 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 681 insertions(+), 38 deletions(-) create mode 100644 src/upic.zig diff --git a/README.md b/README.md index 323c170..e329419 100644 --- a/README.md +++ b/README.md @@ -383,8 +383,22 @@ Apple's own Apple II emulation booting a DOS 3.3 disk inside it, and a ProFile catalogued from Business BASIC — `--hard-disk` puts one on its interface card in slot 4, where SOS's `.PROFILE` driver looks. -The drive and its controller are on the board, so a disk needs no card. What is -not here is anything to put in the four slots. +The drive and its controller are on the board, so a disk needs no card. The +four slots take the two cards that exist for this machine — the ProFile's +interface card and the Universal Parallel Interface Card — and either goes in +any of them, because on an Apple III which slot a card is in is something SOS +is *told* rather than something the hardware decides: the System Configuration +Program's Peripheral Slot Assignment "enables you to tell each device driver +the slot number into which you" put its card, "a number from 1 to 4", and a +driver for something built in shows `n/a` instead. So `--slot 2=block` moves +the ProFile and `--slot 3=parallel` puts the UPIC in slot 3, the same names +that mean the same cards on a IIe. The defaults are slot 4 for the ProFile, +which is what its manual says and what every `SOS.DRIVER` that came to hand is +configured for, and slot 1 for the UPIC. + +An empty slot floats at its ports and at its firmware window, which is what an +empty slot does. That used to be true of slot 4 and not of slots 1 to 3, where +a read answered nought. #### `iigs` — the Apple IIgs @@ -3589,7 +3603,9 @@ machine around them is not. DAC on the E VIA's port B. All three are logged and come out in an `--audio` recording, the DAC mixed into the one speaker they share, though no III program in the catalogue drives the DAC, so it is checked by test - rather than by ear; and the four slots, but for one card. The processor's speed is + rather than by ear; and the four slots, with the two cards this machine has: + the ProFile's interface and the Universal Parallel Interface Card, either in + any slot. The processor's speed is the hardware's: "the Screen timeshares the RAM on the opposite phase of the processor clock", so while the beam is drawing the processor gets every other memory cycle and runs at 1 MHz, and in each line's horizontal @@ -6140,6 +6156,7 @@ before. | `src/ensoniq.zig` | the Ensoniq 5503: thirty-two oscillators and the sixty-four kilobytes they walk | | `src/wav.zig` | either of those written to a file, because a terminal has no speaker | | `src/slots.zig` | the seven expansion slots: what a card is, where it is, and what its page and its sixteen switches answer | +| `src/upic.zig` | the Universal Parallel Interface Card, which is what an Apple III printed through | | `src/parallel.zig` | a parallel printer card: a latch, eight wires, and the firmware in front of them | | `src/serial.zig` | the 6551 in a Super Serial Card | | `src/blockdevice.zig` | a ProDOS block device, and the firmware it answers with | @@ -6893,6 +6910,24 @@ them by — Apple published a great deal and dated little of it. them against. Its Appendix A2 is flowcharts and 6502 assembly and A3 is a 65C02 interface diagram, so it had an eight-bit machine's card in mind. +- Apple Computer, Inc. (1981). *The Universal Parallel Interface Card: + installation and operating manual* (A3L0009, 030-0255-A). + + The parallel card for the Apple III, and the second card that machine has + anywhere to put. Chapter 6 is the hardware — the address decoding, the + control register bit by bit, the two output ports and the input port, the + strobe circuitry and the handshake — and its "Summary of Hardware Addresses" + on printed page 42 is what `src/upic.zig` is built from, read off the page + images rather than the scan's text. Chapters 4 and 5 give the SOS drivers' + configuration blocks, which is where a card in a slot becomes a `.PRINTER` + a program can open. + + It disagrees with itself once, and the disagreement is kept rather than + resolved: the entry for `DATARDY` says a read or write there turns the DATA + READY status *off*, where the entry for `STATUS` and the address-decode table + both say it turns it on. Two against one, and a table of what the hardware + does is worth more than a sentence about it, so the model sets it and says so. + - Parker, N. (2020, January 5). *Inside the Apple IIGS ADB controller*. () diff --git a/src/main.zig b/src/main.zig index 1fb7c52..f98ddd1 100644 --- a/src/main.zig +++ b/src/main.zig @@ -781,6 +781,31 @@ fn slotFor(options: Options, kind: CardKind) u3 { return kind.defaultSlot(); } +/// The same, for an Apple III, whose four slots are numbered 1 to 4 and whose +/// two cards are its own. +/// +/// The names are shared with the Apple II's on purpose rather than by +/// accident: a III's ProFile interface card *is* its block device and the +/// UPIC *is* its parallel printer card, so `--slot 2=block` and +/// `--slot 3=parallel` say the same thing about this machine that they say +/// about a IIe. Only the defaults differ, because the slots do — a block +/// device goes in 7 on a II and a III has no slot 7. +fn slotForIII(options: Options, kind: CardKind, fallback: u3) u3 { + for (options.slots, 0..) |maybe, slot| { + if (maybe == kind) { + if (slot < 1 or slot > 4) { + std.debug.print( + "zig65: an Apple III has four slots, numbered 1 to 4, and no slot {d}\n", + .{slot}, + ); + std.process.exit(2); + } + return @intCast(slot); + } + } + return fallback; +} + fn applyConfig(options: *Options, rom: *?[]const u8, file: config.Config) void { if (file.machine) |name| options.machine = Machine.parse(name) orelse { std.debug.print("zig65: no such machine as '{s}'\n", .{name}); @@ -1549,8 +1574,15 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { std.debug.print("zig65: cannot print to '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; - if (comptime SessionT.hasParallel()) - self.session.cpu.memory.fitPrinter(slotFor(options, .parallel), &self.session.printer.?.writer.interface); + if (comptime SessionT.hasParallel()) { + // An Apple III's parallel card is the UPIC, and its four + // slots are numbered differently from a II's seven. + const slot = if (comptime @hasDecl(CPU.Memory, "fitCard")) + slotForIII(options, .parallel, 1) + else + slotFor(options, .parallel); + self.session.cpu.memory.fitPrinter(slot, &self.session.printer.?.writer.interface); + } } // The cassette port. Neither of these holds the machine to its own @@ -1838,11 +1870,19 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { // Fit the card where it was asked for, before the volume // goes in it: `insertVolume` would otherwise fit one at // the slot a block device has always gone in. - // An Apple III's is a ProFile on an interface card SOS - // configures for slot 4, so it does not move and has no - // such call. if (comptime @hasDecl(CPU.Memory, "fitBlockDevice")) self.session.cpu.memory.fitBlockDevice(slotFor(options, .block)) catch {}; + // An Apple III's block device is a ProFile on an interface + // card, and which slot that card is in is something SOS is + // told rather than something the machine decides, so it + // moves like any other -- see `default_profile_slot`. It + // stays in slot 4 unless asked, because that is what every + // SOS.DRIVER that came to hand is configured for. + if (comptime @hasDecl(CPU.Memory, "fitCard")) + self.session.cpu.memory.fitCard( + slotForIII(options, .block, zig65.memory.apple3.default_profile_slot), + .profile, + ) catch {}; self.session.cpu.memory.insertVolume(0, volume); } } diff --git a/src/memory8/apple3.zig b/src/memory8/apple3.zig index feab38c..dbb4cbd 100644 --- a/src/memory8/apple3.zig +++ b/src/memory8/apple3.zig @@ -82,6 +82,7 @@ const via = @import("../via.zig"); const mm58167 = @import("../mm58167.zig"); const blockdevice = @import("../blockdevice.zig"); const profile = @import("../profile.zig"); +const upic_module = @import("../upic.zig"); /// A bank: "banks of 32K bytes each". pub const bank_size: usize = 0x8000; @@ -160,12 +161,42 @@ pub const blanking_cycles: u64 = 70 * cycles_per_line; pub const beep_half_period: u64 = clock_hz / 2000; pub const beep_edge_count: u16 = 200; -/// The slot the ProFile's interface card is in: "This Interface Card is -/// installed in slot #4 in your Apple III" (*Using the ProFile with the -/// Apple ///*, n.d., p. 1), and every SOS.DRIVER file that came to hand -/// configures its `.PROFILE` for slot 4. So its ports are at `$C0C0` and its -/// control latch under `$C400`. -pub const profile_slot: u8 = 4; +/// Where the ProFile's interface card goes when nobody says otherwise: "This +/// Interface Card is installed in slot #4 in your Apple III" (*Using the +/// ProFile with the Apple ///*, n.d., p. 1), and every SOS.DRIVER file that +/// came to hand configures its `.PROFILE` for slot 4. So its ports are at +/// `$C0C0` and its control latch under `$C400`. +/// +/// It is a default rather than a fact about the machine, which is why the slot +/// is a field rather than this constant. Slot assignment on an Apple III is +/// software: the System Configuration Program's Peripheral Slot Assignment +/// "enables you to tell each device driver the slot number into which you" +/// put its card, "a number from 1 to 4", and a driver for something built in +/// shows `n/a` instead (Apple Computer, Inc., 1981b, p. 17). So a SOS.DRIVER +/// built with the ProFile assigned elsewhere expects the card elsewhere, and a +/// model that had slot 4 compiled into it could not follow. +pub const default_profile_slot: u3 = 4; + +/// The four slots, and what is in each. +/// +/// **These are the Apple III's own slots and not `slots.zig`'s.** That module +/// is the Apple II's seven, and its cards are Apple II cards: a Videoterm or a +/// Mockingboard in an Apple III would be a card the machine has no driver for +/// and no business holding. The III has four slots, two cards that exist for +/// it, and an I/O page laid out nothing like a II's — so what is shared with +/// the II here is the `$c080 + s0` convention and nothing else, and one +/// four-entry array is the whole of the apparatus. +pub const SlotCard = enum { + empty, + /// The ProFile's interface card, whose state is the model's `profile`. + profile, + /// A Universal Parallel Interface Card, whose state is its `upic`. + upic, +}; + +/// The lowest and highest of the four. Slot 0 is not a slot. +pub const first_slot: u3 = 1; +pub const last_slot: u3 = 4; /// The video modes, as the four switches at `$C050` to `$C057` set them. Each /// switch is a pair of addresses, the even one clearing it and the odd one @@ -328,6 +359,12 @@ pub fn AppleIII(comptime options: Options) fn (type) type { /// card and the drive, and `read8` for the pseudo-DMA that /// moves its blocks. profile: profile.Card = .{}, + /// A Universal Parallel Interface Card, which is the other + /// card this machine has anywhere to put. + upic: upic_module.Card = .{}, + /// Which of the four slots holds what, indexed by slot number. + /// Index 0 is not a slot and is always empty. + cards: [last_slot + 1]SlotCard = @splat(.empty), /// What was last on the data bus, which is what an address /// nothing decodes reads as: the operand byte just fetched, @@ -581,6 +618,18 @@ pub fn AppleIII(comptime options: Options) fn (type) type { pub fn insertVolume(self: *Self, which: u1, volume: ?*blockdevice.Volume) void { if (which != 0) return; self.profile.volume = volume; + // A volume arriving means the card is in the machine, and + // it goes where the ProFile's manual says unless somebody + // has already put it somewhere else. Taking the volume + // away takes the card out with it: an interface card with + // no drive on the end of its cable is not what any of this + // is for, and SOS finding one would be worse than SOS + // finding nothing. + if (volume == null) { + if (self.slotOf(.profile)) |slot| self.cards[slot] = .empty; + } else if (self.slotOf(.profile) == null) { + self.cards[default_profile_slot] = .profile; + } } /// The VIAs' idea of the time. Their clock pin "is the @@ -845,7 +894,7 @@ pub fn AppleIII(comptime options: Options) fn (type) type { // window does — the driver reads `$CN00` plus a code — // and no other card is fitted, so the rest is the bus. if (address >= 0xc100) { - if (address >> 8 == 0xc0 + profile_slot and self.profile.fitted()) self.profile.control(@truncate(address)); + self.slotFirmware(address); return self.floating; } const which: u8 = @truncate(address); @@ -907,22 +956,12 @@ pub fn AppleIII(comptime options: Options) fn (type) type { self.character_download = which & 1 != 0; return 0; }, - // The disk controller's sixteen switches. - // Slot 4's sixteen I/O addresses: the ProFile card's - // two ports and its BUSY register; an empty slot - // floats. - 0xc0...0xcf => { - if (!self.profile.fitted()) return self.floating; - return switch (which & 0x0f) { - 0x1 => self.profile.readPort(), - 0x2 => self.profile.statusRegister(), - 0x3 => taken: { - self.profile.clearParity(); - break :taken 0; - }, - else => 0, - }; - }, + // The four slots' sixteen device select addresses + // each, at `$c080 + s0` the way an Apple II lays them + // out: slot 1 at `$c090` through slot 4 at `$c0c0`. + // An empty slot floats, because there is nothing in it + // to drive the bus. + 0x90...0xcf => return self.slotAccess(which, false, 0) orelse self.floating, 0xe0...0xef => return self.disk.access(@truncate(which), false, 0, self.diskCycles()), 0xf0...0xf3 => return self.acia.read(@enumFromInt(@as(u2, @truncate(which))), self.getCPU().clock.cycles), else => return 0, @@ -931,7 +970,7 @@ pub fn AppleIII(comptime options: Options) fn (type) type { fn writeIO(self: *Self, address: u16, value: u8) void { if (address >= 0xc100) { - if (address >> 8 == 0xc0 + profile_slot and self.profile.fitted()) self.profile.control(@truncate(address)); + self.slotFirmware(address); return; } const which: u8 = @truncate(address); @@ -947,17 +986,85 @@ pub fn AppleIII(comptime options: Options) fn (type) type { self.clock.write(@enumFromInt(@as(u5, @truncate(self.zeroPage()))), value, self.getCPU().clock.cycles); self.updateInterrupt(); }, - 0xc0...0xcf => switch (which & 0x0f) { - 0x0 => self.profile.writePort(value), - 0x3 => self.profile.clearParity(), - else => {}, - }, + 0x90...0xcf => _ = self.slotAccess(which, true, value), 0xe0...0xef => _ = self.disk.access(@truncate(which), true, value, self.diskCycles()), 0xf0...0xf3 => self.acia.write(@enumFromInt(@as(u2, @truncate(which))), value, self.getCPU().clock.cycles), else => {}, } } + /// One of the four slots' device select addresses, `$c090` + /// to `$c0cf`. Null where nothing in the slot drove the bus. + fn slotAccess(self: *Self, which: u8, is_write: bool, value: u8) ?u8 { + const slot: u3 = @truncate((which -% 0x80) >> 4); + const offset: u4 = @truncate(which); + return switch (self.cards[slot]) { + .empty => null, + // The ProFile's interface card: two ports and a status + // register, and the rest of its sixteen drive nothing. + .profile => switch (offset) { + 0x0 => taken: { + if (is_write) self.profile.writePort(value); + break :taken 0; + }, + 0x1 => if (is_write) 0 else self.profile.readPort(), + 0x2 => if (is_write) 0 else self.profile.statusRegister(), + 0x3 => taken: { + self.profile.clearParity(); + break :taken 0; + }, + else => 0, + }, + .upic => self.upic.access(offset, is_write, value), + }; + } + + /// A touch of a slot's firmware page, `$Cs00` to `$CsFF`. + /// + /// Neither of this machine's cards has a ROM this reads: what + /// they have there is a side effect. The ProFile's card puts + /// its control latch under the window -- the driver reads + /// `$Cn00` plus a code -- and touching the UPIC's turns its + /// autostrobe on. + fn slotFirmware(self: *Self, address: u16) void { + const slot: u3 = @truncate(address >> 8); + if (slot < first_slot or slot > last_slot) return; + switch (self.cards[slot]) { + .empty => {}, + .profile => self.profile.control(@truncate(address)), + .upic => self.upic.touchFirmware(), + } + } + + /// Fits a Universal Parallel Interface Card and gives it + /// somewhere to print, which is what `--parallel-out` does. + /// + /// Slot 1 by default, which is only a convention: this + /// machine's slots are all alike and SOS is told which one the + /// card is in. + pub fn fitPrinter(self: *Self, slot: u3, out: ?*std.Io.Writer) void { + self.fitCard(slot, .upic) catch return; + self.upic = .{ .out = out }; + } + + /// Puts a card in one of the four slots, or takes one out. + /// + /// A card can go in any of them, because on this machine which + /// slot a card is in is something SOS is told rather than + /// something the hardware decides -- see `default_profile_slot`. + pub fn fitCard(self: *Self, slot: u3, card: SlotCard) error{NotASlot}!void { + if (slot < first_slot or slot > last_slot) return error.NotASlot; + self.cards[slot] = card; + } + + /// Which slot holds a given kind of card, if any does. + pub fn slotOf(self: *const Self, card: SlotCard) ?u3 { + for (first_slot..last_slot + 1) |slot| { + if (self.cards[slot] == card) return @intCast(slot); + } + return null; + } + /// `$C058` to `$C05F`: the even address clears and the odd /// sets, `$C058`/`$C059` select bit 0, `$C05A`/`$C05B` bit 2 /// and `$C05E`/`$C05F` bit 1 — `AD.SEL0 $C058`, `AD.SEL1 @@ -1830,3 +1937,99 @@ test "writing the E VIA's port B drives the sound DAC, and its levels are logged const all = cpu.memory.dac_log.taken(); try testing.expectEqual(@as(f32, 1.0), all[all.len - 1].level); } + +test "a card goes in any of the four slots, and only the four" { + var cpu: TestCPU = undefined; + try setUp(&cpu); + const m = &cpu.memory; + + // "The Peripheral Slot Assignment option... enables you to tell each + // device driver the slot number into which you" put its card, "a number + // from 1 to 4" (Apple Computer, Inc., 1981b, p. 17). So which slot a card + // is in is software, and any of the four will do. + try testing.expectError(error.NotASlot, m.fitCard(0, .upic)); + try testing.expectError(error.NotASlot, m.fitCard(5, .upic)); + try m.fitCard(2, .upic); + try testing.expectEqual(@as(?u3, 2), m.slotOf(.upic)); + try testing.expect(m.slotOf(.profile) == null); +} + +test "an empty Apple III slot floats at its ports and its window" { + var cpu: TestCPU = undefined; + try setUp(&cpu); + const m = &cpu.memory; + + // All four are empty to begin with, and an empty slot has nothing in it to + // drive the bus. This used to be true of slot 4 and not of slots 1 to 3, + // which fell through to a case that answered nought. + m.floating = 0xa5; + for ([_]u16{ 0xc090, 0xc0a0, 0xc0b0, 0xc0c0 }) |port| { + try testing.expectEqual(@as(u8, 0xa5), m.read(u8, port)); + } + // And the four firmware windows, which no card here answers either. + for ([_]u16{ 0xc100, 0xc200, 0xc300, 0xc400 }) |window| { + try testing.expectEqual(@as(u8, 0xa5), m.read(u8, window)); + } +} + +test "a UPIC prints from whichever slot it is in" { + var cpu: TestCPU = undefined; + try setUp(&cpu); + const m = &cpu.memory; + + var buffer: [8]u8 = undefined; + var writer = std.Io.Writer.fixed(&buffer); + + // Slot 3, which is not where anything is by default: the card's eight + // addresses are then at `$c080 + s0`, so `$c0b0` to `$c0b7`. + m.fitPrinter(3, &writer); + m.write(u8, 0xc0b0, 'A'); // PORTA + m.write(u8, 0xc0b2, 0); // STROBE + try testing.expectEqualStrings("A", writer.buffered()); + + // And it is not at any other slot's addresses. + m.floating = 0x5a; + try testing.expectEqual(@as(u8, 0x5a), m.read(u8, 0xc094)); + // Its own status register, though, answers: the strobe was acknowledged. + try testing.expectEqual(upic_module.status_ack, m.read(u8, 0xc0b4) & upic_module.status_ack); + + // Touching its firmware window turns autostrobe on, which is the one thing + // that space does on this card, and then a write to PORTA is enough. + _ = m.read(u8, 0xc300); + m.write(u8, 0xc0b0, 'B'); + try testing.expectEqualStrings("AB", writer.buffered()); +} + +test "a ProFile and a UPIC share the bus without answering for each other" { + var cpu: TestCPU = undefined; + try setUp(&cpu); + const m = &cpu.memory; + var image: [4 * blockdevice.block_size]u8 = @splat(0); + var volume: blockdevice.Volume = .{ .image = &image }; + + var buffer: [4]u8 = undefined; + var writer = std.Io.Writer.fixed(&buffer); + m.fitPrinter(1, &writer); + m.insertVolume(0, &volume); + + // The ProFile went to slot 4 because that is what its manual says and what + // every SOS.DRIVER expects, and the UPIC stayed in slot 1. + try testing.expectEqual(@as(?u3, 4), m.slotOf(.profile)); + try testing.expectEqual(@as(?u3, 1), m.slotOf(.upic)); + + // Each answers at its own sixteen and nowhere else. + m.write(u8, 0xc090, 'x'); // the UPIC's PORTA, slot 1 + m.write(u8, 0xc092, 0); // and its strobe + try testing.expectEqualStrings("x", writer.buffered()); + + // Slot 4's status register is the ProFile's, not the UPIC's. + _ = m.read(u8, 0xc0c2); + try testing.expectEqualStrings("x", writer.buffered()); + + // Taking the volume away takes the card off the bus with it: an interface + // card with no drive on the end is not what any of this is for. + m.insertVolume(0, null); + try testing.expect(m.slotOf(.profile) == null); + m.floating = 0x33; + try testing.expectEqual(@as(u8, 0x33), m.read(u8, 0xc0c2)); +} diff --git a/src/session8.zig b/src/session8.zig index 4f8f170..ca82afa 100644 --- a/src/session8.zig +++ b/src/session8.zig @@ -617,7 +617,11 @@ pub fn Session(comptime CPU: type, comptime has_slots: bool, comptime brk_is_sys /// them; a IIc has no slots, and what is at $c090 on one is its second /// serial port rather than a card. pub fn hasParallel() bool { - return @hasDecl(CPU.Memory, "fitPrinter") and has_slots; + // An Apple III has no `slots.zig` slots and does have a parallel + // card -- the UPIC -- so this asks for the call rather than for + // the Apple II's slot apparatus. `has_slots` is what the machine + // that has no cards at all answers with. + return @hasDecl(CPU.Memory, "fitPrinter") and (has_slots or @hasDecl(CPU.Memory, "fitCard")); } pub fn hasSerial() bool { diff --git a/src/upic.zig b/src/upic.zig new file mode 100644 index 0000000..5ef3a53 --- /dev/null +++ b/src/upic.zig @@ -0,0 +1,361 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +//! The Universal Parallel Interface Card, which is what an Apple III printed +//! through when it did not print through the serial port on its back. +//! +//! Apple's product A3L0009, and the second card this machine has anywhere to +//! put — the first being the ProFile's interface. It is a parallel port with +//! rather more to it than the Apple II's parallel card: that one is a latch and +//! a strobe and nothing else, and this one has two output ports, an input port, +//! a control register that sets the strobe's width and the polarity of three +//! separate signals, two status flip-flops, and an interrupt on either of them. +//! +//! Eight addresses, from `$c080 + s0` where `s` is the slot, which is the same +//! convention an Apple II uses (Apple Computer, Inc., 1981, "Summary of +//! Hardware Addresses", p. 42, and the address-decode table on p. 35): +//! +//! ```text +//! $c080 + s0 PORTA the output latch, IC 6C, on connector lines 20-27 +//! $c081 + s0 PORTB the other output latch, IC 6A, on lines 1-8 +//! $c082 + s0 STROBE a write sends the strobe +//! $c083 + s0 READB a read takes the input port, IC 6B +//! $c084 + s0 STATUS a read gives three signals +//! $c085 + s0 DATARDY sets the data ready output +//! $c086 + s0 CTRLREG the control register, IC 5B +//! $c087 + s0 CLEAR clears the handshake and turns autostrobe off +//! ``` +//! +//! ## What the far end is +//! +//! A file, and a file is never busy. So the acknowledgement a printer would +//! send back comes back at once: a strobe puts a byte out and the card has its +//! answer before the next instruction. That is the same choice `parallel.zig` +//! makes for the Apple II's card and for the same reason — what is on the other +//! end of the cable is whatever the caller attached, and a file does not run +//! out of paper. A driver that waits for `ACK` therefore never waits, which is +//! the fast case of real behaviour rather than a special case beside it. +//! +//! ## What is not here +//! +//! The card's own ROM at `$Cs00`. Under SOS nothing reads it: a driver is a +//! file on the boot disk, loaded into memory by the operating system, and the +//! ROM is there for Apple II emulation mode, where the card is driven the way +//! an Apple II card is. What *is* modelled about that space is its side effect, +//! because it has one: touching it turns autostrobe on. + +const std = @import("std"); + +/// The eight addresses, as the manual's decode table names them. +pub const Register = enum(u3) { + port_a = 0, + port_b = 1, + strobe = 2, + read_b = 3, + status = 4, + data_ready = 5, + control = 6, + clear = 7, +}; + +/// The bits of the control register (Apple Computer, Inc., 1981, p. 36). +/// +/// The bottom three set the strobe's width in microseconds, which nothing here +/// measures: this card's timing is the file's, and a strobe that is two +/// microseconds or fourteen puts the same byte in the same place. They are +/// kept because they are written, and because a driver reads its own copy back +/// out of them. +pub const control_strobe_minus_2: u8 = 0x01; +pub const control_strobe_plus_4: u8 = 0x02; +pub const control_strobe_plus_8: u8 = 0x04; +/// "Set ACKNOWLEDGE and DATA READY ACKNOWLEDGE INPUT polarities; 1 = positive". +pub const control_ack_positive: u8 = 0x08; +/// "Set DATA READY OUTPUT polarity; 1 = positive". +pub const control_data_ready_positive: u8 = 0x10; +/// "Set STROBE polarity, 1 = positive". +pub const control_strobe_positive: u8 = 0x20; +/// "1 = enable DATA READY ACKNOWLEDGE Interrupt Request". +pub const control_data_ready_interrupt: u8 = 0x40; +/// "1 = enable ACKNOWLEDGE Interrupt Request". +pub const control_ack_interrupt: u8 = 0x80; + +/// The bits a read of STATUS gives back. +pub const status_ack: u8 = 0x80; +pub const status_data_ready: u8 = 0x40; +pub const status_ack_signal: u8 = 0x01; + +pub const Card = struct { + /// Output Port A's latch, IC 6C: "this data remains on the 40 pin + /// connector lines 20-27 until PORTA is written to again". These are the + /// lines a printer's data arrives on. + port_a: u8 = 0, + /// Output Port B's latch, IC 6A, on lines 1-8. Nothing a printer uses. + port_b: u8 = 0, + /// What the peripheral is driving on the input port, IC 6B. Nothing here + /// drives it, so it is what a caller put there. + input: u8 = 0, + + /// The control register, IC 5B, a 74LS273. + /// + /// **Write only.** "The current status of the control register must always + /// be maintained in software (CTRLWRD) since there is no way to read the + /// contents of CTRLREG" — so a read of `$c086 + s0` is not this, and the + /// caller is told to float the bus there instead. + control: u8 = 0, + + /// The ACKNOWLEDGE status, which a read of STATUS reports in bit 7: + /// "turned on by ACKNOWLEDGE INPUT, turned off by STROBE signal or reset". + acknowledged: bool = false, + /// The DATA READY status, bit 6. + data_ready: bool = false, + + /// Autostrobe, IC 1B, a 74LS74 flip-flop: with it on, a write to PORTA + /// sends a strobe as well as latching. "Autostrobe is turned on when + /// address space Csxx is accessed. It can be turned off by a read from or + /// a write to CLEAR". It is "primarily intended to provide automatic + /// strobes for Apple II Emulation mode", so under SOS it stays off and the + /// driver strobes for itself. + autostrobe: bool = false, + + /// Where a strobed byte goes: whatever the caller attached, which on the + /// command line is a file. Null is a card with nothing plugged into it, + /// which still latches and still strobes and still acknowledges. + out: ?*std.Io.Writer = null, + + /// How many bytes have gone out, which is the only thing a front end needs + /// in order to say the printer is doing something. + sent: u64 = 0, + + /// The first thing that went wrong writing, if anything did, kept so that + /// a failing file is reported once rather than at every byte. + trouble: ?anyerror = null, + + /// Whether the card is pulling the interrupt line: either status whose + /// interrupt the control register has enabled. + /// + /// "If the interrupts are enabled (by setting bits 7 and 6 of the control + /// register), then ACK status (DL7) and/or DATA READY status (DL6) will + /// result in an IRQ signal." + pub fn interrupting(self: *const Card) bool { + if (self.acknowledged and self.control & control_ack_interrupt != 0) return true; + if (self.data_ready and self.control & control_data_ready_interrupt != 0) return true; + return false; + } + + /// One of the sixteen device select addresses, of which this card decodes + /// the low eight. Null where the card drives nothing and the bus floats. + pub fn access(self: *Card, offset: u4, is_write: bool, value: u8) ?u8 { + // Only eight addresses are decoded; A3 is not in the decode table, so + // the top half of the slot's sixteen is nothing at all. + if (offset >= 8) return null; + switch (@as(Register, @enumFromInt(@as(u3, @truncate(offset))))) { + .port_a => { + if (!is_write) return null; + self.port_a = value; + if (self.autostrobe) self.sendStrobe(); + return 0; + }, + // "A read or a write to PORTB will latch whatever is on the data + // lines... For a read operation, the data on the lines is + // undefined" -- so a read latches whatever the bus happened to + // hold, and gives back nothing this can name. + .port_b => { + if (is_write) self.port_b = value; + return if (is_write) 0 else null; + }, + .strobe => { + if (is_write) self.sendStrobe(); + return if (is_write) 0 else null; + }, + .read_b => return if (is_write) 0 else self.input, + .status => { + if (is_write) return 0; + var byte: u8 = 0; + if (self.acknowledged) byte |= status_ack; + if (self.data_ready) byte |= status_data_ready; + // "Mirrors the ACKNOWLEDGE INPUT, but always is positive true + // logic (uses polarity)" -- the same line as bit 7, put the + // right way up whatever the control register's polarity bit + // says, which is what makes it worth having twice. + if (self.acknowledged) byte |= status_ack_signal; + return byte; + }, + // "A write or read to DATARDY sets the Data Ready flip-flop", and + // the decode table calls this address "Set DATA READY OUTPUT". + // + // The manual also says, in the same entry, that DL6 "is turned + // off" here, which contradicts both of those and its own account + // of DL6 under STATUS -- "turned on by a read or write to + // DATARDY". Two statements against one, and the decode table is a + // table of what the hardware does, so this sets it and the + // disagreement is written down rather than quietly resolved. + .data_ready => { + self.data_ready = true; + return 0; + }, + .control => { + if (!is_write) return null; // there is no way to read it + self.control = value; + return 0; + }, + // "A read or write to CLEAR clears the handshaking flip-flop", + // which the decode table spells out as "Clear DATA READY OUTPUT + // and ACKNOWLEDGE INPUT", "and also disables the autostrobe + // feature". + .clear => { + self.data_ready = false; + self.acknowledged = false; + self.autostrobe = false; + return 0; + }, + } + } + + /// Touching the card's ROM space, `$Cs00` to `$CsFF`, which is not a read + /// of anything here but does turn autostrobe on. + pub fn touchFirmware(self: *Card) void { + self.autostrobe = true; + } + + /// The strobe: a byte goes out, and the acknowledgement comes back. + /// + /// "When the STROBE signal is generated, it causes the ACKNOWLEDGE status + /// to be cleared", and then the peripheral's ACKNOWLEDGE INPUT sets it + /// again. Both happen here, because the far end is a file: it has taken + /// the byte by the time the processor could ask. + fn sendStrobe(self: *Card) void { + self.acknowledged = false; + if (self.out) |writer| { + writer.writeByte(self.port_a) catch |err| { + if (self.trouble == null) self.trouble = err; + }; + } + self.sent +|= 1; + self.acknowledged = true; + } + + /// "The contents of the latch are set to zero whenever the IORES line goes + /// low. This occurs when the power is turned on, or when a is + /// done." + pub fn reset(self: *Card) void { + self.control = 0; + self.acknowledged = false; + self.data_ready = false; + self.autostrobe = false; + } +}; + +const testing = std.testing; + +test "a byte written to Port A and strobed is a byte the printer has" { + var buffer: [16]u8 = undefined; + var writer = std.Io.Writer.fixed(&buffer); + var card: Card = .{ .out = &writer }; + + // "A write to PORTA will latch whatever is on the data lines into IC 6C", + // and nothing goes out until the strobe: a latch is not a printer. + _ = card.access(@intFromEnum(Register.port_a), true, 'H'); + try testing.expectEqual(@as(u64, 0), card.sent); + _ = card.access(@intFromEnum(Register.strobe), true, 0); + try testing.expectEqual(@as(u64, 1), card.sent); + + _ = card.access(@intFromEnum(Register.port_a), true, 'i'); + _ = card.access(@intFromEnum(Register.strobe), true, 0); + try testing.expectEqualStrings("Hi", writer.buffered()); + + // The latch keeps what was put in it, so a second strobe with no new byte + // sends the same one again. + _ = card.access(@intFromEnum(Register.strobe), true, 0); + try testing.expectEqualStrings("Hii", writer.buffered()); +} + +test "the strobe clears the acknowledgement and the printer gives it back" { + var card: Card = .{}; + // "Turned off by STROBE signal or reset", then turned on by the + // ACKNOWLEDGE INPUT -- which for a file is at once, because a file is + // never busy. So a driver that waits for ACK never waits. + _ = card.access(@intFromEnum(Register.port_a), true, 0x41); + _ = card.access(@intFromEnum(Register.strobe), true, 0); + const status = card.access(@intFromEnum(Register.status), false, 0).?; + try testing.expectEqual(status_ack, status & status_ack); + // Bit 0 is the same line the right way up whatever the polarity says, + // which is what makes it worth reporting twice. + try testing.expectEqual(status_ack_signal, status & status_ack_signal); +} + +test "the control register can be written and not read" { + var card: Card = .{}; + // "There is no way to read the contents of CTRLREG", so a read of it is + // not the register: nothing drives the bus and the caller floats it. + _ = card.access(@intFromEnum(Register.control), true, control_ack_interrupt | control_strobe_positive); + try testing.expectEqual(control_ack_interrupt | control_strobe_positive, card.control); + try testing.expect(card.access(@intFromEnum(Register.control), false, 0) == null); +} + +test "an enabled status pulls the interrupt line and a disabled one does not" { + var card: Card = .{}; + // "If the interrupts are enabled (by setting bits 7 and 6 of the control + // register), then ACK status (DL7) and/or DATA READY status (DL6) will + // result in an IRQ signal." + _ = card.access(@intFromEnum(Register.port_a), true, 0); + _ = card.access(@intFromEnum(Register.strobe), true, 0); + try testing.expect(card.acknowledged); + try testing.expect(!card.interrupting()); // nothing enabled yet + + _ = card.access(@intFromEnum(Register.control), true, control_ack_interrupt); + try testing.expect(card.interrupting()); + + // And clearing the handshake takes it away again. + _ = card.access(@intFromEnum(Register.clear), false, 0); + try testing.expect(!card.interrupting()); + + // The other status, on its own bit. + _ = card.access(@intFromEnum(Register.control), true, control_data_ready_interrupt); + _ = card.access(@intFromEnum(Register.data_ready), true, 0); + try testing.expect(card.data_ready); + try testing.expect(card.interrupting()); +} + +test "autostrobe comes on with the card's ROM space and off with CLEAR" { + var buffer: [8]u8 = undefined; + var writer = std.Io.Writer.fixed(&buffer); + var card: Card = .{ .out = &writer }; + + // Off to begin with, so a write to PORTA only latches. + _ = card.access(@intFromEnum(Register.port_a), true, 'a'); + try testing.expectEqual(@as(u64, 0), card.sent); + + // "Autostrobe is turned on when address space Csxx is accessed." + card.touchFirmware(); + _ = card.access(@intFromEnum(Register.port_a), true, 'b'); + try testing.expectEqualStrings("b", writer.buffered()); + + // "It can be turned off by a read from or a write to CLEAR." + _ = card.access(@intFromEnum(Register.clear), true, 0); + _ = card.access(@intFromEnum(Register.port_a), true, 'c'); + try testing.expectEqualStrings("b", writer.buffered()); +} + +test "only eight of the sixteen addresses are decoded" { + var card: Card = .{}; + // A3 is not in the manual's decode table, so the top half of the slot's + // sixteen is nothing at all and the bus floats there. + var offset: u4 = 8; + while (true) : (offset += 1) { + try testing.expect(card.access(offset, false, 0) == null); + if (offset == 15) break; + } +} + +test "a card with nothing plugged into it still works the handshake" { + // No writer: the card latches, strobes and acknowledges exactly as it + // would with a printer on the end, because none of that is the printer's + // doing. Only the byte has nowhere to go. + var card: Card = .{}; + _ = card.access(@intFromEnum(Register.port_a), true, 0x7f); + _ = card.access(@intFromEnum(Register.strobe), true, 0); + try testing.expectEqual(@as(u64, 1), card.sent); + try testing.expect(card.acknowledged); + try testing.expect(card.trouble == null); +} -- knotmirror 0.0.1