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