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