"""A whole console: m68000-python's 68000 and z80-python's Z80 on a :class:`Board`. One scheduler, in master clocks (MCLK) -------------------------------------- Every device's time is a count of master clocks from power-on (docs/timing.md): the 68000 ticks every 7, the Z80 every 15, the VDP by its slot table. The scheduler is the 68000's loop, because the 68000 owns the main bus and makes almost every access that matters to the VDP: 1. before a 68000 step, the VDP is brought up to the step's start and its interrupt level is placed on the 68000's IPL lines; 2. the 68000 runs one instruction (or exception entry); each of its bus accesses is placed at its own clock inside the instruction (``Board.m68k_access_clock``), so the VDP, when touched, catches up to that exact clock; 3. any stall a device imposes (a full FIFO, a DMA holding the bus) is added, in MCLK, to that step, which is how the CPU that suffers it is delayed; 4. the Z80 then runs until it has caught up with the 68000. It also catches up *before* the 68000 changes anything the Z80 can observe -- its RAM, its bus request and reset lines, the YM2612, the bank register -- so a bus request stops the Z80 at the right instruction. Why this shape: the 68000 is the CPU whose accesses have to land on the right clock (the FIFO and slot timing of milestones 2 and 5), and m68000-python reports the clock of each access as it makes it; the Z80's accesses matter mostly by order, and z80-python steps a whole instruction at a time (its access-timing table says where in it each access falls, and the board places its device accesses there), so it runs in the 68000's wake, at most one 68000 instruction behind, with the catch-up points above keeping every shared state change in order. The VDP is lazy (it runs only when read, written, or at the start of a 68000 step) because it has nothing to do between those points that the CPUs could see. When the sound chips are modelled they catch up the same way. """ from __future__ import annotations from m68000_python import AUTOVECTOR, M68000CPU from z80_python import Z80CPU from z80_python.timing import instruction_timing from .arbiter import BUSACK_PROPAGATION_MCLK, CUTOFF_MCLK, busack_grant, z80_access_wait from .audio import AudioPath from .board import CART_REFRESH_MCLK, Z80_CATCH_UP_EACH_CYCLE, Board from .cartridge import Cartridge from .machine import M68K_DIVIDER, Z80_DIVIDER, Machine from .sockets import AudioSource, Clocked, Picture, PortDevice, Reset, SlotDevice, VideoTiming #: The longest Z80 step in T-states (an interrupt entry in IM 2 is 19, the longest #: instruction 23): an instruction that starts this long before a bus request #: has finished before it. MAX_Z80_T = 23 #: 68000 clocks the reset button holds the 68000 in reset: "68k RESET pulse is asserted #: for 128 VCLK" (Eke, forum t=1262; VCLK is the 68000's clock). RESET_PULSE_CLOCKS = 128 #: The reset button restarts the 68000's refresh: the cartridge refresh grid starts #: again from the pulse's start, and a pending work-RAM refresh is cleared, the next #: falling due :data:`RESET_RAM_REFRESH_MCLK` after the pulse's start. A **supported #: finding, not a proven model**: on Nuked-MD (Overdrive 2 from power-on) no cartridge #: read is refresh-stretched before the reset and every one after it lies 0-28 MCLK past #: a multiple of 896 from the pulse's start, and the first refreshed work-RAM access #: comes 2,352-2,408 MCLK after it with unrefreshed ones before; with both, the board's #: 68000 bus cycles match the die's four to five times more closely after the reset #: (docs/worklog.md, "The reset exception, the console model, and the refresh #: contradiction"). The work-RAM refresh's rule after that is not settled. Aubrey #: adopted it knowing the Overdrive 2 picture 7,000 frames on matches the die less #: well with it; ``RESET_RESTARTS_REFRESH = False`` is the board without it. RESET_RESTARTS_REFRESH = True RESET_RAM_REFRESH_MCLK = 2380 #: When the Z80 takes up its bus again, measured on the die model (Nuked-MD, the #: Overdrive 2 run from power-on; docs/worklog.md, "The Z80 after a hold"). Its clock #: runs on through a bus hold and a reset: every one of its accesses falls on the same #: phase of the 15-MCLK clock, which meets the 68000's 7-MCLK clock at a fixed point of #: every 105 (the die's relation, :data:`Z80_CLOCK_PHASE` below). After the 68000's write that #: releases the bus, its next access comes on the first such edge 42 MCLK or more after #: the write began (83 of 83 releases, 42 to 56 MCLK); after the write that releases #: its reset, 57 or more (both releases in the run). And when the reset is released #: with the bus already requested, it makes that first opcode fetch before it lets go #: -- BUSREQ is sampled only at the end of a machine cycle (Zilog UM0080) -- and the #: rest of the instruction waits for the bus. Die-derived. #: The phase was 6 in the die's own time; what is physical is the clocks' relation: the #: die's 68000 edges at 6 mod 7 MCLK and its Z80's at 6 mod 15, against its VDP. The #: board's VDP lines up with the die's 240,277 MCLK apart -- every one of 16,427 HBlank #: flags the die's 68000 read in the Overdrive 2 boot falls where the board's VDP puts #: it at that offset and none other (docs/worklog.md, "The VDPs' offset") -- so in the #: board's time the 68000's edges are at 4 (:data:`M68K_POWER_ON_PHASE`) and the Z80's #: at 14. A real console's relation is whatever its power-on gives; this is the die's. Z80_CLOCK_PHASE = 14 #: Where the 68000's clock edges fall against the VDP's, mod 7 MCLK: the board's 68000 #: starts this far into power-on and keeps the phase (its holds are whole clocks). M68K_POWER_ON_PHASE = 4 #: The E clock's phase at power-on, in 68000 clocks (the core counts its E clock from #: ``M68000CPU.clock``): where an autovectored interrupt acknowledge ends. The die's is #: whatever its power-on gave; this matches its acknowledges (docs/worklog.md, "The #: VDPs' offset", "The DMA's read into room"). M68K_E_CLOCK_POWER_ON = 7 #: How far past the 68000's write to $A11100 the Z80 takes a bus request: it lets go at #: the end of the first machine cycle ending this long or more after the write. /BUSREQ #: falls 18 MCLK after the write begins (Nuked-MD, every write in the logo trace) and #: the Z80 samples it on a cycle's last clock, 15 before its end (Zilog UM0080): 33. It #: was refitted as 48 to the mean of ``run_nuked_md.py busack``'s grants (12.5 68000 #: cycles against the die's 12.55), whose Z80 reads the bank window -- machine cycles #: whose ends the board's probe places only roughly; Overdrive 2's driver, running from #: Z80 RAM, has a grant 49 MCLK after the write at +15,912,659 that 48 cannot give and #: 33 does, and with 33 the boot's 68000 bus stream agrees with the die's over the whole #: 16M MCLK the judge looks at. ``busack``'s mean is then 9.4 (docs/worklog.md, "The #: bus request, sampled"). Die-derived; 0 gives the board's old rule. Z80_BUSREQ_LAG_MCLK = 33 #: A Z80 instruction whose accesses fall both before and past the 68000's clock is left #: for a later catch-up, but its accesses over the 68000's bus before it are arbitrated #: at their own time (``System._prearbitrate``): the first read of a ``pop`` from the #: bank window was settled only once the second's time had come, the 68000 cycles in #: between already run. Die-derived (``run_nuked_md.py arbiter``; docs/worklog.md, #: "Each access arbitrated at its own time"); False settles them all when it runs. Z80_ARBITRATE_PER_ACCESS = 1 #: A hold the arbiter owes the 68000 from a Z80 access settled after its instruction is #: a time the bus is the Z80's until, which its next bus cycle waits for, rather than an #: amount added before its next instruction, where it may first spend clocks inside #: itself: +16,143,521, the Z80's read of $7F08 holds the bus to +16,143,593 and the #: 68000's next fetch, two clocks into a taken branch, comes at +16,143,617 on the die #: and came 14 MCLK later here (docs/worklog.md, "The grant over the 68000's own #: clocks"). Die-derived. OWED_AT_FIRST_CYCLE = 1 #: /BUSAK falls this long after the Z80's last machine cycle ends, its wait states #: included: 7 MCLK after the die's last memory cycle releases /MREQ (all 29 grants of #: the probe), which is part way through the cycle's last T-state; 3 fits with the lag. #: The board placed it :data:`~megadrive_python.arbiter.BUSACK_PROPAGATION_MCLK` (57) #: after the probe's estimate of the cycle's end, which leaves the wait states out -- #: right on average for the probe's bank reads, 50 MCLK late for a Z80 running from #: its own RAM, as Overdrive 2's driver does. False keeps the 57 (and the lag's 33-era #: rule for the grant). Z80_BUSACK_AT_CYCLE_END = True Z80_BUSACK_AFTER_MCLK = 3 Z80_RESUME_MCLK = 42 Z80_RESET_RESUME_MCLK = 57 #: A bus request made while the Z80 is held in reset is granted only after its reset #: is released and the M1 cycle it starts with has run (the request is sampled at that #: cycle's end, as at any other): Nuked-MD, Sonic the Hedgehog from power-on requests #: the bus at +6,850, releases the reset at +6,906, the die's Z80 fetches at +6,945 and #: /BUSAK falls at +6,997, so the 68000's first poll reads "busy" (docs/worklog.md, #: "A second title"). Die-derived. False keeps the grant the request made in reset. Z80_BUSACK_AFTER_RESET = 1 class System: """Machine + cartridge, ready to run.""" def __init__(self, machine: Machine, cartridge: Cartridge | None, *, pads: tuple[object, object] | None = None, tmss_rom: bytes | None = None, slot: SlotDevice | None = None, port: PortDevice | None = None) -> None: # fmt: skip """``slot`` and ``port``: the expansion sockets' devices (docs/expansion-sockets.md), plugged in before power-on; a slot device holds its own cartridge, so ``cartridge`` is then None. Each hears the power-on reset before the 68000 fetches its vectors, which may be the device's.""" self.machine = machine board = self.board = Board(machine, cartridge, pads=pads) if slot is not None: board.attach_slot(slot) if port is not None: board.attach_port(port) if tmss_rom is not None: board.install_tmss_rom(tmss_rom) self.m68k = M68000CPU( board.read_byte, board.read_word, board.write_byte, board.write_word, tas_write=board.tas_write, acknowledge=self._acknowledge, reset_devices=self._reset_instruction, ) # fmt: skip #: Socket 5: the devices run up to the 68000's clock after each of its #: instructions, after the Z80 -- the sockets' devices, and anything else an #: add-on puts here. Empty on a console with nothing plugged in. self.clocked: list[Clocked] = list(board.devices) if hasattr(board.game_cartridge, "catch_up"): # A cartridge with a processor of its own (the SVP's DSP) is one more clock domain. self.clocked.append(board.game_cartridge) #: Socket 8: the sound sources mixed with the FM and the PSG (:meth:`take_audio`). self.audio_sources: list[AudioSource] = [] self.z80 = Z80CPU(board.z80_read, board.z80_write) board.m68k = self.m68k board.catch_up_z80 = self.catch_up_z80 board.z80_busack = self.z80_busack board.on_z80_reset = self._z80_reset_line board.on_z80_resume = self._z80_resume self.vdp = board.vdp #: The analogue path the two sound chips meet in (docs: audio.py). self.audio = AudioPath(machine) #: The 68000's time (MCLK) at the start of its next step. self.mclk = 0 #: The Z80's time (MCLK) at the start of its next step. self.z80_mclk = 0 self._in_z80 = False self.m68k_instructions = 0 #: Access offsets by instruction bytes (:meth:`_z80_offsets`). self._z80_timings: dict[tuple[int, ...], tuple[int, ...]] = {} self.z80_instructions = 0 #: Instructions the Z80 left for later because the 68000 took its bus in the #: middle of them (catch_up_z80). self.z80_deferred = 0 #: The instruction the Z80 is part way through while its bus is held: its start #: and the clock from which its remaining accesses wait (:meth:`_z80_resume`). self._z80_partial: tuple[int, int] | None = None #: Clocks of this instruction's holds already added to the 68000's clock (for #: the E clock at an interrupt acknowledge, :meth:`_acknowledge`). self._stall_credited = 0 #: The reset button has been pressed and the 68000 not yet reset #: (:meth:`press_reset`), and the clock it was pressed at. self.reset_pressed = False self.reset_at = 0 # Power-on: the sockets' devices first (the 68000's vector fetches may be theirs), # then the 68000 takes its reset vector; the Z80 is held in reset. for device in board.devices: device.reset(Reset.POWER_ON, 0) self.m68k.clock = M68K_E_CLOCK_POWER_ON # The YM2612 runs on the 68000's clock (MCLK/7): its edges are the 68000's. self.board.fm.mclk = M68K_POWER_ON_PHASE self.mclk = M68K_POWER_ON_PHASE + self.m68k.reset() * M68K_DIVIDER self._z80_reset_line(True) # -- the expansion sockets that are not on the bus -------------------------------- def attach_video_timing(self, device: VideoTiming) -> None: """Socket 6: ``device`` hears every line as the VDP starts it (:class:`~megadrive_ python.sockets.VideoLine`).""" self.vdp.video_timing = device def attach_picture(self, device: Picture) -> None: """Socket 7: ``device`` takes each finished line and returns the one that leaves the console (``Renderer.attach_picture``).""" self.vdp.renderer.attach_picture(device) def _reset_instruction(self) -> None: """The 68000's RESET instruction (socket 9): m68000-python calls this as the pulse ends, 128 clocks into the instruction (``reset_devices``). Nothing on the board itself is reset by it here (whether the Mega Drive wires the 68000's RESET output anywhere is not in the sources this board follows), so only the sockets' devices hear it.""" devices = self.board.devices if devices: board = self.board t = board.step_start + board.stall + self.m68k.step_clocks * M68K_DIVIDER for device in devices: device.reset(Reset.INSTRUCTION, t) # -- the CPUs' interrupt lines ------------------------------------------------ def _acknowledge(self, level: int) -> int: """The 68000's interrupt-acknowledge cycle: the VDP clears the request it answers; every level is autovectored (MAME's ``cpu_space_map`` as a detector; the Manual, PDF page 19, gives the levels).""" self.vdp.acknowledge(level) # The acknowledge waits for the E clock, which the core reads from its clock # count: bring the holds of this instruction so far into it (the PC push # before the acknowledge may have been held). Die-derived: Nuked-MD's # acknowledge after a push held by a refresh (docs/worklog.md, "The E clock # after a held push"). credit = self.board.stall // M68K_DIVIDER - self._stall_credited self.m68k.clock += credit self._stall_credited += credit return AUTOVECTOR def _z80_reset_line(self, held: bool) -> None: if held: self._z80_partial = None self.board.z80_hold = None # The reset state is applied at once; the Z80 is not stepped while held. z80 = self.z80 z80.request_reset() z80.step() z80.clear_reset() # RESET "clears the Program Counter and registers I and R" (Zilog UM0080, # "Reset"); z80-python 0.4.0 clears PC but leaves I and R, so the board does # it (a workaround: the change is proposed to z80-python, docs/worklog.md). z80.i = 0 z80.r = 0 # -- running -------------------------------------------------------------------- def catch_up_z80(self, mclk: int, stopping: bool = False) -> None: """Run the Z80 until its time reaches ``mclk`` (no-op inside a Z80 step). ``stopping``: the caller is about to take the bus from the Z80 or reset it at ``mclk``. The Z80 samples BUSREQ "with the rising edge of the last clock period of any machine cycle" and lets go of the bus after it (Zilog UM0080, "Bus Request/Acknowledge Cycle"; specification tier, and MAME 0.285 agrees: Sonic's handshake reads the Z80 RAM byte the interrupted instruction had not yet written, docs/worklog.md). So an instruction under way at ``mclk`` whose memory accesses are not all started by then does not run now: it is left for when the Z80 has the bus again (:meth:`z80_access_offsets` estimates where the accesses fall). """ if self._in_z80: return board, z80, vdp = self.board, self.z80, self.vdp self._in_z80 = True try: while self.z80_mclk < mclk: if not board.z80_running: if self._z80_partial is None: self.z80_mclk = mclk break sampled = mclk + Z80_BUSREQ_LAG_MCLK if stopping else mclk if stopping and self.z80_mclk + MAX_Z80_T * Z80_DIVIDER >= sampled: offsets = self._z80_offsets() # the table's, as the horizon below if any(self.z80_mclk + t >= sampled for t in offsets): # The machine cycle under way when the request is sampled # finishes; the accesses after it wait for the bus # (:meth:`_z80_resume`). ends = [self.z80_mclk + t * Z80_DIVIDER for t in self.z80_machine_cycle_ends()] # fmt: skip let_go = next((end for end in ends if end >= sampled), sampled) self._z80_partial = (self.z80_mclk, let_go) self.z80_deferred += 1 break if vdp.z80_irq_at(self.z80_mclk): z80.request_maskable_interrupt(0xFF) if z80.iff1 and not z80._ei_delay: # z80-python's acceptance test # The acknowledge takes this step; the table times instructions. board.z80_offsets = None else: board.z80_offsets = self._z80_offsets() else: z80.clear_maskable_interrupt() board.z80_offsets = self._z80_offsets() offsets = board.z80_offsets if offsets and self.z80_mclk + offsets[-1] >= mclk and not board.z80_hold: # An access of this instruction would fall past the 68000's clock, # where the arbiter cannot yet see the 68000's bus: it runs at the # next catch-up, which reaches past it (``Board._bank_delay``). Its # accesses over the 68000's bus that come before are settled now. if Z80_ARBITRATE_PER_ACCESS and board.arbiter_enabled: self._prearbitrate(mclk) break board.z80_access = 0 board.z80_bus_access = 0 board.step_start = self.z80_mclk board.z80_stall = 0 hold = board.z80_hold[1] if board.z80_hold else 0 self.z80_mclk += z80.step() * Z80_DIVIDER + board.z80_stall + hold board.z80_hold = None board.z80_prearbitrated = None self.z80_instructions += 1 finally: self._in_z80 = False board.step_start = self.mclk def _prearbitrate(self, mclk: int) -> None: """The Z80's next instruction is left for a later catch-up, but its accesses over the 68000's bus that begin before ``mclk`` are arbitrated now, at their own time, so the 68000 cycle they hold is the one the die's is (:data:`Z80_ARBITRATE_PER_ACCESS`); the instruction takes their waits when it runs (``Board._bank_delay``). Where the accesses fall comes from a probe of the instruction, made once.""" board = self.board offsets = board.z80_offsets if offsets is None or board.z80_hold or self._z80_partial is not None: return # an interrupt's acceptance, or a held or split instruction start = self.z80_mclk done = board.z80_prearbitrated if done is None or done[0] != start: # Nothing to settle unless an access past the opcode's own fetches comes # before mclk (a prefix is fetched first), or the code runs from the # 68000's side of the bus: then the probe, which runs the instruction, is # spared. before = sum(1 for at in offsets if start + at < mclk) pc = self.z80.pc fetched = 2 if board.z80_peek(pc) in (0xCB, 0xDD, 0xED, 0xFD) else 1 if before <= fetched and pc < 0x4000: return self.z80_probe() ends = (at for _end, at in self._probe_bus_ends) bus = sorted(zip(ends, self._probe_bus_cart, strict=False)) done = board.z80_prearbitrated = (start, [], bus) waits, bus = done[1], done[2] extra = sum(wait for wait, _ in waits) * Z80_DIVIDER for at, cartridge in bus[len(waits) :]: # The probe gives the machine cycle's first T-state; the access-timing table, # by which the access is placed when it runs (``Board._z80_access_time``), # puts it a T-state on (75 MCLK for the read in T-state 4). t = start + (at + 1) * Z80_DIVIDER + extra if t >= mclk: # as an instruction runs only with every access before mclk break settled = board._arbitrate(t, cartridge) waits.append(settled) extra += settled[0] * Z80_DIVIDER def _z80_resume(self, t: int, reset: bool) -> None: """The 68000's write at ``t`` has given the Z80 its bus back, or released its reset (:data:`Z80_RESUME_MCLK`). An instruction left part way through (``_z80_partial``) resumes with its remaining accesses moved to that edge on; otherwise the next instruction's opcode fetch falls there.""" wait = Z80_RESET_RESUME_MCLK if reset else Z80_RESUME_MCLK edge = t + wait + (Z80_CLOCK_PHASE - t - wait) % Z80_DIVIDER board = self.board if reset and board.z80_bus_requested: # The opcode fetch, T1 of a four-T-state M1 cycle, before the bus goes. start = edge - Z80_DIVIDER self.z80_mclk = start self._z80_partial = (start, start + 4 * Z80_DIVIDER) if Z80_BUSACK_AFTER_RESET and board.arbiter_enabled: # The grant asked for during the reset comes after that M1 cycle. board.busack_at = max(board.busack_at, start + 4 * Z80_DIVIDER + Z80_BUSACK_AFTER_MCLK) # fmt: skip return if self._z80_partial is None: self.z80_mclk = max(self.z80_mclk, edge - Z80_DIVIDER) return start, let_go = self._z80_partial self._z80_partial = None # Everything after the machine cycle it let go at moves by the same amount, so # the T-state that follows -- an access, or an internal one -- comes at the # edge, and internal T-states between the two stay where the instruction puts # them (the die: the fetch at $0621 of Overdrive 2's driver, its internal # T-states after the release, its next read 122 MCLK after it; docs/worklog.md # "The bus holds"). An access's time is its T1's start plus one T-state, the # table's convention, hence the Z80_DIVIDER. board.z80_hold = (let_go, max(0, edge - Z80_DIVIDER - let_go)) def _z80_offsets(self) -> tuple[int, ...]: """Where each memory access of the Z80's next instruction falls, in master clocks from its start: z80-python's access-timing table (``timing``, ``instruction_timing``; derived from the SingleStepTests corpus, so emulator-derived), read at PC with no side effects and kept by the instruction's first four bytes.""" board, pc = self.board, self.z80.pc key = tuple(board.z80_peek((pc + i) & 0xFFFF) for i in range(4)) offsets = self._z80_timings.get(key) if offsets is None: timing = instruction_timing(key) offsets = tuple(a.t * Z80_DIVIDER for a in timing.accesses if a.kind in ("read", "write")) # fmt: skip self._z80_timings[key] = offsets return offsets def z80_access_offsets(self) -> list[int]: """The T-state offsets of :meth:`z80_probe`.""" return self.z80_probe()[0] def z80_busack(self, mclk: int) -> int: """The master clock /BUSAK reaches the 68000, for a request made at ``mclk``. BUSREQ "is sampled by the CPU with the rising edge of the last clock period of any machine cycle" and the bus is released after it (Zilog UM0080, specification tier), so the Z80 lets go at the end of the machine cycle in progress; the arbiter then takes :data:`~megadrive_python.arbiter.BUSACK_PROPAGATION_MCLK` to report it (fitted to Nuked-MD, die-derived: the specification says when the Z80 lets go, the referee says how long the board takes to say so). The Z80 is first run up to the request, leaving at most one instruction -- the one the request falls inside -- unrun; its machine-cycle boundaries are the probe's (:meth:`z80_machine_cycle_ends`), and that instruction is executed when the bus comes back, as before. """ self.catch_up_z80(mclk, stopping=True) sampled = mclk + Z80_BUSREQ_LAG_MCLK if not self.board.z80_running or not Z80_BUSACK_AT_CYCLE_END: if self.z80_mclk >= mclk or not self.board.z80_running: return max(mclk, self.z80_mclk) + BUSACK_PROPAGATION_MCLK ends = [self.z80_mclk + t * Z80_DIVIDER for t in self.z80_machine_cycle_ends()] return busack_grant(sampled, ends) if self.z80_mclk >= sampled and self._z80_partial is None: # The instruction the request fell in has run to its end, its last machine # cycle the one that took the request. return self.z80_mclk + Z80_BUSACK_AFTER_MCLK if self._z80_partial is not None: return self._z80_partial[1] + Z80_BUSACK_AFTER_MCLK ends = [self.z80_mclk + t * Z80_DIVIDER for t in self.z80_machine_cycle_ends()] # A machine cycle over the 68000's bus is as long as the arbiter makes it: its # wait states push it and every later one back (the probe places 3 T-states). board, start = self.board, self.z80_mclk for end_t, at_t in self._probe_bus_ends: wait, _, _ = z80_access_wait(start + at_t * Z80_DIVIDER, board.m68k_accesses) extra = wait * Z80_DIVIDER cut = start + end_t * Z80_DIVIDER ends = [e + extra if e >= cut else e for e in ends] let_go = next((e for e in ends if e >= sampled), sampled) return let_go + Z80_BUSACK_AFTER_MCLK def z80_machine_cycle_ends(self) -> list[int]: """Where the next Z80 step's machine cycles end, in T-states from its start. The probe places each fetch and data access (:meth:`z80_probe`); a machine cycle ends where the next begins, and the step's own total ends the last one, so trailing internal T-states belong to the cycle before them. """ return self.z80_probe()[2] def z80_probe(self) -> tuple[list[int], dict[int, int], list[int]]: """When the Z80's next step would start each of its data accesses, in T-states from the step's start: an estimate, with no effect on the machine. The step is run once on a probe bus that records its accesses, and the CPU's state is then restored. (z80-python's access-timing table, which :meth:`_z80_offsets` reads, now gives the same exactly; the probe predates it.) The leading reads at PC, PC+1, ... are the fetches: 4 T-states for the first opcode byte and for an opcode after a DD/ED/FD/CB prefix, 3 for other bytes (UM0080's M1 and memory-read cycles); each data access takes 3. Internal T-states are not placed (the core does not say where they fall), so each estimate is the earliest the access can start. Reads of devices return $FF on the probe bus: only RAM and ROM are read, so a probe has no side effects. Returns the offsets, the writes the step would make ({address: value}), and where each machine cycle ends (every fetch's and access's end, and the step's own total, so that trailing internal T-states belong to the cycle before them). """ z80, board = self.z80, self.board state = z80.capture_state() read, write = z80.read_byte, z80.write_byte offsets: list[int] = [] ends: list[int] = [] self._probe_bus_ends = bus_ends = [] # machine cycles over the 68000's bus self._probe_bus_cart = bus_cart = [] # ... and whether each is to the cartridge written: dict[int, int] = {} clock = 0 fetching = True next_fetch = z80.pc after_prefix = True # the first byte is an M1 fetch def probe_read(address: int) -> int: nonlocal clock, fetching, next_fetch, after_prefix if address in written: value = written[address] elif address < 0x4000: value = board.z80_ram[address & 0x1FFF] else: # The bank window through the board's one decode, so a socket's device # answers the probe as it will the access (``Board.z80_peek``). value = board.z80_peek(address) if fetching and address == next_fetch: clock += 4 if after_prefix else 3 after_prefix = value in (0xCB, 0xDD, 0xED, 0xFD) and after_prefix next_fetch = (address + 1) & 0xFFFF else: fetching = False offsets.append(clock) clock += 3 if address >= 0x8000 or 0x7F00 <= address < 0x7F20: bus_ends.append((clock, offsets[-1])) bus_cart.append(address >= 0x8000 and (board.bank | (address & 0x7FFF)) < 0x800000) # fmt: skip ends.append(clock) return value def probe_write(address: int, value: int) -> None: nonlocal clock, fetching fetching = False written[address] = value offsets.append(clock) clock += 3 if address >= 0x8000 or 0x7F00 <= address < 0x7F20: bus_ends.append((clock, offsets[-1])) bus_cart.append(address >= 0x8000 and (board.bank | (address & 0x7FFF)) < 0x800000) # fmt: skip ends.append(clock) z80.read_byte, z80.write_byte = probe_read, probe_write try: total = z80.step() finally: z80.read_byte, z80.write_byte = read, write z80.restore_state(state) return offsets, written, sorted({*(e for e in ends if e < total), total}) def press_reset(self, at: int | None = None) -> None: """The console's reset button: not a power cycle. Measured on hardware (forum t=1262): the button pulses VRES#, which goes "to 68000 and cartridge connector", and "the 68k RESET pulse is asserted for 128 VCLK" with /HALT (Charles MacDonald, and Eke against the 68000's clock); "when RESET button is pressed, !ZRES is held low at the same time ... but remains low after that until software enables it again" (Eke), so the Z80 and the YM2612 are held in reset until the game writes $A11200. SRES#, which resets the VDP and the I/O chip, "is only asserted on a cold boot", so they are left alone, as is the cartridge's board (what one does with VRES# is not in these sources). ZRES is asserted now; the 68000 is held and reset at its next step. The variable delay from the switch to the pulse -- "Minimum is 2.1ms" -- is not modelled: the pulse starts at the next instruction. ``at``: the master clock the button is pressed at, if not now -- a time at or after the 68000's (``mclk``), before its next step; the 68000 is held from there. The referee comparisons press it at an exact clock (docs/worklog.md, Session 14). """ self.reset_at = self.mclk if at is None else max(at, self.mclk) self.board.set_z80_reset(True, self.reset_at) self.reset_pressed = True # VRES# also goes "to 68000 and cartridge connector" (above): the sockets' devices # hear the button, and each decides what it resets (socket 9). for device in self.board.devices: device.reset(Reset.BUTTON, self.reset_at) # ... and so does the cartridge, if its board has anything that counts presses. press = getattr(self.board.cartridge, "reset", None) if press is not None: press() def step(self) -> int: """One 68000 instruction, then the Z80 up to the same time; returns MCLK.""" board, cpu, vdp = self.board, self.m68k, self.vdp if self.reset_pressed: # The 68000 is held in reset for the pulse, the rest of the machine running # on, then takes the reset exception (which brings a halted one back too). # Its bus cycles -- the vectors and the first prefetch -- come after the # pulse, stamped at their own clocks, so the refresh and the arbiter see # them where they are (Nuked-MD: the vector fetch 98 MCLK after the pulse # ends, taking the cartridge refresh that falls due then; docs/worklog.md # "The reset exception"). self.reset_pressed = False start = self.mclk vdp.sync(start) # Held from the press, on the 68000's next clock edge at or after it. held = -(-(self.reset_at - start) // M68K_DIVIDER) * M68K_DIVIDER cpu.clock += RESET_PULSE_CLOCKS + held // M68K_DIVIDER board.step_start = start + held + RESET_PULSE_CLOCKS * M68K_DIVIDER if RESET_RESTARTS_REFRESH: board.cart_refresh_due = start + held + CART_REFRESH_MCLK board.ram_refresh_due = start + held + RESET_RAM_REFRESH_MCLK board.stall = 0 # What the arbiter charged the 68000 for the Z80's bank accesses before the # press is spent in the pulse: the 68000 is held there, not running. board.m68k_pending_stall = 0 if board.m68k_accesses: board.m68k_accesses.clear() clocks = cpu.reset() elapsed = held + (RESET_PULSE_CLOCKS + clocks) * M68K_DIVIDER + board.stall self.mclk = start + elapsed self.catch_up_z80(self.mclk) if self.clocked: for device in self.clocked: device.catch_up(self.mclk) return elapsed owed = board.m68k_pending_stall if owed and OWED_AT_FIRST_CYCLE and Z80_CATCH_UP_EACH_CYCLE and board.arbiter_enabled: # The bus is the Z80's until then: the 68000's first bus cycle waits for it, # and the clocks it spends inside itself before that overlap the wait. board.m68k_pending_stall = 0 board.m68k_resume_at = self.mclk + owed elif owed: # What the arbiter charged the 68000 for Z80 bank accesses made in the wake # of its last instruction: the Z80 runs behind it, so the delay is added # here rather than inside the instruction it really fell in (arbiter.py). board.m68k_pending_stall = 0 self.mclk += owed cpu.clock += owed // M68K_DIVIDER # keeps the E-clock phase in step start = self.mclk board.step_start = start board.stall = 0 self._stall_credited = 0 board.z80_space_stall = 0 if board.m68k_accesses: board.m68k_accesses.clear() vdp.sync(start) cpu.set_ipl(vdp.ipl) clocks = cpu.step() stall = board.stall elapsed = clocks * M68K_DIVIDER + stall if stall: # Keeps the E-clock phase in step (what an acknowledge already took aside). cpu.clock += stall // M68K_DIVIDER - self._stall_credited self.mclk = start + elapsed self.m68k_instructions += 1 board.m68k_step_end = self.mclk # Not into the arbiter's cut-off before the 68000's next cycle, which may win # the bus from a Z80 access asked for there (``board.Z80_CATCH_UP_EACH_CYCLE``). lead = CUTOFF_MCLK if Z80_CATCH_UP_EACH_CYCLE and board.arbiter_enabled else 0 self.catch_up_z80(self.mclk - lead) if self.clocked: # Socket 5: the other clock domains, up to the 68000's clock. for device in self.clocked: device.catch_up(self.mclk) return elapsed def run_frame(self) -> None: """Run until the VDP starts its next frame, then bring the sound chips up to the same clock so their sample queues fill a frame at a time.""" frame = self.vdp.frame while self.vdp.frame == frame: self.step() self.board.sound_sync(self.mclk) def take_audio(self) -> list[tuple[int, int]]: """The stereo samples finished since the last call, at the host rate. Both chips are brought up to the 68000's clock first, so a caller that only drains at long intervals still gets every sample. """ self.board.sound_sync(self.mclk) # The PSG is mono here: both sides of its samples are the same level. psg = [left for left, _right in self.board.psg.take_samples()] fm = self.board.fm.take_samples() if self.audio_sources: # Socket 8: each further source up to the same clock, at its own rate. taken = [(source, source.take_samples(self.mclk)) for source in self.audio_sources] return self.audio.mix(fm, psg, taken) return self.audio.mix(fm, psg) def run_mclk(self, mclk: int) -> None: target = self.mclk + mclk while self.mclk < target: self.step()