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/group.h"
63 #include "util/session.h"
64 #include "util/tool.h"
65 #include "util/group.h"
68 #include <linux/time64.h>
69 #include <api/fs/fs.h>
71 #include <sys/prctl.h>
75 #define DEFAULT_SEPARATOR " "
76 #define CNTR_NOT_SUPPORTED "<not supported>"
77 #define CNTR_NOT_COUNTED "<not counted>"
79 static void print_counters(struct timespec *ts, int argc, const char **argv);
81 /* Default events used for perf stat -T */
82 static const char *transaction_attrs = {
94 /* More limited version when the CPU does not have all events. */
95 static const char * transaction_limited_attrs = {
105 static const char * topdown_attrs[] = {
106 "topdown-total-slots",
107 "topdown-slots-retired",
108 "topdown-recovery-bubbles",
109 "topdown-fetch-bubbles",
110 "topdown-slots-issued",
114 static struct perf_evlist *evsel_list;
116 static struct target target = {
120 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
122 static int run_count = 1;
123 static bool no_inherit = false;
124 static volatile pid_t child_pid = -1;
125 static bool null_run = false;
126 static int detailed_run = 0;
127 static bool transaction_run;
128 static bool topdown_run = false;
129 static bool big_num = true;
130 static int big_num_opt = -1;
131 static const char *csv_sep = NULL;
132 static bool csv_output = false;
133 static bool group = false;
134 static const char *pre_cmd = NULL;
135 static const char *post_cmd = NULL;
136 static bool sync_run = false;
137 static unsigned int initial_delay = 0;
138 static unsigned int unit_width = 4; /* strlen("unit") */
139 static bool forever = false;
140 static bool metric_only = false;
141 static bool force_metric_only = false;
142 static struct timespec ref_time;
143 static struct cpu_map *aggr_map;
144 static aggr_get_id_t aggr_get_id;
145 static bool append_file;
146 static const char *output_name;
147 static int output_fd;
151 struct perf_data_file file;
152 struct perf_session *session;
154 struct perf_tool tool;
156 struct cpu_map *cpus;
157 struct thread_map *threads;
158 enum aggr_mode aggr_mode;
161 static struct perf_stat perf_stat;
162 #define STAT_RECORD perf_stat.record
164 static volatile int done = 0;
166 static struct perf_stat_config stat_config = {
167 .aggr_mode = AGGR_GLOBAL,
171 static inline void diff_timespec(struct timespec *r, struct timespec *a,
174 r->tv_sec = a->tv_sec - b->tv_sec;
175 if (a->tv_nsec < b->tv_nsec) {
176 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
179 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
183 static void perf_stat__reset_stats(void)
185 perf_evlist__reset_stats(evsel_list);
186 perf_stat__reset_shadow_stats();
189 static int create_perf_stat_counter(struct perf_evsel *evsel)
191 struct perf_event_attr *attr = &evsel->attr;
193 if (stat_config.scale)
194 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
195 PERF_FORMAT_TOTAL_TIME_RUNNING;
197 attr->inherit = !no_inherit;
200 * Some events get initialized with sample_(period/type) set,
201 * like tracepoints. Clear it up for counting.
203 attr->sample_period = 0;
206 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
207 * while avoiding that older tools show confusing messages.
209 * However for pipe sessions we need to keep it zero,
210 * because script's perf_evsel__check_attr is triggered
211 * by attr->sample_type != 0, and we can't run it on
214 if (!(STAT_RECORD && perf_stat.file.is_pipe))
215 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
218 * Disabling all counters initially, they will be enabled
219 * either manually by us or by kernel via enable_on_exec
222 if (perf_evsel__is_group_leader(evsel)) {
226 * In case of initial_delay we enable tracee
229 if (target__none(&target) && !initial_delay)
230 attr->enable_on_exec = 1;
233 if (target__has_cpu(&target))
234 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
236 return perf_evsel__open_per_thread(evsel, evsel_list->threads);
240 * Does the counter have nsecs as a unit?
242 static inline int nsec_counter(struct perf_evsel *evsel)
244 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
245 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
251 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
252 union perf_event *event,
253 struct perf_sample *sample __maybe_unused,
254 struct machine *machine __maybe_unused)
256 if (perf_data_file__write(&perf_stat.file, event, event->header.size) < 0) {
257 pr_err("failed to write perf data, error: %m\n");
261 perf_stat.bytes_written += event->header.size;
265 static int write_stat_round_event(u64 tm, u64 type)
267 return perf_event__synthesize_stat_round(NULL, tm, type,
268 process_synthesized_event,
272 #define WRITE_STAT_ROUND_EVENT(time, interval) \
273 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
275 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
278 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
279 struct perf_counts_values *count)
281 struct perf_sample_id *sid = SID(counter, cpu, thread);
283 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
284 process_synthesized_event, NULL);
288 * Read out the results of a single counter:
289 * do not aggregate counts across CPUs in system-wide mode
291 static int read_counter(struct perf_evsel *counter)
293 int nthreads = thread_map__nr(evsel_list->threads);
294 int ncpus, cpu, thread;
296 if (target__has_cpu(&target))
297 ncpus = perf_evsel__nr_cpus(counter);
301 if (!counter->supported)
304 if (counter->system_wide)
307 for (thread = 0; thread < nthreads; thread++) {
308 for (cpu = 0; cpu < ncpus; cpu++) {
309 struct perf_counts_values *count;
311 count = perf_counts(counter->counts, cpu, thread);
312 if (perf_evsel__read(counter, cpu, thread, count))
316 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
317 pr_err("failed to write stat event\n");
323 fprintf(stat_config.output,
324 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
325 perf_evsel__name(counter),
327 count->val, count->ena, count->run);
335 static void read_counters(void)
337 struct perf_evsel *counter;
339 evlist__for_each_entry(evsel_list, counter) {
340 if (read_counter(counter))
341 pr_debug("failed to read counter %s\n", counter->name);
343 if (perf_stat_process_counter(&stat_config, counter))
344 pr_warning("failed to process counter %s\n", counter->name);
348 static void process_interval(void)
350 struct timespec ts, rs;
354 clock_gettime(CLOCK_MONOTONIC, &ts);
355 diff_timespec(&rs, &ts, &ref_time);
358 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
359 pr_err("failed to write stat round event\n");
362 print_counters(&rs, 0, NULL);
365 static void enable_counters(void)
368 usleep(initial_delay * USEC_PER_MSEC);
371 * We need to enable counters only if:
372 * - we don't have tracee (attaching to task or cpu)
373 * - we have initial delay configured
375 if (!target__none(&target) || initial_delay)
376 perf_evlist__enable(evsel_list);
379 static void disable_counters(void)
382 * If we don't have tracee (attaching to task or cpu), counters may
383 * still be running. To get accurate group ratios, we must stop groups
384 * from counting before reading their constituent counters.
386 if (!target__none(&target))
387 perf_evlist__disable(evsel_list);
390 static volatile int workload_exec_errno;
393 * perf_evlist__prepare_workload will send a SIGUSR1
394 * if the fork fails, since we asked by setting its
395 * want_signal to true.
397 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
398 void *ucontext __maybe_unused)
400 workload_exec_errno = info->si_value.sival_int;
403 static bool has_unit(struct perf_evsel *counter)
405 return counter->unit && *counter->unit;
408 static bool has_scale(struct perf_evsel *counter)
410 return counter->scale != 1;
413 static int perf_stat_synthesize_config(bool is_pipe)
415 struct perf_evsel *counter;
419 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
420 process_synthesized_event);
422 pr_err("Couldn't synthesize attrs.\n");
428 * Synthesize other events stuff not carried within
429 * attr event - unit, scale, name
431 evlist__for_each_entry(evsel_list, counter) {
432 if (!counter->supported)
436 * Synthesize unit and scale only if it's defined.
438 if (has_unit(counter)) {
439 err = perf_event__synthesize_event_update_unit(NULL, counter, process_synthesized_event);
441 pr_err("Couldn't synthesize evsel unit.\n");
446 if (has_scale(counter)) {
447 err = perf_event__synthesize_event_update_scale(NULL, counter, process_synthesized_event);
449 pr_err("Couldn't synthesize evsel scale.\n");
454 if (counter->own_cpus) {
455 err = perf_event__synthesize_event_update_cpus(NULL, counter, process_synthesized_event);
457 pr_err("Couldn't synthesize evsel scale.\n");
463 * Name is needed only for pipe output,
464 * perf.data carries event names.
467 err = perf_event__synthesize_event_update_name(NULL, counter, process_synthesized_event);
469 pr_err("Couldn't synthesize evsel name.\n");
475 err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
476 process_synthesized_event,
479 pr_err("Couldn't synthesize thread map.\n");
483 err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
484 process_synthesized_event, NULL);
486 pr_err("Couldn't synthesize thread map.\n");
490 err = perf_event__synthesize_stat_config(NULL, &stat_config,
491 process_synthesized_event, NULL);
493 pr_err("Couldn't synthesize config.\n");
500 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
502 static int __store_counter_ids(struct perf_evsel *counter,
503 struct cpu_map *cpus,
504 struct thread_map *threads)
508 for (cpu = 0; cpu < cpus->nr; cpu++) {
509 for (thread = 0; thread < threads->nr; thread++) {
510 int fd = FD(counter, cpu, thread);
512 if (perf_evlist__id_add_fd(evsel_list, counter,
513 cpu, thread, fd) < 0)
521 static int store_counter_ids(struct perf_evsel *counter)
523 struct cpu_map *cpus = counter->cpus;
524 struct thread_map *threads = counter->threads;
526 if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
529 return __store_counter_ids(counter, cpus, threads);
532 static int __run_perf_stat(int argc, const char **argv)
534 int interval = stat_config.interval;
536 unsigned long long t0, t1;
537 struct perf_evsel *counter;
541 const bool forks = (argc > 0);
542 bool is_pipe = STAT_RECORD ? perf_stat.file.is_pipe : false;
545 ts.tv_sec = interval / USEC_PER_MSEC;
546 ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
553 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
554 workload_exec_failed_signal) < 0) {
555 perror("failed to prepare workload");
558 child_pid = evsel_list->workload.pid;
562 perf_evlist__set_leader(evsel_list);
564 evlist__for_each_entry(evsel_list, counter) {
566 if (create_perf_stat_counter(counter) < 0) {
568 * PPC returns ENXIO for HW counters until 2.6.37
569 * (behavior changed with commit b0a873e).
571 if (errno == EINVAL || errno == ENOSYS ||
572 errno == ENOENT || errno == EOPNOTSUPP ||
575 ui__warning("%s event is not supported by the kernel.\n",
576 perf_evsel__name(counter));
577 counter->supported = false;
579 if ((counter->leader != counter) ||
580 !(counter->leader->nr_members > 1))
582 } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
584 ui__warning("%s\n", msg);
588 perf_evsel__open_strerror(counter, &target,
589 errno, msg, sizeof(msg));
590 ui__error("%s\n", msg);
593 kill(child_pid, SIGTERM);
597 counter->supported = true;
599 l = strlen(counter->unit);
603 if (STAT_RECORD && store_counter_ids(counter))
607 if (perf_evlist__apply_filters(evsel_list, &counter)) {
608 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
609 counter->filter, perf_evsel__name(counter), errno,
610 str_error_r(errno, msg, sizeof(msg)));
615 int err, fd = perf_data_file__fd(&perf_stat.file);
618 err = perf_header__write_pipe(perf_data_file__fd(&perf_stat.file));
620 err = perf_session__write_header(perf_stat.session, evsel_list,
627 err = perf_stat_synthesize_config(is_pipe);
633 * Enable counters and exec the command:
636 clock_gettime(CLOCK_MONOTONIC, &ref_time);
639 perf_evlist__start_workload(evsel_list);
643 while (!waitpid(child_pid, &status, WNOHANG)) {
644 nanosleep(&ts, NULL);
650 if (workload_exec_errno) {
651 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
652 pr_err("Workload failed: %s\n", emsg);
656 if (WIFSIGNALED(status))
657 psignal(WTERMSIG(status), argv[0]);
661 nanosleep(&ts, NULL);
671 update_stats(&walltime_nsecs_stats, t1 - t0);
674 * Closing a group leader splits the group, and as we only disable
675 * group leaders, results in remaining events becoming enabled. To
676 * avoid arbitrary skew, we must read all counters before closing any
680 perf_evlist__close(evsel_list);
682 return WEXITSTATUS(status);
685 static int run_perf_stat(int argc, const char **argv)
690 ret = system(pre_cmd);
698 ret = __run_perf_stat(argc, argv);
703 ret = system(post_cmd);
711 static void print_running(u64 run, u64 ena)
714 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
718 ena ? 100.0 * run / ena : 100.0);
719 } else if (run != ena) {
720 fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena);
724 static void print_noise_pct(double total, double avg)
726 double pct = rel_stddev_stats(total, avg);
729 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
731 fprintf(stat_config.output, " ( +-%6.2f%% )", pct);
734 static void print_noise(struct perf_evsel *evsel, double avg)
736 struct perf_stat_evsel *ps;
742 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
745 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
747 switch (stat_config.aggr_mode) {
749 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
750 cpu_map__id_to_socket(id),
752 cpu_map__id_to_cpu(id),
759 fprintf(stat_config.output, "S%*d%s%*d%s",
768 fprintf(stat_config.output, "CPU%*d%s",
770 perf_evsel__cpus(evsel)->map[id], csv_sep);
773 fprintf(stat_config.output, "%*s-%*d%s",
775 thread_map__comm(evsel->threads, id),
777 thread_map__pid(evsel->threads, id),
793 struct perf_evsel *evsel;
796 #define METRIC_LEN 35
798 static void new_line_std(void *ctx)
800 struct outstate *os = ctx;
805 static void do_new_line_std(struct outstate *os)
808 fputs(os->prefix, os->fh);
809 aggr_printout(os->evsel, os->id, os->nr);
810 if (stat_config.aggr_mode == AGGR_NONE)
811 fprintf(os->fh, " ");
812 fprintf(os->fh, " ");
815 static void print_metric_std(void *ctx, const char *color, const char *fmt,
816 const char *unit, double val)
818 struct outstate *os = ctx;
821 bool newline = os->newline;
825 if (unit == NULL || fmt == NULL) {
826 fprintf(out, "%-*s", METRIC_LEN, "");
833 n = fprintf(out, " # ");
835 n += color_fprintf(out, color, fmt, val);
837 n += fprintf(out, fmt, val);
838 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
841 static void new_line_csv(void *ctx)
843 struct outstate *os = ctx;
848 fprintf(os->fh, "%s%s", os->prefix, csv_sep);
849 aggr_printout(os->evsel, os->id, os->nr);
850 for (i = 0; i < os->nfields; i++)
851 fputs(csv_sep, os->fh);
854 static void print_metric_csv(void *ctx,
855 const char *color __maybe_unused,
856 const char *fmt, const char *unit, double val)
858 struct outstate *os = ctx;
860 char buf[64], *vals, *ends;
862 if (unit == NULL || fmt == NULL) {
863 fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
866 snprintf(buf, sizeof(buf), fmt, val);
868 while (isspace(*vals))
871 while (isdigit(*ends) || *ends == '.')
874 while (isspace(*unit))
876 fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
879 #define METRIC_ONLY_LEN 20
881 /* Filter out some columns that don't work well in metrics only mode */
883 static bool valid_only_metric(const char *unit)
887 if (strstr(unit, "/sec") ||
888 strstr(unit, "hz") ||
889 strstr(unit, "Hz") ||
890 strstr(unit, "CPUs utilized"))
895 static const char *fixunit(char *buf, struct perf_evsel *evsel,
898 if (!strncmp(unit, "of all", 6)) {
899 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
906 static void print_metric_only(void *ctx, const char *color, const char *fmt,
907 const char *unit, double val)
909 struct outstate *os = ctx;
913 unsigned mlen = METRIC_ONLY_LEN;
915 if (!valid_only_metric(unit))
917 unit = fixunit(buf, os->evsel, unit);
919 n = color_fprintf(out, color, fmt, val);
921 n = fprintf(out, fmt, val);
922 if (n > METRIC_ONLY_LEN)
924 if (mlen < strlen(unit))
925 mlen = strlen(unit) + 1;
926 fprintf(out, "%*s", mlen - n, "");
929 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
931 const char *unit, double val)
933 struct outstate *os = ctx;
935 char buf[64], *vals, *ends;
938 if (!valid_only_metric(unit))
940 unit = fixunit(tbuf, os->evsel, unit);
941 snprintf(buf, sizeof buf, fmt, val);
943 while (isspace(*vals))
946 while (isdigit(*ends) || *ends == '.')
949 fprintf(out, "%s%s", vals, csv_sep);
952 static void new_line_metric(void *ctx __maybe_unused)
956 static void print_metric_header(void *ctx, const char *color __maybe_unused,
957 const char *fmt __maybe_unused,
958 const char *unit, double val __maybe_unused)
960 struct outstate *os = ctx;
963 if (!valid_only_metric(unit))
965 unit = fixunit(tbuf, os->evsel, unit);
967 fprintf(os->fh, "%s%s", unit, csv_sep);
969 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
972 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
974 FILE *output = stat_config.output;
975 double msecs = avg / NSEC_PER_MSEC;
976 const char *fmt_v, *fmt_n;
979 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
980 fmt_n = csv_output ? "%s" : "%-25s";
982 aggr_printout(evsel, id, nr);
984 scnprintf(name, sizeof(name), "%s%s",
985 perf_evsel__name(evsel), csv_output ? "" : " (msec)");
987 fprintf(output, fmt_v, msecs, csv_sep);
990 fprintf(output, "%s%s", evsel->unit, csv_sep);
992 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
994 fprintf(output, fmt_n, name);
997 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1000 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
1007 if (stat_config.aggr_mode == AGGR_NONE)
1010 if (stat_config.aggr_mode == AGGR_GLOBAL)
1013 for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
1014 int cpu2 = perf_evsel__cpus(evsel)->map[i];
1016 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
1022 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1024 FILE *output = stat_config.output;
1025 double sc = evsel->scale;
1029 fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
1032 fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
1034 fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
1037 aggr_printout(evsel, id, nr);
1039 fprintf(output, fmt, avg, csv_sep);
1042 fprintf(output, "%-*s%s",
1043 csv_output ? 0 : unit_width,
1044 evsel->unit, csv_sep);
1046 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1049 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1052 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
1053 char *prefix, u64 run, u64 ena, double noise)
1055 struct perf_stat_output_ctx out;
1056 struct outstate os = {
1057 .fh = stat_config.output,
1058 .prefix = prefix ? prefix : "",
1063 print_metric_t pm = print_metric_std;
1067 nl = new_line_metric;
1069 pm = print_metric_only_csv;
1071 pm = print_metric_only;
1075 if (csv_output && !metric_only) {
1076 static int aggr_fields[] = {
1084 pm = print_metric_csv;
1087 os.nfields += aggr_fields[stat_config.aggr_mode];
1091 if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1093 pm(&os, NULL, "", "", 0);
1096 aggr_printout(counter, id, nr);
1098 fprintf(stat_config.output, "%*s%s",
1099 csv_output ? 0 : 18,
1100 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1103 fprintf(stat_config.output, "%-*s%s",
1104 csv_output ? 0 : unit_width,
1105 counter->unit, csv_sep);
1107 fprintf(stat_config.output, "%*s",
1108 csv_output ? 0 : -25,
1109 perf_evsel__name(counter));
1112 fprintf(stat_config.output, "%s%s",
1113 csv_sep, counter->cgrp->name);
1116 pm(&os, NULL, NULL, "", 0);
1117 print_noise(counter, noise);
1118 print_running(run, ena);
1120 pm(&os, NULL, NULL, "", 0);
1126 else if (nsec_counter(counter))
1127 nsec_printout(id, nr, counter, uval);
1129 abs_printout(id, nr, counter, uval);
1131 out.print_metric = pm;
1135 if (csv_output && !metric_only) {
1136 print_noise(counter, noise);
1137 print_running(run, ena);
1140 perf_stat__print_shadow_stats(counter, uval,
1141 first_shadow_cpu(counter, id),
1143 if (!csv_output && !metric_only) {
1144 print_noise(counter, noise);
1145 print_running(run, ena);
1149 static void aggr_update_shadow(void)
1153 struct perf_evsel *counter;
1155 for (s = 0; s < aggr_map->nr; s++) {
1156 id = aggr_map->map[s];
1157 evlist__for_each_entry(evsel_list, counter) {
1159 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1160 s2 = aggr_get_id(evsel_list->cpus, cpu);
1163 val += perf_counts(counter->counts, cpu, 0)->val;
1165 val = val * counter->scale;
1166 perf_stat__update_shadow_stats(counter, &val,
1167 first_shadow_cpu(counter, id));
1172 static void print_aggr(char *prefix)
1174 FILE *output = stat_config.output;
1175 struct perf_evsel *counter;
1176 int cpu, s, s2, id, nr;
1181 if (!(aggr_map || aggr_get_id))
1184 aggr_update_shadow();
1187 * With metric_only everything is on a single line.
1188 * Without each counter has its own line.
1190 for (s = 0; s < aggr_map->nr; s++) {
1191 if (prefix && metric_only)
1192 fprintf(output, "%s", prefix);
1194 id = aggr_map->map[s];
1196 evlist__for_each_entry(evsel_list, counter) {
1197 val = ena = run = 0;
1199 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1200 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1203 val += perf_counts(counter->counts, cpu, 0)->val;
1204 ena += perf_counts(counter->counts, cpu, 0)->ena;
1205 run += perf_counts(counter->counts, cpu, 0)->run;
1208 if (first && metric_only) {
1210 aggr_printout(counter, id, nr);
1212 if (prefix && !metric_only)
1213 fprintf(output, "%s", prefix);
1215 uval = val * counter->scale;
1216 printout(id, nr, counter, uval, prefix, run, ena, 1.0);
1218 fputc('\n', output);
1221 fputc('\n', output);
1225 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1227 FILE *output = stat_config.output;
1228 int nthreads = thread_map__nr(counter->threads);
1229 int ncpus = cpu_map__nr(counter->cpus);
1233 for (thread = 0; thread < nthreads; thread++) {
1234 u64 ena = 0, run = 0, val = 0;
1236 for (cpu = 0; cpu < ncpus; cpu++) {
1237 val += perf_counts(counter->counts, cpu, thread)->val;
1238 ena += perf_counts(counter->counts, cpu, thread)->ena;
1239 run += perf_counts(counter->counts, cpu, thread)->run;
1243 fprintf(output, "%s", prefix);
1245 uval = val * counter->scale;
1246 printout(thread, 0, counter, uval, prefix, run, ena, 1.0);
1247 fputc('\n', output);
1252 * Print out the results of a single counter:
1253 * aggregated counts in system-wide mode
1255 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1257 FILE *output = stat_config.output;
1258 struct perf_stat_evsel *ps = counter->priv;
1259 double avg = avg_stats(&ps->res_stats[0]);
1261 double avg_enabled, avg_running;
1263 avg_enabled = avg_stats(&ps->res_stats[1]);
1264 avg_running = avg_stats(&ps->res_stats[2]);
1266 if (prefix && !metric_only)
1267 fprintf(output, "%s", prefix);
1269 uval = avg * counter->scale;
1270 printout(-1, 0, counter, uval, prefix, avg_running, avg_enabled, avg);
1272 fprintf(output, "\n");
1276 * Print out the results of a single counter:
1277 * does not use aggregated count in system-wide
1279 static void print_counter(struct perf_evsel *counter, char *prefix)
1281 FILE *output = stat_config.output;
1286 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1287 val = perf_counts(counter->counts, cpu, 0)->val;
1288 ena = perf_counts(counter->counts, cpu, 0)->ena;
1289 run = perf_counts(counter->counts, cpu, 0)->run;
1292 fprintf(output, "%s", prefix);
1294 uval = val * counter->scale;
1295 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1297 fputc('\n', output);
1301 static void print_no_aggr_metric(char *prefix)
1305 struct perf_evsel *counter;
1309 nrcpus = evsel_list->cpus->nr;
1310 for (cpu = 0; cpu < nrcpus; cpu++) {
1314 fputs(prefix, stat_config.output);
1315 evlist__for_each_entry(evsel_list, counter) {
1317 aggr_printout(counter, cpu, 0);
1320 val = perf_counts(counter->counts, cpu, 0)->val;
1321 ena = perf_counts(counter->counts, cpu, 0)->ena;
1322 run = perf_counts(counter->counts, cpu, 0)->run;
1324 uval = val * counter->scale;
1325 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1327 fputc('\n', stat_config.output);
1331 static int aggr_header_lens[] = {
1339 static const char *aggr_header_csv[] = {
1340 [AGGR_CORE] = "core,cpus,",
1341 [AGGR_SOCKET] = "socket,cpus",
1342 [AGGR_NONE] = "cpu,",
1343 [AGGR_THREAD] = "comm-pid,",
1347 static void print_metric_headers(const char *prefix, bool no_indent)
1349 struct perf_stat_output_ctx out;
1350 struct perf_evsel *counter;
1351 struct outstate os = {
1352 .fh = stat_config.output
1356 fprintf(stat_config.output, "%s", prefix);
1358 if (!csv_output && !no_indent)
1359 fprintf(stat_config.output, "%*s",
1360 aggr_header_lens[stat_config.aggr_mode], "");
1362 if (stat_config.interval)
1363 fputs("time,", stat_config.output);
1364 fputs(aggr_header_csv[stat_config.aggr_mode],
1365 stat_config.output);
1368 /* Print metrics headers only */
1369 evlist__for_each_entry(evsel_list, counter) {
1372 out.print_metric = print_metric_header;
1373 out.new_line = new_line_metric;
1375 perf_stat__print_shadow_stats(counter, 0,
1379 fputc('\n', stat_config.output);
1382 static void print_interval(char *prefix, struct timespec *ts)
1384 FILE *output = stat_config.output;
1385 static int num_print_interval;
1387 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1389 if (num_print_interval == 0 && !csv_output) {
1390 switch (stat_config.aggr_mode) {
1392 fprintf(output, "# time socket cpus");
1394 fprintf(output, " counts %*s events\n", unit_width, "unit");
1397 fprintf(output, "# time core cpus");
1399 fprintf(output, " counts %*s events\n", unit_width, "unit");
1402 fprintf(output, "# time CPU");
1404 fprintf(output, " counts %*s events\n", unit_width, "unit");
1407 fprintf(output, "# time comm-pid");
1409 fprintf(output, " counts %*s events\n", unit_width, "unit");
1413 fprintf(output, "# time");
1415 fprintf(output, " counts %*s events\n", unit_width, "unit");
1421 if (num_print_interval == 0 && metric_only)
1422 print_metric_headers(" ", true);
1423 if (++num_print_interval == 25)
1424 num_print_interval = 0;
1427 static void print_header(int argc, const char **argv)
1429 FILE *output = stat_config.output;
1435 fprintf(output, "\n");
1436 fprintf(output, " Performance counter stats for ");
1437 if (target.system_wide)
1438 fprintf(output, "\'system wide");
1439 else if (target.cpu_list)
1440 fprintf(output, "\'CPU(s) %s", target.cpu_list);
1441 else if (!target__has_task(&target)) {
1442 fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1443 for (i = 1; argv && (i < argc); i++)
1444 fprintf(output, " %s", argv[i]);
1445 } else if (target.pid)
1446 fprintf(output, "process id \'%s", target.pid);
1448 fprintf(output, "thread id \'%s", target.tid);
1450 fprintf(output, "\'");
1452 fprintf(output, " (%d runs)", run_count);
1453 fprintf(output, ":\n\n");
1457 static void print_footer(void)
1459 FILE *output = stat_config.output;
1462 fprintf(output, "\n");
1463 fprintf(output, " %17.9f seconds time elapsed",
1464 avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
1465 if (run_count > 1) {
1466 fprintf(output, " ");
1467 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1468 avg_stats(&walltime_nsecs_stats));
1470 fprintf(output, "\n\n");
1473 static void print_counters(struct timespec *ts, int argc, const char **argv)
1475 int interval = stat_config.interval;
1476 struct perf_evsel *counter;
1477 char buf[64], *prefix = NULL;
1479 /* Do not print anything if we record to the pipe. */
1480 if (STAT_RECORD && perf_stat.file.is_pipe)
1484 print_interval(prefix = buf, ts);
1486 print_header(argc, argv);
1489 static int num_print_iv;
1491 if (num_print_iv == 0 && !interval)
1492 print_metric_headers(prefix, false);
1493 if (num_print_iv++ == 25)
1495 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1496 fprintf(stat_config.output, "%s", prefix);
1499 switch (stat_config.aggr_mode) {
1505 evlist__for_each_entry(evsel_list, counter)
1506 print_aggr_thread(counter, prefix);
1509 evlist__for_each_entry(evsel_list, counter)
1510 print_counter_aggr(counter, prefix);
1512 fputc('\n', stat_config.output);
1516 print_no_aggr_metric(prefix);
1518 evlist__for_each_entry(evsel_list, counter)
1519 print_counter(counter, prefix);
1527 if (!interval && !csv_output)
1530 fflush(stat_config.output);
1533 static volatile int signr = -1;
1535 static void skip_signal(int signo)
1537 if ((child_pid == -1) || stat_config.interval)
1542 * render child_pid harmless
1543 * won't send SIGTERM to a random
1544 * process in case of race condition
1545 * and fast PID recycling
1550 static void sig_atexit(void)
1555 * avoid race condition with SIGCHLD handler
1556 * in skip_signal() which is modifying child_pid
1557 * goal is to avoid send SIGTERM to a random
1561 sigaddset(&set, SIGCHLD);
1562 sigprocmask(SIG_BLOCK, &set, &oset);
1564 if (child_pid != -1)
1565 kill(child_pid, SIGTERM);
1567 sigprocmask(SIG_SETMASK, &oset, NULL);
1572 signal(signr, SIG_DFL);
1573 kill(getpid(), signr);
1576 static int stat__set_big_num(const struct option *opt __maybe_unused,
1577 const char *s __maybe_unused, int unset)
1579 big_num_opt = unset ? 0 : 1;
1583 static int enable_metric_only(const struct option *opt __maybe_unused,
1584 const char *s __maybe_unused, int unset)
1586 force_metric_only = true;
1587 metric_only = !unset;
1591 static const struct option stat_options[] = {
1592 OPT_BOOLEAN('T', "transaction", &transaction_run,
1593 "hardware transaction statistics"),
1594 OPT_CALLBACK('e', "event", &evsel_list, "event",
1595 "event selector. use 'perf list' to list available events",
1596 parse_events_option),
1597 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1598 "event filter", parse_filter),
1599 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1600 "child tasks do not inherit counters"),
1601 OPT_STRING('p', "pid", &target.pid, "pid",
1602 "stat events on existing process id"),
1603 OPT_STRING('t', "tid", &target.tid, "tid",
1604 "stat events on existing thread id"),
1605 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1606 "system-wide collection from all CPUs"),
1607 OPT_BOOLEAN('g', "group", &group,
1608 "put the counters into a counter group"),
1609 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1610 OPT_INCR('v', "verbose", &verbose,
1611 "be more verbose (show counter open errors, etc)"),
1612 OPT_INTEGER('r', "repeat", &run_count,
1613 "repeat command and print average + stddev (max: 100, forever: 0)"),
1614 OPT_BOOLEAN('n', "null", &null_run,
1615 "null run - dont start any counters"),
1616 OPT_INCR('d', "detailed", &detailed_run,
1617 "detailed run - start a lot of events"),
1618 OPT_BOOLEAN('S', "sync", &sync_run,
1619 "call sync() before starting a run"),
1620 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1621 "print large numbers with thousands\' separators",
1623 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1624 "list of cpus to monitor in system-wide"),
1625 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1626 "disable CPU count aggregation", AGGR_NONE),
1627 OPT_STRING('x', "field-separator", &csv_sep, "separator",
1628 "print counts with custom separator"),
1629 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1630 "monitor event in cgroup name only", parse_cgroups),
1631 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1632 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1633 OPT_INTEGER(0, "log-fd", &output_fd,
1634 "log output to fd, instead of stderr"),
1635 OPT_STRING(0, "pre", &pre_cmd, "command",
1636 "command to run prior to the measured command"),
1637 OPT_STRING(0, "post", &post_cmd, "command",
1638 "command to run after to the measured command"),
1639 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1640 "print counts at regular interval in ms (>= 10)"),
1641 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1642 "aggregate counts per processor socket", AGGR_SOCKET),
1643 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1644 "aggregate counts per physical processor core", AGGR_CORE),
1645 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1646 "aggregate counts per thread", AGGR_THREAD),
1647 OPT_UINTEGER('D', "delay", &initial_delay,
1648 "ms to wait before starting measurement after program start"),
1649 OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
1650 "Only print computed metrics. No raw values", enable_metric_only),
1651 OPT_BOOLEAN(0, "topdown", &topdown_run,
1652 "measure topdown level 1 statistics"),
1656 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1658 return cpu_map__get_socket(map, cpu, NULL);
1661 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1663 return cpu_map__get_core(map, cpu, NULL);
1666 static int cpu_map__get_max(struct cpu_map *map)
1670 for (i = 0; i < map->nr; i++) {
1671 if (map->map[i] > max)
1678 static struct cpu_map *cpus_aggr_map;
1680 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1687 cpu = map->map[idx];
1689 if (cpus_aggr_map->map[cpu] == -1)
1690 cpus_aggr_map->map[cpu] = get_id(map, idx);
1692 return cpus_aggr_map->map[cpu];
1695 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1697 return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1700 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1702 return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1705 static int perf_stat_init_aggr_mode(void)
1709 switch (stat_config.aggr_mode) {
1711 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1712 perror("cannot build socket map");
1715 aggr_get_id = perf_stat__get_socket_cached;
1718 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1719 perror("cannot build core map");
1722 aggr_get_id = perf_stat__get_core_cached;
1733 * The evsel_list->cpus is the base we operate on,
1734 * taking the highest cpu number to be the size of
1735 * the aggregation translate cpumap.
1737 nr = cpu_map__get_max(evsel_list->cpus);
1738 cpus_aggr_map = cpu_map__empty_new(nr + 1);
1739 return cpus_aggr_map ? 0 : -ENOMEM;
1742 static void perf_stat__exit_aggr_mode(void)
1744 cpu_map__put(aggr_map);
1745 cpu_map__put(cpus_aggr_map);
1747 cpus_aggr_map = NULL;
1750 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1757 cpu = map->map[idx];
1759 if (cpu >= env->nr_cpus_online)
1765 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1767 struct perf_env *env = data;
1768 int cpu = perf_env__get_cpu(env, map, idx);
1770 return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1773 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1775 struct perf_env *env = data;
1776 int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1779 int socket_id = env->cpu[cpu].socket_id;
1782 * Encode socket in upper 16 bits
1783 * core_id is relative to socket, and
1784 * we need a global id. So we combine
1787 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1793 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1794 struct cpu_map **sockp)
1796 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1799 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
1800 struct cpu_map **corep)
1802 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1805 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
1807 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1810 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
1812 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1815 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1817 struct perf_env *env = &st->session->header.env;
1819 switch (stat_config.aggr_mode) {
1821 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
1822 perror("cannot build socket map");
1825 aggr_get_id = perf_stat__get_socket_file;
1828 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
1829 perror("cannot build core map");
1832 aggr_get_id = perf_stat__get_core_file;
1845 static int topdown_filter_events(const char **attr, char **str, bool use_group)
1852 for (i = 0; attr[i]; i++) {
1853 if (pmu_have_event("cpu", attr[i])) {
1854 len += strlen(attr[i]) + 1;
1855 attr[i - off] = attr[i];
1859 attr[i - off] = NULL;
1861 *str = malloc(len + 1 + 2);
1871 for (i = 0; attr[i]; i++) {
1884 __weak bool arch_topdown_check_group(bool *warn)
1890 __weak void arch_topdown_group_warn(void)
1895 * Add default attributes, if there were no attributes specified or
1896 * if -d/--detailed, -d -d or -d -d -d is used:
1898 static int add_default_attributes(void)
1901 struct perf_event_attr default_attrs0[] = {
1903 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
1904 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
1905 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
1906 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
1908 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
1910 struct perf_event_attr frontend_attrs[] = {
1911 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1913 struct perf_event_attr backend_attrs[] = {
1914 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
1916 struct perf_event_attr default_attrs1[] = {
1917 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
1918 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
1919 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
1924 * Detailed stats (-d), covering the L1 and last level data caches:
1926 struct perf_event_attr detailed_attrs[] = {
1928 { .type = PERF_TYPE_HW_CACHE,
1930 PERF_COUNT_HW_CACHE_L1D << 0 |
1931 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1932 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1934 { .type = PERF_TYPE_HW_CACHE,
1936 PERF_COUNT_HW_CACHE_L1D << 0 |
1937 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1938 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1940 { .type = PERF_TYPE_HW_CACHE,
1942 PERF_COUNT_HW_CACHE_LL << 0 |
1943 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1944 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1946 { .type = PERF_TYPE_HW_CACHE,
1948 PERF_COUNT_HW_CACHE_LL << 0 |
1949 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1950 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1954 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1956 struct perf_event_attr very_detailed_attrs[] = {
1958 { .type = PERF_TYPE_HW_CACHE,
1960 PERF_COUNT_HW_CACHE_L1I << 0 |
1961 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1962 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1964 { .type = PERF_TYPE_HW_CACHE,
1966 PERF_COUNT_HW_CACHE_L1I << 0 |
1967 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1968 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1970 { .type = PERF_TYPE_HW_CACHE,
1972 PERF_COUNT_HW_CACHE_DTLB << 0 |
1973 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1974 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1976 { .type = PERF_TYPE_HW_CACHE,
1978 PERF_COUNT_HW_CACHE_DTLB << 0 |
1979 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1980 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1982 { .type = PERF_TYPE_HW_CACHE,
1984 PERF_COUNT_HW_CACHE_ITLB << 0 |
1985 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1986 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1988 { .type = PERF_TYPE_HW_CACHE,
1990 PERF_COUNT_HW_CACHE_ITLB << 0 |
1991 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1992 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1997 * Very, very detailed stats (-d -d -d), adding prefetch events:
1999 struct perf_event_attr very_very_detailed_attrs[] = {
2001 { .type = PERF_TYPE_HW_CACHE,
2003 PERF_COUNT_HW_CACHE_L1D << 0 |
2004 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2005 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2007 { .type = PERF_TYPE_HW_CACHE,
2009 PERF_COUNT_HW_CACHE_L1D << 0 |
2010 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2011 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2014 /* Set attrs if no event is selected and !null_run: */
2018 if (transaction_run) {
2019 if (pmu_have_event("cpu", "cycles-ct") &&
2020 pmu_have_event("cpu", "el-start"))
2021 err = parse_events(evsel_list, transaction_attrs, NULL);
2023 err = parse_events(evsel_list, transaction_limited_attrs, NULL);
2025 fprintf(stderr, "Cannot set up transaction events\n");
2035 if (stat_config.aggr_mode != AGGR_GLOBAL &&
2036 stat_config.aggr_mode != AGGR_CORE) {
2037 pr_err("top down event configuration requires --per-core mode\n");
2040 stat_config.aggr_mode = AGGR_CORE;
2041 if (nr_cgroups || !target__has_cpu(&target)) {
2042 pr_err("top down event configuration requires system-wide mode (-a)\n");
2046 if (!force_metric_only)
2048 if (topdown_filter_events(topdown_attrs, &str,
2049 arch_topdown_check_group(&warn)) < 0) {
2050 pr_err("Out of memory\n");
2053 if (topdown_attrs[0] && str) {
2055 arch_topdown_group_warn();
2056 err = parse_events(evsel_list, str, NULL);
2059 "Cannot set up top down events %s: %d\n",
2065 fprintf(stderr, "System does not support topdown\n");
2071 if (!evsel_list->nr_entries) {
2072 if (target__has_cpu(&target))
2073 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2075 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2077 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2078 if (perf_evlist__add_default_attrs(evsel_list,
2079 frontend_attrs) < 0)
2082 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2083 if (perf_evlist__add_default_attrs(evsel_list,
2087 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2091 /* Detailed events get appended to the event list: */
2093 if (detailed_run < 1)
2096 /* Append detailed run extra attributes: */
2097 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2100 if (detailed_run < 2)
2103 /* Append very detailed run extra attributes: */
2104 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2107 if (detailed_run < 3)
2110 /* Append very, very detailed run extra attributes: */
2111 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2114 static const char * const stat_record_usage[] = {
2115 "perf stat record [<options>]",
2119 static void init_features(struct perf_session *session)
2123 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2124 perf_header__set_feat(&session->header, feat);
2126 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2127 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2128 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2129 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2132 static int __cmd_record(int argc, const char **argv)
2134 struct perf_session *session;
2135 struct perf_data_file *file = &perf_stat.file;
2137 argc = parse_options(argc, argv, stat_options, stat_record_usage,
2138 PARSE_OPT_STOP_AT_NON_OPTION);
2141 file->path = output_name;
2143 if (run_count != 1 || forever) {
2144 pr_err("Cannot use -r option with perf stat record.\n");
2148 session = perf_session__new(file, false, NULL);
2149 if (session == NULL) {
2150 pr_err("Perf session creation failed.\n");
2154 init_features(session);
2156 session->evlist = evsel_list;
2157 perf_stat.session = session;
2158 perf_stat.record = true;
2162 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2163 union perf_event *event,
2164 struct perf_session *session)
2166 struct stat_round_event *stat_round = &event->stat_round;
2167 struct perf_evsel *counter;
2168 struct timespec tsh, *ts = NULL;
2169 const char **argv = session->header.env.cmdline_argv;
2170 int argc = session->header.env.nr_cmdline;
2172 evlist__for_each_entry(evsel_list, counter)
2173 perf_stat_process_counter(&stat_config, counter);
2175 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2176 update_stats(&walltime_nsecs_stats, stat_round->time);
2178 if (stat_config.interval && stat_round->time) {
2179 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2180 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2184 print_counters(ts, argc, argv);
2189 int process_stat_config_event(struct perf_tool *tool __maybe_unused,
2190 union perf_event *event,
2191 struct perf_session *session __maybe_unused)
2193 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2195 perf_event__read_stat_config(&stat_config, &event->stat_config);
2197 if (cpu_map__empty(st->cpus)) {
2198 if (st->aggr_mode != AGGR_UNSET)
2199 pr_warning("warning: processing task data, aggregation mode not set\n");
2203 if (st->aggr_mode != AGGR_UNSET)
2204 stat_config.aggr_mode = st->aggr_mode;
2206 if (perf_stat.file.is_pipe)
2207 perf_stat_init_aggr_mode();
2209 perf_stat_init_aggr_mode_file(st);
2214 static int set_maps(struct perf_stat *st)
2216 if (!st->cpus || !st->threads)
2219 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2222 perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2224 if (perf_evlist__alloc_stats(evsel_list, true))
2227 st->maps_allocated = true;
2232 int process_thread_map_event(struct perf_tool *tool __maybe_unused,
2233 union perf_event *event,
2234 struct perf_session *session __maybe_unused)
2236 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2239 pr_warning("Extra thread map event, ignoring.\n");
2243 st->threads = thread_map__new_event(&event->thread_map);
2247 return set_maps(st);
2251 int process_cpu_map_event(struct perf_tool *tool __maybe_unused,
2252 union perf_event *event,
2253 struct perf_session *session __maybe_unused)
2255 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2256 struct cpu_map *cpus;
2259 pr_warning("Extra cpu map event, ignoring.\n");
2263 cpus = cpu_map__new_data(&event->cpu_map.data);
2268 return set_maps(st);
2271 static const char * const stat_report_usage[] = {
2272 "perf stat report [<options>]",
2276 static struct perf_stat perf_stat = {
2278 .attr = perf_event__process_attr,
2279 .event_update = perf_event__process_event_update,
2280 .thread_map = process_thread_map_event,
2281 .cpu_map = process_cpu_map_event,
2282 .stat_config = process_stat_config_event,
2283 .stat = perf_event__process_stat_event,
2284 .stat_round = process_stat_round_event,
2286 .aggr_mode = AGGR_UNSET,
2289 static int __cmd_report(int argc, const char **argv)
2291 struct perf_session *session;
2292 const struct option options[] = {
2293 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2294 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2295 "aggregate counts per processor socket", AGGR_SOCKET),
2296 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2297 "aggregate counts per physical processor core", AGGR_CORE),
2298 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2299 "disable CPU count aggregation", AGGR_NONE),
2305 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2307 if (!input_name || !strlen(input_name)) {
2308 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2311 input_name = "perf.data";
2314 perf_stat.file.path = input_name;
2315 perf_stat.file.mode = PERF_DATA_MODE_READ;
2317 session = perf_session__new(&perf_stat.file, false, &perf_stat.tool);
2318 if (session == NULL)
2321 perf_stat.session = session;
2322 stat_config.output = stderr;
2323 evsel_list = session->evlist;
2325 ret = perf_session__process_events(session);
2329 perf_session__delete(session);
2333 int cmd_stat(int argc, const char **argv, const char *prefix __maybe_unused)
2335 const char * const stat_usage[] = {
2336 "perf stat [<options>] [<command>]",
2339 int status = -EINVAL, run_idx;
2341 FILE *output = stderr;
2342 unsigned int interval;
2343 const char * const stat_subcommands[] = { "record", "report" };
2345 setlocale(LC_ALL, "");
2347 evsel_list = perf_evlist__new();
2348 if (evsel_list == NULL)
2351 parse_events__shrink_config_terms();
2352 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2353 (const char **) stat_usage,
2354 PARSE_OPT_STOP_AT_NON_OPTION);
2355 perf_stat__init_shadow_stats();
2359 if (!strcmp(csv_sep, "\\t"))
2362 csv_sep = DEFAULT_SEPARATOR;
2364 if (argc && !strncmp(argv[0], "rec", 3)) {
2365 argc = __cmd_record(argc, argv);
2368 } else if (argc && !strncmp(argv[0], "rep", 3))
2369 return __cmd_report(argc, argv);
2371 interval = stat_config.interval;
2374 * For record command the -o is already taken care of.
2376 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2379 if (output_name && output_fd) {
2380 fprintf(stderr, "cannot use both --output and --log-fd\n");
2381 parse_options_usage(stat_usage, stat_options, "o", 1);
2382 parse_options_usage(NULL, stat_options, "log-fd", 0);
2386 if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2387 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2391 if (metric_only && run_count > 1) {
2392 fprintf(stderr, "--metric-only is not supported with -r\n");
2396 if (output_fd < 0) {
2397 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2398 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2404 mode = append_file ? "a" : "w";
2406 output = fopen(output_name, mode);
2408 perror("failed to create output file");
2411 clock_gettime(CLOCK_REALTIME, &tm);
2412 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2413 } else if (output_fd > 0) {
2414 mode = append_file ? "a" : "w";
2415 output = fdopen(output_fd, mode);
2417 perror("Failed opening logfd");
2422 stat_config.output = output;
2425 * let the spreadsheet do the pretty-printing
2428 /* User explicitly passed -B? */
2429 if (big_num_opt == 1) {
2430 fprintf(stderr, "-B option not supported with -x\n");
2431 parse_options_usage(stat_usage, stat_options, "B", 1);
2432 parse_options_usage(NULL, stat_options, "x", 1);
2434 } else /* Nope, so disable big number formatting */
2436 } else if (big_num_opt == 0) /* User passed --no-big-num */
2439 if (!argc && target__none(&target))
2440 usage_with_options(stat_usage, stat_options);
2442 if (run_count < 0) {
2443 pr_err("Run count must be a positive number\n");
2444 parse_options_usage(stat_usage, stat_options, "r", 1);
2446 } else if (run_count == 0) {
2451 if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
2452 fprintf(stderr, "The --per-thread option is only available "
2453 "when monitoring via -p -t options.\n");
2454 parse_options_usage(NULL, stat_options, "p", 1);
2455 parse_options_usage(NULL, stat_options, "t", 1);
2460 * no_aggr, cgroup are for system-wide only
2461 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2463 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2464 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2465 !target__has_cpu(&target)) {
2466 fprintf(stderr, "both cgroup and no-aggregation "
2467 "modes only available in system-wide mode\n");
2469 parse_options_usage(stat_usage, stat_options, "G", 1);
2470 parse_options_usage(NULL, stat_options, "A", 1);
2471 parse_options_usage(NULL, stat_options, "a", 1);
2475 if (add_default_attributes())
2478 target__validate(&target);
2480 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2481 if (target__has_task(&target)) {
2482 pr_err("Problems finding threads of monitor\n");
2483 parse_options_usage(stat_usage, stat_options, "p", 1);
2484 parse_options_usage(NULL, stat_options, "t", 1);
2485 } else if (target__has_cpu(&target)) {
2486 perror("failed to parse CPUs map");
2487 parse_options_usage(stat_usage, stat_options, "C", 1);
2488 parse_options_usage(NULL, stat_options, "a", 1);
2494 * Initialize thread_map with comm names,
2495 * so we could print it out on output.
2497 if (stat_config.aggr_mode == AGGR_THREAD)
2498 thread_map__read_comms(evsel_list->threads);
2500 if (interval && interval < 100) {
2501 if (interval < 10) {
2502 pr_err("print interval must be >= 10ms\n");
2503 parse_options_usage(stat_usage, stat_options, "I", 1);
2506 pr_warning("print interval < 100ms. "
2507 "The overhead percentage could be high in some cases. "
2508 "Please proceed with caution.\n");
2511 if (perf_evlist__alloc_stats(evsel_list, interval))
2514 if (perf_stat_init_aggr_mode())
2518 * We dont want to block the signals - that would cause
2519 * child tasks to inherit that and Ctrl-C would not work.
2520 * What we want is for Ctrl-C to work in the exec()-ed
2521 * task, but being ignored by perf stat itself:
2525 signal(SIGINT, skip_signal);
2526 signal(SIGCHLD, skip_signal);
2527 signal(SIGALRM, skip_signal);
2528 signal(SIGABRT, skip_signal);
2531 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2532 if (run_count != 1 && verbose)
2533 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2536 status = run_perf_stat(argc, argv);
2537 if (forever && status != -1) {
2538 print_counters(NULL, argc, argv);
2539 perf_stat__reset_stats();
2543 if (!forever && status != -1 && !interval)
2544 print_counters(NULL, argc, argv);
2548 * We synthesize the kernel mmap record just so that older tools
2549 * don't emit warnings about not being able to resolve symbols
2550 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2551 * a saner message about no samples being in the perf.data file.
2553 * This also serves to suppress a warning about f_header.data.size == 0
2554 * in header.c at the moment 'perf stat record' gets introduced, which
2555 * is not really needed once we start adding the stat specific PERF_RECORD_
2556 * records, but the need to suppress the kptr_restrict messages in older
2557 * tools remain -acme
2559 int fd = perf_data_file__fd(&perf_stat.file);
2560 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2561 process_synthesized_event,
2562 &perf_stat.session->machines.host);
2564 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2565 "older tools may produce warnings about this file\n.");
2569 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2570 pr_err("failed to write stat round event\n");
2573 if (!perf_stat.file.is_pipe) {
2574 perf_stat.session->header.data_size += perf_stat.bytes_written;
2575 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2578 perf_session__delete(perf_stat.session);
2581 perf_stat__exit_aggr_mode();
2582 perf_evlist__free_stats(evsel_list);
2584 perf_evlist__delete(evsel_list);