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