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 de 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
66 int lines_cumulative_count;
71 smallint cant_enable_timer_stats;
72 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
73 # if BLOATY_HPET_IRQ_NUM_DETECTION
74 smallint scanned_timer_list;
75 int percpu_hpet_start;
80 struct irqdata interrupts[IRQCOUNT];
82 ullong start_usage[MAX_CSTATE_COUNT];
83 ullong last_usage[MAX_CSTATE_COUNT];
84 ullong start_duration[MAX_CSTATE_COUNT];
85 ullong last_duration[MAX_CSTATE_COUNT];
86 char cstate_names[MAX_CSTATE_COUNT][16];
87 #if ENABLE_FEATURE_USE_TERMIOS
88 struct termios init_settings;
91 #define G (*ptr_to_globals)
92 #define INIT_G() do { \
93 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
96 #if ENABLE_FEATURE_USE_TERMIOS
97 static void reset_term(void)
99 tcsetattr_stdin_TCSANOW(&G.init_settings);
102 static void sig_handler(int signo UNUSED_PARAM)
109 static int write_str_to_file(const char *fname, const char *str)
111 FILE *fp = fopen_for_write(fname);
119 /* Make it more readable */
120 #define start_timer() write_str_to_file("/proc/timer_stats", "1\n")
121 #define stop_timer() write_str_to_file("/proc/timer_stats", "0\n")
123 static void NOINLINE 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, 1, 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_count_deltas(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_count_deltas() ((void)0)
407 * Get information about CPU using CPUID opcode.
409 static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
412 /* EAX value specifies what information to return */
414 " pushl %%ebx\n" /* Save EBX */
416 " movl %%ebx, %1\n" /* Save content of EBX */
417 " popl %%ebx\n" /* Restore EBX */
418 : "=a"(*eax), /* Output */
422 : "0"(*eax), /* Input */
426 /* No clobbered registers */
431 static void NOINLINE print_intel_cstates(void)
434 int bios_table[8] = { 0 };
439 unsigned eax, ebx, ecx, edx;
441 cpudir = opendir("/sys/devices/system/cpu");
445 /* Loop over cpuN entries */
446 while ((d = readdir(cpudir)) != NULL) {
449 char fname[sizeof("/sys/devices/system/cpu//cpuidle//desc") + 2*BIG_SYSNAME_LEN];
451 len = strlen(d->d_name);
452 if (len < 3 || len > BIG_SYSNAME_LEN)
455 if (!isdigit(d->d_name[3]))
458 len = sprintf(fname, "/sys/devices/system/cpu/%s/cpuidle", d->d_name);
459 dir = opendir(fname);
464 * Every C-state has its own stateN directory, that
465 * contains a `time' and a `usage' file.
467 while ((d = readdir(dir)) != NULL) {
472 n = strlen(d->d_name);
473 if (n < 3 || n > BIG_SYSNAME_LEN)
476 sprintf(fname + len, "/%s/desc", d->d_name);
477 fp = fopen_for_read(fname);
479 char *p = fgets(buf, sizeof(buf), fp);
483 p = strstr(p, "MWAIT ");
486 p += sizeof("MWAIT ") - 1;
487 pos = (bb_strtoull(p, NULL, 16) >> 4) + 1;
488 if (pos >= ARRAY_SIZE(bios_table))
504 cpuid(&eax, &ebx, &ecx, &edx);
505 if (!edx || !(ecx & 1))
508 printf("Your CPU supports the following C-states: ");
518 /* Print BIOS C-States */
519 printf("Your BIOS reports the following C-states: ");
520 for (i = 0; i < 8; i++)
528 static void print_header(void)
531 /* Clear the screen */
533 /* Print the header */
534 "\033[7m%.*s\033[0m", 79, "PowerTOP (C) 2007 Intel Corporation\n"
538 static void show_cstates(char cstate_lines[][64])
542 for (i = 0; i < 10; i++)
543 if ((cstate_lines[i][0]))
544 printf("%s", cstate_lines[i]);
547 static void show_timerstats(void)
551 /* Get terminal height */
552 get_terminal_width_height(STDOUT_FILENO, NULL, &lines);
554 /* We don't have whole terminal just for timerstats */
557 if (!G.cant_enable_timer_stats) {
560 puts("\nTop causes for wakeups:");
561 for (i = 0; i < G.lines_cnt; i++) {
562 if ((G.lines[i].count > 0 /*|| G.lines[i].disk_count > 0*/)
566 /*if (G.lines[i].disk_count)
568 printf(" %5.1f%% (%5.1f)%c %s\n",
569 G.lines[i].count * 100.0 / G.lines_cumulative_count,
570 G.lines[i].count * 1.0 / DEFAULT_SLEEP, c,
576 bb_error_msg("no stats available; run as root or"
577 " enable the cpufreq_stats module");
581 // Example display from powertop version 1.11
582 // Cn Avg residency P-states (frequencies)
583 // C0 (cpu running) ( 0.5%) 2.00 Ghz 0.0%
584 // polling 0.0ms ( 0.0%) 1.67 Ghz 0.0%
585 // C1 mwait 0.0ms ( 0.0%) 1333 Mhz 0.1%
586 // C2 mwait 0.1ms ( 0.1%) 1000 Mhz 99.9%
587 // C3 mwait 12.1ms (99.4%)
589 // Wakeups-from-idle per second : 93.6 interval: 15.0s
590 // no ACPI power usage estimate available
592 // Top causes for wakeups:
593 // 32.4% ( 26.7) <interrupt> : extra timer interrupt
594 // 29.0% ( 23.9) <kernel core> : hrtimer_start_range_ns (tick_sched_timer)
595 // 9.0% ( 7.5) <kernel core> : hrtimer_start (tick_sched_timer)
596 // 6.5% ( 5.3) <interrupt> : ata_piix
597 // 5.0% ( 4.1) inetd : hrtimer_start_range_ns (hrtimer_wakeup)
599 //usage:#define powertop_trivial_usage
601 //usage:#define powertop_full_usage "\n\n"
602 //usage: "Analyze power consumption on Intel-based laptops\n"
604 int powertop_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
605 int powertop_main(int UNUSED_PARAM argc, char UNUSED_PARAM **argv)
607 ullong cur_usage[MAX_CSTATE_COUNT];
608 ullong cur_duration[MAX_CSTATE_COUNT];
609 char cstate_lines[12][64];
611 #if ENABLE_FEATURE_USE_TERMIOS
612 struct termios new_settings;
613 struct pollfd pfd[1];
616 pfd[0].events = POLLIN;
621 #if ENABLE_FEATURE_POWERTOP_PROCIRQ && BLOATY_HPET_IRQ_NUM_DETECTION
622 G.percpu_hpet_start = INT_MAX;
623 G.percpu_hpet_end = INT_MIN;
626 /* Print warning when we don't have superuser privileges */
628 bb_error_msg("run as root to collect enough information");
630 /* Get number of CPUs */
631 G.total_cpus = get_cpu_count();
633 printf("Collecting data for "DEFAULT_SLEEP_STR" seconds\n");
635 #if ENABLE_FEATURE_USE_TERMIOS
636 tcgetattr(0, (void *)&G.init_settings);
637 memcpy(&new_settings, &G.init_settings, sizeof(new_settings));
638 /* Turn on unbuffered input, turn off echoing */
639 new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
640 /* So we don't forget to reset term settings */
642 bb_signals(BB_FATAL_SIGS, sig_handler);
643 tcsetattr_stdin_TCSANOW(&new_settings);
646 /* Collect initial data */
647 process_irq_count_deltas();
649 /* Read initial usage and duration */
650 read_cstate_counts(G.start_usage, G.start_duration);
652 /* Copy them to "last" */
653 memcpy(G.last_usage, G.start_usage, sizeof(G.last_usage));
654 memcpy(G.last_duration, G.start_duration, sizeof(G.last_duration));
656 /* Display C-states */
657 print_intel_cstates();
659 G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
663 /*double maxsleep = 0.0;*/
664 ullong totalticks, totalevents;
668 G.cant_enable_timer_stats |= start_timer(); /* 1 on error */
669 #if !ENABLE_FEATURE_USE_TERMIOS
670 sleep(DEFAULT_SLEEP);
672 if (safe_poll(pfd, 1, DEFAULT_SLEEP * 1000) > 0) {
674 if (safe_read(STDIN_FILENO, &c, 1) != 1)
675 break; /* EOF/error */
676 if (c == G.init_settings.c_cc[VINTR])
678 if ((c | 0x20) == 'q')
682 G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
685 process_irq_count_deltas();
687 /* Clear the stats */
688 memset(cur_duration, 0, sizeof(cur_duration));
689 memset(cur_usage, 0, sizeof(cur_usage));
692 read_cstate_counts(cur_usage, cur_duration);
694 /* Count totalticks and totalevents */
695 totalticks = totalevents = 0;
696 for (i = 0; i < MAX_CSTATE_COUNT; i++) {
697 if (cur_usage[i] != 0) {
698 totalticks += cur_duration[i] - G.last_duration[i];
699 totalevents += cur_usage[i] - G.last_usage[i];
706 /* Clear C-state lines */
707 memset(&cstate_lines, 0, sizeof(cstate_lines));
709 if (totalevents == 0 && G.maxcstate <= 1) {
710 /* This should not happen */
711 sprintf(cstate_lines[5], "< Detailed C-state information is not "
718 newticks = G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000 - totalticks;
720 /* Handle rounding errors: do not display negative values */
724 sprintf(cstate_lines[0], "Cn\t Avg residency\n");
725 percentage = newticks * 100.0 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
726 sprintf(cstate_lines[1], "C0 (cpu running) (%4.1f%%)\n",
729 /* Compute values for individual C-states */
730 for (i = 0; i < MAX_CSTATE_COUNT; i++) {
731 if (cur_usage[i] != 0) {
732 slept = (cur_duration[i] - G.last_duration[i])
733 / (cur_usage[i] - G.last_usage[i] + 0.1) / FREQ_ACPI;
734 percentage = (cur_duration[i] - G.last_duration[i]) * 100
735 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
737 if (!G.cstate_names[i][0])
738 sprintf(G.cstate_names[i], "C%u", i + 1);
739 sprintf(cstate_lines[i + 2], "%s\t%5.1fms (%4.1f%%)\n",
740 G.cstate_names[i], slept, percentage);
741 /*if (maxsleep < slept)
747 /* Display C-states */
748 show_cstates(cstate_lines);
750 /* Do timer_stats info */
755 if (!G.cant_enable_timer_stats)
756 fp = fopen_for_read("/proc/timer_stats");
758 // Examlpe file contents:
759 // Timer Stats Version: v0.2
760 // Sample period: 1.329 s
761 // 76, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
762 // 88, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
763 // 24, 3787 firefox hrtimer_start_range_ns (hrtimer_wakeup)
764 // 46D, 1136 kondemand/1 do_dbs_timer (delayed_work_timer_fn)
766 // 1, 1656 Xorg hrtimer_start_range_ns (hrtimer_wakeup)
767 // 1, 2159 udisks-daemon hrtimer_start_range_ns (hrtimer_wakeup)
768 // 331 total events, 249.059 events/sec
769 while (fgets(buf, sizeof(buf), fp)) {
770 const char *count, *process, *func;
775 if (strstr(buf, "total events"))
777 count = skip_whitespace(buf);
778 p = strchr(count, ',');
782 p = skip_whitespace(p); /* points to pid */
784 /* Find char ' ', then eat remaining spaces */
785 #define ADVANCE(p) do { \
786 (p) = strchr((p), ' '); \
791 (p) = skip_whitespace(p); \
793 /* Get process name */
801 if (strcmp(process, "swapper") == 0
802 && strcmp(func, "hrtimer_start_range_ns (tick_sched_timer)\n") == 0
804 process = "[kernel scheduler]";
805 func = "Load balancing tick";
808 if (strcmp(process, "insmod") == 0)
809 process = "[kernel module]";
810 if (strcmp(process, "modprobe") == 0)
811 process = "[kernel module]";
812 if (strcmp(process, "swapper") == 0)
813 process = "[kernel core]";
815 if (strncmp(func, "tick_nohz_", 10) == 0)
817 if (strncmp(func, "tick_setup_sched_timer", 20) == 0)
819 if (strcmp(process, "powertop") == 0)
822 strchrnul(p, '\n')[0] = '\0';
824 cnt = bb_strtoull(count, &p, 10);
830 if (strchr(process, '['))
831 sprintf(line, "%s %s", process, func);
833 sprintf(line, "%s", process);
834 save_line(line, cnt);
840 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
841 if (strstr(buf, "total events")) {
842 int n = bb_strtoull(buf, NULL, 10) / G.total_cpus;
844 if (totalevents == 0) {
845 /* No C-state info available, use timerstats */
846 totalevents = n * G.total_cpus + G.total_interrupt;
848 totalevents += G.interrupt_0 - n;
850 if (n > 0 && n < G.interrupt_0)
851 save_line("[extra timer interrupt]", G.interrupt_0 - n);
854 if (totalevents != 0)
855 printf("\n\033[1mWakeups-from-idle per second : %4.1f\tinterval:"
857 (double)totalevents / DEFAULT_SLEEP / G.total_cpus, DEFAULT_SLEEP);
859 update_lines_cumulative_count();
864 /* Clear the stats */
865 memset(cur_duration, 0, sizeof(cur_duration));
866 memset(cur_usage, 0, sizeof(cur_usage));
869 read_cstate_counts(cur_usage, cur_duration);
872 memcpy(G.last_usage, cur_usage, sizeof(G.last_usage));
873 memcpy(G.last_duration, cur_duration, sizeof(G.last_duration));