xref: /freebsd/lib/libpmc/libpmc.c (revision 13ec1e3155c7e9bf037b12af186351b7fa9b9450)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003-2008 Joseph Koshy
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/types.h>
33 #include <sys/param.h>
34 #include <sys/module.h>
35 #include <sys/pmc.h>
36 #include <sys/syscall.h>
37 
38 #include <ctype.h>
39 #include <errno.h>
40 #include <err.h>
41 #include <fcntl.h>
42 #include <pmc.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <strings.h>
47 #include <sysexits.h>
48 #include <unistd.h>
49 
50 #include "libpmcinternal.h"
51 
52 /* Function prototypes */
53 #if defined(__amd64__) || defined(__i386__)
54 static int k8_allocate_pmc(enum pmc_event _pe, char *_ctrspec,
55     struct pmc_op_pmcallocate *_pmc_config);
56 #endif
57 #if defined(__amd64__) || defined(__i386__)
58 static int tsc_allocate_pmc(enum pmc_event _pe, char *_ctrspec,
59     struct pmc_op_pmcallocate *_pmc_config);
60 #endif
61 #if defined(__arm__)
62 static int armv7_allocate_pmc(enum pmc_event _pe, char *_ctrspec,
63     struct pmc_op_pmcallocate *_pmc_config);
64 #endif
65 #if defined(__aarch64__)
66 static int arm64_allocate_pmc(enum pmc_event _pe, char *_ctrspec,
67     struct pmc_op_pmcallocate *_pmc_config);
68 #endif
69 static int soft_allocate_pmc(enum pmc_event _pe, char *_ctrspec,
70     struct pmc_op_pmcallocate *_pmc_config);
71 
72 #if defined(__powerpc__)
73 static int powerpc_allocate_pmc(enum pmc_event _pe, char* ctrspec,
74 			     struct pmc_op_pmcallocate *_pmc_config);
75 #endif /* __powerpc__ */
76 
77 #define PMC_CALL(cmd, params)				\
78 	syscall(pmc_syscall, PMC_OP_##cmd, (params))
79 
80 /*
81  * Event aliases provide a way for the user to ask for generic events
82  * like "cache-misses", or "instructions-retired".  These aliases are
83  * mapped to the appropriate canonical event descriptions using a
84  * lookup table.
85  */
86 struct pmc_event_alias {
87 	const char	*pm_alias;
88 	const char	*pm_spec;
89 };
90 
91 static const struct pmc_event_alias *pmc_mdep_event_aliases;
92 
93 /*
94  * The pmc_event_descr structure maps symbolic names known to the user
95  * to integer codes used by the PMC KLD.
96  */
97 struct pmc_event_descr {
98 	const char	*pm_ev_name;
99 	enum pmc_event	pm_ev_code;
100 };
101 
102 /*
103  * The pmc_class_descr structure maps class name prefixes for
104  * event names to event tables and other PMC class data.
105  */
106 struct pmc_class_descr {
107 	const char	*pm_evc_name;
108 	size_t		pm_evc_name_size;
109 	enum pmc_class	pm_evc_class;
110 	const struct pmc_event_descr *pm_evc_event_table;
111 	size_t		pm_evc_event_table_size;
112 	int		(*pm_evc_allocate_pmc)(enum pmc_event _pe,
113 			    char *_ctrspec, struct pmc_op_pmcallocate *_pa);
114 };
115 
116 #define	PMC_TABLE_SIZE(N)	(sizeof(N)/sizeof(N[0]))
117 #define	PMC_EVENT_TABLE_SIZE(N)	PMC_TABLE_SIZE(N##_event_table)
118 
119 #undef	__PMC_EV
120 #define	__PMC_EV(C,N) { #N, PMC_EV_ ## C ## _ ## N },
121 
122 /*
123  * PMC_CLASSDEP_TABLE(NAME, CLASS)
124  *
125  * Define a table mapping event names and aliases to HWPMC event IDs.
126  */
127 #define	PMC_CLASSDEP_TABLE(N, C)				\
128 	static const struct pmc_event_descr N##_event_table[] =	\
129 	{							\
130 		__PMC_EV_##C()					\
131 	}
132 
133 PMC_CLASSDEP_TABLE(iaf, IAF);
134 PMC_CLASSDEP_TABLE(k8, K8);
135 PMC_CLASSDEP_TABLE(armv7, ARMV7);
136 PMC_CLASSDEP_TABLE(armv8, ARMV8);
137 PMC_CLASSDEP_TABLE(ppc7450, PPC7450);
138 PMC_CLASSDEP_TABLE(ppc970, PPC970);
139 PMC_CLASSDEP_TABLE(e500, E500);
140 
141 static struct pmc_event_descr soft_event_table[PMC_EV_DYN_COUNT];
142 
143 #undef	__PMC_EV_ALIAS
144 #define	__PMC_EV_ALIAS(N,CODE) 	{ N, PMC_EV_##CODE },
145 
146 /*
147  * TODO: Factor out the __PMC_EV_ARMV7/8 list into a single separate table
148  * rather than duplicating for each core.
149  */
150 
151 static const struct pmc_event_descr cortex_a8_event_table[] =
152 {
153 	__PMC_EV_ALIAS_ARMV7_CORTEX_A8()
154 	__PMC_EV_ARMV7()
155 };
156 
157 static const struct pmc_event_descr cortex_a9_event_table[] =
158 {
159 	__PMC_EV_ALIAS_ARMV7_CORTEX_A9()
160 	__PMC_EV_ARMV7()
161 };
162 
163 static const struct pmc_event_descr cortex_a53_event_table[] =
164 {
165 	__PMC_EV_ALIAS_ARMV8_CORTEX_A53()
166 	__PMC_EV_ARMV8()
167 };
168 
169 static const struct pmc_event_descr cortex_a57_event_table[] =
170 {
171 	__PMC_EV_ALIAS_ARMV8_CORTEX_A57()
172 	__PMC_EV_ARMV8()
173 };
174 
175 static const struct pmc_event_descr cortex_a76_event_table[] =
176 {
177 	__PMC_EV_ALIAS_ARMV8_CORTEX_A76()
178 	__PMC_EV_ARMV8()
179 };
180 
181 static const struct pmc_event_descr tsc_event_table[] =
182 {
183 	__PMC_EV_ALIAS_TSC()
184 };
185 
186 #undef	PMC_CLASS_TABLE_DESC
187 #define	PMC_CLASS_TABLE_DESC(NAME, CLASS, EVENTS, ALLOCATOR)	\
188 static const struct pmc_class_descr NAME##_class_table_descr =	\
189 	{							\
190 		.pm_evc_name  = #CLASS "-",			\
191 		.pm_evc_name_size = sizeof(#CLASS "-") - 1,	\
192 		.pm_evc_class = PMC_CLASS_##CLASS ,		\
193 		.pm_evc_event_table = EVENTS##_event_table ,	\
194 		.pm_evc_event_table_size = 			\
195 			PMC_EVENT_TABLE_SIZE(EVENTS),		\
196 		.pm_evc_allocate_pmc = ALLOCATOR##_allocate_pmc	\
197 	}
198 
199 #if	defined(__i386__) || defined(__amd64__)
200 PMC_CLASS_TABLE_DESC(k8, K8, k8, k8);
201 #endif
202 #if	defined(__i386__) || defined(__amd64__)
203 PMC_CLASS_TABLE_DESC(tsc, TSC, tsc, tsc);
204 #endif
205 #if	defined(__arm__)
206 PMC_CLASS_TABLE_DESC(cortex_a8, ARMV7, cortex_a8, armv7);
207 PMC_CLASS_TABLE_DESC(cortex_a9, ARMV7, cortex_a9, armv7);
208 #endif
209 #if	defined(__aarch64__)
210 PMC_CLASS_TABLE_DESC(cortex_a53, ARMV8, cortex_a53, arm64);
211 PMC_CLASS_TABLE_DESC(cortex_a57, ARMV8, cortex_a57, arm64);
212 PMC_CLASS_TABLE_DESC(cortex_a76, ARMV8, cortex_a76, arm64);
213 #endif
214 #if defined(__powerpc__)
215 PMC_CLASS_TABLE_DESC(ppc7450, PPC7450, ppc7450, powerpc);
216 PMC_CLASS_TABLE_DESC(ppc970, PPC970, ppc970, powerpc);
217 PMC_CLASS_TABLE_DESC(e500, E500, e500, powerpc);
218 #endif
219 
220 static struct pmc_class_descr soft_class_table_descr =
221 {
222 	.pm_evc_name  = "SOFT-",
223 	.pm_evc_name_size = sizeof("SOFT-") - 1,
224 	.pm_evc_class = PMC_CLASS_SOFT,
225 	.pm_evc_event_table = NULL,
226 	.pm_evc_event_table_size = 0,
227 	.pm_evc_allocate_pmc = soft_allocate_pmc
228 };
229 
230 #undef	PMC_CLASS_TABLE_DESC
231 
232 static const struct pmc_class_descr **pmc_class_table;
233 #define	PMC_CLASS_TABLE_SIZE	cpu_info.pm_nclass
234 
235 /*
236  * Mapping tables, mapping enumeration values to human readable
237  * strings.
238  */
239 
240 static const char * pmc_capability_names[] = {
241 #undef	__PMC_CAP
242 #define	__PMC_CAP(N,V,D)	#N ,
243 	__PMC_CAPS()
244 };
245 
246 struct pmc_class_map {
247 	enum pmc_class	pm_class;
248 	const char	*pm_name;
249 };
250 
251 static const struct pmc_class_map pmc_class_names[] = {
252 #undef	__PMC_CLASS
253 #define __PMC_CLASS(S,V,D) { .pm_class = PMC_CLASS_##S, .pm_name = #S } ,
254 	__PMC_CLASSES()
255 };
256 
257 struct pmc_cputype_map {
258 	enum pmc_cputype pm_cputype;
259 	const char	*pm_name;
260 };
261 
262 static const struct pmc_cputype_map pmc_cputype_names[] = {
263 #undef	__PMC_CPU
264 #define	__PMC_CPU(S, V, D) { .pm_cputype = PMC_CPU_##S, .pm_name = #S } ,
265 	__PMC_CPUS()
266 };
267 
268 static const char * pmc_disposition_names[] = {
269 #undef	__PMC_DISP
270 #define	__PMC_DISP(D)	#D ,
271 	__PMC_DISPOSITIONS()
272 };
273 
274 static const char * pmc_mode_names[] = {
275 #undef  __PMC_MODE
276 #define __PMC_MODE(M,N)	#M ,
277 	__PMC_MODES()
278 };
279 
280 static const char * pmc_state_names[] = {
281 #undef  __PMC_STATE
282 #define __PMC_STATE(S) #S ,
283 	__PMC_STATES()
284 };
285 
286 /*
287  * Filled in by pmc_init().
288  */
289 static int pmc_syscall = -1;
290 static struct pmc_cpuinfo cpu_info;
291 static struct pmc_op_getdyneventinfo soft_event_info;
292 
293 /* Event masks for events */
294 struct pmc_masks {
295 	const char	*pm_name;
296 	const uint64_t	pm_value;
297 };
298 #define	PMCMASK(N,V)	{ .pm_name = #N, .pm_value = (V) }
299 #define	NULLMASK	{ .pm_name = NULL }
300 
301 #if defined(__amd64__) || defined(__i386__)
302 static int
303 pmc_parse_mask(const struct pmc_masks *pmask, char *p, uint64_t *evmask)
304 {
305 	const struct pmc_masks *pm;
306 	char *q, *r;
307 	int c;
308 
309 	if (pmask == NULL)	/* no mask keywords */
310 		return (-1);
311 	q = strchr(p, '=');	/* skip '=' */
312 	if (*++q == '\0')	/* no more data */
313 		return (-1);
314 	c = 0;			/* count of mask keywords seen */
315 	while ((r = strsep(&q, "+")) != NULL) {
316 		for (pm = pmask; pm->pm_name && strcasecmp(r, pm->pm_name);
317 		    pm++)
318 			;
319 		if (pm->pm_name == NULL) /* not found */
320 			return (-1);
321 		*evmask |= pm->pm_value;
322 		c++;
323 	}
324 	return (c);
325 }
326 #endif
327 
328 #define	KWMATCH(p,kw)		(strcasecmp((p), (kw)) == 0)
329 #define	KWPREFIXMATCH(p,kw)	(strncasecmp((p), (kw), sizeof((kw)) - 1) == 0)
330 #define	EV_ALIAS(N,S)		{ .pm_alias = N, .pm_spec = S }
331 
332 #if defined(__amd64__) || defined(__i386__)
333 /*
334  * AMD K8 PMCs.
335  *
336  */
337 
338 static struct pmc_event_alias k8_aliases[] = {
339 	EV_ALIAS("branches",		"k8-fr-retired-taken-branches"),
340 	EV_ALIAS("branch-mispredicts",
341 	    "k8-fr-retired-taken-branches-mispredicted"),
342 	EV_ALIAS("cycles",		"tsc"),
343 	EV_ALIAS("dc-misses",		"k8-dc-miss"),
344 	EV_ALIAS("ic-misses",		"k8-ic-miss"),
345 	EV_ALIAS("instructions",	"k8-fr-retired-x86-instructions"),
346 	EV_ALIAS("interrupts",		"k8-fr-taken-hardware-interrupts"),
347 	EV_ALIAS("unhalted-cycles",	"k8-bu-cpu-clk-unhalted"),
348 	EV_ALIAS(NULL, NULL)
349 };
350 
351 #define	__K8MASK(N,V) PMCMASK(N,(1 << (V)))
352 
353 /*
354  * Parsing tables
355  */
356 
357 /* fp dispatched fpu ops */
358 static const struct pmc_masks k8_mask_fdfo[] = {
359 	__K8MASK(add-pipe-excluding-junk-ops,	0),
360 	__K8MASK(multiply-pipe-excluding-junk-ops,	1),
361 	__K8MASK(store-pipe-excluding-junk-ops,	2),
362 	__K8MASK(add-pipe-junk-ops,		3),
363 	__K8MASK(multiply-pipe-junk-ops,	4),
364 	__K8MASK(store-pipe-junk-ops,		5),
365 	NULLMASK
366 };
367 
368 /* ls segment register loads */
369 static const struct pmc_masks k8_mask_lsrl[] = {
370 	__K8MASK(es,	0),
371 	__K8MASK(cs,	1),
372 	__K8MASK(ss,	2),
373 	__K8MASK(ds,	3),
374 	__K8MASK(fs,	4),
375 	__K8MASK(gs,	5),
376 	__K8MASK(hs,	6),
377 	NULLMASK
378 };
379 
380 /* ls locked operation */
381 static const struct pmc_masks k8_mask_llo[] = {
382 	__K8MASK(locked-instructions,	0),
383 	__K8MASK(cycles-in-request,	1),
384 	__K8MASK(cycles-to-complete,	2),
385 	NULLMASK
386 };
387 
388 /* dc refill from {l2,system} and dc copyback */
389 static const struct pmc_masks k8_mask_dc[] = {
390 	__K8MASK(invalid,	0),
391 	__K8MASK(shared,	1),
392 	__K8MASK(exclusive,	2),
393 	__K8MASK(owner,		3),
394 	__K8MASK(modified,	4),
395 	NULLMASK
396 };
397 
398 /* dc one bit ecc error */
399 static const struct pmc_masks k8_mask_dobee[] = {
400 	__K8MASK(scrubber,	0),
401 	__K8MASK(piggyback,	1),
402 	NULLMASK
403 };
404 
405 /* dc dispatched prefetch instructions */
406 static const struct pmc_masks k8_mask_ddpi[] = {
407 	__K8MASK(load,	0),
408 	__K8MASK(store,	1),
409 	__K8MASK(nta,	2),
410 	NULLMASK
411 };
412 
413 /* dc dcache accesses by locks */
414 static const struct pmc_masks k8_mask_dabl[] = {
415 	__K8MASK(accesses,	0),
416 	__K8MASK(misses,	1),
417 	NULLMASK
418 };
419 
420 /* bu internal l2 request */
421 static const struct pmc_masks k8_mask_bilr[] = {
422 	__K8MASK(ic-fill,	0),
423 	__K8MASK(dc-fill,	1),
424 	__K8MASK(tlb-reload,	2),
425 	__K8MASK(tag-snoop,	3),
426 	__K8MASK(cancelled,	4),
427 	NULLMASK
428 };
429 
430 /* bu fill request l2 miss */
431 static const struct pmc_masks k8_mask_bfrlm[] = {
432 	__K8MASK(ic-fill,	0),
433 	__K8MASK(dc-fill,	1),
434 	__K8MASK(tlb-reload,	2),
435 	NULLMASK
436 };
437 
438 /* bu fill into l2 */
439 static const struct pmc_masks k8_mask_bfil[] = {
440 	__K8MASK(dirty-l2-victim,	0),
441 	__K8MASK(victim-from-l2,	1),
442 	NULLMASK
443 };
444 
445 /* fr retired fpu instructions */
446 static const struct pmc_masks k8_mask_frfi[] = {
447 	__K8MASK(x87,			0),
448 	__K8MASK(mmx-3dnow,		1),
449 	__K8MASK(packed-sse-sse2,	2),
450 	__K8MASK(scalar-sse-sse2,	3),
451 	NULLMASK
452 };
453 
454 /* fr retired fastpath double op instructions */
455 static const struct pmc_masks k8_mask_frfdoi[] = {
456 	__K8MASK(low-op-pos-0,		0),
457 	__K8MASK(low-op-pos-1,		1),
458 	__K8MASK(low-op-pos-2,		2),
459 	NULLMASK
460 };
461 
462 /* fr fpu exceptions */
463 static const struct pmc_masks k8_mask_ffe[] = {
464 	__K8MASK(x87-reclass-microfaults,	0),
465 	__K8MASK(sse-retype-microfaults,	1),
466 	__K8MASK(sse-reclass-microfaults,	2),
467 	__K8MASK(sse-and-x87-microtraps,	3),
468 	NULLMASK
469 };
470 
471 /* nb memory controller page access event */
472 static const struct pmc_masks k8_mask_nmcpae[] = {
473 	__K8MASK(page-hit,	0),
474 	__K8MASK(page-miss,	1),
475 	__K8MASK(page-conflict,	2),
476 	NULLMASK
477 };
478 
479 /* nb memory controller turnaround */
480 static const struct pmc_masks k8_mask_nmct[] = {
481 	__K8MASK(dimm-turnaround,		0),
482 	__K8MASK(read-to-write-turnaround,	1),
483 	__K8MASK(write-to-read-turnaround,	2),
484 	NULLMASK
485 };
486 
487 /* nb memory controller bypass saturation */
488 static const struct pmc_masks k8_mask_nmcbs[] = {
489 	__K8MASK(memory-controller-hi-pri-bypass,	0),
490 	__K8MASK(memory-controller-lo-pri-bypass,	1),
491 	__K8MASK(dram-controller-interface-bypass,	2),
492 	__K8MASK(dram-controller-queue-bypass,		3),
493 	NULLMASK
494 };
495 
496 /* nb sized commands */
497 static const struct pmc_masks k8_mask_nsc[] = {
498 	__K8MASK(nonpostwrszbyte,	0),
499 	__K8MASK(nonpostwrszdword,	1),
500 	__K8MASK(postwrszbyte,		2),
501 	__K8MASK(postwrszdword,		3),
502 	__K8MASK(rdszbyte,		4),
503 	__K8MASK(rdszdword,		5),
504 	__K8MASK(rdmodwr,		6),
505 	NULLMASK
506 };
507 
508 /* nb probe result */
509 static const struct pmc_masks k8_mask_npr[] = {
510 	__K8MASK(probe-miss,		0),
511 	__K8MASK(probe-hit,		1),
512 	__K8MASK(probe-hit-dirty-no-memory-cancel, 2),
513 	__K8MASK(probe-hit-dirty-with-memory-cancel, 3),
514 	NULLMASK
515 };
516 
517 /* nb hypertransport bus bandwidth */
518 static const struct pmc_masks k8_mask_nhbb[] = { /* HT bus bandwidth */
519 	__K8MASK(command,	0),
520 	__K8MASK(data,	1),
521 	__K8MASK(buffer-release, 2),
522 	__K8MASK(nop,	3),
523 	NULLMASK
524 };
525 
526 #undef	__K8MASK
527 
528 #define	K8_KW_COUNT	"count"
529 #define	K8_KW_EDGE	"edge"
530 #define	K8_KW_INV	"inv"
531 #define	K8_KW_MASK	"mask"
532 #define	K8_KW_OS	"os"
533 #define	K8_KW_USR	"usr"
534 
535 static int
536 k8_allocate_pmc(enum pmc_event pe, char *ctrspec,
537     struct pmc_op_pmcallocate *pmc_config)
538 {
539 	char		*e, *p, *q;
540 	int		n;
541 	uint32_t	count;
542 	uint64_t	evmask;
543 	const struct pmc_masks	*pm, *pmask;
544 
545 	pmc_config->pm_caps |= (PMC_CAP_READ | PMC_CAP_WRITE);
546 	pmc_config->pm_md.pm_amd.pm_amd_config = 0;
547 
548 	pmask = NULL;
549 	evmask = 0;
550 
551 #define	__K8SETMASK(M) pmask = k8_mask_##M
552 
553 	/* setup parsing tables */
554 	switch (pe) {
555 	case PMC_EV_K8_FP_DISPATCHED_FPU_OPS:
556 		__K8SETMASK(fdfo);
557 		break;
558 	case PMC_EV_K8_LS_SEGMENT_REGISTER_LOAD:
559 		__K8SETMASK(lsrl);
560 		break;
561 	case PMC_EV_K8_LS_LOCKED_OPERATION:
562 		__K8SETMASK(llo);
563 		break;
564 	case PMC_EV_K8_DC_REFILL_FROM_L2:
565 	case PMC_EV_K8_DC_REFILL_FROM_SYSTEM:
566 	case PMC_EV_K8_DC_COPYBACK:
567 		__K8SETMASK(dc);
568 		break;
569 	case PMC_EV_K8_DC_ONE_BIT_ECC_ERROR:
570 		__K8SETMASK(dobee);
571 		break;
572 	case PMC_EV_K8_DC_DISPATCHED_PREFETCH_INSTRUCTIONS:
573 		__K8SETMASK(ddpi);
574 		break;
575 	case PMC_EV_K8_DC_DCACHE_ACCESSES_BY_LOCKS:
576 		__K8SETMASK(dabl);
577 		break;
578 	case PMC_EV_K8_BU_INTERNAL_L2_REQUEST:
579 		__K8SETMASK(bilr);
580 		break;
581 	case PMC_EV_K8_BU_FILL_REQUEST_L2_MISS:
582 		__K8SETMASK(bfrlm);
583 		break;
584 	case PMC_EV_K8_BU_FILL_INTO_L2:
585 		__K8SETMASK(bfil);
586 		break;
587 	case PMC_EV_K8_FR_RETIRED_FPU_INSTRUCTIONS:
588 		__K8SETMASK(frfi);
589 		break;
590 	case PMC_EV_K8_FR_RETIRED_FASTPATH_DOUBLE_OP_INSTRUCTIONS:
591 		__K8SETMASK(frfdoi);
592 		break;
593 	case PMC_EV_K8_FR_FPU_EXCEPTIONS:
594 		__K8SETMASK(ffe);
595 		break;
596 	case PMC_EV_K8_NB_MEMORY_CONTROLLER_PAGE_ACCESS_EVENT:
597 		__K8SETMASK(nmcpae);
598 		break;
599 	case PMC_EV_K8_NB_MEMORY_CONTROLLER_TURNAROUND:
600 		__K8SETMASK(nmct);
601 		break;
602 	case PMC_EV_K8_NB_MEMORY_CONTROLLER_BYPASS_SATURATION:
603 		__K8SETMASK(nmcbs);
604 		break;
605 	case PMC_EV_K8_NB_SIZED_COMMANDS:
606 		__K8SETMASK(nsc);
607 		break;
608 	case PMC_EV_K8_NB_PROBE_RESULT:
609 		__K8SETMASK(npr);
610 		break;
611 	case PMC_EV_K8_NB_HT_BUS0_BANDWIDTH:
612 	case PMC_EV_K8_NB_HT_BUS1_BANDWIDTH:
613 	case PMC_EV_K8_NB_HT_BUS2_BANDWIDTH:
614 		__K8SETMASK(nhbb);
615 		break;
616 
617 	default:
618 		break;		/* no options defined */
619 	}
620 
621 	while ((p = strsep(&ctrspec, ",")) != NULL) {
622 		if (KWPREFIXMATCH(p, K8_KW_COUNT "=")) {
623 			q = strchr(p, '=');
624 			if (*++q == '\0') /* skip '=' */
625 				return (-1);
626 
627 			count = strtol(q, &e, 0);
628 			if (e == q || *e != '\0')
629 				return (-1);
630 
631 			pmc_config->pm_caps |= PMC_CAP_THRESHOLD;
632 			pmc_config->pm_md.pm_amd.pm_amd_config |=
633 			    AMD_PMC_TO_COUNTER(count);
634 
635 		} else if (KWMATCH(p, K8_KW_EDGE)) {
636 			pmc_config->pm_caps |= PMC_CAP_EDGE;
637 		} else if (KWMATCH(p, K8_KW_INV)) {
638 			pmc_config->pm_caps |= PMC_CAP_INVERT;
639 		} else if (KWPREFIXMATCH(p, K8_KW_MASK "=")) {
640 			if ((n = pmc_parse_mask(pmask, p, &evmask)) < 0)
641 				return (-1);
642 			pmc_config->pm_caps |= PMC_CAP_QUALIFIER;
643 		} else if (KWMATCH(p, K8_KW_OS)) {
644 			pmc_config->pm_caps |= PMC_CAP_SYSTEM;
645 		} else if (KWMATCH(p, K8_KW_USR)) {
646 			pmc_config->pm_caps |= PMC_CAP_USER;
647 		} else
648 			return (-1);
649 	}
650 
651 	/* other post processing */
652 	switch (pe) {
653 	case PMC_EV_K8_FP_DISPATCHED_FPU_OPS:
654 	case PMC_EV_K8_FP_CYCLES_WITH_NO_FPU_OPS_RETIRED:
655 	case PMC_EV_K8_FP_DISPATCHED_FPU_FAST_FLAG_OPS:
656 	case PMC_EV_K8_FR_RETIRED_FASTPATH_DOUBLE_OP_INSTRUCTIONS:
657 	case PMC_EV_K8_FR_RETIRED_FPU_INSTRUCTIONS:
658 	case PMC_EV_K8_FR_FPU_EXCEPTIONS:
659 		/* XXX only available in rev B and later */
660 		break;
661 	case PMC_EV_K8_DC_DCACHE_ACCESSES_BY_LOCKS:
662 		/* XXX only available in rev C and later */
663 		break;
664 	case PMC_EV_K8_LS_LOCKED_OPERATION:
665 		/* XXX CPU Rev A,B evmask is to be zero */
666 		if (evmask & (evmask - 1)) /* > 1 bit set */
667 			return (-1);
668 		if (evmask == 0) {
669 			evmask = 0x01; /* Rev C and later: #instrs */
670 			pmc_config->pm_caps |= PMC_CAP_QUALIFIER;
671 		}
672 		break;
673 	default:
674 		if (evmask == 0 && pmask != NULL) {
675 			for (pm = pmask; pm->pm_name; pm++)
676 				evmask |= pm->pm_value;
677 			pmc_config->pm_caps |= PMC_CAP_QUALIFIER;
678 		}
679 	}
680 
681 	if (pmc_config->pm_caps & PMC_CAP_QUALIFIER)
682 		pmc_config->pm_md.pm_amd.pm_amd_config =
683 		    AMD_PMC_TO_UNITMASK(evmask);
684 
685 	return (0);
686 }
687 
688 #endif
689 
690 #if	defined(__i386__) || defined(__amd64__)
691 static int
692 tsc_allocate_pmc(enum pmc_event pe, char *ctrspec,
693     struct pmc_op_pmcallocate *pmc_config)
694 {
695 	if (pe != PMC_EV_TSC_TSC)
696 		return (-1);
697 
698 	/* TSC events must be unqualified. */
699 	if (ctrspec && *ctrspec != '\0')
700 		return (-1);
701 
702 	pmc_config->pm_md.pm_amd.pm_amd_config = 0;
703 	pmc_config->pm_caps |= PMC_CAP_READ;
704 
705 	return (0);
706 }
707 #endif
708 
709 static struct pmc_event_alias generic_aliases[] = {
710 	EV_ALIAS("instructions",		"SOFT-CLOCK.HARD"),
711 	EV_ALIAS(NULL, NULL)
712 };
713 
714 static int
715 soft_allocate_pmc(enum pmc_event pe, char *ctrspec,
716     struct pmc_op_pmcallocate *pmc_config)
717 {
718 	(void)ctrspec;
719 	(void)pmc_config;
720 
721 	if ((int)pe < PMC_EV_SOFT_FIRST || (int)pe > PMC_EV_SOFT_LAST)
722 		return (-1);
723 
724 	pmc_config->pm_caps |= (PMC_CAP_READ | PMC_CAP_WRITE);
725 	return (0);
726 }
727 
728 #if	defined(__arm__)
729 static struct pmc_event_alias cortex_a8_aliases[] = {
730 	EV_ALIAS("dc-misses",		"L1_DCACHE_REFILL"),
731 	EV_ALIAS("ic-misses",		"L1_ICACHE_REFILL"),
732 	EV_ALIAS("instructions",	"INSTR_EXECUTED"),
733 	EV_ALIAS(NULL, NULL)
734 };
735 
736 static struct pmc_event_alias cortex_a9_aliases[] = {
737 	EV_ALIAS("dc-misses",		"L1_DCACHE_REFILL"),
738 	EV_ALIAS("ic-misses",		"L1_ICACHE_REFILL"),
739 	EV_ALIAS("instructions",	"INSTR_EXECUTED"),
740 	EV_ALIAS(NULL, NULL)
741 };
742 
743 static int
744 armv7_allocate_pmc(enum pmc_event pe, char *ctrspec __unused,
745     struct pmc_op_pmcallocate *pmc_config __unused)
746 {
747 	switch (pe) {
748 	default:
749 		break;
750 	}
751 
752 	return (0);
753 }
754 #endif
755 
756 #if	defined(__aarch64__)
757 static struct pmc_event_alias cortex_a53_aliases[] = {
758 	EV_ALIAS(NULL, NULL)
759 };
760 static struct pmc_event_alias cortex_a57_aliases[] = {
761 	EV_ALIAS(NULL, NULL)
762 };
763 static struct pmc_event_alias cortex_a76_aliases[] = {
764 	EV_ALIAS(NULL, NULL)
765 };
766 static int
767 arm64_allocate_pmc(enum pmc_event pe, char *ctrspec __unused,
768     struct pmc_op_pmcallocate *pmc_config __unused)
769 {
770 	switch (pe) {
771 	default:
772 		break;
773 	}
774 
775 	return (0);
776 }
777 #endif
778 
779 #if defined(__powerpc__)
780 
781 static struct pmc_event_alias ppc7450_aliases[] = {
782 	EV_ALIAS("instructions",	"INSTR_COMPLETED"),
783 	EV_ALIAS("branches",		"BRANCHES_COMPLETED"),
784 	EV_ALIAS("branch-mispredicts",	"MISPREDICTED_BRANCHES"),
785 	EV_ALIAS(NULL, NULL)
786 };
787 
788 static struct pmc_event_alias ppc970_aliases[] = {
789 	EV_ALIAS("instructions", "INSTR_COMPLETED"),
790 	EV_ALIAS("cycles",       "CYCLES"),
791 	EV_ALIAS(NULL, NULL)
792 };
793 
794 static struct pmc_event_alias e500_aliases[] = {
795 	EV_ALIAS("instructions", "INSTR_COMPLETED"),
796 	EV_ALIAS("cycles",       "CYCLES"),
797 	EV_ALIAS(NULL, NULL)
798 };
799 
800 #define	POWERPC_KW_OS		"os"
801 #define	POWERPC_KW_USR		"usr"
802 #define	POWERPC_KW_ANYTHREAD	"anythread"
803 
804 static int
805 powerpc_allocate_pmc(enum pmc_event pe, char *ctrspec __unused,
806 		     struct pmc_op_pmcallocate *pmc_config __unused)
807 {
808 	char *p;
809 
810 	(void) pe;
811 
812 	pmc_config->pm_caps |= (PMC_CAP_READ | PMC_CAP_WRITE);
813 
814 	while ((p = strsep(&ctrspec, ",")) != NULL) {
815 		if (KWMATCH(p, POWERPC_KW_OS))
816 			pmc_config->pm_caps |= PMC_CAP_SYSTEM;
817 		else if (KWMATCH(p, POWERPC_KW_USR))
818 			pmc_config->pm_caps |= PMC_CAP_USER;
819 		else if (KWMATCH(p, POWERPC_KW_ANYTHREAD))
820 			pmc_config->pm_caps |= (PMC_CAP_USER | PMC_CAP_SYSTEM);
821 		else
822 			return (-1);
823 	}
824 
825 	return (0);
826 }
827 
828 #endif /* __powerpc__ */
829 
830 
831 /*
832  * Match an event name `name' with its canonical form.
833  *
834  * Matches are case insensitive and spaces, periods, underscores and
835  * hyphen characters are considered to match each other.
836  *
837  * Returns 1 for a match, 0 otherwise.
838  */
839 
840 static int
841 pmc_match_event_name(const char *name, const char *canonicalname)
842 {
843 	int cc, nc;
844 	const unsigned char *c, *n;
845 
846 	c = (const unsigned char *) canonicalname;
847 	n = (const unsigned char *) name;
848 
849 	for (; (nc = *n) && (cc = *c); n++, c++) {
850 
851 		if ((nc == ' ' || nc == '_' || nc == '-' || nc == '.') &&
852 		    (cc == ' ' || cc == '_' || cc == '-' || cc == '.'))
853 			continue;
854 
855 		if (toupper(nc) == toupper(cc))
856 			continue;
857 
858 
859 		return (0);
860 	}
861 
862 	if (*n == '\0' && *c == '\0')
863 		return (1);
864 
865 	return (0);
866 }
867 
868 /*
869  * Match an event name against all the event named supported by a
870  * PMC class.
871  *
872  * Returns an event descriptor pointer on match or NULL otherwise.
873  */
874 static const struct pmc_event_descr *
875 pmc_match_event_class(const char *name,
876     const struct pmc_class_descr *pcd)
877 {
878 	size_t n;
879 	const struct pmc_event_descr *ev;
880 
881 	ev = pcd->pm_evc_event_table;
882 	for (n = 0; n < pcd->pm_evc_event_table_size; n++, ev++)
883 		if (pmc_match_event_name(name, ev->pm_ev_name))
884 			return (ev);
885 
886 	return (NULL);
887 }
888 
889 /*
890  * API entry points
891  */
892 
893 int
894 pmc_allocate(const char *ctrspec, enum pmc_mode mode,
895     uint32_t flags, int cpu, pmc_id_t *pmcid,
896     uint64_t count)
897 {
898 	size_t n;
899 	int retval;
900 	char *r, *spec_copy;
901 	const char *ctrname;
902 	const struct pmc_event_descr *ev;
903 	const struct pmc_event_alias *alias;
904 	struct pmc_op_pmcallocate pmc_config;
905 	const struct pmc_class_descr *pcd;
906 
907 	spec_copy = NULL;
908 	retval    = -1;
909 
910 	if (mode != PMC_MODE_SS && mode != PMC_MODE_TS &&
911 	    mode != PMC_MODE_SC && mode != PMC_MODE_TC) {
912 		errno = EINVAL;
913 		goto out;
914 	}
915 	bzero(&pmc_config, sizeof(pmc_config));
916 	pmc_config.pm_cpu   = cpu;
917 	pmc_config.pm_mode  = mode;
918 	pmc_config.pm_flags = flags;
919 	pmc_config.pm_count = count;
920 	if (PMC_IS_SAMPLING_MODE(mode))
921 		pmc_config.pm_caps |= PMC_CAP_INTERRUPT;
922 
923 	/*
924 	 * Try to pull the raw event ID directly from the pmu-events table. If
925 	 * this is unsupported on the platform, or the event is not found,
926 	 * continue with searching the regular event tables.
927 	 */
928 	r = spec_copy = strdup(ctrspec);
929 	ctrname = strsep(&r, ",");
930 	if (pmc_pmu_enabled()) {
931 		if (pmc_pmu_pmcallocate(ctrname, &pmc_config) == 0)
932 			goto found;
933 
934 		/* Otherwise, reset any changes */
935 		pmc_config.pm_ev = 0;
936 		pmc_config.pm_caps = 0;
937 		pmc_config.pm_class = 0;
938 	}
939 	free(spec_copy);
940 	spec_copy = NULL;
941 
942 	/* replace an event alias with the canonical event specifier */
943 	if (pmc_mdep_event_aliases)
944 		for (alias = pmc_mdep_event_aliases; alias->pm_alias; alias++)
945 			if (!strcasecmp(ctrspec, alias->pm_alias)) {
946 				spec_copy = strdup(alias->pm_spec);
947 				break;
948 			}
949 
950 	if (spec_copy == NULL)
951 		spec_copy = strdup(ctrspec);
952 
953 	r = spec_copy;
954 	ctrname = strsep(&r, ",");
955 
956 	/*
957 	 * If a explicit class prefix was given by the user, restrict the
958 	 * search for the event to the specified PMC class.
959 	 */
960 	ev = NULL;
961 	for (n = 0; n < PMC_CLASS_TABLE_SIZE; n++) {
962 		pcd = pmc_class_table[n];
963 		if (pcd != NULL && strncasecmp(ctrname, pcd->pm_evc_name,
964 		    pcd->pm_evc_name_size) == 0) {
965 			if ((ev = pmc_match_event_class(ctrname +
966 			    pcd->pm_evc_name_size, pcd)) == NULL) {
967 				errno = EINVAL;
968 				goto out;
969 			}
970 			break;
971 		}
972 	}
973 
974 	/*
975 	 * Otherwise, search for this event in all compatible PMC
976 	 * classes.
977 	 */
978 	for (n = 0; ev == NULL && n < PMC_CLASS_TABLE_SIZE; n++) {
979 		pcd = pmc_class_table[n];
980 		if (pcd != NULL)
981 			ev = pmc_match_event_class(ctrname, pcd);
982 	}
983 
984 	if (ev == NULL) {
985 		errno = EINVAL;
986 		goto out;
987 	}
988 
989 	pmc_config.pm_ev    = ev->pm_ev_code;
990 	pmc_config.pm_class = pcd->pm_evc_class;
991 
992  	if (pcd->pm_evc_allocate_pmc(ev->pm_ev_code, r, &pmc_config) < 0) {
993 		errno = EINVAL;
994 		goto out;
995 	}
996 
997 found:
998 	if (PMC_CALL(PMCALLOCATE, &pmc_config) == 0) {
999 		*pmcid = pmc_config.pm_pmcid;
1000 		retval = 0;
1001 	}
1002 out:
1003 	if (spec_copy)
1004 		free(spec_copy);
1005 
1006 	return (retval);
1007 }
1008 
1009 int
1010 pmc_attach(pmc_id_t pmc, pid_t pid)
1011 {
1012 	struct pmc_op_pmcattach pmc_attach_args;
1013 
1014 	pmc_attach_args.pm_pmc = pmc;
1015 	pmc_attach_args.pm_pid = pid;
1016 
1017 	return (PMC_CALL(PMCATTACH, &pmc_attach_args));
1018 }
1019 
1020 int
1021 pmc_capabilities(pmc_id_t pmcid, uint32_t *caps)
1022 {
1023 	unsigned int i;
1024 	enum pmc_class cl;
1025 
1026 	cl = PMC_ID_TO_CLASS(pmcid);
1027 	for (i = 0; i < cpu_info.pm_nclass; i++)
1028 		if (cpu_info.pm_classes[i].pm_class == cl) {
1029 			*caps = cpu_info.pm_classes[i].pm_caps;
1030 			return (0);
1031 		}
1032 	errno = EINVAL;
1033 	return (-1);
1034 }
1035 
1036 int
1037 pmc_configure_logfile(int fd)
1038 {
1039 	struct pmc_op_configurelog cla;
1040 
1041 	cla.pm_logfd = fd;
1042 	if (PMC_CALL(CONFIGURELOG, &cla) < 0)
1043 		return (-1);
1044 	return (0);
1045 }
1046 
1047 int
1048 pmc_cpuinfo(const struct pmc_cpuinfo **pci)
1049 {
1050 	if (pmc_syscall == -1) {
1051 		errno = ENXIO;
1052 		return (-1);
1053 	}
1054 
1055 	*pci = &cpu_info;
1056 	return (0);
1057 }
1058 
1059 int
1060 pmc_detach(pmc_id_t pmc, pid_t pid)
1061 {
1062 	struct pmc_op_pmcattach pmc_detach_args;
1063 
1064 	pmc_detach_args.pm_pmc = pmc;
1065 	pmc_detach_args.pm_pid = pid;
1066 	return (PMC_CALL(PMCDETACH, &pmc_detach_args));
1067 }
1068 
1069 int
1070 pmc_disable(int cpu, int pmc)
1071 {
1072 	struct pmc_op_pmcadmin ssa;
1073 
1074 	ssa.pm_cpu = cpu;
1075 	ssa.pm_pmc = pmc;
1076 	ssa.pm_state = PMC_STATE_DISABLED;
1077 	return (PMC_CALL(PMCADMIN, &ssa));
1078 }
1079 
1080 int
1081 pmc_enable(int cpu, int pmc)
1082 {
1083 	struct pmc_op_pmcadmin ssa;
1084 
1085 	ssa.pm_cpu = cpu;
1086 	ssa.pm_pmc = pmc;
1087 	ssa.pm_state = PMC_STATE_FREE;
1088 	return (PMC_CALL(PMCADMIN, &ssa));
1089 }
1090 
1091 /*
1092  * Return a list of events known to a given PMC class.  'cl' is the
1093  * PMC class identifier, 'eventnames' is the returned list of 'const
1094  * char *' pointers pointing to the names of the events. 'nevents' is
1095  * the number of event name pointers returned.
1096  *
1097  * The space for 'eventnames' is allocated using malloc(3).  The caller
1098  * is responsible for freeing this space when done.
1099  */
1100 int
1101 pmc_event_names_of_class(enum pmc_class cl, const char ***eventnames,
1102     int *nevents)
1103 {
1104 	int count;
1105 	const char **names;
1106 	const struct pmc_event_descr *ev;
1107 
1108 	switch (cl)
1109 	{
1110 	case PMC_CLASS_IAF:
1111 		ev = iaf_event_table;
1112 		count = PMC_EVENT_TABLE_SIZE(iaf);
1113 		break;
1114 	case PMC_CLASS_TSC:
1115 		ev = tsc_event_table;
1116 		count = PMC_EVENT_TABLE_SIZE(tsc);
1117 		break;
1118 	case PMC_CLASS_K8:
1119 		ev = k8_event_table;
1120 		count = PMC_EVENT_TABLE_SIZE(k8);
1121 		break;
1122 	case PMC_CLASS_ARMV7:
1123 		switch (cpu_info.pm_cputype) {
1124 		default:
1125 		case PMC_CPU_ARMV7_CORTEX_A8:
1126 			ev = cortex_a8_event_table;
1127 			count = PMC_EVENT_TABLE_SIZE(cortex_a8);
1128 			break;
1129 		case PMC_CPU_ARMV7_CORTEX_A9:
1130 			ev = cortex_a9_event_table;
1131 			count = PMC_EVENT_TABLE_SIZE(cortex_a9);
1132 			break;
1133 		}
1134 		break;
1135 	case PMC_CLASS_ARMV8:
1136 		switch (cpu_info.pm_cputype) {
1137 		default:
1138 		case PMC_CPU_ARMV8_CORTEX_A53:
1139 			ev = cortex_a53_event_table;
1140 			count = PMC_EVENT_TABLE_SIZE(cortex_a53);
1141 			break;
1142 		case PMC_CPU_ARMV8_CORTEX_A57:
1143 			ev = cortex_a57_event_table;
1144 			count = PMC_EVENT_TABLE_SIZE(cortex_a57);
1145 			break;
1146 		case PMC_CPU_ARMV8_CORTEX_A76:
1147 			ev = cortex_a76_event_table;
1148 			count = PMC_EVENT_TABLE_SIZE(cortex_a76);
1149 			break;
1150 		}
1151 		break;
1152 	case PMC_CLASS_PPC7450:
1153 		ev = ppc7450_event_table;
1154 		count = PMC_EVENT_TABLE_SIZE(ppc7450);
1155 		break;
1156 	case PMC_CLASS_PPC970:
1157 		ev = ppc970_event_table;
1158 		count = PMC_EVENT_TABLE_SIZE(ppc970);
1159 		break;
1160 	case PMC_CLASS_E500:
1161 		ev = e500_event_table;
1162 		count = PMC_EVENT_TABLE_SIZE(e500);
1163 		break;
1164 	case PMC_CLASS_SOFT:
1165 		ev = soft_event_table;
1166 		count = soft_event_info.pm_nevent;
1167 		break;
1168 	default:
1169 		errno = EINVAL;
1170 		return (-1);
1171 	}
1172 
1173 	if ((names = malloc(count * sizeof(const char *))) == NULL)
1174 		return (-1);
1175 
1176 	*eventnames = names;
1177 	*nevents = count;
1178 
1179 	for (;count--; ev++, names++)
1180 		*names = ev->pm_ev_name;
1181 
1182 	return (0);
1183 }
1184 
1185 int
1186 pmc_flush_logfile(void)
1187 {
1188 	return (PMC_CALL(FLUSHLOG,0));
1189 }
1190 
1191 int
1192 pmc_close_logfile(void)
1193 {
1194 	return (PMC_CALL(CLOSELOG,0));
1195 }
1196 
1197 int
1198 pmc_get_driver_stats(struct pmc_driverstats *ds)
1199 {
1200 	struct pmc_op_getdriverstats gms;
1201 
1202 	if (PMC_CALL(GETDRIVERSTATS, &gms) < 0)
1203 		return (-1);
1204 
1205 	/* copy out fields in the current userland<->library interface */
1206 	ds->pm_intr_ignored    = gms.pm_intr_ignored;
1207 	ds->pm_intr_processed  = gms.pm_intr_processed;
1208 	ds->pm_intr_bufferfull = gms.pm_intr_bufferfull;
1209 	ds->pm_syscalls        = gms.pm_syscalls;
1210 	ds->pm_syscall_errors  = gms.pm_syscall_errors;
1211 	ds->pm_buffer_requests = gms.pm_buffer_requests;
1212 	ds->pm_buffer_requests_failed = gms.pm_buffer_requests_failed;
1213 	ds->pm_log_sweeps      = gms.pm_log_sweeps;
1214 	return (0);
1215 }
1216 
1217 int
1218 pmc_get_msr(pmc_id_t pmc, uint32_t *msr)
1219 {
1220 	struct pmc_op_getmsr gm;
1221 
1222 	gm.pm_pmcid = pmc;
1223 	if (PMC_CALL(PMCGETMSR, &gm) < 0)
1224 		return (-1);
1225 	*msr = gm.pm_msr;
1226 	return (0);
1227 }
1228 
1229 int
1230 pmc_init(void)
1231 {
1232 	int error, pmc_mod_id;
1233 	unsigned int n;
1234 	uint32_t abi_version;
1235 	struct module_stat pmc_modstat;
1236 	struct pmc_op_getcpuinfo op_cpu_info;
1237 
1238 	if (pmc_syscall != -1) /* already inited */
1239 		return (0);
1240 
1241 	/* retrieve the system call number from the KLD */
1242 	if ((pmc_mod_id = modfind(PMC_MODULE_NAME)) < 0)
1243 		return (-1);
1244 
1245 	pmc_modstat.version = sizeof(struct module_stat);
1246 	if ((error = modstat(pmc_mod_id, &pmc_modstat)) < 0)
1247 		return (-1);
1248 
1249 	pmc_syscall = pmc_modstat.data.intval;
1250 
1251 	/* check the kernel module's ABI against our compiled-in version */
1252 	abi_version = PMC_VERSION;
1253 	if (PMC_CALL(GETMODULEVERSION, &abi_version) < 0)
1254 		return (pmc_syscall = -1);
1255 
1256 	/* ignore patch & minor numbers for the comparison */
1257 	if ((abi_version & 0xFF000000) != (PMC_VERSION & 0xFF000000)) {
1258 		errno  = EPROGMISMATCH;
1259 		return (pmc_syscall = -1);
1260 	}
1261 
1262 	bzero(&op_cpu_info, sizeof(op_cpu_info));
1263 	if (PMC_CALL(GETCPUINFO, &op_cpu_info) < 0)
1264 		return (pmc_syscall = -1);
1265 
1266 	cpu_info.pm_cputype = op_cpu_info.pm_cputype;
1267 	cpu_info.pm_ncpu    = op_cpu_info.pm_ncpu;
1268 	cpu_info.pm_npmc    = op_cpu_info.pm_npmc;
1269 	cpu_info.pm_nclass  = op_cpu_info.pm_nclass;
1270 	for (n = 0; n < op_cpu_info.pm_nclass; n++)
1271 		memcpy(&cpu_info.pm_classes[n], &op_cpu_info.pm_classes[n],
1272 		    sizeof(cpu_info.pm_classes[n]));
1273 
1274 	pmc_class_table = malloc(PMC_CLASS_TABLE_SIZE *
1275 	    sizeof(struct pmc_class_descr *));
1276 
1277 	if (pmc_class_table == NULL)
1278 		return (-1);
1279 
1280 	for (n = 0; n < PMC_CLASS_TABLE_SIZE; n++)
1281 		pmc_class_table[n] = NULL;
1282 
1283 	/*
1284 	 * Get soft events list.
1285 	 */
1286 	soft_event_info.pm_class = PMC_CLASS_SOFT;
1287 	if (PMC_CALL(GETDYNEVENTINFO, &soft_event_info) < 0)
1288 		return (pmc_syscall = -1);
1289 
1290 	/* Map soft events to static list. */
1291 	for (n = 0; n < soft_event_info.pm_nevent; n++) {
1292 		soft_event_table[n].pm_ev_name =
1293 		    soft_event_info.pm_events[n].pm_ev_name;
1294 		soft_event_table[n].pm_ev_code =
1295 		    soft_event_info.pm_events[n].pm_ev_code;
1296 	}
1297 	soft_class_table_descr.pm_evc_event_table_size = \
1298 	    soft_event_info.pm_nevent;
1299 	soft_class_table_descr.pm_evc_event_table = \
1300 	    soft_event_table;
1301 
1302 	/*
1303 	 * Fill in the class table.
1304 	 */
1305 	n = 0;
1306 
1307 	/* Fill soft events information. */
1308 	pmc_class_table[n++] = &soft_class_table_descr;
1309 #if defined(__amd64__) || defined(__i386__)
1310 	if (cpu_info.pm_cputype != PMC_CPU_GENERIC)
1311 		pmc_class_table[n++] = &tsc_class_table_descr;
1312 #endif
1313 
1314 #define	PMC_MDEP_INIT(C) pmc_mdep_event_aliases = C##_aliases
1315 
1316 	/* Configure the event name parser. */
1317 	switch (cpu_info.pm_cputype) {
1318 #if defined(__amd64__) || defined(__i386__)
1319 	case PMC_CPU_AMD_K8:
1320 		PMC_MDEP_INIT(k8);
1321 		pmc_class_table[n] = &k8_class_table_descr;
1322 		break;
1323 #endif
1324 	case PMC_CPU_GENERIC:
1325 		PMC_MDEP_INIT(generic);
1326 		break;
1327 #if defined(__arm__)
1328 	case PMC_CPU_ARMV7_CORTEX_A8:
1329 		PMC_MDEP_INIT(cortex_a8);
1330 		pmc_class_table[n] = &cortex_a8_class_table_descr;
1331 		break;
1332 	case PMC_CPU_ARMV7_CORTEX_A9:
1333 		PMC_MDEP_INIT(cortex_a9);
1334 		pmc_class_table[n] = &cortex_a9_class_table_descr;
1335 		break;
1336 #endif
1337 #if defined(__aarch64__)
1338 	case PMC_CPU_ARMV8_CORTEX_A53:
1339 		PMC_MDEP_INIT(cortex_a53);
1340 		pmc_class_table[n] = &cortex_a53_class_table_descr;
1341 		break;
1342 	case PMC_CPU_ARMV8_CORTEX_A57:
1343 		PMC_MDEP_INIT(cortex_a57);
1344 		pmc_class_table[n] = &cortex_a57_class_table_descr;
1345 		break;
1346 	case PMC_CPU_ARMV8_CORTEX_A76:
1347 		PMC_MDEP_INIT(cortex_a76);
1348 		pmc_class_table[n] = &cortex_a76_class_table_descr;
1349 		break;
1350 #endif
1351 #if defined(__powerpc__)
1352 	case PMC_CPU_PPC_7450:
1353 		PMC_MDEP_INIT(ppc7450);
1354 		pmc_class_table[n] = &ppc7450_class_table_descr;
1355 		break;
1356 	case PMC_CPU_PPC_970:
1357 		PMC_MDEP_INIT(ppc970);
1358 		pmc_class_table[n] = &ppc970_class_table_descr;
1359 		break;
1360 	case PMC_CPU_PPC_E500:
1361 		PMC_MDEP_INIT(e500);
1362 		pmc_class_table[n] = &e500_class_table_descr;
1363 		break;
1364 #endif
1365 	default:
1366 		/*
1367 		 * Some kind of CPU this version of the library knows nothing
1368 		 * about.  This shouldn't happen since the abi version check
1369 		 * should have caught this.
1370 		 */
1371 #if defined(__amd64__) || defined(__i386__) || defined(__powerpc64__)
1372 		break;
1373 #endif
1374 		errno = ENXIO;
1375 		return (pmc_syscall = -1);
1376 	}
1377 
1378 	return (0);
1379 }
1380 
1381 const char *
1382 pmc_name_of_capability(enum pmc_caps cap)
1383 {
1384 	int i;
1385 
1386 	/*
1387 	 * 'cap' should have a single bit set and should be in
1388 	 * range.
1389 	 */
1390 	if ((cap & (cap - 1)) || cap < PMC_CAP_FIRST ||
1391 	    cap > PMC_CAP_LAST) {
1392 		errno = EINVAL;
1393 		return (NULL);
1394 	}
1395 
1396 	i = ffs(cap);
1397 	return (pmc_capability_names[i - 1]);
1398 }
1399 
1400 const char *
1401 pmc_name_of_class(enum pmc_class pc)
1402 {
1403 	size_t n;
1404 
1405 	for (n = 0; n < PMC_TABLE_SIZE(pmc_class_names); n++)
1406 		if (pc == pmc_class_names[n].pm_class)
1407 			return (pmc_class_names[n].pm_name);
1408 
1409 	errno = EINVAL;
1410 	return (NULL);
1411 }
1412 
1413 const char *
1414 pmc_name_of_cputype(enum pmc_cputype cp)
1415 {
1416 	size_t n;
1417 
1418 	for (n = 0; n < PMC_TABLE_SIZE(pmc_cputype_names); n++)
1419 		if (cp == pmc_cputype_names[n].pm_cputype)
1420 			return (pmc_cputype_names[n].pm_name);
1421 
1422 	errno = EINVAL;
1423 	return (NULL);
1424 }
1425 
1426 const char *
1427 pmc_name_of_disposition(enum pmc_disp pd)
1428 {
1429 	if ((int) pd >= PMC_DISP_FIRST &&
1430 	    pd <= PMC_DISP_LAST)
1431 		return (pmc_disposition_names[pd]);
1432 
1433 	errno = EINVAL;
1434 	return (NULL);
1435 }
1436 
1437 const char *
1438 _pmc_name_of_event(enum pmc_event pe, enum pmc_cputype cpu)
1439 {
1440 	const struct pmc_event_descr *ev, *evfence;
1441 
1442 	ev = evfence = NULL;
1443 	if (pe >= PMC_EV_K8_FIRST && pe <= PMC_EV_K8_LAST) {
1444 		ev = k8_event_table;
1445 		evfence = k8_event_table + PMC_EVENT_TABLE_SIZE(k8);
1446 
1447 	} else if (pe >= PMC_EV_ARMV7_FIRST && pe <= PMC_EV_ARMV7_LAST) {
1448 		switch (cpu) {
1449 		case PMC_CPU_ARMV7_CORTEX_A8:
1450 			ev = cortex_a8_event_table;
1451 			evfence = cortex_a8_event_table + PMC_EVENT_TABLE_SIZE(cortex_a8);
1452 			break;
1453 		case PMC_CPU_ARMV7_CORTEX_A9:
1454 			ev = cortex_a9_event_table;
1455 			evfence = cortex_a9_event_table + PMC_EVENT_TABLE_SIZE(cortex_a9);
1456 			break;
1457 		default:	/* Unknown CPU type. */
1458 			break;
1459 		}
1460 	} else if (pe >= PMC_EV_ARMV8_FIRST && pe <= PMC_EV_ARMV8_LAST) {
1461 		switch (cpu) {
1462 		case PMC_CPU_ARMV8_CORTEX_A53:
1463 			ev = cortex_a53_event_table;
1464 			evfence = cortex_a53_event_table + PMC_EVENT_TABLE_SIZE(cortex_a53);
1465 			break;
1466 		case PMC_CPU_ARMV8_CORTEX_A57:
1467 			ev = cortex_a57_event_table;
1468 			evfence = cortex_a57_event_table + PMC_EVENT_TABLE_SIZE(cortex_a57);
1469 			break;
1470 		case PMC_CPU_ARMV8_CORTEX_A76:
1471 			ev = cortex_a76_event_table;
1472 			evfence = cortex_a76_event_table + PMC_EVENT_TABLE_SIZE(cortex_a76);
1473 			break;
1474 		default:	/* Unknown CPU type. */
1475 			break;
1476 		}
1477 	} else if (pe >= PMC_EV_PPC7450_FIRST && pe <= PMC_EV_PPC7450_LAST) {
1478 		ev = ppc7450_event_table;
1479 		evfence = ppc7450_event_table + PMC_EVENT_TABLE_SIZE(ppc7450);
1480 	} else if (pe >= PMC_EV_PPC970_FIRST && pe <= PMC_EV_PPC970_LAST) {
1481 		ev = ppc970_event_table;
1482 		evfence = ppc970_event_table + PMC_EVENT_TABLE_SIZE(ppc970);
1483 	} else if (pe >= PMC_EV_E500_FIRST && pe <= PMC_EV_E500_LAST) {
1484 		ev = e500_event_table;
1485 		evfence = e500_event_table + PMC_EVENT_TABLE_SIZE(e500);
1486 	} else if (pe == PMC_EV_TSC_TSC) {
1487 		ev = tsc_event_table;
1488 		evfence = tsc_event_table + PMC_EVENT_TABLE_SIZE(tsc);
1489 	} else if ((int)pe >= PMC_EV_SOFT_FIRST && (int)pe <= PMC_EV_SOFT_LAST) {
1490 		ev = soft_event_table;
1491 		evfence = soft_event_table + soft_event_info.pm_nevent;
1492 	}
1493 
1494 	for (; ev != evfence; ev++)
1495 		if (pe == ev->pm_ev_code)
1496 			return (ev->pm_ev_name);
1497 
1498 	return (NULL);
1499 }
1500 
1501 const char *
1502 pmc_name_of_event(enum pmc_event pe)
1503 {
1504 	const char *n;
1505 
1506 	if ((n = _pmc_name_of_event(pe, cpu_info.pm_cputype)) != NULL)
1507 		return (n);
1508 
1509 	errno = EINVAL;
1510 	return (NULL);
1511 }
1512 
1513 const char *
1514 pmc_name_of_mode(enum pmc_mode pm)
1515 {
1516 	if ((int) pm >= PMC_MODE_FIRST &&
1517 	    pm <= PMC_MODE_LAST)
1518 		return (pmc_mode_names[pm]);
1519 
1520 	errno = EINVAL;
1521 	return (NULL);
1522 }
1523 
1524 const char *
1525 pmc_name_of_state(enum pmc_state ps)
1526 {
1527 	if ((int) ps >= PMC_STATE_FIRST &&
1528 	    ps <= PMC_STATE_LAST)
1529 		return (pmc_state_names[ps]);
1530 
1531 	errno = EINVAL;
1532 	return (NULL);
1533 }
1534 
1535 int
1536 pmc_ncpu(void)
1537 {
1538 	if (pmc_syscall == -1) {
1539 		errno = ENXIO;
1540 		return (-1);
1541 	}
1542 
1543 	return (cpu_info.pm_ncpu);
1544 }
1545 
1546 int
1547 pmc_npmc(int cpu)
1548 {
1549 	if (pmc_syscall == -1) {
1550 		errno = ENXIO;
1551 		return (-1);
1552 	}
1553 
1554 	if (cpu < 0 || cpu >= (int) cpu_info.pm_ncpu) {
1555 		errno = EINVAL;
1556 		return (-1);
1557 	}
1558 
1559 	return (cpu_info.pm_npmc);
1560 }
1561 
1562 int
1563 pmc_pmcinfo(int cpu, struct pmc_pmcinfo **ppmci)
1564 {
1565 	int nbytes, npmc;
1566 	struct pmc_op_getpmcinfo *pmci;
1567 
1568 	if ((npmc = pmc_npmc(cpu)) < 0)
1569 		return (-1);
1570 
1571 	nbytes = sizeof(struct pmc_op_getpmcinfo) +
1572 	    npmc * sizeof(struct pmc_info);
1573 
1574 	if ((pmci = calloc(1, nbytes)) == NULL)
1575 		return (-1);
1576 
1577 	pmci->pm_cpu  = cpu;
1578 
1579 	if (PMC_CALL(GETPMCINFO, pmci) < 0) {
1580 		free(pmci);
1581 		return (-1);
1582 	}
1583 
1584 	/* kernel<->library, library<->userland interfaces are identical */
1585 	*ppmci = (struct pmc_pmcinfo *) pmci;
1586 	return (0);
1587 }
1588 
1589 int
1590 pmc_read(pmc_id_t pmc, pmc_value_t *value)
1591 {
1592 	struct pmc_op_pmcrw pmc_read_op;
1593 
1594 	pmc_read_op.pm_pmcid = pmc;
1595 	pmc_read_op.pm_flags = PMC_F_OLDVALUE;
1596 	pmc_read_op.pm_value = -1;
1597 
1598 	if (PMC_CALL(PMCRW, &pmc_read_op) < 0)
1599 		return (-1);
1600 
1601 	*value = pmc_read_op.pm_value;
1602 	return (0);
1603 }
1604 
1605 int
1606 pmc_release(pmc_id_t pmc)
1607 {
1608 	struct pmc_op_simple	pmc_release_args;
1609 
1610 	pmc_release_args.pm_pmcid = pmc;
1611 	return (PMC_CALL(PMCRELEASE, &pmc_release_args));
1612 }
1613 
1614 int
1615 pmc_rw(pmc_id_t pmc, pmc_value_t newvalue, pmc_value_t *oldvaluep)
1616 {
1617 	struct pmc_op_pmcrw pmc_rw_op;
1618 
1619 	pmc_rw_op.pm_pmcid = pmc;
1620 	pmc_rw_op.pm_flags = PMC_F_NEWVALUE | PMC_F_OLDVALUE;
1621 	pmc_rw_op.pm_value = newvalue;
1622 
1623 	if (PMC_CALL(PMCRW, &pmc_rw_op) < 0)
1624 		return (-1);
1625 
1626 	*oldvaluep = pmc_rw_op.pm_value;
1627 	return (0);
1628 }
1629 
1630 int
1631 pmc_set(pmc_id_t pmc, pmc_value_t value)
1632 {
1633 	struct pmc_op_pmcsetcount sc;
1634 
1635 	sc.pm_pmcid = pmc;
1636 	sc.pm_count = value;
1637 
1638 	if (PMC_CALL(PMCSETCOUNT, &sc) < 0)
1639 		return (-1);
1640 	return (0);
1641 }
1642 
1643 int
1644 pmc_start(pmc_id_t pmc)
1645 {
1646 	struct pmc_op_simple	pmc_start_args;
1647 
1648 	pmc_start_args.pm_pmcid = pmc;
1649 	return (PMC_CALL(PMCSTART, &pmc_start_args));
1650 }
1651 
1652 int
1653 pmc_stop(pmc_id_t pmc)
1654 {
1655 	struct pmc_op_simple	pmc_stop_args;
1656 
1657 	pmc_stop_args.pm_pmcid = pmc;
1658 	return (PMC_CALL(PMCSTOP, &pmc_stop_args));
1659 }
1660 
1661 int
1662 pmc_width(pmc_id_t pmcid, uint32_t *width)
1663 {
1664 	unsigned int i;
1665 	enum pmc_class cl;
1666 
1667 	cl = PMC_ID_TO_CLASS(pmcid);
1668 	for (i = 0; i < cpu_info.pm_nclass; i++)
1669 		if (cpu_info.pm_classes[i].pm_class == cl) {
1670 			*width = cpu_info.pm_classes[i].pm_width;
1671 			return (0);
1672 		}
1673 	errno = EINVAL;
1674 	return (-1);
1675 }
1676 
1677 int
1678 pmc_write(pmc_id_t pmc, pmc_value_t value)
1679 {
1680 	struct pmc_op_pmcrw pmc_write_op;
1681 
1682 	pmc_write_op.pm_pmcid = pmc;
1683 	pmc_write_op.pm_flags = PMC_F_NEWVALUE;
1684 	pmc_write_op.pm_value = value;
1685 	return (PMC_CALL(PMCRW, &pmc_write_op));
1686 }
1687 
1688 int
1689 pmc_writelog(uint32_t userdata)
1690 {
1691 	struct pmc_op_writelog wl;
1692 
1693 	wl.pm_userdata = userdata;
1694 	return (PMC_CALL(WRITELOG, &wl));
1695 }
1696