# SPDX-License-Identifier: MIT """The 32X as megadrive-python's cartridge-slot device: the 68000's side (milestone 1) and, with the user's boot ROMs, the two SH-2s behind it (milestone 2; ``sh2side.py``). The 32X sits in the Mega Drive's cartridge slot and holds the game (Manual 1.1); on megadrive-python that is a ``sockets.SlotDevice`` whose ``cartridge`` is the held :class:`~megadrive_python.cartridge.Cartridge`. The board puts the held cartridge on the bus wherever the device claims nothing, so this module answers only the ranges the 32X decodes, and changes them with ADEN and RV through ``Board.update_claims``: ======================== ========================================================= State Claims (256-byte pages, ``sockets.CLAIM_PAGE``) ======================== ========================================================= always $A13000-$A130FF (``"MARS"`` at $A130EC-$A130EF; the rest of /TIME passed to the cartridge as the board would) and $A15100-$A153FF (system registers, VDP, palette) ADEN = 1 also $000000-$0000FF (vector ROM, HINT vector register) and $840000-$9FFFFF (frame buffer, overwrite image, windows) ADEN = 1, RV = 0 also $000100-$3FFFFF (the cartridge is not there, Manual 3.1) ======================== ========================================================= With ADEN = 0 nothing at $000000-$3FFFFF is claimed, so megadrive-python's ROM hot path is untouched (``Board._remap`` leaves the cartridge object itself on the bus) and a Mega Drive game runs as if the 32X were not there (Manual 3.5: "After the power is turned on, address space of 68000 is mapped the same as the MEGA Drive unit"); docs/worklog.md, Session 1, has the gate that shows it. With :class:`~sega32x_python.bootrom.BootROMs` the device owns an :class:`~sega32x_python.sh2side.SH2Side`: every 68000 or Z80 access to 32X space first runs the SH-2s up to the access's master clock (socket 4), and ``catch_up`` runs them after every 68000 instruction (socket 5). The registers both sides share live here; the SH-2 side reaches them through ``sh2_register_read``/``sh2_register_write``. The 32X VDP (``vdp.py``, milestone 3) keeps its own line timing from socket 6 and draws the 32X's own picture, which ``composite.py`` lays over the Mega Drive's (milestone 4, socket 7); ``pwm.py`` is the PWM (milestone 5) and socket 8's sound source. The 68000's waits on 32X space are the Manual's (4.1) first model, through ``Board.hold`` (``Quirks.m68k_waits``). Every behaviour chosen here is a field of :class:`~sega32x_python.machine.Quirks`. """ from __future__ import annotations from typing import TYPE_CHECKING from megadrive_python.board import Lockup from megadrive_python.cartridge import BootROM from megadrive_python.sockets import M68K, Reset from .bootrom import BootROMError, BootROMs from .composite import Composite from .machine import MACHINES, Machine from .pwm import PWM from .sh2side import CMD, HINT, VINT, VRES, SH2Side from .sh2side import PWM as PWM_INTERRUPT from .vdp import VDP32X if TYPE_CHECKING: from megadrive_python.board import Board from megadrive_python.cartridge import Cartridge from megadrive_python.sockets import PictureLine, VideoLine #: A 68000 bus cycle without waits: 4 of its clocks, in master clocks. M68K_CYCLE = 28 class ResetLanding(Lockup): """The placeholder for open item 10 (``Quirks.reset_with_rv``): the reset button pressed with ADEN = 1 and RV = 1. Not a hardware claim -- testpico shows the 68000 landing somewhere in its cartridge's $2C8-$304 -- but a stop that says what it is.""" class NotModelled(Exception): """An access to a part of the 32X a later milestone builds (the VDP, PWM, the SH-2 side). Raised rather than answered, so nothing runs on a guess.""" #: The pages claimed in every state: /TIME and the 32X's registers. ALWAYS = ((0xA13000, 0xA13100), (0xA15100, 0xA15400)) #: Frame buffer DRAM: two 1-Mbit chips, one displayed while the other is drawn (Manual 2.1). FRAMEBUFFER_SIZE = 0x20000 #: The DREQ FIFO's depth in words: two 4-word FIFOs (Manual figure 3.28). FIFO_WORDS = 8 class Sega32X: """The 32X in the cartridge slot, holding ``cartridge`` (or None for an empty 32X slot). ``vector_rom``: the 256-byte 68000 boot ROM mapped at $000000 when ADEN is set -- the user's ``32X_G_BIOS.BIN`` through :class:`~sega32x_python.bootrom.BootROMs` (checked by SHA-1 there), or any 256-byte image a test makes; None is allowed until a program sets ADEN.""" def __init__(self, cartridge: Cartridge | None, machine: Machine | None = None, *, vector_rom: bytes | None = None, boot_roms: BootROMs | None = None) -> None: # fmt: skip if boot_roms is not None: vector_rom = boot_roms.m68k if vector_rom is not None and len(vector_rom) != 256: raise BootROMError(f"the 68000 boot ROM is 256 bytes, not {len(vector_rom)}") self.cartridge = cartridge self.machine = machine if machine is not None else MACHINES["genesis-32x"] self.vector_rom = vector_rom self.board: Board | None = None #: The master clock the device has run to (socket 4/5). Nothing runs in it yet. self.clock = 0 q = self.machine.quirks self._adapter_writable = q.adapter_writable.value self._dreq_writable = q.dreq_control_writable.value self._source_mask = q.dreq_source_mask.value self._destination_mask = q.dreq_destination_mask.value self._length_mask = q.dreq_length_mask.value self._sega_tv_writable = q.sega_tv_writable.value self._int_writable = q.interrupt_control_writable.value self._bank_writable = q.bank_writable.value self._reads_zero = frozenset(q.reads_zero.value) self._mars = q.mars_id.value self._waits = q.m68k_waits.value #: The bus master of the access being answered, and whether it is a peek. self._master = M68K self._peeking = False #: The VDP's 68000-to-VDP DMA is reading (``dma_read_word``): not held on the #: cartridge (``Quirks.cartridge_contention``). self._dma = False #: The SH-2 side, when the user's boot ROMs were given (decision 3). self.sh2: SH2Side | None = None if boot_roms is not None: self.sh2 = SH2Side(self, boot_roms.master, boot_roms.slave) #: PWM: registers, FIFOs, the counter and socket 8's sound (``pwm.py``); one object #: for the device's life, since ``System.audio_sources`` holds it. self.pwm = PWM(self) self.power_on() # -- state --------------------------------------------------------------------- def power_on(self) -> None: """Every register to its power-on value (``Quirks``: adapter_power_on, dreq_length_power_on, dreq_address_power_on, hint_vector_power_on). The frame buffers' power-on contents are unknown; they start at 0.""" q = self.machine.quirks #: $A15100 as written (FM, RES, ADEN); REN always reads 1 (adapter_writable). self.adapter = q.adapter_power_on.value & self._adapter_writable self.interrupt_control = 0 self.bank = 0 #: $A15106: RV (bit 0), bit 1, 68S (bit 2). self.dreq_control = 0 self.dreq_source = q.dreq_address_power_on.value & self._source_mask self.dreq_destination = q.dreq_address_power_on.value & self._destination_mask self.dreq_length = q.dreq_length_power_on.value #: The last word written to the FIFO ($A15112); the transfer is milestone 2. self.fifo_last = 0 self.sega_tv = 0 self.comm = [0] * 8 self.hint_vector = q.hint_vector_power_on.value self.framebuffers = (bytearray(FRAMEBUFFER_SIZE), bytearray(FRAMEBUFFER_SIZE)) #: The 32X VDP: registers, palette, FS, auto fill, its line timing and picture #: (``vdp.py``; the CPUs reach the frame buffer FS does not display: Manual 3.1). self.vdp = VDP32X(self) #: Socket 7's composite (``composite.py``), once ``console.build`` attaches it. self.composite: Composite | None = None #: The DREQ FIFO from the 68000 to SH-2 DMA channel 0 (``Quirks.dreq_fifo``). self.fifo: list[int] = [] self.pwm.power_on() #: The SH-2 side's own: standby changer ($20004002), H count ($20004004), HEN. self.standby = 0 self.hcount = 0 self.hen = False if self.sh2 is not None: self.sh2.set_run(False, self.clock) #: The reset button was pressed with ADEN = 1 and RV = 1 and the 68000 has not #: yet reached the windows (``Quirks.reset_with_rv``). self._button_with_rv = False @property def aden(self) -> bool: return bool(self.adapter & 1) @property def fm(self) -> bool: return bool(self.adapter & 0x8000) @property def rv(self) -> bool: return bool(self.dreq_control & 1) # -- the socket ------------------------------------------------------------------ def attach(self, board: Board) -> None: self.board = board def claims(self) -> list[tuple[int, int]]: ranges = list(ALWAYS) if self.adapter & 1: ranges.append((0x000000, 0x000100)) if not self.dreq_control & 1: ranges.append((0x000100, 0x400000)) ranges.append((0x840000, 0xA00000)) return ranges def catch_up(self, mclk: int) -> None: """Sockets 4 and 5: with ADEN = 1, the Mega Drive's VDP is brought to ``mclk`` (its line records are the 32X VDP's time base, socket 6), then the SH-2s and the 32X VDP's events run to it, in order. With ADEN = 0 nothing runs (the SH-2s are held, and nothing can reach the 32X VDP).""" if mclk > self.clock: self.clock = mclk if not self.adapter & 1: return self.video_lines_to(mclk) sh2 = self.sh2 vdp = self.vdp if sh2 is not None and sh2.running: sh2.catch_up(mclk) oldest = sh2.oldest() vdp.advance(mclk) vdp.prune(oldest * 7 // 3) else: vdp.advance(mclk) vdp.prune(mclk) self.pwm.run(mclk * 3 // 7) def shared_cartridge(self) -> Cartridge: """The cartridge as the SH-2s reach it at $02000000 (Manual 3.1): memory both sides share, its contention between them modelled in ``sh2side.py`` (``Quirks.cartridge_contention``); the board's game cartridge.""" return self.board.game_cartridge # type: ignore[union-attr] def video_lines_to(self, mclk: int) -> None: """Socket 6's channel from the Mega Drive side: the Mega Drive's VDP publishes its line records (``video_line``) up to ``mclk`` before anything on the 32X side that reads them runs (docs/domains.md). The one call into the Mega Drive board's own state; megadrive-python has no socket method for it yet (a proposal).""" board = self.board if board is not None: board.vdp.sync(mclk) def video_line(self, line: VideoLine) -> None: """Socket 6 (``System.attach_video_timing``): the 32X VDP's time base -- its status bits, HINT and VINT, register latch, FS swap and rows (``vdp.py``).""" self.vdp.video_line(line, bool(self.adapter & 1)) def picture_line(self, line: PictureLine) -> list[int] | None: """Socket 7 (``System.attach_picture``): the line that leaves the console, the 32X's row laid over the Mega Drive's (``composite.py``). Made on first use, so a device nobody attached as a Picture keeps ``composite`` None.""" composite = self.composite if composite is None: composite = self.composite = Composite(self) return composite.picture_line(line) def _hold(self, kind: str, master: int) -> None: """The Manual's 68000 waits for an access to 32X space (4.1; ``Quirks.m68k_waits``), in 68000 clocks, through ``Board.hold``.""" waits = self._waits[kind] if waits: self.board.hold(master, waits * 7) # type: ignore[union-attr] def reset(self, kind: Reset, mclk: int) -> None: """Power-on resets every register; the reset button and the 68000's RESET leave them (``Quirks.registers_survive_button``). The button's VRES to the SH-2s is milestone 2's.""" if kind == Reset.POWER_ON: self.power_on() if self.board is not None: self.board.update_claims() elif kind == Reset.BUTTON: # The 68000 will fetch its reset vector from the vector ROM ($880200) and run # there; with RV = 1 that is the open item ``_reset_landing`` stands in for. self._button_with_rv = bool(self.adapter & 1 and self.dreq_control & 1) # VRES: level 14 on both SH-2s, no mask (Manual 3.2.2; testpico # t_32x_reset_btn sees it taken on the master and held by SR on the slave). if self.sh2 is not None and self.sh2.running: self.sh2.catch_up(mclk) self.sh2.assert_source(0, VRES) self.sh2.assert_source(1, VRES) def dma_start(self, mclk: int, bus: int) -> None: """Nothing latches at a DMA's start on the 32X side (the one-word-late rule is the Sega CD's word RAM, not this).""" def dma_read_word(self, address: int, mclk: int) -> int: """The VDP's 68000-to-VDP DMA reads what the 68000 would read: the VDP becomes the 68000 bus's master, and nothing in the Manual says the 32X tells the two apart. What it reads from the frame buffer and the windows is open item 3 of docs/undocumented-behavior.md; the board gives the 68000's answer.""" self._dma = True try: return self.read_word(address, mclk) finally: self._dma = False # -- 68000 and Z80 accesses ------------------------------------------------------- def read_word(self, address: int, mclk: int) -> int: if mclk > self.clock: self.catch_up(mclk) self._master = M68K top = address >> 16 if top < 0x40: return self._low_read_word(address) if top < 0xA0: return self._high_read_word(address) page = (address >> 8) & 0xFF if page == 0x30: return self._time_read_word(address) return self._register_read(address) def read_byte(self, address: int, mclk: int, master: int) -> int: if mclk > self.clock: self.catch_up(mclk) self._master = master return self._read_byte(address, master) def peek_byte(self, address: int) -> int: """A side-effect-free byte for the Z80's code peeks and the scheduler's probe: what a Z80 read would give, and $FF where that read would lock up or is not modelled (``Board.z80_peek`` reads $FF for anything it cannot see).""" self._peeking = True try: return self._read_byte(address, 1) except (Lockup, NotModelled): return 0xFF finally: self._peeking = False def write_word(self, address: int, value: int, mclk: int) -> None: if mclk > self.clock: self.catch_up(mclk) self._master = M68K self._write(address, value, 0xFFFF) def write_byte(self, address: int, value: int, mclk: int, master: int) -> None: if mclk > self.clock: self.catch_up(mclk) self._master = master if (address >> 8) & 0xFFFF == 0xA130: # /TIME: a byte write drives the byte on both halves of the bus, as the board's # own byte path does (``Board._system_write``). self._time_write(address, value, value, word=False) return if address & 1: self._write(address & ~1, value, 0x00FF) else: self._write(address, value << 8, 0xFF00) def _read_byte(self, address: int, master: int) -> int: if (address >> 8) & 0xFFFF == 0xA130: low = address & 0xFF if 0xEC <= low <= 0xEF: return self._mars[low - 0xEC] if master != M68K: # The board reads $FF for a Z80 bank read of $A1xxxx past the I/O chip # (``Board._z80_bank_read``); /TIME's reads stay as they were. return 0xFF top = address >> 16 if top < 0x40: if address >= 0x100: # Claimed only with RV = 0 (Quirks.low_map_without_rv). Open bus by bytes # is the board's own rule for undecoded space (``Board.read_byte``: the # next opcode's MSB at an even address, 0 at an odd one). return 0 if address & 1 else self.board.open_bus() >> 8 # type: ignore[union-attr] word = self._low_read_word(address & ~1) elif top < 0xA0: word = self._high_read_word(address & ~1) elif (address >> 8) & 0xFF == 0x30: word = self._time_read_word(address & ~1) else: word = self._register_read(address & ~1) return word & 0xFF if address & 1 else word >> 8 def _write(self, address: int, value: int, lanes: int) -> None: """A write of ``value`` on the byte lanes ``lanes`` ($FF00 even byte, $00FF odd byte, $FFFF word), ``address`` even.""" top = address >> 16 if top < 0x40: if address & 0xFC == 0x70 and address < 0x100: shift = 16 if address & 2 == 0 else 0 keep = ~(lanes << shift) & 0xFFFFFFFF self.hint_vector = (self.hint_vector & keep) | ((value & lanes) << shift) # The rest of the vector ROM is ROM; $000100-$3FFFFF with RV = 0 is # undriven (Quirks.low_map_without_rv): both ignore writes. elif top < 0x88: self._framebuffer_write(address, value, lanes) elif top < 0xA0: cartridge, offset = self._window(address) if lanes == 0xFFFF: cartridge.write_word(offset, value) elif lanes == 0xFF00: cartridge.write_byte(offset, value >> 8) else: cartridge.write_byte(offset | 1, value & 0xFF) elif (address >> 8) & 0xFF == 0x30: # Only a word write gets here (``write_byte`` takes /TIME's bytes first). self._time_write(address, value >> 8, value & 0xFF, word=True) else: self._register_write(address, value, lanes) # -- $000000-$3FFFFF ------------------------------------------------------------- def _low_read_word(self, address: int) -> int: if address < 0x100: if address & 0xFC == 0x70: return (self.hint_vector >> 16 if address & 2 == 0 else self.hint_vector) & 0xFFFF rom = self.vector_rom if rom is None: raise BootROMError("ADEN = 1 maps the 32X's 68000 boot ROM; none was given") return (rom[address] << 8) | rom[address + 1] # $000100-$3FFFFF with ADEN = 1 and RV = 0 (claimed only then). return self.board.open_bus_msb() # type: ignore[union-attr] def _reset_landing(self, address: int) -> None: """Where the 68000 goes after the reset button with ADEN = 1 and RV = 1: open item 10, a placeholder stop (``Quirks.reset_with_rv``). Replace this method, and only this, when a test shows the landing. (The pending flag is left alone here so a side-effect-free peek can pass through.)""" raise ResetLanding( f"68000 fetch at ${address:06X} after the reset button with ADEN = 1 and RV = 1: " "where hardware lands is open (docs/undocumented-behavior.md, item 10); this " "stop is a placeholder, not a hardware claim" ) # -- $840000-$9FFFFF ------------------------------------------------------------- def _high_read_word(self, address: int) -> int: if address < 0x880000: # $840000-$87FFFF: claimed from $840000 up if self.adapter & 0x8000: # Quirks.vdp_side_with_fm: undefined (Manual 3.1); the board's open bus. return self.board.open_bus_msb() # type: ignore[union-attr] if not self._peeking: self._hold("framebuffer_read", self._master) buffer = self.framebuffers[self.vdp.fs ^ 1] offset = address & 0x1FFFE return (buffer[offset] << 8) | buffer[offset + 1] cartridge, offset = self._window(address) return cartridge.read_word(offset) def _window(self, address: int) -> tuple[Cartridge, int]: """$880000-$8FFFFF is the cartridge's first 512 KB; $900000-$9FFFFF the 1 MB bank ``BK1:BK0`` (Manual 3.1, 3.5). With RV = 1 both hang (``Quirks.windows_with_rv``).""" if self.dreq_control & 1: if self._button_with_rv: self._reset_landing(address) raise Lockup(f"68000 access to ${address:06X} with RV = 1") sh2 = self.sh2 if sh2 is not None and sh2.running and not self._peeking and not self._dma: # An SH-2 cartridge cycle under way holds the 68000 to its end; the 68000's # 4 clocks are noted for the SH-2s (Quirks.cartridge_contention). held = sh2.m68k_cartridge(self.clock, M68K_CYCLE) if held: self.board.hold(self._master, held) # type: ignore[union-attr] cartridge = self.board.game_cartridge # type: ignore[union-attr] if address < 0x900000: return cartridge, address & 0x7FFFF return cartridge, (self.bank << 20) | (address & 0xFFFFF) def _framebuffer_write(self, address: int, value: int, lanes: int) -> None: """$840000: a $00 *byte* is dropped, a $0000 word is written; $860000 (the overwrite image of the same DRAM): every $00 byte is dropped (``Quirks.framebuffer_zero_bytes``).""" if self.adapter & 0x8000: return # Quirks.vdp_side_with_fm: "writes are ignored" (Manual 3.1) buffer = self.framebuffers[self.vdp.fs ^ 1] offset = address & 0x1FFFE high, low = value >> 8, value & 0xFF overwrite = address & 0x20000 if lanes == 0xFFFF and not overwrite: buffer[offset] = high buffer[offset + 1] = low return if lanes & 0xFF00 and high: buffer[offset] = high if lanes & 0x00FF and low: buffer[offset + 1] = low # -- $A130xx: /TIME -------------------------------------------------------------- def _time_read_word(self, address: int) -> int: low = address & 0xFF if 0xEC <= low <= 0xEF: index = low & 2 return (self._mars[index] << 8) | self._mars[index + 1] # The rest is the cartridge's, exactly as the board reads /TIME without a device # (``Board._system_read_word``): a board's own word (``read_time_word``), else its # byte on both halves, or the open bus's MSB. board = self.board cartridge = self._time_cartridge() word = getattr(cartridge, "read_time_word", None) if word is not None: value = word(address) if value is not None: return value else: value = cartridge.read_time(address | 1) if value is not None: return value | (value << 8) return board.open_bus_msb() # type: ignore[union-attr] def _time_cartridge(self): # type: ignore[no-untyped-def] """Who answers /TIME behind the 32X: the cartridge it holds (the board's ``game_cartridge``), unless the TMSS boot ROM is switched in, which decodes nothing there (megadrive-python ``BootROM.read_time``/``write_time``). Not ``Board.cartridge``: with ADEN = 1 that is the board's decoder of the claimed $000000-$3FFFFF, which knows only the byte interface.""" board = self.board if isinstance(board.cartridge, BootROM): # type: ignore[union-attr] return board.cartridge # type: ignore[union-attr] return board.game_cartridge # type: ignore[union-attr] def _time_write(self, address: int, high: int, low: int, *, word: bool) -> None: """A write to /TIME passed to the cartridge as the board's own write path passes it (``Board._system_write``): to a board with its own /TIME registers with the byte lanes the 68000 drove (``write_time_lanes``), else its low byte.""" cartridge = self._time_cartridge() lanes = getattr(cartridge, "write_time_lanes", None) if lanes is not None: lanes(address, high, low, word) else: cartridge.write_time(address | 1, low) # -- $A15100-$A153FF: registers --------------------------------------------------- def _register_read(self, address: int) -> int: offset = address & 0x3FF if offset >= 0x180: return self._vdp_access(address, write=False) offset -= 0x100 if offset >= 0x40: # Quirks.unused_registers: as the board reads an undecoded $A1 address. return self.board.open_bus_msb() # type: ignore[union-attr] if offset >= 0x30: self.pwm.run(self.clock * 3 // 7) return self.pwm.read(offset, sh2=False) if offset >= 0x20: return self.comm[(offset - 0x20) >> 1] if offset == 0x00: return (self.adapter & self._adapter_writable) | 0x0080 if offset == 0x02: return self.interrupt_control if offset == 0x04: return self.bank if offset == 0x06: full = 0x80 if len(self.fifo) >= FIFO_WORDS else 0 return self.dreq_control | full if offset == 0x08: return self.dreq_source >> 16 if offset == 0x0A: return self.dreq_source & 0xFFFF if offset == 0x0C: return self.dreq_destination >> 16 if offset == 0x0E: return self.dreq_destination & 0xFFFF if offset == 0x10: return self.dreq_length if offset == 0x12: return self.machine.quirks.fifo_read.value if offset == 0x1A: return self.sega_tv return 0 # $14-$18, $1C, $1E (Quirks.reads_zero) def _register_write(self, address: int, value: int, lanes: int) -> None: offset = address & 0x3FF if offset >= 0x180: self._vdp_access(address, write=True, value=value, lanes=lanes) return offset -= 0x100 if offset >= 0x40: return if offset >= 0x30: self.pwm.run(self.clock * 3 // 7) self.pwm.write(offset, value, lanes, sh2=False) return keep = ~lanes & 0xFFFF value &= lanes if offset >= 0x20: index = (offset - 0x20) >> 1 self.comm[index] = (self.comm[index] & keep) | value elif offset == 0x00: before = self.adapter self.adapter = ((before & keep) | value) & self._adapter_writable if (before ^ self.adapter) & 1: if self.adapter & 1 and self.vector_rom is None: raise BootROMError("ADEN = 1 maps the 32X's 68000 boot ROM; none was given") self.board.update_claims() # type: ignore[union-attr] self._sh2_run() elif offset == 0x02: # INTM/INTS: what is written is what reads back and what requests CMD on the # master/slave; an SH-2's CMD clear clears its bit (``Quirks.cmd_interrupt``). merged = (self.interrupt_control & keep) | value self.interrupt_control = merged & self._int_writable self._cmd_lines() elif offset == 0x04: self.bank = ((self.bank & keep) | value) & self._bank_writable elif offset == 0x06: before = self.dreq_control self.dreq_control = ((before & keep) | value) & self._dreq_writable self._button_with_rv = False if (before ^ self.dreq_control) & 1 and self.adapter & 1: self.board.update_claims() # type: ignore[union-attr] if not self.dreq_control & 4: self.fifo.clear() # "Writing 0 force-ends the operation" (Manual 3.2.1) self._dreq_update() elif offset in (0x08, 0x0A): shift = 16 if offset == 0x08 else 0 word = (self.dreq_source >> shift) & 0xFFFF word = (word & keep) | value other = self.dreq_source & ~(0xFFFF << shift) self.dreq_source = (other | (word << shift)) & self._source_mask elif offset in (0x0C, 0x0E): shift = 16 if offset == 0x0C else 0 word = (self.dreq_destination >> shift) & 0xFFFF word = (word & keep) | value other = self.dreq_destination & ~(0xFFFF << shift) self.dreq_destination = (other | (word << shift)) & self._destination_mask elif offset == 0x10: self.dreq_length = ((self.dreq_length & keep) | value) & self._length_mask elif offset == 0x12: self.fifo_last = (self.fifo_last & keep) | value if self.dreq_control & 4 and len(self.fifo) < FIFO_WORDS: self.fifo.append(self.fifo_last) self._dreq_update() elif offset == 0x1A: self.sega_tv = ((self.sega_tv & keep) | value) & self._sega_tv_writable # $14-$18, $1C, $1E: nothing holds a write (Quirks.reads_zero). def _vdp_access(self, address: int, *, write: bool, value: int = 0, lanes: int = 0) -> int: """$A15180-$A153FF: the VDP registers and the palette. With ADEN = 0 the hardware hangs (``Quirks.vdp_without_aden``); with FM = 1 a read is undefined and a write ignored (``Quirks.vdp_side_with_fm``); otherwise the VDP's registers (``vdp.py``), and a palette access while PEN = 0 waits for it (``Quirks.palette_wait``).""" if not self.adapter & 1: raise Lockup(f"68000 access to ${address:06X} (32X VDP) with ADEN = 0") if self.adapter & 0x8000: return 0 if write else self.board.open_bus_msb() # type: ignore[union-attr] offset = address & 0x3FF if offset < 0x200: if offset >= 0x190: return self.board.open_bus_msb() if not write else 0 # type: ignore[union-attr] if not self._peeking: self._hold("vdp_write" if write else "vdp_read", self._master) if write: self.vdp.write(offset & 0xE, value, lanes, self.clock) return 0 return self.vdp.read(offset & 0xE, self.clock) index = (offset - 0x200) >> 1 if not self._peeking: self._hold("palette_write" if write else "palette_read", self._master) # PEN = 0: held until it is 1 (Manual 3.3; Quirks.palette_wait). wait = self.vdp.palette_wait(self.clock) if wait: self.board.hold(self._master, wait) # type: ignore[union-attr] if write: # Word access only (Manual 3.1); a byte write's lane is taken as it comes. palette = self.vdp.palette palette[index] = (palette[index] & ~lanes & 0xFFFF) | (value & lanes) return 0 return self.vdp.palette[index] # -- the SH-2 side's view (sh2side.py calls these) --------------------------------- def _cmd_lines(self) -> None: """CMD to each SH-2 follows INTM (master) and INTS (slave).""" sh2 = self.sh2 if sh2 is None: return for index in (0, 1): if self.interrupt_control >> index & 1: sh2.assert_source(index, CMD) elif sh2.has_source(index, CMD): sh2.clear_source(index, CMD) def _sh2_run(self) -> None: if self.sh2 is not None: self.sh2.set_run(bool(self.adapter & 1 and self.adapter & 2), self.clock) def _dreq_update(self) -> None: """DREQ0 to both SH-2s' DMAC channel 0 while the FIFO holds a word (``Quirks.dreq_fifo``).""" if self.sh2 is not None: self.sh2.set_dreq0(1 if self.fifo else 0) def sh2_register_read(self, index: int, address: int) -> int: """A word of $20004000-$200043FF from SH-2 ``index`` (0 master, 1 slave).""" offset = address & 0x3FF if offset >= 0x100: if not self.adapter & 0x8000: return 0 # FM = 0: "read is undefined" (Manual 3.1; Quirks.sh2_vdp_without_fm) if offset >= 0x200: self._sh2_palette_wait(index) return self.vdp.palette[(offset - 0x200) >> 1] if offset >= 0x110: return 0 return self.vdp.read(offset & 0xE, self.sh2_mclk(index)) if offset >= 0x40: return 0 if offset >= 0x30: self.pwm.run(self.sh2_mclk(index) * 3 // 7) return self.pwm.read(offset, sh2=True) if offset >= 0x20: return self.comm[(offset - 0x20) >> 1] if offset == 0x00: cart = 0 if self.cartridge is not None else 0x100 return ((self.adapter & 0x8000) | ((self.adapter & 1) << 9) | cart | (0x80 if self.hen else 0) | self.sh2.masks[index]) # type: ignore[union-attr] # fmt: skip if offset == 0x02: return self.standby if offset == 0x04: return self.hcount if offset == 0x06: # FULL/EMPTY of the frame buffer's write FIFO at this access's time # (``Quirks.sh2_dreq_view``, ``Quirks.sh2_framebuffer_fifo``); 68S, bit 1 and # RV as the 68000 set them. sh2 = self.sh2 full, empty = sh2.fifo_status(sh2.cycle_end(index)) # type: ignore[union-attr] return (0x8000 if full else 0) | (0x4000 if empty else 0) | self.dreq_control if offset == 0x08: return self.dreq_source >> 16 if offset == 0x0A: return self.dreq_source & 0xFFFF if offset == 0x0C: return self.dreq_destination >> 16 if offset == 0x0E: return self.dreq_destination & 0xFFFF if offset == 0x10: return self.dreq_length if offset == 0x12: return self._fifo_pop() return 0 def _fifo_pop(self) -> int: """The SH-2 side reads the FIFO (DMA channel 0, or a CPU): the oldest word; the length counts down and 68S clears at 0 (Manual 3.2.1).""" if not self.fifo: return self.fifo_last word = self.fifo.pop(0) self.dreq_length = (self.dreq_length - 1) & 0xFFFF if self.dreq_length == 0: self.dreq_control &= ~4 self._dreq_update() return word def sh2_register_write(self, index: int, address: int, value: int, lanes: int) -> None: offset = address & 0x3FF sh2 = self.sh2 keep = ~lanes & 0xFFFF if offset >= 0x100: if not self.adapter & 0x8000: return # FM = 0: "write is ignored" (Manual 3.1) if offset >= 0x200: self._sh2_palette_wait(index) palette = self.vdp.palette i = (offset - 0x200) >> 1 palette[i] = (palette[i] & keep) | (value & lanes) elif offset < 0x110: self.vdp.write(offset & 0xE, value, lanes, self.sh2_mclk(index)) return if offset >= 0x40: return if offset >= 0x30: self.pwm.run(self.sh2_mclk(index) * 3 // 7) self.pwm.write(offset, value, lanes, sh2=True) return value &= lanes if offset >= 0x20: i = (offset - 0x20) >> 1 self.comm[i] = (self.comm[i] & keep) | value elif offset == 0x00: if lanes & 0xFF00: # FM: "If a 1 is written to the FM bit, access authorization is forced to # switch to the SH2 side" (Manual 3.2.2); ADEN and CART read only. self.adapter = (self.adapter & ~0x8000) | (value & 0x8000) if lanes & 0x00FF: self.hen = bool(value & 0x80) sh2.set_mask(index, value & 0x0F) # type: ignore[union-attr] elif offset == 0x02: self.standby = (self.standby & keep) | value elif offset == 0x04: if lanes & 0x00FF: self.hcount = value & 0xFF elif offset in (0x14, 0x16, 0x18, 0x1A, 0x1C): source = {0x14: VRES, 0x16: VINT, 0x18: HINT, 0x1A: CMD, 0x1C: PWM_INTERRUPT}[offset] sh2.clear_source(index, source) # type: ignore[union-attr] if source == CMD: self.interrupt_control &= ~(1 << index) # $06-$12: the DREQ registers are the 68000's; read only here (testpico # t_32x_reg_w: an SH-2 write to $20004006 leaves RV as it was). def _sh2_palette_wait(self, index: int) -> None: """An SH-2 at the palette while PEN = 0 waits for it (Manual 3.3; Quirks. palette_wait), in its own states.""" wait = self.vdp.palette_wait(self.sh2_mclk(index)) if wait: self.sh2.hold(index, (wait * 3 + 6) // 7) # type: ignore[union-attr] def sh2_mclk(self, index: int) -> int: """The master clock an SH-2 access happens at (its place on the time line).""" return self.sh2.state(index) * 7 // 3 # type: ignore[union-attr] def sh2_framebuffer_read(self, address: int, width: int) -> int: """$04000000-$0403FFFF from an SH-2 (FM = 1); the frame buffer and its overwrite image are the same DRAM, and the range repeats above ($24040000: the 32XDK wiki's mirror; ``Quirks.framebuffer_mirror``).""" if not self.adapter & 0x8000: return 0 buffer = self.framebuffers[self.vdp.fs ^ 1] offset = address & 0x1FFFF if width == 32: return int.from_bytes(buffer[offset : offset + 4], "big") if width == 16: return (buffer[offset] << 8) | buffer[offset + 1] return buffer[offset] def sh2_framebuffer_write(self, address: int, width: int, value: int) -> None: if not self.adapter & 0x8000: return buffer = self.framebuffers[self.vdp.fs ^ 1] offset = address & 0x1FFFF overwrite = address & 0x20000 if width == 8: if value: buffer[offset] = value return data = value.to_bytes(width >> 3, "big") for i, byte in enumerate(data): # A frame-buffer word or longword is written whole; the overwrite image drops # every $00 byte (Manual 3.3, 3.6; testpico t_32x_sh_fb). if byte or not overwrite: buffer[offset + i] = byte