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