// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The SCSI bus, and a disk on the end of it. //! //! This is the wire rather than the chip: the nine control signals, the eight //! data lines, and up to eight devices that arbitrate for them. What drives it //! from the Apple's side is `ncr5380.zig`, which is the controller an Apple II //! SCSI Card has on it and which turns the processor's register accesses into //! the signals below. //! //! ## The one convention worth stating first //! //! **A SCSI bus is active low and nothing here is.** The chip's own manual sets //! the convention and this follows it: "even though the bus is active low, a //! one (1) is used to indicate signal assertion and a zero (0) is used to //! indicate the non-asserted or inactive state" (NCR Corporation, 1986, §6.0, //! p. 10). So `bsy` being true means BSY is *asserted*, which on the wire is a //! low voltage. Modelling the voltages instead would mean writing every //! comparison inside out for no gain. //! //! ## Who drives what //! //! The three phase lines are the target's and nobody else's: C/D says whether //! a byte is a command or data, I/O which way it is going, and MSG whether it //! is a message. Together they name one of eight phases, and the table that //! decodes them is the chip manual's (§6.4, p. 14) because that is the //! document in the archive that prints it. //! //! REQ is the target's and ACK is the initiator's, and one byte moves per //! REQ/ACK pair. The initiator puts a byte on the data lines and the target //! takes it, or the other way about, depending on I/O. const std = @import("std"); /// The eight information transfer phases. /// /// **The number is the Target Command Register's**, which is I/O at bit 0, C/D /// at bit 1 and MSG at bit 2 (NCR Corporation, 1986, Appendix A7, p. 58). That /// is worth saying because the manual's phase table prints its columns in the /// other order -- "ASSERT I/O, ASSERT C/D, ASSERT MSG" reading left to right /// (§6.4, p. 14) -- and reading a row of it straight off the page as a binary /// number gives every phase back to front. The register is the thing the chip /// actually compares against, so the register is what these are. /// /// The Current SCSI Bus Status Register puts the same three lines somewhere /// else again, at bits 2, 3 and 4, which is why `ncr5380.zig` moves them /// rather than masking them. /// /// Two of the eight are "unspecified" in that table and are named so here /// rather than left out, because a target that has driven the lines into one /// of them has done something and the model should be able to say what. pub const Phase = enum(u3) { data_out = 0b000, data_in = 0b001, command = 0b010, status = 0b011, unspecified_msg = 0b100, unspecified_msg_io = 0b101, message_out = 0b110, message_in = 0b111, /// Whether the target is sending rather than receiving, which is I/O. pub fn toInitiator(self: Phase) bool { return @intFromEnum(self) & 0b001 != 0; } }; /// What a target says when a command finishes, in the status phase. pub const Status = enum(u8) { good = 0x00, check_condition = 0x02, busy = 0x08, _, }; /// The sense key a REQUEST SENSE answers with, which is how a target says /// *why* the command before it failed. pub const SenseKey = enum(u8) { none = 0x00, not_ready = 0x02, medium_error = 0x03, illegal_request = 0x05, unit_attention = 0x06, data_protect = 0x07, _, }; /// The commands a disk answers. There are a great many more in the standard; /// these are the ones an Apple II SCSI Card's firmware issues, and anything /// else is refused with an illegal-request sense rather than guessed at. pub const Command = enum(u8) { test_unit_ready = 0x00, rezero_unit = 0x01, request_sense = 0x03, format_unit = 0x04, read_6 = 0x08, write_6 = 0x0a, seek_6 = 0x0b, inquiry = 0x12, mode_select_6 = 0x15, mode_sense_6 = 0x1a, start_stop_unit = 0x1b, send_diagnostic = 0x1d, read_capacity = 0x25, read_10 = 0x28, write_10 = 0x2a, _, /// How long this command's descriptor block is. The top three bits of the /// operation code are the group, and the group is what says the length: /// group 0 is six bytes and group 1 is ten, which covers everything a disk /// of this vintage is asked. pub fn length(self: Command) u8 { return switch (@intFromEnum(self) >> 5) { 0 => 6, 1, 2 => 10, 5 => 12, else => 6, }; } }; /// How big a block is. Everything here is a disk with 512-byte blocks, which /// is what ProDOS wants and what every Apple SCSI disk was formatted as. pub const block_size = 512; /// One disk on the bus: an image, an identity, and whatever command is in /// flight. /// /// A target is a state machine driven by the REQ/ACK handshake rather than by /// anything with a clock in it, which is what makes a SCSI disk cheap to /// model: nothing here has to know how fast the bus is going, only what the /// initiator has done and what to hand back next. pub const Disk = struct { /// The image, borrowed. Nothing here owns it, in the same way as the /// memory card's RAM and a card's firmware: whoever opened the file keeps /// it and writes it back. image: ?[]u8 = null, /// Whether it refuses to be written to, which a target answers with a /// data-protect sense rather than by ignoring the write. write_protected: bool = false, /// The command being carried out, and where in its descriptor block the /// bytes have got to. cdb: [12]u8 = @splat(0), cdb_len: u8 = 0, cdb_at: u8 = 0, /// The bytes going one way or the other. For a read or a write this is a /// window straight into the image -- blocks are contiguous there, so a /// request for forty of them is one slice -- and for the commands that /// answer with something made up it is `scratch`. data: []u8 = &.{}, data_at: usize = 0, /// Where a fabricated answer is built: an inquiry, a sense, a capacity. /// /// Big enough for the largest allocation length anything asks for rather /// than for the largest answer anything has: an Apple II SCSI Card's /// firmware asks INQUIRY for `$91` bytes, a hundred and forty-five, where /// the data it can use is the first thirty-six. A target hands over what /// was asked for and pads the rest with nothing, and a buffer sized to the /// answer instead of to the request cuts the transfer short. scratch: [256]u8 = @splat(0), /// What the last command came to, and why if it went wrong. status: Status = .good, sense: SenseKey = .none, /// The additional sense code and qualifier, which is the pair that says /// which kind of illegal request or medium error it was. sense_code: u8 = 0, sense_qualifier: u8 = 0, /// How many blocks the image holds, which is what READ CAPACITY answers. pub fn blocks(self: *const Disk) u32 { const image = self.image orelse return 0; return @intCast(image.len / block_size); } /// Where a command's descriptor block says to start and how much to move. /// A six-byte command carries twenty-one bits of address and eight of /// length, where a ten-byte one carries thirty-two and sixteen -- and a /// length of nought in a six-byte command means two hundred and fifty-six /// blocks, not none, which is the one place the two disagree about more /// than their widths. fn extent(self: *const Disk) struct { lba: u32, count: u32 } { if (self.cdb_len == 6) { const lba = (@as(u32, self.cdb[1] & 0x1f) << 16) | (@as(u32, self.cdb[2]) << 8) | self.cdb[3]; const count: u32 = if (self.cdb[4] == 0) 256 else self.cdb[4]; return .{ .lba = lba, .count = count }; } const lba = (@as(u32, self.cdb[2]) << 24) | (@as(u32, self.cdb[3]) << 16) | (@as(u32, self.cdb[4]) << 8) | self.cdb[5]; const count = (@as(u32, self.cdb[7]) << 8) | self.cdb[8]; return .{ .lba = lba, .count = count }; } /// Says the command failed, and why. The status phase carries the failure /// and a REQUEST SENSE afterwards carries the reason, which is why the two /// are set together and one of them is remembered. fn fail(self: *Disk, key: SenseKey, code: u8, qualifier: u8) void { self.status = .check_condition; self.sense = key; self.sense_code = code; self.sense_qualifier = qualifier; } /// Carries out whatever the descriptor block says, and returns the phase /// to go to next: data in, data out, or straight to status. fn execute(self: *Disk) Phase { self.data = &.{}; self.data_at = 0; // Anything but a REQUEST SENSE clears what the last failure left, so // that a sense taken after two commands answers about the first of // them and not about nothing. const command: Command = @enumFromInt(self.cdb[0]); if (command != .request_sense) { self.status = .good; self.sense = .none; self.sense_code = 0; self.sense_qualifier = 0; } if (self.image == null and command != .inquiry and command != .request_sense) { self.fail(.not_ready, 0x3a, 0x00); // medium not present return .status; } switch (command) { // Nothing to say but whether the disk is there, which the check // above has already said. .test_unit_ready, .rezero_unit, .seek_6, .start_stop_unit, .send_diagnostic => return .status, // Who the device is. Byte 0 is the peripheral type -- nought is a // direct-access device, which is what a disk is -- and the vendor // and product strings are space-padded fixed fields. .inquiry => { const wanted = @min(self.cdb[4], self.scratch.len); @memset(self.scratch[0..], 0); self.scratch[0] = 0x00; // direct access self.scratch[1] = 0x00; // not removable self.scratch[2] = 0x01; // ANSI SCSI-1 self.scratch[3] = 0x01; // response format self.scratch[4] = 31; // how much follows @memcpy(self.scratch[8..16], "ZIG65 "); @memcpy(self.scratch[16..32], "SCSI HARD DISK "); @memcpy(self.scratch[32..36], "1.0 "); self.data = self.scratch[0..wanted]; return .data_in; }, // Why the last command failed. The "extended" format, which is // what everything after the very first SCSI devices answers. .request_sense => { const wanted = @min(if (self.cdb[4] == 0) 4 else self.cdb[4], self.scratch.len); @memset(self.scratch[0..], 0); self.scratch[0] = 0x70; // current error, extended format self.scratch[2] = @intFromEnum(self.sense); self.scratch[7] = 10; // how much follows self.scratch[12] = self.sense_code; self.scratch[13] = self.sense_qualifier; self.status = .good; self.data = self.scratch[0..wanted]; return .data_in; }, // How big it is: the number of the *last* block rather than how // many there are, and then the size of one. .read_capacity => { const last = self.blocks() -| 1; @memset(self.scratch[0..8], 0); std.mem.writeInt(u32, self.scratch[0..4], last, .big); std.mem.writeInt(u32, self.scratch[4..8], block_size, .big); self.data = self.scratch[0..8]; return .data_in; }, // A mode sense with nothing in it but a header, which is enough // for a driver asking whether the disk is write protected: that // is bit 7 of the device-specific byte. .mode_sense_6 => { const wanted = @min(self.cdb[4], self.scratch.len); @memset(self.scratch[0..4], 0); self.scratch[0] = 3; // how much follows self.scratch[2] = if (self.write_protected) 0x80 else 0x00; self.data = self.scratch[0..@max(wanted, 4)]; return .data_in; }, .mode_select_6 => { self.data = self.scratch[0..@min(self.cdb[4], self.scratch.len)]; return if (self.data.len == 0) .status else .data_out; }, // A format that formats nothing. There is no surface here to lay // down and no defect list to keep: the image is as long as it was // and every block of it is already readable, which is what a // freshly formatted disk means to everything above this. .format_unit => return .status, .read_6, .read_10, .write_6, .write_10 => { const writing = command == .write_6 or command == .write_10; if (writing and self.write_protected) { self.fail(.data_protect, 0x27, 0x00); return .status; } const where = self.extent(); const image = self.image.?; const from = @as(usize, where.lba) * block_size; const bytes = @as(usize, where.count) * block_size; // "Logical block address out of range", which is the one thing // a driver reading past the end of a disk has to be told // rather than quietly given zeroes. if (from + bytes > image.len) { self.fail(.illegal_request, 0x21, 0x00); return .status; } self.data = image[from..][0..bytes]; return if (writing) .data_out else .data_in; }, _ => { self.fail(.illegal_request, 0x20, 0x00); // invalid command return .status; }, } } }; /// The bus: nine control signals, eight data lines, and up to eight devices /// arbitrating for them. /// /// Everything here is in the chip manual's convention -- true means asserted, /// whatever the voltage is -- and the initiator's half of it is driven by /// `ncr5380.zig`. The targets are driven from here, because a target reacts to /// what the initiator does rather than to a clock. pub const Bus = struct { /// What the initiator is asserting. sel: bool = false, ack: bool = false, atn: bool = false, rst: bool = false, /// What the initiator has put on the data lines, and whether it is driving /// them at all. out: u8 = 0, driving: bool = false, /// Whether the *initiator* is asserting BSY, which it does through /// arbitration and while it holds the bus. initiator_busy: bool = false, /// What the target is asserting. target_busy: bool = false, req: bool = false, phase: Phase = .data_out, /// The byte the target has on the data lines. in: u8 = 0, /// Which target is answering, if the bus is not free. selected: ?u3 = null, /// The devices, by identity. Nothing here owns them. devices: [8]?*Disk = @splat(null), /// Whether the target has taken or given the byte for the ACK that is up, /// so that the handshake completes once rather than once an access. handshaken: bool = false, /// BSY as anybody reading the bus sees it, which is either end asserting. pub fn busy(self: *const Bus) bool { return self.initiator_busy or self.target_busy; } /// The data lines as they stand: whoever is driving them. pub fn data(self: *const Bus) u8 { if (self.driving) return self.out; if (self.selected != null and self.phase.toInitiator()) return self.in; return 0; } /// What the reset line does, which is to put every device back and leave /// the bus free. It is a signal on the bus rather than a message to one /// device: "the RST signal will remain asserted until this bit is reset", /// and everything on the bus sees it (NCR Corporation, 1986, §6.2, p. 12). pub fn reset(self: *Bus) void { const devices = self.devices; self.* = .{ .devices = devices }; for (self.devices) |maybe| if (maybe) |disk| { disk.cdb_len = 0; disk.cdb_at = 0; disk.data = &.{}; disk.data_at = 0; // A reset is a unit attention, which is the target's way of saying // "something happened to me since you last spoke to me". disk.sense = .unit_attention; disk.sense_code = 0x29; disk.sense_qualifier = 0x00; }; } /// Brings the bus to rest after the initiator has changed something. /// /// Two things happen here and they are the whole of the protocol as far as /// the targets are concerned: a device notices it has been selected, and a /// device that is selected moves one byte per REQ/ACK pair. pub fn settle(self: *Bus) void { if (self.rst) { self.reset(); return; } // Selection: SEL up, BSY down, and this device's bit on the data // lines. The initiator's own bit is there too -- that is what // arbitration put there -- so the target looks for its own and ignores // the rest. if (self.selected == null and self.sel and !self.target_busy and self.driving) { for (self.devices, 0..) |maybe, id| { const disk = maybe orelse continue; if (self.out & (@as(u8, 1) << @intCast(id)) == 0) continue; if (!self.initiator_busy) { self.selected = @intCast(id); self.target_busy = true; disk.cdb_at = 0; disk.cdb_len = 0; disk.data = &.{}; disk.data_at = 0; self.phase = .command; self.req = false; self.handshaken = false; return; } } } // A selection ends when the initiator drops SEL, and from then on the // target asks for the command a byte at a time. const id = self.selected orelse return; const disk = self.devices[id].?; if (self.sel) return; // ACK going away is what arms the next byte. This has to come first: // dropping ACK also leaves REQ down for an instant, and asking for the // next byte before forgetting the last one would leave the handshake // latched and every byte after the first would be swallowed. if (!self.ack) self.handshaken = false; if (!self.req and !self.ack) { self.startRequest(disk); return; } if (self.req and self.ack and !self.handshaken) { self.transfer(disk); self.handshaken = true; self.req = false; } } /// Asks for the next byte, or finishes if there is nothing left to ask /// for. This is where the phases follow one another. fn startRequest(self: *Bus, disk: *Disk) void { switch (self.phase) { .command => { self.req = true; }, .data_in, .data_out => { if (disk.data_at < disk.data.len) { if (self.phase == .data_in) self.in = disk.data[disk.data_at]; self.req = true; } else { self.phase = .status; self.in = @intFromEnum(disk.status); self.req = true; } }, .status => { self.req = true; }, .message_in => { self.req = true; }, else => {}, } } /// One byte, whichever way it is going, and then whatever that byte /// finished. fn transfer(self: *Bus, disk: *Disk) void { switch (self.phase) { .command => { if (disk.cdb_at == 0) disk.cdb_len = @as(Command, @enumFromInt(self.out)).length(); if (disk.cdb_at < disk.cdb.len) disk.cdb[disk.cdb_at] = self.out; disk.cdb_at += 1; if (disk.cdb_at >= disk.cdb_len) self.phase = disk.execute(); if (self.phase == .status) self.in = @intFromEnum(disk.status); }, .data_in => { disk.data_at += 1; }, .data_out => { if (disk.data_at < disk.data.len) disk.data[disk.data_at] = self.out; disk.data_at += 1; }, // The status byte is followed by one message, COMMAND COMPLETE, // and then the target lets go of the bus. .status => { self.phase = .message_in; self.in = 0x00; // COMMAND COMPLETE }, .message_in => { self.selected = null; self.target_busy = false; self.req = false; self.phase = .data_out; }, else => {}, } } };