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