xref: /openbmc/linux/tools/perf/builtin-stat.c (revision 354575c00d61c174e0ff070f56cf3cdbe6d23f9e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * builtin-stat.c
4  *
5  * Builtin stat command: Give a precise performance counters summary
6  * overview about any workload, CPU or specific PID.
7  *
8  * Sample output:
9 
10    $ perf stat ./hackbench 10
11 
12   Time: 0.118
13 
14   Performance counter stats for './hackbench 10':
15 
16        1708.761321 task-clock                #   11.037 CPUs utilized
17             41,190 context-switches          #    0.024 M/sec
18              6,735 CPU-migrations            #    0.004 M/sec
19             17,318 page-faults               #    0.010 M/sec
20      5,205,202,243 cycles                    #    3.046 GHz
21      3,856,436,920 stalled-cycles-frontend   #   74.09% frontend cycles idle
22      1,600,790,871 stalled-cycles-backend    #   30.75% backend  cycles idle
23      2,603,501,247 instructions              #    0.50  insns per cycle
24                                              #    1.48  stalled cycles per insn
25        484,357,498 branches                  #  283.455 M/sec
26          6,388,934 branch-misses             #    1.32% of all branches
27 
28         0.154822978  seconds time elapsed
29 
30  *
31  * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
32  *
33  * Improvements and fixes by:
34  *
35  *   Arjan van de Ven <arjan@linux.intel.com>
36  *   Yanmin Zhang <yanmin.zhang@intel.com>
37  *   Wu Fengguang <fengguang.wu@intel.com>
38  *   Mike Galbraith <efault@gmx.de>
39  *   Paul Mackerras <paulus@samba.org>
40  *   Jaswinder Singh Rajput <jaswinder@kernel.org>
41  */
42 
43 #include "builtin.h"
44 #include "perf.h"
45 #include "util/cgroup.h"
46 #include <subcmd/parse-options.h>
47 #include "util/parse-events.h"
48 #include "util/pmu.h"
49 #include "util/event.h"
50 #include "util/evlist.h"
51 #include "util/evsel.h"
52 #include "util/debug.h"
53 #include "util/color.h"
54 #include "util/stat.h"
55 #include "util/header.h"
56 #include "util/cpumap.h"
57 #include "util/thread_map.h"
58 #include "util/counts.h"
59 #include "util/group.h"
60 #include "util/session.h"
61 #include "util/tool.h"
62 #include "util/string2.h"
63 #include "util/metricgroup.h"
64 #include "util/synthetic-events.h"
65 #include "util/target.h"
66 #include "util/time-utils.h"
67 #include "util/top.h"
68 #include "util/affinity.h"
69 #include "asm/bug.h"
70 
71 #include <linux/time64.h>
72 #include <linux/zalloc.h>
73 #include <api/fs/fs.h>
74 #include <errno.h>
75 #include <signal.h>
76 #include <stdlib.h>
77 #include <sys/prctl.h>
78 #include <inttypes.h>
79 #include <locale.h>
80 #include <math.h>
81 #include <sys/types.h>
82 #include <sys/stat.h>
83 #include <sys/wait.h>
84 #include <unistd.h>
85 #include <sys/time.h>
86 #include <sys/resource.h>
87 #include <linux/err.h>
88 
89 #include <linux/ctype.h>
90 #include <perf/evlist.h>
91 
92 #define DEFAULT_SEPARATOR	" "
93 #define FREEZE_ON_SMI_PATH	"devices/cpu/freeze_on_smi"
94 
95 static void print_counters(struct timespec *ts, int argc, const char **argv);
96 
97 /* Default events used for perf stat -T */
98 static const char *transaction_attrs = {
99 	"task-clock,"
100 	"{"
101 	"instructions,"
102 	"cycles,"
103 	"cpu/cycles-t/,"
104 	"cpu/tx-start/,"
105 	"cpu/el-start/,"
106 	"cpu/cycles-ct/"
107 	"}"
108 };
109 
110 /* More limited version when the CPU does not have all events. */
111 static const char * transaction_limited_attrs = {
112 	"task-clock,"
113 	"{"
114 	"instructions,"
115 	"cycles,"
116 	"cpu/cycles-t/,"
117 	"cpu/tx-start/"
118 	"}"
119 };
120 
121 static const char * topdown_attrs[] = {
122 	"topdown-total-slots",
123 	"topdown-slots-retired",
124 	"topdown-recovery-bubbles",
125 	"topdown-fetch-bubbles",
126 	"topdown-slots-issued",
127 	NULL,
128 };
129 
130 static const char *smi_cost_attrs = {
131 	"{"
132 	"msr/aperf/,"
133 	"msr/smi/,"
134 	"cycles"
135 	"}"
136 };
137 
138 static struct evlist	*evsel_list;
139 
140 static struct target target = {
141 	.uid	= UINT_MAX,
142 };
143 
144 #define METRIC_ONLY_LEN 20
145 
146 static volatile pid_t		child_pid			= -1;
147 static int			detailed_run			=  0;
148 static bool			transaction_run;
149 static bool			topdown_run			= false;
150 static bool			smi_cost			= false;
151 static bool			smi_reset			= false;
152 static int			big_num_opt			=  -1;
153 static bool			group				= false;
154 static const char		*pre_cmd			= NULL;
155 static const char		*post_cmd			= NULL;
156 static bool			sync_run			= false;
157 static bool			forever				= false;
158 static bool			force_metric_only		= false;
159 static struct timespec		ref_time;
160 static bool			append_file;
161 static bool			interval_count;
162 static const char		*output_name;
163 static int			output_fd;
164 
165 struct perf_stat {
166 	bool			 record;
167 	struct perf_data	 data;
168 	struct perf_session	*session;
169 	u64			 bytes_written;
170 	struct perf_tool	 tool;
171 	bool			 maps_allocated;
172 	struct perf_cpu_map	*cpus;
173 	struct perf_thread_map *threads;
174 	enum aggr_mode		 aggr_mode;
175 };
176 
177 static struct perf_stat		perf_stat;
178 #define STAT_RECORD		perf_stat.record
179 
180 static volatile int done = 0;
181 
182 static struct perf_stat_config stat_config = {
183 	.aggr_mode		= AGGR_GLOBAL,
184 	.scale			= true,
185 	.unit_width		= 4, /* strlen("unit") */
186 	.run_count		= 1,
187 	.metric_only_len	= METRIC_ONLY_LEN,
188 	.walltime_nsecs_stats	= &walltime_nsecs_stats,
189 	.big_num		= true,
190 };
191 
192 static inline void diff_timespec(struct timespec *r, struct timespec *a,
193 				 struct timespec *b)
194 {
195 	r->tv_sec = a->tv_sec - b->tv_sec;
196 	if (a->tv_nsec < b->tv_nsec) {
197 		r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
198 		r->tv_sec--;
199 	} else {
200 		r->tv_nsec = a->tv_nsec - b->tv_nsec ;
201 	}
202 }
203 
204 static void perf_stat__reset_stats(void)
205 {
206 	int i;
207 
208 	perf_evlist__reset_stats(evsel_list);
209 	perf_stat__reset_shadow_stats();
210 
211 	for (i = 0; i < stat_config.stats_num; i++)
212 		perf_stat__reset_shadow_per_stat(&stat_config.stats[i]);
213 }
214 
215 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
216 				     union perf_event *event,
217 				     struct perf_sample *sample __maybe_unused,
218 				     struct machine *machine __maybe_unused)
219 {
220 	if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
221 		pr_err("failed to write perf data, error: %m\n");
222 		return -1;
223 	}
224 
225 	perf_stat.bytes_written += event->header.size;
226 	return 0;
227 }
228 
229 static int write_stat_round_event(u64 tm, u64 type)
230 {
231 	return perf_event__synthesize_stat_round(NULL, tm, type,
232 						 process_synthesized_event,
233 						 NULL);
234 }
235 
236 #define WRITE_STAT_ROUND_EVENT(time, interval) \
237 	write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
238 
239 #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
240 
241 static int
242 perf_evsel__write_stat_event(struct evsel *counter, u32 cpu, u32 thread,
243 			     struct perf_counts_values *count)
244 {
245 	struct perf_sample_id *sid = SID(counter, cpu, thread);
246 
247 	return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
248 					   process_synthesized_event, NULL);
249 }
250 
251 static int read_single_counter(struct evsel *counter, int cpu,
252 			       int thread, struct timespec *rs)
253 {
254 	if (counter->tool_event == PERF_TOOL_DURATION_TIME) {
255 		u64 val = rs->tv_nsec + rs->tv_sec*1000000000ULL;
256 		struct perf_counts_values *count =
257 			perf_counts(counter->counts, cpu, thread);
258 		count->ena = count->run = val;
259 		count->val = val;
260 		return 0;
261 	}
262 	return perf_evsel__read_counter(counter, cpu, thread);
263 }
264 
265 /*
266  * Read out the results of a single counter:
267  * do not aggregate counts across CPUs in system-wide mode
268  */
269 static int read_counter_cpu(struct evsel *counter, struct timespec *rs, int cpu)
270 {
271 	int nthreads = perf_thread_map__nr(evsel_list->core.threads);
272 	int thread;
273 
274 	if (!counter->supported)
275 		return -ENOENT;
276 
277 	if (counter->core.system_wide)
278 		nthreads = 1;
279 
280 	for (thread = 0; thread < nthreads; thread++) {
281 		struct perf_counts_values *count;
282 
283 		count = perf_counts(counter->counts, cpu, thread);
284 
285 		/*
286 		 * The leader's group read loads data into its group members
287 		 * (via perf_evsel__read_counter()) and sets their count->loaded.
288 		 */
289 		if (!perf_counts__is_loaded(counter->counts, cpu, thread) &&
290 		    read_single_counter(counter, cpu, thread, rs)) {
291 			counter->counts->scaled = -1;
292 			perf_counts(counter->counts, cpu, thread)->ena = 0;
293 			perf_counts(counter->counts, cpu, thread)->run = 0;
294 			return -1;
295 		}
296 
297 		perf_counts__set_loaded(counter->counts, cpu, thread, false);
298 
299 		if (STAT_RECORD) {
300 			if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
301 				pr_err("failed to write stat event\n");
302 				return -1;
303 			}
304 		}
305 
306 		if (verbose > 1) {
307 			fprintf(stat_config.output,
308 				"%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
309 					perf_evsel__name(counter),
310 					cpu,
311 					count->val, count->ena, count->run);
312 		}
313 	}
314 
315 	return 0;
316 }
317 
318 static void read_counters(struct timespec *rs)
319 {
320 	struct evsel *counter;
321 	struct affinity affinity;
322 	int i, ncpus, cpu;
323 
324 	if (affinity__setup(&affinity) < 0)
325 		return;
326 
327 	ncpus = perf_cpu_map__nr(evsel_list->core.all_cpus);
328 	if (!target__has_cpu(&target) || target__has_per_thread(&target))
329 		ncpus = 1;
330 	evlist__for_each_cpu(evsel_list, i, cpu) {
331 		if (i >= ncpus)
332 			break;
333 		affinity__set(&affinity, cpu);
334 
335 		evlist__for_each_entry(evsel_list, counter) {
336 			if (evsel__cpu_iter_skip(counter, cpu))
337 				continue;
338 			if (!counter->err) {
339 				counter->err = read_counter_cpu(counter, rs,
340 								counter->cpu_iter - 1);
341 			}
342 		}
343 	}
344 	affinity__cleanup(&affinity);
345 
346 	evlist__for_each_entry(evsel_list, counter) {
347 		if (counter->err)
348 			pr_debug("failed to read counter %s\n", counter->name);
349 		if (counter->err == 0 && perf_stat_process_counter(&stat_config, counter))
350 			pr_warning("failed to process counter %s\n", counter->name);
351 		counter->err = 0;
352 	}
353 }
354 
355 static void process_interval(void)
356 {
357 	struct timespec ts, rs;
358 
359 	clock_gettime(CLOCK_MONOTONIC, &ts);
360 	diff_timespec(&rs, &ts, &ref_time);
361 
362 	perf_stat__reset_shadow_per_stat(&rt_stat);
363 	read_counters(&rs);
364 
365 	if (STAT_RECORD) {
366 		if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
367 			pr_err("failed to write stat round event\n");
368 	}
369 
370 	init_stats(&walltime_nsecs_stats);
371 	update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000);
372 	print_counters(&rs, 0, NULL);
373 }
374 
375 static void enable_counters(void)
376 {
377 	if (stat_config.initial_delay)
378 		usleep(stat_config.initial_delay * USEC_PER_MSEC);
379 
380 	/*
381 	 * We need to enable counters only if:
382 	 * - we don't have tracee (attaching to task or cpu)
383 	 * - we have initial delay configured
384 	 */
385 	if (!target__none(&target) || stat_config.initial_delay)
386 		evlist__enable(evsel_list);
387 }
388 
389 static void disable_counters(void)
390 {
391 	/*
392 	 * If we don't have tracee (attaching to task or cpu), counters may
393 	 * still be running. To get accurate group ratios, we must stop groups
394 	 * from counting before reading their constituent counters.
395 	 */
396 	if (!target__none(&target))
397 		evlist__disable(evsel_list);
398 }
399 
400 static volatile int workload_exec_errno;
401 
402 /*
403  * perf_evlist__prepare_workload will send a SIGUSR1
404  * if the fork fails, since we asked by setting its
405  * want_signal to true.
406  */
407 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
408 					void *ucontext __maybe_unused)
409 {
410 	workload_exec_errno = info->si_value.sival_int;
411 }
412 
413 static bool perf_evsel__should_store_id(struct evsel *counter)
414 {
415 	return STAT_RECORD || counter->core.attr.read_format & PERF_FORMAT_ID;
416 }
417 
418 static bool is_target_alive(struct target *_target,
419 			    struct perf_thread_map *threads)
420 {
421 	struct stat st;
422 	int i;
423 
424 	if (!target__has_task(_target))
425 		return true;
426 
427 	for (i = 0; i < threads->nr; i++) {
428 		char path[PATH_MAX];
429 
430 		scnprintf(path, PATH_MAX, "%s/%d", procfs__mountpoint(),
431 			  threads->map[i].pid);
432 
433 		if (!stat(path, &st))
434 			return true;
435 	}
436 
437 	return false;
438 }
439 
440 enum counter_recovery {
441 	COUNTER_SKIP,
442 	COUNTER_RETRY,
443 	COUNTER_FATAL,
444 };
445 
446 static enum counter_recovery stat_handle_error(struct evsel *counter)
447 {
448 	char msg[BUFSIZ];
449 	/*
450 	 * PPC returns ENXIO for HW counters until 2.6.37
451 	 * (behavior changed with commit b0a873e).
452 	 */
453 	if (errno == EINVAL || errno == ENOSYS ||
454 	    errno == ENOENT || errno == EOPNOTSUPP ||
455 	    errno == ENXIO) {
456 		if (verbose > 0)
457 			ui__warning("%s event is not supported by the kernel.\n",
458 				    perf_evsel__name(counter));
459 		counter->supported = false;
460 		/*
461 		 * errored is a sticky flag that means one of the counter's
462 		 * cpu event had a problem and needs to be reexamined.
463 		 */
464 		counter->errored = true;
465 
466 		if ((counter->leader != counter) ||
467 		    !(counter->leader->core.nr_members > 1))
468 			return COUNTER_SKIP;
469 	} else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
470 		if (verbose > 0)
471 			ui__warning("%s\n", msg);
472 		return COUNTER_RETRY;
473 	} else if (target__has_per_thread(&target) &&
474 		   evsel_list->core.threads &&
475 		   evsel_list->core.threads->err_thread != -1) {
476 		/*
477 		 * For global --per-thread case, skip current
478 		 * error thread.
479 		 */
480 		if (!thread_map__remove(evsel_list->core.threads,
481 					evsel_list->core.threads->err_thread)) {
482 			evsel_list->core.threads->err_thread = -1;
483 			return COUNTER_RETRY;
484 		}
485 	}
486 
487 	perf_evsel__open_strerror(counter, &target,
488 				  errno, msg, sizeof(msg));
489 	ui__error("%s\n", msg);
490 
491 	if (child_pid != -1)
492 		kill(child_pid, SIGTERM);
493 	return COUNTER_FATAL;
494 }
495 
496 static int __run_perf_stat(int argc, const char **argv, int run_idx)
497 {
498 	int interval = stat_config.interval;
499 	int times = stat_config.times;
500 	int timeout = stat_config.timeout;
501 	char msg[BUFSIZ];
502 	unsigned long long t0, t1;
503 	struct evsel *counter;
504 	struct timespec ts;
505 	size_t l;
506 	int status = 0;
507 	const bool forks = (argc > 0);
508 	bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
509 	struct affinity affinity;
510 	int i, cpu;
511 	bool second_pass = false;
512 
513 	if (interval) {
514 		ts.tv_sec  = interval / USEC_PER_MSEC;
515 		ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
516 	} else if (timeout) {
517 		ts.tv_sec  = timeout / USEC_PER_MSEC;
518 		ts.tv_nsec = (timeout % USEC_PER_MSEC) * NSEC_PER_MSEC;
519 	} else {
520 		ts.tv_sec  = 1;
521 		ts.tv_nsec = 0;
522 	}
523 
524 	if (forks) {
525 		if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
526 						  workload_exec_failed_signal) < 0) {
527 			perror("failed to prepare workload");
528 			return -1;
529 		}
530 		child_pid = evsel_list->workload.pid;
531 	}
532 
533 	if (group)
534 		perf_evlist__set_leader(evsel_list);
535 
536 	if (affinity__setup(&affinity) < 0)
537 		return -1;
538 
539 	evlist__for_each_cpu (evsel_list, i, cpu) {
540 		affinity__set(&affinity, cpu);
541 
542 		evlist__for_each_entry(evsel_list, counter) {
543 			if (evsel__cpu_iter_skip(counter, cpu))
544 				continue;
545 			if (counter->reset_group || counter->errored)
546 				continue;
547 try_again:
548 			if (create_perf_stat_counter(counter, &stat_config, &target,
549 						     counter->cpu_iter - 1) < 0) {
550 
551 				/*
552 				 * Weak group failed. We cannot just undo this here
553 				 * because earlier CPUs might be in group mode, and the kernel
554 				 * doesn't support mixing group and non group reads. Defer
555 				 * it to later.
556 				 * Don't close here because we're in the wrong affinity.
557 				 */
558 				if ((errno == EINVAL || errno == EBADF) &&
559 				    counter->leader != counter &&
560 				    counter->weak_group) {
561 					perf_evlist__reset_weak_group(evsel_list, counter, false);
562 					assert(counter->reset_group);
563 					second_pass = true;
564 					continue;
565 				}
566 
567 				switch (stat_handle_error(counter)) {
568 				case COUNTER_FATAL:
569 					return -1;
570 				case COUNTER_RETRY:
571 					goto try_again;
572 				case COUNTER_SKIP:
573 					continue;
574 				default:
575 					break;
576 				}
577 
578 			}
579 			counter->supported = true;
580 		}
581 	}
582 
583 	if (second_pass) {
584 		/*
585 		 * Now redo all the weak group after closing them,
586 		 * and also close errored counters.
587 		 */
588 
589 		evlist__for_each_cpu(evsel_list, i, cpu) {
590 			affinity__set(&affinity, cpu);
591 			/* First close errored or weak retry */
592 			evlist__for_each_entry(evsel_list, counter) {
593 				if (!counter->reset_group && !counter->errored)
594 					continue;
595 				if (evsel__cpu_iter_skip_no_inc(counter, cpu))
596 					continue;
597 				perf_evsel__close_cpu(&counter->core, counter->cpu_iter);
598 			}
599 			/* Now reopen weak */
600 			evlist__for_each_entry(evsel_list, counter) {
601 				if (!counter->reset_group && !counter->errored)
602 					continue;
603 				if (evsel__cpu_iter_skip(counter, cpu))
604 					continue;
605 				if (!counter->reset_group)
606 					continue;
607 try_again_reset:
608 				pr_debug2("reopening weak %s\n", perf_evsel__name(counter));
609 				if (create_perf_stat_counter(counter, &stat_config, &target,
610 							     counter->cpu_iter - 1) < 0) {
611 
612 					switch (stat_handle_error(counter)) {
613 					case COUNTER_FATAL:
614 						return -1;
615 					case COUNTER_RETRY:
616 						goto try_again_reset;
617 					case COUNTER_SKIP:
618 						continue;
619 					default:
620 						break;
621 					}
622 				}
623 				counter->supported = true;
624 			}
625 		}
626 	}
627 	affinity__cleanup(&affinity);
628 
629 	evlist__for_each_entry(evsel_list, counter) {
630 		if (!counter->supported) {
631 			perf_evsel__free_fd(&counter->core);
632 			continue;
633 		}
634 
635 		l = strlen(counter->unit);
636 		if (l > stat_config.unit_width)
637 			stat_config.unit_width = l;
638 
639 		if (perf_evsel__should_store_id(counter) &&
640 		    perf_evsel__store_ids(counter, evsel_list))
641 			return -1;
642 	}
643 
644 	if (perf_evlist__apply_filters(evsel_list, &counter)) {
645 		pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
646 			counter->filter, perf_evsel__name(counter), errno,
647 			str_error_r(errno, msg, sizeof(msg)));
648 		return -1;
649 	}
650 
651 	if (STAT_RECORD) {
652 		int err, fd = perf_data__fd(&perf_stat.data);
653 
654 		if (is_pipe) {
655 			err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
656 		} else {
657 			err = perf_session__write_header(perf_stat.session, evsel_list,
658 							 fd, false);
659 		}
660 
661 		if (err < 0)
662 			return err;
663 
664 		err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
665 							 process_synthesized_event, is_pipe);
666 		if (err < 0)
667 			return err;
668 	}
669 
670 	/*
671 	 * Enable counters and exec the command:
672 	 */
673 	t0 = rdclock();
674 	clock_gettime(CLOCK_MONOTONIC, &ref_time);
675 
676 	if (forks) {
677 		perf_evlist__start_workload(evsel_list);
678 		enable_counters();
679 
680 		if (interval || timeout) {
681 			while (!waitpid(child_pid, &status, WNOHANG)) {
682 				nanosleep(&ts, NULL);
683 				if (timeout)
684 					break;
685 				process_interval();
686 				if (interval_count && !(--times))
687 					break;
688 			}
689 		}
690 		if (child_pid != -1) {
691 			if (timeout)
692 				kill(child_pid, SIGTERM);
693 			wait4(child_pid, &status, 0, &stat_config.ru_data);
694 		}
695 
696 		if (workload_exec_errno) {
697 			const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
698 			pr_err("Workload failed: %s\n", emsg);
699 			return -1;
700 		}
701 
702 		if (WIFSIGNALED(status))
703 			psignal(WTERMSIG(status), argv[0]);
704 	} else {
705 		enable_counters();
706 		while (!done) {
707 			nanosleep(&ts, NULL);
708 			if (!is_target_alive(&target, evsel_list->core.threads))
709 				break;
710 			if (timeout)
711 				break;
712 			if (interval) {
713 				process_interval();
714 				if (interval_count && !(--times))
715 					break;
716 			}
717 		}
718 	}
719 
720 	disable_counters();
721 
722 	t1 = rdclock();
723 
724 	if (stat_config.walltime_run_table)
725 		stat_config.walltime_run[run_idx] = t1 - t0;
726 
727 	update_stats(&walltime_nsecs_stats, t1 - t0);
728 
729 	/*
730 	 * Closing a group leader splits the group, and as we only disable
731 	 * group leaders, results in remaining events becoming enabled. To
732 	 * avoid arbitrary skew, we must read all counters before closing any
733 	 * group leaders.
734 	 */
735 	read_counters(&(struct timespec) { .tv_nsec = t1-t0 });
736 
737 	/*
738 	 * We need to keep evsel_list alive, because it's processed
739 	 * later the evsel_list will be closed after.
740 	 */
741 	if (!STAT_RECORD)
742 		evlist__close(evsel_list);
743 
744 	return WEXITSTATUS(status);
745 }
746 
747 static int run_perf_stat(int argc, const char **argv, int run_idx)
748 {
749 	int ret;
750 
751 	if (pre_cmd) {
752 		ret = system(pre_cmd);
753 		if (ret)
754 			return ret;
755 	}
756 
757 	if (sync_run)
758 		sync();
759 
760 	ret = __run_perf_stat(argc, argv, run_idx);
761 	if (ret)
762 		return ret;
763 
764 	if (post_cmd) {
765 		ret = system(post_cmd);
766 		if (ret)
767 			return ret;
768 	}
769 
770 	return ret;
771 }
772 
773 static void print_counters(struct timespec *ts, int argc, const char **argv)
774 {
775 	/* Do not print anything if we record to the pipe. */
776 	if (STAT_RECORD && perf_stat.data.is_pipe)
777 		return;
778 
779 	perf_evlist__print_counters(evsel_list, &stat_config, &target,
780 				    ts, argc, argv);
781 }
782 
783 static volatile int signr = -1;
784 
785 static void skip_signal(int signo)
786 {
787 	if ((child_pid == -1) || stat_config.interval)
788 		done = 1;
789 
790 	signr = signo;
791 	/*
792 	 * render child_pid harmless
793 	 * won't send SIGTERM to a random
794 	 * process in case of race condition
795 	 * and fast PID recycling
796 	 */
797 	child_pid = -1;
798 }
799 
800 static void sig_atexit(void)
801 {
802 	sigset_t set, oset;
803 
804 	/*
805 	 * avoid race condition with SIGCHLD handler
806 	 * in skip_signal() which is modifying child_pid
807 	 * goal is to avoid send SIGTERM to a random
808 	 * process
809 	 */
810 	sigemptyset(&set);
811 	sigaddset(&set, SIGCHLD);
812 	sigprocmask(SIG_BLOCK, &set, &oset);
813 
814 	if (child_pid != -1)
815 		kill(child_pid, SIGTERM);
816 
817 	sigprocmask(SIG_SETMASK, &oset, NULL);
818 
819 	if (signr == -1)
820 		return;
821 
822 	signal(signr, SIG_DFL);
823 	kill(getpid(), signr);
824 }
825 
826 static int stat__set_big_num(const struct option *opt __maybe_unused,
827 			     const char *s __maybe_unused, int unset)
828 {
829 	big_num_opt = unset ? 0 : 1;
830 	return 0;
831 }
832 
833 static int enable_metric_only(const struct option *opt __maybe_unused,
834 			      const char *s __maybe_unused, int unset)
835 {
836 	force_metric_only = true;
837 	stat_config.metric_only = !unset;
838 	return 0;
839 }
840 
841 static int parse_metric_groups(const struct option *opt,
842 			       const char *str,
843 			       int unset __maybe_unused)
844 {
845 	return metricgroup__parse_groups(opt, str, &stat_config.metric_events);
846 }
847 
848 static struct option stat_options[] = {
849 	OPT_BOOLEAN('T', "transaction", &transaction_run,
850 		    "hardware transaction statistics"),
851 	OPT_CALLBACK('e', "event", &evsel_list, "event",
852 		     "event selector. use 'perf list' to list available events",
853 		     parse_events_option),
854 	OPT_CALLBACK(0, "filter", &evsel_list, "filter",
855 		     "event filter", parse_filter),
856 	OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
857 		    "child tasks do not inherit counters"),
858 	OPT_STRING('p', "pid", &target.pid, "pid",
859 		   "stat events on existing process id"),
860 	OPT_STRING('t', "tid", &target.tid, "tid",
861 		   "stat events on existing thread id"),
862 	OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
863 		    "system-wide collection from all CPUs"),
864 	OPT_BOOLEAN('g', "group", &group,
865 		    "put the counters into a counter group"),
866 	OPT_BOOLEAN(0, "scale", &stat_config.scale,
867 		    "Use --no-scale to disable counter scaling for multiplexing"),
868 	OPT_INCR('v', "verbose", &verbose,
869 		    "be more verbose (show counter open errors, etc)"),
870 	OPT_INTEGER('r', "repeat", &stat_config.run_count,
871 		    "repeat command and print average + stddev (max: 100, forever: 0)"),
872 	OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
873 		    "display details about each run (only with -r option)"),
874 	OPT_BOOLEAN('n', "null", &stat_config.null_run,
875 		    "null run - dont start any counters"),
876 	OPT_INCR('d', "detailed", &detailed_run,
877 		    "detailed run - start a lot of events"),
878 	OPT_BOOLEAN('S', "sync", &sync_run,
879 		    "call sync() before starting a run"),
880 	OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
881 			   "print large numbers with thousands\' separators",
882 			   stat__set_big_num),
883 	OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
884 		    "list of cpus to monitor in system-wide"),
885 	OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
886 		    "disable CPU count aggregation", AGGR_NONE),
887 	OPT_BOOLEAN(0, "no-merge", &stat_config.no_merge, "Do not merge identical named events"),
888 	OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
889 		   "print counts with custom separator"),
890 	OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
891 		     "monitor event in cgroup name only", parse_cgroups),
892 	OPT_STRING('o', "output", &output_name, "file", "output file name"),
893 	OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
894 	OPT_INTEGER(0, "log-fd", &output_fd,
895 		    "log output to fd, instead of stderr"),
896 	OPT_STRING(0, "pre", &pre_cmd, "command",
897 			"command to run prior to the measured command"),
898 	OPT_STRING(0, "post", &post_cmd, "command",
899 			"command to run after to the measured command"),
900 	OPT_UINTEGER('I', "interval-print", &stat_config.interval,
901 		    "print counts at regular interval in ms "
902 		    "(overhead is possible for values <= 100ms)"),
903 	OPT_INTEGER(0, "interval-count", &stat_config.times,
904 		    "print counts for fixed number of times"),
905 	OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
906 		    "clear screen in between new interval"),
907 	OPT_UINTEGER(0, "timeout", &stat_config.timeout,
908 		    "stop workload and print counts after a timeout period in ms (>= 10ms)"),
909 	OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
910 		     "aggregate counts per processor socket", AGGR_SOCKET),
911 	OPT_SET_UINT(0, "per-die", &stat_config.aggr_mode,
912 		     "aggregate counts per processor die", AGGR_DIE),
913 	OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
914 		     "aggregate counts per physical processor core", AGGR_CORE),
915 	OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
916 		     "aggregate counts per thread", AGGR_THREAD),
917 	OPT_SET_UINT(0, "per-node", &stat_config.aggr_mode,
918 		     "aggregate counts per numa node", AGGR_NODE),
919 	OPT_UINTEGER('D', "delay", &stat_config.initial_delay,
920 		     "ms to wait before starting measurement after program start"),
921 	OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
922 			"Only print computed metrics. No raw values", enable_metric_only),
923 	OPT_BOOLEAN(0, "topdown", &topdown_run,
924 			"measure topdown level 1 statistics"),
925 	OPT_BOOLEAN(0, "smi-cost", &smi_cost,
926 			"measure SMI cost"),
927 	OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
928 		     "monitor specified metrics or metric groups (separated by ,)",
929 		     parse_metric_groups),
930 	OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
931 			 "Configure all used events to run in kernel space.",
932 			 PARSE_OPT_EXCLUSIVE),
933 	OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
934 			 "Configure all used events to run in user space.",
935 			 PARSE_OPT_EXCLUSIVE),
936 	OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
937 		    "Use with 'percore' event qualifier to show the event "
938 		    "counts of one hardware thread by sum up total hardware "
939 		    "threads of same physical core"),
940 	OPT_END()
941 };
942 
943 static int perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
944 				 struct perf_cpu_map *map, int cpu)
945 {
946 	return cpu_map__get_socket(map, cpu, NULL);
947 }
948 
949 static int perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
950 			      struct perf_cpu_map *map, int cpu)
951 {
952 	return cpu_map__get_die(map, cpu, NULL);
953 }
954 
955 static int perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
956 			       struct perf_cpu_map *map, int cpu)
957 {
958 	return cpu_map__get_core(map, cpu, NULL);
959 }
960 
961 static int perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
962 			       struct perf_cpu_map *map, int cpu)
963 {
964 	return cpu_map__get_node(map, cpu, NULL);
965 }
966 
967 static int perf_stat__get_aggr(struct perf_stat_config *config,
968 			       aggr_get_id_t get_id, struct perf_cpu_map *map, int idx)
969 {
970 	int cpu;
971 
972 	if (idx >= map->nr)
973 		return -1;
974 
975 	cpu = map->map[idx];
976 
977 	if (config->cpus_aggr_map->map[cpu] == -1)
978 		config->cpus_aggr_map->map[cpu] = get_id(config, map, idx);
979 
980 	return config->cpus_aggr_map->map[cpu];
981 }
982 
983 static int perf_stat__get_socket_cached(struct perf_stat_config *config,
984 					struct perf_cpu_map *map, int idx)
985 {
986 	return perf_stat__get_aggr(config, perf_stat__get_socket, map, idx);
987 }
988 
989 static int perf_stat__get_die_cached(struct perf_stat_config *config,
990 					struct perf_cpu_map *map, int idx)
991 {
992 	return perf_stat__get_aggr(config, perf_stat__get_die, map, idx);
993 }
994 
995 static int perf_stat__get_core_cached(struct perf_stat_config *config,
996 				      struct perf_cpu_map *map, int idx)
997 {
998 	return perf_stat__get_aggr(config, perf_stat__get_core, map, idx);
999 }
1000 
1001 static int perf_stat__get_node_cached(struct perf_stat_config *config,
1002 				      struct perf_cpu_map *map, int idx)
1003 {
1004 	return perf_stat__get_aggr(config, perf_stat__get_node, map, idx);
1005 }
1006 
1007 static bool term_percore_set(void)
1008 {
1009 	struct evsel *counter;
1010 
1011 	evlist__for_each_entry(evsel_list, counter) {
1012 		if (counter->percore)
1013 			return true;
1014 	}
1015 
1016 	return false;
1017 }
1018 
1019 static int perf_stat_init_aggr_mode(void)
1020 {
1021 	int nr;
1022 
1023 	switch (stat_config.aggr_mode) {
1024 	case AGGR_SOCKET:
1025 		if (cpu_map__build_socket_map(evsel_list->core.cpus, &stat_config.aggr_map)) {
1026 			perror("cannot build socket map");
1027 			return -1;
1028 		}
1029 		stat_config.aggr_get_id = perf_stat__get_socket_cached;
1030 		break;
1031 	case AGGR_DIE:
1032 		if (cpu_map__build_die_map(evsel_list->core.cpus, &stat_config.aggr_map)) {
1033 			perror("cannot build die map");
1034 			return -1;
1035 		}
1036 		stat_config.aggr_get_id = perf_stat__get_die_cached;
1037 		break;
1038 	case AGGR_CORE:
1039 		if (cpu_map__build_core_map(evsel_list->core.cpus, &stat_config.aggr_map)) {
1040 			perror("cannot build core map");
1041 			return -1;
1042 		}
1043 		stat_config.aggr_get_id = perf_stat__get_core_cached;
1044 		break;
1045 	case AGGR_NODE:
1046 		if (cpu_map__build_node_map(evsel_list->core.cpus, &stat_config.aggr_map)) {
1047 			perror("cannot build core map");
1048 			return -1;
1049 		}
1050 		stat_config.aggr_get_id = perf_stat__get_node_cached;
1051 		break;
1052 	case AGGR_NONE:
1053 		if (term_percore_set()) {
1054 			if (cpu_map__build_core_map(evsel_list->core.cpus,
1055 						    &stat_config.aggr_map)) {
1056 				perror("cannot build core map");
1057 				return -1;
1058 			}
1059 			stat_config.aggr_get_id = perf_stat__get_core_cached;
1060 		}
1061 		break;
1062 	case AGGR_GLOBAL:
1063 	case AGGR_THREAD:
1064 	case AGGR_UNSET:
1065 	default:
1066 		break;
1067 	}
1068 
1069 	/*
1070 	 * The evsel_list->cpus is the base we operate on,
1071 	 * taking the highest cpu number to be the size of
1072 	 * the aggregation translate cpumap.
1073 	 */
1074 	nr = perf_cpu_map__max(evsel_list->core.cpus);
1075 	stat_config.cpus_aggr_map = perf_cpu_map__empty_new(nr + 1);
1076 	return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
1077 }
1078 
1079 static void perf_stat__exit_aggr_mode(void)
1080 {
1081 	perf_cpu_map__put(stat_config.aggr_map);
1082 	perf_cpu_map__put(stat_config.cpus_aggr_map);
1083 	stat_config.aggr_map = NULL;
1084 	stat_config.cpus_aggr_map = NULL;
1085 }
1086 
1087 static inline int perf_env__get_cpu(struct perf_env *env, struct perf_cpu_map *map, int idx)
1088 {
1089 	int cpu;
1090 
1091 	if (idx > map->nr)
1092 		return -1;
1093 
1094 	cpu = map->map[idx];
1095 
1096 	if (cpu >= env->nr_cpus_avail)
1097 		return -1;
1098 
1099 	return cpu;
1100 }
1101 
1102 static int perf_env__get_socket(struct perf_cpu_map *map, int idx, void *data)
1103 {
1104 	struct perf_env *env = data;
1105 	int cpu = perf_env__get_cpu(env, map, idx);
1106 
1107 	return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
1108 }
1109 
1110 static int perf_env__get_die(struct perf_cpu_map *map, int idx, void *data)
1111 {
1112 	struct perf_env *env = data;
1113 	int die_id = -1, cpu = perf_env__get_cpu(env, map, idx);
1114 
1115 	if (cpu != -1) {
1116 		/*
1117 		 * Encode socket in bit range 15:8
1118 		 * die_id is relative to socket,
1119 		 * we need a global id. So we combine
1120 		 * socket + die id
1121 		 */
1122 		if (WARN_ONCE(env->cpu[cpu].socket_id >> 8, "The socket id number is too big.\n"))
1123 			return -1;
1124 
1125 		if (WARN_ONCE(env->cpu[cpu].die_id >> 8, "The die id number is too big.\n"))
1126 			return -1;
1127 
1128 		die_id = (env->cpu[cpu].socket_id << 8) | (env->cpu[cpu].die_id & 0xff);
1129 	}
1130 
1131 	return die_id;
1132 }
1133 
1134 static int perf_env__get_core(struct perf_cpu_map *map, int idx, void *data)
1135 {
1136 	struct perf_env *env = data;
1137 	int core = -1, cpu = perf_env__get_cpu(env, map, idx);
1138 
1139 	if (cpu != -1) {
1140 		/*
1141 		 * Encode socket in bit range 31:24
1142 		 * encode die id in bit range 23:16
1143 		 * core_id is relative to socket and die,
1144 		 * we need a global id. So we combine
1145 		 * socket + die id + core id
1146 		 */
1147 		if (WARN_ONCE(env->cpu[cpu].socket_id >> 8, "The socket id number is too big.\n"))
1148 			return -1;
1149 
1150 		if (WARN_ONCE(env->cpu[cpu].die_id >> 8, "The die id number is too big.\n"))
1151 			return -1;
1152 
1153 		if (WARN_ONCE(env->cpu[cpu].core_id >> 16, "The core id number is too big.\n"))
1154 			return -1;
1155 
1156 		core = (env->cpu[cpu].socket_id << 24) |
1157 		       (env->cpu[cpu].die_id << 16) |
1158 		       (env->cpu[cpu].core_id & 0xffff);
1159 	}
1160 
1161 	return core;
1162 }
1163 
1164 static int perf_env__get_node(struct perf_cpu_map *map, int idx, void *data)
1165 {
1166 	int cpu = perf_env__get_cpu(data, map, idx);
1167 
1168 	return perf_env__numa_node(data, cpu);
1169 }
1170 
1171 static int perf_env__build_socket_map(struct perf_env *env, struct perf_cpu_map *cpus,
1172 				      struct perf_cpu_map **sockp)
1173 {
1174 	return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
1175 }
1176 
1177 static int perf_env__build_die_map(struct perf_env *env, struct perf_cpu_map *cpus,
1178 				   struct perf_cpu_map **diep)
1179 {
1180 	return cpu_map__build_map(cpus, diep, perf_env__get_die, env);
1181 }
1182 
1183 static int perf_env__build_core_map(struct perf_env *env, struct perf_cpu_map *cpus,
1184 				    struct perf_cpu_map **corep)
1185 {
1186 	return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
1187 }
1188 
1189 static int perf_env__build_node_map(struct perf_env *env, struct perf_cpu_map *cpus,
1190 				    struct perf_cpu_map **nodep)
1191 {
1192 	return cpu_map__build_map(cpus, nodep, perf_env__get_node, env);
1193 }
1194 
1195 static int perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
1196 				      struct perf_cpu_map *map, int idx)
1197 {
1198 	return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
1199 }
1200 static int perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
1201 				   struct perf_cpu_map *map, int idx)
1202 {
1203 	return perf_env__get_die(map, idx, &perf_stat.session->header.env);
1204 }
1205 
1206 static int perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
1207 				    struct perf_cpu_map *map, int idx)
1208 {
1209 	return perf_env__get_core(map, idx, &perf_stat.session->header.env);
1210 }
1211 
1212 static int perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
1213 				    struct perf_cpu_map *map, int idx)
1214 {
1215 	return perf_env__get_node(map, idx, &perf_stat.session->header.env);
1216 }
1217 
1218 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1219 {
1220 	struct perf_env *env = &st->session->header.env;
1221 
1222 	switch (stat_config.aggr_mode) {
1223 	case AGGR_SOCKET:
1224 		if (perf_env__build_socket_map(env, evsel_list->core.cpus, &stat_config.aggr_map)) {
1225 			perror("cannot build socket map");
1226 			return -1;
1227 		}
1228 		stat_config.aggr_get_id = perf_stat__get_socket_file;
1229 		break;
1230 	case AGGR_DIE:
1231 		if (perf_env__build_die_map(env, evsel_list->core.cpus, &stat_config.aggr_map)) {
1232 			perror("cannot build die map");
1233 			return -1;
1234 		}
1235 		stat_config.aggr_get_id = perf_stat__get_die_file;
1236 		break;
1237 	case AGGR_CORE:
1238 		if (perf_env__build_core_map(env, evsel_list->core.cpus, &stat_config.aggr_map)) {
1239 			perror("cannot build core map");
1240 			return -1;
1241 		}
1242 		stat_config.aggr_get_id = perf_stat__get_core_file;
1243 		break;
1244 	case AGGR_NODE:
1245 		if (perf_env__build_node_map(env, evsel_list->core.cpus, &stat_config.aggr_map)) {
1246 			perror("cannot build core map");
1247 			return -1;
1248 		}
1249 		stat_config.aggr_get_id = perf_stat__get_node_file;
1250 		break;
1251 	case AGGR_NONE:
1252 	case AGGR_GLOBAL:
1253 	case AGGR_THREAD:
1254 	case AGGR_UNSET:
1255 	default:
1256 		break;
1257 	}
1258 
1259 	return 0;
1260 }
1261 
1262 static int topdown_filter_events(const char **attr, char **str, bool use_group)
1263 {
1264 	int off = 0;
1265 	int i;
1266 	int len = 0;
1267 	char *s;
1268 
1269 	for (i = 0; attr[i]; i++) {
1270 		if (pmu_have_event("cpu", attr[i])) {
1271 			len += strlen(attr[i]) + 1;
1272 			attr[i - off] = attr[i];
1273 		} else
1274 			off++;
1275 	}
1276 	attr[i - off] = NULL;
1277 
1278 	*str = malloc(len + 1 + 2);
1279 	if (!*str)
1280 		return -1;
1281 	s = *str;
1282 	if (i - off == 0) {
1283 		*s = 0;
1284 		return 0;
1285 	}
1286 	if (use_group)
1287 		*s++ = '{';
1288 	for (i = 0; attr[i]; i++) {
1289 		strcpy(s, attr[i]);
1290 		s += strlen(s);
1291 		*s++ = ',';
1292 	}
1293 	if (use_group) {
1294 		s[-1] = '}';
1295 		*s = 0;
1296 	} else
1297 		s[-1] = 0;
1298 	return 0;
1299 }
1300 
1301 __weak bool arch_topdown_check_group(bool *warn)
1302 {
1303 	*warn = false;
1304 	return false;
1305 }
1306 
1307 __weak void arch_topdown_group_warn(void)
1308 {
1309 }
1310 
1311 /*
1312  * Add default attributes, if there were no attributes specified or
1313  * if -d/--detailed, -d -d or -d -d -d is used:
1314  */
1315 static int add_default_attributes(void)
1316 {
1317 	int err;
1318 	struct perf_event_attr default_attrs0[] = {
1319 
1320   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK		},
1321   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES	},
1322   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS		},
1323   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS		},
1324 
1325   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES		},
1326 };
1327 	struct perf_event_attr frontend_attrs[] = {
1328   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND	},
1329 };
1330 	struct perf_event_attr backend_attrs[] = {
1331   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND	},
1332 };
1333 	struct perf_event_attr default_attrs1[] = {
1334   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS		},
1335   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS	},
1336   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES		},
1337 
1338 };
1339 
1340 /*
1341  * Detailed stats (-d), covering the L1 and last level data caches:
1342  */
1343 	struct perf_event_attr detailed_attrs[] = {
1344 
1345   { .type = PERF_TYPE_HW_CACHE,
1346     .config =
1347 	 PERF_COUNT_HW_CACHE_L1D		<<  0  |
1348 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1349 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
1350 
1351   { .type = PERF_TYPE_HW_CACHE,
1352     .config =
1353 	 PERF_COUNT_HW_CACHE_L1D		<<  0  |
1354 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1355 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
1356 
1357   { .type = PERF_TYPE_HW_CACHE,
1358     .config =
1359 	 PERF_COUNT_HW_CACHE_LL			<<  0  |
1360 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1361 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
1362 
1363   { .type = PERF_TYPE_HW_CACHE,
1364     .config =
1365 	 PERF_COUNT_HW_CACHE_LL			<<  0  |
1366 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1367 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
1368 };
1369 
1370 /*
1371  * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1372  */
1373 	struct perf_event_attr very_detailed_attrs[] = {
1374 
1375   { .type = PERF_TYPE_HW_CACHE,
1376     .config =
1377 	 PERF_COUNT_HW_CACHE_L1I		<<  0  |
1378 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1379 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
1380 
1381   { .type = PERF_TYPE_HW_CACHE,
1382     .config =
1383 	 PERF_COUNT_HW_CACHE_L1I		<<  0  |
1384 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1385 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
1386 
1387   { .type = PERF_TYPE_HW_CACHE,
1388     .config =
1389 	 PERF_COUNT_HW_CACHE_DTLB		<<  0  |
1390 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1391 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
1392 
1393   { .type = PERF_TYPE_HW_CACHE,
1394     .config =
1395 	 PERF_COUNT_HW_CACHE_DTLB		<<  0  |
1396 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1397 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
1398 
1399   { .type = PERF_TYPE_HW_CACHE,
1400     .config =
1401 	 PERF_COUNT_HW_CACHE_ITLB		<<  0  |
1402 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1403 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
1404 
1405   { .type = PERF_TYPE_HW_CACHE,
1406     .config =
1407 	 PERF_COUNT_HW_CACHE_ITLB		<<  0  |
1408 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
1409 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
1410 
1411 };
1412 
1413 /*
1414  * Very, very detailed stats (-d -d -d), adding prefetch events:
1415  */
1416 	struct perf_event_attr very_very_detailed_attrs[] = {
1417 
1418   { .type = PERF_TYPE_HW_CACHE,
1419     .config =
1420 	 PERF_COUNT_HW_CACHE_L1D		<<  0  |
1421 	(PERF_COUNT_HW_CACHE_OP_PREFETCH	<<  8) |
1422 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
1423 
1424   { .type = PERF_TYPE_HW_CACHE,
1425     .config =
1426 	 PERF_COUNT_HW_CACHE_L1D		<<  0  |
1427 	(PERF_COUNT_HW_CACHE_OP_PREFETCH	<<  8) |
1428 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
1429 };
1430 	struct parse_events_error errinfo;
1431 
1432 	/* Set attrs if no event is selected and !null_run: */
1433 	if (stat_config.null_run)
1434 		return 0;
1435 
1436 	bzero(&errinfo, sizeof(errinfo));
1437 	if (transaction_run) {
1438 		/* Handle -T as -M transaction. Once platform specific metrics
1439 		 * support has been added to the json files, all archictures
1440 		 * will use this approach. To determine transaction support
1441 		 * on an architecture test for such a metric name.
1442 		 */
1443 		if (metricgroup__has_metric("transaction")) {
1444 			struct option opt = { .value = &evsel_list };
1445 
1446 			return metricgroup__parse_groups(&opt, "transaction",
1447 							 &stat_config.metric_events);
1448 		}
1449 
1450 		if (pmu_have_event("cpu", "cycles-ct") &&
1451 		    pmu_have_event("cpu", "el-start"))
1452 			err = parse_events(evsel_list, transaction_attrs,
1453 					   &errinfo);
1454 		else
1455 			err = parse_events(evsel_list,
1456 					   transaction_limited_attrs,
1457 					   &errinfo);
1458 		if (err) {
1459 			fprintf(stderr, "Cannot set up transaction events\n");
1460 			parse_events_print_error(&errinfo, transaction_attrs);
1461 			return -1;
1462 		}
1463 		return 0;
1464 	}
1465 
1466 	if (smi_cost) {
1467 		int smi;
1468 
1469 		if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
1470 			fprintf(stderr, "freeze_on_smi is not supported.\n");
1471 			return -1;
1472 		}
1473 
1474 		if (!smi) {
1475 			if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
1476 				fprintf(stderr, "Failed to set freeze_on_smi.\n");
1477 				return -1;
1478 			}
1479 			smi_reset = true;
1480 		}
1481 
1482 		if (pmu_have_event("msr", "aperf") &&
1483 		    pmu_have_event("msr", "smi")) {
1484 			if (!force_metric_only)
1485 				stat_config.metric_only = true;
1486 			err = parse_events(evsel_list, smi_cost_attrs, &errinfo);
1487 		} else {
1488 			fprintf(stderr, "To measure SMI cost, it needs "
1489 				"msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
1490 			parse_events_print_error(&errinfo, smi_cost_attrs);
1491 			return -1;
1492 		}
1493 		if (err) {
1494 			parse_events_print_error(&errinfo, smi_cost_attrs);
1495 			fprintf(stderr, "Cannot set up SMI cost events\n");
1496 			return -1;
1497 		}
1498 		return 0;
1499 	}
1500 
1501 	if (topdown_run) {
1502 		char *str = NULL;
1503 		bool warn = false;
1504 
1505 		if (stat_config.aggr_mode != AGGR_GLOBAL &&
1506 		    stat_config.aggr_mode != AGGR_CORE) {
1507 			pr_err("top down event configuration requires --per-core mode\n");
1508 			return -1;
1509 		}
1510 		stat_config.aggr_mode = AGGR_CORE;
1511 		if (nr_cgroups || !target__has_cpu(&target)) {
1512 			pr_err("top down event configuration requires system-wide mode (-a)\n");
1513 			return -1;
1514 		}
1515 
1516 		if (!force_metric_only)
1517 			stat_config.metric_only = true;
1518 		if (topdown_filter_events(topdown_attrs, &str,
1519 				arch_topdown_check_group(&warn)) < 0) {
1520 			pr_err("Out of memory\n");
1521 			return -1;
1522 		}
1523 		if (topdown_attrs[0] && str) {
1524 			if (warn)
1525 				arch_topdown_group_warn();
1526 			err = parse_events(evsel_list, str, &errinfo);
1527 			if (err) {
1528 				fprintf(stderr,
1529 					"Cannot set up top down events %s: %d\n",
1530 					str, err);
1531 				parse_events_print_error(&errinfo, str);
1532 				free(str);
1533 				return -1;
1534 			}
1535 		} else {
1536 			fprintf(stderr, "System does not support topdown\n");
1537 			return -1;
1538 		}
1539 		free(str);
1540 	}
1541 
1542 	if (!evsel_list->core.nr_entries) {
1543 		if (target__has_cpu(&target))
1544 			default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
1545 
1546 		if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
1547 			return -1;
1548 		if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
1549 			if (perf_evlist__add_default_attrs(evsel_list,
1550 						frontend_attrs) < 0)
1551 				return -1;
1552 		}
1553 		if (pmu_have_event("cpu", "stalled-cycles-backend")) {
1554 			if (perf_evlist__add_default_attrs(evsel_list,
1555 						backend_attrs) < 0)
1556 				return -1;
1557 		}
1558 		if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
1559 			return -1;
1560 	}
1561 
1562 	/* Detailed events get appended to the event list: */
1563 
1564 	if (detailed_run <  1)
1565 		return 0;
1566 
1567 	/* Append detailed run extra attributes: */
1568 	if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1569 		return -1;
1570 
1571 	if (detailed_run < 2)
1572 		return 0;
1573 
1574 	/* Append very detailed run extra attributes: */
1575 	if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1576 		return -1;
1577 
1578 	if (detailed_run < 3)
1579 		return 0;
1580 
1581 	/* Append very, very detailed run extra attributes: */
1582 	return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1583 }
1584 
1585 static const char * const stat_record_usage[] = {
1586 	"perf stat record [<options>]",
1587 	NULL,
1588 };
1589 
1590 static void init_features(struct perf_session *session)
1591 {
1592 	int feat;
1593 
1594 	for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
1595 		perf_header__set_feat(&session->header, feat);
1596 
1597 	perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
1598 	perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
1599 	perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
1600 	perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
1601 	perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
1602 }
1603 
1604 static int __cmd_record(int argc, const char **argv)
1605 {
1606 	struct perf_session *session;
1607 	struct perf_data *data = &perf_stat.data;
1608 
1609 	argc = parse_options(argc, argv, stat_options, stat_record_usage,
1610 			     PARSE_OPT_STOP_AT_NON_OPTION);
1611 
1612 	if (output_name)
1613 		data->path = output_name;
1614 
1615 	if (stat_config.run_count != 1 || forever) {
1616 		pr_err("Cannot use -r option with perf stat record.\n");
1617 		return -1;
1618 	}
1619 
1620 	session = perf_session__new(data, false, NULL);
1621 	if (IS_ERR(session)) {
1622 		pr_err("Perf session creation failed\n");
1623 		return PTR_ERR(session);
1624 	}
1625 
1626 	init_features(session);
1627 
1628 	session->evlist   = evsel_list;
1629 	perf_stat.session = session;
1630 	perf_stat.record  = true;
1631 	return argc;
1632 }
1633 
1634 static int process_stat_round_event(struct perf_session *session,
1635 				    union perf_event *event)
1636 {
1637 	struct perf_record_stat_round *stat_round = &event->stat_round;
1638 	struct evsel *counter;
1639 	struct timespec tsh, *ts = NULL;
1640 	const char **argv = session->header.env.cmdline_argv;
1641 	int argc = session->header.env.nr_cmdline;
1642 
1643 	evlist__for_each_entry(evsel_list, counter)
1644 		perf_stat_process_counter(&stat_config, counter);
1645 
1646 	if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
1647 		update_stats(&walltime_nsecs_stats, stat_round->time);
1648 
1649 	if (stat_config.interval && stat_round->time) {
1650 		tsh.tv_sec  = stat_round->time / NSEC_PER_SEC;
1651 		tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
1652 		ts = &tsh;
1653 	}
1654 
1655 	print_counters(ts, argc, argv);
1656 	return 0;
1657 }
1658 
1659 static
1660 int process_stat_config_event(struct perf_session *session,
1661 			      union perf_event *event)
1662 {
1663 	struct perf_tool *tool = session->tool;
1664 	struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1665 
1666 	perf_event__read_stat_config(&stat_config, &event->stat_config);
1667 
1668 	if (perf_cpu_map__empty(st->cpus)) {
1669 		if (st->aggr_mode != AGGR_UNSET)
1670 			pr_warning("warning: processing task data, aggregation mode not set\n");
1671 		return 0;
1672 	}
1673 
1674 	if (st->aggr_mode != AGGR_UNSET)
1675 		stat_config.aggr_mode = st->aggr_mode;
1676 
1677 	if (perf_stat.data.is_pipe)
1678 		perf_stat_init_aggr_mode();
1679 	else
1680 		perf_stat_init_aggr_mode_file(st);
1681 
1682 	return 0;
1683 }
1684 
1685 static int set_maps(struct perf_stat *st)
1686 {
1687 	if (!st->cpus || !st->threads)
1688 		return 0;
1689 
1690 	if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
1691 		return -EINVAL;
1692 
1693 	perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
1694 
1695 	if (perf_evlist__alloc_stats(evsel_list, true))
1696 		return -ENOMEM;
1697 
1698 	st->maps_allocated = true;
1699 	return 0;
1700 }
1701 
1702 static
1703 int process_thread_map_event(struct perf_session *session,
1704 			     union perf_event *event)
1705 {
1706 	struct perf_tool *tool = session->tool;
1707 	struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1708 
1709 	if (st->threads) {
1710 		pr_warning("Extra thread map event, ignoring.\n");
1711 		return 0;
1712 	}
1713 
1714 	st->threads = thread_map__new_event(&event->thread_map);
1715 	if (!st->threads)
1716 		return -ENOMEM;
1717 
1718 	return set_maps(st);
1719 }
1720 
1721 static
1722 int process_cpu_map_event(struct perf_session *session,
1723 			  union perf_event *event)
1724 {
1725 	struct perf_tool *tool = session->tool;
1726 	struct perf_stat *st = container_of(tool, struct perf_stat, tool);
1727 	struct perf_cpu_map *cpus;
1728 
1729 	if (st->cpus) {
1730 		pr_warning("Extra cpu map event, ignoring.\n");
1731 		return 0;
1732 	}
1733 
1734 	cpus = cpu_map__new_data(&event->cpu_map.data);
1735 	if (!cpus)
1736 		return -ENOMEM;
1737 
1738 	st->cpus = cpus;
1739 	return set_maps(st);
1740 }
1741 
1742 static int runtime_stat_new(struct perf_stat_config *config, int nthreads)
1743 {
1744 	int i;
1745 
1746 	config->stats = calloc(nthreads, sizeof(struct runtime_stat));
1747 	if (!config->stats)
1748 		return -1;
1749 
1750 	config->stats_num = nthreads;
1751 
1752 	for (i = 0; i < nthreads; i++)
1753 		runtime_stat__init(&config->stats[i]);
1754 
1755 	return 0;
1756 }
1757 
1758 static void runtime_stat_delete(struct perf_stat_config *config)
1759 {
1760 	int i;
1761 
1762 	if (!config->stats)
1763 		return;
1764 
1765 	for (i = 0; i < config->stats_num; i++)
1766 		runtime_stat__exit(&config->stats[i]);
1767 
1768 	zfree(&config->stats);
1769 }
1770 
1771 static const char * const stat_report_usage[] = {
1772 	"perf stat report [<options>]",
1773 	NULL,
1774 };
1775 
1776 static struct perf_stat perf_stat = {
1777 	.tool = {
1778 		.attr		= perf_event__process_attr,
1779 		.event_update	= perf_event__process_event_update,
1780 		.thread_map	= process_thread_map_event,
1781 		.cpu_map	= process_cpu_map_event,
1782 		.stat_config	= process_stat_config_event,
1783 		.stat		= perf_event__process_stat_event,
1784 		.stat_round	= process_stat_round_event,
1785 	},
1786 	.aggr_mode = AGGR_UNSET,
1787 };
1788 
1789 static int __cmd_report(int argc, const char **argv)
1790 {
1791 	struct perf_session *session;
1792 	const struct option options[] = {
1793 	OPT_STRING('i', "input", &input_name, "file", "input file name"),
1794 	OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
1795 		     "aggregate counts per processor socket", AGGR_SOCKET),
1796 	OPT_SET_UINT(0, "per-die", &perf_stat.aggr_mode,
1797 		     "aggregate counts per processor die", AGGR_DIE),
1798 	OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
1799 		     "aggregate counts per physical processor core", AGGR_CORE),
1800 	OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
1801 		     "aggregate counts per numa node", AGGR_NODE),
1802 	OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
1803 		     "disable CPU count aggregation", AGGR_NONE),
1804 	OPT_END()
1805 	};
1806 	struct stat st;
1807 	int ret;
1808 
1809 	argc = parse_options(argc, argv, options, stat_report_usage, 0);
1810 
1811 	if (!input_name || !strlen(input_name)) {
1812 		if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
1813 			input_name = "-";
1814 		else
1815 			input_name = "perf.data";
1816 	}
1817 
1818 	perf_stat.data.path = input_name;
1819 	perf_stat.data.mode = PERF_DATA_MODE_READ;
1820 
1821 	session = perf_session__new(&perf_stat.data, false, &perf_stat.tool);
1822 	if (IS_ERR(session))
1823 		return PTR_ERR(session);
1824 
1825 	perf_stat.session  = session;
1826 	stat_config.output = stderr;
1827 	evsel_list         = session->evlist;
1828 
1829 	ret = perf_session__process_events(session);
1830 	if (ret)
1831 		return ret;
1832 
1833 	perf_session__delete(session);
1834 	return 0;
1835 }
1836 
1837 static void setup_system_wide(int forks)
1838 {
1839 	/*
1840 	 * Make system wide (-a) the default target if
1841 	 * no target was specified and one of following
1842 	 * conditions is met:
1843 	 *
1844 	 *   - there's no workload specified
1845 	 *   - there is workload specified but all requested
1846 	 *     events are system wide events
1847 	 */
1848 	if (!target__none(&target))
1849 		return;
1850 
1851 	if (!forks)
1852 		target.system_wide = true;
1853 	else {
1854 		struct evsel *counter;
1855 
1856 		evlist__for_each_entry(evsel_list, counter) {
1857 			if (!counter->core.system_wide)
1858 				return;
1859 		}
1860 
1861 		if (evsel_list->core.nr_entries)
1862 			target.system_wide = true;
1863 	}
1864 }
1865 
1866 int cmd_stat(int argc, const char **argv)
1867 {
1868 	const char * const stat_usage[] = {
1869 		"perf stat [<options>] [<command>]",
1870 		NULL
1871 	};
1872 	int status = -EINVAL, run_idx;
1873 	const char *mode;
1874 	FILE *output = stderr;
1875 	unsigned int interval, timeout;
1876 	const char * const stat_subcommands[] = { "record", "report" };
1877 
1878 	setlocale(LC_ALL, "");
1879 
1880 	evsel_list = evlist__new();
1881 	if (evsel_list == NULL)
1882 		return -ENOMEM;
1883 
1884 	parse_events__shrink_config_terms();
1885 
1886 	/* String-parsing callback-based options would segfault when negated */
1887 	set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
1888 	set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
1889 	set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
1890 
1891 	argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
1892 					(const char **) stat_usage,
1893 					PARSE_OPT_STOP_AT_NON_OPTION);
1894 	perf_stat__collect_metric_expr(evsel_list);
1895 	perf_stat__init_shadow_stats();
1896 
1897 	if (stat_config.csv_sep) {
1898 		stat_config.csv_output = true;
1899 		if (!strcmp(stat_config.csv_sep, "\\t"))
1900 			stat_config.csv_sep = "\t";
1901 	} else
1902 		stat_config.csv_sep = DEFAULT_SEPARATOR;
1903 
1904 	if (argc && !strncmp(argv[0], "rec", 3)) {
1905 		argc = __cmd_record(argc, argv);
1906 		if (argc < 0)
1907 			return -1;
1908 	} else if (argc && !strncmp(argv[0], "rep", 3))
1909 		return __cmd_report(argc, argv);
1910 
1911 	interval = stat_config.interval;
1912 	timeout = stat_config.timeout;
1913 
1914 	/*
1915 	 * For record command the -o is already taken care of.
1916 	 */
1917 	if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
1918 		output = NULL;
1919 
1920 	if (output_name && output_fd) {
1921 		fprintf(stderr, "cannot use both --output and --log-fd\n");
1922 		parse_options_usage(stat_usage, stat_options, "o", 1);
1923 		parse_options_usage(NULL, stat_options, "log-fd", 0);
1924 		goto out;
1925 	}
1926 
1927 	if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
1928 		fprintf(stderr, "--metric-only is not supported with --per-thread\n");
1929 		goto out;
1930 	}
1931 
1932 	if (stat_config.metric_only && stat_config.run_count > 1) {
1933 		fprintf(stderr, "--metric-only is not supported with -r\n");
1934 		goto out;
1935 	}
1936 
1937 	if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
1938 		fprintf(stderr, "--table is only supported with -r\n");
1939 		parse_options_usage(stat_usage, stat_options, "r", 1);
1940 		parse_options_usage(NULL, stat_options, "table", 0);
1941 		goto out;
1942 	}
1943 
1944 	if (output_fd < 0) {
1945 		fprintf(stderr, "argument to --log-fd must be a > 0\n");
1946 		parse_options_usage(stat_usage, stat_options, "log-fd", 0);
1947 		goto out;
1948 	}
1949 
1950 	if (!output) {
1951 		struct timespec tm;
1952 		mode = append_file ? "a" : "w";
1953 
1954 		output = fopen(output_name, mode);
1955 		if (!output) {
1956 			perror("failed to create output file");
1957 			return -1;
1958 		}
1959 		clock_gettime(CLOCK_REALTIME, &tm);
1960 		fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
1961 	} else if (output_fd > 0) {
1962 		mode = append_file ? "a" : "w";
1963 		output = fdopen(output_fd, mode);
1964 		if (!output) {
1965 			perror("Failed opening logfd");
1966 			return -errno;
1967 		}
1968 	}
1969 
1970 	stat_config.output = output;
1971 
1972 	/*
1973 	 * let the spreadsheet do the pretty-printing
1974 	 */
1975 	if (stat_config.csv_output) {
1976 		/* User explicitly passed -B? */
1977 		if (big_num_opt == 1) {
1978 			fprintf(stderr, "-B option not supported with -x\n");
1979 			parse_options_usage(stat_usage, stat_options, "B", 1);
1980 			parse_options_usage(NULL, stat_options, "x", 1);
1981 			goto out;
1982 		} else /* Nope, so disable big number formatting */
1983 			stat_config.big_num = false;
1984 	} else if (big_num_opt == 0) /* User passed --no-big-num */
1985 		stat_config.big_num = false;
1986 
1987 	setup_system_wide(argc);
1988 
1989 	/*
1990 	 * Display user/system times only for single
1991 	 * run and when there's specified tracee.
1992 	 */
1993 	if ((stat_config.run_count == 1) && target__none(&target))
1994 		stat_config.ru_display = true;
1995 
1996 	if (stat_config.run_count < 0) {
1997 		pr_err("Run count must be a positive number\n");
1998 		parse_options_usage(stat_usage, stat_options, "r", 1);
1999 		goto out;
2000 	} else if (stat_config.run_count == 0) {
2001 		forever = true;
2002 		stat_config.run_count = 1;
2003 	}
2004 
2005 	if (stat_config.walltime_run_table) {
2006 		stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
2007 		if (!stat_config.walltime_run) {
2008 			pr_err("failed to setup -r option");
2009 			goto out;
2010 		}
2011 	}
2012 
2013 	if ((stat_config.aggr_mode == AGGR_THREAD) &&
2014 		!target__has_task(&target)) {
2015 		if (!target.system_wide || target.cpu_list) {
2016 			fprintf(stderr, "The --per-thread option is only "
2017 				"available when monitoring via -p -t -a "
2018 				"options or only --per-thread.\n");
2019 			parse_options_usage(NULL, stat_options, "p", 1);
2020 			parse_options_usage(NULL, stat_options, "t", 1);
2021 			goto out;
2022 		}
2023 	}
2024 
2025 	/*
2026 	 * no_aggr, cgroup are for system-wide only
2027 	 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2028 	 */
2029 	if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2030 	      stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2031 	    !target__has_cpu(&target)) {
2032 		fprintf(stderr, "both cgroup and no-aggregation "
2033 			"modes only available in system-wide mode\n");
2034 
2035 		parse_options_usage(stat_usage, stat_options, "G", 1);
2036 		parse_options_usage(NULL, stat_options, "A", 1);
2037 		parse_options_usage(NULL, stat_options, "a", 1);
2038 		goto out;
2039 	}
2040 
2041 	if (add_default_attributes())
2042 		goto out;
2043 
2044 	target__validate(&target);
2045 
2046 	if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2047 		target.per_thread = true;
2048 
2049 	if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2050 		if (target__has_task(&target)) {
2051 			pr_err("Problems finding threads of monitor\n");
2052 			parse_options_usage(stat_usage, stat_options, "p", 1);
2053 			parse_options_usage(NULL, stat_options, "t", 1);
2054 		} else if (target__has_cpu(&target)) {
2055 			perror("failed to parse CPUs map");
2056 			parse_options_usage(stat_usage, stat_options, "C", 1);
2057 			parse_options_usage(NULL, stat_options, "a", 1);
2058 		}
2059 		goto out;
2060 	}
2061 
2062 	/*
2063 	 * Initialize thread_map with comm names,
2064 	 * so we could print it out on output.
2065 	 */
2066 	if (stat_config.aggr_mode == AGGR_THREAD) {
2067 		thread_map__read_comms(evsel_list->core.threads);
2068 		if (target.system_wide) {
2069 			if (runtime_stat_new(&stat_config,
2070 				perf_thread_map__nr(evsel_list->core.threads))) {
2071 				goto out;
2072 			}
2073 		}
2074 	}
2075 
2076 	if (stat_config.aggr_mode == AGGR_NODE)
2077 		cpu__setup_cpunode_map();
2078 
2079 	if (stat_config.times && interval)
2080 		interval_count = true;
2081 	else if (stat_config.times && !interval) {
2082 		pr_err("interval-count option should be used together with "
2083 				"interval-print.\n");
2084 		parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2085 		parse_options_usage(stat_usage, stat_options, "I", 1);
2086 		goto out;
2087 	}
2088 
2089 	if (timeout && timeout < 100) {
2090 		if (timeout < 10) {
2091 			pr_err("timeout must be >= 10ms.\n");
2092 			parse_options_usage(stat_usage, stat_options, "timeout", 0);
2093 			goto out;
2094 		} else
2095 			pr_warning("timeout < 100ms. "
2096 				   "The overhead percentage could be high in some cases. "
2097 				   "Please proceed with caution.\n");
2098 	}
2099 	if (timeout && interval) {
2100 		pr_err("timeout option is not supported with interval-print.\n");
2101 		parse_options_usage(stat_usage, stat_options, "timeout", 0);
2102 		parse_options_usage(stat_usage, stat_options, "I", 1);
2103 		goto out;
2104 	}
2105 
2106 	if (perf_evlist__alloc_stats(evsel_list, interval))
2107 		goto out;
2108 
2109 	if (perf_stat_init_aggr_mode())
2110 		goto out;
2111 
2112 	/*
2113 	 * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2114 	 * while avoiding that older tools show confusing messages.
2115 	 *
2116 	 * However for pipe sessions we need to keep it zero,
2117 	 * because script's perf_evsel__check_attr is triggered
2118 	 * by attr->sample_type != 0, and we can't run it on
2119 	 * stat sessions.
2120 	 */
2121 	stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2122 
2123 	/*
2124 	 * We dont want to block the signals - that would cause
2125 	 * child tasks to inherit that and Ctrl-C would not work.
2126 	 * What we want is for Ctrl-C to work in the exec()-ed
2127 	 * task, but being ignored by perf stat itself:
2128 	 */
2129 	atexit(sig_atexit);
2130 	if (!forever)
2131 		signal(SIGINT,  skip_signal);
2132 	signal(SIGCHLD, skip_signal);
2133 	signal(SIGALRM, skip_signal);
2134 	signal(SIGABRT, skip_signal);
2135 
2136 	status = 0;
2137 	for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
2138 		if (stat_config.run_count != 1 && verbose > 0)
2139 			fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2140 				run_idx + 1);
2141 
2142 		if (run_idx != 0)
2143 			perf_evlist__reset_prev_raw_counts(evsel_list);
2144 
2145 		status = run_perf_stat(argc, argv, run_idx);
2146 		if (forever && status != -1 && !interval) {
2147 			print_counters(NULL, argc, argv);
2148 			perf_stat__reset_stats();
2149 		}
2150 	}
2151 
2152 	if (!forever && status != -1 && !interval)
2153 		print_counters(NULL, argc, argv);
2154 
2155 	if (STAT_RECORD) {
2156 		/*
2157 		 * We synthesize the kernel mmap record just so that older tools
2158 		 * don't emit warnings about not being able to resolve symbols
2159 		 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2160 		 * a saner message about no samples being in the perf.data file.
2161 		 *
2162 		 * This also serves to suppress a warning about f_header.data.size == 0
2163 		 * in header.c at the moment 'perf stat record' gets introduced, which
2164 		 * is not really needed once we start adding the stat specific PERF_RECORD_
2165 		 * records, but the need to suppress the kptr_restrict messages in older
2166 		 * tools remain  -acme
2167 		 */
2168 		int fd = perf_data__fd(&perf_stat.data);
2169 		int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2170 							     process_synthesized_event,
2171 							     &perf_stat.session->machines.host);
2172 		if (err) {
2173 			pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2174 				   "older tools may produce warnings about this file\n.");
2175 		}
2176 
2177 		if (!interval) {
2178 			if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2179 				pr_err("failed to write stat round event\n");
2180 		}
2181 
2182 		if (!perf_stat.data.is_pipe) {
2183 			perf_stat.session->header.data_size += perf_stat.bytes_written;
2184 			perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2185 		}
2186 
2187 		evlist__close(evsel_list);
2188 		perf_session__delete(perf_stat.session);
2189 	}
2190 
2191 	perf_stat__exit_aggr_mode();
2192 	perf_evlist__free_stats(evsel_list);
2193 out:
2194 	zfree(&stat_config.walltime_run);
2195 
2196 	if (smi_cost && smi_reset)
2197 		sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2198 
2199 	evlist__delete(evsel_list);
2200 
2201 	runtime_stat_delete(&stat_config);
2202 
2203 	return status;
2204 }
2205