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