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