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