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