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