xref: /linux/tools/perf/util/intel-pt.c (revision 979e87ab1f258036aab9ed874aecede0163586e5)
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 <inttypes.h>
8 #include <linux/perf_event.h>
9 #include <stdio.h>
10 #include <stdbool.h>
11 #include <errno.h>
12 #include <linux/kernel.h>
13 #include <linux/string.h>
14 #include <linux/types.h>
15 #include <linux/zalloc.h>
16 
17 #include "session.h"
18 #include "machine.h"
19 #include "memswap.h"
20 #include "sort.h"
21 #include "tool.h"
22 #include "event.h"
23 #include "evlist.h"
24 #include "evsel.h"
25 #include "map.h"
26 #include "color.h"
27 #include "thread.h"
28 #include "thread-stack.h"
29 #include "symbol.h"
30 #include "callchain.h"
31 #include "dso.h"
32 #include "debug.h"
33 #include "auxtrace.h"
34 #include "tsc.h"
35 #include "intel-pt.h"
36 #include "config.h"
37 #include "util/perf_api_probe.h"
38 #include "util/synthetic-events.h"
39 #include "time-utils.h"
40 
41 #include "../arch/x86/include/uapi/asm/perf_regs.h"
42 
43 #include "intel-pt-decoder/intel-pt-log.h"
44 #include "intel-pt-decoder/intel-pt-decoder.h"
45 #include "intel-pt-decoder/intel-pt-insn-decoder.h"
46 #include "intel-pt-decoder/intel-pt-pkt-decoder.h"
47 
48 #define MAX_TIMESTAMP (~0ULL)
49 
50 #define INTEL_PT_CFG_PASS_THRU	BIT_ULL(0)
51 #define INTEL_PT_CFG_PWR_EVT_EN	BIT_ULL(4)
52 #define INTEL_PT_CFG_BRANCH_EN	BIT_ULL(13)
53 #define INTEL_PT_CFG_EVT_EN	BIT_ULL(31)
54 #define INTEL_PT_CFG_TNT_DIS	BIT_ULL(55)
55 
56 struct range {
57 	u64 start;
58 	u64 end;
59 };
60 
61 struct intel_pt {
62 	struct auxtrace auxtrace;
63 	struct auxtrace_queues queues;
64 	struct auxtrace_heap heap;
65 	u32 auxtrace_type;
66 	struct perf_session *session;
67 	struct machine *machine;
68 	struct evsel *switch_evsel;
69 	struct thread *unknown_thread;
70 	bool timeless_decoding;
71 	bool sampling_mode;
72 	bool snapshot_mode;
73 	bool per_cpu_mmaps;
74 	bool have_tsc;
75 	bool data_queued;
76 	bool est_tsc;
77 	bool sync_switch;
78 	bool sync_switch_not_supported;
79 	bool mispred_all;
80 	bool use_thread_stack;
81 	bool callstack;
82 	bool cap_event_trace;
83 	bool have_guest_sideband;
84 	unsigned int br_stack_sz;
85 	unsigned int br_stack_sz_plus;
86 	int have_sched_switch;
87 	u32 pmu_type;
88 	u64 kernel_start;
89 	u64 switch_ip;
90 	u64 ptss_ip;
91 	u64 first_timestamp;
92 
93 	struct perf_tsc_conversion tc;
94 	bool cap_user_time_zero;
95 
96 	struct itrace_synth_opts synth_opts;
97 
98 	bool sample_instructions;
99 	u64 instructions_sample_type;
100 	u64 instructions_id;
101 
102 	bool sample_cycles;
103 	u64 cycles_sample_type;
104 	u64 cycles_id;
105 
106 	bool sample_branches;
107 	u32 branches_filter;
108 	u64 branches_sample_type;
109 	u64 branches_id;
110 
111 	bool sample_transactions;
112 	u64 transactions_sample_type;
113 	u64 transactions_id;
114 
115 	bool sample_ptwrites;
116 	u64 ptwrites_sample_type;
117 	u64 ptwrites_id;
118 
119 	bool sample_pwr_events;
120 	u64 pwr_events_sample_type;
121 	u64 mwait_id;
122 	u64 pwre_id;
123 	u64 exstop_id;
124 	u64 pwrx_id;
125 	u64 cbr_id;
126 	u64 psb_id;
127 
128 	bool single_pebs;
129 	bool sample_pebs;
130 	int pebs_data_src_fmt;
131 	struct evsel *pebs_evsel;
132 
133 	u64 evt_sample_type;
134 	u64 evt_id;
135 
136 	u64 iflag_chg_sample_type;
137 	u64 iflag_chg_id;
138 
139 	u64 tsc_bit;
140 	u64 mtc_bit;
141 	u64 mtc_freq_bits;
142 	u32 tsc_ctc_ratio_n;
143 	u32 tsc_ctc_ratio_d;
144 	u64 cyc_bit;
145 	u64 noretcomp_bit;
146 	unsigned max_non_turbo_ratio;
147 	unsigned cbr2khz;
148 	int max_loops;
149 
150 	unsigned long num_events;
151 
152 	char *filter;
153 	struct addr_filters filts;
154 
155 	struct range *time_ranges;
156 	unsigned int range_cnt;
157 
158 	struct ip_callchain *chain;
159 	struct branch_stack *br_stack;
160 
161 	u64 dflt_tsc_offset;
162 	struct rb_root vmcs_info;
163 };
164 
165 enum switch_state {
166 	INTEL_PT_SS_NOT_TRACING,
167 	INTEL_PT_SS_UNKNOWN,
168 	INTEL_PT_SS_TRACING,
169 	INTEL_PT_SS_EXPECTING_SWITCH_EVENT,
170 	INTEL_PT_SS_EXPECTING_SWITCH_IP,
171 };
172 
173 /* applicable_counters is 64-bits */
174 #define INTEL_PT_MAX_PEBS 64
175 
176 struct intel_pt_pebs_event {
177 	struct evsel *evsel;
178 	u64 id;
179 	int data_src_fmt;
180 };
181 
182 struct intel_pt_queue {
183 	struct intel_pt *pt;
184 	unsigned int queue_nr;
185 	struct auxtrace_buffer *buffer;
186 	struct auxtrace_buffer *old_buffer;
187 	void *decoder;
188 	const struct intel_pt_state *state;
189 	struct ip_callchain *chain;
190 	struct branch_stack *last_branch;
191 	union perf_event *event_buf;
192 	bool on_heap;
193 	bool stop;
194 	bool step_through_buffers;
195 	bool use_buffer_pid_tid;
196 	bool sync_switch;
197 	bool sample_ipc;
198 	pid_t pid, tid;
199 	int cpu;
200 	int switch_state;
201 	pid_t next_tid;
202 	struct thread *thread;
203 	struct machine *guest_machine;
204 	struct thread *guest_thread;
205 	struct thread *unknown_guest_thread;
206 	pid_t guest_machine_pid;
207 	pid_t guest_pid;
208 	pid_t guest_tid;
209 	int vcpu;
210 	bool exclude_kernel;
211 	bool have_sample;
212 	u64 time;
213 	u64 timestamp;
214 	u64 sel_timestamp;
215 	bool sel_start;
216 	unsigned int sel_idx;
217 	u32 flags;
218 	u16 insn_len;
219 	u64 last_insn_cnt;
220 	u64 ipc_insn_cnt;
221 	u64 ipc_cyc_cnt;
222 	u64 last_in_insn_cnt;
223 	u64 last_in_cyc_cnt;
224 	u64 last_cy_insn_cnt;
225 	u64 last_cy_cyc_cnt;
226 	u64 last_br_insn_cnt;
227 	u64 last_br_cyc_cnt;
228 	unsigned int cbr_seen;
229 	char insn[INTEL_PT_INSN_BUF_SZ];
230 	struct intel_pt_pebs_event pebs[INTEL_PT_MAX_PEBS];
231 };
232 
233 static void intel_pt_dump(struct intel_pt *pt __maybe_unused,
234 			  unsigned char *buf, size_t len)
235 {
236 	struct intel_pt_pkt packet;
237 	size_t pos = 0;
238 	int ret, pkt_len, i;
239 	char desc[INTEL_PT_PKT_DESC_MAX];
240 	const char *color = PERF_COLOR_BLUE;
241 	enum intel_pt_pkt_ctx ctx = INTEL_PT_NO_CTX;
242 
243 	color_fprintf(stdout, color,
244 		      ". ... Intel Processor Trace data: size %zu bytes\n",
245 		      len);
246 
247 	while (len) {
248 		ret = intel_pt_get_packet(buf, len, &packet, &ctx);
249 		if (ret > 0)
250 			pkt_len = ret;
251 		else
252 			pkt_len = 1;
253 		printf(".");
254 		color_fprintf(stdout, color, "  %08zx: ", pos);
255 		for (i = 0; i < pkt_len; i++)
256 			color_fprintf(stdout, color, " %02x", buf[i]);
257 		for (; i < 16; i++)
258 			color_fprintf(stdout, color, "   ");
259 		if (ret > 0) {
260 			ret = intel_pt_pkt_desc(&packet, desc,
261 						INTEL_PT_PKT_DESC_MAX);
262 			if (ret > 0)
263 				color_fprintf(stdout, color, " %s\n", desc);
264 		} else {
265 			color_fprintf(stdout, color, " Bad packet!\n");
266 		}
267 		pos += pkt_len;
268 		buf += pkt_len;
269 		len -= pkt_len;
270 	}
271 }
272 
273 static void intel_pt_dump_event(struct intel_pt *pt, unsigned char *buf,
274 				size_t len)
275 {
276 	printf(".\n");
277 	intel_pt_dump(pt, buf, len);
278 }
279 
280 static void intel_pt_log_event(union perf_event *event)
281 {
282 	FILE *f = intel_pt_log_fp();
283 
284 	if (!intel_pt_enable_logging || !f)
285 		return;
286 
287 	perf_event__fprintf(event, NULL, f);
288 }
289 
290 static void intel_pt_dump_sample(struct perf_session *session,
291 				 struct perf_sample *sample)
292 {
293 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
294 					   auxtrace);
295 
296 	printf("\n");
297 	intel_pt_dump(pt, sample->aux_sample.data, sample->aux_sample.size);
298 }
299 
300 static bool intel_pt_log_events(struct intel_pt *pt, u64 tm)
301 {
302 	struct perf_time_interval *range = pt->synth_opts.ptime_range;
303 	int n = pt->synth_opts.range_num;
304 
305 	if (pt->synth_opts.log_plus_flags & AUXTRACE_LOG_FLG_ALL_PERF_EVTS)
306 		return true;
307 
308 	if (pt->synth_opts.log_minus_flags & AUXTRACE_LOG_FLG_ALL_PERF_EVTS)
309 		return false;
310 
311 	/* perf_time__ranges_skip_sample does not work if time is zero */
312 	if (!tm)
313 		tm = 1;
314 
315 	return !n || !perf_time__ranges_skip_sample(range, n, tm);
316 }
317 
318 static struct intel_pt_vmcs_info *intel_pt_findnew_vmcs(struct rb_root *rb_root,
319 							u64 vmcs,
320 							u64 dflt_tsc_offset)
321 {
322 	struct rb_node **p = &rb_root->rb_node;
323 	struct rb_node *parent = NULL;
324 	struct intel_pt_vmcs_info *v;
325 
326 	while (*p) {
327 		parent = *p;
328 		v = rb_entry(parent, struct intel_pt_vmcs_info, rb_node);
329 
330 		if (v->vmcs == vmcs)
331 			return v;
332 
333 		if (vmcs < v->vmcs)
334 			p = &(*p)->rb_left;
335 		else
336 			p = &(*p)->rb_right;
337 	}
338 
339 	v = zalloc(sizeof(*v));
340 	if (v) {
341 		v->vmcs = vmcs;
342 		v->tsc_offset = dflt_tsc_offset;
343 		v->reliable = dflt_tsc_offset;
344 
345 		rb_link_node(&v->rb_node, parent, p);
346 		rb_insert_color(&v->rb_node, rb_root);
347 	}
348 
349 	return v;
350 }
351 
352 static struct intel_pt_vmcs_info *intel_pt_findnew_vmcs_info(void *data, uint64_t vmcs)
353 {
354 	struct intel_pt_queue *ptq = data;
355 	struct intel_pt *pt = ptq->pt;
356 
357 	if (!vmcs && !pt->dflt_tsc_offset)
358 		return NULL;
359 
360 	return intel_pt_findnew_vmcs(&pt->vmcs_info, vmcs, pt->dflt_tsc_offset);
361 }
362 
363 static void intel_pt_free_vmcs_info(struct intel_pt *pt)
364 {
365 	struct intel_pt_vmcs_info *v;
366 	struct rb_node *n;
367 
368 	n = rb_first(&pt->vmcs_info);
369 	while (n) {
370 		v = rb_entry(n, struct intel_pt_vmcs_info, rb_node);
371 		n = rb_next(n);
372 		rb_erase(&v->rb_node, &pt->vmcs_info);
373 		free(v);
374 	}
375 }
376 
377 static int intel_pt_do_fix_overlap(struct intel_pt *pt, struct auxtrace_buffer *a,
378 				   struct auxtrace_buffer *b)
379 {
380 	bool consecutive = false;
381 	void *start;
382 
383 	start = intel_pt_find_overlap(a->data, a->size, b->data, b->size,
384 				      pt->have_tsc, &consecutive,
385 				      pt->synth_opts.vm_time_correlation);
386 	if (!start)
387 		return -EINVAL;
388 	/*
389 	 * In the case of vm_time_correlation, the overlap might contain TSC
390 	 * packets that will not be fixed, and that will then no longer work for
391 	 * overlap detection. Avoid that by zeroing out the overlap.
392 	 */
393 	if (pt->synth_opts.vm_time_correlation)
394 		memset(b->data, 0, start - b->data);
395 	b->use_size = b->data + b->size - start;
396 	b->use_data = start;
397 	if (b->use_size && consecutive)
398 		b->consecutive = true;
399 	return 0;
400 }
401 
402 static int intel_pt_get_buffer(struct intel_pt_queue *ptq,
403 			       struct auxtrace_buffer *buffer,
404 			       struct auxtrace_buffer *old_buffer,
405 			       struct intel_pt_buffer *b)
406 {
407 	bool might_overlap;
408 
409 	if (!buffer->data) {
410 		int fd = perf_data__fd(ptq->pt->session->data);
411 
412 		buffer->data = auxtrace_buffer__get_data(buffer, fd);
413 		if (!buffer->data)
414 			return -ENOMEM;
415 	}
416 
417 	might_overlap = ptq->pt->snapshot_mode || ptq->pt->sampling_mode;
418 	if (might_overlap && !buffer->consecutive && old_buffer &&
419 	    intel_pt_do_fix_overlap(ptq->pt, old_buffer, buffer))
420 		return -ENOMEM;
421 
422 	if (buffer->use_data) {
423 		b->len = buffer->use_size;
424 		b->buf = buffer->use_data;
425 	} else {
426 		b->len = buffer->size;
427 		b->buf = buffer->data;
428 	}
429 	b->ref_timestamp = buffer->reference;
430 
431 	if (!old_buffer || (might_overlap && !buffer->consecutive)) {
432 		b->consecutive = false;
433 		b->trace_nr = buffer->buffer_nr + 1;
434 	} else {
435 		b->consecutive = true;
436 	}
437 
438 	return 0;
439 }
440 
441 /* Do not drop buffers with references - refer intel_pt_get_trace() */
442 static void intel_pt_lookahead_drop_buffer(struct intel_pt_queue *ptq,
443 					   struct auxtrace_buffer *buffer)
444 {
445 	if (!buffer || buffer == ptq->buffer || buffer == ptq->old_buffer)
446 		return;
447 
448 	auxtrace_buffer__drop_data(buffer);
449 }
450 
451 /* Must be serialized with respect to intel_pt_get_trace() */
452 static int intel_pt_lookahead(void *data, intel_pt_lookahead_cb_t cb,
453 			      void *cb_data)
454 {
455 	struct intel_pt_queue *ptq = data;
456 	struct auxtrace_buffer *buffer = ptq->buffer;
457 	struct auxtrace_buffer *old_buffer = ptq->old_buffer;
458 	struct auxtrace_queue *queue;
459 	int err = 0;
460 
461 	queue = &ptq->pt->queues.queue_array[ptq->queue_nr];
462 
463 	while (1) {
464 		struct intel_pt_buffer b = { .len = 0 };
465 
466 		buffer = auxtrace_buffer__next(queue, buffer);
467 		if (!buffer)
468 			break;
469 
470 		err = intel_pt_get_buffer(ptq, buffer, old_buffer, &b);
471 		if (err)
472 			break;
473 
474 		if (b.len) {
475 			intel_pt_lookahead_drop_buffer(ptq, old_buffer);
476 			old_buffer = buffer;
477 		} else {
478 			intel_pt_lookahead_drop_buffer(ptq, buffer);
479 			continue;
480 		}
481 
482 		err = cb(&b, cb_data);
483 		if (err)
484 			break;
485 	}
486 
487 	if (buffer != old_buffer)
488 		intel_pt_lookahead_drop_buffer(ptq, buffer);
489 	intel_pt_lookahead_drop_buffer(ptq, old_buffer);
490 
491 	return err;
492 }
493 
494 /*
495  * This function assumes data is processed sequentially only.
496  * Must be serialized with respect to intel_pt_lookahead()
497  */
498 static int intel_pt_get_trace(struct intel_pt_buffer *b, void *data)
499 {
500 	struct intel_pt_queue *ptq = data;
501 	struct auxtrace_buffer *buffer = ptq->buffer;
502 	struct auxtrace_buffer *old_buffer = ptq->old_buffer;
503 	struct auxtrace_queue *queue;
504 	int err;
505 
506 	if (ptq->stop) {
507 		b->len = 0;
508 		return 0;
509 	}
510 
511 	queue = &ptq->pt->queues.queue_array[ptq->queue_nr];
512 
513 	buffer = auxtrace_buffer__next(queue, buffer);
514 	if (!buffer) {
515 		if (old_buffer)
516 			auxtrace_buffer__drop_data(old_buffer);
517 		b->len = 0;
518 		return 0;
519 	}
520 
521 	ptq->buffer = buffer;
522 
523 	err = intel_pt_get_buffer(ptq, buffer, old_buffer, b);
524 	if (err)
525 		return err;
526 
527 	if (ptq->step_through_buffers)
528 		ptq->stop = true;
529 
530 	if (b->len) {
531 		if (old_buffer)
532 			auxtrace_buffer__drop_data(old_buffer);
533 		ptq->old_buffer = buffer;
534 	} else {
535 		auxtrace_buffer__drop_data(buffer);
536 		return intel_pt_get_trace(b, data);
537 	}
538 
539 	return 0;
540 }
541 
542 struct intel_pt_cache_entry {
543 	struct auxtrace_cache_entry	entry;
544 	u64				insn_cnt;
545 	u64				byte_cnt;
546 	enum intel_pt_insn_op		op;
547 	enum intel_pt_insn_branch	branch;
548 	bool				emulated_ptwrite;
549 	int				length;
550 	int32_t				rel;
551 	char				insn[INTEL_PT_INSN_BUF_SZ];
552 };
553 
554 static int intel_pt_config_div(const char *var, const char *value, void *data)
555 {
556 	int *d = data;
557 	long val;
558 
559 	if (!strcmp(var, "intel-pt.cache-divisor")) {
560 		val = strtol(value, NULL, 0);
561 		if (val > 0 && val <= INT_MAX)
562 			*d = val;
563 	}
564 
565 	return 0;
566 }
567 
568 static int intel_pt_cache_divisor(void)
569 {
570 	static int d;
571 
572 	if (d)
573 		return d;
574 
575 	perf_config(intel_pt_config_div, &d);
576 
577 	if (!d)
578 		d = 64;
579 
580 	return d;
581 }
582 
583 static unsigned int intel_pt_cache_size(struct dso *dso,
584 					struct machine *machine)
585 {
586 	off_t size;
587 
588 	size = dso__data_size(dso, machine);
589 	size /= intel_pt_cache_divisor();
590 	if (size < 1000)
591 		return 10;
592 	if (size > (1 << 21))
593 		return 21;
594 	return 32 - __builtin_clz(size);
595 }
596 
597 static struct auxtrace_cache *intel_pt_cache(struct dso *dso,
598 					     struct machine *machine)
599 {
600 	struct auxtrace_cache *c;
601 	unsigned int bits;
602 
603 	if (dso__auxtrace_cache(dso))
604 		return dso__auxtrace_cache(dso);
605 
606 	bits = intel_pt_cache_size(dso, machine);
607 
608 	/* Ignoring cache creation failure */
609 	c = auxtrace_cache__new(bits, sizeof(struct intel_pt_cache_entry), 200);
610 
611 	dso__set_auxtrace_cache(dso, c);
612 
613 	return c;
614 }
615 
616 static int intel_pt_cache_add(struct dso *dso, struct machine *machine,
617 			      u64 offset, u64 insn_cnt, u64 byte_cnt,
618 			      struct intel_pt_insn *intel_pt_insn)
619 {
620 	struct auxtrace_cache *c = intel_pt_cache(dso, machine);
621 	struct intel_pt_cache_entry *e;
622 	int err;
623 
624 	if (!c)
625 		return -ENOMEM;
626 
627 	e = auxtrace_cache__alloc_entry(c);
628 	if (!e)
629 		return -ENOMEM;
630 
631 	e->insn_cnt = insn_cnt;
632 	e->byte_cnt = byte_cnt;
633 	e->op = intel_pt_insn->op;
634 	e->branch = intel_pt_insn->branch;
635 	e->emulated_ptwrite = intel_pt_insn->emulated_ptwrite;
636 	e->length = intel_pt_insn->length;
637 	e->rel = intel_pt_insn->rel;
638 	memcpy(e->insn, intel_pt_insn->buf, INTEL_PT_INSN_BUF_SZ);
639 
640 	err = auxtrace_cache__add(c, offset, &e->entry);
641 	if (err)
642 		auxtrace_cache__free_entry(c, e);
643 
644 	return err;
645 }
646 
647 static struct intel_pt_cache_entry *
648 intel_pt_cache_lookup(struct dso *dso, struct machine *machine, u64 offset)
649 {
650 	struct auxtrace_cache *c = intel_pt_cache(dso, machine);
651 
652 	if (!c)
653 		return NULL;
654 
655 	return auxtrace_cache__lookup(dso__auxtrace_cache(dso), offset);
656 }
657 
658 static void intel_pt_cache_invalidate(struct dso *dso, struct machine *machine,
659 				      u64 offset)
660 {
661 	struct auxtrace_cache *c = intel_pt_cache(dso, machine);
662 
663 	if (!c)
664 		return;
665 
666 	auxtrace_cache__remove(dso__auxtrace_cache(dso), offset);
667 }
668 
669 static inline bool intel_pt_guest_kernel_ip(uint64_t ip)
670 {
671 	/* Assumes 64-bit kernel */
672 	return ip & (1ULL << 63);
673 }
674 
675 static inline u8 intel_pt_nr_cpumode(struct intel_pt_queue *ptq, uint64_t ip, bool nr)
676 {
677 	if (nr) {
678 		return intel_pt_guest_kernel_ip(ip) ?
679 		       PERF_RECORD_MISC_GUEST_KERNEL :
680 		       PERF_RECORD_MISC_GUEST_USER;
681 	}
682 
683 	return ip >= ptq->pt->kernel_start ?
684 	       PERF_RECORD_MISC_KERNEL :
685 	       PERF_RECORD_MISC_USER;
686 }
687 
688 static inline u8 intel_pt_cpumode(struct intel_pt_queue *ptq, uint64_t from_ip, uint64_t to_ip)
689 {
690 	/* No support for non-zero CS base */
691 	if (from_ip)
692 		return intel_pt_nr_cpumode(ptq, from_ip, ptq->state->from_nr);
693 	return intel_pt_nr_cpumode(ptq, to_ip, ptq->state->to_nr);
694 }
695 
696 static int intel_pt_get_guest(struct intel_pt_queue *ptq)
697 {
698 	struct machines *machines = &ptq->pt->session->machines;
699 	struct machine *machine;
700 	pid_t pid = ptq->pid <= 0 ? DEFAULT_GUEST_KERNEL_ID : ptq->pid;
701 
702 	if (ptq->guest_machine && pid == ptq->guest_machine->pid)
703 		return 0;
704 
705 	ptq->guest_machine = NULL;
706 	thread__zput(ptq->unknown_guest_thread);
707 
708 	if (symbol_conf.guest_code) {
709 		thread__zput(ptq->guest_thread);
710 		ptq->guest_thread = machines__findnew_guest_code(machines, pid);
711 	}
712 
713 	machine = machines__find_guest(machines, pid);
714 	if (!machine)
715 		return -1;
716 
717 	ptq->unknown_guest_thread = machine__idle_thread(machine);
718 	if (!ptq->unknown_guest_thread)
719 		return -1;
720 
721 	ptq->guest_machine = machine;
722 
723 	return 0;
724 }
725 
726 static inline bool intel_pt_jmp_16(struct intel_pt_insn *intel_pt_insn)
727 {
728 	return intel_pt_insn->rel == 16 && intel_pt_insn->branch == INTEL_PT_BR_UNCONDITIONAL;
729 }
730 
731 #define PTWRITE_MAGIC		"\x0f\x0bperf,ptwrite  "
732 #define PTWRITE_MAGIC_LEN	16
733 
734 static bool intel_pt_emulated_ptwrite(struct dso *dso, struct machine *machine, u64 offset)
735 {
736 	unsigned char buf[PTWRITE_MAGIC_LEN];
737 	ssize_t len;
738 
739 	len = dso__data_read_offset(dso, machine, offset, buf, PTWRITE_MAGIC_LEN);
740 	if (len == PTWRITE_MAGIC_LEN && !memcmp(buf, PTWRITE_MAGIC, PTWRITE_MAGIC_LEN)) {
741 		intel_pt_log("Emulated ptwrite signature found\n");
742 		return true;
743 	}
744 	intel_pt_log("Emulated ptwrite signature not found\n");
745 	return false;
746 }
747 
748 static int intel_pt_walk_next_insn(struct intel_pt_insn *intel_pt_insn,
749 				   uint64_t *insn_cnt_ptr, uint64_t *ip,
750 				   uint64_t to_ip, uint64_t max_insn_cnt,
751 				   void *data)
752 {
753 	struct intel_pt_queue *ptq = data;
754 	struct machine *machine = ptq->pt->machine;
755 	struct thread *thread;
756 	struct addr_location al;
757 	unsigned char buf[INTEL_PT_INSN_BUF_SZ];
758 	ssize_t len;
759 	int x86_64, ret = 0;
760 	u8 cpumode;
761 	u64 offset, start_offset, start_ip;
762 	u64 insn_cnt = 0;
763 	bool one_map = true;
764 	bool nr;
765 
766 
767 	addr_location__init(&al);
768 	intel_pt_insn->length = 0;
769 	intel_pt_insn->op = INTEL_PT_OP_OTHER;
770 
771 	if (to_ip && *ip == to_ip)
772 		goto out_no_cache;
773 
774 	nr = ptq->state->to_nr;
775 	cpumode = intel_pt_nr_cpumode(ptq, *ip, nr);
776 
777 	if (nr) {
778 		if (ptq->pt->have_guest_sideband) {
779 			if (!ptq->guest_machine || ptq->guest_machine_pid != ptq->pid) {
780 				intel_pt_log("ERROR: guest sideband but no guest machine\n");
781 				ret = -EINVAL;
782 				goto out_ret;
783 			}
784 		} else if ((!symbol_conf.guest_code && cpumode != PERF_RECORD_MISC_GUEST_KERNEL) ||
785 			   intel_pt_get_guest(ptq)) {
786 			intel_pt_log("ERROR: no guest machine\n");
787 			ret = -EINVAL;
788 			goto out_ret;
789 		}
790 		machine = ptq->guest_machine;
791 		thread = ptq->guest_thread;
792 		if (!thread) {
793 			if (cpumode != PERF_RECORD_MISC_GUEST_KERNEL) {
794 				intel_pt_log("ERROR: no guest thread\n");
795 				ret = -EINVAL;
796 				goto out_ret;
797 			}
798 			thread = ptq->unknown_guest_thread;
799 		}
800 	} else {
801 		thread = ptq->thread;
802 		if (!thread) {
803 			if (cpumode != PERF_RECORD_MISC_KERNEL) {
804 				intel_pt_log("ERROR: no thread\n");
805 				ret = -EINVAL;
806 				goto out_ret;
807 			}
808 			thread = ptq->pt->unknown_thread;
809 		}
810 	}
811 
812 	while (1) {
813 		struct dso *dso;
814 
815 		if (!thread__find_map(thread, cpumode, *ip, &al) || !map__dso(al.map)) {
816 			if (al.map)
817 				intel_pt_log("ERROR: thread has no dso for %#" PRIx64 "\n", *ip);
818 			else
819 				intel_pt_log("ERROR: thread has no map for %#" PRIx64 "\n", *ip);
820 			addr_location__exit(&al);
821 			ret = -EINVAL;
822 			goto out_ret;
823 		}
824 		dso = map__dso(al.map);
825 
826 		if (dso__data(dso)->status == DSO_DATA_STATUS_ERROR &&
827 		    dso__data_status_seen(dso, DSO_DATA_STATUS_SEEN_ITRACE)) {
828 			ret = -ENOENT;
829 			goto out_ret;
830 		}
831 
832 		offset = map__map_ip(al.map, *ip);
833 
834 		if (!to_ip && one_map) {
835 			struct intel_pt_cache_entry *e;
836 
837 			e = intel_pt_cache_lookup(dso, machine, offset);
838 			if (e &&
839 			    (!max_insn_cnt || e->insn_cnt <= max_insn_cnt)) {
840 				*insn_cnt_ptr = e->insn_cnt;
841 				*ip += e->byte_cnt;
842 				intel_pt_insn->op = e->op;
843 				intel_pt_insn->branch = e->branch;
844 				intel_pt_insn->emulated_ptwrite = e->emulated_ptwrite;
845 				intel_pt_insn->length = e->length;
846 				intel_pt_insn->rel = e->rel;
847 				memcpy(intel_pt_insn->buf, e->insn, INTEL_PT_INSN_BUF_SZ);
848 				intel_pt_log_insn_no_data(intel_pt_insn, *ip);
849 				ret = 0;
850 				goto out_ret;
851 			}
852 		}
853 
854 		start_offset = offset;
855 		start_ip = *ip;
856 
857 		/* Load maps to ensure dso->is_64_bit has been updated */
858 		map__load(al.map);
859 
860 		x86_64 = dso__is_64_bit(dso);
861 
862 		while (1) {
863 			len = dso__data_read_offset(dso, machine,
864 						    offset, buf,
865 						    INTEL_PT_INSN_BUF_SZ);
866 			if (len <= 0) {
867 				intel_pt_log("ERROR: failed to read at offset %#" PRIx64 " ",
868 					     offset);
869 				if (intel_pt_enable_logging)
870 					dso__fprintf(dso, intel_pt_log_fp());
871 				ret = -EINVAL;
872 				goto out_ret;
873 			}
874 
875 			if (intel_pt_get_insn(buf, len, x86_64, intel_pt_insn)) {
876 				ret = -EINVAL;
877 				goto out_ret;
878 			}
879 
880 			intel_pt_log_insn(intel_pt_insn, *ip);
881 
882 			insn_cnt += 1;
883 
884 			if (intel_pt_insn->branch != INTEL_PT_BR_NO_BRANCH) {
885 				bool eptw;
886 				u64 offs;
887 
888 				if (!intel_pt_jmp_16(intel_pt_insn))
889 					goto out;
890 				/* Check for emulated ptwrite */
891 				offs = offset + intel_pt_insn->length;
892 				eptw = intel_pt_emulated_ptwrite(dso, machine, offs);
893 				intel_pt_insn->emulated_ptwrite = eptw;
894 				goto out;
895 			}
896 
897 			if (max_insn_cnt && insn_cnt >= max_insn_cnt)
898 				goto out_no_cache;
899 
900 			*ip += intel_pt_insn->length;
901 
902 			if (to_ip && *ip == to_ip) {
903 				intel_pt_insn->length = 0;
904 				intel_pt_insn->op = INTEL_PT_OP_OTHER;
905 				goto out_no_cache;
906 			}
907 
908 			if (*ip >= map__end(al.map))
909 				break;
910 
911 			offset += intel_pt_insn->length;
912 		}
913 		one_map = false;
914 	}
915 out:
916 	*insn_cnt_ptr = insn_cnt;
917 
918 	if (!one_map)
919 		goto out_no_cache;
920 
921 	/*
922 	 * Didn't lookup in the 'to_ip' case, so do it now to prevent duplicate
923 	 * entries.
924 	 */
925 	if (to_ip) {
926 		struct intel_pt_cache_entry *e;
927 
928 		e = intel_pt_cache_lookup(map__dso(al.map), machine, start_offset);
929 		if (e)
930 			goto out_ret;
931 	}
932 
933 	/* Ignore cache errors */
934 	intel_pt_cache_add(map__dso(al.map), machine, start_offset, insn_cnt,
935 			   *ip - start_ip, intel_pt_insn);
936 
937 out_ret:
938 	addr_location__exit(&al);
939 	return ret;
940 
941 out_no_cache:
942 	*insn_cnt_ptr = insn_cnt;
943 	addr_location__exit(&al);
944 	return 0;
945 }
946 
947 static bool intel_pt_match_pgd_ip(struct intel_pt *pt, uint64_t ip,
948 				  uint64_t offset, const char *filename)
949 {
950 	struct addr_filter *filt;
951 	bool have_filter   = false;
952 	bool hit_tracestop = false;
953 	bool hit_filter    = false;
954 
955 	list_for_each_entry(filt, &pt->filts.head, list) {
956 		if (filt->start)
957 			have_filter = true;
958 
959 		if ((filename && !filt->filename) ||
960 		    (!filename && filt->filename) ||
961 		    (filename && strcmp(filename, filt->filename)))
962 			continue;
963 
964 		if (!(offset >= filt->addr && offset < filt->addr + filt->size))
965 			continue;
966 
967 		intel_pt_log("TIP.PGD ip %#"PRIx64" offset %#"PRIx64" in %s hit filter: %s offset %#"PRIx64" size %#"PRIx64"\n",
968 			     ip, offset, filename ? filename : "[kernel]",
969 			     filt->start ? "filter" : "stop",
970 			     filt->addr, filt->size);
971 
972 		if (filt->start)
973 			hit_filter = true;
974 		else
975 			hit_tracestop = true;
976 	}
977 
978 	if (!hit_tracestop && !hit_filter)
979 		intel_pt_log("TIP.PGD ip %#"PRIx64" offset %#"PRIx64" in %s is not in a filter region\n",
980 			     ip, offset, filename ? filename : "[kernel]");
981 
982 	return hit_tracestop || (have_filter && !hit_filter);
983 }
984 
985 static int __intel_pt_pgd_ip(uint64_t ip, void *data)
986 {
987 	struct intel_pt_queue *ptq = data;
988 	struct thread *thread;
989 	struct addr_location al;
990 	u8 cpumode;
991 	u64 offset;
992 	int res;
993 
994 	if (ptq->state->to_nr) {
995 		if (intel_pt_guest_kernel_ip(ip))
996 			return intel_pt_match_pgd_ip(ptq->pt, ip, ip, NULL);
997 		/* No support for decoding guest user space */
998 		return -EINVAL;
999 	} else if (ip >= ptq->pt->kernel_start) {
1000 		return intel_pt_match_pgd_ip(ptq->pt, ip, ip, NULL);
1001 	}
1002 
1003 	cpumode = PERF_RECORD_MISC_USER;
1004 
1005 	thread = ptq->thread;
1006 	if (!thread)
1007 		return -EINVAL;
1008 
1009 	addr_location__init(&al);
1010 	if (!thread__find_map(thread, cpumode, ip, &al) || !map__dso(al.map))
1011 		return -EINVAL;
1012 
1013 	offset = map__map_ip(al.map, ip);
1014 
1015 	res = intel_pt_match_pgd_ip(ptq->pt, ip, offset, dso__long_name(map__dso(al.map)));
1016 	addr_location__exit(&al);
1017 	return res;
1018 }
1019 
1020 static bool intel_pt_pgd_ip(uint64_t ip, void *data)
1021 {
1022 	return __intel_pt_pgd_ip(ip, data) > 0;
1023 }
1024 
1025 static bool intel_pt_get_config(struct intel_pt *pt,
1026 				struct perf_event_attr *attr, u64 *config)
1027 {
1028 	if (attr->type == pt->pmu_type) {
1029 		if (config)
1030 			*config = attr->config;
1031 		return true;
1032 	}
1033 
1034 	return false;
1035 }
1036 
1037 static bool intel_pt_exclude_kernel(struct intel_pt *pt)
1038 {
1039 	struct evsel *evsel;
1040 
1041 	evlist__for_each_entry(pt->session->evlist, evsel) {
1042 		if (intel_pt_get_config(pt, &evsel->core.attr, NULL) &&
1043 		    !evsel->core.attr.exclude_kernel)
1044 			return false;
1045 	}
1046 	return true;
1047 }
1048 
1049 static bool intel_pt_return_compression(struct intel_pt *pt)
1050 {
1051 	struct evsel *evsel;
1052 	u64 config;
1053 
1054 	if (!pt->noretcomp_bit)
1055 		return true;
1056 
1057 	evlist__for_each_entry(pt->session->evlist, evsel) {
1058 		if (intel_pt_get_config(pt, &evsel->core.attr, &config) &&
1059 		    (config & pt->noretcomp_bit))
1060 			return false;
1061 	}
1062 	return true;
1063 }
1064 
1065 static bool intel_pt_branch_enable(struct intel_pt *pt)
1066 {
1067 	struct evsel *evsel;
1068 	u64 config;
1069 
1070 	evlist__for_each_entry(pt->session->evlist, evsel) {
1071 		if (intel_pt_get_config(pt, &evsel->core.attr, &config) &&
1072 		    (config & INTEL_PT_CFG_PASS_THRU) &&
1073 		    !(config & INTEL_PT_CFG_BRANCH_EN))
1074 			return false;
1075 	}
1076 	return true;
1077 }
1078 
1079 static bool intel_pt_disabled_tnt(struct intel_pt *pt)
1080 {
1081 	struct evsel *evsel;
1082 	u64 config;
1083 
1084 	evlist__for_each_entry(pt->session->evlist, evsel) {
1085 		if (intel_pt_get_config(pt, &evsel->core.attr, &config) &&
1086 		    config & INTEL_PT_CFG_TNT_DIS)
1087 			return true;
1088 	}
1089 	return false;
1090 }
1091 
1092 static unsigned int intel_pt_mtc_period(struct intel_pt *pt)
1093 {
1094 	struct evsel *evsel;
1095 	unsigned int shift;
1096 	u64 config;
1097 
1098 	if (!pt->mtc_freq_bits)
1099 		return 0;
1100 
1101 	for (shift = 0, config = pt->mtc_freq_bits; !(config & 1); shift++)
1102 		config >>= 1;
1103 
1104 	evlist__for_each_entry(pt->session->evlist, evsel) {
1105 		if (intel_pt_get_config(pt, &evsel->core.attr, &config))
1106 			return (config & pt->mtc_freq_bits) >> shift;
1107 	}
1108 	return 0;
1109 }
1110 
1111 static bool intel_pt_timeless_decoding(struct intel_pt *pt)
1112 {
1113 	struct evsel *evsel;
1114 	bool timeless_decoding = true;
1115 	u64 config;
1116 
1117 	if (!pt->tsc_bit || !pt->cap_user_time_zero || pt->synth_opts.timeless_decoding)
1118 		return true;
1119 
1120 	evlist__for_each_entry(pt->session->evlist, evsel) {
1121 		if (!(evsel->core.attr.sample_type & PERF_SAMPLE_TIME))
1122 			return true;
1123 		if (intel_pt_get_config(pt, &evsel->core.attr, &config)) {
1124 			if (config & pt->tsc_bit)
1125 				timeless_decoding = false;
1126 			else
1127 				return true;
1128 		}
1129 	}
1130 	return timeless_decoding;
1131 }
1132 
1133 static bool intel_pt_tracing_kernel(struct intel_pt *pt)
1134 {
1135 	struct evsel *evsel;
1136 
1137 	evlist__for_each_entry(pt->session->evlist, evsel) {
1138 		if (intel_pt_get_config(pt, &evsel->core.attr, NULL) &&
1139 		    !evsel->core.attr.exclude_kernel)
1140 			return true;
1141 	}
1142 	return false;
1143 }
1144 
1145 static bool intel_pt_have_tsc(struct intel_pt *pt)
1146 {
1147 	struct evsel *evsel;
1148 	bool have_tsc = false;
1149 	u64 config;
1150 
1151 	if (!pt->tsc_bit)
1152 		return false;
1153 
1154 	evlist__for_each_entry(pt->session->evlist, evsel) {
1155 		if (intel_pt_get_config(pt, &evsel->core.attr, &config)) {
1156 			if (config & pt->tsc_bit)
1157 				have_tsc = true;
1158 			else
1159 				return false;
1160 		}
1161 	}
1162 	return have_tsc;
1163 }
1164 
1165 static bool intel_pt_have_mtc(struct intel_pt *pt)
1166 {
1167 	struct evsel *evsel;
1168 	u64 config;
1169 
1170 	evlist__for_each_entry(pt->session->evlist, evsel) {
1171 		if (intel_pt_get_config(pt, &evsel->core.attr, &config) &&
1172 		    (config & pt->mtc_bit))
1173 			return true;
1174 	}
1175 	return false;
1176 }
1177 
1178 static bool intel_pt_sampling_mode(struct intel_pt *pt)
1179 {
1180 	struct evsel *evsel;
1181 
1182 	evlist__for_each_entry(pt->session->evlist, evsel) {
1183 		if ((evsel->core.attr.sample_type & PERF_SAMPLE_AUX) &&
1184 		    evsel->core.attr.aux_sample_size)
1185 			return true;
1186 	}
1187 	return false;
1188 }
1189 
1190 static u64 intel_pt_ctl(struct intel_pt *pt)
1191 {
1192 	struct evsel *evsel;
1193 	u64 config;
1194 
1195 	evlist__for_each_entry(pt->session->evlist, evsel) {
1196 		if (intel_pt_get_config(pt, &evsel->core.attr, &config))
1197 			return config;
1198 	}
1199 	return 0;
1200 }
1201 
1202 static u64 intel_pt_ns_to_ticks(const struct intel_pt *pt, u64 ns)
1203 {
1204 	u64 quot, rem;
1205 
1206 	quot = ns / pt->tc.time_mult;
1207 	rem  = ns % pt->tc.time_mult;
1208 	return (quot << pt->tc.time_shift) + (rem << pt->tc.time_shift) /
1209 		pt->tc.time_mult;
1210 }
1211 
1212 static struct ip_callchain *intel_pt_alloc_chain(struct intel_pt *pt)
1213 {
1214 	size_t sz = sizeof(struct ip_callchain);
1215 
1216 	/* Add 1 to callchain_sz for callchain context */
1217 	sz += (pt->synth_opts.callchain_sz + 1) * sizeof(u64);
1218 	return zalloc(sz);
1219 }
1220 
1221 static int intel_pt_callchain_init(struct intel_pt *pt)
1222 {
1223 	struct evsel *evsel;
1224 
1225 	evlist__for_each_entry(pt->session->evlist, evsel) {
1226 		if (!(evsel->core.attr.sample_type & PERF_SAMPLE_CALLCHAIN))
1227 			evsel->synth_sample_type |= PERF_SAMPLE_CALLCHAIN;
1228 	}
1229 
1230 	pt->chain = intel_pt_alloc_chain(pt);
1231 	if (!pt->chain)
1232 		return -ENOMEM;
1233 
1234 	return 0;
1235 }
1236 
1237 static void intel_pt_add_callchain(struct intel_pt *pt,
1238 				   struct perf_sample *sample)
1239 {
1240 	struct thread *thread = machine__findnew_thread(pt->machine,
1241 							sample->pid,
1242 							sample->tid);
1243 
1244 	thread_stack__sample_late(thread, sample->cpu, pt->chain,
1245 				  pt->synth_opts.callchain_sz + 1, sample->ip,
1246 				  pt->kernel_start);
1247 
1248 	sample->callchain = pt->chain;
1249 }
1250 
1251 static struct branch_stack *intel_pt_alloc_br_stack(unsigned int entry_cnt)
1252 {
1253 	size_t sz = sizeof(struct branch_stack);
1254 
1255 	sz += entry_cnt * sizeof(struct branch_entry);
1256 	return zalloc(sz);
1257 }
1258 
1259 static int intel_pt_br_stack_init(struct intel_pt *pt)
1260 {
1261 	struct evsel *evsel;
1262 
1263 	evlist__for_each_entry(pt->session->evlist, evsel) {
1264 		if (!(evsel->core.attr.sample_type & PERF_SAMPLE_BRANCH_STACK))
1265 			evsel->synth_sample_type |= PERF_SAMPLE_BRANCH_STACK;
1266 	}
1267 
1268 	pt->br_stack = intel_pt_alloc_br_stack(pt->br_stack_sz);
1269 	if (!pt->br_stack)
1270 		return -ENOMEM;
1271 
1272 	return 0;
1273 }
1274 
1275 static void intel_pt_add_br_stack(struct intel_pt *pt,
1276 				  struct perf_sample *sample)
1277 {
1278 	struct thread *thread = machine__findnew_thread(pt->machine,
1279 							sample->pid,
1280 							sample->tid);
1281 
1282 	thread_stack__br_sample_late(thread, sample->cpu, pt->br_stack,
1283 				     pt->br_stack_sz, sample->ip,
1284 				     pt->kernel_start);
1285 
1286 	sample->branch_stack = pt->br_stack;
1287 	thread__put(thread);
1288 }
1289 
1290 /* INTEL_PT_LBR_0, INTEL_PT_LBR_1 and INTEL_PT_LBR_2 */
1291 #define LBRS_MAX (INTEL_PT_BLK_ITEM_ID_CNT * 3U)
1292 
1293 static struct intel_pt_queue *intel_pt_alloc_queue(struct intel_pt *pt,
1294 						   unsigned int queue_nr)
1295 {
1296 	struct intel_pt_params params = { .get_trace = 0, };
1297 	struct perf_env *env = pt->machine->env;
1298 	struct intel_pt_queue *ptq;
1299 
1300 	ptq = zalloc(sizeof(struct intel_pt_queue));
1301 	if (!ptq)
1302 		return NULL;
1303 
1304 	if (pt->synth_opts.callchain) {
1305 		ptq->chain = intel_pt_alloc_chain(pt);
1306 		if (!ptq->chain)
1307 			goto out_free;
1308 	}
1309 
1310 	if (pt->synth_opts.last_branch || pt->synth_opts.add_last_branch ||
1311 	    pt->synth_opts.other_events) {
1312 		unsigned int entry_cnt = max(LBRS_MAX, pt->br_stack_sz);
1313 
1314 		ptq->last_branch = intel_pt_alloc_br_stack(entry_cnt);
1315 		if (!ptq->last_branch)
1316 			goto out_free;
1317 	}
1318 
1319 	ptq->event_buf = malloc(PERF_SAMPLE_MAX_SIZE);
1320 	if (!ptq->event_buf)
1321 		goto out_free;
1322 
1323 	ptq->pt = pt;
1324 	ptq->queue_nr = queue_nr;
1325 	ptq->exclude_kernel = intel_pt_exclude_kernel(pt);
1326 	ptq->pid = -1;
1327 	ptq->tid = -1;
1328 	ptq->cpu = -1;
1329 	ptq->next_tid = -1;
1330 
1331 	params.get_trace = intel_pt_get_trace;
1332 	params.walk_insn = intel_pt_walk_next_insn;
1333 	params.lookahead = intel_pt_lookahead;
1334 	params.findnew_vmcs_info = intel_pt_findnew_vmcs_info;
1335 	params.data = ptq;
1336 	params.return_compression = intel_pt_return_compression(pt);
1337 	params.branch_enable = intel_pt_branch_enable(pt);
1338 	params.ctl = intel_pt_ctl(pt);
1339 	params.max_non_turbo_ratio = pt->max_non_turbo_ratio;
1340 	params.mtc_period = intel_pt_mtc_period(pt);
1341 	params.tsc_ctc_ratio_n = pt->tsc_ctc_ratio_n;
1342 	params.tsc_ctc_ratio_d = pt->tsc_ctc_ratio_d;
1343 	params.quick = pt->synth_opts.quick;
1344 	params.vm_time_correlation = pt->synth_opts.vm_time_correlation;
1345 	params.vm_tm_corr_dry_run = pt->synth_opts.vm_tm_corr_dry_run;
1346 	params.first_timestamp = pt->first_timestamp;
1347 	params.max_loops = pt->max_loops;
1348 
1349 	/* Cannot walk code without TNT, so force 'quick' mode */
1350 	if (params.branch_enable && intel_pt_disabled_tnt(pt) && !params.quick)
1351 		params.quick = 1;
1352 
1353 	if (pt->filts.cnt > 0)
1354 		params.pgd_ip = intel_pt_pgd_ip;
1355 
1356 	if (pt->synth_opts.instructions || pt->synth_opts.cycles) {
1357 		if (pt->synth_opts.period) {
1358 			switch (pt->synth_opts.period_type) {
1359 			case PERF_ITRACE_PERIOD_INSTRUCTIONS:
1360 				params.period_type =
1361 						INTEL_PT_PERIOD_INSTRUCTIONS;
1362 				params.period = pt->synth_opts.period;
1363 				break;
1364 			case PERF_ITRACE_PERIOD_TICKS:
1365 				params.period_type = INTEL_PT_PERIOD_TICKS;
1366 				params.period = pt->synth_opts.period;
1367 				break;
1368 			case PERF_ITRACE_PERIOD_NANOSECS:
1369 				params.period_type = INTEL_PT_PERIOD_TICKS;
1370 				params.period = intel_pt_ns_to_ticks(pt,
1371 							pt->synth_opts.period);
1372 				break;
1373 			default:
1374 				break;
1375 			}
1376 		}
1377 
1378 		if (!params.period) {
1379 			params.period_type = INTEL_PT_PERIOD_INSTRUCTIONS;
1380 			params.period = 1;
1381 		}
1382 	}
1383 
1384 	if (env->cpuid && !strncmp(env->cpuid, "GenuineIntel,6,92,", 18))
1385 		params.flags |= INTEL_PT_FUP_WITH_NLIP;
1386 
1387 	ptq->decoder = intel_pt_decoder_new(&params);
1388 	if (!ptq->decoder)
1389 		goto out_free;
1390 
1391 	return ptq;
1392 
1393 out_free:
1394 	zfree(&ptq->event_buf);
1395 	zfree(&ptq->last_branch);
1396 	zfree(&ptq->chain);
1397 	free(ptq);
1398 	return NULL;
1399 }
1400 
1401 static void intel_pt_free_queue(void *priv)
1402 {
1403 	struct intel_pt_queue *ptq = priv;
1404 
1405 	if (!ptq)
1406 		return;
1407 	thread__zput(ptq->thread);
1408 	thread__zput(ptq->guest_thread);
1409 	thread__zput(ptq->unknown_guest_thread);
1410 	intel_pt_decoder_free(ptq->decoder);
1411 	zfree(&ptq->event_buf);
1412 	zfree(&ptq->last_branch);
1413 	zfree(&ptq->chain);
1414 	free(ptq);
1415 }
1416 
1417 static void intel_pt_first_timestamp(struct intel_pt *pt, u64 timestamp)
1418 {
1419 	unsigned int i;
1420 
1421 	pt->first_timestamp = timestamp;
1422 
1423 	for (i = 0; i < pt->queues.nr_queues; i++) {
1424 		struct auxtrace_queue *queue = &pt->queues.queue_array[i];
1425 		struct intel_pt_queue *ptq = queue->priv;
1426 
1427 		if (ptq && ptq->decoder)
1428 			intel_pt_set_first_timestamp(ptq->decoder, timestamp);
1429 	}
1430 }
1431 
1432 static int intel_pt_get_guest_from_sideband(struct intel_pt_queue *ptq)
1433 {
1434 	struct machines *machines = &ptq->pt->session->machines;
1435 	struct machine *machine;
1436 	pid_t machine_pid = ptq->pid;
1437 	pid_t tid;
1438 	int vcpu;
1439 
1440 	if (machine_pid <= 0)
1441 		return 0; /* Not a guest machine */
1442 
1443 	machine = machines__find(machines, machine_pid);
1444 	if (!machine)
1445 		return 0; /* Not a guest machine */
1446 
1447 	if (ptq->guest_machine != machine) {
1448 		ptq->guest_machine = NULL;
1449 		thread__zput(ptq->guest_thread);
1450 		thread__zput(ptq->unknown_guest_thread);
1451 
1452 		ptq->unknown_guest_thread = machine__find_thread(machine, 0, 0);
1453 		if (!ptq->unknown_guest_thread)
1454 			return -1;
1455 		ptq->guest_machine = machine;
1456 	}
1457 
1458 	vcpu = ptq->thread ? thread__guest_cpu(ptq->thread) : -1;
1459 	if (vcpu < 0)
1460 		return -1;
1461 
1462 	tid = machine__get_current_tid(machine, vcpu);
1463 
1464 	if (ptq->guest_thread && thread__tid(ptq->guest_thread) != tid)
1465 		thread__zput(ptq->guest_thread);
1466 
1467 	if (!ptq->guest_thread) {
1468 		ptq->guest_thread = machine__find_thread(machine, -1, tid);
1469 		if (!ptq->guest_thread)
1470 			return -1;
1471 	}
1472 
1473 	ptq->guest_machine_pid = machine_pid;
1474 	ptq->guest_pid = thread__pid(ptq->guest_thread);
1475 	ptq->guest_tid = tid;
1476 	ptq->vcpu = vcpu;
1477 
1478 	return 0;
1479 }
1480 
1481 static void intel_pt_set_pid_tid_cpu(struct intel_pt *pt,
1482 				     struct auxtrace_queue *queue)
1483 {
1484 	struct intel_pt_queue *ptq = queue->priv;
1485 
1486 	if (queue->tid == -1 || pt->have_sched_switch) {
1487 		ptq->tid = machine__get_current_tid(pt->machine, ptq->cpu);
1488 		if (ptq->tid == -1)
1489 			ptq->pid = -1;
1490 		thread__zput(ptq->thread);
1491 	}
1492 
1493 	if (!ptq->thread && ptq->tid != -1)
1494 		ptq->thread = machine__find_thread(pt->machine, -1, ptq->tid);
1495 
1496 	if (ptq->thread) {
1497 		ptq->pid = thread__pid(ptq->thread);
1498 		if (queue->cpu == -1)
1499 			ptq->cpu = thread__cpu(ptq->thread);
1500 	}
1501 
1502 	if (pt->have_guest_sideband && intel_pt_get_guest_from_sideband(ptq)) {
1503 		ptq->guest_machine_pid = 0;
1504 		ptq->guest_pid = -1;
1505 		ptq->guest_tid = -1;
1506 		ptq->vcpu = -1;
1507 	}
1508 }
1509 
1510 static void intel_pt_sample_flags(struct intel_pt_queue *ptq)
1511 {
1512 	struct intel_pt *pt = ptq->pt;
1513 
1514 	ptq->insn_len = 0;
1515 	if (ptq->state->flags & INTEL_PT_ABORT_TX) {
1516 		ptq->flags = PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT;
1517 	} else if (ptq->state->flags & INTEL_PT_ASYNC) {
1518 		if (!ptq->state->to_ip)
1519 			ptq->flags = PERF_IP_FLAG_BRANCH |
1520 				     PERF_IP_FLAG_ASYNC |
1521 				     PERF_IP_FLAG_TRACE_END;
1522 		else if (ptq->state->from_nr && !ptq->state->to_nr)
1523 			ptq->flags = PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL |
1524 				     PERF_IP_FLAG_ASYNC |
1525 				     PERF_IP_FLAG_VMEXIT;
1526 		else
1527 			ptq->flags = PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL |
1528 				     PERF_IP_FLAG_ASYNC |
1529 				     PERF_IP_FLAG_INTERRUPT;
1530 	} else {
1531 		if (ptq->state->from_ip)
1532 			ptq->flags = intel_pt_insn_type(ptq->state->insn_op);
1533 		else
1534 			ptq->flags = PERF_IP_FLAG_BRANCH |
1535 				     PERF_IP_FLAG_TRACE_BEGIN;
1536 		if (ptq->state->flags & INTEL_PT_IN_TX)
1537 			ptq->flags |= PERF_IP_FLAG_IN_TX;
1538 		ptq->insn_len = ptq->state->insn_len;
1539 		memcpy(ptq->insn, ptq->state->insn, INTEL_PT_INSN_BUF_SZ);
1540 	}
1541 
1542 	if (ptq->state->type & INTEL_PT_TRACE_BEGIN)
1543 		ptq->flags |= PERF_IP_FLAG_TRACE_BEGIN;
1544 	if (ptq->state->type & INTEL_PT_TRACE_END)
1545 		ptq->flags |= PERF_IP_FLAG_TRACE_END;
1546 
1547 	if (pt->cap_event_trace) {
1548 		if (ptq->state->type & INTEL_PT_IFLAG_CHG) {
1549 			if (!ptq->state->from_iflag)
1550 				ptq->flags |= PERF_IP_FLAG_INTR_DISABLE;
1551 			if (ptq->state->from_iflag != ptq->state->to_iflag)
1552 				ptq->flags |= PERF_IP_FLAG_INTR_TOGGLE;
1553 		} else if (!ptq->state->to_iflag) {
1554 			ptq->flags |= PERF_IP_FLAG_INTR_DISABLE;
1555 		}
1556 	}
1557 }
1558 
1559 static void intel_pt_setup_time_range(struct intel_pt *pt,
1560 				      struct intel_pt_queue *ptq)
1561 {
1562 	if (!pt->range_cnt)
1563 		return;
1564 
1565 	ptq->sel_timestamp = pt->time_ranges[0].start;
1566 	ptq->sel_idx = 0;
1567 
1568 	if (ptq->sel_timestamp) {
1569 		ptq->sel_start = true;
1570 	} else {
1571 		ptq->sel_timestamp = pt->time_ranges[0].end;
1572 		ptq->sel_start = false;
1573 	}
1574 }
1575 
1576 static int intel_pt_setup_queue(struct intel_pt *pt,
1577 				struct auxtrace_queue *queue,
1578 				unsigned int queue_nr)
1579 {
1580 	struct intel_pt_queue *ptq = queue->priv;
1581 
1582 	if (list_empty(&queue->head))
1583 		return 0;
1584 
1585 	if (!ptq) {
1586 		ptq = intel_pt_alloc_queue(pt, queue_nr);
1587 		if (!ptq)
1588 			return -ENOMEM;
1589 		queue->priv = ptq;
1590 
1591 		if (queue->cpu != -1)
1592 			ptq->cpu = queue->cpu;
1593 		ptq->tid = queue->tid;
1594 
1595 		ptq->cbr_seen = UINT_MAX;
1596 
1597 		if (pt->sampling_mode && !pt->snapshot_mode &&
1598 		    pt->timeless_decoding)
1599 			ptq->step_through_buffers = true;
1600 
1601 		ptq->sync_switch = pt->sync_switch;
1602 
1603 		intel_pt_setup_time_range(pt, ptq);
1604 	}
1605 
1606 	if (!ptq->on_heap &&
1607 	    (!ptq->sync_switch ||
1608 	     ptq->switch_state != INTEL_PT_SS_EXPECTING_SWITCH_EVENT)) {
1609 		const struct intel_pt_state *state;
1610 		int ret;
1611 
1612 		if (pt->timeless_decoding)
1613 			return 0;
1614 
1615 		intel_pt_log("queue %u getting timestamp\n", queue_nr);
1616 		intel_pt_log("queue %u decoding cpu %d pid %d tid %d\n",
1617 			     queue_nr, ptq->cpu, ptq->pid, ptq->tid);
1618 
1619 		if (ptq->sel_start && ptq->sel_timestamp) {
1620 			ret = intel_pt_fast_forward(ptq->decoder,
1621 						    ptq->sel_timestamp);
1622 			if (ret)
1623 				return ret;
1624 		}
1625 
1626 		while (1) {
1627 			state = intel_pt_decode(ptq->decoder);
1628 			if (state->err) {
1629 				if (state->err == INTEL_PT_ERR_NODATA) {
1630 					intel_pt_log("queue %u has no timestamp\n",
1631 						     queue_nr);
1632 					return 0;
1633 				}
1634 				continue;
1635 			}
1636 			if (state->timestamp)
1637 				break;
1638 		}
1639 
1640 		ptq->timestamp = state->timestamp;
1641 		intel_pt_log("queue %u timestamp 0x%" PRIx64 "\n",
1642 			     queue_nr, ptq->timestamp);
1643 		ptq->state = state;
1644 		ptq->have_sample = true;
1645 		if (ptq->sel_start && ptq->sel_timestamp &&
1646 		    ptq->timestamp < ptq->sel_timestamp)
1647 			ptq->have_sample = false;
1648 		intel_pt_sample_flags(ptq);
1649 		ret = auxtrace_heap__add(&pt->heap, queue_nr, ptq->timestamp);
1650 		if (ret)
1651 			return ret;
1652 		ptq->on_heap = true;
1653 	}
1654 
1655 	return 0;
1656 }
1657 
1658 static int intel_pt_setup_queues(struct intel_pt *pt)
1659 {
1660 	unsigned int i;
1661 	int ret;
1662 
1663 	for (i = 0; i < pt->queues.nr_queues; i++) {
1664 		ret = intel_pt_setup_queue(pt, &pt->queues.queue_array[i], i);
1665 		if (ret)
1666 			return ret;
1667 	}
1668 	return 0;
1669 }
1670 
1671 static inline bool intel_pt_skip_event(struct intel_pt *pt)
1672 {
1673 	return pt->synth_opts.initial_skip &&
1674 	       pt->num_events++ < pt->synth_opts.initial_skip;
1675 }
1676 
1677 /*
1678  * Cannot count CBR as skipped because it won't go away until cbr == cbr_seen.
1679  * Also ensure CBR is first non-skipped event by allowing for 4 more samples
1680  * from this decoder state.
1681  */
1682 static inline bool intel_pt_skip_cbr_event(struct intel_pt *pt)
1683 {
1684 	return pt->synth_opts.initial_skip &&
1685 	       pt->num_events + 4 < pt->synth_opts.initial_skip;
1686 }
1687 
1688 static void intel_pt_prep_a_sample(struct intel_pt_queue *ptq,
1689 				   union perf_event *event,
1690 				   struct perf_sample *sample)
1691 {
1692 	event->sample.header.type = PERF_RECORD_SAMPLE;
1693 	event->sample.header.size = sizeof(struct perf_event_header);
1694 
1695 	sample->pid = ptq->pid;
1696 	sample->tid = ptq->tid;
1697 
1698 	if (ptq->pt->have_guest_sideband) {
1699 		if ((ptq->state->from_ip && ptq->state->from_nr) ||
1700 		    (ptq->state->to_ip && ptq->state->to_nr)) {
1701 			sample->pid = ptq->guest_pid;
1702 			sample->tid = ptq->guest_tid;
1703 			sample->machine_pid = ptq->guest_machine_pid;
1704 			sample->vcpu = ptq->vcpu;
1705 		}
1706 	}
1707 
1708 	sample->cpu = ptq->cpu;
1709 	sample->insn_len = ptq->insn_len;
1710 	memcpy(sample->insn, ptq->insn, INTEL_PT_INSN_BUF_SZ);
1711 }
1712 
1713 static void intel_pt_prep_b_sample(struct intel_pt *pt,
1714 				   struct intel_pt_queue *ptq,
1715 				   union perf_event *event,
1716 				   struct perf_sample *sample)
1717 {
1718 	intel_pt_prep_a_sample(ptq, event, sample);
1719 
1720 	if (!pt->timeless_decoding)
1721 		sample->time = tsc_to_perf_time(ptq->timestamp, &pt->tc);
1722 
1723 	sample->ip = ptq->state->from_ip;
1724 	sample->addr = ptq->state->to_ip;
1725 	sample->cpumode = intel_pt_cpumode(ptq, sample->ip, sample->addr);
1726 	sample->period = 1;
1727 	sample->flags = ptq->flags;
1728 
1729 	event->sample.header.misc = sample->cpumode;
1730 }
1731 
1732 static int intel_pt_inject_event(struct intel_pt *pt, union perf_event *event,
1733 				 struct perf_sample *sample, u64 type)
1734 {
1735 	struct evsel *evsel = sample->evsel;
1736 	u64 branch_sample_type = 0;
1737 	size_t sz;
1738 
1739 	if (!evsel && pt->session && pt->session->evlist)
1740 		evsel = evlist__id2evsel(pt->session->evlist, sample->id);
1741 
1742 	if (evsel)
1743 		branch_sample_type = evsel->core.attr.branch_sample_type;
1744 
1745 	event->header.type = PERF_RECORD_SAMPLE;
1746 	sz = perf_event__sample_event_size(sample, type, /*read_format=*/0,
1747 					   branch_sample_type);
1748 	if (sz >= PERF_SAMPLE_MAX_SIZE) {
1749 		pr_err("Sample size %zu exceeds max size %d\n", sz, PERF_SAMPLE_MAX_SIZE);
1750 		return -EFAULT;
1751 	}
1752 	event->header.size = sz;
1753 
1754 	return perf_event__synthesize_sample(event, type, /*read_format=*/0,
1755 					     branch_sample_type, sample);
1756 }
1757 
1758 static inline int intel_pt_opt_inject(struct intel_pt *pt,
1759 				      union perf_event *event,
1760 				      struct perf_sample *sample, u64 type)
1761 {
1762 	if (!pt->synth_opts.inject)
1763 		return 0;
1764 
1765 	return intel_pt_inject_event(pt, event, sample, type);
1766 }
1767 
1768 static int intel_pt_deliver_synth_event(struct intel_pt *pt,
1769 					union perf_event *event,
1770 					struct perf_sample *sample, u64 type)
1771 {
1772 	int ret;
1773 
1774 	ret = intel_pt_opt_inject(pt, event, sample, type);
1775 	if (ret)
1776 		return ret;
1777 
1778 	ret = perf_session__deliver_synth_event(pt->session, event, sample);
1779 	if (ret)
1780 		pr_err("Intel PT: failed to deliver event, error %d\n", ret);
1781 
1782 	return ret;
1783 }
1784 
1785 static int intel_pt_synth_branch_sample(struct intel_pt_queue *ptq)
1786 {
1787 	struct intel_pt *pt = ptq->pt;
1788 	union perf_event *event = ptq->event_buf;
1789 	struct perf_sample sample;
1790 	struct dummy_branch_stack {
1791 		u64			nr;
1792 		u64			hw_idx;
1793 		struct branch_entry	entries;
1794 	} dummy_bs;
1795 	int ret;
1796 
1797 	if (pt->branches_filter && !(pt->branches_filter & ptq->flags))
1798 		return 0;
1799 
1800 	if (intel_pt_skip_event(pt))
1801 		return 0;
1802 
1803 	perf_sample__init(&sample, /*all=*/true);
1804 	intel_pt_prep_b_sample(pt, ptq, event, &sample);
1805 
1806 	sample.id = ptq->pt->branches_id;
1807 	sample.stream_id = ptq->pt->branches_id;
1808 
1809 	/*
1810 	 * perf report cannot handle events without a branch stack when using
1811 	 * SORT_MODE__BRANCH so make a dummy one.
1812 	 */
1813 	if (pt->synth_opts.last_branch && sort__mode == SORT_MODE__BRANCH) {
1814 		dummy_bs = (struct dummy_branch_stack){
1815 			.nr = 1,
1816 			.hw_idx = -1ULL,
1817 			.entries = {
1818 				.from = sample.ip,
1819 				.to = sample.addr,
1820 			},
1821 		};
1822 		sample.branch_stack = (struct branch_stack *)&dummy_bs;
1823 	}
1824 
1825 	if (ptq->sample_ipc)
1826 		sample.cyc_cnt = ptq->ipc_cyc_cnt - ptq->last_br_cyc_cnt;
1827 	if (sample.cyc_cnt) {
1828 		sample.insn_cnt = ptq->ipc_insn_cnt - ptq->last_br_insn_cnt;
1829 		ptq->last_br_insn_cnt = ptq->ipc_insn_cnt;
1830 		ptq->last_br_cyc_cnt = ptq->ipc_cyc_cnt;
1831 	}
1832 
1833 	perf_sample__exit(&sample);
1834 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
1835 					    pt->branches_sample_type);
1836 	return ret;
1837 }
1838 
1839 static void intel_pt_prep_sample(struct intel_pt *pt,
1840 				 struct intel_pt_queue *ptq,
1841 				 union perf_event *event,
1842 				 struct perf_sample *sample)
1843 {
1844 	intel_pt_prep_b_sample(pt, ptq, event, sample);
1845 
1846 	if (pt->synth_opts.callchain) {
1847 		thread_stack__sample(ptq->thread, ptq->cpu, ptq->chain,
1848 				     pt->synth_opts.callchain_sz + 1,
1849 				     sample->ip, pt->kernel_start);
1850 		sample->callchain = ptq->chain;
1851 	}
1852 
1853 	if (pt->synth_opts.last_branch) {
1854 		thread_stack__br_sample(ptq->thread, ptq->cpu, ptq->last_branch,
1855 					pt->br_stack_sz);
1856 		sample->branch_stack = ptq->last_branch;
1857 	}
1858 }
1859 
1860 static int intel_pt_synth_instruction_sample(struct intel_pt_queue *ptq)
1861 {
1862 	struct intel_pt *pt = ptq->pt;
1863 	union perf_event *event = ptq->event_buf;
1864 	struct perf_sample sample;
1865 	int ret;
1866 
1867 	if (intel_pt_skip_event(pt))
1868 		return 0;
1869 
1870 	perf_sample__init(&sample, /*all=*/true);
1871 	intel_pt_prep_sample(pt, ptq, event, &sample);
1872 
1873 	sample.id = ptq->pt->instructions_id;
1874 	sample.stream_id = ptq->pt->instructions_id;
1875 	if (pt->synth_opts.quick)
1876 		sample.period = 1;
1877 	else
1878 		sample.period = ptq->state->tot_insn_cnt - ptq->last_insn_cnt;
1879 
1880 	if (ptq->sample_ipc)
1881 		sample.cyc_cnt = ptq->ipc_cyc_cnt - ptq->last_in_cyc_cnt;
1882 	if (sample.cyc_cnt) {
1883 		sample.insn_cnt = ptq->ipc_insn_cnt - ptq->last_in_insn_cnt;
1884 		ptq->last_in_insn_cnt = ptq->ipc_insn_cnt;
1885 		ptq->last_in_cyc_cnt = ptq->ipc_cyc_cnt;
1886 	}
1887 
1888 	ptq->last_insn_cnt = ptq->state->tot_insn_cnt;
1889 
1890 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
1891 					   pt->instructions_sample_type);
1892 	perf_sample__exit(&sample);
1893 	return ret;
1894 }
1895 
1896 static int intel_pt_synth_cycle_sample(struct intel_pt_queue *ptq)
1897 {
1898 	struct intel_pt *pt = ptq->pt;
1899 	union perf_event *event = ptq->event_buf;
1900 	struct perf_sample sample;
1901 	u64 period = 0;
1902 	int ret;
1903 
1904 	if (ptq->sample_ipc)
1905 		period = ptq->ipc_cyc_cnt - ptq->last_cy_cyc_cnt;
1906 
1907 	if (!period || intel_pt_skip_event(pt))
1908 		return 0;
1909 
1910 	perf_sample__init(&sample, /*all=*/true);
1911 	intel_pt_prep_sample(pt, ptq, event, &sample);
1912 
1913 	sample.id = ptq->pt->cycles_id;
1914 	sample.stream_id = ptq->pt->cycles_id;
1915 	sample.period = period;
1916 
1917 	sample.cyc_cnt = period;
1918 	sample.insn_cnt = ptq->ipc_insn_cnt - ptq->last_cy_insn_cnt;
1919 	ptq->last_cy_insn_cnt = ptq->ipc_insn_cnt;
1920 	ptq->last_cy_cyc_cnt = ptq->ipc_cyc_cnt;
1921 
1922 	ret = intel_pt_deliver_synth_event(pt, event, &sample, pt->cycles_sample_type);
1923 	perf_sample__exit(&sample);
1924 	return ret;
1925 }
1926 
1927 static int intel_pt_synth_transaction_sample(struct intel_pt_queue *ptq)
1928 {
1929 	struct intel_pt *pt = ptq->pt;
1930 	union perf_event *event = ptq->event_buf;
1931 	struct perf_sample sample;
1932 	int ret;
1933 
1934 	if (intel_pt_skip_event(pt))
1935 		return 0;
1936 
1937 	perf_sample__init(&sample, /*all=*/true);
1938 	intel_pt_prep_sample(pt, ptq, event, &sample);
1939 
1940 	sample.id = ptq->pt->transactions_id;
1941 	sample.stream_id = ptq->pt->transactions_id;
1942 
1943 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
1944 					   pt->transactions_sample_type);
1945 	perf_sample__exit(&sample);
1946 	return ret;
1947 }
1948 
1949 static void intel_pt_prep_p_sample(struct intel_pt *pt,
1950 				   struct intel_pt_queue *ptq,
1951 				   union perf_event *event,
1952 				   struct perf_sample *sample)
1953 {
1954 	intel_pt_prep_sample(pt, ptq, event, sample);
1955 
1956 	/*
1957 	 * Zero IP is used to mean "trace start" but that is not the case for
1958 	 * power or PTWRITE events with no IP, so clear the flags.
1959 	 */
1960 	if (!sample->ip)
1961 		sample->flags = 0;
1962 }
1963 
1964 static int intel_pt_synth_ptwrite_sample(struct intel_pt_queue *ptq)
1965 {
1966 	struct intel_pt *pt = ptq->pt;
1967 	union perf_event *event = ptq->event_buf;
1968 	struct perf_sample sample = { .ip = 0, };
1969 	struct perf_synth_intel_ptwrite raw;
1970 
1971 	if (intel_pt_skip_event(pt))
1972 		return 0;
1973 
1974 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1975 
1976 	sample.id = ptq->pt->ptwrites_id;
1977 	sample.stream_id = ptq->pt->ptwrites_id;
1978 
1979 	raw.flags = 0;
1980 	raw.ip = !!(ptq->state->flags & INTEL_PT_FUP_IP);
1981 	raw.payload = cpu_to_le64(ptq->state->ptw_payload);
1982 
1983 	sample.raw_size = perf_synth__raw_size(raw);
1984 	sample.raw_data = perf_synth__raw_data(&raw);
1985 
1986 	return intel_pt_deliver_synth_event(pt, event, &sample,
1987 					    pt->ptwrites_sample_type);
1988 }
1989 
1990 static int intel_pt_synth_cbr_sample(struct intel_pt_queue *ptq)
1991 {
1992 	struct intel_pt *pt = ptq->pt;
1993 	union perf_event *event = ptq->event_buf;
1994 	struct perf_sample sample;
1995 	struct perf_synth_intel_cbr raw;
1996 	u32 flags;
1997 	int ret;
1998 
1999 	if (intel_pt_skip_cbr_event(pt))
2000 		return 0;
2001 
2002 	ptq->cbr_seen = ptq->state->cbr;
2003 
2004 	perf_sample__init(&sample, /*all=*/true);
2005 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
2006 
2007 	sample.id = ptq->pt->cbr_id;
2008 	sample.stream_id = ptq->pt->cbr_id;
2009 
2010 	flags = (u16)ptq->state->cbr_payload | (pt->max_non_turbo_ratio << 16);
2011 	raw.flags = cpu_to_le32(flags);
2012 	raw.freq = cpu_to_le32(raw.cbr * pt->cbr2khz);
2013 	raw.reserved3 = 0;
2014 
2015 	sample.raw_size = perf_synth__raw_size(raw);
2016 	sample.raw_data = perf_synth__raw_data(&raw);
2017 
2018 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
2019 					   pt->pwr_events_sample_type);
2020 	perf_sample__exit(&sample);
2021 	return ret;
2022 }
2023 
2024 static int intel_pt_synth_psb_sample(struct intel_pt_queue *ptq)
2025 {
2026 	struct intel_pt *pt = ptq->pt;
2027 	union perf_event *event = ptq->event_buf;
2028 	struct perf_sample sample;
2029 	struct perf_synth_intel_psb raw;
2030 	int ret;
2031 
2032 	if (intel_pt_skip_event(pt))
2033 		return 0;
2034 
2035 	perf_sample__init(&sample, /*all=*/true);
2036 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
2037 
2038 	sample.id = ptq->pt->psb_id;
2039 	sample.stream_id = ptq->pt->psb_id;
2040 	sample.flags = 0;
2041 
2042 	raw.reserved = 0;
2043 	raw.offset = ptq->state->psb_offset;
2044 
2045 	sample.raw_size = perf_synth__raw_size(raw);
2046 	sample.raw_data = perf_synth__raw_data(&raw);
2047 
2048 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
2049 					   pt->pwr_events_sample_type);
2050 	perf_sample__exit(&sample);
2051 	return ret;
2052 }
2053 
2054 static int intel_pt_synth_mwait_sample(struct intel_pt_queue *ptq)
2055 {
2056 	struct intel_pt *pt = ptq->pt;
2057 	union perf_event *event = ptq->event_buf;
2058 	struct perf_sample sample;
2059 	struct perf_synth_intel_mwait raw;
2060 	int ret;
2061 
2062 	if (intel_pt_skip_event(pt))
2063 		return 0;
2064 
2065 	perf_sample__init(&sample, /*all=*/true);
2066 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
2067 
2068 	sample.id = ptq->pt->mwait_id;
2069 	sample.stream_id = ptq->pt->mwait_id;
2070 
2071 	raw.reserved = 0;
2072 	raw.payload = cpu_to_le64(ptq->state->mwait_payload);
2073 
2074 	sample.raw_size = perf_synth__raw_size(raw);
2075 	sample.raw_data = perf_synth__raw_data(&raw);
2076 
2077 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
2078 					   pt->pwr_events_sample_type);
2079 	perf_sample__exit(&sample);
2080 	return ret;
2081 }
2082 
2083 static int intel_pt_synth_pwre_sample(struct intel_pt_queue *ptq)
2084 {
2085 	struct intel_pt *pt = ptq->pt;
2086 	union perf_event *event = ptq->event_buf;
2087 	struct perf_sample sample;
2088 	struct perf_synth_intel_pwre raw;
2089 	int ret;
2090 
2091 	if (intel_pt_skip_event(pt))
2092 		return 0;
2093 
2094 	perf_sample__init(&sample, /*all=*/true);
2095 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
2096 
2097 	sample.id = ptq->pt->pwre_id;
2098 	sample.stream_id = ptq->pt->pwre_id;
2099 
2100 	raw.reserved = 0;
2101 	raw.payload = cpu_to_le64(ptq->state->pwre_payload);
2102 
2103 	sample.raw_size = perf_synth__raw_size(raw);
2104 	sample.raw_data = perf_synth__raw_data(&raw);
2105 
2106 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
2107 					   pt->pwr_events_sample_type);
2108 	perf_sample__exit(&sample);
2109 	return ret;
2110 }
2111 
2112 static int intel_pt_synth_exstop_sample(struct intel_pt_queue *ptq)
2113 {
2114 	struct intel_pt *pt = ptq->pt;
2115 	union perf_event *event = ptq->event_buf;
2116 	struct perf_sample sample;
2117 	struct perf_synth_intel_exstop raw;
2118 	int ret;
2119 
2120 	if (intel_pt_skip_event(pt))
2121 		return 0;
2122 
2123 	perf_sample__init(&sample, /*all=*/true);
2124 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
2125 
2126 	sample.id = ptq->pt->exstop_id;
2127 	sample.stream_id = ptq->pt->exstop_id;
2128 
2129 	raw.flags = 0;
2130 	raw.ip = !!(ptq->state->flags & INTEL_PT_FUP_IP);
2131 
2132 	sample.raw_size = perf_synth__raw_size(raw);
2133 	sample.raw_data = perf_synth__raw_data(&raw);
2134 
2135 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
2136 					   pt->pwr_events_sample_type);
2137 	perf_sample__exit(&sample);
2138 	return ret;
2139 }
2140 
2141 static int intel_pt_synth_pwrx_sample(struct intel_pt_queue *ptq)
2142 {
2143 	struct intel_pt *pt = ptq->pt;
2144 	union perf_event *event = ptq->event_buf;
2145 	struct perf_sample sample;
2146 	struct perf_synth_intel_pwrx raw;
2147 	int ret;
2148 
2149 	if (intel_pt_skip_event(pt))
2150 		return 0;
2151 
2152 	perf_sample__init(&sample, /*all=*/true);
2153 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
2154 
2155 	sample.id = ptq->pt->pwrx_id;
2156 	sample.stream_id = ptq->pt->pwrx_id;
2157 
2158 	raw.reserved = 0;
2159 	raw.payload = cpu_to_le64(ptq->state->pwrx_payload);
2160 
2161 	sample.raw_size = perf_synth__raw_size(raw);
2162 	sample.raw_data = perf_synth__raw_data(&raw);
2163 
2164 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
2165 					   pt->pwr_events_sample_type);
2166 	perf_sample__exit(&sample);
2167 	return ret;
2168 }
2169 
2170 /*
2171  * PEBS gp_regs array indexes plus 1 so that 0 means not present. Refer
2172  * intel_pt_add_gp_regs().
2173  */
2174 static const int pebs_gp_regs[] = {
2175 	[PERF_REG_X86_FLAGS]	= 1,
2176 	[PERF_REG_X86_IP]	= 2,
2177 	[PERF_REG_X86_AX]	= 3,
2178 	[PERF_REG_X86_CX]	= 4,
2179 	[PERF_REG_X86_DX]	= 5,
2180 	[PERF_REG_X86_BX]	= 6,
2181 	[PERF_REG_X86_SP]	= 7,
2182 	[PERF_REG_X86_BP]	= 8,
2183 	[PERF_REG_X86_SI]	= 9,
2184 	[PERF_REG_X86_DI]	= 10,
2185 	[PERF_REG_X86_R8]	= 11,
2186 	[PERF_REG_X86_R9]	= 12,
2187 	[PERF_REG_X86_R10]	= 13,
2188 	[PERF_REG_X86_R11]	= 14,
2189 	[PERF_REG_X86_R12]	= 15,
2190 	[PERF_REG_X86_R13]	= 16,
2191 	[PERF_REG_X86_R14]	= 17,
2192 	[PERF_REG_X86_R15]	= 18,
2193 };
2194 
2195 static u64 *intel_pt_add_gp_regs(struct regs_dump *intr_regs, u64 *pos,
2196 				 const struct intel_pt_blk_items *items,
2197 				 u64 regs_mask)
2198 {
2199 	const u64 *gp_regs = items->val[INTEL_PT_GP_REGS_POS];
2200 	u32 mask = items->mask[INTEL_PT_GP_REGS_POS];
2201 	u32 bit;
2202 	int i;
2203 
2204 	for (i = 0, bit = 1; i < PERF_REG_X86_64_MAX; i++, bit <<= 1) {
2205 		/* Get the PEBS gp_regs array index */
2206 		int n = pebs_gp_regs[i] - 1;
2207 
2208 		if (n < 0)
2209 			continue;
2210 		/*
2211 		 * Add only registers that were requested (i.e. 'regs_mask') and
2212 		 * that were provided (i.e. 'mask'), and update the resulting
2213 		 * mask (i.e. 'intr_regs->mask') accordingly.
2214 		 */
2215 		if (mask & 1 << n && regs_mask & bit) {
2216 			intr_regs->mask |= bit;
2217 			*pos++ = gp_regs[n];
2218 		}
2219 	}
2220 
2221 	return pos;
2222 }
2223 
2224 #ifndef PERF_REG_X86_XMM0
2225 #define PERF_REG_X86_XMM0 32
2226 #endif
2227 
2228 static void intel_pt_add_xmm(struct regs_dump *intr_regs, u64 *pos,
2229 			     const struct intel_pt_blk_items *items,
2230 			     u64 regs_mask)
2231 {
2232 	u32 mask = items->has_xmm & (regs_mask >> PERF_REG_X86_XMM0);
2233 	const u64 *xmm = items->xmm;
2234 
2235 	/*
2236 	 * If there are any XMM registers, then there should be all of them.
2237 	 * Nevertheless, follow the logic to add only registers that were
2238 	 * requested (i.e. 'regs_mask') and that were provided (i.e. 'mask'),
2239 	 * and update the resulting mask (i.e. 'intr_regs->mask') accordingly.
2240 	 */
2241 	intr_regs->mask |= (u64)mask << PERF_REG_X86_XMM0;
2242 
2243 	for (; mask; mask >>= 1, xmm++) {
2244 		if (mask & 1)
2245 			*pos++ = *xmm;
2246 	}
2247 }
2248 
2249 #define LBR_INFO_MISPRED	(1ULL << 63)
2250 #define LBR_INFO_IN_TX		(1ULL << 62)
2251 #define LBR_INFO_ABORT		(1ULL << 61)
2252 #define LBR_INFO_CYCLES		0xffff
2253 
2254 /* Refer kernel's intel_pmu_store_pebs_lbrs() */
2255 static u64 intel_pt_lbr_flags(u64 info)
2256 {
2257 	union {
2258 		struct branch_flags flags;
2259 		u64 result;
2260 	} u;
2261 
2262 	u.result	  = 0;
2263 	u.flags.mispred	  = !!(info & LBR_INFO_MISPRED);
2264 	u.flags.predicted = !(info & LBR_INFO_MISPRED);
2265 	u.flags.in_tx	  = !!(info & LBR_INFO_IN_TX);
2266 	u.flags.abort	  = !!(info & LBR_INFO_ABORT);
2267 	u.flags.cycles	  = info & LBR_INFO_CYCLES;
2268 
2269 	return u.result;
2270 }
2271 
2272 static void intel_pt_add_lbrs(struct branch_stack *br_stack,
2273 			      const struct intel_pt_blk_items *items)
2274 {
2275 	u64 *to;
2276 	int i;
2277 
2278 	br_stack->nr = 0;
2279 
2280 	to = &br_stack->entries[0].from;
2281 
2282 	for (i = INTEL_PT_LBR_0_POS; i <= INTEL_PT_LBR_2_POS; i++) {
2283 		u32 mask = items->mask[i];
2284 		const u64 *from = items->val[i];
2285 
2286 		for (; mask; mask >>= 3, from += 3) {
2287 			if ((mask & 7) == 7) {
2288 				*to++ = from[0];
2289 				*to++ = from[1];
2290 				*to++ = intel_pt_lbr_flags(from[2]);
2291 				br_stack->nr += 1;
2292 			}
2293 		}
2294 	}
2295 }
2296 
2297 #define P(a, b) PERF_MEM_S(a, b)
2298 #define OP_LH (P(OP, LOAD) | P(LVL, HIT))
2299 #define LEVEL(x) P(LVLNUM, x)
2300 #define REM P(REMOTE, REMOTE)
2301 #define SNOOP_NONE_MISS (P(SNOOP, NONE) | P(SNOOP, MISS))
2302 
2303 #define PERF_PEBS_DATA_SOURCE_GRT_MAX	0x10
2304 #define PERF_PEBS_DATA_SOURCE_GRT_MASK	(PERF_PEBS_DATA_SOURCE_GRT_MAX - 1)
2305 
2306 /* Based on kernel __intel_pmu_pebs_data_source_grt() and pebs_data_source */
2307 static const u64 pebs_data_source_grt[PERF_PEBS_DATA_SOURCE_GRT_MAX] = {
2308 	P(OP, LOAD) | P(LVL, MISS) | LEVEL(L3) | P(SNOOP, NA),         /* L3 miss|SNP N/A */
2309 	OP_LH | P(LVL, L1)  | LEVEL(L1)  | P(SNOOP, NONE),             /* L1 hit|SNP None */
2310 	OP_LH | P(LVL, LFB) | LEVEL(LFB) | P(SNOOP, NONE),             /* LFB/MAB hit|SNP None */
2311 	OP_LH | P(LVL, L2)  | LEVEL(L2)  | P(SNOOP, NONE),             /* L2 hit|SNP None */
2312 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOP, NONE),             /* L3 hit|SNP None */
2313 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOP, HIT),              /* L3 hit|SNP Hit */
2314 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOP, HITM),             /* L3 hit|SNP HitM */
2315 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOP, HITM),             /* L3 hit|SNP HitM */
2316 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOPX, FWD),             /* L3 hit|SNP Fwd */
2317 	OP_LH | P(LVL, REM_CCE1) | REM | LEVEL(L3) | P(SNOOP, HITM),   /* Remote L3 hit|SNP HitM */
2318 	OP_LH | P(LVL, LOC_RAM)  | LEVEL(RAM) | P(SNOOP, HIT),         /* RAM hit|SNP Hit */
2319 	OP_LH | P(LVL, REM_RAM1) | REM | LEVEL(L3) | P(SNOOP, HIT),    /* Remote L3 hit|SNP Hit */
2320 	OP_LH | P(LVL, LOC_RAM)  | LEVEL(RAM) | SNOOP_NONE_MISS,       /* RAM hit|SNP None or Miss */
2321 	OP_LH | P(LVL, REM_RAM1) | LEVEL(RAM) | REM | SNOOP_NONE_MISS, /* Remote RAM hit|SNP None or Miss */
2322 	OP_LH | P(LVL, IO)  | LEVEL(NA) | P(SNOOP, NONE),              /* I/O hit|SNP None */
2323 	OP_LH | P(LVL, UNC) | LEVEL(NA) | P(SNOOP, NONE),              /* Uncached hit|SNP None */
2324 };
2325 
2326 /* Based on kernel __intel_pmu_pebs_data_source_cmt() and pebs_data_source */
2327 static const u64 pebs_data_source_cmt[PERF_PEBS_DATA_SOURCE_GRT_MAX] = {
2328 	P(OP, LOAD) | P(LVL, MISS) | LEVEL(L3) | P(SNOOP, NA),       /* L3 miss|SNP N/A */
2329 	OP_LH | P(LVL, L1)  | LEVEL(L1)  | P(SNOOP, NONE),           /* L1 hit|SNP None */
2330 	OP_LH | P(LVL, LFB) | LEVEL(LFB) | P(SNOOP, NONE),           /* LFB/MAB hit|SNP None */
2331 	OP_LH | P(LVL, L2)  | LEVEL(L2)  | P(SNOOP, NONE),           /* L2 hit|SNP None */
2332 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOP, NONE),           /* L3 hit|SNP None */
2333 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOP, MISS),           /* L3 hit|SNP Hit */
2334 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOP, HIT),            /* L3 hit|SNP HitM */
2335 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOPX, FWD),           /* L3 hit|SNP HitM */
2336 	OP_LH | P(LVL, L3)  | LEVEL(L3)  | P(SNOOP, HITM),           /* L3 hit|SNP Fwd */
2337 	OP_LH | P(LVL, REM_CCE1) | REM | LEVEL(L3) | P(SNOOP, HITM), /* Remote L3 hit|SNP HitM */
2338 	OP_LH | P(LVL, LOC_RAM)  | LEVEL(RAM) | P(SNOOP, NONE),      /* RAM hit|SNP Hit */
2339 	OP_LH | LEVEL(RAM) | REM | P(SNOOP, NONE),                   /* Remote L3 hit|SNP Hit */
2340 	OP_LH | LEVEL(RAM) | REM | P(SNOOPX, FWD),                   /* RAM hit|SNP None or Miss */
2341 	OP_LH | LEVEL(RAM) | REM | P(SNOOP, HITM),                   /* Remote RAM hit|SNP None or Miss */
2342 	OP_LH | P(LVL, IO)  | LEVEL(NA) | P(SNOOP, NONE),            /* I/O hit|SNP None */
2343 	OP_LH | P(LVL, UNC) | LEVEL(NA) | P(SNOOP, NONE),            /* Uncached hit|SNP None */
2344 };
2345 
2346 /* Based on kernel pebs_set_tlb_lock() */
2347 static inline void pebs_set_tlb_lock(u64 *val, bool tlb, bool lock)
2348 {
2349 	/*
2350 	 * TLB access
2351 	 * 0 = did not miss 2nd level TLB
2352 	 * 1 = missed 2nd level TLB
2353 	 */
2354 	if (tlb)
2355 		*val |= P(TLB, MISS) | P(TLB, L2);
2356 	else
2357 		*val |= P(TLB, HIT) | P(TLB, L1) | P(TLB, L2);
2358 
2359 	/* locked prefix */
2360 	if (lock)
2361 		*val |= P(LOCK, LOCKED);
2362 }
2363 
2364 /* Based on kernel __grt_latency_data() */
2365 static u64 intel_pt_grt_latency_data(u8 dse, bool tlb, bool lock, bool blk,
2366 				     const u64 *pebs_data_source)
2367 {
2368 	u64 val;
2369 
2370 	dse &= PERF_PEBS_DATA_SOURCE_GRT_MASK;
2371 	val = pebs_data_source[dse];
2372 
2373 	pebs_set_tlb_lock(&val, tlb, lock);
2374 
2375 	if (blk)
2376 		val |= P(BLK, DATA);
2377 	else
2378 		val |= P(BLK, NA);
2379 
2380 	return val;
2381 }
2382 
2383 /* Default value for data source */
2384 #define PERF_MEM_NA (PERF_MEM_S(OP, NA)    |\
2385 		     PERF_MEM_S(LVL, NA)   |\
2386 		     PERF_MEM_S(SNOOP, NA) |\
2387 		     PERF_MEM_S(LOCK, NA)  |\
2388 		     PERF_MEM_S(TLB, NA)   |\
2389 		     PERF_MEM_S(LVLNUM, NA))
2390 
2391 enum DATA_SRC_FORMAT {
2392 	DATA_SRC_FORMAT_ERR  = -1,
2393 	DATA_SRC_FORMAT_NA   =  0,
2394 	DATA_SRC_FORMAT_GRT  =  1,
2395 	DATA_SRC_FORMAT_CMT  =  2,
2396 };
2397 
2398 /* Based on kernel grt_latency_data() and cmt_latency_data */
2399 static u64 intel_pt_get_data_src(u64 mem_aux_info, int data_src_fmt)
2400 {
2401 	switch (data_src_fmt) {
2402 	case DATA_SRC_FORMAT_GRT: {
2403 		union {
2404 			u64 val;
2405 			struct {
2406 				unsigned int dse:4;
2407 				unsigned int locked:1;
2408 				unsigned int stlb_miss:1;
2409 				unsigned int fwd_blk:1;
2410 				unsigned int reserved:25;
2411 			};
2412 		} x = {.val = mem_aux_info};
2413 		return intel_pt_grt_latency_data(x.dse, x.stlb_miss, x.locked, x.fwd_blk,
2414 						 pebs_data_source_grt);
2415 	}
2416 	case DATA_SRC_FORMAT_CMT: {
2417 		union {
2418 			u64 val;
2419 			struct {
2420 				unsigned int dse:5;
2421 				unsigned int locked:1;
2422 				unsigned int stlb_miss:1;
2423 				unsigned int fwd_blk:1;
2424 				unsigned int reserved:24;
2425 			};
2426 		} x = {.val = mem_aux_info};
2427 		return intel_pt_grt_latency_data(x.dse, x.stlb_miss, x.locked, x.fwd_blk,
2428 						 pebs_data_source_cmt);
2429 	}
2430 	default:
2431 		return PERF_MEM_NA;
2432 	}
2433 }
2434 
2435 static int intel_pt_do_synth_pebs_sample(struct intel_pt_queue *ptq, struct evsel *evsel,
2436 					 u64 id, int data_src_fmt)
2437 {
2438 	const struct intel_pt_blk_items *items = &ptq->state->items;
2439 	struct perf_sample sample;
2440 	union perf_event *event = ptq->event_buf;
2441 	struct intel_pt *pt = ptq->pt;
2442 	u64 sample_type = evsel->core.attr.sample_type;
2443 	u8 cpumode;
2444 	u64 regs[8 * sizeof(sample.intr_regs->mask)];
2445 	int ret;
2446 
2447 	if (intel_pt_skip_event(pt))
2448 		return 0;
2449 
2450 	perf_sample__init(&sample, /*all=*/true);
2451 	intel_pt_prep_a_sample(ptq, event, &sample);
2452 
2453 	sample.id = id;
2454 	sample.stream_id = id;
2455 
2456 	if (!evsel->core.attr.freq)
2457 		sample.period = evsel->core.attr.sample_period;
2458 
2459 	/* No support for non-zero CS base */
2460 	if (items->has_ip)
2461 		sample.ip = items->ip;
2462 	else if (items->has_rip)
2463 		sample.ip = items->rip;
2464 	else
2465 		sample.ip = ptq->state->from_ip;
2466 
2467 	cpumode = intel_pt_cpumode(ptq, sample.ip, 0);
2468 
2469 	event->sample.header.misc = cpumode | PERF_RECORD_MISC_EXACT_IP;
2470 
2471 	sample.cpumode = cpumode;
2472 
2473 	if (sample_type & PERF_SAMPLE_TIME) {
2474 		u64 timestamp = 0;
2475 
2476 		if (items->has_timestamp)
2477 			timestamp = items->timestamp;
2478 		else if (!pt->timeless_decoding)
2479 			timestamp = ptq->timestamp;
2480 		if (timestamp)
2481 			sample.time = tsc_to_perf_time(timestamp, &pt->tc);
2482 	}
2483 
2484 	if (sample_type & PERF_SAMPLE_CALLCHAIN &&
2485 	    pt->synth_opts.callchain) {
2486 		thread_stack__sample(ptq->thread, ptq->cpu, ptq->chain,
2487 				     pt->synth_opts.callchain_sz, sample.ip,
2488 				     pt->kernel_start);
2489 		sample.callchain = ptq->chain;
2490 	}
2491 
2492 	if (sample_type & PERF_SAMPLE_REGS_INTR &&
2493 	    (items->mask[INTEL_PT_GP_REGS_POS] ||
2494 	     items->mask[INTEL_PT_XMM_POS])) {
2495 		u64 regs_mask = evsel->core.attr.sample_regs_intr;
2496 		u64 *pos;
2497 		struct regs_dump *intr_regs = perf_sample__intr_regs(&sample);
2498 
2499 		intr_regs->abi = items->is_32_bit ?
2500 				       PERF_SAMPLE_REGS_ABI_32 :
2501 				       PERF_SAMPLE_REGS_ABI_64;
2502 		intr_regs->regs = regs;
2503 
2504 		pos = intel_pt_add_gp_regs(intr_regs, regs, items, regs_mask);
2505 
2506 		intel_pt_add_xmm(intr_regs, pos, items, regs_mask);
2507 	}
2508 
2509 	if ((sample_type | evsel->synth_sample_type) & PERF_SAMPLE_BRANCH_STACK) {
2510 		if (items->mask[INTEL_PT_LBR_0_POS] ||
2511 		    items->mask[INTEL_PT_LBR_1_POS] ||
2512 		    items->mask[INTEL_PT_LBR_2_POS]) {
2513 			intel_pt_add_lbrs(ptq->last_branch, items);
2514 		} else if (pt->synth_opts.last_branch) {
2515 			thread_stack__br_sample(ptq->thread, ptq->cpu,
2516 						ptq->last_branch,
2517 						pt->br_stack_sz);
2518 		} else {
2519 			ptq->last_branch->nr = 0;
2520 		}
2521 		sample.branch_stack = ptq->last_branch;
2522 	}
2523 
2524 	if (sample_type & PERF_SAMPLE_ADDR && items->has_mem_access_address)
2525 		sample.addr = items->mem_access_address;
2526 
2527 	if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
2528 		/*
2529 		 * Refer kernel's setup_pebs_adaptive_sample_data() and
2530 		 * intel_hsw_weight().
2531 		 */
2532 		if (items->has_mem_access_latency) {
2533 			u64 weight = items->mem_access_latency >> 32;
2534 
2535 			/*
2536 			 * Starts from SPR, the mem access latency field
2537 			 * contains both cache latency [47:32] and instruction
2538 			 * latency [15:0]. The cache latency is the same as the
2539 			 * mem access latency on previous platforms.
2540 			 *
2541 			 * In practice, no memory access could last than 4G
2542 			 * cycles. Use latency >> 32 to distinguish the
2543 			 * different format of the mem access latency field.
2544 			 */
2545 			if (weight > 0) {
2546 				sample.weight = weight & 0xffff;
2547 				sample.ins_lat = items->mem_access_latency & 0xffff;
2548 			} else
2549 				sample.weight = items->mem_access_latency;
2550 		}
2551 		if (!sample.weight && items->has_tsx_aux_info) {
2552 			/* Cycles last block */
2553 			sample.weight = (u32)items->tsx_aux_info;
2554 		}
2555 	}
2556 
2557 	if (sample_type & PERF_SAMPLE_DATA_SRC) {
2558 		if (items->has_mem_aux_info && data_src_fmt) {
2559 			if (data_src_fmt < 0) {
2560 				pr_err("Intel PT missing data_src info\n");
2561 				return -1;
2562 			}
2563 			sample.data_src = intel_pt_get_data_src(items->mem_aux_info, data_src_fmt);
2564 		} else {
2565 			sample.data_src = PERF_MEM_NA;
2566 		}
2567 	}
2568 
2569 	if (sample_type & PERF_SAMPLE_TRANSACTION && items->has_tsx_aux_info) {
2570 		u64 ax = items->has_rax ? items->rax : 0;
2571 		/* Refer kernel's intel_hsw_transaction() */
2572 		u64 txn = (u8)(items->tsx_aux_info >> 32);
2573 
2574 		/* For RTM XABORTs also log the abort code from AX */
2575 		if (txn & PERF_TXN_TRANSACTION && ax & 1)
2576 			txn |= ((ax >> 24) & 0xff) << PERF_TXN_ABORT_SHIFT;
2577 		sample.transaction = txn;
2578 	}
2579 
2580 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
2581 					   sample_type | evsel->synth_sample_type);
2582 	perf_sample__exit(&sample);
2583 	return ret;
2584 }
2585 
2586 static int intel_pt_synth_single_pebs_sample(struct intel_pt_queue *ptq)
2587 {
2588 	struct intel_pt *pt = ptq->pt;
2589 	struct evsel *evsel = pt->pebs_evsel;
2590 	int data_src_fmt = pt->pebs_data_src_fmt;
2591 	u64 id = evsel->core.id[0];
2592 
2593 	return intel_pt_do_synth_pebs_sample(ptq, evsel, id, data_src_fmt);
2594 }
2595 
2596 static int intel_pt_synth_pebs_sample(struct intel_pt_queue *ptq)
2597 {
2598 	const struct intel_pt_blk_items *items = &ptq->state->items;
2599 	struct intel_pt_pebs_event *pe;
2600 	struct intel_pt *pt = ptq->pt;
2601 	int err = -EINVAL;
2602 	int hw_id;
2603 
2604 	if (!items->has_applicable_counters || !items->applicable_counters) {
2605 		if (!pt->single_pebs)
2606 			pr_err("PEBS-via-PT record with no applicable_counters\n");
2607 		return intel_pt_synth_single_pebs_sample(ptq);
2608 	}
2609 
2610 	for_each_set_bit(hw_id, (unsigned long *)&items->applicable_counters, INTEL_PT_MAX_PEBS) {
2611 		pe = &ptq->pebs[hw_id];
2612 		if (!pe->evsel) {
2613 			if (!pt->single_pebs)
2614 				pr_err("PEBS-via-PT record with no matching event, hw_id %d\n",
2615 				       hw_id);
2616 			return intel_pt_synth_single_pebs_sample(ptq);
2617 		}
2618 		err = intel_pt_do_synth_pebs_sample(ptq, pe->evsel, pe->id, pe->data_src_fmt);
2619 		if (err)
2620 			return err;
2621 	}
2622 
2623 	return err;
2624 }
2625 
2626 static int intel_pt_synth_events_sample(struct intel_pt_queue *ptq)
2627 {
2628 	struct intel_pt *pt = ptq->pt;
2629 	union perf_event *event = ptq->event_buf;
2630 	struct perf_sample sample;
2631 	struct {
2632 		struct perf_synth_intel_evt cfe;
2633 		struct perf_synth_intel_evd evd[INTEL_PT_MAX_EVDS];
2634 	} raw;
2635 	int i, ret;
2636 
2637 	if (intel_pt_skip_event(pt))
2638 		return 0;
2639 
2640 	perf_sample__init(&sample, /*all=*/true);
2641 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
2642 
2643 	sample.id        = ptq->pt->evt_id;
2644 	sample.stream_id = ptq->pt->evt_id;
2645 
2646 	raw.cfe.type     = ptq->state->cfe_type;
2647 	raw.cfe.reserved = 0;
2648 	raw.cfe.ip       = !!(ptq->state->flags & INTEL_PT_FUP_IP);
2649 	raw.cfe.vector   = ptq->state->cfe_vector;
2650 	raw.cfe.evd_cnt  = ptq->state->evd_cnt;
2651 
2652 	for (i = 0; i < ptq->state->evd_cnt; i++) {
2653 		raw.evd[i].et       = 0;
2654 		raw.evd[i].evd_type = ptq->state->evd[i].type;
2655 		raw.evd[i].payload  = ptq->state->evd[i].payload;
2656 	}
2657 
2658 	sample.raw_size = perf_synth__raw_size(raw) +
2659 			  ptq->state->evd_cnt * sizeof(struct perf_synth_intel_evd);
2660 	sample.raw_data = perf_synth__raw_data(&raw);
2661 
2662 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
2663 					   pt->evt_sample_type);
2664 	perf_sample__exit(&sample);
2665 	return ret;
2666 }
2667 
2668 static int intel_pt_synth_iflag_chg_sample(struct intel_pt_queue *ptq)
2669 {
2670 	struct intel_pt *pt = ptq->pt;
2671 	union perf_event *event = ptq->event_buf;
2672 	struct perf_sample sample;
2673 	struct perf_synth_intel_iflag_chg raw;
2674 	int ret;
2675 
2676 	if (intel_pt_skip_event(pt))
2677 		return 0;
2678 
2679 	perf_sample__init(&sample, /*all=*/true);
2680 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
2681 
2682 	sample.id = ptq->pt->iflag_chg_id;
2683 	sample.stream_id = ptq->pt->iflag_chg_id;
2684 
2685 	raw.flags = 0;
2686 	raw.iflag = ptq->state->to_iflag;
2687 
2688 	if (ptq->state->type & INTEL_PT_BRANCH) {
2689 		raw.via_branch = 1;
2690 		raw.branch_ip = ptq->state->to_ip;
2691 	} else {
2692 		sample.addr = 0;
2693 	}
2694 	sample.flags = ptq->flags;
2695 
2696 	sample.raw_size = perf_synth__raw_size(raw);
2697 	sample.raw_data = perf_synth__raw_data(&raw);
2698 
2699 	ret = intel_pt_deliver_synth_event(pt, event, &sample,
2700 					   pt->iflag_chg_sample_type);
2701 	perf_sample__exit(&sample);
2702 	return ret;
2703 }
2704 
2705 static int intel_pt_synth_error(struct intel_pt *pt, int code, int cpu,
2706 				pid_t pid, pid_t tid, u64 ip, u64 timestamp,
2707 				pid_t machine_pid, int vcpu)
2708 {
2709 	bool dump_log_on_error = pt->synth_opts.log_plus_flags & AUXTRACE_LOG_FLG_ON_ERROR;
2710 	bool log_on_stdout = pt->synth_opts.log_plus_flags & AUXTRACE_LOG_FLG_USE_STDOUT;
2711 	union perf_event event;
2712 	char msg[MAX_AUXTRACE_ERROR_MSG];
2713 	int err;
2714 
2715 	if (pt->synth_opts.error_minus_flags) {
2716 		if (code == INTEL_PT_ERR_OVR &&
2717 		    pt->synth_opts.error_minus_flags & AUXTRACE_ERR_FLG_OVERFLOW)
2718 			return 0;
2719 		if (code == INTEL_PT_ERR_LOST &&
2720 		    pt->synth_opts.error_minus_flags & AUXTRACE_ERR_FLG_DATA_LOST)
2721 			return 0;
2722 	}
2723 
2724 	intel_pt__strerror(code, msg, MAX_AUXTRACE_ERROR_MSG);
2725 
2726 	auxtrace_synth_guest_error(&event.auxtrace_error, PERF_AUXTRACE_ERROR_ITRACE,
2727 				   code, cpu, pid, tid, ip, msg, timestamp,
2728 				   machine_pid, vcpu);
2729 
2730 	if (intel_pt_enable_logging && !log_on_stdout) {
2731 		FILE *fp = intel_pt_log_fp();
2732 
2733 		if (fp)
2734 			perf_event__fprintf_auxtrace_error(&event, fp);
2735 	}
2736 
2737 	if (code != INTEL_PT_ERR_LOST && dump_log_on_error)
2738 		intel_pt_log_dump_buf();
2739 
2740 	err = perf_session__deliver_synth_event(pt->session, &event, NULL);
2741 	if (err)
2742 		pr_err("Intel Processor Trace: failed to deliver error event, error %d\n",
2743 		       err);
2744 
2745 	return err;
2746 }
2747 
2748 static int intel_ptq_synth_error(struct intel_pt_queue *ptq,
2749 				 const struct intel_pt_state *state)
2750 {
2751 	struct intel_pt *pt = ptq->pt;
2752 	u64 tm = ptq->timestamp;
2753 	pid_t machine_pid = 0;
2754 	pid_t pid = ptq->pid;
2755 	pid_t tid = ptq->tid;
2756 	int vcpu = -1;
2757 
2758 	tm = pt->timeless_decoding ? 0 : tsc_to_perf_time(tm, &pt->tc);
2759 
2760 	if (pt->have_guest_sideband && state->from_nr) {
2761 		machine_pid = ptq->guest_machine_pid;
2762 		vcpu = ptq->vcpu;
2763 		pid = ptq->guest_pid;
2764 		tid = ptq->guest_tid;
2765 	}
2766 
2767 	return intel_pt_synth_error(pt, state->err, ptq->cpu, pid, tid,
2768 				    state->from_ip, tm, machine_pid, vcpu);
2769 }
2770 
2771 static int intel_pt_next_tid(struct intel_pt *pt, struct intel_pt_queue *ptq)
2772 {
2773 	struct auxtrace_queue *queue;
2774 	pid_t tid = ptq->next_tid;
2775 	int err;
2776 
2777 	if (tid == -1)
2778 		return 0;
2779 
2780 	intel_pt_log("switch: cpu %d tid %d\n", ptq->cpu, tid);
2781 
2782 	err = machine__set_current_tid(pt->machine, ptq->cpu, -1, tid);
2783 
2784 	queue = &pt->queues.queue_array[ptq->queue_nr];
2785 	intel_pt_set_pid_tid_cpu(pt, queue);
2786 
2787 	ptq->next_tid = -1;
2788 
2789 	return err;
2790 }
2791 
2792 static inline bool intel_pt_is_switch_ip(struct intel_pt_queue *ptq, u64 ip)
2793 {
2794 	struct intel_pt *pt = ptq->pt;
2795 
2796 	return ip == pt->switch_ip &&
2797 	       (ptq->flags & PERF_IP_FLAG_BRANCH) &&
2798 	       !(ptq->flags & (PERF_IP_FLAG_CONDITIONAL | PERF_IP_FLAG_ASYNC |
2799 			       PERF_IP_FLAG_INTERRUPT | PERF_IP_FLAG_TX_ABORT));
2800 }
2801 
2802 #define INTEL_PT_PWR_EVT (INTEL_PT_MWAIT_OP | INTEL_PT_PWR_ENTRY | \
2803 			  INTEL_PT_EX_STOP | INTEL_PT_PWR_EXIT)
2804 
2805 static int intel_pt_sample(struct intel_pt_queue *ptq)
2806 {
2807 	const struct intel_pt_state *state = ptq->state;
2808 	struct intel_pt *pt = ptq->pt;
2809 	int err;
2810 
2811 	if (!ptq->have_sample)
2812 		return 0;
2813 
2814 	ptq->have_sample = false;
2815 
2816 	if (pt->synth_opts.approx_ipc) {
2817 		ptq->ipc_insn_cnt = ptq->state->tot_insn_cnt;
2818 		ptq->ipc_cyc_cnt = ptq->state->cycles;
2819 		ptq->sample_ipc = true;
2820 	} else {
2821 		ptq->ipc_insn_cnt = ptq->state->tot_insn_cnt;
2822 		ptq->ipc_cyc_cnt = ptq->state->tot_cyc_cnt;
2823 		ptq->sample_ipc = ptq->state->flags & INTEL_PT_SAMPLE_IPC;
2824 	}
2825 
2826 	/* Ensure guest code maps are set up */
2827 	if (symbol_conf.guest_code && (state->from_nr || state->to_nr))
2828 		intel_pt_get_guest(ptq);
2829 
2830 	/*
2831 	 * Do PEBS first to allow for the possibility that the PEBS timestamp
2832 	 * precedes the current timestamp.
2833 	 */
2834 	if (pt->sample_pebs && state->type & INTEL_PT_BLK_ITEMS) {
2835 		err = intel_pt_synth_pebs_sample(ptq);
2836 		if (err)
2837 			return err;
2838 	}
2839 
2840 	if (pt->synth_opts.intr_events) {
2841 		if (state->type & INTEL_PT_EVT) {
2842 			err = intel_pt_synth_events_sample(ptq);
2843 			if (err)
2844 				return err;
2845 		}
2846 		if (state->type & INTEL_PT_IFLAG_CHG) {
2847 			err = intel_pt_synth_iflag_chg_sample(ptq);
2848 			if (err)
2849 				return err;
2850 		}
2851 	}
2852 
2853 	if (pt->sample_pwr_events) {
2854 		if (state->type & INTEL_PT_PSB_EVT) {
2855 			err = intel_pt_synth_psb_sample(ptq);
2856 			if (err)
2857 				return err;
2858 		}
2859 		if (ptq->state->cbr != ptq->cbr_seen) {
2860 			err = intel_pt_synth_cbr_sample(ptq);
2861 			if (err)
2862 				return err;
2863 		}
2864 		if (state->type & INTEL_PT_PWR_EVT) {
2865 			if (state->type & INTEL_PT_MWAIT_OP) {
2866 				err = intel_pt_synth_mwait_sample(ptq);
2867 				if (err)
2868 					return err;
2869 			}
2870 			if (state->type & INTEL_PT_PWR_ENTRY) {
2871 				err = intel_pt_synth_pwre_sample(ptq);
2872 				if (err)
2873 					return err;
2874 			}
2875 			if (state->type & INTEL_PT_EX_STOP) {
2876 				err = intel_pt_synth_exstop_sample(ptq);
2877 				if (err)
2878 					return err;
2879 			}
2880 			if (state->type & INTEL_PT_PWR_EXIT) {
2881 				err = intel_pt_synth_pwrx_sample(ptq);
2882 				if (err)
2883 					return err;
2884 			}
2885 		}
2886 	}
2887 
2888 	if (state->type & INTEL_PT_INSTRUCTION) {
2889 		if (pt->sample_instructions) {
2890 			err = intel_pt_synth_instruction_sample(ptq);
2891 			if (err)
2892 				return err;
2893 		}
2894 		if (pt->sample_cycles) {
2895 			err = intel_pt_synth_cycle_sample(ptq);
2896 			if (err)
2897 				return err;
2898 		}
2899 	}
2900 
2901 	if (pt->sample_transactions && (state->type & INTEL_PT_TRANSACTION)) {
2902 		err = intel_pt_synth_transaction_sample(ptq);
2903 		if (err)
2904 			return err;
2905 	}
2906 
2907 	if (pt->sample_ptwrites && (state->type & INTEL_PT_PTW)) {
2908 		err = intel_pt_synth_ptwrite_sample(ptq);
2909 		if (err)
2910 			return err;
2911 	}
2912 
2913 	if (!(state->type & INTEL_PT_BRANCH))
2914 		return 0;
2915 
2916 	if (pt->use_thread_stack) {
2917 		thread_stack__event(ptq->thread, ptq->cpu, ptq->flags,
2918 				    state->from_ip, state->to_ip, ptq->insn_len,
2919 				    state->trace_nr, pt->callstack,
2920 				    pt->br_stack_sz_plus,
2921 				    pt->mispred_all);
2922 	} else {
2923 		thread_stack__set_trace_nr(ptq->thread, ptq->cpu, state->trace_nr);
2924 	}
2925 
2926 	if (pt->sample_branches) {
2927 		if (state->from_nr != state->to_nr &&
2928 		    state->from_ip && state->to_ip) {
2929 			struct intel_pt_state *st = (struct intel_pt_state *)state;
2930 			u64 to_ip = st->to_ip;
2931 			u64 from_ip = st->from_ip;
2932 
2933 			/*
2934 			 * perf cannot handle having different machines for ip
2935 			 * and addr, so create 2 branches.
2936 			 */
2937 			st->to_ip = 0;
2938 			err = intel_pt_synth_branch_sample(ptq);
2939 			if (err)
2940 				return err;
2941 			st->from_ip = 0;
2942 			st->to_ip = to_ip;
2943 			err = intel_pt_synth_branch_sample(ptq);
2944 			st->from_ip = from_ip;
2945 		} else {
2946 			err = intel_pt_synth_branch_sample(ptq);
2947 		}
2948 		if (err)
2949 			return err;
2950 	}
2951 
2952 	if (!ptq->sync_switch)
2953 		return 0;
2954 
2955 	if (intel_pt_is_switch_ip(ptq, state->to_ip)) {
2956 		switch (ptq->switch_state) {
2957 		case INTEL_PT_SS_NOT_TRACING:
2958 		case INTEL_PT_SS_UNKNOWN:
2959 		case INTEL_PT_SS_EXPECTING_SWITCH_IP:
2960 			err = intel_pt_next_tid(pt, ptq);
2961 			if (err)
2962 				return err;
2963 			ptq->switch_state = INTEL_PT_SS_TRACING;
2964 			break;
2965 		default:
2966 			ptq->switch_state = INTEL_PT_SS_EXPECTING_SWITCH_EVENT;
2967 			return 1;
2968 		}
2969 	} else if (!state->to_ip) {
2970 		ptq->switch_state = INTEL_PT_SS_NOT_TRACING;
2971 	} else if (ptq->switch_state == INTEL_PT_SS_NOT_TRACING) {
2972 		ptq->switch_state = INTEL_PT_SS_UNKNOWN;
2973 	} else if (ptq->switch_state == INTEL_PT_SS_UNKNOWN &&
2974 		   state->to_ip == pt->ptss_ip &&
2975 		   (ptq->flags & PERF_IP_FLAG_CALL)) {
2976 		ptq->switch_state = INTEL_PT_SS_TRACING;
2977 	}
2978 
2979 	return 0;
2980 }
2981 
2982 static u64 intel_pt_switch_ip(struct intel_pt *pt, u64 *ptss_ip)
2983 {
2984 	struct machine *machine = pt->machine;
2985 	struct map *map;
2986 	struct symbol *sym, *start;
2987 	u64 ip, switch_ip = 0;
2988 	const char *ptss;
2989 
2990 	if (ptss_ip)
2991 		*ptss_ip = 0;
2992 
2993 	map = machine__kernel_map(machine);
2994 	if (!map)
2995 		return 0;
2996 
2997 	if (map__load(map))
2998 		return 0;
2999 
3000 	start = dso__first_symbol(map__dso(map));
3001 
3002 	for (sym = start; sym; sym = dso__next_symbol(sym)) {
3003 		if (symbol__binding(sym) == STB_GLOBAL &&
3004 		    !strcmp(sym->name, "__switch_to")) {
3005 			ip = map__unmap_ip(map, sym->start);
3006 			if (ip >= map__start(map) && ip < map__end(map)) {
3007 				switch_ip = ip;
3008 				break;
3009 			}
3010 		}
3011 	}
3012 
3013 	if (!switch_ip || !ptss_ip)
3014 		return 0;
3015 
3016 	if (pt->have_sched_switch == 1)
3017 		ptss = "perf_trace_sched_switch";
3018 	else
3019 		ptss = "__perf_event_task_sched_out";
3020 
3021 	for (sym = start; sym; sym = dso__next_symbol(sym)) {
3022 		if (!strcmp(sym->name, ptss)) {
3023 			ip = map__unmap_ip(map, sym->start);
3024 			if (ip >= map__start(map) && ip < map__end(map)) {
3025 				*ptss_ip = ip;
3026 				break;
3027 			}
3028 		}
3029 	}
3030 
3031 	return switch_ip;
3032 }
3033 
3034 static void intel_pt_enable_sync_switch(struct intel_pt *pt)
3035 {
3036 	unsigned int i;
3037 
3038 	if (pt->sync_switch_not_supported)
3039 		return;
3040 
3041 	pt->sync_switch = true;
3042 
3043 	for (i = 0; i < pt->queues.nr_queues; i++) {
3044 		struct auxtrace_queue *queue = &pt->queues.queue_array[i];
3045 		struct intel_pt_queue *ptq = queue->priv;
3046 
3047 		if (ptq)
3048 			ptq->sync_switch = true;
3049 	}
3050 }
3051 
3052 static void intel_pt_disable_sync_switch(struct intel_pt *pt)
3053 {
3054 	unsigned int i;
3055 
3056 	pt->sync_switch = false;
3057 
3058 	for (i = 0; i < pt->queues.nr_queues; i++) {
3059 		struct auxtrace_queue *queue = &pt->queues.queue_array[i];
3060 		struct intel_pt_queue *ptq = queue->priv;
3061 
3062 		if (ptq) {
3063 			ptq->sync_switch = false;
3064 			intel_pt_next_tid(pt, ptq);
3065 		}
3066 	}
3067 }
3068 
3069 /*
3070  * To filter against time ranges, it is only necessary to look at the next start
3071  * or end time.
3072  */
3073 static bool intel_pt_next_time(struct intel_pt_queue *ptq)
3074 {
3075 	struct intel_pt *pt = ptq->pt;
3076 
3077 	if (ptq->sel_start) {
3078 		/* Next time is an end time */
3079 		ptq->sel_start = false;
3080 		ptq->sel_timestamp = pt->time_ranges[ptq->sel_idx].end;
3081 		return true;
3082 	} else if (ptq->sel_idx + 1 < pt->range_cnt) {
3083 		/* Next time is a start time */
3084 		ptq->sel_start = true;
3085 		ptq->sel_idx += 1;
3086 		ptq->sel_timestamp = pt->time_ranges[ptq->sel_idx].start;
3087 		return true;
3088 	}
3089 
3090 	/* No next time */
3091 	return false;
3092 }
3093 
3094 static int intel_pt_time_filter(struct intel_pt_queue *ptq, u64 *ff_timestamp)
3095 {
3096 	int err;
3097 
3098 	while (1) {
3099 		if (ptq->sel_start) {
3100 			if (ptq->timestamp >= ptq->sel_timestamp) {
3101 				/* After start time, so consider next time */
3102 				intel_pt_next_time(ptq);
3103 				if (!ptq->sel_timestamp) {
3104 					/* No end time */
3105 					return 0;
3106 				}
3107 				/* Check against end time */
3108 				continue;
3109 			}
3110 			/* Before start time, so fast forward */
3111 			ptq->have_sample = false;
3112 			if (ptq->sel_timestamp > *ff_timestamp) {
3113 				if (ptq->sync_switch) {
3114 					intel_pt_next_tid(ptq->pt, ptq);
3115 					ptq->switch_state = INTEL_PT_SS_UNKNOWN;
3116 				}
3117 				*ff_timestamp = ptq->sel_timestamp;
3118 				err = intel_pt_fast_forward(ptq->decoder,
3119 							    ptq->sel_timestamp);
3120 				if (err)
3121 					return err;
3122 			}
3123 			return 0;
3124 		} else if (ptq->timestamp > ptq->sel_timestamp) {
3125 			/* After end time, so consider next time */
3126 			if (!intel_pt_next_time(ptq)) {
3127 				/* No next time range, so stop decoding */
3128 				ptq->have_sample = false;
3129 				ptq->switch_state = INTEL_PT_SS_NOT_TRACING;
3130 				return 1;
3131 			}
3132 			/* Check against next start time */
3133 			continue;
3134 		} else {
3135 			/* Before end time */
3136 			return 0;
3137 		}
3138 	}
3139 }
3140 
3141 static int intel_pt_run_decoder(struct intel_pt_queue *ptq, u64 *timestamp)
3142 {
3143 	const struct intel_pt_state *state = ptq->state;
3144 	struct intel_pt *pt = ptq->pt;
3145 	u64 ff_timestamp = 0;
3146 	int err;
3147 
3148 	if (!pt->kernel_start) {
3149 		pt->kernel_start = machine__kernel_start(pt->machine);
3150 		if (pt->per_cpu_mmaps &&
3151 		    (pt->have_sched_switch == 1 || pt->have_sched_switch == 3) &&
3152 		    !pt->timeless_decoding && intel_pt_tracing_kernel(pt) &&
3153 		    !pt->sampling_mode && !pt->synth_opts.vm_time_correlation) {
3154 			pt->switch_ip = intel_pt_switch_ip(pt, &pt->ptss_ip);
3155 			if (pt->switch_ip) {
3156 				intel_pt_log("switch_ip: %"PRIx64" ptss_ip: %"PRIx64"\n",
3157 					     pt->switch_ip, pt->ptss_ip);
3158 				intel_pt_enable_sync_switch(pt);
3159 			}
3160 		}
3161 	}
3162 
3163 	intel_pt_log("queue %u decoding cpu %d pid %d tid %d\n",
3164 		     ptq->queue_nr, ptq->cpu, ptq->pid, ptq->tid);
3165 	while (1) {
3166 		err = intel_pt_sample(ptq);
3167 		if (err)
3168 			return err;
3169 
3170 		state = intel_pt_decode(ptq->decoder);
3171 		if (state->err) {
3172 			if (state->err == INTEL_PT_ERR_NODATA)
3173 				return 1;
3174 			if (ptq->sync_switch &&
3175 			    state->from_ip >= pt->kernel_start) {
3176 				ptq->sync_switch = false;
3177 				intel_pt_next_tid(pt, ptq);
3178 			}
3179 			ptq->timestamp = state->est_timestamp;
3180 			if (pt->synth_opts.errors) {
3181 				err = intel_ptq_synth_error(ptq, state);
3182 				if (err)
3183 					return err;
3184 			}
3185 			continue;
3186 		}
3187 
3188 		ptq->state = state;
3189 		ptq->have_sample = true;
3190 		intel_pt_sample_flags(ptq);
3191 
3192 		/* Use estimated TSC upon return to user space */
3193 		if (pt->est_tsc &&
3194 		    (state->from_ip >= pt->kernel_start || !state->from_ip) &&
3195 		    state->to_ip && state->to_ip < pt->kernel_start) {
3196 			intel_pt_log("TSC %"PRIx64" est. TSC %"PRIx64"\n",
3197 				     state->timestamp, state->est_timestamp);
3198 			ptq->timestamp = state->est_timestamp;
3199 		/* Use estimated TSC in unknown switch state */
3200 		} else if (ptq->sync_switch &&
3201 			   ptq->switch_state == INTEL_PT_SS_UNKNOWN &&
3202 			   intel_pt_is_switch_ip(ptq, state->to_ip) &&
3203 			   ptq->next_tid == -1) {
3204 			intel_pt_log("TSC %"PRIx64" est. TSC %"PRIx64"\n",
3205 				     state->timestamp, state->est_timestamp);
3206 			ptq->timestamp = state->est_timestamp;
3207 		} else if (state->timestamp > ptq->timestamp) {
3208 			ptq->timestamp = state->timestamp;
3209 		}
3210 
3211 		if (ptq->sel_timestamp) {
3212 			err = intel_pt_time_filter(ptq, &ff_timestamp);
3213 			if (err)
3214 				return err;
3215 		}
3216 
3217 		if (!pt->timeless_decoding && ptq->timestamp >= *timestamp) {
3218 			*timestamp = ptq->timestamp;
3219 			return 0;
3220 		}
3221 	}
3222 	return 0;
3223 }
3224 
3225 static inline int intel_pt_update_queues(struct intel_pt *pt)
3226 {
3227 	if (pt->queues.new_data) {
3228 		pt->queues.new_data = false;
3229 		return intel_pt_setup_queues(pt);
3230 	}
3231 	return 0;
3232 }
3233 
3234 static int intel_pt_process_queues(struct intel_pt *pt, u64 timestamp)
3235 {
3236 	unsigned int queue_nr;
3237 	u64 ts;
3238 	int ret;
3239 
3240 	while (1) {
3241 		struct auxtrace_queue *queue;
3242 		struct intel_pt_queue *ptq;
3243 
3244 		if (!pt->heap.heap_cnt)
3245 			return 0;
3246 
3247 		if (pt->heap.heap_array[0].ordinal >= timestamp)
3248 			return 0;
3249 
3250 		queue_nr = pt->heap.heap_array[0].queue_nr;
3251 		queue = &pt->queues.queue_array[queue_nr];
3252 		ptq = queue->priv;
3253 
3254 		intel_pt_log("queue %u processing 0x%" PRIx64 " to 0x%" PRIx64 "\n",
3255 			     queue_nr, pt->heap.heap_array[0].ordinal,
3256 			     timestamp);
3257 
3258 		auxtrace_heap__pop(&pt->heap);
3259 
3260 		if (pt->heap.heap_cnt) {
3261 			ts = pt->heap.heap_array[0].ordinal + 1;
3262 			if (ts > timestamp)
3263 				ts = timestamp;
3264 		} else {
3265 			ts = timestamp;
3266 		}
3267 
3268 		intel_pt_set_pid_tid_cpu(pt, queue);
3269 
3270 		ret = intel_pt_run_decoder(ptq, &ts);
3271 
3272 		if (ret < 0) {
3273 			auxtrace_heap__add(&pt->heap, queue_nr, ts);
3274 			return ret;
3275 		}
3276 
3277 		if (!ret) {
3278 			ret = auxtrace_heap__add(&pt->heap, queue_nr, ts);
3279 			if (ret < 0)
3280 				return ret;
3281 		} else {
3282 			ptq->on_heap = false;
3283 		}
3284 	}
3285 
3286 	return 0;
3287 }
3288 
3289 static int intel_pt_process_timeless_queues(struct intel_pt *pt, pid_t tid,
3290 					    u64 time_)
3291 {
3292 	struct auxtrace_queues *queues = &pt->queues;
3293 	unsigned int i;
3294 	u64 ts = 0;
3295 
3296 	for (i = 0; i < queues->nr_queues; i++) {
3297 		struct auxtrace_queue *queue = &pt->queues.queue_array[i];
3298 		struct intel_pt_queue *ptq = queue->priv;
3299 
3300 		if (ptq && (tid == -1 || ptq->tid == tid)) {
3301 			ptq->time = time_;
3302 			intel_pt_set_pid_tid_cpu(pt, queue);
3303 			intel_pt_run_decoder(ptq, &ts);
3304 		}
3305 	}
3306 	return 0;
3307 }
3308 
3309 static void intel_pt_sample_set_pid_tid_cpu(struct intel_pt_queue *ptq,
3310 					    struct auxtrace_queue *queue,
3311 					    struct perf_sample *sample)
3312 {
3313 	struct machine *m = ptq->pt->machine;
3314 
3315 	ptq->pid = sample->pid;
3316 	ptq->tid = sample->tid;
3317 	ptq->cpu = queue->cpu;
3318 
3319 	intel_pt_log("queue %u cpu %d pid %d tid %d\n",
3320 		     ptq->queue_nr, ptq->cpu, ptq->pid, ptq->tid);
3321 
3322 	thread__zput(ptq->thread);
3323 
3324 	if (ptq->tid == -1)
3325 		return;
3326 
3327 	if (ptq->pid == -1) {
3328 		ptq->thread = machine__find_thread(m, -1, ptq->tid);
3329 		if (ptq->thread)
3330 			ptq->pid = thread__pid(ptq->thread);
3331 		return;
3332 	}
3333 
3334 	ptq->thread = machine__findnew_thread(m, ptq->pid, ptq->tid);
3335 }
3336 
3337 static int intel_pt_process_timeless_sample(struct intel_pt *pt,
3338 					    struct perf_sample *sample)
3339 {
3340 	struct auxtrace_queue *queue;
3341 	struct intel_pt_queue *ptq;
3342 	u64 ts = 0;
3343 
3344 	queue = auxtrace_queues__sample_queue(&pt->queues, sample, pt->session);
3345 	if (!queue)
3346 		return -EINVAL;
3347 
3348 	ptq = queue->priv;
3349 	if (!ptq)
3350 		return 0;
3351 
3352 	ptq->stop = false;
3353 	ptq->time = sample->time;
3354 	intel_pt_sample_set_pid_tid_cpu(ptq, queue, sample);
3355 	intel_pt_run_decoder(ptq, &ts);
3356 	return 0;
3357 }
3358 
3359 static int intel_pt_lost(struct intel_pt *pt, struct perf_sample *sample)
3360 {
3361 	return intel_pt_synth_error(pt, INTEL_PT_ERR_LOST, sample->cpu,
3362 				    sample->pid, sample->tid, 0, sample->time,
3363 				    sample->machine_pid, sample->vcpu);
3364 }
3365 
3366 static struct intel_pt_queue *intel_pt_cpu_to_ptq(struct intel_pt *pt, int cpu)
3367 {
3368 	unsigned i, j;
3369 
3370 	if (cpu < 0 || !pt->queues.nr_queues)
3371 		return NULL;
3372 
3373 	if ((unsigned)cpu >= pt->queues.nr_queues)
3374 		i = pt->queues.nr_queues - 1;
3375 	else
3376 		i = cpu;
3377 
3378 	if (pt->queues.queue_array[i].cpu == cpu)
3379 		return pt->queues.queue_array[i].priv;
3380 
3381 	for (j = 0; i > 0; j++) {
3382 		if (pt->queues.queue_array[--i].cpu == cpu)
3383 			return pt->queues.queue_array[i].priv;
3384 	}
3385 
3386 	for (; j < pt->queues.nr_queues; j++) {
3387 		if (pt->queues.queue_array[j].cpu == cpu)
3388 			return pt->queues.queue_array[j].priv;
3389 	}
3390 
3391 	return NULL;
3392 }
3393 
3394 static int intel_pt_sync_switch(struct intel_pt *pt, int cpu, pid_t tid,
3395 				u64 timestamp)
3396 {
3397 	struct intel_pt_queue *ptq;
3398 	int err;
3399 
3400 	if (!pt->sync_switch)
3401 		return 1;
3402 
3403 	ptq = intel_pt_cpu_to_ptq(pt, cpu);
3404 	if (!ptq || !ptq->sync_switch)
3405 		return 1;
3406 
3407 	switch (ptq->switch_state) {
3408 	case INTEL_PT_SS_NOT_TRACING:
3409 		break;
3410 	case INTEL_PT_SS_UNKNOWN:
3411 	case INTEL_PT_SS_TRACING:
3412 		ptq->next_tid = tid;
3413 		ptq->switch_state = INTEL_PT_SS_EXPECTING_SWITCH_IP;
3414 		return 0;
3415 	case INTEL_PT_SS_EXPECTING_SWITCH_EVENT:
3416 		if (!ptq->on_heap) {
3417 			ptq->timestamp = perf_time_to_tsc(timestamp,
3418 							  &pt->tc);
3419 			err = auxtrace_heap__add(&pt->heap, ptq->queue_nr,
3420 						 ptq->timestamp);
3421 			if (err)
3422 				return err;
3423 			ptq->on_heap = true;
3424 		}
3425 		ptq->switch_state = INTEL_PT_SS_TRACING;
3426 		break;
3427 	case INTEL_PT_SS_EXPECTING_SWITCH_IP:
3428 		intel_pt_log("ERROR: cpu %d expecting switch ip\n", cpu);
3429 		break;
3430 	default:
3431 		break;
3432 	}
3433 
3434 	ptq->next_tid = -1;
3435 
3436 	return 1;
3437 }
3438 
3439 #ifdef HAVE_LIBTRACEEVENT
3440 static int intel_pt_process_switch(struct intel_pt *pt,
3441 				   struct perf_sample *sample)
3442 {
3443 	pid_t tid;
3444 	int cpu, ret;
3445 	struct evsel *evsel = evlist__id2evsel(pt->session->evlist, sample->id);
3446 
3447 	if (evsel != pt->switch_evsel)
3448 		return 0;
3449 
3450 	tid = perf_sample__intval(sample, "next_pid");
3451 	cpu = sample->cpu;
3452 
3453 	intel_pt_log("sched_switch: cpu %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
3454 		     cpu, tid, sample->time, perf_time_to_tsc(sample->time,
3455 		     &pt->tc));
3456 
3457 	ret = intel_pt_sync_switch(pt, cpu, tid, sample->time);
3458 	if (ret <= 0)
3459 		return ret;
3460 
3461 	return machine__set_current_tid(pt->machine, cpu, -1, tid);
3462 }
3463 #endif /* HAVE_LIBTRACEEVENT */
3464 
3465 static int intel_pt_context_switch_in(struct intel_pt *pt,
3466 				      struct perf_sample *sample)
3467 {
3468 	pid_t pid = sample->pid;
3469 	pid_t tid = sample->tid;
3470 	int cpu = sample->cpu;
3471 
3472 	if (pt->sync_switch) {
3473 		struct intel_pt_queue *ptq;
3474 
3475 		ptq = intel_pt_cpu_to_ptq(pt, cpu);
3476 		if (ptq && ptq->sync_switch) {
3477 			ptq->next_tid = -1;
3478 			switch (ptq->switch_state) {
3479 			case INTEL_PT_SS_NOT_TRACING:
3480 			case INTEL_PT_SS_UNKNOWN:
3481 			case INTEL_PT_SS_TRACING:
3482 				break;
3483 			case INTEL_PT_SS_EXPECTING_SWITCH_EVENT:
3484 			case INTEL_PT_SS_EXPECTING_SWITCH_IP:
3485 				ptq->switch_state = INTEL_PT_SS_TRACING;
3486 				break;
3487 			default:
3488 				break;
3489 			}
3490 		}
3491 	}
3492 
3493 	/*
3494 	 * If the current tid has not been updated yet, ensure it is now that
3495 	 * a "switch in" event has occurred.
3496 	 */
3497 	if (machine__get_current_tid(pt->machine, cpu) == tid)
3498 		return 0;
3499 
3500 	return machine__set_current_tid(pt->machine, cpu, pid, tid);
3501 }
3502 
3503 static int intel_pt_guest_context_switch(struct intel_pt *pt,
3504 					 union perf_event *event,
3505 					 struct perf_sample *sample)
3506 {
3507 	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
3508 	struct machines *machines = &pt->session->machines;
3509 	struct machine *machine = machines__find(machines, sample->machine_pid);
3510 
3511 	pt->have_guest_sideband = true;
3512 
3513 	/*
3514 	 * sync_switch cannot handle guest machines at present, so just disable
3515 	 * it.
3516 	 */
3517 	pt->sync_switch_not_supported = true;
3518 	if (pt->sync_switch)
3519 		intel_pt_disable_sync_switch(pt);
3520 
3521 	if (out)
3522 		return 0;
3523 
3524 	if (!machine)
3525 		return -EINVAL;
3526 
3527 	return machine__set_current_tid(machine, sample->vcpu, sample->pid, sample->tid);
3528 }
3529 
3530 static int intel_pt_context_switch(struct intel_pt *pt, union perf_event *event,
3531 				   struct perf_sample *sample)
3532 {
3533 	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
3534 	pid_t pid, tid;
3535 	int cpu, ret;
3536 
3537 	if (perf_event__is_guest(event))
3538 		return intel_pt_guest_context_switch(pt, event, sample);
3539 
3540 	cpu = sample->cpu;
3541 
3542 	if (pt->have_sched_switch == 3) {
3543 		if (!out)
3544 			return intel_pt_context_switch_in(pt, sample);
3545 		if (event->header.type != PERF_RECORD_SWITCH_CPU_WIDE) {
3546 			pr_err("Expecting CPU-wide context switch event\n");
3547 			return -EINVAL;
3548 		}
3549 		pid = event->context_switch.next_prev_pid;
3550 		tid = event->context_switch.next_prev_tid;
3551 	} else {
3552 		if (out)
3553 			return 0;
3554 		pid = sample->pid;
3555 		tid = sample->tid;
3556 	}
3557 
3558 	if (tid == -1)
3559 		intel_pt_log("context_switch event has no tid\n");
3560 
3561 	ret = intel_pt_sync_switch(pt, cpu, tid, sample->time);
3562 	if (ret <= 0)
3563 		return ret;
3564 
3565 	return machine__set_current_tid(pt->machine, cpu, pid, tid);
3566 }
3567 
3568 static int intel_pt_process_itrace_start(struct intel_pt *pt,
3569 					 union perf_event *event,
3570 					 struct perf_sample *sample)
3571 {
3572 	if (!pt->per_cpu_mmaps)
3573 		return 0;
3574 
3575 	intel_pt_log("itrace_start: cpu %d pid %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
3576 		     sample->cpu, event->itrace_start.pid,
3577 		     event->itrace_start.tid, sample->time,
3578 		     perf_time_to_tsc(sample->time, &pt->tc));
3579 
3580 	return machine__set_current_tid(pt->machine, sample->cpu,
3581 					event->itrace_start.pid,
3582 					event->itrace_start.tid);
3583 }
3584 
3585 /*
3586  * Events with data_src are identified by L1_Hit_Indication
3587  * refer https://github.com/intel/perfmon
3588  */
3589 static int intel_pt_data_src_fmt(struct intel_pt *pt, struct evsel *evsel)
3590 {
3591 	struct perf_env *env = pt->machine->env;
3592 	int fmt = DATA_SRC_FORMAT_NA;
3593 
3594 	if (!env->cpuid)
3595 		return DATA_SRC_FORMAT_ERR;
3596 
3597 	/*
3598 	 * PEBS-via-PT is only supported on E-core non-hybrid. Of those only
3599 	 * Gracemont and Crestmont have data_src. Check for:
3600 	 *	Alderlake N   (Gracemont)
3601 	 *	Sierra Forest (Crestmont)
3602 	 *	Grand Ridge   (Crestmont)
3603 	 */
3604 
3605 	if (!strncmp(env->cpuid, "GenuineIntel,6,190,", 19))
3606 		fmt = DATA_SRC_FORMAT_GRT;
3607 
3608 	if (!strncmp(env->cpuid, "GenuineIntel,6,175,", 19) ||
3609 	    !strncmp(env->cpuid, "GenuineIntel,6,182,", 19))
3610 		fmt = DATA_SRC_FORMAT_CMT;
3611 
3612 	if (fmt == DATA_SRC_FORMAT_NA)
3613 		return fmt;
3614 
3615 	/*
3616 	 * Only data_src events are:
3617 	 *	mem-loads	event=0xd0,umask=0x5
3618 	 *	mem-stores	event=0xd0,umask=0x6
3619 	 */
3620 	if (evsel->core.attr.type == PERF_TYPE_RAW &&
3621 	    ((evsel->core.attr.config & 0xffff) == 0x5d0 ||
3622 	     (evsel->core.attr.config & 0xffff) == 0x6d0))
3623 		return fmt;
3624 
3625 	return DATA_SRC_FORMAT_NA;
3626 }
3627 
3628 static int intel_pt_process_aux_output_hw_id(struct intel_pt *pt,
3629 					     union perf_event *event,
3630 					     struct perf_sample *sample)
3631 {
3632 	u64 hw_id = event->aux_output_hw_id.hw_id;
3633 	struct auxtrace_queue *queue;
3634 	struct intel_pt_queue *ptq;
3635 	struct evsel *evsel;
3636 
3637 	queue = auxtrace_queues__sample_queue(&pt->queues, sample, pt->session);
3638 	evsel = evlist__id2evsel_strict(pt->session->evlist, sample->id);
3639 	if (!queue || !queue->priv || !evsel || hw_id > INTEL_PT_MAX_PEBS) {
3640 		pr_err("Bad AUX output hardware ID\n");
3641 		return -EINVAL;
3642 	}
3643 
3644 	ptq = queue->priv;
3645 
3646 	ptq->pebs[hw_id].evsel = evsel;
3647 	ptq->pebs[hw_id].id = sample->id;
3648 	ptq->pebs[hw_id].data_src_fmt = intel_pt_data_src_fmt(pt, evsel);
3649 
3650 	return 0;
3651 }
3652 
3653 static int intel_pt_find_map(struct thread *thread, u8 cpumode, u64 addr,
3654 			     struct addr_location *al)
3655 {
3656 	if (!al->map || addr < map__start(al->map) || addr >= map__end(al->map)) {
3657 		if (!thread__find_map(thread, cpumode, addr, al))
3658 			return -1;
3659 	}
3660 
3661 	return 0;
3662 }
3663 
3664 /* Invalidate all instruction cache entries that overlap the text poke */
3665 static int intel_pt_text_poke(struct intel_pt *pt, union perf_event *event)
3666 {
3667 	u8 cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
3668 	u64 addr = event->text_poke.addr + event->text_poke.new_len - 1;
3669 	/* Assume text poke begins in a basic block no more than 4096 bytes */
3670 	int cnt = 4096 + event->text_poke.new_len;
3671 	struct thread *thread = pt->unknown_thread;
3672 	struct addr_location al;
3673 	struct machine *machine = pt->machine;
3674 	struct intel_pt_cache_entry *e;
3675 	u64 offset;
3676 	int ret = 0;
3677 
3678 	addr_location__init(&al);
3679 	if (!event->text_poke.new_len)
3680 		goto out;
3681 
3682 	for (; cnt; cnt--, addr--) {
3683 		struct dso *dso;
3684 
3685 		if (intel_pt_find_map(thread, cpumode, addr, &al)) {
3686 			if (addr < event->text_poke.addr)
3687 				goto out;
3688 			continue;
3689 		}
3690 
3691 		dso = map__dso(al.map);
3692 		if (!dso || !dso__auxtrace_cache(dso))
3693 			continue;
3694 
3695 		offset = map__map_ip(al.map, addr);
3696 
3697 		e = intel_pt_cache_lookup(dso, machine, offset);
3698 		if (!e)
3699 			continue;
3700 
3701 		if (addr + e->byte_cnt + e->length <= event->text_poke.addr) {
3702 			/*
3703 			 * No overlap. Working backwards there cannot be another
3704 			 * basic block that overlaps the text poke if there is a
3705 			 * branch instruction before the text poke address.
3706 			 */
3707 			if (e->branch != INTEL_PT_BR_NO_BRANCH)
3708 				goto out;
3709 		} else {
3710 			intel_pt_cache_invalidate(dso, machine, offset);
3711 			intel_pt_log("Invalidated instruction cache for %s at %#"PRIx64"\n",
3712 				     dso__long_name(dso), addr);
3713 		}
3714 	}
3715 out:
3716 	addr_location__exit(&al);
3717 	return ret;
3718 }
3719 
3720 static int intel_pt_process_event(struct perf_session *session,
3721 				  union perf_event *event,
3722 				  struct perf_sample *sample,
3723 				  const struct perf_tool *tool)
3724 {
3725 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
3726 					   auxtrace);
3727 	u64 timestamp;
3728 	int err = 0;
3729 
3730 	if (dump_trace)
3731 		return 0;
3732 
3733 	if (!tool->ordered_events) {
3734 		pr_err("Intel Processor Trace requires ordered events\n");
3735 		return -EINVAL;
3736 	}
3737 
3738 	if (sample->time && sample->time != (u64)-1)
3739 		timestamp = perf_time_to_tsc(sample->time, &pt->tc);
3740 	else
3741 		timestamp = 0;
3742 
3743 	if (timestamp || pt->timeless_decoding) {
3744 		err = intel_pt_update_queues(pt);
3745 		if (err)
3746 			return err;
3747 	}
3748 
3749 	if (pt->timeless_decoding) {
3750 		if (pt->sampling_mode) {
3751 			if (sample->aux_sample.size)
3752 				err = intel_pt_process_timeless_sample(pt,
3753 								       sample);
3754 		} else if (event->header.type == PERF_RECORD_EXIT) {
3755 			err = intel_pt_process_timeless_queues(pt,
3756 							       event->fork.tid,
3757 							       sample->time);
3758 		}
3759 	} else if (timestamp) {
3760 		if (!pt->first_timestamp)
3761 			intel_pt_first_timestamp(pt, timestamp);
3762 		err = intel_pt_process_queues(pt, timestamp);
3763 	}
3764 	if (err)
3765 		return err;
3766 
3767 	if (event->header.type == PERF_RECORD_SAMPLE) {
3768 		if (pt->synth_opts.add_callchain && !sample->callchain)
3769 			intel_pt_add_callchain(pt, sample);
3770 		if (pt->synth_opts.add_last_branch && !sample->branch_stack)
3771 			intel_pt_add_br_stack(pt, sample);
3772 	}
3773 
3774 	if (event->header.type == PERF_RECORD_AUX &&
3775 	    (event->aux.flags & PERF_AUX_FLAG_TRUNCATED) &&
3776 	    pt->synth_opts.errors) {
3777 		err = intel_pt_lost(pt, sample);
3778 		if (err)
3779 			return err;
3780 	}
3781 
3782 #ifdef HAVE_LIBTRACEEVENT
3783 	if (pt->switch_evsel && event->header.type == PERF_RECORD_SAMPLE)
3784 		err = intel_pt_process_switch(pt, sample);
3785 	else
3786 #endif
3787 	if (event->header.type == PERF_RECORD_ITRACE_START)
3788 		err = intel_pt_process_itrace_start(pt, event, sample);
3789 	else if (event->header.type == PERF_RECORD_AUX_OUTPUT_HW_ID)
3790 		err = intel_pt_process_aux_output_hw_id(pt, event, sample);
3791 	else if (event->header.type == PERF_RECORD_SWITCH ||
3792 		 event->header.type == PERF_RECORD_SWITCH_CPU_WIDE)
3793 		err = intel_pt_context_switch(pt, event, sample);
3794 
3795 	if (!err && event->header.type == PERF_RECORD_TEXT_POKE)
3796 		err = intel_pt_text_poke(pt, event);
3797 
3798 	if (intel_pt_enable_logging && intel_pt_log_events(pt, sample->time)) {
3799 		intel_pt_log("event %u: cpu %d time %"PRIu64" tsc %#"PRIx64" ",
3800 			     event->header.type, sample->cpu, sample->time, timestamp);
3801 		intel_pt_log_event(event);
3802 	}
3803 
3804 	return err;
3805 }
3806 
3807 static int intel_pt_flush(struct perf_session *session, const struct perf_tool *tool)
3808 {
3809 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
3810 					   auxtrace);
3811 	int ret;
3812 
3813 	if (dump_trace)
3814 		return 0;
3815 
3816 	if (!tool->ordered_events)
3817 		return -EINVAL;
3818 
3819 	ret = intel_pt_update_queues(pt);
3820 	if (ret < 0)
3821 		return ret;
3822 
3823 	if (pt->timeless_decoding)
3824 		return intel_pt_process_timeless_queues(pt, -1,
3825 							MAX_TIMESTAMP - 1);
3826 
3827 	return intel_pt_process_queues(pt, MAX_TIMESTAMP);
3828 }
3829 
3830 static void intel_pt_free_events(struct perf_session *session)
3831 {
3832 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
3833 					   auxtrace);
3834 	struct auxtrace_queues *queues = &pt->queues;
3835 	unsigned int i;
3836 
3837 	for (i = 0; i < queues->nr_queues; i++) {
3838 		intel_pt_free_queue(queues->queue_array[i].priv);
3839 		queues->queue_array[i].priv = NULL;
3840 	}
3841 	intel_pt_log_disable();
3842 	auxtrace_queues__free(queues);
3843 }
3844 
3845 static void intel_pt_free(struct perf_session *session)
3846 {
3847 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
3848 					   auxtrace);
3849 
3850 	auxtrace_heap__free(&pt->heap);
3851 	intel_pt_free_events(session);
3852 	session->auxtrace = NULL;
3853 	intel_pt_free_vmcs_info(pt);
3854 	thread__put(pt->unknown_thread);
3855 	addr_filters__exit(&pt->filts);
3856 	zfree(&pt->chain);
3857 	zfree(&pt->filter);
3858 	zfree(&pt->time_ranges);
3859 	zfree(&pt->br_stack);
3860 	free(pt);
3861 }
3862 
3863 static bool intel_pt_evsel_is_auxtrace(struct perf_session *session,
3864 				       struct evsel *evsel)
3865 {
3866 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
3867 					   auxtrace);
3868 
3869 	return evsel->core.attr.type == pt->pmu_type;
3870 }
3871 
3872 static int intel_pt_process_auxtrace_event(struct perf_session *session,
3873 					   union perf_event *event,
3874 					   const struct perf_tool *tool __maybe_unused)
3875 {
3876 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
3877 					   auxtrace);
3878 
3879 	if (!pt->data_queued) {
3880 		struct auxtrace_buffer *buffer;
3881 		off_t data_offset;
3882 		int fd = perf_data__fd(session->data);
3883 		int err;
3884 
3885 		if (perf_data__is_pipe(session->data)) {
3886 			data_offset = 0;
3887 		} else {
3888 			data_offset = lseek(fd, 0, SEEK_CUR);
3889 			if (data_offset == -1)
3890 				return -errno;
3891 		}
3892 
3893 		err = auxtrace_queues__add_event(&pt->queues, session, event,
3894 						 data_offset, &buffer);
3895 		if (err)
3896 			return err;
3897 
3898 		/* Dump here now we have copied a piped trace out of the pipe */
3899 		if (dump_trace) {
3900 			if (auxtrace_buffer__get_data(buffer, fd)) {
3901 				intel_pt_dump_event(pt, buffer->data,
3902 						    buffer->size);
3903 				auxtrace_buffer__put_data(buffer);
3904 			}
3905 		}
3906 	}
3907 
3908 	return 0;
3909 }
3910 
3911 static int intel_pt_queue_data(struct perf_session *session,
3912 			       struct perf_sample *sample,
3913 			       union perf_event *event, u64 data_offset)
3914 {
3915 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
3916 					   auxtrace);
3917 	u64 timestamp;
3918 
3919 	if (event) {
3920 		return auxtrace_queues__add_event(&pt->queues, session, event,
3921 						  data_offset, NULL);
3922 	}
3923 
3924 	if (sample->time && sample->time != (u64)-1)
3925 		timestamp = perf_time_to_tsc(sample->time, &pt->tc);
3926 	else
3927 		timestamp = 0;
3928 
3929 	return auxtrace_queues__add_sample(&pt->queues, session, sample,
3930 					   data_offset, timestamp);
3931 }
3932 
3933 static int intel_pt_synth_event(struct perf_session *session, const char *name,
3934 				struct perf_event_attr *attr, u64 id)
3935 {
3936 	int err;
3937 
3938 	pr_debug("Synthesizing '%s' event with id %" PRIu64 " sample type %#" PRIx64 "\n",
3939 		 name, id, (u64)attr->sample_type);
3940 
3941 	err = perf_session__deliver_synth_attr_event(session, attr, id);
3942 	if (err)
3943 		pr_err("%s: failed to synthesize '%s' event type\n",
3944 		       __func__, name);
3945 
3946 	return err;
3947 }
3948 
3949 static void intel_pt_set_event_name(struct evlist *evlist, u64 id,
3950 				    const char *name)
3951 {
3952 	struct evsel *evsel;
3953 
3954 	evlist__for_each_entry(evlist, evsel) {
3955 		if (evsel->core.id && evsel->core.id[0] == id) {
3956 			if (evsel->name)
3957 				zfree(&evsel->name);
3958 			evsel->name = strdup(name);
3959 			break;
3960 		}
3961 	}
3962 }
3963 
3964 static struct evsel *intel_pt_evsel(struct intel_pt *pt,
3965 					 struct evlist *evlist)
3966 {
3967 	struct evsel *evsel;
3968 
3969 	evlist__for_each_entry(evlist, evsel) {
3970 		if (evsel->core.attr.type == pt->pmu_type && evsel->core.ids)
3971 			return evsel;
3972 	}
3973 
3974 	return NULL;
3975 }
3976 
3977 static int intel_pt_synth_events(struct intel_pt *pt,
3978 				 struct perf_session *session)
3979 {
3980 	struct evlist *evlist = session->evlist;
3981 	struct evsel *evsel = intel_pt_evsel(pt, evlist);
3982 	struct perf_event_attr attr;
3983 	u64 id;
3984 	int err;
3985 
3986 	if (!evsel) {
3987 		pr_debug("There are no selected events with Intel Processor Trace data\n");
3988 		return 0;
3989 	}
3990 
3991 	memset(&attr, 0, sizeof(struct perf_event_attr));
3992 	attr.size = sizeof(struct perf_event_attr);
3993 	attr.type = PERF_TYPE_HARDWARE;
3994 	attr.sample_type = evsel->core.attr.sample_type & PERF_SAMPLE_MASK;
3995 	attr.sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID |
3996 			    PERF_SAMPLE_PERIOD;
3997 	if (pt->timeless_decoding)
3998 		attr.sample_type &= ~(u64)PERF_SAMPLE_TIME;
3999 	else
4000 		attr.sample_type |= PERF_SAMPLE_TIME;
4001 	if (!pt->per_cpu_mmaps)
4002 		attr.sample_type &= ~(u64)PERF_SAMPLE_CPU;
4003 	attr.exclude_user = evsel->core.attr.exclude_user;
4004 	attr.exclude_kernel = evsel->core.attr.exclude_kernel;
4005 	attr.exclude_hv = evsel->core.attr.exclude_hv;
4006 	attr.exclude_host = evsel->core.attr.exclude_host;
4007 	attr.exclude_guest = evsel->core.attr.exclude_guest;
4008 	attr.sample_id_all = evsel->core.attr.sample_id_all;
4009 	attr.read_format = evsel->core.attr.read_format;
4010 
4011 	id = auxtrace_synth_id_range_start(evsel);
4012 
4013 	if (pt->synth_opts.branches) {
4014 		attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
4015 		attr.sample_period = 1;
4016 		attr.sample_type |= PERF_SAMPLE_ADDR;
4017 		err = intel_pt_synth_event(session, "branches", &attr, id);
4018 		if (err)
4019 			return err;
4020 		pt->sample_branches = true;
4021 		pt->branches_sample_type = attr.sample_type;
4022 		pt->branches_id = id;
4023 		id += 1;
4024 		attr.sample_type &= ~(u64)PERF_SAMPLE_ADDR;
4025 	}
4026 
4027 	if (pt->synth_opts.callchain)
4028 		attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
4029 	if (pt->synth_opts.last_branch) {
4030 		attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
4031 		/*
4032 		 * We don't use the hardware index, but the sample generation
4033 		 * code uses the new format branch_stack with this field,
4034 		 * so the event attributes must indicate that it's present.
4035 		 */
4036 		attr.branch_sample_type |= PERF_SAMPLE_BRANCH_HW_INDEX;
4037 	}
4038 
4039 	if (pt->synth_opts.instructions) {
4040 		attr.config = PERF_COUNT_HW_INSTRUCTIONS;
4041 		if (pt->synth_opts.period_type == PERF_ITRACE_PERIOD_NANOSECS)
4042 			attr.sample_period =
4043 				intel_pt_ns_to_ticks(pt, pt->synth_opts.period);
4044 		else
4045 			attr.sample_period = pt->synth_opts.period;
4046 		err = intel_pt_synth_event(session, "instructions", &attr, id);
4047 		if (err)
4048 			return err;
4049 		pt->sample_instructions = true;
4050 		pt->instructions_sample_type = attr.sample_type;
4051 		pt->instructions_id = id;
4052 		id += 1;
4053 	}
4054 
4055 	if (pt->synth_opts.cycles) {
4056 		attr.config = PERF_COUNT_HW_CPU_CYCLES;
4057 		if (pt->synth_opts.period_type == PERF_ITRACE_PERIOD_NANOSECS)
4058 			attr.sample_period =
4059 				intel_pt_ns_to_ticks(pt, pt->synth_opts.period);
4060 		else
4061 			attr.sample_period = pt->synth_opts.period;
4062 		err = intel_pt_synth_event(session, "cycles", &attr, id);
4063 		if (err)
4064 			return err;
4065 		pt->sample_cycles = true;
4066 		pt->cycles_sample_type = attr.sample_type;
4067 		pt->cycles_id = id;
4068 		id += 1;
4069 	}
4070 
4071 	attr.sample_type &= ~(u64)PERF_SAMPLE_PERIOD;
4072 	attr.sample_period = 1;
4073 
4074 	if (pt->synth_opts.transactions) {
4075 		attr.config = PERF_COUNT_HW_INSTRUCTIONS;
4076 		err = intel_pt_synth_event(session, "transactions", &attr, id);
4077 		if (err)
4078 			return err;
4079 		pt->sample_transactions = true;
4080 		pt->transactions_sample_type = attr.sample_type;
4081 		pt->transactions_id = id;
4082 		intel_pt_set_event_name(evlist, id, "transactions");
4083 		id += 1;
4084 	}
4085 
4086 	attr.type = PERF_TYPE_SYNTH;
4087 	attr.sample_type |= PERF_SAMPLE_RAW;
4088 
4089 	if (pt->synth_opts.ptwrites) {
4090 		attr.config = PERF_SYNTH_INTEL_PTWRITE;
4091 		err = intel_pt_synth_event(session, "ptwrite", &attr, id);
4092 		if (err)
4093 			return err;
4094 		pt->sample_ptwrites = true;
4095 		pt->ptwrites_sample_type = attr.sample_type;
4096 		pt->ptwrites_id = id;
4097 		intel_pt_set_event_name(evlist, id, "ptwrite");
4098 		id += 1;
4099 	}
4100 
4101 	if (pt->synth_opts.pwr_events) {
4102 		pt->sample_pwr_events = true;
4103 		pt->pwr_events_sample_type = attr.sample_type;
4104 
4105 		attr.config = PERF_SYNTH_INTEL_CBR;
4106 		err = intel_pt_synth_event(session, "cbr", &attr, id);
4107 		if (err)
4108 			return err;
4109 		pt->cbr_id = id;
4110 		intel_pt_set_event_name(evlist, id, "cbr");
4111 		id += 1;
4112 
4113 		attr.config = PERF_SYNTH_INTEL_PSB;
4114 		err = intel_pt_synth_event(session, "psb", &attr, id);
4115 		if (err)
4116 			return err;
4117 		pt->psb_id = id;
4118 		intel_pt_set_event_name(evlist, id, "psb");
4119 		id += 1;
4120 	}
4121 
4122 	if (pt->synth_opts.pwr_events && (evsel->core.attr.config & INTEL_PT_CFG_PWR_EVT_EN)) {
4123 		attr.config = PERF_SYNTH_INTEL_MWAIT;
4124 		err = intel_pt_synth_event(session, "mwait", &attr, id);
4125 		if (err)
4126 			return err;
4127 		pt->mwait_id = id;
4128 		intel_pt_set_event_name(evlist, id, "mwait");
4129 		id += 1;
4130 
4131 		attr.config = PERF_SYNTH_INTEL_PWRE;
4132 		err = intel_pt_synth_event(session, "pwre", &attr, id);
4133 		if (err)
4134 			return err;
4135 		pt->pwre_id = id;
4136 		intel_pt_set_event_name(evlist, id, "pwre");
4137 		id += 1;
4138 
4139 		attr.config = PERF_SYNTH_INTEL_EXSTOP;
4140 		err = intel_pt_synth_event(session, "exstop", &attr, id);
4141 		if (err)
4142 			return err;
4143 		pt->exstop_id = id;
4144 		intel_pt_set_event_name(evlist, id, "exstop");
4145 		id += 1;
4146 
4147 		attr.config = PERF_SYNTH_INTEL_PWRX;
4148 		err = intel_pt_synth_event(session, "pwrx", &attr, id);
4149 		if (err)
4150 			return err;
4151 		pt->pwrx_id = id;
4152 		intel_pt_set_event_name(evlist, id, "pwrx");
4153 		id += 1;
4154 	}
4155 
4156 	if (pt->synth_opts.intr_events && (evsel->core.attr.config & INTEL_PT_CFG_EVT_EN)) {
4157 		attr.config = PERF_SYNTH_INTEL_EVT;
4158 		err = intel_pt_synth_event(session, "evt", &attr, id);
4159 		if (err)
4160 			return err;
4161 		pt->evt_sample_type = attr.sample_type;
4162 		pt->evt_id = id;
4163 		intel_pt_set_event_name(evlist, id, "evt");
4164 		id += 1;
4165 	}
4166 
4167 	if (pt->synth_opts.intr_events && pt->cap_event_trace) {
4168 		attr.config = PERF_SYNTH_INTEL_IFLAG_CHG;
4169 		err = intel_pt_synth_event(session, "iflag", &attr, id);
4170 		if (err)
4171 			return err;
4172 		pt->iflag_chg_sample_type = attr.sample_type;
4173 		pt->iflag_chg_id = id;
4174 		intel_pt_set_event_name(evlist, id, "iflag");
4175 		id += 1;
4176 	}
4177 
4178 	return 0;
4179 }
4180 
4181 static void intel_pt_setup_pebs_events(struct intel_pt *pt)
4182 {
4183 	struct evsel *evsel;
4184 
4185 	if (!pt->synth_opts.other_events)
4186 		return;
4187 
4188 	evlist__for_each_entry(pt->session->evlist, evsel) {
4189 		if (evsel->core.attr.aux_output && evsel->core.id) {
4190 			if (pt->single_pebs) {
4191 				pt->single_pebs = false;
4192 				return;
4193 			}
4194 			pt->single_pebs = true;
4195 			pt->sample_pebs = true;
4196 			pt->pebs_data_src_fmt = intel_pt_data_src_fmt(pt, evsel);
4197 			pt->pebs_evsel = evsel;
4198 		}
4199 	}
4200 }
4201 
4202 static struct evsel *intel_pt_find_sched_switch(struct evlist *evlist)
4203 {
4204 	struct evsel *evsel;
4205 
4206 	evlist__for_each_entry_reverse(evlist, evsel) {
4207 		const char *name = evsel__name(evsel);
4208 
4209 		if (!strcmp(name, "sched:sched_switch"))
4210 			return evsel;
4211 	}
4212 
4213 	return NULL;
4214 }
4215 
4216 static bool intel_pt_find_switch(struct evlist *evlist)
4217 {
4218 	struct evsel *evsel;
4219 
4220 	evlist__for_each_entry(evlist, evsel) {
4221 		if (evsel->core.attr.context_switch)
4222 			return true;
4223 	}
4224 
4225 	return false;
4226 }
4227 
4228 static int intel_pt_perf_config(const char *var, const char *value, void *data)
4229 {
4230 	struct intel_pt *pt = data;
4231 
4232 	if (!strcmp(var, "intel-pt.mispred-all"))
4233 		pt->mispred_all = perf_config_bool(var, value);
4234 
4235 	if (!strcmp(var, "intel-pt.max-loops"))
4236 		perf_config_int(&pt->max_loops, var, value);
4237 
4238 	return 0;
4239 }
4240 
4241 /* Find least TSC which converts to ns or later */
4242 static u64 intel_pt_tsc_start(u64 ns, struct intel_pt *pt)
4243 {
4244 	u64 tsc, tm;
4245 
4246 	tsc = perf_time_to_tsc(ns, &pt->tc);
4247 
4248 	while (1) {
4249 		tm = tsc_to_perf_time(tsc, &pt->tc);
4250 		if (tm < ns)
4251 			break;
4252 		tsc -= 1;
4253 	}
4254 
4255 	while (tm < ns)
4256 		tm = tsc_to_perf_time(++tsc, &pt->tc);
4257 
4258 	return tsc;
4259 }
4260 
4261 /* Find greatest TSC which converts to ns or earlier */
4262 static u64 intel_pt_tsc_end(u64 ns, struct intel_pt *pt)
4263 {
4264 	u64 tsc, tm;
4265 
4266 	tsc = perf_time_to_tsc(ns, &pt->tc);
4267 
4268 	while (1) {
4269 		tm = tsc_to_perf_time(tsc, &pt->tc);
4270 		if (tm > ns)
4271 			break;
4272 		tsc += 1;
4273 	}
4274 
4275 	while (tm > ns)
4276 		tm = tsc_to_perf_time(--tsc, &pt->tc);
4277 
4278 	return tsc;
4279 }
4280 
4281 static int intel_pt_setup_time_ranges(struct intel_pt *pt,
4282 				      struct itrace_synth_opts *opts)
4283 {
4284 	struct perf_time_interval *p = opts->ptime_range;
4285 	int n = opts->range_num;
4286 	int i;
4287 
4288 	if (!n || !p || pt->timeless_decoding)
4289 		return 0;
4290 
4291 	pt->time_ranges = calloc(n, sizeof(struct range));
4292 	if (!pt->time_ranges)
4293 		return -ENOMEM;
4294 
4295 	pt->range_cnt = n;
4296 
4297 	intel_pt_log("%s: %u range(s)\n", __func__, n);
4298 
4299 	for (i = 0; i < n; i++) {
4300 		struct range *r = &pt->time_ranges[i];
4301 		u64 ts = p[i].start;
4302 		u64 te = p[i].end;
4303 
4304 		/*
4305 		 * Take care to ensure the TSC range matches the perf-time range
4306 		 * when converted back to perf-time.
4307 		 */
4308 		r->start = ts ? intel_pt_tsc_start(ts, pt) : 0;
4309 		r->end   = te ? intel_pt_tsc_end(te, pt) : 0;
4310 
4311 		intel_pt_log("range %d: perf time interval: %"PRIu64" to %"PRIu64"\n",
4312 			     i, ts, te);
4313 		intel_pt_log("range %d: TSC time interval: %#"PRIx64" to %#"PRIx64"\n",
4314 			     i, r->start, r->end);
4315 	}
4316 
4317 	return 0;
4318 }
4319 
4320 static int intel_pt_parse_vm_tm_corr_arg(struct intel_pt *pt, char **args)
4321 {
4322 	struct intel_pt_vmcs_info *vmcs_info;
4323 	u64 tsc_offset, vmcs;
4324 	char *p = *args;
4325 
4326 	errno = 0;
4327 
4328 	p = skip_spaces(p);
4329 	if (!*p)
4330 		return 1;
4331 
4332 	tsc_offset = strtoull(p, &p, 0);
4333 	if (errno)
4334 		return -errno;
4335 	p = skip_spaces(p);
4336 	if (*p != ':') {
4337 		pt->dflt_tsc_offset = tsc_offset;
4338 		*args = p;
4339 		return 0;
4340 	}
4341 	p += 1;
4342 	while (1) {
4343 		vmcs = strtoull(p, &p, 0);
4344 		if (errno)
4345 			return -errno;
4346 		if (!vmcs)
4347 			return -EINVAL;
4348 		vmcs_info = intel_pt_findnew_vmcs(&pt->vmcs_info, vmcs, tsc_offset);
4349 		if (!vmcs_info)
4350 			return -ENOMEM;
4351 		p = skip_spaces(p);
4352 		if (*p != ',')
4353 			break;
4354 		p += 1;
4355 	}
4356 	*args = p;
4357 	return 0;
4358 }
4359 
4360 static int intel_pt_parse_vm_tm_corr_args(struct intel_pt *pt)
4361 {
4362 	char *args = pt->synth_opts.vm_tm_corr_args;
4363 	int ret;
4364 
4365 	if (!args)
4366 		return 0;
4367 
4368 	do {
4369 		ret = intel_pt_parse_vm_tm_corr_arg(pt, &args);
4370 	} while (!ret);
4371 
4372 	if (ret < 0) {
4373 		pr_err("Failed to parse VM Time Correlation options\n");
4374 		return ret;
4375 	}
4376 
4377 	return 0;
4378 }
4379 
4380 static const char * const intel_pt_info_fmts[] = {
4381 	[INTEL_PT_PMU_TYPE]		= "  PMU Type            %"PRId64"\n",
4382 	[INTEL_PT_TIME_SHIFT]		= "  Time Shift          %"PRIu64"\n",
4383 	[INTEL_PT_TIME_MULT]		= "  Time Multiplier     %"PRIu64"\n",
4384 	[INTEL_PT_TIME_ZERO]		= "  Time Zero           %"PRIu64"\n",
4385 	[INTEL_PT_CAP_USER_TIME_ZERO]	= "  Cap Time Zero       %"PRId64"\n",
4386 	[INTEL_PT_TSC_BIT]		= "  TSC bit             %#"PRIx64"\n",
4387 	[INTEL_PT_NORETCOMP_BIT]	= "  NoRETComp bit       %#"PRIx64"\n",
4388 	[INTEL_PT_HAVE_SCHED_SWITCH]	= "  Have sched_switch   %"PRId64"\n",
4389 	[INTEL_PT_SNAPSHOT_MODE]	= "  Snapshot mode       %"PRId64"\n",
4390 	[INTEL_PT_PER_CPU_MMAPS]	= "  Per-cpu maps        %"PRId64"\n",
4391 	[INTEL_PT_MTC_BIT]		= "  MTC bit             %#"PRIx64"\n",
4392 	[INTEL_PT_MTC_FREQ_BITS]	= "  MTC freq bits       %#"PRIx64"\n",
4393 	[INTEL_PT_TSC_CTC_N]		= "  TSC:CTC numerator   %"PRIu64"\n",
4394 	[INTEL_PT_TSC_CTC_D]		= "  TSC:CTC denominator %"PRIu64"\n",
4395 	[INTEL_PT_CYC_BIT]		= "  CYC bit             %#"PRIx64"\n",
4396 	[INTEL_PT_MAX_NONTURBO_RATIO]	= "  Max non-turbo ratio %"PRIu64"\n",
4397 	[INTEL_PT_FILTER_STR_LEN]	= "  Filter string len.  %"PRIu64"\n",
4398 };
4399 
4400 static void intel_pt_print_info(__u64 *arr, int start, int finish)
4401 {
4402 	int i;
4403 
4404 	if (!dump_trace)
4405 		return;
4406 
4407 	for (i = start; i <= finish; i++) {
4408 		const char *fmt = intel_pt_info_fmts[i];
4409 
4410 		if (fmt)
4411 			fprintf(stdout, fmt, arr[i]);
4412 	}
4413 }
4414 
4415 static void intel_pt_print_info_str(const char *name, const char *str)
4416 {
4417 	if (!dump_trace)
4418 		return;
4419 
4420 	fprintf(stdout, "  %-20s%s\n", name, str ? str : "");
4421 }
4422 
4423 static bool intel_pt_has(struct perf_record_auxtrace_info *auxtrace_info, int pos)
4424 {
4425 	return auxtrace_info->header.size >=
4426 		sizeof(struct perf_record_auxtrace_info) + (sizeof(u64) * (pos + 1));
4427 }
4428 
4429 int intel_pt_process_auxtrace_info(union perf_event *event,
4430 				   struct perf_session *session)
4431 {
4432 	struct perf_record_auxtrace_info *auxtrace_info = &event->auxtrace_info;
4433 	size_t min_sz = sizeof(u64) * INTEL_PT_PER_CPU_MMAPS;
4434 	struct intel_pt *pt;
4435 	void *info_end;
4436 	__u64 *info;
4437 	int err;
4438 
4439 	if (auxtrace_info->header.size < sizeof(struct perf_record_auxtrace_info) +
4440 					min_sz)
4441 		return -EINVAL;
4442 
4443 	pt = zalloc(sizeof(struct intel_pt));
4444 	if (!pt)
4445 		return -ENOMEM;
4446 
4447 	pt->vmcs_info = RB_ROOT;
4448 
4449 	addr_filters__init(&pt->filts);
4450 
4451 	err = perf_config(intel_pt_perf_config, pt);
4452 	if (err)
4453 		goto err_free;
4454 
4455 	err = auxtrace_queues__init(&pt->queues);
4456 	if (err)
4457 		goto err_free;
4458 
4459 	if (session->itrace_synth_opts->set) {
4460 		pt->synth_opts = *session->itrace_synth_opts;
4461 	} else {
4462 		struct itrace_synth_opts *opts = session->itrace_synth_opts;
4463 
4464 		itrace_synth_opts__set_default(&pt->synth_opts, opts->default_no_sample);
4465 		if (!opts->default_no_sample && !opts->inject) {
4466 			pt->synth_opts.branches = false;
4467 			pt->synth_opts.callchain = true;
4468 			pt->synth_opts.add_callchain = true;
4469 		}
4470 		pt->synth_opts.thread_stack = opts->thread_stack;
4471 	}
4472 
4473 	if (!(pt->synth_opts.log_plus_flags & AUXTRACE_LOG_FLG_USE_STDOUT))
4474 		intel_pt_log_set_name(INTEL_PT_PMU_NAME);
4475 
4476 	pt->session = session;
4477 	pt->machine = &session->machines.host; /* No kvm support */
4478 	pt->auxtrace_type = auxtrace_info->type;
4479 	pt->pmu_type = auxtrace_info->priv[INTEL_PT_PMU_TYPE];
4480 	pt->tc.time_shift = auxtrace_info->priv[INTEL_PT_TIME_SHIFT];
4481 	pt->tc.time_mult = auxtrace_info->priv[INTEL_PT_TIME_MULT];
4482 	pt->tc.time_zero = auxtrace_info->priv[INTEL_PT_TIME_ZERO];
4483 	pt->cap_user_time_zero = auxtrace_info->priv[INTEL_PT_CAP_USER_TIME_ZERO];
4484 	pt->tsc_bit = auxtrace_info->priv[INTEL_PT_TSC_BIT];
4485 	pt->noretcomp_bit = auxtrace_info->priv[INTEL_PT_NORETCOMP_BIT];
4486 	pt->have_sched_switch = auxtrace_info->priv[INTEL_PT_HAVE_SCHED_SWITCH];
4487 	pt->snapshot_mode = auxtrace_info->priv[INTEL_PT_SNAPSHOT_MODE];
4488 	pt->per_cpu_mmaps = auxtrace_info->priv[INTEL_PT_PER_CPU_MMAPS];
4489 	intel_pt_print_info(&auxtrace_info->priv[0], INTEL_PT_PMU_TYPE,
4490 			    INTEL_PT_PER_CPU_MMAPS);
4491 
4492 	if (intel_pt_has(auxtrace_info, INTEL_PT_CYC_BIT)) {
4493 		pt->mtc_bit = auxtrace_info->priv[INTEL_PT_MTC_BIT];
4494 		pt->mtc_freq_bits = auxtrace_info->priv[INTEL_PT_MTC_FREQ_BITS];
4495 		pt->tsc_ctc_ratio_n = auxtrace_info->priv[INTEL_PT_TSC_CTC_N];
4496 		pt->tsc_ctc_ratio_d = auxtrace_info->priv[INTEL_PT_TSC_CTC_D];
4497 		pt->cyc_bit = auxtrace_info->priv[INTEL_PT_CYC_BIT];
4498 		intel_pt_print_info(&auxtrace_info->priv[0], INTEL_PT_MTC_BIT,
4499 				    INTEL_PT_CYC_BIT);
4500 	}
4501 
4502 	if (intel_pt_has(auxtrace_info, INTEL_PT_MAX_NONTURBO_RATIO)) {
4503 		pt->max_non_turbo_ratio =
4504 			auxtrace_info->priv[INTEL_PT_MAX_NONTURBO_RATIO];
4505 		intel_pt_print_info(&auxtrace_info->priv[0],
4506 				    INTEL_PT_MAX_NONTURBO_RATIO,
4507 				    INTEL_PT_MAX_NONTURBO_RATIO);
4508 	}
4509 
4510 	info = &auxtrace_info->priv[INTEL_PT_FILTER_STR_LEN] + 1;
4511 	info_end = (void *)auxtrace_info + auxtrace_info->header.size;
4512 
4513 	if (intel_pt_has(auxtrace_info, INTEL_PT_FILTER_STR_LEN)) {
4514 		size_t len;
4515 
4516 		len = auxtrace_info->priv[INTEL_PT_FILTER_STR_LEN];
4517 		intel_pt_print_info(&auxtrace_info->priv[0],
4518 				    INTEL_PT_FILTER_STR_LEN,
4519 				    INTEL_PT_FILTER_STR_LEN);
4520 		if (len) {
4521 			const char *filter = (const char *)info;
4522 
4523 			len = roundup(len + 1, 8);
4524 			info += len >> 3;
4525 			if ((void *)info > info_end) {
4526 				pr_err("%s: bad filter string length\n", __func__);
4527 				err = -EINVAL;
4528 				goto err_free_queues;
4529 			}
4530 			pt->filter = memdup(filter, len);
4531 			if (!pt->filter) {
4532 				err = -ENOMEM;
4533 				goto err_free_queues;
4534 			}
4535 			if (session->header.needs_swap)
4536 				mem_bswap_64(pt->filter, len);
4537 			if (pt->filter[len - 1]) {
4538 				pr_err("%s: filter string not null terminated\n", __func__);
4539 				err = -EINVAL;
4540 				goto err_free_queues;
4541 			}
4542 			err = addr_filters__parse_bare_filter(&pt->filts,
4543 							      filter);
4544 			if (err)
4545 				goto err_free_queues;
4546 		}
4547 		intel_pt_print_info_str("Filter string", pt->filter);
4548 	}
4549 
4550 	if ((void *)info < info_end) {
4551 		pt->cap_event_trace = *info++;
4552 		if (dump_trace)
4553 			fprintf(stdout, "  Cap Event Trace     %d\n",
4554 				pt->cap_event_trace);
4555 	}
4556 
4557 	pt->timeless_decoding = intel_pt_timeless_decoding(pt);
4558 	if (pt->timeless_decoding && !pt->tc.time_mult)
4559 		pt->tc.time_mult = 1;
4560 	pt->have_tsc = intel_pt_have_tsc(pt);
4561 	pt->sampling_mode = intel_pt_sampling_mode(pt);
4562 	pt->est_tsc = !pt->timeless_decoding;
4563 
4564 	if (pt->synth_opts.vm_time_correlation) {
4565 		if (pt->timeless_decoding) {
4566 			pr_err("Intel PT has no time information for VM Time Correlation\n");
4567 			err = -EINVAL;
4568 			goto err_free_queues;
4569 		}
4570 		if (session->itrace_synth_opts->ptime_range) {
4571 			pr_err("Time ranges cannot be specified with VM Time Correlation\n");
4572 			err = -EINVAL;
4573 			goto err_free_queues;
4574 		}
4575 		/* Currently TSC Offset is calculated using MTC packets */
4576 		if (!intel_pt_have_mtc(pt)) {
4577 			pr_err("MTC packets must have been enabled for VM Time Correlation\n");
4578 			err = -EINVAL;
4579 			goto err_free_queues;
4580 		}
4581 		err = intel_pt_parse_vm_tm_corr_args(pt);
4582 		if (err)
4583 			goto err_free_queues;
4584 	}
4585 
4586 	pt->unknown_thread = thread__new(999999999, 999999999);
4587 	if (!pt->unknown_thread) {
4588 		err = -ENOMEM;
4589 		goto err_free_queues;
4590 	}
4591 
4592 	err = thread__set_comm(pt->unknown_thread, "unknown", 0);
4593 	if (err)
4594 		goto err_delete_thread;
4595 	if (thread__init_maps(pt->unknown_thread, pt->machine)) {
4596 		err = -ENOMEM;
4597 		goto err_delete_thread;
4598 	}
4599 
4600 	pt->auxtrace.process_event = intel_pt_process_event;
4601 	pt->auxtrace.process_auxtrace_event = intel_pt_process_auxtrace_event;
4602 	pt->auxtrace.queue_data = intel_pt_queue_data;
4603 	pt->auxtrace.dump_auxtrace_sample = intel_pt_dump_sample;
4604 	pt->auxtrace.flush_events = intel_pt_flush;
4605 	pt->auxtrace.free_events = intel_pt_free_events;
4606 	pt->auxtrace.free = intel_pt_free;
4607 	pt->auxtrace.evsel_is_auxtrace = intel_pt_evsel_is_auxtrace;
4608 	session->auxtrace = &pt->auxtrace;
4609 
4610 	if (dump_trace)
4611 		return 0;
4612 
4613 	if (pt->have_sched_switch == 1) {
4614 		pt->switch_evsel = intel_pt_find_sched_switch(session->evlist);
4615 		if (!pt->switch_evsel) {
4616 			pr_err("%s: missing sched_switch event\n", __func__);
4617 			err = -EINVAL;
4618 			goto err_delete_thread;
4619 		}
4620 	} else if (pt->have_sched_switch == 2 &&
4621 		   !intel_pt_find_switch(session->evlist)) {
4622 		pr_err("%s: missing context_switch attribute flag\n", __func__);
4623 		err = -EINVAL;
4624 		goto err_delete_thread;
4625 	}
4626 
4627 	if (pt->synth_opts.log) {
4628 		bool log_on_error = pt->synth_opts.log_plus_flags & AUXTRACE_LOG_FLG_ON_ERROR;
4629 		unsigned int log_on_error_size = pt->synth_opts.log_on_error_size;
4630 
4631 		intel_pt_log_enable(log_on_error, log_on_error_size);
4632 	}
4633 
4634 	/* Maximum non-turbo ratio is TSC freq / 100 MHz */
4635 	if (pt->tc.time_mult) {
4636 		u64 tsc_freq = intel_pt_ns_to_ticks(pt, 1000000000);
4637 
4638 		if (!pt->max_non_turbo_ratio)
4639 			pt->max_non_turbo_ratio =
4640 					(tsc_freq + 50000000) / 100000000;
4641 		intel_pt_log("TSC frequency %"PRIu64"\n", tsc_freq);
4642 		intel_pt_log("Maximum non-turbo ratio %u\n",
4643 			     pt->max_non_turbo_ratio);
4644 		pt->cbr2khz = tsc_freq / pt->max_non_turbo_ratio / 1000;
4645 	}
4646 
4647 	err = intel_pt_setup_time_ranges(pt, session->itrace_synth_opts);
4648 	if (err)
4649 		goto err_delete_thread;
4650 
4651 	if (pt->synth_opts.calls)
4652 		pt->branches_filter |= PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC |
4653 				       PERF_IP_FLAG_TRACE_END;
4654 	if (pt->synth_opts.returns)
4655 		pt->branches_filter |= PERF_IP_FLAG_RETURN |
4656 				       PERF_IP_FLAG_TRACE_BEGIN;
4657 
4658 	if ((pt->synth_opts.callchain || pt->synth_opts.add_callchain) &&
4659 	    !symbol_conf.use_callchain) {
4660 		symbol_conf.use_callchain = true;
4661 		if (callchain_register_param(&callchain_param) < 0) {
4662 			symbol_conf.use_callchain = false;
4663 			pt->synth_opts.callchain = false;
4664 			pt->synth_opts.add_callchain = false;
4665 		}
4666 	}
4667 
4668 	if (pt->synth_opts.add_callchain) {
4669 		err = intel_pt_callchain_init(pt);
4670 		if (err)
4671 			goto err_delete_thread;
4672 	}
4673 
4674 	if (pt->synth_opts.last_branch || pt->synth_opts.add_last_branch) {
4675 		pt->br_stack_sz = pt->synth_opts.last_branch_sz;
4676 		pt->br_stack_sz_plus = pt->br_stack_sz;
4677 	}
4678 
4679 	if (pt->synth_opts.add_last_branch) {
4680 		err = intel_pt_br_stack_init(pt);
4681 		if (err)
4682 			goto err_delete_thread;
4683 		/*
4684 		 * Additional branch stack size to cater for tracing from the
4685 		 * actual sample ip to where the sample time is recorded.
4686 		 * Measured at about 200 branches, but generously set to 1024.
4687 		 * If kernel space is not being traced, then add just 1 for the
4688 		 * branch to kernel space.
4689 		 */
4690 		if (intel_pt_tracing_kernel(pt))
4691 			pt->br_stack_sz_plus += 1024;
4692 		else
4693 			pt->br_stack_sz_plus += 1;
4694 	}
4695 
4696 	pt->use_thread_stack = pt->synth_opts.callchain ||
4697 			       pt->synth_opts.add_callchain ||
4698 			       pt->synth_opts.thread_stack ||
4699 			       pt->synth_opts.last_branch ||
4700 			       pt->synth_opts.add_last_branch;
4701 
4702 	pt->callstack = pt->synth_opts.callchain ||
4703 			pt->synth_opts.add_callchain ||
4704 			pt->synth_opts.thread_stack;
4705 
4706 	err = intel_pt_synth_events(pt, session);
4707 	if (err)
4708 		goto err_delete_thread;
4709 
4710 	intel_pt_setup_pebs_events(pt);
4711 
4712 	if (perf_data__is_pipe(session->data)) {
4713 		pr_warning("WARNING: Intel PT with pipe mode is not recommended.\n"
4714 			   "         The output cannot relied upon.  In particular,\n"
4715 			   "         timestamps and the order of events may be incorrect.\n");
4716 	}
4717 
4718 	if (pt->sampling_mode || list_empty(&session->auxtrace_index))
4719 		err = auxtrace_queue_data(session, true, true);
4720 	else
4721 		err = auxtrace_queues__process_index(&pt->queues, session);
4722 	if (err)
4723 		goto err_delete_thread;
4724 
4725 	if (pt->queues.populated)
4726 		pt->data_queued = true;
4727 
4728 	if (pt->timeless_decoding)
4729 		pr_debug2("Intel PT decoding without timestamps\n");
4730 
4731 	return 0;
4732 
4733 err_delete_thread:
4734 	zfree(&pt->chain);
4735 	thread__zput(pt->unknown_thread);
4736 err_free_queues:
4737 	intel_pt_log_disable();
4738 	auxtrace_queues__free(&pt->queues);
4739 	session->auxtrace = NULL;
4740 err_free:
4741 	addr_filters__exit(&pt->filts);
4742 	zfree(&pt->filter);
4743 	zfree(&pt->time_ranges);
4744 	free(pt);
4745 	return err;
4746 }
4747