xref: /freebsd/sys/dev/hwpmc/hwpmc_mod.c (revision cacdd70cc751fb68dec4b86c5e5b8c969b6e26ef)
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 		if (p->p_flag & P_KTHREAD) {
970 			fullpath = kernelname;
971 			freepath = NULL;
972 		} else
973 			pmclog_process_pmcattach(pm, p->p_pid, fullpath);
974 		if (freepath)
975 			FREE(freepath, M_TEMP);
976 		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
977 			pmc_log_process_mappings(pm->pm_owner, p);
978 	}
979 	/* mark process as using HWPMCs */
980 	PROC_LOCK(p);
981 	p->p_flag |= P_HWPMC;
982 	PROC_UNLOCK(p);
983 
984 	return 0;
985 }
986 
987 /*
988  * Attach a process and optionally its children
989  */
990 
991 static int
992 pmc_attach_process(struct proc *p, struct pmc *pm)
993 {
994 	int error;
995 	struct proc *top;
996 
997 	sx_assert(&pmc_sx, SX_XLOCKED);
998 
999 	PMCDBG(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1000 	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1001 
1002 
1003 	/*
1004 	 * If this PMC successfully allowed a GETMSR operation
1005 	 * in the past, disallow further ATTACHes.
1006 	 */
1007 
1008 	if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1009 		return EPERM;
1010 
1011 	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1012 		return pmc_attach_one_process(p, pm);
1013 
1014 	/*
1015 	 * Traverse all child processes, attaching them to
1016 	 * this PMC.
1017 	 */
1018 
1019 	sx_slock(&proctree_lock);
1020 
1021 	top = p;
1022 
1023 	for (;;) {
1024 		if ((error = pmc_attach_one_process(p, pm)) != 0)
1025 			break;
1026 		if (!LIST_EMPTY(&p->p_children))
1027 			p = LIST_FIRST(&p->p_children);
1028 		else for (;;) {
1029 			if (p == top)
1030 				goto done;
1031 			if (LIST_NEXT(p, p_sibling)) {
1032 				p = LIST_NEXT(p, p_sibling);
1033 				break;
1034 			}
1035 			p = p->p_pptr;
1036 		}
1037 	}
1038 
1039 	if (error)
1040 		(void) pmc_detach_process(top, pm);
1041 
1042  done:
1043 	sx_sunlock(&proctree_lock);
1044 	return error;
1045 }
1046 
1047 /*
1048  * Detach a process from a PMC.  If there are no other PMCs tracking
1049  * this process, remove the process structure from its hash table.  If
1050  * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1051  */
1052 
1053 static int
1054 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1055 {
1056 	int ri;
1057 	struct pmc_process *pp;
1058 
1059 	sx_assert(&pmc_sx, SX_XLOCKED);
1060 
1061 	KASSERT(pm != NULL,
1062 	    ("[pmc,%d] null pm pointer", __LINE__));
1063 
1064 	ri = PMC_TO_ROWINDEX(pm);
1065 
1066 	PMCDBG(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1067 	    pm, ri, p, p->p_pid, p->p_comm, flags);
1068 
1069 	if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1070 		return ESRCH;
1071 
1072 	if (pp->pp_pmcs[ri].pp_pmc != pm)
1073 		return EINVAL;
1074 
1075 	pmc_unlink_target_process(pm, pp);
1076 
1077 	/* Issue a detach entry if a log file is configured */
1078 	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1079 		pmclog_process_pmcdetach(pm, p->p_pid);
1080 
1081 	/*
1082 	 * If there are no PMCs targetting this process, we remove its
1083 	 * descriptor from the target hash table and unset the P_HWPMC
1084 	 * flag in the struct proc.
1085 	 */
1086 	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1087 	    ("[pmc,%d] Illegal refcnt %d for process struct %p",
1088 		__LINE__, pp->pp_refcnt, pp));
1089 
1090 	if (pp->pp_refcnt != 0)	/* still a target of some PMC */
1091 		return 0;
1092 
1093 	pmc_remove_process_descriptor(pp);
1094 
1095 	if (flags & PMC_FLAG_REMOVE)
1096 		FREE(pp, M_PMC);
1097 
1098 	PROC_LOCK(p);
1099 	p->p_flag &= ~P_HWPMC;
1100 	PROC_UNLOCK(p);
1101 
1102 	return 0;
1103 }
1104 
1105 /*
1106  * Detach a process and optionally its descendants from a PMC.
1107  */
1108 
1109 static int
1110 pmc_detach_process(struct proc *p, struct pmc *pm)
1111 {
1112 	struct proc *top;
1113 
1114 	sx_assert(&pmc_sx, SX_XLOCKED);
1115 
1116 	PMCDBG(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1117 	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1118 
1119 	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1120 		return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1121 
1122 	/*
1123 	 * Traverse all children, detaching them from this PMC.  We
1124 	 * ignore errors since we could be detaching a PMC from a
1125 	 * partially attached proc tree.
1126 	 */
1127 
1128 	sx_slock(&proctree_lock);
1129 
1130 	top = p;
1131 
1132 	for (;;) {
1133 		(void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1134 
1135 		if (!LIST_EMPTY(&p->p_children))
1136 			p = LIST_FIRST(&p->p_children);
1137 		else for (;;) {
1138 			if (p == top)
1139 				goto done;
1140 			if (LIST_NEXT(p, p_sibling)) {
1141 				p = LIST_NEXT(p, p_sibling);
1142 				break;
1143 			}
1144 			p = p->p_pptr;
1145 		}
1146 	}
1147 
1148  done:
1149 	sx_sunlock(&proctree_lock);
1150 
1151 	if (LIST_EMPTY(&pm->pm_targets))
1152 		pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1153 
1154 	return 0;
1155 }
1156 
1157 
1158 /*
1159  * Thread context switch IN
1160  */
1161 
1162 static void
1163 pmc_process_csw_in(struct thread *td)
1164 {
1165 	int cpu;
1166 	unsigned int ri;
1167 	struct pmc *pm;
1168 	struct proc *p;
1169 	struct pmc_cpu *pc;
1170 	struct pmc_hw *phw;
1171 	struct pmc_process *pp;
1172 	pmc_value_t newvalue;
1173 
1174 	p = td->td_proc;
1175 
1176 	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1177 		return;
1178 
1179 	KASSERT(pp->pp_proc == td->td_proc,
1180 	    ("[pmc,%d] not my thread state", __LINE__));
1181 
1182 	critical_enter(); /* no preemption from this point */
1183 
1184 	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1185 
1186 	PMCDBG(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1187 	    p->p_pid, p->p_comm, pp);
1188 
1189 	KASSERT(cpu >= 0 && cpu < mp_ncpus,
1190 	    ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
1191 
1192 	pc = pmc_pcpu[cpu];
1193 
1194 	for (ri = 0; ri < md->pmd_npmc; ri++) {
1195 
1196 		if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1197 			continue;
1198 
1199 		KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1200 		    ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1201 			__LINE__, PMC_TO_MODE(pm)));
1202 
1203 		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1204 		    ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1205 			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1206 
1207 		/*
1208 		 * Only PMCs that are marked as 'RUNNING' need
1209 		 * be placed on hardware.
1210 		 */
1211 
1212 		if (pm->pm_state != PMC_STATE_RUNNING)
1213 			continue;
1214 
1215 		/* increment PMC runcount */
1216 		atomic_add_rel_32(&pm->pm_runcount, 1);
1217 
1218 		/* configure the HWPMC we are going to use. */
1219 		md->pmd_config_pmc(cpu, ri, pm);
1220 
1221 		phw = pc->pc_hwpmcs[ri];
1222 
1223 		KASSERT(phw != NULL,
1224 		    ("[pmc,%d] null hw pointer", __LINE__));
1225 
1226 		KASSERT(phw->phw_pmc == pm,
1227 		    ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1228 			phw->phw_pmc, pm));
1229 
1230 		/*
1231 		 * Write out saved value and start the PMC.
1232 		 *
1233 		 * Sampling PMCs use a per-process value, while
1234 		 * counting mode PMCs use a per-pmc value that is
1235 		 * inherited across descendants.
1236 		 */
1237 		if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1238 			mtx_pool_lock_spin(pmc_mtxpool, pm);
1239 			newvalue = PMC_PCPU_SAVED(cpu,ri) =
1240 			    pp->pp_pmcs[ri].pp_pmcval;
1241 			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1242 		} else {
1243 			KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1244 			    ("[pmc,%d] illegal mode=%d", __LINE__,
1245 			    PMC_TO_MODE(pm)));
1246 			mtx_pool_lock_spin(pmc_mtxpool, pm);
1247 			newvalue = PMC_PCPU_SAVED(cpu, ri) =
1248 			    pm->pm_gv.pm_savedvalue;
1249 			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1250 		}
1251 
1252 		PMCDBG(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1253 
1254 		md->pmd_write_pmc(cpu, ri, newvalue);
1255 		md->pmd_start_pmc(cpu, ri);
1256 	}
1257 
1258 	/*
1259 	 * perform any other architecture/cpu dependent thread
1260 	 * switch-in actions.
1261 	 */
1262 
1263 	(void) (*md->pmd_switch_in)(pc, pp);
1264 
1265 	critical_exit();
1266 
1267 }
1268 
1269 /*
1270  * Thread context switch OUT.
1271  */
1272 
1273 static void
1274 pmc_process_csw_out(struct thread *td)
1275 {
1276 	int cpu;
1277 	enum pmc_mode mode;
1278 	unsigned int ri;
1279 	struct pmc *pm;
1280 	struct proc *p;
1281 	struct pmc_cpu *pc;
1282 	struct pmc_process *pp;
1283 	int64_t tmp;
1284 	pmc_value_t newvalue;
1285 
1286 	/*
1287 	 * Locate our process descriptor; this may be NULL if
1288 	 * this process is exiting and we have already removed
1289 	 * the process from the target process table.
1290 	 *
1291 	 * Note that due to kernel preemption, multiple
1292 	 * context switches may happen while the process is
1293 	 * exiting.
1294 	 *
1295 	 * Note also that if the target process cannot be
1296 	 * found we still need to deconfigure any PMCs that
1297 	 * are currently running on hardware.
1298 	 */
1299 
1300 	p = td->td_proc;
1301 	pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1302 
1303 	/*
1304 	 * save PMCs
1305 	 */
1306 
1307 	critical_enter();
1308 
1309 	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1310 
1311 	PMCDBG(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1312 	    p->p_pid, p->p_comm, pp);
1313 
1314 	KASSERT(cpu >= 0 && cpu < mp_ncpus,
1315 	    ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1316 
1317 	pc = pmc_pcpu[cpu];
1318 
1319 	/*
1320 	 * When a PMC gets unlinked from a target PMC, it will
1321 	 * be removed from the target's pp_pmc[] array.
1322 	 *
1323 	 * However, on a MP system, the target could have been
1324 	 * executing on another CPU at the time of the unlink.
1325 	 * So, at context switch OUT time, we need to look at
1326 	 * the hardware to determine if a PMC is scheduled on
1327 	 * it.
1328 	 */
1329 
1330 	for (ri = 0; ri < md->pmd_npmc; ri++) {
1331 
1332 		pm = NULL;
1333 		(void) (*md->pmd_get_config)(cpu, ri, &pm);
1334 
1335 		if (pm == NULL)	/* nothing at this row index */
1336 			continue;
1337 
1338 		mode = PMC_TO_MODE(pm);
1339 		if (!PMC_IS_VIRTUAL_MODE(mode))
1340 			continue; /* not a process virtual PMC */
1341 
1342 		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1343 		    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1344 			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1345 
1346 		/* Stop hardware if not already stopped */
1347 		if (pm->pm_stalled == 0)
1348 			md->pmd_stop_pmc(cpu, ri);
1349 
1350 		/* reduce this PMC's runcount */
1351 		atomic_subtract_rel_32(&pm->pm_runcount, 1);
1352 
1353 		/*
1354 		 * If this PMC is associated with this process,
1355 		 * save the reading.
1356 		 */
1357 
1358 		if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1359 
1360 			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1361 			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1362 				pm, ri, pp->pp_pmcs[ri].pp_pmc));
1363 
1364 			KASSERT(pp->pp_refcnt > 0,
1365 			    ("[pmc,%d] pp refcnt = %d", __LINE__,
1366 				pp->pp_refcnt));
1367 
1368 			md->pmd_read_pmc(cpu, ri, &newvalue);
1369 
1370 			tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1371 
1372 			PMCDBG(CSW,SWI,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
1373 			    tmp);
1374 
1375 			if (mode == PMC_MODE_TS) {
1376 
1377 				/*
1378 				 * For sampling process-virtual PMCs,
1379 				 * we expect the count to be
1380 				 * decreasing as the 'value'
1381 				 * programmed into the PMC is the
1382 				 * number of events to be seen till
1383 				 * the next sampling interrupt.
1384 				 */
1385 				if (tmp < 0)
1386 					tmp += pm->pm_sc.pm_reloadcount;
1387 				mtx_pool_lock_spin(pmc_mtxpool, pm);
1388 				pp->pp_pmcs[ri].pp_pmcval -= tmp;
1389 				if ((int64_t) pp->pp_pmcs[ri].pp_pmcval < 0)
1390 					pp->pp_pmcs[ri].pp_pmcval +=
1391 					    pm->pm_sc.pm_reloadcount;
1392 				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1393 
1394 			} else {
1395 
1396 				/*
1397 				 * For counting process-virtual PMCs,
1398 				 * we expect the count to be
1399 				 * increasing monotonically, modulo a 64
1400 				 * bit wraparound.
1401 				 */
1402 				KASSERT((int64_t) tmp >= 0,
1403 				    ("[pmc,%d] negative increment cpu=%d "
1404 				     "ri=%d newvalue=%jx saved=%jx "
1405 				     "incr=%jx", __LINE__, cpu, ri,
1406 				     newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1407 
1408 				mtx_pool_lock_spin(pmc_mtxpool, pm);
1409 				pm->pm_gv.pm_savedvalue += tmp;
1410 				pp->pp_pmcs[ri].pp_pmcval += tmp;
1411 				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1412 
1413 				if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1414 					pmclog_process_proccsw(pm, pp, tmp);
1415 			}
1416 		}
1417 
1418 		/* mark hardware as free */
1419 		md->pmd_config_pmc(cpu, ri, NULL);
1420 	}
1421 
1422 	/*
1423 	 * perform any other architecture/cpu dependent thread
1424 	 * switch out functions.
1425 	 */
1426 
1427 	(void) (*md->pmd_switch_out)(pc, pp);
1428 
1429 	critical_exit();
1430 }
1431 
1432 /*
1433  * Log a KLD operation.
1434  */
1435 
1436 static void
1437 pmc_process_kld_load(struct pmckern_map_in *pkm)
1438 {
1439 	struct pmc_owner *po;
1440 
1441 	sx_assert(&pmc_sx, SX_LOCKED);
1442 
1443 	/*
1444 	 * Notify owners of system sampling PMCs about KLD operations.
1445 	 */
1446 
1447 	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1448 	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1449 	    	pmclog_process_map_in(po, (pid_t) -1, pkm->pm_address,
1450 		    (char *) pkm->pm_file);
1451 
1452 	/*
1453 	 * TODO: Notify owners of (all) process-sampling PMCs too.
1454 	 */
1455 
1456 	return;
1457 }
1458 
1459 static void
1460 pmc_process_kld_unload(struct pmckern_map_out *pkm)
1461 {
1462 	struct pmc_owner *po;
1463 
1464 	sx_assert(&pmc_sx, SX_LOCKED);
1465 
1466 	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1467 	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1468 		pmclog_process_map_out(po, (pid_t) -1,
1469 		    pkm->pm_address, pkm->pm_address + pkm->pm_size);
1470 
1471 	/*
1472 	 * TODO: Notify owners of process-sampling PMCs.
1473 	 */
1474 }
1475 
1476 /*
1477  * A mapping change for a process.
1478  */
1479 
1480 static void
1481 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1482 {
1483 	int ri;
1484 	pid_t pid;
1485 	char *fullpath, *freepath;
1486 	const struct pmc *pm;
1487 	struct pmc_owner *po;
1488 	const struct pmc_process *pp;
1489 
1490 	freepath = fullpath = NULL;
1491 	pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1492 
1493 	pid = td->td_proc->p_pid;
1494 
1495 	/* Inform owners of all system-wide sampling PMCs. */
1496 	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1497 	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1498 		pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1499 
1500 	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1501 		goto done;
1502 
1503 	/*
1504 	 * Inform sampling PMC owners tracking this process.
1505 	 */
1506 	for (ri = 0; ri < md->pmd_npmc; ri++)
1507 		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1508 		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1509 			pmclog_process_map_in(pm->pm_owner,
1510 			    pid, pkm->pm_address, fullpath);
1511 
1512   done:
1513 	if (freepath)
1514 		FREE(freepath, M_TEMP);
1515 }
1516 
1517 
1518 /*
1519  * Log an munmap request.
1520  */
1521 
1522 static void
1523 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1524 {
1525 	int ri;
1526 	pid_t pid;
1527 	struct pmc_owner *po;
1528 	const struct pmc *pm;
1529 	const struct pmc_process *pp;
1530 
1531 	pid = td->td_proc->p_pid;
1532 
1533 	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1534 	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1535 		pmclog_process_map_out(po, pid, pkm->pm_address,
1536 		    pkm->pm_address + pkm->pm_size);
1537 
1538 	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1539 		return;
1540 
1541 	for (ri = 0; ri < md->pmd_npmc; ri++)
1542 		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1543 		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1544 			pmclog_process_map_out(pm->pm_owner, pid,
1545 			    pkm->pm_address, pkm->pm_address + pkm->pm_size);
1546 }
1547 
1548 /*
1549  * Log mapping information about the kernel.
1550  */
1551 
1552 static void
1553 pmc_log_kernel_mappings(struct pmc *pm)
1554 {
1555 	struct pmc_owner *po;
1556 	struct pmckern_map_in *km, *kmbase;
1557 
1558 	sx_assert(&pmc_sx, SX_LOCKED);
1559 	KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1560 	    ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1561 		__LINE__, (void *) pm));
1562 
1563 	po = pm->pm_owner;
1564 
1565 	if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1566 		return;
1567 
1568 	/*
1569 	 * Log the current set of kernel modules.
1570 	 */
1571 	kmbase = linker_hwpmc_list_objects();
1572 	for (km = kmbase; km->pm_file != NULL; km++) {
1573 		PMCDBG(LOG,REG,1,"%s %p", (char *) km->pm_file,
1574 		    (void *) km->pm_address);
1575 		pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1576 		    km->pm_file);
1577 	}
1578 	FREE(kmbase, M_LINKER);
1579 
1580 	po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1581 }
1582 
1583 /*
1584  * Log the mappings for a single process.
1585  */
1586 
1587 static void
1588 pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1589 {
1590 }
1591 
1592 /*
1593  * Log mappings for all processes in the system.
1594  */
1595 
1596 static void
1597 pmc_log_all_process_mappings(struct pmc_owner *po)
1598 {
1599 	struct proc *p, *top;
1600 
1601 	sx_assert(&pmc_sx, SX_XLOCKED);
1602 
1603 	if ((p = pfind(1)) == NULL)
1604 		panic("[pmc,%d] Cannot find init", __LINE__);
1605 
1606 	PROC_UNLOCK(p);
1607 
1608 	sx_slock(&proctree_lock);
1609 
1610 	top = p;
1611 
1612 	for (;;) {
1613 		pmc_log_process_mappings(po, p);
1614 		if (!LIST_EMPTY(&p->p_children))
1615 			p = LIST_FIRST(&p->p_children);
1616 		else for (;;) {
1617 			if (p == top)
1618 				goto done;
1619 			if (LIST_NEXT(p, p_sibling)) {
1620 				p = LIST_NEXT(p, p_sibling);
1621 				break;
1622 			}
1623 			p = p->p_pptr;
1624 		}
1625 	}
1626  done:
1627 	sx_sunlock(&proctree_lock);
1628 }
1629 
1630 /*
1631  * The 'hook' invoked from the kernel proper
1632  */
1633 
1634 
1635 #ifdef	DEBUG
1636 const char *pmc_hooknames[] = {
1637 	/* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1638 	"",
1639 	"EXEC",
1640 	"CSW-IN",
1641 	"CSW-OUT",
1642 	"SAMPLE",
1643 	"KLDLOAD",
1644 	"KLDUNLOAD",
1645 	"MMAP",
1646 	"MUNMAP",
1647 	"CALLCHAIN"
1648 };
1649 #endif
1650 
1651 static int
1652 pmc_hook_handler(struct thread *td, int function, void *arg)
1653 {
1654 
1655 	PMCDBG(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1656 	    pmc_hooknames[function], arg);
1657 
1658 	switch (function)
1659 	{
1660 
1661 	/*
1662 	 * Process exec()
1663 	 */
1664 
1665 	case PMC_FN_PROCESS_EXEC:
1666 	{
1667 		char *fullpath, *freepath;
1668 		unsigned int ri;
1669 		int is_using_hwpmcs;
1670 		struct pmc *pm;
1671 		struct proc *p;
1672 		struct pmc_owner *po;
1673 		struct pmc_process *pp;
1674 		struct pmckern_procexec *pk;
1675 
1676 		sx_assert(&pmc_sx, SX_XLOCKED);
1677 
1678 		p = td->td_proc;
1679 		pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1680 
1681 		pk = (struct pmckern_procexec *) arg;
1682 
1683 		/* Inform owners of SS mode PMCs of the exec event. */
1684 		LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1685 		    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1686 			    pmclog_process_procexec(po, PMC_ID_INVALID,
1687 				p->p_pid, pk->pm_entryaddr, fullpath);
1688 
1689 		PROC_LOCK(p);
1690 		is_using_hwpmcs = p->p_flag & P_HWPMC;
1691 		PROC_UNLOCK(p);
1692 
1693 		if (!is_using_hwpmcs) {
1694 			if (freepath)
1695 				FREE(freepath, M_TEMP);
1696 			break;
1697 		}
1698 
1699 		/*
1700 		 * PMCs are not inherited across an exec():  remove any
1701 		 * PMCs that this process is the owner of.
1702 		 */
1703 
1704 		if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1705 			pmc_remove_owner(po);
1706 			pmc_destroy_owner_descriptor(po);
1707 		}
1708 
1709 		/*
1710 		 * If the process being exec'ed is not the target of any
1711 		 * PMC, we are done.
1712 		 */
1713 		if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1714 			if (freepath)
1715 				FREE(freepath, M_TEMP);
1716 			break;
1717 		}
1718 
1719 		/*
1720 		 * Log the exec event to all monitoring owners.  Skip
1721 		 * owners who have already recieved the event because
1722 		 * they had system sampling PMCs active.
1723 		 */
1724 		for (ri = 0; ri < md->pmd_npmc; ri++)
1725 			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1726 				po = pm->pm_owner;
1727 				if (po->po_sscount == 0 &&
1728 				    po->po_flags & PMC_PO_OWNS_LOGFILE)
1729 					pmclog_process_procexec(po, pm->pm_id,
1730 					    p->p_pid, pk->pm_entryaddr,
1731 					    fullpath);
1732 			}
1733 
1734 		if (freepath)
1735 			FREE(freepath, M_TEMP);
1736 
1737 
1738 		PMCDBG(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1739 		    p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1740 
1741 		if (pk->pm_credentialschanged == 0) /* no change */
1742 			break;
1743 
1744 		/*
1745 		 * If the newly exec()'ed process has a different credential
1746 		 * than before, allow it to be the target of a PMC only if
1747 		 * the PMC's owner has sufficient priviledge.
1748 		 */
1749 
1750 		for (ri = 0; ri < md->pmd_npmc; ri++)
1751 			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1752 				if (pmc_can_attach(pm, td->td_proc) != 0)
1753 					pmc_detach_one_process(td->td_proc,
1754 					    pm, PMC_FLAG_NONE);
1755 
1756 		KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1757 		    ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1758 			pp->pp_refcnt, pp));
1759 
1760 		/*
1761 		 * If this process is no longer the target of any
1762 		 * PMCs, we can remove the process entry and free
1763 		 * up space.
1764 		 */
1765 
1766 		if (pp->pp_refcnt == 0) {
1767 			pmc_remove_process_descriptor(pp);
1768 			FREE(pp, M_PMC);
1769 			break;
1770 		}
1771 
1772 	}
1773 	break;
1774 
1775 	case PMC_FN_CSW_IN:
1776 		pmc_process_csw_in(td);
1777 		break;
1778 
1779 	case PMC_FN_CSW_OUT:
1780 		pmc_process_csw_out(td);
1781 		break;
1782 
1783 	/*
1784 	 * Process accumulated PC samples.
1785 	 *
1786 	 * This function is expected to be called by hardclock() for
1787 	 * each CPU that has accumulated PC samples.
1788 	 *
1789 	 * This function is to be executed on the CPU whose samples
1790 	 * are being processed.
1791 	 */
1792 	case PMC_FN_DO_SAMPLES:
1793 
1794 		/*
1795 		 * Clear the cpu specific bit in the CPU mask before
1796 		 * do the rest of the processing.  If the NMI handler
1797 		 * gets invoked after the "atomic_clear_int()" call
1798 		 * below but before "pmc_process_samples()" gets
1799 		 * around to processing the interrupt, then we will
1800 		 * come back here at the next hardclock() tick (and
1801 		 * may find nothing to do if "pmc_process_samples()"
1802 		 * had already processed the interrupt).  We don't
1803 		 * lose the interrupt sample.
1804 		 */
1805 		atomic_clear_int(&pmc_cpumask, (1 << PCPU_GET(cpuid)));
1806 		pmc_process_samples(PCPU_GET(cpuid));
1807 		break;
1808 
1809 
1810 	case PMC_FN_KLD_LOAD:
1811 		sx_assert(&pmc_sx, SX_LOCKED);
1812 		pmc_process_kld_load((struct pmckern_map_in *) arg);
1813 		break;
1814 
1815 	case PMC_FN_KLD_UNLOAD:
1816 		sx_assert(&pmc_sx, SX_LOCKED);
1817 		pmc_process_kld_unload((struct pmckern_map_out *) arg);
1818 		break;
1819 
1820 	case PMC_FN_MMAP:
1821 		sx_assert(&pmc_sx, SX_LOCKED);
1822 		pmc_process_mmap(td, (struct pmckern_map_in *) arg);
1823 		break;
1824 
1825 	case PMC_FN_MUNMAP:
1826 		sx_assert(&pmc_sx, SX_LOCKED);
1827 		pmc_process_munmap(td, (struct pmckern_map_out *) arg);
1828 		break;
1829 
1830 	case PMC_FN_USER_CALLCHAIN:
1831 		/*
1832 		 * Record a call chain.
1833 		 */
1834 		pmc_capture_user_callchain(PCPU_GET(cpuid),
1835 		    (struct trapframe *) arg);
1836 		break;
1837 
1838 	default:
1839 #ifdef	DEBUG
1840 		KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
1841 #endif
1842 		break;
1843 
1844 	}
1845 
1846 	return 0;
1847 }
1848 
1849 /*
1850  * allocate a 'struct pmc_owner' descriptor in the owner hash table.
1851  */
1852 
1853 static struct pmc_owner *
1854 pmc_allocate_owner_descriptor(struct proc *p)
1855 {
1856 	uint32_t hindex;
1857 	struct pmc_owner *po;
1858 	struct pmc_ownerhash *poh;
1859 
1860 	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1861 	poh = &pmc_ownerhash[hindex];
1862 
1863 	/* allocate space for N pointers and one descriptor struct */
1864 	MALLOC(po, struct pmc_owner *, sizeof(struct pmc_owner),
1865 	    M_PMC, M_ZERO|M_WAITOK);
1866 
1867 	po->po_sscount = po->po_error = po->po_flags = 0;
1868 	po->po_file  = NULL;
1869 	po->po_owner = p;
1870 	po->po_kthread = NULL;
1871 	LIST_INIT(&po->po_pmcs);
1872 	LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
1873 
1874 	TAILQ_INIT(&po->po_logbuffers);
1875 	mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
1876 
1877 	PMCDBG(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
1878 	    p, p->p_pid, p->p_comm, po);
1879 
1880 	return po;
1881 }
1882 
1883 static void
1884 pmc_destroy_owner_descriptor(struct pmc_owner *po)
1885 {
1886 
1887 	PMCDBG(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
1888 	    po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
1889 
1890 	mtx_destroy(&po->po_mtx);
1891 	FREE(po, M_PMC);
1892 }
1893 
1894 /*
1895  * find the descriptor corresponding to process 'p', adding or removing it
1896  * as specified by 'mode'.
1897  */
1898 
1899 static struct pmc_process *
1900 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
1901 {
1902 	uint32_t hindex;
1903 	struct pmc_process *pp, *ppnew;
1904 	struct pmc_processhash *pph;
1905 
1906 	hindex = PMC_HASH_PTR(p, pmc_processhashmask);
1907 	pph = &pmc_processhash[hindex];
1908 
1909 	ppnew = NULL;
1910 
1911 	/*
1912 	 * Pre-allocate memory in the FIND_ALLOCATE case since we
1913 	 * cannot call malloc(9) once we hold a spin lock.
1914 	 */
1915 
1916 	if (mode & PMC_FLAG_ALLOCATE) {
1917 		/* allocate additional space for 'n' pmc pointers */
1918 		MALLOC(ppnew, struct pmc_process *,
1919 		    sizeof(struct pmc_process) + md->pmd_npmc *
1920 		    sizeof(struct pmc_targetstate), M_PMC, M_ZERO|M_WAITOK);
1921 	}
1922 
1923 	mtx_lock_spin(&pmc_processhash_mtx);
1924 	LIST_FOREACH(pp, pph, pp_next)
1925 	    if (pp->pp_proc == p)
1926 		    break;
1927 
1928 	if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
1929 		LIST_REMOVE(pp, pp_next);
1930 
1931 	if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
1932 	    ppnew != NULL) {
1933 		ppnew->pp_proc = p;
1934 		LIST_INSERT_HEAD(pph, ppnew, pp_next);
1935 		pp = ppnew;
1936 		ppnew = NULL;
1937 	}
1938 	mtx_unlock_spin(&pmc_processhash_mtx);
1939 
1940 	if (pp != NULL && ppnew != NULL)
1941 		FREE(ppnew, M_PMC);
1942 
1943 	return pp;
1944 }
1945 
1946 /*
1947  * remove a process descriptor from the process hash table.
1948  */
1949 
1950 static void
1951 pmc_remove_process_descriptor(struct pmc_process *pp)
1952 {
1953 	KASSERT(pp->pp_refcnt == 0,
1954 	    ("[pmc,%d] Removing process descriptor %p with count %d",
1955 		__LINE__, pp, pp->pp_refcnt));
1956 
1957 	mtx_lock_spin(&pmc_processhash_mtx);
1958 	LIST_REMOVE(pp, pp_next);
1959 	mtx_unlock_spin(&pmc_processhash_mtx);
1960 }
1961 
1962 
1963 /*
1964  * find an owner descriptor corresponding to proc 'p'
1965  */
1966 
1967 static struct pmc_owner *
1968 pmc_find_owner_descriptor(struct proc *p)
1969 {
1970 	uint32_t hindex;
1971 	struct pmc_owner *po;
1972 	struct pmc_ownerhash *poh;
1973 
1974 	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1975 	poh = &pmc_ownerhash[hindex];
1976 
1977 	po = NULL;
1978 	LIST_FOREACH(po, poh, po_next)
1979 	    if (po->po_owner == p)
1980 		    break;
1981 
1982 	PMCDBG(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
1983 	    "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
1984 
1985 	return po;
1986 }
1987 
1988 /*
1989  * pmc_allocate_pmc_descriptor
1990  *
1991  * Allocate a pmc descriptor and initialize its
1992  * fields.
1993  */
1994 
1995 static struct pmc *
1996 pmc_allocate_pmc_descriptor(void)
1997 {
1998 	struct pmc *pmc;
1999 
2000 	MALLOC(pmc, struct pmc *, sizeof(struct pmc), M_PMC, M_ZERO|M_WAITOK);
2001 
2002 	if (pmc != NULL) {
2003 		pmc->pm_owner = NULL;
2004 		LIST_INIT(&pmc->pm_targets);
2005 	}
2006 
2007 	PMCDBG(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2008 
2009 	return pmc;
2010 }
2011 
2012 /*
2013  * Destroy a pmc descriptor.
2014  */
2015 
2016 static void
2017 pmc_destroy_pmc_descriptor(struct pmc *pm)
2018 {
2019 	(void) pm;
2020 
2021 #ifdef	DEBUG
2022 	KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2023 	    pm->pm_state == PMC_STATE_FREE,
2024 	    ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2025 	KASSERT(LIST_EMPTY(&pm->pm_targets),
2026 	    ("[pmc,%d] destroying pmc with targets", __LINE__));
2027 	KASSERT(pm->pm_owner == NULL,
2028 	    ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2029 	KASSERT(pm->pm_runcount == 0,
2030 	    ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
2031 		pm->pm_runcount));
2032 #endif
2033 }
2034 
2035 static void
2036 pmc_wait_for_pmc_idle(struct pmc *pm)
2037 {
2038 #ifdef	DEBUG
2039 	volatile int maxloop;
2040 
2041 	maxloop = 100 * mp_ncpus;
2042 #endif
2043 
2044 	/*
2045 	 * Loop (with a forced context switch) till the PMC's runcount
2046 	 * comes down to zero.
2047 	 */
2048 	while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
2049 #ifdef	DEBUG
2050 		maxloop--;
2051 		KASSERT(maxloop > 0,
2052 		    ("[pmc,%d] (ri%d, rc%d) waiting too long for "
2053 			"pmc to be free", __LINE__,
2054 			PMC_TO_ROWINDEX(pm), pm->pm_runcount));
2055 #endif
2056 		pmc_force_context_switch();
2057 	}
2058 }
2059 
2060 /*
2061  * This function does the following things:
2062  *
2063  *  - detaches the PMC from hardware
2064  *  - unlinks all target threads that were attached to it
2065  *  - removes the PMC from its owner's list
2066  *  - destroy's the PMC private mutex
2067  *
2068  * Once this function completes, the given pmc pointer can be safely
2069  * FREE'd by the caller.
2070  */
2071 
2072 static void
2073 pmc_release_pmc_descriptor(struct pmc *pm)
2074 {
2075 	u_int ri, cpu;
2076 	enum pmc_mode mode;
2077 	struct pmc_hw *phw;
2078 	struct pmc_owner *po;
2079 	struct pmc_process *pp;
2080 	struct pmc_target *ptgt, *tmp;
2081 	struct pmc_binding pb;
2082 
2083 	sx_assert(&pmc_sx, SX_XLOCKED);
2084 
2085 	KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2086 
2087 	ri   = PMC_TO_ROWINDEX(pm);
2088 	mode = PMC_TO_MODE(pm);
2089 
2090 	PMCDBG(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2091 	    mode);
2092 
2093 	/*
2094 	 * First, we take the PMC off hardware.
2095 	 */
2096 	cpu = 0;
2097 	if (PMC_IS_SYSTEM_MODE(mode)) {
2098 
2099 		/*
2100 		 * A system mode PMC runs on a specific CPU.  Switch
2101 		 * to this CPU and turn hardware off.
2102 		 */
2103 		pmc_save_cpu_binding(&pb);
2104 
2105 		cpu = PMC_TO_CPU(pm);
2106 
2107 		pmc_select_cpu(cpu);
2108 
2109 		/* switch off non-stalled CPUs */
2110 		if (pm->pm_state == PMC_STATE_RUNNING &&
2111 		    pm->pm_stalled == 0) {
2112 
2113 			phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2114 
2115 			KASSERT(phw->phw_pmc == pm,
2116 			    ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2117 				__LINE__, ri, phw->phw_pmc, pm));
2118 			PMCDBG(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2119 
2120 			critical_enter();
2121 			md->pmd_stop_pmc(cpu, ri);
2122 			critical_exit();
2123 		}
2124 
2125 		PMCDBG(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2126 
2127 		critical_enter();
2128 		md->pmd_config_pmc(cpu, ri, NULL);
2129 		critical_exit();
2130 
2131 		/* adjust the global and process count of SS mode PMCs */
2132 		if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2133 			po = pm->pm_owner;
2134 			po->po_sscount--;
2135 			if (po->po_sscount == 0) {
2136 				atomic_subtract_rel_int(&pmc_ss_count, 1);
2137 				LIST_REMOVE(po, po_ssnext);
2138 			}
2139 		}
2140 
2141 		pm->pm_state = PMC_STATE_DELETED;
2142 
2143 		pmc_restore_cpu_binding(&pb);
2144 
2145 		/*
2146 		 * We could have references to this PMC structure in
2147 		 * the per-cpu sample queues.  Wait for the queue to
2148 		 * drain.
2149 		 */
2150 		pmc_wait_for_pmc_idle(pm);
2151 
2152 	} else if (PMC_IS_VIRTUAL_MODE(mode)) {
2153 
2154 		/*
2155 		 * A virtual PMC could be running on multiple CPUs at
2156 		 * a given instant.
2157 		 *
2158 		 * By marking its state as DELETED, we ensure that
2159 		 * this PMC is never further scheduled on hardware.
2160 		 *
2161 		 * Then we wait till all CPUs are done with this PMC.
2162 		 */
2163 		pm->pm_state = PMC_STATE_DELETED;
2164 
2165 
2166 		/* Wait for the PMCs runcount to come to zero. */
2167 		pmc_wait_for_pmc_idle(pm);
2168 
2169 		/*
2170 		 * At this point the PMC is off all CPUs and cannot be
2171 		 * freshly scheduled onto a CPU.  It is now safe to
2172 		 * unlink all targets from this PMC.  If a
2173 		 * process-record's refcount falls to zero, we remove
2174 		 * it from the hash table.  The module-wide SX lock
2175 		 * protects us from races.
2176 		 */
2177 		LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2178 			pp = ptgt->pt_process;
2179 			pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2180 
2181 			PMCDBG(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2182 
2183 			/*
2184 			 * If the target process record shows that no
2185 			 * PMCs are attached to it, reclaim its space.
2186 			 */
2187 
2188 			if (pp->pp_refcnt == 0) {
2189 				pmc_remove_process_descriptor(pp);
2190 				FREE(pp, M_PMC);
2191 			}
2192 		}
2193 
2194 		cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2195 
2196 	}
2197 
2198 	/*
2199 	 * Release any MD resources
2200 	 */
2201 
2202 	(void) md->pmd_release_pmc(cpu, ri, pm);
2203 
2204 	/*
2205 	 * Update row disposition
2206 	 */
2207 
2208 	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2209 		PMC_UNMARK_ROW_STANDALONE(ri);
2210 	else
2211 		PMC_UNMARK_ROW_THREAD(ri);
2212 
2213 	/* unlink from the owner's list */
2214 	if (pm->pm_owner) {
2215 		LIST_REMOVE(pm, pm_next);
2216 		pm->pm_owner = NULL;
2217 	}
2218 
2219 	pmc_destroy_pmc_descriptor(pm);
2220 }
2221 
2222 /*
2223  * Register an owner and a pmc.
2224  */
2225 
2226 static int
2227 pmc_register_owner(struct proc *p, struct pmc *pmc)
2228 {
2229 	struct pmc_owner *po;
2230 
2231 	sx_assert(&pmc_sx, SX_XLOCKED);
2232 
2233 	if ((po = pmc_find_owner_descriptor(p)) == NULL)
2234 		if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2235 			return ENOMEM;
2236 
2237 	KASSERT(pmc->pm_owner == NULL,
2238 	    ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2239 	pmc->pm_owner  = po;
2240 
2241 	LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2242 
2243 	PROC_LOCK(p);
2244 	p->p_flag |= P_HWPMC;
2245 	PROC_UNLOCK(p);
2246 
2247 	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2248 		pmclog_process_pmcallocate(pmc);
2249 
2250 	PMCDBG(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2251 	    po, pmc);
2252 
2253 	return 0;
2254 }
2255 
2256 /*
2257  * Return the current row disposition:
2258  * == 0 => FREE
2259  *  > 0 => PROCESS MODE
2260  *  < 0 => SYSTEM MODE
2261  */
2262 
2263 int
2264 pmc_getrowdisp(int ri)
2265 {
2266 	return pmc_pmcdisp[ri];
2267 }
2268 
2269 /*
2270  * Check if a PMC at row index 'ri' can be allocated to the current
2271  * process.
2272  *
2273  * Allocation can fail if:
2274  *   - the current process is already being profiled by a PMC at index 'ri',
2275  *     attached to it via OP_PMCATTACH.
2276  *   - the current process has already allocated a PMC at index 'ri'
2277  *     via OP_ALLOCATE.
2278  */
2279 
2280 static int
2281 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2282 {
2283 	enum pmc_mode mode;
2284 	struct pmc *pm;
2285 	struct pmc_owner *po;
2286 	struct pmc_process *pp;
2287 
2288 	PMCDBG(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2289 	    "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2290 
2291 	/*
2292 	 * We shouldn't have already allocated a process-mode PMC at
2293 	 * row index 'ri'.
2294 	 *
2295 	 * We shouldn't have allocated a system-wide PMC on the same
2296 	 * CPU and same RI.
2297 	 */
2298 	if ((po = pmc_find_owner_descriptor(p)) != NULL)
2299 		LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2300 		    if (PMC_TO_ROWINDEX(pm) == ri) {
2301 			    mode = PMC_TO_MODE(pm);
2302 			    if (PMC_IS_VIRTUAL_MODE(mode))
2303 				    return EEXIST;
2304 			    if (PMC_IS_SYSTEM_MODE(mode) &&
2305 				(int) PMC_TO_CPU(pm) == cpu)
2306 				    return EEXIST;
2307 		    }
2308 	        }
2309 
2310 	/*
2311 	 * We also shouldn't be the target of any PMC at this index
2312 	 * since otherwise a PMC_ATTACH to ourselves will fail.
2313 	 */
2314 	if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2315 		if (pp->pp_pmcs[ri].pp_pmc)
2316 			return EEXIST;
2317 
2318 	PMCDBG(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2319 	    p, p->p_pid, p->p_comm, ri);
2320 
2321 	return 0;
2322 }
2323 
2324 /*
2325  * Check if a given PMC at row index 'ri' can be currently used in
2326  * mode 'mode'.
2327  */
2328 
2329 static int
2330 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2331 {
2332 	enum pmc_disp	disp;
2333 
2334 	sx_assert(&pmc_sx, SX_XLOCKED);
2335 
2336 	PMCDBG(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2337 
2338 	if (PMC_IS_SYSTEM_MODE(mode))
2339 		disp = PMC_DISP_STANDALONE;
2340 	else
2341 		disp = PMC_DISP_THREAD;
2342 
2343 	/*
2344 	 * check disposition for PMC row 'ri':
2345 	 *
2346 	 * Expected disposition		Row-disposition		Result
2347 	 *
2348 	 * STANDALONE			STANDALONE or FREE	proceed
2349 	 * STANDALONE			THREAD			fail
2350 	 * THREAD			THREAD or FREE		proceed
2351 	 * THREAD			STANDALONE		fail
2352 	 */
2353 
2354 	if (!PMC_ROW_DISP_IS_FREE(ri) &&
2355 	    !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2356 	    !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2357 		return EBUSY;
2358 
2359 	/*
2360 	 * All OK
2361 	 */
2362 
2363 	PMCDBG(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2364 
2365 	return 0;
2366 
2367 }
2368 
2369 /*
2370  * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2371  */
2372 
2373 static struct pmc *
2374 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2375 {
2376 	struct pmc *pm;
2377 
2378 	KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2379 	    ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2380 		PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2381 
2382 	LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2383 	    if (pm->pm_id == pmcid)
2384 		    return pm;
2385 
2386 	return NULL;
2387 }
2388 
2389 static int
2390 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2391 {
2392 
2393 	struct pmc *pm;
2394 	struct pmc_owner *po;
2395 
2396 	PMCDBG(PMC,FND,1, "find-pmc id=%d", pmcid);
2397 
2398 	if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2399 		return ESRCH;
2400 
2401 	if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2402 		return EINVAL;
2403 
2404 	PMCDBG(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2405 
2406 	*pmc = pm;
2407 	return 0;
2408 }
2409 
2410 /*
2411  * Start a PMC.
2412  */
2413 
2414 static int
2415 pmc_start(struct pmc *pm)
2416 {
2417 	int error, cpu, ri;
2418 	enum pmc_mode mode;
2419 	struct pmc_owner *po;
2420 	struct pmc_binding pb;
2421 
2422 	KASSERT(pm != NULL,
2423 	    ("[pmc,%d] null pm", __LINE__));
2424 
2425 	mode = PMC_TO_MODE(pm);
2426 	ri   = PMC_TO_ROWINDEX(pm);
2427 	error = 0;
2428 
2429 	PMCDBG(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2430 
2431 	po = pm->pm_owner;
2432 
2433 	/*
2434 	 * Disallow PMCSTART if a logfile is required but has not been
2435 	 * configured yet.
2436 	 */
2437 	if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2438 	    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2439 		return EDOOFUS;	/* programming error */
2440 
2441 	/*
2442 	 * If this is a sampling mode PMC, log mapping information for
2443 	 * the kernel modules that are currently loaded.
2444 	 */
2445 	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2446 	    pmc_log_kernel_mappings(pm);
2447 
2448 	if (PMC_IS_VIRTUAL_MODE(mode)) {
2449 
2450 		/*
2451 		 * If a PMCATTACH has never been done on this PMC,
2452 		 * attach it to its owner process.
2453 		 */
2454 
2455 		if (LIST_EMPTY(&pm->pm_targets))
2456 			error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2457 			    pmc_attach_process(po->po_owner, pm);
2458 
2459 		/*
2460 		 * If the PMC is attached to its owner, then force a context
2461 		 * switch to ensure that the MD state gets set correctly.
2462 		 */
2463 
2464 		if (error == 0) {
2465 			pm->pm_state = PMC_STATE_RUNNING;
2466 			if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2467 				pmc_force_context_switch();
2468 		}
2469 
2470 		return error;
2471 	}
2472 
2473 
2474 	/*
2475 	 * A system-wide PMC.
2476 	 *
2477 	 * Add the owner to the global list if this is a system-wide
2478 	 * sampling PMC.
2479 	 */
2480 
2481 	if (mode == PMC_MODE_SS) {
2482 		if (po->po_sscount == 0) {
2483 			LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2484 			atomic_add_rel_int(&pmc_ss_count, 1);
2485 			PMCDBG(PMC,OPS,1, "po=%p in global list", po);
2486 		}
2487 		po->po_sscount++;
2488 	}
2489 
2490 	/* Log mapping information for all processes in the system. */
2491 	pmc_log_all_process_mappings(po);
2492 
2493 	/*
2494 	 * Move to the CPU associated with this
2495 	 * PMC, and start the hardware.
2496 	 */
2497 
2498 	pmc_save_cpu_binding(&pb);
2499 
2500 	cpu = PMC_TO_CPU(pm);
2501 
2502 	if (pmc_cpu_is_disabled(cpu))
2503 		return ENXIO;
2504 
2505 	pmc_select_cpu(cpu);
2506 
2507 	/*
2508 	 * global PMCs are configured at allocation time
2509 	 * so write out the initial value and start the PMC.
2510 	 */
2511 
2512 	pm->pm_state = PMC_STATE_RUNNING;
2513 
2514 	critical_enter();
2515 	if ((error = md->pmd_write_pmc(cpu, ri,
2516 		 PMC_IS_SAMPLING_MODE(mode) ?
2517 		 pm->pm_sc.pm_reloadcount :
2518 		 pm->pm_sc.pm_initial)) == 0)
2519 		error = md->pmd_start_pmc(cpu, ri);
2520 	critical_exit();
2521 
2522 	pmc_restore_cpu_binding(&pb);
2523 
2524 	return error;
2525 }
2526 
2527 /*
2528  * Stop a PMC.
2529  */
2530 
2531 static int
2532 pmc_stop(struct pmc *pm)
2533 {
2534 	int cpu, error, ri;
2535 	struct pmc_owner *po;
2536 	struct pmc_binding pb;
2537 
2538 	KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2539 
2540 	PMCDBG(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2541 	    PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2542 
2543 	pm->pm_state = PMC_STATE_STOPPED;
2544 
2545 	/*
2546 	 * If the PMC is a virtual mode one, changing the state to
2547 	 * non-RUNNING is enough to ensure that the PMC never gets
2548 	 * scheduled.
2549 	 *
2550 	 * If this PMC is current running on a CPU, then it will
2551 	 * handled correctly at the time its target process is context
2552 	 * switched out.
2553 	 */
2554 
2555 	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2556 		return 0;
2557 
2558 	/*
2559 	 * A system-mode PMC.  Move to the CPU associated with
2560 	 * this PMC, and stop the hardware.  We update the
2561 	 * 'initial count' so that a subsequent PMCSTART will
2562 	 * resume counting from the current hardware count.
2563 	 */
2564 
2565 	pmc_save_cpu_binding(&pb);
2566 
2567 	cpu = PMC_TO_CPU(pm);
2568 
2569 	KASSERT(cpu >= 0 && cpu < mp_ncpus,
2570 	    ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2571 
2572 	if (pmc_cpu_is_disabled(cpu))
2573 		return ENXIO;
2574 
2575 	pmc_select_cpu(cpu);
2576 
2577 	ri = PMC_TO_ROWINDEX(pm);
2578 
2579 	critical_enter();
2580 	if ((error = md->pmd_stop_pmc(cpu, ri)) == 0)
2581 		error = md->pmd_read_pmc(cpu, ri, &pm->pm_sc.pm_initial);
2582 	critical_exit();
2583 
2584 	pmc_restore_cpu_binding(&pb);
2585 
2586 	po = pm->pm_owner;
2587 
2588 	/* remove this owner from the global list of SS PMC owners */
2589 	if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2590 		po->po_sscount--;
2591 		if (po->po_sscount == 0) {
2592 			atomic_subtract_rel_int(&pmc_ss_count, 1);
2593 			LIST_REMOVE(po, po_ssnext);
2594 			PMCDBG(PMC,OPS,2,"po=%p removed from global list", po);
2595 		}
2596 	}
2597 
2598 	return error;
2599 }
2600 
2601 
2602 #ifdef	DEBUG
2603 static const char *pmc_op_to_name[] = {
2604 #undef	__PMC_OP
2605 #define	__PMC_OP(N, D)	#N ,
2606 	__PMC_OPS()
2607 	NULL
2608 };
2609 #endif
2610 
2611 /*
2612  * The syscall interface
2613  */
2614 
2615 #define	PMC_GET_SX_XLOCK(...) do {		\
2616 	sx_xlock(&pmc_sx);			\
2617 	if (pmc_hook == NULL) {			\
2618 		sx_xunlock(&pmc_sx);		\
2619 		return __VA_ARGS__;		\
2620 	}					\
2621 } while (0)
2622 
2623 #define	PMC_DOWNGRADE_SX() do {			\
2624 	sx_downgrade(&pmc_sx);			\
2625 	is_sx_downgraded = 1;			\
2626 } while (0)
2627 
2628 static int
2629 pmc_syscall_handler(struct thread *td, void *syscall_args)
2630 {
2631 	int error, is_sx_downgraded, op;
2632 	struct pmc_syscall_args *c;
2633 	void *arg;
2634 
2635 	PMC_GET_SX_XLOCK(ENOSYS);
2636 
2637 	DROP_GIANT();
2638 
2639 	is_sx_downgraded = 0;
2640 
2641 	c = (struct pmc_syscall_args *) syscall_args;
2642 
2643 	op = c->pmop_code;
2644 	arg = c->pmop_data;
2645 
2646 	PMCDBG(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2647 	    pmc_op_to_name[op], arg);
2648 
2649 	error = 0;
2650 	atomic_add_int(&pmc_stats.pm_syscalls, 1);
2651 
2652 	switch(op)
2653 	{
2654 
2655 
2656 	/*
2657 	 * Configure a log file.
2658 	 *
2659 	 * XXX This OP will be reworked.
2660 	 */
2661 
2662 	case PMC_OP_CONFIGURELOG:
2663 	{
2664 		struct proc *p;
2665 		struct pmc *pm;
2666 		struct pmc_owner *po;
2667 		struct pmc_op_configurelog cl;
2668 
2669 		sx_assert(&pmc_sx, SX_XLOCKED);
2670 
2671 		if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2672 			break;
2673 
2674 		/* mark this process as owning a log file */
2675 		p = td->td_proc;
2676 		if ((po = pmc_find_owner_descriptor(p)) == NULL)
2677 			if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2678 				error = ENOMEM;
2679 				break;
2680 			}
2681 
2682 		/*
2683 		 * If a valid fd was passed in, try to configure that,
2684 		 * otherwise if 'fd' was less than zero and there was
2685 		 * a log file configured, flush its buffers and
2686 		 * de-configure it.
2687 		 */
2688 		if (cl.pm_logfd >= 0)
2689 			error = pmclog_configure_log(po, cl.pm_logfd);
2690 		else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2691 			pmclog_process_closelog(po);
2692 			error = pmclog_flush(po);
2693 			if (error == 0) {
2694 				LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2695 				    if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2696 					pm->pm_state == PMC_STATE_RUNNING)
2697 					    pmc_stop(pm);
2698 				error = pmclog_deconfigure_log(po);
2699 			}
2700 		} else
2701 			error = EINVAL;
2702 
2703 		if (error)
2704 			break;
2705 	}
2706 	break;
2707 
2708 
2709 	/*
2710 	 * Flush a log file.
2711 	 */
2712 
2713 	case PMC_OP_FLUSHLOG:
2714 	{
2715 		struct pmc_owner *po;
2716 
2717 		sx_assert(&pmc_sx, SX_XLOCKED);
2718 
2719 		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2720 			error = EINVAL;
2721 			break;
2722 		}
2723 
2724 		error = pmclog_flush(po);
2725 	}
2726 	break;
2727 
2728 	/*
2729 	 * Retrieve hardware configuration.
2730 	 */
2731 
2732 	case PMC_OP_GETCPUINFO:	/* CPU information */
2733 	{
2734 		struct pmc_op_getcpuinfo gci;
2735 
2736 		gci.pm_cputype = md->pmd_cputype;
2737 		gci.pm_ncpu    = mp_ncpus;
2738 		gci.pm_npmc    = md->pmd_npmc;
2739 		gci.pm_nclass  = md->pmd_nclass;
2740 		bcopy(md->pmd_classes, &gci.pm_classes,
2741 		    sizeof(gci.pm_classes));
2742 		error = copyout(&gci, arg, sizeof(gci));
2743 	}
2744 	break;
2745 
2746 
2747 	/*
2748 	 * Get module statistics
2749 	 */
2750 
2751 	case PMC_OP_GETDRIVERSTATS:
2752 	{
2753 		struct pmc_op_getdriverstats gms;
2754 
2755 		bcopy(&pmc_stats, &gms, sizeof(gms));
2756 		error = copyout(&gms, arg, sizeof(gms));
2757 	}
2758 	break;
2759 
2760 
2761 	/*
2762 	 * Retrieve module version number
2763 	 */
2764 
2765 	case PMC_OP_GETMODULEVERSION:
2766 	{
2767 		uint32_t cv, modv;
2768 
2769 		/* retrieve the client's idea of the ABI version */
2770 		if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
2771 			break;
2772 		/* don't service clients newer than our driver */
2773 		modv = PMC_VERSION;
2774 		if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
2775 			error = EPROGMISMATCH;
2776 			break;
2777 		}
2778 		error = copyout(&modv, arg, sizeof(int));
2779 	}
2780 	break;
2781 
2782 
2783 	/*
2784 	 * Retrieve the state of all the PMCs on a given
2785 	 * CPU.
2786 	 */
2787 
2788 	case PMC_OP_GETPMCINFO:
2789 	{
2790 		uint32_t cpu, n, npmc;
2791 		size_t pmcinfo_size;
2792 		struct pmc *pm;
2793 		struct pmc_info *p, *pmcinfo;
2794 		struct pmc_op_getpmcinfo *gpi;
2795 		struct pmc_owner *po;
2796 		struct pmc_binding pb;
2797 
2798 		PMC_DOWNGRADE_SX();
2799 
2800 		gpi = (struct pmc_op_getpmcinfo *) arg;
2801 
2802 		if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
2803 			break;
2804 
2805 		if (cpu >= (unsigned int) mp_ncpus) {
2806 			error = EINVAL;
2807 			break;
2808 		}
2809 
2810 		if (pmc_cpu_is_disabled(cpu)) {
2811 			error = ENXIO;
2812 			break;
2813 		}
2814 
2815 		/* switch to CPU 'cpu' */
2816 		pmc_save_cpu_binding(&pb);
2817 		pmc_select_cpu(cpu);
2818 
2819 		npmc = md->pmd_npmc;
2820 
2821 		pmcinfo_size = npmc * sizeof(struct pmc_info);
2822 		MALLOC(pmcinfo, struct pmc_info *, pmcinfo_size, M_PMC,
2823 		    M_WAITOK);
2824 
2825 		p = pmcinfo;
2826 
2827 		for (n = 0; n < md->pmd_npmc; n++, p++) {
2828 
2829 			if ((error = md->pmd_describe(cpu, n, p, &pm)) != 0)
2830 				break;
2831 
2832 			if (PMC_ROW_DISP_IS_STANDALONE(n))
2833 				p->pm_rowdisp = PMC_DISP_STANDALONE;
2834 			else if (PMC_ROW_DISP_IS_THREAD(n))
2835 				p->pm_rowdisp = PMC_DISP_THREAD;
2836 			else
2837 				p->pm_rowdisp = PMC_DISP_FREE;
2838 
2839 			p->pm_ownerpid = -1;
2840 
2841 			if (pm == NULL)	/* no PMC associated */
2842 				continue;
2843 
2844 			po = pm->pm_owner;
2845 
2846 			KASSERT(po->po_owner != NULL,
2847 			    ("[pmc,%d] pmc_owner had a null proc pointer",
2848 				__LINE__));
2849 
2850 			p->pm_ownerpid = po->po_owner->p_pid;
2851 			p->pm_mode     = PMC_TO_MODE(pm);
2852 			p->pm_event    = pm->pm_event;
2853 			p->pm_flags    = pm->pm_flags;
2854 
2855 			if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2856 				p->pm_reloadcount =
2857 				    pm->pm_sc.pm_reloadcount;
2858 		}
2859 
2860 		pmc_restore_cpu_binding(&pb);
2861 
2862 		/* now copy out the PMC info collected */
2863 		if (error == 0)
2864 			error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
2865 
2866 		FREE(pmcinfo, M_PMC);
2867 	}
2868 	break;
2869 
2870 
2871 	/*
2872 	 * Set the administrative state of a PMC.  I.e. whether
2873 	 * the PMC is to be used or not.
2874 	 */
2875 
2876 	case PMC_OP_PMCADMIN:
2877 	{
2878 		int cpu, ri;
2879 		enum pmc_state request;
2880 		struct pmc_cpu *pc;
2881 		struct pmc_hw *phw;
2882 		struct pmc_op_pmcadmin pma;
2883 		struct pmc_binding pb;
2884 
2885 		sx_assert(&pmc_sx, SX_XLOCKED);
2886 
2887 		KASSERT(td == curthread,
2888 		    ("[pmc,%d] td != curthread", __LINE__));
2889 
2890 		error = priv_check(td, PRIV_PMC_MANAGE);
2891 		if (error)
2892 			break;
2893 
2894 		if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
2895 			break;
2896 
2897 		cpu = pma.pm_cpu;
2898 
2899 		if (cpu < 0 || cpu >= mp_ncpus) {
2900 			error = EINVAL;
2901 			break;
2902 		}
2903 
2904 		if (pmc_cpu_is_disabled(cpu)) {
2905 			error = ENXIO;
2906 			break;
2907 		}
2908 
2909 		request = pma.pm_state;
2910 
2911 		if (request != PMC_STATE_DISABLED &&
2912 		    request != PMC_STATE_FREE) {
2913 			error = EINVAL;
2914 			break;
2915 		}
2916 
2917 		ri = pma.pm_pmc; /* pmc id == row index */
2918 		if (ri < 0 || ri >= (int) md->pmd_npmc) {
2919 			error = EINVAL;
2920 			break;
2921 		}
2922 
2923 		/*
2924 		 * We can't disable a PMC with a row-index allocated
2925 		 * for process virtual PMCs.
2926 		 */
2927 
2928 		if (PMC_ROW_DISP_IS_THREAD(ri) &&
2929 		    request == PMC_STATE_DISABLED) {
2930 			error = EBUSY;
2931 			break;
2932 		}
2933 
2934 		/*
2935 		 * otherwise, this PMC on this CPU is either free or
2936 		 * in system-wide mode.
2937 		 */
2938 
2939 		pmc_save_cpu_binding(&pb);
2940 		pmc_select_cpu(cpu);
2941 
2942 		pc  = pmc_pcpu[cpu];
2943 		phw = pc->pc_hwpmcs[ri];
2944 
2945 		/*
2946 		 * XXX do we need some kind of 'forced' disable?
2947 		 */
2948 
2949 		if (phw->phw_pmc == NULL) {
2950 			if (request == PMC_STATE_DISABLED &&
2951 			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
2952 				phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
2953 				PMC_MARK_ROW_STANDALONE(ri);
2954 			} else if (request == PMC_STATE_FREE &&
2955 			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
2956 				phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
2957 				PMC_UNMARK_ROW_STANDALONE(ri);
2958 			}
2959 			/* other cases are a no-op */
2960 		} else
2961 			error = EBUSY;
2962 
2963 		pmc_restore_cpu_binding(&pb);
2964 	}
2965 	break;
2966 
2967 
2968 	/*
2969 	 * Allocate a PMC.
2970 	 */
2971 
2972 	case PMC_OP_PMCALLOCATE:
2973 	{
2974 		uint32_t caps;
2975 		u_int cpu;
2976 		int n;
2977 		enum pmc_mode mode;
2978 		struct pmc *pmc;
2979 		struct pmc_hw *phw;
2980 		struct pmc_op_pmcallocate pa;
2981 		struct pmc_binding pb;
2982 
2983 		if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
2984 			break;
2985 
2986 		caps = pa.pm_caps;
2987 		mode = pa.pm_mode;
2988 		cpu  = pa.pm_cpu;
2989 
2990 		if ((mode != PMC_MODE_SS  &&  mode != PMC_MODE_SC  &&
2991 		     mode != PMC_MODE_TS  &&  mode != PMC_MODE_TC) ||
2992 		    (cpu != (u_int) PMC_CPU_ANY && cpu >= (u_int) mp_ncpus)) {
2993 			error = EINVAL;
2994 			break;
2995 		}
2996 
2997 		/*
2998 		 * Virtual PMCs should only ask for a default CPU.
2999 		 * System mode PMCs need to specify a non-default CPU.
3000 		 */
3001 
3002 		if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3003 		    (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3004 			error = EINVAL;
3005 			break;
3006 		}
3007 
3008 		/*
3009 		 * Check that a disabled CPU is not being asked for.
3010 		 */
3011 
3012 		if (PMC_IS_SYSTEM_MODE(mode) && pmc_cpu_is_disabled(cpu)) {
3013 			error = ENXIO;
3014 			break;
3015 		}
3016 
3017 		/*
3018 		 * Refuse an allocation for a system-wide PMC if this
3019 		 * process has been jailed, or if this process lacks
3020 		 * super-user credentials and the sysctl tunable
3021 		 * 'security.bsd.unprivileged_syspmcs' is zero.
3022 		 */
3023 
3024 		if (PMC_IS_SYSTEM_MODE(mode)) {
3025 			if (jailed(curthread->td_ucred)) {
3026 				error = EPERM;
3027 				break;
3028 			}
3029 			if (!pmc_unprivileged_syspmcs) {
3030 				error = priv_check(curthread,
3031 				    PRIV_PMC_SYSTEM);
3032 				if (error)
3033 					break;
3034 			}
3035 		}
3036 
3037 		if (error)
3038 			break;
3039 
3040 		/*
3041 		 * Look for valid values for 'pm_flags'
3042 		 */
3043 
3044 		if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3045 		    PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3046 			error = EINVAL;
3047 			break;
3048 		}
3049 
3050 		/* process logging options are not allowed for system PMCs */
3051 		if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3052 		    (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3053 			error = EINVAL;
3054 			break;
3055 		}
3056 
3057 		/*
3058 		 * All sampling mode PMCs need to be able to interrupt the
3059 		 * CPU.
3060 		 */
3061 		if (PMC_IS_SAMPLING_MODE(mode))
3062 			caps |= PMC_CAP_INTERRUPT;
3063 
3064 		/* A valid class specifier should have been passed in. */
3065 		for (n = 0; n < md->pmd_nclass; n++)
3066 			if (md->pmd_classes[n].pm_class == pa.pm_class)
3067 				break;
3068 		if (n == md->pmd_nclass) {
3069 			error = EINVAL;
3070 			break;
3071 		}
3072 
3073 		/* The requested PMC capabilities should be feasible. */
3074 		if ((md->pmd_classes[n].pm_caps & caps) != caps) {
3075 			error = EOPNOTSUPP;
3076 			break;
3077 		}
3078 
3079 		PMCDBG(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3080 		    pa.pm_ev, caps, mode, cpu);
3081 
3082 		pmc = pmc_allocate_pmc_descriptor();
3083 		pmc->pm_id    = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3084 		    PMC_ID_INVALID);
3085 		pmc->pm_event = pa.pm_ev;
3086 		pmc->pm_state = PMC_STATE_FREE;
3087 		pmc->pm_caps  = caps;
3088 		pmc->pm_flags = pa.pm_flags;
3089 
3090 		/* switch thread to CPU 'cpu' */
3091 		pmc_save_cpu_binding(&pb);
3092 
3093 #define	PMC_IS_SHAREABLE_PMC(cpu, n)				\
3094 	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &		\
3095 	 PMC_PHW_FLAG_IS_SHAREABLE)
3096 #define	PMC_IS_UNALLOCATED(cpu, n)				\
3097 	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3098 
3099 		if (PMC_IS_SYSTEM_MODE(mode)) {
3100 			pmc_select_cpu(cpu);
3101 			for (n = 0; n < (int) md->pmd_npmc; n++)
3102 				if (pmc_can_allocate_row(n, mode) == 0 &&
3103 				    pmc_can_allocate_rowindex(
3104 					    curthread->td_proc, n, cpu) == 0 &&
3105 				    (PMC_IS_UNALLOCATED(cpu, n) ||
3106 				     PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3107 				    md->pmd_allocate_pmc(cpu, n, pmc,
3108 					&pa) == 0)
3109 					break;
3110 		} else {
3111 			/* Process virtual mode */
3112 			for (n = 0; n < (int) md->pmd_npmc; n++) {
3113 				if (pmc_can_allocate_row(n, mode) == 0 &&
3114 				    pmc_can_allocate_rowindex(
3115 					    curthread->td_proc, n,
3116 					    PMC_CPU_ANY) == 0 &&
3117 				    md->pmd_allocate_pmc(curthread->td_oncpu,
3118 					n, pmc, &pa) == 0)
3119 					break;
3120 			}
3121 		}
3122 
3123 #undef	PMC_IS_UNALLOCATED
3124 #undef	PMC_IS_SHAREABLE_PMC
3125 
3126 		pmc_restore_cpu_binding(&pb);
3127 
3128 		if (n == (int) md->pmd_npmc) {
3129 			pmc_destroy_pmc_descriptor(pmc);
3130 			FREE(pmc, M_PMC);
3131 			pmc = NULL;
3132 			error = EINVAL;
3133 			break;
3134 		}
3135 
3136 		/* Fill in the correct value in the ID field */
3137 		pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3138 
3139 		PMCDBG(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3140 		    pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3141 
3142 		/* Process mode PMCs with logging enabled need log files */
3143 		if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3144 			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3145 
3146 		/* All system mode sampling PMCs require a log file */
3147 		if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3148 			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3149 
3150 		/*
3151 		 * Configure global pmc's immediately
3152 		 */
3153 
3154 		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3155 
3156 			pmc_save_cpu_binding(&pb);
3157 			pmc_select_cpu(cpu);
3158 
3159 			phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3160 
3161 			if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3162 			    (error = md->pmd_config_pmc(cpu, n, pmc)) != 0) {
3163 				(void) md->pmd_release_pmc(cpu, n, pmc);
3164 				pmc_destroy_pmc_descriptor(pmc);
3165 				FREE(pmc, M_PMC);
3166 				pmc = NULL;
3167 				pmc_restore_cpu_binding(&pb);
3168 				error = EPERM;
3169 				break;
3170 			}
3171 
3172 			pmc_restore_cpu_binding(&pb);
3173 		}
3174 
3175 		pmc->pm_state    = PMC_STATE_ALLOCATED;
3176 
3177 		/*
3178 		 * mark row disposition
3179 		 */
3180 
3181 		if (PMC_IS_SYSTEM_MODE(mode))
3182 			PMC_MARK_ROW_STANDALONE(n);
3183 		else
3184 			PMC_MARK_ROW_THREAD(n);
3185 
3186 		/*
3187 		 * Register this PMC with the current thread as its owner.
3188 		 */
3189 
3190 		if ((error =
3191 		    pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3192 			pmc_release_pmc_descriptor(pmc);
3193 			FREE(pmc, M_PMC);
3194 			pmc = NULL;
3195 			break;
3196 		}
3197 
3198 		/*
3199 		 * Return the allocated index.
3200 		 */
3201 
3202 		pa.pm_pmcid = pmc->pm_id;
3203 
3204 		error = copyout(&pa, arg, sizeof(pa));
3205 	}
3206 	break;
3207 
3208 
3209 	/*
3210 	 * Attach a PMC to a process.
3211 	 */
3212 
3213 	case PMC_OP_PMCATTACH:
3214 	{
3215 		struct pmc *pm;
3216 		struct proc *p;
3217 		struct pmc_op_pmcattach a;
3218 
3219 		sx_assert(&pmc_sx, SX_XLOCKED);
3220 
3221 		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3222 			break;
3223 
3224 		if (a.pm_pid < 0) {
3225 			error = EINVAL;
3226 			break;
3227 		} else if (a.pm_pid == 0)
3228 			a.pm_pid = td->td_proc->p_pid;
3229 
3230 		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3231 			break;
3232 
3233 		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3234 			error = EINVAL;
3235 			break;
3236 		}
3237 
3238 		/* PMCs may be (re)attached only when allocated or stopped */
3239 		if (pm->pm_state == PMC_STATE_RUNNING) {
3240 			error = EBUSY;
3241 			break;
3242 		} else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3243 		    pm->pm_state != PMC_STATE_STOPPED) {
3244 			error = EINVAL;
3245 			break;
3246 		}
3247 
3248 		/* lookup pid */
3249 		if ((p = pfind(a.pm_pid)) == NULL) {
3250 			error = ESRCH;
3251 			break;
3252 		}
3253 
3254 		/*
3255 		 * Ignore processes that are working on exiting.
3256 		 */
3257 		if (p->p_flag & P_WEXIT) {
3258 			error = ESRCH;
3259 			PROC_UNLOCK(p);	/* pfind() returns a locked process */
3260 			break;
3261 		}
3262 
3263 		/*
3264 		 * we are allowed to attach a PMC to a process if
3265 		 * we can debug it.
3266 		 */
3267 		error = p_candebug(curthread, p);
3268 
3269 		PROC_UNLOCK(p);
3270 
3271 		if (error == 0)
3272 			error = pmc_attach_process(p, pm);
3273 	}
3274 	break;
3275 
3276 
3277 	/*
3278 	 * Detach an attached PMC from a process.
3279 	 */
3280 
3281 	case PMC_OP_PMCDETACH:
3282 	{
3283 		struct pmc *pm;
3284 		struct proc *p;
3285 		struct pmc_op_pmcattach a;
3286 
3287 		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3288 			break;
3289 
3290 		if (a.pm_pid < 0) {
3291 			error = EINVAL;
3292 			break;
3293 		} else if (a.pm_pid == 0)
3294 			a.pm_pid = td->td_proc->p_pid;
3295 
3296 		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3297 			break;
3298 
3299 		if ((p = pfind(a.pm_pid)) == NULL) {
3300 			error = ESRCH;
3301 			break;
3302 		}
3303 
3304 		/*
3305 		 * Treat processes that are in the process of exiting
3306 		 * as if they were not present.
3307 		 */
3308 
3309 		if (p->p_flag & P_WEXIT)
3310 			error = ESRCH;
3311 
3312 		PROC_UNLOCK(p);	/* pfind() returns a locked process */
3313 
3314 		if (error == 0)
3315 			error = pmc_detach_process(p, pm);
3316 	}
3317 	break;
3318 
3319 
3320 	/*
3321 	 * Retrieve the MSR number associated with the counter
3322 	 * 'pmc_id'.  This allows processes to directly use RDPMC
3323 	 * instructions to read their PMCs, without the overhead of a
3324 	 * system call.
3325 	 */
3326 
3327 	case PMC_OP_PMCGETMSR:
3328 	{
3329 		int ri;
3330 		struct pmc	*pm;
3331 		struct pmc_target *pt;
3332 		struct pmc_op_getmsr gm;
3333 
3334 		PMC_DOWNGRADE_SX();
3335 
3336 		/* CPU has no 'GETMSR' support */
3337 		if (md->pmd_get_msr == NULL) {
3338 			error = ENOSYS;
3339 			break;
3340 		}
3341 
3342 		if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3343 			break;
3344 
3345 		if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3346 			break;
3347 
3348 		/*
3349 		 * The allocated PMC has to be a process virtual PMC,
3350 		 * i.e., of type MODE_T[CS].  Global PMCs can only be
3351 		 * read using the PMCREAD operation since they may be
3352 		 * allocated on a different CPU than the one we could
3353 		 * be running on at the time of the RDPMC instruction.
3354 		 *
3355 		 * The GETMSR operation is not allowed for PMCs that
3356 		 * are inherited across processes.
3357 		 */
3358 
3359 		if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3360 		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
3361 			error = EINVAL;
3362 			break;
3363 		}
3364 
3365 		/*
3366 		 * It only makes sense to use a RDPMC (or its
3367 		 * equivalent instruction on non-x86 architectures) on
3368 		 * a process that has allocated and attached a PMC to
3369 		 * itself.  Conversely the PMC is only allowed to have
3370 		 * one process attached to it -- its owner.
3371 		 */
3372 
3373 		if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3374 		    LIST_NEXT(pt, pt_next) != NULL ||
3375 		    pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3376 			error = EINVAL;
3377 			break;
3378 		}
3379 
3380 		ri = PMC_TO_ROWINDEX(pm);
3381 
3382 		if ((error = (*md->pmd_get_msr)(ri, &gm.pm_msr)) < 0)
3383 			break;
3384 
3385 		if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3386 			break;
3387 
3388 		/*
3389 		 * Mark our process as using MSRs.  Update machine
3390 		 * state using a forced context switch.
3391 		 */
3392 
3393 		pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3394 		pmc_force_context_switch();
3395 
3396 	}
3397 	break;
3398 
3399 	/*
3400 	 * Release an allocated PMC
3401 	 */
3402 
3403 	case PMC_OP_PMCRELEASE:
3404 	{
3405 		pmc_id_t pmcid;
3406 		struct pmc *pm;
3407 		struct pmc_owner *po;
3408 		struct pmc_op_simple sp;
3409 
3410 		/*
3411 		 * Find PMC pointer for the named PMC.
3412 		 *
3413 		 * Use pmc_release_pmc_descriptor() to switch off the
3414 		 * PMC, remove all its target threads, and remove the
3415 		 * PMC from its owner's list.
3416 		 *
3417 		 * Remove the owner record if this is the last PMC
3418 		 * owned.
3419 		 *
3420 		 * Free up space.
3421 		 */
3422 
3423 		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3424 			break;
3425 
3426 		pmcid = sp.pm_pmcid;
3427 
3428 		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3429 			break;
3430 
3431 		po = pm->pm_owner;
3432 		pmc_release_pmc_descriptor(pm);
3433 		pmc_maybe_remove_owner(po);
3434 
3435 		FREE(pm, M_PMC);
3436 	}
3437 	break;
3438 
3439 
3440 	/*
3441 	 * Read and/or write a PMC.
3442 	 */
3443 
3444 	case PMC_OP_PMCRW:
3445 	{
3446 		uint32_t cpu, ri;
3447 		struct pmc *pm;
3448 		struct pmc_op_pmcrw *pprw;
3449 		struct pmc_op_pmcrw prw;
3450 		struct pmc_binding pb;
3451 		pmc_value_t oldvalue;
3452 
3453 		PMC_DOWNGRADE_SX();
3454 
3455 		if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3456 			break;
3457 
3458 		ri = 0;
3459 		PMCDBG(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3460 		    prw.pm_flags);
3461 
3462 		/* must have at least one flag set */
3463 		if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3464 			error = EINVAL;
3465 			break;
3466 		}
3467 
3468 		/* locate pmc descriptor */
3469 		if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3470 			break;
3471 
3472 		/* Can't read a PMC that hasn't been started. */
3473 		if (pm->pm_state != PMC_STATE_ALLOCATED &&
3474 		    pm->pm_state != PMC_STATE_STOPPED &&
3475 		    pm->pm_state != PMC_STATE_RUNNING) {
3476 			error = EINVAL;
3477 			break;
3478 		}
3479 
3480 		/* writing a new value is allowed only for 'STOPPED' pmcs */
3481 		if (pm->pm_state == PMC_STATE_RUNNING &&
3482 		    (prw.pm_flags & PMC_F_NEWVALUE)) {
3483 			error = EBUSY;
3484 			break;
3485 		}
3486 
3487 		if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3488 
3489 			/*
3490 			 * If this PMC is attached to its owner (i.e.,
3491 			 * the process requesting this operation) and
3492 			 * is running, then attempt to get an
3493 			 * upto-date reading from hardware for a READ.
3494 			 * Writes are only allowed when the PMC is
3495 			 * stopped, so only update the saved value
3496 			 * field.
3497 			 *
3498 			 * If the PMC is not running, or is not
3499 			 * attached to its owner, read/write to the
3500 			 * savedvalue field.
3501 			 */
3502 
3503 			ri = PMC_TO_ROWINDEX(pm);
3504 
3505 			mtx_pool_lock_spin(pmc_mtxpool, pm);
3506 			cpu = curthread->td_oncpu;
3507 
3508 			if (prw.pm_flags & PMC_F_OLDVALUE) {
3509 				if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3510 				    (pm->pm_state == PMC_STATE_RUNNING))
3511 					error = (*md->pmd_read_pmc)(cpu, ri,
3512 					    &oldvalue);
3513 				else
3514 					oldvalue = pm->pm_gv.pm_savedvalue;
3515 			}
3516 			if (prw.pm_flags & PMC_F_NEWVALUE)
3517 				pm->pm_gv.pm_savedvalue = prw.pm_value;
3518 
3519 			mtx_pool_unlock_spin(pmc_mtxpool, pm);
3520 
3521 		} else { /* System mode PMCs */
3522 			cpu = PMC_TO_CPU(pm);
3523 			ri  = PMC_TO_ROWINDEX(pm);
3524 
3525 			if (pmc_cpu_is_disabled(cpu)) {
3526 				error = ENXIO;
3527 				break;
3528 			}
3529 
3530 			/* move this thread to CPU 'cpu' */
3531 			pmc_save_cpu_binding(&pb);
3532 			pmc_select_cpu(cpu);
3533 
3534 			critical_enter();
3535 			/* save old value */
3536 			if (prw.pm_flags & PMC_F_OLDVALUE)
3537 				if ((error = (*md->pmd_read_pmc)(cpu, ri,
3538 					 &oldvalue)))
3539 					goto error;
3540 			/* write out new value */
3541 			if (prw.pm_flags & PMC_F_NEWVALUE)
3542 				error = (*md->pmd_write_pmc)(cpu, ri,
3543 				    prw.pm_value);
3544 		error:
3545 			critical_exit();
3546 			pmc_restore_cpu_binding(&pb);
3547 			if (error)
3548 				break;
3549 		}
3550 
3551 		pprw = (struct pmc_op_pmcrw *) arg;
3552 
3553 #ifdef	DEBUG
3554 		if (prw.pm_flags & PMC_F_NEWVALUE)
3555 			PMCDBG(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3556 			    ri, prw.pm_value, oldvalue);
3557 		else if (prw.pm_flags & PMC_F_OLDVALUE)
3558 			PMCDBG(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3559 #endif
3560 
3561 		/* return old value if requested */
3562 		if (prw.pm_flags & PMC_F_OLDVALUE)
3563 			if ((error = copyout(&oldvalue, &pprw->pm_value,
3564 				 sizeof(prw.pm_value))))
3565 				break;
3566 
3567 	}
3568 	break;
3569 
3570 
3571 	/*
3572 	 * Set the sampling rate for a sampling mode PMC and the
3573 	 * initial count for a counting mode PMC.
3574 	 */
3575 
3576 	case PMC_OP_PMCSETCOUNT:
3577 	{
3578 		struct pmc *pm;
3579 		struct pmc_op_pmcsetcount sc;
3580 
3581 		PMC_DOWNGRADE_SX();
3582 
3583 		if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3584 			break;
3585 
3586 		if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3587 			break;
3588 
3589 		if (pm->pm_state == PMC_STATE_RUNNING) {
3590 			error = EBUSY;
3591 			break;
3592 		}
3593 
3594 		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3595 			pm->pm_sc.pm_reloadcount = sc.pm_count;
3596 		else
3597 			pm->pm_sc.pm_initial = sc.pm_count;
3598 	}
3599 	break;
3600 
3601 
3602 	/*
3603 	 * Start a PMC.
3604 	 */
3605 
3606 	case PMC_OP_PMCSTART:
3607 	{
3608 		pmc_id_t pmcid;
3609 		struct pmc *pm;
3610 		struct pmc_op_simple sp;
3611 
3612 		sx_assert(&pmc_sx, SX_XLOCKED);
3613 
3614 		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3615 			break;
3616 
3617 		pmcid = sp.pm_pmcid;
3618 
3619 		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3620 			break;
3621 
3622 		KASSERT(pmcid == pm->pm_id,
3623 		    ("[pmc,%d] pmcid %x != id %x", __LINE__,
3624 			pm->pm_id, pmcid));
3625 
3626 		if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3627 			break;
3628 		else if (pm->pm_state != PMC_STATE_STOPPED &&
3629 		    pm->pm_state != PMC_STATE_ALLOCATED) {
3630 			error = EINVAL;
3631 			break;
3632 		}
3633 
3634 		error = pmc_start(pm);
3635 	}
3636 	break;
3637 
3638 
3639 	/*
3640 	 * Stop a PMC.
3641 	 */
3642 
3643 	case PMC_OP_PMCSTOP:
3644 	{
3645 		pmc_id_t pmcid;
3646 		struct pmc *pm;
3647 		struct pmc_op_simple sp;
3648 
3649 		PMC_DOWNGRADE_SX();
3650 
3651 		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3652 			break;
3653 
3654 		pmcid = sp.pm_pmcid;
3655 
3656 		/*
3657 		 * Mark the PMC as inactive and invoke the MD stop
3658 		 * routines if needed.
3659 		 */
3660 
3661 		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3662 			break;
3663 
3664 		KASSERT(pmcid == pm->pm_id,
3665 		    ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3666 			pm->pm_id, pmcid));
3667 
3668 		if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3669 			break;
3670 		else if (pm->pm_state != PMC_STATE_RUNNING) {
3671 			error = EINVAL;
3672 			break;
3673 		}
3674 
3675 		error = pmc_stop(pm);
3676 	}
3677 	break;
3678 
3679 
3680 	/*
3681 	 * Write a user supplied value to the log file.
3682 	 */
3683 
3684 	case PMC_OP_WRITELOG:
3685 	{
3686 		struct pmc_op_writelog wl;
3687 		struct pmc_owner *po;
3688 
3689 		PMC_DOWNGRADE_SX();
3690 
3691 		if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
3692 			break;
3693 
3694 		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3695 			error = EINVAL;
3696 			break;
3697 		}
3698 
3699 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
3700 			error = EINVAL;
3701 			break;
3702 		}
3703 
3704 		error = pmclog_process_userlog(po, &wl);
3705 	}
3706 	break;
3707 
3708 
3709 	default:
3710 		error = EINVAL;
3711 		break;
3712 	}
3713 
3714 	if (is_sx_downgraded)
3715 		sx_sunlock(&pmc_sx);
3716 	else
3717 		sx_xunlock(&pmc_sx);
3718 
3719 	if (error)
3720 		atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
3721 
3722 	PICKUP_GIANT();
3723 
3724 	return error;
3725 }
3726 
3727 /*
3728  * Helper functions
3729  */
3730 
3731 
3732 /*
3733  * Mark the thread as needing callchain capture and post an AST.  The
3734  * actual callchain capture will be done in a context where it is safe
3735  * to take page faults.
3736  */
3737 
3738 static void
3739 pmc_post_callchain_ast(void)
3740 {
3741 	struct thread *td;
3742 
3743 	td = curthread;
3744 
3745 	/*
3746 	 * Mark this thread as needing processing in ast().
3747 	 * td->td_pflags will be safe to touch as the process was in
3748 	 * user space when it was interrupted.
3749 	 */
3750 	td->td_pflags |= TDP_CALLCHAIN;
3751 
3752 	/*
3753 	 * Again, since we've entered this function directly from
3754 	 * userland, `td' is guaranteed to be not locked by this CPU,
3755 	 * so its safe to try acquire the thread lock even though we
3756 	 * are executing in an NMI context.  We need to acquire this
3757 	 * lock before touching `td_flags' because other CPUs may be
3758 	 * in the process of touching this field.
3759 	 */
3760 	thread_lock(td);
3761 	td->td_flags |= TDF_ASTPENDING;
3762 	thread_unlock(td);
3763 
3764 	return;
3765 }
3766 
3767 /*
3768  * Interrupt processing.
3769  *
3770  * Find a free slot in the per-cpu array of samples and capture the
3771  * current callchain there.  If a sample was successfully added, a bit
3772  * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
3773  * needs to be invoked from the clock handler.
3774  *
3775  * This function is meant to be called from an NMI handler.  It cannot
3776  * use any of the locking primitives supplied by the OS.
3777  */
3778 
3779 int
3780 pmc_process_interrupt(int cpu, struct pmc *pm, struct trapframe *tf,
3781     int inuserspace)
3782 {
3783 	int error, callchaindepth;
3784 	struct thread *td;
3785 	struct pmc_sample *ps;
3786 	struct pmc_samplebuffer *psb;
3787 
3788 	error = 0;
3789 
3790 	/*
3791 	 * Allocate space for a sample buffer.
3792 	 */
3793 	psb = pmc_pcpu[cpu]->pc_sb;
3794 
3795 	ps = psb->ps_write;
3796 	if (ps->ps_nsamples) {	/* in use, reader hasn't caught up */
3797 		pm->pm_stalled = 1;
3798 		atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
3799 		PMCDBG(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
3800 		    cpu, pm, (void *) tf, inuserspace,
3801 		    (int) (psb->ps_write - psb->ps_samples),
3802 		    (int) (psb->ps_read - psb->ps_samples));
3803 		error = ENOMEM;
3804 		goto done;
3805 	}
3806 
3807 
3808 	/* Fill in entry. */
3809 	PMCDBG(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
3810 	    (void *) tf, inuserspace,
3811 	    (int) (psb->ps_write - psb->ps_samples),
3812 	    (int) (psb->ps_read - psb->ps_samples));
3813 
3814 	atomic_add_rel_32(&pm->pm_runcount, 1);	/* hold onto PMC */
3815 	ps->ps_pmc = pm;
3816 	if ((td = curthread) && td->td_proc)
3817 		ps->ps_pid = td->td_proc->p_pid;
3818 	else
3819 		ps->ps_pid = -1;
3820 	ps->ps_cpu = cpu;
3821 	ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
3822 
3823 	callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
3824 	    pmc_callchaindepth : 1;
3825 
3826 	if (callchaindepth == 1)
3827 		ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
3828 	else {
3829 		/*
3830 		 * Kernel stack traversals can be done immediately,
3831 		 * while we defer to an AST for user space traversals.
3832 		 */
3833 		if (!inuserspace)
3834 			callchaindepth =
3835 			    pmc_save_kernel_callchain(ps->ps_pc,
3836 				callchaindepth, tf);
3837 		else {
3838 			pmc_post_callchain_ast();
3839 			callchaindepth = PMC_SAMPLE_INUSE;
3840 		}
3841 	}
3842 
3843 	ps->ps_nsamples = callchaindepth;	/* mark entry as in use */
3844 
3845 	/* increment write pointer, modulo ring buffer size */
3846 	ps++;
3847 	if (ps == psb->ps_fence)
3848 		psb->ps_write = psb->ps_samples;
3849 	else
3850 		psb->ps_write = ps;
3851 
3852  done:
3853 	/* mark CPU as needing processing */
3854 	atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3855 
3856 	return (error);
3857 }
3858 
3859 /*
3860  * Capture a user call chain.  This function will be called from ast()
3861  * before control returns to userland and before the process gets
3862  * rescheduled.
3863  */
3864 
3865 static void
3866 pmc_capture_user_callchain(int cpu, struct trapframe *tf)
3867 {
3868 	int i;
3869 	struct pmc *pm;
3870 	struct pmc_sample *ps;
3871 	struct pmc_samplebuffer *psb;
3872 
3873 	psb = pmc_pcpu[cpu]->pc_sb;
3874 
3875 	/*
3876 	 * Iterate through all deferred callchain requests.
3877 	 */
3878 
3879 	for (i = 0; i < pmc_nsamples; i++) {
3880 
3881 		ps = &psb->ps_samples[i];
3882 		if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
3883 			continue;
3884 
3885 		pm = ps->ps_pmc;
3886 
3887 		KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
3888 		    ("[pmc,%d] Retrieving callchain for PMC that doesn't "
3889 			"want it", __LINE__));
3890 
3891 		/*
3892 		 * Retrieve the callchain and mark the sample buffer
3893 		 * as 'processable' by the timer tick sweep code.
3894 		 */
3895 		ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
3896 		    pmc_callchaindepth, tf);
3897 	}
3898 
3899 	return;
3900 }
3901 
3902 
3903 /*
3904  * Process saved PC samples.
3905  */
3906 
3907 static void
3908 pmc_process_samples(int cpu)
3909 {
3910 	int n, ri;
3911 	struct pmc *pm;
3912 	struct thread *td;
3913 	struct pmc_owner *po;
3914 	struct pmc_sample *ps;
3915 	struct pmc_samplebuffer *psb;
3916 
3917 	KASSERT(PCPU_GET(cpuid) == cpu,
3918 	    ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
3919 		PCPU_GET(cpuid), cpu));
3920 
3921 	psb = pmc_pcpu[cpu]->pc_sb;
3922 
3923 	for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
3924 
3925 		ps = psb->ps_read;
3926 		if (ps->ps_nsamples == PMC_SAMPLE_FREE)
3927 			break;
3928 		if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
3929 			/* Need a rescan at a later time. */
3930 			atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3931 			break;
3932 		}
3933 
3934 		pm = ps->ps_pmc;
3935 		po = pm->pm_owner;
3936 
3937 		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
3938 		    ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
3939 			pm, PMC_TO_MODE(pm)));
3940 
3941 		/* Ignore PMCs that have been switched off */
3942 		if (pm->pm_state != PMC_STATE_RUNNING)
3943 			goto entrydone;
3944 
3945 		PMCDBG(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
3946 		    pm, ps->ps_nsamples, ps->ps_flags,
3947 		    (int) (psb->ps_write - psb->ps_samples),
3948 		    (int) (psb->ps_read - psb->ps_samples));
3949 
3950 		/*
3951 		 * If this is a process-mode PMC that is attached to
3952 		 * its owner, and if the PC is in user mode, update
3953 		 * profiling statistics like timer-based profiling
3954 		 * would have done.
3955 		 */
3956 		if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
3957 			if (ps->ps_flags & PMC_CC_F_USERSPACE) {
3958 				td = FIRST_THREAD_IN_PROC(po->po_owner);
3959 				addupc_intr(td, ps->ps_pc[0], 1);
3960 			}
3961 			goto entrydone;
3962 		}
3963 
3964 		/*
3965 		 * Otherwise, this is either a sampling mode PMC that
3966 		 * is attached to a different process than its owner,
3967 		 * or a system-wide sampling PMC.  Dispatch a log
3968 		 * entry to the PMC's owner process.
3969 		 */
3970 
3971 		pmclog_process_callchain(pm, ps);
3972 
3973 	entrydone:
3974 		ps->ps_nsamples = 0;	/* mark entry as free */
3975 		atomic_subtract_rel_32(&pm->pm_runcount, 1);
3976 
3977 		/* increment read pointer, modulo sample size */
3978 		if (++ps == psb->ps_fence)
3979 			psb->ps_read = psb->ps_samples;
3980 		else
3981 			psb->ps_read = ps;
3982 	}
3983 
3984 	atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
3985 
3986 	/* Do not re-enable stalled PMCs if we failed to process any samples */
3987 	if (n == 0)
3988 		return;
3989 
3990 	/*
3991 	 * Restart any stalled sampling PMCs on this CPU.
3992 	 *
3993 	 * If the NMI handler sets the pm_stalled field of a PMC after
3994 	 * the check below, we'll end up processing the stalled PMC at
3995 	 * the next hardclock tick.
3996 	 */
3997 	for (n = 0; n < md->pmd_npmc; n++) {
3998 		(void) (*md->pmd_get_config)(cpu,n,&pm);
3999 		if (pm == NULL ||			 /* !cfg'ed */
4000 		    pm->pm_state != PMC_STATE_RUNNING || /* !active */
4001 		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4002 		    pm->pm_stalled == 0) /* !stalled */
4003 			continue;
4004 
4005 		pm->pm_stalled = 0;
4006 		ri = PMC_TO_ROWINDEX(pm);
4007 		(*md->pmd_start_pmc)(cpu, ri);
4008 	}
4009 }
4010 
4011 /*
4012  * Event handlers.
4013  */
4014 
4015 /*
4016  * Handle a process exit.
4017  *
4018  * Remove this process from all hash tables.  If this process
4019  * owned any PMCs, turn off those PMCs and deallocate them,
4020  * removing any associations with target processes.
4021  *
4022  * This function will be called by the last 'thread' of a
4023  * process.
4024  *
4025  * XXX This eventhandler gets called early in the exit process.
4026  * Consider using a 'hook' invocation from thread_exit() or equivalent
4027  * spot.  Another negative is that kse_exit doesn't seem to call
4028  * exit1() [??].
4029  *
4030  */
4031 
4032 static void
4033 pmc_process_exit(void *arg __unused, struct proc *p)
4034 {
4035 	int is_using_hwpmcs;
4036 	int cpu;
4037 	unsigned int ri;
4038 	struct pmc *pm;
4039 	struct pmc_process *pp;
4040 	struct pmc_owner *po;
4041 	pmc_value_t newvalue, tmp;
4042 
4043 	PROC_LOCK(p);
4044 	is_using_hwpmcs = p->p_flag & P_HWPMC;
4045 	PROC_UNLOCK(p);
4046 
4047 	/*
4048 	 * Log a sysexit event to all SS PMC owners.
4049 	 */
4050 	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4051 	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4052 		    pmclog_process_sysexit(po, p->p_pid);
4053 
4054 	if (!is_using_hwpmcs)
4055 		return;
4056 
4057 	PMC_GET_SX_XLOCK();
4058 	PMCDBG(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4059 	    p->p_comm);
4060 
4061 	/*
4062 	 * Since this code is invoked by the last thread in an exiting
4063 	 * process, we would have context switched IN at some prior
4064 	 * point.  However, with PREEMPTION, kernel mode context
4065 	 * switches may happen any time, so we want to disable a
4066 	 * context switch OUT till we get any PMCs targetting this
4067 	 * process off the hardware.
4068 	 *
4069 	 * We also need to atomically remove this process'
4070 	 * entry from our target process hash table, using
4071 	 * PMC_FLAG_REMOVE.
4072 	 */
4073 	PMCDBG(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4074 	    p->p_comm);
4075 
4076 	critical_enter(); /* no preemption */
4077 
4078 	cpu = curthread->td_oncpu;
4079 
4080 	if ((pp = pmc_find_process_descriptor(p,
4081 		 PMC_FLAG_REMOVE)) != NULL) {
4082 
4083 		PMCDBG(PRC,EXT,2,
4084 		    "process-exit proc=%p pmc-process=%p", p, pp);
4085 
4086 		/*
4087 		 * The exiting process could the target of
4088 		 * some PMCs which will be running on
4089 		 * currently executing CPU.
4090 		 *
4091 		 * We need to turn these PMCs off like we
4092 		 * would do at context switch OUT time.
4093 		 */
4094 		for (ri = 0; ri < md->pmd_npmc; ri++) {
4095 
4096 			/*
4097 			 * Pick up the pmc pointer from hardware
4098 			 * state similar to the CSW_OUT code.
4099 			 */
4100 			pm = NULL;
4101 			(void) (*md->pmd_get_config)(cpu, ri, &pm);
4102 
4103 			PMCDBG(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4104 
4105 			if (pm == NULL ||
4106 			    !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4107 				continue;
4108 
4109 			PMCDBG(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4110 			    "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4111 			    pm, pm->pm_state);
4112 
4113 			KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4114 			    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4115 				__LINE__, PMC_TO_ROWINDEX(pm), ri));
4116 
4117 			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4118 			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4119 				__LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4120 
4121 			(void) md->pmd_stop_pmc(cpu, ri);
4122 
4123 			KASSERT(pm->pm_runcount > 0,
4124 			    ("[pmc,%d] bad runcount ri %d rc %d",
4125 				__LINE__, ri, pm->pm_runcount));
4126 
4127 			/* Stop hardware only if it is actually running */
4128 			if (pm->pm_state == PMC_STATE_RUNNING &&
4129 			    pm->pm_stalled == 0) {
4130 				md->pmd_read_pmc(cpu, ri, &newvalue);
4131 				tmp = newvalue -
4132 				    PMC_PCPU_SAVED(cpu,ri);
4133 
4134 				mtx_pool_lock_spin(pmc_mtxpool, pm);
4135 				pm->pm_gv.pm_savedvalue += tmp;
4136 				pp->pp_pmcs[ri].pp_pmcval += tmp;
4137 				mtx_pool_unlock_spin(pmc_mtxpool, pm);
4138 			}
4139 
4140 			atomic_subtract_rel_32(&pm->pm_runcount,1);
4141 
4142 			KASSERT((int) pm->pm_runcount >= 0,
4143 			    ("[pmc,%d] runcount is %d", __LINE__, ri));
4144 
4145 			(void) md->pmd_config_pmc(cpu, ri, NULL);
4146 		}
4147 
4148 		/*
4149 		 * Inform the MD layer of this pseudo "context switch
4150 		 * out"
4151 		 */
4152 		(void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
4153 
4154 		critical_exit(); /* ok to be pre-empted now */
4155 
4156 		/*
4157 		 * Unlink this process from the PMCs that are
4158 		 * targetting it.  This will send a signal to
4159 		 * all PMC owner's whose PMCs are orphaned.
4160 		 *
4161 		 * Log PMC value at exit time if requested.
4162 		 */
4163 		for (ri = 0; ri < md->pmd_npmc; ri++)
4164 			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
4165 				if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
4166 				    PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
4167 					pmclog_process_procexit(pm, pp);
4168 				pmc_unlink_target_process(pm, pp);
4169 			}
4170 		FREE(pp, M_PMC);
4171 
4172 	} else
4173 		critical_exit(); /* pp == NULL */
4174 
4175 
4176 	/*
4177 	 * If the process owned PMCs, free them up and free up
4178 	 * memory.
4179 	 */
4180 	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
4181 		pmc_remove_owner(po);
4182 		pmc_destroy_owner_descriptor(po);
4183 	}
4184 
4185 	sx_xunlock(&pmc_sx);
4186 }
4187 
4188 /*
4189  * Handle a process fork.
4190  *
4191  * If the parent process 'p1' is under HWPMC monitoring, then copy
4192  * over any attached PMCs that have 'do_descendants' semantics.
4193  */
4194 
4195 static void
4196 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
4197     int flags)
4198 {
4199 	int is_using_hwpmcs;
4200 	unsigned int ri;
4201 	uint32_t do_descendants;
4202 	struct pmc *pm;
4203 	struct pmc_owner *po;
4204 	struct pmc_process *ppnew, *ppold;
4205 
4206 	(void) flags;		/* unused parameter */
4207 
4208 	PROC_LOCK(p1);
4209 	is_using_hwpmcs = p1->p_flag & P_HWPMC;
4210 	PROC_UNLOCK(p1);
4211 
4212 	/*
4213 	 * If there are system-wide sampling PMCs active, we need to
4214 	 * log all fork events to their owner's logs.
4215 	 */
4216 
4217 	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4218 	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4219 		    pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4220 
4221 	if (!is_using_hwpmcs)
4222 		return;
4223 
4224 	PMC_GET_SX_XLOCK();
4225 	PMCDBG(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4226 	    p1->p_pid, p1->p_comm, newproc);
4227 
4228 	/*
4229 	 * If the parent process (curthread->td_proc) is a
4230 	 * target of any PMCs, look for PMCs that are to be
4231 	 * inherited, and link these into the new process
4232 	 * descriptor.
4233 	 */
4234 	if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4235 		 PMC_FLAG_NONE)) == NULL)
4236 		goto done;		/* nothing to do */
4237 
4238 	do_descendants = 0;
4239 	for (ri = 0; ri < md->pmd_npmc; ri++)
4240 		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4241 			do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4242 	if (do_descendants == 0) /* nothing to do */
4243 		goto done;
4244 
4245 	/* allocate a descriptor for the new process  */
4246 	if ((ppnew = pmc_find_process_descriptor(newproc,
4247 		 PMC_FLAG_ALLOCATE)) == NULL)
4248 		goto done;
4249 
4250 	/*
4251 	 * Run through all PMCs that were targeting the old process
4252 	 * and which specified F_DESCENDANTS and attach them to the
4253 	 * new process.
4254 	 *
4255 	 * Log the fork event to all owners of PMCs attached to this
4256 	 * process, if not already logged.
4257 	 */
4258 	for (ri = 0; ri < md->pmd_npmc; ri++)
4259 		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4260 		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
4261 			pmc_link_target_process(pm, ppnew);
4262 			po = pm->pm_owner;
4263 			if (po->po_sscount == 0 &&
4264 			    po->po_flags & PMC_PO_OWNS_LOGFILE)
4265 				pmclog_process_procfork(po, p1->p_pid,
4266 				    newproc->p_pid);
4267 		}
4268 
4269 	/*
4270 	 * Now mark the new process as being tracked by this driver.
4271 	 */
4272 	PROC_LOCK(newproc);
4273 	newproc->p_flag |= P_HWPMC;
4274 	PROC_UNLOCK(newproc);
4275 
4276  done:
4277 	sx_xunlock(&pmc_sx);
4278 }
4279 
4280 
4281 /*
4282  * initialization
4283  */
4284 
4285 static const char *pmc_name_of_pmcclass[] = {
4286 #undef	__PMC_CLASS
4287 #define	__PMC_CLASS(N) #N ,
4288 	__PMC_CLASSES()
4289 };
4290 
4291 static int
4292 pmc_initialize(void)
4293 {
4294 	int cpu, error, n;
4295 	struct pmc_binding pb;
4296 	struct pmc_sample *ps;
4297 	struct pmc_samplebuffer *sb;
4298 
4299 	md = NULL;
4300 	error = 0;
4301 
4302 #ifdef	DEBUG
4303 	/* parse debug flags first */
4304 	if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4305 		pmc_debugstr, sizeof(pmc_debugstr)))
4306 		pmc_debugflags_parse(pmc_debugstr,
4307 		    pmc_debugstr+strlen(pmc_debugstr));
4308 #endif
4309 
4310 	PMCDBG(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4311 
4312 	/* check kernel version */
4313 	if (pmc_kernel_version != PMC_VERSION) {
4314 		if (pmc_kernel_version == 0)
4315 			printf("hwpmc: this kernel has not been compiled with "
4316 			    "'options HWPMC_HOOKS'.\n");
4317 		else
4318 			printf("hwpmc: kernel version (0x%x) does not match "
4319 			    "module version (0x%x).\n", pmc_kernel_version,
4320 			    PMC_VERSION);
4321 		return EPROGMISMATCH;
4322 	}
4323 
4324 	/*
4325 	 * check sysctl parameters
4326 	 */
4327 
4328 	if (pmc_hashsize <= 0) {
4329 		(void) printf("hwpmc: tunable \"hashsize\"=%d must be "
4330 		    "greater than zero.\n", pmc_hashsize);
4331 		pmc_hashsize = PMC_HASH_SIZE;
4332 	}
4333 
4334 	if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4335 		(void) printf("hwpmc: tunable \"nsamples\"=%d out of "
4336 		    "range.\n", pmc_nsamples);
4337 		pmc_nsamples = PMC_NSAMPLES;
4338 	}
4339 
4340 	if (pmc_callchaindepth <= 0 ||
4341 	    pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
4342 		(void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
4343 		    "range.\n", pmc_callchaindepth);
4344 		pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
4345 	}
4346 
4347 	md = pmc_md_initialize();
4348 
4349 	if (md == NULL || md->pmd_init == NULL)
4350 		return ENOSYS;
4351 
4352 	/* allocate space for the per-cpu array */
4353 	MALLOC(pmc_pcpu, struct pmc_cpu **, mp_ncpus * sizeof(struct pmc_cpu *),
4354 	    M_PMC, M_WAITOK|M_ZERO);
4355 
4356 	/* per-cpu 'saved values' for managing process-mode PMCs */
4357 	MALLOC(pmc_pcpu_saved, pmc_value_t *,
4358 	    sizeof(pmc_value_t) * mp_ncpus * md->pmd_npmc, M_PMC, M_WAITOK);
4359 
4360 	/* perform cpu dependent initialization */
4361 	pmc_save_cpu_binding(&pb);
4362 	for (cpu = 0; cpu < mp_ncpus; cpu++) {
4363 		if (pmc_cpu_is_disabled(cpu))
4364 			continue;
4365 		pmc_select_cpu(cpu);
4366 		if ((error = md->pmd_init(cpu)) != 0)
4367 			break;
4368 	}
4369 	pmc_restore_cpu_binding(&pb);
4370 
4371 	if (error != 0)
4372 		return error;
4373 
4374 	/* allocate space for the sample array */
4375 	for (cpu = 0; cpu < mp_ncpus; cpu++) {
4376 		if (pmc_cpu_is_disabled(cpu))
4377 			continue;
4378 		MALLOC(sb, struct pmc_samplebuffer *,
4379 		    sizeof(struct pmc_samplebuffer) +
4380 		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4381 		    M_WAITOK|M_ZERO);
4382 
4383 		sb->ps_read = sb->ps_write = sb->ps_samples;
4384 		sb->ps_fence = sb->ps_samples + pmc_nsamples;
4385 		KASSERT(pmc_pcpu[cpu] != NULL,
4386 		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4387 
4388 		MALLOC(sb->ps_callchains, uintptr_t *,
4389 		    pmc_callchaindepth * pmc_nsamples * sizeof(uintptr_t),
4390 		    M_PMC, M_WAITOK|M_ZERO);
4391 
4392 		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4393 			ps->ps_pc = sb->ps_callchains +
4394 			    (n * pmc_callchaindepth);
4395 
4396 		pmc_pcpu[cpu]->pc_sb = sb;
4397 	}
4398 
4399 	/* allocate space for the row disposition array */
4400 	pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4401 	    M_PMC, M_WAITOK|M_ZERO);
4402 
4403 	KASSERT(pmc_pmcdisp != NULL,
4404 	    ("[pmc,%d] pmcdisp allocation returned NULL", __LINE__));
4405 
4406 	/* mark all PMCs as available */
4407 	for (n = 0; n < (int) md->pmd_npmc; n++)
4408 		PMC_MARK_ROW_FREE(n);
4409 
4410 	/* allocate thread hash tables */
4411 	pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4412 	    &pmc_ownerhashmask);
4413 
4414 	pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4415 	    &pmc_processhashmask);
4416 	mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4417 	    MTX_SPIN);
4418 
4419 	LIST_INIT(&pmc_ss_owners);
4420 	pmc_ss_count = 0;
4421 
4422 	/* allocate a pool of spin mutexes */
4423 	pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4424 	    MTX_SPIN);
4425 
4426 	PMCDBG(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4427 	    "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4428 	    pmc_processhash, pmc_processhashmask);
4429 
4430 	/* register process {exit,fork,exec} handlers */
4431 	pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4432 	    pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4433 	pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4434 	    pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4435 
4436 	/* initialize logging */
4437 	pmclog_initialize();
4438 
4439 	/* set hook functions */
4440 	pmc_intr = md->pmd_intr;
4441 	pmc_hook = pmc_hook_handler;
4442 
4443 	if (error == 0) {
4444 		printf(PMC_MODULE_NAME ":");
4445 		for (n = 0; n < (int) md->pmd_nclass; n++) {
4446 			printf(" %s/%d/0x%b",
4447 			    pmc_name_of_pmcclass[md->pmd_classes[n].pm_class],
4448 			    md->pmd_nclasspmcs[n],
4449 			    md->pmd_classes[n].pm_caps,
4450 			    "\20"
4451 			    "\1INT\2USR\3SYS\4EDG\5THR"
4452 			    "\6REA\7WRI\10INV\11QUA\12PRC"
4453 			    "\13TAG\14CSC");
4454 		}
4455 		printf("\n");
4456 	}
4457 
4458 	return error;
4459 }
4460 
4461 /* prepare to be unloaded */
4462 static void
4463 pmc_cleanup(void)
4464 {
4465 	int cpu;
4466 	struct pmc_ownerhash *ph;
4467 	struct pmc_owner *po, *tmp;
4468 	struct pmc_binding pb;
4469 #ifdef	DEBUG
4470 	struct pmc_processhash *prh;
4471 #endif
4472 
4473 	PMCDBG(MOD,INI,0, "%s", "cleanup");
4474 
4475 	/* switch off sampling */
4476 	atomic_store_rel_int(&pmc_cpumask, 0);
4477 	pmc_intr = NULL;
4478 
4479 	sx_xlock(&pmc_sx);
4480 	if (pmc_hook == NULL) {	/* being unloaded already */
4481 		sx_xunlock(&pmc_sx);
4482 		return;
4483 	}
4484 
4485 	pmc_hook = NULL; /* prevent new threads from entering module */
4486 
4487 	/* deregister event handlers */
4488 	EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4489 	EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4490 
4491 	/* send SIGBUS to all owner threads, free up allocations */
4492 	if (pmc_ownerhash)
4493 		for (ph = pmc_ownerhash;
4494 		     ph <= &pmc_ownerhash[pmc_ownerhashmask];
4495 		     ph++) {
4496 			LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4497 				pmc_remove_owner(po);
4498 
4499 				/* send SIGBUS to owner processes */
4500 				PMCDBG(MOD,INI,2, "cleanup signal proc=%p "
4501 				    "(%d, %s)", po->po_owner,
4502 				    po->po_owner->p_pid,
4503 				    po->po_owner->p_comm);
4504 
4505 				PROC_LOCK(po->po_owner);
4506 				psignal(po->po_owner, SIGBUS);
4507 				PROC_UNLOCK(po->po_owner);
4508 
4509 				pmc_destroy_owner_descriptor(po);
4510 			}
4511 		}
4512 
4513 	/* reclaim allocated data structures */
4514 	if (pmc_mtxpool)
4515 		mtx_pool_destroy(&pmc_mtxpool);
4516 
4517 	mtx_destroy(&pmc_processhash_mtx);
4518 	if (pmc_processhash) {
4519 #ifdef	DEBUG
4520 		struct pmc_process *pp;
4521 
4522 		PMCDBG(MOD,INI,3, "%s", "destroy process hash");
4523 		for (prh = pmc_processhash;
4524 		     prh <= &pmc_processhash[pmc_processhashmask];
4525 		     prh++)
4526 			LIST_FOREACH(pp, prh, pp_next)
4527 			    PMCDBG(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
4528 #endif
4529 
4530 		hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
4531 		pmc_processhash = NULL;
4532 	}
4533 
4534 	if (pmc_ownerhash) {
4535 		PMCDBG(MOD,INI,3, "%s", "destroy owner hash");
4536 		hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
4537 		pmc_ownerhash = NULL;
4538 	}
4539 
4540 	KASSERT(LIST_EMPTY(&pmc_ss_owners),
4541 	    ("[pmc,%d] Global SS owner list not empty", __LINE__));
4542 	KASSERT(pmc_ss_count == 0,
4543 	    ("[pmc,%d] Global SS count not empty", __LINE__));
4544 
4545 	/* free the per-cpu sample buffers */
4546 	for (cpu = 0; cpu < mp_ncpus; cpu++) {
4547 		if (pmc_cpu_is_disabled(cpu))
4548 			continue;
4549 		KASSERT(pmc_pcpu[cpu]->pc_sb != NULL,
4550 		    ("[pmc,%d] Null cpu sample buffer cpu=%d", __LINE__,
4551 			cpu));
4552 		FREE(pmc_pcpu[cpu]->pc_sb->ps_callchains, M_PMC);
4553 		FREE(pmc_pcpu[cpu]->pc_sb, M_PMC);
4554 		pmc_pcpu[cpu]->pc_sb = NULL;
4555 	}
4556 
4557  	/* do processor dependent cleanup */
4558 	PMCDBG(MOD,INI,3, "%s", "md cleanup");
4559 	if (md) {
4560 		pmc_save_cpu_binding(&pb);
4561 		for (cpu = 0; cpu < mp_ncpus; cpu++) {
4562 			PMCDBG(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
4563 			    cpu, pmc_pcpu[cpu]);
4564 			if (pmc_cpu_is_disabled(cpu))
4565 				continue;
4566 			pmc_select_cpu(cpu);
4567 			if (pmc_pcpu[cpu])
4568 				(void) md->pmd_cleanup(cpu);
4569 		}
4570 		FREE(md, M_PMC);
4571 		md = NULL;
4572 		pmc_restore_cpu_binding(&pb);
4573 	}
4574 
4575 	/* deallocate per-cpu structures */
4576 	FREE(pmc_pcpu, M_PMC);
4577 	pmc_pcpu = NULL;
4578 
4579 	FREE(pmc_pcpu_saved, M_PMC);
4580 	pmc_pcpu_saved = NULL;
4581 
4582 	if (pmc_pmcdisp) {
4583 		FREE(pmc_pmcdisp, M_PMC);
4584 		pmc_pmcdisp = NULL;
4585 	}
4586 
4587 	pmclog_shutdown();
4588 
4589 	sx_xunlock(&pmc_sx); 	/* we are done */
4590 }
4591 
4592 /*
4593  * The function called at load/unload.
4594  */
4595 
4596 static int
4597 load (struct module *module __unused, int cmd, void *arg __unused)
4598 {
4599 	int error;
4600 
4601 	error = 0;
4602 
4603 	switch (cmd) {
4604 	case MOD_LOAD :
4605 		/* initialize the subsystem */
4606 		error = pmc_initialize();
4607 		if (error != 0)
4608 			break;
4609 		PMCDBG(MOD,INI,1, "syscall=%d ncpus=%d",
4610 		    pmc_syscall_num, mp_ncpus);
4611 		break;
4612 
4613 
4614 	case MOD_UNLOAD :
4615 	case MOD_SHUTDOWN:
4616 		pmc_cleanup();
4617 		PMCDBG(MOD,INI,1, "%s", "unloaded");
4618 		break;
4619 
4620 	default :
4621 		error = EINVAL;	/* XXX should panic(9) */
4622 		break;
4623 	}
4624 
4625 	return error;
4626 }
4627 
4628 /* memory pool */
4629 MALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");
4630