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