Merge branch 'x86-pti-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux/fpc-iii.git] / tools / perf / builtin-stat.c
blob54a4c152edb3917405dd064a1f79037acbb0d239
1 /*
2 * builtin-stat.c
4 * Builtin stat command: Give a precise performance counters summary
5 * overview about any workload, CPU or specific PID.
7 * Sample output:
9 $ perf stat ./hackbench 10
11 Time: 0.118
13 Performance counter stats for './hackbench 10':
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
27 0.154822978 seconds time elapsed
30 * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
32 * Improvements and fixes by:
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>
41 * Released under the GPL v2. (and only v2, not any later version)
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/string2.h"
67 #include "util/metricgroup.h"
68 #include "asm/bug.h"
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>
84 #include "sane_ctype.h"
86 #define DEFAULT_SEPARATOR " "
87 #define CNTR_NOT_SUPPORTED "<not supported>"
88 #define CNTR_NOT_COUNTED "<not counted>"
89 #define FREEZE_ON_SMI_PATH "devices/cpu/freeze_on_smi"
91 static void print_counters(struct timespec *ts, int argc, const char **argv);
93 /* Default events used for perf stat -T */
94 static const char *transaction_attrs = {
95 "task-clock,"
96 "{"
97 "instructions,"
98 "cycles,"
99 "cpu/cycles-t/,"
100 "cpu/tx-start/,"
101 "cpu/el-start/,"
102 "cpu/cycles-ct/"
106 /* More limited version when the CPU does not have all events. */
107 static const char * transaction_limited_attrs = {
108 "task-clock,"
110 "instructions,"
111 "cycles,"
112 "cpu/cycles-t/,"
113 "cpu/tx-start/"
117 static const char * topdown_attrs[] = {
118 "topdown-total-slots",
119 "topdown-slots-retired",
120 "topdown-recovery-bubbles",
121 "topdown-fetch-bubbles",
122 "topdown-slots-issued",
123 NULL,
126 static const char *smi_cost_attrs = {
128 "msr/aperf/,"
129 "msr/smi/,"
130 "cycles"
134 static struct perf_evlist *evsel_list;
136 static struct rblist metric_events;
138 static struct target target = {
139 .uid = UINT_MAX,
142 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
144 static int run_count = 1;
145 static bool no_inherit = false;
146 static volatile pid_t child_pid = -1;
147 static bool null_run = false;
148 static int detailed_run = 0;
149 static bool transaction_run;
150 static bool topdown_run = false;
151 static bool smi_cost = false;
152 static bool smi_reset = false;
153 static bool big_num = true;
154 static int big_num_opt = -1;
155 static const char *csv_sep = NULL;
156 static bool csv_output = false;
157 static bool group = false;
158 static const char *pre_cmd = NULL;
159 static const char *post_cmd = NULL;
160 static bool sync_run = false;
161 static unsigned int initial_delay = 0;
162 static unsigned int unit_width = 4; /* strlen("unit") */
163 static bool forever = false;
164 static bool metric_only = false;
165 static bool force_metric_only = false;
166 static bool no_merge = false;
167 static struct timespec ref_time;
168 static struct cpu_map *aggr_map;
169 static aggr_get_id_t aggr_get_id;
170 static bool append_file;
171 static const char *output_name;
172 static int output_fd;
173 static int print_free_counters_hint;
175 struct perf_stat {
176 bool record;
177 struct perf_data data;
178 struct perf_session *session;
179 u64 bytes_written;
180 struct perf_tool tool;
181 bool maps_allocated;
182 struct cpu_map *cpus;
183 struct thread_map *threads;
184 enum aggr_mode aggr_mode;
187 static struct perf_stat perf_stat;
188 #define STAT_RECORD perf_stat.record
190 static volatile int done = 0;
192 static struct perf_stat_config stat_config = {
193 .aggr_mode = AGGR_GLOBAL,
194 .scale = true,
197 static bool is_duration_time(struct perf_evsel *evsel)
199 return !strcmp(evsel->name, "duration_time");
202 static inline void diff_timespec(struct timespec *r, struct timespec *a,
203 struct timespec *b)
205 r->tv_sec = a->tv_sec - b->tv_sec;
206 if (a->tv_nsec < b->tv_nsec) {
207 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
208 r->tv_sec--;
209 } else {
210 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
214 static void perf_stat__reset_stats(void)
216 int i;
218 perf_evlist__reset_stats(evsel_list);
219 perf_stat__reset_shadow_stats();
221 for (i = 0; i < stat_config.stats_num; i++)
222 perf_stat__reset_shadow_per_stat(&stat_config.stats[i]);
225 static int create_perf_stat_counter(struct perf_evsel *evsel)
227 struct perf_event_attr *attr = &evsel->attr;
228 struct perf_evsel *leader = evsel->leader;
230 if (stat_config.scale) {
231 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
232 PERF_FORMAT_TOTAL_TIME_RUNNING;
236 * The event is part of non trivial group, let's enable
237 * the group read (for leader) and ID retrieval for all
238 * members.
240 if (leader->nr_members > 1)
241 attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
243 attr->inherit = !no_inherit;
246 * Some events get initialized with sample_(period/type) set,
247 * like tracepoints. Clear it up for counting.
249 attr->sample_period = 0;
252 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
253 * while avoiding that older tools show confusing messages.
255 * However for pipe sessions we need to keep it zero,
256 * because script's perf_evsel__check_attr is triggered
257 * by attr->sample_type != 0, and we can't run it on
258 * stat sessions.
260 if (!(STAT_RECORD && perf_stat.data.is_pipe))
261 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
264 * Disabling all counters initially, they will be enabled
265 * either manually by us or by kernel via enable_on_exec
266 * set later.
268 if (perf_evsel__is_group_leader(evsel)) {
269 attr->disabled = 1;
272 * In case of initial_delay we enable tracee
273 * events manually.
275 if (target__none(&target) && !initial_delay)
276 attr->enable_on_exec = 1;
279 if (target__has_cpu(&target) && !target__has_per_thread(&target))
280 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
282 return perf_evsel__open_per_thread(evsel, evsel_list->threads);
286 * Does the counter have nsecs as a unit?
288 static inline int nsec_counter(struct perf_evsel *evsel)
290 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
291 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
292 return 1;
294 return 0;
297 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
298 union perf_event *event,
299 struct perf_sample *sample __maybe_unused,
300 struct machine *machine __maybe_unused)
302 if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
303 pr_err("failed to write perf data, error: %m\n");
304 return -1;
307 perf_stat.bytes_written += event->header.size;
308 return 0;
311 static int write_stat_round_event(u64 tm, u64 type)
313 return perf_event__synthesize_stat_round(NULL, tm, type,
314 process_synthesized_event,
315 NULL);
318 #define WRITE_STAT_ROUND_EVENT(time, interval) \
319 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
321 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
323 static int
324 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
325 struct perf_counts_values *count)
327 struct perf_sample_id *sid = SID(counter, cpu, thread);
329 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
330 process_synthesized_event, NULL);
334 * Read out the results of a single counter:
335 * do not aggregate counts across CPUs in system-wide mode
337 static int read_counter(struct perf_evsel *counter)
339 int nthreads = thread_map__nr(evsel_list->threads);
340 int ncpus, cpu, thread;
342 if (target__has_cpu(&target) && !target__has_per_thread(&target))
343 ncpus = perf_evsel__nr_cpus(counter);
344 else
345 ncpus = 1;
347 if (!counter->supported)
348 return -ENOENT;
350 if (counter->system_wide)
351 nthreads = 1;
353 for (thread = 0; thread < nthreads; thread++) {
354 for (cpu = 0; cpu < ncpus; cpu++) {
355 struct perf_counts_values *count;
357 count = perf_counts(counter->counts, cpu, thread);
360 * The leader's group read loads data into its group members
361 * (via perf_evsel__read_counter) and sets threir count->loaded.
363 if (!count->loaded &&
364 perf_evsel__read_counter(counter, cpu, thread)) {
365 counter->counts->scaled = -1;
366 perf_counts(counter->counts, cpu, thread)->ena = 0;
367 perf_counts(counter->counts, cpu, thread)->run = 0;
368 return -1;
371 count->loaded = false;
373 if (STAT_RECORD) {
374 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
375 pr_err("failed to write stat event\n");
376 return -1;
380 if (verbose > 1) {
381 fprintf(stat_config.output,
382 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
383 perf_evsel__name(counter),
384 cpu,
385 count->val, count->ena, count->run);
390 return 0;
393 static void read_counters(void)
395 struct perf_evsel *counter;
396 int ret;
398 evlist__for_each_entry(evsel_list, counter) {
399 ret = read_counter(counter);
400 if (ret)
401 pr_debug("failed to read counter %s\n", counter->name);
403 if (ret == 0 && perf_stat_process_counter(&stat_config, counter))
404 pr_warning("failed to process counter %s\n", counter->name);
408 static void process_interval(void)
410 struct timespec ts, rs;
412 read_counters();
414 clock_gettime(CLOCK_MONOTONIC, &ts);
415 diff_timespec(&rs, &ts, &ref_time);
417 if (STAT_RECORD) {
418 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
419 pr_err("failed to write stat round event\n");
422 init_stats(&walltime_nsecs_stats);
423 update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000);
424 print_counters(&rs, 0, NULL);
427 static void enable_counters(void)
429 if (initial_delay)
430 usleep(initial_delay * USEC_PER_MSEC);
433 * We need to enable counters only if:
434 * - we don't have tracee (attaching to task or cpu)
435 * - we have initial delay configured
437 if (!target__none(&target) || initial_delay)
438 perf_evlist__enable(evsel_list);
441 static void disable_counters(void)
444 * If we don't have tracee (attaching to task or cpu), counters may
445 * still be running. To get accurate group ratios, we must stop groups
446 * from counting before reading their constituent counters.
448 if (!target__none(&target))
449 perf_evlist__disable(evsel_list);
452 static volatile int workload_exec_errno;
455 * perf_evlist__prepare_workload will send a SIGUSR1
456 * if the fork fails, since we asked by setting its
457 * want_signal to true.
459 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
460 void *ucontext __maybe_unused)
462 workload_exec_errno = info->si_value.sival_int;
465 static int perf_stat_synthesize_config(bool is_pipe)
467 int err;
469 if (is_pipe) {
470 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
471 process_synthesized_event);
472 if (err < 0) {
473 pr_err("Couldn't synthesize attrs.\n");
474 return err;
478 err = perf_event__synthesize_extra_attr(NULL,
479 evsel_list,
480 process_synthesized_event,
481 is_pipe);
483 err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
484 process_synthesized_event,
485 NULL);
486 if (err < 0) {
487 pr_err("Couldn't synthesize thread map.\n");
488 return err;
491 err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
492 process_synthesized_event, NULL);
493 if (err < 0) {
494 pr_err("Couldn't synthesize thread map.\n");
495 return err;
498 err = perf_event__synthesize_stat_config(NULL, &stat_config,
499 process_synthesized_event, NULL);
500 if (err < 0) {
501 pr_err("Couldn't synthesize config.\n");
502 return err;
505 return 0;
508 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
510 static int __store_counter_ids(struct perf_evsel *counter,
511 struct cpu_map *cpus,
512 struct thread_map *threads)
514 int cpu, thread;
516 for (cpu = 0; cpu < cpus->nr; cpu++) {
517 for (thread = 0; thread < threads->nr; thread++) {
518 int fd = FD(counter, cpu, thread);
520 if (perf_evlist__id_add_fd(evsel_list, counter,
521 cpu, thread, fd) < 0)
522 return -1;
526 return 0;
529 static int store_counter_ids(struct perf_evsel *counter)
531 struct cpu_map *cpus = counter->cpus;
532 struct thread_map *threads = counter->threads;
534 if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
535 return -ENOMEM;
537 return __store_counter_ids(counter, cpus, threads);
540 static bool perf_evsel__should_store_id(struct perf_evsel *counter)
542 return STAT_RECORD || counter->attr.read_format & PERF_FORMAT_ID;
545 static struct perf_evsel *perf_evsel__reset_weak_group(struct perf_evsel *evsel)
547 struct perf_evsel *c2, *leader;
548 bool is_open = true;
550 leader = evsel->leader;
551 pr_debug("Weak group for %s/%d failed\n",
552 leader->name, leader->nr_members);
555 * for_each_group_member doesn't work here because it doesn't
556 * include the first entry.
558 evlist__for_each_entry(evsel_list, c2) {
559 if (c2 == evsel)
560 is_open = false;
561 if (c2->leader == leader) {
562 if (is_open)
563 perf_evsel__close(c2);
564 c2->leader = c2;
565 c2->nr_members = 0;
568 return leader;
571 static int __run_perf_stat(int argc, const char **argv)
573 int interval = stat_config.interval;
574 char msg[BUFSIZ];
575 unsigned long long t0, t1;
576 struct perf_evsel *counter;
577 struct timespec ts;
578 size_t l;
579 int status = 0;
580 const bool forks = (argc > 0);
581 bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
582 struct perf_evsel_config_term *err_term;
584 if (interval) {
585 ts.tv_sec = interval / USEC_PER_MSEC;
586 ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
587 } else {
588 ts.tv_sec = 1;
589 ts.tv_nsec = 0;
592 if (forks) {
593 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
594 workload_exec_failed_signal) < 0) {
595 perror("failed to prepare workload");
596 return -1;
598 child_pid = evsel_list->workload.pid;
601 if (group)
602 perf_evlist__set_leader(evsel_list);
604 evlist__for_each_entry(evsel_list, counter) {
605 try_again:
606 if (create_perf_stat_counter(counter) < 0) {
608 /* Weak group failed. Reset the group. */
609 if ((errno == EINVAL || errno == EBADF) &&
610 counter->leader != counter &&
611 counter->weak_group) {
612 counter = perf_evsel__reset_weak_group(counter);
613 goto try_again;
617 * PPC returns ENXIO for HW counters until 2.6.37
618 * (behavior changed with commit b0a873e).
620 if (errno == EINVAL || errno == ENOSYS ||
621 errno == ENOENT || errno == EOPNOTSUPP ||
622 errno == ENXIO) {
623 if (verbose > 0)
624 ui__warning("%s event is not supported by the kernel.\n",
625 perf_evsel__name(counter));
626 counter->supported = false;
628 if ((counter->leader != counter) ||
629 !(counter->leader->nr_members > 1))
630 continue;
631 } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
632 if (verbose > 0)
633 ui__warning("%s\n", msg);
634 goto try_again;
637 perf_evsel__open_strerror(counter, &target,
638 errno, msg, sizeof(msg));
639 ui__error("%s\n", msg);
641 if (child_pid != -1)
642 kill(child_pid, SIGTERM);
644 return -1;
646 counter->supported = true;
648 l = strlen(counter->unit);
649 if (l > unit_width)
650 unit_width = l;
652 if (perf_evsel__should_store_id(counter) &&
653 store_counter_ids(counter))
654 return -1;
657 if (perf_evlist__apply_filters(evsel_list, &counter)) {
658 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
659 counter->filter, perf_evsel__name(counter), errno,
660 str_error_r(errno, msg, sizeof(msg)));
661 return -1;
664 if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
665 pr_err("failed to set config \"%s\" on event %s with %d (%s)\n",
666 err_term->val.drv_cfg, perf_evsel__name(counter), errno,
667 str_error_r(errno, msg, sizeof(msg)));
668 return -1;
671 if (STAT_RECORD) {
672 int err, fd = perf_data__fd(&perf_stat.data);
674 if (is_pipe) {
675 err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
676 } else {
677 err = perf_session__write_header(perf_stat.session, evsel_list,
678 fd, false);
681 if (err < 0)
682 return err;
684 err = perf_stat_synthesize_config(is_pipe);
685 if (err < 0)
686 return err;
690 * Enable counters and exec the command:
692 t0 = rdclock();
693 clock_gettime(CLOCK_MONOTONIC, &ref_time);
695 if (forks) {
696 perf_evlist__start_workload(evsel_list);
697 enable_counters();
699 if (interval) {
700 while (!waitpid(child_pid, &status, WNOHANG)) {
701 nanosleep(&ts, NULL);
702 process_interval();
705 waitpid(child_pid, &status, 0);
707 if (workload_exec_errno) {
708 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
709 pr_err("Workload failed: %s\n", emsg);
710 return -1;
713 if (WIFSIGNALED(status))
714 psignal(WTERMSIG(status), argv[0]);
715 } else {
716 enable_counters();
717 while (!done) {
718 nanosleep(&ts, NULL);
719 if (interval)
720 process_interval();
724 disable_counters();
726 t1 = rdclock();
728 update_stats(&walltime_nsecs_stats, t1 - t0);
731 * Closing a group leader splits the group, and as we only disable
732 * group leaders, results in remaining events becoming enabled. To
733 * avoid arbitrary skew, we must read all counters before closing any
734 * group leaders.
736 read_counters();
737 perf_evlist__close(evsel_list);
739 return WEXITSTATUS(status);
742 static int run_perf_stat(int argc, const char **argv)
744 int ret;
746 if (pre_cmd) {
747 ret = system(pre_cmd);
748 if (ret)
749 return ret;
752 if (sync_run)
753 sync();
755 ret = __run_perf_stat(argc, argv);
756 if (ret)
757 return ret;
759 if (post_cmd) {
760 ret = system(post_cmd);
761 if (ret)
762 return ret;
765 return ret;
768 static void print_running(u64 run, u64 ena)
770 if (csv_output) {
771 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
772 csv_sep,
773 run,
774 csv_sep,
775 ena ? 100.0 * run / ena : 100.0);
776 } else if (run != ena) {
777 fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena);
781 static void print_noise_pct(double total, double avg)
783 double pct = rel_stddev_stats(total, avg);
785 if (csv_output)
786 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
787 else if (pct)
788 fprintf(stat_config.output, " ( +-%6.2f%% )", pct);
791 static void print_noise(struct perf_evsel *evsel, double avg)
793 struct perf_stat_evsel *ps;
795 if (run_count == 1)
796 return;
798 ps = evsel->stats;
799 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
802 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
804 switch (stat_config.aggr_mode) {
805 case AGGR_CORE:
806 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
807 cpu_map__id_to_socket(id),
808 csv_output ? 0 : -8,
809 cpu_map__id_to_cpu(id),
810 csv_sep,
811 csv_output ? 0 : 4,
813 csv_sep);
814 break;
815 case AGGR_SOCKET:
816 fprintf(stat_config.output, "S%*d%s%*d%s",
817 csv_output ? 0 : -5,
819 csv_sep,
820 csv_output ? 0 : 4,
822 csv_sep);
823 break;
824 case AGGR_NONE:
825 fprintf(stat_config.output, "CPU%*d%s",
826 csv_output ? 0 : -4,
827 perf_evsel__cpus(evsel)->map[id], csv_sep);
828 break;
829 case AGGR_THREAD:
830 fprintf(stat_config.output, "%*s-%*d%s",
831 csv_output ? 0 : 16,
832 thread_map__comm(evsel->threads, id),
833 csv_output ? 0 : -8,
834 thread_map__pid(evsel->threads, id),
835 csv_sep);
836 break;
837 case AGGR_GLOBAL:
838 case AGGR_UNSET:
839 default:
840 break;
844 struct outstate {
845 FILE *fh;
846 bool newline;
847 const char *prefix;
848 int nfields;
849 int id, nr;
850 struct perf_evsel *evsel;
853 #define METRIC_LEN 35
855 static void new_line_std(void *ctx)
857 struct outstate *os = ctx;
859 os->newline = true;
862 static void do_new_line_std(struct outstate *os)
864 fputc('\n', os->fh);
865 fputs(os->prefix, os->fh);
866 aggr_printout(os->evsel, os->id, os->nr);
867 if (stat_config.aggr_mode == AGGR_NONE)
868 fprintf(os->fh, " ");
869 fprintf(os->fh, " ");
872 static void print_metric_std(void *ctx, const char *color, const char *fmt,
873 const char *unit, double val)
875 struct outstate *os = ctx;
876 FILE *out = os->fh;
877 int n;
878 bool newline = os->newline;
880 os->newline = false;
882 if (unit == NULL || fmt == NULL) {
883 fprintf(out, "%-*s", METRIC_LEN, "");
884 return;
887 if (newline)
888 do_new_line_std(os);
890 n = fprintf(out, " # ");
891 if (color)
892 n += color_fprintf(out, color, fmt, val);
893 else
894 n += fprintf(out, fmt, val);
895 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
898 static void new_line_csv(void *ctx)
900 struct outstate *os = ctx;
901 int i;
903 fputc('\n', os->fh);
904 if (os->prefix)
905 fprintf(os->fh, "%s%s", os->prefix, csv_sep);
906 aggr_printout(os->evsel, os->id, os->nr);
907 for (i = 0; i < os->nfields; i++)
908 fputs(csv_sep, os->fh);
911 static void print_metric_csv(void *ctx,
912 const char *color __maybe_unused,
913 const char *fmt, const char *unit, double val)
915 struct outstate *os = ctx;
916 FILE *out = os->fh;
917 char buf[64], *vals, *ends;
919 if (unit == NULL || fmt == NULL) {
920 fprintf(out, "%s%s", csv_sep, csv_sep);
921 return;
923 snprintf(buf, sizeof(buf), fmt, val);
924 ends = vals = ltrim(buf);
925 while (isdigit(*ends) || *ends == '.')
926 ends++;
927 *ends = 0;
928 while (isspace(*unit))
929 unit++;
930 fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
933 #define METRIC_ONLY_LEN 20
935 /* Filter out some columns that don't work well in metrics only mode */
937 static bool valid_only_metric(const char *unit)
939 if (!unit)
940 return false;
941 if (strstr(unit, "/sec") ||
942 strstr(unit, "hz") ||
943 strstr(unit, "Hz") ||
944 strstr(unit, "CPUs utilized"))
945 return false;
946 return true;
949 static const char *fixunit(char *buf, struct perf_evsel *evsel,
950 const char *unit)
952 if (!strncmp(unit, "of all", 6)) {
953 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
954 unit);
955 return buf;
957 return unit;
960 static void print_metric_only(void *ctx, const char *color, const char *fmt,
961 const char *unit, double val)
963 struct outstate *os = ctx;
964 FILE *out = os->fh;
965 int n;
966 char buf[1024];
967 unsigned mlen = METRIC_ONLY_LEN;
969 if (!valid_only_metric(unit))
970 return;
971 unit = fixunit(buf, os->evsel, unit);
972 if (color)
973 n = color_fprintf(out, color, fmt, val);
974 else
975 n = fprintf(out, fmt, val);
976 if (n > METRIC_ONLY_LEN)
977 n = METRIC_ONLY_LEN;
978 if (mlen < strlen(unit))
979 mlen = strlen(unit) + 1;
980 fprintf(out, "%*s", mlen - n, "");
983 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
984 const char *fmt,
985 const char *unit, double val)
987 struct outstate *os = ctx;
988 FILE *out = os->fh;
989 char buf[64], *vals, *ends;
990 char tbuf[1024];
992 if (!valid_only_metric(unit))
993 return;
994 unit = fixunit(tbuf, os->evsel, unit);
995 snprintf(buf, sizeof buf, fmt, val);
996 ends = vals = ltrim(buf);
997 while (isdigit(*ends) || *ends == '.')
998 ends++;
999 *ends = 0;
1000 fprintf(out, "%s%s", vals, csv_sep);
1003 static void new_line_metric(void *ctx __maybe_unused)
1007 static void print_metric_header(void *ctx, const char *color __maybe_unused,
1008 const char *fmt __maybe_unused,
1009 const char *unit, double val __maybe_unused)
1011 struct outstate *os = ctx;
1012 char tbuf[1024];
1014 if (!valid_only_metric(unit))
1015 return;
1016 unit = fixunit(tbuf, os->evsel, unit);
1017 if (csv_output)
1018 fprintf(os->fh, "%s%s", unit, csv_sep);
1019 else
1020 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
1023 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1025 FILE *output = stat_config.output;
1026 double msecs = avg / NSEC_PER_MSEC;
1027 const char *fmt_v, *fmt_n;
1028 char name[25];
1030 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
1031 fmt_n = csv_output ? "%s" : "%-25s";
1033 aggr_printout(evsel, id, nr);
1035 scnprintf(name, sizeof(name), "%s%s",
1036 perf_evsel__name(evsel), csv_output ? "" : " (msec)");
1038 fprintf(output, fmt_v, msecs, csv_sep);
1040 if (csv_output)
1041 fprintf(output, "%s%s", evsel->unit, csv_sep);
1042 else
1043 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
1045 fprintf(output, fmt_n, name);
1047 if (evsel->cgrp)
1048 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1051 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
1053 int i;
1055 if (!aggr_get_id)
1056 return 0;
1058 if (stat_config.aggr_mode == AGGR_NONE)
1059 return id;
1061 if (stat_config.aggr_mode == AGGR_GLOBAL)
1062 return 0;
1064 for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
1065 int cpu2 = perf_evsel__cpus(evsel)->map[i];
1067 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
1068 return cpu2;
1070 return 0;
1073 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1075 FILE *output = stat_config.output;
1076 double sc = evsel->scale;
1077 const char *fmt;
1079 if (csv_output) {
1080 fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
1081 } else {
1082 if (big_num)
1083 fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
1084 else
1085 fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
1088 aggr_printout(evsel, id, nr);
1090 fprintf(output, fmt, avg, csv_sep);
1092 if (evsel->unit)
1093 fprintf(output, "%-*s%s",
1094 csv_output ? 0 : unit_width,
1095 evsel->unit, csv_sep);
1097 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1099 if (evsel->cgrp)
1100 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1103 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
1104 char *prefix, u64 run, u64 ena, double noise,
1105 struct runtime_stat *st)
1107 struct perf_stat_output_ctx out;
1108 struct outstate os = {
1109 .fh = stat_config.output,
1110 .prefix = prefix ? prefix : "",
1111 .id = id,
1112 .nr = nr,
1113 .evsel = counter,
1115 print_metric_t pm = print_metric_std;
1116 void (*nl)(void *);
1118 if (metric_only) {
1119 nl = new_line_metric;
1120 if (csv_output)
1121 pm = print_metric_only_csv;
1122 else
1123 pm = print_metric_only;
1124 } else
1125 nl = new_line_std;
1127 if (csv_output && !metric_only) {
1128 static int aggr_fields[] = {
1129 [AGGR_GLOBAL] = 0,
1130 [AGGR_THREAD] = 1,
1131 [AGGR_NONE] = 1,
1132 [AGGR_SOCKET] = 2,
1133 [AGGR_CORE] = 2,
1136 pm = print_metric_csv;
1137 nl = new_line_csv;
1138 os.nfields = 3;
1139 os.nfields += aggr_fields[stat_config.aggr_mode];
1140 if (counter->cgrp)
1141 os.nfields++;
1143 if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1144 if (metric_only) {
1145 pm(&os, NULL, "", "", 0);
1146 return;
1148 aggr_printout(counter, id, nr);
1150 fprintf(stat_config.output, "%*s%s",
1151 csv_output ? 0 : 18,
1152 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1153 csv_sep);
1155 if (counter->supported)
1156 print_free_counters_hint = 1;
1158 fprintf(stat_config.output, "%-*s%s",
1159 csv_output ? 0 : unit_width,
1160 counter->unit, csv_sep);
1162 fprintf(stat_config.output, "%*s",
1163 csv_output ? 0 : -25,
1164 perf_evsel__name(counter));
1166 if (counter->cgrp)
1167 fprintf(stat_config.output, "%s%s",
1168 csv_sep, counter->cgrp->name);
1170 if (!csv_output)
1171 pm(&os, NULL, NULL, "", 0);
1172 print_noise(counter, noise);
1173 print_running(run, ena);
1174 if (csv_output)
1175 pm(&os, NULL, NULL, "", 0);
1176 return;
1179 if (metric_only)
1180 /* nothing */;
1181 else if (nsec_counter(counter))
1182 nsec_printout(id, nr, counter, uval);
1183 else
1184 abs_printout(id, nr, counter, uval);
1186 out.print_metric = pm;
1187 out.new_line = nl;
1188 out.ctx = &os;
1189 out.force_header = false;
1191 if (csv_output && !metric_only) {
1192 print_noise(counter, noise);
1193 print_running(run, ena);
1196 perf_stat__print_shadow_stats(counter, uval,
1197 first_shadow_cpu(counter, id),
1198 &out, &metric_events, st);
1199 if (!csv_output && !metric_only) {
1200 print_noise(counter, noise);
1201 print_running(run, ena);
1205 static void aggr_update_shadow(void)
1207 int cpu, s2, id, s;
1208 u64 val;
1209 struct perf_evsel *counter;
1211 for (s = 0; s < aggr_map->nr; s++) {
1212 id = aggr_map->map[s];
1213 evlist__for_each_entry(evsel_list, counter) {
1214 val = 0;
1215 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1216 s2 = aggr_get_id(evsel_list->cpus, cpu);
1217 if (s2 != id)
1218 continue;
1219 val += perf_counts(counter->counts, cpu, 0)->val;
1221 perf_stat__update_shadow_stats(counter, val,
1222 first_shadow_cpu(counter, id),
1223 &rt_stat);
1228 static void collect_all_aliases(struct perf_evsel *counter,
1229 void (*cb)(struct perf_evsel *counter, void *data,
1230 bool first),
1231 void *data)
1233 struct perf_evsel *alias;
1235 alias = list_prepare_entry(counter, &(evsel_list->entries), node);
1236 list_for_each_entry_continue (alias, &evsel_list->entries, node) {
1237 if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
1238 alias->scale != counter->scale ||
1239 alias->cgrp != counter->cgrp ||
1240 strcmp(alias->unit, counter->unit) ||
1241 nsec_counter(alias) != nsec_counter(counter))
1242 break;
1243 alias->merged_stat = true;
1244 cb(alias, data, false);
1248 static bool collect_data(struct perf_evsel *counter,
1249 void (*cb)(struct perf_evsel *counter, void *data,
1250 bool first),
1251 void *data)
1253 if (counter->merged_stat)
1254 return false;
1255 cb(counter, data, true);
1256 if (!no_merge && counter->auto_merge_stats)
1257 collect_all_aliases(counter, cb, data);
1258 return true;
1261 struct aggr_data {
1262 u64 ena, run, val;
1263 int id;
1264 int nr;
1265 int cpu;
1268 static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
1270 struct aggr_data *ad = data;
1271 int cpu, s2;
1273 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1274 struct perf_counts_values *counts;
1276 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1277 if (s2 != ad->id)
1278 continue;
1279 if (first)
1280 ad->nr++;
1281 counts = perf_counts(counter->counts, cpu, 0);
1283 * When any result is bad, make them all to give
1284 * consistent output in interval mode.
1286 if (counts->ena == 0 || counts->run == 0 ||
1287 counter->counts->scaled == -1) {
1288 ad->ena = 0;
1289 ad->run = 0;
1290 break;
1292 ad->val += counts->val;
1293 ad->ena += counts->ena;
1294 ad->run += counts->run;
1298 static void print_aggr(char *prefix)
1300 FILE *output = stat_config.output;
1301 struct perf_evsel *counter;
1302 int s, id, nr;
1303 double uval;
1304 u64 ena, run, val;
1305 bool first;
1307 if (!(aggr_map || aggr_get_id))
1308 return;
1310 aggr_update_shadow();
1313 * With metric_only everything is on a single line.
1314 * Without each counter has its own line.
1316 for (s = 0; s < aggr_map->nr; s++) {
1317 struct aggr_data ad;
1318 if (prefix && metric_only)
1319 fprintf(output, "%s", prefix);
1321 ad.id = id = aggr_map->map[s];
1322 first = true;
1323 evlist__for_each_entry(evsel_list, counter) {
1324 if (is_duration_time(counter))
1325 continue;
1327 ad.val = ad.ena = ad.run = 0;
1328 ad.nr = 0;
1329 if (!collect_data(counter, aggr_cb, &ad))
1330 continue;
1331 nr = ad.nr;
1332 ena = ad.ena;
1333 run = ad.run;
1334 val = ad.val;
1335 if (first && metric_only) {
1336 first = false;
1337 aggr_printout(counter, id, nr);
1339 if (prefix && !metric_only)
1340 fprintf(output, "%s", prefix);
1342 uval = val * counter->scale;
1343 printout(id, nr, counter, uval, prefix, run, ena, 1.0,
1344 &rt_stat);
1345 if (!metric_only)
1346 fputc('\n', output);
1348 if (metric_only)
1349 fputc('\n', output);
1353 static int cmp_val(const void *a, const void *b)
1355 return ((struct perf_aggr_thread_value *)b)->val -
1356 ((struct perf_aggr_thread_value *)a)->val;
1359 static struct perf_aggr_thread_value *sort_aggr_thread(
1360 struct perf_evsel *counter,
1361 int nthreads, int ncpus,
1362 int *ret)
1364 int cpu, thread, i = 0;
1365 double uval;
1366 struct perf_aggr_thread_value *buf;
1368 buf = calloc(nthreads, sizeof(struct perf_aggr_thread_value));
1369 if (!buf)
1370 return NULL;
1372 for (thread = 0; thread < nthreads; thread++) {
1373 u64 ena = 0, run = 0, val = 0;
1375 for (cpu = 0; cpu < ncpus; cpu++) {
1376 val += perf_counts(counter->counts, cpu, thread)->val;
1377 ena += perf_counts(counter->counts, cpu, thread)->ena;
1378 run += perf_counts(counter->counts, cpu, thread)->run;
1381 uval = val * counter->scale;
1384 * Skip value 0 when enabling --per-thread globally,
1385 * otherwise too many 0 output.
1387 if (uval == 0.0 && target__has_per_thread(&target))
1388 continue;
1390 buf[i].counter = counter;
1391 buf[i].id = thread;
1392 buf[i].uval = uval;
1393 buf[i].val = val;
1394 buf[i].run = run;
1395 buf[i].ena = ena;
1396 i++;
1399 qsort(buf, i, sizeof(struct perf_aggr_thread_value), cmp_val);
1401 if (ret)
1402 *ret = i;
1404 return buf;
1407 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1409 FILE *output = stat_config.output;
1410 int nthreads = thread_map__nr(counter->threads);
1411 int ncpus = cpu_map__nr(counter->cpus);
1412 int thread, sorted_threads, id;
1413 struct perf_aggr_thread_value *buf;
1415 buf = sort_aggr_thread(counter, nthreads, ncpus, &sorted_threads);
1416 if (!buf) {
1417 perror("cannot sort aggr thread");
1418 return;
1421 for (thread = 0; thread < sorted_threads; thread++) {
1422 if (prefix)
1423 fprintf(output, "%s", prefix);
1425 id = buf[thread].id;
1426 if (stat_config.stats)
1427 printout(id, 0, buf[thread].counter, buf[thread].uval,
1428 prefix, buf[thread].run, buf[thread].ena, 1.0,
1429 &stat_config.stats[id]);
1430 else
1431 printout(id, 0, buf[thread].counter, buf[thread].uval,
1432 prefix, buf[thread].run, buf[thread].ena, 1.0,
1433 &rt_stat);
1434 fputc('\n', output);
1437 free(buf);
1440 struct caggr_data {
1441 double avg, avg_enabled, avg_running;
1444 static void counter_aggr_cb(struct perf_evsel *counter, void *data,
1445 bool first __maybe_unused)
1447 struct caggr_data *cd = data;
1448 struct perf_stat_evsel *ps = counter->stats;
1450 cd->avg += avg_stats(&ps->res_stats[0]);
1451 cd->avg_enabled += avg_stats(&ps->res_stats[1]);
1452 cd->avg_running += avg_stats(&ps->res_stats[2]);
1456 * Print out the results of a single counter:
1457 * aggregated counts in system-wide mode
1459 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1461 FILE *output = stat_config.output;
1462 double uval;
1463 struct caggr_data cd = { .avg = 0.0 };
1465 if (!collect_data(counter, counter_aggr_cb, &cd))
1466 return;
1468 if (prefix && !metric_only)
1469 fprintf(output, "%s", prefix);
1471 uval = cd.avg * counter->scale;
1472 printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled,
1473 cd.avg, &rt_stat);
1474 if (!metric_only)
1475 fprintf(output, "\n");
1478 static void counter_cb(struct perf_evsel *counter, void *data,
1479 bool first __maybe_unused)
1481 struct aggr_data *ad = data;
1483 ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
1484 ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
1485 ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
1489 * Print out the results of a single counter:
1490 * does not use aggregated count in system-wide
1492 static void print_counter(struct perf_evsel *counter, char *prefix)
1494 FILE *output = stat_config.output;
1495 u64 ena, run, val;
1496 double uval;
1497 int cpu;
1499 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1500 struct aggr_data ad = { .cpu = cpu };
1502 if (!collect_data(counter, counter_cb, &ad))
1503 return;
1504 val = ad.val;
1505 ena = ad.ena;
1506 run = ad.run;
1508 if (prefix)
1509 fprintf(output, "%s", prefix);
1511 uval = val * counter->scale;
1512 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0,
1513 &rt_stat);
1515 fputc('\n', output);
1519 static void print_no_aggr_metric(char *prefix)
1521 int cpu;
1522 int nrcpus = 0;
1523 struct perf_evsel *counter;
1524 u64 ena, run, val;
1525 double uval;
1527 nrcpus = evsel_list->cpus->nr;
1528 for (cpu = 0; cpu < nrcpus; cpu++) {
1529 bool first = true;
1531 if (prefix)
1532 fputs(prefix, stat_config.output);
1533 evlist__for_each_entry(evsel_list, counter) {
1534 if (is_duration_time(counter))
1535 continue;
1536 if (first) {
1537 aggr_printout(counter, cpu, 0);
1538 first = false;
1540 val = perf_counts(counter->counts, cpu, 0)->val;
1541 ena = perf_counts(counter->counts, cpu, 0)->ena;
1542 run = perf_counts(counter->counts, cpu, 0)->run;
1544 uval = val * counter->scale;
1545 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0,
1546 &rt_stat);
1548 fputc('\n', stat_config.output);
1552 static int aggr_header_lens[] = {
1553 [AGGR_CORE] = 18,
1554 [AGGR_SOCKET] = 12,
1555 [AGGR_NONE] = 6,
1556 [AGGR_THREAD] = 24,
1557 [AGGR_GLOBAL] = 0,
1560 static const char *aggr_header_csv[] = {
1561 [AGGR_CORE] = "core,cpus,",
1562 [AGGR_SOCKET] = "socket,cpus",
1563 [AGGR_NONE] = "cpu,",
1564 [AGGR_THREAD] = "comm-pid,",
1565 [AGGR_GLOBAL] = ""
1568 static void print_metric_headers(const char *prefix, bool no_indent)
1570 struct perf_stat_output_ctx out;
1571 struct perf_evsel *counter;
1572 struct outstate os = {
1573 .fh = stat_config.output
1576 if (prefix)
1577 fprintf(stat_config.output, "%s", prefix);
1579 if (!csv_output && !no_indent)
1580 fprintf(stat_config.output, "%*s",
1581 aggr_header_lens[stat_config.aggr_mode], "");
1582 if (csv_output) {
1583 if (stat_config.interval)
1584 fputs("time,", stat_config.output);
1585 fputs(aggr_header_csv[stat_config.aggr_mode],
1586 stat_config.output);
1589 /* Print metrics headers only */
1590 evlist__for_each_entry(evsel_list, counter) {
1591 if (is_duration_time(counter))
1592 continue;
1593 os.evsel = counter;
1594 out.ctx = &os;
1595 out.print_metric = print_metric_header;
1596 out.new_line = new_line_metric;
1597 out.force_header = true;
1598 os.evsel = counter;
1599 perf_stat__print_shadow_stats(counter, 0,
1601 &out,
1602 &metric_events,
1603 &rt_stat);
1605 fputc('\n', stat_config.output);
1608 static void print_interval(char *prefix, struct timespec *ts)
1610 FILE *output = stat_config.output;
1611 static int num_print_interval;
1613 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1615 if (num_print_interval == 0 && !csv_output) {
1616 switch (stat_config.aggr_mode) {
1617 case AGGR_SOCKET:
1618 fprintf(output, "# time socket cpus");
1619 if (!metric_only)
1620 fprintf(output, " counts %*s events\n", unit_width, "unit");
1621 break;
1622 case AGGR_CORE:
1623 fprintf(output, "# time core cpus");
1624 if (!metric_only)
1625 fprintf(output, " counts %*s events\n", unit_width, "unit");
1626 break;
1627 case AGGR_NONE:
1628 fprintf(output, "# time CPU");
1629 if (!metric_only)
1630 fprintf(output, " counts %*s events\n", unit_width, "unit");
1631 break;
1632 case AGGR_THREAD:
1633 fprintf(output, "# time comm-pid");
1634 if (!metric_only)
1635 fprintf(output, " counts %*s events\n", unit_width, "unit");
1636 break;
1637 case AGGR_GLOBAL:
1638 default:
1639 fprintf(output, "# time");
1640 if (!metric_only)
1641 fprintf(output, " counts %*s events\n", unit_width, "unit");
1642 case AGGR_UNSET:
1643 break;
1647 if (num_print_interval == 0 && metric_only)
1648 print_metric_headers(" ", true);
1649 if (++num_print_interval == 25)
1650 num_print_interval = 0;
1653 static void print_header(int argc, const char **argv)
1655 FILE *output = stat_config.output;
1656 int i;
1658 fflush(stdout);
1660 if (!csv_output) {
1661 fprintf(output, "\n");
1662 fprintf(output, " Performance counter stats for ");
1663 if (target.system_wide)
1664 fprintf(output, "\'system wide");
1665 else if (target.cpu_list)
1666 fprintf(output, "\'CPU(s) %s", target.cpu_list);
1667 else if (!target__has_task(&target)) {
1668 fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1669 for (i = 1; argv && (i < argc); i++)
1670 fprintf(output, " %s", argv[i]);
1671 } else if (target.pid)
1672 fprintf(output, "process id \'%s", target.pid);
1673 else
1674 fprintf(output, "thread id \'%s", target.tid);
1676 fprintf(output, "\'");
1677 if (run_count > 1)
1678 fprintf(output, " (%d runs)", run_count);
1679 fprintf(output, ":\n\n");
1683 static void print_footer(void)
1685 FILE *output = stat_config.output;
1686 int n;
1688 if (!null_run)
1689 fprintf(output, "\n");
1690 fprintf(output, " %17.9f seconds time elapsed",
1691 avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
1692 if (run_count > 1) {
1693 fprintf(output, " ");
1694 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1695 avg_stats(&walltime_nsecs_stats));
1697 fprintf(output, "\n\n");
1699 if (print_free_counters_hint &&
1700 sysctl__read_int("kernel/nmi_watchdog", &n) >= 0 &&
1701 n > 0)
1702 fprintf(output,
1703 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1704 " echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1705 " perf stat ...\n"
1706 " echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1709 static void print_counters(struct timespec *ts, int argc, const char **argv)
1711 int interval = stat_config.interval;
1712 struct perf_evsel *counter;
1713 char buf[64], *prefix = NULL;
1715 /* Do not print anything if we record to the pipe. */
1716 if (STAT_RECORD && perf_stat.data.is_pipe)
1717 return;
1719 if (interval)
1720 print_interval(prefix = buf, ts);
1721 else
1722 print_header(argc, argv);
1724 if (metric_only) {
1725 static int num_print_iv;
1727 if (num_print_iv == 0 && !interval)
1728 print_metric_headers(prefix, false);
1729 if (num_print_iv++ == 25)
1730 num_print_iv = 0;
1731 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1732 fprintf(stat_config.output, "%s", prefix);
1735 switch (stat_config.aggr_mode) {
1736 case AGGR_CORE:
1737 case AGGR_SOCKET:
1738 print_aggr(prefix);
1739 break;
1740 case AGGR_THREAD:
1741 evlist__for_each_entry(evsel_list, counter) {
1742 if (is_duration_time(counter))
1743 continue;
1744 print_aggr_thread(counter, prefix);
1746 break;
1747 case AGGR_GLOBAL:
1748 evlist__for_each_entry(evsel_list, counter) {
1749 if (is_duration_time(counter))
1750 continue;
1751 print_counter_aggr(counter, prefix);
1753 if (metric_only)
1754 fputc('\n', stat_config.output);
1755 break;
1756 case AGGR_NONE:
1757 if (metric_only)
1758 print_no_aggr_metric(prefix);
1759 else {
1760 evlist__for_each_entry(evsel_list, counter) {
1761 if (is_duration_time(counter))
1762 continue;
1763 print_counter(counter, prefix);
1766 break;
1767 case AGGR_UNSET:
1768 default:
1769 break;
1772 if (!interval && !csv_output)
1773 print_footer();
1775 fflush(stat_config.output);
1778 static volatile int signr = -1;
1780 static void skip_signal(int signo)
1782 if ((child_pid == -1) || stat_config.interval)
1783 done = 1;
1785 signr = signo;
1787 * render child_pid harmless
1788 * won't send SIGTERM to a random
1789 * process in case of race condition
1790 * and fast PID recycling
1792 child_pid = -1;
1795 static void sig_atexit(void)
1797 sigset_t set, oset;
1800 * avoid race condition with SIGCHLD handler
1801 * in skip_signal() which is modifying child_pid
1802 * goal is to avoid send SIGTERM to a random
1803 * process
1805 sigemptyset(&set);
1806 sigaddset(&set, SIGCHLD);
1807 sigprocmask(SIG_BLOCK, &set, &oset);
1809 if (child_pid != -1)
1810 kill(child_pid, SIGTERM);
1812 sigprocmask(SIG_SETMASK, &oset, NULL);
1814 if (signr == -1)
1815 return;
1817 signal(signr, SIG_DFL);
1818 kill(getpid(), signr);
1821 static int stat__set_big_num(const struct option *opt __maybe_unused,
1822 const char *s __maybe_unused, int unset)
1824 big_num_opt = unset ? 0 : 1;
1825 return 0;
1828 static int enable_metric_only(const struct option *opt __maybe_unused,
1829 const char *s __maybe_unused, int unset)
1831 force_metric_only = true;
1832 metric_only = !unset;
1833 return 0;
1836 static int parse_metric_groups(const struct option *opt,
1837 const char *str,
1838 int unset __maybe_unused)
1840 return metricgroup__parse_groups(opt, str, &metric_events);
1843 static const struct option stat_options[] = {
1844 OPT_BOOLEAN('T', "transaction", &transaction_run,
1845 "hardware transaction statistics"),
1846 OPT_CALLBACK('e', "event", &evsel_list, "event",
1847 "event selector. use 'perf list' to list available events",
1848 parse_events_option),
1849 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1850 "event filter", parse_filter),
1851 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1852 "child tasks do not inherit counters"),
1853 OPT_STRING('p', "pid", &target.pid, "pid",
1854 "stat events on existing process id"),
1855 OPT_STRING('t', "tid", &target.tid, "tid",
1856 "stat events on existing thread id"),
1857 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1858 "system-wide collection from all CPUs"),
1859 OPT_BOOLEAN('g', "group", &group,
1860 "put the counters into a counter group"),
1861 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1862 OPT_INCR('v', "verbose", &verbose,
1863 "be more verbose (show counter open errors, etc)"),
1864 OPT_INTEGER('r', "repeat", &run_count,
1865 "repeat command and print average + stddev (max: 100, forever: 0)"),
1866 OPT_BOOLEAN('n', "null", &null_run,
1867 "null run - dont start any counters"),
1868 OPT_INCR('d', "detailed", &detailed_run,
1869 "detailed run - start a lot of events"),
1870 OPT_BOOLEAN('S', "sync", &sync_run,
1871 "call sync() before starting a run"),
1872 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1873 "print large numbers with thousands\' separators",
1874 stat__set_big_num),
1875 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1876 "list of cpus to monitor in system-wide"),
1877 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1878 "disable CPU count aggregation", AGGR_NONE),
1879 OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
1880 OPT_STRING('x', "field-separator", &csv_sep, "separator",
1881 "print counts with custom separator"),
1882 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1883 "monitor event in cgroup name only", parse_cgroups),
1884 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1885 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1886 OPT_INTEGER(0, "log-fd", &output_fd,
1887 "log output to fd, instead of stderr"),
1888 OPT_STRING(0, "pre", &pre_cmd, "command",
1889 "command to run prior to the measured command"),
1890 OPT_STRING(0, "post", &post_cmd, "command",
1891 "command to run after to the measured command"),
1892 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1893 "print counts at regular interval in ms (>= 10)"),
1894 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1895 "aggregate counts per processor socket", AGGR_SOCKET),
1896 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1897 "aggregate counts per physical processor core", AGGR_CORE),
1898 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1899 "aggregate counts per thread", AGGR_THREAD),
1900 OPT_UINTEGER('D', "delay", &initial_delay,
1901 "ms to wait before starting measurement after program start"),
1902 OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
1903 "Only print computed metrics. No raw values", enable_metric_only),
1904 OPT_BOOLEAN(0, "topdown", &topdown_run,
1905 "measure topdown level 1 statistics"),
1906 OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1907 "measure SMI cost"),
1908 OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1909 "monitor specified metrics or metric groups (separated by ,)",
1910 parse_metric_groups),
1911 OPT_END()
1914 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1916 return cpu_map__get_socket(map, cpu, NULL);
1919 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1921 return cpu_map__get_core(map, cpu, NULL);
1924 static int cpu_map__get_max(struct cpu_map *map)
1926 int i, max = -1;
1928 for (i = 0; i < map->nr; i++) {
1929 if (map->map[i] > max)
1930 max = map->map[i];
1933 return max;
1936 static struct cpu_map *cpus_aggr_map;
1938 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1940 int cpu;
1942 if (idx >= map->nr)
1943 return -1;
1945 cpu = map->map[idx];
1947 if (cpus_aggr_map->map[cpu] == -1)
1948 cpus_aggr_map->map[cpu] = get_id(map, idx);
1950 return cpus_aggr_map->map[cpu];
1953 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1955 return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1958 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1960 return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1963 static int perf_stat_init_aggr_mode(void)
1965 int nr;
1967 switch (stat_config.aggr_mode) {
1968 case AGGR_SOCKET:
1969 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1970 perror("cannot build socket map");
1971 return -1;
1973 aggr_get_id = perf_stat__get_socket_cached;
1974 break;
1975 case AGGR_CORE:
1976 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1977 perror("cannot build core map");
1978 return -1;
1980 aggr_get_id = perf_stat__get_core_cached;
1981 break;
1982 case AGGR_NONE:
1983 case AGGR_GLOBAL:
1984 case AGGR_THREAD:
1985 case AGGR_UNSET:
1986 default:
1987 break;
1991 * The evsel_list->cpus is the base we operate on,
1992 * taking the highest cpu number to be the size of
1993 * the aggregation translate cpumap.
1995 nr = cpu_map__get_max(evsel_list->cpus);
1996 cpus_aggr_map = cpu_map__empty_new(nr + 1);
1997 return cpus_aggr_map ? 0 : -ENOMEM;
2000 static void perf_stat__exit_aggr_mode(void)
2002 cpu_map__put(aggr_map);
2003 cpu_map__put(cpus_aggr_map);
2004 aggr_map = NULL;
2005 cpus_aggr_map = NULL;
2008 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
2010 int cpu;
2012 if (idx > map->nr)
2013 return -1;
2015 cpu = map->map[idx];
2017 if (cpu >= env->nr_cpus_avail)
2018 return -1;
2020 return cpu;
2023 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
2025 struct perf_env *env = data;
2026 int cpu = perf_env__get_cpu(env, map, idx);
2028 return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
2031 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
2033 struct perf_env *env = data;
2034 int core = -1, cpu = perf_env__get_cpu(env, map, idx);
2036 if (cpu != -1) {
2037 int socket_id = env->cpu[cpu].socket_id;
2040 * Encode socket in upper 16 bits
2041 * core_id is relative to socket, and
2042 * we need a global id. So we combine
2043 * socket + core id.
2045 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
2048 return core;
2051 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
2052 struct cpu_map **sockp)
2054 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
2057 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
2058 struct cpu_map **corep)
2060 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
2063 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
2065 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
2068 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
2070 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
2073 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
2075 struct perf_env *env = &st->session->header.env;
2077 switch (stat_config.aggr_mode) {
2078 case AGGR_SOCKET:
2079 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
2080 perror("cannot build socket map");
2081 return -1;
2083 aggr_get_id = perf_stat__get_socket_file;
2084 break;
2085 case AGGR_CORE:
2086 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
2087 perror("cannot build core map");
2088 return -1;
2090 aggr_get_id = perf_stat__get_core_file;
2091 break;
2092 case AGGR_NONE:
2093 case AGGR_GLOBAL:
2094 case AGGR_THREAD:
2095 case AGGR_UNSET:
2096 default:
2097 break;
2100 return 0;
2103 static int topdown_filter_events(const char **attr, char **str, bool use_group)
2105 int off = 0;
2106 int i;
2107 int len = 0;
2108 char *s;
2110 for (i = 0; attr[i]; i++) {
2111 if (pmu_have_event("cpu", attr[i])) {
2112 len += strlen(attr[i]) + 1;
2113 attr[i - off] = attr[i];
2114 } else
2115 off++;
2117 attr[i - off] = NULL;
2119 *str = malloc(len + 1 + 2);
2120 if (!*str)
2121 return -1;
2122 s = *str;
2123 if (i - off == 0) {
2124 *s = 0;
2125 return 0;
2127 if (use_group)
2128 *s++ = '{';
2129 for (i = 0; attr[i]; i++) {
2130 strcpy(s, attr[i]);
2131 s += strlen(s);
2132 *s++ = ',';
2134 if (use_group) {
2135 s[-1] = '}';
2136 *s = 0;
2137 } else
2138 s[-1] = 0;
2139 return 0;
2142 __weak bool arch_topdown_check_group(bool *warn)
2144 *warn = false;
2145 return false;
2148 __weak void arch_topdown_group_warn(void)
2153 * Add default attributes, if there were no attributes specified or
2154 * if -d/--detailed, -d -d or -d -d -d is used:
2156 static int add_default_attributes(void)
2158 int err;
2159 struct perf_event_attr default_attrs0[] = {
2161 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
2162 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
2163 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
2164 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
2166 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
2168 struct perf_event_attr frontend_attrs[] = {
2169 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
2171 struct perf_event_attr backend_attrs[] = {
2172 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
2174 struct perf_event_attr default_attrs1[] = {
2175 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
2176 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
2177 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
2182 * Detailed stats (-d), covering the L1 and last level data caches:
2184 struct perf_event_attr detailed_attrs[] = {
2186 { .type = PERF_TYPE_HW_CACHE,
2187 .config =
2188 PERF_COUNT_HW_CACHE_L1D << 0 |
2189 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2190 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2192 { .type = PERF_TYPE_HW_CACHE,
2193 .config =
2194 PERF_COUNT_HW_CACHE_L1D << 0 |
2195 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2196 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2198 { .type = PERF_TYPE_HW_CACHE,
2199 .config =
2200 PERF_COUNT_HW_CACHE_LL << 0 |
2201 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2202 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2204 { .type = PERF_TYPE_HW_CACHE,
2205 .config =
2206 PERF_COUNT_HW_CACHE_LL << 0 |
2207 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2208 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2212 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2214 struct perf_event_attr very_detailed_attrs[] = {
2216 { .type = PERF_TYPE_HW_CACHE,
2217 .config =
2218 PERF_COUNT_HW_CACHE_L1I << 0 |
2219 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2220 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2222 { .type = PERF_TYPE_HW_CACHE,
2223 .config =
2224 PERF_COUNT_HW_CACHE_L1I << 0 |
2225 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2226 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2228 { .type = PERF_TYPE_HW_CACHE,
2229 .config =
2230 PERF_COUNT_HW_CACHE_DTLB << 0 |
2231 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2232 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2234 { .type = PERF_TYPE_HW_CACHE,
2235 .config =
2236 PERF_COUNT_HW_CACHE_DTLB << 0 |
2237 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2238 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2240 { .type = PERF_TYPE_HW_CACHE,
2241 .config =
2242 PERF_COUNT_HW_CACHE_ITLB << 0 |
2243 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2244 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2246 { .type = PERF_TYPE_HW_CACHE,
2247 .config =
2248 PERF_COUNT_HW_CACHE_ITLB << 0 |
2249 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2250 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2255 * Very, very detailed stats (-d -d -d), adding prefetch events:
2257 struct perf_event_attr very_very_detailed_attrs[] = {
2259 { .type = PERF_TYPE_HW_CACHE,
2260 .config =
2261 PERF_COUNT_HW_CACHE_L1D << 0 |
2262 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2263 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2265 { .type = PERF_TYPE_HW_CACHE,
2266 .config =
2267 PERF_COUNT_HW_CACHE_L1D << 0 |
2268 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2269 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2272 /* Set attrs if no event is selected and !null_run: */
2273 if (null_run)
2274 return 0;
2276 if (transaction_run) {
2277 if (pmu_have_event("cpu", "cycles-ct") &&
2278 pmu_have_event("cpu", "el-start"))
2279 err = parse_events(evsel_list, transaction_attrs, NULL);
2280 else
2281 err = parse_events(evsel_list, transaction_limited_attrs, NULL);
2282 if (err) {
2283 fprintf(stderr, "Cannot set up transaction events\n");
2284 return -1;
2286 return 0;
2289 if (smi_cost) {
2290 int smi;
2292 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
2293 fprintf(stderr, "freeze_on_smi is not supported.\n");
2294 return -1;
2297 if (!smi) {
2298 if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
2299 fprintf(stderr, "Failed to set freeze_on_smi.\n");
2300 return -1;
2302 smi_reset = true;
2305 if (pmu_have_event("msr", "aperf") &&
2306 pmu_have_event("msr", "smi")) {
2307 if (!force_metric_only)
2308 metric_only = true;
2309 err = parse_events(evsel_list, smi_cost_attrs, NULL);
2310 } else {
2311 fprintf(stderr, "To measure SMI cost, it needs "
2312 "msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
2313 return -1;
2315 if (err) {
2316 fprintf(stderr, "Cannot set up SMI cost events\n");
2317 return -1;
2319 return 0;
2322 if (topdown_run) {
2323 char *str = NULL;
2324 bool warn = false;
2326 if (stat_config.aggr_mode != AGGR_GLOBAL &&
2327 stat_config.aggr_mode != AGGR_CORE) {
2328 pr_err("top down event configuration requires --per-core mode\n");
2329 return -1;
2331 stat_config.aggr_mode = AGGR_CORE;
2332 if (nr_cgroups || !target__has_cpu(&target)) {
2333 pr_err("top down event configuration requires system-wide mode (-a)\n");
2334 return -1;
2337 if (!force_metric_only)
2338 metric_only = true;
2339 if (topdown_filter_events(topdown_attrs, &str,
2340 arch_topdown_check_group(&warn)) < 0) {
2341 pr_err("Out of memory\n");
2342 return -1;
2344 if (topdown_attrs[0] && str) {
2345 if (warn)
2346 arch_topdown_group_warn();
2347 err = parse_events(evsel_list, str, NULL);
2348 if (err) {
2349 fprintf(stderr,
2350 "Cannot set up top down events %s: %d\n",
2351 str, err);
2352 free(str);
2353 return -1;
2355 } else {
2356 fprintf(stderr, "System does not support topdown\n");
2357 return -1;
2359 free(str);
2362 if (!evsel_list->nr_entries) {
2363 if (target__has_cpu(&target))
2364 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2366 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2367 return -1;
2368 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2369 if (perf_evlist__add_default_attrs(evsel_list,
2370 frontend_attrs) < 0)
2371 return -1;
2373 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2374 if (perf_evlist__add_default_attrs(evsel_list,
2375 backend_attrs) < 0)
2376 return -1;
2378 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2379 return -1;
2382 /* Detailed events get appended to the event list: */
2384 if (detailed_run < 1)
2385 return 0;
2387 /* Append detailed run extra attributes: */
2388 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2389 return -1;
2391 if (detailed_run < 2)
2392 return 0;
2394 /* Append very detailed run extra attributes: */
2395 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2396 return -1;
2398 if (detailed_run < 3)
2399 return 0;
2401 /* Append very, very detailed run extra attributes: */
2402 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2405 static const char * const stat_record_usage[] = {
2406 "perf stat record [<options>]",
2407 NULL,
2410 static void init_features(struct perf_session *session)
2412 int feat;
2414 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2415 perf_header__set_feat(&session->header, feat);
2417 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2418 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2419 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2420 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2423 static int __cmd_record(int argc, const char **argv)
2425 struct perf_session *session;
2426 struct perf_data *data = &perf_stat.data;
2428 argc = parse_options(argc, argv, stat_options, stat_record_usage,
2429 PARSE_OPT_STOP_AT_NON_OPTION);
2431 if (output_name)
2432 data->file.path = output_name;
2434 if (run_count != 1 || forever) {
2435 pr_err("Cannot use -r option with perf stat record.\n");
2436 return -1;
2439 session = perf_session__new(data, false, NULL);
2440 if (session == NULL) {
2441 pr_err("Perf session creation failed.\n");
2442 return -1;
2445 init_features(session);
2447 session->evlist = evsel_list;
2448 perf_stat.session = session;
2449 perf_stat.record = true;
2450 return argc;
2453 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2454 union perf_event *event,
2455 struct perf_session *session)
2457 struct stat_round_event *stat_round = &event->stat_round;
2458 struct perf_evsel *counter;
2459 struct timespec tsh, *ts = NULL;
2460 const char **argv = session->header.env.cmdline_argv;
2461 int argc = session->header.env.nr_cmdline;
2463 evlist__for_each_entry(evsel_list, counter)
2464 perf_stat_process_counter(&stat_config, counter);
2466 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2467 update_stats(&walltime_nsecs_stats, stat_round->time);
2469 if (stat_config.interval && stat_round->time) {
2470 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2471 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2472 ts = &tsh;
2475 print_counters(ts, argc, argv);
2476 return 0;
2479 static
2480 int process_stat_config_event(struct perf_tool *tool,
2481 union perf_event *event,
2482 struct perf_session *session __maybe_unused)
2484 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2486 perf_event__read_stat_config(&stat_config, &event->stat_config);
2488 if (cpu_map__empty(st->cpus)) {
2489 if (st->aggr_mode != AGGR_UNSET)
2490 pr_warning("warning: processing task data, aggregation mode not set\n");
2491 return 0;
2494 if (st->aggr_mode != AGGR_UNSET)
2495 stat_config.aggr_mode = st->aggr_mode;
2497 if (perf_stat.data.is_pipe)
2498 perf_stat_init_aggr_mode();
2499 else
2500 perf_stat_init_aggr_mode_file(st);
2502 return 0;
2505 static int set_maps(struct perf_stat *st)
2507 if (!st->cpus || !st->threads)
2508 return 0;
2510 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2511 return -EINVAL;
2513 perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2515 if (perf_evlist__alloc_stats(evsel_list, true))
2516 return -ENOMEM;
2518 st->maps_allocated = true;
2519 return 0;
2522 static
2523 int process_thread_map_event(struct perf_tool *tool,
2524 union perf_event *event,
2525 struct perf_session *session __maybe_unused)
2527 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2529 if (st->threads) {
2530 pr_warning("Extra thread map event, ignoring.\n");
2531 return 0;
2534 st->threads = thread_map__new_event(&event->thread_map);
2535 if (!st->threads)
2536 return -ENOMEM;
2538 return set_maps(st);
2541 static
2542 int process_cpu_map_event(struct perf_tool *tool,
2543 union perf_event *event,
2544 struct perf_session *session __maybe_unused)
2546 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2547 struct cpu_map *cpus;
2549 if (st->cpus) {
2550 pr_warning("Extra cpu map event, ignoring.\n");
2551 return 0;
2554 cpus = cpu_map__new_data(&event->cpu_map.data);
2555 if (!cpus)
2556 return -ENOMEM;
2558 st->cpus = cpus;
2559 return set_maps(st);
2562 static int runtime_stat_new(struct perf_stat_config *config, int nthreads)
2564 int i;
2566 config->stats = calloc(nthreads, sizeof(struct runtime_stat));
2567 if (!config->stats)
2568 return -1;
2570 config->stats_num = nthreads;
2572 for (i = 0; i < nthreads; i++)
2573 runtime_stat__init(&config->stats[i]);
2575 return 0;
2578 static void runtime_stat_delete(struct perf_stat_config *config)
2580 int i;
2582 if (!config->stats)
2583 return;
2585 for (i = 0; i < config->stats_num; i++)
2586 runtime_stat__exit(&config->stats[i]);
2588 free(config->stats);
2591 static const char * const stat_report_usage[] = {
2592 "perf stat report [<options>]",
2593 NULL,
2596 static struct perf_stat perf_stat = {
2597 .tool = {
2598 .attr = perf_event__process_attr,
2599 .event_update = perf_event__process_event_update,
2600 .thread_map = process_thread_map_event,
2601 .cpu_map = process_cpu_map_event,
2602 .stat_config = process_stat_config_event,
2603 .stat = perf_event__process_stat_event,
2604 .stat_round = process_stat_round_event,
2606 .aggr_mode = AGGR_UNSET,
2609 static int __cmd_report(int argc, const char **argv)
2611 struct perf_session *session;
2612 const struct option options[] = {
2613 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2614 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2615 "aggregate counts per processor socket", AGGR_SOCKET),
2616 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2617 "aggregate counts per physical processor core", AGGR_CORE),
2618 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2619 "disable CPU count aggregation", AGGR_NONE),
2620 OPT_END()
2622 struct stat st;
2623 int ret;
2625 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2627 if (!input_name || !strlen(input_name)) {
2628 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2629 input_name = "-";
2630 else
2631 input_name = "perf.data";
2634 perf_stat.data.file.path = input_name;
2635 perf_stat.data.mode = PERF_DATA_MODE_READ;
2637 session = perf_session__new(&perf_stat.data, false, &perf_stat.tool);
2638 if (session == NULL)
2639 return -1;
2641 perf_stat.session = session;
2642 stat_config.output = stderr;
2643 evsel_list = session->evlist;
2645 ret = perf_session__process_events(session);
2646 if (ret)
2647 return ret;
2649 perf_session__delete(session);
2650 return 0;
2653 static void setup_system_wide(int forks)
2656 * Make system wide (-a) the default target if
2657 * no target was specified and one of following
2658 * conditions is met:
2660 * - there's no workload specified
2661 * - there is workload specified but all requested
2662 * events are system wide events
2664 if (!target__none(&target))
2665 return;
2667 if (!forks)
2668 target.system_wide = true;
2669 else {
2670 struct perf_evsel *counter;
2672 evlist__for_each_entry(evsel_list, counter) {
2673 if (!counter->system_wide)
2674 return;
2677 if (evsel_list->nr_entries)
2678 target.system_wide = true;
2682 int cmd_stat(int argc, const char **argv)
2684 const char * const stat_usage[] = {
2685 "perf stat [<options>] [<command>]",
2686 NULL
2688 int status = -EINVAL, run_idx;
2689 const char *mode;
2690 FILE *output = stderr;
2691 unsigned int interval;
2692 const char * const stat_subcommands[] = { "record", "report" };
2694 setlocale(LC_ALL, "");
2696 evsel_list = perf_evlist__new();
2697 if (evsel_list == NULL)
2698 return -ENOMEM;
2700 parse_events__shrink_config_terms();
2701 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2702 (const char **) stat_usage,
2703 PARSE_OPT_STOP_AT_NON_OPTION);
2704 perf_stat__collect_metric_expr(evsel_list);
2705 perf_stat__init_shadow_stats();
2707 if (csv_sep) {
2708 csv_output = true;
2709 if (!strcmp(csv_sep, "\\t"))
2710 csv_sep = "\t";
2711 } else
2712 csv_sep = DEFAULT_SEPARATOR;
2714 if (argc && !strncmp(argv[0], "rec", 3)) {
2715 argc = __cmd_record(argc, argv);
2716 if (argc < 0)
2717 return -1;
2718 } else if (argc && !strncmp(argv[0], "rep", 3))
2719 return __cmd_report(argc, argv);
2721 interval = stat_config.interval;
2724 * For record command the -o is already taken care of.
2726 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2727 output = NULL;
2729 if (output_name && output_fd) {
2730 fprintf(stderr, "cannot use both --output and --log-fd\n");
2731 parse_options_usage(stat_usage, stat_options, "o", 1);
2732 parse_options_usage(NULL, stat_options, "log-fd", 0);
2733 goto out;
2736 if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2737 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2738 goto out;
2741 if (metric_only && run_count > 1) {
2742 fprintf(stderr, "--metric-only is not supported with -r\n");
2743 goto out;
2746 if (output_fd < 0) {
2747 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2748 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2749 goto out;
2752 if (!output) {
2753 struct timespec tm;
2754 mode = append_file ? "a" : "w";
2756 output = fopen(output_name, mode);
2757 if (!output) {
2758 perror("failed to create output file");
2759 return -1;
2761 clock_gettime(CLOCK_REALTIME, &tm);
2762 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2763 } else if (output_fd > 0) {
2764 mode = append_file ? "a" : "w";
2765 output = fdopen(output_fd, mode);
2766 if (!output) {
2767 perror("Failed opening logfd");
2768 return -errno;
2772 stat_config.output = output;
2775 * let the spreadsheet do the pretty-printing
2777 if (csv_output) {
2778 /* User explicitly passed -B? */
2779 if (big_num_opt == 1) {
2780 fprintf(stderr, "-B option not supported with -x\n");
2781 parse_options_usage(stat_usage, stat_options, "B", 1);
2782 parse_options_usage(NULL, stat_options, "x", 1);
2783 goto out;
2784 } else /* Nope, so disable big number formatting */
2785 big_num = false;
2786 } else if (big_num_opt == 0) /* User passed --no-big-num */
2787 big_num = false;
2789 setup_system_wide(argc);
2791 if (run_count < 0) {
2792 pr_err("Run count must be a positive number\n");
2793 parse_options_usage(stat_usage, stat_options, "r", 1);
2794 goto out;
2795 } else if (run_count == 0) {
2796 forever = true;
2797 run_count = 1;
2800 if ((stat_config.aggr_mode == AGGR_THREAD) &&
2801 !target__has_task(&target)) {
2802 if (!target.system_wide || target.cpu_list) {
2803 fprintf(stderr, "The --per-thread option is only "
2804 "available when monitoring via -p -t -a "
2805 "options or only --per-thread.\n");
2806 parse_options_usage(NULL, stat_options, "p", 1);
2807 parse_options_usage(NULL, stat_options, "t", 1);
2808 goto out;
2813 * no_aggr, cgroup are for system-wide only
2814 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2816 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2817 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2818 !target__has_cpu(&target)) {
2819 fprintf(stderr, "both cgroup and no-aggregation "
2820 "modes only available in system-wide mode\n");
2822 parse_options_usage(stat_usage, stat_options, "G", 1);
2823 parse_options_usage(NULL, stat_options, "A", 1);
2824 parse_options_usage(NULL, stat_options, "a", 1);
2825 goto out;
2828 if (add_default_attributes())
2829 goto out;
2831 target__validate(&target);
2833 if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2834 target.per_thread = true;
2836 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2837 if (target__has_task(&target)) {
2838 pr_err("Problems finding threads of monitor\n");
2839 parse_options_usage(stat_usage, stat_options, "p", 1);
2840 parse_options_usage(NULL, stat_options, "t", 1);
2841 } else if (target__has_cpu(&target)) {
2842 perror("failed to parse CPUs map");
2843 parse_options_usage(stat_usage, stat_options, "C", 1);
2844 parse_options_usage(NULL, stat_options, "a", 1);
2846 goto out;
2850 * Initialize thread_map with comm names,
2851 * so we could print it out on output.
2853 if (stat_config.aggr_mode == AGGR_THREAD) {
2854 thread_map__read_comms(evsel_list->threads);
2855 if (target.system_wide) {
2856 if (runtime_stat_new(&stat_config,
2857 thread_map__nr(evsel_list->threads))) {
2858 goto out;
2863 if (interval && interval < 100) {
2864 if (interval < 10) {
2865 pr_err("print interval must be >= 10ms\n");
2866 parse_options_usage(stat_usage, stat_options, "I", 1);
2867 goto out;
2868 } else
2869 pr_warning("print interval < 100ms. "
2870 "The overhead percentage could be high in some cases. "
2871 "Please proceed with caution.\n");
2874 if (perf_evlist__alloc_stats(evsel_list, interval))
2875 goto out;
2877 if (perf_stat_init_aggr_mode())
2878 goto out;
2881 * We dont want to block the signals - that would cause
2882 * child tasks to inherit that and Ctrl-C would not work.
2883 * What we want is for Ctrl-C to work in the exec()-ed
2884 * task, but being ignored by perf stat itself:
2886 atexit(sig_atexit);
2887 if (!forever)
2888 signal(SIGINT, skip_signal);
2889 signal(SIGCHLD, skip_signal);
2890 signal(SIGALRM, skip_signal);
2891 signal(SIGABRT, skip_signal);
2893 status = 0;
2894 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2895 if (run_count != 1 && verbose > 0)
2896 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2897 run_idx + 1);
2899 status = run_perf_stat(argc, argv);
2900 if (forever && status != -1) {
2901 print_counters(NULL, argc, argv);
2902 perf_stat__reset_stats();
2906 if (!forever && status != -1 && !interval)
2907 print_counters(NULL, argc, argv);
2909 if (STAT_RECORD) {
2911 * We synthesize the kernel mmap record just so that older tools
2912 * don't emit warnings about not being able to resolve symbols
2913 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2914 * a saner message about no samples being in the perf.data file.
2916 * This also serves to suppress a warning about f_header.data.size == 0
2917 * in header.c at the moment 'perf stat record' gets introduced, which
2918 * is not really needed once we start adding the stat specific PERF_RECORD_
2919 * records, but the need to suppress the kptr_restrict messages in older
2920 * tools remain -acme
2922 int fd = perf_data__fd(&perf_stat.data);
2923 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2924 process_synthesized_event,
2925 &perf_stat.session->machines.host);
2926 if (err) {
2927 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2928 "older tools may produce warnings about this file\n.");
2931 if (!interval) {
2932 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2933 pr_err("failed to write stat round event\n");
2936 if (!perf_stat.data.is_pipe) {
2937 perf_stat.session->header.data_size += perf_stat.bytes_written;
2938 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2941 perf_session__delete(perf_stat.session);
2944 perf_stat__exit_aggr_mode();
2945 perf_evlist__free_stats(evsel_list);
2946 out:
2947 if (smi_cost && smi_reset)
2948 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2950 perf_evlist__delete(evsel_list);
2952 runtime_stat_delete(&stat_config);
2954 return status;