Basys 3 RISC-V computer

The Basys 3 Z-80 computer with the Z-80 replaced by an RV32IM processor
written from scratch (rtl/rv32_cpu.v): multi-cycle, 90 MHz, CSRs and
traps, interrupts, two hardware triggers and a resumable NMI for the
monitor. Passes riscv-tests rv32ui/um/mi.

rv32_system.v keeps all the Z-80 machine's peripherals, with I/O port N
at FFFFFF00h + N, 80 KB of RAM with BASIC preloaded, and a 32 KB monitor
ROM. BASIC, the five games and the monitor (with an RV32 disassembler,
assembler, breakpoints and single step) are ported to RISC-V GCC. Python
emulator and tests in tools/; full-system simulation in sim/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
brad ArantandClaude Opus 5.5 committed 2026-11-30 18:09:18 -08:00
commit 5930b958b4
103 files changed
+55677

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Binary image -> $readmemh file of 32-bit little-endian words.
bin2mem.py image.bin image.mem [words] (pads with zeros to `words`)
"""
import sys
data = open(sys.argv[1], 'rb').read()
data += b'\0' * (-len(data) % 4)
words = int(sys.argv[3]) if len(sys.argv) > 3 else len(data) // 4
if len(data) // 4 > words:
raise SystemExit("%s: %d bytes, more than %d words" % (sys.argv[1], len(data), words))
data += b'\0' * (words * 4 - len(data))
with open(sys.argv[2], 'w') as f:
for i in range(0, len(data), 4):
f.write('%08x\n' % int.from_bytes(data[i:i + 4], 'little'))
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""A model of the Basys 3 RISC-V computer's game hardware around
tools/rv32emu.py, for testing programs on the PC: the terminal (port 1), the
graphics layer with scrolling (30h-37h), the sprites (70h-78h) and the
held-key port (88h).
from boardemu import Board, load_ihx, load_font
mem, end = load_ihx("prog.ihx")
b = Board(mem, code_end=end) # runs from GAME_BASE, returns to address 0
b.run_frames(60, joy=FIRE)
b.shot("screen.png", load_font())
The frame counter (78h) moves on when the program comes back to read it after
doing some work (more than 100 instructions since it last moved), so a program
that waits for it to change runs one frame per wait, however long its frames
take, and two reads close together see the same frame. Screenshots need
pyte and Pillow, and are drawn the way the board's video combines the layers:
text over sprites over graphics.
"""
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from rv32emu import RV32 # noqa: E402
GAME_BASE = 0xA200 # where BASIC's loader programs put machine code
STACK_TOP = 0x13FF0
PAL = ["000", "A00", "0A0", "A50", "00A", "A0A", "0AA", "AAA",
"555", "F55", "5F5", "FF5", "55F", "F5F", "5FF", "FFF"]
PAL = [tuple(int(c, 16) * 17 for c in p) for p in PAL]
UP, DOWN, LEFT, RIGHT, FIRE, ENTER, ESC = 1, 2, 4, 8, 16, 32, 128
class Board(RV32):
def __init__(self, mem, code_end=0x14000, start=GAME_BASE, rom_top=0):
super().__init__(mem, rom_top=rom_top)
self.code_end = code_end
self.code_start = start
self.steps = 0 # instructions run
self.scroll_x = self.scroll_y = 0
self.border = False
self.pc, self.sp = start, STACK_TOP
self.x[1] = 0 # ra: the program returns to 0
self.frame = 0
self.frame_at = -1000
self.joy = 0
self.gfx = bytearray(320 * 240)
self.gxv = self.gyv = 0
self.spr = [[0, 0, 0, 0] for _ in range(32)] # x, y, shape, ctl
self.sel = 0
self.xst = 0
self.pat = bytearray(8192)
self.pat_a = 0
self.text = bytearray()
self.keys_in = bytearray()
def io_in(self, port):
p = port & 0xFF
if p == 0:
return (1 if self.keys_in else 0) | 2
if p == 1:
return self.keys_in.pop(0) if self.keys_in else 0
if p == 0x78:
if self.steps - self.frame_at > 100:
self.frame += 1
self.frame_at = self.steps
return self.frame & 0xFF
if p == 0x88:
return self.joy
if p == 0x33:
return self.gfx[self.gyv * 320 + self.gxv] if self.gxv < 320 and self.gyv < 240 else 0
if p == 0x34:
return 0
return 0xFF
def io_out(self, port, v):
p = port & 0xFF
if p == 1:
self.text.append(v)
elif p == 0x30: self.gxv = (self.gxv & 0x100) | v
elif p == 0x31: self.gxv = (self.gxv & 0xFF) | (v & 1) << 8
elif p == 0x32: self.gyv = v
elif p == 0x33:
if self.gxv < 320 and self.gyv < 240:
self.gfx[self.gyv * 320 + self.gxv] = v & 15
self.gxv = (self.gxv + 1) & 0x1FF
elif p == 0x34:
self.gfx[:] = bytes([v & 15]) * (320 * 240)
if not v & 0x80:
for s in self.spr: s[3] &= ~1
self.scroll_x = self.scroll_y = 0
self.border = False
elif p == 0x35: self.scroll_x = (self.scroll_x & 0x100) | v
elif p == 0x36:
self.scroll_x = (self.scroll_x & 0xFF) | (v & 1) << 8
self.border = bool(v & 2)
elif p == 0x37: self.scroll_y = v - 240 if v >= 240 else v
elif p == 0x70: self.sel = v & 31
elif p == 0x71: self.xst = (self.xst & 0x100) | v
elif p == 0x72: self.xst = (self.xst & 0xFF) | (v & 1) << 8
elif p == 0x73: self.spr[self.sel][0], self.spr[self.sel][1] = self.xst, v
elif p == 0x74: self.spr[self.sel][2] = v & 63
elif p == 0x75: self.spr[self.sel][3] = v & 7
elif p == 0x76: self.pat_a = (v & 63) * 128
elif p == 0x77:
self.pat[self.pat_a & 8191] = v
self.pat_a += 1
def run_frames(self, n, joy=0):
"""Run until the program has waited for n more frames (or returned)."""
self.joy = joy
end = self.frame + n
while self.frame < end and self.pc != 0:
self.step()
self.steps += 1
if not (self.code_start <= self.pc < self.code_end or self.pc == 0):
raise SystemExit("PC left the program: %05X" % self.pc)
if self.sp < STACK_TOP - 0x1000:
raise SystemExit("stack ran into memory: SP %05X" % self.sp)
def screen_text(self):
import pyte
scr = pyte.Screen(80, 32)
pyte.ByteStream(scr).feed(bytes(self.text))
return scr
def shot(self, path, font):
from PIL import Image
scr = self.screen_text()
img = Image.new("RGB", (1280, 1024))
px = img.load()
lay = bytearray(320 * 240) # the graphics as scrolled onto the screen
for y in range(240):
fy = (y + self.scroll_y) % 240
row = self.gfx[fy * 320:(fy + 1) * 320]
sx = self.scroll_x % 320
lay[y * 320:(y + 1) * 320] = row[sx:] + row[:sx]
if self.border: # hidden: 4 columns each side, 2 rows top and bottom
if y < 2 or y >= 238:
lay[y * 320:(y + 1) * 320] = bytes(320)
else:
lay[y * 320:y * 320 + 4] = bytes(4)
lay[y * 320 + 316:(y + 1) * 320] = bytes(4)
for s in reversed(self.spr): # sprite 0 in front
x0, y0, shape, ctl = s
if not ctl & 1:
continue
for r in range(16):
for c in range(16):
rr = 15 - r if ctl & 4 else r
cc = 15 - c if ctl & 2 else c
b = self.pat[shape * 128 + rr * 8 + cc // 2]
col = b & 15 if cc & 1 else b >> 4
x, y = (x0 + c) & 511, (y0 + r) & 255
if col and x < 320 and y < 240:
lay[y * 320 + x] = col | 16
for y in range(1024):
for x in range(1280):
gx, gy = x >> 2, y >> 2
c = lay[gy * 320 + gx] & 15 if gy < 240 else 0
px[x, y] = PAL[c]
names = ["black", "red", "green", "brown", "blue", "magenta", "cyan", "white"]
for r in range(32):
for c in range(80):
ch = scr.buffer[r][c]
code = ord(ch.data[0]) if ch.data else 32
if code == 32 and ch.bg == "default":
continue
def colour(n, d):
if n in names: return PAL[names.index(n)]
if n.startswith("bright") and n[6:] in names: return PAL[names.index(n[6:]) + 8]
try:
v = int(n, 16); return ((v >> 16) & 255, (v >> 8) & 255, v & 255)
except ValueError:
return d
fg = colour(ch.fg, PAL[10])
bg = colour(ch.bg, None)
for y in range(16):
bits = font[(code if code < 256 else 63) * 16 + y]
for x in range(8):
on = bits & (0x80 >> x)
for dy in (0, 1):
for dx in (0, 1):
X, Y = c * 16 + 2 * x + dx, r * 32 + 2 * y + dy
if on: px[X, Y] = fg
elif bg is not None and px[X, Y] == (0, 0, 0): px[X, Y] = bg
img.save(path)
def load_ihx(path):
"""Memory image and the end of the loaded bytes (Intel HEX with type 04
extended linear addresses, as objcopy writes it)."""
mem = bytearray(0x28000)
hi = 0
base = 0
for line in open(path):
if not line.startswith(":"):
continue
n, a, t = int(line[1:3], 16), int(line[3:7], 16), int(line[7:9], 16)
if t == 0:
mem[base + a:base + a + n] = bytes.fromhex(line[9:9 + 2 * n])
hi = max(hi, base + a + n)
elif t == 4:
base = int(line[9:13], 16) << 16
return mem, hi
def load_syms(path):
"""Symbol addresses from `nm` output."""
sym = {}
for line in open(path):
f = line.split()
if len(f) == 3:
sym[f[2]] = int(f[0], 16)
return sym
def load_font():
root = os.path.join(HERE, "..")
return [int(l.split("//")[0], 16) for l in open(os.path.join(root, "font", "font.mem"))
if l.split("//")[0].strip()]
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Copy the program in the Basys 3 RISC-V computer's memory to a file on the PC, or send
BASIC a command and print what it answers.
The board needs SW15 and SW14 up (computer mode, PC serial linked: the computer's
output is then copied to the PC), and nothing else may be using the port
(stop the getty first). The baud rate must match SW1:0. BASIC's clock is set
to the PC's first (unless --no-date), so files saved get today's date.
tools/get-bas.py myprog.bas --baud 9600 # LIST into myprog.bas
tools/get-bas.py --cmd 'LOAD "DEMO"' --baud 9600 # run a command, show output
"""
import argparse
import os
import re
import select
import termios
import time
BAUDS = {9600: termios.B9600, 115200: termios.B115200, 921600: termios.B921600,
3000000: termios.B3000000}
ap = argparse.ArgumentParser()
ap.add_argument("file", nargs="?", help="where to write the listing")
ap.add_argument("--cmd", action="append", help="send this command instead (repeatable)")
ap.add_argument("--port", default="/dev/ttyUSB1")
ap.add_argument("--baud", type=int, default=115200, choices=sorted(BAUDS))
ap.add_argument("--timeout", type=float, default=30, help="seconds to wait for READY")
ap.add_argument("--no-date", action="store_true", help="don't set BASIC's clock")
a = ap.parse_args()
if not a.file and not a.cmd:
ap.error("give a file name or --cmd")
fd = os.open(a.port, os.O_RDWR | os.O_NOCTTY)
t = termios.tcgetattr(fd)
t[0] = termios.IXON
t[1] = 0
t[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
t[3] = 0
t[4] = t[5] = BAUDS[a.baud]
t[6][termios.VMIN] = 0
t[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, t)
termios.tcflush(fd, termios.TCIFLUSH)
def run(cmd):
"""Send one line; return everything BASIC prints up to its next READY."""
os.write(fd, cmd.encode("ascii") + b"\r")
buf = b""
end = time.time() + a.timeout
while time.time() < end:
r, _, _ = select.select([fd], [], [], 0.2)
if r:
buf += os.read(fd, 4096)
if re.search(rb"\r\nREADY\r\n$", buf):
break
text = buf.decode("latin-1").replace("\r", "")
lines = text.split("\n")
if lines and lines[0].strip() == cmd.strip(): # BASIC echoes the command
lines = lines[1:]
return "\n".join(l for l in lines if l != "READY").strip("\n")
if not a.no_date:
run(time.strftime('DATE "%Y-%m-%d %H:%M:%S"'))
if a.cmd:
for c in a.cmd:
print(run(c))
else:
out = run("LIST")
prog = [l for l in out.split("\n") if re.match(r"\d+ ", l)]
with open(a.file, "w") as f:
f.write("\n".join(prog) + "\n")
print("%d lines written to %s" % (len(prog), a.file))
os.close(fd)
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""Convert a Linux console PSF font (8x16) into a CP437-ordered font ROM.
Output is a $readmemh file with 4096 lines: byte (code*16 + row), MSB = leftmost pixel.
usage: psf2mem.py [font.psf.gz[,fallback.psf.gz...]] [out.mem] [preview.png]
Glyphs missing from the first font are taken from the fallbacks in order.
"""
import gzip
import struct
import sys
CP437_LOW = ("\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼")
DEFAULT_FONTS = ",".join("/usr/share/consolefonts/%s.psf.gz" % f for f in
("Uni2-VGA16", "FullGreek-VGA16", "Vietnamese-TerminusBoldVGA16"))
# Fonts often carry the triangle pointers under their newer code points.
CP437_ALT = {"►": "▶", "◄": "◀"}
def cp437(code):
if code < 0x20:
return CP437_LOW[code]
if code == 0x7F:
return "⌂"
return bytes([code]).decode("cp437")
def load_psf(path):
raw = gzip.open(path).read() if path.endswith(".gz") else open(path, "rb").read()
if raw[:2] == b"\x36\x04":
mode, charsize = raw[2], raw[3]
count = 512 if mode & 1 else 256
width, height, hdr = 8, charsize, 4
has_table = bool(mode & 6)
glyphs = [raw[hdr + i * charsize: hdr + (i + 1) * charsize] for i in range(count)]
table = {}
if has_table:
pos, g = hdr + count * charsize, 0
while g < count and pos + 1 < len(raw):
(u,) = struct.unpack_from("<H", raw, pos)
pos += 2
if u == 0xFFFF:
g += 1
elif u != 0xFFFE:
table.setdefault(chr(u), g)
return glyphs, table, width, height
if raw[:4] == b"\x72\xb5\x4a\x86":
_, hdr, flags, count, charsize, height, width = struct.unpack_from("<7I", raw, 4)
glyphs = [raw[hdr + i * charsize: hdr + (i + 1) * charsize] for i in range(count)]
table = {}
if flags & 1:
data = raw[hdr + count * charsize:]
for g, entry in enumerate(data.split(b"\xff")[:count]):
for seq in entry.split(b"\xfe")[:1]:
for ch in seq.decode("utf-8", "ignore"):
table.setdefault(ch, g)
return glyphs, table, width, height
raise SystemExit("not a PSF font: " + path)
def main():
src = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] else DEFAULT_FONTS
out = sys.argv[2] if len(sys.argv) > 2 else "font.mem"
fonts = []
for path in src.split(","):
glyphs, table, width, height = load_psf(path)
if width != 8 or height != 16:
raise SystemExit(f"{path}: need an 8x16 font, got {width}x{height}")
fonts.append((glyphs, table))
missing = []
rom = []
for code in range(256):
ch = cp437(code)
glyph = None
if code not in (0, 0x20):
for glyphs, table in fonts:
g = table.get(ch, code if not table else None)
if g is None and ch in CP437_ALT:
g = table.get(CP437_ALT[ch])
if g is not None:
glyph = glyphs[g][:16]
break
if glyph is None:
missing.append(f"{code:02X}")
rom.extend(glyph or [0] * 16)
with open(out, "w") as f:
f.write("// CP437 order, 256 glyphs x 16 rows, from: %s\n"
% ", ".join(p.split("/")[-1] for p in src.split(",")))
for b in rom:
f.write(f"{b:02x}\n")
print(f"wrote {out}; glyphs missing: {' '.join(missing) or 'none'}")
if len(sys.argv) > 3:
from PIL import Image
img = Image.new("1", (32 * 9, 8 * 17), 0)
for code in range(256):
ox, oy = (code % 32) * 9, (code // 32) * 17
for r in range(16):
for c in range(8):
if rom[code * 16 + r] & (0x80 >> c):
img.putpixel((ox + c, oy + r), 1)
img.save(sys.argv[3])
if __name__ == "__main__":
main()
+497
View File
@@ -0,0 +1,497 @@
#!/usr/bin/env python3
"""RV32IM emulator of the Basys 3 RISC-V computer, for testing programs on the
PC and as a reference for rtl/rv32_cpu.v.
The same machine as rtl/rv32_cpu.v and rtl/rv32_system.v: RV32IM, machine
mode, the CSRs the core has (no triggers), the resumable NMI, 80 KB of RAM
(writes below rom_top ignored), the monitor's 32 KB ROM at 20000h and 8 KB of
RAM at 28000h, the I/O ports at FFFFFF00h + N (io_in / io_out, to be
overridden) and the 32-bit registers at FFFFFE00h + N.
python3 tools/rv32emu.py image.bin [--input FILE] [--max N] [--trace FILE]
runs a raw image from address 0 with the console on ports 0/1: text from
--input is typed, output goes to stdout. --trace writes "pc instruction" for
each instruction run. The emulator also counts the clocks rv32_cpu would take
(cycles; see cost()).
"""
import sys
M32 = 0xFFFFFFFF
RAM_END = 0x14000
MON_BASE, MON_RAM, MON_END = 0x20000, 0x28000, 0x2A000
MEM_SIZE = MON_END
class Trap(Exception):
def __init__(self, cause, tval=0):
self.cause, self.tval = cause, tval
def sx(v, bits):
v &= (1 << bits) - 1
return v - (1 << bits) if v >> (bits - 1) else v
def s32(v):
return v - (1 << 32) if v & 0x80000000 else v
class RV32:
def __init__(self, mem=b"", rom_top=0, inp=b"", out=None):
self.m = bytearray(MEM_SIZE)
self.m[:len(mem)] = mem
self.rom_top = rom_top # writes below are ignored
self.x = [0] * 32
self.pc = 0
self.cache = {}
self.csr = {0x300: 0, 0x304: 0, 0x305: 0, 0x340: 0, 0x341: 0, 0x342: 0, 0x343: 0,
0x740: 0, 0x741: 0, 0x742: 0}
self.nmie = True
self.count = 0 # instructions completed
self.cycles = 0 # clocks rv32_cpu would take (see cost())
self.inp = bytearray(inp)
self.out = out if out is not None else bytearray()
self.step_arm = False # nmi after the next instruction (port 60)
self.stepped = False
self.nmi_pending = False
self.why = 0
self.bp = [0, 0]
self.bp_on = 0
@property
def sp(self):
return self.x[2]
@sp.setter
def sp(self, v):
self.x[2] = v & M32
# ---------------------------------------------------------------- memory
def rd8(self, a):
if a < MEM_SIZE:
return self.m[a]
if a >= 0xFFFFFF00:
return self.io_in(a & 0xFF) & 0xFF
if a >= 0xFFFFFE00:
return self.word_in(a & 0xFC) >> (8 * (a & 3)) & 0xFF
return 0
def rd16(self, a):
if a < MEM_SIZE - 1:
return self.m[a] | self.m[a + 1] << 8
return self.rd8(a) | self.rd8(a + 1) << 8
def rd32(self, a):
if a < MEM_SIZE - 3:
return int.from_bytes(self.m[a:a + 4], "little")
if a >= 0xFFFFFF00:
return self.io_in(a & 0xFF) & 0xFF
if a >= 0xFFFFFE00:
return self.word_in(a & 0xFC) & M32
return 0
def writable(self, a):
return self.rom_top <= a < RAM_END or MON_RAM <= a < MON_END
def wr8(self, a, v):
if a < MEM_SIZE:
if self.writable(a):
self.m[a] = v & 0xFF
if a & ~3 in self.cache:
del self.cache[a & ~3]
elif a >= 0xFFFFFF00:
self.port_out(a & 0xFF, v & 0xFF)
elif a >= 0xFFFFFE00 and not a & 3:
self.word_out(a & 0xFC, v & 0xFF)
def wr16(self, a, v):
self.wr8(a, v)
self.wr8(a + 1, v >> 8)
def wr32(self, a, v):
if a >= 0xFFFFFF00:
self.port_out(a & 0xFF, v & 0xFF)
elif a >= 0xFFFFFE00:
self.word_out(a & 0xFC, v & M32)
else:
for i in range(4):
self.wr8(a + i, v >> 8 * i)
# -------------------------------------------------------------- devices
def io_in(self, port):
"""A port read; override. The console is ports 0 and 1."""
if port == 0:
return (1 if self.inp else 0) | 2
if port == 1:
return self.inp.pop(0) if self.inp else 0
if port == 0x60:
return self.why
if port == 0x34:
return 0 # graphics fill: done at once
return 0xFF
def io_out(self, port, v):
"""A port write; override."""
if port == 1:
self.out.append(v)
def port_out(self, port, v):
if port == 0x60:
self.step_arm = bool(v & 2)
elif port == 0x61:
if not self.nmi_pending and not self.in_monitor():
self.nmi_pending, self.why_r = True, 2
elif port == 0x67:
self.bp_on = v & 3
self.io_out(port, v)
def millis(self):
return self.count // 30000 # about 30 instructions a microsecond
def word_in(self, a):
if a == 0x00:
return self.millis() & M32
if a == 0x04:
return (self.count // 30) & M32
if a == 0x10:
return self.bp[0]
if a == 0x14:
return self.bp[1]
return 0
def word_out(self, a, v):
if a == 0x10:
self.bp[0] = v
elif a == 0x14:
self.bp[1] = v
def in_monitor(self):
return MON_BASE <= self.pc < MON_RAM
# ------------------------------------------------------------------ CSRs
def csr_read(self, n):
if n == 0x300:
return self.csr[0x300] | 0x1800
if n == 0x301:
return 0x40001100
if n == 0x344:
return 0
if n == 0x744:
return 0x1800 | (8 if self.nmie else 0)
if n in (0xB00, 0xC00, 0xC01, 0xB02, 0xC02):
return self.count & M32
if n in (0xB80, 0xC80, 0xC81, 0xB82, 0xC82):
return self.count >> 32 & M32
if n in (0xF11, 0xF12, 0xF13, 0xF14, 0xF15, 0x310, 0x7A0, 0x7A1, 0x7A2):
return 0 # (no triggers: tselect stays 0, tdata1 type 0)
if n in self.csr:
return self.csr[n]
raise Trap(2)
def csr_write(self, n, v):
if n >> 10 == 3:
raise Trap(2)
if n == 0x300:
self.csr[0x300] = v & 0x88
elif n == 0x304:
self.csr[0x304] = v & 0xFFFF0888
elif n in (0x305, 0x341, 0x741):
self.csr[n] = v & ~3 & M32
elif n == 0x744:
self.nmie = bool(v & 8)
elif n in self.csr:
self.csr[n] = v & M32
elif n in (0x301, 0x344, 0x310, 0x7A0, 0x7A1, 0x7A2):
pass
elif n in (0xB00, 0xB02): # the count after this instruction is v
self.count = (self.count & ~M32 | v) - 1
elif n in (0xB80, 0xB82):
self.count = (self.count & M32 | v << 32) - 1
else:
raise Trap(2)
# --------------------------------------------------------------- decode
def decode(self, pc):
ins = self.rd32(pc)
opc, rd, f3 = ins & 0x7F, ins >> 7 & 31, ins >> 12 & 7
rs1, rs2, f7 = ins >> 15 & 31, ins >> 20 & 31, ins >> 25
x = self.x
nxt = (pc + 4) & M32
immi = sx(ins >> 20, 12)
ill = Trap(2, ins)
def illegal():
raise ill
if opc == 0x37 or opc == 0x17: # lui, auipc
v = (ins & 0xFFFFF000) + (pc if opc == 0x17 else 0) & M32
if rd == 0:
return lambda: nxt
def f():
x[rd] = v
return nxt
return f
if opc == 0x6F: # jal
t = (pc + sx((ins >> 31) << 20 | (ins >> 12 & 0xFF) << 12 | (ins >> 20 & 1) << 11 |
(ins >> 21 & 0x3FF) << 1, 21)) & M32
def f():
if t & 3:
raise Trap(0, t)
if rd:
x[rd] = nxt
return t
return f
if opc == 0x67 and f3 == 0: # jalr
def f():
t = (x[rs1] + immi) & 0xFFFFFFFE
if t & 3:
raise Trap(0, t)
if rd:
x[rd] = nxt
return t
return f
if opc == 0x63 and f3 not in (2, 3): # branches
t = (pc + sx((ins >> 31) << 12 | (ins >> 7 & 1) << 11 | (ins >> 25 & 0x3F) << 5 |
(ins >> 8 & 15) << 1, 13)) & M32
cmp = [lambda a, b: a == b, lambda a, b: a != b, None, None,
lambda a, b: s32(a) < s32(b), lambda a, b: s32(a) >= s32(b),
lambda a, b: a < b, lambda a, b: a >= b][f3]
def f():
if cmp(x[rs1], x[rs2]):
if t & 3:
raise Trap(0, t)
return t
return nxt
return f
if opc == 0x03 and f3 in (0, 1, 2, 4, 5): # loads
def f():
a = (x[rs1] + immi) & M32
if f3 == 2:
if a & 3:
raise Trap(4, a)
v = self.rd32(a)
elif f3 & 3 == 1:
if a & 1:
raise Trap(4, a)
v = self.rd16(a)
if f3 == 1 and v & 0x8000:
v |= 0xFFFF0000
else:
v = self.rd8(a)
if f3 == 0 and v & 0x80:
v |= 0xFFFFFF00
if rd:
x[rd] = v
return nxt
return f
if opc == 0x23 and f3 in (0, 1, 2): # stores
imms = sx((ins >> 25) << 5 | (ins >> 7 & 31), 12)
def f():
a = (x[rs1] + imms) & M32
v = x[rs2]
if f3 == 2:
if a & 3:
raise Trap(6, a)
self.wr32(a, v)
elif f3 == 1:
if a & 1:
raise Trap(6, a)
if a >= 0xFFFFFE00:
self.wr32(a, v & 0xFFFF)
else:
self.wr16(a, v)
else:
self.wr8(a, v)
return nxt
return f
if opc == 0x13: # op-imm
sh = rs2
if (f3 == 1 and f7 != 0) or (f3 == 5 and f7 not in (0, 0x20)):
return illegal
ops = {
0: lambda a: (a + immi) & M32,
2: lambda a: int(s32(a) < immi),
3: lambda a: int(a < (immi & M32)),
4: lambda a: (a ^ immi) & M32,
6: lambda a: (a | immi) & M32,
7: lambda a: (a & immi) & M32,
1: lambda a: (a << sh) & M32,
5: (lambda a: (s32(a) >> sh) & M32) if f7 else (lambda a: a >> sh),
}
op = ops[f3]
if rd == 0:
return lambda: nxt
def f():
x[rd] = op(x[rs1])
return nxt
return f
if opc == 0x33 and f7 in (0, 0x20, 1): # op, mul/div
if f7 == 1:
op = [
lambda a, b: (a * b) & M32,
lambda a, b: (s32(a) * s32(b)) >> 32 & M32,
lambda a, b: (s32(a) * b) >> 32 & M32,
lambda a, b: (a * b) >> 32,
lambda a, b: M32 if b == 0 else (a if (a == 0x80000000 and b == M32) else
int(s32(a) / s32(b)) & M32),
lambda a, b: M32 if b == 0 else a // b,
lambda a, b: a if b == 0 else (0 if (a == 0x80000000 and b == M32) else
(s32(a) - int(s32(a) / s32(b)) * s32(b)) & M32),
lambda a, b: a if b == 0 else a % b,
][f3]
else:
if f7 == 0x20 and f3 not in (0, 5):
return illegal
op = {
(0, 0): lambda a, b: (a + b) & M32,
(0, 0x20): lambda a, b: (a - b) & M32,
(1, 0): lambda a, b: (a << (b & 31)) & M32,
(2, 0): lambda a, b: int(s32(a) < s32(b)),
(3, 0): lambda a, b: int(a < b),
(4, 0): lambda a, b: a ^ b,
(5, 0): lambda a, b: a >> (b & 31),
(5, 0x20): lambda a, b: (s32(a) >> (b & 31)) & M32,
(6, 0): lambda a, b: a | b,
(7, 0): lambda a, b: a & b,
}[(f3, f7)]
if rd == 0:
return lambda: nxt
def f():
x[rd] = op(x[rs1], x[rs2])
return nxt
return f
if opc == 0x0F and f3 in (0, 1): # fence, fence.i
return lambda: nxt
if opc == 0x73:
if ins == 0x00000073:
def f():
raise Trap(11)
return f
if ins == 0x00100073:
def f():
raise Trap(3, pc)
return f
if ins == 0x30200073: # mret
def f():
st = self.csr[0x300]
self.csr[0x300] = (st & ~8) | (8 if st & 0x80 else 0) | 0x80
return self.csr[0x341]
return f
if ins == 0x70200073: # mnret
def f():
self.nmie = True
return self.csr[0x741]
return f
if ins == 0x10500073: # wfi
return lambda: nxt
if f3 in (1, 2, 3, 5, 6, 7):
n = ins >> 20
uimm = rs1
def f():
src = uimm if f3 & 4 else x[rs1]
write = f3 & 3 == 1 or rs1 != 0
old = self.csr_read(n)
if write:
v = src if f3 & 3 == 1 else (old | src if f3 & 3 == 2 else old & ~src)
self.csr_write(n, v & M32)
if rd:
x[rd] = old
return nxt
return f
return illegal
# ------------------------------------------------------------------ run
def trap(self, cause, tval):
self.csr[0x341] = self.pc
self.csr[0x342] = cause
self.csr[0x343] = tval & M32
st = self.csr[0x300]
self.csr[0x300] = (st & ~0x88) | (0x80 if st & 8 else 0)
self.pc = self.csr[0x305]
def enter_nmi(self):
self.csr[0x741] = self.pc
self.csr[0x742] = 0x80000000
self.nmie = False
self.stepped = False
self.pc = MON_BASE
def step(self):
"""One instruction (or the NMI before it)."""
if self.nmie:
hit = self.bp_on & 1 and self.pc == self.bp[0] and 4 or \
self.bp_on & 2 and self.pc == self.bp[1] and 5
if self.nmi_pending or hit or (self.step_arm and self.stepped):
self.why = self.why_r if self.nmi_pending else hit or 3
self.nmi_pending = self.step_arm = False
self.enter_nmi()
return
f = self.cache.get(self.pc)
if f is None:
f = self.cache[self.pc] = self.decode(self.pc)
pc = self.pc
try:
self.pc = f()
except Trap as t:
self.trap(t.cause, t.tval)
self.cycles += 3
return
self.count += 1
self.cycles += self.cost(pc)
if self.nmie:
self.stepped = True
def cost(self, pc):
"""Clocks rv32_cpu takes for the instruction at pc, just run: 2, or 3
for a load, store, jump or taken branch (4 for I/O), 4 for a multiply,
35 for a divide."""
ins = self.rd32(pc)
op = ins & 0x7F
if op in (0x03, 0x23):
a = (self.x[ins >> 15 & 31] + sx(ins >> 20 if op == 3 else (ins >> 25) << 5 | (ins >> 7 & 31), 12)) & M32
return 4 if a >= 0xFFFFFE00 or MON_RAM <= a < MON_END else 3
if op in (0x6F, 0x67) or (op == 0x63 and self.pc != (pc + 4) & M32):
return 3
if op == 0x33 and ins >> 25 == 1:
return 35 if ins >> 14 & 1 else 4
if op == 0x0F and ins >> 12 & 7 == 1:
return 3
return 2
def nmi(self, why=1):
"""The Pause key."""
if not self.nmi_pending and not self.in_monitor():
self.nmi_pending, self.why_r = True, why
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("image")
ap.add_argument("--input", default=None)
ap.add_argument("--max", type=int, default=10_000_000)
ap.add_argument("--trace", default=None)
a = ap.parse_args()
inp = open(a.input, "rb").read() if a.input else b""
cpu = RV32(open(a.image, "rb").read(), inp=inp)
tr = open(a.trace, "w") if a.trace else None
for _ in range(a.max):
if tr:
tr.write("%08x %08x\n" % (cpu.pc, cpu.rd32(cpu.pc)))
cpu.step()
if cpu.out:
sys.stdout.buffer.write(bytes(cpu.out))
cpu.out.clear()
sys.stdout.flush()
if __name__ == "__main__":
main()
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Type a BASIC program into the Basys 3 RISC-V computer over the serial port.
The board needs SW15 and SW14 up (computer mode, PC serial linked), and nothing
else may be using the port (stop the getty first). The baud rate must match
SW1:0. Sets BASIC's clock to the PC's (unless --no-date), sends NEW unless
--keep is given, then the program, then RUN if --run is given.
tools/send-bas.py basic/examples/graphics-demo.bas --baud 9600 --run
"""
import argparse
import os
import select
import termios
import time
BAUDS = {9600: termios.B9600, 115200: termios.B115200, 921600: termios.B921600,
3000000: termios.B3000000}
ap = argparse.ArgumentParser()
ap.add_argument("file")
ap.add_argument("--port", default="/dev/ttyUSB1")
ap.add_argument("--baud", type=int, default=115200, choices=sorted(BAUDS))
ap.add_argument("--keep", action="store_true", help="don't send NEW first")
ap.add_argument("--run", action="store_true", help="send RUN at the end")
ap.add_argument("--no-date", action="store_true", help="don't set BASIC's clock")
a = ap.parse_args()
fd = os.open(a.port, os.O_RDWR | os.O_NOCTTY)
t = termios.tcgetattr(fd)
t[0] = termios.IXON # honour XON/XOFF
t[1] = 0
t[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
t[3] = 0
t[4] = t[5] = BAUDS[a.baud]
termios.tcsetattr(fd, termios.TCSANOW, t)
lines = [l.rstrip() for l in open(a.file) if l.strip()]
if not a.keep:
lines.insert(0, "NEW")
if a.run:
lines.append("RUN")
if not a.no_date:
lines.insert(0, time.strftime('DATE "%Y-%m-%d %H:%M:%S"'))
t[6][termios.VMIN] = 0 # reads don't wait
t[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, t)
for n, line in enumerate(lines, 1):
os.write(fd, line.encode("ascii") + b"\r")
termios.tcdrain(fd)
time.sleep(0.02) # let BASIC store the line
# Read BASIC's echo (copied back when SW14 is up). Left unread, it fills the
# PC's input buffer; Linux then stops reading the port, misses the board's
# XON and never sends again.
while select.select([fd], [], [], 0)[0] and os.read(fd, 4096):
pass
print("\r%d/%d lines" % (n, len(lines)), end="", flush=True)
print()
os.close(fd)
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""Load an Intel HEX file (as objcopy -O ihex writes it) into the Basys 3 RISC-V
computer's memory through the monitor, and optionally save it as a memory
file in flash.
The board needs SW15 and SW14 up and BASIC at READY; nothing else may be
using the serial port, and the baud rate must match SW1:0. The tool types
MONITOR, sends every record (the monitor writes each one into memory),
saves the loaded range if asked, and leaves the monitor again.
tools/send-hex.py games/keep/keep.ihx --save KEEPGAME --baud 3000000
Code must go at 0A000h or above. Memory files are loaded back with BLOAD in
BASIC or LOAD in the monitor.
"""
import argparse
import os
import re
import select
import termios
import time
BAUDS = {9600: termios.B9600, 115200: termios.B115200, 921600: termios.B921600,
3000000: termios.B3000000}
ap = argparse.ArgumentParser()
ap.add_argument("file", help="Intel HEX file")
ap.add_argument("--save", metavar="NAME", help="save the loaded bytes in flash under this name")
ap.add_argument("--port", default="/dev/ttyUSB1")
ap.add_argument("--baud", type=int, default=115200, choices=sorted(BAUDS))
ap.add_argument("--no-date", action="store_true", help="don't set BASIC's clock (which dates the file)")
a = ap.parse_args()
records = [l.strip() for l in open(a.file) if l.startswith(":")]
if not records or not records[-1].upper().startswith(":00000001"):
records.append(":00000001FF")
for r in records:
if len(r) > 79:
raise SystemExit("record too long for the monitor (79 characters): " + r[:20])
if a.save and not re.fullmatch(r"[A-Za-z][A-Za-z0-9]{0,7}", a.save):
raise SystemExit("a file name is 1-8 letters and digits, starting with a letter")
fd = os.open(a.port, os.O_RDWR | os.O_NOCTTY)
t = termios.tcgetattr(fd)
t[0] = termios.IXON
t[1] = 0
t[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
t[3] = 0
t[4] = t[5] = BAUDS[a.baud]
t[6][termios.VMIN] = 0
t[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, t)
termios.tcflush(fd, termios.TCIFLUSH)
buf = b""
def send(s):
os.write(fd, s.encode("ascii"))
def wait_for(pattern, timeout=10.0):
"""Read until the output since the last call matches; return it."""
global buf
end = time.time() + timeout
while time.time() < end:
m = re.search(pattern, buf, re.S)
if m:
out, buf = buf[:m.end()], buf[m.end():]
return out
r, _, _ = select.select([fd], [], [], 0.05)
if r:
buf += os.read(fd, 65536)
raise SystemExit("no answer from the board (waiting for %r); last output: %r" % (pattern, buf[-200:]))
# the monitor's command line, redrawn after each command; its message comes
# after the prompt, and the cursor is turned back on last
PROMPT = rb"\x1b\[30;1H> .*?\x1b\[\?25h"
send("\r")
time.sleep(0.3)
if not a.no_date: # the file gets the PC's date
send(time.strftime('DATE "%Y-%m-%d %H:%M:%S"\r'))
wait_for(rb"READY\r\n")
send("MONITOR\r")
wait_for(rb"RISC-V MONITOR")
wait_for(PROMPT)
n = 0
for r in records:
send(r.upper() + "\r")
out = wait_for(PROMPT)
if re.search(rb"BAD HEX|CHECKSUM|ROM: NOT|NO HEX", out):
send("X\r")
raise SystemExit("the monitor refused record %d: %s" % (n + 1, r))
n += 1
if n % 50 == 0:
print("\r%d/%d records" % (n, len(records)), end="", flush=True)
m = re.search(rb"HEX LOADED ([0-9A-F]{5})-([0-9A-F]{5})", out)
if not m:
send("X\r")
raise SystemExit("the monitor did not report the loaded range")
lo, hi = m.group(1).decode(), m.group(2).decode()
print("\rloaded %s-%s (%d bytes) from %d records" % (lo, hi, int(hi, 16) - int(lo, 16) + 1, len(records)))
if a.save:
send('SAVE "%s" %s %s\r' % (a.save.upper(), lo, hi))
out = wait_for(PROMPT, 30)
if b"SAVED" not in out:
send("X\r")
raise SystemExit("saving failed: %r" % out[-120:])
print('saved as "%s"; BLOAD "%s" in BASIC loads it at %sh' % (a.save.upper(), a.save.upper(), lo))
send("X\r")
wait_for(rb"\x1b\[\?47l", 5) # the monitor's screen goes away
os.close(fd)