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