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