devterm-a06-gearbox 11 KB

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