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