OSDN Git Service

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