lenovo_fix.py 23 KB

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