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