drm/modes: Fix drm_mode_vrefres() docs
[drm/drm-misc.git] / arch / x86 / events / intel / pt.c
blob4b0373bc8ab4475ec72622554ede7cd1568e7b20
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.
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 */
11 #undef DEBUG
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
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>
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>
27 #include "../perf_event.h"
28 #include "pt.h"
30 static DEFINE_PER_CPU(struct pt, pt_ctx);
32 static struct pt_pmu pt_pmu;
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.
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).
45 #define PT_CAP(_n, _l, _r, _m) \
46 [PT_CAP_ ## _n] = { .name = __stringify(_n), .leaf = _l, \
47 .reg = _r, .mask = _m }
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),
75 u32 intel_pt_validate_cap(u32 *caps, enum pt_capabilities capability)
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);
81 return (c & cd->mask) >> shift;
83 EXPORT_SYMBOL_GPL(intel_pt_validate_cap);
85 u32 intel_pt_validate_hw_cap(enum pt_capabilities cap)
87 return intel_pt_validate_cap(pt_pmu.caps, cap);
89 EXPORT_SYMBOL_GPL(intel_pt_validate_hw_cap);
91 static ssize_t pt_cap_show(struct device *cdev,
92 struct device_attribute *attr,
93 char *buf)
95 struct dev_ext_attribute *ea =
96 container_of(attr, struct dev_ext_attribute, attr);
97 enum pt_capabilities cap = (long)ea->var;
99 return snprintf(buf, PAGE_SIZE, "%x\n", intel_pt_validate_hw_cap(cap));
102 static struct attribute_group pt_cap_group __ro_after_init = {
103 .name = "caps",
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" );
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,
139 static struct attribute_group pt_format_group = {
140 .name = "format",
141 .attrs = pt_formats_attr,
144 static ssize_t
145 pt_timing_attr_show(struct device *dev, struct device_attribute *attr,
146 char *page)
148 struct perf_pmu_events_attr *pmu_attr =
149 container_of(attr, struct perf_pmu_events_attr, attr);
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;
162 return -EINVAL;
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);
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,
176 static struct attribute_group pt_timing_group = {
177 .attrs = pt_timing_attr,
180 static const struct attribute_group *pt_attr_groups[] = {
181 &pt_cap_group,
182 &pt_format_group,
183 &pt_timing_group,
184 NULL,
187 static int __init pt_pmu_hw_init(void)
189 struct dev_ext_attribute *de_attrs;
190 struct attribute **attrs;
191 size_t size;
192 u64 reg;
193 int ret;
194 long i;
196 rdmsrl(MSR_PLATFORM_INFO, reg);
197 pt_pmu.max_nonturbo_ratio = (reg & 0xff00) >> 8;
200 * if available, read in TSC to core crystal clock ratio,
201 * otherwise, zero for numerator stands for "not enumerated"
202 * as per SDM
204 if (boot_cpu_data.cpuid_level >= CPUID_TSC_LEAF) {
205 u32 eax, ebx, ecx, edx;
207 cpuid(CPUID_TSC_LEAF, &eax, &ebx, &ecx, &edx);
209 pt_pmu.tsc_art_num = ebx;
210 pt_pmu.tsc_art_den = eax;
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;
226 if (boot_cpu_has(X86_FEATURE_VMX)) {
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.
232 rdmsrl(MSR_IA32_VMX_MISC, reg);
233 if (reg & BIT(14))
234 pt_pmu.vmx = true;
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]);
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;
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;
256 for (i = 0; i < ARRAY_SIZE(pt_caps); i++) {
257 struct dev_ext_attribute *de_attr = de_attrs + i;
259 de_attr->attr.attr.name = pt_caps[i].name;
261 sysfs_attr_init(&de_attr->attr.attr);
263 de_attr->attr.attr.mode = S_IRUGO;
264 de_attr->attr.show = pt_cap_show;
265 de_attr->var = (void *)i;
267 attrs[i] = &de_attr->attr.attr;
270 pt_cap_group.attrs = attrs;
272 return 0;
274 fail:
275 kfree(attrs);
277 return ret;
280 #define RTIT_CTL_CYC_PSB (RTIT_CTL_CYCLEACC | \
281 RTIT_CTL_CYC_THRESH | \
282 RTIT_CTL_PSB_FREQ)
284 #define RTIT_CTL_MTC (RTIT_CTL_MTC_EN | \
285 RTIT_CTL_MTC_RANGE)
287 #define RTIT_CTL_PTW (RTIT_CTL_PTW_EN | \
288 RTIT_CTL_FUP_ON_PTW)
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().
298 #define RTIT_CTL_PASSTHROUGH RTIT_CTL_TRACEEN
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)
312 static bool pt_event_valid(struct perf_event *event)
314 u64 config = event->attr.config;
315 u64 allowed, requested;
317 if ((config & PT_CONFIG_MASK) != config)
318 return false;
320 if (config & RTIT_CTL_CYC_PSB) {
321 if (!intel_pt_validate_hw_cap(PT_CAP_psb_cyc))
322 return false;
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;
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;
337 if (config & RTIT_CTL_MTC) {
339 * In the unlikely case that CPUID lists valid mtc periods,
340 * but not the mtc capability, drop out here.
342 * Spec says that setting mtc period bits while mtc bit in
343 * CPUID is 0 will #GP, so better safe than sorry.
345 if (!intel_pt_validate_hw_cap(PT_CAP_mtc))
346 return false;
348 allowed = intel_pt_validate_hw_cap(PT_CAP_mtc_periods);
349 if (!allowed)
350 return false;
352 requested = (config & RTIT_CTL_MTC_RANGE) >>
353 RTIT_CTL_MTC_RANGE_OFFSET;
355 if (!(allowed & BIT(requested)))
356 return false;
359 if (config & RTIT_CTL_PWR_EVT_EN &&
360 !intel_pt_validate_hw_cap(PT_CAP_power_event_trace))
361 return false;
363 if (config & RTIT_CTL_EVENT_EN &&
364 !intel_pt_validate_hw_cap(PT_CAP_event_trace))
365 return false;
367 if (config & RTIT_CTL_NOTNT &&
368 !intel_pt_validate_hw_cap(PT_CAP_tnt_disable))
369 return false;
371 if (config & RTIT_CTL_PTW) {
372 if (!intel_pt_validate_hw_cap(PT_CAP_ptwrite))
373 return false;
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;
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.
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.
392 if (config & RTIT_CTL_PASSTHROUGH) {
394 * Disallow not setting BRANCH_EN where BRANCH_EN is
395 * always required.
397 if (pt_pmu.branch_en_always_on &&
398 !(config & RTIT_CTL_BRANCH_EN))
399 return false;
400 } else {
402 * Disallow BRANCH_EN without the PASSTHROUGH.
404 if (config & RTIT_CTL_BRANCH_EN)
405 return false;
408 return true;
412 * PT configuration helpers
413 * These all are cpu affine and operate on a local PT
416 static void pt_config_start(struct perf_event *event)
418 struct pt *pt = this_cpu_ptr(&pt_ctx);
419 u64 ctl = event->hw.aux_config;
421 if (READ_ONCE(event->hw.aux_paused))
422 return;
424 ctl |= RTIT_CTL_TRACEEN;
425 if (READ_ONCE(pt->vmx_on))
426 perf_aux_output_flag(&pt->handle, PERF_AUX_FLAG_PARTIAL);
427 else
428 wrmsrl(MSR_IA32_RTIT_CTL, ctl);
430 WRITE_ONCE(event->hw.aux_config, ctl);
433 /* Address ranges and their corresponding msr configuration registers */
434 static const struct pt_address_range {
435 unsigned long msr_a;
436 unsigned long msr_b;
437 unsigned int reg_off;
438 } pt_address_ranges[] = {
440 .msr_a = MSR_IA32_RTIT_ADDR0_A,
441 .msr_b = MSR_IA32_RTIT_ADDR0_B,
442 .reg_off = RTIT_CTL_ADDR0_OFFSET,
445 .msr_a = MSR_IA32_RTIT_ADDR1_A,
446 .msr_b = MSR_IA32_RTIT_ADDR1_B,
447 .reg_off = RTIT_CTL_ADDR1_OFFSET,
450 .msr_a = MSR_IA32_RTIT_ADDR2_A,
451 .msr_b = MSR_IA32_RTIT_ADDR2_B,
452 .reg_off = RTIT_CTL_ADDR2_OFFSET,
455 .msr_a = MSR_IA32_RTIT_ADDR3_A,
456 .msr_b = MSR_IA32_RTIT_ADDR3_B,
457 .reg_off = RTIT_CTL_ADDR3_OFFSET,
461 static u64 pt_config_filters(struct perf_event *event)
463 struct pt_filters *filters = event->hw.addr_filters;
464 struct pt *pt = this_cpu_ptr(&pt_ctx);
465 unsigned int range = 0;
466 u64 rtit_ctl = 0;
468 if (!filters)
469 return 0;
471 perf_event_addr_filters_sync(event);
473 for (range = 0; range < filters->nr_filters; range++) {
474 struct pt_filter *filter = &filters->filter[range];
477 * Note, if the range has zero start/end addresses due
478 * to its dynamic object not being loaded yet, we just
479 * go ahead and program zeroed range, which will simply
480 * produce no data. Note^2: if executable code at 0x0
481 * is a concern, we can set up an "invalid" configuration
482 * such as msr_b < msr_a.
485 /* avoid redundant msr writes */
486 if (pt->filters.filter[range].msr_a != filter->msr_a) {
487 wrmsrl(pt_address_ranges[range].msr_a, filter->msr_a);
488 pt->filters.filter[range].msr_a = filter->msr_a;
491 if (pt->filters.filter[range].msr_b != filter->msr_b) {
492 wrmsrl(pt_address_ranges[range].msr_b, filter->msr_b);
493 pt->filters.filter[range].msr_b = filter->msr_b;
496 rtit_ctl |= (u64)filter->config << pt_address_ranges[range].reg_off;
499 return rtit_ctl;
502 static void pt_config(struct perf_event *event)
504 struct pt *pt = this_cpu_ptr(&pt_ctx);
505 struct pt_buffer *buf = perf_get_aux(&pt->handle);
506 u64 reg;
508 /* First round: clear STATUS, in particular the PSB byte counter. */
509 if (!event->hw.aux_config) {
510 perf_event_itrace_started(event);
511 wrmsrl(MSR_IA32_RTIT_STATUS, 0);
514 reg = pt_config_filters(event);
515 reg |= RTIT_CTL_TRACEEN;
516 if (!buf->single)
517 reg |= RTIT_CTL_TOPA;
520 * Previously, we had BRANCH_EN on by default, but now that PT has
521 * grown features outside of branch tracing, it is useful to allow
522 * the user to disable it. Setting bit 0 in the event's attr.config
523 * allows BRANCH_EN to pass through instead of being always on. See
524 * also the comment in pt_event_valid().
526 if (event->attr.config & BIT(0)) {
527 reg |= event->attr.config & RTIT_CTL_BRANCH_EN;
528 } else {
529 reg |= RTIT_CTL_BRANCH_EN;
532 if (!event->attr.exclude_kernel)
533 reg |= RTIT_CTL_OS;
534 if (!event->attr.exclude_user)
535 reg |= RTIT_CTL_USR;
537 reg |= (event->attr.config & PT_CONFIG_MASK);
539 event->hw.aux_config = reg;
542 * Allow resume before starting so as not to overwrite a value set by a
543 * PMI.
545 barrier();
546 WRITE_ONCE(pt->resume_allowed, 1);
547 /* Configuration is complete, it is now OK to handle an NMI */
548 barrier();
549 WRITE_ONCE(pt->handle_nmi, 1);
550 barrier();
551 pt_config_start(event);
552 barrier();
554 * Allow pause after starting so its pt_config_stop() doesn't race with
555 * pt_config_start().
557 WRITE_ONCE(pt->pause_allowed, 1);
560 static void pt_config_stop(struct perf_event *event)
562 struct pt *pt = this_cpu_ptr(&pt_ctx);
563 u64 ctl = READ_ONCE(event->hw.aux_config);
565 /* may be already stopped by a PMI */
566 if (!(ctl & RTIT_CTL_TRACEEN))
567 return;
569 ctl &= ~RTIT_CTL_TRACEEN;
570 if (!READ_ONCE(pt->vmx_on))
571 wrmsrl(MSR_IA32_RTIT_CTL, ctl);
573 WRITE_ONCE(event->hw.aux_config, ctl);
576 * A wrmsr that disables trace generation serializes other PT
577 * registers and causes all data packets to be written to memory,
578 * but a fence is required for the data to become globally visible.
580 * The below WMB, separating data store and aux_head store matches
581 * the consumer's RMB that separates aux_head load and data load.
583 wmb();
587 * struct topa - ToPA metadata
588 * @list: linkage to struct pt_buffer's list of tables
589 * @offset: offset of the first entry in this table in the buffer
590 * @size: total size of all entries in this table
591 * @last: index of the last initialized entry in this table
592 * @z_count: how many times the first entry repeats
594 struct topa {
595 struct list_head list;
596 u64 offset;
597 size_t size;
598 int last;
599 unsigned int z_count;
603 * Keep ToPA table-related metadata on the same page as the actual table,
604 * taking up a few words from the top
607 #define TENTS_PER_PAGE \
608 ((PAGE_SIZE - sizeof(struct topa)) / sizeof(struct topa_entry))
611 * struct topa_page - page-sized ToPA table with metadata at the top
612 * @table: actual ToPA table entries, as understood by PT hardware
613 * @topa: metadata
615 struct topa_page {
616 struct topa_entry table[TENTS_PER_PAGE];
617 struct topa topa;
620 static inline struct topa_page *topa_to_page(struct topa *topa)
622 return container_of(topa, struct topa_page, topa);
625 static inline struct topa_page *topa_entry_to_page(struct topa_entry *te)
627 return (struct topa_page *)((unsigned long)te & PAGE_MASK);
630 static inline phys_addr_t topa_pfn(struct topa *topa)
632 return PFN_DOWN(virt_to_phys(topa_to_page(topa)));
635 /* make -1 stand for the last table entry */
636 #define TOPA_ENTRY(t, i) \
637 ((i) == -1 \
638 ? &topa_to_page(t)->table[(t)->last] \
639 : &topa_to_page(t)->table[(i)])
640 #define TOPA_ENTRY_SIZE(t, i) (sizes(TOPA_ENTRY((t), (i))->size))
641 #define TOPA_ENTRY_PAGES(t, i) (1 << TOPA_ENTRY((t), (i))->size)
643 static void pt_config_buffer(struct pt_buffer *buf)
645 struct pt *pt = this_cpu_ptr(&pt_ctx);
646 u64 reg, mask;
647 void *base;
649 if (buf->single) {
650 base = buf->data_pages[0];
651 mask = (buf->nr_pages * PAGE_SIZE - 1) >> 7;
652 } else {
653 base = topa_to_page(buf->cur)->table;
654 mask = (u64)buf->cur_idx;
657 reg = virt_to_phys(base);
658 if (pt->output_base != reg) {
659 pt->output_base = reg;
660 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, reg);
663 reg = 0x7f | (mask << 7) | ((u64)buf->output_off << 32);
664 if (pt->output_mask != reg) {
665 pt->output_mask = reg;
666 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, reg);
671 * topa_alloc() - allocate page-sized ToPA table
672 * @cpu: CPU on which to allocate.
673 * @gfp: Allocation flags.
675 * Return: On success, return the pointer to ToPA table page.
677 static struct topa *topa_alloc(int cpu, gfp_t gfp)
679 int node = cpu_to_node(cpu);
680 struct topa_page *tp;
681 struct page *p;
683 p = alloc_pages_node(node, gfp | __GFP_ZERO, 0);
684 if (!p)
685 return NULL;
687 tp = page_address(p);
688 tp->topa.last = 0;
691 * In case of singe-entry ToPA, always put the self-referencing END
692 * link as the 2nd entry in the table
694 if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) {
695 TOPA_ENTRY(&tp->topa, 1)->base = page_to_phys(p) >> TOPA_SHIFT;
696 TOPA_ENTRY(&tp->topa, 1)->end = 1;
699 return &tp->topa;
703 * topa_free() - free a page-sized ToPA table
704 * @topa: Table to deallocate.
706 static void topa_free(struct topa *topa)
708 free_page((unsigned long)topa);
712 * topa_insert_table() - insert a ToPA table into a buffer
713 * @buf: PT buffer that's being extended.
714 * @topa: New topa table to be inserted.
716 * If it's the first table in this buffer, set up buffer's pointers
717 * accordingly; otherwise, add a END=1 link entry to @topa to the current
718 * "last" table and adjust the last table pointer to @topa.
720 static void topa_insert_table(struct pt_buffer *buf, struct topa *topa)
722 struct topa *last = buf->last;
724 list_add_tail(&topa->list, &buf->tables);
726 if (!buf->first) {
727 buf->first = buf->last = buf->cur = topa;
728 return;
731 topa->offset = last->offset + last->size;
732 buf->last = topa;
734 if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries))
735 return;
737 BUG_ON(last->last != TENTS_PER_PAGE - 1);
739 TOPA_ENTRY(last, -1)->base = topa_pfn(topa);
740 TOPA_ENTRY(last, -1)->end = 1;
744 * topa_table_full() - check if a ToPA table is filled up
745 * @topa: ToPA table.
747 static bool topa_table_full(struct topa *topa)
749 /* single-entry ToPA is a special case */
750 if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries))
751 return !!topa->last;
753 return topa->last == TENTS_PER_PAGE - 1;
757 * topa_insert_pages() - create a list of ToPA tables
758 * @buf: PT buffer being initialized.
759 * @cpu: CPU on which to allocate.
760 * @gfp: Allocation flags.
762 * This initializes a list of ToPA tables with entries from
763 * the data_pages provided by rb_alloc_aux().
765 * Return: 0 on success or error code.
767 static int topa_insert_pages(struct pt_buffer *buf, int cpu, gfp_t gfp)
769 struct topa *topa = buf->last;
770 int order = 0;
771 struct page *p;
773 p = virt_to_page(buf->data_pages[buf->nr_pages]);
774 if (PagePrivate(p))
775 order = page_private(p);
777 if (topa_table_full(topa)) {
778 topa = topa_alloc(cpu, gfp);
779 if (!topa)
780 return -ENOMEM;
782 topa_insert_table(buf, topa);
785 if (topa->z_count == topa->last - 1) {
786 if (order == TOPA_ENTRY(topa, topa->last - 1)->size)
787 topa->z_count++;
790 TOPA_ENTRY(topa, -1)->base = page_to_phys(p) >> TOPA_SHIFT;
791 TOPA_ENTRY(topa, -1)->size = order;
792 if (!buf->snapshot &&
793 !intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) {
794 TOPA_ENTRY(topa, -1)->intr = 1;
795 TOPA_ENTRY(topa, -1)->stop = 1;
798 topa->last++;
799 topa->size += sizes(order);
801 buf->nr_pages += 1ul << order;
803 return 0;
807 * pt_topa_dump() - print ToPA tables and their entries
808 * @buf: PT buffer.
810 static void pt_topa_dump(struct pt_buffer *buf)
812 struct topa *topa;
814 list_for_each_entry(topa, &buf->tables, list) {
815 struct topa_page *tp = topa_to_page(topa);
816 int i;
818 pr_debug("# table @%p, off %llx size %zx\n", tp->table,
819 topa->offset, topa->size);
820 for (i = 0; i < TENTS_PER_PAGE; i++) {
821 pr_debug("# entry @%p (%lx sz %u %c%c%c) raw=%16llx\n",
822 &tp->table[i],
823 (unsigned long)tp->table[i].base << TOPA_SHIFT,
824 sizes(tp->table[i].size),
825 tp->table[i].end ? 'E' : ' ',
826 tp->table[i].intr ? 'I' : ' ',
827 tp->table[i].stop ? 'S' : ' ',
828 *(u64 *)&tp->table[i]);
829 if ((intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries) &&
830 tp->table[i].stop) ||
831 tp->table[i].end)
832 break;
833 if (!i && topa->z_count)
834 i += topa->z_count;
840 * pt_buffer_advance() - advance to the next output region
841 * @buf: PT buffer.
843 * Advance the current pointers in the buffer to the next ToPA entry.
845 static void pt_buffer_advance(struct pt_buffer *buf)
847 buf->output_off = 0;
848 buf->cur_idx++;
850 if (buf->cur_idx == buf->cur->last) {
851 if (buf->cur == buf->last) {
852 buf->cur = buf->first;
853 buf->wrapped = true;
854 } else {
855 buf->cur = list_entry(buf->cur->list.next, struct topa,
856 list);
858 buf->cur_idx = 0;
863 * pt_update_head() - calculate current offsets and sizes
864 * @pt: Per-cpu pt context.
866 * Update buffer's current write pointer position and data size.
868 static void pt_update_head(struct pt *pt)
870 struct pt_buffer *buf = perf_get_aux(&pt->handle);
871 bool wrapped = buf->wrapped;
872 u64 topa_idx, base, old;
874 buf->wrapped = false;
876 if (buf->single) {
877 local_set(&buf->data_size, buf->output_off);
878 return;
881 /* offset of the first region in this table from the beginning of buf */
882 base = buf->cur->offset + buf->output_off;
884 /* offset of the current output region within this table */
885 for (topa_idx = 0; topa_idx < buf->cur_idx; topa_idx++)
886 base += TOPA_ENTRY_SIZE(buf->cur, topa_idx);
888 if (buf->snapshot) {
889 local_set(&buf->data_size, base);
890 } else {
891 old = (local64_xchg(&buf->head, base) &
892 ((buf->nr_pages << PAGE_SHIFT) - 1));
893 if (base < old || (base == old && wrapped))
894 base += buf->nr_pages << PAGE_SHIFT;
896 local_add(base - old, &buf->data_size);
901 * pt_buffer_region() - obtain current output region's address
902 * @buf: PT buffer.
904 static void *pt_buffer_region(struct pt_buffer *buf)
906 return phys_to_virt((phys_addr_t)TOPA_ENTRY(buf->cur, buf->cur_idx)->base << TOPA_SHIFT);
910 * pt_buffer_region_size() - obtain current output region's size
911 * @buf: PT buffer.
913 static size_t pt_buffer_region_size(struct pt_buffer *buf)
915 return TOPA_ENTRY_SIZE(buf->cur, buf->cur_idx);
919 * pt_handle_status() - take care of possible status conditions
920 * @pt: Per-cpu pt context.
922 static void pt_handle_status(struct pt *pt)
924 struct pt_buffer *buf = perf_get_aux(&pt->handle);
925 int advance = 0;
926 u64 status;
928 rdmsrl(MSR_IA32_RTIT_STATUS, status);
930 if (status & RTIT_STATUS_ERROR) {
931 pr_err_ratelimited("ToPA ERROR encountered, trying to recover\n");
932 pt_topa_dump(buf);
933 status &= ~RTIT_STATUS_ERROR;
936 if (status & RTIT_STATUS_STOPPED) {
937 status &= ~RTIT_STATUS_STOPPED;
940 * On systems that only do single-entry ToPA, hitting STOP
941 * means we are already losing data; need to let the decoder
942 * know.
944 if (!buf->single &&
945 (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries) ||
946 buf->output_off == pt_buffer_region_size(buf))) {
947 perf_aux_output_flag(&pt->handle,
948 PERF_AUX_FLAG_TRUNCATED);
949 advance++;
954 * Also on single-entry ToPA implementations, interrupt will come
955 * before the output reaches its output region's boundary.
957 if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries) &&
958 !buf->snapshot &&
959 pt_buffer_region_size(buf) - buf->output_off <= TOPA_PMI_MARGIN) {
960 void *head = pt_buffer_region(buf);
962 /* everything within this margin needs to be zeroed out */
963 memset(head + buf->output_off, 0,
964 pt_buffer_region_size(buf) -
965 buf->output_off);
966 advance++;
969 if (advance)
970 pt_buffer_advance(buf);
972 wrmsrl(MSR_IA32_RTIT_STATUS, status);
976 * pt_read_offset() - translate registers into buffer pointers
977 * @buf: PT buffer.
979 * Set buffer's output pointers from MSR values.
981 static void pt_read_offset(struct pt_buffer *buf)
983 struct pt *pt = this_cpu_ptr(&pt_ctx);
984 struct topa_page *tp;
986 if (!buf->single) {
987 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, pt->output_base);
988 tp = phys_to_virt(pt->output_base);
989 buf->cur = &tp->topa;
992 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, pt->output_mask);
993 /* offset within current output region */
994 buf->output_off = pt->output_mask >> 32;
995 /* index of current output region within this table */
996 if (!buf->single)
997 buf->cur_idx = (pt->output_mask & 0xffffff80) >> 7;
1000 static struct topa_entry *
1001 pt_topa_entry_for_page(struct pt_buffer *buf, unsigned int pg)
1003 struct topa_page *tp;
1004 struct topa *topa;
1005 unsigned int idx, cur_pg = 0, z_pg = 0, start_idx = 0;
1008 * Indicates a bug in the caller.
1010 if (WARN_ON_ONCE(pg >= buf->nr_pages))
1011 return NULL;
1014 * First, find the ToPA table where @pg fits. With high
1015 * order allocations, there shouldn't be many of these.
1017 list_for_each_entry(topa, &buf->tables, list) {
1018 if (topa->offset + topa->size > (unsigned long)pg << PAGE_SHIFT)
1019 goto found;
1023 * Hitting this means we have a problem in the ToPA
1024 * allocation code.
1026 WARN_ON_ONCE(1);
1028 return NULL;
1030 found:
1032 * Indicates a problem in the ToPA allocation code.
1034 if (WARN_ON_ONCE(topa->last == -1))
1035 return NULL;
1037 tp = topa_to_page(topa);
1038 cur_pg = PFN_DOWN(topa->offset);
1039 if (topa->z_count) {
1040 z_pg = TOPA_ENTRY_PAGES(topa, 0) * (topa->z_count + 1);
1041 start_idx = topa->z_count + 1;
1045 * Multiple entries at the beginning of the table have the same size,
1046 * ideally all of them; if @pg falls there, the search is done.
1048 if (pg >= cur_pg && pg < cur_pg + z_pg) {
1049 idx = (pg - cur_pg) / TOPA_ENTRY_PAGES(topa, 0);
1050 return &tp->table[idx];
1054 * Otherwise, slow path: iterate through the remaining entries.
1056 for (idx = start_idx, cur_pg += z_pg; idx < topa->last; idx++) {
1057 if (cur_pg + TOPA_ENTRY_PAGES(topa, idx) > pg)
1058 return &tp->table[idx];
1060 cur_pg += TOPA_ENTRY_PAGES(topa, idx);
1064 * Means we couldn't find a ToPA entry in the table that does match.
1066 WARN_ON_ONCE(1);
1068 return NULL;
1071 static struct topa_entry *
1072 pt_topa_prev_entry(struct pt_buffer *buf, struct topa_entry *te)
1074 unsigned long table = (unsigned long)te & ~(PAGE_SIZE - 1);
1075 struct topa_page *tp;
1076 struct topa *topa;
1078 tp = (struct topa_page *)table;
1079 if (tp->table != te)
1080 return --te;
1082 topa = &tp->topa;
1083 if (topa == buf->first)
1084 topa = buf->last;
1085 else
1086 topa = list_prev_entry(topa, list);
1088 tp = topa_to_page(topa);
1090 return &tp->table[topa->last - 1];
1094 * pt_buffer_reset_markers() - place interrupt and stop bits in the buffer
1095 * @buf: PT buffer.
1096 * @handle: Current output handle.
1098 * Place INT and STOP marks to prevent overwriting old data that the consumer
1099 * hasn't yet collected and waking up the consumer after a certain fraction of
1100 * the buffer has filled up. Only needed and sensible for non-snapshot counters.
1102 * This obviously relies on buf::head to figure out buffer markers, so it has
1103 * to be called after pt_buffer_reset_offsets() and before the hardware tracing
1104 * is enabled.
1106 static int pt_buffer_reset_markers(struct pt_buffer *buf,
1107 struct perf_output_handle *handle)
1110 unsigned long head = local64_read(&buf->head);
1111 unsigned long idx, npages, wakeup;
1113 if (buf->single)
1114 return 0;
1116 /* can't stop in the middle of an output region */
1117 if (buf->output_off + handle->size + 1 < pt_buffer_region_size(buf)) {
1118 perf_aux_output_flag(handle, PERF_AUX_FLAG_TRUNCATED);
1119 return -EINVAL;
1123 /* single entry ToPA is handled by marking all regions STOP=1 INT=1 */
1124 if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries))
1125 return 0;
1127 /* clear STOP and INT from current entry */
1128 if (buf->stop_te) {
1129 buf->stop_te->stop = 0;
1130 buf->stop_te->intr = 0;
1133 if (buf->intr_te)
1134 buf->intr_te->intr = 0;
1136 /* how many pages till the STOP marker */
1137 npages = handle->size >> PAGE_SHIFT;
1139 /* if it's on a page boundary, fill up one more page */
1140 if (!offset_in_page(head + handle->size + 1))
1141 npages++;
1143 idx = (head >> PAGE_SHIFT) + npages;
1144 idx &= buf->nr_pages - 1;
1146 if (idx != buf->stop_pos) {
1147 buf->stop_pos = idx;
1148 buf->stop_te = pt_topa_entry_for_page(buf, idx);
1149 buf->stop_te = pt_topa_prev_entry(buf, buf->stop_te);
1152 wakeup = handle->wakeup >> PAGE_SHIFT;
1154 /* in the worst case, wake up the consumer one page before hard stop */
1155 idx = (head >> PAGE_SHIFT) + npages - 1;
1156 if (idx > wakeup)
1157 idx = wakeup;
1159 idx &= buf->nr_pages - 1;
1160 if (idx != buf->intr_pos) {
1161 buf->intr_pos = idx;
1162 buf->intr_te = pt_topa_entry_for_page(buf, idx);
1163 buf->intr_te = pt_topa_prev_entry(buf, buf->intr_te);
1166 buf->stop_te->stop = 1;
1167 buf->stop_te->intr = 1;
1168 buf->intr_te->intr = 1;
1170 return 0;
1174 * pt_buffer_reset_offsets() - adjust buffer's write pointers from aux_head
1175 * @buf: PT buffer.
1176 * @head: Write pointer (aux_head) from AUX buffer.
1178 * Find the ToPA table and entry corresponding to given @head and set buffer's
1179 * "current" pointers accordingly. This is done after we have obtained the
1180 * current aux_head position from a successful call to perf_aux_output_begin()
1181 * to make sure the hardware is writing to the right place.
1183 * This function modifies buf::{cur,cur_idx,output_off} that will be programmed
1184 * into PT msrs when the tracing is enabled and buf::head and buf::data_size,
1185 * which are used to determine INT and STOP markers' locations by a subsequent
1186 * call to pt_buffer_reset_markers().
1188 static void pt_buffer_reset_offsets(struct pt_buffer *buf, unsigned long head)
1190 struct topa_page *cur_tp;
1191 struct topa_entry *te;
1192 int pg;
1194 if (buf->snapshot)
1195 head &= (buf->nr_pages << PAGE_SHIFT) - 1;
1197 if (!buf->single) {
1198 pg = (head >> PAGE_SHIFT) & (buf->nr_pages - 1);
1199 te = pt_topa_entry_for_page(buf, pg);
1201 cur_tp = topa_entry_to_page(te);
1202 buf->cur = &cur_tp->topa;
1203 buf->cur_idx = te - TOPA_ENTRY(buf->cur, 0);
1204 buf->output_off = head & (pt_buffer_region_size(buf) - 1);
1205 } else {
1206 buf->output_off = head;
1209 local64_set(&buf->head, head);
1210 local_set(&buf->data_size, 0);
1214 * pt_buffer_fini_topa() - deallocate ToPA structure of a buffer
1215 * @buf: PT buffer.
1217 static void pt_buffer_fini_topa(struct pt_buffer *buf)
1219 struct topa *topa, *iter;
1221 if (buf->single)
1222 return;
1224 list_for_each_entry_safe(topa, iter, &buf->tables, list) {
1226 * right now, this is in free_aux() path only, so
1227 * no need to unlink this table from the list
1229 topa_free(topa);
1234 * pt_buffer_init_topa() - initialize ToPA table for pt buffer
1235 * @buf: PT buffer.
1236 * @cpu: CPU on which to allocate.
1237 * @nr_pages: No. of pages to allocate.
1238 * @gfp: Allocation flags.
1240 * Return: 0 on success or error code.
1242 static int pt_buffer_init_topa(struct pt_buffer *buf, int cpu,
1243 unsigned long nr_pages, gfp_t gfp)
1245 struct topa *topa;
1246 int err;
1248 topa = topa_alloc(cpu, gfp);
1249 if (!topa)
1250 return -ENOMEM;
1252 topa_insert_table(buf, topa);
1254 while (buf->nr_pages < nr_pages) {
1255 err = topa_insert_pages(buf, cpu, gfp);
1256 if (err) {
1257 pt_buffer_fini_topa(buf);
1258 return -ENOMEM;
1262 /* link last table to the first one, unless we're double buffering */
1263 if (intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries)) {
1264 TOPA_ENTRY(buf->last, -1)->base = topa_pfn(buf->first);
1265 TOPA_ENTRY(buf->last, -1)->end = 1;
1268 pt_topa_dump(buf);
1269 return 0;
1272 static int pt_buffer_try_single(struct pt_buffer *buf, int nr_pages)
1274 struct page *p = virt_to_page(buf->data_pages[0]);
1275 int ret = -ENOTSUPP, order = 0;
1278 * We can use single range output mode
1279 * + in snapshot mode, where we don't need interrupts;
1280 * + if the hardware supports it;
1281 * + if the entire buffer is one contiguous allocation.
1283 if (!buf->snapshot)
1284 goto out;
1286 if (!intel_pt_validate_hw_cap(PT_CAP_single_range_output))
1287 goto out;
1289 if (PagePrivate(p))
1290 order = page_private(p);
1292 if (1 << order != nr_pages)
1293 goto out;
1296 * Some processors cannot always support single range for more than
1297 * 4KB - refer errata TGL052, ADL037 and RPL017. Future processors might
1298 * also be affected, so for now rather than trying to keep track of
1299 * which ones, just disable it for all.
1301 if (nr_pages > 1)
1302 goto out;
1304 buf->single = true;
1305 buf->nr_pages = nr_pages;
1306 ret = 0;
1307 out:
1308 return ret;
1312 * pt_buffer_setup_aux() - set up topa tables for a PT buffer
1313 * @event: Performance event
1314 * @pages: Array of pointers to buffer pages passed from perf core.
1315 * @nr_pages: Number of pages in the buffer.
1316 * @snapshot: If this is a snapshot/overwrite counter.
1318 * This is a pmu::setup_aux callback that sets up ToPA tables and all the
1319 * bookkeeping for an AUX buffer.
1321 * Return: Our private PT buffer structure.
1323 static void *
1324 pt_buffer_setup_aux(struct perf_event *event, void **pages,
1325 int nr_pages, bool snapshot)
1327 struct pt_buffer *buf;
1328 int node, ret, cpu = event->cpu;
1330 if (!nr_pages)
1331 return NULL;
1334 * Only support AUX sampling in snapshot mode, where we don't
1335 * generate NMIs.
1337 if (event->attr.aux_sample_size && !snapshot)
1338 return NULL;
1340 if (cpu == -1)
1341 cpu = raw_smp_processor_id();
1342 node = cpu_to_node(cpu);
1344 buf = kzalloc_node(sizeof(struct pt_buffer), GFP_KERNEL, node);
1345 if (!buf)
1346 return NULL;
1348 buf->snapshot = snapshot;
1349 buf->data_pages = pages;
1350 buf->stop_pos = -1;
1351 buf->intr_pos = -1;
1353 INIT_LIST_HEAD(&buf->tables);
1355 ret = pt_buffer_try_single(buf, nr_pages);
1356 if (!ret)
1357 return buf;
1359 ret = pt_buffer_init_topa(buf, cpu, nr_pages, GFP_KERNEL);
1360 if (ret) {
1361 kfree(buf);
1362 return NULL;
1365 return buf;
1369 * pt_buffer_free_aux() - perf AUX deallocation path callback
1370 * @data: PT buffer.
1372 static void pt_buffer_free_aux(void *data)
1374 struct pt_buffer *buf = data;
1376 pt_buffer_fini_topa(buf);
1377 kfree(buf);
1380 static int pt_addr_filters_init(struct perf_event *event)
1382 struct pt_filters *filters;
1383 int node = event->cpu == -1 ? -1 : cpu_to_node(event->cpu);
1385 if (!intel_pt_validate_hw_cap(PT_CAP_num_address_ranges))
1386 return 0;
1388 filters = kzalloc_node(sizeof(struct pt_filters), GFP_KERNEL, node);
1389 if (!filters)
1390 return -ENOMEM;
1392 if (event->parent)
1393 memcpy(filters, event->parent->hw.addr_filters,
1394 sizeof(*filters));
1396 event->hw.addr_filters = filters;
1398 return 0;
1401 static void pt_addr_filters_fini(struct perf_event *event)
1403 kfree(event->hw.addr_filters);
1404 event->hw.addr_filters = NULL;
1407 #ifdef CONFIG_X86_64
1408 /* Clamp to a canonical address greater-than-or-equal-to the address given */
1409 static u64 clamp_to_ge_canonical_addr(u64 vaddr, u8 vaddr_bits)
1411 return __is_canonical_address(vaddr, vaddr_bits) ?
1412 vaddr :
1413 -BIT_ULL(vaddr_bits - 1);
1416 /* Clamp to a canonical address less-than-or-equal-to the address given */
1417 static u64 clamp_to_le_canonical_addr(u64 vaddr, u8 vaddr_bits)
1419 return __is_canonical_address(vaddr, vaddr_bits) ?
1420 vaddr :
1421 BIT_ULL(vaddr_bits - 1) - 1;
1423 #else
1424 #define clamp_to_ge_canonical_addr(x, y) (x)
1425 #define clamp_to_le_canonical_addr(x, y) (x)
1426 #endif
1428 static int pt_event_addr_filters_validate(struct list_head *filters)
1430 struct perf_addr_filter *filter;
1431 int range = 0;
1433 list_for_each_entry(filter, filters, entry) {
1435 * PT doesn't support single address triggers and
1436 * 'start' filters.
1438 if (!filter->size ||
1439 filter->action == PERF_ADDR_FILTER_ACTION_START)
1440 return -EOPNOTSUPP;
1442 if (++range > intel_pt_validate_hw_cap(PT_CAP_num_address_ranges))
1443 return -EOPNOTSUPP;
1446 return 0;
1449 static void pt_event_addr_filters_sync(struct perf_event *event)
1451 struct perf_addr_filters_head *head = perf_event_addr_filters(event);
1452 unsigned long msr_a, msr_b;
1453 struct perf_addr_filter_range *fr = event->addr_filter_ranges;
1454 struct pt_filters *filters = event->hw.addr_filters;
1455 struct perf_addr_filter *filter;
1456 int range = 0;
1458 if (!filters)
1459 return;
1461 list_for_each_entry(filter, &head->list, entry) {
1462 if (filter->path.dentry && !fr[range].start) {
1463 msr_a = msr_b = 0;
1464 } else {
1465 unsigned long n = fr[range].size - 1;
1466 unsigned long a = fr[range].start;
1467 unsigned long b;
1469 if (a > ULONG_MAX - n)
1470 b = ULONG_MAX;
1471 else
1472 b = a + n;
1474 * Apply the offset. 64-bit addresses written to the
1475 * MSRs must be canonical, but the range can encompass
1476 * non-canonical addresses. Since software cannot
1477 * execute at non-canonical addresses, adjusting to
1478 * canonical addresses does not affect the result of the
1479 * address filter.
1481 msr_a = clamp_to_ge_canonical_addr(a, boot_cpu_data.x86_virt_bits);
1482 msr_b = clamp_to_le_canonical_addr(b, boot_cpu_data.x86_virt_bits);
1483 if (msr_b < msr_a)
1484 msr_a = msr_b = 0;
1487 filters->filter[range].msr_a = msr_a;
1488 filters->filter[range].msr_b = msr_b;
1489 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER)
1490 filters->filter[range].config = 1;
1491 else
1492 filters->filter[range].config = 2;
1493 range++;
1496 filters->nr_filters = range;
1500 * intel_pt_interrupt() - PT PMI handler
1502 void intel_pt_interrupt(void)
1504 struct pt *pt = this_cpu_ptr(&pt_ctx);
1505 struct pt_buffer *buf;
1506 struct perf_event *event = pt->handle.event;
1509 * There may be a dangling PT bit in the interrupt status register
1510 * after PT has been disabled by pt_event_stop(). Make sure we don't
1511 * do anything (particularly, re-enable) for this event here.
1513 if (!READ_ONCE(pt->handle_nmi))
1514 return;
1516 if (!event)
1517 return;
1519 pt_config_stop(event);
1521 buf = perf_get_aux(&pt->handle);
1522 if (!buf)
1523 return;
1525 pt_read_offset(buf);
1527 pt_handle_status(pt);
1529 pt_update_head(pt);
1531 perf_aux_output_end(&pt->handle, local_xchg(&buf->data_size, 0));
1533 if (!event->hw.state) {
1534 int ret;
1536 buf = perf_aux_output_begin(&pt->handle, event);
1537 if (!buf) {
1538 event->hw.state = PERF_HES_STOPPED;
1539 WRITE_ONCE(pt->resume_allowed, 0);
1540 return;
1543 pt_buffer_reset_offsets(buf, pt->handle.head);
1544 /* snapshot counters don't use PMI, so it's safe */
1545 ret = pt_buffer_reset_markers(buf, &pt->handle);
1546 if (ret) {
1547 perf_aux_output_end(&pt->handle, 0);
1548 WRITE_ONCE(pt->resume_allowed, 0);
1549 return;
1552 pt_config_buffer(buf);
1553 pt_config_start(event);
1557 void intel_pt_handle_vmx(int on)
1559 struct pt *pt = this_cpu_ptr(&pt_ctx);
1560 struct perf_event *event;
1561 unsigned long flags;
1563 /* PT plays nice with VMX, do nothing */
1564 if (pt_pmu.vmx)
1565 return;
1568 * VMXON will clear RTIT_CTL.TraceEn; we need to make
1569 * sure to not try to set it while VMX is on. Disable
1570 * interrupts to avoid racing with pmu callbacks;
1571 * concurrent PMI should be handled fine.
1573 local_irq_save(flags);
1574 WRITE_ONCE(pt->vmx_on, on);
1577 * If an AUX transaction is in progress, it will contain
1578 * gap(s), so flag it PARTIAL to inform the user.
1580 event = pt->handle.event;
1581 if (event)
1582 perf_aux_output_flag(&pt->handle,
1583 PERF_AUX_FLAG_PARTIAL);
1585 /* Turn PTs back on */
1586 if (!on && event)
1587 wrmsrl(MSR_IA32_RTIT_CTL, event->hw.aux_config);
1589 local_irq_restore(flags);
1591 EXPORT_SYMBOL_GPL(intel_pt_handle_vmx);
1594 * PMU callbacks
1597 static void pt_event_start(struct perf_event *event, int mode)
1599 struct hw_perf_event *hwc = &event->hw;
1600 struct pt *pt = this_cpu_ptr(&pt_ctx);
1601 struct pt_buffer *buf;
1603 if (mode & PERF_EF_RESUME) {
1604 if (READ_ONCE(pt->resume_allowed)) {
1605 u64 status;
1608 * Only if the trace is not active and the error and
1609 * stopped bits are clear, is it safe to start, but a
1610 * PMI might have just cleared these, so resume_allowed
1611 * must be checked again also.
1613 rdmsrl(MSR_IA32_RTIT_STATUS, status);
1614 if (!(status & (RTIT_STATUS_TRIGGEREN |
1615 RTIT_STATUS_ERROR |
1616 RTIT_STATUS_STOPPED)) &&
1617 READ_ONCE(pt->resume_allowed))
1618 pt_config_start(event);
1620 return;
1623 buf = perf_aux_output_begin(&pt->handle, event);
1624 if (!buf)
1625 goto fail_stop;
1627 pt_buffer_reset_offsets(buf, pt->handle.head);
1628 if (!buf->snapshot) {
1629 if (pt_buffer_reset_markers(buf, &pt->handle))
1630 goto fail_end_stop;
1633 hwc->state = 0;
1635 pt_config_buffer(buf);
1636 pt_config(event);
1638 return;
1640 fail_end_stop:
1641 perf_aux_output_end(&pt->handle, 0);
1642 fail_stop:
1643 hwc->state = PERF_HES_STOPPED;
1646 static void pt_event_stop(struct perf_event *event, int mode)
1648 struct pt *pt = this_cpu_ptr(&pt_ctx);
1650 if (mode & PERF_EF_PAUSE) {
1651 if (READ_ONCE(pt->pause_allowed))
1652 pt_config_stop(event);
1653 return;
1657 * Protect against the PMI racing with disabling wrmsr,
1658 * see comment in intel_pt_interrupt().
1660 WRITE_ONCE(pt->handle_nmi, 0);
1661 barrier();
1664 * Prevent a resume from attempting to restart tracing, or a pause
1665 * during a subsequent start. Do this after clearing handle_nmi so that
1666 * pt_event_snapshot_aux() will not re-allow them.
1668 WRITE_ONCE(pt->pause_allowed, 0);
1669 WRITE_ONCE(pt->resume_allowed, 0);
1670 barrier();
1672 pt_config_stop(event);
1674 if (event->hw.state == PERF_HES_STOPPED)
1675 return;
1677 event->hw.state = PERF_HES_STOPPED;
1679 if (mode & PERF_EF_UPDATE) {
1680 struct pt_buffer *buf = perf_get_aux(&pt->handle);
1682 if (!buf)
1683 return;
1685 if (WARN_ON_ONCE(pt->handle.event != event))
1686 return;
1688 pt_read_offset(buf);
1690 pt_handle_status(pt);
1692 pt_update_head(pt);
1694 if (buf->snapshot)
1695 pt->handle.head =
1696 local_xchg(&buf->data_size,
1697 buf->nr_pages << PAGE_SHIFT);
1698 perf_aux_output_end(&pt->handle, local_xchg(&buf->data_size, 0));
1702 static long pt_event_snapshot_aux(struct perf_event *event,
1703 struct perf_output_handle *handle,
1704 unsigned long size)
1706 struct pt *pt = this_cpu_ptr(&pt_ctx);
1707 struct pt_buffer *buf = perf_get_aux(&pt->handle);
1708 unsigned long from = 0, to;
1709 long ret;
1711 if (WARN_ON_ONCE(!buf))
1712 return 0;
1715 * Sampling is only allowed on snapshot events;
1716 * see pt_buffer_setup_aux().
1718 if (WARN_ON_ONCE(!buf->snapshot))
1719 return 0;
1721 /* Prevent pause/resume from attempting to start/stop tracing */
1722 WRITE_ONCE(pt->pause_allowed, 0);
1723 WRITE_ONCE(pt->resume_allowed, 0);
1724 barrier();
1726 * There is no PT interrupt in this mode, so stop the trace and it will
1727 * remain stopped while the buffer is copied.
1729 pt_config_stop(event);
1730 pt_read_offset(buf);
1731 pt_update_head(pt);
1733 to = local_read(&buf->data_size);
1734 if (to < size)
1735 from = buf->nr_pages << PAGE_SHIFT;
1736 from += to - size;
1738 ret = perf_output_copy_aux(&pt->handle, handle, from, to);
1741 * Here, handle_nmi tells us if the tracing was on.
1742 * If the tracing was on, restart it.
1744 if (READ_ONCE(pt->handle_nmi)) {
1745 WRITE_ONCE(pt->resume_allowed, 1);
1746 barrier();
1747 pt_config_start(event);
1748 barrier();
1749 WRITE_ONCE(pt->pause_allowed, 1);
1752 return ret;
1755 static void pt_event_del(struct perf_event *event, int mode)
1757 pt_event_stop(event, PERF_EF_UPDATE);
1760 static int pt_event_add(struct perf_event *event, int mode)
1762 struct pt *pt = this_cpu_ptr(&pt_ctx);
1763 struct hw_perf_event *hwc = &event->hw;
1764 int ret = -EBUSY;
1766 if (pt->handle.event)
1767 goto fail;
1769 if (mode & PERF_EF_START) {
1770 pt_event_start(event, 0);
1771 ret = -EINVAL;
1772 if (hwc->state == PERF_HES_STOPPED)
1773 goto fail;
1774 } else {
1775 hwc->state = PERF_HES_STOPPED;
1778 ret = 0;
1779 fail:
1781 return ret;
1784 static void pt_event_read(struct perf_event *event)
1788 static void pt_event_destroy(struct perf_event *event)
1790 pt_addr_filters_fini(event);
1791 x86_del_exclusive(x86_lbr_exclusive_pt);
1794 static int pt_event_init(struct perf_event *event)
1796 if (event->attr.type != pt_pmu.pmu.type)
1797 return -ENOENT;
1799 if (!pt_event_valid(event))
1800 return -EINVAL;
1802 if (x86_add_exclusive(x86_lbr_exclusive_pt))
1803 return -EBUSY;
1805 if (pt_addr_filters_init(event)) {
1806 x86_del_exclusive(x86_lbr_exclusive_pt);
1807 return -ENOMEM;
1810 event->destroy = pt_event_destroy;
1812 return 0;
1815 void cpu_emergency_stop_pt(void)
1817 struct pt *pt = this_cpu_ptr(&pt_ctx);
1819 if (pt->handle.event)
1820 pt_event_stop(pt->handle.event, PERF_EF_UPDATE);
1823 int is_intel_pt_event(struct perf_event *event)
1825 return event->pmu == &pt_pmu.pmu;
1828 static __init int pt_init(void)
1830 int ret, cpu, prior_warn = 0;
1832 BUILD_BUG_ON(sizeof(struct topa) > PAGE_SIZE);
1834 if (!boot_cpu_has(X86_FEATURE_INTEL_PT))
1835 return -ENODEV;
1837 cpus_read_lock();
1838 for_each_online_cpu(cpu) {
1839 u64 ctl;
1841 ret = rdmsrl_safe_on_cpu(cpu, MSR_IA32_RTIT_CTL, &ctl);
1842 if (!ret && (ctl & RTIT_CTL_TRACEEN))
1843 prior_warn++;
1845 cpus_read_unlock();
1847 if (prior_warn) {
1848 x86_add_exclusive(x86_lbr_exclusive_pt);
1849 pr_warn("PT is enabled at boot time, doing nothing\n");
1851 return -EBUSY;
1854 ret = pt_pmu_hw_init();
1855 if (ret)
1856 return ret;
1858 if (!intel_pt_validate_hw_cap(PT_CAP_topa_output)) {
1859 pr_warn("ToPA output is not supported on this CPU\n");
1860 return -ENODEV;
1863 if (!intel_pt_validate_hw_cap(PT_CAP_topa_multiple_entries))
1864 pt_pmu.pmu.capabilities = PERF_PMU_CAP_AUX_NO_SG;
1866 pt_pmu.pmu.capabilities |= PERF_PMU_CAP_EXCLUSIVE |
1867 PERF_PMU_CAP_ITRACE |
1868 PERF_PMU_CAP_AUX_PAUSE;
1869 pt_pmu.pmu.attr_groups = pt_attr_groups;
1870 pt_pmu.pmu.task_ctx_nr = perf_sw_context;
1871 pt_pmu.pmu.event_init = pt_event_init;
1872 pt_pmu.pmu.add = pt_event_add;
1873 pt_pmu.pmu.del = pt_event_del;
1874 pt_pmu.pmu.start = pt_event_start;
1875 pt_pmu.pmu.stop = pt_event_stop;
1876 pt_pmu.pmu.snapshot_aux = pt_event_snapshot_aux;
1877 pt_pmu.pmu.read = pt_event_read;
1878 pt_pmu.pmu.setup_aux = pt_buffer_setup_aux;
1879 pt_pmu.pmu.free_aux = pt_buffer_free_aux;
1880 pt_pmu.pmu.addr_filters_sync = pt_event_addr_filters_sync;
1881 pt_pmu.pmu.addr_filters_validate = pt_event_addr_filters_validate;
1882 pt_pmu.pmu.nr_addr_filters =
1883 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges);
1885 ret = perf_pmu_register(&pt_pmu.pmu, "intel_pt", -1);
1887 return ret;
1889 arch_initcall(pt_init);