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