1 // SPDX-License-Identifier: GPL-2.0-only
5 * Builtin stat command: Give a precise performance counters summary
6 * overview about any workload, CPU or specific PID.
10 $ perf stat ./hackbench 10
14 Performance counter stats for './hackbench 10':
16 1708.761321 task-clock # 11.037 CPUs utilized
17 41,190 context-switches # 0.024 M/sec
18 6,735 CPU-migrations # 0.004 M/sec
19 17,318 page-faults # 0.010 M/sec
20 5,205,202,243 cycles # 3.046 GHz
21 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle
22 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle
23 2,603,501,247 instructions # 0.50 insns per cycle
24 # 1.48 stalled cycles per insn
25 484,357,498 branches # 283.455 M/sec
26 6,388,934 branch-misses # 1.32% of all branches
28 0.154822978 seconds time elapsed
31 * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
33 * Improvements and fixes by:
35 * Arjan van de Ven <arjan@linux.intel.com>
36 * Yanmin Zhang <yanmin.zhang@intel.com>
37 * Wu Fengguang <fengguang.wu@intel.com>
38 * Mike Galbraith <efault@gmx.de>
39 * Paul Mackerras <paulus@samba.org>
40 * Jaswinder Singh Rajput <jaswinder@kernel.org>
45 #include "util/cgroup.h"
46 #include <subcmd/parse-options.h>
47 #include "util/parse-events.h"
49 #include "util/event.h"
50 #include "util/evlist.h"
51 #include "util/evsel.h"
52 #include "util/debug.h"
53 #include "util/color.h"
54 #include "util/stat.h"
55 #include "util/header.h"
56 #include "util/cpumap.h"
57 #include "util/thread_map.h"
58 #include "util/counts.h"
59 #include "util/topdown.h"
60 #include "util/session.h"
61 #include "util/tool.h"
62 #include "util/string2.h"
63 #include "util/metricgroup.h"
64 #include "util/synthetic-events.h"
65 #include "util/target.h"
66 #include "util/time-utils.h"
68 #include "util/affinity.h"
70 #include "util/bpf_counter.h"
73 #include <linux/time64.h>
74 #include <linux/zalloc.h>
75 #include <api/fs/fs.h>
79 #include <sys/prctl.h>
83 #include <sys/types.h>
88 #include <sys/resource.h>
89 #include <linux/err.h>
91 #include <linux/ctype.h>
92 #include <perf/evlist.h>
94 #define DEFAULT_SEPARATOR " "
95 #define FREEZE_ON_SMI_PATH "devices/cpu/freeze_on_smi"
97 static void print_counters(struct timespec *ts, int argc, const char **argv);
99 /* Default events used for perf stat -T */
100 static const char *transaction_attrs = {
112 /* More limited version when the CPU does not have all events. */
113 static const char * transaction_limited_attrs = {
123 static const char * topdown_attrs[] = {
124 "topdown-total-slots",
125 "topdown-slots-retired",
126 "topdown-recovery-bubbles",
127 "topdown-fetch-bubbles",
128 "topdown-slots-issued",
132 static const char *topdown_metric_attrs[] = {
141 static const char *topdown_metric_L2_attrs[] = {
148 "topdown-br-mispredict",
154 static const char *smi_cost_attrs = {
162 static struct evlist *evsel_list;
164 static struct target target = {
168 #define METRIC_ONLY_LEN 20
170 static volatile pid_t child_pid = -1;
171 static int detailed_run = 0;
172 static bool transaction_run;
173 static bool topdown_run = false;
174 static bool smi_cost = false;
175 static bool smi_reset = false;
176 static int big_num_opt = -1;
177 static bool group = false;
178 static const char *pre_cmd = NULL;
179 static const char *post_cmd = NULL;
180 static bool sync_run = false;
181 static bool forever = false;
182 static bool force_metric_only = false;
183 static struct timespec ref_time;
184 static bool append_file;
185 static bool interval_count;
186 static const char *output_name;
187 static int output_fd;
191 struct perf_data data;
192 struct perf_session *session;
194 struct perf_tool tool;
196 struct perf_cpu_map *cpus;
197 struct perf_thread_map *threads;
198 enum aggr_mode aggr_mode;
201 static struct perf_stat perf_stat;
202 #define STAT_RECORD perf_stat.record
204 static volatile int done = 0;
206 static struct perf_stat_config stat_config = {
207 .aggr_mode = AGGR_GLOBAL,
209 .unit_width = 4, /* strlen("unit") */
211 .metric_only_len = METRIC_ONLY_LEN,
212 .walltime_nsecs_stats = &walltime_nsecs_stats,
218 static bool cpus_map_matched(struct evsel *a, struct evsel *b)
220 if (!a->core.cpus && !b->core.cpus)
223 if (!a->core.cpus || !b->core.cpus)
226 if (a->core.cpus->nr != b->core.cpus->nr)
229 for (int i = 0; i < a->core.cpus->nr; i++) {
230 if (a->core.cpus->map[i] != b->core.cpus->map[i])
237 static void evlist__check_cpu_maps(struct evlist *evlist)
239 struct evsel *evsel, *pos, *leader;
242 evlist__for_each_entry(evlist, evsel) {
243 leader = evsel->leader;
245 /* Check that leader matches cpus with each member. */
248 if (cpus_map_matched(leader, evsel))
251 /* If there's mismatch disable the group and warn user. */
252 WARN_ONCE(1, "WARNING: grouped events cpus do not match, disabling group:\n");
253 evsel__group_desc(leader, buf, sizeof(buf));
254 pr_warning(" %s\n", buf);
257 cpu_map__snprint(leader->core.cpus, buf, sizeof(buf));
258 pr_warning(" %s: %s\n", leader->name, buf);
259 cpu_map__snprint(evsel->core.cpus, buf, sizeof(buf));
260 pr_warning(" %s: %s\n", evsel->name, buf);
263 for_each_group_evsel(pos, leader) {
265 pos->core.nr_members = 0;
267 evsel->leader->core.nr_members = 0;
271 static inline void diff_timespec(struct timespec *r, struct timespec *a,
274 r->tv_sec = a->tv_sec - b->tv_sec;
275 if (a->tv_nsec < b->tv_nsec) {
276 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
279 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
283 static void perf_stat__reset_stats(void)
287 evlist__reset_stats(evsel_list);
288 perf_stat__reset_shadow_stats();
290 for (i = 0; i < stat_config.stats_num; i++)
291 perf_stat__reset_shadow_per_stat(&stat_config.stats[i]);
294 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
295 union perf_event *event,
296 struct perf_sample *sample __maybe_unused,
297 struct machine *machine __maybe_unused)
299 if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
300 pr_err("failed to write perf data, error: %m\n");
304 perf_stat.bytes_written += event->header.size;
308 static int write_stat_round_event(u64 tm, u64 type)
310 return perf_event__synthesize_stat_round(NULL, tm, type,
311 process_synthesized_event,
315 #define WRITE_STAT_ROUND_EVENT(time, interval) \
316 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
318 #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
320 static int evsel__write_stat_event(struct evsel *counter, u32 cpu, u32 thread,
321 struct perf_counts_values *count)
323 struct perf_sample_id *sid = SID(counter, cpu, thread);
325 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
326 process_synthesized_event, NULL);
329 static int read_single_counter(struct evsel *counter, int cpu,
330 int thread, struct timespec *rs)
332 if (counter->tool_event == PERF_TOOL_DURATION_TIME) {
333 u64 val = rs->tv_nsec + rs->tv_sec*1000000000ULL;
334 struct perf_counts_values *count =
335 perf_counts(counter->counts, cpu, thread);
336 count->ena = count->run = val;
340 return evsel__read_counter(counter, cpu, thread);
344 * Read out the results of a single counter:
345 * do not aggregate counts across CPUs in system-wide mode
347 static int read_counter_cpu(struct evsel *counter, struct timespec *rs, int cpu)
349 int nthreads = perf_thread_map__nr(evsel_list->core.threads);
352 if (!counter->supported)
355 if (counter->core.system_wide)
358 for (thread = 0; thread < nthreads; thread++) {
359 struct perf_counts_values *count;
361 count = perf_counts(counter->counts, cpu, thread);
364 * The leader's group read loads data into its group members
365 * (via evsel__read_counter()) and sets their count->loaded.
367 if (!perf_counts__is_loaded(counter->counts, cpu, thread) &&
368 read_single_counter(counter, cpu, thread, rs)) {
369 counter->counts->scaled = -1;
370 perf_counts(counter->counts, cpu, thread)->ena = 0;
371 perf_counts(counter->counts, cpu, thread)->run = 0;
375 perf_counts__set_loaded(counter->counts, cpu, thread, false);
378 if (evsel__write_stat_event(counter, cpu, thread, count)) {
379 pr_err("failed to write stat event\n");
385 fprintf(stat_config.output,
386 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
387 evsel__name(counter),
389 count->val, count->ena, count->run);
396 static int read_affinity_counters(struct timespec *rs)
398 struct evsel *counter;
399 struct affinity affinity;
402 if (affinity__setup(&affinity) < 0)
405 ncpus = perf_cpu_map__nr(evsel_list->core.all_cpus);
406 if (!target__has_cpu(&target) || target__has_per_thread(&target))
408 evlist__for_each_cpu(evsel_list, i, cpu) {
411 affinity__set(&affinity, cpu);
413 evlist__for_each_entry(evsel_list, counter) {
414 if (evsel__cpu_iter_skip(counter, cpu))
417 counter->err = read_counter_cpu(counter, rs,
418 counter->cpu_iter - 1);
422 affinity__cleanup(&affinity);
426 static int read_bpf_map_counters(void)
428 struct evsel *counter;
431 evlist__for_each_entry(evsel_list, counter) {
432 err = bpf_counter__read(counter);
439 static void read_counters(struct timespec *rs)
441 struct evsel *counter;
444 if (!stat_config.stop_read_counter) {
445 if (target__has_bpf(&target))
446 err = read_bpf_map_counters();
448 err = read_affinity_counters(rs);
453 evlist__for_each_entry(evsel_list, counter) {
455 pr_debug("failed to read counter %s\n", counter->name);
456 if (counter->err == 0 && perf_stat_process_counter(&stat_config, counter))
457 pr_warning("failed to process counter %s\n", counter->name);
462 static int runtime_stat_new(struct perf_stat_config *config, int nthreads)
466 config->stats = calloc(nthreads, sizeof(struct runtime_stat));
470 config->stats_num = nthreads;
472 for (i = 0; i < nthreads; i++)
473 runtime_stat__init(&config->stats[i]);
478 static void runtime_stat_delete(struct perf_stat_config *config)
485 for (i = 0; i < config->stats_num; i++)
486 runtime_stat__exit(&config->stats[i]);
488 zfree(&config->stats);
491 static void runtime_stat_reset(struct perf_stat_config *config)
498 for (i = 0; i < config->stats_num; i++)
499 perf_stat__reset_shadow_per_stat(&config->stats[i]);
502 static void process_interval(void)
504 struct timespec ts, rs;
506 clock_gettime(CLOCK_MONOTONIC, &ts);
507 diff_timespec(&rs, &ts, &ref_time);
509 perf_stat__reset_shadow_per_stat(&rt_stat);
510 runtime_stat_reset(&stat_config);
514 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
515 pr_err("failed to write stat round event\n");
518 init_stats(&walltime_nsecs_stats);
519 update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000ULL);
520 print_counters(&rs, 0, NULL);
523 static bool handle_interval(unsigned int interval, int *times)
527 if (interval_count && !(--(*times)))
533 static int enable_counters(void)
538 if (target__has_bpf(&target)) {
539 evlist__for_each_entry(evsel_list, evsel) {
540 err = bpf_counter__enable(evsel);
546 if (stat_config.initial_delay < 0) {
547 pr_info(EVLIST_DISABLED_MSG);
551 if (stat_config.initial_delay > 0) {
552 pr_info(EVLIST_DISABLED_MSG);
553 usleep(stat_config.initial_delay * USEC_PER_MSEC);
557 * We need to enable counters only if:
558 * - we don't have tracee (attaching to task or cpu)
559 * - we have initial delay configured
561 if (!target__none(&target) || stat_config.initial_delay) {
562 evlist__enable(evsel_list);
563 if (stat_config.initial_delay > 0)
564 pr_info(EVLIST_ENABLED_MSG);
569 static void disable_counters(void)
572 * If we don't have tracee (attaching to task or cpu), counters may
573 * still be running. To get accurate group ratios, we must stop groups
574 * from counting before reading their constituent counters.
576 if (!target__none(&target))
577 evlist__disable(evsel_list);
580 static volatile int workload_exec_errno;
583 * evlist__prepare_workload will send a SIGUSR1
584 * if the fork fails, since we asked by setting its
585 * want_signal to true.
587 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
588 void *ucontext __maybe_unused)
590 workload_exec_errno = info->si_value.sival_int;
593 static bool evsel__should_store_id(struct evsel *counter)
595 return STAT_RECORD || counter->core.attr.read_format & PERF_FORMAT_ID;
598 static bool is_target_alive(struct target *_target,
599 struct perf_thread_map *threads)
604 if (!target__has_task(_target))
607 for (i = 0; i < threads->nr; i++) {
610 scnprintf(path, PATH_MAX, "%s/%d", procfs__mountpoint(),
611 threads->map[i].pid);
613 if (!stat(path, &st))
620 static void process_evlist(struct evlist *evlist, unsigned int interval)
622 enum evlist_ctl_cmd cmd = EVLIST_CTL_CMD_UNSUPPORTED;
624 if (evlist__ctlfd_process(evlist, &cmd) > 0) {
626 case EVLIST_CTL_CMD_ENABLE:
630 case EVLIST_CTL_CMD_DISABLE:
634 case EVLIST_CTL_CMD_SNAPSHOT:
635 case EVLIST_CTL_CMD_ACK:
636 case EVLIST_CTL_CMD_UNSUPPORTED:
637 case EVLIST_CTL_CMD_EVLIST:
638 case EVLIST_CTL_CMD_STOP:
639 case EVLIST_CTL_CMD_PING:
646 static void compute_tts(struct timespec *time_start, struct timespec *time_stop,
649 int tts = *time_to_sleep;
650 struct timespec time_diff;
652 diff_timespec(&time_diff, time_stop, time_start);
654 tts -= time_diff.tv_sec * MSEC_PER_SEC +
655 time_diff.tv_nsec / NSEC_PER_MSEC;
660 *time_to_sleep = tts;
663 static int dispatch_events(bool forks, int timeout, int interval, int *times)
665 int child_exited = 0, status = 0;
666 int time_to_sleep, sleep_time;
667 struct timespec time_start, time_stop;
670 sleep_time = interval;
672 sleep_time = timeout;
676 time_to_sleep = sleep_time;
680 child_exited = waitpid(child_pid, &status, WNOHANG);
682 child_exited = !is_target_alive(&target, evsel_list->core.threads) ? 1 : 0;
687 clock_gettime(CLOCK_MONOTONIC, &time_start);
688 if (!(evlist__poll(evsel_list, time_to_sleep) > 0)) { /* poll timeout or EINTR */
689 if (timeout || handle_interval(interval, times))
691 time_to_sleep = sleep_time;
692 } else { /* fd revent */
693 process_evlist(evsel_list, interval);
694 clock_gettime(CLOCK_MONOTONIC, &time_stop);
695 compute_tts(&time_start, &time_stop, &time_to_sleep);
702 enum counter_recovery {
708 static enum counter_recovery stat_handle_error(struct evsel *counter)
712 * PPC returns ENXIO for HW counters until 2.6.37
713 * (behavior changed with commit b0a873e).
715 if (errno == EINVAL || errno == ENOSYS ||
716 errno == ENOENT || errno == EOPNOTSUPP ||
719 ui__warning("%s event is not supported by the kernel.\n",
720 evsel__name(counter));
721 counter->supported = false;
723 * errored is a sticky flag that means one of the counter's
724 * cpu event had a problem and needs to be reexamined.
726 counter->errored = true;
728 if ((counter->leader != counter) ||
729 !(counter->leader->core.nr_members > 1))
731 } else if (evsel__fallback(counter, errno, msg, sizeof(msg))) {
733 ui__warning("%s\n", msg);
734 return COUNTER_RETRY;
735 } else if (target__has_per_thread(&target) &&
736 evsel_list->core.threads &&
737 evsel_list->core.threads->err_thread != -1) {
739 * For global --per-thread case, skip current
742 if (!thread_map__remove(evsel_list->core.threads,
743 evsel_list->core.threads->err_thread)) {
744 evsel_list->core.threads->err_thread = -1;
745 return COUNTER_RETRY;
749 evsel__open_strerror(counter, &target, errno, msg, sizeof(msg));
750 ui__error("%s\n", msg);
753 kill(child_pid, SIGTERM);
754 return COUNTER_FATAL;
757 static int __run_perf_stat(int argc, const char **argv, int run_idx)
759 int interval = stat_config.interval;
760 int times = stat_config.times;
761 int timeout = stat_config.timeout;
763 unsigned long long t0, t1;
764 struct evsel *counter;
767 const bool forks = (argc > 0);
768 bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
769 struct affinity affinity;
771 bool second_pass = false;
774 if (evlist__prepare_workload(evsel_list, &target, argv, is_pipe, workload_exec_failed_signal) < 0) {
775 perror("failed to prepare workload");
778 child_pid = evsel_list->workload.pid;
782 evlist__set_leader(evsel_list);
784 if (affinity__setup(&affinity) < 0)
787 if (target__has_bpf(&target)) {
788 evlist__for_each_entry(evsel_list, counter) {
789 if (bpf_counter__load(counter, &target))
794 evlist__for_each_cpu (evsel_list, i, cpu) {
796 * bperf calls evsel__open_per_cpu() in bperf__load(), so
797 * no need to call it again here.
801 affinity__set(&affinity, cpu);
803 evlist__for_each_entry(evsel_list, counter) {
804 if (evsel__cpu_iter_skip(counter, cpu))
806 if (counter->reset_group || counter->errored)
809 if (create_perf_stat_counter(counter, &stat_config, &target,
810 counter->cpu_iter - 1) < 0) {
813 * Weak group failed. We cannot just undo this here
814 * because earlier CPUs might be in group mode, and the kernel
815 * doesn't support mixing group and non group reads. Defer
817 * Don't close here because we're in the wrong affinity.
819 if ((errno == EINVAL || errno == EBADF) &&
820 counter->leader != counter &&
821 counter->weak_group) {
822 evlist__reset_weak_group(evsel_list, counter, false);
823 assert(counter->reset_group);
828 switch (stat_handle_error(counter)) {
840 counter->supported = true;
846 * Now redo all the weak group after closing them,
847 * and also close errored counters.
850 evlist__for_each_cpu(evsel_list, i, cpu) {
851 affinity__set(&affinity, cpu);
852 /* First close errored or weak retry */
853 evlist__for_each_entry(evsel_list, counter) {
854 if (!counter->reset_group && !counter->errored)
856 if (evsel__cpu_iter_skip_no_inc(counter, cpu))
858 perf_evsel__close_cpu(&counter->core, counter->cpu_iter);
860 /* Now reopen weak */
861 evlist__for_each_entry(evsel_list, counter) {
862 if (!counter->reset_group && !counter->errored)
864 if (evsel__cpu_iter_skip(counter, cpu))
866 if (!counter->reset_group)
869 pr_debug2("reopening weak %s\n", evsel__name(counter));
870 if (create_perf_stat_counter(counter, &stat_config, &target,
871 counter->cpu_iter - 1) < 0) {
873 switch (stat_handle_error(counter)) {
877 goto try_again_reset;
884 counter->supported = true;
888 affinity__cleanup(&affinity);
890 evlist__for_each_entry(evsel_list, counter) {
891 if (!counter->supported) {
892 perf_evsel__free_fd(&counter->core);
896 l = strlen(counter->unit);
897 if (l > stat_config.unit_width)
898 stat_config.unit_width = l;
900 if (evsel__should_store_id(counter) &&
901 evsel__store_ids(counter, evsel_list))
905 if (evlist__apply_filters(evsel_list, &counter)) {
906 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
907 counter->filter, evsel__name(counter), errno,
908 str_error_r(errno, msg, sizeof(msg)));
913 int fd = perf_data__fd(&perf_stat.data);
916 err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
918 err = perf_session__write_header(perf_stat.session, evsel_list,
925 err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
926 process_synthesized_event, is_pipe);
932 * Enable counters and exec the command:
935 clock_gettime(CLOCK_MONOTONIC, &ref_time);
938 evlist__start_workload(evsel_list);
939 err = enable_counters();
943 if (interval || timeout || evlist__ctlfd_initialized(evsel_list))
944 status = dispatch_events(forks, timeout, interval, ×);
945 if (child_pid != -1) {
947 kill(child_pid, SIGTERM);
948 wait4(child_pid, &status, 0, &stat_config.ru_data);
951 if (workload_exec_errno) {
952 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
953 pr_err("Workload failed: %s\n", emsg);
957 if (WIFSIGNALED(status))
958 psignal(WTERMSIG(status), argv[0]);
960 err = enable_counters();
963 status = dispatch_events(forks, timeout, interval, ×);
970 if (stat_config.walltime_run_table)
971 stat_config.walltime_run[run_idx] = t1 - t0;
973 if (interval && stat_config.summary) {
974 stat_config.interval = 0;
975 stat_config.stop_read_counter = true;
976 init_stats(&walltime_nsecs_stats);
977 update_stats(&walltime_nsecs_stats, t1 - t0);
979 if (stat_config.aggr_mode == AGGR_GLOBAL)
980 evlist__save_aggr_prev_raw_counts(evsel_list);
982 evlist__copy_prev_raw_counts(evsel_list);
983 evlist__reset_prev_raw_counts(evsel_list);
984 runtime_stat_reset(&stat_config);
985 perf_stat__reset_shadow_per_stat(&rt_stat);
987 update_stats(&walltime_nsecs_stats, t1 - t0);
990 * Closing a group leader splits the group, and as we only disable
991 * group leaders, results in remaining events becoming enabled. To
992 * avoid arbitrary skew, we must read all counters before closing any
995 read_counters(&(struct timespec) { .tv_nsec = t1-t0 });
998 * We need to keep evsel_list alive, because it's processed
999 * later the evsel_list will be closed after.
1002 evlist__close(evsel_list);
1004 return WEXITSTATUS(status);
1007 static int run_perf_stat(int argc, const char **argv, int run_idx)
1012 ret = system(pre_cmd);
1020 ret = __run_perf_stat(argc, argv, run_idx);
1025 ret = system(post_cmd);
1033 static void print_counters(struct timespec *ts, int argc, const char **argv)
1035 /* Do not print anything if we record to the pipe. */
1036 if (STAT_RECORD && perf_stat.data.is_pipe)
1038 if (stat_config.quiet)
1041 evlist__print_counters(evsel_list, &stat_config, &target, ts, argc, argv);
1044 static volatile int signr = -1;
1046 static void skip_signal(int signo)
1048 if ((child_pid == -1) || stat_config.interval)
1053 * render child_pid harmless
1054 * won't send SIGTERM to a random
1055 * process in case of race condition
1056 * and fast PID recycling
1061 static void sig_atexit(void)
1066 * avoid race condition with SIGCHLD handler
1067 * in skip_signal() which is modifying child_pid
1068 * goal is to avoid send SIGTERM to a random
1072 sigaddset(&set, SIGCHLD);
1073 sigprocmask(SIG_BLOCK, &set, &oset);
1075 if (child_pid != -1)
1076 kill(child_pid, SIGTERM);
1078 sigprocmask(SIG_SETMASK, &oset, NULL);
1083 signal(signr, SIG_DFL);
1084 kill(getpid(), signr);
1087 void perf_stat__set_big_num(int set)
1089 stat_config.big_num = (set != 0);
1092 static int stat__set_big_num(const struct option *opt __maybe_unused,
1093 const char *s __maybe_unused, int unset)
1095 big_num_opt = unset ? 0 : 1;
1096 perf_stat__set_big_num(!unset);
1100 static int enable_metric_only(const struct option *opt __maybe_unused,
1101 const char *s __maybe_unused, int unset)
1103 force_metric_only = true;
1104 stat_config.metric_only = !unset;
1108 static int parse_metric_groups(const struct option *opt,
1110 int unset __maybe_unused)
1112 return metricgroup__parse_groups(opt, str,
1113 stat_config.metric_no_group,
1114 stat_config.metric_no_merge,
1115 &stat_config.metric_events);
1118 static int parse_control_option(const struct option *opt,
1120 int unset __maybe_unused)
1122 struct perf_stat_config *config = opt->value;
1124 return evlist__parse_control(str, &config->ctl_fd, &config->ctl_fd_ack, &config->ctl_fd_close);
1127 static int parse_stat_cgroups(const struct option *opt,
1128 const char *str, int unset)
1130 if (stat_config.cgroup_list) {
1131 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
1135 return parse_cgroups(opt, str, unset);
1138 static struct option stat_options[] = {
1139 OPT_BOOLEAN('T', "transaction", &transaction_run,
1140 "hardware transaction statistics"),
1141 OPT_CALLBACK('e', "event", &evsel_list, "event",
1142 "event selector. use 'perf list' to list available events",
1143 parse_events_option),
1144 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1145 "event filter", parse_filter),
1146 OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
1147 "child tasks do not inherit counters"),
1148 OPT_STRING('p', "pid", &target.pid, "pid",
1149 "stat events on existing process id"),
1150 OPT_STRING('t', "tid", &target.tid, "tid",
1151 "stat events on existing thread id"),
1152 #ifdef HAVE_BPF_SKEL
1153 OPT_STRING('b', "bpf-prog", &target.bpf_str, "bpf-prog-id",
1154 "stat events on existing bpf program id"),
1155 OPT_BOOLEAN(0, "bpf-counters", &target.use_bpf,
1156 "use bpf program to count events"),
1157 OPT_STRING(0, "bpf-attr-map", &target.attr_map, "attr-map-path",
1158 "path to perf_event_attr map"),
1160 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1161 "system-wide collection from all CPUs"),
1162 OPT_BOOLEAN('g', "group", &group,
1163 "put the counters into a counter group"),
1164 OPT_BOOLEAN(0, "scale", &stat_config.scale,
1165 "Use --no-scale to disable counter scaling for multiplexing"),
1166 OPT_INCR('v', "verbose", &verbose,
1167 "be more verbose (show counter open errors, etc)"),
1168 OPT_INTEGER('r', "repeat", &stat_config.run_count,
1169 "repeat command and print average + stddev (max: 100, forever: 0)"),
1170 OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
1171 "display details about each run (only with -r option)"),
1172 OPT_BOOLEAN('n', "null", &stat_config.null_run,
1173 "null run - dont start any counters"),
1174 OPT_INCR('d', "detailed", &detailed_run,
1175 "detailed run - start a lot of events"),
1176 OPT_BOOLEAN('S', "sync", &sync_run,
1177 "call sync() before starting a run"),
1178 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1179 "print large numbers with thousands\' separators",
1181 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1182 "list of cpus to monitor in system-wide"),
1183 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1184 "disable CPU count aggregation", AGGR_NONE),
1185 OPT_BOOLEAN(0, "no-merge", &stat_config.no_merge, "Do not merge identical named events"),
1186 OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
1187 "print counts with custom separator"),
1188 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1189 "monitor event in cgroup name only", parse_stat_cgroups),
1190 OPT_STRING(0, "for-each-cgroup", &stat_config.cgroup_list, "name",
1191 "expand events for each cgroup"),
1192 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1193 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1194 OPT_INTEGER(0, "log-fd", &output_fd,
1195 "log output to fd, instead of stderr"),
1196 OPT_STRING(0, "pre", &pre_cmd, "command",
1197 "command to run prior to the measured command"),
1198 OPT_STRING(0, "post", &post_cmd, "command",
1199 "command to run after to the measured command"),
1200 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1201 "print counts at regular interval in ms "
1202 "(overhead is possible for values <= 100ms)"),
1203 OPT_INTEGER(0, "interval-count", &stat_config.times,
1204 "print counts for fixed number of times"),
1205 OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
1206 "clear screen in between new interval"),
1207 OPT_UINTEGER(0, "timeout", &stat_config.timeout,
1208 "stop workload and print counts after a timeout period in ms (>= 10ms)"),
1209 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1210 "aggregate counts per processor socket", AGGR_SOCKET),
1211 OPT_SET_UINT(0, "per-die", &stat_config.aggr_mode,
1212 "aggregate counts per processor die", AGGR_DIE),
1213 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1214 "aggregate counts per physical processor core", AGGR_CORE),
1215 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1216 "aggregate counts per thread", AGGR_THREAD),
1217 OPT_SET_UINT(0, "per-node", &stat_config.aggr_mode,
1218 "aggregate counts per numa node", AGGR_NODE),
1219 OPT_INTEGER('D', "delay", &stat_config.initial_delay,
1220 "ms to wait before starting measurement after program start (-1: start with events disabled)"),
1221 OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
1222 "Only print computed metrics. No raw values", enable_metric_only),
1223 OPT_BOOLEAN(0, "metric-no-group", &stat_config.metric_no_group,
1224 "don't group metric events, impacts multiplexing"),
1225 OPT_BOOLEAN(0, "metric-no-merge", &stat_config.metric_no_merge,
1226 "don't try to share events between metrics in a group"),
1227 OPT_BOOLEAN(0, "topdown", &topdown_run,
1228 "measure top-down statistics"),
1229 OPT_UINTEGER(0, "td-level", &stat_config.topdown_level,
1230 "Set the metrics level for the top-down statistics (0: max level)"),
1231 OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1232 "measure SMI cost"),
1233 OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1234 "monitor specified metrics or metric groups (separated by ,)",
1235 parse_metric_groups),
1236 OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
1237 "Configure all used events to run in kernel space.",
1238 PARSE_OPT_EXCLUSIVE),
1239 OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
1240 "Configure all used events to run in user space.",
1241 PARSE_OPT_EXCLUSIVE),
1242 OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
1243 "Use with 'percore' event qualifier to show the event "
1244 "counts of one hardware thread by sum up total hardware "
1245 "threads of same physical core"),
1246 OPT_BOOLEAN(0, "summary", &stat_config.summary,
1247 "print summary for interval mode"),
1248 OPT_BOOLEAN(0, "quiet", &stat_config.quiet,
1249 "don't print output (useful with record)"),
1251 OPT_CALLBACK(0, "pfm-events", &evsel_list, "event",
1252 "libpfm4 event selector. use 'perf list' to list available events",
1253 parse_libpfm_events_option),
1255 OPT_CALLBACK(0, "control", &stat_config, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]",
1256 "Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events).\n"
1257 "\t\t\t Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n"
1258 "\t\t\t Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.",
1259 parse_control_option),
1263 static struct aggr_cpu_id perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
1264 struct perf_cpu_map *map, int cpu)
1266 return cpu_map__get_socket(map, cpu, NULL);
1269 static struct aggr_cpu_id perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
1270 struct perf_cpu_map *map, int cpu)
1272 return cpu_map__get_die(map, cpu, NULL);
1275 static struct aggr_cpu_id perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
1276 struct perf_cpu_map *map, int cpu)
1278 return cpu_map__get_core(map, cpu, NULL);
1281 static struct aggr_cpu_id perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
1282 struct perf_cpu_map *map, int cpu)
1284 return cpu_map__get_node(map, cpu, NULL);
1287 static struct aggr_cpu_id perf_stat__get_aggr(struct perf_stat_config *config,
1288 aggr_get_id_t get_id, struct perf_cpu_map *map, int idx)
1291 struct aggr_cpu_id id = cpu_map__empty_aggr_cpu_id();
1296 cpu = map->map[idx];
1298 if (cpu_map__aggr_cpu_id_is_empty(config->cpus_aggr_map->map[cpu]))
1299 config->cpus_aggr_map->map[cpu] = get_id(config, map, idx);
1301 id = config->cpus_aggr_map->map[cpu];
1305 static struct aggr_cpu_id perf_stat__get_socket_cached(struct perf_stat_config *config,
1306 struct perf_cpu_map *map, int idx)
1308 return perf_stat__get_aggr(config, perf_stat__get_socket, map, idx);
1311 static struct aggr_cpu_id perf_stat__get_die_cached(struct perf_stat_config *config,
1312 struct perf_cpu_map *map, int idx)
1314 return perf_stat__get_aggr(config, perf_stat__get_die, map, idx);
1317 static struct aggr_cpu_id perf_stat__get_core_cached(struct perf_stat_config *config,
1318 struct perf_cpu_map *map, int idx)
1320 return perf_stat__get_aggr(config, perf_stat__get_core, map, idx);
1323 static struct aggr_cpu_id perf_stat__get_node_cached(struct perf_stat_config *config,
1324 struct perf_cpu_map *map, int idx)
1326 return perf_stat__get_aggr(config, perf_stat__get_node, map, idx);
1329 static bool term_percore_set(void)
1331 struct evsel *counter;
1333 evlist__for_each_entry(evsel_list, counter) {
1334 if (counter->percore)
1341 static int perf_stat_init_aggr_mode(void)
1345 switch (stat_config.aggr_mode) {
1347 if (cpu_map__build_socket_map(evsel_list->core.cpus, &stat_config.aggr_map)) {
1348 perror("cannot build socket map");
1351 stat_config.aggr_get_id = perf_stat__get_socket_cached;
1354 if (cpu_map__build_die_map(evsel_list->core.cpus, &stat_config.aggr_map)) {
1355 perror("cannot build die map");
1358 stat_config.aggr_get_id = perf_stat__get_die_cached;
1361 if (cpu_map__build_core_map(evsel_list->core.cpus, &stat_config.aggr_map)) {
1362 perror("cannot build core map");
1365 stat_config.aggr_get_id = perf_stat__get_core_cached;
1368 if (cpu_map__build_node_map(evsel_list->core.cpus, &stat_config.aggr_map)) {
1369 perror("cannot build core map");
1372 stat_config.aggr_get_id = perf_stat__get_node_cached;
1375 if (term_percore_set()) {
1376 if (cpu_map__build_core_map(evsel_list->core.cpus,
1377 &stat_config.aggr_map)) {
1378 perror("cannot build core map");
1381 stat_config.aggr_get_id = perf_stat__get_core_cached;
1392 * The evsel_list->cpus is the base we operate on,
1393 * taking the highest cpu number to be the size of
1394 * the aggregation translate cpumap.
1396 nr = perf_cpu_map__max(evsel_list->core.cpus);
1397 stat_config.cpus_aggr_map = cpu_aggr_map__empty_new(nr + 1);
1398 return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
1401 static void cpu_aggr_map__delete(struct cpu_aggr_map *map)
1404 WARN_ONCE(refcount_read(&map->refcnt) != 0,
1405 "cpu_aggr_map refcnt unbalanced\n");
1410 static void cpu_aggr_map__put(struct cpu_aggr_map *map)
1412 if (map && refcount_dec_and_test(&map->refcnt))
1413 cpu_aggr_map__delete(map);
1416 static void perf_stat__exit_aggr_mode(void)
1418 cpu_aggr_map__put(stat_config.aggr_map);
1419 cpu_aggr_map__put(stat_config.cpus_aggr_map);
1420 stat_config.aggr_map = NULL;
1421 stat_config.cpus_aggr_map = NULL;
1424 static inline int perf_env__get_cpu(struct perf_env *env, struct perf_cpu_map *map, int idx)
1431 cpu = map->map[idx];
1433 if (cpu >= env->nr_cpus_avail)
1439 static struct aggr_cpu_id perf_env__get_socket(struct perf_cpu_map *map, int idx, void *data)
1441 struct perf_env *env = data;
1442 int cpu = perf_env__get_cpu(env, map, idx);
1443 struct aggr_cpu_id id = cpu_map__empty_aggr_cpu_id();
1446 id.socket = env->cpu[cpu].socket_id;
1451 static struct aggr_cpu_id perf_env__get_die(struct perf_cpu_map *map, int idx, void *data)
1453 struct perf_env *env = data;
1454 struct aggr_cpu_id id = cpu_map__empty_aggr_cpu_id();
1455 int cpu = perf_env__get_cpu(env, map, idx);
1459 * die_id is relative to socket, so start
1460 * with the socket ID and then add die to
1463 id.socket = env->cpu[cpu].socket_id;
1464 id.die = env->cpu[cpu].die_id;
1470 static struct aggr_cpu_id perf_env__get_core(struct perf_cpu_map *map, int idx, void *data)
1472 struct perf_env *env = data;
1473 struct aggr_cpu_id id = cpu_map__empty_aggr_cpu_id();
1474 int cpu = perf_env__get_cpu(env, map, idx);
1478 * core_id is relative to socket and die,
1479 * we need a global id. So we set
1480 * socket, die id and core id
1482 id.socket = env->cpu[cpu].socket_id;
1483 id.die = env->cpu[cpu].die_id;
1484 id.core = env->cpu[cpu].core_id;
1490 static struct aggr_cpu_id perf_env__get_node(struct perf_cpu_map *map, int idx, void *data)
1492 int cpu = perf_env__get_cpu(data, map, idx);
1493 struct aggr_cpu_id id = cpu_map__empty_aggr_cpu_id();
1495 id.node = perf_env__numa_node(data, cpu);
1499 static int perf_env__build_socket_map(struct perf_env *env, struct perf_cpu_map *cpus,
1500 struct cpu_aggr_map **sockp)
1502 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1505 static int perf_env__build_die_map(struct perf_env *env, struct perf_cpu_map *cpus,
1506 struct cpu_aggr_map **diep)
1508 return cpu_map__build_map(cpus, diep, perf_env__get_die, env);
1511 static int perf_env__build_core_map(struct perf_env *env, struct perf_cpu_map *cpus,
1512 struct cpu_aggr_map **corep)
1514 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1517 static int perf_env__build_node_map(struct perf_env *env, struct perf_cpu_map *cpus,
1518 struct cpu_aggr_map **nodep)
1520 return cpu_map__build_map(cpus, nodep, perf_env__get_node, env);
1523 static struct aggr_cpu_id perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
1524 struct perf_cpu_map *map, int idx)
1526 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1528 static struct aggr_cpu_id perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
1529 struct perf_cpu_map *map, int idx)
1531 return perf_env__get_die(map, idx, &perf_stat.session->header.env);
1534 static struct aggr_cpu_id perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
1535 struct perf_cpu_map *map, int idx)
1537 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1540 static struct aggr_cpu_id perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
1541 struct perf_cpu_map *map, int idx)
1543 return perf_env__get_node(map, idx, &perf_stat.session->header.env);
1546 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1548 struct perf_env *env = &st->session->header.env;
1550 switch (stat_config.aggr_mode) {
1552 if (perf_env__build_socket_map(env, evsel_list->core.cpus, &stat_config.aggr_map)) {
1553 perror("cannot build socket map");
1556 stat_config.aggr_get_id = perf_stat__get_socket_file;
1559 if (perf_env__build_die_map(env, evsel_list->core.cpus, &stat_config.aggr_map)) {
1560 perror("cannot build die map");
1563 stat_config.aggr_get_id = perf_stat__get_die_file;
1566 if (perf_env__build_core_map(env, evsel_list->core.cpus, &stat_config.aggr_map)) {
1567 perror("cannot build core map");
1570 stat_config.aggr_get_id = perf_stat__get_core_file;
1573 if (perf_env__build_node_map(env, evsel_list->core.cpus, &stat_config.aggr_map)) {
1574 perror("cannot build core map");
1577 stat_config.aggr_get_id = perf_stat__get_node_file;
1591 * Add default attributes, if there were no attributes specified or
1592 * if -d/--detailed, -d -d or -d -d -d is used:
1594 static int add_default_attributes(void)
1597 struct perf_event_attr default_attrs0[] = {
1599 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
1600 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
1601 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
1602 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
1604 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
1606 struct perf_event_attr frontend_attrs[] = {
1607 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1609 struct perf_event_attr backend_attrs[] = {
1610 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
1612 struct perf_event_attr default_attrs1[] = {
1613 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
1614 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
1615 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
1620 * Detailed stats (-d), covering the L1 and last level data caches:
1622 struct perf_event_attr detailed_attrs[] = {
1624 { .type = PERF_TYPE_HW_CACHE,
1626 PERF_COUNT_HW_CACHE_L1D << 0 |
1627 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1628 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1630 { .type = PERF_TYPE_HW_CACHE,
1632 PERF_COUNT_HW_CACHE_L1D << 0 |
1633 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1634 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1636 { .type = PERF_TYPE_HW_CACHE,
1638 PERF_COUNT_HW_CACHE_LL << 0 |
1639 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1640 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1642 { .type = PERF_TYPE_HW_CACHE,
1644 PERF_COUNT_HW_CACHE_LL << 0 |
1645 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1646 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1650 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1652 struct perf_event_attr very_detailed_attrs[] = {
1654 { .type = PERF_TYPE_HW_CACHE,
1656 PERF_COUNT_HW_CACHE_L1I << 0 |
1657 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1658 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1660 { .type = PERF_TYPE_HW_CACHE,
1662 PERF_COUNT_HW_CACHE_L1I << 0 |
1663 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1664 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1666 { .type = PERF_TYPE_HW_CACHE,
1668 PERF_COUNT_HW_CACHE_DTLB << 0 |
1669 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1670 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1672 { .type = PERF_TYPE_HW_CACHE,
1674 PERF_COUNT_HW_CACHE_DTLB << 0 |
1675 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1676 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1678 { .type = PERF_TYPE_HW_CACHE,
1680 PERF_COUNT_HW_CACHE_ITLB << 0 |
1681 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1682 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1684 { .type = PERF_TYPE_HW_CACHE,
1686 PERF_COUNT_HW_CACHE_ITLB << 0 |
1687 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1688 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1693 * Very, very detailed stats (-d -d -d), adding prefetch events:
1695 struct perf_event_attr very_very_detailed_attrs[] = {
1697 { .type = PERF_TYPE_HW_CACHE,
1699 PERF_COUNT_HW_CACHE_L1D << 0 |
1700 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1701 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1703 { .type = PERF_TYPE_HW_CACHE,
1705 PERF_COUNT_HW_CACHE_L1D << 0 |
1706 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1707 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1709 struct parse_events_error errinfo;
1711 /* Set attrs if no event is selected and !null_run: */
1712 if (stat_config.null_run)
1715 bzero(&errinfo, sizeof(errinfo));
1716 if (transaction_run) {
1717 /* Handle -T as -M transaction. Once platform specific metrics
1718 * support has been added to the json files, all architectures
1719 * will use this approach. To determine transaction support
1720 * on an architecture test for such a metric name.
1722 if (metricgroup__has_metric("transaction")) {
1723 struct option opt = { .value = &evsel_list };
1725 return metricgroup__parse_groups(&opt, "transaction",
1726 stat_config.metric_no_group,
1727 stat_config.metric_no_merge,
1728 &stat_config.metric_events);
1731 if (pmu_have_event("cpu", "cycles-ct") &&
1732 pmu_have_event("cpu", "el-start"))
1733 err = parse_events(evsel_list, transaction_attrs,
1736 err = parse_events(evsel_list,
1737 transaction_limited_attrs,
1740 fprintf(stderr, "Cannot set up transaction events\n");
1741 parse_events_print_error(&errinfo, transaction_attrs);
1750 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
1751 fprintf(stderr, "freeze_on_smi is not supported.\n");
1756 if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
1757 fprintf(stderr, "Failed to set freeze_on_smi.\n");
1763 if (pmu_have_event("msr", "aperf") &&
1764 pmu_have_event("msr", "smi")) {
1765 if (!force_metric_only)
1766 stat_config.metric_only = true;
1767 err = parse_events(evsel_list, smi_cost_attrs, &errinfo);
1769 fprintf(stderr, "To measure SMI cost, it needs "
1770 "msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
1771 parse_events_print_error(&errinfo, smi_cost_attrs);
1775 parse_events_print_error(&errinfo, smi_cost_attrs);
1776 fprintf(stderr, "Cannot set up SMI cost events\n");
1783 const char **metric_attrs = topdown_metric_attrs;
1784 unsigned int max_level = 1;
1788 if (!force_metric_only)
1789 stat_config.metric_only = true;
1791 if (pmu_have_event("cpu", topdown_metric_L2_attrs[5])) {
1792 metric_attrs = topdown_metric_L2_attrs;
1796 if (stat_config.topdown_level > max_level) {
1797 pr_err("Invalid top-down metrics level. The max level is %u.\n", max_level);
1799 } else if (!stat_config.topdown_level)
1800 stat_config.topdown_level = max_level;
1802 if (topdown_filter_events(metric_attrs, &str, 1) < 0) {
1803 pr_err("Out of memory\n");
1806 if (metric_attrs[0] && str) {
1807 if (!stat_config.interval && !stat_config.metric_only) {
1808 fprintf(stat_config.output,
1809 "Topdown accuracy may decrease when measuring long periods.\n"
1810 "Please print the result regularly, e.g. -I1000\n");
1817 if (stat_config.aggr_mode != AGGR_GLOBAL &&
1818 stat_config.aggr_mode != AGGR_CORE) {
1819 pr_err("top down event configuration requires --per-core mode\n");
1822 stat_config.aggr_mode = AGGR_CORE;
1823 if (nr_cgroups || !target__has_cpu(&target)) {
1824 pr_err("top down event configuration requires system-wide mode (-a)\n");
1828 if (topdown_filter_events(topdown_attrs, &str,
1829 arch_topdown_check_group(&warn)) < 0) {
1830 pr_err("Out of memory\n");
1833 if (topdown_attrs[0] && str) {
1835 arch_topdown_group_warn();
1837 err = parse_events(evsel_list, str, &errinfo);
1840 "Cannot set up top down events %s: %d\n",
1842 parse_events_print_error(&errinfo, str);
1847 fprintf(stderr, "System does not support topdown\n");
1853 if (!evsel_list->core.nr_entries) {
1854 if (target__has_cpu(&target))
1855 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
1857 if (evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
1859 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
1860 if (evlist__add_default_attrs(evsel_list, frontend_attrs) < 0)
1863 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
1864 if (evlist__add_default_attrs(evsel_list, backend_attrs) < 0)
1867 if (evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
1870 if (arch_evlist__add_default_attrs(evsel_list) < 0)
1874 /* Detailed events get appended to the event list: */
1876 if (detailed_run < 1)
1879 /* Append detailed run extra attributes: */
1880 if (evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1883 if (detailed_run < 2)
1886 /* Append very detailed run extra attributes: */
1887 if (evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1890 if (detailed_run < 3)
1893 /* Append very, very detailed run extra attributes: */
1894 return evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1897 static const char * const stat_record_usage[] = {
1898 "perf stat record [<options>]",
1902 static void init_features(struct perf_session *session)
1906 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
1907 perf_header__set_feat(&session->header, feat);
1909 perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
1910 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
1911 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
1912 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
1913 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
1916 static int __cmd_record(int argc, const char **argv)
1918 struct perf_session *session;
1919 struct perf_data *data = &perf_stat.data;
1921 argc = parse_options(argc, argv, stat_options, stat_record_usage,
1922 PARSE_OPT_STOP_AT_NON_OPTION);
1925 data->path = output_name;
1927 if (stat_config.run_count != 1 || forever) {
1928 pr_err("Cannot use -r option with perf stat record.\n");
1932 session = perf_session__new(data, false, NULL);
1933 if (IS_ERR(session)) {
1934 pr_err("Perf session creation failed\n");
1935 return PTR_ERR(session);
1938 init_features(session);
1940 session->evlist = evsel_list;
1941 perf_stat.session = session;
1942 perf_stat.record = true;
1946 static int process_stat_round_event(struct perf_session *session,
1947 union perf_event *event)
1949 struct perf_record_stat_round *stat_round = &event->stat_round;
1950 struct evsel *counter;
1951 struct timespec tsh, *ts = NULL;
1952 const char **argv = session->header.env.cmdline_argv;
1953 int argc = session->header.env.nr_cmdline;
1955 evlist__for_each_entry(evsel_list, counter)
1956 perf_stat_process_counter(&stat_config, counter);
1958 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
1959 update_stats(&walltime_nsecs_stats, stat_round->time);
1961 if (stat_config.interval && stat_round->time) {
1962 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
1963 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
1967 print_counters(ts, argc, argv);
1972 int process_stat_config_event(struct perf_session *session,
1973 union perf_event *event)
1975 struct perf_tool *tool = session->tool;
1976 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1978 perf_event__read_stat_config(&stat_config, &event->stat_config);
1980 if (perf_cpu_map__empty(st->cpus)) {
1981 if (st->aggr_mode != AGGR_UNSET)
1982 pr_warning("warning: processing task data, aggregation mode not set\n");
1986 if (st->aggr_mode != AGGR_UNSET)
1987 stat_config.aggr_mode = st->aggr_mode;
1989 if (perf_stat.data.is_pipe)
1990 perf_stat_init_aggr_mode();
1992 perf_stat_init_aggr_mode_file(st);
1997 static int set_maps(struct perf_stat *st)
1999 if (!st->cpus || !st->threads)
2002 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2005 perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
2007 if (evlist__alloc_stats(evsel_list, true))
2010 st->maps_allocated = true;
2015 int process_thread_map_event(struct perf_session *session,
2016 union perf_event *event)
2018 struct perf_tool *tool = session->tool;
2019 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2022 pr_warning("Extra thread map event, ignoring.\n");
2026 st->threads = thread_map__new_event(&event->thread_map);
2030 return set_maps(st);
2034 int process_cpu_map_event(struct perf_session *session,
2035 union perf_event *event)
2037 struct perf_tool *tool = session->tool;
2038 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2039 struct perf_cpu_map *cpus;
2042 pr_warning("Extra cpu map event, ignoring.\n");
2046 cpus = cpu_map__new_data(&event->cpu_map.data);
2051 return set_maps(st);
2054 static const char * const stat_report_usage[] = {
2055 "perf stat report [<options>]",
2059 static struct perf_stat perf_stat = {
2061 .attr = perf_event__process_attr,
2062 .event_update = perf_event__process_event_update,
2063 .thread_map = process_thread_map_event,
2064 .cpu_map = process_cpu_map_event,
2065 .stat_config = process_stat_config_event,
2066 .stat = perf_event__process_stat_event,
2067 .stat_round = process_stat_round_event,
2069 .aggr_mode = AGGR_UNSET,
2072 static int __cmd_report(int argc, const char **argv)
2074 struct perf_session *session;
2075 const struct option options[] = {
2076 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2077 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2078 "aggregate counts per processor socket", AGGR_SOCKET),
2079 OPT_SET_UINT(0, "per-die", &perf_stat.aggr_mode,
2080 "aggregate counts per processor die", AGGR_DIE),
2081 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2082 "aggregate counts per physical processor core", AGGR_CORE),
2083 OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
2084 "aggregate counts per numa node", AGGR_NODE),
2085 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2086 "disable CPU count aggregation", AGGR_NONE),
2092 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2094 if (!input_name || !strlen(input_name)) {
2095 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2098 input_name = "perf.data";
2101 perf_stat.data.path = input_name;
2102 perf_stat.data.mode = PERF_DATA_MODE_READ;
2104 session = perf_session__new(&perf_stat.data, false, &perf_stat.tool);
2105 if (IS_ERR(session))
2106 return PTR_ERR(session);
2108 perf_stat.session = session;
2109 stat_config.output = stderr;
2110 evsel_list = session->evlist;
2112 ret = perf_session__process_events(session);
2116 perf_session__delete(session);
2120 static void setup_system_wide(int forks)
2123 * Make system wide (-a) the default target if
2124 * no target was specified and one of following
2125 * conditions is met:
2127 * - there's no workload specified
2128 * - there is workload specified but all requested
2129 * events are system wide events
2131 if (!target__none(&target))
2135 target.system_wide = true;
2137 struct evsel *counter;
2139 evlist__for_each_entry(evsel_list, counter) {
2140 if (!counter->core.system_wide &&
2141 strcmp(counter->name, "duration_time")) {
2146 if (evsel_list->core.nr_entries)
2147 target.system_wide = true;
2151 int cmd_stat(int argc, const char **argv)
2153 const char * const stat_usage[] = {
2154 "perf stat [<options>] [<command>]",
2157 int status = -EINVAL, run_idx, err;
2159 FILE *output = stderr;
2160 unsigned int interval, timeout;
2161 const char * const stat_subcommands[] = { "record", "report" };
2162 char errbuf[BUFSIZ];
2164 setlocale(LC_ALL, "");
2166 evsel_list = evlist__new();
2167 if (evsel_list == NULL)
2170 parse_events__shrink_config_terms();
2172 /* String-parsing callback-based options would segfault when negated */
2173 set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
2174 set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
2175 set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
2177 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2178 (const char **) stat_usage,
2179 PARSE_OPT_STOP_AT_NON_OPTION);
2180 perf_stat__collect_metric_expr(evsel_list);
2181 perf_stat__init_shadow_stats();
2183 if (stat_config.csv_sep) {
2184 stat_config.csv_output = true;
2185 if (!strcmp(stat_config.csv_sep, "\\t"))
2186 stat_config.csv_sep = "\t";
2188 stat_config.csv_sep = DEFAULT_SEPARATOR;
2190 if (argc && !strncmp(argv[0], "rec", 3)) {
2191 argc = __cmd_record(argc, argv);
2194 } else if (argc && !strncmp(argv[0], "rep", 3))
2195 return __cmd_report(argc, argv);
2197 interval = stat_config.interval;
2198 timeout = stat_config.timeout;
2201 * For record command the -o is already taken care of.
2203 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2206 if (output_name && output_fd) {
2207 fprintf(stderr, "cannot use both --output and --log-fd\n");
2208 parse_options_usage(stat_usage, stat_options, "o", 1);
2209 parse_options_usage(NULL, stat_options, "log-fd", 0);
2213 if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2214 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2218 if (stat_config.metric_only && stat_config.run_count > 1) {
2219 fprintf(stderr, "--metric-only is not supported with -r\n");
2223 if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
2224 fprintf(stderr, "--table is only supported with -r\n");
2225 parse_options_usage(stat_usage, stat_options, "r", 1);
2226 parse_options_usage(NULL, stat_options, "table", 0);
2230 if (output_fd < 0) {
2231 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2232 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2236 if (!output && !stat_config.quiet) {
2238 mode = append_file ? "a" : "w";
2240 output = fopen(output_name, mode);
2242 perror("failed to create output file");
2245 clock_gettime(CLOCK_REALTIME, &tm);
2246 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2247 } else if (output_fd > 0) {
2248 mode = append_file ? "a" : "w";
2249 output = fdopen(output_fd, mode);
2251 perror("Failed opening logfd");
2256 stat_config.output = output;
2259 * let the spreadsheet do the pretty-printing
2261 if (stat_config.csv_output) {
2262 /* User explicitly passed -B? */
2263 if (big_num_opt == 1) {
2264 fprintf(stderr, "-B option not supported with -x\n");
2265 parse_options_usage(stat_usage, stat_options, "B", 1);
2266 parse_options_usage(NULL, stat_options, "x", 1);
2268 } else /* Nope, so disable big number formatting */
2269 stat_config.big_num = false;
2270 } else if (big_num_opt == 0) /* User passed --no-big-num */
2271 stat_config.big_num = false;
2273 err = target__validate(&target);
2275 target__strerror(&target, err, errbuf, BUFSIZ);
2276 pr_warning("%s\n", errbuf);
2279 setup_system_wide(argc);
2282 * Display user/system times only for single
2283 * run and when there's specified tracee.
2285 if ((stat_config.run_count == 1) && target__none(&target))
2286 stat_config.ru_display = true;
2288 if (stat_config.run_count < 0) {
2289 pr_err("Run count must be a positive number\n");
2290 parse_options_usage(stat_usage, stat_options, "r", 1);
2292 } else if (stat_config.run_count == 0) {
2294 stat_config.run_count = 1;
2297 if (stat_config.walltime_run_table) {
2298 stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
2299 if (!stat_config.walltime_run) {
2300 pr_err("failed to setup -r option");
2305 if ((stat_config.aggr_mode == AGGR_THREAD) &&
2306 !target__has_task(&target)) {
2307 if (!target.system_wide || target.cpu_list) {
2308 fprintf(stderr, "The --per-thread option is only "
2309 "available when monitoring via -p -t -a "
2310 "options or only --per-thread.\n");
2311 parse_options_usage(NULL, stat_options, "p", 1);
2312 parse_options_usage(NULL, stat_options, "t", 1);
2318 * no_aggr, cgroup are for system-wide only
2319 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2321 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2322 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2323 !target__has_cpu(&target)) {
2324 fprintf(stderr, "both cgroup and no-aggregation "
2325 "modes only available in system-wide mode\n");
2327 parse_options_usage(stat_usage, stat_options, "G", 1);
2328 parse_options_usage(NULL, stat_options, "A", 1);
2329 parse_options_usage(NULL, stat_options, "a", 1);
2333 if (add_default_attributes())
2336 if (stat_config.cgroup_list) {
2337 if (nr_cgroups > 0) {
2338 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
2339 parse_options_usage(stat_usage, stat_options, "G", 1);
2340 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2344 if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list,
2345 &stat_config.metric_events, true) < 0) {
2346 parse_options_usage(stat_usage, stat_options,
2347 "for-each-cgroup", 0);
2352 if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2353 target.per_thread = true;
2355 if (evlist__create_maps(evsel_list, &target) < 0) {
2356 if (target__has_task(&target)) {
2357 pr_err("Problems finding threads of monitor\n");
2358 parse_options_usage(stat_usage, stat_options, "p", 1);
2359 parse_options_usage(NULL, stat_options, "t", 1);
2360 } else if (target__has_cpu(&target)) {
2361 perror("failed to parse CPUs map");
2362 parse_options_usage(stat_usage, stat_options, "C", 1);
2363 parse_options_usage(NULL, stat_options, "a", 1);
2368 evlist__check_cpu_maps(evsel_list);
2371 * Initialize thread_map with comm names,
2372 * so we could print it out on output.
2374 if (stat_config.aggr_mode == AGGR_THREAD) {
2375 thread_map__read_comms(evsel_list->core.threads);
2376 if (target.system_wide) {
2377 if (runtime_stat_new(&stat_config,
2378 perf_thread_map__nr(evsel_list->core.threads))) {
2384 if (stat_config.aggr_mode == AGGR_NODE)
2385 cpu__setup_cpunode_map();
2387 if (stat_config.times && interval)
2388 interval_count = true;
2389 else if (stat_config.times && !interval) {
2390 pr_err("interval-count option should be used together with "
2391 "interval-print.\n");
2392 parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2393 parse_options_usage(stat_usage, stat_options, "I", 1);
2397 if (timeout && timeout < 100) {
2399 pr_err("timeout must be >= 10ms.\n");
2400 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2403 pr_warning("timeout < 100ms. "
2404 "The overhead percentage could be high in some cases. "
2405 "Please proceed with caution.\n");
2407 if (timeout && interval) {
2408 pr_err("timeout option is not supported with interval-print.\n");
2409 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2410 parse_options_usage(stat_usage, stat_options, "I", 1);
2414 if (evlist__alloc_stats(evsel_list, interval))
2417 if (perf_stat_init_aggr_mode())
2421 * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2422 * while avoiding that older tools show confusing messages.
2424 * However for pipe sessions we need to keep it zero,
2425 * because script's perf_evsel__check_attr is triggered
2426 * by attr->sample_type != 0, and we can't run it on
2429 stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2432 * We dont want to block the signals - that would cause
2433 * child tasks to inherit that and Ctrl-C would not work.
2434 * What we want is for Ctrl-C to work in the exec()-ed
2435 * task, but being ignored by perf stat itself:
2439 signal(SIGINT, skip_signal);
2440 signal(SIGCHLD, skip_signal);
2441 signal(SIGALRM, skip_signal);
2442 signal(SIGABRT, skip_signal);
2444 if (evlist__initialize_ctlfd(evsel_list, stat_config.ctl_fd, stat_config.ctl_fd_ack))
2448 for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
2449 if (stat_config.run_count != 1 && verbose > 0)
2450 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2454 evlist__reset_prev_raw_counts(evsel_list);
2456 status = run_perf_stat(argc, argv, run_idx);
2457 if (forever && status != -1 && !interval) {
2458 print_counters(NULL, argc, argv);
2459 perf_stat__reset_stats();
2463 if (!forever && status != -1 && (!interval || stat_config.summary))
2464 print_counters(NULL, argc, argv);
2466 evlist__finalize_ctlfd(evsel_list);
2470 * We synthesize the kernel mmap record just so that older tools
2471 * don't emit warnings about not being able to resolve symbols
2472 * due to /proc/sys/kernel/kptr_restrict settings and instead provide
2473 * a saner message about no samples being in the perf.data file.
2475 * This also serves to suppress a warning about f_header.data.size == 0
2476 * in header.c at the moment 'perf stat record' gets introduced, which
2477 * is not really needed once we start adding the stat specific PERF_RECORD_
2478 * records, but the need to suppress the kptr_restrict messages in older
2479 * tools remain -acme
2481 int fd = perf_data__fd(&perf_stat.data);
2483 err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2484 process_synthesized_event,
2485 &perf_stat.session->machines.host);
2487 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2488 "older tools may produce warnings about this file\n.");
2492 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2493 pr_err("failed to write stat round event\n");
2496 if (!perf_stat.data.is_pipe) {
2497 perf_stat.session->header.data_size += perf_stat.bytes_written;
2498 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2501 evlist__close(evsel_list);
2502 perf_session__delete(perf_stat.session);
2505 perf_stat__exit_aggr_mode();
2506 evlist__free_stats(evsel_list);
2508 zfree(&stat_config.walltime_run);
2510 if (smi_cost && smi_reset)
2511 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2513 evlist__delete(evsel_list);
2515 metricgroup__rblist_exit(&stat_config.metric_events);
2516 runtime_stat_delete(&stat_config);
2517 evlist__close_control(stat_config.ctl_fd, stat_config.ctl_fd_ack, &stat_config.ctl_fd_close);