lenovo_fix.py 9.3 KB

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