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