#!/usr/bin/python3
"""Use ordinary Linux CPU ceilings to reduce power/temperature clamp triggers."""
from datetime import datetime, timezone
import json
import math
import os
from pathlib import Path
import signal
import time
POLICIES = Path('/sys/devices/system/cpu/cpufreq')
STATUS = Path('/run/motherboard-stability/status.json')
def read_number(path, divisor=1):
try:
value = float(Path(path).read_text().strip()) / divisor
return value if math.isfinite(value) else None
except (OSError, ValueError):
return None
def choose_limit(ac_online, cpu_c, gpu_c, main_rpm, previous_stage=0):
if (cpu_c is None or gpu_c is None or main_rpm is None or main_rpm <= 0
or not all(math.isfinite(t) and 0 <= t <= 125 for t in (cpu_c, gpu_c))):
return 1800000, 2, 'essential sensor or main fan unavailable'
hottest = max(cpu_c, gpu_c)
if hottest >= 73 or (previous_stage == 2 and hottest > 66):
return 1800000, 2, 'hot: CPU or board GPU temperature at/above 73C, or cooling down'
if hottest >= 65 or (previous_stage >= 1 and hottest > 58):
return 2400000, 1, 'warm: CPU or board GPU temperature at/above 65C, or cooling down'
if ac_online is not True:
return 2400000, 0, 'battery or mains status unavailable'
return 3200000, 0, 'mains power; normal temperatures'
def find_hwmon(name):
for path in Path('/sys/class/hwmon').glob('hwmon*'):
try:
if (path / 'name').read_text().strip() == name:
return path
except OSError:
continue
return None
def set_limits(target):
policies = sorted(POLICIES.glob('policy*'))
if len(policies) != 16:
raise RuntimeError('Unexpected CPU policy count')
for p in policies:
low = read_number(p / 'scaling_min_freq')
high = read_number(p / 'cpuinfo_max_freq')
if low is None or high is None or not low <= target <= high:
raise RuntimeError('Requested ceiling conflicts with CPU bounds: ' + p.name)
for p in policies:
if read_number(p / 'scaling_max_freq') != target:
(p / 'scaling_max_freq').write_text(str(target))
deadline = time.monotonic() + 5
while True:
values = [read_number(p / 'scaling_max_freq') for p in policies]
if all(value == target for value in values):
return
if time.monotonic() >= deadline:
raise RuntimeError('CPU ceiling readback did not settle: ' + repr(values))
time.sleep(0.05)
def write_status(data):
temporary = STATUS.with_suffix('.tmp')
temporary.write_text(json.dumps(data, indent=2) + '\n')
os.replace(temporary, STATUS)
def main():
if Path('/sys/class/dmi/id/board_name').read_text().strip() != 'GM7RGxM':
raise RuntimeError('Unsupported motherboard')
if 'AMD Ryzen 9 6900HX' not in Path('/proc/cpuinfo').read_text():
raise RuntimeError('Unsupported CPU')
stage = 0
running = True
last = None
data = {}
def stop(signum, frame):
nonlocal running
running = False
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
try:
while running:
cpu, board = find_hwmon('k10temp'), find_hwmon('uniwill')
cpu_c = read_number(cpu / 'temp1_input', 1000) if cpu else None
gpu_c = read_number(board / 'temp2_input', 1000) if board else None
rpm = read_number(board / 'fan1_input') if board else None
ac = read_number('/sys/class/power_supply/AC0/online') == 1
target, stage, reason = choose_limit(ac, cpu_c, gpu_c, rpm, stage)
set_limits(target)
data = {'running': True, 'timestamp': datetime.now(timezone.utc).isoformat(),
'limit_mhz': target // 1000, 'thermal_stage': stage, 'reason': reason,
'mains_online': ac, 'cpu_c': cpu_c, 'board_gpu_c': gpu_c, 'main_fan_rpm': rpm,
'note': 'Avoidance workaround; firmware thermal/power protection remains active.'}
write_status(data)
if last != (target, stage, reason):
print(json.dumps(data), flush=True)
last = (target, stage, reason)
time.sleep(1)
finally:
if data:
data['running'] = False
data['timestamp'] = datetime.now(timezone.utc).isoformat()
write_status(data)
if __name__ == '__main__':
main()