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