lenovo_fix.py 8.2 KB

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