Merge remote-tracking branch 'acme/perf-tools' into perf-tools-next
[platform/kernel/linux-rpi.git] / tools / perf / builtin-stat.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * builtin-stat.c
4  *
5  * Builtin stat command: Give a precise performance counters summary
6  * overview about any workload, CPU or specific PID.
7  *
8  * Sample output:
9
10    $ perf stat ./hackbench 10
11
12   Time: 0.118
13
14   Performance counter stats for './hackbench 10':
15
16        1708.761321 task-clock                #   11.037 CPUs utilized
17             41,190 context-switches          #    0.024 M/sec
18              6,735 CPU-migrations            #    0.004 M/sec
19             17,318 page-faults               #    0.010 M/sec
20      5,205,202,243 cycles                    #    3.046 GHz
21      3,856,436,920 stalled-cycles-frontend   #   74.09% frontend cycles idle
22      1,600,790,871 stalled-cycles-backend    #   30.75% backend  cycles idle
23      2,603,501,247 instructions              #    0.50  insns per cycle
24                                              #    1.48  stalled cycles per insn
25        484,357,498 branches                  #  283.455 M/sec
26          6,388,934 branch-misses             #    1.32% of all branches
27
28         0.154822978  seconds time elapsed
29
30  *
31  * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
32  *
33  * Improvements and fixes by:
34  *
35  *   Arjan van de Ven <arjan@linux.intel.com>
36  *   Yanmin Zhang <yanmin.zhang@intel.com>
37  *   Wu Fengguang <fengguang.wu@intel.com>
38  *   Mike Galbraith <efault@gmx.de>
39  *   Paul Mackerras <paulus@samba.org>
40  *   Jaswinder Singh Rajput <jaswinder@kernel.org>
41  */
42
43 #include "builtin.h"
44 #include "perf.h"
45 #include "util/cgroup.h"
46 #include <subcmd/parse-options.h>
47 #include "util/parse-events.h"
48 #include "util/pmu.h"
49 #include "util/event.h"
50 #include "util/evlist.h"
51 #include "util/evlist-hybrid.h"
52 #include "util/evsel.h"
53 #include "util/debug.h"
54 #include "util/color.h"
55 #include "util/stat.h"
56 #include "util/header.h"
57 #include "util/cpumap.h"
58 #include "util/thread_map.h"
59 #include "util/counts.h"
60 #include "util/topdown.h"
61 #include "util/session.h"
62 #include "util/tool.h"
63 #include "util/string2.h"
64 #include "util/metricgroup.h"
65 #include "util/synthetic-events.h"
66 #include "util/target.h"
67 #include "util/time-utils.h"
68 #include "util/top.h"
69 #include "util/affinity.h"
70 #include "util/pfm.h"
71 #include "util/bpf_counter.h"
72 #include "util/iostat.h"
73 #include "util/pmu-hybrid.h"
74 #include "asm/bug.h"
75
76 #include <linux/time64.h>
77 #include <linux/zalloc.h>
78 #include <api/fs/fs.h>
79 #include <errno.h>
80 #include <signal.h>
81 #include <stdlib.h>
82 #include <sys/prctl.h>
83 #include <inttypes.h>
84 #include <locale.h>
85 #include <math.h>
86 #include <sys/types.h>
87 #include <sys/stat.h>
88 #include <sys/wait.h>
89 #include <unistd.h>
90 #include <sys/time.h>
91 #include <sys/resource.h>
92 #include <linux/err.h>
93
94 #include <linux/ctype.h>
95 #include <perf/evlist.h>
96 #include <internal/threadmap.h>
97
98 #define DEFAULT_SEPARATOR       " "
99 #define FREEZE_ON_SMI_PATH      "devices/cpu/freeze_on_smi"
100
101 static void print_counters(struct timespec *ts, int argc, const char **argv);
102
103 static struct evlist    *evsel_list;
104 static bool all_counters_use_bpf = true;
105
106 static struct target target = {
107         .uid    = UINT_MAX,
108 };
109
110 #define METRIC_ONLY_LEN 20
111
112 static volatile sig_atomic_t    child_pid                       = -1;
113 static int                      detailed_run                    =  0;
114 static bool                     transaction_run;
115 static bool                     topdown_run                     = false;
116 static bool                     smi_cost                        = false;
117 static bool                     smi_reset                       = false;
118 static int                      big_num_opt                     =  -1;
119 static const char               *pre_cmd                        = NULL;
120 static const char               *post_cmd                       = NULL;
121 static bool                     sync_run                        = false;
122 static bool                     forever                         = false;
123 static bool                     force_metric_only               = false;
124 static struct timespec          ref_time;
125 static bool                     append_file;
126 static bool                     interval_count;
127 static const char               *output_name;
128 static int                      output_fd;
129 static char                     *metrics;
130
131 struct perf_stat {
132         bool                     record;
133         struct perf_data         data;
134         struct perf_session     *session;
135         u64                      bytes_written;
136         struct perf_tool         tool;
137         bool                     maps_allocated;
138         struct perf_cpu_map     *cpus;
139         struct perf_thread_map *threads;
140         enum aggr_mode           aggr_mode;
141 };
142
143 static struct perf_stat         perf_stat;
144 #define STAT_RECORD             perf_stat.record
145
146 static volatile sig_atomic_t done = 0;
147
148 static struct perf_stat_config stat_config = {
149         .aggr_mode              = AGGR_GLOBAL,
150         .scale                  = true,
151         .unit_width             = 4, /* strlen("unit") */
152         .run_count              = 1,
153         .metric_only_len        = METRIC_ONLY_LEN,
154         .walltime_nsecs_stats   = &walltime_nsecs_stats,
155         .ru_stats               = &ru_stats,
156         .big_num                = true,
157         .ctl_fd                 = -1,
158         .ctl_fd_ack             = -1,
159         .iostat_run             = false,
160 };
161
162 static bool cpus_map_matched(struct evsel *a, struct evsel *b)
163 {
164         if (!a->core.cpus && !b->core.cpus)
165                 return true;
166
167         if (!a->core.cpus || !b->core.cpus)
168                 return false;
169
170         if (perf_cpu_map__nr(a->core.cpus) != perf_cpu_map__nr(b->core.cpus))
171                 return false;
172
173         for (int i = 0; i < perf_cpu_map__nr(a->core.cpus); i++) {
174                 if (perf_cpu_map__cpu(a->core.cpus, i).cpu !=
175                     perf_cpu_map__cpu(b->core.cpus, i).cpu)
176                         return false;
177         }
178
179         return true;
180 }
181
182 static void evlist__check_cpu_maps(struct evlist *evlist)
183 {
184         struct evsel *evsel, *pos, *leader;
185         char buf[1024];
186
187         if (evlist__has_hybrid(evlist))
188                 evlist__warn_hybrid_group(evlist);
189
190         evlist__for_each_entry(evlist, evsel) {
191                 leader = evsel__leader(evsel);
192
193                 /* Check that leader matches cpus with each member. */
194                 if (leader == evsel)
195                         continue;
196                 if (cpus_map_matched(leader, evsel))
197                         continue;
198
199                 /* If there's mismatch disable the group and warn user. */
200                 WARN_ONCE(1, "WARNING: grouped events cpus do not match, disabling group:\n");
201                 evsel__group_desc(leader, buf, sizeof(buf));
202                 pr_warning("  %s\n", buf);
203
204                 if (verbose > 0) {
205                         cpu_map__snprint(leader->core.cpus, buf, sizeof(buf));
206                         pr_warning("     %s: %s\n", leader->name, buf);
207                         cpu_map__snprint(evsel->core.cpus, buf, sizeof(buf));
208                         pr_warning("     %s: %s\n", evsel->name, buf);
209                 }
210
211                 for_each_group_evsel(pos, leader)
212                         evsel__remove_from_group(pos, leader);
213         }
214 }
215
216 static inline void diff_timespec(struct timespec *r, struct timespec *a,
217                                  struct timespec *b)
218 {
219         r->tv_sec = a->tv_sec - b->tv_sec;
220         if (a->tv_nsec < b->tv_nsec) {
221                 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
222                 r->tv_sec--;
223         } else {
224                 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
225         }
226 }
227
228 static void perf_stat__reset_stats(void)
229 {
230         evlist__reset_stats(evsel_list);
231         perf_stat__reset_shadow_stats();
232 }
233
234 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
235                                      union perf_event *event,
236                                      struct perf_sample *sample __maybe_unused,
237                                      struct machine *machine __maybe_unused)
238 {
239         if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
240                 pr_err("failed to write perf data, error: %m\n");
241                 return -1;
242         }
243
244         perf_stat.bytes_written += event->header.size;
245         return 0;
246 }
247
248 static int write_stat_round_event(u64 tm, u64 type)
249 {
250         return perf_event__synthesize_stat_round(NULL, tm, type,
251                                                  process_synthesized_event,
252                                                  NULL);
253 }
254
255 #define WRITE_STAT_ROUND_EVENT(time, interval) \
256         write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
257
258 #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
259
260 static int evsel__write_stat_event(struct evsel *counter, int cpu_map_idx, u32 thread,
261                                    struct perf_counts_values *count)
262 {
263         struct perf_sample_id *sid = SID(counter, cpu_map_idx, thread);
264         struct perf_cpu cpu = perf_cpu_map__cpu(evsel__cpus(counter), cpu_map_idx);
265
266         return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
267                                            process_synthesized_event, NULL);
268 }
269
270 static int read_single_counter(struct evsel *counter, int cpu_map_idx,
271                                int thread, struct timespec *rs)
272 {
273         switch(counter->tool_event) {
274                 case PERF_TOOL_DURATION_TIME: {
275                         u64 val = rs->tv_nsec + rs->tv_sec*1000000000ULL;
276                         struct perf_counts_values *count =
277                                 perf_counts(counter->counts, cpu_map_idx, thread);
278                         count->ena = count->run = val;
279                         count->val = val;
280                         return 0;
281                 }
282                 case PERF_TOOL_USER_TIME:
283                 case PERF_TOOL_SYSTEM_TIME: {
284                         u64 val;
285                         struct perf_counts_values *count =
286                                 perf_counts(counter->counts, cpu_map_idx, thread);
287                         if (counter->tool_event == PERF_TOOL_USER_TIME)
288                                 val = ru_stats.ru_utime_usec_stat.mean;
289                         else
290                                 val = ru_stats.ru_stime_usec_stat.mean;
291                         count->ena = count->run = val;
292                         count->val = val;
293                         return 0;
294                 }
295                 default:
296                 case PERF_TOOL_NONE:
297                         return evsel__read_counter(counter, cpu_map_idx, thread);
298                 case PERF_TOOL_MAX:
299                         /* This should never be reached */
300                         return 0;
301         }
302 }
303
304 /*
305  * Read out the results of a single counter:
306  * do not aggregate counts across CPUs in system-wide mode
307  */
308 static int read_counter_cpu(struct evsel *counter, struct timespec *rs, int cpu_map_idx)
309 {
310         int nthreads = perf_thread_map__nr(evsel_list->core.threads);
311         int thread;
312
313         if (!counter->supported)
314                 return -ENOENT;
315
316         for (thread = 0; thread < nthreads; thread++) {
317                 struct perf_counts_values *count;
318
319                 count = perf_counts(counter->counts, cpu_map_idx, thread);
320
321                 /*
322                  * The leader's group read loads data into its group members
323                  * (via evsel__read_counter()) and sets their count->loaded.
324                  */
325                 if (!perf_counts__is_loaded(counter->counts, cpu_map_idx, thread) &&
326                     read_single_counter(counter, cpu_map_idx, thread, rs)) {
327                         counter->counts->scaled = -1;
328                         perf_counts(counter->counts, cpu_map_idx, thread)->ena = 0;
329                         perf_counts(counter->counts, cpu_map_idx, thread)->run = 0;
330                         return -1;
331                 }
332
333                 perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, false);
334
335                 if (STAT_RECORD) {
336                         if (evsel__write_stat_event(counter, cpu_map_idx, thread, count)) {
337                                 pr_err("failed to write stat event\n");
338                                 return -1;
339                         }
340                 }
341
342                 if (verbose > 1) {
343                         fprintf(stat_config.output,
344                                 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
345                                         evsel__name(counter),
346                                         perf_cpu_map__cpu(evsel__cpus(counter),
347                                                           cpu_map_idx).cpu,
348                                         count->val, count->ena, count->run);
349                 }
350         }
351
352         return 0;
353 }
354
355 static int read_affinity_counters(struct timespec *rs)
356 {
357         struct evlist_cpu_iterator evlist_cpu_itr;
358         struct affinity saved_affinity, *affinity;
359
360         if (all_counters_use_bpf)
361                 return 0;
362
363         if (!target__has_cpu(&target) || target__has_per_thread(&target))
364                 affinity = NULL;
365         else if (affinity__setup(&saved_affinity) < 0)
366                 return -1;
367         else
368                 affinity = &saved_affinity;
369
370         evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
371                 struct evsel *counter = evlist_cpu_itr.evsel;
372
373                 if (evsel__is_bpf(counter))
374                         continue;
375
376                 if (!counter->err) {
377                         counter->err = read_counter_cpu(counter, rs,
378                                                         evlist_cpu_itr.cpu_map_idx);
379                 }
380         }
381         if (affinity)
382                 affinity__cleanup(&saved_affinity);
383
384         return 0;
385 }
386
387 static int read_bpf_map_counters(void)
388 {
389         struct evsel *counter;
390         int err;
391
392         evlist__for_each_entry(evsel_list, counter) {
393                 if (!evsel__is_bpf(counter))
394                         continue;
395
396                 err = bpf_counter__read(counter);
397                 if (err)
398                         return err;
399         }
400         return 0;
401 }
402
403 static int read_counters(struct timespec *rs)
404 {
405         if (!stat_config.stop_read_counter) {
406                 if (read_bpf_map_counters() ||
407                     read_affinity_counters(rs))
408                         return -1;
409         }
410         return 0;
411 }
412
413 static void process_counters(void)
414 {
415         struct evsel *counter;
416
417         evlist__for_each_entry(evsel_list, counter) {
418                 if (counter->err)
419                         pr_debug("failed to read counter %s\n", counter->name);
420                 if (counter->err == 0 && perf_stat_process_counter(&stat_config, counter))
421                         pr_warning("failed to process counter %s\n", counter->name);
422                 counter->err = 0;
423         }
424
425         perf_stat_merge_counters(&stat_config, evsel_list);
426         perf_stat_process_percore(&stat_config, evsel_list);
427 }
428
429 static void process_interval(void)
430 {
431         struct timespec ts, rs;
432
433         clock_gettime(CLOCK_MONOTONIC, &ts);
434         diff_timespec(&rs, &ts, &ref_time);
435
436         evlist__reset_aggr_stats(evsel_list);
437
438         if (read_counters(&rs) == 0)
439                 process_counters();
440
441         if (STAT_RECORD) {
442                 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
443                         pr_err("failed to write stat round event\n");
444         }
445
446         init_stats(&walltime_nsecs_stats);
447         update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000ULL);
448         print_counters(&rs, 0, NULL);
449 }
450
451 static bool handle_interval(unsigned int interval, int *times)
452 {
453         if (interval) {
454                 process_interval();
455                 if (interval_count && !(--(*times)))
456                         return true;
457         }
458         return false;
459 }
460
461 static int enable_counters(void)
462 {
463         struct evsel *evsel;
464         int err;
465
466         evlist__for_each_entry(evsel_list, evsel) {
467                 if (!evsel__is_bpf(evsel))
468                         continue;
469
470                 err = bpf_counter__enable(evsel);
471                 if (err)
472                         return err;
473         }
474
475         if (!target__enable_on_exec(&target)) {
476                 if (!all_counters_use_bpf)
477                         evlist__enable(evsel_list);
478         }
479         return 0;
480 }
481
482 static void disable_counters(void)
483 {
484         struct evsel *counter;
485
486         /*
487          * If we don't have tracee (attaching to task or cpu), counters may
488          * still be running. To get accurate group ratios, we must stop groups
489          * from counting before reading their constituent counters.
490          */
491         if (!target__none(&target)) {
492                 evlist__for_each_entry(evsel_list, counter)
493                         bpf_counter__disable(counter);
494                 if (!all_counters_use_bpf)
495                         evlist__disable(evsel_list);
496         }
497 }
498
499 static volatile sig_atomic_t workload_exec_errno;
500
501 /*
502  * evlist__prepare_workload will send a SIGUSR1
503  * if the fork fails, since we asked by setting its
504  * want_signal to true.
505  */
506 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
507                                         void *ucontext __maybe_unused)
508 {
509         workload_exec_errno = info->si_value.sival_int;
510 }
511
512 static bool evsel__should_store_id(struct evsel *counter)
513 {
514         return STAT_RECORD || counter->core.attr.read_format & PERF_FORMAT_ID;
515 }
516
517 static bool is_target_alive(struct target *_target,
518                             struct perf_thread_map *threads)
519 {
520         struct stat st;
521         int i;
522
523         if (!target__has_task(_target))
524                 return true;
525
526         for (i = 0; i < threads->nr; i++) {
527                 char path[PATH_MAX];
528
529                 scnprintf(path, PATH_MAX, "%s/%d", procfs__mountpoint(),
530                           threads->map[i].pid);
531
532                 if (!stat(path, &st))
533                         return true;
534         }
535
536         return false;
537 }
538
539 static void process_evlist(struct evlist *evlist, unsigned int interval)
540 {
541         enum evlist_ctl_cmd cmd = EVLIST_CTL_CMD_UNSUPPORTED;
542
543         if (evlist__ctlfd_process(evlist, &cmd) > 0) {
544                 switch (cmd) {
545                 case EVLIST_CTL_CMD_ENABLE:
546                         __fallthrough;
547                 case EVLIST_CTL_CMD_DISABLE:
548                         if (interval)
549                                 process_interval();
550                         break;
551                 case EVLIST_CTL_CMD_SNAPSHOT:
552                 case EVLIST_CTL_CMD_ACK:
553                 case EVLIST_CTL_CMD_UNSUPPORTED:
554                 case EVLIST_CTL_CMD_EVLIST:
555                 case EVLIST_CTL_CMD_STOP:
556                 case EVLIST_CTL_CMD_PING:
557                 default:
558                         break;
559                 }
560         }
561 }
562
563 static void compute_tts(struct timespec *time_start, struct timespec *time_stop,
564                         int *time_to_sleep)
565 {
566         int tts = *time_to_sleep;
567         struct timespec time_diff;
568
569         diff_timespec(&time_diff, time_stop, time_start);
570
571         tts -= time_diff.tv_sec * MSEC_PER_SEC +
572                time_diff.tv_nsec / NSEC_PER_MSEC;
573
574         if (tts < 0)
575                 tts = 0;
576
577         *time_to_sleep = tts;
578 }
579
580 static int dispatch_events(bool forks, int timeout, int interval, int *times)
581 {
582         int child_exited = 0, status = 0;
583         int time_to_sleep, sleep_time;
584         struct timespec time_start, time_stop;
585
586         if (interval)
587                 sleep_time = interval;
588         else if (timeout)
589                 sleep_time = timeout;
590         else
591                 sleep_time = 1000;
592
593         time_to_sleep = sleep_time;
594
595         while (!done) {
596                 if (forks)
597                         child_exited = waitpid(child_pid, &status, WNOHANG);
598                 else
599                         child_exited = !is_target_alive(&target, evsel_list->core.threads) ? 1 : 0;
600
601                 if (child_exited)
602                         break;
603
604                 clock_gettime(CLOCK_MONOTONIC, &time_start);
605                 if (!(evlist__poll(evsel_list, time_to_sleep) > 0)) { /* poll timeout or EINTR */
606                         if (timeout || handle_interval(interval, times))
607                                 break;
608                         time_to_sleep = sleep_time;
609                 } else { /* fd revent */
610                         process_evlist(evsel_list, interval);
611                         clock_gettime(CLOCK_MONOTONIC, &time_stop);
612                         compute_tts(&time_start, &time_stop, &time_to_sleep);
613                 }
614         }
615
616         return status;
617 }
618
619 enum counter_recovery {
620         COUNTER_SKIP,
621         COUNTER_RETRY,
622         COUNTER_FATAL,
623 };
624
625 static enum counter_recovery stat_handle_error(struct evsel *counter)
626 {
627         char msg[BUFSIZ];
628         /*
629          * PPC returns ENXIO for HW counters until 2.6.37
630          * (behavior changed with commit b0a873e).
631          */
632         if (errno == EINVAL || errno == ENOSYS ||
633             errno == ENOENT || errno == EOPNOTSUPP ||
634             errno == ENXIO) {
635                 if (verbose > 0)
636                         ui__warning("%s event is not supported by the kernel.\n",
637                                     evsel__name(counter));
638                 counter->supported = false;
639                 /*
640                  * errored is a sticky flag that means one of the counter's
641                  * cpu event had a problem and needs to be reexamined.
642                  */
643                 counter->errored = true;
644
645                 if ((evsel__leader(counter) != counter) ||
646                     !(counter->core.leader->nr_members > 1))
647                         return COUNTER_SKIP;
648         } else if (evsel__fallback(counter, errno, msg, sizeof(msg))) {
649                 if (verbose > 0)
650                         ui__warning("%s\n", msg);
651                 return COUNTER_RETRY;
652         } else if (target__has_per_thread(&target) &&
653                    evsel_list->core.threads &&
654                    evsel_list->core.threads->err_thread != -1) {
655                 /*
656                  * For global --per-thread case, skip current
657                  * error thread.
658                  */
659                 if (!thread_map__remove(evsel_list->core.threads,
660                                         evsel_list->core.threads->err_thread)) {
661                         evsel_list->core.threads->err_thread = -1;
662                         return COUNTER_RETRY;
663                 }
664         }
665
666         evsel__open_strerror(counter, &target, errno, msg, sizeof(msg));
667         ui__error("%s\n", msg);
668
669         if (child_pid != -1)
670                 kill(child_pid, SIGTERM);
671         return COUNTER_FATAL;
672 }
673
674 static int __run_perf_stat(int argc, const char **argv, int run_idx)
675 {
676         int interval = stat_config.interval;
677         int times = stat_config.times;
678         int timeout = stat_config.timeout;
679         char msg[BUFSIZ];
680         unsigned long long t0, t1;
681         struct evsel *counter;
682         size_t l;
683         int status = 0;
684         const bool forks = (argc > 0);
685         bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
686         struct evlist_cpu_iterator evlist_cpu_itr;
687         struct affinity saved_affinity, *affinity = NULL;
688         int err;
689         bool second_pass = false;
690
691         if (forks) {
692                 if (evlist__prepare_workload(evsel_list, &target, argv, is_pipe, workload_exec_failed_signal) < 0) {
693                         perror("failed to prepare workload");
694                         return -1;
695                 }
696                 child_pid = evsel_list->workload.pid;
697         }
698
699         if (!cpu_map__is_dummy(evsel_list->core.user_requested_cpus)) {
700                 if (affinity__setup(&saved_affinity) < 0)
701                         return -1;
702                 affinity = &saved_affinity;
703         }
704
705         evlist__for_each_entry(evsel_list, counter) {
706                 counter->reset_group = false;
707                 if (bpf_counter__load(counter, &target))
708                         return -1;
709                 if (!evsel__is_bpf(counter))
710                         all_counters_use_bpf = false;
711         }
712
713         evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
714                 counter = evlist_cpu_itr.evsel;
715
716                 /*
717                  * bperf calls evsel__open_per_cpu() in bperf__load(), so
718                  * no need to call it again here.
719                  */
720                 if (target.use_bpf)
721                         break;
722
723                 if (counter->reset_group || counter->errored)
724                         continue;
725                 if (evsel__is_bpf(counter))
726                         continue;
727 try_again:
728                 if (create_perf_stat_counter(counter, &stat_config, &target,
729                                              evlist_cpu_itr.cpu_map_idx) < 0) {
730
731                         /*
732                          * Weak group failed. We cannot just undo this here
733                          * because earlier CPUs might be in group mode, and the kernel
734                          * doesn't support mixing group and non group reads. Defer
735                          * it to later.
736                          * Don't close here because we're in the wrong affinity.
737                          */
738                         if ((errno == EINVAL || errno == EBADF) &&
739                                 evsel__leader(counter) != counter &&
740                                 counter->weak_group) {
741                                 evlist__reset_weak_group(evsel_list, counter, false);
742                                 assert(counter->reset_group);
743                                 second_pass = true;
744                                 continue;
745                         }
746
747                         switch (stat_handle_error(counter)) {
748                         case COUNTER_FATAL:
749                                 return -1;
750                         case COUNTER_RETRY:
751                                 goto try_again;
752                         case COUNTER_SKIP:
753                                 continue;
754                         default:
755                                 break;
756                         }
757
758                 }
759                 counter->supported = true;
760         }
761
762         if (second_pass) {
763                 /*
764                  * Now redo all the weak group after closing them,
765                  * and also close errored counters.
766                  */
767
768                 /* First close errored or weak retry */
769                 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
770                         counter = evlist_cpu_itr.evsel;
771
772                         if (!counter->reset_group && !counter->errored)
773                                 continue;
774
775                         perf_evsel__close_cpu(&counter->core, evlist_cpu_itr.cpu_map_idx);
776                 }
777                 /* Now reopen weak */
778                 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
779                         counter = evlist_cpu_itr.evsel;
780
781                         if (!counter->reset_group)
782                                 continue;
783 try_again_reset:
784                         pr_debug2("reopening weak %s\n", evsel__name(counter));
785                         if (create_perf_stat_counter(counter, &stat_config, &target,
786                                                      evlist_cpu_itr.cpu_map_idx) < 0) {
787
788                                 switch (stat_handle_error(counter)) {
789                                 case COUNTER_FATAL:
790                                         return -1;
791                                 case COUNTER_RETRY:
792                                         goto try_again_reset;
793                                 case COUNTER_SKIP:
794                                         continue;
795                                 default:
796                                         break;
797                                 }
798                         }
799                         counter->supported = true;
800                 }
801         }
802         affinity__cleanup(affinity);
803
804         evlist__for_each_entry(evsel_list, counter) {
805                 if (!counter->supported) {
806                         perf_evsel__free_fd(&counter->core);
807                         continue;
808                 }
809
810                 l = strlen(counter->unit);
811                 if (l > stat_config.unit_width)
812                         stat_config.unit_width = l;
813
814                 if (evsel__should_store_id(counter) &&
815                     evsel__store_ids(counter, evsel_list))
816                         return -1;
817         }
818
819         if (evlist__apply_filters(evsel_list, &counter)) {
820                 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
821                         counter->filter, evsel__name(counter), errno,
822                         str_error_r(errno, msg, sizeof(msg)));
823                 return -1;
824         }
825
826         if (STAT_RECORD) {
827                 int fd = perf_data__fd(&perf_stat.data);
828
829                 if (is_pipe) {
830                         err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
831                 } else {
832                         err = perf_session__write_header(perf_stat.session, evsel_list,
833                                                          fd, false);
834                 }
835
836                 if (err < 0)
837                         return err;
838
839                 err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
840                                                          process_synthesized_event, is_pipe);
841                 if (err < 0)
842                         return err;
843         }
844
845         if (target.initial_delay) {
846                 pr_info(EVLIST_DISABLED_MSG);
847         } else {
848                 err = enable_counters();
849                 if (err)
850                         return -1;
851         }
852
853         /* Exec the command, if any */
854         if (forks)
855                 evlist__start_workload(evsel_list);
856
857         if (target.initial_delay > 0) {
858                 usleep(target.initial_delay * USEC_PER_MSEC);
859                 err = enable_counters();
860                 if (err)
861                         return -1;
862
863                 pr_info(EVLIST_ENABLED_MSG);
864         }
865
866         t0 = rdclock();
867         clock_gettime(CLOCK_MONOTONIC, &ref_time);
868
869         if (forks) {
870                 if (interval || timeout || evlist__ctlfd_initialized(evsel_list))
871                         status = dispatch_events(forks, timeout, interval, &times);
872                 if (child_pid != -1) {
873                         if (timeout)
874                                 kill(child_pid, SIGTERM);
875                         wait4(child_pid, &status, 0, &stat_config.ru_data);
876                 }
877
878                 if (workload_exec_errno) {
879                         const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
880                         pr_err("Workload failed: %s\n", emsg);
881                         return -1;
882                 }
883
884                 if (WIFSIGNALED(status))
885                         psignal(WTERMSIG(status), argv[0]);
886         } else {
887                 status = dispatch_events(forks, timeout, interval, &times);
888         }
889
890         disable_counters();
891
892         t1 = rdclock();
893
894         if (stat_config.walltime_run_table)
895                 stat_config.walltime_run[run_idx] = t1 - t0;
896
897         if (interval && stat_config.summary) {
898                 stat_config.interval = 0;
899                 stat_config.stop_read_counter = true;
900                 init_stats(&walltime_nsecs_stats);
901                 update_stats(&walltime_nsecs_stats, t1 - t0);
902
903                 evlist__copy_prev_raw_counts(evsel_list);
904                 evlist__reset_prev_raw_counts(evsel_list);
905                 evlist__reset_aggr_stats(evsel_list);
906         } else {
907                 update_stats(&walltime_nsecs_stats, t1 - t0);
908                 update_rusage_stats(&ru_stats, &stat_config.ru_data);
909         }
910
911         /*
912          * Closing a group leader splits the group, and as we only disable
913          * group leaders, results in remaining events becoming enabled. To
914          * avoid arbitrary skew, we must read all counters before closing any
915          * group leaders.
916          */
917         if (read_counters(&(struct timespec) { .tv_nsec = t1-t0 }) == 0)
918                 process_counters();
919
920         /*
921          * We need to keep evsel_list alive, because it's processed
922          * later the evsel_list will be closed after.
923          */
924         if (!STAT_RECORD)
925                 evlist__close(evsel_list);
926
927         return WEXITSTATUS(status);
928 }
929
930 static int run_perf_stat(int argc, const char **argv, int run_idx)
931 {
932         int ret;
933
934         if (pre_cmd) {
935                 ret = system(pre_cmd);
936                 if (ret)
937                         return ret;
938         }
939
940         if (sync_run)
941                 sync();
942
943         ret = __run_perf_stat(argc, argv, run_idx);
944         if (ret)
945                 return ret;
946
947         if (post_cmd) {
948                 ret = system(post_cmd);
949                 if (ret)
950                         return ret;
951         }
952
953         return ret;
954 }
955
956 static void print_counters(struct timespec *ts, int argc, const char **argv)
957 {
958         /* Do not print anything if we record to the pipe. */
959         if (STAT_RECORD && perf_stat.data.is_pipe)
960                 return;
961         if (quiet)
962                 return;
963
964         evlist__print_counters(evsel_list, &stat_config, &target, ts, argc, argv);
965 }
966
967 static volatile sig_atomic_t signr = -1;
968
969 static void skip_signal(int signo)
970 {
971         if ((child_pid == -1) || stat_config.interval)
972                 done = 1;
973
974         signr = signo;
975         /*
976          * render child_pid harmless
977          * won't send SIGTERM to a random
978          * process in case of race condition
979          * and fast PID recycling
980          */
981         child_pid = -1;
982 }
983
984 static void sig_atexit(void)
985 {
986         sigset_t set, oset;
987
988         /*
989          * avoid race condition with SIGCHLD handler
990          * in skip_signal() which is modifying child_pid
991          * goal is to avoid send SIGTERM to a random
992          * process
993          */
994         sigemptyset(&set);
995         sigaddset(&set, SIGCHLD);
996         sigprocmask(SIG_BLOCK, &set, &oset);
997
998         if (child_pid != -1)
999                 kill(child_pid, SIGTERM);
1000
1001         sigprocmask(SIG_SETMASK, &oset, NULL);
1002
1003         if (signr == -1)
1004                 return;
1005
1006         signal(signr, SIG_DFL);
1007         kill(getpid(), signr);
1008 }
1009
1010 void perf_stat__set_big_num(int set)
1011 {
1012         stat_config.big_num = (set != 0);
1013 }
1014
1015 void perf_stat__set_no_csv_summary(int set)
1016 {
1017         stat_config.no_csv_summary = (set != 0);
1018 }
1019
1020 static int stat__set_big_num(const struct option *opt __maybe_unused,
1021                              const char *s __maybe_unused, int unset)
1022 {
1023         big_num_opt = unset ? 0 : 1;
1024         perf_stat__set_big_num(!unset);
1025         return 0;
1026 }
1027
1028 static int enable_metric_only(const struct option *opt __maybe_unused,
1029                               const char *s __maybe_unused, int unset)
1030 {
1031         force_metric_only = true;
1032         stat_config.metric_only = !unset;
1033         return 0;
1034 }
1035
1036 static int append_metric_groups(const struct option *opt __maybe_unused,
1037                                const char *str,
1038                                int unset __maybe_unused)
1039 {
1040         if (metrics) {
1041                 char *tmp;
1042
1043                 if (asprintf(&tmp, "%s,%s", metrics, str) < 0)
1044                         return -ENOMEM;
1045                 free(metrics);
1046                 metrics = tmp;
1047         } else {
1048                 metrics = strdup(str);
1049                 if (!metrics)
1050                         return -ENOMEM;
1051         }
1052         return 0;
1053 }
1054
1055 static int parse_control_option(const struct option *opt,
1056                                 const char *str,
1057                                 int unset __maybe_unused)
1058 {
1059         struct perf_stat_config *config = opt->value;
1060
1061         return evlist__parse_control(str, &config->ctl_fd, &config->ctl_fd_ack, &config->ctl_fd_close);
1062 }
1063
1064 static int parse_stat_cgroups(const struct option *opt,
1065                               const char *str, int unset)
1066 {
1067         if (stat_config.cgroup_list) {
1068                 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
1069                 return -1;
1070         }
1071
1072         return parse_cgroups(opt, str, unset);
1073 }
1074
1075 static int parse_hybrid_type(const struct option *opt,
1076                              const char *str,
1077                              int unset __maybe_unused)
1078 {
1079         struct evlist *evlist = *(struct evlist **)opt->value;
1080
1081         if (!list_empty(&evlist->core.entries)) {
1082                 fprintf(stderr, "Must define cputype before events/metrics\n");
1083                 return -1;
1084         }
1085
1086         evlist->hybrid_pmu_name = perf_pmu__hybrid_type_to_pmu(str);
1087         if (!evlist->hybrid_pmu_name) {
1088                 fprintf(stderr, "--cputype %s is not supported!\n", str);
1089                 return -1;
1090         }
1091
1092         return 0;
1093 }
1094
1095 static struct option stat_options[] = {
1096         OPT_BOOLEAN('T', "transaction", &transaction_run,
1097                     "hardware transaction statistics"),
1098         OPT_CALLBACK('e', "event", &evsel_list, "event",
1099                      "event selector. use 'perf list' to list available events",
1100                      parse_events_option),
1101         OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1102                      "event filter", parse_filter),
1103         OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
1104                     "child tasks do not inherit counters"),
1105         OPT_STRING('p', "pid", &target.pid, "pid",
1106                    "stat events on existing process id"),
1107         OPT_STRING('t', "tid", &target.tid, "tid",
1108                    "stat events on existing thread id"),
1109 #ifdef HAVE_BPF_SKEL
1110         OPT_STRING('b', "bpf-prog", &target.bpf_str, "bpf-prog-id",
1111                    "stat events on existing bpf program id"),
1112         OPT_BOOLEAN(0, "bpf-counters", &target.use_bpf,
1113                     "use bpf program to count events"),
1114         OPT_STRING(0, "bpf-attr-map", &target.attr_map, "attr-map-path",
1115                    "path to perf_event_attr map"),
1116 #endif
1117         OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1118                     "system-wide collection from all CPUs"),
1119         OPT_BOOLEAN(0, "scale", &stat_config.scale,
1120                     "Use --no-scale to disable counter scaling for multiplexing"),
1121         OPT_INCR('v', "verbose", &verbose,
1122                     "be more verbose (show counter open errors, etc)"),
1123         OPT_INTEGER('r', "repeat", &stat_config.run_count,
1124                     "repeat command and print average + stddev (max: 100, forever: 0)"),
1125         OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
1126                     "display details about each run (only with -r option)"),
1127         OPT_BOOLEAN('n', "null", &stat_config.null_run,
1128                     "null run - dont start any counters"),
1129         OPT_INCR('d', "detailed", &detailed_run,
1130                     "detailed run - start a lot of events"),
1131         OPT_BOOLEAN('S', "sync", &sync_run,
1132                     "call sync() before starting a run"),
1133         OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1134                            "print large numbers with thousands\' separators",
1135                            stat__set_big_num),
1136         OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1137                     "list of cpus to monitor in system-wide"),
1138         OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1139                     "disable CPU count aggregation", AGGR_NONE),
1140         OPT_BOOLEAN(0, "no-merge", &stat_config.no_merge, "Do not merge identical named events"),
1141         OPT_BOOLEAN(0, "hybrid-merge", &stat_config.hybrid_merge,
1142                     "Merge identical named hybrid events"),
1143         OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
1144                    "print counts with custom separator"),
1145         OPT_BOOLEAN('j', "json-output", &stat_config.json_output,
1146                    "print counts in JSON format"),
1147         OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1148                      "monitor event in cgroup name only", parse_stat_cgroups),
1149         OPT_STRING(0, "for-each-cgroup", &stat_config.cgroup_list, "name",
1150                     "expand events for each cgroup"),
1151         OPT_STRING('o', "output", &output_name, "file", "output file name"),
1152         OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1153         OPT_INTEGER(0, "log-fd", &output_fd,
1154                     "log output to fd, instead of stderr"),
1155         OPT_STRING(0, "pre", &pre_cmd, "command",
1156                         "command to run prior to the measured command"),
1157         OPT_STRING(0, "post", &post_cmd, "command",
1158                         "command to run after to the measured command"),
1159         OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1160                     "print counts at regular interval in ms "
1161                     "(overhead is possible for values <= 100ms)"),
1162         OPT_INTEGER(0, "interval-count", &stat_config.times,
1163                     "print counts for fixed number of times"),
1164         OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
1165                     "clear screen in between new interval"),
1166         OPT_UINTEGER(0, "timeout", &stat_config.timeout,
1167                     "stop workload and print counts after a timeout period in ms (>= 10ms)"),
1168         OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1169                      "aggregate counts per processor socket", AGGR_SOCKET),
1170         OPT_SET_UINT(0, "per-die", &stat_config.aggr_mode,
1171                      "aggregate counts per processor die", AGGR_DIE),
1172         OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1173                      "aggregate counts per physical processor core", AGGR_CORE),
1174         OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1175                      "aggregate counts per thread", AGGR_THREAD),
1176         OPT_SET_UINT(0, "per-node", &stat_config.aggr_mode,
1177                      "aggregate counts per numa node", AGGR_NODE),
1178         OPT_INTEGER('D', "delay", &target.initial_delay,
1179                     "ms to wait before starting measurement after program start (-1: start with events disabled)"),
1180         OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
1181                         "Only print computed metrics. No raw values", enable_metric_only),
1182         OPT_BOOLEAN(0, "metric-no-group", &stat_config.metric_no_group,
1183                        "don't group metric events, impacts multiplexing"),
1184         OPT_BOOLEAN(0, "metric-no-merge", &stat_config.metric_no_merge,
1185                        "don't try to share events between metrics in a group"),
1186         OPT_BOOLEAN(0, "metric-no-threshold", &stat_config.metric_no_threshold,
1187                        "don't try to share events between metrics in a group  "),
1188         OPT_BOOLEAN(0, "topdown", &topdown_run,
1189                         "measure top-down statistics"),
1190         OPT_UINTEGER(0, "td-level", &stat_config.topdown_level,
1191                         "Set the metrics level for the top-down statistics (0: max level)"),
1192         OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1193                         "measure SMI cost"),
1194         OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1195                      "monitor specified metrics or metric groups (separated by ,)",
1196                      append_metric_groups),
1197         OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
1198                          "Configure all used events to run in kernel space.",
1199                          PARSE_OPT_EXCLUSIVE),
1200         OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
1201                          "Configure all used events to run in user space.",
1202                          PARSE_OPT_EXCLUSIVE),
1203         OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
1204                     "Use with 'percore' event qualifier to show the event "
1205                     "counts of one hardware thread by sum up total hardware "
1206                     "threads of same physical core"),
1207         OPT_BOOLEAN(0, "summary", &stat_config.summary,
1208                        "print summary for interval mode"),
1209         OPT_BOOLEAN(0, "no-csv-summary", &stat_config.no_csv_summary,
1210                        "don't print 'summary' for CSV summary output"),
1211         OPT_BOOLEAN(0, "quiet", &quiet,
1212                         "don't print any output, messages or warnings (useful with record)"),
1213         OPT_CALLBACK(0, "cputype", &evsel_list, "hybrid cpu type",
1214                      "Only enable events on applying cpu with this type "
1215                      "for hybrid platform (e.g. core or atom)",
1216                      parse_hybrid_type),
1217 #ifdef HAVE_LIBPFM
1218         OPT_CALLBACK(0, "pfm-events", &evsel_list, "event",
1219                 "libpfm4 event selector. use 'perf list' to list available events",
1220                 parse_libpfm_events_option),
1221 #endif
1222         OPT_CALLBACK(0, "control", &stat_config, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]",
1223                      "Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events).\n"
1224                      "\t\t\t  Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n"
1225                      "\t\t\t  Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.",
1226                       parse_control_option),
1227         OPT_CALLBACK_OPTARG(0, "iostat", &evsel_list, &stat_config, "default",
1228                             "measure I/O performance metrics provided by arch/platform",
1229                             iostat_parse),
1230         OPT_END()
1231 };
1232
1233 static const char *const aggr_mode__string[] = {
1234         [AGGR_CORE] = "core",
1235         [AGGR_DIE] = "die",
1236         [AGGR_GLOBAL] = "global",
1237         [AGGR_NODE] = "node",
1238         [AGGR_NONE] = "none",
1239         [AGGR_SOCKET] = "socket",
1240         [AGGR_THREAD] = "thread",
1241         [AGGR_UNSET] = "unset",
1242 };
1243
1244 static struct aggr_cpu_id perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
1245                                                 struct perf_cpu cpu)
1246 {
1247         return aggr_cpu_id__socket(cpu, /*data=*/NULL);
1248 }
1249
1250 static struct aggr_cpu_id perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
1251                                              struct perf_cpu cpu)
1252 {
1253         return aggr_cpu_id__die(cpu, /*data=*/NULL);
1254 }
1255
1256 static struct aggr_cpu_id perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
1257                                               struct perf_cpu cpu)
1258 {
1259         return aggr_cpu_id__core(cpu, /*data=*/NULL);
1260 }
1261
1262 static struct aggr_cpu_id perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
1263                                               struct perf_cpu cpu)
1264 {
1265         return aggr_cpu_id__node(cpu, /*data=*/NULL);
1266 }
1267
1268 static struct aggr_cpu_id perf_stat__get_global(struct perf_stat_config *config __maybe_unused,
1269                                                 struct perf_cpu cpu)
1270 {
1271         return aggr_cpu_id__global(cpu, /*data=*/NULL);
1272 }
1273
1274 static struct aggr_cpu_id perf_stat__get_cpu(struct perf_stat_config *config __maybe_unused,
1275                                              struct perf_cpu cpu)
1276 {
1277         return aggr_cpu_id__cpu(cpu, /*data=*/NULL);
1278 }
1279
1280 static struct aggr_cpu_id perf_stat__get_aggr(struct perf_stat_config *config,
1281                                               aggr_get_id_t get_id, struct perf_cpu cpu)
1282 {
1283         struct aggr_cpu_id id;
1284
1285         /* per-process mode - should use global aggr mode */
1286         if (cpu.cpu == -1)
1287                 return get_id(config, cpu);
1288
1289         if (aggr_cpu_id__is_empty(&config->cpus_aggr_map->map[cpu.cpu]))
1290                 config->cpus_aggr_map->map[cpu.cpu] = get_id(config, cpu);
1291
1292         id = config->cpus_aggr_map->map[cpu.cpu];
1293         return id;
1294 }
1295
1296 static struct aggr_cpu_id perf_stat__get_socket_cached(struct perf_stat_config *config,
1297                                                        struct perf_cpu cpu)
1298 {
1299         return perf_stat__get_aggr(config, perf_stat__get_socket, cpu);
1300 }
1301
1302 static struct aggr_cpu_id perf_stat__get_die_cached(struct perf_stat_config *config,
1303                                                     struct perf_cpu cpu)
1304 {
1305         return perf_stat__get_aggr(config, perf_stat__get_die, cpu);
1306 }
1307
1308 static struct aggr_cpu_id perf_stat__get_core_cached(struct perf_stat_config *config,
1309                                                      struct perf_cpu cpu)
1310 {
1311         return perf_stat__get_aggr(config, perf_stat__get_core, cpu);
1312 }
1313
1314 static struct aggr_cpu_id perf_stat__get_node_cached(struct perf_stat_config *config,
1315                                                      struct perf_cpu cpu)
1316 {
1317         return perf_stat__get_aggr(config, perf_stat__get_node, cpu);
1318 }
1319
1320 static struct aggr_cpu_id perf_stat__get_global_cached(struct perf_stat_config *config,
1321                                                        struct perf_cpu cpu)
1322 {
1323         return perf_stat__get_aggr(config, perf_stat__get_global, cpu);
1324 }
1325
1326 static struct aggr_cpu_id perf_stat__get_cpu_cached(struct perf_stat_config *config,
1327                                                     struct perf_cpu cpu)
1328 {
1329         return perf_stat__get_aggr(config, perf_stat__get_cpu, cpu);
1330 }
1331
1332 static aggr_cpu_id_get_t aggr_mode__get_aggr(enum aggr_mode aggr_mode)
1333 {
1334         switch (aggr_mode) {
1335         case AGGR_SOCKET:
1336                 return aggr_cpu_id__socket;
1337         case AGGR_DIE:
1338                 return aggr_cpu_id__die;
1339         case AGGR_CORE:
1340                 return aggr_cpu_id__core;
1341         case AGGR_NODE:
1342                 return aggr_cpu_id__node;
1343         case AGGR_NONE:
1344                 return aggr_cpu_id__cpu;
1345         case AGGR_GLOBAL:
1346                 return aggr_cpu_id__global;
1347         case AGGR_THREAD:
1348         case AGGR_UNSET:
1349         case AGGR_MAX:
1350         default:
1351                 return NULL;
1352         }
1353 }
1354
1355 static aggr_get_id_t aggr_mode__get_id(enum aggr_mode aggr_mode)
1356 {
1357         switch (aggr_mode) {
1358         case AGGR_SOCKET:
1359                 return perf_stat__get_socket_cached;
1360         case AGGR_DIE:
1361                 return perf_stat__get_die_cached;
1362         case AGGR_CORE:
1363                 return perf_stat__get_core_cached;
1364         case AGGR_NODE:
1365                 return perf_stat__get_node_cached;
1366         case AGGR_NONE:
1367                 return perf_stat__get_cpu_cached;
1368         case AGGR_GLOBAL:
1369                 return perf_stat__get_global_cached;
1370         case AGGR_THREAD:
1371         case AGGR_UNSET:
1372         case AGGR_MAX:
1373         default:
1374                 return NULL;
1375         }
1376 }
1377
1378 static int perf_stat_init_aggr_mode(void)
1379 {
1380         int nr;
1381         aggr_cpu_id_get_t get_id = aggr_mode__get_aggr(stat_config.aggr_mode);
1382
1383         if (get_id) {
1384                 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1385                 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1386                                                          get_id, /*data=*/NULL, needs_sort);
1387                 if (!stat_config.aggr_map) {
1388                         pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
1389                         return -1;
1390                 }
1391                 stat_config.aggr_get_id = aggr_mode__get_id(stat_config.aggr_mode);
1392         }
1393
1394         if (stat_config.aggr_mode == AGGR_THREAD) {
1395                 nr = perf_thread_map__nr(evsel_list->core.threads);
1396                 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1397                 if (stat_config.aggr_map == NULL)
1398                         return -ENOMEM;
1399
1400                 for (int s = 0; s < nr; s++) {
1401                         struct aggr_cpu_id id = aggr_cpu_id__empty();
1402
1403                         id.thread_idx = s;
1404                         stat_config.aggr_map->map[s] = id;
1405                 }
1406                 return 0;
1407         }
1408
1409         /*
1410          * The evsel_list->cpus is the base we operate on,
1411          * taking the highest cpu number to be the size of
1412          * the aggregation translate cpumap.
1413          */
1414         if (evsel_list->core.user_requested_cpus)
1415                 nr = perf_cpu_map__max(evsel_list->core.user_requested_cpus).cpu;
1416         else
1417                 nr = 0;
1418         stat_config.cpus_aggr_map = cpu_aggr_map__empty_new(nr + 1);
1419         return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
1420 }
1421
1422 static void cpu_aggr_map__delete(struct cpu_aggr_map *map)
1423 {
1424         if (map) {
1425                 WARN_ONCE(refcount_read(&map->refcnt) != 0,
1426                           "cpu_aggr_map refcnt unbalanced\n");
1427                 free(map);
1428         }
1429 }
1430
1431 static void cpu_aggr_map__put(struct cpu_aggr_map *map)
1432 {
1433         if (map && refcount_dec_and_test(&map->refcnt))
1434                 cpu_aggr_map__delete(map);
1435 }
1436
1437 static void perf_stat__exit_aggr_mode(void)
1438 {
1439         cpu_aggr_map__put(stat_config.aggr_map);
1440         cpu_aggr_map__put(stat_config.cpus_aggr_map);
1441         stat_config.aggr_map = NULL;
1442         stat_config.cpus_aggr_map = NULL;
1443 }
1444
1445 static struct aggr_cpu_id perf_env__get_socket_aggr_by_cpu(struct perf_cpu cpu, void *data)
1446 {
1447         struct perf_env *env = data;
1448         struct aggr_cpu_id id = aggr_cpu_id__empty();
1449
1450         if (cpu.cpu != -1)
1451                 id.socket = env->cpu[cpu.cpu].socket_id;
1452
1453         return id;
1454 }
1455
1456 static struct aggr_cpu_id perf_env__get_die_aggr_by_cpu(struct perf_cpu cpu, void *data)
1457 {
1458         struct perf_env *env = data;
1459         struct aggr_cpu_id id = aggr_cpu_id__empty();
1460
1461         if (cpu.cpu != -1) {
1462                 /*
1463                  * die_id is relative to socket, so start
1464                  * with the socket ID and then add die to
1465                  * make a unique ID.
1466                  */
1467                 id.socket = env->cpu[cpu.cpu].socket_id;
1468                 id.die = env->cpu[cpu.cpu].die_id;
1469         }
1470
1471         return id;
1472 }
1473
1474 static struct aggr_cpu_id perf_env__get_core_aggr_by_cpu(struct perf_cpu cpu, void *data)
1475 {
1476         struct perf_env *env = data;
1477         struct aggr_cpu_id id = aggr_cpu_id__empty();
1478
1479         if (cpu.cpu != -1) {
1480                 /*
1481                  * core_id is relative to socket and die,
1482                  * we need a global id. So we set
1483                  * socket, die id and core id
1484                  */
1485                 id.socket = env->cpu[cpu.cpu].socket_id;
1486                 id.die = env->cpu[cpu.cpu].die_id;
1487                 id.core = env->cpu[cpu.cpu].core_id;
1488         }
1489
1490         return id;
1491 }
1492
1493 static struct aggr_cpu_id perf_env__get_cpu_aggr_by_cpu(struct perf_cpu cpu, void *data)
1494 {
1495         struct perf_env *env = data;
1496         struct aggr_cpu_id id = aggr_cpu_id__empty();
1497
1498         if (cpu.cpu != -1) {
1499                 /*
1500                  * core_id is relative to socket and die,
1501                  * we need a global id. So we set
1502                  * socket, die id and core id
1503                  */
1504                 id.socket = env->cpu[cpu.cpu].socket_id;
1505                 id.die = env->cpu[cpu.cpu].die_id;
1506                 id.core = env->cpu[cpu.cpu].core_id;
1507                 id.cpu = cpu;
1508         }
1509
1510         return id;
1511 }
1512
1513 static struct aggr_cpu_id perf_env__get_node_aggr_by_cpu(struct perf_cpu cpu, void *data)
1514 {
1515         struct aggr_cpu_id id = aggr_cpu_id__empty();
1516
1517         id.node = perf_env__numa_node(data, cpu);
1518         return id;
1519 }
1520
1521 static struct aggr_cpu_id perf_env__get_global_aggr_by_cpu(struct perf_cpu cpu __maybe_unused,
1522                                                            void *data __maybe_unused)
1523 {
1524         struct aggr_cpu_id id = aggr_cpu_id__empty();
1525
1526         /* it always aggregates to the cpu 0 */
1527         id.cpu = (struct perf_cpu){ .cpu = 0 };
1528         return id;
1529 }
1530
1531 static struct aggr_cpu_id perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
1532                                                      struct perf_cpu cpu)
1533 {
1534         return perf_env__get_socket_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1535 }
1536 static struct aggr_cpu_id perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
1537                                                   struct perf_cpu cpu)
1538 {
1539         return perf_env__get_die_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1540 }
1541
1542 static struct aggr_cpu_id perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
1543                                                    struct perf_cpu cpu)
1544 {
1545         return perf_env__get_core_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1546 }
1547
1548 static struct aggr_cpu_id perf_stat__get_cpu_file(struct perf_stat_config *config __maybe_unused,
1549                                                   struct perf_cpu cpu)
1550 {
1551         return perf_env__get_cpu_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1552 }
1553
1554 static struct aggr_cpu_id perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
1555                                                    struct perf_cpu cpu)
1556 {
1557         return perf_env__get_node_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1558 }
1559
1560 static struct aggr_cpu_id perf_stat__get_global_file(struct perf_stat_config *config __maybe_unused,
1561                                                      struct perf_cpu cpu)
1562 {
1563         return perf_env__get_global_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1564 }
1565
1566 static aggr_cpu_id_get_t aggr_mode__get_aggr_file(enum aggr_mode aggr_mode)
1567 {
1568         switch (aggr_mode) {
1569         case AGGR_SOCKET:
1570                 return perf_env__get_socket_aggr_by_cpu;
1571         case AGGR_DIE:
1572                 return perf_env__get_die_aggr_by_cpu;
1573         case AGGR_CORE:
1574                 return perf_env__get_core_aggr_by_cpu;
1575         case AGGR_NODE:
1576                 return perf_env__get_node_aggr_by_cpu;
1577         case AGGR_GLOBAL:
1578                 return perf_env__get_global_aggr_by_cpu;
1579         case AGGR_NONE:
1580                 return perf_env__get_cpu_aggr_by_cpu;
1581         case AGGR_THREAD:
1582         case AGGR_UNSET:
1583         case AGGR_MAX:
1584         default:
1585                 return NULL;
1586         }
1587 }
1588
1589 static aggr_get_id_t aggr_mode__get_id_file(enum aggr_mode aggr_mode)
1590 {
1591         switch (aggr_mode) {
1592         case AGGR_SOCKET:
1593                 return perf_stat__get_socket_file;
1594         case AGGR_DIE:
1595                 return perf_stat__get_die_file;
1596         case AGGR_CORE:
1597                 return perf_stat__get_core_file;
1598         case AGGR_NODE:
1599                 return perf_stat__get_node_file;
1600         case AGGR_GLOBAL:
1601                 return perf_stat__get_global_file;
1602         case AGGR_NONE:
1603                 return perf_stat__get_cpu_file;
1604         case AGGR_THREAD:
1605         case AGGR_UNSET:
1606         case AGGR_MAX:
1607         default:
1608                 return NULL;
1609         }
1610 }
1611
1612 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1613 {
1614         struct perf_env *env = &st->session->header.env;
1615         aggr_cpu_id_get_t get_id = aggr_mode__get_aggr_file(stat_config.aggr_mode);
1616         bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1617
1618         if (stat_config.aggr_mode == AGGR_THREAD) {
1619                 int nr = perf_thread_map__nr(evsel_list->core.threads);
1620
1621                 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1622                 if (stat_config.aggr_map == NULL)
1623                         return -ENOMEM;
1624
1625                 for (int s = 0; s < nr; s++) {
1626                         struct aggr_cpu_id id = aggr_cpu_id__empty();
1627
1628                         id.thread_idx = s;
1629                         stat_config.aggr_map->map[s] = id;
1630                 }
1631                 return 0;
1632         }
1633
1634         if (!get_id)
1635                 return 0;
1636
1637         stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1638                                                  get_id, env, needs_sort);
1639         if (!stat_config.aggr_map) {
1640                 pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
1641                 return -1;
1642         }
1643         stat_config.aggr_get_id = aggr_mode__get_id_file(stat_config.aggr_mode);
1644         return 0;
1645 }
1646
1647 /*
1648  * Add default attributes, if there were no attributes specified or
1649  * if -d/--detailed, -d -d or -d -d -d is used:
1650  */
1651 static int add_default_attributes(void)
1652 {
1653         struct perf_event_attr default_attrs0[] = {
1654
1655   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK              },
1656   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES        },
1657   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS          },
1658   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS             },
1659
1660   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES              },
1661 };
1662         struct perf_event_attr frontend_attrs[] = {
1663   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1664 };
1665         struct perf_event_attr backend_attrs[] = {
1666   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND  },
1667 };
1668         struct perf_event_attr default_attrs1[] = {
1669   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS            },
1670   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS     },
1671   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES           },
1672
1673 };
1674
1675 /*
1676  * Detailed stats (-d), covering the L1 and last level data caches:
1677  */
1678         struct perf_event_attr detailed_attrs[] = {
1679
1680   { .type = PERF_TYPE_HW_CACHE,
1681     .config =
1682          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1683         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1684         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1685
1686   { .type = PERF_TYPE_HW_CACHE,
1687     .config =
1688          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1689         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1690         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1691
1692   { .type = PERF_TYPE_HW_CACHE,
1693     .config =
1694          PERF_COUNT_HW_CACHE_LL                 <<  0  |
1695         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1696         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1697
1698   { .type = PERF_TYPE_HW_CACHE,
1699     .config =
1700          PERF_COUNT_HW_CACHE_LL                 <<  0  |
1701         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1702         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1703 };
1704
1705 /*
1706  * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1707  */
1708         struct perf_event_attr very_detailed_attrs[] = {
1709
1710   { .type = PERF_TYPE_HW_CACHE,
1711     .config =
1712          PERF_COUNT_HW_CACHE_L1I                <<  0  |
1713         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1714         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1715
1716   { .type = PERF_TYPE_HW_CACHE,
1717     .config =
1718          PERF_COUNT_HW_CACHE_L1I                <<  0  |
1719         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1720         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1721
1722   { .type = PERF_TYPE_HW_CACHE,
1723     .config =
1724          PERF_COUNT_HW_CACHE_DTLB               <<  0  |
1725         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1726         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1727
1728   { .type = PERF_TYPE_HW_CACHE,
1729     .config =
1730          PERF_COUNT_HW_CACHE_DTLB               <<  0  |
1731         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1732         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1733
1734   { .type = PERF_TYPE_HW_CACHE,
1735     .config =
1736          PERF_COUNT_HW_CACHE_ITLB               <<  0  |
1737         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1738         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1739
1740   { .type = PERF_TYPE_HW_CACHE,
1741     .config =
1742          PERF_COUNT_HW_CACHE_ITLB               <<  0  |
1743         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
1744         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1745
1746 };
1747
1748 /*
1749  * Very, very detailed stats (-d -d -d), adding prefetch events:
1750  */
1751         struct perf_event_attr very_very_detailed_attrs[] = {
1752
1753   { .type = PERF_TYPE_HW_CACHE,
1754     .config =
1755          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1756         (PERF_COUNT_HW_CACHE_OP_PREFETCH        <<  8) |
1757         (PERF_COUNT_HW_CACHE_RESULT_ACCESS      << 16)                          },
1758
1759   { .type = PERF_TYPE_HW_CACHE,
1760     .config =
1761          PERF_COUNT_HW_CACHE_L1D                <<  0  |
1762         (PERF_COUNT_HW_CACHE_OP_PREFETCH        <<  8) |
1763         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
1764 };
1765
1766         struct perf_event_attr default_null_attrs[] = {};
1767
1768         /* Set attrs if no event is selected and !null_run: */
1769         if (stat_config.null_run)
1770                 return 0;
1771
1772         if (transaction_run) {
1773                 /* Handle -T as -M transaction. Once platform specific metrics
1774                  * support has been added to the json files, all architectures
1775                  * will use this approach. To determine transaction support
1776                  * on an architecture test for such a metric name.
1777                  */
1778                 if (!metricgroup__has_metric("transaction")) {
1779                         pr_err("Missing transaction metrics");
1780                         return -1;
1781                 }
1782                 return metricgroup__parse_groups(evsel_list, "transaction",
1783                                                 stat_config.metric_no_group,
1784                                                 stat_config.metric_no_merge,
1785                                                 stat_config.metric_no_threshold,
1786                                                 stat_config.user_requested_cpu_list,
1787                                                 stat_config.system_wide,
1788                                                 &stat_config.metric_events);
1789         }
1790
1791         if (smi_cost) {
1792                 int smi;
1793
1794                 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
1795                         pr_err("freeze_on_smi is not supported.");
1796                         return -1;
1797                 }
1798
1799                 if (!smi) {
1800                         if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
1801                                 fprintf(stderr, "Failed to set freeze_on_smi.\n");
1802                                 return -1;
1803                         }
1804                         smi_reset = true;
1805                 }
1806
1807                 if (!metricgroup__has_metric("smi")) {
1808                         pr_err("Missing smi metrics");
1809                         return -1;
1810                 }
1811
1812                 if (!force_metric_only)
1813                         stat_config.metric_only = true;
1814
1815                 return metricgroup__parse_groups(evsel_list, "smi",
1816                                                 stat_config.metric_no_group,
1817                                                 stat_config.metric_no_merge,
1818                                                 stat_config.metric_no_threshold,
1819                                                 stat_config.user_requested_cpu_list,
1820                                                 stat_config.system_wide,
1821                                                 &stat_config.metric_events);
1822         }
1823
1824         if (topdown_run) {
1825                 unsigned int max_level = metricgroups__topdown_max_level();
1826                 char str[] = "TopdownL1";
1827
1828                 if (!force_metric_only)
1829                         stat_config.metric_only = true;
1830
1831                 if (!max_level) {
1832                         pr_err("Topdown requested but the topdown metric groups aren't present.\n"
1833                                 "(See perf list the metric groups have names like TopdownL1)");
1834                         return -1;
1835                 }
1836                 if (stat_config.topdown_level > max_level) {
1837                         pr_err("Invalid top-down metrics level. The max level is %u.\n", max_level);
1838                         return -1;
1839                 } else if (!stat_config.topdown_level)
1840                         stat_config.topdown_level = 1;
1841
1842                 if (!stat_config.interval && !stat_config.metric_only) {
1843                         fprintf(stat_config.output,
1844                                 "Topdown accuracy may decrease when measuring long periods.\n"
1845                                 "Please print the result regularly, e.g. -I1000\n");
1846                 }
1847                 str[8] = stat_config.topdown_level + '0';
1848                 if (metricgroup__parse_groups(evsel_list, str,
1849                                                 /*metric_no_group=*/false,
1850                                                 /*metric_no_merge=*/false,
1851                                                 /*metric_no_threshold=*/true,
1852                                                 stat_config.user_requested_cpu_list,
1853                                                 stat_config.system_wide,
1854                                                 &stat_config.metric_events) < 0)
1855                         return -1;
1856         }
1857
1858         if (!stat_config.topdown_level)
1859                 stat_config.topdown_level = 1;
1860
1861         if (!evsel_list->core.nr_entries) {
1862                 /* No events so add defaults. */
1863                 if (target__has_cpu(&target))
1864                         default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
1865
1866                 if (evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
1867                         return -1;
1868                 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
1869                         if (evlist__add_default_attrs(evsel_list, frontend_attrs) < 0)
1870                                 return -1;
1871                 }
1872                 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
1873                         if (evlist__add_default_attrs(evsel_list, backend_attrs) < 0)
1874                                 return -1;
1875                 }
1876                 if (evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
1877                         return -1;
1878                 /*
1879                  * Add TopdownL1 metrics if they exist. To minimize
1880                  * multiplexing, don't request threshold computation.
1881                  */
1882                 if (metricgroup__has_metric("TopdownL1") &&
1883                     metricgroup__parse_groups(evsel_list, "TopdownL1",
1884                                             /*metric_no_group=*/false,
1885                                             /*metric_no_merge=*/false,
1886                                             /*metric_no_threshold=*/true,
1887                                             stat_config.user_requested_cpu_list,
1888                                             stat_config.system_wide,
1889                                             &stat_config.metric_events) < 0)
1890                         return -1;
1891                 /* Platform specific attrs */
1892                 if (evlist__add_default_attrs(evsel_list, default_null_attrs) < 0)
1893                         return -1;
1894         }
1895
1896         /* Detailed events get appended to the event list: */
1897
1898         if (detailed_run <  1)
1899                 return 0;
1900
1901         /* Append detailed run extra attributes: */
1902         if (evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1903                 return -1;
1904
1905         if (detailed_run < 2)
1906                 return 0;
1907
1908         /* Append very detailed run extra attributes: */
1909         if (evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1910                 return -1;
1911
1912         if (detailed_run < 3)
1913                 return 0;
1914
1915         /* Append very, very detailed run extra attributes: */
1916         return evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1917 }
1918
1919 static const char * const stat_record_usage[] = {
1920         "perf stat record [<options>]",
1921         NULL,
1922 };
1923
1924 static void init_features(struct perf_session *session)
1925 {
1926         int feat;
1927
1928         for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
1929                 perf_header__set_feat(&session->header, feat);
1930
1931         perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
1932         perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
1933         perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
1934         perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
1935         perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
1936 }
1937
1938 static int __cmd_record(int argc, const char **argv)
1939 {
1940         struct perf_session *session;
1941         struct perf_data *data = &perf_stat.data;
1942
1943         argc = parse_options(argc, argv, stat_options, stat_record_usage,
1944                              PARSE_OPT_STOP_AT_NON_OPTION);
1945
1946         if (output_name)
1947                 data->path = output_name;
1948
1949         if (stat_config.run_count != 1 || forever) {
1950                 pr_err("Cannot use -r option with perf stat record.\n");
1951                 return -1;
1952         }
1953
1954         session = perf_session__new(data, NULL);
1955         if (IS_ERR(session)) {
1956                 pr_err("Perf session creation failed\n");
1957                 return PTR_ERR(session);
1958         }
1959
1960         init_features(session);
1961
1962         session->evlist   = evsel_list;
1963         perf_stat.session = session;
1964         perf_stat.record  = true;
1965         return argc;
1966 }
1967
1968 static int process_stat_round_event(struct perf_session *session,
1969                                     union perf_event *event)
1970 {
1971         struct perf_record_stat_round *stat_round = &event->stat_round;
1972         struct timespec tsh, *ts = NULL;
1973         const char **argv = session->header.env.cmdline_argv;
1974         int argc = session->header.env.nr_cmdline;
1975
1976         process_counters();
1977
1978         if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
1979                 update_stats(&walltime_nsecs_stats, stat_round->time);
1980
1981         if (stat_config.interval && stat_round->time) {
1982                 tsh.tv_sec  = stat_round->time / NSEC_PER_SEC;
1983                 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
1984                 ts = &tsh;
1985         }
1986
1987         print_counters(ts, argc, argv);
1988         return 0;
1989 }
1990
1991 static
1992 int process_stat_config_event(struct perf_session *session,
1993                               union perf_event *event)
1994 {
1995         struct perf_tool *tool = session->tool;
1996         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1997
1998         perf_event__read_stat_config(&stat_config, &event->stat_config);
1999
2000         if (perf_cpu_map__empty(st->cpus)) {
2001                 if (st->aggr_mode != AGGR_UNSET)
2002                         pr_warning("warning: processing task data, aggregation mode not set\n");
2003         } else if (st->aggr_mode != AGGR_UNSET) {
2004                 stat_config.aggr_mode = st->aggr_mode;
2005         }
2006
2007         if (perf_stat.data.is_pipe)
2008                 perf_stat_init_aggr_mode();
2009         else
2010                 perf_stat_init_aggr_mode_file(st);
2011
2012         if (stat_config.aggr_map) {
2013                 int nr_aggr = stat_config.aggr_map->nr;
2014
2015                 if (evlist__alloc_aggr_stats(session->evlist, nr_aggr) < 0) {
2016                         pr_err("cannot allocate aggr counts\n");
2017                         return -1;
2018                 }
2019         }
2020         return 0;
2021 }
2022
2023 static int set_maps(struct perf_stat *st)
2024 {
2025         if (!st->cpus || !st->threads)
2026                 return 0;
2027
2028         if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2029                 return -EINVAL;
2030
2031         perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
2032
2033         if (evlist__alloc_stats(&stat_config, evsel_list, /*alloc_raw=*/true))
2034                 return -ENOMEM;
2035
2036         st->maps_allocated = true;
2037         return 0;
2038 }
2039
2040 static
2041 int process_thread_map_event(struct perf_session *session,
2042                              union perf_event *event)
2043 {
2044         struct perf_tool *tool = session->tool;
2045         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2046
2047         if (st->threads) {
2048                 pr_warning("Extra thread map event, ignoring.\n");
2049                 return 0;
2050         }
2051
2052         st->threads = thread_map__new_event(&event->thread_map);
2053         if (!st->threads)
2054                 return -ENOMEM;
2055
2056         return set_maps(st);
2057 }
2058
2059 static
2060 int process_cpu_map_event(struct perf_session *session,
2061                           union perf_event *event)
2062 {
2063         struct perf_tool *tool = session->tool;
2064         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2065         struct perf_cpu_map *cpus;
2066
2067         if (st->cpus) {
2068                 pr_warning("Extra cpu map event, ignoring.\n");
2069                 return 0;
2070         }
2071
2072         cpus = cpu_map__new_data(&event->cpu_map.data);
2073         if (!cpus)
2074                 return -ENOMEM;
2075
2076         st->cpus = cpus;
2077         return set_maps(st);
2078 }
2079
2080 static const char * const stat_report_usage[] = {
2081         "perf stat report [<options>]",
2082         NULL,
2083 };
2084
2085 static struct perf_stat perf_stat = {
2086         .tool = {
2087                 .attr           = perf_event__process_attr,
2088                 .event_update   = perf_event__process_event_update,
2089                 .thread_map     = process_thread_map_event,
2090                 .cpu_map        = process_cpu_map_event,
2091                 .stat_config    = process_stat_config_event,
2092                 .stat           = perf_event__process_stat_event,
2093                 .stat_round     = process_stat_round_event,
2094         },
2095         .aggr_mode = AGGR_UNSET,
2096 };
2097
2098 static int __cmd_report(int argc, const char **argv)
2099 {
2100         struct perf_session *session;
2101         const struct option options[] = {
2102         OPT_STRING('i', "input", &input_name, "file", "input file name"),
2103         OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2104                      "aggregate counts per processor socket", AGGR_SOCKET),
2105         OPT_SET_UINT(0, "per-die", &perf_stat.aggr_mode,
2106                      "aggregate counts per processor die", AGGR_DIE),
2107         OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2108                      "aggregate counts per physical processor core", AGGR_CORE),
2109         OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
2110                      "aggregate counts per numa node", AGGR_NODE),
2111         OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2112                      "disable CPU count aggregation", AGGR_NONE),
2113         OPT_END()
2114         };
2115         struct stat st;
2116         int ret;
2117
2118         argc = parse_options(argc, argv, options, stat_report_usage, 0);
2119
2120         if (!input_name || !strlen(input_name)) {
2121                 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2122                         input_name = "-";
2123                 else
2124                         input_name = "perf.data";
2125         }
2126
2127         perf_stat.data.path = input_name;
2128         perf_stat.data.mode = PERF_DATA_MODE_READ;
2129
2130         session = perf_session__new(&perf_stat.data, &perf_stat.tool);
2131         if (IS_ERR(session))
2132                 return PTR_ERR(session);
2133
2134         perf_stat.session  = session;
2135         stat_config.output = stderr;
2136         evsel_list         = session->evlist;
2137
2138         ret = perf_session__process_events(session);
2139         if (ret)
2140                 return ret;
2141
2142         perf_session__delete(session);
2143         return 0;
2144 }
2145
2146 static void setup_system_wide(int forks)
2147 {
2148         /*
2149          * Make system wide (-a) the default target if
2150          * no target was specified and one of following
2151          * conditions is met:
2152          *
2153          *   - there's no workload specified
2154          *   - there is workload specified but all requested
2155          *     events are system wide events
2156          */
2157         if (!target__none(&target))
2158                 return;
2159
2160         if (!forks)
2161                 target.system_wide = true;
2162         else {
2163                 struct evsel *counter;
2164
2165                 evlist__for_each_entry(evsel_list, counter) {
2166                         if (!counter->core.requires_cpu &&
2167                             strcmp(counter->name, "duration_time")) {
2168                                 return;
2169                         }
2170                 }
2171
2172                 if (evsel_list->core.nr_entries)
2173                         target.system_wide = true;
2174         }
2175 }
2176
2177 int cmd_stat(int argc, const char **argv)
2178 {
2179         const char * const stat_usage[] = {
2180                 "perf stat [<options>] [<command>]",
2181                 NULL
2182         };
2183         int status = -EINVAL, run_idx, err;
2184         const char *mode;
2185         FILE *output = stderr;
2186         unsigned int interval, timeout;
2187         const char * const stat_subcommands[] = { "record", "report" };
2188         char errbuf[BUFSIZ];
2189
2190         setlocale(LC_ALL, "");
2191
2192         evsel_list = evlist__new();
2193         if (evsel_list == NULL)
2194                 return -ENOMEM;
2195
2196         parse_events__shrink_config_terms();
2197
2198         /* String-parsing callback-based options would segfault when negated */
2199         set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
2200         set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
2201         set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
2202
2203         argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2204                                         (const char **) stat_usage,
2205                                         PARSE_OPT_STOP_AT_NON_OPTION);
2206
2207         if (stat_config.csv_sep) {
2208                 stat_config.csv_output = true;
2209                 if (!strcmp(stat_config.csv_sep, "\\t"))
2210                         stat_config.csv_sep = "\t";
2211         } else
2212                 stat_config.csv_sep = DEFAULT_SEPARATOR;
2213
2214         if (argc && strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
2215                 argc = __cmd_record(argc, argv);
2216                 if (argc < 0)
2217                         return -1;
2218         } else if (argc && strlen(argv[0]) > 2 && strstarts("report", argv[0]))
2219                 return __cmd_report(argc, argv);
2220
2221         interval = stat_config.interval;
2222         timeout = stat_config.timeout;
2223
2224         /*
2225          * For record command the -o is already taken care of.
2226          */
2227         if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2228                 output = NULL;
2229
2230         if (output_name && output_fd) {
2231                 fprintf(stderr, "cannot use both --output and --log-fd\n");
2232                 parse_options_usage(stat_usage, stat_options, "o", 1);
2233                 parse_options_usage(NULL, stat_options, "log-fd", 0);
2234                 goto out;
2235         }
2236
2237         if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2238                 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2239                 goto out;
2240         }
2241
2242         if (stat_config.metric_only && stat_config.run_count > 1) {
2243                 fprintf(stderr, "--metric-only is not supported with -r\n");
2244                 goto out;
2245         }
2246
2247         if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
2248                 fprintf(stderr, "--table is only supported with -r\n");
2249                 parse_options_usage(stat_usage, stat_options, "r", 1);
2250                 parse_options_usage(NULL, stat_options, "table", 0);
2251                 goto out;
2252         }
2253
2254         if (output_fd < 0) {
2255                 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2256                 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2257                 goto out;
2258         }
2259
2260         if (!output && !quiet) {
2261                 struct timespec tm;
2262                 mode = append_file ? "a" : "w";
2263
2264                 output = fopen(output_name, mode);
2265                 if (!output) {
2266                         perror("failed to create output file");
2267                         return -1;
2268                 }
2269                 clock_gettime(CLOCK_REALTIME, &tm);
2270                 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2271         } else if (output_fd > 0) {
2272                 mode = append_file ? "a" : "w";
2273                 output = fdopen(output_fd, mode);
2274                 if (!output) {
2275                         perror("Failed opening logfd");
2276                         return -errno;
2277                 }
2278         }
2279
2280         if (stat_config.interval_clear && !isatty(fileno(output))) {
2281                 fprintf(stderr, "--interval-clear does not work with output\n");
2282                 parse_options_usage(stat_usage, stat_options, "o", 1);
2283                 parse_options_usage(NULL, stat_options, "log-fd", 0);
2284                 parse_options_usage(NULL, stat_options, "interval-clear", 0);
2285                 return -1;
2286         }
2287
2288         stat_config.output = output;
2289
2290         /*
2291          * let the spreadsheet do the pretty-printing
2292          */
2293         if (stat_config.csv_output) {
2294                 /* User explicitly passed -B? */
2295                 if (big_num_opt == 1) {
2296                         fprintf(stderr, "-B option not supported with -x\n");
2297                         parse_options_usage(stat_usage, stat_options, "B", 1);
2298                         parse_options_usage(NULL, stat_options, "x", 1);
2299                         goto out;
2300                 } else /* Nope, so disable big number formatting */
2301                         stat_config.big_num = false;
2302         } else if (big_num_opt == 0) /* User passed --no-big-num */
2303                 stat_config.big_num = false;
2304
2305         err = target__validate(&target);
2306         if (err) {
2307                 target__strerror(&target, err, errbuf, BUFSIZ);
2308                 pr_warning("%s\n", errbuf);
2309         }
2310
2311         setup_system_wide(argc);
2312
2313         /*
2314          * Display user/system times only for single
2315          * run and when there's specified tracee.
2316          */
2317         if ((stat_config.run_count == 1) && target__none(&target))
2318                 stat_config.ru_display = true;
2319
2320         if (stat_config.run_count < 0) {
2321                 pr_err("Run count must be a positive number\n");
2322                 parse_options_usage(stat_usage, stat_options, "r", 1);
2323                 goto out;
2324         } else if (stat_config.run_count == 0) {
2325                 forever = true;
2326                 stat_config.run_count = 1;
2327         }
2328
2329         if (stat_config.walltime_run_table) {
2330                 stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
2331                 if (!stat_config.walltime_run) {
2332                         pr_err("failed to setup -r option");
2333                         goto out;
2334                 }
2335         }
2336
2337         if ((stat_config.aggr_mode == AGGR_THREAD) &&
2338                 !target__has_task(&target)) {
2339                 if (!target.system_wide || target.cpu_list) {
2340                         fprintf(stderr, "The --per-thread option is only "
2341                                 "available when monitoring via -p -t -a "
2342                                 "options or only --per-thread.\n");
2343                         parse_options_usage(NULL, stat_options, "p", 1);
2344                         parse_options_usage(NULL, stat_options, "t", 1);
2345                         goto out;
2346                 }
2347         }
2348
2349         /*
2350          * no_aggr, cgroup are for system-wide only
2351          * --per-thread is aggregated per thread, we dont mix it with cpu mode
2352          */
2353         if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2354               stat_config.aggr_mode != AGGR_THREAD) ||
2355              (nr_cgroups || stat_config.cgroup_list)) &&
2356             !target__has_cpu(&target)) {
2357                 fprintf(stderr, "both cgroup and no-aggregation "
2358                         "modes only available in system-wide mode\n");
2359
2360                 parse_options_usage(stat_usage, stat_options, "G", 1);
2361                 parse_options_usage(NULL, stat_options, "A", 1);
2362                 parse_options_usage(NULL, stat_options, "a", 1);
2363                 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2364                 goto out;
2365         }
2366
2367         if (stat_config.iostat_run) {
2368                 status = iostat_prepare(evsel_list, &stat_config);
2369                 if (status)
2370                         goto out;
2371                 if (iostat_mode == IOSTAT_LIST) {
2372                         iostat_list(evsel_list, &stat_config);
2373                         goto out;
2374                 } else if (verbose > 0)
2375                         iostat_list(evsel_list, &stat_config);
2376                 if (iostat_mode == IOSTAT_RUN && !target__has_cpu(&target))
2377                         target.system_wide = true;
2378         }
2379
2380         if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2381                 target.per_thread = true;
2382
2383         stat_config.system_wide = target.system_wide;
2384         if (target.cpu_list) {
2385                 stat_config.user_requested_cpu_list = strdup(target.cpu_list);
2386                 if (!stat_config.user_requested_cpu_list) {
2387                         status = -ENOMEM;
2388                         goto out;
2389                 }
2390         }
2391
2392         /*
2393          * Metric parsing needs to be delayed as metrics may optimize events
2394          * knowing the target is system-wide.
2395          */
2396         if (metrics) {
2397                 metricgroup__parse_groups(evsel_list, metrics,
2398                                         stat_config.metric_no_group,
2399                                         stat_config.metric_no_merge,
2400                                         stat_config.metric_no_threshold,
2401                                         stat_config.user_requested_cpu_list,
2402                                         stat_config.system_wide,
2403                                         &stat_config.metric_events);
2404                 zfree(&metrics);
2405         }
2406
2407         if (add_default_attributes())
2408                 goto out;
2409
2410         if (stat_config.cgroup_list) {
2411                 if (nr_cgroups > 0) {
2412                         pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
2413                         parse_options_usage(stat_usage, stat_options, "G", 1);
2414                         parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2415                         goto out;
2416                 }
2417
2418                 if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list,
2419                                           &stat_config.metric_events, true) < 0) {
2420                         parse_options_usage(stat_usage, stat_options,
2421                                             "for-each-cgroup", 0);
2422                         goto out;
2423                 }
2424         }
2425
2426         if (evlist__fix_hybrid_cpus(evsel_list, target.cpu_list)) {
2427                 pr_err("failed to use cpu list %s\n", target.cpu_list);
2428                 goto out;
2429         }
2430
2431         target.hybrid = perf_pmu__has_hybrid();
2432         if (evlist__create_maps(evsel_list, &target) < 0) {
2433                 if (target__has_task(&target)) {
2434                         pr_err("Problems finding threads of monitor\n");
2435                         parse_options_usage(stat_usage, stat_options, "p", 1);
2436                         parse_options_usage(NULL, stat_options, "t", 1);
2437                 } else if (target__has_cpu(&target)) {
2438                         perror("failed to parse CPUs map");
2439                         parse_options_usage(stat_usage, stat_options, "C", 1);
2440                         parse_options_usage(NULL, stat_options, "a", 1);
2441                 }
2442                 goto out;
2443         }
2444
2445         evlist__check_cpu_maps(evsel_list);
2446
2447         /*
2448          * Initialize thread_map with comm names,
2449          * so we could print it out on output.
2450          */
2451         if (stat_config.aggr_mode == AGGR_THREAD) {
2452                 thread_map__read_comms(evsel_list->core.threads);
2453         }
2454
2455         if (stat_config.aggr_mode == AGGR_NODE)
2456                 cpu__setup_cpunode_map();
2457
2458         if (stat_config.times && interval)
2459                 interval_count = true;
2460         else if (stat_config.times && !interval) {
2461                 pr_err("interval-count option should be used together with "
2462                                 "interval-print.\n");
2463                 parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2464                 parse_options_usage(stat_usage, stat_options, "I", 1);
2465                 goto out;
2466         }
2467
2468         if (timeout && timeout < 100) {
2469                 if (timeout < 10) {
2470                         pr_err("timeout must be >= 10ms.\n");
2471                         parse_options_usage(stat_usage, stat_options, "timeout", 0);
2472                         goto out;
2473                 } else
2474                         pr_warning("timeout < 100ms. "
2475                                    "The overhead percentage could be high in some cases. "
2476                                    "Please proceed with caution.\n");
2477         }
2478         if (timeout && interval) {
2479                 pr_err("timeout option is not supported with interval-print.\n");
2480                 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2481                 parse_options_usage(stat_usage, stat_options, "I", 1);
2482                 goto out;
2483         }
2484
2485         if (perf_stat_init_aggr_mode())
2486                 goto out;
2487
2488         if (evlist__alloc_stats(&stat_config, evsel_list, interval))
2489                 goto out;
2490
2491         /*
2492          * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2493          * while avoiding that older tools show confusing messages.
2494          *
2495          * However for pipe sessions we need to keep it zero,
2496          * because script's perf_evsel__check_attr is triggered
2497          * by attr->sample_type != 0, and we can't run it on
2498          * stat sessions.
2499          */
2500         stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2501
2502         /*
2503          * We dont want to block the signals - that would cause
2504          * child tasks to inherit that and Ctrl-C would not work.
2505          * What we want is for Ctrl-C to work in the exec()-ed
2506          * task, but being ignored by perf stat itself:
2507          */
2508         atexit(sig_atexit);
2509         if (!forever)
2510                 signal(SIGINT,  skip_signal);
2511         signal(SIGCHLD, skip_signal);
2512         signal(SIGALRM, skip_signal);
2513         signal(SIGABRT, skip_signal);
2514
2515         if (evlist__initialize_ctlfd(evsel_list, stat_config.ctl_fd, stat_config.ctl_fd_ack))
2516                 goto out;
2517
2518         /* Enable ignoring missing threads when -p option is defined. */
2519         evlist__first(evsel_list)->ignore_missing_thread = target.pid;
2520         status = 0;
2521         for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
2522                 if (stat_config.run_count != 1 && verbose > 0)
2523                         fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2524                                 run_idx + 1);
2525
2526                 if (run_idx != 0)
2527                         evlist__reset_prev_raw_counts(evsel_list);
2528
2529                 status = run_perf_stat(argc, argv, run_idx);
2530                 if (forever && status != -1 && !interval) {
2531                         print_counters(NULL, argc, argv);
2532                         perf_stat__reset_stats();
2533                 }
2534         }
2535
2536         if (!forever && status != -1 && (!interval || stat_config.summary))
2537                 print_counters(NULL, argc, argv);
2538
2539         evlist__finalize_ctlfd(evsel_list);
2540
2541         if (STAT_RECORD) {
2542                 /*
2543                  * We synthesize the kernel mmap record just so that older tools
2544                  * don't emit warnings about not being able to resolve symbols
2545                  * due to /proc/sys/kernel/kptr_restrict settings and instead provide
2546                  * a saner message about no samples being in the perf.data file.
2547                  *
2548                  * This also serves to suppress a warning about f_header.data.size == 0
2549                  * in header.c at the moment 'perf stat record' gets introduced, which
2550                  * is not really needed once we start adding the stat specific PERF_RECORD_
2551                  * records, but the need to suppress the kptr_restrict messages in older
2552                  * tools remain  -acme
2553                  */
2554                 int fd = perf_data__fd(&perf_stat.data);
2555
2556                 err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2557                                                          process_synthesized_event,
2558                                                          &perf_stat.session->machines.host);
2559                 if (err) {
2560                         pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2561                                    "older tools may produce warnings about this file\n.");
2562                 }
2563
2564                 if (!interval) {
2565                         if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2566                                 pr_err("failed to write stat round event\n");
2567                 }
2568
2569                 if (!perf_stat.data.is_pipe) {
2570                         perf_stat.session->header.data_size += perf_stat.bytes_written;
2571                         perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2572                 }
2573
2574                 evlist__close(evsel_list);
2575                 perf_session__delete(perf_stat.session);
2576         }
2577
2578         perf_stat__exit_aggr_mode();
2579         evlist__free_stats(evsel_list);
2580 out:
2581         if (stat_config.iostat_run)
2582                 iostat_release(evsel_list);
2583
2584         zfree(&stat_config.walltime_run);
2585         zfree(&stat_config.user_requested_cpu_list);
2586
2587         if (smi_cost && smi_reset)
2588                 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2589
2590         evlist__delete(evsel_list);
2591
2592         metricgroup__rblist_exit(&stat_config.metric_events);
2593         evlist__close_control(stat_config.ctl_fd, stat_config.ctl_fd_ack, &stat_config.ctl_fd_close);
2594
2595         return status;
2596 }