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