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