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