Z-80 computer with Dartmouth-style BASIC as the terminal's console

SW15 switches the terminal from the PC's serial line to a Z-80 running at
90 MHz from its own clock, with 64 KB of block RAM preloaded with BASIC.

- rtl/z80_cpu.v: Z-80 built for speed (one clock per memory access, next
  byte read during decode), full documented instruction set plus the
  common undocumented forms; no interrupts.
- rtl/z80_system.v: RAM, console/timer/7-segment ports, toggle handshakes
  to the terminal clock.
- basic/: BASIC interpreter in C for SDCC, start-up code, prebuilt image.
- tools/z80emu.py, tools/cputest.py, scripts/cpusim.sh: reference emulator
  and random tests comparing the CPU after every instruction.
- SW14 feeds the PC's UART into the Z-80 for pasting programs; BTND
  resets the Z-80 only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
brad ArantandClaude Opus 5.5 committed 2026-11-27 20:25:41 -08:00
1 parent 1e4e2101b8
commit 59d5e617f2
20 files changed
+68756 -48

No files matched your search

+2
View File
@@ -4,3 +4,5 @@ build/
*.jou *.jou
*.log *.log
*_out.txt *_out.txt
basic/out/
sim/cpu/
+123 -3
View File
@@ -10,6 +10,9 @@ serial terminal with ANSI colour:
- **Serial line**: the micro-USB **PROG/UART** port (the FTDI chip), 8N1. Bytes - **Serial line**: the micro-USB **PROG/UART** port (the FTDI chip), 8N1. Bytes
received there are drawn on the screen. Keystrokes are sent out there. received there are drawn on the screen. Keystrokes are sent out there.
It also contains a **Z-80 computer running Dartmouth-style BASIC**. Flip SW15 up
and the terminal becomes its console (see [Z-80 BASIC](#z-80-basic)).
Plug the micro-USB into a PC and open the serial port (`/dev/ttyUSB1` is usually Plug the micro-USB into a PC and open the serial port (`/dev/ttyUSB1` is usually
the UART; `ttyUSB0` is JTAG). For example: the UART; `ttyUSB0` is JTAG). For example:
@@ -68,12 +71,15 @@ Set SW6 up so Backspace sends DEL, which the `basys3` entry expects.
| SW7 | Enter sends CR LF instead of CR | | SW7 | Enter sends CR LF instead of CR |
| SW8 | Smooth scrolling (the host can also turn it on with `ESC[?4h`) | | SW8 | Smooth scrolling (the host can also turn it on with `ESC[?4h`) |
| SW9 | Fast smooth scrolling: 15 lines/s instead of 7.5 | | SW9 | Fast smooth scrolling: 15 lines/s instead of 7.5 |
| BTNC | Reset (clears screen, shows banner) | | SW14 | Z-80 mode: text from the PC's serial port also goes to the Z-80 (for pasting programs) |
| SW15 | Z-80 mode: the terminal is the Z-80's console |
| BTNC | Reset (clears screen, shows banner, restarts the Z-80) |
| BTNU | Clear screen | | BTNU | Clear screen |
| BTND | Reset the Z-80 only |
| LED7:0 | Last byte received | | LED7:0 | Last byte received |
| LED11:8 | VT220 keyboard LEDs L4..L1 (`ESC[n q`) | | LED11:8 | VT220 keyboard LEDs L4..L1 (`ESC[n q`) |
| LED12 / 13 / 14 / 15 | Bell / Caps Lock / UART RX activity / keyboard activity | | LED12 / 13 / 14 / 15 | Bell / Caps Lock / UART RX activity / keyboard activity |
| 7-segment | Left: last keyboard scan code. Right: last byte sent. | | 7-segment | Left: last keyboard scan code. Right: last byte sent. In Z-80 mode: whatever BASIC sends to ports 33/32 (`OUT 32,n`). |
## Terminal features ## Terminal features
@@ -130,6 +136,107 @@ Set SW6 up so Backspace sends DEL, which the `basys3` entry expects.
non-UTF-8 locale such as `LANG=C`, or ASCII-only output, for clean line drawing. non-UTF-8 locale such as `LANG=C`, or ASCII-only output, for clean line drawing.
- No 132-column mode, double-width/height lines, soft fonts, or printer port. - No 132-column mode, double-width/height lines, soft fonts, or printer port.
## Z-80 BASIC
Flip **SW15 up**. The Z-80 runs all the time; while the switch is down it simply
waits at its next character of output, so flipping back and forth loses
nothing. The first time, the BASIC banner and `READY` appear.
```
10 FOR I = 1 TO 10
20 PRINT I, SQR(I)
30 NEXT I
RUN
```
Type numbered lines to store a program, or a statement without a number to run
it at once (`PRINT 2^10`). Ctrl-C stops a running program; Backspace and Ctrl-U
edit the line being typed.
- **Commands**: `RUN [line]`, `LIST [a][-b]`, `NEW` (also `SCRATCH`).
- **Statements**:
- Assignment and output: `LET` (optional), `PRINT` (`,` for 15-column zones,
`;` to join, `TAB(n)`), `INPUT ["prompt";] vars`
- Control: `IF expr THEN line|statement`, `GOTO`, `GOSUB`/`RETURN`,
`ON expr GOTO|GOSUB list`, `FOR v = a TO b [STEP s]` / `NEXT [v]`, `END`,
`STOP`
- Data: `DIM`, `DEF FNx(v) = expr`, `READ`/`DATA`/`RESTORE`, `REM`
- Machine access: `RANDOMIZE`, `POKE addr,v`, `OUT port,v`
- Several statements can share a line, separated by `:`.
- **Variables**:
- Numbers: a letter or a letter and digit (`X`, `A1`), single-precision
floating point.
- Arrays: one letter, one or two subscripts from 0, 10 by default.
- Strings: `A$`..`Z$`, up to 79 characters.
- **Operators**: `+ - * / ^`, `= <> < > <= >=`, `AND OR NOT`.
- **Functions**:
- Numeric: `SIN COS TAN ATN EXP LOG ABS SQR INT RND SGN`, `FNx`
- Strings: `LEN VAL ASC`, `CHR$ STR$ LEFT$ RIGHT$ MID$`
- Machine: `PEEK(addr)`, `INP(port)`, `TIM` (seconds since reset)
- Spaces are optional, as at Dartmouth: `FORI=1TO10` works.
- `DATA` takes the rest of its line.
About 22 KB of program space is free. To paste a program from the PC, flip SW14
up too (stop the getty first, or it will talk to BASIC), then paste into
`picocom`. The terminal holds the PC back with XON/XOFF while BASIC catches up.
### The Z-80
`rtl/z80_cpu.v` is a Z-80 written for speed rather than cycle accuracy:
- Every memory access takes one clock from block RAM.
- The CPU reads the next byte while it decodes the current one, so a
register-to-register instruction takes 1 clock, `LD r,n` 2, `LD r,(HL)` 3,
`JP` 4, `CALL` 6, `RET` 5.
- `LDIR` moves a byte every 3 clocks.
- BASIC averages about 2.7 clocks per instruction. At 90 MHz that is about 33
million instructions a second, against roughly 0.6 million for a 4 MHz Z-80.
- It runs at 90 MHz from its own clock (an MMCM), the fastest that meets
timing. The limit is the path from the RAM through opcode decoding into the
registers.
- It has the documented instruction set plus the undocumented IXH/IXL/IYH/IYL
forms, `SLL` and the DDCB register copies, with the undocumented X/Y flags.
- There are no interrupts and HALT stops it until reset.
Memory is 64 KB of block RAM loaded with BASIC at configuration. Writes below
8000h are ignored, so the interpreter can't be damaged. BASIC's data and the
stack fill the top half.
| Port | In | Out |
|---|---|---|
| 00h | bit 0: key waiting, bit 1: console ready | |
| 01h | key | character to the screen |
| 10h–13h | millisecond counter (reading 10h latches the rest) | |
| 20h / 21h | | 7-segment display, right / left byte |
BASIC is C (`basic/basic.c`) compiled with SDCC (`sudo apt install sdcc`):
```bash
basic/build.sh # -> basic/basic.mem, loaded by the bitstream build
```
The same source builds natively for trying the interpreter on a PC
(`gcc basic/basic.c -lm`).
### Testing the CPU
`tools/z80emu.py` is an independent Z-80 emulator in Python.
`scripts/cpusim.sh` runs an image on the Verilog CPU in xsim and on the
emulator, then compares every register after every instruction and the RAM at
the end.
```bash
cd build/cputest && python3 ../../tools/cputest.py 1 1000 && cd ../..
scripts/cpusim.sh build/cputest/cputest.mem
```
- **Random tests**: `tools/cputest.py <seed>` writes 1000 blocks. Each loads
random registers, then runs one random instruction from the whole instruction
set (prefixes, memory forms and block moves included). 50 seeds pass.
- **BASIC**: `scripts/cpusim.sh basic/basic.mem input.txt` boots BASIC and runs
a program typed from `input.txt`. That is 1.1 million instructions, all
identical.
## Build and program ## Build and program
Requires Vivado. The scripts use the newest install in `~/vivado/<version>/Vivado`; Requires Vivado. The scripts use the newest install in `~/vivado/<version>/Vivado`;
@@ -140,6 +247,13 @@ license, so use 2025.2 (`export VIVADO=~/vivado/2025.2/Vivado`).
./scripts/build.sh # bitstream -> build/basys3_terminal.bit (+ .mcs) ./scripts/build.sh # bitstream -> build/basys3_terminal.bit (+ .mcs)
``` ```
The Z-80 clock is `100 MHz × CPU_MULT / CPU_DIV`. The default is 9 / 10, which
gives 90 MHz, the fastest that meets timing. To try another speed:
```bash
CPU_MULT=8.5 CPU_DIV=10 ./scripts/build.sh
```
```bash ```bash
./scripts/build.sh program # build and load into the FPGA (until power-off) ./scripts/build.sh program # build and load into the FPGA (until power-off)
``` ```
@@ -162,6 +276,8 @@ older boards, Macronix `mx25l3273f` on newer ones).
scroll, then checks the screen buffer. scroll, then checks the screen buffer.
- It checks VGA sync timing and saves two frames, `sim/work/frame_1.png` and - It checks VGA sync timing and saves two frames, `sim/work/frame_1.png` and
`sim/work/frame_2.png` (the second is taken mid-scroll). `sim/work/frame_2.png` (the second is taken mid-scroll).
- It switches to Z-80 mode, types `PRINT 2+2` and a short program over the
UART, and checks BASIC's output on the screen.
```bash ```bash
VIVADO=~/vivado/2025.2/Vivado ./scripts/sim.sh VIVADO=~/vivado/2025.2/Vivado ./scripts/sim.sh
@@ -174,7 +290,11 @@ which Vivado needs on newer distros.
| Path | Contents | | Path | Contents |
|---|---| |---|---|
| `rtl/basys3_terminal.v` | Top level: reset, switches, FIFOs, flow control, banner, LEDs | | `rtl/basys3_terminal.v` | Top level: reset, switches, FIFOs, flow control, banner, LEDs, Z-80 clock |
| `rtl/z80_cpu.v` | Z-80 CPU |
| `rtl/z80_system.v` | Z-80 RAM, console and timer ports, clock-domain handshakes |
| `basic/` | BASIC interpreter (C), start-up code, build script, `basic.mem` |
| `tools/z80emu.py`, `tools/cputest.py`, `scripts/cpusim.sh` | CPU test bench: reference emulator, random tests |
| `rtl/term_ctrl.v` | VT220 engine (parser, modes, attributes, copy/fill engine, smooth scroll) | | `rtl/term_ctrl.v` | VT220 engine (parser, modes, attributes, copy/fill engine, smooth scroll) |
| `rtl/text_display.v` | VGA timing, colour palette, character RAM, font lookup | | `rtl/text_display.v` | VGA timing, colour palette, character RAM, font lookup |
| `rtl/ps2_keyboard.v` | PS/2 receiver and scan code set 2 to ASCII / VT220 keys | | `rtl/ps2_keyboard.v` | PS/2 receiver and scan code set 2 to ASCII / VT220 keys |
BIN
View File
Binary file not shown.
+1265
View File
File diff suppressed because it is too large. Load diff
+65536
View File
File diff suppressed because it is too large. Load diff
Executable
+9
View File
@@ -0,0 +1,9 @@
#!/bin/bash
# Compile BASIC for the Z-80 and write basic.mem (64 KB RAM image) and basic.bin.
set -e
cd "$(dirname "$0")"
mkdir -p out
sdasz80 -plosgff out/crt0.rel crt0.s
sdcc -mz80 --opt-code-speed --max-allocs-per-node 20000 --std-sdcc11 -c -o out/basic.rel basic.c
sdcc -mz80 --no-std-crt0 --code-loc 0x0080 --data-loc 0x8000 -o out/basic.ihx out/crt0.rel out/basic.rel
python3 ../tools/ihx2mem.py out/basic.ihx basic.bin basic.mem
+50
View File
@@ -0,0 +1,50 @@
;; Start-up code for BASIC on the Basys 3 Z-80: stack at the top of RAM,
;; copy initialised data, clear BSS, run main.
.module crt0
.globl _main
.globl l__INITIALIZER, s__INITIALIZER, s__INITIALIZED
.globl l__DATA, s__DATA
.area _HEADER (ABS)
.org 0x0000
di
ld sp, #0x0000
call gsinit
call _main
halt
.area _HOME
.area _CODE
.area _INITIALIZER
.area _GSINIT
.area _GSFINAL
.area _DATA
.area _INITIALIZED
.area _BSEG
.area _BSS
.area _HEAP
.area _GSINIT
gsinit:
ld bc, #l__DATA ; clear uninitialised data
ld a, b
or a, c
jr z, 1$
ld hl, #s__DATA
ld (hl), #0
dec bc
ld a, b
or a, c
jr z, 1$
ld de, #s__DATA + 1
ldir
1$: ld bc, #l__INITIALIZER ; copy initialised data
ld a, b
or a, c
jr z, 2$
ld de, #s__INITIALIZED
ld hl, #s__INITIALIZER
ldir
2$:
.area _GSFINAL
ret
+6 -1
View File
@@ -57,6 +57,7 @@ set_property -dict { PACKAGE_PIN W4 IOSTANDARD LVCMOS33 } [get_ports {an[3]}]
## Buttons ## Buttons
set_property -dict { PACKAGE_PIN U18 IOSTANDARD LVCMOS33 } [get_ports btnC] set_property -dict { PACKAGE_PIN U18 IOSTANDARD LVCMOS33 } [get_ports btnC]
set_property -dict { PACKAGE_PIN T18 IOSTANDARD LVCMOS33 } [get_ports btnU] set_property -dict { PACKAGE_PIN T18 IOSTANDARD LVCMOS33 } [get_ports btnU]
set_property -dict { PACKAGE_PIN U17 IOSTANDARD LVCMOS33 } [get_ports btnD]
## VGA ## VGA
set_property -dict { PACKAGE_PIN G19 IOSTANDARD LVCMOS33 } [get_ports {vgaRed[0]}] set_property -dict { PACKAGE_PIN G19 IOSTANDARD LVCMOS33 } [get_ports {vgaRed[0]}]
@@ -83,7 +84,11 @@ set_property -dict { PACKAGE_PIN C17 IOSTANDARD LVCMOS33 PULLUP true } [get_por
set_property -dict { PACKAGE_PIN B17 IOSTANDARD LVCMOS33 PULLUP true } [get_ports PS2Data] set_property -dict { PACKAGE_PIN B17 IOSTANDARD LVCMOS33 PULLUP true } [get_ports PS2Data]
## Asynchronous / human-speed I/O ## Asynchronous / human-speed I/O
set_false_path -from [get_ports {btnC btnU sw[*] RsRx PS2Clk PS2Data}] set_false_path -from [get_ports {btnC btnU btnD sw[*] RsRx PS2Clk PS2Data}]
# The Z-80 clock is only crossed through synchronisers and toggle handshakes.
set_clock_groups -asynchronous -group [get_clocks sys_clk_pin] \
-group [get_clocks -of_objects [get_pins cpu_mmcm/CLKOUT0]]
set_false_path -to [get_ports {led[*] seg[*] dp an[*] RsTx}] set_false_path -to [get_ports {led[*] seg[*] dp an[*] RsTx}]
## Configuration ## Configuration
+134 -36
View File
@@ -1,8 +1,9 @@
`timescale 1ns / 1ps `timescale 1ns / 1ps
// Basys 3 VT220 terminal with ANSI colour. // Basys 3 VT220 terminal with ANSI colour, and a Z-80 computer running BASIC.
// Keyboard (USB HID port) -> UART TX (USB-UART port) // SW15 down: keyboard (USB HID port) -> UART TX (USB-UART port),
// UART RX -> 80x30 colour text on VGA // UART RX -> 80x30 colour text on VGA
// SW15 up: the terminal is the Z-80's console
// //
// SW1:0 baud rate: 00 115200, 01 9600, 10 19200, 11 57600 (8N1) // SW1:0 baud rate: 00 115200, 01 9600, 10 19200, 11 57600 (8N1)
// SW2 local echo // SW2 local echo
@@ -12,21 +13,29 @@
// SW7 Enter sends CR LF instead of CR // SW7 Enter sends CR LF instead of CR
// SW8 smooth scrolling (also turned on by ESC [ ? 4 h) // SW8 smooth scrolling (also turned on by ESC [ ? 4 h)
// SW9 fast smooth scrolling // SW9 fast smooth scrolling
// BTNC reset BTNU clear screen // SW14 in Z-80 mode, bytes from the PC's UART also go to the Z-80 (paste programs)
// SW15 Z-80 mode
// BTNC reset BTNU clear screen BTND reset the Z-80 only
// LED7:0 last byte received LED11:8 VT220 LEDs L4..L1 (DECLL) // LED7:0 last byte received LED11:8 VT220 LEDs L4..L1 (DECLL)
// LED12 bell LED13 Caps Lock LED14 UART RX activity LED15 keyboard activity // LED12 bell LED13 Caps Lock LED14 UART RX activity LED15 keyboard activity
// 7-seg last scan code (left), last byte sent (right) // 7-seg last scan code (left), last byte sent (right); in Z-80 mode, ports 21h/20h
// //
// The terminal sends XOFF when its input buffer passes 256 bytes and XON when // The terminal sends XOFF when its input buffer passes 256 bytes and XON when
// it drains below 32, so smooth scrolling can hold the host back. // it drains below 32, so smooth scrolling can hold the host back. In Z-80 mode
// it does the same for the Z-80's input buffer, for text pasted over the UART.
module basys3_terminal #( module basys3_terminal #(
parameter FONT_FILE = "font.mem", parameter FONT_FILE = "font.mem",
parameter CLK_HZ = 100_000_000 parameter MEM_FILE = "basic.mem",
parameter CLK_HZ = 100_000_000,
parameter real CPU_MULT = 9.0, // Z-80 clock = 100 MHz * CPU_MULT / CPU_DIV
parameter real CPU_DIV = 10.0,
parameter CPU_HZ = 90_000_000
) ( ) (
input clk, input clk,
input btnC, input btnC,
input btnU, input btnU,
input btnD,
input [15:0] sw, input [15:0] sw,
output [15:0] led, output [15:0] led,
output [6:0] seg, output [6:0] seg,
@@ -55,12 +64,15 @@ module basys3_terminal #(
rst <= !por[15]; rst <= !por[15];
end end
reg [9:0] sw_r; reg [15:0] sw_r;
reg [1:0] clr_sync; reg [1:0] clr_sync, zrst_sync;
always @(posedge clk) begin always @(posedge clk) begin
sw_r <= sw[9:0]; sw_r <= sw;
clr_sync <= {clr_sync[0], btnU}; clr_sync <= {clr_sync[0], btnU};
zrst_sync <= {zrst_sync[0], btnD};
end end
wire z80_mode = sw_r[15];
wire z80_link = sw_r[14];
reg [13:0] baud_div; reg [13:0] baud_div;
always @(posedge clk) always @(posedge clk)
@@ -100,10 +112,11 @@ module basys3_terminal #(
.ascii(key), .ascii_valid(key_valid), .caps(caps) .ascii(key), .ascii_valid(key_valid), .caps(caps)
); );
// ------------------------------------------------------------- transmit // ----------------------------------------------------------- host input
// Sources: flow control (first), then keyboard and terminal replies. The // Keyboard bytes and terminal replies go to the host: the PC's UART, or in
// keyboard/reply choice sticks until that queue is empty, so multi-byte // Z-80 mode the Z-80's input FIFO. The keyboard/reply choice sticks until
// sequences are never interleaved. // that queue is empty, so multi-byte sequences are never interleaved.
// Flow control bytes for the PC go first.
wire [7:0] kq, rq; wire [7:0] kq, rq;
wire kq_empty, rq_empty, rq_full; wire kq_empty, rq_empty, rq_full;
wire [7:0] resp_byte; wire [7:0] resp_byte;
@@ -124,7 +137,27 @@ module basys3_terminal #(
.rd(rq_rd), .dout(rq), .empty(rq_empty), .full(rq_full), .count() .rd(rq_rd), .dout(rq), .empty(rq_empty), .full(rq_full), .count()
); );
wire [7:0] h_byte = from_resp ? rq : kq;
wire h_avail = from_resp ? !rq_empty : !kq_empty;
wire pop_pend = kq_rd | rq_rd; // last byte taken pops this clock
// Z-80 input FIFO: keyboard/replies, and the PC's UART when linked
wire [7:0] rx_byte;
wire rx_valid;
wire [7:0] zin;
wire zin_empty, zin_full;
wire [10:0] zin_count;
reg zin_rd;
wire rx_to_z = z80_mode && z80_link && rx_valid;
wire take_z = z80_mode && h_avail && !zin_full && !rx_to_z && !pop_pend;
fifo #(.W(8), .A(10)) z80_in_fifo (
.clk(clk), .rst(rst), .din(rx_to_z ? rx_byte : h_byte), .wr(rx_to_z || take_z),
.rd(zin_rd), .dout(zin), .empty(zin_empty), .full(zin_full), .count(zin_count)
);
wire [10:0] tq_count; wire [10:0] tq_count;
wire [10:0] flow_count = z80_mode ? zin_count : tq_count;
reg xoff_sent; reg xoff_sent;
always @(posedge clk) begin always @(posedge clk) begin
@@ -136,27 +169,29 @@ module basys3_terminal #(
flow_pend <= 1'b0; flow_pend <= 1'b0;
xoff_sent <= 1'b0; xoff_sent <= 1'b0;
end else begin end else begin
if (!flow_pend && !xoff_sent && tq_count >= 256) begin if (!flow_pend && !xoff_sent && flow_count >= 256) begin
flow_pend <= 1'b1; flow_byte <= XOFF; xoff_sent <= 1'b1; flow_pend <= 1'b1; flow_byte <= XOFF; xoff_sent <= 1'b1;
end else if (!flow_pend && xoff_sent && tq_count < 32) begin end else if (!flow_pend && xoff_sent && flow_count < 32) begin
flow_pend <= 1'b1; flow_byte <= XON; xoff_sent <= 1'b0; flow_pend <= 1'b1; flow_byte <= XON; xoff_sent <= 1'b0;
end end
if (take_z) begin
kq_rd <= !from_resp;
rq_rd <= from_resp;
end else if (!h_avail)
from_resp <= !from_resp;
if (!tx_busy && !tx_start) begin if (!tx_busy && !tx_start) begin
if (flow_pend) begin if (flow_pend) begin
tx_byte <= flow_byte; tx_byte <= flow_byte;
tx_start <= 1'b1; tx_start <= 1'b1;
flow_pend <= 1'b0; flow_pend <= 1'b0;
end else if (!from_resp && !kq_empty) begin end else if (!z80_mode && h_avail && !pop_pend) begin
tx_byte <= kq; tx_byte <= h_byte;
tx_start <= 1'b1; tx_start <= 1'b1;
kq_rd <= 1'b1; kq_rd <= !from_resp;
end else if (from_resp && !rq_empty) begin rq_rd <= from_resp;
tx_byte <= rq; end
tx_start <= 1'b1;
rq_rd <= 1'b1;
end else
from_resp <= !from_resp;
end end
end end
end end
@@ -167,9 +202,6 @@ module basys3_terminal #(
); );
// -------------------------------------------------------------- receive // -------------------------------------------------------------- receive
wire [7:0] rx_byte;
wire rx_valid;
uart_rx urx ( uart_rx urx (
.clk(clk), .rst(rst), .div(baud_div), .rx(RsRx), .clk(clk), .rst(rst), .div(baud_div), .rx(RsRx),
.data(rx_byte), .valid(rx_valid) .data(rx_byte), .valid(rx_valid)
@@ -182,10 +214,69 @@ module basys3_terminal #(
"\033[31mc\033[33mo\033[32ml\033[36mo\033[34mu\033[35mr\033[0m ", "\033[31mc\033[33mo\033[32ml\033[36mo\033[34mu\033[35mr\033[0m ",
"\033[4munderline\033[0m\015\012", "\033[4munderline\033[0m\015\012",
"UART RX -> screen, keyboard -> UART TX TERM=basys3 or vt220\015\012\012"}; "UART RX -> screen, keyboard -> UART TX TERM=basys3 or vt220\015\012\012"};
// (not shown in Z-80 mode, where BASIC prints its own)
reg [7:0] ban_i; reg [7:0] ban_i;
wire [7:0] ban_c = BANNER[ban_i*8 +: 8]; wire [7:0] ban_c = BANNER[ban_i*8 +: 8];
// terminal input: received bytes, local echo, banner (in that priority) // ---------------------------------------------------------------- Z-80
wire cpu_clk, locked;
`ifdef SIMULATION
assign cpu_clk = clk;
assign locked = 1'b1;
`else
wire cpu_fb, cpu_clk_mmcm;
MMCME2_BASE #(
.CLKIN1_PERIOD(10.0), .DIVCLK_DIVIDE(1),
.CLKFBOUT_MULT_F(CPU_MULT), .CLKOUT0_DIVIDE_F(CPU_DIV)
) cpu_mmcm (
.CLKIN1(clk), .CLKFBIN(cpu_fb), .CLKFBOUT(cpu_fb), .CLKFBOUTB(),
.CLKOUT0(cpu_clk_mmcm), .CLKOUT0B(), .CLKOUT1(), .CLKOUT1B(), .CLKOUT2(),
.CLKOUT2B(), .CLKOUT3(), .CLKOUT3B(), .CLKOUT4(), .CLKOUT5(), .CLKOUT6(),
.LOCKED(locked), .PWRDWN(1'b0), .RST(1'b0)
);
BUFG cpu_bufg (.I(cpu_clk_mmcm), .O(cpu_clk));
`endif
(* ASYNC_REG = "TRUE" *) reg [2:0] cpu_rst_s;
always @(posedge cpu_clk) cpu_rst_s <= {cpu_rst_s[1:0], rst | zrst_sync[1] | !locked};
// Z-80 input: one byte at a time from z80_in_fifo
reg zrx_req, zrx_pend;
reg [7:0] zrx_data;
wire zrx_ack;
(* ASYNC_REG = "TRUE" *) reg [1:0] zrx_ack_s;
always @(posedge clk) begin
zin_rd <= 1'b0;
zrx_ack_s <= {zrx_ack_s[0], zrx_ack};
if (rst)
zrx_pend <= 1'b0;
else if (!zrx_pend && !zin_empty && !zin_rd) begin
zrx_data <= zin;
zin_rd <= 1'b1;
zrx_req <= ~zrx_req;
zrx_pend <= 1'b1;
end else if (zrx_pend && zrx_ack_s[1] == zrx_req)
zrx_pend <= 1'b0;
end
initial zrx_req = 1'b0;
// Z-80 output
wire ztx_req;
wire [7:0] ztx_data;
reg ztx_ack = 1'b0;
(* ASYNC_REG = "TRUE" *) reg [1:0] ztx_req_s;
always @(posedge clk) ztx_req_s <= {ztx_req_s[0], ztx_req};
wire [15:0] z80_seg;
z80_system #(.MEM_FILE(MEM_FILE), .CPU_HZ(CPU_HZ)) z80 (
.clk(cpu_clk), .rst(cpu_rst_s[2]),
.rx_req(zrx_req), .rx_data(zrx_data), .rx_ack(zrx_ack),
.tx_req(ztx_req), .tx_data(ztx_data), .tx_ack(ztx_ack),
.seg_val(z80_seg), .halted()
);
// terminal input: Z-80 output or received bytes, local echo, banner
reg echo_pend; reg echo_pend;
reg [7:0] echo_byte; reg [7:0] echo_byte;
reg [7:0] tin; reg [7:0] tin;
@@ -194,20 +285,26 @@ module basys3_terminal #(
always @(posedge clk) begin always @(posedge clk) begin
tin_wr <= 1'b0; tin_wr <= 1'b0;
if (kq_rd && sw_r[2]) begin if (kq_rd && sw_r[2] && !z80_mode) begin
echo_pend <= 1'b1; echo_pend <= 1'b1;
echo_byte <= kq; echo_byte <= kq;
end end
if (rst) begin if (rst) begin
echo_pend <= 1'b0; echo_pend <= 1'b0;
ban_i <= 8'd199; ban_i <= z80_mode ? 8'hFF : 8'd199;
end else if (z80_mode) begin
if (ztx_req_s[1] != ztx_ack && !tin_wr && tq_count < 1000) begin
tin <= ztx_data;
tin_wr <= 1'b1;
ztx_ack <= ~ztx_ack;
end
end else if (rx_valid) begin end else if (rx_valid) begin
tin <= rx_byte; tin <= rx_byte;
tin_wr <= 1'b1; tin_wr <= 1'b1;
end else if (echo_pend && !tin_full) begin end else if (echo_pend && !tin_full) begin
tin <= echo_byte; tin <= echo_byte;
tin_wr <= 1'b1; tin_wr <= 1'b1;
echo_pend <= kq_rd && sw_r[2]; echo_pend <= kq_rd && sw_r[2] && !z80_mode;
end else if (ban_i != 8'hFF && !tin_full && !tin_wr) begin end else if (ban_i != 8'hFF && !tin_full && !tin_wr) begin
ban_i <= ban_i - 1'b1; ban_i <= ban_i - 1'b1;
if (ban_c != 0) begin if (ban_c != 0) begin
@@ -273,10 +370,10 @@ module basys3_terminal #(
reg [22:0] rx_led, kb_led, bell_led; // ~84 ms pulse stretchers reg [22:0] rx_led, kb_led, bell_led; // ~84 ms pulse stretchers
always @(posedge clk) begin always @(posedge clk) begin
if (rx_valid) last_rx <= rx_byte; if (z80_mode ? tin_wr : rx_valid) last_rx <= z80_mode ? tin : rx_byte;
if (scan_valid) last_scan <= scan; if (scan_valid) last_scan <= scan;
if (tx_start) last_tx <= tx_byte; if (tx_start) last_tx <= tx_byte;
rx_led <= rx_valid ? 23'h7FFFFF : rx_led - (rx_led != 0); rx_led <= (z80_mode ? tin_wr : rx_valid) ? 23'h7FFFFF : rx_led - (rx_led != 0);
kb_led <= scan_valid ? 23'h7FFFFF : kb_led - (kb_led != 0); kb_led <= scan_valid ? 23'h7FFFFF : kb_led - (kb_led != 0);
bell_led <= bell ? 23'h7FFFFF : bell_led - (bell_led != 0); bell_led <= bell ? 23'h7FFFFF : bell_led - (bell_led != 0);
end end
@@ -284,5 +381,6 @@ module basys3_terminal #(
assign led = {kb_led != 0, rx_led != 0, caps, bell_led != 0, dec_leds[3:0], last_rx}; assign led = {kb_led != 0, rx_led != 0, caps, bell_led != 0, dec_leds[3:0], last_rx};
assign dp = 1'b1; assign dp = 1'b1;
sevenseg digits (.clk(clk), .value({last_scan, last_tx}), .seg(seg), .an(an)); sevenseg digits (.clk(clk), .value(z80_mode ? z80_seg : {last_scan, last_tx}),
.seg(seg), .an(an));
endmodule endmodule
+723
View File
@@ -0,0 +1,723 @@
`timescale 1ns / 1ps
// Z-80 compatible CPU built for speed on block RAM, not for cycle accuracy.
//
// Every memory access takes one clock. The memory is synchronous: the byte at
// `ma` appears on `din` one clock later. While an opcode is being decoded the
// CPU is already reading the byte after it, so register-to-register
// instructions take 1 clock, LD r,n 2, LD r,(HL) 3, JP 4, CALL 6, RET 5.
// For instructions that do not use that byte as an operand it is kept (`nxt`)
// and decoded straight after, without reading it again.
//
// The full documented instruction set is implemented, plus the undocumented
// IXH/IXL/IYH/IYL forms, SLL and the DDCB register copies. Block instructions
// loop internally (LDIR moves a byte every 3 clocks). There are no interrupts:
// EI/DI/IM only set their registers, and HALT stops the CPU until reset.
module z80_cpu (
input clk,
input rst,
// memory: synchronous RAM, read data for ma arrives on din a clock later
output reg [15:0] ma,
output reg we,
output reg [7:0] wd,
input [7:0] din,
// I/O: io_din is sampled the clock after io_rd
output reg [15:0] io_addr,
output reg io_rd,
output reg io_wr,
output reg [7:0] io_wd,
input [7:0] io_din,
output halted,
// debug: ins_start is high on the first clock of each instruction
output ins_start,
output [15:0] dbg_pc,
output [15:0] dbg_af, dbg_bc, dbg_de, dbg_hl, dbg_ix, dbg_iy, dbg_sp
);
localparam [4:0] S_F = 0, S_D = 1, S_CB = 2, S_ED = 3, S_JR = 4,
S_IML = 5, S_IMH = 6, S_IMM = 7, S_IX = 8, S_IXN = 9,
S_RD = 10, S_RDD = 11, S_W = 12, S_W1 = 13, S_W2 = 14,
S_P1 = 15, S_P2 = 16, S_P3 = 17, S_IXCB1 = 18, S_IXCB2 = 19,
S_IOR = 20, S_BLK = 21, S_HALT = 22, S_ST2 = 23, S_LD1 = 24,
S_LD2 = 25, S_LD3 = 26, S_EX2 = 27, S_INIW = 28;
// instruction classes for the shared states
localparam [4:0] I_LDRM = 0, I_ALUM = 1, I_INCM = 2, I_DECM = 3, I_LDMR = 4,
I_LDMN = 5, I_CBM = 6, I_LDRP = 7, I_JP = 8, I_CALL = 9,
I_STNN = 10, I_STNNA = 11, I_LDNN = 12, I_LDNNA = 13, I_ALUN = 14,
I_LDRN = 15, I_OUTN = 16, I_INN = 17, I_RET = 18, I_POP = 19,
I_EXSP = 20, I_RRD = 21, I_RLD = 22, I_LDI = 23, I_CPI = 24,
I_INI = 25, I_OUTI = 26, I_INC = 27, I_PUSH = 28;
localparam SF = 7, ZF = 6, HF = 4, PF = 2, NF = 1, CF = 0;
reg [7:0] rA, rF, rB, rC, rD, rE, rH, rL;
reg [7:0] aA, aF, aB, aC, aD, aE, aH, aL;
reg [15:0] IX, IY, SP, PC;
reg [7:0] rI, rR;
reg iff1, iff2;
reg [1:0] im;
reg [4:0] st, ic;
reg [1:0] xm, xi; // index prefix: 0 HL, 1 IX, 2 IY
reg [7:0] ir;
reg [2:0] dst;
reg [7:0] nxt; // byte after the opcode, read during decode
reg un; // decode nxt instead of din
reg pd; // last clock was a decode: capture nxt
reg rsm; // instruction did not consume nxt
reg nbad; // instruction wrote over nxt
reg [15:0] nxa; // address of nxt
reg take;
reg [15:0] ea, tmp;
reg [7:0] tlo;
wire [15:0] BC = {rB, rC}, DE = {rD, rE}, HL = {rH, rL};
assign halted = st == S_HALT;
assign ins_start = st == S_D && xm == 2'd0;
assign dbg_pc = PC - 1'b1;
assign dbg_af = {rA, rF}; assign dbg_bc = BC; assign dbg_de = DE;
assign dbg_hl = HL; assign dbg_ix = IX; assign dbg_iy = IY; assign dbg_sp = SP;
// ------------------------------------------------------------ register file
function [15:0] xr(input [1:0] x);
xr = x == 2'd1 ? IX : x == 2'd2 ? IY : HL;
endfunction
function [7:0] get8(input [2:0] i, input [1:0] x);
case (i)
3'd0: get8 = rB;
3'd1: get8 = rC;
3'd2: get8 = rD;
3'd3: get8 = rE;
3'd4: get8 = x == 2'd1 ? IX[15:8] : x == 2'd2 ? IY[15:8] : rH;
3'd5: get8 = x == 2'd1 ? IX[7:0] : x == 2'd2 ? IY[7:0] : rL;
3'd6: get8 = 8'h00;
3'd7: get8 = rA;
endcase
endfunction
task put8(input [2:0] i, input [1:0] x, input [7:0] v);
case (i)
3'd0: rB <= v;
3'd1: rC <= v;
3'd2: rD <= v;
3'd3: rE <= v;
3'd4: if (x == 2'd1) IX[15:8] <= v; else if (x == 2'd2) IY[15:8] <= v; else rH <= v;
3'd5: if (x == 2'd1) IX[7:0] <= v; else if (x == 2'd2) IY[7:0] <= v; else rL <= v;
3'd6: ;
3'd7: rA <= v;
endcase
endtask
function [15:0] getrp(input [1:0] p, input [1:0] x);
case (p)
2'd0: getrp = BC;
2'd1: getrp = DE;
2'd2: getrp = xr(x);
2'd3: getrp = SP;
endcase
endfunction
task putrp(input [1:0] p, input [1:0] x, input [15:0] v);
case (p)
2'd0: {rB, rC} <= v;
2'd1: {rD, rE} <= v;
2'd2: if (x == 2'd1) IX <= v; else if (x == 2'd2) IY <= v; else {rH, rL} <= v;
2'd3: SP <= v;
endcase
endtask
function [15:0] getrp2(input [1:0] p, input [1:0] x);
getrp2 = p == 2'd3 ? {rA, rF} : getrp(p, x);
endfunction
task putrp2(input [1:0] p, input [1:0] x, input [15:0] v);
if (p == 2'd3) {rA, rF} <= v; else putrp(p, x, v);
endtask
// -------------------------------------------------------------------- ALU
// Each returns {flags, result}. Flags: S Z Y H X P/V N C.
function [15:0] alu(input [2:0] op, input [7:0] a, input [7:0] b, input [7:0] f);
reg [8:0] s;
reg [7:0] r;
reg h, v, n, c;
begin
case (op)
3'd0, 3'd1: begin
s = {1'b0, a} + {1'b0, b} + (op[0] & f[CF]);
r = s[7:0]; c = s[8]; n = 1'b0;
h = a[4] ^ b[4] ^ r[4];
v = a[7] == b[7] && r[7] != a[7];
end
3'd2, 3'd3, 3'd7: begin
s = {1'b0, a} - {1'b0, b} - (op == 3'd3 & f[CF]);
r = s[7:0]; c = s[8]; n = 1'b1;
h = a[4] ^ b[4] ^ r[4];
v = a[7] != b[7] && r[7] != a[7];
end
3'd4: begin r = a & b; c = 1'b0; n = 1'b0; h = 1'b1; v = ~^r; end
3'd5: begin r = a ^ b; c = 1'b0; n = 1'b0; h = 1'b0; v = ~^r; end
default: begin r = a | b; c = 1'b0; n = 1'b0; h = 1'b0; v = ~^r; end
endcase
if (op == 3'd7) // CP takes the undocumented bits from the operand
alu = {r[7], r == 8'd0, b[5], h, b[3], v, n, c, r};
else
alu = {r[7], r == 8'd0, r[5], h, r[3], v, n, c, r};
end
endfunction
function [15:0] incdec(input dec, input [7:0] a, input [7:0] f);
reg [7:0] r;
begin
r = dec ? a - 1'b1 : a + 1'b1;
incdec = {r[7], r == 8'd0, r[5], dec ? a[3:0] == 4'h0 : a[3:0] == 4'hF, r[3],
dec ? a == 8'h80 : a == 8'h7F, dec, f[CF], r};
end
endfunction
function [15:0] cbop(input [7:0] op, input [7:0] a, input [7:0] f);
reg [7:0] r;
reg c, z;
begin
case (op[7:6])
2'd0: begin
case (op[5:3])
3'd0: begin r = {a[6:0], a[7]}; c = a[7]; end // RLC
3'd1: begin r = {a[0], a[7:1]}; c = a[0]; end // RRC
3'd2: begin r = {a[6:0], f[CF]}; c = a[7]; end // RL
3'd3: begin r = {f[CF], a[7:1]}; c = a[0]; end // RR
3'd4: begin r = {a[6:0], 1'b0}; c = a[7]; end // SLA
3'd5: begin r = {a[7], a[7:1]}; c = a[0]; end // SRA
3'd6: begin r = {a[6:0], 1'b1}; c = a[7]; end // SLL
3'd7: begin r = {1'b0, a[7:1]}; c = a[0]; end // SRL
endcase
cbop = {r[7], r == 8'd0, r[5], 1'b0, r[3], ~^r, 1'b0, c, r};
end
2'd1: begin // BIT
z = ~a[op[5:3]];
cbop = {op[5:3] == 3'd7 && a[7], z, a[5], 1'b1, a[3], z, 1'b0, f[CF], a};
end
2'd2: begin r = a & ~(8'd1 << op[5:3]); cbop = {f, r}; end // RES
2'd3: begin r = a | (8'd1 << op[5:3]); cbop = {f, r}; end // SET
endcase
end
endfunction
// RLCA RRCA RLA RRA DAA CPL SCF CCF
function [15:0] accop(input [2:0] y, input [7:0] a, input [7:0] f);
reg [7:0] r, corr;
reg c, h;
begin
case (y)
3'd0: accop = {f[7:6], a[4], 1'b0, a[2], f[PF], 1'b0, a[7], a[6:0], a[7]};
3'd1: accop = {f[7:6], a[6], 1'b0, a[4], f[PF], 1'b0, a[0], a[0], a[7:1]};
3'd2: accop = {f[7:6], a[4], 1'b0, a[2], f[PF], 1'b0, a[7], a[6:0], f[CF]};
3'd3: accop = {f[7:6], a[6], 1'b0, a[4], f[PF], 1'b0, a[0], f[CF], a[7:1]};
3'd4: begin
corr = 8'h00;
c = f[CF];
if (f[HF] || a[3:0] > 4'd9) corr[3:0] = 4'h6;
if (f[CF] || a > 8'h99) begin corr[7:4] = 4'h6; c = 1'b1; end
if (f[NF]) begin r = a - corr; h = f[HF] && a[3:0] < 4'd6; end
else begin r = a + corr; h = a[3:0] > 4'd9; end
accop = {r[7], r == 8'd0, r[5], h, r[3], ~^r, f[NF], c, r};
end
3'd5: begin
r = ~a;
accop = {f[7:6], r[5], 1'b1, r[3], f[PF], 1'b1, f[CF], r};
end
3'd6: accop = {f[7:6], a[5], 1'b0, a[3], f[PF], 1'b0, 1'b1, a};
3'd7: accop = {f[7:6], a[5], f[CF], a[3], f[PF], 1'b0, ~f[CF], a};
endcase
end
endfunction
function [23:0] add16(input [15:0] a, input [15:0] b, input [7:0] f);
reg [16:0] s;
begin
s = {1'b0, a} + {1'b0, b};
add16 = {f[7:6], s[13], a[12] ^ b[12] ^ s[12], s[11], f[PF], 1'b0, s[16], s[15:0]};
end
endfunction
function [23:0] adc16(input sub, input [15:0] a, input [15:0] b, input [7:0] f);
reg [16:0] s;
reg v;
begin
if (sub) begin
s = {1'b0, a} - {1'b0, b} - f[CF];
v = a[15] != b[15] && s[15] != a[15];
end else begin
s = {1'b0, a} + {1'b0, b} + f[CF];
v = a[15] == b[15] && s[15] != a[15];
end
adc16 = {s[15], s[15:0] == 16'd0, s[13], a[12] ^ b[12] ^ s[12], s[11], v, sub, s[16],
s[15:0]};
end
endfunction
function cond(input [2:0] cc, input [7:0] f);
case (cc)
3'd0: cond = !f[ZF];
3'd1: cond = f[ZF];
3'd2: cond = !f[CF];
3'd3: cond = f[CF];
3'd4: cond = !f[PF];
3'd5: cond = f[PF];
3'd6: cond = !f[SF];
3'd7: cond = f[SF];
endcase
endfunction
// ------------------------------------------------------- sequencing helpers
wire dec_st = st == S_D || st == S_CB || st == S_ED;
wire [15:0] nxa_now = dec_st ? PC : nxa;
task wr(input [15:0] a, input [7:0] d);
begin
ma <= a; we <= 1'b1; wd <= d;
if (a == nxa_now) nbad <= 1'b1;
end
endtask
// next instruction when ma == PC (the next opcode is being read now)
task next_stream;
begin ma <= PC + 1'b1; PC <= PC + 1'b1; un <= 1'b0; st <= S_D; end
endtask
// next instruction from any state
task finish;
if (!rsm) begin ma <= PC; st <= S_F; end
else if (nbad) begin ma <= nxa; PC <= nxa; st <= S_F; end
else begin ma <= PC; un <= 1'b1; st <= S_D; end
endtask
// finish from S_RDD, where S_RD left ma == PC for non-resuming instructions
task finish_rd;
if (rsm) finish; else next_stream;
endtask
task jump(input [15:0] t);
begin PC <= t; ma <= t; st <= S_F; end
endtask
// ----------------------------------------------------------------- engine
reg [7:0] op, v8;
reg [1:0] x;
reg [2:0] y, z;
reg [1:0] p;
reg q;
reg [15:0] v16, r16;
reg [23:0] w24;
always @(posedge clk) begin
we <= 1'b0;
io_rd <= 1'b0;
io_wr <= 1'b0;
pd <= 1'b0;
if (pd) nxt <= din;
if (rst) begin
st <= S_F; ma <= 16'h0000; PC <= 16'h0000;
SP <= 16'hFFFF; rA <= 8'hFF; rF <= 8'hFF;
{rB, rC, rD, rE, rH, rL} <= 48'd0;
{aA, aF, aB, aC, aD, aE, aH, aL} <= 64'd0;
IX <= 16'hFFFF; IY <= 16'hFFFF;
rI <= 8'h00; rR <= 8'h00; iff1 <= 1'b0; iff2 <= 1'b0; im <= 2'd0;
xm <= 2'd0; un <= 1'b0; rsm <= 1'b0; nbad <= 1'b0;
end else case (st)
S_F: next_stream;
// ------------------------------------------------------ main opcodes
S_D: begin
op = un ? nxt : din;
x = op[7:6]; y = op[5:3]; z = op[2:0]; p = op[5:4]; q = op[3];
rR <= {rR[7], rR[6:0] + 7'd1};
pd <= 1'b1;
nxa <= PC;
nbad <= 1'b0;
rsm <= 1'b1;
xi <= xm;
xm <= 2'd0;
ir <= op;
next_stream; // default: 1-byte instruction
case (x)
2'd0: case (z)
3'd0: case (y)
3'd0: ; // NOP
3'd1: begin rA <= aA; rF <= aF; aA <= rA; aF <= rF; end
3'd2: begin // DJNZ
rB <= rB - 1'b1; take <= rB != 8'd1; rsm <= 1'b0; st <= S_JR;
end
3'd3: begin take <= 1'b1; rsm <= 1'b0; st <= S_JR; end
default: begin take <= cond({1'b0, y[1:0]}, rF); rsm <= 1'b0; st <= S_JR; end
endcase
3'd1: if (!q) begin ic <= I_LDRP; rsm <= 1'b0; st <= S_IML; end
else begin
w24 = add16(xr(xm), getrp(p, xm), rF);
putrp(2'd2, xm, w24[15:0]); rF <= w24[23:16];
end
3'd2: case ({p, q})
3'b000: begin wr(BC, rA); st <= S_W; end
3'b010: begin wr(DE, rA); st <= S_W; end
3'b100: begin tmp <= xr(xm); ic <= I_STNN; rsm <= 1'b0; st <= S_IML; end
3'b110: begin ic <= I_STNNA; rsm <= 1'b0; st <= S_IML; end
3'b001: begin ma <= BC; dst <= 3'd7; ic <= I_LDRM; st <= S_RD; end
3'b011: begin ma <= DE; dst <= 3'd7; ic <= I_LDRM; st <= S_RD; end
3'b101: begin ic <= I_LDNN; rsm <= 1'b0; st <= S_IML; end
3'b111: begin ic <= I_LDNNA; rsm <= 1'b0; st <= S_IML; end
endcase
3'd3: putrp(p, xm, q ? getrp(p, xm) - 1'b1 : getrp(p, xm) + 1'b1);
3'd4, 3'd5:
if (y == 3'd6) begin
ic <= z[0] ? I_DECM : I_INCM;
if (xm == 2'd0) begin ma <= HL; ea <= HL; st <= S_RD; end
else begin rsm <= 1'b0; st <= S_IX; end
end else begin
v16 = incdec(z[0], get8(y, xm), rF);
put8(y, xm, v16[7:0]); rF <= v16[15:8];
end
3'd6: begin
rsm <= 1'b0;
if (y == 3'd6) begin
ic <= I_LDMN;
st <= xm == 2'd0 ? S_IMM : S_IX;
end else begin
ic <= I_LDRN; dst <= y; st <= S_IMM;
end
end
3'd7: begin v16 = accop(y, rA, rF); rA <= v16[7:0]; rF <= v16[15:8]; end
endcase
2'd1:
if (op == 8'h76) st <= S_HALT;
else if (z == 3'd6) begin // LD r,(m)
dst <= y; ic <= I_LDRM;
if (xm == 2'd0) begin ma <= HL; st <= S_RD; end
else begin rsm <= 1'b0; st <= S_IX; end
end else if (y == 3'd6) begin // LD (m),r
if (xm == 2'd0) begin wr(HL, get8(z, 2'd0)); st <= S_W; end
else begin tmp[7:0] <= get8(z, 2'd0); ic <= I_LDMR; rsm <= 1'b0; st <= S_IX; end
end else
put8(y, xm, get8(z, xm));
2'd2:
if (z == 3'd6) begin
ic <= I_ALUM;
if (xm == 2'd0) begin ma <= HL; st <= S_RD; end
else begin rsm <= 1'b0; st <= S_IX; end
end else begin
v16 = alu(y, rA, get8(z, xm), rF);
if (y != 3'd7) rA <= v16[7:0];
rF <= v16[15:8];
end
2'd3: case (z)
3'd0: if (cond(y, rF)) begin ic <= I_RET; ma <= SP; st <= S_P1; end
3'd1:
if (!q) begin ic <= I_POP; ma <= SP; st <= S_P1; end
else case (p)
2'd0: begin ic <= I_RET; ma <= SP; st <= S_P1; end
2'd1: begin
{rB, rC, rD, rE, rH, rL} <= {aB, aC, aD, aE, aH, aL};
{aB, aC, aD, aE, aH, aL} <= {rB, rC, rD, rE, rH, rL};
end
2'd2: jump(xr(xm));
2'd3: SP <= xr(xm);
endcase
3'd2: begin take <= cond(y, rF); ic <= I_JP; rsm <= 1'b0; st <= S_IML; end
3'd3: case (y)
3'd0: begin take <= 1'b1; ic <= I_JP; rsm <= 1'b0; st <= S_IML; end
3'd1: if (xm != 2'd0) begin rsm <= 1'b0; st <= S_IXCB1; end
else st <= S_CB;
3'd2: begin ic <= I_OUTN; rsm <= 1'b0; st <= S_IMM; end
3'd3: begin ic <= I_INN; rsm <= 1'b0; st <= S_IMM; end
3'd4: begin ic <= I_EXSP; ma <= SP; st <= S_P1; end
3'd5: begin {rD, rE} <= HL; {rH, rL} <= DE; end
3'd6: begin iff1 <= 1'b0; iff2 <= 1'b0; end
3'd7: begin iff1 <= 1'b1; iff2 <= 1'b1; end
endcase
3'd4: begin take <= cond(y, rF); ic <= I_CALL; rsm <= 1'b0; st <= S_IML; end
3'd5:
if (!q) begin // PUSH
v16 = getrp2(p, xm);
tmp <= v16; SP <= SP - 1'b1; wr(SP - 1'b1, v16[15:8]);
ic <= I_PUSH; st <= S_W1;
end else case (p)
2'd0: begin take <= 1'b1; ic <= I_CALL; rsm <= 1'b0; st <= S_IML; end
2'd1: xm <= 2'd1;
2'd2: st <= S_ED;
2'd3: xm <= 2'd2;
endcase
3'd6: begin ic <= I_ALUN; rsm <= 1'b0; st <= S_IMM; end
3'd7: begin // RST
tmp <= PC; ea <= {10'd0, y, 3'd0};
SP <= SP - 1'b1; wr(SP - 1'b1, PC[15:8]);
ic <= I_CALL; st <= S_W1;
end
endcase
endcase
end
// ------------------------------------------------------------ CB xx
S_CB: begin
x = din[7:6]; z = din[2:0];
rR <= {rR[7], rR[6:0] + 7'd1};
pd <= 1'b1;
nxa <= PC;
nbad <= 1'b0;
rsm <= 1'b1;
xi <= 2'd0;
ir <= din;
next_stream;
if (z == 3'd6) begin
ic <= I_CBM; ma <= HL; ea <= HL; st <= S_RD;
end else begin
v16 = cbop(din, get8(z, 2'd0), rF);
rF <= v16[15:8];
if (x != 2'd1) put8(z, 2'd0, v16[7:0]);
end
end
S_IXCB1: begin // din = displacement
ea <= xr(xi) + {{8{din[7]}}, din};
ma <= PC + 1'b1; PC <= PC + 1'b1;
st <= S_IXCB2;
end
S_IXCB2: begin // din = operation
ir <= din; ic <= I_CBM; ma <= ea; st <= S_RD;
end
// ------------------------------------------------------------ ED xx
S_ED: begin
x = din[7:6]; y = din[5:3]; z = din[2:0]; p = din[5:4]; q = din[3];
rR <= {rR[7], rR[6:0] + 7'd1};
pd <= 1'b1;
nxa <= PC;
nbad <= 1'b0;
rsm <= 1'b1;
xi <= 2'd0;
ir <= din;
next_stream;
if (x == 2'd1) case (z)
3'd0: begin io_addr <= BC; io_rd <= 1'b1; ic <= I_INC; st <= S_IOR; end
3'd1: begin io_addr <= BC; io_wd <= get8(y, 2'd0); io_wr <= 1'b1; end
3'd2: begin
w24 = adc16(!q, HL, getrp(p, 2'd0), rF);
{rH, rL} <= w24[15:0]; rF <= w24[23:16];
end
3'd3: begin
rsm <= 1'b0;
if (!q) begin tmp <= getrp(p, 2'd0); ic <= I_STNN; end
else ic <= I_LDNN;
st <= S_IML;
end
3'd4: begin v16 = alu(3'd2, 8'd0, rA, rF); rA <= v16[7:0]; rF <= v16[15:8]; end
3'd5: begin iff1 <= iff2; ic <= I_RET; ma <= SP; st <= S_P1; end
3'd6: im <= y[1] ? (y[0] ? 2'd2 : 2'd1) : 2'd0;
3'd7: case (y)
3'd0: rI <= rA;
3'd1: rR <= rA;
3'd2: begin
rA <= rI;
rF <= {rI[7], rI == 8'd0, rI[5], 1'b0, rI[3], iff2, 1'b0, rF[CF]};
end
3'd3: begin
v8 = {rR[7], rR[6:0] + 7'd1};
rA <= v8;
rF <= {v8[7], v8 == 8'd0, v8[5], 1'b0, v8[3], iff2, 1'b0, rF[CF]};
end
3'd4: begin ic <= I_RRD; ma <= HL; ea <= HL; st <= S_RD; end
3'd5: begin ic <= I_RLD; ma <= HL; ea <= HL; st <= S_RD; end
default: ;
endcase
endcase
else if (x == 2'd2 && y[2] && !z[2]) case (z[1:0])
2'd0: begin ic <= I_LDI; ma <= HL; st <= S_RD; end
2'd1: begin ic <= I_CPI; ma <= HL; st <= S_RD; end
2'd2: begin ic <= I_INI; io_addr <= BC; io_rd <= 1'b1; st <= S_IOR; end
2'd3: begin ic <= I_OUTI; ma <= HL; st <= S_RD; end
endcase
end
// ------------------------------------------------------ operand bytes
S_JR:
if (take) jump(PC + {{8{din[7]}}, din});
else next_stream;
S_IMM: case (ic) // din = n, ma == PC
I_LDRN: begin put8(dst, xi, din); next_stream; end
I_ALUN: begin
v16 = alu(ir[5:3], rA, din, rF);
if (ir[5:3] != 3'd7) rA <= v16[7:0];
rF <= v16[15:8];
next_stream;
end
I_LDMN: begin wr(HL, din); st <= S_W; end
I_OUTN: begin io_addr <= {rA, din}; io_wd <= rA; io_wr <= 1'b1; next_stream; end
default: begin io_addr <= {rA, din}; io_rd <= 1'b1; ma <= PC; st <= S_IOR; end
endcase
S_IX: begin // din = displacement
v16 = xr(xi) + {{8{din[7]}}, din};
ea <= v16;
case (ic)
I_LDMR: begin wr(v16, tmp[7:0]); st <= S_W; end
I_LDMN: begin ma <= PC + 1'b1; PC <= PC + 1'b1; st <= S_IXN; end
default: begin ma <= v16; st <= S_RD; end
endcase
end
S_IXN: begin wr(ea, din); st <= S_W; end
S_IML: begin tlo <= din; ma <= PC + 1'b1; PC <= PC + 1'b1; st <= S_IMH; end
S_IMH: begin // din = high byte, ma == PC
v16 = {din, tlo};
case (ic)
I_LDRP: begin putrp(ir[5:4], xi, v16); next_stream; end
I_JP: if (take) jump(v16); else next_stream;
I_CALL:
if (take) begin
tmp <= PC; ea <= v16;
SP <= SP - 1'b1; wr(SP - 1'b1, PC[15:8]);
st <= S_W1;
end else next_stream;
I_STNN: begin wr(v16, tmp[7:0]); ea <= v16 + 1'b1; st <= S_ST2; end
I_STNNA: begin wr(v16, rA); st <= S_W; end
I_LDNN: begin ma <= v16; ea <= v16 + 1'b1; st <= S_LD1; end
default: begin ma <= v16; dst <= 3'd7; ic <= I_LDRM; st <= S_RD; end
endcase
end
S_ST2: begin wr(ea, tmp[15:8]); st <= S_W; end
S_LD1: begin ma <= ea; st <= S_LD2; end
S_LD2: begin tlo <= din; ma <= PC; st <= S_LD3; end
S_LD3: begin putrp(ir[5:4], xi, {din, tlo}); next_stream; end
// ------------------------------------------------------ memory operand
S_RD: begin if (!rsm) ma <= PC; st <= S_RDD; end
S_RDD: case (ic) // din = memory byte
I_LDRM: begin put8(dst, 2'd0, din); finish_rd; end
I_ALUM: begin
v16 = alu(ir[5:3], rA, din, rF);
if (ir[5:3] != 3'd7) rA <= v16[7:0];
rF <= v16[15:8];
finish_rd;
end
I_INCM, I_DECM: begin
v16 = incdec(ic == I_DECM, din, rF);
rF <= v16[15:8]; wr(ea, v16[7:0]); st <= S_W;
end
I_CBM: begin
v16 = cbop(ir, din, rF);
rF <= v16[15:8];
if (ir[7:6] == 2'd1) finish_rd;
else begin
wr(ea, v16[7:0]);
if (xi != 2'd0) put8(ir[2:0], 2'd0, v16[7:0]);
st <= S_W;
end
end
I_RRD: begin
rA <= {rA[7:4], din[3:0]};
v8 = {rA[7:4], din[3:0]};
rF <= {v8[7], v8 == 8'd0, v8[5], 1'b0, v8[3], ~^v8, 1'b0, rF[CF]};
wr(ea, {rA[3:0], din[7:4]}); st <= S_W;
end
I_RLD: begin
rA <= {rA[7:4], din[7:4]};
v8 = {rA[7:4], din[7:4]};
rF <= {v8[7], v8 == 8'd0, v8[5], 1'b0, v8[3], ~^v8, 1'b0, rF[CF]};
wr(ea, {din[3:0], rA[3:0]}); st <= S_W;
end
I_LDI: begin
v8 = rA + din;
r16 = BC - 1'b1;
rF <= {rF[SF], rF[ZF], v8[1], 1'b0, v8[3], r16 != 16'd0, 1'b0, rF[CF]};
wr(DE, din);
{rB, rC} <= r16;
{rH, rL} <= ir[3] ? HL - 1'b1 : HL + 1'b1;
{rD, rE} <= ir[3] ? DE - 1'b1 : DE + 1'b1;
st <= ir[4] && r16 != 16'd0 ? S_BLK : S_W;
end
I_CPI: begin
v16 = alu(3'd2, rA, din, rF);
v8 = v16[7:0] - v16[HF + 8];
r16 = BC - 1'b1;
rF <= {v16[15], v16[14], v8[1], v16[HF + 8], v8[3], r16 != 16'd0, 1'b1, rF[CF]};
{rB, rC} <= r16;
v16 = ir[3] ? HL - 1'b1 : HL + 1'b1;
{rH, rL} <= v16;
if (ir[4] && r16 != 16'd0 && rA != din) begin ma <= v16; st <= S_RD; end
else finish;
end
default: begin // OUTI/OUTD/OTIR/OTDR
v8 = rB - 1'b1;
io_addr <= {v8, rC}; io_wd <= din; io_wr <= 1'b1;
rB <= v8;
rF <= {v8[7], v8 == 8'd0, v8[5], rF[HF], v8[3], rF[PF], 1'b1, rF[CF]};
v16 = ir[3] ? HL - 1'b1 : HL + 1'b1;
{rH, rL} <= v16;
if (ir[4] && v8 != 8'd0) begin ma <= v16; st <= S_RD; end
else finish;
end
endcase
S_BLK: begin ma <= HL; st <= S_RD; end // LDIR: write done, read next
S_IOR: case (ic) // io_din valid
I_INC: begin
v8 = io_din;
put8(ir[5:3], 2'd0, v8);
rF <= {v8[7], v8 == 8'd0, v8[5], 1'b0, v8[3], ~^v8, 1'b0, rF[CF]};
finish;
end
I_INN: begin rA <= io_din; next_stream; end
default: begin // INI/IND/INIR/INDR
v8 = rB - 1'b1;
wr(HL, io_din);
rB <= v8;
rF <= {v8[7], v8 == 8'd0, v8[5], rF[HF], v8[3], rF[PF], 1'b1, rF[CF]};
{rH, rL} <= ir[3] ? HL - 1'b1 : HL + 1'b1;
st <= ir[4] && v8 != 8'd0 ? S_INIW : S_W;
end
endcase
S_INIW: begin io_addr <= BC; io_rd <= 1'b1; st <= S_IOR; end
S_W: finish; // a write is completing
// ------------------------------------------------------------- stack
S_W1: begin wr(SP - 1'b1, tmp[7:0]); SP <= SP - 1'b1; st <= S_W2; end
S_W2: if (ic == I_CALL) jump(ea); else finish;
S_P1: begin ma <= SP + 1'b1; st <= S_P2; end
S_P2: begin tlo <= din; st <= S_P3; end
S_P3: begin
v16 = {din, tlo};
case (ic)
I_RET: begin SP <= SP + 2'd2; jump(v16); end
I_POP: begin SP <= SP + 2'd2; putrp2(ir[5:4], xi, v16); finish; end
default: begin // EX (SP),HL
tmp <= v16;
v16 = xr(xi);
wr(SP, v16[7:0]); st <= S_EX2;
end
endcase
end
S_EX2: begin
v16 = xr(xi);
wr(SP + 1'b1, v16[15:8]);
putrp(2'd2, xi, tmp);
st <= S_W;
end
S_HALT: ;
default: st <= S_F;
endcase
end
endmodule
+97
View File
@@ -0,0 +1,97 @@
`timescale 1ns / 1ps
// Z-80 computer: CPU, 64 KB of block RAM preloaded with BASIC, console and
// timer ports. Runs on its own clock; the console crosses to the terminal's
// clock with toggle handshakes (one byte in flight each way).
//
// I/O ports (low address byte):
// 00 in bit 0 = key waiting, bit 1 = console can take a byte
// 01 in key (clears bit 0) out byte to the terminal
// 10 in millisecond counter bits 7:0; reading it latches bits 31:8 for 11-13
// 20 out 7-segment display, right two digits 21 out left two digits
//
// Writes below ROM_TOP are ignored so a crashed program cannot damage BASIC.
module z80_system #(
parameter MEM_FILE = "basic.mem",
parameter CPU_HZ = 100_000_000,
parameter ROM_TOP = 16'h8000
) (
input clk, // CPU clock
input rst, // synchronous to clk
// keyboard side: a byte is offered when rx_req != rx_ack
input rx_req,
input [7:0] rx_data,
output reg rx_ack,
// screen side: a byte is offered when tx_req != tx_ack
output reg tx_req,
output reg [7:0] tx_data,
input tx_ack,
output reg [15:0] seg_val,
output halted
);
wire [15:0] ma, io_addr;
wire we, io_rd, io_wr;
wire [7:0] wd, io_wd;
reg [7:0] din, io_din;
z80_cpu cpu (
.clk(clk), .rst(rst), .ma(ma), .we(we), .wd(wd), .din(din),
.io_addr(io_addr), .io_rd(io_rd), .io_wr(io_wr), .io_wd(io_wd), .io_din(io_din),
.halted(halted), .ins_start(), .dbg_pc(),
.dbg_af(), .dbg_bc(), .dbg_de(), .dbg_hl(), .dbg_ix(), .dbg_iy(), .dbg_sp()
);
reg [7:0] ram [0:65535];
initial $readmemh(MEM_FILE, ram);
always @(posedge clk) begin
if (we && ma >= ROM_TOP) ram[ma] <= wd;
din <= ram[ma];
end
// ------------------------------------------------------------- console
(* ASYNC_REG = "TRUE" *) reg [1:0] rx_req_s, tx_ack_s;
always @(posedge clk) begin
rx_req_s <= {rx_req_s[0], rx_req};
tx_ack_s <= {tx_ack_s[0], tx_ack};
end
wire rx_avail = rx_req_s[1] != rx_ack;
wire tx_ready = tx_ack_s[1] == tx_req;
// millisecond timer
localparam MS_DIV = CPU_HZ / 1000;
reg [31:0] ms, ms_latch;
reg [17:0] ms_div;
always @(posedge clk)
if (rst) begin
ms <= 0; ms_div <= 0;
end else if (ms_div == MS_DIV - 1) begin
ms <= ms + 1'b1; ms_div <= 0;
end else
ms_div <= ms_div + 1'b1;
always @* case (io_addr[7:0])
8'h00: io_din = {6'd0, tx_ready, rx_avail};
8'h01: io_din = rx_data;
8'h10: io_din = ms_latch[7:0];
8'h11: io_din = ms_latch[15:8];
8'h12: io_din = ms_latch[23:16];
8'h13: io_din = ms_latch[31:24];
default: io_din = 8'hFF;
endcase
always @(posedge clk)
if (rst) begin
rx_ack <= rx_req_s[1];
tx_req <= tx_ack_s[1];
seg_val <= 16'h2080;
end else begin
if (io_rd && io_addr[7:0] == 8'h01 && rx_avail) rx_ack <= ~rx_ack;
if (io_rd && io_addr[7:0] == 8'h10) ms_latch <= ms;
if (io_wr && io_addr[7:0] == 8'h01 && tx_ready) begin
tx_data <= io_wd;
tx_req <= ~tx_req;
end
if (io_wr && io_addr[7:0] == 8'h20) seg_val[7:0] <= io_wd;
if (io_wr && io_addr[7:0] == 8'h21) seg_val[15:8] <= io_wd;
end
endmodule
+16 -4
View File
@@ -1,19 +1,31 @@
# Non-project Vivado build: vivado -mode batch -source scripts/build.tcl # Non-project Vivado build: vivado -mode batch -source scripts/build.tcl
# The Z-80 clock is 100 MHz * CPU_MULT / CPU_DIV (environment variables).
set root [file normalize [file dirname [info script]]/..] set root [file normalize [file dirname [info script]]/..]
set out $root/build set out $root/build
file mkdir $out file mkdir $out
set mult [expr {[info exists ::env(CPU_MULT)] ? $::env(CPU_MULT) : 9.0}]
set div [expr {[info exists ::env(CPU_DIV)] ? $::env(CPU_DIV) : 10.0}]
set hz [expr {int(round(100e6 * $mult / $div))}]
puts "Z-80 clock: [expr {$hz / 1e6}] MHz"
read_verilog [glob $root/rtl/*.v] read_verilog [glob $root/rtl/*.v]
read_mem $root/font/font.mem read_mem $root/font/font.mem
read_mem $root/basic/basic.mem
read_xdc $root/constraints/basys3.xdc read_xdc $root/constraints/basys3.xdc
synth_design -top basys3_terminal -part xc7a35tcpg236-1 synth_design -top basys3_terminal -part xc7a35tcpg236-1 \
opt_design -generic CPU_MULT=$mult -generic CPU_DIV=$div -generic CPU_HZ=$hz
place_design opt_design -directive Explore
route_design place_design -directive ExtraTimingOpt
phys_opt_design -directive AggressiveExplore
route_design -directive Explore
phys_opt_design -directive AggressiveExplore
write_checkpoint -force $out/routed.dcp
report_utilization -file $out/utilization.rpt report_utilization -file $out/utilization.rpt
report_timing_summary -file $out/timing.rpt report_timing_summary -file $out/timing.rpt
report_timing -max_paths 30 -nworst 1 -unique_pins -file $out/paths.rpt
write_bitstream -force $out/basys3_terminal.bit write_bitstream -force $out/basys3_terminal.bit
write_cfgmem -force -format mcs -interface SPIx4 -size 4 \ write_cfgmem -force -format mcs -interface SPIx4 -size 4 \
-loadbit "up 0x0 $out/basys3_terminal.bit" $out/basys3_terminal.mcs -loadbit "up 0x0 $out/basys3_terminal.bit" $out/basys3_terminal.mcs
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
# Run a Z-80 image on the Verilog CPU and on tools/z80emu.py and compare traces.
# scripts/cpusim.sh image.mem [input-file] [max-clocks]
set -e
cd "$(dirname "$0")/.."
ROOT=$(pwd)
IMG=$(realpath "$1")
INP=$(realpath "${2:-/dev/null}")
MAX=${3:-20000000}
source scripts/vivado_env.sh
mkdir -p sim/cpu
cd sim/cpu
xvlog -d IMAGE="\"$IMG\"" -d INPUT="\"$INP\"" "$ROOT/rtl/z80_cpu.v" "$ROOT/sim/tb_cpu.v" >/dev/null
xelab -debug off tb_cpu -s tb_cpu >/dev/null
xsim tb_cpu -R -testplusarg max=$MAX | grep -v -e '^INFO' -e '^#' -e '^\*\*' -e '^Vivado' -e '^ *\*\*\*\*' -e '^source' -e '^run' -e '^exit' -e '^\$finish' -e '^Time:' -e '^Copyright'
python3 "$ROOT/tools/z80emu.py" "${IMG%.mem}.bin" --input "$INP" --trace trace_sw.txt \
--max "$(wc -l < trace_hw.txt)" > out_sw.txt
python3 "$ROOT/tools/cmptrace.py" trace_sw.txt trace_hw.txt
cmp -s mem_sw.txt mem_hw.txt && echo "memory 8000-FFFF matches" || { echo "MEMORY DIFFERS"; exit 1; }
+1 -1
View File
@@ -6,7 +6,7 @@ ROOT=$(pwd)
source scripts/vivado_env.sh source scripts/vivado_env.sh
mkdir -p sim/work mkdir -p sim/work
cd sim/work cd sim/work
xvlog -d FONT_FILE="\"$ROOT/font/font.mem\"" "$ROOT"/rtl/*.v "$ROOT"/sim/tb_terminal.v xvlog -d SIMULATION -d FONT_FILE="\"$ROOT/font/font.mem\"" -d MEM_FILE="\"$ROOT/basic/basic.mem\"" "$ROOT"/rtl/*.v "$ROOT"/sim/tb_terminal.v
xelab -debug off tb_terminal -s tb_terminal xelab -debug off tb_terminal -s tb_terminal
xsim tb_terminal -R xsim tb_terminal -R
if command -v python3 >/dev/null; then if command -v python3 >/dev/null; then
+67
View File
@@ -0,0 +1,67 @@
`timescale 1ns / 1ps
// CPU-only test: runs an image in 64 KB of RAM and writes a register trace at
// the start of every instruction (compared against tools/z80emu.py).
// Console: port 0 reads {tx ready, input available}, port 1 reads/writes data.
module tb_cpu;
reg clk = 0, rst = 1;
always #5 clk = ~clk;
wire [15:0] ma, io_addr;
wire we, io_rd, io_wr, halted, ins_start;
wire [7:0] wd, io_wd;
reg [7:0] din, io_din;
wire [15:0] pc, af, bc, de, hl, ix, iy, sp;
z80_cpu cpu (
.clk(clk), .rst(rst), .ma(ma), .we(we), .wd(wd), .din(din),
.io_addr(io_addr), .io_rd(io_rd), .io_wr(io_wr), .io_wd(io_wd), .io_din(io_din),
.halted(halted), .ins_start(ins_start), .dbg_pc(pc),
.dbg_af(af), .dbg_bc(bc), .dbg_de(de), .dbg_hl(hl), .dbg_ix(ix), .dbg_iy(iy), .dbg_sp(sp)
);
reg [7:0] mem [0:65535];
integer rom_top = 0;
always @(posedge clk) begin
if (we && ma >= rom_top) mem[ma] <= wd;
din <= mem[ma];
end
reg [7:0] inbuf [0:65535];
integer in_n = 0, in_p = 0, fd, tr, n = 0, cycles = 0, max_cycles;
always @* io_din = io_addr[7:0] == 8'd0 ? {6'd0, 1'b1, in_p < in_n} :
io_addr[7:0] == 8'd1 ? (in_p < in_n ? inbuf[in_p] : 8'd0) : 8'hFF;
always @(posedge clk) if (io_rd && io_addr[7:0] == 8'd1 && in_p < in_n) in_p <= in_p + 1;
always @(posedge clk) if (io_wr && io_addr[7:0] == 8'd1) $write("%c", io_wd);
always @(posedge clk) if (!rst) begin
cycles = cycles + 1;
if (ins_start) begin
if (tr) $fwrite(tr, "%h %h %h %h %h %h %h %h\n", pc, af, bc, de, hl, ix, iy, sp);
n = n + 1;
end
end
initial begin
if (!$value$plusargs("max=%d", max_cycles)) max_cycles = 10_000_000;
$value$plusargs("romtop=%d", rom_top);
for (n = 0; n < 65536; n = n + 1) mem[n] = 8'h00;
n = 0;
$readmemh(`IMAGE, mem);
fd = $fopen(`INPUT, "rb");
if (fd) begin
while (!$feof(fd)) begin inbuf[in_n] = $fgetc(fd); in_n = in_n + 1; end
in_n = in_n - 1;
end
tr = $fopen("trace_hw.txt", "w");
#20 rst = 0;
wait (halted || cycles >= max_cycles);
repeat (2) @(posedge clk);
$display("\n[%0d instructions, %0d clocks%0s]", n, cycles, halted ? ", halted" : "");
$fclose(tr);
fd = $fopen("mem_hw.txt", "w");
for (n = 32768; n < 65536; n = n + 1) $fwrite(fd, "%h\n", mem[n]);
$fclose(fd);
$finish;
end
endmodule
+21 -3
View File
@@ -8,15 +8,15 @@ module tb_terminal;
always #5 clk = ~clk; always #5 clk = ~clk;
reg [15:0] sw = 16'h0200; // 115200 baud, fast smooth scroll when enabled reg [15:0] sw = 16'h0200; // 115200 baud, fast smooth scroll when enabled
reg btnC = 0, btnU = 0; reg btnC = 0, btnU = 0, btnD = 0;
reg rsrx = 1; reg rsrx = 1;
reg ps2c = 1, ps2d = 1; reg ps2c = 1, ps2d = 1;
wire rstx, hs, vs; wire rstx, hs, vs;
wire [3:0] r, g, b; wire [3:0] r, g, b;
wire [15:0] led; wire [15:0] led;
basys3_terminal #(.FONT_FILE(`FONT_FILE)) dut ( basys3_terminal #(.FONT_FILE(`FONT_FILE), .MEM_FILE(`MEM_FILE)) dut (
.clk(clk), .btnC(btnC), .btnU(btnU), .sw(sw), .led(led), .seg(), .dp(), .an(), .clk(clk), .btnC(btnC), .btnU(btnU), .btnD(btnD), .sw(sw), .led(led), .seg(), .dp(), .an(),
.vgaRed(r), .vgaGreen(g), .vgaBlue(b), .Hsync(hs), .Vsync(vs), .vgaRed(r), .vgaGreen(g), .vgaBlue(b), .Hsync(hs), .Vsync(vs),
.RsRx(rsrx), .RsTx(rstx), .PS2Clk(ps2c), .PS2Data(ps2d) .RsRx(rsrx), .RsTx(rstx), .PS2Clk(ps2c), .PS2Data(ps2d)
); );
@@ -245,6 +245,24 @@ module tb_terminal;
expect_row(17, "r7"); expect_row(17, "r7");
expect_row(18, "below region"); expect_row(18, "below region");
uart_str("\033[?4l\033[r"); uart_str("\033[?4l\033[r");
dump_screen;
// ---- Z-80 BASIC as the console, input pasted over the UART
uart_str("\033[2J\033[H");
#100_000;
sw[15] = 1; sw[14] = 1; // the Z-80 has been waiting to print its banner
#3_000_000;
uart_str("PRINT 2+2\015");
#2_000_000;
uart_str("10 FOR I=1 TO 3: PRINT I*I;: NEXT I\015RUN\015");
#5_000_000;
expect_row(1, "DARTMOUTH-STYLE BASIC");
expect_row(3, "READY");
expect_row(4, "PRINT 2+2");
expect_row(5, " 4");
expect_row(7, "READY");
expect_row(10, " 1 4 9");
expect_row(11, "READY");
dump_screen; dump_screen;
if (errors == 0) $display("ALL TESTS PASSED"); if (errors == 0) $display("ALL TESTS PASSED");
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Compare two register traces; print the first difference with context."""
import sys
names = "pc af bc de hl ix iy sp".split()
a = open(sys.argv[1]).read().split("\n")
b = open(sys.argv[2]).read().split("\n")
for i, (x, y) in enumerate(zip(a, b)):
if x != y:
print("MISMATCH at instruction %d" % i)
for j in range(max(0, i - 4), i):
print(" ", a[j])
print("sw:", x)
print("hw:", y)
print(" ", " ".join(n for n, u, v in zip(names, x.split(), y.split()) if u != v), "differ")
sys.exit(1)
print("traces match: %d instructions" % (min(len(a), len(b)) - 1))
if len(a) != len(b):
print("lengths differ: sw %d hw %d" % (len(a) - 1, len(b) - 1))
sys.exit(1)
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Random instruction test for the CPU: writes cputest.bin/.mem.
Each block loads random values into the registers (pointers aim at a scratch
area), then runs one random instruction. Control flow instructions branch to
the next block either way, so the program always runs straight through.
"""
import random
import sys
rnd = random.Random(int(sys.argv[1]) if len(sys.argv) > 1 else 1)
blocks = int(sys.argv[2]) if len(sys.argv) > 2 else 3000
code = bytearray()
def w16(v):
return [v & 0xFF, v >> 8 & 0xFF]
def ptr():
return 0x8000 + rnd.randrange(0x40, 0x1C0)
def setup(block_op):
c = [0x31] + w16(0xF000) # LD SP,F000
c += [0x01] + w16(rnd.randrange(65536)) + [0xC5, 0xF1] # random AF
c += [0x01] + w16(rnd.randrange(1, 4) if block_op else ptr())
c += [0x11] + w16(ptr()) + [0x21] + w16(ptr())
c += [0xDD, 0x21] + w16(ptr()) + [0xFD, 0x21] + w16(ptr())
return c
def main_op():
"""A random non-prefixed opcode with its operands, or None to retry."""
op = rnd.randrange(256)
x, y, z = op >> 6, op >> 3 & 7, op & 7
if op in (0x76, 0xCB, 0xDD, 0xED, 0xFD):
return None
if op in (0xC9, 0xE9, 0xD3, 0xDB) or (x == 3 and z in (0, 7)): # RET, JP (HL), I/O, RST
return None
if op in (0x10, 0x18) or (x == 0 and z == 0 and y >= 4):
return [op, 0] # JR/DJNZ to the next byte
if op == 0x22 or op == 0x2A or op == 0x32 or op == 0x3A:
return [op] + w16(ptr())
if x == 0 and z == 1 and op & 8 == 0:
return [op] + w16(rnd.randrange(65536))
if x == 0 and z == 6:
return [op, rnd.randrange(256)]
if x == 3 and z == 6:
return [op, rnd.randrange(256)]
if x == 3 and z in (2, 4) or op in (0xC3, 0xCD):
return [op, None, None] # target filled in later
return [op]
def instruction():
kind = rnd.randrange(10)
if kind < 5:
while (c := main_op()) is None:
pass
return c, False
if kind < 7:
while (c := main_op()) is None:
pass
if c[0] == 0xF9: # LD SP,IX is fine too
pass
c = [rnd.choice((0xDD, 0xFD))] + c
op = c[1]
if op >> 6 in (1, 2) and (op & 7 == 6 or (op >> 6 == 1 and op >> 3 & 7 == 6)) \
or op in (0x34, 0x35):
c.insert(2, rnd.randrange(256)) # (IX+d) displacement
elif op == 0x36:
c[2:3] = [rnd.randrange(256), rnd.randrange(256)]
return c, False
if kind == 7:
return [0xCB, rnd.randrange(256)], False
if kind == 8:
return [rnd.choice((0xDD, 0xFD)), 0xCB, rnd.randrange(256), rnd.randrange(256)], False
while True:
op = rnd.randrange(0x40, 0xC0)
x, y, z = op >> 6, op >> 3 & 7, op & 7
if x == 1 and z in (0, 1) or (x == 1 and z == 5) or (x == 1 and z == 7 and y == 1):
continue # I/O, RETN, LD R,A
if x == 2 and not (y >= 4 and z <= 1):
continue # only LDI/LDD/CPI/CPD (+R)
if x == 1 and z == 3:
return [0xED, op] + w16(ptr()), False
return [0xED, op], x == 2
for _ in range(blocks):
ins, blk = instruction()
code += bytes(setup(blk))
if None in ins:
end = len(code) + len(ins)
ins = [v if v is not None else 0 for v in ins]
ins[-2:] = w16(end)
code += bytes(ins)
code += b"\x76"
assert len(code) < 0x8000
open("cputest.bin", "wb").write(code)
open("cputest.mem", "w").write("".join("%02x\n" % b for b in code))
print("%d bytes" % len(code))
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
"""Convert an Intel HEX file to a raw binary and a 64 KB $readmemh image."""
import sys
mem = bytearray(65536)
top = 0
for line in open(sys.argv[1]):
line = line.strip()
if not line.startswith(":"):
continue
b = bytes.fromhex(line[1:])
n, addr, kind = b[0], b[1] << 8 | b[2], b[3]
if kind == 0:
mem[addr:addr + n] = b[4:4 + n]
top = max(top, addr + n)
open(sys.argv[2], "wb").write(mem[:top])
open(sys.argv[3], "w").write("".join("%02x\n" % v for v in mem))
code = max(a for a in range(0x8000) if mem[a]) + 1 if any(mem[:0x8000]) else 0
print("image: %d bytes, code ends at 0x%04X" % (top, code))
+545
View File
@@ -0,0 +1,545 @@
#!/usr/bin/env python3
"""Reference Z-80 emulator used to check the Verilog CPU instruction by instruction.
Same behaviour as rtl/z80_cpu.v: documented instruction set, undocumented
IXH/IXL forms, SLL and DDCB register copies, X/Y flags; no interrupts.
python3 tools/z80emu.py image.bin [--input FILE] [--trace FILE] [--max N]
"""
import sys
SF, ZF, YF, HF, XF, PF, NF, CF = 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01
def parity(v):
return 0 if bin(v & 0xFF).count("1") & 1 else PF
def szxy(r):
return (r & (SF | YF | XF)) | (0 if r & 0xFF else ZF)
class Z80:
def __init__(self, mem, inp=b"", out=None):
self.m = bytearray(mem) + bytearray(65536 - len(mem))
self.a = self.f = 0xFF
self.b = self.c = self.d = self.e = self.h = self.l = 0
self.alt = [0] * 8 # a f b c d e h l
self.ix = self.iy = 0xFFFF
self.sp = 0xFFFF
self.pc = 0
self.i = self.r = 0
self.iff1 = self.iff2 = 0
self.im = 0
self.halted = False
self.inp = bytearray(inp)
self.out = out if out is not None else bytearray()
self.rom_top = 0
# ------------------------------------------------------------- helpers
def rd(self, a):
return self.m[a & 0xFFFF]
def wr(self, a, v):
a &= 0xFFFF
if a >= self.rom_top:
self.m[a] = v & 0xFF
def rd16(self, a):
return self.rd(a) | self.rd(a + 1) << 8
def wr16(self, a, v):
self.wr(a, v)
self.wr(a + 1, v >> 8)
def fetch(self):
v = self.m[self.pc]
self.pc = (self.pc + 1) & 0xFFFF
return v
def fetch16(self):
lo = self.fetch()
return lo | self.fetch() << 8
def push(self, v):
self.sp = (self.sp - 1) & 0xFFFF
self.wr(self.sp, v >> 8)
self.sp = (self.sp - 1) & 0xFFFF
self.wr(self.sp, v)
def pop(self):
v = self.rd16(self.sp)
self.sp = (self.sp + 2) & 0xFFFF
return v
def inc_r(self):
self.r = (self.r & 0x80) | ((self.r + 1) & 0x7F)
def io_in(self, port):
p = port & 0xFF
if p == 0:
return (1 if self.inp else 0) | 2
if p == 1:
return self.inp.pop(0) if self.inp else 0
return 0xFF
def io_out(self, port, v):
if port & 0xFF == 1:
self.out.append(v)
# register pairs
@property
def bc(self): return self.b << 8 | self.c
@bc.setter
def bc(self, v): self.b, self.c = v >> 8 & 0xFF, v & 0xFF
@property
def de(self): return self.d << 8 | self.e
@de.setter
def de(self, v): self.d, self.e = v >> 8 & 0xFF, v & 0xFF
@property
def hl(self): return self.h << 8 | self.l
@hl.setter
def hl(self, v): self.h, self.l = v >> 8 & 0xFF, v & 0xFF
def getx(self, x):
return (self.hl, self.ix, self.iy)[x]
def setx(self, x, v):
v &= 0xFFFF
if x == 0: self.hl = v
elif x == 1: self.ix = v
else: self.iy = v
def get8(self, i, x):
if i == 0: return self.b
if i == 1: return self.c
if i == 2: return self.d
if i == 3: return self.e
if i == 4: return self.getx(x) >> 8
if i == 5: return self.getx(x) & 0xFF
if i == 7: return self.a
return 0
def put8(self, i, x, v):
v &= 0xFF
if i == 0: self.b = v
elif i == 1: self.c = v
elif i == 2: self.d = v
elif i == 3: self.e = v
elif i == 4: self.setx(x, (self.getx(x) & 0xFF) | v << 8)
elif i == 5: self.setx(x, (self.getx(x) & 0xFF00) | v)
elif i == 7: self.a = v
def getrp(self, p, x):
return (self.bc, self.de, self.getx(x), self.sp)[p]
def putrp(self, p, x, v):
v &= 0xFFFF
if p == 0: self.bc = v
elif p == 1: self.de = v
elif p == 2: self.setx(x, v)
else: self.sp = v
def getrp2(self, p, x):
return self.a << 8 | self.f if p == 3 else self.getrp(p, x)
def putrp2(self, p, x, v):
if p == 3:
self.a, self.f = v >> 8 & 0xFF, v & 0xFF
else:
self.putrp(p, x, v)
def cond(self, cc):
f = self.f
return [not f & ZF, bool(f & ZF), not f & CF, bool(f & CF),
not f & PF, bool(f & PF), not f & SF, bool(f & SF)][cc]
# ----------------------------------------------------------------- ALU
def alu(self, op, b):
a = self.a
if op in (0, 1):
c = self.f & CF if op == 1 else 0
s = a + b + c
r = s & 0xFF
f = (CF if s > 0xFF else 0) | ((a ^ b ^ r) & HF)
if (a ^ b) & 0x80 == 0 and (a ^ r) & 0x80: f |= PF
elif op in (2, 3, 7):
c = self.f & CF if op == 3 else 0
s = a - b - c
r = s & 0xFF
f = NF | (CF if s < 0 else 0) | ((a ^ b ^ r) & HF)
if (a ^ b) & 0x80 and (a ^ r) & 0x80: f |= PF
else:
r = (a & b, a ^ b, a | b)[op - 4]
f = parity(r) | (HF if op == 4 else 0)
f |= (r & SF) | (0 if r else ZF)
if op == 7:
f |= b & (YF | XF)
else:
f |= r & (YF | XF)
self.a = r
self.f = f
def incdec(self, v, dec):
r = (v - 1 if dec else v + 1) & 0xFF
f = (self.f & CF) | szxy(r)
if dec:
f |= NF | (HF if v & 0xF == 0 else 0) | (PF if v == 0x80 else 0)
else:
f |= (HF if v & 0xF == 0xF else 0) | (PF if v == 0x7F else 0)
self.f = f
return r
def cbop(self, op, v):
x, y = op >> 6, op >> 3 & 7
if x == 0:
c = self.f & CF
if y == 0: c = v >> 7; r = v << 1 | c
elif y == 1: c = v & 1; r = v >> 1 | c << 7
elif y == 2: r = v << 1 | c; c = v >> 7
elif y == 3: r = v >> 1 | c << 7; c = v & 1
elif y == 4: c = v >> 7; r = v << 1
elif y == 5: c = v & 1; r = v >> 1 | (v & 0x80)
elif y == 6: c = v >> 7; r = v << 1 | 1
else: c = v & 1; r = v >> 1
r &= 0xFF
self.f = szxy(r) | parity(r) | c
return r
if x == 1:
z = 0 if v >> y & 1 else ZF | PF
s = SF if y == 7 and v & 0x80 else 0
self.f = s | z | HF | (v & (YF | XF)) | (self.f & CF)
return v
if x == 2:
return v & ~(1 << y) & 0xFF
return v | 1 << y
def accop(self, y):
a, f = self.a, self.f
keep = f & (SF | ZF | PF)
if y == 0:
c = a >> 7; r = (a << 1 | c) & 0xFF
self.f = keep | (r & (YF | XF)) | c
elif y == 1:
c = a & 1; r = a >> 1 | c << 7
self.f = keep | (r & (YF | XF)) | c
elif y == 2:
r = (a << 1 | (f & CF)) & 0xFF
self.f = keep | (r & (YF | XF)) | a >> 7
elif y == 3:
r = a >> 1 | (f & CF) << 7
self.f = keep | (r & (YF | XF)) | (a & 1)
elif y == 4:
corr, c = 0, f & CF
if f & HF or a & 0xF > 9: corr |= 0x06
if f & CF or a > 0x99: corr |= 0x60; c = 1
if f & NF:
r = (a - corr) & 0xFF
h = HF if f & HF and a & 0xF < 6 else 0
else:
r = (a + corr) & 0xFF
h = HF if a & 0xF > 9 else 0
self.f = szxy(r) | parity(r) | h | (f & NF) | c
elif y == 5:
r = a ^ 0xFF
self.f = keep | (r & (YF | XF)) | HF | NF | (f & CF)
elif y == 6:
r = a
self.f = keep | (a & (YF | XF)) | CF
else:
r = a
self.f = keep | (a & (YF | XF)) | (HF if f & CF else 0) | (f & CF ^ 1)
self.a = r
def add16(self, a, b):
s = a + b
self.f = (self.f & (SF | ZF | PF)) | (s >> 8 & (YF | XF)) | ((a ^ b ^ s) >> 8 & HF) | \
(CF if s > 0xFFFF else 0)
return s & 0xFFFF
def adc16(self, a, b, sub):
c = self.f & CF
if sub:
s = a - b - c
v = (a ^ b) & 0x8000 and (a ^ s) & 0x8000
else:
s = a + b + c
v = not (a ^ b) & 0x8000 and (a ^ s) & 0x8000
r = s & 0xFFFF
self.f = (r >> 8 & (SF | YF | XF)) | (0 if r else ZF) | ((a ^ b ^ s) >> 8 & HF) | \
(PF if v else 0) | (NF if sub else 0) | (CF if s < 0 or s > 0xFFFF else 0)
return r
# ------------------------------------------------------------- execute
def step(self):
x = 0
while True:
op = self.fetch()
self.inc_r()
if op == 0xDD: x = 1; continue
if op == 0xFD: x = 2; continue
break
if op == 0xCB:
if x:
d = self.fetch()
d = d - 256 if d > 127 else d
op2 = self.fetch()
self.exec_cb(op2, x, (self.getx(x) + d) & 0xFFFF)
else:
op2 = self.fetch()
self.inc_r()
self.exec_cb(op2, 0, None)
return
if op == 0xED:
op2 = self.fetch()
self.inc_r()
self.exec_ed(op2)
return
self.exec_main(op, x)
def ea(self, x):
if x == 0:
return self.hl
d = self.fetch()
return (self.getx(x) + (d - 256 if d > 127 else d)) & 0xFFFF
def exec_main(self, op, x):
xx, y, z, p, q = op >> 6, op >> 3 & 7, op & 7, op >> 4 & 3, op >> 3 & 1
if xx == 0:
if z == 0:
if y == 0: return
if y == 1:
self.a, self.f, self.alt[0], self.alt[1] = self.alt[0], self.alt[1], self.a, self.f
return
d = self.fetch()
d = d - 256 if d > 127 else d
if y == 2:
self.b = (self.b - 1) & 0xFF
take = self.b != 0
elif y == 3:
take = True
else:
take = self.cond(y - 4)
if take:
self.pc = (self.pc + d) & 0xFFFF
elif z == 1:
if q == 0:
self.putrp(p, x, self.fetch16())
else:
self.setx(x, self.add16(self.getx(x), self.getrp(p, x)))
elif z == 2:
if p == 0 and q == 0: self.wr(self.bc, self.a)
elif p == 1 and q == 0: self.wr(self.de, self.a)
elif p == 2 and q == 0: self.wr16(self.fetch16(), self.getx(x))
elif p == 3 and q == 0: self.wr(self.fetch16(), self.a)
elif p == 0: self.a = self.rd(self.bc)
elif p == 1: self.a = self.rd(self.de)
elif p == 2: self.setx(x, self.rd16(self.fetch16()))
else: self.a = self.rd(self.fetch16())
elif z == 3:
self.putrp(p, x, self.getrp(p, x) + (-1 if q else 1))
elif z in (4, 5):
if y == 6:
a = self.ea(x)
self.wr(a, self.incdec(self.rd(a), z == 5))
else:
self.put8(y, x, self.incdec(self.get8(y, x), z == 5))
elif z == 6:
if y == 6:
a = self.ea(x)
self.wr(a, self.fetch())
else:
self.put8(y, x, self.fetch())
else:
self.accop(y)
elif xx == 1:
if op == 0x76:
self.halted = True
self.pc = (self.pc - 1) & 0xFFFF
elif z == 6:
self.put8(y, 0, self.rd(self.ea(x)))
elif y == 6:
self.wr(self.ea(x), self.get8(z, 0))
else:
self.put8(y, x, self.get8(z, x))
elif xx == 2:
if z == 6:
self.alu(y, self.rd(self.ea(x)))
else:
self.alu(y, self.get8(z, x))
else:
if z == 0:
if self.cond(y): self.pc = self.pop()
elif z == 1:
if q == 0: self.putrp2(p, x, self.pop())
elif p == 0: self.pc = self.pop()
elif p == 1:
regs = [self.b, self.c, self.d, self.e, self.h, self.l]
self.b, self.c, self.d, self.e, self.h, self.l = self.alt[2:]
self.alt[2:] = regs
elif p == 2: self.pc = self.getx(x)
else: self.sp = self.getx(x)
elif z == 2:
t = self.fetch16()
if self.cond(y): self.pc = t
elif z == 3:
if y == 0: self.pc = self.fetch16()
elif y == 2:
n = self.fetch()
self.io_out(self.a << 8 | n, self.a)
elif y == 3:
n = self.fetch()
self.a = self.io_in(self.a << 8 | n)
elif y == 4:
v = self.rd16(self.sp)
self.wr16(self.sp, self.getx(x))
self.setx(x, v)
elif y == 5:
self.de, self.hl = self.hl, self.de
elif y == 6: self.iff1 = self.iff2 = 0
elif y == 7: self.iff1 = self.iff2 = 1
elif z == 4:
t = self.fetch16()
if self.cond(y):
self.push(self.pc)
self.pc = t
elif z == 5:
if q == 0: self.push(self.getrp2(p, x))
else:
t = self.fetch16()
self.push(self.pc)
self.pc = t
elif z == 6:
self.alu(y, self.fetch())
else:
self.push(self.pc)
self.pc = y * 8
def exec_cb(self, op, x, addr):
z = op & 7
if x:
r = self.cbop(op, self.rd(addr))
if op >> 6 != 1:
self.wr(addr, r)
if z != 6: self.put8(z, 0, r)
elif z == 6:
r = self.cbop(op, self.rd(self.hl))
if op >> 6 != 1: self.wr(self.hl, r)
else:
r = self.cbop(op, self.get8(z, 0))
if op >> 6 != 1: self.put8(z, 0, r)
def exec_ed(self, op):
xx, y, z, p, q = op >> 6, op >> 3 & 7, op & 7, op >> 4 & 3, op >> 3 & 1
if xx == 1:
if z == 0:
v = self.io_in(self.bc)
if y != 6: self.put8(y, 0, v)
self.f = szxy(v) | parity(v) | (self.f & CF)
elif z == 1:
self.io_out(self.bc, self.get8(y, 0))
elif z == 2:
self.hl = self.adc16(self.hl, self.getrp(p, 0), q == 0)
elif z == 3:
a = self.fetch16()
if q == 0: self.wr16(a, self.getrp(p, 0))
else: self.putrp(p, 0, self.rd16(a))
elif z == 4:
a = self.a
self.a = 0
self.alu(2, a)
elif z == 5:
self.iff1 = self.iff2
self.pc = self.pop()
elif z == 6:
self.im = (0, 0, 1, 2)[y & 3]
else:
if y == 0: self.i = self.a
elif y == 1: self.r = self.a
elif y in (2, 3):
v = self.i if y == 2 else self.r
self.a = v
self.f = szxy(v) | (PF if self.iff2 else 0) | (self.f & CF)
elif y in (4, 5):
m = self.rd(self.hl)
if y == 4:
self.a, m = (self.a & 0xF0) | (m & 0x0F), ((self.a & 0x0F) << 4) | (m >> 4)
else:
self.a, m = (self.a & 0xF0) | (m >> 4), ((m & 0x0F) << 4) | (self.a & 0x0F)
self.wr(self.hl, m)
self.f = szxy(self.a) | parity(self.a) | (self.f & CF)
elif xx == 2 and y >= 4 and z <= 3:
dec, rep = y & 1, y & 2
step = -1 if dec else 1
while True:
if z == 0:
v = self.rd(self.hl)
self.wr(self.de, v)
self.hl = (self.hl + step) & 0xFFFF
self.de = (self.de + step) & 0xFFFF
self.bc = (self.bc - 1) & 0xFFFF
n = (self.a + v) & 0xFF
self.f = (self.f & (SF | ZF | CF)) | (YF if n & 2 else 0) | (n & XF) | \
(PF if self.bc else 0)
again = rep and self.bc
elif z == 1:
v = self.rd(self.hl)
r = (self.a - v) & 0xFF
h = (self.a ^ v ^ r) & HF
n = (r - (1 if h else 0)) & 0xFF
self.hl = (self.hl + step) & 0xFFFF
self.bc = (self.bc - 1) & 0xFFFF
self.f = (r & SF) | (0 if r else ZF) | h | NF | (self.f & CF) | \
(YF if n & 2 else 0) | (n & XF) | (PF if self.bc else 0)
again = rep and self.bc and r
elif z == 2:
v = self.io_in(self.bc)
self.wr(self.hl, v)
self.b = (self.b - 1) & 0xFF
self.hl = (self.hl + step) & 0xFFFF
self.f = (self.f & (HF | PF | CF)) | szxy(self.b) | NF
again = rep and self.b
else:
v = self.rd(self.hl)
self.b = (self.b - 1) & 0xFF
self.io_out(self.bc, v)
self.hl = (self.hl + step) & 0xFFFF
self.f = (self.f & (HF | PF | CF)) | szxy(self.b) | NF
again = rep and self.b
if not again:
break
def state(self):
return (self.pc, self.a << 8 | self.f, self.bc, self.de, self.hl, self.ix, self.iy, self.sp)
def fmt(s):
return " ".join("%04x" % v for v in s)
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("image")
ap.add_argument("--input", help="console input file")
ap.add_argument("--trace", help="write a register trace here")
ap.add_argument("--max", type=int, default=10_000_000, help="instruction limit")
ap.add_argument("--rom-top", type=lambda s: int(s, 0), default=0)
a = ap.parse_args()
inp = open(a.input, "rb").read() if a.input else b""
cpu = Z80(open(a.image, "rb").read(), inp)
cpu.rom_top = a.rom_top
tr = open(a.trace, "w") if a.trace else None
n = 0
while not cpu.halted and n < a.max:
if tr: tr.write(fmt(cpu.state()) + "\n")
cpu.step()
n += 1
sys.stdout.write(cpu.out.decode("latin-1"))
if tr:
open(a.trace.replace("trace", "mem"), "w").write("".join("%02x\n" % v for v in cpu.m[32768:]))
print("\n[%d instructions%s]" % (n, ", halted" if cpu.halted else ""), file=sys.stderr)
if __name__ == "__main__":
main()