lenovo_fix.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. #!/usr/bin/env python3
  2. from __future__ import print_function
  3. import argparse
  4. import configparser
  5. import dbus
  6. import glob
  7. import gzip
  8. import os
  9. import re
  10. import struct
  11. import subprocess
  12. import sys
  13. from collections import defaultdict
  14. from dbus.mainloop.glib import DBusGMainLoop
  15. from errno import EACCES, EPERM
  16. from gi.repository import GLib
  17. from mmio import MMIO, MMIOError
  18. from multiprocessing import cpu_count
  19. from platform import uname
  20. from threading import Event, Thread
  21. from time import time
  22. DEFAULT_SYSFS_POWER_PATH = '/sys/class/power_supply/AC*/online'
  23. VOLTAGE_PLANES = {'CORE': 0, 'GPU': 1, 'CACHE': 2, 'UNCORE': 3, 'ANALOGIO': 4}
  24. TRIP_TEMP_RANGE = [40, 97]
  25. UNDERVOLT_KEYS = ('UNDERVOLT', 'UNDERVOLT.AC', 'UNDERVOLT.BATTERY')
  26. power = {'source': None, 'method': 'polling'}
  27. platform_info_bits = {
  28. 'maximum_non_turbo_ratio': [8, 15],
  29. 'maximum_efficiency_ratio': [40, 47],
  30. 'minimum_operating_ratio': [48, 55],
  31. 'feature_ppin_cap': [23, 23],
  32. 'feature_programmable_turbo_ratio': [28, 28],
  33. 'feature_programmable_tdp_limit': [29, 29],
  34. 'number_of_additional_tdp_profiles': [33, 34],
  35. 'feature_programmable_temperature_target': [30, 30],
  36. 'feature_low_power_mode': [32, 32],
  37. }
  38. thermal_status_bits = {
  39. 'thermal_limit_status': [0, 0],
  40. 'thermal_limit_log': [1, 1],
  41. 'prochot_or_forcepr_status': [2, 2],
  42. 'prochot_or_forcepr_log': [3, 3],
  43. 'crit_temp_status': [4, 4],
  44. 'crit_temp_log': [5, 5],
  45. 'thermal_threshold1_status': [6, 6],
  46. 'thermal_threshold1_log': [7, 7],
  47. 'thermal_threshold2_status': [8, 8],
  48. 'thermal_threshold2_log': [9, 9],
  49. 'power_limit_status': [10, 10],
  50. 'power_limit_log': [11, 11],
  51. 'current_limit_status': [12, 12],
  52. 'current_limit_log': [13, 13],
  53. 'cross_domain_limit_status': [14, 14],
  54. 'cross_domain_limit_log': [15, 15],
  55. 'cpu_temp': [16, 22],
  56. 'temp_resolution': [27, 30],
  57. 'reading_valid': [31, 31],
  58. }
  59. class bcolors:
  60. YELLOW = '\033[93m'
  61. GREEN = '\033[92m'
  62. RED = '\033[91m'
  63. RESET = '\033[0m'
  64. BOLD = '\033[1m'
  65. OK = bcolors.GREEN + bcolors.BOLD + 'OK' + bcolors.RESET
  66. ERR = bcolors.RED + bcolors.BOLD + 'ERR' + bcolors.RESET
  67. LIM = bcolors.YELLOW + bcolors.BOLD + 'LIM' + bcolors.RESET
  68. def writemsr(msr, val):
  69. msr_list = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  70. if not os.path.exists(msr_list[0]):
  71. try:
  72. subprocess.check_call(('modprobe', 'msr'))
  73. except subprocess.CalledProcessError:
  74. print('[E] Unable to load the msr module.')
  75. sys.exit(1)
  76. try:
  77. for addr in msr_list:
  78. f = os.open(addr, os.O_WRONLY)
  79. os.lseek(f, msr, os.SEEK_SET)
  80. os.write(f, struct.pack('Q', val))
  81. os.close(f)
  82. except (IOError, OSError) as e:
  83. if e.errno == EPERM or e.errno == EACCES:
  84. print(
  85. '[E] Unable to write to MSR. Try to disable Secure Boot '
  86. 'and check if your kernel does not restrict access to MSR.'
  87. )
  88. sys.exit(1)
  89. else:
  90. raise e
  91. # returns the value between from_bit and to_bit as unsigned long
  92. def readmsr(msr, from_bit=0, to_bit=63, cpu=None, flatten=False):
  93. assert cpu is None or cpu in range(cpu_count())
  94. if from_bit > to_bit:
  95. print('[E] Wrong readmsr bit params')
  96. sys.exit(1)
  97. msr_list = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  98. if not os.path.exists(msr_list[0]):
  99. try:
  100. subprocess.check_call(('modprobe', 'msr'))
  101. except subprocess.CalledProcessError:
  102. print('[E] Unable to load the msr module.')
  103. sys.exit(1)
  104. try:
  105. output = []
  106. for addr in msr_list:
  107. f = os.open(addr, os.O_RDONLY)
  108. os.lseek(f, msr, os.SEEK_SET)
  109. val = struct.unpack('Q', os.read(f, 8))[0]
  110. os.close(f)
  111. output.append(get_value_for_bits(val, from_bit, to_bit))
  112. if flatten:
  113. return output[0] if len(set(output)) == 1 else output
  114. return output[cpu] if cpu is not None else output
  115. except (IOError, OSError) as e:
  116. if e.errno == EPERM or e.errno == EACCES:
  117. print('[E] Unable to read from MSR. Try to disable Secure Boot.')
  118. sys.exit(1)
  119. else:
  120. raise e
  121. def cpu_usage_pct(exit_event, interval=1.0):
  122. last_idle = last_total = 0
  123. for i in range(2):
  124. with open('/proc/stat') as f:
  125. fields = [float(column) for column in f.readline().strip().split()[1:]]
  126. idle, total = fields[3], sum(fields)
  127. idle_delta, total_delta = idle - last_idle, total - last_total
  128. last_idle, last_total = idle, total
  129. if i == 0:
  130. exit_event.wait(interval)
  131. return 100.0 * (1.0 - idle_delta / total_delta)
  132. def get_value_for_bits(val, from_bit=0, to_bit=63):
  133. mask = sum(2 ** x for x in range(from_bit, to_bit + 1))
  134. return (val & mask) >> from_bit
  135. def is_on_battery(config):
  136. try:
  137. for path in glob.glob(config.get('GENERAL', 'Sysfs_Power_Path', fallback=DEFAULT_SYSFS_POWER_PATH)):
  138. with open(path) as f:
  139. return not bool(int(f.read()))
  140. except:
  141. pass
  142. print('[E] No valid Sysfs_Power_Path found!')
  143. sys.exit(1)
  144. def get_cpu_platform_info():
  145. features_msr_value = readmsr(0xCE, cpu=0)
  146. cpu_platform_info = {}
  147. for key, value in platform_info_bits.items():
  148. cpu_platform_info[key] = int(get_value_for_bits(features_msr_value, value[0], value[1]))
  149. return cpu_platform_info
  150. def get_reset_thermal_status():
  151. # read thermal status
  152. thermal_status_msr_value = readmsr(0x19C)
  153. thermal_status = []
  154. for core in range(cpu_count()):
  155. thermal_status_core = {}
  156. for key, value in thermal_status_bits.items():
  157. thermal_status_core[key] = int(get_value_for_bits(thermal_status_msr_value[core], value[0], value[1]))
  158. thermal_status.append(thermal_status_core)
  159. # reset log bits
  160. writemsr(0x19C, 0)
  161. return thermal_status
  162. def get_time_unit():
  163. # 0.000977 is the time unit of my CPU
  164. # TODO formula might be different for other CPUs
  165. return 1.0 / 2 ** readmsr(0x606, 16, 19, cpu=0)
  166. def get_power_unit():
  167. # 0.125 is the power unit of my CPU
  168. # TODO formula might be different for other CPUs
  169. return 1.0 / 2 ** readmsr(0x606, 0, 3, cpu=0)
  170. def get_critical_temp():
  171. # the critical temperature for my CPU is 100 'C
  172. return readmsr(0x1A2, 16, 23, cpu=0)
  173. def get_cur_pkg_power_limits():
  174. value = readmsr(0x610, 0, 55, flatten=True)
  175. return {
  176. 'PL1': get_value_for_bits(value, 0, 14),
  177. 'TW1': get_value_for_bits(value, 17, 23),
  178. 'PL2': get_value_for_bits(value, 32, 46),
  179. 'TW2': get_value_for_bits(value, 49, 55),
  180. }
  181. def calc_time_window_vars(t):
  182. time_unit = get_time_unit()
  183. for Y in range(2 ** 5):
  184. for Z in range(2 ** 2):
  185. if t <= (2 ** Y) * (1.0 + Z / 4.0) * time_unit:
  186. return (Y, Z)
  187. raise ValueError('Unable to find a good combination!')
  188. def calc_undervolt_msr(plane, offset):
  189. """Return the value to be written in the MSR 150h for setting the given
  190. offset voltage (in mV) to the given voltage plane.
  191. """
  192. assert offset <= 0
  193. assert plane in VOLTAGE_PLANES
  194. offset = int(round(offset * 1.024))
  195. offset = 0xFFE00000 & ((offset & 0xFFF) << 21)
  196. return 0x8000001100000000 | (VOLTAGE_PLANES[plane] << 40) | offset
  197. def calc_undervolt_mv(msr_value):
  198. """Return the offset voltage (in mV) from the given raw MSR 150h value.
  199. """
  200. offset = (msr_value & 0xFFE00000) >> 21
  201. offset = offset if offset <= 0x400 else -(0x800 - offset)
  202. return int(round(offset / 1.024))
  203. def undervolt(config):
  204. for plane in VOLTAGE_PLANES:
  205. write_offset_mv = config.getfloat(
  206. 'UNDERVOLT.{:s}'.format(power['source']), plane, fallback=config.getfloat('UNDERVOLT', plane, fallback=0.0)
  207. )
  208. write_value = calc_undervolt_msr(plane, write_offset_mv)
  209. writemsr(0x150, write_value)
  210. if args.debug:
  211. write_value &= 0xFFFFFFFF
  212. writemsr(0x150, 0x8000001000000000 | (VOLTAGE_PLANES[plane] << 40))
  213. read_value = readmsr(0x150, flatten=True)
  214. read_offset_mv = calc_undervolt_mv(read_value)
  215. match = OK if write_value == read_value else ERR
  216. print(
  217. '[D] Undervolt plane {:s} - write {:.0f} mV ({:#x}) - read {:.0f} mV ({:#x}) - match {}'.format(
  218. plane, write_offset_mv, write_value, read_offset_mv, read_value, match
  219. )
  220. )
  221. def load_config():
  222. config = configparser.ConfigParser()
  223. config.read(args.config)
  224. # config values sanity check
  225. for power_source in ('AC', 'BATTERY'):
  226. for option in ('Update_Rate_s', 'PL1_Tdp_W', 'PL1_Duration_s', 'PL2_Tdp_W', 'PL2_Duration_S'):
  227. value = config.getfloat(power_source, option, fallback=None)
  228. if value is not None:
  229. value = config.set(power_source, option, str(max(0.1, value)))
  230. elif option == 'Update_Rate_s':
  231. print('[E] The mandatory "Update_Rate_s" parameter is missing.')
  232. sys.exit(1)
  233. trip_temp = config.getfloat(power_source, 'Trip_Temp_C', fallback=None)
  234. if trip_temp is not None:
  235. valid_trip_temp = min(TRIP_TEMP_RANGE[1], max(TRIP_TEMP_RANGE[0], trip_temp))
  236. if trip_temp != valid_trip_temp:
  237. config.set(power_source, 'Trip_Temp_C', str(valid_trip_temp))
  238. print(
  239. '[!] Overriding invalid "Trip_Temp_C" value in "{:s}": {:.1f} -> {:.1f}'.format(
  240. power_source, trip_temp, valid_trip_temp
  241. )
  242. )
  243. # fix any invalid value (ie. < 0) in the undervolt settings
  244. for key in UNDERVOLT_KEYS:
  245. for plane in VOLTAGE_PLANES:
  246. if key in config:
  247. value = config.getfloat(key, plane)
  248. valid_value = min(0, value)
  249. if value != valid_value:
  250. config.set(key, plane, str(valid_value))
  251. print(
  252. '[!] Overriding invalid "{:s}" value in "{:s}" voltage plane: {:.0f} -> {:.0f}'.format(
  253. key, plane, value, valid_value
  254. )
  255. )
  256. # handle the case where only one of UNDERVOLT.AC, UNDERVOLT.BATTERY keys exists
  257. # by forcing the other key to all zeros (ie. no undervolt)
  258. if any(key in config for key in UNDERVOLT_KEYS[1:]):
  259. for key in UNDERVOLT_KEYS[1:]:
  260. if key not in config:
  261. config.add_section(key)
  262. for plane in VOLTAGE_PLANES:
  263. value = config.getfloat(key, plane, fallback=0.0)
  264. config.set(key, plane, str(value))
  265. return config
  266. def calc_reg_values(platform_info, config):
  267. regs = defaultdict(dict)
  268. for power_source in ('AC', 'BATTERY'):
  269. if platform_info['feature_programmable_temperature_target'] != 1:
  270. print("[W] Setting temperature target is not supported by this CPU")
  271. else:
  272. # the critical temperature for my CPU is 100 'C
  273. critical_temp = get_critical_temp()
  274. # update the allowed temp range to keep at least 3 'C from the CPU critical temperature
  275. global TRIP_TEMP_RANGE
  276. TRIP_TEMP_RANGE[1] = min(TRIP_TEMP_RANGE[1], critical_temp - 3)
  277. Trip_Temp_C = config.getfloat(power_source, 'Trip_Temp_C', fallback=None)
  278. if Trip_Temp_C is not None:
  279. trip_offset = int(round(critical_temp - Trip_Temp_C))
  280. regs[power_source]['MSR_TEMPERATURE_TARGET'] = trip_offset << 24
  281. else:
  282. print('[I] {:s} trip temperature is disabled in config.'.format(power_source))
  283. power_unit = get_power_unit()
  284. PL1_Tdp_W = config.getfloat(power_source, 'PL1_Tdp_W', fallback=None)
  285. PL1_Duration_s = config.getfloat(power_source, 'PL1_Duration_s', fallback=None)
  286. PL2_Tdp_W = config.getfloat(power_source, 'PL2_Tdp_W', fallback=None)
  287. PL2_Duration_s = config.getfloat(power_source, 'PL2_Duration_s', fallback=None)
  288. if (PL1_Tdp_W, PL1_Duration_s, PL2_Tdp_W, PL2_Duration_s).count(None) < 4:
  289. cur_pkg_power_limits = get_cur_pkg_power_limits()
  290. if PL1_Tdp_W is None:
  291. PL1 = cur_pkg_power_limits['PL1']
  292. print('[I] {:s} PL1_Tdp_W disabled in config.'.format(power_source))
  293. else:
  294. PL1 = int(round(PL1_Tdp_W / power_unit))
  295. if PL1_Duration_s is None:
  296. TW1 = cur_pkg_power_limits['TW1']
  297. print('[I] {:s} PL1_Duration_s disabled in config.'.format(power_source))
  298. else:
  299. Y, Z = calc_time_window_vars(PL1_Duration_s)
  300. TW1 = Y | (Z << 5)
  301. if PL2_Tdp_W is None:
  302. PL2 = cur_pkg_power_limits['PL2']
  303. print('[I] {:s} PL2_Tdp_W disabled in config.'.format(power_source))
  304. else:
  305. PL2 = int(round(PL2_Tdp_W / power_unit))
  306. if PL2_Duration_s is None:
  307. TW2 = cur_pkg_power_limits['TW2']
  308. print('[I] {:s} PL2_Duration_s disabled in config.'.format(power_source))
  309. else:
  310. Y, Z = calc_time_window_vars(PL2_Duration_s)
  311. TW2 = Y | (Z << 5)
  312. regs[power_source]['MSR_PKG_POWER_LIMIT'] = (
  313. PL1 | (1 << 15) | (TW1 << 17) | (PL2 << 32) | (1 << 47) | (TW2 << 49)
  314. )
  315. else:
  316. print('[I] {:s} package power limits are disabled in config.'.format(power_source))
  317. # cTDP
  318. c_tdp_target_value = config.getint(power_source, 'cTDP', fallback=None)
  319. if c_tdp_target_value is not None:
  320. if platform_info['feature_programmable_tdp_limit'] != 1:
  321. print("[W] cTDP setting not supported by this CPU")
  322. elif platform_info['number_of_additional_tdp_profiles'] < c_tdp_target_value:
  323. print("[W] the configured cTDP profile is not supported by this CPU")
  324. else:
  325. valid_c_tdp_target_value = max(0, c_tdp_target_value)
  326. regs[power_source]['MSR_CONFIG_TDP_CONTROL'] = valid_c_tdp_target_value
  327. return regs
  328. def set_hwp(pref):
  329. # set HWP energy performance hints
  330. assert pref in ('performance', 'balance_performance', 'default', 'balance_power', 'power')
  331. CPUs = [
  332. '/sys/devices/system/cpu/cpu{:d}/cpufreq/energy_performance_preference'.format(x) for x in range(cpu_count())
  333. ]
  334. for i, c in enumerate(CPUs):
  335. with open(c, 'wb') as f:
  336. f.write(pref.encode())
  337. if args.debug:
  338. with open(c) as f:
  339. read_value = f.read().strip()
  340. match = OK if pref == read_value else ERR
  341. print('[D] HWP for cpu{:d} - write "{:s}" - read "{:s}" - match {}'.format(i, pref, read_value, match))
  342. def power_thread(config, regs, exit_event):
  343. try:
  344. mchbar_mmio = MMIO(0xFED159A0, 8)
  345. except MMIOError:
  346. print('[E] Unable to open /dev/mem. Try to disable Secure Boot.')
  347. sys.exit(1)
  348. while not exit_event.is_set():
  349. # print thermal status
  350. if args.debug:
  351. thermal_status = get_reset_thermal_status()
  352. for index, core_thermal_status in enumerate(thermal_status):
  353. for key, value in core_thermal_status.items():
  354. print('[D] core {} thermal status: {} = {}'.format(index, key.replace("_", " "), value))
  355. # switch back to sysfs polling
  356. if power['method'] == 'polling':
  357. power['source'] = 'BATTERY' if is_on_battery(config) else 'AC'
  358. # set temperature trip point
  359. if 'MSR_TEMPERATURE_TARGET' in regs[power['source']]:
  360. write_value = regs[power['source']]['MSR_TEMPERATURE_TARGET']
  361. writemsr(0x1A2, write_value)
  362. if args.debug:
  363. read_value = readmsr(0x1A2, 24, 29, flatten=True)
  364. match = OK if write_value >> 24 == read_value else ERR
  365. print(
  366. '[D] TEMPERATURE_TARGET - write {:#x} - read {:#x} - match {}'.format(
  367. write_value >> 24, read_value, match
  368. )
  369. )
  370. # set cTDP
  371. if 'MSR_CONFIG_TDP_CONTROL' in regs[power['source']]:
  372. write_value = regs[power['source']]['MSR_CONFIG_TDP_CONTROL']
  373. writemsr(0x64B, write_value)
  374. if args.debug:
  375. read_value = readmsr(0x64B, 0, 1, flatten=True)
  376. match = OK if write_value == read_value else ERR
  377. print(
  378. '[D] CONFIG_TDP_CONTROL - write {:#x} - read {:#x} - match {}'.format(
  379. write_value, read_value, match
  380. )
  381. )
  382. # set PL1/2 on MSR
  383. write_value = regs[power['source']]['MSR_PKG_POWER_LIMIT']
  384. writemsr(0x610, write_value)
  385. if args.debug:
  386. read_value = readmsr(0x610, 0, 55, flatten=True)
  387. match = OK if write_value == read_value else ERR
  388. print(
  389. '[D] MSR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x} - match {}'.format(
  390. write_value, read_value, match
  391. )
  392. )
  393. # set MCHBAR register to the same PL1/2 values
  394. mchbar_mmio.write32(0, write_value & 0xFFFFFFFF)
  395. mchbar_mmio.write32(4, write_value >> 32)
  396. if args.debug:
  397. read_value = mchbar_mmio.read32(0) | (mchbar_mmio.read32(4) << 32)
  398. match = OK if write_value == read_value else ERR
  399. print(
  400. '[D] MCHBAR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x} - match {}'.format(
  401. write_value, read_value, match
  402. )
  403. )
  404. wait_t = config.getfloat(power['source'], 'Update_Rate_s')
  405. enable_hwp_mode = config.getboolean('AC', 'HWP_Mode', fallback=False)
  406. if power['source'] == 'AC' and enable_hwp_mode:
  407. cpu_usage = cpu_usage_pct(exit_event, interval=wait_t)
  408. # set full performance mode only when load is greater than this threshold (~ at least 1 core full speed)
  409. performance_mode = cpu_usage > 100.0 / (cpu_count() * 1.25)
  410. # check again if we are on AC, since in the meantime we might have switched to BATTERY
  411. if not is_on_battery(config):
  412. set_hwp('performance' if performance_mode else 'balance_performance')
  413. else:
  414. exit_event.wait(wait_t)
  415. def check_kernel():
  416. if os.geteuid() != 0:
  417. print('[E] No root no party. Try again with sudo.')
  418. sys.exit(1)
  419. kernel_config = None
  420. try:
  421. with open(os.path.join('/boot', 'config-{:s}'.format(uname()[2]))) as f:
  422. kernel_config = f.read()
  423. except IOError:
  424. config_gz_path = os.path.join('/proc', 'config.gz')
  425. try:
  426. if not os.path.isfile(config_gz_path):
  427. subprocess.check_call(('modprobe', 'configs'))
  428. with gzip.open(config_gz_path) as f:
  429. kernel_config = f.read().decode()
  430. except (subprocess.CalledProcessError, IOError):
  431. pass
  432. if kernel_config is None:
  433. print('[W] Unable to obtain and validate kernel config.')
  434. elif not re.search('CONFIG_DEVMEM=y', kernel_config):
  435. print('[E] Bad kernel config: you need CONFIG_DEVMEM=y.')
  436. sys.exit(1)
  437. elif not re.search('CONFIG_X86_MSR=(y|m)', kernel_config):
  438. print('[E] Bad kernel config: you need CONFIG_X86_MSR builtin or as module.')
  439. sys.exit(1)
  440. def monitor(exit_event, wait):
  441. IA32_THERM_STATUS = 0x19C
  442. IA32_PERF_STATUS = 0x198
  443. MSR_RAPL_POWER_UNIT = 0x606
  444. MSR_INTEL_PKG_ENERGY_STATUS = 0x611
  445. MSR_PP1_ENERGY_STATUS = 0x641
  446. MSR_DRAM_ENERGY_STATUS = 0x619
  447. wait = max(0.1, wait)
  448. rapl_power_unit = 0.5 ** readmsr(MSR_RAPL_POWER_UNIT, from_bit=8, to_bit=12, cpu=0)
  449. power_plane_msr = {
  450. 'Package': MSR_INTEL_PKG_ENERGY_STATUS,
  451. 'Graphics': MSR_PP1_ENERGY_STATUS,
  452. 'DRAM': MSR_DRAM_ENERGY_STATUS,
  453. }
  454. prev_energy = {
  455. 'Package': (readmsr(MSR_INTEL_PKG_ENERGY_STATUS, cpu=0) * rapl_power_unit, time()),
  456. 'Graphics': (readmsr(MSR_PP1_ENERGY_STATUS, cpu=0) * rapl_power_unit, time()),
  457. 'DRAM': (readmsr(MSR_DRAM_ENERGY_STATUS, cpu=0) * rapl_power_unit, time()),
  458. }
  459. print('Realtime monitoring of throttling causes:\n')
  460. while not exit_event.is_set():
  461. value = readmsr(IA32_THERM_STATUS, from_bit=0, to_bit=15, cpu=0)
  462. offsets = {'Thermal': 0, 'Power': 10, 'Current': 12, 'Cross-comain (e.g. GPU)': 14}
  463. output = ('{:s}: {:s}'.format(cause, LIM if bool((value >> offsets[cause]) & 1) else OK) for cause in offsets)
  464. # ugly code, just testing...
  465. vcore = readmsr(IA32_PERF_STATUS, from_bit=32, to_bit=47, cpu=0) / (2.0 ** 13) * 1000
  466. stats2 = {'VCore': '{:.0f} mV'.format(vcore)}
  467. for power_plane in ('Package', 'Graphics', 'DRAM'):
  468. energy_j = readmsr(power_plane_msr[power_plane], cpu=0) * rapl_power_unit
  469. now = time()
  470. prev_energy[power_plane], energy_w = (
  471. (energy_j, now),
  472. (energy_j - prev_energy[power_plane][0]) / (now - prev_energy[power_plane][1]),
  473. )
  474. stats2[power_plane] = '{:.1f} W'.format(energy_w)
  475. output2 = ('{:s}: {:s}'.format(label, stats2[label]) for label in stats2)
  476. print('[{}] {} || {}{}'.format(power['source'], ' - '.join(output), ' - '.join(output2), ' ' * 10), end='\r')
  477. exit_event.wait(wait)
  478. def main():
  479. global args
  480. check_kernel()
  481. parser = argparse.ArgumentParser()
  482. exclusive_group = parser.add_mutually_exclusive_group()
  483. exclusive_group.add_argument('--debug', action='store_true', help='add some debug info and additional checks')
  484. exclusive_group.add_argument(
  485. '--monitor',
  486. metavar='update_rate',
  487. const=1.0,
  488. type=float,
  489. nargs='?',
  490. help='realtime monitoring of throttling causes (default 1s)',
  491. )
  492. parser.add_argument('--config', default='/etc/lenovo_fix.conf', help='override default config file path')
  493. args = parser.parse_args()
  494. config = load_config()
  495. power['source'] = 'BATTERY' if is_on_battery(config) else 'AC'
  496. platform_info = get_cpu_platform_info()
  497. if args.debug:
  498. for key, value in platform_info.items():
  499. print('[D] cpu platform info: {} = {}'.format(key.replace("_", " "), value))
  500. regs = calc_reg_values(platform_info, config)
  501. if not config.getboolean('GENERAL', 'Enabled'):
  502. return
  503. exit_event = Event()
  504. thread = Thread(target=power_thread, args=(config, regs, exit_event))
  505. thread.daemon = True
  506. thread.start()
  507. undervolt(config)
  508. # handle dbus events for applying undervolt on resume from sleep/hybernate
  509. def handle_sleep_callback(sleeping):
  510. if not sleeping:
  511. undervolt(config)
  512. def handle_ac_callback(*args):
  513. try:
  514. power['source'] = 'BATTERY' if args[1]['Online'] == 0 else 'AC'
  515. power['method'] = 'dbus'
  516. except:
  517. power['method'] = 'polling'
  518. DBusGMainLoop(set_as_default=True)
  519. bus = dbus.SystemBus()
  520. # add dbus receiver only if undervolt is enabled in config
  521. if any(config.getfloat(key, plane, fallback=0) != 0 for plane in VOLTAGE_PLANES for key in UNDERVOLT_KEYS):
  522. bus.add_signal_receiver(
  523. handle_sleep_callback, 'PrepareForSleep', 'org.freedesktop.login1.Manager', 'org.freedesktop.login1'
  524. )
  525. bus.add_signal_receiver(
  526. handle_ac_callback,
  527. signal_name="PropertiesChanged",
  528. dbus_interface="org.freedesktop.DBus.Properties",
  529. path="/org/freedesktop/UPower/devices/line_power_AC",
  530. )
  531. if args.monitor is not None:
  532. monitor_thread = Thread(target=monitor, args=(exit_event, args.monitor))
  533. monitor_thread.daemon = True
  534. monitor_thread.start()
  535. try:
  536. loop = GLib.MainLoop()
  537. loop.run()
  538. except (KeyboardInterrupt, SystemExit):
  539. pass
  540. exit_event.set()
  541. loop.quit()
  542. thread.join(timeout=1)
  543. if args.monitor is not None:
  544. monitor_thread.join(timeout=0.1)
  545. if __name__ == '__main__':
  546. main()