c8b535bc27bd70a8e6f3bc276ce9537050d28f8b
[linux-3.10.git] / tools / perf / builtin-stat.c
1 /*
2  * builtin-stat.c
3  *
4  * Builtin stat command: Give a precise performance counters summary
5  * overview about any workload, CPU or specific PID.
6  *
7  * Sample output:
8
9    $ perf stat ~/hackbench 10
10    Time: 0.104
11
12     Performance counter stats for '/home/mingo/hackbench':
13
14        1255.538611  task clock ticks     #      10.143 CPU utilization factor
15              54011  context switches     #       0.043 M/sec
16                385  CPU migrations       #       0.000 M/sec
17              17755  pagefaults           #       0.014 M/sec
18         3808323185  CPU cycles           #    3033.219 M/sec
19         1575111190  instructions         #    1254.530 M/sec
20           17367895  cache references     #      13.833 M/sec
21            7674421  cache misses         #       6.112 M/sec
22
23     Wall-clock time elapsed:   123.786620 msecs
24
25  *
26  * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
27  *
28  * Improvements and fixes by:
29  *
30  *   Arjan van de Ven <arjan@linux.intel.com>
31  *   Yanmin Zhang <yanmin.zhang@intel.com>
32  *   Wu Fengguang <fengguang.wu@intel.com>
33  *   Mike Galbraith <efault@gmx.de>
34  *   Paul Mackerras <paulus@samba.org>
35  *   Jaswinder Singh Rajput <jaswinder@kernel.org>
36  *
37  * Released under the GPL v2. (and only v2, not any later version)
38  */
39
40 #include "perf.h"
41 #include "builtin.h"
42 #include "util/util.h"
43 #include "util/parse-options.h"
44 #include "util/parse-events.h"
45 #include "util/event.h"
46 #include "util/evlist.h"
47 #include "util/evsel.h"
48 #include "util/debug.h"
49 #include "util/color.h"
50 #include "util/header.h"
51 #include "util/cpumap.h"
52 #include "util/thread.h"
53 #include "util/thread_map.h"
54
55 #include <sys/prctl.h>
56 #include <math.h>
57 #include <locale.h>
58
59 #define DEFAULT_SEPARATOR       " "
60
61 static struct perf_event_attr default_attrs[] = {
62
63   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK              },
64   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES        },
65   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS          },
66   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS             },
67
68   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES              },
69   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
70   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND  },
71   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS            },
72   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS     },
73   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES           },
74
75 };
76
77 /*
78  * Detailed stats:
79  */
80 static struct perf_event_attr detailed_attrs[] = {
81
82   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK              },
83   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES        },
84   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS          },
85   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS             },
86
87   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES              },
88   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
89   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND  },
90   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS            },
91   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS     },
92   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES           },
93
94   { .type = PERF_TYPE_HW_CACHE,
95     .config =
96          PERF_COUNT_HW_CACHE_L1D                <<  0  |
97         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
98         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
99
100   { .type = PERF_TYPE_HW_CACHE,
101     .config =
102          PERF_COUNT_HW_CACHE_L1D                <<  0  |
103         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
104         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
105
106   { .type = PERF_TYPE_HW_CACHE,
107     .config =
108          PERF_COUNT_HW_CACHE_LL                 <<  0  |
109         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
110         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
111
112   { .type = PERF_TYPE_HW_CACHE,
113     .config =
114          PERF_COUNT_HW_CACHE_LL                 <<  0  |
115         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
116         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
117 };
118
119 struct perf_evlist              *evsel_list;
120
121 static bool                     system_wide                     =  false;
122 static int                      run_idx                         =  0;
123
124 static int                      run_count                       =  1;
125 static bool                     no_inherit                      = false;
126 static bool                     scale                           =  true;
127 static bool                     no_aggr                         = false;
128 static pid_t                    target_pid                      = -1;
129 static pid_t                    target_tid                      = -1;
130 static pid_t                    child_pid                       = -1;
131 static bool                     null_run                        =  false;
132 static bool                     detailed_run                    =  false;
133 static bool                     sync_run                        =  false;
134 static bool                     big_num                         =  true;
135 static int                      big_num_opt                     =  -1;
136 static const char               *cpu_list;
137 static const char               *csv_sep                        = NULL;
138 static bool                     csv_output                      = false;
139
140 static volatile int done = 0;
141
142 struct stats
143 {
144         double n, mean, M2;
145 };
146
147 struct perf_stat {
148         struct stats      res_stats[3];
149 };
150
151 static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
152 {
153         evsel->priv = zalloc(sizeof(struct perf_stat));
154         return evsel->priv == NULL ? -ENOMEM : 0;
155 }
156
157 static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
158 {
159         free(evsel->priv);
160         evsel->priv = NULL;
161 }
162
163 static void update_stats(struct stats *stats, u64 val)
164 {
165         double delta;
166
167         stats->n++;
168         delta = val - stats->mean;
169         stats->mean += delta / stats->n;
170         stats->M2 += delta*(val - stats->mean);
171 }
172
173 static double avg_stats(struct stats *stats)
174 {
175         return stats->mean;
176 }
177
178 /*
179  * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
180  *
181  *       (\Sum n_i^2) - ((\Sum n_i)^2)/n
182  * s^2 = -------------------------------
183  *                  n - 1
184  *
185  * http://en.wikipedia.org/wiki/Stddev
186  *
187  * The std dev of the mean is related to the std dev by:
188  *
189  *             s
190  * s_mean = -------
191  *          sqrt(n)
192  *
193  */
194 static double stddev_stats(struct stats *stats)
195 {
196         double variance = stats->M2 / (stats->n - 1);
197         double variance_mean = variance / stats->n;
198
199         return sqrt(variance_mean);
200 }
201
202 struct stats                    runtime_nsecs_stats[MAX_NR_CPUS];
203 struct stats                    runtime_cycles_stats[MAX_NR_CPUS];
204 struct stats                    runtime_stalled_cycles_front_stats[MAX_NR_CPUS];
205 struct stats                    runtime_stalled_cycles_back_stats[MAX_NR_CPUS];
206 struct stats                    runtime_branches_stats[MAX_NR_CPUS];
207 struct stats                    runtime_cacherefs_stats[MAX_NR_CPUS];
208 struct stats                    runtime_l1_dcache_stats[MAX_NR_CPUS];
209 struct stats                    walltime_nsecs_stats;
210
211 static int create_perf_stat_counter(struct perf_evsel *evsel)
212 {
213         struct perf_event_attr *attr = &evsel->attr;
214
215         if (scale)
216                 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
217                                     PERF_FORMAT_TOTAL_TIME_RUNNING;
218
219         attr->inherit = !no_inherit;
220
221         if (system_wide)
222                 return perf_evsel__open_per_cpu(evsel, evsel_list->cpus, false);
223
224         if (target_pid == -1 && target_tid == -1) {
225                 attr->disabled = 1;
226                 attr->enable_on_exec = 1;
227         }
228
229         return perf_evsel__open_per_thread(evsel, evsel_list->threads, false);
230 }
231
232 /*
233  * Does the counter have nsecs as a unit?
234  */
235 static inline int nsec_counter(struct perf_evsel *evsel)
236 {
237         if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
238             perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
239                 return 1;
240
241         return 0;
242 }
243
244 /*
245  * Update various tracking values we maintain to print
246  * more semantic information such as miss/hit ratios,
247  * instruction rates, etc:
248  */
249 static void update_shadow_stats(struct perf_evsel *counter, u64 *count)
250 {
251         if (perf_evsel__match(counter, SOFTWARE, SW_TASK_CLOCK))
252                 update_stats(&runtime_nsecs_stats[0], count[0]);
253         else if (perf_evsel__match(counter, HARDWARE, HW_CPU_CYCLES))
254                 update_stats(&runtime_cycles_stats[0], count[0]);
255         else if (perf_evsel__match(counter, HARDWARE, HW_STALLED_CYCLES_FRONTEND))
256                 update_stats(&runtime_stalled_cycles_front_stats[0], count[0]);
257         else if (perf_evsel__match(counter, HARDWARE, HW_STALLED_CYCLES_BACKEND))
258                 update_stats(&runtime_stalled_cycles_back_stats[0], count[0]);
259         else if (perf_evsel__match(counter, HARDWARE, HW_BRANCH_INSTRUCTIONS))
260                 update_stats(&runtime_branches_stats[0], count[0]);
261         else if (perf_evsel__match(counter, HARDWARE, HW_CACHE_REFERENCES))
262                 update_stats(&runtime_cacherefs_stats[0], count[0]);
263         else if (perf_evsel__match(counter, HW_CACHE, HW_CACHE_L1D))
264                 update_stats(&runtime_l1_dcache_stats[0], count[0]);
265 }
266
267 /*
268  * Read out the results of a single counter:
269  * aggregate counts across CPUs in system-wide mode
270  */
271 static int read_counter_aggr(struct perf_evsel *counter)
272 {
273         struct perf_stat *ps = counter->priv;
274         u64 *count = counter->counts->aggr.values;
275         int i;
276
277         if (__perf_evsel__read(counter, evsel_list->cpus->nr,
278                                evsel_list->threads->nr, scale) < 0)
279                 return -1;
280
281         for (i = 0; i < 3; i++)
282                 update_stats(&ps->res_stats[i], count[i]);
283
284         if (verbose) {
285                 fprintf(stderr, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
286                         event_name(counter), count[0], count[1], count[2]);
287         }
288
289         /*
290          * Save the full runtime - to allow normalization during printout:
291          */
292         update_shadow_stats(counter, count);
293
294         return 0;
295 }
296
297 /*
298  * Read out the results of a single counter:
299  * do not aggregate counts across CPUs in system-wide mode
300  */
301 static int read_counter(struct perf_evsel *counter)
302 {
303         u64 *count;
304         int cpu;
305
306         for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
307                 if (__perf_evsel__read_on_cpu(counter, cpu, 0, scale) < 0)
308                         return -1;
309
310                 count = counter->counts->cpu[cpu].values;
311
312                 update_shadow_stats(counter, count);
313         }
314
315         return 0;
316 }
317
318 static int run_perf_stat(int argc __used, const char **argv)
319 {
320         unsigned long long t0, t1;
321         struct perf_evsel *counter;
322         int status = 0;
323         int child_ready_pipe[2], go_pipe[2];
324         const bool forks = (argc > 0);
325         char buf;
326
327         if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
328                 perror("failed to create pipes");
329                 exit(1);
330         }
331
332         if (forks) {
333                 if ((child_pid = fork()) < 0)
334                         perror("failed to fork");
335
336                 if (!child_pid) {
337                         close(child_ready_pipe[0]);
338                         close(go_pipe[1]);
339                         fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
340
341                         /*
342                          * Do a dummy execvp to get the PLT entry resolved,
343                          * so we avoid the resolver overhead on the real
344                          * execvp call.
345                          */
346                         execvp("", (char **)argv);
347
348                         /*
349                          * Tell the parent we're ready to go
350                          */
351                         close(child_ready_pipe[1]);
352
353                         /*
354                          * Wait until the parent tells us to go.
355                          */
356                         if (read(go_pipe[0], &buf, 1) == -1)
357                                 perror("unable to read pipe");
358
359                         execvp(argv[0], (char **)argv);
360
361                         perror(argv[0]);
362                         exit(-1);
363                 }
364
365                 if (target_tid == -1 && target_pid == -1 && !system_wide)
366                         evsel_list->threads->map[0] = child_pid;
367
368                 /*
369                  * Wait for the child to be ready to exec.
370                  */
371                 close(child_ready_pipe[1]);
372                 close(go_pipe[0]);
373                 if (read(child_ready_pipe[0], &buf, 1) == -1)
374                         perror("unable to read pipe");
375                 close(child_ready_pipe[0]);
376         }
377
378         list_for_each_entry(counter, &evsel_list->entries, node) {
379                 if (create_perf_stat_counter(counter) < 0) {
380                         if (errno == EINVAL || errno == ENOSYS || errno == ENOENT)
381                                 continue;
382
383                         if (errno == EPERM || errno == EACCES) {
384                                 error("You may not have permission to collect %sstats.\n"
385                                       "\t Consider tweaking"
386                                       " /proc/sys/kernel/perf_event_paranoid or running as root.",
387                                       system_wide ? "system-wide " : "");
388                         } else {
389                                 error("open_counter returned with %d (%s). "
390                                       "/bin/dmesg may provide additional information.\n",
391                                        errno, strerror(errno));
392                         }
393                         if (child_pid != -1)
394                                 kill(child_pid, SIGTERM);
395                         die("Not all events could be opened.\n");
396                         return -1;
397                 }
398         }
399
400         if (perf_evlist__set_filters(evsel_list)) {
401                 error("failed to set filter with %d (%s)\n", errno,
402                         strerror(errno));
403                 return -1;
404         }
405
406         /*
407          * Enable counters and exec the command:
408          */
409         t0 = rdclock();
410
411         if (forks) {
412                 close(go_pipe[1]);
413                 wait(&status);
414         } else {
415                 while(!done) sleep(1);
416         }
417
418         t1 = rdclock();
419
420         update_stats(&walltime_nsecs_stats, t1 - t0);
421
422         if (no_aggr) {
423                 list_for_each_entry(counter, &evsel_list->entries, node) {
424                         read_counter(counter);
425                         perf_evsel__close_fd(counter, evsel_list->cpus->nr, 1);
426                 }
427         } else {
428                 list_for_each_entry(counter, &evsel_list->entries, node) {
429                         read_counter_aggr(counter);
430                         perf_evsel__close_fd(counter, evsel_list->cpus->nr,
431                                              evsel_list->threads->nr);
432                 }
433         }
434
435         return WEXITSTATUS(status);
436 }
437
438 static void print_noise_pct(double total, double avg)
439 {
440         double pct = 0.0;
441
442         if (avg)
443                 pct = 100.0*total/avg;
444
445         fprintf(stderr, "  ( +-%6.2f%% )", pct);
446 }
447
448 static void print_noise(struct perf_evsel *evsel, double avg)
449 {
450         struct perf_stat *ps;
451
452         if (run_count == 1)
453                 return;
454
455         ps = evsel->priv;
456         print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
457 }
458
459 static void nsec_printout(int cpu, struct perf_evsel *evsel, double avg)
460 {
461         double msecs = avg / 1e6;
462         char cpustr[16] = { '\0', };
463         const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
464
465         if (no_aggr)
466                 sprintf(cpustr, "CPU%*d%s",
467                         csv_output ? 0 : -4,
468                         evsel_list->cpus->map[cpu], csv_sep);
469
470         fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(evsel));
471
472         if (evsel->cgrp)
473                 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
474
475         if (csv_output)
476                 return;
477
478         if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
479                 fprintf(stderr, " # %8.3f CPUs utilized          ", avg / avg_stats(&walltime_nsecs_stats));
480 }
481
482 static void print_stalled_cycles_frontend(int cpu, struct perf_evsel *evsel __used, double avg)
483 {
484         double total, ratio = 0.0;
485         const char *color;
486
487         total = avg_stats(&runtime_cycles_stats[cpu]);
488
489         if (total)
490                 ratio = avg / total * 100.0;
491
492         color = PERF_COLOR_NORMAL;
493         if (ratio > 50.0)
494                 color = PERF_COLOR_RED;
495         else if (ratio > 30.0)
496                 color = PERF_COLOR_MAGENTA;
497         else if (ratio > 10.0)
498                 color = PERF_COLOR_YELLOW;
499
500         fprintf(stderr, " #  ");
501         color_fprintf(stderr, color, "%6.2f%%", ratio);
502         fprintf(stderr, " frontend cycles idle   ");
503 }
504
505 static void print_stalled_cycles_backend(int cpu, struct perf_evsel *evsel __used, double avg)
506 {
507         double total, ratio = 0.0;
508         const char *color;
509
510         total = avg_stats(&runtime_cycles_stats[cpu]);
511
512         if (total)
513                 ratio = avg / total * 100.0;
514
515         color = PERF_COLOR_NORMAL;
516         if (ratio > 75.0)
517                 color = PERF_COLOR_RED;
518         else if (ratio > 50.0)
519                 color = PERF_COLOR_MAGENTA;
520         else if (ratio > 20.0)
521                 color = PERF_COLOR_YELLOW;
522
523         fprintf(stderr, " #  ");
524         color_fprintf(stderr, color, "%6.2f%%", ratio);
525         fprintf(stderr, " backend  cycles idle   ");
526 }
527
528 static void print_branch_misses(int cpu, struct perf_evsel *evsel __used, double avg)
529 {
530         double total, ratio = 0.0;
531         const char *color;
532
533         total = avg_stats(&runtime_branches_stats[cpu]);
534
535         if (total)
536                 ratio = avg / total * 100.0;
537
538         color = PERF_COLOR_NORMAL;
539         if (ratio > 20.0)
540                 color = PERF_COLOR_RED;
541         else if (ratio > 10.0)
542                 color = PERF_COLOR_MAGENTA;
543         else if (ratio > 5.0)
544                 color = PERF_COLOR_YELLOW;
545
546         fprintf(stderr, " #  ");
547         color_fprintf(stderr, color, "%6.2f%%", ratio);
548         fprintf(stderr, " of all branches        ");
549 }
550
551 static void print_l1_dcache_misses(int cpu, struct perf_evsel *evsel __used, double avg)
552 {
553         double total, ratio = 0.0;
554         const char *color;
555
556         total = avg_stats(&runtime_l1_dcache_stats[cpu]);
557
558         if (total)
559                 ratio = avg / total * 100.0;
560
561         color = PERF_COLOR_NORMAL;
562         if (ratio > 20.0)
563                 color = PERF_COLOR_RED;
564         else if (ratio > 10.0)
565                 color = PERF_COLOR_MAGENTA;
566         else if (ratio > 5.0)
567                 color = PERF_COLOR_YELLOW;
568
569         fprintf(stderr, " #  ");
570         color_fprintf(stderr, color, "%6.2f%%", ratio);
571         fprintf(stderr, " of all L1-dcache hits  ");
572 }
573
574 static void abs_printout(int cpu, struct perf_evsel *evsel, double avg)
575 {
576         double total, ratio = 0.0;
577         char cpustr[16] = { '\0', };
578         const char *fmt;
579
580         if (csv_output)
581                 fmt = "%s%.0f%s%s";
582         else if (big_num)
583                 fmt = "%s%'18.0f%s%-24s";
584         else
585                 fmt = "%s%18.0f%s%-24s";
586
587         if (no_aggr)
588                 sprintf(cpustr, "CPU%*d%s",
589                         csv_output ? 0 : -4,
590                         evsel_list->cpus->map[cpu], csv_sep);
591         else
592                 cpu = 0;
593
594         fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(evsel));
595
596         if (evsel->cgrp)
597                 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
598
599         if (csv_output)
600                 return;
601
602         if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
603                 total = avg_stats(&runtime_cycles_stats[cpu]);
604
605                 if (total)
606                         ratio = avg / total;
607
608                 fprintf(stderr, " #   %5.2f  insns per cycle        ", ratio);
609
610                 total = avg_stats(&runtime_stalled_cycles_front_stats[cpu]);
611                 total = max(total, avg_stats(&runtime_stalled_cycles_back_stats[cpu]));
612
613                 if (total && avg) {
614                         ratio = total / avg;
615                         fprintf(stderr, "\n                                            #   %5.2f  stalled cycles per insn", ratio);
616                 }
617
618         } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
619                         runtime_branches_stats[cpu].n != 0) {
620                 print_branch_misses(cpu, evsel, avg);
621         } else if (
622                 evsel->attr.type == PERF_TYPE_HW_CACHE &&
623                 evsel->attr.config ==  ( PERF_COUNT_HW_CACHE_L1D |
624                                         ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
625                                         ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
626                         runtime_l1_dcache_stats[cpu].n != 0) {
627                 print_l1_dcache_misses(cpu, evsel, avg);
628         } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
629                         runtime_cacherefs_stats[cpu].n != 0) {
630                 total = avg_stats(&runtime_cacherefs_stats[cpu]);
631
632                 if (total)
633                         ratio = avg * 100 / total;
634
635                 fprintf(stderr, " # %8.3f %% of all cache refs    ", ratio);
636
637         } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES_FRONTEND)) {
638                 print_stalled_cycles_frontend(cpu, evsel, avg);
639         } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES_BACKEND)) {
640                 print_stalled_cycles_backend(cpu, evsel, avg);
641         } else if (perf_evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
642                 total = avg_stats(&runtime_nsecs_stats[cpu]);
643
644                 if (total)
645                         ratio = 1.0 * avg / total;
646
647                 fprintf(stderr, " # %8.3f GHz                    ", ratio);
648         } else if (runtime_nsecs_stats[cpu].n != 0) {
649                 total = avg_stats(&runtime_nsecs_stats[cpu]);
650
651                 if (total)
652                         ratio = 1000.0 * avg / total;
653
654                 fprintf(stderr, " # %8.3f M/sec                  ", ratio);
655         } else {
656                 fprintf(stderr, "                                   ");
657         }
658 }
659
660 /*
661  * Print out the results of a single counter:
662  * aggregated counts in system-wide mode
663  */
664 static void print_counter_aggr(struct perf_evsel *counter)
665 {
666         struct perf_stat *ps = counter->priv;
667         double avg = avg_stats(&ps->res_stats[0]);
668         int scaled = counter->counts->scaled;
669
670         if (scaled == -1) {
671                 fprintf(stderr, "%*s%s%*s",
672                         csv_output ? 0 : 18,
673                         "<not counted>",
674                         csv_sep,
675                         csv_output ? 0 : -24,
676                         event_name(counter));
677
678                 if (counter->cgrp)
679                         fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
680
681                 fputc('\n', stderr);
682                 return;
683         }
684
685         if (nsec_counter(counter))
686                 nsec_printout(-1, counter, avg);
687         else
688                 abs_printout(-1, counter, avg);
689
690         if (csv_output) {
691                 fputc('\n', stderr);
692                 return;
693         }
694
695         print_noise(counter, avg);
696
697         if (scaled) {
698                 double avg_enabled, avg_running;
699
700                 avg_enabled = avg_stats(&ps->res_stats[1]);
701                 avg_running = avg_stats(&ps->res_stats[2]);
702
703                 fprintf(stderr, "  (%.2f%%)", 100 * avg_running / avg_enabled);
704         }
705         fprintf(stderr, "\n");
706 }
707
708 /*
709  * Print out the results of a single counter:
710  * does not use aggregated count in system-wide
711  */
712 static void print_counter(struct perf_evsel *counter)
713 {
714         u64 ena, run, val;
715         int cpu;
716
717         for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
718                 val = counter->counts->cpu[cpu].val;
719                 ena = counter->counts->cpu[cpu].ena;
720                 run = counter->counts->cpu[cpu].run;
721                 if (run == 0 || ena == 0) {
722                         fprintf(stderr, "CPU%*d%s%*s%s%*s",
723                                 csv_output ? 0 : -4,
724                                 evsel_list->cpus->map[cpu], csv_sep,
725                                 csv_output ? 0 : 18,
726                                 "<not counted>", csv_sep,
727                                 csv_output ? 0 : -24,
728                                 event_name(counter));
729
730                         if (counter->cgrp)
731                                 fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
732
733                         fputc('\n', stderr);
734                         continue;
735                 }
736
737                 if (nsec_counter(counter))
738                         nsec_printout(cpu, counter, val);
739                 else
740                         abs_printout(cpu, counter, val);
741
742                 if (!csv_output) {
743                         print_noise(counter, 1.0);
744
745                         if (run != ena)
746                                 fprintf(stderr, "  (%.2f%%)", 100.0 * run / ena);
747                 }
748                 fputc('\n', stderr);
749         }
750 }
751
752 static void print_stat(int argc, const char **argv)
753 {
754         struct perf_evsel *counter;
755         int i;
756
757         fflush(stdout);
758
759         if (!csv_output) {
760                 fprintf(stderr, "\n");
761                 fprintf(stderr, " Performance counter stats for ");
762                 if(target_pid == -1 && target_tid == -1) {
763                         fprintf(stderr, "\'%s", argv[0]);
764                         for (i = 1; i < argc; i++)
765                                 fprintf(stderr, " %s", argv[i]);
766                 } else if (target_pid != -1)
767                         fprintf(stderr, "process id \'%d", target_pid);
768                 else
769                         fprintf(stderr, "thread id \'%d", target_tid);
770
771                 fprintf(stderr, "\'");
772                 if (run_count > 1)
773                         fprintf(stderr, " (%d runs)", run_count);
774                 fprintf(stderr, ":\n\n");
775         }
776
777         if (no_aggr) {
778                 list_for_each_entry(counter, &evsel_list->entries, node)
779                         print_counter(counter);
780         } else {
781                 list_for_each_entry(counter, &evsel_list->entries, node)
782                         print_counter_aggr(counter);
783         }
784
785         if (!csv_output) {
786                 fprintf(stderr, "\n");
787                 fprintf(stderr, " %18.9f  seconds time elapsed",
788                                 avg_stats(&walltime_nsecs_stats)/1e9);
789                 if (run_count > 1) {
790                         print_noise_pct(stddev_stats(&walltime_nsecs_stats),
791                                         avg_stats(&walltime_nsecs_stats));
792                 }
793                 fprintf(stderr, "\n\n");
794         }
795 }
796
797 static volatile int signr = -1;
798
799 static void skip_signal(int signo)
800 {
801         if(child_pid == -1)
802                 done = 1;
803
804         signr = signo;
805 }
806
807 static void sig_atexit(void)
808 {
809         if (child_pid != -1)
810                 kill(child_pid, SIGTERM);
811
812         if (signr == -1)
813                 return;
814
815         signal(signr, SIG_DFL);
816         kill(getpid(), signr);
817 }
818
819 static const char * const stat_usage[] = {
820         "perf stat [<options>] [<command>]",
821         NULL
822 };
823
824 static int stat__set_big_num(const struct option *opt __used,
825                              const char *s __used, int unset)
826 {
827         big_num_opt = unset ? 0 : 1;
828         return 0;
829 }
830
831 static const struct option options[] = {
832         OPT_CALLBACK('e', "event", &evsel_list, "event",
833                      "event selector. use 'perf list' to list available events",
834                      parse_events),
835         OPT_CALLBACK(0, "filter", &evsel_list, "filter",
836                      "event filter", parse_filter),
837         OPT_BOOLEAN('i', "no-inherit", &no_inherit,
838                     "child tasks do not inherit counters"),
839         OPT_INTEGER('p', "pid", &target_pid,
840                     "stat events on existing process id"),
841         OPT_INTEGER('t', "tid", &target_tid,
842                     "stat events on existing thread id"),
843         OPT_BOOLEAN('a', "all-cpus", &system_wide,
844                     "system-wide collection from all CPUs"),
845         OPT_BOOLEAN('c', "scale", &scale,
846                     "scale/normalize counters"),
847         OPT_INCR('v', "verbose", &verbose,
848                     "be more verbose (show counter open errors, etc)"),
849         OPT_INTEGER('r', "repeat", &run_count,
850                     "repeat command and print average + stddev (max: 100)"),
851         OPT_BOOLEAN('n', "null", &null_run,
852                     "null run - dont start any counters"),
853         OPT_BOOLEAN('d', "detailed", &detailed_run,
854                     "detailed run - start a lot of events"),
855         OPT_BOOLEAN('S', "sync", &sync_run,
856                     "call sync() before starting a run"),
857         OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL, 
858                            "print large numbers with thousands\' separators",
859                            stat__set_big_num),
860         OPT_STRING('C', "cpu", &cpu_list, "cpu",
861                     "list of cpus to monitor in system-wide"),
862         OPT_BOOLEAN('A', "no-aggr", &no_aggr,
863                     "disable CPU count aggregation"),
864         OPT_STRING('x', "field-separator", &csv_sep, "separator",
865                    "print counts with custom separator"),
866         OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
867                      "monitor event in cgroup name only",
868                      parse_cgroups),
869         OPT_END()
870 };
871
872 int cmd_stat(int argc, const char **argv, const char *prefix __used)
873 {
874         struct perf_evsel *pos;
875         int status = -ENOMEM;
876
877         setlocale(LC_ALL, "");
878
879         evsel_list = perf_evlist__new(NULL, NULL);
880         if (evsel_list == NULL)
881                 return -ENOMEM;
882
883         argc = parse_options(argc, argv, options, stat_usage,
884                 PARSE_OPT_STOP_AT_NON_OPTION);
885
886         if (csv_sep)
887                 csv_output = true;
888         else
889                 csv_sep = DEFAULT_SEPARATOR;
890
891         /*
892          * let the spreadsheet do the pretty-printing
893          */
894         if (csv_output) {
895                 /* User explicitely passed -B? */
896                 if (big_num_opt == 1) {
897                         fprintf(stderr, "-B option not supported with -x\n");
898                         usage_with_options(stat_usage, options);
899                 } else /* Nope, so disable big number formatting */
900                         big_num = false;
901         } else if (big_num_opt == 0) /* User passed --no-big-num */
902                 big_num = false;
903
904         if (!argc && target_pid == -1 && target_tid == -1)
905                 usage_with_options(stat_usage, options);
906         if (run_count <= 0)
907                 usage_with_options(stat_usage, options);
908
909         /* no_aggr, cgroup are for system-wide only */
910         if ((no_aggr || nr_cgroups) && !system_wide) {
911                 fprintf(stderr, "both cgroup and no-aggregation "
912                         "modes only available in system-wide mode\n");
913
914                 usage_with_options(stat_usage, options);
915         }
916
917         /* Set attrs and nr_counters if no event is selected and !null_run */
918         if (detailed_run) {
919                 size_t c;
920
921                 for (c = 0; c < ARRAY_SIZE(detailed_attrs); ++c) {
922                         pos = perf_evsel__new(&detailed_attrs[c], c);
923                         if (pos == NULL)
924                                 goto out;
925                         perf_evlist__add(evsel_list, pos);
926                 }
927         }
928         /* Set attrs and nr_counters if no event is selected and !null_run */
929         if (!detailed_run && !null_run && !evsel_list->nr_entries) {
930                 size_t c;
931
932                 for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
933                         pos = perf_evsel__new(&default_attrs[c], c);
934                         if (pos == NULL)
935                                 goto out;
936                         perf_evlist__add(evsel_list, pos);
937                 }
938         }
939
940         if (target_pid != -1)
941                 target_tid = target_pid;
942
943         evsel_list->threads = thread_map__new(target_pid, target_tid);
944         if (evsel_list->threads == NULL) {
945                 pr_err("Problems finding threads of monitor\n");
946                 usage_with_options(stat_usage, options);
947         }
948
949         if (system_wide)
950                 evsel_list->cpus = cpu_map__new(cpu_list);
951         else
952                 evsel_list->cpus = cpu_map__dummy_new();
953
954         if (evsel_list->cpus == NULL) {
955                 perror("failed to parse CPUs map");
956                 usage_with_options(stat_usage, options);
957                 return -1;
958         }
959
960         list_for_each_entry(pos, &evsel_list->entries, node) {
961                 if (perf_evsel__alloc_stat_priv(pos) < 0 ||
962                     perf_evsel__alloc_counts(pos, evsel_list->cpus->nr) < 0 ||
963                     perf_evsel__alloc_fd(pos, evsel_list->cpus->nr, evsel_list->threads->nr) < 0)
964                         goto out_free_fd;
965         }
966
967         /*
968          * We dont want to block the signals - that would cause
969          * child tasks to inherit that and Ctrl-C would not work.
970          * What we want is for Ctrl-C to work in the exec()-ed
971          * task, but being ignored by perf stat itself:
972          */
973         atexit(sig_atexit);
974         signal(SIGINT,  skip_signal);
975         signal(SIGALRM, skip_signal);
976         signal(SIGABRT, skip_signal);
977
978         status = 0;
979         for (run_idx = 0; run_idx < run_count; run_idx++) {
980                 if (run_count != 1 && verbose)
981                         fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
982
983                 if (sync_run)
984                         sync();
985
986                 status = run_perf_stat(argc, argv);
987         }
988
989         if (status != -1)
990                 print_stat(argc, argv);
991 out_free_fd:
992         list_for_each_entry(pos, &evsel_list->entries, node)
993                 perf_evsel__free_stat_priv(pos);
994         perf_evlist__delete_maps(evsel_list);
995 out:
996         perf_evlist__delete(evsel_list);
997         return status;
998 }