#!/usr/bin/env python3
"""jtagio — packets through the JTAG pipe ([test/ztex/jtag_io.md]).

    jtagio status                       the pipe's status word: room and beats waiting
    jtagio push FILE [-frame N] [-back OUT]   send FILE as frames of N bytes (default: one frame);
                                        -back writes what came back meanwhile (a loop design) to OUT
    jtagio pull FILE [-secs S]          receive frames into FILE until nothing came for S seconds
    jtagio loop [-n N] [-max BYTES] [-raw]   send N random frames through a loop design, check them back;
                                        -raw: the design carries WORDS (`jtag.io_stream`), boundaries are not compared
    jtagio lag                          measure the cable's TDO lag on an idle pipe
    jtagio shell                        a Vivado tcl prompt on the open target
    jtagio --targets                    list the cables the hardware server sees (names for --target)

The design carries `jtag.io(rx, tx)` (`jtag_pipe` on BSCANE2 USER2).  One
data-register pass moves SLOTS of W + 2 bits both ways at once:
[valid][last][data]; slot 0 in is the command [data slots : 9], slot 0 out
the status [room / 8 : 9][waiting : 9] (511 waiting means "at least").  This tool never sends more valid slots than the
room it was last told, and reads back what comes in the same pass.  It
talks to Vivado's hardware manager like ilactrl does -- one `vivado -mode
tcl` kept open -- but with the target in JTAG mode, which the ILAs cannot
share: close one tool before starting the other.
"""
import argparse, glob, os, random, subprocess, sys, time

HERE = os.path.dirname(os.path.abspath(__file__))
TCL = os.path.join(HERE, "jtagio.tcl")
W = 16
SW = W + 2
MAXSLOTS = 2048            # slots per pass: 36864 bits, a 9 kB hex string
TDO_LAG = 2                # measured on the 2.14b: the register's first bit comes out two TCKs after the
                           # pass begins (the TAP's own TDO retiming), so a pass shifts two bits more and
                           # the two leading zeros are dropped -- the same on every pass length.
                           # `--lag N` overrides it; `--lag auto` (and `jtagio lag`) measures it: an idle
                           # pipe's status is room 2048 and nothing waiting, ONE set bit (bit 8), and
                           # where that bit arrives is the lag


def find_vivado(explicit):
    if explicit:
        return explicit
    from shutil import which
    w = which("vivado")
    if w:
        return w
    sys.exit("jtagio: vivado not found: put it on the PATH (its settings64.sh) or pass --vivado /path/to/vivado")


class Vivado:
    """one `vivado -mode tcl`, kept open; `run` sends tcl and returns the @@ lines"""

    def __init__(self, vivado, quiet=True):
        self.helpers = self._helpers()
        self.p = subprocess.Popen([vivado, "-mode", "tcl", "-nojournal", "-nolog"],
                                  stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                  stderr=subprocess.STDOUT, text=True, bufsize=1)
        self.quiet = quiet
        self.run("source {" + TCL + "}")

    def run(self, tcl):
        self.p.stdin.write(tcl + "\nputs \"@@end\"\n")
        self.p.stdin.flush()
        out = []
        while True:
            line = self.p.stdout.readline()
            if not line:
                raise RuntimeError("vivado exited")
            line = line.rstrip("\n")
            if line == "@@end":
                return out
            if line.startswith("@@"):
                out.append(line[2:])
            elif not self.quiet and not line.startswith("#"):
                print("  | " + line)

    @staticmethod
    def _helpers():
        out = subprocess.run(["pgrep", "-f", "lnx64.o/(cs|hw)_server"], capture_output=True, text=True).stdout
        return set(int(x) for x in out.split())

    def close(self):
        try:
            self.p.stdin.write("jtag_disconnect\nexit\n")
            self.p.stdin.flush()
            self.p.wait(timeout=30)
        except Exception:
            self.p.kill()
        for pid in self._helpers() - self.helpers:
            try:
                os.kill(pid, 15)
            except OSError:
                pass


