xref: /freebsd/sys/dev/hwpmc/hwpmc_amd.c (revision c2dee7786bf32cb66cedec226e42e79e06457c51)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2003-2008 Joseph Koshy
5  * Copyright (c) 2007 The FreeBSD Foundation
6  * All rights reserved.
7  *
8  * Portions of this software were developed by A. Joseph Koshy under
9  * sponsorship from the FreeBSD Foundation and Google, Inc.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /* Support for the AMD K8 and later processors */
34 
35 #include <sys/param.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mutex.h>
39 #include <sys/pcpu.h>
40 #include <sys/pmc.h>
41 #include <sys/pmckern.h>
42 #include <sys/smp.h>
43 #include <sys/systm.h>
44 
45 #include <machine/cpu.h>
46 #include <machine/cpufunc.h>
47 #include <machine/md_var.h>
48 #include <machine/specialreg.h>
49 
50 #define	OVERFLOW_WAIT_COUNT	50
51 
52 DPCPU_DEFINE_STATIC(uint32_t, nmi_counter);
53 
54 /* AMD K8 PMCs */
55 struct amd_descr {
56 	struct pmc_descr pm_descr;   /* "base class" */
57 	uint32_t	pm_evsel;    /* address of EVSEL register */
58 	uint32_t	pm_perfctr;  /* address of PERFCTR register */
59 	enum sub_class	pm_subclass; /* register subclass */
60 };
61 
62 static int amd_npmcs;
63 static struct amd_descr amd_pmcdesc[AMD_NPMCS_MAX];
64 
65 struct amd_event_code_map {
66 	enum pmc_event	pe_ev;	 /* enum value */
67 	uint16_t	pe_code; /* encoded event mask */
68 	uint8_t		pe_mask; /* bits allowed in unit mask */
69 };
70 
71 const struct amd_event_code_map amd_event_codes[] = {
72 	{ PMC_EV_K8_FP_DISPATCHED_FPU_OPS,		0x00, 0x3F },
73 	{ PMC_EV_K8_FP_CYCLES_WITH_NO_FPU_OPS_RETIRED,	0x01, 0x00 },
74 	{ PMC_EV_K8_FP_DISPATCHED_FPU_FAST_FLAG_OPS,	0x02, 0x00 },
75 
76 	{ PMC_EV_K8_LS_SEGMENT_REGISTER_LOAD, 		0x20, 0x7F },
77 	{ PMC_EV_K8_LS_MICROARCHITECTURAL_RESYNC_BY_SELF_MODIFYING_CODE,
78 	  						0x21, 0x00 },
79 	{ PMC_EV_K8_LS_MICROARCHITECTURAL_RESYNC_BY_SNOOP, 0x22, 0x00 },
80 	{ PMC_EV_K8_LS_BUFFER2_FULL,			0x23, 0x00 },
81 	{ PMC_EV_K8_LS_LOCKED_OPERATION,		0x24, 0x07 },
82 	{ PMC_EV_K8_LS_MICROARCHITECTURAL_LATE_CANCEL,	0x25, 0x00 },
83 	{ PMC_EV_K8_LS_RETIRED_CFLUSH_INSTRUCTIONS,	0x26, 0x00 },
84 	{ PMC_EV_K8_LS_RETIRED_CPUID_INSTRUCTIONS,	0x27, 0x00 },
85 
86 	{ PMC_EV_K8_DC_ACCESS,				0x40, 0x00 },
87 	{ PMC_EV_K8_DC_MISS,				0x41, 0x00 },
88 	{ PMC_EV_K8_DC_REFILL_FROM_L2,			0x42, 0x1F },
89 	{ PMC_EV_K8_DC_REFILL_FROM_SYSTEM,		0x43, 0x1F },
90 	{ PMC_EV_K8_DC_COPYBACK,			0x44, 0x1F },
91 	{ PMC_EV_K8_DC_L1_DTLB_MISS_AND_L2_DTLB_HIT,	0x45, 0x00 },
92 	{ PMC_EV_K8_DC_L1_DTLB_MISS_AND_L2_DTLB_MISS,	0x46, 0x00 },
93 	{ PMC_EV_K8_DC_MISALIGNED_DATA_REFERENCE,	0x47, 0x00 },
94 	{ PMC_EV_K8_DC_MICROARCHITECTURAL_LATE_CANCEL,	0x48, 0x00 },
95 	{ PMC_EV_K8_DC_MICROARCHITECTURAL_EARLY_CANCEL, 0x49, 0x00 },
96 	{ PMC_EV_K8_DC_ONE_BIT_ECC_ERROR,		0x4A, 0x03 },
97 	{ PMC_EV_K8_DC_DISPATCHED_PREFETCH_INSTRUCTIONS, 0x4B, 0x07 },
98 	{ PMC_EV_K8_DC_DCACHE_ACCESSES_BY_LOCKS,	0x4C, 0x03 },
99 
100 	{ PMC_EV_K8_BU_CPU_CLK_UNHALTED,		0x76, 0x00 },
101 	{ PMC_EV_K8_BU_INTERNAL_L2_REQUEST,		0x7D, 0x1F },
102 	{ PMC_EV_K8_BU_FILL_REQUEST_L2_MISS,		0x7E, 0x07 },
103 	{ PMC_EV_K8_BU_FILL_INTO_L2,			0x7F, 0x03 },
104 
105 	{ PMC_EV_K8_IC_FETCH,				0x80, 0x00 },
106 	{ PMC_EV_K8_IC_MISS,				0x81, 0x00 },
107 	{ PMC_EV_K8_IC_REFILL_FROM_L2,			0x82, 0x00 },
108 	{ PMC_EV_K8_IC_REFILL_FROM_SYSTEM,		0x83, 0x00 },
109 	{ PMC_EV_K8_IC_L1_ITLB_MISS_AND_L2_ITLB_HIT,	0x84, 0x00 },
110 	{ PMC_EV_K8_IC_L1_ITLB_MISS_AND_L2_ITLB_MISS,	0x85, 0x00 },
111 	{ PMC_EV_K8_IC_MICROARCHITECTURAL_RESYNC_BY_SNOOP, 0x86, 0x00 },
112 	{ PMC_EV_K8_IC_INSTRUCTION_FETCH_STALL,		0x87, 0x00 },
113 	{ PMC_EV_K8_IC_RETURN_STACK_HIT,		0x88, 0x00 },
114 	{ PMC_EV_K8_IC_RETURN_STACK_OVERFLOW,		0x89, 0x00 },
115 
116 	{ PMC_EV_K8_FR_RETIRED_X86_INSTRUCTIONS,	0xC0, 0x00 },
117 	{ PMC_EV_K8_FR_RETIRED_UOPS,			0xC1, 0x00 },
118 	{ PMC_EV_K8_FR_RETIRED_BRANCHES,		0xC2, 0x00 },
119 	{ PMC_EV_K8_FR_RETIRED_BRANCHES_MISPREDICTED,	0xC3, 0x00 },
120 	{ PMC_EV_K8_FR_RETIRED_TAKEN_BRANCHES,		0xC4, 0x00 },
121 	{ PMC_EV_K8_FR_RETIRED_TAKEN_BRANCHES_MISPREDICTED, 0xC5, 0x00 },
122 	{ PMC_EV_K8_FR_RETIRED_FAR_CONTROL_TRANSFERS,	0xC6, 0x00 },
123 	{ PMC_EV_K8_FR_RETIRED_RESYNCS,			0xC7, 0x00 },
124 	{ PMC_EV_K8_FR_RETIRED_NEAR_RETURNS,		0xC8, 0x00 },
125 	{ PMC_EV_K8_FR_RETIRED_NEAR_RETURNS_MISPREDICTED, 0xC9, 0x00 },
126 	{ PMC_EV_K8_FR_RETIRED_TAKEN_BRANCHES_MISPREDICTED_BY_ADDR_MISCOMPARE,
127 							0xCA, 0x00 },
128 	{ PMC_EV_K8_FR_RETIRED_FPU_INSTRUCTIONS,	0xCB, 0x0F },
129 	{ PMC_EV_K8_FR_RETIRED_FASTPATH_DOUBLE_OP_INSTRUCTIONS,
130 							0xCC, 0x07 },
131 	{ PMC_EV_K8_FR_INTERRUPTS_MASKED_CYCLES,	0xCD, 0x00 },
132 	{ PMC_EV_K8_FR_INTERRUPTS_MASKED_WHILE_PENDING_CYCLES, 0xCE, 0x00 },
133 	{ PMC_EV_K8_FR_TAKEN_HARDWARE_INTERRUPTS,	0xCF, 0x00 },
134 
135 	{ PMC_EV_K8_FR_DECODER_EMPTY,			0xD0, 0x00 },
136 	{ PMC_EV_K8_FR_DISPATCH_STALLS,			0xD1, 0x00 },
137 	{ PMC_EV_K8_FR_DISPATCH_STALL_FROM_BRANCH_ABORT_TO_RETIRE,
138 							0xD2, 0x00 },
139 	{ PMC_EV_K8_FR_DISPATCH_STALL_FOR_SERIALIZATION, 0xD3, 0x00 },
140 	{ PMC_EV_K8_FR_DISPATCH_STALL_FOR_SEGMENT_LOAD,	0xD4, 0x00 },
141 	{ PMC_EV_K8_FR_DISPATCH_STALL_WHEN_REORDER_BUFFER_IS_FULL,
142 							0xD5, 0x00 },
143 	{ PMC_EV_K8_FR_DISPATCH_STALL_WHEN_RESERVATION_STATIONS_ARE_FULL,
144 							0xD6, 0x00 },
145 	{ PMC_EV_K8_FR_DISPATCH_STALL_WHEN_FPU_IS_FULL,	0xD7, 0x00 },
146 	{ PMC_EV_K8_FR_DISPATCH_STALL_WHEN_LS_IS_FULL,	0xD8, 0x00 },
147 	{ PMC_EV_K8_FR_DISPATCH_STALL_WHEN_WAITING_FOR_ALL_TO_BE_QUIET,
148 							0xD9, 0x00 },
149 	{ PMC_EV_K8_FR_DISPATCH_STALL_WHEN_FAR_XFER_OR_RESYNC_BRANCH_PENDING,
150 							0xDA, 0x00 },
151 	{ PMC_EV_K8_FR_FPU_EXCEPTIONS,			0xDB, 0x0F },
152 	{ PMC_EV_K8_FR_NUMBER_OF_BREAKPOINTS_FOR_DR0,	0xDC, 0x00 },
153 	{ PMC_EV_K8_FR_NUMBER_OF_BREAKPOINTS_FOR_DR1,	0xDD, 0x00 },
154 	{ PMC_EV_K8_FR_NUMBER_OF_BREAKPOINTS_FOR_DR2,	0xDE, 0x00 },
155 	{ PMC_EV_K8_FR_NUMBER_OF_BREAKPOINTS_FOR_DR3,	0xDF, 0x00 },
156 
157 	{ PMC_EV_K8_NB_MEMORY_CONTROLLER_PAGE_ACCESS_EVENT, 0xE0, 0x7 },
158 	{ PMC_EV_K8_NB_MEMORY_CONTROLLER_PAGE_TABLE_OVERFLOW, 0xE1, 0x00 },
159 	{ PMC_EV_K8_NB_MEMORY_CONTROLLER_DRAM_COMMAND_SLOTS_MISSED,
160 							0xE2, 0x00 },
161 	{ PMC_EV_K8_NB_MEMORY_CONTROLLER_TURNAROUND,	0xE3, 0x07 },
162 	{ PMC_EV_K8_NB_MEMORY_CONTROLLER_BYPASS_SATURATION, 0xE4, 0x0F },
163 	{ PMC_EV_K8_NB_SIZED_COMMANDS,			0xEB, 0x7F },
164 	{ PMC_EV_K8_NB_PROBE_RESULT,			0xEC, 0x0F },
165 	{ PMC_EV_K8_NB_HT_BUS0_BANDWIDTH,		0xF6, 0x0F },
166 	{ PMC_EV_K8_NB_HT_BUS1_BANDWIDTH,		0xF7, 0x0F },
167 	{ PMC_EV_K8_NB_HT_BUS2_BANDWIDTH,		0xF8, 0x0F }
168 
169 };
170 
171 const int amd_event_codes_size = nitems(amd_event_codes);
172 
173 /*
174  * Per-processor information
175  */
176 struct amd_cpu {
177 	struct pmc_hw	pc_amdpmcs[AMD_NPMCS_MAX];
178 };
179 static struct amd_cpu **amd_pcpu;
180 
181 /*
182  * Read a PMC value from the MSR.
183  */
184 static int
185 amd_read_pmc(int cpu, int ri, struct pmc *pm, pmc_value_t *v)
186 {
187 	const struct amd_descr *pd;
188 	pmc_value_t tmp;
189 	enum pmc_mode mode;
190 
191 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
192 	    ("[amd,%d] illegal CPU value %d", __LINE__, cpu));
193 	KASSERT(ri >= 0 && ri < amd_npmcs,
194 	    ("[amd,%d] illegal row-index %d", __LINE__, ri));
195 	KASSERT(amd_pcpu[cpu],
196 	    ("[amd,%d] null per-cpu, cpu %d", __LINE__, cpu));
197 
198 	pd = &amd_pmcdesc[ri];
199 	mode = PMC_TO_MODE(pm);
200 
201 	PMCDBG2(MDP, REA, 1, "amd-read id=%d class=%d", ri,
202 	    pd->pm_descr.pd_class);
203 
204 	tmp = rdmsr(pd->pm_perfctr); /* RDMSR serializes */
205 	PMCDBG2(MDP, REA, 2, "amd-read (pre-munge) id=%d -> %jd", ri, tmp);
206 	if (PMC_IS_SAMPLING_MODE(mode)) {
207 		/*
208 		 * Clamp value to 0 if the counter just overflowed,
209 		 * otherwise the returned reload count would wrap to a
210 		 * huge value.
211 		 */
212 		if ((tmp & (1ULL << 47)) == 0)
213 			tmp = 0;
214 		else {
215 			/* Sign extend 48 bit value to 64 bits. */
216 			tmp = (pmc_value_t) ((int64_t)(tmp << 16) >> 16);
217 			tmp = AMD_PERFCTR_VALUE_TO_RELOAD_COUNT(tmp);
218 		}
219 	}
220 	*v = tmp;
221 
222 	PMCDBG2(MDP, REA, 2, "amd-read (post-munge) id=%d -> %jd", ri, *v);
223 
224 	return (0);
225 }
226 
227 /*
228  * Write a PMC MSR.
229  */
230 static int
231 amd_write_pmc(int cpu, int ri, struct pmc *pm, pmc_value_t v)
232 {
233 	const struct amd_descr *pd;
234 	enum pmc_mode mode;
235 
236 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
237 	    ("[amd,%d] illegal CPU value %d", __LINE__, cpu));
238 	KASSERT(ri >= 0 && ri < amd_npmcs,
239 	    ("[amd,%d] illegal row-index %d", __LINE__, ri));
240 
241 	pd = &amd_pmcdesc[ri];
242 	mode = PMC_TO_MODE(pm);
243 
244 	/* use 2's complement of the count for sampling mode PMCs */
245 	if (PMC_IS_SAMPLING_MODE(mode))
246 		v = AMD_RELOAD_COUNT_TO_PERFCTR_VALUE(v);
247 
248 	PMCDBG3(MDP, WRI, 1, "amd-write cpu=%d ri=%d v=%jx", cpu, ri, v);
249 
250 	/* write the PMC value */
251 	wrmsr(pd->pm_perfctr, v);
252 	return (0);
253 }
254 
255 /*
256  * Configure hardware PMC according to the configuration recorded in 'pm'.
257  */
258 static int
259 amd_config_pmc(int cpu, int ri, struct pmc *pm)
260 {
261 	struct pmc_hw *phw;
262 
263 	PMCDBG3(MDP, CFG, 1, "cpu=%d ri=%d pm=%p", cpu, ri, pm);
264 
265 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
266 	    ("[amd,%d] illegal CPU value %d", __LINE__, cpu));
267 	KASSERT(ri >= 0 && ri < amd_npmcs,
268 	    ("[amd,%d] illegal row-index %d", __LINE__, ri));
269 
270 	phw = &amd_pcpu[cpu]->pc_amdpmcs[ri];
271 
272 	KASSERT(pm == NULL || phw->phw_pmc == NULL,
273 	    ("[amd,%d] pm=%p phw->pm=%p hwpmc not unconfigured",
274 		__LINE__, pm, phw->phw_pmc));
275 
276 	phw->phw_pmc = pm;
277 	return (0);
278 }
279 
280 /*
281  * Retrieve a configured PMC pointer from hardware state.
282  */
283 static int
284 amd_get_config(int cpu, int ri, struct pmc **ppm)
285 {
286 	*ppm = amd_pcpu[cpu]->pc_amdpmcs[ri].phw_pmc;
287 	return (0);
288 }
289 
290 /*
291  * Machine-dependent actions taken during the context switch in of a
292  * thread.
293  */
294 static int
295 amd_switch_in(struct pmc_cpu *pc __pmcdbg_used, struct pmc_process *pp)
296 {
297 	PMCDBG3(MDP, SWI, 1, "pc=%p pp=%p enable-msr=%d", pc, pp,
298 	    (pp->pp_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0);
299 
300 	/* enable the RDPMC instruction if needed */
301 	if (pp->pp_flags & PMC_PP_ENABLE_MSR_ACCESS)
302 		load_cr4(rcr4() | CR4_PCE);
303 
304 	return (0);
305 }
306 
307 /*
308  * Machine-dependent actions taken during the context switch out of a
309  * thread.
310  */
311 static int
312 amd_switch_out(struct pmc_cpu *pc __pmcdbg_used,
313     struct pmc_process *pp __pmcdbg_used)
314 {
315 	PMCDBG3(MDP, SWO, 1, "pc=%p pp=%p enable-msr=%d", pc, pp, pp ?
316 	    (pp->pp_flags & PMC_PP_ENABLE_MSR_ACCESS) == 1 : 0);
317 
318 	/* always turn off the RDPMC instruction */
319 	load_cr4(rcr4() & ~CR4_PCE);
320 
321 	return (0);
322 }
323 
324 /*
325  * Check if a given PMC allocation is feasible.
326  */
327 static int
328 amd_allocate_pmc(int cpu __unused, int ri, struct pmc *pm,
329     const struct pmc_op_pmcallocate *a)
330 {
331 	const struct pmc_descr *pd;
332 	uint64_t allowed_unitmask, caps, config, unitmask;
333 	enum pmc_event pe;
334 	int i;
335 
336 	KASSERT(ri >= 0 && ri < amd_npmcs,
337 	    ("[amd,%d] illegal row index %d", __LINE__, ri));
338 
339 	pd = &amd_pmcdesc[ri].pm_descr;
340 
341 	/* check class match */
342 	if (pd->pd_class != a->pm_class)
343 		return (EINVAL);
344 
345 	if ((a->pm_flags & PMC_F_EV_PMU) == 0)
346 		return (EINVAL);
347 
348 	caps = pm->pm_caps;
349 
350 	if (((caps & PMC_CAP_PRECISE) != 0) &&
351 	    ((pd->pd_caps & PMC_CAP_PRECISE) == 0))
352 		return (EINVAL);
353 
354 	PMCDBG2(MDP, ALL, 1,"amd-allocate ri=%d caps=0x%x", ri, caps);
355 
356 	/* Validate sub-class. */
357 	if (amd_pmcdesc[ri].pm_subclass != a->pm_md.pm_amd.pm_amd_sub_class)
358 		return (EINVAL);
359 
360 	if (strlen(pmc_cpuid) != 0) {
361 		pm->pm_md.pm_amd.pm_amd_evsel = a->pm_md.pm_amd.pm_amd_config;
362 		PMCDBG2(MDP, ALL, 2,"amd-allocate ri=%d -> config=0x%x", ri,
363 		    a->pm_md.pm_amd.pm_amd_config);
364 		return (0);
365 	}
366 
367 	/*
368 	 * Everything below this is for supporting older processors.
369 	 */
370 	pe = a->pm_ev;
371 
372 	/* map ev to the correct event mask code */
373 	config = allowed_unitmask = 0;
374 	for (i = 0; i < amd_event_codes_size; i++) {
375 		if (amd_event_codes[i].pe_ev == pe) {
376 			config =
377 			    AMD_PMC_TO_EVENTMASK(amd_event_codes[i].pe_code);
378 			allowed_unitmask =
379 			    AMD_PMC_TO_UNITMASK(amd_event_codes[i].pe_mask);
380 			break;
381 		}
382 	}
383 	if (i == amd_event_codes_size)
384 		return (EINVAL);
385 
386 	unitmask = a->pm_md.pm_amd.pm_amd_config & AMD_PMC_UNITMASK;
387 	if ((unitmask & ~allowed_unitmask) != 0) /* disallow reserved bits */
388 		return (EINVAL);
389 
390 	if (unitmask && (caps & PMC_CAP_QUALIFIER) != 0)
391 		config |= unitmask;
392 
393 	if ((caps & PMC_CAP_THRESHOLD) != 0)
394 		config |= a->pm_md.pm_amd.pm_amd_config & AMD_PMC_COUNTERMASK;
395 
396 	/* Set at least one of the 'usr' or 'os' caps. */
397 	if ((caps & PMC_CAP_USER) != 0)
398 		config |= AMD_PMC_USR;
399 	if ((caps & PMC_CAP_SYSTEM) != 0)
400 		config |= AMD_PMC_OS;
401 	if ((caps & (PMC_CAP_USER | PMC_CAP_SYSTEM)) == 0)
402 		config |= (AMD_PMC_USR|AMD_PMC_OS);
403 
404 	if ((caps & PMC_CAP_EDGE) != 0)
405 		config |= AMD_PMC_EDGE;
406 	if ((caps & PMC_CAP_INVERT) != 0)
407 		config |= AMD_PMC_INVERT;
408 	if ((caps & PMC_CAP_INTERRUPT) != 0)
409 		config |= AMD_PMC_INT;
410 
411 	pm->pm_md.pm_amd.pm_amd_evsel = config; /* save config value */
412 
413 	PMCDBG2(MDP, ALL, 2, "amd-allocate ri=%d -> config=0x%x", ri, config);
414 
415 	return (0);
416 }
417 
418 /*
419  * Release machine dependent state associated with a PMC.  This is a
420  * no-op on this architecture.
421  */
422 static int
423 amd_release_pmc(int cpu, int ri, struct pmc *pmc __unused)
424 {
425 	struct pmc_hw *phw __diagused;
426 
427 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
428 	    ("[amd,%d] illegal CPU value %d", __LINE__, cpu));
429 	KASSERT(ri >= 0 && ri < amd_npmcs,
430 	    ("[amd,%d] illegal row-index %d", __LINE__, ri));
431 
432 	phw = &amd_pcpu[cpu]->pc_amdpmcs[ri];
433 
434 	KASSERT(phw->phw_pmc == NULL,
435 	    ("[amd,%d] PHW pmc %p non-NULL", __LINE__, phw->phw_pmc));
436 
437 	return (0);
438 }
439 
440 /*
441  * Start a PMC.
442  */
443 static int
444 amd_start_pmc(int cpu __diagused, int ri, struct pmc *pm)
445 {
446 	const struct amd_descr *pd;
447 	uint64_t config;
448 
449 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
450 	    ("[amd,%d] illegal CPU value %d", __LINE__, cpu));
451 	KASSERT(ri >= 0 && ri < amd_npmcs,
452 	    ("[amd,%d] illegal row-index %d", __LINE__, ri));
453 
454 	pd = &amd_pmcdesc[ri];
455 
456 	PMCDBG2(MDP, STA, 1, "amd-start cpu=%d ri=%d", cpu, ri);
457 
458 	/*
459 	 * Triggered by DF counters because all DF MSRs are shared.  We need to
460 	 * change the code to honor the per-package flag in the JSON event
461 	 * definitions.
462 	 */
463 	KASSERT(AMD_PMC_IS_STOPPED(pd->pm_evsel),
464 	    ("[amd,%d] pmc%d,cpu%d: Starting active PMC \"%s\"", __LINE__,
465 	    ri, cpu, pd->pm_descr.pd_name));
466 
467 	/* turn on the PMC ENABLE bit */
468 	config = pm->pm_md.pm_amd.pm_amd_evsel | AMD_PMC_ENABLE;
469 
470 	PMCDBG1(MDP, STA, 2, "amd-start config=0x%x", config);
471 
472 	wrmsr(pd->pm_evsel, config);
473 	return (0);
474 }
475 
476 /*
477  * Stop a PMC.
478  */
479 static int
480 amd_stop_pmc(int cpu __diagused, int ri, struct pmc *pm)
481 {
482 	const struct amd_descr *pd;
483 	uint64_t config;
484 	int i;
485 
486 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
487 	    ("[amd,%d] illegal CPU value %d", __LINE__, cpu));
488 	KASSERT(ri >= 0 && ri < amd_npmcs,
489 	    ("[amd,%d] illegal row-index %d", __LINE__, ri));
490 
491 	pd = &amd_pmcdesc[ri];
492 
493 	KASSERT(!AMD_PMC_IS_STOPPED(pd->pm_evsel),
494 	    ("[amd,%d] PMC%d, CPU%d \"%s\" already stopped",
495 		__LINE__, ri, cpu, pd->pm_descr.pd_name));
496 
497 	PMCDBG1(MDP, STO, 1, "amd-stop ri=%d", ri);
498 
499 	/* turn off the PMC ENABLE bit */
500 	config = pm->pm_md.pm_amd.pm_amd_evsel & ~AMD_PMC_ENABLE;
501 	wrmsr(pd->pm_evsel, config);
502 
503 	/*
504 	 * Due to NMI latency on newer AMD processors
505 	 * NMI interrupts are ignored, which leads to
506 	 * panic or messages based on kernel configuration
507 	 */
508 
509 	/* Wait for the count to be reset */
510 	for (i = 0; i < OVERFLOW_WAIT_COUNT; i++) {
511 		if (rdmsr(pd->pm_perfctr) & (1 << (pd->pm_descr.pd_width - 1)))
512 			break;
513 
514 		DELAY(1);
515 	}
516 
517 	return (0);
518 }
519 
520 /*
521  * Interrupt handler.  This function needs to return '1' if the
522  * interrupt was this CPU's PMCs or '0' otherwise.  It is not allowed
523  * to sleep or do anything a 'fast' interrupt handler is not allowed
524  * to do.
525  */
526 static int
527 amd_intr(struct trapframe *tf)
528 {
529 	struct amd_cpu *pac;
530 	struct pmc *pm;
531 	pmc_value_t v;
532 	uint64_t config, evsel, perfctr;
533 	uint32_t active = 0, count = 0;
534 	int i, error, retval, cpu;
535 
536 	cpu = curcpu;
537 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
538 	    ("[amd,%d] out of range CPU %d", __LINE__, cpu));
539 
540 	PMCDBG3(MDP, INT, 1, "cpu=%d tf=%p um=%d", cpu, tf, TRAPF_USERMODE(tf));
541 
542 	retval = 0;
543 
544 	pac = amd_pcpu[cpu];
545 
546 	retval = pmc_ibs_intr(tf);
547 	if (retval)
548 		goto done;
549 
550 	/*
551 	 * look for all PMCs that have interrupted:
552 	 * - look for a running, sampling PMC which has overflowed
553 	 *   and which has a valid 'struct pmc' association
554 	 *
555 	 * If found, we call a helper to process the interrupt.
556 	 *
557 	 * PMCs interrupting at the same time are collapsed into
558 	 * a single interrupt. Check all the valid pmcs for
559 	 * overflow.
560 	 */
561 	for (i = 0; i < amd_npmcs; i++) {
562 		if (amd_pmcdesc[i].pm_subclass != PMC_AMD_SUB_CLASS_CORE)
563 		    break;
564 
565 		if ((pm = pac->pc_amdpmcs[i].phw_pmc) == NULL ||
566 		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
567 			continue;
568 		}
569 
570 		/* Consider pmc with valid handle as active */
571 		active++;
572 
573 		if (!AMD_PMC_HAS_OVERFLOWED(i))
574 			continue;
575 
576 		retval = 1;	/* Found an interrupting PMC. */
577 
578 		if (pm->pm_state != PMC_STATE_RUNNING)
579 			continue;
580 
581 		/* Stop the PMC, reload count. */
582 		evsel   = amd_pmcdesc[i].pm_evsel;
583 		perfctr = amd_pmcdesc[i].pm_perfctr;
584 		v       = pm->pm_sc.pm_reloadcount;
585 		config  = rdmsr(evsel);
586 
587 		KASSERT((config & ~AMD_PMC_ENABLE) ==
588 		    (pm->pm_md.pm_amd.pm_amd_evsel & ~AMD_PMC_ENABLE),
589 		    ("[amd,%d] config mismatch reg=0x%jx pm=0x%jx", __LINE__,
590 			 (uintmax_t)config, (uintmax_t)pm->pm_md.pm_amd.pm_amd_evsel));
591 
592 		wrmsr(evsel, config & ~AMD_PMC_ENABLE);
593 		wrmsr(perfctr, AMD_RELOAD_COUNT_TO_PERFCTR_VALUE(v));
594 
595 		/* Restart the counter if logging succeeded. */
596 		error = pmc_process_interrupt(PMC_HR, pm, tf);
597 		if (error == 0)
598 			wrmsr(evsel, config);
599 	}
600 
601 	/*
602 	 * Due to NMI latency, there can be a scenario in which
603 	 * multiple pmcs gets serviced in an earlier NMI and we
604 	 * do not find an overflow in the subsequent NMI.
605 	 *
606 	 * For such cases we keep a per-cpu count of active NMIs
607 	 * and compare it with min(active pmcs, 2) to determine
608 	 * if this NMI was for a pmc overflow which was serviced
609 	 * in an earlier request or should be ignored.
610 	 */
611 	if (retval) {
612 		DPCPU_SET(nmi_counter, min(2, active));
613 	} else {
614 		if ((count = DPCPU_GET(nmi_counter))) {
615 			retval = 1;
616 			DPCPU_SET(nmi_counter, --count);
617 		}
618 	}
619 
620 done:
621 	if (retval)
622 		counter_u64_add(pmc_stats.pm_intr_processed, 1);
623 	else
624 		counter_u64_add(pmc_stats.pm_intr_ignored, 1);
625 
626 	PMCDBG1(MDP, INT, 2, "retval=%d", retval);
627 	return (retval);
628 }
629 
630 /*
631  * Describe a PMC.
632  */
633 static int
634 amd_describe(int cpu, int ri, struct pmc_info *pi, struct pmc **ppmc)
635 {
636 	const struct amd_descr *pd;
637 	struct pmc_hw *phw;
638 
639 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
640 	    ("[amd,%d] illegal CPU %d", __LINE__, cpu));
641 	KASSERT(ri >= 0 && ri < amd_npmcs,
642 	    ("[amd,%d] row-index %d out of range", __LINE__, ri));
643 
644 	phw = &amd_pcpu[cpu]->pc_amdpmcs[ri];
645 	pd  = &amd_pmcdesc[ri];
646 
647 	strlcpy(pi->pm_name, pd->pm_descr.pd_name, sizeof(pi->pm_name));
648 	pi->pm_class = pd->pm_descr.pd_class;
649 
650 	if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) != 0) {
651 		pi->pm_enabled = true;
652 		*ppmc          = phw->phw_pmc;
653 	} else {
654 		pi->pm_enabled = false;
655 		*ppmc          = NULL;
656 	}
657 
658 	return (0);
659 }
660 
661 /*
662  * Return the MSR address of the given PMC.
663  */
664 static int
665 amd_get_msr(int ri, uint32_t *msr)
666 {
667 	KASSERT(ri >= 0 && ri < amd_npmcs,
668 	    ("[amd,%d] ri %d out of range", __LINE__, ri));
669 
670 	*msr = amd_pmcdesc[ri].pm_perfctr - AMD_PMC_PERFCTR_0;
671 	return (0);
672 }
673 
674 /*
675  * Processor-dependent initialization.
676  */
677 static int
678 amd_pcpu_init(struct pmc_mdep *md, int cpu)
679 {
680 	struct amd_cpu *pac;
681 	struct pmc_cpu *pc;
682 	struct pmc_hw  *phw;
683 	int first_ri, n;
684 
685 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
686 	    ("[amd,%d] insane cpu number %d", __LINE__, cpu));
687 
688 	PMCDBG1(MDP, INI, 1, "amd-init cpu=%d", cpu);
689 
690 	amd_pcpu[cpu] = pac = malloc(sizeof(struct amd_cpu), M_PMC,
691 	    M_WAITOK | M_ZERO);
692 
693 	/*
694 	 * Set the content of the hardware descriptors to a known
695 	 * state and initialize pointers in the MI per-cpu descriptor.
696 	 */
697 	pc = pmc_pcpu[cpu];
698 	first_ri = md->pmd_classdep[PMC_MDEP_CLASS_INDEX_K8].pcd_ri;
699 
700 	KASSERT(pc != NULL, ("[amd,%d] NULL per-cpu pointer", __LINE__));
701 
702 	for (n = 0, phw = pac->pc_amdpmcs; n < amd_npmcs; n++, phw++) {
703 		phw->phw_state = PMC_PHW_FLAG_IS_ENABLED |
704 		    PMC_PHW_CPU_TO_STATE(cpu) | PMC_PHW_INDEX_TO_STATE(n);
705 		phw->phw_pmc = NULL;
706 		pc->pc_hwpmcs[n + first_ri] = phw;
707 	}
708 
709 	return (0);
710 }
711 
712 /*
713  * Processor-dependent cleanup prior to the KLD being unloaded.
714  */
715 static int
716 amd_pcpu_fini(struct pmc_mdep *md, int cpu)
717 {
718 	struct amd_cpu *pac;
719 	struct pmc_cpu *pc;
720 	int first_ri, i;
721 
722 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
723 	    ("[amd,%d] insane cpu number (%d)", __LINE__, cpu));
724 
725 	PMCDBG1(MDP, INI, 1, "amd-cleanup cpu=%d", cpu);
726 
727 	/*
728 	 * Next, free up allocated space.
729 	 */
730 	if ((pac = amd_pcpu[cpu]) == NULL)
731 		return (0);
732 
733 	amd_pcpu[cpu] = NULL;
734 
735 #ifdef	HWPMC_DEBUG
736 	for (i = 0; i < AMD_NPMCS_K8; i++) {
737 		KASSERT(pac->pc_amdpmcs[i].phw_pmc == NULL,
738 		    ("[amd,%d] CPU%d/PMC%d in use", __LINE__, cpu, i));
739 		KASSERT(AMD_PMC_IS_STOPPED(AMD_PMC_EVSEL_0 + i),
740 		    ("[amd,%d] CPU%d/PMC%d not stopped", __LINE__, cpu, i));
741 	}
742 #endif
743 
744 	pc = pmc_pcpu[cpu];
745 	KASSERT(pc != NULL, ("[amd,%d] NULL per-cpu state", __LINE__));
746 
747 	first_ri = md->pmd_classdep[PMC_MDEP_CLASS_INDEX_K8].pcd_ri;
748 
749 	/*
750 	 * Reset pointers in the MI 'per-cpu' state.
751 	 */
752 	for (i = 0; i < amd_npmcs; i++)
753 		pc->pc_hwpmcs[i + first_ri] = NULL;
754 
755 	free(pac, M_PMC);
756 	return (0);
757 }
758 
759 /*
760  * Initialize ourselves.
761  */
762 struct pmc_mdep *
763 pmc_amd_initialize(void)
764 {
765 	struct pmc_classdep *pcd;
766 	struct pmc_mdep *pmc_mdep;
767 	enum pmc_cputype cputype;
768 	int error, i, ncpus, nclasses;
769 	int family, model, stepping;
770 	int amd_core_npmcs, amd_l3_npmcs, amd_df_npmcs;
771 	struct amd_descr *d;
772 
773 	/*
774 	 * The presence of hardware performance counters on the AMD
775 	 * Athlon, Duron or later processors, is _not_ indicated by
776 	 * any of the processor feature flags set by the 'CPUID'
777 	 * instruction, so we only check the 'instruction family'
778 	 * field returned by CPUID for instruction family >= 6.
779 	 */
780 
781 	family = CPUID_TO_FAMILY(cpu_id);
782 	model = CPUID_TO_MODEL(cpu_id);
783 	stepping = CPUID_TO_STEPPING(cpu_id);
784 
785 	if (family == 0x18)
786 		snprintf(pmc_cpuid, sizeof(pmc_cpuid), "HygonGenuine-%d-%02X-%X",
787 		    family, model, stepping);
788 	else
789 		snprintf(pmc_cpuid, sizeof(pmc_cpuid), "AuthenticAMD-%d-%02X-%X",
790 		    family, model, stepping);
791 
792 	switch (cpu_id & 0xF00) {
793 	case 0xF00:		/* Athlon64/Opteron processor */
794 		cputype = PMC_CPU_AMD_K8;
795 		break;
796 	default:
797 		printf("pmc: Unknown AMD CPU %x %d-%d.\n", cpu_id, family,
798 		    model);
799 		return (NULL);
800 	}
801 
802 	/*
803 	 * From PPR for AMD Family 1Ah, a new cpuid leaf specifies the maximum
804 	 * number of PMCs of each type.  If we do not have that leaf, we use
805 	 * the prior default values that are only valid if we have the feature
806 	 * bit enabled in CPU.
807 	 */
808 	if ((amd_feature2 & AMDID2_PCXC) != 0) {
809 		amd_core_npmcs = AMD_PMC_CORE_DEFAULT;
810 	} else {
811 		amd_core_npmcs = AMD_NPMCS_K8;
812 	}
813 	amd_l3_npmcs = AMD_PMC_L3_DEFAULT;
814 	amd_df_npmcs = AMD_PMC_DF_DEFAULT;
815 
816 	if (cpu_exthigh >= CPUID_EXTPERFMON) {
817 		u_int regs[4];
818 		do_cpuid(CPUID_EXTPERFMON, regs);
819 		if (regs[1] != 0) {
820 			amd_core_npmcs = EXTPERFMON_CORE_PMCS(regs[1]);
821 			amd_df_npmcs = EXTPERFMON_DF_PMCS(regs[1]);
822 		}
823 	}
824 
825 	/* Enable the newer core counters */
826 	for (i = 0; i < amd_core_npmcs; i++) {
827 		d = &amd_pmcdesc[i];
828 		snprintf(d->pm_descr.pd_name, PMC_NAME_MAX,
829 		    "K8-%d", i);
830 		d->pm_descr.pd_class = PMC_CLASS_K8;
831 		d->pm_descr.pd_caps = AMD_PMC_CAPS;
832 		/*
833 		 * Zen 5 can precisely count retire events.
834 		 *
835 		 * Refer to PPR Vol 1 for AMD Family 1Ah Model 02h C1 57238
836 		 * Rev. 0.24 September 29, 2024.
837 		 */
838 		if ((family >= 0x1a) && (i == 2))
839 			d->pm_descr.pd_caps |= PMC_CAP_PRECISE;
840 		d->pm_descr.pd_width = 48;
841 		if ((amd_feature2 & AMDID2_PCXC) != 0) {
842 			d->pm_evsel = AMD_PMC_CORE_BASE + 2 * i;
843 			d->pm_perfctr = AMD_PMC_CORE_BASE + 2 * i + 1;
844 		} else {
845 			d->pm_evsel = AMD_PMC_EVSEL_0 + i;
846 			d->pm_perfctr = AMD_PMC_PERFCTR_0 + i;
847 		}
848 		d->pm_subclass = PMC_AMD_SUB_CLASS_CORE;
849 	}
850 	amd_npmcs = amd_core_npmcs;
851 
852 	if ((amd_feature2 & AMDID2_PTSCEL2I) != 0) {
853 		/* Enable the LLC/L3 counters */
854 		for (i = 0; i < amd_l3_npmcs; i++) {
855 			d = &amd_pmcdesc[amd_npmcs + i];
856 			snprintf(d->pm_descr.pd_name, PMC_NAME_MAX,
857 			    "K8-L3-%d", i);
858 			d->pm_descr.pd_class = PMC_CLASS_K8;
859 			d->pm_descr.pd_caps = AMD_PMC_L3_CAPS;
860 			d->pm_descr.pd_width = 48;
861 			d->pm_evsel = AMD_PMC_L3_BASE + 2 * i;
862 			d->pm_perfctr = AMD_PMC_L3_BASE + 2 * i + 1;
863 			d->pm_subclass = PMC_AMD_SUB_CLASS_L3_CACHE;
864 		}
865 		amd_npmcs += amd_l3_npmcs;
866 	}
867 
868 	if ((amd_feature2 & AMDID2_PNXC) != 0) {
869 		/* Enable the data fabric counters */
870 		for (i = 0; i < amd_df_npmcs; i++) {
871 			d = &amd_pmcdesc[amd_npmcs + i];
872 			snprintf(d->pm_descr.pd_name, PMC_NAME_MAX,
873 			    "K8-DF-%d", i);
874 			d->pm_descr.pd_class = PMC_CLASS_K8;
875 			d->pm_descr.pd_caps = AMD_PMC_DF_CAPS;
876 			d->pm_descr.pd_width = 48;
877 			d->pm_evsel = AMD_PMC_DF_BASE + 2 * i;
878 			d->pm_perfctr = AMD_PMC_DF_BASE + 2 * i + 1;
879 			d->pm_subclass = PMC_AMD_SUB_CLASS_DATA_FABRIC;
880 		}
881 		amd_npmcs += amd_df_npmcs;
882 	}
883 
884 	/*
885 	 * Allocate space for pointers to PMC HW descriptors and for
886 	 * the MDEP structure used by MI code.
887 	 */
888 	amd_pcpu = malloc(sizeof(struct amd_cpu *) * pmc_cpu_max(), M_PMC,
889 	    M_WAITOK | M_ZERO);
890 
891 	/*
892 	 * These processors have two or three classes of PMCs: the TSC,
893 	 * programmable PMCs, and AMD IBS.
894 	 */
895 	if ((amd_feature2 & AMDID2_IBS) != 0) {
896 		nclasses = 3;
897 	} else {
898 		nclasses = 2;
899 	}
900 
901 	pmc_mdep = pmc_mdep_alloc(nclasses);
902 
903 	ncpus = pmc_cpu_max();
904 
905 	/* Initialize the TSC. */
906 	error = pmc_tsc_initialize(pmc_mdep, ncpus);
907 	if (error != 0)
908 		goto error;
909 
910 	/* Initialize AMD K8 PMC handling. */
911 	pcd = &pmc_mdep->pmd_classdep[PMC_MDEP_CLASS_INDEX_K8];
912 
913 	pcd->pcd_caps		= AMD_PMC_CAPS;
914 	pcd->pcd_class		= PMC_CLASS_K8;
915 	pcd->pcd_num		= amd_npmcs;
916 	pcd->pcd_ri		= pmc_mdep->pmd_npmc;
917 	pcd->pcd_width		= 48;
918 
919 	pcd->pcd_allocate_pmc	= amd_allocate_pmc;
920 	pcd->pcd_config_pmc	= amd_config_pmc;
921 	pcd->pcd_describe	= amd_describe;
922 	pcd->pcd_get_config	= amd_get_config;
923 	pcd->pcd_get_msr	= amd_get_msr;
924 	pcd->pcd_pcpu_fini	= amd_pcpu_fini;
925 	pcd->pcd_pcpu_init	= amd_pcpu_init;
926 	pcd->pcd_read_pmc	= amd_read_pmc;
927 	pcd->pcd_release_pmc	= amd_release_pmc;
928 	pcd->pcd_start_pmc	= amd_start_pmc;
929 	pcd->pcd_stop_pmc	= amd_stop_pmc;
930 	pcd->pcd_write_pmc	= amd_write_pmc;
931 
932 	pmc_mdep->pmd_cputype	= cputype;
933 	pmc_mdep->pmd_intr	= amd_intr;
934 	pmc_mdep->pmd_switch_in	= amd_switch_in;
935 	pmc_mdep->pmd_switch_out = amd_switch_out;
936 
937 	pmc_mdep->pmd_npmc	+= amd_npmcs;
938 
939 	PMCDBG0(MDP, INI, 0, "amd-initialize");
940 
941 	if (nclasses >= 3) {
942 		error = pmc_ibs_initialize(pmc_mdep, ncpus);
943 		if (error != 0)
944 			goto error;
945 	}
946 
947 	return (pmc_mdep);
948 
949 error:
950 	free(pmc_mdep, M_PMC);
951 	return (NULL);
952 }
953 
954 /*
955  * Finalization code for AMD CPUs.
956  */
957 void
958 pmc_amd_finalize(struct pmc_mdep *md)
959 {
960 	PMCDBG0(MDP, INI, 1, "amd-finalize");
961 
962 	pmc_tsc_finalize(md);
963 
964 	for (int i = 0; i < pmc_cpu_max(); i++)
965 		KASSERT(amd_pcpu[i] == NULL,
966 		    ("[amd,%d] non-null pcpu cpu %d", __LINE__, i));
967 
968 	free(amd_pcpu, M_PMC);
969 	amd_pcpu = NULL;
970 }
971