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