]> git.karo-electronics.de Git - karo-tx-linux.git/blob - tools/perf/builtin-stat.c
perf tools: Remove unused 'prefix' from builtin functions
[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         vals = buf;
879         while (isspace(*vals))
880                 vals++;
881         ends = vals;
882         while (isdigit(*ends) || *ends == '.')
883                 ends++;
884         *ends = 0;
885         while (isspace(*unit))
886                 unit++;
887         fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
888 }
889
890 #define METRIC_ONLY_LEN 20
891
892 /* Filter out some columns that don't work well in metrics only mode */
893
894 static bool valid_only_metric(const char *unit)
895 {
896         if (!unit)
897                 return false;
898         if (strstr(unit, "/sec") ||
899             strstr(unit, "hz") ||
900             strstr(unit, "Hz") ||
901             strstr(unit, "CPUs utilized"))
902                 return false;
903         return true;
904 }
905
906 static const char *fixunit(char *buf, struct perf_evsel *evsel,
907                            const char *unit)
908 {
909         if (!strncmp(unit, "of all", 6)) {
910                 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
911                          unit);
912                 return buf;
913         }
914         return unit;
915 }
916
917 static void print_metric_only(void *ctx, const char *color, const char *fmt,
918                               const char *unit, double val)
919 {
920         struct outstate *os = ctx;
921         FILE *out = os->fh;
922         int n;
923         char buf[1024];
924         unsigned mlen = METRIC_ONLY_LEN;
925
926         if (!valid_only_metric(unit))
927                 return;
928         unit = fixunit(buf, os->evsel, unit);
929         if (color)
930                 n = color_fprintf(out, color, fmt, val);
931         else
932                 n = fprintf(out, fmt, val);
933         if (n > METRIC_ONLY_LEN)
934                 n = METRIC_ONLY_LEN;
935         if (mlen < strlen(unit))
936                 mlen = strlen(unit) + 1;
937         fprintf(out, "%*s", mlen - n, "");
938 }
939
940 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
941                                   const char *fmt,
942                                   const char *unit, double val)
943 {
944         struct outstate *os = ctx;
945         FILE *out = os->fh;
946         char buf[64], *vals, *ends;
947         char tbuf[1024];
948
949         if (!valid_only_metric(unit))
950                 return;
951         unit = fixunit(tbuf, os->evsel, unit);
952         snprintf(buf, sizeof buf, fmt, val);
953         vals = buf;
954         while (isspace(*vals))
955                 vals++;
956         ends = vals;
957         while (isdigit(*ends) || *ends == '.')
958                 ends++;
959         *ends = 0;
960         fprintf(out, "%s%s", vals, csv_sep);
961 }
962
963 static void new_line_metric(void *ctx __maybe_unused)
964 {
965 }
966
967 static void print_metric_header(void *ctx, const char *color __maybe_unused,
968                                 const char *fmt __maybe_unused,
969                                 const char *unit, double val __maybe_unused)
970 {
971         struct outstate *os = ctx;
972         char tbuf[1024];
973
974         if (!valid_only_metric(unit))
975                 return;
976         unit = fixunit(tbuf, os->evsel, unit);
977         if (csv_output)
978                 fprintf(os->fh, "%s%s", unit, csv_sep);
979         else
980                 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
981 }
982
983 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
984 {
985         FILE *output = stat_config.output;
986         double msecs = avg / NSEC_PER_MSEC;
987         const char *fmt_v, *fmt_n;
988         char name[25];
989
990         fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
991         fmt_n = csv_output ? "%s" : "%-25s";
992
993         aggr_printout(evsel, id, nr);
994
995         scnprintf(name, sizeof(name), "%s%s",
996                   perf_evsel__name(evsel), csv_output ? "" : " (msec)");
997
998         fprintf(output, fmt_v, msecs, csv_sep);
999
1000         if (csv_output)
1001                 fprintf(output, "%s%s", evsel->unit, csv_sep);
1002         else
1003                 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
1004
1005         fprintf(output, fmt_n, name);
1006
1007         if (evsel->cgrp)
1008                 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1009 }
1010
1011 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
1012 {
1013         int i;
1014
1015         if (!aggr_get_id)
1016                 return 0;
1017
1018         if (stat_config.aggr_mode == AGGR_NONE)
1019                 return id;
1020
1021         if (stat_config.aggr_mode == AGGR_GLOBAL)
1022                 return 0;
1023
1024         for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
1025                 int cpu2 = perf_evsel__cpus(evsel)->map[i];
1026
1027                 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
1028                         return cpu2;
1029         }
1030         return 0;
1031 }
1032
1033 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1034 {
1035         FILE *output = stat_config.output;
1036         double sc =  evsel->scale;
1037         const char *fmt;
1038
1039         if (csv_output) {
1040                 fmt = floor(sc) != sc ?  "%.2f%s" : "%.0f%s";
1041         } else {
1042                 if (big_num)
1043                         fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
1044                 else
1045                         fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
1046         }
1047
1048         aggr_printout(evsel, id, nr);
1049
1050         fprintf(output, fmt, avg, csv_sep);
1051
1052         if (evsel->unit)
1053                 fprintf(output, "%-*s%s",
1054                         csv_output ? 0 : unit_width,
1055                         evsel->unit, csv_sep);
1056
1057         fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1058
1059         if (evsel->cgrp)
1060                 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1061 }
1062
1063 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
1064                      char *prefix, u64 run, u64 ena, double noise)
1065 {
1066         struct perf_stat_output_ctx out;
1067         struct outstate os = {
1068                 .fh = stat_config.output,
1069                 .prefix = prefix ? prefix : "",
1070                 .id = id,
1071                 .nr = nr,
1072                 .evsel = counter,
1073         };
1074         print_metric_t pm = print_metric_std;
1075         void (*nl)(void *);
1076
1077         if (metric_only) {
1078                 nl = new_line_metric;
1079                 if (csv_output)
1080                         pm = print_metric_only_csv;
1081                 else
1082                         pm = print_metric_only;
1083         } else
1084                 nl = new_line_std;
1085
1086         if (csv_output && !metric_only) {
1087                 static int aggr_fields[] = {
1088                         [AGGR_GLOBAL] = 0,
1089                         [AGGR_THREAD] = 1,
1090                         [AGGR_NONE] = 1,
1091                         [AGGR_SOCKET] = 2,
1092                         [AGGR_CORE] = 2,
1093                 };
1094
1095                 pm = print_metric_csv;
1096                 nl = new_line_csv;
1097                 os.nfields = 3;
1098                 os.nfields += aggr_fields[stat_config.aggr_mode];
1099                 if (counter->cgrp)
1100                         os.nfields++;
1101         }
1102         if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1103                 if (metric_only) {
1104                         pm(&os, NULL, "", "", 0);
1105                         return;
1106                 }
1107                 aggr_printout(counter, id, nr);
1108
1109                 fprintf(stat_config.output, "%*s%s",
1110                         csv_output ? 0 : 18,
1111                         counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1112                         csv_sep);
1113
1114                 if (counter->supported)
1115                         print_free_counters_hint = 1;
1116
1117                 fprintf(stat_config.output, "%-*s%s",
1118                         csv_output ? 0 : unit_width,
1119                         counter->unit, csv_sep);
1120
1121                 fprintf(stat_config.output, "%*s",
1122                         csv_output ? 0 : -25,
1123                         perf_evsel__name(counter));
1124
1125                 if (counter->cgrp)
1126                         fprintf(stat_config.output, "%s%s",
1127                                 csv_sep, counter->cgrp->name);
1128
1129                 if (!csv_output)
1130                         pm(&os, NULL, NULL, "", 0);
1131                 print_noise(counter, noise);
1132                 print_running(run, ena);
1133                 if (csv_output)
1134                         pm(&os, NULL, NULL, "", 0);
1135                 return;
1136         }
1137
1138         if (metric_only)
1139                 /* nothing */;
1140         else if (nsec_counter(counter))
1141                 nsec_printout(id, nr, counter, uval);
1142         else
1143                 abs_printout(id, nr, counter, uval);
1144
1145         out.print_metric = pm;
1146         out.new_line = nl;
1147         out.ctx = &os;
1148         out.force_header = false;
1149
1150         if (csv_output && !metric_only) {
1151                 print_noise(counter, noise);
1152                 print_running(run, ena);
1153         }
1154
1155         perf_stat__print_shadow_stats(counter, uval,
1156                                 first_shadow_cpu(counter, id),
1157                                 &out);
1158         if (!csv_output && !metric_only) {
1159                 print_noise(counter, noise);
1160                 print_running(run, ena);
1161         }
1162 }
1163
1164 static void aggr_update_shadow(void)
1165 {
1166         int cpu, s2, id, s;
1167         u64 val;
1168         struct perf_evsel *counter;
1169
1170         for (s = 0; s < aggr_map->nr; s++) {
1171                 id = aggr_map->map[s];
1172                 evlist__for_each_entry(evsel_list, counter) {
1173                         val = 0;
1174                         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1175                                 s2 = aggr_get_id(evsel_list->cpus, cpu);
1176                                 if (s2 != id)
1177                                         continue;
1178                                 val += perf_counts(counter->counts, cpu, 0)->val;
1179                         }
1180                         val = val * counter->scale;
1181                         perf_stat__update_shadow_stats(counter, &val,
1182                                                        first_shadow_cpu(counter, id));
1183                 }
1184         }
1185 }
1186
1187 static void collect_all_aliases(struct perf_evsel *counter,
1188                             void (*cb)(struct perf_evsel *counter, void *data,
1189                                        bool first),
1190                             void *data)
1191 {
1192         struct perf_evsel *alias;
1193
1194         alias = list_prepare_entry(counter, &(evsel_list->entries), node);
1195         list_for_each_entry_continue (alias, &evsel_list->entries, node) {
1196                 if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
1197                     alias->scale != counter->scale ||
1198                     alias->cgrp != counter->cgrp ||
1199                     strcmp(alias->unit, counter->unit) ||
1200                     nsec_counter(alias) != nsec_counter(counter))
1201                         break;
1202                 alias->merged_stat = true;
1203                 cb(alias, data, false);
1204         }
1205 }
1206
1207 static bool collect_data(struct perf_evsel *counter,
1208                             void (*cb)(struct perf_evsel *counter, void *data,
1209                                        bool first),
1210                             void *data)
1211 {
1212         if (counter->merged_stat)
1213                 return false;
1214         cb(counter, data, true);
1215         if (!no_merge)
1216                 collect_all_aliases(counter, cb, data);
1217         return true;
1218 }
1219
1220 struct aggr_data {
1221         u64 ena, run, val;
1222         int id;
1223         int nr;
1224         int cpu;
1225 };
1226
1227 static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
1228 {
1229         struct aggr_data *ad = data;
1230         int cpu, s2;
1231
1232         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1233                 struct perf_counts_values *counts;
1234
1235                 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1236                 if (s2 != ad->id)
1237                         continue;
1238                 if (first)
1239                         ad->nr++;
1240                 counts = perf_counts(counter->counts, cpu, 0);
1241                 /*
1242                  * When any result is bad, make them all to give
1243                  * consistent output in interval mode.
1244                  */
1245                 if (counts->ena == 0 || counts->run == 0 ||
1246                     counter->counts->scaled == -1) {
1247                         ad->ena = 0;
1248                         ad->run = 0;
1249                         break;
1250                 }
1251                 ad->val += counts->val;
1252                 ad->ena += counts->ena;
1253                 ad->run += counts->run;
1254         }
1255 }
1256
1257 static void print_aggr(char *prefix)
1258 {
1259         FILE *output = stat_config.output;
1260         struct perf_evsel *counter;
1261         int s, id, nr;
1262         double uval;
1263         u64 ena, run, val;
1264         bool first;
1265
1266         if (!(aggr_map || aggr_get_id))
1267                 return;
1268
1269         aggr_update_shadow();
1270
1271         /*
1272          * With metric_only everything is on a single line.
1273          * Without each counter has its own line.
1274          */
1275         for (s = 0; s < aggr_map->nr; s++) {
1276                 struct aggr_data ad;
1277                 if (prefix && metric_only)
1278                         fprintf(output, "%s", prefix);
1279
1280                 ad.id = id = aggr_map->map[s];
1281                 first = true;
1282                 evlist__for_each_entry(evsel_list, counter) {
1283                         ad.val = ad.ena = ad.run = 0;
1284                         ad.nr = 0;
1285                         if (!collect_data(counter, aggr_cb, &ad))
1286                                 continue;
1287                         nr = ad.nr;
1288                         ena = ad.ena;
1289                         run = ad.run;
1290                         val = ad.val;
1291                         if (first && metric_only) {
1292                                 first = false;
1293                                 aggr_printout(counter, id, nr);
1294                         }
1295                         if (prefix && !metric_only)
1296                                 fprintf(output, "%s", prefix);
1297
1298                         uval = val * counter->scale;
1299                         printout(id, nr, counter, uval, prefix, run, ena, 1.0);
1300                         if (!metric_only)
1301                                 fputc('\n', output);
1302                 }
1303                 if (metric_only)
1304                         fputc('\n', output);
1305         }
1306 }
1307
1308 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1309 {
1310         FILE *output = stat_config.output;
1311         int nthreads = thread_map__nr(counter->threads);
1312         int ncpus = cpu_map__nr(counter->cpus);
1313         int cpu, thread;
1314         double uval;
1315
1316         for (thread = 0; thread < nthreads; thread++) {
1317                 u64 ena = 0, run = 0, val = 0;
1318
1319                 for (cpu = 0; cpu < ncpus; cpu++) {
1320                         val += perf_counts(counter->counts, cpu, thread)->val;
1321                         ena += perf_counts(counter->counts, cpu, thread)->ena;
1322                         run += perf_counts(counter->counts, cpu, thread)->run;
1323                 }
1324
1325                 if (prefix)
1326                         fprintf(output, "%s", prefix);
1327
1328                 uval = val * counter->scale;
1329                 printout(thread, 0, counter, uval, prefix, run, ena, 1.0);
1330                 fputc('\n', output);
1331         }
1332 }
1333
1334 struct caggr_data {
1335         double avg, avg_enabled, avg_running;
1336 };
1337
1338 static void counter_aggr_cb(struct perf_evsel *counter, void *data,
1339                             bool first __maybe_unused)
1340 {
1341         struct caggr_data *cd = data;
1342         struct perf_stat_evsel *ps = counter->priv;
1343
1344         cd->avg += avg_stats(&ps->res_stats[0]);
1345         cd->avg_enabled += avg_stats(&ps->res_stats[1]);
1346         cd->avg_running += avg_stats(&ps->res_stats[2]);
1347 }
1348
1349 /*
1350  * Print out the results of a single counter:
1351  * aggregated counts in system-wide mode
1352  */
1353 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1354 {
1355         FILE *output = stat_config.output;
1356         double uval;
1357         struct caggr_data cd = { .avg = 0.0 };
1358
1359         if (!collect_data(counter, counter_aggr_cb, &cd))
1360                 return;
1361
1362         if (prefix && !metric_only)
1363                 fprintf(output, "%s", prefix);
1364
1365         uval = cd.avg * counter->scale;
1366         printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled, cd.avg);
1367         if (!metric_only)
1368                 fprintf(output, "\n");
1369 }
1370
1371 static void counter_cb(struct perf_evsel *counter, void *data,
1372                        bool first __maybe_unused)
1373 {
1374         struct aggr_data *ad = data;
1375
1376         ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
1377         ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
1378         ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
1379 }
1380
1381 /*
1382  * Print out the results of a single counter:
1383  * does not use aggregated count in system-wide
1384  */
1385 static void print_counter(struct perf_evsel *counter, char *prefix)
1386 {
1387         FILE *output = stat_config.output;
1388         u64 ena, run, val;
1389         double uval;
1390         int cpu;
1391
1392         for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1393                 struct aggr_data ad = { .cpu = cpu };
1394
1395                 if (!collect_data(counter, counter_cb, &ad))
1396                         return;
1397                 val = ad.val;
1398                 ena = ad.ena;
1399                 run = ad.run;
1400
1401                 if (prefix)
1402                         fprintf(output, "%s", prefix);
1403
1404                 uval = val * counter->scale;
1405                 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1406
1407                 fputc('\n', output);
1408         }
1409 }
1410
1411 static void print_no_aggr_metric(char *prefix)
1412 {
1413         int cpu;
1414         int nrcpus = 0;
1415         struct perf_evsel *counter;
1416         u64 ena, run, val;
1417         double uval;
1418
1419         nrcpus = evsel_list->cpus->nr;
1420         for (cpu = 0; cpu < nrcpus; cpu++) {
1421                 bool first = true;
1422
1423                 if (prefix)
1424                         fputs(prefix, stat_config.output);
1425                 evlist__for_each_entry(evsel_list, counter) {
1426                         if (first) {
1427                                 aggr_printout(counter, cpu, 0);
1428                                 first = false;
1429                         }
1430                         val = perf_counts(counter->counts, cpu, 0)->val;
1431                         ena = perf_counts(counter->counts, cpu, 0)->ena;
1432                         run = perf_counts(counter->counts, cpu, 0)->run;
1433
1434                         uval = val * counter->scale;
1435                         printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1436                 }
1437                 fputc('\n', stat_config.output);
1438         }
1439 }
1440
1441 static int aggr_header_lens[] = {
1442         [AGGR_CORE] = 18,
1443         [AGGR_SOCKET] = 12,
1444         [AGGR_NONE] = 6,
1445         [AGGR_THREAD] = 24,
1446         [AGGR_GLOBAL] = 0,
1447 };
1448
1449 static const char *aggr_header_csv[] = {
1450         [AGGR_CORE]     =       "core,cpus,",
1451         [AGGR_SOCKET]   =       "socket,cpus",
1452         [AGGR_NONE]     =       "cpu,",
1453         [AGGR_THREAD]   =       "comm-pid,",
1454         [AGGR_GLOBAL]   =       ""
1455 };
1456
1457 static void print_metric_headers(const char *prefix, bool no_indent)
1458 {
1459         struct perf_stat_output_ctx out;
1460         struct perf_evsel *counter;
1461         struct outstate os = {
1462                 .fh = stat_config.output
1463         };
1464
1465         if (prefix)
1466                 fprintf(stat_config.output, "%s", prefix);
1467
1468         if (!csv_output && !no_indent)
1469                 fprintf(stat_config.output, "%*s",
1470                         aggr_header_lens[stat_config.aggr_mode], "");
1471         if (csv_output) {
1472                 if (stat_config.interval)
1473                         fputs("time,", stat_config.output);
1474                 fputs(aggr_header_csv[stat_config.aggr_mode],
1475                         stat_config.output);
1476         }
1477
1478         /* Print metrics headers only */
1479         evlist__for_each_entry(evsel_list, counter) {
1480                 os.evsel = counter;
1481                 out.ctx = &os;
1482                 out.print_metric = print_metric_header;
1483                 out.new_line = new_line_metric;
1484                 out.force_header = true;
1485                 os.evsel = counter;
1486                 perf_stat__print_shadow_stats(counter, 0,
1487                                               0,
1488                                               &out);
1489         }
1490         fputc('\n', stat_config.output);
1491 }
1492
1493 static void print_interval(char *prefix, struct timespec *ts)
1494 {
1495         FILE *output = stat_config.output;
1496         static int num_print_interval;
1497
1498         sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1499
1500         if (num_print_interval == 0 && !csv_output) {
1501                 switch (stat_config.aggr_mode) {
1502                 case AGGR_SOCKET:
1503                         fprintf(output, "#           time socket cpus");
1504                         if (!metric_only)
1505                                 fprintf(output, "             counts %*s events\n", unit_width, "unit");
1506                         break;
1507                 case AGGR_CORE:
1508                         fprintf(output, "#           time core         cpus");
1509                         if (!metric_only)
1510                                 fprintf(output, "             counts %*s events\n", unit_width, "unit");
1511                         break;
1512                 case AGGR_NONE:
1513                         fprintf(output, "#           time CPU");
1514                         if (!metric_only)
1515                                 fprintf(output, "                counts %*s events\n", unit_width, "unit");
1516                         break;
1517                 case AGGR_THREAD:
1518                         fprintf(output, "#           time             comm-pid");
1519                         if (!metric_only)
1520                                 fprintf(output, "                  counts %*s events\n", unit_width, "unit");
1521                         break;
1522                 case AGGR_GLOBAL:
1523                 default:
1524                         fprintf(output, "#           time");
1525                         if (!metric_only)
1526                                 fprintf(output, "             counts %*s events\n", unit_width, "unit");
1527                 case AGGR_UNSET:
1528                         break;
1529                 }
1530         }
1531
1532         if (num_print_interval == 0 && metric_only)
1533                 print_metric_headers(" ", true);
1534         if (++num_print_interval == 25)
1535                 num_print_interval = 0;
1536 }
1537
1538 static void print_header(int argc, const char **argv)
1539 {
1540         FILE *output = stat_config.output;
1541         int i;
1542
1543         fflush(stdout);
1544
1545         if (!csv_output) {
1546                 fprintf(output, "\n");
1547                 fprintf(output, " Performance counter stats for ");
1548                 if (target.system_wide)
1549                         fprintf(output, "\'system wide");
1550                 else if (target.cpu_list)
1551                         fprintf(output, "\'CPU(s) %s", target.cpu_list);
1552                 else if (!target__has_task(&target)) {
1553                         fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1554                         for (i = 1; argv && (i < argc); i++)
1555                                 fprintf(output, " %s", argv[i]);
1556                 } else if (target.pid)
1557                         fprintf(output, "process id \'%s", target.pid);
1558                 else
1559                         fprintf(output, "thread id \'%s", target.tid);
1560
1561                 fprintf(output, "\'");
1562                 if (run_count > 1)
1563                         fprintf(output, " (%d runs)", run_count);
1564                 fprintf(output, ":\n\n");
1565         }
1566 }
1567
1568 static void print_footer(void)
1569 {
1570         FILE *output = stat_config.output;
1571
1572         if (!null_run)
1573                 fprintf(output, "\n");
1574         fprintf(output, " %17.9f seconds time elapsed",
1575                         avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
1576         if (run_count > 1) {
1577                 fprintf(output, "                                        ");
1578                 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1579                                 avg_stats(&walltime_nsecs_stats));
1580         }
1581         fprintf(output, "\n\n");
1582
1583         if (print_free_counters_hint)
1584                 fprintf(output,
1585 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1586 "       echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1587 "       perf stat ...\n"
1588 "       echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1589 }
1590
1591 static void print_counters(struct timespec *ts, int argc, const char **argv)
1592 {
1593         int interval = stat_config.interval;
1594         struct perf_evsel *counter;
1595         char buf[64], *prefix = NULL;
1596
1597         /* Do not print anything if we record to the pipe. */
1598         if (STAT_RECORD && perf_stat.file.is_pipe)
1599                 return;
1600
1601         if (interval)
1602                 print_interval(prefix = buf, ts);
1603         else
1604                 print_header(argc, argv);
1605
1606         if (metric_only) {
1607                 static int num_print_iv;
1608
1609                 if (num_print_iv == 0 && !interval)
1610                         print_metric_headers(prefix, false);
1611                 if (num_print_iv++ == 25)
1612                         num_print_iv = 0;
1613                 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1614                         fprintf(stat_config.output, "%s", prefix);
1615         }
1616
1617         switch (stat_config.aggr_mode) {
1618         case AGGR_CORE:
1619         case AGGR_SOCKET:
1620                 print_aggr(prefix);
1621                 break;
1622         case AGGR_THREAD:
1623                 evlist__for_each_entry(evsel_list, counter)
1624                         print_aggr_thread(counter, prefix);
1625                 break;
1626         case AGGR_GLOBAL:
1627                 evlist__for_each_entry(evsel_list, counter)
1628                         print_counter_aggr(counter, prefix);
1629                 if (metric_only)
1630                         fputc('\n', stat_config.output);
1631                 break;
1632         case AGGR_NONE:
1633                 if (metric_only)
1634                         print_no_aggr_metric(prefix);
1635                 else {
1636                         evlist__for_each_entry(evsel_list, counter)
1637                                 print_counter(counter, prefix);
1638                 }
1639                 break;
1640         case AGGR_UNSET:
1641         default:
1642                 break;
1643         }
1644
1645         if (!interval && !csv_output)
1646                 print_footer();
1647
1648         fflush(stat_config.output);
1649 }
1650
1651 static volatile int signr = -1;
1652
1653 static void skip_signal(int signo)
1654 {
1655         if ((child_pid == -1) || stat_config.interval)
1656                 done = 1;
1657
1658         signr = signo;
1659         /*
1660          * render child_pid harmless
1661          * won't send SIGTERM to a random
1662          * process in case of race condition
1663          * and fast PID recycling
1664          */
1665         child_pid = -1;
1666 }
1667
1668 static void sig_atexit(void)
1669 {
1670         sigset_t set, oset;
1671
1672         /*
1673          * avoid race condition with SIGCHLD handler
1674          * in skip_signal() which is modifying child_pid
1675          * goal is to avoid send SIGTERM to a random
1676          * process
1677          */
1678         sigemptyset(&set);
1679         sigaddset(&set, SIGCHLD);
1680         sigprocmask(SIG_BLOCK, &set, &oset);
1681
1682         if (child_pid != -1)
1683                 kill(child_pid, SIGTERM);
1684
1685         sigprocmask(SIG_SETMASK, &oset, NULL);
1686
1687         if (signr == -1)
1688                 return;
1689
1690         signal(signr, SIG_DFL);
1691         kill(getpid(), signr);
1692 }
1693
1694 static int stat__set_big_num(const struct option *opt __maybe_unused,
1695                              const char *s __maybe_unused, int unset)
1696 {
1697         big_num_opt = unset ? 0 : 1;
1698         return 0;
1699 }
1700
1701 static int enable_metric_only(const struct option *opt __maybe_unused,
1702                               const char *s __maybe_unused, int unset)
1703 {
1704         force_metric_only = true;
1705         metric_only = !unset;
1706         return 0;
1707 }
1708
1709 static const struct option stat_options[] = {
1710         OPT_BOOLEAN('T', "transaction", &transaction_run,
1711                     "hardware transaction statistics"),
1712         OPT_CALLBACK('e', "event", &evsel_list, "event",
1713                      "event selector. use 'perf list' to list available events",
1714                      parse_events_option),
1715         OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1716                      "event filter", parse_filter),
1717         OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1718                     "child tasks do not inherit counters"),
1719         OPT_STRING('p', "pid", &target.pid, "pid",
1720                    "stat events on existing process id"),
1721         OPT_STRING('t', "tid", &target.tid, "tid",
1722                    "stat events on existing thread id"),
1723         OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1724                     "system-wide collection from all CPUs"),
1725         OPT_BOOLEAN('g', "group", &group,
1726                     "put the counters into a counter group"),
1727         OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1728         OPT_INCR('v', "verbose", &verbose,
1729                     "be more verbose (show counter open errors, etc)"),
1730         OPT_INTEGER('r', "repeat", &run_count,
1731                     "repeat command and print average + stddev (max: 100, forever: 0)"),
1732         OPT_BOOLEAN('n', "null", &null_run,
1733                     "null run - dont start any counters"),
1734         OPT_INCR('d', "detailed", &detailed_run,
1735                     "detailed run - start a lot of events"),
1736         OPT_BOOLEAN('S', "sync", &sync_run,
1737                     "call sync() before starting a run"),
1738         OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1739                            "print large numbers with thousands\' separators",
1740                            stat__set_big_num),
1741         OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1742                     "list of cpus to monitor in system-wide"),
1743         OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1744                     "disable CPU count aggregation", AGGR_NONE),
1745         OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
1746         OPT_STRING('x', "field-separator", &csv_sep, "separator",
1747                    "print counts with custom separator"),
1748         OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1749                      "monitor event in cgroup name only", parse_cgroups),
1750         OPT_STRING('o', "output", &output_name, "file", "output file name"),
1751         OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1752         OPT_INTEGER(0, "log-fd", &output_fd,
1753                     "log output to fd, instead of stderr"),
1754         OPT_STRING(0, "pre", &pre_cmd, "command",
1755                         "command to run prior to the measured command"),
1756         OPT_STRING(0, "post", &post_cmd, "command",
1757                         "command to run after to the measured command"),
1758         OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1759                     "print counts at regular interval in ms (>= 10)"),
1760         OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1761                      "aggregate counts per processor socket", AGGR_SOCKET),
1762         OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1763                      "aggregate counts per physical processor core", AGGR_CORE),
1764         OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1765                      "aggregate counts per thread", AGGR_THREAD),
1766         OPT_UINTEGER('D', "delay", &initial_delay,
1767                      "ms to wait before starting measurement after program start"),
1768         OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
1769                         "Only print computed metrics. No raw values", enable_metric_only),
1770         OPT_BOOLEAN(0, "topdown", &topdown_run,
1771                         "measure topdown level 1 statistics"),
1772         OPT_END()
1773 };
1774
1775 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1776 {
1777         return cpu_map__get_socket(map, cpu, NULL);
1778 }
1779
1780 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1781 {
1782         return cpu_map__get_core(map, cpu, NULL);
1783 }
1784
1785 static int cpu_map__get_max(struct cpu_map *map)
1786 {
1787         int i, max = -1;
1788
1789         for (i = 0; i < map->nr; i++) {
1790                 if (map->map[i] > max)
1791                         max = map->map[i];
1792         }
1793
1794         return max;
1795 }
1796
1797 static struct cpu_map *cpus_aggr_map;
1798
1799 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1800 {
1801         int cpu;
1802
1803         if (idx >= map->nr)
1804                 return -1;
1805
1806         cpu = map->map[idx];
1807
1808         if (cpus_aggr_map->map[cpu] == -1)
1809                 cpus_aggr_map->map[cpu] = get_id(map, idx);
1810
1811         return cpus_aggr_map->map[cpu];
1812 }
1813
1814 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1815 {
1816         return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1817 }
1818
1819 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1820 {
1821         return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1822 }
1823
1824 static int perf_stat_init_aggr_mode(void)
1825 {
1826         int nr;
1827
1828         switch (stat_config.aggr_mode) {
1829         case AGGR_SOCKET:
1830                 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1831                         perror("cannot build socket map");
1832                         return -1;
1833                 }
1834                 aggr_get_id = perf_stat__get_socket_cached;
1835                 break;
1836         case AGGR_CORE:
1837                 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1838                         perror("cannot build core map");
1839                         return -1;
1840                 }
1841                 aggr_get_id = perf_stat__get_core_cached;
1842                 break;
1843         case AGGR_NONE:
1844         case AGGR_GLOBAL:
1845         case AGGR_THREAD:
1846         case AGGR_UNSET:
1847         default:
1848                 break;
1849         }
1850
1851         /*
1852          * The evsel_list->cpus is the base we operate on,
1853          * taking the highest cpu number to be the size of
1854          * the aggregation translate cpumap.
1855          */
1856         nr = cpu_map__get_max(evsel_list->cpus);
1857         cpus_aggr_map = cpu_map__empty_new(nr + 1);
1858         return cpus_aggr_map ? 0 : -ENOMEM;
1859 }
1860
1861 static void perf_stat__exit_aggr_mode(void)
1862 {
1863         cpu_map__put(aggr_map);
1864         cpu_map__put(cpus_aggr_map);
1865         aggr_map = NULL;
1866         cpus_aggr_map = NULL;
1867 }
1868
1869 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1870 {
1871         int cpu;
1872
1873         if (idx > map->nr)
1874                 return -1;
1875
1876         cpu = map->map[idx];
1877
1878         if (cpu >= env->nr_cpus_avail)
1879                 return -1;
1880
1881         return cpu;
1882 }
1883
1884 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1885 {
1886         struct perf_env *env = data;
1887         int cpu = perf_env__get_cpu(env, map, idx);
1888
1889         return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1890 }
1891
1892 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1893 {
1894         struct perf_env *env = data;
1895         int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1896
1897         if (cpu != -1) {
1898                 int socket_id = env->cpu[cpu].socket_id;
1899
1900                 /*
1901                  * Encode socket in upper 16 bits
1902                  * core_id is relative to socket, and
1903                  * we need a global id. So we combine
1904                  * socket + core id.
1905                  */
1906                 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1907         }
1908
1909         return core;
1910 }
1911
1912 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1913                                       struct cpu_map **sockp)
1914 {
1915         return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1916 }
1917
1918 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
1919                                     struct cpu_map **corep)
1920 {
1921         return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1922 }
1923
1924 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
1925 {
1926         return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1927 }
1928
1929 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
1930 {
1931         return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1932 }
1933
1934 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1935 {
1936         struct perf_env *env = &st->session->header.env;
1937
1938         switch (stat_config.aggr_mode) {
1939         case AGGR_SOCKET:
1940                 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
1941                         perror("cannot build socket map");
1942                         return -1;
1943                 }
1944                 aggr_get_id = perf_stat__get_socket_file;
1945                 break;
1946         case AGGR_CORE:
1947                 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
1948                         perror("cannot build core map");
1949                         return -1;
1950                 }
1951                 aggr_get_id = perf_stat__get_core_file;
1952                 break;
1953         case AGGR_NONE:
1954         case AGGR_GLOBAL:
1955         case AGGR_THREAD:
1956         case AGGR_UNSET:
1957         default:
1958                 break;
1959         }
1960
1961         return 0;
1962 }
1963
1964 static int topdown_filter_events(const char **attr, char **str, bool use_group)
1965 {
1966         int off = 0;
1967         int i;
1968         int len = 0;
1969         char *s;
1970
1971         for (i = 0; attr[i]; i++) {
1972                 if (pmu_have_event("cpu", attr[i])) {
1973                         len += strlen(attr[i]) + 1;
1974                         attr[i - off] = attr[i];
1975                 } else
1976                         off++;
1977         }
1978         attr[i - off] = NULL;
1979
1980         *str = malloc(len + 1 + 2);
1981         if (!*str)
1982                 return -1;
1983         s = *str;
1984         if (i - off == 0) {
1985                 *s = 0;
1986                 return 0;
1987         }
1988         if (use_group)
1989                 *s++ = '{';
1990         for (i = 0; attr[i]; i++) {
1991                 strcpy(s, attr[i]);
1992                 s += strlen(s);
1993                 *s++ = ',';
1994         }
1995         if (use_group) {
1996                 s[-1] = '}';
1997                 *s = 0;
1998         } else
1999                 s[-1] = 0;
2000         return 0;
2001 }
2002
2003 __weak bool arch_topdown_check_group(bool *warn)
2004 {
2005         *warn = false;
2006         return false;
2007 }
2008
2009 __weak void arch_topdown_group_warn(void)
2010 {
2011 }
2012
2013 /*
2014  * Add default attributes, if there were no attributes specified or
2015  * if -d/--detailed, -d -d or -d -d -d is used:
2016  */
2017 static int add_default_attributes(void)
2018 {
2019         int err;
2020         struct perf_event_attr default_attrs0[] = {
2021
2022   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK              },
2023   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES        },
2024   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS          },
2025   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS             },
2026
2027   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES              },
2028 };
2029         struct perf_event_attr frontend_attrs[] = {
2030   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
2031 };
2032         struct perf_event_attr backend_attrs[] = {
2033   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND  },
2034 };
2035         struct perf_event_attr default_attrs1[] = {
2036   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS            },
2037   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS     },
2038   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES           },
2039
2040 };
2041
2042 /*
2043  * Detailed stats (-d), covering the L1 and last level data caches:
2044  */
2045         struct perf_event_attr detailed_attrs[] = {
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_ACCESS      << 16)                          },
2052
2053   { .type = PERF_TYPE_HW_CACHE,
2054     .config =
2055          PERF_COUNT_HW_CACHE_L1D                <<  0  |
2056         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2057         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 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_ACCESS      << 16)                          },
2064
2065   { .type = PERF_TYPE_HW_CACHE,
2066     .config =
2067          PERF_COUNT_HW_CACHE_LL                 <<  0  |
2068         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2069         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
2070 };
2071
2072 /*
2073  * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2074  */
2075         struct perf_event_attr very_detailed_attrs[] = {
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_ACCESS      << 16)                          },
2082
2083   { .type = PERF_TYPE_HW_CACHE,
2084     .config =
2085          PERF_COUNT_HW_CACHE_L1I                <<  0  |
2086         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2087         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 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_ACCESS      << 16)                          },
2094
2095   { .type = PERF_TYPE_HW_CACHE,
2096     .config =
2097          PERF_COUNT_HW_CACHE_DTLB               <<  0  |
2098         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2099         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 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_ACCESS      << 16)                          },
2106
2107   { .type = PERF_TYPE_HW_CACHE,
2108     .config =
2109          PERF_COUNT_HW_CACHE_ITLB               <<  0  |
2110         (PERF_COUNT_HW_CACHE_OP_READ            <<  8) |
2111         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
2112
2113 };
2114
2115 /*
2116  * Very, very detailed stats (-d -d -d), adding prefetch events:
2117  */
2118         struct perf_event_attr very_very_detailed_attrs[] = {
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_ACCESS      << 16)                          },
2125
2126   { .type = PERF_TYPE_HW_CACHE,
2127     .config =
2128          PERF_COUNT_HW_CACHE_L1D                <<  0  |
2129         (PERF_COUNT_HW_CACHE_OP_PREFETCH        <<  8) |
2130         (PERF_COUNT_HW_CACHE_RESULT_MISS        << 16)                          },
2131 };
2132
2133         /* Set attrs if no event is selected and !null_run: */
2134         if (null_run)
2135                 return 0;
2136
2137         if (transaction_run) {
2138                 if (pmu_have_event("cpu", "cycles-ct") &&
2139                     pmu_have_event("cpu", "el-start"))
2140                         err = parse_events(evsel_list, transaction_attrs, NULL);
2141                 else
2142                         err = parse_events(evsel_list, transaction_limited_attrs, NULL);
2143                 if (err) {
2144                         fprintf(stderr, "Cannot set up transaction events\n");
2145                         return -1;
2146                 }
2147                 return 0;
2148         }
2149
2150         if (topdown_run) {
2151                 char *str = NULL;
2152                 bool warn = false;
2153
2154                 if (stat_config.aggr_mode != AGGR_GLOBAL &&
2155                     stat_config.aggr_mode != AGGR_CORE) {
2156                         pr_err("top down event configuration requires --per-core mode\n");
2157                         return -1;
2158                 }
2159                 stat_config.aggr_mode = AGGR_CORE;
2160                 if (nr_cgroups || !target__has_cpu(&target)) {
2161                         pr_err("top down event configuration requires system-wide mode (-a)\n");
2162                         return -1;
2163                 }
2164
2165                 if (!force_metric_only)
2166                         metric_only = true;
2167                 if (topdown_filter_events(topdown_attrs, &str,
2168                                 arch_topdown_check_group(&warn)) < 0) {
2169                         pr_err("Out of memory\n");
2170                         return -1;
2171                 }
2172                 if (topdown_attrs[0] && str) {
2173                         if (warn)
2174                                 arch_topdown_group_warn();
2175                         err = parse_events(evsel_list, str, NULL);
2176                         if (err) {
2177                                 fprintf(stderr,
2178                                         "Cannot set up top down events %s: %d\n",
2179                                         str, err);
2180                                 free(str);
2181                                 return -1;
2182                         }
2183                 } else {
2184                         fprintf(stderr, "System does not support topdown\n");
2185                         return -1;
2186                 }
2187                 free(str);
2188         }
2189
2190         if (!evsel_list->nr_entries) {
2191                 if (target__has_cpu(&target))
2192                         default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2193
2194                 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2195                         return -1;
2196                 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2197                         if (perf_evlist__add_default_attrs(evsel_list,
2198                                                 frontend_attrs) < 0)
2199                                 return -1;
2200                 }
2201                 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2202                         if (perf_evlist__add_default_attrs(evsel_list,
2203                                                 backend_attrs) < 0)
2204                                 return -1;
2205                 }
2206                 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2207                         return -1;
2208         }
2209
2210         /* Detailed events get appended to the event list: */
2211
2212         if (detailed_run <  1)
2213                 return 0;
2214
2215         /* Append detailed run extra attributes: */
2216         if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2217                 return -1;
2218
2219         if (detailed_run < 2)
2220                 return 0;
2221
2222         /* Append very detailed run extra attributes: */
2223         if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2224                 return -1;
2225
2226         if (detailed_run < 3)
2227                 return 0;
2228
2229         /* Append very, very detailed run extra attributes: */
2230         return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2231 }
2232
2233 static const char * const stat_record_usage[] = {
2234         "perf stat record [<options>]",
2235         NULL,
2236 };
2237
2238 static void init_features(struct perf_session *session)
2239 {
2240         int feat;
2241
2242         for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2243                 perf_header__set_feat(&session->header, feat);
2244
2245         perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2246         perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2247         perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2248         perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2249 }
2250
2251 static int __cmd_record(int argc, const char **argv)
2252 {
2253         struct perf_session *session;
2254         struct perf_data_file *file = &perf_stat.file;
2255
2256         argc = parse_options(argc, argv, stat_options, stat_record_usage,
2257                              PARSE_OPT_STOP_AT_NON_OPTION);
2258
2259         if (output_name)
2260                 file->path = output_name;
2261
2262         if (run_count != 1 || forever) {
2263                 pr_err("Cannot use -r option with perf stat record.\n");
2264                 return -1;
2265         }
2266
2267         session = perf_session__new(file, false, NULL);
2268         if (session == NULL) {
2269                 pr_err("Perf session creation failed.\n");
2270                 return -1;
2271         }
2272
2273         init_features(session);
2274
2275         session->evlist   = evsel_list;
2276         perf_stat.session = session;
2277         perf_stat.record  = true;
2278         return argc;
2279 }
2280
2281 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2282                                     union perf_event *event,
2283                                     struct perf_session *session)
2284 {
2285         struct stat_round_event *stat_round = &event->stat_round;
2286         struct perf_evsel *counter;
2287         struct timespec tsh, *ts = NULL;
2288         const char **argv = session->header.env.cmdline_argv;
2289         int argc = session->header.env.nr_cmdline;
2290
2291         evlist__for_each_entry(evsel_list, counter)
2292                 perf_stat_process_counter(&stat_config, counter);
2293
2294         if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2295                 update_stats(&walltime_nsecs_stats, stat_round->time);
2296
2297         if (stat_config.interval && stat_round->time) {
2298                 tsh.tv_sec  = stat_round->time / NSEC_PER_SEC;
2299                 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2300                 ts = &tsh;
2301         }
2302
2303         print_counters(ts, argc, argv);
2304         return 0;
2305 }
2306
2307 static
2308 int process_stat_config_event(struct perf_tool *tool,
2309                               union perf_event *event,
2310                               struct perf_session *session __maybe_unused)
2311 {
2312         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2313
2314         perf_event__read_stat_config(&stat_config, &event->stat_config);
2315
2316         if (cpu_map__empty(st->cpus)) {
2317                 if (st->aggr_mode != AGGR_UNSET)
2318                         pr_warning("warning: processing task data, aggregation mode not set\n");
2319                 return 0;
2320         }
2321
2322         if (st->aggr_mode != AGGR_UNSET)
2323                 stat_config.aggr_mode = st->aggr_mode;
2324
2325         if (perf_stat.file.is_pipe)
2326                 perf_stat_init_aggr_mode();
2327         else
2328                 perf_stat_init_aggr_mode_file(st);
2329
2330         return 0;
2331 }
2332
2333 static int set_maps(struct perf_stat *st)
2334 {
2335         if (!st->cpus || !st->threads)
2336                 return 0;
2337
2338         if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2339                 return -EINVAL;
2340
2341         perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2342
2343         if (perf_evlist__alloc_stats(evsel_list, true))
2344                 return -ENOMEM;
2345
2346         st->maps_allocated = true;
2347         return 0;
2348 }
2349
2350 static
2351 int process_thread_map_event(struct perf_tool *tool,
2352                              union perf_event *event,
2353                              struct perf_session *session __maybe_unused)
2354 {
2355         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2356
2357         if (st->threads) {
2358                 pr_warning("Extra thread map event, ignoring.\n");
2359                 return 0;
2360         }
2361
2362         st->threads = thread_map__new_event(&event->thread_map);
2363         if (!st->threads)
2364                 return -ENOMEM;
2365
2366         return set_maps(st);
2367 }
2368
2369 static
2370 int process_cpu_map_event(struct perf_tool *tool,
2371                           union perf_event *event,
2372                           struct perf_session *session __maybe_unused)
2373 {
2374         struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2375         struct cpu_map *cpus;
2376
2377         if (st->cpus) {
2378                 pr_warning("Extra cpu map event, ignoring.\n");
2379                 return 0;
2380         }
2381
2382         cpus = cpu_map__new_data(&event->cpu_map.data);
2383         if (!cpus)
2384                 return -ENOMEM;
2385
2386         st->cpus = cpus;
2387         return set_maps(st);
2388 }
2389
2390 static const char * const stat_report_usage[] = {
2391         "perf stat report [<options>]",
2392         NULL,
2393 };
2394
2395 static struct perf_stat perf_stat = {
2396         .tool = {
2397                 .attr           = perf_event__process_attr,
2398                 .event_update   = perf_event__process_event_update,
2399                 .thread_map     = process_thread_map_event,
2400                 .cpu_map        = process_cpu_map_event,
2401                 .stat_config    = process_stat_config_event,
2402                 .stat           = perf_event__process_stat_event,
2403                 .stat_round     = process_stat_round_event,
2404         },
2405         .aggr_mode = AGGR_UNSET,
2406 };
2407
2408 static int __cmd_report(int argc, const char **argv)
2409 {
2410         struct perf_session *session;
2411         const struct option options[] = {
2412         OPT_STRING('i', "input", &input_name, "file", "input file name"),
2413         OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2414                      "aggregate counts per processor socket", AGGR_SOCKET),
2415         OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2416                      "aggregate counts per physical processor core", AGGR_CORE),
2417         OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2418                      "disable CPU count aggregation", AGGR_NONE),
2419         OPT_END()
2420         };
2421         struct stat st;
2422         int ret;
2423
2424         argc = parse_options(argc, argv, options, stat_report_usage, 0);
2425
2426         if (!input_name || !strlen(input_name)) {
2427                 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2428                         input_name = "-";
2429                 else
2430                         input_name = "perf.data";
2431         }
2432
2433         perf_stat.file.path = input_name;
2434         perf_stat.file.mode = PERF_DATA_MODE_READ;
2435
2436         session = perf_session__new(&perf_stat.file, false, &perf_stat.tool);
2437         if (session == NULL)
2438                 return -1;
2439
2440         perf_stat.session  = session;
2441         stat_config.output = stderr;
2442         evsel_list         = session->evlist;
2443
2444         ret = perf_session__process_events(session);
2445         if (ret)
2446                 return ret;
2447
2448         perf_session__delete(session);
2449         return 0;
2450 }
2451
2452 static void setup_system_wide(int forks)
2453 {
2454         /*
2455          * Make system wide (-a) the default target if
2456          * no target was specified and one of following
2457          * conditions is met:
2458          *
2459          *   - there's no workload specified
2460          *   - there is workload specified but all requested
2461          *     events are system wide events
2462          */
2463         if (!target__none(&target))
2464                 return;
2465
2466         if (!forks)
2467                 target.system_wide = true;
2468         else {
2469                 struct perf_evsel *counter;
2470
2471                 evlist__for_each_entry(evsel_list, counter) {
2472                         if (!counter->system_wide)
2473                                 return;
2474                 }
2475
2476                 if (evsel_list->nr_entries)
2477                         target.system_wide = true;
2478         }
2479 }
2480
2481 int cmd_stat(int argc, const char **argv)
2482 {
2483         const char * const stat_usage[] = {
2484                 "perf stat [<options>] [<command>]",
2485                 NULL
2486         };
2487         int status = -EINVAL, run_idx;
2488         const char *mode;
2489         FILE *output = stderr;
2490         unsigned int interval;
2491         const char * const stat_subcommands[] = { "record", "report" };
2492
2493         setlocale(LC_ALL, "");
2494
2495         evsel_list = perf_evlist__new();
2496         if (evsel_list == NULL)
2497                 return -ENOMEM;
2498
2499         parse_events__shrink_config_terms();
2500         argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2501                                         (const char **) stat_usage,
2502                                         PARSE_OPT_STOP_AT_NON_OPTION);
2503         perf_stat__collect_metric_expr(evsel_list);
2504         perf_stat__init_shadow_stats();
2505
2506         if (csv_sep) {
2507                 csv_output = true;
2508                 if (!strcmp(csv_sep, "\\t"))
2509                         csv_sep = "\t";
2510         } else
2511                 csv_sep = DEFAULT_SEPARATOR;
2512
2513         if (argc && !strncmp(argv[0], "rec", 3)) {
2514                 argc = __cmd_record(argc, argv);
2515                 if (argc < 0)
2516                         return -1;
2517         } else if (argc && !strncmp(argv[0], "rep", 3))
2518                 return __cmd_report(argc, argv);
2519
2520         interval = stat_config.interval;
2521
2522         /*
2523          * For record command the -o is already taken care of.
2524          */
2525         if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2526                 output = NULL;
2527
2528         if (output_name && output_fd) {
2529                 fprintf(stderr, "cannot use both --output and --log-fd\n");
2530                 parse_options_usage(stat_usage, stat_options, "o", 1);
2531                 parse_options_usage(NULL, stat_options, "log-fd", 0);
2532                 goto out;
2533         }
2534
2535         if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2536                 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2537                 goto out;
2538         }
2539
2540         if (metric_only && run_count > 1) {
2541                 fprintf(stderr, "--metric-only is not supported with -r\n");
2542                 goto out;
2543         }
2544
2545         if (output_fd < 0) {
2546                 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2547                 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2548                 goto out;
2549         }
2550
2551         if (!output) {
2552                 struct timespec tm;
2553                 mode = append_file ? "a" : "w";
2554
2555                 output = fopen(output_name, mode);
2556                 if (!output) {
2557                         perror("failed to create output file");
2558                         return -1;
2559                 }
2560                 clock_gettime(CLOCK_REALTIME, &tm);
2561                 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2562         } else if (output_fd > 0) {
2563                 mode = append_file ? "a" : "w";
2564                 output = fdopen(output_fd, mode);
2565                 if (!output) {
2566                         perror("Failed opening logfd");
2567                         return -errno;
2568                 }
2569         }
2570
2571         stat_config.output = output;
2572
2573         /*
2574          * let the spreadsheet do the pretty-printing
2575          */
2576         if (csv_output) {
2577                 /* User explicitly passed -B? */
2578                 if (big_num_opt == 1) {
2579                         fprintf(stderr, "-B option not supported with -x\n");
2580                         parse_options_usage(stat_usage, stat_options, "B", 1);
2581                         parse_options_usage(NULL, stat_options, "x", 1);
2582                         goto out;
2583                 } else /* Nope, so disable big number formatting */
2584                         big_num = false;
2585         } else if (big_num_opt == 0) /* User passed --no-big-num */
2586                 big_num = false;
2587
2588         setup_system_wide(argc);
2589
2590         if (run_count < 0) {
2591                 pr_err("Run count must be a positive number\n");
2592                 parse_options_usage(stat_usage, stat_options, "r", 1);
2593                 goto out;
2594         } else if (run_count == 0) {
2595                 forever = true;
2596                 run_count = 1;
2597         }
2598
2599         if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
2600                 fprintf(stderr, "The --per-thread option is only available "
2601                         "when monitoring via -p -t options.\n");
2602                 parse_options_usage(NULL, stat_options, "p", 1);
2603                 parse_options_usage(NULL, stat_options, "t", 1);
2604                 goto out;
2605         }
2606
2607         /*
2608          * no_aggr, cgroup are for system-wide only
2609          * --per-thread is aggregated per thread, we dont mix it with cpu mode
2610          */
2611         if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2612               stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2613             !target__has_cpu(&target)) {
2614                 fprintf(stderr, "both cgroup and no-aggregation "
2615                         "modes only available in system-wide mode\n");
2616
2617                 parse_options_usage(stat_usage, stat_options, "G", 1);
2618                 parse_options_usage(NULL, stat_options, "A", 1);
2619                 parse_options_usage(NULL, stat_options, "a", 1);
2620                 goto out;
2621         }
2622
2623         if (add_default_attributes())
2624                 goto out;
2625
2626         target__validate(&target);
2627
2628         if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2629                 if (target__has_task(&target)) {
2630                         pr_err("Problems finding threads of monitor\n");
2631                         parse_options_usage(stat_usage, stat_options, "p", 1);
2632                         parse_options_usage(NULL, stat_options, "t", 1);
2633                 } else if (target__has_cpu(&target)) {
2634                         perror("failed to parse CPUs map");
2635                         parse_options_usage(stat_usage, stat_options, "C", 1);
2636                         parse_options_usage(NULL, stat_options, "a", 1);
2637                 }
2638                 goto out;
2639         }
2640
2641         /*
2642          * Initialize thread_map with comm names,
2643          * so we could print it out on output.
2644          */
2645         if (stat_config.aggr_mode == AGGR_THREAD)
2646                 thread_map__read_comms(evsel_list->threads);
2647
2648         if (interval && interval < 100) {
2649                 if (interval < 10) {
2650                         pr_err("print interval must be >= 10ms\n");
2651                         parse_options_usage(stat_usage, stat_options, "I", 1);
2652                         goto out;
2653                 } else
2654                         pr_warning("print interval < 100ms. "
2655                                    "The overhead percentage could be high in some cases. "
2656                                    "Please proceed with caution.\n");
2657         }
2658
2659         if (perf_evlist__alloc_stats(evsel_list, interval))
2660                 goto out;
2661
2662         if (perf_stat_init_aggr_mode())
2663                 goto out;
2664
2665         /*
2666          * We dont want to block the signals - that would cause
2667          * child tasks to inherit that and Ctrl-C would not work.
2668          * What we want is for Ctrl-C to work in the exec()-ed
2669          * task, but being ignored by perf stat itself:
2670          */
2671         atexit(sig_atexit);
2672         if (!forever)
2673                 signal(SIGINT,  skip_signal);
2674         signal(SIGCHLD, skip_signal);
2675         signal(SIGALRM, skip_signal);
2676         signal(SIGABRT, skip_signal);
2677
2678         status = 0;
2679         for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2680                 if (run_count != 1 && verbose > 0)
2681                         fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2682                                 run_idx + 1);
2683
2684                 status = run_perf_stat(argc, argv);
2685                 if (forever && status != -1) {
2686                         print_counters(NULL, argc, argv);
2687                         perf_stat__reset_stats();
2688                 }
2689         }
2690
2691         if (!forever && status != -1 && !interval)
2692                 print_counters(NULL, argc, argv);
2693
2694         if (STAT_RECORD) {
2695                 /*
2696                  * We synthesize the kernel mmap record just so that older tools
2697                  * don't emit warnings about not being able to resolve symbols
2698                  * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2699                  * a saner message about no samples being in the perf.data file.
2700                  *
2701                  * This also serves to suppress a warning about f_header.data.size == 0
2702                  * in header.c at the moment 'perf stat record' gets introduced, which
2703                  * is not really needed once we start adding the stat specific PERF_RECORD_
2704                  * records, but the need to suppress the kptr_restrict messages in older
2705                  * tools remain  -acme
2706                  */
2707                 int fd = perf_data_file__fd(&perf_stat.file);
2708                 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2709                                                              process_synthesized_event,
2710                                                              &perf_stat.session->machines.host);
2711                 if (err) {
2712                         pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2713                                    "older tools may produce warnings about this file\n.");
2714                 }
2715
2716                 if (!interval) {
2717                         if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2718                                 pr_err("failed to write stat round event\n");
2719                 }
2720
2721                 if (!perf_stat.file.is_pipe) {
2722                         perf_stat.session->header.data_size += perf_stat.bytes_written;
2723                         perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2724                 }
2725
2726                 perf_session__delete(perf_stat.session);
2727         }
2728
2729         perf_stat__exit_aggr_mode();
2730         perf_evlist__free_stats(evsel_list);
2731 out:
2732         perf_evlist__delete(evsel_list);
2733         return status;
2734 }