powertop.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A mini 'powertop' utility:
  4. * Analyze power consumption on Intel-based laptops.
  5. * Based on powertop 1.11.
  6. *
  7. * Copyright (C) 2010 Marek Polacek <mmpolacek@gmail.com>
  8. *
  9. * Licensed under GPLv2, see file LICENSE in this source tree.
  10. */
  11. //applet:IF_POWERTOP(APPLET(powertop, BB_DIR_USR_SBIN, BB_SUID_DROP))
  12. //kbuild:lib-$(CONFIG_POWERTOP) += powertop.o
  13. //config:config POWERTOP
  14. //config: bool "powertop"
  15. //config: default y
  16. //config: help
  17. //config: Analyze power consumption on Intel-based laptops
  18. //config:
  19. //config:config FEATURE_POWERTOP_INTERACTIVE
  20. //config: bool "Accept keyboard commands"
  21. //config: default y
  22. //config: depends on POWERTOP
  23. //config: help
  24. //config: Without this, powertop will only refresh display every 10 seconds.
  25. //config: No keyboard commands will work, only ^C to terminate.
  26. // XXX This should be configurable
  27. #define ENABLE_FEATURE_POWERTOP_PROCIRQ 1
  28. #include "libbb.h"
  29. //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
  30. #define debug(fmt, ...) ((void)0)
  31. #define BLOATY_HPET_IRQ_NUM_DETECTION 0
  32. #define MAX_CSTATE_COUNT 8
  33. #define IRQCOUNT 40
  34. #define DEFAULT_SLEEP 10
  35. #define DEFAULT_SLEEP_STR "10"
  36. /* Frequency of the ACPI timer */
  37. #define FREQ_ACPI 3579.545
  38. #define FREQ_ACPI_1000 3579545
  39. /* Max filename length of entry in /sys/devices subsystem */
  40. #define BIG_SYSNAME_LEN 16
  41. typedef unsigned long long ullong;
  42. struct line {
  43. char *string;
  44. int count;
  45. /*int disk_count;*/
  46. };
  47. #if ENABLE_FEATURE_POWERTOP_PROCIRQ
  48. struct irqdata {
  49. smallint active;
  50. int number;
  51. ullong count;
  52. char irq_desc[32];
  53. };
  54. #endif
  55. struct globals {
  56. struct line *lines; /* the most often used member */
  57. int lines_cnt;
  58. int lines_cumulative_count;
  59. int maxcstate;
  60. unsigned total_cpus;
  61. smallint cant_enable_timer_stats;
  62. #if ENABLE_FEATURE_POWERTOP_PROCIRQ
  63. # if BLOATY_HPET_IRQ_NUM_DETECTION
  64. smallint scanned_timer_list;
  65. int percpu_hpet_start;
  66. int percpu_hpet_end;
  67. # endif
  68. int interrupt_0;
  69. int total_interrupt;
  70. struct irqdata interrupts[IRQCOUNT];
  71. #endif
  72. ullong start_usage[MAX_CSTATE_COUNT];
  73. ullong last_usage[MAX_CSTATE_COUNT];
  74. ullong start_duration[MAX_CSTATE_COUNT];
  75. ullong last_duration[MAX_CSTATE_COUNT];
  76. #if ENABLE_FEATURE_POWERTOP_INTERACTIVE
  77. struct termios init_settings;
  78. #endif
  79. };
  80. #define G (*ptr_to_globals)
  81. #define INIT_G() do { \
  82. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  83. } while (0)
  84. #if ENABLE_FEATURE_POWERTOP_INTERACTIVE
  85. static void reset_term(void)
  86. {
  87. tcsetattr_stdin_TCSANOW(&G.init_settings);
  88. }
  89. static void sig_handler(int signo UNUSED_PARAM)
  90. {
  91. reset_term();
  92. _exit(EXIT_FAILURE);
  93. }
  94. #endif
  95. static int write_str_to_file(const char *fname, const char *str)
  96. {
  97. FILE *fp = fopen_for_write(fname);
  98. if (!fp)
  99. return 1;
  100. fputs(str, fp);
  101. fclose(fp);
  102. return 0;
  103. }
  104. /* Make it more readable */
  105. #define start_timer() write_str_to_file("/proc/timer_stats", "1\n")
  106. #define stop_timer() write_str_to_file("/proc/timer_stats", "0\n")
  107. static NOINLINE void clear_lines(void)
  108. {
  109. int i;
  110. if (G.lines) {
  111. for (i = 0; i < G.lines_cnt; i++)
  112. free(G.lines[i].string);
  113. free(G.lines);
  114. G.lines_cnt = 0;
  115. G.lines = NULL;
  116. }
  117. }
  118. static void update_lines_cumulative_count(void)
  119. {
  120. int i;
  121. for (i = 0; i < G.lines_cnt; i++)
  122. G.lines_cumulative_count += G.lines[i].count;
  123. }
  124. static int line_compare(const void *p1, const void *p2)
  125. {
  126. const struct line *a = p1;
  127. const struct line *b = p2;
  128. return (b->count /*+ 50 * b->disk_count*/) - (a->count /*+ 50 * a->disk_count*/);
  129. }
  130. static void sort_lines(void)
  131. {
  132. qsort(G.lines, G.lines_cnt, sizeof(G.lines[0]), line_compare);
  133. }
  134. /* Save C-state usage and duration. Also update maxcstate. */
  135. static void read_cstate_counts(ullong *usage, ullong *duration)
  136. {
  137. DIR *dir;
  138. struct dirent *d;
  139. dir = opendir("/proc/acpi/processor");
  140. if (!dir)
  141. return;
  142. while ((d = readdir(dir)) != NULL) {
  143. FILE *fp;
  144. char buf[192];
  145. int level;
  146. int len;
  147. len = strlen(d->d_name); /* "CPUnn" */
  148. if (len < 3 || len > BIG_SYSNAME_LEN)
  149. continue;
  150. sprintf(buf, "%s/%s/power", "/proc/acpi/processor", d->d_name);
  151. fp = fopen_for_read(buf);
  152. if (!fp)
  153. continue;
  154. // Example file contents:
  155. // active state: C0
  156. // max_cstate: C8
  157. // maximum allowed latency: 2000000000 usec
  158. // states:
  159. // C1: type[C1] promotion[--] demotion[--] latency[001] usage[00006173] duration[00000000000000000000]
  160. // C2: type[C2] promotion[--] demotion[--] latency[001] usage[00085191] duration[00000000000083024907]
  161. // C3: type[C3] promotion[--] demotion[--] latency[017] usage[01017622] duration[00000000017921327182]
  162. level = 0;
  163. while (fgets(buf, sizeof(buf), fp)) {
  164. char *p = strstr(buf, "age[");
  165. if (!p)
  166. continue;
  167. p += 4;
  168. usage[level] += bb_strtoull(p, NULL, 10) + 1;
  169. p = strstr(buf, "ation[");
  170. if (!p)
  171. continue;
  172. p += 6;
  173. duration[level] += bb_strtoull(p, NULL, 10);
  174. if (level >= MAX_CSTATE_COUNT-1)
  175. break;
  176. level++;
  177. if (level > G.maxcstate) /* update maxcstate */
  178. G.maxcstate = level;
  179. }
  180. fclose(fp);
  181. }
  182. closedir(dir);
  183. }
  184. /* Add line and/or update count */
  185. static void save_line(const char *string, int count)
  186. {
  187. int i;
  188. for (i = 0; i < G.lines_cnt; i++) {
  189. if (strcmp(string, G.lines[i].string) == 0) {
  190. /* It's already there, only update count */
  191. G.lines[i].count += count;
  192. return;
  193. }
  194. }
  195. /* Add new line */
  196. G.lines = xrealloc_vector(G.lines, 4, G.lines_cnt);
  197. G.lines[G.lines_cnt].string = xstrdup(string);
  198. G.lines[G.lines_cnt].count = count;
  199. /*G.lines[G.lines_cnt].disk_count = 0;*/
  200. G.lines_cnt++;
  201. }
  202. #if ENABLE_FEATURE_POWERTOP_PROCIRQ
  203. static int is_hpet_irq(const char *name)
  204. {
  205. char *p;
  206. # if BLOATY_HPET_IRQ_NUM_DETECTION
  207. long hpet_chan;
  208. /* Learn the range of existing hpet timers. This is done once */
  209. if (!G.scanned_timer_list) {
  210. FILE *fp;
  211. char buf[80];
  212. G.scanned_timer_list = true;
  213. fp = fopen_for_read("/proc/timer_list");
  214. if (!fp)
  215. return 0;
  216. while (fgets(buf, sizeof(buf), fp)) {
  217. p = strstr(buf, "Clock Event Device: hpet");
  218. if (!p)
  219. continue;
  220. p += sizeof("Clock Event Device: hpet")-1;
  221. if (!isdigit(*p))
  222. continue;
  223. hpet_chan = xatoi_positive(p);
  224. if (hpet_chan < G.percpu_hpet_start)
  225. G.percpu_hpet_start = hpet_chan;
  226. if (hpet_chan > G.percpu_hpet_end)
  227. G.percpu_hpet_end = hpet_chan;
  228. }
  229. fclose(fp);
  230. }
  231. # endif
  232. //TODO: optimize
  233. p = strstr(name, "hpet");
  234. if (!p)
  235. return 0;
  236. p += 4;
  237. if (!isdigit(*p))
  238. return 0;
  239. # if BLOATY_HPET_IRQ_NUM_DETECTION
  240. hpet_chan = xatoi_positive(p);
  241. if (hpet_chan < G.percpu_hpet_start || hpet_chan > G.percpu_hpet_end)
  242. return 0;
  243. # endif
  244. return 1;
  245. }
  246. /* Save new IRQ count, return delta from old one */
  247. static int save_irq_count(int irq, ullong count)
  248. {
  249. int unused = IRQCOUNT;
  250. int i;
  251. for (i = 0; i < IRQCOUNT; i++) {
  252. if (G.interrupts[i].active && G.interrupts[i].number == irq) {
  253. ullong old = G.interrupts[i].count;
  254. G.interrupts[i].count = count;
  255. return count - old;
  256. }
  257. if (!G.interrupts[i].active && unused > i)
  258. unused = i;
  259. }
  260. if (unused < IRQCOUNT) {
  261. G.interrupts[unused].active = 1;
  262. G.interrupts[unused].count = count;
  263. G.interrupts[unused].number = irq;
  264. }
  265. return count;
  266. }
  267. /* Read /proc/interrupts, save IRQ counts and IRQ description */
  268. static void process_irq_counts(void)
  269. {
  270. FILE *fp;
  271. char buf[128];
  272. /* Reset values */
  273. G.interrupt_0 = 0;
  274. G.total_interrupt = 0;
  275. fp = xfopen_for_read("/proc/interrupts");
  276. while (fgets(buf, sizeof(buf), fp)) {
  277. char irq_desc[sizeof(" <kernel IPI> : ") + sizeof(buf)];
  278. char *p;
  279. const char *name;
  280. int nr;
  281. ullong count;
  282. ullong delta;
  283. p = strchr(buf, ':');
  284. if (!p)
  285. continue;
  286. /* 0: 143646045 153901007 IO-APIC-edge timer
  287. * ^
  288. */
  289. *p = '\0';
  290. /* Deal with non-maskable interrupts -- make up fake numbers */
  291. nr = index_in_strings("NMI\0RES\0CAL\0TLB\0TRM\0THR\0SPU\0", buf);
  292. if (nr >= 0) {
  293. nr += 20000;
  294. } else {
  295. /* bb_strtou doesn't eat leading spaces, using strtoul */
  296. errno = 0;
  297. nr = strtoul(buf, NULL, 10);
  298. if (errno)
  299. continue;
  300. }
  301. p++;
  302. /* 0: 143646045 153901007 IO-APIC-edge timer
  303. * ^
  304. */
  305. /* Sum counts for this IRQ */
  306. count = 0;
  307. while (1) {
  308. char *tmp;
  309. p = skip_whitespace(p);
  310. if (!isdigit(*p))
  311. break;
  312. count += bb_strtoull(p, &tmp, 10);
  313. p = tmp;
  314. }
  315. /* 0: 143646045 153901007 IO-APIC-edge timer
  316. * NMI: 1 2 Non-maskable interrupts
  317. * ^
  318. */
  319. if (nr < 20000) {
  320. /* Skip to the interrupt name, e.g. 'timer' */
  321. p = strchr(p, ' ');
  322. if (!p)
  323. continue;
  324. p = skip_whitespace(p);
  325. }
  326. name = p;
  327. chomp(p);
  328. /* Save description of the interrupt */
  329. if (nr >= 20000)
  330. sprintf(irq_desc, " <kernel IPI> : %s", name);
  331. else
  332. sprintf(irq_desc, " <interrupt> : %s", name);
  333. delta = save_irq_count(nr, count);
  334. /* Skip per CPU timer interrupts */
  335. if (is_hpet_irq(name))
  336. continue;
  337. if (nr != 0 && delta != 0)
  338. save_line(irq_desc, delta);
  339. if (nr == 0)
  340. G.interrupt_0 = delta;
  341. else
  342. G.total_interrupt += delta;
  343. }
  344. fclose(fp);
  345. }
  346. #else /* !ENABLE_FEATURE_POWERTOP_PROCIRQ */
  347. # define process_irq_counts() ((void)0)
  348. #endif
  349. static NOINLINE int process_timer_stats(void)
  350. {
  351. char buf[128];
  352. char line[15 + 3 + 128];
  353. int n;
  354. FILE *fp;
  355. buf[0] = '\0';
  356. n = 0;
  357. fp = NULL;
  358. if (!G.cant_enable_timer_stats)
  359. fp = fopen_for_read("/proc/timer_stats");
  360. if (fp) {
  361. // Example file contents:
  362. // Timer Stats Version: v0.2
  363. // Sample period: 1.329 s
  364. // 76, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
  365. // 88, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
  366. // 24, 3787 firefox hrtimer_start_range_ns (hrtimer_wakeup)
  367. // 46D, 1136 kondemand/1 do_dbs_timer (delayed_work_timer_fn)
  368. // ...
  369. // 1, 1656 Xorg hrtimer_start_range_ns (hrtimer_wakeup)
  370. // 1, 2159 udisks-daemon hrtimer_start_range_ns (hrtimer_wakeup)
  371. // 331 total events, 249.059 events/sec
  372. while (fgets(buf, sizeof(buf), fp)) {
  373. const char *count, *process, *func;
  374. char *p;
  375. int idx;
  376. unsigned cnt;
  377. count = skip_whitespace(buf);
  378. p = strchr(count, ',');
  379. if (!p)
  380. continue;
  381. *p++ = '\0';
  382. cnt = bb_strtou(count, NULL, 10);
  383. if (strcmp(skip_non_whitespace(count), " total events") == 0) {
  384. #if ENABLE_FEATURE_POWERTOP_PROCIRQ
  385. n = cnt / G.total_cpus;
  386. if (n > 0 && n < G.interrupt_0) {
  387. sprintf(line, " <interrupt> : %s", "extra timer interrupt");
  388. save_line(line, G.interrupt_0 - n);
  389. }
  390. #endif
  391. break;
  392. }
  393. if (strchr(count, 'D'))
  394. continue; /* deferred */
  395. p = skip_whitespace(p); /* points to pid now */
  396. process = NULL;
  397. get_func_name:
  398. p = strchr(p, ' ');
  399. if (!p)
  400. continue;
  401. *p++ = '\0';
  402. p = skip_whitespace(p);
  403. if (process == NULL) {
  404. process = p;
  405. goto get_func_name;
  406. }
  407. func = p;
  408. //if (strcmp(process, "swapper") == 0
  409. // && strcmp(func, "hrtimer_start_range_ns (tick_sched_timer)\n") == 0
  410. //) {
  411. // process = "[kernel scheduler]";
  412. // func = "Load balancing tick";
  413. //}
  414. if (is_prefixed_with(func, "tick_nohz_"))
  415. continue;
  416. if (is_prefixed_with(func, "tick_setup_sched_timer"))
  417. continue;
  418. //if (strcmp(process, "powertop") == 0)
  419. // continue;
  420. idx = index_in_strings("insmod\0modprobe\0swapper\0", process);
  421. if (idx != -1) {
  422. process = idx < 2 ? "[kernel module]" : "<kernel core>";
  423. }
  424. chomp(p);
  425. // 46D\01136\0kondemand/1\0do_dbs_timer (delayed_work_timer_fn)
  426. // ^ ^ ^
  427. // count process func
  428. //if (strchr(process, '['))
  429. sprintf(line, "%15.15s : %s", process, func);
  430. //else
  431. // sprintf(line, "%s", process);
  432. save_line(line, cnt);
  433. }
  434. fclose(fp);
  435. }
  436. return n;
  437. }
  438. #ifdef __i386__
  439. /*
  440. * Get information about CPU using CPUID opcode.
  441. */
  442. static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
  443. unsigned int *edx)
  444. {
  445. /* EAX value specifies what information to return */
  446. __asm__(
  447. " pushl %%ebx\n" /* Save EBX */
  448. " cpuid\n"
  449. " movl %%ebx, %1\n" /* Save content of EBX */
  450. " popl %%ebx\n" /* Restore EBX */
  451. : "=a"(*eax), /* Output */
  452. "=r"(*ebx),
  453. "=c"(*ecx),
  454. "=d"(*edx)
  455. : "0"(*eax), /* Input */
  456. "1"(*ebx),
  457. "2"(*ecx),
  458. "3"(*edx)
  459. /* No clobbered registers */
  460. );
  461. }
  462. #endif
  463. #ifdef __i386__
  464. static NOINLINE void print_intel_cstates(void)
  465. {
  466. int bios_table[8] = { 0 };
  467. int nbios = 0;
  468. DIR *cpudir;
  469. struct dirent *d;
  470. int i;
  471. unsigned eax, ebx, ecx, edx;
  472. cpudir = opendir("/sys/devices/system/cpu");
  473. if (!cpudir)
  474. return;
  475. /* Loop over cpuN entries */
  476. while ((d = readdir(cpudir)) != NULL) {
  477. DIR *dir;
  478. int len;
  479. char fname[sizeof("/sys/devices/system/cpu//cpuidle//desc") + 2*BIG_SYSNAME_LEN];
  480. len = strlen(d->d_name);
  481. if (len < 3 || len > BIG_SYSNAME_LEN)
  482. continue;
  483. if (!isdigit(d->d_name[3]))
  484. continue;
  485. len = sprintf(fname, "%s/%s/cpuidle", "/sys/devices/system/cpu", d->d_name);
  486. dir = opendir(fname);
  487. if (!dir)
  488. continue;
  489. /*
  490. * Every C-state has its own stateN directory, that
  491. * contains a 'time' and a 'usage' file.
  492. */
  493. while ((d = readdir(dir)) != NULL) {
  494. FILE *fp;
  495. char buf[64];
  496. int n;
  497. n = strlen(d->d_name);
  498. if (n < 3 || n > BIG_SYSNAME_LEN)
  499. continue;
  500. sprintf(fname + len, "/%s/desc", d->d_name);
  501. fp = fopen_for_read(fname);
  502. if (fp) {
  503. char *p = fgets(buf, sizeof(buf), fp);
  504. fclose(fp);
  505. if (!p)
  506. break;
  507. p = strstr(p, "MWAIT ");
  508. if (p) {
  509. int pos;
  510. p += sizeof("MWAIT ") - 1;
  511. pos = (bb_strtoull(p, NULL, 16) >> 4) + 1;
  512. if (pos >= ARRAY_SIZE(bios_table))
  513. continue;
  514. bios_table[pos]++;
  515. nbios++;
  516. }
  517. }
  518. }
  519. closedir(dir);
  520. }
  521. closedir(cpudir);
  522. if (!nbios)
  523. return;
  524. eax = 5;
  525. ebx = ecx = edx = 0;
  526. cpuid(&eax, &ebx, &ecx, &edx);
  527. if (!edx || !(ecx & 1))
  528. return;
  529. printf("Your %s the following C-states: ", "CPU supports");
  530. i = 0;
  531. while (edx) {
  532. if (edx & 7)
  533. printf("C%u ", i);
  534. edx >>= 4;
  535. i++;
  536. }
  537. bb_putchar('\n');
  538. /* Print BIOS C-States */
  539. printf("Your %s the following C-states: ", "BIOS reports");
  540. for (i = 0; i < ARRAY_SIZE(bios_table); i++)
  541. if (bios_table[i])
  542. printf("C%u ", i);
  543. bb_putchar('\n');
  544. }
  545. #else
  546. # define print_intel_cstates() ((void)0)
  547. #endif
  548. static void show_timerstats(void)
  549. {
  550. unsigned lines;
  551. /* Get terminal height */
  552. get_terminal_width_height(STDOUT_FILENO, NULL, &lines);
  553. /* We don't have whole terminal just for timerstats */
  554. lines -= 12;
  555. if (!G.cant_enable_timer_stats) {
  556. int i, n = 0;
  557. char strbuf6[6];
  558. puts("\nTop causes for wakeups:");
  559. for (i = 0; i < G.lines_cnt; i++) {
  560. if ((G.lines[i].count > 0 /*|| G.lines[i].disk_count > 0*/)
  561. && n++ < lines
  562. ) {
  563. /* NB: upstream powertop prints "(wakeups/sec)",
  564. * we print just "(wakeup counts)".
  565. */
  566. /*char c = ' ';
  567. if (G.lines[i].disk_count)
  568. c = 'D';*/
  569. smart_ulltoa5(G.lines[i].count, strbuf6, " KMGTPEZY")[0] = '\0';
  570. printf(/*" %5.1f%% (%s)%c %s\n"*/
  571. " %5.1f%% (%s) %s\n",
  572. G.lines[i].count * 100.0 / G.lines_cumulative_count,
  573. strbuf6, /*c,*/
  574. G.lines[i].string);
  575. }
  576. }
  577. } else {
  578. bb_putchar('\n');
  579. bb_error_msg("no stats available; run as root or"
  580. " enable the timer_stats module");
  581. }
  582. }
  583. // Example display from powertop version 1.11
  584. // Cn Avg residency P-states (frequencies)
  585. // C0 (cpu running) ( 0.5%) 2.00 Ghz 0.0%
  586. // polling 0.0ms ( 0.0%) 1.67 Ghz 0.0%
  587. // C1 mwait 0.0ms ( 0.0%) 1333 Mhz 0.1%
  588. // C2 mwait 0.1ms ( 0.1%) 1000 Mhz 99.9%
  589. // C3 mwait 12.1ms (99.4%)
  590. //
  591. // Wakeups-from-idle per second : 93.6 interval: 15.0s
  592. // no ACPI power usage estimate available
  593. //
  594. // Top causes for wakeups:
  595. // 32.4% ( 26.7) <interrupt> : extra timer interrupt
  596. // 29.0% ( 23.9) <kernel core> : hrtimer_start_range_ns (tick_sched_timer)
  597. // 9.0% ( 7.5) <kernel core> : hrtimer_start (tick_sched_timer)
  598. // 6.5% ( 5.3) <interrupt> : ata_piix
  599. // 5.0% ( 4.1) inetd : hrtimer_start_range_ns (hrtimer_wakeup)
  600. //usage:#define powertop_trivial_usage
  601. //usage: ""
  602. //usage:#define powertop_full_usage "\n\n"
  603. //usage: "Analyze power consumption on Intel-based laptops"
  604. int powertop_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  605. int powertop_main(int UNUSED_PARAM argc, char UNUSED_PARAM **argv)
  606. {
  607. ullong cur_usage[MAX_CSTATE_COUNT];
  608. ullong cur_duration[MAX_CSTATE_COUNT];
  609. char cstate_lines[MAX_CSTATE_COUNT + 2][64];
  610. #if ENABLE_FEATURE_POWERTOP_INTERACTIVE
  611. struct pollfd pfd[1];
  612. pfd[0].fd = 0;
  613. pfd[0].events = POLLIN;
  614. #endif
  615. INIT_G();
  616. #if ENABLE_FEATURE_POWERTOP_PROCIRQ && BLOATY_HPET_IRQ_NUM_DETECTION
  617. G.percpu_hpet_start = INT_MAX;
  618. G.percpu_hpet_end = INT_MIN;
  619. #endif
  620. /* Print warning when we don't have superuser privileges */
  621. if (geteuid() != 0)
  622. bb_error_msg("run as root to collect enough information");
  623. /* Get number of CPUs */
  624. G.total_cpus = get_cpu_count();
  625. puts("Collecting data for "DEFAULT_SLEEP_STR" seconds");
  626. #if ENABLE_FEATURE_POWERTOP_INTERACTIVE
  627. /* Turn on unbuffered input; turn off echoing, ^C ^Z etc */
  628. set_termios_to_raw(STDIN_FILENO, &G.init_settings, TERMIOS_CLEAR_ISIG);
  629. bb_signals(BB_FATAL_SIGS, sig_handler);
  630. /* So we don't forget to reset term settings */
  631. atexit(reset_term);
  632. #endif
  633. /* Collect initial data */
  634. process_irq_counts();
  635. /* Read initial usage and duration */
  636. read_cstate_counts(G.start_usage, G.start_duration);
  637. /* Copy them to "last" */
  638. memcpy(G.last_usage, G.start_usage, sizeof(G.last_usage));
  639. memcpy(G.last_duration, G.start_duration, sizeof(G.last_duration));
  640. /* Display C-states */
  641. print_intel_cstates();
  642. G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
  643. /* The main loop */
  644. for (;;) {
  645. //double maxsleep = 0.0;
  646. ullong totalticks, totalevents;
  647. int i;
  648. G.cant_enable_timer_stats |= start_timer(); /* 1 on error */
  649. #if !ENABLE_FEATURE_POWERTOP_INTERACTIVE
  650. sleep(DEFAULT_SLEEP);
  651. #else
  652. if (safe_poll(pfd, 1, DEFAULT_SLEEP * 1000) > 0) {
  653. unsigned char c;
  654. if (safe_read(STDIN_FILENO, &c, 1) != 1)
  655. break; /* EOF/error */
  656. if (c == G.init_settings.c_cc[VINTR])
  657. break; /* ^C */
  658. if ((c | 0x20) == 'q')
  659. break;
  660. }
  661. #endif
  662. G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
  663. clear_lines();
  664. process_irq_counts();
  665. /* Clear the stats */
  666. memset(cur_duration, 0, sizeof(cur_duration));
  667. memset(cur_usage, 0, sizeof(cur_usage));
  668. /* Read them */
  669. read_cstate_counts(cur_usage, cur_duration);
  670. /* Count totalticks and totalevents */
  671. totalticks = totalevents = 0;
  672. for (i = 0; i < MAX_CSTATE_COUNT; i++) {
  673. if (cur_usage[i] != 0) {
  674. totalticks += cur_duration[i] - G.last_duration[i];
  675. totalevents += cur_usage[i] - G.last_usage[i];
  676. }
  677. }
  678. /* Clear the screen */
  679. printf("\033[H\033[J");
  680. /* Clear C-state lines */
  681. memset(&cstate_lines, 0, sizeof(cstate_lines));
  682. if (totalevents == 0 && G.maxcstate <= 1) {
  683. /* This should not happen */
  684. strcpy(cstate_lines[0], "C-state information is not available\n");
  685. } else {
  686. double percentage;
  687. unsigned newticks;
  688. newticks = G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000 - totalticks;
  689. /* Handle rounding errors: do not display negative values */
  690. if ((int)newticks < 0)
  691. newticks = 0;
  692. sprintf(cstate_lines[0], "Cn\t\t Avg residency\n");
  693. percentage = newticks * 100.0 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
  694. sprintf(cstate_lines[1], "C0 (cpu running) (%4.1f%%)\n", percentage);
  695. /* Compute values for individual C-states */
  696. for (i = 0; i < MAX_CSTATE_COUNT; i++) {
  697. if (cur_usage[i] != 0) {
  698. double slept;
  699. slept = (cur_duration[i] - G.last_duration[i])
  700. / (cur_usage[i] - G.last_usage[i] + 0.1) / FREQ_ACPI;
  701. percentage = (cur_duration[i] - G.last_duration[i]) * 100
  702. / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
  703. sprintf(cstate_lines[i + 2], "C%u\t\t%5.1fms (%4.1f%%)\n",
  704. i + 1, slept, percentage);
  705. //if (maxsleep < slept)
  706. // maxsleep = slept;
  707. }
  708. }
  709. }
  710. for (i = 0; i < MAX_CSTATE_COUNT + 2; i++)
  711. if (cstate_lines[i][0])
  712. fputs(cstate_lines[i], stdout);
  713. i = process_timer_stats();
  714. #if ENABLE_FEATURE_POWERTOP_PROCIRQ
  715. if (totalevents == 0) {
  716. /* No C-state info available, use timerstats */
  717. totalevents = i * G.total_cpus + G.total_interrupt;
  718. if (i < 0)
  719. totalevents += G.interrupt_0 - i;
  720. }
  721. #endif
  722. /* Upstream powertop prints wakeups per sec per CPU,
  723. * we print just raw wakeup counts.
  724. */
  725. //TODO: show real seconds (think about manual refresh)
  726. printf("\nWakeups-from-idle in %u seconds: %llu\n",
  727. DEFAULT_SLEEP,
  728. totalevents
  729. );
  730. update_lines_cumulative_count();
  731. sort_lines();
  732. show_timerstats();
  733. fflush(stdout);
  734. /* Clear the stats */
  735. memset(cur_duration, 0, sizeof(cur_duration));
  736. memset(cur_usage, 0, sizeof(cur_usage));
  737. /* Get new values */
  738. read_cstate_counts(cur_usage, cur_duration);
  739. /* Save them */
  740. memcpy(G.last_usage, cur_usage, sizeof(G.last_usage));
  741. memcpy(G.last_duration, cur_duration, sizeof(G.last_duration));
  742. } /* for (;;) */
  743. bb_putchar('\n');
  744. return EXIT_SUCCESS;
  745. }