perf stat: Leave more room for percentages
[linux-2.6.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)
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 if (errno == ENOENT) {
389                                 error("%s event is not supported. ", event_name(counter));
390                         } else {
391                                 error("open_counter returned with %d (%s). "
392                                       "/bin/dmesg may provide additional information.\n",
393                                        errno, strerror(errno));
394                         }
395                         if (child_pid != -1)
396                                 kill(child_pid, SIGTERM);
397                         die("Not all events could be opened.\n");
398                         return -1;
399                 }
400         }
401
402         if (perf_evlist__set_filters(evsel_list)) {
403                 error("failed to set filter with %d (%s)\n", errno,
404                         strerror(errno));
405                 return -1;
406         }
407
408         /*
409          * Enable counters and exec the command:
410          */
411         t0 = rdclock();
412
413         if (forks) {
414                 close(go_pipe[1]);
415                 wait(&status);
416         } else {
417                 while(!done) sleep(1);
418         }
419
420         t1 = rdclock();
421
422         update_stats(&walltime_nsecs_stats, t1 - t0);
423
424         if (no_aggr) {
425                 list_for_each_entry(counter, &evsel_list->entries, node) {
426                         read_counter(counter);
427                         perf_evsel__close_fd(counter, evsel_list->cpus->nr, 1);
428                 }
429         } else {
430                 list_for_each_entry(counter, &evsel_list->entries, node) {
431                         read_counter_aggr(counter);
432                         perf_evsel__close_fd(counter, evsel_list->cpus->nr,
433                                              evsel_list->threads->nr);
434                 }
435         }
436
437         return WEXITSTATUS(status);
438 }
439
440 static void print_noise_pct(double total, double avg)
441 {
442         double pct = 0.0;
443
444         if (avg)
445                 pct = 100.0*total/avg;
446
447         fprintf(stderr, "  ( +-%6.2f%% )", pct);
448 }
449
450 static void print_noise(struct perf_evsel *evsel, double avg)
451 {
452         struct perf_stat *ps;
453
454         if (run_count == 1)
455                 return;
456
457         ps = evsel->priv;
458         print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
459 }
460
461 static void nsec_printout(int cpu, struct perf_evsel *evsel, double avg)
462 {
463         double msecs = avg / 1e6;
464         char cpustr[16] = { '\0', };
465         const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
466
467         if (no_aggr)
468                 sprintf(cpustr, "CPU%*d%s",
469                         csv_output ? 0 : -4,
470                         evsel_list->cpus->map[cpu], csv_sep);
471
472         fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(evsel));
473
474         if (evsel->cgrp)
475                 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
476
477         if (csv_output)
478                 return;
479
480         if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
481                 fprintf(stderr, " # %8.3f CPUs utilized          ", avg / avg_stats(&walltime_nsecs_stats));
482 }
483
484 static void print_stalled_cycles_frontend(int cpu, struct perf_evsel *evsel __used, double avg)
485 {
486         double total, ratio = 0.0;
487         const char *color;
488
489         total = avg_stats(&runtime_cycles_stats[cpu]);
490
491         if (total)
492                 ratio = avg / total * 100.0;
493
494         color = PERF_COLOR_NORMAL;
495         if (ratio > 50.0)
496                 color = PERF_COLOR_RED;
497         else if (ratio > 30.0)
498                 color = PERF_COLOR_MAGENTA;
499         else if (ratio > 10.0)
500                 color = PERF_COLOR_YELLOW;
501
502         fprintf(stderr, " #  ");
503         color_fprintf(stderr, color, "%6.2f%%", ratio);
504         fprintf(stderr, " frontend cycles idle   ");
505 }
506
507 static void print_stalled_cycles_backend(int cpu, struct perf_evsel *evsel __used, double avg)
508 {
509         double total, ratio = 0.0;
510         const char *color;
511
512         total = avg_stats(&runtime_cycles_stats[cpu]);
513
514         if (total)
515                 ratio = avg / total * 100.0;
516
517         color = PERF_COLOR_NORMAL;
518         if (ratio > 75.0)
519                 color = PERF_COLOR_RED;
520         else if (ratio > 50.0)
521                 color = PERF_COLOR_MAGENTA;
522         else if (ratio > 20.0)
523                 color = PERF_COLOR_YELLOW;
524
525         fprintf(stderr, " #  ");
526         color_fprintf(stderr, color, "%6.2f%%", ratio);
527         fprintf(stderr, " backend  cycles idle   ");
528 }
529
530 static void print_branch_misses(int cpu, struct perf_evsel *evsel __used, double avg)
531 {
532         double total, ratio = 0.0;
533         const char *color;
534
535         total = avg_stats(&runtime_branches_stats[cpu]);
536
537         if (total)
538                 ratio = avg / total * 100.0;
539
540         color = PERF_COLOR_NORMAL;
541         if (ratio > 20.0)
542                 color = PERF_COLOR_RED;
543         else if (ratio > 10.0)
544                 color = PERF_COLOR_MAGENTA;
545         else if (ratio > 5.0)
546                 color = PERF_COLOR_YELLOW;
547
548         fprintf(stderr, " #  ");
549         color_fprintf(stderr, color, "%6.2f%%", ratio);
550         fprintf(stderr, " of all branches        ");
551 }
552
553 static void print_l1_dcache_misses(int cpu, struct perf_evsel *evsel __used, double avg)
554 {
555         double total, ratio = 0.0;
556         const char *color;
557
558         total = avg_stats(&runtime_l1_dcache_stats[cpu]);
559
560         if (total)
561                 ratio = avg / total * 100.0;
562
563         color = PERF_COLOR_NORMAL;
564         if (ratio > 20.0)
565                 color = PERF_COLOR_RED;
566         else if (ratio > 10.0)
567                 color = PERF_COLOR_MAGENTA;
568         else if (ratio > 5.0)
569                 color = PERF_COLOR_YELLOW;
570
571         fprintf(stderr, " #  ");
572         color_fprintf(stderr, color, "%6.2f%%", ratio);
573         fprintf(stderr, " of all L1-dcache hits  ");
574 }
575
576 static void abs_printout(int cpu, struct perf_evsel *evsel, double avg)
577 {
578         double total, ratio = 0.0;
579         char cpustr[16] = { '\0', };
580         const char *fmt;
581
582         if (csv_output)
583                 fmt = "%s%.0f%s%s";
584         else if (big_num)
585                 fmt = "%s%'18.0f%s%-24s";
586         else
587                 fmt = "%s%18.0f%s%-24s";
588
589         if (no_aggr)
590                 sprintf(cpustr, "CPU%*d%s",
591                         csv_output ? 0 : -4,
592                         evsel_list->cpus->map[cpu], csv_sep);
593         else
594                 cpu = 0;
595
596         fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(evsel));
597
598         if (evsel->cgrp)
599                 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
600
601         if (csv_output)
602                 return;
603
604         if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
605                 total = avg_stats(&runtime_cycles_stats[cpu]);
606
607                 if (total)
608                         ratio = avg / total;
609
610                 fprintf(stderr, " #   %5.2f  insns per cycle        ", ratio);
611
612                 total = avg_stats(&runtime_stalled_cycles_front_stats[cpu]);
613                 total = max(total, avg_stats(&runtime_stalled_cycles_back_stats[cpu]));
614
615                 if (total && avg) {
616                         ratio = total / avg;
617                         fprintf(stderr, "\n                                            #   %5.2f  stalled cycles per insn", ratio);
618                 }
619
620         } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
621                         runtime_branches_stats[cpu].n != 0) {
622                 print_branch_misses(cpu, evsel, avg);
623         } else if (
624                 evsel->attr.type == PERF_TYPE_HW_CACHE &&
625                 evsel->attr.config ==  ( PERF_COUNT_HW_CACHE_L1D |
626                                         ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
627                                         ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
628                         runtime_l1_dcache_stats[cpu].n != 0) {
629                 print_l1_dcache_misses(cpu, evsel, avg);
630         } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
631                         runtime_cacherefs_stats[cpu].n != 0) {
632                 total = avg_stats(&runtime_cacherefs_stats[cpu]);
633
634                 if (total)
635                         ratio = avg * 100 / total;
636
637                 fprintf(stderr, " # %8.3f %% of all cache refs    ", ratio);
638
639         } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES_FRONTEND)) {
640                 print_stalled_cycles_frontend(cpu, evsel, avg);
641         } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES_BACKEND)) {
642                 print_stalled_cycles_backend(cpu, evsel, avg);
643         } else if (perf_evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
644                 total = avg_stats(&runtime_nsecs_stats[cpu]);
645
646                 if (total)
647                         ratio = 1.0 * avg / total;
648
649                 fprintf(stderr, " # %8.3f GHz                    ", ratio);
650         } else if (runtime_nsecs_stats[cpu].n != 0) {
651                 total = avg_stats(&runtime_nsecs_stats[cpu]);
652
653                 if (total)
654                         ratio = 1000.0 * avg / total;
655
656                 fprintf(stderr, " # %8.3f M/sec                  ", ratio);
657         } else {
658                 fprintf(stderr, "                                   ");
659         }
660 }
661
662 /*
663  * Print out the results of a single counter:
664  * aggregated counts in system-wide mode
665  */
666 static void print_counter_aggr(struct perf_evsel *counter)
667 {
668         struct perf_stat *ps = counter->priv;
669         double avg = avg_stats(&ps->res_stats[0]);
670         int scaled = counter->counts->scaled;
671
672         if (scaled == -1) {
673                 fprintf(stderr, "%*s%s%*s",
674                         csv_output ? 0 : 18,
675                         "<not counted>",
676                         csv_sep,
677                         csv_output ? 0 : -24,
678                         event_name(counter));
679
680                 if (counter->cgrp)
681                         fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
682
683                 fputc('\n', stderr);
684                 return;
685         }
686
687         if (nsec_counter(counter))
688                 nsec_printout(-1, counter, avg);
689         else
690                 abs_printout(-1, counter, avg);
691
692         if (csv_output) {
693                 fputc('\n', stderr);
694                 return;
695         }
696
697         print_noise(counter, avg);
698
699         if (scaled) {
700                 double avg_enabled, avg_running;
701
702                 avg_enabled = avg_stats(&ps->res_stats[1]);
703                 avg_running = avg_stats(&ps->res_stats[2]);
704
705                 fprintf(stderr, "  (%.2f%%)", 100 * avg_running / avg_enabled);
706         }
707         fprintf(stderr, "\n");
708 }
709
710 /*
711  * Print out the results of a single counter:
712  * does not use aggregated count in system-wide
713  */
714 static void print_counter(struct perf_evsel *counter)
715 {
716         u64 ena, run, val;
717         int cpu;
718
719         for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
720                 val = counter->counts->cpu[cpu].val;
721                 ena = counter->counts->cpu[cpu].ena;
722                 run = counter->counts->cpu[cpu].run;
723                 if (run == 0 || ena == 0) {
724                         fprintf(stderr, "CPU%*d%s%*s%s%*s",
725                                 csv_output ? 0 : -4,
726                                 evsel_list->cpus->map[cpu], csv_sep,
727                                 csv_output ? 0 : 18,
728                                 "<not counted>", csv_sep,
729                                 csv_output ? 0 : -24,
730                                 event_name(counter));
731
732                         if (counter->cgrp)
733                                 fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
734
735                         fputc('\n', stderr);
736                         continue;
737                 }
738
739                 if (nsec_counter(counter))
740                         nsec_printout(cpu, counter, val);
741                 else
742                         abs_printout(cpu, counter, val);
743
744                 if (!csv_output) {
745                         print_noise(counter, 1.0);
746
747                         if (run != ena)
748                                 fprintf(stderr, "  (%.2f%%)", 100.0 * run / ena);
749                 }
750                 fputc('\n', stderr);
751         }
752 }
753
754 static void print_stat(int argc, const char **argv)
755 {
756         struct perf_evsel *counter;
757         int i;
758
759         fflush(stdout);
760
761         if (!csv_output) {
762                 fprintf(stderr, "\n");
763                 fprintf(stderr, " Performance counter stats for ");
764                 if(target_pid == -1 && target_tid == -1) {
765                         fprintf(stderr, "\'%s", argv[0]);
766                         for (i = 1; i < argc; i++)
767                                 fprintf(stderr, " %s", argv[i]);
768                 } else if (target_pid != -1)
769                         fprintf(stderr, "process id \'%d", target_pid);
770                 else
771                         fprintf(stderr, "thread id \'%d", target_tid);
772
773                 fprintf(stderr, "\'");
774                 if (run_count > 1)
775                         fprintf(stderr, " (%d runs)", run_count);
776                 fprintf(stderr, ":\n\n");
777         }
778
779         if (no_aggr) {
780                 list_for_each_entry(counter, &evsel_list->entries, node)
781                         print_counter(counter);
782         } else {
783                 list_for_each_entry(counter, &evsel_list->entries, node)
784                         print_counter_aggr(counter);
785         }
786
787         if (!csv_output) {
788                 fprintf(stderr, "\n");
789                 fprintf(stderr, " %18.9f  seconds time elapsed",
790                                 avg_stats(&walltime_nsecs_stats)/1e9);
791                 if (run_count > 1) {
792                         print_noise_pct(stddev_stats(&walltime_nsecs_stats),
793                                         avg_stats(&walltime_nsecs_stats));
794                 }
795                 fprintf(stderr, "\n\n");
796         }
797 }
798
799 static volatile int signr = -1;
800
801 static void skip_signal(int signo)
802 {
803         if(child_pid == -1)
804                 done = 1;
805
806         signr = signo;
807 }
808
809 static void sig_atexit(void)
810 {
811         if (child_pid != -1)
812                 kill(child_pid, SIGTERM);
813
814         if (signr == -1)
815                 return;
816
817         signal(signr, SIG_DFL);
818         kill(getpid(), signr);
819 }
820
821 static const char * const stat_usage[] = {
822         "perf stat [<options>] [<command>]",
823         NULL
824 };
825
826 static int stat__set_big_num(const struct option *opt __used,
827                              const char *s __used, int unset)
828 {
829         big_num_opt = unset ? 0 : 1;
830         return 0;
831 }
832
833 static const struct option options[] = {
834         OPT_CALLBACK('e', "event", &evsel_list, "event",
835                      "event selector. use 'perf list' to list available events",
836                      parse_events),
837         OPT_CALLBACK(0, "filter", &evsel_list, "filter",
838                      "event filter", parse_filter),
839         OPT_BOOLEAN('i', "no-inherit", &no_inherit,
840                     "child tasks do not inherit counters"),
841         OPT_INTEGER('p', "pid", &target_pid,
842                     "stat events on existing process id"),
843         OPT_INTEGER('t', "tid", &target_tid,
844                     "stat events on existing thread id"),
845         OPT_BOOLEAN('a', "all-cpus", &system_wide,
846                     "system-wide collection from all CPUs"),
847         OPT_BOOLEAN('c', "scale", &scale,
848                     "scale/normalize counters"),
849         OPT_INCR('v', "verbose", &verbose,
850                     "be more verbose (show counter open errors, etc)"),
851         OPT_INTEGER('r', "repeat", &run_count,
852                     "repeat command and print average + stddev (max: 100)"),
853         OPT_BOOLEAN('n', "null", &null_run,
854                     "null run - dont start any counters"),
855         OPT_BOOLEAN('d', "detailed", &detailed_run,
856                     "detailed run - start a lot of events"),
857         OPT_BOOLEAN('S', "sync", &sync_run,
858                     "call sync() before starting a run"),
859         OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL, 
860                            "print large numbers with thousands\' separators",
861                            stat__set_big_num),
862         OPT_STRING('C', "cpu", &cpu_list, "cpu",
863                     "list of cpus to monitor in system-wide"),
864         OPT_BOOLEAN('A', "no-aggr", &no_aggr,
865                     "disable CPU count aggregation"),
866         OPT_STRING('x', "field-separator", &csv_sep, "separator",
867                    "print counts with custom separator"),
868         OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
869                      "monitor event in cgroup name only",
870                      parse_cgroups),
871         OPT_END()
872 };
873
874 int cmd_stat(int argc, const char **argv, const char *prefix __used)
875 {
876         struct perf_evsel *pos;
877         int status = -ENOMEM;
878
879         setlocale(LC_ALL, "");
880
881         evsel_list = perf_evlist__new(NULL, NULL);
882         if (evsel_list == NULL)
883                 return -ENOMEM;
884
885         argc = parse_options(argc, argv, options, stat_usage,
886                 PARSE_OPT_STOP_AT_NON_OPTION);
887
888         if (csv_sep)
889                 csv_output = true;
890         else
891                 csv_sep = DEFAULT_SEPARATOR;
892
893         /*
894          * let the spreadsheet do the pretty-printing
895          */
896         if (csv_output) {
897                 /* User explicitely passed -B? */
898                 if (big_num_opt == 1) {
899                         fprintf(stderr, "-B option not supported with -x\n");
900                         usage_with_options(stat_usage, options);
901                 } else /* Nope, so disable big number formatting */
902                         big_num = false;
903         } else if (big_num_opt == 0) /* User passed --no-big-num */
904                 big_num = false;
905
906         if (!argc && target_pid == -1 && target_tid == -1)
907                 usage_with_options(stat_usage, options);
908         if (run_count <= 0)
909                 usage_with_options(stat_usage, options);
910
911         /* no_aggr, cgroup are for system-wide only */
912         if ((no_aggr || nr_cgroups) && !system_wide) {
913                 fprintf(stderr, "both cgroup and no-aggregation "
914                         "modes only available in system-wide mode\n");
915
916                 usage_with_options(stat_usage, options);
917         }
918
919         /* Set attrs and nr_counters if no event is selected and !null_run */
920         if (detailed_run) {
921                 size_t c;
922
923                 for (c = 0; c < ARRAY_SIZE(detailed_attrs); ++c) {
924                         pos = perf_evsel__new(&detailed_attrs[c], c);
925                         if (pos == NULL)
926                                 goto out;
927                         perf_evlist__add(evsel_list, pos);
928                 }
929         }
930         /* Set attrs and nr_counters if no event is selected and !null_run */
931         if (!detailed_run && !null_run && !evsel_list->nr_entries) {
932                 size_t c;
933
934                 for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
935                         pos = perf_evsel__new(&default_attrs[c], c);
936                         if (pos == NULL)
937                                 goto out;
938                         perf_evlist__add(evsel_list, pos);
939                 }
940         }
941
942         if (target_pid != -1)
943                 target_tid = target_pid;
944
945         evsel_list->threads = thread_map__new(target_pid, target_tid);
946         if (evsel_list->threads == NULL) {
947                 pr_err("Problems finding threads of monitor\n");
948                 usage_with_options(stat_usage, options);
949         }
950
951         if (system_wide)
952                 evsel_list->cpus = cpu_map__new(cpu_list);
953         else
954                 evsel_list->cpus = cpu_map__dummy_new();
955
956         if (evsel_list->cpus == NULL) {
957                 perror("failed to parse CPUs map");
958                 usage_with_options(stat_usage, options);
959                 return -1;
960         }
961
962         list_for_each_entry(pos, &evsel_list->entries, node) {
963                 if (perf_evsel__alloc_stat_priv(pos) < 0 ||
964                     perf_evsel__alloc_counts(pos, evsel_list->cpus->nr) < 0 ||
965                     perf_evsel__alloc_fd(pos, evsel_list->cpus->nr, evsel_list->threads->nr) < 0)
966                         goto out_free_fd;
967         }
968
969         /*
970          * We dont want to block the signals - that would cause
971          * child tasks to inherit that and Ctrl-C would not work.
972          * What we want is for Ctrl-C to work in the exec()-ed
973          * task, but being ignored by perf stat itself:
974          */
975         atexit(sig_atexit);
976         signal(SIGINT,  skip_signal);
977         signal(SIGALRM, skip_signal);
978         signal(SIGABRT, skip_signal);
979
980         status = 0;
981         for (run_idx = 0; run_idx < run_count; run_idx++) {
982                 if (run_count != 1 && verbose)
983                         fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
984
985                 if (sync_run)
986                         sync();
987
988                 status = run_perf_stat(argc, argv);
989         }
990
991         if (status != -1)
992                 print_stat(argc, argv);
993 out_free_fd:
994         list_for_each_entry(pos, &evsel_list->entries, node)
995                 perf_evsel__free_stat_priv(pos);
996         perf_evlist__delete_maps(evsel_list);
997 out:
998         perf_evlist__delete(evsel_list);
999         return status;
1000 }