xref: /linux/tools/perf/arch/x86/util/intel-pt.c (revision cbdb1f163af2bb90d01be1f0263df1d8d5c9d9d3)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * intel_pt.c: Intel Processor Trace support
4  * Copyright (c) 2013-2015, Intel Corporation.
5  */
6 
7 #include <errno.h>
8 #include <stdbool.h>
9 #include <linux/kernel.h>
10 #include <linux/types.h>
11 #include <linux/bitops.h>
12 #include <linux/log2.h>
13 #include <linux/zalloc.h>
14 #include <linux/err.h>
15 #include <cpuid.h>
16 
17 #include "../../../util/session.h"
18 #include "../../../util/event.h"
19 #include "../../../util/evlist.h"
20 #include "../../../util/evsel.h"
21 #include "../../../util/evsel_config.h"
22 #include "../../../util/cpumap.h"
23 #include "../../../util/mmap.h"
24 #include <subcmd/parse-options.h>
25 #include "../../../util/parse-events.h"
26 #include "../../../util/pmu.h"
27 #include "../../../util/debug.h"
28 #include "../../../util/auxtrace.h"
29 #include "../../../util/perf_api_probe.h"
30 #include "../../../util/record.h"
31 #include "../../../util/target.h"
32 #include "../../../util/tsc.h"
33 #include <internal/lib.h> // page_size
34 #include "../../../util/intel-pt.h"
35 
36 #define KiB(x) ((x) * 1024)
37 #define MiB(x) ((x) * 1024 * 1024)
38 #define KiB_MASK(x) (KiB(x) - 1)
39 #define MiB_MASK(x) (MiB(x) - 1)
40 
41 #define INTEL_PT_PSB_PERIOD_NEAR	256
42 
43 struct intel_pt_snapshot_ref {
44 	void *ref_buf;
45 	size_t ref_offset;
46 	bool wrapped;
47 };
48 
49 struct intel_pt_recording {
50 	struct auxtrace_record		itr;
51 	struct perf_pmu			*intel_pt_pmu;
52 	int				have_sched_switch;
53 	struct evlist		*evlist;
54 	bool				snapshot_mode;
55 	bool				snapshot_init_done;
56 	size_t				snapshot_size;
57 	size_t				snapshot_ref_buf_size;
58 	int				snapshot_ref_cnt;
59 	struct intel_pt_snapshot_ref	*snapshot_refs;
60 	size_t				priv_size;
61 };
62 
63 static int intel_pt_parse_terms_with_default(const char *pmu_name,
64 					     struct list_head *formats,
65 					     const char *str,
66 					     u64 *config)
67 {
68 	struct list_head *terms;
69 	struct perf_event_attr attr = { .size = 0, };
70 	int err;
71 
72 	terms = malloc(sizeof(struct list_head));
73 	if (!terms)
74 		return -ENOMEM;
75 
76 	INIT_LIST_HEAD(terms);
77 
78 	err = parse_events_terms(terms, str);
79 	if (err)
80 		goto out_free;
81 
82 	attr.config = *config;
83 	err = perf_pmu__config_terms(pmu_name, formats, &attr, terms, true,
84 				     NULL);
85 	if (err)
86 		goto out_free;
87 
88 	*config = attr.config;
89 out_free:
90 	parse_events_terms__delete(terms);
91 	return err;
92 }
93 
94 static int intel_pt_parse_terms(const char *pmu_name, struct list_head *formats,
95 				const char *str, u64 *config)
96 {
97 	*config = 0;
98 	return intel_pt_parse_terms_with_default(pmu_name, formats, str,
99 						 config);
100 }
101 
102 static u64 intel_pt_masked_bits(u64 mask, u64 bits)
103 {
104 	const u64 top_bit = 1ULL << 63;
105 	u64 res = 0;
106 	int i;
107 
108 	for (i = 0; i < 64; i++) {
109 		if (mask & top_bit) {
110 			res <<= 1;
111 			if (bits & top_bit)
112 				res |= 1;
113 		}
114 		mask <<= 1;
115 		bits <<= 1;
116 	}
117 
118 	return res;
119 }
120 
121 static int intel_pt_read_config(struct perf_pmu *intel_pt_pmu, const char *str,
122 				struct evlist *evlist, u64 *res)
123 {
124 	struct evsel *evsel;
125 	u64 mask;
126 
127 	*res = 0;
128 
129 	mask = perf_pmu__format_bits(&intel_pt_pmu->format, str);
130 	if (!mask)
131 		return -EINVAL;
132 
133 	evlist__for_each_entry(evlist, evsel) {
134 		if (evsel->core.attr.type == intel_pt_pmu->type) {
135 			*res = intel_pt_masked_bits(mask, evsel->core.attr.config);
136 			return 0;
137 		}
138 	}
139 
140 	return -EINVAL;
141 }
142 
143 static size_t intel_pt_psb_period(struct perf_pmu *intel_pt_pmu,
144 				  struct evlist *evlist)
145 {
146 	u64 val;
147 	int err, topa_multiple_entries;
148 	size_t psb_period;
149 
150 	if (perf_pmu__scan_file(intel_pt_pmu, "caps/topa_multiple_entries",
151 				"%d", &topa_multiple_entries) != 1)
152 		topa_multiple_entries = 0;
153 
154 	/*
155 	 * Use caps/topa_multiple_entries to indicate early hardware that had
156 	 * extra frequent PSBs.
157 	 */
158 	if (!topa_multiple_entries) {
159 		psb_period = 256;
160 		goto out;
161 	}
162 
163 	err = intel_pt_read_config(intel_pt_pmu, "psb_period", evlist, &val);
164 	if (err)
165 		val = 0;
166 
167 	psb_period = 1 << (val + 11);
168 out:
169 	pr_debug2("%s psb_period %zu\n", intel_pt_pmu->name, psb_period);
170 	return psb_period;
171 }
172 
173 static int intel_pt_pick_bit(int bits, int target)
174 {
175 	int pos, pick = -1;
176 
177 	for (pos = 0; bits; bits >>= 1, pos++) {
178 		if (bits & 1) {
179 			if (pos <= target || pick < 0)
180 				pick = pos;
181 			if (pos >= target)
182 				break;
183 		}
184 	}
185 
186 	return pick;
187 }
188 
189 static u64 intel_pt_default_config(struct perf_pmu *intel_pt_pmu)
190 {
191 	char buf[256];
192 	int mtc, mtc_periods = 0, mtc_period;
193 	int psb_cyc, psb_periods, psb_period;
194 	int pos = 0;
195 	u64 config;
196 	char c;
197 
198 	pos += scnprintf(buf + pos, sizeof(buf) - pos, "tsc");
199 
200 	if (perf_pmu__scan_file(intel_pt_pmu, "caps/mtc", "%d",
201 				&mtc) != 1)
202 		mtc = 1;
203 
204 	if (mtc) {
205 		if (perf_pmu__scan_file(intel_pt_pmu, "caps/mtc_periods", "%x",
206 					&mtc_periods) != 1)
207 			mtc_periods = 0;
208 		if (mtc_periods) {
209 			mtc_period = intel_pt_pick_bit(mtc_periods, 3);
210 			pos += scnprintf(buf + pos, sizeof(buf) - pos,
211 					 ",mtc,mtc_period=%d", mtc_period);
212 		}
213 	}
214 
215 	if (perf_pmu__scan_file(intel_pt_pmu, "caps/psb_cyc", "%d",
216 				&psb_cyc) != 1)
217 		psb_cyc = 1;
218 
219 	if (psb_cyc && mtc_periods) {
220 		if (perf_pmu__scan_file(intel_pt_pmu, "caps/psb_periods", "%x",
221 					&psb_periods) != 1)
222 			psb_periods = 0;
223 		if (psb_periods) {
224 			psb_period = intel_pt_pick_bit(psb_periods, 3);
225 			pos += scnprintf(buf + pos, sizeof(buf) - pos,
226 					 ",psb_period=%d", psb_period);
227 		}
228 	}
229 
230 	if (perf_pmu__scan_file(intel_pt_pmu, "format/pt", "%c", &c) == 1 &&
231 	    perf_pmu__scan_file(intel_pt_pmu, "format/branch", "%c", &c) == 1)
232 		pos += scnprintf(buf + pos, sizeof(buf) - pos, ",pt,branch");
233 
234 	pr_debug2("%s default config: %s\n", intel_pt_pmu->name, buf);
235 
236 	intel_pt_parse_terms(intel_pt_pmu->name, &intel_pt_pmu->format, buf,
237 			     &config);
238 
239 	return config;
240 }
241 
242 static int intel_pt_parse_snapshot_options(struct auxtrace_record *itr,
243 					   struct record_opts *opts,
244 					   const char *str)
245 {
246 	struct intel_pt_recording *ptr =
247 			container_of(itr, struct intel_pt_recording, itr);
248 	unsigned long long snapshot_size = 0;
249 	char *endptr;
250 
251 	if (str) {
252 		snapshot_size = strtoull(str, &endptr, 0);
253 		if (*endptr || snapshot_size > SIZE_MAX)
254 			return -1;
255 	}
256 
257 	opts->auxtrace_snapshot_mode = true;
258 	opts->auxtrace_snapshot_size = snapshot_size;
259 
260 	ptr->snapshot_size = snapshot_size;
261 
262 	return 0;
263 }
264 
265 struct perf_event_attr *
266 intel_pt_pmu_default_config(struct perf_pmu *intel_pt_pmu)
267 {
268 	struct perf_event_attr *attr;
269 
270 	attr = zalloc(sizeof(struct perf_event_attr));
271 	if (!attr)
272 		return NULL;
273 
274 	attr->config = intel_pt_default_config(intel_pt_pmu);
275 
276 	intel_pt_pmu->selectable = true;
277 
278 	return attr;
279 }
280 
281 static const char *intel_pt_find_filter(struct evlist *evlist,
282 					struct perf_pmu *intel_pt_pmu)
283 {
284 	struct evsel *evsel;
285 
286 	evlist__for_each_entry(evlist, evsel) {
287 		if (evsel->core.attr.type == intel_pt_pmu->type)
288 			return evsel->filter;
289 	}
290 
291 	return NULL;
292 }
293 
294 static size_t intel_pt_filter_bytes(const char *filter)
295 {
296 	size_t len = filter ? strlen(filter) : 0;
297 
298 	return len ? roundup(len + 1, 8) : 0;
299 }
300 
301 static size_t
302 intel_pt_info_priv_size(struct auxtrace_record *itr, struct evlist *evlist)
303 {
304 	struct intel_pt_recording *ptr =
305 			container_of(itr, struct intel_pt_recording, itr);
306 	const char *filter = intel_pt_find_filter(evlist, ptr->intel_pt_pmu);
307 
308 	ptr->priv_size = (INTEL_PT_AUXTRACE_PRIV_MAX * sizeof(u64)) +
309 			 intel_pt_filter_bytes(filter);
310 	ptr->priv_size += sizeof(u64); /* Cap Event Trace */
311 
312 	return ptr->priv_size;
313 }
314 
315 static void intel_pt_tsc_ctc_ratio(u32 *n, u32 *d)
316 {
317 	unsigned int eax = 0, ebx = 0, ecx = 0, edx = 0;
318 
319 	__get_cpuid(0x15, &eax, &ebx, &ecx, &edx);
320 	*n = ebx;
321 	*d = eax;
322 }
323 
324 static int intel_pt_info_fill(struct auxtrace_record *itr,
325 			      struct perf_session *session,
326 			      struct perf_record_auxtrace_info *auxtrace_info,
327 			      size_t priv_size)
328 {
329 	struct intel_pt_recording *ptr =
330 			container_of(itr, struct intel_pt_recording, itr);
331 	struct perf_pmu *intel_pt_pmu = ptr->intel_pt_pmu;
332 	struct perf_event_mmap_page *pc;
333 	struct perf_tsc_conversion tc = { .time_mult = 0, };
334 	bool cap_user_time_zero = false, per_cpu_mmaps;
335 	u64 tsc_bit, mtc_bit, mtc_freq_bits, cyc_bit, noretcomp_bit;
336 	u32 tsc_ctc_ratio_n, tsc_ctc_ratio_d;
337 	unsigned long max_non_turbo_ratio;
338 	size_t filter_str_len;
339 	const char *filter;
340 	int event_trace;
341 	__u64 *info;
342 	int err;
343 
344 	if (priv_size != ptr->priv_size)
345 		return -EINVAL;
346 
347 	intel_pt_parse_terms(intel_pt_pmu->name, &intel_pt_pmu->format,
348 			     "tsc", &tsc_bit);
349 	intel_pt_parse_terms(intel_pt_pmu->name, &intel_pt_pmu->format,
350 			     "noretcomp", &noretcomp_bit);
351 	intel_pt_parse_terms(intel_pt_pmu->name, &intel_pt_pmu->format,
352 			     "mtc", &mtc_bit);
353 	mtc_freq_bits = perf_pmu__format_bits(&intel_pt_pmu->format,
354 					      "mtc_period");
355 	intel_pt_parse_terms(intel_pt_pmu->name, &intel_pt_pmu->format,
356 			     "cyc", &cyc_bit);
357 
358 	intel_pt_tsc_ctc_ratio(&tsc_ctc_ratio_n, &tsc_ctc_ratio_d);
359 
360 	if (perf_pmu__scan_file(intel_pt_pmu, "max_nonturbo_ratio",
361 				"%lu", &max_non_turbo_ratio) != 1)
362 		max_non_turbo_ratio = 0;
363 	if (perf_pmu__scan_file(intel_pt_pmu, "caps/event_trace",
364 				"%d", &event_trace) != 1)
365 		event_trace = 0;
366 
367 	filter = intel_pt_find_filter(session->evlist, ptr->intel_pt_pmu);
368 	filter_str_len = filter ? strlen(filter) : 0;
369 
370 	if (!session->evlist->core.nr_mmaps)
371 		return -EINVAL;
372 
373 	pc = session->evlist->mmap[0].core.base;
374 	if (pc) {
375 		err = perf_read_tsc_conversion(pc, &tc);
376 		if (err) {
377 			if (err != -EOPNOTSUPP)
378 				return err;
379 		} else {
380 			cap_user_time_zero = tc.time_mult != 0;
381 		}
382 		if (!cap_user_time_zero)
383 			ui__warning("Intel Processor Trace: TSC not available\n");
384 	}
385 
386 	per_cpu_mmaps = !perf_cpu_map__empty(session->evlist->core.user_requested_cpus);
387 
388 	auxtrace_info->type = PERF_AUXTRACE_INTEL_PT;
389 	auxtrace_info->priv[INTEL_PT_PMU_TYPE] = intel_pt_pmu->type;
390 	auxtrace_info->priv[INTEL_PT_TIME_SHIFT] = tc.time_shift;
391 	auxtrace_info->priv[INTEL_PT_TIME_MULT] = tc.time_mult;
392 	auxtrace_info->priv[INTEL_PT_TIME_ZERO] = tc.time_zero;
393 	auxtrace_info->priv[INTEL_PT_CAP_USER_TIME_ZERO] = cap_user_time_zero;
394 	auxtrace_info->priv[INTEL_PT_TSC_BIT] = tsc_bit;
395 	auxtrace_info->priv[INTEL_PT_NORETCOMP_BIT] = noretcomp_bit;
396 	auxtrace_info->priv[INTEL_PT_HAVE_SCHED_SWITCH] = ptr->have_sched_switch;
397 	auxtrace_info->priv[INTEL_PT_SNAPSHOT_MODE] = ptr->snapshot_mode;
398 	auxtrace_info->priv[INTEL_PT_PER_CPU_MMAPS] = per_cpu_mmaps;
399 	auxtrace_info->priv[INTEL_PT_MTC_BIT] = mtc_bit;
400 	auxtrace_info->priv[INTEL_PT_MTC_FREQ_BITS] = mtc_freq_bits;
401 	auxtrace_info->priv[INTEL_PT_TSC_CTC_N] = tsc_ctc_ratio_n;
402 	auxtrace_info->priv[INTEL_PT_TSC_CTC_D] = tsc_ctc_ratio_d;
403 	auxtrace_info->priv[INTEL_PT_CYC_BIT] = cyc_bit;
404 	auxtrace_info->priv[INTEL_PT_MAX_NONTURBO_RATIO] = max_non_turbo_ratio;
405 	auxtrace_info->priv[INTEL_PT_FILTER_STR_LEN] = filter_str_len;
406 
407 	info = &auxtrace_info->priv[INTEL_PT_FILTER_STR_LEN] + 1;
408 
409 	if (filter_str_len) {
410 		size_t len = intel_pt_filter_bytes(filter);
411 
412 		strncpy((char *)info, filter, len);
413 		info += len >> 3;
414 	}
415 
416 	*info++ = event_trace;
417 
418 	return 0;
419 }
420 
421 #ifdef HAVE_LIBTRACEEVENT
422 static int intel_pt_track_switches(struct evlist *evlist)
423 {
424 	const char *sched_switch = "sched:sched_switch";
425 	struct evsel *evsel;
426 	int err;
427 
428 	if (!evlist__can_select_event(evlist, sched_switch))
429 		return -EPERM;
430 
431 	evsel = evlist__add_sched_switch(evlist, true);
432 	if (IS_ERR(evsel)) {
433 		err = PTR_ERR(evsel);
434 		pr_debug2("%s: failed to create %s, error = %d\n",
435 			  __func__, sched_switch, err);
436 		return err;
437 	}
438 
439 	evsel->immediate = true;
440 
441 	return 0;
442 }
443 #endif
444 
445 static void intel_pt_valid_str(char *str, size_t len, u64 valid)
446 {
447 	unsigned int val, last = 0, state = 1;
448 	int p = 0;
449 
450 	str[0] = '\0';
451 
452 	for (val = 0; val <= 64; val++, valid >>= 1) {
453 		if (valid & 1) {
454 			last = val;
455 			switch (state) {
456 			case 0:
457 				p += scnprintf(str + p, len - p, ",");
458 				/* Fall through */
459 			case 1:
460 				p += scnprintf(str + p, len - p, "%u", val);
461 				state = 2;
462 				break;
463 			case 2:
464 				state = 3;
465 				break;
466 			case 3:
467 				state = 4;
468 				break;
469 			default:
470 				break;
471 			}
472 		} else {
473 			switch (state) {
474 			case 3:
475 				p += scnprintf(str + p, len - p, ",%u", last);
476 				state = 0;
477 				break;
478 			case 4:
479 				p += scnprintf(str + p, len - p, "-%u", last);
480 				state = 0;
481 				break;
482 			default:
483 				break;
484 			}
485 			if (state != 1)
486 				state = 0;
487 		}
488 	}
489 }
490 
491 static int intel_pt_val_config_term(struct perf_pmu *intel_pt_pmu,
492 				    const char *caps, const char *name,
493 				    const char *supported, u64 config)
494 {
495 	char valid_str[256];
496 	unsigned int shift;
497 	unsigned long long valid;
498 	u64 bits;
499 	int ok;
500 
501 	if (perf_pmu__scan_file(intel_pt_pmu, caps, "%llx", &valid) != 1)
502 		valid = 0;
503 
504 	if (supported &&
505 	    perf_pmu__scan_file(intel_pt_pmu, supported, "%d", &ok) == 1 && !ok)
506 		valid = 0;
507 
508 	valid |= 1;
509 
510 	bits = perf_pmu__format_bits(&intel_pt_pmu->format, name);
511 
512 	config &= bits;
513 
514 	for (shift = 0; bits && !(bits & 1); shift++)
515 		bits >>= 1;
516 
517 	config >>= shift;
518 
519 	if (config > 63)
520 		goto out_err;
521 
522 	if (valid & (1 << config))
523 		return 0;
524 out_err:
525 	intel_pt_valid_str(valid_str, sizeof(valid_str), valid);
526 	pr_err("Invalid %s for %s. Valid values are: %s\n",
527 	       name, INTEL_PT_PMU_NAME, valid_str);
528 	return -EINVAL;
529 }
530 
531 static int intel_pt_validate_config(struct perf_pmu *intel_pt_pmu,
532 				    struct evsel *evsel)
533 {
534 	int err;
535 	char c;
536 
537 	if (!evsel)
538 		return 0;
539 
540 	/*
541 	 * If supported, force pass-through config term (pt=1) even if user
542 	 * sets pt=0, which avoids senseless kernel errors.
543 	 */
544 	if (perf_pmu__scan_file(intel_pt_pmu, "format/pt", "%c", &c) == 1 &&
545 	    !(evsel->core.attr.config & 1)) {
546 		pr_warning("pt=0 doesn't make sense, forcing pt=1\n");
547 		evsel->core.attr.config |= 1;
548 	}
549 
550 	err = intel_pt_val_config_term(intel_pt_pmu, "caps/cycle_thresholds",
551 				       "cyc_thresh", "caps/psb_cyc",
552 				       evsel->core.attr.config);
553 	if (err)
554 		return err;
555 
556 	err = intel_pt_val_config_term(intel_pt_pmu, "caps/mtc_periods",
557 				       "mtc_period", "caps/mtc",
558 				       evsel->core.attr.config);
559 	if (err)
560 		return err;
561 
562 	return intel_pt_val_config_term(intel_pt_pmu, "caps/psb_periods",
563 					"psb_period", "caps/psb_cyc",
564 					evsel->core.attr.config);
565 }
566 
567 static void intel_pt_config_sample_mode(struct perf_pmu *intel_pt_pmu,
568 					struct evsel *evsel)
569 {
570 	u64 user_bits = 0, bits;
571 	struct evsel_config_term *term = evsel__get_config_term(evsel, CFG_CHG);
572 
573 	if (term)
574 		user_bits = term->val.cfg_chg;
575 
576 	bits = perf_pmu__format_bits(&intel_pt_pmu->format, "psb_period");
577 
578 	/* Did user change psb_period */
579 	if (bits & user_bits)
580 		return;
581 
582 	/* Set psb_period to 0 */
583 	evsel->core.attr.config &= ~bits;
584 }
585 
586 static void intel_pt_min_max_sample_sz(struct evlist *evlist,
587 				       size_t *min_sz, size_t *max_sz)
588 {
589 	struct evsel *evsel;
590 
591 	evlist__for_each_entry(evlist, evsel) {
592 		size_t sz = evsel->core.attr.aux_sample_size;
593 
594 		if (!sz)
595 			continue;
596 		if (min_sz && (sz < *min_sz || !*min_sz))
597 			*min_sz = sz;
598 		if (max_sz && sz > *max_sz)
599 			*max_sz = sz;
600 	}
601 }
602 
603 /*
604  * Currently, there is not enough information to disambiguate different PEBS
605  * events, so only allow one.
606  */
607 static bool intel_pt_too_many_aux_output(struct evlist *evlist)
608 {
609 	struct evsel *evsel;
610 	int aux_output_cnt = 0;
611 
612 	evlist__for_each_entry(evlist, evsel)
613 		aux_output_cnt += !!evsel->core.attr.aux_output;
614 
615 	if (aux_output_cnt > 1) {
616 		pr_err(INTEL_PT_PMU_NAME " supports at most one event with aux-output\n");
617 		return true;
618 	}
619 
620 	return false;
621 }
622 
623 static int intel_pt_recording_options(struct auxtrace_record *itr,
624 				      struct evlist *evlist,
625 				      struct record_opts *opts)
626 {
627 	struct intel_pt_recording *ptr =
628 			container_of(itr, struct intel_pt_recording, itr);
629 	struct perf_pmu *intel_pt_pmu = ptr->intel_pt_pmu;
630 	bool have_timing_info, need_immediate = false;
631 	struct evsel *evsel, *intel_pt_evsel = NULL;
632 	const struct perf_cpu_map *cpus = evlist->core.user_requested_cpus;
633 	bool privileged = perf_event_paranoid_check(-1);
634 	u64 tsc_bit;
635 	int err;
636 
637 	ptr->evlist = evlist;
638 	ptr->snapshot_mode = opts->auxtrace_snapshot_mode;
639 
640 	evlist__for_each_entry(evlist, evsel) {
641 		if (evsel->core.attr.type == intel_pt_pmu->type) {
642 			if (intel_pt_evsel) {
643 				pr_err("There may be only one " INTEL_PT_PMU_NAME " event\n");
644 				return -EINVAL;
645 			}
646 			evsel->core.attr.freq = 0;
647 			evsel->core.attr.sample_period = 1;
648 			evsel->no_aux_samples = true;
649 			evsel->needs_auxtrace_mmap = true;
650 			intel_pt_evsel = evsel;
651 			opts->full_auxtrace = true;
652 		}
653 	}
654 
655 	if (opts->auxtrace_snapshot_mode && !opts->full_auxtrace) {
656 		pr_err("Snapshot mode (-S option) requires " INTEL_PT_PMU_NAME " PMU event (-e " INTEL_PT_PMU_NAME ")\n");
657 		return -EINVAL;
658 	}
659 
660 	if (opts->auxtrace_snapshot_mode && opts->auxtrace_sample_mode) {
661 		pr_err("Snapshot mode (" INTEL_PT_PMU_NAME " PMU) and sample trace cannot be used together\n");
662 		return -EINVAL;
663 	}
664 
665 	if (opts->use_clockid) {
666 		pr_err("Cannot use clockid (-k option) with " INTEL_PT_PMU_NAME "\n");
667 		return -EINVAL;
668 	}
669 
670 	if (intel_pt_too_many_aux_output(evlist))
671 		return -EINVAL;
672 
673 	if (!opts->full_auxtrace)
674 		return 0;
675 
676 	if (opts->auxtrace_sample_mode)
677 		intel_pt_config_sample_mode(intel_pt_pmu, intel_pt_evsel);
678 
679 	err = intel_pt_validate_config(intel_pt_pmu, intel_pt_evsel);
680 	if (err)
681 		return err;
682 
683 	/* Set default sizes for snapshot mode */
684 	if (opts->auxtrace_snapshot_mode) {
685 		size_t psb_period = intel_pt_psb_period(intel_pt_pmu, evlist);
686 
687 		if (!opts->auxtrace_snapshot_size && !opts->auxtrace_mmap_pages) {
688 			if (privileged) {
689 				opts->auxtrace_mmap_pages = MiB(4) / page_size;
690 			} else {
691 				opts->auxtrace_mmap_pages = KiB(128) / page_size;
692 				if (opts->mmap_pages == UINT_MAX)
693 					opts->mmap_pages = KiB(256) / page_size;
694 			}
695 		} else if (!opts->auxtrace_mmap_pages && !privileged &&
696 			   opts->mmap_pages == UINT_MAX) {
697 			opts->mmap_pages = KiB(256) / page_size;
698 		}
699 		if (!opts->auxtrace_snapshot_size)
700 			opts->auxtrace_snapshot_size =
701 				opts->auxtrace_mmap_pages * (size_t)page_size;
702 		if (!opts->auxtrace_mmap_pages) {
703 			size_t sz = opts->auxtrace_snapshot_size;
704 
705 			sz = round_up(sz, page_size) / page_size;
706 			opts->auxtrace_mmap_pages = roundup_pow_of_two(sz);
707 		}
708 		if (opts->auxtrace_snapshot_size >
709 				opts->auxtrace_mmap_pages * (size_t)page_size) {
710 			pr_err("Snapshot size %zu must not be greater than AUX area tracing mmap size %zu\n",
711 			       opts->auxtrace_snapshot_size,
712 			       opts->auxtrace_mmap_pages * (size_t)page_size);
713 			return -EINVAL;
714 		}
715 		if (!opts->auxtrace_snapshot_size || !opts->auxtrace_mmap_pages) {
716 			pr_err("Failed to calculate default snapshot size and/or AUX area tracing mmap pages\n");
717 			return -EINVAL;
718 		}
719 		pr_debug2("Intel PT snapshot size: %zu\n",
720 			  opts->auxtrace_snapshot_size);
721 		if (psb_period &&
722 		    opts->auxtrace_snapshot_size <= psb_period +
723 						  INTEL_PT_PSB_PERIOD_NEAR)
724 			ui__warning("Intel PT snapshot size (%zu) may be too small for PSB period (%zu)\n",
725 				    opts->auxtrace_snapshot_size, psb_period);
726 	}
727 
728 	/* Set default sizes for sample mode */
729 	if (opts->auxtrace_sample_mode) {
730 		size_t psb_period = intel_pt_psb_period(intel_pt_pmu, evlist);
731 		size_t min_sz = 0, max_sz = 0;
732 
733 		intel_pt_min_max_sample_sz(evlist, &min_sz, &max_sz);
734 		if (!opts->auxtrace_mmap_pages && !privileged &&
735 		    opts->mmap_pages == UINT_MAX)
736 			opts->mmap_pages = KiB(256) / page_size;
737 		if (!opts->auxtrace_mmap_pages) {
738 			size_t sz = round_up(max_sz, page_size) / page_size;
739 
740 			opts->auxtrace_mmap_pages = roundup_pow_of_two(sz);
741 		}
742 		if (max_sz > opts->auxtrace_mmap_pages * (size_t)page_size) {
743 			pr_err("Sample size %zu must not be greater than AUX area tracing mmap size %zu\n",
744 			       max_sz,
745 			       opts->auxtrace_mmap_pages * (size_t)page_size);
746 			return -EINVAL;
747 		}
748 		pr_debug2("Intel PT min. sample size: %zu max. sample size: %zu\n",
749 			  min_sz, max_sz);
750 		if (psb_period &&
751 		    min_sz <= psb_period + INTEL_PT_PSB_PERIOD_NEAR)
752 			ui__warning("Intel PT sample size (%zu) may be too small for PSB period (%zu)\n",
753 				    min_sz, psb_period);
754 	}
755 
756 	/* Set default sizes for full trace mode */
757 	if (opts->full_auxtrace && !opts->auxtrace_mmap_pages) {
758 		if (privileged) {
759 			opts->auxtrace_mmap_pages = MiB(4) / page_size;
760 		} else {
761 			opts->auxtrace_mmap_pages = KiB(128) / page_size;
762 			if (opts->mmap_pages == UINT_MAX)
763 				opts->mmap_pages = KiB(256) / page_size;
764 		}
765 	}
766 
767 	/* Validate auxtrace_mmap_pages */
768 	if (opts->auxtrace_mmap_pages) {
769 		size_t sz = opts->auxtrace_mmap_pages * (size_t)page_size;
770 		size_t min_sz;
771 
772 		if (opts->auxtrace_snapshot_mode || opts->auxtrace_sample_mode)
773 			min_sz = KiB(4);
774 		else
775 			min_sz = KiB(8);
776 
777 		if (sz < min_sz || !is_power_of_2(sz)) {
778 			pr_err("Invalid mmap size for Intel Processor Trace: must be at least %zuKiB and a power of 2\n",
779 			       min_sz / 1024);
780 			return -EINVAL;
781 		}
782 	}
783 
784 	if (!opts->auxtrace_snapshot_mode && !opts->auxtrace_sample_mode) {
785 		u32 aux_watermark = opts->auxtrace_mmap_pages * page_size / 4;
786 
787 		intel_pt_evsel->core.attr.aux_watermark = aux_watermark;
788 	}
789 
790 	intel_pt_parse_terms(intel_pt_pmu->name, &intel_pt_pmu->format,
791 			     "tsc", &tsc_bit);
792 
793 	if (opts->full_auxtrace && (intel_pt_evsel->core.attr.config & tsc_bit))
794 		have_timing_info = true;
795 	else
796 		have_timing_info = false;
797 
798 	/*
799 	 * Per-cpu recording needs sched_switch events to distinguish different
800 	 * threads.
801 	 */
802 	if (have_timing_info && !perf_cpu_map__empty(cpus) &&
803 	    !record_opts__no_switch_events(opts)) {
804 		if (perf_can_record_switch_events()) {
805 			bool cpu_wide = !target__none(&opts->target) &&
806 					!target__has_task(&opts->target);
807 
808 			if (!cpu_wide && perf_can_record_cpu_wide()) {
809 				struct evsel *switch_evsel;
810 
811 				switch_evsel = evlist__add_dummy_on_all_cpus(evlist);
812 				if (!switch_evsel)
813 					return -ENOMEM;
814 
815 				switch_evsel->core.attr.context_switch = 1;
816 				switch_evsel->immediate = true;
817 
818 				evsel__set_sample_bit(switch_evsel, TID);
819 				evsel__set_sample_bit(switch_evsel, TIME);
820 				evsel__set_sample_bit(switch_evsel, CPU);
821 				evsel__reset_sample_bit(switch_evsel, BRANCH_STACK);
822 
823 				opts->record_switch_events = false;
824 				ptr->have_sched_switch = 3;
825 			} else {
826 				opts->record_switch_events = true;
827 				need_immediate = true;
828 				if (cpu_wide)
829 					ptr->have_sched_switch = 3;
830 				else
831 					ptr->have_sched_switch = 2;
832 			}
833 		} else {
834 #ifdef HAVE_LIBTRACEEVENT
835 			err = intel_pt_track_switches(evlist);
836 			if (err == -EPERM)
837 				pr_debug2("Unable to select sched:sched_switch\n");
838 			else if (err)
839 				return err;
840 			else
841 				ptr->have_sched_switch = 1;
842 #endif
843 		}
844 	}
845 
846 	if (have_timing_info && !intel_pt_evsel->core.attr.exclude_kernel &&
847 	    perf_can_record_text_poke_events() && perf_can_record_cpu_wide())
848 		opts->text_poke = true;
849 
850 	if (intel_pt_evsel) {
851 		/*
852 		 * To obtain the auxtrace buffer file descriptor, the auxtrace
853 		 * event must come first.
854 		 */
855 		evlist__to_front(evlist, intel_pt_evsel);
856 		/*
857 		 * In the case of per-cpu mmaps, we need the CPU on the
858 		 * AUX event.
859 		 */
860 		if (!perf_cpu_map__empty(cpus))
861 			evsel__set_sample_bit(intel_pt_evsel, CPU);
862 	}
863 
864 	/* Add dummy event to keep tracking */
865 	if (opts->full_auxtrace) {
866 		bool need_system_wide_tracking;
867 		struct evsel *tracking_evsel;
868 
869 		/*
870 		 * User space tasks can migrate between CPUs, so when tracing
871 		 * selected CPUs, sideband for all CPUs is still needed.
872 		 */
873 		need_system_wide_tracking = opts->target.cpu_list &&
874 					    !intel_pt_evsel->core.attr.exclude_user;
875 
876 		tracking_evsel = evlist__add_aux_dummy(evlist, need_system_wide_tracking);
877 		if (!tracking_evsel)
878 			return -ENOMEM;
879 
880 		evlist__set_tracking_event(evlist, tracking_evsel);
881 
882 		if (need_immediate)
883 			tracking_evsel->immediate = true;
884 
885 		/* In per-cpu case, always need the time of mmap events etc */
886 		if (!perf_cpu_map__empty(cpus)) {
887 			evsel__set_sample_bit(tracking_evsel, TIME);
888 			/* And the CPU for switch events */
889 			evsel__set_sample_bit(tracking_evsel, CPU);
890 		}
891 		evsel__reset_sample_bit(tracking_evsel, BRANCH_STACK);
892 	}
893 
894 	/*
895 	 * Warn the user when we do not have enough information to decode i.e.
896 	 * per-cpu with no sched_switch (except workload-only).
897 	 */
898 	if (!ptr->have_sched_switch && !perf_cpu_map__empty(cpus) &&
899 	    !target__none(&opts->target) &&
900 	    !intel_pt_evsel->core.attr.exclude_user)
901 		ui__warning("Intel Processor Trace decoding will not be possible except for kernel tracing!\n");
902 
903 	return 0;
904 }
905 
906 static int intel_pt_snapshot_start(struct auxtrace_record *itr)
907 {
908 	struct intel_pt_recording *ptr =
909 			container_of(itr, struct intel_pt_recording, itr);
910 	struct evsel *evsel;
911 
912 	evlist__for_each_entry(ptr->evlist, evsel) {
913 		if (evsel->core.attr.type == ptr->intel_pt_pmu->type)
914 			return evsel__disable(evsel);
915 	}
916 	return -EINVAL;
917 }
918 
919 static int intel_pt_snapshot_finish(struct auxtrace_record *itr)
920 {
921 	struct intel_pt_recording *ptr =
922 			container_of(itr, struct intel_pt_recording, itr);
923 	struct evsel *evsel;
924 
925 	evlist__for_each_entry(ptr->evlist, evsel) {
926 		if (evsel->core.attr.type == ptr->intel_pt_pmu->type)
927 			return evsel__enable(evsel);
928 	}
929 	return -EINVAL;
930 }
931 
932 static int intel_pt_alloc_snapshot_refs(struct intel_pt_recording *ptr, int idx)
933 {
934 	const size_t sz = sizeof(struct intel_pt_snapshot_ref);
935 	int cnt = ptr->snapshot_ref_cnt, new_cnt = cnt * 2;
936 	struct intel_pt_snapshot_ref *refs;
937 
938 	if (!new_cnt)
939 		new_cnt = 16;
940 
941 	while (new_cnt <= idx)
942 		new_cnt *= 2;
943 
944 	refs = calloc(new_cnt, sz);
945 	if (!refs)
946 		return -ENOMEM;
947 
948 	memcpy(refs, ptr->snapshot_refs, cnt * sz);
949 
950 	ptr->snapshot_refs = refs;
951 	ptr->snapshot_ref_cnt = new_cnt;
952 
953 	return 0;
954 }
955 
956 static void intel_pt_free_snapshot_refs(struct intel_pt_recording *ptr)
957 {
958 	int i;
959 
960 	for (i = 0; i < ptr->snapshot_ref_cnt; i++)
961 		zfree(&ptr->snapshot_refs[i].ref_buf);
962 	zfree(&ptr->snapshot_refs);
963 }
964 
965 static void intel_pt_recording_free(struct auxtrace_record *itr)
966 {
967 	struct intel_pt_recording *ptr =
968 			container_of(itr, struct intel_pt_recording, itr);
969 
970 	intel_pt_free_snapshot_refs(ptr);
971 	free(ptr);
972 }
973 
974 static int intel_pt_alloc_snapshot_ref(struct intel_pt_recording *ptr, int idx,
975 				       size_t snapshot_buf_size)
976 {
977 	size_t ref_buf_size = ptr->snapshot_ref_buf_size;
978 	void *ref_buf;
979 
980 	ref_buf = zalloc(ref_buf_size);
981 	if (!ref_buf)
982 		return -ENOMEM;
983 
984 	ptr->snapshot_refs[idx].ref_buf = ref_buf;
985 	ptr->snapshot_refs[idx].ref_offset = snapshot_buf_size - ref_buf_size;
986 
987 	return 0;
988 }
989 
990 static size_t intel_pt_snapshot_ref_buf_size(struct intel_pt_recording *ptr,
991 					     size_t snapshot_buf_size)
992 {
993 	const size_t max_size = 256 * 1024;
994 	size_t buf_size = 0, psb_period;
995 
996 	if (ptr->snapshot_size <= 64 * 1024)
997 		return 0;
998 
999 	psb_period = intel_pt_psb_period(ptr->intel_pt_pmu, ptr->evlist);
1000 	if (psb_period)
1001 		buf_size = psb_period * 2;
1002 
1003 	if (!buf_size || buf_size > max_size)
1004 		buf_size = max_size;
1005 
1006 	if (buf_size >= snapshot_buf_size)
1007 		return 0;
1008 
1009 	if (buf_size >= ptr->snapshot_size / 2)
1010 		return 0;
1011 
1012 	return buf_size;
1013 }
1014 
1015 static int intel_pt_snapshot_init(struct intel_pt_recording *ptr,
1016 				  size_t snapshot_buf_size)
1017 {
1018 	if (ptr->snapshot_init_done)
1019 		return 0;
1020 
1021 	ptr->snapshot_init_done = true;
1022 
1023 	ptr->snapshot_ref_buf_size = intel_pt_snapshot_ref_buf_size(ptr,
1024 							snapshot_buf_size);
1025 
1026 	return 0;
1027 }
1028 
1029 /**
1030  * intel_pt_compare_buffers - compare bytes in a buffer to a circular buffer.
1031  * @buf1: first buffer
1032  * @compare_size: number of bytes to compare
1033  * @buf2: second buffer (a circular buffer)
1034  * @offs2: offset in second buffer
1035  * @buf2_size: size of second buffer
1036  *
1037  * The comparison allows for the possibility that the bytes to compare in the
1038  * circular buffer are not contiguous.  It is assumed that @compare_size <=
1039  * @buf2_size.  This function returns %false if the bytes are identical, %true
1040  * otherwise.
1041  */
1042 static bool intel_pt_compare_buffers(void *buf1, size_t compare_size,
1043 				     void *buf2, size_t offs2, size_t buf2_size)
1044 {
1045 	size_t end2 = offs2 + compare_size, part_size;
1046 
1047 	if (end2 <= buf2_size)
1048 		return memcmp(buf1, buf2 + offs2, compare_size);
1049 
1050 	part_size = end2 - buf2_size;
1051 	if (memcmp(buf1, buf2 + offs2, part_size))
1052 		return true;
1053 
1054 	compare_size -= part_size;
1055 
1056 	return memcmp(buf1 + part_size, buf2, compare_size);
1057 }
1058 
1059 static bool intel_pt_compare_ref(void *ref_buf, size_t ref_offset,
1060 				 size_t ref_size, size_t buf_size,
1061 				 void *data, size_t head)
1062 {
1063 	size_t ref_end = ref_offset + ref_size;
1064 
1065 	if (ref_end > buf_size) {
1066 		if (head > ref_offset || head < ref_end - buf_size)
1067 			return true;
1068 	} else if (head > ref_offset && head < ref_end) {
1069 		return true;
1070 	}
1071 
1072 	return intel_pt_compare_buffers(ref_buf, ref_size, data, ref_offset,
1073 					buf_size);
1074 }
1075 
1076 static void intel_pt_copy_ref(void *ref_buf, size_t ref_size, size_t buf_size,
1077 			      void *data, size_t head)
1078 {
1079 	if (head >= ref_size) {
1080 		memcpy(ref_buf, data + head - ref_size, ref_size);
1081 	} else {
1082 		memcpy(ref_buf, data, head);
1083 		ref_size -= head;
1084 		memcpy(ref_buf + head, data + buf_size - ref_size, ref_size);
1085 	}
1086 }
1087 
1088 static bool intel_pt_wrapped(struct intel_pt_recording *ptr, int idx,
1089 			     struct auxtrace_mmap *mm, unsigned char *data,
1090 			     u64 head)
1091 {
1092 	struct intel_pt_snapshot_ref *ref = &ptr->snapshot_refs[idx];
1093 	bool wrapped;
1094 
1095 	wrapped = intel_pt_compare_ref(ref->ref_buf, ref->ref_offset,
1096 				       ptr->snapshot_ref_buf_size, mm->len,
1097 				       data, head);
1098 
1099 	intel_pt_copy_ref(ref->ref_buf, ptr->snapshot_ref_buf_size, mm->len,
1100 			  data, head);
1101 
1102 	return wrapped;
1103 }
1104 
1105 static bool intel_pt_first_wrap(u64 *data, size_t buf_size)
1106 {
1107 	int i, a, b;
1108 
1109 	b = buf_size >> 3;
1110 	a = b - 512;
1111 	if (a < 0)
1112 		a = 0;
1113 
1114 	for (i = a; i < b; i++) {
1115 		if (data[i])
1116 			return true;
1117 	}
1118 
1119 	return false;
1120 }
1121 
1122 static int intel_pt_find_snapshot(struct auxtrace_record *itr, int idx,
1123 				  struct auxtrace_mmap *mm, unsigned char *data,
1124 				  u64 *head, u64 *old)
1125 {
1126 	struct intel_pt_recording *ptr =
1127 			container_of(itr, struct intel_pt_recording, itr);
1128 	bool wrapped;
1129 	int err;
1130 
1131 	pr_debug3("%s: mmap index %d old head %zu new head %zu\n",
1132 		  __func__, idx, (size_t)*old, (size_t)*head);
1133 
1134 	err = intel_pt_snapshot_init(ptr, mm->len);
1135 	if (err)
1136 		goto out_err;
1137 
1138 	if (idx >= ptr->snapshot_ref_cnt) {
1139 		err = intel_pt_alloc_snapshot_refs(ptr, idx);
1140 		if (err)
1141 			goto out_err;
1142 	}
1143 
1144 	if (ptr->snapshot_ref_buf_size) {
1145 		if (!ptr->snapshot_refs[idx].ref_buf) {
1146 			err = intel_pt_alloc_snapshot_ref(ptr, idx, mm->len);
1147 			if (err)
1148 				goto out_err;
1149 		}
1150 		wrapped = intel_pt_wrapped(ptr, idx, mm, data, *head);
1151 	} else {
1152 		wrapped = ptr->snapshot_refs[idx].wrapped;
1153 		if (!wrapped && intel_pt_first_wrap((u64 *)data, mm->len)) {
1154 			ptr->snapshot_refs[idx].wrapped = true;
1155 			wrapped = true;
1156 		}
1157 	}
1158 
1159 	/*
1160 	 * In full trace mode 'head' continually increases.  However in snapshot
1161 	 * mode 'head' is an offset within the buffer.  Here 'old' and 'head'
1162 	 * are adjusted to match the full trace case which expects that 'old' is
1163 	 * always less than 'head'.
1164 	 */
1165 	if (wrapped) {
1166 		*old = *head;
1167 		*head += mm->len;
1168 	} else {
1169 		if (mm->mask)
1170 			*old &= mm->mask;
1171 		else
1172 			*old %= mm->len;
1173 		if (*old > *head)
1174 			*head += mm->len;
1175 	}
1176 
1177 	pr_debug3("%s: wrap-around %sdetected, adjusted old head %zu adjusted new head %zu\n",
1178 		  __func__, wrapped ? "" : "not ", (size_t)*old, (size_t)*head);
1179 
1180 	return 0;
1181 
1182 out_err:
1183 	pr_err("%s: failed, error %d\n", __func__, err);
1184 	return err;
1185 }
1186 
1187 static u64 intel_pt_reference(struct auxtrace_record *itr __maybe_unused)
1188 {
1189 	return rdtsc();
1190 }
1191 
1192 struct auxtrace_record *intel_pt_recording_init(int *err)
1193 {
1194 	struct perf_pmu *intel_pt_pmu = perf_pmu__find(INTEL_PT_PMU_NAME);
1195 	struct intel_pt_recording *ptr;
1196 
1197 	if (!intel_pt_pmu)
1198 		return NULL;
1199 
1200 	if (setenv("JITDUMP_USE_ARCH_TIMESTAMP", "1", 1)) {
1201 		*err = -errno;
1202 		return NULL;
1203 	}
1204 
1205 	ptr = zalloc(sizeof(struct intel_pt_recording));
1206 	if (!ptr) {
1207 		*err = -ENOMEM;
1208 		return NULL;
1209 	}
1210 
1211 	ptr->intel_pt_pmu = intel_pt_pmu;
1212 	ptr->itr.pmu = intel_pt_pmu;
1213 	ptr->itr.recording_options = intel_pt_recording_options;
1214 	ptr->itr.info_priv_size = intel_pt_info_priv_size;
1215 	ptr->itr.info_fill = intel_pt_info_fill;
1216 	ptr->itr.free = intel_pt_recording_free;
1217 	ptr->itr.snapshot_start = intel_pt_snapshot_start;
1218 	ptr->itr.snapshot_finish = intel_pt_snapshot_finish;
1219 	ptr->itr.find_snapshot = intel_pt_find_snapshot;
1220 	ptr->itr.parse_snapshot_options = intel_pt_parse_snapshot_options;
1221 	ptr->itr.reference = intel_pt_reference;
1222 	ptr->itr.read_finish = auxtrace_record__read_finish;
1223 	/*
1224 	 * Decoding starts at a PSB packet. Minimum PSB period is 2K so 4K
1225 	 * should give at least 1 PSB per sample.
1226 	 */
1227 	ptr->itr.default_aux_sample_size = 4096;
1228 	return &ptr->itr;
1229 }
1230