powertop: fixes to output format and 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 be 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         struct line *lines; /* the most often used member */
66         int lines_cnt;
67         int lines_cumulative_count;
68         int maxcstate;
69         unsigned total_cpus;
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;
75         int percpu_hpet_end;
76 # endif
77         int interrupt_0;
78         int total_interrupt;
79         struct irqdata interrupts[IRQCOUNT];
80 #endif
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;
88 #endif
89 };
90 #define G (*ptr_to_globals)
91 #define INIT_G() do { \
92         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
93 } while (0)
94
95 #if ENABLE_FEATURE_USE_TERMIOS
96 static void reset_term(void)
97 {
98         tcsetattr_stdin_TCSANOW(&G.init_settings);
99 }
100
101 static void sig_handler(int signo UNUSED_PARAM)
102 {
103         reset_term();
104         _exit(EXIT_FAILURE);
105 }
106 #endif
107
108 static int write_str_to_file(const char *fname, const char *str)
109 {
110         FILE *fp = fopen_for_write(fname);
111         if (!fp)
112                 return 1;
113         fputs(str, fp);
114         fclose(fp);
115         return 0;
116 }
117
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")
121
122 static NOINLINE void clear_lines(void)
123 {
124         int i;
125         if (G.lines) {
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.lines = NULL;
131         }
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, 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;*/
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_counts(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_counts()  ((void)0)
403 #endif
404
405 static NOINLINE int process_timer_stats(void)
406 {
407         char buf[128];
408         char line[15 + 3 + 128];
409         int n;
410         ullong totalticks;
411         FILE *fp;
412
413         buf[0] = '\0';
414         totalticks = 0;
415
416         fp = NULL;
417         if (!G.cant_enable_timer_stats)
418                 fp = fopen_for_read("/proc/timer_stats");
419         if (fp) {
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)
427 // ...
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;
433                         char *p;
434                         int cnt;
435
436                         count = skip_whitespace(buf);
437                         p = strchr(count, ',');
438                         if (!p)
439                                 continue;
440                         *p++ = '\0';
441                         if (strcmp(strchrnul(count, ' '), " total events") == 0)
442                                 break;
443                         p = skip_whitespace(p); /* points to pid */
444
445 /* Find char ' ', then eat remaining spaces */
446 #define ADVANCE(p) do {           \
447         (p) = strchr((p), ' ');   \
448         if (!(p))                 \
449                 continue;         \
450         *(p) = '\0';              \
451         (p)++;                    \
452         (p) = skip_whitespace(p); \
453 } while (0)
454                         /* Get process name */
455                         ADVANCE(p);
456                         process = p;
457                         /* Get function */
458                         ADVANCE(p);
459                         func = p;
460 #undef ADVANCE
461                         //if (strcmp(process, "swapper") == 0
462                         // && strcmp(func, "hrtimer_start_range_ns (tick_sched_timer)\n") == 0
463                         //) {
464                         //      process = "[kernel scheduler]";
465                         //      func = "Load balancing tick";
466                         //}
467
468                         if (strncmp(func, "tick_nohz_", 10) == 0)
469                                 continue;
470                         if (strncmp(func, "tick_setup_sched_timer", 20) == 0)
471                                 continue;
472                         //if (strcmp(process, "powertop") == 0)
473                         //      continue;
474
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>";
481
482                         strchrnul(p, '\n')[0] = '\0';
483
484                         {
485                                 char *tmp;
486                                 cnt = bb_strtoull(count, &tmp, 10);
487                                 p = tmp;
488                         }
489                         while (*p != '\0') {
490                                 if (*p++ == 'D') /* deferred */
491                                         goto skip;
492                         }
493
494                         //if (strchr(process, '['))
495                                 sprintf(line, "%15.15s : %s", process, func);
496                         //else
497                         //      sprintf(line, "%s", process);
498                         save_line(line, cnt);
499  skip: ;
500                 }
501                 fclose(fp);
502         }
503
504         n = 0;
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);
511                 }
512         }
513 #endif
514         return n;
515 }
516
517 #ifdef __i386__
518 /*
519  * Get information about CPU using CPUID opcode.
520  */
521 static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
522                                   unsigned int *edx)
523 {
524         /* EAX value specifies what information to return */
525         __asm__(
526                 "       pushl %%ebx\n"     /* Save EBX */
527                 "       cpuid\n"
528                 "       movl %%ebx, %1\n"  /* Save content of EBX */
529                 "       popl %%ebx\n"      /* Restore EBX */
530                 : "=a"(*eax), /* Output */
531                   "=r"(*ebx),
532                   "=c"(*ecx),
533                   "=d"(*edx)
534                 : "0"(*eax),  /* Input */
535                   "1"(*ebx),
536                   "2"(*ecx),
537                   "3"(*edx)
538                 /* No clobbered registers */
539         );
540 }
541 #endif
542
543 static NOINLINE void print_intel_cstates(void)
544 {
545 #ifdef __i386__
546         int bios_table[8] = { 0 };
547         int nbios = 0;
548         DIR *cpudir;
549         struct dirent *d;
550         int i;
551         unsigned eax, ebx, ecx, edx;
552
553         cpudir = opendir("/sys/devices/system/cpu");
554         if (!cpudir)
555                 return;
556
557         /* Loop over cpuN entries */
558         while ((d = readdir(cpudir)) != NULL) {
559                 DIR *dir;
560                 int len;
561                 char fname[sizeof("/sys/devices/system/cpu//cpuidle//desc") + 2*BIG_SYSNAME_LEN];
562
563                 len = strlen(d->d_name);
564                 if (len < 3 || len > BIG_SYSNAME_LEN)
565                         continue;
566
567                 if (!isdigit(d->d_name[3]))
568                         continue;
569
570                 len = sprintf(fname, "/sys/devices/system/cpu/%s/cpuidle", d->d_name);
571                 dir = opendir(fname);
572                 if (!dir)
573                         continue;
574
575                 /*
576                  * Every C-state has its own stateN directory, that
577                  * contains a 'time' and a 'usage' file.
578                  */
579                 while ((d = readdir(dir)) != NULL) {
580                         FILE *fp;
581                         char buf[64];
582                         int n;
583
584                         n = strlen(d->d_name);
585                         if (n < 3 || n > BIG_SYSNAME_LEN)
586                                 continue;
587
588                         sprintf(fname + len, "/%s/desc", d->d_name);
589                         fp = fopen_for_read(fname);
590                         if (fp) {
591                                 char *p = fgets(buf, sizeof(buf), fp);
592                                 fclose(fp);
593                                 if (!p)
594                                         break;
595                                 p = strstr(p, "MWAIT ");
596                                 if (p) {
597                                         int pos;
598                                         p += sizeof("MWAIT ") - 1;
599                                         pos = (bb_strtoull(p, NULL, 16) >> 4) + 1;
600                                         if (pos >= ARRAY_SIZE(bios_table))
601                                                 continue;
602                                         bios_table[pos]++;
603                                         nbios++;
604                                 }
605                         }
606                 }
607                 closedir(dir);
608         }
609         closedir(cpudir);
610
611         if (!nbios)
612                 return;
613
614         eax = 5;
615         ebx = ecx = edx = 0;
616         cpuid(&eax, &ebx, &ecx, &edx);
617         if (!edx || !(ecx & 1))
618                 return;
619
620         printf("Your CPU supports the following C-states: ");
621         i = 0;
622         while (edx) {
623                 if (edx & 7)
624                         printf("C%u ", i);
625                 edx >>= 4;
626                 i++;
627         }
628         bb_putchar('\n');
629
630         /* Print BIOS C-States */
631         printf("Your BIOS reports the following C-states: ");
632         for (i = 0; i < 8; i++)
633                 if (bios_table[i])
634                         printf("C%u ", i);
635
636         bb_putchar('\n');
637 #endif
638 }
639
640 static void show_timerstats(void)
641 {
642         unsigned lines;
643
644         /* Get terminal height */
645         get_terminal_width_height(STDOUT_FILENO, NULL, &lines);
646
647         /* We don't have whole terminal just for timerstats */
648         lines -= 12;
649
650         if (!G.cant_enable_timer_stats) {
651                 int i, n = 0;
652                 char strbuf6[6];
653
654                 strbuf6[5] = '\0';
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*/)
658                          && n++ < lines
659                         ) {
660                                 /* NB: upstream powertop prints "(wakeups/sec)",
661                                  * we print just "(wakeup counts)".
662                                  */
663                                 /*char c = ' ';
664                                 if (G.lines[i].disk_count)
665                                         c = 'D';*/
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,
670                                         strbuf6, /*c,*/
671                                         G.lines[i].string);
672                         }
673                 }
674         } else {
675                 bb_putchar('\n');
676                 bb_error_msg("no stats available; run as root or"
677                                 " enable the cpufreq_stats module");
678         }
679 }
680
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%)
688 //
689 // Wakeups-from-idle per second : 93.6     interval: 15.0s
690 // no ACPI power usage estimate available
691 //
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)
698
699 //usage:#define powertop_trivial_usage
700 //usage:       ""
701 //usage:#define powertop_full_usage "\n\n"
702 //usage:       "Analyze power consumption on Intel-based laptops\n"
703
704 int powertop_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
705 int powertop_main(int UNUSED_PARAM argc, char UNUSED_PARAM **argv)
706 {
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];
713
714         pfd[0].fd = 0;
715         pfd[0].events = POLLIN;
716 #endif
717
718         INIT_G();
719
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;
723 #endif
724
725         /* Print warning when we don't have superuser privileges */
726         if (geteuid() != 0)
727                 bb_error_msg("run as root to collect enough information");
728
729         /* Get number of CPUs */
730         G.total_cpus = get_cpu_count();
731
732         printf("Collecting data for "DEFAULT_SLEEP_STR" seconds\n");
733
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 */
740         atexit(reset_term);
741         bb_signals(BB_FATAL_SIGS, sig_handler);
742         tcsetattr_stdin_TCSANOW(&new_settings);
743 #endif
744
745         /* Collect initial data */
746         process_irq_counts();
747
748         /* Read initial usage and duration */
749         read_cstate_counts(G.start_usage, G.start_duration);
750
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));
754
755         /* Display C-states */
756         print_intel_cstates();
757
758         G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
759
760         /* The main loop */
761         for (;;) {
762                 //double maxsleep = 0.0;
763                 ullong totalticks, totalevents;
764                 int i;
765
766                 G.cant_enable_timer_stats |= start_timer(); /* 1 on error */
767 #if !ENABLE_FEATURE_USE_TERMIOS
768                 sleep(DEFAULT_SLEEP);
769 #else
770                 if (safe_poll(pfd, 1, DEFAULT_SLEEP * 1000) > 0) {
771                         unsigned char c;
772                         if (safe_read(STDIN_FILENO, &c, 1) != 1)
773                                 break; /* EOF/error */
774                         if (c == G.init_settings.c_cc[VINTR])
775                                 break; /* ^C */
776                         if ((c | 0x20) == 'q')
777                                 break;
778                 }
779 #endif
780                 G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
781
782                 clear_lines();
783                 process_irq_counts();
784
785                 /* Clear the stats */
786                 memset(cur_duration, 0, sizeof(cur_duration));
787                 memset(cur_usage, 0, sizeof(cur_usage));
788
789                 /* Read them */
790                 read_cstate_counts(cur_usage, cur_duration);
791
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];
798                         }
799                 }
800
801                 /* Clear the screen */
802                 printf("\033[H\033[J");
803
804                 /* Clear C-state lines */
805                 memset(&cstate_lines, 0, sizeof(cstate_lines));
806
807                 if (totalevents == 0 && G.maxcstate <= 1) {
808                         /* This should not happen */
809                         sprintf(cstate_lines[5], "< Detailed C-state information is not "
810                                 "available.>\n");
811                 } else {
812                         double percentage;
813                         double newticks;
814
815                         newticks = G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000 - totalticks;
816
817                         /* Handle rounding errors: do not display negative values */
818                         if (newticks < 0)
819                                 newticks = 0;
820
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",
824                                 percentage);
825
826                         /* Compute values for individual C-states */
827                         for (i = 0; i < MAX_CSTATE_COUNT; i++) {
828                                 if (cur_usage[i] != 0) {
829                                         double slept;
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);
834
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)
840                                         //      maxsleep = slept;
841                                 }
842                         }
843                 }
844
845                 for (i = 0; i < MAX_CSTATE_COUNT + 2; i++)
846                         if (cstate_lines[i][0])
847                                 printf("%s", cstate_lines[i]);
848
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;
854                         if (i < 0)
855                                 totalevents += G.interrupt_0 - i;
856                 }
857 #endif
858                 /* Upstream powertop prints wakeups per sec per CPU,
859                  * we print just raw wakeup counts.
860                  */
861 //TODO: show real seconds (think about manual refresh)
862                 printf("\nWakeups-from-idle in %u seconds: %llu\n",
863                         DEFAULT_SLEEP,
864                         totalevents
865                 );
866
867                 update_lines_cumulative_count();
868                 sort_lines();
869                 show_timerstats();
870                 fflush(stdout);
871
872                 /* Clear the stats */
873                 memset(cur_duration, 0, sizeof(cur_duration));
874                 memset(cur_usage, 0, sizeof(cur_usage));
875
876                 /* Get new values */
877                 read_cstate_counts(cur_usage, cur_duration);
878
879                 /* Save them */
880                 memcpy(G.last_usage, cur_usage, sizeof(G.last_usage));
881                 memcpy(G.last_duration, cur_duration, sizeof(G.last_duration));
882         } /* for (;;) */
883
884         bb_putchar('\n');
885
886         return EXIT_SUCCESS;
887 }