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.
11 //config:config POWERTOP
12 //config: bool "powertop (9.1 kb)"
15 //config: Analyze power consumption on Intel-based laptops
17 //config:config FEATURE_POWERTOP_INTERACTIVE
18 //config: bool "Accept keyboard commands"
20 //config: depends on POWERTOP
22 //config: Without this, powertop will only refresh display every 10 seconds.
23 //config: No keyboard commands will work, only ^C to terminate.
25 //applet:IF_POWERTOP(APPLET(powertop, BB_DIR_USR_SBIN, BB_SUID_DROP))
27 //kbuild:lib-$(CONFIG_POWERTOP) += powertop.o
29 // XXX This should be configurable
30 #define ENABLE_FEATURE_POWERTOP_PROCIRQ 1
35 //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
36 #define debug(fmt, ...) ((void)0)
39 #define BLOATY_HPET_IRQ_NUM_DETECTION 0
40 #define MAX_CSTATE_COUNT 8
44 #define DEFAULT_SLEEP 10
45 #define DEFAULT_SLEEP_STR "10"
47 /* Frequency of the ACPI timer */
48 #define FREQ_ACPI 3579.545
49 #define FREQ_ACPI_1000 3579545
51 /* Max filename length of entry in /sys/devices subsystem */
52 #define BIG_SYSNAME_LEN 16
56 typedef unsigned long long ullong;
64 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
74 struct line *lines; /* the most often used member */
76 int lines_cumulative_count;
79 smallint cant_enable_timer_stats;
80 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
81 # if BLOATY_HPET_IRQ_NUM_DETECTION
82 smallint scanned_timer_list;
83 int percpu_hpet_start;
88 struct irqdata interrupts[IRQCOUNT];
90 ullong start_usage[MAX_CSTATE_COUNT];
91 ullong last_usage[MAX_CSTATE_COUNT];
92 ullong start_duration[MAX_CSTATE_COUNT];
93 ullong last_duration[MAX_CSTATE_COUNT];
94 #if ENABLE_FEATURE_POWERTOP_INTERACTIVE
95 struct termios init_settings;
98 #define G (*ptr_to_globals)
99 #define INIT_G() do { \
100 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
103 #if ENABLE_FEATURE_POWERTOP_INTERACTIVE
104 static void reset_term(void)
106 tcsetattr_stdin_TCSANOW(&G.init_settings);
109 static void sig_handler(int signo UNUSED_PARAM)
116 static int write_str_to_file(const char *fname, const char *str)
118 FILE *fp = fopen_for_write(fname);
126 /* Make it more readable */
127 #define start_timer() write_str_to_file("/proc/timer_stats", "1\n")
128 #define stop_timer() write_str_to_file("/proc/timer_stats", "0\n")
130 static NOINLINE void clear_lines(void)
134 for (i = 0; i < G.lines_cnt; i++)
135 free(G.lines[i].string);
142 static void update_lines_cumulative_count(void)
145 for (i = 0; i < G.lines_cnt; i++)
146 G.lines_cumulative_count += G.lines[i].count;
149 static int line_compare(const void *p1, const void *p2)
151 const struct line *a = p1;
152 const struct line *b = p2;
153 return (b->count /*+ 50 * b->disk_count*/) - (a->count /*+ 50 * a->disk_count*/);
156 static void sort_lines(void)
158 qsort(G.lines, G.lines_cnt, sizeof(G.lines[0]), line_compare);
161 /* Save C-state usage and duration. Also update maxcstate. */
162 static void read_cstate_counts(ullong *usage, ullong *duration)
167 dir = opendir("/proc/acpi/processor");
171 while ((d = readdir(dir)) != NULL) {
177 len = strlen(d->d_name); /* "CPUnn" */
178 if (len < 3 || len > BIG_SYSNAME_LEN)
181 sprintf(buf, "%s/%s/power", "/proc/acpi/processor", d->d_name);
182 fp = fopen_for_read(buf);
186 // Example file contents:
189 // maximum allowed latency: 2000000000 usec
191 // C1: type[C1] promotion[--] demotion[--] latency[001] usage[00006173] duration[00000000000000000000]
192 // C2: type[C2] promotion[--] demotion[--] latency[001] usage[00085191] duration[00000000000083024907]
193 // C3: type[C3] promotion[--] demotion[--] latency[017] usage[01017622] duration[00000000017921327182]
195 while (fgets(buf, sizeof(buf), fp)) {
196 char *p = strstr(buf, "age[");
200 usage[level] += bb_strtoull(p, NULL, 10) + 1;
201 p = strstr(buf, "ation[");
205 duration[level] += bb_strtoull(p, NULL, 10);
207 if (level >= MAX_CSTATE_COUNT-1)
210 if (level > G.maxcstate) /* update maxcstate */
218 /* Add line and/or update count */
219 static void save_line(const char *string, int count)
222 for (i = 0; i < G.lines_cnt; i++) {
223 if (strcmp(string, G.lines[i].string) == 0) {
224 /* It's already there, only update count */
225 G.lines[i].count += count;
231 G.lines = xrealloc_vector(G.lines, 4, G.lines_cnt);
232 G.lines[G.lines_cnt].string = xstrdup(string);
233 G.lines[G.lines_cnt].count = count;
234 /*G.lines[G.lines_cnt].disk_count = 0;*/
238 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
239 static int is_hpet_irq(const char *name)
242 # if BLOATY_HPET_IRQ_NUM_DETECTION
245 /* Learn the range of existing hpet timers. This is done once */
246 if (!G.scanned_timer_list) {
250 G.scanned_timer_list = true;
251 fp = fopen_for_read("/proc/timer_list");
255 while (fgets(buf, sizeof(buf), fp)) {
256 p = strstr(buf, "Clock Event Device: hpet");
259 p += sizeof("Clock Event Device: hpet")-1;
262 hpet_chan = xatoi_positive(p);
263 if (hpet_chan < G.percpu_hpet_start)
264 G.percpu_hpet_start = hpet_chan;
265 if (hpet_chan > G.percpu_hpet_end)
266 G.percpu_hpet_end = hpet_chan;
272 p = strstr(name, "hpet");
278 # if BLOATY_HPET_IRQ_NUM_DETECTION
279 hpet_chan = xatoi_positive(p);
280 if (hpet_chan < G.percpu_hpet_start || hpet_chan > G.percpu_hpet_end)
286 /* Save new IRQ count, return delta from old one */
287 static int save_irq_count(int irq, ullong count)
289 int unused = IRQCOUNT;
291 for (i = 0; i < IRQCOUNT; i++) {
292 if (G.interrupts[i].active && G.interrupts[i].number == irq) {
293 ullong old = G.interrupts[i].count;
294 G.interrupts[i].count = count;
297 if (!G.interrupts[i].active && unused > i)
300 if (unused < IRQCOUNT) {
301 G.interrupts[unused].active = 1;
302 G.interrupts[unused].count = count;
303 G.interrupts[unused].number = irq;
308 /* Read /proc/interrupts, save IRQ counts and IRQ description */
309 static void process_irq_counts(void)
316 G.total_interrupt = 0;
318 fp = xfopen_for_read("/proc/interrupts");
319 while (fgets(buf, sizeof(buf), fp)) {
320 char irq_desc[sizeof(" <kernel IPI> : ") + sizeof(buf)];
327 p = strchr(buf, ':');
330 /* 0: 143646045 153901007 IO-APIC-edge timer
334 /* Deal with non-maskable interrupts -- make up fake numbers */
335 nr = index_in_strings("NMI\0RES\0CAL\0TLB\0TRM\0THR\0SPU\0", buf);
339 /* bb_strtou doesn't eat leading spaces, using strtoul */
341 nr = strtoul(buf, NULL, 10);
346 /* 0: 143646045 153901007 IO-APIC-edge timer
349 /* Sum counts for this IRQ */
353 p = skip_whitespace(p);
356 count += bb_strtoull(p, &tmp, 10);
359 /* 0: 143646045 153901007 IO-APIC-edge timer
360 * NMI: 1 2 Non-maskable interrupts
364 /* Skip to the interrupt name, e.g. 'timer' */
368 p = skip_whitespace(p);
373 /* Save description of the interrupt */
375 sprintf(irq_desc, " <kernel IPI> : %s", name);
377 sprintf(irq_desc, " <interrupt> : %s", name);
379 delta = save_irq_count(nr, count);
381 /* Skip per CPU timer interrupts */
382 if (is_hpet_irq(name))
385 if (nr != 0 && delta != 0)
386 save_line(irq_desc, delta);
389 G.interrupt_0 = delta;
391 G.total_interrupt += delta;
396 #else /* !ENABLE_FEATURE_POWERTOP_PROCIRQ */
397 # define process_irq_counts() ((void)0)
400 static NOINLINE int process_timer_stats(void)
403 char line[15 + 3 + 128];
411 if (!G.cant_enable_timer_stats)
412 fp = fopen_for_read("/proc/timer_stats");
414 // Example file contents:
415 // Timer Stats Version: v0.2
416 // Sample period: 1.329 s
417 // 76, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
418 // 88, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
419 // 24, 3787 firefox hrtimer_start_range_ns (hrtimer_wakeup)
420 // 46D, 1136 kondemand/1 do_dbs_timer (delayed_work_timer_fn)
422 // 1, 1656 Xorg hrtimer_start_range_ns (hrtimer_wakeup)
423 // 1, 2159 udisks-daemon hrtimer_start_range_ns (hrtimer_wakeup)
424 // 331 total events, 249.059 events/sec
425 while (fgets(buf, sizeof(buf), fp)) {
426 const char *count, *process, *func;
431 count = skip_whitespace(buf);
432 p = strchr(count, ',');
436 cnt = bb_strtou(count, NULL, 10);
437 if (strcmp(skip_non_whitespace(count), " total events") == 0) {
438 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
439 n = cnt / G.total_cpus;
440 if (n > 0 && n < G.interrupt_0) {
441 sprintf(line, " <interrupt> : %s", "extra timer interrupt");
442 save_line(line, G.interrupt_0 - n);
447 if (strchr(count, 'D'))
448 continue; /* deferred */
449 p = skip_whitespace(p); /* points to pid now */
456 p = skip_whitespace(p);
457 if (process == NULL) {
463 //if (strcmp(process, "swapper") == 0
464 // && strcmp(func, "hrtimer_start_range_ns (tick_sched_timer)\n") == 0
466 // process = "[kernel scheduler]";
467 // func = "Load balancing tick";
470 if (is_prefixed_with(func, "tick_nohz_"))
472 if (is_prefixed_with(func, "tick_setup_sched_timer"))
474 //if (strcmp(process, "powertop") == 0)
477 idx = index_in_strings("insmod\0modprobe\0swapper\0", process);
479 process = idx < 2 ? "[kernel module]" : "<kernel core>";
484 // 46D\01136\0kondemand/1\0do_dbs_timer (delayed_work_timer_fn)
486 // count process func
488 //if (strchr(process, '['))
489 sprintf(line, "%15.15s : %s", process, func);
491 // sprintf(line, "%s", process);
492 save_line(line, cnt);
502 * Get information about CPU using CPUID opcode.
504 static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
507 /* EAX value specifies what information to return */
509 " pushl %%ebx\n" /* Save EBX */
511 " movl %%ebx, %1\n" /* Save content of EBX */
512 " popl %%ebx\n" /* Restore EBX */
513 : "=a"(*eax), /* Output */
517 : "0"(*eax), /* Input */
521 /* No clobbered registers */
527 static NOINLINE void print_intel_cstates(void)
529 int bios_table[8] = { 0 };
534 unsigned eax, ebx, ecx, edx;
536 cpudir = opendir("/sys/devices/system/cpu");
540 /* Loop over cpuN entries */
541 while ((d = readdir(cpudir)) != NULL) {
544 char fname[sizeof("/sys/devices/system/cpu//cpuidle//desc") + 2*BIG_SYSNAME_LEN];
546 len = strlen(d->d_name);
547 if (len < 3 || len > BIG_SYSNAME_LEN)
550 if (!isdigit(d->d_name[3]))
553 len = sprintf(fname, "%s/%s/cpuidle", "/sys/devices/system/cpu", d->d_name);
554 dir = opendir(fname);
559 * Every C-state has its own stateN directory, that
560 * contains a 'time' and a 'usage' file.
562 while ((d = readdir(dir)) != NULL) {
567 n = strlen(d->d_name);
568 if (n < 3 || n > BIG_SYSNAME_LEN)
571 sprintf(fname + len, "/%s/desc", d->d_name);
572 fp = fopen_for_read(fname);
574 char *p = fgets(buf, sizeof(buf), fp);
578 p = strstr(p, "MWAIT ");
581 p += sizeof("MWAIT ") - 1;
582 pos = (bb_strtoull(p, NULL, 16) >> 4) + 1;
583 if (pos >= ARRAY_SIZE(bios_table))
599 cpuid(&eax, &ebx, &ecx, &edx);
600 if (!edx || !(ecx & 1))
603 printf("Your %s the following C-states: ", "CPU supports");
613 /* Print BIOS C-States */
614 printf("Your %s the following C-states: ", "BIOS reports");
615 for (i = 0; i < ARRAY_SIZE(bios_table); i++)
622 # define print_intel_cstates() ((void)0)
625 static void show_timerstats(void)
629 /* Get terminal height */
630 get_terminal_width_height(STDOUT_FILENO, NULL, &lines);
632 /* We don't have whole terminal just for timerstats */
635 if (!G.cant_enable_timer_stats) {
639 puts("\nTop causes for wakeups:");
640 for (i = 0; i < G.lines_cnt; i++) {
641 if ((G.lines[i].count > 0 /*|| G.lines[i].disk_count > 0*/)
644 /* NB: upstream powertop prints "(wakeups/sec)",
645 * we print just "(wakeup counts)".
648 if (G.lines[i].disk_count)
650 smart_ulltoa5(G.lines[i].count, strbuf6, " KMGTPEZY")[0] = '\0';
651 printf(/*" %5.1f%% (%s)%c %s\n"*/
652 " %5.1f%% (%s) %s\n",
653 G.lines[i].count * 100.0 / G.lines_cumulative_count,
660 bb_error_msg("no stats available; run as root or"
661 " enable the timer_stats module");
665 // Example display from powertop version 1.11
666 // Cn Avg residency P-states (frequencies)
667 // C0 (cpu running) ( 0.5%) 2.00 Ghz 0.0%
668 // polling 0.0ms ( 0.0%) 1.67 Ghz 0.0%
669 // C1 mwait 0.0ms ( 0.0%) 1333 Mhz 0.1%
670 // C2 mwait 0.1ms ( 0.1%) 1000 Mhz 99.9%
671 // C3 mwait 12.1ms (99.4%)
673 // Wakeups-from-idle per second : 93.6 interval: 15.0s
674 // no ACPI power usage estimate available
676 // Top causes for wakeups:
677 // 32.4% ( 26.7) <interrupt> : extra timer interrupt
678 // 29.0% ( 23.9) <kernel core> : hrtimer_start_range_ns (tick_sched_timer)
679 // 9.0% ( 7.5) <kernel core> : hrtimer_start (tick_sched_timer)
680 // 6.5% ( 5.3) <interrupt> : ata_piix
681 // 5.0% ( 4.1) inetd : hrtimer_start_range_ns (hrtimer_wakeup)
683 //usage:#define powertop_trivial_usage
685 //usage:#define powertop_full_usage "\n\n"
686 //usage: "Analyze power consumption on Intel-based laptops"
688 int powertop_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
689 int powertop_main(int argc UNUSED_PARAM, char UNUSED_PARAM **argv)
691 ullong cur_usage[MAX_CSTATE_COUNT];
692 ullong cur_duration[MAX_CSTATE_COUNT];
693 char cstate_lines[MAX_CSTATE_COUNT + 2][64];
694 #if ENABLE_FEATURE_POWERTOP_INTERACTIVE
695 struct pollfd pfd[1];
698 pfd[0].events = POLLIN;
703 #if ENABLE_FEATURE_POWERTOP_PROCIRQ && BLOATY_HPET_IRQ_NUM_DETECTION
704 G.percpu_hpet_start = INT_MAX;
705 G.percpu_hpet_end = INT_MIN;
708 /* Print warning when we don't have superuser privileges */
710 bb_error_msg("run as root to collect enough information");
712 /* Get number of CPUs */
713 G.total_cpus = get_cpu_count();
715 puts("Collecting data for "DEFAULT_SLEEP_STR" seconds");
717 #if ENABLE_FEATURE_POWERTOP_INTERACTIVE
718 /* Turn on unbuffered input; turn off echoing, ^C ^Z etc */
719 set_termios_to_raw(STDIN_FILENO, &G.init_settings, TERMIOS_CLEAR_ISIG);
720 bb_signals(BB_FATAL_SIGS, sig_handler);
721 /* So we don't forget to reset term settings */
722 die_func = reset_term;
725 /* Collect initial data */
726 process_irq_counts();
728 /* Read initial usage and duration */
729 read_cstate_counts(G.start_usage, G.start_duration);
731 /* Copy them to "last" */
732 memcpy(G.last_usage, G.start_usage, sizeof(G.last_usage));
733 memcpy(G.last_duration, G.start_duration, sizeof(G.last_duration));
735 /* Display C-states */
736 print_intel_cstates();
738 G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
742 //double maxsleep = 0.0;
743 ullong totalticks, totalevents;
746 G.cant_enable_timer_stats |= start_timer(); /* 1 on error */
747 #if !ENABLE_FEATURE_POWERTOP_INTERACTIVE
748 sleep(DEFAULT_SLEEP);
750 if (safe_poll(pfd, 1, DEFAULT_SLEEP * 1000) > 0) {
752 if (safe_read(STDIN_FILENO, &c, 1) != 1)
753 break; /* EOF/error */
754 if (c == G.init_settings.c_cc[VINTR])
756 if ((c | 0x20) == 'q')
760 G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
763 process_irq_counts();
765 /* Clear the stats */
766 memset(cur_duration, 0, sizeof(cur_duration));
767 memset(cur_usage, 0, sizeof(cur_usage));
770 read_cstate_counts(cur_usage, cur_duration);
772 /* Count totalticks and totalevents */
773 totalticks = totalevents = 0;
774 for (i = 0; i < MAX_CSTATE_COUNT; i++) {
775 if (cur_usage[i] != 0) {
776 totalticks += cur_duration[i] - G.last_duration[i];
777 totalevents += cur_usage[i] - G.last_usage[i];
781 /* Home; clear screen */
782 printf(ESC"[H" ESC"[J");
784 /* Clear C-state lines */
785 memset(&cstate_lines, 0, sizeof(cstate_lines));
787 if (totalevents == 0 && G.maxcstate <= 1) {
788 /* This should not happen */
789 strcpy(cstate_lines[0], "C-state information is not available\n");
794 newticks = G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000 - totalticks;
795 /* Handle rounding errors: do not display negative values */
796 if ((int)newticks < 0)
799 sprintf(cstate_lines[0], "Cn\t\t Avg residency\n");
800 percentage = newticks * 100.0 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
801 sprintf(cstate_lines[1], "C0 (cpu running) (%4.1f%%)\n", percentage);
803 /* Compute values for individual C-states */
804 for (i = 0; i < MAX_CSTATE_COUNT; i++) {
805 if (cur_usage[i] != 0) {
807 slept = (cur_duration[i] - G.last_duration[i])
808 / (cur_usage[i] - G.last_usage[i] + 0.1) / FREQ_ACPI;
809 percentage = (cur_duration[i] - G.last_duration[i]) * 100
810 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
811 sprintf(cstate_lines[i + 2], "C%u\t\t%5.1fms (%4.1f%%)\n",
812 i + 1, slept, percentage);
813 //if (maxsleep < slept)
819 for (i = 0; i < MAX_CSTATE_COUNT + 2; i++)
820 if (cstate_lines[i][0])
821 fputs(cstate_lines[i], stdout);
823 i = process_timer_stats();
824 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
825 if (totalevents == 0) {
826 /* No C-state info available, use timerstats */
827 totalevents = i * G.total_cpus + G.total_interrupt;
829 totalevents += G.interrupt_0 - i;
832 /* Upstream powertop prints wakeups per sec per CPU,
833 * we print just raw wakeup counts.
835 //TODO: show real seconds (think about manual refresh)
836 printf("\nWakeups-from-idle in %u seconds: %llu\n",
841 update_lines_cumulative_count();
846 /* Clear the stats */
847 memset(cur_duration, 0, sizeof(cur_duration));
848 memset(cur_usage, 0, sizeof(cur_usage));
851 read_cstate_counts(cur_usage, cur_duration);
854 memcpy(G.last_usage, cur_usage, sizeof(G.last_usage));
855 memcpy(G.last_duration, cur_duration, sizeof(G.last_duration));
859 #if ENABLE_FEATURE_POWERTOP_INTERACTIVE