]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - tools/perf/builtin-stat.c
perf stat: Collapse identically named events
[mirror_ubuntu-bionic-kernel.git] / tools / perf / builtin-stat.c
CommitLineData
ddcacfa0 1/*
bf9e1876
IM
2 * builtin-stat.c
3 *
4 * Builtin stat command: Give a precise performance counters summary
5 * overview about any workload, CPU or specific PID.
6 *
7 * Sample output:
ddcacfa0 8
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"
5d8bb1ec 55#include "util/drv_configs.h"
a5d243d0 56#include "util/color.h"
0007ecea 57#include "util/stat.h"
60666c63 58#include "util/header.h"
a12b51c4 59#include "util/cpumap.h"
d6d901c2 60#include "util/thread.h"
fd78260b 61#include "util/thread_map.h"
d809560b 62#include "util/counts.h"
44b1e60a 63#include "util/group.h"
4979d0c7 64#include "util/session.h"
ba6039b6 65#include "util/tool.h"
44b1e60a 66#include "util/group.h"
ba6039b6 67#include "asm/bug.h"
ddcacfa0 68
bd48c63e 69#include <linux/time64.h>
44b1e60a 70#include <api/fs/fs.h>
1f16c575 71#include <stdlib.h>
ddcacfa0 72#include <sys/prctl.h>
5af52b51 73#include <locale.h>
e3b03b6c 74#include <math.h>
16c8a109 75
d7470b6a 76#define DEFAULT_SEPARATOR " "
2cee77c4
DA
77#define CNTR_NOT_SUPPORTED "<not supported>"
78#define CNTR_NOT_COUNTED "<not counted>"
d7470b6a 79
d4f63a47 80static void print_counters(struct timespec *ts, int argc, const char **argv);
13370a9b 81
4cabc3d1 82/* Default events used for perf stat -T */
a454742c
JO
83static const char *transaction_attrs = {
84 "task-clock,"
4cabc3d1
AK
85 "{"
86 "instructions,"
87 "cycles,"
88 "cpu/cycles-t/,"
89 "cpu/tx-start/,"
90 "cpu/el-start/,"
91 "cpu/cycles-ct/"
92 "}"
93};
94
95/* More limited version when the CPU does not have all events. */
a454742c
JO
96static const char * transaction_limited_attrs = {
97 "task-clock,"
4cabc3d1
AK
98 "{"
99 "instructions,"
100 "cycles,"
101 "cpu/cycles-t/,"
102 "cpu/tx-start/"
103 "}"
104};
105
44b1e60a
AK
106static const char * topdown_attrs[] = {
107 "topdown-total-slots",
108 "topdown-slots-retired",
109 "topdown-recovery-bubbles",
110 "topdown-fetch-bubbles",
111 "topdown-slots-issued",
112 NULL,
113};
114
666e6d48 115static struct perf_evlist *evsel_list;
361c99a6 116
602ad878 117static struct target target = {
77a6f014
NK
118 .uid = UINT_MAX,
119};
ddcacfa0 120
1e5a2931
JO
121typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
122
3d632595 123static int run_count = 1;
2e6cdf99 124static bool no_inherit = false;
d07f0b12 125static volatile pid_t child_pid = -1;
c0555642 126static bool null_run = false;
2cba3ffb 127static int detailed_run = 0;
4cabc3d1 128static bool transaction_run;
44b1e60a 129static bool topdown_run = false;
201e0b06 130static bool big_num = true;
d7470b6a 131static int big_num_opt = -1;
d7470b6a
SE
132static const char *csv_sep = NULL;
133static bool csv_output = false;
43bece79 134static bool group = false;
1f16c575
PZ
135static const char *pre_cmd = NULL;
136static const char *post_cmd = NULL;
137static bool sync_run = false;
41191688 138static unsigned int initial_delay = 0;
410136f5 139static unsigned int unit_width = 4; /* strlen("unit") */
a7e191c3 140static bool forever = false;
54b50916 141static bool metric_only = false;
44b1e60a 142static bool force_metric_only = false;
430daf2d 143static bool no_merge = false;
13370a9b 144static struct timespec ref_time;
86ee6e18 145static struct cpu_map *aggr_map;
1e5a2931 146static aggr_get_id_t aggr_get_id;
e0547311
JO
147static bool append_file;
148static const char *output_name;
149static int output_fd;
02d492e5 150static int print_free_counters_hint;
5af52b51 151
4979d0c7
JO
152struct perf_stat {
153 bool record;
154 struct perf_data_file file;
155 struct perf_session *session;
156 u64 bytes_written;
ba6039b6 157 struct perf_tool tool;
1975d36e
JO
158 bool maps_allocated;
159 struct cpu_map *cpus;
160 struct thread_map *threads;
89af4e05 161 enum aggr_mode aggr_mode;
4979d0c7
JO
162};
163
164static struct perf_stat perf_stat;
165#define STAT_RECORD perf_stat.record
166
60666c63
LW
167static volatile int done = 0;
168
421a50f3
JO
169static struct perf_stat_config stat_config = {
170 .aggr_mode = AGGR_GLOBAL,
711a572e 171 .scale = true,
421a50f3
JO
172};
173
13370a9b
SE
174static inline void diff_timespec(struct timespec *r, struct timespec *a,
175 struct timespec *b)
176{
177 r->tv_sec = a->tv_sec - b->tv_sec;
178 if (a->tv_nsec < b->tv_nsec) {
310ebb93 179 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
13370a9b
SE
180 r->tv_sec--;
181 } else {
182 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
183 }
184}
185
254ecbc7
JO
186static void perf_stat__reset_stats(void)
187{
188 perf_evlist__reset_stats(evsel_list);
f87027b9 189 perf_stat__reset_shadow_stats();
1eda3b21
JO
190}
191
cac21425 192static int create_perf_stat_counter(struct perf_evsel *evsel)
ddcacfa0 193{
69aad6f1 194 struct perf_event_attr *attr = &evsel->attr;
727ab04e 195
711a572e 196 if (stat_config.scale)
a21ca2ca
IM
197 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
198 PERF_FORMAT_TOTAL_TIME_RUNNING;
ddcacfa0 199
5d2cd909
ACM
200 attr->inherit = !no_inherit;
201
6acd8e92
JO
202 /*
203 * Some events get initialized with sample_(period/type) set,
204 * like tracepoints. Clear it up for counting.
205 */
206 attr->sample_period = 0;
6db1a5c1 207
4979d0c7
JO
208 /*
209 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
210 * while avoiding that older tools show confusing messages.
6db1a5c1
JO
211 *
212 * However for pipe sessions we need to keep it zero,
213 * because script's perf_evsel__check_attr is triggered
214 * by attr->sample_type != 0, and we can't run it on
215 * stat sessions.
4979d0c7 216 */
6db1a5c1
JO
217 if (!(STAT_RECORD && perf_stat.file.is_pipe))
218 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
6acd8e92 219
67ccdecd
JO
220 /*
221 * Disabling all counters initially, they will be enabled
222 * either manually by us or by kernel via enable_on_exec
223 * set later.
224 */
c8280cec 225 if (perf_evsel__is_group_leader(evsel)) {
67ccdecd
JO
226 attr->disabled = 1;
227
c8280cec
JO
228 /*
229 * In case of initial_delay we enable tracee
230 * events manually.
231 */
232 if (target__none(&target) && !initial_delay)
41191688 233 attr->enable_on_exec = 1;
ddcacfa0 234 }
084ab9f8 235
c8280cec
JO
236 if (target__has_cpu(&target))
237 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
238
594ac61a 239 return perf_evsel__open_per_thread(evsel, evsel_list->threads);
ddcacfa0
IM
240}
241
c04f5e5d
IM
242/*
243 * Does the counter have nsecs as a unit?
244 */
daec78a0 245static inline int nsec_counter(struct perf_evsel *evsel)
c04f5e5d 246{
daec78a0
ACM
247 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
248 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
c04f5e5d
IM
249 return 1;
250
251 return 0;
252}
253
8b99b1a4
JO
254static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
255 union perf_event *event,
256 struct perf_sample *sample __maybe_unused,
257 struct machine *machine __maybe_unused)
4979d0c7 258{
8b99b1a4 259 if (perf_data_file__write(&perf_stat.file, event, event->header.size) < 0) {
4979d0c7
JO
260 pr_err("failed to write perf data, error: %m\n");
261 return -1;
262 }
263
8b99b1a4 264 perf_stat.bytes_written += event->header.size;
4979d0c7
JO
265 return 0;
266}
267
1975d36e 268static int write_stat_round_event(u64 tm, u64 type)
7aad0c32 269{
1975d36e 270 return perf_event__synthesize_stat_round(NULL, tm, type,
7aad0c32
JO
271 process_synthesized_event,
272 NULL);
273}
274
275#define WRITE_STAT_ROUND_EVENT(time, interval) \
276 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
277
5a6ea81b
JO
278#define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
279
280static int
281perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
282 struct perf_counts_values *count)
283{
284 struct perf_sample_id *sid = SID(counter, cpu, thread);
285
286 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
287 process_synthesized_event, NULL);
288}
289
f5b4a9c3
SE
290/*
291 * Read out the results of a single counter:
292 * do not aggregate counts across CPUs in system-wide mode
293 */
c52b12ed 294static int read_counter(struct perf_evsel *counter)
f5b4a9c3 295{
9bf1a529 296 int nthreads = thread_map__nr(evsel_list->threads);
00e727bb
MR
297 int ncpus, cpu, thread;
298
299 if (target__has_cpu(&target))
300 ncpus = perf_evsel__nr_cpus(counter);
301 else
302 ncpus = 1;
f5b4a9c3 303
3b4331d9
SP
304 if (!counter->supported)
305 return -ENOENT;
306
9bf1a529
JO
307 if (counter->system_wide)
308 nthreads = 1;
309
310 for (thread = 0; thread < nthreads; thread++) {
311 for (cpu = 0; cpu < ncpus; cpu++) {
3b3eb044
JO
312 struct perf_counts_values *count;
313
314 count = perf_counts(counter->counts, cpu, thread);
315 if (perf_evsel__read(counter, cpu, thread, count))
9bf1a529 316 return -1;
5a6ea81b
JO
317
318 if (STAT_RECORD) {
319 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
320 pr_err("failed to write stat event\n");
321 return -1;
322 }
323 }
0b1abbf4
AK
324
325 if (verbose > 1) {
326 fprintf(stat_config.output,
327 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
328 perf_evsel__name(counter),
329 cpu,
330 count->val, count->ena, count->run);
331 }
9bf1a529 332 }
f5b4a9c3 333 }
c52b12ed
ACM
334
335 return 0;
2996f5dd
IM
336}
337
3df33eff 338static void read_counters(void)
13370a9b 339{
13370a9b 340 struct perf_evsel *counter;
13370a9b 341
e5cadb93 342 evlist__for_each_entry(evsel_list, counter) {
3b3eb044 343 if (read_counter(counter))
245bad8e 344 pr_debug("failed to read counter %s\n", counter->name);
3b3eb044 345
f80010eb 346 if (perf_stat_process_counter(&stat_config, counter))
3b3eb044 347 pr_warning("failed to process counter %s\n", counter->name);
13370a9b 348 }
106a94a0
JO
349}
350
ba411a95 351static void process_interval(void)
106a94a0 352{
106a94a0 353 struct timespec ts, rs;
106a94a0 354
3df33eff 355 read_counters();
86ee6e18 356
13370a9b
SE
357 clock_gettime(CLOCK_MONOTONIC, &ts);
358 diff_timespec(&rs, &ts, &ref_time);
13370a9b 359
7aad0c32 360 if (STAT_RECORD) {
bd48c63e 361 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
7aad0c32
JO
362 pr_err("failed to write stat round event\n");
363 }
364
d4f63a47 365 print_counters(&rs, 0, NULL);
13370a9b
SE
366}
367
67ccdecd 368static void enable_counters(void)
41191688 369{
67ccdecd 370 if (initial_delay)
310ebb93 371 usleep(initial_delay * USEC_PER_MSEC);
67ccdecd
JO
372
373 /*
374 * We need to enable counters only if:
375 * - we don't have tracee (attaching to task or cpu)
376 * - we have initial delay configured
377 */
378 if (!target__none(&target) || initial_delay)
ab46db0a 379 perf_evlist__enable(evsel_list);
41191688
AK
380}
381
3df33eff
MR
382static void disable_counters(void)
383{
384 /*
385 * If we don't have tracee (attaching to task or cpu), counters may
386 * still be running. To get accurate group ratios, we must stop groups
387 * from counting before reading their constituent counters.
388 */
389 if (!target__none(&target))
390 perf_evlist__disable(evsel_list);
391}
392
f33cbe72 393static volatile int workload_exec_errno;
6af206fd
ACM
394
395/*
396 * perf_evlist__prepare_workload will send a SIGUSR1
397 * if the fork fails, since we asked by setting its
398 * want_signal to true.
399 */
f33cbe72
ACM
400static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
401 void *ucontext __maybe_unused)
6af206fd 402{
f33cbe72 403 workload_exec_errno = info->si_value.sival_int;
6af206fd
ACM
404}
405
7b60a7e3
JO
406static bool has_unit(struct perf_evsel *counter)
407{
408 return counter->unit && *counter->unit;
409}
410
411static bool has_scale(struct perf_evsel *counter)
412{
413 return counter->scale != 1;
414}
415
664c98d4 416static int perf_stat_synthesize_config(bool is_pipe)
8b99b1a4 417{
7b60a7e3 418 struct perf_evsel *counter;
8b99b1a4
JO
419 int err;
420
664c98d4
JO
421 if (is_pipe) {
422 err = perf_event__synthesize_attrs(NULL, perf_stat.session,
423 process_synthesized_event);
424 if (err < 0) {
425 pr_err("Couldn't synthesize attrs.\n");
426 return err;
427 }
428 }
429
7b60a7e3
JO
430 /*
431 * Synthesize other events stuff not carried within
432 * attr event - unit, scale, name
433 */
e5cadb93 434 evlist__for_each_entry(evsel_list, counter) {
7b60a7e3
JO
435 if (!counter->supported)
436 continue;
437
438 /*
439 * Synthesize unit and scale only if it's defined.
440 */
441 if (has_unit(counter)) {
442 err = perf_event__synthesize_event_update_unit(NULL, counter, process_synthesized_event);
443 if (err < 0) {
444 pr_err("Couldn't synthesize evsel unit.\n");
445 return err;
446 }
447 }
448
449 if (has_scale(counter)) {
450 err = perf_event__synthesize_event_update_scale(NULL, counter, process_synthesized_event);
451 if (err < 0) {
452 pr_err("Couldn't synthesize evsel scale.\n");
453 return err;
454 }
455 }
456
457 if (counter->own_cpus) {
458 err = perf_event__synthesize_event_update_cpus(NULL, counter, process_synthesized_event);
459 if (err < 0) {
460 pr_err("Couldn't synthesize evsel scale.\n");
461 return err;
462 }
463 }
464
465 /*
466 * Name is needed only for pipe output,
467 * perf.data carries event names.
468 */
469 if (is_pipe) {
470 err = perf_event__synthesize_event_update_name(NULL, counter, process_synthesized_event);
471 if (err < 0) {
472 pr_err("Couldn't synthesize evsel name.\n");
473 return err;
474 }
475 }
476 }
477
8b99b1a4
JO
478 err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
479 process_synthesized_event,
480 NULL);
481 if (err < 0) {
482 pr_err("Couldn't synthesize thread map.\n");
483 return err;
484 }
485
486 err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
487 process_synthesized_event, NULL);
488 if (err < 0) {
489 pr_err("Couldn't synthesize thread map.\n");
490 return err;
491 }
492
493 err = perf_event__synthesize_stat_config(NULL, &stat_config,
494 process_synthesized_event, NULL);
495 if (err < 0) {
496 pr_err("Couldn't synthesize config.\n");
497 return err;
498 }
499
500 return 0;
501}
502
2af4646d
JO
503#define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
504
505static int __store_counter_ids(struct perf_evsel *counter,
506 struct cpu_map *cpus,
507 struct thread_map *threads)
508{
509 int cpu, thread;
510
511 for (cpu = 0; cpu < cpus->nr; cpu++) {
512 for (thread = 0; thread < threads->nr; thread++) {
513 int fd = FD(counter, cpu, thread);
514
515 if (perf_evlist__id_add_fd(evsel_list, counter,
516 cpu, thread, fd) < 0)
517 return -1;
518 }
519 }
520
521 return 0;
522}
523
524static int store_counter_ids(struct perf_evsel *counter)
525{
526 struct cpu_map *cpus = counter->cpus;
527 struct thread_map *threads = counter->threads;
528
529 if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
530 return -ENOMEM;
531
532 return __store_counter_ids(counter, cpus, threads);
533}
534
acf28922 535static int __run_perf_stat(int argc, const char **argv)
42202dd5 536{
ec0d3d1f 537 int interval = stat_config.interval;
d6195a6a 538 char msg[BUFSIZ];
42202dd5 539 unsigned long long t0, t1;
cac21425 540 struct perf_evsel *counter;
13370a9b 541 struct timespec ts;
410136f5 542 size_t l;
42202dd5 543 int status = 0;
6be2850e 544 const bool forks = (argc > 0);
664c98d4 545 bool is_pipe = STAT_RECORD ? perf_stat.file.is_pipe : false;
5d8bb1ec 546 struct perf_evsel_config_term *err_term;
42202dd5 547
13370a9b 548 if (interval) {
310ebb93
ACM
549 ts.tv_sec = interval / USEC_PER_MSEC;
550 ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
13370a9b
SE
551 } else {
552 ts.tv_sec = 1;
553 ts.tv_nsec = 0;
554 }
555
60666c63 556 if (forks) {
664c98d4 557 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
735f7e0b 558 workload_exec_failed_signal) < 0) {
acf28922
NK
559 perror("failed to prepare workload");
560 return -1;
60666c63 561 }
d20a47e7 562 child_pid = evsel_list->workload.pid;
051ae7f7
PM
563 }
564
6a4bb04c 565 if (group)
63dab225 566 perf_evlist__set_leader(evsel_list);
6a4bb04c 567
e5cadb93 568 evlist__for_each_entry(evsel_list, counter) {
42ef8a78 569try_again:
cac21425 570 if (create_perf_stat_counter(counter) < 0) {
979987a5
DA
571 /*
572 * PPC returns ENXIO for HW counters until 2.6.37
573 * (behavior changed with commit b0a873e).
574 */
38f6ae1e 575 if (errno == EINVAL || errno == ENOSYS ||
979987a5
DA
576 errno == ENOENT || errno == EOPNOTSUPP ||
577 errno == ENXIO) {
bb963e16 578 if (verbose > 0)
c63ca0c0 579 ui__warning("%s event is not supported by the kernel.\n",
7289f83c 580 perf_evsel__name(counter));
2cee77c4 581 counter->supported = false;
cb5ef600
KL
582
583 if ((counter->leader != counter) ||
584 !(counter->leader->nr_members > 1))
585 continue;
42ef8a78 586 } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
bb963e16 587 if (verbose > 0)
42ef8a78
ACM
588 ui__warning("%s\n", msg);
589 goto try_again;
590 }
ede70290 591
56e52e85
ACM
592 perf_evsel__open_strerror(counter, &target,
593 errno, msg, sizeof(msg));
594 ui__error("%s\n", msg);
595
48290609
ACM
596 if (child_pid != -1)
597 kill(child_pid, SIGTERM);
fceda7fe 598
48290609
ACM
599 return -1;
600 }
2cee77c4 601 counter->supported = true;
410136f5
SE
602
603 l = strlen(counter->unit);
604 if (l > unit_width)
605 unit_width = l;
2af4646d
JO
606
607 if (STAT_RECORD && store_counter_ids(counter))
608 return -1;
084ab9f8 609 }
42202dd5 610
23d4aad4
ACM
611 if (perf_evlist__apply_filters(evsel_list, &counter)) {
612 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
613 counter->filter, perf_evsel__name(counter), errno,
c8b5f2c9 614 str_error_r(errno, msg, sizeof(msg)));
cfd748ae
FW
615 return -1;
616 }
617
5d8bb1ec
MP
618 if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
619 error("failed to set config \"%s\" on event %s with %d (%s)\n",
620 err_term->val.drv_cfg, perf_evsel__name(counter), errno,
621 str_error_r(errno, msg, sizeof(msg)));
622 return -1;
623 }
624
4979d0c7
JO
625 if (STAT_RECORD) {
626 int err, fd = perf_data_file__fd(&perf_stat.file);
627
664c98d4
JO
628 if (is_pipe) {
629 err = perf_header__write_pipe(perf_data_file__fd(&perf_stat.file));
630 } else {
631 err = perf_session__write_header(perf_stat.session, evsel_list,
632 fd, false);
633 }
634
4979d0c7
JO
635 if (err < 0)
636 return err;
8b99b1a4 637
664c98d4 638 err = perf_stat_synthesize_config(is_pipe);
8b99b1a4
JO
639 if (err < 0)
640 return err;
4979d0c7
JO
641 }
642
42202dd5
IM
643 /*
644 * Enable counters and exec the command:
645 */
646 t0 = rdclock();
13370a9b 647 clock_gettime(CLOCK_MONOTONIC, &ref_time);
42202dd5 648
60666c63 649 if (forks) {
acf28922 650 perf_evlist__start_workload(evsel_list);
67ccdecd 651 enable_counters();
acf28922 652
13370a9b
SE
653 if (interval) {
654 while (!waitpid(child_pid, &status, WNOHANG)) {
655 nanosleep(&ts, NULL);
ba411a95 656 process_interval();
13370a9b
SE
657 }
658 }
60666c63 659 wait(&status);
6af206fd 660
f33cbe72 661 if (workload_exec_errno) {
c8b5f2c9 662 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
f33cbe72 663 pr_err("Workload failed: %s\n", emsg);
6af206fd 664 return -1;
f33cbe72 665 }
6af206fd 666
33e49ea7
AK
667 if (WIFSIGNALED(status))
668 psignal(WTERMSIG(status), argv[0]);
60666c63 669 } else {
67ccdecd 670 enable_counters();
13370a9b
SE
671 while (!done) {
672 nanosleep(&ts, NULL);
673 if (interval)
ba411a95 674 process_interval();
13370a9b 675 }
60666c63 676 }
42202dd5 677
3df33eff
MR
678 disable_counters();
679
42202dd5
IM
680 t1 = rdclock();
681
9e9772c4 682 update_stats(&walltime_nsecs_stats, t1 - t0);
42202dd5 683
3df33eff
MR
684 /*
685 * Closing a group leader splits the group, and as we only disable
686 * group leaders, results in remaining events becoming enabled. To
687 * avoid arbitrary skew, we must read all counters before closing any
688 * group leaders.
689 */
690 read_counters();
691 perf_evlist__close(evsel_list);
c52b12ed 692
42202dd5
IM
693 return WEXITSTATUS(status);
694}
695
41cde476 696static int run_perf_stat(int argc, const char **argv)
1f16c575
PZ
697{
698 int ret;
699
700 if (pre_cmd) {
701 ret = system(pre_cmd);
702 if (ret)
703 return ret;
704 }
705
706 if (sync_run)
707 sync();
708
709 ret = __run_perf_stat(argc, argv);
710 if (ret)
711 return ret;
712
713 if (post_cmd) {
714 ret = system(post_cmd);
715 if (ret)
716 return ret;
717 }
718
719 return ret;
720}
721
d73515c0
AK
722static void print_running(u64 run, u64 ena)
723{
724 if (csv_output) {
5821522e 725 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
d73515c0
AK
726 csv_sep,
727 run,
728 csv_sep,
729 ena ? 100.0 * run / ena : 100.0);
730 } else if (run != ena) {
5821522e 731 fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena);
d73515c0
AK
732 }
733}
734
f99844cb
IM
735static void print_noise_pct(double total, double avg)
736{
0007ecea 737 double pct = rel_stddev_stats(total, avg);
f99844cb 738
3ae9a34d 739 if (csv_output)
5821522e 740 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
a1bca6cc 741 else if (pct)
5821522e 742 fprintf(stat_config.output, " ( +-%6.2f%% )", pct);
f99844cb
IM
743}
744
69aad6f1 745static void print_noise(struct perf_evsel *evsel, double avg)
42202dd5 746{
581cc8a2 747 struct perf_stat_evsel *ps;
69aad6f1 748
849abde9
PZ
749 if (run_count == 1)
750 return;
751
69aad6f1 752 ps = evsel->priv;
f99844cb 753 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
42202dd5
IM
754}
755
12c08a9f 756static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
44175b6f 757{
421a50f3 758 switch (stat_config.aggr_mode) {
12c08a9f 759 case AGGR_CORE:
5821522e 760 fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
12c08a9f
SE
761 cpu_map__id_to_socket(id),
762 csv_output ? 0 : -8,
763 cpu_map__id_to_cpu(id),
764 csv_sep,
765 csv_output ? 0 : 4,
766 nr,
767 csv_sep);
768 break;
86ee6e18 769 case AGGR_SOCKET:
5821522e 770 fprintf(stat_config.output, "S%*d%s%*d%s",
d7e7a451 771 csv_output ? 0 : -5,
12c08a9f 772 id,
d7e7a451
SE
773 csv_sep,
774 csv_output ? 0 : 4,
775 nr,
776 csv_sep);
86ee6e18
SE
777 break;
778 case AGGR_NONE:
5821522e 779 fprintf(stat_config.output, "CPU%*d%s",
d7470b6a 780 csv_output ? 0 : -4,
12c08a9f 781 perf_evsel__cpus(evsel)->map[id], csv_sep);
86ee6e18 782 break;
32b8af82 783 case AGGR_THREAD:
5821522e 784 fprintf(stat_config.output, "%*s-%*d%s",
32b8af82
JO
785 csv_output ? 0 : 16,
786 thread_map__comm(evsel->threads, id),
787 csv_output ? 0 : -8,
788 thread_map__pid(evsel->threads, id),
789 csv_sep);
790 break;
86ee6e18 791 case AGGR_GLOBAL:
208df99e 792 case AGGR_UNSET:
86ee6e18
SE
793 default:
794 break;
795 }
796}
797
140aeadc
AK
798struct outstate {
799 FILE *fh;
800 bool newline;
f9483392 801 const char *prefix;
92a61f64 802 int nfields;
44d49a60
AK
803 int id, nr;
804 struct perf_evsel *evsel;
140aeadc
AK
805};
806
807#define METRIC_LEN 35
808
809static void new_line_std(void *ctx)
810{
811 struct outstate *os = ctx;
812
813 os->newline = true;
814}
815
816static void do_new_line_std(struct outstate *os)
817{
818 fputc('\n', os->fh);
f9483392 819 fputs(os->prefix, os->fh);
44d49a60 820 aggr_printout(os->evsel, os->id, os->nr);
140aeadc
AK
821 if (stat_config.aggr_mode == AGGR_NONE)
822 fprintf(os->fh, " ");
140aeadc
AK
823 fprintf(os->fh, " ");
824}
825
826static void print_metric_std(void *ctx, const char *color, const char *fmt,
827 const char *unit, double val)
828{
829 struct outstate *os = ctx;
830 FILE *out = os->fh;
831 int n;
832 bool newline = os->newline;
833
834 os->newline = false;
835
836 if (unit == NULL || fmt == NULL) {
837 fprintf(out, "%-*s", METRIC_LEN, "");
838 return;
839 }
840
841 if (newline)
842 do_new_line_std(os);
843
844 n = fprintf(out, " # ");
845 if (color)
846 n += color_fprintf(out, color, fmt, val);
847 else
848 n += fprintf(out, fmt, val);
849 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
850}
851
92a61f64
AK
852static void new_line_csv(void *ctx)
853{
854 struct outstate *os = ctx;
855 int i;
856
857 fputc('\n', os->fh);
858 if (os->prefix)
859 fprintf(os->fh, "%s%s", os->prefix, csv_sep);
44d49a60 860 aggr_printout(os->evsel, os->id, os->nr);
92a61f64
AK
861 for (i = 0; i < os->nfields; i++)
862 fputs(csv_sep, os->fh);
863}
864
865static void print_metric_csv(void *ctx,
866 const char *color __maybe_unused,
867 const char *fmt, const char *unit, double val)
868{
869 struct outstate *os = ctx;
870 FILE *out = os->fh;
871 char buf[64], *vals, *ends;
872
873 if (unit == NULL || fmt == NULL) {
874 fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
875 return;
876 }
877 snprintf(buf, sizeof(buf), fmt, val);
878 vals = buf;
879 while (isspace(*vals))
880 vals++;
881 ends = vals;
882 while (isdigit(*ends) || *ends == '.')
883 ends++;
884 *ends = 0;
885 while (isspace(*unit))
886 unit++;
887 fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
888}
889
54b50916
AK
890#define METRIC_ONLY_LEN 20
891
892/* Filter out some columns that don't work well in metrics only mode */
893
894static bool valid_only_metric(const char *unit)
895{
896 if (!unit)
897 return false;
898 if (strstr(unit, "/sec") ||
899 strstr(unit, "hz") ||
900 strstr(unit, "Hz") ||
901 strstr(unit, "CPUs utilized"))
902 return false;
903 return true;
904}
905
906static const char *fixunit(char *buf, struct perf_evsel *evsel,
907 const char *unit)
908{
909 if (!strncmp(unit, "of all", 6)) {
910 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
911 unit);
912 return buf;
913 }
914 return unit;
915}
916
917static void print_metric_only(void *ctx, const char *color, const char *fmt,
918 const char *unit, double val)
919{
920 struct outstate *os = ctx;
921 FILE *out = os->fh;
922 int n;
923 char buf[1024];
924 unsigned mlen = METRIC_ONLY_LEN;
925
926 if (!valid_only_metric(unit))
927 return;
928 unit = fixunit(buf, os->evsel, unit);
929 if (color)
930 n = color_fprintf(out, color, fmt, val);
931 else
932 n = fprintf(out, fmt, val);
933 if (n > METRIC_ONLY_LEN)
934 n = METRIC_ONLY_LEN;
935 if (mlen < strlen(unit))
936 mlen = strlen(unit) + 1;
937 fprintf(out, "%*s", mlen - n, "");
938}
939
940static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
941 const char *fmt,
942 const char *unit, double val)
943{
944 struct outstate *os = ctx;
945 FILE *out = os->fh;
946 char buf[64], *vals, *ends;
947 char tbuf[1024];
948
949 if (!valid_only_metric(unit))
950 return;
951 unit = fixunit(tbuf, os->evsel, unit);
952 snprintf(buf, sizeof buf, fmt, val);
953 vals = buf;
954 while (isspace(*vals))
955 vals++;
956 ends = vals;
957 while (isdigit(*ends) || *ends == '.')
958 ends++;
959 *ends = 0;
960 fprintf(out, "%s%s", vals, csv_sep);
961}
962
963static void new_line_metric(void *ctx __maybe_unused)
964{
965}
966
967static void print_metric_header(void *ctx, const char *color __maybe_unused,
968 const char *fmt __maybe_unused,
969 const char *unit, double val __maybe_unused)
970{
971 struct outstate *os = ctx;
972 char tbuf[1024];
973
974 if (!valid_only_metric(unit))
975 return;
976 unit = fixunit(tbuf, os->evsel, unit);
977 if (csv_output)
978 fprintf(os->fh, "%s%s", unit, csv_sep);
979 else
980 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
981}
982
da88c7f7 983static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
86ee6e18 984{
5821522e 985 FILE *output = stat_config.output;
310ebb93 986 double msecs = avg / NSEC_PER_MSEC;
410136f5 987 const char *fmt_v, *fmt_n;
4bbe5a61 988 char name[25];
86ee6e18 989
410136f5
SE
990 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
991 fmt_n = csv_output ? "%s" : "%-25s";
992
da88c7f7 993 aggr_printout(evsel, id, nr);
d7470b6a 994
4bbe5a61
DA
995 scnprintf(name, sizeof(name), "%s%s",
996 perf_evsel__name(evsel), csv_output ? "" : " (msec)");
410136f5
SE
997
998 fprintf(output, fmt_v, msecs, csv_sep);
999
1000 if (csv_output)
1001 fprintf(output, "%s%s", evsel->unit, csv_sep);
1002 else
1003 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
1004
1005 fprintf(output, fmt_n, name);
d7470b6a 1006
023695d9 1007 if (evsel->cgrp)
4aa9015f 1008 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
44175b6f
IM
1009}
1010
44d49a60
AK
1011static int first_shadow_cpu(struct perf_evsel *evsel, int id)
1012{
1013 int i;
1014
1015 if (!aggr_get_id)
1016 return 0;
1017
1018 if (stat_config.aggr_mode == AGGR_NONE)
1019 return id;
1020
1021 if (stat_config.aggr_mode == AGGR_GLOBAL)
1022 return 0;
1023
1024 for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
1025 int cpu2 = perf_evsel__cpus(evsel)->map[i];
1026
1027 if (aggr_get_id(evsel_list->cpus, cpu2) == id)
1028 return cpu2;
1029 }
1030 return 0;
1031}
1032
556b1fb7
JO
1033static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1034{
5821522e 1035 FILE *output = stat_config.output;
556b1fb7
JO
1036 double sc = evsel->scale;
1037 const char *fmt;
556b1fb7
JO
1038
1039 if (csv_output) {
e3b03b6c 1040 fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
556b1fb7
JO
1041 } else {
1042 if (big_num)
e3b03b6c 1043 fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
556b1fb7 1044 else
e3b03b6c 1045 fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
556b1fb7
JO
1046 }
1047
1048 aggr_printout(evsel, id, nr);
1049
556b1fb7
JO
1050 fprintf(output, fmt, avg, csv_sep);
1051
1052 if (evsel->unit)
1053 fprintf(output, "%-*s%s",
1054 csv_output ? 0 : unit_width,
1055 evsel->unit, csv_sep);
1056
1057 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1058
1059 if (evsel->cgrp)
1060 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
eedfcb4b 1061}
556b1fb7 1062
f9483392 1063static void printout(int id, int nr, struct perf_evsel *counter, double uval,
cb110f47 1064 char *prefix, u64 run, u64 ena, double noise)
eedfcb4b 1065{
140aeadc 1066 struct perf_stat_output_ctx out;
f9483392
AK
1067 struct outstate os = {
1068 .fh = stat_config.output,
44d49a60
AK
1069 .prefix = prefix ? prefix : "",
1070 .id = id,
1071 .nr = nr,
1072 .evsel = counter,
f9483392 1073 };
140aeadc
AK
1074 print_metric_t pm = print_metric_std;
1075 void (*nl)(void *);
eedfcb4b 1076
54b50916
AK
1077 if (metric_only) {
1078 nl = new_line_metric;
1079 if (csv_output)
1080 pm = print_metric_only_csv;
1081 else
1082 pm = print_metric_only;
1083 } else
1084 nl = new_line_std;
eedfcb4b 1085
54b50916 1086 if (csv_output && !metric_only) {
92a61f64
AK
1087 static int aggr_fields[] = {
1088 [AGGR_GLOBAL] = 0,
1089 [AGGR_THREAD] = 1,
1090 [AGGR_NONE] = 1,
1091 [AGGR_SOCKET] = 2,
1092 [AGGR_CORE] = 2,
1093 };
1094
1095 pm = print_metric_csv;
1096 nl = new_line_csv;
1097 os.nfields = 3;
1098 os.nfields += aggr_fields[stat_config.aggr_mode];
1099 if (counter->cgrp)
1100 os.nfields++;
1101 }
b002f3bb 1102 if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
54b50916
AK
1103 if (metric_only) {
1104 pm(&os, NULL, "", "", 0);
1105 return;
1106 }
cb110f47
AK
1107 aggr_printout(counter, id, nr);
1108
1109 fprintf(stat_config.output, "%*s%s",
1110 csv_output ? 0 : 18,
1111 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1112 csv_sep);
1113
02d492e5
BP
1114 if (counter->supported)
1115 print_free_counters_hint = 1;
1116
cb110f47
AK
1117 fprintf(stat_config.output, "%-*s%s",
1118 csv_output ? 0 : unit_width,
1119 counter->unit, csv_sep);
1120
1121 fprintf(stat_config.output, "%*s",
1122 csv_output ? 0 : -25,
1123 perf_evsel__name(counter));
1124
1125 if (counter->cgrp)
1126 fprintf(stat_config.output, "%s%s",
1127 csv_sep, counter->cgrp->name);
1128
92a61f64
AK
1129 if (!csv_output)
1130 pm(&os, NULL, NULL, "", 0);
1131 print_noise(counter, noise);
cb110f47 1132 print_running(run, ena);
92a61f64
AK
1133 if (csv_output)
1134 pm(&os, NULL, NULL, "", 0);
cb110f47
AK
1135 return;
1136 }
1137
54b50916
AK
1138 if (metric_only)
1139 /* nothing */;
1140 else if (nsec_counter(counter))
eedfcb4b
AK
1141 nsec_printout(id, nr, counter, uval);
1142 else
1143 abs_printout(id, nr, counter, uval);
556b1fb7 1144
140aeadc
AK
1145 out.print_metric = pm;
1146 out.new_line = nl;
1147 out.ctx = &os;
1148
54b50916 1149 if (csv_output && !metric_only) {
92a61f64
AK
1150 print_noise(counter, noise);
1151 print_running(run, ena);
1152 }
1153
1154 perf_stat__print_shadow_stats(counter, uval,
44d49a60 1155 first_shadow_cpu(counter, id),
140aeadc 1156 &out);
54b50916 1157 if (!csv_output && !metric_only) {
92a61f64
AK
1158 print_noise(counter, noise);
1159 print_running(run, ena);
1160 }
556b1fb7
JO
1161}
1162
44d49a60
AK
1163static void aggr_update_shadow(void)
1164{
1165 int cpu, s2, id, s;
1166 u64 val;
1167 struct perf_evsel *counter;
1168
1169 for (s = 0; s < aggr_map->nr; s++) {
1170 id = aggr_map->map[s];
e5cadb93 1171 evlist__for_each_entry(evsel_list, counter) {
44d49a60
AK
1172 val = 0;
1173 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1174 s2 = aggr_get_id(evsel_list->cpus, cpu);
1175 if (s2 != id)
1176 continue;
1177 val += perf_counts(counter->counts, cpu, 0)->val;
1178 }
1179 val = val * counter->scale;
1180 perf_stat__update_shadow_stats(counter, &val,
1181 first_shadow_cpu(counter, id));
1182 }
1183 }
1184}
1185
430daf2d 1186static void collect_all_aliases(struct perf_evsel *counter,
fbe51fba
AK
1187 void (*cb)(struct perf_evsel *counter, void *data,
1188 bool first),
1189 void *data)
1190{
430daf2d
AK
1191 struct perf_evsel *alias;
1192
1193 alias = list_prepare_entry(counter, &(evsel_list->entries), node);
1194 list_for_each_entry_continue (alias, &evsel_list->entries, node) {
1195 if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
1196 alias->scale != counter->scale ||
1197 alias->cgrp != counter->cgrp ||
1198 strcmp(alias->unit, counter->unit) ||
1199 nsec_counter(alias) != nsec_counter(counter))
1200 break;
1201 alias->merged_stat = true;
1202 cb(alias, data, false);
1203 }
1204}
1205
1206static bool collect_data(struct perf_evsel *counter,
1207 void (*cb)(struct perf_evsel *counter, void *data,
1208 bool first),
1209 void *data)
1210{
1211 if (counter->merged_stat)
1212 return false;
fbe51fba 1213 cb(counter, data, true);
430daf2d
AK
1214 if (!no_merge)
1215 collect_all_aliases(counter, cb, data);
1216 return true;
fbe51fba
AK
1217}
1218
1219struct aggr_data {
1220 u64 ena, run, val;
1221 int id;
1222 int nr;
1223 int cpu;
1224};
1225
1226static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
1227{
1228 struct aggr_data *ad = data;
1229 int cpu, s2;
1230
1231 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1232 struct perf_counts_values *counts;
1233
1234 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1235 if (s2 != ad->id)
1236 continue;
1237 if (first)
1238 ad->nr++;
1239 counts = perf_counts(counter->counts, cpu, 0);
1240 ad->val += counts->val;
1241 ad->ena += counts->ena;
1242 ad->run += counts->run;
1243 }
1244}
1245
86ee6e18 1246static void print_aggr(char *prefix)
d7e7a451 1247{
5821522e 1248 FILE *output = stat_config.output;
d7e7a451 1249 struct perf_evsel *counter;
fbe51fba 1250 int s, id, nr;
410136f5 1251 double uval;
d7e7a451 1252 u64 ena, run, val;
54b50916 1253 bool first;
d7e7a451 1254
86ee6e18 1255 if (!(aggr_map || aggr_get_id))
d7e7a451
SE
1256 return;
1257
44d49a60
AK
1258 aggr_update_shadow();
1259
54b50916
AK
1260 /*
1261 * With metric_only everything is on a single line.
1262 * Without each counter has its own line.
1263 */
86ee6e18 1264 for (s = 0; s < aggr_map->nr; s++) {
fbe51fba 1265 struct aggr_data ad;
54b50916
AK
1266 if (prefix && metric_only)
1267 fprintf(output, "%s", prefix);
1268
fbe51fba 1269 ad.id = id = aggr_map->map[s];
54b50916 1270 first = true;
e5cadb93 1271 evlist__for_each_entry(evsel_list, counter) {
fbe51fba
AK
1272 ad.val = ad.ena = ad.run = 0;
1273 ad.nr = 0;
430daf2d
AK
1274 if (!collect_data(counter, aggr_cb, &ad))
1275 continue;
fbe51fba
AK
1276 nr = ad.nr;
1277 ena = ad.ena;
1278 run = ad.run;
1279 val = ad.val;
54b50916
AK
1280 if (first && metric_only) {
1281 first = false;
1282 aggr_printout(counter, id, nr);
1283 }
1284 if (prefix && !metric_only)
d7e7a451
SE
1285 fprintf(output, "%s", prefix);
1286
410136f5 1287 uval = val * counter->scale;
cb110f47 1288 printout(id, nr, counter, uval, prefix, run, ena, 1.0);
54b50916
AK
1289 if (!metric_only)
1290 fputc('\n', output);
d7e7a451 1291 }
54b50916
AK
1292 if (metric_only)
1293 fputc('\n', output);
d7e7a451
SE
1294 }
1295}
1296
32b8af82
JO
1297static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1298{
5821522e 1299 FILE *output = stat_config.output;
32b8af82
JO
1300 int nthreads = thread_map__nr(counter->threads);
1301 int ncpus = cpu_map__nr(counter->cpus);
1302 int cpu, thread;
1303 double uval;
1304
1305 for (thread = 0; thread < nthreads; thread++) {
1306 u64 ena = 0, run = 0, val = 0;
1307
1308 for (cpu = 0; cpu < ncpus; cpu++) {
1309 val += perf_counts(counter->counts, cpu, thread)->val;
1310 ena += perf_counts(counter->counts, cpu, thread)->ena;
1311 run += perf_counts(counter->counts, cpu, thread)->run;
1312 }
1313
1314 if (prefix)
1315 fprintf(output, "%s", prefix);
1316
1317 uval = val * counter->scale;
cb110f47 1318 printout(thread, 0, counter, uval, prefix, run, ena, 1.0);
32b8af82
JO
1319 fputc('\n', output);
1320 }
1321}
1322
fbe51fba
AK
1323struct caggr_data {
1324 double avg, avg_enabled, avg_running;
1325};
1326
1327static void counter_aggr_cb(struct perf_evsel *counter, void *data,
1328 bool first __maybe_unused)
1329{
1330 struct caggr_data *cd = data;
1331 struct perf_stat_evsel *ps = counter->priv;
1332
1333 cd->avg += avg_stats(&ps->res_stats[0]);
1334 cd->avg_enabled += avg_stats(&ps->res_stats[1]);
1335 cd->avg_running += avg_stats(&ps->res_stats[2]);
1336}
1337
2996f5dd
IM
1338/*
1339 * Print out the results of a single counter:
f5b4a9c3 1340 * aggregated counts in system-wide mode
2996f5dd 1341 */
13370a9b 1342static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
2996f5dd 1343{
5821522e 1344 FILE *output = stat_config.output;
410136f5 1345 double uval;
fbe51fba 1346 struct caggr_data cd = { .avg = 0.0 };
d73515c0 1347
430daf2d
AK
1348 if (!collect_data(counter, counter_aggr_cb, &cd))
1349 return;
2996f5dd 1350
54b50916 1351 if (prefix && !metric_only)
13370a9b
SE
1352 fprintf(output, "%s", prefix);
1353
fbe51fba
AK
1354 uval = cd.avg * counter->scale;
1355 printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled, cd.avg);
54b50916
AK
1356 if (!metric_only)
1357 fprintf(output, "\n");
c04f5e5d
IM
1358}
1359
fbe51fba
AK
1360static void counter_cb(struct perf_evsel *counter, void *data,
1361 bool first __maybe_unused)
1362{
1363 struct aggr_data *ad = data;
1364
1365 ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
1366 ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
1367 ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
1368}
1369
f5b4a9c3
SE
1370/*
1371 * Print out the results of a single counter:
1372 * does not use aggregated count in system-wide
1373 */
13370a9b 1374static void print_counter(struct perf_evsel *counter, char *prefix)
f5b4a9c3 1375{
5821522e 1376 FILE *output = stat_config.output;
f5b4a9c3 1377 u64 ena, run, val;
410136f5 1378 double uval;
f5b4a9c3
SE
1379 int cpu;
1380
7ae92e74 1381 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
fbe51fba
AK
1382 struct aggr_data ad = { .cpu = cpu };
1383
430daf2d
AK
1384 if (!collect_data(counter, counter_cb, &ad))
1385 return;
fbe51fba
AK
1386 val = ad.val;
1387 ena = ad.ena;
1388 run = ad.run;
13370a9b
SE
1389
1390 if (prefix)
1391 fprintf(output, "%s", prefix);
1392
410136f5 1393 uval = val * counter->scale;
cb110f47 1394 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
f5b4a9c3 1395
4aa9015f 1396 fputc('\n', output);
f5b4a9c3
SE
1397 }
1398}
1399
206cab65
AK
1400static void print_no_aggr_metric(char *prefix)
1401{
1402 int cpu;
1403 int nrcpus = 0;
1404 struct perf_evsel *counter;
1405 u64 ena, run, val;
1406 double uval;
1407
1408 nrcpus = evsel_list->cpus->nr;
1409 for (cpu = 0; cpu < nrcpus; cpu++) {
1410 bool first = true;
1411
1412 if (prefix)
1413 fputs(prefix, stat_config.output);
e5cadb93 1414 evlist__for_each_entry(evsel_list, counter) {
206cab65
AK
1415 if (first) {
1416 aggr_printout(counter, cpu, 0);
1417 first = false;
1418 }
1419 val = perf_counts(counter->counts, cpu, 0)->val;
1420 ena = perf_counts(counter->counts, cpu, 0)->ena;
1421 run = perf_counts(counter->counts, cpu, 0)->run;
1422
1423 uval = val * counter->scale;
1424 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0);
1425 }
1426 fputc('\n', stat_config.output);
1427 }
1428}
1429
54b50916
AK
1430static int aggr_header_lens[] = {
1431 [AGGR_CORE] = 18,
1432 [AGGR_SOCKET] = 12,
206cab65 1433 [AGGR_NONE] = 6,
54b50916
AK
1434 [AGGR_THREAD] = 24,
1435 [AGGR_GLOBAL] = 0,
1436};
1437
c51fd639
AK
1438static const char *aggr_header_csv[] = {
1439 [AGGR_CORE] = "core,cpus,",
1440 [AGGR_SOCKET] = "socket,cpus",
1441 [AGGR_NONE] = "cpu,",
1442 [AGGR_THREAD] = "comm-pid,",
1443 [AGGR_GLOBAL] = ""
1444};
1445
41c8ca2a 1446static void print_metric_headers(const char *prefix, bool no_indent)
54b50916
AK
1447{
1448 struct perf_stat_output_ctx out;
1449 struct perf_evsel *counter;
1450 struct outstate os = {
1451 .fh = stat_config.output
1452 };
1453
1454 if (prefix)
1455 fprintf(stat_config.output, "%s", prefix);
1456
41c8ca2a 1457 if (!csv_output && !no_indent)
54b50916
AK
1458 fprintf(stat_config.output, "%*s",
1459 aggr_header_lens[stat_config.aggr_mode], "");
c51fd639
AK
1460 if (csv_output) {
1461 if (stat_config.interval)
1462 fputs("time,", stat_config.output);
1463 fputs(aggr_header_csv[stat_config.aggr_mode],
1464 stat_config.output);
1465 }
54b50916
AK
1466
1467 /* Print metrics headers only */
e5cadb93 1468 evlist__for_each_entry(evsel_list, counter) {
54b50916
AK
1469 os.evsel = counter;
1470 out.ctx = &os;
1471 out.print_metric = print_metric_header;
1472 out.new_line = new_line_metric;
1473 os.evsel = counter;
1474 perf_stat__print_shadow_stats(counter, 0,
1475 0,
1476 &out);
1477 }
1478 fputc('\n', stat_config.output);
1479}
1480
d4f63a47
JO
1481static void print_interval(char *prefix, struct timespec *ts)
1482{
5821522e 1483 FILE *output = stat_config.output;
d4f63a47
JO
1484 static int num_print_interval;
1485
1486 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1487
41c8ca2a 1488 if (num_print_interval == 0 && !csv_output) {
421a50f3 1489 switch (stat_config.aggr_mode) {
d4f63a47 1490 case AGGR_SOCKET:
41c8ca2a
AK
1491 fprintf(output, "# time socket cpus");
1492 if (!metric_only)
1493 fprintf(output, " counts %*s events\n", unit_width, "unit");
d4f63a47
JO
1494 break;
1495 case AGGR_CORE:
41c8ca2a
AK
1496 fprintf(output, "# time core cpus");
1497 if (!metric_only)
1498 fprintf(output, " counts %*s events\n", unit_width, "unit");
d4f63a47
JO
1499 break;
1500 case AGGR_NONE:
41c8ca2a
AK
1501 fprintf(output, "# time CPU");
1502 if (!metric_only)
1503 fprintf(output, " counts %*s events\n", unit_width, "unit");
d4f63a47 1504 break;
32b8af82 1505 case AGGR_THREAD:
41c8ca2a
AK
1506 fprintf(output, "# time comm-pid");
1507 if (!metric_only)
1508 fprintf(output, " counts %*s events\n", unit_width, "unit");
32b8af82 1509 break;
d4f63a47
JO
1510 case AGGR_GLOBAL:
1511 default:
41c8ca2a
AK
1512 fprintf(output, "# time");
1513 if (!metric_only)
1514 fprintf(output, " counts %*s events\n", unit_width, "unit");
208df99e
JO
1515 case AGGR_UNSET:
1516 break;
d4f63a47
JO
1517 }
1518 }
1519
41c8ca2a
AK
1520 if (num_print_interval == 0 && metric_only)
1521 print_metric_headers(" ", true);
d4f63a47
JO
1522 if (++num_print_interval == 25)
1523 num_print_interval = 0;
1524}
1525
1526static void print_header(int argc, const char **argv)
42202dd5 1527{
5821522e 1528 FILE *output = stat_config.output;
69aad6f1 1529 int i;
42202dd5 1530
ddcacfa0
IM
1531 fflush(stdout);
1532
d7470b6a 1533 if (!csv_output) {
4aa9015f
SE
1534 fprintf(output, "\n");
1535 fprintf(output, " Performance counter stats for ");
62d3b617
DA
1536 if (target.system_wide)
1537 fprintf(output, "\'system wide");
1538 else if (target.cpu_list)
1539 fprintf(output, "\'CPU(s) %s", target.cpu_list);
602ad878 1540 else if (!target__has_task(&target)) {
ba6039b6
JO
1541 fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1542 for (i = 1; argv && (i < argc); i++)
4aa9015f 1543 fprintf(output, " %s", argv[i]);
20f946b4
NK
1544 } else if (target.pid)
1545 fprintf(output, "process id \'%s", target.pid);
d7470b6a 1546 else
20f946b4 1547 fprintf(output, "thread id \'%s", target.tid);
44db76c8 1548
4aa9015f 1549 fprintf(output, "\'");
d7470b6a 1550 if (run_count > 1)
4aa9015f
SE
1551 fprintf(output, " (%d runs)", run_count);
1552 fprintf(output, ":\n\n");
d7470b6a 1553 }
d4f63a47
JO
1554}
1555
1556static void print_footer(void)
1557{
5821522e
JO
1558 FILE *output = stat_config.output;
1559
d4f63a47
JO
1560 if (!null_run)
1561 fprintf(output, "\n");
1562 fprintf(output, " %17.9f seconds time elapsed",
310ebb93 1563 avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
d4f63a47
JO
1564 if (run_count > 1) {
1565 fprintf(output, " ");
1566 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1567 avg_stats(&walltime_nsecs_stats));
1568 }
1569 fprintf(output, "\n\n");
02d492e5
BP
1570
1571 if (print_free_counters_hint)
1572 fprintf(output,
1573"Some events weren't counted. Try disabling the NMI watchdog:\n"
1574" echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1575" perf stat ...\n"
1576" echo 1 > /proc/sys/kernel/nmi_watchdog\n");
d4f63a47
JO
1577}
1578
1579static void print_counters(struct timespec *ts, int argc, const char **argv)
1580{
ec0d3d1f 1581 int interval = stat_config.interval;
d4f63a47
JO
1582 struct perf_evsel *counter;
1583 char buf[64], *prefix = NULL;
1584
664c98d4
JO
1585 /* Do not print anything if we record to the pipe. */
1586 if (STAT_RECORD && perf_stat.file.is_pipe)
1587 return;
1588
d4f63a47
JO
1589 if (interval)
1590 print_interval(prefix = buf, ts);
1591 else
1592 print_header(argc, argv);
2996f5dd 1593
54b50916
AK
1594 if (metric_only) {
1595 static int num_print_iv;
1596
41c8ca2a
AK
1597 if (num_print_iv == 0 && !interval)
1598 print_metric_headers(prefix, false);
54b50916
AK
1599 if (num_print_iv++ == 25)
1600 num_print_iv = 0;
1601 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1602 fprintf(stat_config.output, "%s", prefix);
1603 }
1604
421a50f3 1605 switch (stat_config.aggr_mode) {
12c08a9f 1606 case AGGR_CORE:
86ee6e18 1607 case AGGR_SOCKET:
d4f63a47 1608 print_aggr(prefix);
86ee6e18 1609 break;
32b8af82 1610 case AGGR_THREAD:
e5cadb93 1611 evlist__for_each_entry(evsel_list, counter)
32b8af82
JO
1612 print_aggr_thread(counter, prefix);
1613 break;
86ee6e18 1614 case AGGR_GLOBAL:
e5cadb93 1615 evlist__for_each_entry(evsel_list, counter)
d4f63a47 1616 print_counter_aggr(counter, prefix);
54b50916
AK
1617 if (metric_only)
1618 fputc('\n', stat_config.output);
86ee6e18
SE
1619 break;
1620 case AGGR_NONE:
206cab65
AK
1621 if (metric_only)
1622 print_no_aggr_metric(prefix);
1623 else {
e5cadb93 1624 evlist__for_each_entry(evsel_list, counter)
206cab65
AK
1625 print_counter(counter, prefix);
1626 }
86ee6e18 1627 break;
208df99e 1628 case AGGR_UNSET:
86ee6e18
SE
1629 default:
1630 break;
f5b4a9c3 1631 }
ddcacfa0 1632
d4f63a47
JO
1633 if (!interval && !csv_output)
1634 print_footer();
1635
5821522e 1636 fflush(stat_config.output);
ddcacfa0
IM
1637}
1638
f7b7c26e
PZ
1639static volatile int signr = -1;
1640
5242519b 1641static void skip_signal(int signo)
ddcacfa0 1642{
ec0d3d1f 1643 if ((child_pid == -1) || stat_config.interval)
60666c63
LW
1644 done = 1;
1645
f7b7c26e 1646 signr = signo;
d07f0b12
SE
1647 /*
1648 * render child_pid harmless
1649 * won't send SIGTERM to a random
1650 * process in case of race condition
1651 * and fast PID recycling
1652 */
1653 child_pid = -1;
f7b7c26e
PZ
1654}
1655
1656static void sig_atexit(void)
1657{
d07f0b12
SE
1658 sigset_t set, oset;
1659
1660 /*
1661 * avoid race condition with SIGCHLD handler
1662 * in skip_signal() which is modifying child_pid
1663 * goal is to avoid send SIGTERM to a random
1664 * process
1665 */
1666 sigemptyset(&set);
1667 sigaddset(&set, SIGCHLD);
1668 sigprocmask(SIG_BLOCK, &set, &oset);
1669
933da83a
CW
1670 if (child_pid != -1)
1671 kill(child_pid, SIGTERM);
1672
d07f0b12
SE
1673 sigprocmask(SIG_SETMASK, &oset, NULL);
1674
f7b7c26e
PZ
1675 if (signr == -1)
1676 return;
1677
1678 signal(signr, SIG_DFL);
1679 kill(getpid(), signr);
5242519b
IM
1680}
1681
1d037ca1
IT
1682static int stat__set_big_num(const struct option *opt __maybe_unused,
1683 const char *s __maybe_unused, int unset)
d7470b6a
SE
1684{
1685 big_num_opt = unset ? 0 : 1;
1686 return 0;
1687}
1688
44b1e60a
AK
1689static int enable_metric_only(const struct option *opt __maybe_unused,
1690 const char *s __maybe_unused, int unset)
1691{
1692 force_metric_only = true;
1693 metric_only = !unset;
1694 return 0;
1695}
1696
e0547311
JO
1697static const struct option stat_options[] = {
1698 OPT_BOOLEAN('T', "transaction", &transaction_run,
1699 "hardware transaction statistics"),
1700 OPT_CALLBACK('e', "event", &evsel_list, "event",
1701 "event selector. use 'perf list' to list available events",
1702 parse_events_option),
1703 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1704 "event filter", parse_filter),
1705 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1706 "child tasks do not inherit counters"),
1707 OPT_STRING('p', "pid", &target.pid, "pid",
1708 "stat events on existing process id"),
1709 OPT_STRING('t', "tid", &target.tid, "tid",
1710 "stat events on existing thread id"),
1711 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1712 "system-wide collection from all CPUs"),
1713 OPT_BOOLEAN('g', "group", &group,
1714 "put the counters into a counter group"),
1715 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1716 OPT_INCR('v', "verbose", &verbose,
1717 "be more verbose (show counter open errors, etc)"),
1718 OPT_INTEGER('r', "repeat", &run_count,
1719 "repeat command and print average + stddev (max: 100, forever: 0)"),
1720 OPT_BOOLEAN('n', "null", &null_run,
1721 "null run - dont start any counters"),
1722 OPT_INCR('d', "detailed", &detailed_run,
1723 "detailed run - start a lot of events"),
1724 OPT_BOOLEAN('S', "sync", &sync_run,
1725 "call sync() before starting a run"),
1726 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1727 "print large numbers with thousands\' separators",
1728 stat__set_big_num),
1729 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1730 "list of cpus to monitor in system-wide"),
1731 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1732 "disable CPU count aggregation", AGGR_NONE),
430daf2d 1733 OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
e0547311
JO
1734 OPT_STRING('x', "field-separator", &csv_sep, "separator",
1735 "print counts with custom separator"),
1736 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1737 "monitor event in cgroup name only", parse_cgroups),
1738 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1739 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1740 OPT_INTEGER(0, "log-fd", &output_fd,
1741 "log output to fd, instead of stderr"),
1742 OPT_STRING(0, "pre", &pre_cmd, "command",
1743 "command to run prior to the measured command"),
1744 OPT_STRING(0, "post", &post_cmd, "command",
1745 "command to run after to the measured command"),
1746 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1747 "print counts at regular interval in ms (>= 10)"),
1748 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1749 "aggregate counts per processor socket", AGGR_SOCKET),
1750 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1751 "aggregate counts per physical processor core", AGGR_CORE),
1752 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1753 "aggregate counts per thread", AGGR_THREAD),
1754 OPT_UINTEGER('D', "delay", &initial_delay,
1755 "ms to wait before starting measurement after program start"),
44b1e60a
AK
1756 OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
1757 "Only print computed metrics. No raw values", enable_metric_only),
1758 OPT_BOOLEAN(0, "topdown", &topdown_run,
1759 "measure topdown level 1 statistics"),
e0547311
JO
1760 OPT_END()
1761};
1762
1fe7a300
JO
1763static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1764{
1765 return cpu_map__get_socket(map, cpu, NULL);
1766}
1767
1768static int perf_stat__get_core(struct cpu_map *map, int cpu)
1769{
1770 return cpu_map__get_core(map, cpu, NULL);
1771}
1772
1e5a2931
JO
1773static int cpu_map__get_max(struct cpu_map *map)
1774{
1775 int i, max = -1;
1776
1777 for (i = 0; i < map->nr; i++) {
1778 if (map->map[i] > max)
1779 max = map->map[i];
1780 }
1781
1782 return max;
1783}
1784
1785static struct cpu_map *cpus_aggr_map;
1786
1787static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1788{
1789 int cpu;
1790
1791 if (idx >= map->nr)
1792 return -1;
1793
1794 cpu = map->map[idx];
1795
1796 if (cpus_aggr_map->map[cpu] == -1)
1797 cpus_aggr_map->map[cpu] = get_id(map, idx);
1798
1799 return cpus_aggr_map->map[cpu];
1800}
1801
1802static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1803{
1804 return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1805}
1806
1807static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1808{
1809 return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1810}
1811
86ee6e18
SE
1812static int perf_stat_init_aggr_mode(void)
1813{
1e5a2931
JO
1814 int nr;
1815
421a50f3 1816 switch (stat_config.aggr_mode) {
86ee6e18
SE
1817 case AGGR_SOCKET:
1818 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1819 perror("cannot build socket map");
1820 return -1;
1821 }
1e5a2931 1822 aggr_get_id = perf_stat__get_socket_cached;
86ee6e18 1823 break;
12c08a9f
SE
1824 case AGGR_CORE:
1825 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1826 perror("cannot build core map");
1827 return -1;
1828 }
1e5a2931 1829 aggr_get_id = perf_stat__get_core_cached;
12c08a9f 1830 break;
86ee6e18
SE
1831 case AGGR_NONE:
1832 case AGGR_GLOBAL:
32b8af82 1833 case AGGR_THREAD:
208df99e 1834 case AGGR_UNSET:
86ee6e18
SE
1835 default:
1836 break;
1837 }
1e5a2931
JO
1838
1839 /*
1840 * The evsel_list->cpus is the base we operate on,
1841 * taking the highest cpu number to be the size of
1842 * the aggregation translate cpumap.
1843 */
1844 nr = cpu_map__get_max(evsel_list->cpus);
1845 cpus_aggr_map = cpu_map__empty_new(nr + 1);
1846 return cpus_aggr_map ? 0 : -ENOMEM;
86ee6e18
SE
1847}
1848
544c2ae7
MH
1849static void perf_stat__exit_aggr_mode(void)
1850{
1851 cpu_map__put(aggr_map);
1852 cpu_map__put(cpus_aggr_map);
1853 aggr_map = NULL;
1854 cpus_aggr_map = NULL;
1855}
1856
68d702f7
JO
1857static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
1858{
1859 int cpu;
1860
1861 if (idx > map->nr)
1862 return -1;
1863
1864 cpu = map->map[idx];
1865
da8a58b5 1866 if (cpu >= env->nr_cpus_avail)
68d702f7
JO
1867 return -1;
1868
1869 return cpu;
1870}
1871
1872static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
1873{
1874 struct perf_env *env = data;
1875 int cpu = perf_env__get_cpu(env, map, idx);
1876
1877 return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1878}
1879
1880static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
1881{
1882 struct perf_env *env = data;
1883 int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1884
1885 if (cpu != -1) {
1886 int socket_id = env->cpu[cpu].socket_id;
1887
1888 /*
1889 * Encode socket in upper 16 bits
1890 * core_id is relative to socket, and
1891 * we need a global id. So we combine
1892 * socket + core id.
1893 */
1894 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
1895 }
1896
1897 return core;
1898}
1899
1900static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
1901 struct cpu_map **sockp)
1902{
1903 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1904}
1905
1906static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
1907 struct cpu_map **corep)
1908{
1909 return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1910}
1911
1912static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
1913{
1914 return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1915}
1916
1917static int perf_stat__get_core_file(struct cpu_map *map, int idx)
1918{
1919 return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1920}
1921
1922static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1923{
1924 struct perf_env *env = &st->session->header.env;
1925
1926 switch (stat_config.aggr_mode) {
1927 case AGGR_SOCKET:
1928 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
1929 perror("cannot build socket map");
1930 return -1;
1931 }
1932 aggr_get_id = perf_stat__get_socket_file;
1933 break;
1934 case AGGR_CORE:
1935 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
1936 perror("cannot build core map");
1937 return -1;
1938 }
1939 aggr_get_id = perf_stat__get_core_file;
1940 break;
1941 case AGGR_NONE:
1942 case AGGR_GLOBAL:
1943 case AGGR_THREAD:
1944 case AGGR_UNSET:
1945 default:
1946 break;
1947 }
1948
1949 return 0;
1950}
1951
44b1e60a
AK
1952static int topdown_filter_events(const char **attr, char **str, bool use_group)
1953{
1954 int off = 0;
1955 int i;
1956 int len = 0;
1957 char *s;
1958
1959 for (i = 0; attr[i]; i++) {
1960 if (pmu_have_event("cpu", attr[i])) {
1961 len += strlen(attr[i]) + 1;
1962 attr[i - off] = attr[i];
1963 } else
1964 off++;
1965 }
1966 attr[i - off] = NULL;
1967
1968 *str = malloc(len + 1 + 2);
1969 if (!*str)
1970 return -1;
1971 s = *str;
1972 if (i - off == 0) {
1973 *s = 0;
1974 return 0;
1975 }
1976 if (use_group)
1977 *s++ = '{';
1978 for (i = 0; attr[i]; i++) {
1979 strcpy(s, attr[i]);
1980 s += strlen(s);
1981 *s++ = ',';
1982 }
1983 if (use_group) {
1984 s[-1] = '}';
1985 *s = 0;
1986 } else
1987 s[-1] = 0;
1988 return 0;
1989}
1990
1991__weak bool arch_topdown_check_group(bool *warn)
1992{
1993 *warn = false;
1994 return false;
1995}
1996
1997__weak void arch_topdown_group_warn(void)
1998{
1999}
2000
2cba3ffb
IM
2001/*
2002 * Add default attributes, if there were no attributes specified or
2003 * if -d/--detailed, -d -d or -d -d -d is used:
2004 */
2005static int add_default_attributes(void)
2006{
44b1e60a 2007 int err;
9dec4473 2008 struct perf_event_attr default_attrs0[] = {
b070a547
ACM
2009
2010 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
2011 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
2012 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
2013 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
2014
2015 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
9dec4473
AK
2016};
2017 struct perf_event_attr frontend_attrs[] = {
b070a547 2018 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
9dec4473
AK
2019};
2020 struct perf_event_attr backend_attrs[] = {
b070a547 2021 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
9dec4473
AK
2022};
2023 struct perf_event_attr default_attrs1[] = {
b070a547
ACM
2024 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
2025 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
2026 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
2027
2028};
2029
2030/*
2031 * Detailed stats (-d), covering the L1 and last level data caches:
2032 */
2033 struct perf_event_attr detailed_attrs[] = {
2034
2035 { .type = PERF_TYPE_HW_CACHE,
2036 .config =
2037 PERF_COUNT_HW_CACHE_L1D << 0 |
2038 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2039 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2040
2041 { .type = PERF_TYPE_HW_CACHE,
2042 .config =
2043 PERF_COUNT_HW_CACHE_L1D << 0 |
2044 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2045 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2046
2047 { .type = PERF_TYPE_HW_CACHE,
2048 .config =
2049 PERF_COUNT_HW_CACHE_LL << 0 |
2050 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2051 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2052
2053 { .type = PERF_TYPE_HW_CACHE,
2054 .config =
2055 PERF_COUNT_HW_CACHE_LL << 0 |
2056 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2057 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2058};
2059
2060/*
2061 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2062 */
2063 struct perf_event_attr very_detailed_attrs[] = {
2064
2065 { .type = PERF_TYPE_HW_CACHE,
2066 .config =
2067 PERF_COUNT_HW_CACHE_L1I << 0 |
2068 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2069 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2070
2071 { .type = PERF_TYPE_HW_CACHE,
2072 .config =
2073 PERF_COUNT_HW_CACHE_L1I << 0 |
2074 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2075 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2076
2077 { .type = PERF_TYPE_HW_CACHE,
2078 .config =
2079 PERF_COUNT_HW_CACHE_DTLB << 0 |
2080 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2081 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2082
2083 { .type = PERF_TYPE_HW_CACHE,
2084 .config =
2085 PERF_COUNT_HW_CACHE_DTLB << 0 |
2086 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2087 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2088
2089 { .type = PERF_TYPE_HW_CACHE,
2090 .config =
2091 PERF_COUNT_HW_CACHE_ITLB << 0 |
2092 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2093 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2094
2095 { .type = PERF_TYPE_HW_CACHE,
2096 .config =
2097 PERF_COUNT_HW_CACHE_ITLB << 0 |
2098 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
2099 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2100
2101};
2102
2103/*
2104 * Very, very detailed stats (-d -d -d), adding prefetch events:
2105 */
2106 struct perf_event_attr very_very_detailed_attrs[] = {
2107
2108 { .type = PERF_TYPE_HW_CACHE,
2109 .config =
2110 PERF_COUNT_HW_CACHE_L1D << 0 |
2111 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2112 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
2113
2114 { .type = PERF_TYPE_HW_CACHE,
2115 .config =
2116 PERF_COUNT_HW_CACHE_L1D << 0 |
2117 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
2118 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
2119};
2120
2cba3ffb
IM
2121 /* Set attrs if no event is selected and !null_run: */
2122 if (null_run)
2123 return 0;
2124
4cabc3d1 2125 if (transaction_run) {
4cabc3d1
AK
2126 if (pmu_have_event("cpu", "cycles-ct") &&
2127 pmu_have_event("cpu", "el-start"))
a454742c 2128 err = parse_events(evsel_list, transaction_attrs, NULL);
4cabc3d1 2129 else
a454742c
JO
2130 err = parse_events(evsel_list, transaction_limited_attrs, NULL);
2131 if (err) {
4cabc3d1
AK
2132 fprintf(stderr, "Cannot set up transaction events\n");
2133 return -1;
2134 }
2135 return 0;
2136 }
2137
44b1e60a
AK
2138 if (topdown_run) {
2139 char *str = NULL;
2140 bool warn = false;
2141
2142 if (stat_config.aggr_mode != AGGR_GLOBAL &&
2143 stat_config.aggr_mode != AGGR_CORE) {
2144 pr_err("top down event configuration requires --per-core mode\n");
2145 return -1;
2146 }
2147 stat_config.aggr_mode = AGGR_CORE;
2148 if (nr_cgroups || !target__has_cpu(&target)) {
2149 pr_err("top down event configuration requires system-wide mode (-a)\n");
2150 return -1;
2151 }
2152
2153 if (!force_metric_only)
2154 metric_only = true;
2155 if (topdown_filter_events(topdown_attrs, &str,
2156 arch_topdown_check_group(&warn)) < 0) {
2157 pr_err("Out of memory\n");
2158 return -1;
2159 }
2160 if (topdown_attrs[0] && str) {
2161 if (warn)
2162 arch_topdown_group_warn();
2163 err = parse_events(evsel_list, str, NULL);
2164 if (err) {
2165 fprintf(stderr,
2166 "Cannot set up top down events %s: %d\n",
2167 str, err);
2168 free(str);
2169 return -1;
2170 }
2171 } else {
2172 fprintf(stderr, "System does not support topdown\n");
2173 return -1;
2174 }
2175 free(str);
2176 }
2177
2cba3ffb 2178 if (!evsel_list->nr_entries) {
a1f3d567
NK
2179 if (target__has_cpu(&target))
2180 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2181
9dec4473
AK
2182 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2183 return -1;
2184 if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2185 if (perf_evlist__add_default_attrs(evsel_list,
2186 frontend_attrs) < 0)
2187 return -1;
2188 }
2189 if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2190 if (perf_evlist__add_default_attrs(evsel_list,
2191 backend_attrs) < 0)
2192 return -1;
2193 }
2194 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
50d08e47 2195 return -1;
2cba3ffb
IM
2196 }
2197
2198 /* Detailed events get appended to the event list: */
2199
2200 if (detailed_run < 1)
2201 return 0;
2202
2203 /* Append detailed run extra attributes: */
79695e1b 2204 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
50d08e47 2205 return -1;
2cba3ffb
IM
2206
2207 if (detailed_run < 2)
2208 return 0;
2209
2210 /* Append very detailed run extra attributes: */
79695e1b 2211 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
50d08e47 2212 return -1;
2cba3ffb
IM
2213
2214 if (detailed_run < 3)
2215 return 0;
2216
2217 /* Append very, very detailed run extra attributes: */
79695e1b 2218 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2cba3ffb
IM
2219}
2220
8a59f3cc 2221static const char * const stat_record_usage[] = {
4979d0c7
JO
2222 "perf stat record [<options>]",
2223 NULL,
2224};
2225
3ba78bd0
JO
2226static void init_features(struct perf_session *session)
2227{
2228 int feat;
2229
2230 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2231 perf_header__set_feat(&session->header, feat);
2232
2233 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2234 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2235 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2236 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2237}
2238
4979d0c7
JO
2239static int __cmd_record(int argc, const char **argv)
2240{
2241 struct perf_session *session;
2242 struct perf_data_file *file = &perf_stat.file;
2243
8a59f3cc 2244 argc = parse_options(argc, argv, stat_options, stat_record_usage,
4979d0c7
JO
2245 PARSE_OPT_STOP_AT_NON_OPTION);
2246
2247 if (output_name)
2248 file->path = output_name;
2249
e9d6db8e
JO
2250 if (run_count != 1 || forever) {
2251 pr_err("Cannot use -r option with perf stat record.\n");
2252 return -1;
2253 }
2254
4979d0c7
JO
2255 session = perf_session__new(file, false, NULL);
2256 if (session == NULL) {
2257 pr_err("Perf session creation failed.\n");
2258 return -1;
2259 }
2260
3ba78bd0
JO
2261 init_features(session);
2262
4979d0c7
JO
2263 session->evlist = evsel_list;
2264 perf_stat.session = session;
2265 perf_stat.record = true;
2266 return argc;
2267}
2268
a56f9390
JO
2269static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2270 union perf_event *event,
2271 struct perf_session *session)
2272{
e3b03b6c 2273 struct stat_round_event *stat_round = &event->stat_round;
a56f9390
JO
2274 struct perf_evsel *counter;
2275 struct timespec tsh, *ts = NULL;
2276 const char **argv = session->header.env.cmdline_argv;
2277 int argc = session->header.env.nr_cmdline;
2278
e5cadb93 2279 evlist__for_each_entry(evsel_list, counter)
a56f9390
JO
2280 perf_stat_process_counter(&stat_config, counter);
2281
e3b03b6c
AK
2282 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2283 update_stats(&walltime_nsecs_stats, stat_round->time);
a56f9390 2284
e3b03b6c 2285 if (stat_config.interval && stat_round->time) {
bd48c63e
ACM
2286 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2287 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
a56f9390
JO
2288 ts = &tsh;
2289 }
2290
2291 print_counters(ts, argc, argv);
2292 return 0;
2293}
2294
62ba18ba 2295static
7e6a7998 2296int process_stat_config_event(struct perf_tool *tool,
62ba18ba
JO
2297 union perf_event *event,
2298 struct perf_session *session __maybe_unused)
2299{
68d702f7
JO
2300 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2301
62ba18ba 2302 perf_event__read_stat_config(&stat_config, &event->stat_config);
68d702f7 2303
89af4e05
JO
2304 if (cpu_map__empty(st->cpus)) {
2305 if (st->aggr_mode != AGGR_UNSET)
2306 pr_warning("warning: processing task data, aggregation mode not set\n");
2307 return 0;
2308 }
2309
2310 if (st->aggr_mode != AGGR_UNSET)
2311 stat_config.aggr_mode = st->aggr_mode;
2312
68d702f7
JO
2313 if (perf_stat.file.is_pipe)
2314 perf_stat_init_aggr_mode();
2315 else
2316 perf_stat_init_aggr_mode_file(st);
2317
62ba18ba
JO
2318 return 0;
2319}
2320
1975d36e
JO
2321static int set_maps(struct perf_stat *st)
2322{
2323 if (!st->cpus || !st->threads)
2324 return 0;
2325
2326 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2327 return -EINVAL;
2328
2329 perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2330
2331 if (perf_evlist__alloc_stats(evsel_list, true))
2332 return -ENOMEM;
2333
2334 st->maps_allocated = true;
2335 return 0;
2336}
2337
2338static
7e6a7998 2339int process_thread_map_event(struct perf_tool *tool,
1975d36e
JO
2340 union perf_event *event,
2341 struct perf_session *session __maybe_unused)
2342{
2343 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2344
2345 if (st->threads) {
2346 pr_warning("Extra thread map event, ignoring.\n");
2347 return 0;
2348 }
2349
2350 st->threads = thread_map__new_event(&event->thread_map);
2351 if (!st->threads)
2352 return -ENOMEM;
2353
2354 return set_maps(st);
2355}
2356
2357static
7e6a7998 2358int process_cpu_map_event(struct perf_tool *tool,
1975d36e
JO
2359 union perf_event *event,
2360 struct perf_session *session __maybe_unused)
2361{
2362 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2363 struct cpu_map *cpus;
2364
2365 if (st->cpus) {
2366 pr_warning("Extra cpu map event, ignoring.\n");
2367 return 0;
2368 }
2369
2370 cpus = cpu_map__new_data(&event->cpu_map.data);
2371 if (!cpus)
2372 return -ENOMEM;
2373
2374 st->cpus = cpus;
2375 return set_maps(st);
2376}
2377
8a59f3cc 2378static const char * const stat_report_usage[] = {
ba6039b6
JO
2379 "perf stat report [<options>]",
2380 NULL,
2381};
2382
2383static struct perf_stat perf_stat = {
2384 .tool = {
2385 .attr = perf_event__process_attr,
fa6ea781 2386 .event_update = perf_event__process_event_update,
1975d36e
JO
2387 .thread_map = process_thread_map_event,
2388 .cpu_map = process_cpu_map_event,
62ba18ba 2389 .stat_config = process_stat_config_event,
a56f9390
JO
2390 .stat = perf_event__process_stat_event,
2391 .stat_round = process_stat_round_event,
ba6039b6 2392 },
89af4e05 2393 .aggr_mode = AGGR_UNSET,
ba6039b6
JO
2394};
2395
2396static int __cmd_report(int argc, const char **argv)
2397{
2398 struct perf_session *session;
2399 const struct option options[] = {
2400 OPT_STRING('i', "input", &input_name, "file", "input file name"),
89af4e05
JO
2401 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2402 "aggregate counts per processor socket", AGGR_SOCKET),
2403 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2404 "aggregate counts per physical processor core", AGGR_CORE),
2405 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2406 "disable CPU count aggregation", AGGR_NONE),
ba6039b6
JO
2407 OPT_END()
2408 };
2409 struct stat st;
2410 int ret;
2411
8a59f3cc 2412 argc = parse_options(argc, argv, options, stat_report_usage, 0);
ba6039b6
JO
2413
2414 if (!input_name || !strlen(input_name)) {
2415 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2416 input_name = "-";
2417 else
2418 input_name = "perf.data";
2419 }
2420
2421 perf_stat.file.path = input_name;
2422 perf_stat.file.mode = PERF_DATA_MODE_READ;
2423
2424 session = perf_session__new(&perf_stat.file, false, &perf_stat.tool);
2425 if (session == NULL)
2426 return -1;
2427
2428 perf_stat.session = session;
2429 stat_config.output = stderr;
2430 evsel_list = session->evlist;
2431
2432 ret = perf_session__process_events(session);
2433 if (ret)
2434 return ret;
2435
2436 perf_session__delete(session);
2437 return 0;
2438}
2439
e3ba76de
JO
2440static void setup_system_wide(int forks)
2441{
2442 /*
2443 * Make system wide (-a) the default target if
2444 * no target was specified and one of following
2445 * conditions is met:
2446 *
2447 * - there's no workload specified
2448 * - there is workload specified but all requested
2449 * events are system wide events
2450 */
2451 if (!target__none(&target))
2452 return;
2453
2454 if (!forks)
2455 target.system_wide = true;
2456 else {
2457 struct perf_evsel *counter;
2458
2459 evlist__for_each_entry(evsel_list, counter) {
2460 if (!counter->system_wide)
2461 return;
2462 }
2463
2464 if (evsel_list->nr_entries)
2465 target.system_wide = true;
2466 }
2467}
2468
1d037ca1 2469int cmd_stat(int argc, const char **argv, const char *prefix __maybe_unused)
5242519b 2470{
b070a547
ACM
2471 const char * const stat_usage[] = {
2472 "perf stat [<options>] [<command>]",
2473 NULL
2474 };
cc03c542 2475 int status = -EINVAL, run_idx;
4aa9015f 2476 const char *mode;
5821522e 2477 FILE *output = stderr;
ec0d3d1f 2478 unsigned int interval;
ba6039b6 2479 const char * const stat_subcommands[] = { "record", "report" };
42202dd5 2480
5af52b51
SE
2481 setlocale(LC_ALL, "");
2482
334fe7a3 2483 evsel_list = perf_evlist__new();
361c99a6
ACM
2484 if (evsel_list == NULL)
2485 return -ENOMEM;
2486
1669e509 2487 parse_events__shrink_config_terms();
4979d0c7
JO
2488 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2489 (const char **) stat_usage,
2490 PARSE_OPT_STOP_AT_NON_OPTION);
fb4605ba 2491 perf_stat__init_shadow_stats();
4979d0c7 2492
6edb78a2
JO
2493 if (csv_sep) {
2494 csv_output = true;
2495 if (!strcmp(csv_sep, "\\t"))
2496 csv_sep = "\t";
2497 } else
2498 csv_sep = DEFAULT_SEPARATOR;
2499
4979d0c7
JO
2500 if (argc && !strncmp(argv[0], "rec", 3)) {
2501 argc = __cmd_record(argc, argv);
2502 if (argc < 0)
2503 return -1;
ba6039b6
JO
2504 } else if (argc && !strncmp(argv[0], "rep", 3))
2505 return __cmd_report(argc, argv);
d7470b6a 2506
ec0d3d1f
JO
2507 interval = stat_config.interval;
2508
4979d0c7
JO
2509 /*
2510 * For record command the -o is already taken care of.
2511 */
2512 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
4aa9015f
SE
2513 output = NULL;
2514
56f3bae7
JC
2515 if (output_name && output_fd) {
2516 fprintf(stderr, "cannot use both --output and --log-fd\n");
e0547311
JO
2517 parse_options_usage(stat_usage, stat_options, "o", 1);
2518 parse_options_usage(NULL, stat_options, "log-fd", 0);
cc03c542 2519 goto out;
56f3bae7 2520 }
fc3e4d07 2521
54b50916
AK
2522 if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2523 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2524 goto out;
2525 }
2526
54b50916
AK
2527 if (metric_only && run_count > 1) {
2528 fprintf(stderr, "--metric-only is not supported with -r\n");
2529 goto out;
2530 }
2531
fc3e4d07
SE
2532 if (output_fd < 0) {
2533 fprintf(stderr, "argument to --log-fd must be a > 0\n");
e0547311 2534 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
cc03c542 2535 goto out;
fc3e4d07
SE
2536 }
2537
4aa9015f
SE
2538 if (!output) {
2539 struct timespec tm;
2540 mode = append_file ? "a" : "w";
2541
2542 output = fopen(output_name, mode);
2543 if (!output) {
2544 perror("failed to create output file");
fceda7fe 2545 return -1;
4aa9015f
SE
2546 }
2547 clock_gettime(CLOCK_REALTIME, &tm);
2548 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
fc3e4d07 2549 } else if (output_fd > 0) {
56f3bae7
JC
2550 mode = append_file ? "a" : "w";
2551 output = fdopen(output_fd, mode);
2552 if (!output) {
2553 perror("Failed opening logfd");
2554 return -errno;
2555 }
4aa9015f
SE
2556 }
2557
5821522e
JO
2558 stat_config.output = output;
2559
d7470b6a
SE
2560 /*
2561 * let the spreadsheet do the pretty-printing
2562 */
2563 if (csv_output) {
61a9f324 2564 /* User explicitly passed -B? */
d7470b6a
SE
2565 if (big_num_opt == 1) {
2566 fprintf(stderr, "-B option not supported with -x\n");
e0547311
JO
2567 parse_options_usage(stat_usage, stat_options, "B", 1);
2568 parse_options_usage(NULL, stat_options, "x", 1);
cc03c542 2569 goto out;
d7470b6a
SE
2570 } else /* Nope, so disable big number formatting */
2571 big_num = false;
2572 } else if (big_num_opt == 0) /* User passed --no-big-num */
2573 big_num = false;
2574
e3ba76de 2575 setup_system_wide(argc);
ac3063bd 2576
a7e191c3 2577 if (run_count < 0) {
cc03c542 2578 pr_err("Run count must be a positive number\n");
e0547311 2579 parse_options_usage(stat_usage, stat_options, "r", 1);
cc03c542 2580 goto out;
a7e191c3
FD
2581 } else if (run_count == 0) {
2582 forever = true;
2583 run_count = 1;
2584 }
ddcacfa0 2585
421a50f3 2586 if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) {
32b8af82
JO
2587 fprintf(stderr, "The --per-thread option is only available "
2588 "when monitoring via -p -t options.\n");
e0547311
JO
2589 parse_options_usage(NULL, stat_options, "p", 1);
2590 parse_options_usage(NULL, stat_options, "t", 1);
32b8af82
JO
2591 goto out;
2592 }
2593
2594 /*
2595 * no_aggr, cgroup are for system-wide only
2596 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2597 */
421a50f3
JO
2598 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2599 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
602ad878 2600 !target__has_cpu(&target)) {
023695d9
SE
2601 fprintf(stderr, "both cgroup and no-aggregation "
2602 "modes only available in system-wide mode\n");
2603
e0547311
JO
2604 parse_options_usage(stat_usage, stat_options, "G", 1);
2605 parse_options_usage(NULL, stat_options, "A", 1);
2606 parse_options_usage(NULL, stat_options, "a", 1);
cc03c542 2607 goto out;
d7e7a451
SE
2608 }
2609
2cba3ffb
IM
2610 if (add_default_attributes())
2611 goto out;
ddcacfa0 2612
602ad878 2613 target__validate(&target);
5c98d466 2614
77a6f014 2615 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
602ad878 2616 if (target__has_task(&target)) {
77a6f014 2617 pr_err("Problems finding threads of monitor\n");
e0547311
JO
2618 parse_options_usage(stat_usage, stat_options, "p", 1);
2619 parse_options_usage(NULL, stat_options, "t", 1);
602ad878 2620 } else if (target__has_cpu(&target)) {
77a6f014 2621 perror("failed to parse CPUs map");
e0547311
JO
2622 parse_options_usage(stat_usage, stat_options, "C", 1);
2623 parse_options_usage(NULL, stat_options, "a", 1);
cc03c542
NK
2624 }
2625 goto out;
60d567e2 2626 }
32b8af82
JO
2627
2628 /*
2629 * Initialize thread_map with comm names,
2630 * so we could print it out on output.
2631 */
421a50f3 2632 if (stat_config.aggr_mode == AGGR_THREAD)
32b8af82
JO
2633 thread_map__read_comms(evsel_list->threads);
2634
13370a9b 2635 if (interval && interval < 100) {
19afd104
KL
2636 if (interval < 10) {
2637 pr_err("print interval must be >= 10ms\n");
e0547311 2638 parse_options_usage(stat_usage, stat_options, "I", 1);
19afd104
KL
2639 goto out;
2640 } else
2641 pr_warning("print interval < 100ms. "
2642 "The overhead percentage could be high in some cases. "
2643 "Please proceed with caution.\n");
13370a9b 2644 }
c45c6ea2 2645
d134ffb9 2646 if (perf_evlist__alloc_stats(evsel_list, interval))
03ad9747 2647 goto out;
d6d901c2 2648
86ee6e18 2649 if (perf_stat_init_aggr_mode())
03ad9747 2650 goto out;
86ee6e18 2651
58d7e993
IM
2652 /*
2653 * We dont want to block the signals - that would cause
2654 * child tasks to inherit that and Ctrl-C would not work.
2655 * What we want is for Ctrl-C to work in the exec()-ed
2656 * task, but being ignored by perf stat itself:
2657 */
f7b7c26e 2658 atexit(sig_atexit);
a7e191c3
FD
2659 if (!forever)
2660 signal(SIGINT, skip_signal);
13370a9b 2661 signal(SIGCHLD, skip_signal);
58d7e993
IM
2662 signal(SIGALRM, skip_signal);
2663 signal(SIGABRT, skip_signal);
2664
42202dd5 2665 status = 0;
a7e191c3 2666 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
bb963e16 2667 if (run_count != 1 && verbose > 0)
4aa9015f
SE
2668 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2669 run_idx + 1);
f9cef0a9 2670
42202dd5 2671 status = run_perf_stat(argc, argv);
a7e191c3 2672 if (forever && status != -1) {
d4f63a47 2673 print_counters(NULL, argc, argv);
254ecbc7 2674 perf_stat__reset_stats();
a7e191c3 2675 }
42202dd5
IM
2676 }
2677
a7e191c3 2678 if (!forever && status != -1 && !interval)
d4f63a47 2679 print_counters(NULL, argc, argv);
d134ffb9 2680
4979d0c7
JO
2681 if (STAT_RECORD) {
2682 /*
2683 * We synthesize the kernel mmap record just so that older tools
2684 * don't emit warnings about not being able to resolve symbols
2685 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2686 * a saner message about no samples being in the perf.data file.
2687 *
2688 * This also serves to suppress a warning about f_header.data.size == 0
8b99b1a4
JO
2689 * in header.c at the moment 'perf stat record' gets introduced, which
2690 * is not really needed once we start adding the stat specific PERF_RECORD_
2691 * records, but the need to suppress the kptr_restrict messages in older
2692 * tools remain -acme
4979d0c7
JO
2693 */
2694 int fd = perf_data_file__fd(&perf_stat.file);
2695 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2696 process_synthesized_event,
2697 &perf_stat.session->machines.host);
2698 if (err) {
2699 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2700 "older tools may produce warnings about this file\n.");
2701 }
2702
7aad0c32
JO
2703 if (!interval) {
2704 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2705 pr_err("failed to write stat round event\n");
2706 }
2707
664c98d4
JO
2708 if (!perf_stat.file.is_pipe) {
2709 perf_stat.session->header.data_size += perf_stat.bytes_written;
2710 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2711 }
4979d0c7
JO
2712
2713 perf_session__delete(perf_stat.session);
2714 }
2715
544c2ae7 2716 perf_stat__exit_aggr_mode();
d134ffb9 2717 perf_evlist__free_stats(evsel_list);
0015e2e1
ACM
2718out:
2719 perf_evlist__delete(evsel_list);
42202dd5 2720 return status;
ddcacfa0 2721}