powertop: replace erroneous \n with \0; make numberic conversion more robust
[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 #if ENABLE_FEATURE_USE_TERMIOS
86         struct termios init_settings;
87 #endif
88 };
89 #define G (*ptr_to_globals)
90 #define INIT_G() do { \
91         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
92 } while (0)
93
94 #if ENABLE_FEATURE_USE_TERMIOS
95 static void reset_term(void)
96 {
97         tcsetattr_stdin_TCSANOW(&G.init_settings);
98 }
99
100 static void sig_handler(int signo UNUSED_PARAM)
101 {
102         reset_term();
103         _exit(EXIT_FAILURE);
104 }
105 #endif
106
107 static int write_str_to_file(const char *fname, const char *str)
108 {
109         FILE *fp = fopen_for_write(fname);
110         if (!fp)
111                 return 1;
112         fputs(str, fp);
113         fclose(fp);
114         return 0;
115 }
116
117 /* Make it more readable */
118 #define start_timer() write_str_to_file("/proc/timer_stats", "1\n")
119 #define stop_timer()  write_str_to_file("/proc/timer_stats", "0\n")
120
121 static NOINLINE void clear_lines(void)
122 {
123         int i;
124         if (G.lines) {
125                 for (i = 0; i < G.lines_cnt; i++)
126                         free(G.lines[i].string);
127                 free(G.lines);
128                 G.lines_cnt = 0;
129                 G.lines = NULL;
130         }
131 }
132
133 static void update_lines_cumulative_count(void)
134 {
135         int i;
136         for (i = 0; i < G.lines_cnt; i++)
137                 G.lines_cumulative_count += G.lines[i].count;
138 }
139
140 static int line_compare(const void *p1, const void *p2)
141 {
142         const struct line *a = p1;
143         const struct line *b = p2;
144         return (b->count /*+ 50 * b->disk_count*/) - (a->count /*+ 50 * a->disk_count*/);
145 }
146
147 static void sort_lines(void)
148 {
149         qsort(G.lines, G.lines_cnt, sizeof(G.lines[0]), line_compare);
150 }
151
152 /* Save C-state usage and duration. Also update maxcstate. */
153 static void read_cstate_counts(ullong *usage, ullong *duration)
154 {
155         DIR *dir;
156         struct dirent *d;
157
158         dir = opendir("/proc/acpi/processor");
159         if (!dir)
160                 return;
161
162         while ((d = readdir(dir)) != NULL) {
163                 FILE *fp;
164                 char buf[192];
165                 int level;
166                 int len;
167
168                 len = strlen(d->d_name); /* "CPUnn" */
169                 if (len < 3 || len > BIG_SYSNAME_LEN)
170                         continue;
171
172                 sprintf(buf, "%s/%s/power", "/proc/acpi/processor", d->d_name);
173                 fp = fopen_for_read(buf);
174                 if (!fp)
175                         continue;
176
177 // Example file contents:
178 // active state:            C0
179 // max_cstate:              C8
180 // maximum allowed latency: 2000000000 usec
181 // states:
182 //     C1:                  type[C1] promotion[--] demotion[--] latency[001] usage[00006173] duration[00000000000000000000]
183 //     C2:                  type[C2] promotion[--] demotion[--] latency[001] usage[00085191] duration[00000000000083024907]
184 //     C3:                  type[C3] promotion[--] demotion[--] latency[017] usage[01017622] duration[00000000017921327182]
185                 level = 0;
186                 while (fgets(buf, sizeof(buf), fp)) {
187                         char *p = strstr(buf, "age[");
188                         if (!p)
189                                 continue;
190                         p += 4;
191                         usage[level] += bb_strtoull(p, NULL, 10) + 1;
192                         p = strstr(buf, "ation[");
193                         if (!p)
194                                 continue;
195                         p += 6;
196                         duration[level] += bb_strtoull(p, NULL, 10);
197
198                         if (level >= MAX_CSTATE_COUNT-1)
199                                 break;
200                         level++;
201                         if (level > G.maxcstate)  /* update maxcstate */
202                                 G.maxcstate = level;
203                 }
204                 fclose(fp);
205         }
206         closedir(dir);
207 }
208
209 /* Add line and/or update count */
210 static void save_line(const char *string, int count)
211 {
212         int i;
213         for (i = 0; i < G.lines_cnt; i++) {
214                 if (strcmp(string, G.lines[i].string) == 0) {
215                         /* It's already there, only update count */
216                         G.lines[i].count += count;
217                         return;
218                 }
219         }
220
221         /* Add new line */
222         G.lines = xrealloc_vector(G.lines, 4, G.lines_cnt);
223         G.lines[G.lines_cnt].string = xstrdup(string);
224         G.lines[G.lines_cnt].count = count;
225         /*G.lines[G.lines_cnt].disk_count = 0;*/
226         G.lines_cnt++;
227 }
228
229 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
230 static int is_hpet_irq(const char *name)
231 {
232         char *p;
233 # if BLOATY_HPET_IRQ_NUM_DETECTION
234         long hpet_chan;
235
236         /* Learn the range of existing hpet timers. This is done once */
237         if (!G.scanned_timer_list) {
238                 FILE *fp;
239                 char buf[80];
240
241                 G.scanned_timer_list = true;
242                 fp = fopen_for_read("/proc/timer_list");
243                 if (!fp)
244                         return 0;
245
246                 while (fgets(buf, sizeof(buf), fp)) {
247                         p = strstr(buf, "Clock Event Device: hpet");
248                         if (!p)
249                                 continue;
250                         p += sizeof("Clock Event Device: hpet")-1;
251                         if (!isdigit(*p))
252                                 continue;
253                         hpet_chan = xatoi_positive(p);
254                         if (hpet_chan < G.percpu_hpet_start)
255                                 G.percpu_hpet_start = hpet_chan;
256                         if (hpet_chan > G.percpu_hpet_end)
257                                 G.percpu_hpet_end = hpet_chan;
258                 }
259                 fclose(fp);
260         }
261 # endif
262 //TODO: optimize
263         p = strstr(name, "hpet");
264         if (!p)
265                 return 0;
266         p += 4;
267         if (!isdigit(*p))
268                 return 0;
269 # if BLOATY_HPET_IRQ_NUM_DETECTION
270         hpet_chan = xatoi_positive(p);
271         if (hpet_chan < G.percpu_hpet_start || hpet_chan > G.percpu_hpet_end)
272                 return 0;
273 # endif
274         return 1;
275 }
276
277 /* Save new IRQ count, return delta from old one */
278 static int save_irq_count(int irq, ullong count)
279 {
280         int unused = IRQCOUNT;
281         int i;
282         for (i = 0; i < IRQCOUNT; i++) {
283                 if (G.interrupts[i].active && G.interrupts[i].number == irq) {
284                         ullong old = G.interrupts[i].count;
285                         G.interrupts[i].count = count;
286                         return count - old;
287                 }
288                 if (!G.interrupts[i].active && unused > i)
289                         unused = i;
290         }
291         if (unused < IRQCOUNT) {
292                 G.interrupts[unused].active = 1;
293                 G.interrupts[unused].count = count;
294                 G.interrupts[unused].number = irq;
295         }
296         return count;
297 }
298
299 /* Read /proc/interrupts, save IRQ counts and IRQ description */
300 static void process_irq_counts(void)
301 {
302         FILE *fp;
303         char buf[128];
304
305         /* Reset values */
306         G.interrupt_0 = 0;
307         G.total_interrupt = 0;
308
309         fp = xfopen_for_read("/proc/interrupts");
310         while (fgets(buf, sizeof(buf), fp)) {
311                 char irq_desc[sizeof("   <kernel IPI> : ") + sizeof(buf)];
312                 char *p;
313                 const char *name;
314                 int nr;
315                 ullong count;
316                 ullong delta;
317
318                 p = strchr(buf, ':');
319                 if (!p)
320                         continue;
321                 /*  0:  143646045  153901007   IO-APIC-edge      timer
322                  *   ^
323                  */
324                 *p = '\0';
325                 /* Deal with non-maskable interrupts -- make up fake numbers */
326                 nr = index_in_strings("NMI\0RES\0CAL\0TLB\0TRM\0THR\0SPU\0", buf);
327                 if (nr >= 0) {
328                         nr += 20000;
329                 } else {
330                         /* bb_strtou doesn't eat leading spaces, using strtoul */
331                         errno = 0;
332                         nr = strtoul(buf, NULL, 10);
333                         if (errno)
334                                 continue;
335                 }
336                 p++;
337                 /*  0:  143646045  153901007   IO-APIC-edge      timer
338                  *    ^
339                  */
340                 /* Sum counts for this IRQ */
341                 count = 0;
342                 while (1) {
343                         char *tmp;
344                         p = skip_whitespace(p);
345                         if (!isdigit(*p))
346                                 break;
347                         count += bb_strtoull(p, &tmp, 10);
348                         p = tmp;
349                 }
350                 /*   0:  143646045  153901007   IO-APIC-edge      timer
351                  * NMI:          1          2   Non-maskable interrupts
352                  *                              ^
353                  */
354                 if (nr < 20000) {
355                         /* Skip to the interrupt name, e.g. 'timer' */
356                         p = strchr(p, ' ');
357                         if (!p)
358                                 continue;
359                         p = skip_whitespace(p);
360                 }
361
362                 name = p;
363                 strchrnul(name, '\n')[0] = '\0';
364                 /* Save description of the interrupt */
365                 if (nr >= 20000)
366                         sprintf(irq_desc, "   <kernel IPI> : %s", name);
367                 else
368                         sprintf(irq_desc, "    <interrupt> : %s", name);
369
370                 delta = save_irq_count(nr, count);
371
372                 /* Skip per CPU timer interrupts */
373                 if (is_hpet_irq(name))
374                         continue;
375
376                 if (nr != 0 && delta != 0)
377                         save_line(irq_desc, delta);
378
379                 if (nr == 0)
380                         G.interrupt_0 = delta;
381                 else
382                         G.total_interrupt += delta;
383         }
384
385         fclose(fp);
386 }
387 #else /* !ENABLE_FEATURE_POWERTOP_PROCIRQ */
388 # define process_irq_counts()  ((void)0)
389 #endif
390
391 static NOINLINE int process_timer_stats(void)
392 {
393         char buf[128];
394         char line[15 + 3 + 128];
395         int n;
396         ullong totalticks;
397         FILE *fp;
398
399         buf[0] = '\0';
400         totalticks = 0;
401
402         fp = NULL;
403         if (!G.cant_enable_timer_stats)
404                 fp = fopen_for_read("/proc/timer_stats");
405         if (fp) {
406 // Example file contents:
407 // Timer Stats Version: v0.2
408 // Sample period: 1.329 s
409 //    76,     0 swapper          hrtimer_start_range_ns (tick_sched_timer)
410 //    88,     0 swapper          hrtimer_start_range_ns (tick_sched_timer)
411 //    24,  3787 firefox          hrtimer_start_range_ns (hrtimer_wakeup)
412 //   46D,  1136 kondemand/1      do_dbs_timer (delayed_work_timer_fn)
413 // ...
414 //     1,  1656 Xorg             hrtimer_start_range_ns (hrtimer_wakeup)
415 //     1,  2159 udisks-daemon    hrtimer_start_range_ns (hrtimer_wakeup)
416 // 331 total events, 249.059 events/sec
417                 while (fgets(buf, sizeof(buf), fp)) {
418                         const char *count, *process, *func;
419                         char *p;
420                         int idx;
421
422                         count = skip_whitespace(buf);
423                         if (strcmp(strchrnul(count, ' '), " total events") == 0)
424                                 break;
425                         p = strchr(count, ',');
426                         if (!p)
427                                 continue;
428                         *p++ = '\0';
429                         if (strchr(count, 'D'))
430                                 continue; /* deferred */
431                         p = skip_whitespace(p); /* points to pid now */
432                         process = NULL;
433  get_func_name:
434                         p = strchr(p, ' ');
435                         if (!p)
436                                 continue;
437                         *p++ = '\0';
438                         p = skip_whitespace(p);
439                         if (process == NULL) {
440                                 process = p;
441                                 goto get_func_name;
442                         }
443                         func = p;
444
445                         //if (strcmp(process, "swapper") == 0
446                         // && strcmp(func, "hrtimer_start_range_ns (tick_sched_timer)\n") == 0
447                         //) {
448                         //      process = "[kernel scheduler]";
449                         //      func = "Load balancing tick";
450                         //}
451
452                         if (strncmp(func, "tick_nohz_", 10) == 0)
453                                 continue;
454                         if (strncmp(func, "tick_setup_sched_timer", 20) == 0)
455                                 continue;
456                         //if (strcmp(process, "powertop") == 0)
457                         //      continue;
458
459                         idx = index_in_strings("insmod\0modprobe\0swapper\0", process);
460                         if (idx != -1) {
461                                 process = idx < 2 ? "[kernel module]" : "<kernel core>";
462                         }
463
464                         strchrnul(p, '\n')[0] = '\0';
465
466                         // 46D\01136\0kondemand/1\0do_dbs_timer (delayed_work_timer_fn)
467                         // ^          ^            ^
468                         // count      process      func
469
470                         //if (strchr(process, '['))
471                                 sprintf(line, "%15.15s : %s", process, func);
472                         //else
473                         //      sprintf(line, "%s", process);
474                         save_line(line, bb_strtoull(count, NULL, 10));
475                 }
476                 fclose(fp);
477         }
478
479         n = 0;
480 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
481         if (strstr(buf, " total events")) {
482                 n = bb_strtoull(buf, NULL, 10) / G.total_cpus;
483                 if (n > 0 && n < G.interrupt_0) {
484                         sprintf(line, "    <interrupt> : %s", "extra timer interrupt");
485                         save_line(line, G.interrupt_0 - n);
486                 }
487         }
488 #endif
489         return n;
490 }
491
492 #ifdef __i386__
493 /*
494  * Get information about CPU using CPUID opcode.
495  */
496 static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
497                                   unsigned int *edx)
498 {
499         /* EAX value specifies what information to return */
500         __asm__(
501                 "       pushl %%ebx\n"     /* Save EBX */
502                 "       cpuid\n"
503                 "       movl %%ebx, %1\n"  /* Save content of EBX */
504                 "       popl %%ebx\n"      /* Restore EBX */
505                 : "=a"(*eax), /* Output */
506                   "=r"(*ebx),
507                   "=c"(*ecx),
508                   "=d"(*edx)
509                 : "0"(*eax),  /* Input */
510                   "1"(*ebx),
511                   "2"(*ecx),
512                   "3"(*edx)
513                 /* No clobbered registers */
514         );
515 }
516 #endif
517
518 #ifdef __i386__
519 static NOINLINE void print_intel_cstates(void)
520 {
521         int bios_table[8] = { 0 };
522         int nbios = 0;
523         DIR *cpudir;
524         struct dirent *d;
525         int i;
526         unsigned eax, ebx, ecx, edx;
527
528         cpudir = opendir("/sys/devices/system/cpu");
529         if (!cpudir)
530                 return;
531
532         /* Loop over cpuN entries */
533         while ((d = readdir(cpudir)) != NULL) {
534                 DIR *dir;
535                 int len;
536                 char fname[sizeof("/sys/devices/system/cpu//cpuidle//desc") + 2*BIG_SYSNAME_LEN];
537
538                 len = strlen(d->d_name);
539                 if (len < 3 || len > BIG_SYSNAME_LEN)
540                         continue;
541
542                 if (!isdigit(d->d_name[3]))
543                         continue;
544
545                 len = sprintf(fname, "%s/%s/cpuidle", "/sys/devices/system/cpu", d->d_name);
546                 dir = opendir(fname);
547                 if (!dir)
548                         continue;
549
550                 /*
551                  * Every C-state has its own stateN directory, that
552                  * contains a 'time' and a 'usage' file.
553                  */
554                 while ((d = readdir(dir)) != NULL) {
555                         FILE *fp;
556                         char buf[64];
557                         int n;
558
559                         n = strlen(d->d_name);
560                         if (n < 3 || n > BIG_SYSNAME_LEN)
561                                 continue;
562
563                         sprintf(fname + len, "/%s/desc", d->d_name);
564                         fp = fopen_for_read(fname);
565                         if (fp) {
566                                 char *p = fgets(buf, sizeof(buf), fp);
567                                 fclose(fp);
568                                 if (!p)
569                                         break;
570                                 p = strstr(p, "MWAIT ");
571                                 if (p) {
572                                         int pos;
573                                         p += sizeof("MWAIT ") - 1;
574                                         pos = (bb_strtoull(p, NULL, 16) >> 4) + 1;
575                                         if (pos >= ARRAY_SIZE(bios_table))
576                                                 continue;
577                                         bios_table[pos]++;
578                                         nbios++;
579                                 }
580                         }
581                 }
582                 closedir(dir);
583         }
584         closedir(cpudir);
585
586         if (!nbios)
587                 return;
588
589         eax = 5;
590         ebx = ecx = edx = 0;
591         cpuid(&eax, &ebx, &ecx, &edx);
592         if (!edx || !(ecx & 1))
593                 return;
594
595         printf("Your CPU supports the following C-states: ");
596         i = 0;
597         while (edx) {
598                 if (edx & 7)
599                         printf("C%u ", i);
600                 edx >>= 4;
601                 i++;
602         }
603         bb_putchar('\n');
604
605         /* Print BIOS C-States */
606         printf("Your BIOS reports the following C-states: ");
607         for (i = 0; i < ARRAY_SIZE(bios_table); i++)
608                 if (bios_table[i])
609                         printf("C%u ", i);
610
611         bb_putchar('\n');
612 }
613 #else
614 # define print_intel_cstates() ((void)0)
615 #endif
616
617 static void show_timerstats(void)
618 {
619         unsigned lines;
620
621         /* Get terminal height */
622         get_terminal_width_height(STDOUT_FILENO, NULL, &lines);
623
624         /* We don't have whole terminal just for timerstats */
625         lines -= 12;
626
627         if (!G.cant_enable_timer_stats) {
628                 int i, n = 0;
629                 char strbuf6[6];
630
631                 strbuf6[5] = '\0';
632                 puts("\nTop causes for wakeups:");
633                 for (i = 0; i < G.lines_cnt; i++) {
634                         if ((G.lines[i].count > 0 /*|| G.lines[i].disk_count > 0*/)
635                          && n++ < lines
636                         ) {
637                                 /* NB: upstream powertop prints "(wakeups/sec)",
638                                  * we print just "(wakeup counts)".
639                                  */
640                                 /*char c = ' ';
641                                 if (G.lines[i].disk_count)
642                                         c = 'D';*/
643                                 smart_ulltoa5(G.lines[i].count, strbuf6, " KMGTPEZY");
644                                 printf(/*" %5.1f%% (%s)%c  %s\n"*/
645                                         " %5.1f%% (%s)   %s\n",
646                                         G.lines[i].count * 100.0 / G.lines_cumulative_count,
647                                         strbuf6, /*c,*/
648                                         G.lines[i].string);
649                         }
650                 }
651         } else {
652                 bb_putchar('\n');
653                 bb_error_msg("no stats available; run as root or"
654                                 " enable the cpufreq_stats module");
655         }
656 }
657
658 // Example display from powertop version 1.11
659 // Cn                Avg residency       P-states (frequencies)
660 // C0 (cpu running)        ( 0.5%)         2.00 Ghz     0.0%
661 // polling           0.0ms ( 0.0%)         1.67 Ghz     0.0%
662 // C1 mwait          0.0ms ( 0.0%)         1333 Mhz     0.1%
663 // C2 mwait          0.1ms ( 0.1%)         1000 Mhz    99.9%
664 // C3 mwait         12.1ms (99.4%)
665 //
666 // Wakeups-from-idle per second : 93.6     interval: 15.0s
667 // no ACPI power usage estimate available
668 //
669 // Top causes for wakeups:
670 //   32.4% ( 26.7)       <interrupt> : extra timer interrupt
671 //   29.0% ( 23.9)     <kernel core> : hrtimer_start_range_ns (tick_sched_timer)
672 //    9.0% (  7.5)     <kernel core> : hrtimer_start (tick_sched_timer)
673 //    6.5% (  5.3)       <interrupt> : ata_piix
674 //    5.0% (  4.1)             inetd : hrtimer_start_range_ns (hrtimer_wakeup)
675
676 //usage:#define powertop_trivial_usage
677 //usage:       ""
678 //usage:#define powertop_full_usage "\n\n"
679 //usage:       "Analyze power consumption on Intel-based laptops\n"
680
681 int powertop_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
682 int powertop_main(int UNUSED_PARAM argc, char UNUSED_PARAM **argv)
683 {
684         ullong cur_usage[MAX_CSTATE_COUNT];
685         ullong cur_duration[MAX_CSTATE_COUNT];
686         char cstate_lines[MAX_CSTATE_COUNT + 2][64];
687 #if ENABLE_FEATURE_USE_TERMIOS
688         struct termios new_settings;
689         struct pollfd pfd[1];
690
691         pfd[0].fd = 0;
692         pfd[0].events = POLLIN;
693 #endif
694
695         INIT_G();
696
697 #if ENABLE_FEATURE_POWERTOP_PROCIRQ && BLOATY_HPET_IRQ_NUM_DETECTION
698         G.percpu_hpet_start = INT_MAX;
699         G.percpu_hpet_end = INT_MIN;
700 #endif
701
702         /* Print warning when we don't have superuser privileges */
703         if (geteuid() != 0)
704                 bb_error_msg("run as root to collect enough information");
705
706         /* Get number of CPUs */
707         G.total_cpus = get_cpu_count();
708
709         printf("Collecting data for "DEFAULT_SLEEP_STR" seconds\n");
710
711 #if ENABLE_FEATURE_USE_TERMIOS
712         tcgetattr(0, (void *)&G.init_settings);
713         memcpy(&new_settings, &G.init_settings, sizeof(new_settings));
714         /* Turn on unbuffered input, turn off echoing */
715         new_settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHONL);
716         /* So we don't forget to reset term settings */
717         atexit(reset_term);
718         bb_signals(BB_FATAL_SIGS, sig_handler);
719         tcsetattr_stdin_TCSANOW(&new_settings);
720 #endif
721
722         /* Collect initial data */
723         process_irq_counts();
724
725         /* Read initial usage and duration */
726         read_cstate_counts(G.start_usage, G.start_duration);
727
728         /* Copy them to "last" */
729         memcpy(G.last_usage, G.start_usage, sizeof(G.last_usage));
730         memcpy(G.last_duration, G.start_duration, sizeof(G.last_duration));
731
732         /* Display C-states */
733         print_intel_cstates();
734
735         G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
736
737         /* The main loop */
738         for (;;) {
739                 //double maxsleep = 0.0;
740                 ullong totalticks, totalevents;
741                 int i;
742
743                 G.cant_enable_timer_stats |= start_timer(); /* 1 on error */
744 #if !ENABLE_FEATURE_USE_TERMIOS
745                 sleep(DEFAULT_SLEEP);
746 #else
747                 if (safe_poll(pfd, 1, DEFAULT_SLEEP * 1000) > 0) {
748                         unsigned char c;
749                         if (safe_read(STDIN_FILENO, &c, 1) != 1)
750                                 break; /* EOF/error */
751                         if (c == G.init_settings.c_cc[VINTR])
752                                 break; /* ^C */
753                         if ((c | 0x20) == 'q')
754                                 break;
755                 }
756 #endif
757                 G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
758
759                 clear_lines();
760                 process_irq_counts();
761
762                 /* Clear the stats */
763                 memset(cur_duration, 0, sizeof(cur_duration));
764                 memset(cur_usage, 0, sizeof(cur_usage));
765
766                 /* Read them */
767                 read_cstate_counts(cur_usage, cur_duration);
768
769                 /* Count totalticks and totalevents */
770                 totalticks = totalevents = 0;
771                 for (i = 0; i < MAX_CSTATE_COUNT; i++) {
772                         if (cur_usage[i] != 0) {
773                                 totalticks += cur_duration[i] - G.last_duration[i];
774                                 totalevents += cur_usage[i] - G.last_usage[i];
775                         }
776                 }
777
778                 /* Clear the screen */
779                 printf("\033[H\033[J");
780
781                 /* Clear C-state lines */
782                 memset(&cstate_lines, 0, sizeof(cstate_lines));
783
784                 if (totalevents == 0 && G.maxcstate <= 1) {
785                         /* This should not happen */
786                         strcpy(cstate_lines[0], "C-state information is not available\n");
787                 } else {
788                         double percentage;
789                         unsigned newticks;
790
791                         newticks = G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000 - totalticks;
792                         /* Handle rounding errors: do not display negative values */
793                         if ((int)newticks < 0)
794                                 newticks = 0;
795
796                         sprintf(cstate_lines[0], "Cn\t\t  Avg residency\n");
797                         percentage = newticks * 100.0 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
798                         sprintf(cstate_lines[1], "C0 (cpu running)        (%4.1f%%)\n", percentage);
799
800                         /* Compute values for individual C-states */
801                         for (i = 0; i < MAX_CSTATE_COUNT; i++) {
802                                 if (cur_usage[i] != 0) {
803                                         double slept;
804                                         slept = (cur_duration[i] - G.last_duration[i])
805                                                 / (cur_usage[i] - G.last_usage[i] + 0.1) / FREQ_ACPI;
806                                         percentage = (cur_duration[i] - G.last_duration[i]) * 100
807                                                 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
808                                         sprintf(cstate_lines[i + 2], "C%u\t\t%5.1fms (%4.1f%%)\n",
809                                                 i + 1, slept, percentage);
810                                         //if (maxsleep < slept)
811                                         //      maxsleep = slept;
812                                 }
813                         }
814                 }
815
816                 for (i = 0; i < MAX_CSTATE_COUNT + 2; i++)
817                         if (cstate_lines[i][0])
818                                 fputs(cstate_lines[i], stdout);
819
820                 i = process_timer_stats();
821 #if ENABLE_FEATURE_POWERTOP_PROCIRQ
822                 if (totalevents == 0) {
823                         /* No C-state info available, use timerstats */
824                         totalevents = i * G.total_cpus + G.total_interrupt;
825                         if (i < 0)
826                                 totalevents += G.interrupt_0 - i;
827                 }
828 #endif
829                 /* Upstream powertop prints wakeups per sec per CPU,
830                  * we print just raw wakeup counts.
831                  */
832 //TODO: show real seconds (think about manual refresh)
833                 printf("\nWakeups-from-idle in %u seconds: %llu\n",
834                         DEFAULT_SLEEP,
835                         totalevents
836                 );
837
838                 update_lines_cumulative_count();
839                 sort_lines();
840                 show_timerstats();
841                 fflush(stdout);
842
843                 /* Clear the stats */
844                 memset(cur_duration, 0, sizeof(cur_duration));
845                 memset(cur_usage, 0, sizeof(cur_usage));
846
847                 /* Get new values */
848                 read_cstate_counts(cur_usage, cur_duration);
849
850                 /* Save them */
851                 memcpy(G.last_usage, cur_usage, sizeof(G.last_usage));
852                 memcpy(G.last_duration, cur_duration, sizeof(G.last_duration));
853         } /* for (;;) */
854
855         bb_putchar('\n');
856
857         return EXIT_SUCCESS;
858 }