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