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