lenovo_fix.py 33 KB

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