# SPDX-License-Identifier: MIT """The Lynx board: one 16 MHz tick line, the CPU's bus callbacks, the memory map. Domains and channels (charter, "Domains and channels"): the whole machine is one clock domain, the 16 MHz crystal; the CPU, Mikey's timers and display, Suzy and the cart port all advance on the one tick counter here, in the order of record: a CPU bus cycle charges its ticks, then Mikey runs up to the cycle's end, then the access is made. The channels between the parts are the bus (this module), the interrupt line (Mikey -> CPU), the cart port (Mikey drives its address lines, Suzy strobes and reads it: :mod:`lynx_python.cart.port`) and the bus grant (Mikey's CPUSLEEP <-> Suzy's sprite engine). Audio synthesis is a pure producer of Mikey's register state over time. Modelling levels: CPU cycle level (w65c02-python, one callback per bus cycle); Mikey timers cycle level; tick costs per bus cycle from the documents and the hardware tests. """ from __future__ import annotations from lynx_python.cart.port import CartPort from lynx_python.machine import DEFAULT, Machine from lynx_python.mikey import Mikey from lynx_python.mikey.display import DMA_TICKS from lynx_python.suzy import Suzy # -- CPU cycle costs in ticks (Spec §4 "CPU Cycle Tick Summary", DOC; LT page-mode) ------- # MEASURED below means: decoded from the Lynx II logic-analyser captures with this # repository's own scripts (scripts/la_trace.py, la_compare.py, la_registers.py, # la_refresh.py, la_dma.py); docs/validation.md "M2 (bus costs from the captures)". PAGE_MODE_TICKS = 4 # DOC + MEASURED: a page-mode RAM/ROM read of the instruction stream NORMAL_TICKS = 5 # DOC + MEASURED: normal RAM/ROM read or write; Mikey registers; Suzy write # MEASURED (la_registers.py, lynx2-mikey-refresh_rate-* captures, 879-1,387 reads each): # a read of Suzy's SCB/math register file ($FC00) takes 10 ticks, a read of her other # registers ($FC92 SPRSYS, $FCB0 JOYSTICK) 9. Other addresses are given the cost of the # group they belong to (HYPOTHESIS). DOC Spec §4: 9 to 15. SUZY_FILE_READ_TICKS = 10 SUZY_READ_TICKS = 9 CART_READ_TICKS = 15 # DOC Spec §9: "The CPU cycle that performed the actual read uses 15 ticks" # The timer/audio dual-ported RAM ($FD00-$FD3F). MEASURED (la_compare.py on # lynx2-mikey-page_mode, la_registers.py on three refresh_rate captures): an access # ends on its timer's slot, which recurs every 16 ticks; timer n's slot (audio channel c # is timer 8 + c) ends 1 tick after timer n-1's (timers 0, 2, 6 and audio 0 measured); # lengths seen 5 to 20 ticks (DOC Spec §4: "5 to 20"), so an access takes 5 ticks plus # the wait for the slot: 5 + ((slot end - start - 5) mod 16). DPRAM_CYCLE = 16 # The slot phase against the timer prescaler is not in the captures (no timer edge is # visible on the bus). FITTED: see docs/validation.md "M2 (bus costs from the captures)". DPRAM_PHASE = 0 # DRAM refresh. MEASURED (la_refresh.py, la_dma.py): every display DMA half-burst is # followed by one refresh cycle (row = column, a counter); in lines without display # DMA a refresh cycle of 4 ticks takes the bus every 256 ticks (spacings 250-260, mean # 256), at the next CPU cycle boundary, and the CPU's next access opens a new row. The # refresh request's phase equals the timer 0 slot end modulo 16 in all four captures # measured (la_refresh.py + la_registers.py); its phase modulo 256 is unknown # (HYPOTHESIS: the slot phase). REFRESH_PERIOD = 256 REFRESH_TICKS = 4 # FITTED to the capture's alignment (scripts/la_phase.py on lynx2-mikey-page_mode: the # refresh cycles fall where the capture has them for this phase and no other of 21 tried). REFRESH_PHASE = DPRAM_PHASE + 140 class Lynx: """A Lynx console: RAM, boot ROM, Mikey, Suzy, the CPU, a cart.""" __slots__ = ( "cpu", "frame_ticks", "frames", "irq_line", "last_page", "last_stream", "machine", "mapctl", "mikey", "next_refresh", "on_sleep", "port", "ram", "rom", "row_open", "stream_open", "suzy", "tick", ) # fmt: skip def __init__( self, bank0: bytes = b"", block0: int = 1024, *, machine: Machine = DEFAULT, boot_rom: bytes | None = None, bank1: bytes = b"", block1: int = 0, ) -> None: self.machine = machine # HYPOTHESIS (U15): power-on RAM contents are not documented; zeros. self.ram = bytearray(0x10000) self.rom = bytes(boot_rom) if boot_rom is not None else None self.port = CartPort(bank0, block0, bank1, block1) self.mikey = Mikey(self.port, machine.stereo) self.mikey.ram = self.ram # display DMA reads the same RAM (the bus is the channel) self.suzy = Suzy(self.port) self.cpu = machine.cpu(self._read, self._write) self.tick = 0 self.mapctl = 0 # DOC Appx 2: MAPCTL reset = 0 (everything overlaid, page mode on) self.stream_open = False self.row_open = False self.last_stream = -2 # address of the last instruction-stream read self.last_page = False # the last CPU cycle was a page-mode read self.irq_line = False self.frames = 0 self.frame_ticks = 0 self.on_sleep = None # a test hook replacing the CPUSLEEP hold self.next_refresh = REFRESH_PHASE # -- running ------------------------------------------------------------------------- def reset(self) -> None: self.cpu.request_reset() def step(self) -> int: return self.cpu.step() def run_ticks(self, ticks: int) -> None: end = self.tick + ticks step = self.cpu.step while self.tick < end: step() # -- the bus ----------------------------------------------------------------------- def _read_cost(self, address: int) -> int: """Ticks of a CPU read of RAM or the boot ROM. MEASURED (``scripts/la_compare.py`` against ``lynx2-mikey-page_mode``, and ``la_trace.py`` on the refresh_rate captures' interrupt routine), agreeing with TEST ROM + the LT page-mode guide where it states a rule: - A read of the instruction stream (an opcode or operand byte, the byte a one-byte instruction reads and drops, an RTS's second cycle, a taken branch's extra cycle: every read at the address after the last stream read) takes 4 ticks when page mode is on (MAPCTL bit 7 clear), the stream is open, the DRAM row is still open (no DMA or refresh in between), ``address & $0F != 0`` and the address is the last stream address or the one after it. Otherwise 5, and it opens the stream. So a branch, JSR or RTS target costs 5 (the captures: every one is a new row). - Any other read (data, stack, pointers) is 5 and closes the stream. So is the last cycle of an RTS (a read at the pulled address, not after the last stream byte): the captured opcode after it is a new row, 5 ticks. - While Mikey's interrupt line is asserted no page-mode read follows a page-mode read (MEASURED: the refresh_rate interrupt routine alternates new-row and page-mode reads throughout; why is unknown, U22). """ cpu = self.cpu if cpu.sync or ( (cpu.fetch or self.stream_open) and address == (self.last_stream + 1) & 0xFFFF ): fast = ( self.stream_open and self.row_open and address & 0x0F and 0 <= (address - self.last_stream) & 0xFFFF <= 1 and not self.mapctl & 0x80 and not (self.irq_line and self.last_page) ) self.stream_open = True self.last_stream = address self.last_page = bool(fast) return PAGE_MODE_TICKS if fast else NORMAL_TICKS self.stream_open = False self.last_page = False return NORMAL_TICKS def _dpram_cost(self, address: int) -> int: """Ticks of a CPU access to the timer/audio DPRAM (see ``DPRAM_CYCLE``).""" reg = address & 0xFF slot = reg >> 2 if reg < 0x20 else 8 + ((reg - 0x20) >> 3) end = DPRAM_PHASE + slot return NORMAL_TICKS + (end - self.tick - NORMAL_TICKS) % DPRAM_CYCLE def _advance(self, ticks: int) -> None: self.tick += ticks mikey = self.mikey mikey.run_until(self.tick) # The interrupt line follows Mikey's pending bits as they change, not only on a # register access (a program waiting in RAM for its interrupt handler's flag). if (mikey.timers.pending != 0) != self.irq_line: self._irq() def _video(self) -> None: """Display DMA takes the bus before the next CPU or Suzy cycle. DOC (Spec Appx "bus interplay"): priority video, refresh, CPU, Suzy. The CPU cycle in progress completes first (HYPOTHESIS: the burst starts at the next cycle boundary; Spec appendix 7, the bus state machine, is lost: U5). The burst closes the CPU's DRAM row (LT page-mode: the next CPU access is 5 ticks). """ times = self.mikey.display.dma_times while times and times[0] <= self.tick: times.pop(0) self.tick += DMA_TICKS self.row_open = False self.mikey.run_until(self.tick) def _refresh(self) -> None: """DRAM refresh takes the bus (DOC Spec Appx "bus interplay": priority video, refresh, CPU, Suzy; "video and refresh requests should occur together"). In a line with display DMA the refresh rides on the DMA bursts (inside ``DMA_TICKS``); otherwise a 4-tick cycle every 256 ticks (MEASURED: see ``REFRESH_PERIOD``).""" while self.next_refresh <= self.tick: self.next_refresh += REFRESH_PERIOD if not self.mikey.display.fetching(): self.tick += REFRESH_TICKS self.row_open = False self.mikey.run_until(self.tick) def _irq(self) -> None: line = self.mikey.irq_bits() != 0 if line != self.irq_line: self.irq_line = line if line: self.cpu.request_maskable_interrupt() else: self.cpu.clear_maskable_interrupt() def _read(self, address: int) -> int: dma = self.mikey.display.dma_times if dma and dma[0] <= self.tick: self._video() if self.next_refresh <= self.tick: self._refresh() mapctl = self.mapctl if address < 0xFC00 or address == 0xFFF8: return self._ram_read(address) if address < 0xFD00: if mapctl & 0x01: return self._ram_read(address) self._register_cycle() reg = address & 0xFF if reg in (0xB2, 0xB3): cost = CART_READ_TICKS else: cost = SUZY_FILE_READ_TICKS if reg < 0x80 else SUZY_READ_TICKS self._advance(cost) value = self.suzy.read(address, self.tick) self._irq() return value if address < 0xFE00: if mapctl & 0x02: return self._ram_read(address) self._register_cycle() self._advance(self._dpram_cost(address) if address < 0xFD40 else NORMAL_TICKS) value = self.mikey.read(address) self._irq() return value if address == 0xFFF9: self._register_cycle() self._advance(NORMAL_TICKS) # MEASURED + TEST ROM (LT page-mode): 5 ticks return self.machine.mapctl_readback(mapctl) rom_mapped = not (mapctl & 0x08) if address >= 0xFFFA else not (mapctl & 0x04) if not rom_mapped or self.rom is None: return self._ram_read(address) self._advance(self._read_cost(address)) self.row_open = True return self.rom[address - 0xFE00] def _register_cycle(self) -> None: """A register access is a data cycle: it closes the stream and the DRAM row.""" self.stream_open = False self.last_page = False self.row_open = False def _ram_read(self, address: int) -> int: self._advance(self._read_cost(address)) self.row_open = True return self.ram[address] def _write(self, address: int, value: int) -> None: dma = self.mikey.display.dma_times if dma and dma[0] <= self.tick: self._video() if self.next_refresh <= self.tick: self._refresh() self.stream_open = False self.last_page = False mapctl = self.mapctl if address < 0xFC00 or address == 0xFFF8: self._advance(NORMAL_TICKS) self.row_open = True self.ram[address] = value return if address < 0xFD00 and not mapctl & 0x01: self._advance(NORMAL_TICKS) # DOC: Suzy writes are blind 5-tick cycles self.row_open = False self.suzy.write(address, value, self.tick) self._irq() return if 0xFD00 <= address < 0xFE00 and not mapctl & 0x02: self._advance(self._dpram_cost(address) if address < 0xFD40 else NORMAL_TICKS) self.row_open = False reg = address & 0xFF if reg == 0x90: self.mikey.sdone_pending = 0 # DOC SDONEACK: any value acknowledges (C4) elif reg == 0x91: self._sleep() else: self.mikey.write(address, value) self._irq() return if address == 0xFFF9: self._advance(NORMAL_TICKS) self.row_open = False # DOC Appx 2: Mikey and Suzy both accept the write; only bit 0 matters to Suzy. self.mapctl = value return # RAM under the overlays, and the ROM space. HYPOTHESIS (U14): a write to the ROM # space with the overlay on reaches the RAM underneath. self._advance(NORMAL_TICKS) self.row_open = True self.ram[address] = value def _sleep(self) -> None: """A write to CPUSLEEP ($FD91): the CPU drops its bus request and Suzy runs. DOC Spec §4 "CPU Sleep" and §16: "the CPU will NOT remain asleep unless Suzy is using the bus"; §18: an unacknowledged Suzy completion, or any Mikey interrupt "regardless of the state of the CPU enable interrupt bit", keeps the CPU from sleeping (C4: TEST ROM sdoneack 1-10). LT timers: an enabled pending interrupt wakes it; Suzy then waits and software sleeps again. The CPU's next cycle happens after this callback returns: the hold is inside the write, as the core's contract allows (``note_stall``). """ if self.on_sleep is not None: self.on_sleep(self) return suzy, mikey = self.suzy, self.mikey if not (suzy.sprite_busy and suzy.busen) or mikey.sdone_pending: return cpu = self.cpu cpu.note_stall() while not mikey.irq_bits(): if suzy.run_engine(self): suzy.sprite_busy = 0 suzy.sprgo &= ~1 mikey.sdone_pending = 1 # DOC: Suzy's done, to be acknowledged by SDONEACK break cpu.note_stall() def suzy_cycles(self, ticks: int) -> None: """Suzy owns the bus for ``ticks`` (the sprite engine calls this per access).""" dma = self.mikey.display.dma_times if dma and dma[0] <= self.tick: self._video() # Suzy yields to video (DOC Spec §4: within 40 ticks) if self.next_refresh <= self.tick: self._refresh() # and to refresh (DOC Appx "bus interplay") self.tick += ticks self.row_open = False self.mikey.run_until(self.tick) # -- inspection ---------------------------------------------------------------------- def peek(self, address: int) -> int: """What the CPU would read, without side effects or time (for traces and tools).""" if 0xFC00 <= address < 0xFD00 and not self.mapctl & 1: return 0 if 0xFD00 <= address < 0xFE00 and not self.mapctl & 2: return 0 vectors = address >= 0xFFFA and not self.mapctl & 8 rom_space = 0xFE00 <= address < 0xFFF8 and not self.mapctl & 4 if self.rom and (vectors or rom_space): return self.rom[address - 0xFE00] return self.ram[address]