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