lenovo_fix.py 12 KB

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