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
33 * Improvements and fixes by:
44 #include "util/cgroup.h"
45 #include <subcmd/parse-options.h>
46 #include "util/parse-events.h"
47 #include "util/pmus.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"
71 #include "util/iostat.h"
72 #include "util/util.h"
75 #include <linux/time64.h>
76 #include <linux/zalloc.h>
77 #include <api/fs/fs.h>
81 #include <sys/prctl.h>
85 #include <sys/types.h>
90 #include <sys/resource.h>
91 #include <linux/err.h>
93 #include <linux/ctype.h>
94 #include <perf/evlist.h>
95 #include <internal/threadmap.h>
97 #define DEFAULT_SEPARATOR " "
98 #define FREEZE_ON_SMI_PATH "devices/cpu/freeze_on_smi"
100 static void print_counters(struct timespec *ts, int argc, const char **argv);
102 static struct evlist *evsel_list;
103 static struct parse_events_option_args parse_events_option_args = {
104 .evlistp = &evsel_list,
107 static bool all_counters_use_bpf = true;
109 static struct target target = {
113 #define METRIC_ONLY_LEN 20
115 static volatile sig_atomic_t child_pid = -1;
116 static int detailed_run = 0;
117 static bool transaction_run;
118 static bool topdown_run = false;
119 static bool smi_cost = false;
120 static bool smi_reset = false;
121 static int big_num_opt = -1;
122 static const char *pre_cmd = NULL;
123 static const char *post_cmd = NULL;
124 static bool sync_run = false;
125 static bool forever = false;
126 static bool force_metric_only = false;
127 static struct timespec ref_time;
128 static bool append_file;
129 static bool interval_count;
130 static const char *output_name;
131 static int output_fd;
132 static char *metrics;
136 struct perf_data data;
137 struct perf_session *session;
139 struct perf_tool tool;
141 struct perf_cpu_map *cpus;
142 struct perf_thread_map *threads;
143 enum aggr_mode aggr_mode;
147 static struct perf_stat perf_stat;
148 #define STAT_RECORD perf_stat.record
150 static volatile sig_atomic_t done = 0;
152 static struct perf_stat_config stat_config = {
153 .aggr_mode = AGGR_GLOBAL,
154 .aggr_level = MAX_CACHE_LVL + 1,
156 .unit_width = 4, /* strlen("unit") */
158 .metric_only_len = METRIC_ONLY_LEN,
159 .walltime_nsecs_stats = &walltime_nsecs_stats,
160 .ru_stats = &ru_stats,
167 static void evlist__check_cpu_maps(struct evlist *evlist)
169 struct evsel *evsel, *warned_leader = NULL;
171 evlist__for_each_entry(evlist, evsel) {
172 struct evsel *leader = evsel__leader(evsel);
174 /* Check that leader matches cpus with each member. */
177 if (perf_cpu_map__equal(leader->core.cpus, evsel->core.cpus))
180 /* If there's mismatch disable the group and warn user. */
181 if (warned_leader != leader) {
184 pr_warning("WARNING: grouped events cpus do not match.\n"
185 "Events with CPUs not matching the leader will "
186 "be removed from the group.\n");
187 evsel__group_desc(leader, buf, sizeof(buf));
188 pr_warning(" %s\n", buf);
189 warned_leader = leader;
194 cpu_map__snprint(leader->core.cpus, buf, sizeof(buf));
195 pr_warning(" %s: %s\n", leader->name, buf);
196 cpu_map__snprint(evsel->core.cpus, buf, sizeof(buf));
197 pr_warning(" %s: %s\n", evsel->name, buf);
200 evsel__remove_from_group(evsel, leader);
204 static inline void diff_timespec(struct timespec *r, struct timespec *a,
207 r->tv_sec = a->tv_sec - b->tv_sec;
208 if (a->tv_nsec < b->tv_nsec) {
209 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
212 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
216 static void perf_stat__reset_stats(void)
218 evlist__reset_stats(evsel_list);
219 perf_stat__reset_shadow_stats();
222 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
223 union perf_event *event,
224 struct perf_sample *sample __maybe_unused,
225 struct machine *machine __maybe_unused)
227 if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
228 pr_err("failed to write perf data, error: %m\n");
232 perf_stat.bytes_written += event->header.size;
236 static int write_stat_round_event(u64 tm, u64 type)
238 return perf_event__synthesize_stat_round(NULL, tm, type,
239 process_synthesized_event,
243 #define WRITE_STAT_ROUND_EVENT(time, interval) \
244 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
246 #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
248 static int evsel__write_stat_event(struct evsel *counter, int cpu_map_idx, u32 thread,
249 struct perf_counts_values *count)
251 struct perf_sample_id *sid = SID(counter, cpu_map_idx, thread);
252 struct perf_cpu cpu = perf_cpu_map__cpu(evsel__cpus(counter), cpu_map_idx);
254 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
255 process_synthesized_event, NULL);
258 static int read_single_counter(struct evsel *counter, int cpu_map_idx,
259 int thread, struct timespec *rs)
261 switch(counter->tool_event) {
262 case PERF_TOOL_DURATION_TIME: {
263 u64 val = rs->tv_nsec + rs->tv_sec*1000000000ULL;
264 struct perf_counts_values *count =
265 perf_counts(counter->counts, cpu_map_idx, thread);
266 count->ena = count->run = val;
270 case PERF_TOOL_USER_TIME:
271 case PERF_TOOL_SYSTEM_TIME: {
273 struct perf_counts_values *count =
274 perf_counts(counter->counts, cpu_map_idx, thread);
275 if (counter->tool_event == PERF_TOOL_USER_TIME)
276 val = ru_stats.ru_utime_usec_stat.mean;
278 val = ru_stats.ru_stime_usec_stat.mean;
279 count->ena = count->run = val;
285 return evsel__read_counter(counter, cpu_map_idx, thread);
287 /* This should never be reached */
293 * Read out the results of a single counter:
294 * do not aggregate counts across CPUs in system-wide mode
296 static int read_counter_cpu(struct evsel *counter, struct timespec *rs, int cpu_map_idx)
298 int nthreads = perf_thread_map__nr(evsel_list->core.threads);
301 if (!counter->supported)
304 for (thread = 0; thread < nthreads; thread++) {
305 struct perf_counts_values *count;
307 count = perf_counts(counter->counts, cpu_map_idx, thread);
310 * The leader's group read loads data into its group members
311 * (via evsel__read_counter()) and sets their count->loaded.
313 if (!perf_counts__is_loaded(counter->counts, cpu_map_idx, thread) &&
314 read_single_counter(counter, cpu_map_idx, thread, rs)) {
315 counter->counts->scaled = -1;
316 perf_counts(counter->counts, cpu_map_idx, thread)->ena = 0;
317 perf_counts(counter->counts, cpu_map_idx, thread)->run = 0;
321 perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, false);
324 if (evsel__write_stat_event(counter, cpu_map_idx, thread, count)) {
325 pr_err("failed to write stat event\n");
331 fprintf(stat_config.output,
332 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
333 evsel__name(counter),
334 perf_cpu_map__cpu(evsel__cpus(counter),
336 count->val, count->ena, count->run);
343 static int read_affinity_counters(struct timespec *rs)
345 struct evlist_cpu_iterator evlist_cpu_itr;
346 struct affinity saved_affinity, *affinity;
348 if (all_counters_use_bpf)
351 if (!target__has_cpu(&target) || target__has_per_thread(&target))
353 else if (affinity__setup(&saved_affinity) < 0)
356 affinity = &saved_affinity;
358 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
359 struct evsel *counter = evlist_cpu_itr.evsel;
361 if (evsel__is_bpf(counter))
365 counter->err = read_counter_cpu(counter, rs,
366 evlist_cpu_itr.cpu_map_idx);
370 affinity__cleanup(&saved_affinity);
375 static int read_bpf_map_counters(void)
377 struct evsel *counter;
380 evlist__for_each_entry(evsel_list, counter) {
381 if (!evsel__is_bpf(counter))
384 err = bpf_counter__read(counter);
391 static int read_counters(struct timespec *rs)
393 if (!stat_config.stop_read_counter) {
394 if (read_bpf_map_counters() ||
395 read_affinity_counters(rs))
401 static void process_counters(void)
403 struct evsel *counter;
405 evlist__for_each_entry(evsel_list, counter) {
407 pr_debug("failed to read counter %s\n", counter->name);
408 if (counter->err == 0 && perf_stat_process_counter(&stat_config, counter))
409 pr_warning("failed to process counter %s\n", counter->name);
413 perf_stat_merge_counters(&stat_config, evsel_list);
414 perf_stat_process_percore(&stat_config, evsel_list);
417 static void process_interval(void)
419 struct timespec ts, rs;
421 clock_gettime(CLOCK_MONOTONIC, &ts);
422 diff_timespec(&rs, &ts, &ref_time);
424 evlist__reset_aggr_stats(evsel_list);
426 if (read_counters(&rs) == 0)
430 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
431 pr_err("failed to write stat round event\n");
434 init_stats(&walltime_nsecs_stats);
435 update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000ULL);
436 print_counters(&rs, 0, NULL);
439 static bool handle_interval(unsigned int interval, int *times)
443 if (interval_count && !(--(*times)))
449 static int enable_counters(void)
454 evlist__for_each_entry(evsel_list, evsel) {
455 if (!evsel__is_bpf(evsel))
458 err = bpf_counter__enable(evsel);
463 if (!target__enable_on_exec(&target)) {
464 if (!all_counters_use_bpf)
465 evlist__enable(evsel_list);
470 static void disable_counters(void)
472 struct evsel *counter;
475 * If we don't have tracee (attaching to task or cpu), counters may
476 * still be running. To get accurate group ratios, we must stop groups
477 * from counting before reading their constituent counters.
479 if (!target__none(&target)) {
480 evlist__for_each_entry(evsel_list, counter)
481 bpf_counter__disable(counter);
482 if (!all_counters_use_bpf)
483 evlist__disable(evsel_list);
487 static volatile sig_atomic_t workload_exec_errno;
490 * evlist__prepare_workload will send a SIGUSR1
491 * if the fork fails, since we asked by setting its
492 * want_signal to true.
494 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
495 void *ucontext __maybe_unused)
497 workload_exec_errno = info->si_value.sival_int;
500 static bool evsel__should_store_id(struct evsel *counter)
502 return STAT_RECORD || counter->core.attr.read_format & PERF_FORMAT_ID;
505 static bool is_target_alive(struct target *_target,
506 struct perf_thread_map *threads)
511 if (!target__has_task(_target))
514 for (i = 0; i < threads->nr; i++) {
517 scnprintf(path, PATH_MAX, "%s/%d", procfs__mountpoint(),
518 threads->map[i].pid);
520 if (!stat(path, &st))
527 static void process_evlist(struct evlist *evlist, unsigned int interval)
529 enum evlist_ctl_cmd cmd = EVLIST_CTL_CMD_UNSUPPORTED;
531 if (evlist__ctlfd_process(evlist, &cmd) > 0) {
533 case EVLIST_CTL_CMD_ENABLE:
535 case EVLIST_CTL_CMD_DISABLE:
539 case EVLIST_CTL_CMD_SNAPSHOT:
540 case EVLIST_CTL_CMD_ACK:
541 case EVLIST_CTL_CMD_UNSUPPORTED:
542 case EVLIST_CTL_CMD_EVLIST:
543 case EVLIST_CTL_CMD_STOP:
544 case EVLIST_CTL_CMD_PING:
551 static void compute_tts(struct timespec *time_start, struct timespec *time_stop,
554 int tts = *time_to_sleep;
555 struct timespec time_diff;
557 diff_timespec(&time_diff, time_stop, time_start);
559 tts -= time_diff.tv_sec * MSEC_PER_SEC +
560 time_diff.tv_nsec / NSEC_PER_MSEC;
565 *time_to_sleep = tts;
568 static int dispatch_events(bool forks, int timeout, int interval, int *times)
570 int child_exited = 0, status = 0;
571 int time_to_sleep, sleep_time;
572 struct timespec time_start, time_stop;
575 sleep_time = interval;
577 sleep_time = timeout;
581 time_to_sleep = sleep_time;
585 child_exited = waitpid(child_pid, &status, WNOHANG);
587 child_exited = !is_target_alive(&target, evsel_list->core.threads) ? 1 : 0;
592 clock_gettime(CLOCK_MONOTONIC, &time_start);
593 if (!(evlist__poll(evsel_list, time_to_sleep) > 0)) { /* poll timeout or EINTR */
594 if (timeout || handle_interval(interval, times))
596 time_to_sleep = sleep_time;
597 } else { /* fd revent */
598 process_evlist(evsel_list, interval);
599 clock_gettime(CLOCK_MONOTONIC, &time_stop);
600 compute_tts(&time_start, &time_stop, &time_to_sleep);
607 enum counter_recovery {
613 static enum counter_recovery stat_handle_error(struct evsel *counter)
617 * PPC returns ENXIO for HW counters until 2.6.37
618 * (behavior changed with commit b0a873e).
620 if (errno == EINVAL || errno == ENOSYS ||
621 errno == ENOENT || errno == EOPNOTSUPP ||
624 ui__warning("%s event is not supported by the kernel.\n",
625 evsel__name(counter));
626 counter->supported = false;
628 * errored is a sticky flag that means one of the counter's
629 * cpu event had a problem and needs to be reexamined.
631 counter->errored = true;
633 if ((evsel__leader(counter) != counter) ||
634 !(counter->core.leader->nr_members > 1))
636 } else if (evsel__fallback(counter, &target, errno, msg, sizeof(msg))) {
638 ui__warning("%s\n", msg);
639 return COUNTER_RETRY;
640 } else if (target__has_per_thread(&target) &&
641 evsel_list->core.threads &&
642 evsel_list->core.threads->err_thread != -1) {
644 * For global --per-thread case, skip current
647 if (!thread_map__remove(evsel_list->core.threads,
648 evsel_list->core.threads->err_thread)) {
649 evsel_list->core.threads->err_thread = -1;
650 return COUNTER_RETRY;
652 } else if (counter->skippable) {
654 ui__warning("skipping event %s that kernel failed to open .\n",
655 evsel__name(counter));
656 counter->supported = false;
657 counter->errored = true;
661 evsel__open_strerror(counter, &target, errno, msg, sizeof(msg));
662 ui__error("%s\n", msg);
665 kill(child_pid, SIGTERM);
666 return COUNTER_FATAL;
669 static int __run_perf_stat(int argc, const char **argv, int run_idx)
671 int interval = stat_config.interval;
672 int times = stat_config.times;
673 int timeout = stat_config.timeout;
675 unsigned long long t0, t1;
676 struct evsel *counter;
679 const bool forks = (argc > 0);
680 bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
681 struct evlist_cpu_iterator evlist_cpu_itr;
682 struct affinity saved_affinity, *affinity = NULL;
684 bool second_pass = false;
687 if (evlist__prepare_workload(evsel_list, &target, argv, is_pipe, workload_exec_failed_signal) < 0) {
688 perror("failed to prepare workload");
691 child_pid = evsel_list->workload.pid;
694 if (!cpu_map__is_dummy(evsel_list->core.user_requested_cpus)) {
695 if (affinity__setup(&saved_affinity) < 0)
697 affinity = &saved_affinity;
700 evlist__for_each_entry(evsel_list, counter) {
701 counter->reset_group = false;
702 if (bpf_counter__load(counter, &target))
704 if (!(evsel__is_bperf(counter)))
705 all_counters_use_bpf = false;
708 evlist__reset_aggr_stats(evsel_list);
710 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
711 counter = evlist_cpu_itr.evsel;
714 * bperf calls evsel__open_per_cpu() in bperf__load(), so
715 * no need to call it again here.
720 if (counter->reset_group || counter->errored)
722 if (evsel__is_bperf(counter))
725 if (create_perf_stat_counter(counter, &stat_config, &target,
726 evlist_cpu_itr.cpu_map_idx) < 0) {
729 * Weak group failed. We cannot just undo this here
730 * because earlier CPUs might be in group mode, and the kernel
731 * doesn't support mixing group and non group reads. Defer
733 * Don't close here because we're in the wrong affinity.
735 if ((errno == EINVAL || errno == EBADF) &&
736 evsel__leader(counter) != counter &&
737 counter->weak_group) {
738 evlist__reset_weak_group(evsel_list, counter, false);
739 assert(counter->reset_group);
744 switch (stat_handle_error(counter)) {
756 counter->supported = true;
761 * Now redo all the weak group after closing them,
762 * and also close errored counters.
765 /* First close errored or weak retry */
766 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
767 counter = evlist_cpu_itr.evsel;
769 if (!counter->reset_group && !counter->errored)
772 perf_evsel__close_cpu(&counter->core, evlist_cpu_itr.cpu_map_idx);
774 /* Now reopen weak */
775 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
776 counter = evlist_cpu_itr.evsel;
778 if (!counter->reset_group)
781 pr_debug2("reopening weak %s\n", evsel__name(counter));
782 if (create_perf_stat_counter(counter, &stat_config, &target,
783 evlist_cpu_itr.cpu_map_idx) < 0) {
785 switch (stat_handle_error(counter)) {
789 goto try_again_reset;
796 counter->supported = true;
799 affinity__cleanup(affinity);
801 evlist__for_each_entry(evsel_list, counter) {
802 if (!counter->supported) {
803 perf_evsel__free_fd(&counter->core);
807 l = strlen(counter->unit);
808 if (l > stat_config.unit_width)
809 stat_config.unit_width = l;
811 if (evsel__should_store_id(counter) &&
812 evsel__store_ids(counter, evsel_list))
816 if (evlist__apply_filters(evsel_list, &counter)) {
817 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
818 counter->filter, evsel__name(counter), errno,
819 str_error_r(errno, msg, sizeof(msg)));
824 int fd = perf_data__fd(&perf_stat.data);
827 err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
829 err = perf_session__write_header(perf_stat.session, evsel_list,
836 err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
837 process_synthesized_event, is_pipe);
842 if (target.initial_delay) {
843 pr_info(EVLIST_DISABLED_MSG);
845 err = enable_counters();
850 /* Exec the command, if any */
852 evlist__start_workload(evsel_list);
854 if (target.initial_delay > 0) {
855 usleep(target.initial_delay * USEC_PER_MSEC);
856 err = enable_counters();
860 pr_info(EVLIST_ENABLED_MSG);
864 clock_gettime(CLOCK_MONOTONIC, &ref_time);
867 if (interval || timeout || evlist__ctlfd_initialized(evsel_list))
868 status = dispatch_events(forks, timeout, interval, ×);
869 if (child_pid != -1) {
871 kill(child_pid, SIGTERM);
872 wait4(child_pid, &status, 0, &stat_config.ru_data);
875 if (workload_exec_errno) {
876 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
877 pr_err("Workload failed: %s\n", emsg);
881 if (WIFSIGNALED(status))
882 psignal(WTERMSIG(status), argv[0]);
884 status = dispatch_events(forks, timeout, interval, ×);
891 if (stat_config.walltime_run_table)
892 stat_config.walltime_run[run_idx] = t1 - t0;
894 if (interval && stat_config.summary) {
895 stat_config.interval = 0;
896 stat_config.stop_read_counter = true;
897 init_stats(&walltime_nsecs_stats);
898 update_stats(&walltime_nsecs_stats, t1 - t0);
900 evlist__copy_prev_raw_counts(evsel_list);
901 evlist__reset_prev_raw_counts(evsel_list);
902 evlist__reset_aggr_stats(evsel_list);
904 update_stats(&walltime_nsecs_stats, t1 - t0);
905 update_rusage_stats(&ru_stats, &stat_config.ru_data);
909 * Closing a group leader splits the group, and as we only disable
910 * group leaders, results in remaining events becoming enabled. To
911 * avoid arbitrary skew, we must read all counters before closing any
914 if (read_counters(&(struct timespec) { .tv_nsec = t1-t0 }) == 0)
918 * We need to keep evsel_list alive, because it's processed
919 * later the evsel_list will be closed after.
922 evlist__close(evsel_list);
924 return WEXITSTATUS(status);
927 static int run_perf_stat(int argc, const char **argv, int run_idx)
932 ret = system(pre_cmd);
940 ret = __run_perf_stat(argc, argv, run_idx);
945 ret = system(post_cmd);
953 static void print_counters(struct timespec *ts, int argc, const char **argv)
955 /* Do not print anything if we record to the pipe. */
956 if (STAT_RECORD && perf_stat.data.is_pipe)
961 evlist__print_counters(evsel_list, &stat_config, &target, ts, argc, argv);
964 static volatile sig_atomic_t signr = -1;
966 static void skip_signal(int signo)
968 if ((child_pid == -1) || stat_config.interval)
973 * render child_pid harmless
974 * won't send SIGTERM to a random
975 * process in case of race condition
976 * and fast PID recycling
981 static void sig_atexit(void)
986 * avoid race condition with SIGCHLD handler
987 * in skip_signal() which is modifying child_pid
988 * goal is to avoid send SIGTERM to a random
992 sigaddset(&set, SIGCHLD);
993 sigprocmask(SIG_BLOCK, &set, &oset);
996 kill(child_pid, SIGTERM);
998 sigprocmask(SIG_SETMASK, &oset, NULL);
1003 signal(signr, SIG_DFL);
1004 kill(getpid(), signr);
1007 void perf_stat__set_big_num(int set)
1009 stat_config.big_num = (set != 0);
1012 void perf_stat__set_no_csv_summary(int set)
1014 stat_config.no_csv_summary = (set != 0);
1017 static int stat__set_big_num(const struct option *opt __maybe_unused,
1018 const char *s __maybe_unused, int unset)
1020 big_num_opt = unset ? 0 : 1;
1021 perf_stat__set_big_num(!unset);
1025 static int enable_metric_only(const struct option *opt __maybe_unused,
1026 const char *s __maybe_unused, int unset)
1028 force_metric_only = true;
1029 stat_config.metric_only = !unset;
1033 static int append_metric_groups(const struct option *opt __maybe_unused,
1035 int unset __maybe_unused)
1040 if (asprintf(&tmp, "%s,%s", metrics, str) < 0)
1045 metrics = strdup(str);
1052 static int parse_control_option(const struct option *opt,
1054 int unset __maybe_unused)
1056 struct perf_stat_config *config = opt->value;
1058 return evlist__parse_control(str, &config->ctl_fd, &config->ctl_fd_ack, &config->ctl_fd_close);
1061 static int parse_stat_cgroups(const struct option *opt,
1062 const char *str, int unset)
1064 if (stat_config.cgroup_list) {
1065 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
1069 return parse_cgroups(opt, str, unset);
1072 static int parse_cputype(const struct option *opt,
1074 int unset __maybe_unused)
1076 const struct perf_pmu *pmu;
1077 struct evlist *evlist = *(struct evlist **)opt->value;
1079 if (!list_empty(&evlist->core.entries)) {
1080 fprintf(stderr, "Must define cputype before events/metrics\n");
1084 pmu = perf_pmus__pmu_for_pmu_filter(str);
1086 fprintf(stderr, "--cputype %s is not supported!\n", str);
1089 parse_events_option_args.pmu_filter = pmu->name;
1094 static int parse_cache_level(const struct option *opt,
1096 int unset __maybe_unused)
1099 u32 *aggr_mode = (u32 *)opt->value;
1100 u32 *aggr_level = (u32 *)opt->data;
1103 * If no string is specified, aggregate based on the topology of
1104 * Last Level Cache (LLC). Since the LLC level can change from
1105 * architecture to architecture, set level greater than
1106 * MAX_CACHE_LVL which will be interpreted as LLC.
1109 level = MAX_CACHE_LVL + 1;
1114 * The format to specify cache level is LX or lX where X is the
1117 if (strlen(str) != 2 || (str[0] != 'l' && str[0] != 'L')) {
1118 pr_err("Cache level must be of form L[1-%d], or l[1-%d]\n",
1124 level = atoi(&str[1]);
1126 pr_err("Cache level must be of form L[1-%d], or l[1-%d]\n",
1132 if (level > MAX_CACHE_LVL) {
1133 pr_err("perf only supports max cache level of %d.\n"
1134 "Consider increasing MAX_CACHE_LVL\n", MAX_CACHE_LVL);
1138 *aggr_mode = AGGR_CACHE;
1139 *aggr_level = level;
1143 static struct option stat_options[] = {
1144 OPT_BOOLEAN('T', "transaction", &transaction_run,
1145 "hardware transaction statistics"),
1146 OPT_CALLBACK('e', "event", &parse_events_option_args, "event",
1147 "event selector. use 'perf list' to list available events",
1148 parse_events_option),
1149 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1150 "event filter", parse_filter),
1151 OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
1152 "child tasks do not inherit counters"),
1153 OPT_STRING('p', "pid", &target.pid, "pid",
1154 "stat events on existing process id"),
1155 OPT_STRING('t', "tid", &target.tid, "tid",
1156 "stat events on existing thread id"),
1157 #ifdef HAVE_BPF_SKEL
1158 OPT_STRING('b', "bpf-prog", &target.bpf_str, "bpf-prog-id",
1159 "stat events on existing bpf program id"),
1160 OPT_BOOLEAN(0, "bpf-counters", &target.use_bpf,
1161 "use bpf program to count events"),
1162 OPT_STRING(0, "bpf-attr-map", &target.attr_map, "attr-map-path",
1163 "path to perf_event_attr map"),
1165 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1166 "system-wide collection from all CPUs"),
1167 OPT_BOOLEAN(0, "scale", &stat_config.scale,
1168 "Use --no-scale to disable counter scaling for multiplexing"),
1169 OPT_INCR('v', "verbose", &verbose,
1170 "be more verbose (show counter open errors, etc)"),
1171 OPT_INTEGER('r', "repeat", &stat_config.run_count,
1172 "repeat command and print average + stddev (max: 100, forever: 0)"),
1173 OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
1174 "display details about each run (only with -r option)"),
1175 OPT_BOOLEAN('n', "null", &stat_config.null_run,
1176 "null run - dont start any counters"),
1177 OPT_INCR('d', "detailed", &detailed_run,
1178 "detailed run - start a lot of events"),
1179 OPT_BOOLEAN('S', "sync", &sync_run,
1180 "call sync() before starting a run"),
1181 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1182 "print large numbers with thousands\' separators",
1184 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1185 "list of cpus to monitor in system-wide"),
1186 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1187 "disable aggregation across CPUs or PMUs", AGGR_NONE),
1188 OPT_SET_UINT(0, "no-merge", &stat_config.aggr_mode,
1189 "disable aggregation the same as -A or -no-aggr", AGGR_NONE),
1190 OPT_BOOLEAN(0, "hybrid-merge", &stat_config.hybrid_merge,
1191 "Merge identical named hybrid events"),
1192 OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
1193 "print counts with custom separator"),
1194 OPT_BOOLEAN('j', "json-output", &stat_config.json_output,
1195 "print counts in JSON format"),
1196 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1197 "monitor event in cgroup name only", parse_stat_cgroups),
1198 OPT_STRING(0, "for-each-cgroup", &stat_config.cgroup_list, "name",
1199 "expand events for each cgroup"),
1200 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1201 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1202 OPT_INTEGER(0, "log-fd", &output_fd,
1203 "log output to fd, instead of stderr"),
1204 OPT_STRING(0, "pre", &pre_cmd, "command",
1205 "command to run prior to the measured command"),
1206 OPT_STRING(0, "post", &post_cmd, "command",
1207 "command to run after to the measured command"),
1208 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1209 "print counts at regular interval in ms "
1210 "(overhead is possible for values <= 100ms)"),
1211 OPT_INTEGER(0, "interval-count", &stat_config.times,
1212 "print counts for fixed number of times"),
1213 OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
1214 "clear screen in between new interval"),
1215 OPT_UINTEGER(0, "timeout", &stat_config.timeout,
1216 "stop workload and print counts after a timeout period in ms (>= 10ms)"),
1217 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1218 "aggregate counts per processor socket", AGGR_SOCKET),
1219 OPT_SET_UINT(0, "per-die", &stat_config.aggr_mode,
1220 "aggregate counts per processor die", AGGR_DIE),
1221 OPT_SET_UINT(0, "per-cluster", &stat_config.aggr_mode,
1222 "aggregate counts per processor cluster", AGGR_CLUSTER),
1223 OPT_CALLBACK_OPTARG(0, "per-cache", &stat_config.aggr_mode, &stat_config.aggr_level,
1224 "cache level", "aggregate count at this cache level (Default: LLC)",
1226 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1227 "aggregate counts per physical processor core", AGGR_CORE),
1228 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1229 "aggregate counts per thread", AGGR_THREAD),
1230 OPT_SET_UINT(0, "per-node", &stat_config.aggr_mode,
1231 "aggregate counts per numa node", AGGR_NODE),
1232 OPT_INTEGER('D', "delay", &target.initial_delay,
1233 "ms to wait before starting measurement after program start (-1: start with events disabled)"),
1234 OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
1235 "Only print computed metrics. No raw values", enable_metric_only),
1236 OPT_BOOLEAN(0, "metric-no-group", &stat_config.metric_no_group,
1237 "don't group metric events, impacts multiplexing"),
1238 OPT_BOOLEAN(0, "metric-no-merge", &stat_config.metric_no_merge,
1239 "don't try to share events between metrics in a group"),
1240 OPT_BOOLEAN(0, "metric-no-threshold", &stat_config.metric_no_threshold,
1241 "disable adding events for the metric threshold calculation"),
1242 OPT_BOOLEAN(0, "topdown", &topdown_run,
1243 "measure top-down statistics"),
1244 OPT_UINTEGER(0, "td-level", &stat_config.topdown_level,
1245 "Set the metrics level for the top-down statistics (0: max level)"),
1246 OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1247 "measure SMI cost"),
1248 OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1249 "monitor specified metrics or metric groups (separated by ,)",
1250 append_metric_groups),
1251 OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
1252 "Configure all used events to run in kernel space.",
1253 PARSE_OPT_EXCLUSIVE),
1254 OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
1255 "Configure all used events to run in user space.",
1256 PARSE_OPT_EXCLUSIVE),
1257 OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
1258 "Use with 'percore' event qualifier to show the event "
1259 "counts of one hardware thread by sum up total hardware "
1260 "threads of same physical core"),
1261 OPT_BOOLEAN(0, "summary", &stat_config.summary,
1262 "print summary for interval mode"),
1263 OPT_BOOLEAN(0, "no-csv-summary", &stat_config.no_csv_summary,
1264 "don't print 'summary' for CSV summary output"),
1265 OPT_BOOLEAN(0, "quiet", &quiet,
1266 "don't print any output, messages or warnings (useful with record)"),
1267 OPT_CALLBACK(0, "cputype", &evsel_list, "hybrid cpu type",
1268 "Only enable events on applying cpu with this type "
1269 "for hybrid platform (e.g. core or atom)",
1272 OPT_CALLBACK(0, "pfm-events", &evsel_list, "event",
1273 "libpfm4 event selector. use 'perf list' to list available events",
1274 parse_libpfm_events_option),
1276 OPT_CALLBACK(0, "control", &stat_config, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]",
1277 "Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events).\n"
1278 "\t\t\t Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n"
1279 "\t\t\t Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.",
1280 parse_control_option),
1281 OPT_CALLBACK_OPTARG(0, "iostat", &evsel_list, &stat_config, "default",
1282 "measure I/O performance metrics provided by arch/platform",
1288 * Calculate the cache instance ID from the map in
1289 * /sys/devices/system/cpu/cpuX/cache/indexY/shared_cpu_list
1290 * Cache instance ID is the first CPU reported in the shared_cpu_list file.
1292 static int cpu__get_cache_id_from_map(struct perf_cpu cpu, char *map)
1295 struct perf_cpu_map *cpu_map = perf_cpu_map__new(map);
1298 * If the map contains no CPU, consider the current CPU to
1299 * be the first online CPU in the cache domain else use the
1300 * first online CPU of the cache domain as the ID.
1302 id = perf_cpu_map__min(cpu_map).cpu;
1306 /* Free the perf_cpu_map used to find the cache ID */
1307 perf_cpu_map__put(cpu_map);
1313 * cpu__get_cache_id - Returns 0 if successful in populating the
1314 * cache level and cache id. Cache level is read from
1315 * /sys/devices/system/cpu/cpuX/cache/indexY/level where as cache instance ID
1316 * is the first CPU reported by
1317 * /sys/devices/system/cpu/cpuX/cache/indexY/shared_cpu_list
1319 static int cpu__get_cache_details(struct perf_cpu cpu, struct perf_cache *cache)
1322 u32 cache_level = stat_config.aggr_level;
1323 struct cpu_cache_level caches[MAX_CACHE_LVL];
1324 u32 i = 0, caches_cnt = 0;
1326 cache->cache_lvl = (cache_level > MAX_CACHE_LVL) ? 0 : cache_level;
1329 ret = build_caches_for_cpu(cpu.cpu, caches, &caches_cnt);
1332 * If caches_cnt is not 0, cpu_cache_level data
1333 * was allocated when building the topology.
1334 * Free the allocated data before returning.
1346 * Save the data for the highest level if no
1347 * level was specified by the user.
1349 if (cache_level > MAX_CACHE_LVL) {
1350 int max_level_index = 0;
1352 for (i = 1; i < caches_cnt; ++i) {
1353 if (caches[i].level > caches[max_level_index].level)
1354 max_level_index = i;
1357 cache->cache_lvl = caches[max_level_index].level;
1358 cache->cache = cpu__get_cache_id_from_map(cpu, caches[max_level_index].map);
1360 /* Reset i to 0 to free entire caches[] */
1365 for (i = 0; i < caches_cnt; ++i) {
1366 if (caches[i].level == cache_level) {
1367 cache->cache_lvl = cache_level;
1368 cache->cache = cpu__get_cache_id_from_map(cpu, caches[i].map);
1371 cpu_cache_level__free(&caches[i]);
1376 * Free all the allocated cpu_cache_level data.
1378 while (i < caches_cnt)
1379 cpu_cache_level__free(&caches[i++]);
1385 * aggr_cpu_id__cache - Create an aggr_cpu_id with cache instache ID, cache
1386 * level, die and socket populated with the cache instache ID, cache level,
1387 * die and socket for cpu. The function signature is compatible with
1388 * aggr_cpu_id_get_t.
1390 static struct aggr_cpu_id aggr_cpu_id__cache(struct perf_cpu cpu, void *data)
1393 struct aggr_cpu_id id;
1394 struct perf_cache cache;
1396 id = aggr_cpu_id__die(cpu, data);
1397 if (aggr_cpu_id__is_empty(&id))
1400 ret = cpu__get_cache_details(cpu, &cache);
1404 id.cache_lvl = cache.cache_lvl;
1405 id.cache = cache.cache;
1409 static const char *const aggr_mode__string[] = {
1410 [AGGR_CORE] = "core",
1411 [AGGR_CACHE] = "cache",
1412 [AGGR_CLUSTER] = "cluster",
1414 [AGGR_GLOBAL] = "global",
1415 [AGGR_NODE] = "node",
1416 [AGGR_NONE] = "none",
1417 [AGGR_SOCKET] = "socket",
1418 [AGGR_THREAD] = "thread",
1419 [AGGR_UNSET] = "unset",
1422 static struct aggr_cpu_id perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
1423 struct perf_cpu cpu)
1425 return aggr_cpu_id__socket(cpu, /*data=*/NULL);
1428 static struct aggr_cpu_id perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
1429 struct perf_cpu cpu)
1431 return aggr_cpu_id__die(cpu, /*data=*/NULL);
1434 static struct aggr_cpu_id perf_stat__get_cache_id(struct perf_stat_config *config __maybe_unused,
1435 struct perf_cpu cpu)
1437 return aggr_cpu_id__cache(cpu, /*data=*/NULL);
1440 static struct aggr_cpu_id perf_stat__get_cluster(struct perf_stat_config *config __maybe_unused,
1441 struct perf_cpu cpu)
1443 return aggr_cpu_id__cluster(cpu, /*data=*/NULL);
1446 static struct aggr_cpu_id perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
1447 struct perf_cpu cpu)
1449 return aggr_cpu_id__core(cpu, /*data=*/NULL);
1452 static struct aggr_cpu_id perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
1453 struct perf_cpu cpu)
1455 return aggr_cpu_id__node(cpu, /*data=*/NULL);
1458 static struct aggr_cpu_id perf_stat__get_global(struct perf_stat_config *config __maybe_unused,
1459 struct perf_cpu cpu)
1461 return aggr_cpu_id__global(cpu, /*data=*/NULL);
1464 static struct aggr_cpu_id perf_stat__get_cpu(struct perf_stat_config *config __maybe_unused,
1465 struct perf_cpu cpu)
1467 return aggr_cpu_id__cpu(cpu, /*data=*/NULL);
1470 static struct aggr_cpu_id perf_stat__get_aggr(struct perf_stat_config *config,
1471 aggr_get_id_t get_id, struct perf_cpu cpu)
1473 struct aggr_cpu_id id;
1475 /* per-process mode - should use global aggr mode */
1477 return get_id(config, cpu);
1479 if (aggr_cpu_id__is_empty(&config->cpus_aggr_map->map[cpu.cpu]))
1480 config->cpus_aggr_map->map[cpu.cpu] = get_id(config, cpu);
1482 id = config->cpus_aggr_map->map[cpu.cpu];
1486 static struct aggr_cpu_id perf_stat__get_socket_cached(struct perf_stat_config *config,
1487 struct perf_cpu cpu)
1489 return perf_stat__get_aggr(config, perf_stat__get_socket, cpu);
1492 static struct aggr_cpu_id perf_stat__get_die_cached(struct perf_stat_config *config,
1493 struct perf_cpu cpu)
1495 return perf_stat__get_aggr(config, perf_stat__get_die, cpu);
1498 static struct aggr_cpu_id perf_stat__get_cluster_cached(struct perf_stat_config *config,
1499 struct perf_cpu cpu)
1501 return perf_stat__get_aggr(config, perf_stat__get_cluster, cpu);
1504 static struct aggr_cpu_id perf_stat__get_cache_id_cached(struct perf_stat_config *config,
1505 struct perf_cpu cpu)
1507 return perf_stat__get_aggr(config, perf_stat__get_cache_id, cpu);
1510 static struct aggr_cpu_id perf_stat__get_core_cached(struct perf_stat_config *config,
1511 struct perf_cpu cpu)
1513 return perf_stat__get_aggr(config, perf_stat__get_core, cpu);
1516 static struct aggr_cpu_id perf_stat__get_node_cached(struct perf_stat_config *config,
1517 struct perf_cpu cpu)
1519 return perf_stat__get_aggr(config, perf_stat__get_node, cpu);
1522 static struct aggr_cpu_id perf_stat__get_global_cached(struct perf_stat_config *config,
1523 struct perf_cpu cpu)
1525 return perf_stat__get_aggr(config, perf_stat__get_global, cpu);
1528 static struct aggr_cpu_id perf_stat__get_cpu_cached(struct perf_stat_config *config,
1529 struct perf_cpu cpu)
1531 return perf_stat__get_aggr(config, perf_stat__get_cpu, cpu);
1534 static aggr_cpu_id_get_t aggr_mode__get_aggr(enum aggr_mode aggr_mode)
1536 switch (aggr_mode) {
1538 return aggr_cpu_id__socket;
1540 return aggr_cpu_id__die;
1542 return aggr_cpu_id__cluster;
1544 return aggr_cpu_id__cache;
1546 return aggr_cpu_id__core;
1548 return aggr_cpu_id__node;
1550 return aggr_cpu_id__cpu;
1552 return aggr_cpu_id__global;
1561 static aggr_get_id_t aggr_mode__get_id(enum aggr_mode aggr_mode)
1563 switch (aggr_mode) {
1565 return perf_stat__get_socket_cached;
1567 return perf_stat__get_die_cached;
1569 return perf_stat__get_cluster_cached;
1571 return perf_stat__get_cache_id_cached;
1573 return perf_stat__get_core_cached;
1575 return perf_stat__get_node_cached;
1577 return perf_stat__get_cpu_cached;
1579 return perf_stat__get_global_cached;
1588 static int perf_stat_init_aggr_mode(void)
1591 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr(stat_config.aggr_mode);
1594 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1595 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1596 get_id, /*data=*/NULL, needs_sort);
1597 if (!stat_config.aggr_map) {
1598 pr_err("cannot build %s map\n", aggr_mode__string[stat_config.aggr_mode]);
1601 stat_config.aggr_get_id = aggr_mode__get_id(stat_config.aggr_mode);
1604 if (stat_config.aggr_mode == AGGR_THREAD) {
1605 nr = perf_thread_map__nr(evsel_list->core.threads);
1606 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1607 if (stat_config.aggr_map == NULL)
1610 for (int s = 0; s < nr; s++) {
1611 struct aggr_cpu_id id = aggr_cpu_id__empty();
1614 stat_config.aggr_map->map[s] = id;
1620 * The evsel_list->cpus is the base we operate on,
1621 * taking the highest cpu number to be the size of
1622 * the aggregation translate cpumap.
1624 if (!perf_cpu_map__is_any_cpu_or_is_empty(evsel_list->core.user_requested_cpus))
1625 nr = perf_cpu_map__max(evsel_list->core.user_requested_cpus).cpu;
1628 stat_config.cpus_aggr_map = cpu_aggr_map__empty_new(nr + 1);
1629 return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
1632 static void cpu_aggr_map__delete(struct cpu_aggr_map *map)
1637 static void perf_stat__exit_aggr_mode(void)
1639 cpu_aggr_map__delete(stat_config.aggr_map);
1640 cpu_aggr_map__delete(stat_config.cpus_aggr_map);
1641 stat_config.aggr_map = NULL;
1642 stat_config.cpus_aggr_map = NULL;
1645 static struct aggr_cpu_id perf_env__get_socket_aggr_by_cpu(struct perf_cpu cpu, void *data)
1647 struct perf_env *env = data;
1648 struct aggr_cpu_id id = aggr_cpu_id__empty();
1651 id.socket = env->cpu[cpu.cpu].socket_id;
1656 static struct aggr_cpu_id perf_env__get_die_aggr_by_cpu(struct perf_cpu cpu, void *data)
1658 struct perf_env *env = data;
1659 struct aggr_cpu_id id = aggr_cpu_id__empty();
1661 if (cpu.cpu != -1) {
1663 * die_id is relative to socket, so start
1664 * with the socket ID and then add die to
1667 id.socket = env->cpu[cpu.cpu].socket_id;
1668 id.die = env->cpu[cpu.cpu].die_id;
1674 static void perf_env__get_cache_id_for_cpu(struct perf_cpu cpu, struct perf_env *env,
1675 u32 cache_level, struct aggr_cpu_id *id)
1678 int caches_cnt = env->caches_cnt;
1679 struct cpu_cache_level *caches = env->caches;
1681 id->cache_lvl = (cache_level > MAX_CACHE_LVL) ? 0 : cache_level;
1687 for (i = caches_cnt - 1; i > -1; --i) {
1688 struct perf_cpu_map *cpu_map;
1689 int map_contains_cpu;
1692 * If user has not specified a level, find the fist level with
1693 * the cpu in the map. Since building the map is expensive, do
1694 * this only if levels match.
1696 if (cache_level <= MAX_CACHE_LVL && caches[i].level != cache_level)
1699 cpu_map = perf_cpu_map__new(caches[i].map);
1700 map_contains_cpu = perf_cpu_map__idx(cpu_map, cpu);
1701 perf_cpu_map__put(cpu_map);
1703 if (map_contains_cpu != -1) {
1704 id->cache_lvl = caches[i].level;
1705 id->cache = cpu__get_cache_id_from_map(cpu, caches[i].map);
1711 static struct aggr_cpu_id perf_env__get_cache_aggr_by_cpu(struct perf_cpu cpu,
1714 struct perf_env *env = data;
1715 struct aggr_cpu_id id = aggr_cpu_id__empty();
1717 if (cpu.cpu != -1) {
1718 u32 cache_level = (perf_stat.aggr_level) ?: stat_config.aggr_level;
1720 id.socket = env->cpu[cpu.cpu].socket_id;
1721 id.die = env->cpu[cpu.cpu].die_id;
1722 perf_env__get_cache_id_for_cpu(cpu, env, cache_level, &id);
1728 static struct aggr_cpu_id perf_env__get_cluster_aggr_by_cpu(struct perf_cpu cpu,
1731 struct perf_env *env = data;
1732 struct aggr_cpu_id id = aggr_cpu_id__empty();
1734 if (cpu.cpu != -1) {
1735 id.socket = env->cpu[cpu.cpu].socket_id;
1736 id.die = env->cpu[cpu.cpu].die_id;
1737 id.cluster = env->cpu[cpu.cpu].cluster_id;
1743 static struct aggr_cpu_id perf_env__get_core_aggr_by_cpu(struct perf_cpu cpu, void *data)
1745 struct perf_env *env = data;
1746 struct aggr_cpu_id id = aggr_cpu_id__empty();
1748 if (cpu.cpu != -1) {
1750 * core_id is relative to socket, die and cluster, we need a
1751 * global id. So we set socket, die id, cluster id and core id.
1753 id.socket = env->cpu[cpu.cpu].socket_id;
1754 id.die = env->cpu[cpu.cpu].die_id;
1755 id.cluster = env->cpu[cpu.cpu].cluster_id;
1756 id.core = env->cpu[cpu.cpu].core_id;
1762 static struct aggr_cpu_id perf_env__get_cpu_aggr_by_cpu(struct perf_cpu cpu, void *data)
1764 struct perf_env *env = data;
1765 struct aggr_cpu_id id = aggr_cpu_id__empty();
1767 if (cpu.cpu != -1) {
1769 * core_id is relative to socket and die,
1770 * we need a global id. So we set
1771 * socket, die id and core id
1773 id.socket = env->cpu[cpu.cpu].socket_id;
1774 id.die = env->cpu[cpu.cpu].die_id;
1775 id.core = env->cpu[cpu.cpu].core_id;
1782 static struct aggr_cpu_id perf_env__get_node_aggr_by_cpu(struct perf_cpu cpu, void *data)
1784 struct aggr_cpu_id id = aggr_cpu_id__empty();
1786 id.node = perf_env__numa_node(data, cpu);
1790 static struct aggr_cpu_id perf_env__get_global_aggr_by_cpu(struct perf_cpu cpu __maybe_unused,
1791 void *data __maybe_unused)
1793 struct aggr_cpu_id id = aggr_cpu_id__empty();
1795 /* it always aggregates to the cpu 0 */
1796 id.cpu = (struct perf_cpu){ .cpu = 0 };
1800 static struct aggr_cpu_id perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
1801 struct perf_cpu cpu)
1803 return perf_env__get_socket_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1805 static struct aggr_cpu_id perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
1806 struct perf_cpu cpu)
1808 return perf_env__get_die_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1811 static struct aggr_cpu_id perf_stat__get_cluster_file(struct perf_stat_config *config __maybe_unused,
1812 struct perf_cpu cpu)
1814 return perf_env__get_cluster_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1817 static struct aggr_cpu_id perf_stat__get_cache_file(struct perf_stat_config *config __maybe_unused,
1818 struct perf_cpu cpu)
1820 return perf_env__get_cache_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1823 static struct aggr_cpu_id perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
1824 struct perf_cpu cpu)
1826 return perf_env__get_core_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1829 static struct aggr_cpu_id perf_stat__get_cpu_file(struct perf_stat_config *config __maybe_unused,
1830 struct perf_cpu cpu)
1832 return perf_env__get_cpu_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1835 static struct aggr_cpu_id perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
1836 struct perf_cpu cpu)
1838 return perf_env__get_node_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1841 static struct aggr_cpu_id perf_stat__get_global_file(struct perf_stat_config *config __maybe_unused,
1842 struct perf_cpu cpu)
1844 return perf_env__get_global_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1847 static aggr_cpu_id_get_t aggr_mode__get_aggr_file(enum aggr_mode aggr_mode)
1849 switch (aggr_mode) {
1851 return perf_env__get_socket_aggr_by_cpu;
1853 return perf_env__get_die_aggr_by_cpu;
1855 return perf_env__get_cluster_aggr_by_cpu;
1857 return perf_env__get_cache_aggr_by_cpu;
1859 return perf_env__get_core_aggr_by_cpu;
1861 return perf_env__get_node_aggr_by_cpu;
1863 return perf_env__get_global_aggr_by_cpu;
1865 return perf_env__get_cpu_aggr_by_cpu;
1874 static aggr_get_id_t aggr_mode__get_id_file(enum aggr_mode aggr_mode)
1876 switch (aggr_mode) {
1878 return perf_stat__get_socket_file;
1880 return perf_stat__get_die_file;
1882 return perf_stat__get_cluster_file;
1884 return perf_stat__get_cache_file;
1886 return perf_stat__get_core_file;
1888 return perf_stat__get_node_file;
1890 return perf_stat__get_global_file;
1892 return perf_stat__get_cpu_file;
1901 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1903 struct perf_env *env = &st->session->header.env;
1904 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr_file(stat_config.aggr_mode);
1905 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1907 if (stat_config.aggr_mode == AGGR_THREAD) {
1908 int nr = perf_thread_map__nr(evsel_list->core.threads);
1910 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1911 if (stat_config.aggr_map == NULL)
1914 for (int s = 0; s < nr; s++) {
1915 struct aggr_cpu_id id = aggr_cpu_id__empty();
1918 stat_config.aggr_map->map[s] = id;
1926 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1927 get_id, env, needs_sort);
1928 if (!stat_config.aggr_map) {
1929 pr_err("cannot build %s map\n", aggr_mode__string[stat_config.aggr_mode]);
1932 stat_config.aggr_get_id = aggr_mode__get_id_file(stat_config.aggr_mode);
1937 * Add default attributes, if there were no attributes specified or
1938 * if -d/--detailed, -d -d or -d -d -d is used:
1940 static int add_default_attributes(void)
1942 struct perf_event_attr default_attrs0[] = {
1944 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
1945 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
1946 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
1947 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
1949 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
1951 struct perf_event_attr frontend_attrs[] = {
1952 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1954 struct perf_event_attr backend_attrs[] = {
1955 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
1957 struct perf_event_attr default_attrs1[] = {
1958 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
1959 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
1960 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
1965 * Detailed stats (-d), covering the L1 and last level data caches:
1967 struct perf_event_attr detailed_attrs[] = {
1969 { .type = PERF_TYPE_HW_CACHE,
1971 PERF_COUNT_HW_CACHE_L1D << 0 |
1972 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1973 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1975 { .type = PERF_TYPE_HW_CACHE,
1977 PERF_COUNT_HW_CACHE_L1D << 0 |
1978 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1979 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1981 { .type = PERF_TYPE_HW_CACHE,
1983 PERF_COUNT_HW_CACHE_LL << 0 |
1984 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1985 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1987 { .type = PERF_TYPE_HW_CACHE,
1989 PERF_COUNT_HW_CACHE_LL << 0 |
1990 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1991 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1995 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1997 struct perf_event_attr very_detailed_attrs[] = {
1999 { .type = PERF_TYPE_HW_CACHE,
2001 PERF_COUNT_HW_CACHE_L1I << 0 |
2002 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2003 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2005 { .type = PERF_TYPE_HW_CACHE,
2007 PERF_COUNT_HW_CACHE_L1I << 0 |
2008 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2009 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2011 { .type = PERF_TYPE_HW_CACHE,
2013 PERF_COUNT_HW_CACHE_DTLB << 0 |
2014 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2015 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2017 { .type = PERF_TYPE_HW_CACHE,
2019 PERF_COUNT_HW_CACHE_DTLB << 0 |
2020 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2021 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2023 { .type = PERF_TYPE_HW_CACHE,
2025 PERF_COUNT_HW_CACHE_ITLB << 0 |
2026 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2027 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2029 { .type = PERF_TYPE_HW_CACHE,
2031 PERF_COUNT_HW_CACHE_ITLB << 0 |
2032 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2033 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2038 * Very, very detailed stats (-d -d -d), adding prefetch events:
2040 struct perf_event_attr very_very_detailed_attrs[] = {
2042 { .type = PERF_TYPE_HW_CACHE,
2044 PERF_COUNT_HW_CACHE_L1D << 0 |
2045 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2046 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2048 { .type = PERF_TYPE_HW_CACHE,
2050 PERF_COUNT_HW_CACHE_L1D << 0 |
2051 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2052 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2055 struct perf_event_attr default_null_attrs[] = {};
2056 const char *pmu = parse_events_option_args.pmu_filter ?: "all";
2058 /* Set attrs if no event is selected and !null_run: */
2059 if (stat_config.null_run)
2062 if (transaction_run) {
2063 /* Handle -T as -M transaction. Once platform specific metrics
2064 * support has been added to the json files, all architectures
2065 * will use this approach. To determine transaction support
2066 * on an architecture test for such a metric name.
2068 if (!metricgroup__has_metric(pmu, "transaction")) {
2069 pr_err("Missing transaction metrics\n");
2072 return metricgroup__parse_groups(evsel_list, pmu, "transaction",
2073 stat_config.metric_no_group,
2074 stat_config.metric_no_merge,
2075 stat_config.metric_no_threshold,
2076 stat_config.user_requested_cpu_list,
2077 stat_config.system_wide,
2078 stat_config.hardware_aware_grouping,
2079 &stat_config.metric_events);
2085 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
2086 pr_err("freeze_on_smi is not supported.\n");
2091 if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
2092 fprintf(stderr, "Failed to set freeze_on_smi.\n");
2098 if (!metricgroup__has_metric(pmu, "smi")) {
2099 pr_err("Missing smi metrics\n");
2103 if (!force_metric_only)
2104 stat_config.metric_only = true;
2106 return metricgroup__parse_groups(evsel_list, pmu, "smi",
2107 stat_config.metric_no_group,
2108 stat_config.metric_no_merge,
2109 stat_config.metric_no_threshold,
2110 stat_config.user_requested_cpu_list,
2111 stat_config.system_wide,
2112 stat_config.hardware_aware_grouping,
2113 &stat_config.metric_events);
2117 unsigned int max_level = metricgroups__topdown_max_level();
2118 char str[] = "TopdownL1";
2120 if (!force_metric_only)
2121 stat_config.metric_only = true;
2124 pr_err("Topdown requested but the topdown metric groups aren't present.\n"
2125 "(See perf list the metric groups have names like TopdownL1)\n");
2128 if (stat_config.topdown_level > max_level) {
2129 pr_err("Invalid top-down metrics level. The max level is %u.\n", max_level);
2131 } else if (!stat_config.topdown_level)
2132 stat_config.topdown_level = 1;
2134 if (!stat_config.interval && !stat_config.metric_only) {
2135 fprintf(stat_config.output,
2136 "Topdown accuracy may decrease when measuring long periods.\n"
2137 "Please print the result regularly, e.g. -I1000\n");
2139 str[8] = stat_config.topdown_level + '0';
2140 if (metricgroup__parse_groups(evsel_list,
2142 /*metric_no_group=*/false,
2143 /*metric_no_merge=*/false,
2144 /*metric_no_threshold=*/true,
2145 stat_config.user_requested_cpu_list,
2146 stat_config.system_wide,
2147 stat_config.hardware_aware_grouping,
2148 &stat_config.metric_events) < 0)
2152 if (!stat_config.topdown_level)
2153 stat_config.topdown_level = 1;
2155 if (!evsel_list->core.nr_entries) {
2156 /* No events so add defaults. */
2157 if (target__has_cpu(&target))
2158 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2160 if (evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2162 if (perf_pmus__have_event("cpu", "stalled-cycles-frontend")) {
2163 if (evlist__add_default_attrs(evsel_list, frontend_attrs) < 0)
2166 if (perf_pmus__have_event("cpu", "stalled-cycles-backend")) {
2167 if (evlist__add_default_attrs(evsel_list, backend_attrs) < 0)
2170 if (evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2173 * Add TopdownL1 metrics if they exist. To minimize
2174 * multiplexing, don't request threshold computation.
2176 if (metricgroup__has_metric(pmu, "Default")) {
2177 struct evlist *metric_evlist = evlist__new();
2178 struct evsel *metric_evsel;
2183 if (metricgroup__parse_groups(metric_evlist, pmu, "Default",
2184 /*metric_no_group=*/false,
2185 /*metric_no_merge=*/false,
2186 /*metric_no_threshold=*/true,
2187 stat_config.user_requested_cpu_list,
2188 stat_config.system_wide,
2189 stat_config.hardware_aware_grouping,
2190 &stat_config.metric_events) < 0)
2193 evlist__for_each_entry(metric_evlist, metric_evsel) {
2194 metric_evsel->skippable = true;
2195 metric_evsel->default_metricgroup = true;
2197 evlist__splice_list_tail(evsel_list, &metric_evlist->core.entries);
2198 evlist__delete(metric_evlist);
2201 /* Platform specific attrs */
2202 if (evlist__add_default_attrs(evsel_list, default_null_attrs) < 0)
2206 /* Detailed events get appended to the event list: */
2208 if (detailed_run < 1)
2211 /* Append detailed run extra attributes: */
2212 if (evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2215 if (detailed_run < 2)
2218 /* Append very detailed run extra attributes: */
2219 if (evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2222 if (detailed_run < 3)
2225 /* Append very, very detailed run extra attributes: */
2226 return evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2229 static const char * const stat_record_usage[] = {
2230 "perf stat record [<options>]",
2234 static void init_features(struct perf_session *session)
2238 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2239 perf_header__set_feat(&session->header, feat);
2241 perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
2242 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2243 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2244 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2245 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2248 static int __cmd_record(int argc, const char **argv)
2250 struct perf_session *session;
2251 struct perf_data *data = &perf_stat.data;
2253 argc = parse_options(argc, argv, stat_options, stat_record_usage,
2254 PARSE_OPT_STOP_AT_NON_OPTION);
2257 data->path = output_name;
2259 if (stat_config.run_count != 1 || forever) {
2260 pr_err("Cannot use -r option with perf stat record.\n");
2264 session = perf_session__new(data, NULL);
2265 if (IS_ERR(session)) {
2266 pr_err("Perf session creation failed\n");
2267 return PTR_ERR(session);
2270 init_features(session);
2272 session->evlist = evsel_list;
2273 perf_stat.session = session;
2274 perf_stat.record = true;
2278 static int process_stat_round_event(struct perf_session *session,
2279 union perf_event *event)
2281 struct perf_record_stat_round *stat_round = &event->stat_round;
2282 struct timespec tsh, *ts = NULL;
2283 const char **argv = session->header.env.cmdline_argv;
2284 int argc = session->header.env.nr_cmdline;
2288 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2289 update_stats(&walltime_nsecs_stats, stat_round->time);
2291 if (stat_config.interval && stat_round->time) {
2292 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2293 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2297 print_counters(ts, argc, argv);
2302 int process_stat_config_event(struct perf_session *session,
2303 union perf_event *event)
2305 struct perf_tool *tool = session->tool;
2306 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2308 perf_event__read_stat_config(&stat_config, &event->stat_config);
2310 if (perf_cpu_map__is_empty(st->cpus)) {
2311 if (st->aggr_mode != AGGR_UNSET)
2312 pr_warning("warning: processing task data, aggregation mode not set\n");
2313 } else if (st->aggr_mode != AGGR_UNSET) {
2314 stat_config.aggr_mode = st->aggr_mode;
2317 if (perf_stat.data.is_pipe)
2318 perf_stat_init_aggr_mode();
2320 perf_stat_init_aggr_mode_file(st);
2322 if (stat_config.aggr_map) {
2323 int nr_aggr = stat_config.aggr_map->nr;
2325 if (evlist__alloc_aggr_stats(session->evlist, nr_aggr) < 0) {
2326 pr_err("cannot allocate aggr counts\n");
2333 static int set_maps(struct perf_stat *st)
2335 if (!st->cpus || !st->threads)
2338 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2341 perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
2343 if (evlist__alloc_stats(&stat_config, evsel_list, /*alloc_raw=*/true))
2346 st->maps_allocated = true;
2351 int process_thread_map_event(struct perf_session *session,
2352 union perf_event *event)
2354 struct perf_tool *tool = session->tool;
2355 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2358 pr_warning("Extra thread map event, ignoring.\n");
2362 st->threads = thread_map__new_event(&event->thread_map);
2366 return set_maps(st);
2370 int process_cpu_map_event(struct perf_session *session,
2371 union perf_event *event)
2373 struct perf_tool *tool = session->tool;
2374 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2375 struct perf_cpu_map *cpus;
2378 pr_warning("Extra cpu map event, ignoring.\n");
2382 cpus = cpu_map__new_data(&event->cpu_map.data);
2387 return set_maps(st);
2390 static const char * const stat_report_usage[] = {
2391 "perf stat report [<options>]",
2395 static struct perf_stat perf_stat = {
2397 .attr = perf_event__process_attr,
2398 .event_update = perf_event__process_event_update,
2399 .thread_map = process_thread_map_event,
2400 .cpu_map = process_cpu_map_event,
2401 .stat_config = process_stat_config_event,
2402 .stat = perf_event__process_stat_event,
2403 .stat_round = process_stat_round_event,
2405 .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-die", &perf_stat.aggr_mode,
2417 "aggregate counts per processor die", AGGR_DIE),
2418 OPT_SET_UINT(0, "per-cluster", &perf_stat.aggr_mode,
2419 "aggregate counts perf processor cluster", AGGR_CLUSTER),
2420 OPT_CALLBACK_OPTARG(0, "per-cache", &perf_stat.aggr_mode, &perf_stat.aggr_level,
2422 "aggregate count at this cache level (Default: LLC)",
2424 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2425 "aggregate counts per physical processor core", AGGR_CORE),
2426 OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
2427 "aggregate counts per numa node", AGGR_NODE),
2428 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2429 "disable CPU count aggregation", AGGR_NONE),
2435 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2437 if (!input_name || !strlen(input_name)) {
2438 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2441 input_name = "perf.data";
2444 perf_stat.data.path = input_name;
2445 perf_stat.data.mode = PERF_DATA_MODE_READ;
2447 session = perf_session__new(&perf_stat.data, &perf_stat.tool);
2448 if (IS_ERR(session))
2449 return PTR_ERR(session);
2451 perf_stat.session = session;
2452 stat_config.output = stderr;
2453 evlist__delete(evsel_list);
2454 evsel_list = session->evlist;
2456 ret = perf_session__process_events(session);
2460 perf_session__delete(session);
2464 static void setup_system_wide(int forks)
2467 * Make system wide (-a) the default target if
2468 * no target was specified and one of following
2469 * conditions is met:
2471 * - there's no workload specified
2472 * - there is workload specified but all requested
2473 * events are system wide events
2475 if (!target__none(&target))
2479 target.system_wide = true;
2481 struct evsel *counter;
2483 evlist__for_each_entry(evsel_list, counter) {
2484 if (!counter->core.requires_cpu &&
2485 !evsel__name_is(counter, "duration_time")) {
2490 if (evsel_list->core.nr_entries)
2491 target.system_wide = true;
2495 int cmd_stat(int argc, const char **argv)
2497 const char * const stat_usage[] = {
2498 "perf stat [<options>] [<command>]",
2501 int status = -EINVAL, run_idx, err;
2503 FILE *output = stderr;
2504 unsigned int interval, timeout;
2505 const char * const stat_subcommands[] = { "record", "report" };
2506 char errbuf[BUFSIZ];
2508 setlocale(LC_ALL, "");
2510 evsel_list = evlist__new();
2511 if (evsel_list == NULL)
2514 parse_events__shrink_config_terms();
2516 /* String-parsing callback-based options would segfault when negated */
2517 set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
2518 set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
2519 set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
2521 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2522 (const char **) stat_usage,
2523 PARSE_OPT_STOP_AT_NON_OPTION);
2525 if (stat_config.csv_sep) {
2526 stat_config.csv_output = true;
2527 if (!strcmp(stat_config.csv_sep, "\\t"))
2528 stat_config.csv_sep = "\t";
2530 stat_config.csv_sep = DEFAULT_SEPARATOR;
2532 if (argc && strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
2533 argc = __cmd_record(argc, argv);
2536 } else if (argc && strlen(argv[0]) > 2 && strstarts("report", argv[0]))
2537 return __cmd_report(argc, argv);
2539 interval = stat_config.interval;
2540 timeout = stat_config.timeout;
2543 * For record command the -o is already taken care of.
2545 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2548 if (output_name && output_fd) {
2549 fprintf(stderr, "cannot use both --output and --log-fd\n");
2550 parse_options_usage(stat_usage, stat_options, "o", 1);
2551 parse_options_usage(NULL, stat_options, "log-fd", 0);
2555 if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2556 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2560 if (stat_config.metric_only && stat_config.run_count > 1) {
2561 fprintf(stderr, "--metric-only is not supported with -r\n");
2565 if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
2566 fprintf(stderr, "--table is only supported with -r\n");
2567 parse_options_usage(stat_usage, stat_options, "r", 1);
2568 parse_options_usage(NULL, stat_options, "table", 0);
2572 if (output_fd < 0) {
2573 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2574 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2578 if (!output && !quiet) {
2580 mode = append_file ? "a" : "w";
2582 output = fopen(output_name, mode);
2584 perror("failed to create output file");
2587 if (!stat_config.json_output) {
2588 clock_gettime(CLOCK_REALTIME, &tm);
2589 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2591 } else if (output_fd > 0) {
2592 mode = append_file ? "a" : "w";
2593 output = fdopen(output_fd, mode);
2595 perror("Failed opening logfd");
2600 if (stat_config.interval_clear && !isatty(fileno(output))) {
2601 fprintf(stderr, "--interval-clear does not work with output\n");
2602 parse_options_usage(stat_usage, stat_options, "o", 1);
2603 parse_options_usage(NULL, stat_options, "log-fd", 0);
2604 parse_options_usage(NULL, stat_options, "interval-clear", 0);
2608 stat_config.output = output;
2611 * let the spreadsheet do the pretty-printing
2613 if (stat_config.csv_output) {
2614 /* User explicitly passed -B? */
2615 if (big_num_opt == 1) {
2616 fprintf(stderr, "-B option not supported with -x\n");
2617 parse_options_usage(stat_usage, stat_options, "B", 1);
2618 parse_options_usage(NULL, stat_options, "x", 1);
2620 } else /* Nope, so disable big number formatting */
2621 stat_config.big_num = false;
2622 } else if (big_num_opt == 0) /* User passed --no-big-num */
2623 stat_config.big_num = false;
2625 err = target__validate(&target);
2627 target__strerror(&target, err, errbuf, BUFSIZ);
2628 pr_warning("%s\n", errbuf);
2631 setup_system_wide(argc);
2634 * Display user/system times only for single
2635 * run and when there's specified tracee.
2637 if ((stat_config.run_count == 1) && target__none(&target))
2638 stat_config.ru_display = true;
2640 if (stat_config.run_count < 0) {
2641 pr_err("Run count must be a positive number\n");
2642 parse_options_usage(stat_usage, stat_options, "r", 1);
2644 } else if (stat_config.run_count == 0) {
2646 stat_config.run_count = 1;
2649 if (stat_config.walltime_run_table) {
2650 stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
2651 if (!stat_config.walltime_run) {
2652 pr_err("failed to setup -r option");
2657 if ((stat_config.aggr_mode == AGGR_THREAD) &&
2658 !target__has_task(&target)) {
2659 if (!target.system_wide || target.cpu_list) {
2660 fprintf(stderr, "The --per-thread option is only "
2661 "available when monitoring via -p -t -a "
2662 "options or only --per-thread.\n");
2663 parse_options_usage(NULL, stat_options, "p", 1);
2664 parse_options_usage(NULL, stat_options, "t", 1);
2670 * no_aggr, cgroup are for system-wide only
2671 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2673 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2674 stat_config.aggr_mode != AGGR_THREAD) ||
2675 (nr_cgroups || stat_config.cgroup_list)) &&
2676 !target__has_cpu(&target)) {
2677 fprintf(stderr, "both cgroup and no-aggregation "
2678 "modes only available in system-wide mode\n");
2680 parse_options_usage(stat_usage, stat_options, "G", 1);
2681 parse_options_usage(NULL, stat_options, "A", 1);
2682 parse_options_usage(NULL, stat_options, "a", 1);
2683 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2687 if (stat_config.iostat_run) {
2688 status = iostat_prepare(evsel_list, &stat_config);
2691 if (iostat_mode == IOSTAT_LIST) {
2692 iostat_list(evsel_list, &stat_config);
2694 } else if (verbose > 0)
2695 iostat_list(evsel_list, &stat_config);
2696 if (iostat_mode == IOSTAT_RUN && !target__has_cpu(&target))
2697 target.system_wide = true;
2700 if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2701 target.per_thread = true;
2703 stat_config.system_wide = target.system_wide;
2704 if (target.cpu_list) {
2705 stat_config.user_requested_cpu_list = strdup(target.cpu_list);
2706 if (!stat_config.user_requested_cpu_list) {
2713 * Metric parsing needs to be delayed as metrics may optimize events
2714 * knowing the target is system-wide.
2717 const char *pmu = parse_events_option_args.pmu_filter ?: "all";
2718 int ret = metricgroup__parse_groups(evsel_list, pmu, metrics,
2719 stat_config.metric_no_group,
2720 stat_config.metric_no_merge,
2721 stat_config.metric_no_threshold,
2722 stat_config.user_requested_cpu_list,
2723 stat_config.system_wide,
2724 stat_config.hardware_aware_grouping,
2725 &stat_config.metric_events);
2734 if (add_default_attributes())
2737 if (stat_config.cgroup_list) {
2738 if (nr_cgroups > 0) {
2739 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
2740 parse_options_usage(stat_usage, stat_options, "G", 1);
2741 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2745 if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list,
2746 &stat_config.metric_events, true) < 0) {
2747 parse_options_usage(stat_usage, stat_options,
2748 "for-each-cgroup", 0);
2753 evlist__warn_user_requested_cpus(evsel_list, target.cpu_list);
2755 if (evlist__create_maps(evsel_list, &target) < 0) {
2756 if (target__has_task(&target)) {
2757 pr_err("Problems finding threads of monitor\n");
2758 parse_options_usage(stat_usage, stat_options, "p", 1);
2759 parse_options_usage(NULL, stat_options, "t", 1);
2760 } else if (target__has_cpu(&target)) {
2761 perror("failed to parse CPUs map");
2762 parse_options_usage(stat_usage, stat_options, "C", 1);
2763 parse_options_usage(NULL, stat_options, "a", 1);
2768 evlist__check_cpu_maps(evsel_list);
2771 * Initialize thread_map with comm names,
2772 * so we could print it out on output.
2774 if (stat_config.aggr_mode == AGGR_THREAD) {
2775 thread_map__read_comms(evsel_list->core.threads);
2778 if (stat_config.aggr_mode == AGGR_NODE)
2779 cpu__setup_cpunode_map();
2781 if (stat_config.times && interval)
2782 interval_count = true;
2783 else if (stat_config.times && !interval) {
2784 pr_err("interval-count option should be used together with "
2785 "interval-print.\n");
2786 parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2787 parse_options_usage(stat_usage, stat_options, "I", 1);
2791 if (timeout && timeout < 100) {
2793 pr_err("timeout must be >= 10ms.\n");
2794 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2797 pr_warning("timeout < 100ms. "
2798 "The overhead percentage could be high in some cases. "
2799 "Please proceed with caution.\n");
2801 if (timeout && interval) {
2802 pr_err("timeout option is not supported with interval-print.\n");
2803 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2804 parse_options_usage(stat_usage, stat_options, "I", 1);
2808 if (perf_stat_init_aggr_mode())
2811 if (evlist__alloc_stats(&stat_config, evsel_list, interval))
2815 * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2816 * while avoiding that older tools show confusing messages.
2818 * However for pipe sessions we need to keep it zero,
2819 * because script's perf_evsel__check_attr is triggered
2820 * by attr->sample_type != 0, and we can't run it on
2823 stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2826 * We dont want to block the signals - that would cause
2827 * child tasks to inherit that and Ctrl-C would not work.
2828 * What we want is for Ctrl-C to work in the exec()-ed
2829 * task, but being ignored by perf stat itself:
2833 signal(SIGINT, skip_signal);
2834 signal(SIGCHLD, skip_signal);
2835 signal(SIGALRM, skip_signal);
2836 signal(SIGABRT, skip_signal);
2838 if (evlist__initialize_ctlfd(evsel_list, stat_config.ctl_fd, stat_config.ctl_fd_ack))
2841 /* Enable ignoring missing threads when -p option is defined. */
2842 evlist__first(evsel_list)->ignore_missing_thread = target.pid;
2844 for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
2845 if (stat_config.run_count != 1 && verbose > 0)
2846 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2850 evlist__reset_prev_raw_counts(evsel_list);
2852 status = run_perf_stat(argc, argv, run_idx);
2853 if (forever && status != -1 && !interval) {
2854 print_counters(NULL, argc, argv);
2855 perf_stat__reset_stats();
2859 if (!forever && status != -1 && (!interval || stat_config.summary)) {
2860 if (stat_config.run_count > 1)
2861 evlist__copy_res_stats(&stat_config, evsel_list);
2862 print_counters(NULL, argc, argv);
2865 evlist__finalize_ctlfd(evsel_list);
2869 * We synthesize the kernel mmap record just so that older tools
2870 * don't emit warnings about not being able to resolve symbols
2871 * due to /proc/sys/kernel/kptr_restrict settings and instead provide
2872 * a saner message about no samples being in the perf.data file.
2874 * This also serves to suppress a warning about f_header.data.size == 0
2875 * in header.c at the moment 'perf stat record' gets introduced, which
2876 * is not really needed once we start adding the stat specific PERF_RECORD_
2877 * records, but the need to suppress the kptr_restrict messages in older
2878 * tools remain -acme
2880 int fd = perf_data__fd(&perf_stat.data);
2882 err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2883 process_synthesized_event,
2884 &perf_stat.session->machines.host);
2886 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2887 "older tools may produce warnings about this file\n.");
2891 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2892 pr_err("failed to write stat round event\n");
2895 if (!perf_stat.data.is_pipe) {
2896 perf_stat.session->header.data_size += perf_stat.bytes_written;
2897 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2900 evlist__close(evsel_list);
2901 perf_session__delete(perf_stat.session);
2904 perf_stat__exit_aggr_mode();
2905 evlist__free_stats(evsel_list);
2907 if (stat_config.iostat_run)
2908 iostat_release(evsel_list);
2910 zfree(&stat_config.walltime_run);
2911 zfree(&stat_config.user_requested_cpu_list);
2913 if (smi_cost && smi_reset)
2914 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2916 evlist__delete(evsel_list);
2918 metricgroup__rblist_exit(&stat_config.metric_events);
2919 evlist__close_control(stat_config.ctl_fd, stat_config.ctl_fd_ack, &stat_config.ctl_fd_close);