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