# SPDX-License-Identifier: MIT AND ISC """The gate array's registers: the main CPU's $A12000-$A1203F and the sub CPU's $FF8000-$FF81FF, the word-RAM hand-over, the timer, the stopwatch and the sub CPU's interrupt controller. Every rule names its source. ``p.N`` is Sega's *Mega-CD Hardware Manual* (1991) as read in docs/manual-registers.md (DOC). ``KRIKzz`` is mcd-verificator's prose notes (``notes/random notes.txt``), his findings on real consoles (DOC: a community document reporting hardware findings). ``ares`` is ares 9408cb4 (``ares/md/mcd``, ISC; notice in NOTICE), read and used for behaviour the manual leaves open (OBSERVED: an emulator fact, not a hardware fact). ``TEST ROM`` marks a rule a mcd-verificator row settles (its author ran it on a CDX and a Mega-CD 2). Byte and word writes: the 68000 drives a byte on both halves of the data bus (Motorola M68000 UM 5.1.2), so a byte write reaches a register as ``value * $0101`` with only one strobe (``upper`` or ``lower``). Registers the manual draws as eight bits in one half ($A1200E's CFM, $FF8002, $FF800E's CFS, $FF8030, $FF804C) take their byte from the data lines whichever strobe is asserted: ares ("8-bit register mapped into 16-bit gate array"), OBSERVED. """ from __future__ import annotations from typing import TYPE_CHECKING from .wiring import unplugged if TYPE_CHECKING: from .cdc import CDC from .cdd import CDD from .graphics import Graphics #: Sub CPU clocks a timer or stopwatch count takes: 30.72 us at 12.5 MHz (p.28, p.30, #: p.59; 30.72 us x 12.5 MHz = 384). DOC. TICK = 384 #: Sub CPU clocks from the start of the main CPU's write to $A12000 (the clock the #: board gives an access) until a level-2 request can be taken at the sub CPU's next #: instruction boundary. The parts: the write's data is latched at the end of the #: 68000's write cycle, about 3.5 of its 4 clocks after the start (Motorola M68000 UM, #: write-cycle timing; about 6 sub clocks); the request crosses from the main CPU's #: clock to the sub CPU's (two crystals, p.iv); the sub 68000 synchronises its IPL #: inputs and decides on an interrupt before an instruction's last bus cycle. None of #: the last two is given in clocks in a document here, so the total is FITTED to #: mcd-verificator's IRQ TEST row (TEST ROM): the row passes for 9-19 and fails with #: "127 ERROR 06" at 8 or less (the main CPU posts a command that clears the sub CPU's #: interrupt counter, then fires level 2 while the sub CPU is still carrying it out) #: and with "ERROR 0A" at 20 or more. 14 is the middle. HYPOTHESIS for the mechanism. IFL2_LATENCY = 14 #: Sub CPU clocks RES0 reads 0 after the sub CPU writes 0 to it: "100 ms after a reset, #: the periphery becomes operable and RES0 becomes '1'" (p.22). DOC, "approx.". PERIPHERY_RESET = 1_250_000 class GateArray: """Register state of both sides. :class:`~segacd_python.megacd.MegaCD` owns it and the buses that reach it.""" def __init__(self, cdc: CDC, cdd: CDD, graphics: Graphics) -> None: self.cdc = cdc self.cdd = cdd self.graphics = graphics #: Set by the device: called with True when SRES puts the sub CPU into reset, #: False when it lets it run. self.on_sub_reset = unplugged self.power_on() def power_on(self) -> None: # $A12000 = $0002 at power-on: SBRQ=1, SRES=0 (p.21). DOC. self.sres = 0 # 1 = run self.sbrq = 1 # $A12002 / $FF8002 = $0001: 2M, main CPU owns word RAM (p.21, p.24). DOC. self.mode = 0 # MODE: 0 = 2M, 1 = 1M #: 2M owner: 1 when the RAM has been given to the sub CPU (main's DMNA=1 write), #: 0 when it is the main CPU's (sub's RET=1 write). ares ``wramSwitch``, OBSERVED; #: the reads it gives are p.23-25's. DOC. self.given_to_sub = 0 #: RET as the sub CPU last wrote it; in 1M the bank the main CPU has (p.24). DOC. self.ret = 1 #: A swap requested by the main CPU (1M DMNA reads 1 until the sub CPU changes #: RET). KRIKzz: "0 to dmna to submit request ... sub should invert ret to clear #: this flag" (DOC); p.57's main-side table agrees (write 0 = swap request). self.swap_request = 0 self.priority = 0 # PM1-0 self.write_protect = 0 # WP7-0, in $200-byte units (p.57). DOC. self.prg_bank = 0 # BK1-0 # Communication (p.28-29, p.59-60). Power-on 0 (p.21). DOC. self.cfm = 0 self.cfs = 0 self.command = [0] * 8 self.status = [0] * 8 #: $A12006, "After a reset, $A12006 is set to -1" (p.58, p.21). DOC. self.hint_vector = 0xFFFF self.reset_sub_side() def reset_sub_side(self) -> None: """What the forced reset initialises: "Refresh/Timer/Stop watch/DMA/Rotation/ Interrupt/CDD communication/Sub-code reception/Fader" (p.56-57). DOC. Power-on does too.""" self.led = 0 # bits 9-8 of $FF8000; "Power-on and a reset ... '0'" (p.22). DOC. self.periphery_reset = 0 # sub clocks left before RES0 reads 1 self.timer_reload = 0 # $FF8030 as written self.timer_count = 0 self.stopwatch = 0 self.divider = 0 # sub clocks into the current 30.72 us count #: Interrupt enables, IEN1-6 at bits 1-6 of $FF8032 (p.30). DOC. self.enable = 0 #: Pending requests by level, bit n = level n. A request is latched only while #: its level is enabled, and the acknowledge clears it: ares (``IRQ::raise``, #: ``lower``), OBSERVED. The manual does not say (p.30, p.56). self.pending = 0 #: Level-sensitive sources (the CDC's INT5): bit n while the source holds it. self.lines = 0 #: Requests not yet at the IPL pins (``IFL2_LATENCY``): bit n, and the sub clock #: at which each becomes visible. self.arriving = 0 self.arrives_at = [0] * 8 #: The sub clock of the main CPU's access being served (set by the device). self.now = 0 self.fader = 0 self.graphics.reset() self.cdd.reset_host() def __setstate__(self, state: dict[str, object]) -> None: """A machine saved before the request latency existed loads with none pending.""" state.setdefault("arriving", 0) state.setdefault("arrives_at", [0] * 8) state.setdefault("now", 0) self.__dict__.update(state) # -- interrupts ----------------------------------------------------------- def request(self, level: int) -> None: if self.enable & (1 << level): self.pending |= 1 << level def set_line(self, level: int, active: bool) -> None: """A source that holds its request while its condition lasts (the LC8951's INT pin follows its flags, LC8951 ยง11.3). Masked by the enable like the rest.""" if active: self.lines |= 1 << level else: self.lines &= ~(1 << level) def request_later(self, level: int, at: int) -> None: """A request that reaches the IPL pins at sub clock ``at`` (latched now).""" if self.enable & (1 << level): self.arriving |= 1 << level self.arrives_at[level] = at def ipl(self, now: int | None = None) -> int: """The level on the sub CPU's IPL pins at sub clock ``now``: the highest pending request (``now`` None: every latched request counts).""" if self.arriving: for level in range(1, 7): bit = 1 << level if self.arriving & bit and (now is None or self.arrives_at[level] <= now): self.arriving &= ~bit self.pending |= bit pending = self.pending | (self.lines & self.enable) return pending.bit_length() - 1 if pending else 0 def acknowledge(self, level: int) -> None: self.pending &= ~(1 << level) self.arriving &= ~(1 << level) # -- time ----------------------------------------------------------------- def run(self, clocks: int) -> None: """``clocks`` sub CPU clocks of the timer, the stopwatch and RES0's delay.""" if self.periphery_reset: self.periphery_reset = max(0, self.periphery_reset - clocks) self.divider += clocks while self.divider >= TICK: self.divider -= TICK self.tick() def tick(self) -> None: """One 30.72 us count.""" # Stopwatch: 12 bits, wraps from 4095 to 0 (p.28). DOC. self.stopwatch = (self.stopwatch + 1) & 0xFFF # Timer: counts down from n; at 0, INT3 and the count starts again, so the # interval is (n+1) counts; 0 disables (p.30). DOC. if self.timer_reload: if self.timer_count == 0: self.timer_count = self.timer_reload self.request(3) else: self.timer_count -= 1 # -- word RAM ownership --------------------------------------------------- def main_owns_2m(self) -> bool: return self.mode == 0 and not self.given_to_sub def sub_owns_2m(self) -> bool: return self.mode == 0 and bool(self.given_to_sub) def memory_mode_bits(self) -> int: """MODE, DMNA and RET as both sides read them (p.23-25, p.57). DOC. In 2M DMNA reads 1 once the RAM is the sub CPU's and RET 1 once it is the main CPU's; in 1M RET is the main CPU's bank and DMNA the pending swap.""" if self.mode == 0: dmna, ret = self.given_to_sub, 1 - self.given_to_sub else: dmna, ret = self.swap_request, self.ret return (self.mode << 2) | (dmna << 1) | ret # -- the main CPU's registers, $A12000-$A1203F ----------------------------- def main_read(self, offset: int) -> int: """The word at $A12000 + ``offset`` (even, 0-$3E).""" if offset == 0x00: # IEN2 is a read-only copy of the sub side's mask (p.56). DOC. IFL2 reads the # pending level-2 request (ares, OBSERVED; p.56's read meanings are inverted # wording of the same state and are taken as "1 = requested"). return ( ((self.enable >> 2) & 1) << 15 | (((self.pending | self.arriving) >> 2) & 1) << 8 | self.sbrq << 1 | self.sres ) if offset == 0x02: return self.write_protect << 8 | self.prg_bank << 6 | self.memory_mode_bits() if offset == 0x04: # EDT, DSR, DD2-0; no UBR on this side (p.58). DOC. cdc = self.cdc return cdc.edt << 15 | cdc.dsr << 14 | cdc.destination << 8 if offset == 0x06: return self.hint_vector if offset == 0x08: return self.cdc.host_read(main=True) if offset == 0x0C: return self.stopwatch if offset == 0x0E: return self.cfm << 8 | self.cfs if 0x10 <= offset < 0x20: return self.command[(offset - 0x10) >> 1] if 0x20 <= offset < 0x30: return self.status[(offset - 0x20) >> 1] # $A1200A is "Reserved by the system" (p.59); $A12030-$A1203F are not in the # manual. They read 0: HYPOTHESIS. return 0 def main_write(self, offset: int, data: int, upper: bool, lower: bool) -> None: if offset == 0x00: if upper and data & 0x0100: # IFL2: "INT Level 2 is generated (When IEN2=1)" (p.56). DOC. It reaches # the sub CPU IFL2_LATENCY clocks after the write (FITTED). self.request_later(2, self.now + IFL2_LATENCY) if lower: self._write_reset_bits(data & 3) elif offset == 0x02: if upper: self.write_protect = data >> 8 if lower: self.prg_bank = (data >> 6) & 3 # DMNA. 2M: 1 "returns the 2M RAM to the SUB-CPU" (p.57). 1M: 0 is the # swap request (p.57; KRIKzz). DOC. A 0 written in 2M is remembered as # the request too and shows as DMNA=1 when 1M is chosen: ares, OBSERVED, # and KRIKzz's "dmna bit will be 1 if mem mode switched from 2m to 1m". if data & 2: self.given_to_sub = 1 else: self.swap_request = 1 elif offset == 0x06: # The low word of the level-4 vector (p.58). Word access only per the # manual; a byte write sets its half (ares, OBSERVED). if upper: self.hint_vector = (self.hint_vector & 0x00FF) | (data & 0xFF00) if lower: self.hint_vector = (self.hint_vector & 0xFF00) | (data & 0x00FF) elif offset == 0x08: # $A12008 is read-only (p.58), but a write still takes a word from the host # register as a read does: CDC DMA3 writes it 588 times in a 1,176-word # main-CPU transfer and gets past that step (60 -> 62) only so (TEST ROM; # the mechanism, the gate array strobing the CDC on any access, is a # HYPOTHESIS). The sub CPU's $FF8008 does the same (sub_write). self.cdc.host_read(main=True) elif offset == 0x0E: # CFM, the main CPU's flags (p.59); its byte from the data lines, either # strobe (module docstring). CFS is read-only here. self.cfm = data >> 8 elif 0x10 <= offset < 0x20: index = (offset - 0x10) >> 1 word = self.command[index] if upper: word = (word & 0x00FF) | (data & 0xFF00) if lower: word = (word & 0xFF00) | (data & 0x00FF) self.command[index] = word # $A12004, $A1200C and the status words are read-only (p.58-60). DOC. def _write_reset_bits(self, bits: int) -> None: """SRES (bit 0: 0 holds the sub CPU in reset, 1 lets it run) and SBRQ (bit 1: 1 requests its bus), levels both (p.56). DOC. While SRES=0 the request reads 1: ares ("asserting reset forces busreq"), OBSERVED; it fits p.21's power-on $0002.""" sres = bits & 1 sbrq = (bits >> 1) & 1 if sres else 1 was_running = self.sres self.sres = sres self.sbrq = sbrq if was_running and not sres: self.on_sub_reset(True) elif sres and not was_running: self.on_sub_reset(False) # -- the sub CPU's registers, $FF8000-$FF81FF ------------------------------- def sub_read(self, offset: int) -> int: """The word at $FF8000 + ``offset`` (even, 0-$1FE).""" if offset == 0x00: # LEDs at bits 9-8 (red 8, green 9: ares, OBSERVED; the scan does not show # which, p.22); version 0 in bits 7-4 (ares, OBSERVED); RES0 (p.22). DOC. return self.led << 8 | (0 if self.periphery_reset else 1) if offset == 0x02: return self.write_protect << 8 | self.priority << 3 | self.memory_mode_bits() if offset == 0x04: cdc = self.cdc return cdc.edt << 15 | cdc.dsr << 14 | cdc.destination << 8 | cdc.address if offset == 0x06: return self.cdc.read_register() if offset == 0x08: return self.cdc.host_read(main=False) if offset == 0x0A: return self.cdc.dma_address >> 3 if offset == 0x0C: return self.stopwatch if offset == 0x0E: return self.cfm << 8 | self.cfs if 0x10 <= offset < 0x20: return self.command[(offset - 0x10) >> 1] if 0x20 <= offset < 0x30: return self.status[(offset - 0x20) >> 1] if offset == 0x30: # "set values can be reread (This does not include the count value.)" (p.30). return self.timer_reload if offset == 0x32: return self.enable if offset == 0x34: # EFDT (bit 15) reads 0, "ready": the fade is applied at once here # (HYPOTHESIS; p.31 gives 22 us per step of depth). return self.fader & 0x7FFE if offset == 0x36: return self.cdd.control() if 0x38 <= offset < 0x42: return self.cdd.status_word(offset - 0x38) if 0x42 <= offset < 0x4C: return self.cdd.command_word(offset - 0x42) if 0x4C <= offset < 0x68: return self.graphics.read(offset) if offset == 0x68: return self.cdd.subcode_address() if offset >= 0x100: return self.cdd.subcode_word((offset - 0x100) >> 1 & 0x3F) return 0 def sub_write(self, offset: int, data: int, upper: bool, lower: bool) -> None: if offset == 0x00: if upper: self.led = (data >> 8) & 3 if lower and not data & 1: # RES0 written 0: "Periphery reset" (p.22); RES0 reads 0 for about # 100 ms. What the periphery is the manual does not list; here the # drive's host interface (ares resets the CDD, OBSERVED). self.periphery_reset = PERIPHERY_RESET self.cdd.reset_host() elif offset == 0x02: # One byte, from the data lines (module docstring): RET, MODE, PM1-0 (p.22). byte = data & 0xFF ret = byte & 1 if ret != self.ret: # Changing RET answers a 1M swap request (KRIKzz). DOC. self.swap_request = 0 self.ret = ret self.mode = (byte >> 2) & 1 self.priority = (byte >> 3) & 3 if ret: # 2M: "when the RET bit is set to '1', the 2M RAM is returned to # MAIN-CPU" (p.24). DOC. ares applies it in either mode (OBSERVED). self.given_to_sub = 0 elif offset == 0x04: if upper: self.cdc.set_destination((data >> 8) & 7) if lower: self.cdc.address = data & 0x1F elif offset == 0x06: if lower: self.cdc.write_register(data & 0xFF) elif offset == 0x08: # $FF8008 is read-only (p.58), and a write takes a word as on the main side # ($A12008 above): CDC DMA3 has the sub CPU write it 588 times in a # 1,176-word sub-CPU transfer (DD=3), then reads it through its mailbox and # fails with 62 when the words come from the block's start (TEST ROM; the # same HYPOTHESIS for the mechanism). self.cdc.host_read(main=False) elif offset == 0x0A: self.cdc.set_dma_address((data & 0xFFFF) << 3) elif offset == 0x0C: # "A write causes the counter to restart from '0'" (p.28). DOC. self.stopwatch = 0 elif offset == 0x0E: self.cfs = data & 0xFF elif 0x20 <= offset < 0x30: index = (offset - 0x20) >> 1 word = self.status[index] if upper: word = (word & 0x00FF) | (data & 0xFF00) if lower: word = (word & 0xFF00) | (data & 0x00FF) self.status[index] = word elif offset == 0x30: # "Count down from n to 0 is started when 'n' is written" (p.30). DOC. self.timer_reload = data & 0xFF self.timer_count = self.timer_reload elif offset == 0x32: if lower: self.enable = data & 0x7E elif offset == 0x34: self.fader = data & 0xFFFF self.cdd.set_fader(self.fader) elif offset == 0x36: if lower: self.cdd.set_control(data & 0xFF) elif 0x42 <= offset < 0x4C: # A nibble a byte; nibble 9 sends the command (cdd.py ``write_command``, p.33). self.cdd.write_command(offset - 0x42, data, upper, lower) elif 0x4C <= offset < 0x68: self.graphics.write(offset, data, upper, lower) # $FF8008, the command words, the CDD status and $FF8050-$FF8056 are read-only. __all__ = ["TICK", "GateArray"]