]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - arch/x86/kernel/cpu/perf_event_intel_pt.c
Merge branch 'fixes' of git://ftp.arm.linux.org.uk/~rmk/linux-arm
[karo-tx-linux.git] / arch / x86 / kernel / cpu / perf_event_intel_pt.c
1 /*
2  * Intel(R) Processor Trace PMU driver for perf
3  * Copyright (c) 2013-2014, Intel Corporation.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  *
14  * Intel PT is specified in the Intel Architecture Instruction Set Extensions
15  * Programming Reference:
16  * http://software.intel.com/en-us/intel-isa-extensions
17  */
18
19 #undef DEBUG
20
21 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
22
23 #include <linux/types.h>
24 #include <linux/slab.h>
25 #include <linux/device.h>
26
27 #include <asm/perf_event.h>
28 #include <asm/insn.h>
29 #include <asm/io.h>
30
31 #include "perf_event.h"
32 #include "intel_pt.h"
33
34 static DEFINE_PER_CPU(struct pt, pt_ctx);
35
36 static struct pt_pmu pt_pmu;
37
38 enum cpuid_regs {
39         CR_EAX = 0,
40         CR_ECX,
41         CR_EDX,
42         CR_EBX
43 };
44
45 /*
46  * Capabilities of Intel PT hardware, such as number of address bits or
47  * supported output schemes, are cached and exported to userspace as "caps"
48  * attribute group of pt pmu device
49  * (/sys/bus/event_source/devices/intel_pt/caps/) so that userspace can store
50  * relevant bits together with intel_pt traces.
51  *
52  * These are necessary for both trace decoding (payloads_lip, contains address
53  * width encoded in IP-related packets), and event configuration (bitmasks with
54  * permitted values for certain bit fields).
55  */
56 #define PT_CAP(_n, _l, _r, _m)                                          \
57         [PT_CAP_ ## _n] = { .name = __stringify(_n), .leaf = _l,        \
58                             .reg = _r, .mask = _m }
59
60 static struct pt_cap_desc {
61         const char      *name;
62         u32             leaf;
63         u8              reg;
64         u32             mask;
65 } pt_caps[] = {
66         PT_CAP(max_subleaf,             0, CR_EAX, 0xffffffff),
67         PT_CAP(cr3_filtering,           0, CR_EBX, BIT(0)),
68         PT_CAP(psb_cyc,                 0, CR_EBX, BIT(1)),
69         PT_CAP(mtc,                     0, CR_EBX, BIT(3)),
70         PT_CAP(topa_output,             0, CR_ECX, BIT(0)),
71         PT_CAP(topa_multiple_entries,   0, CR_ECX, BIT(1)),
72         PT_CAP(single_range_output,     0, CR_ECX, BIT(2)),
73         PT_CAP(payloads_lip,            0, CR_ECX, BIT(31)),
74         PT_CAP(mtc_periods,             1, CR_EAX, 0xffff0000),
75         PT_CAP(cycle_thresholds,        1, CR_EBX, 0xffff),
76         PT_CAP(psb_periods,             1, CR_EBX, 0xffff0000),
77 };
78
79 static u32 pt_cap_get(enum pt_capabilities cap)
80 {
81         struct pt_cap_desc *cd = &pt_caps[cap];
82         u32 c = pt_pmu.caps[cd->leaf * PT_CPUID_REGS_NUM + cd->reg];
83         unsigned int shift = __ffs(cd->mask);
84
85         return (c & cd->mask) >> shift;
86 }
87
88 static ssize_t pt_cap_show(struct device *cdev,
89                            struct device_attribute *attr,
90                            char *buf)
91 {
92         struct dev_ext_attribute *ea =
93                 container_of(attr, struct dev_ext_attribute, attr);
94         enum pt_capabilities cap = (long)ea->var;
95
96         return snprintf(buf, PAGE_SIZE, "%x\n", pt_cap_get(cap));
97 }
98
99 static struct attribute_group pt_cap_group = {
100         .name   = "caps",
101 };
102
103 PMU_FORMAT_ATTR(cyc,            "config:1"      );
104 PMU_FORMAT_ATTR(mtc,            "config:9"      );
105 PMU_FORMAT_ATTR(tsc,            "config:10"     );
106 PMU_FORMAT_ATTR(noretcomp,      "config:11"     );
107 PMU_FORMAT_ATTR(mtc_period,     "config:14-17"  );
108 PMU_FORMAT_ATTR(cyc_thresh,     "config:19-22"  );
109 PMU_FORMAT_ATTR(psb_period,     "config:24-27"  );
110
111 static struct attribute *pt_formats_attr[] = {
112         &format_attr_cyc.attr,
113         &format_attr_mtc.attr,
114         &format_attr_tsc.attr,
115         &format_attr_noretcomp.attr,
116         &format_attr_mtc_period.attr,
117         &format_attr_cyc_thresh.attr,
118         &format_attr_psb_period.attr,
119         NULL,
120 };
121
122 static struct attribute_group pt_format_group = {
123         .name   = "format",
124         .attrs  = pt_formats_attr,
125 };
126
127 static const struct attribute_group *pt_attr_groups[] = {
128         &pt_cap_group,
129         &pt_format_group,
130         NULL,
131 };
132
133 static int __init pt_pmu_hw_init(void)
134 {
135         struct dev_ext_attribute *de_attrs;
136         struct attribute **attrs;
137         size_t size;
138         int ret;
139         long i;
140
141         attrs = NULL;
142         ret = -ENODEV;
143         if (!test_cpu_cap(&boot_cpu_data, X86_FEATURE_INTEL_PT))
144                 goto fail;
145
146         for (i = 0; i < PT_CPUID_LEAVES; i++) {
147                 cpuid_count(20, i,
148                             &pt_pmu.caps[CR_EAX + i*PT_CPUID_REGS_NUM],
149                             &pt_pmu.caps[CR_EBX + i*PT_CPUID_REGS_NUM],
150                             &pt_pmu.caps[CR_ECX + i*PT_CPUID_REGS_NUM],
151                             &pt_pmu.caps[CR_EDX + i*PT_CPUID_REGS_NUM]);
152         }
153
154         ret = -ENOMEM;
155         size = sizeof(struct attribute *) * (ARRAY_SIZE(pt_caps)+1);
156         attrs = kzalloc(size, GFP_KERNEL);
157         if (!attrs)
158                 goto fail;
159
160         size = sizeof(struct dev_ext_attribute) * (ARRAY_SIZE(pt_caps)+1);
161         de_attrs = kzalloc(size, GFP_KERNEL);
162         if (!de_attrs)
163                 goto fail;
164
165         for (i = 0; i < ARRAY_SIZE(pt_caps); i++) {
166                 struct dev_ext_attribute *de_attr = de_attrs + i;
167
168                 de_attr->attr.attr.name = pt_caps[i].name;
169
170                 sysfs_attr_init(&de_attr->attr.attr);
171
172                 de_attr->attr.attr.mode         = S_IRUGO;
173                 de_attr->attr.show              = pt_cap_show;
174                 de_attr->var                    = (void *)i;
175
176                 attrs[i] = &de_attr->attr.attr;
177         }
178
179         pt_cap_group.attrs = attrs;
180
181         return 0;
182
183 fail:
184         kfree(attrs);
185
186         return ret;
187 }
188
189 #define RTIT_CTL_CYC_PSB (RTIT_CTL_CYCLEACC     | \
190                           RTIT_CTL_CYC_THRESH   | \
191                           RTIT_CTL_PSB_FREQ)
192
193 #define RTIT_CTL_MTC    (RTIT_CTL_MTC_EN        | \
194                          RTIT_CTL_MTC_RANGE)
195
196 #define PT_CONFIG_MASK (RTIT_CTL_TSC_EN         | \
197                         RTIT_CTL_DISRETC        | \
198                         RTIT_CTL_CYC_PSB        | \
199                         RTIT_CTL_MTC)
200
201 static bool pt_event_valid(struct perf_event *event)
202 {
203         u64 config = event->attr.config;
204         u64 allowed, requested;
205
206         if ((config & PT_CONFIG_MASK) != config)
207                 return false;
208
209         if (config & RTIT_CTL_CYC_PSB) {
210                 if (!pt_cap_get(PT_CAP_psb_cyc))
211                         return false;
212
213                 allowed = pt_cap_get(PT_CAP_psb_periods);
214                 requested = (config & RTIT_CTL_PSB_FREQ) >>
215                         RTIT_CTL_PSB_FREQ_OFFSET;
216                 if (requested && (!(allowed & BIT(requested))))
217                         return false;
218
219                 allowed = pt_cap_get(PT_CAP_cycle_thresholds);
220                 requested = (config & RTIT_CTL_CYC_THRESH) >>
221                         RTIT_CTL_CYC_THRESH_OFFSET;
222                 if (requested && (!(allowed & BIT(requested))))
223                         return false;
224         }
225
226         if (config & RTIT_CTL_MTC) {
227                 /*
228                  * In the unlikely case that CPUID lists valid mtc periods,
229                  * but not the mtc capability, drop out here.
230                  *
231                  * Spec says that setting mtc period bits while mtc bit in
232                  * CPUID is 0 will #GP, so better safe than sorry.
233                  */
234                 if (!pt_cap_get(PT_CAP_mtc))
235                         return false;
236
237                 allowed = pt_cap_get(PT_CAP_mtc_periods);
238                 if (!allowed)
239                         return false;
240
241                 requested = (config & RTIT_CTL_MTC_RANGE) >>
242                         RTIT_CTL_MTC_RANGE_OFFSET;
243
244                 if (!(allowed & BIT(requested)))
245                         return false;
246         }
247
248         return true;
249 }
250
251 /*
252  * PT configuration helpers
253  * These all are cpu affine and operate on a local PT
254  */
255
256 static void pt_config(struct perf_event *event)
257 {
258         u64 reg;
259
260         if (!event->hw.itrace_started) {
261                 event->hw.itrace_started = 1;
262                 wrmsrl(MSR_IA32_RTIT_STATUS, 0);
263         }
264
265         reg = RTIT_CTL_TOPA | RTIT_CTL_BRANCH_EN | RTIT_CTL_TRACEEN;
266
267         if (!event->attr.exclude_kernel)
268                 reg |= RTIT_CTL_OS;
269         if (!event->attr.exclude_user)
270                 reg |= RTIT_CTL_USR;
271
272         reg |= (event->attr.config & PT_CONFIG_MASK);
273
274         wrmsrl(MSR_IA32_RTIT_CTL, reg);
275 }
276
277 static void pt_config_start(bool start)
278 {
279         u64 ctl;
280
281         rdmsrl(MSR_IA32_RTIT_CTL, ctl);
282         if (start)
283                 ctl |= RTIT_CTL_TRACEEN;
284         else
285                 ctl &= ~RTIT_CTL_TRACEEN;
286         wrmsrl(MSR_IA32_RTIT_CTL, ctl);
287
288         /*
289          * A wrmsr that disables trace generation serializes other PT
290          * registers and causes all data packets to be written to memory,
291          * but a fence is required for the data to become globally visible.
292          *
293          * The below WMB, separating data store and aux_head store matches
294          * the consumer's RMB that separates aux_head load and data load.
295          */
296         if (!start)
297                 wmb();
298 }
299
300 static void pt_config_buffer(void *buf, unsigned int topa_idx,
301                              unsigned int output_off)
302 {
303         u64 reg;
304
305         wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, virt_to_phys(buf));
306
307         reg = 0x7f | ((u64)topa_idx << 7) | ((u64)output_off << 32);
308
309         wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, reg);
310 }
311
312 /*
313  * Keep ToPA table-related metadata on the same page as the actual table,
314  * taking up a few words from the top
315  */
316
317 #define TENTS_PER_PAGE (((PAGE_SIZE - 40) / sizeof(struct topa_entry)) - 1)
318
319 /**
320  * struct topa - page-sized ToPA table with metadata at the top
321  * @table:      actual ToPA table entries, as understood by PT hardware
322  * @list:       linkage to struct pt_buffer's list of tables
323  * @phys:       physical address of this page
324  * @offset:     offset of the first entry in this table in the buffer
325  * @size:       total size of all entries in this table
326  * @last:       index of the last initialized entry in this table
327  */
328 struct topa {
329         struct topa_entry       table[TENTS_PER_PAGE];
330         struct list_head        list;
331         u64                     phys;
332         u64                     offset;
333         size_t                  size;
334         int                     last;
335 };
336
337 /* make -1 stand for the last table entry */
338 #define TOPA_ENTRY(t, i) ((i) == -1 ? &(t)->table[(t)->last] : &(t)->table[(i)])
339
340 /**
341  * topa_alloc() - allocate page-sized ToPA table
342  * @cpu:        CPU on which to allocate.
343  * @gfp:        Allocation flags.
344  *
345  * Return:      On success, return the pointer to ToPA table page.
346  */
347 static struct topa *topa_alloc(int cpu, gfp_t gfp)
348 {
349         int node = cpu_to_node(cpu);
350         struct topa *topa;
351         struct page *p;
352
353         p = alloc_pages_node(node, gfp | __GFP_ZERO, 0);
354         if (!p)
355                 return NULL;
356
357         topa = page_address(p);
358         topa->last = 0;
359         topa->phys = page_to_phys(p);
360
361         /*
362          * In case of singe-entry ToPA, always put the self-referencing END
363          * link as the 2nd entry in the table
364          */
365         if (!pt_cap_get(PT_CAP_topa_multiple_entries)) {
366                 TOPA_ENTRY(topa, 1)->base = topa->phys >> TOPA_SHIFT;
367                 TOPA_ENTRY(topa, 1)->end = 1;
368         }
369
370         return topa;
371 }
372
373 /**
374  * topa_free() - free a page-sized ToPA table
375  * @topa:       Table to deallocate.
376  */
377 static void topa_free(struct topa *topa)
378 {
379         free_page((unsigned long)topa);
380 }
381
382 /**
383  * topa_insert_table() - insert a ToPA table into a buffer
384  * @buf:         PT buffer that's being extended.
385  * @topa:        New topa table to be inserted.
386  *
387  * If it's the first table in this buffer, set up buffer's pointers
388  * accordingly; otherwise, add a END=1 link entry to @topa to the current
389  * "last" table and adjust the last table pointer to @topa.
390  */
391 static void topa_insert_table(struct pt_buffer *buf, struct topa *topa)
392 {
393         struct topa *last = buf->last;
394
395         list_add_tail(&topa->list, &buf->tables);
396
397         if (!buf->first) {
398                 buf->first = buf->last = buf->cur = topa;
399                 return;
400         }
401
402         topa->offset = last->offset + last->size;
403         buf->last = topa;
404
405         if (!pt_cap_get(PT_CAP_topa_multiple_entries))
406                 return;
407
408         BUG_ON(last->last != TENTS_PER_PAGE - 1);
409
410         TOPA_ENTRY(last, -1)->base = topa->phys >> TOPA_SHIFT;
411         TOPA_ENTRY(last, -1)->end = 1;
412 }
413
414 /**
415  * topa_table_full() - check if a ToPA table is filled up
416  * @topa:       ToPA table.
417  */
418 static bool topa_table_full(struct topa *topa)
419 {
420         /* single-entry ToPA is a special case */
421         if (!pt_cap_get(PT_CAP_topa_multiple_entries))
422                 return !!topa->last;
423
424         return topa->last == TENTS_PER_PAGE - 1;
425 }
426
427 /**
428  * topa_insert_pages() - create a list of ToPA tables
429  * @buf:        PT buffer being initialized.
430  * @gfp:        Allocation flags.
431  *
432  * This initializes a list of ToPA tables with entries from
433  * the data_pages provided by rb_alloc_aux().
434  *
435  * Return:      0 on success or error code.
436  */
437 static int topa_insert_pages(struct pt_buffer *buf, gfp_t gfp)
438 {
439         struct topa *topa = buf->last;
440         int order = 0;
441         struct page *p;
442
443         p = virt_to_page(buf->data_pages[buf->nr_pages]);
444         if (PagePrivate(p))
445                 order = page_private(p);
446
447         if (topa_table_full(topa)) {
448                 topa = topa_alloc(buf->cpu, gfp);
449                 if (!topa)
450                         return -ENOMEM;
451
452                 topa_insert_table(buf, topa);
453         }
454
455         TOPA_ENTRY(topa, -1)->base = page_to_phys(p) >> TOPA_SHIFT;
456         TOPA_ENTRY(topa, -1)->size = order;
457         if (!buf->snapshot && !pt_cap_get(PT_CAP_topa_multiple_entries)) {
458                 TOPA_ENTRY(topa, -1)->intr = 1;
459                 TOPA_ENTRY(topa, -1)->stop = 1;
460         }
461
462         topa->last++;
463         topa->size += sizes(order);
464
465         buf->nr_pages += 1ul << order;
466
467         return 0;
468 }
469
470 /**
471  * pt_topa_dump() - print ToPA tables and their entries
472  * @buf:        PT buffer.
473  */
474 static void pt_topa_dump(struct pt_buffer *buf)
475 {
476         struct topa *topa;
477
478         list_for_each_entry(topa, &buf->tables, list) {
479                 int i;
480
481                 pr_debug("# table @%p (%016Lx), off %llx size %zx\n", topa->table,
482                          topa->phys, topa->offset, topa->size);
483                 for (i = 0; i < TENTS_PER_PAGE; i++) {
484                         pr_debug("# entry @%p (%lx sz %u %c%c%c) raw=%16llx\n",
485                                  &topa->table[i],
486                                  (unsigned long)topa->table[i].base << TOPA_SHIFT,
487                                  sizes(topa->table[i].size),
488                                  topa->table[i].end ?  'E' : ' ',
489                                  topa->table[i].intr ? 'I' : ' ',
490                                  topa->table[i].stop ? 'S' : ' ',
491                                  *(u64 *)&topa->table[i]);
492                         if ((pt_cap_get(PT_CAP_topa_multiple_entries) &&
493                              topa->table[i].stop) ||
494                             topa->table[i].end)
495                                 break;
496                 }
497         }
498 }
499
500 /**
501  * pt_buffer_advance() - advance to the next output region
502  * @buf:        PT buffer.
503  *
504  * Advance the current pointers in the buffer to the next ToPA entry.
505  */
506 static void pt_buffer_advance(struct pt_buffer *buf)
507 {
508         buf->output_off = 0;
509         buf->cur_idx++;
510
511         if (buf->cur_idx == buf->cur->last) {
512                 if (buf->cur == buf->last)
513                         buf->cur = buf->first;
514                 else
515                         buf->cur = list_entry(buf->cur->list.next, struct topa,
516                                               list);
517                 buf->cur_idx = 0;
518         }
519 }
520
521 /**
522  * pt_update_head() - calculate current offsets and sizes
523  * @pt:         Per-cpu pt context.
524  *
525  * Update buffer's current write pointer position and data size.
526  */
527 static void pt_update_head(struct pt *pt)
528 {
529         struct pt_buffer *buf = perf_get_aux(&pt->handle);
530         u64 topa_idx, base, old;
531
532         /* offset of the first region in this table from the beginning of buf */
533         base = buf->cur->offset + buf->output_off;
534
535         /* offset of the current output region within this table */
536         for (topa_idx = 0; topa_idx < buf->cur_idx; topa_idx++)
537                 base += sizes(buf->cur->table[topa_idx].size);
538
539         if (buf->snapshot) {
540                 local_set(&buf->data_size, base);
541         } else {
542                 old = (local64_xchg(&buf->head, base) &
543                        ((buf->nr_pages << PAGE_SHIFT) - 1));
544                 if (base < old)
545                         base += buf->nr_pages << PAGE_SHIFT;
546
547                 local_add(base - old, &buf->data_size);
548         }
549 }
550
551 /**
552  * pt_buffer_region() - obtain current output region's address
553  * @buf:        PT buffer.
554  */
555 static void *pt_buffer_region(struct pt_buffer *buf)
556 {
557         return phys_to_virt(buf->cur->table[buf->cur_idx].base << TOPA_SHIFT);
558 }
559
560 /**
561  * pt_buffer_region_size() - obtain current output region's size
562  * @buf:        PT buffer.
563  */
564 static size_t pt_buffer_region_size(struct pt_buffer *buf)
565 {
566         return sizes(buf->cur->table[buf->cur_idx].size);
567 }
568
569 /**
570  * pt_handle_status() - take care of possible status conditions
571  * @pt:         Per-cpu pt context.
572  */
573 static void pt_handle_status(struct pt *pt)
574 {
575         struct pt_buffer *buf = perf_get_aux(&pt->handle);
576         int advance = 0;
577         u64 status;
578
579         rdmsrl(MSR_IA32_RTIT_STATUS, status);
580
581         if (status & RTIT_STATUS_ERROR) {
582                 pr_err_ratelimited("ToPA ERROR encountered, trying to recover\n");
583                 pt_topa_dump(buf);
584                 status &= ~RTIT_STATUS_ERROR;
585         }
586
587         if (status & RTIT_STATUS_STOPPED) {
588                 status &= ~RTIT_STATUS_STOPPED;
589
590                 /*
591                  * On systems that only do single-entry ToPA, hitting STOP
592                  * means we are already losing data; need to let the decoder
593                  * know.
594                  */
595                 if (!pt_cap_get(PT_CAP_topa_multiple_entries) ||
596                     buf->output_off == sizes(TOPA_ENTRY(buf->cur, buf->cur_idx)->size)) {
597                         local_inc(&buf->lost);
598                         advance++;
599                 }
600         }
601
602         /*
603          * Also on single-entry ToPA implementations, interrupt will come
604          * before the output reaches its output region's boundary.
605          */
606         if (!pt_cap_get(PT_CAP_topa_multiple_entries) && !buf->snapshot &&
607             pt_buffer_region_size(buf) - buf->output_off <= TOPA_PMI_MARGIN) {
608                 void *head = pt_buffer_region(buf);
609
610                 /* everything within this margin needs to be zeroed out */
611                 memset(head + buf->output_off, 0,
612                        pt_buffer_region_size(buf) -
613                        buf->output_off);
614                 advance++;
615         }
616
617         if (advance)
618                 pt_buffer_advance(buf);
619
620         wrmsrl(MSR_IA32_RTIT_STATUS, status);
621 }
622
623 /**
624  * pt_read_offset() - translate registers into buffer pointers
625  * @buf:        PT buffer.
626  *
627  * Set buffer's output pointers from MSR values.
628  */
629 static void pt_read_offset(struct pt_buffer *buf)
630 {
631         u64 offset, base_topa;
632
633         rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, base_topa);
634         buf->cur = phys_to_virt(base_topa);
635
636         rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, offset);
637         /* offset within current output region */
638         buf->output_off = offset >> 32;
639         /* index of current output region within this table */
640         buf->cur_idx = (offset & 0xffffff80) >> 7;
641 }
642
643 /**
644  * pt_topa_next_entry() - obtain index of the first page in the next ToPA entry
645  * @buf:        PT buffer.
646  * @pg:         Page offset in the buffer.
647  *
648  * When advancing to the next output region (ToPA entry), given a page offset
649  * into the buffer, we need to find the offset of the first page in the next
650  * region.
651  */
652 static unsigned int pt_topa_next_entry(struct pt_buffer *buf, unsigned int pg)
653 {
654         struct topa_entry *te = buf->topa_index[pg];
655
656         /* one region */
657         if (buf->first == buf->last && buf->first->last == 1)
658                 return pg;
659
660         do {
661                 pg++;
662                 pg &= buf->nr_pages - 1;
663         } while (buf->topa_index[pg] == te);
664
665         return pg;
666 }
667
668 /**
669  * pt_buffer_reset_markers() - place interrupt and stop bits in the buffer
670  * @buf:        PT buffer.
671  * @handle:     Current output handle.
672  *
673  * Place INT and STOP marks to prevent overwriting old data that the consumer
674  * hasn't yet collected and waking up the consumer after a certain fraction of
675  * the buffer has filled up. Only needed and sensible for non-snapshot counters.
676  *
677  * This obviously relies on buf::head to figure out buffer markers, so it has
678  * to be called after pt_buffer_reset_offsets() and before the hardware tracing
679  * is enabled.
680  */
681 static int pt_buffer_reset_markers(struct pt_buffer *buf,
682                                    struct perf_output_handle *handle)
683
684 {
685         unsigned long head = local64_read(&buf->head);
686         unsigned long idx, npages, wakeup;
687
688         /* can't stop in the middle of an output region */
689         if (buf->output_off + handle->size + 1 <
690             sizes(TOPA_ENTRY(buf->cur, buf->cur_idx)->size))
691                 return -EINVAL;
692
693
694         /* single entry ToPA is handled by marking all regions STOP=1 INT=1 */
695         if (!pt_cap_get(PT_CAP_topa_multiple_entries))
696                 return 0;
697
698         /* clear STOP and INT from current entry */
699         buf->topa_index[buf->stop_pos]->stop = 0;
700         buf->topa_index[buf->intr_pos]->intr = 0;
701
702         /* how many pages till the STOP marker */
703         npages = handle->size >> PAGE_SHIFT;
704
705         /* if it's on a page boundary, fill up one more page */
706         if (!offset_in_page(head + handle->size + 1))
707                 npages++;
708
709         idx = (head >> PAGE_SHIFT) + npages;
710         idx &= buf->nr_pages - 1;
711         buf->stop_pos = idx;
712
713         wakeup = handle->wakeup >> PAGE_SHIFT;
714
715         /* in the worst case, wake up the consumer one page before hard stop */
716         idx = (head >> PAGE_SHIFT) + npages - 1;
717         if (idx > wakeup)
718                 idx = wakeup;
719
720         idx &= buf->nr_pages - 1;
721         buf->intr_pos = idx;
722
723         buf->topa_index[buf->stop_pos]->stop = 1;
724         buf->topa_index[buf->intr_pos]->intr = 1;
725
726         return 0;
727 }
728
729 /**
730  * pt_buffer_setup_topa_index() - build topa_index[] table of regions
731  * @buf:        PT buffer.
732  *
733  * topa_index[] references output regions indexed by offset into the
734  * buffer for purposes of quick reverse lookup.
735  */
736 static void pt_buffer_setup_topa_index(struct pt_buffer *buf)
737 {
738         struct topa *cur = buf->first, *prev = buf->last;
739         struct topa_entry *te_cur = TOPA_ENTRY(cur, 0),
740                 *te_prev = TOPA_ENTRY(prev, prev->last - 1);
741         int pg = 0, idx = 0;
742
743         while (pg < buf->nr_pages) {
744                 int tidx;
745
746                 /* pages within one topa entry */
747                 for (tidx = 0; tidx < 1 << te_cur->size; tidx++, pg++)
748                         buf->topa_index[pg] = te_prev;
749
750                 te_prev = te_cur;
751
752                 if (idx == cur->last - 1) {
753                         /* advance to next topa table */
754                         idx = 0;
755                         cur = list_entry(cur->list.next, struct topa, list);
756                 } else {
757                         idx++;
758                 }
759                 te_cur = TOPA_ENTRY(cur, idx);
760         }
761
762 }
763
764 /**
765  * pt_buffer_reset_offsets() - adjust buffer's write pointers from aux_head
766  * @buf:        PT buffer.
767  * @head:       Write pointer (aux_head) from AUX buffer.
768  *
769  * Find the ToPA table and entry corresponding to given @head and set buffer's
770  * "current" pointers accordingly. This is done after we have obtained the
771  * current aux_head position from a successful call to perf_aux_output_begin()
772  * to make sure the hardware is writing to the right place.
773  *
774  * This function modifies buf::{cur,cur_idx,output_off} that will be programmed
775  * into PT msrs when the tracing is enabled and buf::head and buf::data_size,
776  * which are used to determine INT and STOP markers' locations by a subsequent
777  * call to pt_buffer_reset_markers().
778  */
779 static void pt_buffer_reset_offsets(struct pt_buffer *buf, unsigned long head)
780 {
781         int pg;
782
783         if (buf->snapshot)
784                 head &= (buf->nr_pages << PAGE_SHIFT) - 1;
785
786         pg = (head >> PAGE_SHIFT) & (buf->nr_pages - 1);
787         pg = pt_topa_next_entry(buf, pg);
788
789         buf->cur = (struct topa *)((unsigned long)buf->topa_index[pg] & PAGE_MASK);
790         buf->cur_idx = ((unsigned long)buf->topa_index[pg] -
791                         (unsigned long)buf->cur) / sizeof(struct topa_entry);
792         buf->output_off = head & (sizes(buf->cur->table[buf->cur_idx].size) - 1);
793
794         local64_set(&buf->head, head);
795         local_set(&buf->data_size, 0);
796 }
797
798 /**
799  * pt_buffer_fini_topa() - deallocate ToPA structure of a buffer
800  * @buf:        PT buffer.
801  */
802 static void pt_buffer_fini_topa(struct pt_buffer *buf)
803 {
804         struct topa *topa, *iter;
805
806         list_for_each_entry_safe(topa, iter, &buf->tables, list) {
807                 /*
808                  * right now, this is in free_aux() path only, so
809                  * no need to unlink this table from the list
810                  */
811                 topa_free(topa);
812         }
813 }
814
815 /**
816  * pt_buffer_init_topa() - initialize ToPA table for pt buffer
817  * @buf:        PT buffer.
818  * @size:       Total size of all regions within this ToPA.
819  * @gfp:        Allocation flags.
820  */
821 static int pt_buffer_init_topa(struct pt_buffer *buf, unsigned long nr_pages,
822                                gfp_t gfp)
823 {
824         struct topa *topa;
825         int err;
826
827         topa = topa_alloc(buf->cpu, gfp);
828         if (!topa)
829                 return -ENOMEM;
830
831         topa_insert_table(buf, topa);
832
833         while (buf->nr_pages < nr_pages) {
834                 err = topa_insert_pages(buf, gfp);
835                 if (err) {
836                         pt_buffer_fini_topa(buf);
837                         return -ENOMEM;
838                 }
839         }
840
841         pt_buffer_setup_topa_index(buf);
842
843         /* link last table to the first one, unless we're double buffering */
844         if (pt_cap_get(PT_CAP_topa_multiple_entries)) {
845                 TOPA_ENTRY(buf->last, -1)->base = buf->first->phys >> TOPA_SHIFT;
846                 TOPA_ENTRY(buf->last, -1)->end = 1;
847         }
848
849         pt_topa_dump(buf);
850         return 0;
851 }
852
853 /**
854  * pt_buffer_setup_aux() - set up topa tables for a PT buffer
855  * @cpu:        Cpu on which to allocate, -1 means current.
856  * @pages:      Array of pointers to buffer pages passed from perf core.
857  * @nr_pages:   Number of pages in the buffer.
858  * @snapshot:   If this is a snapshot/overwrite counter.
859  *
860  * This is a pmu::setup_aux callback that sets up ToPA tables and all the
861  * bookkeeping for an AUX buffer.
862  *
863  * Return:      Our private PT buffer structure.
864  */
865 static void *
866 pt_buffer_setup_aux(int cpu, void **pages, int nr_pages, bool snapshot)
867 {
868         struct pt_buffer *buf;
869         int node, ret;
870
871         if (!nr_pages)
872                 return NULL;
873
874         if (cpu == -1)
875                 cpu = raw_smp_processor_id();
876         node = cpu_to_node(cpu);
877
878         buf = kzalloc_node(offsetof(struct pt_buffer, topa_index[nr_pages]),
879                            GFP_KERNEL, node);
880         if (!buf)
881                 return NULL;
882
883         buf->cpu = cpu;
884         buf->snapshot = snapshot;
885         buf->data_pages = pages;
886
887         INIT_LIST_HEAD(&buf->tables);
888
889         ret = pt_buffer_init_topa(buf, nr_pages, GFP_KERNEL);
890         if (ret) {
891                 kfree(buf);
892                 return NULL;
893         }
894
895         return buf;
896 }
897
898 /**
899  * pt_buffer_free_aux() - perf AUX deallocation path callback
900  * @data:       PT buffer.
901  */
902 static void pt_buffer_free_aux(void *data)
903 {
904         struct pt_buffer *buf = data;
905
906         pt_buffer_fini_topa(buf);
907         kfree(buf);
908 }
909
910 /**
911  * pt_buffer_is_full() - check if the buffer is full
912  * @buf:        PT buffer.
913  * @pt:         Per-cpu pt handle.
914  *
915  * If the user hasn't read data from the output region that aux_head
916  * points to, the buffer is considered full: the user needs to read at
917  * least this region and update aux_tail to point past it.
918  */
919 static bool pt_buffer_is_full(struct pt_buffer *buf, struct pt *pt)
920 {
921         if (buf->snapshot)
922                 return false;
923
924         if (local_read(&buf->data_size) >= pt->handle.size)
925                 return true;
926
927         return false;
928 }
929
930 /**
931  * intel_pt_interrupt() - PT PMI handler
932  */
933 void intel_pt_interrupt(void)
934 {
935         struct pt *pt = this_cpu_ptr(&pt_ctx);
936         struct pt_buffer *buf;
937         struct perf_event *event = pt->handle.event;
938
939         /*
940          * There may be a dangling PT bit in the interrupt status register
941          * after PT has been disabled by pt_event_stop(). Make sure we don't
942          * do anything (particularly, re-enable) for this event here.
943          */
944         if (!ACCESS_ONCE(pt->handle_nmi))
945                 return;
946
947         pt_config_start(false);
948
949         if (!event)
950                 return;
951
952         buf = perf_get_aux(&pt->handle);
953         if (!buf)
954                 return;
955
956         pt_read_offset(buf);
957
958         pt_handle_status(pt);
959
960         pt_update_head(pt);
961
962         perf_aux_output_end(&pt->handle, local_xchg(&buf->data_size, 0),
963                             local_xchg(&buf->lost, 0));
964
965         if (!event->hw.state) {
966                 int ret;
967
968                 buf = perf_aux_output_begin(&pt->handle, event);
969                 if (!buf) {
970                         event->hw.state = PERF_HES_STOPPED;
971                         return;
972                 }
973
974                 pt_buffer_reset_offsets(buf, pt->handle.head);
975                 /* snapshot counters don't use PMI, so it's safe */
976                 ret = pt_buffer_reset_markers(buf, &pt->handle);
977                 if (ret) {
978                         perf_aux_output_end(&pt->handle, 0, true);
979                         return;
980                 }
981
982                 pt_config_buffer(buf->cur->table, buf->cur_idx,
983                                  buf->output_off);
984                 pt_config(event);
985         }
986 }
987
988 /*
989  * PMU callbacks
990  */
991
992 static void pt_event_start(struct perf_event *event, int mode)
993 {
994         struct pt *pt = this_cpu_ptr(&pt_ctx);
995         struct pt_buffer *buf = perf_get_aux(&pt->handle);
996
997         if (!buf || pt_buffer_is_full(buf, pt)) {
998                 event->hw.state = PERF_HES_STOPPED;
999                 return;
1000         }
1001
1002         ACCESS_ONCE(pt->handle_nmi) = 1;
1003         event->hw.state = 0;
1004
1005         pt_config_buffer(buf->cur->table, buf->cur_idx,
1006                          buf->output_off);
1007         pt_config(event);
1008 }
1009
1010 static void pt_event_stop(struct perf_event *event, int mode)
1011 {
1012         struct pt *pt = this_cpu_ptr(&pt_ctx);
1013
1014         /*
1015          * Protect against the PMI racing with disabling wrmsr,
1016          * see comment in intel_pt_interrupt().
1017          */
1018         ACCESS_ONCE(pt->handle_nmi) = 0;
1019         pt_config_start(false);
1020
1021         if (event->hw.state == PERF_HES_STOPPED)
1022                 return;
1023
1024         event->hw.state = PERF_HES_STOPPED;
1025
1026         if (mode & PERF_EF_UPDATE) {
1027                 struct pt_buffer *buf = perf_get_aux(&pt->handle);
1028
1029                 if (!buf)
1030                         return;
1031
1032                 if (WARN_ON_ONCE(pt->handle.event != event))
1033                         return;
1034
1035                 pt_read_offset(buf);
1036
1037                 pt_handle_status(pt);
1038
1039                 pt_update_head(pt);
1040         }
1041 }
1042
1043 static void pt_event_del(struct perf_event *event, int mode)
1044 {
1045         struct pt *pt = this_cpu_ptr(&pt_ctx);
1046         struct pt_buffer *buf;
1047
1048         pt_event_stop(event, PERF_EF_UPDATE);
1049
1050         buf = perf_get_aux(&pt->handle);
1051
1052         if (buf) {
1053                 if (buf->snapshot)
1054                         pt->handle.head =
1055                                 local_xchg(&buf->data_size,
1056                                            buf->nr_pages << PAGE_SHIFT);
1057                 perf_aux_output_end(&pt->handle, local_xchg(&buf->data_size, 0),
1058                                     local_xchg(&buf->lost, 0));
1059         }
1060 }
1061
1062 static int pt_event_add(struct perf_event *event, int mode)
1063 {
1064         struct pt_buffer *buf;
1065         struct pt *pt = this_cpu_ptr(&pt_ctx);
1066         struct hw_perf_event *hwc = &event->hw;
1067         int ret = -EBUSY;
1068
1069         if (pt->handle.event)
1070                 goto fail;
1071
1072         buf = perf_aux_output_begin(&pt->handle, event);
1073         ret = -EINVAL;
1074         if (!buf)
1075                 goto fail_stop;
1076
1077         pt_buffer_reset_offsets(buf, pt->handle.head);
1078         if (!buf->snapshot) {
1079                 ret = pt_buffer_reset_markers(buf, &pt->handle);
1080                 if (ret)
1081                         goto fail_end_stop;
1082         }
1083
1084         if (mode & PERF_EF_START) {
1085                 pt_event_start(event, 0);
1086                 ret = -EBUSY;
1087                 if (hwc->state == PERF_HES_STOPPED)
1088                         goto fail_end_stop;
1089         } else {
1090                 hwc->state = PERF_HES_STOPPED;
1091         }
1092
1093         return 0;
1094
1095 fail_end_stop:
1096         perf_aux_output_end(&pt->handle, 0, true);
1097 fail_stop:
1098         hwc->state = PERF_HES_STOPPED;
1099 fail:
1100         return ret;
1101 }
1102
1103 static void pt_event_read(struct perf_event *event)
1104 {
1105 }
1106
1107 static void pt_event_destroy(struct perf_event *event)
1108 {
1109         x86_del_exclusive(x86_lbr_exclusive_pt);
1110 }
1111
1112 static int pt_event_init(struct perf_event *event)
1113 {
1114         if (event->attr.type != pt_pmu.pmu.type)
1115                 return -ENOENT;
1116
1117         if (!pt_event_valid(event))
1118                 return -EINVAL;
1119
1120         if (x86_add_exclusive(x86_lbr_exclusive_pt))
1121                 return -EBUSY;
1122
1123         event->destroy = pt_event_destroy;
1124
1125         return 0;
1126 }
1127
1128 static __init int pt_init(void)
1129 {
1130         int ret, cpu, prior_warn = 0;
1131
1132         BUILD_BUG_ON(sizeof(struct topa) > PAGE_SIZE);
1133         get_online_cpus();
1134         for_each_online_cpu(cpu) {
1135                 u64 ctl;
1136
1137                 ret = rdmsrl_safe_on_cpu(cpu, MSR_IA32_RTIT_CTL, &ctl);
1138                 if (!ret && (ctl & RTIT_CTL_TRACEEN))
1139                         prior_warn++;
1140         }
1141         put_online_cpus();
1142
1143         if (prior_warn) {
1144                 x86_add_exclusive(x86_lbr_exclusive_pt);
1145                 pr_warn("PT is enabled at boot time, doing nothing\n");
1146
1147                 return -EBUSY;
1148         }
1149
1150         ret = pt_pmu_hw_init();
1151         if (ret)
1152                 return ret;
1153
1154         if (!pt_cap_get(PT_CAP_topa_output)) {
1155                 pr_warn("ToPA output is not supported on this CPU\n");
1156                 return -ENODEV;
1157         }
1158
1159         if (!pt_cap_get(PT_CAP_topa_multiple_entries))
1160                 pt_pmu.pmu.capabilities =
1161                         PERF_PMU_CAP_AUX_NO_SG | PERF_PMU_CAP_AUX_SW_DOUBLEBUF;
1162
1163         pt_pmu.pmu.capabilities |= PERF_PMU_CAP_EXCLUSIVE | PERF_PMU_CAP_ITRACE;
1164         pt_pmu.pmu.attr_groups  = pt_attr_groups;
1165         pt_pmu.pmu.task_ctx_nr  = perf_sw_context;
1166         pt_pmu.pmu.event_init   = pt_event_init;
1167         pt_pmu.pmu.add          = pt_event_add;
1168         pt_pmu.pmu.del          = pt_event_del;
1169         pt_pmu.pmu.start        = pt_event_start;
1170         pt_pmu.pmu.stop         = pt_event_stop;
1171         pt_pmu.pmu.read         = pt_event_read;
1172         pt_pmu.pmu.setup_aux    = pt_buffer_setup_aux;
1173         pt_pmu.pmu.free_aux     = pt_buffer_free_aux;
1174         ret = perf_pmu_register(&pt_pmu.pmu, "intel_pt", -1);
1175
1176         return ret;
1177 }
1178 arch_initcall(pt_init);