xref: /openbmc/linux/arch/x86/events/intel/ds.c (revision c4c3c32d)
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 	/*
1234 	 * Make sure we get updated with the first PEBS
1235 	 * event. It will trigger also during removal, but
1236 	 * that does not hurt:
1237 	 */
1238 	if (cpuc->n_pebs == 1)
1239 		cpuc->pebs_data_cfg = PEBS_UPDATE_DS_SW;
1240 
1241 	if (needed_cb != pebs_needs_sched_cb(cpuc)) {
1242 		if (!needed_cb)
1243 			perf_sched_cb_inc(pmu);
1244 		else
1245 			perf_sched_cb_dec(pmu);
1246 
1247 		cpuc->pebs_data_cfg |= PEBS_UPDATE_DS_SW;
1248 	}
1249 
1250 	/*
1251 	 * The PEBS record doesn't shrink on pmu::del(). Doing so would require
1252 	 * iterating all remaining PEBS events to reconstruct the config.
1253 	 */
1254 	if (x86_pmu.intel_cap.pebs_baseline && add) {
1255 		u64 pebs_data_cfg;
1256 
1257 		pebs_data_cfg = pebs_update_adaptive_cfg(event);
1258 		/*
1259 		 * Be sure to update the thresholds when we change the record.
1260 		 */
1261 		if (pebs_data_cfg & ~cpuc->pebs_data_cfg)
1262 			cpuc->pebs_data_cfg |= pebs_data_cfg | PEBS_UPDATE_DS_SW;
1263 	}
1264 }
1265 
1266 void intel_pmu_pebs_add(struct perf_event *event)
1267 {
1268 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1269 	struct hw_perf_event *hwc = &event->hw;
1270 	bool needed_cb = pebs_needs_sched_cb(cpuc);
1271 
1272 	cpuc->n_pebs++;
1273 	if (hwc->flags & PERF_X86_EVENT_LARGE_PEBS)
1274 		cpuc->n_large_pebs++;
1275 	if (hwc->flags & PERF_X86_EVENT_PEBS_VIA_PT)
1276 		cpuc->n_pebs_via_pt++;
1277 
1278 	pebs_update_state(needed_cb, cpuc, event, true);
1279 }
1280 
1281 static void intel_pmu_pebs_via_pt_disable(struct perf_event *event)
1282 {
1283 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1284 
1285 	if (!is_pebs_pt(event))
1286 		return;
1287 
1288 	if (!(cpuc->pebs_enabled & ~PEBS_VIA_PT_MASK))
1289 		cpuc->pebs_enabled &= ~PEBS_VIA_PT_MASK;
1290 }
1291 
1292 static void intel_pmu_pebs_via_pt_enable(struct perf_event *event)
1293 {
1294 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1295 	struct hw_perf_event *hwc = &event->hw;
1296 	struct debug_store *ds = cpuc->ds;
1297 	u64 value = ds->pebs_event_reset[hwc->idx];
1298 	u32 base = MSR_RELOAD_PMC0;
1299 	unsigned int idx = hwc->idx;
1300 
1301 	if (!is_pebs_pt(event))
1302 		return;
1303 
1304 	if (!(event->hw.flags & PERF_X86_EVENT_LARGE_PEBS))
1305 		cpuc->pebs_enabled |= PEBS_PMI_AFTER_EACH_RECORD;
1306 
1307 	cpuc->pebs_enabled |= PEBS_OUTPUT_PT;
1308 
1309 	if (hwc->idx >= INTEL_PMC_IDX_FIXED) {
1310 		base = MSR_RELOAD_FIXED_CTR0;
1311 		idx = hwc->idx - INTEL_PMC_IDX_FIXED;
1312 		if (x86_pmu.intel_cap.pebs_format < 5)
1313 			value = ds->pebs_event_reset[MAX_PEBS_EVENTS_FMT4 + idx];
1314 		else
1315 			value = ds->pebs_event_reset[MAX_PEBS_EVENTS + idx];
1316 	}
1317 	wrmsrl(base + idx, value);
1318 }
1319 
1320 static inline void intel_pmu_drain_large_pebs(struct cpu_hw_events *cpuc)
1321 {
1322 	if (cpuc->n_pebs == cpuc->n_large_pebs &&
1323 	    cpuc->n_pebs != cpuc->n_pebs_via_pt)
1324 		intel_pmu_drain_pebs_buffer();
1325 }
1326 
1327 void intel_pmu_pebs_enable(struct perf_event *event)
1328 {
1329 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1330 	u64 pebs_data_cfg = cpuc->pebs_data_cfg & ~PEBS_UPDATE_DS_SW;
1331 	struct hw_perf_event *hwc = &event->hw;
1332 	struct debug_store *ds = cpuc->ds;
1333 	unsigned int idx = hwc->idx;
1334 
1335 	hwc->config &= ~ARCH_PERFMON_EVENTSEL_INT;
1336 
1337 	cpuc->pebs_enabled |= 1ULL << hwc->idx;
1338 
1339 	if ((event->hw.flags & PERF_X86_EVENT_PEBS_LDLAT) && (x86_pmu.version < 5))
1340 		cpuc->pebs_enabled |= 1ULL << (hwc->idx + 32);
1341 	else if (event->hw.flags & PERF_X86_EVENT_PEBS_ST)
1342 		cpuc->pebs_enabled |= 1ULL << 63;
1343 
1344 	if (x86_pmu.intel_cap.pebs_baseline) {
1345 		hwc->config |= ICL_EVENTSEL_ADAPTIVE;
1346 		if (pebs_data_cfg != cpuc->active_pebs_data_cfg) {
1347 			/*
1348 			 * drain_pebs() assumes uniform record size;
1349 			 * hence we need to drain when changing said
1350 			 * size.
1351 			 */
1352 			intel_pmu_drain_large_pebs(cpuc);
1353 			adaptive_pebs_record_size_update();
1354 			wrmsrl(MSR_PEBS_DATA_CFG, pebs_data_cfg);
1355 			cpuc->active_pebs_data_cfg = pebs_data_cfg;
1356 		}
1357 	}
1358 	if (cpuc->pebs_data_cfg & PEBS_UPDATE_DS_SW) {
1359 		cpuc->pebs_data_cfg = pebs_data_cfg;
1360 		pebs_update_threshold(cpuc);
1361 	}
1362 
1363 	if (idx >= INTEL_PMC_IDX_FIXED) {
1364 		if (x86_pmu.intel_cap.pebs_format < 5)
1365 			idx = MAX_PEBS_EVENTS_FMT4 + (idx - INTEL_PMC_IDX_FIXED);
1366 		else
1367 			idx = MAX_PEBS_EVENTS + (idx - INTEL_PMC_IDX_FIXED);
1368 	}
1369 
1370 	/*
1371 	 * Use auto-reload if possible to save a MSR write in the PMI.
1372 	 * This must be done in pmu::start(), because PERF_EVENT_IOC_PERIOD.
1373 	 */
1374 	if (hwc->flags & PERF_X86_EVENT_AUTO_RELOAD) {
1375 		ds->pebs_event_reset[idx] =
1376 			(u64)(-hwc->sample_period) & x86_pmu.cntval_mask;
1377 	} else {
1378 		ds->pebs_event_reset[idx] = 0;
1379 	}
1380 
1381 	intel_pmu_pebs_via_pt_enable(event);
1382 }
1383 
1384 void intel_pmu_pebs_del(struct perf_event *event)
1385 {
1386 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1387 	struct hw_perf_event *hwc = &event->hw;
1388 	bool needed_cb = pebs_needs_sched_cb(cpuc);
1389 
1390 	cpuc->n_pebs--;
1391 	if (hwc->flags & PERF_X86_EVENT_LARGE_PEBS)
1392 		cpuc->n_large_pebs--;
1393 	if (hwc->flags & PERF_X86_EVENT_PEBS_VIA_PT)
1394 		cpuc->n_pebs_via_pt--;
1395 
1396 	pebs_update_state(needed_cb, cpuc, event, false);
1397 }
1398 
1399 void intel_pmu_pebs_disable(struct perf_event *event)
1400 {
1401 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1402 	struct hw_perf_event *hwc = &event->hw;
1403 
1404 	intel_pmu_drain_large_pebs(cpuc);
1405 
1406 	cpuc->pebs_enabled &= ~(1ULL << hwc->idx);
1407 
1408 	if ((event->hw.flags & PERF_X86_EVENT_PEBS_LDLAT) &&
1409 	    (x86_pmu.version < 5))
1410 		cpuc->pebs_enabled &= ~(1ULL << (hwc->idx + 32));
1411 	else if (event->hw.flags & PERF_X86_EVENT_PEBS_ST)
1412 		cpuc->pebs_enabled &= ~(1ULL << 63);
1413 
1414 	intel_pmu_pebs_via_pt_disable(event);
1415 
1416 	if (cpuc->enabled)
1417 		wrmsrl(MSR_IA32_PEBS_ENABLE, cpuc->pebs_enabled);
1418 
1419 	hwc->config |= ARCH_PERFMON_EVENTSEL_INT;
1420 }
1421 
1422 void intel_pmu_pebs_enable_all(void)
1423 {
1424 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1425 
1426 	if (cpuc->pebs_enabled)
1427 		wrmsrl(MSR_IA32_PEBS_ENABLE, cpuc->pebs_enabled);
1428 }
1429 
1430 void intel_pmu_pebs_disable_all(void)
1431 {
1432 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1433 
1434 	if (cpuc->pebs_enabled)
1435 		__intel_pmu_pebs_disable_all();
1436 }
1437 
1438 static int intel_pmu_pebs_fixup_ip(struct pt_regs *regs)
1439 {
1440 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1441 	unsigned long from = cpuc->lbr_entries[0].from;
1442 	unsigned long old_to, to = cpuc->lbr_entries[0].to;
1443 	unsigned long ip = regs->ip;
1444 	int is_64bit = 0;
1445 	void *kaddr;
1446 	int size;
1447 
1448 	/*
1449 	 * We don't need to fixup if the PEBS assist is fault like
1450 	 */
1451 	if (!x86_pmu.intel_cap.pebs_trap)
1452 		return 1;
1453 
1454 	/*
1455 	 * No LBR entry, no basic block, no rewinding
1456 	 */
1457 	if (!cpuc->lbr_stack.nr || !from || !to)
1458 		return 0;
1459 
1460 	/*
1461 	 * Basic blocks should never cross user/kernel boundaries
1462 	 */
1463 	if (kernel_ip(ip) != kernel_ip(to))
1464 		return 0;
1465 
1466 	/*
1467 	 * unsigned math, either ip is before the start (impossible) or
1468 	 * the basic block is larger than 1 page (sanity)
1469 	 */
1470 	if ((ip - to) > PEBS_FIXUP_SIZE)
1471 		return 0;
1472 
1473 	/*
1474 	 * We sampled a branch insn, rewind using the LBR stack
1475 	 */
1476 	if (ip == to) {
1477 		set_linear_ip(regs, from);
1478 		return 1;
1479 	}
1480 
1481 	size = ip - to;
1482 	if (!kernel_ip(ip)) {
1483 		int bytes;
1484 		u8 *buf = this_cpu_read(insn_buffer);
1485 
1486 		/* 'size' must fit our buffer, see above */
1487 		bytes = copy_from_user_nmi(buf, (void __user *)to, size);
1488 		if (bytes != 0)
1489 			return 0;
1490 
1491 		kaddr = buf;
1492 	} else {
1493 		kaddr = (void *)to;
1494 	}
1495 
1496 	do {
1497 		struct insn insn;
1498 
1499 		old_to = to;
1500 
1501 #ifdef CONFIG_X86_64
1502 		is_64bit = kernel_ip(to) || any_64bit_mode(regs);
1503 #endif
1504 		insn_init(&insn, kaddr, size, is_64bit);
1505 
1506 		/*
1507 		 * Make sure there was not a problem decoding the instruction.
1508 		 * This is doubly important because we have an infinite loop if
1509 		 * insn.length=0.
1510 		 */
1511 		if (insn_get_length(&insn))
1512 			break;
1513 
1514 		to += insn.length;
1515 		kaddr += insn.length;
1516 		size -= insn.length;
1517 	} while (to < ip);
1518 
1519 	if (to == ip) {
1520 		set_linear_ip(regs, old_to);
1521 		return 1;
1522 	}
1523 
1524 	/*
1525 	 * Even though we decoded the basic block, the instruction stream
1526 	 * never matched the given IP, either the TO or the IP got corrupted.
1527 	 */
1528 	return 0;
1529 }
1530 
1531 static inline u64 intel_get_tsx_weight(u64 tsx_tuning)
1532 {
1533 	if (tsx_tuning) {
1534 		union hsw_tsx_tuning tsx = { .value = tsx_tuning };
1535 		return tsx.cycles_last_block;
1536 	}
1537 	return 0;
1538 }
1539 
1540 static inline u64 intel_get_tsx_transaction(u64 tsx_tuning, u64 ax)
1541 {
1542 	u64 txn = (tsx_tuning & PEBS_HSW_TSX_FLAGS) >> 32;
1543 
1544 	/* For RTM XABORTs also log the abort code from AX */
1545 	if ((txn & PERF_TXN_TRANSACTION) && (ax & 1))
1546 		txn |= ((ax >> 24) & 0xff) << PERF_TXN_ABORT_SHIFT;
1547 	return txn;
1548 }
1549 
1550 static inline u64 get_pebs_status(void *n)
1551 {
1552 	if (x86_pmu.intel_cap.pebs_format < 4)
1553 		return ((struct pebs_record_nhm *)n)->status;
1554 	return ((struct pebs_basic *)n)->applicable_counters;
1555 }
1556 
1557 #define PERF_X86_EVENT_PEBS_HSW_PREC \
1558 		(PERF_X86_EVENT_PEBS_ST_HSW | \
1559 		 PERF_X86_EVENT_PEBS_LD_HSW | \
1560 		 PERF_X86_EVENT_PEBS_NA_HSW)
1561 
1562 static u64 get_data_src(struct perf_event *event, u64 aux)
1563 {
1564 	u64 val = PERF_MEM_NA;
1565 	int fl = event->hw.flags;
1566 	bool fst = fl & (PERF_X86_EVENT_PEBS_ST | PERF_X86_EVENT_PEBS_HSW_PREC);
1567 
1568 	if (fl & PERF_X86_EVENT_PEBS_LDLAT)
1569 		val = load_latency_data(event, aux);
1570 	else if (fl & PERF_X86_EVENT_PEBS_STLAT)
1571 		val = store_latency_data(event, aux);
1572 	else if (fl & PERF_X86_EVENT_PEBS_LAT_HYBRID)
1573 		val = x86_pmu.pebs_latency_data(event, aux);
1574 	else if (fst && (fl & PERF_X86_EVENT_PEBS_HSW_PREC))
1575 		val = precise_datala_hsw(event, aux);
1576 	else if (fst)
1577 		val = precise_store_data(aux);
1578 	return val;
1579 }
1580 
1581 static void setup_pebs_time(struct perf_event *event,
1582 			    struct perf_sample_data *data,
1583 			    u64 tsc)
1584 {
1585 	/* Converting to a user-defined clock is not supported yet. */
1586 	if (event->attr.use_clockid != 0)
1587 		return;
1588 
1589 	/*
1590 	 * Doesn't support the conversion when the TSC is unstable.
1591 	 * The TSC unstable case is a corner case and very unlikely to
1592 	 * happen. If it happens, the TSC in a PEBS record will be
1593 	 * dropped and fall back to perf_event_clock().
1594 	 */
1595 	if (!using_native_sched_clock() || !sched_clock_stable())
1596 		return;
1597 
1598 	data->time = native_sched_clock_from_tsc(tsc) + __sched_clock_offset;
1599 	data->sample_flags |= PERF_SAMPLE_TIME;
1600 }
1601 
1602 #define PERF_SAMPLE_ADDR_TYPE	(PERF_SAMPLE_ADDR |		\
1603 				 PERF_SAMPLE_PHYS_ADDR |	\
1604 				 PERF_SAMPLE_DATA_PAGE_SIZE)
1605 
1606 static void setup_pebs_fixed_sample_data(struct perf_event *event,
1607 				   struct pt_regs *iregs, void *__pebs,
1608 				   struct perf_sample_data *data,
1609 				   struct pt_regs *regs)
1610 {
1611 	/*
1612 	 * We cast to the biggest pebs_record but are careful not to
1613 	 * unconditionally access the 'extra' entries.
1614 	 */
1615 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1616 	struct pebs_record_skl *pebs = __pebs;
1617 	u64 sample_type;
1618 	int fll;
1619 
1620 	if (pebs == NULL)
1621 		return;
1622 
1623 	sample_type = event->attr.sample_type;
1624 	fll = event->hw.flags & PERF_X86_EVENT_PEBS_LDLAT;
1625 
1626 	perf_sample_data_init(data, 0, event->hw.last_period);
1627 
1628 	data->period = event->hw.last_period;
1629 
1630 	/*
1631 	 * Use latency for weight (only avail with PEBS-LL)
1632 	 */
1633 	if (fll && (sample_type & PERF_SAMPLE_WEIGHT_TYPE)) {
1634 		data->weight.full = pebs->lat;
1635 		data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
1636 	}
1637 
1638 	/*
1639 	 * data.data_src encodes the data source
1640 	 */
1641 	if (sample_type & PERF_SAMPLE_DATA_SRC) {
1642 		data->data_src.val = get_data_src(event, pebs->dse);
1643 		data->sample_flags |= PERF_SAMPLE_DATA_SRC;
1644 	}
1645 
1646 	/*
1647 	 * We must however always use iregs for the unwinder to stay sane; the
1648 	 * record BP,SP,IP can point into thin air when the record is from a
1649 	 * previous PMI context or an (I)RET happened between the record and
1650 	 * PMI.
1651 	 */
1652 	if (sample_type & PERF_SAMPLE_CALLCHAIN)
1653 		perf_sample_save_callchain(data, event, iregs);
1654 
1655 	/*
1656 	 * We use the interrupt regs as a base because the PEBS record does not
1657 	 * contain a full regs set, specifically it seems to lack segment
1658 	 * descriptors, which get used by things like user_mode().
1659 	 *
1660 	 * In the simple case fix up only the IP for PERF_SAMPLE_IP.
1661 	 */
1662 	*regs = *iregs;
1663 
1664 	/*
1665 	 * Initialize regs_>flags from PEBS,
1666 	 * Clear exact bit (which uses x86 EFLAGS Reserved bit 3),
1667 	 * i.e., do not rely on it being zero:
1668 	 */
1669 	regs->flags = pebs->flags & ~PERF_EFLAGS_EXACT;
1670 
1671 	if (sample_type & PERF_SAMPLE_REGS_INTR) {
1672 		regs->ax = pebs->ax;
1673 		regs->bx = pebs->bx;
1674 		regs->cx = pebs->cx;
1675 		regs->dx = pebs->dx;
1676 		regs->si = pebs->si;
1677 		regs->di = pebs->di;
1678 
1679 		regs->bp = pebs->bp;
1680 		regs->sp = pebs->sp;
1681 
1682 #ifndef CONFIG_X86_32
1683 		regs->r8 = pebs->r8;
1684 		regs->r9 = pebs->r9;
1685 		regs->r10 = pebs->r10;
1686 		regs->r11 = pebs->r11;
1687 		regs->r12 = pebs->r12;
1688 		regs->r13 = pebs->r13;
1689 		regs->r14 = pebs->r14;
1690 		regs->r15 = pebs->r15;
1691 #endif
1692 	}
1693 
1694 	if (event->attr.precise_ip > 1) {
1695 		/*
1696 		 * Haswell and later processors have an 'eventing IP'
1697 		 * (real IP) which fixes the off-by-1 skid in hardware.
1698 		 * Use it when precise_ip >= 2 :
1699 		 */
1700 		if (x86_pmu.intel_cap.pebs_format >= 2) {
1701 			set_linear_ip(regs, pebs->real_ip);
1702 			regs->flags |= PERF_EFLAGS_EXACT;
1703 		} else {
1704 			/* Otherwise, use PEBS off-by-1 IP: */
1705 			set_linear_ip(regs, pebs->ip);
1706 
1707 			/*
1708 			 * With precise_ip >= 2, try to fix up the off-by-1 IP
1709 			 * using the LBR. If successful, the fixup function
1710 			 * corrects regs->ip and calls set_linear_ip() on regs:
1711 			 */
1712 			if (intel_pmu_pebs_fixup_ip(regs))
1713 				regs->flags |= PERF_EFLAGS_EXACT;
1714 		}
1715 	} else {
1716 		/*
1717 		 * When precise_ip == 1, return the PEBS off-by-1 IP,
1718 		 * no fixup attempted:
1719 		 */
1720 		set_linear_ip(regs, pebs->ip);
1721 	}
1722 
1723 
1724 	if ((sample_type & PERF_SAMPLE_ADDR_TYPE) &&
1725 	    x86_pmu.intel_cap.pebs_format >= 1) {
1726 		data->addr = pebs->dla;
1727 		data->sample_flags |= PERF_SAMPLE_ADDR;
1728 	}
1729 
1730 	if (x86_pmu.intel_cap.pebs_format >= 2) {
1731 		/* Only set the TSX weight when no memory weight. */
1732 		if ((sample_type & PERF_SAMPLE_WEIGHT_TYPE) && !fll) {
1733 			data->weight.full = intel_get_tsx_weight(pebs->tsx_tuning);
1734 			data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
1735 		}
1736 		if (sample_type & PERF_SAMPLE_TRANSACTION) {
1737 			data->txn = intel_get_tsx_transaction(pebs->tsx_tuning,
1738 							      pebs->ax);
1739 			data->sample_flags |= PERF_SAMPLE_TRANSACTION;
1740 		}
1741 	}
1742 
1743 	/*
1744 	 * v3 supplies an accurate time stamp, so we use that
1745 	 * for the time stamp.
1746 	 *
1747 	 * We can only do this for the default trace clock.
1748 	 */
1749 	if (x86_pmu.intel_cap.pebs_format >= 3)
1750 		setup_pebs_time(event, data, pebs->tsc);
1751 
1752 	if (has_branch_stack(event))
1753 		perf_sample_save_brstack(data, event, &cpuc->lbr_stack);
1754 }
1755 
1756 static void adaptive_pebs_save_regs(struct pt_regs *regs,
1757 				    struct pebs_gprs *gprs)
1758 {
1759 	regs->ax = gprs->ax;
1760 	regs->bx = gprs->bx;
1761 	regs->cx = gprs->cx;
1762 	regs->dx = gprs->dx;
1763 	regs->si = gprs->si;
1764 	regs->di = gprs->di;
1765 	regs->bp = gprs->bp;
1766 	regs->sp = gprs->sp;
1767 #ifndef CONFIG_X86_32
1768 	regs->r8 = gprs->r8;
1769 	regs->r9 = gprs->r9;
1770 	regs->r10 = gprs->r10;
1771 	regs->r11 = gprs->r11;
1772 	regs->r12 = gprs->r12;
1773 	regs->r13 = gprs->r13;
1774 	regs->r14 = gprs->r14;
1775 	regs->r15 = gprs->r15;
1776 #endif
1777 }
1778 
1779 #define PEBS_LATENCY_MASK			0xffff
1780 #define PEBS_CACHE_LATENCY_OFFSET		32
1781 #define PEBS_RETIRE_LATENCY_OFFSET		32
1782 
1783 /*
1784  * With adaptive PEBS the layout depends on what fields are configured.
1785  */
1786 
1787 static void setup_pebs_adaptive_sample_data(struct perf_event *event,
1788 					    struct pt_regs *iregs, void *__pebs,
1789 					    struct perf_sample_data *data,
1790 					    struct pt_regs *regs)
1791 {
1792 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1793 	struct pebs_basic *basic = __pebs;
1794 	void *next_record = basic + 1;
1795 	u64 sample_type;
1796 	u64 format_size;
1797 	struct pebs_meminfo *meminfo = NULL;
1798 	struct pebs_gprs *gprs = NULL;
1799 	struct x86_perf_regs *perf_regs;
1800 
1801 	if (basic == NULL)
1802 		return;
1803 
1804 	perf_regs = container_of(regs, struct x86_perf_regs, regs);
1805 	perf_regs->xmm_regs = NULL;
1806 
1807 	sample_type = event->attr.sample_type;
1808 	format_size = basic->format_size;
1809 	perf_sample_data_init(data, 0, event->hw.last_period);
1810 	data->period = event->hw.last_period;
1811 
1812 	setup_pebs_time(event, data, basic->tsc);
1813 
1814 	/*
1815 	 * We must however always use iregs for the unwinder to stay sane; the
1816 	 * record BP,SP,IP can point into thin air when the record is from a
1817 	 * previous PMI context or an (I)RET happened between the record and
1818 	 * PMI.
1819 	 */
1820 	if (sample_type & PERF_SAMPLE_CALLCHAIN)
1821 		perf_sample_save_callchain(data, event, iregs);
1822 
1823 	*regs = *iregs;
1824 	/* The ip in basic is EventingIP */
1825 	set_linear_ip(regs, basic->ip);
1826 	regs->flags = PERF_EFLAGS_EXACT;
1827 
1828 	if ((sample_type & PERF_SAMPLE_WEIGHT_STRUCT) && (x86_pmu.flags & PMU_FL_RETIRE_LATENCY))
1829 		data->weight.var3_w = format_size >> PEBS_RETIRE_LATENCY_OFFSET & PEBS_LATENCY_MASK;
1830 
1831 	/*
1832 	 * The record for MEMINFO is in front of GP
1833 	 * But PERF_SAMPLE_TRANSACTION needs gprs->ax.
1834 	 * Save the pointer here but process later.
1835 	 */
1836 	if (format_size & PEBS_DATACFG_MEMINFO) {
1837 		meminfo = next_record;
1838 		next_record = meminfo + 1;
1839 	}
1840 
1841 	if (format_size & PEBS_DATACFG_GP) {
1842 		gprs = next_record;
1843 		next_record = gprs + 1;
1844 
1845 		if (event->attr.precise_ip < 2) {
1846 			set_linear_ip(regs, gprs->ip);
1847 			regs->flags &= ~PERF_EFLAGS_EXACT;
1848 		}
1849 
1850 		if (sample_type & PERF_SAMPLE_REGS_INTR)
1851 			adaptive_pebs_save_regs(regs, gprs);
1852 	}
1853 
1854 	if (format_size & PEBS_DATACFG_MEMINFO) {
1855 		if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
1856 			u64 weight = meminfo->latency;
1857 
1858 			if (x86_pmu.flags & PMU_FL_INSTR_LATENCY) {
1859 				data->weight.var2_w = weight & PEBS_LATENCY_MASK;
1860 				weight >>= PEBS_CACHE_LATENCY_OFFSET;
1861 			}
1862 
1863 			/*
1864 			 * Although meminfo::latency is defined as a u64,
1865 			 * only the lower 32 bits include the valid data
1866 			 * in practice on Ice Lake and earlier platforms.
1867 			 */
1868 			if (sample_type & PERF_SAMPLE_WEIGHT) {
1869 				data->weight.full = weight ?:
1870 					intel_get_tsx_weight(meminfo->tsx_tuning);
1871 			} else {
1872 				data->weight.var1_dw = (u32)(weight & PEBS_LATENCY_MASK) ?:
1873 					intel_get_tsx_weight(meminfo->tsx_tuning);
1874 			}
1875 			data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
1876 		}
1877 
1878 		if (sample_type & PERF_SAMPLE_DATA_SRC) {
1879 			data->data_src.val = get_data_src(event, meminfo->aux);
1880 			data->sample_flags |= PERF_SAMPLE_DATA_SRC;
1881 		}
1882 
1883 		if (sample_type & PERF_SAMPLE_ADDR_TYPE) {
1884 			data->addr = meminfo->address;
1885 			data->sample_flags |= PERF_SAMPLE_ADDR;
1886 		}
1887 
1888 		if (sample_type & PERF_SAMPLE_TRANSACTION) {
1889 			data->txn = intel_get_tsx_transaction(meminfo->tsx_tuning,
1890 							  gprs ? gprs->ax : 0);
1891 			data->sample_flags |= PERF_SAMPLE_TRANSACTION;
1892 		}
1893 	}
1894 
1895 	if (format_size & PEBS_DATACFG_XMMS) {
1896 		struct pebs_xmm *xmm = next_record;
1897 
1898 		next_record = xmm + 1;
1899 		perf_regs->xmm_regs = xmm->xmm;
1900 	}
1901 
1902 	if (format_size & PEBS_DATACFG_LBRS) {
1903 		struct lbr_entry *lbr = next_record;
1904 		int num_lbr = ((format_size >> PEBS_DATACFG_LBR_SHIFT)
1905 					& 0xff) + 1;
1906 		next_record = next_record + num_lbr * sizeof(struct lbr_entry);
1907 
1908 		if (has_branch_stack(event)) {
1909 			intel_pmu_store_pebs_lbrs(lbr);
1910 			perf_sample_save_brstack(data, event, &cpuc->lbr_stack);
1911 		}
1912 	}
1913 
1914 	WARN_ONCE(next_record != __pebs + (format_size >> 48),
1915 			"PEBS record size %llu, expected %llu, config %llx\n",
1916 			format_size >> 48,
1917 			(u64)(next_record - __pebs),
1918 			basic->format_size);
1919 }
1920 
1921 static inline void *
1922 get_next_pebs_record_by_bit(void *base, void *top, int bit)
1923 {
1924 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1925 	void *at;
1926 	u64 pebs_status;
1927 
1928 	/*
1929 	 * fmt0 does not have a status bitfield (does not use
1930 	 * perf_record_nhm format)
1931 	 */
1932 	if (x86_pmu.intel_cap.pebs_format < 1)
1933 		return base;
1934 
1935 	if (base == NULL)
1936 		return NULL;
1937 
1938 	for (at = base; at < top; at += cpuc->pebs_record_size) {
1939 		unsigned long status = get_pebs_status(at);
1940 
1941 		if (test_bit(bit, (unsigned long *)&status)) {
1942 			/* PEBS v3 has accurate status bits */
1943 			if (x86_pmu.intel_cap.pebs_format >= 3)
1944 				return at;
1945 
1946 			if (status == (1 << bit))
1947 				return at;
1948 
1949 			/* clear non-PEBS bit and re-check */
1950 			pebs_status = status & cpuc->pebs_enabled;
1951 			pebs_status &= PEBS_COUNTER_MASK;
1952 			if (pebs_status == (1 << bit))
1953 				return at;
1954 		}
1955 	}
1956 	return NULL;
1957 }
1958 
1959 void intel_pmu_auto_reload_read(struct perf_event *event)
1960 {
1961 	WARN_ON(!(event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD));
1962 
1963 	perf_pmu_disable(event->pmu);
1964 	intel_pmu_drain_pebs_buffer();
1965 	perf_pmu_enable(event->pmu);
1966 }
1967 
1968 /*
1969  * Special variant of intel_pmu_save_and_restart() for auto-reload.
1970  */
1971 static int
1972 intel_pmu_save_and_restart_reload(struct perf_event *event, int count)
1973 {
1974 	struct hw_perf_event *hwc = &event->hw;
1975 	int shift = 64 - x86_pmu.cntval_bits;
1976 	u64 period = hwc->sample_period;
1977 	u64 prev_raw_count, new_raw_count;
1978 	s64 new, old;
1979 
1980 	WARN_ON(!period);
1981 
1982 	/*
1983 	 * drain_pebs() only happens when the PMU is disabled.
1984 	 */
1985 	WARN_ON(this_cpu_read(cpu_hw_events.enabled));
1986 
1987 	prev_raw_count = local64_read(&hwc->prev_count);
1988 	rdpmcl(hwc->event_base_rdpmc, new_raw_count);
1989 	local64_set(&hwc->prev_count, new_raw_count);
1990 
1991 	/*
1992 	 * Since the counter increments a negative counter value and
1993 	 * overflows on the sign switch, giving the interval:
1994 	 *
1995 	 *   [-period, 0]
1996 	 *
1997 	 * the difference between two consecutive reads is:
1998 	 *
1999 	 *   A) value2 - value1;
2000 	 *      when no overflows have happened in between,
2001 	 *
2002 	 *   B) (0 - value1) + (value2 - (-period));
2003 	 *      when one overflow happened in between,
2004 	 *
2005 	 *   C) (0 - value1) + (n - 1) * (period) + (value2 - (-period));
2006 	 *      when @n overflows happened in between.
2007 	 *
2008 	 * Here A) is the obvious difference, B) is the extension to the
2009 	 * discrete interval, where the first term is to the top of the
2010 	 * interval and the second term is from the bottom of the next
2011 	 * interval and C) the extension to multiple intervals, where the
2012 	 * middle term is the whole intervals covered.
2013 	 *
2014 	 * An equivalent of C, by reduction, is:
2015 	 *
2016 	 *   value2 - value1 + n * period
2017 	 */
2018 	new = ((s64)(new_raw_count << shift) >> shift);
2019 	old = ((s64)(prev_raw_count << shift) >> shift);
2020 	local64_add(new - old + count * period, &event->count);
2021 
2022 	local64_set(&hwc->period_left, -new);
2023 
2024 	perf_event_update_userpage(event);
2025 
2026 	return 0;
2027 }
2028 
2029 static __always_inline void
2030 __intel_pmu_pebs_event(struct perf_event *event,
2031 		       struct pt_regs *iregs,
2032 		       struct perf_sample_data *data,
2033 		       void *base, void *top,
2034 		       int bit, int count,
2035 		       void (*setup_sample)(struct perf_event *,
2036 					    struct pt_regs *,
2037 					    void *,
2038 					    struct perf_sample_data *,
2039 					    struct pt_regs *))
2040 {
2041 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2042 	struct hw_perf_event *hwc = &event->hw;
2043 	struct x86_perf_regs perf_regs;
2044 	struct pt_regs *regs = &perf_regs.regs;
2045 	void *at = get_next_pebs_record_by_bit(base, top, bit);
2046 	static struct pt_regs dummy_iregs;
2047 
2048 	if (hwc->flags & PERF_X86_EVENT_AUTO_RELOAD) {
2049 		/*
2050 		 * Now, auto-reload is only enabled in fixed period mode.
2051 		 * The reload value is always hwc->sample_period.
2052 		 * May need to change it, if auto-reload is enabled in
2053 		 * freq mode later.
2054 		 */
2055 		intel_pmu_save_and_restart_reload(event, count);
2056 	} else if (!intel_pmu_save_and_restart(event))
2057 		return;
2058 
2059 	if (!iregs)
2060 		iregs = &dummy_iregs;
2061 
2062 	while (count > 1) {
2063 		setup_sample(event, iregs, at, data, regs);
2064 		perf_event_output(event, data, regs);
2065 		at += cpuc->pebs_record_size;
2066 		at = get_next_pebs_record_by_bit(at, top, bit);
2067 		count--;
2068 	}
2069 
2070 	setup_sample(event, iregs, at, data, regs);
2071 	if (iregs == &dummy_iregs) {
2072 		/*
2073 		 * The PEBS records may be drained in the non-overflow context,
2074 		 * e.g., large PEBS + context switch. Perf should treat the
2075 		 * last record the same as other PEBS records, and doesn't
2076 		 * invoke the generic overflow handler.
2077 		 */
2078 		perf_event_output(event, data, regs);
2079 	} else {
2080 		/*
2081 		 * All but the last records are processed.
2082 		 * The last one is left to be able to call the overflow handler.
2083 		 */
2084 		if (perf_event_overflow(event, data, regs))
2085 			x86_pmu_stop(event, 0);
2086 	}
2087 }
2088 
2089 static void intel_pmu_drain_pebs_core(struct pt_regs *iregs, struct perf_sample_data *data)
2090 {
2091 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2092 	struct debug_store *ds = cpuc->ds;
2093 	struct perf_event *event = cpuc->events[0]; /* PMC0 only */
2094 	struct pebs_record_core *at, *top;
2095 	int n;
2096 
2097 	if (!x86_pmu.pebs_active)
2098 		return;
2099 
2100 	at  = (struct pebs_record_core *)(unsigned long)ds->pebs_buffer_base;
2101 	top = (struct pebs_record_core *)(unsigned long)ds->pebs_index;
2102 
2103 	/*
2104 	 * Whatever else happens, drain the thing
2105 	 */
2106 	ds->pebs_index = ds->pebs_buffer_base;
2107 
2108 	if (!test_bit(0, cpuc->active_mask))
2109 		return;
2110 
2111 	WARN_ON_ONCE(!event);
2112 
2113 	if (!event->attr.precise_ip)
2114 		return;
2115 
2116 	n = top - at;
2117 	if (n <= 0) {
2118 		if (event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD)
2119 			intel_pmu_save_and_restart_reload(event, 0);
2120 		return;
2121 	}
2122 
2123 	__intel_pmu_pebs_event(event, iregs, data, at, top, 0, n,
2124 			       setup_pebs_fixed_sample_data);
2125 }
2126 
2127 static void intel_pmu_pebs_event_update_no_drain(struct cpu_hw_events *cpuc, int size)
2128 {
2129 	struct perf_event *event;
2130 	int bit;
2131 
2132 	/*
2133 	 * The drain_pebs() could be called twice in a short period
2134 	 * for auto-reload event in pmu::read(). There are no
2135 	 * overflows have happened in between.
2136 	 * It needs to call intel_pmu_save_and_restart_reload() to
2137 	 * update the event->count for this case.
2138 	 */
2139 	for_each_set_bit(bit, (unsigned long *)&cpuc->pebs_enabled, size) {
2140 		event = cpuc->events[bit];
2141 		if (event->hw.flags & PERF_X86_EVENT_AUTO_RELOAD)
2142 			intel_pmu_save_and_restart_reload(event, 0);
2143 	}
2144 }
2145 
2146 static void intel_pmu_drain_pebs_nhm(struct pt_regs *iregs, struct perf_sample_data *data)
2147 {
2148 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2149 	struct debug_store *ds = cpuc->ds;
2150 	struct perf_event *event;
2151 	void *base, *at, *top;
2152 	short counts[INTEL_PMC_IDX_FIXED + MAX_FIXED_PEBS_EVENTS] = {};
2153 	short error[INTEL_PMC_IDX_FIXED + MAX_FIXED_PEBS_EVENTS] = {};
2154 	int bit, i, size;
2155 	u64 mask;
2156 
2157 	if (!x86_pmu.pebs_active)
2158 		return;
2159 
2160 	base = (struct pebs_record_nhm *)(unsigned long)ds->pebs_buffer_base;
2161 	top = (struct pebs_record_nhm *)(unsigned long)ds->pebs_index;
2162 
2163 	ds->pebs_index = ds->pebs_buffer_base;
2164 
2165 	mask = (1ULL << x86_pmu.max_pebs_events) - 1;
2166 	size = x86_pmu.max_pebs_events;
2167 	if (x86_pmu.flags & PMU_FL_PEBS_ALL) {
2168 		mask |= ((1ULL << x86_pmu.num_counters_fixed) - 1) << INTEL_PMC_IDX_FIXED;
2169 		size = INTEL_PMC_IDX_FIXED + x86_pmu.num_counters_fixed;
2170 	}
2171 
2172 	if (unlikely(base >= top)) {
2173 		intel_pmu_pebs_event_update_no_drain(cpuc, size);
2174 		return;
2175 	}
2176 
2177 	for (at = base; at < top; at += x86_pmu.pebs_record_size) {
2178 		struct pebs_record_nhm *p = at;
2179 		u64 pebs_status;
2180 
2181 		pebs_status = p->status & cpuc->pebs_enabled;
2182 		pebs_status &= mask;
2183 
2184 		/* PEBS v3 has more accurate status bits */
2185 		if (x86_pmu.intel_cap.pebs_format >= 3) {
2186 			for_each_set_bit(bit, (unsigned long *)&pebs_status, size)
2187 				counts[bit]++;
2188 
2189 			continue;
2190 		}
2191 
2192 		/*
2193 		 * On some CPUs the PEBS status can be zero when PEBS is
2194 		 * racing with clearing of GLOBAL_STATUS.
2195 		 *
2196 		 * Normally we would drop that record, but in the
2197 		 * case when there is only a single active PEBS event
2198 		 * we can assume it's for that event.
2199 		 */
2200 		if (!pebs_status && cpuc->pebs_enabled &&
2201 			!(cpuc->pebs_enabled & (cpuc->pebs_enabled-1)))
2202 			pebs_status = p->status = cpuc->pebs_enabled;
2203 
2204 		bit = find_first_bit((unsigned long *)&pebs_status,
2205 					x86_pmu.max_pebs_events);
2206 		if (bit >= x86_pmu.max_pebs_events)
2207 			continue;
2208 
2209 		/*
2210 		 * The PEBS hardware does not deal well with the situation
2211 		 * when events happen near to each other and multiple bits
2212 		 * are set. But it should happen rarely.
2213 		 *
2214 		 * If these events include one PEBS and multiple non-PEBS
2215 		 * events, it doesn't impact PEBS record. The record will
2216 		 * be handled normally. (slow path)
2217 		 *
2218 		 * If these events include two or more PEBS events, the
2219 		 * records for the events can be collapsed into a single
2220 		 * one, and it's not possible to reconstruct all events
2221 		 * that caused the PEBS record. It's called collision.
2222 		 * If collision happened, the record will be dropped.
2223 		 */
2224 		if (pebs_status != (1ULL << bit)) {
2225 			for_each_set_bit(i, (unsigned long *)&pebs_status, size)
2226 				error[i]++;
2227 			continue;
2228 		}
2229 
2230 		counts[bit]++;
2231 	}
2232 
2233 	for_each_set_bit(bit, (unsigned long *)&mask, size) {
2234 		if ((counts[bit] == 0) && (error[bit] == 0))
2235 			continue;
2236 
2237 		event = cpuc->events[bit];
2238 		if (WARN_ON_ONCE(!event))
2239 			continue;
2240 
2241 		if (WARN_ON_ONCE(!event->attr.precise_ip))
2242 			continue;
2243 
2244 		/* log dropped samples number */
2245 		if (error[bit]) {
2246 			perf_log_lost_samples(event, error[bit]);
2247 
2248 			if (iregs && perf_event_account_interrupt(event))
2249 				x86_pmu_stop(event, 0);
2250 		}
2251 
2252 		if (counts[bit]) {
2253 			__intel_pmu_pebs_event(event, iregs, data, base,
2254 					       top, bit, counts[bit],
2255 					       setup_pebs_fixed_sample_data);
2256 		}
2257 	}
2258 }
2259 
2260 static void intel_pmu_drain_pebs_icl(struct pt_regs *iregs, struct perf_sample_data *data)
2261 {
2262 	short counts[INTEL_PMC_IDX_FIXED + MAX_FIXED_PEBS_EVENTS] = {};
2263 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2264 	int max_pebs_events = hybrid(cpuc->pmu, max_pebs_events);
2265 	int num_counters_fixed = hybrid(cpuc->pmu, num_counters_fixed);
2266 	struct debug_store *ds = cpuc->ds;
2267 	struct perf_event *event;
2268 	void *base, *at, *top;
2269 	int bit, size;
2270 	u64 mask;
2271 
2272 	if (!x86_pmu.pebs_active)
2273 		return;
2274 
2275 	base = (struct pebs_basic *)(unsigned long)ds->pebs_buffer_base;
2276 	top = (struct pebs_basic *)(unsigned long)ds->pebs_index;
2277 
2278 	ds->pebs_index = ds->pebs_buffer_base;
2279 
2280 	mask = ((1ULL << max_pebs_events) - 1) |
2281 	       (((1ULL << num_counters_fixed) - 1) << INTEL_PMC_IDX_FIXED);
2282 	size = INTEL_PMC_IDX_FIXED + num_counters_fixed;
2283 
2284 	if (unlikely(base >= top)) {
2285 		intel_pmu_pebs_event_update_no_drain(cpuc, size);
2286 		return;
2287 	}
2288 
2289 	for (at = base; at < top; at += cpuc->pebs_record_size) {
2290 		u64 pebs_status;
2291 
2292 		pebs_status = get_pebs_status(at) & cpuc->pebs_enabled;
2293 		pebs_status &= mask;
2294 
2295 		for_each_set_bit(bit, (unsigned long *)&pebs_status, size)
2296 			counts[bit]++;
2297 	}
2298 
2299 	for_each_set_bit(bit, (unsigned long *)&mask, size) {
2300 		if (counts[bit] == 0)
2301 			continue;
2302 
2303 		event = cpuc->events[bit];
2304 		if (WARN_ON_ONCE(!event))
2305 			continue;
2306 
2307 		if (WARN_ON_ONCE(!event->attr.precise_ip))
2308 			continue;
2309 
2310 		__intel_pmu_pebs_event(event, iregs, data, base,
2311 				       top, bit, counts[bit],
2312 				       setup_pebs_adaptive_sample_data);
2313 	}
2314 }
2315 
2316 /*
2317  * BTS, PEBS probe and setup
2318  */
2319 
2320 void __init intel_ds_init(void)
2321 {
2322 	/*
2323 	 * No support for 32bit formats
2324 	 */
2325 	if (!boot_cpu_has(X86_FEATURE_DTES64))
2326 		return;
2327 
2328 	x86_pmu.bts  = boot_cpu_has(X86_FEATURE_BTS);
2329 	x86_pmu.pebs = boot_cpu_has(X86_FEATURE_PEBS);
2330 	x86_pmu.pebs_buffer_size = PEBS_BUFFER_SIZE;
2331 	if (x86_pmu.version <= 4)
2332 		x86_pmu.pebs_no_isolation = 1;
2333 
2334 	if (x86_pmu.pebs) {
2335 		char pebs_type = x86_pmu.intel_cap.pebs_trap ?  '+' : '-';
2336 		char *pebs_qual = "";
2337 		int format = x86_pmu.intel_cap.pebs_format;
2338 
2339 		if (format < 4)
2340 			x86_pmu.intel_cap.pebs_baseline = 0;
2341 
2342 		switch (format) {
2343 		case 0:
2344 			pr_cont("PEBS fmt0%c, ", pebs_type);
2345 			x86_pmu.pebs_record_size = sizeof(struct pebs_record_core);
2346 			/*
2347 			 * Using >PAGE_SIZE buffers makes the WRMSR to
2348 			 * PERF_GLOBAL_CTRL in intel_pmu_enable_all()
2349 			 * mysteriously hang on Core2.
2350 			 *
2351 			 * As a workaround, we don't do this.
2352 			 */
2353 			x86_pmu.pebs_buffer_size = PAGE_SIZE;
2354 			x86_pmu.drain_pebs = intel_pmu_drain_pebs_core;
2355 			break;
2356 
2357 		case 1:
2358 			pr_cont("PEBS fmt1%c, ", pebs_type);
2359 			x86_pmu.pebs_record_size = sizeof(struct pebs_record_nhm);
2360 			x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm;
2361 			break;
2362 
2363 		case 2:
2364 			pr_cont("PEBS fmt2%c, ", pebs_type);
2365 			x86_pmu.pebs_record_size = sizeof(struct pebs_record_hsw);
2366 			x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm;
2367 			break;
2368 
2369 		case 3:
2370 			pr_cont("PEBS fmt3%c, ", pebs_type);
2371 			x86_pmu.pebs_record_size =
2372 						sizeof(struct pebs_record_skl);
2373 			x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm;
2374 			x86_pmu.large_pebs_flags |= PERF_SAMPLE_TIME;
2375 			break;
2376 
2377 		case 5:
2378 			x86_pmu.pebs_ept = 1;
2379 			fallthrough;
2380 		case 4:
2381 			x86_pmu.drain_pebs = intel_pmu_drain_pebs_icl;
2382 			x86_pmu.pebs_record_size = sizeof(struct pebs_basic);
2383 			if (x86_pmu.intel_cap.pebs_baseline) {
2384 				x86_pmu.large_pebs_flags |=
2385 					PERF_SAMPLE_BRANCH_STACK |
2386 					PERF_SAMPLE_TIME;
2387 				x86_pmu.flags |= PMU_FL_PEBS_ALL;
2388 				x86_pmu.pebs_capable = ~0ULL;
2389 				pebs_qual = "-baseline";
2390 				x86_get_pmu(smp_processor_id())->capabilities |= PERF_PMU_CAP_EXTENDED_REGS;
2391 			} else {
2392 				/* Only basic record supported */
2393 				x86_pmu.large_pebs_flags &=
2394 					~(PERF_SAMPLE_ADDR |
2395 					  PERF_SAMPLE_TIME |
2396 					  PERF_SAMPLE_DATA_SRC |
2397 					  PERF_SAMPLE_TRANSACTION |
2398 					  PERF_SAMPLE_REGS_USER |
2399 					  PERF_SAMPLE_REGS_INTR);
2400 			}
2401 			pr_cont("PEBS fmt4%c%s, ", pebs_type, pebs_qual);
2402 
2403 			if (!is_hybrid() && x86_pmu.intel_cap.pebs_output_pt_available) {
2404 				pr_cont("PEBS-via-PT, ");
2405 				x86_get_pmu(smp_processor_id())->capabilities |= PERF_PMU_CAP_AUX_OUTPUT;
2406 			}
2407 
2408 			break;
2409 
2410 		default:
2411 			pr_cont("no PEBS fmt%d%c, ", format, pebs_type);
2412 			x86_pmu.pebs = 0;
2413 		}
2414 	}
2415 }
2416 
2417 void perf_restore_debug_store(void)
2418 {
2419 	struct debug_store *ds = __this_cpu_read(cpu_hw_events.ds);
2420 
2421 	if (!x86_pmu.bts && !x86_pmu.pebs)
2422 		return;
2423 
2424 	wrmsrl(MSR_IA32_DS_AREA, (unsigned long)ds);
2425 }
2426