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