perf stat: Introduce perf_counts function
[cascardo/linux.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
11   Time: 0.118
12
13   Performance counter stats for './hackbench 10':
14
15        1708.761321 task-clock                #   11.037 CPUs utilized
16             41,190 context-switches          #    0.024 M/sec
17              6,735 CPU-migrations            #    0.004 M/sec
18             17,318 page-faults               #    0.010 M/sec
19      5,205,202,243 cycles                    #    3.046 GHz
20      3,856,436,920 stalled-cycles-frontend   #   74.09% frontend cycles idle
21      1,600,790,871 stalled-cycles-backend    #   30.75% backend  cycles idle
22      2,603,501,247 instructions              #    0.50  insns per cycle
23                                              #    1.48  stalled cycles per insn
24        484,357,498 branches                  #  283.455 M/sec
25          6,388,934 branch-misses             #    1.32% of all branches
26
27         0.154822978  seconds time elapsed
28
29  *
30  * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
31  *
32  * Improvements and fixes by:
33  *
34  *   Arjan van de Ven <arjan@linux.intel.com>
35  *   Yanmin Zhang <yanmin.zhang@intel.com>
36  *   Wu Fengguang <fengguang.wu@intel.com>
37  *   Mike Galbraith <efault@gmx.de>
38  *   Paul Mackerras <paulus@samba.org>
39  *   Jaswinder Singh Rajput <jaswinder@kernel.org>
40  *
41  * Released under the GPL v2. (and only v2, not any later version)
42  */
43
44 #include "perf.h"
45 #include "builtin.h"
46 #include "util/cgroup.h"
47 #include "util/util.h"
48 #include "util/parse-options.h"
49 #include "util/parse-events.h"
50 #include "util/pmu.h"
51 #include "util/event.h"
52 #include "util/evlist.h"
53 #include "util/evsel.h"
54 #include "util/debug.h"
55 #include "util/color.h"
56 #include "util/stat.h"
57 #include "util/header.h"
58 #include "util/cpumap.h"
59 #include "util/thread.h"
60 #include "util/thread_map.h"
61
62 #include <stdlib.h>
63 #include <sys/prctl.h>
64 #include <locale.h>
65
66 #define DEFAULT_SEPARATOR       " "
67 #define CNTR_NOT_SUPPORTED      "<not supported>"
68 #define CNTR_NOT_COUNTED        "<not counted>"
69
70 static void print_stat(int argc, const char **argv);
71 static void print_counter_aggr(struct perf_evsel *counter, char *prefix);
72 static void print_counter(struct perf_evsel *counter, char *prefix);
73 static void print_aggr(char *prefix);
74
75 /* Default events used for perf stat -T */
76 static const char *transaction_attrs = {
77         "task-clock,"
78         "{"
79         "instructions,"
80         "cycles,"
81         "cpu/cycles-t/,"
82         "cpu/tx-start/,"
83         "cpu/el-start/,"
84         "cpu/cycles-ct/"
85         "}"
86 };
87
88 /* More limited version when the CPU does not have all events. */
89 static const char * transaction_limited_attrs = {
90         "task-clock,"
91         "{"
92         "instructions,"
93         "cycles,"
94         "cpu/cycles-t/,"
95         "cpu/tx-start/"
96         "}"
97 };
98
99 static struct perf_evlist       *evsel_list;
100
101 static struct target target = {
102         .uid    = UINT_MAX,
103 };
104
105 static int                      run_count                       =  1;
106 static bool                     no_inherit                      = false;
107 static bool                     scale                           =  true;
108 static enum aggr_mode           aggr_mode                       = AGGR_GLOBAL;
109 static volatile pid_t           child_pid                       = -1;
110 static bool                     null_run                        =  false;
111 static int                      detailed_run                    =  0;
112 static bool                     transaction_run;
113 static bool                     big_num                         =  true;
114 static int                      big_num_opt                     =  -1;
115 static const char               *csv_sep                        = NULL;
116 static bool                     csv_output                      = false;
117 static bool                     group                           = false;
118 static FILE                     *output                         = NULL;
119 static const char               *pre_cmd                        = NULL;
120 static const char               *post_cmd                       = NULL;
121 static bool                     sync_run                        = false;
122 static unsigned int             interval                        = 0;
123 static unsigned int             initial_delay                   = 0;
124 static unsigned int             unit_width                      = 4; /* strlen("unit") */
125 static bool                     forever                         = false;
126 static struct timespec          ref_time;
127 static struct cpu_map           *aggr_map;
128 static int                      (*aggr_get_id)(struct cpu_map *m, int cpu);
129
130 static volatile int done = 0;
131
132 static inline void diff_timespec(struct timespec *r, struct timespec *a,
133                                  struct timespec *b)
134 {
135         r->tv_sec = a->tv_sec - b->tv_sec;
136         if (a->tv_nsec < b->tv_nsec) {
137                 r->tv_nsec = a->tv_nsec + 1000000000L - b->tv_nsec;
138                 r->tv_sec--;
139         } else {
140                 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
141         }
142 }
143
144 static void perf_evsel__reset_stat_priv(struct perf_evsel *evsel)
145 {
146         int i;
147         struct perf_stat *ps = evsel->priv;
148
149         for (i = 0; i < 3; i++)
150                 init_stats(&ps->res_stats[i]);
151
152         perf_stat_evsel_id_init(evsel);
153 }
154
155 static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
156 {
157         evsel->priv = zalloc(sizeof(struct perf_stat));
158         if (evsel->priv == NULL)
159                 return -ENOMEM;
160         perf_evsel__reset_stat_priv(evsel);
161         return 0;
162 }
163
164 static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
165 {
166         zfree(&evsel->priv);
167 }
168
169 static int perf_evsel__alloc_prev_raw_counts(struct perf_evsel *evsel)
170 {
171         struct perf_counts *counts;
172
173         counts = perf_counts__new(perf_evsel__nr_cpus(evsel));
174         if (counts)
175                 evsel->prev_raw_counts = counts;
176
177         return counts ? 0 : -ENOMEM;
178 }
179
180 static void perf_evsel__free_prev_raw_counts(struct perf_evsel *evsel)
181 {
182         perf_counts__delete(evsel->prev_raw_counts);
183         evsel->prev_raw_counts = NULL;
184 }
185
186 static void perf_evlist__free_stats(struct perf_evlist *evlist)
187 {
188         struct perf_evsel *evsel;
189
190         evlist__for_each(evlist, evsel) {
191                 perf_evsel__free_stat_priv(evsel);
192                 perf_evsel__free_counts(evsel);
193                 perf_evsel__free_prev_raw_counts(evsel);
194         }
195 }
196
197 static int perf_evlist__alloc_stats(struct perf_evlist *evlist, bool alloc_raw)
198 {
199         struct perf_evsel *evsel;
200
201         evlist__for_each(evlist, evsel) {
202                 if (perf_evsel__alloc_stat_priv(evsel) < 0 ||
203                     perf_evsel__alloc_counts(evsel, perf_evsel__nr_cpus(evsel)) < 0 ||
204                     (alloc_raw && perf_evsel__alloc_prev_raw_counts(evsel) < 0))
205                         goto out_free;
206         }
207
208         return 0;
209
210 out_free:
211         perf_evlist__free_stats(evlist);
212         return -1;
213 }
214
215 static void perf_stat__reset_stats(struct perf_evlist *evlist)
216 {
217         struct perf_evsel *evsel;
218
219         evlist__for_each(evlist, evsel) {
220                 perf_evsel__reset_stat_priv(evsel);
221                 perf_evsel__reset_counts(evsel, perf_evsel__nr_cpus(evsel));
222         }
223
224         perf_stat__reset_shadow_stats();
225 }
226
227 static int create_perf_stat_counter(struct perf_evsel *evsel)
228 {
229         struct perf_event_attr *attr = &evsel->attr;
230
231         if (scale)
232                 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
233                                     PERF_FORMAT_TOTAL_TIME_RUNNING;
234
235         attr->inherit = !no_inherit;
236
237         if (target__has_cpu(&target))
238                 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
239
240         if (!target__has_task(&target) && perf_evsel__is_group_leader(evsel)) {
241                 attr->disabled = 1;
242                 if (!initial_delay)
243                         attr->enable_on_exec = 1;
244         }
245
246         return perf_evsel__open_per_thread(evsel, evsel_list->threads);
247 }
248
249 /*
250  * Does the counter have nsecs as a unit?
251  */
252 static inline int nsec_counter(struct perf_evsel *evsel)
253 {
254         if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
255             perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
256                 return 1;
257
258         return 0;
259 }
260
261 static void zero_per_pkg(struct perf_evsel *counter)
262 {
263         if (counter->per_pkg_mask)
264                 memset(counter->per_pkg_mask, 0, MAX_NR_CPUS);
265 }
266
267 static int check_per_pkg(struct perf_evsel *counter, int cpu, bool *skip)
268 {
269         unsigned long *mask = counter->per_pkg_mask;
270         struct cpu_map *cpus = perf_evsel__cpus(counter);
271         int s;
272
273         *skip = false;
274
275         if (!counter->per_pkg)
276                 return 0;
277
278         if (cpu_map__empty(cpus))
279                 return 0;
280
281         if (!mask) {
282                 mask = zalloc(MAX_NR_CPUS);
283                 if (!mask)
284                         return -ENOMEM;
285
286                 counter->per_pkg_mask = mask;
287         }
288
289         s = cpu_map__get_socket(cpus, cpu);
290         if (s < 0)
291                 return -1;
292
293         *skip = test_and_set_bit(s, mask) == 1;
294         return 0;
295 }
296
297 static int read_cb(struct perf_evsel *evsel, int cpu, int thread __maybe_unused,
298                    struct perf_counts_values *count)
299 {
300         struct perf_counts_values *aggr = &evsel->counts->aggr;
301         static struct perf_counts_values zero;
302         bool skip = false;
303
304         if (check_per_pkg(evsel, cpu, &skip)) {
305                 pr_err("failed to read per-pkg counter\n");
306                 return -1;
307         }
308
309         if (skip)
310                 count = &zero;
311
312         switch (aggr_mode) {
313         case AGGR_CORE:
314         case AGGR_SOCKET:
315         case AGGR_NONE:
316                 if (!evsel->snapshot)
317                         perf_evsel__compute_deltas(evsel, cpu, count);
318                 perf_counts_values__scale(count, scale, NULL);
319                 *perf_counts(evsel->counts, cpu) = *count;
320                 if (aggr_mode == AGGR_NONE)
321                         perf_stat__update_shadow_stats(evsel, count->values, cpu);
322                 break;
323         case AGGR_GLOBAL:
324                 aggr->val += count->val;
325                 if (scale) {
326                         aggr->ena += count->ena;
327                         aggr->run += count->run;
328                 }
329         default:
330                 break;
331         }
332
333         return 0;
334 }
335
336 static int read_counter(struct perf_evsel *counter);
337
338 /*
339  * Read out the results of a single counter:
340  * aggregate counts across CPUs in system-wide mode
341  */
342 static int read_counter_aggr(struct perf_evsel *counter)
343 {
344         struct perf_counts_values *aggr = &counter->counts->aggr;
345         struct perf_stat *ps = counter->priv;
346         u64 *count = counter->counts->aggr.values;
347         int i;
348
349         aggr->val = aggr->ena = aggr->run = 0;
350
351         if (read_counter(counter))
352                 return -1;
353
354         if (!counter->snapshot)
355                 perf_evsel__compute_deltas(counter, -1, aggr);
356         perf_counts_values__scale(aggr, scale, &counter->counts->scaled);
357
358         for (i = 0; i < 3; i++)
359                 update_stats(&ps->res_stats[i], count[i]);
360
361         if (verbose) {
362                 fprintf(output, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
363                         perf_evsel__name(counter), count[0], count[1], count[2]);
364         }
365
366         /*
367          * Save the full runtime - to allow normalization during printout:
368          */
369         perf_stat__update_shadow_stats(counter, count, 0);
370
371         return 0;
372 }
373
374 /*
375  * Read out the results of a single counter:
376  * do not aggregate counts across CPUs in system-wide mode
377  */
378 static int read_counter(struct perf_evsel *counter)
379 {
380         int nthreads = thread_map__nr(evsel_list->threads);
381         int ncpus = perf_evsel__nr_cpus(counter);
382         int cpu, thread;
383
384         if (!counter->supported)
385                 return -ENOENT;
386
387         if (counter->system_wide)
388                 nthreads = 1;
389
390         if (counter->per_pkg)
391                 zero_per_pkg(counter);
392
393         for (thread = 0; thread < nthreads; thread++) {
394                 for (cpu = 0; cpu < ncpus; cpu++) {
395                         if (perf_evsel__read_cb(counter, cpu, thread, read_cb))
396                                 return -1;
397                 }
398         }
399
400         return 0;
401 }
402
403 static void print_interval(void)
404 {
405         static int num_print_interval;
406         struct perf_evsel *counter;
407         struct perf_stat *ps;
408         struct timespec ts, rs;
409         char prefix[64];
410
411         if (aggr_mode == AGGR_GLOBAL) {
412                 evlist__for_each(evsel_list, counter) {
413                         ps = counter->priv;
414                         memset(ps->res_stats, 0, sizeof(ps->res_stats));
415                         read_counter_aggr(counter);
416                 }
417         } else  {
418                 evlist__for_each(evsel_list, counter) {
419                         ps = counter->priv;
420                         memset(ps->res_stats, 0, sizeof(ps->res_stats));
421                         read_counter(counter);
422                 }
423         }
424
425         clock_gettime(CLOCK_MONOTONIC, &ts);
426         diff_timespec(&rs, &ts, &ref_time);
427         sprintf(prefix, "%6lu.%09lu%s", rs.tv_sec, rs.tv_nsec, csv_sep);
428
429         if (num_print_interval == 0 && !csv_output) {
430                 switch (aggr_mode) {
431                 case AGGR_SOCKET:
432                         fprintf(output, "#           time socket cpus             counts %*s events\n", unit_width, "unit");
433                         break;
434                 case AGGR_CORE:
435                         fprintf(output, "#           time core         cpus             counts %*s events\n", unit_width, "unit");
436                         break;
437                 case AGGR_NONE:
438                         fprintf(output, "#           time CPU                counts %*s events\n", unit_width, "unit");
439                         break;
440                 case AGGR_GLOBAL:
441                 default:
442                         fprintf(output, "#           time             counts %*s events\n", unit_width, "unit");
443                 }
444         }
445
446         if (++num_print_interval == 25)
447                 num_print_interval = 0;
448
449         switch (aggr_mode) {
450         case AGGR_CORE:
451         case AGGR_SOCKET:
452                 print_aggr(prefix);
453                 break;
454         case AGGR_NONE:
455                 evlist__for_each(evsel_list, counter)
456                         print_counter(counter, prefix);
457                 break;
458         case AGGR_GLOBAL:
459         default:
460                 evlist__for_each(evsel_list, counter)
461                         print_counter_aggr(counter, prefix);
462         }
463
464         fflush(output);
465 }
466
467 static void handle_initial_delay(void)
468 {
469         struct perf_evsel *counter;
470
471         if (initial_delay) {
472                 const int ncpus = cpu_map__nr(evsel_list->cpus),
473                         nthreads = thread_map__nr(evsel_list->threads);
474
475                 usleep(initial_delay * 1000);
476                 evlist__for_each(evsel_list, counter)
477                         perf_evsel__enable(counter, ncpus, nthreads);
478         }
479 }
480
481 static volatile int workload_exec_errno;
482
483 /*
484  * perf_evlist__prepare_workload will send a SIGUSR1
485  * if the fork fails, since we asked by setting its
486  * want_signal to true.
487  */
488 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
489                                         void *ucontext __maybe_unused)
490 {
491         workload_exec_errno = info->si_value.sival_int;
492 }
493
494 static int __run_perf_stat(int argc, const char **argv)
495 {
496         char msg[512];
497         unsigned long long t0, t1;
498         struct perf_evsel *counter;
499         struct timespec ts;
500         size_t l;
501         int status = 0;
502         const bool forks = (argc > 0);
503
504         if (interval) {
505                 ts.tv_sec  = interval / 1000;
506                 ts.tv_nsec = (interval % 1000) * 1000000;
507         } else {
508                 ts.tv_sec  = 1;
509                 ts.tv_nsec = 0;
510         }
511
512         if (forks) {
513                 if (perf_evlist__prepare_workload(evsel_list, &target, argv, false,
514                                                   workload_exec_failed_signal) < 0) {
515                         perror("failed to prepare workload");
516                         return -1;
517                 }
518                 child_pid = evsel_list->workload.pid;
519         }
520
521         if (group)
522                 perf_evlist__set_leader(evsel_list);
523
524         evlist__for_each(evsel_list, counter) {
525                 if (create_perf_stat_counter(counter) < 0) {
526                         /*
527                          * PPC returns ENXIO for HW counters until 2.6.37
528                          * (behavior changed with commit b0a873e).
529                          */
530                         if (errno == EINVAL || errno == ENOSYS ||
531                             errno == ENOENT || errno == EOPNOTSUPP ||
532                             errno == ENXIO) {
533                                 if (verbose)
534                                         ui__warning("%s event is not supported by the kernel.\n",
535                                                     perf_evsel__name(counter));
536                                 counter->supported = false;
537
538                                 if ((counter->leader != counter) ||
539                                     !(counter->leader->nr_members > 1))
540                                         continue;
541                         }
542
543                         perf_evsel__open_strerror(counter, &target,
544                                                   errno, msg, sizeof(msg));
545                         ui__error("%s\n", msg);
546
547                         if (child_pid != -1)
548                                 kill(child_pid, SIGTERM);
549
550                         return -1;
551                 }
552                 counter->supported = true;
553
554                 l = strlen(counter->unit);
555                 if (l > unit_width)
556                         unit_width = l;
557         }
558
559         if (perf_evlist__apply_filters(evsel_list, &counter)) {
560                 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
561                         counter->filter, perf_evsel__name(counter), errno,
562                         strerror_r(errno, msg, sizeof(msg)));
563                 return -1;
564         }
565
566         /*
567          * Enable counters and exec the command:
568          */
569         t0 = rdclock();
570         clock_gettime(CLOCK_MONOTONIC, &ref_time);
571
572         if (forks) {
573                 perf_evlist__start_workload(evsel_list);
574                 handle_initial_delay();
575
576                 if (interval) {
577                         while (!waitpid(child_pid, &status, WNOHANG)) {
578                                 nanosleep(&ts, NULL);
579                                 print_interval();
580                         }
581                 }
582                 wait(&status);
583
584                 if (workload_exec_errno) {
585                         const char *emsg = strerror_r(workload_exec_errno, msg, sizeof(msg));
586                         pr_err("Workload failed: %s\n", emsg);
587                         return -1;
588                 }
589
590                 if (WIFSIGNALED(status))
591                         psignal(WTERMSIG(status), argv[0]);
592         } else {
593                 handle_initial_delay();
594                 while (!done) {
595                         nanosleep(&ts, NULL);
596                         if (interval)
597                                 print_interval();
598                 }
599         }
600
601         t1 = rdclock();
602
603         update_stats(&walltime_nsecs_stats, t1 - t0);
604
605         if (aggr_mode == AGGR_GLOBAL) {
606                 evlist__for_each(evsel_list, counter) {
607                         read_counter_aggr(counter);
608                         perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter),
609                                              thread_map__nr(evsel_list->threads));
610                 }
611         } else {
612                 evlist__for_each(evsel_list, counter) {
613                         read_counter(counter);
614                         perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter), 1);
615                 }
616         }
617
618         return WEXITSTATUS(status);
619 }
620
621 static int run_perf_stat(int argc, const char **argv)
622 {
623         int ret;
624
625         if (pre_cmd) {
626                 ret = system(pre_cmd);
627                 if (ret)
628                         return ret;
629         }
630
631         if (sync_run)
632                 sync();
633
634         ret = __run_perf_stat(argc, argv);
635         if (ret)
636                 return ret;
637
638         if (post_cmd) {
639                 ret = system(post_cmd);
640                 if (ret)
641                         return ret;
642         }
643
644         return ret;
645 }
646
647 static void print_running(u64 run, u64 ena)
648 {
649         if (csv_output) {
650                 fprintf(output, "%s%" PRIu64 "%s%.2f",
651                                         csv_sep,
652                                         run,
653                                         csv_sep,
654                                         ena ? 100.0 * run / ena : 100.0);
655         } else if (run != ena) {
656                 fprintf(output, "  (%.2f%%)", 100.0 * run / ena);
657         }
658 }
659
660 static void print_noise_pct(double total, double avg)
661 {
662         double pct = rel_stddev_stats(total, avg);
663
664         if (csv_output)
665                 fprintf(output, "%s%.2f%%", csv_sep, pct);
666         else if (pct)
667                 fprintf(output, "  ( +-%6.2f%% )", pct);
668 }
669
670 static void print_noise(struct perf_evsel *evsel, double avg)
671 {
672         struct perf_stat *ps;
673
674         if (run_count == 1)
675                 return;
676
677         ps = evsel->priv;
678         print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
679 }
680
681 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
682 {
683         switch (aggr_mode) {
684         case AGGR_CORE:
685                 fprintf(output, "S%d-C%*d%s%*d%s",
686                         cpu_map__id_to_socket(id),
687                         csv_output ? 0 : -8,
688                         cpu_map__id_to_cpu(id),
689                         csv_sep,
690                         csv_output ? 0 : 4,
691                         nr,
692                         csv_sep);
693                 break;
694         case AGGR_SOCKET:
695                 fprintf(output, "S%*d%s%*d%s",
696                         csv_output ? 0 : -5,
697                         id,
698                         csv_sep,
699                         csv_output ? 0 : 4,
700                         nr,
701                         csv_sep);
702                         break;
703         case AGGR_NONE:
704                 fprintf(output, "CPU%*d%s",
705                         csv_output ? 0 : -4,
706                         perf_evsel__cpus(evsel)->map[id], csv_sep);
707                 break;
708         case AGGR_GLOBAL:
709         default:
710                 break;
711         }
712 }
713
714 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
715 {
716         double msecs = avg / 1e6;
717         const char *fmt_v, *fmt_n;
718         char name[25];
719
720         fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
721         fmt_n = csv_output ? "%s" : "%-25s";
722
723         aggr_printout(evsel, id, nr);
724
725         scnprintf(name, sizeof(name), "%s%s",
726                   perf_evsel__name(evsel), csv_output ? "" : " (msec)");
727
728         fprintf(output, fmt_v, msecs, csv_sep);
729
730         if (csv_output)
731                 fprintf(output, "%s%s", evsel->unit, csv_sep);
732         else
733                 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
734
735         fprintf(output, fmt_n, name);
736
737         if (evsel->cgrp)
738                 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
739
740         if (csv_output || interval)
741                 return;
742
743         if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
744                 fprintf(output, " # %8.3f CPUs utilized          ",
745                         avg / avg_stats(&walltime_nsecs_stats));
746         else
747                 fprintf(output, "                                   ");
748 }
749
750 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
751 {
752         double sc =  evsel->scale;
753         const char *fmt;
754         int cpu = cpu_map__id_to_cpu(id);
755
756         if (csv_output) {
757                 fmt = sc != 1.0 ?  "%.2f%s" : "%.0f%s";
758         } else {
759                 if (big_num)
760                         fmt = sc != 1.0 ? "%'18.2f%s" : "%'18.0f%s";
761                 else
762                         fmt = sc != 1.0 ? "%18.2f%s" : "%18.0f%s";
763         }
764
765         aggr_printout(evsel, id, nr);
766
767         if (aggr_mode == AGGR_GLOBAL)
768                 cpu = 0;
769
770         fprintf(output, fmt, avg, csv_sep);
771
772         if (evsel->unit)
773                 fprintf(output, "%-*s%s",
774                         csv_output ? 0 : unit_width,
775                         evsel->unit, csv_sep);
776
777         fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
778
779         if (evsel->cgrp)
780                 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
781
782         if (csv_output || interval)
783                 return;
784
785         perf_stat__print_shadow_stats(output, evsel, avg, cpu, aggr_mode);
786 }
787
788 static void print_aggr(char *prefix)
789 {
790         struct perf_evsel *counter;
791         int cpu, cpu2, s, s2, id, nr;
792         double uval;
793         u64 ena, run, val;
794
795         if (!(aggr_map || aggr_get_id))
796                 return;
797
798         for (s = 0; s < aggr_map->nr; s++) {
799                 id = aggr_map->map[s];
800                 evlist__for_each(evsel_list, counter) {
801                         val = ena = run = 0;
802                         nr = 0;
803                         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
804                                 cpu2 = perf_evsel__cpus(counter)->map[cpu];
805                                 s2 = aggr_get_id(evsel_list->cpus, cpu2);
806                                 if (s2 != id)
807                                         continue;
808                                 val += perf_counts(counter->counts, cpu)->val;
809                                 ena += perf_counts(counter->counts, cpu)->ena;
810                                 run += perf_counts(counter->counts, cpu)->run;
811                                 nr++;
812                         }
813                         if (prefix)
814                                 fprintf(output, "%s", prefix);
815
816                         if (run == 0 || ena == 0) {
817                                 aggr_printout(counter, id, nr);
818
819                                 fprintf(output, "%*s%s",
820                                         csv_output ? 0 : 18,
821                                         counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
822                                         csv_sep);
823
824                                 fprintf(output, "%-*s%s",
825                                         csv_output ? 0 : unit_width,
826                                         counter->unit, csv_sep);
827
828                                 fprintf(output, "%*s",
829                                         csv_output ? 0 : -25,
830                                         perf_evsel__name(counter));
831
832                                 if (counter->cgrp)
833                                         fprintf(output, "%s%s",
834                                                 csv_sep, counter->cgrp->name);
835
836                                 print_running(run, ena);
837                                 fputc('\n', output);
838                                 continue;
839                         }
840                         uval = val * counter->scale;
841
842                         if (nsec_counter(counter))
843                                 nsec_printout(id, nr, counter, uval);
844                         else
845                                 abs_printout(id, nr, counter, uval);
846
847                         if (!csv_output)
848                                 print_noise(counter, 1.0);
849
850                         print_running(run, ena);
851                         fputc('\n', output);
852                 }
853         }
854 }
855
856 /*
857  * Print out the results of a single counter:
858  * aggregated counts in system-wide mode
859  */
860 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
861 {
862         struct perf_stat *ps = counter->priv;
863         double avg = avg_stats(&ps->res_stats[0]);
864         int scaled = counter->counts->scaled;
865         double uval;
866         double avg_enabled, avg_running;
867
868         avg_enabled = avg_stats(&ps->res_stats[1]);
869         avg_running = avg_stats(&ps->res_stats[2]);
870
871         if (prefix)
872                 fprintf(output, "%s", prefix);
873
874         if (scaled == -1 || !counter->supported) {
875                 fprintf(output, "%*s%s",
876                         csv_output ? 0 : 18,
877                         counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
878                         csv_sep);
879                 fprintf(output, "%-*s%s",
880                         csv_output ? 0 : unit_width,
881                         counter->unit, csv_sep);
882                 fprintf(output, "%*s",
883                         csv_output ? 0 : -25,
884                         perf_evsel__name(counter));
885
886                 if (counter->cgrp)
887                         fprintf(output, "%s%s", csv_sep, counter->cgrp->name);
888
889                 print_running(avg_running, avg_enabled);
890                 fputc('\n', output);
891                 return;
892         }
893
894         uval = avg * counter->scale;
895
896         if (nsec_counter(counter))
897                 nsec_printout(-1, 0, counter, uval);
898         else
899                 abs_printout(-1, 0, counter, uval);
900
901         print_noise(counter, avg);
902
903         print_running(avg_running, avg_enabled);
904         fprintf(output, "\n");
905 }
906
907 /*
908  * Print out the results of a single counter:
909  * does not use aggregated count in system-wide
910  */
911 static void print_counter(struct perf_evsel *counter, char *prefix)
912 {
913         u64 ena, run, val;
914         double uval;
915         int cpu;
916
917         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
918                 val = perf_counts(counter->counts, cpu)->val;
919                 ena = perf_counts(counter->counts, cpu)->ena;
920                 run = perf_counts(counter->counts, cpu)->run;
921
922                 if (prefix)
923                         fprintf(output, "%s", prefix);
924
925                 if (run == 0 || ena == 0) {
926                         fprintf(output, "CPU%*d%s%*s%s",
927                                 csv_output ? 0 : -4,
928                                 perf_evsel__cpus(counter)->map[cpu], csv_sep,
929                                 csv_output ? 0 : 18,
930                                 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
931                                 csv_sep);
932
933                                 fprintf(output, "%-*s%s",
934                                         csv_output ? 0 : unit_width,
935                                         counter->unit, csv_sep);
936
937                                 fprintf(output, "%*s",
938                                         csv_output ? 0 : -25,
939                                         perf_evsel__name(counter));
940
941                         if (counter->cgrp)
942                                 fprintf(output, "%s%s",
943                                         csv_sep, counter->cgrp->name);
944
945                         print_running(run, ena);
946                         fputc('\n', output);
947                         continue;
948                 }
949
950                 uval = val * counter->scale;
951
952                 if (nsec_counter(counter))
953                         nsec_printout(cpu, 0, counter, uval);
954                 else
955                         abs_printout(cpu, 0, counter, uval);
956
957                 if (!csv_output)
958                         print_noise(counter, 1.0);
959                 print_running(run, ena);
960
961                 fputc('\n', output);
962         }
963 }
964
965 static void print_stat(int argc, const char **argv)
966 {
967         struct perf_evsel *counter;
968         int i;
969
970         fflush(stdout);
971
972         if (!csv_output) {
973                 fprintf(output, "\n");
974                 fprintf(output, " Performance counter stats for ");
975                 if (target.system_wide)
976                         fprintf(output, "\'system wide");
977                 else if (target.cpu_list)
978                         fprintf(output, "\'CPU(s) %s", target.cpu_list);
979                 else if (!target__has_task(&target)) {
980                         fprintf(output, "\'%s", argv[0]);
981                         for (i = 1; i < argc; i++)
982                                 fprintf(output, " %s", argv[i]);
983                 } else if (target.pid)
984                         fprintf(output, "process id \'%s", target.pid);
985                 else
986                         fprintf(output, "thread id \'%s", target.tid);
987
988                 fprintf(output, "\'");
989                 if (run_count > 1)
990                         fprintf(output, " (%d runs)", run_count);
991                 fprintf(output, ":\n\n");
992         }
993
994         switch (aggr_mode) {
995         case AGGR_CORE:
996         case AGGR_SOCKET:
997                 print_aggr(NULL);
998                 break;
999         case AGGR_GLOBAL:
1000                 evlist__for_each(evsel_list, counter)
1001                         print_counter_aggr(counter, NULL);
1002                 break;
1003         case AGGR_NONE:
1004                 evlist__for_each(evsel_list, counter)
1005                         print_counter(counter, NULL);
1006                 break;
1007         default:
1008                 break;
1009         }
1010
1011         if (!csv_output) {
1012                 if (!null_run)
1013                         fprintf(output, "\n");
1014                 fprintf(output, " %17.9f seconds time elapsed",
1015                                 avg_stats(&walltime_nsecs_stats)/1e9);
1016                 if (run_count > 1) {
1017                         fprintf(output, "                                        ");
1018                         print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1019                                         avg_stats(&walltime_nsecs_stats));
1020                 }
1021                 fprintf(output, "\n\n");
1022         }
1023 }
1024
1025 static volatile int signr = -1;
1026
1027 static void skip_signal(int signo)
1028 {
1029         if ((child_pid == -1) || interval)
1030                 done = 1;
1031
1032         signr = signo;
1033         /*
1034          * render child_pid harmless
1035          * won't send SIGTERM to a random
1036          * process in case of race condition
1037          * and fast PID recycling
1038          */
1039         child_pid = -1;
1040 }
1041
1042 static void sig_atexit(void)
1043 {
1044         sigset_t set, oset;
1045
1046         /*
1047          * avoid race condition with SIGCHLD handler
1048          * in skip_signal() which is modifying child_pid
1049          * goal is to avoid send SIGTERM to a random
1050          * process
1051          */
1052         sigemptyset(&set);
1053         sigaddset(&set, SIGCHLD);
1054         sigprocmask(SIG_BLOCK, &set, &oset);
1055
1056         if (child_pid != -1)
1057                 kill(child_pid, SIGTERM);
1058
1059         sigprocmask(SIG_SETMASK, &oset, NULL);
1060
1061         if (signr == -1)
1062                 return;
1063
1064         signal(signr, SIG_DFL);
1065         kill(getpid(), signr);
1066 }
1067
1068 static int stat__set_big_num(const struct option *opt __maybe_unused,
1069                              const char *s __maybe_unused, int unset)
1070 {
1071         big_num_opt = unset ? 0 : 1;
1072         return 0;
1073 }
1074
1075 static int perf_stat_init_aggr_mode(void)
1076 {
1077         switch (aggr_mode) {
1078         case AGGR_SOCKET:
1079                 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1080                         perror("cannot build socket map");
1081                         return -1;
1082                 }
1083                 aggr_get_id = cpu_map__get_socket;
1084                 break;
1085         case AGGR_CORE:
1086                 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1087                         perror("cannot build core map");
1088                         return -1;
1089                 }
1090                 aggr_get_id = cpu_map__get_core;
1091                 break;
1092         case AGGR_NONE:
1093         case AGGR_GLOBAL:
1094         default:
1095                 break;
1096         }
1097         return 0;
1098 }
1099
1100 /*
1101  * Add default attributes, if there were no attributes specified or
1102  * if -d/--detailed, -d -d or -d -d -d is used:
1103  */
1104 static int add_default_attributes(void)
1105 {
1106         struct perf_event_attr default_attrs[] = {
1107
1108   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK              },
1109   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES        },
1110   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS          },
1111   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS             },
1112
1113   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES              },
1114   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1115   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND  },
1116   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS            },
1117   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS     },
1118   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES           },
1119
1120 };
1121
1122 /*
1123  * Detailed stats (-d), covering the L1 and last level data caches:
1124  */
1125         struct perf_event_attr detailed_attrs[] = {
1126
1127   { .type = PERF_TYPE_HW_CACHE,
1128     .config =
1129          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1130         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1131         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1132
1133   { .type = PERF_TYPE_HW_CACHE,
1134     .config =
1135          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1136         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1137         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1138
1139   { .type = PERF_TYPE_HW_CACHE,
1140     .config =
1141          PERF_COUNT_HW_CACHE_LL                 <<  0  |
1142         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1143         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1144
1145   { .type = PERF_TYPE_HW_CACHE,
1146     .config =
1147          PERF_COUNT_HW_CACHE_LL                 <<  0  |
1148         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1149         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1150 };
1151
1152 /*
1153  * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1154  */
1155         struct perf_event_attr very_detailed_attrs[] = {
1156
1157   { .type = PERF_TYPE_HW_CACHE,
1158     .config =
1159          PERF_COUNT_HW_CACHE_L1I                <<  0  |
1160         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1161         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1162
1163   { .type = PERF_TYPE_HW_CACHE,
1164     .config =
1165          PERF_COUNT_HW_CACHE_L1I                <<  0  |
1166         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1167         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1168
1169   { .type = PERF_TYPE_HW_CACHE,
1170     .config =
1171          PERF_COUNT_HW_CACHE_DTLB               <<  0  |
1172         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1173         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1174
1175   { .type = PERF_TYPE_HW_CACHE,
1176     .config =
1177          PERF_COUNT_HW_CACHE_DTLB               <<  0  |
1178         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1179         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1180
1181   { .type = PERF_TYPE_HW_CACHE,
1182     .config =
1183          PERF_COUNT_HW_CACHE_ITLB               <<  0  |
1184         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1185         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1186
1187   { .type = PERF_TYPE_HW_CACHE,
1188     .config =
1189          PERF_COUNT_HW_CACHE_ITLB               <<  0  |
1190         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1191         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1192
1193 };
1194
1195 /*
1196  * Very, very detailed stats (-d -d -d), adding prefetch events:
1197  */
1198         struct perf_event_attr very_very_detailed_attrs[] = {
1199
1200   { .type = PERF_TYPE_HW_CACHE,
1201     .config =
1202          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1203         (PERF_COUNT_HW_CACHE_OP_PREFETCH        <<  8) |
1204         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1205
1206   { .type = PERF_TYPE_HW_CACHE,
1207     .config =
1208          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1209         (PERF_COUNT_HW_CACHE_OP_PREFETCH        <<  8) |
1210         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1211 };
1212
1213         /* Set attrs if no event is selected and !null_run: */
1214         if (null_run)
1215                 return 0;
1216
1217         if (transaction_run) {
1218                 int err;
1219                 if (pmu_have_event("cpu", "cycles-ct") &&
1220                     pmu_have_event("cpu", "el-start"))
1221                         err = parse_events(evsel_list, transaction_attrs, NULL);
1222                 else
1223                         err = parse_events(evsel_list, transaction_limited_attrs, NULL);
1224                 if (err) {
1225                         fprintf(stderr, "Cannot set up transaction events\n");
1226                         return -1;
1227                 }
1228                 return 0;
1229         }
1230
1231         if (!evsel_list->nr_entries) {
1232                 if (perf_evlist__add_default_attrs(evsel_list, default_attrs) < 0)
1233                         return -1;
1234         }
1235
1236         /* Detailed events get appended to the event list: */
1237
1238         if (detailed_run <  1)
1239                 return 0;
1240
1241         /* Append detailed run extra attributes: */
1242         if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1243                 return -1;
1244
1245         if (detailed_run < 2)
1246                 return 0;
1247
1248         /* Append very detailed run extra attributes: */
1249         if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1250                 return -1;
1251
1252         if (detailed_run < 3)
1253                 return 0;
1254
1255         /* Append very, very detailed run extra attributes: */
1256         return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1257 }
1258
1259 int cmd_stat(int argc, const char **argv, const char *prefix __maybe_unused)
1260 {
1261         bool append_file = false;
1262         int output_fd = 0;
1263         const char *output_name = NULL;
1264         const struct option options[] = {
1265         OPT_BOOLEAN('T', "transaction", &transaction_run,
1266                     "hardware transaction statistics"),
1267         OPT_CALLBACK('e', "event", &evsel_list, "event",
1268                      "event selector. use 'perf list' to list available events",
1269                      parse_events_option),
1270         OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1271                      "event filter", parse_filter),
1272         OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1273                     "child tasks do not inherit counters"),
1274         OPT_STRING('p', "pid", &target.pid, "pid",
1275                    "stat events on existing process id"),
1276         OPT_STRING('t', "tid", &target.tid, "tid",
1277                    "stat events on existing thread id"),
1278         OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1279                     "system-wide collection from all CPUs"),
1280         OPT_BOOLEAN('g', "group", &group,
1281                     "put the counters into a counter group"),
1282         OPT_BOOLEAN('c', "scale", &scale, "scale/normalize counters"),
1283         OPT_INCR('v', "verbose", &verbose,
1284                     "be more verbose (show counter open errors, etc)"),
1285         OPT_INTEGER('r', "repeat", &run_count,
1286                     "repeat command and print average + stddev (max: 100, forever: 0)"),
1287         OPT_BOOLEAN('n', "null", &null_run,
1288                     "null run - dont start any counters"),
1289         OPT_INCR('d', "detailed", &detailed_run,
1290                     "detailed run - start a lot of events"),
1291         OPT_BOOLEAN('S', "sync", &sync_run,
1292                     "call sync() before starting a run"),
1293         OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1294                            "print large numbers with thousands\' separators",
1295                            stat__set_big_num),
1296         OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1297                     "list of cpus to monitor in system-wide"),
1298         OPT_SET_UINT('A', "no-aggr", &aggr_mode,
1299                     "disable CPU count aggregation", AGGR_NONE),
1300         OPT_STRING('x', "field-separator", &csv_sep, "separator",
1301                    "print counts with custom separator"),
1302         OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1303                      "monitor event in cgroup name only", parse_cgroups),
1304         OPT_STRING('o', "output", &output_name, "file", "output file name"),
1305         OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1306         OPT_INTEGER(0, "log-fd", &output_fd,
1307                     "log output to fd, instead of stderr"),
1308         OPT_STRING(0, "pre", &pre_cmd, "command",
1309                         "command to run prior to the measured command"),
1310         OPT_STRING(0, "post", &post_cmd, "command",
1311                         "command to run after to the measured command"),
1312         OPT_UINTEGER('I', "interval-print", &interval,
1313                     "print counts at regular interval in ms (>= 100)"),
1314         OPT_SET_UINT(0, "per-socket", &aggr_mode,
1315                      "aggregate counts per processor socket", AGGR_SOCKET),
1316         OPT_SET_UINT(0, "per-core", &aggr_mode,
1317                      "aggregate counts per physical processor core", AGGR_CORE),
1318         OPT_UINTEGER('D', "delay", &initial_delay,
1319                      "ms to wait before starting measurement after program start"),
1320         OPT_END()
1321         };
1322         const char * const stat_usage[] = {
1323                 "perf stat [<options>] [<command>]",
1324                 NULL
1325         };
1326         int status = -EINVAL, run_idx;
1327         const char *mode;
1328
1329         setlocale(LC_ALL, "");
1330
1331         evsel_list = perf_evlist__new();
1332         if (evsel_list == NULL)
1333                 return -ENOMEM;
1334
1335         argc = parse_options(argc, argv, options, stat_usage,
1336                 PARSE_OPT_STOP_AT_NON_OPTION);
1337
1338         output = stderr;
1339         if (output_name && strcmp(output_name, "-"))
1340                 output = NULL;
1341
1342         if (output_name && output_fd) {
1343                 fprintf(stderr, "cannot use both --output and --log-fd\n");
1344                 parse_options_usage(stat_usage, options, "o", 1);
1345                 parse_options_usage(NULL, options, "log-fd", 0);
1346                 goto out;
1347         }
1348
1349         if (output_fd < 0) {
1350                 fprintf(stderr, "argument to --log-fd must be a > 0\n");
1351                 parse_options_usage(stat_usage, options, "log-fd", 0);
1352                 goto out;
1353         }
1354
1355         if (!output) {
1356                 struct timespec tm;
1357                 mode = append_file ? "a" : "w";
1358
1359                 output = fopen(output_name, mode);
1360                 if (!output) {
1361                         perror("failed to create output file");
1362                         return -1;
1363                 }
1364                 clock_gettime(CLOCK_REALTIME, &tm);
1365                 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
1366         } else if (output_fd > 0) {
1367                 mode = append_file ? "a" : "w";
1368                 output = fdopen(output_fd, mode);
1369                 if (!output) {
1370                         perror("Failed opening logfd");
1371                         return -errno;
1372                 }
1373         }
1374
1375         if (csv_sep) {
1376                 csv_output = true;
1377                 if (!strcmp(csv_sep, "\\t"))
1378                         csv_sep = "\t";
1379         } else
1380                 csv_sep = DEFAULT_SEPARATOR;
1381
1382         /*
1383          * let the spreadsheet do the pretty-printing
1384          */
1385         if (csv_output) {
1386                 /* User explicitly passed -B? */
1387                 if (big_num_opt == 1) {
1388                         fprintf(stderr, "-B option not supported with -x\n");
1389                         parse_options_usage(stat_usage, options, "B", 1);
1390                         parse_options_usage(NULL, options, "x", 1);
1391                         goto out;
1392                 } else /* Nope, so disable big number formatting */
1393                         big_num = false;
1394         } else if (big_num_opt == 0) /* User passed --no-big-num */
1395                 big_num = false;
1396
1397         if (!argc && target__none(&target))
1398                 usage_with_options(stat_usage, options);
1399
1400         if (run_count < 0) {
1401                 pr_err("Run count must be a positive number\n");
1402                 parse_options_usage(stat_usage, options, "r", 1);
1403                 goto out;
1404         } else if (run_count == 0) {
1405                 forever = true;
1406                 run_count = 1;
1407         }
1408
1409         /* no_aggr, cgroup are for system-wide only */
1410         if ((aggr_mode != AGGR_GLOBAL || nr_cgroups) &&
1411             !target__has_cpu(&target)) {
1412                 fprintf(stderr, "both cgroup and no-aggregation "
1413                         "modes only available in system-wide mode\n");
1414
1415                 parse_options_usage(stat_usage, options, "G", 1);
1416                 parse_options_usage(NULL, options, "A", 1);
1417                 parse_options_usage(NULL, options, "a", 1);
1418                 goto out;
1419         }
1420
1421         if (add_default_attributes())
1422                 goto out;
1423
1424         target__validate(&target);
1425
1426         if (perf_evlist__create_maps(evsel_list, &target) < 0) {
1427                 if (target__has_task(&target)) {
1428                         pr_err("Problems finding threads of monitor\n");
1429                         parse_options_usage(stat_usage, options, "p", 1);
1430                         parse_options_usage(NULL, options, "t", 1);
1431                 } else if (target__has_cpu(&target)) {
1432                         perror("failed to parse CPUs map");
1433                         parse_options_usage(stat_usage, options, "C", 1);
1434                         parse_options_usage(NULL, options, "a", 1);
1435                 }
1436                 goto out;
1437         }
1438         if (interval && interval < 100) {
1439                 pr_err("print interval must be >= 100ms\n");
1440                 parse_options_usage(stat_usage, options, "I", 1);
1441                 goto out;
1442         }
1443
1444         if (perf_evlist__alloc_stats(evsel_list, interval))
1445                 goto out;
1446
1447         if (perf_stat_init_aggr_mode())
1448                 goto out;
1449
1450         /*
1451          * We dont want to block the signals - that would cause
1452          * child tasks to inherit that and Ctrl-C would not work.
1453          * What we want is for Ctrl-C to work in the exec()-ed
1454          * task, but being ignored by perf stat itself:
1455          */
1456         atexit(sig_atexit);
1457         if (!forever)
1458                 signal(SIGINT,  skip_signal);
1459         signal(SIGCHLD, skip_signal);
1460         signal(SIGALRM, skip_signal);
1461         signal(SIGABRT, skip_signal);
1462
1463         status = 0;
1464         for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
1465                 if (run_count != 1 && verbose)
1466                         fprintf(output, "[ perf stat: executing run #%d ... ]\n",
1467                                 run_idx + 1);
1468
1469                 status = run_perf_stat(argc, argv);
1470                 if (forever && status != -1) {
1471                         print_stat(argc, argv);
1472                         perf_stat__reset_stats(evsel_list);
1473                 }
1474         }
1475
1476         if (!forever && status != -1 && !interval)
1477                 print_stat(argc, argv);
1478
1479         perf_evlist__free_stats(evsel_list);
1480 out:
1481         perf_evlist__delete(evsel_list);
1482         return status;
1483 }