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