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