#!/usr/bin/env python3
# SkillFishOS — GPU gfxclk and power sampler.
#
# Reads gpu_metrics ONCE every 2 s and publishes two small files that every other
# tool reads instead of the SMU:
#   /run/skillfish-gpu-freq   current gfxclk in MHz
#   /run/skillfish-potenze    "apu cpu gpu" in watts, "-" where the SMU says nothing
#
# ⚠️ THIS PROGRAM MUST NOT TALK TO THE SMU MAILBOX ITSELF. Until 26.11.2 it sent
# 0x0E/0x0F on "queue 0" through the SMN window (PCI config 0xB8/0xBC of 00:00.0),
# at 0x03B10A08/48/68. Those are C2PMSG_66/82/90: THE SAME MAILBOX amdgpu uses,
# through MMIO and under its own mutex, which knows nothing about our flock. Every
# 2 s we cleared the response register and wrote our command; when amdgpu was in
# the middle of exporting the metrics table it found its answer gone and logged
#   amdgpu: SMU: No response msg_reg: 6 resp_reg: 0
#   amdgpu: Failed to export SMU metrics table!
# On the .32 that happened on almost every boot from October on (up to 66 times),
# and the community guide reports the same signature freezing the display about
# one boot in three (15/11/2026).
#
# It is not needed any more either: our kernel (patch 0125) answers current_gfxclk
# with QueryGfxclk, sent by the driver under its lock, so gpu_metrics, hwmon
# freq1_input and pp_dpm_sclk all carry the real clock (checked on 7.3.4: all
# 1850 MHz, same as the old mailbox read).
#
# ⚠️ EVERY READ OF gpu_metrics IS A MESSAGE TO THE SMU, and this board's SMU does
# not want many. On 20/09/2026 skillfish-hud-val read that file three times per
# call while conky, the dashboard sampler and the Monitor all called it: SMU
# traffic doubled and the board rebooted on its own three times in half an hour
# (SMU stops answering, hwmon hangs, fand misses its watchdog, the hardware
# watchdog resets). So exactly one program reads it, this one, and the others
# read the files above, which cost as much as a `cat`.
#
# Offsets are measured, not taken from a header: the 8-core unlock moves the
# per-core arrays (that is what patch 0006 is about). 40 the whole package, 44 the
# CPU cores, 46 the GPU, 76 current_gfxclk (gpu_metrics v2.x). 0xFFFF means "not
# reported" and must never be shown as 65 W.
import os, struct, sys, time

METRICS = "/sys/class/drm/card0/device/gpu_metrics"
OUT_FREQ = "/run/skillfish-gpu-freq"
OUT_POWER = "/run/skillfish-potenze"
POWER_OFFSETS = (40, 44, 46)               # apu, cpu, gpu
GFXCLK_OFFSET = 76
GFXCLK_RANGE = (50, 2500)
INTERVAL = 2.0


def read_metrics():
    try:
        with open(METRICS, "rb") as f:
            d = f.read()
    except OSError:
        return None
    # format_revision 2 is the APU layout the offsets above were measured on.
    if len(d) < GFXCLK_OFFSET + 2 or d[2] != 2:
        return None
    return d


def u16(d, off):
    return struct.unpack_from("<H", d, off)[0]


def power_line(d):
    out = []
    for o in POWER_OFFSETS:
        v = u16(d, o)
        out.append("-" if v == 0xFFFF else "%.1f" % (v / 1000.0))
    return " ".join(out)


def publish(path, text):
    # Atomic replace. World-readable on purpose: the HUD and the apps that read
    # the clock run as the desktop user, and the file holds only a number.
    try:
        tmp = path + ".tmp"
        with open(tmp, "w") as f:
            f.write(text + "\n")
        os.chmod(tmp, 0o644)
        os.replace(tmp, path)
    except OSError:
        # /run full or read-only: the readers keep the previous file, which is
        # two seconds old. Better than a sampler that dies because it could
        # not write.
        pass


def main():
    if not os.path.exists(METRICS):
        sys.exit(0)                         # no amdgpu metrics: nothing to sample
    last = 350
    publish(OUT_FREQ, str(last))
    while True:
        d = read_metrics()
        if d is not None:
            v = u16(d, GFXCLK_OFFSET)
            if GFXCLK_RANGE[0] <= v <= GFXCLK_RANGE[1]:
                last = v
            publish(OUT_POWER, power_line(d))
        # The clock is published even when the table could not be read: the last
        # good value, never garbage, and the power file stays the previous one.
        publish(OUT_FREQ, str(last))
        time.sleep(INTERVAL)


if __name__ == "__main__":
    main()
