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