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