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"
71 #include <linux/time64.h>
72 #include <api/fs/fs.h>
76 #include <sys/prctl.h>
80 #include <sys/types.h>
85 #include <sys/resource.h>
88 #include "sane_ctype.h"
90 #define DEFAULT_SEPARATOR " "
91 #define CNTR_NOT_SUPPORTED "<not supported>"
92 #define CNTR_NOT_COUNTED "<not counted>"
93 #define FREEZE_ON_SMI_PATH "devices/cpu/freeze_on_smi"
95 static void print_counters(struct timespec *ts, int argc, const char **argv);
97 /* Default events used for perf stat -T */
98 static const char *transaction_attrs = {
110 /* More limited version when the CPU does not have all events. */
111 static const char * transaction_limited_attrs = {
121 static const char * topdown_attrs[] = {
122 "topdown-total-slots",
123 "topdown-slots-retired",
124 "topdown-recovery-bubbles",
125 "topdown-fetch-bubbles",
126 "topdown-slots-issued",
130 static const char *smi_cost_attrs = {
138 static struct perf_evlist *evsel_list;
140 static struct rblist metric_events;
142 static struct target target = {
146 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
148 #define METRIC_ONLY_LEN 20
150 static int run_count = 1;
151 static volatile pid_t child_pid = -1;
152 static bool null_run = false;
153 static int detailed_run = 0;
154 static bool transaction_run;
155 static bool topdown_run = false;
156 static bool smi_cost = false;
157 static bool smi_reset = false;
158 static bool big_num = true;
159 static int big_num_opt = -1;
160 static bool group = false;
161 static const char *pre_cmd = NULL;
162 static const char *post_cmd = NULL;
163 static bool sync_run = false;
164 static bool forever = false;
165 static bool force_metric_only = false;
166 static bool no_merge = false;
167 static bool walltime_run_table = false;
168 static struct timespec ref_time;
169 static struct cpu_map *aggr_map;
170 static aggr_get_id_t aggr_get_id;
171 static bool append_file;
172 static bool interval_count;
173 static const char *output_name;
174 static int output_fd;
175 static int print_free_counters_hint;
176 static int print_mixed_hw_group_error;
177 static u64 *walltime_run;
178 static bool ru_display = false;
179 static struct rusage ru_data;
180 static unsigned int metric_only_len = METRIC_ONLY_LEN;
184 struct perf_data data;
185 struct perf_session *session;
187 struct perf_tool tool;
189 struct cpu_map *cpus;
190 struct thread_map *threads;
191 enum aggr_mode aggr_mode;
194 static struct perf_stat perf_stat;
195 #define STAT_RECORD perf_stat.record
197 static volatile int done = 0;
199 static struct perf_stat_config stat_config = {
200 .aggr_mode = AGGR_GLOBAL,
202 .unit_width = 4, /* strlen("unit") */
205 static bool is_duration_time(struct perf_evsel *evsel)
207 return !strcmp(evsel->name, "duration_time");
210 static inline void diff_timespec(struct timespec *r, struct timespec *a,
213 r->tv_sec = a->tv_sec - b->tv_sec;
214 if (a->tv_nsec < b->tv_nsec) {
215 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
218 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
222 static void perf_stat__reset_stats(void)
226 perf_evlist__reset_stats(evsel_list);
227 perf_stat__reset_shadow_stats();
229 for (i = 0; i < stat_config.stats_num; i++)
230 perf_stat__reset_shadow_per_stat(&stat_config.stats[i]);
233 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
234 union perf_event *event,
235 struct perf_sample *sample __maybe_unused,
236 struct machine *machine __maybe_unused)
238 if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
239 pr_err("failed to write perf data, error: %m\n");
243 perf_stat.bytes_written += event->header.size;
247 static int write_stat_round_event(u64 tm, u64 type)
249 return perf_event__synthesize_stat_round(NULL, tm, type,
250 process_synthesized_event,
254 #define WRITE_STAT_ROUND_EVENT(time, interval) \
255 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
257 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
260 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
261 struct perf_counts_values *count)
263 struct perf_sample_id *sid = SID(counter, cpu, thread);
265 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
266 process_synthesized_event, NULL);
270 * Read out the results of a single counter:
271 * do not aggregate counts across CPUs in system-wide mode
273 static int read_counter(struct perf_evsel *counter)
275 int nthreads = thread_map__nr(evsel_list->threads);
276 int ncpus, cpu, thread;
278 if (target__has_cpu(&target) && !target__has_per_thread(&target))
279 ncpus = perf_evsel__nr_cpus(counter);
283 if (!counter->supported)
286 if (counter->system_wide)
289 for (thread = 0; thread < nthreads; thread++) {
290 for (cpu = 0; cpu < ncpus; cpu++) {
291 struct perf_counts_values *count;
293 count = perf_counts(counter->counts, cpu, thread);
296 * The leader's group read loads data into its group members
297 * (via perf_evsel__read_counter) and sets threir count->loaded.
299 if (!count->loaded &&
300 perf_evsel__read_counter(counter, cpu, thread)) {
301 counter->counts->scaled = -1;
302 perf_counts(counter->counts, cpu, thread)->ena = 0;
303 perf_counts(counter->counts, cpu, thread)->run = 0;
307 count->loaded = false;
310 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
311 pr_err("failed to write stat event\n");
317 fprintf(stat_config.output,
318 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
319 perf_evsel__name(counter),
321 count->val, count->ena, count->run);
329 static void read_counters(void)
331 struct perf_evsel *counter;
334 evlist__for_each_entry(evsel_list, counter) {
335 ret = read_counter(counter);
337 pr_debug("failed to read counter %s\n", counter->name);
339 if (ret == 0 && perf_stat_process_counter(&stat_config, counter))
340 pr_warning("failed to process counter %s\n", counter->name);
344 static void process_interval(void)
346 struct timespec ts, rs;
350 clock_gettime(CLOCK_MONOTONIC, &ts);
351 diff_timespec(&rs, &ts, &ref_time);
354 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
355 pr_err("failed to write stat round event\n");
358 init_stats(&walltime_nsecs_stats);
359 update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000);
360 print_counters(&rs, 0, NULL);
363 static void enable_counters(void)
365 if (stat_config.initial_delay)
366 usleep(stat_config.initial_delay * USEC_PER_MSEC);
369 * We need to enable counters only if:
370 * - we don't have tracee (attaching to task or cpu)
371 * - we have initial delay configured
373 if (!target__none(&target) || stat_config.initial_delay)
374 perf_evlist__enable(evsel_list);
377 static void disable_counters(void)
380 * If we don't have tracee (attaching to task or cpu), counters may
381 * still be running. To get accurate group ratios, we must stop groups
382 * from counting before reading their constituent counters.
384 if (!target__none(&target))
385 perf_evlist__disable(evsel_list);
388 static volatile int workload_exec_errno;
391 * perf_evlist__prepare_workload will send a SIGUSR1
392 * if the fork fails, since we asked by setting its
393 * want_signal to true.
395 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
396 void *ucontext __maybe_unused)
398 workload_exec_errno = info->si_value.sival_int;
401 static bool perf_evsel__should_store_id(struct perf_evsel *counter)
403 return STAT_RECORD || counter->attr.read_format & PERF_FORMAT_ID;
406 static struct perf_evsel *perf_evsel__reset_weak_group(struct perf_evsel *evsel)
408 struct perf_evsel *c2, *leader;
411 leader = evsel->leader;
412 pr_debug("Weak group for %s/%d failed\n",
413 leader->name, leader->nr_members);
416 * for_each_group_member doesn't work here because it doesn't
417 * include the first entry.
419 evlist__for_each_entry(evsel_list, c2) {
422 if (c2->leader == leader) {
424 perf_evsel__close(c2);
432 static int __run_perf_stat(int argc, const char **argv, int run_idx)
434 int interval = stat_config.interval;
435 int times = stat_config.times;
436 int timeout = stat_config.timeout;
438 unsigned long long t0, t1;
439 struct perf_evsel *counter;
443 const bool forks = (argc > 0);
444 bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
445 struct perf_evsel_config_term *err_term;
448 ts.tv_sec = interval / USEC_PER_MSEC;
449 ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
450 } else if (timeout) {
451 ts.tv_sec = timeout / USEC_PER_MSEC;
452 ts.tv_nsec = (timeout % USEC_PER_MSEC) * NSEC_PER_MSEC;
459 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
460 workload_exec_failed_signal) < 0) {
461 perror("failed to prepare workload");
464 child_pid = evsel_list->workload.pid;
468 perf_evlist__set_leader(evsel_list);
470 evlist__for_each_entry(evsel_list, counter) {
472 if (create_perf_stat_counter(counter, &stat_config, &target) < 0) {
474 /* Weak group failed. Reset the group. */
475 if ((errno == EINVAL || errno == EBADF) &&
476 counter->leader != counter &&
477 counter->weak_group) {
478 counter = perf_evsel__reset_weak_group(counter);
483 * PPC returns ENXIO for HW counters until 2.6.37
484 * (behavior changed with commit b0a873e).
486 if (errno == EINVAL || errno == ENOSYS ||
487 errno == ENOENT || errno == EOPNOTSUPP ||
490 ui__warning("%s event is not supported by the kernel.\n",
491 perf_evsel__name(counter));
492 counter->supported = false;
494 if ((counter->leader != counter) ||
495 !(counter->leader->nr_members > 1))
497 } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
499 ui__warning("%s\n", msg);
501 } else if (target__has_per_thread(&target) &&
502 evsel_list->threads &&
503 evsel_list->threads->err_thread != -1) {
505 * For global --per-thread case, skip current
508 if (!thread_map__remove(evsel_list->threads,
509 evsel_list->threads->err_thread)) {
510 evsel_list->threads->err_thread = -1;
515 perf_evsel__open_strerror(counter, &target,
516 errno, msg, sizeof(msg));
517 ui__error("%s\n", msg);
520 kill(child_pid, SIGTERM);
524 counter->supported = true;
526 l = strlen(counter->unit);
527 if (l > stat_config.unit_width)
528 stat_config.unit_width = l;
530 if (perf_evsel__should_store_id(counter) &&
531 perf_evsel__store_ids(counter, evsel_list))
535 if (perf_evlist__apply_filters(evsel_list, &counter)) {
536 pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
537 counter->filter, perf_evsel__name(counter), errno,
538 str_error_r(errno, msg, sizeof(msg)));
542 if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
543 pr_err("failed to set config \"%s\" on event %s with %d (%s)\n",
544 err_term->val.drv_cfg, perf_evsel__name(counter), errno,
545 str_error_r(errno, msg, sizeof(msg)));
550 int err, fd = perf_data__fd(&perf_stat.data);
553 err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
555 err = perf_session__write_header(perf_stat.session, evsel_list,
562 err = perf_stat_synthesize_config(&stat_config, NULL, evsel_list,
563 process_synthesized_event, is_pipe);
569 * Enable counters and exec the command:
572 clock_gettime(CLOCK_MONOTONIC, &ref_time);
575 perf_evlist__start_workload(evsel_list);
578 if (interval || timeout) {
579 while (!waitpid(child_pid, &status, WNOHANG)) {
580 nanosleep(&ts, NULL);
584 if (interval_count && !(--times))
588 wait4(child_pid, &status, 0, &ru_data);
590 if (workload_exec_errno) {
591 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
592 pr_err("Workload failed: %s\n", emsg);
596 if (WIFSIGNALED(status))
597 psignal(WTERMSIG(status), argv[0]);
601 nanosleep(&ts, NULL);
606 if (interval_count && !(--times))
616 if (walltime_run_table)
617 walltime_run[run_idx] = t1 - t0;
619 update_stats(&walltime_nsecs_stats, t1 - t0);
622 * Closing a group leader splits the group, and as we only disable
623 * group leaders, results in remaining events becoming enabled. To
624 * avoid arbitrary skew, we must read all counters before closing any
628 perf_evlist__close(evsel_list);
630 return WEXITSTATUS(status);
633 static int run_perf_stat(int argc, const char **argv, int run_idx)
638 ret = system(pre_cmd);
646 ret = __run_perf_stat(argc, argv, run_idx);
651 ret = system(post_cmd);
659 static void print_running(struct perf_stat_config *config,
662 if (config->csv_output) {
663 fprintf(config->output, "%s%" PRIu64 "%s%.2f",
667 ena ? 100.0 * run / ena : 100.0);
668 } else if (run != ena) {
669 fprintf(config->output, " (%.2f%%)", 100.0 * run / ena);
673 static void print_noise_pct(struct perf_stat_config *config,
674 double total, double avg)
676 double pct = rel_stddev_stats(total, avg);
678 if (config->csv_output)
679 fprintf(config->output, "%s%.2f%%", config->csv_sep, pct);
681 fprintf(config->output, " ( +-%6.2f%% )", pct);
684 static void print_noise(struct perf_stat_config *config,
685 struct perf_evsel *evsel, double avg)
687 struct perf_stat_evsel *ps;
693 print_noise_pct(config, stddev_stats(&ps->res_stats[0]), avg);
696 static void aggr_printout(struct perf_stat_config *config,
697 struct perf_evsel *evsel, int id, int nr)
699 switch (config->aggr_mode) {
701 fprintf(config->output, "S%d-C%*d%s%*d%s",
702 cpu_map__id_to_socket(id),
703 config->csv_output ? 0 : -8,
704 cpu_map__id_to_cpu(id),
706 config->csv_output ? 0 : 4,
711 fprintf(config->output, "S%*d%s%*d%s",
712 config->csv_output ? 0 : -5,
715 config->csv_output ? 0 : 4,
720 fprintf(config->output, "CPU%*d%s",
721 config->csv_output ? 0 : -4,
722 perf_evsel__cpus(evsel)->map[id], config->csv_sep);
725 fprintf(config->output, "%*s-%*d%s",
726 config->csv_output ? 0 : 16,
727 thread_map__comm(evsel->threads, id),
728 config->csv_output ? 0 : -8,
729 thread_map__pid(evsel->threads, id),
745 struct perf_evsel *evsel;
748 #define METRIC_LEN 35
750 static void new_line_std(struct perf_stat_config *config __maybe_unused,
753 struct outstate *os = ctx;
758 static void do_new_line_std(struct perf_stat_config *config,
762 fputs(os->prefix, os->fh);
763 aggr_printout(config, os->evsel, os->id, os->nr);
764 if (config->aggr_mode == AGGR_NONE)
765 fprintf(os->fh, " ");
766 fprintf(os->fh, " ");
769 static void print_metric_std(struct perf_stat_config *config,
770 void *ctx, const char *color, const char *fmt,
771 const char *unit, double val)
773 struct outstate *os = ctx;
776 bool newline = os->newline;
780 if (unit == NULL || fmt == NULL) {
781 fprintf(out, "%-*s", METRIC_LEN, "");
786 do_new_line_std(config, os);
788 n = fprintf(out, " # ");
790 n += color_fprintf(out, color, fmt, val);
792 n += fprintf(out, fmt, val);
793 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
796 static void new_line_csv(struct perf_stat_config *config, void *ctx)
798 struct outstate *os = ctx;
803 fprintf(os->fh, "%s%s", os->prefix, config->csv_sep);
804 aggr_printout(config, os->evsel, os->id, os->nr);
805 for (i = 0; i < os->nfields; i++)
806 fputs(config->csv_sep, os->fh);
809 static void print_metric_csv(struct perf_stat_config *config __maybe_unused,
811 const char *color __maybe_unused,
812 const char *fmt, const char *unit, double val)
814 struct outstate *os = ctx;
816 char buf[64], *vals, *ends;
818 if (unit == NULL || fmt == NULL) {
819 fprintf(out, "%s%s", config->csv_sep, config->csv_sep);
822 snprintf(buf, sizeof(buf), fmt, val);
823 ends = vals = ltrim(buf);
824 while (isdigit(*ends) || *ends == '.')
827 while (isspace(*unit))
829 fprintf(out, "%s%s%s%s", config->csv_sep, vals, config->csv_sep, unit);
832 /* Filter out some columns that don't work well in metrics only mode */
834 static bool valid_only_metric(const char *unit)
838 if (strstr(unit, "/sec") ||
839 strstr(unit, "hz") ||
840 strstr(unit, "Hz") ||
841 strstr(unit, "CPUs utilized"))
846 static const char *fixunit(char *buf, struct perf_evsel *evsel,
849 if (!strncmp(unit, "of all", 6)) {
850 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
857 static void print_metric_only(struct perf_stat_config *config __maybe_unused,
858 void *ctx, const char *color, const char *fmt,
859 const char *unit, double val)
861 struct outstate *os = ctx;
863 char buf[1024], str[1024];
864 unsigned mlen = metric_only_len;
866 if (!valid_only_metric(unit))
868 unit = fixunit(buf, os->evsel, unit);
869 if (mlen < strlen(unit))
870 mlen = strlen(unit) + 1;
873 mlen += strlen(color) + sizeof(PERF_COLOR_RESET) - 1;
875 color_snprintf(str, sizeof(str), color ?: "", fmt, val);
876 fprintf(out, "%*s ", mlen, str);
879 static void print_metric_only_csv(struct perf_stat_config *config __maybe_unused,
880 void *ctx, const char *color __maybe_unused,
882 const char *unit, double val)
884 struct outstate *os = ctx;
886 char buf[64], *vals, *ends;
889 if (!valid_only_metric(unit))
891 unit = fixunit(tbuf, os->evsel, unit);
892 snprintf(buf, sizeof buf, fmt, val);
893 ends = vals = ltrim(buf);
894 while (isdigit(*ends) || *ends == '.')
897 fprintf(out, "%s%s", vals, config->csv_sep);
900 static void new_line_metric(struct perf_stat_config *config __maybe_unused,
901 void *ctx __maybe_unused)
905 static void print_metric_header(struct perf_stat_config *config __maybe_unused,
906 void *ctx, const char *color __maybe_unused,
907 const char *fmt __maybe_unused,
908 const char *unit, double val __maybe_unused)
910 struct outstate *os = ctx;
913 if (!valid_only_metric(unit))
915 unit = fixunit(tbuf, os->evsel, unit);
916 if (config->csv_output)
917 fprintf(os->fh, "%s%s", unit, config->csv_sep);
919 fprintf(os->fh, "%*s ", metric_only_len, unit);
922 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
929 if (stat_config.aggr_mode == AGGR_NONE)
932 if (stat_config.aggr_mode == AGGR_GLOBAL)
935 for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
936 int cpu2 = perf_evsel__cpus(evsel)->map[i];
938 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
944 static void abs_printout(struct perf_stat_config *config,
945 int id, int nr, struct perf_evsel *evsel, double avg)
947 FILE *output = config->output;
948 double sc = evsel->scale;
951 if (config->csv_output) {
952 fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
955 fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
957 fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
960 aggr_printout(config, evsel, id, nr);
962 fprintf(output, fmt, avg, config->csv_sep);
965 fprintf(output, "%-*s%s",
966 config->csv_output ? 0 : config->unit_width,
967 evsel->unit, config->csv_sep);
969 fprintf(output, "%-*s", config->csv_output ? 0 : 25, perf_evsel__name(evsel));
972 fprintf(output, "%s%s", config->csv_sep, evsel->cgrp->name);
975 static bool is_mixed_hw_group(struct perf_evsel *counter)
977 struct perf_evlist *evlist = counter->evlist;
978 u32 pmu_type = counter->attr.type;
979 struct perf_evsel *pos;
981 if (counter->nr_members < 2)
984 evlist__for_each_entry(evlist, pos) {
985 /* software events can be part of any hardware group */
986 if (pos->attr.type == PERF_TYPE_SOFTWARE)
988 if (pmu_type == PERF_TYPE_SOFTWARE) {
989 pmu_type = pos->attr.type;
992 if (pmu_type != pos->attr.type)
999 static void printout(struct perf_stat_config *config, int id, int nr,
1000 struct perf_evsel *counter, double uval,
1001 char *prefix, u64 run, u64 ena, double noise,
1002 struct runtime_stat *st)
1004 struct perf_stat_output_ctx out;
1005 struct outstate os = {
1006 .fh = config->output,
1007 .prefix = prefix ? prefix : "",
1012 print_metric_t pm = print_metric_std;
1015 if (config->metric_only) {
1016 nl = new_line_metric;
1017 if (config->csv_output)
1018 pm = print_metric_only_csv;
1020 pm = print_metric_only;
1024 if (config->csv_output && !config->metric_only) {
1025 static int aggr_fields[] = {
1033 pm = print_metric_csv;
1036 os.nfields += aggr_fields[config->aggr_mode];
1040 if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1041 if (config->metric_only) {
1042 pm(config, &os, NULL, "", "", 0);
1045 aggr_printout(config, counter, id, nr);
1047 fprintf(config->output, "%*s%s",
1048 config->csv_output ? 0 : 18,
1049 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1052 if (counter->supported) {
1053 print_free_counters_hint = 1;
1054 if (is_mixed_hw_group(counter))
1055 print_mixed_hw_group_error = 1;
1058 fprintf(config->output, "%-*s%s",
1059 config->csv_output ? 0 : config->unit_width,
1060 counter->unit, config->csv_sep);
1062 fprintf(config->output, "%*s",
1063 config->csv_output ? 0 : -25,
1064 perf_evsel__name(counter));
1067 fprintf(config->output, "%s%s",
1068 config->csv_sep, counter->cgrp->name);
1070 if (!config->csv_output)
1071 pm(config, &os, NULL, NULL, "", 0);
1072 print_noise(config, counter, noise);
1073 print_running(config, run, ena);
1074 if (config->csv_output)
1075 pm(config, &os, NULL, NULL, "", 0);
1079 if (!config->metric_only)
1080 abs_printout(config, id, nr, counter, uval);
1082 out.print_metric = pm;
1085 out.force_header = false;
1087 if (config->csv_output && !config->metric_only) {
1088 print_noise(config, counter, noise);
1089 print_running(config, run, ena);
1092 perf_stat__print_shadow_stats(config, counter, uval,
1093 first_shadow_cpu(counter, id),
1094 &out, &metric_events, st);
1095 if (!config->csv_output && !config->metric_only) {
1096 print_noise(config, counter, noise);
1097 print_running(config, run, ena);
1101 static void aggr_update_shadow(void)
1105 struct perf_evsel *counter;
1107 for (s = 0; s < aggr_map->nr; s++) {
1108 id = aggr_map->map[s];
1109 evlist__for_each_entry(evsel_list, counter) {
1111 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1112 s2 = aggr_get_id(evsel_list->cpus, cpu);
1115 val += perf_counts(counter->counts, cpu, 0)->val;
1117 perf_stat__update_shadow_stats(counter, val,
1118 first_shadow_cpu(counter, id),
1124 static void uniquify_event_name(struct perf_evsel *counter)
1129 if (counter->uniquified_name ||
1130 !counter->pmu_name || !strncmp(counter->name, counter->pmu_name,
1131 strlen(counter->pmu_name)))
1134 config = strchr(counter->name, '/');
1136 if (asprintf(&new_name,
1137 "%s%s", counter->pmu_name, config) > 0) {
1138 free(counter->name);
1139 counter->name = new_name;
1142 if (asprintf(&new_name,
1143 "%s [%s]", counter->name, counter->pmu_name) > 0) {
1144 free(counter->name);
1145 counter->name = new_name;
1149 counter->uniquified_name = true;
1152 static void collect_all_aliases(struct perf_evsel *counter,
1153 void (*cb)(struct perf_evsel *counter, void *data,
1157 struct perf_evsel *alias;
1159 alias = list_prepare_entry(counter, &(evsel_list->entries), node);
1160 list_for_each_entry_continue (alias, &evsel_list->entries, node) {
1161 if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
1162 alias->scale != counter->scale ||
1163 alias->cgrp != counter->cgrp ||
1164 strcmp(alias->unit, counter->unit) ||
1165 perf_evsel__is_clock(alias) != perf_evsel__is_clock(counter))
1167 alias->merged_stat = true;
1168 cb(alias, data, false);
1172 static bool collect_data(struct perf_evsel *counter,
1173 void (*cb)(struct perf_evsel *counter, void *data,
1177 if (counter->merged_stat)
1179 cb(counter, data, true);
1181 uniquify_event_name(counter);
1182 else if (counter->auto_merge_stats)
1183 collect_all_aliases(counter, cb, data);
1194 static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
1196 struct aggr_data *ad = data;
1199 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1200 struct perf_counts_values *counts;
1202 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1207 counts = perf_counts(counter->counts, cpu, 0);
1209 * When any result is bad, make them all to give
1210 * consistent output in interval mode.
1212 if (counts->ena == 0 || counts->run == 0 ||
1213 counter->counts->scaled == -1) {
1218 ad->val += counts->val;
1219 ad->ena += counts->ena;
1220 ad->run += counts->run;
1224 static void print_aggr(struct perf_stat_config *config,
1225 struct perf_evlist *evlist,
1228 bool metric_only = config->metric_only;
1229 FILE *output = config->output;
1230 struct perf_evsel *counter;
1236 if (!(aggr_map || aggr_get_id))
1239 aggr_update_shadow();
1242 * With metric_only everything is on a single line.
1243 * Without each counter has its own line.
1245 for (s = 0; s < aggr_map->nr; s++) {
1246 struct aggr_data ad;
1247 if (prefix && metric_only)
1248 fprintf(output, "%s", prefix);
1250 ad.id = id = aggr_map->map[s];
1252 evlist__for_each_entry(evlist, counter) {
1253 if (is_duration_time(counter))
1256 ad.val = ad.ena = ad.run = 0;
1258 if (!collect_data(counter, aggr_cb, &ad))
1264 if (first && metric_only) {
1266 aggr_printout(config, counter, id, nr);
1268 if (prefix && !metric_only)
1269 fprintf(output, "%s", prefix);
1271 uval = val * counter->scale;
1272 printout(config, id, nr, counter, uval, prefix,
1273 run, ena, 1.0, &rt_stat);
1275 fputc('\n', output);
1278 fputc('\n', output);
1282 static int cmp_val(const void *a, const void *b)
1284 return ((struct perf_aggr_thread_value *)b)->val -
1285 ((struct perf_aggr_thread_value *)a)->val;
1288 static struct perf_aggr_thread_value *sort_aggr_thread(
1289 struct perf_evsel *counter,
1290 int nthreads, int ncpus,
1293 int cpu, thread, i = 0;
1295 struct perf_aggr_thread_value *buf;
1297 buf = calloc(nthreads, sizeof(struct perf_aggr_thread_value));
1301 for (thread = 0; thread < nthreads; thread++) {
1302 u64 ena = 0, run = 0, val = 0;
1304 for (cpu = 0; cpu < ncpus; cpu++) {
1305 val += perf_counts(counter->counts, cpu, thread)->val;
1306 ena += perf_counts(counter->counts, cpu, thread)->ena;
1307 run += perf_counts(counter->counts, cpu, thread)->run;
1310 uval = val * counter->scale;
1313 * Skip value 0 when enabling --per-thread globally,
1314 * otherwise too many 0 output.
1316 if (uval == 0.0 && target__has_per_thread(&target))
1319 buf[i].counter = counter;
1328 qsort(buf, i, sizeof(struct perf_aggr_thread_value), cmp_val);
1336 static void print_aggr_thread(struct perf_stat_config *config,
1337 struct perf_evsel *counter, char *prefix)
1339 FILE *output = config->output;
1340 int nthreads = thread_map__nr(counter->threads);
1341 int ncpus = cpu_map__nr(counter->cpus);
1342 int thread, sorted_threads, id;
1343 struct perf_aggr_thread_value *buf;
1345 buf = sort_aggr_thread(counter, nthreads, ncpus, &sorted_threads);
1347 perror("cannot sort aggr thread");
1351 for (thread = 0; thread < sorted_threads; thread++) {
1353 fprintf(output, "%s", prefix);
1355 id = buf[thread].id;
1357 printout(config, id, 0, buf[thread].counter, buf[thread].uval,
1358 prefix, buf[thread].run, buf[thread].ena, 1.0,
1359 &config->stats[id]);
1361 printout(config, id, 0, buf[thread].counter, buf[thread].uval,
1362 prefix, buf[thread].run, buf[thread].ena, 1.0,
1364 fputc('\n', output);
1371 double avg, avg_enabled, avg_running;
1374 static void counter_aggr_cb(struct perf_evsel *counter, void *data,
1375 bool first __maybe_unused)
1377 struct caggr_data *cd = data;
1378 struct perf_stat_evsel *ps = counter->stats;
1380 cd->avg += avg_stats(&ps->res_stats[0]);
1381 cd->avg_enabled += avg_stats(&ps->res_stats[1]);
1382 cd->avg_running += avg_stats(&ps->res_stats[2]);
1386 * Print out the results of a single counter:
1387 * aggregated counts in system-wide mode
1389 static void print_counter_aggr(struct perf_stat_config *config,
1390 struct perf_evsel *counter, char *prefix)
1392 bool metric_only = config->metric_only;
1393 FILE *output = config->output;
1395 struct caggr_data cd = { .avg = 0.0 };
1397 if (!collect_data(counter, counter_aggr_cb, &cd))
1400 if (prefix && !metric_only)
1401 fprintf(output, "%s", prefix);
1403 uval = cd.avg * counter->scale;
1404 printout(config, -1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled,
1407 fprintf(output, "\n");
1410 static void counter_cb(struct perf_evsel *counter, void *data,
1411 bool first __maybe_unused)
1413 struct aggr_data *ad = data;
1415 ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
1416 ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
1417 ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
1421 * Print out the results of a single counter:
1422 * does not use aggregated count in system-wide
1424 static void print_counter(struct perf_stat_config *config,
1425 struct perf_evsel *counter, char *prefix)
1427 FILE *output = config->output;
1432 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1433 struct aggr_data ad = { .cpu = cpu };
1435 if (!collect_data(counter, counter_cb, &ad))
1442 fprintf(output, "%s", prefix);
1444 uval = val * counter->scale;
1445 printout(config, cpu, 0, counter, uval, prefix, run, ena, 1.0,
1448 fputc('\n', output);
1452 static void print_no_aggr_metric(struct perf_stat_config *config,
1453 struct perf_evlist *evlist,
1458 struct perf_evsel *counter;
1462 nrcpus = evlist->cpus->nr;
1463 for (cpu = 0; cpu < nrcpus; cpu++) {
1467 fputs(prefix, config->output);
1468 evlist__for_each_entry(evlist, counter) {
1469 if (is_duration_time(counter))
1472 aggr_printout(config, counter, cpu, 0);
1475 val = perf_counts(counter->counts, cpu, 0)->val;
1476 ena = perf_counts(counter->counts, cpu, 0)->ena;
1477 run = perf_counts(counter->counts, cpu, 0)->run;
1479 uval = val * counter->scale;
1480 printout(config, cpu, 0, counter, uval, prefix, run, ena, 1.0,
1483 fputc('\n', config->output);
1487 static int aggr_header_lens[] = {
1495 static const char *aggr_header_csv[] = {
1496 [AGGR_CORE] = "core,cpus,",
1497 [AGGR_SOCKET] = "socket,cpus",
1498 [AGGR_NONE] = "cpu,",
1499 [AGGR_THREAD] = "comm-pid,",
1503 static void print_metric_headers(struct perf_stat_config *config,
1504 struct perf_evlist *evlist,
1505 const char *prefix, bool no_indent)
1507 struct perf_stat_output_ctx out;
1508 struct perf_evsel *counter;
1509 struct outstate os = {
1510 .fh = config->output
1514 fprintf(config->output, "%s", prefix);
1516 if (!config->csv_output && !no_indent)
1517 fprintf(config->output, "%*s",
1518 aggr_header_lens[config->aggr_mode], "");
1519 if (config->csv_output) {
1520 if (config->interval)
1521 fputs("time,", config->output);
1522 fputs(aggr_header_csv[config->aggr_mode], config->output);
1525 /* Print metrics headers only */
1526 evlist__for_each_entry(evlist, counter) {
1527 if (is_duration_time(counter))
1531 out.print_metric = print_metric_header;
1532 out.new_line = new_line_metric;
1533 out.force_header = true;
1535 perf_stat__print_shadow_stats(config, counter, 0,
1541 fputc('\n', config->output);
1544 static void print_interval(struct perf_stat_config *config,
1545 struct perf_evlist *evlist,
1546 char *prefix, struct timespec *ts)
1548 bool metric_only = config->metric_only;
1549 unsigned int unit_width = config->unit_width;
1550 FILE *output = config->output;
1551 static int num_print_interval;
1553 if (config->interval_clear)
1554 puts(CONSOLE_CLEAR);
1556 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, config->csv_sep);
1558 if ((num_print_interval == 0 && !config->csv_output) || config->interval_clear) {
1559 switch (config->aggr_mode) {
1561 fprintf(output, "# time socket cpus");
1563 fprintf(output, " counts %*s events\n", unit_width, "unit");
1566 fprintf(output, "# time core cpus");
1568 fprintf(output, " counts %*s events\n", unit_width, "unit");
1571 fprintf(output, "# time CPU ");
1573 fprintf(output, " counts %*s events\n", unit_width, "unit");
1576 fprintf(output, "# time comm-pid");
1578 fprintf(output, " counts %*s events\n", unit_width, "unit");
1582 fprintf(output, "# time");
1584 fprintf(output, " counts %*s events\n", unit_width, "unit");
1590 if ((num_print_interval == 0 || config->interval_clear) && metric_only)
1591 print_metric_headers(config, evlist, " ", true);
1592 if (++num_print_interval == 25)
1593 num_print_interval = 0;
1596 static void print_header(struct perf_stat_config *config,
1597 struct target *_target,
1598 int argc, const char **argv)
1600 FILE *output = config->output;
1605 if (!config->csv_output) {
1606 fprintf(output, "\n");
1607 fprintf(output, " Performance counter stats for ");
1608 if (_target->system_wide)
1609 fprintf(output, "\'system wide");
1610 else if (_target->cpu_list)
1611 fprintf(output, "\'CPU(s) %s", _target->cpu_list);
1612 else if (!target__has_task(_target)) {
1613 fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1614 for (i = 1; argv && (i < argc); i++)
1615 fprintf(output, " %s", argv[i]);
1616 } else if (_target->pid)
1617 fprintf(output, "process id \'%s", _target->pid);
1619 fprintf(output, "thread id \'%s", _target->tid);
1621 fprintf(output, "\'");
1623 fprintf(output, " (%d runs)", run_count);
1624 fprintf(output, ":\n\n");
1628 static int get_precision(double num)
1633 return lround(ceil(-log10(num)));
1636 static void print_table(FILE *output, int precision, double avg)
1639 int idx, indent = 0;
1641 scnprintf(tmp, 64, " %17.*f", precision, avg);
1642 while (tmp[indent] == ' ')
1645 fprintf(output, "%*s# Table of individual measurements:\n", indent, "");
1647 for (idx = 0; idx < run_count; idx++) {
1648 double run = (double) walltime_run[idx] / NSEC_PER_SEC;
1649 int h, n = 1 + abs((int) (100.0 * (run - avg)/run) / 5);
1651 fprintf(output, " %17.*f (%+.*f) ",
1652 precision, run, precision, run - avg);
1654 for (h = 0; h < n; h++)
1655 fprintf(output, "#");
1657 fprintf(output, "\n");
1660 fprintf(output, "\n%*s# Final result:\n", indent, "");
1663 static double timeval2double(struct timeval *t)
1665 return t->tv_sec + (double) t->tv_usec/USEC_PER_SEC;
1668 static void print_footer(struct perf_stat_config *config)
1670 double avg = avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC;
1671 FILE *output = config->output;
1675 fprintf(output, "\n");
1677 if (run_count == 1) {
1678 fprintf(output, " %17.9f seconds time elapsed", avg);
1681 double ru_utime = timeval2double(&ru_data.ru_utime);
1682 double ru_stime = timeval2double(&ru_data.ru_stime);
1684 fprintf(output, "\n\n");
1685 fprintf(output, " %17.9f seconds user\n", ru_utime);
1686 fprintf(output, " %17.9f seconds sys\n", ru_stime);
1689 double sd = stddev_stats(&walltime_nsecs_stats) / NSEC_PER_SEC;
1691 * Display at most 2 more significant
1692 * digits than the stddev inaccuracy.
1694 int precision = get_precision(sd) + 2;
1696 if (walltime_run_table)
1697 print_table(output, precision, avg);
1699 fprintf(output, " %17.*f +- %.*f seconds time elapsed",
1700 precision, avg, precision, sd);
1702 print_noise_pct(config, sd, avg);
1704 fprintf(output, "\n\n");
1706 if (print_free_counters_hint &&
1707 sysctl__read_int("kernel/nmi_watchdog", &n) >= 0 &&
1710 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1711 " echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1713 " echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1715 if (print_mixed_hw_group_error)
1717 "The events in group usually have to be from "
1718 "the same PMU. Try reorganizing the group.\n");
1722 perf_evlist__print_counters(struct perf_evlist *evlist,
1723 struct perf_stat_config *config,
1724 struct target *_target,
1725 struct timespec *ts,
1726 int argc, const char **argv)
1728 bool metric_only = config->metric_only;
1729 int interval = config->interval;
1730 struct perf_evsel *counter;
1731 char buf[64], *prefix = NULL;
1734 print_interval(config, evlist, prefix = buf, ts);
1736 print_header(config, _target, argc, argv);
1739 static int num_print_iv;
1741 if (num_print_iv == 0 && !interval)
1742 print_metric_headers(config, evlist, prefix, false);
1743 if (num_print_iv++ == 25)
1745 if (config->aggr_mode == AGGR_GLOBAL && prefix)
1746 fprintf(config->output, "%s", prefix);
1749 switch (config->aggr_mode) {
1752 print_aggr(config, evlist, prefix);
1755 evlist__for_each_entry(evlist, counter) {
1756 if (is_duration_time(counter))
1758 print_aggr_thread(config, counter, prefix);
1762 evlist__for_each_entry(evlist, counter) {
1763 if (is_duration_time(counter))
1765 print_counter_aggr(config, counter, prefix);
1768 fputc('\n', config->output);
1772 print_no_aggr_metric(config, evlist, prefix);
1774 evlist__for_each_entry(evlist, counter) {
1775 if (is_duration_time(counter))
1777 print_counter(config, counter, prefix);
1786 if (!interval && !config->csv_output)
1787 print_footer(config);
1789 fflush(config->output);
1792 static void print_counters(struct timespec *ts, int argc, const char **argv)
1794 /* Do not print anything if we record to the pipe. */
1795 if (STAT_RECORD && perf_stat.data.is_pipe)
1798 perf_evlist__print_counters(evsel_list, &stat_config, &target,
1802 static volatile int signr = -1;
1804 static void skip_signal(int signo)
1806 if ((child_pid == -1) || stat_config.interval)
1811 * render child_pid harmless
1812 * won't send SIGTERM to a random
1813 * process in case of race condition
1814 * and fast PID recycling
1819 static void sig_atexit(void)
1824 * avoid race condition with SIGCHLD handler
1825 * in skip_signal() which is modifying child_pid
1826 * goal is to avoid send SIGTERM to a random
1830 sigaddset(&set, SIGCHLD);
1831 sigprocmask(SIG_BLOCK, &set, &oset);
1833 if (child_pid != -1)
1834 kill(child_pid, SIGTERM);
1836 sigprocmask(SIG_SETMASK, &oset, NULL);
1841 signal(signr, SIG_DFL);
1842 kill(getpid(), signr);
1845 static int stat__set_big_num(const struct option *opt __maybe_unused,
1846 const char *s __maybe_unused, int unset)
1848 big_num_opt = unset ? 0 : 1;
1852 static int enable_metric_only(const struct option *opt __maybe_unused,
1853 const char *s __maybe_unused, int unset)
1855 force_metric_only = true;
1856 stat_config.metric_only = !unset;
1860 static int parse_metric_groups(const struct option *opt,
1862 int unset __maybe_unused)
1864 return metricgroup__parse_groups(opt, str, &metric_events);
1867 static const struct option stat_options[] = {
1868 OPT_BOOLEAN('T', "transaction", &transaction_run,
1869 "hardware transaction statistics"),
1870 OPT_CALLBACK('e', "event", &evsel_list, "event",
1871 "event selector. use 'perf list' to list available events",
1872 parse_events_option),
1873 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1874 "event filter", parse_filter),
1875 OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
1876 "child tasks do not inherit counters"),
1877 OPT_STRING('p', "pid", &target.pid, "pid",
1878 "stat events on existing process id"),
1879 OPT_STRING('t', "tid", &target.tid, "tid",
1880 "stat events on existing thread id"),
1881 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1882 "system-wide collection from all CPUs"),
1883 OPT_BOOLEAN('g', "group", &group,
1884 "put the counters into a counter group"),
1885 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1886 OPT_INCR('v', "verbose", &verbose,
1887 "be more verbose (show counter open errors, etc)"),
1888 OPT_INTEGER('r', "repeat", &run_count,
1889 "repeat command and print average + stddev (max: 100, forever: 0)"),
1890 OPT_BOOLEAN(0, "table", &walltime_run_table,
1891 "display details about each run (only with -r option)"),
1892 OPT_BOOLEAN('n', "null", &null_run,
1893 "null run - dont start any counters"),
1894 OPT_INCR('d', "detailed", &detailed_run,
1895 "detailed run - start a lot of events"),
1896 OPT_BOOLEAN('S', "sync", &sync_run,
1897 "call sync() before starting a run"),
1898 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1899 "print large numbers with thousands\' separators",
1901 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1902 "list of cpus to monitor in system-wide"),
1903 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1904 "disable CPU count aggregation", AGGR_NONE),
1905 OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
1906 OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
1907 "print counts with custom separator"),
1908 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1909 "monitor event in cgroup name only", parse_cgroups),
1910 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1911 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1912 OPT_INTEGER(0, "log-fd", &output_fd,
1913 "log output to fd, instead of stderr"),
1914 OPT_STRING(0, "pre", &pre_cmd, "command",
1915 "command to run prior to the measured command"),
1916 OPT_STRING(0, "post", &post_cmd, "command",
1917 "command to run after to the measured command"),
1918 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1919 "print counts at regular interval in ms "
1920 "(overhead is possible for values <= 100ms)"),
1921 OPT_INTEGER(0, "interval-count", &stat_config.times,
1922 "print counts for fixed number of times"),
1923 OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
1924 "clear screen in between new interval"),
1925 OPT_UINTEGER(0, "timeout", &stat_config.timeout,
1926 "stop workload and print counts after a timeout period in ms (>= 10ms)"),
1927 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1928 "aggregate counts per processor socket", AGGR_SOCKET),
1929 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1930 "aggregate counts per physical processor core", AGGR_CORE),
1931 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1932 "aggregate counts per thread", AGGR_THREAD),
1933 OPT_UINTEGER('D', "delay", &stat_config.initial_delay,
1934 "ms to wait before starting measurement after program start"),
1935 OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
1936 "Only print computed metrics. No raw values", enable_metric_only),
1937 OPT_BOOLEAN(0, "topdown", &topdown_run,
1938 "measure topdown level 1 statistics"),
1939 OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1940 "measure SMI cost"),
1941 OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1942 "monitor specified metrics or metric groups (separated by ,)",
1943 parse_metric_groups),
1947 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1949 return cpu_map__get_socket(map, cpu, NULL);
1952 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1954 return cpu_map__get_core(map, cpu, NULL);
1957 static int cpu_map__get_max(struct cpu_map *map)
1961 for (i = 0; i < map->nr; i++) {
1962 if (map->map[i] > max)
1969 static struct cpu_map *cpus_aggr_map;
1971 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1978 cpu = map->map[idx];
1980 if (cpus_aggr_map->map[cpu] == -1)
1981 cpus_aggr_map->map[cpu] = get_id(map, idx);
1983 return cpus_aggr_map->map[cpu];
1986 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1988 return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1991 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1993 return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1996 static int perf_stat_init_aggr_mode(void)
2000 switch (stat_config.aggr_mode) {
2002 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
2003 perror("cannot build socket map");
2006 aggr_get_id = perf_stat__get_socket_cached;
2009 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
2010 perror("cannot build core map");
2013 aggr_get_id = perf_stat__get_core_cached;
2024 * The evsel_list->cpus is the base we operate on,
2025 * taking the highest cpu number to be the size of
2026 * the aggregation translate cpumap.
2028 nr = cpu_map__get_max(evsel_list->cpus);
2029 cpus_aggr_map = cpu_map__empty_new(nr + 1);
2030 return cpus_aggr_map ? 0 : -ENOMEM;
2033 static void perf_stat__exit_aggr_mode(void)
2035 cpu_map__put(aggr_map);
2036 cpu_map__put(cpus_aggr_map);
2038 cpus_aggr_map = NULL;
2041 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
2048 cpu = map->map[idx];
2050 if (cpu >= env->nr_cpus_avail)
2056 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
2058 struct perf_env *env = data;
2059 int cpu = perf_env__get_cpu(env, map, idx);
2061 return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
2064 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
2066 struct perf_env *env = data;
2067 int core = -1, cpu = perf_env__get_cpu(env, map, idx);
2070 int socket_id = env->cpu[cpu].socket_id;
2073 * Encode socket in upper 16 bits
2074 * core_id is relative to socket, and
2075 * we need a global id. So we combine
2078 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
2084 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
2085 struct cpu_map **sockp)
2087 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
2090 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
2091 struct cpu_map **corep)
2093 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
2096 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
2098 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
2101 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
2103 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
2106 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
2108 struct perf_env *env = &st->session->header.env;
2110 switch (stat_config.aggr_mode) {
2112 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
2113 perror("cannot build socket map");
2116 aggr_get_id = perf_stat__get_socket_file;
2119 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
2120 perror("cannot build core map");
2123 aggr_get_id = perf_stat__get_core_file;
2136 static int topdown_filter_events(const char **attr, char **str, bool use_group)
2143 for (i = 0; attr[i]; i++) {
2144 if (pmu_have_event("cpu", attr[i])) {
2145 len += strlen(attr[i]) + 1;
2146 attr[i - off] = attr[i];
2150 attr[i - off] = NULL;
2152 *str = malloc(len + 1 + 2);
2162 for (i = 0; attr[i]; i++) {
2175 __weak bool arch_topdown_check_group(bool *warn)
2181 __weak void arch_topdown_group_warn(void)
2186 * Add default attributes, if there were no attributes specified or
2187 * if -d/--detailed, -d -d or -d -d -d is used:
2189 static int add_default_attributes(void)
2192 struct perf_event_attr default_attrs0[] = {
2194 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
2195 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
2196 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
2197 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
2199 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
2201 struct perf_event_attr frontend_attrs[] = {
2202 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
2204 struct perf_event_attr backend_attrs[] = {
2205 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
2207 struct perf_event_attr default_attrs1[] = {
2208 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
2209 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
2210 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
2215 * Detailed stats (-d), covering the L1 and last level data caches:
2217 struct perf_event_attr detailed_attrs[] = {
2219 { .type = PERF_TYPE_HW_CACHE,
2221 PERF_COUNT_HW_CACHE_L1D << 0 |
2222 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2223 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2225 { .type = PERF_TYPE_HW_CACHE,
2227 PERF_COUNT_HW_CACHE_L1D << 0 |
2228 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2229 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2231 { .type = PERF_TYPE_HW_CACHE,
2233 PERF_COUNT_HW_CACHE_LL << 0 |
2234 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2235 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2237 { .type = PERF_TYPE_HW_CACHE,
2239 PERF_COUNT_HW_CACHE_LL << 0 |
2240 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2241 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2245 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2247 struct perf_event_attr very_detailed_attrs[] = {
2249 { .type = PERF_TYPE_HW_CACHE,
2251 PERF_COUNT_HW_CACHE_L1I << 0 |
2252 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2253 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2255 { .type = PERF_TYPE_HW_CACHE,
2257 PERF_COUNT_HW_CACHE_L1I << 0 |
2258 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2259 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2261 { .type = PERF_TYPE_HW_CACHE,
2263 PERF_COUNT_HW_CACHE_DTLB << 0 |
2264 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2265 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2267 { .type = PERF_TYPE_HW_CACHE,
2269 PERF_COUNT_HW_CACHE_DTLB << 0 |
2270 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2271 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2273 { .type = PERF_TYPE_HW_CACHE,
2275 PERF_COUNT_HW_CACHE_ITLB << 0 |
2276 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2277 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2279 { .type = PERF_TYPE_HW_CACHE,
2281 PERF_COUNT_HW_CACHE_ITLB << 0 |
2282 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2283 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2288 * Very, very detailed stats (-d -d -d), adding prefetch events:
2290 struct perf_event_attr very_very_detailed_attrs[] = {
2292 { .type = PERF_TYPE_HW_CACHE,
2294 PERF_COUNT_HW_CACHE_L1D << 0 |
2295 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2296 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2298 { .type = PERF_TYPE_HW_CACHE,
2300 PERF_COUNT_HW_CACHE_L1D << 0 |
2301 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2302 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2304 struct parse_events_error errinfo;
2306 /* Set attrs if no event is selected and !null_run: */
2310 if (transaction_run) {
2311 /* Handle -T as -M transaction. Once platform specific metrics
2312 * support has been added to the json files, all archictures
2313 * will use this approach. To determine transaction support
2314 * on an architecture test for such a metric name.
2316 if (metricgroup__has_metric("transaction")) {
2317 struct option opt = { .value = &evsel_list };
2319 return metricgroup__parse_groups(&opt, "transaction",
2323 if (pmu_have_event("cpu", "cycles-ct") &&
2324 pmu_have_event("cpu", "el-start"))
2325 err = parse_events(evsel_list, transaction_attrs,
2328 err = parse_events(evsel_list,
2329 transaction_limited_attrs,
2332 fprintf(stderr, "Cannot set up transaction events\n");
2333 parse_events_print_error(&errinfo, transaction_attrs);
2342 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
2343 fprintf(stderr, "freeze_on_smi is not supported.\n");
2348 if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
2349 fprintf(stderr, "Failed to set freeze_on_smi.\n");
2355 if (pmu_have_event("msr", "aperf") &&
2356 pmu_have_event("msr", "smi")) {
2357 if (!force_metric_only)
2358 stat_config.metric_only = true;
2359 err = parse_events(evsel_list, smi_cost_attrs, &errinfo);
2361 fprintf(stderr, "To measure SMI cost, it needs "
2362 "msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
2363 parse_events_print_error(&errinfo, smi_cost_attrs);
2367 fprintf(stderr, "Cannot set up SMI cost events\n");
2377 if (stat_config.aggr_mode != AGGR_GLOBAL &&
2378 stat_config.aggr_mode != AGGR_CORE) {
2379 pr_err("top down event configuration requires --per-core mode\n");
2382 stat_config.aggr_mode = AGGR_CORE;
2383 if (nr_cgroups || !target__has_cpu(&target)) {
2384 pr_err("top down event configuration requires system-wide mode (-a)\n");
2388 if (!force_metric_only)
2389 stat_config.metric_only = true;
2390 if (topdown_filter_events(topdown_attrs, &str,
2391 arch_topdown_check_group(&warn)) < 0) {
2392 pr_err("Out of memory\n");
2395 if (topdown_attrs[0] && str) {
2397 arch_topdown_group_warn();
2398 err = parse_events(evsel_list, str, &errinfo);
2401 "Cannot set up top down events %s: %d\n",
2404 parse_events_print_error(&errinfo, str);
2408 fprintf(stderr, "System does not support topdown\n");
2414 if (!evsel_list->nr_entries) {
2415 if (target__has_cpu(&target))
2416 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2418 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2420 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2421 if (perf_evlist__add_default_attrs(evsel_list,
2422 frontend_attrs) < 0)
2425 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2426 if (perf_evlist__add_default_attrs(evsel_list,
2430 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2434 /* Detailed events get appended to the event list: */
2436 if (detailed_run < 1)
2439 /* Append detailed run extra attributes: */
2440 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2443 if (detailed_run < 2)
2446 /* Append very detailed run extra attributes: */
2447 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2450 if (detailed_run < 3)
2453 /* Append very, very detailed run extra attributes: */
2454 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2457 static const char * const stat_record_usage[] = {
2458 "perf stat record [<options>]",
2462 static void init_features(struct perf_session *session)
2466 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2467 perf_header__set_feat(&session->header, feat);
2469 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2470 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2471 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2472 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2475 static int __cmd_record(int argc, const char **argv)
2477 struct perf_session *session;
2478 struct perf_data *data = &perf_stat.data;
2480 argc = parse_options(argc, argv, stat_options, stat_record_usage,
2481 PARSE_OPT_STOP_AT_NON_OPTION);
2484 data->file.path = output_name;
2486 if (run_count != 1 || forever) {
2487 pr_err("Cannot use -r option with perf stat record.\n");
2491 session = perf_session__new(data, false, NULL);
2492 if (session == NULL) {
2493 pr_err("Perf session creation failed.\n");
2497 init_features(session);
2499 session->evlist = evsel_list;
2500 perf_stat.session = session;
2501 perf_stat.record = true;
2505 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2506 union perf_event *event,
2507 struct perf_session *session)
2509 struct stat_round_event *stat_round = &event->stat_round;
2510 struct perf_evsel *counter;
2511 struct timespec tsh, *ts = NULL;
2512 const char **argv = session->header.env.cmdline_argv;
2513 int argc = session->header.env.nr_cmdline;
2515 evlist__for_each_entry(evsel_list, counter)
2516 perf_stat_process_counter(&stat_config, counter);
2518 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2519 update_stats(&walltime_nsecs_stats, stat_round->time);
2521 if (stat_config.interval && stat_round->time) {
2522 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2523 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2527 print_counters(ts, argc, argv);
2532 int process_stat_config_event(struct perf_tool *tool,
2533 union perf_event *event,
2534 struct perf_session *session __maybe_unused)
2536 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2538 perf_event__read_stat_config(&stat_config, &event->stat_config);
2540 if (cpu_map__empty(st->cpus)) {
2541 if (st->aggr_mode != AGGR_UNSET)
2542 pr_warning("warning: processing task data, aggregation mode not set\n");
2546 if (st->aggr_mode != AGGR_UNSET)
2547 stat_config.aggr_mode = st->aggr_mode;
2549 if (perf_stat.data.is_pipe)
2550 perf_stat_init_aggr_mode();
2552 perf_stat_init_aggr_mode_file(st);
2557 static int set_maps(struct perf_stat *st)
2559 if (!st->cpus || !st->threads)
2562 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2565 perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2567 if (perf_evlist__alloc_stats(evsel_list, true))
2570 st->maps_allocated = true;
2575 int process_thread_map_event(struct perf_tool *tool,
2576 union perf_event *event,
2577 struct perf_session *session __maybe_unused)
2579 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2582 pr_warning("Extra thread map event, ignoring.\n");
2586 st->threads = thread_map__new_event(&event->thread_map);
2590 return set_maps(st);
2594 int process_cpu_map_event(struct perf_tool *tool,
2595 union perf_event *event,
2596 struct perf_session *session __maybe_unused)
2598 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2599 struct cpu_map *cpus;
2602 pr_warning("Extra cpu map event, ignoring.\n");
2606 cpus = cpu_map__new_data(&event->cpu_map.data);
2611 return set_maps(st);
2614 static int runtime_stat_new(struct perf_stat_config *config, int nthreads)
2618 config->stats = calloc(nthreads, sizeof(struct runtime_stat));
2622 config->stats_num = nthreads;
2624 for (i = 0; i < nthreads; i++)
2625 runtime_stat__init(&config->stats[i]);
2630 static void runtime_stat_delete(struct perf_stat_config *config)
2637 for (i = 0; i < config->stats_num; i++)
2638 runtime_stat__exit(&config->stats[i]);
2640 free(config->stats);
2643 static const char * const stat_report_usage[] = {
2644 "perf stat report [<options>]",
2648 static struct perf_stat perf_stat = {
2650 .attr = perf_event__process_attr,
2651 .event_update = perf_event__process_event_update,
2652 .thread_map = process_thread_map_event,
2653 .cpu_map = process_cpu_map_event,
2654 .stat_config = process_stat_config_event,
2655 .stat = perf_event__process_stat_event,
2656 .stat_round = process_stat_round_event,
2658 .aggr_mode = AGGR_UNSET,
2661 static int __cmd_report(int argc, const char **argv)
2663 struct perf_session *session;
2664 const struct option options[] = {
2665 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2666 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2667 "aggregate counts per processor socket", AGGR_SOCKET),
2668 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2669 "aggregate counts per physical processor core", AGGR_CORE),
2670 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2671 "disable CPU count aggregation", AGGR_NONE),
2677 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2679 if (!input_name || !strlen(input_name)) {
2680 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2683 input_name = "perf.data";
2686 perf_stat.data.file.path = input_name;
2687 perf_stat.data.mode = PERF_DATA_MODE_READ;
2689 session = perf_session__new(&perf_stat.data, false, &perf_stat.tool);
2690 if (session == NULL)
2693 perf_stat.session = session;
2694 stat_config.output = stderr;
2695 evsel_list = session->evlist;
2697 ret = perf_session__process_events(session);
2701 perf_session__delete(session);
2705 static void setup_system_wide(int forks)
2708 * Make system wide (-a) the default target if
2709 * no target was specified and one of following
2710 * conditions is met:
2712 * - there's no workload specified
2713 * - there is workload specified but all requested
2714 * events are system wide events
2716 if (!target__none(&target))
2720 target.system_wide = true;
2722 struct perf_evsel *counter;
2724 evlist__for_each_entry(evsel_list, counter) {
2725 if (!counter->system_wide)
2729 if (evsel_list->nr_entries)
2730 target.system_wide = true;
2734 int cmd_stat(int argc, const char **argv)
2736 const char * const stat_usage[] = {
2737 "perf stat [<options>] [<command>]",
2740 int status = -EINVAL, run_idx;
2742 FILE *output = stderr;
2743 unsigned int interval, timeout;
2744 const char * const stat_subcommands[] = { "record", "report" };
2746 setlocale(LC_ALL, "");
2748 evsel_list = perf_evlist__new();
2749 if (evsel_list == NULL)
2752 parse_events__shrink_config_terms();
2753 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2754 (const char **) stat_usage,
2755 PARSE_OPT_STOP_AT_NON_OPTION);
2756 perf_stat__collect_metric_expr(evsel_list);
2757 perf_stat__init_shadow_stats();
2759 if (stat_config.csv_sep) {
2760 stat_config.csv_output = true;
2761 if (!strcmp(stat_config.csv_sep, "\\t"))
2762 stat_config.csv_sep = "\t";
2764 stat_config.csv_sep = DEFAULT_SEPARATOR;
2766 if (argc && !strncmp(argv[0], "rec", 3)) {
2767 argc = __cmd_record(argc, argv);
2770 } else if (argc && !strncmp(argv[0], "rep", 3))
2771 return __cmd_report(argc, argv);
2773 interval = stat_config.interval;
2774 timeout = stat_config.timeout;
2777 * For record command the -o is already taken care of.
2779 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2782 if (output_name && output_fd) {
2783 fprintf(stderr, "cannot use both --output and --log-fd\n");
2784 parse_options_usage(stat_usage, stat_options, "o", 1);
2785 parse_options_usage(NULL, stat_options, "log-fd", 0);
2789 if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2790 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2794 if (stat_config.metric_only && run_count > 1) {
2795 fprintf(stderr, "--metric-only is not supported with -r\n");
2799 if (walltime_run_table && run_count <= 1) {
2800 fprintf(stderr, "--table is only supported with -r\n");
2801 parse_options_usage(stat_usage, stat_options, "r", 1);
2802 parse_options_usage(NULL, stat_options, "table", 0);
2806 if (output_fd < 0) {
2807 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2808 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2814 mode = append_file ? "a" : "w";
2816 output = fopen(output_name, mode);
2818 perror("failed to create output file");
2821 clock_gettime(CLOCK_REALTIME, &tm);
2822 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2823 } else if (output_fd > 0) {
2824 mode = append_file ? "a" : "w";
2825 output = fdopen(output_fd, mode);
2827 perror("Failed opening logfd");
2832 stat_config.output = output;
2835 * let the spreadsheet do the pretty-printing
2837 if (stat_config.csv_output) {
2838 /* User explicitly passed -B? */
2839 if (big_num_opt == 1) {
2840 fprintf(stderr, "-B option not supported with -x\n");
2841 parse_options_usage(stat_usage, stat_options, "B", 1);
2842 parse_options_usage(NULL, stat_options, "x", 1);
2844 } else /* Nope, so disable big number formatting */
2846 } else if (big_num_opt == 0) /* User passed --no-big-num */
2849 setup_system_wide(argc);
2852 * Display user/system times only for single
2853 * run and when there's specified tracee.
2855 if ((run_count == 1) && target__none(&target))
2858 if (run_count < 0) {
2859 pr_err("Run count must be a positive number\n");
2860 parse_options_usage(stat_usage, stat_options, "r", 1);
2862 } else if (run_count == 0) {
2867 if (walltime_run_table) {
2868 walltime_run = zalloc(run_count * sizeof(walltime_run[0]));
2869 if (!walltime_run) {
2870 pr_err("failed to setup -r option");
2875 if ((stat_config.aggr_mode == AGGR_THREAD) &&
2876 !target__has_task(&target)) {
2877 if (!target.system_wide || target.cpu_list) {
2878 fprintf(stderr, "The --per-thread option is only "
2879 "available when monitoring via -p -t -a "
2880 "options or only --per-thread.\n");
2881 parse_options_usage(NULL, stat_options, "p", 1);
2882 parse_options_usage(NULL, stat_options, "t", 1);
2888 * no_aggr, cgroup are for system-wide only
2889 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2891 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2892 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2893 !target__has_cpu(&target)) {
2894 fprintf(stderr, "both cgroup and no-aggregation "
2895 "modes only available in system-wide mode\n");
2897 parse_options_usage(stat_usage, stat_options, "G", 1);
2898 parse_options_usage(NULL, stat_options, "A", 1);
2899 parse_options_usage(NULL, stat_options, "a", 1);
2903 if (add_default_attributes())
2906 target__validate(&target);
2908 if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2909 target.per_thread = true;
2911 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2912 if (target__has_task(&target)) {
2913 pr_err("Problems finding threads of monitor\n");
2914 parse_options_usage(stat_usage, stat_options, "p", 1);
2915 parse_options_usage(NULL, stat_options, "t", 1);
2916 } else if (target__has_cpu(&target)) {
2917 perror("failed to parse CPUs map");
2918 parse_options_usage(stat_usage, stat_options, "C", 1);
2919 parse_options_usage(NULL, stat_options, "a", 1);
2925 * Initialize thread_map with comm names,
2926 * so we could print it out on output.
2928 if (stat_config.aggr_mode == AGGR_THREAD) {
2929 thread_map__read_comms(evsel_list->threads);
2930 if (target.system_wide) {
2931 if (runtime_stat_new(&stat_config,
2932 thread_map__nr(evsel_list->threads))) {
2938 if (stat_config.times && interval)
2939 interval_count = true;
2940 else if (stat_config.times && !interval) {
2941 pr_err("interval-count option should be used together with "
2942 "interval-print.\n");
2943 parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2944 parse_options_usage(stat_usage, stat_options, "I", 1);
2948 if (timeout && timeout < 100) {
2950 pr_err("timeout must be >= 10ms.\n");
2951 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2954 pr_warning("timeout < 100ms. "
2955 "The overhead percentage could be high in some cases. "
2956 "Please proceed with caution.\n");
2958 if (timeout && interval) {
2959 pr_err("timeout option is not supported with interval-print.\n");
2960 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2961 parse_options_usage(stat_usage, stat_options, "I", 1);
2965 if (perf_evlist__alloc_stats(evsel_list, interval))
2968 if (perf_stat_init_aggr_mode())
2972 * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2973 * while avoiding that older tools show confusing messages.
2975 * However for pipe sessions we need to keep it zero,
2976 * because script's perf_evsel__check_attr is triggered
2977 * by attr->sample_type != 0, and we can't run it on
2980 stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2983 * We dont want to block the signals - that would cause
2984 * child tasks to inherit that and Ctrl-C would not work.
2985 * What we want is for Ctrl-C to work in the exec()-ed
2986 * task, but being ignored by perf stat itself:
2990 signal(SIGINT, skip_signal);
2991 signal(SIGCHLD, skip_signal);
2992 signal(SIGALRM, skip_signal);
2993 signal(SIGABRT, skip_signal);
2996 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2997 if (run_count != 1 && verbose > 0)
2998 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
3001 status = run_perf_stat(argc, argv, run_idx);
3002 if (forever && status != -1) {
3003 print_counters(NULL, argc, argv);
3004 perf_stat__reset_stats();
3008 if (!forever && status != -1 && !interval)
3009 print_counters(NULL, argc, argv);
3013 * We synthesize the kernel mmap record just so that older tools
3014 * don't emit warnings about not being able to resolve symbols
3015 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
3016 * a saner message about no samples being in the perf.data file.
3018 * This also serves to suppress a warning about f_header.data.size == 0
3019 * in header.c at the moment 'perf stat record' gets introduced, which
3020 * is not really needed once we start adding the stat specific PERF_RECORD_
3021 * records, but the need to suppress the kptr_restrict messages in older
3022 * tools remain -acme
3024 int fd = perf_data__fd(&perf_stat.data);
3025 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
3026 process_synthesized_event,
3027 &perf_stat.session->machines.host);
3029 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
3030 "older tools may produce warnings about this file\n.");
3034 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
3035 pr_err("failed to write stat round event\n");
3038 if (!perf_stat.data.is_pipe) {
3039 perf_stat.session->header.data_size += perf_stat.bytes_written;
3040 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
3043 perf_session__delete(perf_stat.session);
3046 perf_stat__exit_aggr_mode();
3047 perf_evlist__free_stats(evsel_list);
3051 if (smi_cost && smi_reset)
3052 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
3054 perf_evlist__delete(evsel_list);
3056 runtime_stat_delete(&stat_config);