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