1
/* vi: set sw=4 ts=4: */
3
* A mini 'powertop' utility:
4
* Analyze power consumption on Intel-based laptops.
5
* Based on powertop 1.11.
7
* Copyright (C) 2010 Marek Polacek <mmpolacek@gmail.com>
9
* Licensed under GPLv2, see file LICENSE in this source tree.
11
//config:config POWERTOP
12
//config: bool "powertop (9.9 kb)"
15
//config: Analyze power consumption on Intel-based laptops
17
//config:config FEATURE_POWERTOP_INTERACTIVE
18
//config: bool "Accept keyboard commands"
20
//config: depends on POWERTOP
22
//config: Without this, powertop will only refresh display every 10 seconds.
23
//config: No keyboard commands will work, only ^C to terminate.
25
//applet:IF_POWERTOP(APPLET(powertop, BB_DIR_USR_SBIN, BB_SUID_DROP))
27
//kbuild:lib-$(CONFIG_POWERTOP) += powertop.o
29
// XXX This should be configurable
30
#define ENABLE_FEATURE_POWERTOP_PROCIRQ 1
35
//#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__)
36
#define debug(fmt, ...) ((void)0)
39
#define BLOATY_HPET_IRQ_NUM_DETECTION 0
40
#define MAX_CSTATE_COUNT 8
44
#define DEFAULT_SLEEP 10
45
#define DEFAULT_SLEEP_STR "10"
47
/* Frequency of the ACPI timer */
48
#define FREQ_ACPI 3579.545
49
#define FREQ_ACPI_1000 3579545
51
/* Max filename length of entry in /sys/devices subsystem */
52
#define BIG_SYSNAME_LEN 16
56
typedef unsigned long long ullong;
64
#if ENABLE_FEATURE_POWERTOP_PROCIRQ
74
struct line *lines; /* the most often used member */
76
int lines_cumulative_count;
79
smallint cant_enable_timer_stats;
80
#if ENABLE_FEATURE_POWERTOP_PROCIRQ
81
# if BLOATY_HPET_IRQ_NUM_DETECTION
82
smallint scanned_timer_list;
83
int percpu_hpet_start;
88
struct irqdata interrupts[IRQCOUNT];
90
ullong start_usage[MAX_CSTATE_COUNT];
91
ullong last_usage[MAX_CSTATE_COUNT];
92
ullong start_duration[MAX_CSTATE_COUNT];
93
ullong last_duration[MAX_CSTATE_COUNT];
94
#if ENABLE_FEATURE_POWERTOP_INTERACTIVE
95
struct termios init_settings;
98
#define G (*ptr_to_globals)
99
#define INIT_G() do { \
100
SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
103
#if ENABLE_FEATURE_POWERTOP_INTERACTIVE
104
static void reset_term(void)
106
tcsetattr_stdin_TCSANOW(&G.init_settings);
109
static void sig_handler(int signo UNUSED_PARAM)
116
static int write_str_to_file(const char *fname, const char *str)
118
FILE *fp = fopen_for_write(fname);
126
/* Make it more readable */
127
#define start_timer() write_str_to_file("/proc/timer_stats", "1\n")
128
#define stop_timer() write_str_to_file("/proc/timer_stats", "0\n")
130
static NOINLINE void clear_lines(void)
134
for (i = 0; i < G.lines_cnt; i++)
135
free(G.lines[i].string);
142
static void update_lines_cumulative_count(void)
145
for (i = 0; i < G.lines_cnt; i++)
146
G.lines_cumulative_count += G.lines[i].count;
149
static int line_compare(const void *p1, const void *p2)
151
const struct line *a = p1;
152
const struct line *b = p2;
153
return (b->count /*+ 50 * b->disk_count*/) - (a->count /*+ 50 * a->disk_count*/);
156
static void sort_lines(void)
158
qsort(G.lines, G.lines_cnt, sizeof(G.lines[0]), line_compare);
161
/* Save C-state usage and duration. Also update maxcstate. */
162
static void read_cstate_counts(ullong *usage, ullong *duration)
167
dir = opendir("/proc/acpi/processor");
171
while ((d = readdir(dir)) != NULL) {
177
len = strlen(d->d_name); /* "CPUnn" */
178
if (len < 3 || len > BIG_SYSNAME_LEN)
181
sprintf(buf, "%s/%s/power", "/proc/acpi/processor", d->d_name);
182
fp = fopen_for_read(buf);
186
// Example file contents:
189
// maximum allowed latency: 2000000000 usec
191
// C1: type[C1] promotion[--] demotion[--] latency[001] usage[00006173] duration[00000000000000000000]
192
// C2: type[C2] promotion[--] demotion[--] latency[001] usage[00085191] duration[00000000000083024907]
193
// C3: type[C3] promotion[--] demotion[--] latency[017] usage[01017622] duration[00000000017921327182]
195
while (fgets(buf, sizeof(buf), fp)) {
196
char *p = strstr(buf, "age[");
200
usage[level] += bb_strtoull(p, NULL, 10) + 1;
201
p = strstr(buf, "ation[");
205
duration[level] += bb_strtoull(p, NULL, 10);
207
if (level >= MAX_CSTATE_COUNT-1)
210
if (level > G.maxcstate) /* update maxcstate */
218
/* Add line and/or update count */
219
static void save_line(const char *string, int count)
222
for (i = 0; i < G.lines_cnt; i++) {
223
if (strcmp(string, G.lines[i].string) == 0) {
224
/* It's already there, only update count */
225
G.lines[i].count += count;
231
G.lines = xrealloc_vector(G.lines, 4, G.lines_cnt);
232
G.lines[G.lines_cnt].string = xstrdup(string);
233
G.lines[G.lines_cnt].count = count;
234
/*G.lines[G.lines_cnt].disk_count = 0;*/
238
#if ENABLE_FEATURE_POWERTOP_PROCIRQ
239
static int is_hpet_irq(const char *name)
242
# if BLOATY_HPET_IRQ_NUM_DETECTION
245
/* Learn the range of existing hpet timers. This is done once */
246
if (!G.scanned_timer_list) {
250
G.scanned_timer_list = true;
251
fp = fopen_for_read("/proc/timer_list");
255
while (fgets(buf, sizeof(buf), fp)) {
256
p = strstr(buf, "Clock Event Device: hpet");
259
p += sizeof("Clock Event Device: hpet")-1;
262
hpet_chan = xatoi_positive(p);
263
if (hpet_chan < G.percpu_hpet_start)
264
G.percpu_hpet_start = hpet_chan;
265
if (hpet_chan > G.percpu_hpet_end)
266
G.percpu_hpet_end = hpet_chan;
272
p = strstr(name, "hpet");
278
# if BLOATY_HPET_IRQ_NUM_DETECTION
279
hpet_chan = xatoi_positive(p);
280
if (hpet_chan < G.percpu_hpet_start || hpet_chan > G.percpu_hpet_end)
286
/* Save new IRQ count, return delta from old one */
287
static int save_irq_count(int irq, ullong count)
289
int unused = IRQCOUNT;
291
for (i = 0; i < IRQCOUNT; i++) {
292
if (G.interrupts[i].active && G.interrupts[i].number == irq) {
293
ullong old = G.interrupts[i].count;
294
G.interrupts[i].count = count;
297
if (!G.interrupts[i].active && unused > i)
300
if (unused < IRQCOUNT) {
301
G.interrupts[unused].active = 1;
302
G.interrupts[unused].count = count;
303
G.interrupts[unused].number = irq;
308
/* Read /proc/interrupts, save IRQ counts and IRQ description */
309
static void process_irq_counts(void)
316
G.total_interrupt = 0;
318
fp = xfopen_for_read("/proc/interrupts");
319
while (fgets(buf, sizeof(buf), fp)) {
320
char irq_desc[sizeof(" <kernel IPI> : ") + sizeof(buf)];
327
p = strchr(buf, ':');
330
/* 0: 143646045 153901007 IO-APIC-edge timer
334
/* Deal with non-maskable interrupts -- make up fake numbers */
335
nr = index_in_strings("NMI\0RES\0CAL\0TLB\0TRM\0THR\0SPU\0", buf);
339
/* bb_strtou doesn't eat leading spaces, using strtoul */
341
nr = strtoul(buf, NULL, 10);
346
/* 0: 143646045 153901007 IO-APIC-edge timer
349
/* Sum counts for this IRQ */
353
p = skip_whitespace(p);
356
count += bb_strtoull(p, &tmp, 10);
359
/* 0: 143646045 153901007 IO-APIC-edge timer
360
* NMI: 1 2 Non-maskable interrupts
364
/* Skip to the interrupt name, e.g. 'timer' */
368
p = skip_whitespace(p);
373
/* Save description of the interrupt */
375
sprintf(irq_desc, " <kernel IPI> : %s", name);
377
sprintf(irq_desc, " <interrupt> : %s", name);
379
delta = save_irq_count(nr, count);
381
/* Skip per CPU timer interrupts */
382
if (is_hpet_irq(name))
385
if (nr != 0 && delta != 0)
386
save_line(irq_desc, delta);
389
G.interrupt_0 = delta;
391
G.total_interrupt += delta;
396
#else /* !ENABLE_FEATURE_POWERTOP_PROCIRQ */
397
# define process_irq_counts() ((void)0)
400
static NOINLINE int process_timer_stats(void)
403
char line[15 + 3 + 128];
411
if (!G.cant_enable_timer_stats)
412
fp = fopen_for_read("/proc/timer_stats");
414
// Example file contents:
415
// Timer Stats Version: v0.2
416
// Sample period: 1.329 s
417
// 76, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
418
// 88, 0 swapper hrtimer_start_range_ns (tick_sched_timer)
419
// 24, 3787 firefox hrtimer_start_range_ns (hrtimer_wakeup)
420
// 46D, 1136 kondemand/1 do_dbs_timer (delayed_work_timer_fn)
422
// 1, 1656 Xorg hrtimer_start_range_ns (hrtimer_wakeup)
423
// 1, 2159 udisks-daemon hrtimer_start_range_ns (hrtimer_wakeup)
424
// 331 total events, 249.059 events/sec
425
while (fgets(buf, sizeof(buf), fp)) {
426
const char *count, *process, *func;
431
count = skip_whitespace(buf);
432
p = strchr(count, ',');
436
cnt = bb_strtou(count, NULL, 10);
437
if (strcmp(skip_non_whitespace(count), " total events") == 0) {
438
#if ENABLE_FEATURE_POWERTOP_PROCIRQ
439
n = cnt / G.total_cpus;
440
if (n > 0 && n < G.interrupt_0) {
441
sprintf(line, " <interrupt> : %s", "extra timer interrupt");
442
save_line(line, G.interrupt_0 - n);
447
if (strchr(count, 'D'))
448
continue; /* deferred */
449
p = skip_whitespace(p); /* points to pid now */
456
p = skip_whitespace(p);
457
if (process == NULL) {
463
//if (strcmp(process, "swapper") == 0
464
// && strcmp(func, "hrtimer_start_range_ns (tick_sched_timer)\n") == 0
466
// process = "[kernel scheduler]";
467
// func = "Load balancing tick";
470
if (is_prefixed_with(func, "tick_nohz_"))
472
if (is_prefixed_with(func, "tick_setup_sched_timer"))
474
//if (strcmp(process, "powertop") == 0)
477
idx = index_in_strings("insmod\0modprobe\0swapper\0", process);
479
process = idx < 2 ? "[kernel module]" : "<kernel core>";
484
// 46D\01136\0kondemand/1\0do_dbs_timer (delayed_work_timer_fn)
486
// count process func
488
//if (strchr(process, '['))
489
sprintf(line, "%15.15s : %s", process, func);
491
// sprintf(line, "%s", process);
492
save_line(line, cnt);
501
static void cpuid_eax_ecx_edx(unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx)
504
: "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx)
505
: "0" (*eax), "2" (*ecx), "3" (*edx)
511
static NOINLINE void print_intel_cstates(void)
513
int bios_table[8] = { 0 };
518
unsigned eax, ebx, ecx, edx;
520
cpudir = opendir("/sys/devices/system/cpu");
524
/* Loop over cpuN entries */
525
while ((d = readdir(cpudir)) != NULL) {
528
char fname[sizeof("/sys/devices/system/cpu//cpuidle//desc") + 2*BIG_SYSNAME_LEN];
530
len = strlen(d->d_name);
531
if (len < 3 || len > BIG_SYSNAME_LEN)
534
if (!isdigit(d->d_name[3]))
537
len = sprintf(fname, "%s/%s/cpuidle", "/sys/devices/system/cpu", d->d_name);
538
dir = opendir(fname);
543
* Every C-state has its own stateN directory, that
544
* contains a 'time' and a 'usage' file.
546
while ((d = readdir(dir)) != NULL) {
551
n = strlen(d->d_name);
552
if (n < 3 || n > BIG_SYSNAME_LEN)
555
sprintf(fname + len, "/%s/desc", d->d_name);
556
fp = fopen_for_read(fname);
558
char *p = fgets(buf, sizeof(buf), fp);
562
p = strstr(p, "MWAIT ");
565
p += sizeof("MWAIT ") - 1;
566
pos = (bb_strtoull(p, NULL, 16) >> 4) + 1;
567
if (pos >= ARRAY_SIZE(bios_table))
582
ecx = edx = 0; /* paranoia, should not be needed */
583
cpuid_eax_ecx_edx(&eax, /*unused:*/&ebx, &ecx, &edx);
584
if (!edx || !(ecx & 1))
587
printf("Your %s the following C-states: ", "CPU supports");
597
/* Print BIOS C-States */
598
printf("Your %s the following C-states: ", "BIOS reports");
599
for (i = 0; i < ARRAY_SIZE(bios_table); i++)
606
# define print_intel_cstates() ((void)0)
609
static void show_timerstats(void)
613
/* Get terminal height */
614
get_terminal_width_height(STDOUT_FILENO, NULL, &lines);
616
/* We don't have whole terminal just for timerstats */
619
if (!G.cant_enable_timer_stats) {
623
puts("\nTop causes for wakeups:");
624
for (i = 0; i < G.lines_cnt; i++) {
625
if ((G.lines[i].count > 0 /*|| G.lines[i].disk_count > 0*/)
628
/* NB: upstream powertop prints "(wakeups/sec)",
629
* we print just "(wakeup counts)".
632
if (G.lines[i].disk_count)
634
smart_ulltoa5(G.lines[i].count, strbuf6, " KMGTPEZY")[0] = '\0';
635
printf(/*" %5.1f%% (%s)%c %s\n"*/
636
" %5.1f%% (%s) %s\n",
637
G.lines[i].count * 100.0 / G.lines_cumulative_count,
644
bb_simple_error_msg("no stats available; run as root or"
645
" enable the timer_stats module");
649
// Example display from powertop version 1.11
650
// Cn Avg residency P-states (frequencies)
651
// C0 (cpu running) ( 0.5%) 2.00 Ghz 0.0%
652
// polling 0.0ms ( 0.0%) 1.67 Ghz 0.0%
653
// C1 mwait 0.0ms ( 0.0%) 1333 Mhz 0.1%
654
// C2 mwait 0.1ms ( 0.1%) 1000 Mhz 99.9%
655
// C3 mwait 12.1ms (99.4%)
657
// Wakeups-from-idle per second : 93.6 interval: 15.0s
658
// no ACPI power usage estimate available
660
// Top causes for wakeups:
661
// 32.4% ( 26.7) <interrupt> : extra timer interrupt
662
// 29.0% ( 23.9) <kernel core> : hrtimer_start_range_ns (tick_sched_timer)
663
// 9.0% ( 7.5) <kernel core> : hrtimer_start (tick_sched_timer)
664
// 6.5% ( 5.3) <interrupt> : ata_piix
665
// 5.0% ( 4.1) inetd : hrtimer_start_range_ns (hrtimer_wakeup)
667
//usage:#define powertop_trivial_usage
669
//usage:#define powertop_full_usage "\n\n"
670
//usage: "Analyze power consumption on Intel-based laptops"
672
int powertop_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
673
int powertop_main(int argc UNUSED_PARAM, char UNUSED_PARAM **argv)
675
ullong cur_usage[MAX_CSTATE_COUNT];
676
ullong cur_duration[MAX_CSTATE_COUNT];
677
char cstate_lines[MAX_CSTATE_COUNT + 2][64];
678
#if ENABLE_FEATURE_POWERTOP_INTERACTIVE
679
struct pollfd pfd[1];
682
pfd[0].events = POLLIN;
687
#if ENABLE_FEATURE_POWERTOP_PROCIRQ && BLOATY_HPET_IRQ_NUM_DETECTION
688
G.percpu_hpet_start = INT_MAX;
689
G.percpu_hpet_end = INT_MIN;
692
/* Print warning when we don't have superuser privileges */
694
bb_simple_error_msg("run as root to collect enough information");
696
/* Get number of CPUs */
697
G.total_cpus = get_cpu_count();
699
puts("Collecting data for "DEFAULT_SLEEP_STR" seconds");
701
#if ENABLE_FEATURE_POWERTOP_INTERACTIVE
702
/* Turn on unbuffered input; turn off echoing, ^C ^Z etc */
703
set_termios_to_raw(STDIN_FILENO, &G.init_settings, TERMIOS_CLEAR_ISIG);
704
bb_signals(BB_FATAL_SIGS, sig_handler);
705
/* So we don't forget to reset term settings */
706
die_func = reset_term;
709
/* Collect initial data */
710
process_irq_counts();
712
/* Read initial usage and duration */
713
read_cstate_counts(G.start_usage, G.start_duration);
715
/* Copy them to "last" */
716
memcpy(G.last_usage, G.start_usage, sizeof(G.last_usage));
717
memcpy(G.last_duration, G.start_duration, sizeof(G.last_duration));
719
/* Display C-states */
720
print_intel_cstates();
722
G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
726
//double maxsleep = 0.0;
727
ullong totalticks, totalevents;
730
G.cant_enable_timer_stats |= start_timer(); /* 1 on error */
731
#if !ENABLE_FEATURE_POWERTOP_INTERACTIVE
732
sleep(DEFAULT_SLEEP);
734
if (safe_poll(pfd, 1, DEFAULT_SLEEP * 1000) > 0) {
736
if (safe_read(STDIN_FILENO, &c, 1) != 1)
737
break; /* EOF/error */
738
if (c == G.init_settings.c_cc[VINTR])
740
if ((c | 0x20) == 'q')
744
G.cant_enable_timer_stats |= stop_timer(); /* 1 on error */
747
process_irq_counts();
749
/* Clear the stats */
750
memset(cur_duration, 0, sizeof(cur_duration));
751
memset(cur_usage, 0, sizeof(cur_usage));
754
read_cstate_counts(cur_usage, cur_duration);
756
/* Count totalticks and totalevents */
757
totalticks = totalevents = 0;
758
for (i = 0; i < MAX_CSTATE_COUNT; i++) {
759
if (cur_usage[i] != 0) {
760
totalticks += cur_duration[i] - G.last_duration[i];
761
totalevents += cur_usage[i] - G.last_usage[i];
765
/* Home; clear screen */
766
printf(ESC"[H" ESC"[J");
768
/* Clear C-state lines */
769
memset(&cstate_lines, 0, sizeof(cstate_lines));
771
if (totalevents == 0 && G.maxcstate <= 1) {
772
/* This should not happen */
773
strcpy(cstate_lines[0], "C-state information is not available\n");
778
newticks = G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000 - totalticks;
779
/* Handle rounding errors: do not display negative values */
780
if ((int)newticks < 0)
783
sprintf(cstate_lines[0], "Cn\t\t Avg residency\n");
784
percentage = newticks * 100.0 / (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
785
sprintf(cstate_lines[1], "C0 (cpu running) (%4.1f%%)\n", percentage);
787
/* Compute values for individual C-states */
788
for (i = 0; i < MAX_CSTATE_COUNT; i++) {
789
if (cur_usage[i] != 0) {
791
slept = (cur_duration[i] - G.last_duration[i])
792
/ (cur_usage[i] - G.last_usage[i] + 0.1) / FREQ_ACPI;
793
percentage = (cur_duration[i] - G.last_duration[i]) * 100
794
/ (G.total_cpus * DEFAULT_SLEEP * FREQ_ACPI_1000);
795
sprintf(cstate_lines[i + 2], "C%u\t\t%5.1fms (%4.1f%%)\n",
796
i + 1, slept, percentage);
797
//if (maxsleep < slept)
803
for (i = 0; i < MAX_CSTATE_COUNT + 2; i++)
804
if (cstate_lines[i][0])
805
fputs_stdout(cstate_lines[i]);
807
i = process_timer_stats();
808
#if ENABLE_FEATURE_POWERTOP_PROCIRQ
809
if (totalevents == 0) {
810
/* No C-state info available, use timerstats */
811
totalevents = i * G.total_cpus + G.total_interrupt;
813
totalevents += G.interrupt_0 - i;
816
/* Upstream powertop prints wakeups per sec per CPU,
817
* we print just raw wakeup counts.
819
//TODO: show real seconds (think about manual refresh)
820
printf("\nWakeups-from-idle in %u seconds: %llu\n",
825
update_lines_cumulative_count();
830
/* Clear the stats */
831
memset(cur_duration, 0, sizeof(cur_duration));
832
memset(cur_usage, 0, sizeof(cur_usage));
835
read_cstate_counts(cur_usage, cur_duration);
838
memcpy(G.last_usage, cur_usage, sizeof(G.last_usage));
839
memcpy(G.last_duration, cur_duration, sizeof(G.last_duration));
843
#if ENABLE_FEATURE_POWERTOP_INTERACTIVE