lenovo_fix.py 29 KB

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