]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libpmc/libpmc.c
libedit: import version of 2022-04-11
[FreeBSD/FreeBSD.git] / lib / libpmc / libpmc.c
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
767 static int
768 arm64_allocate_pmc(enum pmc_event pe, char *ctrspec,
769     struct pmc_op_pmcallocate *pmc_config)
770 {
771         char *p;
772
773         while ((p = strsep(&ctrspec, ",")) != NULL) {
774                 if (KWMATCH(p, "os"))
775                         pmc_config->pm_caps |= PMC_CAP_SYSTEM;
776                 else if (KWMATCH(p, "usr"))
777                         pmc_config->pm_caps |= PMC_CAP_USER;
778                 else
779                         return (-1);
780         }
781
782         return (0);
783 }
784 #endif
785
786 #if defined(__powerpc__)
787
788 static struct pmc_event_alias ppc7450_aliases[] = {
789         EV_ALIAS("instructions",        "INSTR_COMPLETED"),
790         EV_ALIAS("branches",            "BRANCHES_COMPLETED"),
791         EV_ALIAS("branch-mispredicts",  "MISPREDICTED_BRANCHES"),
792         EV_ALIAS(NULL, NULL)
793 };
794
795 static struct pmc_event_alias ppc970_aliases[] = {
796         EV_ALIAS("instructions", "INSTR_COMPLETED"),
797         EV_ALIAS("cycles",       "CYCLES"),
798         EV_ALIAS(NULL, NULL)
799 };
800
801 static struct pmc_event_alias e500_aliases[] = {
802         EV_ALIAS("instructions", "INSTR_COMPLETED"),
803         EV_ALIAS("cycles",       "CYCLES"),
804         EV_ALIAS(NULL, NULL)
805 };
806
807 #define POWERPC_KW_OS           "os"
808 #define POWERPC_KW_USR          "usr"
809 #define POWERPC_KW_ANYTHREAD    "anythread"
810
811 static int
812 powerpc_allocate_pmc(enum pmc_event pe, char *ctrspec __unused,
813                      struct pmc_op_pmcallocate *pmc_config __unused)
814 {
815         char *p;
816
817         (void) pe;
818
819         pmc_config->pm_caps |= (PMC_CAP_READ | PMC_CAP_WRITE);
820         
821         while ((p = strsep(&ctrspec, ",")) != NULL) {
822                 if (KWMATCH(p, POWERPC_KW_OS))
823                         pmc_config->pm_caps |= PMC_CAP_SYSTEM;
824                 else if (KWMATCH(p, POWERPC_KW_USR))
825                         pmc_config->pm_caps |= PMC_CAP_USER;
826                 else if (KWMATCH(p, POWERPC_KW_ANYTHREAD))
827                         pmc_config->pm_caps |= (PMC_CAP_USER | PMC_CAP_SYSTEM);
828                 else
829                         return (-1);
830         }
831
832         return (0);
833 }
834
835 #endif /* __powerpc__ */
836
837
838 /*
839  * Match an event name `name' with its canonical form.
840  *
841  * Matches are case insensitive and spaces, periods, underscores and
842  * hyphen characters are considered to match each other.
843  *
844  * Returns 1 for a match, 0 otherwise.
845  */
846
847 static int
848 pmc_match_event_name(const char *name, const char *canonicalname)
849 {
850         int cc, nc;
851         const unsigned char *c, *n;
852
853         c = (const unsigned char *) canonicalname;
854         n = (const unsigned char *) name;
855
856         for (; (nc = *n) && (cc = *c); n++, c++) {
857
858                 if ((nc == ' ' || nc == '_' || nc == '-' || nc == '.') &&
859                     (cc == ' ' || cc == '_' || cc == '-' || cc == '.'))
860                         continue;
861
862                 if (toupper(nc) == toupper(cc))
863                         continue;
864
865
866                 return (0);
867         }
868
869         if (*n == '\0' && *c == '\0')
870                 return (1);
871
872         return (0);
873 }
874
875 /*
876  * Match an event name against all the event named supported by a
877  * PMC class.
878  *
879  * Returns an event descriptor pointer on match or NULL otherwise.
880  */
881 static const struct pmc_event_descr *
882 pmc_match_event_class(const char *name,
883     const struct pmc_class_descr *pcd)
884 {
885         size_t n;
886         const struct pmc_event_descr *ev;
887
888         ev = pcd->pm_evc_event_table;
889         for (n = 0; n < pcd->pm_evc_event_table_size; n++, ev++)
890                 if (pmc_match_event_name(name, ev->pm_ev_name))
891                         return (ev);
892
893         return (NULL);
894 }
895
896 /*
897  * API entry points
898  */
899
900 int
901 pmc_allocate(const char *ctrspec, enum pmc_mode mode,
902     uint32_t flags, int cpu, pmc_id_t *pmcid,
903     uint64_t count)
904 {
905         size_t n;
906         int retval;
907         char *r, *spec_copy;
908         const char *ctrname;
909         const struct pmc_event_descr *ev;
910         const struct pmc_event_alias *alias;
911         struct pmc_op_pmcallocate pmc_config;
912         const struct pmc_class_descr *pcd;
913
914         spec_copy = NULL;
915         retval    = -1;
916
917         if (mode != PMC_MODE_SS && mode != PMC_MODE_TS &&
918             mode != PMC_MODE_SC && mode != PMC_MODE_TC) {
919                 errno = EINVAL;
920                 goto out;
921         }
922         bzero(&pmc_config, sizeof(pmc_config));
923         pmc_config.pm_cpu   = cpu;
924         pmc_config.pm_mode  = mode;
925         pmc_config.pm_flags = flags;
926         pmc_config.pm_count = count;
927         if (PMC_IS_SAMPLING_MODE(mode))
928                 pmc_config.pm_caps |= PMC_CAP_INTERRUPT;
929
930         /*
931          * Try to pull the raw event ID directly from the pmu-events table. If
932          * this is unsupported on the platform, or the event is not found,
933          * continue with searching the regular event tables.
934          */
935         r = spec_copy = strdup(ctrspec);
936         ctrname = strsep(&r, ",");
937         if (pmc_pmu_enabled()) {
938                 if (pmc_pmu_pmcallocate(ctrname, &pmc_config) == 0)
939                         goto found;
940
941                 /* Otherwise, reset any changes */
942                 pmc_config.pm_ev = 0;
943                 pmc_config.pm_caps = 0;
944                 pmc_config.pm_class = 0;
945         }
946         free(spec_copy);
947         spec_copy = NULL;
948
949         /* replace an event alias with the canonical event specifier */
950         if (pmc_mdep_event_aliases)
951                 for (alias = pmc_mdep_event_aliases; alias->pm_alias; alias++)
952                         if (!strcasecmp(ctrspec, alias->pm_alias)) {
953                                 spec_copy = strdup(alias->pm_spec);
954                                 break;
955                         }
956
957         if (spec_copy == NULL)
958                 spec_copy = strdup(ctrspec);
959
960         r = spec_copy;
961         ctrname = strsep(&r, ",");
962
963         /*
964          * If a explicit class prefix was given by the user, restrict the
965          * search for the event to the specified PMC class.
966          */
967         ev = NULL;
968         for (n = 0; n < PMC_CLASS_TABLE_SIZE; n++) {
969                 pcd = pmc_class_table[n];
970                 if (pcd != NULL && strncasecmp(ctrname, pcd->pm_evc_name,
971                     pcd->pm_evc_name_size) == 0) {
972                         if ((ev = pmc_match_event_class(ctrname +
973                             pcd->pm_evc_name_size, pcd)) == NULL) {
974                                 errno = EINVAL;
975                                 goto out;
976                         }
977                         break;
978                 }
979         }
980
981         /*
982          * Otherwise, search for this event in all compatible PMC
983          * classes.
984          */
985         for (n = 0; ev == NULL && n < PMC_CLASS_TABLE_SIZE; n++) {
986                 pcd = pmc_class_table[n];
987                 if (pcd != NULL)
988                         ev = pmc_match_event_class(ctrname, pcd);
989         }
990
991         if (ev == NULL) {
992                 errno = EINVAL;
993                 goto out;
994         }
995
996         pmc_config.pm_ev    = ev->pm_ev_code;
997         pmc_config.pm_class = pcd->pm_evc_class;
998
999         if (pcd->pm_evc_allocate_pmc(ev->pm_ev_code, r, &pmc_config) < 0) {
1000                 errno = EINVAL;
1001                 goto out;
1002         }
1003
1004 found:
1005         if (PMC_CALL(PMCALLOCATE, &pmc_config) == 0) {
1006                 *pmcid = pmc_config.pm_pmcid;
1007                 retval = 0;
1008         }
1009 out:
1010         if (spec_copy)
1011                 free(spec_copy);
1012
1013         return (retval);
1014 }
1015
1016 int
1017 pmc_attach(pmc_id_t pmc, pid_t pid)
1018 {
1019         struct pmc_op_pmcattach pmc_attach_args;
1020
1021         pmc_attach_args.pm_pmc = pmc;
1022         pmc_attach_args.pm_pid = pid;
1023
1024         return (PMC_CALL(PMCATTACH, &pmc_attach_args));
1025 }
1026
1027 int
1028 pmc_capabilities(pmc_id_t pmcid, uint32_t *caps)
1029 {
1030         unsigned int i;
1031         enum pmc_class cl;
1032
1033         cl = PMC_ID_TO_CLASS(pmcid);
1034         for (i = 0; i < cpu_info.pm_nclass; i++)
1035                 if (cpu_info.pm_classes[i].pm_class == cl) {
1036                         *caps = cpu_info.pm_classes[i].pm_caps;
1037                         return (0);
1038                 }
1039         errno = EINVAL;
1040         return (-1);
1041 }
1042
1043 int
1044 pmc_configure_logfile(int fd)
1045 {
1046         struct pmc_op_configurelog cla;
1047
1048         cla.pm_logfd = fd;
1049         if (PMC_CALL(CONFIGURELOG, &cla) < 0)
1050                 return (-1);
1051         return (0);
1052 }
1053
1054 int
1055 pmc_cpuinfo(const struct pmc_cpuinfo **pci)
1056 {
1057         if (pmc_syscall == -1) {
1058                 errno = ENXIO;
1059                 return (-1);
1060         }
1061
1062         *pci = &cpu_info;
1063         return (0);
1064 }
1065
1066 int
1067 pmc_detach(pmc_id_t pmc, pid_t pid)
1068 {
1069         struct pmc_op_pmcattach pmc_detach_args;
1070
1071         pmc_detach_args.pm_pmc = pmc;
1072         pmc_detach_args.pm_pid = pid;
1073         return (PMC_CALL(PMCDETACH, &pmc_detach_args));
1074 }
1075
1076 int
1077 pmc_disable(int cpu, int pmc)
1078 {
1079         struct pmc_op_pmcadmin ssa;
1080
1081         ssa.pm_cpu = cpu;
1082         ssa.pm_pmc = pmc;
1083         ssa.pm_state = PMC_STATE_DISABLED;
1084         return (PMC_CALL(PMCADMIN, &ssa));
1085 }
1086
1087 int
1088 pmc_enable(int cpu, int pmc)
1089 {
1090         struct pmc_op_pmcadmin ssa;
1091
1092         ssa.pm_cpu = cpu;
1093         ssa.pm_pmc = pmc;
1094         ssa.pm_state = PMC_STATE_FREE;
1095         return (PMC_CALL(PMCADMIN, &ssa));
1096 }
1097
1098 /*
1099  * Return a list of events known to a given PMC class.  'cl' is the
1100  * PMC class identifier, 'eventnames' is the returned list of 'const
1101  * char *' pointers pointing to the names of the events. 'nevents' is
1102  * the number of event name pointers returned.
1103  *
1104  * The space for 'eventnames' is allocated using malloc(3).  The caller
1105  * is responsible for freeing this space when done.
1106  */
1107 int
1108 pmc_event_names_of_class(enum pmc_class cl, const char ***eventnames,
1109     int *nevents)
1110 {
1111         int count;
1112         const char **names;
1113         const struct pmc_event_descr *ev;
1114
1115         switch (cl)
1116         {
1117         case PMC_CLASS_IAF:
1118                 ev = iaf_event_table;
1119                 count = PMC_EVENT_TABLE_SIZE(iaf);
1120                 break;
1121         case PMC_CLASS_TSC:
1122                 ev = tsc_event_table;
1123                 count = PMC_EVENT_TABLE_SIZE(tsc);
1124                 break;
1125         case PMC_CLASS_K8:
1126                 ev = k8_event_table;
1127                 count = PMC_EVENT_TABLE_SIZE(k8);
1128                 break;
1129         case PMC_CLASS_ARMV7:
1130                 switch (cpu_info.pm_cputype) {
1131                 default:
1132                 case PMC_CPU_ARMV7_CORTEX_A8:
1133                         ev = cortex_a8_event_table;
1134                         count = PMC_EVENT_TABLE_SIZE(cortex_a8);
1135                         break;
1136                 case PMC_CPU_ARMV7_CORTEX_A9:
1137                         ev = cortex_a9_event_table;
1138                         count = PMC_EVENT_TABLE_SIZE(cortex_a9);
1139                         break;
1140                 }
1141                 break;
1142         case PMC_CLASS_ARMV8:
1143                 switch (cpu_info.pm_cputype) {
1144                 default:
1145                 case PMC_CPU_ARMV8_CORTEX_A53:
1146                         ev = cortex_a53_event_table;
1147                         count = PMC_EVENT_TABLE_SIZE(cortex_a53);
1148                         break;
1149                 case PMC_CPU_ARMV8_CORTEX_A57:
1150                         ev = cortex_a57_event_table;
1151                         count = PMC_EVENT_TABLE_SIZE(cortex_a57);
1152                         break;
1153                 case PMC_CPU_ARMV8_CORTEX_A76:
1154                         ev = cortex_a76_event_table;
1155                         count = PMC_EVENT_TABLE_SIZE(cortex_a76);
1156                         break;
1157                 }
1158                 break;
1159         case PMC_CLASS_PPC7450:
1160                 ev = ppc7450_event_table;
1161                 count = PMC_EVENT_TABLE_SIZE(ppc7450);
1162                 break;
1163         case PMC_CLASS_PPC970:
1164                 ev = ppc970_event_table;
1165                 count = PMC_EVENT_TABLE_SIZE(ppc970);
1166                 break;
1167         case PMC_CLASS_E500:
1168                 ev = e500_event_table;
1169                 count = PMC_EVENT_TABLE_SIZE(e500);
1170                 break;
1171         case PMC_CLASS_SOFT:
1172                 ev = soft_event_table;
1173                 count = soft_event_info.pm_nevent;
1174                 break;
1175         default:
1176                 errno = EINVAL;
1177                 return (-1);
1178         }
1179
1180         if ((names = malloc(count * sizeof(const char *))) == NULL)
1181                 return (-1);
1182
1183         *eventnames = names;
1184         *nevents = count;
1185
1186         for (;count--; ev++, names++)
1187                 *names = ev->pm_ev_name;
1188
1189         return (0);
1190 }
1191
1192 int
1193 pmc_flush_logfile(void)
1194 {
1195         return (PMC_CALL(FLUSHLOG,0));
1196 }
1197
1198 int
1199 pmc_close_logfile(void)
1200 {
1201         return (PMC_CALL(CLOSELOG,0));
1202 }
1203
1204 int
1205 pmc_get_driver_stats(struct pmc_driverstats *ds)
1206 {
1207         struct pmc_op_getdriverstats gms;
1208
1209         if (PMC_CALL(GETDRIVERSTATS, &gms) < 0)
1210                 return (-1);
1211
1212         /* copy out fields in the current userland<->library interface */
1213         ds->pm_intr_ignored    = gms.pm_intr_ignored;
1214         ds->pm_intr_processed  = gms.pm_intr_processed;
1215         ds->pm_intr_bufferfull = gms.pm_intr_bufferfull;
1216         ds->pm_syscalls        = gms.pm_syscalls;
1217         ds->pm_syscall_errors  = gms.pm_syscall_errors;
1218         ds->pm_buffer_requests = gms.pm_buffer_requests;
1219         ds->pm_buffer_requests_failed = gms.pm_buffer_requests_failed;
1220         ds->pm_log_sweeps      = gms.pm_log_sweeps;
1221         return (0);
1222 }
1223
1224 int
1225 pmc_get_msr(pmc_id_t pmc, uint32_t *msr)
1226 {
1227         struct pmc_op_getmsr gm;
1228
1229         gm.pm_pmcid = pmc;
1230         if (PMC_CALL(PMCGETMSR, &gm) < 0)
1231                 return (-1);
1232         *msr = gm.pm_msr;
1233         return (0);
1234 }
1235
1236 int
1237 pmc_init(void)
1238 {
1239         int error, pmc_mod_id;
1240         unsigned int n;
1241         uint32_t abi_version;
1242         struct module_stat pmc_modstat;
1243         struct pmc_op_getcpuinfo op_cpu_info;
1244
1245         if (pmc_syscall != -1) /* already inited */
1246                 return (0);
1247
1248         /* retrieve the system call number from the KLD */
1249         if ((pmc_mod_id = modfind(PMC_MODULE_NAME)) < 0)
1250                 return (-1);
1251
1252         pmc_modstat.version = sizeof(struct module_stat);
1253         if ((error = modstat(pmc_mod_id, &pmc_modstat)) < 0)
1254                 return (-1);
1255
1256         pmc_syscall = pmc_modstat.data.intval;
1257
1258         /* check the kernel module's ABI against our compiled-in version */
1259         abi_version = PMC_VERSION;
1260         if (PMC_CALL(GETMODULEVERSION, &abi_version) < 0)
1261                 return (pmc_syscall = -1);
1262
1263         /* ignore patch & minor numbers for the comparison */
1264         if ((abi_version & 0xFF000000) != (PMC_VERSION & 0xFF000000)) {
1265                 errno  = EPROGMISMATCH;
1266                 return (pmc_syscall = -1);
1267         }
1268
1269         bzero(&op_cpu_info, sizeof(op_cpu_info));
1270         if (PMC_CALL(GETCPUINFO, &op_cpu_info) < 0)
1271                 return (pmc_syscall = -1);
1272
1273         cpu_info.pm_cputype = op_cpu_info.pm_cputype;
1274         cpu_info.pm_ncpu    = op_cpu_info.pm_ncpu;
1275         cpu_info.pm_npmc    = op_cpu_info.pm_npmc;
1276         cpu_info.pm_nclass  = op_cpu_info.pm_nclass;
1277         for (n = 0; n < op_cpu_info.pm_nclass; n++)
1278                 memcpy(&cpu_info.pm_classes[n], &op_cpu_info.pm_classes[n],
1279                     sizeof(cpu_info.pm_classes[n]));
1280
1281         pmc_class_table = malloc(PMC_CLASS_TABLE_SIZE *
1282             sizeof(struct pmc_class_descr *));
1283
1284         if (pmc_class_table == NULL)
1285                 return (-1);
1286
1287         for (n = 0; n < PMC_CLASS_TABLE_SIZE; n++)
1288                 pmc_class_table[n] = NULL;
1289
1290         /*
1291          * Get soft events list.
1292          */
1293         soft_event_info.pm_class = PMC_CLASS_SOFT;
1294         if (PMC_CALL(GETDYNEVENTINFO, &soft_event_info) < 0)
1295                 return (pmc_syscall = -1);
1296
1297         /* Map soft events to static list. */
1298         for (n = 0; n < soft_event_info.pm_nevent; n++) {
1299                 soft_event_table[n].pm_ev_name =
1300                     soft_event_info.pm_events[n].pm_ev_name;
1301                 soft_event_table[n].pm_ev_code =
1302                     soft_event_info.pm_events[n].pm_ev_code;
1303         }
1304         soft_class_table_descr.pm_evc_event_table_size = \
1305             soft_event_info.pm_nevent;
1306         soft_class_table_descr.pm_evc_event_table = \
1307             soft_event_table;
1308
1309         /*
1310          * Fill in the class table.
1311          */
1312         n = 0;
1313
1314         /* Fill soft events information. */
1315         pmc_class_table[n++] = &soft_class_table_descr;
1316 #if defined(__amd64__) || defined(__i386__)
1317         if (cpu_info.pm_cputype != PMC_CPU_GENERIC)
1318                 pmc_class_table[n++] = &tsc_class_table_descr;
1319 #endif
1320
1321 #define PMC_MDEP_INIT(C) pmc_mdep_event_aliases = C##_aliases
1322
1323         /* Configure the event name parser. */
1324         switch (cpu_info.pm_cputype) {
1325 #if defined(__amd64__) || defined(__i386__)
1326         case PMC_CPU_AMD_K8:
1327                 PMC_MDEP_INIT(k8);
1328                 pmc_class_table[n] = &k8_class_table_descr;
1329                 break;
1330 #endif
1331         case PMC_CPU_GENERIC:
1332                 PMC_MDEP_INIT(generic);
1333                 break;
1334 #if defined(__arm__)
1335         case PMC_CPU_ARMV7_CORTEX_A8:
1336                 PMC_MDEP_INIT(cortex_a8);
1337                 pmc_class_table[n] = &cortex_a8_class_table_descr;
1338                 break;
1339         case PMC_CPU_ARMV7_CORTEX_A9:
1340                 PMC_MDEP_INIT(cortex_a9);
1341                 pmc_class_table[n] = &cortex_a9_class_table_descr;
1342                 break;
1343 #endif
1344 #if defined(__aarch64__)
1345         case PMC_CPU_ARMV8_CORTEX_A53:
1346                 PMC_MDEP_INIT(cortex_a53);
1347                 pmc_class_table[n] = &cortex_a53_class_table_descr;
1348                 break;
1349         case PMC_CPU_ARMV8_CORTEX_A57:
1350                 PMC_MDEP_INIT(cortex_a57);
1351                 pmc_class_table[n] = &cortex_a57_class_table_descr;
1352                 break;
1353         case PMC_CPU_ARMV8_CORTEX_A76:
1354                 PMC_MDEP_INIT(cortex_a76);
1355                 pmc_class_table[n] = &cortex_a76_class_table_descr;
1356                 break;
1357 #endif
1358 #if defined(__powerpc__)
1359         case PMC_CPU_PPC_7450:
1360                 PMC_MDEP_INIT(ppc7450);
1361                 pmc_class_table[n] = &ppc7450_class_table_descr;
1362                 break;
1363         case PMC_CPU_PPC_970:
1364                 PMC_MDEP_INIT(ppc970);
1365                 pmc_class_table[n] = &ppc970_class_table_descr;
1366                 break;
1367         case PMC_CPU_PPC_E500:
1368                 PMC_MDEP_INIT(e500);
1369                 pmc_class_table[n] = &e500_class_table_descr;
1370                 break;
1371 #endif
1372         default:
1373                 /*
1374                  * Some kind of CPU this version of the library knows nothing
1375                  * about.  This shouldn't happen since the abi version check
1376                  * should have caught this.
1377                  */
1378 #if defined(__amd64__) || defined(__i386__) || defined(__powerpc64__)
1379                 break;
1380 #endif
1381                 errno = ENXIO;
1382                 return (pmc_syscall = -1);
1383         }
1384
1385         return (0);
1386 }
1387
1388 const char *
1389 pmc_name_of_capability(enum pmc_caps cap)
1390 {
1391         int i;
1392
1393         /*
1394          * 'cap' should have a single bit set and should be in
1395          * range.
1396          */
1397         if ((cap & (cap - 1)) || cap < PMC_CAP_FIRST ||
1398             cap > PMC_CAP_LAST) {
1399                 errno = EINVAL;
1400                 return (NULL);
1401         }
1402
1403         i = ffs(cap);
1404         return (pmc_capability_names[i - 1]);
1405 }
1406
1407 const char *
1408 pmc_name_of_class(enum pmc_class pc)
1409 {
1410         size_t n;
1411
1412         for (n = 0; n < PMC_TABLE_SIZE(pmc_class_names); n++)
1413                 if (pc == pmc_class_names[n].pm_class)
1414                         return (pmc_class_names[n].pm_name);
1415
1416         errno = EINVAL;
1417         return (NULL);
1418 }
1419
1420 const char *
1421 pmc_name_of_cputype(enum pmc_cputype cp)
1422 {
1423         size_t n;
1424
1425         for (n = 0; n < PMC_TABLE_SIZE(pmc_cputype_names); n++)
1426                 if (cp == pmc_cputype_names[n].pm_cputype)
1427                         return (pmc_cputype_names[n].pm_name);
1428
1429         errno = EINVAL;
1430         return (NULL);
1431 }
1432
1433 const char *
1434 pmc_name_of_disposition(enum pmc_disp pd)
1435 {
1436         if ((int) pd >= PMC_DISP_FIRST &&
1437             pd <= PMC_DISP_LAST)
1438                 return (pmc_disposition_names[pd]);
1439
1440         errno = EINVAL;
1441         return (NULL);
1442 }
1443
1444 const char *
1445 _pmc_name_of_event(enum pmc_event pe, enum pmc_cputype cpu)
1446 {
1447         const struct pmc_event_descr *ev, *evfence;
1448
1449         ev = evfence = NULL;
1450         if (pe >= PMC_EV_K8_FIRST && pe <= PMC_EV_K8_LAST) {
1451                 ev = k8_event_table;
1452                 evfence = k8_event_table + PMC_EVENT_TABLE_SIZE(k8);
1453
1454         } else if (pe >= PMC_EV_ARMV7_FIRST && pe <= PMC_EV_ARMV7_LAST) {
1455                 switch (cpu) {
1456                 case PMC_CPU_ARMV7_CORTEX_A8:
1457                         ev = cortex_a8_event_table;
1458                         evfence = cortex_a8_event_table + PMC_EVENT_TABLE_SIZE(cortex_a8);
1459                         break;
1460                 case PMC_CPU_ARMV7_CORTEX_A9:
1461                         ev = cortex_a9_event_table;
1462                         evfence = cortex_a9_event_table + PMC_EVENT_TABLE_SIZE(cortex_a9);
1463                         break;
1464                 default:        /* Unknown CPU type. */
1465                         break;
1466                 }
1467         } else if (pe >= PMC_EV_ARMV8_FIRST && pe <= PMC_EV_ARMV8_LAST) {
1468                 switch (cpu) {
1469                 case PMC_CPU_ARMV8_CORTEX_A53:
1470                         ev = cortex_a53_event_table;
1471                         evfence = cortex_a53_event_table + PMC_EVENT_TABLE_SIZE(cortex_a53);
1472                         break;
1473                 case PMC_CPU_ARMV8_CORTEX_A57:
1474                         ev = cortex_a57_event_table;
1475                         evfence = cortex_a57_event_table + PMC_EVENT_TABLE_SIZE(cortex_a57);
1476                         break;
1477                 case PMC_CPU_ARMV8_CORTEX_A76:
1478                         ev = cortex_a76_event_table;
1479                         evfence = cortex_a76_event_table + PMC_EVENT_TABLE_SIZE(cortex_a76);
1480                         break;
1481                 default:        /* Unknown CPU type. */
1482                         break;
1483                 }
1484         } else if (pe >= PMC_EV_PPC7450_FIRST && pe <= PMC_EV_PPC7450_LAST) {
1485                 ev = ppc7450_event_table;
1486                 evfence = ppc7450_event_table + PMC_EVENT_TABLE_SIZE(ppc7450);
1487         } else if (pe >= PMC_EV_PPC970_FIRST && pe <= PMC_EV_PPC970_LAST) {
1488                 ev = ppc970_event_table;
1489                 evfence = ppc970_event_table + PMC_EVENT_TABLE_SIZE(ppc970);
1490         } else if (pe >= PMC_EV_E500_FIRST && pe <= PMC_EV_E500_LAST) {
1491                 ev = e500_event_table;
1492                 evfence = e500_event_table + PMC_EVENT_TABLE_SIZE(e500);
1493         } else if (pe == PMC_EV_TSC_TSC) {
1494                 ev = tsc_event_table;
1495                 evfence = tsc_event_table + PMC_EVENT_TABLE_SIZE(tsc);
1496         } else if ((int)pe >= PMC_EV_SOFT_FIRST && (int)pe <= PMC_EV_SOFT_LAST) {
1497                 ev = soft_event_table;
1498                 evfence = soft_event_table + soft_event_info.pm_nevent;
1499         }
1500
1501         for (; ev != evfence; ev++)
1502                 if (pe == ev->pm_ev_code)
1503                         return (ev->pm_ev_name);
1504
1505         return (NULL);
1506 }
1507
1508 const char *
1509 pmc_name_of_event(enum pmc_event pe)
1510 {
1511         const char *n;
1512
1513         if ((n = _pmc_name_of_event(pe, cpu_info.pm_cputype)) != NULL)
1514                 return (n);
1515
1516         errno = EINVAL;
1517         return (NULL);
1518 }
1519
1520 const char *
1521 pmc_name_of_mode(enum pmc_mode pm)
1522 {
1523         if ((int) pm >= PMC_MODE_FIRST &&
1524             pm <= PMC_MODE_LAST)
1525                 return (pmc_mode_names[pm]);
1526
1527         errno = EINVAL;
1528         return (NULL);
1529 }
1530
1531 const char *
1532 pmc_name_of_state(enum pmc_state ps)
1533 {
1534         if ((int) ps >= PMC_STATE_FIRST &&
1535             ps <= PMC_STATE_LAST)
1536                 return (pmc_state_names[ps]);
1537
1538         errno = EINVAL;
1539         return (NULL);
1540 }
1541
1542 int
1543 pmc_ncpu(void)
1544 {
1545         if (pmc_syscall == -1) {
1546                 errno = ENXIO;
1547                 return (-1);
1548         }
1549
1550         return (cpu_info.pm_ncpu);
1551 }
1552
1553 int
1554 pmc_npmc(int cpu)
1555 {
1556         if (pmc_syscall == -1) {
1557                 errno = ENXIO;
1558                 return (-1);
1559         }
1560
1561         if (cpu < 0 || cpu >= (int) cpu_info.pm_ncpu) {
1562                 errno = EINVAL;
1563                 return (-1);
1564         }
1565
1566         return (cpu_info.pm_npmc);
1567 }
1568
1569 int
1570 pmc_pmcinfo(int cpu, struct pmc_pmcinfo **ppmci)
1571 {
1572         int nbytes, npmc;
1573         struct pmc_op_getpmcinfo *pmci;
1574
1575         if ((npmc = pmc_npmc(cpu)) < 0)
1576                 return (-1);
1577
1578         nbytes = sizeof(struct pmc_op_getpmcinfo) +
1579             npmc * sizeof(struct pmc_info);
1580
1581         if ((pmci = calloc(1, nbytes)) == NULL)
1582                 return (-1);
1583
1584         pmci->pm_cpu  = cpu;
1585
1586         if (PMC_CALL(GETPMCINFO, pmci) < 0) {
1587                 free(pmci);
1588                 return (-1);
1589         }
1590
1591         /* kernel<->library, library<->userland interfaces are identical */
1592         *ppmci = (struct pmc_pmcinfo *) pmci;
1593         return (0);
1594 }
1595
1596 int
1597 pmc_read(pmc_id_t pmc, pmc_value_t *value)
1598 {
1599         struct pmc_op_pmcrw pmc_read_op;
1600
1601         pmc_read_op.pm_pmcid = pmc;
1602         pmc_read_op.pm_flags = PMC_F_OLDVALUE;
1603         pmc_read_op.pm_value = -1;
1604
1605         if (PMC_CALL(PMCRW, &pmc_read_op) < 0)
1606                 return (-1);
1607
1608         *value = pmc_read_op.pm_value;
1609         return (0);
1610 }
1611
1612 int
1613 pmc_release(pmc_id_t pmc)
1614 {
1615         struct pmc_op_simple    pmc_release_args;
1616
1617         pmc_release_args.pm_pmcid = pmc;
1618         return (PMC_CALL(PMCRELEASE, &pmc_release_args));
1619 }
1620
1621 int
1622 pmc_rw(pmc_id_t pmc, pmc_value_t newvalue, pmc_value_t *oldvaluep)
1623 {
1624         struct pmc_op_pmcrw pmc_rw_op;
1625
1626         pmc_rw_op.pm_pmcid = pmc;
1627         pmc_rw_op.pm_flags = PMC_F_NEWVALUE | PMC_F_OLDVALUE;
1628         pmc_rw_op.pm_value = newvalue;
1629
1630         if (PMC_CALL(PMCRW, &pmc_rw_op) < 0)
1631                 return (-1);
1632
1633         *oldvaluep = pmc_rw_op.pm_value;
1634         return (0);
1635 }
1636
1637 int
1638 pmc_set(pmc_id_t pmc, pmc_value_t value)
1639 {
1640         struct pmc_op_pmcsetcount sc;
1641
1642         sc.pm_pmcid = pmc;
1643         sc.pm_count = value;
1644
1645         if (PMC_CALL(PMCSETCOUNT, &sc) < 0)
1646                 return (-1);
1647         return (0);
1648 }
1649
1650 int
1651 pmc_start(pmc_id_t pmc)
1652 {
1653         struct pmc_op_simple    pmc_start_args;
1654
1655         pmc_start_args.pm_pmcid = pmc;
1656         return (PMC_CALL(PMCSTART, &pmc_start_args));
1657 }
1658
1659 int
1660 pmc_stop(pmc_id_t pmc)
1661 {
1662         struct pmc_op_simple    pmc_stop_args;
1663
1664         pmc_stop_args.pm_pmcid = pmc;
1665         return (PMC_CALL(PMCSTOP, &pmc_stop_args));
1666 }
1667
1668 int
1669 pmc_width(pmc_id_t pmcid, uint32_t *width)
1670 {
1671         unsigned int i;
1672         enum pmc_class cl;
1673
1674         cl = PMC_ID_TO_CLASS(pmcid);
1675         for (i = 0; i < cpu_info.pm_nclass; i++)
1676                 if (cpu_info.pm_classes[i].pm_class == cl) {
1677                         *width = cpu_info.pm_classes[i].pm_width;
1678                         return (0);
1679                 }
1680         errno = EINVAL;
1681         return (-1);
1682 }
1683
1684 int
1685 pmc_write(pmc_id_t pmc, pmc_value_t value)
1686 {
1687         struct pmc_op_pmcrw pmc_write_op;
1688
1689         pmc_write_op.pm_pmcid = pmc;
1690         pmc_write_op.pm_flags = PMC_F_NEWVALUE;
1691         pmc_write_op.pm_value = value;
1692         return (PMC_CALL(PMCRW, &pmc_write_op));
1693 }
1694
1695 int
1696 pmc_writelog(uint32_t userdata)
1697 {
1698         struct pmc_op_writelog wl;
1699
1700         wl.pm_userdata = userdata;
1701         return (PMC_CALL(WRITELOG, &wl));
1702 }