lenovo_fix.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. C_TDP_RANGE = (0, 2)
  30. power = {'source': None, 'method': 'polling'}
  31. def writemsr(msr, val):
  32. msr_list = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  33. if not os.path.exists(msr_list[0]):
  34. try:
  35. subprocess.check_call(('modprobe', 'msr'))
  36. except subprocess.CalledProcessError:
  37. print('[E] Unable to load the msr module.')
  38. sys.exit(1)
  39. try:
  40. for addr in msr_list:
  41. f = os.open(addr, os.O_WRONLY)
  42. os.lseek(f, msr, os.SEEK_SET)
  43. os.write(f, struct.pack('Q', val))
  44. os.close(f)
  45. except (IOError, OSError) as e:
  46. if e.errno == EPERM or e.errno == EACCES:
  47. print('[E] Unable to write to MSR. Try to disable Secure Boot.')
  48. sys.exit(1)
  49. else:
  50. raise e
  51. # returns the value between from_bit and to_bit as unsigned long
  52. def readmsr(msr, from_bit=0, to_bit=63, cpu=None, flatten=False):
  53. assert cpu is None or cpu in range(cpu_count())
  54. if from_bit > to_bit:
  55. print('[E] Wrong readmsr bit params')
  56. sys.exit(1)
  57. msr_list = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  58. if not os.path.exists(msr_list[0]):
  59. try:
  60. subprocess.check_call(('modprobe', 'msr'))
  61. except subprocess.CalledProcessError:
  62. print('[E] Unable to load the msr module.')
  63. sys.exit(1)
  64. try:
  65. output = []
  66. for addr in msr_list:
  67. f = os.open(addr, os.O_RDONLY)
  68. os.lseek(f, msr, os.SEEK_SET)
  69. val = struct.unpack('Q', os.read(f, 8))[0]
  70. os.close(f)
  71. mask = sum(2**x for x in range(from_bit, to_bit + 1))
  72. output.append((val & mask) >> from_bit)
  73. if flatten:
  74. return output[0] if len(set(output)) == 1 else output
  75. return output[cpu] if cpu is not None else output
  76. except (IOError, OSError) as e:
  77. if e.errno == EPERM or e.errno == EACCES:
  78. print('[E] Unable to read from MSR. Try to disable Secure Boot.')
  79. sys.exit(1)
  80. else:
  81. raise e
  82. def is_on_battery():
  83. with open(SYSFS_POWER_PATH) as f:
  84. return not bool(int(f.read()))
  85. def calc_time_window_vars(t):
  86. # 0.000977 is the time unit of my CPU
  87. time_unit = 1.0 / 2**readmsr(0x606, 16, 19, cpu=0)
  88. for Y in range(2**5):
  89. for Z in range(2**2):
  90. if t <= (2**Y) * (1. + Z / 4.) * time_unit:
  91. return (Y, Z)
  92. raise ValueError('Unable to find a good combination!')
  93. def undervolt(config):
  94. for plane in VOLTAGE_PLANES:
  95. write_value = calc_undervolt_msr(plane, config.getfloat('UNDERVOLT', plane))
  96. writemsr(0x150, write_value)
  97. if args.debug:
  98. write_value &= 0xFFFFFFFF
  99. writemsr(0x150, 0x8000001000000000 | (VOLTAGE_PLANES[plane] << 40))
  100. read_value = readmsr(0x150, flatten=True)
  101. match = write_value == read_value
  102. print('[D] Undervolt plane {:s} - write {:#x} - read {:#x} - match {}'.format(
  103. plane, write_value, read_value, match))
  104. def calc_undervolt_msr(plane, offset):
  105. assert offset <= 0
  106. assert plane in VOLTAGE_PLANES
  107. offset = int(round(offset * 1.024))
  108. offset = 0xFFE00000 & ((offset & 0xFFF) << 21)
  109. return 0x8000001100000000 | (VOLTAGE_PLANES[plane] << 40) | offset
  110. def load_config():
  111. config = configparser.ConfigParser()
  112. config.read(args.config)
  113. # config values sanity check
  114. for power_source in ('AC', 'BATTERY'):
  115. for option in (
  116. 'Update_Rate_s',
  117. 'PL1_Tdp_W',
  118. 'PL1_Duration_s',
  119. 'PL2_Tdp_W',
  120. 'PL2_Duration_S',
  121. ):
  122. config.set(power_source, option, str(max(0.1, config.getfloat(power_source, option))))
  123. trip_temp = config.getfloat(power_source, 'Trip_Temp_C')
  124. valid_trip_temp = min(TRIP_TEMP_RANGE[1], max(TRIP_TEMP_RANGE[0], trip_temp))
  125. if trip_temp != valid_trip_temp:
  126. config.set(power_source, 'Trip_Temp_C', str(valid_trip_temp))
  127. print('[!] Overriding invalid "Trip_Temp_C" value in "{:s}": {:.1f} -> {:.1f}'.format(
  128. power_source, trip_temp, valid_trip_temp))
  129. for plane in VOLTAGE_PLANES:
  130. value = config.getfloat('UNDERVOLT', plane)
  131. valid_value = min(0, value)
  132. if value != valid_value:
  133. config.set('UNDERVOLT', plane, str(valid_value))
  134. print('[!] Overriding invalid "UNDERVOLT" value in "{:s}" voltage plane: {:.0f} -> {:.0f}'.format(
  135. plane, value, valid_value))
  136. return config
  137. def calc_reg_values(config):
  138. regs = defaultdict(dict)
  139. for power_source in ('AC', 'BATTERY'):
  140. if readmsr(0xce, 30, 30, cpu=0) != 1:
  141. print("[W] Setting temperature target is not supported by this CPU")
  142. else:
  143. # the critical temperature for my CPU is 100 'C
  144. critical_temp = readmsr(0x1a2, 16, 23, cpu=0)
  145. # update the allowed temp range to keep at least 3 'C from the CPU critical temperature
  146. global TRIP_TEMP_RANGE
  147. TRIP_TEMP_RANGE[1] = min(TRIP_TEMP_RANGE[1], critical_temp - 3)
  148. trip_offset = int(round(critical_temp - config.getfloat(power_source, 'Trip_Temp_C')))
  149. regs[power_source]['MSR_TEMPERATURE_TARGET'] = trip_offset << 24
  150. # 0.125 is the power unit of my CPU
  151. power_unit = 1.0 / 2**readmsr(0x606, 0, 3, cpu=0)
  152. PL1 = int(round(config.getfloat(power_source, 'PL1_Tdp_W') / power_unit))
  153. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL1_Duration_s'))
  154. TW1 = Y | (Z << 5)
  155. PL2 = int(round(config.getfloat(power_source, 'PL2_Tdp_W') / power_unit))
  156. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL2_Duration_s'))
  157. TW2 = Y | (Z << 5)
  158. regs[power_source]['MSR_PKG_POWER_LIMIT'] = PL1 | (1 << 15) | (TW1 << 17) | (PL2 << 32) | (1 << 47) | (
  159. TW2 << 49)
  160. # cTDP
  161. c_tdp_target_value = config.getint(power_source, 'cTDP', fallback=None)
  162. if c_tdp_target_value is not None:
  163. if readmsr(0xce, 33, 34, cpu=0) < 2:
  164. print("[W] cTDP setting not supported by this CPU")
  165. else:
  166. valid_c_tdp_target_value = min(C_TDP_RANGE[1], max(C_TDP_RANGE[0], c_tdp_target_value))
  167. regs[power_source]['MSR_CONFIG_TDP_CONTROL'] = valid_c_tdp_target_value
  168. return regs
  169. def set_hwp(pref):
  170. # set HWP energy performance hints
  171. assert pref in ('performance', 'balance_performance', 'default', 'balance_power', 'power')
  172. CPUs = [
  173. '/sys/devices/system/cpu/cpu{:d}/cpufreq/energy_performance_preference'.format(x) for x in range(cpu_count())
  174. ]
  175. for i, c in enumerate(CPUs):
  176. with open(c, 'wb') as f:
  177. f.write(pref.encode())
  178. if args.debug:
  179. with open(c) as f:
  180. read_value = f.read().strip()
  181. match = pref == read_value
  182. print('[D] HWP for cpu{:d} - write "{:s}" - read "{:s}" - match {}'.format(i, pref, read_value, match))
  183. def power_thread(config, regs, exit_event):
  184. try:
  185. mchbar_mmio = MMIO(0xfed159a0, 8)
  186. except MMIOError:
  187. print('[E] Unable to open /dev/mem. Try to disable Secure Boot.')
  188. sys.exit(1)
  189. while not exit_event.is_set():
  190. # switch back to sysfs polling
  191. if power['method'] == 'polling':
  192. power['source'] = 'BATTERY' if is_on_battery() else 'AC'
  193. # set temperature trip point
  194. if 'MSR_TEMPERATURE_TARGET' in regs[power['source']]:
  195. write_value = regs[power['source']]['MSR_TEMPERATURE_TARGET']
  196. writemsr(0x1a2, write_value)
  197. if args.debug:
  198. read_value = readmsr(0x1a2, 24, 29, flatten=True)
  199. match = write_value >> 24 == read_value
  200. print('[D] TEMPERATURE_TARGET - write {:#x} - read {:#x} - match {}'.format(
  201. write_value >> 24, read_value, match))
  202. # set cTDP
  203. if 'MSR_CONFIG_TDP_CONTROL' in regs[power['source']]:
  204. write_value = regs[power['source']]['MSR_CONFIG_TDP_CONTROL']
  205. writemsr(0x64b, write_value)
  206. if args.debug:
  207. read_value = readmsr(0x64b, 0, 1, flatten=True)
  208. match = write_value == read_value
  209. print('[D] CONFIG_TDP_CONTROL - write {:#x} - read {:#x} - match {}'.format(
  210. write_value, read_value, match))
  211. # set PL1/2 on MSR
  212. write_value = regs[power['source']]['MSR_PKG_POWER_LIMIT']
  213. writemsr(0x610, write_value)
  214. if args.debug:
  215. read_value = readmsr(0x610, 0, 55, flatten=True)
  216. match = write_value == read_value
  217. print('[D] MSR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x} - match {}'.format(
  218. write_value, read_value, match))
  219. # set MCHBAR register to the same PL1/2 values
  220. mchbar_mmio.write32(0, write_value & 0xffffffff)
  221. mchbar_mmio.write32(4, write_value >> 32)
  222. if args.debug:
  223. read_value = mchbar_mmio.read32(0) | (mchbar_mmio.read32(4) << 32)
  224. match = write_value == read_value
  225. print('[D] MCHBAR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x} - match {}'.format(
  226. write_value, read_value, match))
  227. wait_t = config.getfloat(power['source'], 'Update_Rate_s')
  228. enable_hwp_mode = config.getboolean('AC', 'HWP_Mode', fallback=False)
  229. if power['source'] == 'AC' and enable_hwp_mode:
  230. cpu_usage = float(psutil.cpu_percent(interval=wait_t))
  231. # set full performance mode only when load is greater than this threshold (~ at least 1 core full speed)
  232. performance_mode = cpu_usage > 100. / (cpu_count() * 1.25)
  233. # check again if we are on AC, since in the meantime we might have switched to BATTERY
  234. if not is_on_battery():
  235. set_hwp('performance' if performance_mode else 'balance_performance')
  236. else:
  237. exit_event.wait(wait_t)
  238. def main():
  239. global args
  240. if os.geteuid() != 0:
  241. print('[E] No root no party. Try again with sudo.')
  242. sys.exit(1)
  243. parser = argparse.ArgumentParser()
  244. parser.add_argument('--debug', action='store_true', help='add some debug info and additional checks')
  245. parser.add_argument('--config', default='/etc/lenovo_fix.conf', help='override default config file path')
  246. args = parser.parse_args()
  247. power['source'] = 'BATTERY' if is_on_battery() else 'AC'
  248. config = load_config()
  249. regs = calc_reg_values(config)
  250. if not config.getboolean('GENERAL', 'Enabled'):
  251. return
  252. exit_event = Event()
  253. thread = Thread(target=power_thread, args=(config, regs, exit_event))
  254. thread.daemon = True
  255. thread.start()
  256. undervolt(config)
  257. # handle dbus events for applying undervolt on resume from sleep/hybernate
  258. def handle_sleep_callback(sleeping):
  259. if not sleeping:
  260. undervolt(config)
  261. def handle_ac_callback(*args):
  262. try:
  263. power['source'] = 'BATTERY' if args[1]['Online'] == 0 else 'AC'
  264. power['method'] = 'dbus'
  265. except:
  266. power['method'] = 'polling'
  267. DBusGMainLoop(set_as_default=True)
  268. bus = dbus.SystemBus()
  269. # add dbus receiver only if undervolt is enabled in config
  270. if any(config.getfloat('UNDERVOLT', plane) != 0 for plane in VOLTAGE_PLANES):
  271. bus.add_signal_receiver(handle_sleep_callback, 'PrepareForSleep', 'org.freedesktop.login1.Manager',
  272. 'org.freedesktop.login1')
  273. bus.add_signal_receiver(
  274. handle_ac_callback,
  275. signal_name="PropertiesChanged",
  276. dbus_interface="org.freedesktop.DBus.Properties",
  277. path="/org/freedesktop/UPower/devices/line_power_AC")
  278. try:
  279. GObject.threads_init()
  280. loop = GObject.MainLoop()
  281. loop.run()
  282. except (KeyboardInterrupt, SystemExit):
  283. pass
  284. exit_event.set()
  285. loop.quit()
  286. thread.join(timeout=1)
  287. if __name__ == '__main__':
  288. main()