devterm-a06-gearbox 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. #!/usr/bin/python3
  2. import argparse
  3. import glob
  4. import os
  5. import subprocess
  6. import sys
  7. from typing import Any, NoReturn
  8. # The gearings below were picked based on various tests by the ClockworkPi devs.
  9. # The maximum-performance maximum-power gearing is present for completeness, but
  10. # shouldn't be needed for most uses.
  11. #
  12. # You can customise the gearings by editing the list below. The valid freqencies
  13. # for CPU <N> can be looked up here (substituting for <N>):
  14. # /sys/devices/system/cpu/cpu<N>/cpufreq/scaling_available_frequencies
  15. #
  16. # The valid GPU frequencies can be looked up here:
  17. # /sys/devices/platform/ff9a0000.gpu/devfreq/ff9a0000.gpu/available_frequencies
  18. #
  19. # Gears are numbered in-order, starting from 1.
  20. # It's up to you to ensure that they are sorted by performance :)
  21. GPU_GOV_SIMPLE = "simple_ondemand"
  22. GPU_GOV_PERF = "performance"
  23. def gears() -> list[dict[str, Any]]:
  24. return [
  25. gear(little=(600000,), use="simple writing tasks with long battery life"),
  26. gear(little=(800000,) * 2, use="browsing most websites with long battery life"),
  27. gear(little=(1008000,) * 4, gpu_freq=400000000, use="most 2D games and emulators"),
  28. gear(big=(1008000,) * 2, gpu_freq=400000000, use="playing videos and 3D games"),
  29. gear(big=(1200000,) * 2, gpu_freq=400000000, use="performance-first tasks"),
  30. gear(
  31. little=(1416000,) * 4,
  32. big=(1800000,) * 2,
  33. gpu_freq=800000000,
  34. use="max performance, max power (usage)",
  35. ),
  36. ]
  37. def gear(
  38. little=(0, 0, 0, 0),
  39. big=(0, 0),
  40. gpu_freq=200000000,
  41. gpu_gov=GPU_GOV_SIMPLE,
  42. use="",
  43. ) -> dict[str, Any]:
  44. """Helper to convert the concise gear format above into a full description.
  45. `little` and `big` define the number of A53 and A72 CPU cores to enable, and
  46. their maximum frequencies (in kHz). Cores that are omitted or set to zero are
  47. :param little: A53 Core.
  48. :param big: A72 Core
  49. :param gpu_freq: Gpu frequency in kHz
  50. :param gpu_gov: Gpu Governor
  51. :param use: Description of the gear.
  52. :return: A dictionary of the parameters.
  53. """
  54. # Extend to 4 little and 2 big cores (matching the A06).
  55. assert len(little) <= 4
  56. assert len(big) <= 2
  57. cpu = little + (0,) * (4 - len(little)) + big + (0,) * (2 - len(big))
  58. # At least one CPU must be enabled
  59. assert sum(cpu) > 0
  60. return {
  61. "cpu": cpu,
  62. "gpu_freq": gpu_freq,
  63. "gpu_gov": gpu_gov,
  64. "use": use,
  65. }
  66. # We placed gears() at the top of the file to make it easier to find and edit.
  67. # Now that we've defined the helpers it needs, evaluate the gears.
  68. gears = gears()
  69. def load_gear(gear: int) -> dict[str, Any]:
  70. return gears[gear - 1]
  71. cur_stat = [
  72. "+-----------------------------------+-----------------+-----------+",
  73. "| Cortex-A53 | Cortex-A72 | Mali-T860 |",
  74. "+--------+--------+--------+--------+--------+--------+-----------+",
  75. "| CPU 0 | CPU 1 | CPU 2 | CPU 3 | CPU 4 | CPU 5 | GPU |",
  76. "+--------+--------+--------+--------+--------+--------+-----------+",
  77. "| 600 MHz| OFF | OFF | OFF | OFF | OFF | 400 MHz |",
  78. "+--------+--------+--------+--------+--------+--------+-----------+",
  79. ]
  80. class A06:
  81. """A06 Module class."""
  82. cpus = []
  83. cpu_scaling_governor: str = "schedutil"
  84. gear = load_gear(1) # 1-5
  85. null_out: str = "2>/dev/null"
  86. def __init__(self):
  87. self.cpus = []
  88. self.init_cpu_infos()
  89. self.cpu_total_count = len(self.cpus)
  90. def init_cpu_infos(self):
  91. self.cpus = glob.glob("/sys/devices/system/cpu/cpu[0-9]")
  92. self.cpus.sort()
  93. @property
  94. def cpu_gov(self) -> str:
  95. if self.gear["cpu"][0] > 0:
  96. cpu_gov_path = "/sys/devices/system/cpu/cpufreq/policy0/scaling_governor"
  97. else:
  98. cpu_gov_path = "/sys/devices/system/cpu/cpufreq/policy4/scaling_governor"
  99. with open(cpu_gov_path, "r") as f:
  100. return f.read().strip()
  101. @property
  102. def gpu_gov(self) -> str:
  103. with open(
  104. "/sys/devices/platform/ff9a0000.gpu/devfreq/ff9a0000.gpu/governor", "r"
  105. ) as gov_file:
  106. return gov_file.read().strip()
  107. def set_cpu_gov0(self, gov):
  108. cpu_gov_path = "/sys/devices/system/cpu/cpufreq/policy0/scaling_governor"
  109. try:
  110. subprocess.run(
  111. "echo %s | sudo tee %s " % (gov, cpu_gov_path),
  112. shell=True,
  113. stdout=subprocess.DEVNULL,
  114. )
  115. except Exception:
  116. print("set cpu governor failed")
  117. def set_cpu_gov4(self, gov):
  118. cpu_gov_path = "/sys/devices/system/cpu/cpufreq/policy4/scaling_governor"
  119. try:
  120. subprocess.run(
  121. "echo %s | sudo tee %s" % (gov, cpu_gov_path),
  122. shell=True,
  123. stdout=subprocess.DEVNULL,
  124. )
  125. except Exception:
  126. print("set cpu governor failed")
  127. def get_cpu_on_off(self, cpu_num):
  128. cpu_onoff_file = "/sys/devices/system/cpu/cpu%d/online" % cpu_num
  129. with open(cpu_onoff_file, "r") as f:
  130. onoff = f.read().strip()
  131. if onoff == "1":
  132. cpu_max_freq_file = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq" % cpu_num
  133. with open(cpu_max_freq_file, "r") as f:
  134. max_freq = f.read().strip()
  135. mhz = int(max_freq) // 1000
  136. return f"{mhz} MHz"
  137. return "OFF"
  138. def set_cpu_on_off(self, cpu_num, onoff):
  139. cpu_onoff_file = "/sys/devices/system/cpu/cpu%d/online" % cpu_num
  140. try:
  141. subprocess.run(
  142. "echo %d | sudo tee %s" % (onoff, cpu_onoff_file),
  143. shell=True,
  144. stdout=subprocess.DEVNULL,
  145. )
  146. except Exception:
  147. print("set cpu %d on off failed" % cpu_num)
  148. def set_cpu_max_freq(self, cpu_num, max_freq):
  149. cpu_max_freq_file = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq" % cpu_num
  150. try:
  151. subprocess.run(
  152. "echo %d | sudo tee %s" % (max_freq, cpu_max_freq_file),
  153. shell=True,
  154. stdout=subprocess.DEVNULL,
  155. )
  156. except Exception:
  157. print("set cpu %d max freq failed" % cpu_num)
  158. def get_gpu_freq(self):
  159. gpu_sys_path = "/sys/devices/platform/ff9a0000.gpu/devfreq/ff9a0000.gpu"
  160. gpu_freq_path = os.path.join(gpu_sys_path, "max_freq")
  161. with open(gpu_freq_path, "r") as f:
  162. freq = f.read().strip()
  163. mhz = int(freq) // 1000000
  164. return f"{mhz} MHz"
  165. def set_gpu(self, gov, hz):
  166. gpu_sys_path = "/sys/devices/platform/ff9a0000.gpu/devfreq/ff9a0000.gpu"
  167. gpu_gov_path = os.path.join(gpu_sys_path, "governor")
  168. gpu_freq_path = os.path.join(gpu_sys_path, "max_freq")
  169. try:
  170. subprocess.run(
  171. "echo %s | sudo tee %s" % (gov, gpu_gov_path), shell=True, stdout=subprocess.DEVNULL
  172. )
  173. subprocess.run(
  174. "echo %d | sudo tee %s" % (hz, gpu_freq_path), shell=True, stdout=subprocess.DEVNULL
  175. )
  176. except Exception:
  177. print("set gpu failed")
  178. def print_cpu_gpu_gov(self):
  179. print(f"CPU Governor: {self.cpu_gov} GPU Governor: {self.gpu_gov}")
  180. def print_cur_status(self):
  181. global cur_stat
  182. stat_str = "|%s|%s|%s|%s|%s|%s|%s|"
  183. cpu0 = self.get_cpu_on_off(0).center(8)[:8]
  184. cpu1 = self.get_cpu_on_off(1).center(8)[:8]
  185. cpu2 = self.get_cpu_on_off(2).center(8)[:8]
  186. cpu3 = self.get_cpu_on_off(3).center(8)[:8]
  187. cpu4 = self.get_cpu_on_off(4).center(8)[:8]
  188. cpu5 = self.get_cpu_on_off(5).center(8)[:8]
  189. gpu = self.get_gpu_freq().center(11)[:11]
  190. table_str = stat_str % (cpu0, cpu1, cpu2, cpu3, cpu4, cpu5, gpu)
  191. print("\nCurrent Status:")
  192. for idx, val in enumerate(cur_stat):
  193. if idx == 5:
  194. print(table_str)
  195. else:
  196. print(val)
  197. self.print_cpu_gpu_gov()
  198. def set_gear(self, g):
  199. self.gear = load_gear(g)
  200. if g > 3:
  201. for (cpu, freq) in reversed(list(enumerate(self.gear["cpu"]))):
  202. enabled = freq > 0
  203. self.set_cpu_on_off(cpu, int(enabled))
  204. if enabled:
  205. self.set_cpu_max_freq(cpu, freq)
  206. else:
  207. for (cpu, freq) in enumerate(self.gear["cpu"]):
  208. enabled = freq > 0
  209. self.set_cpu_on_off(cpu, int(enabled))
  210. if enabled:
  211. self.set_cpu_max_freq(cpu, freq)
  212. self.set_gpu(self.gear["gpu_gov"], self.gear["gpu_freq"])
  213. # TODO: Generalise this
  214. if self.gear["cpu"][0] > 0:
  215. self.set_cpu_gov0(self.cpu_scaling_governor)
  216. else:
  217. self.set_cpu_gov4(self.cpu_scaling_governor)
  218. def print_gear_map(gear: int) -> NoReturn:
  219. print(
  220. " +-----------------------------------+-----------------+-----------+\n"
  221. " | Cortex-A53 | Cortex-A72 | Mali-T860 |\n"
  222. " +--------+--------+--------+--------+--------+--------+-----------+\n"
  223. " | CPU 0 | CPU 1 | CPU 2 | CPU 3 | CPU 4 | CPU 5 | GPU |\n"
  224. "+---+--------+--------+--------+--------+--------+--------+-----------+"
  225. )
  226. def freq(khz: int) -> str:
  227. mhz = khz // 1000
  228. if mhz >= 1000:
  229. return f"{mhz} MHz"
  230. elif mhz > 0:
  231. return f" {mhz} MHz"
  232. else:
  233. return " OFF "
  234. for idx, val in enumerate(gears):
  235. g = idx + 1
  236. selected = g == gear
  237. print(
  238. "|%s|%s| %s |%s"
  239. % (
  240. ("*%s*" if selected else " %s ") % g,
  241. "|".join([freq(cpu) for cpu in val["cpu"]]),
  242. freq(val["gpu_freq"] // 1000),
  243. " <===" if selected else "",
  244. )
  245. )
  246. print("+---+--------+--------+--------+--------+--------+--------+-----------+")
  247. def print_help_msg() -> NoReturn:
  248. print("Usage: devterm-a06-gearbox [OPTION]...")
  249. print(
  250. "Show or set the CPU operating frequency,online status and GPU operating frequency for DevTerm A06.\n"
  251. )
  252. print(f" -s, --set [n] set a speed mode between the number 1-{len(gears)}:")
  253. for (i, _) in enumerate(gears):
  254. print(" %d for %s." % (i + 1, gears[i]["use"]))
  255. print()
  256. print("Examples:")
  257. # TODO: Generate this example
  258. print("Set to mode 1, single LITTLE core @600MHz(max), GPU@200MHz.")
  259. print(" $ devterm-a06-gearbox -s 1")
  260. def is_root() -> bool:
  261. return os.geteuid() == 0
  262. def main() -> SystemExit:
  263. devterm = A06()
  264. parser = argparse.ArgumentParser(add_help=False)
  265. parser.add_argument("-s", "--set", type=int)
  266. parser.add_argument("-h", "--help", action="store_true")
  267. args = parser.parse_args()
  268. if args.set:
  269. gear = args.set
  270. if gear not in range(1, len(gears) + 1):
  271. print(f"Illegal input: mode range 1-{len(gears)}")
  272. sys.exit(-1)
  273. if is_root():
  274. devterm.set_gear(gear)
  275. print_gear_map(gear)
  276. devterm.print_cpu_gpu_gov()
  277. else:
  278. print("Requires super user privilege to set mode, try running it with sudo.")
  279. sys.exit(1)
  280. elif args.help:
  281. print_help_msg()
  282. sys.exit()
  283. else:
  284. if len(sys.argv) == 1:
  285. devterm.print_cur_status()
  286. sys.exit()
  287. if __name__ == "__main__":
  288. main()