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