xref: /openbmc/linux/arch/x86/events/amd/core.c (revision 706460a9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/perf_event.h>
3 #include <linux/jump_label.h>
4 #include <linux/export.h>
5 #include <linux/types.h>
6 #include <linux/init.h>
7 #include <linux/slab.h>
8 #include <linux/delay.h>
9 #include <linux/jiffies.h>
10 #include <asm/apicdef.h>
11 #include <asm/apic.h>
12 #include <asm/nmi.h>
13 
14 #include "../perf_event.h"
15 
16 static DEFINE_PER_CPU(unsigned long, perf_nmi_tstamp);
17 static unsigned long perf_nmi_window;
18 
19 /* AMD Event 0xFFF: Merge.  Used with Large Increment per Cycle events */
20 #define AMD_MERGE_EVENT ((0xFULL << 32) | 0xFFULL)
21 #define AMD_MERGE_EVENT_ENABLE (AMD_MERGE_EVENT | ARCH_PERFMON_EVENTSEL_ENABLE)
22 
23 /* PMC Enable and Overflow bits for PerfCntrGlobal* registers */
24 static u64 amd_pmu_global_cntr_mask __read_mostly;
25 
26 static __initconst const u64 amd_hw_cache_event_ids
27 				[PERF_COUNT_HW_CACHE_MAX]
28 				[PERF_COUNT_HW_CACHE_OP_MAX]
29 				[PERF_COUNT_HW_CACHE_RESULT_MAX] =
30 {
31  [ C(L1D) ] = {
32 	[ C(OP_READ) ] = {
33 		[ C(RESULT_ACCESS) ] = 0x0040, /* Data Cache Accesses        */
34 		[ C(RESULT_MISS)   ] = 0x0141, /* Data Cache Misses          */
35 	},
36 	[ C(OP_WRITE) ] = {
37 		[ C(RESULT_ACCESS) ] = 0,
38 		[ C(RESULT_MISS)   ] = 0,
39 	},
40 	[ C(OP_PREFETCH) ] = {
41 		[ C(RESULT_ACCESS) ] = 0x0267, /* Data Prefetcher :attempts  */
42 		[ C(RESULT_MISS)   ] = 0x0167, /* Data Prefetcher :cancelled */
43 	},
44  },
45  [ C(L1I ) ] = {
46 	[ C(OP_READ) ] = {
47 		[ C(RESULT_ACCESS) ] = 0x0080, /* Instruction cache fetches  */
48 		[ C(RESULT_MISS)   ] = 0x0081, /* Instruction cache misses   */
49 	},
50 	[ C(OP_WRITE) ] = {
51 		[ C(RESULT_ACCESS) ] = -1,
52 		[ C(RESULT_MISS)   ] = -1,
53 	},
54 	[ C(OP_PREFETCH) ] = {
55 		[ C(RESULT_ACCESS) ] = 0x014B, /* Prefetch Instructions :Load */
56 		[ C(RESULT_MISS)   ] = 0,
57 	},
58  },
59  [ C(LL  ) ] = {
60 	[ C(OP_READ) ] = {
61 		[ C(RESULT_ACCESS) ] = 0x037D, /* Requests to L2 Cache :IC+DC */
62 		[ C(RESULT_MISS)   ] = 0x037E, /* L2 Cache Misses : IC+DC     */
63 	},
64 	[ C(OP_WRITE) ] = {
65 		[ C(RESULT_ACCESS) ] = 0x017F, /* L2 Fill/Writeback           */
66 		[ C(RESULT_MISS)   ] = 0,
67 	},
68 	[ C(OP_PREFETCH) ] = {
69 		[ C(RESULT_ACCESS) ] = 0,
70 		[ C(RESULT_MISS)   ] = 0,
71 	},
72  },
73  [ C(DTLB) ] = {
74 	[ C(OP_READ) ] = {
75 		[ C(RESULT_ACCESS) ] = 0x0040, /* Data Cache Accesses        */
76 		[ C(RESULT_MISS)   ] = 0x0746, /* L1_DTLB_AND_L2_DLTB_MISS.ALL */
77 	},
78 	[ C(OP_WRITE) ] = {
79 		[ C(RESULT_ACCESS) ] = 0,
80 		[ C(RESULT_MISS)   ] = 0,
81 	},
82 	[ C(OP_PREFETCH) ] = {
83 		[ C(RESULT_ACCESS) ] = 0,
84 		[ C(RESULT_MISS)   ] = 0,
85 	},
86  },
87  [ C(ITLB) ] = {
88 	[ C(OP_READ) ] = {
89 		[ C(RESULT_ACCESS) ] = 0x0080, /* Instruction fecthes        */
90 		[ C(RESULT_MISS)   ] = 0x0385, /* L1_ITLB_AND_L2_ITLB_MISS.ALL */
91 	},
92 	[ C(OP_WRITE) ] = {
93 		[ C(RESULT_ACCESS) ] = -1,
94 		[ C(RESULT_MISS)   ] = -1,
95 	},
96 	[ C(OP_PREFETCH) ] = {
97 		[ C(RESULT_ACCESS) ] = -1,
98 		[ C(RESULT_MISS)   ] = -1,
99 	},
100  },
101  [ C(BPU ) ] = {
102 	[ C(OP_READ) ] = {
103 		[ C(RESULT_ACCESS) ] = 0x00c2, /* Retired Branch Instr.      */
104 		[ C(RESULT_MISS)   ] = 0x00c3, /* Retired Mispredicted BI    */
105 	},
106 	[ C(OP_WRITE) ] = {
107 		[ C(RESULT_ACCESS) ] = -1,
108 		[ C(RESULT_MISS)   ] = -1,
109 	},
110 	[ C(OP_PREFETCH) ] = {
111 		[ C(RESULT_ACCESS) ] = -1,
112 		[ C(RESULT_MISS)   ] = -1,
113 	},
114  },
115  [ C(NODE) ] = {
116 	[ C(OP_READ) ] = {
117 		[ C(RESULT_ACCESS) ] = 0xb8e9, /* CPU Request to Memory, l+r */
118 		[ C(RESULT_MISS)   ] = 0x98e9, /* CPU Request to Memory, r   */
119 	},
120 	[ C(OP_WRITE) ] = {
121 		[ C(RESULT_ACCESS) ] = -1,
122 		[ C(RESULT_MISS)   ] = -1,
123 	},
124 	[ C(OP_PREFETCH) ] = {
125 		[ C(RESULT_ACCESS) ] = -1,
126 		[ C(RESULT_MISS)   ] = -1,
127 	},
128  },
129 };
130 
131 static __initconst const u64 amd_hw_cache_event_ids_f17h
132 				[PERF_COUNT_HW_CACHE_MAX]
133 				[PERF_COUNT_HW_CACHE_OP_MAX]
134 				[PERF_COUNT_HW_CACHE_RESULT_MAX] = {
135 [C(L1D)] = {
136 	[C(OP_READ)] = {
137 		[C(RESULT_ACCESS)] = 0x0040, /* Data Cache Accesses */
138 		[C(RESULT_MISS)]   = 0xc860, /* L2$ access from DC Miss */
139 	},
140 	[C(OP_WRITE)] = {
141 		[C(RESULT_ACCESS)] = 0,
142 		[C(RESULT_MISS)]   = 0,
143 	},
144 	[C(OP_PREFETCH)] = {
145 		[C(RESULT_ACCESS)] = 0xff5a, /* h/w prefetch DC Fills */
146 		[C(RESULT_MISS)]   = 0,
147 	},
148 },
149 [C(L1I)] = {
150 	[C(OP_READ)] = {
151 		[C(RESULT_ACCESS)] = 0x0080, /* Instruction cache fetches  */
152 		[C(RESULT_MISS)]   = 0x0081, /* Instruction cache misses   */
153 	},
154 	[C(OP_WRITE)] = {
155 		[C(RESULT_ACCESS)] = -1,
156 		[C(RESULT_MISS)]   = -1,
157 	},
158 	[C(OP_PREFETCH)] = {
159 		[C(RESULT_ACCESS)] = 0,
160 		[C(RESULT_MISS)]   = 0,
161 	},
162 },
163 [C(LL)] = {
164 	[C(OP_READ)] = {
165 		[C(RESULT_ACCESS)] = 0,
166 		[C(RESULT_MISS)]   = 0,
167 	},
168 	[C(OP_WRITE)] = {
169 		[C(RESULT_ACCESS)] = 0,
170 		[C(RESULT_MISS)]   = 0,
171 	},
172 	[C(OP_PREFETCH)] = {
173 		[C(RESULT_ACCESS)] = 0,
174 		[C(RESULT_MISS)]   = 0,
175 	},
176 },
177 [C(DTLB)] = {
178 	[C(OP_READ)] = {
179 		[C(RESULT_ACCESS)] = 0xff45, /* All L2 DTLB accesses */
180 		[C(RESULT_MISS)]   = 0xf045, /* L2 DTLB misses (PT walks) */
181 	},
182 	[C(OP_WRITE)] = {
183 		[C(RESULT_ACCESS)] = 0,
184 		[C(RESULT_MISS)]   = 0,
185 	},
186 	[C(OP_PREFETCH)] = {
187 		[C(RESULT_ACCESS)] = 0,
188 		[C(RESULT_MISS)]   = 0,
189 	},
190 },
191 [C(ITLB)] = {
192 	[C(OP_READ)] = {
193 		[C(RESULT_ACCESS)] = 0x0084, /* L1 ITLB misses, L2 ITLB hits */
194 		[C(RESULT_MISS)]   = 0xff85, /* L1 ITLB misses, L2 misses */
195 	},
196 	[C(OP_WRITE)] = {
197 		[C(RESULT_ACCESS)] = -1,
198 		[C(RESULT_MISS)]   = -1,
199 	},
200 	[C(OP_PREFETCH)] = {
201 		[C(RESULT_ACCESS)] = -1,
202 		[C(RESULT_MISS)]   = -1,
203 	},
204 },
205 [C(BPU)] = {
206 	[C(OP_READ)] = {
207 		[C(RESULT_ACCESS)] = 0x00c2, /* Retired Branch Instr.      */
208 		[C(RESULT_MISS)]   = 0x00c3, /* Retired Mispredicted BI    */
209 	},
210 	[C(OP_WRITE)] = {
211 		[C(RESULT_ACCESS)] = -1,
212 		[C(RESULT_MISS)]   = -1,
213 	},
214 	[C(OP_PREFETCH)] = {
215 		[C(RESULT_ACCESS)] = -1,
216 		[C(RESULT_MISS)]   = -1,
217 	},
218 },
219 [C(NODE)] = {
220 	[C(OP_READ)] = {
221 		[C(RESULT_ACCESS)] = 0,
222 		[C(RESULT_MISS)]   = 0,
223 	},
224 	[C(OP_WRITE)] = {
225 		[C(RESULT_ACCESS)] = -1,
226 		[C(RESULT_MISS)]   = -1,
227 	},
228 	[C(OP_PREFETCH)] = {
229 		[C(RESULT_ACCESS)] = -1,
230 		[C(RESULT_MISS)]   = -1,
231 	},
232 },
233 };
234 
235 /*
236  * AMD Performance Monitor K7 and later, up to and including Family 16h:
237  */
238 static const u64 amd_perfmon_event_map[PERF_COUNT_HW_MAX] =
239 {
240 	[PERF_COUNT_HW_CPU_CYCLES]		= 0x0076,
241 	[PERF_COUNT_HW_INSTRUCTIONS]		= 0x00c0,
242 	[PERF_COUNT_HW_CACHE_REFERENCES]	= 0x077d,
243 	[PERF_COUNT_HW_CACHE_MISSES]		= 0x077e,
244 	[PERF_COUNT_HW_BRANCH_INSTRUCTIONS]	= 0x00c2,
245 	[PERF_COUNT_HW_BRANCH_MISSES]		= 0x00c3,
246 	[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND]	= 0x00d0, /* "Decoder empty" event */
247 	[PERF_COUNT_HW_STALLED_CYCLES_BACKEND]	= 0x00d1, /* "Dispatch stalls" event */
248 };
249 
250 /*
251  * AMD Performance Monitor Family 17h and later:
252  */
253 static const u64 amd_f17h_perfmon_event_map[PERF_COUNT_HW_MAX] =
254 {
255 	[PERF_COUNT_HW_CPU_CYCLES]		= 0x0076,
256 	[PERF_COUNT_HW_INSTRUCTIONS]		= 0x00c0,
257 	[PERF_COUNT_HW_CACHE_REFERENCES]	= 0xff60,
258 	[PERF_COUNT_HW_CACHE_MISSES]		= 0x0964,
259 	[PERF_COUNT_HW_BRANCH_INSTRUCTIONS]	= 0x00c2,
260 	[PERF_COUNT_HW_BRANCH_MISSES]		= 0x00c3,
261 	[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND]	= 0x0287,
262 	[PERF_COUNT_HW_STALLED_CYCLES_BACKEND]	= 0x0187,
263 };
264 
265 static u64 amd_pmu_event_map(int hw_event)
266 {
267 	if (boot_cpu_data.x86 >= 0x17)
268 		return amd_f17h_perfmon_event_map[hw_event];
269 
270 	return amd_perfmon_event_map[hw_event];
271 }
272 
273 /*
274  * Previously calculated offsets
275  */
276 static unsigned int event_offsets[X86_PMC_IDX_MAX] __read_mostly;
277 static unsigned int count_offsets[X86_PMC_IDX_MAX] __read_mostly;
278 
279 /*
280  * Legacy CPUs:
281  *   4 counters starting at 0xc0010000 each offset by 1
282  *
283  * CPUs with core performance counter extensions:
284  *   6 counters starting at 0xc0010200 each offset by 2
285  */
286 static inline int amd_pmu_addr_offset(int index, bool eventsel)
287 {
288 	int offset;
289 
290 	if (!index)
291 		return index;
292 
293 	if (eventsel)
294 		offset = event_offsets[index];
295 	else
296 		offset = count_offsets[index];
297 
298 	if (offset)
299 		return offset;
300 
301 	if (!boot_cpu_has(X86_FEATURE_PERFCTR_CORE))
302 		offset = index;
303 	else
304 		offset = index << 1;
305 
306 	if (eventsel)
307 		event_offsets[index] = offset;
308 	else
309 		count_offsets[index] = offset;
310 
311 	return offset;
312 }
313 
314 /*
315  * AMD64 events are detected based on their event codes.
316  */
317 static inline unsigned int amd_get_event_code(struct hw_perf_event *hwc)
318 {
319 	return ((hwc->config >> 24) & 0x0f00) | (hwc->config & 0x00ff);
320 }
321 
322 static inline bool amd_is_pair_event_code(struct hw_perf_event *hwc)
323 {
324 	if (!(x86_pmu.flags & PMU_FL_PAIR))
325 		return false;
326 
327 	switch (amd_get_event_code(hwc)) {
328 	case 0x003:	return true;	/* Retired SSE/AVX FLOPs */
329 	default:	return false;
330 	}
331 }
332 
333 DEFINE_STATIC_CALL_RET0(amd_pmu_branch_hw_config, *x86_pmu.hw_config);
334 
335 static int amd_core_hw_config(struct perf_event *event)
336 {
337 	if (event->attr.exclude_host && event->attr.exclude_guest)
338 		/*
339 		 * When HO == GO == 1 the hardware treats that as GO == HO == 0
340 		 * and will count in both modes. We don't want to count in that
341 		 * case so we emulate no-counting by setting US = OS = 0.
342 		 */
343 		event->hw.config &= ~(ARCH_PERFMON_EVENTSEL_USR |
344 				      ARCH_PERFMON_EVENTSEL_OS);
345 	else if (event->attr.exclude_host)
346 		event->hw.config |= AMD64_EVENTSEL_GUESTONLY;
347 	else if (event->attr.exclude_guest)
348 		event->hw.config |= AMD64_EVENTSEL_HOSTONLY;
349 
350 	if ((x86_pmu.flags & PMU_FL_PAIR) && amd_is_pair_event_code(&event->hw))
351 		event->hw.flags |= PERF_X86_EVENT_PAIR;
352 
353 	if (has_branch_stack(event))
354 		return static_call(amd_pmu_branch_hw_config)(event);
355 
356 	return 0;
357 }
358 
359 static inline int amd_is_nb_event(struct hw_perf_event *hwc)
360 {
361 	return (hwc->config & 0xe0) == 0xe0;
362 }
363 
364 static inline int amd_has_nb(struct cpu_hw_events *cpuc)
365 {
366 	struct amd_nb *nb = cpuc->amd_nb;
367 
368 	return nb && nb->nb_id != -1;
369 }
370 
371 static int amd_pmu_hw_config(struct perf_event *event)
372 {
373 	int ret;
374 
375 	/* pass precise event sampling to ibs: */
376 	if (event->attr.precise_ip && get_ibs_caps())
377 		return -ENOENT;
378 
379 	if (has_branch_stack(event) && !x86_pmu.lbr_nr)
380 		return -EOPNOTSUPP;
381 
382 	ret = x86_pmu_hw_config(event);
383 	if (ret)
384 		return ret;
385 
386 	if (event->attr.type == PERF_TYPE_RAW)
387 		event->hw.config |= event->attr.config & AMD64_RAW_EVENT_MASK;
388 
389 	return amd_core_hw_config(event);
390 }
391 
392 static void __amd_put_nb_event_constraints(struct cpu_hw_events *cpuc,
393 					   struct perf_event *event)
394 {
395 	struct amd_nb *nb = cpuc->amd_nb;
396 	int i;
397 
398 	/*
399 	 * need to scan whole list because event may not have
400 	 * been assigned during scheduling
401 	 *
402 	 * no race condition possible because event can only
403 	 * be removed on one CPU at a time AND PMU is disabled
404 	 * when we come here
405 	 */
406 	for (i = 0; i < x86_pmu.num_counters; i++) {
407 		if (cmpxchg(nb->owners + i, event, NULL) == event)
408 			break;
409 	}
410 }
411 
412  /*
413   * AMD64 NorthBridge events need special treatment because
414   * counter access needs to be synchronized across all cores
415   * of a package. Refer to BKDG section 3.12
416   *
417   * NB events are events measuring L3 cache, Hypertransport
418   * traffic. They are identified by an event code >= 0xe00.
419   * They measure events on the NorthBride which is shared
420   * by all cores on a package. NB events are counted on a
421   * shared set of counters. When a NB event is programmed
422   * in a counter, the data actually comes from a shared
423   * counter. Thus, access to those counters needs to be
424   * synchronized.
425   *
426   * We implement the synchronization such that no two cores
427   * can be measuring NB events using the same counters. Thus,
428   * we maintain a per-NB allocation table. The available slot
429   * is propagated using the event_constraint structure.
430   *
431   * We provide only one choice for each NB event based on
432   * the fact that only NB events have restrictions. Consequently,
433   * if a counter is available, there is a guarantee the NB event
434   * will be assigned to it. If no slot is available, an empty
435   * constraint is returned and scheduling will eventually fail
436   * for this event.
437   *
438   * Note that all cores attached the same NB compete for the same
439   * counters to host NB events, this is why we use atomic ops. Some
440   * multi-chip CPUs may have more than one NB.
441   *
442   * Given that resources are allocated (cmpxchg), they must be
443   * eventually freed for others to use. This is accomplished by
444   * calling __amd_put_nb_event_constraints()
445   *
446   * Non NB events are not impacted by this restriction.
447   */
448 static struct event_constraint *
449 __amd_get_nb_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event,
450 			       struct event_constraint *c)
451 {
452 	struct hw_perf_event *hwc = &event->hw;
453 	struct amd_nb *nb = cpuc->amd_nb;
454 	struct perf_event *old;
455 	int idx, new = -1;
456 
457 	if (!c)
458 		c = &unconstrained;
459 
460 	if (cpuc->is_fake)
461 		return c;
462 
463 	/*
464 	 * detect if already present, if so reuse
465 	 *
466 	 * cannot merge with actual allocation
467 	 * because of possible holes
468 	 *
469 	 * event can already be present yet not assigned (in hwc->idx)
470 	 * because of successive calls to x86_schedule_events() from
471 	 * hw_perf_group_sched_in() without hw_perf_enable()
472 	 */
473 	for_each_set_bit(idx, c->idxmsk, x86_pmu.num_counters) {
474 		if (new == -1 || hwc->idx == idx)
475 			/* assign free slot, prefer hwc->idx */
476 			old = cmpxchg(nb->owners + idx, NULL, event);
477 		else if (nb->owners[idx] == event)
478 			/* event already present */
479 			old = event;
480 		else
481 			continue;
482 
483 		if (old && old != event)
484 			continue;
485 
486 		/* reassign to this slot */
487 		if (new != -1)
488 			cmpxchg(nb->owners + new, event, NULL);
489 		new = idx;
490 
491 		/* already present, reuse */
492 		if (old == event)
493 			break;
494 	}
495 
496 	if (new == -1)
497 		return &emptyconstraint;
498 
499 	return &nb->event_constraints[new];
500 }
501 
502 static struct amd_nb *amd_alloc_nb(int cpu)
503 {
504 	struct amd_nb *nb;
505 	int i;
506 
507 	nb = kzalloc_node(sizeof(struct amd_nb), GFP_KERNEL, cpu_to_node(cpu));
508 	if (!nb)
509 		return NULL;
510 
511 	nb->nb_id = -1;
512 
513 	/*
514 	 * initialize all possible NB constraints
515 	 */
516 	for (i = 0; i < x86_pmu.num_counters; i++) {
517 		__set_bit(i, nb->event_constraints[i].idxmsk);
518 		nb->event_constraints[i].weight = 1;
519 	}
520 	return nb;
521 }
522 
523 typedef void (amd_pmu_branch_reset_t)(void);
524 DEFINE_STATIC_CALL_NULL(amd_pmu_branch_reset, amd_pmu_branch_reset_t);
525 
526 static void amd_pmu_cpu_reset(int cpu)
527 {
528 	if (x86_pmu.lbr_nr)
529 		static_call(amd_pmu_branch_reset)();
530 
531 	if (x86_pmu.version < 2)
532 		return;
533 
534 	/* Clear enable bits i.e. PerfCntrGlobalCtl.PerfCntrEn */
535 	wrmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_CTL, 0);
536 
537 	/* Clear overflow bits i.e. PerfCntrGLobalStatus.PerfCntrOvfl */
538 	wrmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR, amd_pmu_global_cntr_mask);
539 }
540 
541 static int amd_pmu_cpu_prepare(int cpu)
542 {
543 	struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
544 
545 	WARN_ON_ONCE(cpuc->amd_nb);
546 
547 	if (!x86_pmu.amd_nb_constraints)
548 		return 0;
549 
550 	cpuc->amd_nb = amd_alloc_nb(cpu);
551 	if (!cpuc->amd_nb)
552 		return -ENOMEM;
553 
554 	return 0;
555 }
556 
557 static void amd_pmu_cpu_starting(int cpu)
558 {
559 	struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
560 	void **onln = &cpuc->kfree_on_online[X86_PERF_KFREE_SHARED];
561 	struct amd_nb *nb;
562 	int i, nb_id;
563 
564 	cpuc->perf_ctr_virt_mask = AMD64_EVENTSEL_HOSTONLY;
565 
566 	if (!x86_pmu.amd_nb_constraints)
567 		return;
568 
569 	nb_id = topology_die_id(cpu);
570 	WARN_ON_ONCE(nb_id == BAD_APICID);
571 
572 	for_each_online_cpu(i) {
573 		nb = per_cpu(cpu_hw_events, i).amd_nb;
574 		if (WARN_ON_ONCE(!nb))
575 			continue;
576 
577 		if (nb->nb_id == nb_id) {
578 			*onln = cpuc->amd_nb;
579 			cpuc->amd_nb = nb;
580 			break;
581 		}
582 	}
583 
584 	cpuc->amd_nb->nb_id = nb_id;
585 	cpuc->amd_nb->refcnt++;
586 
587 	amd_pmu_cpu_reset(cpu);
588 }
589 
590 static void amd_pmu_cpu_dead(int cpu)
591 {
592 	struct cpu_hw_events *cpuhw;
593 
594 	if (!x86_pmu.amd_nb_constraints)
595 		return;
596 
597 	cpuhw = &per_cpu(cpu_hw_events, cpu);
598 
599 	if (cpuhw->amd_nb) {
600 		struct amd_nb *nb = cpuhw->amd_nb;
601 
602 		if (nb->nb_id == -1 || --nb->refcnt == 0)
603 			kfree(nb);
604 
605 		cpuhw->amd_nb = NULL;
606 	}
607 
608 	amd_pmu_cpu_reset(cpu);
609 }
610 
611 static inline void amd_pmu_set_global_ctl(u64 ctl)
612 {
613 	wrmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_CTL, ctl);
614 }
615 
616 static inline u64 amd_pmu_get_global_status(void)
617 {
618 	u64 status;
619 
620 	/* PerfCntrGlobalStatus is read-only */
621 	rdmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_STATUS, status);
622 
623 	return status & amd_pmu_global_cntr_mask;
624 }
625 
626 static inline void amd_pmu_ack_global_status(u64 status)
627 {
628 	/*
629 	 * PerfCntrGlobalStatus is read-only but an overflow acknowledgment
630 	 * mechanism exists; writing 1 to a bit in PerfCntrGlobalStatusClr
631 	 * clears the same bit in PerfCntrGlobalStatus
632 	 */
633 
634 	/* Only allow modifications to PerfCntrGlobalStatus.PerfCntrOvfl */
635 	status &= amd_pmu_global_cntr_mask;
636 	wrmsrl(MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR, status);
637 }
638 
639 static bool amd_pmu_test_overflow_topbit(int idx)
640 {
641 	u64 counter;
642 
643 	rdmsrl(x86_pmu_event_addr(idx), counter);
644 
645 	return !(counter & BIT_ULL(x86_pmu.cntval_bits - 1));
646 }
647 
648 static bool amd_pmu_test_overflow_status(int idx)
649 {
650 	return amd_pmu_get_global_status() & BIT_ULL(idx);
651 }
652 
653 DEFINE_STATIC_CALL(amd_pmu_test_overflow, amd_pmu_test_overflow_topbit);
654 
655 /*
656  * When a PMC counter overflows, an NMI is used to process the event and
657  * reset the counter. NMI latency can result in the counter being updated
658  * before the NMI can run, which can result in what appear to be spurious
659  * NMIs. This function is intended to wait for the NMI to run and reset
660  * the counter to avoid possible unhandled NMI messages.
661  */
662 #define OVERFLOW_WAIT_COUNT	50
663 
664 static void amd_pmu_wait_on_overflow(int idx)
665 {
666 	unsigned int i;
667 
668 	/*
669 	 * Wait for the counter to be reset if it has overflowed. This loop
670 	 * should exit very, very quickly, but just in case, don't wait
671 	 * forever...
672 	 */
673 	for (i = 0; i < OVERFLOW_WAIT_COUNT; i++) {
674 		if (!static_call(amd_pmu_test_overflow)(idx))
675 			break;
676 
677 		/* Might be in IRQ context, so can't sleep */
678 		udelay(1);
679 	}
680 }
681 
682 static void amd_pmu_check_overflow(void)
683 {
684 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
685 	int idx;
686 
687 	/*
688 	 * This shouldn't be called from NMI context, but add a safeguard here
689 	 * to return, since if we're in NMI context we can't wait for an NMI
690 	 * to reset an overflowed counter value.
691 	 */
692 	if (in_nmi())
693 		return;
694 
695 	/*
696 	 * Check each counter for overflow and wait for it to be reset by the
697 	 * NMI if it has overflowed. This relies on the fact that all active
698 	 * counters are always enabled when this function is called and
699 	 * ARCH_PERFMON_EVENTSEL_INT is always set.
700 	 */
701 	for (idx = 0; idx < x86_pmu.num_counters; idx++) {
702 		if (!test_bit(idx, cpuc->active_mask))
703 			continue;
704 
705 		amd_pmu_wait_on_overflow(idx);
706 	}
707 }
708 
709 static void amd_pmu_enable_event(struct perf_event *event)
710 {
711 	x86_pmu_enable_event(event);
712 }
713 
714 static void amd_pmu_enable_all(int added)
715 {
716 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
717 	int idx;
718 
719 	amd_brs_enable_all();
720 
721 	for (idx = 0; idx < x86_pmu.num_counters; idx++) {
722 		/* only activate events which are marked as active */
723 		if (!test_bit(idx, cpuc->active_mask))
724 			continue;
725 
726 		amd_pmu_enable_event(cpuc->events[idx]);
727 	}
728 }
729 
730 static void amd_pmu_v2_enable_event(struct perf_event *event)
731 {
732 	struct hw_perf_event *hwc = &event->hw;
733 
734 	/*
735 	 * Testing cpu_hw_events.enabled should be skipped in this case unlike
736 	 * in x86_pmu_enable_event().
737 	 *
738 	 * Since cpu_hw_events.enabled is set only after returning from
739 	 * x86_pmu_start(), the PMCs must be programmed and kept ready.
740 	 * Counting starts only after x86_pmu_enable_all() is called.
741 	 */
742 	__x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
743 }
744 
745 static void amd_pmu_v2_enable_all(int added)
746 {
747 	amd_pmu_set_global_ctl(amd_pmu_global_cntr_mask);
748 }
749 
750 static void amd_pmu_disable_event(struct perf_event *event)
751 {
752 	x86_pmu_disable_event(event);
753 
754 	/*
755 	 * This can be called from NMI context (via x86_pmu_stop). The counter
756 	 * may have overflowed, but either way, we'll never see it get reset
757 	 * by the NMI if we're already in the NMI. And the NMI latency support
758 	 * below will take care of any pending NMI that might have been
759 	 * generated by the overflow.
760 	 */
761 	if (in_nmi())
762 		return;
763 
764 	amd_pmu_wait_on_overflow(event->hw.idx);
765 }
766 
767 static void amd_pmu_disable_all(void)
768 {
769 	amd_brs_disable_all();
770 	x86_pmu_disable_all();
771 	amd_pmu_check_overflow();
772 }
773 
774 static void amd_pmu_v2_disable_all(void)
775 {
776 	/* Disable all PMCs */
777 	amd_pmu_set_global_ctl(0);
778 	amd_pmu_check_overflow();
779 }
780 
781 DEFINE_STATIC_CALL_NULL(amd_pmu_branch_add, *x86_pmu.add);
782 
783 static void amd_pmu_add_event(struct perf_event *event)
784 {
785 	if (needs_branch_stack(event))
786 		static_call(amd_pmu_branch_add)(event);
787 }
788 
789 DEFINE_STATIC_CALL_NULL(amd_pmu_branch_del, *x86_pmu.del);
790 
791 static void amd_pmu_del_event(struct perf_event *event)
792 {
793 	if (needs_branch_stack(event))
794 		static_call(amd_pmu_branch_del)(event);
795 }
796 
797 /*
798  * Because of NMI latency, if multiple PMC counters are active or other sources
799  * of NMIs are received, the perf NMI handler can handle one or more overflowed
800  * PMC counters outside of the NMI associated with the PMC overflow. If the NMI
801  * doesn't arrive at the LAPIC in time to become a pending NMI, then the kernel
802  * back-to-back NMI support won't be active. This PMC handler needs to take into
803  * account that this can occur, otherwise this could result in unknown NMI
804  * messages being issued. Examples of this is PMC overflow while in the NMI
805  * handler when multiple PMCs are active or PMC overflow while handling some
806  * other source of an NMI.
807  *
808  * Attempt to mitigate this by creating an NMI window in which un-handled NMIs
809  * received during this window will be claimed. This prevents extending the
810  * window past when it is possible that latent NMIs should be received. The
811  * per-CPU perf_nmi_tstamp will be set to the window end time whenever perf has
812  * handled a counter. When an un-handled NMI is received, it will be claimed
813  * only if arriving within that window.
814  */
815 static inline int amd_pmu_adjust_nmi_window(int handled)
816 {
817 	/*
818 	 * If a counter was handled, record a timestamp such that un-handled
819 	 * NMIs will be claimed if arriving within that window.
820 	 */
821 	if (handled) {
822 		this_cpu_write(perf_nmi_tstamp, jiffies + perf_nmi_window);
823 
824 		return handled;
825 	}
826 
827 	if (time_after(jiffies, this_cpu_read(perf_nmi_tstamp)))
828 		return NMI_DONE;
829 
830 	return NMI_HANDLED;
831 }
832 
833 static int amd_pmu_handle_irq(struct pt_regs *regs)
834 {
835 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
836 	int handled;
837 	int pmu_enabled;
838 
839 	/*
840 	 * Save the PMU state.
841 	 * It needs to be restored when leaving the handler.
842 	 */
843 	pmu_enabled = cpuc->enabled;
844 	cpuc->enabled = 0;
845 
846 	/* stop everything (includes BRS) */
847 	amd_pmu_disable_all();
848 
849 	/* Drain BRS is in use (could be inactive) */
850 	if (cpuc->lbr_users)
851 		amd_brs_drain();
852 
853 	/* Process any counter overflows */
854 	handled = x86_pmu_handle_irq(regs);
855 
856 	cpuc->enabled = pmu_enabled;
857 	if (pmu_enabled)
858 		amd_pmu_enable_all(0);
859 
860 	return amd_pmu_adjust_nmi_window(handled);
861 }
862 
863 static int amd_pmu_v2_handle_irq(struct pt_regs *regs)
864 {
865 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
866 	struct perf_sample_data data;
867 	struct hw_perf_event *hwc;
868 	struct perf_event *event;
869 	int handled = 0, idx;
870 	u64 status, mask;
871 	bool pmu_enabled;
872 
873 	/*
874 	 * Save the PMU state as it needs to be restored when leaving the
875 	 * handler
876 	 */
877 	pmu_enabled = cpuc->enabled;
878 	cpuc->enabled = 0;
879 
880 	/* Stop counting */
881 	amd_pmu_v2_disable_all();
882 
883 	status = amd_pmu_get_global_status();
884 
885 	/* Check if any overflows are pending */
886 	if (!status)
887 		goto done;
888 
889 	for (idx = 0; idx < x86_pmu.num_counters; idx++) {
890 		if (!test_bit(idx, cpuc->active_mask))
891 			continue;
892 
893 		event = cpuc->events[idx];
894 		hwc = &event->hw;
895 		x86_perf_event_update(event);
896 		mask = BIT_ULL(idx);
897 
898 		if (!(status & mask))
899 			continue;
900 
901 		/* Event overflow */
902 		handled++;
903 		perf_sample_data_init(&data, 0, hwc->last_period);
904 
905 		if (!x86_perf_event_set_period(event))
906 			continue;
907 
908 		if (perf_event_overflow(event, &data, regs))
909 			x86_pmu_stop(event, 0);
910 
911 		status &= ~mask;
912 	}
913 
914 	/*
915 	 * It should never be the case that some overflows are not handled as
916 	 * the corresponding PMCs are expected to be inactive according to the
917 	 * active_mask
918 	 */
919 	WARN_ON(status > 0);
920 
921 	/* Clear overflow bits */
922 	amd_pmu_ack_global_status(~status);
923 
924 	/*
925 	 * Unmasking the LVTPC is not required as the Mask (M) bit of the LVT
926 	 * PMI entry is not set by the local APIC when a PMC overflow occurs
927 	 */
928 	inc_irq_stat(apic_perf_irqs);
929 
930 done:
931 	cpuc->enabled = pmu_enabled;
932 
933 	/* Resume counting only if PMU is active */
934 	if (pmu_enabled)
935 		amd_pmu_v2_enable_all(0);
936 
937 	return amd_pmu_adjust_nmi_window(handled);
938 }
939 
940 static struct event_constraint *
941 amd_get_event_constraints(struct cpu_hw_events *cpuc, int idx,
942 			  struct perf_event *event)
943 {
944 	/*
945 	 * if not NB event or no NB, then no constraints
946 	 */
947 	if (!(amd_has_nb(cpuc) && amd_is_nb_event(&event->hw)))
948 		return &unconstrained;
949 
950 	return __amd_get_nb_event_constraints(cpuc, event, NULL);
951 }
952 
953 static void amd_put_event_constraints(struct cpu_hw_events *cpuc,
954 				      struct perf_event *event)
955 {
956 	if (amd_has_nb(cpuc) && amd_is_nb_event(&event->hw))
957 		__amd_put_nb_event_constraints(cpuc, event);
958 }
959 
960 PMU_FORMAT_ATTR(event,	"config:0-7,32-35");
961 PMU_FORMAT_ATTR(umask,	"config:8-15"	);
962 PMU_FORMAT_ATTR(edge,	"config:18"	);
963 PMU_FORMAT_ATTR(inv,	"config:23"	);
964 PMU_FORMAT_ATTR(cmask,	"config:24-31"	);
965 
966 static struct attribute *amd_format_attr[] = {
967 	&format_attr_event.attr,
968 	&format_attr_umask.attr,
969 	&format_attr_edge.attr,
970 	&format_attr_inv.attr,
971 	&format_attr_cmask.attr,
972 	NULL,
973 };
974 
975 /* AMD Family 15h */
976 
977 #define AMD_EVENT_TYPE_MASK	0x000000F0ULL
978 
979 #define AMD_EVENT_FP		0x00000000ULL ... 0x00000010ULL
980 #define AMD_EVENT_LS		0x00000020ULL ... 0x00000030ULL
981 #define AMD_EVENT_DC		0x00000040ULL ... 0x00000050ULL
982 #define AMD_EVENT_CU		0x00000060ULL ... 0x00000070ULL
983 #define AMD_EVENT_IC_DE		0x00000080ULL ... 0x00000090ULL
984 #define AMD_EVENT_EX_LS		0x000000C0ULL
985 #define AMD_EVENT_DE		0x000000D0ULL
986 #define AMD_EVENT_NB		0x000000E0ULL ... 0x000000F0ULL
987 
988 /*
989  * AMD family 15h event code/PMC mappings:
990  *
991  * type = event_code & 0x0F0:
992  *
993  * 0x000	FP	PERF_CTL[5:3]
994  * 0x010	FP	PERF_CTL[5:3]
995  * 0x020	LS	PERF_CTL[5:0]
996  * 0x030	LS	PERF_CTL[5:0]
997  * 0x040	DC	PERF_CTL[5:0]
998  * 0x050	DC	PERF_CTL[5:0]
999  * 0x060	CU	PERF_CTL[2:0]
1000  * 0x070	CU	PERF_CTL[2:0]
1001  * 0x080	IC/DE	PERF_CTL[2:0]
1002  * 0x090	IC/DE	PERF_CTL[2:0]
1003  * 0x0A0	---
1004  * 0x0B0	---
1005  * 0x0C0	EX/LS	PERF_CTL[5:0]
1006  * 0x0D0	DE	PERF_CTL[2:0]
1007  * 0x0E0	NB	NB_PERF_CTL[3:0]
1008  * 0x0F0	NB	NB_PERF_CTL[3:0]
1009  *
1010  * Exceptions:
1011  *
1012  * 0x000	FP	PERF_CTL[3], PERF_CTL[5:3] (*)
1013  * 0x003	FP	PERF_CTL[3]
1014  * 0x004	FP	PERF_CTL[3], PERF_CTL[5:3] (*)
1015  * 0x00B	FP	PERF_CTL[3]
1016  * 0x00D	FP	PERF_CTL[3]
1017  * 0x023	DE	PERF_CTL[2:0]
1018  * 0x02D	LS	PERF_CTL[3]
1019  * 0x02E	LS	PERF_CTL[3,0]
1020  * 0x031	LS	PERF_CTL[2:0] (**)
1021  * 0x043	CU	PERF_CTL[2:0]
1022  * 0x045	CU	PERF_CTL[2:0]
1023  * 0x046	CU	PERF_CTL[2:0]
1024  * 0x054	CU	PERF_CTL[2:0]
1025  * 0x055	CU	PERF_CTL[2:0]
1026  * 0x08F	IC	PERF_CTL[0]
1027  * 0x187	DE	PERF_CTL[0]
1028  * 0x188	DE	PERF_CTL[0]
1029  * 0x0DB	EX	PERF_CTL[5:0]
1030  * 0x0DC	LS	PERF_CTL[5:0]
1031  * 0x0DD	LS	PERF_CTL[5:0]
1032  * 0x0DE	LS	PERF_CTL[5:0]
1033  * 0x0DF	LS	PERF_CTL[5:0]
1034  * 0x1C0	EX	PERF_CTL[5:3]
1035  * 0x1D6	EX	PERF_CTL[5:0]
1036  * 0x1D8	EX	PERF_CTL[5:0]
1037  *
1038  * (*)  depending on the umask all FPU counters may be used
1039  * (**) only one unitmask enabled at a time
1040  */
1041 
1042 static struct event_constraint amd_f15_PMC0  = EVENT_CONSTRAINT(0, 0x01, 0);
1043 static struct event_constraint amd_f15_PMC20 = EVENT_CONSTRAINT(0, 0x07, 0);
1044 static struct event_constraint amd_f15_PMC3  = EVENT_CONSTRAINT(0, 0x08, 0);
1045 static struct event_constraint amd_f15_PMC30 = EVENT_CONSTRAINT_OVERLAP(0, 0x09, 0);
1046 static struct event_constraint amd_f15_PMC50 = EVENT_CONSTRAINT(0, 0x3F, 0);
1047 static struct event_constraint amd_f15_PMC53 = EVENT_CONSTRAINT(0, 0x38, 0);
1048 
1049 static struct event_constraint *
1050 amd_get_event_constraints_f15h(struct cpu_hw_events *cpuc, int idx,
1051 			       struct perf_event *event)
1052 {
1053 	struct hw_perf_event *hwc = &event->hw;
1054 	unsigned int event_code = amd_get_event_code(hwc);
1055 
1056 	switch (event_code & AMD_EVENT_TYPE_MASK) {
1057 	case AMD_EVENT_FP:
1058 		switch (event_code) {
1059 		case 0x000:
1060 			if (!(hwc->config & 0x0000F000ULL))
1061 				break;
1062 			if (!(hwc->config & 0x00000F00ULL))
1063 				break;
1064 			return &amd_f15_PMC3;
1065 		case 0x004:
1066 			if (hweight_long(hwc->config & ARCH_PERFMON_EVENTSEL_UMASK) <= 1)
1067 				break;
1068 			return &amd_f15_PMC3;
1069 		case 0x003:
1070 		case 0x00B:
1071 		case 0x00D:
1072 			return &amd_f15_PMC3;
1073 		}
1074 		return &amd_f15_PMC53;
1075 	case AMD_EVENT_LS:
1076 	case AMD_EVENT_DC:
1077 	case AMD_EVENT_EX_LS:
1078 		switch (event_code) {
1079 		case 0x023:
1080 		case 0x043:
1081 		case 0x045:
1082 		case 0x046:
1083 		case 0x054:
1084 		case 0x055:
1085 			return &amd_f15_PMC20;
1086 		case 0x02D:
1087 			return &amd_f15_PMC3;
1088 		case 0x02E:
1089 			return &amd_f15_PMC30;
1090 		case 0x031:
1091 			if (hweight_long(hwc->config & ARCH_PERFMON_EVENTSEL_UMASK) <= 1)
1092 				return &amd_f15_PMC20;
1093 			return &emptyconstraint;
1094 		case 0x1C0:
1095 			return &amd_f15_PMC53;
1096 		default:
1097 			return &amd_f15_PMC50;
1098 		}
1099 	case AMD_EVENT_CU:
1100 	case AMD_EVENT_IC_DE:
1101 	case AMD_EVENT_DE:
1102 		switch (event_code) {
1103 		case 0x08F:
1104 		case 0x187:
1105 		case 0x188:
1106 			return &amd_f15_PMC0;
1107 		case 0x0DB ... 0x0DF:
1108 		case 0x1D6:
1109 		case 0x1D8:
1110 			return &amd_f15_PMC50;
1111 		default:
1112 			return &amd_f15_PMC20;
1113 		}
1114 	case AMD_EVENT_NB:
1115 		/* moved to uncore.c */
1116 		return &emptyconstraint;
1117 	default:
1118 		return &emptyconstraint;
1119 	}
1120 }
1121 
1122 static struct event_constraint pair_constraint;
1123 
1124 static struct event_constraint *
1125 amd_get_event_constraints_f17h(struct cpu_hw_events *cpuc, int idx,
1126 			       struct perf_event *event)
1127 {
1128 	struct hw_perf_event *hwc = &event->hw;
1129 
1130 	if (amd_is_pair_event_code(hwc))
1131 		return &pair_constraint;
1132 
1133 	return &unconstrained;
1134 }
1135 
1136 static void amd_put_event_constraints_f17h(struct cpu_hw_events *cpuc,
1137 					   struct perf_event *event)
1138 {
1139 	struct hw_perf_event *hwc = &event->hw;
1140 
1141 	if (is_counter_pair(hwc))
1142 		--cpuc->n_pair;
1143 }
1144 
1145 /*
1146  * Because of the way BRS operates with an inactive and active phases, and
1147  * the link to one counter, it is not possible to have two events using BRS
1148  * scheduled at the same time. There would be an issue with enforcing the
1149  * period of each one and given that the BRS saturates, it would not be possible
1150  * to guarantee correlated content for all events. Therefore, in situations
1151  * where multiple events want to use BRS, the kernel enforces mutual exclusion.
1152  * Exclusion is enforced by chosing only one counter for events using BRS.
1153  * The event scheduling logic will then automatically multiplex the
1154  * events and ensure that at most one event is actively using BRS.
1155  *
1156  * The BRS counter could be any counter, but there is no constraint on Fam19h,
1157  * therefore all counters are equal and thus we pick the first one: PMC0
1158  */
1159 static struct event_constraint amd_fam19h_brs_cntr0_constraint =
1160 	EVENT_CONSTRAINT(0, 0x1, AMD64_RAW_EVENT_MASK);
1161 
1162 static struct event_constraint amd_fam19h_brs_pair_cntr0_constraint =
1163 	__EVENT_CONSTRAINT(0, 0x1, AMD64_RAW_EVENT_MASK, 1, 0, PERF_X86_EVENT_PAIR);
1164 
1165 static struct event_constraint *
1166 amd_get_event_constraints_f19h(struct cpu_hw_events *cpuc, int idx,
1167 			  struct perf_event *event)
1168 {
1169 	struct hw_perf_event *hwc = &event->hw;
1170 	bool has_brs = has_amd_brs(hwc);
1171 
1172 	/*
1173 	 * In case BRS is used with an event requiring a counter pair,
1174 	 * the kernel allows it but only on counter 0 & 1 to enforce
1175 	 * multiplexing requiring to protect BRS in case of multiple
1176 	 * BRS users
1177 	 */
1178 	if (amd_is_pair_event_code(hwc)) {
1179 		return has_brs ? &amd_fam19h_brs_pair_cntr0_constraint
1180 			       : &pair_constraint;
1181 	}
1182 
1183 	if (has_brs)
1184 		return &amd_fam19h_brs_cntr0_constraint;
1185 
1186 	return &unconstrained;
1187 }
1188 
1189 
1190 static ssize_t amd_event_sysfs_show(char *page, u64 config)
1191 {
1192 	u64 event = (config & ARCH_PERFMON_EVENTSEL_EVENT) |
1193 		    (config & AMD64_EVENTSEL_EVENT) >> 24;
1194 
1195 	return x86_event_sysfs_show(page, config, event);
1196 }
1197 
1198 static u64 amd_pmu_limit_period(struct perf_event *event, u64 left)
1199 {
1200 	/*
1201 	 * Decrease period by the depth of the BRS feature to get the last N
1202 	 * taken branches and approximate the desired period
1203 	 */
1204 	if (has_branch_stack(event) && left > x86_pmu.lbr_nr)
1205 		left -= x86_pmu.lbr_nr;
1206 
1207 	return left;
1208 }
1209 
1210 static __initconst const struct x86_pmu amd_pmu = {
1211 	.name			= "AMD",
1212 	.handle_irq		= amd_pmu_handle_irq,
1213 	.disable_all		= amd_pmu_disable_all,
1214 	.enable_all		= amd_pmu_enable_all,
1215 	.enable			= amd_pmu_enable_event,
1216 	.disable		= amd_pmu_disable_event,
1217 	.hw_config		= amd_pmu_hw_config,
1218 	.schedule_events	= x86_schedule_events,
1219 	.eventsel		= MSR_K7_EVNTSEL0,
1220 	.perfctr		= MSR_K7_PERFCTR0,
1221 	.addr_offset            = amd_pmu_addr_offset,
1222 	.event_map		= amd_pmu_event_map,
1223 	.max_events		= ARRAY_SIZE(amd_perfmon_event_map),
1224 	.num_counters		= AMD64_NUM_COUNTERS,
1225 	.add			= amd_pmu_add_event,
1226 	.del			= amd_pmu_del_event,
1227 	.cntval_bits		= 48,
1228 	.cntval_mask		= (1ULL << 48) - 1,
1229 	.apic			= 1,
1230 	/* use highest bit to detect overflow */
1231 	.max_period		= (1ULL << 47) - 1,
1232 	.get_event_constraints	= amd_get_event_constraints,
1233 	.put_event_constraints	= amd_put_event_constraints,
1234 
1235 	.format_attrs		= amd_format_attr,
1236 	.events_sysfs_show	= amd_event_sysfs_show,
1237 
1238 	.cpu_prepare		= amd_pmu_cpu_prepare,
1239 	.cpu_starting		= amd_pmu_cpu_starting,
1240 	.cpu_dead		= amd_pmu_cpu_dead,
1241 
1242 	.amd_nb_constraints	= 1,
1243 };
1244 
1245 static ssize_t branches_show(struct device *cdev,
1246 			      struct device_attribute *attr,
1247 			      char *buf)
1248 {
1249 	return snprintf(buf, PAGE_SIZE, "%d\n", x86_pmu.lbr_nr);
1250 }
1251 
1252 static DEVICE_ATTR_RO(branches);
1253 
1254 static struct attribute *amd_pmu_branches_attrs[] = {
1255 	&dev_attr_branches.attr,
1256 	NULL,
1257 };
1258 
1259 static umode_t
1260 amd_branches_is_visible(struct kobject *kobj, struct attribute *attr, int i)
1261 {
1262 	return x86_pmu.lbr_nr ? attr->mode : 0;
1263 }
1264 
1265 static struct attribute_group group_caps_amd_branches = {
1266 	.name  = "caps",
1267 	.attrs = amd_pmu_branches_attrs,
1268 	.is_visible = amd_branches_is_visible,
1269 };
1270 
1271 #ifdef CONFIG_PERF_EVENTS_AMD_BRS
1272 
1273 EVENT_ATTR_STR(branch-brs, amd_branch_brs,
1274 	       "event=" __stringify(AMD_FAM19H_BRS_EVENT)"\n");
1275 
1276 static struct attribute *amd_brs_events_attrs[] = {
1277 	EVENT_PTR(amd_branch_brs),
1278 	NULL,
1279 };
1280 
1281 static umode_t
1282 amd_brs_is_visible(struct kobject *kobj, struct attribute *attr, int i)
1283 {
1284 	return static_cpu_has(X86_FEATURE_BRS) && x86_pmu.lbr_nr ?
1285 	       attr->mode : 0;
1286 }
1287 
1288 static struct attribute_group group_events_amd_brs = {
1289 	.name       = "events",
1290 	.attrs      = amd_brs_events_attrs,
1291 	.is_visible = amd_brs_is_visible,
1292 };
1293 
1294 #endif	/* CONFIG_PERF_EVENTS_AMD_BRS */
1295 
1296 static const struct attribute_group *amd_attr_update[] = {
1297 	&group_caps_amd_branches,
1298 #ifdef CONFIG_PERF_EVENTS_AMD_BRS
1299 	&group_events_amd_brs,
1300 #endif
1301 	NULL,
1302 };
1303 
1304 static int __init amd_core_pmu_init(void)
1305 {
1306 	union cpuid_0x80000022_ebx ebx;
1307 	u64 even_ctr_mask = 0ULL;
1308 	int i;
1309 
1310 	if (!boot_cpu_has(X86_FEATURE_PERFCTR_CORE))
1311 		return 0;
1312 
1313 	/* Avoid calculating the value each time in the NMI handler */
1314 	perf_nmi_window = msecs_to_jiffies(100);
1315 
1316 	/*
1317 	 * If core performance counter extensions exists, we must use
1318 	 * MSR_F15H_PERF_CTL/MSR_F15H_PERF_CTR msrs. See also
1319 	 * amd_pmu_addr_offset().
1320 	 */
1321 	x86_pmu.eventsel	= MSR_F15H_PERF_CTL;
1322 	x86_pmu.perfctr		= MSR_F15H_PERF_CTR;
1323 	x86_pmu.num_counters	= AMD64_NUM_COUNTERS_CORE;
1324 
1325 	/* Check for Performance Monitoring v2 support */
1326 	if (boot_cpu_has(X86_FEATURE_PERFMON_V2)) {
1327 		ebx.full = cpuid_ebx(EXT_PERFMON_DEBUG_FEATURES);
1328 
1329 		/* Update PMU version for later usage */
1330 		x86_pmu.version = 2;
1331 
1332 		/* Find the number of available Core PMCs */
1333 		x86_pmu.num_counters = ebx.split.num_core_pmc;
1334 
1335 		amd_pmu_global_cntr_mask = (1ULL << x86_pmu.num_counters) - 1;
1336 
1337 		/* Update PMC handling functions */
1338 		x86_pmu.enable_all = amd_pmu_v2_enable_all;
1339 		x86_pmu.disable_all = amd_pmu_v2_disable_all;
1340 		x86_pmu.enable = amd_pmu_v2_enable_event;
1341 		x86_pmu.handle_irq = amd_pmu_v2_handle_irq;
1342 		static_call_update(amd_pmu_test_overflow, amd_pmu_test_overflow_status);
1343 	}
1344 
1345 	/*
1346 	 * AMD Core perfctr has separate MSRs for the NB events, see
1347 	 * the amd/uncore.c driver.
1348 	 */
1349 	x86_pmu.amd_nb_constraints = 0;
1350 
1351 	if (boot_cpu_data.x86 == 0x15) {
1352 		pr_cont("Fam15h ");
1353 		x86_pmu.get_event_constraints = amd_get_event_constraints_f15h;
1354 	}
1355 	if (boot_cpu_data.x86 >= 0x17) {
1356 		pr_cont("Fam17h+ ");
1357 		/*
1358 		 * Family 17h and compatibles have constraints for Large
1359 		 * Increment per Cycle events: they may only be assigned an
1360 		 * even numbered counter that has a consecutive adjacent odd
1361 		 * numbered counter following it.
1362 		 */
1363 		for (i = 0; i < x86_pmu.num_counters - 1; i += 2)
1364 			even_ctr_mask |= 1 << i;
1365 
1366 		pair_constraint = (struct event_constraint)
1367 				    __EVENT_CONSTRAINT(0, even_ctr_mask, 0,
1368 				    x86_pmu.num_counters / 2, 0,
1369 				    PERF_X86_EVENT_PAIR);
1370 
1371 		x86_pmu.get_event_constraints = amd_get_event_constraints_f17h;
1372 		x86_pmu.put_event_constraints = amd_put_event_constraints_f17h;
1373 		x86_pmu.perf_ctr_pair_en = AMD_MERGE_EVENT_ENABLE;
1374 		x86_pmu.flags |= PMU_FL_PAIR;
1375 	}
1376 
1377 	/*
1378 	 * BRS requires special event constraints and flushing on ctxsw.
1379 	 */
1380 	if (boot_cpu_data.x86 >= 0x19 && !amd_brs_init()) {
1381 		x86_pmu.get_event_constraints = amd_get_event_constraints_f19h;
1382 		x86_pmu.sched_task = amd_pmu_brs_sched_task;
1383 		x86_pmu.limit_period = amd_pmu_limit_period;
1384 
1385 		static_call_update(amd_pmu_branch_hw_config, amd_brs_hw_config);
1386 		static_call_update(amd_pmu_branch_reset, amd_brs_reset);
1387 		static_call_update(amd_pmu_branch_add, amd_pmu_brs_add);
1388 		static_call_update(amd_pmu_branch_del, amd_pmu_brs_del);
1389 
1390 		/*
1391 		 * put_event_constraints callback same as Fam17h, set above
1392 		 */
1393 
1394 		/* branch sampling must be stopped when entering low power */
1395 		amd_brs_lopwr_init();
1396 	}
1397 
1398 	x86_pmu.attr_update = amd_attr_update;
1399 
1400 	pr_cont("core perfctr, ");
1401 	return 0;
1402 }
1403 
1404 __init int amd_pmu_init(void)
1405 {
1406 	int ret;
1407 
1408 	/* Performance-monitoring supported from K7 and later: */
1409 	if (boot_cpu_data.x86 < 6)
1410 		return -ENODEV;
1411 
1412 	x86_pmu = amd_pmu;
1413 
1414 	ret = amd_core_pmu_init();
1415 	if (ret)
1416 		return ret;
1417 
1418 	if (num_possible_cpus() == 1) {
1419 		/*
1420 		 * No point in allocating data structures to serialize
1421 		 * against other CPUs, when there is only the one CPU.
1422 		 */
1423 		x86_pmu.amd_nb_constraints = 0;
1424 	}
1425 
1426 	if (boot_cpu_data.x86 >= 0x17)
1427 		memcpy(hw_cache_event_ids, amd_hw_cache_event_ids_f17h, sizeof(hw_cache_event_ids));
1428 	else
1429 		memcpy(hw_cache_event_ids, amd_hw_cache_event_ids, sizeof(hw_cache_event_ids));
1430 
1431 	return 0;
1432 }
1433 
1434 static inline void amd_pmu_reload_virt(void)
1435 {
1436 	if (x86_pmu.version >= 2) {
1437 		/*
1438 		 * Clear global enable bits, reprogram the PERF_CTL
1439 		 * registers with updated perf_ctr_virt_mask and then
1440 		 * set global enable bits once again
1441 		 */
1442 		amd_pmu_v2_disable_all();
1443 		amd_pmu_enable_all(0);
1444 		amd_pmu_v2_enable_all(0);
1445 		return;
1446 	}
1447 
1448 	amd_pmu_disable_all();
1449 	amd_pmu_enable_all(0);
1450 }
1451 
1452 void amd_pmu_enable_virt(void)
1453 {
1454 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1455 
1456 	cpuc->perf_ctr_virt_mask = 0;
1457 
1458 	/* Reload all events */
1459 	amd_pmu_reload_virt();
1460 }
1461 EXPORT_SYMBOL_GPL(amd_pmu_enable_virt);
1462 
1463 void amd_pmu_disable_virt(void)
1464 {
1465 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1466 
1467 	/*
1468 	 * We only mask out the Host-only bit so that host-only counting works
1469 	 * when SVM is disabled. If someone sets up a guest-only counter when
1470 	 * SVM is disabled the Guest-only bits still gets set and the counter
1471 	 * will not count anything.
1472 	 */
1473 	cpuc->perf_ctr_virt_mask = AMD64_EVENTSEL_HOSTONLY;
1474 
1475 	/* Reload all events */
1476 	amd_pmu_reload_virt();
1477 }
1478 EXPORT_SYMBOL_GPL(amd_pmu_disable_virt);
1479