xref: /linux/tools/perf/builtin-stat.c (revision 8dc364fa484df22d301a16148d1b356931d0cbb0)
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 "util/cgroup.h"
45 #include <subcmd/parse-options.h>
46 #include "util/parse-events.h"
47 #include "util/pmus.h"
48 #include "util/pmu.h"
49 #include "util/tool_pmu.h"
50 #include "util/event.h"
51 #include "util/evlist.h"
52 #include "util/evsel.h"
53 #include "util/debug.h"
54 #include "util/color.h"
55 #include "util/stat.h"
56 #include "util/header.h"
57 #include "util/cpumap.h"
58 #include "util/thread_map.h"
59 #include "util/counts.h"
60 #include "util/topdown.h"
61 #include "util/session.h"
62 #include "util/tool.h"
63 #include "util/string2.h"
64 #include "util/metricgroup.h"
65 #include "util/synthetic-events.h"
66 #include "util/target.h"
67 #include "util/time-utils.h"
68 #include "util/top.h"
69 #include "util/affinity.h"
70 #include "util/pfm.h"
71 #include "util/bpf_counter.h"
72 #include "util/iostat.h"
73 #include "util/util.h"
74 #include "util/intel-tpebs.h"
75 #include "asm/bug.h"
76 
77 #include <linux/time64.h>
78 #include <linux/zalloc.h>
79 #include <api/fs/fs.h>
80 #include <errno.h>
81 #include <signal.h>
82 #include <stdlib.h>
83 #include <sys/prctl.h>
84 #include <inttypes.h>
85 #include <locale.h>
86 #include <math.h>
87 #include <sys/types.h>
88 #include <sys/stat.h>
89 #include <sys/wait.h>
90 #include <unistd.h>
91 #include <sys/time.h>
92 #include <sys/resource.h>
93 #include <linux/err.h>
94 
95 #include <linux/ctype.h>
96 #include <perf/evlist.h>
97 #include <internal/threadmap.h>
98 
99 #define DEFAULT_SEPARATOR	" "
100 #define FREEZE_ON_SMI_PATH	"bus/event_source/devices/cpu/freeze_on_smi"
101 
102 static void print_counters(struct timespec *ts, int argc, const char **argv);
103 
104 static struct evlist	*evsel_list;
105 static struct parse_events_option_args parse_events_option_args = {
106 	.evlistp = &evsel_list,
107 };
108 
109 static bool all_counters_use_bpf = true;
110 
111 static struct target target;
112 
113 static volatile sig_atomic_t	child_pid			= -1;
114 static int			detailed_run			=  0;
115 static bool			transaction_run;
116 static bool			topdown_run			= false;
117 static bool			smi_cost			= false;
118 static bool			smi_reset			= false;
119 static int			big_num_opt			=  -1;
120 static const char		*pre_cmd			= NULL;
121 static const char		*post_cmd			= NULL;
122 static bool			sync_run			= false;
123 static bool			forever				= false;
124 static bool			force_metric_only		= false;
125 static struct timespec		ref_time;
126 static bool			append_file;
127 static bool			interval_count;
128 static const char		*output_name;
129 static int			output_fd;
130 static char			*metrics;
131 
132 struct perf_stat {
133 	bool			 record;
134 	struct perf_data	 data;
135 	struct perf_session	*session;
136 	u64			 bytes_written;
137 	struct perf_tool	 tool;
138 	bool			 maps_allocated;
139 	struct perf_cpu_map	*cpus;
140 	struct perf_thread_map *threads;
141 	enum aggr_mode		 aggr_mode;
142 	u32			 aggr_level;
143 };
144 
145 static struct perf_stat		perf_stat;
146 #define STAT_RECORD		perf_stat.record
147 
148 static volatile sig_atomic_t done = 0;
149 
150 /* Options set from the command line. */
151 struct opt_aggr_mode {
152 	bool node, socket, die, cluster, cache, core, thread, no_aggr;
153 };
154 
155 /* Turn command line option into most generic aggregation mode setting. */
156 static enum aggr_mode opt_aggr_mode_to_aggr_mode(struct opt_aggr_mode *opt_mode)
157 {
158 	enum aggr_mode mode = AGGR_GLOBAL;
159 
160 	if (opt_mode->node)
161 		mode = AGGR_NODE;
162 	if (opt_mode->socket)
163 		mode = AGGR_SOCKET;
164 	if (opt_mode->die)
165 		mode = AGGR_DIE;
166 	if (opt_mode->cluster)
167 		mode = AGGR_CLUSTER;
168 	if (opt_mode->cache)
169 		mode = AGGR_CACHE;
170 	if (opt_mode->core)
171 		mode = AGGR_CORE;
172 	if (opt_mode->thread)
173 		mode = AGGR_THREAD;
174 	if (opt_mode->no_aggr)
175 		mode = AGGR_NONE;
176 	return mode;
177 }
178 
179 static void evlist__check_cpu_maps(struct evlist *evlist)
180 {
181 	struct evsel *evsel, *warned_leader = NULL;
182 
183 	evlist__for_each_entry(evlist, evsel) {
184 		struct evsel *leader = evsel__leader(evsel);
185 
186 		/* Check that leader matches cpus with each member. */
187 		if (leader == evsel)
188 			continue;
189 		if (perf_cpu_map__equal(leader->core.cpus, evsel->core.cpus))
190 			continue;
191 
192 		/* If there's mismatch disable the group and warn user. */
193 		if (warned_leader != leader) {
194 			char buf[200];
195 
196 			pr_warning("WARNING: grouped events cpus do not match.\n"
197 				"Events with CPUs not matching the leader will "
198 				"be removed from the group.\n");
199 			evsel__group_desc(leader, buf, sizeof(buf));
200 			pr_warning("  %s\n", buf);
201 			warned_leader = leader;
202 		}
203 		if (verbose > 0) {
204 			char buf[200];
205 
206 			cpu_map__snprint(leader->core.cpus, buf, sizeof(buf));
207 			pr_warning("     %s: %s\n", leader->name, buf);
208 			cpu_map__snprint(evsel->core.cpus, buf, sizeof(buf));
209 			pr_warning("     %s: %s\n", evsel->name, buf);
210 		}
211 
212 		evsel__remove_from_group(evsel, leader);
213 	}
214 }
215 
216 static inline void diff_timespec(struct timespec *r, struct timespec *a,
217 				 struct timespec *b)
218 {
219 	r->tv_sec = a->tv_sec - b->tv_sec;
220 	if (a->tv_nsec < b->tv_nsec) {
221 		r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
222 		r->tv_sec--;
223 	} else {
224 		r->tv_nsec = a->tv_nsec - b->tv_nsec ;
225 	}
226 }
227 
228 static void perf_stat__reset_stats(void)
229 {
230 	evlist__reset_stats(evsel_list);
231 	perf_stat__reset_shadow_stats();
232 }
233 
234 static int process_synthesized_event(const struct perf_tool *tool __maybe_unused,
235 				     union perf_event *event,
236 				     struct perf_sample *sample __maybe_unused,
237 				     struct machine *machine __maybe_unused)
238 {
239 	if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
240 		pr_err("failed to write perf data, error: %m\n");
241 		return -1;
242 	}
243 
244 	perf_stat.bytes_written += event->header.size;
245 	return 0;
246 }
247 
248 static int write_stat_round_event(u64 tm, u64 type)
249 {
250 	return perf_event__synthesize_stat_round(NULL, tm, type,
251 						 process_synthesized_event,
252 						 NULL);
253 }
254 
255 #define WRITE_STAT_ROUND_EVENT(time, interval) \
256 	write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
257 
258 #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
259 
260 static int evsel__write_stat_event(struct evsel *counter, int cpu_map_idx, u32 thread,
261 				   struct perf_counts_values *count)
262 {
263 	struct perf_sample_id *sid = SID(counter, cpu_map_idx, thread);
264 	struct perf_cpu cpu = perf_cpu_map__cpu(evsel__cpus(counter), cpu_map_idx);
265 
266 	return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
267 					   process_synthesized_event, NULL);
268 }
269 
270 static int read_single_counter(struct evsel *counter, int cpu_map_idx, int thread)
271 {
272 	int err = evsel__read_counter(counter, cpu_map_idx, thread);
273 
274 	/*
275 	 * Reading user and system time will fail when the process
276 	 * terminates. Use the wait4 values in that case.
277 	 */
278 	if (err && cpu_map_idx == 0 &&
279 	    (evsel__tool_event(counter) == TOOL_PMU__EVENT_USER_TIME ||
280 	     evsel__tool_event(counter) == TOOL_PMU__EVENT_SYSTEM_TIME)) {
281 		u64 val, *start_time;
282 		struct perf_counts_values *count =
283 			perf_counts(counter->counts, cpu_map_idx, thread);
284 
285 		start_time = xyarray__entry(counter->start_times, cpu_map_idx, thread);
286 		if (evsel__tool_event(counter) == TOOL_PMU__EVENT_USER_TIME)
287 			val = ru_stats.ru_utime_usec_stat.mean;
288 		else
289 			val = ru_stats.ru_stime_usec_stat.mean;
290 		count->ena = count->run = *start_time + val;
291 		count->val = val;
292 		return 0;
293 	}
294 	return err;
295 }
296 
297 /*
298  * Read out the results of a single counter:
299  * do not aggregate counts across CPUs in system-wide mode
300  */
301 static int read_counter_cpu(struct evsel *counter, int cpu_map_idx)
302 {
303 	int nthreads = perf_thread_map__nr(evsel_list->core.threads);
304 	int thread;
305 
306 	if (!counter->supported)
307 		return -ENOENT;
308 
309 	for (thread = 0; thread < nthreads; thread++) {
310 		struct perf_counts_values *count;
311 
312 		count = perf_counts(counter->counts, cpu_map_idx, thread);
313 
314 		/*
315 		 * The leader's group read loads data into its group members
316 		 * (via evsel__read_counter()) and sets their count->loaded.
317 		 */
318 		if (!perf_counts__is_loaded(counter->counts, cpu_map_idx, thread) &&
319 		    read_single_counter(counter, cpu_map_idx, thread)) {
320 			counter->counts->scaled = -1;
321 			perf_counts(counter->counts, cpu_map_idx, thread)->ena = 0;
322 			perf_counts(counter->counts, cpu_map_idx, thread)->run = 0;
323 			return -1;
324 		}
325 
326 		perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, false);
327 
328 		if (STAT_RECORD) {
329 			if (evsel__write_stat_event(counter, cpu_map_idx, thread, count)) {
330 				pr_err("failed to write stat event\n");
331 				return -1;
332 			}
333 		}
334 
335 		if (verbose > 1) {
336 			fprintf(stat_config.output,
337 				"%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
338 					evsel__name(counter),
339 					perf_cpu_map__cpu(evsel__cpus(counter),
340 							  cpu_map_idx).cpu,
341 					count->val, count->ena, count->run);
342 		}
343 	}
344 
345 	return 0;
346 }
347 
348 static int read_affinity_counters(void)
349 {
350 	struct evlist_cpu_iterator evlist_cpu_itr;
351 	struct affinity saved_affinity, *affinity;
352 
353 	if (all_counters_use_bpf)
354 		return 0;
355 
356 	if (!target__has_cpu(&target) || target__has_per_thread(&target))
357 		affinity = NULL;
358 	else if (affinity__setup(&saved_affinity) < 0)
359 		return -1;
360 	else
361 		affinity = &saved_affinity;
362 
363 	evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
364 		struct evsel *counter = evlist_cpu_itr.evsel;
365 
366 		if (evsel__is_bpf(counter))
367 			continue;
368 
369 		if (!counter->err)
370 			counter->err = read_counter_cpu(counter, evlist_cpu_itr.cpu_map_idx);
371 	}
372 	if (affinity)
373 		affinity__cleanup(&saved_affinity);
374 
375 	return 0;
376 }
377 
378 static int read_bpf_map_counters(void)
379 {
380 	struct evsel *counter;
381 	int err;
382 
383 	evlist__for_each_entry(evsel_list, counter) {
384 		if (!evsel__is_bpf(counter))
385 			continue;
386 
387 		err = bpf_counter__read(counter);
388 		if (err)
389 			return err;
390 	}
391 	return 0;
392 }
393 
394 static int read_counters(void)
395 {
396 	if (!stat_config.stop_read_counter) {
397 		if (read_bpf_map_counters() ||
398 		    read_affinity_counters())
399 			return -1;
400 	}
401 	return 0;
402 }
403 
404 static void process_counters(void)
405 {
406 	struct evsel *counter;
407 
408 	evlist__for_each_entry(evsel_list, counter) {
409 		if (counter->err)
410 			pr_debug("failed to read counter %s\n", counter->name);
411 		if (counter->err == 0 && perf_stat_process_counter(&stat_config, counter))
412 			pr_warning("failed to process counter %s\n", counter->name);
413 		counter->err = 0;
414 	}
415 
416 	perf_stat_merge_counters(&stat_config, evsel_list);
417 	perf_stat_process_percore(&stat_config, evsel_list);
418 }
419 
420 static void process_interval(void)
421 {
422 	struct timespec ts, rs;
423 
424 	clock_gettime(CLOCK_MONOTONIC, &ts);
425 	diff_timespec(&rs, &ts, &ref_time);
426 
427 	evlist__reset_aggr_stats(evsel_list);
428 
429 	if (read_counters() == 0)
430 		process_counters();
431 
432 	if (STAT_RECORD) {
433 		if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
434 			pr_err("failed to write stat round event\n");
435 	}
436 
437 	init_stats(&walltime_nsecs_stats);
438 	update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000ULL);
439 	print_counters(&rs, 0, NULL);
440 }
441 
442 static bool handle_interval(unsigned int interval, int *times)
443 {
444 	if (interval) {
445 		process_interval();
446 		if (interval_count && !(--(*times)))
447 			return true;
448 	}
449 	return false;
450 }
451 
452 static int enable_counters(void)
453 {
454 	struct evsel *evsel;
455 	int err;
456 
457 	evlist__for_each_entry(evsel_list, evsel) {
458 		if (!evsel__is_bpf(evsel))
459 			continue;
460 
461 		err = bpf_counter__enable(evsel);
462 		if (err)
463 			return err;
464 	}
465 
466 	if (!target__enable_on_exec(&target)) {
467 		if (!all_counters_use_bpf)
468 			evlist__enable(evsel_list);
469 	}
470 	return 0;
471 }
472 
473 static void disable_counters(void)
474 {
475 	struct evsel *counter;
476 
477 	/*
478 	 * If we don't have tracee (attaching to task or cpu), counters may
479 	 * still be running. To get accurate group ratios, we must stop groups
480 	 * from counting before reading their constituent counters.
481 	 */
482 	if (!target__none(&target)) {
483 		evlist__for_each_entry(evsel_list, counter)
484 			bpf_counter__disable(counter);
485 		if (!all_counters_use_bpf)
486 			evlist__disable(evsel_list);
487 	}
488 }
489 
490 static volatile sig_atomic_t workload_exec_errno;
491 
492 /*
493  * evlist__prepare_workload will send a SIGUSR1
494  * if the fork fails, since we asked by setting its
495  * want_signal to true.
496  */
497 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
498 					void *ucontext __maybe_unused)
499 {
500 	workload_exec_errno = info->si_value.sival_int;
501 }
502 
503 static bool evsel__should_store_id(struct evsel *counter)
504 {
505 	return STAT_RECORD || counter->core.attr.read_format & PERF_FORMAT_ID;
506 }
507 
508 static bool is_target_alive(struct target *_target,
509 			    struct perf_thread_map *threads)
510 {
511 	struct stat st;
512 	int i;
513 
514 	if (!target__has_task(_target))
515 		return true;
516 
517 	for (i = 0; i < threads->nr; i++) {
518 		char path[PATH_MAX];
519 
520 		scnprintf(path, PATH_MAX, "%s/%d", procfs__mountpoint(),
521 			  threads->map[i].pid);
522 
523 		if (!stat(path, &st))
524 			return true;
525 	}
526 
527 	return false;
528 }
529 
530 static void process_evlist(struct evlist *evlist, unsigned int interval)
531 {
532 	enum evlist_ctl_cmd cmd = EVLIST_CTL_CMD_UNSUPPORTED;
533 
534 	if (evlist__ctlfd_process(evlist, &cmd) > 0) {
535 		switch (cmd) {
536 		case EVLIST_CTL_CMD_ENABLE:
537 			fallthrough;
538 		case EVLIST_CTL_CMD_DISABLE:
539 			if (interval)
540 				process_interval();
541 			break;
542 		case EVLIST_CTL_CMD_SNAPSHOT:
543 		case EVLIST_CTL_CMD_ACK:
544 		case EVLIST_CTL_CMD_UNSUPPORTED:
545 		case EVLIST_CTL_CMD_EVLIST:
546 		case EVLIST_CTL_CMD_STOP:
547 		case EVLIST_CTL_CMD_PING:
548 		default:
549 			break;
550 		}
551 	}
552 }
553 
554 static void compute_tts(struct timespec *time_start, struct timespec *time_stop,
555 			int *time_to_sleep)
556 {
557 	int tts = *time_to_sleep;
558 	struct timespec time_diff;
559 
560 	diff_timespec(&time_diff, time_stop, time_start);
561 
562 	tts -= time_diff.tv_sec * MSEC_PER_SEC +
563 	       time_diff.tv_nsec / NSEC_PER_MSEC;
564 
565 	if (tts < 0)
566 		tts = 0;
567 
568 	*time_to_sleep = tts;
569 }
570 
571 static int dispatch_events(bool forks, int timeout, int interval, int *times)
572 {
573 	int child_exited = 0, status = 0;
574 	int time_to_sleep, sleep_time;
575 	struct timespec time_start, time_stop;
576 
577 	if (interval)
578 		sleep_time = interval;
579 	else if (timeout)
580 		sleep_time = timeout;
581 	else
582 		sleep_time = 1000;
583 
584 	time_to_sleep = sleep_time;
585 
586 	while (!done) {
587 		if (forks)
588 			child_exited = waitpid(child_pid, &status, WNOHANG);
589 		else
590 			child_exited = !is_target_alive(&target, evsel_list->core.threads) ? 1 : 0;
591 
592 		if (child_exited)
593 			break;
594 
595 		clock_gettime(CLOCK_MONOTONIC, &time_start);
596 		if (!(evlist__poll(evsel_list, time_to_sleep) > 0)) { /* poll timeout or EINTR */
597 			if (timeout || handle_interval(interval, times))
598 				break;
599 			time_to_sleep = sleep_time;
600 		} else { /* fd revent */
601 			process_evlist(evsel_list, interval);
602 			clock_gettime(CLOCK_MONOTONIC, &time_stop);
603 			compute_tts(&time_start, &time_stop, &time_to_sleep);
604 		}
605 	}
606 
607 	return status;
608 }
609 
610 enum counter_recovery {
611 	COUNTER_SKIP,
612 	COUNTER_RETRY,
613 	COUNTER_FATAL,
614 };
615 
616 static enum counter_recovery stat_handle_error(struct evsel *counter, int err)
617 {
618 	char msg[BUFSIZ];
619 
620 	if (counter->skippable) {
621 		if (verbose > 0) {
622 			ui__warning("skipping event %s that kernel failed to open .\n",
623 				    evsel__name(counter));
624 		}
625 		counter->supported = false;
626 		counter->errored = true;
627 		return COUNTER_SKIP;
628 	}
629 
630 	/*
631 	 * PPC returns ENXIO for HW counters until 2.6.37
632 	 * (behavior changed with commit b0a873e).
633 	 */
634 	if (err == EINVAL || err == ENOSYS || err == ENOENT || err == ENXIO) {
635 		if (verbose > 0) {
636 			ui__warning("%s event is not supported by the kernel.\n",
637 				    evsel__name(counter));
638 		}
639 		counter->supported = false;
640 		/*
641 		 * errored is a sticky flag that means one of the counter's
642 		 * cpu event had a problem and needs to be reexamined.
643 		 */
644 		counter->errored = true;
645 	} else if (evsel__fallback(counter, &target, err, msg, sizeof(msg))) {
646 		if (verbose > 0)
647 			ui__warning("%s\n", msg);
648 		return COUNTER_RETRY;
649 	} else if (target__has_per_thread(&target) && err != EOPNOTSUPP &&
650 		   evsel_list->core.threads &&
651 		   evsel_list->core.threads->err_thread != -1) {
652 		/*
653 		 * For global --per-thread case, skip current
654 		 * error thread.
655 		 */
656 		if (!thread_map__remove(evsel_list->core.threads,
657 					evsel_list->core.threads->err_thread)) {
658 			evsel_list->core.threads->err_thread = -1;
659 			return COUNTER_RETRY;
660 		}
661 	} else if (err == EOPNOTSUPP) {
662 		if (verbose > 0) {
663 			ui__warning("%s event is not supported by the kernel.\n",
664 				    evsel__name(counter));
665 		}
666 		counter->supported = false;
667 		counter->errored = true;
668 	}
669 
670 	evsel__open_strerror(counter, &target, err, msg, sizeof(msg));
671 	ui__error("%s\n", msg);
672 
673 	if (child_pid != -1)
674 		kill(child_pid, SIGTERM);
675 
676 	return COUNTER_FATAL;
677 }
678 
679 static int __run_perf_stat(int argc, const char **argv, int run_idx)
680 {
681 	int interval = stat_config.interval;
682 	int times = stat_config.times;
683 	int timeout = stat_config.timeout;
684 	char msg[BUFSIZ];
685 	unsigned long long t0, t1;
686 	struct evsel *counter;
687 	size_t l;
688 	int status = 0;
689 	const bool forks = (argc > 0);
690 	bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
691 	struct evlist_cpu_iterator evlist_cpu_itr;
692 	struct affinity saved_affinity, *affinity = NULL;
693 	int err;
694 	bool second_pass = false;
695 
696 	if (forks) {
697 		if (evlist__prepare_workload(evsel_list, &target, argv, is_pipe, workload_exec_failed_signal) < 0) {
698 			perror("failed to prepare workload");
699 			return -1;
700 		}
701 		child_pid = evsel_list->workload.pid;
702 	}
703 
704 	if (!cpu_map__is_dummy(evsel_list->core.user_requested_cpus)) {
705 		if (affinity__setup(&saved_affinity) < 0) {
706 			err = -1;
707 			goto err_out;
708 		}
709 		affinity = &saved_affinity;
710 	}
711 
712 	evlist__for_each_entry(evsel_list, counter) {
713 		counter->reset_group = false;
714 		if (bpf_counter__load(counter, &target)) {
715 			err = -1;
716 			goto err_out;
717 		}
718 		if (!(evsel__is_bperf(counter)))
719 			all_counters_use_bpf = false;
720 	}
721 
722 	evlist__reset_aggr_stats(evsel_list);
723 
724 	evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
725 		counter = evlist_cpu_itr.evsel;
726 
727 		/*
728 		 * bperf calls evsel__open_per_cpu() in bperf__load(), so
729 		 * no need to call it again here.
730 		 */
731 		if (target.use_bpf)
732 			break;
733 
734 		if (counter->reset_group || counter->errored)
735 			continue;
736 		if (evsel__is_bperf(counter))
737 			continue;
738 try_again:
739 		if (create_perf_stat_counter(counter, &stat_config, &target,
740 					     evlist_cpu_itr.cpu_map_idx) < 0) {
741 
742 			/*
743 			 * Weak group failed. We cannot just undo this here
744 			 * because earlier CPUs might be in group mode, and the kernel
745 			 * doesn't support mixing group and non group reads. Defer
746 			 * it to later.
747 			 * Don't close here because we're in the wrong affinity.
748 			 */
749 			if ((errno == EINVAL || errno == EBADF) &&
750 				evsel__leader(counter) != counter &&
751 				counter->weak_group) {
752 				evlist__reset_weak_group(evsel_list, counter, false);
753 				assert(counter->reset_group);
754 				second_pass = true;
755 				continue;
756 			}
757 
758 			switch (stat_handle_error(counter, errno)) {
759 			case COUNTER_FATAL:
760 				err = -1;
761 				goto err_out;
762 			case COUNTER_RETRY:
763 				goto try_again;
764 			case COUNTER_SKIP:
765 				continue;
766 			default:
767 				break;
768 			}
769 
770 		}
771 		counter->supported = true;
772 	}
773 
774 	if (second_pass) {
775 		/*
776 		 * Now redo all the weak group after closing them,
777 		 * and also close errored counters.
778 		 */
779 
780 		/* First close errored or weak retry */
781 		evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
782 			counter = evlist_cpu_itr.evsel;
783 
784 			if (!counter->reset_group && !counter->errored)
785 				continue;
786 
787 			perf_evsel__close_cpu(&counter->core, evlist_cpu_itr.cpu_map_idx);
788 		}
789 		/* Now reopen weak */
790 		evlist__for_each_cpu(evlist_cpu_itr, evsel_list, affinity) {
791 			counter = evlist_cpu_itr.evsel;
792 
793 			if (!counter->reset_group)
794 				continue;
795 try_again_reset:
796 			pr_debug2("reopening weak %s\n", evsel__name(counter));
797 			if (create_perf_stat_counter(counter, &stat_config, &target,
798 						     evlist_cpu_itr.cpu_map_idx) < 0) {
799 
800 				switch (stat_handle_error(counter, errno)) {
801 				case COUNTER_FATAL:
802 					err = -1;
803 					goto err_out;
804 				case COUNTER_RETRY:
805 					goto try_again_reset;
806 				case COUNTER_SKIP:
807 					continue;
808 				default:
809 					break;
810 				}
811 			}
812 			counter->supported = true;
813 		}
814 	}
815 	affinity__cleanup(affinity);
816 	affinity = NULL;
817 
818 	evlist__for_each_entry(evsel_list, counter) {
819 		if (!counter->supported) {
820 			perf_evsel__free_fd(&counter->core);
821 			continue;
822 		}
823 
824 		l = strlen(counter->unit);
825 		if (l > stat_config.unit_width)
826 			stat_config.unit_width = l;
827 
828 		if (evsel__should_store_id(counter) &&
829 		    evsel__store_ids(counter, evsel_list)) {
830 			err = -1;
831 			goto err_out;
832 		}
833 	}
834 
835 	if (evlist__apply_filters(evsel_list, &counter, &target)) {
836 		pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
837 			counter->filter, evsel__name(counter), errno,
838 			str_error_r(errno, msg, sizeof(msg)));
839 		return -1;
840 	}
841 
842 	if (STAT_RECORD) {
843 		int fd = perf_data__fd(&perf_stat.data);
844 
845 		if (is_pipe) {
846 			err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
847 		} else {
848 			err = perf_session__write_header(perf_stat.session, evsel_list,
849 							 fd, false);
850 		}
851 
852 		if (err < 0)
853 			goto err_out;
854 
855 		err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
856 							 process_synthesized_event, is_pipe);
857 		if (err < 0)
858 			goto err_out;
859 
860 	}
861 
862 	if (target.initial_delay) {
863 		pr_info(EVLIST_DISABLED_MSG);
864 	} else {
865 		err = enable_counters();
866 		if (err) {
867 			err = -1;
868 			goto err_out;
869 		}
870 	}
871 
872 	/* Exec the command, if any */
873 	if (forks)
874 		evlist__start_workload(evsel_list);
875 
876 	if (target.initial_delay > 0) {
877 		usleep(target.initial_delay * USEC_PER_MSEC);
878 		err = enable_counters();
879 		if (err) {
880 			err = -1;
881 			goto err_out;
882 		}
883 
884 		pr_info(EVLIST_ENABLED_MSG);
885 	}
886 
887 	t0 = rdclock();
888 	clock_gettime(CLOCK_MONOTONIC, &ref_time);
889 
890 	if (forks) {
891 		if (interval || timeout || evlist__ctlfd_initialized(evsel_list))
892 			status = dispatch_events(forks, timeout, interval, &times);
893 		if (child_pid != -1) {
894 			if (timeout)
895 				kill(child_pid, SIGTERM);
896 			wait4(child_pid, &status, 0, &stat_config.ru_data);
897 		}
898 
899 		if (workload_exec_errno) {
900 			const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
901 			pr_err("Workload failed: %s\n", emsg);
902 			err = -1;
903 			goto err_out;
904 		}
905 
906 		if (WIFSIGNALED(status))
907 			psignal(WTERMSIG(status), argv[0]);
908 	} else {
909 		status = dispatch_events(forks, timeout, interval, &times);
910 	}
911 
912 	disable_counters();
913 
914 	t1 = rdclock();
915 
916 	if (stat_config.walltime_run_table)
917 		stat_config.walltime_run[run_idx] = t1 - t0;
918 
919 	if (interval && stat_config.summary) {
920 		stat_config.interval = 0;
921 		stat_config.stop_read_counter = true;
922 		init_stats(&walltime_nsecs_stats);
923 		update_stats(&walltime_nsecs_stats, t1 - t0);
924 
925 		evlist__copy_prev_raw_counts(evsel_list);
926 		evlist__reset_prev_raw_counts(evsel_list);
927 		evlist__reset_aggr_stats(evsel_list);
928 	} else {
929 		update_stats(&walltime_nsecs_stats, t1 - t0);
930 		update_rusage_stats(&ru_stats, &stat_config.ru_data);
931 	}
932 
933 	/*
934 	 * Closing a group leader splits the group, and as we only disable
935 	 * group leaders, results in remaining events becoming enabled. To
936 	 * avoid arbitrary skew, we must read all counters before closing any
937 	 * group leaders.
938 	 */
939 	if (read_counters() == 0)
940 		process_counters();
941 
942 	/*
943 	 * We need to keep evsel_list alive, because it's processed
944 	 * later the evsel_list will be closed after.
945 	 */
946 	if (!STAT_RECORD)
947 		evlist__close(evsel_list);
948 
949 	return WEXITSTATUS(status);
950 
951 err_out:
952 	if (forks)
953 		evlist__cancel_workload(evsel_list);
954 
955 	affinity__cleanup(affinity);
956 	return err;
957 }
958 
959 /*
960  * Returns -1 for fatal errors which signifies to not continue
961  * when in repeat mode.
962  *
963  * Returns < -1 error codes when stat record is used. These
964  * result in the stat information being displayed, but writing
965  * to the file fails and is non fatal.
966  */
967 static int run_perf_stat(int argc, const char **argv, int run_idx)
968 {
969 	int ret;
970 
971 	if (pre_cmd) {
972 		ret = system(pre_cmd);
973 		if (ret)
974 			return ret;
975 	}
976 
977 	if (sync_run)
978 		sync();
979 
980 	ret = __run_perf_stat(argc, argv, run_idx);
981 	if (ret)
982 		return ret;
983 
984 	if (post_cmd) {
985 		ret = system(post_cmd);
986 		if (ret)
987 			return ret;
988 	}
989 
990 	return ret;
991 }
992 
993 static void print_counters(struct timespec *ts, int argc, const char **argv)
994 {
995 	/* Do not print anything if we record to the pipe. */
996 	if (STAT_RECORD && perf_stat.data.is_pipe)
997 		return;
998 	if (quiet)
999 		return;
1000 
1001 	evlist__print_counters(evsel_list, &stat_config, &target, ts, argc, argv);
1002 }
1003 
1004 static volatile sig_atomic_t signr = -1;
1005 
1006 static void skip_signal(int signo)
1007 {
1008 	if ((child_pid == -1) || stat_config.interval)
1009 		done = 1;
1010 
1011 	signr = signo;
1012 	/*
1013 	 * render child_pid harmless
1014 	 * won't send SIGTERM to a random
1015 	 * process in case of race condition
1016 	 * and fast PID recycling
1017 	 */
1018 	child_pid = -1;
1019 }
1020 
1021 static void sig_atexit(void)
1022 {
1023 	sigset_t set, oset;
1024 
1025 	/*
1026 	 * avoid race condition with SIGCHLD handler
1027 	 * in skip_signal() which is modifying child_pid
1028 	 * goal is to avoid send SIGTERM to a random
1029 	 * process
1030 	 */
1031 	sigemptyset(&set);
1032 	sigaddset(&set, SIGCHLD);
1033 	sigprocmask(SIG_BLOCK, &set, &oset);
1034 
1035 	if (child_pid != -1)
1036 		kill(child_pid, SIGTERM);
1037 
1038 	sigprocmask(SIG_SETMASK, &oset, NULL);
1039 
1040 	if (signr == -1)
1041 		return;
1042 
1043 	signal(signr, SIG_DFL);
1044 	kill(getpid(), signr);
1045 }
1046 
1047 static int stat__set_big_num(const struct option *opt __maybe_unused,
1048 			     const char *s __maybe_unused, int unset)
1049 {
1050 	big_num_opt = unset ? 0 : 1;
1051 	perf_stat__set_big_num(!unset);
1052 	return 0;
1053 }
1054 
1055 static int enable_metric_only(const struct option *opt __maybe_unused,
1056 			      const char *s __maybe_unused, int unset)
1057 {
1058 	force_metric_only = true;
1059 	stat_config.metric_only = !unset;
1060 	return 0;
1061 }
1062 
1063 static int append_metric_groups(const struct option *opt __maybe_unused,
1064 			       const char *str,
1065 			       int unset __maybe_unused)
1066 {
1067 	if (metrics) {
1068 		char *tmp;
1069 
1070 		if (asprintf(&tmp, "%s,%s", metrics, str) < 0)
1071 			return -ENOMEM;
1072 		free(metrics);
1073 		metrics = tmp;
1074 	} else {
1075 		metrics = strdup(str);
1076 		if (!metrics)
1077 			return -ENOMEM;
1078 	}
1079 	return 0;
1080 }
1081 
1082 static int parse_control_option(const struct option *opt,
1083 				const char *str,
1084 				int unset __maybe_unused)
1085 {
1086 	struct perf_stat_config *config = opt->value;
1087 
1088 	return evlist__parse_control(str, &config->ctl_fd, &config->ctl_fd_ack, &config->ctl_fd_close);
1089 }
1090 
1091 static int parse_stat_cgroups(const struct option *opt,
1092 			      const char *str, int unset)
1093 {
1094 	if (stat_config.cgroup_list) {
1095 		pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
1096 		return -1;
1097 	}
1098 
1099 	return parse_cgroups(opt, str, unset);
1100 }
1101 
1102 static int parse_cputype(const struct option *opt,
1103 			     const char *str,
1104 			     int unset __maybe_unused)
1105 {
1106 	const struct perf_pmu *pmu;
1107 	struct evlist *evlist = *(struct evlist **)opt->value;
1108 
1109 	if (!list_empty(&evlist->core.entries)) {
1110 		fprintf(stderr, "Must define cputype before events/metrics\n");
1111 		return -1;
1112 	}
1113 
1114 	pmu = perf_pmus__pmu_for_pmu_filter(str);
1115 	if (!pmu) {
1116 		fprintf(stderr, "--cputype %s is not supported!\n", str);
1117 		return -1;
1118 	}
1119 	parse_events_option_args.pmu_filter = pmu->name;
1120 
1121 	return 0;
1122 }
1123 
1124 static int parse_cache_level(const struct option *opt,
1125 			     const char *str,
1126 			     int unset __maybe_unused)
1127 {
1128 	int level;
1129 	struct opt_aggr_mode *opt_aggr_mode = (struct opt_aggr_mode *)opt->value;
1130 	u32 *aggr_level = (u32 *)opt->data;
1131 
1132 	/*
1133 	 * If no string is specified, aggregate based on the topology of
1134 	 * Last Level Cache (LLC). Since the LLC level can change from
1135 	 * architecture to architecture, set level greater than
1136 	 * MAX_CACHE_LVL which will be interpreted as LLC.
1137 	 */
1138 	if (str == NULL) {
1139 		level = MAX_CACHE_LVL + 1;
1140 		goto out;
1141 	}
1142 
1143 	/*
1144 	 * The format to specify cache level is LX or lX where X is the
1145 	 * cache level.
1146 	 */
1147 	if (strlen(str) != 2 || (str[0] != 'l' && str[0] != 'L')) {
1148 		pr_err("Cache level must be of form L[1-%d], or l[1-%d]\n",
1149 		       MAX_CACHE_LVL,
1150 		       MAX_CACHE_LVL);
1151 		return -EINVAL;
1152 	}
1153 
1154 	level = atoi(&str[1]);
1155 	if (level < 1) {
1156 		pr_err("Cache level must be of form L[1-%d], or l[1-%d]\n",
1157 		       MAX_CACHE_LVL,
1158 		       MAX_CACHE_LVL);
1159 		return -EINVAL;
1160 	}
1161 
1162 	if (level > MAX_CACHE_LVL) {
1163 		pr_err("perf only supports max cache level of %d.\n"
1164 		       "Consider increasing MAX_CACHE_LVL\n", MAX_CACHE_LVL);
1165 		return -EINVAL;
1166 	}
1167 out:
1168 	opt_aggr_mode->cache = true;
1169 	*aggr_level = level;
1170 	return 0;
1171 }
1172 
1173 /**
1174  * Calculate the cache instance ID from the map in
1175  * /sys/devices/system/cpu/cpuX/cache/indexY/shared_cpu_list
1176  * Cache instance ID is the first CPU reported in the shared_cpu_list file.
1177  */
1178 static int cpu__get_cache_id_from_map(struct perf_cpu cpu, char *map)
1179 {
1180 	int id;
1181 	struct perf_cpu_map *cpu_map = perf_cpu_map__new(map);
1182 
1183 	/*
1184 	 * If the map contains no CPU, consider the current CPU to
1185 	 * be the first online CPU in the cache domain else use the
1186 	 * first online CPU of the cache domain as the ID.
1187 	 */
1188 	id = perf_cpu_map__min(cpu_map).cpu;
1189 	if (id == -1)
1190 		id = cpu.cpu;
1191 
1192 	/* Free the perf_cpu_map used to find the cache ID */
1193 	perf_cpu_map__put(cpu_map);
1194 
1195 	return id;
1196 }
1197 
1198 /**
1199  * cpu__get_cache_id - Returns 0 if successful in populating the
1200  * cache level and cache id. Cache level is read from
1201  * /sys/devices/system/cpu/cpuX/cache/indexY/level where as cache instance ID
1202  * is the first CPU reported by
1203  * /sys/devices/system/cpu/cpuX/cache/indexY/shared_cpu_list
1204  */
1205 static int cpu__get_cache_details(struct perf_cpu cpu, struct perf_cache *cache)
1206 {
1207 	int ret = 0;
1208 	u32 cache_level = stat_config.aggr_level;
1209 	struct cpu_cache_level caches[MAX_CACHE_LVL];
1210 	u32 i = 0, caches_cnt = 0;
1211 
1212 	cache->cache_lvl = (cache_level > MAX_CACHE_LVL) ? 0 : cache_level;
1213 	cache->cache = -1;
1214 
1215 	ret = build_caches_for_cpu(cpu.cpu, caches, &caches_cnt);
1216 	if (ret) {
1217 		/*
1218 		 * If caches_cnt is not 0, cpu_cache_level data
1219 		 * was allocated when building the topology.
1220 		 * Free the allocated data before returning.
1221 		 */
1222 		if (caches_cnt)
1223 			goto free_caches;
1224 
1225 		return ret;
1226 	}
1227 
1228 	if (!caches_cnt)
1229 		return -1;
1230 
1231 	/*
1232 	 * Save the data for the highest level if no
1233 	 * level was specified by the user.
1234 	 */
1235 	if (cache_level > MAX_CACHE_LVL) {
1236 		int max_level_index = 0;
1237 
1238 		for (i = 1; i < caches_cnt; ++i) {
1239 			if (caches[i].level > caches[max_level_index].level)
1240 				max_level_index = i;
1241 		}
1242 
1243 		cache->cache_lvl = caches[max_level_index].level;
1244 		cache->cache = cpu__get_cache_id_from_map(cpu, caches[max_level_index].map);
1245 
1246 		/* Reset i to 0 to free entire caches[] */
1247 		i = 0;
1248 		goto free_caches;
1249 	}
1250 
1251 	for (i = 0; i < caches_cnt; ++i) {
1252 		if (caches[i].level == cache_level) {
1253 			cache->cache_lvl = cache_level;
1254 			cache->cache = cpu__get_cache_id_from_map(cpu, caches[i].map);
1255 		}
1256 
1257 		cpu_cache_level__free(&caches[i]);
1258 	}
1259 
1260 free_caches:
1261 	/*
1262 	 * Free all the allocated cpu_cache_level data.
1263 	 */
1264 	while (i < caches_cnt)
1265 		cpu_cache_level__free(&caches[i++]);
1266 
1267 	return ret;
1268 }
1269 
1270 /**
1271  * aggr_cpu_id__cache - Create an aggr_cpu_id with cache instache ID, cache
1272  * level, die and socket populated with the cache instache ID, cache level,
1273  * die and socket for cpu. The function signature is compatible with
1274  * aggr_cpu_id_get_t.
1275  */
1276 static struct aggr_cpu_id aggr_cpu_id__cache(struct perf_cpu cpu, void *data)
1277 {
1278 	int ret;
1279 	struct aggr_cpu_id id;
1280 	struct perf_cache cache;
1281 
1282 	id = aggr_cpu_id__die(cpu, data);
1283 	if (aggr_cpu_id__is_empty(&id))
1284 		return id;
1285 
1286 	ret = cpu__get_cache_details(cpu, &cache);
1287 	if (ret)
1288 		return id;
1289 
1290 	id.cache_lvl = cache.cache_lvl;
1291 	id.cache = cache.cache;
1292 	return id;
1293 }
1294 
1295 static const char *const aggr_mode__string[] = {
1296 	[AGGR_CORE] = "core",
1297 	[AGGR_CACHE] = "cache",
1298 	[AGGR_CLUSTER] = "cluster",
1299 	[AGGR_DIE] = "die",
1300 	[AGGR_GLOBAL] = "global",
1301 	[AGGR_NODE] = "node",
1302 	[AGGR_NONE] = "none",
1303 	[AGGR_SOCKET] = "socket",
1304 	[AGGR_THREAD] = "thread",
1305 	[AGGR_UNSET] = "unset",
1306 };
1307 
1308 static struct aggr_cpu_id perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
1309 						struct perf_cpu cpu)
1310 {
1311 	return aggr_cpu_id__socket(cpu, /*data=*/NULL);
1312 }
1313 
1314 static struct aggr_cpu_id perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
1315 					     struct perf_cpu cpu)
1316 {
1317 	return aggr_cpu_id__die(cpu, /*data=*/NULL);
1318 }
1319 
1320 static struct aggr_cpu_id perf_stat__get_cache_id(struct perf_stat_config *config __maybe_unused,
1321 						  struct perf_cpu cpu)
1322 {
1323 	return aggr_cpu_id__cache(cpu, /*data=*/NULL);
1324 }
1325 
1326 static struct aggr_cpu_id perf_stat__get_cluster(struct perf_stat_config *config __maybe_unused,
1327 						 struct perf_cpu cpu)
1328 {
1329 	return aggr_cpu_id__cluster(cpu, /*data=*/NULL);
1330 }
1331 
1332 static struct aggr_cpu_id perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
1333 					      struct perf_cpu cpu)
1334 {
1335 	return aggr_cpu_id__core(cpu, /*data=*/NULL);
1336 }
1337 
1338 static struct aggr_cpu_id perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
1339 					      struct perf_cpu cpu)
1340 {
1341 	return aggr_cpu_id__node(cpu, /*data=*/NULL);
1342 }
1343 
1344 static struct aggr_cpu_id perf_stat__get_global(struct perf_stat_config *config __maybe_unused,
1345 						struct perf_cpu cpu)
1346 {
1347 	return aggr_cpu_id__global(cpu, /*data=*/NULL);
1348 }
1349 
1350 static struct aggr_cpu_id perf_stat__get_cpu(struct perf_stat_config *config __maybe_unused,
1351 					     struct perf_cpu cpu)
1352 {
1353 	return aggr_cpu_id__cpu(cpu, /*data=*/NULL);
1354 }
1355 
1356 static struct aggr_cpu_id perf_stat__get_aggr(struct perf_stat_config *config,
1357 					      aggr_get_id_t get_id, struct perf_cpu cpu)
1358 {
1359 	struct aggr_cpu_id id;
1360 
1361 	/* per-process mode - should use global aggr mode */
1362 	if (cpu.cpu == -1 || cpu.cpu >= config->cpus_aggr_map->nr)
1363 		return get_id(config, cpu);
1364 
1365 	if (aggr_cpu_id__is_empty(&config->cpus_aggr_map->map[cpu.cpu]))
1366 		config->cpus_aggr_map->map[cpu.cpu] = get_id(config, cpu);
1367 
1368 	id = config->cpus_aggr_map->map[cpu.cpu];
1369 	return id;
1370 }
1371 
1372 static struct aggr_cpu_id perf_stat__get_socket_cached(struct perf_stat_config *config,
1373 						       struct perf_cpu cpu)
1374 {
1375 	return perf_stat__get_aggr(config, perf_stat__get_socket, cpu);
1376 }
1377 
1378 static struct aggr_cpu_id perf_stat__get_die_cached(struct perf_stat_config *config,
1379 						    struct perf_cpu cpu)
1380 {
1381 	return perf_stat__get_aggr(config, perf_stat__get_die, cpu);
1382 }
1383 
1384 static struct aggr_cpu_id perf_stat__get_cluster_cached(struct perf_stat_config *config,
1385 							struct perf_cpu cpu)
1386 {
1387 	return perf_stat__get_aggr(config, perf_stat__get_cluster, cpu);
1388 }
1389 
1390 static struct aggr_cpu_id perf_stat__get_cache_id_cached(struct perf_stat_config *config,
1391 							 struct perf_cpu cpu)
1392 {
1393 	return perf_stat__get_aggr(config, perf_stat__get_cache_id, cpu);
1394 }
1395 
1396 static struct aggr_cpu_id perf_stat__get_core_cached(struct perf_stat_config *config,
1397 						     struct perf_cpu cpu)
1398 {
1399 	return perf_stat__get_aggr(config, perf_stat__get_core, cpu);
1400 }
1401 
1402 static struct aggr_cpu_id perf_stat__get_node_cached(struct perf_stat_config *config,
1403 						     struct perf_cpu cpu)
1404 {
1405 	return perf_stat__get_aggr(config, perf_stat__get_node, cpu);
1406 }
1407 
1408 static struct aggr_cpu_id perf_stat__get_global_cached(struct perf_stat_config *config,
1409 						       struct perf_cpu cpu)
1410 {
1411 	return perf_stat__get_aggr(config, perf_stat__get_global, cpu);
1412 }
1413 
1414 static struct aggr_cpu_id perf_stat__get_cpu_cached(struct perf_stat_config *config,
1415 						    struct perf_cpu cpu)
1416 {
1417 	return perf_stat__get_aggr(config, perf_stat__get_cpu, cpu);
1418 }
1419 
1420 static aggr_cpu_id_get_t aggr_mode__get_aggr(enum aggr_mode aggr_mode)
1421 {
1422 	switch (aggr_mode) {
1423 	case AGGR_SOCKET:
1424 		return aggr_cpu_id__socket;
1425 	case AGGR_DIE:
1426 		return aggr_cpu_id__die;
1427 	case AGGR_CLUSTER:
1428 		return aggr_cpu_id__cluster;
1429 	case AGGR_CACHE:
1430 		return aggr_cpu_id__cache;
1431 	case AGGR_CORE:
1432 		return aggr_cpu_id__core;
1433 	case AGGR_NODE:
1434 		return aggr_cpu_id__node;
1435 	case AGGR_NONE:
1436 		return aggr_cpu_id__cpu;
1437 	case AGGR_GLOBAL:
1438 		return aggr_cpu_id__global;
1439 	case AGGR_THREAD:
1440 	case AGGR_UNSET:
1441 	case AGGR_MAX:
1442 	default:
1443 		return NULL;
1444 	}
1445 }
1446 
1447 static aggr_get_id_t aggr_mode__get_id(enum aggr_mode aggr_mode)
1448 {
1449 	switch (aggr_mode) {
1450 	case AGGR_SOCKET:
1451 		return perf_stat__get_socket_cached;
1452 	case AGGR_DIE:
1453 		return perf_stat__get_die_cached;
1454 	case AGGR_CLUSTER:
1455 		return perf_stat__get_cluster_cached;
1456 	case AGGR_CACHE:
1457 		return perf_stat__get_cache_id_cached;
1458 	case AGGR_CORE:
1459 		return perf_stat__get_core_cached;
1460 	case AGGR_NODE:
1461 		return perf_stat__get_node_cached;
1462 	case AGGR_NONE:
1463 		return perf_stat__get_cpu_cached;
1464 	case AGGR_GLOBAL:
1465 		return perf_stat__get_global_cached;
1466 	case AGGR_THREAD:
1467 	case AGGR_UNSET:
1468 	case AGGR_MAX:
1469 	default:
1470 		return NULL;
1471 	}
1472 }
1473 
1474 static int perf_stat_init_aggr_mode(void)
1475 {
1476 	int nr;
1477 	aggr_cpu_id_get_t get_id = aggr_mode__get_aggr(stat_config.aggr_mode);
1478 
1479 	if (get_id) {
1480 		bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1481 		stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1482 							 get_id, /*data=*/NULL, needs_sort);
1483 		if (!stat_config.aggr_map) {
1484 			pr_err("cannot build %s map\n", aggr_mode__string[stat_config.aggr_mode]);
1485 			return -1;
1486 		}
1487 		stat_config.aggr_get_id = aggr_mode__get_id(stat_config.aggr_mode);
1488 	}
1489 
1490 	if (stat_config.aggr_mode == AGGR_THREAD) {
1491 		nr = perf_thread_map__nr(evsel_list->core.threads);
1492 		stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1493 		if (stat_config.aggr_map == NULL)
1494 			return -ENOMEM;
1495 
1496 		for (int s = 0; s < nr; s++) {
1497 			struct aggr_cpu_id id = aggr_cpu_id__empty();
1498 
1499 			id.thread_idx = s;
1500 			stat_config.aggr_map->map[s] = id;
1501 		}
1502 		return 0;
1503 	}
1504 
1505 	/*
1506 	 * The evsel_list->cpus is the base we operate on,
1507 	 * taking the highest cpu number to be the size of
1508 	 * the aggregation translate cpumap.
1509 	 */
1510 	nr = perf_cpu_map__max(evsel_list->core.all_cpus).cpu + 1;
1511 	stat_config.cpus_aggr_map = cpu_aggr_map__empty_new(nr);
1512 	return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
1513 }
1514 
1515 static void cpu_aggr_map__delete(struct cpu_aggr_map *map)
1516 {
1517 	free(map);
1518 }
1519 
1520 static void perf_stat__exit_aggr_mode(void)
1521 {
1522 	cpu_aggr_map__delete(stat_config.aggr_map);
1523 	cpu_aggr_map__delete(stat_config.cpus_aggr_map);
1524 	stat_config.aggr_map = NULL;
1525 	stat_config.cpus_aggr_map = NULL;
1526 }
1527 
1528 static struct aggr_cpu_id perf_env__get_socket_aggr_by_cpu(struct perf_cpu cpu, void *data)
1529 {
1530 	struct perf_env *env = data;
1531 	struct aggr_cpu_id id = aggr_cpu_id__empty();
1532 
1533 	if (cpu.cpu != -1)
1534 		id.socket = env->cpu[cpu.cpu].socket_id;
1535 
1536 	return id;
1537 }
1538 
1539 static struct aggr_cpu_id perf_env__get_die_aggr_by_cpu(struct perf_cpu cpu, void *data)
1540 {
1541 	struct perf_env *env = data;
1542 	struct aggr_cpu_id id = aggr_cpu_id__empty();
1543 
1544 	if (cpu.cpu != -1) {
1545 		/*
1546 		 * die_id is relative to socket, so start
1547 		 * with the socket ID and then add die to
1548 		 * make a unique ID.
1549 		 */
1550 		id.socket = env->cpu[cpu.cpu].socket_id;
1551 		id.die = env->cpu[cpu.cpu].die_id;
1552 	}
1553 
1554 	return id;
1555 }
1556 
1557 static void perf_env__get_cache_id_for_cpu(struct perf_cpu cpu, struct perf_env *env,
1558 					   u32 cache_level, struct aggr_cpu_id *id)
1559 {
1560 	int i;
1561 	int caches_cnt = env->caches_cnt;
1562 	struct cpu_cache_level *caches = env->caches;
1563 
1564 	id->cache_lvl = (cache_level > MAX_CACHE_LVL) ? 0 : cache_level;
1565 	id->cache = -1;
1566 
1567 	if (!caches_cnt)
1568 		return;
1569 
1570 	for (i = caches_cnt - 1; i > -1; --i) {
1571 		struct perf_cpu_map *cpu_map;
1572 		int map_contains_cpu;
1573 
1574 		/*
1575 		 * If user has not specified a level, find the fist level with
1576 		 * the cpu in the map. Since building the map is expensive, do
1577 		 * this only if levels match.
1578 		 */
1579 		if (cache_level <= MAX_CACHE_LVL && caches[i].level != cache_level)
1580 			continue;
1581 
1582 		cpu_map = perf_cpu_map__new(caches[i].map);
1583 		map_contains_cpu = perf_cpu_map__idx(cpu_map, cpu);
1584 		perf_cpu_map__put(cpu_map);
1585 
1586 		if (map_contains_cpu != -1) {
1587 			id->cache_lvl = caches[i].level;
1588 			id->cache = cpu__get_cache_id_from_map(cpu, caches[i].map);
1589 			return;
1590 		}
1591 	}
1592 }
1593 
1594 static struct aggr_cpu_id perf_env__get_cache_aggr_by_cpu(struct perf_cpu cpu,
1595 							  void *data)
1596 {
1597 	struct perf_env *env = data;
1598 	struct aggr_cpu_id id = aggr_cpu_id__empty();
1599 
1600 	if (cpu.cpu != -1) {
1601 		u32 cache_level = (perf_stat.aggr_level) ?: stat_config.aggr_level;
1602 
1603 		id.socket = env->cpu[cpu.cpu].socket_id;
1604 		id.die = env->cpu[cpu.cpu].die_id;
1605 		perf_env__get_cache_id_for_cpu(cpu, env, cache_level, &id);
1606 	}
1607 
1608 	return id;
1609 }
1610 
1611 static struct aggr_cpu_id perf_env__get_cluster_aggr_by_cpu(struct perf_cpu cpu,
1612 							    void *data)
1613 {
1614 	struct perf_env *env = data;
1615 	struct aggr_cpu_id id = aggr_cpu_id__empty();
1616 
1617 	if (cpu.cpu != -1) {
1618 		id.socket = env->cpu[cpu.cpu].socket_id;
1619 		id.die = env->cpu[cpu.cpu].die_id;
1620 		id.cluster = env->cpu[cpu.cpu].cluster_id;
1621 	}
1622 
1623 	return id;
1624 }
1625 
1626 static struct aggr_cpu_id perf_env__get_core_aggr_by_cpu(struct perf_cpu cpu, void *data)
1627 {
1628 	struct perf_env *env = data;
1629 	struct aggr_cpu_id id = aggr_cpu_id__empty();
1630 
1631 	if (cpu.cpu != -1) {
1632 		/*
1633 		 * core_id is relative to socket, die and cluster, we need a
1634 		 * global id. So we set socket, die id, cluster id and core id.
1635 		 */
1636 		id.socket = env->cpu[cpu.cpu].socket_id;
1637 		id.die = env->cpu[cpu.cpu].die_id;
1638 		id.cluster = env->cpu[cpu.cpu].cluster_id;
1639 		id.core = env->cpu[cpu.cpu].core_id;
1640 	}
1641 
1642 	return id;
1643 }
1644 
1645 static struct aggr_cpu_id perf_env__get_cpu_aggr_by_cpu(struct perf_cpu cpu, void *data)
1646 {
1647 	struct perf_env *env = data;
1648 	struct aggr_cpu_id id = aggr_cpu_id__empty();
1649 
1650 	if (cpu.cpu != -1) {
1651 		/*
1652 		 * core_id is relative to socket and die,
1653 		 * we need a global id. So we set
1654 		 * socket, die id and core id
1655 		 */
1656 		id.socket = env->cpu[cpu.cpu].socket_id;
1657 		id.die = env->cpu[cpu.cpu].die_id;
1658 		id.core = env->cpu[cpu.cpu].core_id;
1659 		id.cpu = cpu;
1660 	}
1661 
1662 	return id;
1663 }
1664 
1665 static struct aggr_cpu_id perf_env__get_node_aggr_by_cpu(struct perf_cpu cpu, void *data)
1666 {
1667 	struct aggr_cpu_id id = aggr_cpu_id__empty();
1668 
1669 	id.node = perf_env__numa_node(data, cpu);
1670 	return id;
1671 }
1672 
1673 static struct aggr_cpu_id perf_env__get_global_aggr_by_cpu(struct perf_cpu cpu __maybe_unused,
1674 							   void *data __maybe_unused)
1675 {
1676 	struct aggr_cpu_id id = aggr_cpu_id__empty();
1677 
1678 	/* it always aggregates to the cpu 0 */
1679 	id.cpu = (struct perf_cpu){ .cpu = 0 };
1680 	return id;
1681 }
1682 
1683 static struct aggr_cpu_id perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
1684 						     struct perf_cpu cpu)
1685 {
1686 	return perf_env__get_socket_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1687 }
1688 static struct aggr_cpu_id perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
1689 						  struct perf_cpu cpu)
1690 {
1691 	return perf_env__get_die_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1692 }
1693 
1694 static struct aggr_cpu_id perf_stat__get_cluster_file(struct perf_stat_config *config __maybe_unused,
1695 						      struct perf_cpu cpu)
1696 {
1697 	return perf_env__get_cluster_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1698 }
1699 
1700 static struct aggr_cpu_id perf_stat__get_cache_file(struct perf_stat_config *config __maybe_unused,
1701 						    struct perf_cpu cpu)
1702 {
1703 	return perf_env__get_cache_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1704 }
1705 
1706 static struct aggr_cpu_id perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
1707 						   struct perf_cpu cpu)
1708 {
1709 	return perf_env__get_core_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1710 }
1711 
1712 static struct aggr_cpu_id perf_stat__get_cpu_file(struct perf_stat_config *config __maybe_unused,
1713 						  struct perf_cpu cpu)
1714 {
1715 	return perf_env__get_cpu_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1716 }
1717 
1718 static struct aggr_cpu_id perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
1719 						   struct perf_cpu cpu)
1720 {
1721 	return perf_env__get_node_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1722 }
1723 
1724 static struct aggr_cpu_id perf_stat__get_global_file(struct perf_stat_config *config __maybe_unused,
1725 						     struct perf_cpu cpu)
1726 {
1727 	return perf_env__get_global_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1728 }
1729 
1730 static aggr_cpu_id_get_t aggr_mode__get_aggr_file(enum aggr_mode aggr_mode)
1731 {
1732 	switch (aggr_mode) {
1733 	case AGGR_SOCKET:
1734 		return perf_env__get_socket_aggr_by_cpu;
1735 	case AGGR_DIE:
1736 		return perf_env__get_die_aggr_by_cpu;
1737 	case AGGR_CLUSTER:
1738 		return perf_env__get_cluster_aggr_by_cpu;
1739 	case AGGR_CACHE:
1740 		return perf_env__get_cache_aggr_by_cpu;
1741 	case AGGR_CORE:
1742 		return perf_env__get_core_aggr_by_cpu;
1743 	case AGGR_NODE:
1744 		return perf_env__get_node_aggr_by_cpu;
1745 	case AGGR_GLOBAL:
1746 		return perf_env__get_global_aggr_by_cpu;
1747 	case AGGR_NONE:
1748 		return perf_env__get_cpu_aggr_by_cpu;
1749 	case AGGR_THREAD:
1750 	case AGGR_UNSET:
1751 	case AGGR_MAX:
1752 	default:
1753 		return NULL;
1754 	}
1755 }
1756 
1757 static aggr_get_id_t aggr_mode__get_id_file(enum aggr_mode aggr_mode)
1758 {
1759 	switch (aggr_mode) {
1760 	case AGGR_SOCKET:
1761 		return perf_stat__get_socket_file;
1762 	case AGGR_DIE:
1763 		return perf_stat__get_die_file;
1764 	case AGGR_CLUSTER:
1765 		return perf_stat__get_cluster_file;
1766 	case AGGR_CACHE:
1767 		return perf_stat__get_cache_file;
1768 	case AGGR_CORE:
1769 		return perf_stat__get_core_file;
1770 	case AGGR_NODE:
1771 		return perf_stat__get_node_file;
1772 	case AGGR_GLOBAL:
1773 		return perf_stat__get_global_file;
1774 	case AGGR_NONE:
1775 		return perf_stat__get_cpu_file;
1776 	case AGGR_THREAD:
1777 	case AGGR_UNSET:
1778 	case AGGR_MAX:
1779 	default:
1780 		return NULL;
1781 	}
1782 }
1783 
1784 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1785 {
1786 	struct perf_env *env = perf_session__env(st->session);
1787 	aggr_cpu_id_get_t get_id = aggr_mode__get_aggr_file(stat_config.aggr_mode);
1788 	bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1789 
1790 	if (stat_config.aggr_mode == AGGR_THREAD) {
1791 		int nr = perf_thread_map__nr(evsel_list->core.threads);
1792 
1793 		stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1794 		if (stat_config.aggr_map == NULL)
1795 			return -ENOMEM;
1796 
1797 		for (int s = 0; s < nr; s++) {
1798 			struct aggr_cpu_id id = aggr_cpu_id__empty();
1799 
1800 			id.thread_idx = s;
1801 			stat_config.aggr_map->map[s] = id;
1802 		}
1803 		return 0;
1804 	}
1805 
1806 	if (!get_id)
1807 		return 0;
1808 
1809 	stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1810 						 get_id, env, needs_sort);
1811 	if (!stat_config.aggr_map) {
1812 		pr_err("cannot build %s map\n", aggr_mode__string[stat_config.aggr_mode]);
1813 		return -1;
1814 	}
1815 	stat_config.aggr_get_id = aggr_mode__get_id_file(stat_config.aggr_mode);
1816 	return 0;
1817 }
1818 
1819 /*
1820  * Add default events, if there were no attributes specified or
1821  * if -d/--detailed, -d -d or -d -d -d is used:
1822  */
1823 static int add_default_events(void)
1824 {
1825 	const char *pmu = parse_events_option_args.pmu_filter ?: "all";
1826 	struct parse_events_error err;
1827 	struct evlist *evlist = evlist__new();
1828 	struct evsel *evsel;
1829 	int ret = 0;
1830 
1831 	if (!evlist)
1832 		return -ENOMEM;
1833 
1834 	parse_events_error__init(&err);
1835 
1836 	/* Set attrs if no event is selected and !null_run: */
1837 	if (stat_config.null_run)
1838 		goto out;
1839 
1840 	if (transaction_run) {
1841 		/* Handle -T as -M transaction. Once platform specific metrics
1842 		 * support has been added to the json files, all architectures
1843 		 * will use this approach. To determine transaction support
1844 		 * on an architecture test for such a metric name.
1845 		 */
1846 		if (!metricgroup__has_metric_or_groups(pmu, "transaction")) {
1847 			pr_err("Missing transaction metrics\n");
1848 			ret = -1;
1849 			goto out;
1850 		}
1851 		ret = metricgroup__parse_groups(evlist, pmu, "transaction",
1852 						stat_config.metric_no_group,
1853 						stat_config.metric_no_merge,
1854 						stat_config.metric_no_threshold,
1855 						stat_config.user_requested_cpu_list,
1856 						stat_config.system_wide,
1857 						stat_config.hardware_aware_grouping);
1858 		goto out;
1859 	}
1860 
1861 	if (smi_cost) {
1862 		int smi;
1863 
1864 		if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
1865 			pr_err("freeze_on_smi is not supported.\n");
1866 			ret = -1;
1867 			goto out;
1868 		}
1869 
1870 		if (!smi) {
1871 			if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
1872 				pr_err("Failed to set freeze_on_smi.\n");
1873 				ret = -1;
1874 				goto out;
1875 			}
1876 			smi_reset = true;
1877 		}
1878 
1879 		if (!metricgroup__has_metric_or_groups(pmu, "smi")) {
1880 			pr_err("Missing smi metrics\n");
1881 			ret = -1;
1882 			goto out;
1883 		}
1884 
1885 		if (!force_metric_only)
1886 			stat_config.metric_only = true;
1887 
1888 		ret = metricgroup__parse_groups(evlist, pmu, "smi",
1889 						stat_config.metric_no_group,
1890 						stat_config.metric_no_merge,
1891 						stat_config.metric_no_threshold,
1892 						stat_config.user_requested_cpu_list,
1893 						stat_config.system_wide,
1894 						stat_config.hardware_aware_grouping);
1895 		goto out;
1896 	}
1897 
1898 	if (topdown_run) {
1899 		unsigned int max_level = metricgroups__topdown_max_level();
1900 		char str[] = "TopdownL1";
1901 
1902 		if (!force_metric_only)
1903 			stat_config.metric_only = true;
1904 
1905 		if (!max_level) {
1906 			pr_err("Topdown requested but the topdown metric groups aren't present.\n"
1907 				"(See perf list the metric groups have names like TopdownL1)\n");
1908 			ret = -1;
1909 			goto out;
1910 		}
1911 		if (stat_config.topdown_level > max_level) {
1912 			pr_err("Invalid top-down metrics level. The max level is %u.\n", max_level);
1913 			ret = -1;
1914 			goto out;
1915 		} else if (!stat_config.topdown_level) {
1916 			stat_config.topdown_level = 1;
1917 		}
1918 		if (!stat_config.interval && !stat_config.metric_only) {
1919 			fprintf(stat_config.output,
1920 				"Topdown accuracy may decrease when measuring long periods.\n"
1921 				"Please print the result regularly, e.g. -I1000\n");
1922 		}
1923 		str[8] = stat_config.topdown_level + '0';
1924 		if (metricgroup__parse_groups(evlist,
1925 						pmu, str,
1926 						/*metric_no_group=*/false,
1927 						/*metric_no_merge=*/false,
1928 						/*metric_no_threshold=*/true,
1929 						stat_config.user_requested_cpu_list,
1930 						stat_config.system_wide,
1931 						stat_config.hardware_aware_grouping) < 0) {
1932 			ret = -1;
1933 			goto out;
1934 		}
1935 	}
1936 
1937 	if (!stat_config.topdown_level)
1938 		stat_config.topdown_level = 1;
1939 
1940 	if (!evlist->core.nr_entries && !evsel_list->core.nr_entries) {
1941 		/* No events so add defaults. */
1942 		if (target__has_cpu(&target))
1943 			ret = parse_events(evlist, "cpu-clock", &err);
1944 		else
1945 			ret = parse_events(evlist, "task-clock", &err);
1946 		if (ret)
1947 			goto out;
1948 
1949 		ret = parse_events(evlist,
1950 				"context-switches,"
1951 				"cpu-migrations,"
1952 				"page-faults,"
1953 				"instructions,"
1954 				"cycles,"
1955 				"stalled-cycles-frontend,"
1956 				"stalled-cycles-backend,"
1957 				"branches,"
1958 				"branch-misses",
1959 				&err);
1960 		if (ret)
1961 			goto out;
1962 
1963 		/*
1964 		 * Add TopdownL1 metrics if they exist. To minimize
1965 		 * multiplexing, don't request threshold computation.
1966 		 */
1967 		if (metricgroup__has_metric_or_groups(pmu, "Default")) {
1968 			struct evlist *metric_evlist = evlist__new();
1969 
1970 			if (!metric_evlist) {
1971 				ret = -ENOMEM;
1972 				goto out;
1973 			}
1974 			if (metricgroup__parse_groups(metric_evlist, pmu, "Default",
1975 							/*metric_no_group=*/false,
1976 							/*metric_no_merge=*/false,
1977 							/*metric_no_threshold=*/true,
1978 							stat_config.user_requested_cpu_list,
1979 							stat_config.system_wide,
1980 							stat_config.hardware_aware_grouping) < 0) {
1981 				ret = -1;
1982 				goto out;
1983 			}
1984 
1985 			evlist__for_each_entry(metric_evlist, evsel)
1986 				evsel->default_metricgroup = true;
1987 
1988 			evlist__splice_list_tail(evlist, &metric_evlist->core.entries);
1989 			metricgroup__copy_metric_events(evlist, /*cgrp=*/NULL,
1990 							&evlist->metric_events,
1991 							&metric_evlist->metric_events);
1992 			evlist__delete(metric_evlist);
1993 		}
1994 	}
1995 
1996 	/* Detailed events get appended to the event list: */
1997 
1998 	if (!ret && detailed_run >=  1) {
1999 		/*
2000 		 * Detailed stats (-d), covering the L1 and last level data
2001 		 * caches:
2002 		 */
2003 		ret = parse_events(evlist,
2004 				"L1-dcache-loads,"
2005 				"L1-dcache-load-misses,"
2006 				"LLC-loads,"
2007 				"LLC-load-misses",
2008 				&err);
2009 	}
2010 	if (!ret && detailed_run >=  2) {
2011 		/*
2012 		 * Very detailed stats (-d -d), covering the instruction cache
2013 		 * and the TLB caches:
2014 		 */
2015 		ret = parse_events(evlist,
2016 				"L1-icache-loads,"
2017 				"L1-icache-load-misses,"
2018 				"dTLB-loads,"
2019 				"dTLB-load-misses,"
2020 				"iTLB-loads,"
2021 				"iTLB-load-misses",
2022 				&err);
2023 	}
2024 	if (!ret && detailed_run >=  3) {
2025 		/*
2026 		 * Very, very detailed stats (-d -d -d), adding prefetch events:
2027 		 */
2028 		ret = parse_events(evlist,
2029 				"L1-dcache-prefetches,"
2030 				"L1-dcache-prefetch-misses",
2031 				&err);
2032 	}
2033 out:
2034 	if (!ret) {
2035 		evlist__for_each_entry(evlist, evsel) {
2036 			/*
2037 			 * Make at least one event non-skippable so fatal errors are visible.
2038 			 * 'cycles' always used to be default and non-skippable, so use that.
2039 			 */
2040 			if (strcmp("cycles", evsel__name(evsel)))
2041 				evsel->skippable = true;
2042 		}
2043 	}
2044 	parse_events_error__exit(&err);
2045 	evlist__splice_list_tail(evsel_list, &evlist->core.entries);
2046 	metricgroup__copy_metric_events(evsel_list, /*cgrp=*/NULL,
2047 					&evsel_list->metric_events,
2048 					&evlist->metric_events);
2049 	evlist__delete(evlist);
2050 	return ret;
2051 }
2052 
2053 static const char * const stat_record_usage[] = {
2054 	"perf stat record [<options>]",
2055 	NULL,
2056 };
2057 
2058 static void init_features(struct perf_session *session)
2059 {
2060 	int feat;
2061 
2062 	for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2063 		perf_header__set_feat(&session->header, feat);
2064 
2065 	perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
2066 	perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2067 	perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2068 	perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2069 	perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2070 }
2071 
2072 static int __cmd_record(const struct option stat_options[], struct opt_aggr_mode *opt_mode,
2073 			int argc, const char **argv)
2074 {
2075 	struct perf_session *session;
2076 	struct perf_data *data = &perf_stat.data;
2077 
2078 	argc = parse_options(argc, argv, stat_options, stat_record_usage,
2079 			     PARSE_OPT_STOP_AT_NON_OPTION);
2080 	stat_config.aggr_mode = opt_aggr_mode_to_aggr_mode(opt_mode);
2081 
2082 	if (output_name)
2083 		data->path = output_name;
2084 
2085 	if (stat_config.run_count != 1 || forever) {
2086 		pr_err("Cannot use -r option with perf stat record.\n");
2087 		return -1;
2088 	}
2089 
2090 	session = perf_session__new(data, NULL);
2091 	if (IS_ERR(session)) {
2092 		pr_err("Perf session creation failed\n");
2093 		return PTR_ERR(session);
2094 	}
2095 
2096 	init_features(session);
2097 
2098 	session->evlist   = evsel_list;
2099 	perf_stat.session = session;
2100 	perf_stat.record  = true;
2101 	return argc;
2102 }
2103 
2104 static int process_stat_round_event(struct perf_session *session,
2105 				    union perf_event *event)
2106 {
2107 	struct perf_record_stat_round *stat_round = &event->stat_round;
2108 	struct timespec tsh, *ts = NULL;
2109 	struct perf_env *env = perf_session__env(session);
2110 	const char **argv = env->cmdline_argv;
2111 	int argc = env->nr_cmdline;
2112 
2113 	process_counters();
2114 
2115 	if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2116 		update_stats(&walltime_nsecs_stats, stat_round->time);
2117 
2118 	if (stat_config.interval && stat_round->time) {
2119 		tsh.tv_sec  = stat_round->time / NSEC_PER_SEC;
2120 		tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2121 		ts = &tsh;
2122 	}
2123 
2124 	print_counters(ts, argc, argv);
2125 	return 0;
2126 }
2127 
2128 static
2129 int process_stat_config_event(struct perf_session *session,
2130 			      union perf_event *event)
2131 {
2132 	const struct perf_tool *tool = session->tool;
2133 	struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2134 
2135 	perf_event__read_stat_config(&stat_config, &event->stat_config);
2136 
2137 	if (perf_cpu_map__is_empty(st->cpus)) {
2138 		if (st->aggr_mode != AGGR_UNSET)
2139 			pr_warning("warning: processing task data, aggregation mode not set\n");
2140 	} else if (st->aggr_mode != AGGR_UNSET) {
2141 		stat_config.aggr_mode = st->aggr_mode;
2142 	}
2143 
2144 	if (perf_stat.data.is_pipe)
2145 		perf_stat_init_aggr_mode();
2146 	else
2147 		perf_stat_init_aggr_mode_file(st);
2148 
2149 	if (stat_config.aggr_map) {
2150 		int nr_aggr = stat_config.aggr_map->nr;
2151 
2152 		if (evlist__alloc_aggr_stats(session->evlist, nr_aggr) < 0) {
2153 			pr_err("cannot allocate aggr counts\n");
2154 			return -1;
2155 		}
2156 	}
2157 	return 0;
2158 }
2159 
2160 static int set_maps(struct perf_stat *st)
2161 {
2162 	if (!st->cpus || !st->threads)
2163 		return 0;
2164 
2165 	if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2166 		return -EINVAL;
2167 
2168 	perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
2169 
2170 	if (evlist__alloc_stats(&stat_config, evsel_list, /*alloc_raw=*/true))
2171 		return -ENOMEM;
2172 
2173 	st->maps_allocated = true;
2174 	return 0;
2175 }
2176 
2177 static
2178 int process_thread_map_event(struct perf_session *session,
2179 			     union perf_event *event)
2180 {
2181 	const struct perf_tool *tool = session->tool;
2182 	struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2183 
2184 	if (st->threads) {
2185 		pr_warning("Extra thread map event, ignoring.\n");
2186 		return 0;
2187 	}
2188 
2189 	st->threads = thread_map__new_event(&event->thread_map);
2190 	if (!st->threads)
2191 		return -ENOMEM;
2192 
2193 	return set_maps(st);
2194 }
2195 
2196 static
2197 int process_cpu_map_event(struct perf_session *session,
2198 			  union perf_event *event)
2199 {
2200 	const struct perf_tool *tool = session->tool;
2201 	struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2202 	struct perf_cpu_map *cpus;
2203 
2204 	if (st->cpus) {
2205 		pr_warning("Extra cpu map event, ignoring.\n");
2206 		return 0;
2207 	}
2208 
2209 	cpus = cpu_map__new_data(&event->cpu_map.data);
2210 	if (!cpus)
2211 		return -ENOMEM;
2212 
2213 	st->cpus = cpus;
2214 	return set_maps(st);
2215 }
2216 
2217 static const char * const stat_report_usage[] = {
2218 	"perf stat report [<options>]",
2219 	NULL,
2220 };
2221 
2222 static struct perf_stat perf_stat = {
2223 	.aggr_mode	= AGGR_UNSET,
2224 	.aggr_level	= 0,
2225 };
2226 
2227 static int __cmd_report(int argc, const char **argv)
2228 {
2229 	struct perf_session *session;
2230 	const struct option options[] = {
2231 	OPT_STRING('i', "input", &input_name, "file", "input file name"),
2232 	OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2233 		     "aggregate counts per processor socket", AGGR_SOCKET),
2234 	OPT_SET_UINT(0, "per-die", &perf_stat.aggr_mode,
2235 		     "aggregate counts per processor die", AGGR_DIE),
2236 	OPT_SET_UINT(0, "per-cluster", &perf_stat.aggr_mode,
2237 		     "aggregate counts perf processor cluster", AGGR_CLUSTER),
2238 	OPT_CALLBACK_OPTARG(0, "per-cache", &perf_stat.aggr_mode, &perf_stat.aggr_level,
2239 			    "cache level",
2240 			    "aggregate count at this cache level (Default: LLC)",
2241 			    parse_cache_level),
2242 	OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2243 		     "aggregate counts per physical processor core", AGGR_CORE),
2244 	OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
2245 		     "aggregate counts per numa node", AGGR_NODE),
2246 	OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2247 		     "disable CPU count aggregation", AGGR_NONE),
2248 	OPT_END()
2249 	};
2250 	struct stat st;
2251 	int ret;
2252 
2253 	argc = parse_options(argc, argv, options, stat_report_usage, 0);
2254 
2255 	if (!input_name || !strlen(input_name)) {
2256 		if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2257 			input_name = "-";
2258 		else
2259 			input_name = "perf.data";
2260 	}
2261 
2262 	perf_stat.data.path = input_name;
2263 	perf_stat.data.mode = PERF_DATA_MODE_READ;
2264 
2265 	perf_tool__init(&perf_stat.tool, /*ordered_events=*/false);
2266 	perf_stat.tool.attr		= perf_event__process_attr;
2267 	perf_stat.tool.event_update	= perf_event__process_event_update;
2268 	perf_stat.tool.thread_map	= process_thread_map_event;
2269 	perf_stat.tool.cpu_map		= process_cpu_map_event;
2270 	perf_stat.tool.stat_config	= process_stat_config_event;
2271 	perf_stat.tool.stat		= perf_event__process_stat_event;
2272 	perf_stat.tool.stat_round	= process_stat_round_event;
2273 
2274 	session = perf_session__new(&perf_stat.data, &perf_stat.tool);
2275 	if (IS_ERR(session))
2276 		return PTR_ERR(session);
2277 
2278 	perf_stat.session  = session;
2279 	stat_config.output = stderr;
2280 	evlist__delete(evsel_list);
2281 	evsel_list         = session->evlist;
2282 
2283 	ret = perf_session__process_events(session);
2284 	if (ret)
2285 		return ret;
2286 
2287 	perf_session__delete(session);
2288 	return 0;
2289 }
2290 
2291 static void setup_system_wide(int forks)
2292 {
2293 	/*
2294 	 * Make system wide (-a) the default target if
2295 	 * no target was specified and one of following
2296 	 * conditions is met:
2297 	 *
2298 	 *   - there's no workload specified
2299 	 *   - there is workload specified but all requested
2300 	 *     events are system wide events
2301 	 */
2302 	if (!target__none(&target))
2303 		return;
2304 
2305 	if (!forks)
2306 		target.system_wide = true;
2307 	else {
2308 		struct evsel *counter;
2309 
2310 		evlist__for_each_entry(evsel_list, counter) {
2311 			if (!counter->core.requires_cpu &&
2312 			    !evsel__name_is(counter, "duration_time")) {
2313 				return;
2314 			}
2315 		}
2316 
2317 		if (evsel_list->core.nr_entries)
2318 			target.system_wide = true;
2319 	}
2320 }
2321 
2322 #ifdef HAVE_ARCH_X86_64_SUPPORT
2323 static int parse_tpebs_mode(const struct option *opt, const char *str,
2324 			    int unset __maybe_unused)
2325 {
2326 	enum tpebs_mode *mode = opt->value;
2327 
2328 	if (!strcasecmp("mean", str)) {
2329 		*mode = TPEBS_MODE__MEAN;
2330 		return 0;
2331 	}
2332 	if (!strcasecmp("min", str)) {
2333 		*mode = TPEBS_MODE__MIN;
2334 		return 0;
2335 	}
2336 	if (!strcasecmp("max", str)) {
2337 		*mode = TPEBS_MODE__MAX;
2338 		return 0;
2339 	}
2340 	if (!strcasecmp("last", str)) {
2341 		*mode = TPEBS_MODE__LAST;
2342 		return 0;
2343 	}
2344 	return -1;
2345 }
2346 #endif // HAVE_ARCH_X86_64_SUPPORT
2347 
2348 int cmd_stat(int argc, const char **argv)
2349 {
2350 	struct opt_aggr_mode opt_mode = {};
2351 	struct option stat_options[] = {
2352 		OPT_BOOLEAN('T', "transaction", &transaction_run,
2353 			"hardware transaction statistics"),
2354 		OPT_CALLBACK('e', "event", &parse_events_option_args, "event",
2355 			"event selector. use 'perf list' to list available events",
2356 			parse_events_option),
2357 		OPT_CALLBACK(0, "filter", &evsel_list, "filter",
2358 			"event filter", parse_filter),
2359 		OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
2360 			"child tasks do not inherit counters"),
2361 		OPT_STRING('p', "pid", &target.pid, "pid",
2362 			"stat events on existing process id"),
2363 		OPT_STRING('t', "tid", &target.tid, "tid",
2364 			"stat events on existing thread id"),
2365 #ifdef HAVE_BPF_SKEL
2366 		OPT_STRING('b', "bpf-prog", &target.bpf_str, "bpf-prog-id",
2367 			"stat events on existing bpf program id"),
2368 		OPT_BOOLEAN(0, "bpf-counters", &target.use_bpf,
2369 			"use bpf program to count events"),
2370 		OPT_STRING(0, "bpf-attr-map", &target.attr_map, "attr-map-path",
2371 			"path to perf_event_attr map"),
2372 #endif
2373 		OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
2374 			"system-wide collection from all CPUs"),
2375 		OPT_BOOLEAN(0, "scale", &stat_config.scale,
2376 			"Use --no-scale to disable counter scaling for multiplexing"),
2377 		OPT_INCR('v', "verbose", &verbose,
2378 			"be more verbose (show counter open errors, etc)"),
2379 		OPT_INTEGER('r', "repeat", &stat_config.run_count,
2380 			"repeat command and print average + stddev (max: 100, forever: 0)"),
2381 		OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
2382 			"display details about each run (only with -r option)"),
2383 		OPT_BOOLEAN('n', "null", &stat_config.null_run,
2384 			"null run - dont start any counters"),
2385 		OPT_INCR('d', "detailed", &detailed_run,
2386 			"detailed run - start a lot of events"),
2387 		OPT_BOOLEAN('S', "sync", &sync_run,
2388 			"call sync() before starting a run"),
2389 		OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
2390 				"print large numbers with thousands\' separators",
2391 				stat__set_big_num),
2392 		OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
2393 			"list of cpus to monitor in system-wide"),
2394 		OPT_BOOLEAN('A', "no-aggr", &opt_mode.no_aggr,
2395 			"disable aggregation across CPUs or PMUs"),
2396 		OPT_BOOLEAN(0, "no-merge", &opt_mode.no_aggr,
2397 			"disable aggregation the same as -A or -no-aggr"),
2398 		OPT_BOOLEAN(0, "hybrid-merge", &stat_config.hybrid_merge,
2399 			"Merge identical named hybrid events"),
2400 		OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
2401 			"print counts with custom separator"),
2402 		OPT_BOOLEAN('j', "json-output", &stat_config.json_output,
2403 			"print counts in JSON format"),
2404 		OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
2405 			"monitor event in cgroup name only", parse_stat_cgroups),
2406 		OPT_STRING(0, "for-each-cgroup", &stat_config.cgroup_list, "name",
2407 			"expand events for each cgroup"),
2408 		OPT_STRING('o', "output", &output_name, "file", "output file name"),
2409 		OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
2410 		OPT_INTEGER(0, "log-fd", &output_fd,
2411 			"log output to fd, instead of stderr"),
2412 		OPT_STRING(0, "pre", &pre_cmd, "command",
2413 			"command to run prior to the measured command"),
2414 		OPT_STRING(0, "post", &post_cmd, "command",
2415 			"command to run after to the measured command"),
2416 		OPT_UINTEGER('I', "interval-print", &stat_config.interval,
2417 			"print counts at regular interval in ms "
2418 			"(overhead is possible for values <= 100ms)"),
2419 		OPT_INTEGER(0, "interval-count", &stat_config.times,
2420 			"print counts for fixed number of times"),
2421 		OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
2422 			"clear screen in between new interval"),
2423 		OPT_UINTEGER(0, "timeout", &stat_config.timeout,
2424 			"stop workload and print counts after a timeout period in ms (>= 10ms)"),
2425 		OPT_BOOLEAN(0, "per-socket", &opt_mode.socket,
2426 			"aggregate counts per processor socket"),
2427 		OPT_BOOLEAN(0, "per-die", &opt_mode.die, "aggregate counts per processor die"),
2428 		OPT_BOOLEAN(0, "per-cluster", &opt_mode.cluster,
2429 			"aggregate counts per processor cluster"),
2430 		OPT_CALLBACK_OPTARG(0, "per-cache", &opt_mode, &stat_config.aggr_level,
2431 				"cache level", "aggregate count at this cache level (Default: LLC)",
2432 				parse_cache_level),
2433 		OPT_BOOLEAN(0, "per-core", &opt_mode.core,
2434 			"aggregate counts per physical processor core"),
2435 		OPT_BOOLEAN(0, "per-thread", &opt_mode.thread, "aggregate counts per thread"),
2436 		OPT_BOOLEAN(0, "per-node", &opt_mode.node, "aggregate counts per numa node"),
2437 		OPT_INTEGER('D', "delay", &target.initial_delay,
2438 			"ms to wait before starting measurement after program start (-1: start with events disabled)"),
2439 		OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
2440 				"Only print computed metrics. No raw values", enable_metric_only),
2441 		OPT_BOOLEAN(0, "metric-no-group", &stat_config.metric_no_group,
2442 			"don't group metric events, impacts multiplexing"),
2443 		OPT_BOOLEAN(0, "metric-no-merge", &stat_config.metric_no_merge,
2444 			"don't try to share events between metrics in a group"),
2445 		OPT_BOOLEAN(0, "metric-no-threshold", &stat_config.metric_no_threshold,
2446 			"disable adding events for the metric threshold calculation"),
2447 		OPT_BOOLEAN(0, "topdown", &topdown_run,
2448 			"measure top-down statistics"),
2449 #ifdef HAVE_ARCH_X86_64_SUPPORT
2450 		OPT_BOOLEAN(0, "record-tpebs", &tpebs_recording,
2451 			"enable recording for tpebs when retire_latency required"),
2452 		OPT_CALLBACK(0, "tpebs-mode", &tpebs_mode, "tpebs-mode",
2453 			"Mode of TPEBS recording: mean, min or max",
2454 			parse_tpebs_mode),
2455 #endif
2456 		OPT_UINTEGER(0, "td-level", &stat_config.topdown_level,
2457 			"Set the metrics level for the top-down statistics (0: max level)"),
2458 		OPT_BOOLEAN(0, "smi-cost", &smi_cost,
2459 			"measure SMI cost"),
2460 		OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
2461 			"monitor specified metrics or metric groups (separated by ,)",
2462 			append_metric_groups),
2463 		OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
2464 				"Configure all used events to run in kernel space.",
2465 				PARSE_OPT_EXCLUSIVE),
2466 		OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
2467 				"Configure all used events to run in user space.",
2468 				PARSE_OPT_EXCLUSIVE),
2469 		OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
2470 			"Use with 'percore' event qualifier to show the event "
2471 			"counts of one hardware thread by sum up total hardware "
2472 			"threads of same physical core"),
2473 		OPT_BOOLEAN(0, "summary", &stat_config.summary,
2474 			"print summary for interval mode"),
2475 		OPT_BOOLEAN(0, "no-csv-summary", &stat_config.no_csv_summary,
2476 			"don't print 'summary' for CSV summary output"),
2477 		OPT_BOOLEAN(0, "quiet", &quiet,
2478 			"don't print any output, messages or warnings (useful with record)"),
2479 		OPT_CALLBACK(0, "cputype", &evsel_list, "hybrid cpu type",
2480 			"Only enable events on applying cpu with this type "
2481 			"for hybrid platform (e.g. core or atom)",
2482 			parse_cputype),
2483 #ifdef HAVE_LIBPFM
2484 		OPT_CALLBACK(0, "pfm-events", &evsel_list, "event",
2485 			"libpfm4 event selector. use 'perf list' to list available events",
2486 			parse_libpfm_events_option),
2487 #endif
2488 		OPT_CALLBACK(0, "control", &stat_config, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]",
2489 			"Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events).\n"
2490 			"\t\t\t  Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n"
2491 			"\t\t\t  Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.",
2492 			parse_control_option),
2493 		OPT_CALLBACK_OPTARG(0, "iostat", &evsel_list, &stat_config, "default",
2494 				"measure I/O performance metrics provided by arch/platform",
2495 				iostat_parse),
2496 		OPT_END()
2497 	};
2498 	const char * const stat_usage[] = {
2499 		"perf stat [<options>] [<command>]",
2500 		NULL
2501 	};
2502 	int status = -EINVAL, run_idx, err;
2503 	const char *mode;
2504 	FILE *output = stderr;
2505 	unsigned int interval, timeout;
2506 	const char * const stat_subcommands[] = { "record", "report" };
2507 	char errbuf[BUFSIZ];
2508 
2509 	setlocale(LC_ALL, "");
2510 
2511 	evsel_list = evlist__new();
2512 	if (evsel_list == NULL)
2513 		return -ENOMEM;
2514 
2515 	parse_events__shrink_config_terms();
2516 
2517 	/* String-parsing callback-based options would segfault when negated */
2518 	set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
2519 	set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
2520 	set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
2521 
2522 	argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2523 					(const char **) stat_usage,
2524 					PARSE_OPT_STOP_AT_NON_OPTION);
2525 
2526 	stat_config.aggr_mode = opt_aggr_mode_to_aggr_mode(&opt_mode);
2527 
2528 	if (stat_config.csv_sep) {
2529 		stat_config.csv_output = true;
2530 		if (!strcmp(stat_config.csv_sep, "\\t"))
2531 			stat_config.csv_sep = "\t";
2532 	} else
2533 		stat_config.csv_sep = DEFAULT_SEPARATOR;
2534 
2535 	if (argc && strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
2536 		argc = __cmd_record(stat_options, &opt_mode, argc, argv);
2537 		if (argc < 0)
2538 			return -1;
2539 	} else if (argc && strlen(argv[0]) > 2 && strstarts("report", argv[0]))
2540 		return __cmd_report(argc, argv);
2541 
2542 	interval = stat_config.interval;
2543 	timeout = stat_config.timeout;
2544 
2545 	/*
2546 	 * For record command the -o is already taken care of.
2547 	 */
2548 	if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2549 		output = NULL;
2550 
2551 	if (output_name && output_fd) {
2552 		fprintf(stderr, "cannot use both --output and --log-fd\n");
2553 		parse_options_usage(stat_usage, stat_options, "o", 1);
2554 		parse_options_usage(NULL, stat_options, "log-fd", 0);
2555 		goto out;
2556 	}
2557 
2558 	if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2559 		fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2560 		goto out;
2561 	}
2562 
2563 	if (stat_config.metric_only && stat_config.run_count > 1) {
2564 		fprintf(stderr, "--metric-only is not supported with -r\n");
2565 		goto out;
2566 	}
2567 
2568 	if (stat_config.csv_output || (stat_config.metric_only && stat_config.json_output)) {
2569 		/*
2570 		 * Current CSV and metric-only JSON output doesn't display the
2571 		 * metric threshold so don't compute it.
2572 		 */
2573 		stat_config.metric_no_threshold = true;
2574 	}
2575 
2576 	if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
2577 		fprintf(stderr, "--table is only supported with -r\n");
2578 		parse_options_usage(stat_usage, stat_options, "r", 1);
2579 		parse_options_usage(NULL, stat_options, "table", 0);
2580 		goto out;
2581 	}
2582 
2583 	if (output_fd < 0) {
2584 		fprintf(stderr, "argument to --log-fd must be a > 0\n");
2585 		parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2586 		goto out;
2587 	}
2588 
2589 	if (!output && !quiet) {
2590 		struct timespec tm;
2591 		mode = append_file ? "a" : "w";
2592 
2593 		output = fopen(output_name, mode);
2594 		if (!output) {
2595 			perror("failed to create output file");
2596 			return -1;
2597 		}
2598 		if (!stat_config.json_output) {
2599 			clock_gettime(CLOCK_REALTIME, &tm);
2600 			fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2601 		}
2602 	} else if (output_fd > 0) {
2603 		mode = append_file ? "a" : "w";
2604 		output = fdopen(output_fd, mode);
2605 		if (!output) {
2606 			perror("Failed opening logfd");
2607 			return -errno;
2608 		}
2609 	}
2610 
2611 	if (stat_config.interval_clear && !isatty(fileno(output))) {
2612 		fprintf(stderr, "--interval-clear does not work with output\n");
2613 		parse_options_usage(stat_usage, stat_options, "o", 1);
2614 		parse_options_usage(NULL, stat_options, "log-fd", 0);
2615 		parse_options_usage(NULL, stat_options, "interval-clear", 0);
2616 		return -1;
2617 	}
2618 
2619 	stat_config.output = output;
2620 
2621 	/*
2622 	 * let the spreadsheet do the pretty-printing
2623 	 */
2624 	if (stat_config.csv_output) {
2625 		/* User explicitly passed -B? */
2626 		if (big_num_opt == 1) {
2627 			fprintf(stderr, "-B option not supported with -x\n");
2628 			parse_options_usage(stat_usage, stat_options, "B", 1);
2629 			parse_options_usage(NULL, stat_options, "x", 1);
2630 			goto out;
2631 		} else /* Nope, so disable big number formatting */
2632 			stat_config.big_num = false;
2633 	} else if (big_num_opt == 0) /* User passed --no-big-num */
2634 		stat_config.big_num = false;
2635 
2636 	target.inherit = !stat_config.no_inherit;
2637 	err = target__validate(&target);
2638 	if (err) {
2639 		target__strerror(&target, err, errbuf, BUFSIZ);
2640 		pr_warning("%s\n", errbuf);
2641 	}
2642 
2643 	setup_system_wide(argc);
2644 
2645 	/*
2646 	 * Display user/system times only for single
2647 	 * run and when there's specified tracee.
2648 	 */
2649 	if ((stat_config.run_count == 1) && target__none(&target))
2650 		stat_config.ru_display = true;
2651 
2652 	if (stat_config.run_count < 0) {
2653 		pr_err("Run count must be a positive number\n");
2654 		parse_options_usage(stat_usage, stat_options, "r", 1);
2655 		goto out;
2656 	} else if (stat_config.run_count == 0) {
2657 		forever = true;
2658 		stat_config.run_count = 1;
2659 	}
2660 
2661 	if (stat_config.walltime_run_table) {
2662 		stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
2663 		if (!stat_config.walltime_run) {
2664 			pr_err("failed to setup -r option");
2665 			goto out;
2666 		}
2667 	}
2668 
2669 	if ((stat_config.aggr_mode == AGGR_THREAD) &&
2670 		!target__has_task(&target)) {
2671 		if (!target.system_wide || target.cpu_list) {
2672 			fprintf(stderr, "The --per-thread option is only "
2673 				"available when monitoring via -p -t -a "
2674 				"options or only --per-thread.\n");
2675 			parse_options_usage(NULL, stat_options, "p", 1);
2676 			parse_options_usage(NULL, stat_options, "t", 1);
2677 			goto out;
2678 		}
2679 	}
2680 
2681 	/*
2682 	 * no_aggr, cgroup are for system-wide only
2683 	 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2684 	 */
2685 	if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2686 	      stat_config.aggr_mode != AGGR_THREAD) ||
2687 	     (nr_cgroups || stat_config.cgroup_list)) &&
2688 	    !target__has_cpu(&target)) {
2689 		fprintf(stderr, "both cgroup and no-aggregation "
2690 			"modes only available in system-wide mode\n");
2691 
2692 		parse_options_usage(stat_usage, stat_options, "G", 1);
2693 		parse_options_usage(NULL, stat_options, "A", 1);
2694 		parse_options_usage(NULL, stat_options, "a", 1);
2695 		parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2696 		goto out;
2697 	}
2698 
2699 	if (stat_config.iostat_run) {
2700 		status = iostat_prepare(evsel_list, &stat_config);
2701 		if (status)
2702 			goto out;
2703 		if (iostat_mode == IOSTAT_LIST) {
2704 			iostat_list(evsel_list, &stat_config);
2705 			goto out;
2706 		} else if (verbose > 0)
2707 			iostat_list(evsel_list, &stat_config);
2708 		if (iostat_mode == IOSTAT_RUN && !target__has_cpu(&target))
2709 			target.system_wide = true;
2710 	}
2711 
2712 	if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2713 		target.per_thread = true;
2714 
2715 	stat_config.system_wide = target.system_wide;
2716 	if (target.cpu_list) {
2717 		stat_config.user_requested_cpu_list = strdup(target.cpu_list);
2718 		if (!stat_config.user_requested_cpu_list) {
2719 			status = -ENOMEM;
2720 			goto out;
2721 		}
2722 	}
2723 
2724 	/*
2725 	 * Metric parsing needs to be delayed as metrics may optimize events
2726 	 * knowing the target is system-wide.
2727 	 */
2728 	if (metrics) {
2729 		const char *pmu = parse_events_option_args.pmu_filter ?: "all";
2730 		int ret = metricgroup__parse_groups(evsel_list, pmu, metrics,
2731 						stat_config.metric_no_group,
2732 						stat_config.metric_no_merge,
2733 						stat_config.metric_no_threshold,
2734 						stat_config.user_requested_cpu_list,
2735 						stat_config.system_wide,
2736 						stat_config.hardware_aware_grouping);
2737 
2738 		zfree(&metrics);
2739 		if (ret) {
2740 			status = ret;
2741 			goto out;
2742 		}
2743 	}
2744 
2745 	if (add_default_events())
2746 		goto out;
2747 
2748 	if (stat_config.cgroup_list) {
2749 		if (nr_cgroups > 0) {
2750 			pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
2751 			parse_options_usage(stat_usage, stat_options, "G", 1);
2752 			parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2753 			goto out;
2754 		}
2755 
2756 		if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list, true) < 0) {
2757 			parse_options_usage(stat_usage, stat_options,
2758 					    "for-each-cgroup", 0);
2759 			goto out;
2760 		}
2761 	}
2762 
2763 	evlist__warn_user_requested_cpus(evsel_list, target.cpu_list);
2764 
2765 	if (evlist__create_maps(evsel_list, &target) < 0) {
2766 		if (target__has_task(&target)) {
2767 			pr_err("Problems finding threads of monitor\n");
2768 			parse_options_usage(stat_usage, stat_options, "p", 1);
2769 			parse_options_usage(NULL, stat_options, "t", 1);
2770 		} else if (target__has_cpu(&target)) {
2771 			perror("failed to parse CPUs map");
2772 			parse_options_usage(stat_usage, stat_options, "C", 1);
2773 			parse_options_usage(NULL, stat_options, "a", 1);
2774 		}
2775 		goto out;
2776 	}
2777 
2778 	evlist__check_cpu_maps(evsel_list);
2779 
2780 	/*
2781 	 * Initialize thread_map with comm names,
2782 	 * so we could print it out on output.
2783 	 */
2784 	if (stat_config.aggr_mode == AGGR_THREAD) {
2785 		thread_map__read_comms(evsel_list->core.threads);
2786 	}
2787 
2788 	if (stat_config.aggr_mode == AGGR_NODE)
2789 		cpu__setup_cpunode_map();
2790 
2791 	if (stat_config.times && interval)
2792 		interval_count = true;
2793 	else if (stat_config.times && !interval) {
2794 		pr_err("interval-count option should be used together with "
2795 				"interval-print.\n");
2796 		parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2797 		parse_options_usage(stat_usage, stat_options, "I", 1);
2798 		goto out;
2799 	}
2800 
2801 	if (timeout && timeout < 100) {
2802 		if (timeout < 10) {
2803 			pr_err("timeout must be >= 10ms.\n");
2804 			parse_options_usage(stat_usage, stat_options, "timeout", 0);
2805 			goto out;
2806 		} else
2807 			pr_warning("timeout < 100ms. "
2808 				   "The overhead percentage could be high in some cases. "
2809 				   "Please proceed with caution.\n");
2810 	}
2811 	if (timeout && interval) {
2812 		pr_err("timeout option is not supported with interval-print.\n");
2813 		parse_options_usage(stat_usage, stat_options, "timeout", 0);
2814 		parse_options_usage(stat_usage, stat_options, "I", 1);
2815 		goto out;
2816 	}
2817 
2818 	if (perf_stat_init_aggr_mode())
2819 		goto out;
2820 
2821 	if (evlist__alloc_stats(&stat_config, evsel_list, interval))
2822 		goto out;
2823 
2824 	/*
2825 	 * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2826 	 * while avoiding that older tools show confusing messages.
2827 	 *
2828 	 * However for pipe sessions we need to keep it zero,
2829 	 * because script's perf_evsel__check_attr is triggered
2830 	 * by attr->sample_type != 0, and we can't run it on
2831 	 * stat sessions.
2832 	 */
2833 	stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2834 
2835 	/*
2836 	 * We dont want to block the signals - that would cause
2837 	 * child tasks to inherit that and Ctrl-C would not work.
2838 	 * What we want is for Ctrl-C to work in the exec()-ed
2839 	 * task, but being ignored by perf stat itself:
2840 	 */
2841 	atexit(sig_atexit);
2842 	if (!forever)
2843 		signal(SIGINT,  skip_signal);
2844 	signal(SIGCHLD, skip_signal);
2845 	signal(SIGALRM, skip_signal);
2846 	signal(SIGABRT, skip_signal);
2847 
2848 	if (evlist__initialize_ctlfd(evsel_list, stat_config.ctl_fd, stat_config.ctl_fd_ack))
2849 		goto out;
2850 
2851 	/* Enable ignoring missing threads when -p option is defined. */
2852 	evlist__first(evsel_list)->ignore_missing_thread = target.pid;
2853 	status = 0;
2854 	for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
2855 		if (stat_config.run_count != 1 && verbose > 0)
2856 			fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2857 				run_idx + 1);
2858 
2859 		if (run_idx != 0)
2860 			evlist__reset_prev_raw_counts(evsel_list);
2861 
2862 		status = run_perf_stat(argc, argv, run_idx);
2863 		if (status == -1)
2864 			break;
2865 
2866 		if (forever && !interval) {
2867 			print_counters(NULL, argc, argv);
2868 			perf_stat__reset_stats();
2869 		}
2870 	}
2871 
2872 	if (!forever && status != -1 && (!interval || stat_config.summary)) {
2873 		if (stat_config.run_count > 1)
2874 			evlist__copy_res_stats(&stat_config, evsel_list);
2875 		print_counters(NULL, argc, argv);
2876 	}
2877 
2878 	evlist__finalize_ctlfd(evsel_list);
2879 
2880 	if (STAT_RECORD) {
2881 		/*
2882 		 * We synthesize the kernel mmap record just so that older tools
2883 		 * don't emit warnings about not being able to resolve symbols
2884 		 * due to /proc/sys/kernel/kptr_restrict settings and instead provide
2885 		 * a saner message about no samples being in the perf.data file.
2886 		 *
2887 		 * This also serves to suppress a warning about f_header.data.size == 0
2888 		 * in header.c at the moment 'perf stat record' gets introduced, which
2889 		 * is not really needed once we start adding the stat specific PERF_RECORD_
2890 		 * records, but the need to suppress the kptr_restrict messages in older
2891 		 * tools remain  -acme
2892 		 */
2893 		int fd = perf_data__fd(&perf_stat.data);
2894 
2895 		err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2896 							 process_synthesized_event,
2897 							 &perf_stat.session->machines.host);
2898 		if (err) {
2899 			pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2900 				   "older tools may produce warnings about this file\n.");
2901 		}
2902 
2903 		if (!interval) {
2904 			if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2905 				pr_err("failed to write stat round event\n");
2906 		}
2907 
2908 		if (!perf_stat.data.is_pipe) {
2909 			perf_stat.session->header.data_size += perf_stat.bytes_written;
2910 			perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2911 		}
2912 
2913 		evlist__close(evsel_list);
2914 		perf_session__delete(perf_stat.session);
2915 	}
2916 
2917 	perf_stat__exit_aggr_mode();
2918 	evlist__free_stats(evsel_list);
2919 out:
2920 	if (stat_config.iostat_run)
2921 		iostat_release(evsel_list);
2922 
2923 	zfree(&stat_config.walltime_run);
2924 	zfree(&stat_config.user_requested_cpu_list);
2925 
2926 	if (smi_cost && smi_reset)
2927 		sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2928 
2929 	evlist__delete(evsel_list);
2930 
2931 	evlist__close_control(stat_config.ctl_fd, stat_config.ctl_fd_ack, &stat_config.ctl_fd_close);
2932 
2933 	return status;
2934 }
2935