xref: /linux/tools/perf/builtin-diff.c (revision 390d5ea26622f794c2d29cefd5a01ef116b4fe1d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * builtin-diff.c
4  *
5  * Builtin diff command: Analyze two perf.data input files, look up and read
6  * DSOs and symbol information, sort them and produce a diff.
7  */
8 #include "builtin.h"
9 #include "perf.h"
10 
11 #include "util/debug.h"
12 #include "util/event.h"
13 #include "util/hist.h"
14 #include "util/evsel.h"
15 #include "util/evlist.h"
16 #include "util/session.h"
17 #include "util/tool.h"
18 #include "util/sort.h"
19 #include "util/srcline.h"
20 #include "util/symbol.h"
21 #include "util/data.h"
22 #include "util/config.h"
23 #include "util/time-utils.h"
24 #include "util/annotate.h"
25 #include "util/map.h"
26 #include "util/spark.h"
27 #include "util/block-info.h"
28 #include "util/stream.h"
29 #include "util/util.h"
30 #include <linux/err.h>
31 #include <linux/zalloc.h>
32 #include <subcmd/pager.h>
33 #include <subcmd/parse-options.h>
34 
35 #include <errno.h>
36 #include <inttypes.h>
37 #include <stdlib.h>
38 #include <math.h>
39 
40 struct perf_diff {
41 	struct perf_tool		 tool;
42 	const char			*time_str;
43 	struct perf_time_interval	*ptime_range;
44 	int				 range_size;
45 	int				 range_num;
46 	bool				 has_br_stack;
47 	bool				 stream;
48 };
49 
50 /* Diff command specific HPP columns. */
51 enum {
52 	PERF_HPP_DIFF__BASELINE,
53 	PERF_HPP_DIFF__PERIOD,
54 	PERF_HPP_DIFF__PERIOD_BASELINE,
55 	PERF_HPP_DIFF__DELTA,
56 	PERF_HPP_DIFF__RATIO,
57 	PERF_HPP_DIFF__WEIGHTED_DIFF,
58 	PERF_HPP_DIFF__FORMULA,
59 	PERF_HPP_DIFF__DELTA_ABS,
60 	PERF_HPP_DIFF__CYCLES,
61 	PERF_HPP_DIFF__CYCLES_HIST,
62 
63 	PERF_HPP_DIFF__MAX_INDEX
64 };
65 
66 struct diff_hpp_fmt {
67 	struct perf_hpp_fmt	 fmt;
68 	int			 idx;
69 	char			*header;
70 	int			 header_width;
71 };
72 
73 struct data__file {
74 	struct perf_session	*session;
75 	struct perf_data	 data;
76 	int			 idx;
77 	struct hists		*hists;
78 	struct evlist_streams	*evlist_streams;
79 	struct diff_hpp_fmt	 fmt[PERF_HPP_DIFF__MAX_INDEX];
80 };
81 
82 static struct data__file *data__files;
83 static int data__files_cnt;
84 
85 #define data__for_each_file_start(i, d, s)	\
86 	for (i = s, d = &data__files[s];	\
87 	     i < data__files_cnt;		\
88 	     i++, d = &data__files[i])
89 
90 #define data__for_each_file(i, d) data__for_each_file_start(i, d, 0)
91 #define data__for_each_file_new(i, d) data__for_each_file_start(i, d, 1)
92 
93 static bool force;
94 static bool show_period;
95 static bool show_formula;
96 static bool show_baseline_only;
97 static bool cycles_hist;
98 static unsigned int sort_compute = 1;
99 
100 static s64 compute_wdiff_w1;
101 static s64 compute_wdiff_w2;
102 
103 static const char		*cpu_list;
104 static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
105 
106 enum {
107 	COMPUTE_DELTA,
108 	COMPUTE_RATIO,
109 	COMPUTE_WEIGHTED_DIFF,
110 	COMPUTE_DELTA_ABS,
111 	COMPUTE_CYCLES,
112 	COMPUTE_MAX,
113 	COMPUTE_STREAM,	/* After COMPUTE_MAX to avoid use current compute arrays */
114 };
115 
116 static const char *compute_names[COMPUTE_MAX] = {
117 	[COMPUTE_DELTA] = "delta",
118 	[COMPUTE_DELTA_ABS] = "delta-abs",
119 	[COMPUTE_RATIO] = "ratio",
120 	[COMPUTE_WEIGHTED_DIFF] = "wdiff",
121 	[COMPUTE_CYCLES] = "cycles",
122 };
123 
124 static int compute = COMPUTE_DELTA_ABS;
125 
126 static int compute_2_hpp[COMPUTE_MAX] = {
127 	[COMPUTE_DELTA]		= PERF_HPP_DIFF__DELTA,
128 	[COMPUTE_DELTA_ABS]	= PERF_HPP_DIFF__DELTA_ABS,
129 	[COMPUTE_RATIO]		= PERF_HPP_DIFF__RATIO,
130 	[COMPUTE_WEIGHTED_DIFF]	= PERF_HPP_DIFF__WEIGHTED_DIFF,
131 	[COMPUTE_CYCLES]	= PERF_HPP_DIFF__CYCLES,
132 };
133 
134 #define MAX_COL_WIDTH 70
135 
136 static struct header_column {
137 	const char *name;
138 	int width;
139 } columns[PERF_HPP_DIFF__MAX_INDEX] = {
140 	[PERF_HPP_DIFF__BASELINE] = {
141 		.name  = "Baseline",
142 	},
143 	[PERF_HPP_DIFF__PERIOD] = {
144 		.name  = "Period",
145 		.width = 14,
146 	},
147 	[PERF_HPP_DIFF__PERIOD_BASELINE] = {
148 		.name  = "Base period",
149 		.width = 14,
150 	},
151 	[PERF_HPP_DIFF__DELTA] = {
152 		.name  = "Delta",
153 		.width = 7,
154 	},
155 	[PERF_HPP_DIFF__DELTA_ABS] = {
156 		.name  = "Delta Abs",
157 		.width = 7,
158 	},
159 	[PERF_HPP_DIFF__RATIO] = {
160 		.name  = "Ratio",
161 		.width = 14,
162 	},
163 	[PERF_HPP_DIFF__WEIGHTED_DIFF] = {
164 		.name  = "Weighted diff",
165 		.width = 14,
166 	},
167 	[PERF_HPP_DIFF__FORMULA] = {
168 		.name  = "Formula",
169 		.width = MAX_COL_WIDTH,
170 	},
171 	[PERF_HPP_DIFF__CYCLES] = {
172 		.name  = "[Program Block Range] Cycles Diff",
173 		.width = 70,
174 	},
175 	[PERF_HPP_DIFF__CYCLES_HIST] = {
176 		.name  = "stddev/Hist",
177 		.width = NUM_SPARKS + 9,
178 	}
179 };
180 
181 static int setup_compute_opt_wdiff(const char *opt)
182 {
183 	const char *w1_str = opt, *w2_str;
184 
185 	int ret = -EINVAL;
186 
187 	if (!opt)
188 		goto out;
189 
190 	w2_str = strchr(opt, ',');
191 	if (!w2_str)
192 		goto out;
193 
194 	if (!*++w2_str)
195 		goto out;
196 
197 	compute_wdiff_w1 = strtol(w1_str, NULL, 10);
198 	compute_wdiff_w2 = strtol(w2_str, NULL, 10);
199 
200 	if (!compute_wdiff_w1 || !compute_wdiff_w2)
201 		goto out;
202 
203 	pr_debug("compute wdiff w1(%" PRId64 ") w2(%" PRId64 ")\n",
204 		  compute_wdiff_w1, compute_wdiff_w2);
205 
206 	ret = 0;
207 
208  out:
209 	if (ret)
210 		pr_err("Failed: wrong weight data, use 'wdiff:w1,w2'\n");
211 
212 	return ret;
213 }
214 
215 static int setup_compute_opt(const char *opt)
216 {
217 	if (compute == COMPUTE_WEIGHTED_DIFF)
218 		return setup_compute_opt_wdiff(opt);
219 
220 	if (opt) {
221 		pr_err("Failed: extra option specified '%s'", opt);
222 		return -EINVAL;
223 	}
224 
225 	return 0;
226 }
227 
228 static int setup_compute(const struct option *opt, const char *str,
229 			 int unset __maybe_unused)
230 {
231 	int *cp = (int *) opt->value;
232 	char *cstr = (char *) str;
233 	char buf[50];
234 	unsigned i;
235 	const char *option;
236 
237 	if (!str) {
238 		*cp = COMPUTE_DELTA;
239 		return 0;
240 	}
241 
242 	option = strchr(str, ':');
243 	if (option) {
244 		unsigned len = option++ - str;
245 
246 		/*
247 		 * The str data are not writeable, so we need
248 		 * to use another buffer.
249 		 */
250 
251 		/* No option value is longer. */
252 		if (len >= sizeof(buf))
253 			return -EINVAL;
254 
255 		strncpy(buf, str, len);
256 		buf[len] = 0x0;
257 		cstr = buf;
258 	}
259 
260 	for (i = 0; i < COMPUTE_MAX; i++)
261 		if (!strcmp(cstr, compute_names[i])) {
262 			*cp = i;
263 			return setup_compute_opt(option);
264 		}
265 
266 	pr_err("Failed: '%s' is not computation method "
267 	       "(use 'delta','ratio' or 'wdiff')\n", str);
268 	return -EINVAL;
269 }
270 
271 static double period_percent(struct hist_entry *he, u64 period)
272 {
273 	u64 total = hists__total_period(he->hists);
274 
275 	return (period * 100.0) / total;
276 }
277 
278 static double compute_delta(struct hist_entry *he, struct hist_entry *pair)
279 {
280 	double old_percent = period_percent(he, he->stat.period);
281 	double new_percent = period_percent(pair, pair->stat.period);
282 
283 	pair->diff.period_ratio_delta = new_percent - old_percent;
284 	pair->diff.computed = true;
285 	return pair->diff.period_ratio_delta;
286 }
287 
288 static double compute_ratio(struct hist_entry *he, struct hist_entry *pair)
289 {
290 	double old_period = he->stat.period ?: 1;
291 	double new_period = pair->stat.period;
292 
293 	pair->diff.computed = true;
294 	pair->diff.period_ratio = new_period / old_period;
295 	return pair->diff.period_ratio;
296 }
297 
298 static s64 compute_wdiff(struct hist_entry *he, struct hist_entry *pair)
299 {
300 	u64 old_period = he->stat.period;
301 	u64 new_period = pair->stat.period;
302 
303 	pair->diff.computed = true;
304 	pair->diff.wdiff = new_period * compute_wdiff_w2 -
305 			   old_period * compute_wdiff_w1;
306 
307 	return pair->diff.wdiff;
308 }
309 
310 static int formula_delta(struct hist_entry *he, struct hist_entry *pair,
311 			 char *buf, size_t size)
312 {
313 	u64 he_total = he->hists->stats.total_period;
314 	u64 pair_total = pair->hists->stats.total_period;
315 
316 	if (symbol_conf.filter_relative) {
317 		he_total = he->hists->stats.total_non_filtered_period;
318 		pair_total = pair->hists->stats.total_non_filtered_period;
319 	}
320 	return scnprintf(buf, size,
321 			 "(%" PRIu64 " * 100 / %" PRIu64 ") - "
322 			 "(%" PRIu64 " * 100 / %" PRIu64 ")",
323 			 pair->stat.period, pair_total,
324 			 he->stat.period, he_total);
325 }
326 
327 static int formula_ratio(struct hist_entry *he, struct hist_entry *pair,
328 			 char *buf, size_t size)
329 {
330 	double old_period = he->stat.period;
331 	double new_period = pair->stat.period;
332 
333 	return scnprintf(buf, size, "%.0F / %.0F", new_period, old_period);
334 }
335 
336 static int formula_wdiff(struct hist_entry *he, struct hist_entry *pair,
337 			 char *buf, size_t size)
338 {
339 	u64 old_period = he->stat.period;
340 	u64 new_period = pair->stat.period;
341 
342 	return scnprintf(buf, size,
343 		  "(%" PRIu64 " * " "%" PRId64 ") - (%" PRIu64 " * " "%" PRId64 ")",
344 		  new_period, compute_wdiff_w2, old_period, compute_wdiff_w1);
345 }
346 
347 static int formula_fprintf(struct hist_entry *he, struct hist_entry *pair,
348 			   char *buf, size_t size)
349 {
350 	switch (compute) {
351 	case COMPUTE_DELTA:
352 	case COMPUTE_DELTA_ABS:
353 		return formula_delta(he, pair, buf, size);
354 	case COMPUTE_RATIO:
355 		return formula_ratio(he, pair, buf, size);
356 	case COMPUTE_WEIGHTED_DIFF:
357 		return formula_wdiff(he, pair, buf, size);
358 	default:
359 		BUG_ON(1);
360 	}
361 
362 	return -1;
363 }
364 
365 static void *block_hist_zalloc(size_t size)
366 {
367 	struct block_hist *bh;
368 
369 	bh = zalloc(size + sizeof(*bh));
370 	if (!bh)
371 		return NULL;
372 
373 	return &bh->he;
374 }
375 
376 static void block_hist_free(void *he)
377 {
378 	struct block_hist *bh;
379 
380 	bh = container_of(he, struct block_hist, he);
381 	hists__delete_entries(&bh->block_hists);
382 	free(bh);
383 }
384 
385 static struct hist_entry_ops block_hist_ops = {
386 	.new    = block_hist_zalloc,
387 	.free   = block_hist_free,
388 };
389 
390 static int diff__process_sample_event(const struct perf_tool *tool,
391 				      union perf_event *event,
392 				      struct perf_sample *sample,
393 				      struct machine *machine)
394 {
395 	struct perf_diff *pdiff = container_of(tool, struct perf_diff, tool);
396 	struct addr_location al;
397 	struct evsel *evsel = sample->evsel;
398 	struct hists *hists = evsel__hists(evsel);
399 	struct hist_entry_iter iter = {
400 		.sample	= sample,
401 		.ops	= &hist_iter_normal,
402 	};
403 	int ret = -1;
404 
405 	if (perf_time__ranges_skip_sample(pdiff->ptime_range, pdiff->range_num,
406 					  sample->time)) {
407 		return 0;
408 	}
409 
410 	addr_location__init(&al);
411 	if (machine__resolve(machine, &al, sample) < 0) {
412 		pr_warning("problem processing %d event, skipping it.\n",
413 			   event->header.type);
414 		ret = -1;
415 		goto out;
416 	}
417 
418 	if (cpu_list && !test_bit(sample->cpu, cpu_bitmap)) {
419 		ret = 0;
420 		goto out;
421 	}
422 
423 	switch (compute) {
424 	case COMPUTE_CYCLES:
425 		if (!hists__add_entry_ops(hists, &block_hist_ops, &al, NULL,
426 					  NULL, NULL, NULL, sample, true)) {
427 			pr_warning("problem incrementing symbol period, "
428 				   "skipping event\n");
429 			goto out;
430 		}
431 
432 		hist__account_cycles(sample->branch_stack, &al, sample,
433 				     /*nonany_branch_mode=*/false, /*total_cycles=*/NULL);
434 		break;
435 
436 	case COMPUTE_STREAM:
437 		if (hist_entry_iter__add(&iter, &al, PERF_MAX_STACK_DEPTH,
438 					 NULL)) {
439 			pr_debug("problem adding hist entry, skipping event\n");
440 			goto out;
441 		}
442 		break;
443 
444 	default:
445 		if (!hists__add_entry(hists, &al, NULL, NULL, NULL, NULL, sample,
446 				      true)) {
447 			pr_warning("problem incrementing symbol period, "
448 				   "skipping event\n");
449 			goto out;
450 		}
451 	}
452 
453 	/*
454 	 * The total_period is updated here before going to the output
455 	 * tree since normally only the baseline hists will call
456 	 * hists__output_resort() and precompute needs the total
457 	 * period in order to sort entries by percentage delta.
458 	 */
459 	hists->stats.total_period += sample->period;
460 	if (!al.filtered)
461 		hists->stats.total_non_filtered_period += sample->period;
462 	ret = 0;
463 out:
464 	addr_location__exit(&al);
465 	return ret;
466 }
467 
468 static struct perf_diff pdiff;
469 
470 static struct evsel *evsel_match(struct evsel *evsel, struct evlist *evlist)
471 {
472 	struct evsel *e;
473 
474 	evlist__for_each_entry(evlist, e) {
475 		if ((evsel->core.attr.type == e->core.attr.type) &&
476 		    (evsel->core.attr.config == e->core.attr.config))
477 			return e;
478 	}
479 
480 	return NULL;
481 }
482 
483 static void evlist__collapse_resort(struct evlist *evlist)
484 {
485 	struct evsel *evsel;
486 
487 	evlist__for_each_entry(evlist, evsel) {
488 		struct hists *hists = evsel__hists(evsel);
489 
490 		hists__collapse_resort(hists, NULL);
491 	}
492 }
493 
494 static struct data__file *fmt_to_data_file(struct perf_hpp_fmt *fmt)
495 {
496 	struct diff_hpp_fmt *dfmt = container_of(fmt, struct diff_hpp_fmt, fmt);
497 	void *ptr = dfmt - dfmt->idx;
498 	struct data__file *d = container_of(ptr, struct data__file, fmt);
499 
500 	return d;
501 }
502 
503 static struct hist_entry*
504 get_pair_data(struct hist_entry *he, struct data__file *d)
505 {
506 	if (hist_entry__has_pairs(he)) {
507 		struct hist_entry *pair;
508 
509 		list_for_each_entry(pair, &he->pairs.head, pairs.node)
510 			if (pair->hists == d->hists)
511 				return pair;
512 	}
513 
514 	return NULL;
515 }
516 
517 static struct hist_entry*
518 get_pair_fmt(struct hist_entry *he, struct diff_hpp_fmt *dfmt)
519 {
520 	struct data__file *d = fmt_to_data_file(&dfmt->fmt);
521 
522 	return get_pair_data(he, d);
523 }
524 
525 static void hists__baseline_only(struct hists *hists)
526 {
527 	struct rb_root_cached *root;
528 	struct rb_node *next;
529 
530 	if (hists__has(hists, need_collapse))
531 		root = &hists->entries_collapsed;
532 	else
533 		root = hists->entries_in;
534 
535 	next = rb_first_cached(root);
536 	while (next != NULL) {
537 		struct hist_entry *he = rb_entry(next, struct hist_entry, rb_node_in);
538 
539 		next = rb_next(&he->rb_node_in);
540 		if (!hist_entry__next_pair(he)) {
541 			rb_erase_cached(&he->rb_node_in, root);
542 			hist_entry__delete(he);
543 		}
544 	}
545 }
546 
547 static int64_t block_cycles_diff_cmp(struct hist_entry *left,
548 				     struct hist_entry *right)
549 {
550 	bool pairs_left  = hist_entry__has_pairs(left);
551 	bool pairs_right = hist_entry__has_pairs(right);
552 	s64 l, r;
553 
554 	if (!pairs_left && !pairs_right)
555 		return 0;
556 
557 	l = llabs(left->diff.cycles);
558 	r = llabs(right->diff.cycles);
559 	return r - l;
560 }
561 
562 static int64_t block_sort(struct perf_hpp_fmt *fmt __maybe_unused,
563 			  struct hist_entry *left, struct hist_entry *right)
564 {
565 	return block_cycles_diff_cmp(right, left);
566 }
567 
568 static void init_block_hist(struct block_hist *bh)
569 {
570 	__hists__init(&bh->block_hists, &bh->block_list);
571 	perf_hpp_list__init(&bh->block_list);
572 
573 	INIT_LIST_HEAD(&bh->block_fmt.list);
574 	INIT_LIST_HEAD(&bh->block_fmt.sort_list);
575 	bh->block_fmt.cmp = block_info__cmp;
576 	bh->block_fmt.sort = block_sort;
577 	perf_hpp_list__register_sort_field(&bh->block_list,
578 					   &bh->block_fmt);
579 	bh->valid = true;
580 }
581 
582 static struct hist_entry *get_block_pair(struct hist_entry *he,
583 					 struct hists *hists_pair)
584 {
585 	struct rb_root_cached *root = hists_pair->entries_in;
586 	struct rb_node *next = rb_first_cached(root);
587 	int64_t cmp;
588 
589 	while (next != NULL) {
590 		struct hist_entry *he_pair = rb_entry(next, struct hist_entry,
591 						      rb_node_in);
592 
593 		next = rb_next(&he_pair->rb_node_in);
594 
595 		cmp = __block_info__cmp(he_pair, he);
596 		if (!cmp)
597 			return he_pair;
598 	}
599 
600 	return NULL;
601 }
602 
603 static void init_spark_values(unsigned long *svals, int num)
604 {
605 	for (int i = 0; i < num; i++)
606 		svals[i] = 0;
607 }
608 
609 static void update_spark_value(unsigned long *svals, int num,
610 			       struct stats *stats, u64 val)
611 {
612 	int n = stats->n;
613 
614 	if (n < num)
615 		svals[n] = val;
616 }
617 
618 static void compute_cycles_diff(struct hist_entry *he,
619 				struct hist_entry *pair)
620 {
621 	pair->diff.computed = true;
622 	if (pair->block_info->num && he->block_info->num) {
623 		pair->diff.cycles =
624 			pair->block_info->cycles_aggr / pair->block_info->num_aggr -
625 			he->block_info->cycles_aggr / he->block_info->num_aggr;
626 
627 		if (!cycles_hist)
628 			return;
629 
630 		init_stats(&pair->diff.stats);
631 		init_spark_values(pair->diff.svals, NUM_SPARKS);
632 
633 		for (int i = 0; i < pair->block_info->num; i++) {
634 			u64 val;
635 
636 			if (i >= he->block_info->num || i >= NUM_SPARKS)
637 				break;
638 
639 			val = llabs(pair->block_info->cycles_spark[i] -
640 				     he->block_info->cycles_spark[i]);
641 
642 			update_spark_value(pair->diff.svals, NUM_SPARKS,
643 					   &pair->diff.stats, val);
644 			update_stats(&pair->diff.stats, val);
645 		}
646 	}
647 }
648 
649 static void block_hists_match(struct hists *hists_base,
650 			      struct hists *hists_pair)
651 {
652 	struct rb_root_cached *root = hists_base->entries_in;
653 	struct rb_node *next = rb_first_cached(root);
654 
655 	while (next != NULL) {
656 		struct hist_entry *he = rb_entry(next, struct hist_entry,
657 						 rb_node_in);
658 		struct hist_entry *pair = get_block_pair(he, hists_pair);
659 
660 		next = rb_next(&he->rb_node_in);
661 
662 		if (pair) {
663 			hist_entry__add_pair(pair, he);
664 			compute_cycles_diff(he, pair);
665 		}
666 	}
667 }
668 
669 static void hists__precompute(struct hists *hists)
670 {
671 	struct rb_root_cached *root;
672 	struct rb_node *next;
673 
674 	if (hists__has(hists, need_collapse))
675 		root = &hists->entries_collapsed;
676 	else
677 		root = hists->entries_in;
678 
679 	next = rb_first_cached(root);
680 	while (next != NULL) {
681 		struct block_hist *bh, *pair_bh;
682 		struct hist_entry *he, *pair;
683 		struct data__file *d;
684 		int i;
685 
686 		he   = rb_entry(next, struct hist_entry, rb_node_in);
687 		next = rb_next(&he->rb_node_in);
688 
689 		if (compute == COMPUTE_CYCLES) {
690 			bh = container_of(he, struct block_hist, he);
691 			init_block_hist(bh);
692 			block_info__process_sym(he, bh, NULL, 0, 0);
693 		}
694 
695 		data__for_each_file_new(i, d) {
696 			pair = get_pair_data(he, d);
697 			if (!pair)
698 				continue;
699 
700 			switch (compute) {
701 			case COMPUTE_DELTA:
702 			case COMPUTE_DELTA_ABS:
703 				compute_delta(he, pair);
704 				break;
705 			case COMPUTE_RATIO:
706 				compute_ratio(he, pair);
707 				break;
708 			case COMPUTE_WEIGHTED_DIFF:
709 				compute_wdiff(he, pair);
710 				break;
711 			case COMPUTE_CYCLES:
712 				pair_bh = container_of(pair, struct block_hist,
713 						       he);
714 				init_block_hist(pair_bh);
715 				block_info__process_sym(pair, pair_bh, NULL, 0, 0);
716 
717 				bh = container_of(he, struct block_hist, he);
718 
719 				if (bh->valid && pair_bh->valid) {
720 					block_hists_match(&bh->block_hists,
721 							  &pair_bh->block_hists);
722 					hists__output_resort(&pair_bh->block_hists,
723 							     NULL);
724 				}
725 				break;
726 			default:
727 				BUG_ON(1);
728 			}
729 		}
730 	}
731 }
732 
733 static int64_t cmp_doubles(double l, double r)
734 {
735 	if (l > r)
736 		return -1;
737 	else if (l < r)
738 		return 1;
739 	else
740 		return 0;
741 }
742 
743 static int64_t
744 __hist_entry__cmp_compute(struct hist_entry *left, struct hist_entry *right,
745 			int c)
746 {
747 	switch (c) {
748 	case COMPUTE_DELTA:
749 	{
750 		double l = left->diff.period_ratio_delta;
751 		double r = right->diff.period_ratio_delta;
752 
753 		return cmp_doubles(l, r);
754 	}
755 	case COMPUTE_DELTA_ABS:
756 	{
757 		double l = fabs(left->diff.period_ratio_delta);
758 		double r = fabs(right->diff.period_ratio_delta);
759 
760 		return cmp_doubles(l, r);
761 	}
762 	case COMPUTE_RATIO:
763 	{
764 		double l = left->diff.period_ratio;
765 		double r = right->diff.period_ratio;
766 
767 		return cmp_doubles(l, r);
768 	}
769 	case COMPUTE_WEIGHTED_DIFF:
770 	{
771 		s64 l = left->diff.wdiff;
772 		s64 r = right->diff.wdiff;
773 
774 		return r - l;
775 	}
776 	default:
777 		BUG_ON(1);
778 	}
779 
780 	return 0;
781 }
782 
783 static int64_t
784 hist_entry__cmp_compute(struct hist_entry *left, struct hist_entry *right,
785 			int c, int sort_idx)
786 {
787 	bool pairs_left  = hist_entry__has_pairs(left);
788 	bool pairs_right = hist_entry__has_pairs(right);
789 	struct hist_entry *p_right, *p_left;
790 
791 	if (!pairs_left && !pairs_right)
792 		return 0;
793 
794 	if (!pairs_left || !pairs_right)
795 		return pairs_left ? -1 : 1;
796 
797 	p_left  = get_pair_data(left,  &data__files[sort_idx]);
798 	p_right = get_pair_data(right, &data__files[sort_idx]);
799 
800 	if (!p_left && !p_right)
801 		return 0;
802 
803 	if (!p_left || !p_right)
804 		return p_left ? -1 : 1;
805 
806 	/*
807 	 * We have 2 entries of same kind, let's
808 	 * make the data comparison.
809 	 */
810 	return __hist_entry__cmp_compute(p_left, p_right, c);
811 }
812 
813 static int64_t
814 hist_entry__cmp_compute_idx(struct hist_entry *left, struct hist_entry *right,
815 			    int c, int sort_idx)
816 {
817 	struct hist_entry *p_right, *p_left;
818 
819 	p_left  = get_pair_data(left,  &data__files[sort_idx]);
820 	p_right = get_pair_data(right, &data__files[sort_idx]);
821 
822 	if (!p_left && !p_right)
823 		return 0;
824 
825 	if (!p_left || !p_right)
826 		return p_left ? -1 : 1;
827 
828 	if (c != COMPUTE_DELTA && c != COMPUTE_DELTA_ABS) {
829 		/*
830 		 * The delta can be computed without the baseline, but
831 		 * others are not.  Put those entries which have no
832 		 * values below.
833 		 */
834 		if (left->dummy && right->dummy)
835 			return 0;
836 
837 		if (left->dummy || right->dummy)
838 			return left->dummy ? 1 : -1;
839 	}
840 
841 	return __hist_entry__cmp_compute(p_left, p_right, c);
842 }
843 
844 static int64_t
845 hist_entry__cmp_nop(struct perf_hpp_fmt *fmt __maybe_unused,
846 		    struct hist_entry *left __maybe_unused,
847 		    struct hist_entry *right __maybe_unused)
848 {
849 	return 0;
850 }
851 
852 static int64_t
853 hist_entry__cmp_baseline(struct perf_hpp_fmt *fmt __maybe_unused,
854 			 struct hist_entry *left, struct hist_entry *right)
855 {
856 	if (left->stat.period == right->stat.period)
857 		return 0;
858 	return left->stat.period > right->stat.period ? 1 : -1;
859 }
860 
861 static int64_t
862 hist_entry__cmp_delta(struct perf_hpp_fmt *fmt,
863 		      struct hist_entry *left, struct hist_entry *right)
864 {
865 	struct data__file *d = fmt_to_data_file(fmt);
866 
867 	return hist_entry__cmp_compute(right, left, COMPUTE_DELTA, d->idx);
868 }
869 
870 static int64_t
871 hist_entry__cmp_delta_abs(struct perf_hpp_fmt *fmt,
872 		      struct hist_entry *left, struct hist_entry *right)
873 {
874 	struct data__file *d = fmt_to_data_file(fmt);
875 
876 	return hist_entry__cmp_compute(right, left, COMPUTE_DELTA_ABS, d->idx);
877 }
878 
879 static int64_t
880 hist_entry__cmp_ratio(struct perf_hpp_fmt *fmt,
881 		      struct hist_entry *left, struct hist_entry *right)
882 {
883 	struct data__file *d = fmt_to_data_file(fmt);
884 
885 	return hist_entry__cmp_compute(right, left, COMPUTE_RATIO, d->idx);
886 }
887 
888 static int64_t
889 hist_entry__cmp_wdiff(struct perf_hpp_fmt *fmt,
890 		      struct hist_entry *left, struct hist_entry *right)
891 {
892 	struct data__file *d = fmt_to_data_file(fmt);
893 
894 	return hist_entry__cmp_compute(right, left, COMPUTE_WEIGHTED_DIFF, d->idx);
895 }
896 
897 static int64_t
898 hist_entry__cmp_delta_idx(struct perf_hpp_fmt *fmt __maybe_unused,
899 			  struct hist_entry *left, struct hist_entry *right)
900 {
901 	return hist_entry__cmp_compute_idx(right, left, COMPUTE_DELTA,
902 					   sort_compute);
903 }
904 
905 static int64_t
906 hist_entry__cmp_delta_abs_idx(struct perf_hpp_fmt *fmt __maybe_unused,
907 			      struct hist_entry *left, struct hist_entry *right)
908 {
909 	return hist_entry__cmp_compute_idx(right, left, COMPUTE_DELTA_ABS,
910 					   sort_compute);
911 }
912 
913 static int64_t
914 hist_entry__cmp_ratio_idx(struct perf_hpp_fmt *fmt __maybe_unused,
915 			  struct hist_entry *left, struct hist_entry *right)
916 {
917 	return hist_entry__cmp_compute_idx(right, left, COMPUTE_RATIO,
918 					   sort_compute);
919 }
920 
921 static int64_t
922 hist_entry__cmp_wdiff_idx(struct perf_hpp_fmt *fmt __maybe_unused,
923 			  struct hist_entry *left, struct hist_entry *right)
924 {
925 	return hist_entry__cmp_compute_idx(right, left, COMPUTE_WEIGHTED_DIFF,
926 					   sort_compute);
927 }
928 
929 static void hists__process(struct hists *hists)
930 {
931 	if (show_baseline_only)
932 		hists__baseline_only(hists);
933 
934 	hists__precompute(hists);
935 	hists__output_resort(hists, NULL);
936 
937 	if (compute == COMPUTE_CYCLES)
938 		symbol_conf.report_block = true;
939 
940 	hists__fprintf(hists, !quiet, 0, 0, 0, stdout,
941 		       !symbol_conf.use_callchain);
942 }
943 
944 static void data__fprintf(void)
945 {
946 	struct data__file *d;
947 	int i;
948 
949 	fprintf(stdout, "# Data files:\n");
950 
951 	data__for_each_file(i, d)
952 		fprintf(stdout, "#  [%d] %s %s\n",
953 			d->idx, d->data.path,
954 			!d->idx ? "(Baseline)" : "");
955 
956 	fprintf(stdout, "#\n");
957 }
958 
959 static void data_process(void)
960 {
961 	struct evlist *evlist_base = data__files[0].session->evlist;
962 	struct evsel *evsel_base;
963 	bool first = true;
964 
965 	evlist__for_each_entry(evlist_base, evsel_base) {
966 		struct hists *hists_base = evsel__hists(evsel_base);
967 		struct data__file *d;
968 		int i;
969 
970 		data__for_each_file_new(i, d) {
971 			struct evlist *evlist = d->session->evlist;
972 			struct evsel *evsel;
973 			struct hists *hists;
974 
975 			evsel = evsel_match(evsel_base, evlist);
976 			if (!evsel)
977 				continue;
978 
979 			hists = evsel__hists(evsel);
980 			d->hists = hists;
981 
982 			hists__match(hists_base, hists);
983 
984 			if (!show_baseline_only)
985 				hists__link(hists_base, hists);
986 		}
987 
988 		if (!quiet) {
989 			fprintf(stdout, "%s# Event '%s'\n#\n", first ? "" : "\n",
990 				evsel__name(evsel_base));
991 		}
992 
993 		first = false;
994 
995 		if (verbose > 0 || ((data__files_cnt > 2) && !quiet))
996 			data__fprintf();
997 
998 		/* Don't sort callchain for perf diff */
999 		evsel__reset_sample_bit(evsel_base, CALLCHAIN);
1000 
1001 		hists__process(hists_base);
1002 	}
1003 }
1004 
1005 static int process_base_stream(struct data__file *data_base,
1006 			       struct data__file *data_pair,
1007 			       const char *title __maybe_unused)
1008 {
1009 	struct evlist *evlist_base = data_base->session->evlist;
1010 	struct evlist *evlist_pair = data_pair->session->evlist;
1011 	struct evsel *evsel_base, *evsel_pair;
1012 	struct evsel_streams *es_base, *es_pair;
1013 
1014 	evlist__for_each_entry(evlist_base, evsel_base) {
1015 		evsel_pair = evsel_match(evsel_base, evlist_pair);
1016 		if (!evsel_pair)
1017 			continue;
1018 
1019 		es_base = evsel_streams__entry(data_base->evlist_streams,
1020 					       evsel_base);
1021 		if (!es_base)
1022 			return -1;
1023 
1024 		es_pair = evsel_streams__entry(data_pair->evlist_streams,
1025 					       evsel_pair);
1026 		if (!es_pair)
1027 			return -1;
1028 
1029 		evsel_streams__match(es_base, es_pair);
1030 		evsel_streams__report(es_base, es_pair);
1031 	}
1032 
1033 	return 0;
1034 }
1035 
1036 static void stream_process(void)
1037 {
1038 	/*
1039 	 * Stream comparison only supports two data files.
1040 	 * perf.data.old and perf.data. data__files[0] is perf.data.old,
1041 	 * data__files[1] is perf.data.
1042 	 */
1043 	process_base_stream(&data__files[0], &data__files[1],
1044 			    "# Output based on old perf data:\n#\n");
1045 }
1046 
1047 static void data__free(struct data__file *d)
1048 {
1049 	int col;
1050 
1051 	if (d->evlist_streams)
1052 		evlist_streams__delete(d->evlist_streams);
1053 
1054 	for (col = 0; col < PERF_HPP_DIFF__MAX_INDEX; col++) {
1055 		struct diff_hpp_fmt *fmt = &d->fmt[col];
1056 
1057 		zfree(&fmt->header);
1058 	}
1059 }
1060 
1061 static int abstime_str_dup(char **pstr)
1062 {
1063 	char *str = NULL;
1064 
1065 	if (pdiff.time_str && strchr(pdiff.time_str, ':')) {
1066 		str = strdup(pdiff.time_str);
1067 		if (!str)
1068 			return -ENOMEM;
1069 	}
1070 
1071 	*pstr = str;
1072 	return 0;
1073 }
1074 
1075 static int parse_absolute_time(struct data__file *d, char **pstr)
1076 {
1077 	char *p = *pstr;
1078 	int ret;
1079 
1080 	/*
1081 	 * Absolute timestamp for one file has the format: a.b,c.d
1082 	 * For multiple files, the format is: a.b,c.d:a.b,c.d
1083 	 */
1084 	p = strchr(*pstr, ':');
1085 	if (p) {
1086 		if (p == *pstr) {
1087 			pr_err("Invalid time string\n");
1088 			return -EINVAL;
1089 		}
1090 
1091 		*p = 0;
1092 		p++;
1093 		if (*p == 0) {
1094 			pr_err("Invalid time string\n");
1095 			return -EINVAL;
1096 		}
1097 	}
1098 
1099 	ret = perf_time__parse_for_ranges(*pstr, d->session,
1100 					  &pdiff.ptime_range,
1101 					  &pdiff.range_size,
1102 					  &pdiff.range_num);
1103 	if (ret < 0)
1104 		return ret;
1105 
1106 	if (!p || *p == 0)
1107 		*pstr = NULL;
1108 	else
1109 		*pstr = p;
1110 
1111 	return ret;
1112 }
1113 
1114 static int parse_percent_time(struct data__file *d)
1115 {
1116 	int ret;
1117 
1118 	ret = perf_time__parse_for_ranges(pdiff.time_str, d->session,
1119 					  &pdiff.ptime_range,
1120 					  &pdiff.range_size,
1121 					  &pdiff.range_num);
1122 	return ret;
1123 }
1124 
1125 static int parse_time_str(struct data__file *d, char *abstime_ostr,
1126 			   char **pabstime_tmp)
1127 {
1128 	int ret = 0;
1129 
1130 	if (abstime_ostr)
1131 		ret = parse_absolute_time(d, pabstime_tmp);
1132 	else if (pdiff.time_str)
1133 		ret = parse_percent_time(d);
1134 
1135 	return ret;
1136 }
1137 
1138 static int check_file_brstack(void)
1139 {
1140 	struct data__file *d;
1141 	bool has_br_stack;
1142 	int i;
1143 
1144 	data__for_each_file(i, d) {
1145 		d->session = perf_session__new(&d->data, &pdiff.tool);
1146 		if (IS_ERR(d->session)) {
1147 			pr_err("Failed to open %s\n", d->data.path);
1148 			return PTR_ERR(d->session);
1149 		}
1150 
1151 		has_br_stack = perf_header__has_feat(&d->session->header,
1152 						     HEADER_BRANCH_STACK);
1153 		perf_session__delete(d->session);
1154 		if (!has_br_stack)
1155 			return 0;
1156 	}
1157 
1158 	/* Set only all files having branch stacks */
1159 	pdiff.has_br_stack = true;
1160 	return 0;
1161 }
1162 
1163 static int __cmd_diff(void)
1164 {
1165 	struct data__file *d;
1166 	int ret, i;
1167 	char *abstime_ostr, *abstime_tmp;
1168 
1169 	ret = abstime_str_dup(&abstime_ostr);
1170 	if (ret)
1171 		return ret;
1172 
1173 	abstime_tmp = abstime_ostr;
1174 	ret = -EINVAL;
1175 
1176 	data__for_each_file(i, d) {
1177 		d->session = perf_session__new(&d->data, &pdiff.tool);
1178 		if (IS_ERR(d->session)) {
1179 			ret = PTR_ERR(d->session);
1180 			pr_err("Failed to open %s\n", d->data.path);
1181 			goto out_delete;
1182 		}
1183 
1184 		if (pdiff.time_str) {
1185 			ret = parse_time_str(d, abstime_ostr, &abstime_tmp);
1186 			if (ret < 0)
1187 				goto out_delete;
1188 		}
1189 
1190 		if (cpu_list) {
1191 			ret = perf_session__cpu_bitmap(d->session, cpu_list,
1192 						       cpu_bitmap);
1193 			if (ret < 0)
1194 				goto out_delete;
1195 		}
1196 
1197 		ret = perf_session__process_events(d->session);
1198 		if (ret) {
1199 			pr_err("Failed to process %s\n", d->data.path);
1200 			goto out_delete;
1201 		}
1202 
1203 		evlist__collapse_resort(d->session->evlist);
1204 
1205 		if (pdiff.ptime_range)
1206 			zfree(&pdiff.ptime_range);
1207 
1208 		if (compute == COMPUTE_STREAM) {
1209 			d->evlist_streams = evlist__create_streams(
1210 						d->session->evlist, 5);
1211 			if (!d->evlist_streams) {
1212 				ret = -ENOMEM;
1213 				goto out_delete;
1214 			}
1215 		}
1216 	}
1217 
1218 	if (compute == COMPUTE_STREAM)
1219 		stream_process();
1220 	else
1221 		data_process();
1222 
1223  out_delete:
1224 	data__for_each_file(i, d) {
1225 		if (!IS_ERR(d->session))
1226 			perf_session__delete(d->session);
1227 		data__free(d);
1228 	}
1229 
1230 	free(data__files);
1231 
1232 	if (pdiff.ptime_range)
1233 		zfree(&pdiff.ptime_range);
1234 
1235 	if (abstime_ostr)
1236 		free(abstime_ostr);
1237 
1238 	return ret;
1239 }
1240 
1241 static const char * const diff_usage[] = {
1242 	"perf diff [<options>] [old_file] [new_file]",
1243 	NULL,
1244 };
1245 
1246 static const struct option options[] = {
1247 	OPT_INCR('v', "verbose", &verbose,
1248 		    "be more verbose (show symbol address, etc)"),
1249 	OPT_BOOLEAN('q', "quiet", &quiet, "Do not show any warnings or messages"),
1250 	OPT_BOOLEAN('b', "baseline-only", &show_baseline_only,
1251 		    "Show only items with match in baseline"),
1252 	OPT_CALLBACK('c', "compute", &compute,
1253 		     "delta,delta-abs,ratio,wdiff:w1,w2 (default delta-abs),cycles",
1254 		     "Entries differential computation selection",
1255 		     setup_compute),
1256 	OPT_BOOLEAN('p', "period", &show_period,
1257 		    "Show period values."),
1258 	OPT_BOOLEAN('F', "formula", &show_formula,
1259 		    "Show formula."),
1260 	OPT_BOOLEAN(0, "cycles-hist", &cycles_hist,
1261 		    "Show cycles histogram and standard deviation "
1262 		    "- WARNING: use only with -c cycles."),
1263 	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1264 		    "dump raw trace in ASCII"),
1265 	OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
1266 	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
1267 		   "file", "kallsyms pathname"),
1268 	OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
1269 		    "load module symbols - WARNING: use only with -k and LIVE kernel"),
1270 	OPT_STRING('d', "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
1271 		   "only consider symbols in these dsos"),
1272 	OPT_STRING('C', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
1273 		   "only consider symbols in these comms"),
1274 	OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
1275 		   "only consider these symbols"),
1276 	OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1277 		   "sort by key(s): pid, comm, dso, symbol, parent, cpu, srcline, ..."
1278 		   " Please refer the man page for the complete list."),
1279 	OPT_STRING_NOEMPTY('t', "field-separator", &symbol_conf.field_sep, "separator",
1280 		   "separator for columns, no spaces will be added between "
1281 		   "columns '.' is reserved."),
1282 	OPT_CALLBACK(0, "symfs", NULL, "directory[,layout]", SYMFS_HELP,
1283 		     symbol__config_symfs),
1284 	OPT_UINTEGER('o', "order", &sort_compute, "Specify compute sorting."),
1285 	OPT_CALLBACK(0, "percentage", NULL, "relative|absolute",
1286 		     "How to display percentage of filtered entries", parse_filter_percentage),
1287 	OPT_STRING(0, "time", &pdiff.time_str, "str",
1288 		   "Time span (time percent or absolute timestamp)"),
1289 	OPT_STRING(0, "cpu", &cpu_list, "cpu", "list of cpus to profile"),
1290 	OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
1291 		   "only consider symbols in these pids"),
1292 	OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
1293 		   "only consider symbols in these tids"),
1294 	OPT_BOOLEAN(0, "stream", &pdiff.stream,
1295 		    "Enable hot streams comparison."),
1296 	OPT_END()
1297 };
1298 
1299 static double baseline_percent(struct hist_entry *he)
1300 {
1301 	u64 total = hists__total_period(he->hists);
1302 
1303 	return 100.0 * he->stat.period / total;
1304 }
1305 
1306 static int hpp__color_baseline(struct perf_hpp_fmt *fmt,
1307 			       struct perf_hpp *hpp, struct hist_entry *he)
1308 {
1309 	struct diff_hpp_fmt *dfmt =
1310 		container_of(fmt, struct diff_hpp_fmt, fmt);
1311 	double percent = baseline_percent(he);
1312 	char pfmt[20] = " ";
1313 
1314 	if (!he->dummy) {
1315 		scnprintf(pfmt, 20, "%%%d.2f%%%%", dfmt->header_width - 1);
1316 		return percent_color_snprintf(hpp->buf, hpp->size,
1317 					      pfmt, percent);
1318 	} else
1319 		return scnprintf(hpp->buf, hpp->size, "%*s",
1320 				 dfmt->header_width, pfmt);
1321 }
1322 
1323 static int hpp__entry_baseline(struct hist_entry *he, char *buf, size_t size)
1324 {
1325 	double percent = baseline_percent(he);
1326 	const char *fmt = symbol_conf.field_sep ? "%.2f" : "%6.2f%%";
1327 	int ret = 0;
1328 
1329 	if (!he->dummy)
1330 		ret = scnprintf(buf, size, fmt, percent);
1331 
1332 	return ret;
1333 }
1334 
1335 static int cycles_printf(struct hist_entry *he, struct hist_entry *pair,
1336 			 struct perf_hpp *hpp, int width)
1337 {
1338 	struct block_hist *bh = container_of(he, struct block_hist, he);
1339 	struct block_hist *bh_pair = container_of(pair, struct block_hist, he);
1340 	struct hist_entry *block_he;
1341 	struct block_info *bi;
1342 	char buf[128];
1343 	char *start_line, *end_line;
1344 
1345 	block_he = hists__get_entry(&bh_pair->block_hists, bh->block_idx);
1346 	if (!block_he) {
1347 		hpp->skip = true;
1348 		return 0;
1349 	}
1350 
1351 	/*
1352 	 * Avoid printing the warning "addr2line_init failed for ..."
1353 	 */
1354 	symbol_conf.addr2line_disable_warn = true;
1355 
1356 	bi = block_he->block_info;
1357 
1358 	start_line = map__srcline(he->ms.map, bi->sym->start + bi->start,
1359 				  he->ms.sym);
1360 
1361 	end_line = map__srcline(he->ms.map, bi->sym->start + bi->end,
1362 				he->ms.sym);
1363 
1364 	if (start_line != SRCLINE_UNKNOWN &&
1365 	    end_line != SRCLINE_UNKNOWN) {
1366 		scnprintf(buf, sizeof(buf), "[%s -> %s] %4ld",
1367 			  start_line, end_line, block_he->diff.cycles);
1368 	} else {
1369 		scnprintf(buf, sizeof(buf), "[%7lx -> %7lx] %4ld",
1370 			  bi->start, bi->end, block_he->diff.cycles);
1371 	}
1372 
1373 	zfree_srcline(&start_line);
1374 	zfree_srcline(&end_line);
1375 
1376 	return scnprintf(hpp->buf, hpp->size, "%*s", width, buf);
1377 }
1378 
1379 static int __hpp__color_compare(struct perf_hpp_fmt *fmt,
1380 				struct perf_hpp *hpp, struct hist_entry *he,
1381 				int comparison_method)
1382 {
1383 	struct diff_hpp_fmt *dfmt =
1384 		container_of(fmt, struct diff_hpp_fmt, fmt);
1385 	struct hist_entry *pair = get_pair_fmt(he, dfmt);
1386 	double diff;
1387 	s64 wdiff;
1388 	char pfmt[20] = " ";
1389 
1390 	if (!pair) {
1391 		if (comparison_method == COMPUTE_CYCLES) {
1392 			struct block_hist *bh;
1393 
1394 			bh = container_of(he, struct block_hist, he);
1395 			if (bh->block_idx)
1396 				hpp->skip = true;
1397 		}
1398 
1399 		goto no_print;
1400 	}
1401 
1402 	switch (comparison_method) {
1403 	case COMPUTE_DELTA:
1404 		if (pair->diff.computed)
1405 			diff = pair->diff.period_ratio_delta;
1406 		else
1407 			diff = compute_delta(he, pair);
1408 
1409 		scnprintf(pfmt, 20, "%%%+d.2f%%%%", dfmt->header_width - 1);
1410 		return percent_color_snprintf(hpp->buf, hpp->size,
1411 					pfmt, diff);
1412 	case COMPUTE_RATIO:
1413 		if (he->dummy)
1414 			goto dummy_print;
1415 		if (pair->diff.computed)
1416 			diff = pair->diff.period_ratio;
1417 		else
1418 			diff = compute_ratio(he, pair);
1419 
1420 		scnprintf(pfmt, 20, "%%%d.6f", dfmt->header_width);
1421 		return value_color_snprintf(hpp->buf, hpp->size,
1422 					pfmt, diff);
1423 	case COMPUTE_WEIGHTED_DIFF:
1424 		if (he->dummy)
1425 			goto dummy_print;
1426 		if (pair->diff.computed)
1427 			wdiff = pair->diff.wdiff;
1428 		else
1429 			wdiff = compute_wdiff(he, pair);
1430 
1431 		scnprintf(pfmt, 20, "%%14ld", dfmt->header_width);
1432 		return color_snprintf(hpp->buf, hpp->size,
1433 				get_percent_color(wdiff),
1434 				pfmt, wdiff);
1435 	case COMPUTE_CYCLES:
1436 		return cycles_printf(he, pair, hpp, dfmt->header_width);
1437 	default:
1438 		BUG_ON(1);
1439 	}
1440 dummy_print:
1441 	return scnprintf(hpp->buf, hpp->size, "%*s",
1442 			dfmt->header_width, "N/A");
1443 no_print:
1444 	return scnprintf(hpp->buf, hpp->size, "%*s",
1445 			dfmt->header_width, pfmt);
1446 }
1447 
1448 static int hpp__color_delta(struct perf_hpp_fmt *fmt,
1449 			struct perf_hpp *hpp, struct hist_entry *he)
1450 {
1451 	return __hpp__color_compare(fmt, hpp, he, COMPUTE_DELTA);
1452 }
1453 
1454 static int hpp__color_ratio(struct perf_hpp_fmt *fmt,
1455 			struct perf_hpp *hpp, struct hist_entry *he)
1456 {
1457 	return __hpp__color_compare(fmt, hpp, he, COMPUTE_RATIO);
1458 }
1459 
1460 static int hpp__color_wdiff(struct perf_hpp_fmt *fmt,
1461 			struct perf_hpp *hpp, struct hist_entry *he)
1462 {
1463 	return __hpp__color_compare(fmt, hpp, he, COMPUTE_WEIGHTED_DIFF);
1464 }
1465 
1466 static int hpp__color_cycles(struct perf_hpp_fmt *fmt,
1467 			     struct perf_hpp *hpp, struct hist_entry *he)
1468 {
1469 	return __hpp__color_compare(fmt, hpp, he, COMPUTE_CYCLES);
1470 }
1471 
1472 static int all_zero(unsigned long *vals, int len)
1473 {
1474 	int i;
1475 
1476 	for (i = 0; i < len; i++)
1477 		if (vals[i] != 0)
1478 			return 0;
1479 	return 1;
1480 }
1481 
1482 static int print_cycles_spark(char *bf, int size, unsigned long *svals, u64 n)
1483 {
1484 	int printed;
1485 
1486 	if (n <= 1)
1487 		return 0;
1488 
1489 	if (n > NUM_SPARKS)
1490 		n = NUM_SPARKS;
1491 	if (all_zero(svals, n))
1492 		return 0;
1493 
1494 	printed = print_spark(bf, size, svals, n);
1495 	printed += scnprintf(bf + printed, size - printed, " ");
1496 	return printed;
1497 }
1498 
1499 static int hpp__color_cycles_hist(struct perf_hpp_fmt *fmt,
1500 			    struct perf_hpp *hpp, struct hist_entry *he)
1501 {
1502 	struct diff_hpp_fmt *dfmt =
1503 		container_of(fmt, struct diff_hpp_fmt, fmt);
1504 	struct hist_entry *pair = get_pair_fmt(he, dfmt);
1505 	struct block_hist *bh = container_of(he, struct block_hist, he);
1506 	struct block_hist *bh_pair;
1507 	struct hist_entry *block_he;
1508 	char spark[32], buf[128];
1509 	double r;
1510 	int ret, pad;
1511 
1512 	if (!pair) {
1513 		if (bh->block_idx)
1514 			hpp->skip = true;
1515 
1516 		goto no_print;
1517 	}
1518 
1519 	bh_pair = container_of(pair, struct block_hist, he);
1520 
1521 	block_he = hists__get_entry(&bh_pair->block_hists, bh->block_idx);
1522 	if (!block_he) {
1523 		hpp->skip = true;
1524 		goto no_print;
1525 	}
1526 
1527 	ret = print_cycles_spark(spark, sizeof(spark), block_he->diff.svals,
1528 				 block_he->diff.stats.n);
1529 
1530 	r = rel_stddev_stats(stddev_stats(&block_he->diff.stats),
1531 			     avg_stats(&block_he->diff.stats));
1532 
1533 	if (ret) {
1534 		/*
1535 		 * Padding spaces if number of sparks less than NUM_SPARKS
1536 		 * otherwise the output is not aligned.
1537 		 */
1538 		pad = NUM_SPARKS - ((ret - 1) / 3);
1539 		scnprintf(buf, sizeof(buf), "%s%5.1f%% %s", "\u00B1", r, spark);
1540 		ret = scnprintf(hpp->buf, hpp->size, "%*s",
1541 				dfmt->header_width, buf);
1542 
1543 		if (pad) {
1544 			ret += scnprintf(hpp->buf + ret, hpp->size - ret,
1545 					 "%-*s", pad, " ");
1546 		}
1547 
1548 		return ret;
1549 	}
1550 
1551 no_print:
1552 	return scnprintf(hpp->buf, hpp->size, "%*s",
1553 			dfmt->header_width, " ");
1554 }
1555 
1556 static void
1557 hpp__entry_unpair(struct hist_entry *he, int idx, char *buf, size_t size)
1558 {
1559 	switch (idx) {
1560 	case PERF_HPP_DIFF__PERIOD_BASELINE:
1561 		scnprintf(buf, size, "%" PRIu64, he->stat.period);
1562 		break;
1563 
1564 	default:
1565 		break;
1566 	}
1567 }
1568 
1569 static void
1570 hpp__entry_pair(struct hist_entry *he, struct hist_entry *pair,
1571 		int idx, char *buf, size_t size)
1572 {
1573 	double diff;
1574 	double ratio;
1575 	s64 wdiff;
1576 
1577 	switch (idx) {
1578 	case PERF_HPP_DIFF__DELTA:
1579 	case PERF_HPP_DIFF__DELTA_ABS:
1580 		if (pair->diff.computed)
1581 			diff = pair->diff.period_ratio_delta;
1582 		else
1583 			diff = compute_delta(he, pair);
1584 
1585 		scnprintf(buf, size, "%+4.2F%%", diff);
1586 		break;
1587 
1588 	case PERF_HPP_DIFF__RATIO:
1589 		/* No point for ratio number if we are dummy.. */
1590 		if (he->dummy) {
1591 			scnprintf(buf, size, "N/A");
1592 			break;
1593 		}
1594 
1595 		if (pair->diff.computed)
1596 			ratio = pair->diff.period_ratio;
1597 		else
1598 			ratio = compute_ratio(he, pair);
1599 
1600 		if (ratio > 0.0)
1601 			scnprintf(buf, size, "%14.6F", ratio);
1602 		break;
1603 
1604 	case PERF_HPP_DIFF__WEIGHTED_DIFF:
1605 		/* No point for wdiff number if we are dummy.. */
1606 		if (he->dummy) {
1607 			scnprintf(buf, size, "N/A");
1608 			break;
1609 		}
1610 
1611 		if (pair->diff.computed)
1612 			wdiff = pair->diff.wdiff;
1613 		else
1614 			wdiff = compute_wdiff(he, pair);
1615 
1616 		if (wdiff != 0)
1617 			scnprintf(buf, size, "%14ld", wdiff);
1618 		break;
1619 
1620 	case PERF_HPP_DIFF__FORMULA:
1621 		formula_fprintf(he, pair, buf, size);
1622 		break;
1623 
1624 	case PERF_HPP_DIFF__PERIOD:
1625 		scnprintf(buf, size, "%" PRIu64, pair->stat.period);
1626 		break;
1627 
1628 	default:
1629 		BUG_ON(1);
1630 	}
1631 }
1632 
1633 static void
1634 __hpp__entry_global(struct hist_entry *he, struct diff_hpp_fmt *dfmt,
1635 		    char *buf, size_t size)
1636 {
1637 	struct hist_entry *pair = get_pair_fmt(he, dfmt);
1638 	int idx = dfmt->idx;
1639 
1640 	/* baseline is special */
1641 	if (idx == PERF_HPP_DIFF__BASELINE)
1642 		hpp__entry_baseline(he, buf, size);
1643 	else {
1644 		if (pair)
1645 			hpp__entry_pair(he, pair, idx, buf, size);
1646 		else
1647 			hpp__entry_unpair(he, idx, buf, size);
1648 	}
1649 }
1650 
1651 static int hpp__entry_global(struct perf_hpp_fmt *_fmt, struct perf_hpp *hpp,
1652 			     struct hist_entry *he)
1653 {
1654 	struct diff_hpp_fmt *dfmt =
1655 		container_of(_fmt, struct diff_hpp_fmt, fmt);
1656 	char buf[MAX_COL_WIDTH] = " ";
1657 
1658 	__hpp__entry_global(he, dfmt, buf, MAX_COL_WIDTH);
1659 
1660 	if (symbol_conf.field_sep)
1661 		return scnprintf(hpp->buf, hpp->size, "%s", buf);
1662 	else
1663 		return scnprintf(hpp->buf, hpp->size, "%*s",
1664 				 dfmt->header_width, buf);
1665 }
1666 
1667 static int hpp__header(struct perf_hpp_fmt *fmt, struct perf_hpp *hpp,
1668 		       struct hists *hists __maybe_unused,
1669 		       int line __maybe_unused,
1670 		       int *span __maybe_unused)
1671 {
1672 	struct diff_hpp_fmt *dfmt =
1673 		container_of(fmt, struct diff_hpp_fmt, fmt);
1674 
1675 	BUG_ON(!dfmt->header);
1676 	return scnprintf(hpp->buf, hpp->size, dfmt->header);
1677 }
1678 
1679 static int hpp__width(struct perf_hpp_fmt *fmt,
1680 		      struct perf_hpp *hpp __maybe_unused,
1681 		      struct hists *hists __maybe_unused)
1682 {
1683 	struct diff_hpp_fmt *dfmt =
1684 		container_of(fmt, struct diff_hpp_fmt, fmt);
1685 
1686 	BUG_ON(dfmt->header_width <= 0);
1687 	return dfmt->header_width;
1688 }
1689 
1690 static void init_header(struct data__file *d, struct diff_hpp_fmt *dfmt)
1691 {
1692 #define MAX_HEADER_NAME 100
1693 	char buf_indent[MAX_HEADER_NAME];
1694 	char buf[MAX_HEADER_NAME];
1695 	const char *header = NULL;
1696 	int width = 0;
1697 
1698 	BUG_ON(dfmt->idx >= PERF_HPP_DIFF__MAX_INDEX);
1699 	header = columns[dfmt->idx].name;
1700 	width  = columns[dfmt->idx].width;
1701 
1702 	/* Only our defined HPP fmts should appear here. */
1703 	BUG_ON(!header);
1704 
1705 	if (data__files_cnt > 2)
1706 		scnprintf(buf, MAX_HEADER_NAME, "%s/%d", header, d->idx);
1707 
1708 #define NAME (data__files_cnt > 2 ? buf : header)
1709 	dfmt->header_width = width;
1710 	width = (int) strlen(NAME);
1711 	if (dfmt->header_width < width)
1712 		dfmt->header_width = width;
1713 
1714 	scnprintf(buf_indent, MAX_HEADER_NAME, "%*s",
1715 		  dfmt->header_width, NAME);
1716 
1717 	dfmt->header = strdup(buf_indent);
1718 #undef MAX_HEADER_NAME
1719 #undef NAME
1720 }
1721 
1722 static void data__hpp_register(struct data__file *d, int idx)
1723 {
1724 	struct diff_hpp_fmt *dfmt = &d->fmt[idx];
1725 	struct perf_hpp_fmt *fmt = &dfmt->fmt;
1726 
1727 	dfmt->idx = idx;
1728 
1729 	fmt->header = hpp__header;
1730 	fmt->width  = hpp__width;
1731 	fmt->entry  = hpp__entry_global;
1732 	fmt->cmp    = hist_entry__cmp_nop;
1733 	fmt->collapse = hist_entry__cmp_nop;
1734 
1735 	/* TODO more colors */
1736 	switch (idx) {
1737 	case PERF_HPP_DIFF__BASELINE:
1738 		fmt->color = hpp__color_baseline;
1739 		fmt->sort  = hist_entry__cmp_baseline;
1740 		break;
1741 	case PERF_HPP_DIFF__DELTA:
1742 		fmt->color = hpp__color_delta;
1743 		fmt->sort  = hist_entry__cmp_delta;
1744 		break;
1745 	case PERF_HPP_DIFF__RATIO:
1746 		fmt->color = hpp__color_ratio;
1747 		fmt->sort  = hist_entry__cmp_ratio;
1748 		break;
1749 	case PERF_HPP_DIFF__WEIGHTED_DIFF:
1750 		fmt->color = hpp__color_wdiff;
1751 		fmt->sort  = hist_entry__cmp_wdiff;
1752 		break;
1753 	case PERF_HPP_DIFF__DELTA_ABS:
1754 		fmt->color = hpp__color_delta;
1755 		fmt->sort  = hist_entry__cmp_delta_abs;
1756 		break;
1757 	case PERF_HPP_DIFF__CYCLES:
1758 		fmt->color = hpp__color_cycles;
1759 		fmt->sort  = hist_entry__cmp_nop;
1760 		break;
1761 	case PERF_HPP_DIFF__CYCLES_HIST:
1762 		fmt->color = hpp__color_cycles_hist;
1763 		fmt->sort  = hist_entry__cmp_nop;
1764 		break;
1765 	default:
1766 		fmt->sort  = hist_entry__cmp_nop;
1767 		break;
1768 	}
1769 
1770 	init_header(d, dfmt);
1771 	perf_hpp__column_register(fmt);
1772 	perf_hpp__register_sort_field(fmt);
1773 }
1774 
1775 static int ui_init(void)
1776 {
1777 	struct data__file *d;
1778 	struct perf_hpp_fmt *fmt;
1779 	int i;
1780 
1781 	data__for_each_file(i, d) {
1782 
1783 		/*
1784 		 * Baseline or compute related columns:
1785 		 *
1786 		 *   PERF_HPP_DIFF__BASELINE
1787 		 *   PERF_HPP_DIFF__DELTA
1788 		 *   PERF_HPP_DIFF__RATIO
1789 		 *   PERF_HPP_DIFF__WEIGHTED_DIFF
1790 		 *   PERF_HPP_DIFF__CYCLES
1791 		 */
1792 		data__hpp_register(d, i ? compute_2_hpp[compute] :
1793 					  PERF_HPP_DIFF__BASELINE);
1794 
1795 		if (cycles_hist && i)
1796 			data__hpp_register(d, PERF_HPP_DIFF__CYCLES_HIST);
1797 
1798 		/*
1799 		 * And the rest:
1800 		 *
1801 		 * PERF_HPP_DIFF__FORMULA
1802 		 * PERF_HPP_DIFF__PERIOD
1803 		 * PERF_HPP_DIFF__PERIOD_BASELINE
1804 		 */
1805 		if (show_formula && i)
1806 			data__hpp_register(d, PERF_HPP_DIFF__FORMULA);
1807 
1808 		if (show_period)
1809 			data__hpp_register(d, i ? PERF_HPP_DIFF__PERIOD :
1810 						  PERF_HPP_DIFF__PERIOD_BASELINE);
1811 	}
1812 
1813 	if (!sort_compute)
1814 		return 0;
1815 
1816 	/*
1817 	 * Prepend an fmt to sort on columns at 'sort_compute' first.
1818 	 * This fmt is added only to the sort list but not to the
1819 	 * output fields list.
1820 	 *
1821 	 * Note that this column (data) can be compared twice - one
1822 	 * for this 'sort_compute' fmt and another for the normal
1823 	 * diff_hpp_fmt.  But it shouldn't a problem as most entries
1824 	 * will be sorted out by first try or baseline and comparing
1825 	 * is not a costly operation.
1826 	 */
1827 	fmt = zalloc(sizeof(*fmt));
1828 	if (fmt == NULL) {
1829 		pr_err("Memory allocation failed\n");
1830 		return -1;
1831 	}
1832 
1833 	fmt->cmp      = hist_entry__cmp_nop;
1834 	fmt->collapse = hist_entry__cmp_nop;
1835 
1836 	switch (compute) {
1837 	case COMPUTE_DELTA:
1838 		fmt->sort = hist_entry__cmp_delta_idx;
1839 		break;
1840 	case COMPUTE_RATIO:
1841 		fmt->sort = hist_entry__cmp_ratio_idx;
1842 		break;
1843 	case COMPUTE_WEIGHTED_DIFF:
1844 		fmt->sort = hist_entry__cmp_wdiff_idx;
1845 		break;
1846 	case COMPUTE_DELTA_ABS:
1847 		fmt->sort = hist_entry__cmp_delta_abs_idx;
1848 		break;
1849 	case COMPUTE_CYCLES:
1850 		/*
1851 		 * Should set since 'fmt->sort' is called without
1852 		 * checking valid during sorting
1853 		 */
1854 		fmt->sort = hist_entry__cmp_nop;
1855 		break;
1856 	default:
1857 		BUG_ON(1);
1858 	}
1859 
1860 	perf_hpp__prepend_sort_field(fmt);
1861 	return 0;
1862 }
1863 
1864 static int data_init(int argc, const char **argv)
1865 {
1866 	struct data__file *d;
1867 	static const char *defaults[] = {
1868 		"perf.data.old",
1869 		"perf.data",
1870 	};
1871 	bool use_default = true;
1872 	int i;
1873 
1874 	data__files_cnt = 2;
1875 
1876 	if (argc) {
1877 		if (argc == 1)
1878 			defaults[1] = argv[0];
1879 		else {
1880 			data__files_cnt = argc;
1881 			use_default = false;
1882 		}
1883 	} else if (perf_guest) {
1884 		defaults[0] = "perf.data.host";
1885 		defaults[1] = "perf.data.guest";
1886 	}
1887 
1888 	if (sort_compute >= (unsigned int) data__files_cnt) {
1889 		pr_err("Order option out of limit.\n");
1890 		return -EINVAL;
1891 	}
1892 
1893 	data__files = calloc(data__files_cnt, sizeof(*data__files));
1894 	if (!data__files)
1895 		return -ENOMEM;
1896 
1897 	data__for_each_file(i, d) {
1898 		struct perf_data *data = &d->data;
1899 
1900 		data->path  = use_default ? defaults[i] : argv[i];
1901 		data->mode  = PERF_DATA_MODE_READ;
1902 		data->force = force;
1903 
1904 		d->idx  = i;
1905 	}
1906 
1907 	return 0;
1908 }
1909 
1910 static int diff__config(const char *var, const char *value,
1911 			void *cb __maybe_unused)
1912 {
1913 	if (!strcmp(var, "diff.order")) {
1914 		int ret;
1915 		if (perf_config_int(&ret, var, value) < 0)
1916 			return -1;
1917 		sort_compute = ret;
1918 		return 0;
1919 	}
1920 	if (!strcmp(var, "diff.compute")) {
1921 		if (!strcmp(value, "delta")) {
1922 			compute = COMPUTE_DELTA;
1923 		} else if (!strcmp(value, "delta-abs")) {
1924 			compute = COMPUTE_DELTA_ABS;
1925 		} else if (!strcmp(value, "ratio")) {
1926 			compute = COMPUTE_RATIO;
1927 		} else if (!strcmp(value, "wdiff")) {
1928 			compute = COMPUTE_WEIGHTED_DIFF;
1929 		} else {
1930 			pr_err("Invalid compute method: %s\n", value);
1931 			return -1;
1932 		}
1933 	}
1934 
1935 	return 0;
1936 }
1937 
1938 int cmd_diff(int argc, const char **argv)
1939 {
1940 	int ret = hists__init();
1941 
1942 	if (ret < 0)
1943 		return ret;
1944 
1945 	perf_tool__init(&pdiff.tool, /*ordered_events=*/true);
1946 	pdiff.tool.sample	= diff__process_sample_event;
1947 	pdiff.tool.mmap	= perf_event__process_mmap;
1948 	pdiff.tool.mmap2	= perf_event__process_mmap2;
1949 	pdiff.tool.comm	= perf_event__process_comm;
1950 	pdiff.tool.exit	= perf_event__process_exit;
1951 	pdiff.tool.fork	= perf_event__process_fork;
1952 	pdiff.tool.lost	= perf_event__process_lost;
1953 	pdiff.tool.namespaces = perf_event__process_namespaces;
1954 	pdiff.tool.cgroup = perf_event__process_cgroup;
1955 	pdiff.tool.ordering_requires_timestamps = true;
1956 
1957 	perf_config(diff__config, NULL);
1958 
1959 	argc = parse_options(argc, argv, options, diff_usage, 0);
1960 
1961 	if (quiet)
1962 		perf_quiet_option();
1963 
1964 	if (cycles_hist && (compute != COMPUTE_CYCLES))
1965 		usage_with_options(diff_usage, options);
1966 
1967 	if (pdiff.stream)
1968 		compute = COMPUTE_STREAM;
1969 
1970 	symbol__annotation_init();
1971 
1972 	if (symbol__init(NULL) < 0)
1973 		return -1;
1974 
1975 	if (data_init(argc, argv) < 0)
1976 		return -1;
1977 
1978 	if (check_file_brstack() < 0)
1979 		return -1;
1980 
1981 	if ((compute == COMPUTE_CYCLES || compute == COMPUTE_STREAM)
1982 	    && !pdiff.has_br_stack) {
1983 		return -1;
1984 	}
1985 
1986 	if (compute == COMPUTE_STREAM) {
1987 		symbol_conf.show_branchflag_count = true;
1988 		symbol_conf.addr2line_disable_warn = true;
1989 		callchain_param.mode = CHAIN_FLAT;
1990 		callchain_param.key = CCKEY_SRCLINE;
1991 		callchain_param.branch_callstack = 1;
1992 		symbol_conf.use_callchain = true;
1993 		callchain_register_param(&callchain_param);
1994 		sort_order = "srcline,symbol,dso";
1995 	} else {
1996 		if (ui_init() < 0)
1997 			return -1;
1998 
1999 		sort__mode = SORT_MODE__DIFF;
2000 	}
2001 
2002 	if (setup_sorting(/*evlist=*/NULL, perf_session__env(data__files[0].session)) < 0)
2003 		usage_with_options(diff_usage, options);
2004 
2005 	setup_pager();
2006 
2007 	sort__setup_elide(NULL);
2008 
2009 	return __cmd_diff();
2010 }
2011