Merge tag 'armsoc-dt' of git://git.kernel.org/pub/scm/linux/kernel/git/soc/soc
[sfrench/cifs-2.6.git] / arch / x86 / events / intel / ds.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/bitops.h>
3 #include <linux/types.h>
4 #include <linux/slab.h>
5
6 #include <asm/cpu_entry_area.h>
7 #include <asm/perf_event.h>
8 #include <asm/tlbflush.h>
9 #include <asm/insn.h>
10 #include <asm/io.h>
11
12 #include "../perf_event.h"
13
14 /* Waste a full page so it can be mapped into the cpu_entry_area */
15 DEFINE_PER_CPU_PAGE_ALIGNED(struct debug_store, cpu_debug_store);
16
17 /* The size of a BTS record in bytes: */
18 #define BTS_RECORD_SIZE         24
19
20 #define PEBS_FIXUP_SIZE         PAGE_SIZE
21
22 /*
23  * pebs_record_32 for p4 and core not supported
24
25 struct pebs_record_32 {
26         u32 flags, ip;
27         u32 ax, bc, cx, dx;
28         u32 si, di, bp, sp;
29 };
30
31  */
32
33 union intel_x86_pebs_dse {
34         u64 val;
35         struct {
36                 unsigned int ld_dse:4;
37                 unsigned int ld_stlb_miss:1;
38                 unsigned int ld_locked:1;
39                 unsigned int ld_reserved:26;
40         };
41         struct {
42                 unsigned int st_l1d_hit:1;
43                 unsigned int st_reserved1:3;
44                 unsigned int st_stlb_miss:1;
45                 unsigned int st_locked:1;
46                 unsigned int st_reserved2:26;
47         };
48 };
49
50
51 /*
52  * Map PEBS Load Latency Data Source encodings to generic
53  * memory data source information
54  */
55 #define P(a, b) PERF_MEM_S(a, b)
56 #define OP_LH (P(OP, LOAD) | P(LVL, HIT))
57 #define LEVEL(x) P(LVLNUM, x)
58 #define REM P(REMOTE, REMOTE)
59 #define SNOOP_NONE_MISS (P(SNOOP, NONE) | P(SNOOP, MISS))
60
61 /* Version for Sandy Bridge and later */
62 static u64 pebs_data_source[] = {
63         P(OP, LOAD) | P(LVL, MISS) | LEVEL(L3) | P(SNOOP, NA),/* 0x00:ukn L3 */
64         OP_LH | P(LVL, L1)  | LEVEL(L1) | P(SNOOP, NONE),  /* 0x01: L1 local */
65         OP_LH | P(LVL, LFB) | LEVEL(LFB) | P(SNOOP, NONE), /* 0x02: LFB hit */
66         OP_LH | P(LVL, L2)  | LEVEL(L2) | P(SNOOP, NONE),  /* 0x03: L2 hit */
67         OP_LH | P(LVL, L3)  | LEVEL(L3) | P(SNOOP, NONE),  /* 0x04: L3 hit */
68         OP_LH | P(LVL, L3)  | LEVEL(L3) | P(SNOOP, MISS),  /* 0x05: L3 hit, snoop miss */
69         OP_LH | P(LVL, L3)  | LEVEL(L3) | P(SNOOP, HIT),   /* 0x06: L3 hit, snoop hit */
70         OP_LH | P(LVL, L3)  | LEVEL(L3) | P(SNOOP, HITM),  /* 0x07: L3 hit, snoop hitm */
71         OP_LH | P(LVL, REM_CCE1) | REM | LEVEL(L3) | P(SNOOP, HIT),  /* 0x08: L3 miss snoop hit */
72         OP_LH | P(LVL, REM_CCE1) | REM | LEVEL(L3) | P(SNOOP, HITM), /* 0x09: L3 miss snoop hitm*/
73         OP_LH | P(LVL, LOC_RAM)  | LEVEL(RAM) | P(SNOOP, HIT),       /* 0x0a: L3 miss, shared */
74         OP_LH | P(LVL, REM_RAM1) | REM | LEVEL(L3) | P(SNOOP, HIT),  /* 0x0b: L3 miss, shared */
75         OP_LH | P(LVL, LOC_RAM)  | LEVEL(RAM) | SNOOP_NONE_MISS,     /* 0x0c: L3 miss, excl */
76         OP_LH | P(LVL, REM_RAM1) | LEVEL(RAM) | REM | SNOOP_NONE_MISS, /* 0x0d: L3 miss, excl */
77         OP_LH | P(LVL, IO)  | LEVEL(NA) | P(SNOOP, NONE), /* 0x0e: I/O */
78         OP_LH | P(LVL, UNC) | LEVEL(NA) | P(SNOOP, NONE), /* 0x0f: uncached */
79 };
80
81 /* Patch up minor differences in the bits */
82 void __init intel_pmu_pebs_data_source_nhm(void)
83 {
84         pebs_data_source[0x05] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HIT);
85         pebs_data_source[0x06] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HITM);
86         pebs_data_source[0x07] = OP_LH | P(LVL, L3) | LEVEL(L3) | P(SNOOP, HITM);
87 }
88
89 void __init intel_pmu_pebs_data_source_skl(bool pmem)
90 {
91         u64 pmem_or_l4 = pmem ? LEVEL(PMEM) : LEVEL(L4);
92
93         pebs_data_source[0x08] = OP_LH | pmem_or_l4 | P(SNOOP, HIT);
94         pebs_data_source[0x09] = OP_LH | pmem_or_l4 | REM | P(SNOOP, HIT);
95         pebs_data_source[0x0b] = OP_LH | LEVEL(RAM) | REM | P(SNOOP, NONE);
96         pebs_data_source[0x0c] = OP_LH | LEVEL(ANY_CACHE) | REM | P(SNOOPX, FWD);
97         pebs_data_source[0x0d] = OP_LH | LEVEL(ANY_CACHE) | REM | P(SNOOP, HITM);
98 }
99
100 static u64 precise_store_data(u64 status)
101 {
102         union intel_x86_pebs_dse dse;
103         u64 val = P(OP, STORE) | P(SNOOP, NA) | P(LVL, L1) | P(TLB, L2);
104
105         dse.val = status;
106
107         /*
108          * bit 4: TLB access
109          * 1 = stored missed 2nd level TLB
110          *
111          * so it either hit the walker or the OS
112          * otherwise hit 2nd level TLB
113          */
114         if (dse.st_stlb_miss)
115                 val |= P(TLB, MISS);
116         else
117                 val |= P(TLB, HIT);
118
119         /*
120          * bit 0: hit L1 data cache
121          * if not set, then all we know is that
122          * it missed L1D
123          */
124         if (dse.st_l1d_hit)
125                 val |= P(LVL, HIT);
126         else
127                 val |= P(LVL, MISS);
128
129         /*
130          * bit 5: Locked prefix
131          */
132         if (dse.st_locked)
133                 val |= P(LOCK, LOCKED);
134
135         return val;
136 }
137
138 static u64 precise_datala_hsw(struct perf_event *event, u64 status)
139 {
140         union perf_mem_data_src dse;
141
142         dse.val = PERF_MEM_NA;
143
144         if (event->hw.flags & PERF_X86_EVENT_PEBS_ST_HSW)
145                 dse.mem_op = PERF_MEM_OP_STORE;
146         else if (event->hw.flags & PERF_X86_EVENT_PEBS_LD_HSW)
147                 dse.mem_op = PERF_MEM_OP_LOAD;
148
149         /*
150          * L1 info only valid for following events:
151          *
152          * MEM_UOPS_RETIRED.STLB_MISS_STORES
153          * MEM_UOPS_RETIRED.LOCK_STORES
154          * MEM_UOPS_RETIRED.SPLIT_STORES
155          * MEM_UOPS_RETIRED.ALL_STORES
156          */
157         if (event->hw.flags & PERF_X86_EVENT_PEBS_ST_HSW) {
158                 if (status & 1)
159                         dse.mem_lvl = PERF_MEM_LVL_L1 | PERF_MEM_LVL_HIT;
160                 else
161                         dse.mem_lvl = PERF_MEM_LVL_L1 | PERF_MEM_LVL_MISS;
162         }
163         return dse.val;
164 }
165
166 static u64 load_latency_data(u64 status)
167 {
168         union intel_x86_pebs_dse dse;
169         u64 val;
170
171         dse.val = status;
172
173         /*
174          * use the mapping table for bit 0-3
175          */
176         val = pebs_data_source[dse.ld_dse];
177
178         /*
179          * Nehalem models do not support TLB, Lock infos
180          */
181         if (x86_pmu.pebs_no_tlb) {
182                 val |= P(TLB, NA) | P(LOCK, NA);
183                 return val;
184         }
185         /*
186          * bit 4: TLB access
187          * 0 = did not miss 2nd level TLB
188          * 1 = missed 2nd level TLB
189          */
190         if (dse.ld_stlb_miss)
191                 val |= P(TLB, MISS) | P(TLB, L2);
192         else
193                 val |= P(TLB, HIT) | P(TLB, L1) | P(TLB, L2);
194
195         /*
196          * bit 5: locked prefix
197          */
198         if (dse.ld_locked)
199                 val |= P(LOCK, LOCKED);
200
201         return val;
202 }
203
204 struct pebs_record_core {
205         u64 flags, ip;
206         u64 ax, bx, cx, dx;
207         u64 si, di, bp, sp;
208         u64 r8,  r9,  r10, r11;
209         u64 r12, r13, r14, r15;
210 };
211
212 struct pebs_record_nhm {
213         u64 flags, ip;
214         u64 ax, bx, cx, dx;
215         u64 si, di, bp, sp;
216         u64 r8,  r9,  r10, r11;
217         u64 r12, r13, r14, r15;
218         u64 status, dla, dse, lat;
219 };
220
221 /*
222  * Same as pebs_record_nhm, with two additional fields.
223  */
224 struct pebs_record_hsw {
225         u64 flags, ip;
226         u64 ax, bx, cx, dx;
227         u64 si, di, bp, sp;
228         u64 r8,  r9,  r10, r11;
229         u64 r12, r13, r14, r15;
230         u64 status, dla, dse, lat;
231         u64 real_ip, tsx_tuning;
232 };
233
234 union hsw_tsx_tuning {
235         struct {
236                 u32 cycles_last_block     : 32,
237                     hle_abort             : 1,
238                     rtm_abort             : 1,
239                     instruction_abort     : 1,
240                     non_instruction_abort : 1,
241                     retry                 : 1,
242                     data_conflict         : 1,
243                     capacity_writes       : 1,
244                     capacity_reads        : 1;
245         };
246         u64         value;
247 };
248
249 #define PEBS_HSW_TSX_FLAGS      0xff00000000ULL
250
251 /* Same as HSW, plus TSC */
252
253 struct pebs_record_skl {
254         u64 flags, ip;
255         u64 ax, bx, cx, dx;
256         u64 si, di, bp, sp;
257         u64 r8,  r9,  r10, r11;
258         u64 r12, r13, r14, r15;
259         u64 status, dla, dse, lat;
260         u64 real_ip, tsx_tuning;
261         u64 tsc;
262 };
263
264 void init_debug_store_on_cpu(int cpu)
265 {
266         struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds;
267
268         if (!ds)
269                 return;
270
271         wrmsr_on_cpu(cpu, MSR_IA32_DS_AREA,
272                      (u32)((u64)(unsigned long)ds),
273                      (u32)((u64)(unsigned long)ds >> 32));
274 }
275
276 void fini_debug_store_on_cpu(int cpu)
277 {
278         if (!per_cpu(cpu_hw_events, cpu).ds)
279                 return;
280
281         wrmsr_on_cpu(cpu, MSR_IA32_DS_AREA, 0, 0);
282 }
283
284 static DEFINE_PER_CPU(void *, insn_buffer);
285
286 static void ds_update_cea(void *cea, void *addr, size_t size, pgprot_t prot)
287 {
288         unsigned long start = (unsigned long)cea;
289         phys_addr_t pa;
290         size_t msz = 0;
291
292         pa = virt_to_phys(addr);
293
294         preempt_disable();
295         for (; msz < size; msz += PAGE_SIZE, pa += PAGE_SIZE, cea += PAGE_SIZE)
296                 cea_set_pte(cea, pa, prot);
297
298         /*
299          * This is a cross-CPU update of the cpu_entry_area, we must shoot down
300          * all TLB entries for it.
301          */
302         flush_tlb_kernel_range(start, start + size);
303         preempt_enable();
304 }
305
306 static void ds_clear_cea(void *cea, size_t size)
307 {
308         unsigned long start = (unsigned long)cea;
309         size_t msz = 0;
310
311         preempt_disable();
312         for (; msz < size; msz += PAGE_SIZE, cea += PAGE_SIZE)
313                 cea_set_pte(cea, 0, PAGE_NONE);
314
315         flush_tlb_kernel_range(start, start + size);
316         preempt_enable();
317 }
318
319 static void *dsalloc_pages(size_t size, gfp_t flags, int cpu)
320 {
321         unsigned int order = get_order(size);
322         int node = cpu_to_node(cpu);
323         struct page *page;
324
325         page = __alloc_pages_node(node, flags | __GFP_ZERO, order);
326         return page ? page_address(page) : NULL;
327 }
328
329 static void dsfree_pages(const void *buffer, size_t size)
330 {
331         if (buffer)
332                 free_pages((unsigned long)buffer, get_order(size));
333 }
334
335 static int alloc_pebs_buffer(int cpu)
336 {
337         struct cpu_hw_events *hwev = per_cpu_ptr(&cpu_hw_events, cpu);
338         struct debug_store *ds = hwev->ds;
339         size_t bsiz = x86_pmu.pebs_buffer_size;
340         int max, node = cpu_to_node(cpu);
341         void *buffer, *insn_buff, *cea;
342
343         if (!x86_pmu.pebs)
344                 return 0;
345
346         buffer = dsalloc_pages(bsiz, GFP_KERNEL, cpu);
347         if (unlikely(!buffer))
348                 return -ENOMEM;
349
350         /*
351          * HSW+ already provides us the eventing ip; no need to allocate this
352          * buffer then.
353          */
354         if (x86_pmu.intel_cap.pebs_format < 2) {
355                 insn_buff = kzalloc_node(PEBS_FIXUP_SIZE, GFP_KERNEL, node);
356                 if (!insn_buff) {
357                         dsfree_pages(buffer, bsiz);
358                         return -ENOMEM;
359                 }
360                 per_cpu(insn_buffer, cpu) = insn_buff;
361         }
362         hwev->ds_pebs_vaddr = buffer;
363         /* Update the cpu entry area mapping */
364         cea = &get_cpu_entry_area(cpu)->cpu_debug_buffers.pebs_buffer;
365         ds->pebs_buffer_base = (unsigned long) cea;
366         ds_update_cea(cea, buffer, bsiz, PAGE_KERNEL);
367         ds->pebs_index = ds->pebs_buffer_base;
368         max = x86_pmu.pebs_record_size * (bsiz / x86_pmu.pebs_record_size);
369         ds->pebs_absolute_maximum = ds->pebs_buffer_base + max;
370         return 0;
371 }
372
373 static void release_pebs_buffer(int cpu)
374 {
375         struct cpu_hw_events *hwev = per_cpu_ptr(&cpu_hw_events, cpu);
376         void *cea;
377
378         if (!x86_pmu.pebs)
379                 return;
380
381         kfree(per_cpu(insn_buffer, cpu));
382         per_cpu(insn_buffer, cpu) = NULL;
383
384         /* Clear the fixmap */
385         cea = &get_cpu_entry_area(cpu)->cpu_debug_buffers.pebs_buffer;
386         ds_clear_cea(cea, x86_pmu.pebs_buffer_size);
387         dsfree_pages(hwev->ds_pebs_vaddr, x86_pmu.pebs_buffer_size);
388         hwev->ds_pebs_vaddr = NULL;
389 }
390
391 static int alloc_bts_buffer(int cpu)
392 {
393         struct cpu_hw_events *hwev = per_cpu_ptr(&cpu_hw_events, cpu);
394         struct debug_store *ds = hwev->ds;
395         void *buffer, *cea;
396         int max;
397
398         if (!x86_pmu.bts)
399                 return 0;
400
401         buffer = dsalloc_pages(BTS_BUFFER_SIZE, GFP_KERNEL | __GFP_NOWARN, cpu);
402         if (unlikely(!buffer)) {
403                 WARN_ONCE(1, "%s: BTS buffer allocation failure\n", __func__);
404                 return -ENOMEM;
405         }
406         hwev->ds_bts_vaddr = buffer;
407         /* Update the fixmap */
408         cea = &get_cpu_entry_area(cpu)->cpu_debug_buffers.bts_buffer;
409         ds->bts_buffer_base = (unsigned long) cea;
410         ds_update_cea(cea, buffer, BTS_BUFFER_SIZE, PAGE_KERNEL);
411         ds->bts_index = ds->bts_buffer_base;
412         max = BTS_BUFFER_SIZE / BTS_RECORD_SIZE;
413         ds->bts_absolute_maximum = ds->bts_buffer_base +
414                                         max * BTS_RECORD_SIZE;
415         ds->bts_interrupt_threshold = ds->bts_absolute_maximum -
416                                         (max / 16) * BTS_RECORD_SIZE;
417         return 0;
418 }
419
420 static void release_bts_buffer(int cpu)
421 {
422         struct cpu_hw_events *hwev = per_cpu_ptr(&cpu_hw_events, cpu);
423         void *cea;
424
425         if (!x86_pmu.bts)
426                 return;
427
428         /* Clear the fixmap */
429         cea = &get_cpu_entry_area(cpu)->cpu_debug_buffers.bts_buffer;
430         ds_clear_cea(cea, BTS_BUFFER_SIZE);
431         dsfree_pages(hwev->ds_bts_vaddr, BTS_BUFFER_SIZE);
432         hwev->ds_bts_vaddr = NULL;
433 }
434
435 static int alloc_ds_buffer(int cpu)
436 {
437         struct debug_store *ds = &get_cpu_entry_area(cpu)->cpu_debug_store;
438
439         memset(ds, 0, sizeof(*ds));
440         per_cpu(cpu_hw_events, cpu).ds = ds;
441         return 0;
442 }
443
444 static void release_ds_buffer(int cpu)
445 {
446         per_cpu(cpu_hw_events, cpu).ds = NULL;
447 }
448
449 void release_ds_buffers(void)
450 {
451         int cpu;
452
453         if (!x86_pmu.bts && !x86_pmu.pebs)
454                 return;
455
456         for_each_possible_cpu(cpu)
457                 release_ds_buffer(cpu);
458
459         for_each_possible_cpu(cpu) {
460                 /*
461                  * Again, ignore errors from offline CPUs, they will no longer
462                  * observe cpu_hw_events.ds and not program the DS_AREA when
463                  * they come up.
464                  */
465                 fini_debug_store_on_cpu(cpu);
466         }
467
468         for_each_possible_cpu(cpu) {
469                 release_pebs_buffer(cpu);
470                 release_bts_buffer(cpu);
471         }
472 }
473
474 void reserve_ds_buffers(void)
475 {
476         int bts_err = 0, pebs_err = 0;
477         int cpu;
478
479         x86_pmu.bts_active = 0;
480         x86_pmu.pebs_active = 0;
481
482         if (!x86_pmu.bts && !x86_pmu.pebs)
483                 return;
484
485         if (!x86_pmu.bts)
486                 bts_err = 1;
487
488         if (!x86_pmu.pebs)
489                 pebs_err = 1;
490
491         for_each_possible_cpu(cpu) {
492                 if (alloc_ds_buffer(cpu)) {
493                         bts_err = 1;
494                         pebs_err = 1;
495                 }
496
497                 if (!bts_err && alloc_bts_buffer(cpu))
498                         bts_err = 1;
499
500                 if (!pebs_err && alloc_pebs_buffer(cpu))
501                         pebs_err = 1;
502
503                 if (bts_err && pebs_err)
504                         break;
505         }
506
507         if (bts_err) {
508                 for_each_possible_cpu(cpu)
509                         release_bts_buffer(cpu);
510         }
511
512         if (pebs_err) {
513                 for_each_possible_cpu(cpu)
514                         release_pebs_buffer(cpu);
515         }
516
517         if (bts_err && pebs_err) {
518                 for_each_possible_cpu(cpu)
519                         release_ds_buffer(cpu);
520         } else {
521                 if (x86_pmu.bts && !bts_err)
522                         x86_pmu.bts_active = 1;
523
524                 if (x86_pmu.pebs && !pebs_err)
525                         x86_pmu.pebs_active = 1;
526
527                 for_each_possible_cpu(cpu) {
528                         /*
529                          * Ignores wrmsr_on_cpu() errors for offline CPUs they
530                          * will get this call through intel_pmu_cpu_starting().
531                          */
532                         init_debug_store_on_cpu(cpu);
533                 }
534         }
535 }
536
537 /*
538  * BTS
539  */
540
541 struct event_constraint bts_constraint =
542         EVENT_CONSTRAINT(0, 1ULL << INTEL_PMC_IDX_FIXED_BTS, 0);
543
544 void intel_pmu_enable_bts(u64 config)
545 {
546         unsigned long debugctlmsr;
547
548         debugctlmsr = get_debugctlmsr();
549
550         debugctlmsr |= DEBUGCTLMSR_TR;
551         debugctlmsr |= DEBUGCTLMSR_BTS;
552         if (config & ARCH_PERFMON_EVENTSEL_INT)
553                 debugctlmsr |= DEBUGCTLMSR_BTINT;
554
555         if (!(config & ARCH_PERFMON_EVENTSEL_OS))
556                 debugctlmsr |= DEBUGCTLMSR_BTS_OFF_OS;
557
558         if (!(config & ARCH_PERFMON_EVENTSEL_USR))
559                 debugctlmsr |= DEBUGCTLMSR_BTS_OFF_USR;
560
561         update_debugctlmsr(debugctlmsr);
562 }
563
564 void intel_pmu_disable_bts(void)
565 {
566         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
567         unsigned long debugctlmsr;
568
569         if (!cpuc->ds)
570                 return;
571
572         debugctlmsr = get_debugctlmsr();
573
574         debugctlmsr &=
575                 ~(DEBUGCTLMSR_TR | DEBUGCTLMSR_BTS | DEBUGCTLMSR_BTINT |
576                   DEBUGCTLMSR_BTS_OFF_OS | DEBUGCTLMSR_BTS_OFF_USR);
577
578         update_debugctlmsr(debugctlmsr);
579 }
580
581 int intel_pmu_drain_bts_buffer(void)
582 {
583         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
584         struct debug_store *ds = cpuc->ds;
585         struct bts_record {
586                 u64     from;
587                 u64     to;
588                 u64     flags;
589         };
590         struct perf_event *event = cpuc->events[INTEL_PMC_IDX_FIXED_BTS];
591         struct bts_record *at, *base, *top;
592         struct perf_output_handle handle;
593         struct perf_event_header header;
594         struct perf_sample_data data;
595         unsigned long skip = 0;
596         struct pt_regs regs;
597
598         if (!event)
599                 return 0;
600
601         if (!x86_pmu.bts_active)
602                 return 0;
603
604         base = (struct bts_record *)(unsigned long)ds->bts_buffer_base;
605         top  = (struct bts_record *)(unsigned long)ds->bts_index;
606
607         if (top <= base)
608                 return 0;
609
610         memset(&regs, 0, sizeof(regs));
611
612         ds->bts_index = ds->bts_buffer_base;
613
614         perf_sample_data_init(&data, 0, event->hw.last_period);
615
616         /*
617          * BTS leaks kernel addresses in branches across the cpl boundary,
618          * such as traps or system calls, so unless the user is asking for
619          * kernel tracing (and right now it's not possible), we'd need to
620          * filter them out. But first we need to count how many of those we
621          * have in the current batch. This is an extra O(n) pass, however,
622          * it's much faster than the other one especially considering that
623          * n <= 2560 (BTS_BUFFER_SIZE / BTS_RECORD_SIZE * 15/16; see the
624          * alloc_bts_buffer()).
625          */
626         for (at = base; at < top; at++) {
627                 /*
628                  * Note that right now *this* BTS code only works if
629                  * attr::exclude_kernel is set, but let's keep this extra
630                  * check here in case that changes.
631                  */
632                 if (event->attr.exclude_kernel &&
633                     (kernel_ip(at->from) || kernel_ip(at->to)))
634                         skip++;
635         }
636
637         /*
638          * Prepare a generic sample, i.e. fill in the invariant fields.
639          * We will overwrite the from and to address before we output
640          * the sample.
641          */
642         rcu_read_lock();
643         perf_prepare_sample(&header, &data, event, &regs);
644
645         if (perf_output_begin(&handle, event, header.size *
646                               (top - base - skip)))
647                 goto unlock;
648
649         for (at = base; at < top; at++) {
650                 /* Filter out any records that contain kernel addresses. */
651                 if (event->attr.exclude_kernel &&
652                     (kernel_ip(at->from) || kernel_ip(at->to)))
653                         continue;
654
655                 data.ip         = at->from;
656                 data.addr       = at->to;
657
658                 perf_output_sample(&handle, &header, &data, event);
659         }
660
661         perf_output_end(&handle);
662
663         /* There's new data available. */
664         event->hw.interrupts++;
665         event->pending_kill = POLL_IN;
666 unlock:
667         rcu_read_unlock();
668         return 1;
669 }
670
671 static inline void intel_pmu_drain_pebs_buffer(void)
672 {
673         x86_pmu.drain_pebs(NULL);
674 }
675
676 /*
677  * PEBS
678  */
679 struct event_constraint intel_core2_pebs_event_constraints[] = {
680         INTEL_FLAGS_UEVENT_CONSTRAINT(0x00c0, 0x1), /* INST_RETIRED.ANY */
681         INTEL_FLAGS_UEVENT_CONSTRAINT(0xfec1, 0x1), /* X87_OPS_RETIRED.ANY */
682         INTEL_FLAGS_UEVENT_CONSTRAINT(0x00c5, 0x1), /* BR_INST_RETIRED.MISPRED */
683         INTEL_FLAGS_UEVENT_CONSTRAINT(0x1fc7, 0x1), /* SIMD_INST_RETURED.ANY */
684         INTEL_FLAGS_EVENT_CONSTRAINT(0xcb, 0x1),    /* MEM_LOAD_RETIRED.* */
685         /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */
686         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x01),
687         EVENT_CONSTRAINT_END
688 };
689
690 struct event_constraint intel_atom_pebs_event_constraints[] = {
691         INTEL_FLAGS_UEVENT_CONSTRAINT(0x00c0, 0x1), /* INST_RETIRED.ANY */
692         INTEL_FLAGS_UEVENT_CONSTRAINT(0x00c5, 0x1), /* MISPREDICTED_BRANCH_RETIRED */
693         INTEL_FLAGS_EVENT_CONSTRAINT(0xcb, 0x1),    /* MEM_LOAD_RETIRED.* */
694         /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */
695         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x01),
696         /* Allow all events as PEBS with no flags */
697         INTEL_ALL_EVENT_CONSTRAINT(0, 0x1),
698         EVENT_CONSTRAINT_END
699 };
700
701 struct event_constraint intel_slm_pebs_event_constraints[] = {
702         /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */
703         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x1),
704         /* Allow all events as PEBS with no flags */
705         INTEL_ALL_EVENT_CONSTRAINT(0, 0x1),
706         EVENT_CONSTRAINT_END
707 };
708
709 struct event_constraint intel_glm_pebs_event_constraints[] = {
710         /* Allow all events as PEBS with no flags */
711         INTEL_ALL_EVENT_CONSTRAINT(0, 0x1),
712         EVENT_CONSTRAINT_END
713 };
714
715 struct event_constraint intel_nehalem_pebs_event_constraints[] = {
716         INTEL_PLD_CONSTRAINT(0x100b, 0xf),      /* MEM_INST_RETIRED.* */
717         INTEL_FLAGS_EVENT_CONSTRAINT(0x0f, 0xf),    /* MEM_UNCORE_RETIRED.* */
718         INTEL_FLAGS_UEVENT_CONSTRAINT(0x010c, 0xf), /* MEM_STORE_RETIRED.DTLB_MISS */
719         INTEL_FLAGS_EVENT_CONSTRAINT(0xc0, 0xf),    /* INST_RETIRED.ANY */
720         INTEL_EVENT_CONSTRAINT(0xc2, 0xf),    /* UOPS_RETIRED.* */
721         INTEL_FLAGS_EVENT_CONSTRAINT(0xc4, 0xf),    /* BR_INST_RETIRED.* */
722         INTEL_FLAGS_UEVENT_CONSTRAINT(0x02c5, 0xf), /* BR_MISP_RETIRED.NEAR_CALL */
723         INTEL_FLAGS_EVENT_CONSTRAINT(0xc7, 0xf),    /* SSEX_UOPS_RETIRED.* */
724         INTEL_FLAGS_UEVENT_CONSTRAINT(0x20c8, 0xf), /* ITLB_MISS_RETIRED */
725         INTEL_FLAGS_EVENT_CONSTRAINT(0xcb, 0xf),    /* MEM_LOAD_RETIRED.* */
726         INTEL_FLAGS_EVENT_CONSTRAINT(0xf7, 0xf),    /* FP_ASSIST.* */
727         /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */
728         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x0f),
729         EVENT_CONSTRAINT_END
730 };
731
732 struct event_constraint intel_westmere_pebs_event_constraints[] = {
733         INTEL_PLD_CONSTRAINT(0x100b, 0xf),      /* MEM_INST_RETIRED.* */
734         INTEL_FLAGS_EVENT_CONSTRAINT(0x0f, 0xf),    /* MEM_UNCORE_RETIRED.* */
735         INTEL_FLAGS_UEVENT_CONSTRAINT(0x010c, 0xf), /* MEM_STORE_RETIRED.DTLB_MISS */
736         INTEL_FLAGS_EVENT_CONSTRAINT(0xc0, 0xf),    /* INSTR_RETIRED.* */
737         INTEL_EVENT_CONSTRAINT(0xc2, 0xf),    /* UOPS_RETIRED.* */
738         INTEL_FLAGS_EVENT_CONSTRAINT(0xc4, 0xf),    /* BR_INST_RETIRED.* */
739         INTEL_FLAGS_EVENT_CONSTRAINT(0xc5, 0xf),    /* BR_MISP_RETIRED.* */
740         INTEL_FLAGS_EVENT_CONSTRAINT(0xc7, 0xf),    /* SSEX_UOPS_RETIRED.* */
741         INTEL_FLAGS_UEVENT_CONSTRAINT(0x20c8, 0xf), /* ITLB_MISS_RETIRED */
742         INTEL_FLAGS_EVENT_CONSTRAINT(0xcb, 0xf),    /* MEM_LOAD_RETIRED.* */
743         INTEL_FLAGS_EVENT_CONSTRAINT(0xf7, 0xf),    /* FP_ASSIST.* */
744         /* INST_RETIRED.ANY_P, inv=1, cmask=16 (cycles:p). */
745         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x0f),
746         EVENT_CONSTRAINT_END
747 };
748
749 struct event_constraint intel_snb_pebs_event_constraints[] = {
750         INTEL_FLAGS_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PRECDIST */
751         INTEL_PLD_CONSTRAINT(0x01cd, 0x8),    /* MEM_TRANS_RETIRED.LAT_ABOVE_THR */
752         INTEL_PST_CONSTRAINT(0x02cd, 0x8),    /* MEM_TRANS_RETIRED.PRECISE_STORES */
753         /* UOPS_RETIRED.ALL, inv=1, cmask=16 (cycles:p). */
754         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c2, 0xf),
755         INTEL_EXCLEVT_CONSTRAINT(0xd0, 0xf),    /* MEM_UOP_RETIRED.* */
756         INTEL_EXCLEVT_CONSTRAINT(0xd1, 0xf),    /* MEM_LOAD_UOPS_RETIRED.* */
757         INTEL_EXCLEVT_CONSTRAINT(0xd2, 0xf),    /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */
758         INTEL_EXCLEVT_CONSTRAINT(0xd3, 0xf),    /* MEM_LOAD_UOPS_LLC_MISS_RETIRED.* */
759         /* Allow all events as PEBS with no flags */
760         INTEL_ALL_EVENT_CONSTRAINT(0, 0xf),
761         EVENT_CONSTRAINT_END
762 };
763
764 struct event_constraint intel_ivb_pebs_event_constraints[] = {
765         INTEL_FLAGS_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PRECDIST */
766         INTEL_PLD_CONSTRAINT(0x01cd, 0x8),    /* MEM_TRANS_RETIRED.LAT_ABOVE_THR */
767         INTEL_PST_CONSTRAINT(0x02cd, 0x8),    /* MEM_TRANS_RETIRED.PRECISE_STORES */
768         /* UOPS_RETIRED.ALL, inv=1, cmask=16 (cycles:p). */
769         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c2, 0xf),
770         /* INST_RETIRED.PREC_DIST, inv=1, cmask=16 (cycles:ppp). */
771         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c0, 0x2),
772         INTEL_EXCLEVT_CONSTRAINT(0xd0, 0xf),    /* MEM_UOP_RETIRED.* */
773         INTEL_EXCLEVT_CONSTRAINT(0xd1, 0xf),    /* MEM_LOAD_UOPS_RETIRED.* */
774         INTEL_EXCLEVT_CONSTRAINT(0xd2, 0xf),    /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */
775         INTEL_EXCLEVT_CONSTRAINT(0xd3, 0xf),    /* MEM_LOAD_UOPS_LLC_MISS_RETIRED.* */
776         /* Allow all events as PEBS with no flags */
777         INTEL_ALL_EVENT_CONSTRAINT(0, 0xf),
778         EVENT_CONSTRAINT_END
779 };
780
781 struct event_constraint intel_hsw_pebs_event_constraints[] = {
782         INTEL_FLAGS_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PRECDIST */
783         INTEL_PLD_CONSTRAINT(0x01cd, 0xf),    /* MEM_TRANS_RETIRED.* */
784         /* UOPS_RETIRED.ALL, inv=1, cmask=16 (cycles:p). */
785         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c2, 0xf),
786         /* INST_RETIRED.PREC_DIST, inv=1, cmask=16 (cycles:ppp). */
787         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c0, 0x2),
788         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_NA(0x01c2, 0xf), /* UOPS_RETIRED.ALL */
789         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XLD(0x11d0, 0xf), /* MEM_UOPS_RETIRED.STLB_MISS_LOADS */
790         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XLD(0x21d0, 0xf), /* MEM_UOPS_RETIRED.LOCK_LOADS */
791         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XLD(0x41d0, 0xf), /* MEM_UOPS_RETIRED.SPLIT_LOADS */
792         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XLD(0x81d0, 0xf), /* MEM_UOPS_RETIRED.ALL_LOADS */
793         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XST(0x12d0, 0xf), /* MEM_UOPS_RETIRED.STLB_MISS_STORES */
794         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XST(0x42d0, 0xf), /* MEM_UOPS_RETIRED.SPLIT_STORES */
795         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_XST(0x82d0, 0xf), /* MEM_UOPS_RETIRED.ALL_STORES */
796         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_XLD(0xd1, 0xf),    /* MEM_LOAD_UOPS_RETIRED.* */
797         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_XLD(0xd2, 0xf),    /* MEM_LOAD_UOPS_L3_HIT_RETIRED.* */
798         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_XLD(0xd3, 0xf),    /* MEM_LOAD_UOPS_L3_MISS_RETIRED.* */
799         /* Allow all events as PEBS with no flags */
800         INTEL_ALL_EVENT_CONSTRAINT(0, 0xf),
801         EVENT_CONSTRAINT_END
802 };
803
804 struct event_constraint intel_bdw_pebs_event_constraints[] = {
805         INTEL_FLAGS_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PRECDIST */
806         INTEL_PLD_CONSTRAINT(0x01cd, 0xf),    /* MEM_TRANS_RETIRED.* */
807         /* UOPS_RETIRED.ALL, inv=1, cmask=16 (cycles:p). */
808         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c2, 0xf),
809         /* INST_RETIRED.PREC_DIST, inv=1, cmask=16 (cycles:ppp). */
810         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c0, 0x2),
811         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_NA(0x01c2, 0xf), /* UOPS_RETIRED.ALL */
812         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x11d0, 0xf), /* MEM_UOPS_RETIRED.STLB_MISS_LOADS */
813         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x21d0, 0xf), /* MEM_UOPS_RETIRED.LOCK_LOADS */
814         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x41d0, 0xf), /* MEM_UOPS_RETIRED.SPLIT_LOADS */
815         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x81d0, 0xf), /* MEM_UOPS_RETIRED.ALL_LOADS */
816         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x12d0, 0xf), /* MEM_UOPS_RETIRED.STLB_MISS_STORES */
817         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x42d0, 0xf), /* MEM_UOPS_RETIRED.SPLIT_STORES */
818         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x82d0, 0xf), /* MEM_UOPS_RETIRED.ALL_STORES */
819         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd1, 0xf),    /* MEM_LOAD_UOPS_RETIRED.* */
820         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd2, 0xf),    /* MEM_LOAD_UOPS_L3_HIT_RETIRED.* */
821         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd3, 0xf),    /* MEM_LOAD_UOPS_L3_MISS_RETIRED.* */
822         /* Allow all events as PEBS with no flags */
823         INTEL_ALL_EVENT_CONSTRAINT(0, 0xf),
824         EVENT_CONSTRAINT_END
825 };
826
827
828 struct event_constraint intel_skl_pebs_event_constraints[] = {
829         INTEL_FLAGS_UEVENT_CONSTRAINT(0x1c0, 0x2),      /* INST_RETIRED.PREC_DIST */
830         /* INST_RETIRED.PREC_DIST, inv=1, cmask=16 (cycles:ppp). */
831         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108001c0, 0x2),
832         /* INST_RETIRED.TOTAL_CYCLES_PS (inv=1, cmask=16) (cycles:p). */
833         INTEL_FLAGS_UEVENT_CONSTRAINT(0x108000c0, 0x0f),
834         INTEL_PLD_CONSTRAINT(0x1cd, 0xf),                     /* MEM_TRANS_RETIRED.* */
835         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x11d0, 0xf), /* MEM_INST_RETIRED.STLB_MISS_LOADS */
836         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x12d0, 0xf), /* MEM_INST_RETIRED.STLB_MISS_STORES */
837         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x21d0, 0xf), /* MEM_INST_RETIRED.LOCK_LOADS */
838         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x22d0, 0xf), /* MEM_INST_RETIRED.LOCK_STORES */
839         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x41d0, 0xf), /* MEM_INST_RETIRED.SPLIT_LOADS */
840         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x42d0, 0xf), /* MEM_INST_RETIRED.SPLIT_STORES */
841         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x81d0, 0xf), /* MEM_INST_RETIRED.ALL_LOADS */
842         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x82d0, 0xf), /* MEM_INST_RETIRED.ALL_STORES */
843         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd1, 0xf),    /* MEM_LOAD_RETIRED.* */
844         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd2, 0xf),    /* MEM_LOAD_L3_HIT_RETIRED.* */
845         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD(0xd3, 0xf),    /* MEM_LOAD_L3_MISS_RETIRED.* */
846         /* Allow all events as PEBS with no flags */
847         INTEL_ALL_EVENT_CONSTRAINT(0, 0xf),
848         EVENT_CONSTRAINT_END
849 };
850
851 struct event_constraint intel_icl_pebs_event_constraints[] = {
852         INTEL_FLAGS_UEVENT_CONSTRAINT(0x1c0, 0x100000000ULL),   /* INST_RETIRED.PREC_DIST */
853         INTEL_FLAGS_UEVENT_CONSTRAINT(0x0400, 0x800000000ULL),  /* SLOTS */
854
855         INTEL_PLD_CONSTRAINT(0x1cd, 0xff),                      /* MEM_TRANS_RETIRED.LOAD_LATENCY */
856         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_LD(0x1d0, 0xf),    /* MEM_INST_RETIRED.LOAD */
857         INTEL_FLAGS_UEVENT_CONSTRAINT_DATALA_ST(0x2d0, 0xf),    /* MEM_INST_RETIRED.STORE */
858
859         INTEL_FLAGS_EVENT_CONSTRAINT_DATALA_LD_RANGE(0xd1, 0xd4, 0xf), /* MEM_LOAD_*_RETIRED.* */
860
861         INTEL_FLAGS_EVENT_CONSTRAINT(0xd0, 0xf),                /* MEM_INST_RETIRED.* */
862
863         /*
864          * Everything else is handled by PMU_FL_PEBS_ALL, because we
865          * need the full constraints from the main table.
866          */
867
868         EVENT_CONSTRAINT_END
869 };
870
871 struct event_constraint *intel_pebs_constraints(struct perf_event *event)
872 {
873         struct event_constraint *c;
874
875         if (!event->attr.precise_ip)
876                 return NULL;
877
878         if (x86_pmu.pebs_constraints) {
879                 for_each_event_constraint(c, x86_pmu.pebs_constraints) {
880                         if (constraint_match(c, event->hw.config)) {
881                                 event->hw.flags |= c->flags;
882                                 return c;
883                         }
884                 }
885         }
886
887         /*
888          * Extended PEBS support
889          * Makes the PEBS code search the normal constraints.
890          */
891         if (x86_pmu.flags & PMU_FL_PEBS_ALL)
892                 return NULL;
893
894         return &emptyconstraint;
895 }
896
897 /*
898  * We need the sched_task callback even for per-cpu events when we use
899  * the large interrupt threshold, such that we can provide PID and TID
900  * to PEBS samples.
901  */
902 static inline bool pebs_needs_sched_cb(struct cpu_hw_events *cpuc)
903 {
904         if (cpuc->n_pebs == cpuc->n_pebs_via_pt)
905                 return false;
906
907         return cpuc->n_pebs && (cpuc->n_pebs == cpuc->n_large_pebs);
908 }
909
910 void intel_pmu_pebs_sched_task(struct perf_event_context *ctx, bool sched_in)
911 {
912         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
913
914         if (!sched_in && pebs_needs_sched_cb(cpuc))
915                 intel_pmu_drain_pebs_buffer();
916 }
917
918 static inline void pebs_update_threshold(struct cpu_hw_events *cpuc)
919 {
920         struct debug_store *ds = cpuc->ds;
921         u64 threshold;
922         int reserved;
923
924         if (cpuc->n_pebs_via_pt)
925                 return;
926
927         if (x86_pmu.flags & PMU_FL_PEBS_ALL)
928                 reserved = x86_pmu.max_pebs_events + x86_pmu.num_counters_fixed;
929         else
930                 reserved = x86_pmu.max_pebs_events;
931
932         if (cpuc->n_pebs == cpuc->n_large_pebs) {
933                 threshold = ds->pebs_absolute_maximum -
934                         reserved * cpuc->pebs_record_size;
935         } else {
936                 threshold = ds->pebs_buffer_base + cpuc->pebs_record_size;
937         }
938
939         ds->pebs_interrupt_threshold = threshold;
940 }
941
942 static void adaptive_pebs_record_size_update(void)
943 {
944         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
945         u64 pebs_data_cfg = cpuc->pebs_data_cfg;
946         int sz = sizeof(struct pebs_basic);
947
948         if (pebs_data_cfg & PEBS_DATACFG_MEMINFO)
949                 sz += sizeof(struct pebs_meminfo);
950         if (pebs_data_cfg & PEBS_DATACFG_GP)
951                 sz += sizeof(struct pebs_gprs);
952         if (pebs_data_cfg & PEBS_DATACFG_XMMS)
953                 sz += sizeof(struct pebs_xmm);
954         if (pebs_data_cfg & PEBS_DATACFG_LBRS)
955                 sz += x86_pmu.lbr_nr * sizeof(struct lbr_entry);
956
957         cpuc->pebs_record_size = sz;
958 }
959
960 #define PERF_PEBS_MEMINFO_TYPE  (PERF_SAMPLE_ADDR | PERF_SAMPLE_DATA_SRC |   \
961                                 PERF_SAMPLE_PHYS_ADDR | PERF_SAMPLE_WEIGHT | \
962                                 PERF_SAMPLE_TRANSACTION)
963
964 static u64 pebs_update_adaptive_cfg(struct perf_event *event)
965 {
966         struct perf_event_attr *attr = &event->attr;
967         u64 sample_type = attr->sample_type;
968         u64 pebs_data_cfg = 0;
969         bool gprs, tsx_weight;
970
971         if (!(sample_type & ~(PERF_SAMPLE_IP|PERF_SAMPLE_TIME)) &&
972             attr->precise_ip > 1)
973                 return pebs_data_cfg;
974
975         if (sample_type & PERF_PEBS_MEMINFO_TYPE)
976                 pebs_data_cfg |= PEBS_DATACFG_MEMINFO;
977
978         /*
979          * We need GPRs when:
980          * + user requested them
981          * + precise_ip < 2 for the non event IP
982          * + For RTM TSX weight we need GPRs for the abort code.
983          */
984         gprs = (sample_type & PERF_SAMPLE_REGS_INTR) &&
985                (attr->sample_regs_intr & PEBS_GP_REGS);
986
987         tsx_weight = (sample_type & PERF_SAMPLE_WEIGHT) &&
988                      ((attr->config & INTEL_ARCH_EVENT_MASK) ==
989                       x86_pmu.rtm_abort_event);
990
991         if (gprs || (attr->precise_ip < 2) || tsx_weight)
992                 pebs_data_cfg |= PEBS_DATACFG_GP;
993
994         if ((sample_type & PERF_SAMPLE_REGS_INTR) &&
995             (attr->sample_regs_intr & PERF_REG_EXTENDED_MASK))
996                 pebs_data_cfg |= PEBS_DATACFG_XMMS;
997
998         if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
999                 /*
1000                  * For now always log all LBRs. Could configure this
1001                  * later.
1002                  */
1003                 pebs_data_cfg |= PEBS_DATACFG_LBRS |
1004                         ((x86_pmu.lbr_nr-1) << PEBS_DATACFG_LBR_SHIFT);
1005         }
1006
1007         return pebs_data_cfg;
1008 }
1009
1010 static void
1011 pebs_update_state(bool needed_cb, struct cpu_hw_events *cpuc,
1012                   struct perf_event *event, bool add)
1013 {
1014         struct pmu *pmu = event->ctx->pmu;
1015         /*
1016          * Make sure we get updated with the first PEBS
1017          * event. It will trigger also during removal, but
1018          * that does not hurt:
1019          */
1020         bool update = cpuc->n_pebs == 1;
1021
1022         if (needed_cb != pebs_needs_sched_cb(cpuc)) {
1023                 if (!needed_cb)
1024                         perf_sched_cb_inc(pmu);
1025                 else
1026                         perf_sched_cb_dec(pmu);
1027
1028                 update = true;
1029         }
1030
1031         /*
1032          * The PEBS record doesn't shrink on pmu::del(). Doing so would require
1033          * iterating all remaining PEBS events to reconstruct the config.
1034          */
1035         if (x86_pmu.intel_cap.pebs_baseline && add) {
1036                 u64 pebs_data_cfg;
1037
1038                 /* Clear pebs_data_cfg and pebs_record_size for first PEBS. */
1039                 if (cpuc->n_pebs == 1) {
1040                         cpuc->pebs_data_cfg = 0;
1041                         cpuc->pebs_record_size = sizeof(struct pebs_basic);
1042                 }
1043
1044                 pebs_data_cfg = pebs_update_adaptive_cfg(event);
1045
1046                 /* Update pebs_record_size if new event requires more data. */
1047                 if (pebs_data_cfg & ~cpuc->pebs_data_cfg) {
1048                         cpuc->pebs_data_cfg |= pebs_data_cfg;
1049                         adaptive_pebs_record_size_update();
1050                         update = true;
1051                 }
1052         }
1053
1054         if (update)
1055                 pebs_update_threshold(cpuc);
1056 }
1057
1058 void intel_pmu_pebs_add(struct perf_event *event)
1059 {
1060         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1061         struct hw_perf_event *hwc = &event->hw;
1062         bool needed_cb = pebs_needs_sched_cb(cpuc);
1063
1064         cpuc->n_pebs++;
1065         if (hwc->flags & PERF_X86_EVENT_LARGE_PEBS)
1066                 cpuc->n_large_pebs++;
1067         if (hwc->flags & PERF_X86_EVENT_PEBS_VIA_PT)
1068                 cpuc->n_pebs_via_pt++;
1069
1070         pebs_update_state(needed_cb, cpuc, event, true);
1071 }
1072
1073 static void intel_pmu_pebs_via_pt_disable(struct perf_event *event)
1074 {
1075         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1076
1077         if (!is_pebs_pt(event))
1078                 return;
1079
1080         if (!(cpuc->pebs_enabled & ~PEBS_VIA_PT_MASK))
1081                 cpuc->pebs_enabled &= ~PEBS_VIA_PT_MASK;
1082 }
1083
1084 static void intel_pmu_pebs_via_pt_enable(struct perf_event *event)
1085 {
1086         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1087         struct hw_perf_event *hwc = &event->hw;
1088         struct debug_store *ds = cpuc->ds;
1089
1090         if (!is_pebs_pt(event))
1091                 return;
1092
1093         if (!(event->hw.flags & PERF_X86_EVENT_LARGE_PEBS))
1094                 cpuc->pebs_enabled |= PEBS_PMI_AFTER_EACH_RECORD;
1095
1096         cpuc->pebs_enabled |= PEBS_OUTPUT_PT;
1097
1098         wrmsrl(MSR_RELOAD_PMC0 + hwc->idx, ds->pebs_event_reset[hwc->idx]);
1099 }
1100
1101 void intel_pmu_pebs_enable(struct perf_event *event)
1102 {
1103         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1104         struct hw_perf_event *hwc = &event->hw;
1105         struct debug_store *ds = cpuc->ds;
1106
1107         hwc->config &= ~ARCH_PERFMON_EVENTSEL_INT;
1108
1109         cpuc->pebs_enabled |= 1ULL << hwc->idx;
1110
1111         if ((event->hw.flags & PERF_X86_EVENT_PEBS_LDLAT) && (x86_pmu.version < 5))
1112                 cpuc->pebs_enabled |= 1ULL << (hwc->idx + 32);
1113         else if (event->hw.flags & PERF_X86_EVENT_PEBS_ST)
1114                 cpuc->pebs_enabled |= 1ULL << 63;
1115
1116         if (x86_pmu.intel_cap.pebs_baseline) {
1117                 hwc->config |= ICL_EVENTSEL_ADAPTIVE;
1118                 if (cpuc->pebs_data_cfg != cpuc->active_pebs_data_cfg) {
1119                         wrmsrl(MSR_PEBS_DATA_CFG, cpuc->pebs_data_cfg);
1120                         cpuc->active_pebs_data_cfg = cpuc->pebs_data_cfg;
1121                 }
1122         }
1123
1124         /*
1125          * Use auto-reload if possible to save a MSR write in the PMI.
1126          * This must be done in pmu::start(), because PERF_EVENT_IOC_PERIOD.
1127          */
1128         if (hwc->flags & PERF_X86_EVENT_AUTO_RELOAD) {
1129                 unsigned int idx = hwc->idx;
1130
1131                 if (idx >= INTEL_PMC_IDX_FIXED)
1132                         idx = MAX_PEBS_EVENTS + (idx - INTEL_PMC_IDX_FIXED);
1133                 ds->pebs_event_reset[idx] =
1134                         (u64)(-hwc->sample_period) & x86_pmu.cntval_mask;
1135         } else {
1136                 ds->pebs_event_reset[hwc->idx] = 0;
1137         }
1138
1139         intel_pmu_pebs_via_pt_enable(event);
1140 }
1141
1142 void intel_pmu_pebs_del(struct perf_event *event)
1143 {
1144         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1145         struct hw_perf_event *hwc = &event->hw;
1146         bool needed_cb = pebs_needs_sched_cb(cpuc);
1147
1148         cpuc->n_pebs--;
1149         if (hwc->flags & PERF_X86_EVENT_LARGE_PEBS)
1150                 cpuc->n_large_pebs--;
1151         if (hwc->flags & PERF_X86_EVENT_PEBS_VIA_PT)
1152                 cpuc->n_pebs_via_pt--;
1153
1154         pebs_update_state(needed_cb, cpuc, event, false);
1155 }
1156
1157 void intel_pmu_pebs_disable(struct perf_event *event)
1158 {
1159         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1160         struct hw_perf_event *hwc = &event->hw;
1161
1162         if (cpuc->n_pebs == cpuc->n_large_pebs &&
1163             cpuc->n_pebs != cpuc->n_pebs_via_pt)
1164                 intel_pmu_drain_pebs_buffer();
1165
1166         cpuc->pebs_enabled &= ~(1ULL << hwc->idx);
1167
1168         if ((event->hw.flags & PERF_X86_EVENT_PEBS_LDLAT) &&
1169             (x86_pmu.version < 5))
1170                 cpuc->pebs_enabled &= ~(1ULL << (hwc->idx + 32));
1171         else if (event->hw.flags & PERF_X86_EVENT_PEBS_ST)
1172                 cpuc->pebs_enabled &= ~(1ULL << 63);
1173
1174         intel_pmu_pebs_via_pt_disable(event);
1175
1176         if (cpuc->enabled)
1177                 wrmsrl(MSR_IA32_PEBS_ENABLE, cpuc->pebs_enabled);
1178
1179         hwc->config |= ARCH_PERFMON_EVENTSEL_INT;
1180 }
1181
1182 void intel_pmu_pebs_enable_all(void)
1183 {
1184         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1185
1186         if (cpuc->pebs_enabled)
1187                 wrmsrl(MSR_IA32_PEBS_ENABLE, cpuc->pebs_enabled);
1188 }
1189
1190 void intel_pmu_pebs_disable_all(void)
1191 {
1192         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1193
1194         if (cpuc->pebs_enabled)
1195                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
1196 }
1197
1198 static int intel_pmu_pebs_fixup_ip(struct pt_regs *regs)
1199 {
1200         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1201         unsigned long from = cpuc->lbr_entries[0].from;
1202         unsigned long old_to, to = cpuc->lbr_entries[0].to;
1203         unsigned long ip = regs->ip;
1204         int is_64bit = 0;
1205         void *kaddr;
1206         int size;
1207
1208         /*
1209          * We don't need to fixup if the PEBS assist is fault like
1210          */
1211         if (!x86_pmu.intel_cap.pebs_trap)
1212                 return 1;
1213
1214         /*
1215          * No LBR entry, no basic block, no rewinding
1216          */
1217         if (!cpuc->lbr_stack.nr || !from || !to)
1218                 return 0;
1219
1220         /*
1221          * Basic blocks should never cross user/kernel boundaries
1222          */
1223         if (kernel_ip(ip) != kernel_ip(to))
1224                 return 0;
1225
1226         /*
1227          * unsigned math, either ip is before the start (impossible) or
1228          * the basic block is larger than 1 page (sanity)
1229          */
1230         if ((ip - to) > PEBS_FIXUP_SIZE)
1231                 return 0;
1232
1233         /*
1234          * We sampled a branch insn, rewind using the LBR stack
1235          */
1236         if (ip == to) {
1237                 set_linear_ip(regs, from);
1238                 return 1;
1239         }
1240
1241         size = ip - to;
1242         if (!kernel_ip(ip)) {
1243                 int bytes;
1244                 u8 *buf = this_cpu_read(insn_buffer);
1245
1246                 /* 'size' must fit our buffer, see above */
1247                 bytes = copy_from_user_nmi(buf, (void __user *)to, size);
1248                 if (bytes != 0)
1249                         return 0;
1250
1251                 kaddr = buf;
1252         } else {
1253                 kaddr = (void *)to;
1254         }
1255
1256         do {
1257                 struct insn insn;
1258
1259                 old_to = to;
1260
1261 #ifdef CONFIG_X86_64
1262                 is_64bit = kernel_ip(to) || !test_thread_flag(TIF_IA32);
1263 #endif
1264                 insn_init(&insn, kaddr, size, is_64bit);
1265                 insn_get_length(&insn);
1266                 /*
1267                  * Make sure there was not a problem decoding the
1268                  * instruction and getting the length.  This is
1269                  * doubly important because we have an infinite
1270                  * loop if insn.length=0.
1271                  */
1272                 if (!insn.length)
1273                         break;
1274
1275                 to += insn.length;
1276                 kaddr += insn.length;
1277                 size -= insn.length;
1278         } while (to < ip);
1279
1280         if (to == ip) {
1281                 set_linear_ip(regs, old_to);
1282                 return 1;
1283         }
1284
1285         /*
1286          * Even though we decoded the basic block, the instruction stream
1287          * never matched the given IP, either the TO or the IP got corrupted.
1288          */
1289         return 0;
1290 }
1291
1292 static inline u64 intel_get_tsx_weight(u64 tsx_tuning)
1293 {
1294         if (tsx_tuning) {
1295                 union hsw_tsx_tuning tsx = { .value = tsx_tuning };
1296                 return tsx.cycles_last_block;
1297         }
1298         return 0;
1299 }
1300
1301 static inline u64 intel_get_tsx_transaction(u64 tsx_tuning, u64 ax)
1302 {
1303         u64 txn = (tsx_tuning & PEBS_HSW_TSX_FLAGS) >> 32;
1304
1305         /* For RTM XABORTs also log the abort code from AX */
1306         if ((txn & PERF_TXN_TRANSACTION) && (ax & 1))
1307                 txn |= ((ax >> 24) & 0xff) << PERF_TXN_ABORT_SHIFT;
1308         return txn;
1309 }
1310
1311 static inline u64 get_pebs_status(void *n)
1312 {
1313         if (x86_pmu.intel_cap.pebs_format < 4)
1314                 return ((struct pebs_record_nhm *)n)->status;
1315         return ((struct pebs_basic *)n)->applicable_counters;
1316 }
1317
1318 #define PERF_X86_EVENT_PEBS_HSW_PREC \
1319                 (PERF_X86_EVENT_PEBS_ST_HSW | \
1320                  PERF_X86_EVENT_PEBS_LD_HSW | \
1321                  PERF_X86_EVENT_PEBS_NA_HSW)
1322
1323 static u64 get_data_src(struct perf_event *event, u64 aux)
1324 {
1325         u64 val = PERF_MEM_NA;
1326         int fl = event->hw.flags;
1327         bool fst = fl & (PERF_X86_EVENT_PEBS_ST | PERF_X86_EVENT_PEBS_HSW_PREC);
1328
1329         if (fl & PERF_X86_EVENT_PEBS_LDLAT)
1330                 val = load_latency_data(aux);
1331         else if (fst && (fl & PERF_X86_EVENT_PEBS_HSW_PREC))
1332                 val = precise_datala_hsw(event, aux);
1333         else if (fst)
1334                 val = precise_store_data(aux);
1335         return val;
1336 }
1337
1338 static void setup_pebs_fixed_sample_data(struct perf_event *event,
1339                                    struct pt_regs *iregs, void *__pebs,
1340                                    struct perf_sample_data *data,
1341                                    struct pt_regs *regs)
1342 {
1343         /*
1344          * We cast to the biggest pebs_record but are careful not to
1345          * unconditionally access the 'extra' entries.
1346          */
1347         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1348         struct pebs_record_skl *pebs = __pebs;
1349         u64 sample_type;
1350         int fll;
1351
1352         if (pebs == NULL)
1353                 return;
1354
1355         sample_type = event->attr.sample_type;
1356         fll = event->hw.flags & PERF_X86_EVENT_PEBS_LDLAT;
1357
1358         perf_sample_data_init(data, 0, event->hw.last_period);
1359
1360         data->period = event->hw.last_period;
1361
1362         /*
1363          * Use latency for weight (only avail with PEBS-LL)
1364          */
1365         if (fll && (sample_type & PERF_SAMPLE_WEIGHT))
1366                 data->weight = pebs->lat;
1367
1368         /*
1369          * data.data_src encodes the data source
1370          */
1371         if (sample_type & PERF_SAMPLE_DATA_SRC)
1372                 data->data_src.val = get_data_src(event, pebs->dse);
1373
1374         /*
1375          * We must however always use iregs for the unwinder to stay sane; the
1376          * record BP,SP,IP can point into thin air when the record is from a
1377          * previous PMI context or an (I)RET happened between the record and
1378          * PMI.
1379          */
1380         if (sample_type & PERF_SAMPLE_CALLCHAIN)
1381                 data->callchain = perf_callchain(event, iregs);
1382
1383         /*
1384          * We use the interrupt regs as a base because the PEBS record does not
1385          * contain a full regs set, specifically it seems to lack segment
1386          * descriptors, which get used by things like user_mode().
1387          *
1388          * In the simple case fix up only the IP for PERF_SAMPLE_IP.
1389          */
1390         *regs = *iregs;
1391
1392         /*
1393          * Initialize regs_>flags from PEBS,
1394          * Clear exact bit (which uses x86 EFLAGS Reserved bit 3),
1395          * i.e., do not rely on it being zero:
1396          */
1397         regs->flags = pebs->flags & ~PERF_EFLAGS_EXACT;
1398
1399         if (sample_type & PERF_SAMPLE_REGS_INTR) {
1400                 regs->ax = pebs->ax;
1401                 regs->bx = pebs->bx;
1402                 regs->cx = pebs->cx;
1403                 regs->dx = pebs->dx;
1404                 regs->si = pebs->si;
1405                 regs->di = pebs->di;
1406
1407                 regs->bp = pebs->bp;
1408                 regs->sp = pebs->sp;
1409
1410 #ifndef CONFIG_X86_32
1411                 regs->r8 = pebs->r8;
1412                 regs->r9 = pebs->r9;
1413                 regs->r10 = pebs->r10;
1414                 regs->r11 = pebs->r11;
1415                 regs->r12 = pebs->r12;
1416                 regs->r13 = pebs->r13;
1417                 regs->r14 = pebs->r14;
1418                 regs->r15 = pebs->r15;
1419 #endif
1420         }
1421
1422         if (event->attr.precise_ip > 1) {
1423                 /*
1424                  * Haswell and later processors have an 'eventing IP'
1425                  * (real IP) which fixes the off-by-1 skid in hardware.
1426                  * Use it when precise_ip >= 2 :
1427                  */
1428                 if (x86_pmu.intel_cap.pebs_format >= 2) {
1429                         set_linear_ip(regs, pebs->real_ip);
1430                         regs->flags |= PERF_EFLAGS_EXACT;
1431                 } else {
1432                         /* Otherwise, use PEBS off-by-1 IP: */
1433                         set_linear_ip(regs, pebs->ip);
1434
1435                         /*
1436                          * With precise_ip >= 2, try to fix up the off-by-1 IP
1437                          * using the LBR. If successful, the fixup function
1438                          * corrects regs->ip and calls set_linear_ip() on regs:
1439                          */
1440                         if (intel_pmu_pebs_fixup_ip(regs))
1441                                 regs->flags |= PERF_EFLAGS_EXACT;
1442                 }
1443         } else {
1444                 /*
1445                  * When precise_ip == 1, return the PEBS off-by-1 IP,
1446                  * no fixup attempted:
1447                  */
1448                 set_linear_ip(regs, pebs->ip);
1449         }
1450
1451
1452         if ((sample_type & (PERF_SAMPLE_ADDR | PERF_SAMPLE_PHYS_ADDR)) &&
1453             x86_pmu.intel_cap.pebs_format >= 1)
1454                 data->addr = pebs->dla;
1455
1456         if (x86_pmu.intel_cap.pebs_format >= 2) {
1457                 /* Only set the TSX weight when no memory weight. */
1458                 if ((sample_type & PERF_SAMPLE_WEIGHT) && !fll)
1459                         data->weight = intel_get_tsx_weight(pebs->tsx_tuning);
1460
1461                 if (sample_type & PERF_SAMPLE_TRANSACTION)
1462                         data->txn = intel_get_tsx_transaction(pebs->tsx_tuning,
1463                                                               pebs->ax);
1464         }
1465
1466         /*
1467          * v3 supplies an accurate time stamp, so we use that
1468          * for the time stamp.
1469          *
1470          * We can only do this for the default trace clock.
1471          */
1472         if (x86_pmu.intel_cap.pebs_format >= 3 &&
1473                 event->attr.use_clockid == 0)
1474                 data->time = native_sched_clock_from_tsc(pebs->tsc);
1475
1476         if (has_branch_stack(event))
1477                 data->br_stack = &cpuc->lbr_stack;
1478 }
1479
1480 static void adaptive_pebs_save_regs(struct pt_regs *regs,
1481                                     struct pebs_gprs *gprs)
1482 {
1483         regs->ax = gprs->ax;
1484         regs->bx = gprs->bx;
1485         regs->cx = gprs->cx;
1486         regs->dx = gprs->dx;
1487         regs->si = gprs->si;
1488         regs->di = gprs->di;
1489         regs->bp = gprs->bp;
1490         regs->sp = gprs->sp;
1491 #ifndef CONFIG_X86_32
1492         regs->r8 = gprs->r8;
1493         regs->r9 = gprs->r9;
1494         regs->r10 = gprs->r10;
1495         regs->r11 = gprs->r11;
1496         regs->r12 = gprs->r12;
1497         regs->r13 = gprs->r13;
1498         regs->r14 = gprs->r14;
1499         regs->r15 = gprs->r15;
1500 #endif
1501 }
1502
1503 /*
1504  * With adaptive PEBS the layout depends on what fields are configured.
1505  */
1506
1507 static void setup_pebs_adaptive_sample_data(struct perf_event *event,
1508                                             struct pt_regs *iregs, void *__pebs,
1509                                             struct perf_sample_data *data,
1510                                             struct pt_regs *regs)
1511 {
1512         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1513         struct pebs_basic *basic = __pebs;
1514         void *next_record = basic + 1;
1515         u64 sample_type;
1516         u64 format_size;
1517         struct pebs_meminfo *meminfo = NULL;
1518         struct pebs_gprs *gprs = NULL;
1519         struct x86_perf_regs *perf_regs;
1520
1521         if (basic == NULL)
1522                 return;
1523
1524         perf_regs = container_of(regs, struct x86_perf_regs, regs);
1525         perf_regs->xmm_regs = NULL;
1526
1527         sample_type = event->attr.sample_type;
1528         format_size = basic->format_size;
1529         perf_sample_data_init(data, 0, event->hw.last_period);
1530         data->period = event->hw.last_period;
1531
1532         if (event->attr.use_clockid == 0)
1533                 data->time = native_sched_clock_from_tsc(basic->tsc);
1534
1535         /*
1536          * We must however always use iregs for the unwinder to stay sane; the
1537          * record BP,SP,IP can point into thin air when the record is from a
1538          * previous PMI context or an (I)RET happened between the record and
1539          * PMI.
1540          */
1541         if (sample_type & PERF_SAMPLE_CALLCHAIN)
1542                 data->callchain = perf_callchain(event, iregs);
1543
1544         *regs = *iregs;
1545         /* The ip in basic is EventingIP */
1546         set_linear_ip(regs, basic->ip);
1547         regs->flags = PERF_EFLAGS_EXACT;
1548
1549         /*
1550          * The record for MEMINFO is in front of GP
1551          * But PERF_SAMPLE_TRANSACTION needs gprs->ax.
1552          * Save the pointer here but process later.
1553          */
1554         if (format_size & PEBS_DATACFG_MEMINFO) {
1555                 meminfo = next_record;
1556                 next_record = meminfo + 1;
1557         }
1558
1559         if (format_size & PEBS_DATACFG_GP) {
1560                 gprs = next_record;
1561                 next_record = gprs + 1;
1562
1563                 if (event->attr.precise_ip < 2) {
1564                         set_linear_ip(regs, gprs->ip);
1565                         regs->flags &= ~PERF_EFLAGS_EXACT;
1566                 }
1567
1568                 if (sample_type & PERF_SAMPLE_REGS_INTR)
1569                         adaptive_pebs_save_regs(regs, gprs);
1570         }
1571
1572         if (format_size & PEBS_DATACFG_MEMINFO) {
1573                 if (sample_type & PERF_SAMPLE_WEIGHT)
1574                         data->weight = meminfo->latency ?:
1575                                 intel_get_tsx_weight(meminfo->tsx_tuning);
1576
1577                 if (sample_type & PERF_SAMPLE_DATA_SRC)
1578                         data->data_src.val = get_data_src(event, meminfo->aux);
1579
1580                 if (sample_type & (PERF_SAMPLE_ADDR | PERF_SAMPLE_PHYS_ADDR))
1581                         data->addr = meminfo->address;
1582
1583                 if (sample_type & PERF_SAMPLE_TRANSACTION)
1584                         data->txn = intel_get_tsx_transaction(meminfo->tsx_tuning,
1585                                                           gprs ? gprs->ax : 0);
1586         }
1587
1588         if (format_size & PEBS_DATACFG_XMMS) {
1589                 struct pebs_xmm *xmm = next_record;
1590
1591                 next_record = xmm + 1;
1592                 perf_regs->xmm_regs = xmm->xmm;
1593         }
1594
1595         if (format_size & PEBS_DATACFG_LBRS) {
1596                 struct lbr_entry *lbr = next_record;
1597                 int num_lbr = ((format_size >> PEBS_DATACFG_LBR_SHIFT)
1598                                         & 0xff) + 1;
1599                 next_record = next_record + num_lbr * sizeof(struct lbr_entry);
1600
1601                 if (has_branch_stack(event)) {
1602                         intel_pmu_store_pebs_lbrs(lbr);
1603                         data->br_stack = &cpuc->lbr_stack;
1604                 }
1605         }
1606
1607         WARN_ONCE(next_record != __pebs + (format_size >> 48),
1608                         "PEBS record size %llu, expected %llu, config %llx\n",
1609                         format_size >> 48,
1610                         (u64)(next_record - __pebs),
1611                         basic->format_size);
1612 }
1613
1614 static inline void *
1615 get_next_pebs_record_by_bit(void *base, void *top, int bit)
1616 {
1617         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1618         void *at;
1619         u64 pebs_status;
1620
1621         /*
1622          * fmt0 does not have a status bitfield (does not use
1623          * perf_record_nhm format)
1624          */
1625         if (x86_pmu.intel_cap.pebs_format < 1)
1626                 return base;
1627
1628         if (base == NULL)
1629                 return NULL;
1630
1631         for (at = base; at < top; at += cpuc->pebs_record_size) {
1632                 unsigned long status = get_pebs_status(at);
1633
1634                 if (test_bit(bit, (unsigned long *)&status)) {
1635                         /* PEBS v3 has accurate status bits */
1636                         if (x86_pmu.intel_cap.pebs_format >= 3)
1637                                 return at;
1638
1639                         if (status == (1 << bit))
1640                                 return at;
1641
1642                         /* clear non-PEBS bit and re-check */
1643                         pebs_status = status & cpuc->pebs_enabled;
1644                         pebs_status &= PEBS_COUNTER_MASK;
1645                         if (pebs_status == (1 << bit))
1646                                 return at;
1647                 }
1648         }
1649         return NULL;
1650 }
1651
1652 void intel_pmu_auto_reload_read(struct perf_event *event)
1653 {
1654         WARN_ON(!(event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD));
1655
1656         perf_pmu_disable(event->pmu);
1657         intel_pmu_drain_pebs_buffer();
1658         perf_pmu_enable(event->pmu);
1659 }
1660
1661 /*
1662  * Special variant of intel_pmu_save_and_restart() for auto-reload.
1663  */
1664 static int
1665 intel_pmu_save_and_restart_reload(struct perf_event *event, int count)
1666 {
1667         struct hw_perf_event *hwc = &event->hw;
1668         int shift = 64 - x86_pmu.cntval_bits;
1669         u64 period = hwc->sample_period;
1670         u64 prev_raw_count, new_raw_count;
1671         s64 new, old;
1672
1673         WARN_ON(!period);
1674
1675         /*
1676          * drain_pebs() only happens when the PMU is disabled.
1677          */
1678         WARN_ON(this_cpu_read(cpu_hw_events.enabled));
1679
1680         prev_raw_count = local64_read(&hwc->prev_count);
1681         rdpmcl(hwc->event_base_rdpmc, new_raw_count);
1682         local64_set(&hwc->prev_count, new_raw_count);
1683
1684         /*
1685          * Since the counter increments a negative counter value and
1686          * overflows on the sign switch, giving the interval:
1687          *
1688          *   [-period, 0]
1689          *
1690          * the difference between two consequtive reads is:
1691          *
1692          *   A) value2 - value1;
1693          *      when no overflows have happened in between,
1694          *
1695          *   B) (0 - value1) + (value2 - (-period));
1696          *      when one overflow happened in between,
1697          *
1698          *   C) (0 - value1) + (n - 1) * (period) + (value2 - (-period));
1699          *      when @n overflows happened in between.
1700          *
1701          * Here A) is the obvious difference, B) is the extension to the
1702          * discrete interval, where the first term is to the top of the
1703          * interval and the second term is from the bottom of the next
1704          * interval and C) the extension to multiple intervals, where the
1705          * middle term is the whole intervals covered.
1706          *
1707          * An equivalent of C, by reduction, is:
1708          *
1709          *   value2 - value1 + n * period
1710          */
1711         new = ((s64)(new_raw_count << shift) >> shift);
1712         old = ((s64)(prev_raw_count << shift) >> shift);
1713         local64_add(new - old + count * period, &event->count);
1714
1715         local64_set(&hwc->period_left, -new);
1716
1717         perf_event_update_userpage(event);
1718
1719         return 0;
1720 }
1721
1722 static void __intel_pmu_pebs_event(struct perf_event *event,
1723                                    struct pt_regs *iregs,
1724                                    void *base, void *top,
1725                                    int bit, int count,
1726                                    void (*setup_sample)(struct perf_event *,
1727                                                 struct pt_regs *,
1728                                                 void *,
1729                                                 struct perf_sample_data *,
1730                                                 struct pt_regs *))
1731 {
1732         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1733         struct hw_perf_event *hwc = &event->hw;
1734         struct perf_sample_data data;
1735         struct x86_perf_regs perf_regs;
1736         struct pt_regs *regs = &perf_regs.regs;
1737         void *at = get_next_pebs_record_by_bit(base, top, bit);
1738         struct pt_regs dummy_iregs;
1739
1740         if (hwc->flags & PERF_X86_EVENT_AUTO_RELOAD) {
1741                 /*
1742                  * Now, auto-reload is only enabled in fixed period mode.
1743                  * The reload value is always hwc->sample_period.
1744                  * May need to change it, if auto-reload is enabled in
1745                  * freq mode later.
1746                  */
1747                 intel_pmu_save_and_restart_reload(event, count);
1748         } else if (!intel_pmu_save_and_restart(event))
1749                 return;
1750
1751         if (!iregs)
1752                 iregs = &dummy_iregs;
1753
1754         while (count > 1) {
1755                 setup_sample(event, iregs, at, &data, regs);
1756                 perf_event_output(event, &data, regs);
1757                 at += cpuc->pebs_record_size;
1758                 at = get_next_pebs_record_by_bit(at, top, bit);
1759                 count--;
1760         }
1761
1762         setup_sample(event, iregs, at, &data, regs);
1763         if (iregs == &dummy_iregs) {
1764                 /*
1765                  * The PEBS records may be drained in the non-overflow context,
1766                  * e.g., large PEBS + context switch. Perf should treat the
1767                  * last record the same as other PEBS records, and doesn't
1768                  * invoke the generic overflow handler.
1769                  */
1770                 perf_event_output(event, &data, regs);
1771         } else {
1772                 /*
1773                  * All but the last records are processed.
1774                  * The last one is left to be able to call the overflow handler.
1775                  */
1776                 if (perf_event_overflow(event, &data, regs))
1777                         x86_pmu_stop(event, 0);
1778         }
1779 }
1780
1781 static void intel_pmu_drain_pebs_core(struct pt_regs *iregs)
1782 {
1783         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1784         struct debug_store *ds = cpuc->ds;
1785         struct perf_event *event = cpuc->events[0]; /* PMC0 only */
1786         struct pebs_record_core *at, *top;
1787         int n;
1788
1789         if (!x86_pmu.pebs_active)
1790                 return;
1791
1792         at  = (struct pebs_record_core *)(unsigned long)ds->pebs_buffer_base;
1793         top = (struct pebs_record_core *)(unsigned long)ds->pebs_index;
1794
1795         /*
1796          * Whatever else happens, drain the thing
1797          */
1798         ds->pebs_index = ds->pebs_buffer_base;
1799
1800         if (!test_bit(0, cpuc->active_mask))
1801                 return;
1802
1803         WARN_ON_ONCE(!event);
1804
1805         if (!event->attr.precise_ip)
1806                 return;
1807
1808         n = top - at;
1809         if (n <= 0) {
1810                 if (event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD)
1811                         intel_pmu_save_and_restart_reload(event, 0);
1812                 return;
1813         }
1814
1815         __intel_pmu_pebs_event(event, iregs, at, top, 0, n,
1816                                setup_pebs_fixed_sample_data);
1817 }
1818
1819 static void intel_pmu_pebs_event_update_no_drain(struct cpu_hw_events *cpuc, int size)
1820 {
1821         struct perf_event *event;
1822         int bit;
1823
1824         /*
1825          * The drain_pebs() could be called twice in a short period
1826          * for auto-reload event in pmu::read(). There are no
1827          * overflows have happened in between.
1828          * It needs to call intel_pmu_save_and_restart_reload() to
1829          * update the event->count for this case.
1830          */
1831         for_each_set_bit(bit, (unsigned long *)&cpuc->pebs_enabled, size) {
1832                 event = cpuc->events[bit];
1833                 if (event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD)
1834                         intel_pmu_save_and_restart_reload(event, 0);
1835         }
1836 }
1837
1838 static void intel_pmu_drain_pebs_nhm(struct pt_regs *iregs)
1839 {
1840         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1841         struct debug_store *ds = cpuc->ds;
1842         struct perf_event *event;
1843         void *base, *at, *top;
1844         short counts[INTEL_PMC_IDX_FIXED + MAX_FIXED_PEBS_EVENTS] = {};
1845         short error[INTEL_PMC_IDX_FIXED + MAX_FIXED_PEBS_EVENTS] = {};
1846         int bit, i, size;
1847         u64 mask;
1848
1849         if (!x86_pmu.pebs_active)
1850                 return;
1851
1852         base = (struct pebs_record_nhm *)(unsigned long)ds->pebs_buffer_base;
1853         top = (struct pebs_record_nhm *)(unsigned long)ds->pebs_index;
1854
1855         ds->pebs_index = ds->pebs_buffer_base;
1856
1857         mask = (1ULL << x86_pmu.max_pebs_events) - 1;
1858         size = x86_pmu.max_pebs_events;
1859         if (x86_pmu.flags & PMU_FL_PEBS_ALL) {
1860                 mask |= ((1ULL << x86_pmu.num_counters_fixed) - 1) << INTEL_PMC_IDX_FIXED;
1861                 size = INTEL_PMC_IDX_FIXED + x86_pmu.num_counters_fixed;
1862         }
1863
1864         if (unlikely(base >= top)) {
1865                 intel_pmu_pebs_event_update_no_drain(cpuc, size);
1866                 return;
1867         }
1868
1869         for (at = base; at < top; at += x86_pmu.pebs_record_size) {
1870                 struct pebs_record_nhm *p = at;
1871                 u64 pebs_status;
1872
1873                 pebs_status = p->status & cpuc->pebs_enabled;
1874                 pebs_status &= mask;
1875
1876                 /* PEBS v3 has more accurate status bits */
1877                 if (x86_pmu.intel_cap.pebs_format >= 3) {
1878                         for_each_set_bit(bit, (unsigned long *)&pebs_status, size)
1879                                 counts[bit]++;
1880
1881                         continue;
1882                 }
1883
1884                 /*
1885                  * On some CPUs the PEBS status can be zero when PEBS is
1886                  * racing with clearing of GLOBAL_STATUS.
1887                  *
1888                  * Normally we would drop that record, but in the
1889                  * case when there is only a single active PEBS event
1890                  * we can assume it's for that event.
1891                  */
1892                 if (!pebs_status && cpuc->pebs_enabled &&
1893                         !(cpuc->pebs_enabled & (cpuc->pebs_enabled-1)))
1894                         pebs_status = cpuc->pebs_enabled;
1895
1896                 bit = find_first_bit((unsigned long *)&pebs_status,
1897                                         x86_pmu.max_pebs_events);
1898                 if (bit >= x86_pmu.max_pebs_events)
1899                         continue;
1900
1901                 /*
1902                  * The PEBS hardware does not deal well with the situation
1903                  * when events happen near to each other and multiple bits
1904                  * are set. But it should happen rarely.
1905                  *
1906                  * If these events include one PEBS and multiple non-PEBS
1907                  * events, it doesn't impact PEBS record. The record will
1908                  * be handled normally. (slow path)
1909                  *
1910                  * If these events include two or more PEBS events, the
1911                  * records for the events can be collapsed into a single
1912                  * one, and it's not possible to reconstruct all events
1913                  * that caused the PEBS record. It's called collision.
1914                  * If collision happened, the record will be dropped.
1915                  */
1916                 if (p->status != (1ULL << bit)) {
1917                         for_each_set_bit(i, (unsigned long *)&pebs_status, size)
1918                                 error[i]++;
1919                         continue;
1920                 }
1921
1922                 counts[bit]++;
1923         }
1924
1925         for_each_set_bit(bit, (unsigned long *)&mask, size) {
1926                 if ((counts[bit] == 0) && (error[bit] == 0))
1927                         continue;
1928
1929                 event = cpuc->events[bit];
1930                 if (WARN_ON_ONCE(!event))
1931                         continue;
1932
1933                 if (WARN_ON_ONCE(!event->attr.precise_ip))
1934                         continue;
1935
1936                 /* log dropped samples number */
1937                 if (error[bit]) {
1938                         perf_log_lost_samples(event, error[bit]);
1939
1940                         if (perf_event_account_interrupt(event))
1941                                 x86_pmu_stop(event, 0);
1942                 }
1943
1944                 if (counts[bit]) {
1945                         __intel_pmu_pebs_event(event, iregs, base,
1946                                                top, bit, counts[bit],
1947                                                setup_pebs_fixed_sample_data);
1948                 }
1949         }
1950 }
1951
1952 static void intel_pmu_drain_pebs_icl(struct pt_regs *iregs)
1953 {
1954         short counts[INTEL_PMC_IDX_FIXED + MAX_FIXED_PEBS_EVENTS] = {};
1955         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1956         struct debug_store *ds = cpuc->ds;
1957         struct perf_event *event;
1958         void *base, *at, *top;
1959         int bit, size;
1960         u64 mask;
1961
1962         if (!x86_pmu.pebs_active)
1963                 return;
1964
1965         base = (struct pebs_basic *)(unsigned long)ds->pebs_buffer_base;
1966         top = (struct pebs_basic *)(unsigned long)ds->pebs_index;
1967
1968         ds->pebs_index = ds->pebs_buffer_base;
1969
1970         mask = ((1ULL << x86_pmu.max_pebs_events) - 1) |
1971                (((1ULL << x86_pmu.num_counters_fixed) - 1) << INTEL_PMC_IDX_FIXED);
1972         size = INTEL_PMC_IDX_FIXED + x86_pmu.num_counters_fixed;
1973
1974         if (unlikely(base >= top)) {
1975                 intel_pmu_pebs_event_update_no_drain(cpuc, size);
1976                 return;
1977         }
1978
1979         for (at = base; at < top; at += cpuc->pebs_record_size) {
1980                 u64 pebs_status;
1981
1982                 pebs_status = get_pebs_status(at) & cpuc->pebs_enabled;
1983                 pebs_status &= mask;
1984
1985                 for_each_set_bit(bit, (unsigned long *)&pebs_status, size)
1986                         counts[bit]++;
1987         }
1988
1989         for_each_set_bit(bit, (unsigned long *)&mask, size) {
1990                 if (counts[bit] == 0)
1991                         continue;
1992
1993                 event = cpuc->events[bit];
1994                 if (WARN_ON_ONCE(!event))
1995                         continue;
1996
1997                 if (WARN_ON_ONCE(!event->attr.precise_ip))
1998                         continue;
1999
2000                 __intel_pmu_pebs_event(event, iregs, base,
2001                                        top, bit, counts[bit],
2002                                        setup_pebs_adaptive_sample_data);
2003         }
2004 }
2005
2006 /*
2007  * BTS, PEBS probe and setup
2008  */
2009
2010 void __init intel_ds_init(void)
2011 {
2012         /*
2013          * No support for 32bit formats
2014          */
2015         if (!boot_cpu_has(X86_FEATURE_DTES64))
2016                 return;
2017
2018         x86_pmu.bts  = boot_cpu_has(X86_FEATURE_BTS);
2019         x86_pmu.pebs = boot_cpu_has(X86_FEATURE_PEBS);
2020         x86_pmu.pebs_buffer_size = PEBS_BUFFER_SIZE;
2021         if (x86_pmu.version <= 4)
2022                 x86_pmu.pebs_no_isolation = 1;
2023
2024         if (x86_pmu.pebs) {
2025                 char pebs_type = x86_pmu.intel_cap.pebs_trap ?  '+' : '-';
2026                 char *pebs_qual = "";
2027                 int format = x86_pmu.intel_cap.pebs_format;
2028
2029                 if (format < 4)
2030                         x86_pmu.intel_cap.pebs_baseline = 0;
2031
2032                 switch (format) {
2033                 case 0:
2034                         pr_cont("PEBS fmt0%c, ", pebs_type);
2035                         x86_pmu.pebs_record_size = sizeof(struct pebs_record_core);
2036                         /*
2037                          * Using >PAGE_SIZE buffers makes the WRMSR to
2038                          * PERF_GLOBAL_CTRL in intel_pmu_enable_all()
2039                          * mysteriously hang on Core2.
2040                          *
2041                          * As a workaround, we don't do this.
2042                          */
2043                         x86_pmu.pebs_buffer_size = PAGE_SIZE;
2044                         x86_pmu.drain_pebs = intel_pmu_drain_pebs_core;
2045                         break;
2046
2047                 case 1:
2048                         pr_cont("PEBS fmt1%c, ", pebs_type);
2049                         x86_pmu.pebs_record_size = sizeof(struct pebs_record_nhm);
2050                         x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm;
2051                         break;
2052
2053                 case 2:
2054                         pr_cont("PEBS fmt2%c, ", pebs_type);
2055                         x86_pmu.pebs_record_size = sizeof(struct pebs_record_hsw);
2056                         x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm;
2057                         break;
2058
2059                 case 3:
2060                         pr_cont("PEBS fmt3%c, ", pebs_type);
2061                         x86_pmu.pebs_record_size =
2062                                                 sizeof(struct pebs_record_skl);
2063                         x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm;
2064                         x86_pmu.large_pebs_flags |= PERF_SAMPLE_TIME;
2065                         break;
2066
2067                 case 4:
2068                         x86_pmu.drain_pebs = intel_pmu_drain_pebs_icl;
2069                         x86_pmu.pebs_record_size = sizeof(struct pebs_basic);
2070                         if (x86_pmu.intel_cap.pebs_baseline) {
2071                                 x86_pmu.large_pebs_flags |=
2072                                         PERF_SAMPLE_BRANCH_STACK |
2073                                         PERF_SAMPLE_TIME;
2074                                 x86_pmu.flags |= PMU_FL_PEBS_ALL;
2075                                 pebs_qual = "-baseline";
2076                                 x86_get_pmu()->capabilities |= PERF_PMU_CAP_EXTENDED_REGS;
2077                         } else {
2078                                 /* Only basic record supported */
2079                                 x86_pmu.large_pebs_flags &=
2080                                         ~(PERF_SAMPLE_ADDR |
2081                                           PERF_SAMPLE_TIME |
2082                                           PERF_SAMPLE_DATA_SRC |
2083                                           PERF_SAMPLE_TRANSACTION |
2084                                           PERF_SAMPLE_REGS_USER |
2085                                           PERF_SAMPLE_REGS_INTR);
2086                         }
2087                         pr_cont("PEBS fmt4%c%s, ", pebs_type, pebs_qual);
2088
2089                         if (x86_pmu.intel_cap.pebs_output_pt_available) {
2090                                 pr_cont("PEBS-via-PT, ");
2091                                 x86_get_pmu()->capabilities |= PERF_PMU_CAP_AUX_OUTPUT;
2092                         }
2093
2094                         break;
2095
2096                 default:
2097                         pr_cont("no PEBS fmt%d%c, ", format, pebs_type);
2098                         x86_pmu.pebs = 0;
2099                 }
2100         }
2101 }
2102
2103 void perf_restore_debug_store(void)
2104 {
2105         struct debug_store *ds = __this_cpu_read(cpu_hw_events.ds);
2106
2107         if (!x86_pmu.bts && !x86_pmu.pebs)
2108                 return;
2109
2110         wrmsrl(MSR_IA32_DS_AREA, (unsigned long)ds);
2111 }