lenovo_fix.py 30 KB

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