GNU Linux-libre 5.15.137-gnu
[releases.git] / arch / x86 / events / intel / pt.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Intel(R) Processor Trace PMU driver for perf
4  * Copyright (c) 2013-2014, Intel Corporation.
5  *
6  * Intel PT is specified in the Intel Architecture Instruction Set Extensions
7  * Programming Reference:
8  * http://software.intel.com/en-us/intel-isa-extensions
9  */
10
11 #undef DEBUG
12
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
15 #include <linux/types.h>
16 #include <linux/bits.h>
17 #include <linux/limits.h>
18 #include <linux/slab.h>
19 #include <linux/device.h>
20
21 #include <asm/perf_event.h>
22 #include <asm/insn.h>
23 #include <asm/io.h>
24 #include <asm/intel_pt.h>
25 #include <asm/intel-family.h>
26
27 #include "../perf_event.h"
28 #include "pt.h"
29
30 static DEFINE_PER_CPU(struct pt, pt_ctx);
31
32 static struct pt_pmu pt_pmu;
33
34 /*
35  * Capabilities of Intel PT hardware, such as number of address bits or
36  * supported output schemes, are cached and exported to userspace as "caps"
37  * attribute group of pt pmu device
38  * (/sys/bus/event_source/devices/intel_pt/caps/) so that userspace can store
39  * relevant bits together with intel_pt traces.
40  *
41  * These are necessary for both trace decoding (payloads_lip, contains address
42  * width encoded in IP-related packets), and event configuration (bitmasks with
43  * permitted values for certain bit fields).
44  */
45 #define PT_CAP(_n, _l, _r, _m)                                          \
46         [PT_CAP_ ## _n] = { .name = __stringify(_n), .leaf = _l,        \
47                             .reg = _r, .mask = _m }
48
49 static struct pt_cap_desc {
50         const char      *name;
51         u32             leaf;
52         u8              reg;
53         u32             mask;
54 } pt_caps[] = {
55         PT_CAP(max_subleaf,             0, CPUID_EAX, 0xffffffff),
56         PT_CAP(cr3_filtering,           0, CPUID_EBX, BIT(0)),
57         PT_CAP(psb_cyc,                 0, CPUID_EBX, BIT(1)),
58         PT_CAP(ip_filtering,            0, CPUID_EBX, BIT(2)),
59         PT_CAP(mtc,                     0, CPUID_EBX, BIT(3)),
60         PT_CAP(ptwrite,                 0, CPUID_EBX, BIT(4)),
61         PT_CAP(power_event_trace,       0, CPUID_EBX, BIT(5)),
62         PT_CAP(topa_output,             0, CPUID_ECX, BIT(0)),
63         PT_CAP(topa_multiple_entries,   0, CPUID_ECX, BIT(1)),
64         PT_CAP(single_range_output,     0, CPUID_ECX, BIT(2)),
65         PT_CAP(output_subsys,           0, CPUID_ECX, BIT(3)),
66         PT_CAP(payloads_lip,            0, CPUID_ECX, BIT(31)),
67         PT_CAP(num_address_ranges,      1, CPUID_EAX, 0x7),
68         PT_CAP(mtc_periods,             1, CPUID_EAX, 0xffff0000),
69         PT_CAP(cycle_thresholds,        1, CPUID_EBX, 0xffff),
70         PT_CAP(psb_periods,             1, CPUID_EBX, 0xffff0000),
71 };
72
73 u32 intel_pt_validate_cap(u32 *caps, enum pt_capabilities capability)
74 {
75         struct pt_cap_desc *cd = &pt_caps[capability];
76         u32 c = caps[cd->leaf * PT_CPUID_REGS_NUM + cd->reg];
77         unsigned int shift = __ffs(cd->mask);
78
79         return (c & cd->mask) >> shift;
80 }
81 EXPORT_SYMBOL_GPL(intel_pt_validate_cap);
82
83 u32 intel_pt_validate_hw_cap(enum pt_capabilities cap)
84 {
85         return intel_pt_validate_cap(pt_pmu.caps, cap);
86 }
87 EXPORT_SYMBOL_GPL(intel_pt_validate_hw_cap);
88
89 static ssize_t pt_cap_show(struct device *cdev,
90                            struct device_attribute *attr,
91                            char *buf)
92 {
93         struct dev_ext_attribute *ea =
94                 container_of(attr, struct dev_ext_attribute, attr);
95         enum pt_capabilities cap = (long)ea->var;
96
97         return snprintf(buf, PAGE_SIZE, "%x\n", intel_pt_validate_hw_cap(cap));
98 }
99
100 static struct attribute_group pt_cap_group __ro_after_init = {
101         .name   = "caps",
102 };
103
104 PMU_FORMAT_ATTR(pt,             "config:0"      );
105 PMU_FORMAT_ATTR(cyc,            "config:1"      );
106 PMU_FORMAT_ATTR(pwr_evt,        "config:4"      );
107 PMU_FORMAT_ATTR(fup_on_ptw,     "config:5"      );
108 PMU_FORMAT_ATTR(mtc,            "config:9"      );
109 PMU_FORMAT_ATTR(tsc,            "config:10"     );
110 PMU_FORMAT_ATTR(noretcomp,      "config:11"     );
111 PMU_FORMAT_ATTR(ptw,            "config:12"     );
112 PMU_FORMAT_ATTR(branch,         "config:13"     );
113 PMU_FORMAT_ATTR(mtc_period,     "config:14-17"  );
114 PMU_FORMAT_ATTR(cyc_thresh,     "config:19-22"  );
115 PMU_FORMAT_ATTR(psb_period,     "config:24-27"  );
116
117 static struct attribute *pt_formats_attr[] = {
118         &format_attr_pt.attr,
119         &format_attr_cyc.attr,
120         &format_attr_pwr_evt.attr,
121         &format_attr_fup_on_ptw.attr,
122         &format_attr_mtc.attr,
123         &format_attr_tsc.attr,
124         &format_attr_noretcomp.attr,
125         &format_attr_ptw.attr,
126         &format_attr_branch.attr,
127         &format_attr_mtc_period.attr,
128         &format_attr_cyc_thresh.attr,
129         &format_attr_psb_period.attr,
130         NULL,
131 };
132
133 static struct attribute_group pt_format_group = {
134         .name   = "format",
135         .attrs  = pt_formats_attr,
136 };
137
138 static ssize_t
139 pt_timing_attr_show(struct device *dev, struct device_attribute *attr,
140                     char *page)
141 {
142         struct perf_pmu_events_attr *pmu_attr =
143                 container_of(attr, struct perf_pmu_events_attr, attr);
144
145         switch (pmu_attr->id) {
146         case 0:
147                 return sprintf(page, "%lu\n", pt_pmu.max_nonturbo_ratio);
148         case 1:
149                 return sprintf(page, "%u:%u\n",
150                                pt_pmu.tsc_art_num,
151                                pt_pmu.tsc_art_den);
152         default:
153                 break;
154         }
155
156         return -EINVAL;
157 }
158
159 PMU_EVENT_ATTR(max_nonturbo_ratio, timing_attr_max_nonturbo_ratio, 0,
160                pt_timing_attr_show);
161 PMU_EVENT_ATTR(tsc_art_ratio, timing_attr_tsc_art_ratio, 1,
162                pt_timing_attr_show);
163
164 static struct attribute *pt_timing_attr[] = {
165         &timing_attr_max_nonturbo_ratio.attr.attr,
166         &timing_attr_tsc_art_ratio.attr.attr,
167         NULL,
168 };
169
170 static struct attribute_group pt_timing_group = {
171         .attrs  = pt_timing_attr,
172 };
173
174 static const struct attribute_group *pt_attr_groups[] = {
175         &pt_cap_group,
176         &pt_format_group,
177         &pt_timing_group,
178         NULL,
179 };
180
181 static int __init pt_pmu_hw_init(void)
182 {
183         struct dev_ext_attribute *de_attrs;
184         struct attribute **attrs;
185         size_t size;
186         u64 reg;
187         int ret;
188         long i;
189
190         rdmsrl(MSR_PLATFORM_INFO, reg);
191         pt_pmu.max_nonturbo_ratio = (reg & 0xff00) >> 8;
192
193         /*
194          * if available, read in TSC to core crystal clock ratio,
195          * otherwise, zero for numerator stands for "not enumerated"
196          * as per SDM
197          */
198         if (boot_cpu_data.cpuid_level >= CPUID_TSC_LEAF) {
199                 u32 eax, ebx, ecx, edx;
200
201                 cpuid(CPUID_TSC_LEAF, &eax, &ebx, &ecx, &edx);
202
203                 pt_pmu.tsc_art_num = ebx;
204                 pt_pmu.tsc_art_den = eax;
205         }
206
207         /* model-specific quirks */
208         switch (boot_cpu_data.x86_model) {
209         case INTEL_FAM6_BROADWELL:
210         case INTEL_FAM6_BROADWELL_D:
211         case INTEL_FAM6_BROADWELL_G:
212         case INTEL_FAM6_BROADWELL_X:
213                 /* not setting BRANCH_EN will #GP, erratum BDM106 */
214                 pt_pmu.branch_en_always_on = true;
215                 break;
216         default:
217                 break;
218         }
219
220         if (boot_cpu_has(X86_FEATURE_VMX)) {
221                 /*
222                  * Intel SDM, 36.5 "Tracing post-VMXON" says that
223                  * "IA32_VMX_MISC[bit 14]" being 1 means PT can trace
224                  * post-VMXON.
225                  */
226                 rdmsrl(MSR_IA32_VMX_MISC, reg);
227                 if (reg & BIT(14))
228                         pt_pmu.vmx = true;
229         }
230
231         for (i = 0; i < PT_CPUID_LEAVES; i++) {
232                 cpuid_count(20, i,
233                             &pt_pmu.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM],
234                             &pt_pmu.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM],
235                             &pt_pmu.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM],
236                             &pt_pmu.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM]);
237         }
238
239         ret = -ENOMEM;
240         size = sizeof(struct attribute *) * (ARRAY_SIZE(pt_caps)+1);
241         attrs = kzalloc(size, GFP_KERNEL);
242         if (!attrs)
243                 goto fail;
244
245         size = sizeof(struct dev_ext_attribute) * (ARRAY_SIZE(pt_caps)+1);
246         de_attrs = kzalloc(size, GFP_KERNEL);
247         if (!de_attrs)
248                 goto fail;
249
250         for (i = 0; i < ARRAY_SIZE(pt_caps); i++) {
251                 struct dev_ext_attribute *de_attr = de_attrs + i;
252
253                 de_attr->attr.attr.name = pt_caps[i].name;
254
255                 sysfs_attr_init(&de_attr->attr.attr);
256
257                 de_attr->attr.attr.mode         = S_IRUGO;
258                 de_attr->attr.show              = pt_cap_show;
259                 de_attr->var                    = (void *)i;
260
261                 attrs[i] = &de_attr->attr.attr;
262         }
263
264         pt_cap_group.attrs = attrs;
265
266         return 0;
267
268 fail:
269         kfree(attrs);
270
271         return ret;
272 }
273
274 #define RTIT_CTL_CYC_PSB (RTIT_CTL_CYCLEACC     | \
275                           RTIT_CTL_CYC_THRESH   | \
276                           RTIT_CTL_PSB_FREQ)
277
278 #define RTIT_CTL_MTC    (RTIT_CTL_MTC_EN        | \
279                          RTIT_CTL_MTC_RANGE)
280
281 #define RTIT_CTL_PTW    (RTIT_CTL_PTW_EN        | \
282                          RTIT_CTL_FUP_ON_PTW)
283
284 /*
285  * Bit 0 (TraceEn) in the attr.config is meaningless as the
286  * corresponding bit in the RTIT_CTL can only be controlled
287  * by the driver; therefore, repurpose it to mean: pass
288  * through the bit that was previously assumed to be always
289  * on for PT, thereby allowing the user to *not* set it if
290  * they so wish. See also pt_event_valid() and pt_config().
291  */
292 #define RTIT_CTL_PASSTHROUGH RTIT_CTL_TRACEEN
293
294 #define PT_CONFIG_MASK (RTIT_CTL_TRACEEN        | \
295                         RTIT_CTL_TSC_EN         | \
296                         RTIT_CTL_DISRETC        | \
297                         RTIT_CTL_BRANCH_EN      | \
298                         RTIT_CTL_CYC_PSB        | \
299                         RTIT_CTL_MTC            | \
300                         RTIT_CTL_PWR_EVT_EN     | \
301                         RTIT_CTL_FUP_ON_PTW     | \
302                         RTIT_CTL_PTW_EN)
303
304 static bool pt_event_valid(struct perf_event *event)
305 {
306         u64 config = event->attr.config;
307         u64 allowed, requested;
308
309         if ((config & PT_CONFIG_MASK) != config)
310                 return false;
311
312         if (config & RTIT_CTL_CYC_PSB) {
313                 if (!intel_pt_validate_hw_cap(PT_CAP_psb_cyc))
314                         return false;
315
316                 allowed = intel_pt_validate_hw_cap(PT_CAP_psb_periods);
317                 requested = (config & RTIT_CTL_PSB_FREQ) >>
318                         RTIT_CTL_PSB_FREQ_OFFSET;
319                 if (requested && (!(allowed & BIT(requested))))
320                         return false;
321
322                 allowed = intel_pt_validate_hw_cap(PT_CAP_cycle_thresholds);
323                 requested = (config & RTIT_CTL_CYC_THRESH) >>
324                         RTIT_CTL_CYC_THRESH_OFFSET;
325                 if (requested && (!(allowed & BIT(requested))))
326                         return false;
327         }
328
329         if (config & RTIT_CTL_MTC) {
330                 /*
331                  * In the unlikely case that CPUID lists valid mtc periods,
332                  * but not the mtc capability, drop out here.
333                  *
334                  * Spec says that setting mtc period bits while mtc bit in
335                  * CPUID is 0 will #GP, so better safe than sorry.
336                  */
337                 if (!intel_pt_validate_hw_cap(PT_CAP_mtc))
338                         return false;
339
340                 allowed = intel_pt_validate_hw_cap(PT_CAP_mtc_periods);
341                 if (!allowed)
342                         return false;
343
344                 requested = (config & RTIT_CTL_MTC_RANGE) >>
345                         RTIT_CTL_MTC_RANGE_OFFSET;
346
347                 if (!(allowed & BIT(requested)))
348                         return false;
349         }
350
351         if (config & RTIT_CTL_PWR_EVT_EN &&
352             !intel_pt_validate_hw_cap(PT_CAP_power_event_trace))
353                 return false;
354
355         if (config & RTIT_CTL_PTW) {
356                 if (!intel_pt_validate_hw_cap(PT_CAP_ptwrite))
357                         return false;
358
359                 /* FUPonPTW without PTW doesn't make sense */
360                 if ((config & RTIT_CTL_FUP_ON_PTW) &&
361                     !(config & RTIT_CTL_PTW_EN))
362                         return false;
363         }
364
365         /*
366          * Setting bit 0 (TraceEn in RTIT_CTL MSR) in the attr.config
367          * clears the assumption that BranchEn must always be enabled,
368          * as was the case with the first implementation of PT.
369          * If this bit is not set, the legacy behavior is preserved
370          * for compatibility with the older userspace.
371          *
372          * Re-using bit 0 for this purpose is fine because it is never
373          * directly set by the user; previous attempts at setting it in
374          * the attr.config resulted in -EINVAL.
375          */
376         if (config & RTIT_CTL_PASSTHROUGH) {
377                 /*
378                  * Disallow not setting BRANCH_EN where BRANCH_EN is
379                  * always required.
380                  */
381                 if (pt_pmu.branch_en_always_on &&
382                     !(config & RTIT_CTL_BRANCH_EN))
383                         return false;
384         } else {
385                 /*
386                  * Disallow BRANCH_EN without the PASSTHROUGH.
387                  */
388                 if (config & RTIT_CTL_BRANCH_EN)
389                         return false;
390         }
391
392         return true;
393 }
394
395 /*
396  * PT configuration helpers
397  * These all are cpu affine and operate on a local PT
398  */
399
400 static void pt_config_start(struct perf_event *event)
401 {
402         struct pt *pt = this_cpu_ptr(&pt_ctx);
403         u64 ctl = event->hw.config;
404
405         ctl |= RTIT_CTL_TRACEEN;
406         if (READ_ONCE(pt->vmx_on))
407                 perf_aux_output_flag(&pt->handle, PERF_AUX_FLAG_PARTIAL);
408         else
409                 wrmsrl(MSR_IA32_RTIT_CTL, ctl);
410
411         WRITE_ONCE(event->hw.config, ctl);
412 }
413
414 /* Address ranges and their corresponding msr configuration registers */
415 static const struct pt_address_range {
416         unsigned long   msr_a;
417         unsigned long   msr_b;
418         unsigned int    reg_off;
419 } pt_address_ranges[] = {
420         {
421                 .msr_a   = MSR_IA32_RTIT_ADDR0_A,
422                 .msr_b   = MSR_IA32_RTIT_ADDR0_B,
423                 .reg_off = RTIT_CTL_ADDR0_OFFSET,
424         },
425         {
426                 .msr_a   = MSR_IA32_RTIT_ADDR1_A,
427                 .msr_b   = MSR_IA32_RTIT_ADDR1_B,
428                 .reg_off = RTIT_CTL_ADDR1_OFFSET,
429         },
430         {
431                 .msr_a   = MSR_IA32_RTIT_ADDR2_A,
432                 .msr_b   = MSR_IA32_RTIT_ADDR2_B,
433                 .reg_off = RTIT_CTL_ADDR2_OFFSET,
434         },
435         {
436                 .msr_a   = MSR_IA32_RTIT_ADDR3_A,
437                 .msr_b   = MSR_IA32_RTIT_ADDR3_B,
438                 .reg_off = RTIT_CTL_ADDR3_OFFSET,
439         }
440 };
441
442 static u64 pt_config_filters(struct perf_event *event)
443 {
444         struct pt_filters *filters = event->hw.addr_filters;
445         struct pt *pt = this_cpu_ptr(&pt_ctx);
446         unsigned int range = 0;
447         u64 rtit_ctl = 0;
448
449         if (!filters)
450                 return 0;
451
452         perf_event_addr_filters_sync(event);
453
454         for (range = 0; range < filters->nr_filters; range++) {
455                 struct pt_filter *filter = &filters->filter[range];
456
457                 /*
458                  * Note, if the range has zero start/end addresses due
459                  * to its dynamic object not being loaded yet, we just
460                  * go ahead and program zeroed range, which will simply
461                  * produce no data. Note^2: if executable code at 0x0
462                  * is a concern, we can set up an "invalid" configuration
463                  * such as msr_b < msr_a.
464                  */
465
466                 /* avoid redundant msr writes */
467                 if (pt->filters.filter[range].msr_a != filter->msr_a) {
468                         wrmsrl(pt_address_ranges[range].msr_a, filter->msr_a);
469                         pt->filters.filter[range].msr_a = filter->msr_a;
470                 }
471
472                 if (pt->filters.filter[range].msr_b != filter->msr_b) {
473                         wrmsrl(pt_address_ranges[range].msr_b, filter->msr_b);
474                         pt->filters.filter[range].msr_b = filter->msr_b;
475                 }
476
477                 rtit_ctl |= (u64)filter->config << pt_address_ranges[range].reg_off;
478         }
479
480         return rtit_ctl;
481 }
482
483 static void pt_config(struct perf_event *event)
484 {
485         struct pt *pt = this_cpu_ptr(&pt_ctx);
486         struct pt_buffer *buf = perf_get_aux(&pt->handle);
487         u64 reg;
488
489         /* First round: clear STATUS, in particular the PSB byte counter. */
490         if (!event->hw.config) {
491                 perf_event_itrace_started(event);
492                 wrmsrl(MSR_IA32_RTIT_STATUS, 0);
493         }
494
495         reg = pt_config_filters(event);
496         reg |= RTIT_CTL_TRACEEN;
497         if (!buf->single)
498                 reg |= RTIT_CTL_TOPA;
499
500         /*
501          * Previously, we had BRANCH_EN on by default, but now that PT has
502          * grown features outside of branch tracing, it is useful to allow
503          * the user to disable it. Setting bit 0 in the event's attr.config
504          * allows BRANCH_EN to pass through instead of being always on. See
505          * also the comment in pt_event_valid().
506          */
507         if (event->attr.config & BIT(0)) {
508                 reg |= event->attr.config & RTIT_CTL_BRANCH_EN;
509         } else {
510                 reg |= RTIT_CTL_BRANCH_EN;
511         }
512
513         if (!event->attr.exclude_kernel)
514                 reg |= RTIT_CTL_OS;
515         if (!event->attr.exclude_user)
516                 reg |= RTIT_CTL_USR;
517
518         reg |= (event->attr.config & PT_CONFIG_MASK);
519
520         event->hw.config = reg;
521         pt_config_start(event);
522 }
523
524 static void pt_config_stop(struct perf_event *event)
525 {
526         struct pt *pt = this_cpu_ptr(&pt_ctx);
527         u64 ctl = READ_ONCE(event->hw.config);
528
529         /* may be already stopped by a PMI */
530         if (!(ctl & RTIT_CTL_TRACEEN))
531                 return;
532
533         ctl &= ~RTIT_CTL_TRACEEN;
534         if (!READ_ONCE(pt->vmx_on))
535                 wrmsrl(MSR_IA32_RTIT_CTL, ctl);
536
537         WRITE_ONCE(event->hw.config, ctl);
538
539         /*
540          * A wrmsr that disables trace generation serializes other PT
541          * registers and causes all data packets to be written to memory,
542          * but a fence is required for the data to become globally visible.
543          *
544          * The below WMB, separating data store and aux_head store matches
545          * the consumer's RMB that separates aux_head load and data load.
546          */
547         wmb();
548 }
549
550 /**
551  * struct topa - ToPA metadata
552  * @list:       linkage to struct pt_buffer's list of tables
553  * @offset:     offset of the first entry in this table in the buffer
554  * @size:       total size of all entries in this table
555  * @last:       index of the last initialized entry in this table
556  * @z_count:    how many times the first entry repeats
557  */
558 struct topa {
559         struct list_head        list;
560         u64                     offset;
561         size_t                  size;
562         int                     last;
563         unsigned int            z_count;
564 };
565
566 /*
567  * Keep ToPA table-related metadata on the same page as the actual table,
568  * taking up a few words from the top
569  */
570
571 #define TENTS_PER_PAGE  \
572         ((PAGE_SIZE - sizeof(struct topa)) / sizeof(struct topa_entry))
573
574 /**
575  * struct topa_page - page-sized ToPA table with metadata at the top
576  * @table:      actual ToPA table entries, as understood by PT hardware
577  * @topa:       metadata
578  */
579 struct topa_page {
580         struct topa_entry       table[TENTS_PER_PAGE];
581         struct topa             topa;
582 };
583
584 static inline struct topa_page *topa_to_page(struct topa *topa)
585 {
586         return container_of(topa, struct topa_page, topa);
587 }
588
589 static inline struct topa_page *topa_entry_to_page(struct topa_entry *te)
590 {
591         return (struct topa_page *)((unsigned long)te & PAGE_MASK);
592 }
593
594 static inline phys_addr_t topa_pfn(struct topa *topa)
595 {
596         return PFN_DOWN(virt_to_phys(topa_to_page(topa)));
597 }
598
599 /* make -1 stand for the last table entry */
600 #define TOPA_ENTRY(t, i)                                \
601         ((i) == -1                                      \
602                 ? &topa_to_page(t)->table[(t)->last]    \
603                 : &topa_to_page(t)->table[(i)])
604 #define TOPA_ENTRY_SIZE(t, i) (sizes(TOPA_ENTRY((t), (i))->size))
605 #define TOPA_ENTRY_PAGES(t, i) (1 << TOPA_ENTRY((t), (i))->size)
606
607 static void pt_config_buffer(struct pt_buffer *buf)
608 {
609         struct pt *pt = this_cpu_ptr(&pt_ctx);
610         u64 reg, mask;
611         void *base;
612
613         if (buf->single) {
614                 base = buf->data_pages[0];
615                 mask = (buf->nr_pages * PAGE_SIZE - 1) >> 7;
616         } else {
617                 base = topa_to_page(buf->cur)->table;
618                 mask = (u64)buf->cur_idx;
619         }
620
621         reg = virt_to_phys(base);
622         if (pt->output_base != reg) {
623                 pt->output_base = reg;
624                 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, reg);
625         }
626
627         reg = 0x7f | (mask << 7) | ((u64)buf->output_off << 32);
628         if (pt->output_mask != reg) {
629                 pt->output_mask = reg;
630                 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, reg);
631         }
632 }
633
634 /**
635  * topa_alloc() - allocate page-sized ToPA table
636  * @cpu:        CPU on which to allocate.
637  * @gfp:        Allocation flags.
638  *
639  * Return:      On success, return the pointer to ToPA table page.
640  */
641 static struct topa *topa_alloc(int cpu, gfp_t gfp)
642 {
643         int node = cpu_to_node(cpu);
644         struct topa_page *tp;
645         struct page *p;
646
647         p = alloc_pages_node(node, gfp | __GFP_ZERO, 0);
648         if (!p)
649                 return NULL;
650
651         tp = page_address(p);
652         tp->topa.last = 0;
653
654         /*
655          * In case of singe-entry ToPA, always put the self-referencing END
656          * link as the 2nd entry in the table
657          */
658         if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) {
659                 TOPA_ENTRY(&tp->topa, 1)->base = page_to_phys(p) >> TOPA_SHIFT;
660                 TOPA_ENTRY(&tp->topa, 1)->end = 1;
661         }
662
663         return &tp->topa;
664 }
665
666 /**
667  * topa_free() - free a page-sized ToPA table
668  * @topa:       Table to deallocate.
669  */
670 static void topa_free(struct topa *topa)
671 {
672         free_page((unsigned long)topa);
673 }
674
675 /**
676  * topa_insert_table() - insert a ToPA table into a buffer
677  * @buf:         PT buffer that's being extended.
678  * @topa:        New topa table to be inserted.
679  *
680  * If it's the first table in this buffer, set up buffer's pointers
681  * accordingly; otherwise, add a END=1 link entry to @topa to the current
682  * "last" table and adjust the last table pointer to @topa.
683  */
684 static void topa_insert_table(struct pt_buffer *buf, struct topa *topa)
685 {
686         struct topa *last = buf->last;
687
688         list_add_tail(&topa->list, &buf->tables);
689
690         if (!buf->first) {
691                 buf->first = buf->last = buf->cur = topa;
692                 return;
693         }
694
695         topa->offset = last->offset + last->size;
696         buf->last = topa;
697
698         if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries))
699                 return;
700
701         BUG_ON(last->last != TENTS_PER_PAGE - 1);
702
703         TOPA_ENTRY(last, -1)->base = topa_pfn(topa);
704         TOPA_ENTRY(last, -1)->end = 1;
705 }
706
707 /**
708  * topa_table_full() - check if a ToPA table is filled up
709  * @topa:       ToPA table.
710  */
711 static bool topa_table_full(struct topa *topa)
712 {
713         /* single-entry ToPA is a special case */
714         if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries))
715                 return !!topa->last;
716
717         return topa->last == TENTS_PER_PAGE - 1;
718 }
719
720 /**
721  * topa_insert_pages() - create a list of ToPA tables
722  * @buf:        PT buffer being initialized.
723  * @gfp:        Allocation flags.
724  *
725  * This initializes a list of ToPA tables with entries from
726  * the data_pages provided by rb_alloc_aux().
727  *
728  * Return:      0 on success or error code.
729  */
730 static int topa_insert_pages(struct pt_buffer *buf, int cpu, gfp_t gfp)
731 {
732         struct topa *topa = buf->last;
733         int order = 0;
734         struct page *p;
735
736         p = virt_to_page(buf->data_pages[buf->nr_pages]);
737         if (PagePrivate(p))
738                 order = page_private(p);
739
740         if (topa_table_full(topa)) {
741                 topa = topa_alloc(cpu, gfp);
742                 if (!topa)
743                         return -ENOMEM;
744
745                 topa_insert_table(buf, topa);
746         }
747
748         if (topa->z_count == topa->last - 1) {
749                 if (order == TOPA_ENTRY(topa, topa->last - 1)->size)
750                         topa->z_count++;
751         }
752
753         TOPA_ENTRY(topa, -1)->base = page_to_phys(p) >> TOPA_SHIFT;
754         TOPA_ENTRY(topa, -1)->size = order;
755         if (!buf->snapshot &&
756             !intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) {
757                 TOPA_ENTRY(topa, -1)->intr = 1;
758                 TOPA_ENTRY(topa, -1)->stop = 1;
759         }
760
761         topa->last++;
762         topa->size += sizes(order);
763
764         buf->nr_pages += 1ul << order;
765
766         return 0;
767 }
768
769 /**
770  * pt_topa_dump() - print ToPA tables and their entries
771  * @buf:        PT buffer.
772  */
773 static void pt_topa_dump(struct pt_buffer *buf)
774 {
775         struct topa *topa;
776
777         list_for_each_entry(topa, &buf->tables, list) {
778                 struct topa_page *tp = topa_to_page(topa);
779                 int i;
780
781                 pr_debug("# table @%p, off %llx size %zx\n", tp->table,
782                          topa->offset, topa->size);
783                 for (i = 0; i < TENTS_PER_PAGE; i++) {
784                         pr_debug("# entry @%p (%lx sz %u %c%c%c) raw=%16llx\n",
785                                  &tp->table[i],
786                                  (unsigned long)tp->table[i].base << TOPA_SHIFT,
787                                  sizes(tp->table[i].size),
788                                  tp->table[i].end ?  'E' : ' ',
789                                  tp->table[i].intr ? 'I' : ' ',
790                                  tp->table[i].stop ? 'S' : ' ',
791                                  *(u64 *)&tp->table[i]);
792                         if ((intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries) &&
793                              tp->table[i].stop) ||
794                             tp->table[i].end)
795                                 break;
796                         if (!i && topa->z_count)
797                                 i += topa->z_count;
798                 }
799         }
800 }
801
802 /**
803  * pt_buffer_advance() - advance to the next output region
804  * @buf:        PT buffer.
805  *
806  * Advance the current pointers in the buffer to the next ToPA entry.
807  */
808 static void pt_buffer_advance(struct pt_buffer *buf)
809 {
810         buf->output_off = 0;
811         buf->cur_idx++;
812
813         if (buf->cur_idx == buf->cur->last) {
814                 if (buf->cur == buf->last)
815                         buf->cur = buf->first;
816                 else
817                         buf->cur = list_entry(buf->cur->list.next, struct topa,
818                                               list);
819                 buf->cur_idx = 0;
820         }
821 }
822
823 /**
824  * pt_update_head() - calculate current offsets and sizes
825  * @pt:         Per-cpu pt context.
826  *
827  * Update buffer's current write pointer position and data size.
828  */
829 static void pt_update_head(struct pt *pt)
830 {
831         struct pt_buffer *buf = perf_get_aux(&pt->handle);
832         u64 topa_idx, base, old;
833
834         if (buf->single) {
835                 local_set(&buf->data_size, buf->output_off);
836                 return;
837         }
838
839         /* offset of the first region in this table from the beginning of buf */
840         base = buf->cur->offset + buf->output_off;
841
842         /* offset of the current output region within this table */
843         for (topa_idx = 0; topa_idx < buf->cur_idx; topa_idx++)
844                 base += TOPA_ENTRY_SIZE(buf->cur, topa_idx);
845
846         if (buf->snapshot) {
847                 local_set(&buf->data_size, base);
848         } else {
849                 old = (local64_xchg(&buf->head, base) &
850                        ((buf->nr_pages << PAGE_SHIFT) - 1));
851                 if (base < old)
852                         base += buf->nr_pages << PAGE_SHIFT;
853
854                 local_add(base - old, &buf->data_size);
855         }
856 }
857
858 /**
859  * pt_buffer_region() - obtain current output region's address
860  * @buf:        PT buffer.
861  */
862 static void *pt_buffer_region(struct pt_buffer *buf)
863 {
864         return phys_to_virt(TOPA_ENTRY(buf->cur, buf->cur_idx)->base << TOPA_SHIFT);
865 }
866
867 /**
868  * pt_buffer_region_size() - obtain current output region's size
869  * @buf:        PT buffer.
870  */
871 static size_t pt_buffer_region_size(struct pt_buffer *buf)
872 {
873         return TOPA_ENTRY_SIZE(buf->cur, buf->cur_idx);
874 }
875
876 /**
877  * pt_handle_status() - take care of possible status conditions
878  * @pt:         Per-cpu pt context.
879  */
880 static void pt_handle_status(struct pt *pt)
881 {
882         struct pt_buffer *buf = perf_get_aux(&pt->handle);
883         int advance = 0;
884         u64 status;
885
886         rdmsrl(MSR_IA32_RTIT_STATUS, status);
887
888         if (status & RTIT_STATUS_ERROR) {
889                 pr_err_ratelimited("ToPA ERROR encountered, trying to recover\n");
890                 pt_topa_dump(buf);
891                 status &= ~RTIT_STATUS_ERROR;
892         }
893
894         if (status & RTIT_STATUS_STOPPED) {
895                 status &= ~RTIT_STATUS_STOPPED;
896
897                 /*
898                  * On systems that only do single-entry ToPA, hitting STOP
899                  * means we are already losing data; need to let the decoder
900                  * know.
901                  */
902                 if (!buf->single &&
903                     (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries) ||
904                      buf->output_off == pt_buffer_region_size(buf))) {
905                         perf_aux_output_flag(&pt->handle,
906                                              PERF_AUX_FLAG_TRUNCATED);
907                         advance++;
908                 }
909         }
910
911         /*
912          * Also on single-entry ToPA implementations, interrupt will come
913          * before the output reaches its output region's boundary.
914          */
915         if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries) &&
916             !buf->snapshot &&
917             pt_buffer_region_size(buf) - buf->output_off <= TOPA_PMI_MARGIN) {
918                 void *head = pt_buffer_region(buf);
919
920                 /* everything within this margin needs to be zeroed out */
921                 memset(head + buf->output_off, 0,
922                        pt_buffer_region_size(buf) -
923                        buf->output_off);
924                 advance++;
925         }
926
927         if (advance)
928                 pt_buffer_advance(buf);
929
930         wrmsrl(MSR_IA32_RTIT_STATUS, status);
931 }
932
933 /**
934  * pt_read_offset() - translate registers into buffer pointers
935  * @buf:        PT buffer.
936  *
937  * Set buffer's output pointers from MSR values.
938  */
939 static void pt_read_offset(struct pt_buffer *buf)
940 {
941         struct pt *pt = this_cpu_ptr(&pt_ctx);
942         struct topa_page *tp;
943
944         if (!buf->single) {
945                 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, pt->output_base);
946                 tp = phys_to_virt(pt->output_base);
947                 buf->cur = &tp->topa;
948         }
949
950         rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, pt->output_mask);
951         /* offset within current output region */
952         buf->output_off = pt->output_mask >> 32;
953         /* index of current output region within this table */
954         if (!buf->single)
955                 buf->cur_idx = (pt->output_mask & 0xffffff80) >> 7;
956 }
957
958 static struct topa_entry *
959 pt_topa_entry_for_page(struct pt_buffer *buf, unsigned int pg)
960 {
961         struct topa_page *tp;
962         struct topa *topa;
963         unsigned int idx, cur_pg = 0, z_pg = 0, start_idx = 0;
964
965         /*
966          * Indicates a bug in the caller.
967          */
968         if (WARN_ON_ONCE(pg >= buf->nr_pages))
969                 return NULL;
970
971         /*
972          * First, find the ToPA table where @pg fits. With high
973          * order allocations, there shouldn't be many of these.
974          */
975         list_for_each_entry(topa, &buf->tables, list) {
976                 if (topa->offset + topa->size > pg << PAGE_SHIFT)
977                         goto found;
978         }
979
980         /*
981          * Hitting this means we have a problem in the ToPA
982          * allocation code.
983          */
984         WARN_ON_ONCE(1);
985
986         return NULL;
987
988 found:
989         /*
990          * Indicates a problem in the ToPA allocation code.
991          */
992         if (WARN_ON_ONCE(topa->last == -1))
993                 return NULL;
994
995         tp = topa_to_page(topa);
996         cur_pg = PFN_DOWN(topa->offset);
997         if (topa->z_count) {
998                 z_pg = TOPA_ENTRY_PAGES(topa, 0) * (topa->z_count + 1);
999                 start_idx = topa->z_count + 1;
1000         }
1001
1002         /*
1003          * Multiple entries at the beginning of the table have the same size,
1004          * ideally all of them; if @pg falls there, the search is done.
1005          */
1006         if (pg >= cur_pg && pg < cur_pg + z_pg) {
1007                 idx = (pg - cur_pg) / TOPA_ENTRY_PAGES(topa, 0);
1008                 return &tp->table[idx];
1009         }
1010
1011         /*
1012          * Otherwise, slow path: iterate through the remaining entries.
1013          */
1014         for (idx = start_idx, cur_pg += z_pg; idx < topa->last; idx++) {
1015                 if (cur_pg + TOPA_ENTRY_PAGES(topa, idx) > pg)
1016                         return &tp->table[idx];
1017
1018                 cur_pg += TOPA_ENTRY_PAGES(topa, idx);
1019         }
1020
1021         /*
1022          * Means we couldn't find a ToPA entry in the table that does match.
1023          */
1024         WARN_ON_ONCE(1);
1025
1026         return NULL;
1027 }
1028
1029 static struct topa_entry *
1030 pt_topa_prev_entry(struct pt_buffer *buf, struct topa_entry *te)
1031 {
1032         unsigned long table = (unsigned long)te & ~(PAGE_SIZE - 1);
1033         struct topa_page *tp;
1034         struct topa *topa;
1035
1036         tp = (struct topa_page *)table;
1037         if (tp->table != te)
1038                 return --te;
1039
1040         topa = &tp->topa;
1041         if (topa == buf->first)
1042                 topa = buf->last;
1043         else
1044                 topa = list_prev_entry(topa, list);
1045
1046         tp = topa_to_page(topa);
1047
1048         return &tp->table[topa->last - 1];
1049 }
1050
1051 /**
1052  * pt_buffer_reset_markers() - place interrupt and stop bits in the buffer
1053  * @buf:        PT buffer.
1054  * @handle:     Current output handle.
1055  *
1056  * Place INT and STOP marks to prevent overwriting old data that the consumer
1057  * hasn't yet collected and waking up the consumer after a certain fraction of
1058  * the buffer has filled up. Only needed and sensible for non-snapshot counters.
1059  *
1060  * This obviously relies on buf::head to figure out buffer markers, so it has
1061  * to be called after pt_buffer_reset_offsets() and before the hardware tracing
1062  * is enabled.
1063  */
1064 static int pt_buffer_reset_markers(struct pt_buffer *buf,
1065                                    struct perf_output_handle *handle)
1066
1067 {
1068         unsigned long head = local64_read(&buf->head);
1069         unsigned long idx, npages, wakeup;
1070
1071         if (buf->single)
1072                 return 0;
1073
1074         /* can't stop in the middle of an output region */
1075         if (buf->output_off + handle->size + 1 < pt_buffer_region_size(buf)) {
1076                 perf_aux_output_flag(handle, PERF_AUX_FLAG_TRUNCATED);
1077                 return -EINVAL;
1078         }
1079
1080
1081         /* single entry ToPA is handled by marking all regions STOP=1 INT=1 */
1082         if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries))
1083                 return 0;
1084
1085         /* clear STOP and INT from current entry */
1086         if (buf->stop_te) {
1087                 buf->stop_te->stop = 0;
1088                 buf->stop_te->intr = 0;
1089         }
1090
1091         if (buf->intr_te)
1092                 buf->intr_te->intr = 0;
1093
1094         /* how many pages till the STOP marker */
1095         npages = handle->size >> PAGE_SHIFT;
1096
1097         /* if it's on a page boundary, fill up one more page */
1098         if (!offset_in_page(head + handle->size + 1))
1099                 npages++;
1100
1101         idx = (head >> PAGE_SHIFT) + npages;
1102         idx &= buf->nr_pages - 1;
1103
1104         if (idx != buf->stop_pos) {
1105                 buf->stop_pos = idx;
1106                 buf->stop_te = pt_topa_entry_for_page(buf, idx);
1107                 buf->stop_te = pt_topa_prev_entry(buf, buf->stop_te);
1108         }
1109
1110         wakeup = handle->wakeup >> PAGE_SHIFT;
1111
1112         /* in the worst case, wake up the consumer one page before hard stop */
1113         idx = (head >> PAGE_SHIFT) + npages - 1;
1114         if (idx > wakeup)
1115                 idx = wakeup;
1116
1117         idx &= buf->nr_pages - 1;
1118         if (idx != buf->intr_pos) {
1119                 buf->intr_pos = idx;
1120                 buf->intr_te = pt_topa_entry_for_page(buf, idx);
1121                 buf->intr_te = pt_topa_prev_entry(buf, buf->intr_te);
1122         }
1123
1124         buf->stop_te->stop = 1;
1125         buf->stop_te->intr = 1;
1126         buf->intr_te->intr = 1;
1127
1128         return 0;
1129 }
1130
1131 /**
1132  * pt_buffer_reset_offsets() - adjust buffer's write pointers from aux_head
1133  * @buf:        PT buffer.
1134  * @head:       Write pointer (aux_head) from AUX buffer.
1135  *
1136  * Find the ToPA table and entry corresponding to given @head and set buffer's
1137  * "current" pointers accordingly. This is done after we have obtained the
1138  * current aux_head position from a successful call to perf_aux_output_begin()
1139  * to make sure the hardware is writing to the right place.
1140  *
1141  * This function modifies buf::{cur,cur_idx,output_off} that will be programmed
1142  * into PT msrs when the tracing is enabled and buf::head and buf::data_size,
1143  * which are used to determine INT and STOP markers' locations by a subsequent
1144  * call to pt_buffer_reset_markers().
1145  */
1146 static void pt_buffer_reset_offsets(struct pt_buffer *buf, unsigned long head)
1147 {
1148         struct topa_page *cur_tp;
1149         struct topa_entry *te;
1150         int pg;
1151
1152         if (buf->snapshot)
1153                 head &= (buf->nr_pages << PAGE_SHIFT) - 1;
1154
1155         if (!buf->single) {
1156                 pg = (head >> PAGE_SHIFT) & (buf->nr_pages - 1);
1157                 te = pt_topa_entry_for_page(buf, pg);
1158
1159                 cur_tp = topa_entry_to_page(te);
1160                 buf->cur = &cur_tp->topa;
1161                 buf->cur_idx = te - TOPA_ENTRY(buf->cur, 0);
1162                 buf->output_off = head & (pt_buffer_region_size(buf) - 1);
1163         } else {
1164                 buf->output_off = head;
1165         }
1166
1167         local64_set(&buf->head, head);
1168         local_set(&buf->data_size, 0);
1169 }
1170
1171 /**
1172  * pt_buffer_fini_topa() - deallocate ToPA structure of a buffer
1173  * @buf:        PT buffer.
1174  */
1175 static void pt_buffer_fini_topa(struct pt_buffer *buf)
1176 {
1177         struct topa *topa, *iter;
1178
1179         if (buf->single)
1180                 return;
1181
1182         list_for_each_entry_safe(topa, iter, &buf->tables, list) {
1183                 /*
1184                  * right now, this is in free_aux() path only, so
1185                  * no need to unlink this table from the list
1186                  */
1187                 topa_free(topa);
1188         }
1189 }
1190
1191 /**
1192  * pt_buffer_init_topa() - initialize ToPA table for pt buffer
1193  * @buf:        PT buffer.
1194  * @size:       Total size of all regions within this ToPA.
1195  * @gfp:        Allocation flags.
1196  */
1197 static int pt_buffer_init_topa(struct pt_buffer *buf, int cpu,
1198                                unsigned long nr_pages, gfp_t gfp)
1199 {
1200         struct topa *topa;
1201         int err;
1202
1203         topa = topa_alloc(cpu, gfp);
1204         if (!topa)
1205                 return -ENOMEM;
1206
1207         topa_insert_table(buf, topa);
1208
1209         while (buf->nr_pages < nr_pages) {
1210                 err = topa_insert_pages(buf, cpu, gfp);
1211                 if (err) {
1212                         pt_buffer_fini_topa(buf);
1213                         return -ENOMEM;
1214                 }
1215         }
1216
1217         /* link last table to the first one, unless we're double buffering */
1218         if (intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) {
1219                 TOPA_ENTRY(buf->last, -1)->base = topa_pfn(buf->first);
1220                 TOPA_ENTRY(buf->last, -1)->end = 1;
1221         }
1222
1223         pt_topa_dump(buf);
1224         return 0;
1225 }
1226
1227 static int pt_buffer_try_single(struct pt_buffer *buf, int nr_pages)
1228 {
1229         struct page *p = virt_to_page(buf->data_pages[0]);
1230         int ret = -ENOTSUPP, order = 0;
1231
1232         /*
1233          * We can use single range output mode
1234          * + in snapshot mode, where we don't need interrupts;
1235          * + if the hardware supports it;
1236          * + if the entire buffer is one contiguous allocation.
1237          */
1238         if (!buf->snapshot)
1239                 goto out;
1240
1241         if (!intel_pt_validate_hw_cap(PT_CAP_single_range_output))
1242                 goto out;
1243
1244         if (PagePrivate(p))
1245                 order = page_private(p);
1246
1247         if (1 << order != nr_pages)
1248                 goto out;
1249
1250         /*
1251          * Some processors cannot always support single range for more than
1252          * 4KB - refer errata TGL052, ADL037 and RPL017. Future processors might
1253          * also be affected, so for now rather than trying to keep track of
1254          * which ones, just disable it for all.
1255          */
1256         if (nr_pages > 1)
1257                 goto out;
1258
1259         buf->single = true;
1260         buf->nr_pages = nr_pages;
1261         ret = 0;
1262 out:
1263         return ret;
1264 }
1265
1266 /**
1267  * pt_buffer_setup_aux() - set up topa tables for a PT buffer
1268  * @cpu:        Cpu on which to allocate, -1 means current.
1269  * @pages:      Array of pointers to buffer pages passed from perf core.
1270  * @nr_pages:   Number of pages in the buffer.
1271  * @snapshot:   If this is a snapshot/overwrite counter.
1272  *
1273  * This is a pmu::setup_aux callback that sets up ToPA tables and all the
1274  * bookkeeping for an AUX buffer.
1275  *
1276  * Return:      Our private PT buffer structure.
1277  */
1278 static void *
1279 pt_buffer_setup_aux(struct perf_event *event, void **pages,
1280                     int nr_pages, bool snapshot)
1281 {
1282         struct pt_buffer *buf;
1283         int node, ret, cpu = event->cpu;
1284
1285         if (!nr_pages)
1286                 return NULL;
1287
1288         /*
1289          * Only support AUX sampling in snapshot mode, where we don't
1290          * generate NMIs.
1291          */
1292         if (event->attr.aux_sample_size && !snapshot)
1293                 return NULL;
1294
1295         if (cpu == -1)
1296                 cpu = raw_smp_processor_id();
1297         node = cpu_to_node(cpu);
1298
1299         buf = kzalloc_node(sizeof(struct pt_buffer), GFP_KERNEL, node);
1300         if (!buf)
1301                 return NULL;
1302
1303         buf->snapshot = snapshot;
1304         buf->data_pages = pages;
1305         buf->stop_pos = -1;
1306         buf->intr_pos = -1;
1307
1308         INIT_LIST_HEAD(&buf->tables);
1309
1310         ret = pt_buffer_try_single(buf, nr_pages);
1311         if (!ret)
1312                 return buf;
1313
1314         ret = pt_buffer_init_topa(buf, cpu, nr_pages, GFP_KERNEL);
1315         if (ret) {
1316                 kfree(buf);
1317                 return NULL;
1318         }
1319
1320         return buf;
1321 }
1322
1323 /**
1324  * pt_buffer_free_aux() - perf AUX deallocation path callback
1325  * @data:       PT buffer.
1326  */
1327 static void pt_buffer_free_aux(void *data)
1328 {
1329         struct pt_buffer *buf = data;
1330
1331         pt_buffer_fini_topa(buf);
1332         kfree(buf);
1333 }
1334
1335 static int pt_addr_filters_init(struct perf_event *event)
1336 {
1337         struct pt_filters *filters;
1338         int node = event->cpu == -1 ? -1 : cpu_to_node(event->cpu);
1339
1340         if (!intel_pt_validate_hw_cap(PT_CAP_num_address_ranges))
1341                 return 0;
1342
1343         filters = kzalloc_node(sizeof(struct pt_filters), GFP_KERNEL, node);
1344         if (!filters)
1345                 return -ENOMEM;
1346
1347         if (event->parent)
1348                 memcpy(filters, event->parent->hw.addr_filters,
1349                        sizeof(*filters));
1350
1351         event->hw.addr_filters = filters;
1352
1353         return 0;
1354 }
1355
1356 static void pt_addr_filters_fini(struct perf_event *event)
1357 {
1358         kfree(event->hw.addr_filters);
1359         event->hw.addr_filters = NULL;
1360 }
1361
1362 #ifdef CONFIG_X86_64
1363 static u64 canonical_address(u64 vaddr, u8 vaddr_bits)
1364 {
1365         return ((s64)vaddr << (64 - vaddr_bits)) >> (64 - vaddr_bits);
1366 }
1367
1368 static u64 is_canonical_address(u64 vaddr, u8 vaddr_bits)
1369 {
1370         return canonical_address(vaddr, vaddr_bits) == vaddr;
1371 }
1372
1373 /* Clamp to a canonical address greater-than-or-equal-to the address given */
1374 static u64 clamp_to_ge_canonical_addr(u64 vaddr, u8 vaddr_bits)
1375 {
1376         return is_canonical_address(vaddr, vaddr_bits) ?
1377                vaddr :
1378                -BIT_ULL(vaddr_bits - 1);
1379 }
1380
1381 /* Clamp to a canonical address less-than-or-equal-to the address given */
1382 static u64 clamp_to_le_canonical_addr(u64 vaddr, u8 vaddr_bits)
1383 {
1384         return is_canonical_address(vaddr, vaddr_bits) ?
1385                vaddr :
1386                BIT_ULL(vaddr_bits - 1) - 1;
1387 }
1388 #else
1389 #define clamp_to_ge_canonical_addr(x, y) (x)
1390 #define clamp_to_le_canonical_addr(x, y) (x)
1391 #endif
1392
1393 static int pt_event_addr_filters_validate(struct list_head *filters)
1394 {
1395         struct perf_addr_filter *filter;
1396         int range = 0;
1397
1398         list_for_each_entry(filter, filters, entry) {
1399                 /*
1400                  * PT doesn't support single address triggers and
1401                  * 'start' filters.
1402                  */
1403                 if (!filter->size ||
1404                     filter->action == PERF_ADDR_FILTER_ACTION_START)
1405                         return -EOPNOTSUPP;
1406
1407                 if (++range > intel_pt_validate_hw_cap(PT_CAP_num_address_ranges))
1408                         return -EOPNOTSUPP;
1409         }
1410
1411         return 0;
1412 }
1413
1414 static void pt_event_addr_filters_sync(struct perf_event *event)
1415 {
1416         struct perf_addr_filters_head *head = perf_event_addr_filters(event);
1417         unsigned long msr_a, msr_b;
1418         struct perf_addr_filter_range *fr = event->addr_filter_ranges;
1419         struct pt_filters *filters = event->hw.addr_filters;
1420         struct perf_addr_filter *filter;
1421         int range = 0;
1422
1423         if (!filters)
1424                 return;
1425
1426         list_for_each_entry(filter, &head->list, entry) {
1427                 if (filter->path.dentry && !fr[range].start) {
1428                         msr_a = msr_b = 0;
1429                 } else {
1430                         unsigned long n = fr[range].size - 1;
1431                         unsigned long a = fr[range].start;
1432                         unsigned long b;
1433
1434                         if (a > ULONG_MAX - n)
1435                                 b = ULONG_MAX;
1436                         else
1437                                 b = a + n;
1438                         /*
1439                          * Apply the offset. 64-bit addresses written to the
1440                          * MSRs must be canonical, but the range can encompass
1441                          * non-canonical addresses. Since software cannot
1442                          * execute at non-canonical addresses, adjusting to
1443                          * canonical addresses does not affect the result of the
1444                          * address filter.
1445                          */
1446                         msr_a = clamp_to_ge_canonical_addr(a, boot_cpu_data.x86_virt_bits);
1447                         msr_b = clamp_to_le_canonical_addr(b, boot_cpu_data.x86_virt_bits);
1448                         if (msr_b < msr_a)
1449                                 msr_a = msr_b = 0;
1450                 }
1451
1452                 filters->filter[range].msr_a  = msr_a;
1453                 filters->filter[range].msr_b  = msr_b;
1454                 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER)
1455                         filters->filter[range].config = 1;
1456                 else
1457                         filters->filter[range].config = 2;
1458                 range++;
1459         }
1460
1461         filters->nr_filters = range;
1462 }
1463
1464 /**
1465  * intel_pt_interrupt() - PT PMI handler
1466  */
1467 void intel_pt_interrupt(void)
1468 {
1469         struct pt *pt = this_cpu_ptr(&pt_ctx);
1470         struct pt_buffer *buf;
1471         struct perf_event *event = pt->handle.event;
1472
1473         /*
1474          * There may be a dangling PT bit in the interrupt status register
1475          * after PT has been disabled by pt_event_stop(). Make sure we don't
1476          * do anything (particularly, re-enable) for this event here.
1477          */
1478         if (!READ_ONCE(pt->handle_nmi))
1479                 return;
1480
1481         if (!event)
1482                 return;
1483
1484         pt_config_stop(event);
1485
1486         buf = perf_get_aux(&pt->handle);
1487         if (!buf)
1488                 return;
1489
1490         pt_read_offset(buf);
1491
1492         pt_handle_status(pt);
1493
1494         pt_update_head(pt);
1495
1496         perf_aux_output_end(&pt->handle, local_xchg(&buf->data_size, 0));
1497
1498         if (!event->hw.state) {
1499                 int ret;
1500
1501                 buf = perf_aux_output_begin(&pt->handle, event);
1502                 if (!buf) {
1503                         event->hw.state = PERF_HES_STOPPED;
1504                         return;
1505                 }
1506
1507                 pt_buffer_reset_offsets(buf, pt->handle.head);
1508                 /* snapshot counters don't use PMI, so it's safe */
1509                 ret = pt_buffer_reset_markers(buf, &pt->handle);
1510                 if (ret) {
1511                         perf_aux_output_end(&pt->handle, 0);
1512                         return;
1513                 }
1514
1515                 pt_config_buffer(buf);
1516                 pt_config_start(event);
1517         }
1518 }
1519
1520 void intel_pt_handle_vmx(int on)
1521 {
1522         struct pt *pt = this_cpu_ptr(&pt_ctx);
1523         struct perf_event *event;
1524         unsigned long flags;
1525
1526         /* PT plays nice with VMX, do nothing */
1527         if (pt_pmu.vmx)
1528                 return;
1529
1530         /*
1531          * VMXON will clear RTIT_CTL.TraceEn; we need to make
1532          * sure to not try to set it while VMX is on. Disable
1533          * interrupts to avoid racing with pmu callbacks;
1534          * concurrent PMI should be handled fine.
1535          */
1536         local_irq_save(flags);
1537         WRITE_ONCE(pt->vmx_on, on);
1538
1539         /*
1540          * If an AUX transaction is in progress, it will contain
1541          * gap(s), so flag it PARTIAL to inform the user.
1542          */
1543         event = pt->handle.event;
1544         if (event)
1545                 perf_aux_output_flag(&pt->handle,
1546                                      PERF_AUX_FLAG_PARTIAL);
1547
1548         /* Turn PTs back on */
1549         if (!on && event)
1550                 wrmsrl(MSR_IA32_RTIT_CTL, event->hw.config);
1551
1552         local_irq_restore(flags);
1553 }
1554 EXPORT_SYMBOL_GPL(intel_pt_handle_vmx);
1555
1556 /*
1557  * PMU callbacks
1558  */
1559
1560 static void pt_event_start(struct perf_event *event, int mode)
1561 {
1562         struct hw_perf_event *hwc = &event->hw;
1563         struct pt *pt = this_cpu_ptr(&pt_ctx);
1564         struct pt_buffer *buf;
1565
1566         buf = perf_aux_output_begin(&pt->handle, event);
1567         if (!buf)
1568                 goto fail_stop;
1569
1570         pt_buffer_reset_offsets(buf, pt->handle.head);
1571         if (!buf->snapshot) {
1572                 if (pt_buffer_reset_markers(buf, &pt->handle))
1573                         goto fail_end_stop;
1574         }
1575
1576         WRITE_ONCE(pt->handle_nmi, 1);
1577         hwc->state = 0;
1578
1579         pt_config_buffer(buf);
1580         pt_config(event);
1581
1582         return;
1583
1584 fail_end_stop:
1585         perf_aux_output_end(&pt->handle, 0);
1586 fail_stop:
1587         hwc->state = PERF_HES_STOPPED;
1588 }
1589
1590 static void pt_event_stop(struct perf_event *event, int mode)
1591 {
1592         struct pt *pt = this_cpu_ptr(&pt_ctx);
1593
1594         /*
1595          * Protect against the PMI racing with disabling wrmsr,
1596          * see comment in intel_pt_interrupt().
1597          */
1598         WRITE_ONCE(pt->handle_nmi, 0);
1599
1600         pt_config_stop(event);
1601
1602         if (event->hw.state == PERF_HES_STOPPED)
1603                 return;
1604
1605         event->hw.state = PERF_HES_STOPPED;
1606
1607         if (mode & PERF_EF_UPDATE) {
1608                 struct pt_buffer *buf = perf_get_aux(&pt->handle);
1609
1610                 if (!buf)
1611                         return;
1612
1613                 if (WARN_ON_ONCE(pt->handle.event != event))
1614                         return;
1615
1616                 pt_read_offset(buf);
1617
1618                 pt_handle_status(pt);
1619
1620                 pt_update_head(pt);
1621
1622                 if (buf->snapshot)
1623                         pt->handle.head =
1624                                 local_xchg(&buf->data_size,
1625                                            buf->nr_pages << PAGE_SHIFT);
1626                 perf_aux_output_end(&pt->handle, local_xchg(&buf->data_size, 0));
1627         }
1628 }
1629
1630 static long pt_event_snapshot_aux(struct perf_event *event,
1631                                   struct perf_output_handle *handle,
1632                                   unsigned long size)
1633 {
1634         struct pt *pt = this_cpu_ptr(&pt_ctx);
1635         struct pt_buffer *buf = perf_get_aux(&pt->handle);
1636         unsigned long from = 0, to;
1637         long ret;
1638
1639         if (WARN_ON_ONCE(!buf))
1640                 return 0;
1641
1642         /*
1643          * Sampling is only allowed on snapshot events;
1644          * see pt_buffer_setup_aux().
1645          */
1646         if (WARN_ON_ONCE(!buf->snapshot))
1647                 return 0;
1648
1649         /*
1650          * Here, handle_nmi tells us if the tracing is on
1651          */
1652         if (READ_ONCE(pt->handle_nmi))
1653                 pt_config_stop(event);
1654
1655         pt_read_offset(buf);
1656         pt_update_head(pt);
1657
1658         to = local_read(&buf->data_size);
1659         if (to < size)
1660                 from = buf->nr_pages << PAGE_SHIFT;
1661         from += to - size;
1662
1663         ret = perf_output_copy_aux(&pt->handle, handle, from, to);
1664
1665         /*
1666          * If the tracing was on when we turned up, restart it.
1667          * Compiler barrier not needed as we couldn't have been
1668          * preempted by anything that touches pt->handle_nmi.
1669          */
1670         if (pt->handle_nmi)
1671                 pt_config_start(event);
1672
1673         return ret;
1674 }
1675
1676 static void pt_event_del(struct perf_event *event, int mode)
1677 {
1678         pt_event_stop(event, PERF_EF_UPDATE);
1679 }
1680
1681 static int pt_event_add(struct perf_event *event, int mode)
1682 {
1683         struct pt *pt = this_cpu_ptr(&pt_ctx);
1684         struct hw_perf_event *hwc = &event->hw;
1685         int ret = -EBUSY;
1686
1687         if (pt->handle.event)
1688                 goto fail;
1689
1690         if (mode & PERF_EF_START) {
1691                 pt_event_start(event, 0);
1692                 ret = -EINVAL;
1693                 if (hwc->state == PERF_HES_STOPPED)
1694                         goto fail;
1695         } else {
1696                 hwc->state = PERF_HES_STOPPED;
1697         }
1698
1699         ret = 0;
1700 fail:
1701
1702         return ret;
1703 }
1704
1705 static void pt_event_read(struct perf_event *event)
1706 {
1707 }
1708
1709 static void pt_event_destroy(struct perf_event *event)
1710 {
1711         pt_addr_filters_fini(event);
1712         x86_del_exclusive(x86_lbr_exclusive_pt);
1713 }
1714
1715 static int pt_event_init(struct perf_event *event)
1716 {
1717         if (event->attr.type != pt_pmu.pmu.type)
1718                 return -ENOENT;
1719
1720         if (!pt_event_valid(event))
1721                 return -EINVAL;
1722
1723         if (x86_add_exclusive(x86_lbr_exclusive_pt))
1724                 return -EBUSY;
1725
1726         if (pt_addr_filters_init(event)) {
1727                 x86_del_exclusive(x86_lbr_exclusive_pt);
1728                 return -ENOMEM;
1729         }
1730
1731         event->destroy = pt_event_destroy;
1732
1733         return 0;
1734 }
1735
1736 void cpu_emergency_stop_pt(void)
1737 {
1738         struct pt *pt = this_cpu_ptr(&pt_ctx);
1739
1740         if (pt->handle.event)
1741                 pt_event_stop(pt->handle.event, PERF_EF_UPDATE);
1742 }
1743
1744 int is_intel_pt_event(struct perf_event *event)
1745 {
1746         return event->pmu == &pt_pmu.pmu;
1747 }
1748
1749 static __init int pt_init(void)
1750 {
1751         int ret, cpu, prior_warn = 0;
1752
1753         BUILD_BUG_ON(sizeof(struct topa) > PAGE_SIZE);
1754
1755         if (!boot_cpu_has(X86_FEATURE_INTEL_PT))
1756                 return -ENODEV;
1757
1758         cpus_read_lock();
1759         for_each_online_cpu(cpu) {
1760                 u64 ctl;
1761
1762                 ret = rdmsrl_safe_on_cpu(cpu, MSR_IA32_RTIT_CTL, &ctl);
1763                 if (!ret && (ctl & RTIT_CTL_TRACEEN))
1764                         prior_warn++;
1765         }
1766         cpus_read_unlock();
1767
1768         if (prior_warn) {
1769                 x86_add_exclusive(x86_lbr_exclusive_pt);
1770                 pr_warn("PT is enabled at boot time, doing nothing\n");
1771
1772                 return -EBUSY;
1773         }
1774
1775         ret = pt_pmu_hw_init();
1776         if (ret)
1777                 return ret;
1778
1779         if (!intel_pt_validate_hw_cap(PT_CAP_topa_output)) {
1780                 pr_warn("ToPA output is not supported on this CPU\n");
1781                 return -ENODEV;
1782         }
1783
1784         if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries))
1785                 pt_pmu.pmu.capabilities = PERF_PMU_CAP_AUX_NO_SG;
1786
1787         pt_pmu.pmu.capabilities |= PERF_PMU_CAP_EXCLUSIVE | PERF_PMU_CAP_ITRACE;
1788         pt_pmu.pmu.attr_groups           = pt_attr_groups;
1789         pt_pmu.pmu.task_ctx_nr           = perf_sw_context;
1790         pt_pmu.pmu.event_init            = pt_event_init;
1791         pt_pmu.pmu.add                   = pt_event_add;
1792         pt_pmu.pmu.del                   = pt_event_del;
1793         pt_pmu.pmu.start                 = pt_event_start;
1794         pt_pmu.pmu.stop                  = pt_event_stop;
1795         pt_pmu.pmu.snapshot_aux          = pt_event_snapshot_aux;
1796         pt_pmu.pmu.read                  = pt_event_read;
1797         pt_pmu.pmu.setup_aux             = pt_buffer_setup_aux;
1798         pt_pmu.pmu.free_aux              = pt_buffer_free_aux;
1799         pt_pmu.pmu.addr_filters_sync     = pt_event_addr_filters_sync;
1800         pt_pmu.pmu.addr_filters_validate = pt_event_addr_filters_validate;
1801         pt_pmu.pmu.nr_addr_filters       =
1802                 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges);
1803
1804         ret = perf_pmu_register(&pt_pmu.pmu, "intel_pt", -1);
1805
1806         return ret;
1807 }
1808 arch_initcall(pt_init);