"""A 68000-to-VDP transfer owns the 68000's bus: a Z80 access over that bus waits it out. On the die a Z80 cartridge read asked for while a transfer holds the bus lasts until the transfer's last read (645 to 1,395 MCLK behind a 40-word one, 113,235 behind a 3,376-word one), and the 68000's cycle after it is only stretched (od2-20k ``flaws/FABLE-HANDOFF.md``, 2026-11-11, "The Z80 waits out a DMA"). """ from __future__ import annotations from megadrive_python.arbiter import ( CUTOFF_MCLK, DMA_Z80_GRANT_MCLK, DMA_Z80_RESUME_MCLK, OWN_CYCLE_CARTRIDGE_MCLK, RELEASE_MCLK, ) from megadrive_python.cartridge import Cartridge from megadrive_python.machine import MACHINES from megadrive_python.system import System def idle_board(machine: str = "nuked-md"): board = System(MACHINES[machine], Cartridge(bytes(0x10000))).board board.z80_reset = board.z80_bus_requested = False board.cart_refresh_due = 10_000_000 board.z80_refresh_taken = -1 board.m68k_accesses = [] board.m68k_step_end = 990 board.m68k_pending_stall = 0 return board def test_no_transfer_no_hold() -> None: board = idle_board() assert board.arbiter_grid(1000) is board.m68k_accesses assert board._arbitrate(1000, True)[0] == 2 def test_an_access_inside_a_transfer_waits_for_its_last_read() -> None: board = idle_board() board.dma_bus = (900, 60_000, 60_034) wait, _m68k = board._arbitrate(1000, True) # The Z80's own cycle begins DMA_Z80_GRANT_MCLK after the last read, on the 68000's # clock edge (at most 6 later), and its wait ends on the first Z80 clock past it. start = 60_000 + DMA_Z80_GRANT_MCLK least = -(-(start + OWN_CYCLE_CARTRIDGE_MCLK - 1000 - RELEASE_MCLK) // 15) assert least <= wait <= least + 1 assert wait > 3900 def test_the_window_is_the_transfers_own() -> None: board = idle_board() board.dma_bus = (2000, 60_000, 60_034) # Asked for more than the cut-off before the transfer takes the bus: the Z80 goes first. assert board._arbitrate(2000 - CUTOFF_MCLK - 1, True)[0] == 2 assert board._arbitrate(2000 - CUTOFF_MCLK, True)[0] > 3000 # Asked for at or after the last read: the bus is free again. board.m68k_pending_stall = 0 assert board.arbiter_grid(60_000) is board.m68k_accesses def test_the_68000_is_charged_only_the_stretch() -> None: """Its cycle is under way when the Z80's read ends and finishes 7 MCLK after it: from when the transfer gives the bus back it loses at most the Z80's cycle, never the transfer's length over again.""" board = idle_board() board.dma_bus = (900, 60_000, 60_034) board.m68k_step_end = 60_034 _wait, m68k_cycles = board._arbitrate(1000, True) assert DMA_Z80_RESUME_MCLK == -11 assert 0 <= m68k_cycles * 7 <= 42 def test_a_real_transfer_records_its_hold() -> None: system = System(MACHINES["nuked-md"], Cartridge(bytes(0x10000))) assert system.board.dma_bus is None