perf stat: Add stalled cycles to the default output
[linux-flexiantxendom0-3.2.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/header.h"
50 #include "util/cpumap.h"
51 #include "util/thread.h"
52 #include "util/thread_map.h"
53
54 #include <sys/prctl.h>
55 #include <math.h>
56 #include <locale.h>
57
58 #define DEFAULT_SEPARATOR       " "
59
60 static struct perf_event_attr default_attrs[] = {
61
62   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK              },
63   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES        },
64   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS          },
65   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS             },
66
67   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES              },
68   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES          },
69   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS            },
70   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS     },
71   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES           },
72
73 };
74
75 struct perf_evlist              *evsel_list;
76
77 static bool                     system_wide                     =  false;
78 static int                      run_idx                         =  0;
79
80 static int                      run_count                       =  1;
81 static bool                     no_inherit                      = false;
82 static bool                     scale                           =  true;
83 static bool                     no_aggr                         = false;
84 static pid_t                    target_pid                      = -1;
85 static pid_t                    target_tid                      = -1;
86 static pid_t                    child_pid                       = -1;
87 static bool                     null_run                        =  false;
88 static bool                     big_num                         =  true;
89 static int                      big_num_opt                     =  -1;
90 static const char               *cpu_list;
91 static const char               *csv_sep                        = NULL;
92 static bool                     csv_output                      = false;
93
94 static volatile int done = 0;
95
96 struct stats
97 {
98         double n, mean, M2;
99 };
100
101 struct perf_stat {
102         struct stats      res_stats[3];
103 };
104
105 static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
106 {
107         evsel->priv = zalloc(sizeof(struct perf_stat));
108         return evsel->priv == NULL ? -ENOMEM : 0;
109 }
110
111 static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
112 {
113         free(evsel->priv);
114         evsel->priv = NULL;
115 }
116
117 static void update_stats(struct stats *stats, u64 val)
118 {
119         double delta;
120
121         stats->n++;
122         delta = val - stats->mean;
123         stats->mean += delta / stats->n;
124         stats->M2 += delta*(val - stats->mean);
125 }
126
127 static double avg_stats(struct stats *stats)
128 {
129         return stats->mean;
130 }
131
132 /*
133  * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
134  *
135  *       (\Sum n_i^2) - ((\Sum n_i)^2)/n
136  * s^2 = -------------------------------
137  *                  n - 1
138  *
139  * http://en.wikipedia.org/wiki/Stddev
140  *
141  * The std dev of the mean is related to the std dev by:
142  *
143  *             s
144  * s_mean = -------
145  *          sqrt(n)
146  *
147  */
148 static double stddev_stats(struct stats *stats)
149 {
150         double variance = stats->M2 / (stats->n - 1);
151         double variance_mean = variance / stats->n;
152
153         return sqrt(variance_mean);
154 }
155
156 struct stats                    runtime_nsecs_stats[MAX_NR_CPUS];
157 struct stats                    runtime_cycles_stats[MAX_NR_CPUS];
158 struct stats                    runtime_stalled_cycles_stats[MAX_NR_CPUS];
159 struct stats                    runtime_branches_stats[MAX_NR_CPUS];
160 struct stats                    runtime_cacherefs_stats[MAX_NR_CPUS];
161 struct stats                    walltime_nsecs_stats;
162
163 static int create_perf_stat_counter(struct perf_evsel *evsel)
164 {
165         struct perf_event_attr *attr = &evsel->attr;
166
167         if (scale)
168                 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
169                                     PERF_FORMAT_TOTAL_TIME_RUNNING;
170
171         attr->inherit = !no_inherit;
172
173         if (system_wide)
174                 return perf_evsel__open_per_cpu(evsel, evsel_list->cpus, false);
175
176         if (target_pid == -1 && target_tid == -1) {
177                 attr->disabled = 1;
178                 attr->enable_on_exec = 1;
179         }
180
181         return perf_evsel__open_per_thread(evsel, evsel_list->threads, false);
182 }
183
184 /*
185  * Does the counter have nsecs as a unit?
186  */
187 static inline int nsec_counter(struct perf_evsel *evsel)
188 {
189         if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
190             perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
191                 return 1;
192
193         return 0;
194 }
195
196 /*
197  * Update various tracking values we maintain to print
198  * more semantic information such as miss/hit ratios,
199  * instruction rates, etc:
200  */
201 static void update_shadow_stats(struct perf_evsel *counter, u64 *count)
202 {
203         if (perf_evsel__match(counter, SOFTWARE, SW_TASK_CLOCK))
204                 update_stats(&runtime_nsecs_stats[0], count[0]);
205         else if (perf_evsel__match(counter, HARDWARE, HW_CPU_CYCLES))
206                 update_stats(&runtime_cycles_stats[0], count[0]);
207         else if (perf_evsel__match(counter, HARDWARE, HW_STALLED_CYCLES))
208                 update_stats(&runtime_stalled_cycles_stats[0], count[0]);
209         else if (perf_evsel__match(counter, HARDWARE, HW_BRANCH_INSTRUCTIONS))
210                 update_stats(&runtime_branches_stats[0], count[0]);
211         else if (perf_evsel__match(counter, HARDWARE, HW_CACHE_REFERENCES))
212                 update_stats(&runtime_cacherefs_stats[0], count[0]);
213 }
214
215 /*
216  * Read out the results of a single counter:
217  * aggregate counts across CPUs in system-wide mode
218  */
219 static int read_counter_aggr(struct perf_evsel *counter)
220 {
221         struct perf_stat *ps = counter->priv;
222         u64 *count = counter->counts->aggr.values;
223         int i;
224
225         if (__perf_evsel__read(counter, evsel_list->cpus->nr,
226                                evsel_list->threads->nr, scale) < 0)
227                 return -1;
228
229         for (i = 0; i < 3; i++)
230                 update_stats(&ps->res_stats[i], count[i]);
231
232         if (verbose) {
233                 fprintf(stderr, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
234                         event_name(counter), count[0], count[1], count[2]);
235         }
236
237         /*
238          * Save the full runtime - to allow normalization during printout:
239          */
240         update_shadow_stats(counter, count);
241
242         return 0;
243 }
244
245 /*
246  * Read out the results of a single counter:
247  * do not aggregate counts across CPUs in system-wide mode
248  */
249 static int read_counter(struct perf_evsel *counter)
250 {
251         u64 *count;
252         int cpu;
253
254         for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
255                 if (__perf_evsel__read_on_cpu(counter, cpu, 0, scale) < 0)
256                         return -1;
257
258                 count = counter->counts->cpu[cpu].values;
259
260                 update_shadow_stats(counter, count);
261         }
262
263         return 0;
264 }
265
266 static int run_perf_stat(int argc __used, const char **argv)
267 {
268         unsigned long long t0, t1;
269         struct perf_evsel *counter;
270         int status = 0;
271         int child_ready_pipe[2], go_pipe[2];
272         const bool forks = (argc > 0);
273         char buf;
274
275         if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
276                 perror("failed to create pipes");
277                 exit(1);
278         }
279
280         if (forks) {
281                 if ((child_pid = fork()) < 0)
282                         perror("failed to fork");
283
284                 if (!child_pid) {
285                         close(child_ready_pipe[0]);
286                         close(go_pipe[1]);
287                         fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
288
289                         /*
290                          * Do a dummy execvp to get the PLT entry resolved,
291                          * so we avoid the resolver overhead on the real
292                          * execvp call.
293                          */
294                         execvp("", (char **)argv);
295
296                         /*
297                          * Tell the parent we're ready to go
298                          */
299                         close(child_ready_pipe[1]);
300
301                         /*
302                          * Wait until the parent tells us to go.
303                          */
304                         if (read(go_pipe[0], &buf, 1) == -1)
305                                 perror("unable to read pipe");
306
307                         execvp(argv[0], (char **)argv);
308
309                         perror(argv[0]);
310                         exit(-1);
311                 }
312
313                 if (target_tid == -1 && target_pid == -1 && !system_wide)
314                         evsel_list->threads->map[0] = child_pid;
315
316                 /*
317                  * Wait for the child to be ready to exec.
318                  */
319                 close(child_ready_pipe[1]);
320                 close(go_pipe[0]);
321                 if (read(child_ready_pipe[0], &buf, 1) == -1)
322                         perror("unable to read pipe");
323                 close(child_ready_pipe[0]);
324         }
325
326         list_for_each_entry(counter, &evsel_list->entries, node) {
327                 if (create_perf_stat_counter(counter) < 0) {
328                         if (errno == -EPERM || errno == -EACCES) {
329                                 error("You may not have permission to collect %sstats.\n"
330                                       "\t Consider tweaking"
331                                       " /proc/sys/kernel/perf_event_paranoid or running as root.",
332                                       system_wide ? "system-wide " : "");
333                         } else if (errno == ENOENT) {
334                                 error("%s event is not supported. ", event_name(counter));
335                         } else {
336                                 error("open_counter returned with %d (%s). "
337                                       "/bin/dmesg may provide additional information.\n",
338                                        errno, strerror(errno));
339                         }
340                         if (child_pid != -1)
341                                 kill(child_pid, SIGTERM);
342                         die("Not all events could be opened.\n");
343                         return -1;
344                 }
345         }
346
347         if (perf_evlist__set_filters(evsel_list)) {
348                 error("failed to set filter with %d (%s)\n", errno,
349                         strerror(errno));
350                 return -1;
351         }
352
353         /*
354          * Enable counters and exec the command:
355          */
356         t0 = rdclock();
357
358         if (forks) {
359                 close(go_pipe[1]);
360                 wait(&status);
361         } else {
362                 while(!done) sleep(1);
363         }
364
365         t1 = rdclock();
366
367         update_stats(&walltime_nsecs_stats, t1 - t0);
368
369         if (no_aggr) {
370                 list_for_each_entry(counter, &evsel_list->entries, node) {
371                         read_counter(counter);
372                         perf_evsel__close_fd(counter, evsel_list->cpus->nr, 1);
373                 }
374         } else {
375                 list_for_each_entry(counter, &evsel_list->entries, node) {
376                         read_counter_aggr(counter);
377                         perf_evsel__close_fd(counter, evsel_list->cpus->nr,
378                                              evsel_list->threads->nr);
379                 }
380         }
381
382         return WEXITSTATUS(status);
383 }
384
385 static void print_noise(struct perf_evsel *evsel, double avg)
386 {
387         struct perf_stat *ps;
388
389         if (run_count == 1)
390                 return;
391
392         ps = evsel->priv;
393         fprintf(stderr, "   ( +- %7.3f%% )",
394                         100 * stddev_stats(&ps->res_stats[0]) / avg);
395 }
396
397 static void nsec_printout(int cpu, struct perf_evsel *evsel, double avg)
398 {
399         double msecs = avg / 1e6;
400         char cpustr[16] = { '\0', };
401         const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
402
403         if (no_aggr)
404                 sprintf(cpustr, "CPU%*d%s",
405                         csv_output ? 0 : -4,
406                         evsel_list->cpus->map[cpu], csv_sep);
407
408         fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(evsel));
409
410         if (evsel->cgrp)
411                 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
412
413         if (csv_output)
414                 return;
415
416         if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
417                 fprintf(stderr, " # %8.3f CPUs utilized          ", avg / avg_stats(&walltime_nsecs_stats));
418 }
419
420 static void abs_printout(int cpu, struct perf_evsel *evsel, double avg)
421 {
422         double total, ratio = 0.0;
423         char cpustr[16] = { '\0', };
424         const char *fmt;
425
426         if (csv_output)
427                 fmt = "%s%.0f%s%s";
428         else if (big_num)
429                 fmt = "%s%'18.0f%s%-24s";
430         else
431                 fmt = "%s%18.0f%s%-24s";
432
433         if (no_aggr)
434                 sprintf(cpustr, "CPU%*d%s",
435                         csv_output ? 0 : -4,
436                         evsel_list->cpus->map[cpu], csv_sep);
437         else
438                 cpu = 0;
439
440         fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(evsel));
441
442         if (evsel->cgrp)
443                 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
444
445         if (csv_output)
446                 return;
447
448         if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
449                 total = avg_stats(&runtime_cycles_stats[cpu]);
450
451                 if (total)
452                         ratio = avg / total;
453
454                 fprintf(stderr, " #    %4.2f  insns per cycle", ratio);
455
456                 total = avg_stats(&runtime_stalled_cycles_stats[cpu]);
457
458                 if (total && avg) {
459                         ratio = total / avg;
460                         fprintf(stderr, "\n                                            #    %4.2f  stalled cycles per insn", ratio);
461                 }
462
463         } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
464                         runtime_branches_stats[cpu].n != 0) {
465                 total = avg_stats(&runtime_branches_stats[cpu]);
466
467                 if (total)
468                         ratio = avg * 100 / total;
469
470                 fprintf(stderr, " #   %5.2f  %% of all branches      ", ratio);
471
472         } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
473                         runtime_cacherefs_stats[cpu].n != 0) {
474                 total = avg_stats(&runtime_cacherefs_stats[cpu]);
475
476                 if (total)
477                         ratio = avg * 100 / total;
478
479                 fprintf(stderr, " # %8.3f %% of all cache refs    ", ratio);
480
481         } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES)) {
482                 total = avg_stats(&runtime_cycles_stats[cpu]);
483
484                 if (total)
485                         ratio = avg / total * 100.0;
486
487                 fprintf(stderr, " #   %5.2f%% of all cycles are idle ", ratio);
488         } else if (perf_evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
489                 total = avg_stats(&runtime_nsecs_stats[cpu]);
490
491                 if (total)
492                         ratio = 1.0 * avg / total;
493
494                 fprintf(stderr, " # %8.3f GHz                    ", ratio);
495         } else if (runtime_nsecs_stats[cpu].n != 0) {
496                 total = avg_stats(&runtime_nsecs_stats[cpu]);
497
498                 if (total)
499                         ratio = 1000.0 * avg / total;
500
501                 fprintf(stderr, " # %8.3f M/sec                  ", ratio);
502         }
503 }
504
505 /*
506  * Print out the results of a single counter:
507  * aggregated counts in system-wide mode
508  */
509 static void print_counter_aggr(struct perf_evsel *counter)
510 {
511         struct perf_stat *ps = counter->priv;
512         double avg = avg_stats(&ps->res_stats[0]);
513         int scaled = counter->counts->scaled;
514
515         if (scaled == -1) {
516                 fprintf(stderr, "%*s%s%*s",
517                         csv_output ? 0 : 18,
518                         "<not counted>",
519                         csv_sep,
520                         csv_output ? 0 : -24,
521                         event_name(counter));
522
523                 if (counter->cgrp)
524                         fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
525
526                 fputc('\n', stderr);
527                 return;
528         }
529
530         if (nsec_counter(counter))
531                 nsec_printout(-1, counter, avg);
532         else
533                 abs_printout(-1, counter, avg);
534
535         if (csv_output) {
536                 fputc('\n', stderr);
537                 return;
538         }
539
540         print_noise(counter, avg);
541
542         if (scaled) {
543                 double avg_enabled, avg_running;
544
545                 avg_enabled = avg_stats(&ps->res_stats[1]);
546                 avg_running = avg_stats(&ps->res_stats[2]);
547
548                 fprintf(stderr, "  (scaled from %.2f%%)",
549                                 100 * avg_running / avg_enabled);
550         }
551         fprintf(stderr, "\n");
552 }
553
554 /*
555  * Print out the results of a single counter:
556  * does not use aggregated count in system-wide
557  */
558 static void print_counter(struct perf_evsel *counter)
559 {
560         u64 ena, run, val;
561         int cpu;
562
563         for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
564                 val = counter->counts->cpu[cpu].val;
565                 ena = counter->counts->cpu[cpu].ena;
566                 run = counter->counts->cpu[cpu].run;
567                 if (run == 0 || ena == 0) {
568                         fprintf(stderr, "CPU%*d%s%*s%s%*s",
569                                 csv_output ? 0 : -4,
570                                 evsel_list->cpus->map[cpu], csv_sep,
571                                 csv_output ? 0 : 18,
572                                 "<not counted>", csv_sep,
573                                 csv_output ? 0 : -24,
574                                 event_name(counter));
575
576                         if (counter->cgrp)
577                                 fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
578
579                         fputc('\n', stderr);
580                         continue;
581                 }
582
583                 if (nsec_counter(counter))
584                         nsec_printout(cpu, counter, val);
585                 else
586                         abs_printout(cpu, counter, val);
587
588                 if (!csv_output) {
589                         print_noise(counter, 1.0);
590
591                         if (run != ena) {
592                                 fprintf(stderr, "  (scaled from %.2f%%)",
593                                         100.0 * run / ena);
594                         }
595                 }
596                 fputc('\n', stderr);
597         }
598 }
599
600 static void print_stat(int argc, const char **argv)
601 {
602         struct perf_evsel *counter;
603         int i;
604
605         fflush(stdout);
606
607         if (!csv_output) {
608                 fprintf(stderr, "\n");
609                 fprintf(stderr, " Performance counter stats for ");
610                 if(target_pid == -1 && target_tid == -1) {
611                         fprintf(stderr, "\'%s", argv[0]);
612                         for (i = 1; i < argc; i++)
613                                 fprintf(stderr, " %s", argv[i]);
614                 } else if (target_pid != -1)
615                         fprintf(stderr, "process id \'%d", target_pid);
616                 else
617                         fprintf(stderr, "thread id \'%d", target_tid);
618
619                 fprintf(stderr, "\'");
620                 if (run_count > 1)
621                         fprintf(stderr, " (%d runs)", run_count);
622                 fprintf(stderr, ":\n\n");
623         }
624
625         if (no_aggr) {
626                 list_for_each_entry(counter, &evsel_list->entries, node)
627                         print_counter(counter);
628         } else {
629                 list_for_each_entry(counter, &evsel_list->entries, node)
630                         print_counter_aggr(counter);
631         }
632
633         if (!csv_output) {
634                 fprintf(stderr, "\n");
635                 fprintf(stderr, " %18.9f  seconds time elapsed",
636                                 avg_stats(&walltime_nsecs_stats)/1e9);
637                 if (run_count > 1) {
638                         fprintf(stderr, "   ( +-%5.2f%% )",
639                                 100*stddev_stats(&walltime_nsecs_stats) /
640                                 avg_stats(&walltime_nsecs_stats));
641                 }
642                 fprintf(stderr, "\n\n");
643         }
644 }
645
646 static volatile int signr = -1;
647
648 static void skip_signal(int signo)
649 {
650         if(child_pid == -1)
651                 done = 1;
652
653         signr = signo;
654 }
655
656 static void sig_atexit(void)
657 {
658         if (child_pid != -1)
659                 kill(child_pid, SIGTERM);
660
661         if (signr == -1)
662                 return;
663
664         signal(signr, SIG_DFL);
665         kill(getpid(), signr);
666 }
667
668 static const char * const stat_usage[] = {
669         "perf stat [<options>] [<command>]",
670         NULL
671 };
672
673 static int stat__set_big_num(const struct option *opt __used,
674                              const char *s __used, int unset)
675 {
676         big_num_opt = unset ? 0 : 1;
677         return 0;
678 }
679
680 static const struct option options[] = {
681         OPT_CALLBACK('e', "event", &evsel_list, "event",
682                      "event selector. use 'perf list' to list available events",
683                      parse_events),
684         OPT_CALLBACK(0, "filter", &evsel_list, "filter",
685                      "event filter", parse_filter),
686         OPT_BOOLEAN('i', "no-inherit", &no_inherit,
687                     "child tasks do not inherit counters"),
688         OPT_INTEGER('p', "pid", &target_pid,
689                     "stat events on existing process id"),
690         OPT_INTEGER('t', "tid", &target_tid,
691                     "stat events on existing thread id"),
692         OPT_BOOLEAN('a', "all-cpus", &system_wide,
693                     "system-wide collection from all CPUs"),
694         OPT_BOOLEAN('c', "scale", &scale,
695                     "scale/normalize counters"),
696         OPT_INCR('v', "verbose", &verbose,
697                     "be more verbose (show counter open errors, etc)"),
698         OPT_INTEGER('r', "repeat", &run_count,
699                     "repeat command and print average + stddev (max: 100)"),
700         OPT_BOOLEAN('n', "null", &null_run,
701                     "null run - dont start any counters"),
702         OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL, 
703                            "print large numbers with thousands\' separators",
704                            stat__set_big_num),
705         OPT_STRING('C', "cpu", &cpu_list, "cpu",
706                     "list of cpus to monitor in system-wide"),
707         OPT_BOOLEAN('A', "no-aggr", &no_aggr,
708                     "disable CPU count aggregation"),
709         OPT_STRING('x', "field-separator", &csv_sep, "separator",
710                    "print counts with custom separator"),
711         OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
712                      "monitor event in cgroup name only",
713                      parse_cgroups),
714         OPT_END()
715 };
716
717 int cmd_stat(int argc, const char **argv, const char *prefix __used)
718 {
719         struct perf_evsel *pos;
720         int status = -ENOMEM;
721
722         setlocale(LC_ALL, "");
723
724         evsel_list = perf_evlist__new(NULL, NULL);
725         if (evsel_list == NULL)
726                 return -ENOMEM;
727
728         argc = parse_options(argc, argv, options, stat_usage,
729                 PARSE_OPT_STOP_AT_NON_OPTION);
730
731         if (csv_sep)
732                 csv_output = true;
733         else
734                 csv_sep = DEFAULT_SEPARATOR;
735
736         /*
737          * let the spreadsheet do the pretty-printing
738          */
739         if (csv_output) {
740                 /* User explicitely passed -B? */
741                 if (big_num_opt == 1) {
742                         fprintf(stderr, "-B option not supported with -x\n");
743                         usage_with_options(stat_usage, options);
744                 } else /* Nope, so disable big number formatting */
745                         big_num = false;
746         } else if (big_num_opt == 0) /* User passed --no-big-num */
747                 big_num = false;
748
749         if (!argc && target_pid == -1 && target_tid == -1)
750                 usage_with_options(stat_usage, options);
751         if (run_count <= 0)
752                 usage_with_options(stat_usage, options);
753
754         /* no_aggr, cgroup are for system-wide only */
755         if ((no_aggr || nr_cgroups) && !system_wide) {
756                 fprintf(stderr, "both cgroup and no-aggregation "
757                         "modes only available in system-wide mode\n");
758
759                 usage_with_options(stat_usage, options);
760         }
761
762         /* Set attrs and nr_counters if no event is selected and !null_run */
763         if (!null_run && !evsel_list->nr_entries) {
764                 size_t c;
765
766                 for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
767                         pos = perf_evsel__new(&default_attrs[c], c);
768                         if (pos == NULL)
769                                 goto out;
770                         perf_evlist__add(evsel_list, pos);
771                 }
772         }
773
774         if (target_pid != -1)
775                 target_tid = target_pid;
776
777         evsel_list->threads = thread_map__new(target_pid, target_tid);
778         if (evsel_list->threads == NULL) {
779                 pr_err("Problems finding threads of monitor\n");
780                 usage_with_options(stat_usage, options);
781         }
782
783         if (system_wide)
784                 evsel_list->cpus = cpu_map__new(cpu_list);
785         else
786                 evsel_list->cpus = cpu_map__dummy_new();
787
788         if (evsel_list->cpus == NULL) {
789                 perror("failed to parse CPUs map");
790                 usage_with_options(stat_usage, options);
791                 return -1;
792         }
793
794         list_for_each_entry(pos, &evsel_list->entries, node) {
795                 if (perf_evsel__alloc_stat_priv(pos) < 0 ||
796                     perf_evsel__alloc_counts(pos, evsel_list->cpus->nr) < 0 ||
797                     perf_evsel__alloc_fd(pos, evsel_list->cpus->nr, evsel_list->threads->nr) < 0)
798                         goto out_free_fd;
799         }
800
801         /*
802          * We dont want to block the signals - that would cause
803          * child tasks to inherit that and Ctrl-C would not work.
804          * What we want is for Ctrl-C to work in the exec()-ed
805          * task, but being ignored by perf stat itself:
806          */
807         atexit(sig_atexit);
808         signal(SIGINT,  skip_signal);
809         signal(SIGALRM, skip_signal);
810         signal(SIGABRT, skip_signal);
811
812         status = 0;
813         for (run_idx = 0; run_idx < run_count; run_idx++) {
814                 if (run_count != 1 && verbose)
815                         fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
816                 status = run_perf_stat(argc, argv);
817         }
818
819         if (status != -1)
820                 print_stat(argc, argv);
821 out_free_fd:
822         list_for_each_entry(pos, &evsel_list->entries, node)
823                 perf_evsel__free_stat_priv(pos);
824         perf_evlist__delete_maps(evsel_list);
825 out:
826         perf_evlist__delete(evsel_list);
827         return status;
828 }