1 /* vi: set sw=4 ts=4: */
3 * A mini 'powertop' utility:
4 * Analyze power consumption on Intel-based laptops.
5 * Based on powertop 1.11.
7 * Copyright (C) 2010 Marek Polacek <mmpolacek@gmail.com>
9 * Licensed under GPLv2, see file LICENSE in this source tree.
12 //applet:IF_POWERTOP(APPLET(powertop, _BB_DIR_BIN, _BB_SUID_DROP))
14 //kbuild:lib-$(CONFIG_POWERTOP) += powertop.o
16 //config:config POWERTOP
17 //config: bool "powertop"
20 //config: Analyze power consumption on Intel-based laptops
22 // XXX This should be configurable
23 #define ENABLE_FEATURE_POWERTOP_PROCIRQ 1
28 //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
29 #define debug(fmt, ...) ((void)0)
32 #define BLOATY_HPET_IRQ_NUM_DETECTION 0
33 #define MAX_CSTATE_COUNT 8
37 #define DEFAULT_SLEEP 10
38 #define DEFAULT_SLEEP_STR "10"
40 /* Frequency of the ACPI timer */
41 #define FREQ_ACPI 3579.545
42 #define FREQ_ACPI_1000 3579545
44 /* Max filename length of entry in /sys/devices subsystem */
45 #define BIG_SYSNAME_LEN 16
47 typedef unsigned long long ullong;
55 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
65 struct line *lines; /* the most often used member */
67 int lines_cumulative_count;
70 smallint cant_enable_timer_stats;
71 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
72 # if BLOATY_HPET_IRQ_NUM_DETECTION
73 smallint scanned_timer_list;
74 int percpu_hpet_start;
79 struct irqdata interrupts[IRQCOUNT];
81 ullong start_usage[MAX_CSTATE_COUNT];
82 ullong last_usage[MAX_CSTATE_COUNT];
83 ullong start_duration[MAX_CSTATE_COUNT];
84 ullong last_duration[MAX_CSTATE_COUNT];
85 char cstate_names[MAX_CSTATE_COUNT][16];
86 #if ENABLE_FEATURE_USE_TERMIOS
87 struct termios init_settings;
90 #define G (*ptr_to_globals)
91 #define INIT_G() do { \
92 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
95 #if ENABLE_FEATURE_USE_TERMIOS
96 static void reset_term(void)
98 tcsetattr_stdin_TCSANOW(&G.init_settings);
101 static void sig_handler(int signo UNUSED_PARAM)
108 static int write_str_to_file(const char *fname, const char *str)
110 FILE *fp = fopen_for_write(fname);
118 /* Make it more readable */
119 #define start_timer() write_str_to_file("/proc/timer_stats", "1\n")
120 #define stop_timer() write_str_to_file("/proc/timer_stats", "0\n")
122 static NOINLINE void clear_lines(void)
126 for (i = 0; i < G.lines_cnt; i++)
127 free(G.lines[i].string);
134 static void update_lines_cumulative_count(void)
137 for (i = 0; i < G.lines_cnt; i++)
138 G.lines_cumulative_count += G.lines[i].count;
141 static int line_compare(const void *p1, const void *p2)
143 const struct line *a = p1;
144 const struct line *b = p2;
145 return (b->count /*+ 50 * b->disk_count*/) - (a->count /*+ 50 * a->disk_count*/);
148 static void sort_lines(void)
150 qsort(G.lines, G.lines_cnt, sizeof(G.lines[0]), line_compare);
153 /* Save C-state usage and duration. Also update maxcstate. */
154 static void read_cstate_counts(ullong *usage, ullong *duration)
159 dir = opendir("/proc/acpi/processor");
163 while ((d = readdir(dir)) != NULL) {
169 len = strlen(d->d_name); /* "CPUnn" */
170 if (len < 3 || len > BIG_SYSNAME_LEN)
173 sprintf(buf, "/proc/acpi/processor/%s/power", d->d_name);
174 fp = fopen_for_read(buf);
178 // Example file contents:
181 // maximum allowed latency: 2000000000 usec
183 // C1: type[C1] promotion[--] demotion[--] latency[001] usage[00006173] duration[00000000000000000000]
184 // C2: type[C2] promotion[--] demotion[--] latency[001] usage[00085191] duration[00000000000083024907]
185 // C3: type[C3] promotion[--] demotion[--] latency[017] usage[01017622] duration[00000000017921327182]
187 while (fgets(buf, sizeof(buf), fp)) {
188 char *p = strstr(buf, "age[");
192 usage[level] += bb_strtoull(p, NULL, 10) + 1;
193 p = strstr(buf, "ation[");
197 duration[level] += bb_strtoull(p, NULL, 10);
199 if (level >= MAX_CSTATE_COUNT-1)
202 if (level > G.maxcstate) /* update maxcstate */
210 /* Add line and/or update count */
211 static void save_line(const char *string, int count)
214 for (i = 0; i < G.lines_cnt; i++) {
215 if (strcmp(string, G.lines[i].string) == 0) {
216 /* It's already there, only update count */
217 G.lines[i].count += count;
223 G.lines = xrealloc_vector(G.lines, 4, G.lines_cnt);
224 G.lines[G.lines_cnt].string = xstrdup(string);
225 G.lines[G.lines_cnt].count = count;
226 /*G.lines[G.lines_cnt].disk_count = 0;*/
230 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
231 static int is_hpet_irq(const char *name)
234 # if BLOATY_HPET_IRQ_NUM_DETECTION
237 /* Learn the range of existing hpet timers. This is done once */
238 if (!G.scanned_timer_list) {
242 G.scanned_timer_list = true;
243 fp = fopen_for_read("/proc/timer_list");
247 while (fgets(buf, sizeof(buf), fp)) {
248 p = strstr(buf, "Clock Event Device: hpet");
251 p += sizeof("Clock Event Device: hpet")-1;
254 hpet_chan = xatoi_positive(p);
255 if (hpet_chan < G.percpu_hpet_start)
256 G.percpu_hpet_start = hpet_chan;
257 if (hpet_chan > G.percpu_hpet_end)
258 G.percpu_hpet_end = hpet_chan;
264 p = strstr(name, "hpet");
270 # if BLOATY_HPET_IRQ_NUM_DETECTION
271 hpet_chan = xatoi_positive(p);
272 if (hpet_chan < G.percpu_hpet_start || hpet_chan > G.percpu_hpet_end)
278 /* Save new IRQ count, return delta from old one */
279 static int save_irq_count(int irq, ullong count)
281 int unused = IRQCOUNT;
283 for (i = 0; i < IRQCOUNT; i++) {
284 if (G.interrupts[i].active && G.interrupts[i].number == irq) {
285 ullong old = G.interrupts[i].count;
286 G.interrupts[i].count = count;
289 if (!G.interrupts[i].active && unused > i)
292 if (unused < IRQCOUNT) {
293 G.interrupts[unused].active = 1;
294 G.interrupts[unused].count = count;
295 G.interrupts[unused].number = irq;
300 /* Read /proc/interrupts, save IRQ counts and IRQ description */
301 static void process_irq_counts(void)
308 G.total_interrupt = 0;
310 fp = xfopen_for_read("/proc/interrupts");
311 while (fgets(buf, sizeof(buf), fp)) {
312 char irq_desc[sizeof(" <kernel IPI> : ") + sizeof(buf)];
319 p = strchr(buf, ':');
322 /* 0: 143646045 153901007 IO-APIC-edge timer
325 /* Deal with non-maskable interrupts -- make up fake numbers */
327 if (buf[0] != ' ' && !isdigit(buf[0])) {
329 if (strncmp(buf, "NMI:", 4) == 0)
331 if (strncmp(buf, "RES:", 4) == 0)
333 if (strncmp(buf, "CAL:", 4) == 0)
335 if (strncmp(buf, "TLB:", 4) == 0)
337 if (strncmp(buf, "TRM:", 4) == 0)
339 if (strncmp(buf, "THR:", 4) == 0)
341 if (strncmp(buf, "SPU:", 4) == 0)
344 /* bb_strtou doesn't eat leading spaces, using strtoul */
345 nr = strtoul(buf, NULL, 10);
351 /* 0: 143646045 153901007 IO-APIC-edge timer
354 /* Sum counts for this IRQ */
358 p = skip_whitespace(p);
361 count += bb_strtoull(p, &tmp, 10);
364 /* 0: 143646045 153901007 IO-APIC-edge timer
365 * NMI: 1 2 Non-maskable interrupts
369 /* Skip to the interrupt name, e.g. 'timer' */
373 p = skip_whitespace(p);
377 strchrnul(name, '\n')[0] = '\0';
378 /* Save description of the interrupt */
380 sprintf(irq_desc, " <kernel IPI> : %s", name);
382 sprintf(irq_desc, " <interrupt> : %s", name);
384 delta = save_irq_count(nr, count);
386 /* Skip per CPU timer interrupts */
387 if (is_hpet_irq(name))
390 if (nr != 0 && delta != 0)
391 save_line(irq_desc, delta);
394 G.interrupt_0 = delta;
396 G.total_interrupt += delta;
401 #else /* !ENABLE_FEATURE_POWERTOP_PROCIRQ */
402 # define process_irq_counts() ((void)0)
405 static NOINLINE int process_timer_stats(void)
408 char line[15 + 3 + 128];
417 if (!G.cant_enable_timer_stats)
418 fp = fopen_for_read("/proc/timer_stats");
420 // Example file contents:
421 // Timer Stats Version: v0.2
422 // Sample period: 1.329 s
423 // 76, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
424 // 88, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
425 // 24, 3787 firefox hrtimer_start_range_ns (hrtimer_wakeup)
426 // 46D, 1136 kondemand/1 do_dbs_timer (delayed_work_timer_fn)
428 // 1, 1656 Xorg hrtimer_start_range_ns (hrtimer_wakeup)
429 // 1, 2159 udisks-daemon hrtimer_start_range_ns (hrtimer_wakeup)
430 // 331 total events, 249.059 events/sec
431 while (fgets(buf, sizeof(buf), fp)) {
432 const char *count, *process, *func;
436 count = skip_whitespace(buf);
437 p = strchr(count, ',');
441 if (strcmp(strchrnul(count, ' '), " total events") == 0)
443 p = skip_whitespace(p); /* points to pid */
445 /* Find char ' ', then eat remaining spaces */
446 #define ADVANCE(p) do { \
447 (p) = strchr((p), ' '); \
452 (p) = skip_whitespace(p); \
454 /* Get process name */
461 //if (strcmp(process, "swapper") == 0
462 // && strcmp(func, "hrtimer_start_range_ns (tick_sched_timer)\n") == 0
464 // process = "[kernel scheduler]";
465 // func = "Load balancing tick";
468 if (strncmp(func, "tick_nohz_", 10) == 0)
470 if (strncmp(func, "tick_setup_sched_timer", 20) == 0)
472 //if (strcmp(process, "powertop") == 0)
475 if (strcmp(process, "insmod") == 0)
476 process = "[kernel module]";
477 if (strcmp(process, "modprobe") == 0)
478 process = "[kernel module]";
479 if (strcmp(process, "swapper") == 0)
480 process = "<kernel core>";
482 strchrnul(p, '\n')[0] = '\0';
486 cnt = bb_strtoull(count, &tmp, 10);
490 if (*p++ == 'D') /* deferred */
494 //if (strchr(process, '['))
495 sprintf(line, "%15.15s : %s", process, func);
497 // sprintf(line, "%s", process);
498 save_line(line, cnt);
505 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
506 if (strstr(buf, "total events")) {
507 n = bb_strtoull(buf, NULL, 10) / G.total_cpus;
508 if (n > 0 && n < G.interrupt_0) {
509 sprintf(line, " <interrupt> : %s", "extra timer interrupt");
510 save_line(line, G.interrupt_0 - n);
519 * Get information about CPU using CPUID opcode.
521 static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
524 /* EAX value specifies what information to return */
526 " pushl %%ebx\n" /* Save EBX */
528 " movl %%ebx, %1\n" /* Save content of EBX */
529 " popl %%ebx\n" /* Restore EBX */
530 : "=a"(*eax), /* Output */
534 : "0"(*eax), /* Input */
538 /* No clobbered registers */
543 static NOINLINE void print_intel_cstates(void)
546 int bios_table[8] = { 0 };
551 unsigned eax, ebx, ecx, edx;
553 cpudir = opendir("/sys/devices/system/cpu");
557 /* Loop over cpuN entries */
558 while ((d = readdir(cpudir)) != NULL) {
561 char fname[sizeof("/sys/devices/system/cpu//cpuidle//desc") + 2*BIG_SYSNAME_LEN];
563 len = strlen(d->d_name);
564 if (len < 3 || len > BIG_SYSNAME_LEN)
567 if (!isdigit(d->d_name[3]))
570 len = sprintf(fname, "/sys/devices/system/cpu/%s/cpuidle", d->d_name);
571 dir = opendir(fname);
576 * Every C-state has its own stateN directory, that
577 * contains a 'time' and a 'usage' file.
579 while ((d = readdir(dir)) != NULL) {
584 n = strlen(d->d_name);
585 if (n < 3 || n > BIG_SYSNAME_LEN)
588 sprintf(fname + len, "/%s/desc", d->d_name);
589 fp = fopen_for_read(fname);
591 char *p = fgets(buf, sizeof(buf), fp);
595 p = strstr(p, "MWAIT ");
598 p += sizeof("MWAIT ") - 1;
599 pos = (bb_strtoull(p, NULL, 16) >> 4) + 1;
600 if (pos >= ARRAY_SIZE(bios_table))
616 cpuid(&eax, &ebx, &ecx, &edx);
617 if (!edx || !(ecx & 1))
620 printf("Your CPU supports the following C-states: ");
630 /* Print BIOS C-States */
631 printf("Your BIOS reports the following C-states: ");
632 for (i = 0; i < 8; i++)
640 static void show_timerstats(void)
644 /* Get terminal height */
645 get_terminal_width_height(STDOUT_FILENO, NULL, &lines);
647 /* We don't have whole terminal just for timerstats */
650 if (!G.cant_enable_timer_stats) {
655 puts("\nTop causes for wakeups:");
656 for (i = 0; i < G.lines_cnt; i++) {
657 if ((G.lines[i].count > 0 /*|| G.lines[i].disk_count > 0*/)
660 /* NB: upstream powertop prints "(wakeups/sec)",
661 * we print just "(wakeup counts)".
664 if (G.lines[i].disk_count)
666 smart_ulltoa5(G.lines[i].count, strbuf6, " KMGTPEZY");
667 printf(/*" %5.1f%% (%s)%c %s\n"*/
668 " %5.1f%% (%s) %s\n",
669 G.lines[i].count * 100.0 / G.lines_cumulative_count,
676 bb_error_msg("no stats available; run as root or"
677 " enable the cpufreq_stats module");
681 // Example display from powertop version 1.11
682 // Cn Avg residency P-states (frequencies)
683 // C0 (cpu running) ( 0.5%) 2.00 Ghz 0.0%
684 // polling 0.0ms ( 0.0%) 1.67 Ghz 0.0%
685 // C1 mwait 0.0ms ( 0.0%) 1333 Mhz 0.1%
686 // C2 mwait 0.1ms ( 0.1%) 1000 Mhz 99.9%
687 // C3 mwait 12.1ms (99.4%)
689 // Wakeups-from-idle per second : 93.6 interval: 15.0s
690 // no ACPI power usage estimate available
692 // Top causes for wakeups:
693 // 32.4% ( 26.7) <interrupt> : extra timer interrupt
694 // 29.0% ( 23.9) <kernel core> : hrtimer_start_range_ns (tick_sched_timer)
695 // 9.0% ( 7.5) <kernel core> : hrtimer_start (tick_sched_timer)
696 // 6.5% ( 5.3) <interrupt> : ata_piix
697 // 5.0% ( 4.1) inetd : hrtimer_start_range_ns (hrtimer_wakeup)
699 //usage:#define powertop_trivial_usage
701 //usage:#define powertop_full_usage "\n\n"
702 //usage: "Analyze power consumption on Intel-based laptops\n"
704 int powertop_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
705 int powertop_main(int UNUSED_PARAM argc, char UNUSED_PARAM **argv)
707 ullong cur_usage[MAX_CSTATE_COUNT];
708 ullong cur_duration[MAX_CSTATE_COUNT];
709 char cstate_lines[MAX_CSTATE_COUNT + 2][64];
710 #if ENABLE_FEATURE_USE_TERMIOS
711 struct termios new_settings;
712 struct pollfd pfd[1];
715 pfd[0].events = POLLIN;
720 #if ENABLE_FEATURE_POWERTOP_PROCIRQ && BLOATY_HPET_IRQ_NUM_DETECTION
721 G.percpu_hpet_start = INT_MAX;
722 G.percpu_hpet_end = INT_MIN;
725 /* Print warning when we don't have superuser privileges */
727 bb_error_msg("run as root to collect enough information");
729 /* Get number of CPUs */
730 G.total_cpus = get_cpu_count();
732 printf("Collecting data for "DEFAULT_SLEEP_STR" seconds\n");
734 #if ENABLE_FEATURE_USE_TERMIOS
735 tcgetattr(0, (void *)&G.init_settings);
736 memcpy(&new_settings, &G.init_settings, sizeof(new_settings));
737 /* Turn on unbuffered input, turn off echoing */
738 new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
739 /* So we don't forget to reset term settings */
741 bb_signals(BB_FATAL_SIGS, sig_handler);
742 tcsetattr_stdin_TCSANOW(&new_settings);
745 /* Collect initial data */
746 process_irq_counts();
748 /* Read initial usage and duration */
749 read_cstate_counts(G.start_usage, G.start_duration);
751 /* Copy them to "last" */
752 memcpy(G.last_usage, G.start_usage, sizeof(G.last_usage));
753 memcpy(G.last_duration, G.start_duration, sizeof(G.last_duration));
755 /* Display C-states */
756 print_intel_cstates();
758 G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
762 //double maxsleep = 0.0;
763 ullong totalticks, totalevents;
766 G.cant_enable_timer_stats |= start_timer(); /* 1 on error */
767 #if !ENABLE_FEATURE_USE_TERMIOS
768 sleep(DEFAULT_SLEEP);
770 if (safe_poll(pfd, 1, DEFAULT_SLEEP * 1000) > 0) {
772 if (safe_read(STDIN_FILENO, &c, 1) != 1)
773 break; /* EOF/error */
774 if (c == G.init_settings.c_cc[VINTR])
776 if ((c | 0x20) == 'q')
780 G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
783 process_irq_counts();
785 /* Clear the stats */
786 memset(cur_duration, 0, sizeof(cur_duration));
787 memset(cur_usage, 0, sizeof(cur_usage));
790 read_cstate_counts(cur_usage, cur_duration);
792 /* Count totalticks and totalevents */
793 totalticks = totalevents = 0;
794 for (i = 0; i < MAX_CSTATE_COUNT; i++) {
795 if (cur_usage[i] != 0) {
796 totalticks += cur_duration[i] - G.last_duration[i];
797 totalevents += cur_usage[i] - G.last_usage[i];
801 /* Clear the screen */
802 printf("\033[H\033[J");
804 /* Clear C-state lines */
805 memset(&cstate_lines, 0, sizeof(cstate_lines));
807 if (totalevents == 0 && G.maxcstate <= 1) {
808 /* This should not happen */
809 sprintf(cstate_lines[5], "< Detailed C-state information is not "
815 newticks = G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000 - totalticks;
817 /* Handle rounding errors: do not display negative values */
821 sprintf(cstate_lines[0], "Cn\t\t Avg residency\n");
822 percentage = newticks * 100.0 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
823 sprintf(cstate_lines[1], "C0 (cpu running) (%4.1f%%)\n",
826 /* Compute values for individual C-states */
827 for (i = 0; i < MAX_CSTATE_COUNT; i++) {
828 if (cur_usage[i] != 0) {
830 slept = (cur_duration[i] - G.last_duration[i])
831 / (cur_usage[i] - G.last_usage[i] + 0.1) / FREQ_ACPI;
832 percentage = (cur_duration[i] - G.last_duration[i]) * 100
833 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
835 if (!G.cstate_names[i][0])
836 sprintf(G.cstate_names[i], "C%u", i + 1);
837 sprintf(cstate_lines[i + 2], "%s\t\t%5.1fms (%4.1f%%)\n",
838 G.cstate_names[i], slept, percentage);
839 //if (maxsleep < slept)
845 for (i = 0; i < MAX_CSTATE_COUNT + 2; i++)
846 if (cstate_lines[i][0])
847 printf("%s", cstate_lines[i]);
849 i = process_timer_stats();
850 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
851 if (totalevents == 0) {
852 /* No C-state info available, use timerstats */
853 totalevents = i * G.total_cpus + G.total_interrupt;
855 totalevents += G.interrupt_0 - i;
858 /* Upstream powertop prints wakeups per sec per CPU,
859 * we print just raw wakeup counts.
861 //TODO: show real seconds (think about manual refresh)
862 printf("\nWakeups-from-idle in %u seconds: %llu\n",
867 update_lines_cumulative_count();
872 /* Clear the stats */
873 memset(cur_duration, 0, sizeof(cur_duration));
874 memset(cur_usage, 0, sizeof(cur_usage));
877 read_cstate_counts(cur_usage, cur_duration);
880 memcpy(G.last_usage, cur_usage, sizeof(G.last_usage));
881 memcpy(G.last_duration, cur_duration, sizeof(G.last_duration));