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