perf tools: Pass Intel PT information for decoding MTC and CYC
[cascardo/linux.git] / tools / perf / arch / x86 / 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 <stdbool.h>
17 #include <linux/kernel.h>
18 #include <linux/types.h>
19 #include <linux/bitops.h>
20 #include <linux/log2.h>
21 #include <cpuid.h>
22
23 #include "../../perf.h"
24 #include "../../util/session.h"
25 #include "../../util/event.h"
26 #include "../../util/evlist.h"
27 #include "../../util/evsel.h"
28 #include "../../util/cpumap.h"
29 #include "../../util/parse-options.h"
30 #include "../../util/parse-events.h"
31 #include "../../util/pmu.h"
32 #include "../../util/debug.h"
33 #include "../../util/auxtrace.h"
34 #include "../../util/tsc.h"
35 #include "../../util/intel-pt.h"
36
37 #define KiB(x) ((x) * 1024)
38 #define MiB(x) ((x) * 1024 * 1024)
39 #define KiB_MASK(x) (KiB(x) - 1)
40 #define MiB_MASK(x) (MiB(x) - 1)
41
42 #define INTEL_PT_DEFAULT_SAMPLE_SIZE    KiB(4)
43
44 #define INTEL_PT_MAX_SAMPLE_SIZE        KiB(60)
45
46 #define INTEL_PT_PSB_PERIOD_NEAR        256
47
48 struct intel_pt_snapshot_ref {
49         void *ref_buf;
50         size_t ref_offset;
51         bool wrapped;
52 };
53
54 struct intel_pt_recording {
55         struct auxtrace_record          itr;
56         struct perf_pmu                 *intel_pt_pmu;
57         int                             have_sched_switch;
58         struct perf_evlist              *evlist;
59         bool                            snapshot_mode;
60         bool                            snapshot_init_done;
61         size_t                          snapshot_size;
62         size_t                          snapshot_ref_buf_size;
63         int                             snapshot_ref_cnt;
64         struct intel_pt_snapshot_ref    *snapshot_refs;
65 };
66
67 static int intel_pt_parse_terms_with_default(struct list_head *formats,
68                                              const char *str,
69                                              u64 *config)
70 {
71         struct list_head *terms;
72         struct perf_event_attr attr = { .size = 0, };
73         int err;
74
75         terms = malloc(sizeof(struct list_head));
76         if (!terms)
77                 return -ENOMEM;
78
79         INIT_LIST_HEAD(terms);
80
81         err = parse_events_terms(terms, str);
82         if (err)
83                 goto out_free;
84
85         attr.config = *config;
86         err = perf_pmu__config_terms(formats, &attr, terms, true, NULL);
87         if (err)
88                 goto out_free;
89
90         *config = attr.config;
91 out_free:
92         parse_events__free_terms(terms);
93         return err;
94 }
95
96 static int intel_pt_parse_terms(struct list_head *formats, const char *str,
97                                 u64 *config)
98 {
99         *config = 0;
100         return intel_pt_parse_terms_with_default(formats, str, config);
101 }
102
103 static u64 intel_pt_masked_bits(u64 mask, u64 bits)
104 {
105         const u64 top_bit = 1ULL << 63;
106         u64 res = 0;
107         int i;
108
109         for (i = 0; i < 64; i++) {
110                 if (mask & top_bit) {
111                         res <<= 1;
112                         if (bits & top_bit)
113                                 res |= 1;
114                 }
115                 mask <<= 1;
116                 bits <<= 1;
117         }
118
119         return res;
120 }
121
122 static int intel_pt_read_config(struct perf_pmu *intel_pt_pmu, const char *str,
123                                 struct perf_evlist *evlist, u64 *res)
124 {
125         struct perf_evsel *evsel;
126         u64 mask;
127
128         *res = 0;
129
130         mask = perf_pmu__format_bits(&intel_pt_pmu->format, str);
131         if (!mask)
132                 return -EINVAL;
133
134         evlist__for_each(evlist, evsel) {
135                 if (evsel->attr.type == intel_pt_pmu->type) {
136                         *res = intel_pt_masked_bits(mask, evsel->attr.config);
137                         return 0;
138                 }
139         }
140
141         return -EINVAL;
142 }
143
144 static size_t intel_pt_psb_period(struct perf_pmu *intel_pt_pmu,
145                                   struct perf_evlist *evlist)
146 {
147         u64 val;
148         int err, topa_multiple_entries;
149         size_t psb_period;
150
151         if (perf_pmu__scan_file(intel_pt_pmu, "caps/topa_multiple_entries",
152                                 "%d", &topa_multiple_entries) != 1)
153                 topa_multiple_entries = 0;
154
155         /*
156          * Use caps/topa_multiple_entries to indicate early hardware that had
157          * extra frequent PSBs.
158          */
159         if (!topa_multiple_entries) {
160                 psb_period = 256;
161                 goto out;
162         }
163
164         err = intel_pt_read_config(intel_pt_pmu, "psb_period", evlist, &val);
165         if (err)
166                 val = 0;
167
168         psb_period = 1 << (val + 11);
169 out:
170         pr_debug2("%s psb_period %zu\n", intel_pt_pmu->name, psb_period);
171         return psb_period;
172 }
173
174 static int intel_pt_pick_bit(int bits, int target)
175 {
176         int pos, pick = -1;
177
178         for (pos = 0; bits; bits >>= 1, pos++) {
179                 if (bits & 1) {
180                         if (pos <= target || pick < 0)
181                                 pick = pos;
182                         if (pos >= target)
183                                 break;
184                 }
185         }
186
187         return pick;
188 }
189
190 static u64 intel_pt_default_config(struct perf_pmu *intel_pt_pmu)
191 {
192         char buf[256];
193         int psb_cyc, psb_periods, psb_period;
194         int pos = 0;
195         u64 config;
196
197         pos += scnprintf(buf + pos, sizeof(buf) - pos, "tsc");
198
199         if (perf_pmu__scan_file(intel_pt_pmu, "caps/psb_cyc", "%d",
200                                 &psb_cyc) != 1)
201                 psb_cyc = 1;
202
203         if (psb_cyc) {
204                 if (perf_pmu__scan_file(intel_pt_pmu, "caps/psb_periods", "%x",
205                                         &psb_periods) != 1)
206                         psb_periods = 0;
207                 if (psb_periods) {
208                         psb_period = intel_pt_pick_bit(psb_periods, 3);
209                         pos += scnprintf(buf + pos, sizeof(buf) - pos,
210                                          ",psb_period=%d", psb_period);
211                 }
212         }
213
214         pr_debug2("%s default config: %s\n", intel_pt_pmu->name, buf);
215
216         intel_pt_parse_terms(&intel_pt_pmu->format, buf, &config);
217
218         return config;
219 }
220
221 static int intel_pt_parse_snapshot_options(struct auxtrace_record *itr,
222                                            struct record_opts *opts,
223                                            const char *str)
224 {
225         struct intel_pt_recording *ptr =
226                         container_of(itr, struct intel_pt_recording, itr);
227         unsigned long long snapshot_size = 0;
228         char *endptr;
229
230         if (str) {
231                 snapshot_size = strtoull(str, &endptr, 0);
232                 if (*endptr || snapshot_size > SIZE_MAX)
233                         return -1;
234         }
235
236         opts->auxtrace_snapshot_mode = true;
237         opts->auxtrace_snapshot_size = snapshot_size;
238
239         ptr->snapshot_size = snapshot_size;
240
241         return 0;
242 }
243
244 struct perf_event_attr *
245 intel_pt_pmu_default_config(struct perf_pmu *intel_pt_pmu)
246 {
247         struct perf_event_attr *attr;
248
249         attr = zalloc(sizeof(struct perf_event_attr));
250         if (!attr)
251                 return NULL;
252
253         attr->config = intel_pt_default_config(intel_pt_pmu);
254
255         intel_pt_pmu->selectable = true;
256
257         return attr;
258 }
259
260 static size_t intel_pt_info_priv_size(struct auxtrace_record *itr __maybe_unused)
261 {
262         return INTEL_PT_AUXTRACE_PRIV_SIZE;
263 }
264
265 static void intel_pt_tsc_ctc_ratio(u32 *n, u32 *d)
266 {
267         unsigned int eax = 0, ebx = 0, ecx = 0, edx = 0;
268
269         __get_cpuid(0x15, &eax, &ebx, &ecx, &edx);
270         *n = ebx;
271         *d = eax;
272 }
273
274 static int intel_pt_info_fill(struct auxtrace_record *itr,
275                               struct perf_session *session,
276                               struct auxtrace_info_event *auxtrace_info,
277                               size_t priv_size)
278 {
279         struct intel_pt_recording *ptr =
280                         container_of(itr, struct intel_pt_recording, itr);
281         struct perf_pmu *intel_pt_pmu = ptr->intel_pt_pmu;
282         struct perf_event_mmap_page *pc;
283         struct perf_tsc_conversion tc = { .time_mult = 0, };
284         bool cap_user_time_zero = false, per_cpu_mmaps;
285         u64 tsc_bit, mtc_bit, mtc_freq_bits, cyc_bit, noretcomp_bit;
286         u32 tsc_ctc_ratio_n, tsc_ctc_ratio_d;
287         int err;
288
289         if (priv_size != INTEL_PT_AUXTRACE_PRIV_SIZE)
290                 return -EINVAL;
291
292         intel_pt_parse_terms(&intel_pt_pmu->format, "tsc", &tsc_bit);
293         intel_pt_parse_terms(&intel_pt_pmu->format, "noretcomp",
294                              &noretcomp_bit);
295         intel_pt_parse_terms(&intel_pt_pmu->format, "mtc", &mtc_bit);
296         mtc_freq_bits = perf_pmu__format_bits(&intel_pt_pmu->format,
297                                               "mtc_period");
298         intel_pt_parse_terms(&intel_pt_pmu->format, "cyc", &cyc_bit);
299
300         intel_pt_tsc_ctc_ratio(&tsc_ctc_ratio_n, &tsc_ctc_ratio_d);
301
302         if (!session->evlist->nr_mmaps)
303                 return -EINVAL;
304
305         pc = session->evlist->mmap[0].base;
306         if (pc) {
307                 err = perf_read_tsc_conversion(pc, &tc);
308                 if (err) {
309                         if (err != -EOPNOTSUPP)
310                                 return err;
311                 } else {
312                         cap_user_time_zero = tc.time_mult != 0;
313                 }
314                 if (!cap_user_time_zero)
315                         ui__warning("Intel Processor Trace: TSC not available\n");
316         }
317
318         per_cpu_mmaps = !cpu_map__empty(session->evlist->cpus);
319
320         auxtrace_info->type = PERF_AUXTRACE_INTEL_PT;
321         auxtrace_info->priv[INTEL_PT_PMU_TYPE] = intel_pt_pmu->type;
322         auxtrace_info->priv[INTEL_PT_TIME_SHIFT] = tc.time_shift;
323         auxtrace_info->priv[INTEL_PT_TIME_MULT] = tc.time_mult;
324         auxtrace_info->priv[INTEL_PT_TIME_ZERO] = tc.time_zero;
325         auxtrace_info->priv[INTEL_PT_CAP_USER_TIME_ZERO] = cap_user_time_zero;
326         auxtrace_info->priv[INTEL_PT_TSC_BIT] = tsc_bit;
327         auxtrace_info->priv[INTEL_PT_NORETCOMP_BIT] = noretcomp_bit;
328         auxtrace_info->priv[INTEL_PT_HAVE_SCHED_SWITCH] = ptr->have_sched_switch;
329         auxtrace_info->priv[INTEL_PT_SNAPSHOT_MODE] = ptr->snapshot_mode;
330         auxtrace_info->priv[INTEL_PT_PER_CPU_MMAPS] = per_cpu_mmaps;
331         auxtrace_info->priv[INTEL_PT_MTC_BIT] = mtc_bit;
332         auxtrace_info->priv[INTEL_PT_MTC_FREQ_BITS] = mtc_freq_bits;
333         auxtrace_info->priv[INTEL_PT_TSC_CTC_N] = tsc_ctc_ratio_n;
334         auxtrace_info->priv[INTEL_PT_TSC_CTC_D] = tsc_ctc_ratio_d;
335         auxtrace_info->priv[INTEL_PT_CYC_BIT] = cyc_bit;
336
337         return 0;
338 }
339
340 static int intel_pt_track_switches(struct perf_evlist *evlist)
341 {
342         const char *sched_switch = "sched:sched_switch";
343         struct perf_evsel *evsel;
344         int err;
345
346         if (!perf_evlist__can_select_event(evlist, sched_switch))
347                 return -EPERM;
348
349         err = parse_events(evlist, sched_switch, NULL);
350         if (err) {
351                 pr_debug2("%s: failed to parse %s, error %d\n",
352                           __func__, sched_switch, err);
353                 return err;
354         }
355
356         evsel = perf_evlist__last(evlist);
357
358         perf_evsel__set_sample_bit(evsel, CPU);
359         perf_evsel__set_sample_bit(evsel, TIME);
360
361         evsel->system_wide = true;
362         evsel->no_aux_samples = true;
363         evsel->immediate = true;
364
365         return 0;
366 }
367
368 static void intel_pt_valid_str(char *str, size_t len, u64 valid)
369 {
370         unsigned int val, last = 0, state = 1;
371         int p = 0;
372
373         str[0] = '\0';
374
375         for (val = 0; val <= 64; val++, valid >>= 1) {
376                 if (valid & 1) {
377                         last = val;
378                         switch (state) {
379                         case 0:
380                                 p += scnprintf(str + p, len - p, ",");
381                                 /* Fall through */
382                         case 1:
383                                 p += scnprintf(str + p, len - p, "%u", val);
384                                 state = 2;
385                                 break;
386                         case 2:
387                                 state = 3;
388                                 break;
389                         case 3:
390                                 state = 4;
391                                 break;
392                         default:
393                                 break;
394                         }
395                 } else {
396                         switch (state) {
397                         case 3:
398                                 p += scnprintf(str + p, len - p, ",%u", last);
399                                 state = 0;
400                                 break;
401                         case 4:
402                                 p += scnprintf(str + p, len - p, "-%u", last);
403                                 state = 0;
404                                 break;
405                         default:
406                                 break;
407                         }
408                         if (state != 1)
409                                 state = 0;
410                 }
411         }
412 }
413
414 static int intel_pt_val_config_term(struct perf_pmu *intel_pt_pmu,
415                                     const char *caps, const char *name,
416                                     const char *supported, u64 config)
417 {
418         char valid_str[256];
419         unsigned int shift;
420         unsigned long long valid;
421         u64 bits;
422         int ok;
423
424         if (perf_pmu__scan_file(intel_pt_pmu, caps, "%llx", &valid) != 1)
425                 valid = 0;
426
427         if (supported &&
428             perf_pmu__scan_file(intel_pt_pmu, supported, "%d", &ok) == 1 && !ok)
429                 valid = 0;
430
431         valid |= 1;
432
433         bits = perf_pmu__format_bits(&intel_pt_pmu->format, name);
434
435         config &= bits;
436
437         for (shift = 0; bits && !(bits & 1); shift++)
438                 bits >>= 1;
439
440         config >>= shift;
441
442         if (config > 63)
443                 goto out_err;
444
445         if (valid & (1 << config))
446                 return 0;
447 out_err:
448         intel_pt_valid_str(valid_str, sizeof(valid_str), valid);
449         pr_err("Invalid %s for %s. Valid values are: %s\n",
450                name, INTEL_PT_PMU_NAME, valid_str);
451         return -EINVAL;
452 }
453
454 static int intel_pt_validate_config(struct perf_pmu *intel_pt_pmu,
455                                     struct perf_evsel *evsel)
456 {
457         if (!evsel)
458                 return 0;
459
460         return intel_pt_val_config_term(intel_pt_pmu, "caps/psb_periods",
461                                         "psb_period", "caps/psb_cyc",
462                                         evsel->attr.config);
463 }
464
465 static int intel_pt_recording_options(struct auxtrace_record *itr,
466                                       struct perf_evlist *evlist,
467                                       struct record_opts *opts)
468 {
469         struct intel_pt_recording *ptr =
470                         container_of(itr, struct intel_pt_recording, itr);
471         struct perf_pmu *intel_pt_pmu = ptr->intel_pt_pmu;
472         bool have_timing_info;
473         struct perf_evsel *evsel, *intel_pt_evsel = NULL;
474         const struct cpu_map *cpus = evlist->cpus;
475         bool privileged = geteuid() == 0 || perf_event_paranoid() < 0;
476         u64 tsc_bit;
477         int err;
478
479         ptr->evlist = evlist;
480         ptr->snapshot_mode = opts->auxtrace_snapshot_mode;
481
482         evlist__for_each(evlist, evsel) {
483                 if (evsel->attr.type == intel_pt_pmu->type) {
484                         if (intel_pt_evsel) {
485                                 pr_err("There may be only one " INTEL_PT_PMU_NAME " event\n");
486                                 return -EINVAL;
487                         }
488                         evsel->attr.freq = 0;
489                         evsel->attr.sample_period = 1;
490                         intel_pt_evsel = evsel;
491                         opts->full_auxtrace = true;
492                 }
493         }
494
495         if (opts->auxtrace_snapshot_mode && !opts->full_auxtrace) {
496                 pr_err("Snapshot mode (-S option) requires " INTEL_PT_PMU_NAME " PMU event (-e " INTEL_PT_PMU_NAME ")\n");
497                 return -EINVAL;
498         }
499
500         if (opts->use_clockid) {
501                 pr_err("Cannot use clockid (-k option) with " INTEL_PT_PMU_NAME "\n");
502                 return -EINVAL;
503         }
504
505         if (!opts->full_auxtrace)
506                 return 0;
507
508         err = intel_pt_validate_config(intel_pt_pmu, intel_pt_evsel);
509         if (err)
510                 return err;
511
512         /* Set default sizes for snapshot mode */
513         if (opts->auxtrace_snapshot_mode) {
514                 size_t psb_period = intel_pt_psb_period(intel_pt_pmu, evlist);
515
516                 if (!opts->auxtrace_snapshot_size && !opts->auxtrace_mmap_pages) {
517                         if (privileged) {
518                                 opts->auxtrace_mmap_pages = MiB(4) / page_size;
519                         } else {
520                                 opts->auxtrace_mmap_pages = KiB(128) / page_size;
521                                 if (opts->mmap_pages == UINT_MAX)
522                                         opts->mmap_pages = KiB(256) / page_size;
523                         }
524                 } else if (!opts->auxtrace_mmap_pages && !privileged &&
525                            opts->mmap_pages == UINT_MAX) {
526                         opts->mmap_pages = KiB(256) / page_size;
527                 }
528                 if (!opts->auxtrace_snapshot_size)
529                         opts->auxtrace_snapshot_size =
530                                 opts->auxtrace_mmap_pages * (size_t)page_size;
531                 if (!opts->auxtrace_mmap_pages) {
532                         size_t sz = opts->auxtrace_snapshot_size;
533
534                         sz = round_up(sz, page_size) / page_size;
535                         opts->auxtrace_mmap_pages = roundup_pow_of_two(sz);
536                 }
537                 if (opts->auxtrace_snapshot_size >
538                                 opts->auxtrace_mmap_pages * (size_t)page_size) {
539                         pr_err("Snapshot size %zu must not be greater than AUX area tracing mmap size %zu\n",
540                                opts->auxtrace_snapshot_size,
541                                opts->auxtrace_mmap_pages * (size_t)page_size);
542                         return -EINVAL;
543                 }
544                 if (!opts->auxtrace_snapshot_size || !opts->auxtrace_mmap_pages) {
545                         pr_err("Failed to calculate default snapshot size and/or AUX area tracing mmap pages\n");
546                         return -EINVAL;
547                 }
548                 pr_debug2("Intel PT snapshot size: %zu\n",
549                           opts->auxtrace_snapshot_size);
550                 if (psb_period &&
551                     opts->auxtrace_snapshot_size <= psb_period +
552                                                   INTEL_PT_PSB_PERIOD_NEAR)
553                         ui__warning("Intel PT snapshot size (%zu) may be too small for PSB period (%zu)\n",
554                                     opts->auxtrace_snapshot_size, psb_period);
555         }
556
557         /* Set default sizes for full trace mode */
558         if (opts->full_auxtrace && !opts->auxtrace_mmap_pages) {
559                 if (privileged) {
560                         opts->auxtrace_mmap_pages = MiB(4) / page_size;
561                 } else {
562                         opts->auxtrace_mmap_pages = KiB(128) / page_size;
563                         if (opts->mmap_pages == UINT_MAX)
564                                 opts->mmap_pages = KiB(256) / page_size;
565                 }
566         }
567
568         /* Validate auxtrace_mmap_pages */
569         if (opts->auxtrace_mmap_pages) {
570                 size_t sz = opts->auxtrace_mmap_pages * (size_t)page_size;
571                 size_t min_sz;
572
573                 if (opts->auxtrace_snapshot_mode)
574                         min_sz = KiB(4);
575                 else
576                         min_sz = KiB(8);
577
578                 if (sz < min_sz || !is_power_of_2(sz)) {
579                         pr_err("Invalid mmap size for Intel Processor Trace: must be at least %zuKiB and a power of 2\n",
580                                min_sz / 1024);
581                         return -EINVAL;
582                 }
583         }
584
585         intel_pt_parse_terms(&intel_pt_pmu->format, "tsc", &tsc_bit);
586
587         if (opts->full_auxtrace && (intel_pt_evsel->attr.config & tsc_bit))
588                 have_timing_info = true;
589         else
590                 have_timing_info = false;
591
592         /*
593          * Per-cpu recording needs sched_switch events to distinguish different
594          * threads.
595          */
596         if (have_timing_info && !cpu_map__empty(cpus)) {
597                 err = intel_pt_track_switches(evlist);
598                 if (err == -EPERM)
599                         pr_debug2("Unable to select sched:sched_switch\n");
600                 else if (err)
601                         return err;
602                 else
603                         ptr->have_sched_switch = 1;
604         }
605
606         if (intel_pt_evsel) {
607                 /*
608                  * To obtain the auxtrace buffer file descriptor, the auxtrace
609                  * event must come first.
610                  */
611                 perf_evlist__to_front(evlist, intel_pt_evsel);
612                 /*
613                  * In the case of per-cpu mmaps, we need the CPU on the
614                  * AUX event.
615                  */
616                 if (!cpu_map__empty(cpus))
617                         perf_evsel__set_sample_bit(intel_pt_evsel, CPU);
618         }
619
620         /* Add dummy event to keep tracking */
621         if (opts->full_auxtrace) {
622                 struct perf_evsel *tracking_evsel;
623
624                 err = parse_events(evlist, "dummy:u", NULL);
625                 if (err)
626                         return err;
627
628                 tracking_evsel = perf_evlist__last(evlist);
629
630                 perf_evlist__set_tracking_event(evlist, tracking_evsel);
631
632                 tracking_evsel->attr.freq = 0;
633                 tracking_evsel->attr.sample_period = 1;
634
635                 /* In per-cpu case, always need the time of mmap events etc */
636                 if (!cpu_map__empty(cpus))
637                         perf_evsel__set_sample_bit(tracking_evsel, TIME);
638         }
639
640         /*
641          * Warn the user when we do not have enough information to decode i.e.
642          * per-cpu with no sched_switch (except workload-only).
643          */
644         if (!ptr->have_sched_switch && !cpu_map__empty(cpus) &&
645             !target__none(&opts->target))
646                 ui__warning("Intel Processor Trace decoding will not be possible except for kernel tracing!\n");
647
648         return 0;
649 }
650
651 static int intel_pt_snapshot_start(struct auxtrace_record *itr)
652 {
653         struct intel_pt_recording *ptr =
654                         container_of(itr, struct intel_pt_recording, itr);
655         struct perf_evsel *evsel;
656
657         evlist__for_each(ptr->evlist, evsel) {
658                 if (evsel->attr.type == ptr->intel_pt_pmu->type)
659                         return perf_evlist__disable_event(ptr->evlist, evsel);
660         }
661         return -EINVAL;
662 }
663
664 static int intel_pt_snapshot_finish(struct auxtrace_record *itr)
665 {
666         struct intel_pt_recording *ptr =
667                         container_of(itr, struct intel_pt_recording, itr);
668         struct perf_evsel *evsel;
669
670         evlist__for_each(ptr->evlist, evsel) {
671                 if (evsel->attr.type == ptr->intel_pt_pmu->type)
672                         return perf_evlist__enable_event(ptr->evlist, evsel);
673         }
674         return -EINVAL;
675 }
676
677 static int intel_pt_alloc_snapshot_refs(struct intel_pt_recording *ptr, int idx)
678 {
679         const size_t sz = sizeof(struct intel_pt_snapshot_ref);
680         int cnt = ptr->snapshot_ref_cnt, new_cnt = cnt * 2;
681         struct intel_pt_snapshot_ref *refs;
682
683         if (!new_cnt)
684                 new_cnt = 16;
685
686         while (new_cnt <= idx)
687                 new_cnt *= 2;
688
689         refs = calloc(new_cnt, sz);
690         if (!refs)
691                 return -ENOMEM;
692
693         memcpy(refs, ptr->snapshot_refs, cnt * sz);
694
695         ptr->snapshot_refs = refs;
696         ptr->snapshot_ref_cnt = new_cnt;
697
698         return 0;
699 }
700
701 static void intel_pt_free_snapshot_refs(struct intel_pt_recording *ptr)
702 {
703         int i;
704
705         for (i = 0; i < ptr->snapshot_ref_cnt; i++)
706                 zfree(&ptr->snapshot_refs[i].ref_buf);
707         zfree(&ptr->snapshot_refs);
708 }
709
710 static void intel_pt_recording_free(struct auxtrace_record *itr)
711 {
712         struct intel_pt_recording *ptr =
713                         container_of(itr, struct intel_pt_recording, itr);
714
715         intel_pt_free_snapshot_refs(ptr);
716         free(ptr);
717 }
718
719 static int intel_pt_alloc_snapshot_ref(struct intel_pt_recording *ptr, int idx,
720                                        size_t snapshot_buf_size)
721 {
722         size_t ref_buf_size = ptr->snapshot_ref_buf_size;
723         void *ref_buf;
724
725         ref_buf = zalloc(ref_buf_size);
726         if (!ref_buf)
727                 return -ENOMEM;
728
729         ptr->snapshot_refs[idx].ref_buf = ref_buf;
730         ptr->snapshot_refs[idx].ref_offset = snapshot_buf_size - ref_buf_size;
731
732         return 0;
733 }
734
735 static size_t intel_pt_snapshot_ref_buf_size(struct intel_pt_recording *ptr,
736                                              size_t snapshot_buf_size)
737 {
738         const size_t max_size = 256 * 1024;
739         size_t buf_size = 0, psb_period;
740
741         if (ptr->snapshot_size <= 64 * 1024)
742                 return 0;
743
744         psb_period = intel_pt_psb_period(ptr->intel_pt_pmu, ptr->evlist);
745         if (psb_period)
746                 buf_size = psb_period * 2;
747
748         if (!buf_size || buf_size > max_size)
749                 buf_size = max_size;
750
751         if (buf_size >= snapshot_buf_size)
752                 return 0;
753
754         if (buf_size >= ptr->snapshot_size / 2)
755                 return 0;
756
757         return buf_size;
758 }
759
760 static int intel_pt_snapshot_init(struct intel_pt_recording *ptr,
761                                   size_t snapshot_buf_size)
762 {
763         if (ptr->snapshot_init_done)
764                 return 0;
765
766         ptr->snapshot_init_done = true;
767
768         ptr->snapshot_ref_buf_size = intel_pt_snapshot_ref_buf_size(ptr,
769                                                         snapshot_buf_size);
770
771         return 0;
772 }
773
774 /**
775  * intel_pt_compare_buffers - compare bytes in a buffer to a circular buffer.
776  * @buf1: first buffer
777  * @compare_size: number of bytes to compare
778  * @buf2: second buffer (a circular buffer)
779  * @offs2: offset in second buffer
780  * @buf2_size: size of second buffer
781  *
782  * The comparison allows for the possibility that the bytes to compare in the
783  * circular buffer are not contiguous.  It is assumed that @compare_size <=
784  * @buf2_size.  This function returns %false if the bytes are identical, %true
785  * otherwise.
786  */
787 static bool intel_pt_compare_buffers(void *buf1, size_t compare_size,
788                                      void *buf2, size_t offs2, size_t buf2_size)
789 {
790         size_t end2 = offs2 + compare_size, part_size;
791
792         if (end2 <= buf2_size)
793                 return memcmp(buf1, buf2 + offs2, compare_size);
794
795         part_size = end2 - buf2_size;
796         if (memcmp(buf1, buf2 + offs2, part_size))
797                 return true;
798
799         compare_size -= part_size;
800
801         return memcmp(buf1 + part_size, buf2, compare_size);
802 }
803
804 static bool intel_pt_compare_ref(void *ref_buf, size_t ref_offset,
805                                  size_t ref_size, size_t buf_size,
806                                  void *data, size_t head)
807 {
808         size_t ref_end = ref_offset + ref_size;
809
810         if (ref_end > buf_size) {
811                 if (head > ref_offset || head < ref_end - buf_size)
812                         return true;
813         } else if (head > ref_offset && head < ref_end) {
814                 return true;
815         }
816
817         return intel_pt_compare_buffers(ref_buf, ref_size, data, ref_offset,
818                                         buf_size);
819 }
820
821 static void intel_pt_copy_ref(void *ref_buf, size_t ref_size, size_t buf_size,
822                               void *data, size_t head)
823 {
824         if (head >= ref_size) {
825                 memcpy(ref_buf, data + head - ref_size, ref_size);
826         } else {
827                 memcpy(ref_buf, data, head);
828                 ref_size -= head;
829                 memcpy(ref_buf + head, data + buf_size - ref_size, ref_size);
830         }
831 }
832
833 static bool intel_pt_wrapped(struct intel_pt_recording *ptr, int idx,
834                              struct auxtrace_mmap *mm, unsigned char *data,
835                              u64 head)
836 {
837         struct intel_pt_snapshot_ref *ref = &ptr->snapshot_refs[idx];
838         bool wrapped;
839
840         wrapped = intel_pt_compare_ref(ref->ref_buf, ref->ref_offset,
841                                        ptr->snapshot_ref_buf_size, mm->len,
842                                        data, head);
843
844         intel_pt_copy_ref(ref->ref_buf, ptr->snapshot_ref_buf_size, mm->len,
845                           data, head);
846
847         return wrapped;
848 }
849
850 static bool intel_pt_first_wrap(u64 *data, size_t buf_size)
851 {
852         int i, a, b;
853
854         b = buf_size >> 3;
855         a = b - 512;
856         if (a < 0)
857                 a = 0;
858
859         for (i = a; i < b; i++) {
860                 if (data[i])
861                         return true;
862         }
863
864         return false;
865 }
866
867 static int intel_pt_find_snapshot(struct auxtrace_record *itr, int idx,
868                                   struct auxtrace_mmap *mm, unsigned char *data,
869                                   u64 *head, u64 *old)
870 {
871         struct intel_pt_recording *ptr =
872                         container_of(itr, struct intel_pt_recording, itr);
873         bool wrapped;
874         int err;
875
876         pr_debug3("%s: mmap index %d old head %zu new head %zu\n",
877                   __func__, idx, (size_t)*old, (size_t)*head);
878
879         err = intel_pt_snapshot_init(ptr, mm->len);
880         if (err)
881                 goto out_err;
882
883         if (idx >= ptr->snapshot_ref_cnt) {
884                 err = intel_pt_alloc_snapshot_refs(ptr, idx);
885                 if (err)
886                         goto out_err;
887         }
888
889         if (ptr->snapshot_ref_buf_size) {
890                 if (!ptr->snapshot_refs[idx].ref_buf) {
891                         err = intel_pt_alloc_snapshot_ref(ptr, idx, mm->len);
892                         if (err)
893                                 goto out_err;
894                 }
895                 wrapped = intel_pt_wrapped(ptr, idx, mm, data, *head);
896         } else {
897                 wrapped = ptr->snapshot_refs[idx].wrapped;
898                 if (!wrapped && intel_pt_first_wrap((u64 *)data, mm->len)) {
899                         ptr->snapshot_refs[idx].wrapped = true;
900                         wrapped = true;
901                 }
902         }
903
904         /*
905          * In full trace mode 'head' continually increases.  However in snapshot
906          * mode 'head' is an offset within the buffer.  Here 'old' and 'head'
907          * are adjusted to match the full trace case which expects that 'old' is
908          * always less than 'head'.
909          */
910         if (wrapped) {
911                 *old = *head;
912                 *head += mm->len;
913         } else {
914                 if (mm->mask)
915                         *old &= mm->mask;
916                 else
917                         *old %= mm->len;
918                 if (*old > *head)
919                         *head += mm->len;
920         }
921
922         pr_debug3("%s: wrap-around %sdetected, adjusted old head %zu adjusted new head %zu\n",
923                   __func__, wrapped ? "" : "not ", (size_t)*old, (size_t)*head);
924
925         return 0;
926
927 out_err:
928         pr_err("%s: failed, error %d\n", __func__, err);
929         return err;
930 }
931
932 static u64 intel_pt_reference(struct auxtrace_record *itr __maybe_unused)
933 {
934         return rdtsc();
935 }
936
937 static int intel_pt_read_finish(struct auxtrace_record *itr, int idx)
938 {
939         struct intel_pt_recording *ptr =
940                         container_of(itr, struct intel_pt_recording, itr);
941         struct perf_evsel *evsel;
942
943         evlist__for_each(ptr->evlist, evsel) {
944                 if (evsel->attr.type == ptr->intel_pt_pmu->type)
945                         return perf_evlist__enable_event_idx(ptr->evlist, evsel,
946                                                              idx);
947         }
948         return -EINVAL;
949 }
950
951 struct auxtrace_record *intel_pt_recording_init(int *err)
952 {
953         struct perf_pmu *intel_pt_pmu = perf_pmu__find(INTEL_PT_PMU_NAME);
954         struct intel_pt_recording *ptr;
955
956         if (!intel_pt_pmu)
957                 return NULL;
958
959         ptr = zalloc(sizeof(struct intel_pt_recording));
960         if (!ptr) {
961                 *err = -ENOMEM;
962                 return NULL;
963         }
964
965         ptr->intel_pt_pmu = intel_pt_pmu;
966         ptr->itr.recording_options = intel_pt_recording_options;
967         ptr->itr.info_priv_size = intel_pt_info_priv_size;
968         ptr->itr.info_fill = intel_pt_info_fill;
969         ptr->itr.free = intel_pt_recording_free;
970         ptr->itr.snapshot_start = intel_pt_snapshot_start;
971         ptr->itr.snapshot_finish = intel_pt_snapshot_finish;
972         ptr->itr.find_snapshot = intel_pt_find_snapshot;
973         ptr->itr.parse_snapshot_options = intel_pt_parse_snapshot_options;
974         ptr->itr.reference = intel_pt_reference;
975         ptr->itr.read_finish = intel_pt_read_finish;
976         return &ptr->itr;
977 }