lenovo_fix.py 26 KB

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