1 // SPDX-License-Identifier: GPL-2.0-only
5 * Builtin stat command: Give a precise performance counters summary
6 * overview about any workload, CPU or specific PID.
10 $ perf stat ./hackbench 10
14 Performance counter stats for './hackbench 10':
16 1708.761321 task-clock # 11.037 CPUs utilized
17 41,190 context-switches # 0.024 M/sec
18 6,735 CPU-migrations # 0.004 M/sec
19 17,318 page-faults # 0.010 M/sec
20 5,205,202,243 cycles # 3.046 GHz
21 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle
22 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle
23 2,603,501,247 instructions # 0.50 insns per cycle
24 # 1.48 stalled cycles per insn
25 484,357,498 branches # 283.455 M/sec
26 6,388,934 branch-misses # 1.32% of all branches
28 0.154822978 seconds time elapsed
31 * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
33 * Improvements and fixes by:
35 * Arjan van de Ven <arjan@linux.intel.com>
36 * Yanmin Zhang <yanmin.zhang@intel.com>
37 * Wu Fengguang <fengguang.wu@intel.com>
38 * Mike Galbraith <efault@gmx.de>
39 * Paul Mackerras <paulus@samba.org>
40 * Jaswinder Singh Rajput <jaswinder@kernel.org>
45 #include "util/cgroup.h"
46 #include <subcmd/parse-options.h>
47 #include "util/parse-events.h"
49 #include "util/event.h"
50 #include "util/evlist.h"
51 #include "util/evlist-hybrid.h"
52 #include "util/evsel.h"
53 #include "util/debug.h"
54 #include "util/color.h"
55 #include "util/stat.h"
56 #include "util/header.h"
57 #include "util/cpumap.h"
58 #include "util/thread_map.h"
59 #include "util/counts.h"
60 #include "util/topdown.h"
61 #include "util/session.h"
62 #include "util/tool.h"
63 #include "util/string2.h"
64 #include "util/metricgroup.h"
65 #include "util/synthetic-events.h"
66 #include "util/target.h"
67 #include "util/time-utils.h"
69 #include "util/affinity.h"
71 #include "util/bpf_counter.h"
72 #include "util/iostat.h"
73 #include "util/pmu-hybrid.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, *pos, *leader;
187 if (evlist__has_hybrid(evlist))
188 evlist__warn_hybrid_group(evlist);
190 evlist__for_each_entry(evlist, evsel) {
191 leader = evsel__leader(evsel);
193 /* Check that leader matches cpus with each member. */
196 if (cpus_map_matched(leader, evsel))
199 /* If there's mismatch disable the group and warn user. */
200 WARN_ONCE(1, "WARNING: grouped events cpus do not match, disabling group:\n");
201 evsel__group_desc(leader, buf, sizeof(buf));
202 pr_warning(" %s\n", buf);
205 cpu_map__snprint(leader->core.cpus, buf, sizeof(buf));
206 pr_warning(" %s: %s\n", leader->name, buf);
207 cpu_map__snprint(evsel->core.cpus, buf, sizeof(buf));
208 pr_warning(" %s: %s\n", evsel->name, buf);
211 for_each_group_evsel(pos, leader)
212 evsel__remove_from_group(pos, leader);
216 static inline void diff_timespec(struct timespec *r, struct timespec *a,
219 r->tv_sec = a->tv_sec - b->tv_sec;
220 if (a->tv_nsec < b->tv_nsec) {
221 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
224 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
228 static void perf_stat__reset_stats(void)
230 evlist__reset_stats(evsel_list);
231 perf_stat__reset_shadow_stats();
234 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
235 union perf_event *event,
236 struct perf_sample *sample __maybe_unused,
237 struct machine *machine __maybe_unused)
239 if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
240 pr_err("failed to write perf data, error: %m\n");
244 perf_stat.bytes_written += event->header.size;
248 static int write_stat_round_event(u64 tm, u64 type)
250 return perf_event__synthesize_stat_round(NULL, tm, type,
251 process_synthesized_event,
255 #define WRITE_STAT_ROUND_EVENT(time, interval) \
256 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
258 #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
260 static int evsel__write_stat_event(struct evsel *counter, int cpu_map_idx, u32 thread,
261 struct perf_counts_values *count)
263 struct perf_sample_id *sid = SID(counter, cpu_map_idx, thread);
264 struct perf_cpu cpu = perf_cpu_map__cpu(evsel__cpus(counter), cpu_map_idx);
266 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
267 process_synthesized_event, NULL);
270 static int read_single_counter(struct evsel *counter, int cpu_map_idx,
271 int thread, struct timespec *rs)
273 switch(counter->tool_event) {
274 case PERF_TOOL_DURATION_TIME: {
275 u64 val = rs->tv_nsec + rs->tv_sec*1000000000ULL;
276 struct perf_counts_values *count =
277 perf_counts(counter->counts, cpu_map_idx, thread);
278 count->ena = count->run = val;
282 case PERF_TOOL_USER_TIME:
283 case PERF_TOOL_SYSTEM_TIME: {
285 struct perf_counts_values *count =
286 perf_counts(counter->counts, cpu_map_idx, thread);
287 if (counter->tool_event == PERF_TOOL_USER_TIME)
288 val = ru_stats.ru_utime_usec_stat.mean;
290 val = ru_stats.ru_stime_usec_stat.mean;
291 count->ena = count->run = val;
297 return evsel__read_counter(counter, cpu_map_idx, thread);
299 /* This should never be reached */
305 * Read out the results of a single counter:
306 * do not aggregate counts across CPUs in system-wide mode
308 static int read_counter_cpu(struct evsel *counter, struct timespec *rs, int cpu_map_idx)
310 int nthreads = perf_thread_map__nr(evsel_list->core.threads);
313 if (!counter->supported)
316 for (thread = 0; thread < nthreads; thread++) {
317 struct perf_counts_values *count;
319 count = perf_counts(counter->counts, cpu_map_idx, thread);
322 * The leader's group read loads data into its group members
323 * (via evsel__read_counter()) and sets their count->loaded.
325 if (!perf_counts__is_loaded(counter->counts, cpu_map_idx, thread) &&
326 read_single_counter(counter, cpu_map_idx, thread, rs)) {
327 counter->counts->scaled = -1;
328 perf_counts(counter->counts, cpu_map_idx, thread)->ena = 0;
329 perf_counts(counter->counts, cpu_map_idx, thread)->run = 0;
333 perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, false);
336 if (evsel__write_stat_event(counter, cpu_map_idx, thread, count)) {
337 pr_err("failed to write stat event\n");
343 fprintf(stat_config.output,
344 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
345 evsel__name(counter),
346 perf_cpu_map__cpu(evsel__cpus(counter),
348 count->val, count->ena, count->run);
355 static int read_affinity_counters(struct timespec *rs)
357 struct evlist_cpu_iterator evlist_cpu_itr;
358 struct affinity saved_affinity, *affinity;
360 if (all_counters_use_bpf)
363 if (!target__has_cpu(&target) || target__has_per_thread(&target))
365 else if (affinity__setup(&saved_affinity) < 0)
368 affinity = &saved_affinity;
370 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
371 struct evsel *counter = evlist_cpu_itr.evsel;
373 if (evsel__is_bpf(counter))
377 counter->err = read_counter_cpu(counter, rs,
378 evlist_cpu_itr.cpu_map_idx);
382 affinity__cleanup(&saved_affinity);
387 static int read_bpf_map_counters(void)
389 struct evsel *counter;
392 evlist__for_each_entry(evsel_list, counter) {
393 if (!evsel__is_bpf(counter))
396 err = bpf_counter__read(counter);
403 static int read_counters(struct timespec *rs)
405 if (!stat_config.stop_read_counter) {
406 if (read_bpf_map_counters() ||
407 read_affinity_counters(rs))
413 static void process_counters(void)
415 struct evsel *counter;
417 evlist__for_each_entry(evsel_list, counter) {
419 pr_debug("failed to read counter %s\n", counter->name);
420 if (counter->err == 0 && perf_stat_process_counter(&stat_config, counter))
421 pr_warning("failed to process counter %s\n", counter->name);
425 perf_stat_merge_counters(&stat_config, evsel_list);
426 perf_stat_process_percore(&stat_config, evsel_list);
429 static void process_interval(void)
431 struct timespec ts, rs;
433 clock_gettime(CLOCK_MONOTONIC, &ts);
434 diff_timespec(&rs, &ts, &ref_time);
436 evlist__reset_aggr_stats(evsel_list);
438 if (read_counters(&rs) == 0)
442 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
443 pr_err("failed to write stat round event\n");
446 init_stats(&walltime_nsecs_stats);
447 update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000ULL);
448 print_counters(&rs, 0, NULL);
451 static bool handle_interval(unsigned int interval, int *times)
455 if (interval_count && !(--(*times)))
461 static int enable_counters(void)
466 evlist__for_each_entry(evsel_list, evsel) {
467 if (!evsel__is_bpf(evsel))
470 err = bpf_counter__enable(evsel);
475 if (!target__enable_on_exec(&target)) {
476 if (!all_counters_use_bpf)
477 evlist__enable(evsel_list);
482 static void disable_counters(void)
484 struct evsel *counter;
487 * If we don't have tracee (attaching to task or cpu), counters may
488 * still be running. To get accurate group ratios, we must stop groups
489 * from counting before reading their constituent counters.
491 if (!target__none(&target)) {
492 evlist__for_each_entry(evsel_list, counter)
493 bpf_counter__disable(counter);
494 if (!all_counters_use_bpf)
495 evlist__disable(evsel_list);
499 static volatile sig_atomic_t workload_exec_errno;
502 * evlist__prepare_workload will send a SIGUSR1
503 * if the fork fails, since we asked by setting its
504 * want_signal to true.
506 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
507 void *ucontext __maybe_unused)
509 workload_exec_errno = info->si_value.sival_int;
512 static bool evsel__should_store_id(struct evsel *counter)
514 return STAT_RECORD || counter->core.attr.read_format & PERF_FORMAT_ID;
517 static bool is_target_alive(struct target *_target,
518 struct perf_thread_map *threads)
523 if (!target__has_task(_target))
526 for (i = 0; i < threads->nr; i++) {
529 scnprintf(path, PATH_MAX, "%s/%d", procfs__mountpoint(),
530 threads->map[i].pid);
532 if (!stat(path, &st))
539 static void process_evlist(struct evlist *evlist, unsigned int interval)
541 enum evlist_ctl_cmd cmd = EVLIST_CTL_CMD_UNSUPPORTED;
543 if (evlist__ctlfd_process(evlist, &cmd) > 0) {
545 case EVLIST_CTL_CMD_ENABLE:
547 case EVLIST_CTL_CMD_DISABLE:
551 case EVLIST_CTL_CMD_SNAPSHOT:
552 case EVLIST_CTL_CMD_ACK:
553 case EVLIST_CTL_CMD_UNSUPPORTED:
554 case EVLIST_CTL_CMD_EVLIST:
555 case EVLIST_CTL_CMD_STOP:
556 case EVLIST_CTL_CMD_PING:
563 static void compute_tts(struct timespec *time_start, struct timespec *time_stop,
566 int tts = *time_to_sleep;
567 struct timespec time_diff;
569 diff_timespec(&time_diff, time_stop, time_start);
571 tts -= time_diff.tv_sec * MSEC_PER_SEC +
572 time_diff.tv_nsec / NSEC_PER_MSEC;
577 *time_to_sleep = tts;
580 static int dispatch_events(bool forks, int timeout, int interval, int *times)
582 int child_exited = 0, status = 0;
583 int time_to_sleep, sleep_time;
584 struct timespec time_start, time_stop;
587 sleep_time = interval;
589 sleep_time = timeout;
593 time_to_sleep = sleep_time;
597 child_exited = waitpid(child_pid, &status, WNOHANG);
599 child_exited = !is_target_alive(&target, evsel_list->core.threads) ? 1 : 0;
604 clock_gettime(CLOCK_MONOTONIC, &time_start);
605 if (!(evlist__poll(evsel_list, time_to_sleep) > 0)) { /* poll timeout or EINTR */
606 if (timeout || handle_interval(interval, times))
608 time_to_sleep = sleep_time;
609 } else { /* fd revent */
610 process_evlist(evsel_list, interval);
611 clock_gettime(CLOCK_MONOTONIC, &time_stop);
612 compute_tts(&time_start, &time_stop, &time_to_sleep);
619 enum counter_recovery {
625 static enum counter_recovery stat_handle_error(struct evsel *counter)
629 * PPC returns ENXIO for HW counters until 2.6.37
630 * (behavior changed with commit b0a873e).
632 if (errno == EINVAL || errno == ENOSYS ||
633 errno == ENOENT || errno == EOPNOTSUPP ||
636 ui__warning("%s event is not supported by the kernel.\n",
637 evsel__name(counter));
638 counter->supported = false;
640 * errored is a sticky flag that means one of the counter's
641 * cpu event had a problem and needs to be reexamined.
643 counter->errored = true;
645 if ((evsel__leader(counter) != counter) ||
646 !(counter->core.leader->nr_members > 1))
648 } else if (evsel__fallback(counter, errno, msg, sizeof(msg))) {
650 ui__warning("%s\n", msg);
651 return COUNTER_RETRY;
652 } else if (target__has_per_thread(&target) &&
653 evsel_list->core.threads &&
654 evsel_list->core.threads->err_thread != -1) {
656 * For global --per-thread case, skip current
659 if (!thread_map__remove(evsel_list->core.threads,
660 evsel_list->core.threads->err_thread)) {
661 evsel_list->core.threads->err_thread = -1;
662 return COUNTER_RETRY;
666 evsel__open_strerror(counter, &target, errno, msg, sizeof(msg));
667 ui__error("%s\n", msg);
670 kill(child_pid, SIGTERM);
671 return COUNTER_FATAL;
674 static int __run_perf_stat(int argc, const char **argv, int run_idx)
676 int interval = stat_config.interval;
677 int times = stat_config.times;
678 int timeout = stat_config.timeout;
680 unsigned long long t0, t1;
681 struct evsel *counter;
684 const bool forks = (argc > 0);
685 bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
686 struct evlist_cpu_iterator evlist_cpu_itr;
687 struct affinity saved_affinity, *affinity = NULL;
689 bool second_pass = false;
692 if (evlist__prepare_workload(evsel_list, &target, argv, is_pipe, workload_exec_failed_signal) < 0) {
693 perror("failed to prepare workload");
696 child_pid = evsel_list->workload.pid;
699 if (!cpu_map__is_dummy(evsel_list->core.user_requested_cpus)) {
700 if (affinity__setup(&saved_affinity) < 0)
702 affinity = &saved_affinity;
705 evlist__for_each_entry(evsel_list, counter) {
706 counter->reset_group = false;
707 if (bpf_counter__load(counter, &target))
709 if (!evsel__is_bpf(counter))
710 all_counters_use_bpf = false;
713 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
714 counter = evlist_cpu_itr.evsel;
717 * bperf calls evsel__open_per_cpu() in bperf__load(), so
718 * no need to call it again here.
723 if (counter->reset_group || counter->errored)
725 if (evsel__is_bpf(counter))
728 if (create_perf_stat_counter(counter, &stat_config, &target,
729 evlist_cpu_itr.cpu_map_idx) < 0) {
732 * Weak group failed. We cannot just undo this here
733 * because earlier CPUs might be in group mode, and the kernel
734 * doesn't support mixing group and non group reads. Defer
736 * Don't close here because we're in the wrong affinity.
738 if ((errno == EINVAL || errno == EBADF) &&
739 evsel__leader(counter) != counter &&
740 counter->weak_group) {
741 evlist__reset_weak_group(evsel_list, counter, false);
742 assert(counter->reset_group);
747 switch (stat_handle_error(counter)) {
759 counter->supported = true;
764 * Now redo all the weak group after closing them,
765 * and also close errored counters.
768 /* First close errored or weak retry */
769 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
770 counter = evlist_cpu_itr.evsel;
772 if (!counter->reset_group && !counter->errored)
775 perf_evsel__close_cpu(&counter->core, evlist_cpu_itr.cpu_map_idx);
777 /* Now reopen weak */
778 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
779 counter = evlist_cpu_itr.evsel;
781 if (!counter->reset_group)
784 pr_debug2("reopening weak %s\n", evsel__name(counter));
785 if (create_perf_stat_counter(counter, &stat_config, &target,
786 evlist_cpu_itr.cpu_map_idx) < 0) {
788 switch (stat_handle_error(counter)) {
792 goto try_again_reset;
799 counter->supported = true;
802 affinity__cleanup(affinity);
804 evlist__for_each_entry(evsel_list, counter) {
805 if (!counter->supported) {
806 perf_evsel__free_fd(&counter->core);
810 l = strlen(counter->unit);
811 if (l > stat_config.unit_width)
812 stat_config.unit_width = l;
814 if (evsel__should_store_id(counter) &&
815 evsel__store_ids(counter, evsel_list))
819 if (evlist__apply_filters(evsel_list, &counter)) {
820 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
821 counter->filter, evsel__name(counter), errno,
822 str_error_r(errno, msg, sizeof(msg)));
827 int fd = perf_data__fd(&perf_stat.data);
830 err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
832 err = perf_session__write_header(perf_stat.session, evsel_list,
839 err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
840 process_synthesized_event, is_pipe);
845 if (target.initial_delay) {
846 pr_info(EVLIST_DISABLED_MSG);
848 err = enable_counters();
853 /* Exec the command, if any */
855 evlist__start_workload(evsel_list);
857 if (target.initial_delay > 0) {
858 usleep(target.initial_delay * USEC_PER_MSEC);
859 err = enable_counters();
863 pr_info(EVLIST_ENABLED_MSG);
867 clock_gettime(CLOCK_MONOTONIC, &ref_time);
870 if (interval || timeout || evlist__ctlfd_initialized(evsel_list))
871 status = dispatch_events(forks, timeout, interval, ×);
872 if (child_pid != -1) {
874 kill(child_pid, SIGTERM);
875 wait4(child_pid, &status, 0, &stat_config.ru_data);
878 if (workload_exec_errno) {
879 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
880 pr_err("Workload failed: %s\n", emsg);
884 if (WIFSIGNALED(status))
885 psignal(WTERMSIG(status), argv[0]);
887 status = dispatch_events(forks, timeout, interval, ×);
894 if (stat_config.walltime_run_table)
895 stat_config.walltime_run[run_idx] = t1 - t0;
897 if (interval && stat_config.summary) {
898 stat_config.interval = 0;
899 stat_config.stop_read_counter = true;
900 init_stats(&walltime_nsecs_stats);
901 update_stats(&walltime_nsecs_stats, t1 - t0);
903 evlist__copy_prev_raw_counts(evsel_list);
904 evlist__reset_prev_raw_counts(evsel_list);
905 evlist__reset_aggr_stats(evsel_list);
907 update_stats(&walltime_nsecs_stats, t1 - t0);
908 update_rusage_stats(&ru_stats, &stat_config.ru_data);
912 * Closing a group leader splits the group, and as we only disable
913 * group leaders, results in remaining events becoming enabled. To
914 * avoid arbitrary skew, we must read all counters before closing any
917 if (read_counters(&(struct timespec) { .tv_nsec = t1-t0 }) == 0)
921 * We need to keep evsel_list alive, because it's processed
922 * later the evsel_list will be closed after.
925 evlist__close(evsel_list);
927 return WEXITSTATUS(status);
930 static int run_perf_stat(int argc, const char **argv, int run_idx)
935 ret = system(pre_cmd);
943 ret = __run_perf_stat(argc, argv, run_idx);
948 ret = system(post_cmd);
956 static void print_counters(struct timespec *ts, int argc, const char **argv)
958 /* Do not print anything if we record to the pipe. */
959 if (STAT_RECORD && perf_stat.data.is_pipe)
964 evlist__print_counters(evsel_list, &stat_config, &target, ts, argc, argv);
967 static volatile sig_atomic_t signr = -1;
969 static void skip_signal(int signo)
971 if ((child_pid == -1) || stat_config.interval)
976 * render child_pid harmless
977 * won't send SIGTERM to a random
978 * process in case of race condition
979 * and fast PID recycling
984 static void sig_atexit(void)
989 * avoid race condition with SIGCHLD handler
990 * in skip_signal() which is modifying child_pid
991 * goal is to avoid send SIGTERM to a random
995 sigaddset(&set, SIGCHLD);
996 sigprocmask(SIG_BLOCK, &set, &oset);
999 kill(child_pid, SIGTERM);
1001 sigprocmask(SIG_SETMASK, &oset, NULL);
1006 signal(signr, SIG_DFL);
1007 kill(getpid(), signr);
1010 void perf_stat__set_big_num(int set)
1012 stat_config.big_num = (set != 0);
1015 void perf_stat__set_no_csv_summary(int set)
1017 stat_config.no_csv_summary = (set != 0);
1020 static int stat__set_big_num(const struct option *opt __maybe_unused,
1021 const char *s __maybe_unused, int unset)
1023 big_num_opt = unset ? 0 : 1;
1024 perf_stat__set_big_num(!unset);
1028 static int enable_metric_only(const struct option *opt __maybe_unused,
1029 const char *s __maybe_unused, int unset)
1031 force_metric_only = true;
1032 stat_config.metric_only = !unset;
1036 static int append_metric_groups(const struct option *opt __maybe_unused,
1038 int unset __maybe_unused)
1043 if (asprintf(&tmp, "%s,%s", metrics, str) < 0)
1048 metrics = strdup(str);
1055 static int parse_control_option(const struct option *opt,
1057 int unset __maybe_unused)
1059 struct perf_stat_config *config = opt->value;
1061 return evlist__parse_control(str, &config->ctl_fd, &config->ctl_fd_ack, &config->ctl_fd_close);
1064 static int parse_stat_cgroups(const struct option *opt,
1065 const char *str, int unset)
1067 if (stat_config.cgroup_list) {
1068 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
1072 return parse_cgroups(opt, str, unset);
1075 static int parse_hybrid_type(const struct option *opt,
1077 int unset __maybe_unused)
1079 struct evlist *evlist = *(struct evlist **)opt->value;
1081 if (!list_empty(&evlist->core.entries)) {
1082 fprintf(stderr, "Must define cputype before events/metrics\n");
1086 evlist->hybrid_pmu_name = perf_pmu__hybrid_type_to_pmu(str);
1087 if (!evlist->hybrid_pmu_name) {
1088 fprintf(stderr, "--cputype %s is not supported!\n", str);
1095 static struct option stat_options[] = {
1096 OPT_BOOLEAN('T', "transaction", &transaction_run,
1097 "hardware transaction statistics"),
1098 OPT_CALLBACK('e', "event", &evsel_list, "event",
1099 "event selector. use 'perf list' to list available events",
1100 parse_events_option),
1101 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1102 "event filter", parse_filter),
1103 OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
1104 "child tasks do not inherit counters"),
1105 OPT_STRING('p', "pid", &target.pid, "pid",
1106 "stat events on existing process id"),
1107 OPT_STRING('t', "tid", &target.tid, "tid",
1108 "stat events on existing thread id"),
1109 #ifdef HAVE_BPF_SKEL
1110 OPT_STRING('b', "bpf-prog", &target.bpf_str, "bpf-prog-id",
1111 "stat events on existing bpf program id"),
1112 OPT_BOOLEAN(0, "bpf-counters", &target.use_bpf,
1113 "use bpf program to count events"),
1114 OPT_STRING(0, "bpf-attr-map", &target.attr_map, "attr-map-path",
1115 "path to perf_event_attr map"),
1117 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1118 "system-wide collection from all CPUs"),
1119 OPT_BOOLEAN(0, "scale", &stat_config.scale,
1120 "Use --no-scale to disable counter scaling for multiplexing"),
1121 OPT_INCR('v', "verbose", &verbose,
1122 "be more verbose (show counter open errors, etc)"),
1123 OPT_INTEGER('r', "repeat", &stat_config.run_count,
1124 "repeat command and print average + stddev (max: 100, forever: 0)"),
1125 OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
1126 "display details about each run (only with -r option)"),
1127 OPT_BOOLEAN('n', "null", &stat_config.null_run,
1128 "null run - dont start any counters"),
1129 OPT_INCR('d', "detailed", &detailed_run,
1130 "detailed run - start a lot of events"),
1131 OPT_BOOLEAN('S', "sync", &sync_run,
1132 "call sync() before starting a run"),
1133 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1134 "print large numbers with thousands\' separators",
1136 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1137 "list of cpus to monitor in system-wide"),
1138 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1139 "disable CPU count aggregation", AGGR_NONE),
1140 OPT_BOOLEAN(0, "no-merge", &stat_config.no_merge, "Do not merge identical named events"),
1141 OPT_BOOLEAN(0, "hybrid-merge", &stat_config.hybrid_merge,
1142 "Merge identical named hybrid events"),
1143 OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
1144 "print counts with custom separator"),
1145 OPT_BOOLEAN('j', "json-output", &stat_config.json_output,
1146 "print counts in JSON format"),
1147 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1148 "monitor event in cgroup name only", parse_stat_cgroups),
1149 OPT_STRING(0, "for-each-cgroup", &stat_config.cgroup_list, "name",
1150 "expand events for each cgroup"),
1151 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1152 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1153 OPT_INTEGER(0, "log-fd", &output_fd,
1154 "log output to fd, instead of stderr"),
1155 OPT_STRING(0, "pre", &pre_cmd, "command",
1156 "command to run prior to the measured command"),
1157 OPT_STRING(0, "post", &post_cmd, "command",
1158 "command to run after to the measured command"),
1159 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1160 "print counts at regular interval in ms "
1161 "(overhead is possible for values <= 100ms)"),
1162 OPT_INTEGER(0, "interval-count", &stat_config.times,
1163 "print counts for fixed number of times"),
1164 OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
1165 "clear screen in between new interval"),
1166 OPT_UINTEGER(0, "timeout", &stat_config.timeout,
1167 "stop workload and print counts after a timeout period in ms (>= 10ms)"),
1168 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1169 "aggregate counts per processor socket", AGGR_SOCKET),
1170 OPT_SET_UINT(0, "per-die", &stat_config.aggr_mode,
1171 "aggregate counts per processor die", AGGR_DIE),
1172 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1173 "aggregate counts per physical processor core", AGGR_CORE),
1174 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1175 "aggregate counts per thread", AGGR_THREAD),
1176 OPT_SET_UINT(0, "per-node", &stat_config.aggr_mode,
1177 "aggregate counts per numa node", AGGR_NODE),
1178 OPT_INTEGER('D', "delay", &target.initial_delay,
1179 "ms to wait before starting measurement after program start (-1: start with events disabled)"),
1180 OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
1181 "Only print computed metrics. No raw values", enable_metric_only),
1182 OPT_BOOLEAN(0, "metric-no-group", &stat_config.metric_no_group,
1183 "don't group metric events, impacts multiplexing"),
1184 OPT_BOOLEAN(0, "metric-no-merge", &stat_config.metric_no_merge,
1185 "don't try to share events between metrics in a group"),
1186 OPT_BOOLEAN(0, "metric-no-threshold", &stat_config.metric_no_threshold,
1187 "don't try to share events between metrics in a group "),
1188 OPT_BOOLEAN(0, "topdown", &topdown_run,
1189 "measure top-down statistics"),
1190 OPT_UINTEGER(0, "td-level", &stat_config.topdown_level,
1191 "Set the metrics level for the top-down statistics (0: max level)"),
1192 OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1193 "measure SMI cost"),
1194 OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1195 "monitor specified metrics or metric groups (separated by ,)",
1196 append_metric_groups),
1197 OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
1198 "Configure all used events to run in kernel space.",
1199 PARSE_OPT_EXCLUSIVE),
1200 OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
1201 "Configure all used events to run in user space.",
1202 PARSE_OPT_EXCLUSIVE),
1203 OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
1204 "Use with 'percore' event qualifier to show the event "
1205 "counts of one hardware thread by sum up total hardware "
1206 "threads of same physical core"),
1207 OPT_BOOLEAN(0, "summary", &stat_config.summary,
1208 "print summary for interval mode"),
1209 OPT_BOOLEAN(0, "no-csv-summary", &stat_config.no_csv_summary,
1210 "don't print 'summary' for CSV summary output"),
1211 OPT_BOOLEAN(0, "quiet", &quiet,
1212 "don't print any output, messages or warnings (useful with record)"),
1213 OPT_CALLBACK(0, "cputype", &evsel_list, "hybrid cpu type",
1214 "Only enable events on applying cpu with this type "
1215 "for hybrid platform (e.g. core or atom)",
1218 OPT_CALLBACK(0, "pfm-events", &evsel_list, "event",
1219 "libpfm4 event selector. use 'perf list' to list available events",
1220 parse_libpfm_events_option),
1222 OPT_CALLBACK(0, "control", &stat_config, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]",
1223 "Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events).\n"
1224 "\t\t\t Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n"
1225 "\t\t\t Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.",
1226 parse_control_option),
1227 OPT_CALLBACK_OPTARG(0, "iostat", &evsel_list, &stat_config, "default",
1228 "measure I/O performance metrics provided by arch/platform",
1233 static const char *const aggr_mode__string[] = {
1234 [AGGR_CORE] = "core",
1236 [AGGR_GLOBAL] = "global",
1237 [AGGR_NODE] = "node",
1238 [AGGR_NONE] = "none",
1239 [AGGR_SOCKET] = "socket",
1240 [AGGR_THREAD] = "thread",
1241 [AGGR_UNSET] = "unset",
1244 static struct aggr_cpu_id perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
1245 struct perf_cpu cpu)
1247 return aggr_cpu_id__socket(cpu, /*data=*/NULL);
1250 static struct aggr_cpu_id perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
1251 struct perf_cpu cpu)
1253 return aggr_cpu_id__die(cpu, /*data=*/NULL);
1256 static struct aggr_cpu_id perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
1257 struct perf_cpu cpu)
1259 return aggr_cpu_id__core(cpu, /*data=*/NULL);
1262 static struct aggr_cpu_id perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
1263 struct perf_cpu cpu)
1265 return aggr_cpu_id__node(cpu, /*data=*/NULL);
1268 static struct aggr_cpu_id perf_stat__get_global(struct perf_stat_config *config __maybe_unused,
1269 struct perf_cpu cpu)
1271 return aggr_cpu_id__global(cpu, /*data=*/NULL);
1274 static struct aggr_cpu_id perf_stat__get_cpu(struct perf_stat_config *config __maybe_unused,
1275 struct perf_cpu cpu)
1277 return aggr_cpu_id__cpu(cpu, /*data=*/NULL);
1280 static struct aggr_cpu_id perf_stat__get_aggr(struct perf_stat_config *config,
1281 aggr_get_id_t get_id, struct perf_cpu cpu)
1283 struct aggr_cpu_id id;
1285 /* per-process mode - should use global aggr mode */
1287 return get_id(config, cpu);
1289 if (aggr_cpu_id__is_empty(&config->cpus_aggr_map->map[cpu.cpu]))
1290 config->cpus_aggr_map->map[cpu.cpu] = get_id(config, cpu);
1292 id = config->cpus_aggr_map->map[cpu.cpu];
1296 static struct aggr_cpu_id perf_stat__get_socket_cached(struct perf_stat_config *config,
1297 struct perf_cpu cpu)
1299 return perf_stat__get_aggr(config, perf_stat__get_socket, cpu);
1302 static struct aggr_cpu_id perf_stat__get_die_cached(struct perf_stat_config *config,
1303 struct perf_cpu cpu)
1305 return perf_stat__get_aggr(config, perf_stat__get_die, cpu);
1308 static struct aggr_cpu_id perf_stat__get_core_cached(struct perf_stat_config *config,
1309 struct perf_cpu cpu)
1311 return perf_stat__get_aggr(config, perf_stat__get_core, cpu);
1314 static struct aggr_cpu_id perf_stat__get_node_cached(struct perf_stat_config *config,
1315 struct perf_cpu cpu)
1317 return perf_stat__get_aggr(config, perf_stat__get_node, cpu);
1320 static struct aggr_cpu_id perf_stat__get_global_cached(struct perf_stat_config *config,
1321 struct perf_cpu cpu)
1323 return perf_stat__get_aggr(config, perf_stat__get_global, cpu);
1326 static struct aggr_cpu_id perf_stat__get_cpu_cached(struct perf_stat_config *config,
1327 struct perf_cpu cpu)
1329 return perf_stat__get_aggr(config, perf_stat__get_cpu, cpu);
1332 static aggr_cpu_id_get_t aggr_mode__get_aggr(enum aggr_mode aggr_mode)
1334 switch (aggr_mode) {
1336 return aggr_cpu_id__socket;
1338 return aggr_cpu_id__die;
1340 return aggr_cpu_id__core;
1342 return aggr_cpu_id__node;
1344 return aggr_cpu_id__cpu;
1346 return aggr_cpu_id__global;
1355 static aggr_get_id_t aggr_mode__get_id(enum aggr_mode aggr_mode)
1357 switch (aggr_mode) {
1359 return perf_stat__get_socket_cached;
1361 return perf_stat__get_die_cached;
1363 return perf_stat__get_core_cached;
1365 return perf_stat__get_node_cached;
1367 return perf_stat__get_cpu_cached;
1369 return perf_stat__get_global_cached;
1378 static int perf_stat_init_aggr_mode(void)
1381 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr(stat_config.aggr_mode);
1384 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1385 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1386 get_id, /*data=*/NULL, needs_sort);
1387 if (!stat_config.aggr_map) {
1388 pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
1391 stat_config.aggr_get_id = aggr_mode__get_id(stat_config.aggr_mode);
1394 if (stat_config.aggr_mode == AGGR_THREAD) {
1395 nr = perf_thread_map__nr(evsel_list->core.threads);
1396 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1397 if (stat_config.aggr_map == NULL)
1400 for (int s = 0; s < nr; s++) {
1401 struct aggr_cpu_id id = aggr_cpu_id__empty();
1404 stat_config.aggr_map->map[s] = id;
1410 * The evsel_list->cpus is the base we operate on,
1411 * taking the highest cpu number to be the size of
1412 * the aggregation translate cpumap.
1414 if (evsel_list->core.user_requested_cpus)
1415 nr = perf_cpu_map__max(evsel_list->core.user_requested_cpus).cpu;
1418 stat_config.cpus_aggr_map = cpu_aggr_map__empty_new(nr + 1);
1419 return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
1422 static void cpu_aggr_map__delete(struct cpu_aggr_map *map)
1425 WARN_ONCE(refcount_read(&map->refcnt) != 0,
1426 "cpu_aggr_map refcnt unbalanced\n");
1431 static void cpu_aggr_map__put(struct cpu_aggr_map *map)
1433 if (map && refcount_dec_and_test(&map->refcnt))
1434 cpu_aggr_map__delete(map);
1437 static void perf_stat__exit_aggr_mode(void)
1439 cpu_aggr_map__put(stat_config.aggr_map);
1440 cpu_aggr_map__put(stat_config.cpus_aggr_map);
1441 stat_config.aggr_map = NULL;
1442 stat_config.cpus_aggr_map = NULL;
1445 static struct aggr_cpu_id perf_env__get_socket_aggr_by_cpu(struct perf_cpu cpu, void *data)
1447 struct perf_env *env = data;
1448 struct aggr_cpu_id id = aggr_cpu_id__empty();
1451 id.socket = env->cpu[cpu.cpu].socket_id;
1456 static struct aggr_cpu_id perf_env__get_die_aggr_by_cpu(struct perf_cpu cpu, void *data)
1458 struct perf_env *env = data;
1459 struct aggr_cpu_id id = aggr_cpu_id__empty();
1461 if (cpu.cpu != -1) {
1463 * die_id is relative to socket, so start
1464 * with the socket ID and then add die to
1467 id.socket = env->cpu[cpu.cpu].socket_id;
1468 id.die = env->cpu[cpu.cpu].die_id;
1474 static struct aggr_cpu_id perf_env__get_core_aggr_by_cpu(struct perf_cpu cpu, void *data)
1476 struct perf_env *env = data;
1477 struct aggr_cpu_id id = aggr_cpu_id__empty();
1479 if (cpu.cpu != -1) {
1481 * core_id is relative to socket and die,
1482 * we need a global id. So we set
1483 * socket, die id and core id
1485 id.socket = env->cpu[cpu.cpu].socket_id;
1486 id.die = env->cpu[cpu.cpu].die_id;
1487 id.core = env->cpu[cpu.cpu].core_id;
1493 static struct aggr_cpu_id perf_env__get_cpu_aggr_by_cpu(struct perf_cpu cpu, void *data)
1495 struct perf_env *env = data;
1496 struct aggr_cpu_id id = aggr_cpu_id__empty();
1498 if (cpu.cpu != -1) {
1500 * core_id is relative to socket and die,
1501 * we need a global id. So we set
1502 * socket, die id and core id
1504 id.socket = env->cpu[cpu.cpu].socket_id;
1505 id.die = env->cpu[cpu.cpu].die_id;
1506 id.core = env->cpu[cpu.cpu].core_id;
1513 static struct aggr_cpu_id perf_env__get_node_aggr_by_cpu(struct perf_cpu cpu, void *data)
1515 struct aggr_cpu_id id = aggr_cpu_id__empty();
1517 id.node = perf_env__numa_node(data, cpu);
1521 static struct aggr_cpu_id perf_env__get_global_aggr_by_cpu(struct perf_cpu cpu __maybe_unused,
1522 void *data __maybe_unused)
1524 struct aggr_cpu_id id = aggr_cpu_id__empty();
1526 /* it always aggregates to the cpu 0 */
1527 id.cpu = (struct perf_cpu){ .cpu = 0 };
1531 static struct aggr_cpu_id perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
1532 struct perf_cpu cpu)
1534 return perf_env__get_socket_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1536 static struct aggr_cpu_id perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
1537 struct perf_cpu cpu)
1539 return perf_env__get_die_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1542 static struct aggr_cpu_id perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
1543 struct perf_cpu cpu)
1545 return perf_env__get_core_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1548 static struct aggr_cpu_id perf_stat__get_cpu_file(struct perf_stat_config *config __maybe_unused,
1549 struct perf_cpu cpu)
1551 return perf_env__get_cpu_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1554 static struct aggr_cpu_id perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
1555 struct perf_cpu cpu)
1557 return perf_env__get_node_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1560 static struct aggr_cpu_id perf_stat__get_global_file(struct perf_stat_config *config __maybe_unused,
1561 struct perf_cpu cpu)
1563 return perf_env__get_global_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1566 static aggr_cpu_id_get_t aggr_mode__get_aggr_file(enum aggr_mode aggr_mode)
1568 switch (aggr_mode) {
1570 return perf_env__get_socket_aggr_by_cpu;
1572 return perf_env__get_die_aggr_by_cpu;
1574 return perf_env__get_core_aggr_by_cpu;
1576 return perf_env__get_node_aggr_by_cpu;
1578 return perf_env__get_global_aggr_by_cpu;
1580 return perf_env__get_cpu_aggr_by_cpu;
1589 static aggr_get_id_t aggr_mode__get_id_file(enum aggr_mode aggr_mode)
1591 switch (aggr_mode) {
1593 return perf_stat__get_socket_file;
1595 return perf_stat__get_die_file;
1597 return perf_stat__get_core_file;
1599 return perf_stat__get_node_file;
1601 return perf_stat__get_global_file;
1603 return perf_stat__get_cpu_file;
1612 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1614 struct perf_env *env = &st->session->header.env;
1615 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr_file(stat_config.aggr_mode);
1616 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1618 if (stat_config.aggr_mode == AGGR_THREAD) {
1619 int nr = perf_thread_map__nr(evsel_list->core.threads);
1621 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1622 if (stat_config.aggr_map == NULL)
1625 for (int s = 0; s < nr; s++) {
1626 struct aggr_cpu_id id = aggr_cpu_id__empty();
1629 stat_config.aggr_map->map[s] = id;
1637 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1638 get_id, env, needs_sort);
1639 if (!stat_config.aggr_map) {
1640 pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
1643 stat_config.aggr_get_id = aggr_mode__get_id_file(stat_config.aggr_mode);
1648 * Add default attributes, if there were no attributes specified or
1649 * if -d/--detailed, -d -d or -d -d -d is used:
1651 static int add_default_attributes(void)
1653 struct perf_event_attr default_attrs0[] = {
1655 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
1656 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
1657 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
1658 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
1660 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
1662 struct perf_event_attr frontend_attrs[] = {
1663 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1665 struct perf_event_attr backend_attrs[] = {
1666 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
1668 struct perf_event_attr default_attrs1[] = {
1669 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
1670 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
1671 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
1676 * Detailed stats (-d), covering the L1 and last level data caches:
1678 struct perf_event_attr detailed_attrs[] = {
1680 { .type = PERF_TYPE_HW_CACHE,
1682 PERF_COUNT_HW_CACHE_L1D << 0 |
1683 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1684 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
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_MISS << 16) },
1692 { .type = PERF_TYPE_HW_CACHE,
1694 PERF_COUNT_HW_CACHE_LL << 0 |
1695 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1696 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 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_MISS << 16) },
1706 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1708 struct perf_event_attr very_detailed_attrs[] = {
1710 { .type = PERF_TYPE_HW_CACHE,
1712 PERF_COUNT_HW_CACHE_L1I << 0 |
1713 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1714 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
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_MISS << 16) },
1722 { .type = PERF_TYPE_HW_CACHE,
1724 PERF_COUNT_HW_CACHE_DTLB << 0 |
1725 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1726 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 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_MISS << 16) },
1734 { .type = PERF_TYPE_HW_CACHE,
1736 PERF_COUNT_HW_CACHE_ITLB << 0 |
1737 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1738 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 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_MISS << 16) },
1749 * Very, very detailed stats (-d -d -d), adding prefetch events:
1751 struct perf_event_attr very_very_detailed_attrs[] = {
1753 { .type = PERF_TYPE_HW_CACHE,
1755 PERF_COUNT_HW_CACHE_L1D << 0 |
1756 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1757 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
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_MISS << 16) },
1766 struct perf_event_attr default_null_attrs[] = {};
1768 /* Set attrs if no event is selected and !null_run: */
1769 if (stat_config.null_run)
1772 if (transaction_run) {
1773 /* Handle -T as -M transaction. Once platform specific metrics
1774 * support has been added to the json files, all architectures
1775 * will use this approach. To determine transaction support
1776 * on an architecture test for such a metric name.
1778 if (!metricgroup__has_metric("transaction")) {
1779 pr_err("Missing transaction metrics");
1782 return metricgroup__parse_groups(evsel_list, "transaction",
1783 stat_config.metric_no_group,
1784 stat_config.metric_no_merge,
1785 stat_config.metric_no_threshold,
1786 stat_config.user_requested_cpu_list,
1787 stat_config.system_wide,
1788 &stat_config.metric_events);
1794 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
1795 pr_err("freeze_on_smi is not supported.");
1800 if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
1801 fprintf(stderr, "Failed to set freeze_on_smi.\n");
1807 if (!metricgroup__has_metric("smi")) {
1808 pr_err("Missing smi metrics");
1812 if (!force_metric_only)
1813 stat_config.metric_only = true;
1815 return metricgroup__parse_groups(evsel_list, "smi",
1816 stat_config.metric_no_group,
1817 stat_config.metric_no_merge,
1818 stat_config.metric_no_threshold,
1819 stat_config.user_requested_cpu_list,
1820 stat_config.system_wide,
1821 &stat_config.metric_events);
1825 unsigned int max_level = metricgroups__topdown_max_level();
1826 char str[] = "TopdownL1";
1828 if (!force_metric_only)
1829 stat_config.metric_only = true;
1832 pr_err("Topdown requested but the topdown metric groups aren't present.\n"
1833 "(See perf list the metric groups have names like TopdownL1)");
1836 if (stat_config.topdown_level > max_level) {
1837 pr_err("Invalid top-down metrics level. The max level is %u.\n", max_level);
1839 } else if (!stat_config.topdown_level)
1840 stat_config.topdown_level = 1;
1842 if (!stat_config.interval && !stat_config.metric_only) {
1843 fprintf(stat_config.output,
1844 "Topdown accuracy may decrease when measuring long periods.\n"
1845 "Please print the result regularly, e.g. -I1000\n");
1847 str[8] = stat_config.topdown_level + '0';
1848 if (metricgroup__parse_groups(evsel_list, str,
1849 /*metric_no_group=*/false,
1850 /*metric_no_merge=*/false,
1851 /*metric_no_threshold=*/true,
1852 stat_config.user_requested_cpu_list,
1853 stat_config.system_wide,
1854 &stat_config.metric_events) < 0)
1858 if (!stat_config.topdown_level)
1859 stat_config.topdown_level = 1;
1861 if (!evsel_list->core.nr_entries) {
1862 /* No events so add defaults. */
1863 if (target__has_cpu(&target))
1864 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
1866 if (evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
1868 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
1869 if (evlist__add_default_attrs(evsel_list, frontend_attrs) < 0)
1872 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
1873 if (evlist__add_default_attrs(evsel_list, backend_attrs) < 0)
1876 if (evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
1879 * Add TopdownL1 metrics if they exist. To minimize
1880 * multiplexing, don't request threshold computation.
1882 if (metricgroup__has_metric("TopdownL1") &&
1883 metricgroup__parse_groups(evsel_list, "TopdownL1",
1884 /*metric_no_group=*/false,
1885 /*metric_no_merge=*/false,
1886 /*metric_no_threshold=*/true,
1887 stat_config.user_requested_cpu_list,
1888 stat_config.system_wide,
1889 &stat_config.metric_events) < 0)
1891 /* Platform specific attrs */
1892 if (evlist__add_default_attrs(evsel_list, default_null_attrs) < 0)
1896 /* Detailed events get appended to the event list: */
1898 if (detailed_run < 1)
1901 /* Append detailed run extra attributes: */
1902 if (evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1905 if (detailed_run < 2)
1908 /* Append very detailed run extra attributes: */
1909 if (evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1912 if (detailed_run < 3)
1915 /* Append very, very detailed run extra attributes: */
1916 return evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1919 static const char * const stat_record_usage[] = {
1920 "perf stat record [<options>]",
1924 static void init_features(struct perf_session *session)
1928 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
1929 perf_header__set_feat(&session->header, feat);
1931 perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
1932 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
1933 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
1934 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
1935 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
1938 static int __cmd_record(int argc, const char **argv)
1940 struct perf_session *session;
1941 struct perf_data *data = &perf_stat.data;
1943 argc = parse_options(argc, argv, stat_options, stat_record_usage,
1944 PARSE_OPT_STOP_AT_NON_OPTION);
1947 data->path = output_name;
1949 if (stat_config.run_count != 1 || forever) {
1950 pr_err("Cannot use -r option with perf stat record.\n");
1954 session = perf_session__new(data, NULL);
1955 if (IS_ERR(session)) {
1956 pr_err("Perf session creation failed\n");
1957 return PTR_ERR(session);
1960 init_features(session);
1962 session->evlist = evsel_list;
1963 perf_stat.session = session;
1964 perf_stat.record = true;
1968 static int process_stat_round_event(struct perf_session *session,
1969 union perf_event *event)
1971 struct perf_record_stat_round *stat_round = &event->stat_round;
1972 struct timespec tsh, *ts = NULL;
1973 const char **argv = session->header.env.cmdline_argv;
1974 int argc = session->header.env.nr_cmdline;
1978 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
1979 update_stats(&walltime_nsecs_stats, stat_round->time);
1981 if (stat_config.interval && stat_round->time) {
1982 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
1983 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
1987 print_counters(ts, argc, argv);
1992 int process_stat_config_event(struct perf_session *session,
1993 union perf_event *event)
1995 struct perf_tool *tool = session->tool;
1996 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1998 perf_event__read_stat_config(&stat_config, &event->stat_config);
2000 if (perf_cpu_map__empty(st->cpus)) {
2001 if (st->aggr_mode != AGGR_UNSET)
2002 pr_warning("warning: processing task data, aggregation mode not set\n");
2003 } else if (st->aggr_mode != AGGR_UNSET) {
2004 stat_config.aggr_mode = st->aggr_mode;
2007 if (perf_stat.data.is_pipe)
2008 perf_stat_init_aggr_mode();
2010 perf_stat_init_aggr_mode_file(st);
2012 if (stat_config.aggr_map) {
2013 int nr_aggr = stat_config.aggr_map->nr;
2015 if (evlist__alloc_aggr_stats(session->evlist, nr_aggr) < 0) {
2016 pr_err("cannot allocate aggr counts\n");
2023 static int set_maps(struct perf_stat *st)
2025 if (!st->cpus || !st->threads)
2028 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2031 perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
2033 if (evlist__alloc_stats(&stat_config, evsel_list, /*alloc_raw=*/true))
2036 st->maps_allocated = true;
2041 int process_thread_map_event(struct perf_session *session,
2042 union perf_event *event)
2044 struct perf_tool *tool = session->tool;
2045 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2048 pr_warning("Extra thread map event, ignoring.\n");
2052 st->threads = thread_map__new_event(&event->thread_map);
2056 return set_maps(st);
2060 int process_cpu_map_event(struct perf_session *session,
2061 union perf_event *event)
2063 struct perf_tool *tool = session->tool;
2064 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2065 struct perf_cpu_map *cpus;
2068 pr_warning("Extra cpu map event, ignoring.\n");
2072 cpus = cpu_map__new_data(&event->cpu_map.data);
2077 return set_maps(st);
2080 static const char * const stat_report_usage[] = {
2081 "perf stat report [<options>]",
2085 static struct perf_stat perf_stat = {
2087 .attr = perf_event__process_attr,
2088 .event_update = perf_event__process_event_update,
2089 .thread_map = process_thread_map_event,
2090 .cpu_map = process_cpu_map_event,
2091 .stat_config = process_stat_config_event,
2092 .stat = perf_event__process_stat_event,
2093 .stat_round = process_stat_round_event,
2095 .aggr_mode = AGGR_UNSET,
2098 static int __cmd_report(int argc, const char **argv)
2100 struct perf_session *session;
2101 const struct option options[] = {
2102 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2103 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2104 "aggregate counts per processor socket", AGGR_SOCKET),
2105 OPT_SET_UINT(0, "per-die", &perf_stat.aggr_mode,
2106 "aggregate counts per processor die", AGGR_DIE),
2107 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2108 "aggregate counts per physical processor core", AGGR_CORE),
2109 OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
2110 "aggregate counts per numa node", AGGR_NODE),
2111 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2112 "disable CPU count aggregation", AGGR_NONE),
2118 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2120 if (!input_name || !strlen(input_name)) {
2121 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2124 input_name = "perf.data";
2127 perf_stat.data.path = input_name;
2128 perf_stat.data.mode = PERF_DATA_MODE_READ;
2130 session = perf_session__new(&perf_stat.data, &perf_stat.tool);
2131 if (IS_ERR(session))
2132 return PTR_ERR(session);
2134 perf_stat.session = session;
2135 stat_config.output = stderr;
2136 evsel_list = session->evlist;
2138 ret = perf_session__process_events(session);
2142 perf_session__delete(session);
2146 static void setup_system_wide(int forks)
2149 * Make system wide (-a) the default target if
2150 * no target was specified and one of following
2151 * conditions is met:
2153 * - there's no workload specified
2154 * - there is workload specified but all requested
2155 * events are system wide events
2157 if (!target__none(&target))
2161 target.system_wide = true;
2163 struct evsel *counter;
2165 evlist__for_each_entry(evsel_list, counter) {
2166 if (!counter->core.requires_cpu &&
2167 strcmp(counter->name, "duration_time")) {
2172 if (evsel_list->core.nr_entries)
2173 target.system_wide = true;
2177 int cmd_stat(int argc, const char **argv)
2179 const char * const stat_usage[] = {
2180 "perf stat [<options>] [<command>]",
2183 int status = -EINVAL, run_idx, err;
2185 FILE *output = stderr;
2186 unsigned int interval, timeout;
2187 const char * const stat_subcommands[] = { "record", "report" };
2188 char errbuf[BUFSIZ];
2190 setlocale(LC_ALL, "");
2192 evsel_list = evlist__new();
2193 if (evsel_list == NULL)
2196 parse_events__shrink_config_terms();
2198 /* String-parsing callback-based options would segfault when negated */
2199 set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
2200 set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
2201 set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
2203 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2204 (const char **) stat_usage,
2205 PARSE_OPT_STOP_AT_NON_OPTION);
2207 if (stat_config.csv_sep) {
2208 stat_config.csv_output = true;
2209 if (!strcmp(stat_config.csv_sep, "\\t"))
2210 stat_config.csv_sep = "\t";
2212 stat_config.csv_sep = DEFAULT_SEPARATOR;
2214 if (argc && strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
2215 argc = __cmd_record(argc, argv);
2218 } else if (argc && strlen(argv[0]) > 2 && strstarts("report", argv[0]))
2219 return __cmd_report(argc, argv);
2221 interval = stat_config.interval;
2222 timeout = stat_config.timeout;
2225 * For record command the -o is already taken care of.
2227 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2230 if (output_name && output_fd) {
2231 fprintf(stderr, "cannot use both --output and --log-fd\n");
2232 parse_options_usage(stat_usage, stat_options, "o", 1);
2233 parse_options_usage(NULL, stat_options, "log-fd", 0);
2237 if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2238 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2242 if (stat_config.metric_only && stat_config.run_count > 1) {
2243 fprintf(stderr, "--metric-only is not supported with -r\n");
2247 if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
2248 fprintf(stderr, "--table is only supported with -r\n");
2249 parse_options_usage(stat_usage, stat_options, "r", 1);
2250 parse_options_usage(NULL, stat_options, "table", 0);
2254 if (output_fd < 0) {
2255 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2256 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2260 if (!output && !quiet) {
2262 mode = append_file ? "a" : "w";
2264 output = fopen(output_name, mode);
2266 perror("failed to create output file");
2269 clock_gettime(CLOCK_REALTIME, &tm);
2270 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2271 } else if (output_fd > 0) {
2272 mode = append_file ? "a" : "w";
2273 output = fdopen(output_fd, mode);
2275 perror("Failed opening logfd");
2280 if (stat_config.interval_clear && !isatty(fileno(output))) {
2281 fprintf(stderr, "--interval-clear does not work with output\n");
2282 parse_options_usage(stat_usage, stat_options, "o", 1);
2283 parse_options_usage(NULL, stat_options, "log-fd", 0);
2284 parse_options_usage(NULL, stat_options, "interval-clear", 0);
2288 stat_config.output = output;
2291 * let the spreadsheet do the pretty-printing
2293 if (stat_config.csv_output) {
2294 /* User explicitly passed -B? */
2295 if (big_num_opt == 1) {
2296 fprintf(stderr, "-B option not supported with -x\n");
2297 parse_options_usage(stat_usage, stat_options, "B", 1);
2298 parse_options_usage(NULL, stat_options, "x", 1);
2300 } else /* Nope, so disable big number formatting */
2301 stat_config.big_num = false;
2302 } else if (big_num_opt == 0) /* User passed --no-big-num */
2303 stat_config.big_num = false;
2305 err = target__validate(&target);
2307 target__strerror(&target, err, errbuf, BUFSIZ);
2308 pr_warning("%s\n", errbuf);
2311 setup_system_wide(argc);
2314 * Display user/system times only for single
2315 * run and when there's specified tracee.
2317 if ((stat_config.run_count == 1) && target__none(&target))
2318 stat_config.ru_display = true;
2320 if (stat_config.run_count < 0) {
2321 pr_err("Run count must be a positive number\n");
2322 parse_options_usage(stat_usage, stat_options, "r", 1);
2324 } else if (stat_config.run_count == 0) {
2326 stat_config.run_count = 1;
2329 if (stat_config.walltime_run_table) {
2330 stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
2331 if (!stat_config.walltime_run) {
2332 pr_err("failed to setup -r option");
2337 if ((stat_config.aggr_mode == AGGR_THREAD) &&
2338 !target__has_task(&target)) {
2339 if (!target.system_wide || target.cpu_list) {
2340 fprintf(stderr, "The --per-thread option is only "
2341 "available when monitoring via -p -t -a "
2342 "options or only --per-thread.\n");
2343 parse_options_usage(NULL, stat_options, "p", 1);
2344 parse_options_usage(NULL, stat_options, "t", 1);
2350 * no_aggr, cgroup are for system-wide only
2351 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2353 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2354 stat_config.aggr_mode != AGGR_THREAD) ||
2355 (nr_cgroups || stat_config.cgroup_list)) &&
2356 !target__has_cpu(&target)) {
2357 fprintf(stderr, "both cgroup and no-aggregation "
2358 "modes only available in system-wide mode\n");
2360 parse_options_usage(stat_usage, stat_options, "G", 1);
2361 parse_options_usage(NULL, stat_options, "A", 1);
2362 parse_options_usage(NULL, stat_options, "a", 1);
2363 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2367 if (stat_config.iostat_run) {
2368 status = iostat_prepare(evsel_list, &stat_config);
2371 if (iostat_mode == IOSTAT_LIST) {
2372 iostat_list(evsel_list, &stat_config);
2374 } else if (verbose > 0)
2375 iostat_list(evsel_list, &stat_config);
2376 if (iostat_mode == IOSTAT_RUN && !target__has_cpu(&target))
2377 target.system_wide = true;
2380 if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2381 target.per_thread = true;
2383 stat_config.system_wide = target.system_wide;
2384 if (target.cpu_list) {
2385 stat_config.user_requested_cpu_list = strdup(target.cpu_list);
2386 if (!stat_config.user_requested_cpu_list) {
2393 * Metric parsing needs to be delayed as metrics may optimize events
2394 * knowing the target is system-wide.
2397 metricgroup__parse_groups(evsel_list, metrics,
2398 stat_config.metric_no_group,
2399 stat_config.metric_no_merge,
2400 stat_config.metric_no_threshold,
2401 stat_config.user_requested_cpu_list,
2402 stat_config.system_wide,
2403 &stat_config.metric_events);
2407 if (add_default_attributes())
2410 if (stat_config.cgroup_list) {
2411 if (nr_cgroups > 0) {
2412 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
2413 parse_options_usage(stat_usage, stat_options, "G", 1);
2414 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2418 if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list,
2419 &stat_config.metric_events, true) < 0) {
2420 parse_options_usage(stat_usage, stat_options,
2421 "for-each-cgroup", 0);
2426 if (evlist__fix_hybrid_cpus(evsel_list, target.cpu_list)) {
2427 pr_err("failed to use cpu list %s\n", target.cpu_list);
2431 target.hybrid = perf_pmu__has_hybrid();
2432 if (evlist__create_maps(evsel_list, &target) < 0) {
2433 if (target__has_task(&target)) {
2434 pr_err("Problems finding threads of monitor\n");
2435 parse_options_usage(stat_usage, stat_options, "p", 1);
2436 parse_options_usage(NULL, stat_options, "t", 1);
2437 } else if (target__has_cpu(&target)) {
2438 perror("failed to parse CPUs map");
2439 parse_options_usage(stat_usage, stat_options, "C", 1);
2440 parse_options_usage(NULL, stat_options, "a", 1);
2445 evlist__check_cpu_maps(evsel_list);
2448 * Initialize thread_map with comm names,
2449 * so we could print it out on output.
2451 if (stat_config.aggr_mode == AGGR_THREAD) {
2452 thread_map__read_comms(evsel_list->core.threads);
2455 if (stat_config.aggr_mode == AGGR_NODE)
2456 cpu__setup_cpunode_map();
2458 if (stat_config.times && interval)
2459 interval_count = true;
2460 else if (stat_config.times && !interval) {
2461 pr_err("interval-count option should be used together with "
2462 "interval-print.\n");
2463 parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2464 parse_options_usage(stat_usage, stat_options, "I", 1);
2468 if (timeout && timeout < 100) {
2470 pr_err("timeout must be >= 10ms.\n");
2471 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2474 pr_warning("timeout < 100ms. "
2475 "The overhead percentage could be high in some cases. "
2476 "Please proceed with caution.\n");
2478 if (timeout && interval) {
2479 pr_err("timeout option is not supported with interval-print.\n");
2480 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2481 parse_options_usage(stat_usage, stat_options, "I", 1);
2485 if (perf_stat_init_aggr_mode())
2488 if (evlist__alloc_stats(&stat_config, evsel_list, interval))
2492 * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2493 * while avoiding that older tools show confusing messages.
2495 * However for pipe sessions we need to keep it zero,
2496 * because script's perf_evsel__check_attr is triggered
2497 * by attr->sample_type != 0, and we can't run it on
2500 stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2503 * We dont want to block the signals - that would cause
2504 * child tasks to inherit that and Ctrl-C would not work.
2505 * What we want is for Ctrl-C to work in the exec()-ed
2506 * task, but being ignored by perf stat itself:
2510 signal(SIGINT, skip_signal);
2511 signal(SIGCHLD, skip_signal);
2512 signal(SIGALRM, skip_signal);
2513 signal(SIGABRT, skip_signal);
2515 if (evlist__initialize_ctlfd(evsel_list, stat_config.ctl_fd, stat_config.ctl_fd_ack))
2518 /* Enable ignoring missing threads when -p option is defined. */
2519 evlist__first(evsel_list)->ignore_missing_thread = target.pid;
2521 for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
2522 if (stat_config.run_count != 1 && verbose > 0)
2523 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2527 evlist__reset_prev_raw_counts(evsel_list);
2529 status = run_perf_stat(argc, argv, run_idx);
2530 if (forever && status != -1 && !interval) {
2531 print_counters(NULL, argc, argv);
2532 perf_stat__reset_stats();
2536 if (!forever && status != -1 && (!interval || stat_config.summary))
2537 print_counters(NULL, argc, argv);
2539 evlist__finalize_ctlfd(evsel_list);
2543 * We synthesize the kernel mmap record just so that older tools
2544 * don't emit warnings about not being able to resolve symbols
2545 * due to /proc/sys/kernel/kptr_restrict settings and instead provide
2546 * a saner message about no samples being in the perf.data file.
2548 * This also serves to suppress a warning about f_header.data.size == 0
2549 * in header.c at the moment 'perf stat record' gets introduced, which
2550 * is not really needed once we start adding the stat specific PERF_RECORD_
2551 * records, but the need to suppress the kptr_restrict messages in older
2552 * tools remain -acme
2554 int fd = perf_data__fd(&perf_stat.data);
2556 err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2557 process_synthesized_event,
2558 &perf_stat.session->machines.host);
2560 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2561 "older tools may produce warnings about this file\n.");
2565 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2566 pr_err("failed to write stat round event\n");
2569 if (!perf_stat.data.is_pipe) {
2570 perf_stat.session->header.data_size += perf_stat.bytes_written;
2571 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2574 evlist__close(evsel_list);
2575 perf_session__delete(perf_stat.session);
2578 perf_stat__exit_aggr_mode();
2579 evlist__free_stats(evsel_list);
2581 if (stat_config.iostat_run)
2582 iostat_release(evsel_list);
2584 zfree(&stat_config.walltime_run);
2585 zfree(&stat_config.user_requested_cpu_list);
2587 if (smi_cost && smi_reset)
2588 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2590 evlist__delete(evsel_list);
2592 metricgroup__rblist_exit(&stat_config.metric_events);
2593 evlist__close_control(stat_config.ctl_fd, stat_config.ctl_fd_ack, &stat_config.ctl_fd_close);