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/color.h"
56 #include "util/stat.h"
57 #include "util/header.h"
58 #include "util/cpumap.h"
59 #include "util/thread.h"
60 #include "util/thread_map.h"
61 #include "util/counts.h"
62 #include "util/session.h"
63 #include "util/tool.h"
67 #include <sys/prctl.h>
71 #define DEFAULT_SEPARATOR " "
72 #define CNTR_NOT_SUPPORTED "<not supported>"
73 #define CNTR_NOT_COUNTED "<not counted>"
75 static void print_counters(struct timespec *ts, int argc, const char **argv);
77 /* Default events used for perf stat -T */
78 static const char *transaction_attrs = {
90 /* More limited version when the CPU does not have all events. */
91 static const char * transaction_limited_attrs = {
101 static struct perf_evlist *evsel_list;
103 static struct target target = {
107 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
109 static int run_count = 1;
110 static bool no_inherit = false;
111 static volatile pid_t child_pid = -1;
112 static bool null_run = false;
113 static int detailed_run = 0;
114 static bool transaction_run;
115 static bool big_num = true;
116 static int big_num_opt = -1;
117 static const char *csv_sep = NULL;
118 static bool csv_output = false;
119 static bool group = false;
120 static const char *pre_cmd = NULL;
121 static const char *post_cmd = NULL;
122 static bool sync_run = false;
123 static unsigned int initial_delay = 0;
124 static unsigned int unit_width = 4; /* strlen("unit") */
125 static bool forever = false;
126 static bool metric_only = false;
127 static struct timespec ref_time;
128 static struct cpu_map *aggr_map;
129 static aggr_get_id_t aggr_get_id;
130 static bool append_file;
131 static const char *output_name;
132 static int output_fd;
136 struct perf_data_file file;
137 struct perf_session *session;
139 struct perf_tool tool;
141 struct cpu_map *cpus;
142 struct thread_map *threads;
143 enum aggr_mode aggr_mode;
146 static struct perf_stat perf_stat;
147 #define STAT_RECORD perf_stat.record
149 static volatile int done = 0;
151 static struct perf_stat_config stat_config = {
152 .aggr_mode = AGGR_GLOBAL,
156 static inline void diff_timespec(struct timespec *r, struct timespec *a,
159 r->tv_sec = a->tv_sec - b->tv_sec;
160 if (a->tv_nsec < b->tv_nsec) {
161 r->tv_nsec = a->tv_nsec + 1000000000L - b->tv_nsec;
164 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
168 static void perf_stat__reset_stats(void)
170 perf_evlist__reset_stats(evsel_list);
171 perf_stat__reset_shadow_stats();
174 static int create_perf_stat_counter(struct perf_evsel *evsel)
176 struct perf_event_attr *attr = &evsel->attr;
178 if (stat_config.scale)
179 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
180 PERF_FORMAT_TOTAL_TIME_RUNNING;
182 attr->inherit = !no_inherit;
185 * Some events get initialized with sample_(period/type) set,
186 * like tracepoints. Clear it up for counting.
188 attr->sample_period = 0;
191 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
192 * while avoiding that older tools show confusing messages.
194 * However for pipe sessions we need to keep it zero,
195 * because script's perf_evsel__check_attr is triggered
196 * by attr->sample_type != 0, and we can't run it on
199 if (!(STAT_RECORD && perf_stat.file.is_pipe))
200 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
203 * Disabling all counters initially, they will be enabled
204 * either manually by us or by kernel via enable_on_exec
207 if (perf_evsel__is_group_leader(evsel)) {
211 * In case of initial_delay we enable tracee
214 if (target__none(&target) && !initial_delay)
215 attr->enable_on_exec = 1;
218 if (target__has_cpu(&target))
219 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
221 return perf_evsel__open_per_thread(evsel, evsel_list->threads);
225 * Does the counter have nsecs as a unit?
227 static inline int nsec_counter(struct perf_evsel *evsel)
229 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
230 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
236 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
237 union perf_event *event,
238 struct perf_sample *sample __maybe_unused,
239 struct machine *machine __maybe_unused)
241 if (perf_data_file__write(&perf_stat.file, event, event->header.size) < 0) {
242 pr_err("failed to write perf data, error: %m\n");
246 perf_stat.bytes_written += event->header.size;
250 static int write_stat_round_event(u64 tm, u64 type)
252 return perf_event__synthesize_stat_round(NULL, tm, type,
253 process_synthesized_event,
257 #define WRITE_STAT_ROUND_EVENT(time, interval) \
258 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
260 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
263 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
264 struct perf_counts_values *count)
266 struct perf_sample_id *sid = SID(counter, cpu, thread);
268 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
269 process_synthesized_event, NULL);
273 * Read out the results of a single counter:
274 * do not aggregate counts across CPUs in system-wide mode
276 static int read_counter(struct perf_evsel *counter)
278 int nthreads = thread_map__nr(evsel_list->threads);
279 int ncpus = perf_evsel__nr_cpus(counter);
282 if (!counter->supported)
285 if (counter->system_wide)
288 for (thread = 0; thread < nthreads; thread++) {
289 for (cpu = 0; cpu < ncpus; cpu++) {
290 struct perf_counts_values *count;
292 count = perf_counts(counter->counts, cpu, thread);
293 if (perf_evsel__read(counter, cpu, thread, count))
297 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
298 pr_err("failed to write stat event\n");
304 fprintf(stat_config.output,
305 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
306 perf_evsel__name(counter),
308 count->val, count->ena, count->run);
316 static void read_counters(bool close_counters)
318 struct perf_evsel *counter;
320 evlist__for_each(evsel_list, counter) {
321 if (read_counter(counter))
322 pr_debug("failed to read counter %s\n", counter->name);
324 if (perf_stat_process_counter(&stat_config, counter))
325 pr_warning("failed to process counter %s\n", counter->name);
327 if (close_counters) {
328 perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter),
329 thread_map__nr(evsel_list->threads));
334 static void process_interval(void)
336 struct timespec ts, rs;
338 read_counters(false);
340 clock_gettime(CLOCK_MONOTONIC, &ts);
341 diff_timespec(&rs, &ts, &ref_time);
344 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSECS_PER_SEC + rs.tv_nsec, INTERVAL))
345 pr_err("failed to write stat round event\n");
348 print_counters(&rs, 0, NULL);
351 static void enable_counters(void)
354 usleep(initial_delay * 1000);
357 * We need to enable counters only if:
358 * - we don't have tracee (attaching to task or cpu)
359 * - we have initial delay configured
361 if (!target__none(&target) || initial_delay)
362 perf_evlist__enable(evsel_list);
365 static volatile int workload_exec_errno;
368 * perf_evlist__prepare_workload will send a SIGUSR1
369 * if the fork fails, since we asked by setting its
370 * want_signal to true.
372 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
373 void *ucontext __maybe_unused)
375 workload_exec_errno = info->si_value.sival_int;
378 static bool has_unit(struct perf_evsel *counter)
380 return counter->unit && *counter->unit;
383 static bool has_scale(struct perf_evsel *counter)
385 return counter->scale != 1;
388 static int perf_stat_synthesize_config(bool is_pipe)
390 struct perf_evsel *counter;
394 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
395 process_synthesized_event);
397 pr_err("Couldn't synthesize attrs.\n");
403 * Synthesize other events stuff not carried within
404 * attr event - unit, scale, name
406 evlist__for_each(evsel_list, counter) {
407 if (!counter->supported)
411 * Synthesize unit and scale only if it's defined.
413 if (has_unit(counter)) {
414 err = perf_event__synthesize_event_update_unit(NULL, counter, process_synthesized_event);
416 pr_err("Couldn't synthesize evsel unit.\n");
421 if (has_scale(counter)) {
422 err = perf_event__synthesize_event_update_scale(NULL, counter, process_synthesized_event);
424 pr_err("Couldn't synthesize evsel scale.\n");
429 if (counter->own_cpus) {
430 err = perf_event__synthesize_event_update_cpus(NULL, counter, process_synthesized_event);
432 pr_err("Couldn't synthesize evsel scale.\n");
438 * Name is needed only for pipe output,
439 * perf.data carries event names.
442 err = perf_event__synthesize_event_update_name(NULL, counter, process_synthesized_event);
444 pr_err("Couldn't synthesize evsel name.\n");
450 err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
451 process_synthesized_event,
454 pr_err("Couldn't synthesize thread map.\n");
458 err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
459 process_synthesized_event, NULL);
461 pr_err("Couldn't synthesize thread map.\n");
465 err = perf_event__synthesize_stat_config(NULL, &stat_config,
466 process_synthesized_event, NULL);
468 pr_err("Couldn't synthesize config.\n");
475 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
477 static int __store_counter_ids(struct perf_evsel *counter,
478 struct cpu_map *cpus,
479 struct thread_map *threads)
483 for (cpu = 0; cpu < cpus->nr; cpu++) {
484 for (thread = 0; thread < threads->nr; thread++) {
485 int fd = FD(counter, cpu, thread);
487 if (perf_evlist__id_add_fd(evsel_list, counter,
488 cpu, thread, fd) < 0)
496 static int store_counter_ids(struct perf_evsel *counter)
498 struct cpu_map *cpus = counter->cpus;
499 struct thread_map *threads = counter->threads;
501 if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
504 return __store_counter_ids(counter, cpus, threads);
507 static int __run_perf_stat(int argc, const char **argv)
509 int interval = stat_config.interval;
511 unsigned long long t0, t1;
512 struct perf_evsel *counter;
516 const bool forks = (argc > 0);
517 bool is_pipe = STAT_RECORD ? perf_stat.file.is_pipe : false;
520 ts.tv_sec = interval / 1000;
521 ts.tv_nsec = (interval % 1000) * 1000000;
528 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
529 workload_exec_failed_signal) < 0) {
530 perror("failed to prepare workload");
533 child_pid = evsel_list->workload.pid;
537 perf_evlist__set_leader(evsel_list);
539 evlist__for_each(evsel_list, counter) {
540 if (create_perf_stat_counter(counter) < 0) {
542 * PPC returns ENXIO for HW counters until 2.6.37
543 * (behavior changed with commit b0a873e).
545 if (errno == EINVAL || errno == ENOSYS ||
546 errno == ENOENT || errno == EOPNOTSUPP ||
549 ui__warning("%s event is not supported by the kernel.\n",
550 perf_evsel__name(counter));
551 counter->supported = false;
553 if ((counter->leader != counter) ||
554 !(counter->leader->nr_members > 1))
558 perf_evsel__open_strerror(counter, &target,
559 errno, msg, sizeof(msg));
560 ui__error("%s\n", msg);
563 kill(child_pid, SIGTERM);
567 counter->supported = true;
569 l = strlen(counter->unit);
573 if (STAT_RECORD && store_counter_ids(counter))
577 if (perf_evlist__apply_filters(evsel_list, &counter)) {
578 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
579 counter->filter, perf_evsel__name(counter), errno,
580 strerror_r(errno, msg, sizeof(msg)));
585 int err, fd = perf_data_file__fd(&perf_stat.file);
588 err = perf_header__write_pipe(perf_data_file__fd(&perf_stat.file));
590 err = perf_session__write_header(perf_stat.session, evsel_list,
597 err = perf_stat_synthesize_config(is_pipe);
603 * Enable counters and exec the command:
606 clock_gettime(CLOCK_MONOTONIC, &ref_time);
609 perf_evlist__start_workload(evsel_list);
613 while (!waitpid(child_pid, &status, WNOHANG)) {
614 nanosleep(&ts, NULL);
620 if (workload_exec_errno) {
621 const char *emsg = strerror_r(workload_exec_errno, msg, sizeof(msg));
622 pr_err("Workload failed: %s\n", emsg);
626 if (WIFSIGNALED(status))
627 psignal(WTERMSIG(status), argv[0]);
631 nanosleep(&ts, NULL);
639 update_stats(&walltime_nsecs_stats, t1 - t0);
643 return WEXITSTATUS(status);
646 static int run_perf_stat(int argc, const char **argv)
651 ret = system(pre_cmd);
659 ret = __run_perf_stat(argc, argv);
664 ret = system(post_cmd);
672 static void print_running(u64 run, u64 ena)
675 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
679 ena ? 100.0 * run / ena : 100.0);
680 } else if (run != ena) {
681 fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena);
685 static void print_noise_pct(double total, double avg)
687 double pct = rel_stddev_stats(total, avg);
690 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
692 fprintf(stat_config.output, " ( +-%6.2f%% )", pct);
695 static void print_noise(struct perf_evsel *evsel, double avg)
697 struct perf_stat_evsel *ps;
703 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
706 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
708 switch (stat_config.aggr_mode) {
710 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
711 cpu_map__id_to_socket(id),
713 cpu_map__id_to_cpu(id),
720 fprintf(stat_config.output, "S%*d%s%*d%s",
729 fprintf(stat_config.output, "CPU%*d%s",
731 perf_evsel__cpus(evsel)->map[id], csv_sep);
734 fprintf(stat_config.output, "%*s-%*d%s",
736 thread_map__comm(evsel->threads, id),
738 thread_map__pid(evsel->threads, id),
754 struct perf_evsel *evsel;
757 #define METRIC_LEN 35
759 static void new_line_std(void *ctx)
761 struct outstate *os = ctx;
766 static void do_new_line_std(struct outstate *os)
769 fputs(os->prefix, os->fh);
770 aggr_printout(os->evsel, os->id, os->nr);
771 if (stat_config.aggr_mode == AGGR_NONE)
772 fprintf(os->fh, " ");
773 fprintf(os->fh, " ");
776 static void print_metric_std(void *ctx, const char *color, const char *fmt,
777 const char *unit, double val)
779 struct outstate *os = ctx;
782 bool newline = os->newline;
786 if (unit == NULL || fmt == NULL) {
787 fprintf(out, "%-*s", METRIC_LEN, "");
794 n = fprintf(out, " # ");
796 n += color_fprintf(out, color, fmt, val);
798 n += fprintf(out, fmt, val);
799 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
802 static void new_line_csv(void *ctx)
804 struct outstate *os = ctx;
809 fprintf(os->fh, "%s%s", os->prefix, csv_sep);
810 aggr_printout(os->evsel, os->id, os->nr);
811 for (i = 0; i < os->nfields; i++)
812 fputs(csv_sep, os->fh);
815 static void print_metric_csv(void *ctx,
816 const char *color __maybe_unused,
817 const char *fmt, const char *unit, double val)
819 struct outstate *os = ctx;
821 char buf[64], *vals, *ends;
823 if (unit == NULL || fmt == NULL) {
824 fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
827 snprintf(buf, sizeof(buf), fmt, val);
829 while (isspace(*vals))
832 while (isdigit(*ends) || *ends == '.')
835 while (isspace(*unit))
837 fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
840 #define METRIC_ONLY_LEN 20
842 /* Filter out some columns that don't work well in metrics only mode */
844 static bool valid_only_metric(const char *unit)
848 if (strstr(unit, "/sec") ||
849 strstr(unit, "hz") ||
850 strstr(unit, "Hz") ||
851 strstr(unit, "CPUs utilized"))
856 static const char *fixunit(char *buf, struct perf_evsel *evsel,
859 if (!strncmp(unit, "of all", 6)) {
860 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
867 static void print_metric_only(void *ctx, const char *color, const char *fmt,
868 const char *unit, double val)
870 struct outstate *os = ctx;
874 unsigned mlen = METRIC_ONLY_LEN;
876 if (!valid_only_metric(unit))
878 unit = fixunit(buf, os->evsel, unit);
880 n = color_fprintf(out, color, fmt, val);
882 n = fprintf(out, fmt, val);
883 if (n > METRIC_ONLY_LEN)
885 if (mlen < strlen(unit))
886 mlen = strlen(unit) + 1;
887 fprintf(out, "%*s", mlen - n, "");
890 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
892 const char *unit, double val)
894 struct outstate *os = ctx;
896 char buf[64], *vals, *ends;
899 if (!valid_only_metric(unit))
901 unit = fixunit(tbuf, os->evsel, unit);
902 snprintf(buf, sizeof buf, fmt, val);
904 while (isspace(*vals))
907 while (isdigit(*ends) || *ends == '.')
910 fprintf(out, "%s%s", vals, csv_sep);
913 static void new_line_metric(void *ctx __maybe_unused)
917 static void print_metric_header(void *ctx, const char *color __maybe_unused,
918 const char *fmt __maybe_unused,
919 const char *unit, double val __maybe_unused)
921 struct outstate *os = ctx;
924 if (!valid_only_metric(unit))
926 unit = fixunit(tbuf, os->evsel, unit);
928 fprintf(os->fh, "%s%s", unit, csv_sep);
930 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
933 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
935 FILE *output = stat_config.output;
936 double msecs = avg / 1e6;
937 const char *fmt_v, *fmt_n;
940 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
941 fmt_n = csv_output ? "%s" : "%-25s";
943 aggr_printout(evsel, id, nr);
945 scnprintf(name, sizeof(name), "%s%s",
946 perf_evsel__name(evsel), csv_output ? "" : " (msec)");
948 fprintf(output, fmt_v, msecs, csv_sep);
951 fprintf(output, "%s%s", evsel->unit, csv_sep);
953 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
955 fprintf(output, fmt_n, name);
958 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
961 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
968 if (stat_config.aggr_mode == AGGR_NONE)
971 if (stat_config.aggr_mode == AGGR_GLOBAL)
974 for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
975 int cpu2 = perf_evsel__cpus(evsel)->map[i];
977 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
983 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
985 FILE *output = stat_config.output;
986 double sc = evsel->scale;
990 fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
993 fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
995 fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
998 aggr_printout(evsel, id, nr);
1000 fprintf(output, fmt, avg, csv_sep);
1003 fprintf(output, "%-*s%s",
1004 csv_output ? 0 : unit_width,
1005 evsel->unit, csv_sep);
1007 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1010 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1013 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
1014 char *prefix, u64 run, u64 ena, double noise)
1016 struct perf_stat_output_ctx out;
1017 struct outstate os = {
1018 .fh = stat_config.output,
1019 .prefix = prefix ? prefix : "",
1024 print_metric_t pm = print_metric_std;
1028 nl = new_line_metric;
1030 pm = print_metric_only_csv;
1032 pm = print_metric_only;
1036 if (csv_output && !metric_only) {
1037 static int aggr_fields[] = {
1045 pm = print_metric_csv;
1048 os.nfields += aggr_fields[stat_config.aggr_mode];
1052 if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1054 pm(&os, NULL, "", "", 0);
1057 aggr_printout(counter, id, nr);
1059 fprintf(stat_config.output, "%*s%s",
1060 csv_output ? 0 : 18,
1061 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1064 fprintf(stat_config.output, "%-*s%s",
1065 csv_output ? 0 : unit_width,
1066 counter->unit, csv_sep);
1068 fprintf(stat_config.output, "%*s",
1069 csv_output ? 0 : -25,
1070 perf_evsel__name(counter));
1073 fprintf(stat_config.output, "%s%s",
1074 csv_sep, counter->cgrp->name);
1077 pm(&os, NULL, NULL, "", 0);
1078 print_noise(counter, noise);
1079 print_running(run, ena);
1081 pm(&os, NULL, NULL, "", 0);
1087 else if (nsec_counter(counter))
1088 nsec_printout(id, nr, counter, uval);
1090 abs_printout(id, nr, counter, uval);
1092 out.print_metric = pm;
1096 if (csv_output && !metric_only) {
1097 print_noise(counter, noise);
1098 print_running(run, ena);
1101 perf_stat__print_shadow_stats(counter, uval,
1102 first_shadow_cpu(counter, id),
1104 if (!csv_output && !metric_only) {
1105 print_noise(counter, noise);
1106 print_running(run, ena);
1110 static void aggr_update_shadow(void)
1114 struct perf_evsel *counter;
1116 for (s = 0; s < aggr_map->nr; s++) {
1117 id = aggr_map->map[s];
1118 evlist__for_each(evsel_list, counter) {
1120 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1121 s2 = aggr_get_id(evsel_list->cpus, cpu);
1124 val += perf_counts(counter->counts, cpu, 0)->val;
1126 val = val * counter->scale;
1127 perf_stat__update_shadow_stats(counter, &val,
1128 first_shadow_cpu(counter, id));
1133 static void print_aggr(char *prefix)
1135 FILE *output = stat_config.output;
1136 struct perf_evsel *counter;
1137 int cpu, s, s2, id, nr;
1142 if (!(aggr_map || aggr_get_id))
1145 aggr_update_shadow();
1148 * With metric_only everything is on a single line.
1149 * Without each counter has its own line.
1151 for (s = 0; s < aggr_map->nr; s++) {
1152 if (prefix && metric_only)
1153 fprintf(output, "%s", prefix);
1155 id = aggr_map->map[s];
1157 evlist__for_each(evsel_list, counter) {
1158 val = ena = run = 0;
1160 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1161 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1164 val += perf_counts(counter->counts, cpu, 0)->val;
1165 ena += perf_counts(counter->counts, cpu, 0)->ena;
1166 run += perf_counts(counter->counts, cpu, 0)->run;
1169 if (first && metric_only) {
1171 aggr_printout(counter, id, nr);
1173 if (prefix && !metric_only)
1174 fprintf(output, "%s", prefix);
1176 uval = val * counter->scale;
1177 printout(id, nr, counter, uval, prefix, run, ena, 1.0);
1179 fputc('\n', output);
1182 fputc('\n', output);
1186 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1188 FILE *output = stat_config.output;
1189 int nthreads = thread_map__nr(counter->threads);
1190 int ncpus = cpu_map__nr(counter->cpus);
1194 for (thread = 0; thread < nthreads; thread++) {
1195 u64 ena = 0, run = 0, val = 0;
1197 for (cpu = 0; cpu < ncpus; cpu++) {
1198 val += perf_counts(counter->counts, cpu, thread)->val;
1199 ena += perf_counts(counter->counts, cpu, thread)->ena;
1200 run += perf_counts(counter->counts, cpu, thread)->run;
1204 fprintf(output, "%s", prefix);
1206 uval = val * counter->scale;
1207 printout(thread, 0, counter, uval, prefix, run, ena, 1.0);
1208 fputc('\n', output);
1213 * Print out the results of a single counter:
1214 * aggregated counts in system-wide mode
1216 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1218 FILE *output = stat_config.output;
1219 struct perf_stat_evsel *ps = counter->priv;
1220 double avg = avg_stats(&ps->res_stats[0]);
1222 double avg_enabled, avg_running;
1224 avg_enabled = avg_stats(&ps->res_stats[1]);
1225 avg_running = avg_stats(&ps->res_stats[2]);
1227 if (prefix && !metric_only)
1228 fprintf(output, "%s", prefix);
1230 uval = avg * counter->scale;
1231 printout(-1, 0, counter, uval, prefix, avg_running, avg_enabled, avg);
1233 fprintf(output, "\n");
1237 * Print out the results of a single counter:
1238 * does not use aggregated count in system-wide
1240 static void print_counter(struct perf_evsel *counter, char *prefix)
1242 FILE *output = stat_config.output;
1247 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1248 val = perf_counts(counter->counts, cpu, 0)->val;
1249 ena = perf_counts(counter->counts, cpu, 0)->ena;
1250 run = perf_counts(counter->counts, cpu, 0)->run;
1253 fprintf(output, "%s", prefix);
1255 uval = val * counter->scale;
1256 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1258 fputc('\n', output);
1262 static void print_no_aggr_metric(char *prefix)
1266 struct perf_evsel *counter;
1270 nrcpus = evsel_list->cpus->nr;
1271 for (cpu = 0; cpu < nrcpus; cpu++) {
1275 fputs(prefix, stat_config.output);
1276 evlist__for_each(evsel_list, counter) {
1278 aggr_printout(counter, cpu, 0);
1281 val = perf_counts(counter->counts, cpu, 0)->val;
1282 ena = perf_counts(counter->counts, cpu, 0)->ena;
1283 run = perf_counts(counter->counts, cpu, 0)->run;
1285 uval = val * counter->scale;
1286 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1288 fputc('\n', stat_config.output);
1292 static int aggr_header_lens[] = {
1300 static void print_metric_headers(char *prefix)
1302 struct perf_stat_output_ctx out;
1303 struct perf_evsel *counter;
1304 struct outstate os = {
1305 .fh = stat_config.output
1309 fprintf(stat_config.output, "%s", prefix);
1312 fprintf(stat_config.output, "%*s",
1313 aggr_header_lens[stat_config.aggr_mode], "");
1315 /* Print metrics headers only */
1316 evlist__for_each(evsel_list, counter) {
1319 out.print_metric = print_metric_header;
1320 out.new_line = new_line_metric;
1322 perf_stat__print_shadow_stats(counter, 0,
1326 fputc('\n', stat_config.output);
1329 static void print_interval(char *prefix, struct timespec *ts)
1331 FILE *output = stat_config.output;
1332 static int num_print_interval;
1334 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1336 if (num_print_interval == 0 && !csv_output && !metric_only) {
1337 switch (stat_config.aggr_mode) {
1339 fprintf(output, "# time socket cpus counts %*s events\n", unit_width, "unit");
1342 fprintf(output, "# time core cpus counts %*s events\n", unit_width, "unit");
1345 fprintf(output, "# time CPU counts %*s events\n", unit_width, "unit");
1348 fprintf(output, "# time comm-pid counts %*s events\n", unit_width, "unit");
1352 fprintf(output, "# time counts %*s events\n", unit_width, "unit");
1358 if (++num_print_interval == 25)
1359 num_print_interval = 0;
1362 static void print_header(int argc, const char **argv)
1364 FILE *output = stat_config.output;
1370 fprintf(output, "\n");
1371 fprintf(output, " Performance counter stats for ");
1372 if (target.system_wide)
1373 fprintf(output, "\'system wide");
1374 else if (target.cpu_list)
1375 fprintf(output, "\'CPU(s) %s", target.cpu_list);
1376 else if (!target__has_task(&target)) {
1377 fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1378 for (i = 1; argv && (i < argc); i++)
1379 fprintf(output, " %s", argv[i]);
1380 } else if (target.pid)
1381 fprintf(output, "process id \'%s", target.pid);
1383 fprintf(output, "thread id \'%s", target.tid);
1385 fprintf(output, "\'");
1387 fprintf(output, " (%d runs)", run_count);
1388 fprintf(output, ":\n\n");
1392 static void print_footer(void)
1394 FILE *output = stat_config.output;
1397 fprintf(output, "\n");
1398 fprintf(output, " %17.9f seconds time elapsed",
1399 avg_stats(&walltime_nsecs_stats)/1e9);
1400 if (run_count > 1) {
1401 fprintf(output, " ");
1402 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1403 avg_stats(&walltime_nsecs_stats));
1405 fprintf(output, "\n\n");
1408 static void print_counters(struct timespec *ts, int argc, const char **argv)
1410 int interval = stat_config.interval;
1411 struct perf_evsel *counter;
1412 char buf[64], *prefix = NULL;
1414 /* Do not print anything if we record to the pipe. */
1415 if (STAT_RECORD && perf_stat.file.is_pipe)
1419 print_interval(prefix = buf, ts);
1421 print_header(argc, argv);
1424 static int num_print_iv;
1426 if (num_print_iv == 0)
1427 print_metric_headers(prefix);
1428 if (num_print_iv++ == 25)
1430 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1431 fprintf(stat_config.output, "%s", prefix);
1434 switch (stat_config.aggr_mode) {
1440 evlist__for_each(evsel_list, counter)
1441 print_aggr_thread(counter, prefix);
1444 evlist__for_each(evsel_list, counter)
1445 print_counter_aggr(counter, prefix);
1447 fputc('\n', stat_config.output);
1451 print_no_aggr_metric(prefix);
1453 evlist__for_each(evsel_list, counter)
1454 print_counter(counter, prefix);
1462 if (!interval && !csv_output)
1465 fflush(stat_config.output);
1468 static volatile int signr = -1;
1470 static void skip_signal(int signo)
1472 if ((child_pid == -1) || stat_config.interval)
1477 * render child_pid harmless
1478 * won't send SIGTERM to a random
1479 * process in case of race condition
1480 * and fast PID recycling
1485 static void sig_atexit(void)
1490 * avoid race condition with SIGCHLD handler
1491 * in skip_signal() which is modifying child_pid
1492 * goal is to avoid send SIGTERM to a random
1496 sigaddset(&set, SIGCHLD);
1497 sigprocmask(SIG_BLOCK, &set, &oset);
1499 if (child_pid != -1)
1500 kill(child_pid, SIGTERM);
1502 sigprocmask(SIG_SETMASK, &oset, NULL);
1507 signal(signr, SIG_DFL);
1508 kill(getpid(), signr);
1511 static int stat__set_big_num(const struct option *opt __maybe_unused,
1512 const char *s __maybe_unused, int unset)
1514 big_num_opt = unset ? 0 : 1;
1518 static const struct option stat_options[] = {
1519 OPT_BOOLEAN('T', "transaction", &transaction_run,
1520 "hardware transaction statistics"),
1521 OPT_CALLBACK('e', "event", &evsel_list, "event",
1522 "event selector. use 'perf list' to list available events",
1523 parse_events_option),
1524 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1525 "event filter", parse_filter),
1526 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1527 "child tasks do not inherit counters"),
1528 OPT_STRING('p', "pid", &target.pid, "pid",
1529 "stat events on existing process id"),
1530 OPT_STRING('t', "tid", &target.tid, "tid",
1531 "stat events on existing thread id"),
1532 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1533 "system-wide collection from all CPUs"),
1534 OPT_BOOLEAN('g', "group", &group,
1535 "put the counters into a counter group"),
1536 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1537 OPT_INCR('v', "verbose", &verbose,
1538 "be more verbose (show counter open errors, etc)"),
1539 OPT_INTEGER('r', "repeat", &run_count,
1540 "repeat command and print average + stddev (max: 100, forever: 0)"),
1541 OPT_BOOLEAN('n', "null", &null_run,
1542 "null run - dont start any counters"),
1543 OPT_INCR('d', "detailed", &detailed_run,
1544 "detailed run - start a lot of events"),
1545 OPT_BOOLEAN('S', "sync", &sync_run,
1546 "call sync() before starting a run"),
1547 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1548 "print large numbers with thousands\' separators",
1550 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1551 "list of cpus to monitor in system-wide"),
1552 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1553 "disable CPU count aggregation", AGGR_NONE),
1554 OPT_STRING('x', "field-separator", &csv_sep, "separator",
1555 "print counts with custom separator"),
1556 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1557 "monitor event in cgroup name only", parse_cgroups),
1558 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1559 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1560 OPT_INTEGER(0, "log-fd", &output_fd,
1561 "log output to fd, instead of stderr"),
1562 OPT_STRING(0, "pre", &pre_cmd, "command",
1563 "command to run prior to the measured command"),
1564 OPT_STRING(0, "post", &post_cmd, "command",
1565 "command to run after to the measured command"),
1566 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1567 "print counts at regular interval in ms (>= 10)"),
1568 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1569 "aggregate counts per processor socket", AGGR_SOCKET),
1570 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1571 "aggregate counts per physical processor core", AGGR_CORE),
1572 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1573 "aggregate counts per thread", AGGR_THREAD),
1574 OPT_UINTEGER('D', "delay", &initial_delay,
1575 "ms to wait before starting measurement after program start"),
1576 OPT_BOOLEAN(0, "metric-only", &metric_only,
1577 "Only print computed metrics. No raw values"),
1581 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1583 return cpu_map__get_socket(map, cpu, NULL);
1586 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1588 return cpu_map__get_core(map, cpu, NULL);
1591 static int cpu_map__get_max(struct cpu_map *map)
1595 for (i = 0; i < map->nr; i++) {
1596 if (map->map[i] > max)
1603 static struct cpu_map *cpus_aggr_map;
1605 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1612 cpu = map->map[idx];
1614 if (cpus_aggr_map->map[cpu] == -1)
1615 cpus_aggr_map->map[cpu] = get_id(map, idx);
1617 return cpus_aggr_map->map[cpu];
1620 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1622 return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1625 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1627 return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1630 static int perf_stat_init_aggr_mode(void)
1634 switch (stat_config.aggr_mode) {
1636 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1637 perror("cannot build socket map");
1640 aggr_get_id = perf_stat__get_socket_cached;
1643 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1644 perror("cannot build core map");
1647 aggr_get_id = perf_stat__get_core_cached;
1658 * The evsel_list->cpus is the base we operate on,
1659 * taking the highest cpu number to be the size of
1660 * the aggregation translate cpumap.
1662 nr = cpu_map__get_max(evsel_list->cpus);
1663 cpus_aggr_map = cpu_map__empty_new(nr + 1);
1664 return cpus_aggr_map ? 0 : -ENOMEM;
1667 static void perf_stat__exit_aggr_mode(void)
1669 cpu_map__put(aggr_map);
1670 cpu_map__put(cpus_aggr_map);
1672 cpus_aggr_map = NULL;
1675 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1682 cpu = map->map[idx];
1684 if (cpu >= env->nr_cpus_online)
1690 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1692 struct perf_env *env = data;
1693 int cpu = perf_env__get_cpu(env, map, idx);
1695 return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1698 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1700 struct perf_env *env = data;
1701 int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1704 int socket_id = env->cpu[cpu].socket_id;
1707 * Encode socket in upper 16 bits
1708 * core_id is relative to socket, and
1709 * we need a global id. So we combine
1712 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1718 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1719 struct cpu_map **sockp)
1721 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1724 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
1725 struct cpu_map **corep)
1727 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1730 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
1732 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1735 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
1737 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1740 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1742 struct perf_env *env = &st->session->header.env;
1744 switch (stat_config.aggr_mode) {
1746 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
1747 perror("cannot build socket map");
1750 aggr_get_id = perf_stat__get_socket_file;
1753 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
1754 perror("cannot build core map");
1757 aggr_get_id = perf_stat__get_core_file;
1771 * Add default attributes, if there were no attributes specified or
1772 * if -d/--detailed, -d -d or -d -d -d is used:
1774 static int add_default_attributes(void)
1776 struct perf_event_attr default_attrs0[] = {
1778 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
1779 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
1780 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
1781 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
1783 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
1785 struct perf_event_attr frontend_attrs[] = {
1786 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1788 struct perf_event_attr backend_attrs[] = {
1789 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
1791 struct perf_event_attr default_attrs1[] = {
1792 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
1793 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
1794 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
1799 * Detailed stats (-d), covering the L1 and last level data caches:
1801 struct perf_event_attr detailed_attrs[] = {
1803 { .type = PERF_TYPE_HW_CACHE,
1805 PERF_COUNT_HW_CACHE_L1D << 0 |
1806 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1807 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1809 { .type = PERF_TYPE_HW_CACHE,
1811 PERF_COUNT_HW_CACHE_L1D << 0 |
1812 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1813 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1815 { .type = PERF_TYPE_HW_CACHE,
1817 PERF_COUNT_HW_CACHE_LL << 0 |
1818 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1819 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1821 { .type = PERF_TYPE_HW_CACHE,
1823 PERF_COUNT_HW_CACHE_LL << 0 |
1824 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1825 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1829 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1831 struct perf_event_attr very_detailed_attrs[] = {
1833 { .type = PERF_TYPE_HW_CACHE,
1835 PERF_COUNT_HW_CACHE_L1I << 0 |
1836 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1837 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1839 { .type = PERF_TYPE_HW_CACHE,
1841 PERF_COUNT_HW_CACHE_L1I << 0 |
1842 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1843 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1845 { .type = PERF_TYPE_HW_CACHE,
1847 PERF_COUNT_HW_CACHE_DTLB << 0 |
1848 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1849 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1851 { .type = PERF_TYPE_HW_CACHE,
1853 PERF_COUNT_HW_CACHE_DTLB << 0 |
1854 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1855 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1857 { .type = PERF_TYPE_HW_CACHE,
1859 PERF_COUNT_HW_CACHE_ITLB << 0 |
1860 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1861 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1863 { .type = PERF_TYPE_HW_CACHE,
1865 PERF_COUNT_HW_CACHE_ITLB << 0 |
1866 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1867 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1872 * Very, very detailed stats (-d -d -d), adding prefetch events:
1874 struct perf_event_attr very_very_detailed_attrs[] = {
1876 { .type = PERF_TYPE_HW_CACHE,
1878 PERF_COUNT_HW_CACHE_L1D << 0 |
1879 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1880 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1882 { .type = PERF_TYPE_HW_CACHE,
1884 PERF_COUNT_HW_CACHE_L1D << 0 |
1885 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1886 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1889 /* Set attrs if no event is selected and !null_run: */
1893 if (transaction_run) {
1895 if (pmu_have_event("cpu", "cycles-ct") &&
1896 pmu_have_event("cpu", "el-start"))
1897 err = parse_events(evsel_list, transaction_attrs, NULL);
1899 err = parse_events(evsel_list, transaction_limited_attrs, NULL);
1901 fprintf(stderr, "Cannot set up transaction events\n");
1907 if (!evsel_list->nr_entries) {
1908 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
1910 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
1911 if (perf_evlist__add_default_attrs(evsel_list,
1912 frontend_attrs) < 0)
1915 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
1916 if (perf_evlist__add_default_attrs(evsel_list,
1920 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
1924 /* Detailed events get appended to the event list: */
1926 if (detailed_run < 1)
1929 /* Append detailed run extra attributes: */
1930 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1933 if (detailed_run < 2)
1936 /* Append very detailed run extra attributes: */
1937 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1940 if (detailed_run < 3)
1943 /* Append very, very detailed run extra attributes: */
1944 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1947 static const char * const stat_record_usage[] = {
1948 "perf stat record [<options>]",
1952 static void init_features(struct perf_session *session)
1956 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
1957 perf_header__set_feat(&session->header, feat);
1959 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
1960 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
1961 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
1962 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
1965 static int __cmd_record(int argc, const char **argv)
1967 struct perf_session *session;
1968 struct perf_data_file *file = &perf_stat.file;
1970 argc = parse_options(argc, argv, stat_options, stat_record_usage,
1971 PARSE_OPT_STOP_AT_NON_OPTION);
1974 file->path = output_name;
1976 if (run_count != 1 || forever) {
1977 pr_err("Cannot use -r option with perf stat record.\n");
1981 session = perf_session__new(file, false, NULL);
1982 if (session == NULL) {
1983 pr_err("Perf session creation failed.\n");
1987 init_features(session);
1989 session->evlist = evsel_list;
1990 perf_stat.session = session;
1991 perf_stat.record = true;
1995 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
1996 union perf_event *event,
1997 struct perf_session *session)
1999 struct stat_round_event *stat_round = &event->stat_round;
2000 struct perf_evsel *counter;
2001 struct timespec tsh, *ts = NULL;
2002 const char **argv = session->header.env.cmdline_argv;
2003 int argc = session->header.env.nr_cmdline;
2005 evlist__for_each(evsel_list, counter)
2006 perf_stat_process_counter(&stat_config, counter);
2008 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2009 update_stats(&walltime_nsecs_stats, stat_round->time);
2011 if (stat_config.interval && stat_round->time) {
2012 tsh.tv_sec = stat_round->time / NSECS_PER_SEC;
2013 tsh.tv_nsec = stat_round->time % NSECS_PER_SEC;
2017 print_counters(ts, argc, argv);
2022 int process_stat_config_event(struct perf_tool *tool __maybe_unused,
2023 union perf_event *event,
2024 struct perf_session *session __maybe_unused)
2026 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2028 perf_event__read_stat_config(&stat_config, &event->stat_config);
2030 if (cpu_map__empty(st->cpus)) {
2031 if (st->aggr_mode != AGGR_UNSET)
2032 pr_warning("warning: processing task data, aggregation mode not set\n");
2036 if (st->aggr_mode != AGGR_UNSET)
2037 stat_config.aggr_mode = st->aggr_mode;
2039 if (perf_stat.file.is_pipe)
2040 perf_stat_init_aggr_mode();
2042 perf_stat_init_aggr_mode_file(st);
2047 static int set_maps(struct perf_stat *st)
2049 if (!st->cpus || !st->threads)
2052 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2055 perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2057 if (perf_evlist__alloc_stats(evsel_list, true))
2060 st->maps_allocated = true;
2065 int process_thread_map_event(struct perf_tool *tool __maybe_unused,
2066 union perf_event *event,
2067 struct perf_session *session __maybe_unused)
2069 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2072 pr_warning("Extra thread map event, ignoring.\n");
2076 st->threads = thread_map__new_event(&event->thread_map);
2080 return set_maps(st);
2084 int process_cpu_map_event(struct perf_tool *tool __maybe_unused,
2085 union perf_event *event,
2086 struct perf_session *session __maybe_unused)
2088 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2089 struct cpu_map *cpus;
2092 pr_warning("Extra cpu map event, ignoring.\n");
2096 cpus = cpu_map__new_data(&event->cpu_map.data);
2101 return set_maps(st);
2104 static const char * const stat_report_usage[] = {
2105 "perf stat report [<options>]",
2109 static struct perf_stat perf_stat = {
2111 .attr = perf_event__process_attr,
2112 .event_update = perf_event__process_event_update,
2113 .thread_map = process_thread_map_event,
2114 .cpu_map = process_cpu_map_event,
2115 .stat_config = process_stat_config_event,
2116 .stat = perf_event__process_stat_event,
2117 .stat_round = process_stat_round_event,
2119 .aggr_mode = AGGR_UNSET,
2122 static int __cmd_report(int argc, const char **argv)
2124 struct perf_session *session;
2125 const struct option options[] = {
2126 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2127 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2128 "aggregate counts per processor socket", AGGR_SOCKET),
2129 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2130 "aggregate counts per physical processor core", AGGR_CORE),
2131 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2132 "disable CPU count aggregation", AGGR_NONE),
2138 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2140 if (!input_name || !strlen(input_name)) {
2141 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2144 input_name = "perf.data";
2147 perf_stat.file.path = input_name;
2148 perf_stat.file.mode = PERF_DATA_MODE_READ;
2150 session = perf_session__new(&perf_stat.file, false, &perf_stat.tool);
2151 if (session == NULL)
2154 perf_stat.session = session;
2155 stat_config.output = stderr;
2156 evsel_list = session->evlist;
2158 ret = perf_session__process_events(session);
2162 perf_session__delete(session);
2166 int cmd_stat(int argc, const char **argv, const char *prefix __maybe_unused)
2168 const char * const stat_usage[] = {
2169 "perf stat [<options>] [<command>]",
2172 int status = -EINVAL, run_idx;
2174 FILE *output = stderr;
2175 unsigned int interval;
2176 const char * const stat_subcommands[] = { "record", "report" };
2178 setlocale(LC_ALL, "");
2180 evsel_list = perf_evlist__new();
2181 if (evsel_list == NULL)
2184 parse_events__shrink_config_terms();
2185 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2186 (const char **) stat_usage,
2187 PARSE_OPT_STOP_AT_NON_OPTION);
2188 perf_stat__init_shadow_stats();
2192 if (!strcmp(csv_sep, "\\t"))
2195 csv_sep = DEFAULT_SEPARATOR;
2197 if (argc && !strncmp(argv[0], "rec", 3)) {
2198 argc = __cmd_record(argc, argv);
2201 } else if (argc && !strncmp(argv[0], "rep", 3))
2202 return __cmd_report(argc, argv);
2204 interval = stat_config.interval;
2207 * For record command the -o is already taken care of.
2209 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2212 if (output_name && output_fd) {
2213 fprintf(stderr, "cannot use both --output and --log-fd\n");
2214 parse_options_usage(stat_usage, stat_options, "o", 1);
2215 parse_options_usage(NULL, stat_options, "log-fd", 0);
2219 if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2220 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2224 if (metric_only && run_count > 1) {
2225 fprintf(stderr, "--metric-only is not supported with -r\n");
2229 if (output_fd < 0) {
2230 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2231 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2237 mode = append_file ? "a" : "w";
2239 output = fopen(output_name, mode);
2241 perror("failed to create output file");
2244 clock_gettime(CLOCK_REALTIME, &tm);
2245 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2246 } else if (output_fd > 0) {
2247 mode = append_file ? "a" : "w";
2248 output = fdopen(output_fd, mode);
2250 perror("Failed opening logfd");
2255 stat_config.output = output;
2258 * let the spreadsheet do the pretty-printing
2261 /* User explicitly passed -B? */
2262 if (big_num_opt == 1) {
2263 fprintf(stderr, "-B option not supported with -x\n");
2264 parse_options_usage(stat_usage, stat_options, "B", 1);
2265 parse_options_usage(NULL, stat_options, "x", 1);
2267 } else /* Nope, so disable big number formatting */
2269 } else if (big_num_opt == 0) /* User passed --no-big-num */
2272 if (!argc && target__none(&target))
2273 usage_with_options(stat_usage, stat_options);
2275 if (run_count < 0) {
2276 pr_err("Run count must be a positive number\n");
2277 parse_options_usage(stat_usage, stat_options, "r", 1);
2279 } else if (run_count == 0) {
2284 if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
2285 fprintf(stderr, "The --per-thread option is only available "
2286 "when monitoring via -p -t options.\n");
2287 parse_options_usage(NULL, stat_options, "p", 1);
2288 parse_options_usage(NULL, stat_options, "t", 1);
2293 * no_aggr, cgroup are for system-wide only
2294 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2296 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2297 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2298 !target__has_cpu(&target)) {
2299 fprintf(stderr, "both cgroup and no-aggregation "
2300 "modes only available in system-wide mode\n");
2302 parse_options_usage(stat_usage, stat_options, "G", 1);
2303 parse_options_usage(NULL, stat_options, "A", 1);
2304 parse_options_usage(NULL, stat_options, "a", 1);
2308 if (add_default_attributes())
2311 target__validate(&target);
2313 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2314 if (target__has_task(&target)) {
2315 pr_err("Problems finding threads of monitor\n");
2316 parse_options_usage(stat_usage, stat_options, "p", 1);
2317 parse_options_usage(NULL, stat_options, "t", 1);
2318 } else if (target__has_cpu(&target)) {
2319 perror("failed to parse CPUs map");
2320 parse_options_usage(stat_usage, stat_options, "C", 1);
2321 parse_options_usage(NULL, stat_options, "a", 1);
2327 * Initialize thread_map with comm names,
2328 * so we could print it out on output.
2330 if (stat_config.aggr_mode == AGGR_THREAD)
2331 thread_map__read_comms(evsel_list->threads);
2333 if (interval && interval < 100) {
2334 if (interval < 10) {
2335 pr_err("print interval must be >= 10ms\n");
2336 parse_options_usage(stat_usage, stat_options, "I", 1);
2339 pr_warning("print interval < 100ms. "
2340 "The overhead percentage could be high in some cases. "
2341 "Please proceed with caution.\n");
2344 if (perf_evlist__alloc_stats(evsel_list, interval))
2347 if (perf_stat_init_aggr_mode())
2351 * We dont want to block the signals - that would cause
2352 * child tasks to inherit that and Ctrl-C would not work.
2353 * What we want is for Ctrl-C to work in the exec()-ed
2354 * task, but being ignored by perf stat itself:
2358 signal(SIGINT, skip_signal);
2359 signal(SIGCHLD, skip_signal);
2360 signal(SIGALRM, skip_signal);
2361 signal(SIGABRT, skip_signal);
2364 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2365 if (run_count != 1 && verbose)
2366 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2369 status = run_perf_stat(argc, argv);
2370 if (forever && status != -1) {
2371 print_counters(NULL, argc, argv);
2372 perf_stat__reset_stats();
2376 if (!forever && status != -1 && !interval)
2377 print_counters(NULL, argc, argv);
2381 * We synthesize the kernel mmap record just so that older tools
2382 * don't emit warnings about not being able to resolve symbols
2383 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2384 * a saner message about no samples being in the perf.data file.
2386 * This also serves to suppress a warning about f_header.data.size == 0
2387 * in header.c at the moment 'perf stat record' gets introduced, which
2388 * is not really needed once we start adding the stat specific PERF_RECORD_
2389 * records, but the need to suppress the kptr_restrict messages in older
2390 * tools remain -acme
2392 int fd = perf_data_file__fd(&perf_stat.file);
2393 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2394 process_synthesized_event,
2395 &perf_stat.session->machines.host);
2397 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2398 "older tools may produce warnings about this file\n.");
2402 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2403 pr_err("failed to write stat round event\n");
2406 if (!perf_stat.file.is_pipe) {
2407 perf_stat.session->header.data_size += perf_stat.bytes_written;
2408 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2411 perf_session__delete(perf_stat.session);
2414 perf_stat__exit_aggr_mode();
2415 perf_evlist__free_stats(evsel_list);
2417 perf_evlist__delete(evsel_list);