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