# SPDX-License-Identifier: MIT AND ISC """The Sega CD as a device on megadrive-python's expansion port (socket 2). :class:`MegaCD` holds the sub CPU (a second m68000-python), its bus, the memories, the gate array, the CD-ROM decoder, the drive, the graphics unit and the PCM, and answers the main CPU's accesses to the CD's half of the cartridge space and to $A12000-$A120FF. Sources, by tag (``p.N`` is Sega's *Mega-CD Hardware Manual*, 1991, through docs/manual-registers.md): the memory maps of both CPUs (p.5, p.12-16; DOC); the clocks, sub CPU 12.5 MHz from a 50 MHz crystal (p.1, p.iv; DOC); mirrors, which the manual does not state, from ares 9408cb4 (ISC, ``bus-external.cpp``, ``io-external.cpp``, ``io-internal.cpp``; OBSERVED). **Time.** The main CPU leads. Every access the main CPU makes to the CD (other than reading the boot ROM, which nothing changes) first runs the sub CPU and its units up to the access's master clock (sockets.md 4), and the board runs the device up to the 68000's clock after every instruction (socket 5). The sub CPU runs whole instructions, so it may be up to one instruction (at most a DIVS, 158 clocks: Motorola's timing tables) past the main CPU's clock when the main CPU reads: a stated limitation (sockets.md 4). **The hang.** A sub-CPU access to word RAM it does not own in 2M mode hangs the sub CPU (p.24: "If the SUB-CPU accesses the WORD-RAM when mode is 0 and RET is 1, the CPU becomes hang up ... can not be canceled unless a forced reset is done"; DOC), $0C0000-$0DFFFF in 2M too (KRIKzz's notes: "move.l #0x1234abcd, 0x80000 ... access to 0xc0000 hang also", hardware prose; DOC). mcd-verificator's WORD RAM row settles two things the manual does not (TEST ROM): the row has the sub CPU write $080000 while the main CPU owns the RAM and fails with ERROR 20 when the sub CPU answers; and it then gives the RAM to the sub CPU (DMNA=1) and waits for the sub CPU to finish, failing with ERROR 21 if it does not, so the hung access completes when the RAM becomes the sub CPU's, without a reset (ares holds /DTACK until then too; OBSERVED). A forced reset (SRES=0) also ends it. m68000-python cannot hold a bus cycle, so here the instruction finishes at once: a held write is kept and made when the hang ends, a held read gives what the RAM holds at the access (stated simplification), and the sub CPU runs no further instructions until the hang ends. **Stated deviation.** The sub CPU's bus request (SBRQ) stops it between instructions, not at a bus cycle. """ from __future__ import annotations from typing import TYPE_CHECKING from m68000_python import AUTOVECTOR, M68000CPU from .cdc import CDC from .cdd import CDD from .gatearray import GateArray from .graphics import Graphics from .memory import ( BACKUP_RAM_SIZE, PRG_RAM_SIZE, WordRAM, cell_to_dot, formatted_backup_ram, ) from .pcm import PCM if TYPE_CHECKING: from collections.abc import Sequence from megadrive_python.board import Board #: The sub CPU's clock: 12.5 MHz (p.1), the 50 MHz crystal divided by 4 (p.iv). DOC. SUB_HZ = 12_500_000 #: The boot ROM: "1M ROM" at $000000-$01FFFF in mode 2 (p.5, p.12). DOC. BIOS_SIZE = 0x20000 #: Mode 2's CD area at $000000-$3FFFFF: the boot ROM and PRG-RAM window repeat every #: $40000 up to $1FFFFF, and word RAM's $40000 repeats up to $3FFFFF. The manual marks #: $040000-$1FFFFF "Reserved by the system" (p.12) and states no mirrors; the repeats are #: ares's (address bits 18-20 ignored), OBSERVED. LOW_MIRROR = 0x3FFFF class BackupRAM: """The internal 8 KB backup RAM (p.15). ``data`` is what ``--backup-ram`` saves.""" def __init__(self, data: bytes | None = None) -> None: image = formatted_backup_ram() if data is None else bytes(data) self.data = bytearray(image[:BACKUP_RAM_SIZE].ljust(BACKUP_RAM_SIZE, b"\x00")) class MegaCD: """The expansion-port device. ``bios``: the boot ROM image (your own, or mcd-verificator, which stands in for it); ``disc``: a :class:`~segacd_python.disc.Disc` in the drive or None; ``backup_ram``: the internal backup RAM's contents.""" def __init__(self, bios: bytes, *, disc: object | None = None, backup_ram: bytes | None = None) -> None: # fmt: skip self.bios = bytes(bios[:BIOS_SIZE]).ljust(BIOS_SIZE, b"\xff") self.prg = bytearray(PRG_RAM_SIZE) self.wram = WordRAM() self.backup_ram = BackupRAM(backup_ram) self.cdc = CDC() self.cdd = CDD(disc) self.graphics = Graphics(self.wram) self.pcm = PCM() self.gate = GateArray(self.cdc, self.cdd, self.graphics) self.gate.on_sub_reset = self._sub_reset_line self.graphics.request = self.gate.request self.graphics.priority = self._priority self.graphics.in_2m = self._in_2m self.cdc.request = self.gate.request self.cdd.request = self.gate.request self.cdd.decode = self.cdc.decode self.cdc.attach(self) self.sub = M68000CPU( self.sub_read_byte, self.sub_read_word, self.sub_write_byte, self.sub_write_word, acknowledge=self._sub_acknowledge, ) # fmt: skip #: Sources of sound for the console's mixer (socket 8): filled by the sound units. self.audio_sources: list[object] = [self.pcm, self.cdd.audio] self.board: Board | None = None self.mode1 = False self.mclk_hz = 53_693_175 #: Sub CPU clocks since power-on, and the master clock they correspond to. self.sub_clock = 0 self.sub_instructions = 0 self.sub_running = False # out of reset (SRES=1) #: Hung on word RAM it does not own (module docstring), and the held write #: (address, data, upper, lower) or None. self.sub_hung = False self.held_write: tuple[int, int, bool, bool] | None = None #: The word-RAM DMA latch: the VDP reads word RAM one word late (p.61). self.dma_latch = 0 def __setstate__(self, state: dict[str, object]) -> None: """A machine saved before the hang existed loads with it clear.""" state.setdefault("sub_hung", False) state.setdefault("held_write", None) self.__dict__.update(state) # -- socket 2: attach and claims ---------------------------------------------- def attach(self, board: Board) -> None: self.board = board self.mclk_hz = board.machine.mclk # Mode 1 (/CART grounded: a cartridge boots) puts the CD at $400000; mode 2 at # $000000 (p.5). DOC. self.mode1 = board.cartridge_present def claims(self) -> Sequence[tuple[int, int]]: ranges = [(0xA12000, 0xA12100)] if self.mode1: ranges.append((0x400000, 0x800000)) else: ranges.append((0x000000, 0x400000)) board = self.board if board is not None and board.slot is None and board.slot_cartridge is not None: # A cartridge that leaves /CART high (the RAM cartridge) sits at # $400000-$7FFFFF in mode 2 (p.5: "Back-up cartridge, Expansion RAM # cartridge"). DOC. The port routes it (sockets.PortDevice). ranges.append((0x400000, 0x800000)) return ranges def reset(self, kind: int, mclk: int) -> None: """Power-on resets the CD; the reset button and the main CPU's RESET instruction do nothing to it here: the manual names neither (p.27 separates power-on from "other resets"), and on the button the main CPU restarts the BIOS, which resets the sub side itself through SRES. HYPOTHESIS, provisional.""" if kind == 0: # Reset.POWER_ON self.gate.power_on() self.cdd.power_on() self.cdc.reset_chip() self.sub_running = False self.sub_clock = mclk * SUB_HZ // self.mclk_hz # -- time ----------------------------------------------------------------- def catch_up(self, mclk: int) -> None: target = mclk * SUB_HZ // self.mclk_hz if self.sub_clock < target: self.run_sub(target) # When on the sub CPU's clock the main CPU's access lands (gatearray.py, # IFL2_LATENCY). self.gate.now = target def run_sub(self, target: int) -> None: gate, cpu = self.gate, self.sub while self.sub_clock < target: if self.sub_hung and self._hang_over(): self.sub_hung = False if self.held_write is not None: held, self.held_write = self.held_write, None self._sub_word_ram_write(*held) if not self.sub_running or gate.sbrq or self.sub_hung: # Held in reset, or its bus granted to the main CPU (p.56): no # instructions, the units run on. self._units(target - self.sub_clock) self.sub_clock = target return ipl = gate.ipl(self.sub_clock) if ipl != cpu.ipl: cpu.set_ipl(ipl) clocks = cpu.step() self.sub_instructions += 1 self.sub_clock += clocks self._units(clocks) def _hang_over(self) -> bool: """The held access can complete: 1M mode, or 2M with the RAM given to the sub CPU and the access below $0C0000 (module docstring).""" gate = self.gate if gate.mode == 1: return True held = self.held_write return bool(gate.given_to_sub) and (held is None or held[0] < 0xC0000) def _units(self, clocks: int) -> None: """``clocks`` sub CPU clocks of everything on the sub side that keeps time.""" self.gate.run(clocks) if self.graphics.busy: self.graphics.run(clocks) self.cdc.run(clocks) self.cdd.run(clocks) self.pcm.run(clocks) def _sub_reset_line(self, held: bool) -> None: """SRES: 0 holds the sub CPU in reset, 1 lets it run (p.56). DOC. The 68000 takes its reset exception -- SSP and PC from PRG RAM's $0 and $4 -- when RESET is released (Motorola UM 6.3.1). DOC.""" if held: self.sub_running = False self.sub_hung = False self.held_write = None else: self.sub_running = True self.sub_clock += self.sub.reset() def _sub_acknowledge(self, level: int) -> int: """Every sub-CPU level is autovectored (the vectors at $64-$78 of PRG RAM are what the BIOS fills: p.15 lists only levels). HYPOTHESIS; MAME's BSD-3 driver autovectors too (OBSERVED, f379cd0).""" self.gate.acknowledge(level) self.sub.set_ipl(self.gate.ipl(self.sub_clock)) return AUTOVECTOR def _priority(self) -> int: return self.gate.priority def _in_2m(self) -> bool: return self.gate.mode == 0 # -- the main CPU's side --------------------------------------------------------- def _main_offset(self, address: int) -> int: """The offset into the CD's 4 MB area, mirrors folded (``LOW_MIRROR``).""" offset = (address - 0x400000 if self.mode1 else address) & 0x3FFFFF if offset < 0x200000: return offset & LOW_MIRROR return 0x200000 | (offset & LOW_MIRROR) def _cart_passthrough(self, address: int) -> bool: return not self.mode1 and address >= 0x400000 and address < 0x800000 def read_word(self, address: int, mclk: int) -> int: address &= 0xFFFFFF if address >= 0xA00000: self.catch_up(mclk) return self.gate.main_read(address & 0x3E) if self._cart_passthrough(address): return self.board.game_cartridge.read_word(address) # type: ignore[union-attr] offset = self._main_offset(address) if offset < BIOS_SIZE: if offset == 0x70: # The level-4 (HINT) vector's high word reads $FFFF, not the boot ROM's: # mcd-verificator's REG 2006 row passes only so (TEST ROM; it fails with # 02 when the ROM's word is read). ares reads $FFFF there too (OBSERVED). # The manual's "using $70 for the high order portion" (p.58) does not say # what $70 holds. In mode 1 the same holds at $400070-$400073, the boot # ROM's own place: the row, run from a cartridge, fails with 02 without # it (TEST ROM), and ares maps it so (OBSERVED). return 0xFFFF if offset == 0x72: # The level-4 (HINT) vector's low word comes from $A12006 (p.58). DOC. self.catch_up(mclk) return self.gate.hint_vector bios = self.bios return (bios[offset] << 8) | bios[offset + 1] self.catch_up(mclk) if offset < 0x40000: return self._prg_window_read(offset, mclk) return self._word_ram_read(offset & 0x3FFFF) def read_byte(self, address: int, mclk: int, master: int) -> int: address &= 0xFFFFFF if address >= 0xA00000: self.catch_up(mclk) word = self.gate.main_read(address & 0x3E) return word & 0xFF if address & 1 else word >> 8 if self._cart_passthrough(address): return self.board.game_cartridge.read_byte(address) # type: ignore[union-attr] offset = self._main_offset(address) if offset < BIOS_SIZE and offset & ~3 != 0x70: return self.bios[offset] word = self.read_word(address & ~1, mclk) return word & 0xFF if address & 1 else word >> 8 def peek_byte(self, address: int) -> int: address &= 0xFFFFFF if address >= 0xA00000: word = self.gate.main_read(address & 0x3E) elif self._cart_passthrough(address): return self.board.game_cartridge.read_byte(address) # type: ignore[union-attr] else: offset = self._main_offset(address) if offset < BIOS_SIZE: return self.bios[offset] if offset < 0x40000: word = self._prg_window_read(offset, None) else: word = self._word_ram_read(offset & 0x3FFFF) return word & 0xFF if address & 1 else word >> 8 def write_word(self, address: int, value: int, mclk: int) -> None: address &= 0xFFFFFF self.catch_up(mclk) if address >= 0xA00000: self.gate.main_write(address & 0x3E, value, True, True) return if self._cart_passthrough(address): self.board.game_cartridge.write_word(address, value) # type: ignore[union-attr] return self._main_write(self._main_offset(address), value, True, True) def write_byte(self, address: int, value: int, mclk: int, master: int) -> None: address &= 0xFFFFFF self.catch_up(mclk) data = value * 0x0101 # the byte on both halves of the data bus (UM 5.1.2) upper, lower = not address & 1, bool(address & 1) if address >= 0xA00000: self.gate.main_write(address & 0x3E, data, upper, lower) return if self._cart_passthrough(address): self.board.game_cartridge.write_byte(address, value) # type: ignore[union-attr] return self._main_write(self._main_offset(address & ~1), data, upper, lower) def _main_write(self, offset: int, data: int, upper: bool, lower: bool) -> None: if offset < BIOS_SIZE: return # the boot ROM if offset < 0x40000: gate = self.gate if gate.sbrq: at = (gate.prg_bank << 17) | (offset & 0x1FFFE) if upper: self.prg[at] = data >> 8 if lower: self.prg[at + 1] = data & 0xFF return self._word_ram_write(offset & 0x3FFFE, data, upper, lower) def _prg_window_read(self, offset: int, mclk: int | None) -> int: """$020000-$03FFFF: one 128 KB bank of PRG RAM by BK1-0, "When SBRQ=1 or SRES=0" (p.57). DOC. SRES=0 forces SBRQ here (gatearray.py), so SBRQ decides. Without it the main CPU reads open bus (the board's), a documented choice: the manual does not say (sockets.md 2).""" gate = self.gate if not gate.sbrq: return self._open_bus() at = (gate.prg_bank << 17) | (offset & 0x1FFFE) return (self.prg[at] << 8) | self.prg[at + 1] def _open_bus(self) -> int: return self.board.open_bus() if self.board is not None else 0xFFFF def _word_ram_read(self, offset: int) -> int: """$200000-$23FFFF (p.12-13, p.16). 2M: the whole RAM, while the main CPU owns it (DMNA/RET, p.24-25); 1M: its bank at $200000-$21FFFF and that bank's cell image at $220000-$23FFFF (p.13, p.16-18). DOC.""" gate, wram = self.gate, self.wram if gate.mode == 0: if gate.given_to_sub: return self._open_bus() return wram.read_word_2m(offset) bank = gate.ret if offset < 0x20000: return wram.read_word_1m(offset, bank) return wram.read_word_1m(cell_to_dot(offset & 0x3FFFE), bank) def _word_ram_write(self, offset: int, data: int, upper: bool, lower: bool) -> None: gate, wram = self.gate, self.wram if gate.mode == 0: if gate.given_to_sub: return old = wram.read_word_2m(offset) wram.write_word_2m(offset, _merge(old, data, upper, lower)) return bank = gate.ret at = offset if offset < 0x20000 else cell_to_dot(offset) old = wram.read_word_1m(at, bank) wram.write_word_1m(at, bank, _merge(old, data, upper, lower)) # -- the CDC's DMA into the sub side's memories (cdc.py ``CDC.run``) ----------------- # # The decoder's DMA channel (DD = 4, 5, 7; p.26-27) as named calls, so the CDC reaches # the memories and the hand-over state only here (docs/domains.md). The rules and their # evidence are cdc.py's; these only carry them. def cdc_dma_word_ram_held(self) -> bool: """2M word RAM the main CPU owns: the DMA waits (cdc.py; TEST ROM CDC DMA3 44).""" gate = self.gate return gate.mode == 0 and not gate.given_to_sub def cdc_dma_prg_held(self) -> bool: """PRG RAM switched to the main CPU by SBRQ (p.6-7): the DMA waits (TEST ROM CDC DMA3 48).""" return bool(self.gate.sbrq) def cdc_dma_pcm(self, address: int, value: int) -> None: """A byte into PCM wave RAM (DD = 4).""" self.pcm.write(address, value) def cdc_dma_prg(self, at: int, word: int) -> None: """A word into PRG RAM at ``at`` (DD = 5); the write protect does not apply (cdc.py, TEST ROM CDC DMA3 56).""" prg = self.prg prg[at] = word >> 8 prg[at + 1] = word & 0xFF def cdc_dma_word_ram(self, at: int, word: int) -> int: """A word into word RAM at DMA address ``at`` (DD = 7): 2M the whole RAM, 1M the sub CPU's bank (p.26-27). Returns the next DMA address, wrapped to the mode's size.""" gate = self.gate if gate.mode == 0: self.wram.write_word_2m(at & 0x3FFFE, word) return (at + 2) & 0x3FFFF self.wram.write_word_1m(at & 0x1FFFE, 1 - gate.ret, word) return (at + 2) & 0x1FFFF # -- socket 3: the VDP's DMA ------------------------------------------------------- def dma_start(self, mclk: int, bus: int) -> None: """ "the data read from the WORD-RAM will be output with a one cycle delay" (p.61). DOC. What the first word receives the manual does not say; here the 68000's data bus at the start (its prefetch): HYPOTHESIS (ares's comment says the same belief; OBSERVED).""" self.dma_latch = bus def dma_read_word(self, address: int, mclk: int) -> int: address &= 0xFFFFFF if not self._cart_passthrough(address) and address < 0xA00000: offset = self._main_offset(address) if offset >= 0x200000: self.catch_up(mclk) value, self.dma_latch = self.dma_latch, self._word_ram_read(offset & 0x3FFFE) return value return self.read_word(address, mclk) # -- the sub CPU's bus (p.12-15) ------------------------------------------------------- def sub_read_word(self, address: int) -> int: address &= 0xFFFFFF if address < 0x80000: prg = self.prg return (prg[address] << 8) | prg[address + 1] if address < 0xE0000: return self._sub_word_ram_read(address) if address >= 0xFF8000: # $FF8000-$FF81FF repeat through $FFFFFF: ares, OBSERVED. return self.gate.sub_read(address & 0x1FE) if address >= 0xFF0000: # PCM on odd bytes, $FF0000-$FF3FFF and its image to $FF7FFF (p.15). DOC. return self.pcm.read((address >> 1) & 0x1FFF) if address >= 0xFE0000: # Backup RAM on odd bytes, $FE0000-$FE3FFF and its image to $FEFFFF (p.15). return self.backup_ram.data[(address >> 1) & 0x1FFF] return 0 def sub_read_byte(self, address: int) -> int: address &= 0xFFFFFF if address < 0x80000: return self.prg[address] if address < 0xE0000 and self.gate.mode == 1 and address < 0xC0000: return self.wram.read_dot(address - 0x80000, 1 - self.gate.ret) word = self.sub_read_word(address & ~1) return word & 0xFF if address & 1 else word >> 8 def sub_write_word(self, address: int, value: int) -> None: address &= 0xFFFFFF if address < 0x80000: self._prg_write(address, value, True, True) else: self._sub_write(address, value, True, True) def sub_write_byte(self, address: int, value: int) -> None: address &= 0xFFFFFF if address < 0x80000: if address >= self.gate.write_protect << 9: self.prg[address] = value return self._sub_write(address & ~1, value * 0x0101, not address & 1, bool(address & 1)) def _prg_write(self, address: int, data: int, upper: bool, lower: bool) -> None: """Writes below WP x $200 are refused: "The address range $0 to $1FDFF of the SUB-CPU is protected in multiples of $200" (p.14, p.24, p.57). DOC (the threshold reading is derived).""" if address < self.gate.write_protect << 9: return if upper: self.prg[address] = data >> 8 if lower: self.prg[address + 1] = data & 0xFF def _sub_write(self, address: int, data: int, upper: bool, lower: bool) -> None: if address < 0xE0000: self._sub_word_ram_write(address, data, upper, lower) elif address >= 0xFF8000: self.gate.sub_write(address & 0x1FE, data, upper, lower) elif not lower: return # PCM and backup RAM are on the odd bytes (p.15) elif address >= 0xFF0000: self.pcm.write((address >> 1) & 0x1FFF, data & 0xFF) elif address >= 0xFE0000: self.backup_ram.data[(address >> 1) & 0x1FFF] = data & 0xFF def _sub_word_ram_read(self, address: int) -> int: """2M: $080000-$0BFFFF while the sub CPU owns it, nothing at $0C0000. 1M: the dot image at $080000-$0BFFFF and the bank at $0C0000-$0DFFFF; the sub CPU has the bank the main CPU does not (RET, p.24). DOC. An access in 2M to RAM the main CPU owns, or to $0C0000, hangs the sub CPU (the module docstring).""" gate, wram = self.gate, self.wram if gate.mode == 0: if address < 0xC0000: if not gate.given_to_sub: self.sub_hung = True return wram.read_word_2m(address - 0x80000) self.sub_hung = True return 0 bank = 1 - gate.ret if address < 0xC0000: offset = address - 0x80000 return (wram.read_dot(offset, bank) << 8) | wram.read_dot(offset + 1, bank) return wram.read_word_1m(address - 0xC0000, bank) def _sub_word_ram_write(self, address: int, data: int, upper: bool, lower: bool) -> None: gate, wram = self.gate, self.wram if gate.mode == 0: if address < 0xC0000 and gate.given_to_sub: offset = address - 0x80000 wram.write_word_2m(offset, _merge(wram.read_word_2m(offset), data, upper, lower)) else: # Held until the hang ends (the module docstring). self.sub_hung = True self.held_write = (address, data, upper, lower) return bank = 1 - gate.ret if address < 0xC0000: offset = address - 0x80000 if upper: wram.write_dot(offset, bank, data >> 8, gate.priority) if lower: wram.write_dot(offset + 1, bank, data, gate.priority) return offset = address - 0xC0000 old = wram.read_word_1m(offset, bank) wram.write_word_1m(offset, bank, _merge(old, data, upper, lower)) def _merge(old: int, data: int, upper: bool, lower: bool) -> int: if upper and lower: return data & 0xFFFF if upper: return (data & 0xFF00) | (old & 0x00FF) return (old & 0xFF00) | (data & 0x00FF) __all__ = ["SUB_HZ", "BackupRAM", "MegaCD"]