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