lenovo_fix.py 24 KB

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