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