perf tools: Fix hist_entry__filter() for hierarchy
[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 <subcmd/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 #include "util/counts.h"
62 #include "util/session.h"
63 #include "util/tool.h"
64 #include "asm/bug.h"
65
66 #include <stdlib.h>
67 #include <sys/prctl.h>
68 #include <locale.h>
69
70 #define DEFAULT_SEPARATOR       " "
71 #define CNTR_NOT_SUPPORTED      "<not supported>"
72 #define CNTR_NOT_COUNTED        "<not counted>"
73
74 static void print_counters(struct timespec *ts, int argc, const char **argv);
75
76 /* Default events used for perf stat -T */
77 static const char *transaction_attrs = {
78         "task-clock,"
79         "{"
80         "instructions,"
81         "cycles,"
82         "cpu/cycles-t/,"
83         "cpu/tx-start/,"
84         "cpu/el-start/,"
85         "cpu/cycles-ct/"
86         "}"
87 };
88
89 /* More limited version when the CPU does not have all events. */
90 static const char * transaction_limited_attrs = {
91         "task-clock,"
92         "{"
93         "instructions,"
94         "cycles,"
95         "cpu/cycles-t/,"
96         "cpu/tx-start/"
97         "}"
98 };
99
100 static struct perf_evlist       *evsel_list;
101
102 static struct target target = {
103         .uid    = UINT_MAX,
104 };
105
106 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
107
108 static int                      run_count                       =  1;
109 static bool                     no_inherit                      = false;
110 static volatile pid_t           child_pid                       = -1;
111 static bool                     null_run                        =  false;
112 static int                      detailed_run                    =  0;
113 static bool                     transaction_run;
114 static bool                     big_num                         =  true;
115 static int                      big_num_opt                     =  -1;
116 static const char               *csv_sep                        = NULL;
117 static bool                     csv_output                      = false;
118 static bool                     group                           = false;
119 static const char               *pre_cmd                        = NULL;
120 static const char               *post_cmd                       = NULL;
121 static bool                     sync_run                        = false;
122 static unsigned int             initial_delay                   = 0;
123 static unsigned int             unit_width                      = 4; /* strlen("unit") */
124 static bool                     forever                         = false;
125 static struct timespec          ref_time;
126 static struct cpu_map           *aggr_map;
127 static aggr_get_id_t            aggr_get_id;
128 static bool                     append_file;
129 static const char               *output_name;
130 static int                      output_fd;
131
132 struct perf_stat {
133         bool                     record;
134         struct perf_data_file    file;
135         struct perf_session     *session;
136         u64                      bytes_written;
137         struct perf_tool         tool;
138         bool                     maps_allocated;
139         struct cpu_map          *cpus;
140         struct thread_map       *threads;
141         enum aggr_mode           aggr_mode;
142 };
143
144 static struct perf_stat         perf_stat;
145 #define STAT_RECORD             perf_stat.record
146
147 static volatile int done = 0;
148
149 static struct perf_stat_config stat_config = {
150         .aggr_mode      = AGGR_GLOBAL,
151         .scale          = true,
152 };
153
154 static inline void diff_timespec(struct timespec *r, struct timespec *a,
155                                  struct timespec *b)
156 {
157         r->tv_sec = a->tv_sec - b->tv_sec;
158         if (a->tv_nsec < b->tv_nsec) {
159                 r->tv_nsec = a->tv_nsec + 1000000000L - b->tv_nsec;
160                 r->tv_sec--;
161         } else {
162                 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
163         }
164 }
165
166 static void perf_stat__reset_stats(void)
167 {
168         perf_evlist__reset_stats(evsel_list);
169         perf_stat__reset_shadow_stats();
170 }
171
172 static int create_perf_stat_counter(struct perf_evsel *evsel)
173 {
174         struct perf_event_attr *attr = &evsel->attr;
175
176         if (stat_config.scale)
177                 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
178                                     PERF_FORMAT_TOTAL_TIME_RUNNING;
179
180         attr->inherit = !no_inherit;
181
182         /*
183          * Some events get initialized with sample_(period/type) set,
184          * like tracepoints. Clear it up for counting.
185          */
186         attr->sample_period = 0;
187
188         /*
189          * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
190          * while avoiding that older tools show confusing messages.
191          *
192          * However for pipe sessions we need to keep it zero,
193          * because script's perf_evsel__check_attr is triggered
194          * by attr->sample_type != 0, and we can't run it on
195          * stat sessions.
196          */
197         if (!(STAT_RECORD && perf_stat.file.is_pipe))
198                 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
199
200         /*
201          * Disabling all counters initially, they will be enabled
202          * either manually by us or by kernel via enable_on_exec
203          * set later.
204          */
205         if (perf_evsel__is_group_leader(evsel)) {
206                 attr->disabled = 1;
207
208                 /*
209                  * In case of initial_delay we enable tracee
210                  * events manually.
211                  */
212                 if (target__none(&target) && !initial_delay)
213                         attr->enable_on_exec = 1;
214         }
215
216         if (target__has_cpu(&target))
217                 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
218
219         return perf_evsel__open_per_thread(evsel, evsel_list->threads);
220 }
221
222 /*
223  * Does the counter have nsecs as a unit?
224  */
225 static inline int nsec_counter(struct perf_evsel *evsel)
226 {
227         if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
228             perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
229                 return 1;
230
231         return 0;
232 }
233
234 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
235                                      union perf_event *event,
236                                      struct perf_sample *sample __maybe_unused,
237                                      struct machine *machine __maybe_unused)
238 {
239         if (perf_data_file__write(&perf_stat.file, event, event->header.size) < 0) {
240                 pr_err("failed to write perf data, error: %m\n");
241                 return -1;
242         }
243
244         perf_stat.bytes_written += event->header.size;
245         return 0;
246 }
247
248 static int write_stat_round_event(u64 tm, u64 type)
249 {
250         return perf_event__synthesize_stat_round(NULL, tm, type,
251                                                  process_synthesized_event,
252                                                  NULL);
253 }
254
255 #define WRITE_STAT_ROUND_EVENT(time, interval) \
256         write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
257
258 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
259
260 static int
261 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
262                              struct perf_counts_values *count)
263 {
264         struct perf_sample_id *sid = SID(counter, cpu, thread);
265
266         return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
267                                            process_synthesized_event, NULL);
268 }
269
270 /*
271  * Read out the results of a single counter:
272  * do not aggregate counts across CPUs in system-wide mode
273  */
274 static int read_counter(struct perf_evsel *counter)
275 {
276         int nthreads = thread_map__nr(evsel_list->threads);
277         int ncpus = perf_evsel__nr_cpus(counter);
278         int cpu, thread;
279
280         if (!counter->supported)
281                 return -ENOENT;
282
283         if (counter->system_wide)
284                 nthreads = 1;
285
286         for (thread = 0; thread < nthreads; thread++) {
287                 for (cpu = 0; cpu < ncpus; cpu++) {
288                         struct perf_counts_values *count;
289
290                         count = perf_counts(counter->counts, cpu, thread);
291                         if (perf_evsel__read(counter, cpu, thread, count))
292                                 return -1;
293
294                         if (STAT_RECORD) {
295                                 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
296                                         pr_err("failed to write stat event\n");
297                                         return -1;
298                                 }
299                         }
300                 }
301         }
302
303         return 0;
304 }
305
306 static void read_counters(bool close_counters)
307 {
308         struct perf_evsel *counter;
309
310         evlist__for_each(evsel_list, counter) {
311                 if (read_counter(counter))
312                         pr_debug("failed to read counter %s\n", counter->name);
313
314                 if (perf_stat_process_counter(&stat_config, counter))
315                         pr_warning("failed to process counter %s\n", counter->name);
316
317                 if (close_counters) {
318                         perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter),
319                                              thread_map__nr(evsel_list->threads));
320                 }
321         }
322 }
323
324 static void process_interval(void)
325 {
326         struct timespec ts, rs;
327
328         read_counters(false);
329
330         clock_gettime(CLOCK_MONOTONIC, &ts);
331         diff_timespec(&rs, &ts, &ref_time);
332
333         if (STAT_RECORD) {
334                 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSECS_PER_SEC + rs.tv_nsec, INTERVAL))
335                         pr_err("failed to write stat round event\n");
336         }
337
338         print_counters(&rs, 0, NULL);
339 }
340
341 static void enable_counters(void)
342 {
343         if (initial_delay)
344                 usleep(initial_delay * 1000);
345
346         /*
347          * We need to enable counters only if:
348          * - we don't have tracee (attaching to task or cpu)
349          * - we have initial delay configured
350          */
351         if (!target__none(&target) || initial_delay)
352                 perf_evlist__enable(evsel_list);
353 }
354
355 static volatile int workload_exec_errno;
356
357 /*
358  * perf_evlist__prepare_workload will send a SIGUSR1
359  * if the fork fails, since we asked by setting its
360  * want_signal to true.
361  */
362 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
363                                         void *ucontext __maybe_unused)
364 {
365         workload_exec_errno = info->si_value.sival_int;
366 }
367
368 static bool has_unit(struct perf_evsel *counter)
369 {
370         return counter->unit && *counter->unit;
371 }
372
373 static bool has_scale(struct perf_evsel *counter)
374 {
375         return counter->scale != 1;
376 }
377
378 static int perf_stat_synthesize_config(bool is_pipe)
379 {
380         struct perf_evsel *counter;
381         int err;
382
383         if (is_pipe) {
384                 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
385                                                    process_synthesized_event);
386                 if (err < 0) {
387                         pr_err("Couldn't synthesize attrs.\n");
388                         return err;
389                 }
390         }
391
392         /*
393          * Synthesize other events stuff not carried within
394          * attr event - unit, scale, name
395          */
396         evlist__for_each(evsel_list, counter) {
397                 if (!counter->supported)
398                         continue;
399
400                 /*
401                  * Synthesize unit and scale only if it's defined.
402                  */
403                 if (has_unit(counter)) {
404                         err = perf_event__synthesize_event_update_unit(NULL, counter, process_synthesized_event);
405                         if (err < 0) {
406                                 pr_err("Couldn't synthesize evsel unit.\n");
407                                 return err;
408                         }
409                 }
410
411                 if (has_scale(counter)) {
412                         err = perf_event__synthesize_event_update_scale(NULL, counter, process_synthesized_event);
413                         if (err < 0) {
414                                 pr_err("Couldn't synthesize evsel scale.\n");
415                                 return err;
416                         }
417                 }
418
419                 if (counter->own_cpus) {
420                         err = perf_event__synthesize_event_update_cpus(NULL, counter, process_synthesized_event);
421                         if (err < 0) {
422                                 pr_err("Couldn't synthesize evsel scale.\n");
423                                 return err;
424                         }
425                 }
426
427                 /*
428                  * Name is needed only for pipe output,
429                  * perf.data carries event names.
430                  */
431                 if (is_pipe) {
432                         err = perf_event__synthesize_event_update_name(NULL, counter, process_synthesized_event);
433                         if (err < 0) {
434                                 pr_err("Couldn't synthesize evsel name.\n");
435                                 return err;
436                         }
437                 }
438         }
439
440         err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
441                                                 process_synthesized_event,
442                                                 NULL);
443         if (err < 0) {
444                 pr_err("Couldn't synthesize thread map.\n");
445                 return err;
446         }
447
448         err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
449                                              process_synthesized_event, NULL);
450         if (err < 0) {
451                 pr_err("Couldn't synthesize thread map.\n");
452                 return err;
453         }
454
455         err = perf_event__synthesize_stat_config(NULL, &stat_config,
456                                                  process_synthesized_event, NULL);
457         if (err < 0) {
458                 pr_err("Couldn't synthesize config.\n");
459                 return err;
460         }
461
462         return 0;
463 }
464
465 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
466
467 static int __store_counter_ids(struct perf_evsel *counter,
468                                struct cpu_map *cpus,
469                                struct thread_map *threads)
470 {
471         int cpu, thread;
472
473         for (cpu = 0; cpu < cpus->nr; cpu++) {
474                 for (thread = 0; thread < threads->nr; thread++) {
475                         int fd = FD(counter, cpu, thread);
476
477                         if (perf_evlist__id_add_fd(evsel_list, counter,
478                                                    cpu, thread, fd) < 0)
479                                 return -1;
480                 }
481         }
482
483         return 0;
484 }
485
486 static int store_counter_ids(struct perf_evsel *counter)
487 {
488         struct cpu_map *cpus = counter->cpus;
489         struct thread_map *threads = counter->threads;
490
491         if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
492                 return -ENOMEM;
493
494         return __store_counter_ids(counter, cpus, threads);
495 }
496
497 static int __run_perf_stat(int argc, const char **argv)
498 {
499         int interval = stat_config.interval;
500         char msg[512];
501         unsigned long long t0, t1;
502         struct perf_evsel *counter;
503         struct timespec ts;
504         size_t l;
505         int status = 0;
506         const bool forks = (argc > 0);
507         bool is_pipe = STAT_RECORD ? perf_stat.file.is_pipe : false;
508
509         if (interval) {
510                 ts.tv_sec  = interval / 1000;
511                 ts.tv_nsec = (interval % 1000) * 1000000;
512         } else {
513                 ts.tv_sec  = 1;
514                 ts.tv_nsec = 0;
515         }
516
517         if (forks) {
518                 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
519                                                   workload_exec_failed_signal) < 0) {
520                         perror("failed to prepare workload");
521                         return -1;
522                 }
523                 child_pid = evsel_list->workload.pid;
524         }
525
526         if (group)
527                 perf_evlist__set_leader(evsel_list);
528
529         evlist__for_each(evsel_list, counter) {
530                 if (create_perf_stat_counter(counter) < 0) {
531                         /*
532                          * PPC returns ENXIO for HW counters until 2.6.37
533                          * (behavior changed with commit b0a873e).
534                          */
535                         if (errno == EINVAL || errno == ENOSYS ||
536                             errno == ENOENT || errno == EOPNOTSUPP ||
537                             errno == ENXIO) {
538                                 if (verbose)
539                                         ui__warning("%s event is not supported by the kernel.\n",
540                                                     perf_evsel__name(counter));
541                                 counter->supported = false;
542
543                                 if ((counter->leader != counter) ||
544                                     !(counter->leader->nr_members > 1))
545                                         continue;
546                         }
547
548                         perf_evsel__open_strerror(counter, &target,
549                                                   errno, msg, sizeof(msg));
550                         ui__error("%s\n", msg);
551
552                         if (child_pid != -1)
553                                 kill(child_pid, SIGTERM);
554
555                         return -1;
556                 }
557                 counter->supported = true;
558
559                 l = strlen(counter->unit);
560                 if (l > unit_width)
561                         unit_width = l;
562
563                 if (STAT_RECORD && store_counter_ids(counter))
564                         return -1;
565         }
566
567         if (perf_evlist__apply_filters(evsel_list, &counter)) {
568                 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
569                         counter->filter, perf_evsel__name(counter), errno,
570                         strerror_r(errno, msg, sizeof(msg)));
571                 return -1;
572         }
573
574         if (STAT_RECORD) {
575                 int err, fd = perf_data_file__fd(&perf_stat.file);
576
577                 if (is_pipe) {
578                         err = perf_header__write_pipe(perf_data_file__fd(&perf_stat.file));
579                 } else {
580                         err = perf_session__write_header(perf_stat.session, evsel_list,
581                                                          fd, false);
582                 }
583
584                 if (err < 0)
585                         return err;
586
587                 err = perf_stat_synthesize_config(is_pipe);
588                 if (err < 0)
589                         return err;
590         }
591
592         /*
593          * Enable counters and exec the command:
594          */
595         t0 = rdclock();
596         clock_gettime(CLOCK_MONOTONIC, &ref_time);
597
598         if (forks) {
599                 perf_evlist__start_workload(evsel_list);
600                 enable_counters();
601
602                 if (interval) {
603                         while (!waitpid(child_pid, &status, WNOHANG)) {
604                                 nanosleep(&ts, NULL);
605                                 process_interval();
606                         }
607                 }
608                 wait(&status);
609
610                 if (workload_exec_errno) {
611                         const char *emsg = strerror_r(workload_exec_errno, msg, sizeof(msg));
612                         pr_err("Workload failed: %s\n", emsg);
613                         return -1;
614                 }
615
616                 if (WIFSIGNALED(status))
617                         psignal(WTERMSIG(status), argv[0]);
618         } else {
619                 enable_counters();
620                 while (!done) {
621                         nanosleep(&ts, NULL);
622                         if (interval)
623                                 process_interval();
624                 }
625         }
626
627         t1 = rdclock();
628
629         update_stats(&walltime_nsecs_stats, t1 - t0);
630
631         read_counters(true);
632
633         return WEXITSTATUS(status);
634 }
635
636 static int run_perf_stat(int argc, const char **argv)
637 {
638         int ret;
639
640         if (pre_cmd) {
641                 ret = system(pre_cmd);
642                 if (ret)
643                         return ret;
644         }
645
646         if (sync_run)
647                 sync();
648
649         ret = __run_perf_stat(argc, argv);
650         if (ret)
651                 return ret;
652
653         if (post_cmd) {
654                 ret = system(post_cmd);
655                 if (ret)
656                         return ret;
657         }
658
659         return ret;
660 }
661
662 static void print_running(u64 run, u64 ena)
663 {
664         if (csv_output) {
665                 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
666                                         csv_sep,
667                                         run,
668                                         csv_sep,
669                                         ena ? 100.0 * run / ena : 100.0);
670         } else if (run != ena) {
671                 fprintf(stat_config.output, "  (%.2f%%)", 100.0 * run / ena);
672         }
673 }
674
675 static void print_noise_pct(double total, double avg)
676 {
677         double pct = rel_stddev_stats(total, avg);
678
679         if (csv_output)
680                 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
681         else if (pct)
682                 fprintf(stat_config.output, "  ( +-%6.2f%% )", pct);
683 }
684
685 static void print_noise(struct perf_evsel *evsel, double avg)
686 {
687         struct perf_stat_evsel *ps;
688
689         if (run_count == 1)
690                 return;
691
692         ps = evsel->priv;
693         print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
694 }
695
696 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
697 {
698         switch (stat_config.aggr_mode) {
699         case AGGR_CORE:
700                 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
701                         cpu_map__id_to_socket(id),
702                         csv_output ? 0 : -8,
703                         cpu_map__id_to_cpu(id),
704                         csv_sep,
705                         csv_output ? 0 : 4,
706                         nr,
707                         csv_sep);
708                 break;
709         case AGGR_SOCKET:
710                 fprintf(stat_config.output, "S%*d%s%*d%s",
711                         csv_output ? 0 : -5,
712                         id,
713                         csv_sep,
714                         csv_output ? 0 : 4,
715                         nr,
716                         csv_sep);
717                         break;
718         case AGGR_NONE:
719                 fprintf(stat_config.output, "CPU%*d%s",
720                         csv_output ? 0 : -4,
721                         perf_evsel__cpus(evsel)->map[id], csv_sep);
722                 break;
723         case AGGR_THREAD:
724                 fprintf(stat_config.output, "%*s-%*d%s",
725                         csv_output ? 0 : 16,
726                         thread_map__comm(evsel->threads, id),
727                         csv_output ? 0 : -8,
728                         thread_map__pid(evsel->threads, id),
729                         csv_sep);
730                 break;
731         case AGGR_GLOBAL:
732         case AGGR_UNSET:
733         default:
734                 break;
735         }
736 }
737
738 struct outstate {
739         FILE *fh;
740         bool newline;
741         const char *prefix;
742         int  nfields;
743         int  id, nr;
744         struct perf_evsel *evsel;
745 };
746
747 #define METRIC_LEN  35
748
749 static void new_line_std(void *ctx)
750 {
751         struct outstate *os = ctx;
752
753         os->newline = true;
754 }
755
756 static void do_new_line_std(struct outstate *os)
757 {
758         fputc('\n', os->fh);
759         fputs(os->prefix, os->fh);
760         aggr_printout(os->evsel, os->id, os->nr);
761         if (stat_config.aggr_mode == AGGR_NONE)
762                 fprintf(os->fh, "        ");
763         fprintf(os->fh, "                                                 ");
764 }
765
766 static void print_metric_std(void *ctx, const char *color, const char *fmt,
767                              const char *unit, double val)
768 {
769         struct outstate *os = ctx;
770         FILE *out = os->fh;
771         int n;
772         bool newline = os->newline;
773
774         os->newline = false;
775
776         if (unit == NULL || fmt == NULL) {
777                 fprintf(out, "%-*s", METRIC_LEN, "");
778                 return;
779         }
780
781         if (newline)
782                 do_new_line_std(os);
783
784         n = fprintf(out, " # ");
785         if (color)
786                 n += color_fprintf(out, color, fmt, val);
787         else
788                 n += fprintf(out, fmt, val);
789         fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
790 }
791
792 static void new_line_csv(void *ctx)
793 {
794         struct outstate *os = ctx;
795         int i;
796
797         fputc('\n', os->fh);
798         if (os->prefix)
799                 fprintf(os->fh, "%s%s", os->prefix, csv_sep);
800         aggr_printout(os->evsel, os->id, os->nr);
801         for (i = 0; i < os->nfields; i++)
802                 fputs(csv_sep, os->fh);
803 }
804
805 static void print_metric_csv(void *ctx,
806                              const char *color __maybe_unused,
807                              const char *fmt, const char *unit, double val)
808 {
809         struct outstate *os = ctx;
810         FILE *out = os->fh;
811         char buf[64], *vals, *ends;
812
813         if (unit == NULL || fmt == NULL) {
814                 fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
815                 return;
816         }
817         snprintf(buf, sizeof(buf), fmt, val);
818         vals = buf;
819         while (isspace(*vals))
820                 vals++;
821         ends = vals;
822         while (isdigit(*ends) || *ends == '.')
823                 ends++;
824         *ends = 0;
825         while (isspace(*unit))
826                 unit++;
827         fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
828 }
829
830 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
831 {
832         FILE *output = stat_config.output;
833         double msecs = avg / 1e6;
834         const char *fmt_v, *fmt_n;
835         char name[25];
836
837         fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
838         fmt_n = csv_output ? "%s" : "%-25s";
839
840         aggr_printout(evsel, id, nr);
841
842         scnprintf(name, sizeof(name), "%s%s",
843                   perf_evsel__name(evsel), csv_output ? "" : " (msec)");
844
845         fprintf(output, fmt_v, msecs, csv_sep);
846
847         if (csv_output)
848                 fprintf(output, "%s%s", evsel->unit, csv_sep);
849         else
850                 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
851
852         fprintf(output, fmt_n, name);
853
854         if (evsel->cgrp)
855                 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
856 }
857
858 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
859 {
860         int i;
861
862         if (!aggr_get_id)
863                 return 0;
864
865         if (stat_config.aggr_mode == AGGR_NONE)
866                 return id;
867
868         if (stat_config.aggr_mode == AGGR_GLOBAL)
869                 return 0;
870
871         for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
872                 int cpu2 = perf_evsel__cpus(evsel)->map[i];
873
874                 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
875                         return cpu2;
876         }
877         return 0;
878 }
879
880 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
881 {
882         FILE *output = stat_config.output;
883         double sc =  evsel->scale;
884         const char *fmt;
885
886         if (csv_output) {
887                 fmt = sc != 1.0 ?  "%.2f%s" : "%.0f%s";
888         } else {
889                 if (big_num)
890                         fmt = sc != 1.0 ? "%'18.2f%s" : "%'18.0f%s";
891                 else
892                         fmt = sc != 1.0 ? "%18.2f%s" : "%18.0f%s";
893         }
894
895         aggr_printout(evsel, id, nr);
896
897         fprintf(output, fmt, avg, csv_sep);
898
899         if (evsel->unit)
900                 fprintf(output, "%-*s%s",
901                         csv_output ? 0 : unit_width,
902                         evsel->unit, csv_sep);
903
904         fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
905
906         if (evsel->cgrp)
907                 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
908 }
909
910 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
911                      char *prefix, u64 run, u64 ena, double noise)
912 {
913         struct perf_stat_output_ctx out;
914         struct outstate os = {
915                 .fh = stat_config.output,
916                 .prefix = prefix ? prefix : "",
917                 .id = id,
918                 .nr = nr,
919                 .evsel = counter,
920         };
921         print_metric_t pm = print_metric_std;
922         void (*nl)(void *);
923
924         nl = new_line_std;
925
926         if (csv_output) {
927                 static int aggr_fields[] = {
928                         [AGGR_GLOBAL] = 0,
929                         [AGGR_THREAD] = 1,
930                         [AGGR_NONE] = 1,
931                         [AGGR_SOCKET] = 2,
932                         [AGGR_CORE] = 2,
933                 };
934
935                 pm = print_metric_csv;
936                 nl = new_line_csv;
937                 os.nfields = 3;
938                 os.nfields += aggr_fields[stat_config.aggr_mode];
939                 if (counter->cgrp)
940                         os.nfields++;
941         }
942         if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
943                 aggr_printout(counter, id, nr);
944
945                 fprintf(stat_config.output, "%*s%s",
946                         csv_output ? 0 : 18,
947                         counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
948                         csv_sep);
949
950                 fprintf(stat_config.output, "%-*s%s",
951                         csv_output ? 0 : unit_width,
952                         counter->unit, csv_sep);
953
954                 fprintf(stat_config.output, "%*s",
955                         csv_output ? 0 : -25,
956                         perf_evsel__name(counter));
957
958                 if (counter->cgrp)
959                         fprintf(stat_config.output, "%s%s",
960                                 csv_sep, counter->cgrp->name);
961
962                 if (!csv_output)
963                         pm(&os, NULL, NULL, "", 0);
964                 print_noise(counter, noise);
965                 print_running(run, ena);
966                 if (csv_output)
967                         pm(&os, NULL, NULL, "", 0);
968                 return;
969         }
970
971         if (nsec_counter(counter))
972                 nsec_printout(id, nr, counter, uval);
973         else
974                 abs_printout(id, nr, counter, uval);
975
976         out.print_metric = pm;
977         out.new_line = nl;
978         out.ctx = &os;
979
980         if (csv_output) {
981                 print_noise(counter, noise);
982                 print_running(run, ena);
983         }
984
985         perf_stat__print_shadow_stats(counter, uval,
986                                 first_shadow_cpu(counter, id),
987                                 &out);
988         if (!csv_output) {
989                 print_noise(counter, noise);
990                 print_running(run, ena);
991         }
992 }
993
994 static void aggr_update_shadow(void)
995 {
996         int cpu, s2, id, s;
997         u64 val;
998         struct perf_evsel *counter;
999
1000         for (s = 0; s < aggr_map->nr; s++) {
1001                 id = aggr_map->map[s];
1002                 evlist__for_each(evsel_list, counter) {
1003                         val = 0;
1004                         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1005                                 s2 = aggr_get_id(evsel_list->cpus, cpu);
1006                                 if (s2 != id)
1007                                         continue;
1008                                 val += perf_counts(counter->counts, cpu, 0)->val;
1009                         }
1010                         val = val * counter->scale;
1011                         perf_stat__update_shadow_stats(counter, &val,
1012                                                        first_shadow_cpu(counter, id));
1013                 }
1014         }
1015 }
1016
1017 static void print_aggr(char *prefix)
1018 {
1019         FILE *output = stat_config.output;
1020         struct perf_evsel *counter;
1021         int cpu, s, s2, id, nr;
1022         double uval;
1023         u64 ena, run, val;
1024
1025         if (!(aggr_map || aggr_get_id))
1026                 return;
1027
1028         aggr_update_shadow();
1029
1030         for (s = 0; s < aggr_map->nr; s++) {
1031                 id = aggr_map->map[s];
1032                 evlist__for_each(evsel_list, counter) {
1033                         val = ena = run = 0;
1034                         nr = 0;
1035                         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1036                                 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1037                                 if (s2 != id)
1038                                         continue;
1039                                 val += perf_counts(counter->counts, cpu, 0)->val;
1040                                 ena += perf_counts(counter->counts, cpu, 0)->ena;
1041                                 run += perf_counts(counter->counts, cpu, 0)->run;
1042                                 nr++;
1043                         }
1044                         if (prefix)
1045                                 fprintf(output, "%s", prefix);
1046
1047                         uval = val * counter->scale;
1048                         printout(id, nr, counter, uval, prefix, run, ena, 1.0);
1049                         fputc('\n', output);
1050                 }
1051         }
1052 }
1053
1054 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1055 {
1056         FILE *output = stat_config.output;
1057         int nthreads = thread_map__nr(counter->threads);
1058         int ncpus = cpu_map__nr(counter->cpus);
1059         int cpu, thread;
1060         double uval;
1061
1062         for (thread = 0; thread < nthreads; thread++) {
1063                 u64 ena = 0, run = 0, val = 0;
1064
1065                 for (cpu = 0; cpu < ncpus; cpu++) {
1066                         val += perf_counts(counter->counts, cpu, thread)->val;
1067                         ena += perf_counts(counter->counts, cpu, thread)->ena;
1068                         run += perf_counts(counter->counts, cpu, thread)->run;
1069                 }
1070
1071                 if (prefix)
1072                         fprintf(output, "%s", prefix);
1073
1074                 uval = val * counter->scale;
1075                 printout(thread, 0, counter, uval, prefix, run, ena, 1.0);
1076                 fputc('\n', output);
1077         }
1078 }
1079
1080 /*
1081  * Print out the results of a single counter:
1082  * aggregated counts in system-wide mode
1083  */
1084 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1085 {
1086         FILE *output = stat_config.output;
1087         struct perf_stat_evsel *ps = counter->priv;
1088         double avg = avg_stats(&ps->res_stats[0]);
1089         double uval;
1090         double avg_enabled, avg_running;
1091
1092         avg_enabled = avg_stats(&ps->res_stats[1]);
1093         avg_running = avg_stats(&ps->res_stats[2]);
1094
1095         if (prefix)
1096                 fprintf(output, "%s", prefix);
1097
1098         uval = avg * counter->scale;
1099         printout(-1, 0, counter, uval, prefix, avg_running, avg_enabled, avg);
1100         fprintf(output, "\n");
1101 }
1102
1103 /*
1104  * Print out the results of a single counter:
1105  * does not use aggregated count in system-wide
1106  */
1107 static void print_counter(struct perf_evsel *counter, char *prefix)
1108 {
1109         FILE *output = stat_config.output;
1110         u64 ena, run, val;
1111         double uval;
1112         int cpu;
1113
1114         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1115                 val = perf_counts(counter->counts, cpu, 0)->val;
1116                 ena = perf_counts(counter->counts, cpu, 0)->ena;
1117                 run = perf_counts(counter->counts, cpu, 0)->run;
1118
1119                 if (prefix)
1120                         fprintf(output, "%s", prefix);
1121
1122                 uval = val * counter->scale;
1123                 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1124
1125                 fputc('\n', output);
1126         }
1127 }
1128
1129 static void print_interval(char *prefix, struct timespec *ts)
1130 {
1131         FILE *output = stat_config.output;
1132         static int num_print_interval;
1133
1134         sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1135
1136         if (num_print_interval == 0 && !csv_output) {
1137                 switch (stat_config.aggr_mode) {
1138                 case AGGR_SOCKET:
1139                         fprintf(output, "#           time socket cpus             counts %*s events\n", unit_width, "unit");
1140                         break;
1141                 case AGGR_CORE:
1142                         fprintf(output, "#           time core         cpus             counts %*s events\n", unit_width, "unit");
1143                         break;
1144                 case AGGR_NONE:
1145                         fprintf(output, "#           time CPU                counts %*s events\n", unit_width, "unit");
1146                         break;
1147                 case AGGR_THREAD:
1148                         fprintf(output, "#           time             comm-pid                  counts %*s events\n", unit_width, "unit");
1149                         break;
1150                 case AGGR_GLOBAL:
1151                 default:
1152                         fprintf(output, "#           time             counts %*s events\n", unit_width, "unit");
1153                 case AGGR_UNSET:
1154                         break;
1155                 }
1156         }
1157
1158         if (++num_print_interval == 25)
1159                 num_print_interval = 0;
1160 }
1161
1162 static void print_header(int argc, const char **argv)
1163 {
1164         FILE *output = stat_config.output;
1165         int i;
1166
1167         fflush(stdout);
1168
1169         if (!csv_output) {
1170                 fprintf(output, "\n");
1171                 fprintf(output, " Performance counter stats for ");
1172                 if (target.system_wide)
1173                         fprintf(output, "\'system wide");
1174                 else if (target.cpu_list)
1175                         fprintf(output, "\'CPU(s) %s", target.cpu_list);
1176                 else if (!target__has_task(&target)) {
1177                         fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1178                         for (i = 1; argv && (i < argc); i++)
1179                                 fprintf(output, " %s", argv[i]);
1180                 } else if (target.pid)
1181                         fprintf(output, "process id \'%s", target.pid);
1182                 else
1183                         fprintf(output, "thread id \'%s", target.tid);
1184
1185                 fprintf(output, "\'");
1186                 if (run_count > 1)
1187                         fprintf(output, " (%d runs)", run_count);
1188                 fprintf(output, ":\n\n");
1189         }
1190 }
1191
1192 static void print_footer(void)
1193 {
1194         FILE *output = stat_config.output;
1195
1196         if (!null_run)
1197                 fprintf(output, "\n");
1198         fprintf(output, " %17.9f seconds time elapsed",
1199                         avg_stats(&walltime_nsecs_stats)/1e9);
1200         if (run_count > 1) {
1201                 fprintf(output, "                                        ");
1202                 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1203                                 avg_stats(&walltime_nsecs_stats));
1204         }
1205         fprintf(output, "\n\n");
1206 }
1207
1208 static void print_counters(struct timespec *ts, int argc, const char **argv)
1209 {
1210         int interval = stat_config.interval;
1211         struct perf_evsel *counter;
1212         char buf[64], *prefix = NULL;
1213
1214         /* Do not print anything if we record to the pipe. */
1215         if (STAT_RECORD && perf_stat.file.is_pipe)
1216                 return;
1217
1218         if (interval)
1219                 print_interval(prefix = buf, ts);
1220         else
1221                 print_header(argc, argv);
1222
1223         switch (stat_config.aggr_mode) {
1224         case AGGR_CORE:
1225         case AGGR_SOCKET:
1226                 print_aggr(prefix);
1227                 break;
1228         case AGGR_THREAD:
1229                 evlist__for_each(evsel_list, counter)
1230                         print_aggr_thread(counter, prefix);
1231                 break;
1232         case AGGR_GLOBAL:
1233                 evlist__for_each(evsel_list, counter)
1234                         print_counter_aggr(counter, prefix);
1235                 break;
1236         case AGGR_NONE:
1237                 evlist__for_each(evsel_list, counter)
1238                         print_counter(counter, prefix);
1239                 break;
1240         case AGGR_UNSET:
1241         default:
1242                 break;
1243         }
1244
1245         if (!interval && !csv_output)
1246                 print_footer();
1247
1248         fflush(stat_config.output);
1249 }
1250
1251 static volatile int signr = -1;
1252
1253 static void skip_signal(int signo)
1254 {
1255         if ((child_pid == -1) || stat_config.interval)
1256                 done = 1;
1257
1258         signr = signo;
1259         /*
1260          * render child_pid harmless
1261          * won't send SIGTERM to a random
1262          * process in case of race condition
1263          * and fast PID recycling
1264          */
1265         child_pid = -1;
1266 }
1267
1268 static void sig_atexit(void)
1269 {
1270         sigset_t set, oset;
1271
1272         /*
1273          * avoid race condition with SIGCHLD handler
1274          * in skip_signal() which is modifying child_pid
1275          * goal is to avoid send SIGTERM to a random
1276          * process
1277          */
1278         sigemptyset(&set);
1279         sigaddset(&set, SIGCHLD);
1280         sigprocmask(SIG_BLOCK, &set, &oset);
1281
1282         if (child_pid != -1)
1283                 kill(child_pid, SIGTERM);
1284
1285         sigprocmask(SIG_SETMASK, &oset, NULL);
1286
1287         if (signr == -1)
1288                 return;
1289
1290         signal(signr, SIG_DFL);
1291         kill(getpid(), signr);
1292 }
1293
1294 static int stat__set_big_num(const struct option *opt __maybe_unused,
1295                              const char *s __maybe_unused, int unset)
1296 {
1297         big_num_opt = unset ? 0 : 1;
1298         return 0;
1299 }
1300
1301 static const struct option stat_options[] = {
1302         OPT_BOOLEAN('T', "transaction", &transaction_run,
1303                     "hardware transaction statistics"),
1304         OPT_CALLBACK('e', "event", &evsel_list, "event",
1305                      "event selector. use 'perf list' to list available events",
1306                      parse_events_option),
1307         OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1308                      "event filter", parse_filter),
1309         OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1310                     "child tasks do not inherit counters"),
1311         OPT_STRING('p', "pid", &target.pid, "pid",
1312                    "stat events on existing process id"),
1313         OPT_STRING('t', "tid", &target.tid, "tid",
1314                    "stat events on existing thread id"),
1315         OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1316                     "system-wide collection from all CPUs"),
1317         OPT_BOOLEAN('g', "group", &group,
1318                     "put the counters into a counter group"),
1319         OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1320         OPT_INCR('v', "verbose", &verbose,
1321                     "be more verbose (show counter open errors, etc)"),
1322         OPT_INTEGER('r', "repeat", &run_count,
1323                     "repeat command and print average + stddev (max: 100, forever: 0)"),
1324         OPT_BOOLEAN('n', "null", &null_run,
1325                     "null run - dont start any counters"),
1326         OPT_INCR('d', "detailed", &detailed_run,
1327                     "detailed run - start a lot of events"),
1328         OPT_BOOLEAN('S', "sync", &sync_run,
1329                     "call sync() before starting a run"),
1330         OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1331                            "print large numbers with thousands\' separators",
1332                            stat__set_big_num),
1333         OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1334                     "list of cpus to monitor in system-wide"),
1335         OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1336                     "disable CPU count aggregation", AGGR_NONE),
1337         OPT_STRING('x', "field-separator", &csv_sep, "separator",
1338                    "print counts with custom separator"),
1339         OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1340                      "monitor event in cgroup name only", parse_cgroups),
1341         OPT_STRING('o', "output", &output_name, "file", "output file name"),
1342         OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1343         OPT_INTEGER(0, "log-fd", &output_fd,
1344                     "log output to fd, instead of stderr"),
1345         OPT_STRING(0, "pre", &pre_cmd, "command",
1346                         "command to run prior to the measured command"),
1347         OPT_STRING(0, "post", &post_cmd, "command",
1348                         "command to run after to the measured command"),
1349         OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1350                     "print counts at regular interval in ms (>= 10)"),
1351         OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1352                      "aggregate counts per processor socket", AGGR_SOCKET),
1353         OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1354                      "aggregate counts per physical processor core", AGGR_CORE),
1355         OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1356                      "aggregate counts per thread", AGGR_THREAD),
1357         OPT_UINTEGER('D', "delay", &initial_delay,
1358                      "ms to wait before starting measurement after program start"),
1359         OPT_END()
1360 };
1361
1362 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1363 {
1364         return cpu_map__get_socket(map, cpu, NULL);
1365 }
1366
1367 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1368 {
1369         return cpu_map__get_core(map, cpu, NULL);
1370 }
1371
1372 static int cpu_map__get_max(struct cpu_map *map)
1373 {
1374         int i, max = -1;
1375
1376         for (i = 0; i < map->nr; i++) {
1377                 if (map->map[i] > max)
1378                         max = map->map[i];
1379         }
1380
1381         return max;
1382 }
1383
1384 static struct cpu_map *cpus_aggr_map;
1385
1386 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1387 {
1388         int cpu;
1389
1390         if (idx >= map->nr)
1391                 return -1;
1392
1393         cpu = map->map[idx];
1394
1395         if (cpus_aggr_map->map[cpu] == -1)
1396                 cpus_aggr_map->map[cpu] = get_id(map, idx);
1397
1398         return cpus_aggr_map->map[cpu];
1399 }
1400
1401 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1402 {
1403         return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1404 }
1405
1406 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1407 {
1408         return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1409 }
1410
1411 static int perf_stat_init_aggr_mode(void)
1412 {
1413         int nr;
1414
1415         switch (stat_config.aggr_mode) {
1416         case AGGR_SOCKET:
1417                 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1418                         perror("cannot build socket map");
1419                         return -1;
1420                 }
1421                 aggr_get_id = perf_stat__get_socket_cached;
1422                 break;
1423         case AGGR_CORE:
1424                 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1425                         perror("cannot build core map");
1426                         return -1;
1427                 }
1428                 aggr_get_id = perf_stat__get_core_cached;
1429                 break;
1430         case AGGR_NONE:
1431         case AGGR_GLOBAL:
1432         case AGGR_THREAD:
1433         case AGGR_UNSET:
1434         default:
1435                 break;
1436         }
1437
1438         /*
1439          * The evsel_list->cpus is the base we operate on,
1440          * taking the highest cpu number to be the size of
1441          * the aggregation translate cpumap.
1442          */
1443         nr = cpu_map__get_max(evsel_list->cpus);
1444         cpus_aggr_map = cpu_map__empty_new(nr + 1);
1445         return cpus_aggr_map ? 0 : -ENOMEM;
1446 }
1447
1448 static void perf_stat__exit_aggr_mode(void)
1449 {
1450         cpu_map__put(aggr_map);
1451         cpu_map__put(cpus_aggr_map);
1452         aggr_map = NULL;
1453         cpus_aggr_map = NULL;
1454 }
1455
1456 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1457 {
1458         int cpu;
1459
1460         if (idx > map->nr)
1461                 return -1;
1462
1463         cpu = map->map[idx];
1464
1465         if (cpu >= env->nr_cpus_online)
1466                 return -1;
1467
1468         return cpu;
1469 }
1470
1471 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1472 {
1473         struct perf_env *env = data;
1474         int cpu = perf_env__get_cpu(env, map, idx);
1475
1476         return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1477 }
1478
1479 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1480 {
1481         struct perf_env *env = data;
1482         int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1483
1484         if (cpu != -1) {
1485                 int socket_id = env->cpu[cpu].socket_id;
1486
1487                 /*
1488                  * Encode socket in upper 16 bits
1489                  * core_id is relative to socket, and
1490                  * we need a global id. So we combine
1491                  * socket + core id.
1492                  */
1493                 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1494         }
1495
1496         return core;
1497 }
1498
1499 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1500                                       struct cpu_map **sockp)
1501 {
1502         return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1503 }
1504
1505 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
1506                                     struct cpu_map **corep)
1507 {
1508         return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1509 }
1510
1511 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
1512 {
1513         return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1514 }
1515
1516 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
1517 {
1518         return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1519 }
1520
1521 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1522 {
1523         struct perf_env *env = &st->session->header.env;
1524
1525         switch (stat_config.aggr_mode) {
1526         case AGGR_SOCKET:
1527                 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
1528                         perror("cannot build socket map");
1529                         return -1;
1530                 }
1531                 aggr_get_id = perf_stat__get_socket_file;
1532                 break;
1533         case AGGR_CORE:
1534                 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
1535                         perror("cannot build core map");
1536                         return -1;
1537                 }
1538                 aggr_get_id = perf_stat__get_core_file;
1539                 break;
1540         case AGGR_NONE:
1541         case AGGR_GLOBAL:
1542         case AGGR_THREAD:
1543         case AGGR_UNSET:
1544         default:
1545                 break;
1546         }
1547
1548         return 0;
1549 }
1550
1551 /*
1552  * Add default attributes, if there were no attributes specified or
1553  * if -d/--detailed, -d -d or -d -d -d is used:
1554  */
1555 static int add_default_attributes(void)
1556 {
1557         struct perf_event_attr default_attrs0[] = {
1558
1559   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK              },
1560   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES        },
1561   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS          },
1562   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS             },
1563
1564   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES              },
1565 };
1566         struct perf_event_attr frontend_attrs[] = {
1567   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1568 };
1569         struct perf_event_attr backend_attrs[] = {
1570   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND  },
1571 };
1572         struct perf_event_attr default_attrs1[] = {
1573   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS            },
1574   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS     },
1575   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES           },
1576
1577 };
1578
1579 /*
1580  * Detailed stats (-d), covering the L1 and last level data caches:
1581  */
1582         struct perf_event_attr detailed_attrs[] = {
1583
1584   { .type = PERF_TYPE_HW_CACHE,
1585     .config =
1586          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1587         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1588         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1589
1590   { .type = PERF_TYPE_HW_CACHE,
1591     .config =
1592          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1593         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1594         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1595
1596   { .type = PERF_TYPE_HW_CACHE,
1597     .config =
1598          PERF_COUNT_HW_CACHE_LL                 <<  0  |
1599         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1600         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1601
1602   { .type = PERF_TYPE_HW_CACHE,
1603     .config =
1604          PERF_COUNT_HW_CACHE_LL                 <<  0  |
1605         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1606         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1607 };
1608
1609 /*
1610  * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1611  */
1612         struct perf_event_attr very_detailed_attrs[] = {
1613
1614   { .type = PERF_TYPE_HW_CACHE,
1615     .config =
1616          PERF_COUNT_HW_CACHE_L1I                <<  0  |
1617         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1618         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1619
1620   { .type = PERF_TYPE_HW_CACHE,
1621     .config =
1622          PERF_COUNT_HW_CACHE_L1I                <<  0  |
1623         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1624         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1625
1626   { .type = PERF_TYPE_HW_CACHE,
1627     .config =
1628          PERF_COUNT_HW_CACHE_DTLB               <<  0  |
1629         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1630         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1631
1632   { .type = PERF_TYPE_HW_CACHE,
1633     .config =
1634          PERF_COUNT_HW_CACHE_DTLB               <<  0  |
1635         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1636         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1637
1638   { .type = PERF_TYPE_HW_CACHE,
1639     .config =
1640          PERF_COUNT_HW_CACHE_ITLB               <<  0  |
1641         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1642         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1643
1644   { .type = PERF_TYPE_HW_CACHE,
1645     .config =
1646          PERF_COUNT_HW_CACHE_ITLB               <<  0  |
1647         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1648         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1649
1650 };
1651
1652 /*
1653  * Very, very detailed stats (-d -d -d), adding prefetch events:
1654  */
1655         struct perf_event_attr very_very_detailed_attrs[] = {
1656
1657   { .type = PERF_TYPE_HW_CACHE,
1658     .config =
1659          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1660         (PERF_COUNT_HW_CACHE_OP_PREFETCH        <<  8) |
1661         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1662
1663   { .type = PERF_TYPE_HW_CACHE,
1664     .config =
1665          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1666         (PERF_COUNT_HW_CACHE_OP_PREFETCH        <<  8) |
1667         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1668 };
1669
1670         /* Set attrs if no event is selected and !null_run: */
1671         if (null_run)
1672                 return 0;
1673
1674         if (transaction_run) {
1675                 int err;
1676                 if (pmu_have_event("cpu", "cycles-ct") &&
1677                     pmu_have_event("cpu", "el-start"))
1678                         err = parse_events(evsel_list, transaction_attrs, NULL);
1679                 else
1680                         err = parse_events(evsel_list, transaction_limited_attrs, NULL);
1681                 if (err) {
1682                         fprintf(stderr, "Cannot set up transaction events\n");
1683                         return -1;
1684                 }
1685                 return 0;
1686         }
1687
1688         if (!evsel_list->nr_entries) {
1689                 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
1690                         return -1;
1691                 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
1692                         if (perf_evlist__add_default_attrs(evsel_list,
1693                                                 frontend_attrs) < 0)
1694                                 return -1;
1695                 }
1696                 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
1697                         if (perf_evlist__add_default_attrs(evsel_list,
1698                                                 backend_attrs) < 0)
1699                                 return -1;
1700                 }
1701                 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
1702                         return -1;
1703         }
1704
1705         /* Detailed events get appended to the event list: */
1706
1707         if (detailed_run <  1)
1708                 return 0;
1709
1710         /* Append detailed run extra attributes: */
1711         if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1712                 return -1;
1713
1714         if (detailed_run < 2)
1715                 return 0;
1716
1717         /* Append very detailed run extra attributes: */
1718         if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1719                 return -1;
1720
1721         if (detailed_run < 3)
1722                 return 0;
1723
1724         /* Append very, very detailed run extra attributes: */
1725         return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1726 }
1727
1728 static const char * const stat_record_usage[] = {
1729         "perf stat record [<options>]",
1730         NULL,
1731 };
1732
1733 static void init_features(struct perf_session *session)
1734 {
1735         int feat;
1736
1737         for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
1738                 perf_header__set_feat(&session->header, feat);
1739
1740         perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
1741         perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
1742         perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
1743         perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
1744 }
1745
1746 static int __cmd_record(int argc, const char **argv)
1747 {
1748         struct perf_session *session;
1749         struct perf_data_file *file = &perf_stat.file;
1750
1751         argc = parse_options(argc, argv, stat_options, stat_record_usage,
1752                              PARSE_OPT_STOP_AT_NON_OPTION);
1753
1754         if (output_name)
1755                 file->path = output_name;
1756
1757         if (run_count != 1 || forever) {
1758                 pr_err("Cannot use -r option with perf stat record.\n");
1759                 return -1;
1760         }
1761
1762         session = perf_session__new(file, false, NULL);
1763         if (session == NULL) {
1764                 pr_err("Perf session creation failed.\n");
1765                 return -1;
1766         }
1767
1768         init_features(session);
1769
1770         session->evlist   = evsel_list;
1771         perf_stat.session = session;
1772         perf_stat.record  = true;
1773         return argc;
1774 }
1775
1776 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
1777                                     union perf_event *event,
1778                                     struct perf_session *session)
1779 {
1780         struct stat_round_event *round = &event->stat_round;
1781         struct perf_evsel *counter;
1782         struct timespec tsh, *ts = NULL;
1783         const char **argv = session->header.env.cmdline_argv;
1784         int argc = session->header.env.nr_cmdline;
1785
1786         evlist__for_each(evsel_list, counter)
1787                 perf_stat_process_counter(&stat_config, counter);
1788
1789         if (round->type == PERF_STAT_ROUND_TYPE__FINAL)
1790                 update_stats(&walltime_nsecs_stats, round->time);
1791
1792         if (stat_config.interval && round->time) {
1793                 tsh.tv_sec  = round->time / NSECS_PER_SEC;
1794                 tsh.tv_nsec = round->time % NSECS_PER_SEC;
1795                 ts = &tsh;
1796         }
1797
1798         print_counters(ts, argc, argv);
1799         return 0;
1800 }
1801
1802 static
1803 int process_stat_config_event(struct perf_tool *tool __maybe_unused,
1804                               union perf_event *event,
1805                               struct perf_session *session __maybe_unused)
1806 {
1807         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1808
1809         perf_event__read_stat_config(&stat_config, &event->stat_config);
1810
1811         if (cpu_map__empty(st->cpus)) {
1812                 if (st->aggr_mode != AGGR_UNSET)
1813                         pr_warning("warning: processing task data, aggregation mode not set\n");
1814                 return 0;
1815         }
1816
1817         if (st->aggr_mode != AGGR_UNSET)
1818                 stat_config.aggr_mode = st->aggr_mode;
1819
1820         if (perf_stat.file.is_pipe)
1821                 perf_stat_init_aggr_mode();
1822         else
1823                 perf_stat_init_aggr_mode_file(st);
1824
1825         return 0;
1826 }
1827
1828 static int set_maps(struct perf_stat *st)
1829 {
1830         if (!st->cpus || !st->threads)
1831                 return 0;
1832
1833         if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
1834                 return -EINVAL;
1835
1836         perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
1837
1838         if (perf_evlist__alloc_stats(evsel_list, true))
1839                 return -ENOMEM;
1840
1841         st->maps_allocated = true;
1842         return 0;
1843 }
1844
1845 static
1846 int process_thread_map_event(struct perf_tool *tool __maybe_unused,
1847                              union perf_event *event,
1848                              struct perf_session *session __maybe_unused)
1849 {
1850         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1851
1852         if (st->threads) {
1853                 pr_warning("Extra thread map event, ignoring.\n");
1854                 return 0;
1855         }
1856
1857         st->threads = thread_map__new_event(&event->thread_map);
1858         if (!st->threads)
1859                 return -ENOMEM;
1860
1861         return set_maps(st);
1862 }
1863
1864 static
1865 int process_cpu_map_event(struct perf_tool *tool __maybe_unused,
1866                           union perf_event *event,
1867                           struct perf_session *session __maybe_unused)
1868 {
1869         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1870         struct cpu_map *cpus;
1871
1872         if (st->cpus) {
1873                 pr_warning("Extra cpu map event, ignoring.\n");
1874                 return 0;
1875         }
1876
1877         cpus = cpu_map__new_data(&event->cpu_map.data);
1878         if (!cpus)
1879                 return -ENOMEM;
1880
1881         st->cpus = cpus;
1882         return set_maps(st);
1883 }
1884
1885 static const char * const stat_report_usage[] = {
1886         "perf stat report [<options>]",
1887         NULL,
1888 };
1889
1890 static struct perf_stat perf_stat = {
1891         .tool = {
1892                 .attr           = perf_event__process_attr,
1893                 .event_update   = perf_event__process_event_update,
1894                 .thread_map     = process_thread_map_event,
1895                 .cpu_map        = process_cpu_map_event,
1896                 .stat_config    = process_stat_config_event,
1897                 .stat           = perf_event__process_stat_event,
1898                 .stat_round     = process_stat_round_event,
1899         },
1900         .aggr_mode = AGGR_UNSET,
1901 };
1902
1903 static int __cmd_report(int argc, const char **argv)
1904 {
1905         struct perf_session *session;
1906         const struct option options[] = {
1907         OPT_STRING('i', "input", &input_name, "file", "input file name"),
1908         OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
1909                      "aggregate counts per processor socket", AGGR_SOCKET),
1910         OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
1911                      "aggregate counts per physical processor core", AGGR_CORE),
1912         OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
1913                      "disable CPU count aggregation", AGGR_NONE),
1914         OPT_END()
1915         };
1916         struct stat st;
1917         int ret;
1918
1919         argc = parse_options(argc, argv, options, stat_report_usage, 0);
1920
1921         if (!input_name || !strlen(input_name)) {
1922                 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
1923                         input_name = "-";
1924                 else
1925                         input_name = "perf.data";
1926         }
1927
1928         perf_stat.file.path = input_name;
1929         perf_stat.file.mode = PERF_DATA_MODE_READ;
1930
1931         session = perf_session__new(&perf_stat.file, false, &perf_stat.tool);
1932         if (session == NULL)
1933                 return -1;
1934
1935         perf_stat.session  = session;
1936         stat_config.output = stderr;
1937         evsel_list         = session->evlist;
1938
1939         ret = perf_session__process_events(session);
1940         if (ret)
1941                 return ret;
1942
1943         perf_session__delete(session);
1944         return 0;
1945 }
1946
1947 int cmd_stat(int argc, const char **argv, const char *prefix __maybe_unused)
1948 {
1949         const char * const stat_usage[] = {
1950                 "perf stat [<options>] [<command>]",
1951                 NULL
1952         };
1953         int status = -EINVAL, run_idx;
1954         const char *mode;
1955         FILE *output = stderr;
1956         unsigned int interval;
1957         const char * const stat_subcommands[] = { "record", "report" };
1958
1959         setlocale(LC_ALL, "");
1960
1961         evsel_list = perf_evlist__new();
1962         if (evsel_list == NULL)
1963                 return -ENOMEM;
1964
1965         parse_events__shrink_config_terms();
1966         argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
1967                                         (const char **) stat_usage,
1968                                         PARSE_OPT_STOP_AT_NON_OPTION);
1969         perf_stat__init_shadow_stats();
1970
1971         if (csv_sep) {
1972                 csv_output = true;
1973                 if (!strcmp(csv_sep, "\\t"))
1974                         csv_sep = "\t";
1975         } else
1976                 csv_sep = DEFAULT_SEPARATOR;
1977
1978         if (argc && !strncmp(argv[0], "rec", 3)) {
1979                 argc = __cmd_record(argc, argv);
1980                 if (argc < 0)
1981                         return -1;
1982         } else if (argc && !strncmp(argv[0], "rep", 3))
1983                 return __cmd_report(argc, argv);
1984
1985         interval = stat_config.interval;
1986
1987         /*
1988          * For record command the -o is already taken care of.
1989          */
1990         if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
1991                 output = NULL;
1992
1993         if (output_name && output_fd) {
1994                 fprintf(stderr, "cannot use both --output and --log-fd\n");
1995                 parse_options_usage(stat_usage, stat_options, "o", 1);
1996                 parse_options_usage(NULL, stat_options, "log-fd", 0);
1997                 goto out;
1998         }
1999
2000         if (output_fd < 0) {
2001                 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2002                 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2003                 goto out;
2004         }
2005
2006         if (!output) {
2007                 struct timespec tm;
2008                 mode = append_file ? "a" : "w";
2009
2010                 output = fopen(output_name, mode);
2011                 if (!output) {
2012                         perror("failed to create output file");
2013                         return -1;
2014                 }
2015                 clock_gettime(CLOCK_REALTIME, &tm);
2016                 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2017         } else if (output_fd > 0) {
2018                 mode = append_file ? "a" : "w";
2019                 output = fdopen(output_fd, mode);
2020                 if (!output) {
2021                         perror("Failed opening logfd");
2022                         return -errno;
2023                 }
2024         }
2025
2026         stat_config.output = output;
2027
2028         /*
2029          * let the spreadsheet do the pretty-printing
2030          */
2031         if (csv_output) {
2032                 /* User explicitly passed -B? */
2033                 if (big_num_opt == 1) {
2034                         fprintf(stderr, "-B option not supported with -x\n");
2035                         parse_options_usage(stat_usage, stat_options, "B", 1);
2036                         parse_options_usage(NULL, stat_options, "x", 1);
2037                         goto out;
2038                 } else /* Nope, so disable big number formatting */
2039                         big_num = false;
2040         } else if (big_num_opt == 0) /* User passed --no-big-num */
2041                 big_num = false;
2042
2043         if (!argc && target__none(&target))
2044                 usage_with_options(stat_usage, stat_options);
2045
2046         if (run_count < 0) {
2047                 pr_err("Run count must be a positive number\n");
2048                 parse_options_usage(stat_usage, stat_options, "r", 1);
2049                 goto out;
2050         } else if (run_count == 0) {
2051                 forever = true;
2052                 run_count = 1;
2053         }
2054
2055         if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
2056                 fprintf(stderr, "The --per-thread option is only available "
2057                         "when monitoring via -p -t options.\n");
2058                 parse_options_usage(NULL, stat_options, "p", 1);
2059                 parse_options_usage(NULL, stat_options, "t", 1);
2060                 goto out;
2061         }
2062
2063         /*
2064          * no_aggr, cgroup are for system-wide only
2065          * --per-thread is aggregated per thread, we dont mix it with cpu mode
2066          */
2067         if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2068               stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2069             !target__has_cpu(&target)) {
2070                 fprintf(stderr, "both cgroup and no-aggregation "
2071                         "modes only available in system-wide mode\n");
2072
2073                 parse_options_usage(stat_usage, stat_options, "G", 1);
2074                 parse_options_usage(NULL, stat_options, "A", 1);
2075                 parse_options_usage(NULL, stat_options, "a", 1);
2076                 goto out;
2077         }
2078
2079         if (add_default_attributes())
2080                 goto out;
2081
2082         target__validate(&target);
2083
2084         if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2085                 if (target__has_task(&target)) {
2086                         pr_err("Problems finding threads of monitor\n");
2087                         parse_options_usage(stat_usage, stat_options, "p", 1);
2088                         parse_options_usage(NULL, stat_options, "t", 1);
2089                 } else if (target__has_cpu(&target)) {
2090                         perror("failed to parse CPUs map");
2091                         parse_options_usage(stat_usage, stat_options, "C", 1);
2092                         parse_options_usage(NULL, stat_options, "a", 1);
2093                 }
2094                 goto out;
2095         }
2096
2097         /*
2098          * Initialize thread_map with comm names,
2099          * so we could print it out on output.
2100          */
2101         if (stat_config.aggr_mode == AGGR_THREAD)
2102                 thread_map__read_comms(evsel_list->threads);
2103
2104         if (interval && interval < 100) {
2105                 if (interval < 10) {
2106                         pr_err("print interval must be >= 10ms\n");
2107                         parse_options_usage(stat_usage, stat_options, "I", 1);
2108                         goto out;
2109                 } else
2110                         pr_warning("print interval < 100ms. "
2111                                    "The overhead percentage could be high in some cases. "
2112                                    "Please proceed with caution.\n");
2113         }
2114
2115         if (perf_evlist__alloc_stats(evsel_list, interval))
2116                 goto out;
2117
2118         if (perf_stat_init_aggr_mode())
2119                 goto out;
2120
2121         /*
2122          * We dont want to block the signals - that would cause
2123          * child tasks to inherit that and Ctrl-C would not work.
2124          * What we want is for Ctrl-C to work in the exec()-ed
2125          * task, but being ignored by perf stat itself:
2126          */
2127         atexit(sig_atexit);
2128         if (!forever)
2129                 signal(SIGINT,  skip_signal);
2130         signal(SIGCHLD, skip_signal);
2131         signal(SIGALRM, skip_signal);
2132         signal(SIGABRT, skip_signal);
2133
2134         status = 0;
2135         for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2136                 if (run_count != 1 && verbose)
2137                         fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2138                                 run_idx + 1);
2139
2140                 status = run_perf_stat(argc, argv);
2141                 if (forever && status != -1) {
2142                         print_counters(NULL, argc, argv);
2143                         perf_stat__reset_stats();
2144                 }
2145         }
2146
2147         if (!forever && status != -1 && !interval)
2148                 print_counters(NULL, argc, argv);
2149
2150         if (STAT_RECORD) {
2151                 /*
2152                  * We synthesize the kernel mmap record just so that older tools
2153                  * don't emit warnings about not being able to resolve symbols
2154                  * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2155                  * a saner message about no samples being in the perf.data file.
2156                  *
2157                  * This also serves to suppress a warning about f_header.data.size == 0
2158                  * in header.c at the moment 'perf stat record' gets introduced, which
2159                  * is not really needed once we start adding the stat specific PERF_RECORD_
2160                  * records, but the need to suppress the kptr_restrict messages in older
2161                  * tools remain  -acme
2162                  */
2163                 int fd = perf_data_file__fd(&perf_stat.file);
2164                 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2165                                                              process_synthesized_event,
2166                                                              &perf_stat.session->machines.host);
2167                 if (err) {
2168                         pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2169                                    "older tools may produce warnings about this file\n.");
2170                 }
2171
2172                 if (!interval) {
2173                         if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2174                                 pr_err("failed to write stat round event\n");
2175                 }
2176
2177                 if (!perf_stat.file.is_pipe) {
2178                         perf_stat.session->header.data_size += perf_stat.bytes_written;
2179                         perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2180                 }
2181
2182                 perf_session__delete(perf_stat.session);
2183         }
2184
2185         perf_stat__exit_aggr_mode();
2186         perf_evlist__free_stats(evsel_list);
2187 out:
2188         perf_evlist__delete(evsel_list);
2189         return status;
2190 }