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
24 //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
25 #define debug(fmt, ...) ((void)0)
27 // XXX This should not be here
28 #define ENABLE_FEATURE_POWERTOP_PROCIRQ 1
30 #define DEFAULT_SLEEP 10
31 #define DEFAULT_SLEEP_STR "10"
33 /* Frequency of the ACPI timer */
34 #define FREQ_ACPI 3579.545
35 #define FREQ_ACPI_1000 3579545
37 /* Max filename length of entry in /sys/devices subsystem */
38 #define BIG_SYSNAME_LEN 16
40 typedef unsigned long long ullong;
48 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
66 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
69 int percpu_hpet_start;
71 struct irqdata interrupts[IRQCOUNT];
74 ullong start_usage[8];
76 ullong start_duration[8];
77 ullong last_duration[8];
78 char cstate_names[8][16];
80 #if ENABLE_FEATURE_USE_TERMIOS
81 struct termios init_settings;
84 #define G (*ptr_to_globals)
85 #define INIT_G() do { \
86 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
89 #if ENABLE_FEATURE_USE_TERMIOS
90 static void reset_term(void)
92 tcsetattr_stdin_TCSANOW(&G.init_settings);
95 static void sig_handler(int signo UNUSED_PARAM)
102 static int write_str_to_file(const char *fname, const char *str)
104 FILE *fp = fopen_for_write(fname);
112 /* Make it more readable */
113 #define start_timer() write_str_to_file("/proc/timer_stats", "1\n")
114 #define stop_timer() write_str_to_file("/proc/timer_stats", "0\n")
116 static void NOINLINE clear_lines(void)
120 for (i = 0; i < G.headline; i++)
121 free(G.lines[i].string);
123 G.headline = G.linesize = 0;
127 static void count_lines(void)
131 for (i = 0; i < G.headline; i++)
132 G.nlines += G.lines[i].count;
135 static int line_compare(const void *p1, const void *p2)
137 const struct line *a = p1;
138 const struct line *b = p2;
140 return (b->count + 50 * b->disk_count) - (a->count + 50 * a->disk_count);
143 static void do_sort(void)
145 qsort(G.lines, G.headline, sizeof(struct line), line_compare);
149 * Save C-state names, usage and duration. Also get maxcstate.
150 * Reads data from /proc.
152 static void read_data(ullong *usage, ullong *duration)
157 dir = opendir("/proc/acpi/processor");
161 while ((d = readdir(dir)) != NULL) {
167 len = strlen(d->d_name);
168 if (len < 3 || len > BIG_SYSNAME_LEN)
171 sprintf(buf, "/proc/acpi/processor/%s/power", d->d_name);
172 fp = fopen_for_read(buf);
176 while (fgets(buf, sizeof(buf), fp)) {
180 p = strstr(buf, "age[");
184 usage[level] += bb_strtoull(p, NULL, 10) + 1;
187 p = strstr(buf, "ation[");
191 duration[level] += bb_strtoull(p, NULL, 10);
193 /* Increment level */
196 /* Also update maxcstate */
197 if (level > G.maxcstate)
205 /* Add line and/or update count */
206 static void push_line(const char *string, int count)
213 /* Loop through entries */
214 for (i = 0; i < G.headline; i++) {
215 if (strcmp(string, G.lines[i].string) == 0) {
216 /* It's already there, only update count */
217 G.lines[i].count += count;
222 G.lines = xrealloc_vector(G.lines, 1, G.headline);
224 G.lines[G.headline].string = xstrdup(string);
225 G.lines[G.headline].count = count;
226 G.lines[G.headline].disk_count = 0;
228 /* We added a line */
232 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
233 static int percpu_hpet_timer(const char *name)
238 /* This is done once */
239 if (!G.timer_list_read) {
243 G.timer_list_read = true;
244 fp = fopen_for_read("/proc/timer_list");
248 while (fgets(buf, sizeof(buf), fp)) {
249 p = strstr(buf, "Clock Event Device: hpet");
252 p += sizeof("Clock Event Device: hpet")-1;
255 hpet_chan = xatoi_positive(p);
256 if (hpet_chan < G.percpu_hpet_start)
257 G.percpu_hpet_start = hpet_chan;
258 if (hpet_chan > G.percpu_hpet_end)
259 G.percpu_hpet_end = hpet_chan;
264 p = strstr(name, "hpet");
272 hpet_chan = xatoi_positive(p);
273 if (G.percpu_hpet_start <= hpet_chan && hpet_chan <= G.percpu_hpet_end)
279 static int update_irq(int irq, ullong count)
281 int unused = IRQCOUNT;
284 for (i = 0; i < IRQCOUNT; i++) {
285 if (G.interrupts[i].active && G.interrupts[i].number == irq) {
287 old = G.interrupts[i].count;
288 G.interrupts[i].count = count;
291 if (!G.interrupts[i].active && unused > i)
295 G.interrupts[unused].active = 1;
296 G.interrupts[unused].count = count;
297 G.interrupts[unused].number = irq;
303 * Read /proc/interrupts, save IRQ counts and IRQ description.
305 static void do_proc_irq(void)
312 G.total_interrupt = 0;
314 fp = xfopen_for_read("/proc/interrupts");
315 while (fgets(buf, sizeof(buf), fp)) {
316 char irq_desc[sizeof(" <kernel IPI> : ") + sizeof(buf)];
325 p = strchr(buf, ':');
328 /* 0: 143646045 153901007 IO-APIC-edge timer
331 /* Deal with non-maskable interrupts -- make up fake numbers */
333 if (buf[0] != ' ' && !isdigit(buf[0])) {
334 if (strncmp(buf, "NMI:", 4) == 0)
336 if (strncmp(buf, "RES:", 4) == 0)
338 if (strncmp(buf, "CAL:", 4) == 0)
340 if (strncmp(buf, "TLB:", 4) == 0)
342 if (strncmp(buf, "TRM:", 4) == 0)
344 if (strncmp(buf, "THR:", 4) == 0)
346 if (strncmp(buf, "SPU:", 4) == 0)
350 /* bb_strtou don't eat leading spaces, using strtoul */
351 nr = strtoul(buf, NULL, 10); /* xato*() wouldn't work */
357 /* 0: 143646045 153901007 IO-APIC-edge timer
360 /* Count sum of the IRQs */
364 p = skip_whitespace(p);
367 count += bb_strtoull(p, &tmp, 10);
370 /* 0: 143646045 153901007 IO-APIC-edge timer
371 * NMI: 1 2 Non-maskable interrupts
375 /* Skip to the interrupt name, e.g. 'timer' */
379 p = skip_whitespace(p);
383 strchrnul(name, '\n')[0] = '\0';
384 /* Save description of the interrupt */
386 sprintf(irq_desc, " <kernel IPI> : %s", name);
388 sprintf(irq_desc, " <interrupt> : %s", name);
390 delta = update_irq(nr, count);
392 /* Skip per CPU timer interrupts */
393 if (percpu_hpet_timer(name))
395 if (nr > 0 && delta > 0)
396 push_line(irq_desc, delta);
398 G.interrupt_0 = delta;
400 G.total_interrupt += delta;
405 #endif /* ENABLE_FEATURE_POWERTOP_PROCIRQ */
409 * Get information about CPU using CPUID opcode.
411 static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
414 /* EAX value specifies what information to return */
416 " pushl %%ebx\n" /* Save EBX */
418 " movl %%ebx, %1\n" /* Save content of EBX */
419 " popl %%ebx\n" /* Restore EBX */
420 : "=a"(*eax), /* Output */
424 : "0"(*eax), /* Input */
428 /* No clobbered registers */
433 static void NOINLINE print_intel_cstates(void)
436 int bios_table[8] = { 0 };
441 unsigned eax, ebx, ecx, edx;
443 cpudir = opendir("/sys/devices/system/cpu");
447 /* Loop over cpuN entries */
448 while ((d = readdir(cpudir)) != NULL) {
451 char fname[sizeof("/sys/devices/system/cpu//cpuidle//desc") + 2*BIG_SYSNAME_LEN];
453 len = strlen(d->d_name);
454 if (len < 3 || len > BIG_SYSNAME_LEN)
457 if (!isdigit(d->d_name[3]))
460 len = sprintf(fname, "/sys/devices/system/cpu/%s/cpuidle", d->d_name);
461 dir = opendir(fname);
466 * Every C-state has its own stateN directory, that
467 * contains a `time' and a `usage' file.
469 while ((d = readdir(dir)) != NULL) {
474 n = strlen(d->d_name);
475 if (n < 3 || n > BIG_SYSNAME_LEN)
478 sprintf(fname + len, "/%s/desc", d->d_name);
479 fp = fopen_for_read(fname);
481 char *p = fgets(buf, sizeof(buf), fp);
485 p = strstr(p, "MWAIT ");
488 p += sizeof("MWAIT ") - 1;
489 pos = (bb_strtoull(p, NULL, 16) >> 4) + 1;
490 if (pos >= ARRAY_SIZE(bios_table))
506 cpuid(&eax, &ebx, &ecx, &edx);
507 if (!edx || !(ecx & 1))
510 printf("Your CPU supports the following C-states: ");
520 /* Print BIOS C-States */
521 printf("Your BIOS reports the following C-states: ");
522 for (i = 0; i < 8; i++)
530 static void print_header(void)
533 /* Clear the screen */
535 /* Print the header */
536 "\033[7m%.*s\033[0m", 79, "PowerTOP (C) 2007 Intel Corporation\n"
540 static void show_cstates(char cstate_lines[][64])
544 for (i = 0; i < 10; i++)
545 if ((cstate_lines[i][0]))
546 printf("%s", cstate_lines[i]);
549 static void show_timerstats(int nostats)
553 /* Get terminal height */
554 get_terminal_width_height(STDOUT_FILENO, NULL, &lines);
556 /* We don't have whole terminal just for timerstats */
562 puts("\nTop causes for wakeups:");
563 for (i = 0; i < G.headline; i++) {
564 if ((G.lines[i].count > 0 || G.lines[i].disk_count > 0)
568 if (G.lines[i].disk_count)
570 printf(" %5.1f%% (%5.1f)%c %s\n",
571 G.lines[i].count * 100.0 / G.nlines,
572 G.lines[i].count * 1.0 / DEFAULT_SLEEP, c,
578 bb_error_msg("no stats available; run as root or"
579 " enable the cpufreq_stats module");
583 //usage:#define powertop_trivial_usage
585 //usage:#define powertop_full_usage "\n\n"
586 //usage: "Analyze power consumption on Intel-based laptops\n"
588 int powertop_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
589 int powertop_main(int UNUSED_PARAM argc, char UNUSED_PARAM **argv)
592 ullong cur_duration[8];
593 char cstate_lines[12][64];
595 #if ENABLE_FEATURE_USE_TERMIOS
596 struct termios new_settings;
597 struct pollfd pfd[1];
600 pfd[0].events = POLLIN;
605 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
606 G.percpu_hpet_start = INT_MAX;
607 G.percpu_hpet_end = INT_MIN;
610 /* Print warning when we don't have superuser privileges */
612 bb_error_msg("run as root to collect enough information");
614 #if ENABLE_FEATURE_USE_TERMIOS
615 /* So we don't forget to reset term settings */
619 /* Get number of CPUs */
620 G.total_cpus = get_cpu_count();
622 printf("Collecting data for "DEFAULT_SLEEP_STR" seconds\n");
624 #if ENABLE_FEATURE_USE_TERMIOS
625 tcgetattr(0, (void *)&G.init_settings);
626 memcpy(&new_settings, &G.init_settings, sizeof(new_settings));
628 /* Turn on unbuffered input, turn off echoing */
629 new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
631 bb_signals(BB_FATAL_SIGS, sig_handler);
632 tcsetattr_stdin_TCSANOW(&new_settings);
635 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
636 /* Collect initial data */
641 /* Read initial usage and duration */
642 read_data(&G.start_usage[0], &G.start_duration[0]);
644 /* Copy them to "last" */
645 memcpy(G.last_usage, G.start_usage, sizeof(G.last_usage));
646 memcpy(G.last_duration, G.start_duration, sizeof(G.last_duration));
648 /* Display C-states */
649 print_intel_cstates();
656 double maxsleep = 0.0;
657 ullong totalticks, totalevents;
665 #if !ENABLE_FEATURE_USE_TERMIOS
666 sleep(DEFAULT_SLEEP);
668 if (safe_poll(pfd, 1, DEFAULT_SLEEP * 1000) > 0) {
670 if (safe_read(STDIN_FILENO, &c, 1) != 1)
671 break; /* EOF/error */
672 if (c == G.init_settings.c_cc[VINTR])
674 if ((c | 0x20) == 'q')
683 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
687 /* Clear the stats */
688 memset(cur_duration, 0, sizeof(cur_duration));
689 memset(cur_usage, 0, sizeof(cur_usage));
692 read_data(&cur_usage[0], &cur_duration[0]);
694 totalticks = totalevents = 0;
696 /* Count totalticks and totalevents */
697 for (i = 0; i < 8; i++) {
699 totalticks += cur_duration[i] - G.last_duration[i];
700 totalevents += cur_usage[i] - G.last_usage[i];
707 /* Clear C-state lines */
708 memset(&cstate_lines, 0, sizeof(cstate_lines));
710 if (totalevents == 0 && G.maxcstate <= 1) {
711 /* This should not happen */
712 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 < 8; i++) {
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 */
756 fp = fopen_for_read("/proc/timer_stats");
758 while (fgets(buf, sizeof(buf), fp)) {
759 const char *count, *process, *func;
762 bool defferable = false;
766 /* Find char ' ', then eat remaining spaces */
767 #define ADVANCE(p) do { \
768 (p) = strchr((p), ' '); \
773 (p) = skip_whitespace(p); \
776 if (strstr(buf, "total events"))
779 while (isspace(buf[j]))
792 p = skip_whitespace(p);
802 if (strcmp(process, "swapper") == 0
803 && strcmp(func, "hrtimer_start_range_ns (tick_sched_timer)\n") == 0
805 process = "[kernel scheduler]";
806 func = "Load balancing tick";
809 if (strcmp(process, "insmod") == 0)
810 process = "[kernel module]";
811 if (strcmp(process, "modprobe") == 0)
812 process = "[kernel module]";
813 if (strcmp(process, "swapper") == 0)
814 process = "[kernel core]";
818 if (strncmp(func, "tick_nohz_", 10) == 0)
820 if (strncmp(func, "tick_setup_sched_timer", 20) == 0)
822 if (strcmp(process, "powertop") == 0)
828 cnt = bb_strtoull(count, &p, 10);
836 if (strchr(process, '['))
837 sprintf(line, "%s %s", process, func);
839 sprintf(line, "%s", process);
840 push_line(line, cnt);
845 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
846 if (strstr(buf, "total events")) {
847 int n = bb_strtoull(buf, NULL, 10) / G.total_cpus;
849 if (totalevents == 0) {
850 /* No C-state info available, use timerstats */
851 totalevents = n * G.total_cpus + G.total_interrupt;
853 totalevents += G.interrupt_0 - n;
855 if (n > 0 && n < G.interrupt_0)
856 push_line("[extra timer interrupt]", G.interrupt_0 - n);
860 printf("\n\033[1mWakeups-from-idle per second : %4.1f\tinterval:"
862 (double)totalevents / DEFAULT_SLEEP / G.total_cpus, DEFAULT_SLEEP);
867 show_timerstats(G.nostats);
871 /* Clear the stats */
872 memset(cur_duration, 0, sizeof(cur_duration));
873 memset(cur_usage, 0, sizeof(cur_usage));
876 read_data(&cur_usage[0], &cur_duration[0]);
879 memcpy(G.last_usage, cur_usage, sizeof(G.last_usage));
880 memcpy(G.last_duration, cur_duration, sizeof(G.last_duration));