# Timing: the 15-clock machine cycle, and what a host needs Sources as in [start-here.md](start-here.md): Intel's *MCS-48 Family User's Manual* 9800270D (1978) cited as **UM**, and MAME 0.285's `src/devices/cpu/mcs48/` (BSD-3-Clause) at commit `f379cd06`. Board clocks are from MAME 0.285's own machine list and driver sources, quoted with the file and line. ## The machine cycle One divider chain, described in UM §2.1.11, p. 2-10: ``` XTAL ── ÷3 (State Counter) ──> CLK ── ÷5 (Cycle Counter) ──> ALE ``` - The state counter divides the crystal by 3 to produce CLK, which "defines the state times of the machine". CLK can be brought out on the T0 pin by `ENT0 CLK` and is disabled again by reset. - The cycle counter divides CLK by 5 "to provide a clock which defines a machine cycle consisting of 5 machine states. This clock is called Address Latch Enable (ALE) because of its function in MCS-48 systems with external memory. It is provided continuously on the ALE output pin." So **one machine cycle is 15 crystal periods**, and five machine states S1-S5. At 6 MHz that is 2.5 µs per cycle, a 400 kHz ALE, and the manual's own worked figures (UM p. 2-10 diagram: "2.5 µsec CYCLE", ".5 µsec (2 MHz)" CLK) fall out of it. MAME agrees exactly: `mcs48.h` lines 147-148, ```cpp virtual u64 execute_clocks_to_cycles(u64 clocks) const noexcept override { return (clocks + 15 - 1) / 15; } virtual u64 execute_cycles_to_clocks(u64 cycles) const noexcept override { return (cycles * 15); } ``` with the 8021/8022 overriding both to 30 (`mcs48.h` lines 520-521 and 532-533) -- those two parts have a ÷6 state counter, and they are out of scope here anyway because their instruction set is reduced. **What the core should return.** `step()` returns **machine cycles**, not crystal periods, because that is the unit the whole family is specified in and the unit the timer prescaler counts. A host that needs wall time multiplies by 15 and divides by its crystal. ## One- and two-cycle instructions Every MCS-48 instruction is one or two machine cycles, and the split is almost exactly the one- vs two-byte split, but not quite. Derived from MAME's handlers and cross-checked against Intel's summary (UM §4.1, p. 4-5), which prints bytes and cycles for every instruction: | | one cycle | two cycles | | --- | --- | --- | | one byte | 133 defined opcodes: register and accumulator arithmetic, logic, moves, rotates, and every flag and control instruction (plus the 26 undefined ones, which MAME charges one cycle) | 31 opcodes: `MOVX` (4), `MOVP`, `MOVP3`, `JMPP @A`, `IN A,P1/P2`, `OUTL P1/P2,A`, `INS A,BUS`, `OUTL BUS,A`, the 16 expander instructions, `RET`, `RETR` | | two bytes | none | all 66: every immediate form, every conditional jump, `DJNZ`, `JMP`, `CALL`, and `ANL`/`ORL` to a port or BUS | There is no two-byte one-cycle instruction, and the second cycle of a one-byte two-cycle instruction is always a transfer -- a bus access, a port access, an expander handshake, or a stack pop. Totals across the whole 256-entry map, including the 26 undefined opcodes (MAME charges them one cycle): 159 one-cycle, 97 two-cycle; 190 one-byte, 66 two-byte. `scripts/check_instruction_table.py` re-derives these numbers. The reason a one-byte instruction can cost two cycles is that the second cycle is not a fetch -- it is a bus transaction or a port transfer. UM's instruction timing diagram (p. 2-11) breaks each one down by state: `OUTL P,A` fetches in S1-S2 of cycle 1, increments the PC in S3-S4, increments the timer in S5, and outputs to the port in cycle 2; `MOVX @R,A` puts the RAM address out in cycle 1 S4-S5 and the data in cycle 2. The timer is incremented in **S5 of the first cycle of every instruction**, which is why the prescaler counts machine cycles and not instructions. **The interrupt acknowledge costs two cycles** on top of the `CALL` it performs (MAME `check_irqs`: `burn_cycles(2)` before `execute_call`). The manual gives no figure for this; it says only that the jump happens "as soon as all cycles of the current instruction are complete" (UM §2.1.9, p. 2-7). So the 2 is **emulator-derived** and must be labelled that way in any claim, and MAME's own header says its interrupt timing is suspect (see below). ## ALE, PSEN, RD, WR, PROG: what a host must see A host that models a real board needs to know when each strobe fires, because the board hangs latches off them. From UM §3.6, p. 3-11, verbatim: | Signal | When active | | --- | --- | | RD | during `MOVX A,@R` or `INS A,BUS` | | WR | during `MOVX @R,A` or `OUTL BUS,A` | | ALE | **every machine cycle** | | PSEN | during fetch of external program memory (instruction **or immediate data**) | | PROG | during `MOVD A,P`, `MOVD P,A`, `ANLD P,A`, `ORLD P,A` | "During all other instructions these outputs are driven to the inactive state." Two consequences a host contract must get right: 1. **ALE is free-running.** It is not a bus-cycle signal; it ticks once per machine cycle whether or not anything external is accessed (UM §3.1, p. 3-1: "All program memory fetches from addresses less than 1024 (2048) occur internally with no external signals being generated (except ALE which is always present)"). Boards use it as a clock: the manual itself suggests "ALE divided by 3 or more" as an external counter source (UM p. 2-9). 2. **PSEN covers immediate operands.** The second byte of `MOV A,#data` is fetched with PSEN asserted, exactly like an opcode. A host whose program memory is only enabled on the opcode fetch will break. The external fetch sequence, UM §3.1.1, p. 3-1, verbatim: the 12-bit PC is output on BUS (A7-A0) and the lower half of port 2 (A11-A8); "Address Latch Enable (ALE) will indicate the time at which address is valid. The trailing edge of ALE is used to latch the address externally"; PSEN enables the memory device; "BUS reverts to input (floating) mode and the processor accepts its 8 bit contents as an instruction word." The external *data* sequence, UM §3.2.1, p. 3-4: R0 or R1 is output on BUS, ALE latches it, and RD or WR strobes -- **eight bits of address only**, so external data memory is 256 bytes and a board that wants more banks it with port lines (UM §3.5, p. 3-10). Donkey Kong does exactly that: its sample ROM is selected by P2.6 and banked 256 bytes at a time by P2.2-P2.0 (`src/mame/nintendo/dkong.cpp`, the "8035 Memory Map" comment at line 210). **What this core will and will not model.** The core will model machine cycles and the *order* of external accesses -- fetch, operand fetch, `MOVX` read/write, port read/write, expander transfer -- because that is what a host needs to drive latches and DACs. It will not model state times S1-S5, bus float, or the sub-cycle position of a strobe. Anything that needs those needs a Verilog model, and one exists ([validation.md](validation.md)). ## The clocks the arcade boards actually run All from MAME 0.285. The clock column is the value in the machine configuration; the derived columns follow from ÷15 and the ÷32 timer prescaler. `mame -listdevices dkong` prints `soundcpu Fujitsu MB8884 @ 6.00 MHz`, and the constant behind it is `#define I8035_CLOCK (XTAL(6'000'000))` in `src/mame/nintendo/dkong.h` line 68, used at `src/mame/nintendo/dkong_a.cpp` lines 1341 and 1414 (`MB8884(config, m_soundcpu, I8035_CLOCK);`). | Board | Part | Crystal | Machine cycle | ALE | Timer tick (÷32) | Timer overflow | | --- | --- | --- | --- | --- | --- | --- | | Donkey Kong, DK Jr, Radar Scope (`dkong`) | MB8884 (8035) | 6.000 MHz | 2.500 µs | 400.0 kHz | 80.0 µs | 20.48 ms | | DECO Cassette (`decocass`) | 8041A | 6.000 MHz | 2.500 µs | 400.0 kHz | 80.0 µs | 20.48 ms | | Nintendo 8080 sound boards (`sheriff`, `spacefev`) | 8035 | 6.000 MHz | 2.500 µs | 400.0 kHz | 80.0 µs | 20.48 ms | | Sega Universal Sound Board (`startrek`) | 8035 | 6.000 MHz | 2.500 µs | 400.0 kHz | 80.0 µs | 20.48 ms | | Gyruss, Juno First (`gyruss`, `junofrst`) | 8039 | 8.000 MHz | 1.875 µs | 533.3 kHz | 60.0 µs | 15.36 ms | | Finalizer (`finalizr`) | 8049 | 6.144 MHz | 2.441 µs | 409.6 kHz | 78.1 µs | 20.00 ms | | Mega Zone, Pandora's Palace | 8039 | 7.159 MHz | 2.095 µs | 477.3 kHz | 67.1 µs | 17.16 ms | | Carnival (`carnival`) | 8035 | 3.580 MHz | 4.190 µs | 238.6 kHz | 134.1 µs | 34.33 ms | | Sega Speech Board (`astrob`, `spacfury`) | 8035 | 3.120 MHz | 4.808 µs | 208.0 kHz | 153.8 µs | 39.39 ms | | Tecmo Knight, Raiga (`wildfang`) | 8749 | 4.000 MHz | 3.750 µs | 266.7 kHz | 120.0 µs | 30.72 ms | | Wily Tower (`wilytowr`) | 8039 | 3.000 MHz | 5.000 µs | 200.0 kHz | 160.0 µs | 40.96 ms | | Super Stingray (`sstingry`) | 8748 | 9.264 MHz | 1.619 µs | 617.6 kHz | 51.8 µs | 13.26 ms | Finalizer's 6.144 MHz is the pretty one: the timer overflows every 20.000 ms exactly, so the sound program gets a 50 Hz tick for free. Donkey Kong's 6 MHz is the manual's own worked example (UM p. 2-9 uses a 6 MHz crystal for every timer figure), which makes `dkong` a convenient board to reason about. Note that 6 MHz is the **top** of the 8048's rated range (UM §2.1.11, p. 2-9: "a frequency range of 1 to 6 MHz"). Several of these boards run faster than that: Gyruss's 8039 at 8 MHz, Super Stingray's 8748 at 9.264 MHz. Those are the later -6/-8 speed grades or simply overclocked parts, and MAME models them by scaling the same 15-clock cycle. Nothing in the ISA changes. ## Scheduling the MCU against the main CPU Every board above is a main CPU plus an MCS-48 that runs freely and is poked through a latch. Donkey Kong is the archetype, and its wiring is worth writing down because it is the shape a host must implement (`src/mame/nintendo/dkong_a.cpp` lines 1341-1350 and the memory-map comment in `dkong.cpp` line 210): | MCU pin | Wired to | | --- | --- | | external program memory | the 2 KB sound ROM, plus a compressed sample at 0x800-0xFFF reached by `MOVX` | | P1 (out) | the DAC (`dkong_p1_w` writes straight into the discrete sound netlist) | | P2.7 | external decay | | P2.6 | selects the second ROM for `MOVX` | | P2.2-P2.0 | the 256-byte bank of that ROM | | P2.5 (in) | active low when Mario is jumping | | BUS (in) | the tune number the Z80 last wrote | | T0 (in) | which jump sound | | T1 (in) | active low when the gorilla is falling | | INT | asserted by the Z80 through `dkong_audio_irq_w`, held as a **level** until the Z80 clears it | The main CPU is a Z80 at 3.072 MHz; the MCU's crystal is 6 MHz. The two have no fixed ratio in instructions, only in time. **How to schedule them.** The same way MAME does, and the way the existing cores in this family of repositories do it: 1. Choose a time quantum -- a scanline, a frame, or a fixed number of microseconds. A quantum shorter than the shortest meaningful interaction (here: the time between the Z80 writing the latch and the MCU's next `IN`) costs nothing but time; a quantum longer than it loses events. 2. Convert the quantum to a **cycle budget** per device: `budget = quantum × crystal / 15` for the MCS-48, `quantum × crystal / 1` (T-states) for the Z80. 3. Run each device until it has spent its budget, carrying the overshoot of the last instruction into the next quantum. MAME's `execute_run` is literally `do { check_irqs(); ...execute one opcode... } while (m_icount > 0);` -- it always finishes the instruction it started and goes negative. 4. Interrupt lines are **levels**, set and cleared by the host between quanta or from a device callback, never pushed as events. The MCS-48 samples INT itself. At Donkey Kong's clocks one 60 Hz frame is 51,200 Z80 T-states at 3.072 MHz and 6,667 MCS-48 machine cycles at 400 kHz. The measured figure from the trace in [mame-oracle.md](mame-oracle.md) is **5,238 instructions per frame** for the sound CPU in gameplay (314,303 instructions over 60 frames), which is consistent: the loop is dominated by one- and two-cycle instructions averaging about 1.27 cycles. ## Known divergence: MAME's timer and interrupt timing is wrong MAME's own header (`mcs48.cpp`, TODO block, lines 11-45) records two experiments on **real silicon** by the MAME contributor *bataais*, and both say MAME is off by one: > IRQ and/or timer increment timing is wrong? See test below. After IRQ, > A = 0x20 on MAME, A = 0x22 on the real 8048 as tested by bataais. and, for a sequence of `NOP`s between `STRT T` and `MOV A,T`: > With the following test, on MAME, A = 0xff after 30 NOPs, A = 0 after 31 > NOPs. On the real 8048, A = 0xff after 31 NOPs, A = 0 after 32 NOPs. It can > mean that STRT T has a 1 cycle delay, or simply that MOV A,T gets the timer > value pre-increment. A third note says the IRQ timing is hacked outright: > IRQ timing is hacked due to WY-100 needing to take JNI branch before > servicing interrupt (see m_irq_polled), probably related to note above? These three paragraphs are, as far as this repository has been able to establish, **the only hardware-captured facts about MCS-48 timing in existence** (see [validation.md](validation.md)). They are worth more than their size: they are two acceptance tests a core can be held to, and they say that agreeing with MAME on timer/interrupt timing is a *failure* condition, not a success one. Any lockstep against MAME will diverge here, and the divergence is MAME's. ## What the core will claim about timing - `step()` returns Intel's documented machine cycle count for the instruction (UM §4.1, p. 4-5), or that count plus 2 when an interrupt was accepted. The first part is **documentation**; the +2 is **emulator-derived**. - The timer prescaler counts those cycles, resets on `STRT T`, and ticks the counter every 32. - The relative position of the timer increment inside the instruction (UM's diagram puts it in S5 of the first cycle) will be modelled as "before the instruction's effect" or "after" only once a test distinguishes them -- and the bataais experiments above are precisely that test. Until a core passes them, `step()`'s timer phase is `[unverified]`. - No state times, no bus float, no sub-cycle strobe positions. A host that needs those is building hardware, not an emulator.