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>
75 #include <sys/prctl.h>
79 #include <sys/types.h>
83 #include "sane_ctype.h"
85 #define DEFAULT_SEPARATOR " "
86 #define CNTR_NOT_SUPPORTED "<not supported>"
87 #define CNTR_NOT_COUNTED "<not counted>"
89 static void print_counters(struct timespec *ts, int argc, const char **argv);
91 /* Default events used for perf stat -T */
92 static const char *transaction_attrs = {
104 /* More limited version when the CPU does not have all events. */
105 static const char * transaction_limited_attrs = {
115 static const char * topdown_attrs[] = {
116 "topdown-total-slots",
117 "topdown-slots-retired",
118 "topdown-recovery-bubbles",
119 "topdown-fetch-bubbles",
120 "topdown-slots-issued",
124 static struct perf_evlist *evsel_list;
126 static struct target target = {
130 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
132 static int run_count = 1;
133 static bool no_inherit = false;
134 static volatile pid_t child_pid = -1;
135 static bool null_run = false;
136 static int detailed_run = 0;
137 static bool transaction_run;
138 static bool topdown_run = false;
139 static bool big_num = true;
140 static int big_num_opt = -1;
141 static const char *csv_sep = NULL;
142 static bool csv_output = false;
143 static bool group = false;
144 static const char *pre_cmd = NULL;
145 static const char *post_cmd = NULL;
146 static bool sync_run = false;
147 static unsigned int initial_delay = 0;
148 static unsigned int unit_width = 4; /* strlen("unit") */
149 static bool forever = false;
150 static bool metric_only = false;
151 static bool force_metric_only = false;
152 static bool no_merge = false;
153 static struct timespec ref_time;
154 static struct cpu_map *aggr_map;
155 static aggr_get_id_t aggr_get_id;
156 static bool append_file;
157 static const char *output_name;
158 static int output_fd;
159 static int print_free_counters_hint;
163 struct perf_data_file file;
164 struct perf_session *session;
166 struct perf_tool tool;
168 struct cpu_map *cpus;
169 struct thread_map *threads;
170 enum aggr_mode aggr_mode;
173 static struct perf_stat perf_stat;
174 #define STAT_RECORD perf_stat.record
176 static volatile int done = 0;
178 static struct perf_stat_config stat_config = {
179 .aggr_mode = AGGR_GLOBAL,
183 static inline void diff_timespec(struct timespec *r, struct timespec *a,
186 r->tv_sec = a->tv_sec - b->tv_sec;
187 if (a->tv_nsec < b->tv_nsec) {
188 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
191 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
195 static void perf_stat__reset_stats(void)
197 perf_evlist__reset_stats(evsel_list);
198 perf_stat__reset_shadow_stats();
201 static int create_perf_stat_counter(struct perf_evsel *evsel)
203 struct perf_event_attr *attr = &evsel->attr;
205 if (stat_config.scale)
206 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
207 PERF_FORMAT_TOTAL_TIME_RUNNING;
209 attr->inherit = !no_inherit;
212 * Some events get initialized with sample_(period/type) set,
213 * like tracepoints. Clear it up for counting.
215 attr->sample_period = 0;
218 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
219 * while avoiding that older tools show confusing messages.
221 * However for pipe sessions we need to keep it zero,
222 * because script's perf_evsel__check_attr is triggered
223 * by attr->sample_type != 0, and we can't run it on
226 if (!(STAT_RECORD && perf_stat.file.is_pipe))
227 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
230 * Disabling all counters initially, they will be enabled
231 * either manually by us or by kernel via enable_on_exec
234 if (perf_evsel__is_group_leader(evsel)) {
238 * In case of initial_delay we enable tracee
241 if (target__none(&target) && !initial_delay)
242 attr->enable_on_exec = 1;
245 if (target__has_cpu(&target))
246 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
248 return perf_evsel__open_per_thread(evsel, evsel_list->threads);
252 * Does the counter have nsecs as a unit?
254 static inline int nsec_counter(struct perf_evsel *evsel)
256 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
257 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
263 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
264 union perf_event *event,
265 struct perf_sample *sample __maybe_unused,
266 struct machine *machine __maybe_unused)
268 if (perf_data_file__write(&perf_stat.file, event, event->header.size) < 0) {
269 pr_err("failed to write perf data, error: %m\n");
273 perf_stat.bytes_written += event->header.size;
277 static int write_stat_round_event(u64 tm, u64 type)
279 return perf_event__synthesize_stat_round(NULL, tm, type,
280 process_synthesized_event,
284 #define WRITE_STAT_ROUND_EVENT(time, interval) \
285 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
287 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
290 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
291 struct perf_counts_values *count)
293 struct perf_sample_id *sid = SID(counter, cpu, thread);
295 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
296 process_synthesized_event, NULL);
300 * Read out the results of a single counter:
301 * do not aggregate counts across CPUs in system-wide mode
303 static int read_counter(struct perf_evsel *counter)
305 int nthreads = thread_map__nr(evsel_list->threads);
306 int ncpus, cpu, thread;
308 if (target__has_cpu(&target))
309 ncpus = perf_evsel__nr_cpus(counter);
313 if (!counter->supported)
316 if (counter->system_wide)
319 for (thread = 0; thread < nthreads; thread++) {
320 for (cpu = 0; cpu < ncpus; cpu++) {
321 struct perf_counts_values *count;
323 count = perf_counts(counter->counts, cpu, thread);
324 if (perf_evsel__read(counter, cpu, thread, count)) {
325 counter->counts->scaled = -1;
326 perf_counts(counter->counts, cpu, thread)->ena = 0;
327 perf_counts(counter->counts, cpu, thread)->run = 0;
332 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
333 pr_err("failed to write stat event\n");
339 fprintf(stat_config.output,
340 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
341 perf_evsel__name(counter),
343 count->val, count->ena, count->run);
351 static void read_counters(void)
353 struct perf_evsel *counter;
356 evlist__for_each_entry(evsel_list, counter) {
357 ret = read_counter(counter);
359 pr_debug("failed to read counter %s\n", counter->name);
361 if (ret == 0 && perf_stat_process_counter(&stat_config, counter))
362 pr_warning("failed to process counter %s\n", counter->name);
366 static void process_interval(void)
368 struct timespec ts, rs;
372 clock_gettime(CLOCK_MONOTONIC, &ts);
373 diff_timespec(&rs, &ts, &ref_time);
376 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
377 pr_err("failed to write stat round event\n");
380 print_counters(&rs, 0, NULL);
383 static void enable_counters(void)
386 usleep(initial_delay * USEC_PER_MSEC);
389 * We need to enable counters only if:
390 * - we don't have tracee (attaching to task or cpu)
391 * - we have initial delay configured
393 if (!target__none(&target) || initial_delay)
394 perf_evlist__enable(evsel_list);
397 static void disable_counters(void)
400 * If we don't have tracee (attaching to task or cpu), counters may
401 * still be running. To get accurate group ratios, we must stop groups
402 * from counting before reading their constituent counters.
404 if (!target__none(&target))
405 perf_evlist__disable(evsel_list);
408 static volatile int workload_exec_errno;
411 * perf_evlist__prepare_workload will send a SIGUSR1
412 * if the fork fails, since we asked by setting its
413 * want_signal to true.
415 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
416 void *ucontext __maybe_unused)
418 workload_exec_errno = info->si_value.sival_int;
421 static bool has_unit(struct perf_evsel *counter)
423 return counter->unit && *counter->unit;
426 static bool has_scale(struct perf_evsel *counter)
428 return counter->scale != 1;
431 static int perf_stat_synthesize_config(bool is_pipe)
433 struct perf_evsel *counter;
437 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
438 process_synthesized_event);
440 pr_err("Couldn't synthesize attrs.\n");
446 * Synthesize other events stuff not carried within
447 * attr event - unit, scale, name
449 evlist__for_each_entry(evsel_list, counter) {
450 if (!counter->supported)
454 * Synthesize unit and scale only if it's defined.
456 if (has_unit(counter)) {
457 err = perf_event__synthesize_event_update_unit(NULL, counter, process_synthesized_event);
459 pr_err("Couldn't synthesize evsel unit.\n");
464 if (has_scale(counter)) {
465 err = perf_event__synthesize_event_update_scale(NULL, counter, process_synthesized_event);
467 pr_err("Couldn't synthesize evsel scale.\n");
472 if (counter->own_cpus) {
473 err = perf_event__synthesize_event_update_cpus(NULL, counter, process_synthesized_event);
475 pr_err("Couldn't synthesize evsel scale.\n");
481 * Name is needed only for pipe output,
482 * perf.data carries event names.
485 err = perf_event__synthesize_event_update_name(NULL, counter, process_synthesized_event);
487 pr_err("Couldn't synthesize evsel name.\n");
493 err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
494 process_synthesized_event,
497 pr_err("Couldn't synthesize thread map.\n");
501 err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
502 process_synthesized_event, NULL);
504 pr_err("Couldn't synthesize thread map.\n");
508 err = perf_event__synthesize_stat_config(NULL, &stat_config,
509 process_synthesized_event, NULL);
511 pr_err("Couldn't synthesize config.\n");
518 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
520 static int __store_counter_ids(struct perf_evsel *counter,
521 struct cpu_map *cpus,
522 struct thread_map *threads)
526 for (cpu = 0; cpu < cpus->nr; cpu++) {
527 for (thread = 0; thread < threads->nr; thread++) {
528 int fd = FD(counter, cpu, thread);
530 if (perf_evlist__id_add_fd(evsel_list, counter,
531 cpu, thread, fd) < 0)
539 static int store_counter_ids(struct perf_evsel *counter)
541 struct cpu_map *cpus = counter->cpus;
542 struct thread_map *threads = counter->threads;
544 if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
547 return __store_counter_ids(counter, cpus, threads);
550 static int __run_perf_stat(int argc, const char **argv)
552 int interval = stat_config.interval;
554 unsigned long long t0, t1;
555 struct perf_evsel *counter;
559 const bool forks = (argc > 0);
560 bool is_pipe = STAT_RECORD ? perf_stat.file.is_pipe : false;
561 struct perf_evsel_config_term *err_term;
564 ts.tv_sec = interval / USEC_PER_MSEC;
565 ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
572 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
573 workload_exec_failed_signal) < 0) {
574 perror("failed to prepare workload");
577 child_pid = evsel_list->workload.pid;
581 perf_evlist__set_leader(evsel_list);
583 evlist__for_each_entry(evsel_list, counter) {
585 if (create_perf_stat_counter(counter) < 0) {
587 * PPC returns ENXIO for HW counters until 2.6.37
588 * (behavior changed with commit b0a873e).
590 if (errno == EINVAL || errno == ENOSYS ||
591 errno == ENOENT || errno == EOPNOTSUPP ||
594 ui__warning("%s event is not supported by the kernel.\n",
595 perf_evsel__name(counter));
596 counter->supported = false;
598 if ((counter->leader != counter) ||
599 !(counter->leader->nr_members > 1))
601 } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
603 ui__warning("%s\n", msg);
607 perf_evsel__open_strerror(counter, &target,
608 errno, msg, sizeof(msg));
609 ui__error("%s\n", msg);
612 kill(child_pid, SIGTERM);
616 counter->supported = true;
618 l = strlen(counter->unit);
622 if (STAT_RECORD && store_counter_ids(counter))
626 if (perf_evlist__apply_filters(evsel_list, &counter)) {
627 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
628 counter->filter, perf_evsel__name(counter), errno,
629 str_error_r(errno, msg, sizeof(msg)));
633 if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
634 error("failed to set config \"%s\" on event %s with %d (%s)\n",
635 err_term->val.drv_cfg, perf_evsel__name(counter), errno,
636 str_error_r(errno, msg, sizeof(msg)));
641 int err, fd = perf_data_file__fd(&perf_stat.file);
644 err = perf_header__write_pipe(perf_data_file__fd(&perf_stat.file));
646 err = perf_session__write_header(perf_stat.session, evsel_list,
653 err = perf_stat_synthesize_config(is_pipe);
659 * Enable counters and exec the command:
662 clock_gettime(CLOCK_MONOTONIC, &ref_time);
665 perf_evlist__start_workload(evsel_list);
669 while (!waitpid(child_pid, &status, WNOHANG)) {
670 nanosleep(&ts, NULL);
676 if (workload_exec_errno) {
677 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
678 pr_err("Workload failed: %s\n", emsg);
682 if (WIFSIGNALED(status))
683 psignal(WTERMSIG(status), argv[0]);
687 nanosleep(&ts, NULL);
697 update_stats(&walltime_nsecs_stats, t1 - t0);
700 * Closing a group leader splits the group, and as we only disable
701 * group leaders, results in remaining events becoming enabled. To
702 * avoid arbitrary skew, we must read all counters before closing any
706 perf_evlist__close(evsel_list);
708 return WEXITSTATUS(status);
711 static int run_perf_stat(int argc, const char **argv)
716 ret = system(pre_cmd);
724 ret = __run_perf_stat(argc, argv);
729 ret = system(post_cmd);
737 static void print_running(u64 run, u64 ena)
740 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
744 ena ? 100.0 * run / ena : 100.0);
745 } else if (run != ena) {
746 fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena);
750 static void print_noise_pct(double total, double avg)
752 double pct = rel_stddev_stats(total, avg);
755 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
757 fprintf(stat_config.output, " ( +-%6.2f%% )", pct);
760 static void print_noise(struct perf_evsel *evsel, double avg)
762 struct perf_stat_evsel *ps;
768 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
771 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
773 switch (stat_config.aggr_mode) {
775 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
776 cpu_map__id_to_socket(id),
778 cpu_map__id_to_cpu(id),
785 fprintf(stat_config.output, "S%*d%s%*d%s",
794 fprintf(stat_config.output, "CPU%*d%s",
796 perf_evsel__cpus(evsel)->map[id], csv_sep);
799 fprintf(stat_config.output, "%*s-%*d%s",
801 thread_map__comm(evsel->threads, id),
803 thread_map__pid(evsel->threads, id),
819 struct perf_evsel *evsel;
822 #define METRIC_LEN 35
824 static void new_line_std(void *ctx)
826 struct outstate *os = ctx;
831 static void do_new_line_std(struct outstate *os)
834 fputs(os->prefix, os->fh);
835 aggr_printout(os->evsel, os->id, os->nr);
836 if (stat_config.aggr_mode == AGGR_NONE)
837 fprintf(os->fh, " ");
838 fprintf(os->fh, " ");
841 static void print_metric_std(void *ctx, const char *color, const char *fmt,
842 const char *unit, double val)
844 struct outstate *os = ctx;
847 bool newline = os->newline;
851 if (unit == NULL || fmt == NULL) {
852 fprintf(out, "%-*s", METRIC_LEN, "");
859 n = fprintf(out, " # ");
861 n += color_fprintf(out, color, fmt, val);
863 n += fprintf(out, fmt, val);
864 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
867 static void new_line_csv(void *ctx)
869 struct outstate *os = ctx;
874 fprintf(os->fh, "%s%s", os->prefix, csv_sep);
875 aggr_printout(os->evsel, os->id, os->nr);
876 for (i = 0; i < os->nfields; i++)
877 fputs(csv_sep, os->fh);
880 static void print_metric_csv(void *ctx,
881 const char *color __maybe_unused,
882 const char *fmt, const char *unit, double val)
884 struct outstate *os = ctx;
886 char buf[64], *vals, *ends;
888 if (unit == NULL || fmt == NULL) {
889 fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
892 snprintf(buf, sizeof(buf), fmt, val);
893 ends = vals = ltrim(buf);
894 while (isdigit(*ends) || *ends == '.')
897 while (isspace(*unit))
899 fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
902 #define METRIC_ONLY_LEN 20
904 /* Filter out some columns that don't work well in metrics only mode */
906 static bool valid_only_metric(const char *unit)
910 if (strstr(unit, "/sec") ||
911 strstr(unit, "hz") ||
912 strstr(unit, "Hz") ||
913 strstr(unit, "CPUs utilized"))
918 static const char *fixunit(char *buf, struct perf_evsel *evsel,
921 if (!strncmp(unit, "of all", 6)) {
922 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
929 static void print_metric_only(void *ctx, const char *color, const char *fmt,
930 const char *unit, double val)
932 struct outstate *os = ctx;
936 unsigned mlen = METRIC_ONLY_LEN;
938 if (!valid_only_metric(unit))
940 unit = fixunit(buf, os->evsel, unit);
942 n = color_fprintf(out, color, fmt, val);
944 n = fprintf(out, fmt, val);
945 if (n > METRIC_ONLY_LEN)
947 if (mlen < strlen(unit))
948 mlen = strlen(unit) + 1;
949 fprintf(out, "%*s", mlen - n, "");
952 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
954 const char *unit, double val)
956 struct outstate *os = ctx;
958 char buf[64], *vals, *ends;
961 if (!valid_only_metric(unit))
963 unit = fixunit(tbuf, os->evsel, unit);
964 snprintf(buf, sizeof buf, fmt, val);
965 ends = vals = ltrim(buf);
966 while (isdigit(*ends) || *ends == '.')
969 fprintf(out, "%s%s", vals, csv_sep);
972 static void new_line_metric(void *ctx __maybe_unused)
976 static void print_metric_header(void *ctx, const char *color __maybe_unused,
977 const char *fmt __maybe_unused,
978 const char *unit, double val __maybe_unused)
980 struct outstate *os = ctx;
983 if (!valid_only_metric(unit))
985 unit = fixunit(tbuf, os->evsel, unit);
987 fprintf(os->fh, "%s%s", unit, csv_sep);
989 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
992 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
994 FILE *output = stat_config.output;
995 double msecs = avg / NSEC_PER_MSEC;
996 const char *fmt_v, *fmt_n;
999 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
1000 fmt_n = csv_output ? "%s" : "%-25s";
1002 aggr_printout(evsel, id, nr);
1004 scnprintf(name, sizeof(name), "%s%s",
1005 perf_evsel__name(evsel), csv_output ? "" : " (msec)");
1007 fprintf(output, fmt_v, msecs, csv_sep);
1010 fprintf(output, "%s%s", evsel->unit, csv_sep);
1012 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
1014 fprintf(output, fmt_n, name);
1017 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1020 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
1027 if (stat_config.aggr_mode == AGGR_NONE)
1030 if (stat_config.aggr_mode == AGGR_GLOBAL)
1033 for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
1034 int cpu2 = perf_evsel__cpus(evsel)->map[i];
1036 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
1042 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1044 FILE *output = stat_config.output;
1045 double sc = evsel->scale;
1049 fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
1052 fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
1054 fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
1057 aggr_printout(evsel, id, nr);
1059 fprintf(output, fmt, avg, csv_sep);
1062 fprintf(output, "%-*s%s",
1063 csv_output ? 0 : unit_width,
1064 evsel->unit, csv_sep);
1066 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1069 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1072 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
1073 char *prefix, u64 run, u64 ena, double noise)
1075 struct perf_stat_output_ctx out;
1076 struct outstate os = {
1077 .fh = stat_config.output,
1078 .prefix = prefix ? prefix : "",
1083 print_metric_t pm = print_metric_std;
1087 nl = new_line_metric;
1089 pm = print_metric_only_csv;
1091 pm = print_metric_only;
1095 if (csv_output && !metric_only) {
1096 static int aggr_fields[] = {
1104 pm = print_metric_csv;
1107 os.nfields += aggr_fields[stat_config.aggr_mode];
1111 if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1113 pm(&os, NULL, "", "", 0);
1116 aggr_printout(counter, id, nr);
1118 fprintf(stat_config.output, "%*s%s",
1119 csv_output ? 0 : 18,
1120 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1123 if (counter->supported)
1124 print_free_counters_hint = 1;
1126 fprintf(stat_config.output, "%-*s%s",
1127 csv_output ? 0 : unit_width,
1128 counter->unit, csv_sep);
1130 fprintf(stat_config.output, "%*s",
1131 csv_output ? 0 : -25,
1132 perf_evsel__name(counter));
1135 fprintf(stat_config.output, "%s%s",
1136 csv_sep, counter->cgrp->name);
1139 pm(&os, NULL, NULL, "", 0);
1140 print_noise(counter, noise);
1141 print_running(run, ena);
1143 pm(&os, NULL, NULL, "", 0);
1149 else if (nsec_counter(counter))
1150 nsec_printout(id, nr, counter, uval);
1152 abs_printout(id, nr, counter, uval);
1154 out.print_metric = pm;
1157 out.force_header = false;
1159 if (csv_output && !metric_only) {
1160 print_noise(counter, noise);
1161 print_running(run, ena);
1164 perf_stat__print_shadow_stats(counter, uval,
1165 first_shadow_cpu(counter, id),
1167 if (!csv_output && !metric_only) {
1168 print_noise(counter, noise);
1169 print_running(run, ena);
1173 static void aggr_update_shadow(void)
1177 struct perf_evsel *counter;
1179 for (s = 0; s < aggr_map->nr; s++) {
1180 id = aggr_map->map[s];
1181 evlist__for_each_entry(evsel_list, counter) {
1183 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1184 s2 = aggr_get_id(evsel_list->cpus, cpu);
1187 val += perf_counts(counter->counts, cpu, 0)->val;
1189 val = val * counter->scale;
1190 perf_stat__update_shadow_stats(counter, &val,
1191 first_shadow_cpu(counter, id));
1196 static void collect_all_aliases(struct perf_evsel *counter,
1197 void (*cb)(struct perf_evsel *counter, void *data,
1201 struct perf_evsel *alias;
1203 alias = list_prepare_entry(counter, &(evsel_list->entries), node);
1204 list_for_each_entry_continue (alias, &evsel_list->entries, node) {
1205 if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
1206 alias->scale != counter->scale ||
1207 alias->cgrp != counter->cgrp ||
1208 strcmp(alias->unit, counter->unit) ||
1209 nsec_counter(alias) != nsec_counter(counter))
1211 alias->merged_stat = true;
1212 cb(alias, data, false);
1216 static bool collect_data(struct perf_evsel *counter,
1217 void (*cb)(struct perf_evsel *counter, void *data,
1221 if (counter->merged_stat)
1223 cb(counter, data, true);
1225 collect_all_aliases(counter, cb, data);
1236 static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
1238 struct aggr_data *ad = data;
1241 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1242 struct perf_counts_values *counts;
1244 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1249 counts = perf_counts(counter->counts, cpu, 0);
1251 * When any result is bad, make them all to give
1252 * consistent output in interval mode.
1254 if (counts->ena == 0 || counts->run == 0 ||
1255 counter->counts->scaled == -1) {
1260 ad->val += counts->val;
1261 ad->ena += counts->ena;
1262 ad->run += counts->run;
1266 static void print_aggr(char *prefix)
1268 FILE *output = stat_config.output;
1269 struct perf_evsel *counter;
1275 if (!(aggr_map || aggr_get_id))
1278 aggr_update_shadow();
1281 * With metric_only everything is on a single line.
1282 * Without each counter has its own line.
1284 for (s = 0; s < aggr_map->nr; s++) {
1285 struct aggr_data ad;
1286 if (prefix && metric_only)
1287 fprintf(output, "%s", prefix);
1289 ad.id = id = aggr_map->map[s];
1291 evlist__for_each_entry(evsel_list, counter) {
1292 ad.val = ad.ena = ad.run = 0;
1294 if (!collect_data(counter, aggr_cb, &ad))
1300 if (first && metric_only) {
1302 aggr_printout(counter, id, nr);
1304 if (prefix && !metric_only)
1305 fprintf(output, "%s", prefix);
1307 uval = val * counter->scale;
1308 printout(id, nr, counter, uval, prefix, run, ena, 1.0);
1310 fputc('\n', output);
1313 fputc('\n', output);
1317 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1319 FILE *output = stat_config.output;
1320 int nthreads = thread_map__nr(counter->threads);
1321 int ncpus = cpu_map__nr(counter->cpus);
1325 for (thread = 0; thread < nthreads; thread++) {
1326 u64 ena = 0, run = 0, val = 0;
1328 for (cpu = 0; cpu < ncpus; cpu++) {
1329 val += perf_counts(counter->counts, cpu, thread)->val;
1330 ena += perf_counts(counter->counts, cpu, thread)->ena;
1331 run += perf_counts(counter->counts, cpu, thread)->run;
1335 fprintf(output, "%s", prefix);
1337 uval = val * counter->scale;
1338 printout(thread, 0, counter, uval, prefix, run, ena, 1.0);
1339 fputc('\n', output);
1344 double avg, avg_enabled, avg_running;
1347 static void counter_aggr_cb(struct perf_evsel *counter, void *data,
1348 bool first __maybe_unused)
1350 struct caggr_data *cd = data;
1351 struct perf_stat_evsel *ps = counter->priv;
1353 cd->avg += avg_stats(&ps->res_stats[0]);
1354 cd->avg_enabled += avg_stats(&ps->res_stats[1]);
1355 cd->avg_running += avg_stats(&ps->res_stats[2]);
1359 * Print out the results of a single counter:
1360 * aggregated counts in system-wide mode
1362 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1364 FILE *output = stat_config.output;
1366 struct caggr_data cd = { .avg = 0.0 };
1368 if (!collect_data(counter, counter_aggr_cb, &cd))
1371 if (prefix && !metric_only)
1372 fprintf(output, "%s", prefix);
1374 uval = cd.avg * counter->scale;
1375 printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled, cd.avg);
1377 fprintf(output, "\n");
1380 static void counter_cb(struct perf_evsel *counter, void *data,
1381 bool first __maybe_unused)
1383 struct aggr_data *ad = data;
1385 ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
1386 ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
1387 ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
1391 * Print out the results of a single counter:
1392 * does not use aggregated count in system-wide
1394 static void print_counter(struct perf_evsel *counter, char *prefix)
1396 FILE *output = stat_config.output;
1401 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1402 struct aggr_data ad = { .cpu = cpu };
1404 if (!collect_data(counter, counter_cb, &ad))
1411 fprintf(output, "%s", prefix);
1413 uval = val * counter->scale;
1414 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1416 fputc('\n', output);
1420 static void print_no_aggr_metric(char *prefix)
1424 struct perf_evsel *counter;
1428 nrcpus = evsel_list->cpus->nr;
1429 for (cpu = 0; cpu < nrcpus; cpu++) {
1433 fputs(prefix, stat_config.output);
1434 evlist__for_each_entry(evsel_list, counter) {
1436 aggr_printout(counter, cpu, 0);
1439 val = perf_counts(counter->counts, cpu, 0)->val;
1440 ena = perf_counts(counter->counts, cpu, 0)->ena;
1441 run = perf_counts(counter->counts, cpu, 0)->run;
1443 uval = val * counter->scale;
1444 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1446 fputc('\n', stat_config.output);
1450 static int aggr_header_lens[] = {
1458 static const char *aggr_header_csv[] = {
1459 [AGGR_CORE] = "core,cpus,",
1460 [AGGR_SOCKET] = "socket,cpus",
1461 [AGGR_NONE] = "cpu,",
1462 [AGGR_THREAD] = "comm-pid,",
1466 static void print_metric_headers(const char *prefix, bool no_indent)
1468 struct perf_stat_output_ctx out;
1469 struct perf_evsel *counter;
1470 struct outstate os = {
1471 .fh = stat_config.output
1475 fprintf(stat_config.output, "%s", prefix);
1477 if (!csv_output && !no_indent)
1478 fprintf(stat_config.output, "%*s",
1479 aggr_header_lens[stat_config.aggr_mode], "");
1481 if (stat_config.interval)
1482 fputs("time,", stat_config.output);
1483 fputs(aggr_header_csv[stat_config.aggr_mode],
1484 stat_config.output);
1487 /* Print metrics headers only */
1488 evlist__for_each_entry(evsel_list, counter) {
1491 out.print_metric = print_metric_header;
1492 out.new_line = new_line_metric;
1493 out.force_header = true;
1495 perf_stat__print_shadow_stats(counter, 0,
1499 fputc('\n', stat_config.output);
1502 static void print_interval(char *prefix, struct timespec *ts)
1504 FILE *output = stat_config.output;
1505 static int num_print_interval;
1507 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1509 if (num_print_interval == 0 && !csv_output) {
1510 switch (stat_config.aggr_mode) {
1512 fprintf(output, "# time socket cpus");
1514 fprintf(output, " counts %*s events\n", unit_width, "unit");
1517 fprintf(output, "# time core cpus");
1519 fprintf(output, " counts %*s events\n", unit_width, "unit");
1522 fprintf(output, "# time CPU");
1524 fprintf(output, " counts %*s events\n", unit_width, "unit");
1527 fprintf(output, "# time comm-pid");
1529 fprintf(output, " counts %*s events\n", unit_width, "unit");
1533 fprintf(output, "# time");
1535 fprintf(output, " counts %*s events\n", unit_width, "unit");
1541 if (num_print_interval == 0 && metric_only)
1542 print_metric_headers(" ", true);
1543 if (++num_print_interval == 25)
1544 num_print_interval = 0;
1547 static void print_header(int argc, const char **argv)
1549 FILE *output = stat_config.output;
1555 fprintf(output, "\n");
1556 fprintf(output, " Performance counter stats for ");
1557 if (target.system_wide)
1558 fprintf(output, "\'system wide");
1559 else if (target.cpu_list)
1560 fprintf(output, "\'CPU(s) %s", target.cpu_list);
1561 else if (!target__has_task(&target)) {
1562 fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1563 for (i = 1; argv && (i < argc); i++)
1564 fprintf(output, " %s", argv[i]);
1565 } else if (target.pid)
1566 fprintf(output, "process id \'%s", target.pid);
1568 fprintf(output, "thread id \'%s", target.tid);
1570 fprintf(output, "\'");
1572 fprintf(output, " (%d runs)", run_count);
1573 fprintf(output, ":\n\n");
1577 static void print_footer(void)
1579 FILE *output = stat_config.output;
1582 fprintf(output, "\n");
1583 fprintf(output, " %17.9f seconds time elapsed",
1584 avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
1585 if (run_count > 1) {
1586 fprintf(output, " ");
1587 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1588 avg_stats(&walltime_nsecs_stats));
1590 fprintf(output, "\n\n");
1592 if (print_free_counters_hint)
1594 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1595 " echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1597 " echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1600 static void print_counters(struct timespec *ts, int argc, const char **argv)
1602 int interval = stat_config.interval;
1603 struct perf_evsel *counter;
1604 char buf[64], *prefix = NULL;
1606 /* Do not print anything if we record to the pipe. */
1607 if (STAT_RECORD && perf_stat.file.is_pipe)
1611 print_interval(prefix = buf, ts);
1613 print_header(argc, argv);
1616 static int num_print_iv;
1618 if (num_print_iv == 0 && !interval)
1619 print_metric_headers(prefix, false);
1620 if (num_print_iv++ == 25)
1622 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1623 fprintf(stat_config.output, "%s", prefix);
1626 switch (stat_config.aggr_mode) {
1632 evlist__for_each_entry(evsel_list, counter)
1633 print_aggr_thread(counter, prefix);
1636 evlist__for_each_entry(evsel_list, counter)
1637 print_counter_aggr(counter, prefix);
1639 fputc('\n', stat_config.output);
1643 print_no_aggr_metric(prefix);
1645 evlist__for_each_entry(evsel_list, counter)
1646 print_counter(counter, prefix);
1654 if (!interval && !csv_output)
1657 fflush(stat_config.output);
1660 static volatile int signr = -1;
1662 static void skip_signal(int signo)
1664 if ((child_pid == -1) || stat_config.interval)
1669 * render child_pid harmless
1670 * won't send SIGTERM to a random
1671 * process in case of race condition
1672 * and fast PID recycling
1677 static void sig_atexit(void)
1682 * avoid race condition with SIGCHLD handler
1683 * in skip_signal() which is modifying child_pid
1684 * goal is to avoid send SIGTERM to a random
1688 sigaddset(&set, SIGCHLD);
1689 sigprocmask(SIG_BLOCK, &set, &oset);
1691 if (child_pid != -1)
1692 kill(child_pid, SIGTERM);
1694 sigprocmask(SIG_SETMASK, &oset, NULL);
1699 signal(signr, SIG_DFL);
1700 kill(getpid(), signr);
1703 static int stat__set_big_num(const struct option *opt __maybe_unused,
1704 const char *s __maybe_unused, int unset)
1706 big_num_opt = unset ? 0 : 1;
1710 static int enable_metric_only(const struct option *opt __maybe_unused,
1711 const char *s __maybe_unused, int unset)
1713 force_metric_only = true;
1714 metric_only = !unset;
1718 static const struct option stat_options[] = {
1719 OPT_BOOLEAN('T', "transaction", &transaction_run,
1720 "hardware transaction statistics"),
1721 OPT_CALLBACK('e', "event", &evsel_list, "event",
1722 "event selector. use 'perf list' to list available events",
1723 parse_events_option),
1724 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1725 "event filter", parse_filter),
1726 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1727 "child tasks do not inherit counters"),
1728 OPT_STRING('p', "pid", &target.pid, "pid",
1729 "stat events on existing process id"),
1730 OPT_STRING('t', "tid", &target.tid, "tid",
1731 "stat events on existing thread id"),
1732 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1733 "system-wide collection from all CPUs"),
1734 OPT_BOOLEAN('g', "group", &group,
1735 "put the counters into a counter group"),
1736 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1737 OPT_INCR('v', "verbose", &verbose,
1738 "be more verbose (show counter open errors, etc)"),
1739 OPT_INTEGER('r', "repeat", &run_count,
1740 "repeat command and print average + stddev (max: 100, forever: 0)"),
1741 OPT_BOOLEAN('n', "null", &null_run,
1742 "null run - dont start any counters"),
1743 OPT_INCR('d', "detailed", &detailed_run,
1744 "detailed run - start a lot of events"),
1745 OPT_BOOLEAN('S', "sync", &sync_run,
1746 "call sync() before starting a run"),
1747 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1748 "print large numbers with thousands\' separators",
1750 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1751 "list of cpus to monitor in system-wide"),
1752 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1753 "disable CPU count aggregation", AGGR_NONE),
1754 OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
1755 OPT_STRING('x', "field-separator", &csv_sep, "separator",
1756 "print counts with custom separator"),
1757 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1758 "monitor event in cgroup name only", parse_cgroups),
1759 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1760 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1761 OPT_INTEGER(0, "log-fd", &output_fd,
1762 "log output to fd, instead of stderr"),
1763 OPT_STRING(0, "pre", &pre_cmd, "command",
1764 "command to run prior to the measured command"),
1765 OPT_STRING(0, "post", &post_cmd, "command",
1766 "command to run after to the measured command"),
1767 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1768 "print counts at regular interval in ms (>= 10)"),
1769 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1770 "aggregate counts per processor socket", AGGR_SOCKET),
1771 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1772 "aggregate counts per physical processor core", AGGR_CORE),
1773 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1774 "aggregate counts per thread", AGGR_THREAD),
1775 OPT_UINTEGER('D', "delay", &initial_delay,
1776 "ms to wait before starting measurement after program start"),
1777 OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
1778 "Only print computed metrics. No raw values", enable_metric_only),
1779 OPT_BOOLEAN(0, "topdown", &topdown_run,
1780 "measure topdown level 1 statistics"),
1784 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1786 return cpu_map__get_socket(map, cpu, NULL);
1789 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1791 return cpu_map__get_core(map, cpu, NULL);
1794 static int cpu_map__get_max(struct cpu_map *map)
1798 for (i = 0; i < map->nr; i++) {
1799 if (map->map[i] > max)
1806 static struct cpu_map *cpus_aggr_map;
1808 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1815 cpu = map->map[idx];
1817 if (cpus_aggr_map->map[cpu] == -1)
1818 cpus_aggr_map->map[cpu] = get_id(map, idx);
1820 return cpus_aggr_map->map[cpu];
1823 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1825 return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1828 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1830 return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1833 static int perf_stat_init_aggr_mode(void)
1837 switch (stat_config.aggr_mode) {
1839 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1840 perror("cannot build socket map");
1843 aggr_get_id = perf_stat__get_socket_cached;
1846 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1847 perror("cannot build core map");
1850 aggr_get_id = perf_stat__get_core_cached;
1861 * The evsel_list->cpus is the base we operate on,
1862 * taking the highest cpu number to be the size of
1863 * the aggregation translate cpumap.
1865 nr = cpu_map__get_max(evsel_list->cpus);
1866 cpus_aggr_map = cpu_map__empty_new(nr + 1);
1867 return cpus_aggr_map ? 0 : -ENOMEM;
1870 static void perf_stat__exit_aggr_mode(void)
1872 cpu_map__put(aggr_map);
1873 cpu_map__put(cpus_aggr_map);
1875 cpus_aggr_map = NULL;
1878 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1885 cpu = map->map[idx];
1887 if (cpu >= env->nr_cpus_avail)
1893 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1895 struct perf_env *env = data;
1896 int cpu = perf_env__get_cpu(env, map, idx);
1898 return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1901 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1903 struct perf_env *env = data;
1904 int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1907 int socket_id = env->cpu[cpu].socket_id;
1910 * Encode socket in upper 16 bits
1911 * core_id is relative to socket, and
1912 * we need a global id. So we combine
1915 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1921 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1922 struct cpu_map **sockp)
1924 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1927 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
1928 struct cpu_map **corep)
1930 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1933 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
1935 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1938 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
1940 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1943 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1945 struct perf_env *env = &st->session->header.env;
1947 switch (stat_config.aggr_mode) {
1949 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
1950 perror("cannot build socket map");
1953 aggr_get_id = perf_stat__get_socket_file;
1956 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
1957 perror("cannot build core map");
1960 aggr_get_id = perf_stat__get_core_file;
1973 static int topdown_filter_events(const char **attr, char **str, bool use_group)
1980 for (i = 0; attr[i]; i++) {
1981 if (pmu_have_event("cpu", attr[i])) {
1982 len += strlen(attr[i]) + 1;
1983 attr[i - off] = attr[i];
1987 attr[i - off] = NULL;
1989 *str = malloc(len + 1 + 2);
1999 for (i = 0; attr[i]; i++) {
2012 __weak bool arch_topdown_check_group(bool *warn)
2018 __weak void arch_topdown_group_warn(void)
2023 * Add default attributes, if there were no attributes specified or
2024 * if -d/--detailed, -d -d or -d -d -d is used:
2026 static int add_default_attributes(void)
2029 struct perf_event_attr default_attrs0[] = {
2031 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
2032 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
2033 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
2034 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
2036 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
2038 struct perf_event_attr frontend_attrs[] = {
2039 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
2041 struct perf_event_attr backend_attrs[] = {
2042 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
2044 struct perf_event_attr default_attrs1[] = {
2045 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
2046 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
2047 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
2052 * Detailed stats (-d), covering the L1 and last level data caches:
2054 struct perf_event_attr detailed_attrs[] = {
2056 { .type = PERF_TYPE_HW_CACHE,
2058 PERF_COUNT_HW_CACHE_L1D << 0 |
2059 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2060 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2062 { .type = PERF_TYPE_HW_CACHE,
2064 PERF_COUNT_HW_CACHE_L1D << 0 |
2065 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2066 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2068 { .type = PERF_TYPE_HW_CACHE,
2070 PERF_COUNT_HW_CACHE_LL << 0 |
2071 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2072 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2074 { .type = PERF_TYPE_HW_CACHE,
2076 PERF_COUNT_HW_CACHE_LL << 0 |
2077 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2078 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2082 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2084 struct perf_event_attr very_detailed_attrs[] = {
2086 { .type = PERF_TYPE_HW_CACHE,
2088 PERF_COUNT_HW_CACHE_L1I << 0 |
2089 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2090 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2092 { .type = PERF_TYPE_HW_CACHE,
2094 PERF_COUNT_HW_CACHE_L1I << 0 |
2095 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2096 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2098 { .type = PERF_TYPE_HW_CACHE,
2100 PERF_COUNT_HW_CACHE_DTLB << 0 |
2101 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2102 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2104 { .type = PERF_TYPE_HW_CACHE,
2106 PERF_COUNT_HW_CACHE_DTLB << 0 |
2107 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2108 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2110 { .type = PERF_TYPE_HW_CACHE,
2112 PERF_COUNT_HW_CACHE_ITLB << 0 |
2113 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2114 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2116 { .type = PERF_TYPE_HW_CACHE,
2118 PERF_COUNT_HW_CACHE_ITLB << 0 |
2119 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2120 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2125 * Very, very detailed stats (-d -d -d), adding prefetch events:
2127 struct perf_event_attr very_very_detailed_attrs[] = {
2129 { .type = PERF_TYPE_HW_CACHE,
2131 PERF_COUNT_HW_CACHE_L1D << 0 |
2132 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2133 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2135 { .type = PERF_TYPE_HW_CACHE,
2137 PERF_COUNT_HW_CACHE_L1D << 0 |
2138 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2139 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2142 /* Set attrs if no event is selected and !null_run: */
2146 if (transaction_run) {
2147 if (pmu_have_event("cpu", "cycles-ct") &&
2148 pmu_have_event("cpu", "el-start"))
2149 err = parse_events(evsel_list, transaction_attrs, NULL);
2151 err = parse_events(evsel_list, transaction_limited_attrs, NULL);
2153 fprintf(stderr, "Cannot set up transaction events\n");
2163 if (stat_config.aggr_mode != AGGR_GLOBAL &&
2164 stat_config.aggr_mode != AGGR_CORE) {
2165 pr_err("top down event configuration requires --per-core mode\n");
2168 stat_config.aggr_mode = AGGR_CORE;
2169 if (nr_cgroups || !target__has_cpu(&target)) {
2170 pr_err("top down event configuration requires system-wide mode (-a)\n");
2174 if (!force_metric_only)
2176 if (topdown_filter_events(topdown_attrs, &str,
2177 arch_topdown_check_group(&warn)) < 0) {
2178 pr_err("Out of memory\n");
2181 if (topdown_attrs[0] && str) {
2183 arch_topdown_group_warn();
2184 err = parse_events(evsel_list, str, NULL);
2187 "Cannot set up top down events %s: %d\n",
2193 fprintf(stderr, "System does not support topdown\n");
2199 if (!evsel_list->nr_entries) {
2200 if (target__has_cpu(&target))
2201 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2203 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2205 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2206 if (perf_evlist__add_default_attrs(evsel_list,
2207 frontend_attrs) < 0)
2210 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2211 if (perf_evlist__add_default_attrs(evsel_list,
2215 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2219 /* Detailed events get appended to the event list: */
2221 if (detailed_run < 1)
2224 /* Append detailed run extra attributes: */
2225 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2228 if (detailed_run < 2)
2231 /* Append very detailed run extra attributes: */
2232 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2235 if (detailed_run < 3)
2238 /* Append very, very detailed run extra attributes: */
2239 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2242 static const char * const stat_record_usage[] = {
2243 "perf stat record [<options>]",
2247 static void init_features(struct perf_session *session)
2251 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2252 perf_header__set_feat(&session->header, feat);
2254 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2255 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2256 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2257 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2260 static int __cmd_record(int argc, const char **argv)
2262 struct perf_session *session;
2263 struct perf_data_file *file = &perf_stat.file;
2265 argc = parse_options(argc, argv, stat_options, stat_record_usage,
2266 PARSE_OPT_STOP_AT_NON_OPTION);
2269 file->path = output_name;
2271 if (run_count != 1 || forever) {
2272 pr_err("Cannot use -r option with perf stat record.\n");
2276 session = perf_session__new(file, false, NULL);
2277 if (session == NULL) {
2278 pr_err("Perf session creation failed.\n");
2282 init_features(session);
2284 session->evlist = evsel_list;
2285 perf_stat.session = session;
2286 perf_stat.record = true;
2290 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2291 union perf_event *event,
2292 struct perf_session *session)
2294 struct stat_round_event *stat_round = &event->stat_round;
2295 struct perf_evsel *counter;
2296 struct timespec tsh, *ts = NULL;
2297 const char **argv = session->header.env.cmdline_argv;
2298 int argc = session->header.env.nr_cmdline;
2300 evlist__for_each_entry(evsel_list, counter)
2301 perf_stat_process_counter(&stat_config, counter);
2303 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2304 update_stats(&walltime_nsecs_stats, stat_round->time);
2306 if (stat_config.interval && stat_round->time) {
2307 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2308 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2312 print_counters(ts, argc, argv);
2317 int process_stat_config_event(struct perf_tool *tool,
2318 union perf_event *event,
2319 struct perf_session *session __maybe_unused)
2321 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2323 perf_event__read_stat_config(&stat_config, &event->stat_config);
2325 if (cpu_map__empty(st->cpus)) {
2326 if (st->aggr_mode != AGGR_UNSET)
2327 pr_warning("warning: processing task data, aggregation mode not set\n");
2331 if (st->aggr_mode != AGGR_UNSET)
2332 stat_config.aggr_mode = st->aggr_mode;
2334 if (perf_stat.file.is_pipe)
2335 perf_stat_init_aggr_mode();
2337 perf_stat_init_aggr_mode_file(st);
2342 static int set_maps(struct perf_stat *st)
2344 if (!st->cpus || !st->threads)
2347 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2350 perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2352 if (perf_evlist__alloc_stats(evsel_list, true))
2355 st->maps_allocated = true;
2360 int process_thread_map_event(struct perf_tool *tool,
2361 union perf_event *event,
2362 struct perf_session *session __maybe_unused)
2364 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2367 pr_warning("Extra thread map event, ignoring.\n");
2371 st->threads = thread_map__new_event(&event->thread_map);
2375 return set_maps(st);
2379 int process_cpu_map_event(struct perf_tool *tool,
2380 union perf_event *event,
2381 struct perf_session *session __maybe_unused)
2383 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2384 struct cpu_map *cpus;
2387 pr_warning("Extra cpu map event, ignoring.\n");
2391 cpus = cpu_map__new_data(&event->cpu_map.data);
2396 return set_maps(st);
2399 static const char * const stat_report_usage[] = {
2400 "perf stat report [<options>]",
2404 static struct perf_stat perf_stat = {
2406 .attr = perf_event__process_attr,
2407 .event_update = perf_event__process_event_update,
2408 .thread_map = process_thread_map_event,
2409 .cpu_map = process_cpu_map_event,
2410 .stat_config = process_stat_config_event,
2411 .stat = perf_event__process_stat_event,
2412 .stat_round = process_stat_round_event,
2414 .aggr_mode = AGGR_UNSET,
2417 static int __cmd_report(int argc, const char **argv)
2419 struct perf_session *session;
2420 const struct option options[] = {
2421 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2422 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2423 "aggregate counts per processor socket", AGGR_SOCKET),
2424 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2425 "aggregate counts per physical processor core", AGGR_CORE),
2426 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2427 "disable CPU count aggregation", AGGR_NONE),
2433 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2435 if (!input_name || !strlen(input_name)) {
2436 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2439 input_name = "perf.data";
2442 perf_stat.file.path = input_name;
2443 perf_stat.file.mode = PERF_DATA_MODE_READ;
2445 session = perf_session__new(&perf_stat.file, false, &perf_stat.tool);
2446 if (session == NULL)
2449 perf_stat.session = session;
2450 stat_config.output = stderr;
2451 evsel_list = session->evlist;
2453 ret = perf_session__process_events(session);
2457 perf_session__delete(session);
2461 static void setup_system_wide(int forks)
2464 * Make system wide (-a) the default target if
2465 * no target was specified and one of following
2466 * conditions is met:
2468 * - there's no workload specified
2469 * - there is workload specified but all requested
2470 * events are system wide events
2472 if (!target__none(&target))
2476 target.system_wide = true;
2478 struct perf_evsel *counter;
2480 evlist__for_each_entry(evsel_list, counter) {
2481 if (!counter->system_wide)
2485 if (evsel_list->nr_entries)
2486 target.system_wide = true;
2490 int cmd_stat(int argc, const char **argv)
2492 const char * const stat_usage[] = {
2493 "perf stat [<options>] [<command>]",
2496 int status = -EINVAL, run_idx;
2498 FILE *output = stderr;
2499 unsigned int interval;
2500 const char * const stat_subcommands[] = { "record", "report" };
2502 setlocale(LC_ALL, "");
2504 evsel_list = perf_evlist__new();
2505 if (evsel_list == NULL)
2508 parse_events__shrink_config_terms();
2509 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2510 (const char **) stat_usage,
2511 PARSE_OPT_STOP_AT_NON_OPTION);
2512 perf_stat__collect_metric_expr(evsel_list);
2513 perf_stat__init_shadow_stats();
2517 if (!strcmp(csv_sep, "\\t"))
2520 csv_sep = DEFAULT_SEPARATOR;
2522 if (argc && !strncmp(argv[0], "rec", 3)) {
2523 argc = __cmd_record(argc, argv);
2526 } else if (argc && !strncmp(argv[0], "rep", 3))
2527 return __cmd_report(argc, argv);
2529 interval = stat_config.interval;
2532 * For record command the -o is already taken care of.
2534 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2537 if (output_name && output_fd) {
2538 fprintf(stderr, "cannot use both --output and --log-fd\n");
2539 parse_options_usage(stat_usage, stat_options, "o", 1);
2540 parse_options_usage(NULL, stat_options, "log-fd", 0);
2544 if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2545 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2549 if (metric_only && run_count > 1) {
2550 fprintf(stderr, "--metric-only is not supported with -r\n");
2554 if (output_fd < 0) {
2555 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2556 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2562 mode = append_file ? "a" : "w";
2564 output = fopen(output_name, mode);
2566 perror("failed to create output file");
2569 clock_gettime(CLOCK_REALTIME, &tm);
2570 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2571 } else if (output_fd > 0) {
2572 mode = append_file ? "a" : "w";
2573 output = fdopen(output_fd, mode);
2575 perror("Failed opening logfd");
2580 stat_config.output = output;
2583 * let the spreadsheet do the pretty-printing
2586 /* User explicitly passed -B? */
2587 if (big_num_opt == 1) {
2588 fprintf(stderr, "-B option not supported with -x\n");
2589 parse_options_usage(stat_usage, stat_options, "B", 1);
2590 parse_options_usage(NULL, stat_options, "x", 1);
2592 } else /* Nope, so disable big number formatting */
2594 } else if (big_num_opt == 0) /* User passed --no-big-num */
2597 setup_system_wide(argc);
2599 if (run_count < 0) {
2600 pr_err("Run count must be a positive number\n");
2601 parse_options_usage(stat_usage, stat_options, "r", 1);
2603 } else if (run_count == 0) {
2608 if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
2609 fprintf(stderr, "The --per-thread option is only available "
2610 "when monitoring via -p -t options.\n");
2611 parse_options_usage(NULL, stat_options, "p", 1);
2612 parse_options_usage(NULL, stat_options, "t", 1);
2617 * no_aggr, cgroup are for system-wide only
2618 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2620 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2621 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2622 !target__has_cpu(&target)) {
2623 fprintf(stderr, "both cgroup and no-aggregation "
2624 "modes only available in system-wide mode\n");
2626 parse_options_usage(stat_usage, stat_options, "G", 1);
2627 parse_options_usage(NULL, stat_options, "A", 1);
2628 parse_options_usage(NULL, stat_options, "a", 1);
2632 if (add_default_attributes())
2635 target__validate(&target);
2637 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2638 if (target__has_task(&target)) {
2639 pr_err("Problems finding threads of monitor\n");
2640 parse_options_usage(stat_usage, stat_options, "p", 1);
2641 parse_options_usage(NULL, stat_options, "t", 1);
2642 } else if (target__has_cpu(&target)) {
2643 perror("failed to parse CPUs map");
2644 parse_options_usage(stat_usage, stat_options, "C", 1);
2645 parse_options_usage(NULL, stat_options, "a", 1);
2651 * Initialize thread_map with comm names,
2652 * so we could print it out on output.
2654 if (stat_config.aggr_mode == AGGR_THREAD)
2655 thread_map__read_comms(evsel_list->threads);
2657 if (interval && interval < 100) {
2658 if (interval < 10) {
2659 pr_err("print interval must be >= 10ms\n");
2660 parse_options_usage(stat_usage, stat_options, "I", 1);
2663 pr_warning("print interval < 100ms. "
2664 "The overhead percentage could be high in some cases. "
2665 "Please proceed with caution.\n");
2668 if (perf_evlist__alloc_stats(evsel_list, interval))
2671 if (perf_stat_init_aggr_mode())
2675 * We dont want to block the signals - that would cause
2676 * child tasks to inherit that and Ctrl-C would not work.
2677 * What we want is for Ctrl-C to work in the exec()-ed
2678 * task, but being ignored by perf stat itself:
2682 signal(SIGINT, skip_signal);
2683 signal(SIGCHLD, skip_signal);
2684 signal(SIGALRM, skip_signal);
2685 signal(SIGABRT, skip_signal);
2688 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2689 if (run_count != 1 && verbose > 0)
2690 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2693 status = run_perf_stat(argc, argv);
2694 if (forever && status != -1) {
2695 print_counters(NULL, argc, argv);
2696 perf_stat__reset_stats();
2700 if (!forever && status != -1 && !interval)
2701 print_counters(NULL, argc, argv);
2705 * We synthesize the kernel mmap record just so that older tools
2706 * don't emit warnings about not being able to resolve symbols
2707 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2708 * a saner message about no samples being in the perf.data file.
2710 * This also serves to suppress a warning about f_header.data.size == 0
2711 * in header.c at the moment 'perf stat record' gets introduced, which
2712 * is not really needed once we start adding the stat specific PERF_RECORD_
2713 * records, but the need to suppress the kptr_restrict messages in older
2714 * tools remain -acme
2716 int fd = perf_data_file__fd(&perf_stat.file);
2717 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2718 process_synthesized_event,
2719 &perf_stat.session->machines.host);
2721 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2722 "older tools may produce warnings about this file\n.");
2726 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2727 pr_err("failed to write stat round event\n");
2730 if (!perf_stat.file.is_pipe) {
2731 perf_stat.session->header.data_size += perf_stat.bytes_written;
2732 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2735 perf_session__delete(perf_stat.session);
2738 perf_stat__exit_aggr_mode();
2739 perf_evlist__free_stats(evsel_list);
2741 perf_evlist__delete(evsel_list);