xref: /openbmc/linux/tools/perf/util/intel-pt.c (revision 2209fda3)
1 /*
2  * intel_pt.c: Intel Processor Trace support
3  * Copyright (c) 2013-2015, Intel Corporation.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  *
14  */
15 
16 #include <inttypes.h>
17 #include <stdio.h>
18 #include <stdbool.h>
19 #include <errno.h>
20 #include <linux/kernel.h>
21 #include <linux/types.h>
22 
23 #include "../perf.h"
24 #include "session.h"
25 #include "machine.h"
26 #include "memswap.h"
27 #include "sort.h"
28 #include "tool.h"
29 #include "event.h"
30 #include "evlist.h"
31 #include "evsel.h"
32 #include "map.h"
33 #include "color.h"
34 #include "util.h"
35 #include "thread.h"
36 #include "thread-stack.h"
37 #include "symbol.h"
38 #include "callchain.h"
39 #include "dso.h"
40 #include "debug.h"
41 #include "auxtrace.h"
42 #include "tsc.h"
43 #include "intel-pt.h"
44 #include "config.h"
45 
46 #include "intel-pt-decoder/intel-pt-log.h"
47 #include "intel-pt-decoder/intel-pt-decoder.h"
48 #include "intel-pt-decoder/intel-pt-insn-decoder.h"
49 #include "intel-pt-decoder/intel-pt-pkt-decoder.h"
50 
51 #define MAX_TIMESTAMP (~0ULL)
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 perf_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 	u64 tsc_bit;
108 	u64 mtc_bit;
109 	u64 mtc_freq_bits;
110 	u32 tsc_ctc_ratio_n;
111 	u32 tsc_ctc_ratio_d;
112 	u64 cyc_bit;
113 	u64 noretcomp_bit;
114 	unsigned max_non_turbo_ratio;
115 	unsigned cbr2khz;
116 
117 	unsigned long num_events;
118 
119 	char *filter;
120 	struct addr_filters filts;
121 };
122 
123 enum switch_state {
124 	INTEL_PT_SS_NOT_TRACING,
125 	INTEL_PT_SS_UNKNOWN,
126 	INTEL_PT_SS_TRACING,
127 	INTEL_PT_SS_EXPECTING_SWITCH_EVENT,
128 	INTEL_PT_SS_EXPECTING_SWITCH_IP,
129 };
130 
131 struct intel_pt_queue {
132 	struct intel_pt *pt;
133 	unsigned int queue_nr;
134 	struct auxtrace_buffer *buffer;
135 	struct auxtrace_buffer *old_buffer;
136 	void *decoder;
137 	const struct intel_pt_state *state;
138 	struct ip_callchain *chain;
139 	struct branch_stack *last_branch;
140 	struct branch_stack *last_branch_rb;
141 	size_t last_branch_pos;
142 	union perf_event *event_buf;
143 	bool on_heap;
144 	bool stop;
145 	bool step_through_buffers;
146 	bool use_buffer_pid_tid;
147 	bool sync_switch;
148 	pid_t pid, tid;
149 	int cpu;
150 	int switch_state;
151 	pid_t next_tid;
152 	struct thread *thread;
153 	bool exclude_kernel;
154 	bool have_sample;
155 	u64 time;
156 	u64 timestamp;
157 	u32 flags;
158 	u16 insn_len;
159 	u64 last_insn_cnt;
160 	char insn[INTEL_PT_INSN_BUF_SZ];
161 };
162 
163 static void intel_pt_dump(struct intel_pt *pt __maybe_unused,
164 			  unsigned char *buf, size_t len)
165 {
166 	struct intel_pt_pkt packet;
167 	size_t pos = 0;
168 	int ret, pkt_len, i;
169 	char desc[INTEL_PT_PKT_DESC_MAX];
170 	const char *color = PERF_COLOR_BLUE;
171 
172 	color_fprintf(stdout, color,
173 		      ". ... Intel Processor Trace data: size %zu bytes\n",
174 		      len);
175 
176 	while (len) {
177 		ret = intel_pt_get_packet(buf, len, &packet);
178 		if (ret > 0)
179 			pkt_len = ret;
180 		else
181 			pkt_len = 1;
182 		printf(".");
183 		color_fprintf(stdout, color, "  %08x: ", pos);
184 		for (i = 0; i < pkt_len; i++)
185 			color_fprintf(stdout, color, " %02x", buf[i]);
186 		for (; i < 16; i++)
187 			color_fprintf(stdout, color, "   ");
188 		if (ret > 0) {
189 			ret = intel_pt_pkt_desc(&packet, desc,
190 						INTEL_PT_PKT_DESC_MAX);
191 			if (ret > 0)
192 				color_fprintf(stdout, color, " %s\n", desc);
193 		} else {
194 			color_fprintf(stdout, color, " Bad packet!\n");
195 		}
196 		pos += pkt_len;
197 		buf += pkt_len;
198 		len -= pkt_len;
199 	}
200 }
201 
202 static void intel_pt_dump_event(struct intel_pt *pt, unsigned char *buf,
203 				size_t len)
204 {
205 	printf(".\n");
206 	intel_pt_dump(pt, buf, len);
207 }
208 
209 static int intel_pt_do_fix_overlap(struct intel_pt *pt, struct auxtrace_buffer *a,
210 				   struct auxtrace_buffer *b)
211 {
212 	bool consecutive = false;
213 	void *start;
214 
215 	start = intel_pt_find_overlap(a->data, a->size, b->data, b->size,
216 				      pt->have_tsc, &consecutive);
217 	if (!start)
218 		return -EINVAL;
219 	b->use_size = b->data + b->size - start;
220 	b->use_data = start;
221 	if (b->use_size && consecutive)
222 		b->consecutive = true;
223 	return 0;
224 }
225 
226 /* This function assumes data is processed sequentially only */
227 static int intel_pt_get_trace(struct intel_pt_buffer *b, void *data)
228 {
229 	struct intel_pt_queue *ptq = data;
230 	struct auxtrace_buffer *buffer = ptq->buffer;
231 	struct auxtrace_buffer *old_buffer = ptq->old_buffer;
232 	struct auxtrace_queue *queue;
233 	bool might_overlap;
234 
235 	if (ptq->stop) {
236 		b->len = 0;
237 		return 0;
238 	}
239 
240 	queue = &ptq->pt->queues.queue_array[ptq->queue_nr];
241 
242 	buffer = auxtrace_buffer__next(queue, buffer);
243 	if (!buffer) {
244 		if (old_buffer)
245 			auxtrace_buffer__drop_data(old_buffer);
246 		b->len = 0;
247 		return 0;
248 	}
249 
250 	ptq->buffer = buffer;
251 
252 	if (!buffer->data) {
253 		int fd = perf_data__fd(ptq->pt->session->data);
254 
255 		buffer->data = auxtrace_buffer__get_data(buffer, fd);
256 		if (!buffer->data)
257 			return -ENOMEM;
258 	}
259 
260 	might_overlap = ptq->pt->snapshot_mode || ptq->pt->sampling_mode;
261 	if (might_overlap && !buffer->consecutive && old_buffer &&
262 	    intel_pt_do_fix_overlap(ptq->pt, old_buffer, buffer))
263 		return -ENOMEM;
264 
265 	if (buffer->use_data) {
266 		b->len = buffer->use_size;
267 		b->buf = buffer->use_data;
268 	} else {
269 		b->len = buffer->size;
270 		b->buf = buffer->data;
271 	}
272 	b->ref_timestamp = buffer->reference;
273 
274 	if (!old_buffer || (might_overlap && !buffer->consecutive)) {
275 		b->consecutive = false;
276 		b->trace_nr = buffer->buffer_nr + 1;
277 	} else {
278 		b->consecutive = true;
279 	}
280 
281 	if (ptq->step_through_buffers)
282 		ptq->stop = true;
283 
284 	if (b->len) {
285 		if (old_buffer)
286 			auxtrace_buffer__drop_data(old_buffer);
287 		ptq->old_buffer = buffer;
288 	} else {
289 		auxtrace_buffer__drop_data(buffer);
290 		return intel_pt_get_trace(b, data);
291 	}
292 
293 	return 0;
294 }
295 
296 struct intel_pt_cache_entry {
297 	struct auxtrace_cache_entry	entry;
298 	u64				insn_cnt;
299 	u64				byte_cnt;
300 	enum intel_pt_insn_op		op;
301 	enum intel_pt_insn_branch	branch;
302 	int				length;
303 	int32_t				rel;
304 	char				insn[INTEL_PT_INSN_BUF_SZ];
305 };
306 
307 static int intel_pt_config_div(const char *var, const char *value, void *data)
308 {
309 	int *d = data;
310 	long val;
311 
312 	if (!strcmp(var, "intel-pt.cache-divisor")) {
313 		val = strtol(value, NULL, 0);
314 		if (val > 0 && val <= INT_MAX)
315 			*d = val;
316 	}
317 
318 	return 0;
319 }
320 
321 static int intel_pt_cache_divisor(void)
322 {
323 	static int d;
324 
325 	if (d)
326 		return d;
327 
328 	perf_config(intel_pt_config_div, &d);
329 
330 	if (!d)
331 		d = 64;
332 
333 	return d;
334 }
335 
336 static unsigned int intel_pt_cache_size(struct dso *dso,
337 					struct machine *machine)
338 {
339 	off_t size;
340 
341 	size = dso__data_size(dso, machine);
342 	size /= intel_pt_cache_divisor();
343 	if (size < 1000)
344 		return 10;
345 	if (size > (1 << 21))
346 		return 21;
347 	return 32 - __builtin_clz(size);
348 }
349 
350 static struct auxtrace_cache *intel_pt_cache(struct dso *dso,
351 					     struct machine *machine)
352 {
353 	struct auxtrace_cache *c;
354 	unsigned int bits;
355 
356 	if (dso->auxtrace_cache)
357 		return dso->auxtrace_cache;
358 
359 	bits = intel_pt_cache_size(dso, machine);
360 
361 	/* Ignoring cache creation failure */
362 	c = auxtrace_cache__new(bits, sizeof(struct intel_pt_cache_entry), 200);
363 
364 	dso->auxtrace_cache = c;
365 
366 	return c;
367 }
368 
369 static int intel_pt_cache_add(struct dso *dso, struct machine *machine,
370 			      u64 offset, u64 insn_cnt, u64 byte_cnt,
371 			      struct intel_pt_insn *intel_pt_insn)
372 {
373 	struct auxtrace_cache *c = intel_pt_cache(dso, machine);
374 	struct intel_pt_cache_entry *e;
375 	int err;
376 
377 	if (!c)
378 		return -ENOMEM;
379 
380 	e = auxtrace_cache__alloc_entry(c);
381 	if (!e)
382 		return -ENOMEM;
383 
384 	e->insn_cnt = insn_cnt;
385 	e->byte_cnt = byte_cnt;
386 	e->op = intel_pt_insn->op;
387 	e->branch = intel_pt_insn->branch;
388 	e->length = intel_pt_insn->length;
389 	e->rel = intel_pt_insn->rel;
390 	memcpy(e->insn, intel_pt_insn->buf, INTEL_PT_INSN_BUF_SZ);
391 
392 	err = auxtrace_cache__add(c, offset, &e->entry);
393 	if (err)
394 		auxtrace_cache__free_entry(c, e);
395 
396 	return err;
397 }
398 
399 static struct intel_pt_cache_entry *
400 intel_pt_cache_lookup(struct dso *dso, struct machine *machine, u64 offset)
401 {
402 	struct auxtrace_cache *c = intel_pt_cache(dso, machine);
403 
404 	if (!c)
405 		return NULL;
406 
407 	return auxtrace_cache__lookup(dso->auxtrace_cache, offset);
408 }
409 
410 static int intel_pt_walk_next_insn(struct intel_pt_insn *intel_pt_insn,
411 				   uint64_t *insn_cnt_ptr, uint64_t *ip,
412 				   uint64_t to_ip, uint64_t max_insn_cnt,
413 				   void *data)
414 {
415 	struct intel_pt_queue *ptq = data;
416 	struct machine *machine = ptq->pt->machine;
417 	struct thread *thread;
418 	struct addr_location al;
419 	unsigned char buf[INTEL_PT_INSN_BUF_SZ];
420 	ssize_t len;
421 	int x86_64;
422 	u8 cpumode;
423 	u64 offset, start_offset, start_ip;
424 	u64 insn_cnt = 0;
425 	bool one_map = true;
426 
427 	intel_pt_insn->length = 0;
428 
429 	if (to_ip && *ip == to_ip)
430 		goto out_no_cache;
431 
432 	if (*ip >= ptq->pt->kernel_start)
433 		cpumode = PERF_RECORD_MISC_KERNEL;
434 	else
435 		cpumode = PERF_RECORD_MISC_USER;
436 
437 	thread = ptq->thread;
438 	if (!thread) {
439 		if (cpumode != PERF_RECORD_MISC_KERNEL)
440 			return -EINVAL;
441 		thread = ptq->pt->unknown_thread;
442 	}
443 
444 	while (1) {
445 		if (!thread__find_map(thread, cpumode, *ip, &al) || !al.map->dso)
446 			return -EINVAL;
447 
448 		if (al.map->dso->data.status == DSO_DATA_STATUS_ERROR &&
449 		    dso__data_status_seen(al.map->dso,
450 					  DSO_DATA_STATUS_SEEN_ITRACE))
451 			return -ENOENT;
452 
453 		offset = al.map->map_ip(al.map, *ip);
454 
455 		if (!to_ip && one_map) {
456 			struct intel_pt_cache_entry *e;
457 
458 			e = intel_pt_cache_lookup(al.map->dso, machine, offset);
459 			if (e &&
460 			    (!max_insn_cnt || e->insn_cnt <= max_insn_cnt)) {
461 				*insn_cnt_ptr = e->insn_cnt;
462 				*ip += e->byte_cnt;
463 				intel_pt_insn->op = e->op;
464 				intel_pt_insn->branch = e->branch;
465 				intel_pt_insn->length = e->length;
466 				intel_pt_insn->rel = e->rel;
467 				memcpy(intel_pt_insn->buf, e->insn,
468 				       INTEL_PT_INSN_BUF_SZ);
469 				intel_pt_log_insn_no_data(intel_pt_insn, *ip);
470 				return 0;
471 			}
472 		}
473 
474 		start_offset = offset;
475 		start_ip = *ip;
476 
477 		/* Load maps to ensure dso->is_64_bit has been updated */
478 		map__load(al.map);
479 
480 		x86_64 = al.map->dso->is_64_bit;
481 
482 		while (1) {
483 			len = dso__data_read_offset(al.map->dso, machine,
484 						    offset, buf,
485 						    INTEL_PT_INSN_BUF_SZ);
486 			if (len <= 0)
487 				return -EINVAL;
488 
489 			if (intel_pt_get_insn(buf, len, x86_64, intel_pt_insn))
490 				return -EINVAL;
491 
492 			intel_pt_log_insn(intel_pt_insn, *ip);
493 
494 			insn_cnt += 1;
495 
496 			if (intel_pt_insn->branch != INTEL_PT_BR_NO_BRANCH)
497 				goto out;
498 
499 			if (max_insn_cnt && insn_cnt >= max_insn_cnt)
500 				goto out_no_cache;
501 
502 			*ip += intel_pt_insn->length;
503 
504 			if (to_ip && *ip == to_ip)
505 				goto out_no_cache;
506 
507 			if (*ip >= al.map->end)
508 				break;
509 
510 			offset += intel_pt_insn->length;
511 		}
512 		one_map = false;
513 	}
514 out:
515 	*insn_cnt_ptr = insn_cnt;
516 
517 	if (!one_map)
518 		goto out_no_cache;
519 
520 	/*
521 	 * Didn't lookup in the 'to_ip' case, so do it now to prevent duplicate
522 	 * entries.
523 	 */
524 	if (to_ip) {
525 		struct intel_pt_cache_entry *e;
526 
527 		e = intel_pt_cache_lookup(al.map->dso, machine, start_offset);
528 		if (e)
529 			return 0;
530 	}
531 
532 	/* Ignore cache errors */
533 	intel_pt_cache_add(al.map->dso, machine, start_offset, insn_cnt,
534 			   *ip - start_ip, intel_pt_insn);
535 
536 	return 0;
537 
538 out_no_cache:
539 	*insn_cnt_ptr = insn_cnt;
540 	return 0;
541 }
542 
543 static bool intel_pt_match_pgd_ip(struct intel_pt *pt, uint64_t ip,
544 				  uint64_t offset, const char *filename)
545 {
546 	struct addr_filter *filt;
547 	bool have_filter   = false;
548 	bool hit_tracestop = false;
549 	bool hit_filter    = false;
550 
551 	list_for_each_entry(filt, &pt->filts.head, list) {
552 		if (filt->start)
553 			have_filter = true;
554 
555 		if ((filename && !filt->filename) ||
556 		    (!filename && filt->filename) ||
557 		    (filename && strcmp(filename, filt->filename)))
558 			continue;
559 
560 		if (!(offset >= filt->addr && offset < filt->addr + filt->size))
561 			continue;
562 
563 		intel_pt_log("TIP.PGD ip %#"PRIx64" offset %#"PRIx64" in %s hit filter: %s offset %#"PRIx64" size %#"PRIx64"\n",
564 			     ip, offset, filename ? filename : "[kernel]",
565 			     filt->start ? "filter" : "stop",
566 			     filt->addr, filt->size);
567 
568 		if (filt->start)
569 			hit_filter = true;
570 		else
571 			hit_tracestop = true;
572 	}
573 
574 	if (!hit_tracestop && !hit_filter)
575 		intel_pt_log("TIP.PGD ip %#"PRIx64" offset %#"PRIx64" in %s is not in a filter region\n",
576 			     ip, offset, filename ? filename : "[kernel]");
577 
578 	return hit_tracestop || (have_filter && !hit_filter);
579 }
580 
581 static int __intel_pt_pgd_ip(uint64_t ip, void *data)
582 {
583 	struct intel_pt_queue *ptq = data;
584 	struct thread *thread;
585 	struct addr_location al;
586 	u8 cpumode;
587 	u64 offset;
588 
589 	if (ip >= ptq->pt->kernel_start)
590 		return intel_pt_match_pgd_ip(ptq->pt, ip, ip, NULL);
591 
592 	cpumode = PERF_RECORD_MISC_USER;
593 
594 	thread = ptq->thread;
595 	if (!thread)
596 		return -EINVAL;
597 
598 	if (!thread__find_map(thread, cpumode, ip, &al) || !al.map->dso)
599 		return -EINVAL;
600 
601 	offset = al.map->map_ip(al.map, ip);
602 
603 	return intel_pt_match_pgd_ip(ptq->pt, ip, offset,
604 				     al.map->dso->long_name);
605 }
606 
607 static bool intel_pt_pgd_ip(uint64_t ip, void *data)
608 {
609 	return __intel_pt_pgd_ip(ip, data) > 0;
610 }
611 
612 static bool intel_pt_get_config(struct intel_pt *pt,
613 				struct perf_event_attr *attr, u64 *config)
614 {
615 	if (attr->type == pt->pmu_type) {
616 		if (config)
617 			*config = attr->config;
618 		return true;
619 	}
620 
621 	return false;
622 }
623 
624 static bool intel_pt_exclude_kernel(struct intel_pt *pt)
625 {
626 	struct perf_evsel *evsel;
627 
628 	evlist__for_each_entry(pt->session->evlist, evsel) {
629 		if (intel_pt_get_config(pt, &evsel->attr, NULL) &&
630 		    !evsel->attr.exclude_kernel)
631 			return false;
632 	}
633 	return true;
634 }
635 
636 static bool intel_pt_return_compression(struct intel_pt *pt)
637 {
638 	struct perf_evsel *evsel;
639 	u64 config;
640 
641 	if (!pt->noretcomp_bit)
642 		return true;
643 
644 	evlist__for_each_entry(pt->session->evlist, evsel) {
645 		if (intel_pt_get_config(pt, &evsel->attr, &config) &&
646 		    (config & pt->noretcomp_bit))
647 			return false;
648 	}
649 	return true;
650 }
651 
652 static bool intel_pt_branch_enable(struct intel_pt *pt)
653 {
654 	struct perf_evsel *evsel;
655 	u64 config;
656 
657 	evlist__for_each_entry(pt->session->evlist, evsel) {
658 		if (intel_pt_get_config(pt, &evsel->attr, &config) &&
659 		    (config & 1) && !(config & 0x2000))
660 			return false;
661 	}
662 	return true;
663 }
664 
665 static unsigned int intel_pt_mtc_period(struct intel_pt *pt)
666 {
667 	struct perf_evsel *evsel;
668 	unsigned int shift;
669 	u64 config;
670 
671 	if (!pt->mtc_freq_bits)
672 		return 0;
673 
674 	for (shift = 0, config = pt->mtc_freq_bits; !(config & 1); shift++)
675 		config >>= 1;
676 
677 	evlist__for_each_entry(pt->session->evlist, evsel) {
678 		if (intel_pt_get_config(pt, &evsel->attr, &config))
679 			return (config & pt->mtc_freq_bits) >> shift;
680 	}
681 	return 0;
682 }
683 
684 static bool intel_pt_timeless_decoding(struct intel_pt *pt)
685 {
686 	struct perf_evsel *evsel;
687 	bool timeless_decoding = true;
688 	u64 config;
689 
690 	if (!pt->tsc_bit || !pt->cap_user_time_zero)
691 		return true;
692 
693 	evlist__for_each_entry(pt->session->evlist, evsel) {
694 		if (!(evsel->attr.sample_type & PERF_SAMPLE_TIME))
695 			return true;
696 		if (intel_pt_get_config(pt, &evsel->attr, &config)) {
697 			if (config & pt->tsc_bit)
698 				timeless_decoding = false;
699 			else
700 				return true;
701 		}
702 	}
703 	return timeless_decoding;
704 }
705 
706 static bool intel_pt_tracing_kernel(struct intel_pt *pt)
707 {
708 	struct perf_evsel *evsel;
709 
710 	evlist__for_each_entry(pt->session->evlist, evsel) {
711 		if (intel_pt_get_config(pt, &evsel->attr, NULL) &&
712 		    !evsel->attr.exclude_kernel)
713 			return true;
714 	}
715 	return false;
716 }
717 
718 static bool intel_pt_have_tsc(struct intel_pt *pt)
719 {
720 	struct perf_evsel *evsel;
721 	bool have_tsc = false;
722 	u64 config;
723 
724 	if (!pt->tsc_bit)
725 		return false;
726 
727 	evlist__for_each_entry(pt->session->evlist, evsel) {
728 		if (intel_pt_get_config(pt, &evsel->attr, &config)) {
729 			if (config & pt->tsc_bit)
730 				have_tsc = true;
731 			else
732 				return false;
733 		}
734 	}
735 	return have_tsc;
736 }
737 
738 static u64 intel_pt_ns_to_ticks(const struct intel_pt *pt, u64 ns)
739 {
740 	u64 quot, rem;
741 
742 	quot = ns / pt->tc.time_mult;
743 	rem  = ns % pt->tc.time_mult;
744 	return (quot << pt->tc.time_shift) + (rem << pt->tc.time_shift) /
745 		pt->tc.time_mult;
746 }
747 
748 static struct intel_pt_queue *intel_pt_alloc_queue(struct intel_pt *pt,
749 						   unsigned int queue_nr)
750 {
751 	struct intel_pt_params params = { .get_trace = 0, };
752 	struct perf_env *env = pt->machine->env;
753 	struct intel_pt_queue *ptq;
754 
755 	ptq = zalloc(sizeof(struct intel_pt_queue));
756 	if (!ptq)
757 		return NULL;
758 
759 	if (pt->synth_opts.callchain) {
760 		size_t sz = sizeof(struct ip_callchain);
761 
762 		sz += pt->synth_opts.callchain_sz * sizeof(u64);
763 		ptq->chain = zalloc(sz);
764 		if (!ptq->chain)
765 			goto out_free;
766 	}
767 
768 	if (pt->synth_opts.last_branch) {
769 		size_t sz = sizeof(struct branch_stack);
770 
771 		sz += pt->synth_opts.last_branch_sz *
772 		      sizeof(struct branch_entry);
773 		ptq->last_branch = zalloc(sz);
774 		if (!ptq->last_branch)
775 			goto out_free;
776 		ptq->last_branch_rb = zalloc(sz);
777 		if (!ptq->last_branch_rb)
778 			goto out_free;
779 	}
780 
781 	ptq->event_buf = malloc(PERF_SAMPLE_MAX_SIZE);
782 	if (!ptq->event_buf)
783 		goto out_free;
784 
785 	ptq->pt = pt;
786 	ptq->queue_nr = queue_nr;
787 	ptq->exclude_kernel = intel_pt_exclude_kernel(pt);
788 	ptq->pid = -1;
789 	ptq->tid = -1;
790 	ptq->cpu = -1;
791 	ptq->next_tid = -1;
792 
793 	params.get_trace = intel_pt_get_trace;
794 	params.walk_insn = intel_pt_walk_next_insn;
795 	params.data = ptq;
796 	params.return_compression = intel_pt_return_compression(pt);
797 	params.branch_enable = intel_pt_branch_enable(pt);
798 	params.max_non_turbo_ratio = pt->max_non_turbo_ratio;
799 	params.mtc_period = intel_pt_mtc_period(pt);
800 	params.tsc_ctc_ratio_n = pt->tsc_ctc_ratio_n;
801 	params.tsc_ctc_ratio_d = pt->tsc_ctc_ratio_d;
802 
803 	if (pt->filts.cnt > 0)
804 		params.pgd_ip = intel_pt_pgd_ip;
805 
806 	if (pt->synth_opts.instructions) {
807 		if (pt->synth_opts.period) {
808 			switch (pt->synth_opts.period_type) {
809 			case PERF_ITRACE_PERIOD_INSTRUCTIONS:
810 				params.period_type =
811 						INTEL_PT_PERIOD_INSTRUCTIONS;
812 				params.period = pt->synth_opts.period;
813 				break;
814 			case PERF_ITRACE_PERIOD_TICKS:
815 				params.period_type = INTEL_PT_PERIOD_TICKS;
816 				params.period = pt->synth_opts.period;
817 				break;
818 			case PERF_ITRACE_PERIOD_NANOSECS:
819 				params.period_type = INTEL_PT_PERIOD_TICKS;
820 				params.period = intel_pt_ns_to_ticks(pt,
821 							pt->synth_opts.period);
822 				break;
823 			default:
824 				break;
825 			}
826 		}
827 
828 		if (!params.period) {
829 			params.period_type = INTEL_PT_PERIOD_INSTRUCTIONS;
830 			params.period = 1;
831 		}
832 	}
833 
834 	if (env->cpuid && !strncmp(env->cpuid, "GenuineIntel,6,92,", 18))
835 		params.flags |= INTEL_PT_FUP_WITH_NLIP;
836 
837 	ptq->decoder = intel_pt_decoder_new(&params);
838 	if (!ptq->decoder)
839 		goto out_free;
840 
841 	return ptq;
842 
843 out_free:
844 	zfree(&ptq->event_buf);
845 	zfree(&ptq->last_branch);
846 	zfree(&ptq->last_branch_rb);
847 	zfree(&ptq->chain);
848 	free(ptq);
849 	return NULL;
850 }
851 
852 static void intel_pt_free_queue(void *priv)
853 {
854 	struct intel_pt_queue *ptq = priv;
855 
856 	if (!ptq)
857 		return;
858 	thread__zput(ptq->thread);
859 	intel_pt_decoder_free(ptq->decoder);
860 	zfree(&ptq->event_buf);
861 	zfree(&ptq->last_branch);
862 	zfree(&ptq->last_branch_rb);
863 	zfree(&ptq->chain);
864 	free(ptq);
865 }
866 
867 static void intel_pt_set_pid_tid_cpu(struct intel_pt *pt,
868 				     struct auxtrace_queue *queue)
869 {
870 	struct intel_pt_queue *ptq = queue->priv;
871 
872 	if (queue->tid == -1 || pt->have_sched_switch) {
873 		ptq->tid = machine__get_current_tid(pt->machine, ptq->cpu);
874 		thread__zput(ptq->thread);
875 	}
876 
877 	if (!ptq->thread && ptq->tid != -1)
878 		ptq->thread = machine__find_thread(pt->machine, -1, ptq->tid);
879 
880 	if (ptq->thread) {
881 		ptq->pid = ptq->thread->pid_;
882 		if (queue->cpu == -1)
883 			ptq->cpu = ptq->thread->cpu;
884 	}
885 }
886 
887 static void intel_pt_sample_flags(struct intel_pt_queue *ptq)
888 {
889 	if (ptq->state->flags & INTEL_PT_ABORT_TX) {
890 		ptq->flags = PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT;
891 	} else if (ptq->state->flags & INTEL_PT_ASYNC) {
892 		if (ptq->state->to_ip)
893 			ptq->flags = PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL |
894 				     PERF_IP_FLAG_ASYNC |
895 				     PERF_IP_FLAG_INTERRUPT;
896 		else
897 			ptq->flags = PERF_IP_FLAG_BRANCH |
898 				     PERF_IP_FLAG_TRACE_END;
899 		ptq->insn_len = 0;
900 	} else {
901 		if (ptq->state->from_ip)
902 			ptq->flags = intel_pt_insn_type(ptq->state->insn_op);
903 		else
904 			ptq->flags = PERF_IP_FLAG_BRANCH |
905 				     PERF_IP_FLAG_TRACE_BEGIN;
906 		if (ptq->state->flags & INTEL_PT_IN_TX)
907 			ptq->flags |= PERF_IP_FLAG_IN_TX;
908 		ptq->insn_len = ptq->state->insn_len;
909 		memcpy(ptq->insn, ptq->state->insn, INTEL_PT_INSN_BUF_SZ);
910 	}
911 
912 	if (ptq->state->type & INTEL_PT_TRACE_BEGIN)
913 		ptq->flags |= PERF_IP_FLAG_TRACE_BEGIN;
914 	if (ptq->state->type & INTEL_PT_TRACE_END)
915 		ptq->flags |= PERF_IP_FLAG_TRACE_END;
916 }
917 
918 static int intel_pt_setup_queue(struct intel_pt *pt,
919 				struct auxtrace_queue *queue,
920 				unsigned int queue_nr)
921 {
922 	struct intel_pt_queue *ptq = queue->priv;
923 
924 	if (list_empty(&queue->head))
925 		return 0;
926 
927 	if (!ptq) {
928 		ptq = intel_pt_alloc_queue(pt, queue_nr);
929 		if (!ptq)
930 			return -ENOMEM;
931 		queue->priv = ptq;
932 
933 		if (queue->cpu != -1)
934 			ptq->cpu = queue->cpu;
935 		ptq->tid = queue->tid;
936 
937 		if (pt->sampling_mode && !pt->snapshot_mode &&
938 		    pt->timeless_decoding)
939 			ptq->step_through_buffers = true;
940 
941 		ptq->sync_switch = pt->sync_switch;
942 	}
943 
944 	if (!ptq->on_heap &&
945 	    (!ptq->sync_switch ||
946 	     ptq->switch_state != INTEL_PT_SS_EXPECTING_SWITCH_EVENT)) {
947 		const struct intel_pt_state *state;
948 		int ret;
949 
950 		if (pt->timeless_decoding)
951 			return 0;
952 
953 		intel_pt_log("queue %u getting timestamp\n", queue_nr);
954 		intel_pt_log("queue %u decoding cpu %d pid %d tid %d\n",
955 			     queue_nr, ptq->cpu, ptq->pid, ptq->tid);
956 		while (1) {
957 			state = intel_pt_decode(ptq->decoder);
958 			if (state->err) {
959 				if (state->err == INTEL_PT_ERR_NODATA) {
960 					intel_pt_log("queue %u has no timestamp\n",
961 						     queue_nr);
962 					return 0;
963 				}
964 				continue;
965 			}
966 			if (state->timestamp)
967 				break;
968 		}
969 
970 		ptq->timestamp = state->timestamp;
971 		intel_pt_log("queue %u timestamp 0x%" PRIx64 "\n",
972 			     queue_nr, ptq->timestamp);
973 		ptq->state = state;
974 		ptq->have_sample = true;
975 		intel_pt_sample_flags(ptq);
976 		ret = auxtrace_heap__add(&pt->heap, queue_nr, ptq->timestamp);
977 		if (ret)
978 			return ret;
979 		ptq->on_heap = true;
980 	}
981 
982 	return 0;
983 }
984 
985 static int intel_pt_setup_queues(struct intel_pt *pt)
986 {
987 	unsigned int i;
988 	int ret;
989 
990 	for (i = 0; i < pt->queues.nr_queues; i++) {
991 		ret = intel_pt_setup_queue(pt, &pt->queues.queue_array[i], i);
992 		if (ret)
993 			return ret;
994 	}
995 	return 0;
996 }
997 
998 static inline void intel_pt_copy_last_branch_rb(struct intel_pt_queue *ptq)
999 {
1000 	struct branch_stack *bs_src = ptq->last_branch_rb;
1001 	struct branch_stack *bs_dst = ptq->last_branch;
1002 	size_t nr = 0;
1003 
1004 	bs_dst->nr = bs_src->nr;
1005 
1006 	if (!bs_src->nr)
1007 		return;
1008 
1009 	nr = ptq->pt->synth_opts.last_branch_sz - ptq->last_branch_pos;
1010 	memcpy(&bs_dst->entries[0],
1011 	       &bs_src->entries[ptq->last_branch_pos],
1012 	       sizeof(struct branch_entry) * nr);
1013 
1014 	if (bs_src->nr >= ptq->pt->synth_opts.last_branch_sz) {
1015 		memcpy(&bs_dst->entries[nr],
1016 		       &bs_src->entries[0],
1017 		       sizeof(struct branch_entry) * ptq->last_branch_pos);
1018 	}
1019 }
1020 
1021 static inline void intel_pt_reset_last_branch_rb(struct intel_pt_queue *ptq)
1022 {
1023 	ptq->last_branch_pos = 0;
1024 	ptq->last_branch_rb->nr = 0;
1025 }
1026 
1027 static void intel_pt_update_last_branch_rb(struct intel_pt_queue *ptq)
1028 {
1029 	const struct intel_pt_state *state = ptq->state;
1030 	struct branch_stack *bs = ptq->last_branch_rb;
1031 	struct branch_entry *be;
1032 
1033 	if (!ptq->last_branch_pos)
1034 		ptq->last_branch_pos = ptq->pt->synth_opts.last_branch_sz;
1035 
1036 	ptq->last_branch_pos -= 1;
1037 
1038 	be              = &bs->entries[ptq->last_branch_pos];
1039 	be->from        = state->from_ip;
1040 	be->to          = state->to_ip;
1041 	be->flags.abort = !!(state->flags & INTEL_PT_ABORT_TX);
1042 	be->flags.in_tx = !!(state->flags & INTEL_PT_IN_TX);
1043 	/* No support for mispredict */
1044 	be->flags.mispred = ptq->pt->mispred_all;
1045 
1046 	if (bs->nr < ptq->pt->synth_opts.last_branch_sz)
1047 		bs->nr += 1;
1048 }
1049 
1050 static inline bool intel_pt_skip_event(struct intel_pt *pt)
1051 {
1052 	return pt->synth_opts.initial_skip &&
1053 	       pt->num_events++ < pt->synth_opts.initial_skip;
1054 }
1055 
1056 static void intel_pt_prep_b_sample(struct intel_pt *pt,
1057 				   struct intel_pt_queue *ptq,
1058 				   union perf_event *event,
1059 				   struct perf_sample *sample)
1060 {
1061 	event->sample.header.type = PERF_RECORD_SAMPLE;
1062 	event->sample.header.misc = PERF_RECORD_MISC_USER;
1063 	event->sample.header.size = sizeof(struct perf_event_header);
1064 
1065 	if (!pt->timeless_decoding)
1066 		sample->time = tsc_to_perf_time(ptq->timestamp, &pt->tc);
1067 
1068 	sample->cpumode = PERF_RECORD_MISC_USER;
1069 	sample->ip = ptq->state->from_ip;
1070 	sample->pid = ptq->pid;
1071 	sample->tid = ptq->tid;
1072 	sample->addr = ptq->state->to_ip;
1073 	sample->period = 1;
1074 	sample->cpu = ptq->cpu;
1075 	sample->flags = ptq->flags;
1076 	sample->insn_len = ptq->insn_len;
1077 	memcpy(sample->insn, ptq->insn, INTEL_PT_INSN_BUF_SZ);
1078 }
1079 
1080 static int intel_pt_inject_event(union perf_event *event,
1081 				 struct perf_sample *sample, u64 type)
1082 {
1083 	event->header.size = perf_event__sample_event_size(sample, type, 0);
1084 	return perf_event__synthesize_sample(event, type, 0, sample);
1085 }
1086 
1087 static inline int intel_pt_opt_inject(struct intel_pt *pt,
1088 				      union perf_event *event,
1089 				      struct perf_sample *sample, u64 type)
1090 {
1091 	if (!pt->synth_opts.inject)
1092 		return 0;
1093 
1094 	return intel_pt_inject_event(event, sample, type);
1095 }
1096 
1097 static int intel_pt_deliver_synth_b_event(struct intel_pt *pt,
1098 					  union perf_event *event,
1099 					  struct perf_sample *sample, u64 type)
1100 {
1101 	int ret;
1102 
1103 	ret = intel_pt_opt_inject(pt, event, sample, type);
1104 	if (ret)
1105 		return ret;
1106 
1107 	ret = perf_session__deliver_synth_event(pt->session, event, sample);
1108 	if (ret)
1109 		pr_err("Intel PT: failed to deliver event, error %d\n", ret);
1110 
1111 	return ret;
1112 }
1113 
1114 static int intel_pt_synth_branch_sample(struct intel_pt_queue *ptq)
1115 {
1116 	struct intel_pt *pt = ptq->pt;
1117 	union perf_event *event = ptq->event_buf;
1118 	struct perf_sample sample = { .ip = 0, };
1119 	struct dummy_branch_stack {
1120 		u64			nr;
1121 		struct branch_entry	entries;
1122 	} dummy_bs;
1123 
1124 	if (pt->branches_filter && !(pt->branches_filter & ptq->flags))
1125 		return 0;
1126 
1127 	if (intel_pt_skip_event(pt))
1128 		return 0;
1129 
1130 	intel_pt_prep_b_sample(pt, ptq, event, &sample);
1131 
1132 	sample.id = ptq->pt->branches_id;
1133 	sample.stream_id = ptq->pt->branches_id;
1134 
1135 	/*
1136 	 * perf report cannot handle events without a branch stack when using
1137 	 * SORT_MODE__BRANCH so make a dummy one.
1138 	 */
1139 	if (pt->synth_opts.last_branch && sort__mode == SORT_MODE__BRANCH) {
1140 		dummy_bs = (struct dummy_branch_stack){
1141 			.nr = 1,
1142 			.entries = {
1143 				.from = sample.ip,
1144 				.to = sample.addr,
1145 			},
1146 		};
1147 		sample.branch_stack = (struct branch_stack *)&dummy_bs;
1148 	}
1149 
1150 	return intel_pt_deliver_synth_b_event(pt, event, &sample,
1151 					      pt->branches_sample_type);
1152 }
1153 
1154 static void intel_pt_prep_sample(struct intel_pt *pt,
1155 				 struct intel_pt_queue *ptq,
1156 				 union perf_event *event,
1157 				 struct perf_sample *sample)
1158 {
1159 	intel_pt_prep_b_sample(pt, ptq, event, sample);
1160 
1161 	if (pt->synth_opts.callchain) {
1162 		thread_stack__sample(ptq->thread, ptq->chain,
1163 				     pt->synth_opts.callchain_sz, sample->ip);
1164 		sample->callchain = ptq->chain;
1165 	}
1166 
1167 	if (pt->synth_opts.last_branch) {
1168 		intel_pt_copy_last_branch_rb(ptq);
1169 		sample->branch_stack = ptq->last_branch;
1170 	}
1171 }
1172 
1173 static inline int intel_pt_deliver_synth_event(struct intel_pt *pt,
1174 					       struct intel_pt_queue *ptq,
1175 					       union perf_event *event,
1176 					       struct perf_sample *sample,
1177 					       u64 type)
1178 {
1179 	int ret;
1180 
1181 	ret = intel_pt_deliver_synth_b_event(pt, event, sample, type);
1182 
1183 	if (pt->synth_opts.last_branch)
1184 		intel_pt_reset_last_branch_rb(ptq);
1185 
1186 	return ret;
1187 }
1188 
1189 static int intel_pt_synth_instruction_sample(struct intel_pt_queue *ptq)
1190 {
1191 	struct intel_pt *pt = ptq->pt;
1192 	union perf_event *event = ptq->event_buf;
1193 	struct perf_sample sample = { .ip = 0, };
1194 
1195 	if (intel_pt_skip_event(pt))
1196 		return 0;
1197 
1198 	intel_pt_prep_sample(pt, ptq, event, &sample);
1199 
1200 	sample.id = ptq->pt->instructions_id;
1201 	sample.stream_id = ptq->pt->instructions_id;
1202 	sample.period = ptq->state->tot_insn_cnt - ptq->last_insn_cnt;
1203 
1204 	ptq->last_insn_cnt = ptq->state->tot_insn_cnt;
1205 
1206 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1207 					    pt->instructions_sample_type);
1208 }
1209 
1210 static int intel_pt_synth_transaction_sample(struct intel_pt_queue *ptq)
1211 {
1212 	struct intel_pt *pt = ptq->pt;
1213 	union perf_event *event = ptq->event_buf;
1214 	struct perf_sample sample = { .ip = 0, };
1215 
1216 	if (intel_pt_skip_event(pt))
1217 		return 0;
1218 
1219 	intel_pt_prep_sample(pt, ptq, event, &sample);
1220 
1221 	sample.id = ptq->pt->transactions_id;
1222 	sample.stream_id = ptq->pt->transactions_id;
1223 
1224 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1225 					    pt->transactions_sample_type);
1226 }
1227 
1228 static void intel_pt_prep_p_sample(struct intel_pt *pt,
1229 				   struct intel_pt_queue *ptq,
1230 				   union perf_event *event,
1231 				   struct perf_sample *sample)
1232 {
1233 	intel_pt_prep_sample(pt, ptq, event, sample);
1234 
1235 	/*
1236 	 * Zero IP is used to mean "trace start" but that is not the case for
1237 	 * power or PTWRITE events with no IP, so clear the flags.
1238 	 */
1239 	if (!sample->ip)
1240 		sample->flags = 0;
1241 }
1242 
1243 static int intel_pt_synth_ptwrite_sample(struct intel_pt_queue *ptq)
1244 {
1245 	struct intel_pt *pt = ptq->pt;
1246 	union perf_event *event = ptq->event_buf;
1247 	struct perf_sample sample = { .ip = 0, };
1248 	struct perf_synth_intel_ptwrite raw;
1249 
1250 	if (intel_pt_skip_event(pt))
1251 		return 0;
1252 
1253 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1254 
1255 	sample.id = ptq->pt->ptwrites_id;
1256 	sample.stream_id = ptq->pt->ptwrites_id;
1257 
1258 	raw.flags = 0;
1259 	raw.ip = !!(ptq->state->flags & INTEL_PT_FUP_IP);
1260 	raw.payload = cpu_to_le64(ptq->state->ptw_payload);
1261 
1262 	sample.raw_size = perf_synth__raw_size(raw);
1263 	sample.raw_data = perf_synth__raw_data(&raw);
1264 
1265 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1266 					    pt->ptwrites_sample_type);
1267 }
1268 
1269 static int intel_pt_synth_cbr_sample(struct intel_pt_queue *ptq)
1270 {
1271 	struct intel_pt *pt = ptq->pt;
1272 	union perf_event *event = ptq->event_buf;
1273 	struct perf_sample sample = { .ip = 0, };
1274 	struct perf_synth_intel_cbr raw;
1275 	u32 flags;
1276 
1277 	if (intel_pt_skip_event(pt))
1278 		return 0;
1279 
1280 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1281 
1282 	sample.id = ptq->pt->cbr_id;
1283 	sample.stream_id = ptq->pt->cbr_id;
1284 
1285 	flags = (u16)ptq->state->cbr_payload | (pt->max_non_turbo_ratio << 16);
1286 	raw.flags = cpu_to_le32(flags);
1287 	raw.freq = cpu_to_le32(raw.cbr * pt->cbr2khz);
1288 	raw.reserved3 = 0;
1289 
1290 	sample.raw_size = perf_synth__raw_size(raw);
1291 	sample.raw_data = perf_synth__raw_data(&raw);
1292 
1293 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1294 					    pt->pwr_events_sample_type);
1295 }
1296 
1297 static int intel_pt_synth_mwait_sample(struct intel_pt_queue *ptq)
1298 {
1299 	struct intel_pt *pt = ptq->pt;
1300 	union perf_event *event = ptq->event_buf;
1301 	struct perf_sample sample = { .ip = 0, };
1302 	struct perf_synth_intel_mwait raw;
1303 
1304 	if (intel_pt_skip_event(pt))
1305 		return 0;
1306 
1307 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1308 
1309 	sample.id = ptq->pt->mwait_id;
1310 	sample.stream_id = ptq->pt->mwait_id;
1311 
1312 	raw.reserved = 0;
1313 	raw.payload = cpu_to_le64(ptq->state->mwait_payload);
1314 
1315 	sample.raw_size = perf_synth__raw_size(raw);
1316 	sample.raw_data = perf_synth__raw_data(&raw);
1317 
1318 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1319 					    pt->pwr_events_sample_type);
1320 }
1321 
1322 static int intel_pt_synth_pwre_sample(struct intel_pt_queue *ptq)
1323 {
1324 	struct intel_pt *pt = ptq->pt;
1325 	union perf_event *event = ptq->event_buf;
1326 	struct perf_sample sample = { .ip = 0, };
1327 	struct perf_synth_intel_pwre raw;
1328 
1329 	if (intel_pt_skip_event(pt))
1330 		return 0;
1331 
1332 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1333 
1334 	sample.id = ptq->pt->pwre_id;
1335 	sample.stream_id = ptq->pt->pwre_id;
1336 
1337 	raw.reserved = 0;
1338 	raw.payload = cpu_to_le64(ptq->state->pwre_payload);
1339 
1340 	sample.raw_size = perf_synth__raw_size(raw);
1341 	sample.raw_data = perf_synth__raw_data(&raw);
1342 
1343 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1344 					    pt->pwr_events_sample_type);
1345 }
1346 
1347 static int intel_pt_synth_exstop_sample(struct intel_pt_queue *ptq)
1348 {
1349 	struct intel_pt *pt = ptq->pt;
1350 	union perf_event *event = ptq->event_buf;
1351 	struct perf_sample sample = { .ip = 0, };
1352 	struct perf_synth_intel_exstop raw;
1353 
1354 	if (intel_pt_skip_event(pt))
1355 		return 0;
1356 
1357 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1358 
1359 	sample.id = ptq->pt->exstop_id;
1360 	sample.stream_id = ptq->pt->exstop_id;
1361 
1362 	raw.flags = 0;
1363 	raw.ip = !!(ptq->state->flags & INTEL_PT_FUP_IP);
1364 
1365 	sample.raw_size = perf_synth__raw_size(raw);
1366 	sample.raw_data = perf_synth__raw_data(&raw);
1367 
1368 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1369 					    pt->pwr_events_sample_type);
1370 }
1371 
1372 static int intel_pt_synth_pwrx_sample(struct intel_pt_queue *ptq)
1373 {
1374 	struct intel_pt *pt = ptq->pt;
1375 	union perf_event *event = ptq->event_buf;
1376 	struct perf_sample sample = { .ip = 0, };
1377 	struct perf_synth_intel_pwrx raw;
1378 
1379 	if (intel_pt_skip_event(pt))
1380 		return 0;
1381 
1382 	intel_pt_prep_p_sample(pt, ptq, event, &sample);
1383 
1384 	sample.id = ptq->pt->pwrx_id;
1385 	sample.stream_id = ptq->pt->pwrx_id;
1386 
1387 	raw.reserved = 0;
1388 	raw.payload = cpu_to_le64(ptq->state->pwrx_payload);
1389 
1390 	sample.raw_size = perf_synth__raw_size(raw);
1391 	sample.raw_data = perf_synth__raw_data(&raw);
1392 
1393 	return intel_pt_deliver_synth_event(pt, ptq, event, &sample,
1394 					    pt->pwr_events_sample_type);
1395 }
1396 
1397 static int intel_pt_synth_error(struct intel_pt *pt, int code, int cpu,
1398 				pid_t pid, pid_t tid, u64 ip)
1399 {
1400 	union perf_event event;
1401 	char msg[MAX_AUXTRACE_ERROR_MSG];
1402 	int err;
1403 
1404 	intel_pt__strerror(code, msg, MAX_AUXTRACE_ERROR_MSG);
1405 
1406 	auxtrace_synth_error(&event.auxtrace_error, PERF_AUXTRACE_ERROR_ITRACE,
1407 			     code, cpu, pid, tid, ip, msg);
1408 
1409 	err = perf_session__deliver_synth_event(pt->session, &event, NULL);
1410 	if (err)
1411 		pr_err("Intel Processor Trace: failed to deliver error event, error %d\n",
1412 		       err);
1413 
1414 	return err;
1415 }
1416 
1417 static int intel_pt_next_tid(struct intel_pt *pt, struct intel_pt_queue *ptq)
1418 {
1419 	struct auxtrace_queue *queue;
1420 	pid_t tid = ptq->next_tid;
1421 	int err;
1422 
1423 	if (tid == -1)
1424 		return 0;
1425 
1426 	intel_pt_log("switch: cpu %d tid %d\n", ptq->cpu, tid);
1427 
1428 	err = machine__set_current_tid(pt->machine, ptq->cpu, -1, tid);
1429 
1430 	queue = &pt->queues.queue_array[ptq->queue_nr];
1431 	intel_pt_set_pid_tid_cpu(pt, queue);
1432 
1433 	ptq->next_tid = -1;
1434 
1435 	return err;
1436 }
1437 
1438 static inline bool intel_pt_is_switch_ip(struct intel_pt_queue *ptq, u64 ip)
1439 {
1440 	struct intel_pt *pt = ptq->pt;
1441 
1442 	return ip == pt->switch_ip &&
1443 	       (ptq->flags & PERF_IP_FLAG_BRANCH) &&
1444 	       !(ptq->flags & (PERF_IP_FLAG_CONDITIONAL | PERF_IP_FLAG_ASYNC |
1445 			       PERF_IP_FLAG_INTERRUPT | PERF_IP_FLAG_TX_ABORT));
1446 }
1447 
1448 #define INTEL_PT_PWR_EVT (INTEL_PT_MWAIT_OP | INTEL_PT_PWR_ENTRY | \
1449 			  INTEL_PT_EX_STOP | INTEL_PT_PWR_EXIT | \
1450 			  INTEL_PT_CBR_CHG)
1451 
1452 static int intel_pt_sample(struct intel_pt_queue *ptq)
1453 {
1454 	const struct intel_pt_state *state = ptq->state;
1455 	struct intel_pt *pt = ptq->pt;
1456 	int err;
1457 
1458 	if (!ptq->have_sample)
1459 		return 0;
1460 
1461 	ptq->have_sample = false;
1462 
1463 	if (pt->sample_pwr_events && (state->type & INTEL_PT_PWR_EVT)) {
1464 		if (state->type & INTEL_PT_CBR_CHG) {
1465 			err = intel_pt_synth_cbr_sample(ptq);
1466 			if (err)
1467 				return err;
1468 		}
1469 		if (state->type & INTEL_PT_MWAIT_OP) {
1470 			err = intel_pt_synth_mwait_sample(ptq);
1471 			if (err)
1472 				return err;
1473 		}
1474 		if (state->type & INTEL_PT_PWR_ENTRY) {
1475 			err = intel_pt_synth_pwre_sample(ptq);
1476 			if (err)
1477 				return err;
1478 		}
1479 		if (state->type & INTEL_PT_EX_STOP) {
1480 			err = intel_pt_synth_exstop_sample(ptq);
1481 			if (err)
1482 				return err;
1483 		}
1484 		if (state->type & INTEL_PT_PWR_EXIT) {
1485 			err = intel_pt_synth_pwrx_sample(ptq);
1486 			if (err)
1487 				return err;
1488 		}
1489 	}
1490 
1491 	if (pt->sample_instructions && (state->type & INTEL_PT_INSTRUCTION)) {
1492 		err = intel_pt_synth_instruction_sample(ptq);
1493 		if (err)
1494 			return err;
1495 	}
1496 
1497 	if (pt->sample_transactions && (state->type & INTEL_PT_TRANSACTION)) {
1498 		err = intel_pt_synth_transaction_sample(ptq);
1499 		if (err)
1500 			return err;
1501 	}
1502 
1503 	if (pt->sample_ptwrites && (state->type & INTEL_PT_PTW)) {
1504 		err = intel_pt_synth_ptwrite_sample(ptq);
1505 		if (err)
1506 			return err;
1507 	}
1508 
1509 	if (!(state->type & INTEL_PT_BRANCH))
1510 		return 0;
1511 
1512 	if (pt->synth_opts.callchain || pt->synth_opts.thread_stack)
1513 		thread_stack__event(ptq->thread, ptq->flags, state->from_ip,
1514 				    state->to_ip, ptq->insn_len,
1515 				    state->trace_nr);
1516 	else
1517 		thread_stack__set_trace_nr(ptq->thread, state->trace_nr);
1518 
1519 	if (pt->sample_branches) {
1520 		err = intel_pt_synth_branch_sample(ptq);
1521 		if (err)
1522 			return err;
1523 	}
1524 
1525 	if (pt->synth_opts.last_branch)
1526 		intel_pt_update_last_branch_rb(ptq);
1527 
1528 	if (!ptq->sync_switch)
1529 		return 0;
1530 
1531 	if (intel_pt_is_switch_ip(ptq, state->to_ip)) {
1532 		switch (ptq->switch_state) {
1533 		case INTEL_PT_SS_NOT_TRACING:
1534 		case INTEL_PT_SS_UNKNOWN:
1535 		case INTEL_PT_SS_EXPECTING_SWITCH_IP:
1536 			err = intel_pt_next_tid(pt, ptq);
1537 			if (err)
1538 				return err;
1539 			ptq->switch_state = INTEL_PT_SS_TRACING;
1540 			break;
1541 		default:
1542 			ptq->switch_state = INTEL_PT_SS_EXPECTING_SWITCH_EVENT;
1543 			return 1;
1544 		}
1545 	} else if (!state->to_ip) {
1546 		ptq->switch_state = INTEL_PT_SS_NOT_TRACING;
1547 	} else if (ptq->switch_state == INTEL_PT_SS_NOT_TRACING) {
1548 		ptq->switch_state = INTEL_PT_SS_UNKNOWN;
1549 	} else if (ptq->switch_state == INTEL_PT_SS_UNKNOWN &&
1550 		   state->to_ip == pt->ptss_ip &&
1551 		   (ptq->flags & PERF_IP_FLAG_CALL)) {
1552 		ptq->switch_state = INTEL_PT_SS_TRACING;
1553 	}
1554 
1555 	return 0;
1556 }
1557 
1558 static u64 intel_pt_switch_ip(struct intel_pt *pt, u64 *ptss_ip)
1559 {
1560 	struct machine *machine = pt->machine;
1561 	struct map *map;
1562 	struct symbol *sym, *start;
1563 	u64 ip, switch_ip = 0;
1564 	const char *ptss;
1565 
1566 	if (ptss_ip)
1567 		*ptss_ip = 0;
1568 
1569 	map = machine__kernel_map(machine);
1570 	if (!map)
1571 		return 0;
1572 
1573 	if (map__load(map))
1574 		return 0;
1575 
1576 	start = dso__first_symbol(map->dso);
1577 
1578 	for (sym = start; sym; sym = dso__next_symbol(sym)) {
1579 		if (sym->binding == STB_GLOBAL &&
1580 		    !strcmp(sym->name, "__switch_to")) {
1581 			ip = map->unmap_ip(map, sym->start);
1582 			if (ip >= map->start && ip < map->end) {
1583 				switch_ip = ip;
1584 				break;
1585 			}
1586 		}
1587 	}
1588 
1589 	if (!switch_ip || !ptss_ip)
1590 		return 0;
1591 
1592 	if (pt->have_sched_switch == 1)
1593 		ptss = "perf_trace_sched_switch";
1594 	else
1595 		ptss = "__perf_event_task_sched_out";
1596 
1597 	for (sym = start; sym; sym = dso__next_symbol(sym)) {
1598 		if (!strcmp(sym->name, ptss)) {
1599 			ip = map->unmap_ip(map, sym->start);
1600 			if (ip >= map->start && ip < map->end) {
1601 				*ptss_ip = ip;
1602 				break;
1603 			}
1604 		}
1605 	}
1606 
1607 	return switch_ip;
1608 }
1609 
1610 static void intel_pt_enable_sync_switch(struct intel_pt *pt)
1611 {
1612 	unsigned int i;
1613 
1614 	pt->sync_switch = true;
1615 
1616 	for (i = 0; i < pt->queues.nr_queues; i++) {
1617 		struct auxtrace_queue *queue = &pt->queues.queue_array[i];
1618 		struct intel_pt_queue *ptq = queue->priv;
1619 
1620 		if (ptq)
1621 			ptq->sync_switch = true;
1622 	}
1623 }
1624 
1625 static int intel_pt_run_decoder(struct intel_pt_queue *ptq, u64 *timestamp)
1626 {
1627 	const struct intel_pt_state *state = ptq->state;
1628 	struct intel_pt *pt = ptq->pt;
1629 	int err;
1630 
1631 	if (!pt->kernel_start) {
1632 		pt->kernel_start = machine__kernel_start(pt->machine);
1633 		if (pt->per_cpu_mmaps &&
1634 		    (pt->have_sched_switch == 1 || pt->have_sched_switch == 3) &&
1635 		    !pt->timeless_decoding && intel_pt_tracing_kernel(pt) &&
1636 		    !pt->sampling_mode) {
1637 			pt->switch_ip = intel_pt_switch_ip(pt, &pt->ptss_ip);
1638 			if (pt->switch_ip) {
1639 				intel_pt_log("switch_ip: %"PRIx64" ptss_ip: %"PRIx64"\n",
1640 					     pt->switch_ip, pt->ptss_ip);
1641 				intel_pt_enable_sync_switch(pt);
1642 			}
1643 		}
1644 	}
1645 
1646 	intel_pt_log("queue %u decoding cpu %d pid %d tid %d\n",
1647 		     ptq->queue_nr, ptq->cpu, ptq->pid, ptq->tid);
1648 	while (1) {
1649 		err = intel_pt_sample(ptq);
1650 		if (err)
1651 			return err;
1652 
1653 		state = intel_pt_decode(ptq->decoder);
1654 		if (state->err) {
1655 			if (state->err == INTEL_PT_ERR_NODATA)
1656 				return 1;
1657 			if (ptq->sync_switch &&
1658 			    state->from_ip >= pt->kernel_start) {
1659 				ptq->sync_switch = false;
1660 				intel_pt_next_tid(pt, ptq);
1661 			}
1662 			if (pt->synth_opts.errors) {
1663 				err = intel_pt_synth_error(pt, state->err,
1664 							   ptq->cpu, ptq->pid,
1665 							   ptq->tid,
1666 							   state->from_ip);
1667 				if (err)
1668 					return err;
1669 			}
1670 			continue;
1671 		}
1672 
1673 		ptq->state = state;
1674 		ptq->have_sample = true;
1675 		intel_pt_sample_flags(ptq);
1676 
1677 		/* Use estimated TSC upon return to user space */
1678 		if (pt->est_tsc &&
1679 		    (state->from_ip >= pt->kernel_start || !state->from_ip) &&
1680 		    state->to_ip && state->to_ip < pt->kernel_start) {
1681 			intel_pt_log("TSC %"PRIx64" est. TSC %"PRIx64"\n",
1682 				     state->timestamp, state->est_timestamp);
1683 			ptq->timestamp = state->est_timestamp;
1684 		/* Use estimated TSC in unknown switch state */
1685 		} else if (ptq->sync_switch &&
1686 			   ptq->switch_state == INTEL_PT_SS_UNKNOWN &&
1687 			   intel_pt_is_switch_ip(ptq, state->to_ip) &&
1688 			   ptq->next_tid == -1) {
1689 			intel_pt_log("TSC %"PRIx64" est. TSC %"PRIx64"\n",
1690 				     state->timestamp, state->est_timestamp);
1691 			ptq->timestamp = state->est_timestamp;
1692 		} else if (state->timestamp > ptq->timestamp) {
1693 			ptq->timestamp = state->timestamp;
1694 		}
1695 
1696 		if (!pt->timeless_decoding && ptq->timestamp >= *timestamp) {
1697 			*timestamp = ptq->timestamp;
1698 			return 0;
1699 		}
1700 	}
1701 	return 0;
1702 }
1703 
1704 static inline int intel_pt_update_queues(struct intel_pt *pt)
1705 {
1706 	if (pt->queues.new_data) {
1707 		pt->queues.new_data = false;
1708 		return intel_pt_setup_queues(pt);
1709 	}
1710 	return 0;
1711 }
1712 
1713 static int intel_pt_process_queues(struct intel_pt *pt, u64 timestamp)
1714 {
1715 	unsigned int queue_nr;
1716 	u64 ts;
1717 	int ret;
1718 
1719 	while (1) {
1720 		struct auxtrace_queue *queue;
1721 		struct intel_pt_queue *ptq;
1722 
1723 		if (!pt->heap.heap_cnt)
1724 			return 0;
1725 
1726 		if (pt->heap.heap_array[0].ordinal >= timestamp)
1727 			return 0;
1728 
1729 		queue_nr = pt->heap.heap_array[0].queue_nr;
1730 		queue = &pt->queues.queue_array[queue_nr];
1731 		ptq = queue->priv;
1732 
1733 		intel_pt_log("queue %u processing 0x%" PRIx64 " to 0x%" PRIx64 "\n",
1734 			     queue_nr, pt->heap.heap_array[0].ordinal,
1735 			     timestamp);
1736 
1737 		auxtrace_heap__pop(&pt->heap);
1738 
1739 		if (pt->heap.heap_cnt) {
1740 			ts = pt->heap.heap_array[0].ordinal + 1;
1741 			if (ts > timestamp)
1742 				ts = timestamp;
1743 		} else {
1744 			ts = timestamp;
1745 		}
1746 
1747 		intel_pt_set_pid_tid_cpu(pt, queue);
1748 
1749 		ret = intel_pt_run_decoder(ptq, &ts);
1750 
1751 		if (ret < 0) {
1752 			auxtrace_heap__add(&pt->heap, queue_nr, ts);
1753 			return ret;
1754 		}
1755 
1756 		if (!ret) {
1757 			ret = auxtrace_heap__add(&pt->heap, queue_nr, ts);
1758 			if (ret < 0)
1759 				return ret;
1760 		} else {
1761 			ptq->on_heap = false;
1762 		}
1763 	}
1764 
1765 	return 0;
1766 }
1767 
1768 static int intel_pt_process_timeless_queues(struct intel_pt *pt, pid_t tid,
1769 					    u64 time_)
1770 {
1771 	struct auxtrace_queues *queues = &pt->queues;
1772 	unsigned int i;
1773 	u64 ts = 0;
1774 
1775 	for (i = 0; i < queues->nr_queues; i++) {
1776 		struct auxtrace_queue *queue = &pt->queues.queue_array[i];
1777 		struct intel_pt_queue *ptq = queue->priv;
1778 
1779 		if (ptq && (tid == -1 || ptq->tid == tid)) {
1780 			ptq->time = time_;
1781 			intel_pt_set_pid_tid_cpu(pt, queue);
1782 			intel_pt_run_decoder(ptq, &ts);
1783 		}
1784 	}
1785 	return 0;
1786 }
1787 
1788 static int intel_pt_lost(struct intel_pt *pt, struct perf_sample *sample)
1789 {
1790 	return intel_pt_synth_error(pt, INTEL_PT_ERR_LOST, sample->cpu,
1791 				    sample->pid, sample->tid, 0);
1792 }
1793 
1794 static struct intel_pt_queue *intel_pt_cpu_to_ptq(struct intel_pt *pt, int cpu)
1795 {
1796 	unsigned i, j;
1797 
1798 	if (cpu < 0 || !pt->queues.nr_queues)
1799 		return NULL;
1800 
1801 	if ((unsigned)cpu >= pt->queues.nr_queues)
1802 		i = pt->queues.nr_queues - 1;
1803 	else
1804 		i = cpu;
1805 
1806 	if (pt->queues.queue_array[i].cpu == cpu)
1807 		return pt->queues.queue_array[i].priv;
1808 
1809 	for (j = 0; i > 0; j++) {
1810 		if (pt->queues.queue_array[--i].cpu == cpu)
1811 			return pt->queues.queue_array[i].priv;
1812 	}
1813 
1814 	for (; j < pt->queues.nr_queues; j++) {
1815 		if (pt->queues.queue_array[j].cpu == cpu)
1816 			return pt->queues.queue_array[j].priv;
1817 	}
1818 
1819 	return NULL;
1820 }
1821 
1822 static int intel_pt_sync_switch(struct intel_pt *pt, int cpu, pid_t tid,
1823 				u64 timestamp)
1824 {
1825 	struct intel_pt_queue *ptq;
1826 	int err;
1827 
1828 	if (!pt->sync_switch)
1829 		return 1;
1830 
1831 	ptq = intel_pt_cpu_to_ptq(pt, cpu);
1832 	if (!ptq || !ptq->sync_switch)
1833 		return 1;
1834 
1835 	switch (ptq->switch_state) {
1836 	case INTEL_PT_SS_NOT_TRACING:
1837 		ptq->next_tid = -1;
1838 		break;
1839 	case INTEL_PT_SS_UNKNOWN:
1840 	case INTEL_PT_SS_TRACING:
1841 		ptq->next_tid = tid;
1842 		ptq->switch_state = INTEL_PT_SS_EXPECTING_SWITCH_IP;
1843 		return 0;
1844 	case INTEL_PT_SS_EXPECTING_SWITCH_EVENT:
1845 		if (!ptq->on_heap) {
1846 			ptq->timestamp = perf_time_to_tsc(timestamp,
1847 							  &pt->tc);
1848 			err = auxtrace_heap__add(&pt->heap, ptq->queue_nr,
1849 						 ptq->timestamp);
1850 			if (err)
1851 				return err;
1852 			ptq->on_heap = true;
1853 		}
1854 		ptq->switch_state = INTEL_PT_SS_TRACING;
1855 		break;
1856 	case INTEL_PT_SS_EXPECTING_SWITCH_IP:
1857 		ptq->next_tid = tid;
1858 		intel_pt_log("ERROR: cpu %d expecting switch ip\n", cpu);
1859 		break;
1860 	default:
1861 		break;
1862 	}
1863 
1864 	return 1;
1865 }
1866 
1867 static int intel_pt_process_switch(struct intel_pt *pt,
1868 				   struct perf_sample *sample)
1869 {
1870 	struct perf_evsel *evsel;
1871 	pid_t tid;
1872 	int cpu, ret;
1873 
1874 	evsel = perf_evlist__id2evsel(pt->session->evlist, sample->id);
1875 	if (evsel != pt->switch_evsel)
1876 		return 0;
1877 
1878 	tid = perf_evsel__intval(evsel, sample, "next_pid");
1879 	cpu = sample->cpu;
1880 
1881 	intel_pt_log("sched_switch: cpu %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
1882 		     cpu, tid, sample->time, perf_time_to_tsc(sample->time,
1883 		     &pt->tc));
1884 
1885 	ret = intel_pt_sync_switch(pt, cpu, tid, sample->time);
1886 	if (ret <= 0)
1887 		return ret;
1888 
1889 	return machine__set_current_tid(pt->machine, cpu, -1, tid);
1890 }
1891 
1892 static int intel_pt_context_switch(struct intel_pt *pt, union perf_event *event,
1893 				   struct perf_sample *sample)
1894 {
1895 	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
1896 	pid_t pid, tid;
1897 	int cpu, ret;
1898 
1899 	cpu = sample->cpu;
1900 
1901 	if (pt->have_sched_switch == 3) {
1902 		if (!out)
1903 			return 0;
1904 		if (event->header.type != PERF_RECORD_SWITCH_CPU_WIDE) {
1905 			pr_err("Expecting CPU-wide context switch event\n");
1906 			return -EINVAL;
1907 		}
1908 		pid = event->context_switch.next_prev_pid;
1909 		tid = event->context_switch.next_prev_tid;
1910 	} else {
1911 		if (out)
1912 			return 0;
1913 		pid = sample->pid;
1914 		tid = sample->tid;
1915 	}
1916 
1917 	if (tid == -1) {
1918 		pr_err("context_switch event has no tid\n");
1919 		return -EINVAL;
1920 	}
1921 
1922 	intel_pt_log("context_switch: cpu %d pid %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
1923 		     cpu, pid, tid, sample->time, perf_time_to_tsc(sample->time,
1924 		     &pt->tc));
1925 
1926 	ret = intel_pt_sync_switch(pt, cpu, tid, sample->time);
1927 	if (ret <= 0)
1928 		return ret;
1929 
1930 	return machine__set_current_tid(pt->machine, cpu, pid, tid);
1931 }
1932 
1933 static int intel_pt_process_itrace_start(struct intel_pt *pt,
1934 					 union perf_event *event,
1935 					 struct perf_sample *sample)
1936 {
1937 	if (!pt->per_cpu_mmaps)
1938 		return 0;
1939 
1940 	intel_pt_log("itrace_start: cpu %d pid %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
1941 		     sample->cpu, event->itrace_start.pid,
1942 		     event->itrace_start.tid, sample->time,
1943 		     perf_time_to_tsc(sample->time, &pt->tc));
1944 
1945 	return machine__set_current_tid(pt->machine, sample->cpu,
1946 					event->itrace_start.pid,
1947 					event->itrace_start.tid);
1948 }
1949 
1950 static int intel_pt_process_event(struct perf_session *session,
1951 				  union perf_event *event,
1952 				  struct perf_sample *sample,
1953 				  struct perf_tool *tool)
1954 {
1955 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
1956 					   auxtrace);
1957 	u64 timestamp;
1958 	int err = 0;
1959 
1960 	if (dump_trace)
1961 		return 0;
1962 
1963 	if (!tool->ordered_events) {
1964 		pr_err("Intel Processor Trace requires ordered events\n");
1965 		return -EINVAL;
1966 	}
1967 
1968 	if (sample->time && sample->time != (u64)-1)
1969 		timestamp = perf_time_to_tsc(sample->time, &pt->tc);
1970 	else
1971 		timestamp = 0;
1972 
1973 	if (timestamp || pt->timeless_decoding) {
1974 		err = intel_pt_update_queues(pt);
1975 		if (err)
1976 			return err;
1977 	}
1978 
1979 	if (pt->timeless_decoding) {
1980 		if (event->header.type == PERF_RECORD_EXIT) {
1981 			err = intel_pt_process_timeless_queues(pt,
1982 							       event->fork.tid,
1983 							       sample->time);
1984 		}
1985 	} else if (timestamp) {
1986 		err = intel_pt_process_queues(pt, timestamp);
1987 	}
1988 	if (err)
1989 		return err;
1990 
1991 	if (event->header.type == PERF_RECORD_AUX &&
1992 	    (event->aux.flags & PERF_AUX_FLAG_TRUNCATED) &&
1993 	    pt->synth_opts.errors) {
1994 		err = intel_pt_lost(pt, sample);
1995 		if (err)
1996 			return err;
1997 	}
1998 
1999 	if (pt->switch_evsel && event->header.type == PERF_RECORD_SAMPLE)
2000 		err = intel_pt_process_switch(pt, sample);
2001 	else if (event->header.type == PERF_RECORD_ITRACE_START)
2002 		err = intel_pt_process_itrace_start(pt, event, sample);
2003 	else if (event->header.type == PERF_RECORD_SWITCH ||
2004 		 event->header.type == PERF_RECORD_SWITCH_CPU_WIDE)
2005 		err = intel_pt_context_switch(pt, event, sample);
2006 
2007 	intel_pt_log("event %s (%u): cpu %d time %"PRIu64" tsc %#"PRIx64"\n",
2008 		     perf_event__name(event->header.type), event->header.type,
2009 		     sample->cpu, sample->time, timestamp);
2010 
2011 	return err;
2012 }
2013 
2014 static int intel_pt_flush(struct perf_session *session, struct perf_tool *tool)
2015 {
2016 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2017 					   auxtrace);
2018 	int ret;
2019 
2020 	if (dump_trace)
2021 		return 0;
2022 
2023 	if (!tool->ordered_events)
2024 		return -EINVAL;
2025 
2026 	ret = intel_pt_update_queues(pt);
2027 	if (ret < 0)
2028 		return ret;
2029 
2030 	if (pt->timeless_decoding)
2031 		return intel_pt_process_timeless_queues(pt, -1,
2032 							MAX_TIMESTAMP - 1);
2033 
2034 	return intel_pt_process_queues(pt, MAX_TIMESTAMP);
2035 }
2036 
2037 static void intel_pt_free_events(struct perf_session *session)
2038 {
2039 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2040 					   auxtrace);
2041 	struct auxtrace_queues *queues = &pt->queues;
2042 	unsigned int i;
2043 
2044 	for (i = 0; i < queues->nr_queues; i++) {
2045 		intel_pt_free_queue(queues->queue_array[i].priv);
2046 		queues->queue_array[i].priv = NULL;
2047 	}
2048 	intel_pt_log_disable();
2049 	auxtrace_queues__free(queues);
2050 }
2051 
2052 static void intel_pt_free(struct perf_session *session)
2053 {
2054 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2055 					   auxtrace);
2056 
2057 	auxtrace_heap__free(&pt->heap);
2058 	intel_pt_free_events(session);
2059 	session->auxtrace = NULL;
2060 	thread__put(pt->unknown_thread);
2061 	addr_filters__exit(&pt->filts);
2062 	zfree(&pt->filter);
2063 	free(pt);
2064 }
2065 
2066 static int intel_pt_process_auxtrace_event(struct perf_session *session,
2067 					   union perf_event *event,
2068 					   struct perf_tool *tool __maybe_unused)
2069 {
2070 	struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
2071 					   auxtrace);
2072 
2073 	if (!pt->data_queued) {
2074 		struct auxtrace_buffer *buffer;
2075 		off_t data_offset;
2076 		int fd = perf_data__fd(session->data);
2077 		int err;
2078 
2079 		if (perf_data__is_pipe(session->data)) {
2080 			data_offset = 0;
2081 		} else {
2082 			data_offset = lseek(fd, 0, SEEK_CUR);
2083 			if (data_offset == -1)
2084 				return -errno;
2085 		}
2086 
2087 		err = auxtrace_queues__add_event(&pt->queues, session, event,
2088 						 data_offset, &buffer);
2089 		if (err)
2090 			return err;
2091 
2092 		/* Dump here now we have copied a piped trace out of the pipe */
2093 		if (dump_trace) {
2094 			if (auxtrace_buffer__get_data(buffer, fd)) {
2095 				intel_pt_dump_event(pt, buffer->data,
2096 						    buffer->size);
2097 				auxtrace_buffer__put_data(buffer);
2098 			}
2099 		}
2100 	}
2101 
2102 	return 0;
2103 }
2104 
2105 struct intel_pt_synth {
2106 	struct perf_tool dummy_tool;
2107 	struct perf_session *session;
2108 };
2109 
2110 static int intel_pt_event_synth(struct perf_tool *tool,
2111 				union perf_event *event,
2112 				struct perf_sample *sample __maybe_unused,
2113 				struct machine *machine __maybe_unused)
2114 {
2115 	struct intel_pt_synth *intel_pt_synth =
2116 			container_of(tool, struct intel_pt_synth, dummy_tool);
2117 
2118 	return perf_session__deliver_synth_event(intel_pt_synth->session, event,
2119 						 NULL);
2120 }
2121 
2122 static int intel_pt_synth_event(struct perf_session *session, const char *name,
2123 				struct perf_event_attr *attr, u64 id)
2124 {
2125 	struct intel_pt_synth intel_pt_synth;
2126 	int err;
2127 
2128 	pr_debug("Synthesizing '%s' event with id %" PRIu64 " sample type %#" PRIx64 "\n",
2129 		 name, id, (u64)attr->sample_type);
2130 
2131 	memset(&intel_pt_synth, 0, sizeof(struct intel_pt_synth));
2132 	intel_pt_synth.session = session;
2133 
2134 	err = perf_event__synthesize_attr(&intel_pt_synth.dummy_tool, attr, 1,
2135 					  &id, intel_pt_event_synth);
2136 	if (err)
2137 		pr_err("%s: failed to synthesize '%s' event type\n",
2138 		       __func__, name);
2139 
2140 	return err;
2141 }
2142 
2143 static void intel_pt_set_event_name(struct perf_evlist *evlist, u64 id,
2144 				    const char *name)
2145 {
2146 	struct perf_evsel *evsel;
2147 
2148 	evlist__for_each_entry(evlist, evsel) {
2149 		if (evsel->id && evsel->id[0] == id) {
2150 			if (evsel->name)
2151 				zfree(&evsel->name);
2152 			evsel->name = strdup(name);
2153 			break;
2154 		}
2155 	}
2156 }
2157 
2158 static struct perf_evsel *intel_pt_evsel(struct intel_pt *pt,
2159 					 struct perf_evlist *evlist)
2160 {
2161 	struct perf_evsel *evsel;
2162 
2163 	evlist__for_each_entry(evlist, evsel) {
2164 		if (evsel->attr.type == pt->pmu_type && evsel->ids)
2165 			return evsel;
2166 	}
2167 
2168 	return NULL;
2169 }
2170 
2171 static int intel_pt_synth_events(struct intel_pt *pt,
2172 				 struct perf_session *session)
2173 {
2174 	struct perf_evlist *evlist = session->evlist;
2175 	struct perf_evsel *evsel = intel_pt_evsel(pt, evlist);
2176 	struct perf_event_attr attr;
2177 	u64 id;
2178 	int err;
2179 
2180 	if (!evsel) {
2181 		pr_debug("There are no selected events with Intel Processor Trace data\n");
2182 		return 0;
2183 	}
2184 
2185 	memset(&attr, 0, sizeof(struct perf_event_attr));
2186 	attr.size = sizeof(struct perf_event_attr);
2187 	attr.type = PERF_TYPE_HARDWARE;
2188 	attr.sample_type = evsel->attr.sample_type & PERF_SAMPLE_MASK;
2189 	attr.sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID |
2190 			    PERF_SAMPLE_PERIOD;
2191 	if (pt->timeless_decoding)
2192 		attr.sample_type &= ~(u64)PERF_SAMPLE_TIME;
2193 	else
2194 		attr.sample_type |= PERF_SAMPLE_TIME;
2195 	if (!pt->per_cpu_mmaps)
2196 		attr.sample_type &= ~(u64)PERF_SAMPLE_CPU;
2197 	attr.exclude_user = evsel->attr.exclude_user;
2198 	attr.exclude_kernel = evsel->attr.exclude_kernel;
2199 	attr.exclude_hv = evsel->attr.exclude_hv;
2200 	attr.exclude_host = evsel->attr.exclude_host;
2201 	attr.exclude_guest = evsel->attr.exclude_guest;
2202 	attr.sample_id_all = evsel->attr.sample_id_all;
2203 	attr.read_format = evsel->attr.read_format;
2204 
2205 	id = evsel->id[0] + 1000000000;
2206 	if (!id)
2207 		id = 1;
2208 
2209 	if (pt->synth_opts.branches) {
2210 		attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
2211 		attr.sample_period = 1;
2212 		attr.sample_type |= PERF_SAMPLE_ADDR;
2213 		err = intel_pt_synth_event(session, "branches", &attr, id);
2214 		if (err)
2215 			return err;
2216 		pt->sample_branches = true;
2217 		pt->branches_sample_type = attr.sample_type;
2218 		pt->branches_id = id;
2219 		id += 1;
2220 		attr.sample_type &= ~(u64)PERF_SAMPLE_ADDR;
2221 	}
2222 
2223 	if (pt->synth_opts.callchain)
2224 		attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2225 	if (pt->synth_opts.last_branch)
2226 		attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
2227 
2228 	if (pt->synth_opts.instructions) {
2229 		attr.config = PERF_COUNT_HW_INSTRUCTIONS;
2230 		if (pt->synth_opts.period_type == PERF_ITRACE_PERIOD_NANOSECS)
2231 			attr.sample_period =
2232 				intel_pt_ns_to_ticks(pt, pt->synth_opts.period);
2233 		else
2234 			attr.sample_period = pt->synth_opts.period;
2235 		err = intel_pt_synth_event(session, "instructions", &attr, id);
2236 		if (err)
2237 			return err;
2238 		pt->sample_instructions = true;
2239 		pt->instructions_sample_type = attr.sample_type;
2240 		pt->instructions_id = id;
2241 		id += 1;
2242 	}
2243 
2244 	attr.sample_type &= ~(u64)PERF_SAMPLE_PERIOD;
2245 	attr.sample_period = 1;
2246 
2247 	if (pt->synth_opts.transactions) {
2248 		attr.config = PERF_COUNT_HW_INSTRUCTIONS;
2249 		err = intel_pt_synth_event(session, "transactions", &attr, id);
2250 		if (err)
2251 			return err;
2252 		pt->sample_transactions = true;
2253 		pt->transactions_sample_type = attr.sample_type;
2254 		pt->transactions_id = id;
2255 		intel_pt_set_event_name(evlist, id, "transactions");
2256 		id += 1;
2257 	}
2258 
2259 	attr.type = PERF_TYPE_SYNTH;
2260 	attr.sample_type |= PERF_SAMPLE_RAW;
2261 
2262 	if (pt->synth_opts.ptwrites) {
2263 		attr.config = PERF_SYNTH_INTEL_PTWRITE;
2264 		err = intel_pt_synth_event(session, "ptwrite", &attr, id);
2265 		if (err)
2266 			return err;
2267 		pt->sample_ptwrites = true;
2268 		pt->ptwrites_sample_type = attr.sample_type;
2269 		pt->ptwrites_id = id;
2270 		intel_pt_set_event_name(evlist, id, "ptwrite");
2271 		id += 1;
2272 	}
2273 
2274 	if (pt->synth_opts.pwr_events) {
2275 		pt->sample_pwr_events = true;
2276 		pt->pwr_events_sample_type = attr.sample_type;
2277 
2278 		attr.config = PERF_SYNTH_INTEL_CBR;
2279 		err = intel_pt_synth_event(session, "cbr", &attr, id);
2280 		if (err)
2281 			return err;
2282 		pt->cbr_id = id;
2283 		intel_pt_set_event_name(evlist, id, "cbr");
2284 		id += 1;
2285 	}
2286 
2287 	if (pt->synth_opts.pwr_events && (evsel->attr.config & 0x10)) {
2288 		attr.config = PERF_SYNTH_INTEL_MWAIT;
2289 		err = intel_pt_synth_event(session, "mwait", &attr, id);
2290 		if (err)
2291 			return err;
2292 		pt->mwait_id = id;
2293 		intel_pt_set_event_name(evlist, id, "mwait");
2294 		id += 1;
2295 
2296 		attr.config = PERF_SYNTH_INTEL_PWRE;
2297 		err = intel_pt_synth_event(session, "pwre", &attr, id);
2298 		if (err)
2299 			return err;
2300 		pt->pwre_id = id;
2301 		intel_pt_set_event_name(evlist, id, "pwre");
2302 		id += 1;
2303 
2304 		attr.config = PERF_SYNTH_INTEL_EXSTOP;
2305 		err = intel_pt_synth_event(session, "exstop", &attr, id);
2306 		if (err)
2307 			return err;
2308 		pt->exstop_id = id;
2309 		intel_pt_set_event_name(evlist, id, "exstop");
2310 		id += 1;
2311 
2312 		attr.config = PERF_SYNTH_INTEL_PWRX;
2313 		err = intel_pt_synth_event(session, "pwrx", &attr, id);
2314 		if (err)
2315 			return err;
2316 		pt->pwrx_id = id;
2317 		intel_pt_set_event_name(evlist, id, "pwrx");
2318 		id += 1;
2319 	}
2320 
2321 	return 0;
2322 }
2323 
2324 static struct perf_evsel *intel_pt_find_sched_switch(struct perf_evlist *evlist)
2325 {
2326 	struct perf_evsel *evsel;
2327 
2328 	evlist__for_each_entry_reverse(evlist, evsel) {
2329 		const char *name = perf_evsel__name(evsel);
2330 
2331 		if (!strcmp(name, "sched:sched_switch"))
2332 			return evsel;
2333 	}
2334 
2335 	return NULL;
2336 }
2337 
2338 static bool intel_pt_find_switch(struct perf_evlist *evlist)
2339 {
2340 	struct perf_evsel *evsel;
2341 
2342 	evlist__for_each_entry(evlist, evsel) {
2343 		if (evsel->attr.context_switch)
2344 			return true;
2345 	}
2346 
2347 	return false;
2348 }
2349 
2350 static int intel_pt_perf_config(const char *var, const char *value, void *data)
2351 {
2352 	struct intel_pt *pt = data;
2353 
2354 	if (!strcmp(var, "intel-pt.mispred-all"))
2355 		pt->mispred_all = perf_config_bool(var, value);
2356 
2357 	return 0;
2358 }
2359 
2360 static const char * const intel_pt_info_fmts[] = {
2361 	[INTEL_PT_PMU_TYPE]		= "  PMU Type            %"PRId64"\n",
2362 	[INTEL_PT_TIME_SHIFT]		= "  Time Shift          %"PRIu64"\n",
2363 	[INTEL_PT_TIME_MULT]		= "  Time Muliplier      %"PRIu64"\n",
2364 	[INTEL_PT_TIME_ZERO]		= "  Time Zero           %"PRIu64"\n",
2365 	[INTEL_PT_CAP_USER_TIME_ZERO]	= "  Cap Time Zero       %"PRId64"\n",
2366 	[INTEL_PT_TSC_BIT]		= "  TSC bit             %#"PRIx64"\n",
2367 	[INTEL_PT_NORETCOMP_BIT]	= "  NoRETComp bit       %#"PRIx64"\n",
2368 	[INTEL_PT_HAVE_SCHED_SWITCH]	= "  Have sched_switch   %"PRId64"\n",
2369 	[INTEL_PT_SNAPSHOT_MODE]	= "  Snapshot mode       %"PRId64"\n",
2370 	[INTEL_PT_PER_CPU_MMAPS]	= "  Per-cpu maps        %"PRId64"\n",
2371 	[INTEL_PT_MTC_BIT]		= "  MTC bit             %#"PRIx64"\n",
2372 	[INTEL_PT_TSC_CTC_N]		= "  TSC:CTC numerator   %"PRIu64"\n",
2373 	[INTEL_PT_TSC_CTC_D]		= "  TSC:CTC denominator %"PRIu64"\n",
2374 	[INTEL_PT_CYC_BIT]		= "  CYC bit             %#"PRIx64"\n",
2375 	[INTEL_PT_MAX_NONTURBO_RATIO]	= "  Max non-turbo ratio %"PRIu64"\n",
2376 	[INTEL_PT_FILTER_STR_LEN]	= "  Filter string len.  %"PRIu64"\n",
2377 };
2378 
2379 static void intel_pt_print_info(u64 *arr, int start, int finish)
2380 {
2381 	int i;
2382 
2383 	if (!dump_trace)
2384 		return;
2385 
2386 	for (i = start; i <= finish; i++)
2387 		fprintf(stdout, intel_pt_info_fmts[i], arr[i]);
2388 }
2389 
2390 static void intel_pt_print_info_str(const char *name, const char *str)
2391 {
2392 	if (!dump_trace)
2393 		return;
2394 
2395 	fprintf(stdout, "  %-20s%s\n", name, str ? str : "");
2396 }
2397 
2398 static bool intel_pt_has(struct auxtrace_info_event *auxtrace_info, int pos)
2399 {
2400 	return auxtrace_info->header.size >=
2401 		sizeof(struct auxtrace_info_event) + (sizeof(u64) * (pos + 1));
2402 }
2403 
2404 int intel_pt_process_auxtrace_info(union perf_event *event,
2405 				   struct perf_session *session)
2406 {
2407 	struct auxtrace_info_event *auxtrace_info = &event->auxtrace_info;
2408 	size_t min_sz = sizeof(u64) * INTEL_PT_PER_CPU_MMAPS;
2409 	struct intel_pt *pt;
2410 	void *info_end;
2411 	u64 *info;
2412 	int err;
2413 
2414 	if (auxtrace_info->header.size < sizeof(struct auxtrace_info_event) +
2415 					min_sz)
2416 		return -EINVAL;
2417 
2418 	pt = zalloc(sizeof(struct intel_pt));
2419 	if (!pt)
2420 		return -ENOMEM;
2421 
2422 	addr_filters__init(&pt->filts);
2423 
2424 	err = perf_config(intel_pt_perf_config, pt);
2425 	if (err)
2426 		goto err_free;
2427 
2428 	err = auxtrace_queues__init(&pt->queues);
2429 	if (err)
2430 		goto err_free;
2431 
2432 	intel_pt_log_set_name(INTEL_PT_PMU_NAME);
2433 
2434 	pt->session = session;
2435 	pt->machine = &session->machines.host; /* No kvm support */
2436 	pt->auxtrace_type = auxtrace_info->type;
2437 	pt->pmu_type = auxtrace_info->priv[INTEL_PT_PMU_TYPE];
2438 	pt->tc.time_shift = auxtrace_info->priv[INTEL_PT_TIME_SHIFT];
2439 	pt->tc.time_mult = auxtrace_info->priv[INTEL_PT_TIME_MULT];
2440 	pt->tc.time_zero = auxtrace_info->priv[INTEL_PT_TIME_ZERO];
2441 	pt->cap_user_time_zero = auxtrace_info->priv[INTEL_PT_CAP_USER_TIME_ZERO];
2442 	pt->tsc_bit = auxtrace_info->priv[INTEL_PT_TSC_BIT];
2443 	pt->noretcomp_bit = auxtrace_info->priv[INTEL_PT_NORETCOMP_BIT];
2444 	pt->have_sched_switch = auxtrace_info->priv[INTEL_PT_HAVE_SCHED_SWITCH];
2445 	pt->snapshot_mode = auxtrace_info->priv[INTEL_PT_SNAPSHOT_MODE];
2446 	pt->per_cpu_mmaps = auxtrace_info->priv[INTEL_PT_PER_CPU_MMAPS];
2447 	intel_pt_print_info(&auxtrace_info->priv[0], INTEL_PT_PMU_TYPE,
2448 			    INTEL_PT_PER_CPU_MMAPS);
2449 
2450 	if (intel_pt_has(auxtrace_info, INTEL_PT_CYC_BIT)) {
2451 		pt->mtc_bit = auxtrace_info->priv[INTEL_PT_MTC_BIT];
2452 		pt->mtc_freq_bits = auxtrace_info->priv[INTEL_PT_MTC_FREQ_BITS];
2453 		pt->tsc_ctc_ratio_n = auxtrace_info->priv[INTEL_PT_TSC_CTC_N];
2454 		pt->tsc_ctc_ratio_d = auxtrace_info->priv[INTEL_PT_TSC_CTC_D];
2455 		pt->cyc_bit = auxtrace_info->priv[INTEL_PT_CYC_BIT];
2456 		intel_pt_print_info(&auxtrace_info->priv[0], INTEL_PT_MTC_BIT,
2457 				    INTEL_PT_CYC_BIT);
2458 	}
2459 
2460 	if (intel_pt_has(auxtrace_info, INTEL_PT_MAX_NONTURBO_RATIO)) {
2461 		pt->max_non_turbo_ratio =
2462 			auxtrace_info->priv[INTEL_PT_MAX_NONTURBO_RATIO];
2463 		intel_pt_print_info(&auxtrace_info->priv[0],
2464 				    INTEL_PT_MAX_NONTURBO_RATIO,
2465 				    INTEL_PT_MAX_NONTURBO_RATIO);
2466 	}
2467 
2468 	info = &auxtrace_info->priv[INTEL_PT_FILTER_STR_LEN] + 1;
2469 	info_end = (void *)info + auxtrace_info->header.size;
2470 
2471 	if (intel_pt_has(auxtrace_info, INTEL_PT_FILTER_STR_LEN)) {
2472 		size_t len;
2473 
2474 		len = auxtrace_info->priv[INTEL_PT_FILTER_STR_LEN];
2475 		intel_pt_print_info(&auxtrace_info->priv[0],
2476 				    INTEL_PT_FILTER_STR_LEN,
2477 				    INTEL_PT_FILTER_STR_LEN);
2478 		if (len) {
2479 			const char *filter = (const char *)info;
2480 
2481 			len = roundup(len + 1, 8);
2482 			info += len >> 3;
2483 			if ((void *)info > info_end) {
2484 				pr_err("%s: bad filter string length\n", __func__);
2485 				err = -EINVAL;
2486 				goto err_free_queues;
2487 			}
2488 			pt->filter = memdup(filter, len);
2489 			if (!pt->filter) {
2490 				err = -ENOMEM;
2491 				goto err_free_queues;
2492 			}
2493 			if (session->header.needs_swap)
2494 				mem_bswap_64(pt->filter, len);
2495 			if (pt->filter[len - 1]) {
2496 				pr_err("%s: filter string not null terminated\n", __func__);
2497 				err = -EINVAL;
2498 				goto err_free_queues;
2499 			}
2500 			err = addr_filters__parse_bare_filter(&pt->filts,
2501 							      filter);
2502 			if (err)
2503 				goto err_free_queues;
2504 		}
2505 		intel_pt_print_info_str("Filter string", pt->filter);
2506 	}
2507 
2508 	pt->timeless_decoding = intel_pt_timeless_decoding(pt);
2509 	pt->have_tsc = intel_pt_have_tsc(pt);
2510 	pt->sampling_mode = false;
2511 	pt->est_tsc = !pt->timeless_decoding;
2512 
2513 	pt->unknown_thread = thread__new(999999999, 999999999);
2514 	if (!pt->unknown_thread) {
2515 		err = -ENOMEM;
2516 		goto err_free_queues;
2517 	}
2518 
2519 	/*
2520 	 * Since this thread will not be kept in any rbtree not in a
2521 	 * list, initialize its list node so that at thread__put() the
2522 	 * current thread lifetime assuption is kept and we don't segfault
2523 	 * at list_del_init().
2524 	 */
2525 	INIT_LIST_HEAD(&pt->unknown_thread->node);
2526 
2527 	err = thread__set_comm(pt->unknown_thread, "unknown", 0);
2528 	if (err)
2529 		goto err_delete_thread;
2530 	if (thread__init_map_groups(pt->unknown_thread, pt->machine)) {
2531 		err = -ENOMEM;
2532 		goto err_delete_thread;
2533 	}
2534 
2535 	pt->auxtrace.process_event = intel_pt_process_event;
2536 	pt->auxtrace.process_auxtrace_event = intel_pt_process_auxtrace_event;
2537 	pt->auxtrace.flush_events = intel_pt_flush;
2538 	pt->auxtrace.free_events = intel_pt_free_events;
2539 	pt->auxtrace.free = intel_pt_free;
2540 	session->auxtrace = &pt->auxtrace;
2541 
2542 	if (dump_trace)
2543 		return 0;
2544 
2545 	if (pt->have_sched_switch == 1) {
2546 		pt->switch_evsel = intel_pt_find_sched_switch(session->evlist);
2547 		if (!pt->switch_evsel) {
2548 			pr_err("%s: missing sched_switch event\n", __func__);
2549 			err = -EINVAL;
2550 			goto err_delete_thread;
2551 		}
2552 	} else if (pt->have_sched_switch == 2 &&
2553 		   !intel_pt_find_switch(session->evlist)) {
2554 		pr_err("%s: missing context_switch attribute flag\n", __func__);
2555 		err = -EINVAL;
2556 		goto err_delete_thread;
2557 	}
2558 
2559 	if (session->itrace_synth_opts && session->itrace_synth_opts->set) {
2560 		pt->synth_opts = *session->itrace_synth_opts;
2561 	} else {
2562 		itrace_synth_opts__set_default(&pt->synth_opts);
2563 		if (use_browser != -1) {
2564 			pt->synth_opts.branches = false;
2565 			pt->synth_opts.callchain = true;
2566 		}
2567 		if (session->itrace_synth_opts)
2568 			pt->synth_opts.thread_stack =
2569 				session->itrace_synth_opts->thread_stack;
2570 	}
2571 
2572 	if (pt->synth_opts.log)
2573 		intel_pt_log_enable();
2574 
2575 	/* Maximum non-turbo ratio is TSC freq / 100 MHz */
2576 	if (pt->tc.time_mult) {
2577 		u64 tsc_freq = intel_pt_ns_to_ticks(pt, 1000000000);
2578 
2579 		if (!pt->max_non_turbo_ratio)
2580 			pt->max_non_turbo_ratio =
2581 					(tsc_freq + 50000000) / 100000000;
2582 		intel_pt_log("TSC frequency %"PRIu64"\n", tsc_freq);
2583 		intel_pt_log("Maximum non-turbo ratio %u\n",
2584 			     pt->max_non_turbo_ratio);
2585 		pt->cbr2khz = tsc_freq / pt->max_non_turbo_ratio / 1000;
2586 	}
2587 
2588 	if (pt->synth_opts.calls)
2589 		pt->branches_filter |= PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC |
2590 				       PERF_IP_FLAG_TRACE_END;
2591 	if (pt->synth_opts.returns)
2592 		pt->branches_filter |= PERF_IP_FLAG_RETURN |
2593 				       PERF_IP_FLAG_TRACE_BEGIN;
2594 
2595 	if (pt->synth_opts.callchain && !symbol_conf.use_callchain) {
2596 		symbol_conf.use_callchain = true;
2597 		if (callchain_register_param(&callchain_param) < 0) {
2598 			symbol_conf.use_callchain = false;
2599 			pt->synth_opts.callchain = false;
2600 		}
2601 	}
2602 
2603 	err = intel_pt_synth_events(pt, session);
2604 	if (err)
2605 		goto err_delete_thread;
2606 
2607 	err = auxtrace_queues__process_index(&pt->queues, session);
2608 	if (err)
2609 		goto err_delete_thread;
2610 
2611 	if (pt->queues.populated)
2612 		pt->data_queued = true;
2613 
2614 	if (pt->timeless_decoding)
2615 		pr_debug2("Intel PT decoding without timestamps\n");
2616 
2617 	return 0;
2618 
2619 err_delete_thread:
2620 	thread__zput(pt->unknown_thread);
2621 err_free_queues:
2622 	intel_pt_log_disable();
2623 	auxtrace_queues__free(&pt->queues);
2624 	session->auxtrace = NULL;
2625 err_free:
2626 	addr_filters__exit(&pt->filts);
2627 	zfree(&pt->filter);
2628 	free(pt);
2629 	return err;
2630 }
2631