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