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"
48 #include "util/event.h"
49 #include "util/evlist.h"
50 #include "util/evlist-hybrid.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/pmu-hybrid.h"
73 #include "util/util.h"
76 #include <linux/time64.h>
77 #include <linux/zalloc.h>
78 #include <api/fs/fs.h>
82 #include <sys/prctl.h>
86 #include <sys/types.h>
91 #include <sys/resource.h>
92 #include <linux/err.h>
94 #include <linux/ctype.h>
95 #include <perf/evlist.h>
96 #include <internal/threadmap.h>
98 #define DEFAULT_SEPARATOR " "
99 #define FREEZE_ON_SMI_PATH "devices/cpu/freeze_on_smi"
101 static void print_counters(struct timespec *ts, int argc, const char **argv);
103 static struct evlist *evsel_list;
104 static bool all_counters_use_bpf = true;
106 static struct target target = {
110 #define METRIC_ONLY_LEN 20
112 static volatile sig_atomic_t child_pid = -1;
113 static int detailed_run = 0;
114 static bool transaction_run;
115 static bool topdown_run = false;
116 static bool smi_cost = false;
117 static bool smi_reset = false;
118 static int big_num_opt = -1;
119 static const char *pre_cmd = NULL;
120 static const char *post_cmd = NULL;
121 static bool sync_run = false;
122 static bool forever = false;
123 static bool force_metric_only = false;
124 static struct timespec ref_time;
125 static bool append_file;
126 static bool interval_count;
127 static const char *output_name;
128 static int output_fd;
129 static char *metrics;
133 struct perf_data data;
134 struct perf_session *session;
136 struct perf_tool tool;
138 struct perf_cpu_map *cpus;
139 struct perf_thread_map *threads;
140 enum aggr_mode aggr_mode;
143 static struct perf_stat perf_stat;
144 #define STAT_RECORD perf_stat.record
146 static volatile sig_atomic_t done = 0;
148 static struct perf_stat_config stat_config = {
149 .aggr_mode = AGGR_GLOBAL,
151 .unit_width = 4, /* strlen("unit") */
153 .metric_only_len = METRIC_ONLY_LEN,
154 .walltime_nsecs_stats = &walltime_nsecs_stats,
155 .ru_stats = &ru_stats,
162 static bool cpus_map_matched(struct evsel *a, struct evsel *b)
164 if (!a->core.cpus && !b->core.cpus)
167 if (!a->core.cpus || !b->core.cpus)
170 if (perf_cpu_map__nr(a->core.cpus) != perf_cpu_map__nr(b->core.cpus))
173 for (int i = 0; i < perf_cpu_map__nr(a->core.cpus); i++) {
174 if (perf_cpu_map__cpu(a->core.cpus, i).cpu !=
175 perf_cpu_map__cpu(b->core.cpus, i).cpu)
182 static void evlist__check_cpu_maps(struct evlist *evlist)
184 struct evsel *evsel, *warned_leader = NULL;
186 if (evlist__has_hybrid(evlist))
187 evlist__warn_hybrid_group(evlist);
189 evlist__for_each_entry(evlist, evsel) {
190 struct evsel *leader = evsel__leader(evsel);
192 /* Check that leader matches cpus with each member. */
195 if (cpus_map_matched(leader, evsel))
198 /* If there's mismatch disable the group and warn user. */
199 if (warned_leader != leader) {
202 pr_warning("WARNING: grouped events cpus do not match.\n"
203 "Events with CPUs not matching the leader will "
204 "be removed from the group.\n");
205 evsel__group_desc(leader, buf, sizeof(buf));
206 pr_warning(" %s\n", buf);
207 warned_leader = leader;
212 cpu_map__snprint(leader->core.cpus, buf, sizeof(buf));
213 pr_warning(" %s: %s\n", leader->name, buf);
214 cpu_map__snprint(evsel->core.cpus, buf, sizeof(buf));
215 pr_warning(" %s: %s\n", evsel->name, buf);
218 evsel__remove_from_group(evsel, leader);
222 static inline void diff_timespec(struct timespec *r, struct timespec *a,
225 r->tv_sec = a->tv_sec - b->tv_sec;
226 if (a->tv_nsec < b->tv_nsec) {
227 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
230 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
234 static void perf_stat__reset_stats(void)
236 evlist__reset_stats(evsel_list);
237 perf_stat__reset_shadow_stats();
240 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
241 union perf_event *event,
242 struct perf_sample *sample __maybe_unused,
243 struct machine *machine __maybe_unused)
245 if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
246 pr_err("failed to write perf data, error: %m\n");
250 perf_stat.bytes_written += event->header.size;
254 static int write_stat_round_event(u64 tm, u64 type)
256 return perf_event__synthesize_stat_round(NULL, tm, type,
257 process_synthesized_event,
261 #define WRITE_STAT_ROUND_EVENT(time, interval) \
262 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
264 #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
266 static int evsel__write_stat_event(struct evsel *counter, int cpu_map_idx, u32 thread,
267 struct perf_counts_values *count)
269 struct perf_sample_id *sid = SID(counter, cpu_map_idx, thread);
270 struct perf_cpu cpu = perf_cpu_map__cpu(evsel__cpus(counter), cpu_map_idx);
272 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
273 process_synthesized_event, NULL);
276 static int read_single_counter(struct evsel *counter, int cpu_map_idx,
277 int thread, struct timespec *rs)
279 switch(counter->tool_event) {
280 case PERF_TOOL_DURATION_TIME: {
281 u64 val = rs->tv_nsec + rs->tv_sec*1000000000ULL;
282 struct perf_counts_values *count =
283 perf_counts(counter->counts, cpu_map_idx, thread);
284 count->ena = count->run = val;
288 case PERF_TOOL_USER_TIME:
289 case PERF_TOOL_SYSTEM_TIME: {
291 struct perf_counts_values *count =
292 perf_counts(counter->counts, cpu_map_idx, thread);
293 if (counter->tool_event == PERF_TOOL_USER_TIME)
294 val = ru_stats.ru_utime_usec_stat.mean;
296 val = ru_stats.ru_stime_usec_stat.mean;
297 count->ena = count->run = val;
303 return evsel__read_counter(counter, cpu_map_idx, thread);
305 /* This should never be reached */
311 * Read out the results of a single counter:
312 * do not aggregate counts across CPUs in system-wide mode
314 static int read_counter_cpu(struct evsel *counter, struct timespec *rs, int cpu_map_idx)
316 int nthreads = perf_thread_map__nr(evsel_list->core.threads);
319 if (!counter->supported)
322 for (thread = 0; thread < nthreads; thread++) {
323 struct perf_counts_values *count;
325 count = perf_counts(counter->counts, cpu_map_idx, thread);
328 * The leader's group read loads data into its group members
329 * (via evsel__read_counter()) and sets their count->loaded.
331 if (!perf_counts__is_loaded(counter->counts, cpu_map_idx, thread) &&
332 read_single_counter(counter, cpu_map_idx, thread, rs)) {
333 counter->counts->scaled = -1;
334 perf_counts(counter->counts, cpu_map_idx, thread)->ena = 0;
335 perf_counts(counter->counts, cpu_map_idx, thread)->run = 0;
339 perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, false);
342 if (evsel__write_stat_event(counter, cpu_map_idx, thread, count)) {
343 pr_err("failed to write stat event\n");
349 fprintf(stat_config.output,
350 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
351 evsel__name(counter),
352 perf_cpu_map__cpu(evsel__cpus(counter),
354 count->val, count->ena, count->run);
361 static int read_affinity_counters(struct timespec *rs)
363 struct evlist_cpu_iterator evlist_cpu_itr;
364 struct affinity saved_affinity, *affinity;
366 if (all_counters_use_bpf)
369 if (!target__has_cpu(&target) || target__has_per_thread(&target))
371 else if (affinity__setup(&saved_affinity) < 0)
374 affinity = &saved_affinity;
376 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
377 struct evsel *counter = evlist_cpu_itr.evsel;
379 if (evsel__is_bpf(counter))
383 counter->err = read_counter_cpu(counter, rs,
384 evlist_cpu_itr.cpu_map_idx);
388 affinity__cleanup(&saved_affinity);
393 static int read_bpf_map_counters(void)
395 struct evsel *counter;
398 evlist__for_each_entry(evsel_list, counter) {
399 if (!evsel__is_bpf(counter))
402 err = bpf_counter__read(counter);
409 static int read_counters(struct timespec *rs)
411 if (!stat_config.stop_read_counter) {
412 if (read_bpf_map_counters() ||
413 read_affinity_counters(rs))
419 static void process_counters(void)
421 struct evsel *counter;
423 evlist__for_each_entry(evsel_list, counter) {
425 pr_debug("failed to read counter %s\n", counter->name);
426 if (counter->err == 0 && perf_stat_process_counter(&stat_config, counter))
427 pr_warning("failed to process counter %s\n", counter->name);
431 perf_stat_merge_counters(&stat_config, evsel_list);
432 perf_stat_process_percore(&stat_config, evsel_list);
435 static void process_interval(void)
437 struct timespec ts, rs;
439 clock_gettime(CLOCK_MONOTONIC, &ts);
440 diff_timespec(&rs, &ts, &ref_time);
442 evlist__reset_aggr_stats(evsel_list);
444 if (read_counters(&rs) == 0)
448 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
449 pr_err("failed to write stat round event\n");
452 init_stats(&walltime_nsecs_stats);
453 update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000ULL);
454 print_counters(&rs, 0, NULL);
457 static bool handle_interval(unsigned int interval, int *times)
461 if (interval_count && !(--(*times)))
467 static int enable_counters(void)
472 evlist__for_each_entry(evsel_list, evsel) {
473 if (!evsel__is_bpf(evsel))
476 err = bpf_counter__enable(evsel);
481 if (!target__enable_on_exec(&target)) {
482 if (!all_counters_use_bpf)
483 evlist__enable(evsel_list);
488 static void disable_counters(void)
490 struct evsel *counter;
493 * If we don't have tracee (attaching to task or cpu), counters may
494 * still be running. To get accurate group ratios, we must stop groups
495 * from counting before reading their constituent counters.
497 if (!target__none(&target)) {
498 evlist__for_each_entry(evsel_list, counter)
499 bpf_counter__disable(counter);
500 if (!all_counters_use_bpf)
501 evlist__disable(evsel_list);
505 static volatile sig_atomic_t workload_exec_errno;
508 * evlist__prepare_workload will send a SIGUSR1
509 * if the fork fails, since we asked by setting its
510 * want_signal to true.
512 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
513 void *ucontext __maybe_unused)
515 workload_exec_errno = info->si_value.sival_int;
518 static bool evsel__should_store_id(struct evsel *counter)
520 return STAT_RECORD || counter->core.attr.read_format & PERF_FORMAT_ID;
523 static bool is_target_alive(struct target *_target,
524 struct perf_thread_map *threads)
529 if (!target__has_task(_target))
532 for (i = 0; i < threads->nr; i++) {
535 scnprintf(path, PATH_MAX, "%s/%d", procfs__mountpoint(),
536 threads->map[i].pid);
538 if (!stat(path, &st))
545 static void process_evlist(struct evlist *evlist, unsigned int interval)
547 enum evlist_ctl_cmd cmd = EVLIST_CTL_CMD_UNSUPPORTED;
549 if (evlist__ctlfd_process(evlist, &cmd) > 0) {
551 case EVLIST_CTL_CMD_ENABLE:
553 case EVLIST_CTL_CMD_DISABLE:
557 case EVLIST_CTL_CMD_SNAPSHOT:
558 case EVLIST_CTL_CMD_ACK:
559 case EVLIST_CTL_CMD_UNSUPPORTED:
560 case EVLIST_CTL_CMD_EVLIST:
561 case EVLIST_CTL_CMD_STOP:
562 case EVLIST_CTL_CMD_PING:
569 static void compute_tts(struct timespec *time_start, struct timespec *time_stop,
572 int tts = *time_to_sleep;
573 struct timespec time_diff;
575 diff_timespec(&time_diff, time_stop, time_start);
577 tts -= time_diff.tv_sec * MSEC_PER_SEC +
578 time_diff.tv_nsec / NSEC_PER_MSEC;
583 *time_to_sleep = tts;
586 static int dispatch_events(bool forks, int timeout, int interval, int *times)
588 int child_exited = 0, status = 0;
589 int time_to_sleep, sleep_time;
590 struct timespec time_start, time_stop;
593 sleep_time = interval;
595 sleep_time = timeout;
599 time_to_sleep = sleep_time;
603 child_exited = waitpid(child_pid, &status, WNOHANG);
605 child_exited = !is_target_alive(&target, evsel_list->core.threads) ? 1 : 0;
610 clock_gettime(CLOCK_MONOTONIC, &time_start);
611 if (!(evlist__poll(evsel_list, time_to_sleep) > 0)) { /* poll timeout or EINTR */
612 if (timeout || handle_interval(interval, times))
614 time_to_sleep = sleep_time;
615 } else { /* fd revent */
616 process_evlist(evsel_list, interval);
617 clock_gettime(CLOCK_MONOTONIC, &time_stop);
618 compute_tts(&time_start, &time_stop, &time_to_sleep);
625 enum counter_recovery {
631 static enum counter_recovery stat_handle_error(struct evsel *counter)
635 * PPC returns ENXIO for HW counters until 2.6.37
636 * (behavior changed with commit b0a873e).
638 if (errno == EINVAL || errno == ENOSYS ||
639 errno == ENOENT || errno == EOPNOTSUPP ||
642 ui__warning("%s event is not supported by the kernel.\n",
643 evsel__name(counter));
644 counter->supported = false;
646 * errored is a sticky flag that means one of the counter's
647 * cpu event had a problem and needs to be reexamined.
649 counter->errored = true;
651 if ((evsel__leader(counter) != counter) ||
652 !(counter->core.leader->nr_members > 1))
654 } else if (evsel__fallback(counter, errno, msg, sizeof(msg))) {
656 ui__warning("%s\n", msg);
657 return COUNTER_RETRY;
658 } else if (target__has_per_thread(&target) &&
659 evsel_list->core.threads &&
660 evsel_list->core.threads->err_thread != -1) {
662 * For global --per-thread case, skip current
665 if (!thread_map__remove(evsel_list->core.threads,
666 evsel_list->core.threads->err_thread)) {
667 evsel_list->core.threads->err_thread = -1;
668 return COUNTER_RETRY;
672 evsel__open_strerror(counter, &target, errno, msg, sizeof(msg));
673 ui__error("%s\n", msg);
676 kill(child_pid, SIGTERM);
677 return COUNTER_FATAL;
680 static int __run_perf_stat(int argc, const char **argv, int run_idx)
682 int interval = stat_config.interval;
683 int times = stat_config.times;
684 int timeout = stat_config.timeout;
686 unsigned long long t0, t1;
687 struct evsel *counter;
690 const bool forks = (argc > 0);
691 bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
692 struct evlist_cpu_iterator evlist_cpu_itr;
693 struct affinity saved_affinity, *affinity = NULL;
695 bool second_pass = false;
698 if (evlist__prepare_workload(evsel_list, &target, argv, is_pipe, workload_exec_failed_signal) < 0) {
699 perror("failed to prepare workload");
702 child_pid = evsel_list->workload.pid;
705 if (!cpu_map__is_dummy(evsel_list->core.user_requested_cpus)) {
706 if (affinity__setup(&saved_affinity) < 0)
708 affinity = &saved_affinity;
711 evlist__for_each_entry(evsel_list, counter) {
712 counter->reset_group = false;
713 if (bpf_counter__load(counter, &target))
715 if (!(evsel__is_bperf(counter)))
716 all_counters_use_bpf = false;
719 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
720 counter = evlist_cpu_itr.evsel;
723 * bperf calls evsel__open_per_cpu() in bperf__load(), so
724 * no need to call it again here.
729 if (counter->reset_group || counter->errored)
731 if (evsel__is_bperf(counter))
734 if (create_perf_stat_counter(counter, &stat_config, &target,
735 evlist_cpu_itr.cpu_map_idx) < 0) {
738 * Weak group failed. We cannot just undo this here
739 * because earlier CPUs might be in group mode, and the kernel
740 * doesn't support mixing group and non group reads. Defer
742 * Don't close here because we're in the wrong affinity.
744 if ((errno == EINVAL || errno == EBADF) &&
745 evsel__leader(counter) != counter &&
746 counter->weak_group) {
747 evlist__reset_weak_group(evsel_list, counter, false);
748 assert(counter->reset_group);
753 switch (stat_handle_error(counter)) {
765 counter->supported = true;
770 * Now redo all the weak group after closing them,
771 * and also close errored counters.
774 /* First close errored or weak retry */
775 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
776 counter = evlist_cpu_itr.evsel;
778 if (!counter->reset_group && !counter->errored)
781 perf_evsel__close_cpu(&counter->core, evlist_cpu_itr.cpu_map_idx);
783 /* Now reopen weak */
784 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
785 counter = evlist_cpu_itr.evsel;
787 if (!counter->reset_group)
790 pr_debug2("reopening weak %s\n", evsel__name(counter));
791 if (create_perf_stat_counter(counter, &stat_config, &target,
792 evlist_cpu_itr.cpu_map_idx) < 0) {
794 switch (stat_handle_error(counter)) {
798 goto try_again_reset;
805 counter->supported = true;
808 affinity__cleanup(affinity);
810 evlist__for_each_entry(evsel_list, counter) {
811 if (!counter->supported) {
812 perf_evsel__free_fd(&counter->core);
816 l = strlen(counter->unit);
817 if (l > stat_config.unit_width)
818 stat_config.unit_width = l;
820 if (evsel__should_store_id(counter) &&
821 evsel__store_ids(counter, evsel_list))
825 if (evlist__apply_filters(evsel_list, &counter)) {
826 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
827 counter->filter, evsel__name(counter), errno,
828 str_error_r(errno, msg, sizeof(msg)));
833 int fd = perf_data__fd(&perf_stat.data);
836 err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
838 err = perf_session__write_header(perf_stat.session, evsel_list,
845 err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
846 process_synthesized_event, is_pipe);
851 if (target.initial_delay) {
852 pr_info(EVLIST_DISABLED_MSG);
854 err = enable_counters();
859 /* Exec the command, if any */
861 evlist__start_workload(evsel_list);
863 if (target.initial_delay > 0) {
864 usleep(target.initial_delay * USEC_PER_MSEC);
865 err = enable_counters();
869 pr_info(EVLIST_ENABLED_MSG);
873 clock_gettime(CLOCK_MONOTONIC, &ref_time);
876 if (interval || timeout || evlist__ctlfd_initialized(evsel_list))
877 status = dispatch_events(forks, timeout, interval, ×);
878 if (child_pid != -1) {
880 kill(child_pid, SIGTERM);
881 wait4(child_pid, &status, 0, &stat_config.ru_data);
884 if (workload_exec_errno) {
885 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
886 pr_err("Workload failed: %s\n", emsg);
890 if (WIFSIGNALED(status))
891 psignal(WTERMSIG(status), argv[0]);
893 status = dispatch_events(forks, timeout, interval, ×);
900 if (stat_config.walltime_run_table)
901 stat_config.walltime_run[run_idx] = t1 - t0;
903 if (interval && stat_config.summary) {
904 stat_config.interval = 0;
905 stat_config.stop_read_counter = true;
906 init_stats(&walltime_nsecs_stats);
907 update_stats(&walltime_nsecs_stats, t1 - t0);
909 evlist__copy_prev_raw_counts(evsel_list);
910 evlist__reset_prev_raw_counts(evsel_list);
911 evlist__reset_aggr_stats(evsel_list);
913 update_stats(&walltime_nsecs_stats, t1 - t0);
914 update_rusage_stats(&ru_stats, &stat_config.ru_data);
918 * Closing a group leader splits the group, and as we only disable
919 * group leaders, results in remaining events becoming enabled. To
920 * avoid arbitrary skew, we must read all counters before closing any
923 if (read_counters(&(struct timespec) { .tv_nsec = t1-t0 }) == 0)
927 * We need to keep evsel_list alive, because it's processed
928 * later the evsel_list will be closed after.
931 evlist__close(evsel_list);
933 return WEXITSTATUS(status);
936 static int run_perf_stat(int argc, const char **argv, int run_idx)
941 ret = system(pre_cmd);
949 ret = __run_perf_stat(argc, argv, run_idx);
954 ret = system(post_cmd);
962 static void print_counters(struct timespec *ts, int argc, const char **argv)
964 /* Do not print anything if we record to the pipe. */
965 if (STAT_RECORD && perf_stat.data.is_pipe)
970 evlist__print_counters(evsel_list, &stat_config, &target, ts, argc, argv);
973 static volatile sig_atomic_t signr = -1;
975 static void skip_signal(int signo)
977 if ((child_pid == -1) || stat_config.interval)
982 * render child_pid harmless
983 * won't send SIGTERM to a random
984 * process in case of race condition
985 * and fast PID recycling
990 static void sig_atexit(void)
995 * avoid race condition with SIGCHLD handler
996 * in skip_signal() which is modifying child_pid
997 * goal is to avoid send SIGTERM to a random
1001 sigaddset(&set, SIGCHLD);
1002 sigprocmask(SIG_BLOCK, &set, &oset);
1004 if (child_pid != -1)
1005 kill(child_pid, SIGTERM);
1007 sigprocmask(SIG_SETMASK, &oset, NULL);
1012 signal(signr, SIG_DFL);
1013 kill(getpid(), signr);
1016 void perf_stat__set_big_num(int set)
1018 stat_config.big_num = (set != 0);
1021 void perf_stat__set_no_csv_summary(int set)
1023 stat_config.no_csv_summary = (set != 0);
1026 static int stat__set_big_num(const struct option *opt __maybe_unused,
1027 const char *s __maybe_unused, int unset)
1029 big_num_opt = unset ? 0 : 1;
1030 perf_stat__set_big_num(!unset);
1034 static int enable_metric_only(const struct option *opt __maybe_unused,
1035 const char *s __maybe_unused, int unset)
1037 force_metric_only = true;
1038 stat_config.metric_only = !unset;
1042 static int append_metric_groups(const struct option *opt __maybe_unused,
1044 int unset __maybe_unused)
1049 if (asprintf(&tmp, "%s,%s", metrics, str) < 0)
1054 metrics = strdup(str);
1061 static int parse_control_option(const struct option *opt,
1063 int unset __maybe_unused)
1065 struct perf_stat_config *config = opt->value;
1067 return evlist__parse_control(str, &config->ctl_fd, &config->ctl_fd_ack, &config->ctl_fd_close);
1070 static int parse_stat_cgroups(const struct option *opt,
1071 const char *str, int unset)
1073 if (stat_config.cgroup_list) {
1074 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
1078 return parse_cgroups(opt, str, unset);
1081 static int parse_hybrid_type(const struct option *opt,
1083 int unset __maybe_unused)
1085 struct evlist *evlist = *(struct evlist **)opt->value;
1087 if (!list_empty(&evlist->core.entries)) {
1088 fprintf(stderr, "Must define cputype before events/metrics\n");
1092 evlist->hybrid_pmu_name = perf_pmu__hybrid_type_to_pmu(str);
1093 if (!evlist->hybrid_pmu_name) {
1094 fprintf(stderr, "--cputype %s is not supported!\n", str);
1101 static struct option stat_options[] = {
1102 OPT_BOOLEAN('T', "transaction", &transaction_run,
1103 "hardware transaction statistics"),
1104 OPT_CALLBACK('e', "event", &evsel_list, "event",
1105 "event selector. use 'perf list' to list available events",
1106 parse_events_option),
1107 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1108 "event filter", parse_filter),
1109 OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
1110 "child tasks do not inherit counters"),
1111 OPT_STRING('p', "pid", &target.pid, "pid",
1112 "stat events on existing process id"),
1113 OPT_STRING('t', "tid", &target.tid, "tid",
1114 "stat events on existing thread id"),
1115 #ifdef HAVE_BPF_SKEL
1116 OPT_STRING('b', "bpf-prog", &target.bpf_str, "bpf-prog-id",
1117 "stat events on existing bpf program id"),
1118 OPT_BOOLEAN(0, "bpf-counters", &target.use_bpf,
1119 "use bpf program to count events"),
1120 OPT_STRING(0, "bpf-attr-map", &target.attr_map, "attr-map-path",
1121 "path to perf_event_attr map"),
1123 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1124 "system-wide collection from all CPUs"),
1125 OPT_BOOLEAN(0, "scale", &stat_config.scale,
1126 "Use --no-scale to disable counter scaling for multiplexing"),
1127 OPT_INCR('v', "verbose", &verbose,
1128 "be more verbose (show counter open errors, etc)"),
1129 OPT_INTEGER('r', "repeat", &stat_config.run_count,
1130 "repeat command and print average + stddev (max: 100, forever: 0)"),
1131 OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
1132 "display details about each run (only with -r option)"),
1133 OPT_BOOLEAN('n', "null", &stat_config.null_run,
1134 "null run - dont start any counters"),
1135 OPT_INCR('d', "detailed", &detailed_run,
1136 "detailed run - start a lot of events"),
1137 OPT_BOOLEAN('S', "sync", &sync_run,
1138 "call sync() before starting a run"),
1139 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1140 "print large numbers with thousands\' separators",
1142 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1143 "list of cpus to monitor in system-wide"),
1144 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1145 "disable CPU count aggregation", AGGR_NONE),
1146 OPT_BOOLEAN(0, "no-merge", &stat_config.no_merge, "Do not merge identical named events"),
1147 OPT_BOOLEAN(0, "hybrid-merge", &stat_config.hybrid_merge,
1148 "Merge identical named hybrid events"),
1149 OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
1150 "print counts with custom separator"),
1151 OPT_BOOLEAN('j', "json-output", &stat_config.json_output,
1152 "print counts in JSON format"),
1153 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1154 "monitor event in cgroup name only", parse_stat_cgroups),
1155 OPT_STRING(0, "for-each-cgroup", &stat_config.cgroup_list, "name",
1156 "expand events for each cgroup"),
1157 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1158 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1159 OPT_INTEGER(0, "log-fd", &output_fd,
1160 "log output to fd, instead of stderr"),
1161 OPT_STRING(0, "pre", &pre_cmd, "command",
1162 "command to run prior to the measured command"),
1163 OPT_STRING(0, "post", &post_cmd, "command",
1164 "command to run after to the measured command"),
1165 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1166 "print counts at regular interval in ms "
1167 "(overhead is possible for values <= 100ms)"),
1168 OPT_INTEGER(0, "interval-count", &stat_config.times,
1169 "print counts for fixed number of times"),
1170 OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
1171 "clear screen in between new interval"),
1172 OPT_UINTEGER(0, "timeout", &stat_config.timeout,
1173 "stop workload and print counts after a timeout period in ms (>= 10ms)"),
1174 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1175 "aggregate counts per processor socket", AGGR_SOCKET),
1176 OPT_SET_UINT(0, "per-die", &stat_config.aggr_mode,
1177 "aggregate counts per processor die", AGGR_DIE),
1178 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1179 "aggregate counts per physical processor core", AGGR_CORE),
1180 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1181 "aggregate counts per thread", AGGR_THREAD),
1182 OPT_SET_UINT(0, "per-node", &stat_config.aggr_mode,
1183 "aggregate counts per numa node", AGGR_NODE),
1184 OPT_INTEGER('D', "delay", &target.initial_delay,
1185 "ms to wait before starting measurement after program start (-1: start with events disabled)"),
1186 OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
1187 "Only print computed metrics. No raw values", enable_metric_only),
1188 OPT_BOOLEAN(0, "metric-no-group", &stat_config.metric_no_group,
1189 "don't group metric events, impacts multiplexing"),
1190 OPT_BOOLEAN(0, "metric-no-merge", &stat_config.metric_no_merge,
1191 "don't try to share events between metrics in a group"),
1192 OPT_BOOLEAN(0, "metric-no-threshold", &stat_config.metric_no_threshold,
1193 "don't try to share events between metrics in a group "),
1194 OPT_BOOLEAN(0, "topdown", &topdown_run,
1195 "measure top-down statistics"),
1196 OPT_UINTEGER(0, "td-level", &stat_config.topdown_level,
1197 "Set the metrics level for the top-down statistics (0: max level)"),
1198 OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1199 "measure SMI cost"),
1200 OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1201 "monitor specified metrics or metric groups (separated by ,)",
1202 append_metric_groups),
1203 OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
1204 "Configure all used events to run in kernel space.",
1205 PARSE_OPT_EXCLUSIVE),
1206 OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
1207 "Configure all used events to run in user space.",
1208 PARSE_OPT_EXCLUSIVE),
1209 OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
1210 "Use with 'percore' event qualifier to show the event "
1211 "counts of one hardware thread by sum up total hardware "
1212 "threads of same physical core"),
1213 OPT_BOOLEAN(0, "summary", &stat_config.summary,
1214 "print summary for interval mode"),
1215 OPT_BOOLEAN(0, "no-csv-summary", &stat_config.no_csv_summary,
1216 "don't print 'summary' for CSV summary output"),
1217 OPT_BOOLEAN(0, "quiet", &quiet,
1218 "don't print any output, messages or warnings (useful with record)"),
1219 OPT_CALLBACK(0, "cputype", &evsel_list, "hybrid cpu type",
1220 "Only enable events on applying cpu with this type "
1221 "for hybrid platform (e.g. core or atom)",
1224 OPT_CALLBACK(0, "pfm-events", &evsel_list, "event",
1225 "libpfm4 event selector. use 'perf list' to list available events",
1226 parse_libpfm_events_option),
1228 OPT_CALLBACK(0, "control", &stat_config, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]",
1229 "Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events).\n"
1230 "\t\t\t Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n"
1231 "\t\t\t Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.",
1232 parse_control_option),
1233 OPT_CALLBACK_OPTARG(0, "iostat", &evsel_list, &stat_config, "default",
1234 "measure I/O performance metrics provided by arch/platform",
1239 static const char *const aggr_mode__string[] = {
1240 [AGGR_CORE] = "core",
1242 [AGGR_GLOBAL] = "global",
1243 [AGGR_NODE] = "node",
1244 [AGGR_NONE] = "none",
1245 [AGGR_SOCKET] = "socket",
1246 [AGGR_THREAD] = "thread",
1247 [AGGR_UNSET] = "unset",
1250 static struct aggr_cpu_id perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
1251 struct perf_cpu cpu)
1253 return aggr_cpu_id__socket(cpu, /*data=*/NULL);
1256 static struct aggr_cpu_id perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
1257 struct perf_cpu cpu)
1259 return aggr_cpu_id__die(cpu, /*data=*/NULL);
1262 static struct aggr_cpu_id perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
1263 struct perf_cpu cpu)
1265 return aggr_cpu_id__core(cpu, /*data=*/NULL);
1268 static struct aggr_cpu_id perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
1269 struct perf_cpu cpu)
1271 return aggr_cpu_id__node(cpu, /*data=*/NULL);
1274 static struct aggr_cpu_id perf_stat__get_global(struct perf_stat_config *config __maybe_unused,
1275 struct perf_cpu cpu)
1277 return aggr_cpu_id__global(cpu, /*data=*/NULL);
1280 static struct aggr_cpu_id perf_stat__get_cpu(struct perf_stat_config *config __maybe_unused,
1281 struct perf_cpu cpu)
1283 return aggr_cpu_id__cpu(cpu, /*data=*/NULL);
1286 static struct aggr_cpu_id perf_stat__get_aggr(struct perf_stat_config *config,
1287 aggr_get_id_t get_id, struct perf_cpu cpu)
1289 struct aggr_cpu_id id;
1291 /* per-process mode - should use global aggr mode */
1293 return get_id(config, cpu);
1295 if (aggr_cpu_id__is_empty(&config->cpus_aggr_map->map[cpu.cpu]))
1296 config->cpus_aggr_map->map[cpu.cpu] = get_id(config, cpu);
1298 id = config->cpus_aggr_map->map[cpu.cpu];
1302 static struct aggr_cpu_id perf_stat__get_socket_cached(struct perf_stat_config *config,
1303 struct perf_cpu cpu)
1305 return perf_stat__get_aggr(config, perf_stat__get_socket, cpu);
1308 static struct aggr_cpu_id perf_stat__get_die_cached(struct perf_stat_config *config,
1309 struct perf_cpu cpu)
1311 return perf_stat__get_aggr(config, perf_stat__get_die, cpu);
1314 static struct aggr_cpu_id perf_stat__get_core_cached(struct perf_stat_config *config,
1315 struct perf_cpu cpu)
1317 return perf_stat__get_aggr(config, perf_stat__get_core, cpu);
1320 static struct aggr_cpu_id perf_stat__get_node_cached(struct perf_stat_config *config,
1321 struct perf_cpu cpu)
1323 return perf_stat__get_aggr(config, perf_stat__get_node, cpu);
1326 static struct aggr_cpu_id perf_stat__get_global_cached(struct perf_stat_config *config,
1327 struct perf_cpu cpu)
1329 return perf_stat__get_aggr(config, perf_stat__get_global, cpu);
1332 static struct aggr_cpu_id perf_stat__get_cpu_cached(struct perf_stat_config *config,
1333 struct perf_cpu cpu)
1335 return perf_stat__get_aggr(config, perf_stat__get_cpu, cpu);
1338 static aggr_cpu_id_get_t aggr_mode__get_aggr(enum aggr_mode aggr_mode)
1340 switch (aggr_mode) {
1342 return aggr_cpu_id__socket;
1344 return aggr_cpu_id__die;
1346 return aggr_cpu_id__core;
1348 return aggr_cpu_id__node;
1350 return aggr_cpu_id__cpu;
1352 return aggr_cpu_id__global;
1361 static aggr_get_id_t aggr_mode__get_id(enum aggr_mode aggr_mode)
1363 switch (aggr_mode) {
1365 return perf_stat__get_socket_cached;
1367 return perf_stat__get_die_cached;
1369 return perf_stat__get_core_cached;
1371 return perf_stat__get_node_cached;
1373 return perf_stat__get_cpu_cached;
1375 return perf_stat__get_global_cached;
1384 static int perf_stat_init_aggr_mode(void)
1387 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr(stat_config.aggr_mode);
1390 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1391 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1392 get_id, /*data=*/NULL, needs_sort);
1393 if (!stat_config.aggr_map) {
1394 pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
1397 stat_config.aggr_get_id = aggr_mode__get_id(stat_config.aggr_mode);
1400 if (stat_config.aggr_mode == AGGR_THREAD) {
1401 nr = perf_thread_map__nr(evsel_list->core.threads);
1402 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1403 if (stat_config.aggr_map == NULL)
1406 for (int s = 0; s < nr; s++) {
1407 struct aggr_cpu_id id = aggr_cpu_id__empty();
1410 stat_config.aggr_map->map[s] = id;
1416 * The evsel_list->cpus is the base we operate on,
1417 * taking the highest cpu number to be the size of
1418 * the aggregation translate cpumap.
1420 if (evsel_list->core.user_requested_cpus)
1421 nr = perf_cpu_map__max(evsel_list->core.user_requested_cpus).cpu;
1424 stat_config.cpus_aggr_map = cpu_aggr_map__empty_new(nr + 1);
1425 return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
1428 static void cpu_aggr_map__delete(struct cpu_aggr_map *map)
1431 WARN_ONCE(refcount_read(&map->refcnt) != 0,
1432 "cpu_aggr_map refcnt unbalanced\n");
1437 static void cpu_aggr_map__put(struct cpu_aggr_map *map)
1439 if (map && refcount_dec_and_test(&map->refcnt))
1440 cpu_aggr_map__delete(map);
1443 static void perf_stat__exit_aggr_mode(void)
1445 cpu_aggr_map__put(stat_config.aggr_map);
1446 cpu_aggr_map__put(stat_config.cpus_aggr_map);
1447 stat_config.aggr_map = NULL;
1448 stat_config.cpus_aggr_map = NULL;
1451 static struct aggr_cpu_id perf_env__get_socket_aggr_by_cpu(struct perf_cpu cpu, void *data)
1453 struct perf_env *env = data;
1454 struct aggr_cpu_id id = aggr_cpu_id__empty();
1457 id.socket = env->cpu[cpu.cpu].socket_id;
1462 static struct aggr_cpu_id perf_env__get_die_aggr_by_cpu(struct perf_cpu cpu, void *data)
1464 struct perf_env *env = data;
1465 struct aggr_cpu_id id = aggr_cpu_id__empty();
1467 if (cpu.cpu != -1) {
1469 * die_id is relative to socket, so start
1470 * with the socket ID and then add die to
1473 id.socket = env->cpu[cpu.cpu].socket_id;
1474 id.die = env->cpu[cpu.cpu].die_id;
1480 static struct aggr_cpu_id perf_env__get_core_aggr_by_cpu(struct perf_cpu cpu, void *data)
1482 struct perf_env *env = data;
1483 struct aggr_cpu_id id = aggr_cpu_id__empty();
1485 if (cpu.cpu != -1) {
1487 * core_id is relative to socket and die,
1488 * we need a global id. So we set
1489 * socket, die id and core id
1491 id.socket = env->cpu[cpu.cpu].socket_id;
1492 id.die = env->cpu[cpu.cpu].die_id;
1493 id.core = env->cpu[cpu.cpu].core_id;
1499 static struct aggr_cpu_id perf_env__get_cpu_aggr_by_cpu(struct perf_cpu cpu, void *data)
1501 struct perf_env *env = data;
1502 struct aggr_cpu_id id = aggr_cpu_id__empty();
1504 if (cpu.cpu != -1) {
1506 * core_id is relative to socket and die,
1507 * we need a global id. So we set
1508 * socket, die id and core id
1510 id.socket = env->cpu[cpu.cpu].socket_id;
1511 id.die = env->cpu[cpu.cpu].die_id;
1512 id.core = env->cpu[cpu.cpu].core_id;
1519 static struct aggr_cpu_id perf_env__get_node_aggr_by_cpu(struct perf_cpu cpu, void *data)
1521 struct aggr_cpu_id id = aggr_cpu_id__empty();
1523 id.node = perf_env__numa_node(data, cpu);
1527 static struct aggr_cpu_id perf_env__get_global_aggr_by_cpu(struct perf_cpu cpu __maybe_unused,
1528 void *data __maybe_unused)
1530 struct aggr_cpu_id id = aggr_cpu_id__empty();
1532 /* it always aggregates to the cpu 0 */
1533 id.cpu = (struct perf_cpu){ .cpu = 0 };
1537 static struct aggr_cpu_id perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
1538 struct perf_cpu cpu)
1540 return perf_env__get_socket_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1542 static struct aggr_cpu_id perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
1543 struct perf_cpu cpu)
1545 return perf_env__get_die_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1548 static struct aggr_cpu_id perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
1549 struct perf_cpu cpu)
1551 return perf_env__get_core_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1554 static struct aggr_cpu_id perf_stat__get_cpu_file(struct perf_stat_config *config __maybe_unused,
1555 struct perf_cpu cpu)
1557 return perf_env__get_cpu_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1560 static struct aggr_cpu_id perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
1561 struct perf_cpu cpu)
1563 return perf_env__get_node_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1566 static struct aggr_cpu_id perf_stat__get_global_file(struct perf_stat_config *config __maybe_unused,
1567 struct perf_cpu cpu)
1569 return perf_env__get_global_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1572 static aggr_cpu_id_get_t aggr_mode__get_aggr_file(enum aggr_mode aggr_mode)
1574 switch (aggr_mode) {
1576 return perf_env__get_socket_aggr_by_cpu;
1578 return perf_env__get_die_aggr_by_cpu;
1580 return perf_env__get_core_aggr_by_cpu;
1582 return perf_env__get_node_aggr_by_cpu;
1584 return perf_env__get_global_aggr_by_cpu;
1586 return perf_env__get_cpu_aggr_by_cpu;
1595 static aggr_get_id_t aggr_mode__get_id_file(enum aggr_mode aggr_mode)
1597 switch (aggr_mode) {
1599 return perf_stat__get_socket_file;
1601 return perf_stat__get_die_file;
1603 return perf_stat__get_core_file;
1605 return perf_stat__get_node_file;
1607 return perf_stat__get_global_file;
1609 return perf_stat__get_cpu_file;
1618 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1620 struct perf_env *env = &st->session->header.env;
1621 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr_file(stat_config.aggr_mode);
1622 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1624 if (stat_config.aggr_mode == AGGR_THREAD) {
1625 int nr = perf_thread_map__nr(evsel_list->core.threads);
1627 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1628 if (stat_config.aggr_map == NULL)
1631 for (int s = 0; s < nr; s++) {
1632 struct aggr_cpu_id id = aggr_cpu_id__empty();
1635 stat_config.aggr_map->map[s] = id;
1643 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1644 get_id, env, needs_sort);
1645 if (!stat_config.aggr_map) {
1646 pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
1649 stat_config.aggr_get_id = aggr_mode__get_id_file(stat_config.aggr_mode);
1654 * Add default attributes, if there were no attributes specified or
1655 * if -d/--detailed, -d -d or -d -d -d is used:
1657 static int add_default_attributes(void)
1659 struct perf_event_attr default_attrs0[] = {
1661 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
1662 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
1663 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
1664 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
1666 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
1668 struct perf_event_attr frontend_attrs[] = {
1669 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1671 struct perf_event_attr backend_attrs[] = {
1672 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
1674 struct perf_event_attr default_attrs1[] = {
1675 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
1676 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
1677 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
1682 * Detailed stats (-d), covering the L1 and last level data caches:
1684 struct perf_event_attr detailed_attrs[] = {
1686 { .type = PERF_TYPE_HW_CACHE,
1688 PERF_COUNT_HW_CACHE_L1D << 0 |
1689 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1690 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1692 { .type = PERF_TYPE_HW_CACHE,
1694 PERF_COUNT_HW_CACHE_L1D << 0 |
1695 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1696 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1698 { .type = PERF_TYPE_HW_CACHE,
1700 PERF_COUNT_HW_CACHE_LL << 0 |
1701 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1702 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1704 { .type = PERF_TYPE_HW_CACHE,
1706 PERF_COUNT_HW_CACHE_LL << 0 |
1707 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1708 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1712 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1714 struct perf_event_attr very_detailed_attrs[] = {
1716 { .type = PERF_TYPE_HW_CACHE,
1718 PERF_COUNT_HW_CACHE_L1I << 0 |
1719 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1720 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1722 { .type = PERF_TYPE_HW_CACHE,
1724 PERF_COUNT_HW_CACHE_L1I << 0 |
1725 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1726 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1728 { .type = PERF_TYPE_HW_CACHE,
1730 PERF_COUNT_HW_CACHE_DTLB << 0 |
1731 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1732 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1734 { .type = PERF_TYPE_HW_CACHE,
1736 PERF_COUNT_HW_CACHE_DTLB << 0 |
1737 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1738 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1740 { .type = PERF_TYPE_HW_CACHE,
1742 PERF_COUNT_HW_CACHE_ITLB << 0 |
1743 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1744 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1746 { .type = PERF_TYPE_HW_CACHE,
1748 PERF_COUNT_HW_CACHE_ITLB << 0 |
1749 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1750 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1755 * Very, very detailed stats (-d -d -d), adding prefetch events:
1757 struct perf_event_attr very_very_detailed_attrs[] = {
1759 { .type = PERF_TYPE_HW_CACHE,
1761 PERF_COUNT_HW_CACHE_L1D << 0 |
1762 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1763 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1765 { .type = PERF_TYPE_HW_CACHE,
1767 PERF_COUNT_HW_CACHE_L1D << 0 |
1768 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1769 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1772 struct perf_event_attr default_null_attrs[] = {};
1774 /* Set attrs if no event is selected and !null_run: */
1775 if (stat_config.null_run)
1778 if (transaction_run) {
1779 /* Handle -T as -M transaction. Once platform specific metrics
1780 * support has been added to the json files, all architectures
1781 * will use this approach. To determine transaction support
1782 * on an architecture test for such a metric name.
1784 if (!metricgroup__has_metric("transaction")) {
1785 pr_err("Missing transaction metrics");
1788 return metricgroup__parse_groups(evsel_list, "transaction",
1789 stat_config.metric_no_group,
1790 stat_config.metric_no_merge,
1791 stat_config.metric_no_threshold,
1792 stat_config.user_requested_cpu_list,
1793 stat_config.system_wide,
1794 &stat_config.metric_events);
1800 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
1801 pr_err("freeze_on_smi is not supported.");
1806 if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
1807 fprintf(stderr, "Failed to set freeze_on_smi.\n");
1813 if (!metricgroup__has_metric("smi")) {
1814 pr_err("Missing smi metrics");
1818 if (!force_metric_only)
1819 stat_config.metric_only = true;
1821 return metricgroup__parse_groups(evsel_list, "smi",
1822 stat_config.metric_no_group,
1823 stat_config.metric_no_merge,
1824 stat_config.metric_no_threshold,
1825 stat_config.user_requested_cpu_list,
1826 stat_config.system_wide,
1827 &stat_config.metric_events);
1831 unsigned int max_level = metricgroups__topdown_max_level();
1832 char str[] = "TopdownL1";
1834 if (!force_metric_only)
1835 stat_config.metric_only = true;
1838 pr_err("Topdown requested but the topdown metric groups aren't present.\n"
1839 "(See perf list the metric groups have names like TopdownL1)");
1842 if (stat_config.topdown_level > max_level) {
1843 pr_err("Invalid top-down metrics level. The max level is %u.\n", max_level);
1845 } else if (!stat_config.topdown_level)
1846 stat_config.topdown_level = 1;
1848 if (!stat_config.interval && !stat_config.metric_only) {
1849 fprintf(stat_config.output,
1850 "Topdown accuracy may decrease when measuring long periods.\n"
1851 "Please print the result regularly, e.g. -I1000\n");
1853 str[8] = stat_config.topdown_level + '0';
1854 if (metricgroup__parse_groups(evsel_list, str,
1855 /*metric_no_group=*/false,
1856 /*metric_no_merge=*/false,
1857 /*metric_no_threshold=*/true,
1858 stat_config.user_requested_cpu_list,
1859 stat_config.system_wide,
1860 &stat_config.metric_events) < 0)
1864 if (!stat_config.topdown_level)
1865 stat_config.topdown_level = 1;
1867 if (!evsel_list->core.nr_entries) {
1868 /* No events so add defaults. */
1869 if (target__has_cpu(&target))
1870 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
1872 if (evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
1874 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
1875 if (evlist__add_default_attrs(evsel_list, frontend_attrs) < 0)
1878 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
1879 if (evlist__add_default_attrs(evsel_list, backend_attrs) < 0)
1882 if (evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
1885 * Add TopdownL1 metrics if they exist. To minimize
1886 * multiplexing, don't request threshold computation.
1889 * TODO: TopdownL1 is disabled on hybrid CPUs to avoid a crashes
1890 * caused by exposing latent bugs. This is fixed properly in:
1893 if (metricgroup__has_metric("TopdownL1") && !perf_pmu__has_hybrid() &&
1894 metricgroup__parse_groups(evsel_list, "TopdownL1",
1895 /*metric_no_group=*/false,
1896 /*metric_no_merge=*/false,
1897 /*metric_no_threshold=*/true,
1898 stat_config.user_requested_cpu_list,
1899 stat_config.system_wide,
1900 &stat_config.metric_events) < 0)
1903 /* Platform specific attrs */
1904 if (evlist__add_default_attrs(evsel_list, default_null_attrs) < 0)
1908 /* Detailed events get appended to the event list: */
1910 if (detailed_run < 1)
1913 /* Append detailed run extra attributes: */
1914 if (evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1917 if (detailed_run < 2)
1920 /* Append very detailed run extra attributes: */
1921 if (evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1924 if (detailed_run < 3)
1927 /* Append very, very detailed run extra attributes: */
1928 return evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1931 static const char * const stat_record_usage[] = {
1932 "perf stat record [<options>]",
1936 static void init_features(struct perf_session *session)
1940 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
1941 perf_header__set_feat(&session->header, feat);
1943 perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
1944 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
1945 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
1946 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
1947 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
1950 static int __cmd_record(int argc, const char **argv)
1952 struct perf_session *session;
1953 struct perf_data *data = &perf_stat.data;
1955 argc = parse_options(argc, argv, stat_options, stat_record_usage,
1956 PARSE_OPT_STOP_AT_NON_OPTION);
1959 data->path = output_name;
1961 if (stat_config.run_count != 1 || forever) {
1962 pr_err("Cannot use -r option with perf stat record.\n");
1966 session = perf_session__new(data, NULL);
1967 if (IS_ERR(session)) {
1968 pr_err("Perf session creation failed\n");
1969 return PTR_ERR(session);
1972 init_features(session);
1974 session->evlist = evsel_list;
1975 perf_stat.session = session;
1976 perf_stat.record = true;
1980 static int process_stat_round_event(struct perf_session *session,
1981 union perf_event *event)
1983 struct perf_record_stat_round *stat_round = &event->stat_round;
1984 struct timespec tsh, *ts = NULL;
1985 const char **argv = session->header.env.cmdline_argv;
1986 int argc = session->header.env.nr_cmdline;
1990 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
1991 update_stats(&walltime_nsecs_stats, stat_round->time);
1993 if (stat_config.interval && stat_round->time) {
1994 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
1995 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
1999 print_counters(ts, argc, argv);
2004 int process_stat_config_event(struct perf_session *session,
2005 union perf_event *event)
2007 struct perf_tool *tool = session->tool;
2008 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2010 perf_event__read_stat_config(&stat_config, &event->stat_config);
2012 if (perf_cpu_map__empty(st->cpus)) {
2013 if (st->aggr_mode != AGGR_UNSET)
2014 pr_warning("warning: processing task data, aggregation mode not set\n");
2015 } else if (st->aggr_mode != AGGR_UNSET) {
2016 stat_config.aggr_mode = st->aggr_mode;
2019 if (perf_stat.data.is_pipe)
2020 perf_stat_init_aggr_mode();
2022 perf_stat_init_aggr_mode_file(st);
2024 if (stat_config.aggr_map) {
2025 int nr_aggr = stat_config.aggr_map->nr;
2027 if (evlist__alloc_aggr_stats(session->evlist, nr_aggr) < 0) {
2028 pr_err("cannot allocate aggr counts\n");
2035 static int set_maps(struct perf_stat *st)
2037 if (!st->cpus || !st->threads)
2040 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2043 perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
2045 if (evlist__alloc_stats(&stat_config, evsel_list, /*alloc_raw=*/true))
2048 st->maps_allocated = true;
2053 int process_thread_map_event(struct perf_session *session,
2054 union perf_event *event)
2056 struct perf_tool *tool = session->tool;
2057 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2060 pr_warning("Extra thread map event, ignoring.\n");
2064 st->threads = thread_map__new_event(&event->thread_map);
2068 return set_maps(st);
2072 int process_cpu_map_event(struct perf_session *session,
2073 union perf_event *event)
2075 struct perf_tool *tool = session->tool;
2076 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2077 struct perf_cpu_map *cpus;
2080 pr_warning("Extra cpu map event, ignoring.\n");
2084 cpus = cpu_map__new_data(&event->cpu_map.data);
2089 return set_maps(st);
2092 static const char * const stat_report_usage[] = {
2093 "perf stat report [<options>]",
2097 static struct perf_stat perf_stat = {
2099 .attr = perf_event__process_attr,
2100 .event_update = perf_event__process_event_update,
2101 .thread_map = process_thread_map_event,
2102 .cpu_map = process_cpu_map_event,
2103 .stat_config = process_stat_config_event,
2104 .stat = perf_event__process_stat_event,
2105 .stat_round = process_stat_round_event,
2107 .aggr_mode = AGGR_UNSET,
2110 static int __cmd_report(int argc, const char **argv)
2112 struct perf_session *session;
2113 const struct option options[] = {
2114 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2115 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2116 "aggregate counts per processor socket", AGGR_SOCKET),
2117 OPT_SET_UINT(0, "per-die", &perf_stat.aggr_mode,
2118 "aggregate counts per processor die", AGGR_DIE),
2119 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2120 "aggregate counts per physical processor core", AGGR_CORE),
2121 OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
2122 "aggregate counts per numa node", AGGR_NODE),
2123 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2124 "disable CPU count aggregation", AGGR_NONE),
2130 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2132 if (!input_name || !strlen(input_name)) {
2133 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2136 input_name = "perf.data";
2139 perf_stat.data.path = input_name;
2140 perf_stat.data.mode = PERF_DATA_MODE_READ;
2142 session = perf_session__new(&perf_stat.data, &perf_stat.tool);
2143 if (IS_ERR(session))
2144 return PTR_ERR(session);
2146 perf_stat.session = session;
2147 stat_config.output = stderr;
2148 evsel_list = session->evlist;
2150 ret = perf_session__process_events(session);
2154 perf_session__delete(session);
2158 static void setup_system_wide(int forks)
2161 * Make system wide (-a) the default target if
2162 * no target was specified and one of following
2163 * conditions is met:
2165 * - there's no workload specified
2166 * - there is workload specified but all requested
2167 * events are system wide events
2169 if (!target__none(&target))
2173 target.system_wide = true;
2175 struct evsel *counter;
2177 evlist__for_each_entry(evsel_list, counter) {
2178 if (!counter->core.requires_cpu &&
2179 !evsel__name_is(counter, "duration_time")) {
2184 if (evsel_list->core.nr_entries)
2185 target.system_wide = true;
2189 int cmd_stat(int argc, const char **argv)
2191 const char * const stat_usage[] = {
2192 "perf stat [<options>] [<command>]",
2195 int status = -EINVAL, run_idx, err;
2197 FILE *output = stderr;
2198 unsigned int interval, timeout;
2199 const char * const stat_subcommands[] = { "record", "report" };
2200 char errbuf[BUFSIZ];
2202 setlocale(LC_ALL, "");
2204 evsel_list = evlist__new();
2205 if (evsel_list == NULL)
2208 parse_events__shrink_config_terms();
2210 /* String-parsing callback-based options would segfault when negated */
2211 set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
2212 set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
2213 set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
2215 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2216 (const char **) stat_usage,
2217 PARSE_OPT_STOP_AT_NON_OPTION);
2219 if (stat_config.csv_sep) {
2220 stat_config.csv_output = true;
2221 if (!strcmp(stat_config.csv_sep, "\\t"))
2222 stat_config.csv_sep = "\t";
2224 stat_config.csv_sep = DEFAULT_SEPARATOR;
2226 if (argc && strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
2227 argc = __cmd_record(argc, argv);
2230 } else if (argc && strlen(argv[0]) > 2 && strstarts("report", argv[0]))
2231 return __cmd_report(argc, argv);
2233 interval = stat_config.interval;
2234 timeout = stat_config.timeout;
2237 * For record command the -o is already taken care of.
2239 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2242 if (output_name && output_fd) {
2243 fprintf(stderr, "cannot use both --output and --log-fd\n");
2244 parse_options_usage(stat_usage, stat_options, "o", 1);
2245 parse_options_usage(NULL, stat_options, "log-fd", 0);
2249 if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2250 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2254 if (stat_config.metric_only && stat_config.run_count > 1) {
2255 fprintf(stderr, "--metric-only is not supported with -r\n");
2259 if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
2260 fprintf(stderr, "--table is only supported with -r\n");
2261 parse_options_usage(stat_usage, stat_options, "r", 1);
2262 parse_options_usage(NULL, stat_options, "table", 0);
2266 if (output_fd < 0) {
2267 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2268 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2272 if (!output && !quiet) {
2274 mode = append_file ? "a" : "w";
2276 output = fopen(output_name, mode);
2278 perror("failed to create output file");
2281 if (!stat_config.json_output) {
2282 clock_gettime(CLOCK_REALTIME, &tm);
2283 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2285 } else if (output_fd > 0) {
2286 mode = append_file ? "a" : "w";
2287 output = fdopen(output_fd, mode);
2289 perror("Failed opening logfd");
2294 if (stat_config.interval_clear && !isatty(fileno(output))) {
2295 fprintf(stderr, "--interval-clear does not work with output\n");
2296 parse_options_usage(stat_usage, stat_options, "o", 1);
2297 parse_options_usage(NULL, stat_options, "log-fd", 0);
2298 parse_options_usage(NULL, stat_options, "interval-clear", 0);
2302 stat_config.output = output;
2305 * let the spreadsheet do the pretty-printing
2307 if (stat_config.csv_output) {
2308 /* User explicitly passed -B? */
2309 if (big_num_opt == 1) {
2310 fprintf(stderr, "-B option not supported with -x\n");
2311 parse_options_usage(stat_usage, stat_options, "B", 1);
2312 parse_options_usage(NULL, stat_options, "x", 1);
2314 } else /* Nope, so disable big number formatting */
2315 stat_config.big_num = false;
2316 } else if (big_num_opt == 0) /* User passed --no-big-num */
2317 stat_config.big_num = false;
2319 err = target__validate(&target);
2321 target__strerror(&target, err, errbuf, BUFSIZ);
2322 pr_warning("%s\n", errbuf);
2325 setup_system_wide(argc);
2328 * Display user/system times only for single
2329 * run and when there's specified tracee.
2331 if ((stat_config.run_count == 1) && target__none(&target))
2332 stat_config.ru_display = true;
2334 if (stat_config.run_count < 0) {
2335 pr_err("Run count must be a positive number\n");
2336 parse_options_usage(stat_usage, stat_options, "r", 1);
2338 } else if (stat_config.run_count == 0) {
2340 stat_config.run_count = 1;
2343 if (stat_config.walltime_run_table) {
2344 stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
2345 if (!stat_config.walltime_run) {
2346 pr_err("failed to setup -r option");
2351 if ((stat_config.aggr_mode == AGGR_THREAD) &&
2352 !target__has_task(&target)) {
2353 if (!target.system_wide || target.cpu_list) {
2354 fprintf(stderr, "The --per-thread option is only "
2355 "available when monitoring via -p -t -a "
2356 "options or only --per-thread.\n");
2357 parse_options_usage(NULL, stat_options, "p", 1);
2358 parse_options_usage(NULL, stat_options, "t", 1);
2364 * no_aggr, cgroup are for system-wide only
2365 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2367 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2368 stat_config.aggr_mode != AGGR_THREAD) ||
2369 (nr_cgroups || stat_config.cgroup_list)) &&
2370 !target__has_cpu(&target)) {
2371 fprintf(stderr, "both cgroup and no-aggregation "
2372 "modes only available in system-wide mode\n");
2374 parse_options_usage(stat_usage, stat_options, "G", 1);
2375 parse_options_usage(NULL, stat_options, "A", 1);
2376 parse_options_usage(NULL, stat_options, "a", 1);
2377 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2381 if (stat_config.iostat_run) {
2382 status = iostat_prepare(evsel_list, &stat_config);
2385 if (iostat_mode == IOSTAT_LIST) {
2386 iostat_list(evsel_list, &stat_config);
2388 } else if (verbose > 0)
2389 iostat_list(evsel_list, &stat_config);
2390 if (iostat_mode == IOSTAT_RUN && !target__has_cpu(&target))
2391 target.system_wide = true;
2394 if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2395 target.per_thread = true;
2397 stat_config.system_wide = target.system_wide;
2398 if (target.cpu_list) {
2399 stat_config.user_requested_cpu_list = strdup(target.cpu_list);
2400 if (!stat_config.user_requested_cpu_list) {
2407 * Metric parsing needs to be delayed as metrics may optimize events
2408 * knowing the target is system-wide.
2411 metricgroup__parse_groups(evsel_list, metrics,
2412 stat_config.metric_no_group,
2413 stat_config.metric_no_merge,
2414 stat_config.metric_no_threshold,
2415 stat_config.user_requested_cpu_list,
2416 stat_config.system_wide,
2417 &stat_config.metric_events);
2421 if (add_default_attributes())
2424 if (stat_config.cgroup_list) {
2425 if (nr_cgroups > 0) {
2426 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
2427 parse_options_usage(stat_usage, stat_options, "G", 1);
2428 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2432 if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list,
2433 &stat_config.metric_events, true) < 0) {
2434 parse_options_usage(stat_usage, stat_options,
2435 "for-each-cgroup", 0);
2440 if (evlist__fix_hybrid_cpus(evsel_list, target.cpu_list)) {
2441 pr_err("failed to use cpu list %s\n", target.cpu_list);
2445 target.hybrid = perf_pmu__has_hybrid();
2446 if (evlist__create_maps(evsel_list, &target) < 0) {
2447 if (target__has_task(&target)) {
2448 pr_err("Problems finding threads of monitor\n");
2449 parse_options_usage(stat_usage, stat_options, "p", 1);
2450 parse_options_usage(NULL, stat_options, "t", 1);
2451 } else if (target__has_cpu(&target)) {
2452 perror("failed to parse CPUs map");
2453 parse_options_usage(stat_usage, stat_options, "C", 1);
2454 parse_options_usage(NULL, stat_options, "a", 1);
2459 evlist__check_cpu_maps(evsel_list);
2462 * Initialize thread_map with comm names,
2463 * so we could print it out on output.
2465 if (stat_config.aggr_mode == AGGR_THREAD) {
2466 thread_map__read_comms(evsel_list->core.threads);
2469 if (stat_config.aggr_mode == AGGR_NODE)
2470 cpu__setup_cpunode_map();
2472 if (stat_config.times && interval)
2473 interval_count = true;
2474 else if (stat_config.times && !interval) {
2475 pr_err("interval-count option should be used together with "
2476 "interval-print.\n");
2477 parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2478 parse_options_usage(stat_usage, stat_options, "I", 1);
2482 if (timeout && timeout < 100) {
2484 pr_err("timeout must be >= 10ms.\n");
2485 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2488 pr_warning("timeout < 100ms. "
2489 "The overhead percentage could be high in some cases. "
2490 "Please proceed with caution.\n");
2492 if (timeout && interval) {
2493 pr_err("timeout option is not supported with interval-print.\n");
2494 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2495 parse_options_usage(stat_usage, stat_options, "I", 1);
2499 if (perf_stat_init_aggr_mode())
2502 if (evlist__alloc_stats(&stat_config, evsel_list, interval))
2506 * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2507 * while avoiding that older tools show confusing messages.
2509 * However for pipe sessions we need to keep it zero,
2510 * because script's perf_evsel__check_attr is triggered
2511 * by attr->sample_type != 0, and we can't run it on
2514 stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2517 * We dont want to block the signals - that would cause
2518 * child tasks to inherit that and Ctrl-C would not work.
2519 * What we want is for Ctrl-C to work in the exec()-ed
2520 * task, but being ignored by perf stat itself:
2524 signal(SIGINT, skip_signal);
2525 signal(SIGCHLD, skip_signal);
2526 signal(SIGALRM, skip_signal);
2527 signal(SIGABRT, skip_signal);
2529 if (evlist__initialize_ctlfd(evsel_list, stat_config.ctl_fd, stat_config.ctl_fd_ack))
2532 /* Enable ignoring missing threads when -p option is defined. */
2533 evlist__first(evsel_list)->ignore_missing_thread = target.pid;
2535 for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
2536 if (stat_config.run_count != 1 && verbose > 0)
2537 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2541 evlist__reset_prev_raw_counts(evsel_list);
2543 status = run_perf_stat(argc, argv, run_idx);
2544 if (forever && status != -1 && !interval) {
2545 print_counters(NULL, argc, argv);
2546 perf_stat__reset_stats();
2550 if (!forever && status != -1 && (!interval || stat_config.summary))
2551 print_counters(NULL, argc, argv);
2553 evlist__finalize_ctlfd(evsel_list);
2557 * We synthesize the kernel mmap record just so that older tools
2558 * don't emit warnings about not being able to resolve symbols
2559 * due to /proc/sys/kernel/kptr_restrict settings and instead provide
2560 * a saner message about no samples being in the perf.data file.
2562 * This also serves to suppress a warning about f_header.data.size == 0
2563 * in header.c at the moment 'perf stat record' gets introduced, which
2564 * is not really needed once we start adding the stat specific PERF_RECORD_
2565 * records, but the need to suppress the kptr_restrict messages in older
2566 * tools remain -acme
2568 int fd = perf_data__fd(&perf_stat.data);
2570 err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2571 process_synthesized_event,
2572 &perf_stat.session->machines.host);
2574 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2575 "older tools may produce warnings about this file\n.");
2579 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2580 pr_err("failed to write stat round event\n");
2583 if (!perf_stat.data.is_pipe) {
2584 perf_stat.session->header.data_size += perf_stat.bytes_written;
2585 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2588 evlist__close(evsel_list);
2589 perf_session__delete(perf_stat.session);
2592 perf_stat__exit_aggr_mode();
2593 evlist__free_stats(evsel_list);
2595 if (stat_config.iostat_run)
2596 iostat_release(evsel_list);
2598 zfree(&stat_config.walltime_run);
2599 zfree(&stat_config.user_requested_cpu_list);
2601 if (smi_cost && smi_reset)
2602 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2604 evlist__delete(evsel_list);
2606 metricgroup__rblist_exit(&stat_config.metric_events);
2607 evlist__close_control(stat_config.ctl_fd, stat_config.ctl_fd_ack, &stat_config.ctl_fd_close);