"""The SF-7000 Super Control Station: 64 KB of RAM, an IPL ROM and a 3-inch disk drive. The unit plugs into the SC-3000's cartridge slot and brings its own hardware at ports $E0-$FF, where the SC-3000 decodes nothing (sc3000h section 4). What is here: - 64 KB of RAM over the whole address space, with the 8 KB IPL ROM over $0000-$3FFF until the program switches it out ("On power-up, the first 16K is for ROM and the remaining 48K is for RAM. The ROM can be switched out through the SF-7000's PPI", sc3000h section 3); - a second 8255 at $E4-$E7 whose pins run the drive and the ROM switch; - a uPD765A floppy disk controller at $E0 (status) and $E1 (data), polled: its INT output goes to an 8255 pin and not to the Z80. Sources. The port addresses and the 8255's pin list are MAME 0.285's (``src/mame/sega/sg1000.cpp``, quoted in :class:`SuperControlStation`); MAME is a detector here, not a judge, and no hardware document for the unit is in the reference library. The controller follows NEC's uPD765 data sheet of December 1978 (``reference/manuals/NEC_uPD765_Data_Sheet_Dec78.pdf``, "the data sheet" below) for its phases, commands and status bits; the SF-7000's chip is the later uPD765A, whose own data sheet is not pinned. How the machine *uses* all of it is read from the IPL ROM itself (addresses given as ``IPL $xxxx``), which is the one hardware-made witness on hand. Not here: the 8251 serial port at $E8-$E9 and the Centronics printer port (port B and PC7 of the 8255). Nothing is attached to either. """ from __future__ import annotations from collections.abc import Callable from .io import PPI8255 CPU_CLOCK = 3_579_545 # The disk: 40 tracks of 16 sectors of 256 bytes on one side, 163,840 bytes, track # after track. The IPL's own format routine writes exactly this (IPL $11F2: tracks # 0 to $27, sectors $01 to $10, N = 1, head 0). TRACKS = 40 SECTORS = 16 SECTOR_SIZE = 256 DISK_SIZE = TRACKS * SECTORS * SECTOR_SIZE # The disk turns at 300 rpm and holds 6,250 bytes a turn at 250 kbit/s MFM, so a # byte passes the head every 32 us. The IPL checks the speed before it will boot # (IPL $109B: it times the gap between two index pulses and accepts about 180 to # 220 ms), so the rotation is modelled, in CPU cycles. REVOLUTION = CPU_CLOCK // 5 CELLS = 6_250 # The index pulse's width. No source gives the drive's; 2 ms is MAME's floppy # drives' (1% of a turn). The IPL only needs it to be much shorter than a turn. INDEX_PULSE = REVOLUTION // 100 # An IBM System 34 (MFM) track as the uPD765 formats it: gap 4a (80 bytes), sync # (12), index mark (4), gap 1 (50); then for each sector sync (12), ID mark (4), the # four ID bytes, CRC (2), gap 2 (22), sync (12), data mark (4), the data, CRC (2) and # gap 3. Gap 3 is the IPL's format command's ($2A, IPL $1225). TRACK_LEAD = 80 + 12 + 4 + 50 ID_END = 12 + 4 + 4 + 2 DATA_START = ID_END + 22 + 12 + 4 SECTOR_SPAN = DATA_START + SECTOR_SIZE + 2 + 0x2A # Main status register bits (the data sheet, "Main Status Register"). MSR_RQM = 0x80 # request for master: the data register is ready MSR_DIO = 0x40 # direction: 1 = controller to processor MSR_EXM = 0x20 # execution phase in non-DMA mode MSR_CB = 0x10 # controller busy: a command is in progress MSR_D0B = 0x01 # drive 0 is seeking # Status register 0, 1 and 3 bits used here. ST0_ABNORMAL = 0x40 ST0_INVALID = 0x80 ST0_SEEK_END = 0x20 ST0_EQUIPMENT_CHECK = 0x10 ST0_NOT_READY = 0x08 ST1_END_OF_CYLINDER = 0x80 ST1_NO_DATA = 0x04 ST3_READY = 0x20 ST3_TRACK_0 = 0x10 # Command bytes by opcode (low five bits): the ones this machine's software uses. COMMAND_LENGTH = {0x03: 3, 0x04: 2, 0x05: 9, 0x06: 9, 0x07: 2, 0x08: 1, 0x0A: 2, 0x0D: 6, 0x0F: 3} SPECIFY, SENSE_DRIVE, WRITE_DATA, READ_DATA = 0x03, 0x04, 0x05, 0x06 RECALIBRATE, SENSE_INTERRUPT, READ_ID, FORMAT_TRACK, SEEK = 0x07, 0x08, 0x0A, 0x0D, 0x0F COMMAND, EXECUTION, RESULT = range(3) class UPD765: """NEC's uPD765A with one single-sided drive, in non-DMA mode. The processor writes a command's bytes to the data register, exchanges data with it during the execution phase one byte at a time (each when the main status register shows RQM), then reads the result bytes. The INT pin rises for each byte of the execution phase, at the start of the result phase, and when a seek ends; the machine reads it on an 8255 pin (:class:`SuperControlStation`). Time comes from ``now()``, in CPU cycles, and everything is worked out when the processor looks: a seek ends at a known time, and the bytes of a sector are ready as their places on the turning disk pass the head. Left out, each for want of software that would show it: - overrun: a byte not collected before the next one arrives is not lost; - the head load and unload times of SPECIFY (the step rate is kept); - the commands the IPL never sends (read track, the deleted-data pair, the scans), which are answered as invalid; - CRC errors and write protection: an image has neither; - the interrupts a real chip raises after reset as it polls the drives' ready lines. """ def __init__(self, now: Callable[[], int]) -> None: self.now = now self.disk: bytearray | None = None self.selected = False # the drive's /INUSE line self.motor = False self.spin_from = 0 # when the motor started: the index hole is under the sensor self.track = 0 # where the head really is self.step_cycles = CPU_CLOCK * 2 // 1000 self.reset() def reset(self) -> None: """The RESET pin: back to the command phase, nothing pending.""" self.phase = COMMAND self.command: list[int] = [] self.result: list[int] = [] self.result_irq = False self.pcn = 0 # the cylinder the controller believes the head is on self.seek_until: int | None = None self.seek_to = 0 self.seek_status: int | None = None # ST0 waiting for SENSE INTERRUPT STATUS self.byte_at: int | None = None # execution: when the next byte is ready self.ends_at: int | None = None # execution: when it ends by itself self.ending: list[int] = [] # ... and the result it ends with self.reading = False self.sector = 0 # execution: the sector in hand (R) self.offset = 0 # ... and the byte within it self.sector_start = 0 # ... and when its first byte was ready self.format_ids: list[int] = [] # -- the drive -------------------------------------------------------------- def set_motor(self, on: bool) -> None: if on and not self.motor: self.spin_from = self.now() self.motor = on @property def ready(self) -> bool: return self.selected and self.motor and self.disk is not None @property def index(self) -> bool: """The drive's index pulse: true while the index hole passes the sensor.""" return self.ready and (self.now() - self.spin_from) % REVOLUTION < INDEX_PULSE def _next_pass(self, cell: int, after: int) -> int: """When byte ``cell`` of the track has next passed the head, at or after ``after``.""" offset = (cell + 1) * REVOLUTION // CELLS turns = max(0, -(-(after - self.spin_from - offset) // REVOLUTION)) return self.spin_from + turns * REVOLUTION + offset def _sector_address(self, sector: int) -> int: return (self.track * SECTORS + sector - 1) * SECTOR_SIZE # -- the pins --------------------------------------------------------------- @property def irq(self) -> bool: self._poll() if self.phase == EXECUTION: return self._byte_ready() return self.result_irq or self.seek_status is not None def terminal_count(self) -> None: """A pulse on TC: the transfer in hand is the last one. The result names the sector after the last one transferred: "R + 1", or cylinder + 1 and sector 1 past the last sector of the track (data sheet, the table of ID information at the result phase). """ if self.phase != EXECUTION or self.command[0] & 0x1F not in (READ_DATA, WRITE_DATA): return cylinder, head, _, size = self.command[2:6] sector = self.sector if self.offset and not self.reading and self.disk is not None: # "the remainder of the data field is filled with 00 (zeros)" start = self._sector_address(sector) self.disk[start + self.offset : start + SECTOR_SIZE] = bytes(SECTOR_SIZE - self.offset) if self.offset or self.ends_at is not None: sector += 1 if sector > self.command[6]: cylinder, sector = cylinder + 1, 1 self._finish([self.command[1] & 7, 0, 0, cylinder, head, sector, size]) # -- the registers ---------------------------------------------------------- def read_status(self) -> int: self._poll() seeking = MSR_D0B if self.seek_until is not None else 0 if self.phase == COMMAND: return MSR_RQM | (MSR_CB if self.command else 0) | seeking if self.phase == RESULT: return MSR_RQM | MSR_DIO | MSR_CB | seeking status = MSR_CB | MSR_EXM | seeking if self._byte_ready(): status |= MSR_RQM | (MSR_DIO if self.reading else 0) return status def read_data(self) -> int: self._poll() if self.phase == RESULT: self.result_irq = False value = self.result.pop(0) if not self.result: self.phase = COMMAND return value if self.phase == EXECUTION and self.reading and self._byte_ready(): assert self.disk is not None value = self.disk[self._sector_address(self.sector) + self.offset] self._byte_done() return value return 0xFF def write_data(self, value: int) -> None: self._poll() if self.phase == COMMAND: self.command.append(value) if len(self.command) == COMMAND_LENGTH.get(self.command[0] & 0x1F, 1): self._execute() elif self.phase == EXECUTION and not self.reading and self._byte_ready(): if self.command[0] & 0x1F == FORMAT_TRACK: self.format_ids.append(value) self._format_byte_done() else: assert self.disk is not None self.disk[self._sector_address(self.sector) + self.offset] = value self._byte_done() # -- inside ----------------------------------------------------------------- def _byte_ready(self) -> bool: return self.byte_at is not None and self.now() >= self.byte_at def _poll(self) -> None: """Bring the controller up to now: a seek that has ended, a command that has.""" now = self.now() if self.seek_until is not None and now >= self.seek_until: self.seek_until = None self.track = max(0, min(TRACKS - 1, self.track + self.seek_to - self.pcn)) self.pcn = self.seek_to self.seek_status = ST0_SEEK_END if self.phase == EXECUTION and self.ends_at is not None and now >= self.ends_at: self._finish(self.ending) def _finish(self, result: list[int]) -> None: self.phase = RESULT self.result = list(result) self.result_irq = True self.byte_at = self.ends_at = None self.command = [] def _execute(self) -> None: opcode = self.command[0] & 0x1F unit = self.command[1] & 7 if len(self.command) > 1 else 0 if opcode == SPECIFY: # The step rate: "from 1 to 16 ms in increments of 1 ms (F = 1 ms, E = # 2 ms ...)" at 8 MHz, and "if the clock was reduced to 4 MHz ... all # time intervals are increased by a factor of 2" (the data sheet, # SPECIFY). This chip runs at 4 MHz (MAME: 16 MHz / 4). self.step_cycles = (16 - (self.command[1] >> 4)) * 2 * CPU_CLOCK // 1000 self.command = [] elif opcode == SENSE_DRIVE: status = unit | (ST3_READY if self.ready else 0) | (0 if self.track else ST3_TRACK_0) self._finish([status]) elif opcode == SENSE_INTERRUPT: if self.seek_status is None: self._finish([ST0_INVALID]) else: self._finish([self.seek_status, self.pcn]) self.seek_status = None self.result_irq = False # this command's own result raises no interrupt elif opcode in (SEEK, RECALIBRATE): self._start_seek(0 if opcode == RECALIBRATE else self.command[2], opcode == RECALIBRATE) self.command = [] elif opcode in (READ_DATA, WRITE_DATA): self._start_transfer(opcode == READ_DATA) elif opcode == READ_ID: self._start_read_id() elif opcode == FORMAT_TRACK: self._start_format() else: self._finish([ST0_INVALID]) self.result_irq = False def _start_seek(self, cylinder: int, recalibrate: bool) -> None: """SEEK and RECALIBRATE: one step pulse per step-rate time, then an interrupt. "If an FDD is in a NOT READY state at the beginning of the command execution phase or during the seek operation, then the NR (NOT READY) flag is set in Status Register 0 to a 1 (high), and the command is terminated" (the data sheet, SEEK). RECALIBRATE steps outward until the drive's track 0 signal, whatever the controller believed. """ if not self.ready: self.seek_status = ST0_ABNORMAL | ST0_SEEK_END | ST0_NOT_READY return if recalibrate: self.pcn = self.track self.seek_to = cylinder self.seek_until = self.now() + abs(cylinder - self.pcn) * self.step_cycles def _start_transfer(self, reading: bool) -> None: """READ DATA and WRITE DATA: find the sector, then a byte every 32 us. The controller reads ID fields until one matches the command's C, H, R and N. Every sector of an image is where the format put it, so the wait is the time for that sector's data field to come round. "If the FDC detects the Index Hole twice without finding the right sector, (indicated in "R"), then the FDC sets the ND (No Data) flag in Status Register 1 to a 1 (high), and terminates the Read Data Command" (the data sheet, READ DATA). """ cylinder, head, sector, size = address = self.command[2:6] unit = self.command[1] & 7 now = self.now() self.phase = EXECUTION self.reading = reading self.byte_at = self.ends_at = None if not self.ready: self._finish([ST0_ABNORMAL | ST0_NOT_READY | unit, 0, 0, *address]) elif cylinder != self.track or head or not 1 <= sector <= SECTORS or size != 1: self.ends_at = self._next_pass(0, self._next_pass(0, now) + 1) self.ending = [ST0_ABNORMAL | unit, ST1_NO_DATA, 0, *address] else: self.sector, self.offset = sector, 0 cell = TRACK_LEAD + (sector - 1) * SECTOR_SPAN + DATA_START self.sector_start = self.byte_at = self._next_pass(cell, now) def _byte_done(self) -> None: """One byte of a sector went across: the next, the next sector, or the end. After the sector named as the last of the track (EOT) the controller wants another and has none: "When the FDC tries to access a Sector beyond the final Sector of a Cylinder, this flag is set" (the data sheet, Status Register 1, EN), unless TC came first. """ self.offset += 1 if self.offset < SECTOR_SIZE: self.byte_at = self.sector_start + self.offset * REVOLUTION // CELLS return unit, cylinder, head, _, size, last = self.command[1:7] after_crc = self.sector_start + (SECTOR_SIZE + 2) * REVOLUTION // CELLS if self.sector >= last: self.byte_at = None self.ends_at = after_crc self.ending = [ ST0_ABNORMAL | unit & 7, ST1_END_OF_CYLINDER, 0, cylinder, head, self.sector, size ] # fmt: skip else: self.sector += 1 self.offset = 0 self.sector_start += SECTOR_SPAN * REVOLUTION // CELLS self.byte_at = self.sector_start def _start_read_id(self) -> None: """READ ID: the first ID field to pass the head.""" unit = self.command[1] & 7 self.phase = EXECUTION self.reading = True self.byte_at = None if not self.ready: self._finish([ST0_ABNORMAL | ST0_NOT_READY | unit, 0, 0, 0, 0, 0, 0]) return now = self.now() passes = [ (self._next_pass(TRACK_LEAD + index * SECTOR_SPAN + ID_END, now), index + 1) for index in range(SECTORS) ] self.ends_at, sector = min(passes) self.ending = [unit, 0, 0, self.track, 0, sector, 1] def _start_format(self) -> None: """FORMAT TRACK: from the index hole, four ID bytes (C, H, R, N) a sector. The bytes are asked for as each sector's place comes round, and each sector named on this track is filled with the command's filler byte. """ unit, size, count = self.command[1] & 7, self.command[2], self.command[3] self.phase = EXECUTION self.reading = False self.byte_at = None self.format_ids = [] if not self.ready: self._finish([ST0_ABNORMAL | ST0_NOT_READY | unit, 0, 0, 0, 0, 0, size]) elif count: self.sector_start = self._next_pass(0, self.now()) self.byte_at = self.sector_start + TRACK_LEAD * REVOLUTION // CELLS else: self._finish([unit, 0, 0, 0, 0, 0, size]) def _format_byte_done(self) -> None: unit, size, count, gap, filler = self.command[1] & 7, *self.command[2:6] sectors, within = divmod(len(self.format_ids), 4) if sectors < count: span = DATA_START + (128 << size) + 2 + gap cell = TRACK_LEAD + sectors * span + within self.byte_at = self.sector_start + cell * REVOLUTION // CELLS return assert self.disk is not None for index in range(count): cylinder, head, sector, id_size = self.format_ids[index * 4 : index * 4 + 4] if cylinder == self.track and not head and 1 <= sector <= SECTORS and id_size == 1: start = self._sector_address(sector) self.disk[start : start + SECTOR_SIZE] = bytes([filler]) * SECTOR_SIZE self.byte_at = None self.ends_at = self._next_pass(0, self.now()) self.ending = [unit, 0, 0, 0, 0, 0, size] class SuperControlStation: """The unit's 8255, IPL ROM switch and disk controller, at ports $E0-$FF. The ports, as MAME 0.285 maps them: $E0 the controller's status and $E1 its data; $E4-$E7 the 8255 (ports A, B, C and control). The 8255's pins, from the same source: - PA0 "INT from FDC", PA1 "BUSY from Centronics printer", PA2 "INDEX from FDD"; - PB, the printer's data; - PC0 "/INUSE signal to FDD", PC1 "/MOTOR ON signal to FDD", PC2 "TC signal to FDC", PC3 "RESET signal to FDC", PC6 "/ROM SEL (switch between IPL ROM and RAM)", PC7 "/STROBE to Centronics printer". The IPL agrees wherever it can be asked: it sets mode $90 (A in, B and C out; IPL $00EB), waits on PA0 after every command, times PA2 with the motor on, and pulses PC2 after the last byte of a sector. PA2 is high *during* the index pulse: the IPL's speed check measures the time PA2 is low and wants a turn's worth of it. Until the program sets the mode, port C's pins are inputs; MAME notes "/ROM SEL must be active after reset" (it reads the floating pins as $8F), which is how the machine can start in its ROM at all. """ def __init__(self, ipl: bytes, now: Callable[[], int], disk: bytearray | None = None) -> None: if disk is not None and len(disk) != DISK_SIZE: raise ValueError(f"an SF-7000 disk image is {DISK_SIZE} bytes, not {len(disk)}") self.ipl = bytes(ipl) self.fdc = UPD765(now) self.fdc.disk = disk self.ppi = PPI8255() self._tc = False self._apply_port_c() @property def port_c(self) -> int: """Port C's pins: the latch when an output, MAME's floating levels when not.""" return self.ppi.port_c(floating=0x8F) @property def rom_selected(self) -> bool: return not self.port_c & 0x40 def _apply_port_c(self) -> None: pins = self.port_c fdc = self.fdc fdc.selected = not pins & 0x01 fdc.set_motor(not pins & 0x02) if pins & 0x08: fdc.reset() elif pins & 0x04 and not self._tc: fdc.terminal_count() self._tc = bool(pins & 0x04) def read(self, port: int) -> int: if port == 0xE0: return self.fdc.read_status() if port == 0xE1: return self.fdc.read_data() if port == 0xE4: if not self.ppi.a_is_input: return self.ppi.latches[0] return self.fdc.irq | self.fdc.index << 2 # PA1: no printer, never busy if port == 0xE5: return self.ppi.latches[1] if port == 0xE6: return self.port_c return 0xFF # the 8255's control word, the 8251 and everything undecoded def write(self, port: int, value: int) -> None: if port == 0xE1: self.fdc.write_data(value) elif 0xE4 <= port <= 0xE7: self.ppi.write(port, value) self._apply_port_c()