def ok(lines, what):
    for l in lines:
        if l.startswith("err "):
            sys.exit("jtagio: %s: %s" % (what, l[4:]))
    return lines


# ── the protocol ────────────────────────────────────────────────────────────
def slot(valid, last, data):
    return (valid & 1) | ((last & 1) << 1) | ((data & ((1 << W) - 1)) << 2)


class Pipe:
    def __init__(self, v):
        self.v = v
        self.passes = 0
        self.bits = 0

    def pass_(self, slots):
        """one data-register pass: a list of slot values in, the list out"""
        n = len(slots)
        vec = 0
        for k, s in enumerate(slots):
            vec |= (s & ((1 << SW) - 1)) << (k * SW)
        bits = n * SW + TDO_LAG
        hexlen = (bits + 3) // 4
        lines = ok(self.v.run("jtag_pass %d %0*x" % (bits, hexlen, vec)), "pass")
        tdo = 0
        for l in lines:
            if l.startswith("tdo "):
                tdo = int(l[4:], 16) >> TDO_LAG
        self.passes += 1
        self.bits += bits
        return [(tdo >> (k * SW)) & ((1 << SW) - 1) for k in range(n)]

    def measure_lag(self):
        """the TDO lag, from an idle pipe's status word (one set bit, bit 8); None when not idle"""
        global TDO_LAG
        keep, TDO_LAG = TDO_LAG, 0
        bits = SW + 16
        lines = ok(self.v.run("jtag_pass %d %0*x" % (bits, (bits + 3) // 4, 0)), "pass")
        TDO_LAG = keep
        raw = 0
        for l in lines:
            if l.startswith("tdo "):
                raw = int(l[4:], 16)
        if raw == 0 or raw & (raw - 1):
            return None, raw
        return raw.bit_length() - 1 - 8, raw

    def status(self):
        s = self.pass_([0])[0]
        room = (s & 511) * 8
        waiting = (s >> 9) & 511
        if waiting == 511:                       # "at least": read a full pass
            waiting = MAXSLOTS - 1
        return room, waiting

    def exchange(self, beats):
        """send beats (valid slots, at most the room) and return the beats that came back"""
        out = self.pass_([len(beats)] + beats)   # the command: how many data slots follow
        return [s for s in out[1:] if s & 1]

    def send_frames(self, frames, sink):
        """push frames (lists of 16-bit words), collecting returned beats into sink"""
        pending = []
        for f in frames:
            for i, w in enumerate(f):
                pending.append(slot(1, 1 if i == len(f) - 1 else 0, w))
        while pending:
            room, waiting = self.status()
            n = min(room, MAXSLOTS - 1, len(pending))
            if n == 0:
                time.sleep(0.01)
                continue
            take = pending[:n]
            del pending[:n]
            # read back as much as we can in the same pass: pad with empty slots up to the pass size
            slots = take + [0] * max(0, min(MAXSLOTS - 1 - n, waiting))
            sink.extend(self.exchange(slots))

    def drain(self, sink, secs):
        """pull until nothing has come for `secs` seconds"""
        quiet_since = time.time()
        while True:
            room, waiting = self.status()
            if waiting:
                got = self.exchange([0] * min(waiting, MAXSLOTS - 1))
                sink.extend(got)
                quiet_since = time.time()
            elif time.time() - quiet_since >= secs:
                return
            else:
                time.sleep(0.02)


def frames_of(beats):
    """split returned beats into frames at their `last` bits"""
    frames, cur = [], []
    for s in beats:
        cur.append((s >> 2) & ((1 << W) - 1))
        if s & 2:
            frames.append(cur)
            cur = []
    return frames, cur


def words_of(data):
    if len(data) % 2:
        data = data + b"\0"
    return [data[i] | (data[i + 1] << 8) for i in range(0, len(data), 2)]


def bytes_of(words):
    out = bytearray()
    for w in words:
        out += bytes((w & 255, (w >> 8) & 255))
    return bytes(out)


# ── the commands ────────────────────────────────────────────────────────────
def connect(v, tck=0, target="", lag="2"):
    global TDO_LAG
    for l in ok(v.run("jtag_connect %d {%s}" % (tck, target)), "connect"):
        if l.startswith("target "):
            print("connected: " + l[7:])
    ok(v.run("jtag_select"), "select")
    if lag == "auto":
        n, raw = Pipe(v).measure_lag()
        if n is None or n < 0:
            sys.exit("jtagio: --lag auto needs an idle pipe (status read 0x%x: not one set bit)" % raw)
        TDO_LAG = n
        print("TDO lag %d" % n)
    else:
        TDO_LAG = int(lag)


def cmd_lag(v, a):
    n, raw = Pipe(v).measure_lag()
    print("raw status 0x%x: %s" % (raw, ("TDO lag %d" % n) if n is not None else "not an idle pipe's (one set bit expected)"))


def cmd_status(v, a):
    p = Pipe(v)
    room, waiting = p.status()
    print("room %d beats, %d beats waiting" % (room, waiting))


def cmd_push(v, a):
    data = open(a.file, "rb").read()
    words = words_of(data)
    n = max(1, a.frame // 2) if a.frame else len(words)
    frames = [words[i:i + n] for i in range(0, len(words), n)] or [[]]
    p = Pipe(v)
    back = []
    t0 = time.time()
    p.send_frames(frames, back)
    dt = time.time() - t0
    if a.back:
        p.drain(back, 0.3)
        fr, rest = frames_of(back)
        out = bytearray()
        for f in fr:
            out += bytes_of(f)
        open(a.back, "wb").write(bytes(out))
    print("pushed %d bytes as %d frames in %d passes, %.1f kB/s; %d beats came back meanwhile%s"
          % (len(data), len(frames), p.passes, len(data) / 1e3 / max(dt, 1e-9), len(back),
             (", %d frames written to %s" % (len(fr), a.back)) if a.back else ""))


def cmd_pull(v, a):
    p = Pipe(v)
    got = []
    t0 = time.time()
    p.drain(got, a.secs)
    frames, rest = frames_of(got)
    out = bytearray()
    for f in frames:
        out += bytes_of(f)
    if rest:
        out += bytes_of(rest)
        print("note: %d beats after the last frame boundary were written too" % len(rest))
    open(a.file, "wb").write(bytes(out))
    print("pulled %d frames, %d bytes, in %d passes over %.1f s" % (len(frames), len(out), p.passes, time.time() - t0))


def cmd_loop(v, a):
    p = Pipe(v)
    rnd = random.Random(1)
    sent = []
    back = []
    t0 = time.time()
    for k in range(a.n):
        n = rnd.randint(1, max(1, a.max // 2))
        f = [rnd.randrange(1 << W) for _ in range(n)]
        sent.append(f)
        p.send_frames([f], back)
    p.drain(back, a.quiet)
    dt = time.time() - t0
    if a.raw:                                    # words, not frames: one stream against the other
        sw = [w for f in sent for w in f]
        bw = [(s >> 2) & ((1 << W) - 1) for s in back]
        bad = 0
        for k in range(min(len(sw), len(bw))):
            if sw[k] != bw[k]:
                bad += 1
                if bad <= 5:
                    print("word %d: 0x%04x back, 0x%04x sent" % (k, bw[k], sw[k]))
        if len(sw) != len(bw):
            bad += 1
            print("%d words back for %d sent" % (len(bw), len(sw)))
        print("loop -raw: %d words each way, %d passes, %d kbit shifted, %.1f s, %.1f kB/s per direction, %s"
              % (len(sw), p.passes, p.bits // 1000, dt, len(sw) * 2 / 1e3 / max(dt, 1e-9), "OK" if bad == 0 else "%d BAD" % bad))
        return 0 if bad == 0 else 1
    frames, rest = frames_of(back)
    bad = 0
    for k in range(min(len(frames), len(sent))):
        if frames[k] != sent[k]:
            bad += 1
            if bad <= 5:
                print("frame %d: %d words back, %d sent%s" % (k, len(frames[k]), len(sent[k]),
                      "" if len(frames[k]) != len(sent[k]) else ", contents differ"))
    if len(frames) != len(sent) or rest:
        bad += 1
        print("%d frames back for %d sent, %d stray beats" % (len(frames), len(sent), len(rest)))
    words = sum(len(f) for f in sent)
    print("loop: %d frames, %d words each way, %d passes, %d kbit shifted, %.1f s, %.1f kB/s per direction, %s"
          % (len(sent), words, p.passes, p.bits // 1000, dt, words * 2 / 1e3 / max(dt, 1e-9), "OK" if bad == 0 else "%d BAD" % bad))
    return 0 if bad == 0 else 1


def cmd_shell(v, a):
    v.quiet = False
    print("vivado tcl, the target open in JTAG mode; `jtag_pass BITS HEX`, `jtag_select`; empty line to leave")
    while True:
        try:
            line = input("tcl> ")
        except EOFError:
            break
        if not line.strip():
            break
        for l in v.run(line):
            print(l)


def main():
    ap = argparse.ArgumentParser(prog="jtagio")
    ap.add_argument("--vivado")
    ap.add_argument("-v", action="store_true")
    ap.add_argument("--tck", type=float, default=0, help="the cable's TCK in MHz (PARAM.FREQUENCY); the cable's default otherwise")
    ap.add_argument("--target", default="", help="a glob on the hw target's name, e.g. '*210319BE27DA*'; the first target otherwise")
    ap.add_argument("--lag", default=str(TDO_LAG), help="the cable's TDO lag in bits, or `auto` to measure it on an idle pipe")
    sub = ap.add_subparsers(dest="cmd", required=True)
    sub.add_parser("status")
    s = sub.add_parser("push"); s.add_argument("file"); s.add_argument("-frame", type=int, default=0); s.add_argument("-back")
    s = sub.add_parser("pull"); s.add_argument("file"); s.add_argument("-secs", type=float, default=1.0)
    s = sub.add_parser("loop"); s.add_argument("-n", type=int, default=100); s.add_argument("-max", type=int, default=4096)
    s.add_argument("-raw", action="store_true"); s.add_argument("-quiet", type=float, default=0.3, help="seconds without a beat that end the drain")
    sub.add_parser("lag")
    sub.add_parser("shell")
    if "--targets" in sys.argv[1:]:              # no command needed: list the cables and leave
        pre = argparse.ArgumentParser(add_help=False); pre.add_argument("--vivado"); pre.add_argument("--targets", action="store_true")
        k, _ = pre.parse_known_args()
        v = Vivado(find_vivado(k.vivado))
        try:
            names = [l[7:] for l in ok(v.run("jtag_targets"), "targets") if l.startswith("target ")]
        finally:
            v.close()
        for n in names:
            print(n)
        if not names:
            print("no targets: is a cable connected, and free (openFPGALoader, another hw_server)?")
        sys.exit(0 if names else 1)
    a = ap.parse_args()
    v = Vivado(find_vivado(a.vivado), quiet=not a.v)
    rc = 0
    try:
        connect(v, int(a.tck * 1e6), a.target, "0" if a.cmd == "lag" else a.lag)
        rc = {"lag": cmd_lag, "status": cmd_status, "push": cmd_push, "pull": cmd_pull, "loop": cmd_loop, "shell": cmd_shell}[a.cmd](v, a) or 0
    finally:
        v.close()
    sys.exit(rc)


if __name__ == "__main__":
    main()
