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