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