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