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