Upgrade to 4.4.50-rt62
[kvmfornfv.git] / kernel / tools / perf / util / intel-pt.c
1 /*
2  * intel_pt.c: Intel Processor Trace support
3  * Copyright (c) 2013-2015, Intel Corporation.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  *
14  */
15
16 #include <stdio.h>
17 #include <stdbool.h>
18 #include <errno.h>
19 #include <linux/kernel.h>
20 #include <linux/types.h>
21
22 #include "../perf.h"
23 #include "session.h"
24 #include "machine.h"
25 #include "sort.h"
26 #include "tool.h"
27 #include "event.h"
28 #include "evlist.h"
29 #include "evsel.h"
30 #include "map.h"
31 #include "color.h"
32 #include "util.h"
33 #include "thread.h"
34 #include "thread-stack.h"
35 #include "symbol.h"
36 #include "callchain.h"
37 #include "dso.h"
38 #include "debug.h"
39 #include "auxtrace.h"
40 #include "tsc.h"
41 #include "intel-pt.h"
42
43 #include "intel-pt-decoder/intel-pt-log.h"
44 #include "intel-pt-decoder/intel-pt-decoder.h"
45 #include "intel-pt-decoder/intel-pt-insn-decoder.h"
46 #include "intel-pt-decoder/intel-pt-pkt-decoder.h"
47
48 #define MAX_TIMESTAMP (~0ULL)
49
50 struct intel_pt {
51         struct auxtrace auxtrace;
52         struct auxtrace_queues queues;
53         struct auxtrace_heap heap;
54         u32 auxtrace_type;
55         struct perf_session *session;
56         struct machine *machine;
57         struct perf_evsel *switch_evsel;
58         struct thread *unknown_thread;
59         bool timeless_decoding;
60         bool sampling_mode;
61         bool snapshot_mode;
62         bool per_cpu_mmaps;
63         bool have_tsc;
64         bool data_queued;
65         bool est_tsc;
66         bool sync_switch;
67         bool mispred_all;
68         int have_sched_switch;
69         u32 pmu_type;
70         u64 kernel_start;
71         u64 switch_ip;
72         u64 ptss_ip;
73
74         struct perf_tsc_conversion tc;
75         bool cap_user_time_zero;
76
77         struct itrace_synth_opts synth_opts;
78
79         bool sample_instructions;
80         u64 instructions_sample_type;
81         u64 instructions_sample_period;
82         u64 instructions_id;
83
84         bool sample_branches;
85         u32 branches_filter;
86         u64 branches_sample_type;
87         u64 branches_id;
88
89         bool sample_transactions;
90         u64 transactions_sample_type;
91         u64 transactions_id;
92
93         bool synth_needs_swap;
94
95         u64 tsc_bit;
96         u64 mtc_bit;
97         u64 mtc_freq_bits;
98         u32 tsc_ctc_ratio_n;
99         u32 tsc_ctc_ratio_d;
100         u64 cyc_bit;
101         u64 noretcomp_bit;
102         unsigned max_non_turbo_ratio;
103 };
104
105 enum switch_state {
106         INTEL_PT_SS_NOT_TRACING,
107         INTEL_PT_SS_UNKNOWN,
108         INTEL_PT_SS_TRACING,
109         INTEL_PT_SS_EXPECTING_SWITCH_EVENT,
110         INTEL_PT_SS_EXPECTING_SWITCH_IP,
111 };
112
113 struct intel_pt_queue {
114         struct intel_pt *pt;
115         unsigned int queue_nr;
116         struct auxtrace_buffer *buffer;
117         void *decoder;
118         const struct intel_pt_state *state;
119         struct ip_callchain *chain;
120         struct branch_stack *last_branch;
121         struct branch_stack *last_branch_rb;
122         size_t last_branch_pos;
123         union perf_event *event_buf;
124         bool on_heap;
125         bool stop;
126         bool step_through_buffers;
127         bool use_buffer_pid_tid;
128         pid_t pid, tid;
129         int cpu;
130         int switch_state;
131         pid_t next_tid;
132         struct thread *thread;
133         bool exclude_kernel;
134         bool have_sample;
135         u64 time;
136         u64 timestamp;
137         u32 flags;
138         u16 insn_len;
139         u64 last_insn_cnt;
140 };
141
142 static void intel_pt_dump(struct intel_pt *pt __maybe_unused,
143                           unsigned char *buf, size_t len)
144 {
145         struct intel_pt_pkt packet;
146         size_t pos = 0;
147         int ret, pkt_len, i;
148         char desc[INTEL_PT_PKT_DESC_MAX];
149         const char *color = PERF_COLOR_BLUE;
150
151         color_fprintf(stdout, color,
152                       ". ... Intel Processor Trace data: size %zu bytes\n",
153                       len);
154
155         while (len) {
156                 ret = intel_pt_get_packet(buf, len, &packet);
157                 if (ret > 0)
158                         pkt_len = ret;
159                 else
160                         pkt_len = 1;
161                 printf(".");
162                 color_fprintf(stdout, color, "  %08x: ", pos);
163                 for (i = 0; i < pkt_len; i++)
164                         color_fprintf(stdout, color, " %02x", buf[i]);
165                 for (; i < 16; i++)
166                         color_fprintf(stdout, color, "   ");
167                 if (ret > 0) {
168                         ret = intel_pt_pkt_desc(&packet, desc,
169                                                 INTEL_PT_PKT_DESC_MAX);
170                         if (ret > 0)
171                                 color_fprintf(stdout, color, " %s\n", desc);
172                 } else {
173                         color_fprintf(stdout, color, " Bad packet!\n");
174                 }
175                 pos += pkt_len;
176                 buf += pkt_len;
177                 len -= pkt_len;
178         }
179 }
180
181 static void intel_pt_dump_event(struct intel_pt *pt, unsigned char *buf,
182                                 size_t len)
183 {
184         printf(".\n");
185         intel_pt_dump(pt, buf, len);
186 }
187
188 static int intel_pt_do_fix_overlap(struct intel_pt *pt, struct auxtrace_buffer *a,
189                                    struct auxtrace_buffer *b)
190 {
191         void *start;
192
193         start = intel_pt_find_overlap(a->data, a->size, b->data, b->size,
194                                       pt->have_tsc);
195         if (!start)
196                 return -EINVAL;
197         b->use_size = b->data + b->size - start;
198         b->use_data = start;
199         return 0;
200 }
201
202 static void intel_pt_use_buffer_pid_tid(struct intel_pt_queue *ptq,
203                                         struct auxtrace_queue *queue,
204                                         struct auxtrace_buffer *buffer)
205 {
206         if (queue->cpu == -1 && buffer->cpu != -1)
207                 ptq->cpu = buffer->cpu;
208
209         ptq->pid = buffer->pid;
210         ptq->tid = buffer->tid;
211
212         intel_pt_log("queue %u cpu %d pid %d tid %d\n",
213                      ptq->queue_nr, ptq->cpu, ptq->pid, ptq->tid);
214
215         thread__zput(ptq->thread);
216
217         if (ptq->tid != -1) {
218                 if (ptq->pid != -1)
219                         ptq->thread = machine__findnew_thread(ptq->pt->machine,
220                                                               ptq->pid,
221                                                               ptq->tid);
222                 else
223                         ptq->thread = machine__find_thread(ptq->pt->machine, -1,
224                                                            ptq->tid);
225         }
226 }
227
228 /* This function assumes data is processed sequentially only */
229 static int intel_pt_get_trace(struct intel_pt_buffer *b, void *data)
230 {
231         struct intel_pt_queue *ptq = data;
232         struct auxtrace_buffer *buffer = ptq->buffer, *old_buffer = buffer;
233         struct auxtrace_queue *queue;
234
235         if (ptq->stop) {
236                 b->len = 0;
237                 return 0;
238         }
239
240         queue = &ptq->pt->queues.queue_array[ptq->queue_nr];
241 next:
242         buffer = auxtrace_buffer__next(queue, buffer);
243         if (!buffer) {
244                 if (old_buffer)
245                         auxtrace_buffer__drop_data(old_buffer);
246                 b->len = 0;
247                 return 0;
248         }
249
250         ptq->buffer = buffer;
251
252         if (!buffer->data) {
253                 int fd = perf_data_file__fd(ptq->pt->session->file);
254
255                 buffer->data = auxtrace_buffer__get_data(buffer, fd);
256                 if (!buffer->data)
257                         return -ENOMEM;
258         }
259
260         if (ptq->pt->snapshot_mode && !buffer->consecutive && old_buffer &&
261             intel_pt_do_fix_overlap(ptq->pt, old_buffer, buffer))
262                 return -ENOMEM;
263
264         if (buffer->use_data) {
265                 b->len = buffer->use_size;
266                 b->buf = buffer->use_data;
267         } else {
268                 b->len = buffer->size;
269                 b->buf = buffer->data;
270         }
271         b->ref_timestamp = buffer->reference;
272
273         /*
274          * If in snapshot mode and the buffer has no usable data, get next
275          * buffer and again check overlap against old_buffer.
276          */
277         if (ptq->pt->snapshot_mode && !b->len)
278                 goto next;
279
280         if (old_buffer)
281                 auxtrace_buffer__drop_data(old_buffer);
282
283         if (!old_buffer || ptq->pt->sampling_mode || (ptq->pt->snapshot_mode &&
284                                                       !buffer->consecutive)) {
285                 b->consecutive = false;
286                 b->trace_nr = buffer->buffer_nr + 1;
287         } else {
288                 b->consecutive = true;
289         }
290
291         if (ptq->use_buffer_pid_tid && (ptq->pid != buffer->pid ||
292                                         ptq->tid != buffer->tid))
293                 intel_pt_use_buffer_pid_tid(ptq, queue, buffer);
294
295         if (ptq->step_through_buffers)
296                 ptq->stop = true;
297
298         if (!b->len)
299                 return intel_pt_get_trace(b, data);
300
301         return 0;
302 }
303
304 struct intel_pt_cache_entry {
305         struct auxtrace_cache_entry     entry;
306         u64                             insn_cnt;
307         u64                             byte_cnt;
308         enum intel_pt_insn_op           op;
309         enum intel_pt_insn_branch       branch;
310         int                             length;
311         int32_t                         rel;
312 };
313
314 static int intel_pt_config_div(const char *var, const char *value, void *data)
315 {
316         int *d = data;
317         long val;
318
319         if (!strcmp(var, "intel-pt.cache-divisor")) {
320                 val = strtol(value, NULL, 0);
321                 if (val > 0 && val <= INT_MAX)
322                         *d = val;
323         }
324
325         return 0;
326 }
327
328 static int intel_pt_cache_divisor(void)
329 {
330         static int d;
331
332         if (d)
333                 return d;
334
335         perf_config(intel_pt_config_div, &d);
336
337         if (!d)
338                 d = 64;
339
340         return d;
341 }
342
343 static unsigned int intel_pt_cache_size(struct dso *dso,
344                                         struct machine *machine)
345 {
346         off_t size;
347
348         size = dso__data_size(dso, machine);
349         size /= intel_pt_cache_divisor();
350         if (size < 1000)
351                 return 10;
352         if (size > (1 << 21))
353                 return 21;
354         return 32 - __builtin_clz(size);
355 }
356
357 static struct auxtrace_cache *intel_pt_cache(struct dso *dso,
358                                              struct machine *machine)
359 {
360         struct auxtrace_cache *c;
361         unsigned int bits;
362
363         if (dso->auxtrace_cache)
364                 return dso->auxtrace_cache;
365
366         bits = intel_pt_cache_size(dso, machine);
367
368         /* Ignoring cache creation failure */
369         c = auxtrace_cache__new(bits, sizeof(struct intel_pt_cache_entry), 200);
370
371         dso->auxtrace_cache = c;
372
373         return c;
374 }
375
376 static int intel_pt_cache_add(struct dso *dso, struct machine *machine,
377                               u64 offset, u64 insn_cnt, u64 byte_cnt,
378                               struct intel_pt_insn *intel_pt_insn)
379 {
380         struct auxtrace_cache *c = intel_pt_cache(dso, machine);
381         struct intel_pt_cache_entry *e;
382         int err;
383
384         if (!c)
385                 return -ENOMEM;
386
387         e = auxtrace_cache__alloc_entry(c);
388         if (!e)
389                 return -ENOMEM;
390
391         e->insn_cnt = insn_cnt;
392         e->byte_cnt = byte_cnt;
393         e->op = intel_pt_insn->op;
394         e->branch = intel_pt_insn->branch;
395         e->length = intel_pt_insn->length;
396         e->rel = intel_pt_insn->rel;
397
398         err = auxtrace_cache__add(c, offset, &e->entry);
399         if (err)
400                 auxtrace_cache__free_entry(c, e);
401
402         return err;
403 }
404
405 static struct intel_pt_cache_entry *
406 intel_pt_cache_lookup(struct dso *dso, struct machine *machine, u64 offset)
407 {
408         struct auxtrace_cache *c = intel_pt_cache(dso, machine);
409
410         if (!c)
411                 return NULL;
412
413         return auxtrace_cache__lookup(dso->auxtrace_cache, offset);
414 }
415
416 static int intel_pt_walk_next_insn(struct intel_pt_insn *intel_pt_insn,
417                                    uint64_t *insn_cnt_ptr, uint64_t *ip,
418                                    uint64_t to_ip, uint64_t max_insn_cnt,
419                                    void *data)
420 {
421         struct intel_pt_queue *ptq = data;
422         struct machine *machine = ptq->pt->machine;
423         struct thread *thread;
424         struct addr_location al;
425         unsigned char buf[1024];
426         size_t bufsz;
427         ssize_t len;
428         int x86_64;
429         u8 cpumode;
430         u64 offset, start_offset, start_ip;
431         u64 insn_cnt = 0;
432         bool one_map = true;
433
434         if (to_ip && *ip == to_ip)
435                 goto out_no_cache;
436
437         bufsz = intel_pt_insn_max_size();
438
439         if (*ip >= ptq->pt->kernel_start)
440                 cpumode = PERF_RECORD_MISC_KERNEL;
441         else
442                 cpumode = PERF_RECORD_MISC_USER;
443
444         thread = ptq->thread;
445         if (!thread) {
446                 if (cpumode != PERF_RECORD_MISC_KERNEL)
447                         return -EINVAL;
448                 thread = ptq->pt->unknown_thread;
449         }
450
451         while (1) {
452                 thread__find_addr_map(thread, cpumode, MAP__FUNCTION, *ip, &al);
453                 if (!al.map || !al.map->dso)
454                         return -EINVAL;
455
456                 if (al.map->dso->data.status == DSO_DATA_STATUS_ERROR &&
457                     dso__data_status_seen(al.map->dso,
458                                           DSO_DATA_STATUS_SEEN_ITRACE))
459                         return -ENOENT;
460
461                 offset = al.map->map_ip(al.map, *ip);
462
463                 if (!to_ip && one_map) {
464                         struct intel_pt_cache_entry *e;
465
466                         e = intel_pt_cache_lookup(al.map->dso, machine, offset);
467                         if (e &&
468                             (!max_insn_cnt || e->insn_cnt <= max_insn_cnt)) {
469                                 *insn_cnt_ptr = e->insn_cnt;
470                                 *ip += e->byte_cnt;
471                                 intel_pt_insn->op = e->op;
472                                 intel_pt_insn->branch = e->branch;
473                                 intel_pt_insn->length = e->length;
474                                 intel_pt_insn->rel = e->rel;
475                                 intel_pt_log_insn_no_data(intel_pt_insn, *ip);
476                                 return 0;
477                         }
478                 }
479
480                 start_offset = offset;
481                 start_ip = *ip;
482
483                 /* Load maps to ensure dso->is_64_bit has been updated */
484                 map__load(al.map, machine->symbol_filter);
485
486                 x86_64 = al.map->dso->is_64_bit;
487
488                 while (1) {
489                         len = dso__data_read_offset(al.map->dso, machine,
490                                                     offset, buf, bufsz);
491                         if (len <= 0)
492                                 return -EINVAL;
493
494                         if (intel_pt_get_insn(buf, len, x86_64, intel_pt_insn))
495                                 return -EINVAL;
496
497                         intel_pt_log_insn(intel_pt_insn, *ip);
498
499                         insn_cnt += 1;
500
501                         if (intel_pt_insn->branch != INTEL_PT_BR_NO_BRANCH)
502                                 goto out;
503
504                         if (max_insn_cnt && insn_cnt >= max_insn_cnt)
505                                 goto out_no_cache;
506
507                         *ip += intel_pt_insn->length;
508
509                         if (to_ip && *ip == to_ip)
510                                 goto out_no_cache;
511
512                         if (*ip >= al.map->end)
513                                 break;
514
515                         offset += intel_pt_insn->length;
516                 }
517                 one_map = false;
518         }
519 out:
520         *insn_cnt_ptr = insn_cnt;
521
522         if (!one_map)
523                 goto out_no_cache;
524
525         /*
526          * Didn't lookup in the 'to_ip' case, so do it now to prevent duplicate
527          * entries.
528          */
529         if (to_ip) {
530                 struct intel_pt_cache_entry *e;
531
532                 e = intel_pt_cache_lookup(al.map->dso, machine, start_offset);
533                 if (e)
534                         return 0;
535         }
536
537         /* Ignore cache errors */
538         intel_pt_cache_add(al.map->dso, machine, start_offset, insn_cnt,
539                            *ip - start_ip, intel_pt_insn);
540
541         return 0;
542
543 out_no_cache:
544         *insn_cnt_ptr = insn_cnt;
545         return 0;
546 }
547
548 static bool intel_pt_get_config(struct intel_pt *pt,
549                                 struct perf_event_attr *attr, u64 *config)
550 {
551         if (attr->type == pt->pmu_type) {
552                 if (config)
553                         *config = attr->config;
554                 return true;
555         }
556
557         return false;
558 }
559
560 static bool intel_pt_exclude_kernel(struct intel_pt *pt)
561 {
562         struct perf_evsel *evsel;
563
564         evlist__for_each(pt->session->evlist, evsel) {
565                 if (intel_pt_get_config(pt, &evsel->attr, NULL) &&
566                     !evsel->attr.exclude_kernel)
567                         return false;
568         }
569         return true;
570 }
571
572 static bool intel_pt_return_compression(struct intel_pt *pt)
573 {
574         struct perf_evsel *evsel;
575         u64 config;
576
577         if (!pt->noretcomp_bit)
578                 return true;
579
580         evlist__for_each(pt->session->evlist, evsel) {
581                 if (intel_pt_get_config(pt, &evsel->attr, &config) &&
582                     (config & pt->noretcomp_bit))
583                         return false;
584         }
585         return true;
586 }
587
588 static unsigned int intel_pt_mtc_period(struct intel_pt *pt)
589 {
590         struct perf_evsel *evsel;
591         unsigned int shift;
592         u64 config;
593
594         if (!pt->mtc_freq_bits)
595                 return 0;
596
597         for (shift = 0, config = pt->mtc_freq_bits; !(config & 1); shift++)
598                 config >>= 1;
599
600         evlist__for_each(pt->session->evlist, evsel) {
601                 if (intel_pt_get_config(pt, &evsel->attr, &config))
602                         return (config & pt->mtc_freq_bits) >> shift;
603         }
604         return 0;
605 }
606
607 static bool intel_pt_timeless_decoding(struct intel_pt *pt)
608 {
609         struct perf_evsel *evsel;
610         bool timeless_decoding = true;
611         u64 config;
612
613         if (!pt->tsc_bit || !pt->cap_user_time_zero)
614                 return true;
615
616         evlist__for_each(pt->session->evlist, evsel) {
617                 if (!(evsel->attr.sample_type & PERF_SAMPLE_TIME))
618                         return true;
619                 if (intel_pt_get_config(pt, &evsel->attr, &config)) {
620                         if (config & pt->tsc_bit)
621                                 timeless_decoding = false;
622                         else
623                                 return true;
624                 }
625         }
626         return timeless_decoding;
627 }
628
629 static bool intel_pt_tracing_kernel(struct intel_pt *pt)
630 {
631         struct perf_evsel *evsel;
632
633         evlist__for_each(pt->session->evlist, evsel) {
634                 if (intel_pt_get_config(pt, &evsel->attr, NULL) &&
635                     !evsel->attr.exclude_kernel)
636                         return true;
637         }
638         return false;
639 }
640
641 static bool intel_pt_have_tsc(struct intel_pt *pt)
642 {
643         struct perf_evsel *evsel;
644         bool have_tsc = false;
645         u64 config;
646
647         if (!pt->tsc_bit)
648                 return false;
649
650         evlist__for_each(pt->session->evlist, evsel) {
651                 if (intel_pt_get_config(pt, &evsel->attr, &config)) {
652                         if (config & pt->tsc_bit)
653                                 have_tsc = true;
654                         else
655                                 return false;
656                 }
657         }
658         return have_tsc;
659 }
660
661 static u64 intel_pt_ns_to_ticks(const struct intel_pt *pt, u64 ns)
662 {
663         u64 quot, rem;
664
665         quot = ns / pt->tc.time_mult;
666         rem  = ns % pt->tc.time_mult;
667         return (quot << pt->tc.time_shift) + (rem << pt->tc.time_shift) /
668                 pt->tc.time_mult;
669 }
670
671 static struct intel_pt_queue *intel_pt_alloc_queue(struct intel_pt *pt,
672                                                    unsigned int queue_nr)
673 {
674         struct intel_pt_params params = { .get_trace = 0, };
675         struct intel_pt_queue *ptq;
676
677         ptq = zalloc(sizeof(struct intel_pt_queue));
678         if (!ptq)
679                 return NULL;
680
681         if (pt->synth_opts.callchain) {
682                 size_t sz = sizeof(struct ip_callchain);
683
684                 sz += pt->synth_opts.callchain_sz * sizeof(u64);
685                 ptq->chain = zalloc(sz);
686                 if (!ptq->chain)
687                         goto out_free;
688         }
689
690         if (pt->synth_opts.last_branch) {
691                 size_t sz = sizeof(struct branch_stack);
692
693                 sz += pt->synth_opts.last_branch_sz *
694                       sizeof(struct branch_entry);
695                 ptq->last_branch = zalloc(sz);
696                 if (!ptq->last_branch)
697                         goto out_free;
698                 ptq->last_branch_rb = zalloc(sz);
699                 if (!ptq->last_branch_rb)
700                         goto out_free;
701         }
702
703         ptq->event_buf = malloc(PERF_SAMPLE_MAX_SIZE);
704         if (!ptq->event_buf)
705                 goto out_free;
706
707         ptq->pt = pt;
708         ptq->queue_nr = queue_nr;
709         ptq->exclude_kernel = intel_pt_exclude_kernel(pt);
710         ptq->pid = -1;
711         ptq->tid = -1;
712         ptq->cpu = -1;
713         ptq->next_tid = -1;
714
715         params.get_trace = intel_pt_get_trace;
716         params.walk_insn = intel_pt_walk_next_insn;
717         params.data = ptq;
718         params.return_compression = intel_pt_return_compression(pt);
719         params.max_non_turbo_ratio = pt->max_non_turbo_ratio;
720         params.mtc_period = intel_pt_mtc_period(pt);
721         params.tsc_ctc_ratio_n = pt->tsc_ctc_ratio_n;
722         params.tsc_ctc_ratio_d = pt->tsc_ctc_ratio_d;
723
724         if (pt->synth_opts.instructions) {
725                 if (pt->synth_opts.period) {
726                         switch (pt->synth_opts.period_type) {
727                         case PERF_ITRACE_PERIOD_INSTRUCTIONS:
728                                 params.period_type =
729                                                 INTEL_PT_PERIOD_INSTRUCTIONS;
730                                 params.period = pt->synth_opts.period;
731                                 break;
732                         case PERF_ITRACE_PERIOD_TICKS:
733                                 params.period_type = INTEL_PT_PERIOD_TICKS;
734                                 params.period = pt->synth_opts.period;
735                                 break;
736                         case PERF_ITRACE_PERIOD_NANOSECS:
737                                 params.period_type = INTEL_PT_PERIOD_TICKS;
738                                 params.period = intel_pt_ns_to_ticks(pt,
739                                                         pt->synth_opts.period);
740                                 break;
741                         default:
742                                 break;
743                         }
744                 }
745
746                 if (!params.period) {
747                         params.period_type = INTEL_PT_PERIOD_INSTRUCTIONS;
748                         params.period = 1;
749                 }
750         }
751
752         ptq->decoder = intel_pt_decoder_new(&params);
753         if (!ptq->decoder)
754                 goto out_free;
755
756         return ptq;
757
758 out_free:
759         zfree(&ptq->event_buf);
760         zfree(&ptq->last_branch);
761         zfree(&ptq->last_branch_rb);
762         zfree(&ptq->chain);
763         free(ptq);
764         return NULL;
765 }
766
767 static void intel_pt_free_queue(void *priv)
768 {
769         struct intel_pt_queue *ptq = priv;
770
771         if (!ptq)
772                 return;
773         thread__zput(ptq->thread);
774         intel_pt_decoder_free(ptq->decoder);
775         zfree(&ptq->event_buf);
776         zfree(&ptq->last_branch);
777         zfree(&ptq->last_branch_rb);
778         zfree(&ptq->chain);
779         free(ptq);
780 }
781
782 static void intel_pt_set_pid_tid_cpu(struct intel_pt *pt,
783                                      struct auxtrace_queue *queue)
784 {
785         struct intel_pt_queue *ptq = queue->priv;
786
787         if (queue->tid == -1 || pt->have_sched_switch) {
788                 ptq->tid = machine__get_current_tid(pt->machine, ptq->cpu);
789                 thread__zput(ptq->thread);
790         }
791
792         if (!ptq->thread && ptq->tid != -1)
793                 ptq->thread = machine__find_thread(pt->machine, -1, ptq->tid);
794
795         if (ptq->thread) {
796                 ptq->pid = ptq->thread->pid_;
797                 if (queue->cpu == -1)
798                         ptq->cpu = ptq->thread->cpu;
799         }
800 }
801
802 static void intel_pt_sample_flags(struct intel_pt_queue *ptq)
803 {
804         if (ptq->state->flags & INTEL_PT_ABORT_TX) {
805                 ptq->flags = PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT;
806         } else if (ptq->state->flags & INTEL_PT_ASYNC) {
807                 if (ptq->state->to_ip)
808                         ptq->flags = PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL |
809                                      PERF_IP_FLAG_ASYNC |
810                                      PERF_IP_FLAG_INTERRUPT;
811                 else
812                         ptq->flags = PERF_IP_FLAG_BRANCH |
813                                      PERF_IP_FLAG_TRACE_END;
814                 ptq->insn_len = 0;
815         } else {
816                 if (ptq->state->from_ip)
817                         ptq->flags = intel_pt_insn_type(ptq->state->insn_op);
818                 else
819                         ptq->flags = PERF_IP_FLAG_BRANCH |
820                                      PERF_IP_FLAG_TRACE_BEGIN;
821                 if (ptq->state->flags & INTEL_PT_IN_TX)
822                         ptq->flags |= PERF_IP_FLAG_IN_TX;
823                 ptq->insn_len = ptq->state->insn_len;
824         }
825 }
826
827 static int intel_pt_setup_queue(struct intel_pt *pt,
828                                 struct auxtrace_queue *queue,
829                                 unsigned int queue_nr)
830 {
831         struct intel_pt_queue *ptq = queue->priv;
832
833         if (list_empty(&queue->head))
834                 return 0;
835
836         if (!ptq) {
837                 ptq = intel_pt_alloc_queue(pt, queue_nr);
838                 if (!ptq)
839                         return -ENOMEM;
840                 queue->priv = ptq;
841
842                 if (queue->cpu != -1)
843                         ptq->cpu = queue->cpu;
844                 ptq->tid = queue->tid;
845
846                 if (pt->sampling_mode) {
847                         if (pt->timeless_decoding)
848                                 ptq->step_through_buffers = true;
849                         if (pt->timeless_decoding || !pt->have_sched_switch)
850                                 ptq->use_buffer_pid_tid = true;
851                 }
852         }
853
854         if (!ptq->on_heap &&
855             (!pt->sync_switch ||
856              ptq->switch_state != INTEL_PT_SS_EXPECTING_SWITCH_EVENT)) {
857                 const struct intel_pt_state *state;
858                 int ret;
859
860                 if (pt->timeless_decoding)
861                         return 0;
862
863                 intel_pt_log("queue %u getting timestamp\n", queue_nr);
864                 intel_pt_log("queue %u decoding cpu %d pid %d tid %d\n",
865                              queue_nr, ptq->cpu, ptq->pid, ptq->tid);
866                 while (1) {
867                         state = intel_pt_decode(ptq->decoder);
868                         if (state->err) {
869                                 if (state->err == INTEL_PT_ERR_NODATA) {
870                                         intel_pt_log("queue %u has no timestamp\n",
871                                                      queue_nr);
872                                         return 0;
873                                 }
874                                 continue;
875                         }
876                         if (state->timestamp)
877                                 break;
878                 }
879
880                 ptq->timestamp = state->timestamp;
881                 intel_pt_log("queue %u timestamp 0x%" PRIx64 "\n",
882                              queue_nr, ptq->timestamp);
883                 ptq->state = state;
884                 ptq->have_sample = true;
885                 intel_pt_sample_flags(ptq);
886                 ret = auxtrace_heap__add(&pt->heap, queue_nr, ptq->timestamp);
887                 if (ret)
888                         return ret;
889                 ptq->on_heap = true;
890         }
891
892         return 0;
893 }
894
895 static int intel_pt_setup_queues(struct intel_pt *pt)
896 {
897         unsigned int i;
898         int ret;
899
900         for (i = 0; i < pt->queues.nr_queues; i++) {
901                 ret = intel_pt_setup_queue(pt, &pt->queues.queue_array[i], i);
902                 if (ret)
903                         return ret;
904         }
905         return 0;
906 }
907
908 static inline void intel_pt_copy_last_branch_rb(struct intel_pt_queue *ptq)
909 {
910         struct branch_stack *bs_src = ptq->last_branch_rb;
911         struct branch_stack *bs_dst = ptq->last_branch;
912         size_t nr = 0;
913
914         bs_dst->nr = bs_src->nr;
915
916         if (!bs_src->nr)
917                 return;
918
919         nr = ptq->pt->synth_opts.last_branch_sz - ptq->last_branch_pos;
920         memcpy(&bs_dst->entries[0],
921                &bs_src->entries[ptq->last_branch_pos],
922                sizeof(struct branch_entry) * nr);
923
924         if (bs_src->nr >= ptq->pt->synth_opts.last_branch_sz) {
925                 memcpy(&bs_dst->entries[nr],
926                        &bs_src->entries[0],
927                        sizeof(struct branch_entry) * ptq->last_branch_pos);
928         }
929 }
930
931 static inline void intel_pt_reset_last_branch_rb(struct intel_pt_queue *ptq)
932 {
933         ptq->last_branch_pos = 0;
934         ptq->last_branch_rb->nr = 0;
935 }
936
937 static void intel_pt_update_last_branch_rb(struct intel_pt_queue *ptq)
938 {
939         const struct intel_pt_state *state = ptq->state;
940         struct branch_stack *bs = ptq->last_branch_rb;
941         struct branch_entry *be;
942
943         if (!ptq->last_branch_pos)
944                 ptq->last_branch_pos = ptq->pt->synth_opts.last_branch_sz;
945
946         ptq->last_branch_pos -= 1;
947
948         be              = &bs->entries[ptq->last_branch_pos];
949         be->from        = state->from_ip;
950         be->to          = state->to_ip;
951         be->flags.abort = !!(state->flags & INTEL_PT_ABORT_TX);
952         be->flags.in_tx = !!(state->flags & INTEL_PT_IN_TX);
953         /* No support for mispredict */
954         be->flags.mispred = ptq->pt->mispred_all;
955
956         if (bs->nr < ptq->pt->synth_opts.last_branch_sz)
957                 bs->nr += 1;
958 }
959
960 static int intel_pt_inject_event(union perf_event *event,
961                                  struct perf_sample *sample, u64 type,
962                                  bool swapped)
963 {
964         event->header.size = perf_event__sample_event_size(sample, type, 0);
965         return perf_event__synthesize_sample(event, type, 0, sample, swapped);
966 }
967
968 static int intel_pt_synth_branch_sample(struct intel_pt_queue *ptq)
969 {
970         int ret;
971         struct intel_pt *pt = ptq->pt;
972         union perf_event *event = ptq->event_buf;
973         struct perf_sample sample = { .ip = 0, };
974         struct dummy_branch_stack {
975                 u64                     nr;
976                 struct branch_entry     entries;
977         } dummy_bs;
978
979         if (pt->branches_filter && !(pt->branches_filter & ptq->flags))
980                 return 0;
981
982         event->sample.header.type = PERF_RECORD_SAMPLE;
983         event->sample.header.misc = PERF_RECORD_MISC_USER;
984         event->sample.header.size = sizeof(struct perf_event_header);
985
986         if (!pt->timeless_decoding)
987                 sample.time = tsc_to_perf_time(ptq->timestamp, &pt->tc);
988
989         sample.ip = ptq->state->from_ip;
990         sample.pid = ptq->pid;
991         sample.tid = ptq->tid;
992         sample.addr = ptq->state->to_ip;
993         sample.id = ptq->pt->branches_id;
994         sample.stream_id = ptq->pt->branches_id;
995         sample.period = 1;
996         sample.cpu = ptq->cpu;
997         sample.flags = ptq->flags;
998         sample.insn_len = ptq->insn_len;
999
1000         /*
1001          * perf report cannot handle events without a branch stack when using
1002          * SORT_MODE__BRANCH so make a dummy one.
1003          */
1004         if (pt->synth_opts.last_branch && sort__mode == SORT_MODE__BRANCH) {
1005                 dummy_bs = (struct dummy_branch_stack){
1006                         .nr = 1,
1007                         .entries = {
1008                                 .from = sample.ip,
1009                                 .to = sample.addr,
1010                         },
1011                 };
1012                 sample.branch_stack = (struct branch_stack *)&dummy_bs;
1013         }
1014
1015         if (pt->synth_opts.inject) {
1016                 ret = intel_pt_inject_event(event, &sample,
1017                                             pt->branches_sample_type,
1018                                             pt->synth_needs_swap);
1019                 if (ret)
1020                         return ret;
1021         }
1022
1023         ret = perf_session__deliver_synth_event(pt->session, event, &sample);
1024         if (ret)
1025                 pr_err("Intel Processor Trace: failed to deliver branch event, error %d\n",
1026                        ret);
1027
1028         return ret;
1029 }
1030
1031 static int intel_pt_synth_instruction_sample(struct intel_pt_queue *ptq)
1032 {
1033         int ret;
1034         struct intel_pt *pt = ptq->pt;
1035         union perf_event *event = ptq->event_buf;
1036         struct perf_sample sample = { .ip = 0, };
1037
1038         event->sample.header.type = PERF_RECORD_SAMPLE;
1039         event->sample.header.misc = PERF_RECORD_MISC_USER;
1040         event->sample.header.size = sizeof(struct perf_event_header);
1041
1042         if (!pt->timeless_decoding)
1043                 sample.time = tsc_to_perf_time(ptq->timestamp, &pt->tc);
1044
1045         sample.ip = ptq->state->from_ip;
1046         sample.pid = ptq->pid;
1047         sample.tid = ptq->tid;
1048         sample.addr = ptq->state->to_ip;
1049         sample.id = ptq->pt->instructions_id;
1050         sample.stream_id = ptq->pt->instructions_id;
1051         sample.period = ptq->state->tot_insn_cnt - ptq->last_insn_cnt;
1052         sample.cpu = ptq->cpu;
1053         sample.flags = ptq->flags;
1054         sample.insn_len = ptq->insn_len;
1055
1056         ptq->last_insn_cnt = ptq->state->tot_insn_cnt;
1057
1058         if (pt->synth_opts.callchain) {
1059                 thread_stack__sample(ptq->thread, ptq->chain,
1060                                      pt->synth_opts.callchain_sz, sample.ip);
1061                 sample.callchain = ptq->chain;
1062         }
1063
1064         if (pt->synth_opts.last_branch) {
1065                 intel_pt_copy_last_branch_rb(ptq);
1066                 sample.branch_stack = ptq->last_branch;
1067         }
1068
1069         if (pt->synth_opts.inject) {
1070                 ret = intel_pt_inject_event(event, &sample,
1071                                             pt->instructions_sample_type,
1072                                             pt->synth_needs_swap);
1073                 if (ret)
1074                         return ret;
1075         }
1076
1077         ret = perf_session__deliver_synth_event(pt->session, event, &sample);
1078         if (ret)
1079                 pr_err("Intel Processor Trace: failed to deliver instruction event, error %d\n",
1080                        ret);
1081
1082         if (pt->synth_opts.last_branch)
1083                 intel_pt_reset_last_branch_rb(ptq);
1084
1085         return ret;
1086 }
1087
1088 static int intel_pt_synth_transaction_sample(struct intel_pt_queue *ptq)
1089 {
1090         int ret;
1091         struct intel_pt *pt = ptq->pt;
1092         union perf_event *event = ptq->event_buf;
1093         struct perf_sample sample = { .ip = 0, };
1094
1095         event->sample.header.type = PERF_RECORD_SAMPLE;
1096         event->sample.header.misc = PERF_RECORD_MISC_USER;
1097         event->sample.header.size = sizeof(struct perf_event_header);
1098
1099         if (!pt->timeless_decoding)
1100                 sample.time = tsc_to_perf_time(ptq->timestamp, &pt->tc);
1101
1102         sample.ip = ptq->state->from_ip;
1103         sample.pid = ptq->pid;
1104         sample.tid = ptq->tid;
1105         sample.addr = ptq->state->to_ip;
1106         sample.id = ptq->pt->transactions_id;
1107         sample.stream_id = ptq->pt->transactions_id;
1108         sample.period = 1;
1109         sample.cpu = ptq->cpu;
1110         sample.flags = ptq->flags;
1111         sample.insn_len = ptq->insn_len;
1112
1113         if (pt->synth_opts.callchain) {
1114                 thread_stack__sample(ptq->thread, ptq->chain,
1115                                      pt->synth_opts.callchain_sz, sample.ip);
1116                 sample.callchain = ptq->chain;
1117         }
1118
1119         if (pt->synth_opts.last_branch) {
1120                 intel_pt_copy_last_branch_rb(ptq);
1121                 sample.branch_stack = ptq->last_branch;
1122         }
1123
1124         if (pt->synth_opts.inject) {
1125                 ret = intel_pt_inject_event(event, &sample,
1126                                             pt->transactions_sample_type,
1127                                             pt->synth_needs_swap);
1128                 if (ret)
1129                         return ret;
1130         }
1131
1132         ret = perf_session__deliver_synth_event(pt->session, event, &sample);
1133         if (ret)
1134                 pr_err("Intel Processor Trace: failed to deliver transaction event, error %d\n",
1135                        ret);
1136
1137         if (pt->synth_opts.last_branch)
1138                 intel_pt_reset_last_branch_rb(ptq);
1139
1140         return ret;
1141 }
1142
1143 static int intel_pt_synth_error(struct intel_pt *pt, int code, int cpu,
1144                                 pid_t pid, pid_t tid, u64 ip)
1145 {
1146         union perf_event event;
1147         char msg[MAX_AUXTRACE_ERROR_MSG];
1148         int err;
1149
1150         intel_pt__strerror(code, msg, MAX_AUXTRACE_ERROR_MSG);
1151
1152         auxtrace_synth_error(&event.auxtrace_error, PERF_AUXTRACE_ERROR_ITRACE,
1153                              code, cpu, pid, tid, ip, msg);
1154
1155         err = perf_session__deliver_synth_event(pt->session, &event, NULL);
1156         if (err)
1157                 pr_err("Intel Processor Trace: failed to deliver error event, error %d\n",
1158                        err);
1159
1160         return err;
1161 }
1162
1163 static int intel_pt_next_tid(struct intel_pt *pt, struct intel_pt_queue *ptq)
1164 {
1165         struct auxtrace_queue *queue;
1166         pid_t tid = ptq->next_tid;
1167         int err;
1168
1169         if (tid == -1)
1170                 return 0;
1171
1172         intel_pt_log("switch: cpu %d tid %d\n", ptq->cpu, tid);
1173
1174         err = machine__set_current_tid(pt->machine, ptq->cpu, -1, tid);
1175
1176         queue = &pt->queues.queue_array[ptq->queue_nr];
1177         intel_pt_set_pid_tid_cpu(pt, queue);
1178
1179         ptq->next_tid = -1;
1180
1181         return err;
1182 }
1183
1184 static inline bool intel_pt_is_switch_ip(struct intel_pt_queue *ptq, u64 ip)
1185 {
1186         struct intel_pt *pt = ptq->pt;
1187
1188         return ip == pt->switch_ip &&
1189                (ptq->flags & PERF_IP_FLAG_BRANCH) &&
1190                !(ptq->flags & (PERF_IP_FLAG_CONDITIONAL | PERF_IP_FLAG_ASYNC |
1191                                PERF_IP_FLAG_INTERRUPT | PERF_IP_FLAG_TX_ABORT));
1192 }
1193
1194 static int intel_pt_sample(struct intel_pt_queue *ptq)
1195 {
1196         const struct intel_pt_state *state = ptq->state;
1197         struct intel_pt *pt = ptq->pt;
1198         int err;
1199
1200         if (!ptq->have_sample)
1201                 return 0;
1202
1203         ptq->have_sample = false;
1204
1205         if (pt->sample_instructions &&
1206             (state->type & INTEL_PT_INSTRUCTION)) {
1207                 err = intel_pt_synth_instruction_sample(ptq);
1208                 if (err)
1209                         return err;
1210         }
1211
1212         if (pt->sample_transactions &&
1213             (state->type & INTEL_PT_TRANSACTION)) {
1214                 err = intel_pt_synth_transaction_sample(ptq);
1215                 if (err)
1216                         return err;
1217         }
1218
1219         if (!(state->type & INTEL_PT_BRANCH))
1220                 return 0;
1221
1222         if (pt->synth_opts.callchain)
1223                 thread_stack__event(ptq->thread, ptq->flags, state->from_ip,
1224                                     state->to_ip, ptq->insn_len,
1225                                     state->trace_nr);
1226         else
1227                 thread_stack__set_trace_nr(ptq->thread, state->trace_nr);
1228
1229         if (pt->sample_branches) {
1230                 err = intel_pt_synth_branch_sample(ptq);
1231                 if (err)
1232                         return err;
1233         }
1234
1235         if (pt->synth_opts.last_branch)
1236                 intel_pt_update_last_branch_rb(ptq);
1237
1238         if (!pt->sync_switch)
1239                 return 0;
1240
1241         if (intel_pt_is_switch_ip(ptq, state->to_ip)) {
1242                 switch (ptq->switch_state) {
1243                 case INTEL_PT_SS_UNKNOWN:
1244                 case INTEL_PT_SS_EXPECTING_SWITCH_IP:
1245                         err = intel_pt_next_tid(pt, ptq);
1246                         if (err)
1247                                 return err;
1248                         ptq->switch_state = INTEL_PT_SS_TRACING;
1249                         break;
1250                 default:
1251                         ptq->switch_state = INTEL_PT_SS_EXPECTING_SWITCH_EVENT;
1252                         return 1;
1253                 }
1254         } else if (!state->to_ip) {
1255                 ptq->switch_state = INTEL_PT_SS_NOT_TRACING;
1256         } else if (ptq->switch_state == INTEL_PT_SS_NOT_TRACING) {
1257                 ptq->switch_state = INTEL_PT_SS_UNKNOWN;
1258         } else if (ptq->switch_state == INTEL_PT_SS_UNKNOWN &&
1259                    state->to_ip == pt->ptss_ip &&
1260                    (ptq->flags & PERF_IP_FLAG_CALL)) {
1261                 ptq->switch_state = INTEL_PT_SS_TRACING;
1262         }
1263
1264         return 0;
1265 }
1266
1267 static u64 intel_pt_switch_ip(struct intel_pt *pt, u64 *ptss_ip)
1268 {
1269         struct machine *machine = pt->machine;
1270         struct map *map;
1271         struct symbol *sym, *start;
1272         u64 ip, switch_ip = 0;
1273         const char *ptss;
1274
1275         if (ptss_ip)
1276                 *ptss_ip = 0;
1277
1278         map = machine__kernel_map(machine);
1279         if (!map)
1280                 return 0;
1281
1282         if (map__load(map, machine->symbol_filter))
1283                 return 0;
1284
1285         start = dso__first_symbol(map->dso, MAP__FUNCTION);
1286
1287         for (sym = start; sym; sym = dso__next_symbol(sym)) {
1288                 if (sym->binding == STB_GLOBAL &&
1289                     !strcmp(sym->name, "__switch_to")) {
1290                         ip = map->unmap_ip(map, sym->start);
1291                         if (ip >= map->start && ip < map->end) {
1292                                 switch_ip = ip;
1293                                 break;
1294                         }
1295                 }
1296         }
1297
1298         if (!switch_ip || !ptss_ip)
1299                 return 0;
1300
1301         if (pt->have_sched_switch == 1)
1302                 ptss = "perf_trace_sched_switch";
1303         else
1304                 ptss = "__perf_event_task_sched_out";
1305
1306         for (sym = start; sym; sym = dso__next_symbol(sym)) {
1307                 if (!strcmp(sym->name, ptss)) {
1308                         ip = map->unmap_ip(map, sym->start);
1309                         if (ip >= map->start && ip < map->end) {
1310                                 *ptss_ip = ip;
1311                                 break;
1312                         }
1313                 }
1314         }
1315
1316         return switch_ip;
1317 }
1318
1319 static int intel_pt_run_decoder(struct intel_pt_queue *ptq, u64 *timestamp)
1320 {
1321         const struct intel_pt_state *state = ptq->state;
1322         struct intel_pt *pt = ptq->pt;
1323         int err;
1324
1325         if (!pt->kernel_start) {
1326                 pt->kernel_start = machine__kernel_start(pt->machine);
1327                 if (pt->per_cpu_mmaps &&
1328                     (pt->have_sched_switch == 1 || pt->have_sched_switch == 3) &&
1329                     !pt->timeless_decoding && intel_pt_tracing_kernel(pt) &&
1330                     !pt->sampling_mode) {
1331                         pt->switch_ip = intel_pt_switch_ip(pt, &pt->ptss_ip);
1332                         if (pt->switch_ip) {
1333                                 intel_pt_log("switch_ip: %"PRIx64" ptss_ip: %"PRIx64"\n",
1334                                              pt->switch_ip, pt->ptss_ip);
1335                                 pt->sync_switch = true;
1336                         }
1337                 }
1338         }
1339
1340         intel_pt_log("queue %u decoding cpu %d pid %d tid %d\n",
1341                      ptq->queue_nr, ptq->cpu, ptq->pid, ptq->tid);
1342         while (1) {
1343                 err = intel_pt_sample(ptq);
1344                 if (err)
1345                         return err;
1346
1347                 state = intel_pt_decode(ptq->decoder);
1348                 if (state->err) {
1349                         if (state->err == INTEL_PT_ERR_NODATA)
1350                                 return 1;
1351                         if (pt->sync_switch &&
1352                             state->from_ip >= pt->kernel_start) {
1353                                 pt->sync_switch = false;
1354                                 intel_pt_next_tid(pt, ptq);
1355                         }
1356                         if (pt->synth_opts.errors) {
1357                                 err = intel_pt_synth_error(pt, state->err,
1358                                                            ptq->cpu, ptq->pid,
1359                                                            ptq->tid,
1360                                                            state->from_ip);
1361                                 if (err)
1362                                         return err;
1363                         }
1364                         continue;
1365                 }
1366
1367                 ptq->state = state;
1368                 ptq->have_sample = true;
1369                 intel_pt_sample_flags(ptq);
1370
1371                 /* Use estimated TSC upon return to user space */
1372                 if (pt->est_tsc &&
1373                     (state->from_ip >= pt->kernel_start || !state->from_ip) &&
1374                     state->to_ip && state->to_ip < pt->kernel_start) {
1375                         intel_pt_log("TSC %"PRIx64" est. TSC %"PRIx64"\n",
1376                                      state->timestamp, state->est_timestamp);
1377                         ptq->timestamp = state->est_timestamp;
1378                 /* Use estimated TSC in unknown switch state */
1379                 } else if (pt->sync_switch &&
1380                            ptq->switch_state == INTEL_PT_SS_UNKNOWN &&
1381                            intel_pt_is_switch_ip(ptq, state->to_ip) &&
1382                            ptq->next_tid == -1) {
1383                         intel_pt_log("TSC %"PRIx64" est. TSC %"PRIx64"\n",
1384                                      state->timestamp, state->est_timestamp);
1385                         ptq->timestamp = state->est_timestamp;
1386                 } else if (state->timestamp > ptq->timestamp) {
1387                         ptq->timestamp = state->timestamp;
1388                 }
1389
1390                 if (!pt->timeless_decoding && ptq->timestamp >= *timestamp) {
1391                         *timestamp = ptq->timestamp;
1392                         return 0;
1393                 }
1394         }
1395         return 0;
1396 }
1397
1398 static inline int intel_pt_update_queues(struct intel_pt *pt)
1399 {
1400         if (pt->queues.new_data) {
1401                 pt->queues.new_data = false;
1402                 return intel_pt_setup_queues(pt);
1403         }
1404         return 0;
1405 }
1406
1407 static int intel_pt_process_queues(struct intel_pt *pt, u64 timestamp)
1408 {
1409         unsigned int queue_nr;
1410         u64 ts;
1411         int ret;
1412
1413         while (1) {
1414                 struct auxtrace_queue *queue;
1415                 struct intel_pt_queue *ptq;
1416
1417                 if (!pt->heap.heap_cnt)
1418                         return 0;
1419
1420                 if (pt->heap.heap_array[0].ordinal >= timestamp)
1421                         return 0;
1422
1423                 queue_nr = pt->heap.heap_array[0].queue_nr;
1424                 queue = &pt->queues.queue_array[queue_nr];
1425                 ptq = queue->priv;
1426
1427                 intel_pt_log("queue %u processing 0x%" PRIx64 " to 0x%" PRIx64 "\n",
1428                              queue_nr, pt->heap.heap_array[0].ordinal,
1429                              timestamp);
1430
1431                 auxtrace_heap__pop(&pt->heap);
1432
1433                 if (pt->heap.heap_cnt) {
1434                         ts = pt->heap.heap_array[0].ordinal + 1;
1435                         if (ts > timestamp)
1436                                 ts = timestamp;
1437                 } else {
1438                         ts = timestamp;
1439                 }
1440
1441                 intel_pt_set_pid_tid_cpu(pt, queue);
1442
1443                 ret = intel_pt_run_decoder(ptq, &ts);
1444
1445                 if (ret < 0) {
1446                         auxtrace_heap__add(&pt->heap, queue_nr, ts);
1447                         return ret;
1448                 }
1449
1450                 if (!ret) {
1451                         ret = auxtrace_heap__add(&pt->heap, queue_nr, ts);
1452                         if (ret < 0)
1453                                 return ret;
1454                 } else {
1455                         ptq->on_heap = false;
1456                 }
1457         }
1458
1459         return 0;
1460 }
1461
1462 static int intel_pt_process_timeless_queues(struct intel_pt *pt, pid_t tid,
1463                                             u64 time_)
1464 {
1465         struct auxtrace_queues *queues = &pt->queues;
1466         unsigned int i;
1467         u64 ts = 0;
1468
1469         for (i = 0; i < queues->nr_queues; i++) {
1470                 struct auxtrace_queue *queue = &pt->queues.queue_array[i];
1471                 struct intel_pt_queue *ptq = queue->priv;
1472
1473                 if (ptq && (tid == -1 || ptq->tid == tid)) {
1474                         ptq->time = time_;
1475                         intel_pt_set_pid_tid_cpu(pt, queue);
1476                         intel_pt_run_decoder(ptq, &ts);
1477                 }
1478         }
1479         return 0;
1480 }
1481
1482 static int intel_pt_lost(struct intel_pt *pt, struct perf_sample *sample)
1483 {
1484         return intel_pt_synth_error(pt, INTEL_PT_ERR_LOST, sample->cpu,
1485                                     sample->pid, sample->tid, 0);
1486 }
1487
1488 static struct intel_pt_queue *intel_pt_cpu_to_ptq(struct intel_pt *pt, int cpu)
1489 {
1490         unsigned i, j;
1491
1492         if (cpu < 0 || !pt->queues.nr_queues)
1493                 return NULL;
1494
1495         if ((unsigned)cpu >= pt->queues.nr_queues)
1496                 i = pt->queues.nr_queues - 1;
1497         else
1498                 i = cpu;
1499
1500         if (pt->queues.queue_array[i].cpu == cpu)
1501                 return pt->queues.queue_array[i].priv;
1502
1503         for (j = 0; i > 0; j++) {
1504                 if (pt->queues.queue_array[--i].cpu == cpu)
1505                         return pt->queues.queue_array[i].priv;
1506         }
1507
1508         for (; j < pt->queues.nr_queues; j++) {
1509                 if (pt->queues.queue_array[j].cpu == cpu)
1510                         return pt->queues.queue_array[j].priv;
1511         }
1512
1513         return NULL;
1514 }
1515
1516 static int intel_pt_sync_switch(struct intel_pt *pt, int cpu, pid_t tid,
1517                                 u64 timestamp)
1518 {
1519         struct intel_pt_queue *ptq;
1520         int err;
1521
1522         if (!pt->sync_switch)
1523                 return 1;
1524
1525         ptq = intel_pt_cpu_to_ptq(pt, cpu);
1526         if (!ptq)
1527                 return 1;
1528
1529         switch (ptq->switch_state) {
1530         case INTEL_PT_SS_NOT_TRACING:
1531                 ptq->next_tid = -1;
1532                 break;
1533         case INTEL_PT_SS_UNKNOWN:
1534         case INTEL_PT_SS_TRACING:
1535                 ptq->next_tid = tid;
1536                 ptq->switch_state = INTEL_PT_SS_EXPECTING_SWITCH_IP;
1537                 return 0;
1538         case INTEL_PT_SS_EXPECTING_SWITCH_EVENT:
1539                 if (!ptq->on_heap) {
1540                         ptq->timestamp = perf_time_to_tsc(timestamp,
1541                                                           &pt->tc);
1542                         err = auxtrace_heap__add(&pt->heap, ptq->queue_nr,
1543                                                  ptq->timestamp);
1544                         if (err)
1545                                 return err;
1546                         ptq->on_heap = true;
1547                 }
1548                 ptq->switch_state = INTEL_PT_SS_TRACING;
1549                 break;
1550         case INTEL_PT_SS_EXPECTING_SWITCH_IP:
1551                 ptq->next_tid = tid;
1552                 intel_pt_log("ERROR: cpu %d expecting switch ip\n", cpu);
1553                 break;
1554         default:
1555                 break;
1556         }
1557
1558         return 1;
1559 }
1560
1561 static int intel_pt_process_switch(struct intel_pt *pt,
1562                                    struct perf_sample *sample)
1563 {
1564         struct perf_evsel *evsel;
1565         pid_t tid;
1566         int cpu, ret;
1567
1568         evsel = perf_evlist__id2evsel(pt->session->evlist, sample->id);
1569         if (evsel != pt->switch_evsel)
1570                 return 0;
1571
1572         tid = perf_evsel__intval(evsel, sample, "next_pid");
1573         cpu = sample->cpu;
1574
1575         intel_pt_log("sched_switch: cpu %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
1576                      cpu, tid, sample->time, perf_time_to_tsc(sample->time,
1577                      &pt->tc));
1578
1579         ret = intel_pt_sync_switch(pt, cpu, tid, sample->time);
1580         if (ret <= 0)
1581                 return ret;
1582
1583         return machine__set_current_tid(pt->machine, cpu, -1, tid);
1584 }
1585
1586 static int intel_pt_context_switch(struct intel_pt *pt, union perf_event *event,
1587                                    struct perf_sample *sample)
1588 {
1589         bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
1590         pid_t pid, tid;
1591         int cpu, ret;
1592
1593         cpu = sample->cpu;
1594
1595         if (pt->have_sched_switch == 3) {
1596                 if (!out)
1597                         return 0;
1598                 if (event->header.type != PERF_RECORD_SWITCH_CPU_WIDE) {
1599                         pr_err("Expecting CPU-wide context switch event\n");
1600                         return -EINVAL;
1601                 }
1602                 pid = event->context_switch.next_prev_pid;
1603                 tid = event->context_switch.next_prev_tid;
1604         } else {
1605                 if (out)
1606                         return 0;
1607                 pid = sample->pid;
1608                 tid = sample->tid;
1609         }
1610
1611         if (tid == -1) {
1612                 pr_err("context_switch event has no tid\n");
1613                 return -EINVAL;
1614         }
1615
1616         intel_pt_log("context_switch: cpu %d pid %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
1617                      cpu, pid, tid, sample->time, perf_time_to_tsc(sample->time,
1618                      &pt->tc));
1619
1620         ret = intel_pt_sync_switch(pt, cpu, tid, sample->time);
1621         if (ret <= 0)
1622                 return ret;
1623
1624         return machine__set_current_tid(pt->machine, cpu, pid, tid);
1625 }
1626
1627 static int intel_pt_process_itrace_start(struct intel_pt *pt,
1628                                          union perf_event *event,
1629                                          struct perf_sample *sample)
1630 {
1631         if (!pt->per_cpu_mmaps)
1632                 return 0;
1633
1634         intel_pt_log("itrace_start: cpu %d pid %d tid %d time %"PRIu64" tsc %#"PRIx64"\n",
1635                      sample->cpu, event->itrace_start.pid,
1636                      event->itrace_start.tid, sample->time,
1637                      perf_time_to_tsc(sample->time, &pt->tc));
1638
1639         return machine__set_current_tid(pt->machine, sample->cpu,
1640                                         event->itrace_start.pid,
1641                                         event->itrace_start.tid);
1642 }
1643
1644 static int intel_pt_process_event(struct perf_session *session,
1645                                   union perf_event *event,
1646                                   struct perf_sample *sample,
1647                                   struct perf_tool *tool)
1648 {
1649         struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
1650                                            auxtrace);
1651         u64 timestamp;
1652         int err = 0;
1653
1654         if (dump_trace)
1655                 return 0;
1656
1657         if (!tool->ordered_events) {
1658                 pr_err("Intel Processor Trace requires ordered events\n");
1659                 return -EINVAL;
1660         }
1661
1662         if (sample->time && sample->time != (u64)-1)
1663                 timestamp = perf_time_to_tsc(sample->time, &pt->tc);
1664         else
1665                 timestamp = 0;
1666
1667         if (timestamp || pt->timeless_decoding) {
1668                 err = intel_pt_update_queues(pt);
1669                 if (err)
1670                         return err;
1671         }
1672
1673         if (pt->timeless_decoding) {
1674                 if (event->header.type == PERF_RECORD_EXIT) {
1675                         err = intel_pt_process_timeless_queues(pt,
1676                                                                event->fork.tid,
1677                                                                sample->time);
1678                 }
1679         } else if (timestamp) {
1680                 err = intel_pt_process_queues(pt, timestamp);
1681         }
1682         if (err)
1683                 return err;
1684
1685         if (event->header.type == PERF_RECORD_AUX &&
1686             (event->aux.flags & PERF_AUX_FLAG_TRUNCATED) &&
1687             pt->synth_opts.errors) {
1688                 err = intel_pt_lost(pt, sample);
1689                 if (err)
1690                         return err;
1691         }
1692
1693         if (pt->switch_evsel && event->header.type == PERF_RECORD_SAMPLE)
1694                 err = intel_pt_process_switch(pt, sample);
1695         else if (event->header.type == PERF_RECORD_ITRACE_START)
1696                 err = intel_pt_process_itrace_start(pt, event, sample);
1697         else if (event->header.type == PERF_RECORD_SWITCH ||
1698                  event->header.type == PERF_RECORD_SWITCH_CPU_WIDE)
1699                 err = intel_pt_context_switch(pt, event, sample);
1700
1701         intel_pt_log("event %s (%u): cpu %d time %"PRIu64" tsc %#"PRIx64"\n",
1702                      perf_event__name(event->header.type), event->header.type,
1703                      sample->cpu, sample->time, timestamp);
1704
1705         return err;
1706 }
1707
1708 static int intel_pt_flush(struct perf_session *session, struct perf_tool *tool)
1709 {
1710         struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
1711                                            auxtrace);
1712         int ret;
1713
1714         if (dump_trace)
1715                 return 0;
1716
1717         if (!tool->ordered_events)
1718                 return -EINVAL;
1719
1720         ret = intel_pt_update_queues(pt);
1721         if (ret < 0)
1722                 return ret;
1723
1724         if (pt->timeless_decoding)
1725                 return intel_pt_process_timeless_queues(pt, -1,
1726                                                         MAX_TIMESTAMP - 1);
1727
1728         return intel_pt_process_queues(pt, MAX_TIMESTAMP);
1729 }
1730
1731 static void intel_pt_free_events(struct perf_session *session)
1732 {
1733         struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
1734                                            auxtrace);
1735         struct auxtrace_queues *queues = &pt->queues;
1736         unsigned int i;
1737
1738         for (i = 0; i < queues->nr_queues; i++) {
1739                 intel_pt_free_queue(queues->queue_array[i].priv);
1740                 queues->queue_array[i].priv = NULL;
1741         }
1742         intel_pt_log_disable();
1743         auxtrace_queues__free(queues);
1744 }
1745
1746 static void intel_pt_free(struct perf_session *session)
1747 {
1748         struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
1749                                            auxtrace);
1750
1751         auxtrace_heap__free(&pt->heap);
1752         intel_pt_free_events(session);
1753         session->auxtrace = NULL;
1754         thread__delete(pt->unknown_thread);
1755         free(pt);
1756 }
1757
1758 static int intel_pt_process_auxtrace_event(struct perf_session *session,
1759                                            union perf_event *event,
1760                                            struct perf_tool *tool __maybe_unused)
1761 {
1762         struct intel_pt *pt = container_of(session->auxtrace, struct intel_pt,
1763                                            auxtrace);
1764
1765         if (pt->sampling_mode)
1766                 return 0;
1767
1768         if (!pt->data_queued) {
1769                 struct auxtrace_buffer *buffer;
1770                 off_t data_offset;
1771                 int fd = perf_data_file__fd(session->file);
1772                 int err;
1773
1774                 if (perf_data_file__is_pipe(session->file)) {
1775                         data_offset = 0;
1776                 } else {
1777                         data_offset = lseek(fd, 0, SEEK_CUR);
1778                         if (data_offset == -1)
1779                                 return -errno;
1780                 }
1781
1782                 err = auxtrace_queues__add_event(&pt->queues, session, event,
1783                                                  data_offset, &buffer);
1784                 if (err)
1785                         return err;
1786
1787                 /* Dump here now we have copied a piped trace out of the pipe */
1788                 if (dump_trace) {
1789                         if (auxtrace_buffer__get_data(buffer, fd)) {
1790                                 intel_pt_dump_event(pt, buffer->data,
1791                                                     buffer->size);
1792                                 auxtrace_buffer__put_data(buffer);
1793                         }
1794                 }
1795         }
1796
1797         return 0;
1798 }
1799
1800 struct intel_pt_synth {
1801         struct perf_tool dummy_tool;
1802         struct perf_session *session;
1803 };
1804
1805 static int intel_pt_event_synth(struct perf_tool *tool,
1806                                 union perf_event *event,
1807                                 struct perf_sample *sample __maybe_unused,
1808                                 struct machine *machine __maybe_unused)
1809 {
1810         struct intel_pt_synth *intel_pt_synth =
1811                         container_of(tool, struct intel_pt_synth, dummy_tool);
1812
1813         return perf_session__deliver_synth_event(intel_pt_synth->session, event,
1814                                                  NULL);
1815 }
1816
1817 static int intel_pt_synth_event(struct perf_session *session,
1818                                 struct perf_event_attr *attr, u64 id)
1819 {
1820         struct intel_pt_synth intel_pt_synth;
1821
1822         memset(&intel_pt_synth, 0, sizeof(struct intel_pt_synth));
1823         intel_pt_synth.session = session;
1824
1825         return perf_event__synthesize_attr(&intel_pt_synth.dummy_tool, attr, 1,
1826                                            &id, intel_pt_event_synth);
1827 }
1828
1829 static int intel_pt_synth_events(struct intel_pt *pt,
1830                                  struct perf_session *session)
1831 {
1832         struct perf_evlist *evlist = session->evlist;
1833         struct perf_evsel *evsel;
1834         struct perf_event_attr attr;
1835         bool found = false;
1836         u64 id;
1837         int err;
1838
1839         evlist__for_each(evlist, evsel) {
1840                 if (evsel->attr.type == pt->pmu_type && evsel->ids) {
1841                         found = true;
1842                         break;
1843                 }
1844         }
1845
1846         if (!found) {
1847                 pr_debug("There are no selected events with Intel Processor Trace data\n");
1848                 return 0;
1849         }
1850
1851         memset(&attr, 0, sizeof(struct perf_event_attr));
1852         attr.size = sizeof(struct perf_event_attr);
1853         attr.type = PERF_TYPE_HARDWARE;
1854         attr.sample_type = evsel->attr.sample_type & PERF_SAMPLE_MASK;
1855         attr.sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID |
1856                             PERF_SAMPLE_PERIOD;
1857         if (pt->timeless_decoding)
1858                 attr.sample_type &= ~(u64)PERF_SAMPLE_TIME;
1859         else
1860                 attr.sample_type |= PERF_SAMPLE_TIME;
1861         if (!pt->per_cpu_mmaps)
1862                 attr.sample_type &= ~(u64)PERF_SAMPLE_CPU;
1863         attr.exclude_user = evsel->attr.exclude_user;
1864         attr.exclude_kernel = evsel->attr.exclude_kernel;
1865         attr.exclude_hv = evsel->attr.exclude_hv;
1866         attr.exclude_host = evsel->attr.exclude_host;
1867         attr.exclude_guest = evsel->attr.exclude_guest;
1868         attr.sample_id_all = evsel->attr.sample_id_all;
1869         attr.read_format = evsel->attr.read_format;
1870
1871         id = evsel->id[0] + 1000000000;
1872         if (!id)
1873                 id = 1;
1874
1875         if (pt->synth_opts.instructions) {
1876                 attr.config = PERF_COUNT_HW_INSTRUCTIONS;
1877                 if (pt->synth_opts.period_type == PERF_ITRACE_PERIOD_NANOSECS)
1878                         attr.sample_period =
1879                                 intel_pt_ns_to_ticks(pt, pt->synth_opts.period);
1880                 else
1881                         attr.sample_period = pt->synth_opts.period;
1882                 pt->instructions_sample_period = attr.sample_period;
1883                 if (pt->synth_opts.callchain)
1884                         attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
1885                 if (pt->synth_opts.last_branch)
1886                         attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
1887                 pr_debug("Synthesizing 'instructions' event with id %" PRIu64 " sample type %#" PRIx64 "\n",
1888                          id, (u64)attr.sample_type);
1889                 err = intel_pt_synth_event(session, &attr, id);
1890                 if (err) {
1891                         pr_err("%s: failed to synthesize 'instructions' event type\n",
1892                                __func__);
1893                         return err;
1894                 }
1895                 pt->sample_instructions = true;
1896                 pt->instructions_sample_type = attr.sample_type;
1897                 pt->instructions_id = id;
1898                 id += 1;
1899         }
1900
1901         if (pt->synth_opts.transactions) {
1902                 attr.config = PERF_COUNT_HW_INSTRUCTIONS;
1903                 attr.sample_period = 1;
1904                 if (pt->synth_opts.callchain)
1905                         attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
1906                 if (pt->synth_opts.last_branch)
1907                         attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
1908                 pr_debug("Synthesizing 'transactions' event with id %" PRIu64 " sample type %#" PRIx64 "\n",
1909                          id, (u64)attr.sample_type);
1910                 err = intel_pt_synth_event(session, &attr, id);
1911                 if (err) {
1912                         pr_err("%s: failed to synthesize 'transactions' event type\n",
1913                                __func__);
1914                         return err;
1915                 }
1916                 pt->sample_transactions = true;
1917                 pt->transactions_id = id;
1918                 id += 1;
1919                 evlist__for_each(evlist, evsel) {
1920                         if (evsel->id && evsel->id[0] == pt->transactions_id) {
1921                                 if (evsel->name)
1922                                         zfree(&evsel->name);
1923                                 evsel->name = strdup("transactions");
1924                                 break;
1925                         }
1926                 }
1927         }
1928
1929         if (pt->synth_opts.branches) {
1930                 attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
1931                 attr.sample_period = 1;
1932                 attr.sample_type |= PERF_SAMPLE_ADDR;
1933                 attr.sample_type &= ~(u64)PERF_SAMPLE_CALLCHAIN;
1934                 attr.sample_type &= ~(u64)PERF_SAMPLE_BRANCH_STACK;
1935                 pr_debug("Synthesizing 'branches' event with id %" PRIu64 " sample type %#" PRIx64 "\n",
1936                          id, (u64)attr.sample_type);
1937                 err = intel_pt_synth_event(session, &attr, id);
1938                 if (err) {
1939                         pr_err("%s: failed to synthesize 'branches' event type\n",
1940                                __func__);
1941                         return err;
1942                 }
1943                 pt->sample_branches = true;
1944                 pt->branches_sample_type = attr.sample_type;
1945                 pt->branches_id = id;
1946         }
1947
1948         pt->synth_needs_swap = evsel->needs_swap;
1949
1950         return 0;
1951 }
1952
1953 static struct perf_evsel *intel_pt_find_sched_switch(struct perf_evlist *evlist)
1954 {
1955         struct perf_evsel *evsel;
1956
1957         evlist__for_each_reverse(evlist, evsel) {
1958                 const char *name = perf_evsel__name(evsel);
1959
1960                 if (!strcmp(name, "sched:sched_switch"))
1961                         return evsel;
1962         }
1963
1964         return NULL;
1965 }
1966
1967 static bool intel_pt_find_switch(struct perf_evlist *evlist)
1968 {
1969         struct perf_evsel *evsel;
1970
1971         evlist__for_each(evlist, evsel) {
1972                 if (evsel->attr.context_switch)
1973                         return true;
1974         }
1975
1976         return false;
1977 }
1978
1979 static int intel_pt_perf_config(const char *var, const char *value, void *data)
1980 {
1981         struct intel_pt *pt = data;
1982
1983         if (!strcmp(var, "intel-pt.mispred-all"))
1984                 pt->mispred_all = perf_config_bool(var, value);
1985
1986         return 0;
1987 }
1988
1989 static const char * const intel_pt_info_fmts[] = {
1990         [INTEL_PT_PMU_TYPE]             = "  PMU Type            %"PRId64"\n",
1991         [INTEL_PT_TIME_SHIFT]           = "  Time Shift          %"PRIu64"\n",
1992         [INTEL_PT_TIME_MULT]            = "  Time Muliplier      %"PRIu64"\n",
1993         [INTEL_PT_TIME_ZERO]            = "  Time Zero           %"PRIu64"\n",
1994         [INTEL_PT_CAP_USER_TIME_ZERO]   = "  Cap Time Zero       %"PRId64"\n",
1995         [INTEL_PT_TSC_BIT]              = "  TSC bit             %#"PRIx64"\n",
1996         [INTEL_PT_NORETCOMP_BIT]        = "  NoRETComp bit       %#"PRIx64"\n",
1997         [INTEL_PT_HAVE_SCHED_SWITCH]    = "  Have sched_switch   %"PRId64"\n",
1998         [INTEL_PT_SNAPSHOT_MODE]        = "  Snapshot mode       %"PRId64"\n",
1999         [INTEL_PT_PER_CPU_MMAPS]        = "  Per-cpu maps        %"PRId64"\n",
2000         [INTEL_PT_MTC_BIT]              = "  MTC bit             %#"PRIx64"\n",
2001         [INTEL_PT_TSC_CTC_N]            = "  TSC:CTC numerator   %"PRIu64"\n",
2002         [INTEL_PT_TSC_CTC_D]            = "  TSC:CTC denominator %"PRIu64"\n",
2003         [INTEL_PT_CYC_BIT]              = "  CYC bit             %#"PRIx64"\n",
2004 };
2005
2006 static void intel_pt_print_info(u64 *arr, int start, int finish)
2007 {
2008         int i;
2009
2010         if (!dump_trace)
2011                 return;
2012
2013         for (i = start; i <= finish; i++)
2014                 fprintf(stdout, intel_pt_info_fmts[i], arr[i]);
2015 }
2016
2017 int intel_pt_process_auxtrace_info(union perf_event *event,
2018                                    struct perf_session *session)
2019 {
2020         struct auxtrace_info_event *auxtrace_info = &event->auxtrace_info;
2021         size_t min_sz = sizeof(u64) * INTEL_PT_PER_CPU_MMAPS;
2022         struct intel_pt *pt;
2023         int err;
2024
2025         if (auxtrace_info->header.size < sizeof(struct auxtrace_info_event) +
2026                                         min_sz)
2027                 return -EINVAL;
2028
2029         pt = zalloc(sizeof(struct intel_pt));
2030         if (!pt)
2031                 return -ENOMEM;
2032
2033         perf_config(intel_pt_perf_config, pt);
2034
2035         err = auxtrace_queues__init(&pt->queues);
2036         if (err)
2037                 goto err_free;
2038
2039         intel_pt_log_set_name(INTEL_PT_PMU_NAME);
2040
2041         pt->session = session;
2042         pt->machine = &session->machines.host; /* No kvm support */
2043         pt->auxtrace_type = auxtrace_info->type;
2044         pt->pmu_type = auxtrace_info->priv[INTEL_PT_PMU_TYPE];
2045         pt->tc.time_shift = auxtrace_info->priv[INTEL_PT_TIME_SHIFT];
2046         pt->tc.time_mult = auxtrace_info->priv[INTEL_PT_TIME_MULT];
2047         pt->tc.time_zero = auxtrace_info->priv[INTEL_PT_TIME_ZERO];
2048         pt->cap_user_time_zero = auxtrace_info->priv[INTEL_PT_CAP_USER_TIME_ZERO];
2049         pt->tsc_bit = auxtrace_info->priv[INTEL_PT_TSC_BIT];
2050         pt->noretcomp_bit = auxtrace_info->priv[INTEL_PT_NORETCOMP_BIT];
2051         pt->have_sched_switch = auxtrace_info->priv[INTEL_PT_HAVE_SCHED_SWITCH];
2052         pt->snapshot_mode = auxtrace_info->priv[INTEL_PT_SNAPSHOT_MODE];
2053         pt->per_cpu_mmaps = auxtrace_info->priv[INTEL_PT_PER_CPU_MMAPS];
2054         intel_pt_print_info(&auxtrace_info->priv[0], INTEL_PT_PMU_TYPE,
2055                             INTEL_PT_PER_CPU_MMAPS);
2056
2057         if (auxtrace_info->header.size >= sizeof(struct auxtrace_info_event) +
2058                                         (sizeof(u64) * INTEL_PT_CYC_BIT)) {
2059                 pt->mtc_bit = auxtrace_info->priv[INTEL_PT_MTC_BIT];
2060                 pt->mtc_freq_bits = auxtrace_info->priv[INTEL_PT_MTC_FREQ_BITS];
2061                 pt->tsc_ctc_ratio_n = auxtrace_info->priv[INTEL_PT_TSC_CTC_N];
2062                 pt->tsc_ctc_ratio_d = auxtrace_info->priv[INTEL_PT_TSC_CTC_D];
2063                 pt->cyc_bit = auxtrace_info->priv[INTEL_PT_CYC_BIT];
2064                 intel_pt_print_info(&auxtrace_info->priv[0], INTEL_PT_MTC_BIT,
2065                                     INTEL_PT_CYC_BIT);
2066         }
2067
2068         pt->timeless_decoding = intel_pt_timeless_decoding(pt);
2069         pt->have_tsc = intel_pt_have_tsc(pt);
2070         pt->sampling_mode = false;
2071         pt->est_tsc = !pt->timeless_decoding;
2072
2073         pt->unknown_thread = thread__new(999999999, 999999999);
2074         if (!pt->unknown_thread) {
2075                 err = -ENOMEM;
2076                 goto err_free_queues;
2077         }
2078         err = thread__set_comm(pt->unknown_thread, "unknown", 0);
2079         if (err)
2080                 goto err_delete_thread;
2081         if (thread__init_map_groups(pt->unknown_thread, pt->machine)) {
2082                 err = -ENOMEM;
2083                 goto err_delete_thread;
2084         }
2085
2086         pt->auxtrace.process_event = intel_pt_process_event;
2087         pt->auxtrace.process_auxtrace_event = intel_pt_process_auxtrace_event;
2088         pt->auxtrace.flush_events = intel_pt_flush;
2089         pt->auxtrace.free_events = intel_pt_free_events;
2090         pt->auxtrace.free = intel_pt_free;
2091         session->auxtrace = &pt->auxtrace;
2092
2093         if (dump_trace)
2094                 return 0;
2095
2096         if (pt->have_sched_switch == 1) {
2097                 pt->switch_evsel = intel_pt_find_sched_switch(session->evlist);
2098                 if (!pt->switch_evsel) {
2099                         pr_err("%s: missing sched_switch event\n", __func__);
2100                         goto err_delete_thread;
2101                 }
2102         } else if (pt->have_sched_switch == 2 &&
2103                    !intel_pt_find_switch(session->evlist)) {
2104                 pr_err("%s: missing context_switch attribute flag\n", __func__);
2105                 goto err_delete_thread;
2106         }
2107
2108         if (session->itrace_synth_opts && session->itrace_synth_opts->set) {
2109                 pt->synth_opts = *session->itrace_synth_opts;
2110         } else {
2111                 itrace_synth_opts__set_default(&pt->synth_opts);
2112                 if (use_browser != -1) {
2113                         pt->synth_opts.branches = false;
2114                         pt->synth_opts.callchain = true;
2115                 }
2116         }
2117
2118         if (pt->synth_opts.log)
2119                 intel_pt_log_enable();
2120
2121         /* Maximum non-turbo ratio is TSC freq / 100 MHz */
2122         if (pt->tc.time_mult) {
2123                 u64 tsc_freq = intel_pt_ns_to_ticks(pt, 1000000000);
2124
2125                 pt->max_non_turbo_ratio = (tsc_freq + 50000000) / 100000000;
2126                 intel_pt_log("TSC frequency %"PRIu64"\n", tsc_freq);
2127                 intel_pt_log("Maximum non-turbo ratio %u\n",
2128                              pt->max_non_turbo_ratio);
2129         }
2130
2131         if (pt->synth_opts.calls)
2132                 pt->branches_filter |= PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC |
2133                                        PERF_IP_FLAG_TRACE_END;
2134         if (pt->synth_opts.returns)
2135                 pt->branches_filter |= PERF_IP_FLAG_RETURN |
2136                                        PERF_IP_FLAG_TRACE_BEGIN;
2137
2138         if (pt->synth_opts.callchain && !symbol_conf.use_callchain) {
2139                 symbol_conf.use_callchain = true;
2140                 if (callchain_register_param(&callchain_param) < 0) {
2141                         symbol_conf.use_callchain = false;
2142                         pt->synth_opts.callchain = false;
2143                 }
2144         }
2145
2146         err = intel_pt_synth_events(pt, session);
2147         if (err)
2148                 goto err_delete_thread;
2149
2150         err = auxtrace_queues__process_index(&pt->queues, session);
2151         if (err)
2152                 goto err_delete_thread;
2153
2154         if (pt->queues.populated)
2155                 pt->data_queued = true;
2156
2157         if (pt->timeless_decoding)
2158                 pr_debug2("Intel PT decoding without timestamps\n");
2159
2160         return 0;
2161
2162 err_delete_thread:
2163         thread__delete(pt->unknown_thread);
2164 err_free_queues:
2165         intel_pt_log_disable();
2166         auxtrace_queues__free(&pt->queues);
2167         session->auxtrace = NULL;
2168 err_free:
2169         free(pt);
2170         return err;
2171 }