4 * Builtin stat command: Give a precise performance counters summary
5 * overview about any workload, CPU or specific PID.
9 $ perf stat ./hackbench 10
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)
46 #include "util/cgroup.h"
47 #include "util/util.h"
48 #include <subcmd/parse-options.h>
49 #include "util/parse-events.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"
70 #include <linux/time64.h>
71 #include <api/fs/fs.h>
73 #include <sys/prctl.h>
78 #include "sane_ctype.h"
80 #define DEFAULT_SEPARATOR " "
81 #define CNTR_NOT_SUPPORTED "<not supported>"
82 #define CNTR_NOT_COUNTED "<not counted>"
84 static void print_counters(struct timespec *ts, int argc, const char **argv);
86 /* Default events used for perf stat -T */
87 static const char *transaction_attrs = {
99 /* More limited version when the CPU does not have all events. */
100 static const char * transaction_limited_attrs = {
110 static const char * topdown_attrs[] = {
111 "topdown-total-slots",
112 "topdown-slots-retired",
113 "topdown-recovery-bubbles",
114 "topdown-fetch-bubbles",
115 "topdown-slots-issued",
119 static struct perf_evlist *evsel_list;
121 static struct target target = {
125 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
127 static int run_count = 1;
128 static bool no_inherit = false;
129 static volatile pid_t child_pid = -1;
130 static bool null_run = false;
131 static int detailed_run = 0;
132 static bool transaction_run;
133 static bool topdown_run = false;
134 static bool big_num = true;
135 static int big_num_opt = -1;
136 static const char *csv_sep = NULL;
137 static bool csv_output = false;
138 static bool group = false;
139 static const char *pre_cmd = NULL;
140 static const char *post_cmd = NULL;
141 static bool sync_run = false;
142 static unsigned int initial_delay = 0;
143 static unsigned int unit_width = 4; /* strlen("unit") */
144 static bool forever = false;
145 static bool metric_only = false;
146 static bool force_metric_only = false;
147 static bool no_merge = false;
148 static struct timespec ref_time;
149 static struct cpu_map *aggr_map;
150 static aggr_get_id_t aggr_get_id;
151 static bool append_file;
152 static const char *output_name;
153 static int output_fd;
154 static int print_free_counters_hint;
158 struct perf_data_file file;
159 struct perf_session *session;
161 struct perf_tool tool;
163 struct cpu_map *cpus;
164 struct thread_map *threads;
165 enum aggr_mode aggr_mode;
168 static struct perf_stat perf_stat;
169 #define STAT_RECORD perf_stat.record
171 static volatile int done = 0;
173 static struct perf_stat_config stat_config = {
174 .aggr_mode = AGGR_GLOBAL,
178 static inline void diff_timespec(struct timespec *r, struct timespec *a,
181 r->tv_sec = a->tv_sec - b->tv_sec;
182 if (a->tv_nsec < b->tv_nsec) {
183 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
186 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
190 static void perf_stat__reset_stats(void)
192 perf_evlist__reset_stats(evsel_list);
193 perf_stat__reset_shadow_stats();
196 static int create_perf_stat_counter(struct perf_evsel *evsel)
198 struct perf_event_attr *attr = &evsel->attr;
200 if (stat_config.scale)
201 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
202 PERF_FORMAT_TOTAL_TIME_RUNNING;
204 attr->inherit = !no_inherit;
207 * Some events get initialized with sample_(period/type) set,
208 * like tracepoints. Clear it up for counting.
210 attr->sample_period = 0;
213 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
214 * while avoiding that older tools show confusing messages.
216 * However for pipe sessions we need to keep it zero,
217 * because script's perf_evsel__check_attr is triggered
218 * by attr->sample_type != 0, and we can't run it on
221 if (!(STAT_RECORD && perf_stat.file.is_pipe))
222 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
225 * Disabling all counters initially, they will be enabled
226 * either manually by us or by kernel via enable_on_exec
229 if (perf_evsel__is_group_leader(evsel)) {
233 * In case of initial_delay we enable tracee
236 if (target__none(&target) && !initial_delay)
237 attr->enable_on_exec = 1;
240 if (target__has_cpu(&target))
241 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
243 return perf_evsel__open_per_thread(evsel, evsel_list->threads);
247 * Does the counter have nsecs as a unit?
249 static inline int nsec_counter(struct perf_evsel *evsel)
251 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
252 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
258 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
259 union perf_event *event,
260 struct perf_sample *sample __maybe_unused,
261 struct machine *machine __maybe_unused)
263 if (perf_data_file__write(&perf_stat.file, event, event->header.size) < 0) {
264 pr_err("failed to write perf data, error: %m\n");
268 perf_stat.bytes_written += event->header.size;
272 static int write_stat_round_event(u64 tm, u64 type)
274 return perf_event__synthesize_stat_round(NULL, tm, type,
275 process_synthesized_event,
279 #define WRITE_STAT_ROUND_EVENT(time, interval) \
280 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
282 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
285 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
286 struct perf_counts_values *count)
288 struct perf_sample_id *sid = SID(counter, cpu, thread);
290 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
291 process_synthesized_event, NULL);
295 * Read out the results of a single counter:
296 * do not aggregate counts across CPUs in system-wide mode
298 static int read_counter(struct perf_evsel *counter)
300 int nthreads = thread_map__nr(evsel_list->threads);
301 int ncpus, cpu, thread;
303 if (target__has_cpu(&target))
304 ncpus = perf_evsel__nr_cpus(counter);
308 if (!counter->supported)
311 if (counter->system_wide)
314 for (thread = 0; thread < nthreads; thread++) {
315 for (cpu = 0; cpu < ncpus; cpu++) {
316 struct perf_counts_values *count;
318 count = perf_counts(counter->counts, cpu, thread);
319 if (perf_evsel__read(counter, cpu, thread, count)) {
320 counter->counts->scaled = -1;
321 perf_counts(counter->counts, cpu, thread)->ena = 0;
322 perf_counts(counter->counts, cpu, thread)->run = 0;
327 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
328 pr_err("failed to write stat event\n");
334 fprintf(stat_config.output,
335 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
336 perf_evsel__name(counter),
338 count->val, count->ena, count->run);
346 static void read_counters(void)
348 struct perf_evsel *counter;
351 evlist__for_each_entry(evsel_list, counter) {
352 ret = read_counter(counter);
354 pr_debug("failed to read counter %s\n", counter->name);
356 if (ret == 0 && perf_stat_process_counter(&stat_config, counter))
357 pr_warning("failed to process counter %s\n", counter->name);
361 static void process_interval(void)
363 struct timespec ts, rs;
367 clock_gettime(CLOCK_MONOTONIC, &ts);
368 diff_timespec(&rs, &ts, &ref_time);
371 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
372 pr_err("failed to write stat round event\n");
375 print_counters(&rs, 0, NULL);
378 static void enable_counters(void)
381 usleep(initial_delay * USEC_PER_MSEC);
384 * We need to enable counters only if:
385 * - we don't have tracee (attaching to task or cpu)
386 * - we have initial delay configured
388 if (!target__none(&target) || initial_delay)
389 perf_evlist__enable(evsel_list);
392 static void disable_counters(void)
395 * If we don't have tracee (attaching to task or cpu), counters may
396 * still be running. To get accurate group ratios, we must stop groups
397 * from counting before reading their constituent counters.
399 if (!target__none(&target))
400 perf_evlist__disable(evsel_list);
403 static volatile int workload_exec_errno;
406 * perf_evlist__prepare_workload will send a SIGUSR1
407 * if the fork fails, since we asked by setting its
408 * want_signal to true.
410 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
411 void *ucontext __maybe_unused)
413 workload_exec_errno = info->si_value.sival_int;
416 static bool has_unit(struct perf_evsel *counter)
418 return counter->unit && *counter->unit;
421 static bool has_scale(struct perf_evsel *counter)
423 return counter->scale != 1;
426 static int perf_stat_synthesize_config(bool is_pipe)
428 struct perf_evsel *counter;
432 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
433 process_synthesized_event);
435 pr_err("Couldn't synthesize attrs.\n");
441 * Synthesize other events stuff not carried within
442 * attr event - unit, scale, name
444 evlist__for_each_entry(evsel_list, counter) {
445 if (!counter->supported)
449 * Synthesize unit and scale only if it's defined.
451 if (has_unit(counter)) {
452 err = perf_event__synthesize_event_update_unit(NULL, counter, process_synthesized_event);
454 pr_err("Couldn't synthesize evsel unit.\n");
459 if (has_scale(counter)) {
460 err = perf_event__synthesize_event_update_scale(NULL, counter, process_synthesized_event);
462 pr_err("Couldn't synthesize evsel scale.\n");
467 if (counter->own_cpus) {
468 err = perf_event__synthesize_event_update_cpus(NULL, counter, process_synthesized_event);
470 pr_err("Couldn't synthesize evsel scale.\n");
476 * Name is needed only for pipe output,
477 * perf.data carries event names.
480 err = perf_event__synthesize_event_update_name(NULL, counter, process_synthesized_event);
482 pr_err("Couldn't synthesize evsel name.\n");
488 err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
489 process_synthesized_event,
492 pr_err("Couldn't synthesize thread map.\n");
496 err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
497 process_synthesized_event, NULL);
499 pr_err("Couldn't synthesize thread map.\n");
503 err = perf_event__synthesize_stat_config(NULL, &stat_config,
504 process_synthesized_event, NULL);
506 pr_err("Couldn't synthesize config.\n");
513 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
515 static int __store_counter_ids(struct perf_evsel *counter,
516 struct cpu_map *cpus,
517 struct thread_map *threads)
521 for (cpu = 0; cpu < cpus->nr; cpu++) {
522 for (thread = 0; thread < threads->nr; thread++) {
523 int fd = FD(counter, cpu, thread);
525 if (perf_evlist__id_add_fd(evsel_list, counter,
526 cpu, thread, fd) < 0)
534 static int store_counter_ids(struct perf_evsel *counter)
536 struct cpu_map *cpus = counter->cpus;
537 struct thread_map *threads = counter->threads;
539 if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
542 return __store_counter_ids(counter, cpus, threads);
545 static int __run_perf_stat(int argc, const char **argv)
547 int interval = stat_config.interval;
549 unsigned long long t0, t1;
550 struct perf_evsel *counter;
554 const bool forks = (argc > 0);
555 bool is_pipe = STAT_RECORD ? perf_stat.file.is_pipe : false;
556 struct perf_evsel_config_term *err_term;
559 ts.tv_sec = interval / USEC_PER_MSEC;
560 ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
567 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
568 workload_exec_failed_signal) < 0) {
569 perror("failed to prepare workload");
572 child_pid = evsel_list->workload.pid;
576 perf_evlist__set_leader(evsel_list);
578 evlist__for_each_entry(evsel_list, counter) {
580 if (create_perf_stat_counter(counter) < 0) {
582 * PPC returns ENXIO for HW counters until 2.6.37
583 * (behavior changed with commit b0a873e).
585 if (errno == EINVAL || errno == ENOSYS ||
586 errno == ENOENT || errno == EOPNOTSUPP ||
589 ui__warning("%s event is not supported by the kernel.\n",
590 perf_evsel__name(counter));
591 counter->supported = false;
593 if ((counter->leader != counter) ||
594 !(counter->leader->nr_members > 1))
596 } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
598 ui__warning("%s\n", msg);
602 perf_evsel__open_strerror(counter, &target,
603 errno, msg, sizeof(msg));
604 ui__error("%s\n", msg);
607 kill(child_pid, SIGTERM);
611 counter->supported = true;
613 l = strlen(counter->unit);
617 if (STAT_RECORD && store_counter_ids(counter))
621 if (perf_evlist__apply_filters(evsel_list, &counter)) {
622 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
623 counter->filter, perf_evsel__name(counter), errno,
624 str_error_r(errno, msg, sizeof(msg)));
628 if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
629 error("failed to set config \"%s\" on event %s with %d (%s)\n",
630 err_term->val.drv_cfg, perf_evsel__name(counter), errno,
631 str_error_r(errno, msg, sizeof(msg)));
636 int err, fd = perf_data_file__fd(&perf_stat.file);
639 err = perf_header__write_pipe(perf_data_file__fd(&perf_stat.file));
641 err = perf_session__write_header(perf_stat.session, evsel_list,
648 err = perf_stat_synthesize_config(is_pipe);
654 * Enable counters and exec the command:
657 clock_gettime(CLOCK_MONOTONIC, &ref_time);
660 perf_evlist__start_workload(evsel_list);
664 while (!waitpid(child_pid, &status, WNOHANG)) {
665 nanosleep(&ts, NULL);
671 if (workload_exec_errno) {
672 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
673 pr_err("Workload failed: %s\n", emsg);
677 if (WIFSIGNALED(status))
678 psignal(WTERMSIG(status), argv[0]);
682 nanosleep(&ts, NULL);
692 update_stats(&walltime_nsecs_stats, t1 - t0);
695 * Closing a group leader splits the group, and as we only disable
696 * group leaders, results in remaining events becoming enabled. To
697 * avoid arbitrary skew, we must read all counters before closing any
701 perf_evlist__close(evsel_list);
703 return WEXITSTATUS(status);
706 static int run_perf_stat(int argc, const char **argv)
711 ret = system(pre_cmd);
719 ret = __run_perf_stat(argc, argv);
724 ret = system(post_cmd);
732 static void print_running(u64 run, u64 ena)
735 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
739 ena ? 100.0 * run / ena : 100.0);
740 } else if (run != ena) {
741 fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena);
745 static void print_noise_pct(double total, double avg)
747 double pct = rel_stddev_stats(total, avg);
750 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
752 fprintf(stat_config.output, " ( +-%6.2f%% )", pct);
755 static void print_noise(struct perf_evsel *evsel, double avg)
757 struct perf_stat_evsel *ps;
763 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
766 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
768 switch (stat_config.aggr_mode) {
770 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
771 cpu_map__id_to_socket(id),
773 cpu_map__id_to_cpu(id),
780 fprintf(stat_config.output, "S%*d%s%*d%s",
789 fprintf(stat_config.output, "CPU%*d%s",
791 perf_evsel__cpus(evsel)->map[id], csv_sep);
794 fprintf(stat_config.output, "%*s-%*d%s",
796 thread_map__comm(evsel->threads, id),
798 thread_map__pid(evsel->threads, id),
814 struct perf_evsel *evsel;
817 #define METRIC_LEN 35
819 static void new_line_std(void *ctx)
821 struct outstate *os = ctx;
826 static void do_new_line_std(struct outstate *os)
829 fputs(os->prefix, os->fh);
830 aggr_printout(os->evsel, os->id, os->nr);
831 if (stat_config.aggr_mode == AGGR_NONE)
832 fprintf(os->fh, " ");
833 fprintf(os->fh, " ");
836 static void print_metric_std(void *ctx, const char *color, const char *fmt,
837 const char *unit, double val)
839 struct outstate *os = ctx;
842 bool newline = os->newline;
846 if (unit == NULL || fmt == NULL) {
847 fprintf(out, "%-*s", METRIC_LEN, "");
854 n = fprintf(out, " # ");
856 n += color_fprintf(out, color, fmt, val);
858 n += fprintf(out, fmt, val);
859 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
862 static void new_line_csv(void *ctx)
864 struct outstate *os = ctx;
869 fprintf(os->fh, "%s%s", os->prefix, csv_sep);
870 aggr_printout(os->evsel, os->id, os->nr);
871 for (i = 0; i < os->nfields; i++)
872 fputs(csv_sep, os->fh);
875 static void print_metric_csv(void *ctx,
876 const char *color __maybe_unused,
877 const char *fmt, const char *unit, double val)
879 struct outstate *os = ctx;
881 char buf[64], *vals, *ends;
883 if (unit == NULL || fmt == NULL) {
884 fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
887 snprintf(buf, sizeof(buf), fmt, val);
888 ends = vals = ltrim(buf);
889 while (isdigit(*ends) || *ends == '.')
892 while (isspace(*unit))
894 fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
897 #define METRIC_ONLY_LEN 20
899 /* Filter out some columns that don't work well in metrics only mode */
901 static bool valid_only_metric(const char *unit)
905 if (strstr(unit, "/sec") ||
906 strstr(unit, "hz") ||
907 strstr(unit, "Hz") ||
908 strstr(unit, "CPUs utilized"))
913 static const char *fixunit(char *buf, struct perf_evsel *evsel,
916 if (!strncmp(unit, "of all", 6)) {
917 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
924 static void print_metric_only(void *ctx, const char *color, const char *fmt,
925 const char *unit, double val)
927 struct outstate *os = ctx;
931 unsigned mlen = METRIC_ONLY_LEN;
933 if (!valid_only_metric(unit))
935 unit = fixunit(buf, os->evsel, unit);
937 n = color_fprintf(out, color, fmt, val);
939 n = fprintf(out, fmt, val);
940 if (n > METRIC_ONLY_LEN)
942 if (mlen < strlen(unit))
943 mlen = strlen(unit) + 1;
944 fprintf(out, "%*s", mlen - n, "");
947 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
949 const char *unit, double val)
951 struct outstate *os = ctx;
953 char buf[64], *vals, *ends;
956 if (!valid_only_metric(unit))
958 unit = fixunit(tbuf, os->evsel, unit);
959 snprintf(buf, sizeof buf, fmt, val);
960 ends = vals = ltrim(buf);
961 while (isdigit(*ends) || *ends == '.')
964 fprintf(out, "%s%s", vals, csv_sep);
967 static void new_line_metric(void *ctx __maybe_unused)
971 static void print_metric_header(void *ctx, const char *color __maybe_unused,
972 const char *fmt __maybe_unused,
973 const char *unit, double val __maybe_unused)
975 struct outstate *os = ctx;
978 if (!valid_only_metric(unit))
980 unit = fixunit(tbuf, os->evsel, unit);
982 fprintf(os->fh, "%s%s", unit, csv_sep);
984 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
987 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
989 FILE *output = stat_config.output;
990 double msecs = avg / NSEC_PER_MSEC;
991 const char *fmt_v, *fmt_n;
994 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
995 fmt_n = csv_output ? "%s" : "%-25s";
997 aggr_printout(evsel, id, nr);
999 scnprintf(name, sizeof(name), "%s%s",
1000 perf_evsel__name(evsel), csv_output ? "" : " (msec)");
1002 fprintf(output, fmt_v, msecs, csv_sep);
1005 fprintf(output, "%s%s", evsel->unit, csv_sep);
1007 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
1009 fprintf(output, fmt_n, name);
1012 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1015 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
1022 if (stat_config.aggr_mode == AGGR_NONE)
1025 if (stat_config.aggr_mode == AGGR_GLOBAL)
1028 for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
1029 int cpu2 = perf_evsel__cpus(evsel)->map[i];
1031 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
1037 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1039 FILE *output = stat_config.output;
1040 double sc = evsel->scale;
1044 fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
1047 fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
1049 fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
1052 aggr_printout(evsel, id, nr);
1054 fprintf(output, fmt, avg, csv_sep);
1057 fprintf(output, "%-*s%s",
1058 csv_output ? 0 : unit_width,
1059 evsel->unit, csv_sep);
1061 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1064 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1067 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
1068 char *prefix, u64 run, u64 ena, double noise)
1070 struct perf_stat_output_ctx out;
1071 struct outstate os = {
1072 .fh = stat_config.output,
1073 .prefix = prefix ? prefix : "",
1078 print_metric_t pm = print_metric_std;
1082 nl = new_line_metric;
1084 pm = print_metric_only_csv;
1086 pm = print_metric_only;
1090 if (csv_output && !metric_only) {
1091 static int aggr_fields[] = {
1099 pm = print_metric_csv;
1102 os.nfields += aggr_fields[stat_config.aggr_mode];
1106 if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1108 pm(&os, NULL, "", "", 0);
1111 aggr_printout(counter, id, nr);
1113 fprintf(stat_config.output, "%*s%s",
1114 csv_output ? 0 : 18,
1115 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1118 if (counter->supported)
1119 print_free_counters_hint = 1;
1121 fprintf(stat_config.output, "%-*s%s",
1122 csv_output ? 0 : unit_width,
1123 counter->unit, csv_sep);
1125 fprintf(stat_config.output, "%*s",
1126 csv_output ? 0 : -25,
1127 perf_evsel__name(counter));
1130 fprintf(stat_config.output, "%s%s",
1131 csv_sep, counter->cgrp->name);
1134 pm(&os, NULL, NULL, "", 0);
1135 print_noise(counter, noise);
1136 print_running(run, ena);
1138 pm(&os, NULL, NULL, "", 0);
1144 else if (nsec_counter(counter))
1145 nsec_printout(id, nr, counter, uval);
1147 abs_printout(id, nr, counter, uval);
1149 out.print_metric = pm;
1152 out.force_header = false;
1154 if (csv_output && !metric_only) {
1155 print_noise(counter, noise);
1156 print_running(run, ena);
1159 perf_stat__print_shadow_stats(counter, uval,
1160 first_shadow_cpu(counter, id),
1162 if (!csv_output && !metric_only) {
1163 print_noise(counter, noise);
1164 print_running(run, ena);
1168 static void aggr_update_shadow(void)
1172 struct perf_evsel *counter;
1174 for (s = 0; s < aggr_map->nr; s++) {
1175 id = aggr_map->map[s];
1176 evlist__for_each_entry(evsel_list, counter) {
1178 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1179 s2 = aggr_get_id(evsel_list->cpus, cpu);
1182 val += perf_counts(counter->counts, cpu, 0)->val;
1184 val = val * counter->scale;
1185 perf_stat__update_shadow_stats(counter, &val,
1186 first_shadow_cpu(counter, id));
1191 static void collect_all_aliases(struct perf_evsel *counter,
1192 void (*cb)(struct perf_evsel *counter, void *data,
1196 struct perf_evsel *alias;
1198 alias = list_prepare_entry(counter, &(evsel_list->entries), node);
1199 list_for_each_entry_continue (alias, &evsel_list->entries, node) {
1200 if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
1201 alias->scale != counter->scale ||
1202 alias->cgrp != counter->cgrp ||
1203 strcmp(alias->unit, counter->unit) ||
1204 nsec_counter(alias) != nsec_counter(counter))
1206 alias->merged_stat = true;
1207 cb(alias, data, false);
1211 static bool collect_data(struct perf_evsel *counter,
1212 void (*cb)(struct perf_evsel *counter, void *data,
1216 if (counter->merged_stat)
1218 cb(counter, data, true);
1220 collect_all_aliases(counter, cb, data);
1231 static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
1233 struct aggr_data *ad = data;
1236 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1237 struct perf_counts_values *counts;
1239 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1244 counts = perf_counts(counter->counts, cpu, 0);
1246 * When any result is bad, make them all to give
1247 * consistent output in interval mode.
1249 if (counts->ena == 0 || counts->run == 0 ||
1250 counter->counts->scaled == -1) {
1255 ad->val += counts->val;
1256 ad->ena += counts->ena;
1257 ad->run += counts->run;
1261 static void print_aggr(char *prefix)
1263 FILE *output = stat_config.output;
1264 struct perf_evsel *counter;
1270 if (!(aggr_map || aggr_get_id))
1273 aggr_update_shadow();
1276 * With metric_only everything is on a single line.
1277 * Without each counter has its own line.
1279 for (s = 0; s < aggr_map->nr; s++) {
1280 struct aggr_data ad;
1281 if (prefix && metric_only)
1282 fprintf(output, "%s", prefix);
1284 ad.id = id = aggr_map->map[s];
1286 evlist__for_each_entry(evsel_list, counter) {
1287 ad.val = ad.ena = ad.run = 0;
1289 if (!collect_data(counter, aggr_cb, &ad))
1295 if (first && metric_only) {
1297 aggr_printout(counter, id, nr);
1299 if (prefix && !metric_only)
1300 fprintf(output, "%s", prefix);
1302 uval = val * counter->scale;
1303 printout(id, nr, counter, uval, prefix, run, ena, 1.0);
1305 fputc('\n', output);
1308 fputc('\n', output);
1312 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1314 FILE *output = stat_config.output;
1315 int nthreads = thread_map__nr(counter->threads);
1316 int ncpus = cpu_map__nr(counter->cpus);
1320 for (thread = 0; thread < nthreads; thread++) {
1321 u64 ena = 0, run = 0, val = 0;
1323 for (cpu = 0; cpu < ncpus; cpu++) {
1324 val += perf_counts(counter->counts, cpu, thread)->val;
1325 ena += perf_counts(counter->counts, cpu, thread)->ena;
1326 run += perf_counts(counter->counts, cpu, thread)->run;
1330 fprintf(output, "%s", prefix);
1332 uval = val * counter->scale;
1333 printout(thread, 0, counter, uval, prefix, run, ena, 1.0);
1334 fputc('\n', output);
1339 double avg, avg_enabled, avg_running;
1342 static void counter_aggr_cb(struct perf_evsel *counter, void *data,
1343 bool first __maybe_unused)
1345 struct caggr_data *cd = data;
1346 struct perf_stat_evsel *ps = counter->priv;
1348 cd->avg += avg_stats(&ps->res_stats[0]);
1349 cd->avg_enabled += avg_stats(&ps->res_stats[1]);
1350 cd->avg_running += avg_stats(&ps->res_stats[2]);
1354 * Print out the results of a single counter:
1355 * aggregated counts in system-wide mode
1357 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1359 FILE *output = stat_config.output;
1361 struct caggr_data cd = { .avg = 0.0 };
1363 if (!collect_data(counter, counter_aggr_cb, &cd))
1366 if (prefix && !metric_only)
1367 fprintf(output, "%s", prefix);
1369 uval = cd.avg * counter->scale;
1370 printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled, cd.avg);
1372 fprintf(output, "\n");
1375 static void counter_cb(struct perf_evsel *counter, void *data,
1376 bool first __maybe_unused)
1378 struct aggr_data *ad = data;
1380 ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
1381 ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
1382 ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
1386 * Print out the results of a single counter:
1387 * does not use aggregated count in system-wide
1389 static void print_counter(struct perf_evsel *counter, char *prefix)
1391 FILE *output = stat_config.output;
1396 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1397 struct aggr_data ad = { .cpu = cpu };
1399 if (!collect_data(counter, counter_cb, &ad))
1406 fprintf(output, "%s", prefix);
1408 uval = val * counter->scale;
1409 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1411 fputc('\n', output);
1415 static void print_no_aggr_metric(char *prefix)
1419 struct perf_evsel *counter;
1423 nrcpus = evsel_list->cpus->nr;
1424 for (cpu = 0; cpu < nrcpus; cpu++) {
1428 fputs(prefix, stat_config.output);
1429 evlist__for_each_entry(evsel_list, counter) {
1431 aggr_printout(counter, cpu, 0);
1434 val = perf_counts(counter->counts, cpu, 0)->val;
1435 ena = perf_counts(counter->counts, cpu, 0)->ena;
1436 run = perf_counts(counter->counts, cpu, 0)->run;
1438 uval = val * counter->scale;
1439 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1441 fputc('\n', stat_config.output);
1445 static int aggr_header_lens[] = {
1453 static const char *aggr_header_csv[] = {
1454 [AGGR_CORE] = "core,cpus,",
1455 [AGGR_SOCKET] = "socket,cpus",
1456 [AGGR_NONE] = "cpu,",
1457 [AGGR_THREAD] = "comm-pid,",
1461 static void print_metric_headers(const char *prefix, bool no_indent)
1463 struct perf_stat_output_ctx out;
1464 struct perf_evsel *counter;
1465 struct outstate os = {
1466 .fh = stat_config.output
1470 fprintf(stat_config.output, "%s", prefix);
1472 if (!csv_output && !no_indent)
1473 fprintf(stat_config.output, "%*s",
1474 aggr_header_lens[stat_config.aggr_mode], "");
1476 if (stat_config.interval)
1477 fputs("time,", stat_config.output);
1478 fputs(aggr_header_csv[stat_config.aggr_mode],
1479 stat_config.output);
1482 /* Print metrics headers only */
1483 evlist__for_each_entry(evsel_list, counter) {
1486 out.print_metric = print_metric_header;
1487 out.new_line = new_line_metric;
1488 out.force_header = true;
1490 perf_stat__print_shadow_stats(counter, 0,
1494 fputc('\n', stat_config.output);
1497 static void print_interval(char *prefix, struct timespec *ts)
1499 FILE *output = stat_config.output;
1500 static int num_print_interval;
1502 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1504 if (num_print_interval == 0 && !csv_output) {
1505 switch (stat_config.aggr_mode) {
1507 fprintf(output, "# time socket cpus");
1509 fprintf(output, " counts %*s events\n", unit_width, "unit");
1512 fprintf(output, "# time core cpus");
1514 fprintf(output, " counts %*s events\n", unit_width, "unit");
1517 fprintf(output, "# time CPU");
1519 fprintf(output, " counts %*s events\n", unit_width, "unit");
1522 fprintf(output, "# time comm-pid");
1524 fprintf(output, " counts %*s events\n", unit_width, "unit");
1528 fprintf(output, "# time");
1530 fprintf(output, " counts %*s events\n", unit_width, "unit");
1536 if (num_print_interval == 0 && metric_only)
1537 print_metric_headers(" ", true);
1538 if (++num_print_interval == 25)
1539 num_print_interval = 0;
1542 static void print_header(int argc, const char **argv)
1544 FILE *output = stat_config.output;
1550 fprintf(output, "\n");
1551 fprintf(output, " Performance counter stats for ");
1552 if (target.system_wide)
1553 fprintf(output, "\'system wide");
1554 else if (target.cpu_list)
1555 fprintf(output, "\'CPU(s) %s", target.cpu_list);
1556 else if (!target__has_task(&target)) {
1557 fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1558 for (i = 1; argv && (i < argc); i++)
1559 fprintf(output, " %s", argv[i]);
1560 } else if (target.pid)
1561 fprintf(output, "process id \'%s", target.pid);
1563 fprintf(output, "thread id \'%s", target.tid);
1565 fprintf(output, "\'");
1567 fprintf(output, " (%d runs)", run_count);
1568 fprintf(output, ":\n\n");
1572 static void print_footer(void)
1574 FILE *output = stat_config.output;
1577 fprintf(output, "\n");
1578 fprintf(output, " %17.9f seconds time elapsed",
1579 avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
1580 if (run_count > 1) {
1581 fprintf(output, " ");
1582 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1583 avg_stats(&walltime_nsecs_stats));
1585 fprintf(output, "\n\n");
1587 if (print_free_counters_hint)
1589 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1590 " echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1592 " echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1595 static void print_counters(struct timespec *ts, int argc, const char **argv)
1597 int interval = stat_config.interval;
1598 struct perf_evsel *counter;
1599 char buf[64], *prefix = NULL;
1601 /* Do not print anything if we record to the pipe. */
1602 if (STAT_RECORD && perf_stat.file.is_pipe)
1606 print_interval(prefix = buf, ts);
1608 print_header(argc, argv);
1611 static int num_print_iv;
1613 if (num_print_iv == 0 && !interval)
1614 print_metric_headers(prefix, false);
1615 if (num_print_iv++ == 25)
1617 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1618 fprintf(stat_config.output, "%s", prefix);
1621 switch (stat_config.aggr_mode) {
1627 evlist__for_each_entry(evsel_list, counter)
1628 print_aggr_thread(counter, prefix);
1631 evlist__for_each_entry(evsel_list, counter)
1632 print_counter_aggr(counter, prefix);
1634 fputc('\n', stat_config.output);
1638 print_no_aggr_metric(prefix);
1640 evlist__for_each_entry(evsel_list, counter)
1641 print_counter(counter, prefix);
1649 if (!interval && !csv_output)
1652 fflush(stat_config.output);
1655 static volatile int signr = -1;
1657 static void skip_signal(int signo)
1659 if ((child_pid == -1) || stat_config.interval)
1664 * render child_pid harmless
1665 * won't send SIGTERM to a random
1666 * process in case of race condition
1667 * and fast PID recycling
1672 static void sig_atexit(void)
1677 * avoid race condition with SIGCHLD handler
1678 * in skip_signal() which is modifying child_pid
1679 * goal is to avoid send SIGTERM to a random
1683 sigaddset(&set, SIGCHLD);
1684 sigprocmask(SIG_BLOCK, &set, &oset);
1686 if (child_pid != -1)
1687 kill(child_pid, SIGTERM);
1689 sigprocmask(SIG_SETMASK, &oset, NULL);
1694 signal(signr, SIG_DFL);
1695 kill(getpid(), signr);
1698 static int stat__set_big_num(const struct option *opt __maybe_unused,
1699 const char *s __maybe_unused, int unset)
1701 big_num_opt = unset ? 0 : 1;
1705 static int enable_metric_only(const struct option *opt __maybe_unused,
1706 const char *s __maybe_unused, int unset)
1708 force_metric_only = true;
1709 metric_only = !unset;
1713 static const struct option stat_options[] = {
1714 OPT_BOOLEAN('T', "transaction", &transaction_run,
1715 "hardware transaction statistics"),
1716 OPT_CALLBACK('e', "event", &evsel_list, "event",
1717 "event selector. use 'perf list' to list available events",
1718 parse_events_option),
1719 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1720 "event filter", parse_filter),
1721 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1722 "child tasks do not inherit counters"),
1723 OPT_STRING('p', "pid", &target.pid, "pid",
1724 "stat events on existing process id"),
1725 OPT_STRING('t', "tid", &target.tid, "tid",
1726 "stat events on existing thread id"),
1727 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1728 "system-wide collection from all CPUs"),
1729 OPT_BOOLEAN('g', "group", &group,
1730 "put the counters into a counter group"),
1731 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1732 OPT_INCR('v', "verbose", &verbose,
1733 "be more verbose (show counter open errors, etc)"),
1734 OPT_INTEGER('r', "repeat", &run_count,
1735 "repeat command and print average + stddev (max: 100, forever: 0)"),
1736 OPT_BOOLEAN('n', "null", &null_run,
1737 "null run - dont start any counters"),
1738 OPT_INCR('d', "detailed", &detailed_run,
1739 "detailed run - start a lot of events"),
1740 OPT_BOOLEAN('S', "sync", &sync_run,
1741 "call sync() before starting a run"),
1742 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1743 "print large numbers with thousands\' separators",
1745 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1746 "list of cpus to monitor in system-wide"),
1747 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1748 "disable CPU count aggregation", AGGR_NONE),
1749 OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
1750 OPT_STRING('x', "field-separator", &csv_sep, "separator",
1751 "print counts with custom separator"),
1752 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1753 "monitor event in cgroup name only", parse_cgroups),
1754 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1755 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1756 OPT_INTEGER(0, "log-fd", &output_fd,
1757 "log output to fd, instead of stderr"),
1758 OPT_STRING(0, "pre", &pre_cmd, "command",
1759 "command to run prior to the measured command"),
1760 OPT_STRING(0, "post", &post_cmd, "command",
1761 "command to run after to the measured command"),
1762 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1763 "print counts at regular interval in ms (>= 10)"),
1764 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1765 "aggregate counts per processor socket", AGGR_SOCKET),
1766 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1767 "aggregate counts per physical processor core", AGGR_CORE),
1768 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1769 "aggregate counts per thread", AGGR_THREAD),
1770 OPT_UINTEGER('D', "delay", &initial_delay,
1771 "ms to wait before starting measurement after program start"),
1772 OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
1773 "Only print computed metrics. No raw values", enable_metric_only),
1774 OPT_BOOLEAN(0, "topdown", &topdown_run,
1775 "measure topdown level 1 statistics"),
1779 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1781 return cpu_map__get_socket(map, cpu, NULL);
1784 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1786 return cpu_map__get_core(map, cpu, NULL);
1789 static int cpu_map__get_max(struct cpu_map *map)
1793 for (i = 0; i < map->nr; i++) {
1794 if (map->map[i] > max)
1801 static struct cpu_map *cpus_aggr_map;
1803 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1810 cpu = map->map[idx];
1812 if (cpus_aggr_map->map[cpu] == -1)
1813 cpus_aggr_map->map[cpu] = get_id(map, idx);
1815 return cpus_aggr_map->map[cpu];
1818 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1820 return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1823 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1825 return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1828 static int perf_stat_init_aggr_mode(void)
1832 switch (stat_config.aggr_mode) {
1834 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1835 perror("cannot build socket map");
1838 aggr_get_id = perf_stat__get_socket_cached;
1841 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1842 perror("cannot build core map");
1845 aggr_get_id = perf_stat__get_core_cached;
1856 * The evsel_list->cpus is the base we operate on,
1857 * taking the highest cpu number to be the size of
1858 * the aggregation translate cpumap.
1860 nr = cpu_map__get_max(evsel_list->cpus);
1861 cpus_aggr_map = cpu_map__empty_new(nr + 1);
1862 return cpus_aggr_map ? 0 : -ENOMEM;
1865 static void perf_stat__exit_aggr_mode(void)
1867 cpu_map__put(aggr_map);
1868 cpu_map__put(cpus_aggr_map);
1870 cpus_aggr_map = NULL;
1873 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1880 cpu = map->map[idx];
1882 if (cpu >= env->nr_cpus_avail)
1888 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1890 struct perf_env *env = data;
1891 int cpu = perf_env__get_cpu(env, map, idx);
1893 return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1896 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1898 struct perf_env *env = data;
1899 int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1902 int socket_id = env->cpu[cpu].socket_id;
1905 * Encode socket in upper 16 bits
1906 * core_id is relative to socket, and
1907 * we need a global id. So we combine
1910 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1916 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1917 struct cpu_map **sockp)
1919 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1922 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
1923 struct cpu_map **corep)
1925 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1928 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
1930 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1933 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
1935 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1938 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1940 struct perf_env *env = &st->session->header.env;
1942 switch (stat_config.aggr_mode) {
1944 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
1945 perror("cannot build socket map");
1948 aggr_get_id = perf_stat__get_socket_file;
1951 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
1952 perror("cannot build core map");
1955 aggr_get_id = perf_stat__get_core_file;
1968 static int topdown_filter_events(const char **attr, char **str, bool use_group)
1975 for (i = 0; attr[i]; i++) {
1976 if (pmu_have_event("cpu", attr[i])) {
1977 len += strlen(attr[i]) + 1;
1978 attr[i - off] = attr[i];
1982 attr[i - off] = NULL;
1984 *str = malloc(len + 1 + 2);
1994 for (i = 0; attr[i]; i++) {
2007 __weak bool arch_topdown_check_group(bool *warn)
2013 __weak void arch_topdown_group_warn(void)
2018 * Add default attributes, if there were no attributes specified or
2019 * if -d/--detailed, -d -d or -d -d -d is used:
2021 static int add_default_attributes(void)
2024 struct perf_event_attr default_attrs0[] = {
2026 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
2027 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
2028 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
2029 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
2031 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
2033 struct perf_event_attr frontend_attrs[] = {
2034 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
2036 struct perf_event_attr backend_attrs[] = {
2037 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
2039 struct perf_event_attr default_attrs1[] = {
2040 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
2041 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
2042 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
2047 * Detailed stats (-d), covering the L1 and last level data caches:
2049 struct perf_event_attr detailed_attrs[] = {
2051 { .type = PERF_TYPE_HW_CACHE,
2053 PERF_COUNT_HW_CACHE_L1D << 0 |
2054 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2055 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2057 { .type = PERF_TYPE_HW_CACHE,
2059 PERF_COUNT_HW_CACHE_L1D << 0 |
2060 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2061 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2063 { .type = PERF_TYPE_HW_CACHE,
2065 PERF_COUNT_HW_CACHE_LL << 0 |
2066 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2067 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2069 { .type = PERF_TYPE_HW_CACHE,
2071 PERF_COUNT_HW_CACHE_LL << 0 |
2072 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2073 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2077 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2079 struct perf_event_attr very_detailed_attrs[] = {
2081 { .type = PERF_TYPE_HW_CACHE,
2083 PERF_COUNT_HW_CACHE_L1I << 0 |
2084 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2085 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2087 { .type = PERF_TYPE_HW_CACHE,
2089 PERF_COUNT_HW_CACHE_L1I << 0 |
2090 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2091 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2093 { .type = PERF_TYPE_HW_CACHE,
2095 PERF_COUNT_HW_CACHE_DTLB << 0 |
2096 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2097 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2099 { .type = PERF_TYPE_HW_CACHE,
2101 PERF_COUNT_HW_CACHE_DTLB << 0 |
2102 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2103 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2105 { .type = PERF_TYPE_HW_CACHE,
2107 PERF_COUNT_HW_CACHE_ITLB << 0 |
2108 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2109 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2111 { .type = PERF_TYPE_HW_CACHE,
2113 PERF_COUNT_HW_CACHE_ITLB << 0 |
2114 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2115 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2120 * Very, very detailed stats (-d -d -d), adding prefetch events:
2122 struct perf_event_attr very_very_detailed_attrs[] = {
2124 { .type = PERF_TYPE_HW_CACHE,
2126 PERF_COUNT_HW_CACHE_L1D << 0 |
2127 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2128 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2130 { .type = PERF_TYPE_HW_CACHE,
2132 PERF_COUNT_HW_CACHE_L1D << 0 |
2133 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2134 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2137 /* Set attrs if no event is selected and !null_run: */
2141 if (transaction_run) {
2142 if (pmu_have_event("cpu", "cycles-ct") &&
2143 pmu_have_event("cpu", "el-start"))
2144 err = parse_events(evsel_list, transaction_attrs, NULL);
2146 err = parse_events(evsel_list, transaction_limited_attrs, NULL);
2148 fprintf(stderr, "Cannot set up transaction events\n");
2158 if (stat_config.aggr_mode != AGGR_GLOBAL &&
2159 stat_config.aggr_mode != AGGR_CORE) {
2160 pr_err("top down event configuration requires --per-core mode\n");
2163 stat_config.aggr_mode = AGGR_CORE;
2164 if (nr_cgroups || !target__has_cpu(&target)) {
2165 pr_err("top down event configuration requires system-wide mode (-a)\n");
2169 if (!force_metric_only)
2171 if (topdown_filter_events(topdown_attrs, &str,
2172 arch_topdown_check_group(&warn)) < 0) {
2173 pr_err("Out of memory\n");
2176 if (topdown_attrs[0] && str) {
2178 arch_topdown_group_warn();
2179 err = parse_events(evsel_list, str, NULL);
2182 "Cannot set up top down events %s: %d\n",
2188 fprintf(stderr, "System does not support topdown\n");
2194 if (!evsel_list->nr_entries) {
2195 if (target__has_cpu(&target))
2196 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2198 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2200 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2201 if (perf_evlist__add_default_attrs(evsel_list,
2202 frontend_attrs) < 0)
2205 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2206 if (perf_evlist__add_default_attrs(evsel_list,
2210 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2214 /* Detailed events get appended to the event list: */
2216 if (detailed_run < 1)
2219 /* Append detailed run extra attributes: */
2220 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2223 if (detailed_run < 2)
2226 /* Append very detailed run extra attributes: */
2227 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2230 if (detailed_run < 3)
2233 /* Append very, very detailed run extra attributes: */
2234 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2237 static const char * const stat_record_usage[] = {
2238 "perf stat record [<options>]",
2242 static void init_features(struct perf_session *session)
2246 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2247 perf_header__set_feat(&session->header, feat);
2249 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2250 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2251 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2252 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2255 static int __cmd_record(int argc, const char **argv)
2257 struct perf_session *session;
2258 struct perf_data_file *file = &perf_stat.file;
2260 argc = parse_options(argc, argv, stat_options, stat_record_usage,
2261 PARSE_OPT_STOP_AT_NON_OPTION);
2264 file->path = output_name;
2266 if (run_count != 1 || forever) {
2267 pr_err("Cannot use -r option with perf stat record.\n");
2271 session = perf_session__new(file, false, NULL);
2272 if (session == NULL) {
2273 pr_err("Perf session creation failed.\n");
2277 init_features(session);
2279 session->evlist = evsel_list;
2280 perf_stat.session = session;
2281 perf_stat.record = true;
2285 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2286 union perf_event *event,
2287 struct perf_session *session)
2289 struct stat_round_event *stat_round = &event->stat_round;
2290 struct perf_evsel *counter;
2291 struct timespec tsh, *ts = NULL;
2292 const char **argv = session->header.env.cmdline_argv;
2293 int argc = session->header.env.nr_cmdline;
2295 evlist__for_each_entry(evsel_list, counter)
2296 perf_stat_process_counter(&stat_config, counter);
2298 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2299 update_stats(&walltime_nsecs_stats, stat_round->time);
2301 if (stat_config.interval && stat_round->time) {
2302 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2303 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2307 print_counters(ts, argc, argv);
2312 int process_stat_config_event(struct perf_tool *tool,
2313 union perf_event *event,
2314 struct perf_session *session __maybe_unused)
2316 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2318 perf_event__read_stat_config(&stat_config, &event->stat_config);
2320 if (cpu_map__empty(st->cpus)) {
2321 if (st->aggr_mode != AGGR_UNSET)
2322 pr_warning("warning: processing task data, aggregation mode not set\n");
2326 if (st->aggr_mode != AGGR_UNSET)
2327 stat_config.aggr_mode = st->aggr_mode;
2329 if (perf_stat.file.is_pipe)
2330 perf_stat_init_aggr_mode();
2332 perf_stat_init_aggr_mode_file(st);
2337 static int set_maps(struct perf_stat *st)
2339 if (!st->cpus || !st->threads)
2342 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2345 perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2347 if (perf_evlist__alloc_stats(evsel_list, true))
2350 st->maps_allocated = true;
2355 int process_thread_map_event(struct perf_tool *tool,
2356 union perf_event *event,
2357 struct perf_session *session __maybe_unused)
2359 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2362 pr_warning("Extra thread map event, ignoring.\n");
2366 st->threads = thread_map__new_event(&event->thread_map);
2370 return set_maps(st);
2374 int process_cpu_map_event(struct perf_tool *tool,
2375 union perf_event *event,
2376 struct perf_session *session __maybe_unused)
2378 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2379 struct cpu_map *cpus;
2382 pr_warning("Extra cpu map event, ignoring.\n");
2386 cpus = cpu_map__new_data(&event->cpu_map.data);
2391 return set_maps(st);
2394 static const char * const stat_report_usage[] = {
2395 "perf stat report [<options>]",
2399 static struct perf_stat perf_stat = {
2401 .attr = perf_event__process_attr,
2402 .event_update = perf_event__process_event_update,
2403 .thread_map = process_thread_map_event,
2404 .cpu_map = process_cpu_map_event,
2405 .stat_config = process_stat_config_event,
2406 .stat = perf_event__process_stat_event,
2407 .stat_round = process_stat_round_event,
2409 .aggr_mode = AGGR_UNSET,
2412 static int __cmd_report(int argc, const char **argv)
2414 struct perf_session *session;
2415 const struct option options[] = {
2416 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2417 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2418 "aggregate counts per processor socket", AGGR_SOCKET),
2419 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2420 "aggregate counts per physical processor core", AGGR_CORE),
2421 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2422 "disable CPU count aggregation", AGGR_NONE),
2428 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2430 if (!input_name || !strlen(input_name)) {
2431 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2434 input_name = "perf.data";
2437 perf_stat.file.path = input_name;
2438 perf_stat.file.mode = PERF_DATA_MODE_READ;
2440 session = perf_session__new(&perf_stat.file, false, &perf_stat.tool);
2441 if (session == NULL)
2444 perf_stat.session = session;
2445 stat_config.output = stderr;
2446 evsel_list = session->evlist;
2448 ret = perf_session__process_events(session);
2452 perf_session__delete(session);
2456 static void setup_system_wide(int forks)
2459 * Make system wide (-a) the default target if
2460 * no target was specified and one of following
2461 * conditions is met:
2463 * - there's no workload specified
2464 * - there is workload specified but all requested
2465 * events are system wide events
2467 if (!target__none(&target))
2471 target.system_wide = true;
2473 struct perf_evsel *counter;
2475 evlist__for_each_entry(evsel_list, counter) {
2476 if (!counter->system_wide)
2480 if (evsel_list->nr_entries)
2481 target.system_wide = true;
2485 int cmd_stat(int argc, const char **argv)
2487 const char * const stat_usage[] = {
2488 "perf stat [<options>] [<command>]",
2491 int status = -EINVAL, run_idx;
2493 FILE *output = stderr;
2494 unsigned int interval;
2495 const char * const stat_subcommands[] = { "record", "report" };
2497 setlocale(LC_ALL, "");
2499 evsel_list = perf_evlist__new();
2500 if (evsel_list == NULL)
2503 parse_events__shrink_config_terms();
2504 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2505 (const char **) stat_usage,
2506 PARSE_OPT_STOP_AT_NON_OPTION);
2507 perf_stat__collect_metric_expr(evsel_list);
2508 perf_stat__init_shadow_stats();
2512 if (!strcmp(csv_sep, "\\t"))
2515 csv_sep = DEFAULT_SEPARATOR;
2517 if (argc && !strncmp(argv[0], "rec", 3)) {
2518 argc = __cmd_record(argc, argv);
2521 } else if (argc && !strncmp(argv[0], "rep", 3))
2522 return __cmd_report(argc, argv);
2524 interval = stat_config.interval;
2527 * For record command the -o is already taken care of.
2529 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2532 if (output_name && output_fd) {
2533 fprintf(stderr, "cannot use both --output and --log-fd\n");
2534 parse_options_usage(stat_usage, stat_options, "o", 1);
2535 parse_options_usage(NULL, stat_options, "log-fd", 0);
2539 if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2540 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2544 if (metric_only && run_count > 1) {
2545 fprintf(stderr, "--metric-only is not supported with -r\n");
2549 if (output_fd < 0) {
2550 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2551 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2557 mode = append_file ? "a" : "w";
2559 output = fopen(output_name, mode);
2561 perror("failed to create output file");
2564 clock_gettime(CLOCK_REALTIME, &tm);
2565 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2566 } else if (output_fd > 0) {
2567 mode = append_file ? "a" : "w";
2568 output = fdopen(output_fd, mode);
2570 perror("Failed opening logfd");
2575 stat_config.output = output;
2578 * let the spreadsheet do the pretty-printing
2581 /* User explicitly passed -B? */
2582 if (big_num_opt == 1) {
2583 fprintf(stderr, "-B option not supported with -x\n");
2584 parse_options_usage(stat_usage, stat_options, "B", 1);
2585 parse_options_usage(NULL, stat_options, "x", 1);
2587 } else /* Nope, so disable big number formatting */
2589 } else if (big_num_opt == 0) /* User passed --no-big-num */
2592 setup_system_wide(argc);
2594 if (run_count < 0) {
2595 pr_err("Run count must be a positive number\n");
2596 parse_options_usage(stat_usage, stat_options, "r", 1);
2598 } else if (run_count == 0) {
2603 if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
2604 fprintf(stderr, "The --per-thread option is only available "
2605 "when monitoring via -p -t options.\n");
2606 parse_options_usage(NULL, stat_options, "p", 1);
2607 parse_options_usage(NULL, stat_options, "t", 1);
2612 * no_aggr, cgroup are for system-wide only
2613 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2615 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2616 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2617 !target__has_cpu(&target)) {
2618 fprintf(stderr, "both cgroup and no-aggregation "
2619 "modes only available in system-wide mode\n");
2621 parse_options_usage(stat_usage, stat_options, "G", 1);
2622 parse_options_usage(NULL, stat_options, "A", 1);
2623 parse_options_usage(NULL, stat_options, "a", 1);
2627 if (add_default_attributes())
2630 target__validate(&target);
2632 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2633 if (target__has_task(&target)) {
2634 pr_err("Problems finding threads of monitor\n");
2635 parse_options_usage(stat_usage, stat_options, "p", 1);
2636 parse_options_usage(NULL, stat_options, "t", 1);
2637 } else if (target__has_cpu(&target)) {
2638 perror("failed to parse CPUs map");
2639 parse_options_usage(stat_usage, stat_options, "C", 1);
2640 parse_options_usage(NULL, stat_options, "a", 1);
2646 * Initialize thread_map with comm names,
2647 * so we could print it out on output.
2649 if (stat_config.aggr_mode == AGGR_THREAD)
2650 thread_map__read_comms(evsel_list->threads);
2652 if (interval && interval < 100) {
2653 if (interval < 10) {
2654 pr_err("print interval must be >= 10ms\n");
2655 parse_options_usage(stat_usage, stat_options, "I", 1);
2658 pr_warning("print interval < 100ms. "
2659 "The overhead percentage could be high in some cases. "
2660 "Please proceed with caution.\n");
2663 if (perf_evlist__alloc_stats(evsel_list, interval))
2666 if (perf_stat_init_aggr_mode())
2670 * We dont want to block the signals - that would cause
2671 * child tasks to inherit that and Ctrl-C would not work.
2672 * What we want is for Ctrl-C to work in the exec()-ed
2673 * task, but being ignored by perf stat itself:
2677 signal(SIGINT, skip_signal);
2678 signal(SIGCHLD, skip_signal);
2679 signal(SIGALRM, skip_signal);
2680 signal(SIGABRT, skip_signal);
2683 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2684 if (run_count != 1 && verbose > 0)
2685 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2688 status = run_perf_stat(argc, argv);
2689 if (forever && status != -1) {
2690 print_counters(NULL, argc, argv);
2691 perf_stat__reset_stats();
2695 if (!forever && status != -1 && !interval)
2696 print_counters(NULL, argc, argv);
2700 * We synthesize the kernel mmap record just so that older tools
2701 * don't emit warnings about not being able to resolve symbols
2702 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2703 * a saner message about no samples being in the perf.data file.
2705 * This also serves to suppress a warning about f_header.data.size == 0
2706 * in header.c at the moment 'perf stat record' gets introduced, which
2707 * is not really needed once we start adding the stat specific PERF_RECORD_
2708 * records, but the need to suppress the kptr_restrict messages in older
2709 * tools remain -acme
2711 int fd = perf_data_file__fd(&perf_stat.file);
2712 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2713 process_synthesized_event,
2714 &perf_stat.session->machines.host);
2716 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2717 "older tools may produce warnings about this file\n.");
2721 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2722 pr_err("failed to write stat round event\n");
2725 if (!perf_stat.file.is_pipe) {
2726 perf_stat.session->header.data_size += perf_stat.bytes_written;
2727 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2730 perf_session__delete(perf_stat.session);
2733 perf_stat__exit_aggr_mode();
2734 perf_evlist__free_stats(evsel_list);
2736 perf_evlist__delete(evsel_list);