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