xref: /linux/tools/perf/builtin-stat.c (revision c53b4bb02b45ceec7a590e47820afbb5cef0bb81)
1 /*
2  * builtin-stat.c
3  *
4  * Builtin stat command: Give a precise performance counters summary
5  * overview about any workload, CPU or specific PID.
6  *
7  * Sample output:
8 
9    $ perf stat ./hackbench 10
10 
11   Time: 0.118
12 
13   Performance counter stats for './hackbench 10':
14 
15        1708.761321 task-clock                #   11.037 CPUs utilized
16             41,190 context-switches          #    0.024 M/sec
17              6,735 CPU-migrations            #    0.004 M/sec
18             17,318 page-faults               #    0.010 M/sec
19      5,205,202,243 cycles                    #    3.046 GHz
20      3,856,436,920 stalled-cycles-frontend   #   74.09% frontend cycles idle
21      1,600,790,871 stalled-cycles-backend    #   30.75% backend  cycles idle
22      2,603,501,247 instructions              #    0.50  insns per cycle
23                                              #    1.48  stalled cycles per insn
24        484,357,498 branches                  #  283.455 M/sec
25          6,388,934 branch-misses             #    1.32% of all branches
26 
27         0.154822978  seconds time elapsed
28 
29  *
30  * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
31  *
32  * Improvements and fixes by:
33  *
34  *   Arjan van de Ven <arjan@linux.intel.com>
35  *   Yanmin Zhang <yanmin.zhang@intel.com>
36  *   Wu Fengguang <fengguang.wu@intel.com>
37  *   Mike Galbraith <efault@gmx.de>
38  *   Paul Mackerras <paulus@samba.org>
39  *   Jaswinder Singh Rajput <jaswinder@kernel.org>
40  *
41  * Released under the GPL v2. (and only v2, not any later version)
42  */
43 
44 #include "perf.h"
45 #include "builtin.h"
46 #include "util/cgroup.h"
47 #include "util/util.h"
48 #include <subcmd/parse-options.h>
49 #include "util/parse-events.h"
50 #include "util/pmu.h"
51 #include "util/event.h"
52 #include "util/evlist.h"
53 #include "util/evsel.h"
54 #include "util/debug.h"
55 #include "util/drv_configs.h"
56 #include "util/color.h"
57 #include "util/stat.h"
58 #include "util/header.h"
59 #include "util/cpumap.h"
60 #include "util/thread.h"
61 #include "util/thread_map.h"
62 #include "util/counts.h"
63 #include "util/group.h"
64 #include "util/session.h"
65 #include "util/tool.h"
66 #include "util/string2.h"
67 #include "util/metricgroup.h"
68 #include "asm/bug.h"
69 
70 #include <linux/time64.h>
71 #include <api/fs/fs.h>
72 #include <errno.h>
73 #include <signal.h>
74 #include <stdlib.h>
75 #include <sys/prctl.h>
76 #include <inttypes.h>
77 #include <locale.h>
78 #include <math.h>
79 #include <sys/types.h>
80 #include <sys/stat.h>
81 #include <sys/wait.h>
82 #include <unistd.h>
83 
84 #include "sane_ctype.h"
85 
86 #define DEFAULT_SEPARATOR	" "
87 #define CNTR_NOT_SUPPORTED	"<not supported>"
88 #define CNTR_NOT_COUNTED	"<not counted>"
89 #define FREEZE_ON_SMI_PATH	"devices/cpu/freeze_on_smi"
90 
91 static void print_counters(struct timespec *ts, int argc, const char **argv);
92 
93 /* Default events used for perf stat -T */
94 static const char *transaction_attrs = {
95 	"task-clock,"
96 	"{"
97 	"instructions,"
98 	"cycles,"
99 	"cpu/cycles-t/,"
100 	"cpu/tx-start/,"
101 	"cpu/el-start/,"
102 	"cpu/cycles-ct/"
103 	"}"
104 };
105 
106 /* More limited version when the CPU does not have all events. */
107 static const char * transaction_limited_attrs = {
108 	"task-clock,"
109 	"{"
110 	"instructions,"
111 	"cycles,"
112 	"cpu/cycles-t/,"
113 	"cpu/tx-start/"
114 	"}"
115 };
116 
117 static const char * topdown_attrs[] = {
118 	"topdown-total-slots",
119 	"topdown-slots-retired",
120 	"topdown-recovery-bubbles",
121 	"topdown-fetch-bubbles",
122 	"topdown-slots-issued",
123 	NULL,
124 };
125 
126 static const char *smi_cost_attrs = {
127 	"{"
128 	"msr/aperf/,"
129 	"msr/smi/,"
130 	"cycles"
131 	"}"
132 };
133 
134 static struct perf_evlist	*evsel_list;
135 
136 static struct rblist		 metric_events;
137 
138 static struct target target = {
139 	.uid	= UINT_MAX,
140 };
141 
142 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu);
143 
144 static int			run_count			=  1;
145 static bool			no_inherit			= false;
146 static volatile pid_t		child_pid			= -1;
147 static bool			null_run			=  false;
148 static int			detailed_run			=  0;
149 static bool			transaction_run;
150 static bool			topdown_run			= false;
151 static bool			smi_cost			= false;
152 static bool			smi_reset			= false;
153 static bool			big_num				=  true;
154 static int			big_num_opt			=  -1;
155 static const char		*csv_sep			= NULL;
156 static bool			csv_output			= false;
157 static bool			group				= false;
158 static const char		*pre_cmd			= NULL;
159 static const char		*post_cmd			= NULL;
160 static bool			sync_run			= false;
161 static unsigned int		initial_delay			= 0;
162 static unsigned int		unit_width			= 4; /* strlen("unit") */
163 static bool			forever				= false;
164 static bool			metric_only			= false;
165 static bool			force_metric_only		= false;
166 static bool			no_merge			= false;
167 static struct timespec		ref_time;
168 static struct cpu_map		*aggr_map;
169 static aggr_get_id_t		aggr_get_id;
170 static bool			append_file;
171 static bool			interval_count;
172 static const char		*output_name;
173 static int			output_fd;
174 static int			print_free_counters_hint;
175 
176 struct perf_stat {
177 	bool			 record;
178 	struct perf_data	 data;
179 	struct perf_session	*session;
180 	u64			 bytes_written;
181 	struct perf_tool	 tool;
182 	bool			 maps_allocated;
183 	struct cpu_map		*cpus;
184 	struct thread_map	*threads;
185 	enum aggr_mode		 aggr_mode;
186 };
187 
188 static struct perf_stat		perf_stat;
189 #define STAT_RECORD		perf_stat.record
190 
191 static volatile int done = 0;
192 
193 static struct perf_stat_config stat_config = {
194 	.aggr_mode	= AGGR_GLOBAL,
195 	.scale		= true,
196 };
197 
198 static bool is_duration_time(struct perf_evsel *evsel)
199 {
200 	return !strcmp(evsel->name, "duration_time");
201 }
202 
203 static inline void diff_timespec(struct timespec *r, struct timespec *a,
204 				 struct timespec *b)
205 {
206 	r->tv_sec = a->tv_sec - b->tv_sec;
207 	if (a->tv_nsec < b->tv_nsec) {
208 		r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
209 		r->tv_sec--;
210 	} else {
211 		r->tv_nsec = a->tv_nsec - b->tv_nsec ;
212 	}
213 }
214 
215 static void perf_stat__reset_stats(void)
216 {
217 	int i;
218 
219 	perf_evlist__reset_stats(evsel_list);
220 	perf_stat__reset_shadow_stats();
221 
222 	for (i = 0; i < stat_config.stats_num; i++)
223 		perf_stat__reset_shadow_per_stat(&stat_config.stats[i]);
224 }
225 
226 static int create_perf_stat_counter(struct perf_evsel *evsel)
227 {
228 	struct perf_event_attr *attr = &evsel->attr;
229 	struct perf_evsel *leader = evsel->leader;
230 
231 	if (stat_config.scale) {
232 		attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
233 				    PERF_FORMAT_TOTAL_TIME_RUNNING;
234 	}
235 
236 	/*
237 	 * The event is part of non trivial group, let's enable
238 	 * the group read (for leader) and ID retrieval for all
239 	 * members.
240 	 */
241 	if (leader->nr_members > 1)
242 		attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
243 
244 	attr->inherit = !no_inherit;
245 
246 	/*
247 	 * Some events get initialized with sample_(period/type) set,
248 	 * like tracepoints. Clear it up for counting.
249 	 */
250 	attr->sample_period = 0;
251 
252 	/*
253 	 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
254 	 * while avoiding that older tools show confusing messages.
255 	 *
256 	 * However for pipe sessions we need to keep it zero,
257 	 * because script's perf_evsel__check_attr is triggered
258 	 * by attr->sample_type != 0, and we can't run it on
259 	 * stat sessions.
260 	 */
261 	if (!(STAT_RECORD && perf_stat.data.is_pipe))
262 		attr->sample_type = PERF_SAMPLE_IDENTIFIER;
263 
264 	/*
265 	 * Disabling all counters initially, they will be enabled
266 	 * either manually by us or by kernel via enable_on_exec
267 	 * set later.
268 	 */
269 	if (perf_evsel__is_group_leader(evsel)) {
270 		attr->disabled = 1;
271 
272 		/*
273 		 * In case of initial_delay we enable tracee
274 		 * events manually.
275 		 */
276 		if (target__none(&target) && !initial_delay)
277 			attr->enable_on_exec = 1;
278 	}
279 
280 	if (target__has_cpu(&target) && !target__has_per_thread(&target))
281 		return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
282 
283 	return perf_evsel__open_per_thread(evsel, evsel_list->threads);
284 }
285 
286 /*
287  * Does the counter have nsecs as a unit?
288  */
289 static inline int nsec_counter(struct perf_evsel *evsel)
290 {
291 	if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
292 	    perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
293 		return 1;
294 
295 	return 0;
296 }
297 
298 static int process_synthesized_event(struct perf_tool *tool __maybe_unused,
299 				     union perf_event *event,
300 				     struct perf_sample *sample __maybe_unused,
301 				     struct machine *machine __maybe_unused)
302 {
303 	if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
304 		pr_err("failed to write perf data, error: %m\n");
305 		return -1;
306 	}
307 
308 	perf_stat.bytes_written += event->header.size;
309 	return 0;
310 }
311 
312 static int write_stat_round_event(u64 tm, u64 type)
313 {
314 	return perf_event__synthesize_stat_round(NULL, tm, type,
315 						 process_synthesized_event,
316 						 NULL);
317 }
318 
319 #define WRITE_STAT_ROUND_EVENT(time, interval) \
320 	write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
321 
322 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y)
323 
324 static int
325 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread,
326 			     struct perf_counts_values *count)
327 {
328 	struct perf_sample_id *sid = SID(counter, cpu, thread);
329 
330 	return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
331 					   process_synthesized_event, NULL);
332 }
333 
334 /*
335  * Read out the results of a single counter:
336  * do not aggregate counts across CPUs in system-wide mode
337  */
338 static int read_counter(struct perf_evsel *counter)
339 {
340 	int nthreads = thread_map__nr(evsel_list->threads);
341 	int ncpus, cpu, thread;
342 
343 	if (target__has_cpu(&target) && !target__has_per_thread(&target))
344 		ncpus = perf_evsel__nr_cpus(counter);
345 	else
346 		ncpus = 1;
347 
348 	if (!counter->supported)
349 		return -ENOENT;
350 
351 	if (counter->system_wide)
352 		nthreads = 1;
353 
354 	for (thread = 0; thread < nthreads; thread++) {
355 		for (cpu = 0; cpu < ncpus; cpu++) {
356 			struct perf_counts_values *count;
357 
358 			count = perf_counts(counter->counts, cpu, thread);
359 
360 			/*
361 			 * The leader's group read loads data into its group members
362 			 * (via perf_evsel__read_counter) and sets threir count->loaded.
363 			 */
364 			if (!count->loaded &&
365 			    perf_evsel__read_counter(counter, cpu, thread)) {
366 				counter->counts->scaled = -1;
367 				perf_counts(counter->counts, cpu, thread)->ena = 0;
368 				perf_counts(counter->counts, cpu, thread)->run = 0;
369 				return -1;
370 			}
371 
372 			count->loaded = false;
373 
374 			if (STAT_RECORD) {
375 				if (perf_evsel__write_stat_event(counter, cpu, thread, count)) {
376 					pr_err("failed to write stat event\n");
377 					return -1;
378 				}
379 			}
380 
381 			if (verbose > 1) {
382 				fprintf(stat_config.output,
383 					"%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
384 						perf_evsel__name(counter),
385 						cpu,
386 						count->val, count->ena, count->run);
387 			}
388 		}
389 	}
390 
391 	return 0;
392 }
393 
394 static void read_counters(void)
395 {
396 	struct perf_evsel *counter;
397 	int ret;
398 
399 	evlist__for_each_entry(evsel_list, counter) {
400 		ret = read_counter(counter);
401 		if (ret)
402 			pr_debug("failed to read counter %s\n", counter->name);
403 
404 		if (ret == 0 && perf_stat_process_counter(&stat_config, counter))
405 			pr_warning("failed to process counter %s\n", counter->name);
406 	}
407 }
408 
409 static void process_interval(void)
410 {
411 	struct timespec ts, rs;
412 
413 	read_counters();
414 
415 	clock_gettime(CLOCK_MONOTONIC, &ts);
416 	diff_timespec(&rs, &ts, &ref_time);
417 
418 	if (STAT_RECORD) {
419 		if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
420 			pr_err("failed to write stat round event\n");
421 	}
422 
423 	init_stats(&walltime_nsecs_stats);
424 	update_stats(&walltime_nsecs_stats, stat_config.interval * 1000000);
425 	print_counters(&rs, 0, NULL);
426 }
427 
428 static void enable_counters(void)
429 {
430 	if (initial_delay)
431 		usleep(initial_delay * USEC_PER_MSEC);
432 
433 	/*
434 	 * We need to enable counters only if:
435 	 * - we don't have tracee (attaching to task or cpu)
436 	 * - we have initial delay configured
437 	 */
438 	if (!target__none(&target) || initial_delay)
439 		perf_evlist__enable(evsel_list);
440 }
441 
442 static void disable_counters(void)
443 {
444 	/*
445 	 * If we don't have tracee (attaching to task or cpu), counters may
446 	 * still be running. To get accurate group ratios, we must stop groups
447 	 * from counting before reading their constituent counters.
448 	 */
449 	if (!target__none(&target))
450 		perf_evlist__disable(evsel_list);
451 }
452 
453 static volatile int workload_exec_errno;
454 
455 /*
456  * perf_evlist__prepare_workload will send a SIGUSR1
457  * if the fork fails, since we asked by setting its
458  * want_signal to true.
459  */
460 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
461 					void *ucontext __maybe_unused)
462 {
463 	workload_exec_errno = info->si_value.sival_int;
464 }
465 
466 static int perf_stat_synthesize_config(bool is_pipe)
467 {
468 	int err;
469 
470 	if (is_pipe) {
471 		err = perf_event__synthesize_attrs(NULL, perf_stat.session,
472 						   process_synthesized_event);
473 		if (err < 0) {
474 			pr_err("Couldn't synthesize attrs.\n");
475 			return err;
476 		}
477 	}
478 
479 	err = perf_event__synthesize_extra_attr(NULL,
480 						evsel_list,
481 						process_synthesized_event,
482 						is_pipe);
483 
484 	err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads,
485 						process_synthesized_event,
486 						NULL);
487 	if (err < 0) {
488 		pr_err("Couldn't synthesize thread map.\n");
489 		return err;
490 	}
491 
492 	err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus,
493 					     process_synthesized_event, NULL);
494 	if (err < 0) {
495 		pr_err("Couldn't synthesize thread map.\n");
496 		return err;
497 	}
498 
499 	err = perf_event__synthesize_stat_config(NULL, &stat_config,
500 						 process_synthesized_event, NULL);
501 	if (err < 0) {
502 		pr_err("Couldn't synthesize config.\n");
503 		return err;
504 	}
505 
506 	return 0;
507 }
508 
509 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
510 
511 static int __store_counter_ids(struct perf_evsel *counter,
512 			       struct cpu_map *cpus,
513 			       struct thread_map *threads)
514 {
515 	int cpu, thread;
516 
517 	for (cpu = 0; cpu < cpus->nr; cpu++) {
518 		for (thread = 0; thread < threads->nr; thread++) {
519 			int fd = FD(counter, cpu, thread);
520 
521 			if (perf_evlist__id_add_fd(evsel_list, counter,
522 						   cpu, thread, fd) < 0)
523 				return -1;
524 		}
525 	}
526 
527 	return 0;
528 }
529 
530 static int store_counter_ids(struct perf_evsel *counter)
531 {
532 	struct cpu_map *cpus = counter->cpus;
533 	struct thread_map *threads = counter->threads;
534 
535 	if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr))
536 		return -ENOMEM;
537 
538 	return __store_counter_ids(counter, cpus, threads);
539 }
540 
541 static bool perf_evsel__should_store_id(struct perf_evsel *counter)
542 {
543 	return STAT_RECORD || counter->attr.read_format & PERF_FORMAT_ID;
544 }
545 
546 static struct perf_evsel *perf_evsel__reset_weak_group(struct perf_evsel *evsel)
547 {
548 	struct perf_evsel *c2, *leader;
549 	bool is_open = true;
550 
551 	leader = evsel->leader;
552 	pr_debug("Weak group for %s/%d failed\n",
553 			leader->name, leader->nr_members);
554 
555 	/*
556 	 * for_each_group_member doesn't work here because it doesn't
557 	 * include the first entry.
558 	 */
559 	evlist__for_each_entry(evsel_list, c2) {
560 		if (c2 == evsel)
561 			is_open = false;
562 		if (c2->leader == leader) {
563 			if (is_open)
564 				perf_evsel__close(c2);
565 			c2->leader = c2;
566 			c2->nr_members = 0;
567 		}
568 	}
569 	return leader;
570 }
571 
572 static int __run_perf_stat(int argc, const char **argv)
573 {
574 	int interval = stat_config.interval;
575 	int times = stat_config.times;
576 	int timeout = stat_config.timeout;
577 	char msg[BUFSIZ];
578 	unsigned long long t0, t1;
579 	struct perf_evsel *counter;
580 	struct timespec ts;
581 	size_t l;
582 	int status = 0;
583 	const bool forks = (argc > 0);
584 	bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
585 	struct perf_evsel_config_term *err_term;
586 
587 	if (interval) {
588 		ts.tv_sec  = interval / USEC_PER_MSEC;
589 		ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC;
590 	} else if (timeout) {
591 		ts.tv_sec  = timeout / USEC_PER_MSEC;
592 		ts.tv_nsec = (timeout % USEC_PER_MSEC) * NSEC_PER_MSEC;
593 	} else {
594 		ts.tv_sec  = 1;
595 		ts.tv_nsec = 0;
596 	}
597 
598 	if (forks) {
599 		if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe,
600 						  workload_exec_failed_signal) < 0) {
601 			perror("failed to prepare workload");
602 			return -1;
603 		}
604 		child_pid = evsel_list->workload.pid;
605 	}
606 
607 	if (group)
608 		perf_evlist__set_leader(evsel_list);
609 
610 	evlist__for_each_entry(evsel_list, counter) {
611 try_again:
612 		if (create_perf_stat_counter(counter) < 0) {
613 
614 			/* Weak group failed. Reset the group. */
615 			if ((errno == EINVAL || errno == EBADF) &&
616 			    counter->leader != counter &&
617 			    counter->weak_group) {
618 				counter = perf_evsel__reset_weak_group(counter);
619 				goto try_again;
620 			}
621 
622 			/*
623 			 * PPC returns ENXIO for HW counters until 2.6.37
624 			 * (behavior changed with commit b0a873e).
625 			 */
626 			if (errno == EINVAL || errno == ENOSYS ||
627 			    errno == ENOENT || errno == EOPNOTSUPP ||
628 			    errno == ENXIO) {
629 				if (verbose > 0)
630 					ui__warning("%s event is not supported by the kernel.\n",
631 						    perf_evsel__name(counter));
632 				counter->supported = false;
633 
634 				if ((counter->leader != counter) ||
635 				    !(counter->leader->nr_members > 1))
636 					continue;
637 			} else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
638                                 if (verbose > 0)
639                                         ui__warning("%s\n", msg);
640                                 goto try_again;
641                         }
642 
643 			perf_evsel__open_strerror(counter, &target,
644 						  errno, msg, sizeof(msg));
645 			ui__error("%s\n", msg);
646 
647 			if (child_pid != -1)
648 				kill(child_pid, SIGTERM);
649 
650 			return -1;
651 		}
652 		counter->supported = true;
653 
654 		l = strlen(counter->unit);
655 		if (l > unit_width)
656 			unit_width = l;
657 
658 		if (perf_evsel__should_store_id(counter) &&
659 		    store_counter_ids(counter))
660 			return -1;
661 	}
662 
663 	if (perf_evlist__apply_filters(evsel_list, &counter)) {
664 		pr_err("failed to set filter \"%s\" on event %s with %d (%s)\n",
665 			counter->filter, perf_evsel__name(counter), errno,
666 			str_error_r(errno, msg, sizeof(msg)));
667 		return -1;
668 	}
669 
670 	if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) {
671 		pr_err("failed to set config \"%s\" on event %s with %d (%s)\n",
672 		      err_term->val.drv_cfg, perf_evsel__name(counter), errno,
673 		      str_error_r(errno, msg, sizeof(msg)));
674 		return -1;
675 	}
676 
677 	if (STAT_RECORD) {
678 		int err, fd = perf_data__fd(&perf_stat.data);
679 
680 		if (is_pipe) {
681 			err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
682 		} else {
683 			err = perf_session__write_header(perf_stat.session, evsel_list,
684 							 fd, false);
685 		}
686 
687 		if (err < 0)
688 			return err;
689 
690 		err = perf_stat_synthesize_config(is_pipe);
691 		if (err < 0)
692 			return err;
693 	}
694 
695 	/*
696 	 * Enable counters and exec the command:
697 	 */
698 	t0 = rdclock();
699 	clock_gettime(CLOCK_MONOTONIC, &ref_time);
700 
701 	if (forks) {
702 		perf_evlist__start_workload(evsel_list);
703 		enable_counters();
704 
705 		if (interval || timeout) {
706 			while (!waitpid(child_pid, &status, WNOHANG)) {
707 				nanosleep(&ts, NULL);
708 				if (timeout)
709 					break;
710 				process_interval();
711 				if (interval_count && !(--times))
712 					break;
713 			}
714 		}
715 		waitpid(child_pid, &status, 0);
716 
717 		if (workload_exec_errno) {
718 			const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg));
719 			pr_err("Workload failed: %s\n", emsg);
720 			return -1;
721 		}
722 
723 		if (WIFSIGNALED(status))
724 			psignal(WTERMSIG(status), argv[0]);
725 	} else {
726 		enable_counters();
727 		while (!done) {
728 			nanosleep(&ts, NULL);
729 			if (timeout)
730 				break;
731 			if (interval) {
732 				process_interval();
733 				if (interval_count && !(--times))
734 					break;
735 			}
736 		}
737 	}
738 
739 	disable_counters();
740 
741 	t1 = rdclock();
742 
743 	update_stats(&walltime_nsecs_stats, t1 - t0);
744 
745 	/*
746 	 * Closing a group leader splits the group, and as we only disable
747 	 * group leaders, results in remaining events becoming enabled. To
748 	 * avoid arbitrary skew, we must read all counters before closing any
749 	 * group leaders.
750 	 */
751 	read_counters();
752 	perf_evlist__close(evsel_list);
753 
754 	return WEXITSTATUS(status);
755 }
756 
757 static int run_perf_stat(int argc, const char **argv)
758 {
759 	int ret;
760 
761 	if (pre_cmd) {
762 		ret = system(pre_cmd);
763 		if (ret)
764 			return ret;
765 	}
766 
767 	if (sync_run)
768 		sync();
769 
770 	ret = __run_perf_stat(argc, argv);
771 	if (ret)
772 		return ret;
773 
774 	if (post_cmd) {
775 		ret = system(post_cmd);
776 		if (ret)
777 			return ret;
778 	}
779 
780 	return ret;
781 }
782 
783 static void print_running(u64 run, u64 ena)
784 {
785 	if (csv_output) {
786 		fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f",
787 					csv_sep,
788 					run,
789 					csv_sep,
790 					ena ? 100.0 * run / ena : 100.0);
791 	} else if (run != ena) {
792 		fprintf(stat_config.output, "  (%.2f%%)", 100.0 * run / ena);
793 	}
794 }
795 
796 static void print_noise_pct(double total, double avg)
797 {
798 	double pct = rel_stddev_stats(total, avg);
799 
800 	if (csv_output)
801 		fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct);
802 	else if (pct)
803 		fprintf(stat_config.output, "  ( +-%6.2f%% )", pct);
804 }
805 
806 static void print_noise(struct perf_evsel *evsel, double avg)
807 {
808 	struct perf_stat_evsel *ps;
809 
810 	if (run_count == 1)
811 		return;
812 
813 	ps = evsel->stats;
814 	print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
815 }
816 
817 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
818 {
819 	switch (stat_config.aggr_mode) {
820 	case AGGR_CORE:
821 		fprintf(stat_config.output, "S%d-C%*d%s%*d%s",
822 			cpu_map__id_to_socket(id),
823 			csv_output ? 0 : -8,
824 			cpu_map__id_to_cpu(id),
825 			csv_sep,
826 			csv_output ? 0 : 4,
827 			nr,
828 			csv_sep);
829 		break;
830 	case AGGR_SOCKET:
831 		fprintf(stat_config.output, "S%*d%s%*d%s",
832 			csv_output ? 0 : -5,
833 			id,
834 			csv_sep,
835 			csv_output ? 0 : 4,
836 			nr,
837 			csv_sep);
838 			break;
839 	case AGGR_NONE:
840 		fprintf(stat_config.output, "CPU%*d%s",
841 			csv_output ? 0 : -4,
842 			perf_evsel__cpus(evsel)->map[id], csv_sep);
843 		break;
844 	case AGGR_THREAD:
845 		fprintf(stat_config.output, "%*s-%*d%s",
846 			csv_output ? 0 : 16,
847 			thread_map__comm(evsel->threads, id),
848 			csv_output ? 0 : -8,
849 			thread_map__pid(evsel->threads, id),
850 			csv_sep);
851 		break;
852 	case AGGR_GLOBAL:
853 	case AGGR_UNSET:
854 	default:
855 		break;
856 	}
857 }
858 
859 struct outstate {
860 	FILE *fh;
861 	bool newline;
862 	const char *prefix;
863 	int  nfields;
864 	int  id, nr;
865 	struct perf_evsel *evsel;
866 };
867 
868 #define METRIC_LEN  35
869 
870 static void new_line_std(void *ctx)
871 {
872 	struct outstate *os = ctx;
873 
874 	os->newline = true;
875 }
876 
877 static void do_new_line_std(struct outstate *os)
878 {
879 	fputc('\n', os->fh);
880 	fputs(os->prefix, os->fh);
881 	aggr_printout(os->evsel, os->id, os->nr);
882 	if (stat_config.aggr_mode == AGGR_NONE)
883 		fprintf(os->fh, "        ");
884 	fprintf(os->fh, "                                                 ");
885 }
886 
887 static void print_metric_std(void *ctx, const char *color, const char *fmt,
888 			     const char *unit, double val)
889 {
890 	struct outstate *os = ctx;
891 	FILE *out = os->fh;
892 	int n;
893 	bool newline = os->newline;
894 
895 	os->newline = false;
896 
897 	if (unit == NULL || fmt == NULL) {
898 		fprintf(out, "%-*s", METRIC_LEN, "");
899 		return;
900 	}
901 
902 	if (newline)
903 		do_new_line_std(os);
904 
905 	n = fprintf(out, " # ");
906 	if (color)
907 		n += color_fprintf(out, color, fmt, val);
908 	else
909 		n += fprintf(out, fmt, val);
910 	fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
911 }
912 
913 static void new_line_csv(void *ctx)
914 {
915 	struct outstate *os = ctx;
916 	int i;
917 
918 	fputc('\n', os->fh);
919 	if (os->prefix)
920 		fprintf(os->fh, "%s%s", os->prefix, csv_sep);
921 	aggr_printout(os->evsel, os->id, os->nr);
922 	for (i = 0; i < os->nfields; i++)
923 		fputs(csv_sep, os->fh);
924 }
925 
926 static void print_metric_csv(void *ctx,
927 			     const char *color __maybe_unused,
928 			     const char *fmt, const char *unit, double val)
929 {
930 	struct outstate *os = ctx;
931 	FILE *out = os->fh;
932 	char buf[64], *vals, *ends;
933 
934 	if (unit == NULL || fmt == NULL) {
935 		fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep);
936 		return;
937 	}
938 	snprintf(buf, sizeof(buf), fmt, val);
939 	ends = vals = ltrim(buf);
940 	while (isdigit(*ends) || *ends == '.')
941 		ends++;
942 	*ends = 0;
943 	while (isspace(*unit))
944 		unit++;
945 	fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit);
946 }
947 
948 #define METRIC_ONLY_LEN 20
949 
950 /* Filter out some columns that don't work well in metrics only mode */
951 
952 static bool valid_only_metric(const char *unit)
953 {
954 	if (!unit)
955 		return false;
956 	if (strstr(unit, "/sec") ||
957 	    strstr(unit, "hz") ||
958 	    strstr(unit, "Hz") ||
959 	    strstr(unit, "CPUs utilized"))
960 		return false;
961 	return true;
962 }
963 
964 static const char *fixunit(char *buf, struct perf_evsel *evsel,
965 			   const char *unit)
966 {
967 	if (!strncmp(unit, "of all", 6)) {
968 		snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel),
969 			 unit);
970 		return buf;
971 	}
972 	return unit;
973 }
974 
975 static void print_metric_only(void *ctx, const char *color, const char *fmt,
976 			      const char *unit, double val)
977 {
978 	struct outstate *os = ctx;
979 	FILE *out = os->fh;
980 	int n;
981 	char buf[1024];
982 	unsigned mlen = METRIC_ONLY_LEN;
983 
984 	if (!valid_only_metric(unit))
985 		return;
986 	unit = fixunit(buf, os->evsel, unit);
987 	if (color)
988 		n = color_fprintf(out, color, fmt, val);
989 	else
990 		n = fprintf(out, fmt, val);
991 	if (n > METRIC_ONLY_LEN)
992 		n = METRIC_ONLY_LEN;
993 	if (mlen < strlen(unit))
994 		mlen = strlen(unit) + 1;
995 	fprintf(out, "%*s", mlen - n, "");
996 }
997 
998 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused,
999 				  const char *fmt,
1000 				  const char *unit, double val)
1001 {
1002 	struct outstate *os = ctx;
1003 	FILE *out = os->fh;
1004 	char buf[64], *vals, *ends;
1005 	char tbuf[1024];
1006 
1007 	if (!valid_only_metric(unit))
1008 		return;
1009 	unit = fixunit(tbuf, os->evsel, unit);
1010 	snprintf(buf, sizeof buf, fmt, val);
1011 	ends = vals = ltrim(buf);
1012 	while (isdigit(*ends) || *ends == '.')
1013 		ends++;
1014 	*ends = 0;
1015 	fprintf(out, "%s%s", vals, csv_sep);
1016 }
1017 
1018 static void new_line_metric(void *ctx __maybe_unused)
1019 {
1020 }
1021 
1022 static void print_metric_header(void *ctx, const char *color __maybe_unused,
1023 				const char *fmt __maybe_unused,
1024 				const char *unit, double val __maybe_unused)
1025 {
1026 	struct outstate *os = ctx;
1027 	char tbuf[1024];
1028 
1029 	if (!valid_only_metric(unit))
1030 		return;
1031 	unit = fixunit(tbuf, os->evsel, unit);
1032 	if (csv_output)
1033 		fprintf(os->fh, "%s%s", unit, csv_sep);
1034 	else
1035 		fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit);
1036 }
1037 
1038 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1039 {
1040 	FILE *output = stat_config.output;
1041 	double msecs = avg / NSEC_PER_MSEC;
1042 	const char *fmt_v, *fmt_n;
1043 	char name[25];
1044 
1045 	fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
1046 	fmt_n = csv_output ? "%s" : "%-25s";
1047 
1048 	aggr_printout(evsel, id, nr);
1049 
1050 	scnprintf(name, sizeof(name), "%s%s",
1051 		  perf_evsel__name(evsel), csv_output ? "" : " (msec)");
1052 
1053 	fprintf(output, fmt_v, msecs, csv_sep);
1054 
1055 	if (csv_output)
1056 		fprintf(output, "%s%s", evsel->unit, csv_sep);
1057 	else
1058 		fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
1059 
1060 	fprintf(output, fmt_n, name);
1061 
1062 	if (evsel->cgrp)
1063 		fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1064 }
1065 
1066 static int first_shadow_cpu(struct perf_evsel *evsel, int id)
1067 {
1068 	int i;
1069 
1070 	if (!aggr_get_id)
1071 		return 0;
1072 
1073 	if (stat_config.aggr_mode == AGGR_NONE)
1074 		return id;
1075 
1076 	if (stat_config.aggr_mode == AGGR_GLOBAL)
1077 		return 0;
1078 
1079 	for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) {
1080 		int cpu2 = perf_evsel__cpus(evsel)->map[i];
1081 
1082 		if (aggr_get_id(evsel_list->cpus, cpu2) == id)
1083 			return cpu2;
1084 	}
1085 	return 0;
1086 }
1087 
1088 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
1089 {
1090 	FILE *output = stat_config.output;
1091 	double sc =  evsel->scale;
1092 	const char *fmt;
1093 
1094 	if (csv_output) {
1095 		fmt = floor(sc) != sc ?  "%.2f%s" : "%.0f%s";
1096 	} else {
1097 		if (big_num)
1098 			fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s";
1099 		else
1100 			fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s";
1101 	}
1102 
1103 	aggr_printout(evsel, id, nr);
1104 
1105 	fprintf(output, fmt, avg, csv_sep);
1106 
1107 	if (evsel->unit)
1108 		fprintf(output, "%-*s%s",
1109 			csv_output ? 0 : unit_width,
1110 			evsel->unit, csv_sep);
1111 
1112 	fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
1113 
1114 	if (evsel->cgrp)
1115 		fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
1116 }
1117 
1118 static void printout(int id, int nr, struct perf_evsel *counter, double uval,
1119 		     char *prefix, u64 run, u64 ena, double noise,
1120 		     struct runtime_stat *st)
1121 {
1122 	struct perf_stat_output_ctx out;
1123 	struct outstate os = {
1124 		.fh = stat_config.output,
1125 		.prefix = prefix ? prefix : "",
1126 		.id = id,
1127 		.nr = nr,
1128 		.evsel = counter,
1129 	};
1130 	print_metric_t pm = print_metric_std;
1131 	void (*nl)(void *);
1132 
1133 	if (metric_only) {
1134 		nl = new_line_metric;
1135 		if (csv_output)
1136 			pm = print_metric_only_csv;
1137 		else
1138 			pm = print_metric_only;
1139 	} else
1140 		nl = new_line_std;
1141 
1142 	if (csv_output && !metric_only) {
1143 		static int aggr_fields[] = {
1144 			[AGGR_GLOBAL] = 0,
1145 			[AGGR_THREAD] = 1,
1146 			[AGGR_NONE] = 1,
1147 			[AGGR_SOCKET] = 2,
1148 			[AGGR_CORE] = 2,
1149 		};
1150 
1151 		pm = print_metric_csv;
1152 		nl = new_line_csv;
1153 		os.nfields = 3;
1154 		os.nfields += aggr_fields[stat_config.aggr_mode];
1155 		if (counter->cgrp)
1156 			os.nfields++;
1157 	}
1158 	if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
1159 		if (metric_only) {
1160 			pm(&os, NULL, "", "", 0);
1161 			return;
1162 		}
1163 		aggr_printout(counter, id, nr);
1164 
1165 		fprintf(stat_config.output, "%*s%s",
1166 			csv_output ? 0 : 18,
1167 			counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
1168 			csv_sep);
1169 
1170 		if (counter->supported)
1171 			print_free_counters_hint = 1;
1172 
1173 		fprintf(stat_config.output, "%-*s%s",
1174 			csv_output ? 0 : unit_width,
1175 			counter->unit, csv_sep);
1176 
1177 		fprintf(stat_config.output, "%*s",
1178 			csv_output ? 0 : -25,
1179 			perf_evsel__name(counter));
1180 
1181 		if (counter->cgrp)
1182 			fprintf(stat_config.output, "%s%s",
1183 				csv_sep, counter->cgrp->name);
1184 
1185 		if (!csv_output)
1186 			pm(&os, NULL, NULL, "", 0);
1187 		print_noise(counter, noise);
1188 		print_running(run, ena);
1189 		if (csv_output)
1190 			pm(&os, NULL, NULL, "", 0);
1191 		return;
1192 	}
1193 
1194 	if (metric_only)
1195 		/* nothing */;
1196 	else if (nsec_counter(counter))
1197 		nsec_printout(id, nr, counter, uval);
1198 	else
1199 		abs_printout(id, nr, counter, uval);
1200 
1201 	out.print_metric = pm;
1202 	out.new_line = nl;
1203 	out.ctx = &os;
1204 	out.force_header = false;
1205 
1206 	if (csv_output && !metric_only) {
1207 		print_noise(counter, noise);
1208 		print_running(run, ena);
1209 	}
1210 
1211 	perf_stat__print_shadow_stats(counter, uval,
1212 				first_shadow_cpu(counter, id),
1213 				&out, &metric_events, st);
1214 	if (!csv_output && !metric_only) {
1215 		print_noise(counter, noise);
1216 		print_running(run, ena);
1217 	}
1218 }
1219 
1220 static void aggr_update_shadow(void)
1221 {
1222 	int cpu, s2, id, s;
1223 	u64 val;
1224 	struct perf_evsel *counter;
1225 
1226 	for (s = 0; s < aggr_map->nr; s++) {
1227 		id = aggr_map->map[s];
1228 		evlist__for_each_entry(evsel_list, counter) {
1229 			val = 0;
1230 			for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1231 				s2 = aggr_get_id(evsel_list->cpus, cpu);
1232 				if (s2 != id)
1233 					continue;
1234 				val += perf_counts(counter->counts, cpu, 0)->val;
1235 			}
1236 			perf_stat__update_shadow_stats(counter, val,
1237 					first_shadow_cpu(counter, id),
1238 					&rt_stat);
1239 		}
1240 	}
1241 }
1242 
1243 static void collect_all_aliases(struct perf_evsel *counter,
1244 			    void (*cb)(struct perf_evsel *counter, void *data,
1245 				       bool first),
1246 			    void *data)
1247 {
1248 	struct perf_evsel *alias;
1249 
1250 	alias = list_prepare_entry(counter, &(evsel_list->entries), node);
1251 	list_for_each_entry_continue (alias, &evsel_list->entries, node) {
1252 		if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) ||
1253 		    alias->scale != counter->scale ||
1254 		    alias->cgrp != counter->cgrp ||
1255 		    strcmp(alias->unit, counter->unit) ||
1256 		    nsec_counter(alias) != nsec_counter(counter))
1257 			break;
1258 		alias->merged_stat = true;
1259 		cb(alias, data, false);
1260 	}
1261 }
1262 
1263 static bool collect_data(struct perf_evsel *counter,
1264 			    void (*cb)(struct perf_evsel *counter, void *data,
1265 				       bool first),
1266 			    void *data)
1267 {
1268 	if (counter->merged_stat)
1269 		return false;
1270 	cb(counter, data, true);
1271 	if (!no_merge && counter->auto_merge_stats)
1272 		collect_all_aliases(counter, cb, data);
1273 	return true;
1274 }
1275 
1276 struct aggr_data {
1277 	u64 ena, run, val;
1278 	int id;
1279 	int nr;
1280 	int cpu;
1281 };
1282 
1283 static void aggr_cb(struct perf_evsel *counter, void *data, bool first)
1284 {
1285 	struct aggr_data *ad = data;
1286 	int cpu, s2;
1287 
1288 	for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1289 		struct perf_counts_values *counts;
1290 
1291 		s2 = aggr_get_id(perf_evsel__cpus(counter), cpu);
1292 		if (s2 != ad->id)
1293 			continue;
1294 		if (first)
1295 			ad->nr++;
1296 		counts = perf_counts(counter->counts, cpu, 0);
1297 		/*
1298 		 * When any result is bad, make them all to give
1299 		 * consistent output in interval mode.
1300 		 */
1301 		if (counts->ena == 0 || counts->run == 0 ||
1302 		    counter->counts->scaled == -1) {
1303 			ad->ena = 0;
1304 			ad->run = 0;
1305 			break;
1306 		}
1307 		ad->val += counts->val;
1308 		ad->ena += counts->ena;
1309 		ad->run += counts->run;
1310 	}
1311 }
1312 
1313 static void print_aggr(char *prefix)
1314 {
1315 	FILE *output = stat_config.output;
1316 	struct perf_evsel *counter;
1317 	int s, id, nr;
1318 	double uval;
1319 	u64 ena, run, val;
1320 	bool first;
1321 
1322 	if (!(aggr_map || aggr_get_id))
1323 		return;
1324 
1325 	aggr_update_shadow();
1326 
1327 	/*
1328 	 * With metric_only everything is on a single line.
1329 	 * Without each counter has its own line.
1330 	 */
1331 	for (s = 0; s < aggr_map->nr; s++) {
1332 		struct aggr_data ad;
1333 		if (prefix && metric_only)
1334 			fprintf(output, "%s", prefix);
1335 
1336 		ad.id = id = aggr_map->map[s];
1337 		first = true;
1338 		evlist__for_each_entry(evsel_list, counter) {
1339 			if (is_duration_time(counter))
1340 				continue;
1341 
1342 			ad.val = ad.ena = ad.run = 0;
1343 			ad.nr = 0;
1344 			if (!collect_data(counter, aggr_cb, &ad))
1345 				continue;
1346 			nr = ad.nr;
1347 			ena = ad.ena;
1348 			run = ad.run;
1349 			val = ad.val;
1350 			if (first && metric_only) {
1351 				first = false;
1352 				aggr_printout(counter, id, nr);
1353 			}
1354 			if (prefix && !metric_only)
1355 				fprintf(output, "%s", prefix);
1356 
1357 			uval = val * counter->scale;
1358 			printout(id, nr, counter, uval, prefix, run, ena, 1.0,
1359 				 &rt_stat);
1360 			if (!metric_only)
1361 				fputc('\n', output);
1362 		}
1363 		if (metric_only)
1364 			fputc('\n', output);
1365 	}
1366 }
1367 
1368 static int cmp_val(const void *a, const void *b)
1369 {
1370 	return ((struct perf_aggr_thread_value *)b)->val -
1371 		((struct perf_aggr_thread_value *)a)->val;
1372 }
1373 
1374 static struct perf_aggr_thread_value *sort_aggr_thread(
1375 					struct perf_evsel *counter,
1376 					int nthreads, int ncpus,
1377 					int *ret)
1378 {
1379 	int cpu, thread, i = 0;
1380 	double uval;
1381 	struct perf_aggr_thread_value *buf;
1382 
1383 	buf = calloc(nthreads, sizeof(struct perf_aggr_thread_value));
1384 	if (!buf)
1385 		return NULL;
1386 
1387 	for (thread = 0; thread < nthreads; thread++) {
1388 		u64 ena = 0, run = 0, val = 0;
1389 
1390 		for (cpu = 0; cpu < ncpus; cpu++) {
1391 			val += perf_counts(counter->counts, cpu, thread)->val;
1392 			ena += perf_counts(counter->counts, cpu, thread)->ena;
1393 			run += perf_counts(counter->counts, cpu, thread)->run;
1394 		}
1395 
1396 		uval = val * counter->scale;
1397 
1398 		/*
1399 		 * Skip value 0 when enabling --per-thread globally,
1400 		 * otherwise too many 0 output.
1401 		 */
1402 		if (uval == 0.0 && target__has_per_thread(&target))
1403 			continue;
1404 
1405 		buf[i].counter = counter;
1406 		buf[i].id = thread;
1407 		buf[i].uval = uval;
1408 		buf[i].val = val;
1409 		buf[i].run = run;
1410 		buf[i].ena = ena;
1411 		i++;
1412 	}
1413 
1414 	qsort(buf, i, sizeof(struct perf_aggr_thread_value), cmp_val);
1415 
1416 	if (ret)
1417 		*ret = i;
1418 
1419 	return buf;
1420 }
1421 
1422 static void print_aggr_thread(struct perf_evsel *counter, char *prefix)
1423 {
1424 	FILE *output = stat_config.output;
1425 	int nthreads = thread_map__nr(counter->threads);
1426 	int ncpus = cpu_map__nr(counter->cpus);
1427 	int thread, sorted_threads, id;
1428 	struct perf_aggr_thread_value *buf;
1429 
1430 	buf = sort_aggr_thread(counter, nthreads, ncpus, &sorted_threads);
1431 	if (!buf) {
1432 		perror("cannot sort aggr thread");
1433 		return;
1434 	}
1435 
1436 	for (thread = 0; thread < sorted_threads; thread++) {
1437 		if (prefix)
1438 			fprintf(output, "%s", prefix);
1439 
1440 		id = buf[thread].id;
1441 		if (stat_config.stats)
1442 			printout(id, 0, buf[thread].counter, buf[thread].uval,
1443 				 prefix, buf[thread].run, buf[thread].ena, 1.0,
1444 				 &stat_config.stats[id]);
1445 		else
1446 			printout(id, 0, buf[thread].counter, buf[thread].uval,
1447 				 prefix, buf[thread].run, buf[thread].ena, 1.0,
1448 				 &rt_stat);
1449 		fputc('\n', output);
1450 	}
1451 
1452 	free(buf);
1453 }
1454 
1455 struct caggr_data {
1456 	double avg, avg_enabled, avg_running;
1457 };
1458 
1459 static void counter_aggr_cb(struct perf_evsel *counter, void *data,
1460 			    bool first __maybe_unused)
1461 {
1462 	struct caggr_data *cd = data;
1463 	struct perf_stat_evsel *ps = counter->stats;
1464 
1465 	cd->avg += avg_stats(&ps->res_stats[0]);
1466 	cd->avg_enabled += avg_stats(&ps->res_stats[1]);
1467 	cd->avg_running += avg_stats(&ps->res_stats[2]);
1468 }
1469 
1470 /*
1471  * Print out the results of a single counter:
1472  * aggregated counts in system-wide mode
1473  */
1474 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
1475 {
1476 	FILE *output = stat_config.output;
1477 	double uval;
1478 	struct caggr_data cd = { .avg = 0.0 };
1479 
1480 	if (!collect_data(counter, counter_aggr_cb, &cd))
1481 		return;
1482 
1483 	if (prefix && !metric_only)
1484 		fprintf(output, "%s", prefix);
1485 
1486 	uval = cd.avg * counter->scale;
1487 	printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled,
1488 		 cd.avg, &rt_stat);
1489 	if (!metric_only)
1490 		fprintf(output, "\n");
1491 }
1492 
1493 static void counter_cb(struct perf_evsel *counter, void *data,
1494 		       bool first __maybe_unused)
1495 {
1496 	struct aggr_data *ad = data;
1497 
1498 	ad->val += perf_counts(counter->counts, ad->cpu, 0)->val;
1499 	ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena;
1500 	ad->run += perf_counts(counter->counts, ad->cpu, 0)->run;
1501 }
1502 
1503 /*
1504  * Print out the results of a single counter:
1505  * does not use aggregated count in system-wide
1506  */
1507 static void print_counter(struct perf_evsel *counter, char *prefix)
1508 {
1509 	FILE *output = stat_config.output;
1510 	u64 ena, run, val;
1511 	double uval;
1512 	int cpu;
1513 
1514 	for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
1515 		struct aggr_data ad = { .cpu = cpu };
1516 
1517 		if (!collect_data(counter, counter_cb, &ad))
1518 			return;
1519 		val = ad.val;
1520 		ena = ad.ena;
1521 		run = ad.run;
1522 
1523 		if (prefix)
1524 			fprintf(output, "%s", prefix);
1525 
1526 		uval = val * counter->scale;
1527 		printout(cpu, 0, counter, uval, prefix, run, ena, 1.0,
1528 			 &rt_stat);
1529 
1530 		fputc('\n', output);
1531 	}
1532 }
1533 
1534 static void print_no_aggr_metric(char *prefix)
1535 {
1536 	int cpu;
1537 	int nrcpus = 0;
1538 	struct perf_evsel *counter;
1539 	u64 ena, run, val;
1540 	double uval;
1541 
1542 	nrcpus = evsel_list->cpus->nr;
1543 	for (cpu = 0; cpu < nrcpus; cpu++) {
1544 		bool first = true;
1545 
1546 		if (prefix)
1547 			fputs(prefix, stat_config.output);
1548 		evlist__for_each_entry(evsel_list, counter) {
1549 			if (is_duration_time(counter))
1550 				continue;
1551 			if (first) {
1552 				aggr_printout(counter, cpu, 0);
1553 				first = false;
1554 			}
1555 			val = perf_counts(counter->counts, cpu, 0)->val;
1556 			ena = perf_counts(counter->counts, cpu, 0)->ena;
1557 			run = perf_counts(counter->counts, cpu, 0)->run;
1558 
1559 			uval = val * counter->scale;
1560 			printout(cpu, 0, counter, uval, prefix, run, ena, 1.0,
1561 				 &rt_stat);
1562 		}
1563 		fputc('\n', stat_config.output);
1564 	}
1565 }
1566 
1567 static int aggr_header_lens[] = {
1568 	[AGGR_CORE] = 18,
1569 	[AGGR_SOCKET] = 12,
1570 	[AGGR_NONE] = 6,
1571 	[AGGR_THREAD] = 24,
1572 	[AGGR_GLOBAL] = 0,
1573 };
1574 
1575 static const char *aggr_header_csv[] = {
1576 	[AGGR_CORE] 	= 	"core,cpus,",
1577 	[AGGR_SOCKET] 	= 	"socket,cpus",
1578 	[AGGR_NONE] 	= 	"cpu,",
1579 	[AGGR_THREAD] 	= 	"comm-pid,",
1580 	[AGGR_GLOBAL] 	=	""
1581 };
1582 
1583 static void print_metric_headers(const char *prefix, bool no_indent)
1584 {
1585 	struct perf_stat_output_ctx out;
1586 	struct perf_evsel *counter;
1587 	struct outstate os = {
1588 		.fh = stat_config.output
1589 	};
1590 
1591 	if (prefix)
1592 		fprintf(stat_config.output, "%s", prefix);
1593 
1594 	if (!csv_output && !no_indent)
1595 		fprintf(stat_config.output, "%*s",
1596 			aggr_header_lens[stat_config.aggr_mode], "");
1597 	if (csv_output) {
1598 		if (stat_config.interval)
1599 			fputs("time,", stat_config.output);
1600 		fputs(aggr_header_csv[stat_config.aggr_mode],
1601 			stat_config.output);
1602 	}
1603 
1604 	/* Print metrics headers only */
1605 	evlist__for_each_entry(evsel_list, counter) {
1606 		if (is_duration_time(counter))
1607 			continue;
1608 		os.evsel = counter;
1609 		out.ctx = &os;
1610 		out.print_metric = print_metric_header;
1611 		out.new_line = new_line_metric;
1612 		out.force_header = true;
1613 		os.evsel = counter;
1614 		perf_stat__print_shadow_stats(counter, 0,
1615 					      0,
1616 					      &out,
1617 					      &metric_events,
1618 					      &rt_stat);
1619 	}
1620 	fputc('\n', stat_config.output);
1621 }
1622 
1623 static void print_interval(char *prefix, struct timespec *ts)
1624 {
1625 	FILE *output = stat_config.output;
1626 	static int num_print_interval;
1627 
1628 	sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep);
1629 
1630 	if (num_print_interval == 0 && !csv_output) {
1631 		switch (stat_config.aggr_mode) {
1632 		case AGGR_SOCKET:
1633 			fprintf(output, "#           time socket cpus");
1634 			if (!metric_only)
1635 				fprintf(output, "             counts %*s events\n", unit_width, "unit");
1636 			break;
1637 		case AGGR_CORE:
1638 			fprintf(output, "#           time core         cpus");
1639 			if (!metric_only)
1640 				fprintf(output, "             counts %*s events\n", unit_width, "unit");
1641 			break;
1642 		case AGGR_NONE:
1643 			fprintf(output, "#           time CPU");
1644 			if (!metric_only)
1645 				fprintf(output, "                counts %*s events\n", unit_width, "unit");
1646 			break;
1647 		case AGGR_THREAD:
1648 			fprintf(output, "#           time             comm-pid");
1649 			if (!metric_only)
1650 				fprintf(output, "                  counts %*s events\n", unit_width, "unit");
1651 			break;
1652 		case AGGR_GLOBAL:
1653 		default:
1654 			fprintf(output, "#           time");
1655 			if (!metric_only)
1656 				fprintf(output, "             counts %*s events\n", unit_width, "unit");
1657 		case AGGR_UNSET:
1658 			break;
1659 		}
1660 	}
1661 
1662 	if (num_print_interval == 0 && metric_only)
1663 		print_metric_headers(" ", true);
1664 	if (++num_print_interval == 25)
1665 		num_print_interval = 0;
1666 }
1667 
1668 static void print_header(int argc, const char **argv)
1669 {
1670 	FILE *output = stat_config.output;
1671 	int i;
1672 
1673 	fflush(stdout);
1674 
1675 	if (!csv_output) {
1676 		fprintf(output, "\n");
1677 		fprintf(output, " Performance counter stats for ");
1678 		if (target.system_wide)
1679 			fprintf(output, "\'system wide");
1680 		else if (target.cpu_list)
1681 			fprintf(output, "\'CPU(s) %s", target.cpu_list);
1682 		else if (!target__has_task(&target)) {
1683 			fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1684 			for (i = 1; argv && (i < argc); i++)
1685 				fprintf(output, " %s", argv[i]);
1686 		} else if (target.pid)
1687 			fprintf(output, "process id \'%s", target.pid);
1688 		else
1689 			fprintf(output, "thread id \'%s", target.tid);
1690 
1691 		fprintf(output, "\'");
1692 		if (run_count > 1)
1693 			fprintf(output, " (%d runs)", run_count);
1694 		fprintf(output, ":\n\n");
1695 	}
1696 }
1697 
1698 static void print_footer(void)
1699 {
1700 	FILE *output = stat_config.output;
1701 	int n;
1702 
1703 	if (!null_run)
1704 		fprintf(output, "\n");
1705 	fprintf(output, " %17.9f seconds time elapsed",
1706 			avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC);
1707 	if (run_count > 1) {
1708 		fprintf(output, "                                        ");
1709 		print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1710 				avg_stats(&walltime_nsecs_stats));
1711 	}
1712 	fprintf(output, "\n\n");
1713 
1714 	if (print_free_counters_hint &&
1715 	    sysctl__read_int("kernel/nmi_watchdog", &n) >= 0 &&
1716 	    n > 0)
1717 		fprintf(output,
1718 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1719 "	echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1720 "	perf stat ...\n"
1721 "	echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1722 }
1723 
1724 static void print_counters(struct timespec *ts, int argc, const char **argv)
1725 {
1726 	int interval = stat_config.interval;
1727 	struct perf_evsel *counter;
1728 	char buf[64], *prefix = NULL;
1729 
1730 	/* Do not print anything if we record to the pipe. */
1731 	if (STAT_RECORD && perf_stat.data.is_pipe)
1732 		return;
1733 
1734 	if (interval)
1735 		print_interval(prefix = buf, ts);
1736 	else
1737 		print_header(argc, argv);
1738 
1739 	if (metric_only) {
1740 		static int num_print_iv;
1741 
1742 		if (num_print_iv == 0 && !interval)
1743 			print_metric_headers(prefix, false);
1744 		if (num_print_iv++ == 25)
1745 			num_print_iv = 0;
1746 		if (stat_config.aggr_mode == AGGR_GLOBAL && prefix)
1747 			fprintf(stat_config.output, "%s", prefix);
1748 	}
1749 
1750 	switch (stat_config.aggr_mode) {
1751 	case AGGR_CORE:
1752 	case AGGR_SOCKET:
1753 		print_aggr(prefix);
1754 		break;
1755 	case AGGR_THREAD:
1756 		evlist__for_each_entry(evsel_list, counter) {
1757 			if (is_duration_time(counter))
1758 				continue;
1759 			print_aggr_thread(counter, prefix);
1760 		}
1761 		break;
1762 	case AGGR_GLOBAL:
1763 		evlist__for_each_entry(evsel_list, counter) {
1764 			if (is_duration_time(counter))
1765 				continue;
1766 			print_counter_aggr(counter, prefix);
1767 		}
1768 		if (metric_only)
1769 			fputc('\n', stat_config.output);
1770 		break;
1771 	case AGGR_NONE:
1772 		if (metric_only)
1773 			print_no_aggr_metric(prefix);
1774 		else {
1775 			evlist__for_each_entry(evsel_list, counter) {
1776 				if (is_duration_time(counter))
1777 					continue;
1778 				print_counter(counter, prefix);
1779 			}
1780 		}
1781 		break;
1782 	case AGGR_UNSET:
1783 	default:
1784 		break;
1785 	}
1786 
1787 	if (!interval && !csv_output)
1788 		print_footer();
1789 
1790 	fflush(stat_config.output);
1791 }
1792 
1793 static volatile int signr = -1;
1794 
1795 static void skip_signal(int signo)
1796 {
1797 	if ((child_pid == -1) || stat_config.interval)
1798 		done = 1;
1799 
1800 	signr = signo;
1801 	/*
1802 	 * render child_pid harmless
1803 	 * won't send SIGTERM to a random
1804 	 * process in case of race condition
1805 	 * and fast PID recycling
1806 	 */
1807 	child_pid = -1;
1808 }
1809 
1810 static void sig_atexit(void)
1811 {
1812 	sigset_t set, oset;
1813 
1814 	/*
1815 	 * avoid race condition with SIGCHLD handler
1816 	 * in skip_signal() which is modifying child_pid
1817 	 * goal is to avoid send SIGTERM to a random
1818 	 * process
1819 	 */
1820 	sigemptyset(&set);
1821 	sigaddset(&set, SIGCHLD);
1822 	sigprocmask(SIG_BLOCK, &set, &oset);
1823 
1824 	if (child_pid != -1)
1825 		kill(child_pid, SIGTERM);
1826 
1827 	sigprocmask(SIG_SETMASK, &oset, NULL);
1828 
1829 	if (signr == -1)
1830 		return;
1831 
1832 	signal(signr, SIG_DFL);
1833 	kill(getpid(), signr);
1834 }
1835 
1836 static int stat__set_big_num(const struct option *opt __maybe_unused,
1837 			     const char *s __maybe_unused, int unset)
1838 {
1839 	big_num_opt = unset ? 0 : 1;
1840 	return 0;
1841 }
1842 
1843 static int enable_metric_only(const struct option *opt __maybe_unused,
1844 			      const char *s __maybe_unused, int unset)
1845 {
1846 	force_metric_only = true;
1847 	metric_only = !unset;
1848 	return 0;
1849 }
1850 
1851 static int parse_metric_groups(const struct option *opt,
1852 			       const char *str,
1853 			       int unset __maybe_unused)
1854 {
1855 	return metricgroup__parse_groups(opt, str, &metric_events);
1856 }
1857 
1858 static const struct option stat_options[] = {
1859 	OPT_BOOLEAN('T', "transaction", &transaction_run,
1860 		    "hardware transaction statistics"),
1861 	OPT_CALLBACK('e', "event", &evsel_list, "event",
1862 		     "event selector. use 'perf list' to list available events",
1863 		     parse_events_option),
1864 	OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1865 		     "event filter", parse_filter),
1866 	OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1867 		    "child tasks do not inherit counters"),
1868 	OPT_STRING('p', "pid", &target.pid, "pid",
1869 		   "stat events on existing process id"),
1870 	OPT_STRING('t', "tid", &target.tid, "tid",
1871 		   "stat events on existing thread id"),
1872 	OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1873 		    "system-wide collection from all CPUs"),
1874 	OPT_BOOLEAN('g', "group", &group,
1875 		    "put the counters into a counter group"),
1876 	OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"),
1877 	OPT_INCR('v', "verbose", &verbose,
1878 		    "be more verbose (show counter open errors, etc)"),
1879 	OPT_INTEGER('r', "repeat", &run_count,
1880 		    "repeat command and print average + stddev (max: 100, forever: 0)"),
1881 	OPT_BOOLEAN('n', "null", &null_run,
1882 		    "null run - dont start any counters"),
1883 	OPT_INCR('d', "detailed", &detailed_run,
1884 		    "detailed run - start a lot of events"),
1885 	OPT_BOOLEAN('S', "sync", &sync_run,
1886 		    "call sync() before starting a run"),
1887 	OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1888 			   "print large numbers with thousands\' separators",
1889 			   stat__set_big_num),
1890 	OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1891 		    "list of cpus to monitor in system-wide"),
1892 	OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode,
1893 		    "disable CPU count aggregation", AGGR_NONE),
1894 	OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"),
1895 	OPT_STRING('x', "field-separator", &csv_sep, "separator",
1896 		   "print counts with custom separator"),
1897 	OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1898 		     "monitor event in cgroup name only", parse_cgroups),
1899 	OPT_STRING('o', "output", &output_name, "file", "output file name"),
1900 	OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1901 	OPT_INTEGER(0, "log-fd", &output_fd,
1902 		    "log output to fd, instead of stderr"),
1903 	OPT_STRING(0, "pre", &pre_cmd, "command",
1904 			"command to run prior to the measured command"),
1905 	OPT_STRING(0, "post", &post_cmd, "command",
1906 			"command to run after to the measured command"),
1907 	OPT_UINTEGER('I', "interval-print", &stat_config.interval,
1908 		    "print counts at regular interval in ms (>= 10)"),
1909 	OPT_INTEGER(0, "interval-count", &stat_config.times,
1910 		    "print counts for fixed number of times"),
1911 	OPT_UINTEGER(0, "timeout", &stat_config.timeout,
1912 		    "stop workload and print counts after a timeout period in ms (>= 10ms)"),
1913 	OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode,
1914 		     "aggregate counts per processor socket", AGGR_SOCKET),
1915 	OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode,
1916 		     "aggregate counts per physical processor core", AGGR_CORE),
1917 	OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode,
1918 		     "aggregate counts per thread", AGGR_THREAD),
1919 	OPT_UINTEGER('D', "delay", &initial_delay,
1920 		     "ms to wait before starting measurement after program start"),
1921 	OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL,
1922 			"Only print computed metrics. No raw values", enable_metric_only),
1923 	OPT_BOOLEAN(0, "topdown", &topdown_run,
1924 			"measure topdown level 1 statistics"),
1925 	OPT_BOOLEAN(0, "smi-cost", &smi_cost,
1926 			"measure SMI cost"),
1927 	OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
1928 		     "monitor specified metrics or metric groups (separated by ,)",
1929 		     parse_metric_groups),
1930 	OPT_END()
1931 };
1932 
1933 static int perf_stat__get_socket(struct cpu_map *map, int cpu)
1934 {
1935 	return cpu_map__get_socket(map, cpu, NULL);
1936 }
1937 
1938 static int perf_stat__get_core(struct cpu_map *map, int cpu)
1939 {
1940 	return cpu_map__get_core(map, cpu, NULL);
1941 }
1942 
1943 static int cpu_map__get_max(struct cpu_map *map)
1944 {
1945 	int i, max = -1;
1946 
1947 	for (i = 0; i < map->nr; i++) {
1948 		if (map->map[i] > max)
1949 			max = map->map[i];
1950 	}
1951 
1952 	return max;
1953 }
1954 
1955 static struct cpu_map *cpus_aggr_map;
1956 
1957 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx)
1958 {
1959 	int cpu;
1960 
1961 	if (idx >= map->nr)
1962 		return -1;
1963 
1964 	cpu = map->map[idx];
1965 
1966 	if (cpus_aggr_map->map[cpu] == -1)
1967 		cpus_aggr_map->map[cpu] = get_id(map, idx);
1968 
1969 	return cpus_aggr_map->map[cpu];
1970 }
1971 
1972 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx)
1973 {
1974 	return perf_stat__get_aggr(perf_stat__get_socket, map, idx);
1975 }
1976 
1977 static int perf_stat__get_core_cached(struct cpu_map *map, int idx)
1978 {
1979 	return perf_stat__get_aggr(perf_stat__get_core, map, idx);
1980 }
1981 
1982 static int perf_stat_init_aggr_mode(void)
1983 {
1984 	int nr;
1985 
1986 	switch (stat_config.aggr_mode) {
1987 	case AGGR_SOCKET:
1988 		if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1989 			perror("cannot build socket map");
1990 			return -1;
1991 		}
1992 		aggr_get_id = perf_stat__get_socket_cached;
1993 		break;
1994 	case AGGR_CORE:
1995 		if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1996 			perror("cannot build core map");
1997 			return -1;
1998 		}
1999 		aggr_get_id = perf_stat__get_core_cached;
2000 		break;
2001 	case AGGR_NONE:
2002 	case AGGR_GLOBAL:
2003 	case AGGR_THREAD:
2004 	case AGGR_UNSET:
2005 	default:
2006 		break;
2007 	}
2008 
2009 	/*
2010 	 * The evsel_list->cpus is the base we operate on,
2011 	 * taking the highest cpu number to be the size of
2012 	 * the aggregation translate cpumap.
2013 	 */
2014 	nr = cpu_map__get_max(evsel_list->cpus);
2015 	cpus_aggr_map = cpu_map__empty_new(nr + 1);
2016 	return cpus_aggr_map ? 0 : -ENOMEM;
2017 }
2018 
2019 static void perf_stat__exit_aggr_mode(void)
2020 {
2021 	cpu_map__put(aggr_map);
2022 	cpu_map__put(cpus_aggr_map);
2023 	aggr_map = NULL;
2024 	cpus_aggr_map = NULL;
2025 }
2026 
2027 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx)
2028 {
2029 	int cpu;
2030 
2031 	if (idx > map->nr)
2032 		return -1;
2033 
2034 	cpu = map->map[idx];
2035 
2036 	if (cpu >= env->nr_cpus_avail)
2037 		return -1;
2038 
2039 	return cpu;
2040 }
2041 
2042 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data)
2043 {
2044 	struct perf_env *env = data;
2045 	int cpu = perf_env__get_cpu(env, map, idx);
2046 
2047 	return cpu == -1 ? -1 : env->cpu[cpu].socket_id;
2048 }
2049 
2050 static int perf_env__get_core(struct cpu_map *map, int idx, void *data)
2051 {
2052 	struct perf_env *env = data;
2053 	int core = -1, cpu = perf_env__get_cpu(env, map, idx);
2054 
2055 	if (cpu != -1) {
2056 		int socket_id = env->cpu[cpu].socket_id;
2057 
2058 		/*
2059 		 * Encode socket in upper 16 bits
2060 		 * core_id is relative to socket, and
2061 		 * we need a global id. So we combine
2062 		 * socket + core id.
2063 		 */
2064 		core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff);
2065 	}
2066 
2067 	return core;
2068 }
2069 
2070 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus,
2071 				      struct cpu_map **sockp)
2072 {
2073 	return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env);
2074 }
2075 
2076 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus,
2077 				    struct cpu_map **corep)
2078 {
2079 	return cpu_map__build_map(cpus, corep, perf_env__get_core, env);
2080 }
2081 
2082 static int perf_stat__get_socket_file(struct cpu_map *map, int idx)
2083 {
2084 	return perf_env__get_socket(map, idx, &perf_stat.session->header.env);
2085 }
2086 
2087 static int perf_stat__get_core_file(struct cpu_map *map, int idx)
2088 {
2089 	return perf_env__get_core(map, idx, &perf_stat.session->header.env);
2090 }
2091 
2092 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
2093 {
2094 	struct perf_env *env = &st->session->header.env;
2095 
2096 	switch (stat_config.aggr_mode) {
2097 	case AGGR_SOCKET:
2098 		if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) {
2099 			perror("cannot build socket map");
2100 			return -1;
2101 		}
2102 		aggr_get_id = perf_stat__get_socket_file;
2103 		break;
2104 	case AGGR_CORE:
2105 		if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) {
2106 			perror("cannot build core map");
2107 			return -1;
2108 		}
2109 		aggr_get_id = perf_stat__get_core_file;
2110 		break;
2111 	case AGGR_NONE:
2112 	case AGGR_GLOBAL:
2113 	case AGGR_THREAD:
2114 	case AGGR_UNSET:
2115 	default:
2116 		break;
2117 	}
2118 
2119 	return 0;
2120 }
2121 
2122 static int topdown_filter_events(const char **attr, char **str, bool use_group)
2123 {
2124 	int off = 0;
2125 	int i;
2126 	int len = 0;
2127 	char *s;
2128 
2129 	for (i = 0; attr[i]; i++) {
2130 		if (pmu_have_event("cpu", attr[i])) {
2131 			len += strlen(attr[i]) + 1;
2132 			attr[i - off] = attr[i];
2133 		} else
2134 			off++;
2135 	}
2136 	attr[i - off] = NULL;
2137 
2138 	*str = malloc(len + 1 + 2);
2139 	if (!*str)
2140 		return -1;
2141 	s = *str;
2142 	if (i - off == 0) {
2143 		*s = 0;
2144 		return 0;
2145 	}
2146 	if (use_group)
2147 		*s++ = '{';
2148 	for (i = 0; attr[i]; i++) {
2149 		strcpy(s, attr[i]);
2150 		s += strlen(s);
2151 		*s++ = ',';
2152 	}
2153 	if (use_group) {
2154 		s[-1] = '}';
2155 		*s = 0;
2156 	} else
2157 		s[-1] = 0;
2158 	return 0;
2159 }
2160 
2161 __weak bool arch_topdown_check_group(bool *warn)
2162 {
2163 	*warn = false;
2164 	return false;
2165 }
2166 
2167 __weak void arch_topdown_group_warn(void)
2168 {
2169 }
2170 
2171 /*
2172  * Add default attributes, if there were no attributes specified or
2173  * if -d/--detailed, -d -d or -d -d -d is used:
2174  */
2175 static int add_default_attributes(void)
2176 {
2177 	int err;
2178 	struct perf_event_attr default_attrs0[] = {
2179 
2180   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK		},
2181   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES	},
2182   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS		},
2183   { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS		},
2184 
2185   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES		},
2186 };
2187 	struct perf_event_attr frontend_attrs[] = {
2188   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND	},
2189 };
2190 	struct perf_event_attr backend_attrs[] = {
2191   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND	},
2192 };
2193 	struct perf_event_attr default_attrs1[] = {
2194   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS		},
2195   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS	},
2196   { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES		},
2197 
2198 };
2199 
2200 /*
2201  * Detailed stats (-d), covering the L1 and last level data caches:
2202  */
2203 	struct perf_event_attr detailed_attrs[] = {
2204 
2205   { .type = PERF_TYPE_HW_CACHE,
2206     .config =
2207 	 PERF_COUNT_HW_CACHE_L1D		<<  0  |
2208 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2209 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
2210 
2211   { .type = PERF_TYPE_HW_CACHE,
2212     .config =
2213 	 PERF_COUNT_HW_CACHE_L1D		<<  0  |
2214 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2215 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
2216 
2217   { .type = PERF_TYPE_HW_CACHE,
2218     .config =
2219 	 PERF_COUNT_HW_CACHE_LL			<<  0  |
2220 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2221 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
2222 
2223   { .type = PERF_TYPE_HW_CACHE,
2224     .config =
2225 	 PERF_COUNT_HW_CACHE_LL			<<  0  |
2226 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2227 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
2228 };
2229 
2230 /*
2231  * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
2232  */
2233 	struct perf_event_attr very_detailed_attrs[] = {
2234 
2235   { .type = PERF_TYPE_HW_CACHE,
2236     .config =
2237 	 PERF_COUNT_HW_CACHE_L1I		<<  0  |
2238 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2239 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
2240 
2241   { .type = PERF_TYPE_HW_CACHE,
2242     .config =
2243 	 PERF_COUNT_HW_CACHE_L1I		<<  0  |
2244 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2245 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
2246 
2247   { .type = PERF_TYPE_HW_CACHE,
2248     .config =
2249 	 PERF_COUNT_HW_CACHE_DTLB		<<  0  |
2250 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2251 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
2252 
2253   { .type = PERF_TYPE_HW_CACHE,
2254     .config =
2255 	 PERF_COUNT_HW_CACHE_DTLB		<<  0  |
2256 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2257 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
2258 
2259   { .type = PERF_TYPE_HW_CACHE,
2260     .config =
2261 	 PERF_COUNT_HW_CACHE_ITLB		<<  0  |
2262 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2263 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
2264 
2265   { .type = PERF_TYPE_HW_CACHE,
2266     .config =
2267 	 PERF_COUNT_HW_CACHE_ITLB		<<  0  |
2268 	(PERF_COUNT_HW_CACHE_OP_READ		<<  8) |
2269 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
2270 
2271 };
2272 
2273 /*
2274  * Very, very detailed stats (-d -d -d), adding prefetch events:
2275  */
2276 	struct perf_event_attr very_very_detailed_attrs[] = {
2277 
2278   { .type = PERF_TYPE_HW_CACHE,
2279     .config =
2280 	 PERF_COUNT_HW_CACHE_L1D		<<  0  |
2281 	(PERF_COUNT_HW_CACHE_OP_PREFETCH	<<  8) |
2282 	(PERF_COUNT_HW_CACHE_RESULT_ACCESS	<< 16)				},
2283 
2284   { .type = PERF_TYPE_HW_CACHE,
2285     .config =
2286 	 PERF_COUNT_HW_CACHE_L1D		<<  0  |
2287 	(PERF_COUNT_HW_CACHE_OP_PREFETCH	<<  8) |
2288 	(PERF_COUNT_HW_CACHE_RESULT_MISS	<< 16)				},
2289 };
2290 
2291 	/* Set attrs if no event is selected and !null_run: */
2292 	if (null_run)
2293 		return 0;
2294 
2295 	if (transaction_run) {
2296 		if (pmu_have_event("cpu", "cycles-ct") &&
2297 		    pmu_have_event("cpu", "el-start"))
2298 			err = parse_events(evsel_list, transaction_attrs, NULL);
2299 		else
2300 			err = parse_events(evsel_list, transaction_limited_attrs, NULL);
2301 		if (err) {
2302 			fprintf(stderr, "Cannot set up transaction events\n");
2303 			return -1;
2304 		}
2305 		return 0;
2306 	}
2307 
2308 	if (smi_cost) {
2309 		int smi;
2310 
2311 		if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
2312 			fprintf(stderr, "freeze_on_smi is not supported.\n");
2313 			return -1;
2314 		}
2315 
2316 		if (!smi) {
2317 			if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
2318 				fprintf(stderr, "Failed to set freeze_on_smi.\n");
2319 				return -1;
2320 			}
2321 			smi_reset = true;
2322 		}
2323 
2324 		if (pmu_have_event("msr", "aperf") &&
2325 		    pmu_have_event("msr", "smi")) {
2326 			if (!force_metric_only)
2327 				metric_only = true;
2328 			err = parse_events(evsel_list, smi_cost_attrs, NULL);
2329 		} else {
2330 			fprintf(stderr, "To measure SMI cost, it needs "
2331 				"msr/aperf/, msr/smi/ and cpu/cycles/ support\n");
2332 			return -1;
2333 		}
2334 		if (err) {
2335 			fprintf(stderr, "Cannot set up SMI cost events\n");
2336 			return -1;
2337 		}
2338 		return 0;
2339 	}
2340 
2341 	if (topdown_run) {
2342 		char *str = NULL;
2343 		bool warn = false;
2344 
2345 		if (stat_config.aggr_mode != AGGR_GLOBAL &&
2346 		    stat_config.aggr_mode != AGGR_CORE) {
2347 			pr_err("top down event configuration requires --per-core mode\n");
2348 			return -1;
2349 		}
2350 		stat_config.aggr_mode = AGGR_CORE;
2351 		if (nr_cgroups || !target__has_cpu(&target)) {
2352 			pr_err("top down event configuration requires system-wide mode (-a)\n");
2353 			return -1;
2354 		}
2355 
2356 		if (!force_metric_only)
2357 			metric_only = true;
2358 		if (topdown_filter_events(topdown_attrs, &str,
2359 				arch_topdown_check_group(&warn)) < 0) {
2360 			pr_err("Out of memory\n");
2361 			return -1;
2362 		}
2363 		if (topdown_attrs[0] && str) {
2364 			if (warn)
2365 				arch_topdown_group_warn();
2366 			err = parse_events(evsel_list, str, NULL);
2367 			if (err) {
2368 				fprintf(stderr,
2369 					"Cannot set up top down events %s: %d\n",
2370 					str, err);
2371 				free(str);
2372 				return -1;
2373 			}
2374 		} else {
2375 			fprintf(stderr, "System does not support topdown\n");
2376 			return -1;
2377 		}
2378 		free(str);
2379 	}
2380 
2381 	if (!evsel_list->nr_entries) {
2382 		if (target__has_cpu(&target))
2383 			default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK;
2384 
2385 		if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0)
2386 			return -1;
2387 		if (pmu_have_event("cpu", "stalled-cycles-frontend")) {
2388 			if (perf_evlist__add_default_attrs(evsel_list,
2389 						frontend_attrs) < 0)
2390 				return -1;
2391 		}
2392 		if (pmu_have_event("cpu", "stalled-cycles-backend")) {
2393 			if (perf_evlist__add_default_attrs(evsel_list,
2394 						backend_attrs) < 0)
2395 				return -1;
2396 		}
2397 		if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0)
2398 			return -1;
2399 	}
2400 
2401 	/* Detailed events get appended to the event list: */
2402 
2403 	if (detailed_run <  1)
2404 		return 0;
2405 
2406 	/* Append detailed run extra attributes: */
2407 	if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
2408 		return -1;
2409 
2410 	if (detailed_run < 2)
2411 		return 0;
2412 
2413 	/* Append very detailed run extra attributes: */
2414 	if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
2415 		return -1;
2416 
2417 	if (detailed_run < 3)
2418 		return 0;
2419 
2420 	/* Append very, very detailed run extra attributes: */
2421 	return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
2422 }
2423 
2424 static const char * const stat_record_usage[] = {
2425 	"perf stat record [<options>]",
2426 	NULL,
2427 };
2428 
2429 static void init_features(struct perf_session *session)
2430 {
2431 	int feat;
2432 
2433 	for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2434 		perf_header__set_feat(&session->header, feat);
2435 
2436 	perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2437 	perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2438 	perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2439 	perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2440 }
2441 
2442 static int __cmd_record(int argc, const char **argv)
2443 {
2444 	struct perf_session *session;
2445 	struct perf_data *data = &perf_stat.data;
2446 
2447 	argc = parse_options(argc, argv, stat_options, stat_record_usage,
2448 			     PARSE_OPT_STOP_AT_NON_OPTION);
2449 
2450 	if (output_name)
2451 		data->file.path = output_name;
2452 
2453 	if (run_count != 1 || forever) {
2454 		pr_err("Cannot use -r option with perf stat record.\n");
2455 		return -1;
2456 	}
2457 
2458 	session = perf_session__new(data, false, NULL);
2459 	if (session == NULL) {
2460 		pr_err("Perf session creation failed.\n");
2461 		return -1;
2462 	}
2463 
2464 	init_features(session);
2465 
2466 	session->evlist   = evsel_list;
2467 	perf_stat.session = session;
2468 	perf_stat.record  = true;
2469 	return argc;
2470 }
2471 
2472 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2473 				    union perf_event *event,
2474 				    struct perf_session *session)
2475 {
2476 	struct stat_round_event *stat_round = &event->stat_round;
2477 	struct perf_evsel *counter;
2478 	struct timespec tsh, *ts = NULL;
2479 	const char **argv = session->header.env.cmdline_argv;
2480 	int argc = session->header.env.nr_cmdline;
2481 
2482 	evlist__for_each_entry(evsel_list, counter)
2483 		perf_stat_process_counter(&stat_config, counter);
2484 
2485 	if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2486 		update_stats(&walltime_nsecs_stats, stat_round->time);
2487 
2488 	if (stat_config.interval && stat_round->time) {
2489 		tsh.tv_sec  = stat_round->time / NSEC_PER_SEC;
2490 		tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2491 		ts = &tsh;
2492 	}
2493 
2494 	print_counters(ts, argc, argv);
2495 	return 0;
2496 }
2497 
2498 static
2499 int process_stat_config_event(struct perf_tool *tool,
2500 			      union perf_event *event,
2501 			      struct perf_session *session __maybe_unused)
2502 {
2503 	struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2504 
2505 	perf_event__read_stat_config(&stat_config, &event->stat_config);
2506 
2507 	if (cpu_map__empty(st->cpus)) {
2508 		if (st->aggr_mode != AGGR_UNSET)
2509 			pr_warning("warning: processing task data, aggregation mode not set\n");
2510 		return 0;
2511 	}
2512 
2513 	if (st->aggr_mode != AGGR_UNSET)
2514 		stat_config.aggr_mode = st->aggr_mode;
2515 
2516 	if (perf_stat.data.is_pipe)
2517 		perf_stat_init_aggr_mode();
2518 	else
2519 		perf_stat_init_aggr_mode_file(st);
2520 
2521 	return 0;
2522 }
2523 
2524 static int set_maps(struct perf_stat *st)
2525 {
2526 	if (!st->cpus || !st->threads)
2527 		return 0;
2528 
2529 	if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2530 		return -EINVAL;
2531 
2532 	perf_evlist__set_maps(evsel_list, st->cpus, st->threads);
2533 
2534 	if (perf_evlist__alloc_stats(evsel_list, true))
2535 		return -ENOMEM;
2536 
2537 	st->maps_allocated = true;
2538 	return 0;
2539 }
2540 
2541 static
2542 int process_thread_map_event(struct perf_tool *tool,
2543 			     union perf_event *event,
2544 			     struct perf_session *session __maybe_unused)
2545 {
2546 	struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2547 
2548 	if (st->threads) {
2549 		pr_warning("Extra thread map event, ignoring.\n");
2550 		return 0;
2551 	}
2552 
2553 	st->threads = thread_map__new_event(&event->thread_map);
2554 	if (!st->threads)
2555 		return -ENOMEM;
2556 
2557 	return set_maps(st);
2558 }
2559 
2560 static
2561 int process_cpu_map_event(struct perf_tool *tool,
2562 			  union perf_event *event,
2563 			  struct perf_session *session __maybe_unused)
2564 {
2565 	struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2566 	struct cpu_map *cpus;
2567 
2568 	if (st->cpus) {
2569 		pr_warning("Extra cpu map event, ignoring.\n");
2570 		return 0;
2571 	}
2572 
2573 	cpus = cpu_map__new_data(&event->cpu_map.data);
2574 	if (!cpus)
2575 		return -ENOMEM;
2576 
2577 	st->cpus = cpus;
2578 	return set_maps(st);
2579 }
2580 
2581 static int runtime_stat_new(struct perf_stat_config *config, int nthreads)
2582 {
2583 	int i;
2584 
2585 	config->stats = calloc(nthreads, sizeof(struct runtime_stat));
2586 	if (!config->stats)
2587 		return -1;
2588 
2589 	config->stats_num = nthreads;
2590 
2591 	for (i = 0; i < nthreads; i++)
2592 		runtime_stat__init(&config->stats[i]);
2593 
2594 	return 0;
2595 }
2596 
2597 static void runtime_stat_delete(struct perf_stat_config *config)
2598 {
2599 	int i;
2600 
2601 	if (!config->stats)
2602 		return;
2603 
2604 	for (i = 0; i < config->stats_num; i++)
2605 		runtime_stat__exit(&config->stats[i]);
2606 
2607 	free(config->stats);
2608 }
2609 
2610 static const char * const stat_report_usage[] = {
2611 	"perf stat report [<options>]",
2612 	NULL,
2613 };
2614 
2615 static struct perf_stat perf_stat = {
2616 	.tool = {
2617 		.attr		= perf_event__process_attr,
2618 		.event_update	= perf_event__process_event_update,
2619 		.thread_map	= process_thread_map_event,
2620 		.cpu_map	= process_cpu_map_event,
2621 		.stat_config	= process_stat_config_event,
2622 		.stat		= perf_event__process_stat_event,
2623 		.stat_round	= process_stat_round_event,
2624 	},
2625 	.aggr_mode = AGGR_UNSET,
2626 };
2627 
2628 static int __cmd_report(int argc, const char **argv)
2629 {
2630 	struct perf_session *session;
2631 	const struct option options[] = {
2632 	OPT_STRING('i', "input", &input_name, "file", "input file name"),
2633 	OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2634 		     "aggregate counts per processor socket", AGGR_SOCKET),
2635 	OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2636 		     "aggregate counts per physical processor core", AGGR_CORE),
2637 	OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2638 		     "disable CPU count aggregation", AGGR_NONE),
2639 	OPT_END()
2640 	};
2641 	struct stat st;
2642 	int ret;
2643 
2644 	argc = parse_options(argc, argv, options, stat_report_usage, 0);
2645 
2646 	if (!input_name || !strlen(input_name)) {
2647 		if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2648 			input_name = "-";
2649 		else
2650 			input_name = "perf.data";
2651 	}
2652 
2653 	perf_stat.data.file.path = input_name;
2654 	perf_stat.data.mode      = PERF_DATA_MODE_READ;
2655 
2656 	session = perf_session__new(&perf_stat.data, false, &perf_stat.tool);
2657 	if (session == NULL)
2658 		return -1;
2659 
2660 	perf_stat.session  = session;
2661 	stat_config.output = stderr;
2662 	evsel_list         = session->evlist;
2663 
2664 	ret = perf_session__process_events(session);
2665 	if (ret)
2666 		return ret;
2667 
2668 	perf_session__delete(session);
2669 	return 0;
2670 }
2671 
2672 static void setup_system_wide(int forks)
2673 {
2674 	/*
2675 	 * Make system wide (-a) the default target if
2676 	 * no target was specified and one of following
2677 	 * conditions is met:
2678 	 *
2679 	 *   - there's no workload specified
2680 	 *   - there is workload specified but all requested
2681 	 *     events are system wide events
2682 	 */
2683 	if (!target__none(&target))
2684 		return;
2685 
2686 	if (!forks)
2687 		target.system_wide = true;
2688 	else {
2689 		struct perf_evsel *counter;
2690 
2691 		evlist__for_each_entry(evsel_list, counter) {
2692 			if (!counter->system_wide)
2693 				return;
2694 		}
2695 
2696 		if (evsel_list->nr_entries)
2697 			target.system_wide = true;
2698 	}
2699 }
2700 
2701 int cmd_stat(int argc, const char **argv)
2702 {
2703 	const char * const stat_usage[] = {
2704 		"perf stat [<options>] [<command>]",
2705 		NULL
2706 	};
2707 	int status = -EINVAL, run_idx;
2708 	const char *mode;
2709 	FILE *output = stderr;
2710 	unsigned int interval, timeout;
2711 	const char * const stat_subcommands[] = { "record", "report" };
2712 
2713 	setlocale(LC_ALL, "");
2714 
2715 	evsel_list = perf_evlist__new();
2716 	if (evsel_list == NULL)
2717 		return -ENOMEM;
2718 
2719 	parse_events__shrink_config_terms();
2720 	argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2721 					(const char **) stat_usage,
2722 					PARSE_OPT_STOP_AT_NON_OPTION);
2723 	perf_stat__collect_metric_expr(evsel_list);
2724 	perf_stat__init_shadow_stats();
2725 
2726 	if (csv_sep) {
2727 		csv_output = true;
2728 		if (!strcmp(csv_sep, "\\t"))
2729 			csv_sep = "\t";
2730 	} else
2731 		csv_sep = DEFAULT_SEPARATOR;
2732 
2733 	if (argc && !strncmp(argv[0], "rec", 3)) {
2734 		argc = __cmd_record(argc, argv);
2735 		if (argc < 0)
2736 			return -1;
2737 	} else if (argc && !strncmp(argv[0], "rep", 3))
2738 		return __cmd_report(argc, argv);
2739 
2740 	interval = stat_config.interval;
2741 	timeout = stat_config.timeout;
2742 
2743 	/*
2744 	 * For record command the -o is already taken care of.
2745 	 */
2746 	if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2747 		output = NULL;
2748 
2749 	if (output_name && output_fd) {
2750 		fprintf(stderr, "cannot use both --output and --log-fd\n");
2751 		parse_options_usage(stat_usage, stat_options, "o", 1);
2752 		parse_options_usage(NULL, stat_options, "log-fd", 0);
2753 		goto out;
2754 	}
2755 
2756 	if (metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2757 		fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2758 		goto out;
2759 	}
2760 
2761 	if (metric_only && run_count > 1) {
2762 		fprintf(stderr, "--metric-only is not supported with -r\n");
2763 		goto out;
2764 	}
2765 
2766 	if (output_fd < 0) {
2767 		fprintf(stderr, "argument to --log-fd must be a > 0\n");
2768 		parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2769 		goto out;
2770 	}
2771 
2772 	if (!output) {
2773 		struct timespec tm;
2774 		mode = append_file ? "a" : "w";
2775 
2776 		output = fopen(output_name, mode);
2777 		if (!output) {
2778 			perror("failed to create output file");
2779 			return -1;
2780 		}
2781 		clock_gettime(CLOCK_REALTIME, &tm);
2782 		fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2783 	} else if (output_fd > 0) {
2784 		mode = append_file ? "a" : "w";
2785 		output = fdopen(output_fd, mode);
2786 		if (!output) {
2787 			perror("Failed opening logfd");
2788 			return -errno;
2789 		}
2790 	}
2791 
2792 	stat_config.output = output;
2793 
2794 	/*
2795 	 * let the spreadsheet do the pretty-printing
2796 	 */
2797 	if (csv_output) {
2798 		/* User explicitly passed -B? */
2799 		if (big_num_opt == 1) {
2800 			fprintf(stderr, "-B option not supported with -x\n");
2801 			parse_options_usage(stat_usage, stat_options, "B", 1);
2802 			parse_options_usage(NULL, stat_options, "x", 1);
2803 			goto out;
2804 		} else /* Nope, so disable big number formatting */
2805 			big_num = false;
2806 	} else if (big_num_opt == 0) /* User passed --no-big-num */
2807 		big_num = false;
2808 
2809 	setup_system_wide(argc);
2810 
2811 	if (run_count < 0) {
2812 		pr_err("Run count must be a positive number\n");
2813 		parse_options_usage(stat_usage, stat_options, "r", 1);
2814 		goto out;
2815 	} else if (run_count == 0) {
2816 		forever = true;
2817 		run_count = 1;
2818 	}
2819 
2820 	if ((stat_config.aggr_mode == AGGR_THREAD) &&
2821 		!target__has_task(&target)) {
2822 		if (!target.system_wide || target.cpu_list) {
2823 			fprintf(stderr, "The --per-thread option is only "
2824 				"available when monitoring via -p -t -a "
2825 				"options or only --per-thread.\n");
2826 			parse_options_usage(NULL, stat_options, "p", 1);
2827 			parse_options_usage(NULL, stat_options, "t", 1);
2828 			goto out;
2829 		}
2830 	}
2831 
2832 	/*
2833 	 * no_aggr, cgroup are for system-wide only
2834 	 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2835 	 */
2836 	if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2837 	      stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) &&
2838 	    !target__has_cpu(&target)) {
2839 		fprintf(stderr, "both cgroup and no-aggregation "
2840 			"modes only available in system-wide mode\n");
2841 
2842 		parse_options_usage(stat_usage, stat_options, "G", 1);
2843 		parse_options_usage(NULL, stat_options, "A", 1);
2844 		parse_options_usage(NULL, stat_options, "a", 1);
2845 		goto out;
2846 	}
2847 
2848 	if (add_default_attributes())
2849 		goto out;
2850 
2851 	target__validate(&target);
2852 
2853 	if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2854 		target.per_thread = true;
2855 
2856 	if (perf_evlist__create_maps(evsel_list, &target) < 0) {
2857 		if (target__has_task(&target)) {
2858 			pr_err("Problems finding threads of monitor\n");
2859 			parse_options_usage(stat_usage, stat_options, "p", 1);
2860 			parse_options_usage(NULL, stat_options, "t", 1);
2861 		} else if (target__has_cpu(&target)) {
2862 			perror("failed to parse CPUs map");
2863 			parse_options_usage(stat_usage, stat_options, "C", 1);
2864 			parse_options_usage(NULL, stat_options, "a", 1);
2865 		}
2866 		goto out;
2867 	}
2868 
2869 	/*
2870 	 * Initialize thread_map with comm names,
2871 	 * so we could print it out on output.
2872 	 */
2873 	if (stat_config.aggr_mode == AGGR_THREAD) {
2874 		thread_map__read_comms(evsel_list->threads);
2875 		if (target.system_wide) {
2876 			if (runtime_stat_new(&stat_config,
2877 				thread_map__nr(evsel_list->threads))) {
2878 				goto out;
2879 			}
2880 		}
2881 	}
2882 
2883 	if (interval && interval < 100) {
2884 		if (interval < 10) {
2885 			pr_err("print interval must be >= 10ms\n");
2886 			parse_options_usage(stat_usage, stat_options, "I", 1);
2887 			goto out;
2888 		} else
2889 			pr_warning("print interval < 100ms. "
2890 				   "The overhead percentage could be high in some cases. "
2891 				   "Please proceed with caution.\n");
2892 	}
2893 
2894 	if (stat_config.times && interval)
2895 		interval_count = true;
2896 	else if (stat_config.times && !interval) {
2897 		pr_err("interval-count option should be used together with "
2898 				"interval-print.\n");
2899 		parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2900 		parse_options_usage(stat_usage, stat_options, "I", 1);
2901 		goto out;
2902 	}
2903 
2904 	if (timeout && timeout < 100) {
2905 		if (timeout < 10) {
2906 			pr_err("timeout must be >= 10ms.\n");
2907 			parse_options_usage(stat_usage, stat_options, "timeout", 0);
2908 			goto out;
2909 		} else
2910 			pr_warning("timeout < 100ms. "
2911 				   "The overhead percentage could be high in some cases. "
2912 				   "Please proceed with caution.\n");
2913 	}
2914 	if (timeout && interval) {
2915 		pr_err("timeout option is not supported with interval-print.\n");
2916 		parse_options_usage(stat_usage, stat_options, "timeout", 0);
2917 		parse_options_usage(stat_usage, stat_options, "I", 1);
2918 		goto out;
2919 	}
2920 
2921 	if (perf_evlist__alloc_stats(evsel_list, interval))
2922 		goto out;
2923 
2924 	if (perf_stat_init_aggr_mode())
2925 		goto out;
2926 
2927 	/*
2928 	 * We dont want to block the signals - that would cause
2929 	 * child tasks to inherit that and Ctrl-C would not work.
2930 	 * What we want is for Ctrl-C to work in the exec()-ed
2931 	 * task, but being ignored by perf stat itself:
2932 	 */
2933 	atexit(sig_atexit);
2934 	if (!forever)
2935 		signal(SIGINT,  skip_signal);
2936 	signal(SIGCHLD, skip_signal);
2937 	signal(SIGALRM, skip_signal);
2938 	signal(SIGABRT, skip_signal);
2939 
2940 	status = 0;
2941 	for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
2942 		if (run_count != 1 && verbose > 0)
2943 			fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2944 				run_idx + 1);
2945 
2946 		status = run_perf_stat(argc, argv);
2947 		if (forever && status != -1) {
2948 			print_counters(NULL, argc, argv);
2949 			perf_stat__reset_stats();
2950 		}
2951 	}
2952 
2953 	if (!forever && status != -1 && !interval)
2954 		print_counters(NULL, argc, argv);
2955 
2956 	if (STAT_RECORD) {
2957 		/*
2958 		 * We synthesize the kernel mmap record just so that older tools
2959 		 * don't emit warnings about not being able to resolve symbols
2960 		 * due to /proc/sys/kernel/kptr_restrict settings and instear provide
2961 		 * a saner message about no samples being in the perf.data file.
2962 		 *
2963 		 * This also serves to suppress a warning about f_header.data.size == 0
2964 		 * in header.c at the moment 'perf stat record' gets introduced, which
2965 		 * is not really needed once we start adding the stat specific PERF_RECORD_
2966 		 * records, but the need to suppress the kptr_restrict messages in older
2967 		 * tools remain  -acme
2968 		 */
2969 		int fd = perf_data__fd(&perf_stat.data);
2970 		int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
2971 							     process_synthesized_event,
2972 							     &perf_stat.session->machines.host);
2973 		if (err) {
2974 			pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
2975 				   "older tools may produce warnings about this file\n.");
2976 		}
2977 
2978 		if (!interval) {
2979 			if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL))
2980 				pr_err("failed to write stat round event\n");
2981 		}
2982 
2983 		if (!perf_stat.data.is_pipe) {
2984 			perf_stat.session->header.data_size += perf_stat.bytes_written;
2985 			perf_session__write_header(perf_stat.session, evsel_list, fd, true);
2986 		}
2987 
2988 		perf_session__delete(perf_stat.session);
2989 	}
2990 
2991 	perf_stat__exit_aggr_mode();
2992 	perf_evlist__free_stats(evsel_list);
2993 out:
2994 	if (smi_cost && smi_reset)
2995 		sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
2996 
2997 	perf_evlist__delete(evsel_list);
2998 
2999 	runtime_stat_delete(&stat_config);
3000 
3001 	return status;
3002 }
3003