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