#!/usr/bin/env python3 """Read the amdgpu device's sysfs files through the MacLinuxGPU observer client. Paths are relative to the device directory a Linux tool reads under /sys/class/drm/card0/device, for example: read-sysfs.py gpu_busy_percent mem_info_vram_used pp_dpm_sclk read-sysfs.py --list hwmon/hwmon0 read-sysfs.py --hex gpu_metrics read-sysfs.py --sensor gpu_load --grbm 100 read-sysfs.py --list drm/card0 # DRM connectors (display on) read-sysfs.py drm/card0/card0-DP-1/status; read-sysfs.py --hex drm/card0/card0-DP-1/edid Each file read runs the attribute's show() (or a bin attribute's read()) in the driver, exactly as a Linux sysfs read does. The observer client never claims PCI, joins the session or touches queues; reads fail with "not ready" unless the upstream driver is running. """ import argparse import ctypes as c import errno import os import struct import sys import time OBSERVER_CLIENT = 1 SYSFS_READ = 80 # dext/sources/session_state.h MLG_SELECTOR_SYSFS_READ DRM_INFO = 81 # MLG_SELECTOR_DRM_INFO OP_READ, OP_LIST = 0, 1 CHUNK = 4096 # MLG_SYSFS_CHUNK_MAX PATH_MAX = 256 # MLG_SYSFS_PATH_MAX NOT_READY = 0xe00002d8 NOT_PERMITTED = 0xe00002e2 # include/uapi/drm/amdgpu_drm.h INFO_SENSOR = 0x1D INFO_READ_MMR_REG = 0x15 SENSORS = {"gfx_sclk": 1, "gfx_mclk": 2, "gpu_temp": 3, "gpu_load": 4, "gpu_avg_power": 5, "vddnb": 6, "vddgfx": 7, "gpu_input_power": 0xc} # SOC15 GC register layout (gc_*_offset.h regGRBM_STATUS, base index 0) and # GRBM_STATUS__GUI_ACTIVE (gc_*_sh_mask.h); the segment base comes from the # device's IP discovery table in sysfs. GRBM_STATUS = 0x0da4 GUI_ACTIVE = 1 << 31 class DriverError(RuntimeError): pass def signed(value): return value - (1 << 64) if value >= 1 << 63 else value def check_errno(status, what): status = signed(status) if status: code = -status raise OSError(code, f"{what}: {os.strerror(code) if 0 < code < 200 else 'error'} (Linux errno {code})") def read_file(call, path, op=OP_READ): """The whole file (or listing): read in chunks until its full length. A listing of "" is the device directory itself.""" if (not path and op != OP_LIST) or len(path.encode()) > PATH_MAX: raise ValueError(f"path must be 1 to {PATH_MAX} bytes") data = bytearray() while True: values, payload = call(SYSFS_READ, [op, len(data)], path.encode(), CHUNK) status, count, length = values[:3] check_errno(status, path) if count != len(payload) or count > CHUNK: raise DriverError(f"{path}: inconsistent reply") data.extend(payload) # A bin file of unknown size (length 0, such as a connector's edid) # ends at a short read. if not count or (length and len(data) >= length) or (not length and count < CHUNK): return bytes(data[:length]) if length else bytes(data) def list_dir(call, path): """[(type, name)] with type 'f' file, 'd' directory or 'l' link.""" entries = [] for line in read_file(call, path, OP_LIST).decode().splitlines(): kind, _, name = line.partition(" ") if kind not in ("f", "d", "l") or not name: raise DriverError(f"{path}: bad listing line {line!r}") entries.append((kind, name)) return entries def metrics_header(blob): """struct metrics_table_header: (structure_size, format, content).""" if len(blob) < 4: raise DriverError("gpu_metrics shorter than its header") size, frev, crev = struct.unpack_from("= 4: size, frev, crev = metrics_header(data) print(f"{path}: gpu_metrics v{frev}.{crev}, {size} bytes") for at in range(0, len(data), 16): print(f"{at:04x} {data[at:at + 16].hex(' ')}") else: text = data.decode(errors="replace") print(f"{path}: {text}" if "\n" not in text.rstrip("\n") else f"{path}:\n{text}", end="" if text.endswith("\n") else "\n") except (OSError, ValueError, DriverError) as error: print(f"{path}: {error}", file=sys.stderr) failed = True for name in args.sensor or []: try: value, = struct.unpack("