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