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