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