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