]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/hwpmc/hwpmc_mod.c
Merge ^/vendor/llvm-project/release-10.x up to its last change (upstream
[FreeBSD/FreeBSD.git] / sys / dev / hwpmc / hwpmc_mod.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003-2008 Joseph Koshy
5  * Copyright (c) 2007 The FreeBSD Foundation
6  * Copyright (c) 2018 Matthew Macy
7  * All rights reserved.
8  *
9  * Portions of this software were developed by A. Joseph Koshy under
10  * sponsorship from the FreeBSD Foundation and Google, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/domainset.h>
40 #include <sys/eventhandler.h>
41 #include <sys/gtaskqueue.h>
42 #include <sys/jail.h>
43 #include <sys/kernel.h>
44 #include <sys/kthread.h>
45 #include <sys/limits.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/module.h>
49 #include <sys/mount.h>
50 #include <sys/mutex.h>
51 #include <sys/pmc.h>
52 #include <sys/pmckern.h>
53 #include <sys/pmclog.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/queue.h>
57 #include <sys/resourcevar.h>
58 #include <sys/rwlock.h>
59 #include <sys/sched.h>
60 #include <sys/signalvar.h>
61 #include <sys/smp.h>
62 #include <sys/sx.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
65 #include <sys/syslog.h>
66 #include <sys/systm.h>
67 #include <sys/vnode.h>
68
69 #include <sys/linker.h>         /* needs to be after <sys/malloc.h> */
70
71 #include <machine/atomic.h>
72 #include <machine/md_var.h>
73
74 #include <vm/vm.h>
75 #include <vm/vm_extern.h>
76 #include <vm/pmap.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_object.h>
79
80 #include "hwpmc_soft.h"
81
82 #define PMC_EPOCH_ENTER() struct epoch_tracker pmc_et; epoch_enter_preempt(global_epoch_preempt, &pmc_et)
83 #define PMC_EPOCH_EXIT() epoch_exit_preempt(global_epoch_preempt, &pmc_et)
84
85 /*
86  * Types
87  */
88
89 enum pmc_flags {
90         PMC_FLAG_NONE     = 0x00, /* do nothing */
91         PMC_FLAG_REMOVE   = 0x01, /* atomically remove entry from hash */
92         PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
93         PMC_FLAG_NOWAIT   = 0x04, /* do not wait for mallocs */
94 };
95
96 /*
97  * The offset in sysent where the syscall is allocated.
98  */
99
100 static int pmc_syscall_num = NO_SYSCALL;
101 struct pmc_cpu          **pmc_pcpu;      /* per-cpu state */
102 pmc_value_t             *pmc_pcpu_saved; /* saved PMC values: CSW handling */
103
104 #define PMC_PCPU_SAVED(C,R)     pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
105
106 struct mtx_pool         *pmc_mtxpool;
107 static int              *pmc_pmcdisp;    /* PMC row dispositions */
108
109 #define PMC_ROW_DISP_IS_FREE(R)         (pmc_pmcdisp[(R)] == 0)
110 #define PMC_ROW_DISP_IS_THREAD(R)       (pmc_pmcdisp[(R)] > 0)
111 #define PMC_ROW_DISP_IS_STANDALONE(R)   (pmc_pmcdisp[(R)] < 0)
112
113 #define PMC_MARK_ROW_FREE(R) do {                                         \
114         pmc_pmcdisp[(R)] = 0;                                             \
115 } while (0)
116
117 #define PMC_MARK_ROW_STANDALONE(R) do {                                   \
118         KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
119                     __LINE__));                                           \
120         atomic_add_int(&pmc_pmcdisp[(R)], -1);                            \
121         KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()),              \
122                 ("[pmc,%d] row disposition error", __LINE__));            \
123 } while (0)
124
125 #define PMC_UNMARK_ROW_STANDALONE(R) do {                                 \
126         atomic_add_int(&pmc_pmcdisp[(R)], 1);                             \
127         KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
128                     __LINE__));                                           \
129 } while (0)
130
131 #define PMC_MARK_ROW_THREAD(R) do {                                       \
132         KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
133                     __LINE__));                                           \
134         atomic_add_int(&pmc_pmcdisp[(R)], 1);                             \
135 } while (0)
136
137 #define PMC_UNMARK_ROW_THREAD(R) do {                                     \
138         atomic_add_int(&pmc_pmcdisp[(R)], -1);                            \
139         KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
140                     __LINE__));                                           \
141 } while (0)
142
143
144 /* various event handlers */
145 static eventhandler_tag pmc_exit_tag, pmc_fork_tag, pmc_kld_load_tag,
146     pmc_kld_unload_tag;
147
148 /* Module statistics */
149 struct pmc_driverstats pmc_stats;
150
151
152 /* Machine/processor dependent operations */
153 static struct pmc_mdep  *md;
154
155 /*
156  * Hash tables mapping owner processes and target threads to PMCs.
157  */
158
159 struct mtx pmc_processhash_mtx;         /* spin mutex */
160 static u_long pmc_processhashmask;
161 static LIST_HEAD(pmc_processhash, pmc_process)  *pmc_processhash;
162
163 /*
164  * Hash table of PMC owner descriptors.  This table is protected by
165  * the shared PMC "sx" lock.
166  */
167
168 static u_long pmc_ownerhashmask;
169 static LIST_HEAD(pmc_ownerhash, pmc_owner)      *pmc_ownerhash;
170
171 /*
172  * List of PMC owners with system-wide sampling PMCs.
173  */
174
175 static CK_LIST_HEAD(, pmc_owner)                        pmc_ss_owners;
176
177 /*
178  * List of free thread entries. This is protected by the spin
179  * mutex.
180  */
181 static struct mtx pmc_threadfreelist_mtx;       /* spin mutex */
182 static LIST_HEAD(, pmc_thread)                  pmc_threadfreelist;
183 static int pmc_threadfreelist_entries=0;
184 #define THREADENTRY_SIZE                                                \
185 (sizeof(struct pmc_thread) + (md->pmd_npmc * sizeof(struct pmc_threadpmcstate)))
186
187 /*
188  * Task to free thread descriptors
189  */
190 static struct grouptask free_gtask;
191
192 /*
193  * A map of row indices to classdep structures.
194  */
195 static struct pmc_classdep **pmc_rowindex_to_classdep;
196
197 /*
198  * Prototypes
199  */
200
201 #ifdef  HWPMC_DEBUG
202 static int      pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
203 static int      pmc_debugflags_parse(char *newstr, char *fence);
204 #endif
205
206 static int      load(struct module *module, int cmd, void *arg);
207 static int      pmc_add_sample(ring_type_t ring, struct pmc *pm, struct trapframe *tf);
208 static void     pmc_add_thread_descriptors_from_proc(struct proc *p,
209     struct pmc_process *pp);
210 static int      pmc_attach_process(struct proc *p, struct pmc *pm);
211 static struct pmc *pmc_allocate_pmc_descriptor(void);
212 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
213 static int      pmc_attach_one_process(struct proc *p, struct pmc *pm);
214 static int      pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
215     int cpu);
216 static int      pmc_can_attach(struct pmc *pm, struct proc *p);
217 static void     pmc_capture_user_callchain(int cpu, int soft, struct trapframe *tf);
218 static void     pmc_cleanup(void);
219 static int      pmc_detach_process(struct proc *p, struct pmc *pm);
220 static int      pmc_detach_one_process(struct proc *p, struct pmc *pm,
221     int flags);
222 static void     pmc_destroy_owner_descriptor(struct pmc_owner *po);
223 static void     pmc_destroy_pmc_descriptor(struct pmc *pm);
224 static void     pmc_destroy_process_descriptor(struct pmc_process *pp);
225 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
226 static int      pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
227 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
228     pmc_id_t pmc);
229 static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
230     uint32_t mode);
231 static struct pmc_thread *pmc_find_thread_descriptor(struct pmc_process *pp,
232     struct thread *td, uint32_t mode);
233 static void     pmc_force_context_switch(void);
234 static void     pmc_link_target_process(struct pmc *pm,
235     struct pmc_process *pp);
236 static void     pmc_log_all_process_mappings(struct pmc_owner *po);
237 static void     pmc_log_kernel_mappings(struct pmc *pm);
238 static void     pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
239 static void     pmc_maybe_remove_owner(struct pmc_owner *po);
240 static void     pmc_process_csw_in(struct thread *td);
241 static void     pmc_process_csw_out(struct thread *td);
242 static void     pmc_process_exit(void *arg, struct proc *p);
243 static void     pmc_process_fork(void *arg, struct proc *p1,
244     struct proc *p2, int n);
245 static void     pmc_process_samples(int cpu, ring_type_t soft);
246 static void     pmc_release_pmc_descriptor(struct pmc *pmc);
247 static void     pmc_process_thread_add(struct thread *td);
248 static void     pmc_process_thread_delete(struct thread *td);
249 static void     pmc_process_thread_userret(struct thread *td);
250 static void     pmc_remove_owner(struct pmc_owner *po);
251 static void     pmc_remove_process_descriptor(struct pmc_process *pp);
252 static void     pmc_restore_cpu_binding(struct pmc_binding *pb);
253 static void     pmc_save_cpu_binding(struct pmc_binding *pb);
254 static void     pmc_select_cpu(int cpu);
255 static int      pmc_start(struct pmc *pm);
256 static int      pmc_stop(struct pmc *pm);
257 static int      pmc_syscall_handler(struct thread *td, void *syscall_args);
258 static struct pmc_thread *pmc_thread_descriptor_pool_alloc(void);
259 static void     pmc_thread_descriptor_pool_drain(void);
260 static void     pmc_thread_descriptor_pool_free(struct pmc_thread *pt);
261 static void     pmc_unlink_target_process(struct pmc *pmc,
262     struct pmc_process *pp);
263 static int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
264 static int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
265 static struct pmc_mdep *pmc_generic_cpu_initialize(void);
266 static void pmc_generic_cpu_finalize(struct pmc_mdep *md);
267 static void pmc_post_callchain_callback(void);
268 static void pmc_process_threadcreate(struct thread *td);
269 static void pmc_process_threadexit(struct thread *td);
270 static void pmc_process_proccreate(struct proc *p);
271 static void pmc_process_allproc(struct pmc *pm);
272
273 /*
274  * Kernel tunables and sysctl(8) interface.
275  */
276
277 SYSCTL_DECL(_kern_hwpmc);
278 SYSCTL_NODE(_kern_hwpmc, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
279     "HWPMC stats");
280
281
282 /* Stats. */
283 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_ignored, CTLFLAG_RW,
284                                    &pmc_stats.pm_intr_ignored, "# of interrupts ignored");
285 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_processed, CTLFLAG_RW,
286                                    &pmc_stats.pm_intr_processed, "# of interrupts processed");
287 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_bufferfull, CTLFLAG_RW,
288                                    &pmc_stats.pm_intr_bufferfull, "# of interrupts where buffer was full");
289 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscalls, CTLFLAG_RW,
290                                    &pmc_stats.pm_syscalls, "# of syscalls");
291 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscall_errors, CTLFLAG_RW,
292                                    &pmc_stats.pm_syscall_errors, "# of syscall_errors");
293 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests, CTLFLAG_RW,
294                                    &pmc_stats.pm_buffer_requests, "# of buffer requests");
295 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests_failed, CTLFLAG_RW,
296                                    &pmc_stats.pm_buffer_requests_failed, "# of buffer requests which failed");
297 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, log_sweeps, CTLFLAG_RW,
298                                    &pmc_stats.pm_log_sweeps, "# of ?");
299 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, merges, CTLFLAG_RW,
300                                    &pmc_stats.pm_merges, "# of times kernel stack was found for user trace");
301 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, overwrites, CTLFLAG_RW,
302                                    &pmc_stats.pm_overwrites, "# of times a sample was overwritten before being logged");
303
304 static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
305 SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_RDTUN,
306     &pmc_callchaindepth, 0, "depth of call chain records");
307
308 char pmc_cpuid[64];
309 SYSCTL_STRING(_kern_hwpmc, OID_AUTO, cpuid, CTLFLAG_RD,
310         pmc_cpuid, 0, "cpu version string");
311 #ifdef  HWPMC_DEBUG
312 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
313 char    pmc_debugstr[PMC_DEBUG_STRSIZE];
314 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
315     sizeof(pmc_debugstr));
316 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
317     CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_NEEDGIANT,
318     0, 0, pmc_debugflags_sysctl_handler, "A",
319     "debug flags");
320 #endif
321
322
323 /*
324  * kern.hwpmc.hashrows -- determines the number of rows in the
325  * of the hash table used to look up threads
326  */
327
328 static int pmc_hashsize = PMC_HASH_SIZE;
329 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_RDTUN,
330     &pmc_hashsize, 0, "rows in hash tables");
331
332 /*
333  * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
334  */
335
336 static int pmc_nsamples = PMC_NSAMPLES;
337 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_RDTUN,
338     &pmc_nsamples, 0, "number of PC samples per CPU");
339
340 static uint64_t pmc_sample_mask = PMC_NSAMPLES-1;
341
342 /*
343  * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
344  */
345
346 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
347 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_RDTUN,
348     &pmc_mtxpool_size, 0, "size of spin mutex pool");
349
350
351 /*
352  * kern.hwpmc.threadfreelist_entries -- number of free entries
353  */
354
355 SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_entries, CTLFLAG_RD,
356     &pmc_threadfreelist_entries, 0, "number of avalable thread entries");
357
358
359 /*
360  * kern.hwpmc.threadfreelist_max -- maximum number of free entries
361  */
362
363 static int pmc_threadfreelist_max = PMC_THREADLIST_MAX;
364 SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_max, CTLFLAG_RW,
365     &pmc_threadfreelist_max, 0,
366     "maximum number of available thread entries before freeing some");
367
368
369 /*
370  * security.bsd.unprivileged_syspmcs -- allow non-root processes to
371  * allocate system-wide PMCs.
372  *
373  * Allowing unprivileged processes to allocate system PMCs is convenient
374  * if system-wide measurements need to be taken concurrently with other
375  * per-process measurements.  This feature is turned off by default.
376  */
377
378 static int pmc_unprivileged_syspmcs = 0;
379 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RWTUN,
380     &pmc_unprivileged_syspmcs, 0,
381     "allow unprivileged process to allocate system PMCs");
382
383 /*
384  * Hash function.  Discard the lower 2 bits of the pointer since
385  * these are always zero for our uses.  The hash multiplier is
386  * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
387  */
388
389 #if     LONG_BIT == 64
390 #define _PMC_HM         11400714819323198486u
391 #elif   LONG_BIT == 32
392 #define _PMC_HM         2654435769u
393 #else
394 #error  Must know the size of 'long' to compile
395 #endif
396
397 #define PMC_HASH_PTR(P,M)       ((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
398
399 /*
400  * Syscall structures
401  */
402
403 /* The `sysent' for the new syscall */
404 static struct sysent pmc_sysent = {
405         .sy_narg =      2,
406         .sy_call =      pmc_syscall_handler,
407 };
408
409 static struct syscall_module_data pmc_syscall_mod = {
410         .chainevh =     load,
411         .chainarg =     NULL,
412         .offset =       &pmc_syscall_num,
413         .new_sysent =   &pmc_sysent,
414         .old_sysent =   { .sy_narg = 0, .sy_call = NULL },
415         .flags =        SY_THR_STATIC_KLD,
416 };
417
418 static moduledata_t pmc_mod = {
419         .name =         PMC_MODULE_NAME,
420         .evhand =       syscall_module_handler,
421         .priv =         &pmc_syscall_mod,
422 };
423
424 #ifdef EARLY_AP_STARTUP
425 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SYSCALLS, SI_ORDER_ANY);
426 #else
427 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
428 #endif
429 MODULE_VERSION(pmc, PMC_VERSION);
430
431 #ifdef  HWPMC_DEBUG
432 enum pmc_dbgparse_state {
433         PMCDS_WS,               /* in whitespace */
434         PMCDS_MAJOR,            /* seen a major keyword */
435         PMCDS_MINOR
436 };
437
438 static int
439 pmc_debugflags_parse(char *newstr, char *fence)
440 {
441         char c, *p, *q;
442         struct pmc_debugflags *tmpflags;
443         int error, found, *newbits, tmp;
444         size_t kwlen;
445
446         tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK|M_ZERO);
447
448         p = newstr;
449         error = 0;
450
451         for (; p < fence && (c = *p); p++) {
452
453                 /* skip white space */
454                 if (c == ' ' || c == '\t')
455                         continue;
456
457                 /* look for a keyword followed by "=" */
458                 for (q = p; p < fence && (c = *p) && c != '='; p++)
459                         ;
460                 if (c != '=') {
461                         error = EINVAL;
462                         goto done;
463                 }
464
465                 kwlen = p - q;
466                 newbits = NULL;
467
468                 /* lookup flag group name */
469 #define DBG_SET_FLAG_MAJ(S,F)                                           \
470                 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)  \
471                         newbits = &tmpflags->pdb_ ## F;
472
473                 DBG_SET_FLAG_MAJ("cpu",         CPU);
474                 DBG_SET_FLAG_MAJ("csw",         CSW);
475                 DBG_SET_FLAG_MAJ("logging",     LOG);
476                 DBG_SET_FLAG_MAJ("module",      MOD);
477                 DBG_SET_FLAG_MAJ("md",          MDP);
478                 DBG_SET_FLAG_MAJ("owner",       OWN);
479                 DBG_SET_FLAG_MAJ("pmc",         PMC);
480                 DBG_SET_FLAG_MAJ("process",     PRC);
481                 DBG_SET_FLAG_MAJ("sampling",    SAM);
482
483                 if (newbits == NULL) {
484                         error = EINVAL;
485                         goto done;
486                 }
487
488                 p++;            /* skip the '=' */
489
490                 /* Now parse the individual flags */
491                 tmp = 0;
492         newflag:
493                 for (q = p; p < fence && (c = *p); p++)
494                         if (c == ' ' || c == '\t' || c == ',')
495                                 break;
496
497                 /* p == fence or c == ws or c == "," or c == 0 */
498
499                 if ((kwlen = p - q) == 0) {
500                         *newbits = tmp;
501                         continue;
502                 }
503
504                 found = 0;
505 #define DBG_SET_FLAG_MIN(S,F)                                           \
506                 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)  \
507                         tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
508
509                 /* a '*' denotes all possible flags in the group */
510                 if (kwlen == 1 && *q == '*')
511                         tmp = found = ~0;
512                 /* look for individual flag names */
513                 DBG_SET_FLAG_MIN("allocaterow", ALR);
514                 DBG_SET_FLAG_MIN("allocate",    ALL);
515                 DBG_SET_FLAG_MIN("attach",      ATT);
516                 DBG_SET_FLAG_MIN("bind",        BND);
517                 DBG_SET_FLAG_MIN("config",      CFG);
518                 DBG_SET_FLAG_MIN("exec",        EXC);
519                 DBG_SET_FLAG_MIN("exit",        EXT);
520                 DBG_SET_FLAG_MIN("find",        FND);
521                 DBG_SET_FLAG_MIN("flush",       FLS);
522                 DBG_SET_FLAG_MIN("fork",        FRK);
523                 DBG_SET_FLAG_MIN("getbuf",      GTB);
524                 DBG_SET_FLAG_MIN("hook",        PMH);
525                 DBG_SET_FLAG_MIN("init",        INI);
526                 DBG_SET_FLAG_MIN("intr",        INT);
527                 DBG_SET_FLAG_MIN("linktarget",  TLK);
528                 DBG_SET_FLAG_MIN("mayberemove", OMR);
529                 DBG_SET_FLAG_MIN("ops",         OPS);
530                 DBG_SET_FLAG_MIN("read",        REA);
531                 DBG_SET_FLAG_MIN("register",    REG);
532                 DBG_SET_FLAG_MIN("release",     REL);
533                 DBG_SET_FLAG_MIN("remove",      ORM);
534                 DBG_SET_FLAG_MIN("sample",      SAM);
535                 DBG_SET_FLAG_MIN("scheduleio",  SIO);
536                 DBG_SET_FLAG_MIN("select",      SEL);
537                 DBG_SET_FLAG_MIN("signal",      SIG);
538                 DBG_SET_FLAG_MIN("swi",         SWI);
539                 DBG_SET_FLAG_MIN("swo",         SWO);
540                 DBG_SET_FLAG_MIN("start",       STA);
541                 DBG_SET_FLAG_MIN("stop",        STO);
542                 DBG_SET_FLAG_MIN("syscall",     PMS);
543                 DBG_SET_FLAG_MIN("unlinktarget", TUL);
544                 DBG_SET_FLAG_MIN("write",       WRI);
545                 if (found == 0) {
546                         /* unrecognized flag name */
547                         error = EINVAL;
548                         goto done;
549                 }
550
551                 if (c == 0 || c == ' ' || c == '\t') {  /* end of flag group */
552                         *newbits = tmp;
553                         continue;
554                 }
555
556                 p++;
557                 goto newflag;
558         }
559
560         /* save the new flag set */
561         bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
562
563  done:
564         free(tmpflags, M_PMC);
565         return error;
566 }
567
568 static int
569 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
570 {
571         char *fence, *newstr;
572         int error;
573         unsigned int n;
574
575         (void) arg1; (void) arg2; /* unused parameters */
576
577         n = sizeof(pmc_debugstr);
578         newstr = malloc(n, M_PMC, M_WAITOK|M_ZERO);
579         (void) strlcpy(newstr, pmc_debugstr, n);
580
581         error = sysctl_handle_string(oidp, newstr, n, req);
582
583         /* if there is a new string, parse and copy it */
584         if (error == 0 && req->newptr != NULL) {
585                 fence = newstr + (n < req->newlen ? n : req->newlen + 1);
586                 if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
587                         (void) strlcpy(pmc_debugstr, newstr,
588                             sizeof(pmc_debugstr));
589         }
590
591         free(newstr, M_PMC);
592
593         return error;
594 }
595 #endif
596
597 /*
598  * Map a row index to a classdep structure and return the adjusted row
599  * index for the PMC class index.
600  */
601 static struct pmc_classdep *
602 pmc_ri_to_classdep(struct pmc_mdep *md, int ri, int *adjri)
603 {
604         struct pmc_classdep *pcd;
605
606         (void) md;
607
608         KASSERT(ri >= 0 && ri < md->pmd_npmc,
609             ("[pmc,%d] illegal row-index %d", __LINE__, ri));
610
611         pcd = pmc_rowindex_to_classdep[ri];
612
613         KASSERT(pcd != NULL,
614             ("[pmc,%d] ri %d null pcd", __LINE__, ri));
615
616         *adjri = ri - pcd->pcd_ri;
617
618         KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
619             ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));
620
621         return (pcd);
622 }
623
624 /*
625  * Concurrency Control
626  *
627  * The driver manages the following data structures:
628  *
629  *   - target process descriptors, one per target process
630  *   - owner process descriptors (and attached lists), one per owner process
631  *   - lookup hash tables for owner and target processes
632  *   - PMC descriptors (and attached lists)
633  *   - per-cpu hardware state
634  *   - the 'hook' variable through which the kernel calls into
635  *     this module
636  *   - the machine hardware state (managed by the MD layer)
637  *
638  * These data structures are accessed from:
639  *
640  * - thread context-switch code
641  * - interrupt handlers (possibly on multiple cpus)
642  * - kernel threads on multiple cpus running on behalf of user
643  *   processes doing system calls
644  * - this driver's private kernel threads
645  *
646  * = Locks and Locking strategy =
647  *
648  * The driver uses four locking strategies for its operation:
649  *
650  * - The global SX lock "pmc_sx" is used to protect internal
651  *   data structures.
652  *
653  *   Calls into the module by syscall() start with this lock being
654  *   held in exclusive mode.  Depending on the requested operation,
655  *   the lock may be downgraded to 'shared' mode to allow more
656  *   concurrent readers into the module.  Calls into the module from
657  *   other parts of the kernel acquire the lock in shared mode.
658  *
659  *   This SX lock is held in exclusive mode for any operations that
660  *   modify the linkages between the driver's internal data structures.
661  *
662  *   The 'pmc_hook' function pointer is also protected by this lock.
663  *   It is only examined with the sx lock held in exclusive mode.  The
664  *   kernel module is allowed to be unloaded only with the sx lock held
665  *   in exclusive mode.  In normal syscall handling, after acquiring the
666  *   pmc_sx lock we first check that 'pmc_hook' is non-null before
667  *   proceeding.  This prevents races between the thread unloading the module
668  *   and other threads seeking to use the module.
669  *
670  * - Lookups of target process structures and owner process structures
671  *   cannot use the global "pmc_sx" SX lock because these lookups need
672  *   to happen during context switches and in other critical sections
673  *   where sleeping is not allowed.  We protect these lookup tables
674  *   with their own private spin-mutexes, "pmc_processhash_mtx" and
675  *   "pmc_ownerhash_mtx".
676  *
677  * - Interrupt handlers work in a lock free manner.  At interrupt
678  *   time, handlers look at the PMC pointer (phw->phw_pmc) configured
679  *   when the PMC was started.  If this pointer is NULL, the interrupt
680  *   is ignored after updating driver statistics.  We ensure that this
681  *   pointer is set (using an atomic operation if necessary) before the
682  *   PMC hardware is started.  Conversely, this pointer is unset atomically
683  *   only after the PMC hardware is stopped.
684  *
685  *   We ensure that everything needed for the operation of an
686  *   interrupt handler is available without it needing to acquire any
687  *   locks.  We also ensure that a PMC's software state is destroyed only
688  *   after the PMC is taken off hardware (on all CPUs).
689  *
690  * - Context-switch handling with process-private PMCs needs more
691  *   care.
692  *
693  *   A given process may be the target of multiple PMCs.  For example,
694  *   PMCATTACH and PMCDETACH may be requested by a process on one CPU
695  *   while the target process is running on another.  A PMC could also
696  *   be getting released because its owner is exiting.  We tackle
697  *   these situations in the following manner:
698  *
699  *   - each target process structure 'pmc_process' has an array
700  *     of 'struct pmc *' pointers, one for each hardware PMC.
701  *
702  *   - At context switch IN time, each "target" PMC in RUNNING state
703  *     gets started on hardware and a pointer to each PMC is copied into
704  *     the per-cpu phw array.  The 'runcount' for the PMC is
705  *     incremented.
706  *
707  *   - At context switch OUT time, all process-virtual PMCs are stopped
708  *     on hardware.  The saved value is added to the PMCs value field
709  *     only if the PMC is in a non-deleted state (the PMCs state could
710  *     have changed during the current time slice).
711  *
712  *     Note that since in-between a switch IN on a processor and a switch
713  *     OUT, the PMC could have been released on another CPU.  Therefore
714  *     context switch OUT always looks at the hardware state to turn
715  *     OFF PMCs and will update a PMC's saved value only if reachable
716  *     from the target process record.
717  *
718  *   - OP PMCRELEASE could be called on a PMC at any time (the PMC could
719  *     be attached to many processes at the time of the call and could
720  *     be active on multiple CPUs).
721  *
722  *     We prevent further scheduling of the PMC by marking it as in
723  *     state 'DELETED'.  If the runcount of the PMC is non-zero then
724  *     this PMC is currently running on a CPU somewhere.  The thread
725  *     doing the PMCRELEASE operation waits by repeatedly doing a
726  *     pause() till the runcount comes to zero.
727  *
728  * The contents of a PMC descriptor (struct pmc) are protected using
729  * a spin-mutex.  In order to save space, we use a mutex pool.
730  *
731  * In terms of lock types used by witness(4), we use:
732  * - Type "pmc-sx", used by the global SX lock.
733  * - Type "pmc-sleep", for sleep mutexes used by logger threads.
734  * - Type "pmc-per-proc", for protecting PMC owner descriptors.
735  * - Type "pmc-leaf", used for all other spin mutexes.
736  */
737
738 /*
739  * save the cpu binding of the current kthread
740  */
741
742 static void
743 pmc_save_cpu_binding(struct pmc_binding *pb)
744 {
745         PMCDBG0(CPU,BND,2, "save-cpu");
746         thread_lock(curthread);
747         pb->pb_bound = sched_is_bound(curthread);
748         pb->pb_cpu   = curthread->td_oncpu;
749         thread_unlock(curthread);
750         PMCDBG1(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
751 }
752
753 /*
754  * restore the cpu binding of the current thread
755  */
756
757 static void
758 pmc_restore_cpu_binding(struct pmc_binding *pb)
759 {
760         PMCDBG2(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
761             curthread->td_oncpu, pb->pb_cpu);
762         thread_lock(curthread);
763         if (pb->pb_bound)
764                 sched_bind(curthread, pb->pb_cpu);
765         else
766                 sched_unbind(curthread);
767         thread_unlock(curthread);
768         PMCDBG0(CPU,BND,2, "restore-cpu done");
769 }
770
771 /*
772  * move execution over the specified cpu and bind it there.
773  */
774
775 static void
776 pmc_select_cpu(int cpu)
777 {
778         KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
779             ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
780
781         /* Never move to an inactive CPU. */
782         KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
783             "CPU %d", __LINE__, cpu));
784
785         PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d", cpu);
786         thread_lock(curthread);
787         sched_bind(curthread, cpu);
788         thread_unlock(curthread);
789
790         KASSERT(curthread->td_oncpu == cpu,
791             ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
792                 cpu, curthread->td_oncpu));
793
794         PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
795 }
796
797 /*
798  * Force a context switch.
799  *
800  * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
801  * guaranteed to force a context switch.
802  */
803
804 static void
805 pmc_force_context_switch(void)
806 {
807
808         pause("pmcctx", 1);
809 }
810
811 uint64_t
812 pmc_rdtsc(void)
813 {
814 #if defined(__i386__) || defined(__amd64__)
815         if (__predict_true(amd_feature & AMDID_RDTSCP))
816                 return rdtscp();
817         else
818                 return rdtsc();
819 #else
820         return get_cyclecount();
821 #endif
822 }
823
824 /*
825  * Get the file name for an executable.  This is a simple wrapper
826  * around vn_fullpath(9).
827  */
828
829 static void
830 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
831 {
832
833         *fullpath = "unknown";
834         *freepath = NULL;
835         vn_fullpath(curthread, v, fullpath, freepath);
836 }
837
838 /*
839  * remove an process owning PMCs
840  */
841
842 void
843 pmc_remove_owner(struct pmc_owner *po)
844 {
845         struct pmc *pm, *tmp;
846
847         sx_assert(&pmc_sx, SX_XLOCKED);
848
849         PMCDBG1(OWN,ORM,1, "remove-owner po=%p", po);
850
851         /* Remove descriptor from the owner hash table */
852         LIST_REMOVE(po, po_next);
853
854         /* release all owned PMC descriptors */
855         LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
856                 PMCDBG1(OWN,ORM,2, "pmc=%p", pm);
857                 KASSERT(pm->pm_owner == po,
858                     ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
859
860                 pmc_release_pmc_descriptor(pm); /* will unlink from the list */
861                 pmc_destroy_pmc_descriptor(pm);
862         }
863
864         KASSERT(po->po_sscount == 0,
865             ("[pmc,%d] SS count not zero", __LINE__));
866         KASSERT(LIST_EMPTY(&po->po_pmcs),
867             ("[pmc,%d] PMC list not empty", __LINE__));
868
869         /* de-configure the log file if present */
870         if (po->po_flags & PMC_PO_OWNS_LOGFILE)
871                 pmclog_deconfigure_log(po);
872 }
873
874 /*
875  * remove an owner process record if all conditions are met.
876  */
877
878 static void
879 pmc_maybe_remove_owner(struct pmc_owner *po)
880 {
881
882         PMCDBG1(OWN,OMR,1, "maybe-remove-owner po=%p", po);
883
884         /*
885          * Remove owner record if
886          * - this process does not own any PMCs
887          * - this process has not allocated a system-wide sampling buffer
888          */
889
890         if (LIST_EMPTY(&po->po_pmcs) &&
891             ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
892                 pmc_remove_owner(po);
893                 pmc_destroy_owner_descriptor(po);
894         }
895 }
896
897 /*
898  * Add an association between a target process and a PMC.
899  */
900
901 static void
902 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
903 {
904         int ri;
905         struct pmc_target *pt;
906 #ifdef INVARIANTS
907         struct pmc_thread *pt_td;
908 #endif
909
910         sx_assert(&pmc_sx, SX_XLOCKED);
911
912         KASSERT(pm != NULL && pp != NULL,
913             ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
914         KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
915             ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
916                 __LINE__, pm, pp->pp_proc->p_pid));
917         KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1),
918             ("[pmc,%d] Illegal reference count %d for process record %p",
919                 __LINE__, pp->pp_refcnt, (void *) pp));
920
921         ri = PMC_TO_ROWINDEX(pm);
922
923         PMCDBG3(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
924             pm, ri, pp);
925
926 #ifdef  HWPMC_DEBUG
927         LIST_FOREACH(pt, &pm->pm_targets, pt_next)
928             if (pt->pt_process == pp)
929                     KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
930                                 __LINE__, pp, pm));
931 #endif
932
933         pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK|M_ZERO);
934         pt->pt_process = pp;
935
936         LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
937
938         atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
939             (uintptr_t)pm);
940
941         if (pm->pm_owner->po_owner == pp->pp_proc)
942                 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
943
944         /*
945          * Initialize the per-process values at this row index.
946          */
947         pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
948             pm->pm_sc.pm_reloadcount : 0;
949
950         pp->pp_refcnt++;
951
952 #ifdef INVARIANTS
953         /* Confirm that the per-thread values at this row index are cleared. */
954         if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
955                 mtx_lock_spin(pp->pp_tdslock);
956                 LIST_FOREACH(pt_td, &pp->pp_tds, pt_next) {
957                         KASSERT(pt_td->pt_pmcs[ri].pt_pmcval == (pmc_value_t) 0,
958                             ("[pmc,%d] pt_pmcval not cleared for pid=%d at "
959                             "ri=%d", __LINE__, pp->pp_proc->p_pid, ri));
960                 }
961                 mtx_unlock_spin(pp->pp_tdslock);
962         }
963 #endif
964 }
965
966 /*
967  * Removes the association between a target process and a PMC.
968  */
969
970 static void
971 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
972 {
973         int ri;
974         struct proc *p;
975         struct pmc_target *ptgt;
976         struct pmc_thread *pt;
977
978         sx_assert(&pmc_sx, SX_XLOCKED);
979
980         KASSERT(pm != NULL && pp != NULL,
981             ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
982
983         KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc,
984             ("[pmc,%d] Illegal ref count %d on process record %p",
985                 __LINE__, pp->pp_refcnt, (void *) pp));
986
987         ri = PMC_TO_ROWINDEX(pm);
988
989         PMCDBG3(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
990             pm, ri, pp);
991
992         KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
993             ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
994                 ri, pm, pp->pp_pmcs[ri].pp_pmc));
995
996         pp->pp_pmcs[ri].pp_pmc = NULL;
997         pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
998
999         /* Clear the per-thread values at this row index. */
1000         if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1001                 mtx_lock_spin(pp->pp_tdslock);
1002                 LIST_FOREACH(pt, &pp->pp_tds, pt_next)
1003                         pt->pt_pmcs[ri].pt_pmcval = (pmc_value_t) 0;
1004                 mtx_unlock_spin(pp->pp_tdslock);
1005         }
1006
1007         /* Remove owner-specific flags */
1008         if (pm->pm_owner->po_owner == pp->pp_proc) {
1009                 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
1010                 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
1011         }
1012
1013         pp->pp_refcnt--;
1014
1015         /* Remove the target process from the PMC structure */
1016         LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
1017                 if (ptgt->pt_process == pp)
1018                         break;
1019
1020         KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
1021                     "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
1022
1023         LIST_REMOVE(ptgt, pt_next);
1024         free(ptgt, M_PMC);
1025
1026         /* if the PMC now lacks targets, send the owner a SIGIO */
1027         if (LIST_EMPTY(&pm->pm_targets)) {
1028                 p = pm->pm_owner->po_owner;
1029                 PROC_LOCK(p);
1030                 kern_psignal(p, SIGIO);
1031                 PROC_UNLOCK(p);
1032
1033                 PMCDBG2(PRC,SIG,2, "signalling proc=%p signal=%d", p,
1034                     SIGIO);
1035         }
1036 }
1037
1038 /*
1039  * Check if PMC 'pm' may be attached to target process 't'.
1040  */
1041
1042 static int
1043 pmc_can_attach(struct pmc *pm, struct proc *t)
1044 {
1045         struct proc *o;         /* pmc owner */
1046         struct ucred *oc, *tc;  /* owner, target credentials */
1047         int decline_attach, i;
1048
1049         /*
1050          * A PMC's owner can always attach that PMC to itself.
1051          */
1052
1053         if ((o = pm->pm_owner->po_owner) == t)
1054                 return 0;
1055
1056         PROC_LOCK(o);
1057         oc = o->p_ucred;
1058         crhold(oc);
1059         PROC_UNLOCK(o);
1060
1061         PROC_LOCK(t);
1062         tc = t->p_ucred;
1063         crhold(tc);
1064         PROC_UNLOCK(t);
1065
1066         /*
1067          * The effective uid of the PMC owner should match at least one
1068          * of the {effective,real,saved} uids of the target process.
1069          */
1070
1071         decline_attach = oc->cr_uid != tc->cr_uid &&
1072             oc->cr_uid != tc->cr_svuid &&
1073             oc->cr_uid != tc->cr_ruid;
1074
1075         /*
1076          * Every one of the target's group ids, must be in the owner's
1077          * group list.
1078          */
1079         for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
1080                 decline_attach = !groupmember(tc->cr_groups[i], oc);
1081
1082         /* check the read and saved gids too */
1083         if (decline_attach == 0)
1084                 decline_attach = !groupmember(tc->cr_rgid, oc) ||
1085                     !groupmember(tc->cr_svgid, oc);
1086
1087         crfree(tc);
1088         crfree(oc);
1089
1090         return !decline_attach;
1091 }
1092
1093 /*
1094  * Attach a process to a PMC.
1095  */
1096
1097 static int
1098 pmc_attach_one_process(struct proc *p, struct pmc *pm)
1099 {
1100         int ri, error;
1101         char *fullpath, *freepath;
1102         struct pmc_process      *pp;
1103
1104         sx_assert(&pmc_sx, SX_XLOCKED);
1105
1106         PMCDBG5(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
1107             PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1108
1109         /*
1110          * Locate the process descriptor corresponding to process 'p',
1111          * allocating space as needed.
1112          *
1113          * Verify that rowindex 'pm_rowindex' is free in the process
1114          * descriptor.
1115          *
1116          * If not, allocate space for a descriptor and link the
1117          * process descriptor and PMC.
1118          */
1119         ri = PMC_TO_ROWINDEX(pm);
1120
1121         /* mark process as using HWPMCs */
1122         PROC_LOCK(p);
1123         p->p_flag |= P_HWPMC;
1124         PROC_UNLOCK(p);
1125
1126         if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL) {
1127                 error = ENOMEM;
1128                 goto fail;
1129         }
1130
1131         if (pp->pp_pmcs[ri].pp_pmc == pm) {/* already present at slot [ri] */
1132                 error = EEXIST;
1133                 goto fail;
1134         }
1135
1136         if (pp->pp_pmcs[ri].pp_pmc != NULL) {
1137                 error = EBUSY;
1138                 goto fail;
1139         }
1140
1141         pmc_link_target_process(pm, pp);
1142
1143         if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
1144             (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
1145                 pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
1146
1147         pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
1148
1149         /* issue an attach event to a configured log file */
1150         if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
1151                 if (p->p_flag & P_KPROC) {
1152                         fullpath = kernelname;
1153                         freepath = NULL;
1154                 } else {
1155                         pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1156                         pmclog_process_pmcattach(pm, p->p_pid, fullpath);
1157                 }
1158                 free(freepath, M_TEMP);
1159                 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1160                         pmc_log_process_mappings(pm->pm_owner, p);
1161         }
1162
1163         return (0);
1164  fail:
1165         PROC_LOCK(p);
1166         p->p_flag &= ~P_HWPMC;
1167         PROC_UNLOCK(p);
1168         return (error);
1169 }
1170
1171 /*
1172  * Attach a process and optionally its children
1173  */
1174
1175 static int
1176 pmc_attach_process(struct proc *p, struct pmc *pm)
1177 {
1178         int error;
1179         struct proc *top;
1180
1181         sx_assert(&pmc_sx, SX_XLOCKED);
1182
1183         PMCDBG5(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1184             PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1185
1186
1187         /*
1188          * If this PMC successfully allowed a GETMSR operation
1189          * in the past, disallow further ATTACHes.
1190          */
1191
1192         if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1193                 return EPERM;
1194
1195         if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1196                 return pmc_attach_one_process(p, pm);
1197
1198         /*
1199          * Traverse all child processes, attaching them to
1200          * this PMC.
1201          */
1202
1203         sx_slock(&proctree_lock);
1204
1205         top = p;
1206
1207         for (;;) {
1208                 if ((error = pmc_attach_one_process(p, pm)) != 0)
1209                         break;
1210                 if (!LIST_EMPTY(&p->p_children))
1211                         p = LIST_FIRST(&p->p_children);
1212                 else for (;;) {
1213                         if (p == top)
1214                                 goto done;
1215                         if (LIST_NEXT(p, p_sibling)) {
1216                                 p = LIST_NEXT(p, p_sibling);
1217                                 break;
1218                         }
1219                         p = p->p_pptr;
1220                 }
1221         }
1222
1223         if (error)
1224                 (void) pmc_detach_process(top, pm);
1225
1226  done:
1227         sx_sunlock(&proctree_lock);
1228         return error;
1229 }
1230
1231 /*
1232  * Detach a process from a PMC.  If there are no other PMCs tracking
1233  * this process, remove the process structure from its hash table.  If
1234  * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1235  */
1236
1237 static int
1238 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1239 {
1240         int ri;
1241         struct pmc_process *pp;
1242
1243         sx_assert(&pmc_sx, SX_XLOCKED);
1244
1245         KASSERT(pm != NULL,
1246             ("[pmc,%d] null pm pointer", __LINE__));
1247
1248         ri = PMC_TO_ROWINDEX(pm);
1249
1250         PMCDBG6(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1251             pm, ri, p, p->p_pid, p->p_comm, flags);
1252
1253         if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1254                 return ESRCH;
1255
1256         if (pp->pp_pmcs[ri].pp_pmc != pm)
1257                 return EINVAL;
1258
1259         pmc_unlink_target_process(pm, pp);
1260
1261         /* Issue a detach entry if a log file is configured */
1262         if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1263                 pmclog_process_pmcdetach(pm, p->p_pid);
1264
1265         /*
1266          * If there are no PMCs targeting this process, we remove its
1267          * descriptor from the target hash table and unset the P_HWPMC
1268          * flag in the struct proc.
1269          */
1270         KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1271             ("[pmc,%d] Illegal refcnt %d for process struct %p",
1272                 __LINE__, pp->pp_refcnt, pp));
1273
1274         if (pp->pp_refcnt != 0) /* still a target of some PMC */
1275                 return 0;
1276
1277         pmc_remove_process_descriptor(pp);
1278
1279         if (flags & PMC_FLAG_REMOVE)
1280                 pmc_destroy_process_descriptor(pp);
1281
1282         PROC_LOCK(p);
1283         p->p_flag &= ~P_HWPMC;
1284         PROC_UNLOCK(p);
1285
1286         return 0;
1287 }
1288
1289 /*
1290  * Detach a process and optionally its descendants from a PMC.
1291  */
1292
1293 static int
1294 pmc_detach_process(struct proc *p, struct pmc *pm)
1295 {
1296         struct proc *top;
1297
1298         sx_assert(&pmc_sx, SX_XLOCKED);
1299
1300         PMCDBG5(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1301             PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1302
1303         if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1304                 return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1305
1306         /*
1307          * Traverse all children, detaching them from this PMC.  We
1308          * ignore errors since we could be detaching a PMC from a
1309          * partially attached proc tree.
1310          */
1311
1312         sx_slock(&proctree_lock);
1313
1314         top = p;
1315
1316         for (;;) {
1317                 (void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1318
1319                 if (!LIST_EMPTY(&p->p_children))
1320                         p = LIST_FIRST(&p->p_children);
1321                 else for (;;) {
1322                         if (p == top)
1323                                 goto done;
1324                         if (LIST_NEXT(p, p_sibling)) {
1325                                 p = LIST_NEXT(p, p_sibling);
1326                                 break;
1327                         }
1328                         p = p->p_pptr;
1329                 }
1330         }
1331
1332  done:
1333         sx_sunlock(&proctree_lock);
1334
1335         if (LIST_EMPTY(&pm->pm_targets))
1336                 pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1337
1338         return 0;
1339 }
1340
1341
1342 /*
1343  * Thread context switch IN
1344  */
1345
1346 static void
1347 pmc_process_csw_in(struct thread *td)
1348 {
1349         int cpu;
1350         unsigned int adjri, ri;
1351         struct pmc *pm;
1352         struct proc *p;
1353         struct pmc_cpu *pc;
1354         struct pmc_hw *phw;
1355         pmc_value_t newvalue;
1356         struct pmc_process *pp;
1357         struct pmc_thread *pt;
1358         struct pmc_classdep *pcd;
1359
1360         p = td->td_proc;
1361         pt = NULL;
1362         if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1363                 return;
1364
1365         KASSERT(pp->pp_proc == td->td_proc,
1366             ("[pmc,%d] not my thread state", __LINE__));
1367
1368         critical_enter(); /* no preemption from this point */
1369
1370         cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1371
1372         PMCDBG5(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1373             p->p_pid, p->p_comm, pp);
1374
1375         KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1376             ("[pmc,%d] weird CPU id %d", __LINE__, cpu));
1377
1378         pc = pmc_pcpu[cpu];
1379
1380         for (ri = 0; ri < md->pmd_npmc; ri++) {
1381
1382                 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1383                         continue;
1384
1385                 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1386                     ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1387                         __LINE__, PMC_TO_MODE(pm)));
1388
1389                 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1390                     ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1391                         __LINE__, PMC_TO_ROWINDEX(pm), ri));
1392
1393                 /*
1394                  * Only PMCs that are marked as 'RUNNING' need
1395                  * be placed on hardware.
1396                  */
1397
1398                 if (pm->pm_state != PMC_STATE_RUNNING)
1399                         continue;
1400
1401                 KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
1402             ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
1403                  (unsigned long)counter_u64_fetch(pm->pm_runcount)));
1404
1405                 /* increment PMC runcount */
1406                 counter_u64_add(pm->pm_runcount, 1);
1407
1408                 /* configure the HWPMC we are going to use. */
1409                 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1410                 pcd->pcd_config_pmc(cpu, adjri, pm);
1411
1412                 phw = pc->pc_hwpmcs[ri];
1413
1414                 KASSERT(phw != NULL,
1415                     ("[pmc,%d] null hw pointer", __LINE__));
1416
1417                 KASSERT(phw->phw_pmc == pm,
1418                     ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1419                         phw->phw_pmc, pm));
1420
1421                 /*
1422                  * Write out saved value and start the PMC.
1423                  *
1424                  * Sampling PMCs use a per-thread value, while
1425                  * counting mode PMCs use a per-pmc value that is
1426                  * inherited across descendants.
1427                  */
1428                 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1429                         if (pt == NULL)
1430                                 pt = pmc_find_thread_descriptor(pp, td,
1431                                     PMC_FLAG_NONE);
1432
1433                         KASSERT(pt != NULL,
1434                             ("[pmc,%d] No thread found for td=%p", __LINE__,
1435                             td));
1436
1437                         mtx_pool_lock_spin(pmc_mtxpool, pm);
1438
1439                         /*
1440                          * If we have a thread descriptor, use the per-thread
1441                          * counter in the descriptor. If not, we will use
1442                          * a per-process counter. 
1443                          *
1444                          * TODO: Remove the per-process "safety net" once
1445                          * we have thoroughly tested that we don't hit the
1446                          * above assert.
1447                          */
1448                         if (pt != NULL) {
1449                                 if (pt->pt_pmcs[ri].pt_pmcval > 0)
1450                                         newvalue = pt->pt_pmcs[ri].pt_pmcval;
1451                                 else
1452                                         newvalue = pm->pm_sc.pm_reloadcount;
1453                         } else {
1454                                 /*
1455                                  * Use the saved value calculated after the most
1456                                  * recent time a thread using the shared counter
1457                                  * switched out. Reset the saved count in case
1458                                  * another thread from this process switches in
1459                                  * before any threads switch out.
1460                                  */
1461
1462                                 newvalue = pp->pp_pmcs[ri].pp_pmcval;
1463                                 pp->pp_pmcs[ri].pp_pmcval =
1464                                     pm->pm_sc.pm_reloadcount;
1465                         }
1466                         mtx_pool_unlock_spin(pmc_mtxpool, pm);
1467                         KASSERT(newvalue > 0 && newvalue <=
1468                             pm->pm_sc.pm_reloadcount,
1469                             ("[pmc,%d] pmcval outside of expected range cpu=%d "
1470                             "ri=%d pmcval=%jx pm_reloadcount=%jx", __LINE__,
1471                             cpu, ri, newvalue, pm->pm_sc.pm_reloadcount));
1472                 } else {
1473                         KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1474                             ("[pmc,%d] illegal mode=%d", __LINE__,
1475                             PMC_TO_MODE(pm)));
1476                         mtx_pool_lock_spin(pmc_mtxpool, pm);
1477                         newvalue = PMC_PCPU_SAVED(cpu, ri) =
1478                             pm->pm_gv.pm_savedvalue;
1479                         mtx_pool_unlock_spin(pmc_mtxpool, pm);
1480                 }
1481
1482                 PMCDBG3(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1483
1484                 pcd->pcd_write_pmc(cpu, adjri, newvalue);
1485
1486                 /* If a sampling mode PMC, reset stalled state. */
1487                 if (PMC_TO_MODE(pm) == PMC_MODE_TS)
1488                         pm->pm_pcpu_state[cpu].pps_stalled = 0;
1489
1490                 /* Indicate that we desire this to run. */
1491                 pm->pm_pcpu_state[cpu].pps_cpustate = 1;
1492
1493                 /* Start the PMC. */
1494                 pcd->pcd_start_pmc(cpu, adjri);
1495         }
1496
1497         /*
1498          * perform any other architecture/cpu dependent thread
1499          * switch-in actions.
1500          */
1501
1502         (void) (*md->pmd_switch_in)(pc, pp);
1503
1504         critical_exit();
1505
1506 }
1507
1508 /*
1509  * Thread context switch OUT.
1510  */
1511
1512 static void
1513 pmc_process_csw_out(struct thread *td)
1514 {
1515         int cpu;
1516         int64_t tmp;
1517         struct pmc *pm;
1518         struct proc *p;
1519         enum pmc_mode mode;
1520         struct pmc_cpu *pc;
1521         pmc_value_t newvalue;
1522         unsigned int adjri, ri;
1523         struct pmc_process *pp;
1524         struct pmc_thread *pt = NULL;
1525         struct pmc_classdep *pcd;
1526
1527
1528         /*
1529          * Locate our process descriptor; this may be NULL if
1530          * this process is exiting and we have already removed
1531          * the process from the target process table.
1532          *
1533          * Note that due to kernel preemption, multiple
1534          * context switches may happen while the process is
1535          * exiting.
1536          *
1537          * Note also that if the target process cannot be
1538          * found we still need to deconfigure any PMCs that
1539          * are currently running on hardware.
1540          */
1541
1542         p = td->td_proc;
1543         pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1544
1545         /*
1546          * save PMCs
1547          */
1548
1549         critical_enter();
1550
1551         cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1552
1553         PMCDBG5(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1554             p->p_pid, p->p_comm, pp);
1555
1556         KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1557             ("[pmc,%d weird CPU id %d", __LINE__, cpu));
1558
1559         pc = pmc_pcpu[cpu];
1560
1561         /*
1562          * When a PMC gets unlinked from a target PMC, it will
1563          * be removed from the target's pp_pmc[] array.
1564          *
1565          * However, on a MP system, the target could have been
1566          * executing on another CPU at the time of the unlink.
1567          * So, at context switch OUT time, we need to look at
1568          * the hardware to determine if a PMC is scheduled on
1569          * it.
1570          */
1571
1572         for (ri = 0; ri < md->pmd_npmc; ri++) {
1573
1574                 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1575                 pm  = NULL;
1576                 (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
1577
1578                 if (pm == NULL) /* nothing at this row index */
1579                         continue;
1580
1581                 mode = PMC_TO_MODE(pm);
1582                 if (!PMC_IS_VIRTUAL_MODE(mode))
1583                         continue; /* not a process virtual PMC */
1584
1585                 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1586                     ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1587                         __LINE__, PMC_TO_ROWINDEX(pm), ri));
1588
1589                 /*
1590                  * Change desired state, and then stop if not stalled.
1591                  * This two-step dance should avoid race conditions where
1592                  * an interrupt re-enables the PMC after this code has
1593                  * already checked the pm_stalled flag.
1594                  */
1595                 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
1596                 if (pm->pm_pcpu_state[cpu].pps_stalled == 0)
1597                         pcd->pcd_stop_pmc(cpu, adjri);
1598
1599                 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
1600                         ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
1601                          (unsigned long)counter_u64_fetch(pm->pm_runcount)));
1602
1603                 /* reduce this PMC's runcount */
1604                 counter_u64_add(pm->pm_runcount, -1);
1605
1606                 /*
1607                  * If this PMC is associated with this process,
1608                  * save the reading.
1609                  */
1610
1611                 if (pm->pm_state != PMC_STATE_DELETED && pp != NULL &&
1612                     pp->pp_pmcs[ri].pp_pmc != NULL) {
1613                         KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1614                             ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1615                                 pm, ri, pp->pp_pmcs[ri].pp_pmc));
1616
1617                         KASSERT(pp->pp_refcnt > 0,
1618                             ("[pmc,%d] pp refcnt = %d", __LINE__,
1619                                 pp->pp_refcnt));
1620
1621                         pcd->pcd_read_pmc(cpu, adjri, &newvalue);
1622
1623                         if (mode == PMC_MODE_TS) {
1624                                 PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d val=%jd (samp)",
1625                                     cpu, ri, newvalue);
1626
1627                                 if (pt == NULL)
1628                                         pt = pmc_find_thread_descriptor(pp, td,
1629                                             PMC_FLAG_NONE);
1630
1631                                 KASSERT(pt != NULL,
1632                                     ("[pmc,%d] No thread found for td=%p",
1633                                     __LINE__, td));
1634
1635                                 mtx_pool_lock_spin(pmc_mtxpool, pm);
1636
1637                                 /*
1638                                  * If we have a thread descriptor, save the
1639                                  * per-thread counter in the descriptor. If not,
1640                                  * we will update the per-process counter.
1641                                  *
1642                                  * TODO: Remove the per-process "safety net"
1643                                  * once we have thoroughly tested that we
1644                                  * don't hit the above assert.
1645                                  */
1646                                 if (pt != NULL)
1647                                         pt->pt_pmcs[ri].pt_pmcval = newvalue;
1648                                 else {
1649                                         /*
1650                                          * For sampling process-virtual PMCs,
1651                                          * newvalue is the number of events to
1652                                          * be seen until the next sampling
1653                                          * interrupt. We can just add the events
1654                                          * left from this invocation to the
1655                                          * counter, then adjust in case we
1656                                          * overflow our range.
1657                                          *
1658                                          * (Recall that we reload the counter
1659                                          * every time we use it.)
1660                                          */
1661                                         pp->pp_pmcs[ri].pp_pmcval += newvalue;
1662                                         if (pp->pp_pmcs[ri].pp_pmcval >
1663                                             pm->pm_sc.pm_reloadcount)
1664                                                 pp->pp_pmcs[ri].pp_pmcval -=
1665                                                     pm->pm_sc.pm_reloadcount;
1666                                 }
1667                                 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1668                         } else {
1669                                 tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1670
1671                                 PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd (count)",
1672                                     cpu, ri, tmp);
1673
1674                                 /*
1675                                  * For counting process-virtual PMCs,
1676                                  * we expect the count to be
1677                                  * increasing monotonically, modulo a 64
1678                                  * bit wraparound.
1679                                  */
1680                                 KASSERT(tmp >= 0,
1681                                     ("[pmc,%d] negative increment cpu=%d "
1682                                      "ri=%d newvalue=%jx saved=%jx "
1683                                      "incr=%jx", __LINE__, cpu, ri,
1684                                      newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1685
1686                                 mtx_pool_lock_spin(pmc_mtxpool, pm);
1687                                 pm->pm_gv.pm_savedvalue += tmp;
1688                                 pp->pp_pmcs[ri].pp_pmcval += tmp;
1689                                 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1690
1691                                 if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1692                                         pmclog_process_proccsw(pm, pp, tmp, td);
1693                         }
1694                 }
1695
1696                 /* mark hardware as free */
1697                 pcd->pcd_config_pmc(cpu, adjri, NULL);
1698         }
1699
1700         /*
1701          * perform any other architecture/cpu dependent thread
1702          * switch out functions.
1703          */
1704
1705         (void) (*md->pmd_switch_out)(pc, pp);
1706
1707         critical_exit();
1708 }
1709
1710 /*
1711  * A new thread for a process.
1712  */
1713 static void
1714 pmc_process_thread_add(struct thread *td)
1715 {
1716         struct pmc_process *pmc;
1717
1718         pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
1719         if (pmc != NULL)
1720                 pmc_find_thread_descriptor(pmc, td, PMC_FLAG_ALLOCATE);
1721 }
1722
1723 /*
1724  * A thread delete for a process.
1725  */
1726 static void
1727 pmc_process_thread_delete(struct thread *td)
1728 {
1729         struct pmc_process *pmc;
1730
1731         pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
1732         if (pmc != NULL)
1733                 pmc_thread_descriptor_pool_free(pmc_find_thread_descriptor(pmc,
1734                     td, PMC_FLAG_REMOVE));
1735 }
1736
1737 /*
1738  * A userret() call for a thread.
1739  */
1740 static void
1741 pmc_process_thread_userret(struct thread *td)
1742 {
1743         sched_pin();
1744         pmc_capture_user_callchain(curcpu, PMC_UR, td->td_frame);
1745         sched_unpin();
1746 }
1747
1748 /*
1749  * A mapping change for a process.
1750  */
1751
1752 static void
1753 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1754 {
1755         int ri;
1756         pid_t pid;
1757         char *fullpath, *freepath;
1758         const struct pmc *pm;
1759         struct pmc_owner *po;
1760         const struct pmc_process *pp;
1761
1762         freepath = fullpath = NULL;
1763         MPASS(!in_epoch(global_epoch_preempt));
1764         pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1765
1766         pid = td->td_proc->p_pid;
1767
1768         PMC_EPOCH_ENTER();
1769         /* Inform owners of all system-wide sampling PMCs. */
1770         CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1771             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1772                         pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1773
1774         if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1775                 goto done;
1776
1777         /*
1778          * Inform sampling PMC owners tracking this process.
1779          */
1780         for (ri = 0; ri < md->pmd_npmc; ri++)
1781                 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1782                     PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1783                         pmclog_process_map_in(pm->pm_owner,
1784                             pid, pkm->pm_address, fullpath);
1785
1786   done:
1787         if (freepath)
1788                 free(freepath, M_TEMP);
1789         PMC_EPOCH_EXIT();
1790 }
1791
1792
1793 /*
1794  * Log an munmap request.
1795  */
1796
1797 static void
1798 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1799 {
1800         int ri;
1801         pid_t pid;
1802         struct pmc_owner *po;
1803         const struct pmc *pm;
1804         const struct pmc_process *pp;
1805
1806         pid = td->td_proc->p_pid;
1807
1808         PMC_EPOCH_ENTER();
1809         CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1810             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1811                 pmclog_process_map_out(po, pid, pkm->pm_address,
1812                     pkm->pm_address + pkm->pm_size);
1813         PMC_EPOCH_EXIT();
1814
1815         if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1816                 return;
1817
1818         for (ri = 0; ri < md->pmd_npmc; ri++)
1819                 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1820                     PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1821                         pmclog_process_map_out(pm->pm_owner, pid,
1822                             pkm->pm_address, pkm->pm_address + pkm->pm_size);
1823 }
1824
1825 /*
1826  * Log mapping information about the kernel.
1827  */
1828
1829 static void
1830 pmc_log_kernel_mappings(struct pmc *pm)
1831 {
1832         struct pmc_owner *po;
1833         struct pmckern_map_in *km, *kmbase;
1834
1835         MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx));
1836         KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1837             ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1838                 __LINE__, (void *) pm));
1839
1840         po = pm->pm_owner;
1841
1842         if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1843                 return;
1844         if (PMC_TO_MODE(pm) == PMC_MODE_SS)
1845                 pmc_process_allproc(pm);
1846         /*
1847          * Log the current set of kernel modules.
1848          */
1849         kmbase = linker_hwpmc_list_objects();
1850         for (km = kmbase; km->pm_file != NULL; km++) {
1851                 PMCDBG2(LOG,REG,1,"%s %p", (char *) km->pm_file,
1852                     (void *) km->pm_address);
1853                 pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1854                     km->pm_file);
1855         }
1856         free(kmbase, M_LINKER);
1857
1858         po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1859 }
1860
1861 /*
1862  * Log the mappings for a single process.
1863  */
1864
1865 static void
1866 pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1867 {
1868         vm_map_t map;
1869         struct vnode *vp;
1870         struct vmspace *vm;
1871         vm_map_entry_t entry;
1872         vm_offset_t last_end;
1873         u_int last_timestamp;
1874         struct vnode *last_vp;
1875         vm_offset_t start_addr;
1876         vm_object_t obj, lobj, tobj;
1877         char *fullpath, *freepath;
1878
1879         last_vp = NULL;
1880         last_end = (vm_offset_t) 0;
1881         fullpath = freepath = NULL;
1882
1883         if ((vm = vmspace_acquire_ref(p)) == NULL)
1884                 return;
1885
1886         map = &vm->vm_map;
1887         vm_map_lock_read(map);
1888
1889         VM_MAP_ENTRY_FOREACH(entry, map) {
1890
1891                 if (entry == NULL) {
1892                         PMCDBG2(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly "
1893                             "NULL! pid=%d vm_map=%p\n", p->p_pid, map);
1894                         break;
1895                 }
1896
1897                 /*
1898                  * We only care about executable map entries.
1899                  */
1900                 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) ||
1901                     !(entry->protection & VM_PROT_EXECUTE) ||
1902                     (entry->object.vm_object == NULL)) {
1903                         continue;
1904                 }
1905
1906                 obj = entry->object.vm_object;
1907                 VM_OBJECT_RLOCK(obj);
1908
1909                 /* 
1910                  * Walk the backing_object list to find the base
1911                  * (non-shadowed) vm_object.
1912                  */
1913                 for (lobj = tobj = obj; tobj != NULL; tobj = tobj->backing_object) {
1914                         if (tobj != obj)
1915                                 VM_OBJECT_RLOCK(tobj);
1916                         if (lobj != obj)
1917                                 VM_OBJECT_RUNLOCK(lobj);
1918                         lobj = tobj;
1919                 }
1920
1921                 /*
1922                  * At this point lobj is the base vm_object and it is locked.
1923                  */
1924                 if (lobj == NULL) {
1925                         PMCDBG3(LOG,OPS,2, "hwpmc: lobj unexpectedly NULL! pid=%d "
1926                             "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj);
1927                         VM_OBJECT_RUNLOCK(obj);
1928                         continue;
1929                 }
1930
1931                 vp = vm_object_vnode(lobj);
1932                 if (vp == NULL) {
1933                         if (lobj != obj)
1934                                 VM_OBJECT_RUNLOCK(lobj);
1935                         VM_OBJECT_RUNLOCK(obj);
1936                         continue;
1937                 }
1938
1939                 /*
1940                  * Skip contiguous regions that point to the same
1941                  * vnode, so we don't emit redundant MAP-IN
1942                  * directives.
1943                  */
1944                 if (entry->start == last_end && vp == last_vp) {
1945                         last_end = entry->end;
1946                         if (lobj != obj)
1947                                 VM_OBJECT_RUNLOCK(lobj);
1948                         VM_OBJECT_RUNLOCK(obj);
1949                         continue;
1950                 }
1951
1952                 /* 
1953                  * We don't want to keep the proc's vm_map or this
1954                  * vm_object locked while we walk the pathname, since
1955                  * vn_fullpath() can sleep.  However, if we drop the
1956                  * lock, it's possible for concurrent activity to
1957                  * modify the vm_map list.  To protect against this,
1958                  * we save the vm_map timestamp before we release the
1959                  * lock, and check it after we reacquire the lock
1960                  * below.
1961                  */
1962                 start_addr = entry->start;
1963                 last_end = entry->end;
1964                 last_timestamp = map->timestamp;
1965                 vm_map_unlock_read(map);
1966
1967                 vref(vp);
1968                 if (lobj != obj)
1969                         VM_OBJECT_RUNLOCK(lobj);
1970
1971                 VM_OBJECT_RUNLOCK(obj);
1972
1973                 freepath = NULL;
1974                 pmc_getfilename(vp, &fullpath, &freepath);
1975                 last_vp = vp;
1976
1977                 vrele(vp);
1978
1979                 vp = NULL;
1980                 pmclog_process_map_in(po, p->p_pid, start_addr, fullpath);
1981                 if (freepath)
1982                         free(freepath, M_TEMP);
1983
1984                 vm_map_lock_read(map);
1985
1986                 /*
1987                  * If our saved timestamp doesn't match, this means
1988                  * that the vm_map was modified out from under us and
1989                  * we can't trust our current "entry" pointer.  Do a
1990                  * new lookup for this entry.  If there is no entry
1991                  * for this address range, vm_map_lookup_entry() will
1992                  * return the previous one, so we always want to go to
1993                  * the next entry on the next loop iteration.
1994                  * 
1995                  * There is an edge condition here that can occur if
1996                  * there is no entry at or before this address.  In
1997                  * this situation, vm_map_lookup_entry returns
1998                  * &map->header, which would cause our loop to abort
1999                  * without processing the rest of the map.  However,
2000                  * in practice this will never happen for process
2001                  * vm_map.  This is because the executable's text
2002                  * segment is the first mapping in the proc's address
2003                  * space, and this mapping is never removed until the
2004                  * process exits, so there will always be a non-header
2005                  * entry at or before the requested address for
2006                  * vm_map_lookup_entry to return.
2007                  */
2008                 if (map->timestamp != last_timestamp)
2009                         vm_map_lookup_entry(map, last_end - 1, &entry);
2010         }
2011
2012         vm_map_unlock_read(map);
2013         vmspace_free(vm);
2014         return;
2015 }
2016
2017 /*
2018  * Log mappings for all processes in the system.
2019  */
2020
2021 static void
2022 pmc_log_all_process_mappings(struct pmc_owner *po)
2023 {
2024         struct proc *p, *top;
2025
2026         sx_assert(&pmc_sx, SX_XLOCKED);
2027
2028         if ((p = pfind(1)) == NULL)
2029                 panic("[pmc,%d] Cannot find init", __LINE__);
2030
2031         PROC_UNLOCK(p);
2032
2033         sx_slock(&proctree_lock);
2034
2035         top = p;
2036
2037         for (;;) {
2038                 pmc_log_process_mappings(po, p);
2039                 if (!LIST_EMPTY(&p->p_children))
2040                         p = LIST_FIRST(&p->p_children);
2041                 else for (;;) {
2042                         if (p == top)
2043                                 goto done;
2044                         if (LIST_NEXT(p, p_sibling)) {
2045                                 p = LIST_NEXT(p, p_sibling);
2046                                 break;
2047                         }
2048                         p = p->p_pptr;
2049                 }
2050         }
2051  done:
2052         sx_sunlock(&proctree_lock);
2053 }
2054
2055 /*
2056  * The 'hook' invoked from the kernel proper
2057  */
2058
2059
2060 #ifdef  HWPMC_DEBUG
2061 const char *pmc_hooknames[] = {
2062         /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
2063         "",
2064         "EXEC",
2065         "CSW-IN",
2066         "CSW-OUT",
2067         "SAMPLE",
2068         "UNUSED1",
2069         "UNUSED2",
2070         "MMAP",
2071         "MUNMAP",
2072         "CALLCHAIN-NMI",
2073         "CALLCHAIN-SOFT",
2074         "SOFTSAMPLING",
2075         "THR-CREATE",
2076         "THR-EXIT",
2077         "THR-USERRET",
2078         "THR-CREATE-LOG",
2079         "THR-EXIT-LOG",
2080         "PROC-CREATE-LOG"
2081 };
2082 #endif
2083
2084 static int
2085 pmc_hook_handler(struct thread *td, int function, void *arg)
2086 {
2087         int cpu;
2088
2089         PMCDBG4(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
2090             pmc_hooknames[function], arg);
2091
2092         switch (function)
2093         {
2094
2095         /*
2096          * Process exec()
2097          */
2098
2099         case PMC_FN_PROCESS_EXEC:
2100         {
2101                 char *fullpath, *freepath;
2102                 unsigned int ri;
2103                 int is_using_hwpmcs;
2104                 struct pmc *pm;
2105                 struct proc *p;
2106                 struct pmc_owner *po;
2107                 struct pmc_process *pp;
2108                 struct pmckern_procexec *pk;
2109
2110                 sx_assert(&pmc_sx, SX_XLOCKED);
2111
2112                 p = td->td_proc;
2113                 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
2114
2115                 pk = (struct pmckern_procexec *) arg;
2116
2117                 PMC_EPOCH_ENTER();
2118                 /* Inform owners of SS mode PMCs of the exec event. */
2119                 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
2120                     if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2121                             pmclog_process_procexec(po, PMC_ID_INVALID,
2122                                 p->p_pid, pk->pm_entryaddr, fullpath);
2123                 PMC_EPOCH_EXIT();
2124
2125                 PROC_LOCK(p);
2126                 is_using_hwpmcs = p->p_flag & P_HWPMC;
2127                 PROC_UNLOCK(p);
2128
2129                 if (!is_using_hwpmcs) {
2130                         if (freepath)
2131                                 free(freepath, M_TEMP);
2132                         break;
2133                 }
2134
2135                 /*
2136                  * PMCs are not inherited across an exec():  remove any
2137                  * PMCs that this process is the owner of.
2138                  */
2139
2140                 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
2141                         pmc_remove_owner(po);
2142                         pmc_destroy_owner_descriptor(po);
2143                 }
2144
2145                 /*
2146                  * If the process being exec'ed is not the target of any
2147                  * PMC, we are done.
2148                  */
2149                 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
2150                         if (freepath)
2151                                 free(freepath, M_TEMP);
2152                         break;
2153                 }
2154
2155                 /*
2156                  * Log the exec event to all monitoring owners.  Skip
2157                  * owners who have already received the event because
2158                  * they had system sampling PMCs active.
2159                  */
2160                 for (ri = 0; ri < md->pmd_npmc; ri++)
2161                         if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
2162                                 po = pm->pm_owner;
2163                                 if (po->po_sscount == 0 &&
2164                                     po->po_flags & PMC_PO_OWNS_LOGFILE)
2165                                         pmclog_process_procexec(po, pm->pm_id,
2166                                             p->p_pid, pk->pm_entryaddr,
2167                                             fullpath);
2168                         }
2169
2170                 if (freepath)
2171                         free(freepath, M_TEMP);
2172
2173
2174                 PMCDBG4(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
2175                     p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
2176
2177                 if (pk->pm_credentialschanged == 0) /* no change */
2178                         break;
2179
2180                 /*
2181                  * If the newly exec()'ed process has a different credential
2182                  * than before, allow it to be the target of a PMC only if
2183                  * the PMC's owner has sufficient privilege.
2184                  */
2185
2186                 for (ri = 0; ri < md->pmd_npmc; ri++)
2187                         if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
2188                                 if (pmc_can_attach(pm, td->td_proc) != 0)
2189                                         pmc_detach_one_process(td->td_proc,
2190                                             pm, PMC_FLAG_NONE);
2191
2192                 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
2193                     ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
2194                         pp->pp_refcnt, pp));
2195
2196                 /*
2197                  * If this process is no longer the target of any
2198                  * PMCs, we can remove the process entry and free
2199                  * up space.
2200                  */
2201
2202                 if (pp->pp_refcnt == 0) {
2203                         pmc_remove_process_descriptor(pp);
2204                         pmc_destroy_process_descriptor(pp);
2205                         break;
2206                 }
2207
2208         }
2209         break;
2210
2211         case PMC_FN_CSW_IN:
2212                 pmc_process_csw_in(td);
2213                 break;
2214
2215         case PMC_FN_CSW_OUT:
2216                 pmc_process_csw_out(td);
2217                 break;
2218
2219         /*
2220          * Process accumulated PC samples.
2221          *
2222          * This function is expected to be called by hardclock() for
2223          * each CPU that has accumulated PC samples.
2224          *
2225          * This function is to be executed on the CPU whose samples
2226          * are being processed.
2227          */
2228         case PMC_FN_DO_SAMPLES:
2229
2230                 /*
2231                  * Clear the cpu specific bit in the CPU mask before
2232                  * do the rest of the processing.  If the NMI handler
2233                  * gets invoked after the "atomic_clear_int()" call
2234                  * below but before "pmc_process_samples()" gets
2235                  * around to processing the interrupt, then we will
2236                  * come back here at the next hardclock() tick (and
2237                  * may find nothing to do if "pmc_process_samples()"
2238                  * had already processed the interrupt).  We don't
2239                  * lose the interrupt sample.
2240                  */
2241                 DPCPU_SET(pmc_sampled, 0);
2242                 cpu = PCPU_GET(cpuid);
2243                 pmc_process_samples(cpu, PMC_HR);
2244                 pmc_process_samples(cpu, PMC_SR);
2245                 pmc_process_samples(cpu, PMC_UR);
2246                 break;
2247
2248         case PMC_FN_MMAP:
2249                 pmc_process_mmap(td, (struct pmckern_map_in *) arg);
2250                 break;
2251
2252         case PMC_FN_MUNMAP:
2253                 MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx));
2254                 pmc_process_munmap(td, (struct pmckern_map_out *) arg);
2255                 break;
2256
2257         case PMC_FN_PROC_CREATE_LOG:
2258                 pmc_process_proccreate((struct proc *)arg);
2259                 break;
2260
2261         case PMC_FN_USER_CALLCHAIN:
2262                 /*
2263                  * Record a call chain.
2264                  */
2265                 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2266                     __LINE__));
2267
2268                 pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
2269                     (struct trapframe *) arg);
2270
2271                 KASSERT(td->td_pinned == 1,
2272                         ("[pmc,%d] invalid td_pinned value", __LINE__));
2273                 sched_unpin();  /* Can migrate safely now. */
2274
2275                 td->td_pflags &= ~TDP_CALLCHAIN;
2276                 break;
2277
2278         case PMC_FN_USER_CALLCHAIN_SOFT:
2279                 /*
2280                  * Record a call chain.
2281                  */
2282                 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2283                     __LINE__));
2284
2285                 cpu = PCPU_GET(cpuid);
2286                 pmc_capture_user_callchain(cpu, PMC_SR,
2287                     (struct trapframe *) arg);
2288
2289                 KASSERT(td->td_pinned == 1,
2290                     ("[pmc,%d] invalid td_pinned value", __LINE__));
2291
2292                 sched_unpin();  /* Can migrate safely now. */
2293
2294                 td->td_pflags &= ~TDP_CALLCHAIN;
2295                 break;
2296
2297         case PMC_FN_SOFT_SAMPLING:
2298                 /*
2299                  * Call soft PMC sampling intr.
2300                  */
2301                 pmc_soft_intr((struct pmckern_soft *) arg);
2302                 break;
2303
2304         case PMC_FN_THR_CREATE:
2305                 pmc_process_thread_add(td);
2306                 pmc_process_threadcreate(td);
2307                 break;
2308
2309         case PMC_FN_THR_CREATE_LOG:
2310                 pmc_process_threadcreate(td);
2311                 break;
2312
2313         case PMC_FN_THR_EXIT:
2314                 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2315                     __LINE__));
2316                 pmc_process_thread_delete(td);
2317                 pmc_process_threadexit(td);
2318                 break;
2319         case PMC_FN_THR_EXIT_LOG:
2320                 pmc_process_threadexit(td);
2321                 break;
2322         case PMC_FN_THR_USERRET:
2323                 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2324                     __LINE__));
2325                 pmc_process_thread_userret(td);
2326                 break;
2327
2328         default:
2329 #ifdef  HWPMC_DEBUG
2330                 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
2331 #endif
2332                 break;
2333
2334         }
2335
2336         return 0;
2337 }
2338
2339 /*
2340  * allocate a 'struct pmc_owner' descriptor in the owner hash table.
2341  */
2342
2343 static struct pmc_owner *
2344 pmc_allocate_owner_descriptor(struct proc *p)
2345 {
2346         uint32_t hindex;
2347         struct pmc_owner *po;
2348         struct pmc_ownerhash *poh;
2349
2350         hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2351         poh = &pmc_ownerhash[hindex];
2352
2353         /* allocate space for N pointers and one descriptor struct */
2354         po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK|M_ZERO);
2355         po->po_owner = p;
2356         LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
2357
2358         TAILQ_INIT(&po->po_logbuffers);
2359         mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
2360
2361         PMCDBG4(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
2362             p, p->p_pid, p->p_comm, po);
2363
2364         return po;
2365 }
2366
2367 static void
2368 pmc_destroy_owner_descriptor(struct pmc_owner *po)
2369 {
2370
2371         PMCDBG4(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
2372             po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
2373
2374         mtx_destroy(&po->po_mtx);
2375         free(po, M_PMC);
2376 }
2377
2378 /*
2379  * Allocate a thread descriptor from the free pool.
2380  *
2381  * NOTE: This *can* return NULL.
2382  */
2383 static struct pmc_thread *
2384 pmc_thread_descriptor_pool_alloc(void)
2385 {
2386         struct pmc_thread *pt;
2387
2388         mtx_lock_spin(&pmc_threadfreelist_mtx);
2389         if ((pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
2390                 LIST_REMOVE(pt, pt_next);
2391                 pmc_threadfreelist_entries--;
2392         }
2393         mtx_unlock_spin(&pmc_threadfreelist_mtx);
2394
2395         return (pt);
2396 }
2397
2398 /*
2399  * Add a thread descriptor to the free pool. We use this instead of free()
2400  * to maintain a cache of free entries. Additionally, we can safely call
2401  * this function when we cannot call free(), such as in a critical section.
2402  * 
2403  */
2404 static void
2405 pmc_thread_descriptor_pool_free(struct pmc_thread *pt)
2406 {
2407
2408         if (pt == NULL)
2409                 return;
2410
2411         memset(pt, 0, THREADENTRY_SIZE);
2412         mtx_lock_spin(&pmc_threadfreelist_mtx);
2413         LIST_INSERT_HEAD(&pmc_threadfreelist, pt, pt_next);
2414         pmc_threadfreelist_entries++;
2415         if (pmc_threadfreelist_entries > pmc_threadfreelist_max)
2416                 GROUPTASK_ENQUEUE(&free_gtask);
2417         mtx_unlock_spin(&pmc_threadfreelist_mtx);
2418 }
2419
2420 /*
2421  * A callout to manage the free list.
2422  */
2423 static void
2424 pmc_thread_descriptor_pool_free_task(void *arg __unused)
2425 {
2426         struct pmc_thread *pt;
2427         LIST_HEAD(, pmc_thread) tmplist;
2428         int delta;
2429
2430         LIST_INIT(&tmplist);
2431         /* Determine what changes, if any, we need to make. */
2432         mtx_lock_spin(&pmc_threadfreelist_mtx);
2433         delta = pmc_threadfreelist_entries - pmc_threadfreelist_max;
2434         while (delta > 0 &&
2435                    (pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
2436                 delta--;
2437                 LIST_REMOVE(pt, pt_next);
2438                 LIST_INSERT_HEAD(&tmplist, pt, pt_next);
2439         }
2440         mtx_unlock_spin(&pmc_threadfreelist_mtx);
2441
2442         /* If there are entries to free, free them. */
2443         while (!LIST_EMPTY(&tmplist)) {
2444                 pt = LIST_FIRST(&tmplist);
2445                 LIST_REMOVE(pt, pt_next);
2446                 free(pt, M_PMC);
2447         }
2448 }
2449
2450 /*
2451  * Drain the thread free pool, freeing all allocations.
2452  */
2453 static void
2454 pmc_thread_descriptor_pool_drain()
2455 {
2456         struct pmc_thread *pt, *next;
2457
2458         LIST_FOREACH_SAFE(pt, &pmc_threadfreelist, pt_next, next) {
2459                 LIST_REMOVE(pt, pt_next);
2460                 free(pt, M_PMC);
2461         }
2462 }
2463
2464 /*
2465  * find the descriptor corresponding to thread 'td', adding or removing it
2466  * as specified by 'mode'.
2467  *
2468  * Note that this supports additional mode flags in addition to those
2469  * supported by pmc_find_process_descriptor():
2470  * PMC_FLAG_NOWAIT: Causes the function to not wait for mallocs.
2471  *     This makes it safe to call while holding certain other locks.
2472  */
2473
2474 static struct pmc_thread *
2475 pmc_find_thread_descriptor(struct pmc_process *pp, struct thread *td,
2476     uint32_t mode)
2477 {
2478         struct pmc_thread *pt = NULL, *ptnew = NULL;
2479         int wait_flag;
2480
2481         KASSERT(td != NULL, ("[pmc,%d] called to add NULL td", __LINE__));
2482
2483         /*
2484          * Pre-allocate memory in the PMC_FLAG_ALLOCATE case prior to
2485          * acquiring the lock.
2486          */
2487         if (mode & PMC_FLAG_ALLOCATE) {
2488                 if ((ptnew = pmc_thread_descriptor_pool_alloc()) == NULL) {
2489                         wait_flag = M_WAITOK;
2490                         if ((mode & PMC_FLAG_NOWAIT) || in_epoch(global_epoch_preempt))
2491                                 wait_flag = M_NOWAIT;
2492
2493                         ptnew = malloc(THREADENTRY_SIZE, M_PMC,
2494                             wait_flag|M_ZERO);
2495                 }
2496         }
2497
2498         mtx_lock_spin(pp->pp_tdslock);
2499
2500         LIST_FOREACH(pt, &pp->pp_tds, pt_next)
2501                 if (pt->pt_td == td)
2502                         break;
2503
2504         if ((mode & PMC_FLAG_REMOVE) && pt != NULL)
2505                 LIST_REMOVE(pt, pt_next);
2506
2507         if ((mode & PMC_FLAG_ALLOCATE) && pt == NULL && ptnew != NULL) {
2508                 pt = ptnew;
2509                 ptnew = NULL;
2510                 pt->pt_td = td;
2511                 LIST_INSERT_HEAD(&pp->pp_tds, pt, pt_next);
2512         }
2513
2514         mtx_unlock_spin(pp->pp_tdslock);
2515
2516         if (ptnew != NULL) {
2517                 free(ptnew, M_PMC);
2518         }
2519
2520         return pt;
2521 }
2522
2523 /*
2524  * Try to add thread descriptors for each thread in a process.
2525  */
2526
2527 static void
2528 pmc_add_thread_descriptors_from_proc(struct proc *p, struct pmc_process *pp)
2529 {
2530         struct thread *curtd;
2531         struct pmc_thread **tdlist;
2532         int i, tdcnt, tdlistsz;
2533
2534         KASSERT(!PROC_LOCKED(p), ("[pmc,%d] proc unexpectedly locked",
2535             __LINE__));
2536         tdcnt = 32;
2537  restart:
2538         tdlistsz = roundup2(tdcnt, 32);
2539
2540         tdcnt = 0;
2541         tdlist = malloc(sizeof(struct pmc_thread*) * tdlistsz, M_TEMP, M_WAITOK);
2542
2543         PROC_LOCK(p);
2544         FOREACH_THREAD_IN_PROC(p, curtd)
2545                 tdcnt++;
2546         if (tdcnt >= tdlistsz) {
2547                 PROC_UNLOCK(p);
2548                 free(tdlist, M_TEMP);
2549                 goto restart;
2550         }
2551         /*
2552          * Try to add each thread to the list without sleeping. If unable,
2553          * add to a queue to retry after dropping the process lock.
2554          */
2555         tdcnt = 0;
2556         FOREACH_THREAD_IN_PROC(p, curtd) {
2557                 tdlist[tdcnt] = pmc_find_thread_descriptor(pp, curtd,
2558                                                    PMC_FLAG_ALLOCATE|PMC_FLAG_NOWAIT);
2559                 if (tdlist[tdcnt] == NULL) {
2560                         PROC_UNLOCK(p);
2561                         for (i = 0; i <= tdcnt; i++)
2562                                 pmc_thread_descriptor_pool_free(tdlist[i]);
2563                         free(tdlist, M_TEMP);
2564                         goto restart;
2565                 }
2566                 tdcnt++;
2567         }
2568         PROC_UNLOCK(p);
2569         free(tdlist, M_TEMP);
2570 }
2571
2572 /*
2573  * find the descriptor corresponding to process 'p', adding or removing it
2574  * as specified by 'mode'.
2575  */
2576
2577 static struct pmc_process *
2578 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
2579 {
2580         uint32_t hindex;
2581         struct pmc_process *pp, *ppnew;
2582         struct pmc_processhash *pph;
2583
2584         hindex = PMC_HASH_PTR(p, pmc_processhashmask);
2585         pph = &pmc_processhash[hindex];
2586
2587         ppnew = NULL;
2588
2589         /*
2590          * Pre-allocate memory in the PMC_FLAG_ALLOCATE case since we
2591          * cannot call malloc(9) once we hold a spin lock.
2592          */
2593         if (mode & PMC_FLAG_ALLOCATE)
2594                 ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
2595                     sizeof(struct pmc_targetstate), M_PMC, M_WAITOK|M_ZERO);
2596
2597         mtx_lock_spin(&pmc_processhash_mtx);
2598         LIST_FOREACH(pp, pph, pp_next)
2599             if (pp->pp_proc == p)
2600                     break;
2601
2602         if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
2603                 LIST_REMOVE(pp, pp_next);
2604
2605         if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
2606             ppnew != NULL) {
2607                 ppnew->pp_proc = p;
2608                 LIST_INIT(&ppnew->pp_tds);
2609                 ppnew->pp_tdslock = mtx_pool_find(pmc_mtxpool, ppnew);
2610                 LIST_INSERT_HEAD(pph, ppnew, pp_next);
2611                 mtx_unlock_spin(&pmc_processhash_mtx);
2612                 pp = ppnew;
2613                 ppnew = NULL;
2614
2615                 /* Add thread descriptors for this process' current threads. */
2616                 pmc_add_thread_descriptors_from_proc(p, pp);
2617         }
2618         else
2619                 mtx_unlock_spin(&pmc_processhash_mtx);
2620
2621         if (ppnew != NULL)
2622                 free(ppnew, M_PMC);
2623
2624         return pp;
2625 }
2626
2627 /*
2628  * remove a process descriptor from the process hash table.
2629  */
2630
2631 static void
2632 pmc_remove_process_descriptor(struct pmc_process *pp)
2633 {
2634         KASSERT(pp->pp_refcnt == 0,
2635             ("[pmc,%d] Removing process descriptor %p with count %d",
2636                 __LINE__, pp, pp->pp_refcnt));
2637
2638         mtx_lock_spin(&pmc_processhash_mtx);
2639         LIST_REMOVE(pp, pp_next);
2640         mtx_unlock_spin(&pmc_processhash_mtx);
2641 }
2642
2643 /*
2644  * destroy a process descriptor.
2645  */
2646
2647 static void
2648 pmc_destroy_process_descriptor(struct pmc_process *pp)
2649 {
2650         struct pmc_thread *pmc_td;
2651
2652         while ((pmc_td = LIST_FIRST(&pp->pp_tds)) != NULL) {
2653                 LIST_REMOVE(pmc_td, pt_next);
2654                 pmc_thread_descriptor_pool_free(pmc_td);
2655         }
2656         free(pp, M_PMC);
2657 }
2658
2659
2660 /*
2661  * find an owner descriptor corresponding to proc 'p'
2662  */
2663
2664 static struct pmc_owner *
2665 pmc_find_owner_descriptor(struct proc *p)
2666 {
2667         uint32_t hindex;
2668         struct pmc_owner *po;
2669         struct pmc_ownerhash *poh;
2670
2671         hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2672         poh = &pmc_ownerhash[hindex];
2673
2674         po = NULL;
2675         LIST_FOREACH(po, poh, po_next)
2676             if (po->po_owner == p)
2677                     break;
2678
2679         PMCDBG5(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2680             "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2681
2682         return po;
2683 }
2684
2685 /*
2686  * pmc_allocate_pmc_descriptor
2687  *
2688  * Allocate a pmc descriptor and initialize its
2689  * fields.
2690  */
2691
2692 static struct pmc *
2693 pmc_allocate_pmc_descriptor(void)
2694 {
2695         struct pmc *pmc;
2696
2697         pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK|M_ZERO);
2698         pmc->pm_runcount = counter_u64_alloc(M_WAITOK);
2699         pmc->pm_pcpu_state = malloc(sizeof(struct pmc_pcpu_state)*mp_ncpus, M_PMC, M_WAITOK|M_ZERO);
2700         PMCDBG1(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2701
2702         return pmc;
2703 }
2704
2705 /*
2706  * Destroy a pmc descriptor.
2707  */
2708
2709 static void
2710 pmc_destroy_pmc_descriptor(struct pmc *pm)
2711 {
2712
2713         KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2714             pm->pm_state == PMC_STATE_FREE,
2715             ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2716         KASSERT(LIST_EMPTY(&pm->pm_targets),
2717             ("[pmc,%d] destroying pmc with targets", __LINE__));
2718         KASSERT(pm->pm_owner == NULL,
2719             ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2720         KASSERT(counter_u64_fetch(pm->pm_runcount) == 0,
2721             ("[pmc,%d] pmc has non-zero run count %ld", __LINE__,
2722                  (unsigned long)counter_u64_fetch(pm->pm_runcount)));
2723
2724         counter_u64_free(pm->pm_runcount);
2725         free(pm->pm_pcpu_state, M_PMC);
2726         free(pm, M_PMC);
2727 }
2728
2729 static void
2730 pmc_wait_for_pmc_idle(struct pmc *pm)
2731 {
2732 #ifdef INVARIANTS
2733         volatile int maxloop;
2734
2735         maxloop = 100 * pmc_cpu_max();
2736 #endif
2737         /*
2738          * Loop (with a forced context switch) till the PMC's runcount
2739          * comes down to zero.
2740          */
2741         pmclog_flush(pm->pm_owner, 1);
2742         while (counter_u64_fetch(pm->pm_runcount) > 0) {
2743                 pmclog_flush(pm->pm_owner, 1);
2744 #ifdef INVARIANTS
2745                 maxloop--;
2746                 KASSERT(maxloop > 0,
2747                     ("[pmc,%d] (ri%d, rc%ld) waiting too long for "
2748                         "pmc to be free", __LINE__,
2749                          PMC_TO_ROWINDEX(pm), (unsigned long)counter_u64_fetch(pm->pm_runcount)));
2750 #endif
2751                 pmc_force_context_switch();
2752         }
2753 }
2754
2755 /*
2756  * This function does the following things:
2757  *
2758  *  - detaches the PMC from hardware
2759  *  - unlinks all target threads that were attached to it
2760  *  - removes the PMC from its owner's list
2761  *  - destroys the PMC private mutex
2762  *
2763  * Once this function completes, the given pmc pointer can be freed by
2764  * calling pmc_destroy_pmc_descriptor().
2765  */
2766
2767 static void
2768 pmc_release_pmc_descriptor(struct pmc *pm)
2769 {
2770         enum pmc_mode mode;
2771         struct pmc_hw *phw;
2772         u_int adjri, ri, cpu;
2773         struct pmc_owner *po;
2774         struct pmc_binding pb;
2775         struct pmc_process *pp;
2776         struct pmc_classdep *pcd;
2777         struct pmc_target *ptgt, *tmp;
2778
2779         sx_assert(&pmc_sx, SX_XLOCKED);
2780
2781         KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2782
2783         ri   = PMC_TO_ROWINDEX(pm);
2784         pcd  = pmc_ri_to_classdep(md, ri, &adjri);
2785         mode = PMC_TO_MODE(pm);
2786
2787         PMCDBG3(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2788             mode);
2789
2790         /*
2791          * First, we take the PMC off hardware.
2792          */
2793         cpu = 0;
2794         if (PMC_IS_SYSTEM_MODE(mode)) {
2795
2796                 /*
2797                  * A system mode PMC runs on a specific CPU.  Switch
2798                  * to this CPU and turn hardware off.
2799                  */
2800                 pmc_save_cpu_binding(&pb);
2801
2802                 cpu = PMC_TO_CPU(pm);
2803
2804                 pmc_select_cpu(cpu);
2805
2806                 /* switch off non-stalled CPUs */
2807                 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
2808                 if (pm->pm_state == PMC_STATE_RUNNING &&
2809                         pm->pm_pcpu_state[cpu].pps_stalled == 0) {
2810
2811                         phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2812
2813                         KASSERT(phw->phw_pmc == pm,
2814                             ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2815                                 __LINE__, ri, phw->phw_pmc, pm));
2816                         PMCDBG2(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2817
2818                         critical_enter();
2819                         pcd->pcd_stop_pmc(cpu, adjri);
2820                         critical_exit();
2821                 }
2822
2823                 PMCDBG2(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2824
2825                 critical_enter();
2826                 pcd->pcd_config_pmc(cpu, adjri, NULL);
2827                 critical_exit();
2828
2829                 /* adjust the global and process count of SS mode PMCs */
2830                 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2831                         po = pm->pm_owner;
2832                         po->po_sscount--;
2833                         if (po->po_sscount == 0) {
2834                                 atomic_subtract_rel_int(&pmc_ss_count, 1);
2835                                 CK_LIST_REMOVE(po, po_ssnext);
2836                                 epoch_wait_preempt(global_epoch_preempt);
2837                         }
2838                 }
2839
2840                 pm->pm_state = PMC_STATE_DELETED;
2841
2842                 pmc_restore_cpu_binding(&pb);
2843
2844                 /*
2845                  * We could have references to this PMC structure in
2846                  * the per-cpu sample queues.  Wait for the queue to
2847                  * drain.
2848                  */
2849                 pmc_wait_for_pmc_idle(pm);
2850
2851         } else if (PMC_IS_VIRTUAL_MODE(mode)) {
2852
2853                 /*
2854                  * A virtual PMC could be running on multiple CPUs at
2855                  * a given instant.
2856                  *
2857                  * By marking its state as DELETED, we ensure that
2858                  * this PMC is never further scheduled on hardware.
2859                  *
2860                  * Then we wait till all CPUs are done with this PMC.
2861                  */
2862                 pm->pm_state = PMC_STATE_DELETED;
2863
2864
2865                 /* Wait for the PMCs runcount to come to zero. */
2866                 pmc_wait_for_pmc_idle(pm);
2867
2868                 /*
2869                  * At this point the PMC is off all CPUs and cannot be
2870                  * freshly scheduled onto a CPU.  It is now safe to
2871                  * unlink all targets from this PMC.  If a
2872                  * process-record's refcount falls to zero, we remove
2873                  * it from the hash table.  The module-wide SX lock
2874                  * protects us from races.
2875                  */
2876                 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2877                         pp = ptgt->pt_process;
2878                         pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2879
2880                         PMCDBG1(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2881
2882                         /*
2883                          * If the target process record shows that no
2884                          * PMCs are attached to it, reclaim its space.
2885                          */
2886
2887                         if (pp->pp_refcnt == 0) {
2888                                 pmc_remove_process_descriptor(pp);
2889                                 pmc_destroy_process_descriptor(pp);
2890                         }
2891                 }
2892
2893                 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2894
2895         }
2896
2897         /*
2898          * Release any MD resources
2899          */
2900         (void) pcd->pcd_release_pmc(cpu, adjri, pm);
2901
2902         /*
2903          * Update row disposition
2904          */
2905
2906         if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2907                 PMC_UNMARK_ROW_STANDALONE(ri);
2908         else
2909                 PMC_UNMARK_ROW_THREAD(ri);
2910
2911         /* unlink from the owner's list */
2912         if (pm->pm_owner) {
2913                 LIST_REMOVE(pm, pm_next);
2914                 pm->pm_owner = NULL;
2915         }
2916 }
2917
2918 /*
2919  * Register an owner and a pmc.
2920  */
2921
2922 static int
2923 pmc_register_owner(struct proc *p, struct pmc *pmc)
2924 {
2925         struct pmc_owner *po;
2926
2927         sx_assert(&pmc_sx, SX_XLOCKED);
2928
2929         if ((po = pmc_find_owner_descriptor(p)) == NULL)
2930                 if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2931                         return ENOMEM;
2932
2933         KASSERT(pmc->pm_owner == NULL,
2934             ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2935         pmc->pm_owner  = po;
2936
2937         LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2938
2939         PROC_LOCK(p);
2940         p->p_flag |= P_HWPMC;
2941         PROC_UNLOCK(p);
2942
2943         if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2944                 pmclog_process_pmcallocate(pmc);
2945
2946         PMCDBG2(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2947             po, pmc);
2948
2949         return 0;
2950 }
2951
2952 /*
2953  * Return the current row disposition:
2954  * == 0 => FREE
2955  *  > 0 => PROCESS MODE
2956  *  < 0 => SYSTEM MODE
2957  */
2958
2959 int
2960 pmc_getrowdisp(int ri)
2961 {
2962         return pmc_pmcdisp[ri];
2963 }
2964
2965 /*
2966  * Check if a PMC at row index 'ri' can be allocated to the current
2967  * process.
2968  *
2969  * Allocation can fail if:
2970  *   - the current process is already being profiled by a PMC at index 'ri',
2971  *     attached to it via OP_PMCATTACH.
2972  *   - the current process has already allocated a PMC at index 'ri'
2973  *     via OP_ALLOCATE.
2974  */
2975
2976 static int
2977 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2978 {
2979         enum pmc_mode mode;
2980         struct pmc *pm;
2981         struct pmc_owner *po;
2982         struct pmc_process *pp;
2983
2984         PMCDBG5(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2985             "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2986
2987         /*
2988          * We shouldn't have already allocated a process-mode PMC at
2989          * row index 'ri'.
2990          *
2991          * We shouldn't have allocated a system-wide PMC on the same
2992          * CPU and same RI.
2993          */
2994         if ((po = pmc_find_owner_descriptor(p)) != NULL)
2995                 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2996                     if (PMC_TO_ROWINDEX(pm) == ri) {
2997                             mode = PMC_TO_MODE(pm);
2998                             if (PMC_IS_VIRTUAL_MODE(mode))
2999                                     return EEXIST;
3000                             if (PMC_IS_SYSTEM_MODE(mode) &&
3001                                 (int) PMC_TO_CPU(pm) == cpu)
3002                                     return EEXIST;
3003                     }
3004                 }
3005
3006         /*
3007          * We also shouldn't be the target of any PMC at this index
3008          * since otherwise a PMC_ATTACH to ourselves will fail.
3009          */
3010         if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
3011                 if (pp->pp_pmcs[ri].pp_pmc)
3012                         return EEXIST;
3013
3014         PMCDBG4(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
3015             p, p->p_pid, p->p_comm, ri);
3016
3017         return 0;
3018 }
3019
3020 /*
3021  * Check if a given PMC at row index 'ri' can be currently used in
3022  * mode 'mode'.
3023  */
3024
3025 static int
3026 pmc_can_allocate_row(int ri, enum pmc_mode mode)
3027 {
3028         enum pmc_disp   disp;
3029
3030         sx_assert(&pmc_sx, SX_XLOCKED);
3031
3032         PMCDBG2(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
3033
3034         if (PMC_IS_SYSTEM_MODE(mode))
3035                 disp = PMC_DISP_STANDALONE;
3036         else
3037                 disp = PMC_DISP_THREAD;
3038
3039         /*
3040          * check disposition for PMC row 'ri':
3041          *
3042          * Expected disposition         Row-disposition         Result
3043          *
3044          * STANDALONE                   STANDALONE or FREE      proceed
3045          * STANDALONE                   THREAD                  fail
3046          * THREAD                       THREAD or FREE          proceed
3047          * THREAD                       STANDALONE              fail
3048          */
3049
3050         if (!PMC_ROW_DISP_IS_FREE(ri) &&
3051             !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
3052             !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
3053                 return EBUSY;
3054
3055         /*
3056          * All OK
3057          */
3058
3059         PMCDBG2(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
3060
3061         return 0;
3062
3063 }
3064
3065 /*
3066  * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
3067  */
3068
3069 static struct pmc *
3070 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
3071 {
3072         struct pmc *pm;
3073
3074         KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
3075             ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
3076                 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
3077
3078         LIST_FOREACH(pm, &po->po_pmcs, pm_next)
3079             if (pm->pm_id == pmcid)
3080                     return pm;
3081
3082         return NULL;
3083 }
3084
3085 static int
3086 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
3087 {
3088
3089         struct pmc *pm, *opm;
3090         struct pmc_owner *po;
3091         struct pmc_process *pp;
3092
3093         PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid);
3094         if (PMC_ID_TO_ROWINDEX(pmcid) >= md->pmd_npmc)
3095                 return (EINVAL);
3096
3097         if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL) {
3098                 /*
3099                  * In case of PMC_F_DESCENDANTS child processes we will not find
3100                  * the current process in the owners hash list.  Find the owner
3101                  * process first and from there lookup the po.
3102                  */
3103                 if ((pp = pmc_find_process_descriptor(curthread->td_proc,
3104                     PMC_FLAG_NONE)) == NULL) {
3105                         return ESRCH;
3106                 } else {
3107                         opm = pp->pp_pmcs[PMC_ID_TO_ROWINDEX(pmcid)].pp_pmc;
3108                         if (opm == NULL)
3109                                 return ESRCH;
3110                         if ((opm->pm_flags & (PMC_F_ATTACHED_TO_OWNER|
3111                             PMC_F_DESCENDANTS)) != (PMC_F_ATTACHED_TO_OWNER|
3112                             PMC_F_DESCENDANTS))
3113                                 return ESRCH;
3114                         po = opm->pm_owner;
3115                 }
3116         }
3117
3118         if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
3119                 return EINVAL;
3120
3121         PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
3122
3123         *pmc = pm;
3124         return 0;
3125 }
3126
3127 /*
3128  * Start a PMC.
3129  */
3130
3131 static int
3132 pmc_start(struct pmc *pm)
3133 {
3134         enum pmc_mode mode;
3135         struct pmc_owner *po;
3136         struct pmc_binding pb;
3137         struct pmc_classdep *pcd;
3138         int adjri, error, cpu, ri;
3139
3140         KASSERT(pm != NULL,
3141             ("[pmc,%d] null pm", __LINE__));
3142
3143         mode = PMC_TO_MODE(pm);
3144         ri   = PMC_TO_ROWINDEX(pm);
3145         pcd  = pmc_ri_to_classdep(md, ri, &adjri);
3146
3147         error = 0;
3148
3149         PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
3150
3151         po = pm->pm_owner;
3152
3153         /*
3154          * Disallow PMCSTART if a logfile is required but has not been
3155          * configured yet.
3156          */
3157         if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
3158             (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
3159                 return (EDOOFUS);       /* programming error */
3160
3161         /*
3162          * If this is a sampling mode PMC, log mapping information for
3163          * the kernel modules that are currently loaded.
3164          */
3165         if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3166             pmc_log_kernel_mappings(pm);
3167
3168         if (PMC_IS_VIRTUAL_MODE(mode)) {
3169
3170                 /*
3171                  * If a PMCATTACH has never been done on this PMC,
3172                  * attach it to its owner process.
3173                  */
3174
3175                 if (LIST_EMPTY(&pm->pm_targets))
3176                         error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
3177                             pmc_attach_process(po->po_owner, pm);
3178
3179                 /*
3180                  * If the PMC is attached to its owner, then force a context
3181                  * switch to ensure that the MD state gets set correctly.
3182                  */
3183
3184                 if (error == 0) {
3185                         pm->pm_state = PMC_STATE_RUNNING;
3186                         if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
3187                                 pmc_force_context_switch();
3188                 }
3189
3190                 return (error);
3191         }
3192
3193
3194         /*
3195          * A system-wide PMC.
3196          *
3197          * Add the owner to the global list if this is a system-wide
3198          * sampling PMC.
3199          */
3200
3201         if (mode == PMC_MODE_SS) {
3202                 /*
3203                  * Log mapping information for all existing processes in the
3204                  * system.  Subsequent mappings are logged as they happen;
3205                  * see pmc_process_mmap().
3206                  */
3207                 if (po->po_logprocmaps == 0) {
3208                         pmc_log_all_process_mappings(po);
3209                         po->po_logprocmaps = 1;
3210                 }
3211                 po->po_sscount++;
3212                 if (po->po_sscount == 1) {
3213                         atomic_add_rel_int(&pmc_ss_count, 1);
3214                         CK_LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
3215                         PMCDBG1(PMC,OPS,1, "po=%p in global list", po);
3216                 }
3217         }
3218
3219         /*
3220          * Move to the CPU associated with this
3221          * PMC, and start the hardware.
3222          */
3223
3224         pmc_save_cpu_binding(&pb);
3225
3226         cpu = PMC_TO_CPU(pm);
3227
3228         if (!pmc_cpu_is_active(cpu))
3229                 return (ENXIO);
3230
3231         pmc_select_cpu(cpu);
3232
3233         /*
3234          * global PMCs are configured at allocation time
3235          * so write out the initial value and start the PMC.
3236          */
3237
3238         pm->pm_state = PMC_STATE_RUNNING;
3239
3240         critical_enter();
3241         if ((error = pcd->pcd_write_pmc(cpu, adjri,
3242                  PMC_IS_SAMPLING_MODE(mode) ?
3243                  pm->pm_sc.pm_reloadcount :
3244                  pm->pm_sc.pm_initial)) == 0) {
3245                 /* If a sampling mode PMC, reset stalled state. */
3246                 if (PMC_IS_SAMPLING_MODE(mode))
3247                         pm->pm_pcpu_state[cpu].pps_stalled = 0;
3248
3249                 /* Indicate that we desire this to run. Start it. */
3250                 pm->pm_pcpu_state[cpu].pps_cpustate = 1;
3251                 error = pcd->pcd_start_pmc(cpu, adjri);
3252         }
3253         critical_exit();
3254
3255         pmc_restore_cpu_binding(&pb);
3256
3257         return (error);
3258 }
3259
3260 /*
3261  * Stop a PMC.
3262  */
3263
3264 static int
3265 pmc_stop(struct pmc *pm)
3266 {
3267         struct pmc_owner *po;
3268         struct pmc_binding pb;
3269         struct pmc_classdep *pcd;
3270         int adjri, cpu, error, ri;
3271
3272         KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
3273
3274         PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
3275             PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
3276
3277         pm->pm_state = PMC_STATE_STOPPED;
3278
3279         /*
3280          * If the PMC is a virtual mode one, changing the state to
3281          * non-RUNNING is enough to ensure that the PMC never gets
3282          * scheduled.
3283          *
3284          * If this PMC is current running on a CPU, then it will
3285          * handled correctly at the time its target process is context
3286          * switched out.
3287          */
3288
3289         if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
3290                 return 0;
3291
3292         /*
3293          * A system-mode PMC.  Move to the CPU associated with
3294          * this PMC, and stop the hardware.  We update the
3295          * 'initial count' so that a subsequent PMCSTART will
3296          * resume counting from the current hardware count.
3297          */
3298
3299         pmc_save_cpu_binding(&pb);
3300
3301         cpu = PMC_TO_CPU(pm);
3302
3303         KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
3304             ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
3305
3306         if (!pmc_cpu_is_active(cpu))
3307                 return ENXIO;
3308
3309         pmc_select_cpu(cpu);
3310
3311         ri = PMC_TO_ROWINDEX(pm);
3312         pcd = pmc_ri_to_classdep(md, ri, &adjri);
3313
3314         pm->pm_pcpu_state[cpu].pps_cpustate = 0;
3315         critical_enter();
3316         if ((error = pcd->pcd_stop_pmc(cpu, adjri)) == 0)
3317                 error = pcd->pcd_read_pmc(cpu, adjri, &pm->pm_sc.pm_initial);
3318         critical_exit();
3319
3320         pmc_restore_cpu_binding(&pb);
3321
3322         po = pm->pm_owner;
3323
3324         /* remove this owner from the global list of SS PMC owners */
3325         if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
3326                 po->po_sscount--;
3327                 if (po->po_sscount == 0) {
3328                         atomic_subtract_rel_int(&pmc_ss_count, 1);
3329                         CK_LIST_REMOVE(po, po_ssnext);
3330                         epoch_wait_preempt(global_epoch_preempt);
3331                         PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po);
3332                 }
3333         }
3334
3335         return (error);
3336 }
3337
3338 static struct pmc_classdep *
3339 pmc_class_to_classdep(enum pmc_class class)
3340 {
3341         int n;
3342
3343         for (n = 0; n < md->pmd_nclass; n++)
3344                 if (md->pmd_classdep[n].pcd_class == class)
3345                         return (&md->pmd_classdep[n]);
3346         return (NULL);
3347 }
3348
3349 #if defined(HWPMC_DEBUG) && defined(KTR)
3350 static const char *pmc_op_to_name[] = {
3351 #undef  __PMC_OP
3352 #define __PMC_OP(N, D)  #N ,
3353         __PMC_OPS()
3354         NULL
3355 };
3356 #endif
3357
3358 /*
3359  * The syscall interface
3360  */
3361
3362 #define PMC_GET_SX_XLOCK(...) do {              \
3363         sx_xlock(&pmc_sx);                      \
3364         if (pmc_hook == NULL) {                 \
3365                 sx_xunlock(&pmc_sx);            \
3366                 return __VA_ARGS__;             \
3367         }                                       \
3368 } while (0)
3369
3370 #define PMC_DOWNGRADE_SX() do {                 \
3371         sx_downgrade(&pmc_sx);                  \
3372         is_sx_downgraded = 1;                   \
3373 } while (0)
3374
3375 static int
3376 pmc_syscall_handler(struct thread *td, void *syscall_args)
3377 {
3378         int error, is_sx_downgraded, op;
3379         struct pmc_syscall_args *c;
3380         void *pmclog_proc_handle;
3381         void *arg;
3382
3383         c = (struct pmc_syscall_args *)syscall_args;
3384         op = c->pmop_code;
3385         arg = c->pmop_data;
3386         /* PMC isn't set up yet */
3387         if (pmc_hook == NULL)
3388                 return (EINVAL);
3389         if (op == PMC_OP_CONFIGURELOG) {
3390                 /*
3391                  * We cannot create the logging process inside
3392                  * pmclog_configure_log() because there is a LOR
3393                  * between pmc_sx and process structure locks.
3394                  * Instead, pre-create the process and ignite the loop
3395                  * if everything is fine, otherwise direct the process
3396                  * to exit.
3397                  */
3398                 error = pmclog_proc_create(td, &pmclog_proc_handle);
3399                 if (error != 0)
3400                         goto done_syscall;
3401         }
3402
3403         PMC_GET_SX_XLOCK(ENOSYS);
3404         is_sx_downgraded = 0;
3405         PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
3406             pmc_op_to_name[op], arg);
3407
3408         error = 0;
3409         counter_u64_add(pmc_stats.pm_syscalls, 1);
3410
3411         switch (op) {
3412
3413
3414         /*
3415          * Configure a log file.
3416          *
3417          * XXX This OP will be reworked.
3418          */
3419
3420         case PMC_OP_CONFIGURELOG:
3421         {
3422                 struct proc *p;
3423                 struct pmc *pm;
3424                 struct pmc_owner *po;
3425                 struct pmc_op_configurelog cl;
3426
3427                 if ((error = copyin(arg, &cl, sizeof(cl))) != 0) {
3428                         pmclog_proc_ignite(pmclog_proc_handle, NULL);
3429                         break;
3430                 }
3431
3432                 /* mark this process as owning a log file */
3433                 p = td->td_proc;
3434                 if ((po = pmc_find_owner_descriptor(p)) == NULL)
3435                         if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
3436                                 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3437                                 error = ENOMEM;
3438                                 break;
3439                         }
3440
3441                 /*
3442                  * If a valid fd was passed in, try to configure that,
3443                  * otherwise if 'fd' was less than zero and there was
3444                  * a log file configured, flush its buffers and
3445                  * de-configure it.
3446                  */
3447                 if (cl.pm_logfd >= 0) {
3448                         error = pmclog_configure_log(md, po, cl.pm_logfd);
3449                         pmclog_proc_ignite(pmclog_proc_handle, error == 0 ?
3450                             po : NULL);
3451                 } else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
3452                         pmclog_proc_ignite(pmclog_proc_handle, NULL);
3453                         error = pmclog_close(po);
3454                         if (error == 0) {
3455                                 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
3456                                     if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
3457                                         pm->pm_state == PMC_STATE_RUNNING)
3458                                             pmc_stop(pm);
3459                                 error = pmclog_deconfigure_log(po);
3460                         }
3461                 } else {
3462                         pmclog_proc_ignite(pmclog_proc_handle, NULL);
3463                         error = EINVAL;
3464                 }
3465         }
3466         break;
3467
3468         /*
3469          * Flush a log file.
3470          */
3471
3472         case PMC_OP_FLUSHLOG:
3473         {
3474                 struct pmc_owner *po;
3475
3476                 sx_assert(&pmc_sx, SX_XLOCKED);
3477
3478                 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3479                         error = EINVAL;
3480                         break;
3481                 }
3482
3483                 error = pmclog_flush(po, 0);
3484         }
3485         break;
3486
3487         /*
3488          * Close a log file.
3489          */
3490
3491         case PMC_OP_CLOSELOG:
3492         {
3493                 struct pmc_owner *po;
3494
3495                 sx_assert(&pmc_sx, SX_XLOCKED);
3496
3497                 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3498                         error = EINVAL;
3499                         break;
3500                 }
3501
3502                 error = pmclog_close(po);
3503         }
3504         break;
3505
3506         /*
3507          * Retrieve hardware configuration.
3508          */
3509
3510         case PMC_OP_GETCPUINFO: /* CPU information */
3511         {
3512                 struct pmc_op_getcpuinfo gci;
3513                 struct pmc_classinfo *pci;
3514                 struct pmc_classdep *pcd;
3515                 int cl;
3516
3517                 memset(&gci, 0, sizeof(gci));
3518                 gci.pm_cputype = md->pmd_cputype;
3519                 gci.pm_ncpu    = pmc_cpu_max();
3520                 gci.pm_npmc    = md->pmd_npmc;
3521                 gci.pm_nclass  = md->pmd_nclass;
3522                 pci = gci.pm_classes;
3523                 pcd = md->pmd_classdep;
3524                 for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
3525                         pci->pm_caps  = pcd->pcd_caps;
3526                         pci->pm_class = pcd->pcd_class;
3527                         pci->pm_width = pcd->pcd_width;
3528                         pci->pm_num   = pcd->pcd_num;
3529                 }
3530                 error = copyout(&gci, arg, sizeof(gci));
3531         }
3532         break;
3533
3534         /*
3535          * Retrieve soft events list.
3536          */
3537         case PMC_OP_GETDYNEVENTINFO:
3538         {
3539                 enum pmc_class                  cl;
3540                 enum pmc_event                  ev;
3541                 struct pmc_op_getdyneventinfo   *gei;
3542                 struct pmc_dyn_event_descr      dev;
3543                 struct pmc_soft                 *ps;
3544                 uint32_t                        nevent;
3545
3546                 sx_assert(&pmc_sx, SX_LOCKED);
3547
3548                 gei = (struct pmc_op_getdyneventinfo *) arg;
3549
3550                 if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
3551                         break;
3552
3553                 /* Only SOFT class is dynamic. */
3554                 if (cl != PMC_CLASS_SOFT) {
3555                         error = EINVAL;
3556                         break;
3557                 }
3558
3559                 nevent = 0;
3560                 for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) {
3561                         ps = pmc_soft_ev_acquire(ev);
3562                         if (ps == NULL)
3563                                 continue;
3564                         bcopy(&ps->ps_ev, &dev, sizeof(dev));
3565                         pmc_soft_ev_release(ps);
3566
3567                         error = copyout(&dev,
3568                             &gei->pm_events[nevent],
3569                             sizeof(struct pmc_dyn_event_descr));
3570                         if (error != 0)
3571                                 break;
3572                         nevent++;
3573                 }
3574                 if (error != 0)
3575                         break;
3576
3577                 error = copyout(&nevent, &gei->pm_nevent,
3578                     sizeof(nevent));
3579         }
3580         break;
3581
3582         /*
3583          * Get module statistics
3584          */
3585
3586         case PMC_OP_GETDRIVERSTATS:
3587         {
3588                 struct pmc_op_getdriverstats gms;
3589 #define CFETCH(a, b, field) a.field = counter_u64_fetch(b.field)
3590                 CFETCH(gms, pmc_stats, pm_intr_ignored);
3591                 CFETCH(gms, pmc_stats, pm_intr_processed);
3592                 CFETCH(gms, pmc_stats, pm_intr_bufferfull);
3593                 CFETCH(gms, pmc_stats, pm_syscalls);
3594                 CFETCH(gms, pmc_stats, pm_syscall_errors);
3595                 CFETCH(gms, pmc_stats, pm_buffer_requests);
3596                 CFETCH(gms, pmc_stats, pm_buffer_requests_failed);
3597                 CFETCH(gms, pmc_stats, pm_log_sweeps);
3598 #undef CFETCH
3599                 error = copyout(&gms, arg, sizeof(gms));
3600         }
3601         break;
3602
3603
3604         /*
3605          * Retrieve module version number
3606          */
3607
3608         case PMC_OP_GETMODULEVERSION:
3609         {
3610                 uint32_t cv, modv;
3611
3612                 /* retrieve the client's idea of the ABI version */
3613                 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
3614                         break;
3615                 /* don't service clients newer than our driver */
3616                 modv = PMC_VERSION;
3617                 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
3618                         error = EPROGMISMATCH;
3619                         break;
3620                 }
3621                 error = copyout(&modv, arg, sizeof(int));
3622         }
3623         break;
3624
3625
3626         /*
3627          * Retrieve the state of all the PMCs on a given
3628          * CPU.
3629          */
3630
3631         case PMC_OP_GETPMCINFO:
3632         {
3633                 int ari;
3634                 struct pmc *pm;
3635                 size_t pmcinfo_size;
3636                 uint32_t cpu, n, npmc;
3637                 struct pmc_owner *po;
3638                 struct pmc_binding pb;
3639                 struct pmc_classdep *pcd;
3640                 struct pmc_info *p, *pmcinfo;
3641                 struct pmc_op_getpmcinfo *gpi;
3642
3643                 PMC_DOWNGRADE_SX();
3644
3645                 gpi = (struct pmc_op_getpmcinfo *) arg;
3646
3647                 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
3648                         break;
3649
3650                 if (cpu >= pmc_cpu_max()) {
3651                         error = EINVAL;
3652                         break;
3653                 }
3654
3655                 if (!pmc_cpu_is_active(cpu)) {
3656                         error = ENXIO;
3657                         break;
3658                 }
3659
3660                 /* switch to CPU 'cpu' */
3661                 pmc_save_cpu_binding(&pb);
3662                 pmc_select_cpu(cpu);
3663
3664                 npmc = md->pmd_npmc;
3665
3666                 pmcinfo_size = npmc * sizeof(struct pmc_info);
3667                 pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK | M_ZERO);
3668
3669                 p = pmcinfo;
3670
3671                 for (n = 0; n < md->pmd_npmc; n++, p++) {
3672
3673                         pcd = pmc_ri_to_classdep(md, n, &ari);
3674
3675                         KASSERT(pcd != NULL,
3676                             ("[pmc,%d] null pcd ri=%d", __LINE__, n));
3677
3678                         if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
3679                                 break;
3680
3681                         if (PMC_ROW_DISP_IS_STANDALONE(n))
3682                                 p->pm_rowdisp = PMC_DISP_STANDALONE;
3683                         else if (PMC_ROW_DISP_IS_THREAD(n))
3684                                 p->pm_rowdisp = PMC_DISP_THREAD;
3685                         else
3686                                 p->pm_rowdisp = PMC_DISP_FREE;
3687
3688                         p->pm_ownerpid = -1;
3689
3690                         if (pm == NULL) /* no PMC associated */
3691                                 continue;
3692
3693                         po = pm->pm_owner;
3694
3695                         KASSERT(po->po_owner != NULL,
3696                             ("[pmc,%d] pmc_owner had a null proc pointer",
3697                                 __LINE__));
3698
3699                         p->pm_ownerpid = po->po_owner->p_pid;
3700                         p->pm_mode     = PMC_TO_MODE(pm);
3701                         p->pm_event    = pm->pm_event;
3702                         p->pm_flags    = pm->pm_flags;
3703
3704                         if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3705                                 p->pm_reloadcount =
3706                                     pm->pm_sc.pm_reloadcount;
3707                 }
3708
3709                 pmc_restore_cpu_binding(&pb);
3710
3711                 /* now copy out the PMC info collected */
3712                 if (error == 0)
3713                         error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
3714
3715                 free(pmcinfo, M_PMC);
3716         }
3717         break;
3718
3719
3720         /*
3721          * Set the administrative state of a PMC.  I.e. whether
3722          * the PMC is to be used or not.
3723          */
3724
3725         case PMC_OP_PMCADMIN:
3726         {
3727                 int cpu, ri;
3728                 enum pmc_state request;
3729                 struct pmc_cpu *pc;
3730                 struct pmc_hw *phw;
3731                 struct pmc_op_pmcadmin pma;
3732                 struct pmc_binding pb;
3733
3734                 sx_assert(&pmc_sx, SX_XLOCKED);
3735
3736                 KASSERT(td == curthread,
3737                     ("[pmc,%d] td != curthread", __LINE__));
3738
3739                 error = priv_check(td, PRIV_PMC_MANAGE);
3740                 if (error)
3741                         break;
3742
3743                 if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
3744                         break;
3745
3746                 cpu = pma.pm_cpu;
3747
3748                 if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
3749                         error = EINVAL;
3750                         break;
3751                 }
3752
3753                 if (!pmc_cpu_is_active(cpu)) {
3754                         error = ENXIO;
3755                         break;
3756                 }
3757
3758                 request = pma.pm_state;
3759
3760                 if (request != PMC_STATE_DISABLED &&
3761                     request != PMC_STATE_FREE) {
3762                         error = EINVAL;
3763                         break;
3764                 }
3765
3766                 ri = pma.pm_pmc; /* pmc id == row index */
3767                 if (ri < 0 || ri >= (int) md->pmd_npmc) {
3768                         error = EINVAL;
3769                         break;
3770                 }
3771
3772                 /*
3773                  * We can't disable a PMC with a row-index allocated
3774                  * for process virtual PMCs.
3775                  */
3776
3777                 if (PMC_ROW_DISP_IS_THREAD(ri) &&
3778                     request == PMC_STATE_DISABLED) {
3779                         error = EBUSY;
3780                         break;
3781                 }
3782
3783                 /*
3784                  * otherwise, this PMC on this CPU is either free or
3785                  * in system-wide mode.
3786                  */
3787
3788                 pmc_save_cpu_binding(&pb);
3789                 pmc_select_cpu(cpu);
3790
3791                 pc  = pmc_pcpu[cpu];
3792                 phw = pc->pc_hwpmcs[ri];
3793
3794                 /*
3795                  * XXX do we need some kind of 'forced' disable?
3796                  */
3797
3798                 if (phw->phw_pmc == NULL) {
3799                         if (request == PMC_STATE_DISABLED &&
3800                             (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
3801                                 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
3802                                 PMC_MARK_ROW_STANDALONE(ri);
3803                         } else if (request == PMC_STATE_FREE &&
3804                             (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
3805                                 phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
3806                                 PMC_UNMARK_ROW_STANDALONE(ri);
3807                         }
3808                         /* other cases are a no-op */
3809                 } else
3810                         error = EBUSY;
3811
3812                 pmc_restore_cpu_binding(&pb);
3813         }
3814         break;
3815
3816
3817         /*
3818          * Allocate a PMC.
3819          */
3820
3821         case PMC_OP_PMCALLOCATE:
3822         {
3823                 int adjri, n;
3824                 u_int cpu;
3825                 uint32_t caps;
3826                 struct pmc *pmc;
3827                 enum pmc_mode mode;
3828                 struct pmc_hw *phw;
3829                 struct pmc_binding pb;
3830                 struct pmc_classdep *pcd;
3831                 struct pmc_op_pmcallocate pa;
3832
3833                 if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
3834                         break;
3835
3836                 caps = pa.pm_caps;
3837                 mode = pa.pm_mode;
3838                 cpu  = pa.pm_cpu;
3839
3840                 if ((mode != PMC_MODE_SS  &&  mode != PMC_MODE_SC  &&
3841                      mode != PMC_MODE_TS  &&  mode != PMC_MODE_TC) ||
3842                     (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
3843                         error = EINVAL;
3844                         break;
3845                 }
3846
3847                 /*
3848                  * Virtual PMCs should only ask for a default CPU.
3849                  * System mode PMCs need to specify a non-default CPU.
3850                  */
3851
3852                 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3853                     (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3854                         error = EINVAL;
3855                         break;
3856                 }
3857
3858                 /*
3859                  * Check that an inactive CPU is not being asked for.
3860                  */
3861
3862                 if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3863                         error = ENXIO;
3864                         break;
3865                 }
3866
3867                 /*
3868                  * Refuse an allocation for a system-wide PMC if this
3869                  * process has been jailed, or if this process lacks
3870                  * super-user credentials and the sysctl tunable
3871                  * 'security.bsd.unprivileged_syspmcs' is zero.
3872                  */
3873
3874                 if (PMC_IS_SYSTEM_MODE(mode)) {
3875                         if (jailed(curthread->td_ucred)) {
3876                                 error = EPERM;
3877                                 break;
3878                         }
3879                         if (!pmc_unprivileged_syspmcs) {
3880                                 error = priv_check(curthread,
3881                                     PRIV_PMC_SYSTEM);
3882                                 if (error)
3883                                         break;
3884                         }
3885                 }
3886
3887                 /*
3888                  * Look for valid values for 'pm_flags'
3889                  */
3890
3891                 if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3892                     PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN |
3893                     PMC_F_USERCALLCHAIN)) != 0) {
3894                         error = EINVAL;
3895                         break;
3896                 }
3897
3898                 /* PMC_F_USERCALLCHAIN is only valid with PMC_F_CALLCHAIN */
3899                 if ((pa.pm_flags & (PMC_F_CALLCHAIN | PMC_F_USERCALLCHAIN)) ==
3900                     PMC_F_USERCALLCHAIN) {
3901                         error = EINVAL;
3902                         break;
3903                 }
3904
3905                 /* PMC_F_USERCALLCHAIN is only valid for sampling mode */
3906                 if (pa.pm_flags & PMC_F_USERCALLCHAIN &&
3907                         mode != PMC_MODE_TS && mode != PMC_MODE_SS) {
3908                         error = EINVAL;
3909                         break;
3910                 }
3911
3912                 /* process logging options are not allowed for system PMCs */
3913                 if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3914                     (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3915                         error = EINVAL;
3916                         break;
3917                 }
3918
3919                 /*
3920                  * All sampling mode PMCs need to be able to interrupt the
3921                  * CPU.
3922                  */
3923                 if (PMC_IS_SAMPLING_MODE(mode))
3924                         caps |= PMC_CAP_INTERRUPT;
3925
3926                 /* A valid class specifier should have been passed in. */
3927                 pcd = pmc_class_to_classdep(pa.pm_class);
3928                 if (pcd == NULL) {
3929                         error = EINVAL;
3930                         break;
3931                 }
3932
3933                 /* The requested PMC capabilities should be feasible. */
3934                 if ((pcd->pcd_caps & caps) != caps) {
3935                         error = EOPNOTSUPP;
3936                         break;
3937                 }
3938
3939                 PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3940                     pa.pm_ev, caps, mode, cpu);
3941
3942                 pmc = pmc_allocate_pmc_descriptor();
3943                 pmc->pm_id    = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3944                     PMC_ID_INVALID);
3945                 pmc->pm_event = pa.pm_ev;
3946                 pmc->pm_state = PMC_STATE_FREE;
3947                 pmc->pm_caps  = caps;
3948                 pmc->pm_flags = pa.pm_flags;
3949
3950                 /* XXX set lower bound on sampling for process counters */
3951                 if (PMC_IS_SAMPLING_MODE(mode)) {
3952                         /*
3953                          * Don't permit requested sample rate to be less than 1000
3954                          */
3955                         if (pa.pm_count < 1000)
3956                                 log(LOG_WARNING,
3957                                         "pmcallocate: passed sample rate %ju - setting to 1000\n",
3958                                         (uintmax_t)pa.pm_count);
3959                         pmc->pm_sc.pm_reloadcount = MAX(1000, pa.pm_count);
3960                 } else
3961                         pmc->pm_sc.pm_initial = pa.pm_count;
3962
3963                 /* switch thread to CPU 'cpu' */
3964                 pmc_save_cpu_binding(&pb);
3965
3966 #define PMC_IS_SHAREABLE_PMC(cpu, n)                            \
3967         (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &           \
3968          PMC_PHW_FLAG_IS_SHAREABLE)
3969 #define PMC_IS_UNALLOCATED(cpu, n)                              \
3970         (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3971
3972                 if (PMC_IS_SYSTEM_MODE(mode)) {
3973                         pmc_select_cpu(cpu);
3974                         for (n = pcd->pcd_ri; n < (int) md->pmd_npmc; n++) {
3975                                 pcd = pmc_ri_to_classdep(md, n, &adjri);
3976                                 if (pmc_can_allocate_row(n, mode) == 0 &&
3977                                     pmc_can_allocate_rowindex(
3978                                             curthread->td_proc, n, cpu) == 0 &&
3979                                     (PMC_IS_UNALLOCATED(cpu, n) ||
3980                                      PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3981                                     pcd->pcd_allocate_pmc(cpu, adjri, pmc,
3982                                         &pa) == 0)
3983                                         break;
3984                         }
3985                 } else {
3986                         /* Process virtual mode */
3987                         for (n = pcd->pcd_ri; n < (int) md->pmd_npmc; n++) {
3988                                 pcd = pmc_ri_to_classdep(md, n, &adjri);
3989                                 if (pmc_can_allocate_row(n, mode) == 0 &&
3990                                     pmc_can_allocate_rowindex(
3991                                             curthread->td_proc, n,
3992                                             PMC_CPU_ANY) == 0 &&
3993                                     pcd->pcd_allocate_pmc(curthread->td_oncpu,
3994                                         adjri, pmc, &pa) == 0)
3995                                         break;
3996                         }
3997                 }
3998
3999 #undef  PMC_IS_UNALLOCATED
4000 #undef  PMC_IS_SHAREABLE_PMC
4001
4002                 pmc_restore_cpu_binding(&pb);
4003
4004                 if (n == (int) md->pmd_npmc) {
4005                         pmc_destroy_pmc_descriptor(pmc);
4006                         pmc = NULL;
4007                         error = EINVAL;
4008                         break;
4009                 }
4010
4011                 /* Fill in the correct value in the ID field */
4012                 pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
4013
4014                 PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
4015                     pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
4016
4017                 /* Process mode PMCs with logging enabled need log files */
4018                 if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
4019                         pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
4020
4021                 /* All system mode sampling PMCs require a log file */
4022                 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
4023                         pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
4024
4025                 /*
4026                  * Configure global pmc's immediately
4027                  */
4028
4029                 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
4030
4031                         pmc_save_cpu_binding(&pb);
4032                         pmc_select_cpu(cpu);
4033
4034                         phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
4035                         pcd = pmc_ri_to_classdep(md, n, &adjri);
4036
4037                         if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
4038                             (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
4039                                 (void) pcd->pcd_release_pmc(cpu, adjri, pmc);
4040                                 pmc_destroy_pmc_descriptor(pmc);
4041                                 pmc = NULL;
4042                                 pmc_restore_cpu_binding(&pb);
4043                                 error = EPERM;
4044                                 break;
4045                         }
4046
4047                         pmc_restore_cpu_binding(&pb);
4048                 }
4049
4050                 pmc->pm_state    = PMC_STATE_ALLOCATED;
4051                 pmc->pm_class   = pa.pm_class;
4052
4053                 /*
4054                  * mark row disposition
4055                  */
4056
4057                 if (PMC_IS_SYSTEM_MODE(mode))
4058                         PMC_MARK_ROW_STANDALONE(n);
4059                 else
4060                         PMC_MARK_ROW_THREAD(n);
4061
4062                 /*
4063                  * Register this PMC with the current thread as its owner.
4064                  */
4065
4066                 if ((error =
4067                     pmc_register_owner(curthread->td_proc, pmc)) != 0) {
4068                         pmc_release_pmc_descriptor(pmc);
4069                         pmc_destroy_pmc_descriptor(pmc);
4070                         pmc = NULL;
4071                         break;
4072                 }
4073
4074
4075                 /*
4076                  * Return the allocated index.
4077                  */
4078
4079                 pa.pm_pmcid = pmc->pm_id;
4080
4081                 error = copyout(&pa, arg, sizeof(pa));
4082         }
4083         break;
4084
4085
4086         /*
4087          * Attach a PMC to a process.
4088          */
4089
4090         case PMC_OP_PMCATTACH:
4091         {
4092                 struct pmc *pm;
4093                 struct proc *p;
4094                 struct pmc_op_pmcattach a;
4095
4096                 sx_assert(&pmc_sx, SX_XLOCKED);
4097
4098                 if ((error = copyin(arg, &a, sizeof(a))) != 0)
4099                         break;
4100
4101                 if (a.pm_pid < 0) {
4102                         error = EINVAL;
4103                         break;
4104                 } else if (a.pm_pid == 0)
4105                         a.pm_pid = td->td_proc->p_pid;
4106
4107                 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
4108                         break;
4109
4110                 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
4111                         error = EINVAL;
4112                         break;
4113                 }
4114
4115                 /* PMCs may be (re)attached only when allocated or stopped */
4116                 if (pm->pm_state == PMC_STATE_RUNNING) {
4117                         error = EBUSY;
4118                         break;
4119                 } else if (pm->pm_state != PMC_STATE_ALLOCATED &&
4120                     pm->pm_state != PMC_STATE_STOPPED) {
4121                         error = EINVAL;
4122                         break;
4123                 }
4124
4125                 /* lookup pid */
4126                 if ((p = pfind(a.pm_pid)) == NULL) {
4127                         error = ESRCH;
4128                         break;
4129                 }
4130
4131                 /*
4132                  * Ignore processes that are working on exiting.
4133                  */
4134                 if (p->p_flag & P_WEXIT) {
4135                         error = ESRCH;
4136                         PROC_UNLOCK(p); /* pfind() returns a locked process */
4137                         break;
4138                 }
4139
4140                 /*
4141                  * we are allowed to attach a PMC to a process if
4142                  * we can debug it.
4143                  */
4144                 error = p_candebug(curthread, p);
4145
4146                 PROC_UNLOCK(p);
4147
4148                 if (error == 0)
4149                         error = pmc_attach_process(p, pm);
4150         }
4151         break;
4152
4153
4154         /*
4155          * Detach an attached PMC from a process.
4156          */
4157
4158         case PMC_OP_PMCDETACH:
4159         {
4160                 struct pmc *pm;
4161                 struct proc *p;
4162                 struct pmc_op_pmcattach a;
4163
4164                 if ((error = copyin(arg, &a, sizeof(a))) != 0)
4165                         break;
4166
4167                 if (a.pm_pid < 0) {
4168                         error = EINVAL;
4169                         break;
4170                 } else if (a.pm_pid == 0)
4171                         a.pm_pid = td->td_proc->p_pid;
4172
4173                 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
4174                         break;
4175
4176                 if ((p = pfind(a.pm_pid)) == NULL) {
4177                         error = ESRCH;
4178                         break;
4179                 }
4180
4181                 /*
4182                  * Treat processes that are in the process of exiting
4183                  * as if they were not present.
4184                  */
4185
4186                 if (p->p_flag & P_WEXIT)
4187                         error = ESRCH;
4188
4189                 PROC_UNLOCK(p); /* pfind() returns a locked process */
4190
4191                 if (error == 0)
4192                         error = pmc_detach_process(p, pm);
4193         }
4194         break;
4195
4196
4197         /*
4198          * Retrieve the MSR number associated with the counter
4199          * 'pmc_id'.  This allows processes to directly use RDPMC
4200          * instructions to read their PMCs, without the overhead of a
4201          * system call.
4202          */
4203
4204         case PMC_OP_PMCGETMSR:
4205         {
4206                 int adjri, ri;
4207                 struct pmc *pm;
4208                 struct pmc_target *pt;
4209                 struct pmc_op_getmsr gm;
4210                 struct pmc_classdep *pcd;
4211
4212                 PMC_DOWNGRADE_SX();
4213
4214                 if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
4215                         break;
4216
4217                 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
4218                         break;
4219
4220                 /*
4221                  * The allocated PMC has to be a process virtual PMC,
4222                  * i.e., of type MODE_T[CS].  Global PMCs can only be
4223                  * read using the PMCREAD operation since they may be
4224                  * allocated on a different CPU than the one we could
4225                  * be running on at the time of the RDPMC instruction.
4226                  *
4227                  * The GETMSR operation is not allowed for PMCs that
4228                  * are inherited across processes.
4229                  */
4230
4231                 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
4232                     (pm->pm_flags & PMC_F_DESCENDANTS)) {
4233                         error = EINVAL;
4234                         break;
4235                 }
4236
4237                 /*
4238                  * It only makes sense to use a RDPMC (or its
4239                  * equivalent instruction on non-x86 architectures) on
4240                  * a process that has allocated and attached a PMC to
4241                  * itself.  Conversely the PMC is only allowed to have
4242                  * one process attached to it -- its owner.
4243                  */
4244
4245                 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
4246                     LIST_NEXT(pt, pt_next) != NULL ||
4247                     pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
4248                         error = EINVAL;
4249                         break;
4250                 }
4251
4252                 ri = PMC_TO_ROWINDEX(pm);
4253                 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4254
4255                 /* PMC class has no 'GETMSR' support */
4256                 if (pcd->pcd_get_msr == NULL) {
4257                         error = ENOSYS;
4258                         break;
4259                 }
4260
4261                 if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
4262                         break;
4263
4264                 if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
4265                         break;
4266
4267                 /*
4268                  * Mark our process as using MSRs.  Update machine
4269                  * state using a forced context switch.
4270                  */
4271
4272                 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
4273                 pmc_force_context_switch();
4274
4275         }
4276         break;
4277
4278         /*
4279          * Release an allocated PMC
4280          */
4281
4282         case PMC_OP_PMCRELEASE:
4283         {
4284                 pmc_id_t pmcid;
4285                 struct pmc *pm;
4286                 struct pmc_owner *po;
4287                 struct pmc_op_simple sp;
4288
4289                 /*
4290                  * Find PMC pointer for the named PMC.
4291                  *
4292                  * Use pmc_release_pmc_descriptor() to switch off the
4293                  * PMC, remove all its target threads, and remove the
4294                  * PMC from its owner's list.
4295                  *
4296                  * Remove the owner record if this is the last PMC
4297                  * owned.
4298                  *
4299                  * Free up space.
4300                  */
4301
4302                 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4303                         break;
4304
4305                 pmcid = sp.pm_pmcid;
4306
4307                 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4308                         break;
4309
4310                 po = pm->pm_owner;
4311                 pmc_release_pmc_descriptor(pm);
4312                 pmc_maybe_remove_owner(po);
4313                 pmc_destroy_pmc_descriptor(pm);
4314         }
4315         break;
4316
4317
4318         /*
4319          * Read and/or write a PMC.
4320          */
4321
4322         case PMC_OP_PMCRW:
4323         {
4324                 int adjri;
4325                 struct pmc *pm;
4326                 uint32_t cpu, ri;
4327                 pmc_value_t oldvalue;
4328                 struct pmc_binding pb;
4329                 struct pmc_op_pmcrw prw;
4330                 struct pmc_classdep *pcd;
4331                 struct pmc_op_pmcrw *pprw;
4332
4333                 PMC_DOWNGRADE_SX();
4334
4335                 if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
4336                         break;
4337
4338                 ri = 0;
4339                 PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
4340                     prw.pm_flags);
4341
4342                 /* must have at least one flag set */
4343                 if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
4344                         error = EINVAL;
4345                         break;
4346                 }
4347
4348                 /* locate pmc descriptor */
4349                 if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
4350                         break;
4351
4352                 /* Can't read a PMC that hasn't been started. */
4353                 if (pm->pm_state != PMC_STATE_ALLOCATED &&
4354                     pm->pm_state != PMC_STATE_STOPPED &&
4355                     pm->pm_state != PMC_STATE_RUNNING) {
4356                         error = EINVAL;
4357                         break;
4358                 }
4359
4360                 /* writing a new value is allowed only for 'STOPPED' pmcs */
4361                 if (pm->pm_state == PMC_STATE_RUNNING &&
4362                     (prw.pm_flags & PMC_F_NEWVALUE)) {
4363                         error = EBUSY;
4364                         break;
4365                 }
4366
4367                 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
4368
4369                         /*
4370                          * If this PMC is attached to its owner (i.e.,
4371                          * the process requesting this operation) and
4372                          * is running, then attempt to get an
4373                          * upto-date reading from hardware for a READ.
4374                          * Writes are only allowed when the PMC is
4375                          * stopped, so only update the saved value
4376                          * field.
4377                          *
4378                          * If the PMC is not running, or is not
4379                          * attached to its owner, read/write to the
4380                          * savedvalue field.
4381                          */
4382
4383                         ri = PMC_TO_ROWINDEX(pm);
4384                         pcd = pmc_ri_to_classdep(md, ri, &adjri);
4385
4386                         mtx_pool_lock_spin(pmc_mtxpool, pm);
4387                         cpu = curthread->td_oncpu;
4388
4389                         if (prw.pm_flags & PMC_F_OLDVALUE) {
4390                                 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
4391                                     (pm->pm_state == PMC_STATE_RUNNING))
4392                                         error = (*pcd->pcd_read_pmc)(cpu, adjri,
4393                                             &oldvalue);
4394                                 else
4395                                         oldvalue = pm->pm_gv.pm_savedvalue;
4396                         }
4397                         if (prw.pm_flags & PMC_F_NEWVALUE)
4398                                 pm->pm_gv.pm_savedvalue = prw.pm_value;
4399
4400                         mtx_pool_unlock_spin(pmc_mtxpool, pm);
4401
4402                 } else { /* System mode PMCs */
4403                         cpu = PMC_TO_CPU(pm);
4404                         ri  = PMC_TO_ROWINDEX(pm);
4405                         pcd = pmc_ri_to_classdep(md, ri, &adjri);
4406
4407                         if (!pmc_cpu_is_active(cpu)) {
4408                                 error = ENXIO;
4409                                 break;
4410                         }
4411
4412                         /* move this thread to CPU 'cpu' */
4413                         pmc_save_cpu_binding(&pb);
4414                         pmc_select_cpu(cpu);
4415
4416                         critical_enter();
4417                         /* save old value */
4418                         if (prw.pm_flags & PMC_F_OLDVALUE)
4419                                 if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
4420                                          &oldvalue)))
4421                                         goto error;
4422                         /* write out new value */
4423                         if (prw.pm_flags & PMC_F_NEWVALUE)
4424                                 error = (*pcd->pcd_write_pmc)(cpu, adjri,
4425                                     prw.pm_value);
4426                 error:
4427                         critical_exit();
4428                         pmc_restore_cpu_binding(&pb);
4429                         if (error)
4430                                 break;
4431                 }
4432
4433                 pprw = (struct pmc_op_pmcrw *) arg;
4434
4435 #ifdef  HWPMC_DEBUG
4436                 if (prw.pm_flags & PMC_F_NEWVALUE)
4437                         PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
4438                             ri, prw.pm_value, oldvalue);
4439                 else if (prw.pm_flags & PMC_F_OLDVALUE)
4440                         PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
4441 #endif
4442
4443                 /* return old value if requested */
4444                 if (prw.pm_flags & PMC_F_OLDVALUE)
4445                         if ((error = copyout(&oldvalue, &pprw->pm_value,
4446                                  sizeof(prw.pm_value))))
4447                                 break;
4448
4449         }
4450         break;
4451
4452
4453         /*
4454          * Set the sampling rate for a sampling mode PMC and the
4455          * initial count for a counting mode PMC.
4456          */
4457
4458         case PMC_OP_PMCSETCOUNT:
4459         {
4460                 struct pmc *pm;
4461                 struct pmc_op_pmcsetcount sc;
4462
4463                 PMC_DOWNGRADE_SX();
4464
4465                 if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
4466                         break;
4467
4468                 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
4469                         break;
4470
4471                 if (pm->pm_state == PMC_STATE_RUNNING) {
4472                         error = EBUSY;
4473                         break;
4474                 }
4475
4476                 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
4477                         /*
4478                          * Don't permit requested sample rate to be less than 1000
4479                          */
4480                         if (sc.pm_count < 1000)
4481                                 log(LOG_WARNING,
4482                                         "pmcsetcount: passed sample rate %ju - setting to 1000\n",
4483                                         (uintmax_t)sc.pm_count);
4484                         pm->pm_sc.pm_reloadcount = MAX(1000, sc.pm_count);
4485                 } else
4486                         pm->pm_sc.pm_initial = sc.pm_count;
4487         }
4488         break;
4489
4490
4491         /*
4492          * Start a PMC.
4493          */
4494
4495         case PMC_OP_PMCSTART:
4496         {
4497                 pmc_id_t pmcid;
4498                 struct pmc *pm;
4499                 struct pmc_op_simple sp;
4500
4501                 sx_assert(&pmc_sx, SX_XLOCKED);
4502
4503                 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4504                         break;
4505
4506                 pmcid = sp.pm_pmcid;
4507
4508                 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4509                         break;
4510
4511                 KASSERT(pmcid == pm->pm_id,
4512                     ("[pmc,%d] pmcid %x != id %x", __LINE__,
4513                         pm->pm_id, pmcid));
4514
4515                 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
4516                         break;
4517                 else if (pm->pm_state != PMC_STATE_STOPPED &&
4518                     pm->pm_state != PMC_STATE_ALLOCATED) {
4519                         error = EINVAL;
4520                         break;
4521                 }
4522
4523                 error = pmc_start(pm);
4524         }
4525         break;
4526
4527
4528         /*
4529          * Stop a PMC.
4530          */
4531
4532         case PMC_OP_PMCSTOP:
4533         {
4534                 pmc_id_t pmcid;
4535                 struct pmc *pm;
4536                 struct pmc_op_simple sp;
4537
4538                 PMC_DOWNGRADE_SX();
4539
4540                 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4541                         break;
4542
4543                 pmcid = sp.pm_pmcid;
4544
4545                 /*
4546                  * Mark the PMC as inactive and invoke the MD stop
4547                  * routines if needed.
4548                  */
4549
4550                 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4551                         break;
4552
4553                 KASSERT(pmcid == pm->pm_id,
4554                     ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
4555                         pm->pm_id, pmcid));
4556
4557                 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
4558                         break;
4559                 else if (pm->pm_state != PMC_STATE_RUNNING) {
4560                         error = EINVAL;
4561                         break;
4562                 }
4563
4564                 error = pmc_stop(pm);
4565         }
4566         break;
4567
4568
4569         /*
4570          * Write a user supplied value to the log file.
4571          */
4572
4573         case PMC_OP_WRITELOG:
4574         {
4575                 struct pmc_op_writelog wl;
4576                 struct pmc_owner *po;
4577
4578                 PMC_DOWNGRADE_SX();
4579
4580                 if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
4581                         break;
4582
4583                 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
4584                         error = EINVAL;
4585                         break;
4586                 }
4587
4588                 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
4589                         error = EINVAL;
4590                         break;
4591                 }
4592
4593                 error = pmclog_process_userlog(po, &wl);
4594         }
4595         break;
4596
4597
4598         default:
4599                 error = EINVAL;
4600                 break;
4601         }
4602
4603         if (is_sx_downgraded)
4604                 sx_sunlock(&pmc_sx);
4605         else
4606                 sx_xunlock(&pmc_sx);
4607 done_syscall:
4608         if (error)
4609                 counter_u64_add(pmc_stats.pm_syscall_errors, 1);
4610
4611         return (error);
4612 }
4613
4614 /*
4615  * Helper functions
4616  */
4617
4618
4619 /*
4620  * Mark the thread as needing callchain capture and post an AST.  The
4621  * actual callchain capture will be done in a context where it is safe
4622  * to take page faults.
4623  */
4624
4625 static void
4626 pmc_post_callchain_callback(void)
4627 {
4628         struct thread *td;
4629
4630         td = curthread;
4631
4632         /*
4633          * If there is multiple PMCs for the same interrupt ignore new post
4634          */
4635         if (td->td_pflags & TDP_CALLCHAIN)
4636                 return;
4637
4638         /*
4639          * Mark this thread as needing callchain capture.
4640          * `td->td_pflags' will be safe to touch because this thread
4641          * was in user space when it was interrupted.
4642          */
4643         td->td_pflags |= TDP_CALLCHAIN;
4644
4645         /*
4646          * Don't let this thread migrate between CPUs until callchain
4647          * capture completes.
4648          */
4649         sched_pin();
4650
4651         return;
4652 }
4653
4654 /*
4655  * Find a free slot in the per-cpu array of samples and capture the
4656  * current callchain there.  If a sample was successfully added, a bit
4657  * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4658  * needs to be invoked from the clock handler.
4659  *
4660  * This function is meant to be called from an NMI handler.  It cannot
4661  * use any of the locking primitives supplied by the OS.
4662  */
4663
4664 static int
4665 pmc_add_sample(ring_type_t ring, struct pmc *pm, struct trapframe *tf)
4666 {
4667         int error, cpu, callchaindepth, inuserspace;
4668         struct thread *td;
4669         struct pmc_sample *ps;
4670         struct pmc_samplebuffer *psb;
4671
4672         error = 0;
4673
4674         /*
4675          * Allocate space for a sample buffer.
4676          */
4677         cpu = curcpu;
4678         psb = pmc_pcpu[cpu]->pc_sb[ring];
4679         inuserspace = TRAPF_USERMODE(tf);
4680         ps = PMC_PROD_SAMPLE(psb);
4681         if (psb->ps_considx != psb->ps_prodidx &&
4682                 ps->ps_nsamples) {      /* in use, reader hasn't caught up */
4683                 pm->pm_pcpu_state[cpu].pps_stalled = 1;
4684                 counter_u64_add(pmc_stats.pm_intr_bufferfull, 1);
4685                 PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
4686                     cpu, pm, (void *) tf, inuserspace,
4687                     (int) (psb->ps_prodidx & pmc_sample_mask),
4688                     (int) (psb->ps_considx & pmc_sample_mask));
4689                 callchaindepth = 1;
4690                 error = ENOMEM;
4691                 goto done;
4692         }
4693
4694         /* Fill in entry. */
4695         PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
4696             (void *) tf, inuserspace,
4697             (int) (psb->ps_prodidx & pmc_sample_mask),
4698             (int) (psb->ps_considx & pmc_sample_mask));
4699
4700         td = curthread;
4701         ps->ps_pmc = pm;
4702         ps->ps_td = td;
4703         ps->ps_pid = td->td_proc->p_pid;
4704         ps->ps_tid = td->td_tid;
4705         ps->ps_tsc = pmc_rdtsc();
4706         ps->ps_ticks = ticks;
4707         ps->ps_cpu = cpu;
4708         ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4709
4710         callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4711             pmc_callchaindepth : 1;
4712
4713         MPASS(ps->ps_pc != NULL);
4714         if (callchaindepth == 1)
4715                 ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
4716         else {
4717                 /*
4718                  * Kernel stack traversals can be done immediately,
4719                  * while we defer to an AST for user space traversals.
4720                  */
4721                 if (!inuserspace) {
4722                         callchaindepth =
4723                             pmc_save_kernel_callchain(ps->ps_pc,
4724                                 callchaindepth, tf);
4725                 } else {
4726                         pmc_post_callchain_callback();
4727                         callchaindepth = PMC_USER_CALLCHAIN_PENDING;
4728                 }
4729         }
4730
4731         ps->ps_nsamples = callchaindepth;       /* mark entry as in use */
4732         if (ring == PMC_UR) {
4733                 ps->ps_nsamples_actual = callchaindepth;        /* mark entry as in use */
4734                 ps->ps_nsamples = PMC_USER_CALLCHAIN_PENDING;
4735         } else
4736                 ps->ps_nsamples = callchaindepth;       /* mark entry as in use */
4737
4738         KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
4739             ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
4740                  (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4741
4742         counter_u64_add(pm->pm_runcount, 1);    /* hold onto PMC */
4743         /* increment write pointer */
4744         psb->ps_prodidx++;
4745  done:
4746         /* mark CPU as needing processing */
4747         if (callchaindepth != PMC_USER_CALLCHAIN_PENDING)
4748                 DPCPU_SET(pmc_sampled, 1);
4749
4750         return (error);
4751 }
4752
4753 /*
4754  * Interrupt processing.
4755  *
4756  * This function is meant to be called from an NMI handler.  It cannot
4757  * use any of the locking primitives supplied by the OS.
4758  */
4759
4760 int
4761 pmc_process_interrupt(int ring, struct pmc *pm, struct trapframe *tf)
4762 {
4763         struct thread *td;
4764
4765         td = curthread;
4766         if ((pm->pm_flags & PMC_F_USERCALLCHAIN) &&
4767             (td->td_proc->p_flag & P_KPROC) == 0 &&
4768             !TRAPF_USERMODE(tf)) {
4769                 atomic_add_int(&td->td_pmcpend, 1);
4770                 return (pmc_add_sample(PMC_UR, pm, tf));
4771         }
4772         return (pmc_add_sample(ring, pm, tf));
4773 }
4774
4775 /*
4776  * Capture a user call chain.  This function will be called from ast()
4777  * before control returns to userland and before the process gets
4778  * rescheduled.
4779  */
4780
4781 static void
4782 pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4783 {
4784         struct pmc *pm;
4785         struct thread *td;
4786         struct pmc_sample *ps;
4787         struct pmc_samplebuffer *psb;
4788         uint64_t considx, prodidx;
4789         int nsamples, nrecords, pass, iter;
4790 #ifdef  INVARIANTS
4791         int ncallchains;
4792         int nfree;
4793         int start_ticks = ticks;
4794 #endif
4795         psb = pmc_pcpu[cpu]->pc_sb[ring];
4796         td = curthread;
4797
4798         KASSERT(td->td_pflags & TDP_CALLCHAIN,
4799             ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
4800                 __LINE__));
4801
4802 #ifdef  INVARIANTS
4803         ncallchains = 0;
4804         nfree = 0;
4805 #endif
4806         nrecords = INT_MAX;
4807         pass = 0;
4808  restart:
4809         if (ring == PMC_UR)
4810                 nrecords = atomic_readandclear_32(&td->td_pmcpend);
4811
4812         for (iter = 0, considx = psb->ps_considx, prodidx = psb->ps_prodidx;
4813             considx < prodidx && iter < pmc_nsamples; considx++, iter++) {
4814                 ps = PMC_CONS_SAMPLE_OFF(psb, considx);
4815
4816         /*
4817          * Iterate through all deferred callchain requests.
4818          * Walk from the current read pointer to the current
4819          * write pointer.
4820          */
4821
4822 #ifdef  INVARIANTS
4823                 if (ps->ps_nsamples == PMC_SAMPLE_FREE) {
4824                         nfree++;
4825                         continue;
4826                 }
4827
4828                 if ((ps->ps_pmc == NULL) ||
4829                     (ps->ps_pmc->pm_state != PMC_STATE_RUNNING))
4830                         nfree++;
4831 #endif
4832                 if (ps->ps_td != td ||
4833                    ps->ps_nsamples != PMC_USER_CALLCHAIN_PENDING ||
4834                    ps->ps_pmc->pm_state != PMC_STATE_RUNNING)
4835                         continue;
4836
4837                 KASSERT(ps->ps_cpu == cpu,
4838                     ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
4839                         ps->ps_cpu, PCPU_GET(cpuid)));
4840
4841                 pm = ps->ps_pmc;
4842
4843                 KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
4844                     ("[pmc,%d] Retrieving callchain for PMC that doesn't "
4845                         "want it", __LINE__));
4846
4847                 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4848                     ("[pmc,%d] runcount %ld", __LINE__, (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4849
4850                 if (ring == PMC_UR) {
4851                         nsamples = ps->ps_nsamples_actual;
4852                         counter_u64_add(pmc_stats.pm_merges, 1);
4853                 } else
4854                         nsamples = 0;
4855
4856                 /*
4857                  * Retrieve the callchain and mark the sample buffer
4858                  * as 'processable' by the timer tick sweep code.
4859                  */
4860
4861 #ifdef INVARIANTS
4862                 ncallchains++;
4863 #endif
4864
4865                 if (__predict_true(nsamples < pmc_callchaindepth - 1))
4866                         nsamples += pmc_save_user_callchain(ps->ps_pc + nsamples,
4867                        pmc_callchaindepth - nsamples - 1, tf);
4868
4869                 /*
4870                  * We have to prevent hardclock from potentially overwriting
4871                  * this sample between when we read the value and when we set
4872                  * it
4873                  */
4874                 spinlock_enter();
4875                 /*
4876                  * Verify that the sample hasn't been dropped in the meantime
4877                  */
4878                 if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) {
4879                         ps->ps_nsamples = nsamples;
4880                         /*
4881                          * If we couldn't get a sample, simply drop the reference
4882                          */
4883                         if (nsamples == 0)
4884                                 counter_u64_add(pm->pm_runcount, -1);
4885                 }
4886                 spinlock_exit();
4887                 if (nrecords-- == 1)
4888                         break;
4889         }
4890         if (__predict_false(ring == PMC_UR && td->td_pmcpend)) {
4891                 if (pass == 0) {
4892                         pass = 1;
4893                         goto restart;
4894                 }
4895                 /* only collect samples for this part once */
4896                 td->td_pmcpend = 0;
4897         }
4898
4899 #ifdef INVARIANTS
4900         if ((ticks - start_ticks) > hz)
4901                 log(LOG_ERR, "%s took %d ticks\n", __func__, (ticks - start_ticks));
4902 #endif
4903
4904         /* mark CPU as needing processing */
4905         DPCPU_SET(pmc_sampled, 1);
4906 }
4907
4908 /*
4909  * Process saved PC samples.
4910  */
4911
4912 static void
4913 pmc_process_samples(int cpu, ring_type_t ring)
4914 {
4915         struct pmc *pm;
4916         int adjri, n;
4917         struct thread *td;
4918         struct pmc_owner *po;
4919         struct pmc_sample *ps;
4920         struct pmc_classdep *pcd;
4921         struct pmc_samplebuffer *psb;
4922         uint64_t delta;
4923
4924         KASSERT(PCPU_GET(cpuid) == cpu,
4925             ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4926                 PCPU_GET(cpuid), cpu));
4927
4928         psb = pmc_pcpu[cpu]->pc_sb[ring];
4929         delta = psb->ps_prodidx - psb->ps_considx;
4930         MPASS(delta <= pmc_nsamples);
4931         MPASS(psb->ps_considx <= psb->ps_prodidx);
4932         for (n = 0; psb->ps_considx < psb->ps_prodidx; psb->ps_considx++, n++) {
4933                 ps = PMC_CONS_SAMPLE(psb);
4934
4935                 if (__predict_false(ps->ps_nsamples == PMC_SAMPLE_FREE))
4936                         continue;
4937                 pm = ps->ps_pmc;
4938                 /* skip non-running samples */
4939                 if (pm->pm_state != PMC_STATE_RUNNING)
4940                         goto entrydone;
4941
4942                 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4943                     ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
4944                          (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4945
4946                 po = pm->pm_owner;
4947
4948                 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4949                     ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4950                         pm, PMC_TO_MODE(pm)));
4951
4952
4953                 /* If there is a pending AST wait for completion */
4954                 if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) {
4955                         /* if we've been waiting more than 1 tick to 
4956                          * collect a callchain for this record then
4957                          * drop it and move on.
4958                          */
4959                         if (ticks - ps->ps_ticks > 1) {
4960                                 /*
4961                                  * track how often we hit this as it will
4962                                  * preferentially lose user samples
4963                                  * for long running system calls 
4964                                  */
4965                                 counter_u64_add(pmc_stats.pm_overwrites, 1);
4966                                 goto entrydone;
4967                         }
4968                         /* Need a rescan at a later time. */
4969                         DPCPU_SET(pmc_sampled, 1);
4970                         break;
4971                 }
4972
4973                 PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4974                     pm, ps->ps_nsamples, ps->ps_flags,
4975                     (int) (psb->ps_prodidx & pmc_sample_mask),
4976                     (int) (psb->ps_considx & pmc_sample_mask));
4977
4978                 /*
4979                  * If this is a process-mode PMC that is attached to
4980                  * its owner, and if the PC is in user mode, update
4981                  * profiling statistics like timer-based profiling
4982                  * would have done.
4983                  *
4984                  * Otherwise, this is either a sampling-mode PMC that
4985                  * is attached to a different process than its owner,
4986                  * or a system-wide sampling PMC. Dispatch a log
4987                  * entry to the PMC's owner process.
4988                  */
4989                 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4990                         if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4991                                 td = FIRST_THREAD_IN_PROC(po->po_owner);
4992                                 addupc_intr(td, ps->ps_pc[0], 1);
4993                         }
4994                 } else
4995                         pmclog_process_callchain(pm, ps);
4996
4997         entrydone:
4998                 ps->ps_nsamples = 0; /* mark entry as free */
4999                 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
5000                                 ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
5001                                  (unsigned long)counter_u64_fetch(pm->pm_runcount)));
5002
5003                 counter_u64_add(pm->pm_runcount, -1);
5004         }
5005
5006         counter_u64_add(pmc_stats.pm_log_sweeps, 1);
5007
5008         /* Do not re-enable stalled PMCs if we failed to process any samples */
5009         if (n == 0)
5010                 return;
5011
5012         /*
5013          * Restart any stalled sampling PMCs on this CPU.
5014          *
5015          * If the NMI handler sets the pm_stalled field of a PMC after
5016          * the check below, we'll end up processing the stalled PMC at
5017          * the next hardclock tick.
5018          */
5019         for (n = 0; n < md->pmd_npmc; n++) {
5020                 pcd = pmc_ri_to_classdep(md, n, &adjri);
5021                 KASSERT(pcd != NULL,
5022                     ("[pmc,%d] null pcd ri=%d", __LINE__, n));
5023                 (void) (*pcd->pcd_get_config)(cpu,adjri,&pm);
5024
5025                 if (pm == NULL ||                        /* !cfg'ed */
5026                     pm->pm_state != PMC_STATE_RUNNING || /* !active */
5027                     !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
5028                         !pm->pm_pcpu_state[cpu].pps_cpustate  || /* !desired */
5029                     !pm->pm_pcpu_state[cpu].pps_stalled) /* !stalled */
5030                         continue;
5031
5032                 pm->pm_pcpu_state[cpu].pps_stalled = 0;
5033                 (*pcd->pcd_start_pmc)(cpu, adjri);
5034         }
5035 }
5036
5037 /*
5038  * Event handlers.
5039  */
5040
5041 /*
5042  * Handle a process exit.
5043  *
5044  * Remove this process from all hash tables.  If this process
5045  * owned any PMCs, turn off those PMCs and deallocate them,
5046  * removing any associations with target processes.
5047  *
5048  * This function will be called by the last 'thread' of a
5049  * process.
5050  *
5051  * XXX This eventhandler gets called early in the exit process.
5052  * Consider using a 'hook' invocation from thread_exit() or equivalent
5053  * spot.  Another negative is that kse_exit doesn't seem to call
5054  * exit1() [??].
5055  *
5056  */
5057
5058 static void
5059 pmc_process_exit(void *arg __unused, struct proc *p)
5060 {
5061         struct pmc *pm;
5062         int adjri, cpu;
5063         unsigned int ri;
5064         int is_using_hwpmcs;
5065         struct pmc_owner *po;
5066         struct pmc_process *pp;
5067         struct pmc_classdep *pcd;
5068         pmc_value_t newvalue, tmp;
5069
5070         PROC_LOCK(p);
5071         is_using_hwpmcs = p->p_flag & P_HWPMC;
5072         PROC_UNLOCK(p);
5073
5074         /*
5075          * Log a sysexit event to all SS PMC owners.
5076          */
5077         PMC_EPOCH_ENTER();
5078         CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5079             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5080                     pmclog_process_sysexit(po, p->p_pid);
5081         PMC_EPOCH_EXIT();
5082
5083         if (!is_using_hwpmcs)
5084                 return;
5085
5086         PMC_GET_SX_XLOCK();
5087         PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
5088             p->p_comm);
5089
5090         /*
5091          * Since this code is invoked by the last thread in an exiting
5092          * process, we would have context switched IN at some prior
5093          * point.  However, with PREEMPTION, kernel mode context
5094          * switches may happen any time, so we want to disable a
5095          * context switch OUT till we get any PMCs targeting this
5096          * process off the hardware.
5097          *
5098          * We also need to atomically remove this process'
5099          * entry from our target process hash table, using
5100          * PMC_FLAG_REMOVE.
5101          */
5102         PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
5103             p->p_comm);
5104
5105         critical_enter(); /* no preemption */
5106
5107         cpu = curthread->td_oncpu;
5108
5109         if ((pp = pmc_find_process_descriptor(p,
5110                  PMC_FLAG_REMOVE)) != NULL) {
5111
5112                 PMCDBG2(PRC,EXT,2,
5113                     "process-exit proc=%p pmc-process=%p", p, pp);
5114
5115                 /*
5116                  * The exiting process could the target of
5117                  * some PMCs which will be running on
5118                  * currently executing CPU.
5119                  *
5120                  * We need to turn these PMCs off like we
5121                  * would do at context switch OUT time.
5122                  */
5123                 for (ri = 0; ri < md->pmd_npmc; ri++) {
5124
5125                         /*
5126                          * Pick up the pmc pointer from hardware
5127                          * state similar to the CSW_OUT code.
5128                          */
5129                         pm = NULL;
5130
5131                         pcd = pmc_ri_to_classdep(md, ri, &adjri);
5132
5133                         (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
5134
5135                         PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
5136
5137                         if (pm == NULL ||
5138                             !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
5139                                 continue;
5140
5141                         PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
5142                             "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
5143                             pm, pm->pm_state);
5144
5145                         KASSERT(PMC_TO_ROWINDEX(pm) == ri,
5146                             ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
5147                                 __LINE__, PMC_TO_ROWINDEX(pm), ri));
5148
5149                         KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
5150                             ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
5151                                 __LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
5152
5153                         KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
5154                             ("[pmc,%d] bad runcount ri %d rc %ld",
5155                                  __LINE__, ri, (unsigned long)counter_u64_fetch(pm->pm_runcount)));
5156
5157                         /*
5158                          * Change desired state, and then stop if not
5159                          * stalled. This two-step dance should avoid
5160                          * race conditions where an interrupt re-enables
5161                          * the PMC after this code has already checked
5162                          * the pm_stalled flag.
5163                          */
5164                         if (pm->pm_pcpu_state[cpu].pps_cpustate) {
5165                                 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
5166                                 if (!pm->pm_pcpu_state[cpu].pps_stalled) {
5167                                         (void) pcd->pcd_stop_pmc(cpu, adjri);
5168
5169                                         if (PMC_TO_MODE(pm) == PMC_MODE_TC) {
5170                                                 pcd->pcd_read_pmc(cpu, adjri,
5171                                                     &newvalue);
5172                                                 tmp = newvalue -
5173                                                     PMC_PCPU_SAVED(cpu,ri);
5174
5175                                                 mtx_pool_lock_spin(pmc_mtxpool,
5176                                                     pm);
5177                                                 pm->pm_gv.pm_savedvalue += tmp;
5178                                                 pp->pp_pmcs[ri].pp_pmcval +=
5179                                                     tmp;
5180                                                 mtx_pool_unlock_spin(
5181                                                     pmc_mtxpool, pm);
5182                                         }
5183                                 }
5184                         }
5185
5186                         KASSERT((int64_t) counter_u64_fetch(pm->pm_runcount) > 0,
5187                             ("[pmc,%d] runcount is %d", __LINE__, ri));
5188
5189                         counter_u64_add(pm->pm_runcount, -1);
5190
5191                         (void) pcd->pcd_config_pmc(cpu, adjri, NULL);
5192                 }
5193
5194                 /*
5195                  * Inform the MD layer of this pseudo "context switch
5196                  * out"
5197                  */
5198                 (void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
5199
5200                 critical_exit(); /* ok to be pre-empted now */
5201
5202                 /*
5203                  * Unlink this process from the PMCs that are
5204                  * targeting it.  This will send a signal to
5205                  * all PMC owner's whose PMCs are orphaned.
5206                  *
5207                  * Log PMC value at exit time if requested.
5208                  */
5209                 for (ri = 0; ri < md->pmd_npmc; ri++)
5210                         if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
5211                                 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
5212                                     PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
5213                                         pmclog_process_procexit(pm, pp);
5214                                 pmc_unlink_target_process(pm, pp);
5215                         }
5216                 free(pp, M_PMC);
5217
5218         } else
5219                 critical_exit(); /* pp == NULL */
5220
5221
5222         /*
5223          * If the process owned PMCs, free them up and free up
5224          * memory.
5225          */
5226         if ((po = pmc_find_owner_descriptor(p)) != NULL) {
5227                 pmc_remove_owner(po);
5228                 pmc_destroy_owner_descriptor(po);
5229         }
5230
5231         sx_xunlock(&pmc_sx);
5232 }
5233
5234 /*
5235  * Handle a process fork.
5236  *
5237  * If the parent process 'p1' is under HWPMC monitoring, then copy
5238  * over any attached PMCs that have 'do_descendants' semantics.
5239  */
5240
5241 static void
5242 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
5243     int flags)
5244 {
5245         int is_using_hwpmcs;
5246         unsigned int ri;
5247         uint32_t do_descendants;
5248         struct pmc *pm;
5249         struct pmc_owner *po;
5250         struct pmc_process *ppnew, *ppold;
5251
5252         (void) flags;           /* unused parameter */
5253
5254         PROC_LOCK(p1);
5255         is_using_hwpmcs = p1->p_flag & P_HWPMC;
5256         PROC_UNLOCK(p1);
5257
5258         /*
5259          * If there are system-wide sampling PMCs active, we need to
5260          * log all fork events to their owner's logs.
5261          */
5262         PMC_EPOCH_ENTER();
5263         CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5264             if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
5265                     pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
5266                         pmclog_process_proccreate(po, newproc, 1);
5267                 }
5268         PMC_EPOCH_EXIT();
5269
5270         if (!is_using_hwpmcs)
5271                 return;
5272
5273         PMC_GET_SX_XLOCK();
5274         PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
5275             p1->p_pid, p1->p_comm, newproc);
5276
5277         /*
5278          * If the parent process (curthread->td_proc) is a
5279          * target of any PMCs, look for PMCs that are to be
5280          * inherited, and link these into the new process
5281          * descriptor.
5282          */
5283         if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
5284                  PMC_FLAG_NONE)) == NULL)
5285                 goto done;              /* nothing to do */
5286
5287         do_descendants = 0;
5288         for (ri = 0; ri < md->pmd_npmc; ri++)
5289                 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
5290                         do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
5291         if (do_descendants == 0) /* nothing to do */
5292                 goto done;
5293
5294         /*
5295          * Now mark the new process as being tracked by this driver.
5296          */
5297         PROC_LOCK(newproc);
5298         newproc->p_flag |= P_HWPMC;
5299         PROC_UNLOCK(newproc);
5300
5301         /* allocate a descriptor for the new process  */
5302         if ((ppnew = pmc_find_process_descriptor(newproc,
5303                  PMC_FLAG_ALLOCATE)) == NULL)
5304                 goto done;
5305
5306         /*
5307          * Run through all PMCs that were targeting the old process
5308          * and which specified F_DESCENDANTS and attach them to the
5309          * new process.
5310          *
5311          * Log the fork event to all owners of PMCs attached to this
5312          * process, if not already logged.
5313          */
5314         for (ri = 0; ri < md->pmd_npmc; ri++)
5315                 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
5316                     (pm->pm_flags & PMC_F_DESCENDANTS)) {
5317                         pmc_link_target_process(pm, ppnew);
5318                         po = pm->pm_owner;
5319                         if (po->po_sscount == 0 &&
5320                             po->po_flags & PMC_PO_OWNS_LOGFILE)
5321                                 pmclog_process_procfork(po, p1->p_pid,
5322                                     newproc->p_pid);
5323                 }
5324
5325  done:
5326         sx_xunlock(&pmc_sx);
5327 }
5328
5329 static void
5330 pmc_process_threadcreate(struct thread *td)
5331 {
5332         struct pmc_owner *po;
5333
5334         PMC_EPOCH_ENTER();
5335         CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5336             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5337                         pmclog_process_threadcreate(po, td, 1);
5338         PMC_EPOCH_EXIT();
5339 }
5340
5341 static void
5342 pmc_process_threadexit(struct thread *td)
5343 {
5344         struct pmc_owner *po;
5345
5346         PMC_EPOCH_ENTER();
5347         CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5348             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5349                         pmclog_process_threadexit(po, td);
5350         PMC_EPOCH_EXIT();
5351 }
5352
5353 static void
5354 pmc_process_proccreate(struct proc *p)
5355 {
5356         struct pmc_owner *po;
5357
5358         PMC_EPOCH_ENTER();
5359         CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5360             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5361                         pmclog_process_proccreate(po, p, 1 /* sync */);
5362         PMC_EPOCH_EXIT();
5363 }
5364
5365 static void
5366 pmc_process_allproc(struct pmc *pm)
5367 {
5368         struct pmc_owner *po;
5369         struct thread *td;
5370         struct proc *p;
5371
5372         po = pm->pm_owner;
5373         if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
5374                 return;
5375         sx_slock(&allproc_lock);
5376         FOREACH_PROC_IN_SYSTEM(p) {
5377                 pmclog_process_proccreate(po, p, 0 /* sync */);
5378                 PROC_LOCK(p);
5379                 FOREACH_THREAD_IN_PROC(p, td)
5380                         pmclog_process_threadcreate(po, td, 0 /* sync */);
5381                 PROC_UNLOCK(p);
5382         }
5383         sx_sunlock(&allproc_lock);
5384         pmclog_flush(po, 0);
5385 }
5386
5387 static void
5388 pmc_kld_load(void *arg __unused, linker_file_t lf)
5389 {
5390         struct pmc_owner *po;
5391
5392         /*
5393          * Notify owners of system sampling PMCs about KLD operations.
5394          */
5395         PMC_EPOCH_ENTER();
5396         CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5397                 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5398                         pmclog_process_map_in(po, (pid_t) -1,
5399                             (uintfptr_t) lf->address, lf->filename);
5400         PMC_EPOCH_EXIT();
5401
5402         /*
5403          * TODO: Notify owners of (all) process-sampling PMCs too.
5404          */
5405 }
5406
5407 static void
5408 pmc_kld_unload(void *arg __unused, const char *filename __unused,
5409     caddr_t address, size_t size)
5410 {
5411         struct pmc_owner *po;
5412
5413         PMC_EPOCH_ENTER();
5414         CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5415                 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5416                         pmclog_process_map_out(po, (pid_t) -1,
5417                             (uintfptr_t) address, (uintfptr_t) address + size);
5418         PMC_EPOCH_EXIT();
5419
5420         /*
5421          * TODO: Notify owners of process-sampling PMCs.
5422          */
5423 }
5424
5425 /*
5426  * initialization
5427  */
5428 static const char *
5429 pmc_name_of_pmcclass(enum pmc_class class)
5430 {
5431
5432         switch (class) {
5433 #undef  __PMC_CLASS
5434 #define __PMC_CLASS(S,V,D)                                              \
5435         case PMC_CLASS_##S:                                             \
5436                 return #S;
5437         __PMC_CLASSES();
5438         default:
5439                 return ("<unknown>");
5440         }
5441 }
5442
5443 /*
5444  * Base class initializer: allocate structure and set default classes.
5445  */
5446 struct pmc_mdep *
5447 pmc_mdep_alloc(int nclasses)
5448 {
5449         struct pmc_mdep *md;
5450         int     n;
5451
5452         /* SOFT + md classes */
5453         n = 1 + nclasses;
5454         md = malloc(sizeof(struct pmc_mdep) + n *
5455             sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
5456         md->pmd_nclass = n;
5457
5458         /* Add base class. */
5459         pmc_soft_initialize(md);
5460         return md;
5461 }
5462
5463 void
5464 pmc_mdep_free(struct pmc_mdep *md)
5465 {
5466         pmc_soft_finalize(md);
5467         free(md, M_PMC);
5468 }
5469
5470 static int
5471 generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
5472 {
5473         (void) pc; (void) pp;
5474
5475         return (0);
5476 }
5477
5478 static int
5479 generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
5480 {
5481         (void) pc; (void) pp;
5482
5483         return (0);
5484 }
5485
5486 static struct pmc_mdep *
5487 pmc_generic_cpu_initialize(void)
5488 {
5489         struct pmc_mdep *md;
5490
5491         md = pmc_mdep_alloc(0);
5492
5493         md->pmd_cputype    = PMC_CPU_GENERIC;
5494
5495         md->pmd_pcpu_init  = NULL;
5496         md->pmd_pcpu_fini  = NULL;
5497         md->pmd_switch_in  = generic_switch_in;
5498         md->pmd_switch_out = generic_switch_out;
5499
5500         return (md);
5501 }
5502
5503 static void
5504 pmc_generic_cpu_finalize(struct pmc_mdep *md)
5505 {
5506         (void) md;
5507 }
5508
5509
5510 static int
5511 pmc_initialize(void)
5512 {
5513         int c, cpu, error, n, ri;
5514         unsigned int maxcpu, domain;
5515         struct pcpu *pc;
5516         struct pmc_binding pb;
5517         struct pmc_sample *ps;
5518         struct pmc_classdep *pcd;
5519         struct pmc_samplebuffer *sb;
5520
5521         md = NULL;
5522         error = 0;
5523
5524         pmc_stats.pm_intr_ignored = counter_u64_alloc(M_WAITOK);
5525         pmc_stats.pm_intr_processed = counter_u64_alloc(M_WAITOK);
5526         pmc_stats.pm_intr_bufferfull = counter_u64_alloc(M_WAITOK);
5527         pmc_stats.pm_syscalls = counter_u64_alloc(M_WAITOK);
5528         pmc_stats.pm_syscall_errors = counter_u64_alloc(M_WAITOK);
5529         pmc_stats.pm_buffer_requests = counter_u64_alloc(M_WAITOK);
5530         pmc_stats.pm_buffer_requests_failed = counter_u64_alloc(M_WAITOK);
5531         pmc_stats.pm_log_sweeps = counter_u64_alloc(M_WAITOK);
5532         pmc_stats.pm_merges = counter_u64_alloc(M_WAITOK);
5533         pmc_stats.pm_overwrites = counter_u64_alloc(M_WAITOK);
5534
5535 #ifdef  HWPMC_DEBUG
5536         /* parse debug flags first */
5537         if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
5538                 pmc_debugstr, sizeof(pmc_debugstr)))
5539                 pmc_debugflags_parse(pmc_debugstr,
5540                     pmc_debugstr+strlen(pmc_debugstr));
5541 #endif
5542
5543         PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
5544
5545         /* check kernel version */
5546         if (pmc_kernel_version != PMC_VERSION) {
5547                 if (pmc_kernel_version == 0)
5548                         printf("hwpmc: this kernel has not been compiled with "
5549                             "'options HWPMC_HOOKS'.\n");
5550                 else
5551                         printf("hwpmc: kernel version (0x%x) does not match "
5552                             "module version (0x%x).\n", pmc_kernel_version,
5553                             PMC_VERSION);
5554                 return EPROGMISMATCH;
5555         }
5556
5557         /*
5558          * check sysctl parameters
5559          */
5560
5561         if (pmc_hashsize <= 0) {
5562                 (void) printf("hwpmc: tunable \"hashsize\"=%d must be "
5563                     "greater than zero.\n", pmc_hashsize);
5564                 pmc_hashsize = PMC_HASH_SIZE;
5565         }
5566
5567         if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
5568                 (void) printf("hwpmc: tunable \"nsamples\"=%d out of "
5569                     "range.\n", pmc_nsamples);
5570                 pmc_nsamples = PMC_NSAMPLES;
5571         }
5572         pmc_sample_mask = pmc_nsamples-1;
5573
5574         if (pmc_callchaindepth <= 0 ||
5575             pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
5576                 (void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
5577                     "range - using %d.\n", pmc_callchaindepth,
5578                     PMC_CALLCHAIN_DEPTH_MAX);
5579                 pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX;
5580         }
5581
5582         md = pmc_md_initialize();
5583         if (md == NULL) {
5584                 /* Default to generic CPU. */
5585                 md = pmc_generic_cpu_initialize();
5586                 if (md == NULL)
5587                         return (ENOSYS);
5588         }
5589
5590         KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
5591             ("[pmc,%d] no classes or pmcs", __LINE__));
5592
5593         /* Compute the map from row-indices to classdep pointers. */
5594         pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
5595             md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);
5596
5597         for (n = 0; n < md->pmd_npmc; n++)
5598                 pmc_rowindex_to_classdep[n] = NULL;
5599         for (ri = c = 0; c < md->pmd_nclass; c++) {
5600                 pcd = &md->pmd_classdep[c];
5601                 for (n = 0; n < pcd->pcd_num; n++, ri++)
5602                         pmc_rowindex_to_classdep[ri] = pcd;
5603         }
5604
5605         KASSERT(ri == md->pmd_npmc,
5606             ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
5607             ri, md->pmd_npmc));
5608
5609         maxcpu = pmc_cpu_max();
5610
5611         /* allocate space for the per-cpu array */
5612         pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
5613             M_WAITOK|M_ZERO);
5614
5615         /* per-cpu 'saved values' for managing process-mode PMCs */
5616         pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
5617             M_PMC, M_WAITOK);
5618
5619         /* Perform CPU-dependent initialization. */
5620         pmc_save_cpu_binding(&pb);
5621         error = 0;
5622         for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
5623                 if (!pmc_cpu_is_active(cpu))
5624                         continue;
5625                 pmc_select_cpu(cpu);
5626                 pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
5627                     md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
5628                     M_WAITOK|M_ZERO);
5629                 if (md->pmd_pcpu_init)
5630                         error = md->pmd_pcpu_init(md, cpu);
5631                 for (n = 0; error == 0 && n < md->pmd_nclass; n++)
5632                         error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
5633         }
5634         pmc_restore_cpu_binding(&pb);
5635
5636         if (error)
5637                 return (error);
5638
5639         /* allocate space for the sample array */
5640         for (cpu = 0; cpu < maxcpu; cpu++) {
5641                 if (!pmc_cpu_is_active(cpu))
5642                         continue;
5643                 pc = pcpu_find(cpu);
5644                 domain = pc->pc_domain;
5645                 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
5646                     pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
5647                     DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5648
5649                 KASSERT(pmc_pcpu[cpu] != NULL,
5650                     ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
5651
5652                 sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
5653                     pmc_nsamples * sizeof(uintptr_t), M_PMC,
5654                     DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5655
5656                 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5657                         ps->ps_pc = sb->ps_callchains +
5658                             (n * pmc_callchaindepth);
5659
5660                 pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
5661
5662                 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
5663                     pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
5664                     DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5665
5666                 sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
5667                     pmc_nsamples * sizeof(uintptr_t), M_PMC,
5668                     DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5669                 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5670                         ps->ps_pc = sb->ps_callchains +
5671                             (n * pmc_callchaindepth);
5672
5673                 pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
5674
5675                 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
5676                     pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
5677                     DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5678                 sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
5679                     pmc_nsamples * sizeof(uintptr_t), M_PMC,
5680                     DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5681                 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5682                         ps->ps_pc = sb->ps_callchains + n * pmc_callchaindepth;
5683
5684                 pmc_pcpu[cpu]->pc_sb[PMC_UR] = sb;
5685         }
5686
5687         /* allocate space for the row disposition array */
5688         pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
5689             M_PMC, M_WAITOK|M_ZERO);
5690
5691         /* mark all PMCs as available */
5692         for (n = 0; n < (int) md->pmd_npmc; n++)
5693                 PMC_MARK_ROW_FREE(n);
5694
5695         /* allocate thread hash tables */
5696         pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
5697             &pmc_ownerhashmask);
5698
5699         pmc_processhash = hashinit(pmc_hashsize, M_PMC,
5700             &pmc_processhashmask);
5701         mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
5702             MTX_SPIN);
5703
5704         CK_LIST_INIT(&pmc_ss_owners);
5705         pmc_ss_count = 0;
5706
5707         /* allocate a pool of spin mutexes */
5708         pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
5709             MTX_SPIN);
5710
5711         PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
5712             "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
5713             pmc_processhash, pmc_processhashmask);
5714
5715         /* Initialize a spin mutex for the thread free list. */
5716         mtx_init(&pmc_threadfreelist_mtx, "pmc-threadfreelist", "pmc-leaf",
5717             MTX_SPIN);
5718
5719         /*
5720          * Initialize the callout to monitor the thread free list.
5721          * This callout will also handle the initial population of the list.
5722          */
5723         taskqgroup_config_gtask_init(NULL, &free_gtask, pmc_thread_descriptor_pool_free_task, "thread descriptor pool free task");
5724
5725         /* register process {exit,fork,exec} handlers */
5726         pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
5727             pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
5728         pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
5729             pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
5730
5731         /* register kld event handlers */
5732         pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
5733             NULL, EVENTHANDLER_PRI_ANY);
5734         pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
5735             NULL, EVENTHANDLER_PRI_ANY);
5736
5737         /* initialize logging */
5738         pmclog_initialize();
5739
5740         /* set hook functions */
5741         pmc_intr = md->pmd_intr;
5742         wmb();
5743         pmc_hook = pmc_hook_handler;
5744
5745         if (error == 0) {
5746                 printf(PMC_MODULE_NAME ":");
5747                 for (n = 0; n < (int) md->pmd_nclass; n++) {
5748                         pcd = &md->pmd_classdep[n];
5749                         printf(" %s/%d/%d/0x%b",
5750                             pmc_name_of_pmcclass(pcd->pcd_class),
5751                             pcd->pcd_num,
5752                             pcd->pcd_width,
5753                             pcd->pcd_caps,
5754                             "\20"
5755                             "\1INT\2USR\3SYS\4EDG\5THR"
5756                             "\6REA\7WRI\10INV\11QUA\12PRC"
5757                             "\13TAG\14CSC");
5758                 }
5759                 printf("\n");
5760         }
5761
5762         return (error);
5763 }
5764
5765 /* prepare to be unloaded */
5766 static void
5767 pmc_cleanup(void)
5768 {
5769         int c, cpu;
5770         unsigned int maxcpu;
5771         struct pmc_ownerhash *ph;
5772         struct pmc_owner *po, *tmp;
5773         struct pmc_binding pb;
5774 #ifdef  HWPMC_DEBUG
5775         struct pmc_processhash *prh;
5776 #endif
5777
5778         PMCDBG0(MOD,INI,0, "cleanup");
5779
5780         /* switch off sampling */
5781         CPU_FOREACH(cpu)
5782                 DPCPU_ID_SET(cpu, pmc_sampled, 0);
5783         pmc_intr = NULL;
5784
5785         sx_xlock(&pmc_sx);
5786         if (pmc_hook == NULL) { /* being unloaded already */
5787                 sx_xunlock(&pmc_sx);
5788                 return;
5789         }
5790
5791         pmc_hook = NULL; /* prevent new threads from entering module */
5792
5793         /* deregister event handlers */
5794         EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
5795         EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
5796         EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
5797         EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);
5798
5799         /* send SIGBUS to all owner threads, free up allocations */
5800         if (pmc_ownerhash)
5801                 for (ph = pmc_ownerhash;
5802                      ph <= &pmc_ownerhash[pmc_ownerhashmask];
5803                      ph++) {
5804                         LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
5805                                 pmc_remove_owner(po);
5806
5807                                 /* send SIGBUS to owner processes */
5808                                 PMCDBG3(MOD,INI,2, "cleanup signal proc=%p "
5809                                     "(%d, %s)", po->po_owner,
5810                                     po->po_owner->p_pid,
5811                                     po->po_owner->p_comm);
5812
5813                                 PROC_LOCK(po->po_owner);
5814                                 kern_psignal(po->po_owner, SIGBUS);
5815                                 PROC_UNLOCK(po->po_owner);
5816
5817                                 pmc_destroy_owner_descriptor(po);
5818                         }
5819                 }
5820
5821         /* reclaim allocated data structures */
5822         mtx_destroy(&pmc_threadfreelist_mtx);
5823         pmc_thread_descriptor_pool_drain();
5824
5825         if (pmc_mtxpool)
5826                 mtx_pool_destroy(&pmc_mtxpool);
5827
5828         mtx_destroy(&pmc_processhash_mtx);
5829         taskqgroup_config_gtask_deinit(&free_gtask);
5830         if (pmc_processhash) {
5831 #ifdef  HWPMC_DEBUG
5832                 struct pmc_process *pp;
5833
5834                 PMCDBG0(MOD,INI,3, "destroy process hash");
5835                 for (prh = pmc_processhash;
5836                      prh <= &pmc_processhash[pmc_processhashmask];
5837                      prh++)
5838                         LIST_FOREACH(pp, prh, pp_next)
5839                             PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5840 #endif
5841
5842                 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5843                 pmc_processhash = NULL;
5844         }
5845
5846         if (pmc_ownerhash) {
5847                 PMCDBG0(MOD,INI,3, "destroy owner hash");
5848                 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5849                 pmc_ownerhash = NULL;
5850         }
5851
5852         KASSERT(CK_LIST_EMPTY(&pmc_ss_owners),
5853             ("[pmc,%d] Global SS owner list not empty", __LINE__));
5854         KASSERT(pmc_ss_count == 0,
5855             ("[pmc,%d] Global SS count not empty", __LINE__));
5856
5857         /* do processor and pmc-class dependent cleanup */
5858         maxcpu = pmc_cpu_max();
5859
5860         PMCDBG0(MOD,INI,3, "md cleanup");
5861         if (md) {
5862                 pmc_save_cpu_binding(&pb);
5863                 for (cpu = 0; cpu < maxcpu; cpu++) {
5864                         PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5865                             cpu, pmc_pcpu[cpu]);
5866                         if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5867                                 continue;
5868                         pmc_select_cpu(cpu);
5869                         for (c = 0; c < md->pmd_nclass; c++)
5870                                 md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
5871                         if (md->pmd_pcpu_fini)
5872                                 md->pmd_pcpu_fini(md, cpu);
5873                 }
5874
5875                 if (md->pmd_cputype == PMC_CPU_GENERIC)
5876                         pmc_generic_cpu_finalize(md);
5877                 else
5878                         pmc_md_finalize(md);
5879
5880                 pmc_mdep_free(md);
5881                 md = NULL;
5882                 pmc_restore_cpu_binding(&pb);
5883         }
5884
5885         /* Free per-cpu descriptors. */
5886         for (cpu = 0; cpu < maxcpu; cpu++) {
5887                 if (!pmc_cpu_is_active(cpu))
5888                         continue;
5889                 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5890                     ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5891                         cpu));
5892                 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5893                     ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5894                         cpu));
5895                 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_UR] != NULL,
5896                     ("[pmc,%d] Null userret cpu sample buffer cpu=%d", __LINE__,
5897                         cpu));
5898                 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
5899                 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
5900                 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
5901                 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
5902                 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_UR]->ps_callchains, M_PMC);
5903                 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_UR], M_PMC);
5904                 free_domain(pmc_pcpu[cpu], M_PMC);
5905         }
5906
5907         free(pmc_pcpu, M_PMC);
5908         pmc_pcpu = NULL;
5909
5910         free(pmc_pcpu_saved, M_PMC);
5911         pmc_pcpu_saved = NULL;
5912
5913         if (pmc_pmcdisp) {
5914                 free(pmc_pmcdisp, M_PMC);
5915                 pmc_pmcdisp = NULL;
5916         }
5917
5918         if (pmc_rowindex_to_classdep) {
5919                 free(pmc_rowindex_to_classdep, M_PMC);
5920                 pmc_rowindex_to_classdep = NULL;
5921         }
5922
5923         pmclog_shutdown();
5924         counter_u64_free(pmc_stats.pm_intr_ignored);
5925         counter_u64_free(pmc_stats.pm_intr_processed);
5926         counter_u64_free(pmc_stats.pm_intr_bufferfull);
5927         counter_u64_free(pmc_stats.pm_syscalls);
5928         counter_u64_free(pmc_stats.pm_syscall_errors);
5929         counter_u64_free(pmc_stats.pm_buffer_requests);
5930         counter_u64_free(pmc_stats.pm_buffer_requests_failed);
5931         counter_u64_free(pmc_stats.pm_log_sweeps);
5932         counter_u64_free(pmc_stats.pm_merges);
5933         counter_u64_free(pmc_stats.pm_overwrites);
5934         sx_xunlock(&pmc_sx);    /* we are done */
5935 }
5936
5937 /*
5938  * The function called at load/unload.
5939  */
5940
5941 static int
5942 load (struct module *module __unused, int cmd, void *arg __unused)
5943 {
5944         int error;
5945
5946         error = 0;
5947
5948         switch (cmd) {
5949         case MOD_LOAD :
5950                 /* initialize the subsystem */
5951                 error = pmc_initialize();
5952                 if (error != 0)
5953                         break;
5954                 PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d",
5955                     pmc_syscall_num, pmc_cpu_max());
5956                 break;
5957
5958
5959         case MOD_UNLOAD :
5960         case MOD_SHUTDOWN:
5961                 pmc_cleanup();
5962                 PMCDBG0(MOD,INI,1, "unloaded");
5963                 break;
5964
5965         default :
5966                 error = EINVAL; /* XXX should panic(9) */
5967                 break;
5968         }
5969
5970         return error;
5971 }