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