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