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