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