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