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