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 int amd_core_npmcs, amd_l3_npmcs, amd_df_npmcs;
64 static struct amd_descr amd_pmcdesc[AMD_NPMCS_MAX];
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
amd_read_pmc(int cpu,int ri,struct pmc * pm,pmc_value_t * v)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
amd_write_pmc(int cpu,int ri,struct pmc * pm,pmc_value_t v)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
amd_config_pmc(int cpu,int ri,struct pmc * pm)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
amd_get_config(int cpu,int ri,struct pmc ** ppm)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
amd_switch_in(struct pmc_cpu * pc __pmcdbg_used,struct pmc_process * pp)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
amd_switch_out(struct pmc_cpu * pc __pmcdbg_used,struct pmc_process * pp __pmcdbg_used)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
amd_allocate_pmc(int cpu __unused,int ri,struct pmc * pm,const struct pmc_op_pmcallocate * a)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
amd_release_pmc(int cpu,int ri,struct pmc * pmc __unused)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
amd_start_pmc(int cpu __diagused,int ri,struct pmc * pm)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
amd_stop_pmc(int cpu __diagused,int ri,struct pmc * pm)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
amd_intr(struct trapframe * tf)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
amd_describe(int cpu,int ri,struct pmc_info * pi,struct pmc ** ppmc)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
amd_get_msr(int ri,uint32_t * msr)665 amd_get_msr(int ri, uint32_t *msr)
666 {
667 int df_idx;
668
669 KASSERT(ri >= 0 && ri < amd_npmcs,
670 ("[amd,%d] ri %d out of range", __LINE__, ri));
671
672 /*
673 * Map counter row index to RDPMC ECX value.
674 *
675 * AMD BKDG 24594 rev 3.37, page 440,
676 * "RDPMC Read Performance-Monitoring Counter":
677 * ECX 0-5: Core counters 0-5
678 * ECX 6-9: DF/Northbridge counters 0-3
679 * ECX 10-15: L3 Cache counters 0-5
680 * ECX 16-27: DF/Northbridge counters 4-15
681 *
682 * AMD PPR 57930-A0 section 2.1.9,
683 * "Register Sharing" for DF counter details.
684 */
685 if (ri < amd_core_npmcs) {
686 /* ECX 0-5: Core counters */
687 *msr = ri;
688 } else if (ri < amd_core_npmcs + amd_l3_npmcs) {
689 /* ECX 10-15: L3 Cache counters */
690 *msr = 10 + (ri - amd_core_npmcs);
691 } else {
692 /* ECX 6-9: DF counters 0-3
693 * ECX 16-27: DF counters 4-15 */
694 df_idx = ri - amd_core_npmcs - amd_l3_npmcs;
695 if (df_idx < 4)
696 *msr = 6 + df_idx;
697 else if (df_idx < 16)
698 *msr = 16 + (df_idx - 4);
699 else
700 return (EINVAL);
701 }
702 return (0);
703 }
704
705 /*
706 * Return the capabilities of the given PMC.
707 */
708 static int
amd_get_caps(int ri,uint32_t * caps)709 amd_get_caps(int ri, uint32_t *caps)
710 {
711 KASSERT(ri >= 0 && ri < amd_npmcs,
712 ("[amd,%d] ri %d out of range", __LINE__, ri));
713
714 *caps = amd_pmcdesc[ri].pm_descr.pd_caps;
715
716 return (0);
717 }
718
719 /*
720 * Processor-dependent initialization.
721 */
722 static int
amd_pcpu_init(struct pmc_mdep * md,int cpu)723 amd_pcpu_init(struct pmc_mdep *md, int cpu)
724 {
725 struct amd_cpu *pac;
726 struct pmc_cpu *pc;
727 struct pmc_hw *phw;
728 int first_ri, n;
729
730 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
731 ("[amd,%d] insane cpu number %d", __LINE__, cpu));
732
733 PMCDBG1(MDP, INI, 1, "amd-init cpu=%d", cpu);
734
735 amd_pcpu[cpu] = pac = malloc(sizeof(struct amd_cpu), M_PMC,
736 M_WAITOK | M_ZERO);
737
738 /*
739 * Set the content of the hardware descriptors to a known
740 * state and initialize pointers in the MI per-cpu descriptor.
741 */
742 pc = pmc_pcpu[cpu];
743 first_ri = md->pmd_classdep[PMC_MDEP_CLASS_INDEX_K8].pcd_ri;
744
745 KASSERT(pc != NULL, ("[amd,%d] NULL per-cpu pointer", __LINE__));
746
747 for (n = 0, phw = pac->pc_amdpmcs; n < amd_npmcs; n++, phw++) {
748 phw->phw_state = PMC_PHW_FLAG_IS_ENABLED |
749 PMC_PHW_CPU_TO_STATE(cpu) | PMC_PHW_INDEX_TO_STATE(n);
750 phw->phw_pmc = NULL;
751 pc->pc_hwpmcs[n + first_ri] = phw;
752 }
753
754 return (0);
755 }
756
757 /*
758 * Processor-dependent cleanup prior to the KLD being unloaded.
759 */
760 static int
amd_pcpu_fini(struct pmc_mdep * md,int cpu)761 amd_pcpu_fini(struct pmc_mdep *md, int cpu)
762 {
763 struct amd_cpu *pac;
764 struct pmc_cpu *pc;
765 int first_ri, i;
766
767 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
768 ("[amd,%d] insane cpu number (%d)", __LINE__, cpu));
769
770 PMCDBG1(MDP, INI, 1, "amd-cleanup cpu=%d", cpu);
771
772 /*
773 * Next, free up allocated space.
774 */
775 if ((pac = amd_pcpu[cpu]) == NULL)
776 return (0);
777
778 amd_pcpu[cpu] = NULL;
779
780 #ifdef HWPMC_DEBUG
781 for (i = 0; i < AMD_NPMCS_K8; i++) {
782 KASSERT(pac->pc_amdpmcs[i].phw_pmc == NULL,
783 ("[amd,%d] CPU%d/PMC%d in use", __LINE__, cpu, i));
784 KASSERT(AMD_PMC_IS_STOPPED(AMD_PMC_EVSEL_0 + i),
785 ("[amd,%d] CPU%d/PMC%d not stopped", __LINE__, cpu, i));
786 }
787 #endif
788
789 pc = pmc_pcpu[cpu];
790 KASSERT(pc != NULL, ("[amd,%d] NULL per-cpu state", __LINE__));
791
792 first_ri = md->pmd_classdep[PMC_MDEP_CLASS_INDEX_K8].pcd_ri;
793
794 /*
795 * Reset pointers in the MI 'per-cpu' state.
796 */
797 for (i = 0; i < amd_npmcs; i++)
798 pc->pc_hwpmcs[i + first_ri] = NULL;
799
800 free(pac, M_PMC);
801 return (0);
802 }
803
804 /*
805 * Initialize ourselves.
806 */
807 struct pmc_mdep *
pmc_amd_initialize(void)808 pmc_amd_initialize(void)
809 {
810 struct pmc_classdep *pcd;
811 struct pmc_mdep *pmc_mdep;
812 enum pmc_cputype cputype;
813 int error, i, ncpus, nclasses;
814 int family, model, stepping;
815 struct amd_descr *d;
816
817 /*
818 * The presence of hardware performance counters on the AMD
819 * Athlon, Duron or later processors, is _not_ indicated by
820 * any of the processor feature flags set by the 'CPUID'
821 * instruction, so we only check the 'instruction family'
822 * field returned by CPUID for instruction family >= 6.
823 */
824
825 family = CPUID_TO_FAMILY(cpu_id);
826 model = CPUID_TO_MODEL(cpu_id);
827 stepping = CPUID_TO_STEPPING(cpu_id);
828
829 if (family == 0x18)
830 snprintf(pmc_cpuid, sizeof(pmc_cpuid), "HygonGenuine-%d-%02X-%X",
831 family, model, stepping);
832 else
833 snprintf(pmc_cpuid, sizeof(pmc_cpuid), "AuthenticAMD-%d-%02X-%X",
834 family, model, stepping);
835
836 switch (cpu_id & 0xF00) {
837 case 0xF00: /* Athlon64/Opteron processor */
838 cputype = PMC_CPU_AMD_K8;
839 break;
840 default:
841 printf("pmc: Unknown AMD CPU %x %d-%d.\n", cpu_id, family,
842 model);
843 return (NULL);
844 }
845
846 /*
847 * From PPR for AMD Family 1Ah, a new cpuid leaf specifies the maximum
848 * number of PMCs of each type. If we do not have that leaf, we use
849 * the prior default values that are only valid if we have the feature
850 * bit enabled in CPU.
851 */
852 if ((amd_feature2 & AMDID2_PCXC) != 0) {
853 amd_core_npmcs = AMD_PMC_CORE_DEFAULT;
854 } else {
855 amd_core_npmcs = AMD_NPMCS_K8;
856 }
857 amd_l3_npmcs = AMD_PMC_L3_DEFAULT;
858 amd_df_npmcs = AMD_PMC_DF_DEFAULT;
859
860 if (cpu_exthigh >= CPUID_EXTPERFMON) {
861 u_int regs[4];
862 do_cpuid(CPUID_EXTPERFMON, regs);
863 if (regs[1] != 0) {
864 amd_core_npmcs = EXTPERFMON_CORE_PMCS(regs[1]);
865 amd_df_npmcs = EXTPERFMON_DF_PMCS(regs[1]);
866 }
867 }
868
869 /* Enable the newer core counters */
870 for (i = 0; i < amd_core_npmcs; i++) {
871 d = &amd_pmcdesc[i];
872 snprintf(d->pm_descr.pd_name, PMC_NAME_MAX,
873 "K8-%d", i);
874 d->pm_descr.pd_class = PMC_CLASS_K8;
875 d->pm_descr.pd_caps = AMD_PMC_CAPS;
876 /*
877 * Zen 5 can precisely count retire events.
878 *
879 * Refer to PPR Vol 1 for AMD Family 1Ah Model 02h C1 57238
880 * Rev. 0.24 September 29, 2024.
881 */
882 if ((family >= 0x1a) && (i == 2))
883 d->pm_descr.pd_caps |= PMC_CAP_PRECISE;
884 d->pm_descr.pd_width = 48;
885 if ((amd_feature2 & AMDID2_PCXC) != 0) {
886 d->pm_evsel = AMD_PMC_CORE_BASE + 2 * i;
887 d->pm_perfctr = AMD_PMC_CORE_BASE + 2 * i + 1;
888 } else {
889 d->pm_evsel = AMD_PMC_EVSEL_0 + i;
890 d->pm_perfctr = AMD_PMC_PERFCTR_0 + i;
891 }
892 d->pm_subclass = PMC_AMD_SUB_CLASS_CORE;
893 }
894 amd_npmcs = amd_core_npmcs;
895
896 if ((amd_feature2 & AMDID2_PTSCEL2I) != 0) {
897 /* Enable the LLC/L3 counters */
898 for (i = 0; i < amd_l3_npmcs; i++) {
899 d = &amd_pmcdesc[amd_npmcs + i];
900 snprintf(d->pm_descr.pd_name, PMC_NAME_MAX,
901 "K8-L3-%d", i);
902 d->pm_descr.pd_class = PMC_CLASS_K8;
903 d->pm_descr.pd_caps = AMD_PMC_L3_CAPS;
904 d->pm_descr.pd_width = 48;
905 d->pm_evsel = AMD_PMC_L3_BASE + 2 * i;
906 d->pm_perfctr = AMD_PMC_L3_BASE + 2 * i + 1;
907 d->pm_subclass = PMC_AMD_SUB_CLASS_L3_CACHE;
908 }
909 amd_npmcs += amd_l3_npmcs;
910 }
911
912 if ((amd_feature2 & AMDID2_PNXC) != 0) {
913 /* Enable the data fabric counters */
914 for (i = 0; i < amd_df_npmcs; i++) {
915 d = &amd_pmcdesc[amd_npmcs + i];
916 snprintf(d->pm_descr.pd_name, PMC_NAME_MAX,
917 "K8-DF-%d", i);
918 d->pm_descr.pd_class = PMC_CLASS_K8;
919 d->pm_descr.pd_caps = AMD_PMC_DF_CAPS;
920 d->pm_descr.pd_width = 48;
921 d->pm_evsel = AMD_PMC_DF_BASE + 2 * i;
922 d->pm_perfctr = AMD_PMC_DF_BASE + 2 * i + 1;
923 d->pm_subclass = PMC_AMD_SUB_CLASS_DATA_FABRIC;
924 }
925 amd_npmcs += amd_df_npmcs;
926 }
927
928 /*
929 * Allocate space for pointers to PMC HW descriptors and for
930 * the MDEP structure used by MI code.
931 */
932 amd_pcpu = malloc(sizeof(struct amd_cpu *) * pmc_cpu_max(), M_PMC,
933 M_WAITOK | M_ZERO);
934
935 /*
936 * These processors have two or three classes of PMCs: the TSC,
937 * programmable PMCs, and AMD IBS.
938 */
939 if ((amd_feature2 & AMDID2_IBS) != 0) {
940 nclasses = 3;
941 } else {
942 nclasses = 2;
943 }
944
945 pmc_mdep = pmc_mdep_alloc(nclasses);
946
947 ncpus = pmc_cpu_max();
948
949 /* Initialize the TSC. */
950 error = pmc_tsc_initialize(pmc_mdep, ncpus);
951 if (error != 0)
952 goto error;
953
954 /* Initialize AMD K8 PMC handling. */
955 pcd = &pmc_mdep->pmd_classdep[PMC_MDEP_CLASS_INDEX_K8];
956
957 pcd->pcd_caps = AMD_PMC_CAPS;
958 pcd->pcd_class = PMC_CLASS_K8;
959 pcd->pcd_num = amd_npmcs;
960 pcd->pcd_ri = pmc_mdep->pmd_npmc;
961 pcd->pcd_width = 48;
962
963 pcd->pcd_allocate_pmc = amd_allocate_pmc;
964 pcd->pcd_config_pmc = amd_config_pmc;
965 pcd->pcd_describe = amd_describe;
966 pcd->pcd_get_config = amd_get_config;
967 pcd->pcd_get_msr = amd_get_msr;
968 pcd->pcd_pcpu_fini = amd_pcpu_fini;
969 pcd->pcd_pcpu_init = amd_pcpu_init;
970 pcd->pcd_read_pmc = amd_read_pmc;
971 pcd->pcd_release_pmc = amd_release_pmc;
972 pcd->pcd_start_pmc = amd_start_pmc;
973 pcd->pcd_stop_pmc = amd_stop_pmc;
974 pcd->pcd_write_pmc = amd_write_pmc;
975 pcd->pcd_get_caps = amd_get_caps;
976
977 pmc_mdep->pmd_cputype = cputype;
978 pmc_mdep->pmd_intr = amd_intr;
979 pmc_mdep->pmd_switch_in = amd_switch_in;
980 pmc_mdep->pmd_switch_out = amd_switch_out;
981
982 pmc_mdep->pmd_npmc += amd_npmcs;
983
984 PMCDBG0(MDP, INI, 0, "amd-initialize");
985
986 if (nclasses >= 3) {
987 error = pmc_ibs_initialize(pmc_mdep, ncpus);
988 if (error != 0)
989 goto error;
990 }
991
992 return (pmc_mdep);
993
994 error:
995 free(pmc_mdep, M_PMC);
996 return (NULL);
997 }
998
999 /*
1000 * Finalization code for AMD CPUs.
1001 */
1002 void
pmc_amd_finalize(struct pmc_mdep * md)1003 pmc_amd_finalize(struct pmc_mdep *md)
1004 {
1005 PMCDBG0(MDP, INI, 1, "amd-finalize");
1006
1007 pmc_tsc_finalize(md);
1008
1009 for (int i = 0; i < pmc_cpu_max(); i++)
1010 KASSERT(amd_pcpu[i] == NULL,
1011 ("[amd,%d] non-null pcpu cpu %d", __LINE__, i));
1012
1013 free(amd_pcpu, M_PMC);
1014 amd_pcpu = NULL;
1015 }
1016