xref: /freebsd/sys/dev/hwpmc/hwpmc_amd.c (revision 2008043f386721d58158e37e0d7e50df8095942d)
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 	struct pmc_hw *phw __diagused;
455 
456 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
457 	    ("[amd,%d] illegal CPU value %d", __LINE__, cpu));
458 	KASSERT(ri >= 0 && ri < AMD_NPMCS,
459 	    ("[amd,%d] illegal row-index %d", __LINE__, ri));
460 
461 	phw = &amd_pcpu[cpu]->pc_amdpmcs[ri];
462 
463 	KASSERT(phw->phw_pmc == NULL,
464 	    ("[amd,%d] PHW pmc %p non-NULL", __LINE__, phw->phw_pmc));
465 
466 	return (0);
467 }
468 
469 /*
470  * Start a PMC.
471  */
472 static int
473 amd_start_pmc(int cpu __diagused, int ri, struct pmc *pm)
474 {
475 	const struct amd_descr *pd;
476 	uint64_t config;
477 
478 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
479 	    ("[amd,%d] illegal CPU value %d", __LINE__, cpu));
480 	KASSERT(ri >= 0 && ri < AMD_NPMCS,
481 	    ("[amd,%d] illegal row-index %d", __LINE__, ri));
482 
483 	pd = &amd_pmcdesc[ri];
484 
485 	PMCDBG2(MDP, STA, 1, "amd-start cpu=%d ri=%d", cpu, ri);
486 
487 	KASSERT(AMD_PMC_IS_STOPPED(pd->pm_evsel),
488 	    ("[amd,%d] pmc%d,cpu%d: Starting active PMC \"%s\"", __LINE__,
489 	    ri, cpu, pd->pm_descr.pd_name));
490 
491 	/* turn on the PMC ENABLE bit */
492 	config = pm->pm_md.pm_amd.pm_amd_evsel | AMD_PMC_ENABLE;
493 
494 	PMCDBG1(MDP, STA, 2, "amd-start config=0x%x", config);
495 
496 	wrmsr(pd->pm_evsel, config);
497 	return (0);
498 }
499 
500 /*
501  * Stop a PMC.
502  */
503 static int
504 amd_stop_pmc(int cpu __diagused, int ri, struct pmc *pm)
505 {
506 	const struct amd_descr *pd;
507 	uint64_t config;
508 	int i;
509 
510 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
511 	    ("[amd,%d] illegal CPU value %d", __LINE__, cpu));
512 	KASSERT(ri >= 0 && ri < AMD_NPMCS,
513 	    ("[amd,%d] illegal row-index %d", __LINE__, ri));
514 
515 	pd = &amd_pmcdesc[ri];
516 
517 	KASSERT(!AMD_PMC_IS_STOPPED(pd->pm_evsel),
518 	    ("[amd,%d] PMC%d, CPU%d \"%s\" already stopped",
519 		__LINE__, ri, cpu, pd->pm_descr.pd_name));
520 
521 	PMCDBG1(MDP, STO, 1, "amd-stop ri=%d", ri);
522 
523 	/* turn off the PMC ENABLE bit */
524 	config = pm->pm_md.pm_amd.pm_amd_evsel & ~AMD_PMC_ENABLE;
525 	wrmsr(pd->pm_evsel, config);
526 
527 	/*
528 	 * Due to NMI latency on newer AMD processors
529 	 * NMI interrupts are ignored, which leads to
530 	 * panic or messages based on kernel configuration
531 	 */
532 
533 	/* Wait for the count to be reset */
534 	for (i = 0; i < OVERFLOW_WAIT_COUNT; i++) {
535 		if (rdmsr(pd->pm_perfctr) & (1 << (pd->pm_descr.pd_width - 1)))
536 			break;
537 
538 		DELAY(1);
539 	}
540 
541 	return (0);
542 }
543 
544 /*
545  * Interrupt handler.  This function needs to return '1' if the
546  * interrupt was this CPU's PMCs or '0' otherwise.  It is not allowed
547  * to sleep or do anything a 'fast' interrupt handler is not allowed
548  * to do.
549  */
550 static int
551 amd_intr(struct trapframe *tf)
552 {
553 	struct amd_cpu *pac;
554 	struct pmc *pm;
555 	pmc_value_t v;
556 	uint64_t config, evsel, perfctr;
557 	uint32_t active = 0, count = 0;
558 	int i, error, retval, cpu;
559 
560 	cpu = curcpu;
561 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
562 	    ("[amd,%d] out of range CPU %d", __LINE__, cpu));
563 
564 	PMCDBG3(MDP, INT, 1, "cpu=%d tf=%p um=%d", cpu, tf, TRAPF_USERMODE(tf));
565 
566 	retval = 0;
567 
568 	pac = amd_pcpu[cpu];
569 
570 	/*
571 	 * look for all PMCs that have interrupted:
572 	 * - look for a running, sampling PMC which has overflowed
573 	 *   and which has a valid 'struct pmc' association
574 	 *
575 	 * If found, we call a helper to process the interrupt.
576 	 *
577 	 * PMCs interrupting at the same time are collapsed into
578 	 * a single interrupt. Check all the valid pmcs for
579 	 * overflow.
580 	 */
581 	for (i = 0; i < AMD_CORE_NPMCS; i++) {
582 		if ((pm = pac->pc_amdpmcs[i].phw_pmc) == NULL ||
583 		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
584 			continue;
585 		}
586 
587 		/* Consider pmc with valid handle as active */
588 		active++;
589 
590 		if (!AMD_PMC_HAS_OVERFLOWED(i))
591 			continue;
592 
593 		retval = 1;	/* Found an interrupting PMC. */
594 
595 		if (pm->pm_state != PMC_STATE_RUNNING)
596 			continue;
597 
598 		/* Stop the PMC, reload count. */
599 		evsel   = amd_pmcdesc[i].pm_evsel;
600 		perfctr = amd_pmcdesc[i].pm_perfctr;
601 		v       = pm->pm_sc.pm_reloadcount;
602 		config  = rdmsr(evsel);
603 
604 		KASSERT((config & ~AMD_PMC_ENABLE) ==
605 		    (pm->pm_md.pm_amd.pm_amd_evsel & ~AMD_PMC_ENABLE),
606 		    ("[amd,%d] config mismatch reg=0x%jx pm=0x%jx", __LINE__,
607 			 (uintmax_t)config, (uintmax_t)pm->pm_md.pm_amd.pm_amd_evsel));
608 
609 		wrmsr(evsel, config & ~AMD_PMC_ENABLE);
610 		wrmsr(perfctr, AMD_RELOAD_COUNT_TO_PERFCTR_VALUE(v));
611 
612 		/* Restart the counter if logging succeeded. */
613 		error = pmc_process_interrupt(PMC_HR, pm, tf);
614 		if (error == 0)
615 			wrmsr(evsel, config);
616 	}
617 
618 	/*
619 	 * Due to NMI latency, there can be a scenario in which
620 	 * multiple pmcs gets serviced in an earlier NMI and we
621 	 * do not find an overflow in the subsequent NMI.
622 	 *
623 	 * For such cases we keep a per-cpu count of active NMIs
624 	 * and compare it with min(active pmcs, 2) to determine
625 	 * if this NMI was for a pmc overflow which was serviced
626 	 * in an earlier request or should be ignored.
627 	 */
628 	if (retval) {
629 		DPCPU_SET(nmi_counter, min(2, active));
630 	} else {
631 		if ((count = DPCPU_GET(nmi_counter))) {
632 			retval = 1;
633 			DPCPU_SET(nmi_counter, --count);
634 		}
635 	}
636 
637 	if (retval)
638 		counter_u64_add(pmc_stats.pm_intr_processed, 1);
639 	else
640 		counter_u64_add(pmc_stats.pm_intr_ignored, 1);
641 
642 	PMCDBG1(MDP, INT, 2, "retval=%d", retval);
643 	return (retval);
644 }
645 
646 /*
647  * Describe a PMC.
648  */
649 static int
650 amd_describe(int cpu, int ri, struct pmc_info *pi, struct pmc **ppmc)
651 {
652 	const struct amd_descr *pd;
653 	struct pmc_hw *phw;
654 
655 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
656 	    ("[amd,%d] illegal CPU %d", __LINE__, cpu));
657 	KASSERT(ri >= 0 && ri < AMD_NPMCS,
658 	    ("[amd,%d] row-index %d out of range", __LINE__, ri));
659 
660 	phw = &amd_pcpu[cpu]->pc_amdpmcs[ri];
661 	pd  = &amd_pmcdesc[ri];
662 
663 	strlcpy(pi->pm_name, pd->pm_descr.pd_name, sizeof(pi->pm_name));
664 	pi->pm_class = pd->pm_descr.pd_class;
665 
666 	if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) != 0) {
667 		pi->pm_enabled = true;
668 		*ppmc          = phw->phw_pmc;
669 	} else {
670 		pi->pm_enabled = false;
671 		*ppmc          = NULL;
672 	}
673 
674 	return (0);
675 }
676 
677 /*
678  * Return the MSR address of the given PMC.
679  */
680 static int
681 amd_get_msr(int ri, uint32_t *msr)
682 {
683 	KASSERT(ri >= 0 && ri < AMD_NPMCS,
684 	    ("[amd,%d] ri %d out of range", __LINE__, ri));
685 
686 	*msr = amd_pmcdesc[ri].pm_perfctr - AMD_PMC_PERFCTR_0;
687 	return (0);
688 }
689 
690 /*
691  * Processor-dependent initialization.
692  */
693 static int
694 amd_pcpu_init(struct pmc_mdep *md, int cpu)
695 {
696 	struct amd_cpu *pac;
697 	struct pmc_cpu *pc;
698 	struct pmc_hw  *phw;
699 	int first_ri, n;
700 
701 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
702 	    ("[amd,%d] insane cpu number %d", __LINE__, cpu));
703 
704 	PMCDBG1(MDP, INI, 1, "amd-init cpu=%d", cpu);
705 
706 	amd_pcpu[cpu] = pac = malloc(sizeof(struct amd_cpu), M_PMC,
707 	    M_WAITOK | M_ZERO);
708 
709 	/*
710 	 * Set the content of the hardware descriptors to a known
711 	 * state and initialize pointers in the MI per-cpu descriptor.
712 	 */
713 	pc = pmc_pcpu[cpu];
714 	first_ri = md->pmd_classdep[PMC_MDEP_CLASS_INDEX_K8].pcd_ri;
715 
716 	KASSERT(pc != NULL, ("[amd,%d] NULL per-cpu pointer", __LINE__));
717 
718 	for (n = 0, phw = pac->pc_amdpmcs; n < AMD_NPMCS; n++, phw++) {
719 		phw->phw_state = PMC_PHW_FLAG_IS_ENABLED |
720 		    PMC_PHW_CPU_TO_STATE(cpu) | PMC_PHW_INDEX_TO_STATE(n);
721 		phw->phw_pmc = NULL;
722 		pc->pc_hwpmcs[n + first_ri] = phw;
723 	}
724 
725 	return (0);
726 }
727 
728 /*
729  * Processor-dependent cleanup prior to the KLD being unloaded.
730  */
731 static int
732 amd_pcpu_fini(struct pmc_mdep *md, int cpu)
733 {
734 	struct amd_cpu *pac;
735 	struct pmc_cpu *pc;
736 	uint32_t evsel;
737 	int first_ri, i;
738 
739 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
740 	    ("[amd,%d] insane cpu number (%d)", __LINE__, cpu));
741 
742 	PMCDBG1(MDP, INI, 1, "amd-cleanup cpu=%d", cpu);
743 
744 	/*
745 	 * First, turn off all PMCs on this CPU.
746 	 */
747 	for (i = 0; i < 4; i++) { /* XXX this loop is now not needed */
748 		evsel = rdmsr(AMD_PMC_EVSEL_0 + i);
749 		evsel &= ~AMD_PMC_ENABLE;
750 		wrmsr(AMD_PMC_EVSEL_0 + i, evsel);
751 	}
752 
753 	/*
754 	 * Next, free up allocated space.
755 	 */
756 	if ((pac = amd_pcpu[cpu]) == NULL)
757 		return (0);
758 
759 	amd_pcpu[cpu] = NULL;
760 
761 #ifdef	HWPMC_DEBUG
762 	for (i = 0; i < AMD_NPMCS; i++) {
763 		KASSERT(pac->pc_amdpmcs[i].phw_pmc == NULL,
764 		    ("[amd,%d] CPU%d/PMC%d in use", __LINE__, cpu, i));
765 		KASSERT(AMD_PMC_IS_STOPPED(AMD_PMC_EVSEL_0 + i),
766 		    ("[amd,%d] CPU%d/PMC%d not stopped", __LINE__, cpu, i));
767 	}
768 #endif
769 
770 	pc = pmc_pcpu[cpu];
771 	KASSERT(pc != NULL, ("[amd,%d] NULL per-cpu state", __LINE__));
772 
773 	first_ri = md->pmd_classdep[PMC_MDEP_CLASS_INDEX_K8].pcd_ri;
774 
775 	/*
776 	 * Reset pointers in the MI 'per-cpu' state.
777 	 */
778 	for (i = 0; i < AMD_NPMCS; i++)
779 		pc->pc_hwpmcs[i + first_ri] = NULL;
780 
781 	free(pac, M_PMC);
782 	return (0);
783 }
784 
785 /*
786  * Initialize ourselves.
787  */
788 struct pmc_mdep *
789 pmc_amd_initialize(void)
790 {
791 	struct pmc_classdep *pcd;
792 	struct pmc_mdep *pmc_mdep;
793 	enum pmc_cputype cputype;
794 	int error, i, ncpus;
795 	int family, model, stepping;
796 
797 	/*
798 	 * The presence of hardware performance counters on the AMD
799 	 * Athlon, Duron or later processors, is _not_ indicated by
800 	 * any of the processor feature flags set by the 'CPUID'
801 	 * instruction, so we only check the 'instruction family'
802 	 * field returned by CPUID for instruction family >= 6.
803 	 */
804 
805 	family = CPUID_TO_FAMILY(cpu_id);
806 	model = CPUID_TO_MODEL(cpu_id);
807 	stepping = CPUID_TO_STEPPING(cpu_id);
808 
809 	if (family == 0x18)
810 		snprintf(pmc_cpuid, sizeof(pmc_cpuid), "HygonGenuine-%d-%02X-%X",
811 		    family, model, stepping);
812 	else
813 		snprintf(pmc_cpuid, sizeof(pmc_cpuid), "AuthenticAMD-%d-%02X-%X",
814 		    family, model, stepping);
815 
816 	switch (cpu_id & 0xF00) {
817 	case 0xF00:		/* Athlon64/Opteron processor */
818 		cputype = PMC_CPU_AMD_K8;
819 		break;
820 	default:
821 		printf("pmc: Unknown AMD CPU %x %d-%d.\n", cpu_id, family,
822 		    model);
823 		return (NULL);
824 	}
825 
826 	/*
827 	 * Allocate space for pointers to PMC HW descriptors and for
828 	 * the MDEP structure used by MI code.
829 	 */
830 	amd_pcpu = malloc(sizeof(struct amd_cpu *) * pmc_cpu_max(), M_PMC,
831 	    M_WAITOK | M_ZERO);
832 
833 	/*
834 	 * These processors have two classes of PMCs: the TSC and
835 	 * programmable PMCs.
836 	 */
837 	pmc_mdep = pmc_mdep_alloc(2);
838 
839 	ncpus = pmc_cpu_max();
840 
841 	/* Initialize the TSC. */
842 	error = pmc_tsc_initialize(pmc_mdep, ncpus);
843 	if (error != 0)
844 		goto error;
845 
846 	/* Initialize AMD K8 PMC handling. */
847 	pcd = &pmc_mdep->pmd_classdep[PMC_MDEP_CLASS_INDEX_K8];
848 
849 	pcd->pcd_caps		= AMD_PMC_CAPS;
850 	pcd->pcd_class		= PMC_CLASS_K8;
851 	pcd->pcd_num		= AMD_NPMCS;
852 	pcd->pcd_ri		= pmc_mdep->pmd_npmc;
853 	pcd->pcd_width		= 48;
854 
855 	/* fill in the correct pmc name and class */
856 	for (i = 0; i < AMD_NPMCS; i++) {
857 		snprintf(amd_pmcdesc[i].pm_descr.pd_name, PMC_NAME_MAX, "K8-%d",
858 		    i);
859 	}
860 
861 	pcd->pcd_allocate_pmc	= amd_allocate_pmc;
862 	pcd->pcd_config_pmc	= amd_config_pmc;
863 	pcd->pcd_describe	= amd_describe;
864 	pcd->pcd_get_config	= amd_get_config;
865 	pcd->pcd_get_msr	= amd_get_msr;
866 	pcd->pcd_pcpu_fini	= amd_pcpu_fini;
867 	pcd->pcd_pcpu_init	= amd_pcpu_init;
868 	pcd->pcd_read_pmc	= amd_read_pmc;
869 	pcd->pcd_release_pmc	= amd_release_pmc;
870 	pcd->pcd_start_pmc	= amd_start_pmc;
871 	pcd->pcd_stop_pmc	= amd_stop_pmc;
872 	pcd->pcd_write_pmc	= amd_write_pmc;
873 
874 	pmc_mdep->pmd_cputype	= cputype;
875 	pmc_mdep->pmd_intr	= amd_intr;
876 	pmc_mdep->pmd_switch_in	= amd_switch_in;
877 	pmc_mdep->pmd_switch_out = amd_switch_out;
878 
879 	pmc_mdep->pmd_npmc	+= AMD_NPMCS;
880 
881 	PMCDBG0(MDP, INI, 0, "amd-initialize");
882 
883 	return (pmc_mdep);
884 
885 error:
886 	free(pmc_mdep, M_PMC);
887 	return (NULL);
888 }
889 
890 /*
891  * Finalization code for AMD CPUs.
892  */
893 void
894 pmc_amd_finalize(struct pmc_mdep *md)
895 {
896 	PMCDBG0(MDP, INI, 1, "amd-finalize");
897 
898 	pmc_tsc_finalize(md);
899 
900 	for (int i = 0; i < pmc_cpu_max(); i++)
901 		KASSERT(amd_pcpu[i] == NULL,
902 		    ("[amd,%d] non-null pcpu cpu %d", __LINE__, i));
903 
904 	free(amd_pcpu, M_PMC);
905 	amd_pcpu = NULL;
906 }
907