lenovo_fix.py 20 KB

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