xref: /openbmc/linux/tools/perf/util/intel-pt.c (revision 337cbeb2)
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 <stdio.h>
9 #include <stdbool.h>
10 #include <errno.h>
11 #include <linux/kernel.h>
12 #include <linux/string.h>
13 #include <linux/types.h>
14 #include <linux/zalloc.h>
15 
16 #include "session.h"
17 #include "machine.h"
18 #include "memswap.h"
19 #include "sort.h"
20 #include "tool.h"
21 #include "event.h"
22 #include "evlist.h"
23 #include "evsel.h"
24 #include "map.h"
25 #include "color.h"
26 #include "thread.h"
27 #include "thread-stack.h"
28 #include "symbol.h"
29 #include "callchain.h"
30 #include "dso.h"
31 #include "debug.h"
32 #include "auxtrace.h"
33 #include "tsc.h"
34 #include "intel-pt.h"
35 #include "config.h"
36 #include "util/synthetic-events.h"
37 #include "time-utils.h"
38 
39 #include "../arch/x86/include/uapi/asm/perf_regs.h"
40 
41 #include "intel-pt-decoder/intel-pt-log.h"
42 #include "intel-pt-decoder/intel-pt-decoder.h"
43 #include "intel-pt-decoder/intel-pt-insn-decoder.h"
44 #include "intel-pt-decoder/intel-pt-pkt-decoder.h"
45 
46 #define MAX_TIMESTAMP (~0ULL)
47 
48 struct range {
49 	u64 start;
50 	u64 end;
51 };
52 
53 struct intel_pt {
54 	struct auxtrace auxtrace;
55 	struct auxtrace_queues queues;
56 	struct auxtrace_heap heap;
57 	u32 auxtrace_type;
58 	struct perf_session *session;
59 	struct machine *machine;
60 	struct evsel *switch_evsel;
61 	struct thread *unknown_thread;
62 	bool timeless_decoding;
63 	bool sampling_mode;
64 	bool snapshot_mode;
65 	bool per_cpu_mmaps;
66 	bool have_tsc;
67 	bool data_queued;
68 	bool est_tsc;
69 	bool sync_switch;
70 	bool mispred_all;
71 	int have_sched_switch;
72 	u32 pmu_type;
73 	u64 kernel_start;
74 	u64 switch_ip;
75 	u64 ptss_ip;
76 
77 	struct perf_tsc_conversion tc;
78 	bool cap_user_time_zero;
79 
80 	struct itrace_synth_opts synth_opts;
81 
82 	bool sample_instructions;
83 	u64 instructions_sample_type;
84 	u64 instructions_id;
85 
86 	bool sample_branches;
87 	u32 branches_filter;
88 	u64 branches_sample_type;
89 	u64 branches_id;
90 
91 	bool sample_transactions;
92 	u64 transactions_sample_type;
93 	u64 transactions_id;
94 
95 	bool sample_ptwrites;
96 	u64 ptwrites_sample_type;
97 	u64 ptwrites_id;
98 
99 	bool sample_pwr_events;
100 	u64 pwr_events_sample_type;
101 	u64 mwait_id;
102 	u64 pwre_id;
103 	u64 exstop_id;
104 	u64 pwrx_id;
105 	u64 cbr_id;
106 
107 	bool sample_pebs;
108 	struct evsel *pebs_evsel;
109 
110 	u64 tsc_bit;
111 	u64 mtc_bit;
112 	u64 mtc_freq_bits;
113 	u32 tsc_ctc_ratio_n;
114 	u32 tsc_ctc_ratio_d;
115 	u64 cyc_bit;
116 	u64 noretcomp_bit;
117 	unsigned max_non_turbo_ratio;
118 	unsigned cbr2khz;
119 
120 	unsigned long num_events;
121 
122 	char *filter;
123 	struct addr_filters filts;
124 
125 	struct range *time_ranges;
126 	unsigned int range_cnt;
127 };
128 
129 enum switch_state {
130 	INTEL_PT_SS_NOT_TRACING,
131 	INTEL_PT_SS_UNKNOWN,
132 	INTEL_PT_SS_TRACING,
133 	INTEL_PT_SS_EXPECTING_SWITCH_EVENT,
134 	INTEL_PT_SS_EXPECTING_SWITCH_IP,
135 };
136 
137 struct intel_pt_queue {
138 	struct intel_pt *pt;
139 	unsigned int queue_nr;
140 	struct auxtrace_buffer *buffer;
141 	struct auxtrace_buffer *old_buffer;
142 	void *decoder;
143 	const struct intel_pt_state *state;
144 	struct ip_callchain *chain;
145 	struct branch_stack *last_branch;
146 	struct branch_stack *last_branch_rb;
147 	size_t last_branch_pos;
148 	union perf_event *event_buf;
149 	bool on_heap;
150 	bool stop;
151 	bool step_through_buffers;
152 	bool use_buffer_pid_tid;
153 	bool sync_switch;
154 	pid_t pid, tid;
155 	int cpu;
156 	int switch_state;
157 	pid_t next_tid;
158 	struct thread *thread;
159 	bool exclude_kernel;
160 	bool have_sample;
161 	u64 time;
162 	u64 timestamp;
163 	u64 sel_timestamp;
164 	bool sel_start;
165 	unsigned int sel_idx;
166 	u32 flags;
167 	u16 insn_len;
168 	u64 last_insn_cnt;
169 	u64 ipc_insn_cnt;
170 	u64 ipc_cyc_cnt;
171 	u64 last_in_insn_cnt;
172 	u64 last_in_cyc_cnt;
173 	u64 last_br_insn_cnt;
174 	u64 last_br_cyc_cnt;
175 	unsigned int cbr_seen;
176 	char insn[INTEL_PT_INSN_BUF_SZ];
177 };
178 
179 static void intel_pt_dump(struct intel_pt *pt __maybe_unused,
180 			  unsigned char *buf, size_t len)
181 {
182 	struct intel_pt_pkt packet;
183 	size_t pos = 0;
184 	int ret, pkt_len, i;
185 	char desc[INTEL_PT_PKT_DESC_MAX];
186 	const char *color = PERF_COLOR_BLUE;
187 	enum intel_pt_pkt_ctx ctx = INTEL_PT_NO_CTX;
188 
189 	color_fprintf(stdout, color,
190 		      ". ... Intel Processor Trace data: size %zu bytes\n",
191 		      len);
192 
193 	while (len) {
194 		ret = intel_pt_get_packet(buf, len, &packet, &ctx);
195 		if (ret > 0)
196 			pkt_len = ret;
197 		else
198 			pkt_len = 1;
199 		printf(".");
200 		color_fprintf(stdout, color, "  %08x: ", pos);
201 		for (i = 0; i < pkt_len; i++)
202 			color_fprintf(stdout, color, " %02x", buf[i]);
203 		for (; i < 16; i++)
204 			color_fprintf(stdout, color, "   ");
205 		if (ret > 0) {
206 			ret = intel_pt_pkt_desc(&packet, desc,
207 						INTEL_PT_PKT_DESC_MAX);
208 			if (ret > 0)
209 				color_fprintf(stdout, color, " %s\n", desc);
210 		} else {
211 			color_fprintf(stdout, color, " Bad packet!\n");
212 		}
213 		pos += pkt_len;
214 		buf += pkt_len;
215 		len -= pkt_len;
216 	}
217 }
218 
219 static void intel_pt_dump_event(struct intel_pt *pt, unsigned char *buf,
220 				size_t len)
221 {
222 	printf(".\n");
223 	intel_pt_dump(pt, buf, len);
224 }
225 
226 static void intel_pt_log_event(union perf_event *event)
227 {
228 	FILE *f = intel_pt_log_fp();
229 
230 	if (!intel_pt_enable_logging || !f)
231 		return;
232 
233 	perf_event__fprintf(event, f);
234 }
235 
236 static void intel_pt_dump_sample(struct perf_session *session,
237 				 struct perf_sample *sample)
238 {
239 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
240 					   auxtrace);
241 
242 	printf("\n");
243 	intel_pt_dump(pt, sample->aux_sample.data, sample->aux_sample.size);
244 }
245 
246 static int intel_pt_do_fix_overlap(struct intel_pt *pt, struct auxtrace_buffer *a,
247 				   struct auxtrace_buffer *b)
248 {
249 	bool consecutive = false;
250 	void *start;
251 
252 	start = intel_pt_find_overlap(a->data, a->size, b->data, b->size,
253 				      pt->have_tsc, &consecutive);
254 	if (!start)
255 		return -EINVAL;
256 	b->use_size = b->data + b->size - start;
257 	b->use_data = start;
258 	if (b->use_size && consecutive)
259 		b->consecutive = true;
260 	return 0;
261 }
262 
263 static int intel_pt_get_buffer(struct intel_pt_queue *ptq,
264 			       struct auxtrace_buffer *buffer,
265 			       struct auxtrace_buffer *old_buffer,
266 			       struct intel_pt_buffer *b)
267 {
268 	bool might_overlap;
269 
270 	if (!buffer->data) {
271 		int fd = perf_data__fd(ptq->pt->session->data);
272 
273 		buffer->data = auxtrace_buffer__get_data(buffer, fd);
274 		if (!buffer->data)
275 			return -ENOMEM;
276 	}
277 
278 	might_overlap = ptq->pt->snapshot_mode || ptq->pt->sampling_mode;
279 	if (might_overlap && !buffer->consecutive && old_buffer &&
280 	    intel_pt_do_fix_overlap(ptq->pt, old_buffer, buffer))
281 		return -ENOMEM;
282 
283 	if (buffer->use_data) {
284 		b->len = buffer->use_size;
285 		b->buf = buffer->use_data;
286 	} else {
287 		b->len = buffer->size;
288 		b->buf = buffer->data;
289 	}
290 	b->ref_timestamp = buffer->reference;
291 
292 	if (!old_buffer || (might_overlap && !buffer->consecutive)) {
293 		b->consecutive = false;
294 		b->trace_nr = buffer->buffer_nr + 1;
295 	} else {
296 		b->consecutive = true;
297 	}
298 
299 	return 0;
300 }
301 
302 /* Do not drop buffers with references - refer intel_pt_get_trace() */
303 static void intel_pt_lookahead_drop_buffer(struct intel_pt_queue *ptq,
304 					   struct auxtrace_buffer *buffer)
305 {
306 	if (!buffer || buffer == ptq->buffer || buffer == ptq->old_buffer)
307 		return;
308 
309 	auxtrace_buffer__drop_data(buffer);
310 }
311 
312 /* Must be serialized with respect to intel_pt_get_trace() */
313 static int intel_pt_lookahead(void *data, intel_pt_lookahead_cb_t cb,
314 			      void *cb_data)
315 {
316 	struct intel_pt_queue *ptq = data;
317 	struct auxtrace_buffer *buffer = ptq->buffer;
318 	struct auxtrace_buffer *old_buffer = ptq->old_buffer;
319 	struct auxtrace_queue *queue;
320 	int err = 0;
321 
322 	queue = &ptq->pt->queues.queue_array[ptq->queue_nr];
323 
324 	while (1) {
325 		struct intel_pt_buffer b = { .len = 0 };
326 
327 		buffer = auxtrace_buffer__next(queue, buffer);
328 		if (!buffer)
329 			break;
330 
331 		err = intel_pt_get_buffer(ptq, buffer, old_buffer, &b);
332 		if (err)
333 			break;
334 
335 		if (b.len) {
336 			intel_pt_lookahead_drop_buffer(ptq, old_buffer);
337 			old_buffer = buffer;
338 		} else {
339 			intel_pt_lookahead_drop_buffer(ptq, buffer);
340 			continue;
341 		}
342 
343 		err = cb(&b, cb_data);
344 		if (err)
345 			break;
346 	}
347 
348 	if (buffer != old_buffer)
349 		intel_pt_lookahead_drop_buffer(ptq, buffer);
350 	intel_pt_lookahead_drop_buffer(ptq, old_buffer);
351 
352 	return err;
353 }
354 
355 /*
356  * This function assumes data is processed sequentially only.
357  * Must be serialized with respect to intel_pt_lookahead()
358  */
359 static int intel_pt_get_trace(struct intel_pt_buffer *b, void *data)
360 {
361 	struct intel_pt_queue *ptq = data;
362 	struct auxtrace_buffer *buffer = ptq->buffer;
363 	struct auxtrace_buffer *old_buffer = ptq->old_buffer;
364 	struct auxtrace_queue *queue;
365 	int err;
366 
367 	if (ptq->stop) {
368 		b->len = 0;
369 		return 0;
370 	}
371 
372 	queue = &ptq->pt->queues.queue_array[ptq->queue_nr];
373 
374 	buffer = auxtrace_buffer__next(queue, buffer);
375 	if (!buffer) {
376 		if (old_buffer)
377 			auxtrace_buffer__drop_data(old_buffer);
378 		b->len = 0;
379 		return 0;
380 	}
381 
382 	ptq->buffer = buffer;
383 
384 	err = intel_pt_get_buffer(ptq, buffer, old_buffer, b);
385 	if (err)
386 		return err;
387 
388 	if (ptq->step_through_buffers)
389 		ptq->stop = true;
390 
391 	if (b->len) {
392 		if (old_buffer)
393 			auxtrace_buffer__drop_data(old_buffer);
394 		ptq->old_buffer = buffer;
395 	} else {
396 		auxtrace_buffer__drop_data(buffer);
397 		return intel_pt_get_trace(b, data);
398 	}
399 
400 	return 0;
401 }
402 
403 struct intel_pt_cache_entry {
404 	struct auxtrace_cache_entry	entry;
405 	u64				insn_cnt;
406 	u64				byte_cnt;
407 	enum intel_pt_insn_op		op;
408 	enum intel_pt_insn_branch	branch;
409 	int				length;
410 	int32_t				rel;
411 	char				insn[INTEL_PT_INSN_BUF_SZ];
412 };
413 
414 static int intel_pt_config_div(const char *var, const char *value, void *data)
415 {
416 	int *d = data;
417 	long val;
418 
419 	if (!strcmp(var, "intel-pt.cache-divisor")) {
420 		val = strtol(value, NULL, 0);
421 		if (val > 0 && val <= INT_MAX)
422 			*d = val;
423 	}
424 
425 	return 0;
426 }
427 
428 static int intel_pt_cache_divisor(void)
429 {
430 	static int d;
431 
432 	if (d)
433 		return d;
434 
435 	perf_config(intel_pt_config_div, &d);
436 
437 	if (!d)
438 		d = 64;
439 
440 	return d;
441 }
442 
443 static unsigned int intel_pt_cache_size(struct dso *dso,
444 					struct machine *machine)
445 {
446 	off_t size;
447 
448 	size = dso__data_size(dso, machine);
449 	size /= intel_pt_cache_divisor();
450 	if (size < 1000)
451 		return 10;
452 	if (size > (1 << 21))
453 		return 21;
454 	return 32 - __builtin_clz(size);
455 }
456 
457 static struct auxtrace_cache *intel_pt_cache(struct dso *dso,
458 					     struct machine *machine)
459 {
460 	struct auxtrace_cache *c;
461 	unsigned int bits;
462 
463 	if (dso->auxtrace_cache)
464 		return dso->auxtrace_cache;
465 
466 	bits = intel_pt_cache_size(dso, machine);
467 
468 	/* Ignoring cache creation failure */
469 	c = auxtrace_cache__new(bits, sizeof(struct intel_pt_cache_entry), 200);
470 
471 	dso->auxtrace_cache = c;
472 
473 	return c;
474 }
475 
476 static int intel_pt_cache_add(struct dso *dso, struct machine *machine,
477 			      u64 offset, u64 insn_cnt, u64 byte_cnt,
478 			      struct intel_pt_insn *intel_pt_insn)
479 {
480 	struct auxtrace_cache *c = intel_pt_cache(dso, machine);
481 	struct intel_pt_cache_entry *e;
482 	int err;
483 
484 	if (!c)
485 		return -ENOMEM;
486 
487 	e = auxtrace_cache__alloc_entry(c);
488 	if (!e)
489 		return -ENOMEM;
490 
491 	e->insn_cnt = insn_cnt;
492 	e->byte_cnt = byte_cnt;
493 	e->op = intel_pt_insn->op;
494 	e->branch = intel_pt_insn->branch;
495 	e->length = intel_pt_insn->length;
496 	e->rel = intel_pt_insn->rel;
497 	memcpy(e->insn, intel_pt_insn->buf, INTEL_PT_INSN_BUF_SZ);
498 
499 	err = auxtrace_cache__add(c, offset, &e->entry);
500 	if (err)
501 		auxtrace_cache__free_entry(c, e);
502 
503 	return err;
504 }
505 
506 static struct intel_pt_cache_entry *
507 intel_pt_cache_lookup(struct dso *dso, struct machine *machine, u64 offset)
508 {
509 	struct auxtrace_cache *c = intel_pt_cache(dso, machine);
510 
511 	if (!c)
512 		return NULL;
513 
514 	return auxtrace_cache__lookup(dso->auxtrace_cache, offset);
515 }
516 
517 static inline u8 intel_pt_cpumode(struct intel_pt *pt, uint64_t ip)
518 {
519 	return ip >= pt->kernel_start ?
520 	       PERF_RECORD_MISC_KERNEL :
521 	       PERF_RECORD_MISC_USER;
522 }
523 
524 static int intel_pt_walk_next_insn(struct intel_pt_insn *intel_pt_insn,
525 				   uint64_t *insn_cnt_ptr, uint64_t *ip,
526 				   uint64_t to_ip, uint64_t max_insn_cnt,
527 				   void *data)
528 {
529 	struct intel_pt_queue *ptq = data;
530 	struct machine *machine = ptq->pt->machine;
531 	struct thread *thread;
532 	struct addr_location al;
533 	unsigned char buf[INTEL_PT_INSN_BUF_SZ];
534 	ssize_t len;
535 	int x86_64;
536 	u8 cpumode;
537 	u64 offset, start_offset, start_ip;
538 	u64 insn_cnt = 0;
539 	bool one_map = true;
540 
541 	intel_pt_insn->length = 0;
542 
543 	if (to_ip && *ip == to_ip)
544 		goto out_no_cache;
545 
546 	cpumode = intel_pt_cpumode(ptq->pt, *ip);
547 
548 	thread = ptq->thread;
549 	if (!thread) {
550 		if (cpumode != PERF_RECORD_MISC_KERNEL)
551 			return -EINVAL;
552 		thread = ptq->pt->unknown_thread;
553 	}
554 
555 	while (1) {
556 		if (!thread__find_map(thread, cpumode, *ip, &al) || !al.map->dso)
557 			return -EINVAL;
558 
559 		if (al.map->dso->data.status == DSO_DATA_STATUS_ERROR &&
560 		    dso__data_status_seen(al.map->dso,
561 					  DSO_DATA_STATUS_SEEN_ITRACE))
562 			return -ENOENT;
563 
564 		offset = al.map->map_ip(al.map, *ip);
565 
566 		if (!to_ip && one_map) {
567 			struct intel_pt_cache_entry *e;
568 
569 			e = intel_pt_cache_lookup(al.map->dso, machine, offset);
570 			if (e &&
571 			    (!max_insn_cnt || e->insn_cnt <= max_insn_cnt)) {
572 				*insn_cnt_ptr = e->insn_cnt;
573 				*ip += e->byte_cnt;
574 				intel_pt_insn->op = e->op;
575 				intel_pt_insn->branch = e->branch;
576 				intel_pt_insn->length = e->length;
577 				intel_pt_insn->rel = e->rel;
578 				memcpy(intel_pt_insn->buf, e->insn,
579 				       INTEL_PT_INSN_BUF_SZ);
580 				intel_pt_log_insn_no_data(intel_pt_insn, *ip);
581 				return 0;
582 			}
583 		}
584 
585 		start_offset = offset;
586 		start_ip = *ip;
587 
588 		/* Load maps to ensure dso->is_64_bit has been updated */
589 		map__load(al.map);
590 
591 		x86_64 = al.map->dso->is_64_bit;
592 
593 		while (1) {
594 			len = dso__data_read_offset(al.map->dso, machine,
595 						    offset, buf,
596 						    INTEL_PT_INSN_BUF_SZ);
597 			if (len <= 0)
598 				return -EINVAL;
599 
600 			if (intel_pt_get_insn(buf, len, x86_64, intel_pt_insn))
601 				return -EINVAL;
602 
603 			intel_pt_log_insn(intel_pt_insn, *ip);
604 
605 			insn_cnt += 1;
606 
607 			if (intel_pt_insn->branch != INTEL_PT_BR_NO_BRANCH)
608 				goto out;
609 
610 			if (max_insn_cnt && insn_cnt >= max_insn_cnt)
611 				goto out_no_cache;
612 
613 			*ip += intel_pt_insn->length;
614 
615 			if (to_ip && *ip == to_ip)
616 				goto out_no_cache;
617 
618 			if (*ip >= al.map->end)
619 				break;
620 
621 			offset += intel_pt_insn->length;
622 		}
623 		one_map = false;
624 	}
625 out:
626 	*insn_cnt_ptr = insn_cnt;
627 
628 	if (!one_map)
629 		goto out_no_cache;
630 
631 	/*
632 	 * Didn't lookup in the 'to_ip' case, so do it now to prevent duplicate
633 	 * entries.
634 	 */
635 	if (to_ip) {
636 		struct intel_pt_cache_entry *e;
637 
638 		e = intel_pt_cache_lookup(al.map->dso, machine, start_offset);
639 		if (e)
640 			return 0;
641 	}
642 
643 	/* Ignore cache errors */
644 	intel_pt_cache_add(al.map->dso, machine, start_offset, insn_cnt,
645 			   *ip - start_ip, intel_pt_insn);
646 
647 	return 0;
648 
649 out_no_cache:
650 	*insn_cnt_ptr = insn_cnt;
651 	return 0;
652 }
653 
654 static bool intel_pt_match_pgd_ip(struct intel_pt *pt, uint64_t ip,
655 				  uint64_t offset, const char *filename)
656 {
657 	struct addr_filter *filt;
658 	bool have_filter   = false;
659 	bool hit_tracestop = false;
660 	bool hit_filter    = false;
661 
662 	list_for_each_entry(filt, &pt->filts.head, list) {
663 		if (filt->start)
664 			have_filter = true;
665 
666 		if ((filename && !filt->filename) ||
667 		    (!filename && filt->filename) ||
668 		    (filename && strcmp(filename, filt->filename)))
669 			continue;
670 
671 		if (!(offset >= filt->addr && offset < filt->addr + filt->size))
672 			continue;
673 
674 		intel_pt_log("TIP.PGD ip %#"PRIx64" offset %#"PRIx64" in %s hit filter: %s offset %#"PRIx64" size %#"PRIx64"\n",
675 			     ip, offset, filename ? filename : "[kernel]",
676 			     filt->start ? "filter" : "stop",
677 			     filt->addr, filt->size);
678 
679 		if (filt->start)
680 			hit_filter = true;
681 		else
682 			hit_tracestop = true;
683 	}
684 
685 	if (!hit_tracestop && !hit_filter)
686 		intel_pt_log("TIP.PGD ip %#"PRIx64" offset %#"PRIx64" in %s is not in a filter region\n",
687 			     ip, offset, filename ? filename : "[kernel]");
688 
689 	return hit_tracestop || (have_filter && !hit_filter);
690 }
691 
692 static int __intel_pt_pgd_ip(uint64_t ip, void *data)
693 {
694 	struct intel_pt_queue *ptq = data;
695 	struct thread *thread;
696 	struct addr_location al;
697 	u8 cpumode;
698 	u64 offset;
699 
700 	if (ip >= ptq->pt->kernel_start)
701 		return intel_pt_match_pgd_ip(ptq->pt, ip, ip, NULL);
702 
703 	cpumode = PERF_RECORD_MISC_USER;
704 
705 	thread = ptq->thread;
706 	if (!thread)
707 		return -EINVAL;
708 
709 	if (!thread__find_map(thread, cpumode, ip, &al) || !al.map->dso)
710 		return -EINVAL;
711 
712 	offset = al.map->map_ip(al.map, ip);
713 
714 	return intel_pt_match_pgd_ip(ptq->pt, ip, offset,
715 				     al.map->dso->long_name);
716 }
717 
718 static bool intel_pt_pgd_ip(uint64_t ip, void *data)
719 {
720 	return __intel_pt_pgd_ip(ip, data) > 0;
721 }
722 
723 static bool intel_pt_get_config(struct intel_pt *pt,
724 				struct perf_event_attr *attr, u64 *config)
725 {
726 	if (attr->type == pt->pmu_type) {
727 		if (config)
728 			*config = attr->config;
729 		return true;
730 	}
731 
732 	return false;
733 }
734 
735 static bool intel_pt_exclude_kernel(struct intel_pt *pt)
736 {
737 	struct evsel *evsel;
738 
739 	evlist__for_each_entry(pt->session->evlist, evsel) {
740 		if (intel_pt_get_config(pt, &evsel->core.attr, NULL) &&
741 		    !evsel->core.attr.exclude_kernel)
742 			return false;
743 	}
744 	return true;
745 }
746 
747 static bool intel_pt_return_compression(struct intel_pt *pt)
748 {
749 	struct evsel *evsel;
750 	u64 config;
751 
752 	if (!pt->noretcomp_bit)
753 		return true;
754 
755 	evlist__for_each_entry(pt->session->evlist, evsel) {
756 		if (intel_pt_get_config(pt, &evsel->core.attr, &config) &&
757 		    (config & pt->noretcomp_bit))
758 			return false;
759 	}
760 	return true;
761 }
762 
763 static bool intel_pt_branch_enable(struct intel_pt *pt)
764 {
765 	struct evsel *evsel;
766 	u64 config;
767 
768 	evlist__for_each_entry(pt->session->evlist, evsel) {
769 		if (intel_pt_get_config(pt, &evsel->core.attr, &config) &&
770 		    (config & 1) && !(config & 0x2000))
771 			return false;
772 	}
773 	return true;
774 }
775 
776 static unsigned int intel_pt_mtc_period(struct intel_pt *pt)
777 {
778 	struct evsel *evsel;
779 	unsigned int shift;
780 	u64 config;
781 
782 	if (!pt->mtc_freq_bits)
783 		return 0;
784 
785 	for (shift = 0, config = pt->mtc_freq_bits; !(config & 1); shift++)
786 		config >>= 1;
787 
788 	evlist__for_each_entry(pt->session->evlist, evsel) {
789 		if (intel_pt_get_config(pt, &evsel->core.attr, &config))
790 			return (config & pt->mtc_freq_bits) >> shift;
791 	}
792 	return 0;
793 }
794 
795 static bool intel_pt_timeless_decoding(struct intel_pt *pt)
796 {
797 	struct evsel *evsel;
798 	bool timeless_decoding = true;
799 	u64 config;
800 
801 	if (!pt->tsc_bit || !pt->cap_user_time_zero)
802 		return true;
803 
804 	evlist__for_each_entry(pt->session->evlist, evsel) {
805 		if (!(evsel->core.attr.sample_type & PERF_SAMPLE_TIME))
806 			return true;
807 		if (intel_pt_get_config(pt, &evsel->core.attr, &config)) {
808 			if (config & pt->tsc_bit)
809 				timeless_decoding = false;
810 			else
811 				return true;
812 		}
813 	}
814 	return timeless_decoding;
815 }
816 
817 static bool intel_pt_tracing_kernel(struct intel_pt *pt)
818 {
819 	struct evsel *evsel;
820 
821 	evlist__for_each_entry(pt->session->evlist, evsel) {
822 		if (intel_pt_get_config(pt, &evsel->core.attr, NULL) &&
823 		    !evsel->core.attr.exclude_kernel)
824 			return true;
825 	}
826 	return false;
827 }
828 
829 static bool intel_pt_have_tsc(struct intel_pt *pt)
830 {
831 	struct evsel *evsel;
832 	bool have_tsc = false;
833 	u64 config;
834 
835 	if (!pt->tsc_bit)
836 		return false;
837 
838 	evlist__for_each_entry(pt->session->evlist, evsel) {
839 		if (intel_pt_get_config(pt, &evsel->core.attr, &config)) {
840 			if (config & pt->tsc_bit)
841 				have_tsc = true;
842 			else
843 				return false;
844 		}
845 	}
846 	return have_tsc;
847 }
848 
849 static bool intel_pt_sampling_mode(struct intel_pt *pt)
850 {
851 	struct evsel *evsel;
852 
853 	evlist__for_each_entry(pt->session->evlist, evsel) {
854 		if ((evsel->core.attr.sample_type & PERF_SAMPLE_AUX) &&
855 		    evsel->core.attr.aux_sample_size)
856 			return true;
857 	}
858 	return false;
859 }
860 
861 static u64 intel_pt_ns_to_ticks(const struct intel_pt *pt, u64 ns)
862 {
863 	u64 quot, rem;
864 
865 	quot = ns / pt->tc.time_mult;
866 	rem  = ns % pt->tc.time_mult;
867 	return (quot << pt->tc.time_shift) + (rem << pt->tc.time_shift) /
868 		pt->tc.time_mult;
869 }
870 
871 static struct intel_pt_queue *intel_pt_alloc_queue(struct intel_pt *pt,
872 						   unsigned int queue_nr)
873 {
874 	struct intel_pt_params params = { .get_trace = 0, };
875 	struct perf_env *env = pt->machine->env;
876 	struct intel_pt_queue *ptq;
877 
878 	ptq = zalloc(sizeof(struct intel_pt_queue));
879 	if (!ptq)
880 		return NULL;
881 
882 	if (pt->synth_opts.callchain) {
883 		size_t sz = sizeof(struct ip_callchain);
884 
885 		/* Add 1 to callchain_sz for callchain context */
886 		sz += (pt->synth_opts.callchain_sz + 1) * sizeof(u64);
887 		ptq->chain = zalloc(sz);
888 		if (!ptq->chain)
889 			goto out_free;
890 	}
891 
892 	if (pt->synth_opts.last_branch) {
893 		size_t sz = sizeof(struct branch_stack);
894 
895 		sz += pt->synth_opts.last_branch_sz *
896 		      sizeof(struct branch_entry);
897 		ptq->last_branch = zalloc(sz);
898 		if (!ptq->last_branch)
899 			goto out_free;
900 		ptq->last_branch_rb = zalloc(sz);
901 		if (!ptq->last_branch_rb)
902 			goto out_free;
903 	}
904 
905 	ptq->event_buf = malloc(PERF_SAMPLE_MAX_SIZE);
906 	if (!ptq->event_buf)
907 		goto out_free;
908 
909 	ptq->pt = pt;
910 	ptq->queue_nr = queue_nr;
911 	ptq->exclude_kernel = intel_pt_exclude_kernel(pt);
912 	ptq->pid = -1;
913 	ptq->tid = -1;
914 	ptq->cpu = -1;
915 	ptq->next_tid = -1;
916 
917 	params.get_trace = intel_pt_get_trace;
918 	params.walk_insn = intel_pt_walk_next_insn;
919 	params.lookahead = intel_pt_lookahead;
920 	params.data = ptq;
921 	params.return_compression = intel_pt_return_compression(pt);
922 	params.branch_enable = intel_pt_branch_enable(pt);
923 	params.max_non_turbo_ratio = pt->max_non_turbo_ratio;
924 	params.mtc_period = intel_pt_mtc_period(pt);
925 	params.tsc_ctc_ratio_n = pt->tsc_ctc_ratio_n;
926 	params.tsc_ctc_ratio_d = pt->tsc_ctc_ratio_d;
927 
928 	if (pt->filts.cnt > 0)
929 		params.pgd_ip = intel_pt_pgd_ip;
930 
931 	if (pt->synth_opts.instructions) {
932 		if (pt->synth_opts.period) {
933 			switch (pt->synth_opts.period_type) {
934 			case PERF_ITRACE_PERIOD_INSTRUCTIONS:
935 				params.period_type =
936 						INTEL_PT_PERIOD_INSTRUCTIONS;
937 				params.period = pt->synth_opts.period;
938 				break;
939 			case PERF_ITRACE_PERIOD_TICKS:
940 				params.period_type = INTEL_PT_PERIOD_TICKS;
941 				params.period = pt->synth_opts.period;
942 				break;
943 			case PERF_ITRACE_PERIOD_NANOSECS:
944 				params.period_type = INTEL_PT_PERIOD_TICKS;
945 				params.period = intel_pt_ns_to_ticks(pt,
946 							pt->synth_opts.period);
947 				break;
948 			default:
949 				break;
950 			}
951 		}
952 
953 		if (!params.period) {
954 			params.period_type = INTEL_PT_PERIOD_INSTRUCTIONS;
955 			params.period = 1;
956 		}
957 	}
958 
959 	if (env->cpuid && !strncmp(env->cpuid, "GenuineIntel,6,92,", 18))
960 		params.flags |= INTEL_PT_FUP_WITH_NLIP;
961 
962 	ptq->decoder = intel_pt_decoder_new(&params);
963 	if (!ptq->decoder)
964 		goto out_free;
965 
966 	return ptq;
967 
968 out_free:
969 	zfree(&ptq->event_buf);
970 	zfree(&ptq->last_branch);
971 	zfree(&ptq->last_branch_rb);
972 	zfree(&ptq->chain);
973 	free(ptq);
974 	return NULL;
975 }
976 
977 static void intel_pt_free_queue(void *priv)
978 {
979 	struct intel_pt_queue *ptq = priv;
980 
981 	if (!ptq)
982 		return;
983 	thread__zput(ptq->thread);
984 	intel_pt_decoder_free(ptq->decoder);
985 	zfree(&ptq->event_buf);
986 	zfree(&ptq->last_branch);
987 	zfree(&ptq->last_branch_rb);
988 	zfree(&ptq->chain);
989 	free(ptq);
990 }
991 
992 static void intel_pt_set_pid_tid_cpu(struct intel_pt *pt,
993 				     struct auxtrace_queue *queue)
994 {
995 	struct intel_pt_queue *ptq = queue->priv;
996 
997 	if (queue->tid == -1 || pt->have_sched_switch) {
998 		ptq->tid = machine__get_current_tid(pt->machine, ptq->cpu);
999 		thread__zput(ptq->thread);
1000 	}
1001 
1002 	if (!ptq->thread && ptq->tid != -1)
1003 		ptq->thread = machine__find_thread(pt->machine, -1, ptq->tid);
1004 
1005 	if (ptq->thread) {
1006 		ptq->pid = ptq->thread->pid_;
1007 		if (queue->cpu == -1)
1008 			ptq->cpu = ptq->thread->cpu;
1009 	}
1010 }
1011 
1012 static void intel_pt_sample_flags(struct intel_pt_queue *ptq)
1013 {
1014 	if (ptq->state->flags & INTEL_PT_ABORT_TX) {
1015 		ptq->flags = PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT;
1016 	} else if (ptq->state->flags & INTEL_PT_ASYNC) {
1017 		if (ptq->state->to_ip)
1018 			ptq->flags = PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL |
1019 				     PERF_IP_FLAG_ASYNC |
1020 				     PERF_IP_FLAG_INTERRUPT;
1021 		else
1022 			ptq->flags = PERF_IP_FLAG_BRANCH |
1023 				     PERF_IP_FLAG_TRACE_END;
1024 		ptq->insn_len = 0;
1025 	} else {
1026 		if (ptq->state->from_ip)
1027 			ptq->flags = intel_pt_insn_type(ptq->state->insn_op);
1028 		else
1029 			ptq->flags = PERF_IP_FLAG_BRANCH |
1030 				     PERF_IP_FLAG_TRACE_BEGIN;
1031 		if (ptq->state->flags & INTEL_PT_IN_TX)
1032 			ptq->flags |= PERF_IP_FLAG_IN_TX;
1033 		ptq->insn_len = ptq->state->insn_len;
1034 		memcpy(ptq->insn, ptq->state->insn, INTEL_PT_INSN_BUF_SZ);
1035 	}
1036 
1037 	if (ptq->state->type & INTEL_PT_TRACE_BEGIN)
1038 		ptq->flags |= PERF_IP_FLAG_TRACE_BEGIN;
1039 	if (ptq->state->type & INTEL_PT_TRACE_END)
1040 		ptq->flags |= PERF_IP_FLAG_TRACE_END;
1041 }
1042 
1043 static void intel_pt_setup_time_range(struct intel_pt *pt,
1044 				      struct intel_pt_queue *ptq)
1045 {
1046 	if (!pt->range_cnt)
1047 		return;
1048 
1049 	ptq->sel_timestamp = pt->time_ranges[0].start;
1050 	ptq->sel_idx = 0;
1051 
1052 	if (ptq->sel_timestamp) {
1053 		ptq->sel_start = true;
1054 	} else {
1055 		ptq->sel_timestamp = pt->time_ranges[0].end;
1056 		ptq->sel_start = false;
1057 	}
1058 }
1059 
1060 static int intel_pt_setup_queue(struct intel_pt *pt,
1061 				struct auxtrace_queue *queue,
1062 				unsigned int queue_nr)
1063 {
1064 	struct intel_pt_queue *ptq = queue->priv;
1065 
1066 	if (list_empty(&queue->head))
1067 		return 0;
1068 
1069 	if (!ptq) {
1070 		ptq = intel_pt_alloc_queue(pt, queue_nr);
1071 		if (!ptq)
1072 			return -ENOMEM;
1073 		queue->priv = ptq;
1074 
1075 		if (queue->cpu != -1)
1076 			ptq->cpu = queue->cpu;
1077 		ptq->tid = queue->tid;
1078 
1079 		ptq->cbr_seen = UINT_MAX;
1080 
1081 		if (pt->sampling_mode && !pt->snapshot_mode &&
1082 		    pt->timeless_decoding)
1083 			ptq->step_through_buffers = true;
1084 
1085 		ptq->sync_switch = pt->sync_switch;
1086 
1087 		intel_pt_setup_time_range(pt, ptq);
1088 	}
1089 
1090 	if (!ptq->on_heap &&
1091 	    (!ptq->sync_switch ||
1092 	     ptq->switch_state != INTEL_PT_SS_EXPECTING_SWITCH_EVENT)) {
1093 		const struct intel_pt_state *state;
1094 		int ret;
1095 
1096 		if (pt->timeless_decoding)
1097 			return 0;
1098 
1099 		intel_pt_log("queue %u getting timestamp\n", queue_nr);
1100 		intel_pt_log("queue %u decoding cpu %d pid %d tid %d\n",
1101 			     queue_nr, ptq->cpu, ptq->pid, ptq->tid);
1102 
1103 		if (ptq->sel_start && ptq->sel_timestamp) {
1104 			ret = intel_pt_fast_forward(ptq->decoder,
1105 						    ptq->sel_timestamp);
1106 			if (ret)
1107 				return ret;
1108 		}
1109 
1110 		while (1) {
1111 			state = intel_pt_decode(ptq->decoder);
1112 			if (state->err) {
1113 				if (state->err == INTEL_PT_ERR_NODATA) {
1114 					intel_pt_log("queue %u has no timestamp\n",
1115 						     queue_nr);
1116 					return 0;
1117 				}
1118 				continue;
1119 			}
1120 			if (state->timestamp)
1121 				break;
1122 		}
1123 
1124 		ptq->timestamp = state->timestamp;
1125 		intel_pt_log("queue %u timestamp 0x%" PRIx64 "\n",
1126 			     queue_nr, ptq->timestamp);
1127 		ptq->state = state;
1128 		ptq->have_sample = true;
1129 		if (ptq->sel_start && ptq->sel_timestamp &&
1130 		    ptq->timestamp < ptq->sel_timestamp)
1131 			ptq->have_sample = false;
1132 		intel_pt_sample_flags(ptq);
1133 		ret = auxtrace_heap__add(&pt->heap, queue_nr, ptq->timestamp);
1134 		if (ret)
1135 			return ret;
1136 		ptq->on_heap = true;
1137 	}
1138 
1139 	return 0;
1140 }
1141 
1142 static int intel_pt_setup_queues(struct intel_pt *pt)
1143 {
1144 	unsigned int i;
1145 	int ret;
1146 
1147 	for (i = 0; i < pt->queues.nr_queues; i++) {
1148 		ret = intel_pt_setup_queue(pt, &pt->queues.queue_array[i], i);
1149 		if (ret)
1150 			return ret;
1151 	}
1152 	return 0;
1153 }
1154 
1155 static inline void intel_pt_copy_last_branch_rb(struct intel_pt_queue *ptq)
1156 {
1157 	struct branch_stack *bs_src = ptq->last_branch_rb;
1158 	struct branch_stack *bs_dst = ptq->last_branch;
1159 	size_t nr = 0;
1160 
1161 	bs_dst->nr = bs_src->nr;
1162 
1163 	if (!bs_src->nr)
1164 		return;
1165 
1166 	nr = ptq->pt->synth_opts.last_branch_sz - ptq->last_branch_pos;
1167 	memcpy(&bs_dst->entries[0],
1168 	       &bs_src->entries[ptq->last_branch_pos],
1169 	       sizeof(struct branch_entry) * nr);
1170 
1171 	if (bs_src->nr >= ptq->pt->synth_opts.last_branch_sz) {
1172 		memcpy(&bs_dst->entries[nr],
1173 		       &bs_src->entries[0],
1174 		       sizeof(struct branch_entry) * ptq->last_branch_pos);
1175 	}
1176 }
1177 
1178 static inline void intel_pt_reset_last_branch_rb(struct intel_pt_queue *ptq)
1179 {
1180 	ptq->last_branch_pos = 0;
1181 	ptq->last_branch_rb->nr = 0;
1182 }
1183 
1184 static void intel_pt_update_last_branch_rb(struct intel_pt_queue *ptq)
1185 {
1186 	const struct intel_pt_state *state = ptq->state;
1187 	struct branch_stack *bs = ptq->last_branch_rb;
1188 	struct branch_entry *be;
1189 
1190 	if (!ptq->last_branch_pos)
1191 		ptq->last_branch_pos = ptq->pt->synth_opts.last_branch_sz;
1192 
1193 	ptq->last_branch_pos -= 1;
1194 
1195 	be              = &bs->entries[ptq->last_branch_pos];
1196 	be->from        = state->from_ip;
1197 	be->to          = state->to_ip;
1198 	be->flags.abort = !!(state->flags & INTEL_PT_ABORT_TX);
1199 	be->flags.in_tx = !!(state->flags & INTEL_PT_IN_TX);
1200 	/* No support for mispredict */
1201 	be->flags.mispred = ptq->pt->mispred_all;
1202 
1203 	if (bs->nr < ptq->pt->synth_opts.last_branch_sz)
1204 		bs->nr += 1;
1205 }
1206 
1207 static inline bool intel_pt_skip_event(struct intel_pt *pt)
1208 {
1209 	return pt->synth_opts.initial_skip &&
1210 	       pt->num_events++ < pt->synth_opts.initial_skip;
1211 }
1212 
1213 /*
1214  * Cannot count CBR as skipped because it won't go away until cbr == cbr_seen.
1215  * Also ensure CBR is first non-skipped event by allowing for 4 more samples
1216  * from this decoder state.
1217  */
1218 static inline bool intel_pt_skip_cbr_event(struct intel_pt *pt)
1219 {
1220 	return pt->synth_opts.initial_skip &&
1221 	       pt->num_events + 4 < pt->synth_opts.initial_skip;
1222 }
1223 
1224 static void intel_pt_prep_a_sample(struct intel_pt_queue *ptq,
1225 				   union perf_event *event,
1226 				   struct perf_sample *sample)
1227 {
1228 	event->sample.header.type = PERF_RECORD_SAMPLE;
1229 	event->sample.header.size = sizeof(struct perf_event_header);
1230 
1231 	sample->pid = ptq->pid;
1232 	sample->tid = ptq->tid;
1233 	sample->cpu = ptq->cpu;
1234 	sample->insn_len = ptq->insn_len;
1235 	memcpy(sample->insn, ptq->insn, INTEL_PT_INSN_BUF_SZ);
1236 }
1237 
1238 static void intel_pt_prep_b_sample(struct intel_pt *pt,
1239 				   struct intel_pt_queue *ptq,
1240 				   union perf_event *event,
1241 				   struct perf_sample *sample)
1242 {
1243 	intel_pt_prep_a_sample(ptq, event, sample);
1244 
1245 	if (!pt->timeless_decoding)
1246 		sample->time = tsc_to_perf_time(ptq->timestamp, &pt->tc);
1247 
1248 	sample->ip = ptq->state->from_ip;
1249 	sample->cpumode = intel_pt_cpumode(pt, sample->ip);
1250 	sample->addr = ptq->state->to_ip;
1251 	sample->period = 1;
1252 	sample->flags = ptq->flags;
1253 
1254 	event->sample.header.misc = sample->cpumode;
1255 }
1256 
1257 static int intel_pt_inject_event(union perf_event *event,
1258 				 struct perf_sample *sample, u64 type)
1259 {
1260 	event->header.size = perf_event__sample_event_size(sample, type, 0);
1261 	return perf_event__synthesize_sample(event, type, 0, sample);
1262 }
1263 
1264 static inline int intel_pt_opt_inject(struct intel_pt *pt,
1265 				      union perf_event *event,
1266 				      struct perf_sample *sample, u64 type)
1267 {
1268 	if (!pt->synth_opts.inject)
1269 		return 0;
1270 
1271 	return intel_pt_inject_event(event, sample, type);
1272 }
1273 
1274 static int intel_pt_deliver_synth_b_event(struct intel_pt *pt,
1275 					  union perf_event *event,
1276 					  struct perf_sample *sample, u64 type)
1277 {
1278 	int ret;
1279 
1280 	ret = intel_pt_opt_inject(pt, event, sample, type);
1281 	if (ret)
1282 		return ret;
1283 
1284 	ret = perf_session__deliver_synth_event(pt->session, event, sample);
1285 	if (ret)
1286 		pr_err("Intel PT: failed to deliver event, error %d\n", ret);
1287 
1288 	return ret;
1289 }
1290 
1291 static int intel_pt_synth_branch_sample(struct intel_pt_queue *ptq)
1292 {
1293 	struct intel_pt *pt = ptq->pt;
1294 	union perf_event *event = ptq->event_buf;
1295 	struct perf_sample sample = { .ip = 0, };
1296 	struct dummy_branch_stack {
1297 		u64			nr;
1298 		u64			hw_idx;
1299 		struct branch_entry	entries;
1300 	} dummy_bs;
1301 
1302 	if (pt->branches_filter && !(pt->branches_filter & ptq->flags))
1303 		return 0;
1304 
1305 	if (intel_pt_skip_event(pt))
1306 		return 0;
1307 
1308 	intel_pt_prep_b_sample(pt, ptq, event, &sample);
1309 
1310 	sample.id = ptq->pt->branches_id;
1311 	sample.stream_id = ptq->pt->branches_id;
1312 
1313 	/*
1314 	 * perf report cannot handle events without a branch stack when using
1315 	 * SORT_MODE__BRANCH so make a dummy one.
1316 	 */
1317 	if (pt->synth_opts.last_branch && sort__mode == SORT_MODE__BRANCH) {
1318 		dummy_bs = (struct dummy_branch_stack){
1319 			.nr = 1,
1320 			.hw_idx = -1ULL,
1321 			.entries = {
1322 				.from = sample.ip,
1323 				.to = sample.addr,
1324 			},
1325 		};
1326 		sample.branch_stack = (struct branch_stack *)&dummy_bs;
1327 	}
1328 
1329 	sample.cyc_cnt = ptq->ipc_cyc_cnt - ptq->last_br_cyc_cnt;
1330 	if (sample.cyc_cnt) {
1331 		sample.insn_cnt = ptq->ipc_insn_cnt - ptq->last_br_insn_cnt;
1332 		ptq->last_br_insn_cnt = ptq->ipc_insn_cnt;
1333 		ptq->last_br_cyc_cnt = ptq->ipc_cyc_cnt;
1334 	}
1335 
1336 	return intel_pt_deliver_synth_b_event(pt, event, &sample,
1337 					      pt->branches_sample_type);
1338 }
1339 
1340 static void intel_pt_prep_sample(struct intel_pt *pt,
1341 				 struct intel_pt_queue *ptq,
1342 				 union perf_event *event,
1343 				 struct perf_sample *sample)
1344 {
1345 	intel_pt_prep_b_sample(pt, ptq, event, sample);
1346 
1347 	if (pt->synth_opts.callchain) {
1348 		thread_stack__sample(ptq->thread, ptq->cpu, ptq->chain,
1349 				     pt->synth_opts.callchain_sz + 1,
1350 				     sample->ip, pt->kernel_start);
1351 		sample->callchain = ptq->chain;
1352 	}
1353 
1354 	if (pt->synth_opts.last_branch) {
1355 		intel_pt_copy_last_branch_rb(ptq);
1356 		sample->branch_stack = ptq->last_branch;
1357 	}
1358 }
1359 
1360 static inline int intel_pt_deliver_synth_event(struct intel_pt *pt,
1361 					       struct intel_pt_queue *ptq,
1362 					       union perf_event *event,
1363 					       struct perf_sample *sample,
1364 					       u64 type)
1365 {
1366 	int ret;
1367 
1368 	ret = intel_pt_deliver_synth_b_event(pt, event, sample, type);
1369 
1370 	if (pt->synth_opts.last_branch)
1371 		intel_pt_reset_last_branch_rb(ptq);
1372 
1373 	return ret;
1374 }
1375 
1376 static int intel_pt_synth_instruction_sample(struct intel_pt_queue *ptq)
1377 {
1378 	struct intel_pt *pt = ptq->pt;
1379 	union perf_event *event = ptq->event_buf;
1380 	struct perf_sample sample = { .ip = 0, };
1381 
1382 	if (intel_pt_skip_event(pt))
1383 		return 0;
1384 
1385 	intel_pt_prep_sample(pt, ptq, event, &sample);
1386 
1387 	sample.id = ptq->pt->instructions_id;
1388 	sample.stream_id = ptq->pt->instructions_id;
1389 	sample.period = ptq->state->tot_insn_cnt - ptq->last_insn_cnt;
1390 
1391 	sample.cyc_cnt = ptq->ipc_cyc_cnt - ptq->last_in_cyc_cnt;
1392 	if (sample.cyc_cnt) {
1393 		sample.insn_cnt = ptq->ipc_insn_cnt - ptq->last_in_insn_cnt;
1394 		ptq->last_in_insn_cnt = ptq->ipc_insn_cnt;
1395 		ptq->last_in_cyc_cnt = ptq->ipc_cyc_cnt;
1396 	}
1397 
1398 	ptq->last_insn_cnt = ptq->state->tot_insn_cnt;
1399 
1400 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1401 					    pt->instructions_sample_type);
1402 }
1403 
1404 static int intel_pt_synth_transaction_sample(struct intel_pt_queue *ptq)
1405 {
1406 	struct intel_pt *pt = ptq->pt;
1407 	union perf_event *event = ptq->event_buf;
1408 	struct perf_sample sample = { .ip = 0, };
1409 
1410 	if (intel_pt_skip_event(pt))
1411 		return 0;
1412 
1413 	intel_pt_prep_sample(pt, ptq, event, &sample);
1414 
1415 	sample.id = ptq->pt->transactions_id;
1416 	sample.stream_id = ptq->pt->transactions_id;
1417 
1418 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1419 					    pt->transactions_sample_type);
1420 }
1421 
1422 static void intel_pt_prep_p_sample(struct intel_pt *pt,
1423 				   struct intel_pt_queue *ptq,
1424 				   union perf_event *event,
1425 				   struct perf_sample *sample)
1426 {
1427 	intel_pt_prep_sample(pt, ptq, event, sample);
1428 
1429 	/*
1430 	 * Zero IP is used to mean "trace start" but that is not the case for
1431 	 * power or PTWRITE events with no IP, so clear the flags.
1432 	 */
1433 	if (!sample->ip)
1434 		sample->flags = 0;
1435 }
1436 
1437 static int intel_pt_synth_ptwrite_sample(struct intel_pt_queue *ptq)
1438 {
1439 	struct intel_pt *pt = ptq->pt;
1440 	union perf_event *event = ptq->event_buf;
1441 	struct perf_sample sample = { .ip = 0, };
1442 	struct perf_synth_intel_ptwrite raw;
1443 
1444 	if (intel_pt_skip_event(pt))
1445 		return 0;
1446 
1447 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1448 
1449 	sample.id = ptq->pt->ptwrites_id;
1450 	sample.stream_id = ptq->pt->ptwrites_id;
1451 
1452 	raw.flags = 0;
1453 	raw.ip = !!(ptq->state->flags & INTEL_PT_FUP_IP);
1454 	raw.payload = cpu_to_le64(ptq->state->ptw_payload);
1455 
1456 	sample.raw_size = perf_synth__raw_size(raw);
1457 	sample.raw_data = perf_synth__raw_data(&raw);
1458 
1459 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1460 					    pt->ptwrites_sample_type);
1461 }
1462 
1463 static int intel_pt_synth_cbr_sample(struct intel_pt_queue *ptq)
1464 {
1465 	struct intel_pt *pt = ptq->pt;
1466 	union perf_event *event = ptq->event_buf;
1467 	struct perf_sample sample = { .ip = 0, };
1468 	struct perf_synth_intel_cbr raw;
1469 	u32 flags;
1470 
1471 	if (intel_pt_skip_cbr_event(pt))
1472 		return 0;
1473 
1474 	ptq->cbr_seen = ptq->state->cbr;
1475 
1476 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1477 
1478 	sample.id = ptq->pt->cbr_id;
1479 	sample.stream_id = ptq->pt->cbr_id;
1480 
1481 	flags = (u16)ptq->state->cbr_payload | (pt->max_non_turbo_ratio << 16);
1482 	raw.flags = cpu_to_le32(flags);
1483 	raw.freq = cpu_to_le32(raw.cbr * pt->cbr2khz);
1484 	raw.reserved3 = 0;
1485 
1486 	sample.raw_size = perf_synth__raw_size(raw);
1487 	sample.raw_data = perf_synth__raw_data(&raw);
1488 
1489 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1490 					    pt->pwr_events_sample_type);
1491 }
1492 
1493 static int intel_pt_synth_mwait_sample(struct intel_pt_queue *ptq)
1494 {
1495 	struct intel_pt *pt = ptq->pt;
1496 	union perf_event *event = ptq->event_buf;
1497 	struct perf_sample sample = { .ip = 0, };
1498 	struct perf_synth_intel_mwait raw;
1499 
1500 	if (intel_pt_skip_event(pt))
1501 		return 0;
1502 
1503 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1504 
1505 	sample.id = ptq->pt->mwait_id;
1506 	sample.stream_id = ptq->pt->mwait_id;
1507 
1508 	raw.reserved = 0;
1509 	raw.payload = cpu_to_le64(ptq->state->mwait_payload);
1510 
1511 	sample.raw_size = perf_synth__raw_size(raw);
1512 	sample.raw_data = perf_synth__raw_data(&raw);
1513 
1514 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1515 					    pt->pwr_events_sample_type);
1516 }
1517 
1518 static int intel_pt_synth_pwre_sample(struct intel_pt_queue *ptq)
1519 {
1520 	struct intel_pt *pt = ptq->pt;
1521 	union perf_event *event = ptq->event_buf;
1522 	struct perf_sample sample = { .ip = 0, };
1523 	struct perf_synth_intel_pwre raw;
1524 
1525 	if (intel_pt_skip_event(pt))
1526 		return 0;
1527 
1528 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1529 
1530 	sample.id = ptq->pt->pwre_id;
1531 	sample.stream_id = ptq->pt->pwre_id;
1532 
1533 	raw.reserved = 0;
1534 	raw.payload = cpu_to_le64(ptq->state->pwre_payload);
1535 
1536 	sample.raw_size = perf_synth__raw_size(raw);
1537 	sample.raw_data = perf_synth__raw_data(&raw);
1538 
1539 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1540 					    pt->pwr_events_sample_type);
1541 }
1542 
1543 static int intel_pt_synth_exstop_sample(struct intel_pt_queue *ptq)
1544 {
1545 	struct intel_pt *pt = ptq->pt;
1546 	union perf_event *event = ptq->event_buf;
1547 	struct perf_sample sample = { .ip = 0, };
1548 	struct perf_synth_intel_exstop raw;
1549 
1550 	if (intel_pt_skip_event(pt))
1551 		return 0;
1552 
1553 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1554 
1555 	sample.id = ptq->pt->exstop_id;
1556 	sample.stream_id = ptq->pt->exstop_id;
1557 
1558 	raw.flags = 0;
1559 	raw.ip = !!(ptq->state->flags & INTEL_PT_FUP_IP);
1560 
1561 	sample.raw_size = perf_synth__raw_size(raw);
1562 	sample.raw_data = perf_synth__raw_data(&raw);
1563 
1564 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1565 					    pt->pwr_events_sample_type);
1566 }
1567 
1568 static int intel_pt_synth_pwrx_sample(struct intel_pt_queue *ptq)
1569 {
1570 	struct intel_pt *pt = ptq->pt;
1571 	union perf_event *event = ptq->event_buf;
1572 	struct perf_sample sample = { .ip = 0, };
1573 	struct perf_synth_intel_pwrx raw;
1574 
1575 	if (intel_pt_skip_event(pt))
1576 		return 0;
1577 
1578 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1579 
1580 	sample.id = ptq->pt->pwrx_id;
1581 	sample.stream_id = ptq->pt->pwrx_id;
1582 
1583 	raw.reserved = 0;
1584 	raw.payload = cpu_to_le64(ptq->state->pwrx_payload);
1585 
1586 	sample.raw_size = perf_synth__raw_size(raw);
1587 	sample.raw_data = perf_synth__raw_data(&raw);
1588 
1589 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1590 					    pt->pwr_events_sample_type);
1591 }
1592 
1593 /*
1594  * PEBS gp_regs array indexes plus 1 so that 0 means not present. Refer
1595  * intel_pt_add_gp_regs().
1596  */
1597 static const int pebs_gp_regs[] = {
1598 	[PERF_REG_X86_FLAGS]	= 1,
1599 	[PERF_REG_X86_IP]	= 2,
1600 	[PERF_REG_X86_AX]	= 3,
1601 	[PERF_REG_X86_CX]	= 4,
1602 	[PERF_REG_X86_DX]	= 5,
1603 	[PERF_REG_X86_BX]	= 6,
1604 	[PERF_REG_X86_SP]	= 7,
1605 	[PERF_REG_X86_BP]	= 8,
1606 	[PERF_REG_X86_SI]	= 9,
1607 	[PERF_REG_X86_DI]	= 10,
1608 	[PERF_REG_X86_R8]	= 11,
1609 	[PERF_REG_X86_R9]	= 12,
1610 	[PERF_REG_X86_R10]	= 13,
1611 	[PERF_REG_X86_R11]	= 14,
1612 	[PERF_REG_X86_R12]	= 15,
1613 	[PERF_REG_X86_R13]	= 16,
1614 	[PERF_REG_X86_R14]	= 17,
1615 	[PERF_REG_X86_R15]	= 18,
1616 };
1617 
1618 static u64 *intel_pt_add_gp_regs(struct regs_dump *intr_regs, u64 *pos,
1619 				 const struct intel_pt_blk_items *items,
1620 				 u64 regs_mask)
1621 {
1622 	const u64 *gp_regs = items->val[INTEL_PT_GP_REGS_POS];
1623 	u32 mask = items->mask[INTEL_PT_GP_REGS_POS];
1624 	u32 bit;
1625 	int i;
1626 
1627 	for (i = 0, bit = 1; i < PERF_REG_X86_64_MAX; i++, bit <<= 1) {
1628 		/* Get the PEBS gp_regs array index */
1629 		int n = pebs_gp_regs[i] - 1;
1630 
1631 		if (n < 0)
1632 			continue;
1633 		/*
1634 		 * Add only registers that were requested (i.e. 'regs_mask') and
1635 		 * that were provided (i.e. 'mask'), and update the resulting
1636 		 * mask (i.e. 'intr_regs->mask') accordingly.
1637 		 */
1638 		if (mask & 1 << n && regs_mask & bit) {
1639 			intr_regs->mask |= bit;
1640 			*pos++ = gp_regs[n];
1641 		}
1642 	}
1643 
1644 	return pos;
1645 }
1646 
1647 #ifndef PERF_REG_X86_XMM0
1648 #define PERF_REG_X86_XMM0 32
1649 #endif
1650 
1651 static void intel_pt_add_xmm(struct regs_dump *intr_regs, u64 *pos,
1652 			     const struct intel_pt_blk_items *items,
1653 			     u64 regs_mask)
1654 {
1655 	u32 mask = items->has_xmm & (regs_mask >> PERF_REG_X86_XMM0);
1656 	const u64 *xmm = items->xmm;
1657 
1658 	/*
1659 	 * If there are any XMM registers, then there should be all of them.
1660 	 * Nevertheless, follow the logic to add only registers that were
1661 	 * requested (i.e. 'regs_mask') and that were provided (i.e. 'mask'),
1662 	 * and update the resulting mask (i.e. 'intr_regs->mask') accordingly.
1663 	 */
1664 	intr_regs->mask |= (u64)mask << PERF_REG_X86_XMM0;
1665 
1666 	for (; mask; mask >>= 1, xmm++) {
1667 		if (mask & 1)
1668 			*pos++ = *xmm;
1669 	}
1670 }
1671 
1672 #define LBR_INFO_MISPRED	(1ULL << 63)
1673 #define LBR_INFO_IN_TX		(1ULL << 62)
1674 #define LBR_INFO_ABORT		(1ULL << 61)
1675 #define LBR_INFO_CYCLES		0xffff
1676 
1677 /* Refer kernel's intel_pmu_store_pebs_lbrs() */
1678 static u64 intel_pt_lbr_flags(u64 info)
1679 {
1680 	union {
1681 		struct branch_flags flags;
1682 		u64 result;
1683 	} u = {
1684 		.flags = {
1685 			.mispred	= !!(info & LBR_INFO_MISPRED),
1686 			.predicted	= !(info & LBR_INFO_MISPRED),
1687 			.in_tx		= !!(info & LBR_INFO_IN_TX),
1688 			.abort		= !!(info & LBR_INFO_ABORT),
1689 			.cycles		= info & LBR_INFO_CYCLES,
1690 		}
1691 	};
1692 
1693 	return u.result;
1694 }
1695 
1696 static void intel_pt_add_lbrs(struct branch_stack *br_stack,
1697 			      const struct intel_pt_blk_items *items)
1698 {
1699 	u64 *to;
1700 	int i;
1701 
1702 	br_stack->nr = 0;
1703 
1704 	to = &br_stack->entries[0].from;
1705 
1706 	for (i = INTEL_PT_LBR_0_POS; i <= INTEL_PT_LBR_2_POS; i++) {
1707 		u32 mask = items->mask[i];
1708 		const u64 *from = items->val[i];
1709 
1710 		for (; mask; mask >>= 3, from += 3) {
1711 			if ((mask & 7) == 7) {
1712 				*to++ = from[0];
1713 				*to++ = from[1];
1714 				*to++ = intel_pt_lbr_flags(from[2]);
1715 				br_stack->nr += 1;
1716 			}
1717 		}
1718 	}
1719 }
1720 
1721 /* INTEL_PT_LBR_0, INTEL_PT_LBR_1 and INTEL_PT_LBR_2 */
1722 #define LBRS_MAX (INTEL_PT_BLK_ITEM_ID_CNT * 3)
1723 
1724 static int intel_pt_synth_pebs_sample(struct intel_pt_queue *ptq)
1725 {
1726 	const struct intel_pt_blk_items *items = &ptq->state->items;
1727 	struct perf_sample sample = { .ip = 0, };
1728 	union perf_event *event = ptq->event_buf;
1729 	struct intel_pt *pt = ptq->pt;
1730 	struct evsel *evsel = pt->pebs_evsel;
1731 	u64 sample_type = evsel->core.attr.sample_type;
1732 	u64 id = evsel->core.id[0];
1733 	u8 cpumode;
1734 
1735 	if (intel_pt_skip_event(pt))
1736 		return 0;
1737 
1738 	intel_pt_prep_a_sample(ptq, event, &sample);
1739 
1740 	sample.id = id;
1741 	sample.stream_id = id;
1742 
1743 	if (!evsel->core.attr.freq)
1744 		sample.period = evsel->core.attr.sample_period;
1745 
1746 	/* No support for non-zero CS base */
1747 	if (items->has_ip)
1748 		sample.ip = items->ip;
1749 	else if (items->has_rip)
1750 		sample.ip = items->rip;
1751 	else
1752 		sample.ip = ptq->state->from_ip;
1753 
1754 	/* No support for guest mode at this time */
1755 	cpumode = sample.ip < ptq->pt->kernel_start ?
1756 		  PERF_RECORD_MISC_USER :
1757 		  PERF_RECORD_MISC_KERNEL;
1758 
1759 	event->sample.header.misc = cpumode | PERF_RECORD_MISC_EXACT_IP;
1760 
1761 	sample.cpumode = cpumode;
1762 
1763 	if (sample_type & PERF_SAMPLE_TIME) {
1764 		u64 timestamp = 0;
1765 
1766 		if (items->has_timestamp)
1767 			timestamp = items->timestamp;
1768 		else if (!pt->timeless_decoding)
1769 			timestamp = ptq->timestamp;
1770 		if (timestamp)
1771 			sample.time = tsc_to_perf_time(timestamp, &pt->tc);
1772 	}
1773 
1774 	if (sample_type & PERF_SAMPLE_CALLCHAIN &&
1775 	    pt->synth_opts.callchain) {
1776 		thread_stack__sample(ptq->thread, ptq->cpu, ptq->chain,
1777 				     pt->synth_opts.callchain_sz, sample.ip,
1778 				     pt->kernel_start);
1779 		sample.callchain = ptq->chain;
1780 	}
1781 
1782 	if (sample_type & PERF_SAMPLE_REGS_INTR &&
1783 	    items->mask[INTEL_PT_GP_REGS_POS]) {
1784 		u64 regs[sizeof(sample.intr_regs.mask)];
1785 		u64 regs_mask = evsel->core.attr.sample_regs_intr;
1786 		u64 *pos;
1787 
1788 		sample.intr_regs.abi = items->is_32_bit ?
1789 				       PERF_SAMPLE_REGS_ABI_32 :
1790 				       PERF_SAMPLE_REGS_ABI_64;
1791 		sample.intr_regs.regs = regs;
1792 
1793 		pos = intel_pt_add_gp_regs(&sample.intr_regs, regs, items, regs_mask);
1794 
1795 		intel_pt_add_xmm(&sample.intr_regs, pos, items, regs_mask);
1796 	}
1797 
1798 	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
1799 		struct {
1800 			struct branch_stack br_stack;
1801 			struct branch_entry entries[LBRS_MAX];
1802 		} br;
1803 
1804 		if (items->mask[INTEL_PT_LBR_0_POS] ||
1805 		    items->mask[INTEL_PT_LBR_1_POS] ||
1806 		    items->mask[INTEL_PT_LBR_2_POS]) {
1807 			intel_pt_add_lbrs(&br.br_stack, items);
1808 			sample.branch_stack = &br.br_stack;
1809 		} else if (pt->synth_opts.last_branch) {
1810 			intel_pt_copy_last_branch_rb(ptq);
1811 			sample.branch_stack = ptq->last_branch;
1812 		} else {
1813 			br.br_stack.nr = 0;
1814 			sample.branch_stack = &br.br_stack;
1815 		}
1816 	}
1817 
1818 	if (sample_type & PERF_SAMPLE_ADDR && items->has_mem_access_address)
1819 		sample.addr = items->mem_access_address;
1820 
1821 	if (sample_type & PERF_SAMPLE_WEIGHT) {
1822 		/*
1823 		 * Refer kernel's setup_pebs_adaptive_sample_data() and
1824 		 * intel_hsw_weight().
1825 		 */
1826 		if (items->has_mem_access_latency)
1827 			sample.weight = items->mem_access_latency;
1828 		if (!sample.weight && items->has_tsx_aux_info) {
1829 			/* Cycles last block */
1830 			sample.weight = (u32)items->tsx_aux_info;
1831 		}
1832 	}
1833 
1834 	if (sample_type & PERF_SAMPLE_TRANSACTION && items->has_tsx_aux_info) {
1835 		u64 ax = items->has_rax ? items->rax : 0;
1836 		/* Refer kernel's intel_hsw_transaction() */
1837 		u64 txn = (u8)(items->tsx_aux_info >> 32);
1838 
1839 		/* For RTM XABORTs also log the abort code from AX */
1840 		if (txn & PERF_TXN_TRANSACTION && ax & 1)
1841 			txn |= ((ax >> 24) & 0xff) << PERF_TXN_ABORT_SHIFT;
1842 		sample.transaction = txn;
1843 	}
1844 
1845 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample, sample_type);
1846 }
1847 
1848 static int intel_pt_synth_error(struct intel_pt *pt, int code, int cpu,
1849 				pid_t pid, pid_t tid, u64 ip, u64 timestamp)
1850 {
1851 	union perf_event event;
1852 	char msg[MAX_AUXTRACE_ERROR_MSG];
1853 	int err;
1854 
1855 	intel_pt__strerror(code, msg, MAX_AUXTRACE_ERROR_MSG);
1856 
1857 	auxtrace_synth_error(&event.auxtrace_error, PERF_AUXTRACE_ERROR_ITRACE,
1858 			     code, cpu, pid, tid, ip, msg, timestamp);
1859 
1860 	err = perf_session__deliver_synth_event(pt->session, &event, NULL);
1861 	if (err)
1862 		pr_err("Intel Processor Trace: failed to deliver error event, error %d\n",
1863 		       err);
1864 
1865 	return err;
1866 }
1867 
1868 static int intel_ptq_synth_error(struct intel_pt_queue *ptq,
1869 				 const struct intel_pt_state *state)
1870 {
1871 	struct intel_pt *pt = ptq->pt;
1872 	u64 tm = ptq->timestamp;
1873 
1874 	tm = pt->timeless_decoding ? 0 : tsc_to_perf_time(tm, &pt->tc);
1875 
1876 	return intel_pt_synth_error(pt, state->err, ptq->cpu, ptq->pid,
1877 				    ptq->tid, state->from_ip, tm);
1878 }
1879 
1880 static int intel_pt_next_tid(struct intel_pt *pt, struct intel_pt_queue *ptq)
1881 {
1882 	struct auxtrace_queue *queue;
1883 	pid_t tid = ptq->next_tid;
1884 	int err;
1885 
1886 	if (tid == -1)
1887 		return 0;
1888 
1889 	intel_pt_log("switch: cpu %d tid %d\n", ptq->cpu, tid);
1890 
1891 	err = machine__set_current_tid(pt->machine, ptq->cpu, -1, tid);
1892 
1893 	queue = &pt->queues.queue_array[ptq->queue_nr];
1894 	intel_pt_set_pid_tid_cpu(pt, queue);
1895 
1896 	ptq->next_tid = -1;
1897 
1898 	return err;
1899 }
1900 
1901 static inline bool intel_pt_is_switch_ip(struct intel_pt_queue *ptq, u64 ip)
1902 {
1903 	struct intel_pt *pt = ptq->pt;
1904 
1905 	return ip == pt->switch_ip &&
1906 	       (ptq->flags & PERF_IP_FLAG_BRANCH) &&
1907 	       !(ptq->flags & (PERF_IP_FLAG_CONDITIONAL | PERF_IP_FLAG_ASYNC |
1908 			       PERF_IP_FLAG_INTERRUPT | PERF_IP_FLAG_TX_ABORT));
1909 }
1910 
1911 #define INTEL_PT_PWR_EVT (INTEL_PT_MWAIT_OP | INTEL_PT_PWR_ENTRY | \
1912 			  INTEL_PT_EX_STOP | INTEL_PT_PWR_EXIT)
1913 
1914 static int intel_pt_sample(struct intel_pt_queue *ptq)
1915 {
1916 	const struct intel_pt_state *state = ptq->state;
1917 	struct intel_pt *pt = ptq->pt;
1918 	int err;
1919 
1920 	if (!ptq->have_sample)
1921 		return 0;
1922 
1923 	ptq->have_sample = false;
1924 
1925 	if (ptq->state->tot_cyc_cnt > ptq->ipc_cyc_cnt) {
1926 		/*
1927 		 * Cycle count and instruction count only go together to create
1928 		 * a valid IPC ratio when the cycle count changes.
1929 		 */
1930 		ptq->ipc_insn_cnt = ptq->state->tot_insn_cnt;
1931 		ptq->ipc_cyc_cnt = ptq->state->tot_cyc_cnt;
1932 	}
1933 
1934 	/*
1935 	 * Do PEBS first to allow for the possibility that the PEBS timestamp
1936 	 * precedes the current timestamp.
1937 	 */
1938 	if (pt->sample_pebs && state->type & INTEL_PT_BLK_ITEMS) {
1939 		err = intel_pt_synth_pebs_sample(ptq);
1940 		if (err)
1941 			return err;
1942 	}
1943 
1944 	if (pt->sample_pwr_events) {
1945 		if (ptq->state->cbr != ptq->cbr_seen) {
1946 			err = intel_pt_synth_cbr_sample(ptq);
1947 			if (err)
1948 				return err;
1949 		}
1950 		if (state->type & INTEL_PT_PWR_EVT) {
1951 			if (state->type & INTEL_PT_MWAIT_OP) {
1952 				err = intel_pt_synth_mwait_sample(ptq);
1953 				if (err)
1954 					return err;
1955 			}
1956 			if (state->type & INTEL_PT_PWR_ENTRY) {
1957 				err = intel_pt_synth_pwre_sample(ptq);
1958 				if (err)
1959 					return err;
1960 			}
1961 			if (state->type & INTEL_PT_EX_STOP) {
1962 				err = intel_pt_synth_exstop_sample(ptq);
1963 				if (err)
1964 					return err;
1965 			}
1966 			if (state->type & INTEL_PT_PWR_EXIT) {
1967 				err = intel_pt_synth_pwrx_sample(ptq);
1968 				if (err)
1969 					return err;
1970 			}
1971 		}
1972 	}
1973 
1974 	if (pt->sample_instructions && (state->type & INTEL_PT_INSTRUCTION)) {
1975 		err = intel_pt_synth_instruction_sample(ptq);
1976 		if (err)
1977 			return err;
1978 	}
1979 
1980 	if (pt->sample_transactions && (state->type & INTEL_PT_TRANSACTION)) {
1981 		err = intel_pt_synth_transaction_sample(ptq);
1982 		if (err)
1983 			return err;
1984 	}
1985 
1986 	if (pt->sample_ptwrites && (state->type & INTEL_PT_PTW)) {
1987 		err = intel_pt_synth_ptwrite_sample(ptq);
1988 		if (err)
1989 			return err;
1990 	}
1991 
1992 	if (!(state->type & INTEL_PT_BRANCH))
1993 		return 0;
1994 
1995 	if (pt->synth_opts.callchain || pt->synth_opts.thread_stack)
1996 		thread_stack__event(ptq->thread, ptq->cpu, ptq->flags, state->from_ip,
1997 				    state->to_ip, ptq->insn_len,
1998 				    state->trace_nr);
1999 	else
2000 		thread_stack__set_trace_nr(ptq->thread, ptq->cpu, state->trace_nr);
2001 
2002 	if (pt->sample_branches) {
2003 		err = intel_pt_synth_branch_sample(ptq);
2004 		if (err)
2005 			return err;
2006 	}
2007 
2008 	if (pt->synth_opts.last_branch)
2009 		intel_pt_update_last_branch_rb(ptq);
2010 
2011 	if (!ptq->sync_switch)
2012 		return 0;
2013 
2014 	if (intel_pt_is_switch_ip(ptq, state->to_ip)) {
2015 		switch (ptq->switch_state) {
2016 		case INTEL_PT_SS_NOT_TRACING:
2017 		case INTEL_PT_SS_UNKNOWN:
2018 		case INTEL_PT_SS_EXPECTING_SWITCH_IP:
2019 			err = intel_pt_next_tid(pt, ptq);
2020 			if (err)
2021 				return err;
2022 			ptq->switch_state = INTEL_PT_SS_TRACING;
2023 			break;
2024 		default:
2025 			ptq->switch_state = INTEL_PT_SS_EXPECTING_SWITCH_EVENT;
2026 			return 1;
2027 		}
2028 	} else if (!state->to_ip) {
2029 		ptq->switch_state = INTEL_PT_SS_NOT_TRACING;
2030 	} else if (ptq->switch_state == INTEL_PT_SS_NOT_TRACING) {
2031 		ptq->switch_state = INTEL_PT_SS_UNKNOWN;
2032 	} else if (ptq->switch_state == INTEL_PT_SS_UNKNOWN &&
2033 		   state->to_ip == pt->ptss_ip &&
2034 		   (ptq->flags & PERF_IP_FLAG_CALL)) {
2035 		ptq->switch_state = INTEL_PT_SS_TRACING;
2036 	}
2037 
2038 	return 0;
2039 }
2040 
2041 static u64 intel_pt_switch_ip(struct intel_pt *pt, u64 *ptss_ip)
2042 {
2043 	struct machine *machine = pt->machine;
2044 	struct map *map;
2045 	struct symbol *sym, *start;
2046 	u64 ip, switch_ip = 0;
2047 	const char *ptss;
2048 
2049 	if (ptss_ip)
2050 		*ptss_ip = 0;
2051 
2052 	map = machine__kernel_map(machine);
2053 	if (!map)
2054 		return 0;
2055 
2056 	if (map__load(map))
2057 		return 0;
2058 
2059 	start = dso__first_symbol(map->dso);
2060 
2061 	for (sym = start; sym; sym = dso__next_symbol(sym)) {
2062 		if (sym->binding == STB_GLOBAL &&
2063 		    !strcmp(sym->name, "__switch_to")) {
2064 			ip = map->unmap_ip(map, sym->start);
2065 			if (ip >= map->start && ip < map->end) {
2066 				switch_ip = ip;
2067 				break;
2068 			}
2069 		}
2070 	}
2071 
2072 	if (!switch_ip || !ptss_ip)
2073 		return 0;
2074 
2075 	if (pt->have_sched_switch == 1)
2076 		ptss = "perf_trace_sched_switch";
2077 	else
2078 		ptss = "__perf_event_task_sched_out";
2079 
2080 	for (sym = start; sym; sym = dso__next_symbol(sym)) {
2081 		if (!strcmp(sym->name, ptss)) {
2082 			ip = map->unmap_ip(map, sym->start);
2083 			if (ip >= map->start && ip < map->end) {
2084 				*ptss_ip = ip;
2085 				break;
2086 			}
2087 		}
2088 	}
2089 
2090 	return switch_ip;
2091 }
2092 
2093 static void intel_pt_enable_sync_switch(struct intel_pt *pt)
2094 {
2095 	unsigned int i;
2096 
2097 	pt->sync_switch = true;
2098 
2099 	for (i = 0; i < pt->queues.nr_queues; i++) {
2100 		struct auxtrace_queue *queue = &pt->queues.queue_array[i];
2101 		struct intel_pt_queue *ptq = queue->priv;
2102 
2103 		if (ptq)
2104 			ptq->sync_switch = true;
2105 	}
2106 }
2107 
2108 /*
2109  * To filter against time ranges, it is only necessary to look at the next start
2110  * or end time.
2111  */
2112 static bool intel_pt_next_time(struct intel_pt_queue *ptq)
2113 {
2114 	struct intel_pt *pt = ptq->pt;
2115 
2116 	if (ptq->sel_start) {
2117 		/* Next time is an end time */
2118 		ptq->sel_start = false;
2119 		ptq->sel_timestamp = pt->time_ranges[ptq->sel_idx].end;
2120 		return true;
2121 	} else if (ptq->sel_idx + 1 < pt->range_cnt) {
2122 		/* Next time is a start time */
2123 		ptq->sel_start = true;
2124 		ptq->sel_idx += 1;
2125 		ptq->sel_timestamp = pt->time_ranges[ptq->sel_idx].start;
2126 		return true;
2127 	}
2128 
2129 	/* No next time */
2130 	return false;
2131 }
2132 
2133 static int intel_pt_time_filter(struct intel_pt_queue *ptq, u64 *ff_timestamp)
2134 {
2135 	int err;
2136 
2137 	while (1) {
2138 		if (ptq->sel_start) {
2139 			if (ptq->timestamp >= ptq->sel_timestamp) {
2140 				/* After start time, so consider next time */
2141 				intel_pt_next_time(ptq);
2142 				if (!ptq->sel_timestamp) {
2143 					/* No end time */
2144 					return 0;
2145 				}
2146 				/* Check against end time */
2147 				continue;
2148 			}
2149 			/* Before start time, so fast forward */
2150 			ptq->have_sample = false;
2151 			if (ptq->sel_timestamp > *ff_timestamp) {
2152 				if (ptq->sync_switch) {
2153 					intel_pt_next_tid(ptq->pt, ptq);
2154 					ptq->switch_state = INTEL_PT_SS_UNKNOWN;
2155 				}
2156 				*ff_timestamp = ptq->sel_timestamp;
2157 				err = intel_pt_fast_forward(ptq->decoder,
2158 							    ptq->sel_timestamp);
2159 				if (err)
2160 					return err;
2161 			}
2162 			return 0;
2163 		} else if (ptq->timestamp > ptq->sel_timestamp) {
2164 			/* After end time, so consider next time */
2165 			if (!intel_pt_next_time(ptq)) {
2166 				/* No next time range, so stop decoding */
2167 				ptq->have_sample = false;
2168 				ptq->switch_state = INTEL_PT_SS_NOT_TRACING;
2169 				return 1;
2170 			}
2171 			/* Check against next start time */
2172 			continue;
2173 		} else {
2174 			/* Before end time */
2175 			return 0;
2176 		}
2177 	}
2178 }
2179 
2180 static int intel_pt_run_decoder(struct intel_pt_queue *ptq, u64 *timestamp)
2181 {
2182 	const struct intel_pt_state *state = ptq->state;
2183 	struct intel_pt *pt = ptq->pt;
2184 	u64 ff_timestamp = 0;
2185 	int err;
2186 
2187 	if (!pt->kernel_start) {
2188 		pt->kernel_start = machine__kernel_start(pt->machine);
2189 		if (pt->per_cpu_mmaps &&
2190 		    (pt->have_sched_switch == 1 || pt->have_sched_switch == 3) &&
2191 		    !pt->timeless_decoding && intel_pt_tracing_kernel(pt) &&
2192 		    !pt->sampling_mode) {
2193 			pt->switch_ip = intel_pt_switch_ip(pt, &pt->ptss_ip);
2194 			if (pt->switch_ip) {
2195 				intel_pt_log("switch_ip: %"PRIx64" ptss_ip: %"PRIx64"\n",
2196 					     pt->switch_ip, pt->ptss_ip);
2197 				intel_pt_enable_sync_switch(pt);
2198 			}
2199 		}
2200 	}
2201 
2202 	intel_pt_log("queue %u decoding cpu %d pid %d tid %d\n",
2203 		     ptq->queue_nr, ptq->cpu, ptq->pid, ptq->tid);
2204 	while (1) {
2205 		err = intel_pt_sample(ptq);
2206 		if (err)
2207 			return err;
2208 
2209 		state = intel_pt_decode(ptq->decoder);
2210 		if (state->err) {
2211 			if (state->err == INTEL_PT_ERR_NODATA)
2212 				return 1;
2213 			if (ptq->sync_switch &&
2214 			    state->from_ip >= pt->kernel_start) {
2215 				ptq->sync_switch = false;
2216 				intel_pt_next_tid(pt, ptq);
2217 			}
2218 			if (pt->synth_opts.errors) {
2219 				err = intel_ptq_synth_error(ptq, state);
2220 				if (err)
2221 					return err;
2222 			}
2223 			continue;
2224 		}
2225 
2226 		ptq->state = state;
2227 		ptq->have_sample = true;
2228 		intel_pt_sample_flags(ptq);
2229 
2230 		/* Use estimated TSC upon return to user space */
2231 		if (pt->est_tsc &&
2232 		    (state->from_ip >= pt->kernel_start || !state->from_ip) &&
2233 		    state->to_ip && state->to_ip < pt->kernel_start) {
2234 			intel_pt_log("TSC %"PRIx64" est. TSC %"PRIx64"\n",
2235 				     state->timestamp, state->est_timestamp);
2236 			ptq->timestamp = state->est_timestamp;
2237 		/* Use estimated TSC in unknown switch state */
2238 		} else if (ptq->sync_switch &&
2239 			   ptq->switch_state == INTEL_PT_SS_UNKNOWN &&
2240 			   intel_pt_is_switch_ip(ptq, state->to_ip) &&
2241 			   ptq->next_tid == -1) {
2242 			intel_pt_log("TSC %"PRIx64" est. TSC %"PRIx64"\n",
2243 				     state->timestamp, state->est_timestamp);
2244 			ptq->timestamp = state->est_timestamp;
2245 		} else if (state->timestamp > ptq->timestamp) {
2246 			ptq->timestamp = state->timestamp;
2247 		}
2248 
2249 		if (ptq->sel_timestamp) {
2250 			err = intel_pt_time_filter(ptq, &ff_timestamp);
2251 			if (err)
2252 				return err;
2253 		}
2254 
2255 		if (!pt->timeless_decoding && ptq->timestamp >= *timestamp) {
2256 			*timestamp = ptq->timestamp;
2257 			return 0;
2258 		}
2259 	}
2260 	return 0;
2261 }
2262 
2263 static inline int intel_pt_update_queues(struct intel_pt *pt)
2264 {
2265 	if (pt->queues.new_data) {
2266 		pt->queues.new_data = false;
2267 		return intel_pt_setup_queues(pt);
2268 	}
2269 	return 0;
2270 }
2271 
2272 static int intel_pt_process_queues(struct intel_pt *pt, u64 timestamp)
2273 {
2274 	unsigned int queue_nr;
2275 	u64 ts;
2276 	int ret;
2277 
2278 	while (1) {
2279 		struct auxtrace_queue *queue;
2280 		struct intel_pt_queue *ptq;
2281 
2282 		if (!pt->heap.heap_cnt)
2283 			return 0;
2284 
2285 		if (pt->heap.heap_array[0].ordinal >= timestamp)
2286 			return 0;
2287 
2288 		queue_nr = pt->heap.heap_array[0].queue_nr;
2289 		queue = &pt->queues.queue_array[queue_nr];
2290 		ptq = queue->priv;
2291 
2292 		intel_pt_log("queue %u processing 0x%" PRIx64 " to 0x%" PRIx64 "\n",
2293 			     queue_nr, pt->heap.heap_array[0].ordinal,
2294 			     timestamp);
2295 
2296 		auxtrace_heap__pop(&pt->heap);
2297 
2298 		if (pt->heap.heap_cnt) {
2299 			ts = pt->heap.heap_array[0].ordinal + 1;
2300 			if (ts > timestamp)
2301 				ts = timestamp;
2302 		} else {
2303 			ts = timestamp;
2304 		}
2305 
2306 		intel_pt_set_pid_tid_cpu(pt, queue);
2307 
2308 		ret = intel_pt_run_decoder(ptq, &ts);
2309 
2310 		if (ret < 0) {
2311 			auxtrace_heap__add(&pt->heap, queue_nr, ts);
2312 			return ret;
2313 		}
2314 
2315 		if (!ret) {
2316 			ret = auxtrace_heap__add(&pt->heap, queue_nr, ts);
2317 			if (ret < 0)
2318 				return ret;
2319 		} else {
2320 			ptq->on_heap = false;
2321 		}
2322 	}
2323 
2324 	return 0;
2325 }
2326 
2327 static int intel_pt_process_timeless_queues(struct intel_pt *pt, pid_t tid,
2328 					    u64 time_)
2329 {
2330 	struct auxtrace_queues *queues = &pt->queues;
2331 	unsigned int i;
2332 	u64 ts = 0;
2333 
2334 	for (i = 0; i < queues->nr_queues; i++) {
2335 		struct auxtrace_queue *queue = &pt->queues.queue_array[i];
2336 		struct intel_pt_queue *ptq = queue->priv;
2337 
2338 		if (ptq && (tid == -1 || ptq->tid == tid)) {
2339 			ptq->time = time_;
2340 			intel_pt_set_pid_tid_cpu(pt, queue);
2341 			intel_pt_run_decoder(ptq, &ts);
2342 		}
2343 	}
2344 	return 0;
2345 }
2346 
2347 static void intel_pt_sample_set_pid_tid_cpu(struct intel_pt_queue *ptq,
2348 					    struct auxtrace_queue *queue,
2349 					    struct perf_sample *sample)
2350 {
2351 	struct machine *m = ptq->pt->machine;
2352 
2353 	ptq->pid = sample->pid;
2354 	ptq->tid = sample->tid;
2355 	ptq->cpu = queue->cpu;
2356 
2357 	intel_pt_log("queue %u cpu %d pid %d tid %d\n",
2358 		     ptq->queue_nr, ptq->cpu, ptq->pid, ptq->tid);
2359 
2360 	thread__zput(ptq->thread);
2361 
2362 	if (ptq->tid == -1)
2363 		return;
2364 
2365 	if (ptq->pid == -1) {
2366 		ptq->thread = machine__find_thread(m, -1, ptq->tid);
2367 		if (ptq->thread)
2368 			ptq->pid = ptq->thread->pid_;
2369 		return;
2370 	}
2371 
2372 	ptq->thread = machine__findnew_thread(m, ptq->pid, ptq->tid);
2373 }
2374 
2375 static int intel_pt_process_timeless_sample(struct intel_pt *pt,
2376 					    struct perf_sample *sample)
2377 {
2378 	struct auxtrace_queue *queue;
2379 	struct intel_pt_queue *ptq;
2380 	u64 ts = 0;
2381 
2382 	queue = auxtrace_queues__sample_queue(&pt->queues, sample, pt->session);
2383 	if (!queue)
2384 		return -EINVAL;
2385 
2386 	ptq = queue->priv;
2387 	if (!ptq)
2388 		return 0;
2389 
2390 	ptq->stop = false;
2391 	ptq->time = sample->time;
2392 	intel_pt_sample_set_pid_tid_cpu(ptq, queue, sample);
2393 	intel_pt_run_decoder(ptq, &ts);
2394 	return 0;
2395 }
2396 
2397 static int intel_pt_lost(struct intel_pt *pt, struct perf_sample *sample)
2398 {
2399 	return intel_pt_synth_error(pt, INTEL_PT_ERR_LOST, sample->cpu,
2400 				    sample->pid, sample->tid, 0, sample->time);
2401 }
2402 
2403 static struct intel_pt_queue *intel_pt_cpu_to_ptq(struct intel_pt *pt, int cpu)
2404 {
2405 	unsigned i, j;
2406 
2407 	if (cpu < 0 || !pt->queues.nr_queues)
2408 		return NULL;
2409 
2410 	if ((unsigned)cpu >= pt->queues.nr_queues)
2411 		i = pt->queues.nr_queues - 1;
2412 	else
2413 		i = cpu;
2414 
2415 	if (pt->queues.queue_array[i].cpu == cpu)
2416 		return pt->queues.queue_array[i].priv;
2417 
2418 	for (j = 0; i > 0; j++) {
2419 		if (pt->queues.queue_array[--i].cpu == cpu)
2420 			return pt->queues.queue_array[i].priv;
2421 	}
2422 
2423 	for (; j < pt->queues.nr_queues; j++) {
2424 		if (pt->queues.queue_array[j].cpu == cpu)
2425 			return pt->queues.queue_array[j].priv;
2426 	}
2427 
2428 	return NULL;
2429 }
2430 
2431 static int intel_pt_sync_switch(struct intel_pt *pt, int cpu, pid_t tid,
2432 				u64 timestamp)
2433 {
2434 	struct intel_pt_queue *ptq;
2435 	int err;
2436 
2437 	if (!pt->sync_switch)
2438 		return 1;
2439 
2440 	ptq = intel_pt_cpu_to_ptq(pt, cpu);
2441 	if (!ptq || !ptq->sync_switch)
2442 		return 1;
2443 
2444 	switch (ptq->switch_state) {
2445 	case INTEL_PT_SS_NOT_TRACING:
2446 		break;
2447 	case INTEL_PT_SS_UNKNOWN:
2448 	case INTEL_PT_SS_TRACING:
2449 		ptq->next_tid = tid;
2450 		ptq->switch_state = INTEL_PT_SS_EXPECTING_SWITCH_IP;
2451 		return 0;
2452 	case INTEL_PT_SS_EXPECTING_SWITCH_EVENT:
2453 		if (!ptq->on_heap) {
2454 			ptq->timestamp = perf_time_to_tsc(timestamp,
2455 							  &pt->tc);
2456 			err = auxtrace_heap__add(&pt->heap, ptq->queue_nr,
2457 						 ptq->timestamp);
2458 			if (err)
2459 				return err;
2460 			ptq->on_heap = true;
2461 		}
2462 		ptq->switch_state = INTEL_PT_SS_TRACING;
2463 		break;
2464 	case INTEL_PT_SS_EXPECTING_SWITCH_IP:
2465 		intel_pt_log("ERROR: cpu %d expecting switch ip\n", cpu);
2466 		break;
2467 	default:
2468 		break;
2469 	}
2470 
2471 	ptq->next_tid = -1;
2472 
2473 	return 1;
2474 }
2475 
2476 static int intel_pt_process_switch(struct intel_pt *pt,
2477 				   struct perf_sample *sample)
2478 {
2479 	struct evsel *evsel;
2480 	pid_t tid;
2481 	int cpu, ret;
2482 
2483 	evsel = perf_evlist__id2evsel(pt->session->evlist, sample->id);
2484 	if (evsel != pt->switch_evsel)
2485 		return 0;
2486 
2487 	tid = perf_evsel__intval(evsel, sample, "next_pid");
2488 	cpu = sample->cpu;
2489 
2490 	intel_pt_log("sched_switch: cpu %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
2491 		     cpu, tid, sample->time, perf_time_to_tsc(sample->time,
2492 		     &pt->tc));
2493 
2494 	ret = intel_pt_sync_switch(pt, cpu, tid, sample->time);
2495 	if (ret <= 0)
2496 		return ret;
2497 
2498 	return machine__set_current_tid(pt->machine, cpu, -1, tid);
2499 }
2500 
2501 static int intel_pt_context_switch_in(struct intel_pt *pt,
2502 				      struct perf_sample *sample)
2503 {
2504 	pid_t pid = sample->pid;
2505 	pid_t tid = sample->tid;
2506 	int cpu = sample->cpu;
2507 
2508 	if (pt->sync_switch) {
2509 		struct intel_pt_queue *ptq;
2510 
2511 		ptq = intel_pt_cpu_to_ptq(pt, cpu);
2512 		if (ptq && ptq->sync_switch) {
2513 			ptq->next_tid = -1;
2514 			switch (ptq->switch_state) {
2515 			case INTEL_PT_SS_NOT_TRACING:
2516 			case INTEL_PT_SS_UNKNOWN:
2517 			case INTEL_PT_SS_TRACING:
2518 				break;
2519 			case INTEL_PT_SS_EXPECTING_SWITCH_EVENT:
2520 			case INTEL_PT_SS_EXPECTING_SWITCH_IP:
2521 				ptq->switch_state = INTEL_PT_SS_TRACING;
2522 				break;
2523 			default:
2524 				break;
2525 			}
2526 		}
2527 	}
2528 
2529 	/*
2530 	 * If the current tid has not been updated yet, ensure it is now that
2531 	 * a "switch in" event has occurred.
2532 	 */
2533 	if (machine__get_current_tid(pt->machine, cpu) == tid)
2534 		return 0;
2535 
2536 	return machine__set_current_tid(pt->machine, cpu, pid, tid);
2537 }
2538 
2539 static int intel_pt_context_switch(struct intel_pt *pt, union perf_event *event,
2540 				   struct perf_sample *sample)
2541 {
2542 	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
2543 	pid_t pid, tid;
2544 	int cpu, ret;
2545 
2546 	cpu = sample->cpu;
2547 
2548 	if (pt->have_sched_switch == 3) {
2549 		if (!out)
2550 			return intel_pt_context_switch_in(pt, sample);
2551 		if (event->header.type != PERF_RECORD_SWITCH_CPU_WIDE) {
2552 			pr_err("Expecting CPU-wide context switch event\n");
2553 			return -EINVAL;
2554 		}
2555 		pid = event->context_switch.next_prev_pid;
2556 		tid = event->context_switch.next_prev_tid;
2557 	} else {
2558 		if (out)
2559 			return 0;
2560 		pid = sample->pid;
2561 		tid = sample->tid;
2562 	}
2563 
2564 	if (tid == -1) {
2565 		pr_err("context_switch event has no tid\n");
2566 		return -EINVAL;
2567 	}
2568 
2569 	intel_pt_log("context_switch: cpu %d pid %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
2570 		     cpu, pid, tid, sample->time, perf_time_to_tsc(sample->time,
2571 		     &pt->tc));
2572 
2573 	ret = intel_pt_sync_switch(pt, cpu, tid, sample->time);
2574 	if (ret <= 0)
2575 		return ret;
2576 
2577 	return machine__set_current_tid(pt->machine, cpu, pid, tid);
2578 }
2579 
2580 static int intel_pt_process_itrace_start(struct intel_pt *pt,
2581 					 union perf_event *event,
2582 					 struct perf_sample *sample)
2583 {
2584 	if (!pt->per_cpu_mmaps)
2585 		return 0;
2586 
2587 	intel_pt_log("itrace_start: cpu %d pid %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
2588 		     sample->cpu, event->itrace_start.pid,
2589 		     event->itrace_start.tid, sample->time,
2590 		     perf_time_to_tsc(sample->time, &pt->tc));
2591 
2592 	return machine__set_current_tid(pt->machine, sample->cpu,
2593 					event->itrace_start.pid,
2594 					event->itrace_start.tid);
2595 }
2596 
2597 static int intel_pt_process_event(struct perf_session *session,
2598 				  union perf_event *event,
2599 				  struct perf_sample *sample,
2600 				  struct perf_tool *tool)
2601 {
2602 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2603 					   auxtrace);
2604 	u64 timestamp;
2605 	int err = 0;
2606 
2607 	if (dump_trace)
2608 		return 0;
2609 
2610 	if (!tool->ordered_events) {
2611 		pr_err("Intel Processor Trace requires ordered events\n");
2612 		return -EINVAL;
2613 	}
2614 
2615 	if (sample->time && sample->time != (u64)-1)
2616 		timestamp = perf_time_to_tsc(sample->time, &pt->tc);
2617 	else
2618 		timestamp = 0;
2619 
2620 	if (timestamp || pt->timeless_decoding) {
2621 		err = intel_pt_update_queues(pt);
2622 		if (err)
2623 			return err;
2624 	}
2625 
2626 	if (pt->timeless_decoding) {
2627 		if (pt->sampling_mode) {
2628 			if (sample->aux_sample.size)
2629 				err = intel_pt_process_timeless_sample(pt,
2630 								       sample);
2631 		} else if (event->header.type == PERF_RECORD_EXIT) {
2632 			err = intel_pt_process_timeless_queues(pt,
2633 							       event->fork.tid,
2634 							       sample->time);
2635 		}
2636 	} else if (timestamp) {
2637 		err = intel_pt_process_queues(pt, timestamp);
2638 	}
2639 	if (err)
2640 		return err;
2641 
2642 	if (event->header.type == PERF_RECORD_AUX &&
2643 	    (event->aux.flags & PERF_AUX_FLAG_TRUNCATED) &&
2644 	    pt->synth_opts.errors) {
2645 		err = intel_pt_lost(pt, sample);
2646 		if (err)
2647 			return err;
2648 	}
2649 
2650 	if (pt->switch_evsel && event->header.type == PERF_RECORD_SAMPLE)
2651 		err = intel_pt_process_switch(pt, sample);
2652 	else if (event->header.type == PERF_RECORD_ITRACE_START)
2653 		err = intel_pt_process_itrace_start(pt, event, sample);
2654 	else if (event->header.type == PERF_RECORD_SWITCH ||
2655 		 event->header.type == PERF_RECORD_SWITCH_CPU_WIDE)
2656 		err = intel_pt_context_switch(pt, event, sample);
2657 
2658 	intel_pt_log("event %u: cpu %d time %"PRIu64" tsc %#"PRIx64" ",
2659 		     event->header.type, sample->cpu, sample->time, timestamp);
2660 	intel_pt_log_event(event);
2661 
2662 	return err;
2663 }
2664 
2665 static int intel_pt_flush(struct perf_session *session, struct perf_tool *tool)
2666 {
2667 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2668 					   auxtrace);
2669 	int ret;
2670 
2671 	if (dump_trace)
2672 		return 0;
2673 
2674 	if (!tool->ordered_events)
2675 		return -EINVAL;
2676 
2677 	ret = intel_pt_update_queues(pt);
2678 	if (ret < 0)
2679 		return ret;
2680 
2681 	if (pt->timeless_decoding)
2682 		return intel_pt_process_timeless_queues(pt, -1,
2683 							MAX_TIMESTAMP - 1);
2684 
2685 	return intel_pt_process_queues(pt, MAX_TIMESTAMP);
2686 }
2687 
2688 static void intel_pt_free_events(struct perf_session *session)
2689 {
2690 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2691 					   auxtrace);
2692 	struct auxtrace_queues *queues = &pt->queues;
2693 	unsigned int i;
2694 
2695 	for (i = 0; i < queues->nr_queues; i++) {
2696 		intel_pt_free_queue(queues->queue_array[i].priv);
2697 		queues->queue_array[i].priv = NULL;
2698 	}
2699 	intel_pt_log_disable();
2700 	auxtrace_queues__free(queues);
2701 }
2702 
2703 static void intel_pt_free(struct perf_session *session)
2704 {
2705 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2706 					   auxtrace);
2707 
2708 	auxtrace_heap__free(&pt->heap);
2709 	intel_pt_free_events(session);
2710 	session->auxtrace = NULL;
2711 	thread__put(pt->unknown_thread);
2712 	addr_filters__exit(&pt->filts);
2713 	zfree(&pt->filter);
2714 	zfree(&pt->time_ranges);
2715 	free(pt);
2716 }
2717 
2718 static int intel_pt_process_auxtrace_event(struct perf_session *session,
2719 					   union perf_event *event,
2720 					   struct perf_tool *tool __maybe_unused)
2721 {
2722 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2723 					   auxtrace);
2724 
2725 	if (!pt->data_queued) {
2726 		struct auxtrace_buffer *buffer;
2727 		off_t data_offset;
2728 		int fd = perf_data__fd(session->data);
2729 		int err;
2730 
2731 		if (perf_data__is_pipe(session->data)) {
2732 			data_offset = 0;
2733 		} else {
2734 			data_offset = lseek(fd, 0, SEEK_CUR);
2735 			if (data_offset == -1)
2736 				return -errno;
2737 		}
2738 
2739 		err = auxtrace_queues__add_event(&pt->queues, session, event,
2740 						 data_offset, &buffer);
2741 		if (err)
2742 			return err;
2743 
2744 		/* Dump here now we have copied a piped trace out of the pipe */
2745 		if (dump_trace) {
2746 			if (auxtrace_buffer__get_data(buffer, fd)) {
2747 				intel_pt_dump_event(pt, buffer->data,
2748 						    buffer->size);
2749 				auxtrace_buffer__put_data(buffer);
2750 			}
2751 		}
2752 	}
2753 
2754 	return 0;
2755 }
2756 
2757 static int intel_pt_queue_data(struct perf_session *session,
2758 			       struct perf_sample *sample,
2759 			       union perf_event *event, u64 data_offset)
2760 {
2761 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2762 					   auxtrace);
2763 	u64 timestamp;
2764 
2765 	if (event) {
2766 		return auxtrace_queues__add_event(&pt->queues, session, event,
2767 						  data_offset, NULL);
2768 	}
2769 
2770 	if (sample->time && sample->time != (u64)-1)
2771 		timestamp = perf_time_to_tsc(sample->time, &pt->tc);
2772 	else
2773 		timestamp = 0;
2774 
2775 	return auxtrace_queues__add_sample(&pt->queues, session, sample,
2776 					   data_offset, timestamp);
2777 }
2778 
2779 struct intel_pt_synth {
2780 	struct perf_tool dummy_tool;
2781 	struct perf_session *session;
2782 };
2783 
2784 static int intel_pt_event_synth(struct perf_tool *tool,
2785 				union perf_event *event,
2786 				struct perf_sample *sample __maybe_unused,
2787 				struct machine *machine __maybe_unused)
2788 {
2789 	struct intel_pt_synth *intel_pt_synth =
2790 			container_of(tool, struct intel_pt_synth, dummy_tool);
2791 
2792 	return perf_session__deliver_synth_event(intel_pt_synth->session, event,
2793 						 NULL);
2794 }
2795 
2796 static int intel_pt_synth_event(struct perf_session *session, const char *name,
2797 				struct perf_event_attr *attr, u64 id)
2798 {
2799 	struct intel_pt_synth intel_pt_synth;
2800 	int err;
2801 
2802 	pr_debug("Synthesizing '%s' event with id %" PRIu64 " sample type %#" PRIx64 "\n",
2803 		 name, id, (u64)attr->sample_type);
2804 
2805 	memset(&intel_pt_synth, 0, sizeof(struct intel_pt_synth));
2806 	intel_pt_synth.session = session;
2807 
2808 	err = perf_event__synthesize_attr(&intel_pt_synth.dummy_tool, attr, 1,
2809 					  &id, intel_pt_event_synth);
2810 	if (err)
2811 		pr_err("%s: failed to synthesize '%s' event type\n",
2812 		       __func__, name);
2813 
2814 	return err;
2815 }
2816 
2817 static void intel_pt_set_event_name(struct evlist *evlist, u64 id,
2818 				    const char *name)
2819 {
2820 	struct evsel *evsel;
2821 
2822 	evlist__for_each_entry(evlist, evsel) {
2823 		if (evsel->core.id && evsel->core.id[0] == id) {
2824 			if (evsel->name)
2825 				zfree(&evsel->name);
2826 			evsel->name = strdup(name);
2827 			break;
2828 		}
2829 	}
2830 }
2831 
2832 static struct evsel *intel_pt_evsel(struct intel_pt *pt,
2833 					 struct evlist *evlist)
2834 {
2835 	struct evsel *evsel;
2836 
2837 	evlist__for_each_entry(evlist, evsel) {
2838 		if (evsel->core.attr.type == pt->pmu_type && evsel->core.ids)
2839 			return evsel;
2840 	}
2841 
2842 	return NULL;
2843 }
2844 
2845 static int intel_pt_synth_events(struct intel_pt *pt,
2846 				 struct perf_session *session)
2847 {
2848 	struct evlist *evlist = session->evlist;
2849 	struct evsel *evsel = intel_pt_evsel(pt, evlist);
2850 	struct perf_event_attr attr;
2851 	u64 id;
2852 	int err;
2853 
2854 	if (!evsel) {
2855 		pr_debug("There are no selected events with Intel Processor Trace data\n");
2856 		return 0;
2857 	}
2858 
2859 	memset(&attr, 0, sizeof(struct perf_event_attr));
2860 	attr.size = sizeof(struct perf_event_attr);
2861 	attr.type = PERF_TYPE_HARDWARE;
2862 	attr.sample_type = evsel->core.attr.sample_type & PERF_SAMPLE_MASK;
2863 	attr.sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID |
2864 			    PERF_SAMPLE_PERIOD;
2865 	if (pt->timeless_decoding)
2866 		attr.sample_type &= ~(u64)PERF_SAMPLE_TIME;
2867 	else
2868 		attr.sample_type |= PERF_SAMPLE_TIME;
2869 	if (!pt->per_cpu_mmaps)
2870 		attr.sample_type &= ~(u64)PERF_SAMPLE_CPU;
2871 	attr.exclude_user = evsel->core.attr.exclude_user;
2872 	attr.exclude_kernel = evsel->core.attr.exclude_kernel;
2873 	attr.exclude_hv = evsel->core.attr.exclude_hv;
2874 	attr.exclude_host = evsel->core.attr.exclude_host;
2875 	attr.exclude_guest = evsel->core.attr.exclude_guest;
2876 	attr.sample_id_all = evsel->core.attr.sample_id_all;
2877 	attr.read_format = evsel->core.attr.read_format;
2878 
2879 	id = evsel->core.id[0] + 1000000000;
2880 	if (!id)
2881 		id = 1;
2882 
2883 	if (pt->synth_opts.branches) {
2884 		attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
2885 		attr.sample_period = 1;
2886 		attr.sample_type |= PERF_SAMPLE_ADDR;
2887 		err = intel_pt_synth_event(session, "branches", &attr, id);
2888 		if (err)
2889 			return err;
2890 		pt->sample_branches = true;
2891 		pt->branches_sample_type = attr.sample_type;
2892 		pt->branches_id = id;
2893 		id += 1;
2894 		attr.sample_type &= ~(u64)PERF_SAMPLE_ADDR;
2895 	}
2896 
2897 	if (pt->synth_opts.callchain)
2898 		attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2899 	if (pt->synth_opts.last_branch)
2900 		attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
2901 
2902 	if (pt->synth_opts.instructions) {
2903 		attr.config = PERF_COUNT_HW_INSTRUCTIONS;
2904 		if (pt->synth_opts.period_type == PERF_ITRACE_PERIOD_NANOSECS)
2905 			attr.sample_period =
2906 				intel_pt_ns_to_ticks(pt, pt->synth_opts.period);
2907 		else
2908 			attr.sample_period = pt->synth_opts.period;
2909 		err = intel_pt_synth_event(session, "instructions", &attr, id);
2910 		if (err)
2911 			return err;
2912 		pt->sample_instructions = true;
2913 		pt->instructions_sample_type = attr.sample_type;
2914 		pt->instructions_id = id;
2915 		id += 1;
2916 	}
2917 
2918 	attr.sample_type &= ~(u64)PERF_SAMPLE_PERIOD;
2919 	attr.sample_period = 1;
2920 
2921 	if (pt->synth_opts.transactions) {
2922 		attr.config = PERF_COUNT_HW_INSTRUCTIONS;
2923 		err = intel_pt_synth_event(session, "transactions", &attr, id);
2924 		if (err)
2925 			return err;
2926 		pt->sample_transactions = true;
2927 		pt->transactions_sample_type = attr.sample_type;
2928 		pt->transactions_id = id;
2929 		intel_pt_set_event_name(evlist, id, "transactions");
2930 		id += 1;
2931 	}
2932 
2933 	attr.type = PERF_TYPE_SYNTH;
2934 	attr.sample_type |= PERF_SAMPLE_RAW;
2935 
2936 	if (pt->synth_opts.ptwrites) {
2937 		attr.config = PERF_SYNTH_INTEL_PTWRITE;
2938 		err = intel_pt_synth_event(session, "ptwrite", &attr, id);
2939 		if (err)
2940 			return err;
2941 		pt->sample_ptwrites = true;
2942 		pt->ptwrites_sample_type = attr.sample_type;
2943 		pt->ptwrites_id = id;
2944 		intel_pt_set_event_name(evlist, id, "ptwrite");
2945 		id += 1;
2946 	}
2947 
2948 	if (pt->synth_opts.pwr_events) {
2949 		pt->sample_pwr_events = true;
2950 		pt->pwr_events_sample_type = attr.sample_type;
2951 
2952 		attr.config = PERF_SYNTH_INTEL_CBR;
2953 		err = intel_pt_synth_event(session, "cbr", &attr, id);
2954 		if (err)
2955 			return err;
2956 		pt->cbr_id = id;
2957 		intel_pt_set_event_name(evlist, id, "cbr");
2958 		id += 1;
2959 	}
2960 
2961 	if (pt->synth_opts.pwr_events && (evsel->core.attr.config & 0x10)) {
2962 		attr.config = PERF_SYNTH_INTEL_MWAIT;
2963 		err = intel_pt_synth_event(session, "mwait", &attr, id);
2964 		if (err)
2965 			return err;
2966 		pt->mwait_id = id;
2967 		intel_pt_set_event_name(evlist, id, "mwait");
2968 		id += 1;
2969 
2970 		attr.config = PERF_SYNTH_INTEL_PWRE;
2971 		err = intel_pt_synth_event(session, "pwre", &attr, id);
2972 		if (err)
2973 			return err;
2974 		pt->pwre_id = id;
2975 		intel_pt_set_event_name(evlist, id, "pwre");
2976 		id += 1;
2977 
2978 		attr.config = PERF_SYNTH_INTEL_EXSTOP;
2979 		err = intel_pt_synth_event(session, "exstop", &attr, id);
2980 		if (err)
2981 			return err;
2982 		pt->exstop_id = id;
2983 		intel_pt_set_event_name(evlist, id, "exstop");
2984 		id += 1;
2985 
2986 		attr.config = PERF_SYNTH_INTEL_PWRX;
2987 		err = intel_pt_synth_event(session, "pwrx", &attr, id);
2988 		if (err)
2989 			return err;
2990 		pt->pwrx_id = id;
2991 		intel_pt_set_event_name(evlist, id, "pwrx");
2992 		id += 1;
2993 	}
2994 
2995 	return 0;
2996 }
2997 
2998 static void intel_pt_setup_pebs_events(struct intel_pt *pt)
2999 {
3000 	struct evsel *evsel;
3001 
3002 	if (!pt->synth_opts.other_events)
3003 		return;
3004 
3005 	evlist__for_each_entry(pt->session->evlist, evsel) {
3006 		if (evsel->core.attr.aux_output && evsel->core.id) {
3007 			pt->sample_pebs = true;
3008 			pt->pebs_evsel = evsel;
3009 			return;
3010 		}
3011 	}
3012 }
3013 
3014 static struct evsel *intel_pt_find_sched_switch(struct evlist *evlist)
3015 {
3016 	struct evsel *evsel;
3017 
3018 	evlist__for_each_entry_reverse(evlist, evsel) {
3019 		const char *name = perf_evsel__name(evsel);
3020 
3021 		if (!strcmp(name, "sched:sched_switch"))
3022 			return evsel;
3023 	}
3024 
3025 	return NULL;
3026 }
3027 
3028 static bool intel_pt_find_switch(struct evlist *evlist)
3029 {
3030 	struct evsel *evsel;
3031 
3032 	evlist__for_each_entry(evlist, evsel) {
3033 		if (evsel->core.attr.context_switch)
3034 			return true;
3035 	}
3036 
3037 	return false;
3038 }
3039 
3040 static int intel_pt_perf_config(const char *var, const char *value, void *data)
3041 {
3042 	struct intel_pt *pt = data;
3043 
3044 	if (!strcmp(var, "intel-pt.mispred-all"))
3045 		pt->mispred_all = perf_config_bool(var, value);
3046 
3047 	return 0;
3048 }
3049 
3050 /* Find least TSC which converts to ns or later */
3051 static u64 intel_pt_tsc_start(u64 ns, struct intel_pt *pt)
3052 {
3053 	u64 tsc, tm;
3054 
3055 	tsc = perf_time_to_tsc(ns, &pt->tc);
3056 
3057 	while (1) {
3058 		tm = tsc_to_perf_time(tsc, &pt->tc);
3059 		if (tm < ns)
3060 			break;
3061 		tsc -= 1;
3062 	}
3063 
3064 	while (tm < ns)
3065 		tm = tsc_to_perf_time(++tsc, &pt->tc);
3066 
3067 	return tsc;
3068 }
3069 
3070 /* Find greatest TSC which converts to ns or earlier */
3071 static u64 intel_pt_tsc_end(u64 ns, struct intel_pt *pt)
3072 {
3073 	u64 tsc, tm;
3074 
3075 	tsc = perf_time_to_tsc(ns, &pt->tc);
3076 
3077 	while (1) {
3078 		tm = tsc_to_perf_time(tsc, &pt->tc);
3079 		if (tm > ns)
3080 			break;
3081 		tsc += 1;
3082 	}
3083 
3084 	while (tm > ns)
3085 		tm = tsc_to_perf_time(--tsc, &pt->tc);
3086 
3087 	return tsc;
3088 }
3089 
3090 static int intel_pt_setup_time_ranges(struct intel_pt *pt,
3091 				      struct itrace_synth_opts *opts)
3092 {
3093 	struct perf_time_interval *p = opts->ptime_range;
3094 	int n = opts->range_num;
3095 	int i;
3096 
3097 	if (!n || !p || pt->timeless_decoding)
3098 		return 0;
3099 
3100 	pt->time_ranges = calloc(n, sizeof(struct range));
3101 	if (!pt->time_ranges)
3102 		return -ENOMEM;
3103 
3104 	pt->range_cnt = n;
3105 
3106 	intel_pt_log("%s: %u range(s)\n", __func__, n);
3107 
3108 	for (i = 0; i < n; i++) {
3109 		struct range *r = &pt->time_ranges[i];
3110 		u64 ts = p[i].start;
3111 		u64 te = p[i].end;
3112 
3113 		/*
3114 		 * Take care to ensure the TSC range matches the perf-time range
3115 		 * when converted back to perf-time.
3116 		 */
3117 		r->start = ts ? intel_pt_tsc_start(ts, pt) : 0;
3118 		r->end   = te ? intel_pt_tsc_end(te, pt) : 0;
3119 
3120 		intel_pt_log("range %d: perf time interval: %"PRIu64" to %"PRIu64"\n",
3121 			     i, ts, te);
3122 		intel_pt_log("range %d: TSC time interval: %#"PRIx64" to %#"PRIx64"\n",
3123 			     i, r->start, r->end);
3124 	}
3125 
3126 	return 0;
3127 }
3128 
3129 static const char * const intel_pt_info_fmts[] = {
3130 	[INTEL_PT_PMU_TYPE]		= "  PMU Type            %"PRId64"\n",
3131 	[INTEL_PT_TIME_SHIFT]		= "  Time Shift          %"PRIu64"\n",
3132 	[INTEL_PT_TIME_MULT]		= "  Time Muliplier      %"PRIu64"\n",
3133 	[INTEL_PT_TIME_ZERO]		= "  Time Zero           %"PRIu64"\n",
3134 	[INTEL_PT_CAP_USER_TIME_ZERO]	= "  Cap Time Zero       %"PRId64"\n",
3135 	[INTEL_PT_TSC_BIT]		= "  TSC bit             %#"PRIx64"\n",
3136 	[INTEL_PT_NORETCOMP_BIT]	= "  NoRETComp bit       %#"PRIx64"\n",
3137 	[INTEL_PT_HAVE_SCHED_SWITCH]	= "  Have sched_switch   %"PRId64"\n",
3138 	[INTEL_PT_SNAPSHOT_MODE]	= "  Snapshot mode       %"PRId64"\n",
3139 	[INTEL_PT_PER_CPU_MMAPS]	= "  Per-cpu maps        %"PRId64"\n",
3140 	[INTEL_PT_MTC_BIT]		= "  MTC bit             %#"PRIx64"\n",
3141 	[INTEL_PT_TSC_CTC_N]		= "  TSC:CTC numerator   %"PRIu64"\n",
3142 	[INTEL_PT_TSC_CTC_D]		= "  TSC:CTC denominator %"PRIu64"\n",
3143 	[INTEL_PT_CYC_BIT]		= "  CYC bit             %#"PRIx64"\n",
3144 	[INTEL_PT_MAX_NONTURBO_RATIO]	= "  Max non-turbo ratio %"PRIu64"\n",
3145 	[INTEL_PT_FILTER_STR_LEN]	= "  Filter string len.  %"PRIu64"\n",
3146 };
3147 
3148 static void intel_pt_print_info(__u64 *arr, int start, int finish)
3149 {
3150 	int i;
3151 
3152 	if (!dump_trace)
3153 		return;
3154 
3155 	for (i = start; i <= finish; i++)
3156 		fprintf(stdout, intel_pt_info_fmts[i], arr[i]);
3157 }
3158 
3159 static void intel_pt_print_info_str(const char *name, const char *str)
3160 {
3161 	if (!dump_trace)
3162 		return;
3163 
3164 	fprintf(stdout, "  %-20s%s\n", name, str ? str : "");
3165 }
3166 
3167 static bool intel_pt_has(struct perf_record_auxtrace_info *auxtrace_info, int pos)
3168 {
3169 	return auxtrace_info->header.size >=
3170 		sizeof(struct perf_record_auxtrace_info) + (sizeof(u64) * (pos + 1));
3171 }
3172 
3173 int intel_pt_process_auxtrace_info(union perf_event *event,
3174 				   struct perf_session *session)
3175 {
3176 	struct perf_record_auxtrace_info *auxtrace_info = &event->auxtrace_info;
3177 	size_t min_sz = sizeof(u64) * INTEL_PT_PER_CPU_MMAPS;
3178 	struct intel_pt *pt;
3179 	void *info_end;
3180 	__u64 *info;
3181 	int err;
3182 
3183 	if (auxtrace_info->header.size < sizeof(struct perf_record_auxtrace_info) +
3184 					min_sz)
3185 		return -EINVAL;
3186 
3187 	pt = zalloc(sizeof(struct intel_pt));
3188 	if (!pt)
3189 		return -ENOMEM;
3190 
3191 	addr_filters__init(&pt->filts);
3192 
3193 	err = perf_config(intel_pt_perf_config, pt);
3194 	if (err)
3195 		goto err_free;
3196 
3197 	err = auxtrace_queues__init(&pt->queues);
3198 	if (err)
3199 		goto err_free;
3200 
3201 	intel_pt_log_set_name(INTEL_PT_PMU_NAME);
3202 
3203 	pt->session = session;
3204 	pt->machine = &session->machines.host; /* No kvm support */
3205 	pt->auxtrace_type = auxtrace_info->type;
3206 	pt->pmu_type = auxtrace_info->priv[INTEL_PT_PMU_TYPE];
3207 	pt->tc.time_shift = auxtrace_info->priv[INTEL_PT_TIME_SHIFT];
3208 	pt->tc.time_mult = auxtrace_info->priv[INTEL_PT_TIME_MULT];
3209 	pt->tc.time_zero = auxtrace_info->priv[INTEL_PT_TIME_ZERO];
3210 	pt->cap_user_time_zero = auxtrace_info->priv[INTEL_PT_CAP_USER_TIME_ZERO];
3211 	pt->tsc_bit = auxtrace_info->priv[INTEL_PT_TSC_BIT];
3212 	pt->noretcomp_bit = auxtrace_info->priv[INTEL_PT_NORETCOMP_BIT];
3213 	pt->have_sched_switch = auxtrace_info->priv[INTEL_PT_HAVE_SCHED_SWITCH];
3214 	pt->snapshot_mode = auxtrace_info->priv[INTEL_PT_SNAPSHOT_MODE];
3215 	pt->per_cpu_mmaps = auxtrace_info->priv[INTEL_PT_PER_CPU_MMAPS];
3216 	intel_pt_print_info(&auxtrace_info->priv[0], INTEL_PT_PMU_TYPE,
3217 			    INTEL_PT_PER_CPU_MMAPS);
3218 
3219 	if (intel_pt_has(auxtrace_info, INTEL_PT_CYC_BIT)) {
3220 		pt->mtc_bit = auxtrace_info->priv[INTEL_PT_MTC_BIT];
3221 		pt->mtc_freq_bits = auxtrace_info->priv[INTEL_PT_MTC_FREQ_BITS];
3222 		pt->tsc_ctc_ratio_n = auxtrace_info->priv[INTEL_PT_TSC_CTC_N];
3223 		pt->tsc_ctc_ratio_d = auxtrace_info->priv[INTEL_PT_TSC_CTC_D];
3224 		pt->cyc_bit = auxtrace_info->priv[INTEL_PT_CYC_BIT];
3225 		intel_pt_print_info(&auxtrace_info->priv[0], INTEL_PT_MTC_BIT,
3226 				    INTEL_PT_CYC_BIT);
3227 	}
3228 
3229 	if (intel_pt_has(auxtrace_info, INTEL_PT_MAX_NONTURBO_RATIO)) {
3230 		pt->max_non_turbo_ratio =
3231 			auxtrace_info->priv[INTEL_PT_MAX_NONTURBO_RATIO];
3232 		intel_pt_print_info(&auxtrace_info->priv[0],
3233 				    INTEL_PT_MAX_NONTURBO_RATIO,
3234 				    INTEL_PT_MAX_NONTURBO_RATIO);
3235 	}
3236 
3237 	info = &auxtrace_info->priv[INTEL_PT_FILTER_STR_LEN] + 1;
3238 	info_end = (void *)info + auxtrace_info->header.size;
3239 
3240 	if (intel_pt_has(auxtrace_info, INTEL_PT_FILTER_STR_LEN)) {
3241 		size_t len;
3242 
3243 		len = auxtrace_info->priv[INTEL_PT_FILTER_STR_LEN];
3244 		intel_pt_print_info(&auxtrace_info->priv[0],
3245 				    INTEL_PT_FILTER_STR_LEN,
3246 				    INTEL_PT_FILTER_STR_LEN);
3247 		if (len) {
3248 			const char *filter = (const char *)info;
3249 
3250 			len = roundup(len + 1, 8);
3251 			info += len >> 3;
3252 			if ((void *)info > info_end) {
3253 				pr_err("%s: bad filter string length\n", __func__);
3254 				err = -EINVAL;
3255 				goto err_free_queues;
3256 			}
3257 			pt->filter = memdup(filter, len);
3258 			if (!pt->filter) {
3259 				err = -ENOMEM;
3260 				goto err_free_queues;
3261 			}
3262 			if (session->header.needs_swap)
3263 				mem_bswap_64(pt->filter, len);
3264 			if (pt->filter[len - 1]) {
3265 				pr_err("%s: filter string not null terminated\n", __func__);
3266 				err = -EINVAL;
3267 				goto err_free_queues;
3268 			}
3269 			err = addr_filters__parse_bare_filter(&pt->filts,
3270 							      filter);
3271 			if (err)
3272 				goto err_free_queues;
3273 		}
3274 		intel_pt_print_info_str("Filter string", pt->filter);
3275 	}
3276 
3277 	pt->timeless_decoding = intel_pt_timeless_decoding(pt);
3278 	if (pt->timeless_decoding && !pt->tc.time_mult)
3279 		pt->tc.time_mult = 1;
3280 	pt->have_tsc = intel_pt_have_tsc(pt);
3281 	pt->sampling_mode = intel_pt_sampling_mode(pt);
3282 	pt->est_tsc = !pt->timeless_decoding;
3283 
3284 	pt->unknown_thread = thread__new(999999999, 999999999);
3285 	if (!pt->unknown_thread) {
3286 		err = -ENOMEM;
3287 		goto err_free_queues;
3288 	}
3289 
3290 	/*
3291 	 * Since this thread will not be kept in any rbtree not in a
3292 	 * list, initialize its list node so that at thread__put() the
3293 	 * current thread lifetime assuption is kept and we don't segfault
3294 	 * at list_del_init().
3295 	 */
3296 	INIT_LIST_HEAD(&pt->unknown_thread->node);
3297 
3298 	err = thread__set_comm(pt->unknown_thread, "unknown", 0);
3299 	if (err)
3300 		goto err_delete_thread;
3301 	if (thread__init_maps(pt->unknown_thread, pt->machine)) {
3302 		err = -ENOMEM;
3303 		goto err_delete_thread;
3304 	}
3305 
3306 	pt->auxtrace.process_event = intel_pt_process_event;
3307 	pt->auxtrace.process_auxtrace_event = intel_pt_process_auxtrace_event;
3308 	pt->auxtrace.queue_data = intel_pt_queue_data;
3309 	pt->auxtrace.dump_auxtrace_sample = intel_pt_dump_sample;
3310 	pt->auxtrace.flush_events = intel_pt_flush;
3311 	pt->auxtrace.free_events = intel_pt_free_events;
3312 	pt->auxtrace.free = intel_pt_free;
3313 	session->auxtrace = &pt->auxtrace;
3314 
3315 	if (dump_trace)
3316 		return 0;
3317 
3318 	if (pt->have_sched_switch == 1) {
3319 		pt->switch_evsel = intel_pt_find_sched_switch(session->evlist);
3320 		if (!pt->switch_evsel) {
3321 			pr_err("%s: missing sched_switch event\n", __func__);
3322 			err = -EINVAL;
3323 			goto err_delete_thread;
3324 		}
3325 	} else if (pt->have_sched_switch == 2 &&
3326 		   !intel_pt_find_switch(session->evlist)) {
3327 		pr_err("%s: missing context_switch attribute flag\n", __func__);
3328 		err = -EINVAL;
3329 		goto err_delete_thread;
3330 	}
3331 
3332 	if (session->itrace_synth_opts->set) {
3333 		pt->synth_opts = *session->itrace_synth_opts;
3334 	} else {
3335 		itrace_synth_opts__set_default(&pt->synth_opts,
3336 				session->itrace_synth_opts->default_no_sample);
3337 		if (!session->itrace_synth_opts->default_no_sample &&
3338 		    !session->itrace_synth_opts->inject) {
3339 			pt->synth_opts.branches = false;
3340 			pt->synth_opts.callchain = true;
3341 		}
3342 		pt->synth_opts.thread_stack =
3343 				session->itrace_synth_opts->thread_stack;
3344 	}
3345 
3346 	if (pt->synth_opts.log)
3347 		intel_pt_log_enable();
3348 
3349 	/* Maximum non-turbo ratio is TSC freq / 100 MHz */
3350 	if (pt->tc.time_mult) {
3351 		u64 tsc_freq = intel_pt_ns_to_ticks(pt, 1000000000);
3352 
3353 		if (!pt->max_non_turbo_ratio)
3354 			pt->max_non_turbo_ratio =
3355 					(tsc_freq + 50000000) / 100000000;
3356 		intel_pt_log("TSC frequency %"PRIu64"\n", tsc_freq);
3357 		intel_pt_log("Maximum non-turbo ratio %u\n",
3358 			     pt->max_non_turbo_ratio);
3359 		pt->cbr2khz = tsc_freq / pt->max_non_turbo_ratio / 1000;
3360 	}
3361 
3362 	err = intel_pt_setup_time_ranges(pt, session->itrace_synth_opts);
3363 	if (err)
3364 		goto err_delete_thread;
3365 
3366 	if (pt->synth_opts.calls)
3367 		pt->branches_filter |= PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC |
3368 				       PERF_IP_FLAG_TRACE_END;
3369 	if (pt->synth_opts.returns)
3370 		pt->branches_filter |= PERF_IP_FLAG_RETURN |
3371 				       PERF_IP_FLAG_TRACE_BEGIN;
3372 
3373 	if (pt->synth_opts.callchain && !symbol_conf.use_callchain) {
3374 		symbol_conf.use_callchain = true;
3375 		if (callchain_register_param(&callchain_param) < 0) {
3376 			symbol_conf.use_callchain = false;
3377 			pt->synth_opts.callchain = false;
3378 		}
3379 	}
3380 
3381 	err = intel_pt_synth_events(pt, session);
3382 	if (err)
3383 		goto err_delete_thread;
3384 
3385 	intel_pt_setup_pebs_events(pt);
3386 
3387 	if (pt->sampling_mode || list_empty(&session->auxtrace_index))
3388 		err = auxtrace_queue_data(session, true, true);
3389 	else
3390 		err = auxtrace_queues__process_index(&pt->queues, session);
3391 	if (err)
3392 		goto err_delete_thread;
3393 
3394 	if (pt->queues.populated)
3395 		pt->data_queued = true;
3396 
3397 	if (pt->timeless_decoding)
3398 		pr_debug2("Intel PT decoding without timestamps\n");
3399 
3400 	return 0;
3401 
3402 err_delete_thread:
3403 	thread__zput(pt->unknown_thread);
3404 err_free_queues:
3405 	intel_pt_log_disable();
3406 	auxtrace_queues__free(&pt->queues);
3407 	session->auxtrace = NULL;
3408 err_free:
3409 	addr_filters__exit(&pt->filts);
3410 	zfree(&pt->filter);
3411 	zfree(&pt->time_ranges);
3412 	free(pt);
3413 	return err;
3414 }
3415