4 * Builtin stat command: Give a precise performance counters summary
5 * overview about any workload, CPU or specific PID.
9 $ perf stat ./hackbench 10
13 Performance counter stats for './hackbench 10':
15 1708.761321 task-clock # 11.037 CPUs utilized
16 41,190 context-switches # 0.024 M/sec
17 6,735 CPU-migrations # 0.004 M/sec
18 17,318 page-faults # 0.010 M/sec
19 5,205,202,243 cycles # 3.046 GHz
20 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle
21 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle
22 2,603,501,247 instructions # 0.50 insns per cycle
23 # 1.48 stalled cycles per insn
24 484,357,498 branches # 283.455 M/sec
25 6,388,934 branch-misses # 1.32% of all branches
27 0.154822978 seconds time elapsed
30 * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
32 * Improvements and fixes by:
34 * Arjan van de Ven <arjan@linux.intel.com>
35 * Yanmin Zhang <yanmin.zhang@intel.com>
36 * Wu Fengguang <fengguang.wu@intel.com>
37 * Mike Galbraith <efault@gmx.de>
38 * Paul Mackerras <paulus@samba.org>
39 * Jaswinder Singh Rajput <jaswinder@kernel.org>
41 * Released under the GPL v2. (and only v2, not any later version)
46 #include "util/cgroup.h"
47 #include "util/util.h"
48 #include <subcmd/parse-options.h>
49 #include "util/parse-events.h"
51 #include "util/event.h"
52 #include "util/evlist.h"
53 #include "util/evsel.h"
54 #include "util/debug.h"
55 #include "util/drv_configs.h"
56 #include "util/color.h"
57 #include "util/stat.h"
58 #include "util/header.h"
59 #include "util/cpumap.h"
60 #include "util/thread.h"
61 #include "util/thread_map.h"
62 #include "util/counts.h"
63 #include "util/group.h"
64 #include "util/session.h"
65 #include "util/tool.h"
66 #include "util/group.h"
69 #include <linux/time64.h>
70 #include <api/fs/fs.h>
72 #include <sys/prctl.h>
77 #define DEFAULT_SEPARATOR " "
78 #define CNTR_NOT_SUPPORTED "<not supported>"
79 #define CNTR_NOT_COUNTED "<not counted>"
81 static void print_counters(struct timespec *ts, int argc, const char **argv);
83 /* Default events used for perf stat -T */
84 static const char *transaction_attrs = {
96 /* More limited version when the CPU does not have all events. */
97 static const char * transaction_limited_attrs = {
107 static const char * topdown_attrs[] = {
108 "topdown-total-slots",
109 "topdown-slots-retired",
110 "topdown-recovery-bubbles",
111 "topdown-fetch-bubbles",
112 "topdown-slots-issued",
116 static struct perf_evlist *evsel_list;
118 static struct target target = {
122 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
124 static int run_count = 1;
125 static bool no_inherit = false;
126 static volatile pid_t child_pid = -1;
127 static bool null_run = false;
128 static int detailed_run = 0;
129 static bool transaction_run;
130 static bool topdown_run = false;
131 static bool big_num = true;
132 static int big_num_opt = -1;
133 static const char *csv_sep = NULL;
134 static bool csv_output = false;
135 static bool group = false;
136 static const char *pre_cmd = NULL;
137 static const char *post_cmd = NULL;
138 static bool sync_run = false;
139 static unsigned int initial_delay = 0;
140 static unsigned int unit_width = 4; /* strlen("unit") */
141 static bool forever = false;
142 static bool metric_only = false;
143 static bool force_metric_only = false;
144 static bool no_merge = false;
145 static struct timespec ref_time;
146 static struct cpu_map *aggr_map;
147 static aggr_get_id_t aggr_get_id;
148 static bool append_file;
149 static const char *output_name;
150 static int output_fd;
151 static int print_free_counters_hint;
155 struct perf_data_file file;
156 struct perf_session *session;
158 struct perf_tool tool;
160 struct cpu_map *cpus;
161 struct thread_map *threads;
162 enum aggr_mode aggr_mode;
165 static struct perf_stat perf_stat;
166 #define STAT_RECORD perf_stat.record
168 static volatile int done = 0;
170 static struct perf_stat_config stat_config = {
171 .aggr_mode = AGGR_GLOBAL,
175 static inline void diff_timespec(struct timespec *r, struct timespec *a,
178 r->tv_sec = a->tv_sec - b->tv_sec;
179 if (a->tv_nsec < b->tv_nsec) {
180 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
183 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
187 static void perf_stat__reset_stats(void)
189 perf_evlist__reset_stats(evsel_list);
190 perf_stat__reset_shadow_stats();
193 static int create_perf_stat_counter(struct perf_evsel *evsel)
195 struct perf_event_attr *attr = &evsel->attr;
197 if (stat_config.scale)
198 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
199 PERF_FORMAT_TOTAL_TIME_RUNNING;
201 attr->inherit = !no_inherit;
204 * Some events get initialized with sample_(period/type) set,
205 * like tracepoints. Clear it up for counting.
207 attr->sample_period = 0;
210 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
211 * while avoiding that older tools show confusing messages.
213 * However for pipe sessions we need to keep it zero,
214 * because script's perf_evsel__check_attr is triggered
215 * by attr->sample_type != 0, and we can't run it on
218 if (!(STAT_RECORD && perf_stat.file.is_pipe))
219 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
222 * Disabling all counters initially, they will be enabled
223 * either manually by us or by kernel via enable_on_exec
226 if (perf_evsel__is_group_leader(evsel)) {
230 * In case of initial_delay we enable tracee
233 if (target__none(&target) && !initial_delay)
234 attr->enable_on_exec = 1;
237 if (target__has_cpu(&target))
238 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
240 return perf_evsel__open_per_thread(evsel, evsel_list->threads);
244 * Does the counter have nsecs as a unit?
246 static inline int nsec_counter(struct perf_evsel *evsel)
248 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
249 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
255 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
256 union perf_event *event,
257 struct perf_sample *sample __maybe_unused,
258 struct machine *machine __maybe_unused)
260 if (perf_data_file__write(&perf_stat.file, event, event->header.size) < 0) {
261 pr_err("failed to write perf data, error: %m\n");
265 perf_stat.bytes_written += event->header.size;
269 static int write_stat_round_event(u64 tm, u64 type)
271 return perf_event__synthesize_stat_round(NULL, tm, type,
272 process_synthesized_event,
276 #define WRITE_STAT_ROUND_EVENT(time, interval) \
277 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
279 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
282 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
283 struct perf_counts_values *count)
285 struct perf_sample_id *sid = SID(counter, cpu, thread);
287 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
288 process_synthesized_event, NULL);
292 * Read out the results of a single counter:
293 * do not aggregate counts across CPUs in system-wide mode
295 static int read_counter(struct perf_evsel *counter)
297 int nthreads = thread_map__nr(evsel_list->threads);
298 int ncpus, cpu, thread;
300 if (target__has_cpu(&target))
301 ncpus = perf_evsel__nr_cpus(counter);
305 if (!counter->supported)
308 if (counter->system_wide)
311 for (thread = 0; thread < nthreads; thread++) {
312 for (cpu = 0; cpu < ncpus; cpu++) {
313 struct perf_counts_values *count;
315 count = perf_counts(counter->counts, cpu, thread);
316 if (perf_evsel__read(counter, cpu, thread, count)) {
317 counter->counts->scaled = -1;
318 perf_counts(counter->counts, cpu, thread)->ena = 0;
319 perf_counts(counter->counts, cpu, thread)->run = 0;
324 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
325 pr_err("failed to write stat event\n");
331 fprintf(stat_config.output,
332 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
333 perf_evsel__name(counter),
335 count->val, count->ena, count->run);
343 static void read_counters(void)
345 struct perf_evsel *counter;
348 evlist__for_each_entry(evsel_list, counter) {
349 ret = read_counter(counter);
351 pr_debug("failed to read counter %s\n", counter->name);
353 if (ret == 0 && perf_stat_process_counter(&stat_config, counter))
354 pr_warning("failed to process counter %s\n", counter->name);
358 static void process_interval(void)
360 struct timespec ts, rs;
364 clock_gettime(CLOCK_MONOTONIC, &ts);
365 diff_timespec(&rs, &ts, &ref_time);
368 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
369 pr_err("failed to write stat round event\n");
372 print_counters(&rs, 0, NULL);
375 static void enable_counters(void)
378 usleep(initial_delay * USEC_PER_MSEC);
381 * We need to enable counters only if:
382 * - we don't have tracee (attaching to task or cpu)
383 * - we have initial delay configured
385 if (!target__none(&target) || initial_delay)
386 perf_evlist__enable(evsel_list);
389 static void disable_counters(void)
392 * If we don't have tracee (attaching to task or cpu), counters may
393 * still be running. To get accurate group ratios, we must stop groups
394 * from counting before reading their constituent counters.
396 if (!target__none(&target))
397 perf_evlist__disable(evsel_list);
400 static volatile int workload_exec_errno;
403 * perf_evlist__prepare_workload will send a SIGUSR1
404 * if the fork fails, since we asked by setting its
405 * want_signal to true.
407 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
408 void *ucontext __maybe_unused)
410 workload_exec_errno = info->si_value.sival_int;
413 static bool has_unit(struct perf_evsel *counter)
415 return counter->unit && *counter->unit;
418 static bool has_scale(struct perf_evsel *counter)
420 return counter->scale != 1;
423 static int perf_stat_synthesize_config(bool is_pipe)
425 struct perf_evsel *counter;
429 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
430 process_synthesized_event);
432 pr_err("Couldn't synthesize attrs.\n");
438 * Synthesize other events stuff not carried within
439 * attr event - unit, scale, name
441 evlist__for_each_entry(evsel_list, counter) {
442 if (!counter->supported)
446 * Synthesize unit and scale only if it's defined.
448 if (has_unit(counter)) {
449 err = perf_event__synthesize_event_update_unit(NULL, counter, process_synthesized_event);
451 pr_err("Couldn't synthesize evsel unit.\n");
456 if (has_scale(counter)) {
457 err = perf_event__synthesize_event_update_scale(NULL, counter, process_synthesized_event);
459 pr_err("Couldn't synthesize evsel scale.\n");
464 if (counter->own_cpus) {
465 err = perf_event__synthesize_event_update_cpus(NULL, counter, process_synthesized_event);
467 pr_err("Couldn't synthesize evsel scale.\n");
473 * Name is needed only for pipe output,
474 * perf.data carries event names.
477 err = perf_event__synthesize_event_update_name(NULL, counter, process_synthesized_event);
479 pr_err("Couldn't synthesize evsel name.\n");
485 err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
486 process_synthesized_event,
489 pr_err("Couldn't synthesize thread map.\n");
493 err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
494 process_synthesized_event, NULL);
496 pr_err("Couldn't synthesize thread map.\n");
500 err = perf_event__synthesize_stat_config(NULL, &stat_config,
501 process_synthesized_event, NULL);
503 pr_err("Couldn't synthesize config.\n");
510 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
512 static int __store_counter_ids(struct perf_evsel *counter,
513 struct cpu_map *cpus,
514 struct thread_map *threads)
518 for (cpu = 0; cpu < cpus->nr; cpu++) {
519 for (thread = 0; thread < threads->nr; thread++) {
520 int fd = FD(counter, cpu, thread);
522 if (perf_evlist__id_add_fd(evsel_list, counter,
523 cpu, thread, fd) < 0)
531 static int store_counter_ids(struct perf_evsel *counter)
533 struct cpu_map *cpus = counter->cpus;
534 struct thread_map *threads = counter->threads;
536 if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
539 return __store_counter_ids(counter, cpus, threads);
542 static int __run_perf_stat(int argc, const char **argv)
544 int interval = stat_config.interval;
546 unsigned long long t0, t1;
547 struct perf_evsel *counter;
551 const bool forks = (argc > 0);
552 bool is_pipe = STAT_RECORD ? perf_stat.file.is_pipe : false;
553 struct perf_evsel_config_term *err_term;
556 ts.tv_sec = interval / USEC_PER_MSEC;
557 ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
564 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
565 workload_exec_failed_signal) < 0) {
566 perror("failed to prepare workload");
569 child_pid = evsel_list->workload.pid;
573 perf_evlist__set_leader(evsel_list);
575 evlist__for_each_entry(evsel_list, counter) {
577 if (create_perf_stat_counter(counter) < 0) {
579 * PPC returns ENXIO for HW counters until 2.6.37
580 * (behavior changed with commit b0a873e).
582 if (errno == EINVAL || errno == ENOSYS ||
583 errno == ENOENT || errno == EOPNOTSUPP ||
586 ui__warning("%s event is not supported by the kernel.\n",
587 perf_evsel__name(counter));
588 counter->supported = false;
590 if ((counter->leader != counter) ||
591 !(counter->leader->nr_members > 1))
593 } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
595 ui__warning("%s\n", msg);
599 perf_evsel__open_strerror(counter, &target,
600 errno, msg, sizeof(msg));
601 ui__error("%s\n", msg);
604 kill(child_pid, SIGTERM);
608 counter->supported = true;
610 l = strlen(counter->unit);
614 if (STAT_RECORD && store_counter_ids(counter))
618 if (perf_evlist__apply_filters(evsel_list, &counter)) {
619 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
620 counter->filter, perf_evsel__name(counter), errno,
621 str_error_r(errno, msg, sizeof(msg)));
625 if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
626 error("failed to set config \"%s\" on event %s with %d (%s)\n",
627 err_term->val.drv_cfg, perf_evsel__name(counter), errno,
628 str_error_r(errno, msg, sizeof(msg)));
633 int err, fd = perf_data_file__fd(&perf_stat.file);
636 err = perf_header__write_pipe(perf_data_file__fd(&perf_stat.file));
638 err = perf_session__write_header(perf_stat.session, evsel_list,
645 err = perf_stat_synthesize_config(is_pipe);
651 * Enable counters and exec the command:
654 clock_gettime(CLOCK_MONOTONIC, &ref_time);
657 perf_evlist__start_workload(evsel_list);
661 while (!waitpid(child_pid, &status, WNOHANG)) {
662 nanosleep(&ts, NULL);
668 if (workload_exec_errno) {
669 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
670 pr_err("Workload failed: %s\n", emsg);
674 if (WIFSIGNALED(status))
675 psignal(WTERMSIG(status), argv[0]);
679 nanosleep(&ts, NULL);
689 update_stats(&walltime_nsecs_stats, t1 - t0);
692 * Closing a group leader splits the group, and as we only disable
693 * group leaders, results in remaining events becoming enabled. To
694 * avoid arbitrary skew, we must read all counters before closing any
698 perf_evlist__close(evsel_list);
700 return WEXITSTATUS(status);
703 static int run_perf_stat(int argc, const char **argv)
708 ret = system(pre_cmd);
716 ret = __run_perf_stat(argc, argv);
721 ret = system(post_cmd);
729 static void print_running(u64 run, u64 ena)
732 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
736 ena ? 100.0 * run / ena : 100.0);
737 } else if (run != ena) {
738 fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena);
742 static void print_noise_pct(double total, double avg)
744 double pct = rel_stddev_stats(total, avg);
747 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
749 fprintf(stat_config.output, " ( +-%6.2f%% )", pct);
752 static void print_noise(struct perf_evsel *evsel, double avg)
754 struct perf_stat_evsel *ps;
760 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
763 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
765 switch (stat_config.aggr_mode) {
767 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
768 cpu_map__id_to_socket(id),
770 cpu_map__id_to_cpu(id),
777 fprintf(stat_config.output, "S%*d%s%*d%s",
786 fprintf(stat_config.output, "CPU%*d%s",
788 perf_evsel__cpus(evsel)->map[id], csv_sep);
791 fprintf(stat_config.output, "%*s-%*d%s",
793 thread_map__comm(evsel->threads, id),
795 thread_map__pid(evsel->threads, id),
811 struct perf_evsel *evsel;
814 #define METRIC_LEN 35
816 static void new_line_std(void *ctx)
818 struct outstate *os = ctx;
823 static void do_new_line_std(struct outstate *os)
826 fputs(os->prefix, os->fh);
827 aggr_printout(os->evsel, os->id, os->nr);
828 if (stat_config.aggr_mode == AGGR_NONE)
829 fprintf(os->fh, " ");
830 fprintf(os->fh, " ");
833 static void print_metric_std(void *ctx, const char *color, const char *fmt,
834 const char *unit, double val)
836 struct outstate *os = ctx;
839 bool newline = os->newline;
843 if (unit == NULL || fmt == NULL) {
844 fprintf(out, "%-*s", METRIC_LEN, "");
851 n = fprintf(out, " # ");
853 n += color_fprintf(out, color, fmt, val);
855 n += fprintf(out, fmt, val);
856 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
859 static void new_line_csv(void *ctx)
861 struct outstate *os = ctx;
866 fprintf(os->fh, "%s%s", os->prefix, csv_sep);
867 aggr_printout(os->evsel, os->id, os->nr);
868 for (i = 0; i < os->nfields; i++)
869 fputs(csv_sep, os->fh);
872 static void print_metric_csv(void *ctx,
873 const char *color __maybe_unused,
874 const char *fmt, const char *unit, double val)
876 struct outstate *os = ctx;
878 char buf[64], *vals, *ends;
880 if (unit == NULL || fmt == NULL) {
881 fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
884 snprintf(buf, sizeof(buf), fmt, val);
885 ends = vals = ltrim(buf);
886 while (isdigit(*ends) || *ends == '.')
889 while (isspace(*unit))
891 fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
894 #define METRIC_ONLY_LEN 20
896 /* Filter out some columns that don't work well in metrics only mode */
898 static bool valid_only_metric(const char *unit)
902 if (strstr(unit, "/sec") ||
903 strstr(unit, "hz") ||
904 strstr(unit, "Hz") ||
905 strstr(unit, "CPUs utilized"))
910 static const char *fixunit(char *buf, struct perf_evsel *evsel,
913 if (!strncmp(unit, "of all", 6)) {
914 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
921 static void print_metric_only(void *ctx, const char *color, const char *fmt,
922 const char *unit, double val)
924 struct outstate *os = ctx;
928 unsigned mlen = METRIC_ONLY_LEN;
930 if (!valid_only_metric(unit))
932 unit = fixunit(buf, os->evsel, unit);
934 n = color_fprintf(out, color, fmt, val);
936 n = fprintf(out, fmt, val);
937 if (n > METRIC_ONLY_LEN)
939 if (mlen < strlen(unit))
940 mlen = strlen(unit) + 1;
941 fprintf(out, "%*s", mlen - n, "");
944 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
946 const char *unit, double val)
948 struct outstate *os = ctx;
950 char buf[64], *vals, *ends;
953 if (!valid_only_metric(unit))
955 unit = fixunit(tbuf, os->evsel, unit);
956 snprintf(buf, sizeof buf, fmt, val);
957 ends = vals = ltrim(buf);
958 while (isdigit(*ends) || *ends == '.')
961 fprintf(out, "%s%s", vals, csv_sep);
964 static void new_line_metric(void *ctx __maybe_unused)
968 static void print_metric_header(void *ctx, const char *color __maybe_unused,
969 const char *fmt __maybe_unused,
970 const char *unit, double val __maybe_unused)
972 struct outstate *os = ctx;
975 if (!valid_only_metric(unit))
977 unit = fixunit(tbuf, os->evsel, unit);
979 fprintf(os->fh, "%s%s", unit, csv_sep);
981 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
984 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
986 FILE *output = stat_config.output;
987 double msecs = avg / NSEC_PER_MSEC;
988 const char *fmt_v, *fmt_n;
991 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
992 fmt_n = csv_output ? "%s" : "%-25s";
994 aggr_printout(evsel, id, nr);
996 scnprintf(name, sizeof(name), "%s%s",
997 perf_evsel__name(evsel), csv_output ? "" : " (msec)");
999 fprintf(output, fmt_v, msecs, csv_sep);
1002 fprintf(output, "%s%s", evsel->unit, csv_sep);
1004 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
1006 fprintf(output, fmt_n, name);
1009 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1012 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
1019 if (stat_config.aggr_mode == AGGR_NONE)
1022 if (stat_config.aggr_mode == AGGR_GLOBAL)
1025 for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
1026 int cpu2 = perf_evsel__cpus(evsel)->map[i];
1028 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
1034 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1036 FILE *output = stat_config.output;
1037 double sc = evsel->scale;
1041 fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
1044 fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
1046 fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
1049 aggr_printout(evsel, id, nr);
1051 fprintf(output, fmt, avg, csv_sep);
1054 fprintf(output, "%-*s%s",
1055 csv_output ? 0 : unit_width,
1056 evsel->unit, csv_sep);
1058 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1061 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1064 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
1065 char *prefix, u64 run, u64 ena, double noise)
1067 struct perf_stat_output_ctx out;
1068 struct outstate os = {
1069 .fh = stat_config.output,
1070 .prefix = prefix ? prefix : "",
1075 print_metric_t pm = print_metric_std;
1079 nl = new_line_metric;
1081 pm = print_metric_only_csv;
1083 pm = print_metric_only;
1087 if (csv_output && !metric_only) {
1088 static int aggr_fields[] = {
1096 pm = print_metric_csv;
1099 os.nfields += aggr_fields[stat_config.aggr_mode];
1103 if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1105 pm(&os, NULL, "", "", 0);
1108 aggr_printout(counter, id, nr);
1110 fprintf(stat_config.output, "%*s%s",
1111 csv_output ? 0 : 18,
1112 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1115 if (counter->supported)
1116 print_free_counters_hint = 1;
1118 fprintf(stat_config.output, "%-*s%s",
1119 csv_output ? 0 : unit_width,
1120 counter->unit, csv_sep);
1122 fprintf(stat_config.output, "%*s",
1123 csv_output ? 0 : -25,
1124 perf_evsel__name(counter));
1127 fprintf(stat_config.output, "%s%s",
1128 csv_sep, counter->cgrp->name);
1131 pm(&os, NULL, NULL, "", 0);
1132 print_noise(counter, noise);
1133 print_running(run, ena);
1135 pm(&os, NULL, NULL, "", 0);
1141 else if (nsec_counter(counter))
1142 nsec_printout(id, nr, counter, uval);
1144 abs_printout(id, nr, counter, uval);
1146 out.print_metric = pm;
1149 out.force_header = false;
1151 if (csv_output && !metric_only) {
1152 print_noise(counter, noise);
1153 print_running(run, ena);
1156 perf_stat__print_shadow_stats(counter, uval,
1157 first_shadow_cpu(counter, id),
1159 if (!csv_output && !metric_only) {
1160 print_noise(counter, noise);
1161 print_running(run, ena);
1165 static void aggr_update_shadow(void)
1169 struct perf_evsel *counter;
1171 for (s = 0; s < aggr_map->nr; s++) {
1172 id = aggr_map->map[s];
1173 evlist__for_each_entry(evsel_list, counter) {
1175 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1176 s2 = aggr_get_id(evsel_list->cpus, cpu);
1179 val += perf_counts(counter->counts, cpu, 0)->val;
1181 val = val * counter->scale;
1182 perf_stat__update_shadow_stats(counter, &val,
1183 first_shadow_cpu(counter, id));
1188 static void collect_all_aliases(struct perf_evsel *counter,
1189 void (*cb)(struct perf_evsel *counter, void *data,
1193 struct perf_evsel *alias;
1195 alias = list_prepare_entry(counter, &(evsel_list->entries), node);
1196 list_for_each_entry_continue (alias, &evsel_list->entries, node) {
1197 if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
1198 alias->scale != counter->scale ||
1199 alias->cgrp != counter->cgrp ||
1200 strcmp(alias->unit, counter->unit) ||
1201 nsec_counter(alias) != nsec_counter(counter))
1203 alias->merged_stat = true;
1204 cb(alias, data, false);
1208 static bool collect_data(struct perf_evsel *counter,
1209 void (*cb)(struct perf_evsel *counter, void *data,
1213 if (counter->merged_stat)
1215 cb(counter, data, true);
1217 collect_all_aliases(counter, cb, data);
1228 static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
1230 struct aggr_data *ad = data;
1233 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1234 struct perf_counts_values *counts;
1236 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1241 counts = perf_counts(counter->counts, cpu, 0);
1243 * When any result is bad, make them all to give
1244 * consistent output in interval mode.
1246 if (counts->ena == 0 || counts->run == 0 ||
1247 counter->counts->scaled == -1) {
1252 ad->val += counts->val;
1253 ad->ena += counts->ena;
1254 ad->run += counts->run;
1258 static void print_aggr(char *prefix)
1260 FILE *output = stat_config.output;
1261 struct perf_evsel *counter;
1267 if (!(aggr_map || aggr_get_id))
1270 aggr_update_shadow();
1273 * With metric_only everything is on a single line.
1274 * Without each counter has its own line.
1276 for (s = 0; s < aggr_map->nr; s++) {
1277 struct aggr_data ad;
1278 if (prefix && metric_only)
1279 fprintf(output, "%s", prefix);
1281 ad.id = id = aggr_map->map[s];
1283 evlist__for_each_entry(evsel_list, counter) {
1284 ad.val = ad.ena = ad.run = 0;
1286 if (!collect_data(counter, aggr_cb, &ad))
1292 if (first && metric_only) {
1294 aggr_printout(counter, id, nr);
1296 if (prefix && !metric_only)
1297 fprintf(output, "%s", prefix);
1299 uval = val * counter->scale;
1300 printout(id, nr, counter, uval, prefix, run, ena, 1.0);
1302 fputc('\n', output);
1305 fputc('\n', output);
1309 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1311 FILE *output = stat_config.output;
1312 int nthreads = thread_map__nr(counter->threads);
1313 int ncpus = cpu_map__nr(counter->cpus);
1317 for (thread = 0; thread < nthreads; thread++) {
1318 u64 ena = 0, run = 0, val = 0;
1320 for (cpu = 0; cpu < ncpus; cpu++) {
1321 val += perf_counts(counter->counts, cpu, thread)->val;
1322 ena += perf_counts(counter->counts, cpu, thread)->ena;
1323 run += perf_counts(counter->counts, cpu, thread)->run;
1327 fprintf(output, "%s", prefix);
1329 uval = val * counter->scale;
1330 printout(thread, 0, counter, uval, prefix, run, ena, 1.0);
1331 fputc('\n', output);
1336 double avg, avg_enabled, avg_running;
1339 static void counter_aggr_cb(struct perf_evsel *counter, void *data,
1340 bool first __maybe_unused)
1342 struct caggr_data *cd = data;
1343 struct perf_stat_evsel *ps = counter->priv;
1345 cd->avg += avg_stats(&ps->res_stats[0]);
1346 cd->avg_enabled += avg_stats(&ps->res_stats[1]);
1347 cd->avg_running += avg_stats(&ps->res_stats[2]);
1351 * Print out the results of a single counter:
1352 * aggregated counts in system-wide mode
1354 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1356 FILE *output = stat_config.output;
1358 struct caggr_data cd = { .avg = 0.0 };
1360 if (!collect_data(counter, counter_aggr_cb, &cd))
1363 if (prefix && !metric_only)
1364 fprintf(output, "%s", prefix);
1366 uval = cd.avg * counter->scale;
1367 printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled, cd.avg);
1369 fprintf(output, "\n");
1372 static void counter_cb(struct perf_evsel *counter, void *data,
1373 bool first __maybe_unused)
1375 struct aggr_data *ad = data;
1377 ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
1378 ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
1379 ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
1383 * Print out the results of a single counter:
1384 * does not use aggregated count in system-wide
1386 static void print_counter(struct perf_evsel *counter, char *prefix)
1388 FILE *output = stat_config.output;
1393 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1394 struct aggr_data ad = { .cpu = cpu };
1396 if (!collect_data(counter, counter_cb, &ad))
1403 fprintf(output, "%s", prefix);
1405 uval = val * counter->scale;
1406 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1408 fputc('\n', output);
1412 static void print_no_aggr_metric(char *prefix)
1416 struct perf_evsel *counter;
1420 nrcpus = evsel_list->cpus->nr;
1421 for (cpu = 0; cpu < nrcpus; cpu++) {
1425 fputs(prefix, stat_config.output);
1426 evlist__for_each_entry(evsel_list, counter) {
1428 aggr_printout(counter, cpu, 0);
1431 val = perf_counts(counter->counts, cpu, 0)->val;
1432 ena = perf_counts(counter->counts, cpu, 0)->ena;
1433 run = perf_counts(counter->counts, cpu, 0)->run;
1435 uval = val * counter->scale;
1436 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1438 fputc('\n', stat_config.output);
1442 static int aggr_header_lens[] = {
1450 static const char *aggr_header_csv[] = {
1451 [AGGR_CORE] = "core,cpus,",
1452 [AGGR_SOCKET] = "socket,cpus",
1453 [AGGR_NONE] = "cpu,",
1454 [AGGR_THREAD] = "comm-pid,",
1458 static void print_metric_headers(const char *prefix, bool no_indent)
1460 struct perf_stat_output_ctx out;
1461 struct perf_evsel *counter;
1462 struct outstate os = {
1463 .fh = stat_config.output
1467 fprintf(stat_config.output, "%s", prefix);
1469 if (!csv_output && !no_indent)
1470 fprintf(stat_config.output, "%*s",
1471 aggr_header_lens[stat_config.aggr_mode], "");
1473 if (stat_config.interval)
1474 fputs("time,", stat_config.output);
1475 fputs(aggr_header_csv[stat_config.aggr_mode],
1476 stat_config.output);
1479 /* Print metrics headers only */
1480 evlist__for_each_entry(evsel_list, counter) {
1483 out.print_metric = print_metric_header;
1484 out.new_line = new_line_metric;
1485 out.force_header = true;
1487 perf_stat__print_shadow_stats(counter, 0,
1491 fputc('\n', stat_config.output);
1494 static void print_interval(char *prefix, struct timespec *ts)
1496 FILE *output = stat_config.output;
1497 static int num_print_interval;
1499 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1501 if (num_print_interval == 0 && !csv_output) {
1502 switch (stat_config.aggr_mode) {
1504 fprintf(output, "# time socket cpus");
1506 fprintf(output, " counts %*s events\n", unit_width, "unit");
1509 fprintf(output, "# time core cpus");
1511 fprintf(output, " counts %*s events\n", unit_width, "unit");
1514 fprintf(output, "# time CPU");
1516 fprintf(output, " counts %*s events\n", unit_width, "unit");
1519 fprintf(output, "# time comm-pid");
1521 fprintf(output, " counts %*s events\n", unit_width, "unit");
1525 fprintf(output, "# time");
1527 fprintf(output, " counts %*s events\n", unit_width, "unit");
1533 if (num_print_interval == 0 && metric_only)
1534 print_metric_headers(" ", true);
1535 if (++num_print_interval == 25)
1536 num_print_interval = 0;
1539 static void print_header(int argc, const char **argv)
1541 FILE *output = stat_config.output;
1547 fprintf(output, "\n");
1548 fprintf(output, " Performance counter stats for ");
1549 if (target.system_wide)
1550 fprintf(output, "\'system wide");
1551 else if (target.cpu_list)
1552 fprintf(output, "\'CPU(s) %s", target.cpu_list);
1553 else if (!target__has_task(&target)) {
1554 fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1555 for (i = 1; argv && (i < argc); i++)
1556 fprintf(output, " %s", argv[i]);
1557 } else if (target.pid)
1558 fprintf(output, "process id \'%s", target.pid);
1560 fprintf(output, "thread id \'%s", target.tid);
1562 fprintf(output, "\'");
1564 fprintf(output, " (%d runs)", run_count);
1565 fprintf(output, ":\n\n");
1569 static void print_footer(void)
1571 FILE *output = stat_config.output;
1574 fprintf(output, "\n");
1575 fprintf(output, " %17.9f seconds time elapsed",
1576 avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
1577 if (run_count > 1) {
1578 fprintf(output, " ");
1579 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1580 avg_stats(&walltime_nsecs_stats));
1582 fprintf(output, "\n\n");
1584 if (print_free_counters_hint)
1586 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1587 " echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1589 " echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1592 static void print_counters(struct timespec *ts, int argc, const char **argv)
1594 int interval = stat_config.interval;
1595 struct perf_evsel *counter;
1596 char buf[64], *prefix = NULL;
1598 /* Do not print anything if we record to the pipe. */
1599 if (STAT_RECORD && perf_stat.file.is_pipe)
1603 print_interval(prefix = buf, ts);
1605 print_header(argc, argv);
1608 static int num_print_iv;
1610 if (num_print_iv == 0 && !interval)
1611 print_metric_headers(prefix, false);
1612 if (num_print_iv++ == 25)
1614 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1615 fprintf(stat_config.output, "%s", prefix);
1618 switch (stat_config.aggr_mode) {
1624 evlist__for_each_entry(evsel_list, counter)
1625 print_aggr_thread(counter, prefix);
1628 evlist__for_each_entry(evsel_list, counter)
1629 print_counter_aggr(counter, prefix);
1631 fputc('\n', stat_config.output);
1635 print_no_aggr_metric(prefix);
1637 evlist__for_each_entry(evsel_list, counter)
1638 print_counter(counter, prefix);
1646 if (!interval && !csv_output)
1649 fflush(stat_config.output);
1652 static volatile int signr = -1;
1654 static void skip_signal(int signo)
1656 if ((child_pid == -1) || stat_config.interval)
1661 * render child_pid harmless
1662 * won't send SIGTERM to a random
1663 * process in case of race condition
1664 * and fast PID recycling
1669 static void sig_atexit(void)
1674 * avoid race condition with SIGCHLD handler
1675 * in skip_signal() which is modifying child_pid
1676 * goal is to avoid send SIGTERM to a random
1680 sigaddset(&set, SIGCHLD);
1681 sigprocmask(SIG_BLOCK, &set, &oset);
1683 if (child_pid != -1)
1684 kill(child_pid, SIGTERM);
1686 sigprocmask(SIG_SETMASK, &oset, NULL);
1691 signal(signr, SIG_DFL);
1692 kill(getpid(), signr);
1695 static int stat__set_big_num(const struct option *opt __maybe_unused,
1696 const char *s __maybe_unused, int unset)
1698 big_num_opt = unset ? 0 : 1;
1702 static int enable_metric_only(const struct option *opt __maybe_unused,
1703 const char *s __maybe_unused, int unset)
1705 force_metric_only = true;
1706 metric_only = !unset;
1710 static const struct option stat_options[] = {
1711 OPT_BOOLEAN('T', "transaction", &transaction_run,
1712 "hardware transaction statistics"),
1713 OPT_CALLBACK('e', "event", &evsel_list, "event",
1714 "event selector. use 'perf list' to list available events",
1715 parse_events_option),
1716 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1717 "event filter", parse_filter),
1718 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1719 "child tasks do not inherit counters"),
1720 OPT_STRING('p', "pid", &target.pid, "pid",
1721 "stat events on existing process id"),
1722 OPT_STRING('t', "tid", &target.tid, "tid",
1723 "stat events on existing thread id"),
1724 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1725 "system-wide collection from all CPUs"),
1726 OPT_BOOLEAN('g', "group", &group,
1727 "put the counters into a counter group"),
1728 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1729 OPT_INCR('v', "verbose", &verbose,
1730 "be more verbose (show counter open errors, etc)"),
1731 OPT_INTEGER('r', "repeat", &run_count,
1732 "repeat command and print average + stddev (max: 100, forever: 0)"),
1733 OPT_BOOLEAN('n', "null", &null_run,
1734 "null run - dont start any counters"),
1735 OPT_INCR('d', "detailed", &detailed_run,
1736 "detailed run - start a lot of events"),
1737 OPT_BOOLEAN('S', "sync", &sync_run,
1738 "call sync() before starting a run"),
1739 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1740 "print large numbers with thousands\' separators",
1742 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1743 "list of cpus to monitor in system-wide"),
1744 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1745 "disable CPU count aggregation", AGGR_NONE),
1746 OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
1747 OPT_STRING('x', "field-separator", &csv_sep, "separator",
1748 "print counts with custom separator"),
1749 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1750 "monitor event in cgroup name only", parse_cgroups),
1751 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1752 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1753 OPT_INTEGER(0, "log-fd", &output_fd,
1754 "log output to fd, instead of stderr"),
1755 OPT_STRING(0, "pre", &pre_cmd, "command",
1756 "command to run prior to the measured command"),
1757 OPT_STRING(0, "post", &post_cmd, "command",
1758 "command to run after to the measured command"),
1759 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1760 "print counts at regular interval in ms (>= 10)"),
1761 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1762 "aggregate counts per processor socket", AGGR_SOCKET),
1763 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1764 "aggregate counts per physical processor core", AGGR_CORE),
1765 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1766 "aggregate counts per thread", AGGR_THREAD),
1767 OPT_UINTEGER('D', "delay", &initial_delay,
1768 "ms to wait before starting measurement after program start"),
1769 OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
1770 "Only print computed metrics. No raw values", enable_metric_only),
1771 OPT_BOOLEAN(0, "topdown", &topdown_run,
1772 "measure topdown level 1 statistics"),
1776 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1778 return cpu_map__get_socket(map, cpu, NULL);
1781 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1783 return cpu_map__get_core(map, cpu, NULL);
1786 static int cpu_map__get_max(struct cpu_map *map)
1790 for (i = 0; i < map->nr; i++) {
1791 if (map->map[i] > max)
1798 static struct cpu_map *cpus_aggr_map;
1800 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1807 cpu = map->map[idx];
1809 if (cpus_aggr_map->map[cpu] == -1)
1810 cpus_aggr_map->map[cpu] = get_id(map, idx);
1812 return cpus_aggr_map->map[cpu];
1815 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1817 return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1820 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1822 return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1825 static int perf_stat_init_aggr_mode(void)
1829 switch (stat_config.aggr_mode) {
1831 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1832 perror("cannot build socket map");
1835 aggr_get_id = perf_stat__get_socket_cached;
1838 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1839 perror("cannot build core map");
1842 aggr_get_id = perf_stat__get_core_cached;
1853 * The evsel_list->cpus is the base we operate on,
1854 * taking the highest cpu number to be the size of
1855 * the aggregation translate cpumap.
1857 nr = cpu_map__get_max(evsel_list->cpus);
1858 cpus_aggr_map = cpu_map__empty_new(nr + 1);
1859 return cpus_aggr_map ? 0 : -ENOMEM;
1862 static void perf_stat__exit_aggr_mode(void)
1864 cpu_map__put(aggr_map);
1865 cpu_map__put(cpus_aggr_map);
1867 cpus_aggr_map = NULL;
1870 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1877 cpu = map->map[idx];
1879 if (cpu >= env->nr_cpus_avail)
1885 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1887 struct perf_env *env = data;
1888 int cpu = perf_env__get_cpu(env, map, idx);
1890 return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1893 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1895 struct perf_env *env = data;
1896 int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1899 int socket_id = env->cpu[cpu].socket_id;
1902 * Encode socket in upper 16 bits
1903 * core_id is relative to socket, and
1904 * we need a global id. So we combine
1907 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1913 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1914 struct cpu_map **sockp)
1916 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1919 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
1920 struct cpu_map **corep)
1922 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1925 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
1927 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1930 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
1932 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1935 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1937 struct perf_env *env = &st->session->header.env;
1939 switch (stat_config.aggr_mode) {
1941 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
1942 perror("cannot build socket map");
1945 aggr_get_id = perf_stat__get_socket_file;
1948 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
1949 perror("cannot build core map");
1952 aggr_get_id = perf_stat__get_core_file;
1965 static int topdown_filter_events(const char **attr, char **str, bool use_group)
1972 for (i = 0; attr[i]; i++) {
1973 if (pmu_have_event("cpu", attr[i])) {
1974 len += strlen(attr[i]) + 1;
1975 attr[i - off] = attr[i];
1979 attr[i - off] = NULL;
1981 *str = malloc(len + 1 + 2);
1991 for (i = 0; attr[i]; i++) {
2004 __weak bool arch_topdown_check_group(bool *warn)
2010 __weak void arch_topdown_group_warn(void)
2015 * Add default attributes, if there were no attributes specified or
2016 * if -d/--detailed, -d -d or -d -d -d is used:
2018 static int add_default_attributes(void)
2021 struct perf_event_attr default_attrs0[] = {
2023 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
2024 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
2025 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
2026 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
2028 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
2030 struct perf_event_attr frontend_attrs[] = {
2031 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
2033 struct perf_event_attr backend_attrs[] = {
2034 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
2036 struct perf_event_attr default_attrs1[] = {
2037 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
2038 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
2039 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
2044 * Detailed stats (-d), covering the L1 and last level data caches:
2046 struct perf_event_attr detailed_attrs[] = {
2048 { .type = PERF_TYPE_HW_CACHE,
2050 PERF_COUNT_HW_CACHE_L1D << 0 |
2051 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2052 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2054 { .type = PERF_TYPE_HW_CACHE,
2056 PERF_COUNT_HW_CACHE_L1D << 0 |
2057 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2058 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2060 { .type = PERF_TYPE_HW_CACHE,
2062 PERF_COUNT_HW_CACHE_LL << 0 |
2063 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2064 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2066 { .type = PERF_TYPE_HW_CACHE,
2068 PERF_COUNT_HW_CACHE_LL << 0 |
2069 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2070 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2074 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2076 struct perf_event_attr very_detailed_attrs[] = {
2078 { .type = PERF_TYPE_HW_CACHE,
2080 PERF_COUNT_HW_CACHE_L1I << 0 |
2081 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2082 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2084 { .type = PERF_TYPE_HW_CACHE,
2086 PERF_COUNT_HW_CACHE_L1I << 0 |
2087 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2088 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2090 { .type = PERF_TYPE_HW_CACHE,
2092 PERF_COUNT_HW_CACHE_DTLB << 0 |
2093 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2094 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2096 { .type = PERF_TYPE_HW_CACHE,
2098 PERF_COUNT_HW_CACHE_DTLB << 0 |
2099 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2100 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2102 { .type = PERF_TYPE_HW_CACHE,
2104 PERF_COUNT_HW_CACHE_ITLB << 0 |
2105 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2106 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2108 { .type = PERF_TYPE_HW_CACHE,
2110 PERF_COUNT_HW_CACHE_ITLB << 0 |
2111 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2112 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2117 * Very, very detailed stats (-d -d -d), adding prefetch events:
2119 struct perf_event_attr very_very_detailed_attrs[] = {
2121 { .type = PERF_TYPE_HW_CACHE,
2123 PERF_COUNT_HW_CACHE_L1D << 0 |
2124 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2125 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2127 { .type = PERF_TYPE_HW_CACHE,
2129 PERF_COUNT_HW_CACHE_L1D << 0 |
2130 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2131 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2134 /* Set attrs if no event is selected and !null_run: */
2138 if (transaction_run) {
2139 if (pmu_have_event("cpu", "cycles-ct") &&
2140 pmu_have_event("cpu", "el-start"))
2141 err = parse_events(evsel_list, transaction_attrs, NULL);
2143 err = parse_events(evsel_list, transaction_limited_attrs, NULL);
2145 fprintf(stderr, "Cannot set up transaction events\n");
2155 if (stat_config.aggr_mode != AGGR_GLOBAL &&
2156 stat_config.aggr_mode != AGGR_CORE) {
2157 pr_err("top down event configuration requires --per-core mode\n");
2160 stat_config.aggr_mode = AGGR_CORE;
2161 if (nr_cgroups || !target__has_cpu(&target)) {
2162 pr_err("top down event configuration requires system-wide mode (-a)\n");
2166 if (!force_metric_only)
2168 if (topdown_filter_events(topdown_attrs, &str,
2169 arch_topdown_check_group(&warn)) < 0) {
2170 pr_err("Out of memory\n");
2173 if (topdown_attrs[0] && str) {
2175 arch_topdown_group_warn();
2176 err = parse_events(evsel_list, str, NULL);
2179 "Cannot set up top down events %s: %d\n",
2185 fprintf(stderr, "System does not support topdown\n");
2191 if (!evsel_list->nr_entries) {
2192 if (target__has_cpu(&target))
2193 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2195 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2197 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2198 if (perf_evlist__add_default_attrs(evsel_list,
2199 frontend_attrs) < 0)
2202 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2203 if (perf_evlist__add_default_attrs(evsel_list,
2207 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2211 /* Detailed events get appended to the event list: */
2213 if (detailed_run < 1)
2216 /* Append detailed run extra attributes: */
2217 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2220 if (detailed_run < 2)
2223 /* Append very detailed run extra attributes: */
2224 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2227 if (detailed_run < 3)
2230 /* Append very, very detailed run extra attributes: */
2231 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2234 static const char * const stat_record_usage[] = {
2235 "perf stat record [<options>]",
2239 static void init_features(struct perf_session *session)
2243 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2244 perf_header__set_feat(&session->header, feat);
2246 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2247 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2248 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2249 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2252 static int __cmd_record(int argc, const char **argv)
2254 struct perf_session *session;
2255 struct perf_data_file *file = &perf_stat.file;
2257 argc = parse_options(argc, argv, stat_options, stat_record_usage,
2258 PARSE_OPT_STOP_AT_NON_OPTION);
2261 file->path = output_name;
2263 if (run_count != 1 || forever) {
2264 pr_err("Cannot use -r option with perf stat record.\n");
2268 session = perf_session__new(file, false, NULL);
2269 if (session == NULL) {
2270 pr_err("Perf session creation failed.\n");
2274 init_features(session);
2276 session->evlist = evsel_list;
2277 perf_stat.session = session;
2278 perf_stat.record = true;
2282 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2283 union perf_event *event,
2284 struct perf_session *session)
2286 struct stat_round_event *stat_round = &event->stat_round;
2287 struct perf_evsel *counter;
2288 struct timespec tsh, *ts = NULL;
2289 const char **argv = session->header.env.cmdline_argv;
2290 int argc = session->header.env.nr_cmdline;
2292 evlist__for_each_entry(evsel_list, counter)
2293 perf_stat_process_counter(&stat_config, counter);
2295 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2296 update_stats(&walltime_nsecs_stats, stat_round->time);
2298 if (stat_config.interval && stat_round->time) {
2299 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2300 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2304 print_counters(ts, argc, argv);
2309 int process_stat_config_event(struct perf_tool *tool,
2310 union perf_event *event,
2311 struct perf_session *session __maybe_unused)
2313 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2315 perf_event__read_stat_config(&stat_config, &event->stat_config);
2317 if (cpu_map__empty(st->cpus)) {
2318 if (st->aggr_mode != AGGR_UNSET)
2319 pr_warning("warning: processing task data, aggregation mode not set\n");
2323 if (st->aggr_mode != AGGR_UNSET)
2324 stat_config.aggr_mode = st->aggr_mode;
2326 if (perf_stat.file.is_pipe)
2327 perf_stat_init_aggr_mode();
2329 perf_stat_init_aggr_mode_file(st);
2334 static int set_maps(struct perf_stat *st)
2336 if (!st->cpus || !st->threads)
2339 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2342 perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2344 if (perf_evlist__alloc_stats(evsel_list, true))
2347 st->maps_allocated = true;
2352 int process_thread_map_event(struct perf_tool *tool,
2353 union perf_event *event,
2354 struct perf_session *session __maybe_unused)
2356 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2359 pr_warning("Extra thread map event, ignoring.\n");
2363 st->threads = thread_map__new_event(&event->thread_map);
2367 return set_maps(st);
2371 int process_cpu_map_event(struct perf_tool *tool,
2372 union perf_event *event,
2373 struct perf_session *session __maybe_unused)
2375 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2376 struct cpu_map *cpus;
2379 pr_warning("Extra cpu map event, ignoring.\n");
2383 cpus = cpu_map__new_data(&event->cpu_map.data);
2388 return set_maps(st);
2391 static const char * const stat_report_usage[] = {
2392 "perf stat report [<options>]",
2396 static struct perf_stat perf_stat = {
2398 .attr = perf_event__process_attr,
2399 .event_update = perf_event__process_event_update,
2400 .thread_map = process_thread_map_event,
2401 .cpu_map = process_cpu_map_event,
2402 .stat_config = process_stat_config_event,
2403 .stat = perf_event__process_stat_event,
2404 .stat_round = process_stat_round_event,
2406 .aggr_mode = AGGR_UNSET,
2409 static int __cmd_report(int argc, const char **argv)
2411 struct perf_session *session;
2412 const struct option options[] = {
2413 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2414 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2415 "aggregate counts per processor socket", AGGR_SOCKET),
2416 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2417 "aggregate counts per physical processor core", AGGR_CORE),
2418 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2419 "disable CPU count aggregation", AGGR_NONE),
2425 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2427 if (!input_name || !strlen(input_name)) {
2428 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2431 input_name = "perf.data";
2434 perf_stat.file.path = input_name;
2435 perf_stat.file.mode = PERF_DATA_MODE_READ;
2437 session = perf_session__new(&perf_stat.file, false, &perf_stat.tool);
2438 if (session == NULL)
2441 perf_stat.session = session;
2442 stat_config.output = stderr;
2443 evsel_list = session->evlist;
2445 ret = perf_session__process_events(session);
2449 perf_session__delete(session);
2453 static void setup_system_wide(int forks)
2456 * Make system wide (-a) the default target if
2457 * no target was specified and one of following
2458 * conditions is met:
2460 * - there's no workload specified
2461 * - there is workload specified but all requested
2462 * events are system wide events
2464 if (!target__none(&target))
2468 target.system_wide = true;
2470 struct perf_evsel *counter;
2472 evlist__for_each_entry(evsel_list, counter) {
2473 if (!counter->system_wide)
2477 if (evsel_list->nr_entries)
2478 target.system_wide = true;
2482 int cmd_stat(int argc, const char **argv)
2484 const char * const stat_usage[] = {
2485 "perf stat [<options>] [<command>]",
2488 int status = -EINVAL, run_idx;
2490 FILE *output = stderr;
2491 unsigned int interval;
2492 const char * const stat_subcommands[] = { "record", "report" };
2494 setlocale(LC_ALL, "");
2496 evsel_list = perf_evlist__new();
2497 if (evsel_list == NULL)
2500 parse_events__shrink_config_terms();
2501 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2502 (const char **) stat_usage,
2503 PARSE_OPT_STOP_AT_NON_OPTION);
2504 perf_stat__collect_metric_expr(evsel_list);
2505 perf_stat__init_shadow_stats();
2509 if (!strcmp(csv_sep, "\\t"))
2512 csv_sep = DEFAULT_SEPARATOR;
2514 if (argc && !strncmp(argv[0], "rec", 3)) {
2515 argc = __cmd_record(argc, argv);
2518 } else if (argc && !strncmp(argv[0], "rep", 3))
2519 return __cmd_report(argc, argv);
2521 interval = stat_config.interval;
2524 * For record command the -o is already taken care of.
2526 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2529 if (output_name && output_fd) {
2530 fprintf(stderr, "cannot use both --output and --log-fd\n");
2531 parse_options_usage(stat_usage, stat_options, "o", 1);
2532 parse_options_usage(NULL, stat_options, "log-fd", 0);
2536 if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2537 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2541 if (metric_only && run_count > 1) {
2542 fprintf(stderr, "--metric-only is not supported with -r\n");
2546 if (output_fd < 0) {
2547 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2548 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2554 mode = append_file ? "a" : "w";
2556 output = fopen(output_name, mode);
2558 perror("failed to create output file");
2561 clock_gettime(CLOCK_REALTIME, &tm);
2562 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2563 } else if (output_fd > 0) {
2564 mode = append_file ? "a" : "w";
2565 output = fdopen(output_fd, mode);
2567 perror("Failed opening logfd");
2572 stat_config.output = output;
2575 * let the spreadsheet do the pretty-printing
2578 /* User explicitly passed -B? */
2579 if (big_num_opt == 1) {
2580 fprintf(stderr, "-B option not supported with -x\n");
2581 parse_options_usage(stat_usage, stat_options, "B", 1);
2582 parse_options_usage(NULL, stat_options, "x", 1);
2584 } else /* Nope, so disable big number formatting */
2586 } else if (big_num_opt == 0) /* User passed --no-big-num */
2589 setup_system_wide(argc);
2591 if (run_count < 0) {
2592 pr_err("Run count must be a positive number\n");
2593 parse_options_usage(stat_usage, stat_options, "r", 1);
2595 } else if (run_count == 0) {
2600 if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
2601 fprintf(stderr, "The --per-thread option is only available "
2602 "when monitoring via -p -t options.\n");
2603 parse_options_usage(NULL, stat_options, "p", 1);
2604 parse_options_usage(NULL, stat_options, "t", 1);
2609 * no_aggr, cgroup are for system-wide only
2610 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2612 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2613 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2614 !target__has_cpu(&target)) {
2615 fprintf(stderr, "both cgroup and no-aggregation "
2616 "modes only available in system-wide mode\n");
2618 parse_options_usage(stat_usage, stat_options, "G", 1);
2619 parse_options_usage(NULL, stat_options, "A", 1);
2620 parse_options_usage(NULL, stat_options, "a", 1);
2624 if (add_default_attributes())
2627 target__validate(&target);
2629 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2630 if (target__has_task(&target)) {
2631 pr_err("Problems finding threads of monitor\n");
2632 parse_options_usage(stat_usage, stat_options, "p", 1);
2633 parse_options_usage(NULL, stat_options, "t", 1);
2634 } else if (target__has_cpu(&target)) {
2635 perror("failed to parse CPUs map");
2636 parse_options_usage(stat_usage, stat_options, "C", 1);
2637 parse_options_usage(NULL, stat_options, "a", 1);
2643 * Initialize thread_map with comm names,
2644 * so we could print it out on output.
2646 if (stat_config.aggr_mode == AGGR_THREAD)
2647 thread_map__read_comms(evsel_list->threads);
2649 if (interval && interval < 100) {
2650 if (interval < 10) {
2651 pr_err("print interval must be >= 10ms\n");
2652 parse_options_usage(stat_usage, stat_options, "I", 1);
2655 pr_warning("print interval < 100ms. "
2656 "The overhead percentage could be high in some cases. "
2657 "Please proceed with caution.\n");
2660 if (perf_evlist__alloc_stats(evsel_list, interval))
2663 if (perf_stat_init_aggr_mode())
2667 * We dont want to block the signals - that would cause
2668 * child tasks to inherit that and Ctrl-C would not work.
2669 * What we want is for Ctrl-C to work in the exec()-ed
2670 * task, but being ignored by perf stat itself:
2674 signal(SIGINT, skip_signal);
2675 signal(SIGCHLD, skip_signal);
2676 signal(SIGALRM, skip_signal);
2677 signal(SIGABRT, skip_signal);
2680 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2681 if (run_count != 1 && verbose > 0)
2682 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2685 status = run_perf_stat(argc, argv);
2686 if (forever && status != -1) {
2687 print_counters(NULL, argc, argv);
2688 perf_stat__reset_stats();
2692 if (!forever && status != -1 && !interval)
2693 print_counters(NULL, argc, argv);
2697 * We synthesize the kernel mmap record just so that older tools
2698 * don't emit warnings about not being able to resolve symbols
2699 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2700 * a saner message about no samples being in the perf.data file.
2702 * This also serves to suppress a warning about f_header.data.size == 0
2703 * in header.c at the moment 'perf stat record' gets introduced, which
2704 * is not really needed once we start adding the stat specific PERF_RECORD_
2705 * records, but the need to suppress the kptr_restrict messages in older
2706 * tools remain -acme
2708 int fd = perf_data_file__fd(&perf_stat.file);
2709 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2710 process_synthesized_event,
2711 &perf_stat.session->machines.host);
2713 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2714 "older tools may produce warnings about this file\n.");
2718 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2719 pr_err("failed to write stat round event\n");
2722 if (!perf_stat.file.is_pipe) {
2723 perf_stat.session->header.data_size += perf_stat.bytes_written;
2724 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2727 perf_session__delete(perf_stat.session);
2730 perf_stat__exit_aggr_mode();
2731 perf_evlist__free_stats(evsel_list);
2733 perf_evlist__delete(evsel_list);