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