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