lenovo_fix.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #!/usr/bin/env python3
  2. import configparser
  3. import dbus
  4. import glob
  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. CONFIG_PATH = '/etc/lenovo_fix.conf'
  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. n = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  34. if not os.path.exists(n[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 c in n:
  42. f = os.open(c, 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):
  54. if from_bit > to_bit:
  55. print('wrong readmsr bit params')
  56. sys.exit(1)
  57. n = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  58. if not os.path.exists(n[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. for c in n:
  66. f = os.open(c, os.O_RDONLY)
  67. os.lseek(f, msr, os.SEEK_SET)
  68. val = struct.unpack('Q', os.read(f, 8))[0]
  69. os.close(f)
  70. extractor = int(''.join(["0"]*(63-to_bit) + ["1"]*(to_bit+1-from_bit) + ["0"]*from_bit), 2)
  71. return (val & extractor) >> from_bit
  72. except (IOError, OSError) as e:
  73. if e.errno == EPERM or e.errno == EACCES:
  74. print('[E] Unable to read from MSR. Try to disable Secure Boot.')
  75. sys.exit(1)
  76. else:
  77. raise e
  78. def is_on_battery():
  79. with open(SYSFS_POWER_PATH) as f:
  80. return not bool(int(f.read()))
  81. def calc_time_window_vars(t):
  82. # 0.000977 is the time unit of this CPU
  83. time_unit = 1.0/2**readmsr(0x606, 16, 19)
  84. for Y in range(2**5):
  85. for Z in range(2**2):
  86. if t <= (2**Y) * (1. + Z / 4.) * time_unit:
  87. return (Y, Z)
  88. raise ValueError('Unable to find a good combination!')
  89. def undervolt(config):
  90. for plane in VOLTAGE_PLANES:
  91. writemsr(0x150, calc_undervolt_msr(plane, config.getfloat('UNDERVOLT', plane)))
  92. def calc_undervolt_msr(plane, offset):
  93. assert offset <= 0
  94. assert plane in VOLTAGE_PLANES
  95. offset = int(round(offset * 1.024))
  96. offset = 0xFFE00000 & ((offset & 0xFFF) << 21)
  97. return 0x8000001100000000 | (VOLTAGE_PLANES[plane] << 40) | offset
  98. def load_config():
  99. config = configparser.ConfigParser()
  100. config.read(CONFIG_PATH)
  101. # config values sanity check
  102. for power_source in ('AC', 'BATTERY'):
  103. for option in (
  104. 'Update_Rate_s',
  105. 'PL1_Tdp_W',
  106. 'PL1_Duration_s',
  107. 'PL2_Tdp_W',
  108. 'PL2_Duration_S',
  109. ):
  110. config.set(power_source, option, str(max(0.1, config.getfloat(power_source, option))))
  111. trip_temp = config.getfloat(power_source, 'Trip_Temp_C')
  112. valid_trip_temp = min(TRIP_TEMP_RANGE[1], max(TRIP_TEMP_RANGE[0], trip_temp))
  113. if trip_temp != valid_trip_temp:
  114. config.set(power_source, 'Trip_Temp_C', str(valid_trip_temp))
  115. print('[!] Overriding invalid "Trip_Temp_C" value in "{:s}": {:.1f} -> {:.1f}'.format(
  116. power_source, trip_temp, valid_trip_temp))
  117. for plane in VOLTAGE_PLANES:
  118. value = config.getfloat('UNDERVOLT', plane)
  119. valid_value = min(0, value)
  120. if value != valid_value:
  121. config.set('UNDERVOLT', plane, str(valid_value))
  122. print('[!] Overriding invalid "UNDERVOLT" value in "{:s}" voltage plane: {:.0f} -> {:.0f}'.format(
  123. plane, value, valid_value))
  124. return config
  125. def calc_reg_values(config):
  126. regs = defaultdict(dict)
  127. for power_source in ('AC', 'BATTERY'):
  128. # the critical temperature for this CPU is 100 C
  129. trip_offset = int(round(100 - config.getfloat(power_source, 'Trip_Temp_C')))
  130. regs[power_source]['MSR_TEMPERATURE_TARGET'] = trip_offset << 24
  131. # 0.125 is the power unit of this CPU
  132. power_unit = 1.0/2**readmsr(0x606, 0, 3)
  133. PL1 = int(round(config.getfloat(power_source, 'PL1_Tdp_W') / power_unit))
  134. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL1_Duration_s'))
  135. TW1 = Y | (Z << 5)
  136. PL2 = int(round(config.getfloat(power_source, 'PL2_Tdp_W') / power_unit))
  137. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL2_Duration_s'))
  138. TW2 = Y | (Z << 5)
  139. regs[power_source]['MSR_PKG_POWER_LIMIT'] = PL1 | (1 << 15) | (TW1 << 17) | (PL2 << 32) | (1 << 47) | (
  140. TW2 << 49)
  141. # cTDP
  142. try:
  143. c_tdp_target_value = int(config.getfloat(power_source, 'cTDP'))
  144. valid_c_tdp_target_value = min(C_TDP_RANGE[1], max(C_TDP_RANGE[0], c_tdp_target_value))
  145. regs[power_source]['MSR_CONFIG_TDP_CONTROL'] = valid_c_tdp_target_value
  146. except configparser.NoOptionError:
  147. pass
  148. return regs
  149. def set_hwp(pref):
  150. # set HWP energy performance hints
  151. assert pref in ('performance', 'balance_performance', 'default', 'balance_power', 'power')
  152. n = glob.glob('/sys/devices/system/cpu/cpu[0-9]*/cpufreq/energy_performance_preference')
  153. for c in n:
  154. with open(c, 'wb') as f:
  155. f.write(pref.encode())
  156. def power_thread(config, regs, exit_event):
  157. try:
  158. mchbar_mmio = MMIO(0xfed159a0, 8)
  159. except MMIOError:
  160. print('[E] Unable to open /dev/mem. Try to disable Secure Boot.')
  161. sys.exit(1)
  162. while not exit_event.is_set():
  163. #
  164. if power['method'] == 'polling':
  165. power['source'] = 'BATTERY' if is_on_battery() else 'AC'
  166. # set temperature trip point
  167. if readmsr(0xce, 30, 30) != 1:
  168. print("setting temperature target is not supported by this CPU")
  169. else:
  170. writemsr(0x1a2, regs[power['source']]['MSR_TEMPERATURE_TARGET'])
  171. # set cTDP
  172. if readmsr(0xce, 33, 34) < 2:
  173. print("cTDP setting not supported by this cpu")
  174. else:
  175. writemsr(0x64b, regs[power['source']]['MSR_CONFIG_TDP_CONTROL'])
  176. # set PL1/2 on MSR
  177. writemsr(0x610, regs[power['source']]['MSR_PKG_POWER_LIMIT'])
  178. # set MCHBAR register to the same PL1/2 values
  179. mchbar_mmio.write32(0, regs[power['source']]['MSR_PKG_POWER_LIMIT'] & 0xffffffff)
  180. mchbar_mmio.write32(4, regs[power['source']]['MSR_PKG_POWER_LIMIT'] >> 32)
  181. wait_t = config.getfloat(power['source'], 'Update_Rate_s')
  182. enable_hwp_mode = config.getboolean('AC', 'HWP_Mode', fallback=False)
  183. if power['source'] == 'AC' and enable_hwp_mode:
  184. cpu_usage = float(psutil.cpu_percent(interval=wait_t))
  185. # set full performance mode only when load is greater than this threshold (~ at least 1 core full speed)
  186. performance_mode = cpu_usage > 100. / (cpu_count() * 1.25)
  187. # check again if we are on AC, since in the meantime we might have switched to BATTERY
  188. if not is_on_battery():
  189. set_hwp('performance' if performance_mode else 'balance_performance')
  190. else:
  191. exit_event.wait(wait_t)
  192. def main():
  193. if os.geteuid() != 0:
  194. print('[E] No root no party. Try again with sudo.')
  195. sys.exit(1)
  196. power['source'] = 'BATTERY' if is_on_battery() else 'AC'
  197. config = load_config()
  198. regs = calc_reg_values(config)
  199. if not config.getboolean('GENERAL', 'Enabled'):
  200. return
  201. exit_event = Event()
  202. thread = Thread(target=power_thread, args=(config, regs, exit_event))
  203. thread.daemon = True
  204. thread.start()
  205. undervolt(config)
  206. # handle dbus events for applying undervolt on resume from sleep/hybernate
  207. def handle_sleep_callback(sleeping):
  208. if not sleeping:
  209. undervolt(config)
  210. def handle_ac_callback(*args):
  211. try:
  212. power['source'] = 'BATTERY' if args[1]['Online'] == 0 else 'AC'
  213. power['method'] = 'dbus'
  214. except:
  215. power['method'] = 'polling'
  216. DBusGMainLoop(set_as_default=True)
  217. bus = dbus.SystemBus()
  218. # add dbus receiver only if undervolt is enabled in config
  219. if any(config.getfloat('UNDERVOLT', plane) != 0 for plane in VOLTAGE_PLANES):
  220. bus.add_signal_receiver(handle_sleep_callback, 'PrepareForSleep', 'org.freedesktop.login1.Manager',
  221. 'org.freedesktop.login1')
  222. bus.add_signal_receiver(
  223. handle_ac_callback,
  224. signal_name="PropertiesChanged",
  225. dbus_interface="org.freedesktop.DBus.Properties",
  226. path="/org/freedesktop/UPower/devices/line_power_AC")
  227. try:
  228. GObject.threads_init()
  229. loop = GObject.MainLoop()
  230. loop.run()
  231. except (KeyboardInterrupt, SystemExit):
  232. pass
  233. exit_event.set()
  234. loop.quit()
  235. thread.join(timeout=1)
  236. if __name__ == '__main__':
  237. main()