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