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