xref: /linux/tools/perf/util/stat-display.c (revision 325aabebbbc0520f95db3974d46e13a081cf6c28)
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <inttypes.h>
4 #include <linux/string.h>
5 #include <linux/time64.h>
6 #include <math.h>
7 #include <perf/cpumap.h>
8 #include "color.h"
9 #include "counts.h"
10 #include "debug.h"
11 #include "evlist.h"
12 #include "evsel.h"
13 #include "stat.h"
14 #include "top.h"
15 #include "thread_map.h"
16 #include "cpumap.h"
17 #include "string2.h"
18 #include <linux/ctype.h>
19 #include "cgroup.h"
20 #include <api/fs/fs.h>
21 #include "util.h"
22 #include "iostat.h"
23 #include "pmu.h"
24 #include "pmus.h"
25 #include "tool_pmu.h"
26 
27 #define CNTR_NOT_SUPPORTED	"<not supported>"
28 #define CNTR_NOT_COUNTED	"<not counted>"
29 
30 #define MGROUP_LEN   50
31 #define METRIC_LEN   38
32 #define EVNAME_LEN   32
33 #define COUNTS_LEN   18
34 #define INTERVAL_LEN 16
35 #define CGROUP_LEN   16
36 #define COMM_LEN     16
37 #define PID_LEN       7
38 #define CPUS_LEN      4
39 
40 static int aggr_header_lens[] = {
41 	[AGGR_CORE] 	= 18,
42 	[AGGR_CACHE]	= 22,
43 	[AGGR_CLUSTER]	= 20,
44 	[AGGR_DIE] 	= 12,
45 	[AGGR_SOCKET] 	= 6,
46 	[AGGR_NODE] 	= 6,
47 	[AGGR_NONE] 	= 6,
48 	[AGGR_THREAD] 	= 16,
49 	[AGGR_GLOBAL] 	= 0,
50 };
51 
52 static const char *aggr_header_csv[] = {
53 	[AGGR_CORE]	=	"core,ctrs,",
54 	[AGGR_CACHE]	=	"cache,ctrs,",
55 	[AGGR_CLUSTER]	=	"cluster,ctrs,",
56 	[AGGR_DIE]	=	"die,ctrs,",
57 	[AGGR_SOCKET]	=	"socket,ctrs,",
58 	[AGGR_NONE]	=	"cpu,",
59 	[AGGR_THREAD]	=	"comm-pid,",
60 	[AGGR_NODE]	=	"node,",
61 	[AGGR_GLOBAL]	=	""
62 };
63 
64 static const char *aggr_header_std[] = {
65 	[AGGR_CORE] 	= 	"core",
66 	[AGGR_CACHE] 	= 	"cache",
67 	[AGGR_CLUSTER]	= 	"cluster",
68 	[AGGR_DIE] 	= 	"die",
69 	[AGGR_SOCKET] 	= 	"socket",
70 	[AGGR_NONE] 	= 	"cpu",
71 	[AGGR_THREAD] 	= 	"comm-pid",
72 	[AGGR_NODE] 	= 	"node",
73 	[AGGR_GLOBAL] 	=	""
74 };
75 
76 const char *metric_threshold_classify__color(enum metric_threshold_classify thresh)
77 {
78 	const char * const colors[] = {
79 		"", /* unknown */
80 		PERF_COLOR_RED,     /* bad */
81 		PERF_COLOR_MAGENTA, /* nearly bad */
82 		PERF_COLOR_YELLOW,  /* less good */
83 		PERF_COLOR_GREEN,   /* good */
84 	};
85 	static_assert(ARRAY_SIZE(colors) - 1  == METRIC_THRESHOLD_GOOD, "missing enum value");
86 	return colors[thresh];
87 }
88 
89 static const char *metric_threshold_classify__str(enum metric_threshold_classify thresh)
90 {
91 	const char * const strs[] = {
92 		"unknown",
93 		"bad",
94 		"nearly bad",
95 		"less good",
96 		"good",
97 	};
98 	static_assert(ARRAY_SIZE(strs) - 1  == METRIC_THRESHOLD_GOOD, "missing enum value");
99 	return strs[thresh];
100 }
101 
102 static void print_running_std(struct perf_stat_config *config, u64 run, u64 ena)
103 {
104 	if (run != ena)
105 		fprintf(config->output, "  (%.2f%%)", 100.0 * run / ena);
106 }
107 
108 static void print_running_csv(struct perf_stat_config *config, u64 run, u64 ena)
109 {
110 	double enabled_percent = 100;
111 
112 	if (run != ena)
113 		enabled_percent = 100 * run / ena;
114 	fprintf(config->output, "%s%" PRIu64 "%s%.2f",
115 		config->csv_sep, run, config->csv_sep, enabled_percent);
116 }
117 struct outstate {
118 	/* Std mode: insert a newline before the next metric */
119 	bool newline;
120 	/* JSON mode: track need for comma for a previous field or not */
121 	bool first;
122 	/* Num CSV separators remaining to pad out when not all fields are printed */
123 	int  csv_col_pad;
124 
125 	/*
126 	 * The following don't track state across fields, but are here as a shortcut to
127 	 * pass data to the print functions. The alternative would be to update the
128 	 * function signatures of the entire print stack to pass them through.
129 	 */
130 	/* Place to output to */
131 	FILE * const fh;
132 	/* Lines are timestamped in --interval-print mode */
133 	char timestamp[64];
134 	/* Num items aggregated in current line. See struct perf_stat_aggr.nr */
135 	int aggr_nr;
136 	/* Core/socket/die etc ID for the current line */
137 	struct aggr_cpu_id id;
138 	/* Event for current line */
139 	struct evsel *evsel;
140 	/* Cgroup for current line */
141 	struct cgroup *cgrp;
142 };
143 
144 static const char *json_sep(struct outstate *os)
145 {
146 	const char *sep = os->first ? "" : ", ";
147 
148 	os->first = false;
149 	return sep;
150 }
151 
152 #define json_out(os, format, ...) fprintf((os)->fh, "%s" format, json_sep(os), ##__VA_ARGS__)
153 
154 static void print_running_json(struct outstate *os, u64 run, u64 ena)
155 {
156 	double enabled_percent = 100;
157 
158 	if (run != ena)
159 		enabled_percent = 100 * run / ena;
160 	json_out(os, "\"event-runtime\" : %" PRIu64 ", \"pcnt-running\" : %.2f",
161 		 run, enabled_percent);
162 }
163 
164 static void print_running(struct perf_stat_config *config, struct outstate *os,
165 			  u64 run, u64 ena, bool before_metric)
166 {
167 	if (config->json_output) {
168 		if (before_metric)
169 			print_running_json(os, run, ena);
170 	} else if (config->csv_output) {
171 		if (before_metric)
172 			print_running_csv(config, run, ena);
173 	} else {
174 		if (!before_metric)
175 			print_running_std(config, run, ena);
176 	}
177 }
178 
179 static void print_noise_pct_std(struct perf_stat_config *config,
180 				double pct)
181 {
182 	if (pct)
183 		fprintf(config->output, "  ( +-%6.2f%% )", pct);
184 }
185 
186 static void print_noise_pct_csv(struct perf_stat_config *config,
187 				double pct)
188 {
189 	fprintf(config->output, "%s%.2f%%", config->csv_sep, pct);
190 }
191 
192 static void print_noise_pct_json(struct outstate *os,
193 				 double pct)
194 {
195 	json_out(os, "\"variance\" : %.2f", pct);
196 }
197 
198 static void print_noise_pct(struct perf_stat_config *config, struct outstate *os,
199 			    double total, double avg, bool before_metric)
200 {
201 	double pct = rel_stddev_stats(total, avg);
202 
203 	if (config->json_output) {
204 		if (before_metric)
205 			print_noise_pct_json(os, pct);
206 	} else if (config->csv_output) {
207 		if (before_metric)
208 			print_noise_pct_csv(config, pct);
209 	} else {
210 		if (!before_metric)
211 			print_noise_pct_std(config, pct);
212 	}
213 }
214 
215 static void print_noise(struct perf_stat_config *config, struct outstate *os,
216 			struct evsel *evsel, double avg, bool before_metric)
217 {
218 	struct perf_stat_evsel *ps;
219 
220 	if (config->run_count == 1)
221 		return;
222 
223 	ps = evsel->stats;
224 	print_noise_pct(config, os, stddev_stats(&ps->res_stats), avg, before_metric);
225 }
226 
227 static void print_cgroup_std(struct perf_stat_config *config, const char *cgrp_name)
228 {
229 	fprintf(config->output, " %-*s", CGROUP_LEN, cgrp_name);
230 }
231 
232 static void print_cgroup_csv(struct perf_stat_config *config, const char *cgrp_name)
233 {
234 	fprintf(config->output, "%s%s", config->csv_sep, cgrp_name);
235 }
236 
237 static void print_cgroup_json(struct outstate *os, const char *cgrp_name)
238 {
239 	json_out(os, "\"cgroup\" : \"%s\"", cgrp_name);
240 }
241 
242 static void print_cgroup(struct perf_stat_config *config, struct outstate *os,
243 			 struct cgroup *cgrp)
244 {
245 	if (nr_cgroups || config->cgroup_list) {
246 		const char *cgrp_name = cgrp ? cgrp->name  : "";
247 
248 		if (config->json_output)
249 			print_cgroup_json(os, cgrp_name);
250 		else if (config->csv_output)
251 			print_cgroup_csv(config, cgrp_name);
252 		else
253 			print_cgroup_std(config, cgrp_name);
254 	}
255 }
256 
257 static void print_aggr_id_std(struct perf_stat_config *config,
258 			      struct evsel *evsel, struct aggr_cpu_id id, int aggr_nr)
259 {
260 	FILE *output = config->output;
261 	int idx = config->aggr_mode;
262 	char buf[128];
263 
264 	switch (config->aggr_mode) {
265 	case AGGR_CORE:
266 		snprintf(buf, sizeof(buf), "S%d-D%d-C%d", id.socket, id.die, id.core);
267 		break;
268 	case AGGR_CACHE:
269 		snprintf(buf, sizeof(buf), "S%d-D%d-L%d-ID%d",
270 			 id.socket, id.die, id.cache_lvl, id.cache);
271 		break;
272 	case AGGR_CLUSTER:
273 		snprintf(buf, sizeof(buf), "S%d-D%d-CLS%d", id.socket, id.die, id.cluster);
274 		break;
275 	case AGGR_DIE:
276 		snprintf(buf, sizeof(buf), "S%d-D%d", id.socket, id.die);
277 		break;
278 	case AGGR_SOCKET:
279 		snprintf(buf, sizeof(buf), "S%d", id.socket);
280 		break;
281 	case AGGR_NODE:
282 		snprintf(buf, sizeof(buf), "N%d", id.node);
283 		break;
284 	case AGGR_NONE:
285 		if (evsel->percore && !config->percore_show_thread) {
286 			snprintf(buf, sizeof(buf), "S%d-D%d-C%d ",
287 				id.socket, id.die, id.core);
288 			fprintf(output, "%-*s ",
289 				aggr_header_lens[AGGR_CORE], buf);
290 		} else if (id.cpu.cpu > -1) {
291 			fprintf(output, "CPU%-*d ",
292 				aggr_header_lens[AGGR_NONE] - 3, id.cpu.cpu);
293 		}
294 		return;
295 	case AGGR_THREAD:
296 		fprintf(output, "%*s-%-*d ",
297 			COMM_LEN, perf_thread_map__comm(evsel->core.threads, id.thread_idx),
298 			PID_LEN, perf_thread_map__pid(evsel->core.threads, id.thread_idx));
299 		return;
300 	case AGGR_GLOBAL:
301 	case AGGR_UNSET:
302 	case AGGR_MAX:
303 	default:
304 		return;
305 	}
306 
307 	fprintf(output, "%-*s %*d ", aggr_header_lens[idx], buf, /*strlen("ctrs")*/ 4, aggr_nr);
308 }
309 
310 static void print_aggr_id_csv(struct perf_stat_config *config,
311 			      struct evsel *evsel, struct aggr_cpu_id id, int aggr_nr)
312 {
313 	FILE *output = config->output;
314 	const char *sep = config->csv_sep;
315 
316 	switch (config->aggr_mode) {
317 	case AGGR_CORE:
318 		fprintf(output, "S%d-D%d-C%d%s%d%s",
319 			id.socket, id.die, id.core, sep, aggr_nr, sep);
320 		break;
321 	case AGGR_CACHE:
322 		fprintf(config->output, "S%d-D%d-L%d-ID%d%s%d%s",
323 			id.socket, id.die, id.cache_lvl, id.cache, sep, aggr_nr, sep);
324 		break;
325 	case AGGR_CLUSTER:
326 		fprintf(config->output, "S%d-D%d-CLS%d%s%d%s",
327 			id.socket, id.die, id.cluster, sep, aggr_nr, sep);
328 		break;
329 	case AGGR_DIE:
330 		fprintf(output, "S%d-D%d%s%d%s",
331 			id.socket, id.die, sep, aggr_nr, sep);
332 		break;
333 	case AGGR_SOCKET:
334 		fprintf(output, "S%d%s%d%s",
335 			id.socket, sep, aggr_nr, sep);
336 		break;
337 	case AGGR_NODE:
338 		fprintf(output, "N%d%s%d%s",
339 			id.node, sep, aggr_nr, sep);
340 		break;
341 	case AGGR_NONE:
342 		if (evsel->percore && !config->percore_show_thread) {
343 			fprintf(output, "S%d-D%d-C%d%s",
344 				id.socket, id.die, id.core, sep);
345 		} else if (id.cpu.cpu > -1) {
346 			fprintf(output, "CPU%d%s",
347 				id.cpu.cpu, sep);
348 		}
349 		break;
350 	case AGGR_THREAD:
351 		fprintf(output, "%s-%d%s",
352 			perf_thread_map__comm(evsel->core.threads, id.thread_idx),
353 			perf_thread_map__pid(evsel->core.threads, id.thread_idx),
354 			sep);
355 		break;
356 	case AGGR_GLOBAL:
357 	case AGGR_UNSET:
358 	case AGGR_MAX:
359 	default:
360 		break;
361 	}
362 }
363 
364 static void print_aggr_id_json(struct perf_stat_config *config, struct outstate *os,
365 			       struct evsel *evsel, struct aggr_cpu_id id, int aggr_nr)
366 {
367 	switch (config->aggr_mode) {
368 	case AGGR_CORE:
369 		json_out(os, "\"core\" : \"S%d-D%d-C%d\", \"counters\" : %d",
370 			id.socket, id.die, id.core, aggr_nr);
371 		break;
372 	case AGGR_CACHE:
373 		json_out(os, "\"cache\" : \"S%d-D%d-L%d-ID%d\", \"counters\" : %d",
374 			id.socket, id.die, id.cache_lvl, id.cache, aggr_nr);
375 		break;
376 	case AGGR_CLUSTER:
377 		json_out(os, "\"cluster\" : \"S%d-D%d-CLS%d\", \"counters\" : %d",
378 			id.socket, id.die, id.cluster, aggr_nr);
379 		break;
380 	case AGGR_DIE:
381 		json_out(os, "\"die\" : \"S%d-D%d\", \"counters\" : %d",
382 			id.socket, id.die, aggr_nr);
383 		break;
384 	case AGGR_SOCKET:
385 		json_out(os, "\"socket\" : \"S%d\", \"counters\" : %d",
386 			id.socket, aggr_nr);
387 		break;
388 	case AGGR_NODE:
389 		json_out(os, "\"node\" : \"N%d\", \"counters\" : %d",
390 			id.node, aggr_nr);
391 		break;
392 	case AGGR_NONE:
393 		if (evsel->percore && !config->percore_show_thread) {
394 			json_out(os, "\"core\" : \"S%d-D%d-C%d\"",
395 				id.socket, id.die, id.core);
396 		} else if (id.cpu.cpu > -1) {
397 			json_out(os, "\"cpu\" : \"%d\"",
398 				id.cpu.cpu);
399 		}
400 		break;
401 	case AGGR_THREAD:
402 		json_out(os, "\"thread\" : \"%s-%d\"",
403 			perf_thread_map__comm(evsel->core.threads, id.thread_idx),
404 			perf_thread_map__pid(evsel->core.threads, id.thread_idx));
405 		break;
406 	case AGGR_GLOBAL:
407 	case AGGR_UNSET:
408 	case AGGR_MAX:
409 	default:
410 		break;
411 	}
412 }
413 
414 static void aggr_printout(struct perf_stat_config *config, struct outstate *os,
415 			  struct evsel *evsel, struct aggr_cpu_id id, int aggr_nr)
416 {
417 	if (config->json_output)
418 		print_aggr_id_json(config, os, evsel, id, aggr_nr);
419 	else if (config->csv_output)
420 		print_aggr_id_csv(config, evsel, id, aggr_nr);
421 	else
422 		print_aggr_id_std(config, evsel, id, aggr_nr);
423 }
424 
425 static void new_line_std(struct perf_stat_config *config __maybe_unused,
426 			 void *ctx)
427 {
428 	struct outstate *os = ctx;
429 
430 	os->newline = true;
431 }
432 
433 static inline void __new_line_std_csv(struct perf_stat_config *config,
434 				      struct outstate *os)
435 {
436 	fputc('\n', os->fh);
437 	if (config->interval)
438 		fputs(os->timestamp, os->fh);
439 	aggr_printout(config, os, os->evsel, os->id, os->aggr_nr);
440 }
441 
442 static inline void __new_line_std(struct perf_stat_config *config, struct outstate *os)
443 {
444 	fprintf(os->fh, "%*s", COUNTS_LEN + EVNAME_LEN + config->unit_width + 2, "");
445 }
446 
447 static void do_new_line_std(struct perf_stat_config *config,
448 			    struct outstate *os)
449 {
450 	__new_line_std_csv(config, os);
451 	if (config->aggr_mode == AGGR_NONE)
452 		fprintf(os->fh, "        ");
453 	__new_line_std(config, os);
454 }
455 
456 static void print_metric_std(struct perf_stat_config *config,
457 			     void *ctx, enum metric_threshold_classify thresh,
458 			     const char *fmt, const char *unit, double val)
459 {
460 	struct outstate *os = ctx;
461 	FILE *out = os->fh;
462 	int n;
463 	bool newline = os->newline;
464 	const char *color = metric_threshold_classify__color(thresh);
465 
466 	os->newline = false;
467 
468 	if (unit == NULL || fmt == NULL) {
469 		fprintf(out, "%-*s", METRIC_LEN, "");
470 		return;
471 	}
472 
473 	if (newline)
474 		do_new_line_std(config, os);
475 
476 	n = fprintf(out, " # ");
477 	if (color)
478 		n += color_fprintf(out, color, fmt, val);
479 	else
480 		n += fprintf(out, fmt, val);
481 	fprintf(out, " %-*s", METRIC_LEN - n - 1, unit);
482 }
483 
484 static void new_line_csv(struct perf_stat_config *config, void *ctx)
485 {
486 	struct outstate *os = ctx;
487 	int i;
488 
489 	__new_line_std_csv(config, os);
490 	for (i = 0; i < os->csv_col_pad; i++)
491 		fputs(config->csv_sep, os->fh);
492 }
493 
494 static void print_metric_csv(struct perf_stat_config *config __maybe_unused,
495 			     void *ctx,
496 			     enum metric_threshold_classify thresh __maybe_unused,
497 			     const char *fmt, const char *unit, double val)
498 {
499 	struct outstate *os = ctx;
500 	FILE *out = os->fh;
501 	char buf[64], *vals, *ends;
502 
503 	if (unit == NULL || fmt == NULL) {
504 		fprintf(out, "%s%s", config->csv_sep, config->csv_sep);
505 		return;
506 	}
507 	snprintf(buf, sizeof(buf), fmt, val);
508 	ends = vals = skip_spaces(buf);
509 	while (isdigit(*ends) || *ends == '.')
510 		ends++;
511 	*ends = 0;
512 	fprintf(out, "%s%s%s%s", config->csv_sep, vals, config->csv_sep, skip_spaces(unit));
513 }
514 
515 static void print_metric_json(struct perf_stat_config *config __maybe_unused,
516 			     void *ctx,
517 			     enum metric_threshold_classify thresh,
518 			     const char *fmt __maybe_unused,
519 			     const char *unit, double val)
520 {
521 	struct outstate *os = ctx;
522 	FILE *out = os->fh;
523 
524 	if (unit) {
525 		json_out(os, "\"metric-value\" : \"%f\", \"metric-unit\" : \"%s\"", val, unit);
526 		if (thresh != METRIC_THRESHOLD_UNKNOWN) {
527 			json_out(os, "\"metric-threshold\" : \"%s\"",
528 				metric_threshold_classify__str(thresh));
529 		}
530 	}
531 	if (!config->metric_only)
532 		fprintf(out, "}");
533 }
534 
535 static void new_line_json(struct perf_stat_config *config, void *ctx)
536 {
537 	struct outstate *os = ctx;
538 
539 	fputs("\n{", os->fh);
540 	os->first = true;
541 	if (config->interval)
542 		json_out(os, "%s", os->timestamp);
543 
544 	aggr_printout(config, os, os->evsel, os->id, os->aggr_nr);
545 }
546 
547 static void print_metricgroup_header_json(struct perf_stat_config *config,
548 					  void *ctx,
549 					  const char *metricgroup_name)
550 {
551 	if (!metricgroup_name)
552 		return;
553 
554 	json_out((struct outstate *) ctx, "\"metricgroup\" : \"%s\"}", metricgroup_name);
555 	new_line_json(config, ctx);
556 }
557 
558 static void print_metricgroup_header_csv(struct perf_stat_config *config,
559 					 void *ctx,
560 					 const char *metricgroup_name)
561 {
562 	struct outstate *os = ctx;
563 	int i;
564 
565 	if (!metricgroup_name) {
566 		/* Leave space for running and enabling */
567 		for (i = 0; i < os->csv_col_pad - 2; i++)
568 			fputs(config->csv_sep, os->fh);
569 		return;
570 	}
571 
572 	for (i = 0; i < os->csv_col_pad; i++)
573 		fputs(config->csv_sep, os->fh);
574 	fprintf(config->output, "%s", metricgroup_name);
575 	new_line_csv(config, ctx);
576 }
577 
578 static void print_metricgroup_header_std(struct perf_stat_config *config,
579 					 void *ctx,
580 					 const char *metricgroup_name)
581 {
582 	struct outstate *os = ctx;
583 
584 	if (!metricgroup_name) {
585 		__new_line_std(config, os);
586 		return;
587 	}
588 
589 	fprintf(config->output, " %*s", config->metric_only_len, metricgroup_name);
590 }
591 
592 static void print_metric_only(struct perf_stat_config *config,
593 			      void *ctx, enum metric_threshold_classify thresh,
594 			      const char *fmt, const char *unit, double val)
595 {
596 	struct outstate *os = ctx;
597 	FILE *out = os->fh;
598 	char str[1024];
599 	unsigned mlen;
600 	const char *color = metric_threshold_classify__color(thresh);
601 	int olen;
602 
603 	if (!unit) {
604 		os->first = false;
605 		return;
606 	}
607 
608 	mlen = max_t(unsigned, strlen(unit), config->metric_only_len);
609 
610 	olen = snprintf(str, sizeof(str), fmt ?: "", val);
611 	color_snprintf(str, sizeof(str), color ?: "", fmt ?: "", val);
612 	fprintf(out, "%*s%s", max_t(int, mlen - olen, 1), "", str);
613 	os->first = false;
614 }
615 
616 static void print_metric_only_csv(struct perf_stat_config *config __maybe_unused,
617 				  void *ctx,
618 				  enum metric_threshold_classify thresh __maybe_unused,
619 				  const char *fmt,
620 				  const char *unit __maybe_unused, double val)
621 {
622 	struct outstate *os = ctx;
623 	FILE *out = os->fh;
624 	char buf[64], *vals, *ends;
625 
626 	if (!unit)
627 		return;
628 
629 	snprintf(buf, sizeof(buf), fmt ?: "", val);
630 	ends = vals = skip_spaces(buf);
631 	while (isdigit(*ends) || *ends == '.')
632 		ends++;
633 	*ends = 0;
634 	fprintf(out, "%s%s", vals, config->csv_sep);
635 	os->first = false;
636 }
637 
638 static void print_metric_only_json(struct perf_stat_config *config __maybe_unused,
639 				  void *ctx,
640 				  enum metric_threshold_classify thresh __maybe_unused,
641 				  const char *fmt,
642 				  const char *unit, double val)
643 {
644 	struct outstate *os = ctx;
645 	char buf[64], *ends;
646 	const char *vals;
647 
648 	if (!unit || !unit[0])
649 		return;
650 	snprintf(buf, sizeof(buf), fmt ?: "", val);
651 	vals = ends = skip_spaces(buf);
652 	while (isdigit(*ends) || *ends == '.')
653 		ends++;
654 	*ends = 0;
655 	if (!vals[0])
656 		vals = "none";
657 	json_out(os, "\"%s\" : \"%s\"", unit, vals);
658 }
659 
660 static void print_metric_header(struct perf_stat_config *config,
661 				void *ctx,
662 				enum metric_threshold_classify thresh __maybe_unused,
663 				const char *fmt __maybe_unused,
664 				const char *unit, double val __maybe_unused)
665 {
666 	struct outstate *os = ctx;
667 
668 	/* In case of iostat, print metric header for first root port only */
669 	if (config->iostat_run &&
670 	    os->evsel->priv != os->evsel->evlist->selected->priv)
671 		return;
672 
673 	if (os->evsel->cgrp != os->cgrp)
674 		return;
675 
676 	if (!unit)
677 		return;
678 
679 	if (config->json_output)
680 		return;
681 	else if (config->csv_output)
682 		fprintf(os->fh, "%s%s", unit, config->csv_sep);
683 	else
684 		fprintf(os->fh, "%*s ", config->metric_only_len, unit);
685 }
686 
687 static void print_counter_value_std(struct perf_stat_config *config,
688 				    struct evsel *evsel, double avg, bool ok)
689 {
690 	FILE *output = config->output;
691 	double sc =  evsel->scale;
692 	const char *fmt;
693 	const char *bad_count = evsel->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED;
694 
695 	if (config->big_num)
696 		fmt = floor(sc) != sc ? "%'*.2f " : "%'*.0f ";
697 	else
698 		fmt = floor(sc) != sc ? "%*.2f " : "%*.0f ";
699 
700 	if (ok)
701 		fprintf(output, fmt, COUNTS_LEN, avg);
702 	else
703 		fprintf(output, "%*s ", COUNTS_LEN, bad_count);
704 
705 	if (evsel->unit)
706 		fprintf(output, "%-*s ", config->unit_width, evsel->unit);
707 
708 	fprintf(output, "%-*s", EVNAME_LEN, evsel__name(evsel));
709 }
710 
711 static void print_counter_value_csv(struct perf_stat_config *config,
712 				    struct evsel *evsel, double avg, bool ok)
713 {
714 	FILE *output = config->output;
715 	double sc =  evsel->scale;
716 	const char *sep = config->csv_sep;
717 	const char *fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s";
718 	const char *bad_count = evsel->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED;
719 
720 	if (ok)
721 		fprintf(output, fmt, avg, sep);
722 	else
723 		fprintf(output, "%s%s", bad_count, sep);
724 
725 	if (evsel->unit)
726 		fprintf(output, "%s%s", evsel->unit, sep);
727 
728 	fprintf(output, "%s", evsel__name(evsel));
729 }
730 
731 static void print_counter_value_json(struct outstate *os,
732 				     struct evsel *evsel, double avg, bool ok)
733 {
734 	const char *bad_count = evsel->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED;
735 
736 	if (ok)
737 		json_out(os, "\"counter-value\" : \"%f\"", avg);
738 	else
739 		json_out(os, "\"counter-value\" : \"%s\"", bad_count);
740 
741 	if (evsel->unit)
742 		json_out(os, "\"unit\" : \"%s\"", evsel->unit);
743 
744 	json_out(os, "\"event\" : \"%s\"", evsel__name(evsel));
745 }
746 
747 static void print_counter_value(struct perf_stat_config *config, struct outstate *os,
748 				struct evsel *evsel, double avg, bool ok)
749 {
750 	if (config->json_output)
751 		print_counter_value_json(os, evsel, avg, ok);
752 	else if (config->csv_output)
753 		print_counter_value_csv(config, evsel, avg, ok);
754 	else
755 		print_counter_value_std(config, evsel, avg, ok);
756 }
757 
758 static void abs_printout(struct perf_stat_config *config,
759 			 struct outstate *os,
760 			 struct aggr_cpu_id id, int aggr_nr,
761 			 struct evsel *evsel, double avg, bool ok)
762 {
763 	aggr_printout(config, os, evsel, id, aggr_nr);
764 	print_counter_value(config, os, evsel, avg, ok);
765 	print_cgroup(config, os, evsel->cgrp);
766 }
767 
768 static bool evlist__has_hybrid_pmus(struct evlist *evlist)
769 {
770 	struct evsel *evsel;
771 	struct perf_pmu *last_core_pmu = NULL;
772 
773 	if (perf_pmus__num_core_pmus() == 1)
774 		return false;
775 
776 	evlist__for_each_entry(evlist, evsel) {
777 		if (evsel->core.is_pmu_core) {
778 			struct perf_pmu *pmu = evsel__find_pmu(evsel);
779 
780 			if (pmu == last_core_pmu)
781 				continue;
782 
783 			if (last_core_pmu == NULL) {
784 				last_core_pmu = pmu;
785 				continue;
786 			}
787 			/* A distinct core PMU. */
788 			return true;
789 		}
790 	}
791 
792 	return false;
793 }
794 
795 static void printout(struct perf_stat_config *config, struct outstate *os,
796 		     double uval, u64 run, u64 ena, double noise, int aggr_idx)
797 {
798 	struct perf_stat_output_ctx out;
799 	print_metric_t pm;
800 	new_line_t nl;
801 	print_metricgroup_header_t pmh;
802 	bool ok = true;
803 	struct evsel *counter = os->evsel;
804 
805 	if (config->csv_output) {
806 		pm = config->metric_only ? print_metric_only_csv : print_metric_csv;
807 		nl = config->metric_only ? NULL : new_line_csv;
808 		pmh = print_metricgroup_header_csv;
809 		os->csv_col_pad = 4 + (counter->cgrp ? 1 : 0);
810 	} else if (config->json_output) {
811 		pm = config->metric_only ? print_metric_only_json : print_metric_json;
812 		nl = config->metric_only ? NULL : new_line_json;
813 		pmh = print_metricgroup_header_json;
814 	} else {
815 		pm = config->metric_only ? print_metric_only : print_metric_std;
816 		nl = config->metric_only ? NULL : new_line_std;
817 		pmh = print_metricgroup_header_std;
818 	}
819 
820 	if (run == 0 || ena == 0 || counter->counts->scaled == -1) {
821 		ok = false;
822 
823 		if (counter->supported) {
824 			if (!evlist__has_hybrid_pmus(counter->evlist) &&
825 			    counter->pmu && counter->pmu->is_core)
826 				config->print_free_counters_hint = 1;
827 		}
828 	}
829 
830 	out.print_metric = pm;
831 	out.new_line = nl;
832 	out.print_metricgroup_header = pmh;
833 	out.ctx = os;
834 	out.force_header = false;
835 
836 	if (!config->metric_only && (!counter->default_metricgroup || counter->default_show_events)) {
837 		abs_printout(config, os, os->id, os->aggr_nr, counter, uval, ok);
838 
839 		print_noise(config, os, counter, noise, /*before_metric=*/true);
840 		print_running(config, os, run, ena, /*before_metric=*/true);
841 	}
842 
843 	if (!config->metric_only && counter->default_metricgroup &&
844 	    !counter->default_show_events) {
845 		void *from = NULL;
846 
847 		aggr_printout(config, os, os->evsel, os->id, os->aggr_nr);
848 		/* Print out all the metricgroup with the same metric event. */
849 		do {
850 			int num = 0;
851 
852 			/* Print out the new line for the next new metricgroup. */
853 			if (from) {
854 				if (config->json_output)
855 					new_line_json(config, (void *)os);
856 				else
857 					__new_line_std_csv(config, os);
858 			}
859 
860 			print_noise(config, os, counter, noise,
861 				    /*before_metric=*/true);
862 			print_running(config, os, run, ena,
863 				      /*before_metric=*/true);
864 			from = perf_stat__print_shadow_stats_metricgroup(
865 				config, counter, aggr_idx, &num, from, &out);
866 		} while (from != NULL);
867 	} else {
868 		perf_stat__print_shadow_stats(config, counter, aggr_idx, &out);
869 	}
870 
871 	if (!config->metric_only) {
872 		print_noise(config, os, counter, noise, /*before_metric=*/false);
873 		print_running(config, os, run, ena, /*before_metric=*/false);
874 	}
875 }
876 
877 /**
878  * should_skip_zero_count() - Check if the event should print 0 values.
879  * @config: The perf stat configuration (including aggregation mode).
880  * @counter: The evsel with its associated cpumap.
881  * @id: The aggregation id that is being queried.
882  *
883  * Due to mismatch between the event cpumap or thread-map and the
884  * aggregation mode, sometimes it'd iterate the counter with the map
885  * which does not contain any values.
886  *
887  * For example, uncore events have dedicated CPUs to manage them,
888  * result for other CPUs should be zero and skipped.
889  *
890  * Return: %true if the value should NOT be printed, %false if the value
891  * needs to be printed like "<not counted>" or "<not supported>".
892  */
893 static bool should_skip_zero_counter(struct perf_stat_config *config,
894 				     struct evsel *counter,
895 				     const struct aggr_cpu_id *id)
896 {
897 	struct perf_cpu cpu;
898 	unsigned int idx;
899 
900 	/*
901 	 * Skip unsupported default events when not verbose. (default events
902 	 * are all marked 'skippable').
903 	 */
904 	if (verbose == 0 && counter->skippable && !counter->supported)
905 		return true;
906 
907 	/* Metric only counts won't be displayed but the metric wants to be computed. */
908 	if (config->metric_only)
909 		return false;
910 	/*
911 	 * Skip value 0 when enabling --per-thread globally,
912 	 * otherwise it will have too many 0 output.
913 	 */
914 	if (config->aggr_mode == AGGR_THREAD && config->system_wide)
915 		return true;
916 
917 	/*
918 	 * In per-thread mode the aggr_map and aggr_get_id functions may be
919 	 * NULL, assume all 0 values should be output in that case.
920 	 */
921 	if (!config->aggr_map || !config->aggr_get_id)
922 		return false;
923 
924 	/*
925 	 * Tool events may be gathered on all logical CPUs, for example
926 	 * system_time, but for many the first index is the only one used, for
927 	 * example num_cores. Don't skip for the first index.
928 	 */
929 	if (evsel__is_tool(counter)) {
930 		struct aggr_cpu_id own_id =
931 			config->aggr_get_id(config, (struct perf_cpu){ .cpu = 0 });
932 
933 		return !aggr_cpu_id__equal(id, &own_id);
934 	}
935 	/*
936 	 * Skip value 0 when the counter's cpumask doesn't match the given aggr
937 	 * id.
938 	 */
939 
940 	perf_cpu_map__for_each_cpu(cpu, idx, counter->core.cpus) {
941 		struct aggr_cpu_id own_id = config->aggr_get_id(config, cpu);
942 
943 		if (aggr_cpu_id__equal(id, &own_id))
944 			return false;
945 	}
946 	return true;
947 }
948 
949 static void print_counter_aggrdata(struct perf_stat_config *config,
950 				   struct evsel *counter, int aggr_idx,
951 				   struct outstate *os)
952 {
953 	FILE *output = config->output;
954 	u64 ena, run, val;
955 	double uval;
956 	struct perf_stat_evsel *ps = counter->stats;
957 	struct perf_stat_aggr *aggr = &ps->aggr[aggr_idx];
958 	struct aggr_cpu_id id = config->aggr_map->map[aggr_idx];
959 	double avg = aggr->counts.val;
960 	bool metric_only = config->metric_only;
961 
962 	os->id = id;
963 	os->aggr_nr = aggr->nr;
964 	os->evsel = counter;
965 
966 	/* Skip already merged uncore/hybrid events */
967 	if (config->aggr_mode != AGGR_NONE) {
968 		if (evsel__is_hybrid(counter)) {
969 			if (config->hybrid_merge && counter->first_wildcard_match != NULL)
970 				return;
971 		} else {
972 			if (counter->first_wildcard_match != NULL)
973 				return;
974 		}
975 	}
976 
977 	val = aggr->counts.val;
978 	ena = aggr->counts.ena;
979 	run = aggr->counts.run;
980 
981 	if (perf_stat__skip_metric_event(counter))
982 		return;
983 
984 	if (val == 0 && should_skip_zero_counter(config, counter, &id))
985 		return;
986 
987 	if (!metric_only) {
988 		if (config->json_output) {
989 			os->first = true;
990 			fputc('{', output);
991 		}
992 		if (config->interval) {
993 			if (config->json_output)
994 				json_out(os, "%s", os->timestamp);
995 			else
996 				fprintf(output, "%s", os->timestamp);
997 		} else if (config->summary && config->csv_output &&
998 			   !config->no_csv_summary)
999 			fprintf(output, "%s%s", "summary", config->csv_sep);
1000 	}
1001 
1002 	uval = val * counter->scale;
1003 
1004 	printout(config, os, uval, run, ena, avg, aggr_idx);
1005 
1006 	if (!metric_only)
1007 		fputc('\n', output);
1008 }
1009 
1010 static void print_metric_begin(struct perf_stat_config *config,
1011 			       struct evlist *evlist,
1012 			       struct outstate *os, int aggr_idx)
1013 {
1014 	struct perf_stat_aggr *aggr;
1015 	struct aggr_cpu_id id;
1016 	struct evsel *evsel;
1017 
1018 	os->first = true;
1019 	if (!config->metric_only)
1020 		return;
1021 
1022 	if (config->json_output)
1023 		fputc('{', config->output);
1024 
1025 	if (config->interval) {
1026 		if (config->json_output)
1027 			json_out(os, "%s", os->timestamp);
1028 		else
1029 			fprintf(config->output, "%s", os->timestamp);
1030 	}
1031 	evsel = evlist__first(evlist);
1032 	id = config->aggr_map->map[aggr_idx];
1033 	aggr = &evsel->stats->aggr[aggr_idx];
1034 	aggr_printout(config, os, evsel, id, aggr->nr);
1035 
1036 	print_cgroup(config, os, os->cgrp ? : evsel->cgrp);
1037 }
1038 
1039 static void print_metric_end(struct perf_stat_config *config, struct outstate *os)
1040 {
1041 	FILE *output = config->output;
1042 
1043 	if (!config->metric_only)
1044 		return;
1045 
1046 	if (config->json_output) {
1047 		if (os->first)
1048 			fputs("\"metric-value\" : \"none\"", output);
1049 		fputc('}', output);
1050 	}
1051 	fputc('\n', output);
1052 }
1053 
1054 static void print_aggr(struct perf_stat_config *config,
1055 		       struct evlist *evlist,
1056 		       struct outstate *os)
1057 {
1058 	struct evsel *counter;
1059 	int aggr_idx;
1060 
1061 	if (!config->aggr_map || !config->aggr_get_id)
1062 		return;
1063 
1064 	/*
1065 	 * With metric_only everything is on a single line.
1066 	 * Without each counter has its own line.
1067 	 */
1068 	cpu_aggr_map__for_each_idx(aggr_idx, config->aggr_map) {
1069 		print_metric_begin(config, evlist, os, aggr_idx);
1070 
1071 		evlist__for_each_entry(evlist, counter) {
1072 			print_counter_aggrdata(config, counter, aggr_idx, os);
1073 		}
1074 		print_metric_end(config, os);
1075 	}
1076 }
1077 
1078 static void print_aggr_cgroup(struct perf_stat_config *config,
1079 			      struct evlist *evlist,
1080 			      struct outstate *os)
1081 {
1082 	struct evsel *counter, *evsel;
1083 	int aggr_idx;
1084 
1085 	if (!config->aggr_map || !config->aggr_get_id)
1086 		return;
1087 
1088 	evlist__for_each_entry(evlist, evsel) {
1089 		if (os->cgrp == evsel->cgrp)
1090 			continue;
1091 
1092 		os->cgrp = evsel->cgrp;
1093 
1094 		cpu_aggr_map__for_each_idx(aggr_idx, config->aggr_map) {
1095 			print_metric_begin(config, evlist, os, aggr_idx);
1096 
1097 			evlist__for_each_entry(evlist, counter) {
1098 				if (counter->cgrp != os->cgrp)
1099 					continue;
1100 
1101 				print_counter_aggrdata(config, counter, aggr_idx, os);
1102 			}
1103 			print_metric_end(config, os);
1104 		}
1105 	}
1106 }
1107 
1108 static void print_counter(struct perf_stat_config *config,
1109 			  struct evsel *counter, struct outstate *os)
1110 {
1111 	int aggr_idx;
1112 
1113 	/* AGGR_THREAD doesn't have config->aggr_get_id */
1114 	if (!config->aggr_map)
1115 		return;
1116 
1117 	cpu_aggr_map__for_each_idx(aggr_idx, config->aggr_map) {
1118 		print_counter_aggrdata(config, counter, aggr_idx, os);
1119 	}
1120 }
1121 
1122 static void print_no_aggr_metric(struct perf_stat_config *config,
1123 				 struct evlist *evlist,
1124 				 struct outstate *os)
1125 {
1126 	unsigned int all_idx;
1127 	struct perf_cpu cpu;
1128 
1129 	perf_cpu_map__for_each_cpu(cpu, all_idx, evlist->core.user_requested_cpus) {
1130 		struct evsel *counter;
1131 		bool first = true;
1132 
1133 		evlist__for_each_entry(evlist, counter) {
1134 			u64 ena, run, val;
1135 			double uval;
1136 			struct perf_stat_evsel *ps = counter->stats;
1137 			int aggr_idx = 0;
1138 
1139 			if (!perf_cpu_map__has(evsel__cpus(counter), cpu))
1140 				continue;
1141 
1142 			cpu_aggr_map__for_each_idx(aggr_idx, config->aggr_map) {
1143 				if (config->aggr_map->map[aggr_idx].cpu.cpu == cpu.cpu)
1144 					break;
1145 			}
1146 
1147 			os->evsel = counter;
1148 			os->id = aggr_cpu_id__cpu(cpu, /*data=*/NULL);
1149 			if (first) {
1150 				print_metric_begin(config, evlist, os, aggr_idx);
1151 				first = false;
1152 			}
1153 			val = ps->aggr[aggr_idx].counts.val;
1154 			ena = ps->aggr[aggr_idx].counts.ena;
1155 			run = ps->aggr[aggr_idx].counts.run;
1156 
1157 			uval = val * counter->scale;
1158 			printout(config, os, uval, run, ena, 1.0, aggr_idx);
1159 		}
1160 		if (!first)
1161 			print_metric_end(config, os);
1162 	}
1163 }
1164 
1165 static void print_metric_headers_std(struct perf_stat_config *config,
1166 				     bool no_indent)
1167 {
1168 	fputc(' ', config->output);
1169 
1170 	if (!no_indent) {
1171 		int len = aggr_header_lens[config->aggr_mode];
1172 
1173 		if (nr_cgroups || config->cgroup_list)
1174 			len += CGROUP_LEN + 1;
1175 
1176 		fprintf(config->output, "%*s", len, "");
1177 	}
1178 }
1179 
1180 static void print_metric_headers_csv(struct perf_stat_config *config,
1181 				     bool no_indent __maybe_unused)
1182 {
1183 	const char *p;
1184 
1185 	if (config->interval)
1186 		fprintf(config->output, "time%s", config->csv_sep);
1187 	if (config->iostat_run)
1188 		return;
1189 
1190 	p = aggr_header_csv[config->aggr_mode];
1191 	while (*p) {
1192 		if (*p == ',')
1193 			fputs(config->csv_sep, config->output);
1194 		else
1195 			fputc(*p, config->output);
1196 		p++;
1197 	}
1198 }
1199 
1200 static void print_metric_headers_json(struct perf_stat_config *config __maybe_unused,
1201 				      bool no_indent __maybe_unused)
1202 {
1203 }
1204 
1205 static void print_metric_headers(struct perf_stat_config *config,
1206 				 struct evlist *evlist, bool no_indent)
1207 {
1208 	struct evsel *counter;
1209 	struct outstate os = {
1210 		.fh = config->output
1211 	};
1212 	struct perf_stat_output_ctx out = {
1213 		.ctx = &os,
1214 		.print_metric = print_metric_header,
1215 		.new_line = NULL,
1216 		.force_header = true,
1217 	};
1218 
1219 	if (config->json_output)
1220 		print_metric_headers_json(config, no_indent);
1221 	else if (config->csv_output)
1222 		print_metric_headers_csv(config, no_indent);
1223 	else
1224 		print_metric_headers_std(config, no_indent);
1225 
1226 	if (config->iostat_run)
1227 		iostat_print_header_prefix(config);
1228 
1229 	if (config->cgroup_list)
1230 		os.cgrp = evlist__first(evlist)->cgrp;
1231 
1232 	/* Print metrics headers only */
1233 	evlist__for_each_entry(evlist, counter) {
1234 		if (!config->iostat_run &&
1235 		    config->aggr_mode != AGGR_NONE && counter->metric_leader != counter)
1236 			continue;
1237 
1238 		os.evsel = counter;
1239 
1240 		perf_stat__print_shadow_stats(config, counter, /*aggr_idx=*/0, &out);
1241 	}
1242 
1243 	if (!config->json_output)
1244 		fputc('\n', config->output);
1245 }
1246 
1247 static void prepare_timestamp(struct perf_stat_config *config,
1248 			      struct outstate *os, struct timespec *ts)
1249 {
1250 	if (config->iostat_run)
1251 		return;
1252 
1253 	if (config->json_output)
1254 		scnprintf(os->timestamp, sizeof(os->timestamp), "\"interval\" : %lu.%09lu",
1255 			  (unsigned long) ts->tv_sec, ts->tv_nsec);
1256 	else if (config->csv_output)
1257 		scnprintf(os->timestamp, sizeof(os->timestamp), "%lu.%09lu%s",
1258 			  (unsigned long) ts->tv_sec, ts->tv_nsec, config->csv_sep);
1259 	else
1260 		scnprintf(os->timestamp, sizeof(os->timestamp), "%6lu.%09lu ",
1261 			  (unsigned long) ts->tv_sec, ts->tv_nsec);
1262 }
1263 
1264 static void print_header_interval_std(struct perf_stat_config *config,
1265 				      struct target *_target __maybe_unused,
1266 				      struct evlist *evlist,
1267 				      int argc __maybe_unused,
1268 				      const char **argv __maybe_unused)
1269 {
1270 	FILE *output = config->output;
1271 
1272 	switch (config->aggr_mode) {
1273 	case AGGR_NODE:
1274 	case AGGR_SOCKET:
1275 	case AGGR_DIE:
1276 	case AGGR_CLUSTER:
1277 	case AGGR_CACHE:
1278 	case AGGR_CORE:
1279 		fprintf(output, "#%*s %-*s ctrs",
1280 			INTERVAL_LEN - 1, "time",
1281 			aggr_header_lens[config->aggr_mode],
1282 			aggr_header_std[config->aggr_mode]);
1283 		break;
1284 	case AGGR_NONE:
1285 		fprintf(output, "#%*s %-*s",
1286 			INTERVAL_LEN - 1, "time",
1287 			aggr_header_lens[config->aggr_mode],
1288 			aggr_header_std[config->aggr_mode]);
1289 		break;
1290 	case AGGR_THREAD:
1291 		fprintf(output, "#%*s %*s-%-*s",
1292 			INTERVAL_LEN - 1, "time",
1293 			COMM_LEN, "comm", PID_LEN, "pid");
1294 		break;
1295 	case AGGR_GLOBAL:
1296 	default:
1297 		if (!config->iostat_run)
1298 			fprintf(output, "#%*s",
1299 				INTERVAL_LEN - 1, "time");
1300 	case AGGR_UNSET:
1301 	case AGGR_MAX:
1302 		break;
1303 	}
1304 
1305 	if (config->metric_only)
1306 		print_metric_headers(config, evlist, true);
1307 	else
1308 		fprintf(output, " %*s %*s events\n",
1309 			COUNTS_LEN, "counts", config->unit_width, "unit");
1310 }
1311 
1312 static void print_header_std(struct perf_stat_config *config,
1313 			     struct target *_target, struct evlist *evlist,
1314 			     int argc, const char **argv)
1315 {
1316 	FILE *output = config->output;
1317 	int i;
1318 
1319 	fprintf(output, "\n");
1320 	fprintf(output, " Performance counter stats for ");
1321 	if (_target->bpf_str)
1322 		fprintf(output, "\'BPF program(s) %s", _target->bpf_str);
1323 	else if (_target->system_wide)
1324 		fprintf(output, "\'system wide");
1325 	else if (_target->cpu_list)
1326 		fprintf(output, "\'CPU(s) %s", _target->cpu_list);
1327 	else if (!target__has_task(_target)) {
1328 		fprintf(output, "\'%s", argv ? argv[0] : "pipe");
1329 		for (i = 1; argv && (i < argc); i++)
1330 			fprintf(output, " %s", argv[i]);
1331 	} else if (_target->pid)
1332 		fprintf(output, "process id \'%s", _target->pid);
1333 	else
1334 		fprintf(output, "thread id \'%s", _target->tid);
1335 
1336 	fprintf(output, "\'");
1337 	if (config->run_count > 1)
1338 		fprintf(output, " (%d runs)", config->run_count);
1339 	fprintf(output, ":\n\n");
1340 
1341 	if (config->metric_only)
1342 		print_metric_headers(config, evlist, false);
1343 }
1344 
1345 static void print_header_csv(struct perf_stat_config *config,
1346 			     struct target *_target __maybe_unused,
1347 			     struct evlist *evlist,
1348 			     int argc __maybe_unused,
1349 			     const char **argv __maybe_unused)
1350 {
1351 	if (config->metric_only)
1352 		print_metric_headers(config, evlist, true);
1353 }
1354 static void print_header_json(struct perf_stat_config *config,
1355 			      struct target *_target __maybe_unused,
1356 			      struct evlist *evlist,
1357 			      int argc __maybe_unused,
1358 			      const char **argv __maybe_unused)
1359 {
1360 	if (config->metric_only)
1361 		print_metric_headers(config, evlist, true);
1362 }
1363 
1364 static void print_header(struct perf_stat_config *config,
1365 			 struct target *_target,
1366 			 struct evlist *evlist,
1367 			 int argc, const char **argv)
1368 {
1369 	static int num_print_iv;
1370 
1371 	fflush(stdout);
1372 
1373 	if (config->interval_clear)
1374 		puts(CONSOLE_CLEAR);
1375 
1376 	if (num_print_iv == 0 || config->interval_clear) {
1377 		if (config->json_output)
1378 			print_header_json(config, _target, evlist, argc, argv);
1379 		else if (config->csv_output)
1380 			print_header_csv(config, _target, evlist, argc, argv);
1381 		else if (config->interval)
1382 			print_header_interval_std(config, _target, evlist, argc, argv);
1383 		else
1384 			print_header_std(config, _target, evlist, argc, argv);
1385 	}
1386 
1387 	if (num_print_iv++ == 25)
1388 		num_print_iv = 0;
1389 }
1390 
1391 static void print_table(struct perf_stat_config *config, FILE *output, double avg)
1392 {
1393 	char tmp[64];
1394 	int idx, indent = 0;
1395 
1396 	scnprintf(tmp, 64, " %17.9f", avg);
1397 	while (tmp[indent] == ' ')
1398 		indent++;
1399 
1400 	fprintf(output, "%*s# Table of individual measurements:\n", indent, "");
1401 
1402 	for (idx = 0; idx < config->run_count; idx++) {
1403 		double run = (double) config->walltime_run[idx] / NSEC_PER_SEC;
1404 		int h, n = 1 + abs((int) (100.0 * (run - avg)/run) / 5);
1405 
1406 		fprintf(output, " %17.9f (%+.9f) ", run, run - avg);
1407 
1408 		for (h = 0; h < n; h++)
1409 			fprintf(output, "#");
1410 
1411 		fprintf(output, "\n");
1412 	}
1413 
1414 	fprintf(output, "\n%*s# Final result:\n", indent, "");
1415 }
1416 
1417 static double timeval2double(struct timeval *t)
1418 {
1419 	return t->tv_sec + (double) t->tv_usec/USEC_PER_SEC;
1420 }
1421 
1422 static void print_footer(struct perf_stat_config *config)
1423 {
1424 	double avg = avg_stats(config->walltime_nsecs_stats) / NSEC_PER_SEC;
1425 	FILE *output = config->output;
1426 
1427 	if (config->interval || config->csv_output || config->json_output)
1428 		return;
1429 
1430 	if (!config->null_run)
1431 		fprintf(output, "\n");
1432 
1433 	if (config->run_count == 1) {
1434 		fprintf(output, " %17.9f seconds time elapsed", avg);
1435 
1436 		if (config->ru_display) {
1437 			double ru_utime = timeval2double(&config->ru_data.ru_utime);
1438 			double ru_stime = timeval2double(&config->ru_data.ru_stime);
1439 
1440 			fprintf(output, "\n\n");
1441 			fprintf(output, " %17.9f seconds user\n", ru_utime);
1442 			fprintf(output, " %17.9f seconds sys\n", ru_stime);
1443 		}
1444 	} else {
1445 		double sd = stddev_stats(config->walltime_nsecs_stats) / NSEC_PER_SEC;
1446 
1447 		if (config->walltime_run_table)
1448 			print_table(config, output, avg);
1449 
1450 		fprintf(output, " %17.9f +- %.9f seconds time elapsed", avg, sd);
1451 
1452 		print_noise_pct(config, NULL, sd, avg, /*before_metric=*/false);
1453 	}
1454 	fprintf(output, "\n\n");
1455 
1456 	if (config->print_free_counters_hint && sysctl__nmi_watchdog_enabled())
1457 		fprintf(output,
1458 "Some events weren't counted. Try disabling the NMI watchdog:\n"
1459 "	echo 0 > /proc/sys/kernel/nmi_watchdog\n"
1460 "	perf stat ...\n"
1461 "	echo 1 > /proc/sys/kernel/nmi_watchdog\n");
1462 }
1463 
1464 static void print_percore(struct perf_stat_config *config,
1465 			  struct evsel *counter, struct outstate *os)
1466 {
1467 	bool metric_only = config->metric_only;
1468 	FILE *output = config->output;
1469 	struct cpu_aggr_map *core_map;
1470 	int aggr_idx, core_map_len = 0;
1471 
1472 	if (!config->aggr_map || !config->aggr_get_id)
1473 		return;
1474 
1475 	if (config->percore_show_thread)
1476 		return print_counter(config, counter, os);
1477 
1478 	/*
1479 	 * core_map will hold the aggr_cpu_id for the cores that have been
1480 	 * printed so that each core is printed just once.
1481 	 */
1482 	core_map = cpu_aggr_map__empty_new(config->aggr_map->nr);
1483 	if (core_map == NULL) {
1484 		fprintf(output, "Cannot allocate per-core aggr map for display\n");
1485 		return;
1486 	}
1487 
1488 	cpu_aggr_map__for_each_idx(aggr_idx, config->aggr_map) {
1489 		struct perf_cpu curr_cpu = config->aggr_map->map[aggr_idx].cpu;
1490 		struct aggr_cpu_id core_id = aggr_cpu_id__core(curr_cpu, NULL);
1491 		bool found = false;
1492 
1493 		for (int i = 0; i < core_map_len; i++) {
1494 			if (aggr_cpu_id__equal(&core_map->map[i], &core_id)) {
1495 				found = true;
1496 				break;
1497 			}
1498 		}
1499 		if (found)
1500 			continue;
1501 
1502 		print_counter_aggrdata(config, counter, aggr_idx, os);
1503 
1504 		core_map->map[core_map_len++] = core_id;
1505 	}
1506 	free(core_map);
1507 
1508 	if (metric_only)
1509 		fputc('\n', output);
1510 }
1511 
1512 static void print_cgroup_counter(struct perf_stat_config *config, struct evlist *evlist,
1513 				 struct outstate *os)
1514 {
1515 	struct evsel *counter;
1516 
1517 	evlist__for_each_entry(evlist, counter) {
1518 		if (os->cgrp != counter->cgrp) {
1519 			if (os->cgrp != NULL)
1520 				print_metric_end(config, os);
1521 
1522 			os->cgrp = counter->cgrp;
1523 			print_metric_begin(config, evlist, os, /*aggr_idx=*/0);
1524 		}
1525 
1526 		print_counter(config, counter, os);
1527 	}
1528 	if (os->cgrp)
1529 		print_metric_end(config, os);
1530 }
1531 
1532 void evlist__print_counters(struct evlist *evlist, struct perf_stat_config *config,
1533 			    struct target *_target, struct timespec *ts,
1534 			    int argc, const char **argv)
1535 {
1536 	bool metric_only = config->metric_only;
1537 	struct evsel *counter;
1538 	struct outstate os = {
1539 		.fh = config->output,
1540 		.first = true,
1541 	};
1542 
1543 	evlist__uniquify_evsel_names(evlist, config);
1544 
1545 	if (config->iostat_run)
1546 		evlist->selected = evlist__first(evlist);
1547 
1548 	if (config->interval)
1549 		prepare_timestamp(config, &os, ts);
1550 
1551 	print_header(config, _target, evlist, argc, argv);
1552 
1553 	switch (config->aggr_mode) {
1554 	case AGGR_CORE:
1555 	case AGGR_CACHE:
1556 	case AGGR_CLUSTER:
1557 	case AGGR_DIE:
1558 	case AGGR_SOCKET:
1559 	case AGGR_NODE:
1560 		if (config->cgroup_list)
1561 			print_aggr_cgroup(config, evlist, &os);
1562 		else
1563 			print_aggr(config, evlist, &os);
1564 		break;
1565 	case AGGR_THREAD:
1566 	case AGGR_GLOBAL:
1567 		if (config->iostat_run) {
1568 			iostat_print_counters(evlist, config, ts, os.timestamp,
1569 					      (iostat_print_counter_t)print_counter, &os);
1570 		} else if (config->cgroup_list) {
1571 			print_cgroup_counter(config, evlist, &os);
1572 		} else {
1573 			print_metric_begin(config, evlist, &os, /*aggr_idx=*/0);
1574 			evlist__for_each_entry(evlist, counter) {
1575 				print_counter(config, counter, &os);
1576 			}
1577 			print_metric_end(config, &os);
1578 		}
1579 		break;
1580 	case AGGR_NONE:
1581 		if (metric_only)
1582 			print_no_aggr_metric(config, evlist, &os);
1583 		else {
1584 			evlist__for_each_entry(evlist, counter) {
1585 				if (counter->percore)
1586 					print_percore(config, counter, &os);
1587 				else
1588 					print_counter(config, counter, &os);
1589 			}
1590 		}
1591 		break;
1592 	case AGGR_MAX:
1593 	case AGGR_UNSET:
1594 	default:
1595 		break;
1596 	}
1597 
1598 	print_footer(config);
1599 
1600 	fflush(config->output);
1601 }
1602