#!/usr/bin/env python3
# Copyright (c) 2026 Peter Fors
# SPDX-License-Identifier: MIT

import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile


SOURCE = Path(__file__).with_name("kernels.S")
CHAIN_COUNTS = (1, 2, 4, 8)
DEPTHS = (0, 32, 64, 72, 76, *range(80, 97), 104, 112, 128)
CYCLES = "cycles:u"
INSTRUCTIONS = "instructions:u"
OPS = "rc1:u"
AL = "r1af:u"
PRF = "r1ae:u"
BACKEND = "r100001ea0:u"
ZEN4_QUEUES = (AL, "r2af:u", "r4af:u", "r8af:u")


def build(directory, variant, amount, iterations, cpu):
	binary = directory / f"{variant}-{amount}"
	object_file = binary.with_suffix(".o")
	chains = amount if variant == "chains" else 0
	expected = 7 * pow(3, (128 // chains) * iterations, 1 << 64) % (1 << 64) if chains else 0
	symbols = {
		"chains": chains, "depth": 0 if chains else amount,
		"waiting": int(variant == "dependent"), "iterations": iterations, "expected": hex(expected), "cpu": cpu,
	}
	command = ["as", "--64", "--fatal-warnings"]
	for key, value in symbols.items():
		command.extend(("--defsym", f"{key}={value}"))
	subprocess.run([*command, "-o", object_file, SOURCE], check=True)
	subprocess.run(["ld", "--fatal-warnings", "-o", binary, object_file], check=True)
	return binary


def collect(binary, events):
	group = "{" + ",".join(events) + "}:D"
	command = ["perf", "stat", "--no-scale", "-x", ";", "-e", group, "--", binary]
	result = subprocess.run(command, capture_output=True, text=True, env={**os.environ, "LC_ALL": "C"})
	if result.returncode:
		raise RuntimeError(f"{binary.name} exited with status {result.returncode}\n{result.stderr.strip()}")

	counts = {}
	for line in result.stderr.splitlines():
		parts = line.split(";")
		if len(parts) >= 5 and parts[2] in events:
			value, _, event, running, coverage = parts[:5]
			if not value.isdecimal() or not running.isdecimal() or int(running) == 0 or float(coverage) != 100.0:
				raise RuntimeError(f"{binary.name}: counter did not run for the full sample\n{line}")
			counts[event] = int(value)

	if counts.keys() != set(events):
		raise RuntimeError(f"{binary.name}: incomplete perf stat output\n{result.stderr.strip()}")
	return counts


def measure(binary, iterations, loop_instructions, zen4):
	events = (CYCLES, INSTRUCTIONS, OPS, PRF, BACKEND)
	counts = collect(binary, events if zen4 else (*events, AL))
	expected = loop_instructions * iterations
	if abs(counts[INSTRUCTIONS] - expected) > 0.005 * expected or not counts[CYCLES] or not counts[OPS]:
		raise RuntimeError(f"{binary.name}: unexpected instruction, cycle or op count")

	groups = [counts]
	if zen4:
		scheduler = collect(binary, (CYCLES, OPS, *ZEN4_QUEUES))
		if not scheduler[CYCLES] or abs(scheduler[OPS] - counts[OPS]) > 0.005 * counts[OPS]:
			raise RuntimeError(f"{binary.name}: retired ops differ between counter groups")
		groups.append(scheduler)

	return groups


def read_setting(path):
	try:
		return Path(path).read_text().strip()
	except OSError:
		return "unavailable"


def main():
	parser = argparse.ArgumentParser(description="Measure AMD integer scheduler token dispatch stalls.")
	parser.add_argument("--arch", choices=("zen4", "zen5"), default="zen5")
	parser.add_argument("--cpu", type=int, default=9, help="workload CPU (default 9)")
	parser.add_argument("--controller", type=int, default=11, help="perf controller CPU (default 11)")
	parser.add_argument("--rounds", type=int, default=3)
	parser.add_argument("--suite", choices=("all", "chains", "capacity"), default="all")
	args = parser.parse_args()
	if args.rounds < 1 or args.cpu < 0 or args.controller < 0 or args.cpu == args.controller:
		parser.error("use positive rounds and distinct, nonnegative CPU numbers")

	zen4 = args.arch == "zen4"

	os.sched_setscheduler(0, os.SCHED_OTHER, os.sched_param(0))
	os.sched_setaffinity(0, {args.controller})
	model = next(line.split(":", 1)[1].strip() for line in Path("/proc/cpuinfo").read_text().splitlines() if line.startswith("model name"))
	boost = read_setting("/sys/devices/system/cpu/cpufreq/boost")
	governor = read_setting(f"/sys/devices/system/cpu/cpu{args.cpu}/cpufreq/scaling_governor")
	assembler = subprocess.check_output(["as", "--version"], text=True).splitlines()[0]
	print(f"{model} | CPU {args.cpu} | boost {boost} | {governor} | Linux {os.uname().release}", file=sys.stderr)
	print(f"{assembler} | {args.rounds} rounds | perf controller CPU {args.controller}", file=sys.stderr)

	cases = {}
	if args.suite in ("all", "chains"):
		cases.update({("chains", n): (1_000_000, 130) for n in CHAIN_COUNTS})
	if args.suite in ("all", "capacity"):
		for n in DEPTHS:
			for variant in ("ready", "dependent"):
				cases[variant, n] = 200_000, 137

	samples = []
	with tempfile.TemporaryDirectory(prefix="al-tokens-") as temporary:
		binaries = {case: build(Path(temporary), *case, iterations, args.cpu) for case, (iterations, _) in cases.items()}
		for trial in range(args.rounds):
			order = cases if trial % 2 == 0 else reversed(cases)
			for case in order:
				iterations, _ = cases[case]
				groups = measure(binaries[case], *cases[case], zen4)
				samples.append(dict(round=trial + 1, variant=case[0], input=case[1], iterations=iterations, groups=groups))

	metadata = dict(arch=args.arch, model=model, cpu=args.cpu, controller=args.controller, boost=boost, governor=governor, assembler=assembler, kernel=os.uname().release, scheduling="SCHED_OTHER", coverage_percent=100, rounds=args.rounds)
	metadata["siblings"] = read_setting(f"/sys/devices/system/cpu/cpu{args.cpu}/topology/thread_siblings_list")
	metadata["microcode"] = next(line.split(":", 1)[1].strip() for line in Path("/proc/cpuinfo").read_text().splitlines() if line.startswith("microcode"))
	metadata["perf"] = subprocess.check_output(["perf", "version"], text=True).strip()
	print(json.dumps(dict(metadata=metadata, samples=samples), indent=2))


if __name__ == "__main__":
	try:
		main()
	except (OSError, RuntimeError, subprocess.CalledProcessError) as error:
		sys.exit(str(error))
