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