lenovo_fix.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. from collections import defaultdict
  10. from dbus.mainloop.glib import DBusGMainLoop
  11. from mmio import MMIO
  12. from multiprocessing import cpu_count
  13. from threading import Event, Thread
  14. try:
  15. from gi.repository import GObject
  16. except ImportError:
  17. import gobject as GObject
  18. SYSFS_POWER_PATH = '/sys/class/power_supply/AC/online'
  19. CONFIG_PATH = '/etc/lenovo_fix.conf'
  20. VOLTAGE_PLANES = {
  21. 'CORE': 0,
  22. 'GPU': 1,
  23. 'CACHE': 2,
  24. 'UNCORE': 3,
  25. 'ANALOGIO': 4,
  26. }
  27. def writemsr(msr, val):
  28. n = glob.glob('/dev/cpu/[0-9]*/msr')
  29. for c in n:
  30. f = os.open(c, os.O_WRONLY)
  31. os.lseek(f, msr, os.SEEK_SET)
  32. os.write(f, struct.pack('Q', val))
  33. os.close(f)
  34. if not n:
  35. try:
  36. subprocess.check_call(('modprobe', 'msr'))
  37. except subprocess.CalledProcessError:
  38. raise OSError("Unable to load msr module.")
  39. def is_on_battery():
  40. with open(SYSFS_POWER_PATH) as f:
  41. return not bool(int(f.read()))
  42. def calc_time_window_vars(t):
  43. for Y in range(2**5):
  44. for Z in range(2**2):
  45. if t <= (2**Y) * (1. + Z / 4.) * 0.000977:
  46. return (Y, Z)
  47. raise Exception('Unable to find a good combination!')
  48. def undervolt(config):
  49. for plane in VOLTAGE_PLANES:
  50. writemsr(0x150, calc_undervolt_msr(plane, config.getfloat('UNDERVOLT', plane)))
  51. def calc_undervolt_msr(plane, offset):
  52. assert offset <= 0
  53. assert plane in VOLTAGE_PLANES
  54. offset = int(round(offset * 1.024))
  55. offset = 0xFFE00000 & ((offset & 0xFFF) << 21)
  56. return 0x8000001100000000 | (VOLTAGE_PLANES[plane] << 40) | offset
  57. def load_config():
  58. config = configparser.ConfigParser()
  59. config.read(CONFIG_PATH)
  60. for power_source in ('AC', 'BATTERY'):
  61. assert 0 < config.getfloat(power_source, 'Update_Rate_s')
  62. assert 0 < config.getfloat(power_source, 'PL1_Tdp_W')
  63. assert 0 < config.getfloat(power_source, 'PL1_Duration_s')
  64. assert 0 < config.getfloat(power_source, 'PL2_Tdp_W')
  65. assert 0 < config.getfloat(power_source, 'PL2_Duration_S')
  66. assert 40 < config.getfloat(power_source, 'Trip_Temp_C') < 98
  67. for plane in VOLTAGE_PLANES:
  68. assert config.getfloat('UNDERVOLT', plane) <= 0
  69. return config
  70. def calc_reg_values(config):
  71. regs = defaultdict(dict)
  72. for power_source in ('AC', 'BATTERY'):
  73. # the critical temperature for this CPU is 100 C
  74. trip_offset = int(round(100 - config.getfloat(power_source, 'Trip_Temp_C')))
  75. regs[power_source]['MSR_TEMPERATURE_TARGET'] = trip_offset << 24
  76. # 0.125 is the power unit of this CPU
  77. PL1 = int(round(config.getfloat(power_source, 'PL1_Tdp_W') / 0.125))
  78. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL1_Duration_s'))
  79. TW1 = Y | (Z << 5)
  80. PL2 = int(round(config.getfloat(power_source, 'PL2_Tdp_W') / 0.125))
  81. Y, Z = calc_time_window_vars(config.getfloat(power_source, 'PL2_Duration_s'))
  82. TW2 = Y | (Z << 5)
  83. regs[power_source]['MSR_PKG_POWER_LIMIT'] = PL1 | (1 << 15) | (TW1 << 17) | (PL2 << 32) | (1 << 47) | (
  84. TW2 << 49)
  85. return regs
  86. def set_hwp(pref):
  87. # set HWP energy performance hints
  88. assert pref in ('performance', 'balance_performance', 'default', 'balance_power', 'power')
  89. n = glob.glob('/sys/devices/system/cpu/cpu[0-9]*/cpufreq/energy_performance_preference')
  90. for c in n:
  91. with open(c, 'wb') as f:
  92. f.write(pref.encode())
  93. def power_thread(config, regs, exit_event):
  94. mchbar_mmio = MMIO(0xfed159a0, 8)
  95. while not exit_event.is_set():
  96. power_source = 'BATTERY' if is_on_battery() else 'AC'
  97. # set temperature trip point
  98. writemsr(0x1a2, regs[power_source]['MSR_TEMPERATURE_TARGET'])
  99. # set PL1/2 on MSR
  100. writemsr(0x610, regs[power_source]['MSR_PKG_POWER_LIMIT'])
  101. # set MCHBAR register to the same PL1/2 values
  102. mchbar_mmio.write32(0, regs[power_source]['MSR_PKG_POWER_LIMIT'] & 0xffffffff)
  103. mchbar_mmio.write32(4, regs[power_source]['MSR_PKG_POWER_LIMIT'] >> 32)
  104. wait_t = config.getfloat(power_source, 'Update_Rate_s')
  105. enable_hwp_mode = config.getboolean('AC', 'HWP_Mode', fallback=False)
  106. if power_source == 'AC' and enable_hwp_mode:
  107. cpu_usage = float(psutil.cpu_percent(interval=wait_t))
  108. # set full performance mode only when load is greater than this threshold (~ at least 1 core full speed)
  109. performance_mode = cpu_usage > 100. / (cpu_count() * 1.25)
  110. # check again if we are on AC, since in the meantime we might have switched to BATTERY
  111. if not is_on_battery():
  112. set_hwp('performance' if performance_mode else 'balance_performance')
  113. else:
  114. exit_event.wait(wait_t)
  115. def main():
  116. config = load_config()
  117. regs = calc_reg_values(config)
  118. if not config.getboolean('GENERAL', 'Enabled'):
  119. return
  120. exit_event = Event()
  121. t = Thread(target=power_thread, args=(config, regs, exit_event))
  122. t.daemon = True
  123. t.start()
  124. undervolt(config)
  125. # handle dbus events for applying undervolt on resume from sleep/hybernate
  126. def handle_sleep_callback(sleeping):
  127. if not sleeping:
  128. undervolt(config)
  129. DBusGMainLoop(set_as_default=True)
  130. bus = dbus.SystemBus()
  131. # add dbus receiver only if undervolt is enabled in config
  132. if any(config.getfloat('UNDERVOLT', plane) != 0 for plane in VOLTAGE_PLANES):
  133. bus.add_signal_receiver(handle_sleep_callback, 'PrepareForSleep', 'org.freedesktop.login1.Manager',
  134. 'org.freedesktop.login1')
  135. try:
  136. GObject.threads_init()
  137. loop = GObject.MainLoop()
  138. loop.run()
  139. except (KeyboardInterrupt, SystemExit):
  140. pass
  141. exit_event.set()
  142. loop.quit()
  143. t.join(timeout=1)
  144. if __name__ == '__main__':
  145. main()