lenovo_fix.py 6.5 KB

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