perf stat: Add support for metrics in interval mode
[deliverable/linux.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
2cba3ffb 9 $ perf stat ./hackbench 10
ddcacfa0 10
2cba3ffb 11 Time: 0.118
ddcacfa0 12
2cba3ffb 13 Performance counter stats for './hackbench 10':
ddcacfa0 14
2cba3ffb
IM
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
26
27 0.154822978 seconds time elapsed
ddcacfa0 28
5242519b 29 *
2cba3ffb 30 * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
5242519b
IM
31 *
32 * Improvements and fixes by:
33 *
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>
6e750a8f 39 * Jaswinder Singh Rajput <jaswinder@kernel.org>
5242519b
IM
40 *
41 * Released under the GPL v2. (and only v2, not any later version)
ddcacfa0
IM
42 */
43
1a482f38 44#include "perf.h"
16f762a2 45#include "builtin.h"
f14d5707 46#include "util/cgroup.h"
148be2c1 47#include "util/util.h"
4b6ab94e 48#include <subcmd/parse-options.h>
5242519b 49#include "util/parse-events.h"
4cabc3d1 50#include "util/pmu.h"
8f28827a 51#include "util/event.h"
361c99a6 52#include "util/evlist.h"
69aad6f1 53#include "util/evsel.h"
8f28827a 54#include "util/debug.h"
a5d243d0 55#include "util/color.h"
0007ecea 56#include "util/stat.h"
60666c63 57#include "util/header.h"
a12b51c4 58#include "util/cpumap.h"
d6d901c2 59#include "util/thread.h"
fd78260b 60#include "util/thread_map.h"
d809560b 61#include "util/counts.h"
4979d0c7 62#include "util/session.h"
ba6039b6
JO
63#include "util/tool.h"
64#include "asm/bug.h"
ddcacfa0 65
1f16c575 66#include <stdlib.h>
ddcacfa0 67#include <sys/prctl.h>
5af52b51 68#include <locale.h>
16c8a109 69
d7470b6a 70#define DEFAULT_SEPARATOR " "
2cee77c4
DA
71#define CNTR_NOT_SUPPORTED "<not supported>"
72#define CNTR_NOT_COUNTED "<not counted>"
d7470b6a 73
d4f63a47 74static void print_counters(struct timespec *ts, int argc, const char **argv);
13370a9b 75
4cabc3d1 76/* Default events used for perf stat -T */
a454742c
JO
77static const char *transaction_attrs = {
78 "task-clock,"
4cabc3d1
AK
79 "{"
80 "instructions,"
81 "cycles,"
82 "cpu/cycles-t/,"
83 "cpu/tx-start/,"
84 "cpu/el-start/,"
85 "cpu/cycles-ct/"
86 "}"
87};
88
89/* More limited version when the CPU does not have all events. */
a454742c
JO
90static const char * transaction_limited_attrs = {
91 "task-clock,"
4cabc3d1
AK
92 "{"
93 "instructions,"
94 "cycles,"
95 "cpu/cycles-t/,"
96 "cpu/tx-start/"
97 "}"
98};
99
666e6d48 100static struct perf_evlist *evsel_list;
361c99a6 101
602ad878 102static struct target target = {
77a6f014
NK
103 .uid = UINT_MAX,
104};
ddcacfa0 105
1e5a2931
JO
106typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
107
3d632595 108static int run_count = 1;
2e6cdf99 109static bool no_inherit = false;
d07f0b12 110static volatile pid_t child_pid = -1;
c0555642 111static bool null_run = false;
2cba3ffb 112static int detailed_run = 0;
4cabc3d1 113static bool transaction_run;
201e0b06 114static bool big_num = true;
d7470b6a 115static int big_num_opt = -1;
d7470b6a
SE
116static const char *csv_sep = NULL;
117static bool csv_output = false;
43bece79 118static bool group = false;
1f16c575
PZ
119static const char *pre_cmd = NULL;
120static const char *post_cmd = NULL;
121static bool sync_run = false;
41191688 122static unsigned int initial_delay = 0;
410136f5 123static unsigned int unit_width = 4; /* strlen("unit") */
a7e191c3 124static bool forever = false;
13370a9b 125static struct timespec ref_time;
86ee6e18 126static struct cpu_map *aggr_map;
1e5a2931 127static aggr_get_id_t aggr_get_id;
e0547311
JO
128static bool append_file;
129static const char *output_name;
130static int output_fd;
5af52b51 131
4979d0c7
JO
132struct perf_stat {
133 bool record;
134 struct perf_data_file file;
135 struct perf_session *session;
136 u64 bytes_written;
ba6039b6 137 struct perf_tool tool;
1975d36e
JO
138 bool maps_allocated;
139 struct cpu_map *cpus;
140 struct thread_map *threads;
89af4e05 141 enum aggr_mode aggr_mode;
4979d0c7
JO
142};
143
144static struct perf_stat perf_stat;
145#define STAT_RECORD perf_stat.record
146
60666c63
LW
147static volatile int done = 0;
148
421a50f3
JO
149static struct perf_stat_config stat_config = {
150 .aggr_mode = AGGR_GLOBAL,
711a572e 151 .scale = true,
421a50f3
JO
152};
153
13370a9b
SE
154static inline void diff_timespec(struct timespec *r, struct timespec *a,
155 struct timespec *b)
156{
157 r->tv_sec = a->tv_sec - b->tv_sec;
158 if (a->tv_nsec < b->tv_nsec) {
159 r->tv_nsec = a->tv_nsec + 1000000000L - b->tv_nsec;
160 r->tv_sec--;
161 } else {
162 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
163 }
164}
165
254ecbc7
JO
166static void perf_stat__reset_stats(void)
167{
168 perf_evlist__reset_stats(evsel_list);
f87027b9 169 perf_stat__reset_shadow_stats();
1eda3b21
JO
170}
171
cac21425 172static int create_perf_stat_counter(struct perf_evsel *evsel)
ddcacfa0 173{
69aad6f1 174 struct perf_event_attr *attr = &evsel->attr;
727ab04e 175
711a572e 176 if (stat_config.scale)
a21ca2ca
IM
177 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
178 PERF_FORMAT_TOTAL_TIME_RUNNING;
ddcacfa0 179
5d2cd909
ACM
180 attr->inherit = !no_inherit;
181
6acd8e92
JO
182 /*
183 * Some events get initialized with sample_(period/type) set,
184 * like tracepoints. Clear it up for counting.
185 */
186 attr->sample_period = 0;
6db1a5c1 187
4979d0c7
JO
188 /*
189 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
190 * while avoiding that older tools show confusing messages.
6db1a5c1
JO
191 *
192 * However for pipe sessions we need to keep it zero,
193 * because script's perf_evsel__check_attr is triggered
194 * by attr->sample_type != 0, and we can't run it on
195 * stat sessions.
4979d0c7 196 */
6db1a5c1
JO
197 if (!(STAT_RECORD && perf_stat.file.is_pipe))
198 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
6acd8e92 199
67ccdecd
JO
200 /*
201 * Disabling all counters initially, they will be enabled
202 * either manually by us or by kernel via enable_on_exec
203 * set later.
204 */
c8280cec 205 if (perf_evsel__is_group_leader(evsel)) {
67ccdecd
JO
206 attr->disabled = 1;
207
c8280cec
JO
208 /*
209 * In case of initial_delay we enable tracee
210 * events manually.
211 */
212 if (target__none(&target) && !initial_delay)
41191688 213 attr->enable_on_exec = 1;
ddcacfa0 214 }
084ab9f8 215
c8280cec
JO
216 if (target__has_cpu(&target))
217 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
218
594ac61a 219 return perf_evsel__open_per_thread(evsel, evsel_list->threads);
ddcacfa0
IM
220}
221
c04f5e5d
IM
222/*
223 * Does the counter have nsecs as a unit?
224 */
daec78a0 225static inline int nsec_counter(struct perf_evsel *evsel)
c04f5e5d 226{
daec78a0
ACM
227 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
228 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
c04f5e5d
IM
229 return 1;
230
231 return 0;
232}
233
8b99b1a4
JO
234static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
235 union perf_event *event,
236 struct perf_sample *sample __maybe_unused,
237 struct machine *machine __maybe_unused)
4979d0c7 238{
8b99b1a4 239 if (perf_data_file__write(&perf_stat.file, event, event->header.size) < 0) {
4979d0c7
JO
240 pr_err("failed to write perf data, error: %m\n");
241 return -1;
242 }
243
8b99b1a4 244 perf_stat.bytes_written += event->header.size;
4979d0c7
JO
245 return 0;
246}
247
1975d36e 248static int write_stat_round_event(u64 tm, u64 type)
7aad0c32 249{
1975d36e 250 return perf_event__synthesize_stat_round(NULL, tm, type,
7aad0c32
JO
251 process_synthesized_event,
252 NULL);
253}
254
255#define WRITE_STAT_ROUND_EVENT(time, interval) \
256 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
257
5a6ea81b
JO
258#define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
259
260static int
261perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
262 struct perf_counts_values *count)
263{
264 struct perf_sample_id *sid = SID(counter, cpu, thread);
265
266 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
267 process_synthesized_event, NULL);
268}
269
f5b4a9c3
SE
270/*
271 * Read out the results of a single counter:
272 * do not aggregate counts across CPUs in system-wide mode
273 */
c52b12ed 274static int read_counter(struct perf_evsel *counter)
f5b4a9c3 275{
9bf1a529
JO
276 int nthreads = thread_map__nr(evsel_list->threads);
277 int ncpus = perf_evsel__nr_cpus(counter);
278 int cpu, thread;
f5b4a9c3 279
3b4331d9
SP
280 if (!counter->supported)
281 return -ENOENT;
282
9bf1a529
JO
283 if (counter->system_wide)
284 nthreads = 1;
285
286 for (thread = 0; thread < nthreads; thread++) {
287 for (cpu = 0; cpu < ncpus; cpu++) {
3b3eb044
JO
288 struct perf_counts_values *count;
289
290 count = perf_counts(counter->counts, cpu, thread);
291 if (perf_evsel__read(counter, cpu, thread, count))
9bf1a529 292 return -1;
5a6ea81b
JO
293
294 if (STAT_RECORD) {
295 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
296 pr_err("failed to write stat event\n");
297 return -1;
298 }
299 }
9bf1a529 300 }
f5b4a9c3 301 }
c52b12ed
ACM
302
303 return 0;
2996f5dd
IM
304}
305
5fc472a6 306static void read_counters(bool close_counters)
13370a9b 307{
13370a9b 308 struct perf_evsel *counter;
13370a9b 309
106a94a0 310 evlist__for_each(evsel_list, counter) {
3b3eb044 311 if (read_counter(counter))
245bad8e 312 pr_debug("failed to read counter %s\n", counter->name);
3b3eb044 313
f80010eb 314 if (perf_stat_process_counter(&stat_config, counter))
3b3eb044 315 pr_warning("failed to process counter %s\n", counter->name);
106a94a0 316
5fc472a6 317 if (close_counters) {
106a94a0
JO
318 perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter),
319 thread_map__nr(evsel_list->threads));
13370a9b
SE
320 }
321 }
106a94a0
JO
322}
323
ba411a95 324static void process_interval(void)
106a94a0 325{
106a94a0 326 struct timespec ts, rs;
106a94a0
JO
327
328 read_counters(false);
86ee6e18 329
13370a9b
SE
330 clock_gettime(CLOCK_MONOTONIC, &ts);
331 diff_timespec(&rs, &ts, &ref_time);
13370a9b 332
7aad0c32
JO
333 if (STAT_RECORD) {
334 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSECS_PER_SEC + rs.tv_nsec, INTERVAL))
335 pr_err("failed to write stat round event\n");
336 }
337
d4f63a47 338 print_counters(&rs, 0, NULL);
13370a9b
SE
339}
340
67ccdecd 341static void enable_counters(void)
41191688 342{
67ccdecd 343 if (initial_delay)
41191688 344 usleep(initial_delay * 1000);
67ccdecd
JO
345
346 /*
347 * We need to enable counters only if:
348 * - we don't have tracee (attaching to task or cpu)
349 * - we have initial delay configured
350 */
351 if (!target__none(&target) || initial_delay)
ab46db0a 352 perf_evlist__enable(evsel_list);
41191688
AK
353}
354
f33cbe72 355static volatile int workload_exec_errno;
6af206fd
ACM
356
357/*
358 * perf_evlist__prepare_workload will send a SIGUSR1
359 * if the fork fails, since we asked by setting its
360 * want_signal to true.
361 */
f33cbe72
ACM
362static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
363 void *ucontext __maybe_unused)
6af206fd 364{
f33cbe72 365 workload_exec_errno = info->si_value.sival_int;
6af206fd
ACM
366}
367
7b60a7e3
JO
368static bool has_unit(struct perf_evsel *counter)
369{
370 return counter->unit && *counter->unit;
371}
372
373static bool has_scale(struct perf_evsel *counter)
374{
375 return counter->scale != 1;
376}
377
664c98d4 378static int perf_stat_synthesize_config(bool is_pipe)
8b99b1a4 379{
7b60a7e3 380 struct perf_evsel *counter;
8b99b1a4
JO
381 int err;
382
664c98d4
JO
383 if (is_pipe) {
384 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
385 process_synthesized_event);
386 if (err < 0) {
387 pr_err("Couldn't synthesize attrs.\n");
388 return err;
389 }
390 }
391
7b60a7e3
JO
392 /*
393 * Synthesize other events stuff not carried within
394 * attr event - unit, scale, name
395 */
396 evlist__for_each(evsel_list, counter) {
397 if (!counter->supported)
398 continue;
399
400 /*
401 * Synthesize unit and scale only if it's defined.
402 */
403 if (has_unit(counter)) {
404 err = perf_event__synthesize_event_update_unit(NULL, counter, process_synthesized_event);
405 if (err < 0) {
406 pr_err("Couldn't synthesize evsel unit.\n");
407 return err;
408 }
409 }
410
411 if (has_scale(counter)) {
412 err = perf_event__synthesize_event_update_scale(NULL, counter, process_synthesized_event);
413 if (err < 0) {
414 pr_err("Couldn't synthesize evsel scale.\n");
415 return err;
416 }
417 }
418
419 if (counter->own_cpus) {
420 err = perf_event__synthesize_event_update_cpus(NULL, counter, process_synthesized_event);
421 if (err < 0) {
422 pr_err("Couldn't synthesize evsel scale.\n");
423 return err;
424 }
425 }
426
427 /*
428 * Name is needed only for pipe output,
429 * perf.data carries event names.
430 */
431 if (is_pipe) {
432 err = perf_event__synthesize_event_update_name(NULL, counter, process_synthesized_event);
433 if (err < 0) {
434 pr_err("Couldn't synthesize evsel name.\n");
435 return err;
436 }
437 }
438 }
439
8b99b1a4
JO
440 err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
441 process_synthesized_event,
442 NULL);
443 if (err < 0) {
444 pr_err("Couldn't synthesize thread map.\n");
445 return err;
446 }
447
448 err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
449 process_synthesized_event, NULL);
450 if (err < 0) {
451 pr_err("Couldn't synthesize thread map.\n");
452 return err;
453 }
454
455 err = perf_event__synthesize_stat_config(NULL, &stat_config,
456 process_synthesized_event, NULL);
457 if (err < 0) {
458 pr_err("Couldn't synthesize config.\n");
459 return err;
460 }
461
462 return 0;
463}
464
2af4646d
JO
465#define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
466
467static int __store_counter_ids(struct perf_evsel *counter,
468 struct cpu_map *cpus,
469 struct thread_map *threads)
470{
471 int cpu, thread;
472
473 for (cpu = 0; cpu < cpus->nr; cpu++) {
474 for (thread = 0; thread < threads->nr; thread++) {
475 int fd = FD(counter, cpu, thread);
476
477 if (perf_evlist__id_add_fd(evsel_list, counter,
478 cpu, thread, fd) < 0)
479 return -1;
480 }
481 }
482
483 return 0;
484}
485
486static int store_counter_ids(struct perf_evsel *counter)
487{
488 struct cpu_map *cpus = counter->cpus;
489 struct thread_map *threads = counter->threads;
490
491 if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
492 return -ENOMEM;
493
494 return __store_counter_ids(counter, cpus, threads);
495}
496
acf28922 497static int __run_perf_stat(int argc, const char **argv)
42202dd5 498{
ec0d3d1f 499 int interval = stat_config.interval;
56e52e85 500 char msg[512];
42202dd5 501 unsigned long long t0, t1;
cac21425 502 struct perf_evsel *counter;
13370a9b 503 struct timespec ts;
410136f5 504 size_t l;
42202dd5 505 int status = 0;
6be2850e 506 const bool forks = (argc > 0);
664c98d4 507 bool is_pipe = STAT_RECORD ? perf_stat.file.is_pipe : false;
42202dd5 508
13370a9b
SE
509 if (interval) {
510 ts.tv_sec = interval / 1000;
511 ts.tv_nsec = (interval % 1000) * 1000000;
512 } else {
513 ts.tv_sec = 1;
514 ts.tv_nsec = 0;
515 }
516
60666c63 517 if (forks) {
664c98d4 518 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
735f7e0b 519 workload_exec_failed_signal) < 0) {
acf28922
NK
520 perror("failed to prepare workload");
521 return -1;
60666c63 522 }
d20a47e7 523 child_pid = evsel_list->workload.pid;
051ae7f7
PM
524 }
525
6a4bb04c 526 if (group)
63dab225 527 perf_evlist__set_leader(evsel_list);
6a4bb04c 528
0050f7aa 529 evlist__for_each(evsel_list, counter) {
cac21425 530 if (create_perf_stat_counter(counter) < 0) {
979987a5
DA
531 /*
532 * PPC returns ENXIO for HW counters until 2.6.37
533 * (behavior changed with commit b0a873e).
534 */
38f6ae1e 535 if (errno == EINVAL || errno == ENOSYS ||
979987a5
DA
536 errno == ENOENT || errno == EOPNOTSUPP ||
537 errno == ENXIO) {
c63ca0c0
DA
538 if (verbose)
539 ui__warning("%s event is not supported by the kernel.\n",
7289f83c 540 perf_evsel__name(counter));
2cee77c4 541 counter->supported = false;
cb5ef600
KL
542
543 if ((counter->leader != counter) ||
544 !(counter->leader->nr_members > 1))
545 continue;
c63ca0c0 546 }
ede70290 547
56e52e85
ACM
548 perf_evsel__open_strerror(counter, &target,
549 errno, msg, sizeof(msg));
550 ui__error("%s\n", msg);
551
48290609
ACM
552 if (child_pid != -1)
553 kill(child_pid, SIGTERM);
fceda7fe 554
48290609
ACM
555 return -1;
556 }
2cee77c4 557 counter->supported = true;
410136f5
SE
558
559 l = strlen(counter->unit);
560 if (l > unit_width)
561 unit_width = l;
2af4646d
JO
562
563 if (STAT_RECORD && store_counter_ids(counter))
564 return -1;
084ab9f8 565 }
42202dd5 566
23d4aad4
ACM
567 if (perf_evlist__apply_filters(evsel_list, &counter)) {
568 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
569 counter->filter, perf_evsel__name(counter), errno,
759e612b 570 strerror_r(errno, msg, sizeof(msg)));
cfd748ae
FW
571 return -1;
572 }
573
4979d0c7
JO
574 if (STAT_RECORD) {
575 int err, fd = perf_data_file__fd(&perf_stat.file);
576
664c98d4
JO
577 if (is_pipe) {
578 err = perf_header__write_pipe(perf_data_file__fd(&perf_stat.file));
579 } else {
580 err = perf_session__write_header(perf_stat.session, evsel_list,
581 fd, false);
582 }
583
4979d0c7
JO
584 if (err < 0)
585 return err;
8b99b1a4 586
664c98d4 587 err = perf_stat_synthesize_config(is_pipe);
8b99b1a4
JO
588 if (err < 0)
589 return err;
4979d0c7
JO
590 }
591
42202dd5
IM
592 /*
593 * Enable counters and exec the command:
594 */
595 t0 = rdclock();
13370a9b 596 clock_gettime(CLOCK_MONOTONIC, &ref_time);
42202dd5 597
60666c63 598 if (forks) {
acf28922 599 perf_evlist__start_workload(evsel_list);
67ccdecd 600 enable_counters();
acf28922 601
13370a9b
SE
602 if (interval) {
603 while (!waitpid(child_pid, &status, WNOHANG)) {
604 nanosleep(&ts, NULL);
ba411a95 605 process_interval();
13370a9b
SE
606 }
607 }
60666c63 608 wait(&status);
6af206fd 609
f33cbe72
ACM
610 if (workload_exec_errno) {
611 const char *emsg = strerror_r(workload_exec_errno, msg, sizeof(msg));
612 pr_err("Workload failed: %s\n", emsg);
6af206fd 613 return -1;
f33cbe72 614 }
6af206fd 615
33e49ea7
AK
616 if (WIFSIGNALED(status))
617 psignal(WTERMSIG(status), argv[0]);
60666c63 618 } else {
67ccdecd 619 enable_counters();
13370a9b
SE
620 while (!done) {
621 nanosleep(&ts, NULL);
622 if (interval)
ba411a95 623 process_interval();
13370a9b 624 }
60666c63 625 }
42202dd5 626
42202dd5
IM
627 t1 = rdclock();
628
9e9772c4 629 update_stats(&walltime_nsecs_stats, t1 - t0);
42202dd5 630
106a94a0 631 read_counters(true);
c52b12ed 632
42202dd5
IM
633 return WEXITSTATUS(status);
634}
635
41cde476 636static int run_perf_stat(int argc, const char **argv)
1f16c575
PZ
637{
638 int ret;
639
640 if (pre_cmd) {
641 ret = system(pre_cmd);
642 if (ret)
643 return ret;
644 }
645
646 if (sync_run)
647 sync();
648
649 ret = __run_perf_stat(argc, argv);
650 if (ret)
651 return ret;
652
653 if (post_cmd) {
654 ret = system(post_cmd);
655 if (ret)
656 return ret;
657 }
658
659 return ret;
660}
661
d73515c0
AK
662static void print_running(u64 run, u64 ena)
663{
664 if (csv_output) {
5821522e 665 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
d73515c0
AK
666 csv_sep,
667 run,
668 csv_sep,
669 ena ? 100.0 * run / ena : 100.0);
670 } else if (run != ena) {
5821522e 671 fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena);
d73515c0
AK
672 }
673}
674
f99844cb
IM
675static void print_noise_pct(double total, double avg)
676{
0007ecea 677 double pct = rel_stddev_stats(total, avg);
f99844cb 678
3ae9a34d 679 if (csv_output)
5821522e 680 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
a1bca6cc 681 else if (pct)
5821522e 682 fprintf(stat_config.output, " ( +-%6.2f%% )", pct);
f99844cb
IM
683}
684
69aad6f1 685static void print_noise(struct perf_evsel *evsel, double avg)
42202dd5 686{
581cc8a2 687 struct perf_stat_evsel *ps;
69aad6f1 688
849abde9
PZ
689 if (run_count == 1)
690 return;
691
69aad6f1 692 ps = evsel->priv;
f99844cb 693 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
42202dd5
IM
694}
695
12c08a9f 696static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
44175b6f 697{
421a50f3 698 switch (stat_config.aggr_mode) {
12c08a9f 699 case AGGR_CORE:
5821522e 700 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
12c08a9f
SE
701 cpu_map__id_to_socket(id),
702 csv_output ? 0 : -8,
703 cpu_map__id_to_cpu(id),
704 csv_sep,
705 csv_output ? 0 : 4,
706 nr,
707 csv_sep);
708 break;
86ee6e18 709 case AGGR_SOCKET:
5821522e 710 fprintf(stat_config.output, "S%*d%s%*d%s",
d7e7a451 711 csv_output ? 0 : -5,
12c08a9f 712 id,
d7e7a451
SE
713 csv_sep,
714 csv_output ? 0 : 4,
715 nr,
716 csv_sep);
86ee6e18
SE
717 break;
718 case AGGR_NONE:
5821522e 719 fprintf(stat_config.output, "CPU%*d%s",
d7470b6a 720 csv_output ? 0 : -4,
12c08a9f 721 perf_evsel__cpus(evsel)->map[id], csv_sep);
86ee6e18 722 break;
32b8af82 723 case AGGR_THREAD:
5821522e 724 fprintf(stat_config.output, "%*s-%*d%s",
32b8af82
JO
725 csv_output ? 0 : 16,
726 thread_map__comm(evsel->threads, id),
727 csv_output ? 0 : -8,
728 thread_map__pid(evsel->threads, id),
729 csv_sep);
730 break;
86ee6e18 731 case AGGR_GLOBAL:
208df99e 732 case AGGR_UNSET:
86ee6e18
SE
733 default:
734 break;
735 }
736}
737
140aeadc
AK
738struct outstate {
739 FILE *fh;
740 bool newline;
f9483392 741 const char *prefix;
140aeadc
AK
742};
743
744#define METRIC_LEN 35
745
746static void new_line_std(void *ctx)
747{
748 struct outstate *os = ctx;
749
750 os->newline = true;
751}
752
753static void do_new_line_std(struct outstate *os)
754{
755 fputc('\n', os->fh);
f9483392 756 fputs(os->prefix, os->fh);
140aeadc
AK
757 if (stat_config.aggr_mode == AGGR_NONE)
758 fprintf(os->fh, " ");
759 if (stat_config.aggr_mode == AGGR_CORE)
760 fprintf(os->fh, " ");
761 if (stat_config.aggr_mode == AGGR_SOCKET)
762 fprintf(os->fh, " ");
763 fprintf(os->fh, " ");
764}
765
766static void print_metric_std(void *ctx, const char *color, const char *fmt,
767 const char *unit, double val)
768{
769 struct outstate *os = ctx;
770 FILE *out = os->fh;
771 int n;
772 bool newline = os->newline;
773
774 os->newline = false;
775
776 if (unit == NULL || fmt == NULL) {
777 fprintf(out, "%-*s", METRIC_LEN, "");
778 return;
779 }
780
781 if (newline)
782 do_new_line_std(os);
783
784 n = fprintf(out, " # ");
785 if (color)
786 n += color_fprintf(out, color, fmt, val);
787 else
788 n += fprintf(out, fmt, val);
789 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
790}
791
da88c7f7 792static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
86ee6e18 793{
5821522e 794 FILE *output = stat_config.output;
86ee6e18 795 double msecs = avg / 1e6;
410136f5 796 const char *fmt_v, *fmt_n;
4bbe5a61 797 char name[25];
86ee6e18 798
410136f5
SE
799 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
800 fmt_n = csv_output ? "%s" : "%-25s";
801
da88c7f7 802 aggr_printout(evsel, id, nr);
d7470b6a 803
4bbe5a61
DA
804 scnprintf(name, sizeof(name), "%s%s",
805 perf_evsel__name(evsel), csv_output ? "" : " (msec)");
410136f5
SE
806
807 fprintf(output, fmt_v, msecs, csv_sep);
808
809 if (csv_output)
810 fprintf(output, "%s%s", evsel->unit, csv_sep);
811 else
812 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
813
814 fprintf(output, fmt_n, name);
d7470b6a 815
023695d9 816 if (evsel->cgrp)
4aa9015f 817 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
44175b6f
IM
818}
819
556b1fb7
JO
820static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
821{
5821522e 822 FILE *output = stat_config.output;
556b1fb7
JO
823 double sc = evsel->scale;
824 const char *fmt;
556b1fb7
JO
825
826 if (csv_output) {
827 fmt = sc != 1.0 ? "%.2f%s" : "%.0f%s";
828 } else {
829 if (big_num)
830 fmt = sc != 1.0 ? "%'18.2f%s" : "%'18.0f%s";
831 else
832 fmt = sc != 1.0 ? "%18.2f%s" : "%18.0f%s";
833 }
834
835 aggr_printout(evsel, id, nr);
836
556b1fb7
JO
837 fprintf(output, fmt, avg, csv_sep);
838
839 if (evsel->unit)
840 fprintf(output, "%-*s%s",
841 csv_output ? 0 : unit_width,
842 evsel->unit, csv_sep);
843
844 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
845
846 if (evsel->cgrp)
847 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
eedfcb4b 848}
556b1fb7 849
f9483392
AK
850static void printout(int id, int nr, struct perf_evsel *counter, double uval,
851 char *prefix)
eedfcb4b 852{
140aeadc 853 struct perf_stat_output_ctx out;
f9483392
AK
854 struct outstate os = {
855 .fh = stat_config.output,
856 .prefix = prefix ? prefix : ""
857 };
140aeadc
AK
858 print_metric_t pm = print_metric_std;
859 void (*nl)(void *);
eedfcb4b 860
140aeadc 861 nl = new_line_std;
eedfcb4b
AK
862
863 if (nsec_counter(counter))
864 nsec_printout(id, nr, counter, uval);
865 else
866 abs_printout(id, nr, counter, uval);
556b1fb7 867
140aeadc
AK
868 out.print_metric = pm;
869 out.new_line = nl;
870 out.ctx = &os;
871
f9483392 872 if (!csv_output)
140aeadc
AK
873 perf_stat__print_shadow_stats(counter, uval,
874 stat_config.aggr_mode == AGGR_GLOBAL ? 0 :
875 cpu_map__id_to_cpu(id),
876 &out);
556b1fb7
JO
877}
878
86ee6e18 879static void print_aggr(char *prefix)
d7e7a451 880{
5821522e 881 FILE *output = stat_config.output;
d7e7a451 882 struct perf_evsel *counter;
601083cf 883 int cpu, s, s2, id, nr;
410136f5 884 double uval;
d7e7a451 885 u64 ena, run, val;
d7e7a451 886
86ee6e18 887 if (!(aggr_map || aggr_get_id))
d7e7a451
SE
888 return;
889
86ee6e18
SE
890 for (s = 0; s < aggr_map->nr; s++) {
891 id = aggr_map->map[s];
0050f7aa 892 evlist__for_each(evsel_list, counter) {
d7e7a451
SE
893 val = ena = run = 0;
894 nr = 0;
895 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
601083cf 896 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
86ee6e18 897 if (s2 != id)
d7e7a451 898 continue;
a6fa0038
JO
899 val += perf_counts(counter->counts, cpu, 0)->val;
900 ena += perf_counts(counter->counts, cpu, 0)->ena;
901 run += perf_counts(counter->counts, cpu, 0)->run;
d7e7a451
SE
902 nr++;
903 }
904 if (prefix)
905 fprintf(output, "%s", prefix);
906
907 if (run == 0 || ena == 0) {
582ec082 908 aggr_printout(counter, id, nr);
86ee6e18 909
410136f5 910 fprintf(output, "%*s%s",
d7e7a451
SE
911 csv_output ? 0 : 18,
912 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
410136f5
SE
913 csv_sep);
914
915 fprintf(output, "%-*s%s",
916 csv_output ? 0 : unit_width,
917 counter->unit, csv_sep);
918
919 fprintf(output, "%*s",
920 csv_output ? 0 : -25,
d7e7a451 921 perf_evsel__name(counter));
86ee6e18 922
d7e7a451
SE
923 if (counter->cgrp)
924 fprintf(output, "%s%s",
925 csv_sep, counter->cgrp->name);
926
d73515c0 927 print_running(run, ena);
d7e7a451
SE
928 fputc('\n', output);
929 continue;
930 }
410136f5 931 uval = val * counter->scale;
f9483392 932 printout(id, nr, counter, uval, prefix);
d73515c0 933 if (!csv_output)
d7e7a451
SE
934 print_noise(counter, 1.0);
935
d73515c0 936 print_running(run, ena);
d7e7a451
SE
937 fputc('\n', output);
938 }
939 }
940}
941
32b8af82
JO
942static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
943{
5821522e 944 FILE *output = stat_config.output;
32b8af82
JO
945 int nthreads = thread_map__nr(counter->threads);
946 int ncpus = cpu_map__nr(counter->cpus);
947 int cpu, thread;
948 double uval;
949
950 for (thread = 0; thread < nthreads; thread++) {
951 u64 ena = 0, run = 0, val = 0;
952
953 for (cpu = 0; cpu < ncpus; cpu++) {
954 val += perf_counts(counter->counts, cpu, thread)->val;
955 ena += perf_counts(counter->counts, cpu, thread)->ena;
956 run += perf_counts(counter->counts, cpu, thread)->run;
957 }
958
959 if (prefix)
960 fprintf(output, "%s", prefix);
961
962 uval = val * counter->scale;
f9483392 963 printout(thread, 0, counter, uval, prefix);
32b8af82
JO
964
965 if (!csv_output)
966 print_noise(counter, 1.0);
967
968 print_running(run, ena);
969 fputc('\n', output);
970 }
971}
972
2996f5dd
IM
973/*
974 * Print out the results of a single counter:
f5b4a9c3 975 * aggregated counts in system-wide mode
2996f5dd 976 */
13370a9b 977static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
2996f5dd 978{
5821522e 979 FILE *output = stat_config.output;
581cc8a2 980 struct perf_stat_evsel *ps = counter->priv;
69aad6f1 981 double avg = avg_stats(&ps->res_stats[0]);
c52b12ed 982 int scaled = counter->counts->scaled;
410136f5 983 double uval;
d73515c0
AK
984 double avg_enabled, avg_running;
985
986 avg_enabled = avg_stats(&ps->res_stats[1]);
987 avg_running = avg_stats(&ps->res_stats[2]);
2996f5dd 988
13370a9b
SE
989 if (prefix)
990 fprintf(output, "%s", prefix);
991
3b4331d9 992 if (scaled == -1 || !counter->supported) {
410136f5 993 fprintf(output, "%*s%s",
d7470b6a 994 csv_output ? 0 : 18,
2cee77c4 995 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
410136f5
SE
996 csv_sep);
997 fprintf(output, "%-*s%s",
998 csv_output ? 0 : unit_width,
999 counter->unit, csv_sep);
1000 fprintf(output, "%*s",
1001 csv_output ? 0 : -25,
7289f83c 1002 perf_evsel__name(counter));
023695d9
SE
1003
1004 if (counter->cgrp)
4aa9015f 1005 fprintf(output, "%s%s", csv_sep, counter->cgrp->name);
023695d9 1006
d73515c0 1007 print_running(avg_running, avg_enabled);
4aa9015f 1008 fputc('\n', output);
2996f5dd
IM
1009 return;
1010 }
c04f5e5d 1011
410136f5 1012 uval = avg * counter->scale;
f9483392 1013 printout(-1, 0, counter, uval, prefix);
849abde9 1014
3ae9a34d
ZH
1015 print_noise(counter, avg);
1016
d73515c0 1017 print_running(avg_running, avg_enabled);
4aa9015f 1018 fprintf(output, "\n");
c04f5e5d
IM
1019}
1020
f5b4a9c3
SE
1021/*
1022 * Print out the results of a single counter:
1023 * does not use aggregated count in system-wide
1024 */
13370a9b 1025static void print_counter(struct perf_evsel *counter, char *prefix)
f5b4a9c3 1026{
5821522e 1027 FILE *output = stat_config.output;
f5b4a9c3 1028 u64 ena, run, val;
410136f5 1029 double uval;
f5b4a9c3
SE
1030 int cpu;
1031
7ae92e74 1032 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
a6fa0038
JO
1033 val = perf_counts(counter->counts, cpu, 0)->val;
1034 ena = perf_counts(counter->counts, cpu, 0)->ena;
1035 run = perf_counts(counter->counts, cpu, 0)->run;
13370a9b
SE
1036
1037 if (prefix)
1038 fprintf(output, "%s", prefix);
1039
f5b4a9c3 1040 if (run == 0 || ena == 0) {
410136f5 1041 fprintf(output, "CPU%*d%s%*s%s",
d7470b6a 1042 csv_output ? 0 : -4,
7ae92e74 1043 perf_evsel__cpus(counter)->map[cpu], csv_sep,
d7470b6a 1044 csv_output ? 0 : 18,
2cee77c4 1045 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
410136f5
SE
1046 csv_sep);
1047
1048 fprintf(output, "%-*s%s",
1049 csv_output ? 0 : unit_width,
1050 counter->unit, csv_sep);
1051
1052 fprintf(output, "%*s",
1053 csv_output ? 0 : -25,
1054 perf_evsel__name(counter));
f5b4a9c3 1055
023695d9 1056 if (counter->cgrp)
4aa9015f
SE
1057 fprintf(output, "%s%s",
1058 csv_sep, counter->cgrp->name);
023695d9 1059
d73515c0 1060 print_running(run, ena);
4aa9015f 1061 fputc('\n', output);
f5b4a9c3
SE
1062 continue;
1063 }
1064
410136f5 1065 uval = val * counter->scale;
f9483392 1066 printout(cpu, 0, counter, uval, prefix);
d73515c0 1067 if (!csv_output)
d7470b6a 1068 print_noise(counter, 1.0);
d73515c0 1069 print_running(run, ena);
f5b4a9c3 1070
4aa9015f 1071 fputc('\n', output);
f5b4a9c3
SE
1072 }
1073}
1074
d4f63a47
JO
1075static void print_interval(char *prefix, struct timespec *ts)
1076{
5821522e 1077 FILE *output = stat_config.output;
d4f63a47
JO
1078 static int num_print_interval;
1079
1080 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1081
1082 if (num_print_interval == 0 && !csv_output) {
421a50f3 1083 switch (stat_config.aggr_mode) {
d4f63a47
JO
1084 case AGGR_SOCKET:
1085 fprintf(output, "# time socket cpus counts %*s events\n", unit_width, "unit");
1086 break;
1087 case AGGR_CORE:
1088 fprintf(output, "# time core cpus counts %*s events\n", unit_width, "unit");
1089 break;
1090 case AGGR_NONE:
1091 fprintf(output, "# time CPU counts %*s events\n", unit_width, "unit");
1092 break;
32b8af82
JO
1093 case AGGR_THREAD:
1094 fprintf(output, "# time comm-pid counts %*s events\n", unit_width, "unit");
1095 break;
d4f63a47
JO
1096 case AGGR_GLOBAL:
1097 default:
1098 fprintf(output, "# time counts %*s events\n", unit_width, "unit");
208df99e
JO
1099 case AGGR_UNSET:
1100 break;
d4f63a47
JO
1101 }
1102 }
1103
1104 if (++num_print_interval == 25)
1105 num_print_interval = 0;
1106}
1107
1108static void print_header(int argc, const char **argv)
42202dd5 1109{
5821522e 1110 FILE *output = stat_config.output;
69aad6f1 1111 int i;
42202dd5 1112
ddcacfa0
IM
1113 fflush(stdout);
1114
d7470b6a 1115 if (!csv_output) {
4aa9015f
SE
1116 fprintf(output, "\n");
1117 fprintf(output, " Performance counter stats for ");
62d3b617
DA
1118 if (target.system_wide)
1119 fprintf(output, "\'system wide");
1120 else if (target.cpu_list)
1121 fprintf(output, "\'CPU(s) %s", target.cpu_list);
602ad878 1122 else if (!target__has_task(&target)) {
ba6039b6
JO
1123 fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1124 for (i = 1; argv && (i < argc); i++)
4aa9015f 1125 fprintf(output, " %s", argv[i]);
20f946b4
NK
1126 } else if (target.pid)
1127 fprintf(output, "process id \'%s", target.pid);
d7470b6a 1128 else
20f946b4 1129 fprintf(output, "thread id \'%s", target.tid);
44db76c8 1130
4aa9015f 1131 fprintf(output, "\'");
d7470b6a 1132 if (run_count > 1)
4aa9015f
SE
1133 fprintf(output, " (%d runs)", run_count);
1134 fprintf(output, ":\n\n");
d7470b6a 1135 }
d4f63a47
JO
1136}
1137
1138static void print_footer(void)
1139{
5821522e
JO
1140 FILE *output = stat_config.output;
1141
d4f63a47
JO
1142 if (!null_run)
1143 fprintf(output, "\n");
1144 fprintf(output, " %17.9f seconds time elapsed",
1145 avg_stats(&walltime_nsecs_stats)/1e9);
1146 if (run_count > 1) {
1147 fprintf(output, " ");
1148 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1149 avg_stats(&walltime_nsecs_stats));
1150 }
1151 fprintf(output, "\n\n");
1152}
1153
1154static void print_counters(struct timespec *ts, int argc, const char **argv)
1155{
ec0d3d1f 1156 int interval = stat_config.interval;
d4f63a47
JO
1157 struct perf_evsel *counter;
1158 char buf[64], *prefix = NULL;
1159
664c98d4
JO
1160 /* Do not print anything if we record to the pipe. */
1161 if (STAT_RECORD && perf_stat.file.is_pipe)
1162 return;
1163
d4f63a47
JO
1164 if (interval)
1165 print_interval(prefix = buf, ts);
1166 else
1167 print_header(argc, argv);
2996f5dd 1168
421a50f3 1169 switch (stat_config.aggr_mode) {
12c08a9f 1170 case AGGR_CORE:
86ee6e18 1171 case AGGR_SOCKET:
d4f63a47 1172 print_aggr(prefix);
86ee6e18 1173 break;
32b8af82
JO
1174 case AGGR_THREAD:
1175 evlist__for_each(evsel_list, counter)
1176 print_aggr_thread(counter, prefix);
1177 break;
86ee6e18 1178 case AGGR_GLOBAL:
0050f7aa 1179 evlist__for_each(evsel_list, counter)
d4f63a47 1180 print_counter_aggr(counter, prefix);
86ee6e18
SE
1181 break;
1182 case AGGR_NONE:
0050f7aa 1183 evlist__for_each(evsel_list, counter)
d4f63a47 1184 print_counter(counter, prefix);
86ee6e18 1185 break;
208df99e 1186 case AGGR_UNSET:
86ee6e18
SE
1187 default:
1188 break;
f5b4a9c3 1189 }
ddcacfa0 1190
d4f63a47
JO
1191 if (!interval && !csv_output)
1192 print_footer();
1193
5821522e 1194 fflush(stat_config.output);
ddcacfa0
IM
1195}
1196
f7b7c26e
PZ
1197static volatile int signr = -1;
1198
5242519b 1199static void skip_signal(int signo)
ddcacfa0 1200{
ec0d3d1f 1201 if ((child_pid == -1) || stat_config.interval)
60666c63
LW
1202 done = 1;
1203
f7b7c26e 1204 signr = signo;
d07f0b12
SE
1205 /*
1206 * render child_pid harmless
1207 * won't send SIGTERM to a random
1208 * process in case of race condition
1209 * and fast PID recycling
1210 */
1211 child_pid = -1;
f7b7c26e
PZ
1212}
1213
1214static void sig_atexit(void)
1215{
d07f0b12
SE
1216 sigset_t set, oset;
1217
1218 /*
1219 * avoid race condition with SIGCHLD handler
1220 * in skip_signal() which is modifying child_pid
1221 * goal is to avoid send SIGTERM to a random
1222 * process
1223 */
1224 sigemptyset(&set);
1225 sigaddset(&set, SIGCHLD);
1226 sigprocmask(SIG_BLOCK, &set, &oset);
1227
933da83a
CW
1228 if (child_pid != -1)
1229 kill(child_pid, SIGTERM);
1230
d07f0b12
SE
1231 sigprocmask(SIG_SETMASK, &oset, NULL);
1232
f7b7c26e
PZ
1233 if (signr == -1)
1234 return;
1235
1236 signal(signr, SIG_DFL);
1237 kill(getpid(), signr);
5242519b
IM
1238}
1239
1d037ca1
IT
1240static int stat__set_big_num(const struct option *opt __maybe_unused,
1241 const char *s __maybe_unused, int unset)
d7470b6a
SE
1242{
1243 big_num_opt = unset ? 0 : 1;
1244 return 0;
1245}
1246
e0547311
JO
1247static const struct option stat_options[] = {
1248 OPT_BOOLEAN('T', "transaction", &transaction_run,
1249 "hardware transaction statistics"),
1250 OPT_CALLBACK('e', "event", &evsel_list, "event",
1251 "event selector. use 'perf list' to list available events",
1252 parse_events_option),
1253 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1254 "event filter", parse_filter),
1255 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1256 "child tasks do not inherit counters"),
1257 OPT_STRING('p', "pid", &target.pid, "pid",
1258 "stat events on existing process id"),
1259 OPT_STRING('t', "tid", &target.tid, "tid",
1260 "stat events on existing thread id"),
1261 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1262 "system-wide collection from all CPUs"),
1263 OPT_BOOLEAN('g', "group", &group,
1264 "put the counters into a counter group"),
1265 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1266 OPT_INCR('v', "verbose", &verbose,
1267 "be more verbose (show counter open errors, etc)"),
1268 OPT_INTEGER('r', "repeat", &run_count,
1269 "repeat command and print average + stddev (max: 100, forever: 0)"),
1270 OPT_BOOLEAN('n', "null", &null_run,
1271 "null run - dont start any counters"),
1272 OPT_INCR('d', "detailed", &detailed_run,
1273 "detailed run - start a lot of events"),
1274 OPT_BOOLEAN('S', "sync", &sync_run,
1275 "call sync() before starting a run"),
1276 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1277 "print large numbers with thousands\' separators",
1278 stat__set_big_num),
1279 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1280 "list of cpus to monitor in system-wide"),
1281 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1282 "disable CPU count aggregation", AGGR_NONE),
1283 OPT_STRING('x', "field-separator", &csv_sep, "separator",
1284 "print counts with custom separator"),
1285 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1286 "monitor event in cgroup name only", parse_cgroups),
1287 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1288 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1289 OPT_INTEGER(0, "log-fd", &output_fd,
1290 "log output to fd, instead of stderr"),
1291 OPT_STRING(0, "pre", &pre_cmd, "command",
1292 "command to run prior to the measured command"),
1293 OPT_STRING(0, "post", &post_cmd, "command",
1294 "command to run after to the measured command"),
1295 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1296 "print counts at regular interval in ms (>= 10)"),
1297 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1298 "aggregate counts per processor socket", AGGR_SOCKET),
1299 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1300 "aggregate counts per physical processor core", AGGR_CORE),
1301 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1302 "aggregate counts per thread", AGGR_THREAD),
1303 OPT_UINTEGER('D', "delay", &initial_delay,
1304 "ms to wait before starting measurement after program start"),
1305 OPT_END()
1306};
1307
1fe7a300
JO
1308static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1309{
1310 return cpu_map__get_socket(map, cpu, NULL);
1311}
1312
1313static int perf_stat__get_core(struct cpu_map *map, int cpu)
1314{
1315 return cpu_map__get_core(map, cpu, NULL);
1316}
1317
1e5a2931
JO
1318static int cpu_map__get_max(struct cpu_map *map)
1319{
1320 int i, max = -1;
1321
1322 for (i = 0; i < map->nr; i++) {
1323 if (map->map[i] > max)
1324 max = map->map[i];
1325 }
1326
1327 return max;
1328}
1329
1330static struct cpu_map *cpus_aggr_map;
1331
1332static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1333{
1334 int cpu;
1335
1336 if (idx >= map->nr)
1337 return -1;
1338
1339 cpu = map->map[idx];
1340
1341 if (cpus_aggr_map->map[cpu] == -1)
1342 cpus_aggr_map->map[cpu] = get_id(map, idx);
1343
1344 return cpus_aggr_map->map[cpu];
1345}
1346
1347static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1348{
1349 return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1350}
1351
1352static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1353{
1354 return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1355}
1356
86ee6e18
SE
1357static int perf_stat_init_aggr_mode(void)
1358{
1e5a2931
JO
1359 int nr;
1360
421a50f3 1361 switch (stat_config.aggr_mode) {
86ee6e18
SE
1362 case AGGR_SOCKET:
1363 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1364 perror("cannot build socket map");
1365 return -1;
1366 }
1e5a2931 1367 aggr_get_id = perf_stat__get_socket_cached;
86ee6e18 1368 break;
12c08a9f
SE
1369 case AGGR_CORE:
1370 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1371 perror("cannot build core map");
1372 return -1;
1373 }
1e5a2931 1374 aggr_get_id = perf_stat__get_core_cached;
12c08a9f 1375 break;
86ee6e18
SE
1376 case AGGR_NONE:
1377 case AGGR_GLOBAL:
32b8af82 1378 case AGGR_THREAD:
208df99e 1379 case AGGR_UNSET:
86ee6e18
SE
1380 default:
1381 break;
1382 }
1e5a2931
JO
1383
1384 /*
1385 * The evsel_list->cpus is the base we operate on,
1386 * taking the highest cpu number to be the size of
1387 * the aggregation translate cpumap.
1388 */
1389 nr = cpu_map__get_max(evsel_list->cpus);
1390 cpus_aggr_map = cpu_map__empty_new(nr + 1);
1391 return cpus_aggr_map ? 0 : -ENOMEM;
86ee6e18
SE
1392}
1393
544c2ae7
MH
1394static void perf_stat__exit_aggr_mode(void)
1395{
1396 cpu_map__put(aggr_map);
1397 cpu_map__put(cpus_aggr_map);
1398 aggr_map = NULL;
1399 cpus_aggr_map = NULL;
1400}
1401
68d702f7
JO
1402static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1403{
1404 int cpu;
1405
1406 if (idx > map->nr)
1407 return -1;
1408
1409 cpu = map->map[idx];
1410
1411 if (cpu >= env->nr_cpus_online)
1412 return -1;
1413
1414 return cpu;
1415}
1416
1417static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1418{
1419 struct perf_env *env = data;
1420 int cpu = perf_env__get_cpu(env, map, idx);
1421
1422 return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1423}
1424
1425static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1426{
1427 struct perf_env *env = data;
1428 int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1429
1430 if (cpu != -1) {
1431 int socket_id = env->cpu[cpu].socket_id;
1432
1433 /*
1434 * Encode socket in upper 16 bits
1435 * core_id is relative to socket, and
1436 * we need a global id. So we combine
1437 * socket + core id.
1438 */
1439 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1440 }
1441
1442 return core;
1443}
1444
1445static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1446 struct cpu_map **sockp)
1447{
1448 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1449}
1450
1451static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
1452 struct cpu_map **corep)
1453{
1454 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1455}
1456
1457static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
1458{
1459 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1460}
1461
1462static int perf_stat__get_core_file(struct cpu_map *map, int idx)
1463{
1464 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1465}
1466
1467static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1468{
1469 struct perf_env *env = &st->session->header.env;
1470
1471 switch (stat_config.aggr_mode) {
1472 case AGGR_SOCKET:
1473 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
1474 perror("cannot build socket map");
1475 return -1;
1476 }
1477 aggr_get_id = perf_stat__get_socket_file;
1478 break;
1479 case AGGR_CORE:
1480 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
1481 perror("cannot build core map");
1482 return -1;
1483 }
1484 aggr_get_id = perf_stat__get_core_file;
1485 break;
1486 case AGGR_NONE:
1487 case AGGR_GLOBAL:
1488 case AGGR_THREAD:
1489 case AGGR_UNSET:
1490 default:
1491 break;
1492 }
1493
1494 return 0;
1495}
1496
2cba3ffb
IM
1497/*
1498 * Add default attributes, if there were no attributes specified or
1499 * if -d/--detailed, -d -d or -d -d -d is used:
1500 */
1501static int add_default_attributes(void)
1502{
b070a547
ACM
1503 struct perf_event_attr default_attrs[] = {
1504
1505 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
1506 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
1507 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
1508 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
1509
1510 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
1511 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1512 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
1513 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
1514 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
1515 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
1516
1517};
1518
1519/*
1520 * Detailed stats (-d), covering the L1 and last level data caches:
1521 */
1522 struct perf_event_attr detailed_attrs[] = {
1523
1524 { .type = PERF_TYPE_HW_CACHE,
1525 .config =
1526 PERF_COUNT_HW_CACHE_L1D << 0 |
1527 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1528 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1529
1530 { .type = PERF_TYPE_HW_CACHE,
1531 .config =
1532 PERF_COUNT_HW_CACHE_L1D << 0 |
1533 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1534 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1535
1536 { .type = PERF_TYPE_HW_CACHE,
1537 .config =
1538 PERF_COUNT_HW_CACHE_LL << 0 |
1539 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1540 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1541
1542 { .type = PERF_TYPE_HW_CACHE,
1543 .config =
1544 PERF_COUNT_HW_CACHE_LL << 0 |
1545 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1546 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1547};
1548
1549/*
1550 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1551 */
1552 struct perf_event_attr very_detailed_attrs[] = {
1553
1554 { .type = PERF_TYPE_HW_CACHE,
1555 .config =
1556 PERF_COUNT_HW_CACHE_L1I << 0 |
1557 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1558 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1559
1560 { .type = PERF_TYPE_HW_CACHE,
1561 .config =
1562 PERF_COUNT_HW_CACHE_L1I << 0 |
1563 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1564 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1565
1566 { .type = PERF_TYPE_HW_CACHE,
1567 .config =
1568 PERF_COUNT_HW_CACHE_DTLB << 0 |
1569 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1570 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1571
1572 { .type = PERF_TYPE_HW_CACHE,
1573 .config =
1574 PERF_COUNT_HW_CACHE_DTLB << 0 |
1575 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1576 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1577
1578 { .type = PERF_TYPE_HW_CACHE,
1579 .config =
1580 PERF_COUNT_HW_CACHE_ITLB << 0 |
1581 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1582 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1583
1584 { .type = PERF_TYPE_HW_CACHE,
1585 .config =
1586 PERF_COUNT_HW_CACHE_ITLB << 0 |
1587 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1588 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1589
1590};
1591
1592/*
1593 * Very, very detailed stats (-d -d -d), adding prefetch events:
1594 */
1595 struct perf_event_attr very_very_detailed_attrs[] = {
1596
1597 { .type = PERF_TYPE_HW_CACHE,
1598 .config =
1599 PERF_COUNT_HW_CACHE_L1D << 0 |
1600 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1601 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1602
1603 { .type = PERF_TYPE_HW_CACHE,
1604 .config =
1605 PERF_COUNT_HW_CACHE_L1D << 0 |
1606 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1607 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1608};
1609
2cba3ffb
IM
1610 /* Set attrs if no event is selected and !null_run: */
1611 if (null_run)
1612 return 0;
1613
4cabc3d1
AK
1614 if (transaction_run) {
1615 int err;
1616 if (pmu_have_event("cpu", "cycles-ct") &&
1617 pmu_have_event("cpu", "el-start"))
a454742c 1618 err = parse_events(evsel_list, transaction_attrs, NULL);
4cabc3d1 1619 else
a454742c
JO
1620 err = parse_events(evsel_list, transaction_limited_attrs, NULL);
1621 if (err) {
4cabc3d1
AK
1622 fprintf(stderr, "Cannot set up transaction events\n");
1623 return -1;
1624 }
1625 return 0;
1626 }
1627
2cba3ffb 1628 if (!evsel_list->nr_entries) {
79695e1b 1629 if (perf_evlist__add_default_attrs(evsel_list, default_attrs) < 0)
50d08e47 1630 return -1;
2cba3ffb
IM
1631 }
1632
1633 /* Detailed events get appended to the event list: */
1634
1635 if (detailed_run < 1)
1636 return 0;
1637
1638 /* Append detailed run extra attributes: */
79695e1b 1639 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
50d08e47 1640 return -1;
2cba3ffb
IM
1641
1642 if (detailed_run < 2)
1643 return 0;
1644
1645 /* Append very detailed run extra attributes: */
79695e1b 1646 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
50d08e47 1647 return -1;
2cba3ffb
IM
1648
1649 if (detailed_run < 3)
1650 return 0;
1651
1652 /* Append very, very detailed run extra attributes: */
79695e1b 1653 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2cba3ffb
IM
1654}
1655
8a59f3cc 1656static const char * const stat_record_usage[] = {
4979d0c7
JO
1657 "perf stat record [<options>]",
1658 NULL,
1659};
1660
3ba78bd0
JO
1661static void init_features(struct perf_session *session)
1662{
1663 int feat;
1664
1665 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
1666 perf_header__set_feat(&session->header, feat);
1667
1668 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
1669 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
1670 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
1671 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
1672}
1673
4979d0c7
JO
1674static int __cmd_record(int argc, const char **argv)
1675{
1676 struct perf_session *session;
1677 struct perf_data_file *file = &perf_stat.file;
1678
8a59f3cc 1679 argc = parse_options(argc, argv, stat_options, stat_record_usage,
4979d0c7
JO
1680 PARSE_OPT_STOP_AT_NON_OPTION);
1681
1682 if (output_name)
1683 file->path = output_name;
1684
e9d6db8e
JO
1685 if (run_count != 1 || forever) {
1686 pr_err("Cannot use -r option with perf stat record.\n");
1687 return -1;
1688 }
1689
4979d0c7
JO
1690 session = perf_session__new(file, false, NULL);
1691 if (session == NULL) {
1692 pr_err("Perf session creation failed.\n");
1693 return -1;
1694 }
1695
3ba78bd0
JO
1696 init_features(session);
1697
4979d0c7
JO
1698 session->evlist = evsel_list;
1699 perf_stat.session = session;
1700 perf_stat.record = true;
1701 return argc;
1702}
1703
a56f9390
JO
1704static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
1705 union perf_event *event,
1706 struct perf_session *session)
1707{
1708 struct stat_round_event *round = &event->stat_round;
1709 struct perf_evsel *counter;
1710 struct timespec tsh, *ts = NULL;
1711 const char **argv = session->header.env.cmdline_argv;
1712 int argc = session->header.env.nr_cmdline;
1713
1714 evlist__for_each(evsel_list, counter)
1715 perf_stat_process_counter(&stat_config, counter);
1716
1717 if (round->type == PERF_STAT_ROUND_TYPE__FINAL)
1718 update_stats(&walltime_nsecs_stats, round->time);
1719
1720 if (stat_config.interval && round->time) {
1721 tsh.tv_sec = round->time / NSECS_PER_SEC;
1722 tsh.tv_nsec = round->time % NSECS_PER_SEC;
1723 ts = &tsh;
1724 }
1725
1726 print_counters(ts, argc, argv);
1727 return 0;
1728}
1729
62ba18ba
JO
1730static
1731int process_stat_config_event(struct perf_tool *tool __maybe_unused,
1732 union perf_event *event,
1733 struct perf_session *session __maybe_unused)
1734{
68d702f7
JO
1735 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1736
62ba18ba 1737 perf_event__read_stat_config(&stat_config, &event->stat_config);
68d702f7 1738
89af4e05
JO
1739 if (cpu_map__empty(st->cpus)) {
1740 if (st->aggr_mode != AGGR_UNSET)
1741 pr_warning("warning: processing task data, aggregation mode not set\n");
1742 return 0;
1743 }
1744
1745 if (st->aggr_mode != AGGR_UNSET)
1746 stat_config.aggr_mode = st->aggr_mode;
1747
68d702f7
JO
1748 if (perf_stat.file.is_pipe)
1749 perf_stat_init_aggr_mode();
1750 else
1751 perf_stat_init_aggr_mode_file(st);
1752
62ba18ba
JO
1753 return 0;
1754}
1755
1975d36e
JO
1756static int set_maps(struct perf_stat *st)
1757{
1758 if (!st->cpus || !st->threads)
1759 return 0;
1760
1761 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
1762 return -EINVAL;
1763
1764 perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
1765
1766 if (perf_evlist__alloc_stats(evsel_list, true))
1767 return -ENOMEM;
1768
1769 st->maps_allocated = true;
1770 return 0;
1771}
1772
1773static
1774int process_thread_map_event(struct perf_tool *tool __maybe_unused,
1775 union perf_event *event,
1776 struct perf_session *session __maybe_unused)
1777{
1778 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1779
1780 if (st->threads) {
1781 pr_warning("Extra thread map event, ignoring.\n");
1782 return 0;
1783 }
1784
1785 st->threads = thread_map__new_event(&event->thread_map);
1786 if (!st->threads)
1787 return -ENOMEM;
1788
1789 return set_maps(st);
1790}
1791
1792static
1793int process_cpu_map_event(struct perf_tool *tool __maybe_unused,
1794 union perf_event *event,
1795 struct perf_session *session __maybe_unused)
1796{
1797 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1798 struct cpu_map *cpus;
1799
1800 if (st->cpus) {
1801 pr_warning("Extra cpu map event, ignoring.\n");
1802 return 0;
1803 }
1804
1805 cpus = cpu_map__new_data(&event->cpu_map.data);
1806 if (!cpus)
1807 return -ENOMEM;
1808
1809 st->cpus = cpus;
1810 return set_maps(st);
1811}
1812
8a59f3cc 1813static const char * const stat_report_usage[] = {
ba6039b6
JO
1814 "perf stat report [<options>]",
1815 NULL,
1816};
1817
1818static struct perf_stat perf_stat = {
1819 .tool = {
1820 .attr = perf_event__process_attr,
fa6ea781 1821 .event_update = perf_event__process_event_update,
1975d36e
JO
1822 .thread_map = process_thread_map_event,
1823 .cpu_map = process_cpu_map_event,
62ba18ba 1824 .stat_config = process_stat_config_event,
a56f9390
JO
1825 .stat = perf_event__process_stat_event,
1826 .stat_round = process_stat_round_event,
ba6039b6 1827 },
89af4e05 1828 .aggr_mode = AGGR_UNSET,
ba6039b6
JO
1829};
1830
1831static int __cmd_report(int argc, const char **argv)
1832{
1833 struct perf_session *session;
1834 const struct option options[] = {
1835 OPT_STRING('i', "input", &input_name, "file", "input file name"),
89af4e05
JO
1836 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
1837 "aggregate counts per processor socket", AGGR_SOCKET),
1838 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
1839 "aggregate counts per physical processor core", AGGR_CORE),
1840 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
1841 "disable CPU count aggregation", AGGR_NONE),
ba6039b6
JO
1842 OPT_END()
1843 };
1844 struct stat st;
1845 int ret;
1846
8a59f3cc 1847 argc = parse_options(argc, argv, options, stat_report_usage, 0);
ba6039b6
JO
1848
1849 if (!input_name || !strlen(input_name)) {
1850 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
1851 input_name = "-";
1852 else
1853 input_name = "perf.data";
1854 }
1855
1856 perf_stat.file.path = input_name;
1857 perf_stat.file.mode = PERF_DATA_MODE_READ;
1858
1859 session = perf_session__new(&perf_stat.file, false, &perf_stat.tool);
1860 if (session == NULL)
1861 return -1;
1862
1863 perf_stat.session = session;
1864 stat_config.output = stderr;
1865 evsel_list = session->evlist;
1866
1867 ret = perf_session__process_events(session);
1868 if (ret)
1869 return ret;
1870
1871 perf_session__delete(session);
1872 return 0;
1873}
1874
1d037ca1 1875int cmd_stat(int argc, const char **argv, const char *prefix __maybe_unused)
5242519b 1876{
b070a547
ACM
1877 const char * const stat_usage[] = {
1878 "perf stat [<options>] [<command>]",
1879 NULL
1880 };
cc03c542 1881 int status = -EINVAL, run_idx;
4aa9015f 1882 const char *mode;
5821522e 1883 FILE *output = stderr;
ec0d3d1f 1884 unsigned int interval;
ba6039b6 1885 const char * const stat_subcommands[] = { "record", "report" };
42202dd5 1886
5af52b51
SE
1887 setlocale(LC_ALL, "");
1888
334fe7a3 1889 evsel_list = perf_evlist__new();
361c99a6
ACM
1890 if (evsel_list == NULL)
1891 return -ENOMEM;
1892
4979d0c7
JO
1893 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
1894 (const char **) stat_usage,
1895 PARSE_OPT_STOP_AT_NON_OPTION);
1896
6edb78a2
JO
1897 if (csv_sep) {
1898 csv_output = true;
1899 if (!strcmp(csv_sep, "\\t"))
1900 csv_sep = "\t";
1901 } else
1902 csv_sep = DEFAULT_SEPARATOR;
1903
4979d0c7
JO
1904 if (argc && !strncmp(argv[0], "rec", 3)) {
1905 argc = __cmd_record(argc, argv);
1906 if (argc < 0)
1907 return -1;
ba6039b6
JO
1908 } else if (argc && !strncmp(argv[0], "rep", 3))
1909 return __cmd_report(argc, argv);
d7470b6a 1910
ec0d3d1f
JO
1911 interval = stat_config.interval;
1912
4979d0c7
JO
1913 /*
1914 * For record command the -o is already taken care of.
1915 */
1916 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
4aa9015f
SE
1917 output = NULL;
1918
56f3bae7
JC
1919 if (output_name && output_fd) {
1920 fprintf(stderr, "cannot use both --output and --log-fd\n");
e0547311
JO
1921 parse_options_usage(stat_usage, stat_options, "o", 1);
1922 parse_options_usage(NULL, stat_options, "log-fd", 0);
cc03c542 1923 goto out;
56f3bae7 1924 }
fc3e4d07
SE
1925
1926 if (output_fd < 0) {
1927 fprintf(stderr, "argument to --log-fd must be a > 0\n");
e0547311 1928 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
cc03c542 1929 goto out;
fc3e4d07
SE
1930 }
1931
4aa9015f
SE
1932 if (!output) {
1933 struct timespec tm;
1934 mode = append_file ? "a" : "w";
1935
1936 output = fopen(output_name, mode);
1937 if (!output) {
1938 perror("failed to create output file");
fceda7fe 1939 return -1;
4aa9015f
SE
1940 }
1941 clock_gettime(CLOCK_REALTIME, &tm);
1942 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
fc3e4d07 1943 } else if (output_fd > 0) {
56f3bae7
JC
1944 mode = append_file ? "a" : "w";
1945 output = fdopen(output_fd, mode);
1946 if (!output) {
1947 perror("Failed opening logfd");
1948 return -errno;
1949 }
4aa9015f
SE
1950 }
1951
5821522e
JO
1952 stat_config.output = output;
1953
d7470b6a
SE
1954 /*
1955 * let the spreadsheet do the pretty-printing
1956 */
1957 if (csv_output) {
61a9f324 1958 /* User explicitly passed -B? */
d7470b6a
SE
1959 if (big_num_opt == 1) {
1960 fprintf(stderr, "-B option not supported with -x\n");
e0547311
JO
1961 parse_options_usage(stat_usage, stat_options, "B", 1);
1962 parse_options_usage(NULL, stat_options, "x", 1);
cc03c542 1963 goto out;
d7470b6a
SE
1964 } else /* Nope, so disable big number formatting */
1965 big_num = false;
1966 } else if (big_num_opt == 0) /* User passed --no-big-num */
1967 big_num = false;
1968
602ad878 1969 if (!argc && target__none(&target))
e0547311 1970 usage_with_options(stat_usage, stat_options);
ac3063bd 1971
a7e191c3 1972 if (run_count < 0) {
cc03c542 1973 pr_err("Run count must be a positive number\n");
e0547311 1974 parse_options_usage(stat_usage, stat_options, "r", 1);
cc03c542 1975 goto out;
a7e191c3
FD
1976 } else if (run_count == 0) {
1977 forever = true;
1978 run_count = 1;
1979 }
ddcacfa0 1980
421a50f3 1981 if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
32b8af82
JO
1982 fprintf(stderr, "The --per-thread option is only available "
1983 "when monitoring via -p -t options.\n");
e0547311
JO
1984 parse_options_usage(NULL, stat_options, "p", 1);
1985 parse_options_usage(NULL, stat_options, "t", 1);
32b8af82
JO
1986 goto out;
1987 }
1988
1989 /*
1990 * no_aggr, cgroup are for system-wide only
1991 * --per-thread is aggregated per thread, we dont mix it with cpu mode
1992 */
421a50f3
JO
1993 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
1994 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
602ad878 1995 !target__has_cpu(&target)) {
023695d9
SE
1996 fprintf(stderr, "both cgroup and no-aggregation "
1997 "modes only available in system-wide mode\n");
1998
e0547311
JO
1999 parse_options_usage(stat_usage, stat_options, "G", 1);
2000 parse_options_usage(NULL, stat_options, "A", 1);
2001 parse_options_usage(NULL, stat_options, "a", 1);
cc03c542 2002 goto out;
d7e7a451
SE
2003 }
2004
2cba3ffb
IM
2005 if (add_default_attributes())
2006 goto out;
ddcacfa0 2007
602ad878 2008 target__validate(&target);
5c98d466 2009
77a6f014 2010 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
602ad878 2011 if (target__has_task(&target)) {
77a6f014 2012 pr_err("Problems finding threads of monitor\n");
e0547311
JO
2013 parse_options_usage(stat_usage, stat_options, "p", 1);
2014 parse_options_usage(NULL, stat_options, "t", 1);
602ad878 2015 } else if (target__has_cpu(&target)) {
77a6f014 2016 perror("failed to parse CPUs map");
e0547311
JO
2017 parse_options_usage(stat_usage, stat_options, "C", 1);
2018 parse_options_usage(NULL, stat_options, "a", 1);
cc03c542
NK
2019 }
2020 goto out;
60d567e2 2021 }
32b8af82
JO
2022
2023 /*
2024 * Initialize thread_map with comm names,
2025 * so we could print it out on output.
2026 */
421a50f3 2027 if (stat_config.aggr_mode == AGGR_THREAD)
32b8af82
JO
2028 thread_map__read_comms(evsel_list->threads);
2029
13370a9b 2030 if (interval && interval < 100) {
19afd104
KL
2031 if (interval < 10) {
2032 pr_err("print interval must be >= 10ms\n");
e0547311 2033 parse_options_usage(stat_usage, stat_options, "I", 1);
19afd104
KL
2034 goto out;
2035 } else
2036 pr_warning("print interval < 100ms. "
2037 "The overhead percentage could be high in some cases. "
2038 "Please proceed with caution.\n");
13370a9b 2039 }
c45c6ea2 2040
d134ffb9 2041 if (perf_evlist__alloc_stats(evsel_list, interval))
03ad9747 2042 goto out;
d6d901c2 2043
86ee6e18 2044 if (perf_stat_init_aggr_mode())
03ad9747 2045 goto out;
86ee6e18 2046
58d7e993
IM
2047 /*
2048 * We dont want to block the signals - that would cause
2049 * child tasks to inherit that and Ctrl-C would not work.
2050 * What we want is for Ctrl-C to work in the exec()-ed
2051 * task, but being ignored by perf stat itself:
2052 */
f7b7c26e 2053 atexit(sig_atexit);
a7e191c3
FD
2054 if (!forever)
2055 signal(SIGINT, skip_signal);
13370a9b 2056 signal(SIGCHLD, skip_signal);
58d7e993
IM
2057 signal(SIGALRM, skip_signal);
2058 signal(SIGABRT, skip_signal);
2059
42202dd5 2060 status = 0;
a7e191c3 2061 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
42202dd5 2062 if (run_count != 1 && verbose)
4aa9015f
SE
2063 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2064 run_idx + 1);
f9cef0a9 2065
42202dd5 2066 status = run_perf_stat(argc, argv);
a7e191c3 2067 if (forever && status != -1) {
d4f63a47 2068 print_counters(NULL, argc, argv);
254ecbc7 2069 perf_stat__reset_stats();
a7e191c3 2070 }
42202dd5
IM
2071 }
2072
a7e191c3 2073 if (!forever && status != -1 && !interval)
d4f63a47 2074 print_counters(NULL, argc, argv);
d134ffb9 2075
4979d0c7
JO
2076 if (STAT_RECORD) {
2077 /*
2078 * We synthesize the kernel mmap record just so that older tools
2079 * don't emit warnings about not being able to resolve symbols
2080 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2081 * a saner message about no samples being in the perf.data file.
2082 *
2083 * This also serves to suppress a warning about f_header.data.size == 0
8b99b1a4
JO
2084 * in header.c at the moment 'perf stat record' gets introduced, which
2085 * is not really needed once we start adding the stat specific PERF_RECORD_
2086 * records, but the need to suppress the kptr_restrict messages in older
2087 * tools remain -acme
4979d0c7
JO
2088 */
2089 int fd = perf_data_file__fd(&perf_stat.file);
2090 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2091 process_synthesized_event,
2092 &perf_stat.session->machines.host);
2093 if (err) {
2094 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2095 "older tools may produce warnings about this file\n.");
2096 }
2097
7aad0c32
JO
2098 if (!interval) {
2099 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2100 pr_err("failed to write stat round event\n");
2101 }
2102
664c98d4
JO
2103 if (!perf_stat.file.is_pipe) {
2104 perf_stat.session->header.data_size += perf_stat.bytes_written;
2105 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2106 }
4979d0c7
JO
2107
2108 perf_session__delete(perf_stat.session);
2109 }
2110
544c2ae7 2111 perf_stat__exit_aggr_mode();
d134ffb9 2112 perf_evlist__free_stats(evsel_list);
0015e2e1
ACM
2113out:
2114 perf_evlist__delete(evsel_list);
42202dd5 2115 return status;
ddcacfa0 2116}
This page took 0.360545 seconds and 5 git commands to generate.