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