vibed jtagram with script as drop in replacement of serving_ram

This commit is contained in:
2026-02-22 21:27:40 +01:00
parent 20cfece6e3
commit 9322766cef
5 changed files with 471 additions and 0 deletions

196
scripts/jtag_write_ram.py Executable file
View File

@@ -0,0 +1,196 @@
#!/usr/bin/env python3
"""Write a file into serving_ram_jtag over Spartan-6 USER JTAG via OpenOCD.
This script targets the protocol implemented by rtl/serv/serving_ram_jtag_bridge.v:
frame bit[0] = write_enable
frame bit[32:1] = 32-bit address
frame bit[40:33] = data byte
Notes:
- Frame is shifted LSB-first (OpenOCD drscan integer value format matches this).
- USER1/USER2 opcode selection is Spartan-6 specific (IR opcodes 0x02/0x03, IR length 6).
"""
from __future__ import annotations
import argparse
import pathlib
import re
import subprocess
import sys
import tempfile
from typing import Dict, List, Tuple
JTAG_ADDR_W = 32
JTAG_FRAME_W = 1 + JTAG_ADDR_W + 8
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Write file to serving RAM over JTAG")
p.add_argument("input", help="Input file (.bin or readmemh-style .hex/.mem)")
p.add_argument(
"--ram-addr-width",
"--addr-width",
dest="ram_addr_width",
type=int,
default=8,
help="RAM address width (aw) in HDL, default: 8",
)
p.add_argument("--base-addr", type=lambda x: int(x, 0), default=0, help="Base address for .bin input")
p.add_argument("--tap", default="xc6s.tap", help="OpenOCD tap name (default: xc6s.tap)")
p.add_argument(
"--user-chain",
type=int,
choices=[1, 2],
default=1,
help="BSCAN user chain used in HDL (default: 1)",
)
p.add_argument("--openocd-cfg", action="append", default=[], help="OpenOCD -f config file (repeatable)")
p.add_argument("--openocd-cmd", action="append", default=[], help="Extra OpenOCD -c command before programming")
p.add_argument("--limit", type=int, default=None, help="Write only first N bytes")
p.add_argument("--dry-run", action="store_true", help="Generate and print TCL only")
return p.parse_args()
def _strip_line_comments(line: str) -> str:
return line.split("//", 1)[0]
def parse_readmemh_text(path: pathlib.Path) -> Dict[int, int]:
"""Parse a simple readmemh-style file with optional @address directives."""
text = path.read_text(encoding="utf-8")
words: Dict[int, int] = {}
addr = 0
for raw_line in text.splitlines():
line = _strip_line_comments(raw_line).strip()
if not line:
continue
for tok in line.split():
tok = tok.strip()
if not tok:
continue
if tok.startswith("@"):
addr = int(tok[1:], 16)
continue
if not re.fullmatch(r"[0-9a-fA-F]+", tok):
raise ValueError(f"Unsupported token '{tok}' in {path}")
val = int(tok, 16)
if val < 0 or val > 0xFF:
raise ValueError(f"Byte value out of range at address 0x{addr:x}: {tok}")
words[addr] = val
addr += 1
return words
def load_image(path: pathlib.Path, base_addr: int) -> List[Tuple[int, int]]:
suffix = path.suffix.lower()
if suffix == ".bin":
blob = path.read_bytes()
return [(base_addr + i, b) for i, b in enumerate(blob)]
if suffix in {".hex", ".mem", ".vmem"}:
words = parse_readmemh_text(path)
return sorted(words.items())
raise ValueError("Unsupported input format. Use .bin, .hex, .mem, or .vmem")
def build_write_frame(addr: int, data: int) -> int:
return (data << (JTAG_ADDR_W + 1)) | ((addr & ((1 << JTAG_ADDR_W) - 1)) << 1) | 0x1
def build_openocd_tcl(entries: List[Tuple[int, int]], tap: str, user_chain: int, pre_cmds: List[str]) -> str:
ir_opcode = 0x02 if user_chain == 1 else 0x03
lines: List[str] = []
lines.append("init")
for cmd in pre_cmds:
lines.append(cmd)
lines.append(f"irscan {tap} 0x{ir_opcode:x} -endstate IDLE")
for addr, data in entries:
frame = build_write_frame(addr, data)
lines.append(f"drscan {tap} {JTAG_FRAME_W} 0x{frame:x} -endstate IDLE")
lines.append("shutdown")
lines.append("")
return "\n".join(lines)
def run_openocd(cfg_files: List[str], script_path: pathlib.Path) -> int:
cmd = ["openocd"]
for cfg in cfg_files:
cmd += ["-f", cfg]
cmd += ["-f", str(script_path)]
proc = subprocess.run(cmd)
return proc.returncode
def main() -> int:
args = parse_args()
in_path = pathlib.Path(args.input)
if not in_path.exists():
print(f"error: input file not found: {in_path}", file=sys.stderr)
return 2
entries = load_image(in_path, args.base_addr)
if args.limit is not None:
entries = entries[: args.limit]
if not entries:
print("error: no bytes found to write", file=sys.stderr)
return 2
if args.ram_addr_width < 1 or args.ram_addr_width > JTAG_ADDR_W:
print(
f"error: --ram-addr-width must be in [1, {JTAG_ADDR_W}] for this protocol",
file=sys.stderr,
)
return 2
max_jtag_addr = (1 << JTAG_ADDR_W) - 1
max_addr = (1 << args.ram_addr_width) - 1
for addr, _ in entries:
if addr < 0 or addr > max_jtag_addr:
print(
f"error: address 0x{addr:x} exceeds 32-bit protocol range (max 0x{max_jtag_addr:x})",
file=sys.stderr,
)
return 2
if addr > max_addr:
print(
f"error: address 0x{addr:x} exceeds RAM addr width {args.ram_addr_width} (max 0x{max_addr:x})",
file=sys.stderr,
)
return 2
tcl = build_openocd_tcl(entries, args.tap, args.user_chain, args.openocd_cmd)
if args.dry_run:
print(tcl, end="")
print(f"# bytes: {len(entries)}", file=sys.stderr)
return 0
if not args.openocd_cfg:
print("error: provide at least one --openocd-cfg unless using --dry-run", file=sys.stderr)
return 2
with tempfile.NamedTemporaryFile("w", suffix=".tcl", delete=False) as tf:
tf.write(tcl)
tcl_path = pathlib.Path(tf.name)
print(f"Programming {len(entries)} bytes via JTAG...")
rc = run_openocd(args.openocd_cfg, tcl_path)
if rc != 0:
print(f"error: openocd failed with exit code {rc}", file=sys.stderr)
print(f"TCL kept at: {tcl_path}", file=sys.stderr)
return rc
print("Done.")
return 0
if __name__ == "__main__":
raise SystemExit(main())