4 * Builtin stat command: Give a precise performance counters summary
5 * overview about any workload, CPU or specific PID.
9 $ perf stat ./hackbench 10
13 Performance counter stats for './hackbench 10':
15 1708.761321 task-clock # 11.037 CPUs utilized
16 41,190 context-switches # 0.024 M/sec
17 6,735 CPU-migrations # 0.004 M/sec
18 17,318 page-faults # 0.010 M/sec
19 5,205,202,243 cycles # 3.046 GHz
20 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle
21 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle
22 2,603,501,247 instructions # 0.50 insns per cycle
23 # 1.48 stalled cycles per insn
24 484,357,498 branches # 283.455 M/sec
25 6,388,934 branch-misses # 1.32% of all branches
27 0.154822978 seconds time elapsed
30 * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
32 * Improvements and fixes by:
34 * Arjan van de Ven <arjan@linux.intel.com>
35 * Yanmin Zhang <yanmin.zhang@intel.com>
36 * Wu Fengguang <fengguang.wu@intel.com>
37 * Mike Galbraith <efault@gmx.de>
38 * Paul Mackerras <paulus@samba.org>
39 * Jaswinder Singh Rajput <jaswinder@kernel.org>
41 * Released under the GPL v2. (and only v2, not any later version)
46 #include "util/cgroup.h"
47 #include "util/util.h"
48 #include <subcmd/parse-options.h>
49 #include "util/parse-events.h"
51 #include "util/event.h"
52 #include "util/evlist.h"
53 #include "util/evsel.h"
54 #include "util/debug.h"
55 #include "util/drv_configs.h"
56 #include "util/color.h"
57 #include "util/stat.h"
58 #include "util/header.h"
59 #include "util/cpumap.h"
60 #include "util/thread.h"
61 #include "util/thread_map.h"
62 #include "util/counts.h"
63 #include "util/group.h"
64 #include "util/session.h"
65 #include "util/tool.h"
66 #include "util/string2.h"
67 #include "util/metricgroup.h"
70 #include <linux/time64.h>
71 #include <api/fs/fs.h>
75 #include <sys/prctl.h>
79 #include <sys/types.h>
84 #include "sane_ctype.h"
86 #define DEFAULT_SEPARATOR " "
87 #define CNTR_NOT_SUPPORTED "<not supported>"
88 #define CNTR_NOT_COUNTED "<not counted>"
89 #define FREEZE_ON_SMI_PATH "devices/cpu/freeze_on_smi"
91 static void print_counters(struct timespec
*ts
, int argc
, const char **argv
);
93 /* Default events used for perf stat -T */
94 static const char *transaction_attrs
= {
106 /* More limited version when the CPU does not have all events. */
107 static const char * transaction_limited_attrs
= {
117 static const char * topdown_attrs
[] = {
118 "topdown-total-slots",
119 "topdown-slots-retired",
120 "topdown-recovery-bubbles",
121 "topdown-fetch-bubbles",
122 "topdown-slots-issued",
126 static const char *smi_cost_attrs
= {
134 static struct perf_evlist
*evsel_list
;
136 static struct rblist metric_events
;
138 static struct target target
= {
142 typedef int (*aggr_get_id_t
)(struct cpu_map
*m
, int cpu
);
144 static int run_count
= 1;
145 static bool no_inherit
= false;
146 static volatile pid_t child_pid
= -1;
147 static bool null_run
= false;
148 static int detailed_run
= 0;
149 static bool transaction_run
;
150 static bool topdown_run
= false;
151 static bool smi_cost
= false;
152 static bool smi_reset
= false;
153 static bool big_num
= true;
154 static int big_num_opt
= -1;
155 static const char *csv_sep
= NULL
;
156 static bool csv_output
= false;
157 static bool group
= false;
158 static const char *pre_cmd
= NULL
;
159 static const char *post_cmd
= NULL
;
160 static bool sync_run
= false;
161 static unsigned int initial_delay
= 0;
162 static unsigned int unit_width
= 4; /* strlen("unit") */
163 static bool forever
= false;
164 static bool metric_only
= false;
165 static bool force_metric_only
= false;
166 static bool no_merge
= false;
167 static struct timespec ref_time
;
168 static struct cpu_map
*aggr_map
;
169 static aggr_get_id_t aggr_get_id
;
170 static bool append_file
;
171 static const char *output_name
;
172 static int output_fd
;
173 static int print_free_counters_hint
;
177 struct perf_data data
;
178 struct perf_session
*session
;
180 struct perf_tool tool
;
182 struct cpu_map
*cpus
;
183 struct thread_map
*threads
;
184 enum aggr_mode aggr_mode
;
187 static struct perf_stat perf_stat
;
188 #define STAT_RECORD perf_stat.record
190 static volatile int done
= 0;
192 static struct perf_stat_config stat_config
= {
193 .aggr_mode
= AGGR_GLOBAL
,
197 static bool is_duration_time(struct perf_evsel
*evsel
)
199 return !strcmp(evsel
->name
, "duration_time");
202 static inline void diff_timespec(struct timespec
*r
, struct timespec
*a
,
205 r
->tv_sec
= a
->tv_sec
- b
->tv_sec
;
206 if (a
->tv_nsec
< b
->tv_nsec
) {
207 r
->tv_nsec
= a
->tv_nsec
+ NSEC_PER_SEC
- b
->tv_nsec
;
210 r
->tv_nsec
= a
->tv_nsec
- b
->tv_nsec
;
214 static void perf_stat__reset_stats(void)
218 perf_evlist__reset_stats(evsel_list
);
219 perf_stat__reset_shadow_stats();
221 for (i
= 0; i
< stat_config
.stats_num
; i
++)
222 perf_stat__reset_shadow_per_stat(&stat_config
.stats
[i
]);
225 static int create_perf_stat_counter(struct perf_evsel
*evsel
)
227 struct perf_event_attr
*attr
= &evsel
->attr
;
228 struct perf_evsel
*leader
= evsel
->leader
;
230 if (stat_config
.scale
) {
231 attr
->read_format
= PERF_FORMAT_TOTAL_TIME_ENABLED
|
232 PERF_FORMAT_TOTAL_TIME_RUNNING
;
236 * The event is part of non trivial group, let's enable
237 * the group read (for leader) and ID retrieval for all
240 if (leader
->nr_members
> 1)
241 attr
->read_format
|= PERF_FORMAT_ID
|PERF_FORMAT_GROUP
;
243 attr
->inherit
= !no_inherit
;
246 * Some events get initialized with sample_(period/type) set,
247 * like tracepoints. Clear it up for counting.
249 attr
->sample_period
= 0;
252 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
253 * while avoiding that older tools show confusing messages.
255 * However for pipe sessions we need to keep it zero,
256 * because script's perf_evsel__check_attr is triggered
257 * by attr->sample_type != 0, and we can't run it on
260 if (!(STAT_RECORD
&& perf_stat
.data
.is_pipe
))
261 attr
->sample_type
= PERF_SAMPLE_IDENTIFIER
;
264 * Disabling all counters initially, they will be enabled
265 * either manually by us or by kernel via enable_on_exec
268 if (perf_evsel__is_group_leader(evsel
)) {
272 * In case of initial_delay we enable tracee
275 if (target__none(&target
) && !initial_delay
)
276 attr
->enable_on_exec
= 1;
279 if (target__has_cpu(&target
) && !target__has_per_thread(&target
))
280 return perf_evsel__open_per_cpu(evsel
, perf_evsel__cpus(evsel
));
282 return perf_evsel__open_per_thread(evsel
, evsel_list
->threads
);
286 * Does the counter have nsecs as a unit?
288 static inline int nsec_counter(struct perf_evsel
*evsel
)
290 if (perf_evsel__match(evsel
, SOFTWARE
, SW_CPU_CLOCK
) ||
291 perf_evsel__match(evsel
, SOFTWARE
, SW_TASK_CLOCK
))
297 static int process_synthesized_event(struct perf_tool
*tool __maybe_unused
,
298 union perf_event
*event
,
299 struct perf_sample
*sample __maybe_unused
,
300 struct machine
*machine __maybe_unused
)
302 if (perf_data__write(&perf_stat
.data
, event
, event
->header
.size
) < 0) {
303 pr_err("failed to write perf data, error: %m\n");
307 perf_stat
.bytes_written
+= event
->header
.size
;
311 static int write_stat_round_event(u64 tm
, u64 type
)
313 return perf_event__synthesize_stat_round(NULL
, tm
, type
,
314 process_synthesized_event
,
318 #define WRITE_STAT_ROUND_EVENT(time, interval) \
319 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
321 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
324 perf_evsel__write_stat_event(struct perf_evsel
*counter
, u32 cpu
, u32 thread
,
325 struct perf_counts_values
*count
)
327 struct perf_sample_id
*sid
= SID(counter
, cpu
, thread
);
329 return perf_event__synthesize_stat(NULL
, cpu
, thread
, sid
->id
, count
,
330 process_synthesized_event
, NULL
);
334 * Read out the results of a single counter:
335 * do not aggregate counts across CPUs in system-wide mode
337 static int read_counter(struct perf_evsel
*counter
)
339 int nthreads
= thread_map__nr(evsel_list
->threads
);
340 int ncpus
, cpu
, thread
;
342 if (target__has_cpu(&target
) && !target__has_per_thread(&target
))
343 ncpus
= perf_evsel__nr_cpus(counter
);
347 if (!counter
->supported
)
350 if (counter
->system_wide
)
353 for (thread
= 0; thread
< nthreads
; thread
++) {
354 for (cpu
= 0; cpu
< ncpus
; cpu
++) {
355 struct perf_counts_values
*count
;
357 count
= perf_counts(counter
->counts
, cpu
, thread
);
360 * The leader's group read loads data into its group members
361 * (via perf_evsel__read_counter) and sets threir count->loaded.
363 if (!count
->loaded
&&
364 perf_evsel__read_counter(counter
, cpu
, thread
)) {
365 counter
->counts
->scaled
= -1;
366 perf_counts(counter
->counts
, cpu
, thread
)->ena
= 0;
367 perf_counts(counter
->counts
, cpu
, thread
)->run
= 0;
371 count
->loaded
= false;
374 if (perf_evsel__write_stat_event(counter
, cpu
, thread
, count
)) {
375 pr_err("failed to write stat event\n");
381 fprintf(stat_config
.output
,
382 "%s: %d: %" PRIu64
" %" PRIu64
" %" PRIu64
"\n",
383 perf_evsel__name(counter
),
385 count
->val
, count
->ena
, count
->run
);
393 static void read_counters(void)
395 struct perf_evsel
*counter
;
398 evlist__for_each_entry(evsel_list
, counter
) {
399 ret
= read_counter(counter
);
401 pr_debug("failed to read counter %s\n", counter
->name
);
403 if (ret
== 0 && perf_stat_process_counter(&stat_config
, counter
))
404 pr_warning("failed to process counter %s\n", counter
->name
);
408 static void process_interval(void)
410 struct timespec ts
, rs
;
414 clock_gettime(CLOCK_MONOTONIC
, &ts
);
415 diff_timespec(&rs
, &ts
, &ref_time
);
418 if (WRITE_STAT_ROUND_EVENT(rs
.tv_sec
* NSEC_PER_SEC
+ rs
.tv_nsec
, INTERVAL
))
419 pr_err("failed to write stat round event\n");
422 init_stats(&walltime_nsecs_stats
);
423 update_stats(&walltime_nsecs_stats
, stat_config
.interval
* 1000000);
424 print_counters(&rs
, 0, NULL
);
427 static void enable_counters(void)
430 usleep(initial_delay
* USEC_PER_MSEC
);
433 * We need to enable counters only if:
434 * - we don't have tracee (attaching to task or cpu)
435 * - we have initial delay configured
437 if (!target__none(&target
) || initial_delay
)
438 perf_evlist__enable(evsel_list
);
441 static void disable_counters(void)
444 * If we don't have tracee (attaching to task or cpu), counters may
445 * still be running. To get accurate group ratios, we must stop groups
446 * from counting before reading their constituent counters.
448 if (!target__none(&target
))
449 perf_evlist__disable(evsel_list
);
452 static volatile int workload_exec_errno
;
455 * perf_evlist__prepare_workload will send a SIGUSR1
456 * if the fork fails, since we asked by setting its
457 * want_signal to true.
459 static void workload_exec_failed_signal(int signo __maybe_unused
, siginfo_t
*info
,
460 void *ucontext __maybe_unused
)
462 workload_exec_errno
= info
->si_value
.sival_int
;
465 static int perf_stat_synthesize_config(bool is_pipe
)
470 err
= perf_event__synthesize_attrs(NULL
, perf_stat
.session
,
471 process_synthesized_event
);
473 pr_err("Couldn't synthesize attrs.\n");
478 err
= perf_event__synthesize_extra_attr(NULL
,
480 process_synthesized_event
,
483 err
= perf_event__synthesize_thread_map2(NULL
, evsel_list
->threads
,
484 process_synthesized_event
,
487 pr_err("Couldn't synthesize thread map.\n");
491 err
= perf_event__synthesize_cpu_map(NULL
, evsel_list
->cpus
,
492 process_synthesized_event
, NULL
);
494 pr_err("Couldn't synthesize thread map.\n");
498 err
= perf_event__synthesize_stat_config(NULL
, &stat_config
,
499 process_synthesized_event
, NULL
);
501 pr_err("Couldn't synthesize config.\n");
508 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
510 static int __store_counter_ids(struct perf_evsel
*counter
,
511 struct cpu_map
*cpus
,
512 struct thread_map
*threads
)
516 for (cpu
= 0; cpu
< cpus
->nr
; cpu
++) {
517 for (thread
= 0; thread
< threads
->nr
; thread
++) {
518 int fd
= FD(counter
, cpu
, thread
);
520 if (perf_evlist__id_add_fd(evsel_list
, counter
,
521 cpu
, thread
, fd
) < 0)
529 static int store_counter_ids(struct perf_evsel
*counter
)
531 struct cpu_map
*cpus
= counter
->cpus
;
532 struct thread_map
*threads
= counter
->threads
;
534 if (perf_evsel__alloc_id(counter
, cpus
->nr
, threads
->nr
))
537 return __store_counter_ids(counter
, cpus
, threads
);
540 static bool perf_evsel__should_store_id(struct perf_evsel
*counter
)
542 return STAT_RECORD
|| counter
->attr
.read_format
& PERF_FORMAT_ID
;
545 static struct perf_evsel
*perf_evsel__reset_weak_group(struct perf_evsel
*evsel
)
547 struct perf_evsel
*c2
, *leader
;
550 leader
= evsel
->leader
;
551 pr_debug("Weak group for %s/%d failed\n",
552 leader
->name
, leader
->nr_members
);
555 * for_each_group_member doesn't work here because it doesn't
556 * include the first entry.
558 evlist__for_each_entry(evsel_list
, c2
) {
561 if (c2
->leader
== leader
) {
563 perf_evsel__close(c2
);
571 static int __run_perf_stat(int argc
, const char **argv
)
573 int interval
= stat_config
.interval
;
575 unsigned long long t0
, t1
;
576 struct perf_evsel
*counter
;
580 const bool forks
= (argc
> 0);
581 bool is_pipe
= STAT_RECORD
? perf_stat
.data
.is_pipe
: false;
582 struct perf_evsel_config_term
*err_term
;
585 ts
.tv_sec
= interval
/ USEC_PER_MSEC
;
586 ts
.tv_nsec
= (interval
% USEC_PER_MSEC
) * NSEC_PER_MSEC
;
593 if (perf_evlist__prepare_workload(evsel_list
, &target
, argv
, is_pipe
,
594 workload_exec_failed_signal
) < 0) {
595 perror("failed to prepare workload");
598 child_pid
= evsel_list
->workload
.pid
;
602 perf_evlist__set_leader(evsel_list
);
604 evlist__for_each_entry(evsel_list
, counter
) {
606 if (create_perf_stat_counter(counter
) < 0) {
608 /* Weak group failed. Reset the group. */
609 if ((errno
== EINVAL
|| errno
== EBADF
) &&
610 counter
->leader
!= counter
&&
611 counter
->weak_group
) {
612 counter
= perf_evsel__reset_weak_group(counter
);
617 * PPC returns ENXIO for HW counters until 2.6.37
618 * (behavior changed with commit b0a873e).
620 if (errno
== EINVAL
|| errno
== ENOSYS
||
621 errno
== ENOENT
|| errno
== EOPNOTSUPP
||
624 ui__warning("%s event is not supported by the kernel.\n",
625 perf_evsel__name(counter
));
626 counter
->supported
= false;
628 if ((counter
->leader
!= counter
) ||
629 !(counter
->leader
->nr_members
> 1))
631 } else if (perf_evsel__fallback(counter
, errno
, msg
, sizeof(msg
))) {
633 ui__warning("%s\n", msg
);
637 perf_evsel__open_strerror(counter
, &target
,
638 errno
, msg
, sizeof(msg
));
639 ui__error("%s\n", msg
);
642 kill(child_pid
, SIGTERM
);
646 counter
->supported
= true;
648 l
= strlen(counter
->unit
);
652 if (perf_evsel__should_store_id(counter
) &&
653 store_counter_ids(counter
))
657 if (perf_evlist__apply_filters(evsel_list
, &counter
)) {
658 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
659 counter
->filter
, perf_evsel__name(counter
), errno
,
660 str_error_r(errno
, msg
, sizeof(msg
)));
664 if (perf_evlist__apply_drv_configs(evsel_list
, &counter
, &err_term
)) {
665 pr_err("failed to set config \"%s\" on event %s with %d (%s)\n",
666 err_term
->val
.drv_cfg
, perf_evsel__name(counter
), errno
,
667 str_error_r(errno
, msg
, sizeof(msg
)));
672 int err
, fd
= perf_data__fd(&perf_stat
.data
);
675 err
= perf_header__write_pipe(perf_data__fd(&perf_stat
.data
));
677 err
= perf_session__write_header(perf_stat
.session
, evsel_list
,
684 err
= perf_stat_synthesize_config(is_pipe
);
690 * Enable counters and exec the command:
693 clock_gettime(CLOCK_MONOTONIC
, &ref_time
);
696 perf_evlist__start_workload(evsel_list
);
700 while (!waitpid(child_pid
, &status
, WNOHANG
)) {
701 nanosleep(&ts
, NULL
);
705 waitpid(child_pid
, &status
, 0);
707 if (workload_exec_errno
) {
708 const char *emsg
= str_error_r(workload_exec_errno
, msg
, sizeof(msg
));
709 pr_err("Workload failed: %s\n", emsg
);
713 if (WIFSIGNALED(status
))
714 psignal(WTERMSIG(status
), argv
[0]);
718 nanosleep(&ts
, NULL
);
728 update_stats(&walltime_nsecs_stats
, t1
- t0
);
731 * Closing a group leader splits the group, and as we only disable
732 * group leaders, results in remaining events becoming enabled. To
733 * avoid arbitrary skew, we must read all counters before closing any
737 perf_evlist__close(evsel_list
);
739 return WEXITSTATUS(status
);
742 static int run_perf_stat(int argc
, const char **argv
)
747 ret
= system(pre_cmd
);
755 ret
= __run_perf_stat(argc
, argv
);
760 ret
= system(post_cmd
);
768 static void print_running(u64 run
, u64 ena
)
771 fprintf(stat_config
.output
, "%s%" PRIu64
"%s%.2f",
775 ena
? 100.0 * run
/ ena
: 100.0);
776 } else if (run
!= ena
) {
777 fprintf(stat_config
.output
, " (%.2f%%)", 100.0 * run
/ ena
);
781 static void print_noise_pct(double total
, double avg
)
783 double pct
= rel_stddev_stats(total
, avg
);
786 fprintf(stat_config
.output
, "%s%.2f%%", csv_sep
, pct
);
788 fprintf(stat_config
.output
, " ( +-%6.2f%% )", pct
);
791 static void print_noise(struct perf_evsel
*evsel
, double avg
)
793 struct perf_stat_evsel
*ps
;
799 print_noise_pct(stddev_stats(&ps
->res_stats
[0]), avg
);
802 static void aggr_printout(struct perf_evsel
*evsel
, int id
, int nr
)
804 switch (stat_config
.aggr_mode
) {
806 fprintf(stat_config
.output
, "S%d-C%*d%s%*d%s",
807 cpu_map__id_to_socket(id
),
809 cpu_map__id_to_cpu(id
),
816 fprintf(stat_config
.output
, "S%*d%s%*d%s",
825 fprintf(stat_config
.output
, "CPU%*d%s",
827 perf_evsel__cpus(evsel
)->map
[id
], csv_sep
);
830 fprintf(stat_config
.output
, "%*s-%*d%s",
832 thread_map__comm(evsel
->threads
, id
),
834 thread_map__pid(evsel
->threads
, id
),
850 struct perf_evsel
*evsel
;
853 #define METRIC_LEN 35
855 static void new_line_std(void *ctx
)
857 struct outstate
*os
= ctx
;
862 static void do_new_line_std(struct outstate
*os
)
865 fputs(os
->prefix
, os
->fh
);
866 aggr_printout(os
->evsel
, os
->id
, os
->nr
);
867 if (stat_config
.aggr_mode
== AGGR_NONE
)
868 fprintf(os
->fh
, " ");
869 fprintf(os
->fh
, " ");
872 static void print_metric_std(void *ctx
, const char *color
, const char *fmt
,
873 const char *unit
, double val
)
875 struct outstate
*os
= ctx
;
878 bool newline
= os
->newline
;
882 if (unit
== NULL
|| fmt
== NULL
) {
883 fprintf(out
, "%-*s", METRIC_LEN
, "");
890 n
= fprintf(out
, " # ");
892 n
+= color_fprintf(out
, color
, fmt
, val
);
894 n
+= fprintf(out
, fmt
, val
);
895 fprintf(out
, " %-*s", METRIC_LEN
- n
- 1, unit
);
898 static void new_line_csv(void *ctx
)
900 struct outstate
*os
= ctx
;
905 fprintf(os
->fh
, "%s%s", os
->prefix
, csv_sep
);
906 aggr_printout(os
->evsel
, os
->id
, os
->nr
);
907 for (i
= 0; i
< os
->nfields
; i
++)
908 fputs(csv_sep
, os
->fh
);
911 static void print_metric_csv(void *ctx
,
912 const char *color __maybe_unused
,
913 const char *fmt
, const char *unit
, double val
)
915 struct outstate
*os
= ctx
;
917 char buf
[64], *vals
, *ends
;
919 if (unit
== NULL
|| fmt
== NULL
) {
920 fprintf(out
, "%s%s", csv_sep
, csv_sep
);
923 snprintf(buf
, sizeof(buf
), fmt
, val
);
924 ends
= vals
= ltrim(buf
);
925 while (isdigit(*ends
) || *ends
== '.')
928 while (isspace(*unit
))
930 fprintf(out
, "%s%s%s%s", csv_sep
, vals
, csv_sep
, unit
);
933 #define METRIC_ONLY_LEN 20
935 /* Filter out some columns that don't work well in metrics only mode */
937 static bool valid_only_metric(const char *unit
)
941 if (strstr(unit
, "/sec") ||
942 strstr(unit
, "hz") ||
943 strstr(unit
, "Hz") ||
944 strstr(unit
, "CPUs utilized"))
949 static const char *fixunit(char *buf
, struct perf_evsel
*evsel
,
952 if (!strncmp(unit
, "of all", 6)) {
953 snprintf(buf
, 1024, "%s %s", perf_evsel__name(evsel
),
960 static void print_metric_only(void *ctx
, const char *color
, const char *fmt
,
961 const char *unit
, double val
)
963 struct outstate
*os
= ctx
;
967 unsigned mlen
= METRIC_ONLY_LEN
;
969 if (!valid_only_metric(unit
))
971 unit
= fixunit(buf
, os
->evsel
, unit
);
973 n
= color_fprintf(out
, color
, fmt
, val
);
975 n
= fprintf(out
, fmt
, val
);
976 if (n
> METRIC_ONLY_LEN
)
978 if (mlen
< strlen(unit
))
979 mlen
= strlen(unit
) + 1;
980 fprintf(out
, "%*s", mlen
- n
, "");
983 static void print_metric_only_csv(void *ctx
, const char *color __maybe_unused
,
985 const char *unit
, double val
)
987 struct outstate
*os
= ctx
;
989 char buf
[64], *vals
, *ends
;
992 if (!valid_only_metric(unit
))
994 unit
= fixunit(tbuf
, os
->evsel
, unit
);
995 snprintf(buf
, sizeof buf
, fmt
, val
);
996 ends
= vals
= ltrim(buf
);
997 while (isdigit(*ends
) || *ends
== '.')
1000 fprintf(out
, "%s%s", vals
, csv_sep
);
1003 static void new_line_metric(void *ctx __maybe_unused
)
1007 static void print_metric_header(void *ctx
, const char *color __maybe_unused
,
1008 const char *fmt __maybe_unused
,
1009 const char *unit
, double val __maybe_unused
)
1011 struct outstate
*os
= ctx
;
1014 if (!valid_only_metric(unit
))
1016 unit
= fixunit(tbuf
, os
->evsel
, unit
);
1018 fprintf(os
->fh
, "%s%s", unit
, csv_sep
);
1020 fprintf(os
->fh
, "%-*s ", METRIC_ONLY_LEN
, unit
);
1023 static void nsec_printout(int id
, int nr
, struct perf_evsel
*evsel
, double avg
)
1025 FILE *output
= stat_config
.output
;
1026 double msecs
= avg
/ NSEC_PER_MSEC
;
1027 const char *fmt_v
, *fmt_n
;
1030 fmt_v
= csv_output
? "%.6f%s" : "%18.6f%s";
1031 fmt_n
= csv_output
? "%s" : "%-25s";
1033 aggr_printout(evsel
, id
, nr
);
1035 scnprintf(name
, sizeof(name
), "%s%s",
1036 perf_evsel__name(evsel
), csv_output
? "" : " (msec)");
1038 fprintf(output
, fmt_v
, msecs
, csv_sep
);
1041 fprintf(output
, "%s%s", evsel
->unit
, csv_sep
);
1043 fprintf(output
, "%-*s%s", unit_width
, evsel
->unit
, csv_sep
);
1045 fprintf(output
, fmt_n
, name
);
1048 fprintf(output
, "%s%s", csv_sep
, evsel
->cgrp
->name
);
1051 static int first_shadow_cpu(struct perf_evsel
*evsel
, int id
)
1058 if (stat_config
.aggr_mode
== AGGR_NONE
)
1061 if (stat_config
.aggr_mode
== AGGR_GLOBAL
)
1064 for (i
= 0; i
< perf_evsel__nr_cpus(evsel
); i
++) {
1065 int cpu2
= perf_evsel__cpus(evsel
)->map
[i
];
1067 if (aggr_get_id(evsel_list
->cpus
, cpu2
) == id
)
1073 static void abs_printout(int id
, int nr
, struct perf_evsel
*evsel
, double avg
)
1075 FILE *output
= stat_config
.output
;
1076 double sc
= evsel
->scale
;
1080 fmt
= floor(sc
) != sc
? "%.2f%s" : "%.0f%s";
1083 fmt
= floor(sc
) != sc
? "%'18.2f%s" : "%'18.0f%s";
1085 fmt
= floor(sc
) != sc
? "%18.2f%s" : "%18.0f%s";
1088 aggr_printout(evsel
, id
, nr
);
1090 fprintf(output
, fmt
, avg
, csv_sep
);
1093 fprintf(output
, "%-*s%s",
1094 csv_output
? 0 : unit_width
,
1095 evsel
->unit
, csv_sep
);
1097 fprintf(output
, "%-*s", csv_output
? 0 : 25, perf_evsel__name(evsel
));
1100 fprintf(output
, "%s%s", csv_sep
, evsel
->cgrp
->name
);
1103 static void printout(int id
, int nr
, struct perf_evsel
*counter
, double uval
,
1104 char *prefix
, u64 run
, u64 ena
, double noise
,
1105 struct runtime_stat
*st
)
1107 struct perf_stat_output_ctx out
;
1108 struct outstate os
= {
1109 .fh
= stat_config
.output
,
1110 .prefix
= prefix
? prefix
: "",
1115 print_metric_t pm
= print_metric_std
;
1119 nl
= new_line_metric
;
1121 pm
= print_metric_only_csv
;
1123 pm
= print_metric_only
;
1127 if (csv_output
&& !metric_only
) {
1128 static int aggr_fields
[] = {
1136 pm
= print_metric_csv
;
1139 os
.nfields
+= aggr_fields
[stat_config
.aggr_mode
];
1143 if (run
== 0 || ena
== 0 || counter
->counts
->scaled
== -1) {
1145 pm(&os
, NULL
, "", "", 0);
1148 aggr_printout(counter
, id
, nr
);
1150 fprintf(stat_config
.output
, "%*s%s",
1151 csv_output
? 0 : 18,
1152 counter
->supported
? CNTR_NOT_COUNTED
: CNTR_NOT_SUPPORTED
,
1155 if (counter
->supported
)
1156 print_free_counters_hint
= 1;
1158 fprintf(stat_config
.output
, "%-*s%s",
1159 csv_output
? 0 : unit_width
,
1160 counter
->unit
, csv_sep
);
1162 fprintf(stat_config
.output
, "%*s",
1163 csv_output
? 0 : -25,
1164 perf_evsel__name(counter
));
1167 fprintf(stat_config
.output
, "%s%s",
1168 csv_sep
, counter
->cgrp
->name
);
1171 pm(&os
, NULL
, NULL
, "", 0);
1172 print_noise(counter
, noise
);
1173 print_running(run
, ena
);
1175 pm(&os
, NULL
, NULL
, "", 0);
1181 else if (nsec_counter(counter
))
1182 nsec_printout(id
, nr
, counter
, uval
);
1184 abs_printout(id
, nr
, counter
, uval
);
1186 out
.print_metric
= pm
;
1189 out
.force_header
= false;
1191 if (csv_output
&& !metric_only
) {
1192 print_noise(counter
, noise
);
1193 print_running(run
, ena
);
1196 perf_stat__print_shadow_stats(counter
, uval
,
1197 first_shadow_cpu(counter
, id
),
1198 &out
, &metric_events
, st
);
1199 if (!csv_output
&& !metric_only
) {
1200 print_noise(counter
, noise
);
1201 print_running(run
, ena
);
1205 static void aggr_update_shadow(void)
1209 struct perf_evsel
*counter
;
1211 for (s
= 0; s
< aggr_map
->nr
; s
++) {
1212 id
= aggr_map
->map
[s
];
1213 evlist__for_each_entry(evsel_list
, counter
) {
1215 for (cpu
= 0; cpu
< perf_evsel__nr_cpus(counter
); cpu
++) {
1216 s2
= aggr_get_id(evsel_list
->cpus
, cpu
);
1219 val
+= perf_counts(counter
->counts
, cpu
, 0)->val
;
1221 perf_stat__update_shadow_stats(counter
, val
,
1222 first_shadow_cpu(counter
, id
),
1228 static void collect_all_aliases(struct perf_evsel
*counter
,
1229 void (*cb
)(struct perf_evsel
*counter
, void *data
,
1233 struct perf_evsel
*alias
;
1235 alias
= list_prepare_entry(counter
, &(evsel_list
->entries
), node
);
1236 list_for_each_entry_continue (alias
, &evsel_list
->entries
, node
) {
1237 if (strcmp(perf_evsel__name(alias
), perf_evsel__name(counter
)) ||
1238 alias
->scale
!= counter
->scale
||
1239 alias
->cgrp
!= counter
->cgrp
||
1240 strcmp(alias
->unit
, counter
->unit
) ||
1241 nsec_counter(alias
) != nsec_counter(counter
))
1243 alias
->merged_stat
= true;
1244 cb(alias
, data
, false);
1248 static bool collect_data(struct perf_evsel
*counter
,
1249 void (*cb
)(struct perf_evsel
*counter
, void *data
,
1253 if (counter
->merged_stat
)
1255 cb(counter
, data
, true);
1256 if (!no_merge
&& counter
->auto_merge_stats
)
1257 collect_all_aliases(counter
, cb
, data
);
1268 static void aggr_cb(struct perf_evsel
*counter
, void *data
, bool first
)
1270 struct aggr_data
*ad
= data
;
1273 for (cpu
= 0; cpu
< perf_evsel__nr_cpus(counter
); cpu
++) {
1274 struct perf_counts_values
*counts
;
1276 s2
= aggr_get_id(perf_evsel__cpus(counter
), cpu
);
1281 counts
= perf_counts(counter
->counts
, cpu
, 0);
1283 * When any result is bad, make them all to give
1284 * consistent output in interval mode.
1286 if (counts
->ena
== 0 || counts
->run
== 0 ||
1287 counter
->counts
->scaled
== -1) {
1292 ad
->val
+= counts
->val
;
1293 ad
->ena
+= counts
->ena
;
1294 ad
->run
+= counts
->run
;
1298 static void print_aggr(char *prefix
)
1300 FILE *output
= stat_config
.output
;
1301 struct perf_evsel
*counter
;
1307 if (!(aggr_map
|| aggr_get_id
))
1310 aggr_update_shadow();
1313 * With metric_only everything is on a single line.
1314 * Without each counter has its own line.
1316 for (s
= 0; s
< aggr_map
->nr
; s
++) {
1317 struct aggr_data ad
;
1318 if (prefix
&& metric_only
)
1319 fprintf(output
, "%s", prefix
);
1321 ad
.id
= id
= aggr_map
->map
[s
];
1323 evlist__for_each_entry(evsel_list
, counter
) {
1324 if (is_duration_time(counter
))
1327 ad
.val
= ad
.ena
= ad
.run
= 0;
1329 if (!collect_data(counter
, aggr_cb
, &ad
))
1335 if (first
&& metric_only
) {
1337 aggr_printout(counter
, id
, nr
);
1339 if (prefix
&& !metric_only
)
1340 fprintf(output
, "%s", prefix
);
1342 uval
= val
* counter
->scale
;
1343 printout(id
, nr
, counter
, uval
, prefix
, run
, ena
, 1.0,
1346 fputc('\n', output
);
1349 fputc('\n', output
);
1353 static int cmp_val(const void *a
, const void *b
)
1355 return ((struct perf_aggr_thread_value
*)b
)->val
-
1356 ((struct perf_aggr_thread_value
*)a
)->val
;
1359 static struct perf_aggr_thread_value
*sort_aggr_thread(
1360 struct perf_evsel
*counter
,
1361 int nthreads
, int ncpus
,
1364 int cpu
, thread
, i
= 0;
1366 struct perf_aggr_thread_value
*buf
;
1368 buf
= calloc(nthreads
, sizeof(struct perf_aggr_thread_value
));
1372 for (thread
= 0; thread
< nthreads
; thread
++) {
1373 u64 ena
= 0, run
= 0, val
= 0;
1375 for (cpu
= 0; cpu
< ncpus
; cpu
++) {
1376 val
+= perf_counts(counter
->counts
, cpu
, thread
)->val
;
1377 ena
+= perf_counts(counter
->counts
, cpu
, thread
)->ena
;
1378 run
+= perf_counts(counter
->counts
, cpu
, thread
)->run
;
1381 uval
= val
* counter
->scale
;
1384 * Skip value 0 when enabling --per-thread globally,
1385 * otherwise too many 0 output.
1387 if (uval
== 0.0 && target__has_per_thread(&target
))
1390 buf
[i
].counter
= counter
;
1399 qsort(buf
, i
, sizeof(struct perf_aggr_thread_value
), cmp_val
);
1407 static void print_aggr_thread(struct perf_evsel
*counter
, char *prefix
)
1409 FILE *output
= stat_config
.output
;
1410 int nthreads
= thread_map__nr(counter
->threads
);
1411 int ncpus
= cpu_map__nr(counter
->cpus
);
1412 int thread
, sorted_threads
, id
;
1413 struct perf_aggr_thread_value
*buf
;
1415 buf
= sort_aggr_thread(counter
, nthreads
, ncpus
, &sorted_threads
);
1417 perror("cannot sort aggr thread");
1421 for (thread
= 0; thread
< sorted_threads
; thread
++) {
1423 fprintf(output
, "%s", prefix
);
1425 id
= buf
[thread
].id
;
1426 if (stat_config
.stats
)
1427 printout(id
, 0, buf
[thread
].counter
, buf
[thread
].uval
,
1428 prefix
, buf
[thread
].run
, buf
[thread
].ena
, 1.0,
1429 &stat_config
.stats
[id
]);
1431 printout(id
, 0, buf
[thread
].counter
, buf
[thread
].uval
,
1432 prefix
, buf
[thread
].run
, buf
[thread
].ena
, 1.0,
1434 fputc('\n', output
);
1441 double avg
, avg_enabled
, avg_running
;
1444 static void counter_aggr_cb(struct perf_evsel
*counter
, void *data
,
1445 bool first __maybe_unused
)
1447 struct caggr_data
*cd
= data
;
1448 struct perf_stat_evsel
*ps
= counter
->stats
;
1450 cd
->avg
+= avg_stats(&ps
->res_stats
[0]);
1451 cd
->avg_enabled
+= avg_stats(&ps
->res_stats
[1]);
1452 cd
->avg_running
+= avg_stats(&ps
->res_stats
[2]);
1456 * Print out the results of a single counter:
1457 * aggregated counts in system-wide mode
1459 static void print_counter_aggr(struct perf_evsel
*counter
, char *prefix
)
1461 FILE *output
= stat_config
.output
;
1463 struct caggr_data cd
= { .avg
= 0.0 };
1465 if (!collect_data(counter
, counter_aggr_cb
, &cd
))
1468 if (prefix
&& !metric_only
)
1469 fprintf(output
, "%s", prefix
);
1471 uval
= cd
.avg
* counter
->scale
;
1472 printout(-1, 0, counter
, uval
, prefix
, cd
.avg_running
, cd
.avg_enabled
,
1475 fprintf(output
, "\n");
1478 static void counter_cb(struct perf_evsel
*counter
, void *data
,
1479 bool first __maybe_unused
)
1481 struct aggr_data
*ad
= data
;
1483 ad
->val
+= perf_counts(counter
->counts
, ad
->cpu
, 0)->val
;
1484 ad
->ena
+= perf_counts(counter
->counts
, ad
->cpu
, 0)->ena
;
1485 ad
->run
+= perf_counts(counter
->counts
, ad
->cpu
, 0)->run
;
1489 * Print out the results of a single counter:
1490 * does not use aggregated count in system-wide
1492 static void print_counter(struct perf_evsel
*counter
, char *prefix
)
1494 FILE *output
= stat_config
.output
;
1499 for (cpu
= 0; cpu
< perf_evsel__nr_cpus(counter
); cpu
++) {
1500 struct aggr_data ad
= { .cpu
= cpu
};
1502 if (!collect_data(counter
, counter_cb
, &ad
))
1509 fprintf(output
, "%s", prefix
);
1511 uval
= val
* counter
->scale
;
1512 printout(cpu
, 0, counter
, uval
, prefix
, run
, ena
, 1.0,
1515 fputc('\n', output
);
1519 static void print_no_aggr_metric(char *prefix
)
1523 struct perf_evsel
*counter
;
1527 nrcpus
= evsel_list
->cpus
->nr
;
1528 for (cpu
= 0; cpu
< nrcpus
; cpu
++) {
1532 fputs(prefix
, stat_config
.output
);
1533 evlist__for_each_entry(evsel_list
, counter
) {
1534 if (is_duration_time(counter
))
1537 aggr_printout(counter
, cpu
, 0);
1540 val
= perf_counts(counter
->counts
, cpu
, 0)->val
;
1541 ena
= perf_counts(counter
->counts
, cpu
, 0)->ena
;
1542 run
= perf_counts(counter
->counts
, cpu
, 0)->run
;
1544 uval
= val
* counter
->scale
;
1545 printout(cpu
, 0, counter
, uval
, prefix
, run
, ena
, 1.0,
1548 fputc('\n', stat_config
.output
);
1552 static int aggr_header_lens
[] = {
1560 static const char *aggr_header_csv
[] = {
1561 [AGGR_CORE
] = "core,cpus,",
1562 [AGGR_SOCKET
] = "socket,cpus",
1563 [AGGR_NONE
] = "cpu,",
1564 [AGGR_THREAD
] = "comm-pid,",
1568 static void print_metric_headers(const char *prefix
, bool no_indent
)
1570 struct perf_stat_output_ctx out
;
1571 struct perf_evsel
*counter
;
1572 struct outstate os
= {
1573 .fh
= stat_config
.output
1577 fprintf(stat_config
.output
, "%s", prefix
);
1579 if (!csv_output
&& !no_indent
)
1580 fprintf(stat_config
.output
, "%*s",
1581 aggr_header_lens
[stat_config
.aggr_mode
], "");
1583 if (stat_config
.interval
)
1584 fputs("time,", stat_config
.output
);
1585 fputs(aggr_header_csv
[stat_config
.aggr_mode
],
1586 stat_config
.output
);
1589 /* Print metrics headers only */
1590 evlist__for_each_entry(evsel_list
, counter
) {
1591 if (is_duration_time(counter
))
1595 out
.print_metric
= print_metric_header
;
1596 out
.new_line
= new_line_metric
;
1597 out
.force_header
= true;
1599 perf_stat__print_shadow_stats(counter
, 0,
1605 fputc('\n', stat_config
.output
);
1608 static void print_interval(char *prefix
, struct timespec
*ts
)
1610 FILE *output
= stat_config
.output
;
1611 static int num_print_interval
;
1613 sprintf(prefix
, "%6lu.%09lu%s", ts
->tv_sec
, ts
->tv_nsec
, csv_sep
);
1615 if (num_print_interval
== 0 && !csv_output
) {
1616 switch (stat_config
.aggr_mode
) {
1618 fprintf(output
, "# time socket cpus");
1620 fprintf(output
, " counts %*s events\n", unit_width
, "unit");
1623 fprintf(output
, "# time core cpus");
1625 fprintf(output
, " counts %*s events\n", unit_width
, "unit");
1628 fprintf(output
, "# time CPU");
1630 fprintf(output
, " counts %*s events\n", unit_width
, "unit");
1633 fprintf(output
, "# time comm-pid");
1635 fprintf(output
, " counts %*s events\n", unit_width
, "unit");
1639 fprintf(output
, "# time");
1641 fprintf(output
, " counts %*s events\n", unit_width
, "unit");
1647 if (num_print_interval
== 0 && metric_only
)
1648 print_metric_headers(" ", true);
1649 if (++num_print_interval
== 25)
1650 num_print_interval
= 0;
1653 static void print_header(int argc
, const char **argv
)
1655 FILE *output
= stat_config
.output
;
1661 fprintf(output
, "\n");
1662 fprintf(output
, " Performance counter stats for ");
1663 if (target
.system_wide
)
1664 fprintf(output
, "\'system wide");
1665 else if (target
.cpu_list
)
1666 fprintf(output
, "\'CPU(s) %s", target
.cpu_list
);
1667 else if (!target__has_task(&target
)) {
1668 fprintf(output
, "\'%s", argv
? argv
[0] : "pipe");
1669 for (i
= 1; argv
&& (i
< argc
); i
++)
1670 fprintf(output
, " %s", argv
[i
]);
1671 } else if (target
.pid
)
1672 fprintf(output
, "process id \'%s", target
.pid
);
1674 fprintf(output
, "thread id \'%s", target
.tid
);
1676 fprintf(output
, "\'");
1678 fprintf(output
, " (%d runs)", run_count
);
1679 fprintf(output
, ":\n\n");
1683 static void print_footer(void)
1685 FILE *output
= stat_config
.output
;
1689 fprintf(output
, "\n");
1690 fprintf(output
, " %17.9f seconds time elapsed",
1691 avg_stats(&walltime_nsecs_stats
) / NSEC_PER_SEC
);
1692 if (run_count
> 1) {
1693 fprintf(output
, " ");
1694 print_noise_pct(stddev_stats(&walltime_nsecs_stats
),
1695 avg_stats(&walltime_nsecs_stats
));
1697 fprintf(output
, "\n\n");
1699 if (print_free_counters_hint
&&
1700 sysctl__read_int("kernel/nmi_watchdog", &n
) >= 0 &&
1703 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1704 " echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1706 " echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1709 static void print_counters(struct timespec
*ts
, int argc
, const char **argv
)
1711 int interval
= stat_config
.interval
;
1712 struct perf_evsel
*counter
;
1713 char buf
[64], *prefix
= NULL
;
1715 /* Do not print anything if we record to the pipe. */
1716 if (STAT_RECORD
&& perf_stat
.data
.is_pipe
)
1720 print_interval(prefix
= buf
, ts
);
1722 print_header(argc
, argv
);
1725 static int num_print_iv
;
1727 if (num_print_iv
== 0 && !interval
)
1728 print_metric_headers(prefix
, false);
1729 if (num_print_iv
++ == 25)
1731 if (stat_config
.aggr_mode
== AGGR_GLOBAL
&& prefix
)
1732 fprintf(stat_config
.output
, "%s", prefix
);
1735 switch (stat_config
.aggr_mode
) {
1741 evlist__for_each_entry(evsel_list
, counter
) {
1742 if (is_duration_time(counter
))
1744 print_aggr_thread(counter
, prefix
);
1748 evlist__for_each_entry(evsel_list
, counter
) {
1749 if (is_duration_time(counter
))
1751 print_counter_aggr(counter
, prefix
);
1754 fputc('\n', stat_config
.output
);
1758 print_no_aggr_metric(prefix
);
1760 evlist__for_each_entry(evsel_list
, counter
) {
1761 if (is_duration_time(counter
))
1763 print_counter(counter
, prefix
);
1772 if (!interval
&& !csv_output
)
1775 fflush(stat_config
.output
);
1778 static volatile int signr
= -1;
1780 static void skip_signal(int signo
)
1782 if ((child_pid
== -1) || stat_config
.interval
)
1787 * render child_pid harmless
1788 * won't send SIGTERM to a random
1789 * process in case of race condition
1790 * and fast PID recycling
1795 static void sig_atexit(void)
1800 * avoid race condition with SIGCHLD handler
1801 * in skip_signal() which is modifying child_pid
1802 * goal is to avoid send SIGTERM to a random
1806 sigaddset(&set
, SIGCHLD
);
1807 sigprocmask(SIG_BLOCK
, &set
, &oset
);
1809 if (child_pid
!= -1)
1810 kill(child_pid
, SIGTERM
);
1812 sigprocmask(SIG_SETMASK
, &oset
, NULL
);
1817 signal(signr
, SIG_DFL
);
1818 kill(getpid(), signr
);
1821 static int stat__set_big_num(const struct option
*opt __maybe_unused
,
1822 const char *s __maybe_unused
, int unset
)
1824 big_num_opt
= unset
? 0 : 1;
1828 static int enable_metric_only(const struct option
*opt __maybe_unused
,
1829 const char *s __maybe_unused
, int unset
)
1831 force_metric_only
= true;
1832 metric_only
= !unset
;
1836 static int parse_metric_groups(const struct option
*opt
,
1838 int unset __maybe_unused
)
1840 return metricgroup__parse_groups(opt
, str
, &metric_events
);
1843 static const struct option stat_options
[] = {
1844 OPT_BOOLEAN('T', "transaction", &transaction_run
,
1845 "hardware transaction statistics"),
1846 OPT_CALLBACK('e', "event", &evsel_list
, "event",
1847 "event selector. use 'perf list' to list available events",
1848 parse_events_option
),
1849 OPT_CALLBACK(0, "filter", &evsel_list
, "filter",
1850 "event filter", parse_filter
),
1851 OPT_BOOLEAN('i', "no-inherit", &no_inherit
,
1852 "child tasks do not inherit counters"),
1853 OPT_STRING('p', "pid", &target
.pid
, "pid",
1854 "stat events on existing process id"),
1855 OPT_STRING('t', "tid", &target
.tid
, "tid",
1856 "stat events on existing thread id"),
1857 OPT_BOOLEAN('a', "all-cpus", &target
.system_wide
,
1858 "system-wide collection from all CPUs"),
1859 OPT_BOOLEAN('g', "group", &group
,
1860 "put the counters into a counter group"),
1861 OPT_BOOLEAN('c', "scale", &stat_config
.scale
, "scale/normalize counters"),
1862 OPT_INCR('v', "verbose", &verbose
,
1863 "be more verbose (show counter open errors, etc)"),
1864 OPT_INTEGER('r', "repeat", &run_count
,
1865 "repeat command and print average + stddev (max: 100, forever: 0)"),
1866 OPT_BOOLEAN('n', "null", &null_run
,
1867 "null run - dont start any counters"),
1868 OPT_INCR('d', "detailed", &detailed_run
,
1869 "detailed run - start a lot of events"),
1870 OPT_BOOLEAN('S', "sync", &sync_run
,
1871 "call sync() before starting a run"),
1872 OPT_CALLBACK_NOOPT('B', "big-num", NULL
, NULL
,
1873 "print large numbers with thousands\' separators",
1875 OPT_STRING('C', "cpu", &target
.cpu_list
, "cpu",
1876 "list of cpus to monitor in system-wide"),
1877 OPT_SET_UINT('A', "no-aggr", &stat_config
.aggr_mode
,
1878 "disable CPU count aggregation", AGGR_NONE
),
1879 OPT_BOOLEAN(0, "no-merge", &no_merge
, "Do not merge identical named events"),
1880 OPT_STRING('x', "field-separator", &csv_sep
, "separator",
1881 "print counts with custom separator"),
1882 OPT_CALLBACK('G', "cgroup", &evsel_list
, "name",
1883 "monitor event in cgroup name only", parse_cgroups
),
1884 OPT_STRING('o', "output", &output_name
, "file", "output file name"),
1885 OPT_BOOLEAN(0, "append", &append_file
, "append to the output file"),
1886 OPT_INTEGER(0, "log-fd", &output_fd
,
1887 "log output to fd, instead of stderr"),
1888 OPT_STRING(0, "pre", &pre_cmd
, "command",
1889 "command to run prior to the measured command"),
1890 OPT_STRING(0, "post", &post_cmd
, "command",
1891 "command to run after to the measured command"),
1892 OPT_UINTEGER('I', "interval-print", &stat_config
.interval
,
1893 "print counts at regular interval in ms (>= 10)"),
1894 OPT_SET_UINT(0, "per-socket", &stat_config
.aggr_mode
,
1895 "aggregate counts per processor socket", AGGR_SOCKET
),
1896 OPT_SET_UINT(0, "per-core", &stat_config
.aggr_mode
,
1897 "aggregate counts per physical processor core", AGGR_CORE
),
1898 OPT_SET_UINT(0, "per-thread", &stat_config
.aggr_mode
,
1899 "aggregate counts per thread", AGGR_THREAD
),
1900 OPT_UINTEGER('D', "delay", &initial_delay
,
1901 "ms to wait before starting measurement after program start"),
1902 OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only
, NULL
,
1903 "Only print computed metrics. No raw values", enable_metric_only
),
1904 OPT_BOOLEAN(0, "topdown", &topdown_run
,
1905 "measure topdown level 1 statistics"),
1906 OPT_BOOLEAN(0, "smi-cost", &smi_cost
,
1907 "measure SMI cost"),
1908 OPT_CALLBACK('M', "metrics", &evsel_list
, "metric/metric group list",
1909 "monitor specified metrics or metric groups (separated by ,)",
1910 parse_metric_groups
),
1914 static int perf_stat__get_socket(struct cpu_map
*map
, int cpu
)
1916 return cpu_map__get_socket(map
, cpu
, NULL
);
1919 static int perf_stat__get_core(struct cpu_map
*map
, int cpu
)
1921 return cpu_map__get_core(map
, cpu
, NULL
);
1924 static int cpu_map__get_max(struct cpu_map
*map
)
1928 for (i
= 0; i
< map
->nr
; i
++) {
1929 if (map
->map
[i
] > max
)
1936 static struct cpu_map
*cpus_aggr_map
;
1938 static int perf_stat__get_aggr(aggr_get_id_t get_id
, struct cpu_map
*map
, int idx
)
1945 cpu
= map
->map
[idx
];
1947 if (cpus_aggr_map
->map
[cpu
] == -1)
1948 cpus_aggr_map
->map
[cpu
] = get_id(map
, idx
);
1950 return cpus_aggr_map
->map
[cpu
];
1953 static int perf_stat__get_socket_cached(struct cpu_map
*map
, int idx
)
1955 return perf_stat__get_aggr(perf_stat__get_socket
, map
, idx
);
1958 static int perf_stat__get_core_cached(struct cpu_map
*map
, int idx
)
1960 return perf_stat__get_aggr(perf_stat__get_core
, map
, idx
);
1963 static int perf_stat_init_aggr_mode(void)
1967 switch (stat_config
.aggr_mode
) {
1969 if (cpu_map__build_socket_map(evsel_list
->cpus
, &aggr_map
)) {
1970 perror("cannot build socket map");
1973 aggr_get_id
= perf_stat__get_socket_cached
;
1976 if (cpu_map__build_core_map(evsel_list
->cpus
, &aggr_map
)) {
1977 perror("cannot build core map");
1980 aggr_get_id
= perf_stat__get_core_cached
;
1991 * The evsel_list->cpus is the base we operate on,
1992 * taking the highest cpu number to be the size of
1993 * the aggregation translate cpumap.
1995 nr
= cpu_map__get_max(evsel_list
->cpus
);
1996 cpus_aggr_map
= cpu_map__empty_new(nr
+ 1);
1997 return cpus_aggr_map
? 0 : -ENOMEM
;
2000 static void perf_stat__exit_aggr_mode(void)
2002 cpu_map__put(aggr_map
);
2003 cpu_map__put(cpus_aggr_map
);
2005 cpus_aggr_map
= NULL
;
2008 static inline int perf_env__get_cpu(struct perf_env
*env
, struct cpu_map
*map
, int idx
)
2015 cpu
= map
->map
[idx
];
2017 if (cpu
>= env
->nr_cpus_avail
)
2023 static int perf_env__get_socket(struct cpu_map
*map
, int idx
, void *data
)
2025 struct perf_env
*env
= data
;
2026 int cpu
= perf_env__get_cpu(env
, map
, idx
);
2028 return cpu
== -1 ? -1 : env
->cpu
[cpu
].socket_id
;
2031 static int perf_env__get_core(struct cpu_map
*map
, int idx
, void *data
)
2033 struct perf_env
*env
= data
;
2034 int core
= -1, cpu
= perf_env__get_cpu(env
, map
, idx
);
2037 int socket_id
= env
->cpu
[cpu
].socket_id
;
2040 * Encode socket in upper 16 bits
2041 * core_id is relative to socket, and
2042 * we need a global id. So we combine
2045 core
= (socket_id
<< 16) | (env
->cpu
[cpu
].core_id
& 0xffff);
2051 static int perf_env__build_socket_map(struct perf_env
*env
, struct cpu_map
*cpus
,
2052 struct cpu_map
**sockp
)
2054 return cpu_map__build_map(cpus
, sockp
, perf_env__get_socket
, env
);
2057 static int perf_env__build_core_map(struct perf_env
*env
, struct cpu_map
*cpus
,
2058 struct cpu_map
**corep
)
2060 return cpu_map__build_map(cpus
, corep
, perf_env__get_core
, env
);
2063 static int perf_stat__get_socket_file(struct cpu_map
*map
, int idx
)
2065 return perf_env__get_socket(map
, idx
, &perf_stat
.session
->header
.env
);
2068 static int perf_stat__get_core_file(struct cpu_map
*map
, int idx
)
2070 return perf_env__get_core(map
, idx
, &perf_stat
.session
->header
.env
);
2073 static int perf_stat_init_aggr_mode_file(struct perf_stat
*st
)
2075 struct perf_env
*env
= &st
->session
->header
.env
;
2077 switch (stat_config
.aggr_mode
) {
2079 if (perf_env__build_socket_map(env
, evsel_list
->cpus
, &aggr_map
)) {
2080 perror("cannot build socket map");
2083 aggr_get_id
= perf_stat__get_socket_file
;
2086 if (perf_env__build_core_map(env
, evsel_list
->cpus
, &aggr_map
)) {
2087 perror("cannot build core map");
2090 aggr_get_id
= perf_stat__get_core_file
;
2103 static int topdown_filter_events(const char **attr
, char **str
, bool use_group
)
2110 for (i
= 0; attr
[i
]; i
++) {
2111 if (pmu_have_event("cpu", attr
[i
])) {
2112 len
+= strlen(attr
[i
]) + 1;
2113 attr
[i
- off
] = attr
[i
];
2117 attr
[i
- off
] = NULL
;
2119 *str
= malloc(len
+ 1 + 2);
2129 for (i
= 0; attr
[i
]; i
++) {
2142 __weak
bool arch_topdown_check_group(bool *warn
)
2148 __weak
void arch_topdown_group_warn(void)
2153 * Add default attributes, if there were no attributes specified or
2154 * if -d/--detailed, -d -d or -d -d -d is used:
2156 static int add_default_attributes(void)
2159 struct perf_event_attr default_attrs0
[] = {
2161 { .type
= PERF_TYPE_SOFTWARE
, .config
= PERF_COUNT_SW_TASK_CLOCK
},
2162 { .type
= PERF_TYPE_SOFTWARE
, .config
= PERF_COUNT_SW_CONTEXT_SWITCHES
},
2163 { .type
= PERF_TYPE_SOFTWARE
, .config
= PERF_COUNT_SW_CPU_MIGRATIONS
},
2164 { .type
= PERF_TYPE_SOFTWARE
, .config
= PERF_COUNT_SW_PAGE_FAULTS
},
2166 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_CPU_CYCLES
},
2168 struct perf_event_attr frontend_attrs
[] = {
2169 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_STALLED_CYCLES_FRONTEND
},
2171 struct perf_event_attr backend_attrs
[] = {
2172 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_STALLED_CYCLES_BACKEND
},
2174 struct perf_event_attr default_attrs1
[] = {
2175 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_INSTRUCTIONS
},
2176 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_BRANCH_INSTRUCTIONS
},
2177 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_BRANCH_MISSES
},
2182 * Detailed stats (-d), covering the L1 and last level data caches:
2184 struct perf_event_attr detailed_attrs
[] = {
2186 { .type
= PERF_TYPE_HW_CACHE
,
2188 PERF_COUNT_HW_CACHE_L1D
<< 0 |
2189 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2190 (PERF_COUNT_HW_CACHE_RESULT_ACCESS
<< 16) },
2192 { .type
= PERF_TYPE_HW_CACHE
,
2194 PERF_COUNT_HW_CACHE_L1D
<< 0 |
2195 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2196 (PERF_COUNT_HW_CACHE_RESULT_MISS
<< 16) },
2198 { .type
= PERF_TYPE_HW_CACHE
,
2200 PERF_COUNT_HW_CACHE_LL
<< 0 |
2201 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2202 (PERF_COUNT_HW_CACHE_RESULT_ACCESS
<< 16) },
2204 { .type
= PERF_TYPE_HW_CACHE
,
2206 PERF_COUNT_HW_CACHE_LL
<< 0 |
2207 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2208 (PERF_COUNT_HW_CACHE_RESULT_MISS
<< 16) },
2212 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2214 struct perf_event_attr very_detailed_attrs
[] = {
2216 { .type
= PERF_TYPE_HW_CACHE
,
2218 PERF_COUNT_HW_CACHE_L1I
<< 0 |
2219 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2220 (PERF_COUNT_HW_CACHE_RESULT_ACCESS
<< 16) },
2222 { .type
= PERF_TYPE_HW_CACHE
,
2224 PERF_COUNT_HW_CACHE_L1I
<< 0 |
2225 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2226 (PERF_COUNT_HW_CACHE_RESULT_MISS
<< 16) },
2228 { .type
= PERF_TYPE_HW_CACHE
,
2230 PERF_COUNT_HW_CACHE_DTLB
<< 0 |
2231 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2232 (PERF_COUNT_HW_CACHE_RESULT_ACCESS
<< 16) },
2234 { .type
= PERF_TYPE_HW_CACHE
,
2236 PERF_COUNT_HW_CACHE_DTLB
<< 0 |
2237 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2238 (PERF_COUNT_HW_CACHE_RESULT_MISS
<< 16) },
2240 { .type
= PERF_TYPE_HW_CACHE
,
2242 PERF_COUNT_HW_CACHE_ITLB
<< 0 |
2243 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2244 (PERF_COUNT_HW_CACHE_RESULT_ACCESS
<< 16) },
2246 { .type
= PERF_TYPE_HW_CACHE
,
2248 PERF_COUNT_HW_CACHE_ITLB
<< 0 |
2249 (PERF_COUNT_HW_CACHE_OP_READ
<< 8) |
2250 (PERF_COUNT_HW_CACHE_RESULT_MISS
<< 16) },
2255 * Very, very detailed stats (-d -d -d), adding prefetch events:
2257 struct perf_event_attr very_very_detailed_attrs
[] = {
2259 { .type
= PERF_TYPE_HW_CACHE
,
2261 PERF_COUNT_HW_CACHE_L1D
<< 0 |
2262 (PERF_COUNT_HW_CACHE_OP_PREFETCH
<< 8) |
2263 (PERF_COUNT_HW_CACHE_RESULT_ACCESS
<< 16) },
2265 { .type
= PERF_TYPE_HW_CACHE
,
2267 PERF_COUNT_HW_CACHE_L1D
<< 0 |
2268 (PERF_COUNT_HW_CACHE_OP_PREFETCH
<< 8) |
2269 (PERF_COUNT_HW_CACHE_RESULT_MISS
<< 16) },
2272 /* Set attrs if no event is selected and !null_run: */
2276 if (transaction_run
) {
2277 if (pmu_have_event("cpu", "cycles-ct") &&
2278 pmu_have_event("cpu", "el-start"))
2279 err
= parse_events(evsel_list
, transaction_attrs
, NULL
);
2281 err
= parse_events(evsel_list
, transaction_limited_attrs
, NULL
);
2283 fprintf(stderr
, "Cannot set up transaction events\n");
2292 if (sysfs__read_int(FREEZE_ON_SMI_PATH
, &smi
) < 0) {
2293 fprintf(stderr
, "freeze_on_smi is not supported.\n");
2298 if (sysfs__write_int(FREEZE_ON_SMI_PATH
, 1) < 0) {
2299 fprintf(stderr
, "Failed to set freeze_on_smi.\n");
2305 if (pmu_have_event("msr", "aperf") &&
2306 pmu_have_event("msr", "smi")) {
2307 if (!force_metric_only
)
2309 err
= parse_events(evsel_list
, smi_cost_attrs
, NULL
);
2311 fprintf(stderr
, "To measure SMI cost, it needs "
2312 "msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
2316 fprintf(stderr
, "Cannot set up SMI cost events\n");
2326 if (stat_config
.aggr_mode
!= AGGR_GLOBAL
&&
2327 stat_config
.aggr_mode
!= AGGR_CORE
) {
2328 pr_err("top down event configuration requires --per-core mode\n");
2331 stat_config
.aggr_mode
= AGGR_CORE
;
2332 if (nr_cgroups
|| !target__has_cpu(&target
)) {
2333 pr_err("top down event configuration requires system-wide mode (-a)\n");
2337 if (!force_metric_only
)
2339 if (topdown_filter_events(topdown_attrs
, &str
,
2340 arch_topdown_check_group(&warn
)) < 0) {
2341 pr_err("Out of memory\n");
2344 if (topdown_attrs
[0] && str
) {
2346 arch_topdown_group_warn();
2347 err
= parse_events(evsel_list
, str
, NULL
);
2350 "Cannot set up top down events %s: %d\n",
2356 fprintf(stderr
, "System does not support topdown\n");
2362 if (!evsel_list
->nr_entries
) {
2363 if (target__has_cpu(&target
))
2364 default_attrs0
[0].config
= PERF_COUNT_SW_CPU_CLOCK
;
2366 if (perf_evlist__add_default_attrs(evsel_list
, default_attrs0
) < 0)
2368 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2369 if (perf_evlist__add_default_attrs(evsel_list
,
2370 frontend_attrs
) < 0)
2373 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2374 if (perf_evlist__add_default_attrs(evsel_list
,
2378 if (perf_evlist__add_default_attrs(evsel_list
, default_attrs1
) < 0)
2382 /* Detailed events get appended to the event list: */
2384 if (detailed_run
< 1)
2387 /* Append detailed run extra attributes: */
2388 if (perf_evlist__add_default_attrs(evsel_list
, detailed_attrs
) < 0)
2391 if (detailed_run
< 2)
2394 /* Append very detailed run extra attributes: */
2395 if (perf_evlist__add_default_attrs(evsel_list
, very_detailed_attrs
) < 0)
2398 if (detailed_run
< 3)
2401 /* Append very, very detailed run extra attributes: */
2402 return perf_evlist__add_default_attrs(evsel_list
, very_very_detailed_attrs
);
2405 static const char * const stat_record_usage
[] = {
2406 "perf stat record [<options>]",
2410 static void init_features(struct perf_session
*session
)
2414 for (feat
= HEADER_FIRST_FEATURE
; feat
< HEADER_LAST_FEATURE
; feat
++)
2415 perf_header__set_feat(&session
->header
, feat
);
2417 perf_header__clear_feat(&session
->header
, HEADER_BUILD_ID
);
2418 perf_header__clear_feat(&session
->header
, HEADER_TRACING_DATA
);
2419 perf_header__clear_feat(&session
->header
, HEADER_BRANCH_STACK
);
2420 perf_header__clear_feat(&session
->header
, HEADER_AUXTRACE
);
2423 static int __cmd_record(int argc
, const char **argv
)
2425 struct perf_session
*session
;
2426 struct perf_data
*data
= &perf_stat
.data
;
2428 argc
= parse_options(argc
, argv
, stat_options
, stat_record_usage
,
2429 PARSE_OPT_STOP_AT_NON_OPTION
);
2432 data
->file
.path
= output_name
;
2434 if (run_count
!= 1 || forever
) {
2435 pr_err("Cannot use -r option with perf stat record.\n");
2439 session
= perf_session__new(data
, false, NULL
);
2440 if (session
== NULL
) {
2441 pr_err("Perf session creation failed.\n");
2445 init_features(session
);
2447 session
->evlist
= evsel_list
;
2448 perf_stat
.session
= session
;
2449 perf_stat
.record
= true;
2453 static int process_stat_round_event(struct perf_tool
*tool __maybe_unused
,
2454 union perf_event
*event
,
2455 struct perf_session
*session
)
2457 struct stat_round_event
*stat_round
= &event
->stat_round
;
2458 struct perf_evsel
*counter
;
2459 struct timespec tsh
, *ts
= NULL
;
2460 const char **argv
= session
->header
.env
.cmdline_argv
;
2461 int argc
= session
->header
.env
.nr_cmdline
;
2463 evlist__for_each_entry(evsel_list
, counter
)
2464 perf_stat_process_counter(&stat_config
, counter
);
2466 if (stat_round
->type
== PERF_STAT_ROUND_TYPE__FINAL
)
2467 update_stats(&walltime_nsecs_stats
, stat_round
->time
);
2469 if (stat_config
.interval
&& stat_round
->time
) {
2470 tsh
.tv_sec
= stat_round
->time
/ NSEC_PER_SEC
;
2471 tsh
.tv_nsec
= stat_round
->time
% NSEC_PER_SEC
;
2475 print_counters(ts
, argc
, argv
);
2480 int process_stat_config_event(struct perf_tool
*tool
,
2481 union perf_event
*event
,
2482 struct perf_session
*session __maybe_unused
)
2484 struct perf_stat
*st
= container_of(tool
, struct perf_stat
, tool
);
2486 perf_event__read_stat_config(&stat_config
, &event
->stat_config
);
2488 if (cpu_map__empty(st
->cpus
)) {
2489 if (st
->aggr_mode
!= AGGR_UNSET
)
2490 pr_warning("warning: processing task data, aggregation mode not set\n");
2494 if (st
->aggr_mode
!= AGGR_UNSET
)
2495 stat_config
.aggr_mode
= st
->aggr_mode
;
2497 if (perf_stat
.data
.is_pipe
)
2498 perf_stat_init_aggr_mode();
2500 perf_stat_init_aggr_mode_file(st
);
2505 static int set_maps(struct perf_stat
*st
)
2507 if (!st
->cpus
|| !st
->threads
)
2510 if (WARN_ONCE(st
->maps_allocated
, "stats double allocation\n"))
2513 perf_evlist__set_maps(evsel_list
, st
->cpus
, st
->threads
);
2515 if (perf_evlist__alloc_stats(evsel_list
, true))
2518 st
->maps_allocated
= true;
2523 int process_thread_map_event(struct perf_tool
*tool
,
2524 union perf_event
*event
,
2525 struct perf_session
*session __maybe_unused
)
2527 struct perf_stat
*st
= container_of(tool
, struct perf_stat
, tool
);
2530 pr_warning("Extra thread map event, ignoring.\n");
2534 st
->threads
= thread_map__new_event(&event
->thread_map
);
2538 return set_maps(st
);
2542 int process_cpu_map_event(struct perf_tool
*tool
,
2543 union perf_event
*event
,
2544 struct perf_session
*session __maybe_unused
)
2546 struct perf_stat
*st
= container_of(tool
, struct perf_stat
, tool
);
2547 struct cpu_map
*cpus
;
2550 pr_warning("Extra cpu map event, ignoring.\n");
2554 cpus
= cpu_map__new_data(&event
->cpu_map
.data
);
2559 return set_maps(st
);
2562 static int runtime_stat_new(struct perf_stat_config
*config
, int nthreads
)
2566 config
->stats
= calloc(nthreads
, sizeof(struct runtime_stat
));
2570 config
->stats_num
= nthreads
;
2572 for (i
= 0; i
< nthreads
; i
++)
2573 runtime_stat__init(&config
->stats
[i
]);
2578 static void runtime_stat_delete(struct perf_stat_config
*config
)
2585 for (i
= 0; i
< config
->stats_num
; i
++)
2586 runtime_stat__exit(&config
->stats
[i
]);
2588 free(config
->stats
);
2591 static const char * const stat_report_usage
[] = {
2592 "perf stat report [<options>]",
2596 static struct perf_stat perf_stat
= {
2598 .attr
= perf_event__process_attr
,
2599 .event_update
= perf_event__process_event_update
,
2600 .thread_map
= process_thread_map_event
,
2601 .cpu_map
= process_cpu_map_event
,
2602 .stat_config
= process_stat_config_event
,
2603 .stat
= perf_event__process_stat_event
,
2604 .stat_round
= process_stat_round_event
,
2606 .aggr_mode
= AGGR_UNSET
,
2609 static int __cmd_report(int argc
, const char **argv
)
2611 struct perf_session
*session
;
2612 const struct option options
[] = {
2613 OPT_STRING('i', "input", &input_name
, "file", "input file name"),
2614 OPT_SET_UINT(0, "per-socket", &perf_stat
.aggr_mode
,
2615 "aggregate counts per processor socket", AGGR_SOCKET
),
2616 OPT_SET_UINT(0, "per-core", &perf_stat
.aggr_mode
,
2617 "aggregate counts per physical processor core", AGGR_CORE
),
2618 OPT_SET_UINT('A', "no-aggr", &perf_stat
.aggr_mode
,
2619 "disable CPU count aggregation", AGGR_NONE
),
2625 argc
= parse_options(argc
, argv
, options
, stat_report_usage
, 0);
2627 if (!input_name
|| !strlen(input_name
)) {
2628 if (!fstat(STDIN_FILENO
, &st
) && S_ISFIFO(st
.st_mode
))
2631 input_name
= "perf.data";
2634 perf_stat
.data
.file
.path
= input_name
;
2635 perf_stat
.data
.mode
= PERF_DATA_MODE_READ
;
2637 session
= perf_session__new(&perf_stat
.data
, false, &perf_stat
.tool
);
2638 if (session
== NULL
)
2641 perf_stat
.session
= session
;
2642 stat_config
.output
= stderr
;
2643 evsel_list
= session
->evlist
;
2645 ret
= perf_session__process_events(session
);
2649 perf_session__delete(session
);
2653 static void setup_system_wide(int forks
)
2656 * Make system wide (-a) the default target if
2657 * no target was specified and one of following
2658 * conditions is met:
2660 * - there's no workload specified
2661 * - there is workload specified but all requested
2662 * events are system wide events
2664 if (!target__none(&target
))
2668 target
.system_wide
= true;
2670 struct perf_evsel
*counter
;
2672 evlist__for_each_entry(evsel_list
, counter
) {
2673 if (!counter
->system_wide
)
2677 if (evsel_list
->nr_entries
)
2678 target
.system_wide
= true;
2682 int cmd_stat(int argc
, const char **argv
)
2684 const char * const stat_usage
[] = {
2685 "perf stat [<options>] [<command>]",
2688 int status
= -EINVAL
, run_idx
;
2690 FILE *output
= stderr
;
2691 unsigned int interval
;
2692 const char * const stat_subcommands
[] = { "record", "report" };
2694 setlocale(LC_ALL
, "");
2696 evsel_list
= perf_evlist__new();
2697 if (evsel_list
== NULL
)
2700 parse_events__shrink_config_terms();
2701 argc
= parse_options_subcommand(argc
, argv
, stat_options
, stat_subcommands
,
2702 (const char **) stat_usage
,
2703 PARSE_OPT_STOP_AT_NON_OPTION
);
2704 perf_stat__collect_metric_expr(evsel_list
);
2705 perf_stat__init_shadow_stats();
2709 if (!strcmp(csv_sep
, "\\t"))
2712 csv_sep
= DEFAULT_SEPARATOR
;
2714 if (argc
&& !strncmp(argv
[0], "rec", 3)) {
2715 argc
= __cmd_record(argc
, argv
);
2718 } else if (argc
&& !strncmp(argv
[0], "rep", 3))
2719 return __cmd_report(argc
, argv
);
2721 interval
= stat_config
.interval
;
2724 * For record command the -o is already taken care of.
2726 if (!STAT_RECORD
&& output_name
&& strcmp(output_name
, "-"))
2729 if (output_name
&& output_fd
) {
2730 fprintf(stderr
, "cannot use both --output and --log-fd\n");
2731 parse_options_usage(stat_usage
, stat_options
, "o", 1);
2732 parse_options_usage(NULL
, stat_options
, "log-fd", 0);
2736 if (metric_only
&& stat_config
.aggr_mode
== AGGR_THREAD
) {
2737 fprintf(stderr
, "--metric-only is not supported with --per-thread\n");
2741 if (metric_only
&& run_count
> 1) {
2742 fprintf(stderr
, "--metric-only is not supported with -r\n");
2746 if (output_fd
< 0) {
2747 fprintf(stderr
, "argument to --log-fd must be a > 0\n");
2748 parse_options_usage(stat_usage
, stat_options
, "log-fd", 0);
2754 mode
= append_file
? "a" : "w";
2756 output
= fopen(output_name
, mode
);
2758 perror("failed to create output file");
2761 clock_gettime(CLOCK_REALTIME
, &tm
);
2762 fprintf(output
, "# started on %s\n", ctime(&tm
.tv_sec
));
2763 } else if (output_fd
> 0) {
2764 mode
= append_file
? "a" : "w";
2765 output
= fdopen(output_fd
, mode
);
2767 perror("Failed opening logfd");
2772 stat_config
.output
= output
;
2775 * let the spreadsheet do the pretty-printing
2778 /* User explicitly passed -B? */
2779 if (big_num_opt
== 1) {
2780 fprintf(stderr
, "-B option not supported with -x\n");
2781 parse_options_usage(stat_usage
, stat_options
, "B", 1);
2782 parse_options_usage(NULL
, stat_options
, "x", 1);
2784 } else /* Nope, so disable big number formatting */
2786 } else if (big_num_opt
== 0) /* User passed --no-big-num */
2789 setup_system_wide(argc
);
2791 if (run_count
< 0) {
2792 pr_err("Run count must be a positive number\n");
2793 parse_options_usage(stat_usage
, stat_options
, "r", 1);
2795 } else if (run_count
== 0) {
2800 if ((stat_config
.aggr_mode
== AGGR_THREAD
) &&
2801 !target__has_task(&target
)) {
2802 if (!target
.system_wide
|| target
.cpu_list
) {
2803 fprintf(stderr
, "The --per-thread option is only "
2804 "available when monitoring via -p -t -a "
2805 "options or only --per-thread.\n");
2806 parse_options_usage(NULL
, stat_options
, "p", 1);
2807 parse_options_usage(NULL
, stat_options
, "t", 1);
2813 * no_aggr, cgroup are for system-wide only
2814 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2816 if (((stat_config
.aggr_mode
!= AGGR_GLOBAL
&&
2817 stat_config
.aggr_mode
!= AGGR_THREAD
) || nr_cgroups
) &&
2818 !target__has_cpu(&target
)) {
2819 fprintf(stderr
, "both cgroup and no-aggregation "
2820 "modes only available in system-wide mode\n");
2822 parse_options_usage(stat_usage
, stat_options
, "G", 1);
2823 parse_options_usage(NULL
, stat_options
, "A", 1);
2824 parse_options_usage(NULL
, stat_options
, "a", 1);
2828 if (add_default_attributes())
2831 target__validate(&target
);
2833 if ((stat_config
.aggr_mode
== AGGR_THREAD
) && (target
.system_wide
))
2834 target
.per_thread
= true;
2836 if (perf_evlist__create_maps(evsel_list
, &target
) < 0) {
2837 if (target__has_task(&target
)) {
2838 pr_err("Problems finding threads of monitor\n");
2839 parse_options_usage(stat_usage
, stat_options
, "p", 1);
2840 parse_options_usage(NULL
, stat_options
, "t", 1);
2841 } else if (target__has_cpu(&target
)) {
2842 perror("failed to parse CPUs map");
2843 parse_options_usage(stat_usage
, stat_options
, "C", 1);
2844 parse_options_usage(NULL
, stat_options
, "a", 1);
2850 * Initialize thread_map with comm names,
2851 * so we could print it out on output.
2853 if (stat_config
.aggr_mode
== AGGR_THREAD
) {
2854 thread_map__read_comms(evsel_list
->threads
);
2855 if (target
.system_wide
) {
2856 if (runtime_stat_new(&stat_config
,
2857 thread_map__nr(evsel_list
->threads
))) {
2863 if (interval
&& interval
< 100) {
2864 if (interval
< 10) {
2865 pr_err("print interval must be >= 10ms\n");
2866 parse_options_usage(stat_usage
, stat_options
, "I", 1);
2869 pr_warning("print interval < 100ms. "
2870 "The overhead percentage could be high in some cases. "
2871 "Please proceed with caution.\n");
2874 if (perf_evlist__alloc_stats(evsel_list
, interval
))
2877 if (perf_stat_init_aggr_mode())
2881 * We dont want to block the signals - that would cause
2882 * child tasks to inherit that and Ctrl-C would not work.
2883 * What we want is for Ctrl-C to work in the exec()-ed
2884 * task, but being ignored by perf stat itself:
2888 signal(SIGINT
, skip_signal
);
2889 signal(SIGCHLD
, skip_signal
);
2890 signal(SIGALRM
, skip_signal
);
2891 signal(SIGABRT
, skip_signal
);
2894 for (run_idx
= 0; forever
|| run_idx
< run_count
; run_idx
++) {
2895 if (run_count
!= 1 && verbose
> 0)
2896 fprintf(output
, "[ perf stat: executing run #%d ... ]\n",
2899 status
= run_perf_stat(argc
, argv
);
2900 if (forever
&& status
!= -1) {
2901 print_counters(NULL
, argc
, argv
);
2902 perf_stat__reset_stats();
2906 if (!forever
&& status
!= -1 && !interval
)
2907 print_counters(NULL
, argc
, argv
);
2911 * We synthesize the kernel mmap record just so that older tools
2912 * don't emit warnings about not being able to resolve symbols
2913 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2914 * a saner message about no samples being in the perf.data file.
2916 * This also serves to suppress a warning about f_header.data.size == 0
2917 * in header.c at the moment 'perf stat record' gets introduced, which
2918 * is not really needed once we start adding the stat specific PERF_RECORD_
2919 * records, but the need to suppress the kptr_restrict messages in older
2920 * tools remain -acme
2922 int fd
= perf_data__fd(&perf_stat
.data
);
2923 int err
= perf_event__synthesize_kernel_mmap((void *)&perf_stat
,
2924 process_synthesized_event
,
2925 &perf_stat
.session
->machines
.host
);
2927 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2928 "older tools may produce warnings about this file\n.");
2932 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats
.max
, FINAL
))
2933 pr_err("failed to write stat round event\n");
2936 if (!perf_stat
.data
.is_pipe
) {
2937 perf_stat
.session
->header
.data_size
+= perf_stat
.bytes_written
;
2938 perf_session__write_header(perf_stat
.session
, evsel_list
, fd
, true);
2941 perf_session__delete(perf_stat
.session
);
2944 perf_stat__exit_aggr_mode();
2945 perf_evlist__free_stats(evsel_list
);
2947 if (smi_cost
&& smi_reset
)
2948 sysfs__write_int(FREEZE_ON_SMI_PATH
, 0);
2950 perf_evlist__delete(evsel_list
);
2952 runtime_stat_delete(&stat_config
);