powertop: code shrink
[platform/upstream/busybox.git] / procps / powertop.c
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
12 //applet:IF_POWERTOP(APPLET(powertop, _BB_DIR_BIN, _BB_SUID_DROP))
13
14 //kbuild:lib-$(CONFIG_POWERTOP) += powertop.o
15
16 //config:config POWERTOP
17 //config:       bool "powertop"
18 //config:       default y
19 //config:       help
20 //config:         Analyze power consumption on Intel-based laptops
21
22 // XXX This should de configurable
23 #define ENABLE_FEATURE_POWERTOP_PROCIRQ 1
24
25 #include "libbb.h"
26
27
28 //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
29 #define debug(fmt, ...) ((void)0)
30
31
32 #define BLOATY_HPET_IRQ_NUM_DETECTION 0
33 #define MAX_CSTATE_COUNT   8
34 #define IRQCOUNT           40
35
36
37 #define DEFAULT_SLEEP      10
38 #define DEFAULT_SLEEP_STR "10"
39
40 /* Frequency of the ACPI timer */
41 #define FREQ_ACPI          3579.545
42 #define FREQ_ACPI_1000     3579545
43
44 /* Max filename length of entry in /sys/devices subsystem */
45 #define BIG_SYSNAME_LEN    16
46
47 typedef unsigned long long ullong;
48
49 struct line {
50         char *string;
51         int count;
52         /*int disk_count;*/
53 };
54
55 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
56 struct irqdata {
57         smallint active;
58         int number;
59         ullong count;
60         char irq_desc[32];
61 };
62 #endif
63
64 struct globals {
65         int lines_cnt;
66         int lines_cumulative_count;
67         int linesize;
68         int maxcstate;
69         unsigned total_cpus;
70         struct line *lines;
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;
76         int percpu_hpet_end;
77 # endif
78         int interrupt_0;
79         int total_interrupt;
80         struct irqdata interrupts[IRQCOUNT];
81 #endif
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;
89 #endif
90 };
91 #define G (*ptr_to_globals)
92 #define INIT_G() do { \
93         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
94 } while (0)
95
96 #if ENABLE_FEATURE_USE_TERMIOS
97 static void reset_term(void)
98 {
99         tcsetattr_stdin_TCSANOW(&G.init_settings);
100 }
101
102 static void sig_handler(int signo UNUSED_PARAM)
103 {
104         reset_term();
105         _exit(EXIT_FAILURE);
106 }
107 #endif
108
109 static int write_str_to_file(const char *fname, const char *str)
110 {
111         FILE *fp = fopen_for_write(fname);
112         if (!fp)
113                 return 1;
114         fputs(str, fp);
115         fclose(fp);
116         return 0;
117 }
118
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")
122
123 static void NOINLINE clear_lines(void)
124 {
125         int i;
126         for (i = 0; i < G.lines_cnt; i++)
127                 free(G.lines[i].string);
128         free(G.lines);
129         G.lines_cnt = 0;
130         G.linesize = 0;
131         G.lines = NULL;
132 }
133
134 static void update_lines_cumulative_count(void)
135 {
136         int i;
137         for (i = 0; i < G.lines_cnt; i++)
138                 G.lines_cumulative_count += G.lines[i].count;
139 }
140
141 static int line_compare(const void *p1, const void *p2)
142 {
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*/);
146 }
147
148 static void sort_lines(void)
149 {
150         qsort(G.lines, G.lines_cnt, sizeof(G.lines[0]), line_compare);
151 }
152
153 /* Save C-state usage and duration. Also update maxcstate. */
154 static void read_cstate_counts(ullong *usage, ullong *duration)
155 {
156         DIR *dir;
157         struct dirent *d;
158
159         dir = opendir("/proc/acpi/processor");
160         if (!dir)
161                 return;
162
163         while ((d = readdir(dir)) != NULL) {
164                 FILE *fp;
165                 char buf[192];
166                 int level;
167                 int len;
168
169                 len = strlen(d->d_name); /* "CPUnn" */
170                 if (len < 3 || len > BIG_SYSNAME_LEN)
171                         continue;
172
173                 sprintf(buf, "/proc/acpi/processor/%s/power", d->d_name);
174                 fp = fopen_for_read(buf);
175                 if (!fp)
176                         continue;
177
178 // Example file contents:
179 // active state:            C0
180 // max_cstate:              C8
181 // maximum allowed latency: 2000000000 usec
182 // states:
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]
186                 level = 0;
187                 while (fgets(buf, sizeof(buf), fp)) {
188                         char *p = strstr(buf, "age[");
189                         if (!p)
190                                 continue;
191                         p += 4;
192                         usage[level] += bb_strtoull(p, NULL, 10) + 1;
193                         p = strstr(buf, "ation[");
194                         if (!p)
195                                 continue;
196                         p += 6;
197                         duration[level] += bb_strtoull(p, NULL, 10);
198
199                         if (level >= MAX_CSTATE_COUNT-1)
200                                 break;
201                         level++;
202                         if (level > G.maxcstate)  /* update maxcstate */
203                                 G.maxcstate = level;
204                 }
205                 fclose(fp);
206         }
207         closedir(dir);
208 }
209
210 /* Add line and/or update count */
211 static void save_line(const char *string, int count)
212 {
213         int i;
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;
218                         return;
219                 }
220         }
221
222         /* Add new line */
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;*/
227         G.lines_cnt++;
228 }
229
230 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
231 static int is_hpet_irq(const char *name)
232 {
233         char *p;
234 # if BLOATY_HPET_IRQ_NUM_DETECTION
235         long hpet_chan;
236
237         /* Learn the range of existing hpet timers. This is done once */
238         if (!G.scanned_timer_list) {
239                 FILE *fp;
240                 char buf[80];
241
242                 G.scanned_timer_list = true;
243                 fp = fopen_for_read("/proc/timer_list");
244                 if (!fp)
245                         return 0;
246
247                 while (fgets(buf, sizeof(buf), fp)) {
248                         p = strstr(buf, "Clock Event Device: hpet");
249                         if (!p)
250                                 continue;
251                         p += sizeof("Clock Event Device: hpet")-1;
252                         if (!isdigit(*p))
253                                 continue;
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;
259                 }
260                 fclose(fp);
261         }
262 # endif
263 //TODO: optimize
264         p = strstr(name, "hpet");
265         if (!p)
266                 return 0;
267         p += 4;
268         if (!isdigit(*p))
269                 return 0;
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)
273                 return 0;
274 # endif
275         return 1;
276 }
277
278 /* Save new IRQ count, return delta from old one */
279 static int save_irq_count(int irq, ullong count)
280 {
281         int unused = IRQCOUNT;
282         int i;
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;
287                         return count - old;
288                 }
289                 if (!G.interrupts[i].active && unused > i)
290                         unused = i;
291         }
292         if (unused < IRQCOUNT) {
293                 G.interrupts[unused].active = 1;
294                 G.interrupts[unused].count = count;
295                 G.interrupts[unused].number = irq;
296         }
297         return count;
298 }
299
300 /* Read /proc/interrupts, save IRQ counts and IRQ description */
301 static void process_irq_count_deltas(void)
302 {
303         FILE *fp;
304         char buf[128];
305
306         /* Reset values */
307         G.interrupt_0 = 0;
308         G.total_interrupt = 0;
309
310         fp = xfopen_for_read("/proc/interrupts");
311         while (fgets(buf, sizeof(buf), fp)) {
312                 char irq_desc[sizeof("   <kernel IPI> : ") + sizeof(buf)];
313                 char *p;
314                 const char *name;
315                 int nr;
316                 ullong count;
317                 ullong delta;
318
319                 p = strchr(buf, ':');
320                 if (!p)
321                         continue;
322                 /*  0:  143646045  153901007   IO-APIC-edge      timer
323                  *   ^
324                  */
325                 /* Deal with non-maskable interrupts -- make up fake numbers */
326                 nr = -1;
327                 if (buf[0] != ' ' && !isdigit(buf[0])) {
328 //TODO: optimize
329                         if (strncmp(buf, "NMI:", 4) == 0)
330                                 nr = 20000;
331                         if (strncmp(buf, "RES:", 4) == 0)
332                                 nr = 20001;
333                         if (strncmp(buf, "CAL:", 4) == 0)
334                                 nr = 20002;
335                         if (strncmp(buf, "TLB:", 4) == 0)
336                                 nr = 20003;
337                         if (strncmp(buf, "TRM:", 4) == 0)
338                                 nr = 20004;
339                         if (strncmp(buf, "THR:", 4) == 0)
340                                 nr = 20005;
341                         if (strncmp(buf, "SPU:", 4) == 0)
342                                 nr = 20006;
343                 } else {
344                         /* bb_strtou doesn't eat leading spaces, using strtoul */
345                         nr = strtoul(buf, NULL, 10);
346                 }
347                 if (nr == -1)
348                         continue;
349
350                 p++;
351                 /*  0:  143646045  153901007   IO-APIC-edge      timer
352                  *    ^
353                  */
354                 /* Sum counts for this IRQ */
355                 count = 0;
356                 while (1) {
357                         char *tmp;
358                         p = skip_whitespace(p);
359                         if (!isdigit(*p))
360                                 break;
361                         count += bb_strtoull(p, &tmp, 10);
362                         p = tmp;
363                 }
364                 /*   0:  143646045  153901007   IO-APIC-edge      timer
365                  * NMI:          1          2   Non-maskable interrupts
366                  *                              ^
367                  */
368                 if (nr < 20000) {
369                         /* Skip to the interrupt name, e.g. 'timer' */
370                         p = strchr(p, ' ');
371                         if (!p)
372                                 continue;
373                         p = skip_whitespace(p);
374                 }
375
376                 name = p;
377                 strchrnul(name, '\n')[0] = '\0';
378                 /* Save description of the interrupt */
379                 if (nr < 20000)
380                         sprintf(irq_desc, "   <kernel IPI> : %s", name);
381                 else
382                         sprintf(irq_desc, "    <interrupt> : %s", name);
383
384                 delta = save_irq_count(nr, count);
385
386                 /* Skip per CPU timer interrupts */
387                 if (is_hpet_irq(name))
388                         continue;
389
390                 if (nr != 0 && delta != 0)
391                         save_line(irq_desc, delta);
392
393                 if (nr == 0)
394                         G.interrupt_0 = delta;
395                 else
396                         G.total_interrupt += delta;
397         }
398
399         fclose(fp);
400 }
401 #else /* !ENABLE_FEATURE_POWERTOP_PROCIRQ */
402 # define process_irq_count_deltas()  ((void)0)
403 #endif
404
405 #ifdef __i386__
406 /*
407  * Get information about CPU using CPUID opcode.
408  */
409 static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
410                                   unsigned int *edx)
411 {
412         /* EAX value specifies what information to return */
413         __asm__(
414                 "       pushl %%ebx\n"     /* Save EBX */
415                 "       cpuid\n"
416                 "       movl %%ebx, %1\n"  /* Save content of EBX */
417                 "       popl %%ebx\n"      /* Restore EBX */
418                 : "=a"(*eax), /* Output */
419                   "=r"(*ebx),
420                   "=c"(*ecx),
421                   "=d"(*edx)
422                 : "0"(*eax),  /* Input */
423                   "1"(*ebx),
424                   "2"(*ecx),
425                   "3"(*edx)
426                 /* No clobbered registers */
427         );
428 }
429 #endif
430
431 static void NOINLINE print_intel_cstates(void)
432 {
433 #ifdef __i386__
434         int bios_table[8] = { 0 };
435         int nbios = 0;
436         DIR *cpudir;
437         struct dirent *d;
438         int i;
439         unsigned eax, ebx, ecx, edx;
440
441         cpudir = opendir("/sys/devices/system/cpu");
442         if (!cpudir)
443                 return;
444
445         /* Loop over cpuN entries */
446         while ((d = readdir(cpudir)) != NULL) {
447                 DIR *dir;
448                 int len;
449                 char fname[sizeof("/sys/devices/system/cpu//cpuidle//desc") + 2*BIG_SYSNAME_LEN];
450
451                 len = strlen(d->d_name);
452                 if (len < 3 || len > BIG_SYSNAME_LEN)
453                         continue;
454
455                 if (!isdigit(d->d_name[3]))
456                         continue;
457
458                 len = sprintf(fname, "/sys/devices/system/cpu/%s/cpuidle", d->d_name);
459                 dir = opendir(fname);
460                 if (!dir)
461                         continue;
462
463                 /*
464                  * Every C-state has its own stateN directory, that
465                  * contains a `time' and a `usage' file.
466                  */
467                 while ((d = readdir(dir)) != NULL) {
468                         FILE *fp;
469                         char buf[64];
470                         int n;
471
472                         n = strlen(d->d_name);
473                         if (n < 3 || n > BIG_SYSNAME_LEN)
474                                 continue;
475
476                         sprintf(fname + len, "/%s/desc", d->d_name);
477                         fp = fopen_for_read(fname);
478                         if (fp) {
479                                 char *p = fgets(buf, sizeof(buf), fp);
480                                 fclose(fp);
481                                 if (!p)
482                                         break;
483                                 p = strstr(p, "MWAIT ");
484                                 if (p) {
485                                         int pos;
486                                         p += sizeof("MWAIT ") - 1;
487                                         pos = (bb_strtoull(p, NULL, 16) >> 4) + 1;
488                                         if (pos >= ARRAY_SIZE(bios_table))
489                                                 continue;
490                                         bios_table[pos]++;
491                                         nbios++;
492                                 }
493                         }
494                 }
495                 closedir(dir);
496         }
497         closedir(cpudir);
498
499         if (!nbios)
500                 return;
501
502         eax = 5;
503         ebx = ecx = edx = 0;
504         cpuid(&eax, &ebx, &ecx, &edx);
505         if (!edx || !(ecx & 1))
506                 return;
507
508         printf("Your CPU supports the following C-states: ");
509         i = 0;
510         while (edx) {
511                 if (edx & 7)
512                         printf("C%u ", i);
513                 edx >>= 4;
514                 i++;
515         }
516         bb_putchar('\n');
517
518         /* Print BIOS C-States */
519         printf("Your BIOS reports the following C-states: ");
520         for (i = 0; i < 8; i++)
521                 if (bios_table[i])
522                         printf("C%u ", i);
523
524         bb_putchar('\n');
525 #endif
526 }
527
528 static void print_header(void)
529 {
530         printf(
531                 /* Clear the screen */
532                 "\033[H\033[J"
533                 /* Print the header */
534                 "\033[7m%.*s\033[0m", 79, "PowerTOP (C) 2007 Intel Corporation\n"
535         );
536 }
537
538 static void show_cstates(char cstate_lines[][64])
539 {
540         int i;
541
542         for (i = 0; i < 10; i++)
543                 if ((cstate_lines[i][0]))
544                         printf("%s", cstate_lines[i]);
545 }
546
547 static void show_timerstats(void)
548 {
549         unsigned lines;
550
551         /* Get terminal height */
552         get_terminal_width_height(STDOUT_FILENO, NULL, &lines);
553
554         /* We don't have whole terminal just for timerstats */
555         lines -= 12;
556
557         if (!G.cant_enable_timer_stats) {
558                 int i, n = 0;
559
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*/)
563                          && n++ < lines
564                         ) {
565                                 char c = ' ';
566                                 /*if (G.lines[i].disk_count)
567                                         c = 'D';*/
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,
571                                                 G.lines[i].string);
572                         }
573                 }
574         } else {
575                 bb_putchar('\n');
576                 bb_error_msg("no stats available; run as root or"
577                                 " enable the cpufreq_stats module");
578         }
579 }
580
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%)
588 //
589 // Wakeups-from-idle per second : 93.6     interval: 15.0s
590 // no ACPI power usage estimate available
591 //
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)
598
599 //usage:#define powertop_trivial_usage
600 //usage:       ""
601 //usage:#define powertop_full_usage "\n\n"
602 //usage:       "Analyze power consumption on Intel-based laptops\n"
603
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[12][64];
610         char buf[128];
611 #if ENABLE_FEATURE_USE_TERMIOS
612         struct termios new_settings;
613         struct pollfd pfd[1];
614
615         pfd[0].fd = 0;
616         pfd[0].events = POLLIN;
617 #endif
618
619         INIT_G();
620
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;
624 #endif
625
626         /* Print warning when we don't have superuser privileges */
627         if (geteuid() != 0)
628                 bb_error_msg("run as root to collect enough information");
629
630         /* Get number of CPUs */
631         G.total_cpus = get_cpu_count();
632
633         printf("Collecting data for "DEFAULT_SLEEP_STR" seconds\n");
634
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 */
641         atexit(reset_term);
642         bb_signals(BB_FATAL_SIGS, sig_handler);
643         tcsetattr_stdin_TCSANOW(&new_settings);
644 #endif
645
646         /* Collect initial data */
647         process_irq_count_deltas();
648
649         /* Read initial usage and duration */
650         read_cstate_counts(G.start_usage, G.start_duration);
651
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));
655
656         /* Display C-states */
657         print_intel_cstates();
658
659         G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
660
661         /* The main loop */
662         for (;;) {
663                 /*double maxsleep = 0.0;*/
664                 ullong totalticks, totalevents;
665                 int i;
666                 FILE *fp;
667
668                 G.cant_enable_timer_stats |= start_timer(); /* 1 on error */
669 #if !ENABLE_FEATURE_USE_TERMIOS
670                 sleep(DEFAULT_SLEEP);
671 #else
672                 if (safe_poll(pfd, 1, DEFAULT_SLEEP * 1000) > 0) {
673                         unsigned char c;
674                         if (safe_read(STDIN_FILENO, &c, 1) != 1)
675                                 break; /* EOF/error */
676                         if (c == G.init_settings.c_cc[VINTR])
677                                 break; /* ^C */
678                         if ((c | 0x20) == 'q')
679                                 break;
680                 }
681 #endif
682                 G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
683
684                 clear_lines();
685                 process_irq_count_deltas();
686
687                 /* Clear the stats */
688                 memset(cur_duration, 0, sizeof(cur_duration));
689                 memset(cur_usage, 0, sizeof(cur_usage));
690
691                 /* Read them */
692                 read_cstate_counts(cur_usage, cur_duration);
693
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];
700                         }
701                 }
702
703                 /* Show title bar */
704                 print_header();
705
706                 /* Clear C-state lines */
707                 memset(&cstate_lines, 0, sizeof(cstate_lines));
708
709                 if (totalevents == 0 && G.maxcstate <= 1) {
710                         /* This should not happen */
711                         sprintf(cstate_lines[5], "< Detailed C-state information is not "
712                                 "available.>\n");
713                 } else {
714                         double slept;
715                         double percentage;
716                         double newticks;
717
718                         newticks = G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000 - totalticks;
719
720                         /* Handle rounding errors: do not display negative values */
721                         if (newticks < 0)
722                                 newticks = 0;
723
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",
727                                 percentage);
728
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);
736
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)
742                                                 maxsleep = slept;*/
743                                 }
744                         }
745                 }
746
747                 /* Display C-states */
748                 show_cstates(cstate_lines);
749
750                 /* Do timer_stats info */
751                 buf[0] = '\0';
752                 totalticks = 0;
753
754                 fp = NULL;
755                 if (!G.cant_enable_timer_stats)
756                         fp = fopen_for_read("/proc/timer_stats");
757                 if (fp) {
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)
765 // ...
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;
771                                 char *p;
772                                 char line[512];
773                                 int cnt = 0;
774 // TODO: optimize
775                                 if (strstr(buf, "total events"))
776                                         break;
777                                 count = skip_whitespace(buf);
778                                 p = strchr(count, ',');
779                                 if (!p)
780                                         continue;
781                                 *p++ = '\0';
782                                 p = skip_whitespace(p); /* points to pid */
783
784 /* Find char ' ', then eat remaining spaces */
785 #define ADVANCE(p) do {           \
786         (p) = strchr((p), ' ');   \
787         if (!(p))                 \
788                 continue;         \
789         *(p) = '\0';              \
790         (p)++;                    \
791         (p) = skip_whitespace(p); \
792 } while (0)
793                                 /* Get process name */
794                                 ADVANCE(p);
795                                 process = p;
796
797                                 /* Get function */
798                                 ADVANCE(p);
799                                 func = p;
800
801                                 if (strcmp(process, "swapper") == 0
802                                  && strcmp(func, "hrtimer_start_range_ns (tick_sched_timer)\n") == 0
803                                 ) {
804                                         process = "[kernel scheduler]";
805                                         func = "Load balancing tick";
806                                 }
807
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]";
814
815                                 if (strncmp(func, "tick_nohz_", 10) == 0)
816                                         continue;
817                                 if (strncmp(func, "tick_setup_sched_timer", 20) == 0)
818                                         continue;
819                                 if (strcmp(process, "powertop") == 0)
820                                         continue;
821
822                                 strchrnul(p, '\n')[0] = '\0';
823
824                                 cnt = bb_strtoull(count, &p, 10);
825                                 while (*p != '\0') {
826                                         if (*p++ == 'D')
827                                                 goto skip;
828                                 }
829
830                                 if (strchr(process, '['))
831                                         sprintf(line, "%s %s", process, func);
832                                 else
833                                         sprintf(line, "%s", process);
834                                 save_line(line, cnt);
835  skip: ;
836                         }
837                         fclose(fp);
838                 }
839
840 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
841                 if (strstr(buf, "total events")) {
842                         int n = bb_strtoull(buf, NULL, 10) / G.total_cpus;
843
844                         if (totalevents == 0) {
845                                 /* No C-state info available, use timerstats */
846                                 totalevents = n * G.total_cpus + G.total_interrupt;
847                                 if (n < 0)
848                                         totalevents += G.interrupt_0 - n;
849                         }
850                         if (n > 0 && n < G.interrupt_0)
851                                 save_line("[extra timer interrupt]", G.interrupt_0 - n);
852                 }
853 #endif
854                 if (totalevents != 0)
855                         printf("\n\033[1mWakeups-from-idle per second : %4.1f\tinterval:"
856                                 "%ds\n\033[0m",
857                                 (double)totalevents / DEFAULT_SLEEP / G.total_cpus, DEFAULT_SLEEP);
858
859                 update_lines_cumulative_count();
860                 sort_lines();
861                 show_timerstats();
862                 fflush(stdout);
863
864                 /* Clear the stats */
865                 memset(cur_duration, 0, sizeof(cur_duration));
866                 memset(cur_usage, 0, sizeof(cur_usage));
867
868                 /* Get new values */
869                 read_cstate_counts(cur_usage, cur_duration);
870
871                 /* Save them */
872                 memcpy(G.last_usage, cur_usage, sizeof(G.last_usage));
873                 memcpy(G.last_duration, cur_duration, sizeof(G.last_duration));
874         } /* for (;;) */
875
876         bb_putchar('\n');
877
878         return EXIT_SUCCESS;
879 }