Merge tag 'drm-fixes-for-v4.9-rc2' of git://people.freedesktop.org/~airlied/linux
[linux-2.6-microblaze.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
526         if (!evsel)
527                 return 0;
528
529         err = intel_pt_val_config_term(intel_pt_pmu, "caps/cycle_thresholds",
530                                        "cyc_thresh", "caps/psb_cyc",
531                                        evsel->attr.config);
532         if (err)
533                 return err;
534
535         err = intel_pt_val_config_term(intel_pt_pmu, "caps/mtc_periods",
536                                        "mtc_period", "caps/mtc",
537                                        evsel->attr.config);
538         if (err)
539                 return err;
540
541         return intel_pt_val_config_term(intel_pt_pmu, "caps/psb_periods",
542                                         "psb_period", "caps/psb_cyc",
543                                         evsel->attr.config);
544 }
545
546 static int intel_pt_recording_options(struct auxtrace_record *itr,
547                                       struct perf_evlist *evlist,
548                                       struct record_opts *opts)
549 {
550         struct intel_pt_recording *ptr =
551                         container_of(itr, struct intel_pt_recording, itr);
552         struct perf_pmu *intel_pt_pmu = ptr->intel_pt_pmu;
553         bool have_timing_info, need_immediate = false;
554         struct perf_evsel *evsel, *intel_pt_evsel = NULL;
555         const struct cpu_map *cpus = evlist->cpus;
556         bool privileged = geteuid() == 0 || perf_event_paranoid() < 0;
557         u64 tsc_bit;
558         int err;
559
560         ptr->evlist = evlist;
561         ptr->snapshot_mode = opts->auxtrace_snapshot_mode;
562
563         evlist__for_each_entry(evlist, evsel) {
564                 if (evsel->attr.type == intel_pt_pmu->type) {
565                         if (intel_pt_evsel) {
566                                 pr_err("There may be only one " INTEL_PT_PMU_NAME " event\n");
567                                 return -EINVAL;
568                         }
569                         evsel->attr.freq = 0;
570                         evsel->attr.sample_period = 1;
571                         intel_pt_evsel = evsel;
572                         opts->full_auxtrace = true;
573                 }
574         }
575
576         if (opts->auxtrace_snapshot_mode && !opts->full_auxtrace) {
577                 pr_err("Snapshot mode (-S option) requires " INTEL_PT_PMU_NAME " PMU event (-e " INTEL_PT_PMU_NAME ")\n");
578                 return -EINVAL;
579         }
580
581         if (opts->use_clockid) {
582                 pr_err("Cannot use clockid (-k option) with " INTEL_PT_PMU_NAME "\n");
583                 return -EINVAL;
584         }
585
586         if (!opts->full_auxtrace)
587                 return 0;
588
589         err = intel_pt_validate_config(intel_pt_pmu, intel_pt_evsel);
590         if (err)
591                 return err;
592
593         /* Set default sizes for snapshot mode */
594         if (opts->auxtrace_snapshot_mode) {
595                 size_t psb_period = intel_pt_psb_period(intel_pt_pmu, evlist);
596
597                 if (!opts->auxtrace_snapshot_size && !opts->auxtrace_mmap_pages) {
598                         if (privileged) {
599                                 opts->auxtrace_mmap_pages = MiB(4) / page_size;
600                         } else {
601                                 opts->auxtrace_mmap_pages = KiB(128) / page_size;
602                                 if (opts->mmap_pages == UINT_MAX)
603                                         opts->mmap_pages = KiB(256) / page_size;
604                         }
605                 } else if (!opts->auxtrace_mmap_pages && !privileged &&
606                            opts->mmap_pages == UINT_MAX) {
607                         opts->mmap_pages = KiB(256) / page_size;
608                 }
609                 if (!opts->auxtrace_snapshot_size)
610                         opts->auxtrace_snapshot_size =
611                                 opts->auxtrace_mmap_pages * (size_t)page_size;
612                 if (!opts->auxtrace_mmap_pages) {
613                         size_t sz = opts->auxtrace_snapshot_size;
614
615                         sz = round_up(sz, page_size) / page_size;
616                         opts->auxtrace_mmap_pages = roundup_pow_of_two(sz);
617                 }
618                 if (opts->auxtrace_snapshot_size >
619                                 opts->auxtrace_mmap_pages * (size_t)page_size) {
620                         pr_err("Snapshot size %zu must not be greater than AUX area tracing mmap size %zu\n",
621                                opts->auxtrace_snapshot_size,
622                                opts->auxtrace_mmap_pages * (size_t)page_size);
623                         return -EINVAL;
624                 }
625                 if (!opts->auxtrace_snapshot_size || !opts->auxtrace_mmap_pages) {
626                         pr_err("Failed to calculate default snapshot size and/or AUX area tracing mmap pages\n");
627                         return -EINVAL;
628                 }
629                 pr_debug2("Intel PT snapshot size: %zu\n",
630                           opts->auxtrace_snapshot_size);
631                 if (psb_period &&
632                     opts->auxtrace_snapshot_size <= psb_period +
633                                                   INTEL_PT_PSB_PERIOD_NEAR)
634                         ui__warning("Intel PT snapshot size (%zu) may be too small for PSB period (%zu)\n",
635                                     opts->auxtrace_snapshot_size, psb_period);
636         }
637
638         /* Set default sizes for full trace mode */
639         if (opts->full_auxtrace && !opts->auxtrace_mmap_pages) {
640                 if (privileged) {
641                         opts->auxtrace_mmap_pages = MiB(4) / page_size;
642                 } else {
643                         opts->auxtrace_mmap_pages = KiB(128) / page_size;
644                         if (opts->mmap_pages == UINT_MAX)
645                                 opts->mmap_pages = KiB(256) / page_size;
646                 }
647         }
648
649         /* Validate auxtrace_mmap_pages */
650         if (opts->auxtrace_mmap_pages) {
651                 size_t sz = opts->auxtrace_mmap_pages * (size_t)page_size;
652                 size_t min_sz;
653
654                 if (opts->auxtrace_snapshot_mode)
655                         min_sz = KiB(4);
656                 else
657                         min_sz = KiB(8);
658
659                 if (sz < min_sz || !is_power_of_2(sz)) {
660                         pr_err("Invalid mmap size for Intel Processor Trace: must be at least %zuKiB and a power of 2\n",
661                                min_sz / 1024);
662                         return -EINVAL;
663                 }
664         }
665
666         intel_pt_parse_terms(&intel_pt_pmu->format, "tsc", &tsc_bit);
667
668         if (opts->full_auxtrace && (intel_pt_evsel->attr.config & tsc_bit))
669                 have_timing_info = true;
670         else
671                 have_timing_info = false;
672
673         /*
674          * Per-cpu recording needs sched_switch events to distinguish different
675          * threads.
676          */
677         if (have_timing_info && !cpu_map__empty(cpus)) {
678                 if (perf_can_record_switch_events()) {
679                         bool cpu_wide = !target__none(&opts->target) &&
680                                         !target__has_task(&opts->target);
681
682                         if (!cpu_wide && perf_can_record_cpu_wide()) {
683                                 struct perf_evsel *switch_evsel;
684
685                                 err = parse_events(evlist, "dummy:u", NULL);
686                                 if (err)
687                                         return err;
688
689                                 switch_evsel = perf_evlist__last(evlist);
690
691                                 switch_evsel->attr.freq = 0;
692                                 switch_evsel->attr.sample_period = 1;
693                                 switch_evsel->attr.context_switch = 1;
694
695                                 switch_evsel->system_wide = true;
696                                 switch_evsel->no_aux_samples = true;
697                                 switch_evsel->immediate = true;
698
699                                 perf_evsel__set_sample_bit(switch_evsel, TID);
700                                 perf_evsel__set_sample_bit(switch_evsel, TIME);
701                                 perf_evsel__set_sample_bit(switch_evsel, CPU);
702
703                                 opts->record_switch_events = false;
704                                 ptr->have_sched_switch = 3;
705                         } else {
706                                 opts->record_switch_events = true;
707                                 need_immediate = true;
708                                 if (cpu_wide)
709                                         ptr->have_sched_switch = 3;
710                                 else
711                                         ptr->have_sched_switch = 2;
712                         }
713                 } else {
714                         err = intel_pt_track_switches(evlist);
715                         if (err == -EPERM)
716                                 pr_debug2("Unable to select sched:sched_switch\n");
717                         else if (err)
718                                 return err;
719                         else
720                                 ptr->have_sched_switch = 1;
721                 }
722         }
723
724         if (intel_pt_evsel) {
725                 /*
726                  * To obtain the auxtrace buffer file descriptor, the auxtrace
727                  * event must come first.
728                  */
729                 perf_evlist__to_front(evlist, intel_pt_evsel);
730                 /*
731                  * In the case of per-cpu mmaps, we need the CPU on the
732                  * AUX event.
733                  */
734                 if (!cpu_map__empty(cpus))
735                         perf_evsel__set_sample_bit(intel_pt_evsel, CPU);
736         }
737
738         /* Add dummy event to keep tracking */
739         if (opts->full_auxtrace) {
740                 struct perf_evsel *tracking_evsel;
741
742                 err = parse_events(evlist, "dummy:u", NULL);
743                 if (err)
744                         return err;
745
746                 tracking_evsel = perf_evlist__last(evlist);
747
748                 perf_evlist__set_tracking_event(evlist, tracking_evsel);
749
750                 tracking_evsel->attr.freq = 0;
751                 tracking_evsel->attr.sample_period = 1;
752
753                 if (need_immediate)
754                         tracking_evsel->immediate = true;
755
756                 /* In per-cpu case, always need the time of mmap events etc */
757                 if (!cpu_map__empty(cpus)) {
758                         perf_evsel__set_sample_bit(tracking_evsel, TIME);
759                         /* And the CPU for switch events */
760                         perf_evsel__set_sample_bit(tracking_evsel, CPU);
761                 }
762         }
763
764         /*
765          * Warn the user when we do not have enough information to decode i.e.
766          * per-cpu with no sched_switch (except workload-only).
767          */
768         if (!ptr->have_sched_switch && !cpu_map__empty(cpus) &&
769             !target__none(&opts->target))
770                 ui__warning("Intel Processor Trace decoding will not be possible except for kernel tracing!\n");
771
772         return 0;
773 }
774
775 static int intel_pt_snapshot_start(struct auxtrace_record *itr)
776 {
777         struct intel_pt_recording *ptr =
778                         container_of(itr, struct intel_pt_recording, itr);
779         struct perf_evsel *evsel;
780
781         evlist__for_each_entry(ptr->evlist, evsel) {
782                 if (evsel->attr.type == ptr->intel_pt_pmu->type)
783                         return perf_evsel__disable(evsel);
784         }
785         return -EINVAL;
786 }
787
788 static int intel_pt_snapshot_finish(struct auxtrace_record *itr)
789 {
790         struct intel_pt_recording *ptr =
791                         container_of(itr, struct intel_pt_recording, itr);
792         struct perf_evsel *evsel;
793
794         evlist__for_each_entry(ptr->evlist, evsel) {
795                 if (evsel->attr.type == ptr->intel_pt_pmu->type)
796                         return perf_evsel__enable(evsel);
797         }
798         return -EINVAL;
799 }
800
801 static int intel_pt_alloc_snapshot_refs(struct intel_pt_recording *ptr, int idx)
802 {
803         const size_t sz = sizeof(struct intel_pt_snapshot_ref);
804         int cnt = ptr->snapshot_ref_cnt, new_cnt = cnt * 2;
805         struct intel_pt_snapshot_ref *refs;
806
807         if (!new_cnt)
808                 new_cnt = 16;
809
810         while (new_cnt <= idx)
811                 new_cnt *= 2;
812
813         refs = calloc(new_cnt, sz);
814         if (!refs)
815                 return -ENOMEM;
816
817         memcpy(refs, ptr->snapshot_refs, cnt * sz);
818
819         ptr->snapshot_refs = refs;
820         ptr->snapshot_ref_cnt = new_cnt;
821
822         return 0;
823 }
824
825 static void intel_pt_free_snapshot_refs(struct intel_pt_recording *ptr)
826 {
827         int i;
828
829         for (i = 0; i < ptr->snapshot_ref_cnt; i++)
830                 zfree(&ptr->snapshot_refs[i].ref_buf);
831         zfree(&ptr->snapshot_refs);
832 }
833
834 static void intel_pt_recording_free(struct auxtrace_record *itr)
835 {
836         struct intel_pt_recording *ptr =
837                         container_of(itr, struct intel_pt_recording, itr);
838
839         intel_pt_free_snapshot_refs(ptr);
840         free(ptr);
841 }
842
843 static int intel_pt_alloc_snapshot_ref(struct intel_pt_recording *ptr, int idx,
844                                        size_t snapshot_buf_size)
845 {
846         size_t ref_buf_size = ptr->snapshot_ref_buf_size;
847         void *ref_buf;
848
849         ref_buf = zalloc(ref_buf_size);
850         if (!ref_buf)
851                 return -ENOMEM;
852
853         ptr->snapshot_refs[idx].ref_buf = ref_buf;
854         ptr->snapshot_refs[idx].ref_offset = snapshot_buf_size - ref_buf_size;
855
856         return 0;
857 }
858
859 static size_t intel_pt_snapshot_ref_buf_size(struct intel_pt_recording *ptr,
860                                              size_t snapshot_buf_size)
861 {
862         const size_t max_size = 256 * 1024;
863         size_t buf_size = 0, psb_period;
864
865         if (ptr->snapshot_size <= 64 * 1024)
866                 return 0;
867
868         psb_period = intel_pt_psb_period(ptr->intel_pt_pmu, ptr->evlist);
869         if (psb_period)
870                 buf_size = psb_period * 2;
871
872         if (!buf_size || buf_size > max_size)
873                 buf_size = max_size;
874
875         if (buf_size >= snapshot_buf_size)
876                 return 0;
877
878         if (buf_size >= ptr->snapshot_size / 2)
879                 return 0;
880
881         return buf_size;
882 }
883
884 static int intel_pt_snapshot_init(struct intel_pt_recording *ptr,
885                                   size_t snapshot_buf_size)
886 {
887         if (ptr->snapshot_init_done)
888                 return 0;
889
890         ptr->snapshot_init_done = true;
891
892         ptr->snapshot_ref_buf_size = intel_pt_snapshot_ref_buf_size(ptr,
893                                                         snapshot_buf_size);
894
895         return 0;
896 }
897
898 /**
899  * intel_pt_compare_buffers - compare bytes in a buffer to a circular buffer.
900  * @buf1: first buffer
901  * @compare_size: number of bytes to compare
902  * @buf2: second buffer (a circular buffer)
903  * @offs2: offset in second buffer
904  * @buf2_size: size of second buffer
905  *
906  * The comparison allows for the possibility that the bytes to compare in the
907  * circular buffer are not contiguous.  It is assumed that @compare_size <=
908  * @buf2_size.  This function returns %false if the bytes are identical, %true
909  * otherwise.
910  */
911 static bool intel_pt_compare_buffers(void *buf1, size_t compare_size,
912                                      void *buf2, size_t offs2, size_t buf2_size)
913 {
914         size_t end2 = offs2 + compare_size, part_size;
915
916         if (end2 <= buf2_size)
917                 return memcmp(buf1, buf2 + offs2, compare_size);
918
919         part_size = end2 - buf2_size;
920         if (memcmp(buf1, buf2 + offs2, part_size))
921                 return true;
922
923         compare_size -= part_size;
924
925         return memcmp(buf1 + part_size, buf2, compare_size);
926 }
927
928 static bool intel_pt_compare_ref(void *ref_buf, size_t ref_offset,
929                                  size_t ref_size, size_t buf_size,
930                                  void *data, size_t head)
931 {
932         size_t ref_end = ref_offset + ref_size;
933
934         if (ref_end > buf_size) {
935                 if (head > ref_offset || head < ref_end - buf_size)
936                         return true;
937         } else if (head > ref_offset && head < ref_end) {
938                 return true;
939         }
940
941         return intel_pt_compare_buffers(ref_buf, ref_size, data, ref_offset,
942                                         buf_size);
943 }
944
945 static void intel_pt_copy_ref(void *ref_buf, size_t ref_size, size_t buf_size,
946                               void *data, size_t head)
947 {
948         if (head >= ref_size) {
949                 memcpy(ref_buf, data + head - ref_size, ref_size);
950         } else {
951                 memcpy(ref_buf, data, head);
952                 ref_size -= head;
953                 memcpy(ref_buf + head, data + buf_size - ref_size, ref_size);
954         }
955 }
956
957 static bool intel_pt_wrapped(struct intel_pt_recording *ptr, int idx,
958                              struct auxtrace_mmap *mm, unsigned char *data,
959                              u64 head)
960 {
961         struct intel_pt_snapshot_ref *ref = &ptr->snapshot_refs[idx];
962         bool wrapped;
963
964         wrapped = intel_pt_compare_ref(ref->ref_buf, ref->ref_offset,
965                                        ptr->snapshot_ref_buf_size, mm->len,
966                                        data, head);
967
968         intel_pt_copy_ref(ref->ref_buf, ptr->snapshot_ref_buf_size, mm->len,
969                           data, head);
970
971         return wrapped;
972 }
973
974 static bool intel_pt_first_wrap(u64 *data, size_t buf_size)
975 {
976         int i, a, b;
977
978         b = buf_size >> 3;
979         a = b - 512;
980         if (a < 0)
981                 a = 0;
982
983         for (i = a; i < b; i++) {
984                 if (data[i])
985                         return true;
986         }
987
988         return false;
989 }
990
991 static int intel_pt_find_snapshot(struct auxtrace_record *itr, int idx,
992                                   struct auxtrace_mmap *mm, unsigned char *data,
993                                   u64 *head, u64 *old)
994 {
995         struct intel_pt_recording *ptr =
996                         container_of(itr, struct intel_pt_recording, itr);
997         bool wrapped;
998         int err;
999
1000         pr_debug3("%s: mmap index %d old head %zu new head %zu\n",
1001                   __func__, idx, (size_t)*old, (size_t)*head);
1002
1003         err = intel_pt_snapshot_init(ptr, mm->len);
1004         if (err)
1005                 goto out_err;
1006
1007         if (idx >= ptr->snapshot_ref_cnt) {
1008                 err = intel_pt_alloc_snapshot_refs(ptr, idx);
1009                 if (err)
1010                         goto out_err;
1011         }
1012
1013         if (ptr->snapshot_ref_buf_size) {
1014                 if (!ptr->snapshot_refs[idx].ref_buf) {
1015                         err = intel_pt_alloc_snapshot_ref(ptr, idx, mm->len);
1016                         if (err)
1017                                 goto out_err;
1018                 }
1019                 wrapped = intel_pt_wrapped(ptr, idx, mm, data, *head);
1020         } else {
1021                 wrapped = ptr->snapshot_refs[idx].wrapped;
1022                 if (!wrapped && intel_pt_first_wrap((u64 *)data, mm->len)) {
1023                         ptr->snapshot_refs[idx].wrapped = true;
1024                         wrapped = true;
1025                 }
1026         }
1027
1028         /*
1029          * In full trace mode 'head' continually increases.  However in snapshot
1030          * mode 'head' is an offset within the buffer.  Here 'old' and 'head'
1031          * are adjusted to match the full trace case which expects that 'old' is
1032          * always less than 'head'.
1033          */
1034         if (wrapped) {
1035                 *old = *head;
1036                 *head += mm->len;
1037         } else {
1038                 if (mm->mask)
1039                         *old &= mm->mask;
1040                 else
1041                         *old %= mm->len;
1042                 if (*old > *head)
1043                         *head += mm->len;
1044         }
1045
1046         pr_debug3("%s: wrap-around %sdetected, adjusted old head %zu adjusted new head %zu\n",
1047                   __func__, wrapped ? "" : "not ", (size_t)*old, (size_t)*head);
1048
1049         return 0;
1050
1051 out_err:
1052         pr_err("%s: failed, error %d\n", __func__, err);
1053         return err;
1054 }
1055
1056 static u64 intel_pt_reference(struct auxtrace_record *itr __maybe_unused)
1057 {
1058         return rdtsc();
1059 }
1060
1061 static int intel_pt_read_finish(struct auxtrace_record *itr, int idx)
1062 {
1063         struct intel_pt_recording *ptr =
1064                         container_of(itr, struct intel_pt_recording, itr);
1065         struct perf_evsel *evsel;
1066
1067         evlist__for_each_entry(ptr->evlist, evsel) {
1068                 if (evsel->attr.type == ptr->intel_pt_pmu->type)
1069                         return perf_evlist__enable_event_idx(ptr->evlist, evsel,
1070                                                              idx);
1071         }
1072         return -EINVAL;
1073 }
1074
1075 struct auxtrace_record *intel_pt_recording_init(int *err)
1076 {
1077         struct perf_pmu *intel_pt_pmu = perf_pmu__find(INTEL_PT_PMU_NAME);
1078         struct intel_pt_recording *ptr;
1079
1080         if (!intel_pt_pmu)
1081                 return NULL;
1082
1083         if (setenv("JITDUMP_USE_ARCH_TIMESTAMP", "1", 1)) {
1084                 *err = -errno;
1085                 return NULL;
1086         }
1087
1088         ptr = zalloc(sizeof(struct intel_pt_recording));
1089         if (!ptr) {
1090                 *err = -ENOMEM;
1091                 return NULL;
1092         }
1093
1094         ptr->intel_pt_pmu = intel_pt_pmu;
1095         ptr->itr.recording_options = intel_pt_recording_options;
1096         ptr->itr.info_priv_size = intel_pt_info_priv_size;
1097         ptr->itr.info_fill = intel_pt_info_fill;
1098         ptr->itr.free = intel_pt_recording_free;
1099         ptr->itr.snapshot_start = intel_pt_snapshot_start;
1100         ptr->itr.snapshot_finish = intel_pt_snapshot_finish;
1101         ptr->itr.find_snapshot = intel_pt_find_snapshot;
1102         ptr->itr.parse_snapshot_options = intel_pt_parse_snapshot_options;
1103         ptr->itr.reference = intel_pt_reference;
1104         ptr->itr.read_finish = intel_pt_read_finish;
1105         return &ptr->itr;
1106 }