lenovo_fix.py 16 KB

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