lenovo_fix.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. #!/usr/bin/env python3
  2. import argparse
  3. import configparser
  4. import dbus
  5. import glob
  6. import os
  7. import psutil
  8. import struct
  9. import subprocess
  10. import sys
  11. from collections import defaultdict
  12. from dbus.mainloop.glib import DBusGMainLoop
  13. from errno import EACCES, EPERM
  14. from gi.repository import GLib
  15. from mmio import MMIO, MMIOError
  16. from multiprocessing import cpu_count
  17. from threading import Event, Thread
  18. DEFAULT_SYSFS_POWER_PATH = '/sys/class/power_supply/AC*/online'
  19. VOLTAGE_PLANES = {
  20. 'CORE': 0,
  21. 'GPU': 1,
  22. 'CACHE': 2,
  23. 'UNCORE': 3,
  24. 'ANALOGIO': 4,
  25. }
  26. TRIP_TEMP_RANGE = [40, 97]
  27. power = {'source': None, 'method': 'polling'}
  28. platform_info_bits = {
  29. 'maximum_non_turbo_ratio': [8, 15],
  30. 'maximum_efficiency_ratio': [40, 47],
  31. 'minimum_operating_ratio': [48, 55],
  32. 'feature_ppin_cap': [23, 23],
  33. 'feature_programmable_turbo_ratio': [28, 28],
  34. 'feature_programmable_tdp_limit': [29, 29],
  35. 'number_of_additional_tdp_profiles': [33, 34],
  36. 'feature_programmable_temperature_target': [30, 30],
  37. 'feature_low_power_mode': [32, 32]
  38. }
  39. thermal_status_bits = {
  40. 'thermal_limit_status': [0, 0],
  41. 'thermal_limit_log': [1, 1],
  42. 'prochot_or_forcepr_status': [2, 2],
  43. 'prochot_or_forcepr_log': [3, 3],
  44. 'crit_temp_status': [4, 4],
  45. 'crit_temp_log': [5, 5],
  46. 'thermal_threshold1_status': [6, 6],
  47. 'thermal_threshold1_log': [7, 7],
  48. 'thermal_threshold2_status': [8, 8],
  49. 'thermal_threshold2_log': [9, 9],
  50. 'power_limit_status': [10, 10],
  51. 'power_limit_log': [11, 11],
  52. 'current_limit_status': [12, 12],
  53. 'current_limit_log': [13, 13],
  54. 'cross_domain_limit_status': [14, 14],
  55. 'cross_domain_limit_log': [15, 15],
  56. 'cpu_temp': [16, 22],
  57. 'temp_resolution': [27, 30],
  58. 'reading_valid': [31, 31],
  59. }
  60. class bcolors:
  61. GREEN = '\033[92m'
  62. RED = '\033[91m'
  63. RESET = '\033[0m'
  64. BOLD = '\033[1m'
  65. OK = bcolors.GREEN + bcolors.BOLD + 'OK' + bcolors.RESET
  66. ERR = bcolors.RED + bcolors.BOLD + 'ERR' + bcolors.RESET
  67. def writemsr(msr, val):
  68. msr_list = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  69. if not os.path.exists(msr_list[0]):
  70. try:
  71. subprocess.check_call(('modprobe', 'msr'))
  72. except subprocess.CalledProcessError:
  73. print('[E] Unable to load the msr module.')
  74. sys.exit(1)
  75. try:
  76. for addr in msr_list:
  77. f = os.open(addr, os.O_WRONLY)
  78. os.lseek(f, msr, os.SEEK_SET)
  79. os.write(f, struct.pack('Q', val))
  80. os.close(f)
  81. except (IOError, OSError) as e:
  82. if e.errno == EPERM or e.errno == EACCES:
  83. print('[E] Unable to write to MSR. Try to disable Secure Boot.')
  84. sys.exit(1)
  85. else:
  86. raise e
  87. # returns the value between from_bit and to_bit as unsigned long
  88. def readmsr(msr, from_bit=0, to_bit=63, cpu=None, flatten=False):
  89. assert cpu is None or cpu in range(cpu_count())
  90. if from_bit > to_bit:
  91. print('[E] Wrong readmsr bit params')
  92. sys.exit(1)
  93. msr_list = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  94. if not os.path.exists(msr_list[0]):
  95. try:
  96. subprocess.check_call(('modprobe', 'msr'))
  97. except subprocess.CalledProcessError:
  98. print('[E] Unable to load the msr module.')
  99. sys.exit(1)
  100. try:
  101. output = []
  102. for addr in msr_list:
  103. f = os.open(addr, os.O_RDONLY)
  104. os.lseek(f, msr, os.SEEK_SET)
  105. val = struct.unpack('Q', os.read(f, 8))[0]
  106. os.close(f)
  107. output.append(get_value_for_bits(val, from_bit, to_bit))
  108. if flatten:
  109. return output[0] if len(set(output)) == 1 else output
  110. return output[cpu] if cpu is not None else output
  111. except (IOError, OSError) as e:
  112. if e.errno == EPERM or e.errno == EACCES:
  113. print('[E] Unable to read from MSR. Try to disable Secure Boot.')
  114. sys.exit(1)
  115. else:
  116. raise e
  117. def get_value_for_bits(val, from_bit=0, to_bit=63):
  118. mask = sum(2**x for x in range(from_bit, to_bit + 1))
  119. return (val & mask) >> from_bit
  120. def is_on_battery(config):
  121. try:
  122. for path in glob.glob(config.get('Sysfs_Power_Path', 'GENERAL', fallback=DEFAULT_SYSFS_POWER_PATH)):
  123. with open(path) as f:
  124. return not bool(int(f.read()))
  125. except:
  126. pass
  127. print('[E] No valid Sysfs_Power_Path found!')
  128. sys.exit(1)
  129. def get_cpu_platform_info():
  130. features_msr_value = readmsr(0xce, cpu=0)
  131. cpu_platform_info = {}
  132. for key, value in platform_info_bits.items():
  133. cpu_platform_info[key] = int(get_value_for_bits(features_msr_value, value[0], value[1]))
  134. return cpu_platform_info
  135. def get_reset_thermal_status():
  136. # read thermal status
  137. thermal_status_msr_value = readmsr(0x19c)
  138. thermal_status = []
  139. for core in range(cpu_count()):
  140. thermal_status_core = {}
  141. for key, value in thermal_status_bits.items():
  142. thermal_status_core[key] = int(get_value_for_bits(thermal_status_msr_value[core], value[0], value[1]))
  143. thermal_status.append(thermal_status_core)
  144. # reset log bits
  145. writemsr(0x19c, 0)
  146. return thermal_status
  147. def get_time_unit():
  148. # 0.000977 is the time unit of my CPU
  149. # TODO formula might be different for other CPUs
  150. return 1.0 / 2**readmsr(0x606, 16, 19, cpu=0)
  151. def get_power_unit():
  152. # 0.125 is the power unit of my CPU
  153. # TODO formula might be different for other CPUs
  154. return 1.0 / 2**readmsr(0x606, 0, 3, cpu=0)
  155. def get_critical_temp():
  156. # the critical temperature for my CPU is 100 'C
  157. return readmsr(0x1a2, 16, 23, cpu=0)
  158. def calc_time_window_vars(t):
  159. time_unit = get_time_unit()
  160. for Y in range(2**5):
  161. for Z in range(2**2):
  162. if t <= (2**Y) * (1. + Z / 4.) * time_unit:
  163. return (Y, Z)
  164. raise ValueError('Unable to find a good combination!')
  165. def calc_undervolt_msr(plane, offset):
  166. """Return the value to be written in the MSR 150h for setting the given
  167. offset voltage (in mV) to the given voltage plane.
  168. """
  169. assert offset <= 0
  170. assert plane in VOLTAGE_PLANES
  171. offset = int(round(offset * 1.024))
  172. offset = 0xFFE00000 & ((offset & 0xFFF) << 21)
  173. return 0x8000001100000000 | (VOLTAGE_PLANES[plane] << 40) | offset
  174. def calc_undervolt_mv(msr_value):
  175. """Return the offset voltage (in mV) from the given raw MSR 150h value.
  176. """
  177. offset = (msr_value & 0xFFE00000) >> 21
  178. offset = offset if offset <= 0x400 else -(0x800 - offset)
  179. return int(round(offset / 1.024))
  180. def undervolt(config):
  181. for plane in VOLTAGE_PLANES:
  182. write_offset_mv = config.getfloat('UNDERVOLT', plane)
  183. write_value = calc_undervolt_msr(plane, write_offset_mv)
  184. writemsr(0x150, write_value)
  185. if args.debug:
  186. write_value &= 0xFFFFFFFF
  187. writemsr(0x150, 0x8000001000000000 | (VOLTAGE_PLANES[plane] << 40))
  188. read_value = readmsr(0x150, flatten=True)
  189. read_offset_mv = calc_undervolt_mv(read_value)
  190. match = OK if write_value == read_value else ERR
  191. print('[D] Undervolt plane {:s} - write {:.0f} mV ({:#x}) - read {:.0f} mV ({:#x}) - match {}'.format(
  192. plane, write_offset_mv, write_value, read_offset_mv, read_value, match))
  193. def load_config():
  194. config = configparser.ConfigParser()
  195. config.read(args.config)
  196. # config values sanity check
  197. for power_source in ('AC', 'BATTERY'):
  198. for option in (
  199. 'Update_Rate_s',
  200. 'PL1_Tdp_W',
  201. 'PL1_Duration_s',
  202. 'PL2_Tdp_W',
  203. 'PL2_Duration_S',
  204. ):
  205. config.set(power_source, option, str(max(0.1, config.getfloat(power_source, option))))
  206. trip_temp = config.getfloat(power_source, 'Trip_Temp_C')
  207. valid_trip_temp = min(TRIP_TEMP_RANGE[1], max(TRIP_TEMP_RANGE[0], trip_temp))
  208. if trip_temp != valid_trip_temp:
  209. config.set(power_source, 'Trip_Temp_C', str(valid_trip_temp))
  210. print('[!] Overriding invalid "Trip_Temp_C" value in "{:s}": {:.1f} -> {:.1f}'.format(
  211. power_source, trip_temp, valid_trip_temp))
  212. for plane in VOLTAGE_PLANES:
  213. value = config.getfloat('UNDERVOLT', plane)
  214. valid_value = min(0, value)
  215. if value != valid_value:
  216. config.set('UNDERVOLT', plane, str(valid_value))
  217. print('[!] Overriding invalid "UNDERVOLT" value in "{:s}" voltage plane: {:.0f} -> {:.0f}'.format(
  218. plane, value, valid_value))
  219. return config
  220. def calc_reg_values(platform_info, config):
  221. regs = defaultdict(dict)
  222. for power_source in ('AC', 'BATTERY'):
  223. if platform_info['feature_programmable_temperature_target'] != 1:
  224. print("[W] Setting temperature target is not supported by this CPU")
  225. else:
  226. # the critical temperature for my CPU is 100 'C
  227. critical_temp = get_critical_temp()
  228. # update the allowed temp range to keep at least 3 'C from the CPU critical temperature
  229. global TRIP_TEMP_RANGE
  230. TRIP_TEMP_RANGE[1] = min(TRIP_TEMP_RANGE[1], critical_temp - 3)
  231. trip_offset = int(round(critical_temp - config.getfloat(power_source, 'Trip_Temp_C')))
  232. regs[power_source]['MSR_TEMPERATURE_TARGET'] = trip_offset << 24
  233. power_unit = get_power_unit()
  234. PL1 = int(round(config.getfloat(power_source, 'PL1_Tdp_W') / power_unit))
  235. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL1_Duration_s'))
  236. TW1 = Y | (Z << 5)
  237. PL2 = int(round(config.getfloat(power_source, 'PL2_Tdp_W') / power_unit))
  238. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL2_Duration_s'))
  239. TW2 = Y | (Z << 5)
  240. regs[power_source]['MSR_PKG_POWER_LIMIT'] = PL1 | (1 << 15) | (TW1 << 17) | (PL2 << 32) | (1 << 47) | (
  241. TW2 << 49)
  242. # cTDP
  243. c_tdp_target_value = config.getint(power_source, 'cTDP', fallback=None)
  244. if c_tdp_target_value is not None:
  245. if platform_info['feature_programmable_tdp_limit'] != 1:
  246. print("[W] cTDP setting not supported by this CPU")
  247. elif platform_info['number_of_additional_tdp_profiles'] < c_tdp_target_value:
  248. print("[W] the configured cTDP profile is not supported by this CPU")
  249. else:
  250. valid_c_tdp_target_value = max(0, c_tdp_target_value)
  251. regs[power_source]['MSR_CONFIG_TDP_CONTROL'] = valid_c_tdp_target_value
  252. return regs
  253. def set_hwp(pref):
  254. # set HWP energy performance hints
  255. assert pref in ('performance', 'balance_performance', 'default', 'balance_power', 'power')
  256. CPUs = [
  257. '/sys/devices/system/cpu/cpu{:d}/cpufreq/energy_performance_preference'.format(x) for x in range(cpu_count())
  258. ]
  259. for i, c in enumerate(CPUs):
  260. with open(c, 'wb') as f:
  261. f.write(pref.encode())
  262. if args.debug:
  263. with open(c) as f:
  264. read_value = f.read().strip()
  265. match = OK if pref == read_value else ERR
  266. print('[D] HWP for cpu{:d} - write "{:s}" - read "{:s}" - match {}'.format(i, pref, read_value, match))
  267. def power_thread(config, regs, exit_event):
  268. try:
  269. mchbar_mmio = MMIO(0xfed159a0, 8)
  270. except MMIOError:
  271. print('[E] Unable to open /dev/mem. Try to disable Secure Boot.')
  272. sys.exit(1)
  273. while not exit_event.is_set():
  274. #print thermal status
  275. if args.debug:
  276. thermal_status = get_reset_thermal_status()
  277. for index, core_thermal_status in enumerate(thermal_status):
  278. for key, value in core_thermal_status.items():
  279. print('[D] core {} thermal status: {} = {}'.format(index, key.replace("_", " "), value))
  280. # switch back to sysfs polling
  281. if power['method'] == 'polling':
  282. power['source'] = 'BATTERY' if is_on_battery(config) else 'AC'
  283. # set temperature trip point
  284. if 'MSR_TEMPERATURE_TARGET' in regs[power['source']]:
  285. write_value = regs[power['source']]['MSR_TEMPERATURE_TARGET']
  286. writemsr(0x1a2, write_value)
  287. if args.debug:
  288. read_value = readmsr(0x1a2, 24, 29, flatten=True)
  289. match = OK if write_value >> 24 == read_value else ERR
  290. print('[D] TEMPERATURE_TARGET - write {:#x} - read {:#x} - match {}'.format(
  291. write_value >> 24, read_value, match))
  292. # set cTDP
  293. if 'MSR_CONFIG_TDP_CONTROL' in regs[power['source']]:
  294. write_value = regs[power['source']]['MSR_CONFIG_TDP_CONTROL']
  295. writemsr(0x64b, write_value)
  296. if args.debug:
  297. read_value = readmsr(0x64b, 0, 1, flatten=True)
  298. match = OK if write_value == read_value else ERR
  299. print('[D] CONFIG_TDP_CONTROL - write {:#x} - read {:#x} - match {}'.format(
  300. write_value, read_value, match))
  301. # set PL1/2 on MSR
  302. write_value = regs[power['source']]['MSR_PKG_POWER_LIMIT']
  303. writemsr(0x610, write_value)
  304. if args.debug:
  305. read_value = readmsr(0x610, 0, 55, flatten=True)
  306. match = OK if write_value == read_value else ERR
  307. print('[D] MSR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x} - match {}'.format(
  308. write_value, read_value, match))
  309. # set MCHBAR register to the same PL1/2 values
  310. mchbar_mmio.write32(0, write_value & 0xffffffff)
  311. mchbar_mmio.write32(4, write_value >> 32)
  312. if args.debug:
  313. read_value = mchbar_mmio.read32(0) | (mchbar_mmio.read32(4) << 32)
  314. match = OK if write_value == read_value else ERR
  315. print('[D] MCHBAR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x} - match {}'.format(
  316. write_value, read_value, match))
  317. wait_t = config.getfloat(power['source'], 'Update_Rate_s')
  318. enable_hwp_mode = config.getboolean('AC', 'HWP_Mode', fallback=False)
  319. if power['source'] == 'AC' and enable_hwp_mode:
  320. cpu_usage = float(psutil.cpu_percent(interval=wait_t))
  321. # set full performance mode only when load is greater than this threshold (~ at least 1 core full speed)
  322. performance_mode = cpu_usage > 100. / (cpu_count() * 1.25)
  323. # check again if we are on AC, since in the meantime we might have switched to BATTERY
  324. if not is_on_battery(config):
  325. set_hwp('performance' if performance_mode else 'balance_performance')
  326. else:
  327. exit_event.wait(wait_t)
  328. def main():
  329. global args
  330. if os.geteuid() != 0:
  331. print('[E] No root no party. Try again with sudo.')
  332. sys.exit(1)
  333. parser = argparse.ArgumentParser()
  334. parser.add_argument('--debug', action='store_true', help='add some debug info and additional checks')
  335. parser.add_argument('--config', default='/etc/lenovo_fix.conf', help='override default config file path')
  336. args = parser.parse_args()
  337. config = load_config()
  338. power['source'] = 'BATTERY' if is_on_battery(config) else 'AC'
  339. platform_info = get_cpu_platform_info()
  340. if args.debug:
  341. for key, value in platform_info.items():
  342. print('[D] cpu platform info: {} = {}'.format(key.replace("_", " "), value))
  343. regs = calc_reg_values(platform_info, config)
  344. if not config.getboolean('GENERAL', 'Enabled'):
  345. return
  346. exit_event = Event()
  347. thread = Thread(target=power_thread, args=(config, regs, exit_event))
  348. thread.daemon = True
  349. thread.start()
  350. undervolt(config)
  351. # handle dbus events for applying undervolt on resume from sleep/hybernate
  352. def handle_sleep_callback(sleeping):
  353. if not sleeping:
  354. undervolt(config)
  355. def handle_ac_callback(*args):
  356. try:
  357. power['source'] = 'BATTERY' if args[1]['Online'] == 0 else 'AC'
  358. power['method'] = 'dbus'
  359. except:
  360. power['method'] = 'polling'
  361. DBusGMainLoop(set_as_default=True)
  362. bus = dbus.SystemBus()
  363. # add dbus receiver only if undervolt is enabled in config
  364. if any(config.getfloat('UNDERVOLT', plane) != 0 for plane in VOLTAGE_PLANES):
  365. bus.add_signal_receiver(handle_sleep_callback, 'PrepareForSleep', 'org.freedesktop.login1.Manager',
  366. 'org.freedesktop.login1')
  367. bus.add_signal_receiver(
  368. handle_ac_callback,
  369. signal_name="PropertiesChanged",
  370. dbus_interface="org.freedesktop.DBus.Properties",
  371. path="/org/freedesktop/UPower/devices/line_power_AC")
  372. try:
  373. loop = GLib.MainLoop()
  374. loop.run()
  375. except (KeyboardInterrupt, SystemExit):
  376. pass
  377. exit_event.set()
  378. loop.quit()
  379. thread.join(timeout=1)
  380. if __name__ == '__main__':
  381. main()