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>
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;
670 } else if (counter->skippable) {
672 ui__warning("skipping event %s that kernel failed to open .\n",
673 evsel__name(counter));
674 counter->supported = false;
675 counter->errored = true;
679 evsel__open_strerror(counter, &target, errno, msg, sizeof(msg));
680 ui__error("%s\n", msg);
683 kill(child_pid, SIGTERM);
684 return COUNTER_FATAL;
687 static int __run_perf_stat(int argc, const char **argv, int run_idx)
689 int interval = stat_config.interval;
690 int times = stat_config.times;
691 int timeout = stat_config.timeout;
693 unsigned long long t0, t1;
694 struct evsel *counter;
697 const bool forks = (argc > 0);
698 bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
699 struct evlist_cpu_iterator evlist_cpu_itr;
700 struct affinity saved_affinity, *affinity = NULL;
702 bool second_pass = false;
705 if (evlist__prepare_workload(evsel_list, &target, argv, is_pipe, workload_exec_failed_signal) < 0) {
706 perror("failed to prepare workload");
709 child_pid = evsel_list->workload.pid;
712 if (!cpu_map__is_dummy(evsel_list->core.user_requested_cpus)) {
713 if (affinity__setup(&saved_affinity) < 0)
715 affinity = &saved_affinity;
718 evlist__for_each_entry(evsel_list, counter) {
719 counter->reset_group = false;
720 if (bpf_counter__load(counter, &target))
722 if (!(evsel__is_bperf(counter)))
723 all_counters_use_bpf = false;
726 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
727 counter = evlist_cpu_itr.evsel;
730 * bperf calls evsel__open_per_cpu() in bperf__load(), so
731 * no need to call it again here.
736 if (counter->reset_group || counter->errored)
738 if (evsel__is_bperf(counter))
741 if (create_perf_stat_counter(counter, &stat_config, &target,
742 evlist_cpu_itr.cpu_map_idx) < 0) {
745 * Weak group failed. We cannot just undo this here
746 * because earlier CPUs might be in group mode, and the kernel
747 * doesn't support mixing group and non group reads. Defer
749 * Don't close here because we're in the wrong affinity.
751 if ((errno == EINVAL || errno == EBADF) &&
752 evsel__leader(counter) != counter &&
753 counter->weak_group) {
754 evlist__reset_weak_group(evsel_list, counter, false);
755 assert(counter->reset_group);
760 switch (stat_handle_error(counter)) {
772 counter->supported = true;
777 * Now redo all the weak group after closing them,
778 * and also close errored counters.
781 /* First close errored or weak retry */
782 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
783 counter = evlist_cpu_itr.evsel;
785 if (!counter->reset_group && !counter->errored)
788 perf_evsel__close_cpu(&counter->core, evlist_cpu_itr.cpu_map_idx);
790 /* Now reopen weak */
791 evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
792 counter = evlist_cpu_itr.evsel;
794 if (!counter->reset_group)
797 pr_debug2("reopening weak %s\n", evsel__name(counter));
798 if (create_perf_stat_counter(counter, &stat_config, &target,
799 evlist_cpu_itr.cpu_map_idx) < 0) {
801 switch (stat_handle_error(counter)) {
805 goto try_again_reset;
812 counter->supported = true;
815 affinity__cleanup(affinity);
817 evlist__for_each_entry(evsel_list, counter) {
818 if (!counter->supported) {
819 perf_evsel__free_fd(&counter->core);
823 l = strlen(counter->unit);
824 if (l > stat_config.unit_width)
825 stat_config.unit_width = l;
827 if (evsel__should_store_id(counter) &&
828 evsel__store_ids(counter, evsel_list))
832 if (evlist__apply_filters(evsel_list, &counter)) {
833 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
834 counter->filter, evsel__name(counter), errno,
835 str_error_r(errno, msg, sizeof(msg)));
840 int fd = perf_data__fd(&perf_stat.data);
843 err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
845 err = perf_session__write_header(perf_stat.session, evsel_list,
852 err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
853 process_synthesized_event, is_pipe);
858 if (target.initial_delay) {
859 pr_info(EVLIST_DISABLED_MSG);
861 err = enable_counters();
866 /* Exec the command, if any */
868 evlist__start_workload(evsel_list);
870 if (target.initial_delay > 0) {
871 usleep(target.initial_delay * USEC_PER_MSEC);
872 err = enable_counters();
876 pr_info(EVLIST_ENABLED_MSG);
880 clock_gettime(CLOCK_MONOTONIC, &ref_time);
883 if (interval || timeout || evlist__ctlfd_initialized(evsel_list))
884 status = dispatch_events(forks, timeout, interval, ×);
885 if (child_pid != -1) {
887 kill(child_pid, SIGTERM);
888 wait4(child_pid, &status, 0, &stat_config.ru_data);
891 if (workload_exec_errno) {
892 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
893 pr_err("Workload failed: %s\n", emsg);
897 if (WIFSIGNALED(status))
898 psignal(WTERMSIG(status), argv[0]);
900 status = dispatch_events(forks, timeout, interval, ×);
907 if (stat_config.walltime_run_table)
908 stat_config.walltime_run[run_idx] = t1 - t0;
910 if (interval && stat_config.summary) {
911 stat_config.interval = 0;
912 stat_config.stop_read_counter = true;
913 init_stats(&walltime_nsecs_stats);
914 update_stats(&walltime_nsecs_stats, t1 - t0);
916 evlist__copy_prev_raw_counts(evsel_list);
917 evlist__reset_prev_raw_counts(evsel_list);
918 evlist__reset_aggr_stats(evsel_list);
920 update_stats(&walltime_nsecs_stats, t1 - t0);
921 update_rusage_stats(&ru_stats, &stat_config.ru_data);
925 * Closing a group leader splits the group, and as we only disable
926 * group leaders, results in remaining events becoming enabled. To
927 * avoid arbitrary skew, we must read all counters before closing any
930 if (read_counters(&(struct timespec) { .tv_nsec = t1-t0 }) == 0)
934 * We need to keep evsel_list alive, because it's processed
935 * later the evsel_list will be closed after.
938 evlist__close(evsel_list);
940 return WEXITSTATUS(status);
943 static int run_perf_stat(int argc, const char **argv, int run_idx)
948 ret = system(pre_cmd);
956 ret = __run_perf_stat(argc, argv, run_idx);
961 ret = system(post_cmd);
969 static void print_counters(struct timespec *ts, int argc, const char **argv)
971 /* Do not print anything if we record to the pipe. */
972 if (STAT_RECORD && perf_stat.data.is_pipe)
977 evlist__print_counters(evsel_list, &stat_config, &target, ts, argc, argv);
980 static volatile sig_atomic_t signr = -1;
982 static void skip_signal(int signo)
984 if ((child_pid == -1) || stat_config.interval)
989 * render child_pid harmless
990 * won't send SIGTERM to a random
991 * process in case of race condition
992 * and fast PID recycling
997 static void sig_atexit(void)
1002 * avoid race condition with SIGCHLD handler
1003 * in skip_signal() which is modifying child_pid
1004 * goal is to avoid send SIGTERM to a random
1008 sigaddset(&set, SIGCHLD);
1009 sigprocmask(SIG_BLOCK, &set, &oset);
1011 if (child_pid != -1)
1012 kill(child_pid, SIGTERM);
1014 sigprocmask(SIG_SETMASK, &oset, NULL);
1019 signal(signr, SIG_DFL);
1020 kill(getpid(), signr);
1023 void perf_stat__set_big_num(int set)
1025 stat_config.big_num = (set != 0);
1028 void perf_stat__set_no_csv_summary(int set)
1030 stat_config.no_csv_summary = (set != 0);
1033 static int stat__set_big_num(const struct option *opt __maybe_unused,
1034 const char *s __maybe_unused, int unset)
1036 big_num_opt = unset ? 0 : 1;
1037 perf_stat__set_big_num(!unset);
1041 static int enable_metric_only(const struct option *opt __maybe_unused,
1042 const char *s __maybe_unused, int unset)
1044 force_metric_only = true;
1045 stat_config.metric_only = !unset;
1049 static int append_metric_groups(const struct option *opt __maybe_unused,
1051 int unset __maybe_unused)
1056 if (asprintf(&tmp, "%s,%s", metrics, str) < 0)
1061 metrics = strdup(str);
1068 static int parse_control_option(const struct option *opt,
1070 int unset __maybe_unused)
1072 struct perf_stat_config *config = opt->value;
1074 return evlist__parse_control(str, &config->ctl_fd, &config->ctl_fd_ack, &config->ctl_fd_close);
1077 static int parse_stat_cgroups(const struct option *opt,
1078 const char *str, int unset)
1080 if (stat_config.cgroup_list) {
1081 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
1085 return parse_cgroups(opt, str, unset);
1088 static int parse_hybrid_type(const struct option *opt,
1090 int unset __maybe_unused)
1092 struct evlist *evlist = *(struct evlist **)opt->value;
1094 if (!list_empty(&evlist->core.entries)) {
1095 fprintf(stderr, "Must define cputype before events/metrics\n");
1099 evlist->hybrid_pmu_name = perf_pmu__hybrid_type_to_pmu(str);
1100 if (!evlist->hybrid_pmu_name) {
1101 fprintf(stderr, "--cputype %s is not supported!\n", str);
1108 static struct option stat_options[] = {
1109 OPT_BOOLEAN('T', "transaction", &transaction_run,
1110 "hardware transaction statistics"),
1111 OPT_CALLBACK('e', "event", &evsel_list, "event",
1112 "event selector. use 'perf list' to list available events",
1113 parse_events_option),
1114 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1115 "event filter", parse_filter),
1116 OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
1117 "child tasks do not inherit counters"),
1118 OPT_STRING('p', "pid", &target.pid, "pid",
1119 "stat events on existing process id"),
1120 OPT_STRING('t', "tid", &target.tid, "tid",
1121 "stat events on existing thread id"),
1122 #ifdef HAVE_BPF_SKEL
1123 OPT_STRING('b', "bpf-prog", &target.bpf_str, "bpf-prog-id",
1124 "stat events on existing bpf program id"),
1125 OPT_BOOLEAN(0, "bpf-counters", &target.use_bpf,
1126 "use bpf program to count events"),
1127 OPT_STRING(0, "bpf-attr-map", &target.attr_map, "attr-map-path",
1128 "path to perf_event_attr map"),
1130 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1131 "system-wide collection from all CPUs"),
1132 OPT_BOOLEAN(0, "scale", &stat_config.scale,
1133 "Use --no-scale to disable counter scaling for multiplexing"),
1134 OPT_INCR('v', "verbose", &verbose,
1135 "be more verbose (show counter open errors, etc)"),
1136 OPT_INTEGER('r', "repeat", &stat_config.run_count,
1137 "repeat command and print average + stddev (max: 100, forever: 0)"),
1138 OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
1139 "display details about each run (only with -r option)"),
1140 OPT_BOOLEAN('n', "null", &stat_config.null_run,
1141 "null run - dont start any counters"),
1142 OPT_INCR('d', "detailed", &detailed_run,
1143 "detailed run - start a lot of events"),
1144 OPT_BOOLEAN('S', "sync", &sync_run,
1145 "call sync() before starting a run"),
1146 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1147 "print large numbers with thousands\' separators",
1149 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1150 "list of cpus to monitor in system-wide"),
1151 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1152 "disable CPU count aggregation", AGGR_NONE),
1153 OPT_BOOLEAN(0, "no-merge", &stat_config.no_merge, "Do not merge identical named events"),
1154 OPT_BOOLEAN(0, "hybrid-merge", &stat_config.hybrid_merge,
1155 "Merge identical named hybrid events"),
1156 OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
1157 "print counts with custom separator"),
1158 OPT_BOOLEAN('j', "json-output", &stat_config.json_output,
1159 "print counts in JSON format"),
1160 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1161 "monitor event in cgroup name only", parse_stat_cgroups),
1162 OPT_STRING(0, "for-each-cgroup", &stat_config.cgroup_list, "name",
1163 "expand events for each cgroup"),
1164 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1165 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1166 OPT_INTEGER(0, "log-fd", &output_fd,
1167 "log output to fd, instead of stderr"),
1168 OPT_STRING(0, "pre", &pre_cmd, "command",
1169 "command to run prior to the measured command"),
1170 OPT_STRING(0, "post", &post_cmd, "command",
1171 "command to run after to the measured command"),
1172 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1173 "print counts at regular interval in ms "
1174 "(overhead is possible for values <= 100ms)"),
1175 OPT_INTEGER(0, "interval-count", &stat_config.times,
1176 "print counts for fixed number of times"),
1177 OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
1178 "clear screen in between new interval"),
1179 OPT_UINTEGER(0, "timeout", &stat_config.timeout,
1180 "stop workload and print counts after a timeout period in ms (>= 10ms)"),
1181 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1182 "aggregate counts per processor socket", AGGR_SOCKET),
1183 OPT_SET_UINT(0, "per-die", &stat_config.aggr_mode,
1184 "aggregate counts per processor die", AGGR_DIE),
1185 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1186 "aggregate counts per physical processor core", AGGR_CORE),
1187 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1188 "aggregate counts per thread", AGGR_THREAD),
1189 OPT_SET_UINT(0, "per-node", &stat_config.aggr_mode,
1190 "aggregate counts per numa node", AGGR_NODE),
1191 OPT_INTEGER('D', "delay", &target.initial_delay,
1192 "ms to wait before starting measurement after program start (-1: start with events disabled)"),
1193 OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
1194 "Only print computed metrics. No raw values", enable_metric_only),
1195 OPT_BOOLEAN(0, "metric-no-group", &stat_config.metric_no_group,
1196 "don't group metric events, impacts multiplexing"),
1197 OPT_BOOLEAN(0, "metric-no-merge", &stat_config.metric_no_merge,
1198 "don't try to share events between metrics in a group"),
1199 OPT_BOOLEAN(0, "metric-no-threshold", &stat_config.metric_no_threshold,
1200 "don't try to share events between metrics in a group "),
1201 OPT_BOOLEAN(0, "topdown", &topdown_run,
1202 "measure top-down statistics"),
1203 OPT_UINTEGER(0, "td-level", &stat_config.topdown_level,
1204 "Set the metrics level for the top-down statistics (0: max level)"),
1205 OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1206 "measure SMI cost"),
1207 OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1208 "monitor specified metrics or metric groups (separated by ,)",
1209 append_metric_groups),
1210 OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
1211 "Configure all used events to run in kernel space.",
1212 PARSE_OPT_EXCLUSIVE),
1213 OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
1214 "Configure all used events to run in user space.",
1215 PARSE_OPT_EXCLUSIVE),
1216 OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
1217 "Use with 'percore' event qualifier to show the event "
1218 "counts of one hardware thread by sum up total hardware "
1219 "threads of same physical core"),
1220 OPT_BOOLEAN(0, "summary", &stat_config.summary,
1221 "print summary for interval mode"),
1222 OPT_BOOLEAN(0, "no-csv-summary", &stat_config.no_csv_summary,
1223 "don't print 'summary' for CSV summary output"),
1224 OPT_BOOLEAN(0, "quiet", &quiet,
1225 "don't print any output, messages or warnings (useful with record)"),
1226 OPT_CALLBACK(0, "cputype", &evsel_list, "hybrid cpu type",
1227 "Only enable events on applying cpu with this type "
1228 "for hybrid platform (e.g. core or atom)",
1231 OPT_CALLBACK(0, "pfm-events", &evsel_list, "event",
1232 "libpfm4 event selector. use 'perf list' to list available events",
1233 parse_libpfm_events_option),
1235 OPT_CALLBACK(0, "control", &stat_config, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]",
1236 "Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events).\n"
1237 "\t\t\t Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n"
1238 "\t\t\t Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.",
1239 parse_control_option),
1240 OPT_CALLBACK_OPTARG(0, "iostat", &evsel_list, &stat_config, "default",
1241 "measure I/O performance metrics provided by arch/platform",
1246 static const char *const aggr_mode__string[] = {
1247 [AGGR_CORE] = "core",
1249 [AGGR_GLOBAL] = "global",
1250 [AGGR_NODE] = "node",
1251 [AGGR_NONE] = "none",
1252 [AGGR_SOCKET] = "socket",
1253 [AGGR_THREAD] = "thread",
1254 [AGGR_UNSET] = "unset",
1257 static struct aggr_cpu_id perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
1258 struct perf_cpu cpu)
1260 return aggr_cpu_id__socket(cpu, /*data=*/NULL);
1263 static struct aggr_cpu_id perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
1264 struct perf_cpu cpu)
1266 return aggr_cpu_id__die(cpu, /*data=*/NULL);
1269 static struct aggr_cpu_id perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
1270 struct perf_cpu cpu)
1272 return aggr_cpu_id__core(cpu, /*data=*/NULL);
1275 static struct aggr_cpu_id perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
1276 struct perf_cpu cpu)
1278 return aggr_cpu_id__node(cpu, /*data=*/NULL);
1281 static struct aggr_cpu_id perf_stat__get_global(struct perf_stat_config *config __maybe_unused,
1282 struct perf_cpu cpu)
1284 return aggr_cpu_id__global(cpu, /*data=*/NULL);
1287 static struct aggr_cpu_id perf_stat__get_cpu(struct perf_stat_config *config __maybe_unused,
1288 struct perf_cpu cpu)
1290 return aggr_cpu_id__cpu(cpu, /*data=*/NULL);
1293 static struct aggr_cpu_id perf_stat__get_aggr(struct perf_stat_config *config,
1294 aggr_get_id_t get_id, struct perf_cpu cpu)
1296 struct aggr_cpu_id id;
1298 /* per-process mode - should use global aggr mode */
1300 return get_id(config, cpu);
1302 if (aggr_cpu_id__is_empty(&config->cpus_aggr_map->map[cpu.cpu]))
1303 config->cpus_aggr_map->map[cpu.cpu] = get_id(config, cpu);
1305 id = config->cpus_aggr_map->map[cpu.cpu];
1309 static struct aggr_cpu_id perf_stat__get_socket_cached(struct perf_stat_config *config,
1310 struct perf_cpu cpu)
1312 return perf_stat__get_aggr(config, perf_stat__get_socket, cpu);
1315 static struct aggr_cpu_id perf_stat__get_die_cached(struct perf_stat_config *config,
1316 struct perf_cpu cpu)
1318 return perf_stat__get_aggr(config, perf_stat__get_die, cpu);
1321 static struct aggr_cpu_id perf_stat__get_core_cached(struct perf_stat_config *config,
1322 struct perf_cpu cpu)
1324 return perf_stat__get_aggr(config, perf_stat__get_core, cpu);
1327 static struct aggr_cpu_id perf_stat__get_node_cached(struct perf_stat_config *config,
1328 struct perf_cpu cpu)
1330 return perf_stat__get_aggr(config, perf_stat__get_node, cpu);
1333 static struct aggr_cpu_id perf_stat__get_global_cached(struct perf_stat_config *config,
1334 struct perf_cpu cpu)
1336 return perf_stat__get_aggr(config, perf_stat__get_global, cpu);
1339 static struct aggr_cpu_id perf_stat__get_cpu_cached(struct perf_stat_config *config,
1340 struct perf_cpu cpu)
1342 return perf_stat__get_aggr(config, perf_stat__get_cpu, cpu);
1345 static aggr_cpu_id_get_t aggr_mode__get_aggr(enum aggr_mode aggr_mode)
1347 switch (aggr_mode) {
1349 return aggr_cpu_id__socket;
1351 return aggr_cpu_id__die;
1353 return aggr_cpu_id__core;
1355 return aggr_cpu_id__node;
1357 return aggr_cpu_id__cpu;
1359 return aggr_cpu_id__global;
1368 static aggr_get_id_t aggr_mode__get_id(enum aggr_mode aggr_mode)
1370 switch (aggr_mode) {
1372 return perf_stat__get_socket_cached;
1374 return perf_stat__get_die_cached;
1376 return perf_stat__get_core_cached;
1378 return perf_stat__get_node_cached;
1380 return perf_stat__get_cpu_cached;
1382 return perf_stat__get_global_cached;
1391 static int perf_stat_init_aggr_mode(void)
1394 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr(stat_config.aggr_mode);
1397 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1398 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1399 get_id, /*data=*/NULL, needs_sort);
1400 if (!stat_config.aggr_map) {
1401 pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
1404 stat_config.aggr_get_id = aggr_mode__get_id(stat_config.aggr_mode);
1407 if (stat_config.aggr_mode == AGGR_THREAD) {
1408 nr = perf_thread_map__nr(evsel_list->core.threads);
1409 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1410 if (stat_config.aggr_map == NULL)
1413 for (int s = 0; s < nr; s++) {
1414 struct aggr_cpu_id id = aggr_cpu_id__empty();
1417 stat_config.aggr_map->map[s] = id;
1423 * The evsel_list->cpus is the base we operate on,
1424 * taking the highest cpu number to be the size of
1425 * the aggregation translate cpumap.
1427 if (evsel_list->core.user_requested_cpus)
1428 nr = perf_cpu_map__max(evsel_list->core.user_requested_cpus).cpu;
1431 stat_config.cpus_aggr_map = cpu_aggr_map__empty_new(nr + 1);
1432 return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
1435 static void cpu_aggr_map__delete(struct cpu_aggr_map *map)
1438 WARN_ONCE(refcount_read(&map->refcnt) != 0,
1439 "cpu_aggr_map refcnt unbalanced\n");
1444 static void cpu_aggr_map__put(struct cpu_aggr_map *map)
1446 if (map && refcount_dec_and_test(&map->refcnt))
1447 cpu_aggr_map__delete(map);
1450 static void perf_stat__exit_aggr_mode(void)
1452 cpu_aggr_map__put(stat_config.aggr_map);
1453 cpu_aggr_map__put(stat_config.cpus_aggr_map);
1454 stat_config.aggr_map = NULL;
1455 stat_config.cpus_aggr_map = NULL;
1458 static struct aggr_cpu_id perf_env__get_socket_aggr_by_cpu(struct perf_cpu cpu, void *data)
1460 struct perf_env *env = data;
1461 struct aggr_cpu_id id = aggr_cpu_id__empty();
1464 id.socket = env->cpu[cpu.cpu].socket_id;
1469 static struct aggr_cpu_id perf_env__get_die_aggr_by_cpu(struct perf_cpu cpu, void *data)
1471 struct perf_env *env = data;
1472 struct aggr_cpu_id id = aggr_cpu_id__empty();
1474 if (cpu.cpu != -1) {
1476 * die_id is relative to socket, so start
1477 * with the socket ID and then add die to
1480 id.socket = env->cpu[cpu.cpu].socket_id;
1481 id.die = env->cpu[cpu.cpu].die_id;
1487 static struct aggr_cpu_id perf_env__get_core_aggr_by_cpu(struct perf_cpu cpu, void *data)
1489 struct perf_env *env = data;
1490 struct aggr_cpu_id id = aggr_cpu_id__empty();
1492 if (cpu.cpu != -1) {
1494 * core_id is relative to socket and die,
1495 * we need a global id. So we set
1496 * socket, die id and core id
1498 id.socket = env->cpu[cpu.cpu].socket_id;
1499 id.die = env->cpu[cpu.cpu].die_id;
1500 id.core = env->cpu[cpu.cpu].core_id;
1506 static struct aggr_cpu_id perf_env__get_cpu_aggr_by_cpu(struct perf_cpu cpu, void *data)
1508 struct perf_env *env = data;
1509 struct aggr_cpu_id id = aggr_cpu_id__empty();
1511 if (cpu.cpu != -1) {
1513 * core_id is relative to socket and die,
1514 * we need a global id. So we set
1515 * socket, die id and core id
1517 id.socket = env->cpu[cpu.cpu].socket_id;
1518 id.die = env->cpu[cpu.cpu].die_id;
1519 id.core = env->cpu[cpu.cpu].core_id;
1526 static struct aggr_cpu_id perf_env__get_node_aggr_by_cpu(struct perf_cpu cpu, void *data)
1528 struct aggr_cpu_id id = aggr_cpu_id__empty();
1530 id.node = perf_env__numa_node(data, cpu);
1534 static struct aggr_cpu_id perf_env__get_global_aggr_by_cpu(struct perf_cpu cpu __maybe_unused,
1535 void *data __maybe_unused)
1537 struct aggr_cpu_id id = aggr_cpu_id__empty();
1539 /* it always aggregates to the cpu 0 */
1540 id.cpu = (struct perf_cpu){ .cpu = 0 };
1544 static struct aggr_cpu_id perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
1545 struct perf_cpu cpu)
1547 return perf_env__get_socket_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1549 static struct aggr_cpu_id perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
1550 struct perf_cpu cpu)
1552 return perf_env__get_die_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1555 static struct aggr_cpu_id perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
1556 struct perf_cpu cpu)
1558 return perf_env__get_core_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1561 static struct aggr_cpu_id perf_stat__get_cpu_file(struct perf_stat_config *config __maybe_unused,
1562 struct perf_cpu cpu)
1564 return perf_env__get_cpu_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1567 static struct aggr_cpu_id perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
1568 struct perf_cpu cpu)
1570 return perf_env__get_node_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1573 static struct aggr_cpu_id perf_stat__get_global_file(struct perf_stat_config *config __maybe_unused,
1574 struct perf_cpu cpu)
1576 return perf_env__get_global_aggr_by_cpu(cpu, &perf_stat.session->header.env);
1579 static aggr_cpu_id_get_t aggr_mode__get_aggr_file(enum aggr_mode aggr_mode)
1581 switch (aggr_mode) {
1583 return perf_env__get_socket_aggr_by_cpu;
1585 return perf_env__get_die_aggr_by_cpu;
1587 return perf_env__get_core_aggr_by_cpu;
1589 return perf_env__get_node_aggr_by_cpu;
1591 return perf_env__get_global_aggr_by_cpu;
1593 return perf_env__get_cpu_aggr_by_cpu;
1602 static aggr_get_id_t aggr_mode__get_id_file(enum aggr_mode aggr_mode)
1604 switch (aggr_mode) {
1606 return perf_stat__get_socket_file;
1608 return perf_stat__get_die_file;
1610 return perf_stat__get_core_file;
1612 return perf_stat__get_node_file;
1614 return perf_stat__get_global_file;
1616 return perf_stat__get_cpu_file;
1625 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1627 struct perf_env *env = &st->session->header.env;
1628 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr_file(stat_config.aggr_mode);
1629 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1631 if (stat_config.aggr_mode == AGGR_THREAD) {
1632 int nr = perf_thread_map__nr(evsel_list->core.threads);
1634 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1635 if (stat_config.aggr_map == NULL)
1638 for (int s = 0; s < nr; s++) {
1639 struct aggr_cpu_id id = aggr_cpu_id__empty();
1642 stat_config.aggr_map->map[s] = id;
1650 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1651 get_id, env, needs_sort);
1652 if (!stat_config.aggr_map) {
1653 pr_err("cannot build %s map", aggr_mode__string[stat_config.aggr_mode]);
1656 stat_config.aggr_get_id = aggr_mode__get_id_file(stat_config.aggr_mode);
1661 * Add default attributes, if there were no attributes specified or
1662 * if -d/--detailed, -d -d or -d -d -d is used:
1664 static int add_default_attributes(void)
1666 struct perf_event_attr default_attrs0[] = {
1668 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
1669 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
1670 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
1671 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
1673 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
1675 struct perf_event_attr frontend_attrs[] = {
1676 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1678 struct perf_event_attr backend_attrs[] = {
1679 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
1681 struct perf_event_attr default_attrs1[] = {
1682 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
1683 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
1684 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
1689 * Detailed stats (-d), covering the L1 and last level data caches:
1691 struct perf_event_attr detailed_attrs[] = {
1693 { .type = PERF_TYPE_HW_CACHE,
1695 PERF_COUNT_HW_CACHE_L1D << 0 |
1696 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1697 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1699 { .type = PERF_TYPE_HW_CACHE,
1701 PERF_COUNT_HW_CACHE_L1D << 0 |
1702 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1703 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1705 { .type = PERF_TYPE_HW_CACHE,
1707 PERF_COUNT_HW_CACHE_LL << 0 |
1708 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1709 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1711 { .type = PERF_TYPE_HW_CACHE,
1713 PERF_COUNT_HW_CACHE_LL << 0 |
1714 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1715 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1719 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1721 struct perf_event_attr very_detailed_attrs[] = {
1723 { .type = PERF_TYPE_HW_CACHE,
1725 PERF_COUNT_HW_CACHE_L1I << 0 |
1726 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1727 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1729 { .type = PERF_TYPE_HW_CACHE,
1731 PERF_COUNT_HW_CACHE_L1I << 0 |
1732 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1733 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1735 { .type = PERF_TYPE_HW_CACHE,
1737 PERF_COUNT_HW_CACHE_DTLB << 0 |
1738 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1739 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1741 { .type = PERF_TYPE_HW_CACHE,
1743 PERF_COUNT_HW_CACHE_DTLB << 0 |
1744 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1745 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1747 { .type = PERF_TYPE_HW_CACHE,
1749 PERF_COUNT_HW_CACHE_ITLB << 0 |
1750 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1751 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1753 { .type = PERF_TYPE_HW_CACHE,
1755 PERF_COUNT_HW_CACHE_ITLB << 0 |
1756 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1757 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1762 * Very, very detailed stats (-d -d -d), adding prefetch events:
1764 struct perf_event_attr very_very_detailed_attrs[] = {
1766 { .type = PERF_TYPE_HW_CACHE,
1768 PERF_COUNT_HW_CACHE_L1D << 0 |
1769 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1770 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1772 { .type = PERF_TYPE_HW_CACHE,
1774 PERF_COUNT_HW_CACHE_L1D << 0 |
1775 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1776 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1779 struct perf_event_attr default_null_attrs[] = {};
1781 /* Set attrs if no event is selected and !null_run: */
1782 if (stat_config.null_run)
1785 if (transaction_run) {
1786 /* Handle -T as -M transaction. Once platform specific metrics
1787 * support has been added to the json files, all architectures
1788 * will use this approach. To determine transaction support
1789 * on an architecture test for such a metric name.
1791 if (!metricgroup__has_metric("transaction")) {
1792 pr_err("Missing transaction metrics");
1795 return metricgroup__parse_groups(evsel_list, "transaction",
1796 stat_config.metric_no_group,
1797 stat_config.metric_no_merge,
1798 stat_config.metric_no_threshold,
1799 stat_config.user_requested_cpu_list,
1800 stat_config.system_wide,
1801 &stat_config.metric_events);
1807 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
1808 pr_err("freeze_on_smi is not supported.");
1813 if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
1814 fprintf(stderr, "Failed to set freeze_on_smi.\n");
1820 if (!metricgroup__has_metric("smi")) {
1821 pr_err("Missing smi metrics");
1825 if (!force_metric_only)
1826 stat_config.metric_only = true;
1828 return metricgroup__parse_groups(evsel_list, "smi",
1829 stat_config.metric_no_group,
1830 stat_config.metric_no_merge,
1831 stat_config.metric_no_threshold,
1832 stat_config.user_requested_cpu_list,
1833 stat_config.system_wide,
1834 &stat_config.metric_events);
1838 unsigned int max_level = metricgroups__topdown_max_level();
1839 char str[] = "TopdownL1";
1841 if (!force_metric_only)
1842 stat_config.metric_only = true;
1845 pr_err("Topdown requested but the topdown metric groups aren't present.\n"
1846 "(See perf list the metric groups have names like TopdownL1)");
1849 if (stat_config.topdown_level > max_level) {
1850 pr_err("Invalid top-down metrics level. The max level is %u.\n", max_level);
1852 } else if (!stat_config.topdown_level)
1853 stat_config.topdown_level = 1;
1855 if (!stat_config.interval && !stat_config.metric_only) {
1856 fprintf(stat_config.output,
1857 "Topdown accuracy may decrease when measuring long periods.\n"
1858 "Please print the result regularly, e.g. -I1000\n");
1860 str[8] = stat_config.topdown_level + '0';
1861 if (metricgroup__parse_groups(evsel_list, str,
1862 /*metric_no_group=*/false,
1863 /*metric_no_merge=*/false,
1864 /*metric_no_threshold=*/true,
1865 stat_config.user_requested_cpu_list,
1866 stat_config.system_wide,
1867 &stat_config.metric_events) < 0)
1871 if (!stat_config.topdown_level)
1872 stat_config.topdown_level = 1;
1874 if (!evsel_list->core.nr_entries) {
1875 /* No events so add defaults. */
1876 if (target__has_cpu(&target))
1877 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
1879 if (evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
1881 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
1882 if (evlist__add_default_attrs(evsel_list, frontend_attrs) < 0)
1885 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
1886 if (evlist__add_default_attrs(evsel_list, backend_attrs) < 0)
1889 if (evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
1892 * Add TopdownL1 metrics if they exist. To minimize
1893 * multiplexing, don't request threshold computation.
1896 * TODO: TopdownL1 is disabled on hybrid CPUs to avoid a crashes
1897 * caused by exposing latent bugs. This is fixed properly in:
1898 * https://lore.kernel.org/lkml/bff481ba-e60a-763f-0aa0-3ee53302c480@linux.intel.com/
1900 if (metricgroup__has_metric("TopdownL1") && !perf_pmu__has_hybrid()) {
1901 struct evlist *metric_evlist = evlist__new();
1902 struct evsel *metric_evsel;
1907 if (metricgroup__parse_groups(metric_evlist, "TopdownL1",
1908 /*metric_no_group=*/false,
1909 /*metric_no_merge=*/false,
1910 /*metric_no_threshold=*/true,
1911 stat_config.user_requested_cpu_list,
1912 stat_config.system_wide,
1913 &stat_config.metric_events) < 0)
1916 evlist__for_each_entry(metric_evlist, metric_evsel) {
1917 metric_evsel->skippable = true;
1919 evlist__splice_list_tail(evsel_list, &metric_evlist->core.entries);
1920 evlist__delete(metric_evlist);
1923 /* Platform specific attrs */
1924 if (evlist__add_default_attrs(evsel_list, default_null_attrs) < 0)
1928 /* Detailed events get appended to the event list: */
1930 if (detailed_run < 1)
1933 /* Append detailed run extra attributes: */
1934 if (evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1937 if (detailed_run < 2)
1940 /* Append very detailed run extra attributes: */
1941 if (evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1944 if (detailed_run < 3)
1947 /* Append very, very detailed run extra attributes: */
1948 return evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1951 static const char * const stat_record_usage[] = {
1952 "perf stat record [<options>]",
1956 static void init_features(struct perf_session *session)
1960 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
1961 perf_header__set_feat(&session->header, feat);
1963 perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
1964 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
1965 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
1966 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
1967 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
1970 static int __cmd_record(int argc, const char **argv)
1972 struct perf_session *session;
1973 struct perf_data *data = &perf_stat.data;
1975 argc = parse_options(argc, argv, stat_options, stat_record_usage,
1976 PARSE_OPT_STOP_AT_NON_OPTION);
1979 data->path = output_name;
1981 if (stat_config.run_count != 1 || forever) {
1982 pr_err("Cannot use -r option with perf stat record.\n");
1986 session = perf_session__new(data, NULL);
1987 if (IS_ERR(session)) {
1988 pr_err("Perf session creation failed\n");
1989 return PTR_ERR(session);
1992 init_features(session);
1994 session->evlist = evsel_list;
1995 perf_stat.session = session;
1996 perf_stat.record = true;
2000 static int process_stat_round_event(struct perf_session *session,
2001 union perf_event *event)
2003 struct perf_record_stat_round *stat_round = &event->stat_round;
2004 struct timespec tsh, *ts = NULL;
2005 const char **argv = session->header.env.cmdline_argv;
2006 int argc = session->header.env.nr_cmdline;
2010 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2011 update_stats(&walltime_nsecs_stats, stat_round->time);
2013 if (stat_config.interval && stat_round->time) {
2014 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2015 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2019 print_counters(ts, argc, argv);
2024 int process_stat_config_event(struct perf_session *session,
2025 union perf_event *event)
2027 struct perf_tool *tool = session->tool;
2028 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2030 perf_event__read_stat_config(&stat_config, &event->stat_config);
2032 if (perf_cpu_map__empty(st->cpus)) {
2033 if (st->aggr_mode != AGGR_UNSET)
2034 pr_warning("warning: processing task data, aggregation mode not set\n");
2035 } else if (st->aggr_mode != AGGR_UNSET) {
2036 stat_config.aggr_mode = st->aggr_mode;
2039 if (perf_stat.data.is_pipe)
2040 perf_stat_init_aggr_mode();
2042 perf_stat_init_aggr_mode_file(st);
2044 if (stat_config.aggr_map) {
2045 int nr_aggr = stat_config.aggr_map->nr;
2047 if (evlist__alloc_aggr_stats(session->evlist, nr_aggr) < 0) {
2048 pr_err("cannot allocate aggr counts\n");
2055 static int set_maps(struct perf_stat *st)
2057 if (!st->cpus || !st->threads)
2060 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2063 perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
2065 if (evlist__alloc_stats(&stat_config, evsel_list, /*alloc_raw=*/true))
2068 st->maps_allocated = true;
2073 int process_thread_map_event(struct perf_session *session,
2074 union perf_event *event)
2076 struct perf_tool *tool = session->tool;
2077 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2080 pr_warning("Extra thread map event, ignoring.\n");
2084 st->threads = thread_map__new_event(&event->thread_map);
2088 return set_maps(st);
2092 int process_cpu_map_event(struct perf_session *session,
2093 union perf_event *event)
2095 struct perf_tool *tool = session->tool;
2096 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2097 struct perf_cpu_map *cpus;
2100 pr_warning("Extra cpu map event, ignoring.\n");
2104 cpus = cpu_map__new_data(&event->cpu_map.data);
2109 return set_maps(st);
2112 static const char * const stat_report_usage[] = {
2113 "perf stat report [<options>]",
2117 static struct perf_stat perf_stat = {
2119 .attr = perf_event__process_attr,
2120 .event_update = perf_event__process_event_update,
2121 .thread_map = process_thread_map_event,
2122 .cpu_map = process_cpu_map_event,
2123 .stat_config = process_stat_config_event,
2124 .stat = perf_event__process_stat_event,
2125 .stat_round = process_stat_round_event,
2127 .aggr_mode = AGGR_UNSET,
2130 static int __cmd_report(int argc, const char **argv)
2132 struct perf_session *session;
2133 const struct option options[] = {
2134 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2135 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2136 "aggregate counts per processor socket", AGGR_SOCKET),
2137 OPT_SET_UINT(0, "per-die", &perf_stat.aggr_mode,
2138 "aggregate counts per processor die", AGGR_DIE),
2139 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2140 "aggregate counts per physical processor core", AGGR_CORE),
2141 OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
2142 "aggregate counts per numa node", AGGR_NODE),
2143 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2144 "disable CPU count aggregation", AGGR_NONE),
2150 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2152 if (!input_name || !strlen(input_name)) {
2153 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2156 input_name = "perf.data";
2159 perf_stat.data.path = input_name;
2160 perf_stat.data.mode = PERF_DATA_MODE_READ;
2162 session = perf_session__new(&perf_stat.data, &perf_stat.tool);
2163 if (IS_ERR(session))
2164 return PTR_ERR(session);
2166 perf_stat.session = session;
2167 stat_config.output = stderr;
2168 evsel_list = session->evlist;
2170 ret = perf_session__process_events(session);
2174 perf_session__delete(session);
2178 static void setup_system_wide(int forks)
2181 * Make system wide (-a) the default target if
2182 * no target was specified and one of following
2183 * conditions is met:
2185 * - there's no workload specified
2186 * - there is workload specified but all requested
2187 * events are system wide events
2189 if (!target__none(&target))
2193 target.system_wide = true;
2195 struct evsel *counter;
2197 evlist__for_each_entry(evsel_list, counter) {
2198 if (!counter->core.requires_cpu &&
2199 !evsel__name_is(counter, "duration_time")) {
2204 if (evsel_list->core.nr_entries)
2205 target.system_wide = true;
2209 int cmd_stat(int argc, const char **argv)
2211 const char * const stat_usage[] = {
2212 "perf stat [<options>] [<command>]",
2215 int status = -EINVAL, run_idx, err;
2217 FILE *output = stderr;
2218 unsigned int interval, timeout;
2219 const char * const stat_subcommands[] = { "record", "report" };
2220 char errbuf[BUFSIZ];
2222 setlocale(LC_ALL, "");
2224 evsel_list = evlist__new();
2225 if (evsel_list == NULL)
2228 parse_events__shrink_config_terms();
2230 /* String-parsing callback-based options would segfault when negated */
2231 set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
2232 set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
2233 set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
2235 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2236 (const char **) stat_usage,
2237 PARSE_OPT_STOP_AT_NON_OPTION);
2239 if (stat_config.csv_sep) {
2240 stat_config.csv_output = true;
2241 if (!strcmp(stat_config.csv_sep, "\\t"))
2242 stat_config.csv_sep = "\t";
2244 stat_config.csv_sep = DEFAULT_SEPARATOR;
2246 if (argc && strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
2247 argc = __cmd_record(argc, argv);
2250 } else if (argc && strlen(argv[0]) > 2 && strstarts("report", argv[0]))
2251 return __cmd_report(argc, argv);
2253 interval = stat_config.interval;
2254 timeout = stat_config.timeout;
2257 * For record command the -o is already taken care of.
2259 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2262 if (output_name && output_fd) {
2263 fprintf(stderr, "cannot use both --output and --log-fd\n");
2264 parse_options_usage(stat_usage, stat_options, "o", 1);
2265 parse_options_usage(NULL, stat_options, "log-fd", 0);
2269 if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2270 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2274 if (stat_config.metric_only && stat_config.run_count > 1) {
2275 fprintf(stderr, "--metric-only is not supported with -r\n");
2279 if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
2280 fprintf(stderr, "--table is only supported with -r\n");
2281 parse_options_usage(stat_usage, stat_options, "r", 1);
2282 parse_options_usage(NULL, stat_options, "table", 0);
2286 if (output_fd < 0) {
2287 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2288 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2292 if (!output && !quiet) {
2294 mode = append_file ? "a" : "w";
2296 output = fopen(output_name, mode);
2298 perror("failed to create output file");
2301 if (!stat_config.json_output) {
2302 clock_gettime(CLOCK_REALTIME, &tm);
2303 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2305 } else if (output_fd > 0) {
2306 mode = append_file ? "a" : "w";
2307 output = fdopen(output_fd, mode);
2309 perror("Failed opening logfd");
2314 if (stat_config.interval_clear && !isatty(fileno(output))) {
2315 fprintf(stderr, "--interval-clear does not work with output\n");
2316 parse_options_usage(stat_usage, stat_options, "o", 1);
2317 parse_options_usage(NULL, stat_options, "log-fd", 0);
2318 parse_options_usage(NULL, stat_options, "interval-clear", 0);
2322 stat_config.output = output;
2325 * let the spreadsheet do the pretty-printing
2327 if (stat_config.csv_output) {
2328 /* User explicitly passed -B? */
2329 if (big_num_opt == 1) {
2330 fprintf(stderr, "-B option not supported with -x\n");
2331 parse_options_usage(stat_usage, stat_options, "B", 1);
2332 parse_options_usage(NULL, stat_options, "x", 1);
2334 } else /* Nope, so disable big number formatting */
2335 stat_config.big_num = false;
2336 } else if (big_num_opt == 0) /* User passed --no-big-num */
2337 stat_config.big_num = false;
2339 err = target__validate(&target);
2341 target__strerror(&target, err, errbuf, BUFSIZ);
2342 pr_warning("%s\n", errbuf);
2345 setup_system_wide(argc);
2348 * Display user/system times only for single
2349 * run and when there's specified tracee.
2351 if ((stat_config.run_count == 1) && target__none(&target))
2352 stat_config.ru_display = true;
2354 if (stat_config.run_count < 0) {
2355 pr_err("Run count must be a positive number\n");
2356 parse_options_usage(stat_usage, stat_options, "r", 1);
2358 } else if (stat_config.run_count == 0) {
2360 stat_config.run_count = 1;
2363 if (stat_config.walltime_run_table) {
2364 stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
2365 if (!stat_config.walltime_run) {
2366 pr_err("failed to setup -r option");
2371 if ((stat_config.aggr_mode == AGGR_THREAD) &&
2372 !target__has_task(&target)) {
2373 if (!target.system_wide || target.cpu_list) {
2374 fprintf(stderr, "The --per-thread option is only "
2375 "available when monitoring via -p -t -a "
2376 "options or only --per-thread.\n");
2377 parse_options_usage(NULL, stat_options, "p", 1);
2378 parse_options_usage(NULL, stat_options, "t", 1);
2384 * no_aggr, cgroup are for system-wide only
2385 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2387 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2388 stat_config.aggr_mode != AGGR_THREAD) ||
2389 (nr_cgroups || stat_config.cgroup_list)) &&
2390 !target__has_cpu(&target)) {
2391 fprintf(stderr, "both cgroup and no-aggregation "
2392 "modes only available in system-wide mode\n");
2394 parse_options_usage(stat_usage, stat_options, "G", 1);
2395 parse_options_usage(NULL, stat_options, "A", 1);
2396 parse_options_usage(NULL, stat_options, "a", 1);
2397 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2401 if (stat_config.iostat_run) {
2402 status = iostat_prepare(evsel_list, &stat_config);
2405 if (iostat_mode == IOSTAT_LIST) {
2406 iostat_list(evsel_list, &stat_config);
2408 } else if (verbose > 0)
2409 iostat_list(evsel_list, &stat_config);
2410 if (iostat_mode == IOSTAT_RUN && !target__has_cpu(&target))
2411 target.system_wide = true;
2414 if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2415 target.per_thread = true;
2417 stat_config.system_wide = target.system_wide;
2418 if (target.cpu_list) {
2419 stat_config.user_requested_cpu_list = strdup(target.cpu_list);
2420 if (!stat_config.user_requested_cpu_list) {
2427 * Metric parsing needs to be delayed as metrics may optimize events
2428 * knowing the target is system-wide.
2431 metricgroup__parse_groups(evsel_list, metrics,
2432 stat_config.metric_no_group,
2433 stat_config.metric_no_merge,
2434 stat_config.metric_no_threshold,
2435 stat_config.user_requested_cpu_list,
2436 stat_config.system_wide,
2437 &stat_config.metric_events);
2441 if (add_default_attributes())
2444 if (stat_config.cgroup_list) {
2445 if (nr_cgroups > 0) {
2446 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
2447 parse_options_usage(stat_usage, stat_options, "G", 1);
2448 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2452 if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list,
2453 &stat_config.metric_events, true) < 0) {
2454 parse_options_usage(stat_usage, stat_options,
2455 "for-each-cgroup", 0);
2460 if (evlist__fix_hybrid_cpus(evsel_list, target.cpu_list)) {
2461 pr_err("failed to use cpu list %s\n", target.cpu_list);
2465 target.hybrid = perf_pmu__has_hybrid();
2466 if (evlist__create_maps(evsel_list, &target) < 0) {
2467 if (target__has_task(&target)) {
2468 pr_err("Problems finding threads of monitor\n");
2469 parse_options_usage(stat_usage, stat_options, "p", 1);
2470 parse_options_usage(NULL, stat_options, "t", 1);
2471 } else if (target__has_cpu(&target)) {
2472 perror("failed to parse CPUs map");
2473 parse_options_usage(stat_usage, stat_options, "C", 1);
2474 parse_options_usage(NULL, stat_options, "a", 1);
2479 evlist__check_cpu_maps(evsel_list);
2482 * Initialize thread_map with comm names,
2483 * so we could print it out on output.
2485 if (stat_config.aggr_mode == AGGR_THREAD) {
2486 thread_map__read_comms(evsel_list->core.threads);
2489 if (stat_config.aggr_mode == AGGR_NODE)
2490 cpu__setup_cpunode_map();
2492 if (stat_config.times && interval)
2493 interval_count = true;
2494 else if (stat_config.times && !interval) {
2495 pr_err("interval-count option should be used together with "
2496 "interval-print.\n");
2497 parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2498 parse_options_usage(stat_usage, stat_options, "I", 1);
2502 if (timeout && timeout < 100) {
2504 pr_err("timeout must be >= 10ms.\n");
2505 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2508 pr_warning("timeout < 100ms. "
2509 "The overhead percentage could be high in some cases. "
2510 "Please proceed with caution.\n");
2512 if (timeout && interval) {
2513 pr_err("timeout option is not supported with interval-print.\n");
2514 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2515 parse_options_usage(stat_usage, stat_options, "I", 1);
2519 if (perf_stat_init_aggr_mode())
2522 if (evlist__alloc_stats(&stat_config, evsel_list, interval))
2526 * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2527 * while avoiding that older tools show confusing messages.
2529 * However for pipe sessions we need to keep it zero,
2530 * because script's perf_evsel__check_attr is triggered
2531 * by attr->sample_type != 0, and we can't run it on
2534 stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2537 * We dont want to block the signals - that would cause
2538 * child tasks to inherit that and Ctrl-C would not work.
2539 * What we want is for Ctrl-C to work in the exec()-ed
2540 * task, but being ignored by perf stat itself:
2544 signal(SIGINT, skip_signal);
2545 signal(SIGCHLD, skip_signal);
2546 signal(SIGALRM, skip_signal);
2547 signal(SIGABRT, skip_signal);
2549 if (evlist__initialize_ctlfd(evsel_list, stat_config.ctl_fd, stat_config.ctl_fd_ack))
2552 /* Enable ignoring missing threads when -p option is defined. */
2553 evlist__first(evsel_list)->ignore_missing_thread = target.pid;
2555 for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
2556 if (stat_config.run_count != 1 && verbose > 0)
2557 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2561 evlist__reset_prev_raw_counts(evsel_list);
2563 status = run_perf_stat(argc, argv, run_idx);
2564 if (forever && status != -1 && !interval) {
2565 print_counters(NULL, argc, argv);
2566 perf_stat__reset_stats();
2570 if (!forever && status != -1 && (!interval || stat_config.summary))
2571 print_counters(NULL, argc, argv);
2573 evlist__finalize_ctlfd(evsel_list);
2577 * We synthesize the kernel mmap record just so that older tools
2578 * don't emit warnings about not being able to resolve symbols
2579 * due to /proc/sys/kernel/kptr_restrict settings and instead provide
2580 * a saner message about no samples being in the perf.data file.
2582 * This also serves to suppress a warning about f_header.data.size == 0
2583 * in header.c at the moment 'perf stat record' gets introduced, which
2584 * is not really needed once we start adding the stat specific PERF_RECORD_
2585 * records, but the need to suppress the kptr_restrict messages in older
2586 * tools remain -acme
2588 int fd = perf_data__fd(&perf_stat.data);
2590 err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2591 process_synthesized_event,
2592 &perf_stat.session->machines.host);
2594 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2595 "older tools may produce warnings about this file\n.");
2599 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2600 pr_err("failed to write stat round event\n");
2603 if (!perf_stat.data.is_pipe) {
2604 perf_stat.session->header.data_size += perf_stat.bytes_written;
2605 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2608 evlist__close(evsel_list);
2609 perf_session__delete(perf_stat.session);
2612 perf_stat__exit_aggr_mode();
2613 evlist__free_stats(evsel_list);
2615 if (stat_config.iostat_run)
2616 iostat_release(evsel_list);
2618 zfree(&stat_config.walltime_run);
2619 zfree(&stat_config.user_requested_cpu_list);
2621 if (smi_cost && smi_reset)
2622 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2624 evlist__delete(evsel_list);
2626 metricgroup__rblist_exit(&stat_config.metric_events);
2627 evlist__close_control(stat_config.ctl_fd, stat_config.ctl_fd_ack, &stat_config.ctl_fd_close);