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