perf stat: Remove --per-thread pid/tid limitation
[linux-2.6-microblaze.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/drv_configs.h"
56 #include "util/color.h"
57 #include "util/stat.h"
58 #include "util/header.h"
59 #include "util/cpumap.h"
60 #include "util/thread.h"
61 #include "util/thread_map.h"
62 #include "util/counts.h"
63 #include "util/group.h"
64 #include "util/session.h"
65 #include "util/tool.h"
66 #include "util/group.h"
67 #include "util/string2.h"
68 #include "util/metricgroup.h"
69 #include "asm/bug.h"
70
71 #include <linux/time64.h>
72 #include <api/fs/fs.h>
73 #include <errno.h>
74 #include <signal.h>
75 #include <stdlib.h>
76 #include <sys/prctl.h>
77 #include <inttypes.h>
78 #include <locale.h>
79 #include <math.h>
80 #include <sys/types.h>
81 #include <sys/stat.h>
82 #include <sys/wait.h>
83 #include <unistd.h>
84
85 #include "sane_ctype.h"
86
87 #define DEFAULT_SEPARATOR       " "
88 #define CNTR_NOT_SUPPORTED      "<not supported>"
89 #define CNTR_NOT_COUNTED        "<not counted>"
90 #define FREEZE_ON_SMI_PATH      "devices/cpu/freeze_on_smi"
91
92 static void print_counters(struct timespec *ts, int argc, const char **argv);
93
94 /* Default events used for perf stat -T */
95 static const char *transaction_attrs = {
96         "task-clock,"
97         "{"
98         "instructions,"
99         "cycles,"
100         "cpu/cycles-t/,"
101         "cpu/tx-start/,"
102         "cpu/el-start/,"
103         "cpu/cycles-ct/"
104         "}"
105 };
106
107 /* More limited version when the CPU does not have all events. */
108 static const char * transaction_limited_attrs = {
109         "task-clock,"
110         "{"
111         "instructions,"
112         "cycles,"
113         "cpu/cycles-t/,"
114         "cpu/tx-start/"
115         "}"
116 };
117
118 static const char * topdown_attrs[] = {
119         "topdown-total-slots",
120         "topdown-slots-retired",
121         "topdown-recovery-bubbles",
122         "topdown-fetch-bubbles",
123         "topdown-slots-issued",
124         NULL,
125 };
126
127 static const char *smi_cost_attrs = {
128         "{"
129         "msr/aperf/,"
130         "msr/smi/,"
131         "cycles"
132         "}"
133 };
134
135 static struct perf_evlist       *evsel_list;
136
137 static struct rblist             metric_events;
138
139 static struct target target = {
140         .uid    = UINT_MAX,
141 };
142
143 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
144
145 static int                      run_count                       =  1;
146 static bool                     no_inherit                      = false;
147 static volatile pid_t           child_pid                       = -1;
148 static bool                     null_run                        =  false;
149 static int                      detailed_run                    =  0;
150 static bool                     transaction_run;
151 static bool                     topdown_run                     = false;
152 static bool                     smi_cost                        = false;
153 static bool                     smi_reset                       = false;
154 static bool                     big_num                         =  true;
155 static int                      big_num_opt                     =  -1;
156 static const char               *csv_sep                        = NULL;
157 static bool                     csv_output                      = false;
158 static bool                     group                           = false;
159 static const char               *pre_cmd                        = NULL;
160 static const char               *post_cmd                       = NULL;
161 static bool                     sync_run                        = false;
162 static unsigned int             initial_delay                   = 0;
163 static unsigned int             unit_width                      = 4; /* strlen("unit") */
164 static bool                     forever                         = false;
165 static bool                     metric_only                     = false;
166 static bool                     force_metric_only               = false;
167 static bool                     no_merge                        = false;
168 static struct timespec          ref_time;
169 static struct cpu_map           *aggr_map;
170 static aggr_get_id_t            aggr_get_id;
171 static bool                     append_file;
172 static const char               *output_name;
173 static int                      output_fd;
174 static int                      print_free_counters_hint;
175
176 struct perf_stat {
177         bool                     record;
178         struct perf_data         data;
179         struct perf_session     *session;
180         u64                      bytes_written;
181         struct perf_tool         tool;
182         bool                     maps_allocated;
183         struct cpu_map          *cpus;
184         struct thread_map       *threads;
185         enum aggr_mode           aggr_mode;
186 };
187
188 static struct perf_stat         perf_stat;
189 #define STAT_RECORD             perf_stat.record
190
191 static volatile int done = 0;
192
193 static struct perf_stat_config stat_config = {
194         .aggr_mode      = AGGR_GLOBAL,
195         .scale          = true,
196 };
197
198 static bool is_duration_time(struct perf_evsel *evsel)
199 {
200         return !strcmp(evsel->name, "duration_time");
201 }
202
203 static inline void diff_timespec(struct timespec *r, struct timespec *a,
204                                  struct timespec *b)
205 {
206         r->tv_sec = a->tv_sec - b->tv_sec;
207         if (a->tv_nsec < b->tv_nsec) {
208                 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
209                 r->tv_sec--;
210         } else {
211                 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
212         }
213 }
214
215 static void perf_stat__reset_stats(void)
216 {
217         int i;
218
219         perf_evlist__reset_stats(evsel_list);
220         perf_stat__reset_shadow_stats();
221
222         for (i = 0; i < stat_config.stats_num; i++)
223                 perf_stat__reset_shadow_per_stat(&stat_config.stats[i]);
224 }
225
226 static int create_perf_stat_counter(struct perf_evsel *evsel)
227 {
228         struct perf_event_attr *attr = &evsel->attr;
229         struct perf_evsel *leader = evsel->leader;
230
231         if (stat_config.scale) {
232                 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
233                                     PERF_FORMAT_TOTAL_TIME_RUNNING;
234         }
235
236         /*
237          * The event is part of non trivial group, let's enable
238          * the group read (for leader) and ID retrieval for all
239          * members.
240          */
241         if (leader->nr_members > 1)
242                 attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
243
244         attr->inherit = !no_inherit;
245
246         /*
247          * Some events get initialized with sample_(period/type) set,
248          * like tracepoints. Clear it up for counting.
249          */
250         attr->sample_period = 0;
251
252         /*
253          * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
254          * while avoiding that older tools show confusing messages.
255          *
256          * However for pipe sessions we need to keep it zero,
257          * because script's perf_evsel__check_attr is triggered
258          * by attr->sample_type != 0, and we can't run it on
259          * stat sessions.
260          */
261         if (!(STAT_RECORD && perf_stat.data.is_pipe))
262                 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
263
264         /*
265          * Disabling all counters initially, they will be enabled
266          * either manually by us or by kernel via enable_on_exec
267          * set later.
268          */
269         if (perf_evsel__is_group_leader(evsel)) {
270                 attr->disabled = 1;
271
272                 /*
273                  * In case of initial_delay we enable tracee
274                  * events manually.
275                  */
276                 if (target__none(&target) && !initial_delay)
277                         attr->enable_on_exec = 1;
278         }
279
280         if (target__has_cpu(&target) && !target__has_per_thread(&target))
281                 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
282
283         return perf_evsel__open_per_thread(evsel, evsel_list->threads);
284 }
285
286 /*
287  * Does the counter have nsecs as a unit?
288  */
289 static inline int nsec_counter(struct perf_evsel *evsel)
290 {
291         if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
292             perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
293                 return 1;
294
295         return 0;
296 }
297
298 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
299                                      union perf_event *event,
300                                      struct perf_sample *sample __maybe_unused,
301                                      struct machine *machine __maybe_unused)
302 {
303         if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
304                 pr_err("failed to write perf data, error: %m\n");
305                 return -1;
306         }
307
308         perf_stat.bytes_written += event->header.size;
309         return 0;
310 }
311
312 static int write_stat_round_event(u64 tm, u64 type)
313 {
314         return perf_event__synthesize_stat_round(NULL, tm, type,
315                                                  process_synthesized_event,
316                                                  NULL);
317 }
318
319 #define WRITE_STAT_ROUND_EVENT(time, interval) \
320         write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
321
322 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
323
324 static int
325 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
326                              struct perf_counts_values *count)
327 {
328         struct perf_sample_id *sid = SID(counter, cpu, thread);
329
330         return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
331                                            process_synthesized_event, NULL);
332 }
333
334 /*
335  * Read out the results of a single counter:
336  * do not aggregate counts across CPUs in system-wide mode
337  */
338 static int read_counter(struct perf_evsel *counter)
339 {
340         int nthreads = thread_map__nr(evsel_list->threads);
341         int ncpus, cpu, thread;
342
343         if (target__has_cpu(&target) && !target__has_per_thread(&target))
344                 ncpus = perf_evsel__nr_cpus(counter);
345         else
346                 ncpus = 1;
347
348         if (!counter->supported)
349                 return -ENOENT;
350
351         if (counter->system_wide)
352                 nthreads = 1;
353
354         for (thread = 0; thread < nthreads; thread++) {
355                 for (cpu = 0; cpu < ncpus; cpu++) {
356                         struct perf_counts_values *count;
357
358                         count = perf_counts(counter->counts, cpu, thread);
359
360                         /*
361                          * The leader's group read loads data into its group members
362                          * (via perf_evsel__read_counter) and sets threir count->loaded.
363                          */
364                         if (!count->loaded &&
365                             perf_evsel__read_counter(counter, cpu, thread)) {
366                                 counter->counts->scaled = -1;
367                                 perf_counts(counter->counts, cpu, thread)->ena = 0;
368                                 perf_counts(counter->counts, cpu, thread)->run = 0;
369                                 return -1;
370                         }
371
372                         count->loaded = false;
373
374                         if (STAT_RECORD) {
375                                 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
376                                         pr_err("failed to write stat event\n");
377                                         return -1;
378                                 }
379                         }
380
381                         if (verbose > 1) {
382                                 fprintf(stat_config.output,
383                                         "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
384                                                 perf_evsel__name(counter),
385                                                 cpu,
386                                                 count->val, count->ena, count->run);
387                         }
388                 }
389         }
390
391         return 0;
392 }
393
394 static void read_counters(void)
395 {
396         struct perf_evsel *counter;
397         int ret;
398
399         evlist__for_each_entry(evsel_list, counter) {
400                 ret = read_counter(counter);
401                 if (ret)
402                         pr_debug("failed to read counter %s\n", counter->name);
403
404                 if (ret == 0 && perf_stat_process_counter(&stat_config, counter))
405                         pr_warning("failed to process counter %s\n", counter->name);
406         }
407 }
408
409 static void process_interval(void)
410 {
411         struct timespec ts, rs;
412
413         read_counters();
414
415         clock_gettime(CLOCK_MONOTONIC, &ts);
416         diff_timespec(&rs, &ts, &ref_time);
417
418         if (STAT_RECORD) {
419                 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
420                         pr_err("failed to write stat round event\n");
421         }
422
423         init_stats(&walltime_nsecs_stats);
424         update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000);
425         print_counters(&rs, 0, NULL);
426 }
427
428 static void enable_counters(void)
429 {
430         if (initial_delay)
431                 usleep(initial_delay * USEC_PER_MSEC);
432
433         /*
434          * We need to enable counters only if:
435          * - we don't have tracee (attaching to task or cpu)
436          * - we have initial delay configured
437          */
438         if (!target__none(&target) || initial_delay)
439                 perf_evlist__enable(evsel_list);
440 }
441
442 static void disable_counters(void)
443 {
444         /*
445          * If we don't have tracee (attaching to task or cpu), counters may
446          * still be running. To get accurate group ratios, we must stop groups
447          * from counting before reading their constituent counters.
448          */
449         if (!target__none(&target))
450                 perf_evlist__disable(evsel_list);
451 }
452
453 static volatile int workload_exec_errno;
454
455 /*
456  * perf_evlist__prepare_workload will send a SIGUSR1
457  * if the fork fails, since we asked by setting its
458  * want_signal to true.
459  */
460 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
461                                         void *ucontext __maybe_unused)
462 {
463         workload_exec_errno = info->si_value.sival_int;
464 }
465
466 static int perf_stat_synthesize_config(bool is_pipe)
467 {
468         int err;
469
470         if (is_pipe) {
471                 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
472                                                    process_synthesized_event);
473                 if (err < 0) {
474                         pr_err("Couldn't synthesize attrs.\n");
475                         return err;
476                 }
477         }
478
479         err = perf_event__synthesize_extra_attr(NULL,
480                                                 evsel_list,
481                                                 process_synthesized_event,
482                                                 is_pipe);
483
484         err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
485                                                 process_synthesized_event,
486                                                 NULL);
487         if (err < 0) {
488                 pr_err("Couldn't synthesize thread map.\n");
489                 return err;
490         }
491
492         err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
493                                              process_synthesized_event, NULL);
494         if (err < 0) {
495                 pr_err("Couldn't synthesize thread map.\n");
496                 return err;
497         }
498
499         err = perf_event__synthesize_stat_config(NULL, &stat_config,
500                                                  process_synthesized_event, NULL);
501         if (err < 0) {
502                 pr_err("Couldn't synthesize config.\n");
503                 return err;
504         }
505
506         return 0;
507 }
508
509 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
510
511 static int __store_counter_ids(struct perf_evsel *counter,
512                                struct cpu_map *cpus,
513                                struct thread_map *threads)
514 {
515         int cpu, thread;
516
517         for (cpu = 0; cpu < cpus->nr; cpu++) {
518                 for (thread = 0; thread < threads->nr; thread++) {
519                         int fd = FD(counter, cpu, thread);
520
521                         if (perf_evlist__id_add_fd(evsel_list, counter,
522                                                    cpu, thread, fd) < 0)
523                                 return -1;
524                 }
525         }
526
527         return 0;
528 }
529
530 static int store_counter_ids(struct perf_evsel *counter)
531 {
532         struct cpu_map *cpus = counter->cpus;
533         struct thread_map *threads = counter->threads;
534
535         if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
536                 return -ENOMEM;
537
538         return __store_counter_ids(counter, cpus, threads);
539 }
540
541 static bool perf_evsel__should_store_id(struct perf_evsel *counter)
542 {
543         return STAT_RECORD || counter->attr.read_format & PERF_FORMAT_ID;
544 }
545
546 static struct perf_evsel *perf_evsel__reset_weak_group(struct perf_evsel *evsel)
547 {
548         struct perf_evsel *c2, *leader;
549         bool is_open = true;
550
551         leader = evsel->leader;
552         pr_debug("Weak group for %s/%d failed\n",
553                         leader->name, leader->nr_members);
554
555         /*
556          * for_each_group_member doesn't work here because it doesn't
557          * include the first entry.
558          */
559         evlist__for_each_entry(evsel_list, c2) {
560                 if (c2 == evsel)
561                         is_open = false;
562                 if (c2->leader == leader) {
563                         if (is_open)
564                                 perf_evsel__close(c2);
565                         c2->leader = c2;
566                         c2->nr_members = 0;
567                 }
568         }
569         return leader;
570 }
571
572 static int __run_perf_stat(int argc, const char **argv)
573 {
574         int interval = stat_config.interval;
575         char msg[BUFSIZ];
576         unsigned long long t0, t1;
577         struct perf_evsel *counter;
578         struct timespec ts;
579         size_t l;
580         int status = 0;
581         const bool forks = (argc > 0);
582         bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
583         struct perf_evsel_config_term *err_term;
584
585         if (interval) {
586                 ts.tv_sec  = interval / USEC_PER_MSEC;
587                 ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
588         } else {
589                 ts.tv_sec  = 1;
590                 ts.tv_nsec = 0;
591         }
592
593         if (forks) {
594                 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
595                                                   workload_exec_failed_signal) < 0) {
596                         perror("failed to prepare workload");
597                         return -1;
598                 }
599                 child_pid = evsel_list->workload.pid;
600         }
601
602         if (group)
603                 perf_evlist__set_leader(evsel_list);
604
605         evlist__for_each_entry(evsel_list, counter) {
606 try_again:
607                 if (create_perf_stat_counter(counter) < 0) {
608
609                         /* Weak group failed. Reset the group. */
610                         if ((errno == EINVAL || errno == EBADF) &&
611                             counter->leader != counter &&
612                             counter->weak_group) {
613                                 counter = perf_evsel__reset_weak_group(counter);
614                                 goto try_again;
615                         }
616
617                         /*
618                          * PPC returns ENXIO for HW counters until 2.6.37
619                          * (behavior changed with commit b0a873e).
620                          */
621                         if (errno == EINVAL || errno == ENOSYS ||
622                             errno == ENOENT || errno == EOPNOTSUPP ||
623                             errno == ENXIO) {
624                                 if (verbose > 0)
625                                         ui__warning("%s event is not supported by the kernel.\n",
626                                                     perf_evsel__name(counter));
627                                 counter->supported = false;
628
629                                 if ((counter->leader != counter) ||
630                                     !(counter->leader->nr_members > 1))
631                                         continue;
632                         } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
633                                 if (verbose > 0)
634                                         ui__warning("%s\n", msg);
635                                 goto try_again;
636                         }
637
638                         perf_evsel__open_strerror(counter, &target,
639                                                   errno, msg, sizeof(msg));
640                         ui__error("%s\n", msg);
641
642                         if (child_pid != -1)
643                                 kill(child_pid, SIGTERM);
644
645                         return -1;
646                 }
647                 counter->supported = true;
648
649                 l = strlen(counter->unit);
650                 if (l > unit_width)
651                         unit_width = l;
652
653                 if (perf_evsel__should_store_id(counter) &&
654                     store_counter_ids(counter))
655                         return -1;
656         }
657
658         if (perf_evlist__apply_filters(evsel_list, &counter)) {
659                 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
660                         counter->filter, perf_evsel__name(counter), errno,
661                         str_error_r(errno, msg, sizeof(msg)));
662                 return -1;
663         }
664
665         if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
666                 pr_err("failed to set config \"%s\" on event %s with %d (%s)\n",
667                       err_term->val.drv_cfg, perf_evsel__name(counter), errno,
668                       str_error_r(errno, msg, sizeof(msg)));
669                 return -1;
670         }
671
672         if (STAT_RECORD) {
673                 int err, fd = perf_data__fd(&perf_stat.data);
674
675                 if (is_pipe) {
676                         err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
677                 } else {
678                         err = perf_session__write_header(perf_stat.session, evsel_list,
679                                                          fd, false);
680                 }
681
682                 if (err < 0)
683                         return err;
684
685                 err = perf_stat_synthesize_config(is_pipe);
686                 if (err < 0)
687                         return err;
688         }
689
690         /*
691          * Enable counters and exec the command:
692          */
693         t0 = rdclock();
694         clock_gettime(CLOCK_MONOTONIC, &ref_time);
695
696         if (forks) {
697                 perf_evlist__start_workload(evsel_list);
698                 enable_counters();
699
700                 if (interval) {
701                         while (!waitpid(child_pid, &status, WNOHANG)) {
702                                 nanosleep(&ts, NULL);
703                                 process_interval();
704                         }
705                 }
706                 waitpid(child_pid, &status, 0);
707
708                 if (workload_exec_errno) {
709                         const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
710                         pr_err("Workload failed: %s\n", emsg);
711                         return -1;
712                 }
713
714                 if (WIFSIGNALED(status))
715                         psignal(WTERMSIG(status), argv[0]);
716         } else {
717                 enable_counters();
718                 while (!done) {
719                         nanosleep(&ts, NULL);
720                         if (interval)
721                                 process_interval();
722                 }
723         }
724
725         disable_counters();
726
727         t1 = rdclock();
728
729         update_stats(&walltime_nsecs_stats, t1 - t0);
730
731         /*
732          * Closing a group leader splits the group, and as we only disable
733          * group leaders, results in remaining events becoming enabled. To
734          * avoid arbitrary skew, we must read all counters before closing any
735          * group leaders.
736          */
737         read_counters();
738         perf_evlist__close(evsel_list);
739
740         return WEXITSTATUS(status);
741 }
742
743 static int run_perf_stat(int argc, const char **argv)
744 {
745         int ret;
746
747         if (pre_cmd) {
748                 ret = system(pre_cmd);
749                 if (ret)
750                         return ret;
751         }
752
753         if (sync_run)
754                 sync();
755
756         ret = __run_perf_stat(argc, argv);
757         if (ret)
758                 return ret;
759
760         if (post_cmd) {
761                 ret = system(post_cmd);
762                 if (ret)
763                         return ret;
764         }
765
766         return ret;
767 }
768
769 static void print_running(u64 run, u64 ena)
770 {
771         if (csv_output) {
772                 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
773                                         csv_sep,
774                                         run,
775                                         csv_sep,
776                                         ena ? 100.0 * run / ena : 100.0);
777         } else if (run != ena) {
778                 fprintf(stat_config.output, "  (%.2f%%)", 100.0 * run / ena);
779         }
780 }
781
782 static void print_noise_pct(double total, double avg)
783 {
784         double pct = rel_stddev_stats(total, avg);
785
786         if (csv_output)
787                 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
788         else if (pct)
789                 fprintf(stat_config.output, "  ( +-%6.2f%% )", pct);
790 }
791
792 static void print_noise(struct perf_evsel *evsel, double avg)
793 {
794         struct perf_stat_evsel *ps;
795
796         if (run_count == 1)
797                 return;
798
799         ps = evsel->stats;
800         print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
801 }
802
803 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
804 {
805         switch (stat_config.aggr_mode) {
806         case AGGR_CORE:
807                 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
808                         cpu_map__id_to_socket(id),
809                         csv_output ? 0 : -8,
810                         cpu_map__id_to_cpu(id),
811                         csv_sep,
812                         csv_output ? 0 : 4,
813                         nr,
814                         csv_sep);
815                 break;
816         case AGGR_SOCKET:
817                 fprintf(stat_config.output, "S%*d%s%*d%s",
818                         csv_output ? 0 : -5,
819                         id,
820                         csv_sep,
821                         csv_output ? 0 : 4,
822                         nr,
823                         csv_sep);
824                         break;
825         case AGGR_NONE:
826                 fprintf(stat_config.output, "CPU%*d%s",
827                         csv_output ? 0 : -4,
828                         perf_evsel__cpus(evsel)->map[id], csv_sep);
829                 break;
830         case AGGR_THREAD:
831                 fprintf(stat_config.output, "%*s-%*d%s",
832                         csv_output ? 0 : 16,
833                         thread_map__comm(evsel->threads, id),
834                         csv_output ? 0 : -8,
835                         thread_map__pid(evsel->threads, id),
836                         csv_sep);
837                 break;
838         case AGGR_GLOBAL:
839         case AGGR_UNSET:
840         default:
841                 break;
842         }
843 }
844
845 struct outstate {
846         FILE *fh;
847         bool newline;
848         const char *prefix;
849         int  nfields;
850         int  id, nr;
851         struct perf_evsel *evsel;
852 };
853
854 #define METRIC_LEN  35
855
856 static void new_line_std(void *ctx)
857 {
858         struct outstate *os = ctx;
859
860         os->newline = true;
861 }
862
863 static void do_new_line_std(struct outstate *os)
864 {
865         fputc('\n', os->fh);
866         fputs(os->prefix, os->fh);
867         aggr_printout(os->evsel, os->id, os->nr);
868         if (stat_config.aggr_mode == AGGR_NONE)
869                 fprintf(os->fh, "        ");
870         fprintf(os->fh, "                                                 ");
871 }
872
873 static void print_metric_std(void *ctx, const char *color, const char *fmt,
874                              const char *unit, double val)
875 {
876         struct outstate *os = ctx;
877         FILE *out = os->fh;
878         int n;
879         bool newline = os->newline;
880
881         os->newline = false;
882
883         if (unit == NULL || fmt == NULL) {
884                 fprintf(out, "%-*s", METRIC_LEN, "");
885                 return;
886         }
887
888         if (newline)
889                 do_new_line_std(os);
890
891         n = fprintf(out, " # ");
892         if (color)
893                 n += color_fprintf(out, color, fmt, val);
894         else
895                 n += fprintf(out, fmt, val);
896         fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
897 }
898
899 static void new_line_csv(void *ctx)
900 {
901         struct outstate *os = ctx;
902         int i;
903
904         fputc('\n', os->fh);
905         if (os->prefix)
906                 fprintf(os->fh, "%s%s", os->prefix, csv_sep);
907         aggr_printout(os->evsel, os->id, os->nr);
908         for (i = 0; i < os->nfields; i++)
909                 fputs(csv_sep, os->fh);
910 }
911
912 static void print_metric_csv(void *ctx,
913                              const char *color __maybe_unused,
914                              const char *fmt, const char *unit, double val)
915 {
916         struct outstate *os = ctx;
917         FILE *out = os->fh;
918         char buf[64], *vals, *ends;
919
920         if (unit == NULL || fmt == NULL) {
921                 fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
922                 return;
923         }
924         snprintf(buf, sizeof(buf), fmt, val);
925         ends = vals = ltrim(buf);
926         while (isdigit(*ends) || *ends == '.')
927                 ends++;
928         *ends = 0;
929         while (isspace(*unit))
930                 unit++;
931         fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
932 }
933
934 #define METRIC_ONLY_LEN 20
935
936 /* Filter out some columns that don't work well in metrics only mode */
937
938 static bool valid_only_metric(const char *unit)
939 {
940         if (!unit)
941                 return false;
942         if (strstr(unit, "/sec") ||
943             strstr(unit, "hz") ||
944             strstr(unit, "Hz") ||
945             strstr(unit, "CPUs utilized"))
946                 return false;
947         return true;
948 }
949
950 static const char *fixunit(char *buf, struct perf_evsel *evsel,
951                            const char *unit)
952 {
953         if (!strncmp(unit, "of all", 6)) {
954                 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
955                          unit);
956                 return buf;
957         }
958         return unit;
959 }
960
961 static void print_metric_only(void *ctx, const char *color, const char *fmt,
962                               const char *unit, double val)
963 {
964         struct outstate *os = ctx;
965         FILE *out = os->fh;
966         int n;
967         char buf[1024];
968         unsigned mlen = METRIC_ONLY_LEN;
969
970         if (!valid_only_metric(unit))
971                 return;
972         unit = fixunit(buf, os->evsel, unit);
973         if (color)
974                 n = color_fprintf(out, color, fmt, val);
975         else
976                 n = fprintf(out, fmt, val);
977         if (n > METRIC_ONLY_LEN)
978                 n = METRIC_ONLY_LEN;
979         if (mlen < strlen(unit))
980                 mlen = strlen(unit) + 1;
981         fprintf(out, "%*s", mlen - n, "");
982 }
983
984 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
985                                   const char *fmt,
986                                   const char *unit, double val)
987 {
988         struct outstate *os = ctx;
989         FILE *out = os->fh;
990         char buf[64], *vals, *ends;
991         char tbuf[1024];
992
993         if (!valid_only_metric(unit))
994                 return;
995         unit = fixunit(tbuf, os->evsel, unit);
996         snprintf(buf, sizeof buf, fmt, val);
997         ends = vals = ltrim(buf);
998         while (isdigit(*ends) || *ends == '.')
999                 ends++;
1000         *ends = 0;
1001         fprintf(out, "%s%s", vals, csv_sep);
1002 }
1003
1004 static void new_line_metric(void *ctx __maybe_unused)
1005 {
1006 }
1007
1008 static void print_metric_header(void *ctx, const char *color __maybe_unused,
1009                                 const char *fmt __maybe_unused,
1010                                 const char *unit, double val __maybe_unused)
1011 {
1012         struct outstate *os = ctx;
1013         char tbuf[1024];
1014
1015         if (!valid_only_metric(unit))
1016                 return;
1017         unit = fixunit(tbuf, os->evsel, unit);
1018         if (csv_output)
1019                 fprintf(os->fh, "%s%s", unit, csv_sep);
1020         else
1021                 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
1022 }
1023
1024 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1025 {
1026         FILE *output = stat_config.output;
1027         double msecs = avg / NSEC_PER_MSEC;
1028         const char *fmt_v, *fmt_n;
1029         char name[25];
1030
1031         fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
1032         fmt_n = csv_output ? "%s" : "%-25s";
1033
1034         aggr_printout(evsel, id, nr);
1035
1036         scnprintf(name, sizeof(name), "%s%s",
1037                   perf_evsel__name(evsel), csv_output ? "" : " (msec)");
1038
1039         fprintf(output, fmt_v, msecs, csv_sep);
1040
1041         if (csv_output)
1042                 fprintf(output, "%s%s", evsel->unit, csv_sep);
1043         else
1044                 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
1045
1046         fprintf(output, fmt_n, name);
1047
1048         if (evsel->cgrp)
1049                 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1050 }
1051
1052 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
1053 {
1054         int i;
1055
1056         if (!aggr_get_id)
1057                 return 0;
1058
1059         if (stat_config.aggr_mode == AGGR_NONE)
1060                 return id;
1061
1062         if (stat_config.aggr_mode == AGGR_GLOBAL)
1063                 return 0;
1064
1065         for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
1066                 int cpu2 = perf_evsel__cpus(evsel)->map[i];
1067
1068                 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
1069                         return cpu2;
1070         }
1071         return 0;
1072 }
1073
1074 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1075 {
1076         FILE *output = stat_config.output;
1077         double sc =  evsel->scale;
1078         const char *fmt;
1079
1080         if (csv_output) {
1081                 fmt = floor(sc) != sc ?  "%.2f%s" : "%.0f%s";
1082         } else {
1083                 if (big_num)
1084                         fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
1085                 else
1086                         fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
1087         }
1088
1089         aggr_printout(evsel, id, nr);
1090
1091         fprintf(output, fmt, avg, csv_sep);
1092
1093         if (evsel->unit)
1094                 fprintf(output, "%-*s%s",
1095                         csv_output ? 0 : unit_width,
1096                         evsel->unit, csv_sep);
1097
1098         fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1099
1100         if (evsel->cgrp)
1101                 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1102 }
1103
1104 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
1105                      char *prefix, u64 run, u64 ena, double noise,
1106                      struct runtime_stat *st)
1107 {
1108         struct perf_stat_output_ctx out;
1109         struct outstate os = {
1110                 .fh = stat_config.output,
1111                 .prefix = prefix ? prefix : "",
1112                 .id = id,
1113                 .nr = nr,
1114                 .evsel = counter,
1115         };
1116         print_metric_t pm = print_metric_std;
1117         void (*nl)(void *);
1118
1119         if (metric_only) {
1120                 nl = new_line_metric;
1121                 if (csv_output)
1122                         pm = print_metric_only_csv;
1123                 else
1124                         pm = print_metric_only;
1125         } else
1126                 nl = new_line_std;
1127
1128         if (csv_output && !metric_only) {
1129                 static int aggr_fields[] = {
1130                         [AGGR_GLOBAL] = 0,
1131                         [AGGR_THREAD] = 1,
1132                         [AGGR_NONE] = 1,
1133                         [AGGR_SOCKET] = 2,
1134                         [AGGR_CORE] = 2,
1135                 };
1136
1137                 pm = print_metric_csv;
1138                 nl = new_line_csv;
1139                 os.nfields = 3;
1140                 os.nfields += aggr_fields[stat_config.aggr_mode];
1141                 if (counter->cgrp)
1142                         os.nfields++;
1143         }
1144         if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1145                 if (metric_only) {
1146                         pm(&os, NULL, "", "", 0);
1147                         return;
1148                 }
1149                 aggr_printout(counter, id, nr);
1150
1151                 fprintf(stat_config.output, "%*s%s",
1152                         csv_output ? 0 : 18,
1153                         counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1154                         csv_sep);
1155
1156                 if (counter->supported)
1157                         print_free_counters_hint = 1;
1158
1159                 fprintf(stat_config.output, "%-*s%s",
1160                         csv_output ? 0 : unit_width,
1161                         counter->unit, csv_sep);
1162
1163                 fprintf(stat_config.output, "%*s",
1164                         csv_output ? 0 : -25,
1165                         perf_evsel__name(counter));
1166
1167                 if (counter->cgrp)
1168                         fprintf(stat_config.output, "%s%s",
1169                                 csv_sep, counter->cgrp->name);
1170
1171                 if (!csv_output)
1172                         pm(&os, NULL, NULL, "", 0);
1173                 print_noise(counter, noise);
1174                 print_running(run, ena);
1175                 if (csv_output)
1176                         pm(&os, NULL, NULL, "", 0);
1177                 return;
1178         }
1179
1180         if (metric_only)
1181                 /* nothing */;
1182         else if (nsec_counter(counter))
1183                 nsec_printout(id, nr, counter, uval);
1184         else
1185                 abs_printout(id, nr, counter, uval);
1186
1187         out.print_metric = pm;
1188         out.new_line = nl;
1189         out.ctx = &os;
1190         out.force_header = false;
1191
1192         if (csv_output && !metric_only) {
1193                 print_noise(counter, noise);
1194                 print_running(run, ena);
1195         }
1196
1197         perf_stat__print_shadow_stats(counter, uval,
1198                                 first_shadow_cpu(counter, id),
1199                                 &out, &metric_events, st);
1200         if (!csv_output && !metric_only) {
1201                 print_noise(counter, noise);
1202                 print_running(run, ena);
1203         }
1204 }
1205
1206 static void aggr_update_shadow(void)
1207 {
1208         int cpu, s2, id, s;
1209         u64 val;
1210         struct perf_evsel *counter;
1211
1212         for (s = 0; s < aggr_map->nr; s++) {
1213                 id = aggr_map->map[s];
1214                 evlist__for_each_entry(evsel_list, counter) {
1215                         val = 0;
1216                         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1217                                 s2 = aggr_get_id(evsel_list->cpus, cpu);
1218                                 if (s2 != id)
1219                                         continue;
1220                                 val += perf_counts(counter->counts, cpu, 0)->val;
1221                         }
1222                         perf_stat__update_shadow_stats(counter, val,
1223                                         first_shadow_cpu(counter, id),
1224                                         &rt_stat);
1225                 }
1226         }
1227 }
1228
1229 static void collect_all_aliases(struct perf_evsel *counter,
1230                             void (*cb)(struct perf_evsel *counter, void *data,
1231                                        bool first),
1232                             void *data)
1233 {
1234         struct perf_evsel *alias;
1235
1236         alias = list_prepare_entry(counter, &(evsel_list->entries), node);
1237         list_for_each_entry_continue (alias, &evsel_list->entries, node) {
1238                 if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
1239                     alias->scale != counter->scale ||
1240                     alias->cgrp != counter->cgrp ||
1241                     strcmp(alias->unit, counter->unit) ||
1242                     nsec_counter(alias) != nsec_counter(counter))
1243                         break;
1244                 alias->merged_stat = true;
1245                 cb(alias, data, false);
1246         }
1247 }
1248
1249 static bool collect_data(struct perf_evsel *counter,
1250                             void (*cb)(struct perf_evsel *counter, void *data,
1251                                        bool first),
1252                             void *data)
1253 {
1254         if (counter->merged_stat)
1255                 return false;
1256         cb(counter, data, true);
1257         if (!no_merge && counter->auto_merge_stats)
1258                 collect_all_aliases(counter, cb, data);
1259         return true;
1260 }
1261
1262 struct aggr_data {
1263         u64 ena, run, val;
1264         int id;
1265         int nr;
1266         int cpu;
1267 };
1268
1269 static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
1270 {
1271         struct aggr_data *ad = data;
1272         int cpu, s2;
1273
1274         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1275                 struct perf_counts_values *counts;
1276
1277                 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1278                 if (s2 != ad->id)
1279                         continue;
1280                 if (first)
1281                         ad->nr++;
1282                 counts = perf_counts(counter->counts, cpu, 0);
1283                 /*
1284                  * When any result is bad, make them all to give
1285                  * consistent output in interval mode.
1286                  */
1287                 if (counts->ena == 0 || counts->run == 0 ||
1288                     counter->counts->scaled == -1) {
1289                         ad->ena = 0;
1290                         ad->run = 0;
1291                         break;
1292                 }
1293                 ad->val += counts->val;
1294                 ad->ena += counts->ena;
1295                 ad->run += counts->run;
1296         }
1297 }
1298
1299 static void print_aggr(char *prefix)
1300 {
1301         FILE *output = stat_config.output;
1302         struct perf_evsel *counter;
1303         int s, id, nr;
1304         double uval;
1305         u64 ena, run, val;
1306         bool first;
1307
1308         if (!(aggr_map || aggr_get_id))
1309                 return;
1310
1311         aggr_update_shadow();
1312
1313         /*
1314          * With metric_only everything is on a single line.
1315          * Without each counter has its own line.
1316          */
1317         for (s = 0; s < aggr_map->nr; s++) {
1318                 struct aggr_data ad;
1319                 if (prefix && metric_only)
1320                         fprintf(output, "%s", prefix);
1321
1322                 ad.id = id = aggr_map->map[s];
1323                 first = true;
1324                 evlist__for_each_entry(evsel_list, counter) {
1325                         if (is_duration_time(counter))
1326                                 continue;
1327
1328                         ad.val = ad.ena = ad.run = 0;
1329                         ad.nr = 0;
1330                         if (!collect_data(counter, aggr_cb, &ad))
1331                                 continue;
1332                         nr = ad.nr;
1333                         ena = ad.ena;
1334                         run = ad.run;
1335                         val = ad.val;
1336                         if (first && metric_only) {
1337                                 first = false;
1338                                 aggr_printout(counter, id, nr);
1339                         }
1340                         if (prefix && !metric_only)
1341                                 fprintf(output, "%s", prefix);
1342
1343                         uval = val * counter->scale;
1344                         printout(id, nr, counter, uval, prefix, run, ena, 1.0,
1345                                  &rt_stat);
1346                         if (!metric_only)
1347                                 fputc('\n', output);
1348                 }
1349                 if (metric_only)
1350                         fputc('\n', output);
1351         }
1352 }
1353
1354 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1355 {
1356         FILE *output = stat_config.output;
1357         int nthreads = thread_map__nr(counter->threads);
1358         int ncpus = cpu_map__nr(counter->cpus);
1359         int cpu, thread;
1360         double uval;
1361
1362         for (thread = 0; thread < nthreads; thread++) {
1363                 u64 ena = 0, run = 0, val = 0;
1364
1365                 for (cpu = 0; cpu < ncpus; cpu++) {
1366                         val += perf_counts(counter->counts, cpu, thread)->val;
1367                         ena += perf_counts(counter->counts, cpu, thread)->ena;
1368                         run += perf_counts(counter->counts, cpu, thread)->run;
1369                 }
1370
1371                 if (prefix)
1372                         fprintf(output, "%s", prefix);
1373
1374                 uval = val * counter->scale;
1375
1376                 if (stat_config.stats)
1377                         printout(thread, 0, counter, uval, prefix, run, ena,
1378                                  1.0, &stat_config.stats[thread]);
1379                 else
1380                         printout(thread, 0, counter, uval, prefix, run, ena,
1381                                  1.0, &rt_stat);
1382                 fputc('\n', output);
1383         }
1384 }
1385
1386 struct caggr_data {
1387         double avg, avg_enabled, avg_running;
1388 };
1389
1390 static void counter_aggr_cb(struct perf_evsel *counter, void *data,
1391                             bool first __maybe_unused)
1392 {
1393         struct caggr_data *cd = data;
1394         struct perf_stat_evsel *ps = counter->stats;
1395
1396         cd->avg += avg_stats(&ps->res_stats[0]);
1397         cd->avg_enabled += avg_stats(&ps->res_stats[1]);
1398         cd->avg_running += avg_stats(&ps->res_stats[2]);
1399 }
1400
1401 /*
1402  * Print out the results of a single counter:
1403  * aggregated counts in system-wide mode
1404  */
1405 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1406 {
1407         FILE *output = stat_config.output;
1408         double uval;
1409         struct caggr_data cd = { .avg = 0.0 };
1410
1411         if (!collect_data(counter, counter_aggr_cb, &cd))
1412                 return;
1413
1414         if (prefix && !metric_only)
1415                 fprintf(output, "%s", prefix);
1416
1417         uval = cd.avg * counter->scale;
1418         printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled,
1419                  cd.avg, &rt_stat);
1420         if (!metric_only)
1421                 fprintf(output, "\n");
1422 }
1423
1424 static void counter_cb(struct perf_evsel *counter, void *data,
1425                        bool first __maybe_unused)
1426 {
1427         struct aggr_data *ad = data;
1428
1429         ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
1430         ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
1431         ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
1432 }
1433
1434 /*
1435  * Print out the results of a single counter:
1436  * does not use aggregated count in system-wide
1437  */
1438 static void print_counter(struct perf_evsel *counter, char *prefix)
1439 {
1440         FILE *output = stat_config.output;
1441         u64 ena, run, val;
1442         double uval;
1443         int cpu;
1444
1445         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1446                 struct aggr_data ad = { .cpu = cpu };
1447
1448                 if (!collect_data(counter, counter_cb, &ad))
1449                         return;
1450                 val = ad.val;
1451                 ena = ad.ena;
1452                 run = ad.run;
1453
1454                 if (prefix)
1455                         fprintf(output, "%s", prefix);
1456
1457                 uval = val * counter->scale;
1458                 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0,
1459                          &rt_stat);
1460
1461                 fputc('\n', output);
1462         }
1463 }
1464
1465 static void print_no_aggr_metric(char *prefix)
1466 {
1467         int cpu;
1468         int nrcpus = 0;
1469         struct perf_evsel *counter;
1470         u64 ena, run, val;
1471         double uval;
1472
1473         nrcpus = evsel_list->cpus->nr;
1474         for (cpu = 0; cpu < nrcpus; cpu++) {
1475                 bool first = true;
1476
1477                 if (prefix)
1478                         fputs(prefix, stat_config.output);
1479                 evlist__for_each_entry(evsel_list, counter) {
1480                         if (is_duration_time(counter))
1481                                 continue;
1482                         if (first) {
1483                                 aggr_printout(counter, cpu, 0);
1484                                 first = false;
1485                         }
1486                         val = perf_counts(counter->counts, cpu, 0)->val;
1487                         ena = perf_counts(counter->counts, cpu, 0)->ena;
1488                         run = perf_counts(counter->counts, cpu, 0)->run;
1489
1490                         uval = val * counter->scale;
1491                         printout(cpu, 0, counter, uval, prefix, run, ena, 1.0,
1492                                  &rt_stat);
1493                 }
1494                 fputc('\n', stat_config.output);
1495         }
1496 }
1497
1498 static int aggr_header_lens[] = {
1499         [AGGR_CORE] = 18,
1500         [AGGR_SOCKET] = 12,
1501         [AGGR_NONE] = 6,
1502         [AGGR_THREAD] = 24,
1503         [AGGR_GLOBAL] = 0,
1504 };
1505
1506 static const char *aggr_header_csv[] = {
1507         [AGGR_CORE]     =       "core,cpus,",
1508         [AGGR_SOCKET]   =       "socket,cpus",
1509         [AGGR_NONE]     =       "cpu,",
1510         [AGGR_THREAD]   =       "comm-pid,",
1511         [AGGR_GLOBAL]   =       ""
1512 };
1513
1514 static void print_metric_headers(const char *prefix, bool no_indent)
1515 {
1516         struct perf_stat_output_ctx out;
1517         struct perf_evsel *counter;
1518         struct outstate os = {
1519                 .fh = stat_config.output
1520         };
1521
1522         if (prefix)
1523                 fprintf(stat_config.output, "%s", prefix);
1524
1525         if (!csv_output && !no_indent)
1526                 fprintf(stat_config.output, "%*s",
1527                         aggr_header_lens[stat_config.aggr_mode], "");
1528         if (csv_output) {
1529                 if (stat_config.interval)
1530                         fputs("time,", stat_config.output);
1531                 fputs(aggr_header_csv[stat_config.aggr_mode],
1532                         stat_config.output);
1533         }
1534
1535         /* Print metrics headers only */
1536         evlist__for_each_entry(evsel_list, counter) {
1537                 if (is_duration_time(counter))
1538                         continue;
1539                 os.evsel = counter;
1540                 out.ctx = &os;
1541                 out.print_metric = print_metric_header;
1542                 out.new_line = new_line_metric;
1543                 out.force_header = true;
1544                 os.evsel = counter;
1545                 perf_stat__print_shadow_stats(counter, 0,
1546                                               0,
1547                                               &out,
1548                                               &metric_events,
1549                                               &rt_stat);
1550         }
1551         fputc('\n', stat_config.output);
1552 }
1553
1554 static void print_interval(char *prefix, struct timespec *ts)
1555 {
1556         FILE *output = stat_config.output;
1557         static int num_print_interval;
1558
1559         sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1560
1561         if (num_print_interval == 0 && !csv_output) {
1562                 switch (stat_config.aggr_mode) {
1563                 case AGGR_SOCKET:
1564                         fprintf(output, "#           time socket cpus");
1565                         if (!metric_only)
1566                                 fprintf(output, "             counts %*s events\n", unit_width, "unit");
1567                         break;
1568                 case AGGR_CORE:
1569                         fprintf(output, "#           time core         cpus");
1570                         if (!metric_only)
1571                                 fprintf(output, "             counts %*s events\n", unit_width, "unit");
1572                         break;
1573                 case AGGR_NONE:
1574                         fprintf(output, "#           time CPU");
1575                         if (!metric_only)
1576                                 fprintf(output, "                counts %*s events\n", unit_width, "unit");
1577                         break;
1578                 case AGGR_THREAD:
1579                         fprintf(output, "#           time             comm-pid");
1580                         if (!metric_only)
1581                                 fprintf(output, "                  counts %*s events\n", unit_width, "unit");
1582                         break;
1583                 case AGGR_GLOBAL:
1584                 default:
1585                         fprintf(output, "#           time");
1586                         if (!metric_only)
1587                                 fprintf(output, "             counts %*s events\n", unit_width, "unit");
1588                 case AGGR_UNSET:
1589                         break;
1590                 }
1591         }
1592
1593         if (num_print_interval == 0 && metric_only)
1594                 print_metric_headers(" ", true);
1595         if (++num_print_interval == 25)
1596                 num_print_interval = 0;
1597 }
1598
1599 static void print_header(int argc, const char **argv)
1600 {
1601         FILE *output = stat_config.output;
1602         int i;
1603
1604         fflush(stdout);
1605
1606         if (!csv_output) {
1607                 fprintf(output, "\n");
1608                 fprintf(output, " Performance counter stats for ");
1609                 if (target.system_wide)
1610                         fprintf(output, "\'system wide");
1611                 else if (target.cpu_list)
1612                         fprintf(output, "\'CPU(s) %s", target.cpu_list);
1613                 else if (!target__has_task(&target)) {
1614                         fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1615                         for (i = 1; argv && (i < argc); i++)
1616                                 fprintf(output, " %s", argv[i]);
1617                 } else if (target.pid)
1618                         fprintf(output, "process id \'%s", target.pid);
1619                 else
1620                         fprintf(output, "thread id \'%s", target.tid);
1621
1622                 fprintf(output, "\'");
1623                 if (run_count > 1)
1624                         fprintf(output, " (%d runs)", run_count);
1625                 fprintf(output, ":\n\n");
1626         }
1627 }
1628
1629 static void print_footer(void)
1630 {
1631         FILE *output = stat_config.output;
1632         int n;
1633
1634         if (!null_run)
1635                 fprintf(output, "\n");
1636         fprintf(output, " %17.9f seconds time elapsed",
1637                         avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
1638         if (run_count > 1) {
1639                 fprintf(output, "                                        ");
1640                 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1641                                 avg_stats(&walltime_nsecs_stats));
1642         }
1643         fprintf(output, "\n\n");
1644
1645         if (print_free_counters_hint &&
1646             sysctl__read_int("kernel/nmi_watchdog", &n) >= 0 &&
1647             n > 0)
1648                 fprintf(output,
1649 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1650 "       echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1651 "       perf stat ...\n"
1652 "       echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1653 }
1654
1655 static void print_counters(struct timespec *ts, int argc, const char **argv)
1656 {
1657         int interval = stat_config.interval;
1658         struct perf_evsel *counter;
1659         char buf[64], *prefix = NULL;
1660
1661         /* Do not print anything if we record to the pipe. */
1662         if (STAT_RECORD && perf_stat.data.is_pipe)
1663                 return;
1664
1665         if (interval)
1666                 print_interval(prefix = buf, ts);
1667         else
1668                 print_header(argc, argv);
1669
1670         if (metric_only) {
1671                 static int num_print_iv;
1672
1673                 if (num_print_iv == 0 && !interval)
1674                         print_metric_headers(prefix, false);
1675                 if (num_print_iv++ == 25)
1676                         num_print_iv = 0;
1677                 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1678                         fprintf(stat_config.output, "%s", prefix);
1679         }
1680
1681         switch (stat_config.aggr_mode) {
1682         case AGGR_CORE:
1683         case AGGR_SOCKET:
1684                 print_aggr(prefix);
1685                 break;
1686         case AGGR_THREAD:
1687                 evlist__for_each_entry(evsel_list, counter) {
1688                         if (is_duration_time(counter))
1689                                 continue;
1690                         print_aggr_thread(counter, prefix);
1691                 }
1692                 break;
1693         case AGGR_GLOBAL:
1694                 evlist__for_each_entry(evsel_list, counter) {
1695                         if (is_duration_time(counter))
1696                                 continue;
1697                         print_counter_aggr(counter, prefix);
1698                 }
1699                 if (metric_only)
1700                         fputc('\n', stat_config.output);
1701                 break;
1702         case AGGR_NONE:
1703                 if (metric_only)
1704                         print_no_aggr_metric(prefix);
1705                 else {
1706                         evlist__for_each_entry(evsel_list, counter) {
1707                                 if (is_duration_time(counter))
1708                                         continue;
1709                                 print_counter(counter, prefix);
1710                         }
1711                 }
1712                 break;
1713         case AGGR_UNSET:
1714         default:
1715                 break;
1716         }
1717
1718         if (!interval && !csv_output)
1719                 print_footer();
1720
1721         fflush(stat_config.output);
1722 }
1723
1724 static volatile int signr = -1;
1725
1726 static void skip_signal(int signo)
1727 {
1728         if ((child_pid == -1) || stat_config.interval)
1729                 done = 1;
1730
1731         signr = signo;
1732         /*
1733          * render child_pid harmless
1734          * won't send SIGTERM to a random
1735          * process in case of race condition
1736          * and fast PID recycling
1737          */
1738         child_pid = -1;
1739 }
1740
1741 static void sig_atexit(void)
1742 {
1743         sigset_t set, oset;
1744
1745         /*
1746          * avoid race condition with SIGCHLD handler
1747          * in skip_signal() which is modifying child_pid
1748          * goal is to avoid send SIGTERM to a random
1749          * process
1750          */
1751         sigemptyset(&set);
1752         sigaddset(&set, SIGCHLD);
1753         sigprocmask(SIG_BLOCK, &set, &oset);
1754
1755         if (child_pid != -1)
1756                 kill(child_pid, SIGTERM);
1757
1758         sigprocmask(SIG_SETMASK, &oset, NULL);
1759
1760         if (signr == -1)
1761                 return;
1762
1763         signal(signr, SIG_DFL);
1764         kill(getpid(), signr);
1765 }
1766
1767 static int stat__set_big_num(const struct option *opt __maybe_unused,
1768                              const char *s __maybe_unused, int unset)
1769 {
1770         big_num_opt = unset ? 0 : 1;
1771         return 0;
1772 }
1773
1774 static int enable_metric_only(const struct option *opt __maybe_unused,
1775                               const char *s __maybe_unused, int unset)
1776 {
1777         force_metric_only = true;
1778         metric_only = !unset;
1779         return 0;
1780 }
1781
1782 static int parse_metric_groups(const struct option *opt,
1783                                const char *str,
1784                                int unset __maybe_unused)
1785 {
1786         return metricgroup__parse_groups(opt, str, &metric_events);
1787 }
1788
1789 static const struct option stat_options[] = {
1790         OPT_BOOLEAN('T', "transaction", &transaction_run,
1791                     "hardware transaction statistics"),
1792         OPT_CALLBACK('e', "event", &evsel_list, "event",
1793                      "event selector. use 'perf list' to list available events",
1794                      parse_events_option),
1795         OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1796                      "event filter", parse_filter),
1797         OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1798                     "child tasks do not inherit counters"),
1799         OPT_STRING('p', "pid", &target.pid, "pid",
1800                    "stat events on existing process id"),
1801         OPT_STRING('t', "tid", &target.tid, "tid",
1802                    "stat events on existing thread id"),
1803         OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1804                     "system-wide collection from all CPUs"),
1805         OPT_BOOLEAN('g', "group", &group,
1806                     "put the counters into a counter group"),
1807         OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1808         OPT_INCR('v', "verbose", &verbose,
1809                     "be more verbose (show counter open errors, etc)"),
1810         OPT_INTEGER('r', "repeat", &run_count,
1811                     "repeat command and print average + stddev (max: 100, forever: 0)"),
1812         OPT_BOOLEAN('n', "null", &null_run,
1813                     "null run - dont start any counters"),
1814         OPT_INCR('d', "detailed", &detailed_run,
1815                     "detailed run - start a lot of events"),
1816         OPT_BOOLEAN('S', "sync", &sync_run,
1817                     "call sync() before starting a run"),
1818         OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1819                            "print large numbers with thousands\' separators",
1820                            stat__set_big_num),
1821         OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1822                     "list of cpus to monitor in system-wide"),
1823         OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1824                     "disable CPU count aggregation", AGGR_NONE),
1825         OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
1826         OPT_STRING('x', "field-separator", &csv_sep, "separator",
1827                    "print counts with custom separator"),
1828         OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1829                      "monitor event in cgroup name only", parse_cgroups),
1830         OPT_STRING('o', "output", &output_name, "file", "output file name"),
1831         OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1832         OPT_INTEGER(0, "log-fd", &output_fd,
1833                     "log output to fd, instead of stderr"),
1834         OPT_STRING(0, "pre", &pre_cmd, "command",
1835                         "command to run prior to the measured command"),
1836         OPT_STRING(0, "post", &post_cmd, "command",
1837                         "command to run after to the measured command"),
1838         OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1839                     "print counts at regular interval in ms (>= 10)"),
1840         OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1841                      "aggregate counts per processor socket", AGGR_SOCKET),
1842         OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1843                      "aggregate counts per physical processor core", AGGR_CORE),
1844         OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1845                      "aggregate counts per thread", AGGR_THREAD),
1846         OPT_UINTEGER('D', "delay", &initial_delay,
1847                      "ms to wait before starting measurement after program start"),
1848         OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
1849                         "Only print computed metrics. No raw values", enable_metric_only),
1850         OPT_BOOLEAN(0, "topdown", &topdown_run,
1851                         "measure topdown level 1 statistics"),
1852         OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1853                         "measure SMI cost"),
1854         OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1855                      "monitor specified metrics or metric groups (separated by ,)",
1856                      parse_metric_groups),
1857         OPT_END()
1858 };
1859
1860 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1861 {
1862         return cpu_map__get_socket(map, cpu, NULL);
1863 }
1864
1865 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1866 {
1867         return cpu_map__get_core(map, cpu, NULL);
1868 }
1869
1870 static int cpu_map__get_max(struct cpu_map *map)
1871 {
1872         int i, max = -1;
1873
1874         for (i = 0; i < map->nr; i++) {
1875                 if (map->map[i] > max)
1876                         max = map->map[i];
1877         }
1878
1879         return max;
1880 }
1881
1882 static struct cpu_map *cpus_aggr_map;
1883
1884 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1885 {
1886         int cpu;
1887
1888         if (idx >= map->nr)
1889                 return -1;
1890
1891         cpu = map->map[idx];
1892
1893         if (cpus_aggr_map->map[cpu] == -1)
1894                 cpus_aggr_map->map[cpu] = get_id(map, idx);
1895
1896         return cpus_aggr_map->map[cpu];
1897 }
1898
1899 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1900 {
1901         return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1902 }
1903
1904 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1905 {
1906         return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1907 }
1908
1909 static int perf_stat_init_aggr_mode(void)
1910 {
1911         int nr;
1912
1913         switch (stat_config.aggr_mode) {
1914         case AGGR_SOCKET:
1915                 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1916                         perror("cannot build socket map");
1917                         return -1;
1918                 }
1919                 aggr_get_id = perf_stat__get_socket_cached;
1920                 break;
1921         case AGGR_CORE:
1922                 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1923                         perror("cannot build core map");
1924                         return -1;
1925                 }
1926                 aggr_get_id = perf_stat__get_core_cached;
1927                 break;
1928         case AGGR_NONE:
1929         case AGGR_GLOBAL:
1930         case AGGR_THREAD:
1931         case AGGR_UNSET:
1932         default:
1933                 break;
1934         }
1935
1936         /*
1937          * The evsel_list->cpus is the base we operate on,
1938          * taking the highest cpu number to be the size of
1939          * the aggregation translate cpumap.
1940          */
1941         nr = cpu_map__get_max(evsel_list->cpus);
1942         cpus_aggr_map = cpu_map__empty_new(nr + 1);
1943         return cpus_aggr_map ? 0 : -ENOMEM;
1944 }
1945
1946 static void perf_stat__exit_aggr_mode(void)
1947 {
1948         cpu_map__put(aggr_map);
1949         cpu_map__put(cpus_aggr_map);
1950         aggr_map = NULL;
1951         cpus_aggr_map = NULL;
1952 }
1953
1954 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1955 {
1956         int cpu;
1957
1958         if (idx > map->nr)
1959                 return -1;
1960
1961         cpu = map->map[idx];
1962
1963         if (cpu >= env->nr_cpus_avail)
1964                 return -1;
1965
1966         return cpu;
1967 }
1968
1969 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1970 {
1971         struct perf_env *env = data;
1972         int cpu = perf_env__get_cpu(env, map, idx);
1973
1974         return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1975 }
1976
1977 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1978 {
1979         struct perf_env *env = data;
1980         int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1981
1982         if (cpu != -1) {
1983                 int socket_id = env->cpu[cpu].socket_id;
1984
1985                 /*
1986                  * Encode socket in upper 16 bits
1987                  * core_id is relative to socket, and
1988                  * we need a global id. So we combine
1989                  * socket + core id.
1990                  */
1991                 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1992         }
1993
1994         return core;
1995 }
1996
1997 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1998                                       struct cpu_map **sockp)
1999 {
2000         return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
2001 }
2002
2003 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
2004                                     struct cpu_map **corep)
2005 {
2006         return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
2007 }
2008
2009 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
2010 {
2011         return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
2012 }
2013
2014 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
2015 {
2016         return perf_env__get_core(map, idx, &perf_stat.session->header.env);
2017 }
2018
2019 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
2020 {
2021         struct perf_env *env = &st->session->header.env;
2022
2023         switch (stat_config.aggr_mode) {
2024         case AGGR_SOCKET:
2025                 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
2026                         perror("cannot build socket map");
2027                         return -1;
2028                 }
2029                 aggr_get_id = perf_stat__get_socket_file;
2030                 break;
2031         case AGGR_CORE:
2032                 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
2033                         perror("cannot build core map");
2034                         return -1;
2035                 }
2036                 aggr_get_id = perf_stat__get_core_file;
2037                 break;
2038         case AGGR_NONE:
2039         case AGGR_GLOBAL:
2040         case AGGR_THREAD:
2041         case AGGR_UNSET:
2042         default:
2043                 break;
2044         }
2045
2046         return 0;
2047 }
2048
2049 static int topdown_filter_events(const char **attr, char **str, bool use_group)
2050 {
2051         int off = 0;
2052         int i;
2053         int len = 0;
2054         char *s;
2055
2056         for (i = 0; attr[i]; i++) {
2057                 if (pmu_have_event("cpu", attr[i])) {
2058                         len += strlen(attr[i]) + 1;
2059                         attr[i - off] = attr[i];
2060                 } else
2061                         off++;
2062         }
2063         attr[i - off] = NULL;
2064
2065         *str = malloc(len + 1 + 2);
2066         if (!*str)
2067                 return -1;
2068         s = *str;
2069         if (i - off == 0) {
2070                 *s = 0;
2071                 return 0;
2072         }
2073         if (use_group)
2074                 *s++ = '{';
2075         for (i = 0; attr[i]; i++) {
2076                 strcpy(s, attr[i]);
2077                 s += strlen(s);
2078                 *s++ = ',';
2079         }
2080         if (use_group) {
2081                 s[-1] = '}';
2082                 *s = 0;
2083         } else
2084                 s[-1] = 0;
2085         return 0;
2086 }
2087
2088 __weak bool arch_topdown_check_group(bool *warn)
2089 {
2090         *warn = false;
2091         return false;
2092 }
2093
2094 __weak void arch_topdown_group_warn(void)
2095 {
2096 }
2097
2098 /*
2099  * Add default attributes, if there were no attributes specified or
2100  * if -d/--detailed, -d -d or -d -d -d is used:
2101  */
2102 static int add_default_attributes(void)
2103 {
2104         int err;
2105         struct perf_event_attr default_attrs0[] = {
2106
2107   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK              },
2108   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES        },
2109   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS          },
2110   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS             },
2111
2112   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES              },
2113 };
2114         struct perf_event_attr frontend_attrs[] = {
2115   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
2116 };
2117         struct perf_event_attr backend_attrs[] = {
2118   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND  },
2119 };
2120         struct perf_event_attr default_attrs1[] = {
2121   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS            },
2122   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS     },
2123   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES           },
2124
2125 };
2126
2127 /*
2128  * Detailed stats (-d), covering the L1 and last level data caches:
2129  */
2130         struct perf_event_attr detailed_attrs[] = {
2131
2132   { .type = PERF_TYPE_HW_CACHE,
2133     .config =
2134          PERF_COUNT_HW_CACHE_L1D                <<  0  |
2135         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2136         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
2137
2138   { .type = PERF_TYPE_HW_CACHE,
2139     .config =
2140          PERF_COUNT_HW_CACHE_L1D                <<  0  |
2141         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2142         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
2143
2144   { .type = PERF_TYPE_HW_CACHE,
2145     .config =
2146          PERF_COUNT_HW_CACHE_LL                 <<  0  |
2147         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2148         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
2149
2150   { .type = PERF_TYPE_HW_CACHE,
2151     .config =
2152          PERF_COUNT_HW_CACHE_LL                 <<  0  |
2153         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2154         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
2155 };
2156
2157 /*
2158  * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2159  */
2160         struct perf_event_attr very_detailed_attrs[] = {
2161
2162   { .type = PERF_TYPE_HW_CACHE,
2163     .config =
2164          PERF_COUNT_HW_CACHE_L1I                <<  0  |
2165         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2166         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
2167
2168   { .type = PERF_TYPE_HW_CACHE,
2169     .config =
2170          PERF_COUNT_HW_CACHE_L1I                <<  0  |
2171         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2172         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
2173
2174   { .type = PERF_TYPE_HW_CACHE,
2175     .config =
2176          PERF_COUNT_HW_CACHE_DTLB               <<  0  |
2177         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2178         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
2179
2180   { .type = PERF_TYPE_HW_CACHE,
2181     .config =
2182          PERF_COUNT_HW_CACHE_DTLB               <<  0  |
2183         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2184         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
2185
2186   { .type = PERF_TYPE_HW_CACHE,
2187     .config =
2188          PERF_COUNT_HW_CACHE_ITLB               <<  0  |
2189         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2190         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
2191
2192   { .type = PERF_TYPE_HW_CACHE,
2193     .config =
2194          PERF_COUNT_HW_CACHE_ITLB               <<  0  |
2195         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2196         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
2197
2198 };
2199
2200 /*
2201  * Very, very detailed stats (-d -d -d), adding prefetch events:
2202  */
2203         struct perf_event_attr very_very_detailed_attrs[] = {
2204
2205   { .type = PERF_TYPE_HW_CACHE,
2206     .config =
2207          PERF_COUNT_HW_CACHE_L1D                <<  0  |
2208         (PERF_COUNT_HW_CACHE_OP_PREFETCH        <<  8) |
2209         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
2210
2211   { .type = PERF_TYPE_HW_CACHE,
2212     .config =
2213          PERF_COUNT_HW_CACHE_L1D                <<  0  |
2214         (PERF_COUNT_HW_CACHE_OP_PREFETCH        <<  8) |
2215         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
2216 };
2217
2218         /* Set attrs if no event is selected and !null_run: */
2219         if (null_run)
2220                 return 0;
2221
2222         if (transaction_run) {
2223                 if (pmu_have_event("cpu", "cycles-ct") &&
2224                     pmu_have_event("cpu", "el-start"))
2225                         err = parse_events(evsel_list, transaction_attrs, NULL);
2226                 else
2227                         err = parse_events(evsel_list, transaction_limited_attrs, NULL);
2228                 if (err) {
2229                         fprintf(stderr, "Cannot set up transaction events\n");
2230                         return -1;
2231                 }
2232                 return 0;
2233         }
2234
2235         if (smi_cost) {
2236                 int smi;
2237
2238                 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
2239                         fprintf(stderr, "freeze_on_smi is not supported.\n");
2240                         return -1;
2241                 }
2242
2243                 if (!smi) {
2244                         if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
2245                                 fprintf(stderr, "Failed to set freeze_on_smi.\n");
2246                                 return -1;
2247                         }
2248                         smi_reset = true;
2249                 }
2250
2251                 if (pmu_have_event("msr", "aperf") &&
2252                     pmu_have_event("msr", "smi")) {
2253                         if (!force_metric_only)
2254                                 metric_only = true;
2255                         err = parse_events(evsel_list, smi_cost_attrs, NULL);
2256                 } else {
2257                         fprintf(stderr, "To measure SMI cost, it needs "
2258                                 "msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
2259                         return -1;
2260                 }
2261                 if (err) {
2262                         fprintf(stderr, "Cannot set up SMI cost events\n");
2263                         return -1;
2264                 }
2265                 return 0;
2266         }
2267
2268         if (topdown_run) {
2269                 char *str = NULL;
2270                 bool warn = false;
2271
2272                 if (stat_config.aggr_mode != AGGR_GLOBAL &&
2273                     stat_config.aggr_mode != AGGR_CORE) {
2274                         pr_err("top down event configuration requires --per-core mode\n");
2275                         return -1;
2276                 }
2277                 stat_config.aggr_mode = AGGR_CORE;
2278                 if (nr_cgroups || !target__has_cpu(&target)) {
2279                         pr_err("top down event configuration requires system-wide mode (-a)\n");
2280                         return -1;
2281                 }
2282
2283                 if (!force_metric_only)
2284                         metric_only = true;
2285                 if (topdown_filter_events(topdown_attrs, &str,
2286                                 arch_topdown_check_group(&warn)) < 0) {
2287                         pr_err("Out of memory\n");
2288                         return -1;
2289                 }
2290                 if (topdown_attrs[0] && str) {
2291                         if (warn)
2292                                 arch_topdown_group_warn();
2293                         err = parse_events(evsel_list, str, NULL);
2294                         if (err) {
2295                                 fprintf(stderr,
2296                                         "Cannot set up top down events %s: %d\n",
2297                                         str, err);
2298                                 free(str);
2299                                 return -1;
2300                         }
2301                 } else {
2302                         fprintf(stderr, "System does not support topdown\n");
2303                         return -1;
2304                 }
2305                 free(str);
2306         }
2307
2308         if (!evsel_list->nr_entries) {
2309                 if (target__has_cpu(&target))
2310                         default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2311
2312                 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2313                         return -1;
2314                 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2315                         if (perf_evlist__add_default_attrs(evsel_list,
2316                                                 frontend_attrs) < 0)
2317                                 return -1;
2318                 }
2319                 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2320                         if (perf_evlist__add_default_attrs(evsel_list,
2321                                                 backend_attrs) < 0)
2322                                 return -1;
2323                 }
2324                 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2325                         return -1;
2326         }
2327
2328         /* Detailed events get appended to the event list: */
2329
2330         if (detailed_run <  1)
2331                 return 0;
2332
2333         /* Append detailed run extra attributes: */
2334         if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2335                 return -1;
2336
2337         if (detailed_run < 2)
2338                 return 0;
2339
2340         /* Append very detailed run extra attributes: */
2341         if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2342                 return -1;
2343
2344         if (detailed_run < 3)
2345                 return 0;
2346
2347         /* Append very, very detailed run extra attributes: */
2348         return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2349 }
2350
2351 static const char * const stat_record_usage[] = {
2352         "perf stat record [<options>]",
2353         NULL,
2354 };
2355
2356 static void init_features(struct perf_session *session)
2357 {
2358         int feat;
2359
2360         for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2361                 perf_header__set_feat(&session->header, feat);
2362
2363         perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2364         perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2365         perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2366         perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2367 }
2368
2369 static int __cmd_record(int argc, const char **argv)
2370 {
2371         struct perf_session *session;
2372         struct perf_data *data = &perf_stat.data;
2373
2374         argc = parse_options(argc, argv, stat_options, stat_record_usage,
2375                              PARSE_OPT_STOP_AT_NON_OPTION);
2376
2377         if (output_name)
2378                 data->file.path = output_name;
2379
2380         if (run_count != 1 || forever) {
2381                 pr_err("Cannot use -r option with perf stat record.\n");
2382                 return -1;
2383         }
2384
2385         session = perf_session__new(data, false, NULL);
2386         if (session == NULL) {
2387                 pr_err("Perf session creation failed.\n");
2388                 return -1;
2389         }
2390
2391         init_features(session);
2392
2393         session->evlist   = evsel_list;
2394         perf_stat.session = session;
2395         perf_stat.record  = true;
2396         return argc;
2397 }
2398
2399 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2400                                     union perf_event *event,
2401                                     struct perf_session *session)
2402 {
2403         struct stat_round_event *stat_round = &event->stat_round;
2404         struct perf_evsel *counter;
2405         struct timespec tsh, *ts = NULL;
2406         const char **argv = session->header.env.cmdline_argv;
2407         int argc = session->header.env.nr_cmdline;
2408
2409         evlist__for_each_entry(evsel_list, counter)
2410                 perf_stat_process_counter(&stat_config, counter);
2411
2412         if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2413                 update_stats(&walltime_nsecs_stats, stat_round->time);
2414
2415         if (stat_config.interval && stat_round->time) {
2416                 tsh.tv_sec  = stat_round->time / NSEC_PER_SEC;
2417                 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2418                 ts = &tsh;
2419         }
2420
2421         print_counters(ts, argc, argv);
2422         return 0;
2423 }
2424
2425 static
2426 int process_stat_config_event(struct perf_tool *tool,
2427                               union perf_event *event,
2428                               struct perf_session *session __maybe_unused)
2429 {
2430         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2431
2432         perf_event__read_stat_config(&stat_config, &event->stat_config);
2433
2434         if (cpu_map__empty(st->cpus)) {
2435                 if (st->aggr_mode != AGGR_UNSET)
2436                         pr_warning("warning: processing task data, aggregation mode not set\n");
2437                 return 0;
2438         }
2439
2440         if (st->aggr_mode != AGGR_UNSET)
2441                 stat_config.aggr_mode = st->aggr_mode;
2442
2443         if (perf_stat.data.is_pipe)
2444                 perf_stat_init_aggr_mode();
2445         else
2446                 perf_stat_init_aggr_mode_file(st);
2447
2448         return 0;
2449 }
2450
2451 static int set_maps(struct perf_stat *st)
2452 {
2453         if (!st->cpus || !st->threads)
2454                 return 0;
2455
2456         if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2457                 return -EINVAL;
2458
2459         perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2460
2461         if (perf_evlist__alloc_stats(evsel_list, true))
2462                 return -ENOMEM;
2463
2464         st->maps_allocated = true;
2465         return 0;
2466 }
2467
2468 static
2469 int process_thread_map_event(struct perf_tool *tool,
2470                              union perf_event *event,
2471                              struct perf_session *session __maybe_unused)
2472 {
2473         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2474
2475         if (st->threads) {
2476                 pr_warning("Extra thread map event, ignoring.\n");
2477                 return 0;
2478         }
2479
2480         st->threads = thread_map__new_event(&event->thread_map);
2481         if (!st->threads)
2482                 return -ENOMEM;
2483
2484         return set_maps(st);
2485 }
2486
2487 static
2488 int process_cpu_map_event(struct perf_tool *tool,
2489                           union perf_event *event,
2490                           struct perf_session *session __maybe_unused)
2491 {
2492         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2493         struct cpu_map *cpus;
2494
2495         if (st->cpus) {
2496                 pr_warning("Extra cpu map event, ignoring.\n");
2497                 return 0;
2498         }
2499
2500         cpus = cpu_map__new_data(&event->cpu_map.data);
2501         if (!cpus)
2502                 return -ENOMEM;
2503
2504         st->cpus = cpus;
2505         return set_maps(st);
2506 }
2507
2508 static int runtime_stat_new(struct perf_stat_config *config, int nthreads)
2509 {
2510         int i;
2511
2512         config->stats = calloc(nthreads, sizeof(struct runtime_stat));
2513         if (!config->stats)
2514                 return -1;
2515
2516         config->stats_num = nthreads;
2517
2518         for (i = 0; i < nthreads; i++)
2519                 runtime_stat__init(&config->stats[i]);
2520
2521         return 0;
2522 }
2523
2524 static void runtime_stat_delete(struct perf_stat_config *config)
2525 {
2526         int i;
2527
2528         if (!config->stats)
2529                 return;
2530
2531         for (i = 0; i < config->stats_num; i++)
2532                 runtime_stat__exit(&config->stats[i]);
2533
2534         free(config->stats);
2535 }
2536
2537 static const char * const stat_report_usage[] = {
2538         "perf stat report [<options>]",
2539         NULL,
2540 };
2541
2542 static struct perf_stat perf_stat = {
2543         .tool = {
2544                 .attr           = perf_event__process_attr,
2545                 .event_update   = perf_event__process_event_update,
2546                 .thread_map     = process_thread_map_event,
2547                 .cpu_map        = process_cpu_map_event,
2548                 .stat_config    = process_stat_config_event,
2549                 .stat           = perf_event__process_stat_event,
2550                 .stat_round     = process_stat_round_event,
2551         },
2552         .aggr_mode = AGGR_UNSET,
2553 };
2554
2555 static int __cmd_report(int argc, const char **argv)
2556 {
2557         struct perf_session *session;
2558         const struct option options[] = {
2559         OPT_STRING('i', "input", &input_name, "file", "input file name"),
2560         OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2561                      "aggregate counts per processor socket", AGGR_SOCKET),
2562         OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2563                      "aggregate counts per physical processor core", AGGR_CORE),
2564         OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2565                      "disable CPU count aggregation", AGGR_NONE),
2566         OPT_END()
2567         };
2568         struct stat st;
2569         int ret;
2570
2571         argc = parse_options(argc, argv, options, stat_report_usage, 0);
2572
2573         if (!input_name || !strlen(input_name)) {
2574                 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2575                         input_name = "-";
2576                 else
2577                         input_name = "perf.data";
2578         }
2579
2580         perf_stat.data.file.path = input_name;
2581         perf_stat.data.mode      = PERF_DATA_MODE_READ;
2582
2583         session = perf_session__new(&perf_stat.data, false, &perf_stat.tool);
2584         if (session == NULL)
2585                 return -1;
2586
2587         perf_stat.session  = session;
2588         stat_config.output = stderr;
2589         evsel_list         = session->evlist;
2590
2591         ret = perf_session__process_events(session);
2592         if (ret)
2593                 return ret;
2594
2595         perf_session__delete(session);
2596         return 0;
2597 }
2598
2599 static void setup_system_wide(int forks)
2600 {
2601         /*
2602          * Make system wide (-a) the default target if
2603          * no target was specified and one of following
2604          * conditions is met:
2605          *
2606          *   - there's no workload specified
2607          *   - there is workload specified but all requested
2608          *     events are system wide events
2609          */
2610         if (!target__none(&target))
2611                 return;
2612
2613         if (!forks)
2614                 target.system_wide = true;
2615         else {
2616                 struct perf_evsel *counter;
2617
2618                 evlist__for_each_entry(evsel_list, counter) {
2619                         if (!counter->system_wide)
2620                                 return;
2621                 }
2622
2623                 if (evsel_list->nr_entries)
2624                         target.system_wide = true;
2625         }
2626 }
2627
2628 int cmd_stat(int argc, const char **argv)
2629 {
2630         const char * const stat_usage[] = {
2631                 "perf stat [<options>] [<command>]",
2632                 NULL
2633         };
2634         int status = -EINVAL, run_idx;
2635         const char *mode;
2636         FILE *output = stderr;
2637         unsigned int interval;
2638         const char * const stat_subcommands[] = { "record", "report" };
2639
2640         setlocale(LC_ALL, "");
2641
2642         evsel_list = perf_evlist__new();
2643         if (evsel_list == NULL)
2644                 return -ENOMEM;
2645
2646         parse_events__shrink_config_terms();
2647         argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2648                                         (const char **) stat_usage,
2649                                         PARSE_OPT_STOP_AT_NON_OPTION);
2650         perf_stat__collect_metric_expr(evsel_list);
2651         perf_stat__init_shadow_stats();
2652
2653         if (csv_sep) {
2654                 csv_output = true;
2655                 if (!strcmp(csv_sep, "\\t"))
2656                         csv_sep = "\t";
2657         } else
2658                 csv_sep = DEFAULT_SEPARATOR;
2659
2660         if (argc && !strncmp(argv[0], "rec", 3)) {
2661                 argc = __cmd_record(argc, argv);
2662                 if (argc < 0)
2663                         return -1;
2664         } else if (argc && !strncmp(argv[0], "rep", 3))
2665                 return __cmd_report(argc, argv);
2666
2667         interval = stat_config.interval;
2668
2669         /*
2670          * For record command the -o is already taken care of.
2671          */
2672         if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2673                 output = NULL;
2674
2675         if (output_name && output_fd) {
2676                 fprintf(stderr, "cannot use both --output and --log-fd\n");
2677                 parse_options_usage(stat_usage, stat_options, "o", 1);
2678                 parse_options_usage(NULL, stat_options, "log-fd", 0);
2679                 goto out;
2680         }
2681
2682         if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2683                 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2684                 goto out;
2685         }
2686
2687         if (metric_only && run_count > 1) {
2688                 fprintf(stderr, "--metric-only is not supported with -r\n");
2689                 goto out;
2690         }
2691
2692         if (output_fd < 0) {
2693                 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2694                 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2695                 goto out;
2696         }
2697
2698         if (!output) {
2699                 struct timespec tm;
2700                 mode = append_file ? "a" : "w";
2701
2702                 output = fopen(output_name, mode);
2703                 if (!output) {
2704                         perror("failed to create output file");
2705                         return -1;
2706                 }
2707                 clock_gettime(CLOCK_REALTIME, &tm);
2708                 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2709         } else if (output_fd > 0) {
2710                 mode = append_file ? "a" : "w";
2711                 output = fdopen(output_fd, mode);
2712                 if (!output) {
2713                         perror("Failed opening logfd");
2714                         return -errno;
2715                 }
2716         }
2717
2718         stat_config.output = output;
2719
2720         /*
2721          * let the spreadsheet do the pretty-printing
2722          */
2723         if (csv_output) {
2724                 /* User explicitly passed -B? */
2725                 if (big_num_opt == 1) {
2726                         fprintf(stderr, "-B option not supported with -x\n");
2727                         parse_options_usage(stat_usage, stat_options, "B", 1);
2728                         parse_options_usage(NULL, stat_options, "x", 1);
2729                         goto out;
2730                 } else /* Nope, so disable big number formatting */
2731                         big_num = false;
2732         } else if (big_num_opt == 0) /* User passed --no-big-num */
2733                 big_num = false;
2734
2735         setup_system_wide(argc);
2736
2737         if (run_count < 0) {
2738                 pr_err("Run count must be a positive number\n");
2739                 parse_options_usage(stat_usage, stat_options, "r", 1);
2740                 goto out;
2741         } else if (run_count == 0) {
2742                 forever = true;
2743                 run_count = 1;
2744         }
2745
2746         if ((stat_config.aggr_mode == AGGR_THREAD) &&
2747                 !target__has_task(&target)) {
2748                 if (!target.system_wide || target.cpu_list) {
2749                         fprintf(stderr, "The --per-thread option is only "
2750                                 "available when monitoring via -p -t -a "
2751                                 "options or only --per-thread.\n");
2752                         parse_options_usage(NULL, stat_options, "p", 1);
2753                         parse_options_usage(NULL, stat_options, "t", 1);
2754                         goto out;
2755                 }
2756         }
2757
2758         /*
2759          * no_aggr, cgroup are for system-wide only
2760          * --per-thread is aggregated per thread, we dont mix it with cpu mode
2761          */
2762         if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2763               stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2764             !target__has_cpu(&target)) {
2765                 fprintf(stderr, "both cgroup and no-aggregation "
2766                         "modes only available in system-wide mode\n");
2767
2768                 parse_options_usage(stat_usage, stat_options, "G", 1);
2769                 parse_options_usage(NULL, stat_options, "A", 1);
2770                 parse_options_usage(NULL, stat_options, "a", 1);
2771                 goto out;
2772         }
2773
2774         if (add_default_attributes())
2775                 goto out;
2776
2777         target__validate(&target);
2778
2779         if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2780                 target.per_thread = true;
2781
2782         if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2783                 if (target__has_task(&target)) {
2784                         pr_err("Problems finding threads of monitor\n");
2785                         parse_options_usage(stat_usage, stat_options, "p", 1);
2786                         parse_options_usage(NULL, stat_options, "t", 1);
2787                 } else if (target__has_cpu(&target)) {
2788                         perror("failed to parse CPUs map");
2789                         parse_options_usage(stat_usage, stat_options, "C", 1);
2790                         parse_options_usage(NULL, stat_options, "a", 1);
2791                 }
2792                 goto out;
2793         }
2794
2795         /*
2796          * Initialize thread_map with comm names,
2797          * so we could print it out on output.
2798          */
2799         if (stat_config.aggr_mode == AGGR_THREAD) {
2800                 thread_map__read_comms(evsel_list->threads);
2801                 if (target.system_wide) {
2802                         if (runtime_stat_new(&stat_config,
2803                                 thread_map__nr(evsel_list->threads))) {
2804                                 goto out;
2805                         }
2806                 }
2807         }
2808
2809         if (interval && interval < 100) {
2810                 if (interval < 10) {
2811                         pr_err("print interval must be >= 10ms\n");
2812                         parse_options_usage(stat_usage, stat_options, "I", 1);
2813                         goto out;
2814                 } else
2815                         pr_warning("print interval < 100ms. "
2816                                    "The overhead percentage could be high in some cases. "
2817                                    "Please proceed with caution.\n");
2818         }
2819
2820         if (perf_evlist__alloc_stats(evsel_list, interval))
2821                 goto out;
2822
2823         if (perf_stat_init_aggr_mode())
2824                 goto out;
2825
2826         /*
2827          * We dont want to block the signals - that would cause
2828          * child tasks to inherit that and Ctrl-C would not work.
2829          * What we want is for Ctrl-C to work in the exec()-ed
2830          * task, but being ignored by perf stat itself:
2831          */
2832         atexit(sig_atexit);
2833         if (!forever)
2834                 signal(SIGINT,  skip_signal);
2835         signal(SIGCHLD, skip_signal);
2836         signal(SIGALRM, skip_signal);
2837         signal(SIGABRT, skip_signal);
2838
2839         status = 0;
2840         for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2841                 if (run_count != 1 && verbose > 0)
2842                         fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2843                                 run_idx + 1);
2844
2845                 status = run_perf_stat(argc, argv);
2846                 if (forever && status != -1) {
2847                         print_counters(NULL, argc, argv);
2848                         perf_stat__reset_stats();
2849                 }
2850         }
2851
2852         if (!forever && status != -1 && !interval)
2853                 print_counters(NULL, argc, argv);
2854
2855         if (STAT_RECORD) {
2856                 /*
2857                  * We synthesize the kernel mmap record just so that older tools
2858                  * don't emit warnings about not being able to resolve symbols
2859                  * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2860                  * a saner message about no samples being in the perf.data file.
2861                  *
2862                  * This also serves to suppress a warning about f_header.data.size == 0
2863                  * in header.c at the moment 'perf stat record' gets introduced, which
2864                  * is not really needed once we start adding the stat specific PERF_RECORD_
2865                  * records, but the need to suppress the kptr_restrict messages in older
2866                  * tools remain  -acme
2867                  */
2868                 int fd = perf_data__fd(&perf_stat.data);
2869                 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2870                                                              process_synthesized_event,
2871                                                              &perf_stat.session->machines.host);
2872                 if (err) {
2873                         pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2874                                    "older tools may produce warnings about this file\n.");
2875                 }
2876
2877                 if (!interval) {
2878                         if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2879                                 pr_err("failed to write stat round event\n");
2880                 }
2881
2882                 if (!perf_stat.data.is_pipe) {
2883                         perf_stat.session->header.data_size += perf_stat.bytes_written;
2884                         perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2885                 }
2886
2887                 perf_session__delete(perf_stat.session);
2888         }
2889
2890         perf_stat__exit_aggr_mode();
2891         perf_evlist__free_stats(evsel_list);
2892 out:
2893         if (smi_cost && smi_reset)
2894                 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2895
2896         perf_evlist__delete(evsel_list);
2897
2898         runtime_stat_delete(&stat_config);
2899
2900         return status;
2901 }