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