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