lenovo_fix.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. print('[D] Undervolt plane {:s} - write {:#x} - read {:#x}'.format(plane, write_value, read_value))
  102. def calc_undervolt_msr(plane, offset):
  103. assert offset <= 0
  104. assert plane in VOLTAGE_PLANES
  105. offset = int(round(offset * 1.024))
  106. offset = 0xFFE00000 & ((offset & 0xFFF) << 21)
  107. return 0x8000001100000000 | (VOLTAGE_PLANES[plane] << 40) | offset
  108. def load_config():
  109. config = configparser.ConfigParser()
  110. config.read(args.config)
  111. # config values sanity check
  112. for power_source in ('AC', 'BATTERY'):
  113. for option in (
  114. 'Update_Rate_s',
  115. 'PL1_Tdp_W',
  116. 'PL1_Duration_s',
  117. 'PL2_Tdp_W',
  118. 'PL2_Duration_S',
  119. ):
  120. config.set(power_source, option, str(max(0.1, config.getfloat(power_source, option))))
  121. trip_temp = config.getfloat(power_source, 'Trip_Temp_C')
  122. valid_trip_temp = min(TRIP_TEMP_RANGE[1], max(TRIP_TEMP_RANGE[0], trip_temp))
  123. if trip_temp != valid_trip_temp:
  124. config.set(power_source, 'Trip_Temp_C', str(valid_trip_temp))
  125. print('[!] Overriding invalid "Trip_Temp_C" value in "{:s}": {:.1f} -> {:.1f}'.format(
  126. power_source, trip_temp, valid_trip_temp))
  127. for plane in VOLTAGE_PLANES:
  128. value = config.getfloat('UNDERVOLT', plane)
  129. valid_value = min(0, value)
  130. if value != valid_value:
  131. config.set('UNDERVOLT', plane, str(valid_value))
  132. print('[!] Overriding invalid "UNDERVOLT" value in "{:s}" voltage plane: {:.0f} -> {:.0f}'.format(
  133. plane, value, valid_value))
  134. return config
  135. def calc_reg_values(config):
  136. regs = defaultdict(dict)
  137. for power_source in ('AC', 'BATTERY'):
  138. if readmsr(0xce, 30, 30, cpu=0) != 1:
  139. print("[W] Setting temperature target is not supported by this CPU")
  140. else:
  141. # the critical temperature for my CPU is 100 'C
  142. critical_temp = readmsr(0x1a2, 16, 23, cpu=0)
  143. # update the allowed temp range to keep at least 3 'C from the CPU critical temperature
  144. global TRIP_TEMP_RANGE
  145. TRIP_TEMP_RANGE[1] = min(TRIP_TEMP_RANGE[1], critical_temp - 3)
  146. trip_offset = int(round(critical_temp - config.getfloat(power_source, 'Trip_Temp_C')))
  147. regs[power_source]['MSR_TEMPERATURE_TARGET'] = trip_offset << 24
  148. # 0.125 is the power unit of my CPU
  149. power_unit = 1.0 / 2**readmsr(0x606, 0, 3, cpu=0)
  150. PL1 = int(round(config.getfloat(power_source, 'PL1_Tdp_W') / power_unit))
  151. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL1_Duration_s'))
  152. TW1 = Y | (Z << 5)
  153. PL2 = int(round(config.getfloat(power_source, 'PL2_Tdp_W') / power_unit))
  154. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL2_Duration_s'))
  155. TW2 = Y | (Z << 5)
  156. regs[power_source]['MSR_PKG_POWER_LIMIT'] = PL1 | (1 << 15) | (TW1 << 17) | (PL2 << 32) | (1 << 47) | (
  157. TW2 << 49)
  158. # cTDP
  159. c_tdp_target_value = config.getint(power_source, 'cTDP', fallback=None)
  160. if c_tdp_target_value is not None:
  161. if readmsr(0xce, 33, 34, cpu=0) < 2:
  162. print("[W] cTDP setting not supported by this CPU")
  163. else:
  164. valid_c_tdp_target_value = min(C_TDP_RANGE[1], max(C_TDP_RANGE[0], c_tdp_target_value))
  165. regs[power_source]['MSR_CONFIG_TDP_CONTROL'] = valid_c_tdp_target_value
  166. return regs
  167. def set_hwp(pref):
  168. # set HWP energy performance hints
  169. assert pref in ('performance', 'balance_performance', 'default', 'balance_power', 'power')
  170. CPUs = ['/sys/devices/system/cpu/cpu{:d}/cpufreq/energy_performance_preference'.format(x) for x in range(cpu_count())]
  171. for i, c in enumerate(CPUs):
  172. with open(c, 'wb') as f:
  173. f.write(pref.encode())
  174. if args.debug:
  175. with open(c) as f:
  176. print('[D] HWP for cpu{:d} - write "{:s}" - read "{:s}"'.format(i, pref, f.read().strip()))
  177. def power_thread(config, regs, exit_event):
  178. try:
  179. mchbar_mmio = MMIO(0xfed159a0, 8)
  180. except MMIOError:
  181. print('[E] Unable to open /dev/mem. Try to disable Secure Boot.')
  182. sys.exit(1)
  183. while not exit_event.is_set():
  184. # switch back to sysfs polling
  185. if power['method'] == 'polling':
  186. power['source'] = 'BATTERY' if is_on_battery() else 'AC'
  187. # set temperature trip point
  188. if 'MSR_TEMPERATURE_TARGET' in regs[power['source']]:
  189. write_value = regs[power['source']]['MSR_TEMPERATURE_TARGET']
  190. writemsr(0x1a2, write_value)
  191. if args.debug:
  192. read_value = readmsr(0x1a2, 24, 29, flatten=True)
  193. print('[D] TEMPERATURE_TARGET - write {:#x} - read {:#x}'.format(write_value >> 24, read_value))
  194. # set cTDP
  195. if 'MSR_CONFIG_TDP_CONTROL' in regs[power['source']]:
  196. write_value = regs[power['source']]['MSR_CONFIG_TDP_CONTROL']
  197. writemsr(0x64b, write_value)
  198. if args.debug:
  199. read_value = readmsr(0x64b, 0, 1, flatten=True)
  200. print('[D] CONFIG_TDP_CONTROL - write {:#x} - read {:#x}'.format(write_value, read_value))
  201. # set PL1/2 on MSR
  202. write_value = regs[power['source']]['MSR_PKG_POWER_LIMIT']
  203. writemsr(0x610, write_value)
  204. if args.debug:
  205. read_value = readmsr(0x610, 0, 55, flatten=True)
  206. print('[D] MSR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x}'.format(write_value, read_value))
  207. # set MCHBAR register to the same PL1/2 values
  208. mchbar_mmio.write32(0, write_value & 0xffffffff)
  209. mchbar_mmio.write32(4, write_value >> 32)
  210. if args.debug:
  211. read_value = mchbar_mmio.read32(0) | (mchbar_mmio.read32(4) << 32)
  212. print('[D] MCHBAR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x}'.format(write_value, read_value))
  213. wait_t = config.getfloat(power['source'], 'Update_Rate_s')
  214. enable_hwp_mode = config.getboolean('AC', 'HWP_Mode', fallback=False)
  215. if power['source'] == 'AC' and enable_hwp_mode:
  216. cpu_usage = float(psutil.cpu_percent(interval=wait_t))
  217. # set full performance mode only when load is greater than this threshold (~ at least 1 core full speed)
  218. performance_mode = cpu_usage > 100. / (cpu_count() * 1.25)
  219. # check again if we are on AC, since in the meantime we might have switched to BATTERY
  220. if not is_on_battery():
  221. set_hwp('performance' if performance_mode else 'balance_performance')
  222. else:
  223. exit_event.wait(wait_t)
  224. def main():
  225. global args
  226. if os.geteuid() != 0:
  227. print('[E] No root no party. Try again with sudo.')
  228. sys.exit(1)
  229. parser = argparse.ArgumentParser()
  230. parser.add_argument('--debug', action='store_true', help='add some debug info and additional checks')
  231. parser.add_argument('--config', default='/etc/lenovo_fix.conf', help='override default config file path')
  232. args = parser.parse_args()
  233. power['source'] = 'BATTERY' if is_on_battery() else 'AC'
  234. config = load_config()
  235. regs = calc_reg_values(config)
  236. if not config.getboolean('GENERAL', 'Enabled'):
  237. return
  238. exit_event = Event()
  239. thread = Thread(target=power_thread, args=(config, regs, exit_event))
  240. thread.daemon = True
  241. thread.start()
  242. undervolt(config)
  243. # handle dbus events for applying undervolt on resume from sleep/hybernate
  244. def handle_sleep_callback(sleeping):
  245. if not sleeping:
  246. undervolt(config)
  247. def handle_ac_callback(*args):
  248. try:
  249. power['source'] = 'BATTERY' if args[1]['Online'] == 0 else 'AC'
  250. power['method'] = 'dbus'
  251. except:
  252. power['method'] = 'polling'
  253. DBusGMainLoop(set_as_default=True)
  254. bus = dbus.SystemBus()
  255. # add dbus receiver only if undervolt is enabled in config
  256. if any(config.getfloat('UNDERVOLT', plane) != 0 for plane in VOLTAGE_PLANES):
  257. bus.add_signal_receiver(handle_sleep_callback, 'PrepareForSleep', 'org.freedesktop.login1.Manager',
  258. 'org.freedesktop.login1')
  259. bus.add_signal_receiver(
  260. handle_ac_callback,
  261. signal_name="PropertiesChanged",
  262. dbus_interface="org.freedesktop.DBus.Properties",
  263. path="/org/freedesktop/UPower/devices/line_power_AC")
  264. try:
  265. GObject.threads_init()
  266. loop = GObject.MainLoop()
  267. loop.run()
  268. except (KeyboardInterrupt, SystemExit):
  269. pass
  270. exit_event.set()
  271. loop.quit()
  272. thread.join(timeout=1)
  273. if __name__ == '__main__':
  274. main()