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