lenovo_fix.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #!/usr/bin/env python3
  2. from __future__ import print_function
  3. import argparse
  4. import configparser
  5. import dbus
  6. import glob
  7. import os
  8. import re
  9. import struct
  10. import subprocess
  11. import sys
  12. from collections import defaultdict
  13. from dbus.mainloop.glib import DBusGMainLoop
  14. from errno import EACCES, EPERM
  15. from gi.repository import GLib
  16. from mmio import MMIO, MMIOError
  17. from multiprocessing import cpu_count
  18. from platform import uname
  19. from threading import Event, Thread
  20. DEFAULT_SYSFS_POWER_PATH = '/sys/class/power_supply/AC*/online'
  21. VOLTAGE_PLANES = {'CORE': 0, 'GPU': 1, 'CACHE': 2, 'UNCORE': 3, 'ANALOGIO': 4}
  22. TRIP_TEMP_RANGE = [40, 97]
  23. power = {'source': None, 'method': 'polling'}
  24. platform_info_bits = {
  25. 'maximum_non_turbo_ratio': [8, 15],
  26. 'maximum_efficiency_ratio': [40, 47],
  27. 'minimum_operating_ratio': [48, 55],
  28. 'feature_ppin_cap': [23, 23],
  29. 'feature_programmable_turbo_ratio': [28, 28],
  30. 'feature_programmable_tdp_limit': [29, 29],
  31. 'number_of_additional_tdp_profiles': [33, 34],
  32. 'feature_programmable_temperature_target': [30, 30],
  33. 'feature_low_power_mode': [32, 32],
  34. }
  35. thermal_status_bits = {
  36. 'thermal_limit_status': [0, 0],
  37. 'thermal_limit_log': [1, 1],
  38. 'prochot_or_forcepr_status': [2, 2],
  39. 'prochot_or_forcepr_log': [3, 3],
  40. 'crit_temp_status': [4, 4],
  41. 'crit_temp_log': [5, 5],
  42. 'thermal_threshold1_status': [6, 6],
  43. 'thermal_threshold1_log': [7, 7],
  44. 'thermal_threshold2_status': [8, 8],
  45. 'thermal_threshold2_log': [9, 9],
  46. 'power_limit_status': [10, 10],
  47. 'power_limit_log': [11, 11],
  48. 'current_limit_status': [12, 12],
  49. 'current_limit_log': [13, 13],
  50. 'cross_domain_limit_status': [14, 14],
  51. 'cross_domain_limit_log': [15, 15],
  52. 'cpu_temp': [16, 22],
  53. 'temp_resolution': [27, 30],
  54. 'reading_valid': [31, 31],
  55. }
  56. class bcolors:
  57. YELLOW = '\033[93m'
  58. GREEN = '\033[92m'
  59. RED = '\033[91m'
  60. RESET = '\033[0m'
  61. BOLD = '\033[1m'
  62. OK = bcolors.GREEN + bcolors.BOLD + 'OK' + bcolors.RESET
  63. ERR = bcolors.RED + bcolors.BOLD + 'ERR' + bcolors.RESET
  64. LIM = bcolors.YELLOW + bcolors.BOLD + 'LIM' + bcolors.RESET
  65. def writemsr(msr, val):
  66. msr_list = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  67. if not os.path.exists(msr_list[0]):
  68. try:
  69. subprocess.check_call(('modprobe', 'msr'))
  70. except subprocess.CalledProcessError:
  71. print('[E] Unable to load the msr module.')
  72. sys.exit(1)
  73. try:
  74. for addr in msr_list:
  75. f = os.open(addr, os.O_WRONLY)
  76. os.lseek(f, msr, os.SEEK_SET)
  77. os.write(f, struct.pack('Q', val))
  78. os.close(f)
  79. except (IOError, OSError) as e:
  80. if e.errno == EPERM or e.errno == EACCES:
  81. print(
  82. '[E] Unable to write to MSR. Try to disable Secure Boot '
  83. 'and check if your kernel does not restrict access to MSR.'
  84. )
  85. sys.exit(1)
  86. else:
  87. raise e
  88. # returns the value between from_bit and to_bit as unsigned long
  89. def readmsr(msr, from_bit=0, to_bit=63, cpu=None, flatten=False):
  90. assert cpu is None or cpu in range(cpu_count())
  91. if from_bit > to_bit:
  92. print('[E] Wrong readmsr bit params')
  93. sys.exit(1)
  94. msr_list = ['/dev/cpu/{:d}/msr'.format(x) for x in range(cpu_count())]
  95. if not os.path.exists(msr_list[0]):
  96. try:
  97. subprocess.check_call(('modprobe', 'msr'))
  98. except subprocess.CalledProcessError:
  99. print('[E] Unable to load the msr module.')
  100. sys.exit(1)
  101. try:
  102. output = []
  103. for addr in msr_list:
  104. f = os.open(addr, os.O_RDONLY)
  105. os.lseek(f, msr, os.SEEK_SET)
  106. val = struct.unpack('Q', os.read(f, 8))[0]
  107. os.close(f)
  108. output.append(get_value_for_bits(val, from_bit, to_bit))
  109. if flatten:
  110. return output[0] if len(set(output)) == 1 else output
  111. return output[cpu] if cpu is not None else output
  112. except (IOError, OSError) as e:
  113. if e.errno == EPERM or e.errno == EACCES:
  114. print('[E] Unable to read from MSR. Try to disable Secure Boot.')
  115. sys.exit(1)
  116. else:
  117. raise e
  118. def cpu_usage_pct(exit_event, interval=1.0):
  119. last_idle = last_total = 0
  120. for i in range(2):
  121. with open('/proc/stat') as f:
  122. fields = [float(column) for column in f.readline().strip().split()[1:]]
  123. idle, total = fields[3], sum(fields)
  124. idle_delta, total_delta = idle - last_idle, total - last_total
  125. last_idle, last_total = idle, total
  126. if i == 0:
  127. exit_event.wait(interval)
  128. return 100.0 * (1.0 - idle_delta / total_delta)
  129. def get_value_for_bits(val, from_bit=0, to_bit=63):
  130. mask = sum(2 ** x for x in range(from_bit, to_bit + 1))
  131. return (val & mask) >> from_bit
  132. def is_on_battery(config):
  133. try:
  134. for path in glob.glob(config.get('GENERAL', 'Sysfs_Power_Path', fallback=DEFAULT_SYSFS_POWER_PATH)):
  135. with open(path) as f:
  136. return not bool(int(f.read()))
  137. except:
  138. pass
  139. print('[E] No valid Sysfs_Power_Path found!')
  140. sys.exit(1)
  141. def get_cpu_platform_info():
  142. features_msr_value = readmsr(0xCE, cpu=0)
  143. cpu_platform_info = {}
  144. for key, value in platform_info_bits.items():
  145. cpu_platform_info[key] = int(get_value_for_bits(features_msr_value, value[0], value[1]))
  146. return cpu_platform_info
  147. def get_reset_thermal_status():
  148. # read thermal status
  149. thermal_status_msr_value = readmsr(0x19C)
  150. thermal_status = []
  151. for core in range(cpu_count()):
  152. thermal_status_core = {}
  153. for key, value in thermal_status_bits.items():
  154. thermal_status_core[key] = int(get_value_for_bits(thermal_status_msr_value[core], value[0], value[1]))
  155. thermal_status.append(thermal_status_core)
  156. # reset log bits
  157. writemsr(0x19C, 0)
  158. return thermal_status
  159. def get_time_unit():
  160. # 0.000977 is the time unit of my CPU
  161. # TODO formula might be different for other CPUs
  162. return 1.0 / 2 ** readmsr(0x606, 16, 19, cpu=0)
  163. def get_power_unit():
  164. # 0.125 is the power unit of my CPU
  165. # TODO formula might be different for other CPUs
  166. return 1.0 / 2 ** readmsr(0x606, 0, 3, cpu=0)
  167. def get_critical_temp():
  168. # the critical temperature for my CPU is 100 'C
  169. return readmsr(0x1A2, 16, 23, cpu=0)
  170. def get_cur_pkg_power_limits():
  171. value = readmsr(0x610, 0, 55, flatten=True)
  172. return {
  173. 'PL1': get_value_for_bits(value, 0, 14),
  174. 'TW1': get_value_for_bits(value, 17, 23),
  175. 'PL2': get_value_for_bits(value, 32, 46),
  176. 'TW2': get_value_for_bits(value, 49, 55),
  177. }
  178. def calc_time_window_vars(t):
  179. time_unit = get_time_unit()
  180. for Y in range(2 ** 5):
  181. for Z in range(2 ** 2):
  182. if t <= (2 ** Y) * (1.0 + Z / 4.0) * time_unit:
  183. return (Y, Z)
  184. raise ValueError('Unable to find a good combination!')
  185. def calc_undervolt_msr(plane, offset):
  186. """Return the value to be written in the MSR 150h for setting the given
  187. offset voltage (in mV) to the given voltage plane.
  188. """
  189. assert offset <= 0
  190. assert plane in VOLTAGE_PLANES
  191. offset = int(round(offset * 1.024))
  192. offset = 0xFFE00000 & ((offset & 0xFFF) << 21)
  193. return 0x8000001100000000 | (VOLTAGE_PLANES[plane] << 40) | offset
  194. def calc_undervolt_mv(msr_value):
  195. """Return the offset voltage (in mV) from the given raw MSR 150h value.
  196. """
  197. offset = (msr_value & 0xFFE00000) >> 21
  198. offset = offset if offset <= 0x400 else -(0x800 - offset)
  199. return int(round(offset / 1.024))
  200. def undervolt(config):
  201. for plane in VOLTAGE_PLANES:
  202. write_offset_mv = config.getfloat('UNDERVOLT', plane, fallback=0.0)
  203. write_value = calc_undervolt_msr(plane, write_offset_mv)
  204. writemsr(0x150, write_value)
  205. if args.debug:
  206. write_value &= 0xFFFFFFFF
  207. writemsr(0x150, 0x8000001000000000 | (VOLTAGE_PLANES[plane] << 40))
  208. read_value = readmsr(0x150, flatten=True)
  209. read_offset_mv = calc_undervolt_mv(read_value)
  210. match = OK if write_value == read_value else ERR
  211. print(
  212. '[D] Undervolt plane {:s} - write {:.0f} mV ({:#x}) - read {:.0f} mV ({:#x}) - match {}'.format(
  213. plane, write_offset_mv, write_value, read_offset_mv, read_value, match
  214. )
  215. )
  216. def load_config():
  217. config = configparser.ConfigParser()
  218. config.read(args.config)
  219. # config values sanity check
  220. for power_source in ('AC', 'BATTERY'):
  221. for option in ('Update_Rate_s', 'PL1_Tdp_W', 'PL1_Duration_s', 'PL2_Tdp_W', 'PL2_Duration_S'):
  222. value = config.getfloat(power_source, option, fallback=None)
  223. if value is not None:
  224. value = config.set(power_source, option, str(max(0.1, value)))
  225. elif option == 'Update_Rate_s':
  226. print('[E] The mandatory "Update_Rate_s" parameter is missing.')
  227. sys.exit(1)
  228. trip_temp = config.getfloat(power_source, 'Trip_Temp_C', fallback=None)
  229. if trip_temp is not None:
  230. valid_trip_temp = min(TRIP_TEMP_RANGE[1], max(TRIP_TEMP_RANGE[0], trip_temp))
  231. if trip_temp != valid_trip_temp:
  232. config.set(power_source, 'Trip_Temp_C', str(valid_trip_temp))
  233. print(
  234. '[!] Overriding invalid "Trip_Temp_C" value in "{:s}": {:.1f} -> {:.1f}'.format(
  235. power_source, trip_temp, valid_trip_temp
  236. )
  237. )
  238. for plane in VOLTAGE_PLANES:
  239. value = config.getfloat('UNDERVOLT', plane)
  240. valid_value = min(0, value)
  241. if value != valid_value:
  242. config.set('UNDERVOLT', plane, str(valid_value))
  243. print(
  244. '[!] Overriding invalid "UNDERVOLT" value in "{:s}" voltage plane: {:.0f} -> {:.0f}'.format(
  245. plane, value, valid_value
  246. )
  247. )
  248. return config
  249. def calc_reg_values(platform_info, config):
  250. regs = defaultdict(dict)
  251. for power_source in ('AC', 'BATTERY'):
  252. if platform_info['feature_programmable_temperature_target'] != 1:
  253. print("[W] Setting temperature target is not supported by this CPU")
  254. else:
  255. # the critical temperature for my CPU is 100 'C
  256. critical_temp = get_critical_temp()
  257. # update the allowed temp range to keep at least 3 'C from the CPU critical temperature
  258. global TRIP_TEMP_RANGE
  259. TRIP_TEMP_RANGE[1] = min(TRIP_TEMP_RANGE[1], critical_temp - 3)
  260. Trip_Temp_C = config.getfloat(power_source, 'Trip_Temp_C', fallback=None)
  261. if Trip_Temp_C is not None:
  262. trip_offset = int(round(critical_temp - Trip_Temp_C))
  263. regs[power_source]['MSR_TEMPERATURE_TARGET'] = trip_offset << 24
  264. else:
  265. print('[I] {:s} trip temperature is disabled in config.'.format(power_source))
  266. power_unit = get_power_unit()
  267. PL1_Tdp_W = config.getfloat(power_source, 'PL1_Tdp_W', fallback=None)
  268. PL1_Duration_s = config.getfloat(power_source, 'PL1_Duration_s', fallback=None)
  269. PL2_Tdp_W = config.getfloat(power_source, 'PL2_Tdp_W', fallback=None)
  270. PL2_Duration_s = config.getfloat(power_source, 'PL2_Duration_s', fallback=None)
  271. if (PL1_Tdp_W, PL1_Duration_s, PL2_Tdp_W, PL2_Duration_s).count(None) < 4:
  272. cur_pkg_power_limits = get_cur_pkg_power_limits()
  273. if PL1_Tdp_W is None:
  274. PL1 = cur_pkg_power_limits['PL1']
  275. print('[I] {:s} PL1_Tdp_W disabled in config.'.format(power_source))
  276. else:
  277. PL1 = int(round(PL1_Tdp_W / power_unit))
  278. if PL1_Duration_s is None:
  279. TW1 = cur_pkg_power_limits['TW1']
  280. print('[I] {:s} PL1_Duration_s disabled in config.'.format(power_source))
  281. else:
  282. Y, Z = calc_time_window_vars(PL1_Duration_s)
  283. TW1 = Y | (Z << 5)
  284. if PL2_Tdp_W is None:
  285. PL2 = cur_pkg_power_limits['PL2']
  286. print('[I] {:s} PL2_Tdp_W disabled in config.'.format(power_source))
  287. else:
  288. PL2 = int(round(PL2_Tdp_W / power_unit))
  289. if PL2_Duration_s is None:
  290. TW2 = cur_pkg_power_limits['TW2']
  291. print('[I] {:s} PL2_Duration_s disabled in config.'.format(power_source))
  292. else:
  293. Y, Z = calc_time_window_vars(PL2_Duration_s)
  294. TW2 = Y | (Z << 5)
  295. regs[power_source]['MSR_PKG_POWER_LIMIT'] = (
  296. PL1 | (1 << 15) | (TW1 << 17) | (PL2 << 32) | (1 << 47) | (TW2 << 49)
  297. )
  298. else:
  299. print('[I] {:s} package power limits are disabled in config.'.format(power_source))
  300. # cTDP
  301. c_tdp_target_value = config.getint(power_source, 'cTDP', fallback=None)
  302. if c_tdp_target_value is not None:
  303. if platform_info['feature_programmable_tdp_limit'] != 1:
  304. print("[W] cTDP setting not supported by this CPU")
  305. elif platform_info['number_of_additional_tdp_profiles'] < c_tdp_target_value:
  306. print("[W] the configured cTDP profile is not supported by this CPU")
  307. else:
  308. valid_c_tdp_target_value = max(0, c_tdp_target_value)
  309. regs[power_source]['MSR_CONFIG_TDP_CONTROL'] = valid_c_tdp_target_value
  310. return regs
  311. def set_hwp(pref):
  312. # set HWP energy performance hints
  313. assert pref in ('performance', 'balance_performance', 'default', 'balance_power', 'power')
  314. CPUs = [
  315. '/sys/devices/system/cpu/cpu{:d}/cpufreq/energy_performance_preference'.format(x) for x in range(cpu_count())
  316. ]
  317. for i, c in enumerate(CPUs):
  318. with open(c, 'wb') as f:
  319. f.write(pref.encode())
  320. if args.debug:
  321. with open(c) as f:
  322. read_value = f.read().strip()
  323. match = OK if pref == read_value else ERR
  324. print('[D] HWP for cpu{:d} - write "{:s}" - read "{:s}" - match {}'.format(i, pref, read_value, match))
  325. def power_thread(config, regs, exit_event):
  326. try:
  327. mchbar_mmio = MMIO(0xFED159A0, 8)
  328. except MMIOError:
  329. print('[E] Unable to open /dev/mem. Try to disable Secure Boot.')
  330. sys.exit(1)
  331. while not exit_event.is_set():
  332. # print thermal status
  333. if args.debug:
  334. thermal_status = get_reset_thermal_status()
  335. for index, core_thermal_status in enumerate(thermal_status):
  336. for key, value in core_thermal_status.items():
  337. print('[D] core {} thermal status: {} = {}'.format(index, key.replace("_", " "), value))
  338. # switch back to sysfs polling
  339. if power['method'] == 'polling':
  340. power['source'] = 'BATTERY' if is_on_battery(config) else 'AC'
  341. # set temperature trip point
  342. if 'MSR_TEMPERATURE_TARGET' in regs[power['source']]:
  343. write_value = regs[power['source']]['MSR_TEMPERATURE_TARGET']
  344. writemsr(0x1A2, write_value)
  345. if args.debug:
  346. read_value = readmsr(0x1A2, 24, 29, flatten=True)
  347. match = OK if write_value >> 24 == read_value else ERR
  348. print(
  349. '[D] TEMPERATURE_TARGET - write {:#x} - read {:#x} - match {}'.format(
  350. write_value >> 24, read_value, match
  351. )
  352. )
  353. # set cTDP
  354. if 'MSR_CONFIG_TDP_CONTROL' in regs[power['source']]:
  355. write_value = regs[power['source']]['MSR_CONFIG_TDP_CONTROL']
  356. writemsr(0x64B, write_value)
  357. if args.debug:
  358. read_value = readmsr(0x64B, 0, 1, flatten=True)
  359. match = OK if write_value == read_value else ERR
  360. print(
  361. '[D] CONFIG_TDP_CONTROL - write {:#x} - read {:#x} - match {}'.format(
  362. write_value, read_value, match
  363. )
  364. )
  365. # set PL1/2 on MSR
  366. write_value = regs[power['source']]['MSR_PKG_POWER_LIMIT']
  367. writemsr(0x610, write_value)
  368. if args.debug:
  369. read_value = readmsr(0x610, 0, 55, flatten=True)
  370. match = OK if write_value == read_value else ERR
  371. print(
  372. '[D] MSR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x} - match {}'.format(
  373. write_value, read_value, match
  374. )
  375. )
  376. # set MCHBAR register to the same PL1/2 values
  377. mchbar_mmio.write32(0, write_value & 0xFFFFFFFF)
  378. mchbar_mmio.write32(4, write_value >> 32)
  379. if args.debug:
  380. read_value = mchbar_mmio.read32(0) | (mchbar_mmio.read32(4) << 32)
  381. match = OK if write_value == read_value else ERR
  382. print(
  383. '[D] MCHBAR PACKAGE_POWER_LIMIT - write {:#x} - read {:#x} - match {}'.format(
  384. write_value, read_value, match
  385. )
  386. )
  387. wait_t = config.getfloat(power['source'], 'Update_Rate_s')
  388. enable_hwp_mode = config.getboolean('AC', 'HWP_Mode', fallback=False)
  389. if power['source'] == 'AC' and enable_hwp_mode:
  390. cpu_usage = cpu_usage_pct(exit_event, interval=wait_t)
  391. # set full performance mode only when load is greater than this threshold (~ at least 1 core full speed)
  392. performance_mode = cpu_usage > 100.0 / (cpu_count() * 1.25)
  393. # check again if we are on AC, since in the meantime we might have switched to BATTERY
  394. if not is_on_battery(config):
  395. set_hwp('performance' if performance_mode else 'balance_performance')
  396. else:
  397. exit_event.wait(wait_t)
  398. def check_kernel():
  399. if os.geteuid() != 0:
  400. print('[E] No root no party. Try again with sudo.')
  401. sys.exit(1)
  402. kernel_config = None
  403. try:
  404. with open(os.path.join('/boot', 'config-{:s}'.format(uname()[2]))) as f:
  405. kernel_config = f.read()
  406. except IOError:
  407. try:
  408. with open(os.path.join('/proc', 'config.gz')) as f:
  409. kernel_config = f.read()
  410. except IOError:
  411. pass
  412. if kernel_config is None:
  413. print('[W] Unable to obtain and validate kernel config.')
  414. elif not re.search('CONFIG_DEVMEM=y', kernel_config):
  415. print('[E] Bad kernel config: you need CONFIG_DEVMEM=y.')
  416. sys.exit(1)
  417. elif not re.search('CONFIG_X86_MSR=(y|m)', kernel_config):
  418. print('[E] Bad kernel config: you need CONFIG_X86_MSR builtin or as module.')
  419. sys.exit(1)
  420. def monitor(exit_event, wait):
  421. wait = max(0.1, wait)
  422. print('Realtime monitoring of throttling causes:')
  423. while not exit_event.is_set():
  424. value = readmsr(0x19C, from_bit=0, to_bit=15, cpu=0)
  425. offsets = {'Thermal': 0, 'Power': 10, 'Current': 12, 'Cross-comain (e.g. GPU)': 14}
  426. output = ('{:s}: {:s}'.format(cause, LIM if bool((value >> offsets[cause]) & 1) else OK) for cause in offsets)
  427. print(' - '.join(output) + ' ' * 10, end='\r')
  428. exit_event.wait(wait)
  429. def main():
  430. global args
  431. check_kernel()
  432. parser = argparse.ArgumentParser()
  433. exclusive_group = parser.add_mutually_exclusive_group()
  434. exclusive_group.add_argument('--debug', action='store_true', help='add some debug info and additional checks')
  435. exclusive_group.add_argument(
  436. '--monitor',
  437. metavar='update_rate',
  438. const=1.0,
  439. type=float,
  440. nargs='?',
  441. help='realtime monitoring of throttling causes (default 1s)',
  442. )
  443. parser.add_argument('--config', default='/etc/lenovo_fix.conf', help='override default config file path')
  444. args = parser.parse_args()
  445. config = load_config()
  446. power['source'] = 'BATTERY' if is_on_battery(config) else 'AC'
  447. platform_info = get_cpu_platform_info()
  448. if args.debug:
  449. for key, value in platform_info.items():
  450. print('[D] cpu platform info: {} = {}'.format(key.replace("_", " "), value))
  451. regs = calc_reg_values(platform_info, config)
  452. if not config.getboolean('GENERAL', 'Enabled'):
  453. return
  454. exit_event = Event()
  455. thread = Thread(target=power_thread, args=(config, regs, exit_event))
  456. thread.daemon = True
  457. thread.start()
  458. undervolt(config)
  459. # handle dbus events for applying undervolt on resume from sleep/hybernate
  460. def handle_sleep_callback(sleeping):
  461. if not sleeping:
  462. undervolt(config)
  463. def handle_ac_callback(*args):
  464. try:
  465. power['source'] = 'BATTERY' if args[1]['Online'] == 0 else 'AC'
  466. power['method'] = 'dbus'
  467. except:
  468. power['method'] = 'polling'
  469. DBusGMainLoop(set_as_default=True)
  470. bus = dbus.SystemBus()
  471. # add dbus receiver only if undervolt is enabled in config
  472. if any(config.getfloat('UNDERVOLT', plane) != 0 for plane in VOLTAGE_PLANES):
  473. bus.add_signal_receiver(
  474. handle_sleep_callback, 'PrepareForSleep', 'org.freedesktop.login1.Manager', 'org.freedesktop.login1'
  475. )
  476. bus.add_signal_receiver(
  477. handle_ac_callback,
  478. signal_name="PropertiesChanged",
  479. dbus_interface="org.freedesktop.DBus.Properties",
  480. path="/org/freedesktop/UPower/devices/line_power_AC",
  481. )
  482. if args.monitor is not None:
  483. monitor_thread = Thread(target=monitor, args=(exit_event, args.monitor))
  484. monitor_thread.daemon = True
  485. monitor_thread.start()
  486. try:
  487. loop = GLib.MainLoop()
  488. loop.run()
  489. except (KeyboardInterrupt, SystemExit):
  490. pass
  491. exit_event.set()
  492. loop.quit()
  493. thread.join(timeout=1)
  494. if args.monitor is not None:
  495. monitor_thread.join(timeout=0.1)
  496. if __name__ == '__main__':
  497. main()