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