]> git.proxmox.com Git - mirror_ubuntu-focal-kernel.git/blame - tools/perf/builtin-stat.c
perf tools: Add front-end and back-end stalled cycles support
[mirror_ubuntu-focal-kernel.git] / tools / perf / builtin-stat.c
CommitLineData
ddcacfa0 1/*
bf9e1876
IM
2 * builtin-stat.c
3 *
4 * Builtin stat command: Give a precise performance counters summary
5 * overview about any workload, CPU or specific PID.
6 *
7 * Sample output:
ddcacfa0 8
bf9e1876
IM
9 $ perf stat ~/hackbench 10
10 Time: 0.104
ddcacfa0 11
bf9e1876 12 Performance counter stats for '/home/mingo/hackbench':
ddcacfa0 13
bf9e1876
IM
14 1255.538611 task clock ticks # 10.143 CPU utilization factor
15 54011 context switches # 0.043 M/sec
16 385 CPU migrations # 0.000 M/sec
17 17755 pagefaults # 0.014 M/sec
18 3808323185 CPU cycles # 3033.219 M/sec
19 1575111190 instructions # 1254.530 M/sec
20 17367895 cache references # 13.833 M/sec
21 7674421 cache misses # 6.112 M/sec
ddcacfa0 22
bf9e1876 23 Wall-clock time elapsed: 123.786620 msecs
ddcacfa0 24
5242519b
IM
25 *
26 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
27 *
28 * Improvements and fixes by:
29 *
30 * Arjan van de Ven <arjan@linux.intel.com>
31 * Yanmin Zhang <yanmin.zhang@intel.com>
32 * Wu Fengguang <fengguang.wu@intel.com>
33 * Mike Galbraith <efault@gmx.de>
34 * Paul Mackerras <paulus@samba.org>
6e750a8f 35 * Jaswinder Singh Rajput <jaswinder@kernel.org>
5242519b
IM
36 *
37 * Released under the GPL v2. (and only v2, not any later version)
ddcacfa0
IM
38 */
39
1a482f38 40#include "perf.h"
16f762a2 41#include "builtin.h"
148be2c1 42#include "util/util.h"
5242519b
IM
43#include "util/parse-options.h"
44#include "util/parse-events.h"
8f28827a 45#include "util/event.h"
361c99a6 46#include "util/evlist.h"
69aad6f1 47#include "util/evsel.h"
8f28827a 48#include "util/debug.h"
a5d243d0 49#include "util/color.h"
60666c63 50#include "util/header.h"
a12b51c4 51#include "util/cpumap.h"
d6d901c2 52#include "util/thread.h"
fd78260b 53#include "util/thread_map.h"
ddcacfa0 54
ddcacfa0 55#include <sys/prctl.h>
42202dd5 56#include <math.h>
5af52b51 57#include <locale.h>
16c8a109 58
d7470b6a
SE
59#define DEFAULT_SEPARATOR " "
60
cdd6c482 61static struct perf_event_attr default_attrs[] = {
ddcacfa0 62
56aab464
IM
63 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
64 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
65 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
66 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
f4dbfa8f 67
56aab464 68 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
129c04cb
IM
69 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
70 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
56aab464 71 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
56aab464
IM
72 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
73 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
f4dbfa8f 74
ddcacfa0 75};
5242519b 76
c6264def
IM
77/*
78 * Detailed stats:
79 */
80static struct perf_event_attr detailed_attrs[] = {
81
82 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
83 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
84 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
85 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
86
87 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
129c04cb
IM
88 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
89 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
c6264def
IM
90 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
91 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
92 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
93
94 { .type = PERF_TYPE_HW_CACHE,
95 .config =
96 PERF_COUNT_HW_CACHE_L1D << 0 |
97 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
98 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
99
100 { .type = PERF_TYPE_HW_CACHE,
101 .config =
102 PERF_COUNT_HW_CACHE_L1D << 0 |
103 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
104 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
105
106 { .type = PERF_TYPE_HW_CACHE,
107 .config =
108 PERF_COUNT_HW_CACHE_LL << 0 |
109 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
110 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
111
112 { .type = PERF_TYPE_HW_CACHE,
113 .config =
114 PERF_COUNT_HW_CACHE_LL << 0 |
115 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
116 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
117};
118
361c99a6
ACM
119struct perf_evlist *evsel_list;
120
c0555642 121static bool system_wide = false;
3d632595 122static int run_idx = 0;
ddcacfa0 123
3d632595 124static int run_count = 1;
2e6cdf99 125static bool no_inherit = false;
c0555642 126static bool scale = true;
f5b4a9c3 127static bool no_aggr = false;
933da83a 128static pid_t target_pid = -1;
d6d901c2 129static pid_t target_tid = -1;
933da83a 130static pid_t child_pid = -1;
c0555642 131static bool null_run = false;
c6264def 132static bool detailed_run = false;
f9cef0a9 133static bool sync_run = false;
201e0b06 134static bool big_num = true;
d7470b6a 135static int big_num_opt = -1;
c45c6ea2 136static const char *cpu_list;
d7470b6a
SE
137static const char *csv_sep = NULL;
138static bool csv_output = false;
5af52b51 139
60666c63
LW
140static volatile int done = 0;
141
506d4bc8
PZ
142struct stats
143{
8a02631a 144 double n, mean, M2;
506d4bc8 145};
42202dd5 146
69aad6f1
ACM
147struct perf_stat {
148 struct stats res_stats[3];
69aad6f1
ACM
149};
150
c52b12ed 151static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
69aad6f1 152{
c52b12ed 153 evsel->priv = zalloc(sizeof(struct perf_stat));
69aad6f1
ACM
154 return evsel->priv == NULL ? -ENOMEM : 0;
155}
156
157static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
158{
159 free(evsel->priv);
160 evsel->priv = NULL;
161}
162
9e9772c4
PZ
163static void update_stats(struct stats *stats, u64 val)
164{
8a02631a 165 double delta;
9e9772c4 166
8a02631a
PZ
167 stats->n++;
168 delta = val - stats->mean;
169 stats->mean += delta / stats->n;
170 stats->M2 += delta*(val - stats->mean);
9e9772c4
PZ
171}
172
506d4bc8
PZ
173static double avg_stats(struct stats *stats)
174{
8a02631a 175 return stats->mean;
506d4bc8 176}
42202dd5 177
506d4bc8 178/*
63d40deb
PZ
179 * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
180 *
8a02631a
PZ
181 * (\Sum n_i^2) - ((\Sum n_i)^2)/n
182 * s^2 = -------------------------------
183 * n - 1
63d40deb
PZ
184 *
185 * http://en.wikipedia.org/wiki/Stddev
186 *
187 * The std dev of the mean is related to the std dev by:
188 *
189 * s
190 * s_mean = -------
191 * sqrt(n)
192 *
506d4bc8
PZ
193 */
194static double stddev_stats(struct stats *stats)
195{
8a02631a
PZ
196 double variance = stats->M2 / (stats->n - 1);
197 double variance_mean = variance / stats->n;
42202dd5 198
63d40deb 199 return sqrt(variance_mean);
506d4bc8 200}
42202dd5 201
f5b4a9c3
SE
202struct stats runtime_nsecs_stats[MAX_NR_CPUS];
203struct stats runtime_cycles_stats[MAX_NR_CPUS];
481f988a 204struct stats runtime_stalled_cycles_stats[MAX_NR_CPUS];
f5b4a9c3 205struct stats runtime_branches_stats[MAX_NR_CPUS];
d58f4c82 206struct stats runtime_cacherefs_stats[MAX_NR_CPUS];
8bb6c79f 207struct stats runtime_l1_dcache_stats[MAX_NR_CPUS];
506d4bc8 208struct stats walltime_nsecs_stats;
be1ac0d8 209
48290609 210static int create_perf_stat_counter(struct perf_evsel *evsel)
ddcacfa0 211{
69aad6f1 212 struct perf_event_attr *attr = &evsel->attr;
16c8a109 213
ddcacfa0 214 if (scale)
a21ca2ca
IM
215 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
216 PERF_FORMAT_TOTAL_TIME_RUNNING;
ddcacfa0 217
5d2cd909
ACM
218 attr->inherit = !no_inherit;
219
48290609 220 if (system_wide)
5d2cd909 221 return perf_evsel__open_per_cpu(evsel, evsel_list->cpus, false);
48290609 222
48290609
ACM
223 if (target_pid == -1 && target_tid == -1) {
224 attr->disabled = 1;
225 attr->enable_on_exec = 1;
ddcacfa0 226 }
084ab9f8 227
5d2cd909 228 return perf_evsel__open_per_thread(evsel, evsel_list->threads, false);
ddcacfa0
IM
229}
230
c04f5e5d
IM
231/*
232 * Does the counter have nsecs as a unit?
233 */
daec78a0 234static inline int nsec_counter(struct perf_evsel *evsel)
c04f5e5d 235{
daec78a0
ACM
236 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
237 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
c04f5e5d
IM
238 return 1;
239
240 return 0;
241}
242
dcd9936a
IM
243/*
244 * Update various tracking values we maintain to print
245 * more semantic information such as miss/hit ratios,
246 * instruction rates, etc:
247 */
248static void update_shadow_stats(struct perf_evsel *counter, u64 *count)
249{
250 if (perf_evsel__match(counter, SOFTWARE, SW_TASK_CLOCK))
251 update_stats(&runtime_nsecs_stats[0], count[0]);
252 else if (perf_evsel__match(counter, HARDWARE, HW_CPU_CYCLES))
253 update_stats(&runtime_cycles_stats[0], count[0]);
129c04cb 254 else if (perf_evsel__match(counter, HARDWARE, HW_STALLED_CYCLES_BACKEND))
481f988a 255 update_stats(&runtime_stalled_cycles_stats[0], count[0]);
dcd9936a
IM
256 else if (perf_evsel__match(counter, HARDWARE, HW_BRANCH_INSTRUCTIONS))
257 update_stats(&runtime_branches_stats[0], count[0]);
258 else if (perf_evsel__match(counter, HARDWARE, HW_CACHE_REFERENCES))
259 update_stats(&runtime_cacherefs_stats[0], count[0]);
8bb6c79f
IM
260 else if (perf_evsel__match(counter, HW_CACHE, HW_CACHE_L1D))
261 update_stats(&runtime_l1_dcache_stats[0], count[0]);
dcd9936a
IM
262}
263
c04f5e5d 264/*
2996f5dd 265 * Read out the results of a single counter:
f5b4a9c3 266 * aggregate counts across CPUs in system-wide mode
c04f5e5d 267 */
c52b12ed 268static int read_counter_aggr(struct perf_evsel *counter)
c04f5e5d 269{
69aad6f1 270 struct perf_stat *ps = counter->priv;
c52b12ed
ACM
271 u64 *count = counter->counts->aggr.values;
272 int i;
2996f5dd 273
7e2ed097
ACM
274 if (__perf_evsel__read(counter, evsel_list->cpus->nr,
275 evsel_list->threads->nr, scale) < 0)
c52b12ed 276 return -1;
9e9772c4
PZ
277
278 for (i = 0; i < 3; i++)
69aad6f1 279 update_stats(&ps->res_stats[i], count[i]);
9e9772c4
PZ
280
281 if (verbose) {
9486aa38
ACM
282 fprintf(stderr, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
283 event_name(counter), count[0], count[1], count[2]);
9e9772c4
PZ
284 }
285
be1ac0d8
IM
286 /*
287 * Save the full runtime - to allow normalization during printout:
288 */
dcd9936a 289 update_shadow_stats(counter, count);
c52b12ed
ACM
290
291 return 0;
f5b4a9c3
SE
292}
293
294/*
295 * Read out the results of a single counter:
296 * do not aggregate counts across CPUs in system-wide mode
297 */
c52b12ed 298static int read_counter(struct perf_evsel *counter)
f5b4a9c3 299{
c52b12ed 300 u64 *count;
f5b4a9c3 301 int cpu;
f5b4a9c3 302
7e2ed097 303 for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
c52b12ed
ACM
304 if (__perf_evsel__read_on_cpu(counter, cpu, 0, scale) < 0)
305 return -1;
f5b4a9c3 306
c52b12ed 307 count = counter->counts->cpu[cpu].values;
f5b4a9c3 308
dcd9936a 309 update_shadow_stats(counter, count);
f5b4a9c3 310 }
c52b12ed
ACM
311
312 return 0;
2996f5dd
IM
313}
314
f37a291c 315static int run_perf_stat(int argc __used, const char **argv)
42202dd5
IM
316{
317 unsigned long long t0, t1;
69aad6f1 318 struct perf_evsel *counter;
42202dd5 319 int status = 0;
051ae7f7 320 int child_ready_pipe[2], go_pipe[2];
6be2850e 321 const bool forks = (argc > 0);
051ae7f7 322 char buf;
42202dd5 323
60666c63 324 if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
051ae7f7
PM
325 perror("failed to create pipes");
326 exit(1);
327 }
328
60666c63 329 if (forks) {
6be2850e 330 if ((child_pid = fork()) < 0)
60666c63
LW
331 perror("failed to fork");
332
6be2850e 333 if (!child_pid) {
60666c63
LW
334 close(child_ready_pipe[0]);
335 close(go_pipe[1]);
336 fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
337
338 /*
339 * Do a dummy execvp to get the PLT entry resolved,
340 * so we avoid the resolver overhead on the real
341 * execvp call.
342 */
343 execvp("", (char **)argv);
344
345 /*
346 * Tell the parent we're ready to go
347 */
348 close(child_ready_pipe[1]);
349
350 /*
351 * Wait until the parent tells us to go.
352 */
353 if (read(go_pipe[0], &buf, 1) == -1)
354 perror("unable to read pipe");
355
356 execvp(argv[0], (char **)argv);
357
358 perror(argv[0]);
359 exit(-1);
360 }
051ae7f7 361
d6d901c2 362 if (target_tid == -1 && target_pid == -1 && !system_wide)
7e2ed097 363 evsel_list->threads->map[0] = child_pid;
d6d901c2 364
051ae7f7 365 /*
60666c63 366 * Wait for the child to be ready to exec.
051ae7f7
PM
367 */
368 close(child_ready_pipe[1]);
60666c63
LW
369 close(go_pipe[0]);
370 if (read(child_ready_pipe[0], &buf, 1) == -1)
a92bef0f 371 perror("unable to read pipe");
60666c63 372 close(child_ready_pipe[0]);
051ae7f7
PM
373 }
374
361c99a6 375 list_for_each_entry(counter, &evsel_list->entries, node) {
48290609 376 if (create_perf_stat_counter(counter) < 0) {
ede70290
IM
377 if (errno == EINVAL || errno == ENOSYS)
378 continue;
379
380 if (errno == EPERM || errno == EACCES) {
48290609
ACM
381 error("You may not have permission to collect %sstats.\n"
382 "\t Consider tweaking"
383 " /proc/sys/kernel/perf_event_paranoid or running as root.",
384 system_wide ? "system-wide " : "");
5a3446bc
DA
385 } else if (errno == ENOENT) {
386 error("%s event is not supported. ", event_name(counter));
48290609
ACM
387 } else {
388 error("open_counter returned with %d (%s). "
389 "/bin/dmesg may provide additional information.\n",
390 errno, strerror(errno));
391 }
392 if (child_pid != -1)
393 kill(child_pid, SIGTERM);
394 die("Not all events could be opened.\n");
395 return -1;
396 }
084ab9f8 397 }
42202dd5 398
cfd748ae
FW
399 if (perf_evlist__set_filters(evsel_list)) {
400 error("failed to set filter with %d (%s)\n", errno,
401 strerror(errno));
402 return -1;
403 }
404
42202dd5
IM
405 /*
406 * Enable counters and exec the command:
407 */
408 t0 = rdclock();
42202dd5 409
60666c63
LW
410 if (forks) {
411 close(go_pipe[1]);
412 wait(&status);
413 } else {
6be2850e 414 while(!done) sleep(1);
60666c63 415 }
42202dd5 416
42202dd5
IM
417 t1 = rdclock();
418
9e9772c4 419 update_stats(&walltime_nsecs_stats, t1 - t0);
42202dd5 420
f5b4a9c3 421 if (no_aggr) {
361c99a6 422 list_for_each_entry(counter, &evsel_list->entries, node) {
f5b4a9c3 423 read_counter(counter);
7e2ed097 424 perf_evsel__close_fd(counter, evsel_list->cpus->nr, 1);
c52b12ed 425 }
f5b4a9c3 426 } else {
361c99a6 427 list_for_each_entry(counter, &evsel_list->entries, node) {
f5b4a9c3 428 read_counter_aggr(counter);
7e2ed097
ACM
429 perf_evsel__close_fd(counter, evsel_list->cpus->nr,
430 evsel_list->threads->nr);
c52b12ed 431 }
f5b4a9c3 432 }
c52b12ed 433
42202dd5
IM
434 return WEXITSTATUS(status);
435}
436
f99844cb
IM
437static void print_noise_pct(double total, double avg)
438{
439 double pct = 0.0;
440
441 if (avg)
442 pct = 100.0*total/avg;
443
444 fprintf(stderr, " ( +-%6.2f%% )", pct);
445}
446
69aad6f1 447static void print_noise(struct perf_evsel *evsel, double avg)
42202dd5 448{
69aad6f1
ACM
449 struct perf_stat *ps;
450
849abde9
PZ
451 if (run_count == 1)
452 return;
453
69aad6f1 454 ps = evsel->priv;
f99844cb 455 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
42202dd5
IM
456}
457
daec78a0 458static void nsec_printout(int cpu, struct perf_evsel *evsel, double avg)
44175b6f 459{
506d4bc8 460 double msecs = avg / 1e6;
d7470b6a
SE
461 char cpustr[16] = { '\0', };
462 const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
44175b6f 463
f5b4a9c3 464 if (no_aggr)
d7470b6a
SE
465 sprintf(cpustr, "CPU%*d%s",
466 csv_output ? 0 : -4,
7e2ed097 467 evsel_list->cpus->map[cpu], csv_sep);
d7470b6a 468
daec78a0 469 fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(evsel));
d7470b6a 470
023695d9
SE
471 if (evsel->cgrp)
472 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
473
d7470b6a
SE
474 if (csv_output)
475 return;
44175b6f 476
daec78a0 477 if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
481f988a 478 fprintf(stderr, " # %8.3f CPUs utilized ", avg / avg_stats(&walltime_nsecs_stats));
44175b6f
IM
479}
480
a5d243d0
IM
481static void print_stalled_cycles(int cpu, struct perf_evsel *evsel __used, double avg)
482{
483 double total, ratio = 0.0;
484 const char *color;
485
486 total = avg_stats(&runtime_cycles_stats[cpu]);
487
488 if (total)
489 ratio = avg / total * 100.0;
490
491 color = PERF_COLOR_NORMAL;
492 if (ratio > 75.0)
493 color = PERF_COLOR_RED;
494 else if (ratio > 50.0)
495 color = PERF_COLOR_MAGENTA;
496 else if (ratio > 25.0)
497 color = PERF_COLOR_YELLOW;
498
499 fprintf(stderr, " # ");
500 color_fprintf(stderr, color, "%5.2f%%", ratio);
501 fprintf(stderr, " of all cycles are idle ");
502}
503
c78df6c1
IM
504static void print_branch_misses(int cpu, struct perf_evsel *evsel __used, double avg)
505{
506 double total, ratio = 0.0;
507 const char *color;
508
509 total = avg_stats(&runtime_branches_stats[cpu]);
510
511 if (total)
512 ratio = avg / total * 100.0;
513
514 color = PERF_COLOR_NORMAL;
515 if (ratio > 20.0)
516 color = PERF_COLOR_RED;
517 else if (ratio > 10.0)
518 color = PERF_COLOR_MAGENTA;
519 else if (ratio > 5.0)
520 color = PERF_COLOR_YELLOW;
521
522 fprintf(stderr, " # ");
523 color_fprintf(stderr, color, "%5.2f%%", ratio);
524 fprintf(stderr, " of all branches ");
525}
526
8bb6c79f
IM
527static void print_l1_dcache_misses(int cpu, struct perf_evsel *evsel __used, double avg)
528{
529 double total, ratio = 0.0;
530 const char *color;
531
532 total = avg_stats(&runtime_l1_dcache_stats[cpu]);
533
534 if (total)
535 ratio = avg / total * 100.0;
536
537 color = PERF_COLOR_NORMAL;
538 if (ratio > 20.0)
539 color = PERF_COLOR_RED;
540 else if (ratio > 10.0)
541 color = PERF_COLOR_MAGENTA;
542 else if (ratio > 5.0)
543 color = PERF_COLOR_YELLOW;
544
545 fprintf(stderr, " # ");
546 color_fprintf(stderr, color, "%5.2f%%", ratio);
547 fprintf(stderr, " of all L1-dcache hits ");
548}
549
daec78a0 550static void abs_printout(int cpu, struct perf_evsel *evsel, double avg)
44175b6f 551{
c7f7fea3 552 double total, ratio = 0.0;
f5b4a9c3 553 char cpustr[16] = { '\0', };
d7470b6a
SE
554 const char *fmt;
555
556 if (csv_output)
557 fmt = "%s%.0f%s%s";
558 else if (big_num)
559 fmt = "%s%'18.0f%s%-24s";
560 else
561 fmt = "%s%18.0f%s%-24s";
f5b4a9c3
SE
562
563 if (no_aggr)
d7470b6a
SE
564 sprintf(cpustr, "CPU%*d%s",
565 csv_output ? 0 : -4,
7e2ed097 566 evsel_list->cpus->map[cpu], csv_sep);
f5b4a9c3
SE
567 else
568 cpu = 0;
c7f7fea3 569
daec78a0 570 fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(evsel));
d7470b6a 571
023695d9
SE
572 if (evsel->cgrp)
573 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
574
d7470b6a
SE
575 if (csv_output)
576 return;
44175b6f 577
daec78a0 578 if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
f5b4a9c3 579 total = avg_stats(&runtime_cycles_stats[cpu]);
c7f7fea3
IM
580
581 if (total)
582 ratio = avg / total;
583
9ceb1c3d 584 fprintf(stderr, " # %4.2f insns per cycle ", ratio);
481f988a
IM
585
586 total = avg_stats(&runtime_stalled_cycles_stats[cpu]);
587
588 if (total && avg) {
589 ratio = total / avg;
590 fprintf(stderr, "\n # %4.2f stalled cycles per insn", ratio);
591 }
592
daec78a0 593 } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
f5b4a9c3 594 runtime_branches_stats[cpu].n != 0) {
c78df6c1 595 print_branch_misses(cpu, evsel, avg);
8bb6c79f
IM
596 } else if (
597 evsel->attr.type == PERF_TYPE_HW_CACHE &&
598 evsel->attr.config == ( PERF_COUNT_HW_CACHE_L1D |
599 ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
600 ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
c6264def 601 runtime_l1_dcache_stats[cpu].n != 0) {
8bb6c79f 602 print_l1_dcache_misses(cpu, evsel, avg);
d58f4c82
IM
603 } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
604 runtime_cacherefs_stats[cpu].n != 0) {
605 total = avg_stats(&runtime_cacherefs_stats[cpu]);
606
607 if (total)
608 ratio = avg * 100 / total;
609
481f988a 610 fprintf(stderr, " # %8.3f %% of all cache refs ", ratio);
d58f4c82 611
129c04cb 612 } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES_BACKEND)) {
a5d243d0 613 print_stalled_cycles(cpu, evsel, avg);
481f988a 614 } else if (perf_evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
f5b4a9c3 615 total = avg_stats(&runtime_nsecs_stats[cpu]);
c7f7fea3
IM
616
617 if (total)
481f988a 618 ratio = 1.0 * avg / total;
c7f7fea3 619
481f988a
IM
620 fprintf(stderr, " # %8.3f GHz ", ratio);
621 } else if (runtime_nsecs_stats[cpu].n != 0) {
622 total = avg_stats(&runtime_nsecs_stats[cpu]);
11ba2b85
IM
623
624 if (total)
481f988a 625 ratio = 1000.0 * avg / total;
11ba2b85 626
481f988a 627 fprintf(stderr, " # %8.3f M/sec ", ratio);
a5d243d0
IM
628 } else {
629 fprintf(stderr, " ");
44175b6f 630 }
44175b6f
IM
631}
632
2996f5dd
IM
633/*
634 * Print out the results of a single counter:
f5b4a9c3 635 * aggregated counts in system-wide mode
2996f5dd 636 */
69aad6f1 637static void print_counter_aggr(struct perf_evsel *counter)
2996f5dd 638{
69aad6f1
ACM
639 struct perf_stat *ps = counter->priv;
640 double avg = avg_stats(&ps->res_stats[0]);
c52b12ed 641 int scaled = counter->counts->scaled;
2996f5dd 642
2996f5dd 643 if (scaled == -1) {
023695d9 644 fprintf(stderr, "%*s%s%*s",
d7470b6a 645 csv_output ? 0 : 18,
023695d9
SE
646 "<not counted>",
647 csv_sep,
648 csv_output ? 0 : -24,
649 event_name(counter));
650
651 if (counter->cgrp)
652 fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
653
654 fputc('\n', stderr);
2996f5dd
IM
655 return;
656 }
c04f5e5d 657
44175b6f 658 if (nsec_counter(counter))
f5b4a9c3 659 nsec_printout(-1, counter, avg);
44175b6f 660 else
f5b4a9c3 661 abs_printout(-1, counter, avg);
849abde9 662
d7470b6a
SE
663 if (csv_output) {
664 fputc('\n', stderr);
665 return;
666 }
667
849abde9 668 print_noise(counter, avg);
506d4bc8
PZ
669
670 if (scaled) {
671 double avg_enabled, avg_running;
672
69aad6f1
ACM
673 avg_enabled = avg_stats(&ps->res_stats[1]);
674 avg_running = avg_stats(&ps->res_stats[2]);
d7c29318 675
c6264def 676 fprintf(stderr, " (%.2f%%)", 100 * avg_running / avg_enabled);
506d4bc8 677 }
c04f5e5d
IM
678 fprintf(stderr, "\n");
679}
680
f5b4a9c3
SE
681/*
682 * Print out the results of a single counter:
683 * does not use aggregated count in system-wide
684 */
69aad6f1 685static void print_counter(struct perf_evsel *counter)
f5b4a9c3
SE
686{
687 u64 ena, run, val;
688 int cpu;
689
7e2ed097 690 for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
c52b12ed
ACM
691 val = counter->counts->cpu[cpu].val;
692 ena = counter->counts->cpu[cpu].ena;
693 run = counter->counts->cpu[cpu].run;
f5b4a9c3 694 if (run == 0 || ena == 0) {
023695d9 695 fprintf(stderr, "CPU%*d%s%*s%s%*s",
d7470b6a 696 csv_output ? 0 : -4,
7e2ed097 697 evsel_list->cpus->map[cpu], csv_sep,
d7470b6a
SE
698 csv_output ? 0 : 18,
699 "<not counted>", csv_sep,
023695d9 700 csv_output ? 0 : -24,
d7470b6a 701 event_name(counter));
f5b4a9c3 702
023695d9
SE
703 if (counter->cgrp)
704 fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
705
706 fputc('\n', stderr);
f5b4a9c3
SE
707 continue;
708 }
709
710 if (nsec_counter(counter))
711 nsec_printout(cpu, counter, val);
712 else
713 abs_printout(cpu, counter, val);
714
d7470b6a
SE
715 if (!csv_output) {
716 print_noise(counter, 1.0);
f5b4a9c3 717
c6264def
IM
718 if (run != ena)
719 fprintf(stderr, " (%.2f%%)", 100.0 * run / ena);
f5b4a9c3 720 }
023695d9 721 fputc('\n', stderr);
f5b4a9c3
SE
722 }
723}
724
42202dd5
IM
725static void print_stat(int argc, const char **argv)
726{
69aad6f1
ACM
727 struct perf_evsel *counter;
728 int i;
42202dd5 729
ddcacfa0
IM
730 fflush(stdout);
731
d7470b6a
SE
732 if (!csv_output) {
733 fprintf(stderr, "\n");
734 fprintf(stderr, " Performance counter stats for ");
735 if(target_pid == -1 && target_tid == -1) {
736 fprintf(stderr, "\'%s", argv[0]);
737 for (i = 1; i < argc; i++)
738 fprintf(stderr, " %s", argv[i]);
739 } else if (target_pid != -1)
740 fprintf(stderr, "process id \'%d", target_pid);
741 else
742 fprintf(stderr, "thread id \'%d", target_tid);
44db76c8 743
d7470b6a
SE
744 fprintf(stderr, "\'");
745 if (run_count > 1)
746 fprintf(stderr, " (%d runs)", run_count);
747 fprintf(stderr, ":\n\n");
748 }
2996f5dd 749
f5b4a9c3 750 if (no_aggr) {
361c99a6 751 list_for_each_entry(counter, &evsel_list->entries, node)
f5b4a9c3
SE
752 print_counter(counter);
753 } else {
361c99a6 754 list_for_each_entry(counter, &evsel_list->entries, node)
f5b4a9c3
SE
755 print_counter_aggr(counter);
756 }
ddcacfa0 757
d7470b6a
SE
758 if (!csv_output) {
759 fprintf(stderr, "\n");
760 fprintf(stderr, " %18.9f seconds time elapsed",
761 avg_stats(&walltime_nsecs_stats)/1e9);
762 if (run_count > 1) {
f99844cb
IM
763 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
764 avg_stats(&walltime_nsecs_stats));
d7470b6a
SE
765 }
766 fprintf(stderr, "\n\n");
566747e6 767 }
ddcacfa0
IM
768}
769
f7b7c26e
PZ
770static volatile int signr = -1;
771
5242519b 772static void skip_signal(int signo)
ddcacfa0 773{
6be2850e 774 if(child_pid == -1)
60666c63
LW
775 done = 1;
776
f7b7c26e
PZ
777 signr = signo;
778}
779
780static void sig_atexit(void)
781{
933da83a
CW
782 if (child_pid != -1)
783 kill(child_pid, SIGTERM);
784
f7b7c26e
PZ
785 if (signr == -1)
786 return;
787
788 signal(signr, SIG_DFL);
789 kill(getpid(), signr);
5242519b
IM
790}
791
792static const char * const stat_usage[] = {
60666c63 793 "perf stat [<options>] [<command>]",
5242519b
IM
794 NULL
795};
796
d7470b6a
SE
797static int stat__set_big_num(const struct option *opt __used,
798 const char *s __used, int unset)
799{
800 big_num_opt = unset ? 0 : 1;
801 return 0;
802}
803
5242519b 804static const struct option options[] = {
361c99a6 805 OPT_CALLBACK('e', "event", &evsel_list, "event",
86847b62
TG
806 "event selector. use 'perf list' to list available events",
807 parse_events),
cfd748ae
FW
808 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
809 "event filter", parse_filter),
2e6cdf99
SE
810 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
811 "child tasks do not inherit counters"),
5242519b 812 OPT_INTEGER('p', "pid", &target_pid,
d6d901c2
ZY
813 "stat events on existing process id"),
814 OPT_INTEGER('t', "tid", &target_tid,
815 "stat events on existing thread id"),
5242519b 816 OPT_BOOLEAN('a', "all-cpus", &system_wide,
3d632595 817 "system-wide collection from all CPUs"),
b26bc5a7 818 OPT_BOOLEAN('c', "scale", &scale,
3d632595 819 "scale/normalize counters"),
c0555642 820 OPT_INCR('v', "verbose", &verbose,
743ee1f8 821 "be more verbose (show counter open errors, etc)"),
42202dd5
IM
822 OPT_INTEGER('r', "repeat", &run_count,
823 "repeat command and print average + stddev (max: 100)"),
0cfb7a13
IM
824 OPT_BOOLEAN('n', "null", &null_run,
825 "null run - dont start any counters"),
c6264def
IM
826 OPT_BOOLEAN('d', "detailed", &detailed_run,
827 "detailed run - start a lot of events"),
f9cef0a9
IM
828 OPT_BOOLEAN('S', "sync", &sync_run,
829 "call sync() before starting a run"),
d7470b6a
SE
830 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
831 "print large numbers with thousands\' separators",
832 stat__set_big_num),
c45c6ea2
SE
833 OPT_STRING('C', "cpu", &cpu_list, "cpu",
834 "list of cpus to monitor in system-wide"),
f5b4a9c3
SE
835 OPT_BOOLEAN('A', "no-aggr", &no_aggr,
836 "disable CPU count aggregation"),
d7470b6a
SE
837 OPT_STRING('x', "field-separator", &csv_sep, "separator",
838 "print counts with custom separator"),
023695d9
SE
839 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
840 "monitor event in cgroup name only",
841 parse_cgroups),
5242519b
IM
842 OPT_END()
843};
844
f37a291c 845int cmd_stat(int argc, const char **argv, const char *prefix __used)
5242519b 846{
69aad6f1
ACM
847 struct perf_evsel *pos;
848 int status = -ENOMEM;
42202dd5 849
5af52b51
SE
850 setlocale(LC_ALL, "");
851
7e2ed097 852 evsel_list = perf_evlist__new(NULL, NULL);
361c99a6
ACM
853 if (evsel_list == NULL)
854 return -ENOMEM;
855
a0541234
AB
856 argc = parse_options(argc, argv, options, stat_usage,
857 PARSE_OPT_STOP_AT_NON_OPTION);
d7470b6a
SE
858
859 if (csv_sep)
860 csv_output = true;
861 else
862 csv_sep = DEFAULT_SEPARATOR;
863
864 /*
865 * let the spreadsheet do the pretty-printing
866 */
867 if (csv_output) {
868 /* User explicitely passed -B? */
869 if (big_num_opt == 1) {
870 fprintf(stderr, "-B option not supported with -x\n");
871 usage_with_options(stat_usage, options);
872 } else /* Nope, so disable big number formatting */
873 big_num = false;
874 } else if (big_num_opt == 0) /* User passed --no-big-num */
875 big_num = false;
876
d6d901c2 877 if (!argc && target_pid == -1 && target_tid == -1)
5242519b 878 usage_with_options(stat_usage, options);
9e9772c4 879 if (run_count <= 0)
42202dd5 880 usage_with_options(stat_usage, options);
ddcacfa0 881
023695d9
SE
882 /* no_aggr, cgroup are for system-wide only */
883 if ((no_aggr || nr_cgroups) && !system_wide) {
884 fprintf(stderr, "both cgroup and no-aggregation "
885 "modes only available in system-wide mode\n");
886
f5b4a9c3 887 usage_with_options(stat_usage, options);
023695d9 888 }
f5b4a9c3 889
c3043569 890 /* Set attrs and nr_counters if no event is selected and !null_run */
c6264def
IM
891 if (detailed_run) {
892 size_t c;
893
894 for (c = 0; c < ARRAY_SIZE(detailed_attrs); ++c) {
895 pos = perf_evsel__new(&detailed_attrs[c], c);
896 if (pos == NULL)
897 goto out;
898 perf_evlist__add(evsel_list, pos);
899 }
900 }
901 /* Set attrs and nr_counters if no event is selected and !null_run */
902 if (!detailed_run && !null_run && !evsel_list->nr_entries) {
69aad6f1
ACM
903 size_t c;
904
69aad6f1 905 for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
361c99a6 906 pos = perf_evsel__new(&default_attrs[c], c);
69aad6f1
ACM
907 if (pos == NULL)
908 goto out;
361c99a6 909 perf_evlist__add(evsel_list, pos);
69aad6f1 910 }
c3043569 911 }
ddcacfa0 912
5c98d466
ACM
913 if (target_pid != -1)
914 target_tid = target_pid;
915
7e2ed097
ACM
916 evsel_list->threads = thread_map__new(target_pid, target_tid);
917 if (evsel_list->threads == NULL) {
5c98d466
ACM
918 pr_err("Problems finding threads of monitor\n");
919 usage_with_options(stat_usage, options);
920 }
921
a12b51c4 922 if (system_wide)
7e2ed097 923 evsel_list->cpus = cpu_map__new(cpu_list);
a12b51c4 924 else
7e2ed097 925 evsel_list->cpus = cpu_map__dummy_new();
ddcacfa0 926
7e2ed097 927 if (evsel_list->cpus == NULL) {
60d567e2 928 perror("failed to parse CPUs map");
c45c6ea2 929 usage_with_options(stat_usage, options);
60d567e2
ACM
930 return -1;
931 }
c45c6ea2 932
361c99a6 933 list_for_each_entry(pos, &evsel_list->entries, node) {
c52b12ed 934 if (perf_evsel__alloc_stat_priv(pos) < 0 ||
7e2ed097
ACM
935 perf_evsel__alloc_counts(pos, evsel_list->cpus->nr) < 0 ||
936 perf_evsel__alloc_fd(pos, evsel_list->cpus->nr, evsel_list->threads->nr) < 0)
69aad6f1 937 goto out_free_fd;
d6d901c2
ZY
938 }
939
58d7e993
IM
940 /*
941 * We dont want to block the signals - that would cause
942 * child tasks to inherit that and Ctrl-C would not work.
943 * What we want is for Ctrl-C to work in the exec()-ed
944 * task, but being ignored by perf stat itself:
945 */
f7b7c26e 946 atexit(sig_atexit);
58d7e993
IM
947 signal(SIGINT, skip_signal);
948 signal(SIGALRM, skip_signal);
949 signal(SIGABRT, skip_signal);
950
42202dd5
IM
951 status = 0;
952 for (run_idx = 0; run_idx < run_count; run_idx++) {
953 if (run_count != 1 && verbose)
3d632595 954 fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
f9cef0a9
IM
955
956 if (sync_run)
957 sync();
958
42202dd5
IM
959 status = run_perf_stat(argc, argv);
960 }
961
084ab9f8
ACM
962 if (status != -1)
963 print_stat(argc, argv);
69aad6f1 964out_free_fd:
361c99a6 965 list_for_each_entry(pos, &evsel_list->entries, node)
69aad6f1 966 perf_evsel__free_stat_priv(pos);
7e2ed097 967 perf_evlist__delete_maps(evsel_list);
0015e2e1
ACM
968out:
969 perf_evlist__delete(evsel_list);
42202dd5 970 return status;
ddcacfa0 971}