xref: /freebsd/sys/dev/hwpmc/hwpmc_mod.c (revision e52d92164754cbfff84767d4c6eb3cc93e8c21ae)
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 		pmc_process_mmap(td, (struct pmckern_map_in *) arg);
2201 		break;
2202 
2203 	case PMC_FN_MUNMAP:
2204 		MPASS(in_epoch() || sx_xlocked(&pmc_sx));
2205 		pmc_process_munmap(td, (struct pmckern_map_out *) arg);
2206 		break;
2207 
2208 	case PMC_FN_USER_CALLCHAIN:
2209 		/*
2210 		 * Record a call chain.
2211 		 */
2212 		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2213 		    __LINE__));
2214 
2215 		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
2216 		    (struct trapframe *) arg);
2217 		td->td_pflags &= ~TDP_CALLCHAIN;
2218 		break;
2219 
2220 	case PMC_FN_USER_CALLCHAIN_SOFT:
2221 		/*
2222 		 * Record a call chain.
2223 		 */
2224 		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2225 		    __LINE__));
2226 		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_SR,
2227 		    (struct trapframe *) arg);
2228 		td->td_pflags &= ~TDP_CALLCHAIN;
2229 		break;
2230 
2231 	case PMC_FN_SOFT_SAMPLING:
2232 		/*
2233 		 * Call soft PMC sampling intr.
2234 		 */
2235 		pmc_soft_intr((struct pmckern_soft *) arg);
2236 		break;
2237 
2238 	case PMC_FN_THR_CREATE:
2239 		pmc_process_thread_add(td);
2240 		break;
2241 
2242 	case PMC_FN_THR_EXIT:
2243 		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2244 		    __LINE__));
2245 		pmc_process_thread_delete(td);
2246 		break;
2247 
2248 	default:
2249 #ifdef	HWPMC_DEBUG
2250 		KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
2251 #endif
2252 		break;
2253 
2254 	}
2255 
2256 	return 0;
2257 }
2258 
2259 /*
2260  * allocate a 'struct pmc_owner' descriptor in the owner hash table.
2261  */
2262 
2263 static struct pmc_owner *
2264 pmc_allocate_owner_descriptor(struct proc *p)
2265 {
2266 	uint32_t hindex;
2267 	struct pmc_owner *po;
2268 	struct pmc_ownerhash *poh;
2269 
2270 	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2271 	poh = &pmc_ownerhash[hindex];
2272 
2273 	/* allocate space for N pointers and one descriptor struct */
2274 	po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK|M_ZERO);
2275 	po->po_owner = p;
2276 	LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
2277 
2278 	TAILQ_INIT(&po->po_logbuffers);
2279 	mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
2280 
2281 	PMCDBG4(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
2282 	    p, p->p_pid, p->p_comm, po);
2283 
2284 	return po;
2285 }
2286 
2287 static void
2288 pmc_destroy_owner_descriptor(struct pmc_owner *po)
2289 {
2290 
2291 	PMCDBG4(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
2292 	    po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
2293 
2294 	mtx_destroy(&po->po_mtx);
2295 	free(po, M_PMC);
2296 }
2297 
2298 /*
2299  * Allocate a thread descriptor from the free pool.
2300  *
2301  * NOTE: This *can* return NULL.
2302  */
2303 static struct pmc_thread *
2304 pmc_thread_descriptor_pool_alloc(void)
2305 {
2306 	struct pmc_thread *pt;
2307 
2308 	mtx_lock_spin(&pmc_threadfreelist_mtx);
2309 	if ((pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
2310 		LIST_REMOVE(pt, pt_next);
2311 		pmc_threadfreelist_entries--;
2312 	}
2313 	mtx_unlock_spin(&pmc_threadfreelist_mtx);
2314 
2315 	return (pt);
2316 }
2317 
2318 /*
2319  * Add a thread descriptor to the free pool. We use this instead of free()
2320  * to maintain a cache of free entries. Additionally, we can safely call
2321  * this function when we cannot call free(), such as in a critical section.
2322  *
2323  */
2324 static void
2325 pmc_thread_descriptor_pool_free(struct pmc_thread *pt)
2326 {
2327 
2328 	if (pt == NULL)
2329 		return;
2330 
2331 	memset(pt, 0, THREADENTRY_SIZE);
2332 	mtx_lock_spin(&pmc_threadfreelist_mtx);
2333 	LIST_INSERT_HEAD(&pmc_threadfreelist, pt, pt_next);
2334 	pmc_threadfreelist_entries++;
2335 	if (pmc_threadfreelist_entries > pmc_threadfreelist_max)
2336 		GROUPTASK_ENQUEUE(&free_gtask);
2337 	mtx_unlock_spin(&pmc_threadfreelist_mtx);
2338 }
2339 
2340 /*
2341  * A callout to manage the free list.
2342  */
2343 static void
2344 pmc_thread_descriptor_pool_free_task(void *arg __unused)
2345 {
2346 	struct pmc_thread *pt;
2347 	LIST_HEAD(, pmc_thread) tmplist;
2348 	int delta;
2349 
2350 	LIST_INIT(&tmplist);
2351 	/* Determine what changes, if any, we need to make. */
2352 	mtx_lock_spin(&pmc_threadfreelist_mtx);
2353 	delta = pmc_threadfreelist_entries - pmc_threadfreelist_max;
2354 	while (delta > 0 &&
2355 		   (pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
2356 		delta--;
2357 		LIST_REMOVE(pt, pt_next);
2358 		LIST_INSERT_HEAD(&tmplist, pt, pt_next);
2359 	}
2360 	mtx_unlock_spin(&pmc_threadfreelist_mtx);
2361 
2362 	/* If there are entries to free, free them. */
2363 	while (!LIST_EMPTY(&tmplist)) {
2364 		pt = LIST_FIRST(&tmplist);
2365 		LIST_REMOVE(pt, pt_next);
2366 		free(pt, M_PMC);
2367 	}
2368 }
2369 
2370 /*
2371  * Drain the thread free pool, freeing all allocations.
2372  */
2373 static void
2374 pmc_thread_descriptor_pool_drain()
2375 {
2376 	struct pmc_thread *pt, *next;
2377 
2378 	LIST_FOREACH_SAFE(pt, &pmc_threadfreelist, pt_next, next) {
2379 		LIST_REMOVE(pt, pt_next);
2380 		free(pt, M_PMC);
2381 	}
2382 }
2383 
2384 /*
2385  * find the descriptor corresponding to thread 'td', adding or removing it
2386  * as specified by 'mode'.
2387  *
2388  * Note that this supports additional mode flags in addition to those
2389  * supported by pmc_find_process_descriptor():
2390  * PMC_FLAG_NOWAIT: Causes the function to not wait for mallocs.
2391  *     This makes it safe to call while holding certain other locks.
2392  */
2393 
2394 static struct pmc_thread *
2395 pmc_find_thread_descriptor(struct pmc_process *pp, struct thread *td,
2396     uint32_t mode)
2397 {
2398 	struct pmc_thread *pt = NULL, *ptnew = NULL;
2399 	int wait_flag;
2400 
2401 	KASSERT(td != NULL, ("[pmc,%d] called to add NULL td", __LINE__));
2402 
2403 	/*
2404 	 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case prior to
2405 	 * acquiring the lock.
2406 	 */
2407 	if (mode & PMC_FLAG_ALLOCATE) {
2408 		if ((ptnew = pmc_thread_descriptor_pool_alloc()) == NULL) {
2409 			wait_flag = M_WAITOK;
2410 			if ((mode & PMC_FLAG_NOWAIT) || in_epoch())
2411 				wait_flag = M_NOWAIT;
2412 
2413 			ptnew = malloc(THREADENTRY_SIZE, M_PMC,
2414 			    wait_flag|M_ZERO);
2415 		}
2416 	}
2417 
2418 	mtx_lock_spin(pp->pp_tdslock);
2419 
2420 	LIST_FOREACH(pt, &pp->pp_tds, pt_next)
2421 		if (pt->pt_td == td)
2422 			break;
2423 
2424 	if ((mode & PMC_FLAG_REMOVE) && pt != NULL)
2425 		LIST_REMOVE(pt, pt_next);
2426 
2427 	if ((mode & PMC_FLAG_ALLOCATE) && pt == NULL && ptnew != NULL) {
2428 		pt = ptnew;
2429 		ptnew = NULL;
2430 		pt->pt_td = td;
2431 		LIST_INSERT_HEAD(&pp->pp_tds, pt, pt_next);
2432 	}
2433 
2434 	mtx_unlock_spin(pp->pp_tdslock);
2435 
2436 	if (ptnew != NULL) {
2437 		free(ptnew, M_PMC);
2438 	}
2439 
2440 	return pt;
2441 }
2442 
2443 /*
2444  * Try to add thread descriptors for each thread in a process.
2445  */
2446 
2447 static void
2448 pmc_add_thread_descriptors_from_proc(struct proc *p, struct pmc_process *pp)
2449 {
2450 	struct thread *curtd;
2451 	struct pmc_thread **tdlist;
2452 	int i, tdcnt, tdlistsz;
2453 
2454 	KASSERT(!PROC_LOCKED(p), ("[pmc,%d] proc unexpectedly locked",
2455 	    __LINE__));
2456 	tdcnt = 32;
2457  restart:
2458 	tdlistsz = roundup2(tdcnt, 32);
2459 
2460 	tdcnt = 0;
2461 	tdlist = malloc(sizeof(struct pmc_thread*) * tdlistsz, M_TEMP, M_WAITOK);
2462 
2463 	PROC_LOCK(p);
2464 	FOREACH_THREAD_IN_PROC(p, curtd)
2465 		tdcnt++;
2466 	if (tdcnt >= tdlistsz) {
2467 		PROC_UNLOCK(p);
2468 		free(tdlist, M_TEMP);
2469 		goto restart;
2470 	}
2471 	/*
2472 	 * Try to add each thread to the list without sleeping. If unable,
2473 	 * add to a queue to retry after dropping the process lock.
2474 	 */
2475 	tdcnt = 0;
2476 	FOREACH_THREAD_IN_PROC(p, curtd) {
2477 		tdlist[tdcnt] = pmc_find_thread_descriptor(pp, curtd,
2478 						   PMC_FLAG_ALLOCATE|PMC_FLAG_NOWAIT);
2479 		if (tdlist[tdcnt] == NULL) {
2480 			PROC_UNLOCK(p);
2481 			for (i = 0; i <= tdcnt; i++)
2482 				pmc_thread_descriptor_pool_free(tdlist[i]);
2483 			free(tdlist, M_TEMP);
2484 			goto restart;
2485 		}
2486 		tdcnt++;
2487 	}
2488 	PROC_UNLOCK(p);
2489 	free(tdlist, M_TEMP);
2490 }
2491 
2492 /*
2493  * find the descriptor corresponding to process 'p', adding or removing it
2494  * as specified by 'mode'.
2495  */
2496 
2497 static struct pmc_process *
2498 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
2499 {
2500 	uint32_t hindex;
2501 	struct pmc_process *pp, *ppnew;
2502 	struct pmc_processhash *pph;
2503 
2504 	hindex = PMC_HASH_PTR(p, pmc_processhashmask);
2505 	pph = &pmc_processhash[hindex];
2506 
2507 	ppnew = NULL;
2508 
2509 	/*
2510 	 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case since we
2511 	 * cannot call malloc(9) once we hold a spin lock.
2512 	 */
2513 	if (mode & PMC_FLAG_ALLOCATE)
2514 		ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
2515 		    sizeof(struct pmc_targetstate), M_PMC, M_WAITOK|M_ZERO);
2516 
2517 	mtx_lock_spin(&pmc_processhash_mtx);
2518 	LIST_FOREACH(pp, pph, pp_next)
2519 	    if (pp->pp_proc == p)
2520 		    break;
2521 
2522 	if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
2523 		LIST_REMOVE(pp, pp_next);
2524 
2525 	if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
2526 	    ppnew != NULL) {
2527 		ppnew->pp_proc = p;
2528 		LIST_INIT(&ppnew->pp_tds);
2529 		ppnew->pp_tdslock = mtx_pool_find(pmc_mtxpool, ppnew);
2530 		LIST_INSERT_HEAD(pph, ppnew, pp_next);
2531 		mtx_unlock_spin(&pmc_processhash_mtx);
2532 		pp = ppnew;
2533 		ppnew = NULL;
2534 
2535 		/* Add thread descriptors for this process' current threads. */
2536 		pmc_add_thread_descriptors_from_proc(p, pp);
2537 	}
2538 	else
2539 		mtx_unlock_spin(&pmc_processhash_mtx);
2540 
2541 	if (ppnew != NULL)
2542 		free(ppnew, M_PMC);
2543 
2544 	return pp;
2545 }
2546 
2547 /*
2548  * remove a process descriptor from the process hash table.
2549  */
2550 
2551 static void
2552 pmc_remove_process_descriptor(struct pmc_process *pp)
2553 {
2554 	KASSERT(pp->pp_refcnt == 0,
2555 	    ("[pmc,%d] Removing process descriptor %p with count %d",
2556 		__LINE__, pp, pp->pp_refcnt));
2557 
2558 	mtx_lock_spin(&pmc_processhash_mtx);
2559 	LIST_REMOVE(pp, pp_next);
2560 	mtx_unlock_spin(&pmc_processhash_mtx);
2561 }
2562 
2563 /*
2564  * destroy a process descriptor.
2565  */
2566 
2567 static void
2568 pmc_destroy_process_descriptor(struct pmc_process *pp)
2569 {
2570 	struct pmc_thread *pmc_td;
2571 
2572 	while ((pmc_td = LIST_FIRST(&pp->pp_tds)) != NULL) {
2573 		LIST_REMOVE(pmc_td, pt_next);
2574 		pmc_thread_descriptor_pool_free(pmc_td);
2575 	}
2576 	free(pp, M_PMC);
2577 }
2578 
2579 
2580 /*
2581  * find an owner descriptor corresponding to proc 'p'
2582  */
2583 
2584 static struct pmc_owner *
2585 pmc_find_owner_descriptor(struct proc *p)
2586 {
2587 	uint32_t hindex;
2588 	struct pmc_owner *po;
2589 	struct pmc_ownerhash *poh;
2590 
2591 	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2592 	poh = &pmc_ownerhash[hindex];
2593 
2594 	po = NULL;
2595 	LIST_FOREACH(po, poh, po_next)
2596 	    if (po->po_owner == p)
2597 		    break;
2598 
2599 	PMCDBG5(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2600 	    "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2601 
2602 	return po;
2603 }
2604 
2605 /*
2606  * pmc_allocate_pmc_descriptor
2607  *
2608  * Allocate a pmc descriptor and initialize its
2609  * fields.
2610  */
2611 
2612 static struct pmc *
2613 pmc_allocate_pmc_descriptor(void)
2614 {
2615 	struct pmc *pmc;
2616 
2617 	pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK|M_ZERO);
2618 	pmc->pm_runcount = counter_u64_alloc(M_WAITOK);
2619 	pmc->pm_pcpu_state = malloc(sizeof(struct pmc_pcpu_state)*mp_ncpus, M_PMC, M_WAITOK|M_ZERO);
2620 	PMCDBG1(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2621 
2622 	return pmc;
2623 }
2624 
2625 /*
2626  * Destroy a pmc descriptor.
2627  */
2628 
2629 static void
2630 pmc_destroy_pmc_descriptor(struct pmc *pm)
2631 {
2632 
2633 	KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2634 	    pm->pm_state == PMC_STATE_FREE,
2635 	    ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2636 	KASSERT(LIST_EMPTY(&pm->pm_targets),
2637 	    ("[pmc,%d] destroying pmc with targets", __LINE__));
2638 	KASSERT(pm->pm_owner == NULL,
2639 	    ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2640 	KASSERT(counter_u64_fetch(pm->pm_runcount) == 0,
2641 	    ("[pmc,%d] pmc has non-zero run count %ld", __LINE__,
2642 		 (unsigned long)counter_u64_fetch(pm->pm_runcount)));
2643 
2644 	counter_u64_free(pm->pm_runcount);
2645 	free(pm->pm_pcpu_state, M_PMC);
2646 	free(pm, M_PMC);
2647 }
2648 
2649 static void
2650 pmc_wait_for_pmc_idle(struct pmc *pm)
2651 {
2652 #ifdef HWPMC_DEBUG
2653 	volatile int maxloop;
2654 
2655 	maxloop = 100 * pmc_cpu_max();
2656 #endif
2657 	/*
2658 	 * Loop (with a forced context switch) till the PMC's runcount
2659 	 * comes down to zero.
2660 	 */
2661 	while (counter_u64_fetch(pm->pm_runcount) > 0) {
2662 #ifdef HWPMC_DEBUG
2663 		maxloop--;
2664 		KASSERT(maxloop > 0,
2665 		    ("[pmc,%d] (ri%d, rc%ld) waiting too long for "
2666 			"pmc to be free", __LINE__,
2667 			 PMC_TO_ROWINDEX(pm), (unsigned long)counter_u64_fetch(pm->pm_runcount)));
2668 #endif
2669 		pmc_force_context_switch();
2670 	}
2671 }
2672 
2673 /*
2674  * This function does the following things:
2675  *
2676  *  - detaches the PMC from hardware
2677  *  - unlinks all target threads that were attached to it
2678  *  - removes the PMC from its owner's list
2679  *  - destroys the PMC private mutex
2680  *
2681  * Once this function completes, the given pmc pointer can be freed by
2682  * calling pmc_destroy_pmc_descriptor().
2683  */
2684 
2685 static void
2686 pmc_release_pmc_descriptor(struct pmc *pm)
2687 {
2688 	enum pmc_mode mode;
2689 	struct pmc_hw *phw;
2690 	u_int adjri, ri, cpu;
2691 	struct pmc_owner *po;
2692 	struct pmc_binding pb;
2693 	struct pmc_process *pp;
2694 	struct pmc_classdep *pcd;
2695 	struct pmc_target *ptgt, *tmp;
2696 
2697 	sx_assert(&pmc_sx, SX_XLOCKED);
2698 
2699 	KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2700 
2701 	ri   = PMC_TO_ROWINDEX(pm);
2702 	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
2703 	mode = PMC_TO_MODE(pm);
2704 
2705 	PMCDBG3(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2706 	    mode);
2707 
2708 	/*
2709 	 * First, we take the PMC off hardware.
2710 	 */
2711 	cpu = 0;
2712 	if (PMC_IS_SYSTEM_MODE(mode)) {
2713 
2714 		/*
2715 		 * A system mode PMC runs on a specific CPU.  Switch
2716 		 * to this CPU and turn hardware off.
2717 		 */
2718 		pmc_save_cpu_binding(&pb);
2719 
2720 		cpu = PMC_TO_CPU(pm);
2721 
2722 		pmc_select_cpu(cpu);
2723 
2724 		/* switch off non-stalled CPUs */
2725 		pm->pm_pcpu_state[cpu].pps_cpustate = 0;
2726 		if (pm->pm_state == PMC_STATE_RUNNING &&
2727 			pm->pm_pcpu_state[cpu].pps_stalled == 0) {
2728 
2729 			phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2730 
2731 			KASSERT(phw->phw_pmc == pm,
2732 			    ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2733 				__LINE__, ri, phw->phw_pmc, pm));
2734 			PMCDBG2(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2735 
2736 			critical_enter();
2737 			pcd->pcd_stop_pmc(cpu, adjri);
2738 			critical_exit();
2739 		}
2740 
2741 		PMCDBG2(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2742 
2743 		critical_enter();
2744 		pcd->pcd_config_pmc(cpu, adjri, NULL);
2745 		critical_exit();
2746 
2747 		/* adjust the global and process count of SS mode PMCs */
2748 		if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2749 			po = pm->pm_owner;
2750 			po->po_sscount--;
2751 			if (po->po_sscount == 0) {
2752 				atomic_subtract_rel_int(&pmc_ss_count, 1);
2753 				CK_LIST_REMOVE(po, po_ssnext);
2754 				epoch_wait_preempt(global_epoch_preempt);
2755 			}
2756 		}
2757 
2758 		pm->pm_state = PMC_STATE_DELETED;
2759 
2760 		pmc_restore_cpu_binding(&pb);
2761 
2762 		/*
2763 		 * We could have references to this PMC structure in
2764 		 * the per-cpu sample queues.  Wait for the queue to
2765 		 * drain.
2766 		 */
2767 		pmc_wait_for_pmc_idle(pm);
2768 
2769 	} else if (PMC_IS_VIRTUAL_MODE(mode)) {
2770 
2771 		/*
2772 		 * A virtual PMC could be running on multiple CPUs at
2773 		 * a given instant.
2774 		 *
2775 		 * By marking its state as DELETED, we ensure that
2776 		 * this PMC is never further scheduled on hardware.
2777 		 *
2778 		 * Then we wait till all CPUs are done with this PMC.
2779 		 */
2780 		pm->pm_state = PMC_STATE_DELETED;
2781 
2782 
2783 		/* Wait for the PMCs runcount to come to zero. */
2784 		pmc_wait_for_pmc_idle(pm);
2785 
2786 		/*
2787 		 * At this point the PMC is off all CPUs and cannot be
2788 		 * freshly scheduled onto a CPU.  It is now safe to
2789 		 * unlink all targets from this PMC.  If a
2790 		 * process-record's refcount falls to zero, we remove
2791 		 * it from the hash table.  The module-wide SX lock
2792 		 * protects us from races.
2793 		 */
2794 		LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2795 			pp = ptgt->pt_process;
2796 			pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2797 
2798 			PMCDBG1(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2799 
2800 			/*
2801 			 * If the target process record shows that no
2802 			 * PMCs are attached to it, reclaim its space.
2803 			 */
2804 
2805 			if (pp->pp_refcnt == 0) {
2806 				pmc_remove_process_descriptor(pp);
2807 				pmc_destroy_process_descriptor(pp);
2808 			}
2809 		}
2810 
2811 		cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2812 
2813 	}
2814 
2815 	/*
2816 	 * Release any MD resources
2817 	 */
2818 	(void) pcd->pcd_release_pmc(cpu, adjri, pm);
2819 
2820 	/*
2821 	 * Update row disposition
2822 	 */
2823 
2824 	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2825 		PMC_UNMARK_ROW_STANDALONE(ri);
2826 	else
2827 		PMC_UNMARK_ROW_THREAD(ri);
2828 
2829 	/* unlink from the owner's list */
2830 	if (pm->pm_owner) {
2831 		LIST_REMOVE(pm, pm_next);
2832 		pm->pm_owner = NULL;
2833 	}
2834 }
2835 
2836 /*
2837  * Register an owner and a pmc.
2838  */
2839 
2840 static int
2841 pmc_register_owner(struct proc *p, struct pmc *pmc)
2842 {
2843 	struct pmc_owner *po;
2844 
2845 	sx_assert(&pmc_sx, SX_XLOCKED);
2846 
2847 	if ((po = pmc_find_owner_descriptor(p)) == NULL)
2848 		if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2849 			return ENOMEM;
2850 
2851 	KASSERT(pmc->pm_owner == NULL,
2852 	    ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2853 	pmc->pm_owner  = po;
2854 
2855 	LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2856 
2857 	PROC_LOCK(p);
2858 	p->p_flag |= P_HWPMC;
2859 	PROC_UNLOCK(p);
2860 
2861 	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2862 		pmclog_process_pmcallocate(pmc);
2863 
2864 	PMCDBG2(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2865 	    po, pmc);
2866 
2867 	return 0;
2868 }
2869 
2870 /*
2871  * Return the current row disposition:
2872  * == 0 => FREE
2873  *  > 0 => PROCESS MODE
2874  *  < 0 => SYSTEM MODE
2875  */
2876 
2877 int
2878 pmc_getrowdisp(int ri)
2879 {
2880 	return pmc_pmcdisp[ri];
2881 }
2882 
2883 /*
2884  * Check if a PMC at row index 'ri' can be allocated to the current
2885  * process.
2886  *
2887  * Allocation can fail if:
2888  *   - the current process is already being profiled by a PMC at index 'ri',
2889  *     attached to it via OP_PMCATTACH.
2890  *   - the current process has already allocated a PMC at index 'ri'
2891  *     via OP_ALLOCATE.
2892  */
2893 
2894 static int
2895 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2896 {
2897 	enum pmc_mode mode;
2898 	struct pmc *pm;
2899 	struct pmc_owner *po;
2900 	struct pmc_process *pp;
2901 
2902 	PMCDBG5(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2903 	    "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2904 
2905 	/*
2906 	 * We shouldn't have already allocated a process-mode PMC at
2907 	 * row index 'ri'.
2908 	 *
2909 	 * We shouldn't have allocated a system-wide PMC on the same
2910 	 * CPU and same RI.
2911 	 */
2912 	if ((po = pmc_find_owner_descriptor(p)) != NULL)
2913 		LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2914 		    if (PMC_TO_ROWINDEX(pm) == ri) {
2915 			    mode = PMC_TO_MODE(pm);
2916 			    if (PMC_IS_VIRTUAL_MODE(mode))
2917 				    return EEXIST;
2918 			    if (PMC_IS_SYSTEM_MODE(mode) &&
2919 				(int) PMC_TO_CPU(pm) == cpu)
2920 				    return EEXIST;
2921 		    }
2922 	        }
2923 
2924 	/*
2925 	 * We also shouldn't be the target of any PMC at this index
2926 	 * since otherwise a PMC_ATTACH to ourselves will fail.
2927 	 */
2928 	if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2929 		if (pp->pp_pmcs[ri].pp_pmc)
2930 			return EEXIST;
2931 
2932 	PMCDBG4(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2933 	    p, p->p_pid, p->p_comm, ri);
2934 
2935 	return 0;
2936 }
2937 
2938 /*
2939  * Check if a given PMC at row index 'ri' can be currently used in
2940  * mode 'mode'.
2941  */
2942 
2943 static int
2944 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2945 {
2946 	enum pmc_disp	disp;
2947 
2948 	sx_assert(&pmc_sx, SX_XLOCKED);
2949 
2950 	PMCDBG2(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2951 
2952 	if (PMC_IS_SYSTEM_MODE(mode))
2953 		disp = PMC_DISP_STANDALONE;
2954 	else
2955 		disp = PMC_DISP_THREAD;
2956 
2957 	/*
2958 	 * check disposition for PMC row 'ri':
2959 	 *
2960 	 * Expected disposition		Row-disposition		Result
2961 	 *
2962 	 * STANDALONE			STANDALONE or FREE	proceed
2963 	 * STANDALONE			THREAD			fail
2964 	 * THREAD			THREAD or FREE		proceed
2965 	 * THREAD			STANDALONE		fail
2966 	 */
2967 
2968 	if (!PMC_ROW_DISP_IS_FREE(ri) &&
2969 	    !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2970 	    !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2971 		return EBUSY;
2972 
2973 	/*
2974 	 * All OK
2975 	 */
2976 
2977 	PMCDBG2(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2978 
2979 	return 0;
2980 
2981 }
2982 
2983 /*
2984  * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2985  */
2986 
2987 static struct pmc *
2988 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2989 {
2990 	struct pmc *pm;
2991 
2992 	KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2993 	    ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2994 		PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2995 
2996 	LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2997 	    if (pm->pm_id == pmcid)
2998 		    return pm;
2999 
3000 	return NULL;
3001 }
3002 
3003 static int
3004 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
3005 {
3006 
3007 	struct pmc *pm, *opm;
3008 	struct pmc_owner *po;
3009 	struct pmc_process *pp;
3010 
3011 	PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid);
3012 	if (PMC_ID_TO_ROWINDEX(pmcid) >= md->pmd_npmc)
3013 		return (EINVAL);
3014 
3015 	if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL) {
3016 		/*
3017 		 * In case of PMC_F_DESCENDANTS child processes we will not find
3018 		 * the current process in the owners hash list.  Find the owner
3019 		 * process first and from there lookup the po.
3020 		 */
3021 		if ((pp = pmc_find_process_descriptor(curthread->td_proc,
3022 		    PMC_FLAG_NONE)) == NULL) {
3023 			return ESRCH;
3024 		} else {
3025 			opm = pp->pp_pmcs[PMC_ID_TO_ROWINDEX(pmcid)].pp_pmc;
3026 			if (opm == NULL)
3027 				return ESRCH;
3028 			if ((opm->pm_flags & (PMC_F_ATTACHED_TO_OWNER|
3029 			    PMC_F_DESCENDANTS)) != (PMC_F_ATTACHED_TO_OWNER|
3030 			    PMC_F_DESCENDANTS))
3031 				return ESRCH;
3032 			po = opm->pm_owner;
3033 		}
3034 	}
3035 
3036 	if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
3037 		return EINVAL;
3038 
3039 	PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
3040 
3041 	*pmc = pm;
3042 	return 0;
3043 }
3044 
3045 /*
3046  * Start a PMC.
3047  */
3048 
3049 static int
3050 pmc_start(struct pmc *pm)
3051 {
3052 	enum pmc_mode mode;
3053 	struct pmc_owner *po;
3054 	struct pmc_binding pb;
3055 	struct pmc_classdep *pcd;
3056 	int adjri, error, cpu, ri;
3057 
3058 	KASSERT(pm != NULL,
3059 	    ("[pmc,%d] null pm", __LINE__));
3060 
3061 	mode = PMC_TO_MODE(pm);
3062 	ri   = PMC_TO_ROWINDEX(pm);
3063 	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
3064 
3065 	error = 0;
3066 
3067 	PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
3068 
3069 	po = pm->pm_owner;
3070 
3071 	/*
3072 	 * Disallow PMCSTART if a logfile is required but has not been
3073 	 * configured yet.
3074 	 */
3075 	if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
3076 	    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
3077 		return (EDOOFUS);	/* programming error */
3078 
3079 	/*
3080 	 * If this is a sampling mode PMC, log mapping information for
3081 	 * the kernel modules that are currently loaded.
3082 	 */
3083 	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3084 	    pmc_log_kernel_mappings(pm);
3085 
3086 	if (PMC_IS_VIRTUAL_MODE(mode)) {
3087 
3088 		/*
3089 		 * If a PMCATTACH has never been done on this PMC,
3090 		 * attach it to its owner process.
3091 		 */
3092 
3093 		if (LIST_EMPTY(&pm->pm_targets))
3094 			error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
3095 			    pmc_attach_process(po->po_owner, pm);
3096 
3097 		/*
3098 		 * If the PMC is attached to its owner, then force a context
3099 		 * switch to ensure that the MD state gets set correctly.
3100 		 */
3101 
3102 		if (error == 0) {
3103 			pm->pm_state = PMC_STATE_RUNNING;
3104 			if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
3105 				pmc_force_context_switch();
3106 		}
3107 
3108 		return (error);
3109 	}
3110 
3111 
3112 	/*
3113 	 * A system-wide PMC.
3114 	 *
3115 	 * Add the owner to the global list if this is a system-wide
3116 	 * sampling PMC.
3117 	 */
3118 
3119 	if (mode == PMC_MODE_SS) {
3120 		/*
3121 		 * Log mapping information for all existing processes in the
3122 		 * system.  Subsequent mappings are logged as they happen;
3123 		 * see pmc_process_mmap().
3124 		 */
3125 		if (po->po_logprocmaps == 0) {
3126 			pmc_log_all_process_mappings(po);
3127 			po->po_logprocmaps = 1;
3128 		}
3129 		po->po_sscount++;
3130 		if (po->po_sscount == 1) {
3131 			atomic_add_rel_int(&pmc_ss_count, 1);
3132 			CK_LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
3133 			PMCDBG1(PMC,OPS,1, "po=%p in global list", po);
3134 		}
3135 	}
3136 
3137 	/*
3138 	 * Move to the CPU associated with this
3139 	 * PMC, and start the hardware.
3140 	 */
3141 
3142 	pmc_save_cpu_binding(&pb);
3143 
3144 	cpu = PMC_TO_CPU(pm);
3145 
3146 	if (!pmc_cpu_is_active(cpu))
3147 		return (ENXIO);
3148 
3149 	pmc_select_cpu(cpu);
3150 
3151 	/*
3152 	 * global PMCs are configured at allocation time
3153 	 * so write out the initial value and start the PMC.
3154 	 */
3155 
3156 	pm->pm_state = PMC_STATE_RUNNING;
3157 
3158 	critical_enter();
3159 	if ((error = pcd->pcd_write_pmc(cpu, adjri,
3160 		 PMC_IS_SAMPLING_MODE(mode) ?
3161 		 pm->pm_sc.pm_reloadcount :
3162 		 pm->pm_sc.pm_initial)) == 0) {
3163 		/* If a sampling mode PMC, reset stalled state. */
3164 		if (PMC_IS_SAMPLING_MODE(mode))
3165 			pm->pm_pcpu_state[cpu].pps_stalled = 0;
3166 
3167 		/* Indicate that we desire this to run. Start it. */
3168 		pm->pm_pcpu_state[cpu].pps_cpustate = 1;
3169 		error = pcd->pcd_start_pmc(cpu, adjri);
3170 	}
3171 	critical_exit();
3172 
3173 	pmc_restore_cpu_binding(&pb);
3174 
3175 	return (error);
3176 }
3177 
3178 /*
3179  * Stop a PMC.
3180  */
3181 
3182 static int
3183 pmc_stop(struct pmc *pm)
3184 {
3185 	struct pmc_owner *po;
3186 	struct pmc_binding pb;
3187 	struct pmc_classdep *pcd;
3188 	int adjri, cpu, error, ri;
3189 
3190 	KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
3191 
3192 	PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
3193 	    PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
3194 
3195 	pm->pm_state = PMC_STATE_STOPPED;
3196 
3197 	/*
3198 	 * If the PMC is a virtual mode one, changing the state to
3199 	 * non-RUNNING is enough to ensure that the PMC never gets
3200 	 * scheduled.
3201 	 *
3202 	 * If this PMC is current running on a CPU, then it will
3203 	 * handled correctly at the time its target process is context
3204 	 * switched out.
3205 	 */
3206 
3207 	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
3208 		return 0;
3209 
3210 	/*
3211 	 * A system-mode PMC.  Move to the CPU associated with
3212 	 * this PMC, and stop the hardware.  We update the
3213 	 * 'initial count' so that a subsequent PMCSTART will
3214 	 * resume counting from the current hardware count.
3215 	 */
3216 
3217 	pmc_save_cpu_binding(&pb);
3218 
3219 	cpu = PMC_TO_CPU(pm);
3220 
3221 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
3222 	    ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
3223 
3224 	if (!pmc_cpu_is_active(cpu))
3225 		return ENXIO;
3226 
3227 	pmc_select_cpu(cpu);
3228 
3229 	ri = PMC_TO_ROWINDEX(pm);
3230 	pcd = pmc_ri_to_classdep(md, ri, &adjri);
3231 
3232 	pm->pm_pcpu_state[cpu].pps_cpustate = 0;
3233 	critical_enter();
3234 	if ((error = pcd->pcd_stop_pmc(cpu, adjri)) == 0)
3235 		error = pcd->pcd_read_pmc(cpu, adjri, &pm->pm_sc.pm_initial);
3236 	critical_exit();
3237 
3238 	pmc_restore_cpu_binding(&pb);
3239 
3240 	po = pm->pm_owner;
3241 
3242 	/* remove this owner from the global list of SS PMC owners */
3243 	if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
3244 		po->po_sscount--;
3245 		if (po->po_sscount == 0) {
3246 			atomic_subtract_rel_int(&pmc_ss_count, 1);
3247 			CK_LIST_REMOVE(po, po_ssnext);
3248 			epoch_wait_preempt(global_epoch_preempt);
3249 			PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po);
3250 		}
3251 	}
3252 
3253 	return (error);
3254 }
3255 
3256 static struct pmc_classdep *
3257 pmc_class_to_classdep(enum pmc_class class)
3258 {
3259 	int n;
3260 
3261 	for (n = 0; n < md->pmd_nclass; n++)
3262 		if (md->pmd_classdep[n].pcd_class == class)
3263 			return (&md->pmd_classdep[n]);
3264 	return (NULL);
3265 }
3266 
3267 #ifdef	HWPMC_DEBUG
3268 static const char *pmc_op_to_name[] = {
3269 #undef	__PMC_OP
3270 #define	__PMC_OP(N, D)	#N ,
3271 	__PMC_OPS()
3272 	NULL
3273 };
3274 #endif
3275 
3276 /*
3277  * The syscall interface
3278  */
3279 
3280 #define	PMC_GET_SX_XLOCK(...) do {		\
3281 	sx_xlock(&pmc_sx);			\
3282 	if (pmc_hook == NULL) {			\
3283 		sx_xunlock(&pmc_sx);		\
3284 		return __VA_ARGS__;		\
3285 	}					\
3286 } while (0)
3287 
3288 #define	PMC_DOWNGRADE_SX() do {			\
3289 	sx_downgrade(&pmc_sx);			\
3290 	is_sx_downgraded = 1;			\
3291 } while (0)
3292 
3293 static int
3294 pmc_syscall_handler(struct thread *td, void *syscall_args)
3295 {
3296 	int error, is_sx_downgraded, op;
3297 	struct pmc_syscall_args *c;
3298 	void *pmclog_proc_handle;
3299 	void *arg;
3300 
3301 	c = (struct pmc_syscall_args *)syscall_args;
3302 	op = c->pmop_code;
3303 	arg = c->pmop_data;
3304 	/* PMC isn't set up yet */
3305 	if (pmc_hook == NULL)
3306 		return (EINVAL);
3307 	if (op == PMC_OP_CONFIGURELOG) {
3308 		/*
3309 		 * We cannot create the logging process inside
3310 		 * pmclog_configure_log() because there is a LOR
3311 		 * between pmc_sx and process structure locks.
3312 		 * Instead, pre-create the process and ignite the loop
3313 		 * if everything is fine, otherwise direct the process
3314 		 * to exit.
3315 		 */
3316 		error = pmclog_proc_create(td, &pmclog_proc_handle);
3317 		if (error != 0)
3318 			goto done_syscall;
3319 	}
3320 
3321 	PMC_GET_SX_XLOCK(ENOSYS);
3322 	is_sx_downgraded = 0;
3323 	PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
3324 	    pmc_op_to_name[op], arg);
3325 
3326 	error = 0;
3327 	counter_u64_add(pmc_stats.pm_syscalls, 1);
3328 
3329 	switch (op) {
3330 
3331 
3332 	/*
3333 	 * Configure a log file.
3334 	 *
3335 	 * XXX This OP will be reworked.
3336 	 */
3337 
3338 	case PMC_OP_CONFIGURELOG:
3339 	{
3340 		struct proc *p;
3341 		struct pmc *pm;
3342 		struct pmc_owner *po;
3343 		struct pmc_op_configurelog cl;
3344 
3345 		if ((error = copyin(arg, &cl, sizeof(cl))) != 0) {
3346 			pmclog_proc_ignite(pmclog_proc_handle, NULL);
3347 			break;
3348 		}
3349 
3350 		/* mark this process as owning a log file */
3351 		p = td->td_proc;
3352 		if ((po = pmc_find_owner_descriptor(p)) == NULL)
3353 			if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
3354 				pmclog_proc_ignite(pmclog_proc_handle, NULL);
3355 				error = ENOMEM;
3356 				break;
3357 			}
3358 
3359 		/*
3360 		 * If a valid fd was passed in, try to configure that,
3361 		 * otherwise if 'fd' was less than zero and there was
3362 		 * a log file configured, flush its buffers and
3363 		 * de-configure it.
3364 		 */
3365 		if (cl.pm_logfd >= 0) {
3366 			error = pmclog_configure_log(md, po, cl.pm_logfd);
3367 			pmclog_proc_ignite(pmclog_proc_handle, error == 0 ?
3368 			    po : NULL);
3369 		} else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
3370 			pmclog_proc_ignite(pmclog_proc_handle, NULL);
3371 			error = pmclog_close(po);
3372 			if (error == 0) {
3373 				LIST_FOREACH(pm, &po->po_pmcs, pm_next)
3374 				    if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
3375 					pm->pm_state == PMC_STATE_RUNNING)
3376 					    pmc_stop(pm);
3377 				error = pmclog_deconfigure_log(po);
3378 			}
3379 		} else {
3380 			pmclog_proc_ignite(pmclog_proc_handle, NULL);
3381 			error = EINVAL;
3382 		}
3383 	}
3384 	break;
3385 
3386 	/*
3387 	 * Flush a log file.
3388 	 */
3389 
3390 	case PMC_OP_FLUSHLOG:
3391 	{
3392 		struct pmc_owner *po;
3393 
3394 		sx_assert(&pmc_sx, SX_XLOCKED);
3395 
3396 		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3397 			error = EINVAL;
3398 			break;
3399 		}
3400 
3401 		error = pmclog_flush(po);
3402 	}
3403 	break;
3404 
3405 	/*
3406 	 * Close a log file.
3407 	 */
3408 
3409 	case PMC_OP_CLOSELOG:
3410 	{
3411 		struct pmc_owner *po;
3412 
3413 		sx_assert(&pmc_sx, SX_XLOCKED);
3414 
3415 		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3416 			error = EINVAL;
3417 			break;
3418 		}
3419 
3420 		error = pmclog_close(po);
3421 	}
3422 	break;
3423 
3424 	/*
3425 	 * Retrieve hardware configuration.
3426 	 */
3427 
3428 	case PMC_OP_GETCPUINFO:	/* CPU information */
3429 	{
3430 		struct pmc_op_getcpuinfo gci;
3431 		struct pmc_classinfo *pci;
3432 		struct pmc_classdep *pcd;
3433 		int cl;
3434 
3435 		gci.pm_cputype = md->pmd_cputype;
3436 		gci.pm_ncpu    = pmc_cpu_max();
3437 		gci.pm_npmc    = md->pmd_npmc;
3438 		gci.pm_nclass  = md->pmd_nclass;
3439 		pci = gci.pm_classes;
3440 		pcd = md->pmd_classdep;
3441 		for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
3442 			pci->pm_caps  = pcd->pcd_caps;
3443 			pci->pm_class = pcd->pcd_class;
3444 			pci->pm_width = pcd->pcd_width;
3445 			pci->pm_num   = pcd->pcd_num;
3446 		}
3447 		error = copyout(&gci, arg, sizeof(gci));
3448 	}
3449 	break;
3450 
3451 	/*
3452 	 * Retrieve soft events list.
3453 	 */
3454 	case PMC_OP_GETDYNEVENTINFO:
3455 	{
3456 		enum pmc_class			cl;
3457 		enum pmc_event			ev;
3458 		struct pmc_op_getdyneventinfo	*gei;
3459 		struct pmc_dyn_event_descr	dev;
3460 		struct pmc_soft			*ps;
3461 		uint32_t			nevent;
3462 
3463 		sx_assert(&pmc_sx, SX_LOCKED);
3464 
3465 		gei = (struct pmc_op_getdyneventinfo *) arg;
3466 
3467 		if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
3468 			break;
3469 
3470 		/* Only SOFT class is dynamic. */
3471 		if (cl != PMC_CLASS_SOFT) {
3472 			error = EINVAL;
3473 			break;
3474 		}
3475 
3476 		nevent = 0;
3477 		for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) {
3478 			ps = pmc_soft_ev_acquire(ev);
3479 			if (ps == NULL)
3480 				continue;
3481 			bcopy(&ps->ps_ev, &dev, sizeof(dev));
3482 			pmc_soft_ev_release(ps);
3483 
3484 			error = copyout(&dev,
3485 			    &gei->pm_events[nevent],
3486 			    sizeof(struct pmc_dyn_event_descr));
3487 			if (error != 0)
3488 				break;
3489 			nevent++;
3490 		}
3491 		if (error != 0)
3492 			break;
3493 
3494 		error = copyout(&nevent, &gei->pm_nevent,
3495 		    sizeof(nevent));
3496 	}
3497 	break;
3498 
3499 	/*
3500 	 * Get module statistics
3501 	 */
3502 
3503 	case PMC_OP_GETDRIVERSTATS:
3504 	{
3505 		struct pmc_op_getdriverstats gms;
3506 #define CFETCH(a, b, field) a.field = counter_u64_fetch(b.field)
3507 		CFETCH(gms, pmc_stats, pm_intr_ignored);
3508 		CFETCH(gms, pmc_stats, pm_intr_processed);
3509 		CFETCH(gms, pmc_stats, pm_intr_bufferfull);
3510 		CFETCH(gms, pmc_stats, pm_syscalls);
3511 		CFETCH(gms, pmc_stats, pm_syscall_errors);
3512 		CFETCH(gms, pmc_stats, pm_buffer_requests);
3513 		CFETCH(gms, pmc_stats, pm_buffer_requests_failed);
3514 		CFETCH(gms, pmc_stats, pm_log_sweeps);
3515 #undef CFETCH
3516 		error = copyout(&gms, arg, sizeof(gms));
3517 	}
3518 	break;
3519 
3520 
3521 	/*
3522 	 * Retrieve module version number
3523 	 */
3524 
3525 	case PMC_OP_GETMODULEVERSION:
3526 	{
3527 		uint32_t cv, modv;
3528 
3529 		/* retrieve the client's idea of the ABI version */
3530 		if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
3531 			break;
3532 		/* don't service clients newer than our driver */
3533 		modv = PMC_VERSION;
3534 		if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
3535 			error = EPROGMISMATCH;
3536 			break;
3537 		}
3538 		error = copyout(&modv, arg, sizeof(int));
3539 	}
3540 	break;
3541 
3542 
3543 	/*
3544 	 * Retrieve the state of all the PMCs on a given
3545 	 * CPU.
3546 	 */
3547 
3548 	case PMC_OP_GETPMCINFO:
3549 	{
3550 		int ari;
3551 		struct pmc *pm;
3552 		size_t pmcinfo_size;
3553 		uint32_t cpu, n, npmc;
3554 		struct pmc_owner *po;
3555 		struct pmc_binding pb;
3556 		struct pmc_classdep *pcd;
3557 		struct pmc_info *p, *pmcinfo;
3558 		struct pmc_op_getpmcinfo *gpi;
3559 
3560 		PMC_DOWNGRADE_SX();
3561 
3562 		gpi = (struct pmc_op_getpmcinfo *) arg;
3563 
3564 		if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
3565 			break;
3566 
3567 		if (cpu >= pmc_cpu_max()) {
3568 			error = EINVAL;
3569 			break;
3570 		}
3571 
3572 		if (!pmc_cpu_is_active(cpu)) {
3573 			error = ENXIO;
3574 			break;
3575 		}
3576 
3577 		/* switch to CPU 'cpu' */
3578 		pmc_save_cpu_binding(&pb);
3579 		pmc_select_cpu(cpu);
3580 
3581 		npmc = md->pmd_npmc;
3582 
3583 		pmcinfo_size = npmc * sizeof(struct pmc_info);
3584 		pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK);
3585 
3586 		p = pmcinfo;
3587 
3588 		for (n = 0; n < md->pmd_npmc; n++, p++) {
3589 
3590 			pcd = pmc_ri_to_classdep(md, n, &ari);
3591 
3592 			KASSERT(pcd != NULL,
3593 			    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
3594 
3595 			if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
3596 				break;
3597 
3598 			if (PMC_ROW_DISP_IS_STANDALONE(n))
3599 				p->pm_rowdisp = PMC_DISP_STANDALONE;
3600 			else if (PMC_ROW_DISP_IS_THREAD(n))
3601 				p->pm_rowdisp = PMC_DISP_THREAD;
3602 			else
3603 				p->pm_rowdisp = PMC_DISP_FREE;
3604 
3605 			p->pm_ownerpid = -1;
3606 
3607 			if (pm == NULL)	/* no PMC associated */
3608 				continue;
3609 
3610 			po = pm->pm_owner;
3611 
3612 			KASSERT(po->po_owner != NULL,
3613 			    ("[pmc,%d] pmc_owner had a null proc pointer",
3614 				__LINE__));
3615 
3616 			p->pm_ownerpid = po->po_owner->p_pid;
3617 			p->pm_mode     = PMC_TO_MODE(pm);
3618 			p->pm_event    = pm->pm_event;
3619 			p->pm_flags    = pm->pm_flags;
3620 
3621 			if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3622 				p->pm_reloadcount =
3623 				    pm->pm_sc.pm_reloadcount;
3624 		}
3625 
3626 		pmc_restore_cpu_binding(&pb);
3627 
3628 		/* now copy out the PMC info collected */
3629 		if (error == 0)
3630 			error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
3631 
3632 		free(pmcinfo, M_PMC);
3633 	}
3634 	break;
3635 
3636 
3637 	/*
3638 	 * Set the administrative state of a PMC.  I.e. whether
3639 	 * the PMC is to be used or not.
3640 	 */
3641 
3642 	case PMC_OP_PMCADMIN:
3643 	{
3644 		int cpu, ri;
3645 		enum pmc_state request;
3646 		struct pmc_cpu *pc;
3647 		struct pmc_hw *phw;
3648 		struct pmc_op_pmcadmin pma;
3649 		struct pmc_binding pb;
3650 
3651 		sx_assert(&pmc_sx, SX_XLOCKED);
3652 
3653 		KASSERT(td == curthread,
3654 		    ("[pmc,%d] td != curthread", __LINE__));
3655 
3656 		error = priv_check(td, PRIV_PMC_MANAGE);
3657 		if (error)
3658 			break;
3659 
3660 		if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
3661 			break;
3662 
3663 		cpu = pma.pm_cpu;
3664 
3665 		if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
3666 			error = EINVAL;
3667 			break;
3668 		}
3669 
3670 		if (!pmc_cpu_is_active(cpu)) {
3671 			error = ENXIO;
3672 			break;
3673 		}
3674 
3675 		request = pma.pm_state;
3676 
3677 		if (request != PMC_STATE_DISABLED &&
3678 		    request != PMC_STATE_FREE) {
3679 			error = EINVAL;
3680 			break;
3681 		}
3682 
3683 		ri = pma.pm_pmc; /* pmc id == row index */
3684 		if (ri < 0 || ri >= (int) md->pmd_npmc) {
3685 			error = EINVAL;
3686 			break;
3687 		}
3688 
3689 		/*
3690 		 * We can't disable a PMC with a row-index allocated
3691 		 * for process virtual PMCs.
3692 		 */
3693 
3694 		if (PMC_ROW_DISP_IS_THREAD(ri) &&
3695 		    request == PMC_STATE_DISABLED) {
3696 			error = EBUSY;
3697 			break;
3698 		}
3699 
3700 		/*
3701 		 * otherwise, this PMC on this CPU is either free or
3702 		 * in system-wide mode.
3703 		 */
3704 
3705 		pmc_save_cpu_binding(&pb);
3706 		pmc_select_cpu(cpu);
3707 
3708 		pc  = pmc_pcpu[cpu];
3709 		phw = pc->pc_hwpmcs[ri];
3710 
3711 		/*
3712 		 * XXX do we need some kind of 'forced' disable?
3713 		 */
3714 
3715 		if (phw->phw_pmc == NULL) {
3716 			if (request == PMC_STATE_DISABLED &&
3717 			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
3718 				phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
3719 				PMC_MARK_ROW_STANDALONE(ri);
3720 			} else if (request == PMC_STATE_FREE &&
3721 			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
3722 				phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
3723 				PMC_UNMARK_ROW_STANDALONE(ri);
3724 			}
3725 			/* other cases are a no-op */
3726 		} else
3727 			error = EBUSY;
3728 
3729 		pmc_restore_cpu_binding(&pb);
3730 	}
3731 	break;
3732 
3733 
3734 	/*
3735 	 * Allocate a PMC.
3736 	 */
3737 
3738 	case PMC_OP_PMCALLOCATE:
3739 	{
3740 		int adjri, n;
3741 		u_int cpu;
3742 		uint32_t caps;
3743 		struct pmc *pmc;
3744 		enum pmc_mode mode;
3745 		struct pmc_hw *phw;
3746 		struct pmc_binding pb;
3747 		struct pmc_classdep *pcd;
3748 		struct pmc_op_pmcallocate pa;
3749 
3750 		if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
3751 			break;
3752 
3753 		caps = pa.pm_caps;
3754 		mode = pa.pm_mode;
3755 		cpu  = pa.pm_cpu;
3756 
3757 		if ((mode != PMC_MODE_SS  &&  mode != PMC_MODE_SC  &&
3758 		     mode != PMC_MODE_TS  &&  mode != PMC_MODE_TC) ||
3759 		    (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
3760 			error = EINVAL;
3761 			break;
3762 		}
3763 
3764 		/*
3765 		 * Virtual PMCs should only ask for a default CPU.
3766 		 * System mode PMCs need to specify a non-default CPU.
3767 		 */
3768 
3769 		if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3770 		    (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3771 			error = EINVAL;
3772 			break;
3773 		}
3774 
3775 		/*
3776 		 * Check that an inactive CPU is not being asked for.
3777 		 */
3778 
3779 		if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3780 			error = ENXIO;
3781 			break;
3782 		}
3783 
3784 		/*
3785 		 * Refuse an allocation for a system-wide PMC if this
3786 		 * process has been jailed, or if this process lacks
3787 		 * super-user credentials and the sysctl tunable
3788 		 * 'security.bsd.unprivileged_syspmcs' is zero.
3789 		 */
3790 
3791 		if (PMC_IS_SYSTEM_MODE(mode)) {
3792 			if (jailed(curthread->td_ucred)) {
3793 				error = EPERM;
3794 				break;
3795 			}
3796 			if (!pmc_unprivileged_syspmcs) {
3797 				error = priv_check(curthread,
3798 				    PRIV_PMC_SYSTEM);
3799 				if (error)
3800 					break;
3801 			}
3802 		}
3803 
3804 		/*
3805 		 * Look for valid values for 'pm_flags'
3806 		 */
3807 
3808 		if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3809 		    PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3810 			error = EINVAL;
3811 			break;
3812 		}
3813 
3814 		/* process logging options are not allowed for system PMCs */
3815 		if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3816 		    (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3817 			error = EINVAL;
3818 			break;
3819 		}
3820 
3821 		/*
3822 		 * All sampling mode PMCs need to be able to interrupt the
3823 		 * CPU.
3824 		 */
3825 		if (PMC_IS_SAMPLING_MODE(mode))
3826 			caps |= PMC_CAP_INTERRUPT;
3827 
3828 		/* A valid class specifier should have been passed in. */
3829 		pcd = pmc_class_to_classdep(pa.pm_class);
3830 		if (pcd == NULL) {
3831 			error = EINVAL;
3832 			break;
3833 		}
3834 
3835 		/* The requested PMC capabilities should be feasible. */
3836 		if ((pcd->pcd_caps & caps) != caps) {
3837 			error = EOPNOTSUPP;
3838 			break;
3839 		}
3840 
3841 		PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3842 		    pa.pm_ev, caps, mode, cpu);
3843 
3844 		pmc = pmc_allocate_pmc_descriptor();
3845 		pmc->pm_id    = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3846 		    PMC_ID_INVALID);
3847 		pmc->pm_event = pa.pm_ev;
3848 		pmc->pm_state = PMC_STATE_FREE;
3849 		pmc->pm_caps  = caps;
3850 		pmc->pm_flags = pa.pm_flags;
3851 
3852 		/* switch thread to CPU 'cpu' */
3853 		pmc_save_cpu_binding(&pb);
3854 
3855 #define	PMC_IS_SHAREABLE_PMC(cpu, n)				\
3856 	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &		\
3857 	 PMC_PHW_FLAG_IS_SHAREABLE)
3858 #define	PMC_IS_UNALLOCATED(cpu, n)				\
3859 	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3860 
3861 		if (PMC_IS_SYSTEM_MODE(mode)) {
3862 			pmc_select_cpu(cpu);
3863 			for (n = pcd->pcd_ri; n < (int) md->pmd_npmc; n++) {
3864 				pcd = pmc_ri_to_classdep(md, n, &adjri);
3865 				if (pmc_can_allocate_row(n, mode) == 0 &&
3866 				    pmc_can_allocate_rowindex(
3867 					    curthread->td_proc, n, cpu) == 0 &&
3868 				    (PMC_IS_UNALLOCATED(cpu, n) ||
3869 				     PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3870 				    pcd->pcd_allocate_pmc(cpu, adjri, pmc,
3871 					&pa) == 0)
3872 					break;
3873 			}
3874 		} else {
3875 			/* Process virtual mode */
3876 			for (n = pcd->pcd_ri; n < (int) md->pmd_npmc; n++) {
3877 				pcd = pmc_ri_to_classdep(md, n, &adjri);
3878 				if (pmc_can_allocate_row(n, mode) == 0 &&
3879 				    pmc_can_allocate_rowindex(
3880 					    curthread->td_proc, n,
3881 					    PMC_CPU_ANY) == 0 &&
3882 				    pcd->pcd_allocate_pmc(curthread->td_oncpu,
3883 					adjri, pmc, &pa) == 0)
3884 					break;
3885 			}
3886 		}
3887 
3888 #undef	PMC_IS_UNALLOCATED
3889 #undef	PMC_IS_SHAREABLE_PMC
3890 
3891 		pmc_restore_cpu_binding(&pb);
3892 
3893 		if (n == (int) md->pmd_npmc) {
3894 			pmc_destroy_pmc_descriptor(pmc);
3895 			pmc = NULL;
3896 			error = EINVAL;
3897 			break;
3898 		}
3899 
3900 		/* Fill in the correct value in the ID field */
3901 		pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3902 
3903 		PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3904 		    pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3905 
3906 		/* Process mode PMCs with logging enabled need log files */
3907 		if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3908 			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3909 
3910 		/* All system mode sampling PMCs require a log file */
3911 		if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3912 			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3913 
3914 		/*
3915 		 * Configure global pmc's immediately
3916 		 */
3917 
3918 		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3919 
3920 			pmc_save_cpu_binding(&pb);
3921 			pmc_select_cpu(cpu);
3922 
3923 			phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3924 			pcd = pmc_ri_to_classdep(md, n, &adjri);
3925 
3926 			if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3927 			    (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3928 				(void) pcd->pcd_release_pmc(cpu, adjri, pmc);
3929 				pmc_destroy_pmc_descriptor(pmc);
3930 				pmc = NULL;
3931 				pmc_restore_cpu_binding(&pb);
3932 				error = EPERM;
3933 				break;
3934 			}
3935 
3936 			pmc_restore_cpu_binding(&pb);
3937 		}
3938 
3939 		pmc->pm_state    = PMC_STATE_ALLOCATED;
3940 		pmc->pm_class	= pa.pm_class;
3941 
3942 		/*
3943 		 * mark row disposition
3944 		 */
3945 
3946 		if (PMC_IS_SYSTEM_MODE(mode))
3947 			PMC_MARK_ROW_STANDALONE(n);
3948 		else
3949 			PMC_MARK_ROW_THREAD(n);
3950 
3951 		/*
3952 		 * Register this PMC with the current thread as its owner.
3953 		 */
3954 
3955 		if ((error =
3956 		    pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3957 			pmc_release_pmc_descriptor(pmc);
3958 			pmc_destroy_pmc_descriptor(pmc);
3959 			pmc = NULL;
3960 			break;
3961 		}
3962 
3963 		/*
3964 		 * Return the allocated index.
3965 		 */
3966 
3967 		pa.pm_pmcid = pmc->pm_id;
3968 
3969 		error = copyout(&pa, arg, sizeof(pa));
3970 	}
3971 	break;
3972 
3973 
3974 	/*
3975 	 * Attach a PMC to a process.
3976 	 */
3977 
3978 	case PMC_OP_PMCATTACH:
3979 	{
3980 		struct pmc *pm;
3981 		struct proc *p;
3982 		struct pmc_op_pmcattach a;
3983 
3984 		sx_assert(&pmc_sx, SX_XLOCKED);
3985 
3986 		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3987 			break;
3988 
3989 		if (a.pm_pid < 0) {
3990 			error = EINVAL;
3991 			break;
3992 		} else if (a.pm_pid == 0)
3993 			a.pm_pid = td->td_proc->p_pid;
3994 
3995 		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3996 			break;
3997 
3998 		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3999 			error = EINVAL;
4000 			break;
4001 		}
4002 
4003 		/* PMCs may be (re)attached only when allocated or stopped */
4004 		if (pm->pm_state == PMC_STATE_RUNNING) {
4005 			error = EBUSY;
4006 			break;
4007 		} else if (pm->pm_state != PMC_STATE_ALLOCATED &&
4008 		    pm->pm_state != PMC_STATE_STOPPED) {
4009 			error = EINVAL;
4010 			break;
4011 		}
4012 
4013 		/* lookup pid */
4014 		if ((p = pfind(a.pm_pid)) == NULL) {
4015 			error = ESRCH;
4016 			break;
4017 		}
4018 
4019 		/*
4020 		 * Ignore processes that are working on exiting.
4021 		 */
4022 		if (p->p_flag & P_WEXIT) {
4023 			error = ESRCH;
4024 			PROC_UNLOCK(p);	/* pfind() returns a locked process */
4025 			break;
4026 		}
4027 
4028 		/*
4029 		 * we are allowed to attach a PMC to a process if
4030 		 * we can debug it.
4031 		 */
4032 		error = p_candebug(curthread, p);
4033 
4034 		PROC_UNLOCK(p);
4035 
4036 		if (error == 0)
4037 			error = pmc_attach_process(p, pm);
4038 	}
4039 	break;
4040 
4041 
4042 	/*
4043 	 * Detach an attached PMC from a process.
4044 	 */
4045 
4046 	case PMC_OP_PMCDETACH:
4047 	{
4048 		struct pmc *pm;
4049 		struct proc *p;
4050 		struct pmc_op_pmcattach a;
4051 
4052 		if ((error = copyin(arg, &a, sizeof(a))) != 0)
4053 			break;
4054 
4055 		if (a.pm_pid < 0) {
4056 			error = EINVAL;
4057 			break;
4058 		} else if (a.pm_pid == 0)
4059 			a.pm_pid = td->td_proc->p_pid;
4060 
4061 		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
4062 			break;
4063 
4064 		if ((p = pfind(a.pm_pid)) == NULL) {
4065 			error = ESRCH;
4066 			break;
4067 		}
4068 
4069 		/*
4070 		 * Treat processes that are in the process of exiting
4071 		 * as if they were not present.
4072 		 */
4073 
4074 		if (p->p_flag & P_WEXIT)
4075 			error = ESRCH;
4076 
4077 		PROC_UNLOCK(p);	/* pfind() returns a locked process */
4078 
4079 		if (error == 0)
4080 			error = pmc_detach_process(p, pm);
4081 	}
4082 	break;
4083 
4084 
4085 	/*
4086 	 * Retrieve the MSR number associated with the counter
4087 	 * 'pmc_id'.  This allows processes to directly use RDPMC
4088 	 * instructions to read their PMCs, without the overhead of a
4089 	 * system call.
4090 	 */
4091 
4092 	case PMC_OP_PMCGETMSR:
4093 	{
4094 		int adjri, ri;
4095 		struct pmc *pm;
4096 		struct pmc_target *pt;
4097 		struct pmc_op_getmsr gm;
4098 		struct pmc_classdep *pcd;
4099 
4100 		PMC_DOWNGRADE_SX();
4101 
4102 		if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
4103 			break;
4104 
4105 		if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
4106 			break;
4107 
4108 		/*
4109 		 * The allocated PMC has to be a process virtual PMC,
4110 		 * i.e., of type MODE_T[CS].  Global PMCs can only be
4111 		 * read using the PMCREAD operation since they may be
4112 		 * allocated on a different CPU than the one we could
4113 		 * be running on at the time of the RDPMC instruction.
4114 		 *
4115 		 * The GETMSR operation is not allowed for PMCs that
4116 		 * are inherited across processes.
4117 		 */
4118 
4119 		if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
4120 		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
4121 			error = EINVAL;
4122 			break;
4123 		}
4124 
4125 		/*
4126 		 * It only makes sense to use a RDPMC (or its
4127 		 * equivalent instruction on non-x86 architectures) on
4128 		 * a process that has allocated and attached a PMC to
4129 		 * itself.  Conversely the PMC is only allowed to have
4130 		 * one process attached to it -- its owner.
4131 		 */
4132 
4133 		if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
4134 		    LIST_NEXT(pt, pt_next) != NULL ||
4135 		    pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
4136 			error = EINVAL;
4137 			break;
4138 		}
4139 
4140 		ri = PMC_TO_ROWINDEX(pm);
4141 		pcd = pmc_ri_to_classdep(md, ri, &adjri);
4142 
4143 		/* PMC class has no 'GETMSR' support */
4144 		if (pcd->pcd_get_msr == NULL) {
4145 			error = ENOSYS;
4146 			break;
4147 		}
4148 
4149 		if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
4150 			break;
4151 
4152 		if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
4153 			break;
4154 
4155 		/*
4156 		 * Mark our process as using MSRs.  Update machine
4157 		 * state using a forced context switch.
4158 		 */
4159 
4160 		pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
4161 		pmc_force_context_switch();
4162 
4163 	}
4164 	break;
4165 
4166 	/*
4167 	 * Release an allocated PMC
4168 	 */
4169 
4170 	case PMC_OP_PMCRELEASE:
4171 	{
4172 		pmc_id_t pmcid;
4173 		struct pmc *pm;
4174 		struct pmc_owner *po;
4175 		struct pmc_op_simple sp;
4176 
4177 		/*
4178 		 * Find PMC pointer for the named PMC.
4179 		 *
4180 		 * Use pmc_release_pmc_descriptor() to switch off the
4181 		 * PMC, remove all its target threads, and remove the
4182 		 * PMC from its owner's list.
4183 		 *
4184 		 * Remove the owner record if this is the last PMC
4185 		 * owned.
4186 		 *
4187 		 * Free up space.
4188 		 */
4189 
4190 		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4191 			break;
4192 
4193 		pmcid = sp.pm_pmcid;
4194 
4195 		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4196 			break;
4197 
4198 		po = pm->pm_owner;
4199 		pmc_release_pmc_descriptor(pm);
4200 		pmc_maybe_remove_owner(po);
4201 		pmc_destroy_pmc_descriptor(pm);
4202 	}
4203 	break;
4204 
4205 
4206 	/*
4207 	 * Read and/or write a PMC.
4208 	 */
4209 
4210 	case PMC_OP_PMCRW:
4211 	{
4212 		int adjri;
4213 		struct pmc *pm;
4214 		uint32_t cpu, ri;
4215 		pmc_value_t oldvalue;
4216 		struct pmc_binding pb;
4217 		struct pmc_op_pmcrw prw;
4218 		struct pmc_classdep *pcd;
4219 		struct pmc_op_pmcrw *pprw;
4220 
4221 		PMC_DOWNGRADE_SX();
4222 
4223 		if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
4224 			break;
4225 
4226 		ri = 0;
4227 		PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
4228 		    prw.pm_flags);
4229 
4230 		/* must have at least one flag set */
4231 		if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
4232 			error = EINVAL;
4233 			break;
4234 		}
4235 
4236 		/* locate pmc descriptor */
4237 		if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
4238 			break;
4239 
4240 		/* Can't read a PMC that hasn't been started. */
4241 		if (pm->pm_state != PMC_STATE_ALLOCATED &&
4242 		    pm->pm_state != PMC_STATE_STOPPED &&
4243 		    pm->pm_state != PMC_STATE_RUNNING) {
4244 			error = EINVAL;
4245 			break;
4246 		}
4247 
4248 		/* writing a new value is allowed only for 'STOPPED' pmcs */
4249 		if (pm->pm_state == PMC_STATE_RUNNING &&
4250 		    (prw.pm_flags & PMC_F_NEWVALUE)) {
4251 			error = EBUSY;
4252 			break;
4253 		}
4254 
4255 		if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
4256 
4257 			/*
4258 			 * If this PMC is attached to its owner (i.e.,
4259 			 * the process requesting this operation) and
4260 			 * is running, then attempt to get an
4261 			 * upto-date reading from hardware for a READ.
4262 			 * Writes are only allowed when the PMC is
4263 			 * stopped, so only update the saved value
4264 			 * field.
4265 			 *
4266 			 * If the PMC is not running, or is not
4267 			 * attached to its owner, read/write to the
4268 			 * savedvalue field.
4269 			 */
4270 
4271 			ri = PMC_TO_ROWINDEX(pm);
4272 			pcd = pmc_ri_to_classdep(md, ri, &adjri);
4273 
4274 			mtx_pool_lock_spin(pmc_mtxpool, pm);
4275 			cpu = curthread->td_oncpu;
4276 
4277 			if (prw.pm_flags & PMC_F_OLDVALUE) {
4278 				if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
4279 				    (pm->pm_state == PMC_STATE_RUNNING))
4280 					error = (*pcd->pcd_read_pmc)(cpu, adjri,
4281 					    &oldvalue);
4282 				else
4283 					oldvalue = pm->pm_gv.pm_savedvalue;
4284 			}
4285 			if (prw.pm_flags & PMC_F_NEWVALUE)
4286 				pm->pm_gv.pm_savedvalue = prw.pm_value;
4287 
4288 			mtx_pool_unlock_spin(pmc_mtxpool, pm);
4289 
4290 		} else { /* System mode PMCs */
4291 			cpu = PMC_TO_CPU(pm);
4292 			ri  = PMC_TO_ROWINDEX(pm);
4293 			pcd = pmc_ri_to_classdep(md, ri, &adjri);
4294 
4295 			if (!pmc_cpu_is_active(cpu)) {
4296 				error = ENXIO;
4297 				break;
4298 			}
4299 
4300 			/* move this thread to CPU 'cpu' */
4301 			pmc_save_cpu_binding(&pb);
4302 			pmc_select_cpu(cpu);
4303 
4304 			critical_enter();
4305 			/* save old value */
4306 			if (prw.pm_flags & PMC_F_OLDVALUE)
4307 				if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
4308 					 &oldvalue)))
4309 					goto error;
4310 			/* write out new value */
4311 			if (prw.pm_flags & PMC_F_NEWVALUE)
4312 				error = (*pcd->pcd_write_pmc)(cpu, adjri,
4313 				    prw.pm_value);
4314 		error:
4315 			critical_exit();
4316 			pmc_restore_cpu_binding(&pb);
4317 			if (error)
4318 				break;
4319 		}
4320 
4321 		pprw = (struct pmc_op_pmcrw *) arg;
4322 
4323 #ifdef	HWPMC_DEBUG
4324 		if (prw.pm_flags & PMC_F_NEWVALUE)
4325 			PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
4326 			    ri, prw.pm_value, oldvalue);
4327 		else if (prw.pm_flags & PMC_F_OLDVALUE)
4328 			PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
4329 #endif
4330 
4331 		/* return old value if requested */
4332 		if (prw.pm_flags & PMC_F_OLDVALUE)
4333 			if ((error = copyout(&oldvalue, &pprw->pm_value,
4334 				 sizeof(prw.pm_value))))
4335 				break;
4336 
4337 	}
4338 	break;
4339 
4340 
4341 	/*
4342 	 * Set the sampling rate for a sampling mode PMC and the
4343 	 * initial count for a counting mode PMC.
4344 	 */
4345 
4346 	case PMC_OP_PMCSETCOUNT:
4347 	{
4348 		struct pmc *pm;
4349 		struct pmc_op_pmcsetcount sc;
4350 
4351 		PMC_DOWNGRADE_SX();
4352 
4353 		if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
4354 			break;
4355 
4356 		if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
4357 			break;
4358 
4359 		if (pm->pm_state == PMC_STATE_RUNNING) {
4360 			error = EBUSY;
4361 			break;
4362 		}
4363 
4364 		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
4365 			pm->pm_sc.pm_reloadcount = sc.pm_count;
4366 		else
4367 			pm->pm_sc.pm_initial = sc.pm_count;
4368 	}
4369 	break;
4370 
4371 
4372 	/*
4373 	 * Start a PMC.
4374 	 */
4375 
4376 	case PMC_OP_PMCSTART:
4377 	{
4378 		pmc_id_t pmcid;
4379 		struct pmc *pm;
4380 		struct pmc_op_simple sp;
4381 
4382 		sx_assert(&pmc_sx, SX_XLOCKED);
4383 
4384 		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4385 			break;
4386 
4387 		pmcid = sp.pm_pmcid;
4388 
4389 		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4390 			break;
4391 
4392 		KASSERT(pmcid == pm->pm_id,
4393 		    ("[pmc,%d] pmcid %x != id %x", __LINE__,
4394 			pm->pm_id, pmcid));
4395 
4396 		if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
4397 			break;
4398 		else if (pm->pm_state != PMC_STATE_STOPPED &&
4399 		    pm->pm_state != PMC_STATE_ALLOCATED) {
4400 			error = EINVAL;
4401 			break;
4402 		}
4403 
4404 		error = pmc_start(pm);
4405 	}
4406 	break;
4407 
4408 
4409 	/*
4410 	 * Stop a PMC.
4411 	 */
4412 
4413 	case PMC_OP_PMCSTOP:
4414 	{
4415 		pmc_id_t pmcid;
4416 		struct pmc *pm;
4417 		struct pmc_op_simple sp;
4418 
4419 		PMC_DOWNGRADE_SX();
4420 
4421 		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4422 			break;
4423 
4424 		pmcid = sp.pm_pmcid;
4425 
4426 		/*
4427 		 * Mark the PMC as inactive and invoke the MD stop
4428 		 * routines if needed.
4429 		 */
4430 
4431 		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4432 			break;
4433 
4434 		KASSERT(pmcid == pm->pm_id,
4435 		    ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
4436 			pm->pm_id, pmcid));
4437 
4438 		if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
4439 			break;
4440 		else if (pm->pm_state != PMC_STATE_RUNNING) {
4441 			error = EINVAL;
4442 			break;
4443 		}
4444 
4445 		error = pmc_stop(pm);
4446 	}
4447 	break;
4448 
4449 
4450 	/*
4451 	 * Write a user supplied value to the log file.
4452 	 */
4453 
4454 	case PMC_OP_WRITELOG:
4455 	{
4456 		struct pmc_op_writelog wl;
4457 		struct pmc_owner *po;
4458 
4459 		PMC_DOWNGRADE_SX();
4460 
4461 		if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
4462 			break;
4463 
4464 		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
4465 			error = EINVAL;
4466 			break;
4467 		}
4468 
4469 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
4470 			error = EINVAL;
4471 			break;
4472 		}
4473 
4474 		error = pmclog_process_userlog(po, &wl);
4475 	}
4476 	break;
4477 
4478 
4479 	default:
4480 		error = EINVAL;
4481 		break;
4482 	}
4483 
4484 	if (is_sx_downgraded)
4485 		sx_sunlock(&pmc_sx);
4486 	else
4487 		sx_xunlock(&pmc_sx);
4488 done_syscall:
4489 	if (error)
4490 		counter_u64_add(pmc_stats.pm_syscall_errors, 1);
4491 
4492 	return (error);
4493 }
4494 
4495 /*
4496  * Helper functions
4497  */
4498 
4499 
4500 /*
4501  * Mark the thread as needing callchain capture and post an AST.  The
4502  * actual callchain capture will be done in a context where it is safe
4503  * to take page faults.
4504  */
4505 
4506 static void
4507 pmc_post_callchain_callback(void)
4508 {
4509 	struct thread *td;
4510 
4511 	td = curthread;
4512 
4513 	/*
4514 	 * If there is multiple PMCs for the same interrupt ignore new post
4515 	 */
4516 	if (td->td_pflags & TDP_CALLCHAIN)
4517 		return;
4518 
4519 	/*
4520 	 * Mark this thread as needing callchain capture.
4521 	 * `td->td_pflags' will be safe to touch because this thread
4522 	 * was in user space when it was interrupted.
4523 	 */
4524 	td->td_pflags |= TDP_CALLCHAIN;
4525 
4526 	/*
4527 	 * Don't let this thread migrate between CPUs until callchain
4528 	 * capture completes.
4529 	 */
4530 	sched_pin();
4531 
4532 	return;
4533 }
4534 
4535 /*
4536  * Interrupt processing.
4537  *
4538  * Find a free slot in the per-cpu array of samples and capture the
4539  * current callchain there.  If a sample was successfully added, a bit
4540  * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4541  * needs to be invoked from the clock handler.
4542  *
4543  * This function is meant to be called from an NMI handler.  It cannot
4544  * use any of the locking primitives supplied by the OS.
4545  */
4546 
4547 int
4548 pmc_process_interrupt(int cpu, int ring, struct pmc *pm, struct trapframe *tf,
4549     int inuserspace)
4550 {
4551 	int error, callchaindepth;
4552 	struct thread *td;
4553 	struct pmc_sample *ps;
4554 	struct pmc_samplebuffer *psb;
4555 
4556 	error = 0;
4557 
4558 	/*
4559 	 * Allocate space for a sample buffer.
4560 	 */
4561 	psb = pmc_pcpu[cpu]->pc_sb[ring];
4562 
4563 	ps = psb->ps_write;
4564 	if (ps->ps_nsamples) {	/* in use, reader hasn't caught up */
4565 		pm->pm_pcpu_state[cpu].pps_stalled = 1;
4566 		counter_u64_add(pmc_stats.pm_intr_bufferfull, 1);
4567 		PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
4568 		    cpu, pm, (void *) tf, inuserspace,
4569 		    (int) (psb->ps_write - psb->ps_samples),
4570 		    (int) (psb->ps_read - psb->ps_samples));
4571 		callchaindepth = 1;
4572 		error = ENOMEM;
4573 		goto done;
4574 	}
4575 
4576 
4577 	/* Fill in entry. */
4578 	PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
4579 	    (void *) tf, inuserspace,
4580 	    (int) (psb->ps_write - psb->ps_samples),
4581 	    (int) (psb->ps_read - psb->ps_samples));
4582 
4583 	KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
4584 	    ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
4585 		 (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4586 
4587 	counter_u64_add(pm->pm_runcount, 1);	/* hold onto PMC */
4588 
4589 	ps->ps_pmc = pm;
4590 	ps->ps_pid = -1;
4591 	ps->ps_tid = -1;
4592 	if ((td = curthread) != NULL) {
4593 		ps->ps_tid = td->td_tid;
4594 		if (td->td_proc)
4595 			ps->ps_pid = td->td_proc->p_pid;
4596 	}
4597 	ps->ps_cpu = cpu;
4598 	ps->ps_td = td;
4599 	ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4600 
4601 	callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4602 	    pmc_callchaindepth : 1;
4603 
4604 	if (callchaindepth == 1)
4605 		ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
4606 	else {
4607 		/*
4608 		 * Kernel stack traversals can be done immediately,
4609 		 * while we defer to an AST for user space traversals.
4610 		 */
4611 		if (!inuserspace) {
4612 			callchaindepth =
4613 			    pmc_save_kernel_callchain(ps->ps_pc,
4614 				callchaindepth, tf);
4615 		} else {
4616 			pmc_post_callchain_callback();
4617 			callchaindepth = PMC_SAMPLE_INUSE;
4618 		}
4619 	}
4620 
4621 	ps->ps_nsamples = callchaindepth;	/* mark entry as in use */
4622 
4623 	/* increment write pointer, modulo ring buffer size */
4624 	ps++;
4625 	if (ps == psb->ps_fence)
4626 		psb->ps_write = psb->ps_samples;
4627 	else
4628 		psb->ps_write = ps;
4629 
4630  done:
4631 	/* mark CPU as needing processing */
4632 	if (callchaindepth != PMC_SAMPLE_INUSE)
4633 		DPCPU_SET(pmc_sampled, 1);
4634 
4635 	return (error);
4636 }
4637 
4638 /*
4639  * Capture a user call chain.  This function will be called from ast()
4640  * before control returns to userland and before the process gets
4641  * rescheduled.
4642  */
4643 
4644 static void
4645 pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4646 {
4647 	struct pmc *pm;
4648 	struct thread *td;
4649 	struct pmc_sample *ps, *ps_end;
4650 	struct pmc_samplebuffer *psb;
4651 #ifdef	INVARIANTS
4652 	int ncallchains;
4653 	int nfree;
4654 #endif
4655 
4656 	psb = pmc_pcpu[cpu]->pc_sb[ring];
4657 	td = curthread;
4658 
4659 	KASSERT(td->td_pflags & TDP_CALLCHAIN,
4660 	    ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
4661 		__LINE__));
4662 
4663 #ifdef	INVARIANTS
4664 	ncallchains = 0;
4665 	nfree = 0;
4666 #endif
4667 
4668 	/*
4669 	 * Iterate through all deferred callchain requests.
4670 	 * Walk from the current read pointer to the current
4671 	 * write pointer.
4672 	 */
4673 
4674 	ps = psb->ps_read;
4675 	ps_end = psb->ps_write;
4676 	do {
4677 #ifdef	INVARIANTS
4678 		if ((ps->ps_pmc == NULL) ||
4679 		    (ps->ps_pmc->pm_state != PMC_STATE_RUNNING))
4680 			nfree++;
4681 #endif
4682 		if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
4683 			goto next;
4684 		if (ps->ps_td != td)
4685 			goto next;
4686 
4687 		KASSERT(ps->ps_cpu == cpu,
4688 		    ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
4689 			ps->ps_cpu, PCPU_GET(cpuid)));
4690 
4691 		pm = ps->ps_pmc;
4692 
4693 		KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
4694 		    ("[pmc,%d] Retrieving callchain for PMC that doesn't "
4695 			"want it", __LINE__));
4696 
4697 		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4698 		    ("[pmc,%d] runcount %ld", __LINE__, (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4699 
4700 		/*
4701 		 * Retrieve the callchain and mark the sample buffer
4702 		 * as 'processable' by the timer tick sweep code.
4703 		 */
4704 		ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
4705 		    pmc_callchaindepth, tf);
4706 
4707 #ifdef	INVARIANTS
4708 		ncallchains++;
4709 #endif
4710 
4711 next:
4712 		/* increment the pointer, modulo sample ring size */
4713 		if (++ps == psb->ps_fence)
4714 			ps = psb->ps_samples;
4715 	} while (ps != ps_end);
4716 
4717 #ifdef	INVARIANTS
4718 	KASSERT(ncallchains > 0 || nfree > 0,
4719 	    ("[pmc,%d] cpu %d didn't find a sample to collect", __LINE__,
4720 		cpu));
4721 #endif
4722 
4723 	KASSERT(td->td_pinned == 1,
4724 	    ("[pmc,%d] invalid td_pinned value", __LINE__));
4725 	sched_unpin();	/* Can migrate safely now. */
4726 
4727 	/* mark CPU as needing processing */
4728 	DPCPU_SET(pmc_sampled, 1);
4729 }
4730 
4731 /*
4732  * Process saved PC samples.
4733  */
4734 
4735 static void
4736 pmc_process_samples(int cpu, int ring)
4737 {
4738 	struct pmc *pm;
4739 	int adjri, n;
4740 	struct thread *td;
4741 	struct pmc_owner *po;
4742 	struct pmc_sample *ps;
4743 	struct pmc_classdep *pcd;
4744 	struct pmc_samplebuffer *psb;
4745 
4746 	KASSERT(PCPU_GET(cpuid) == cpu,
4747 	    ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4748 		PCPU_GET(cpuid), cpu));
4749 
4750 	psb = pmc_pcpu[cpu]->pc_sb[ring];
4751 
4752 	for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
4753 
4754 		ps = psb->ps_read;
4755 		if (ps->ps_nsamples == PMC_SAMPLE_FREE)
4756 			break;
4757 
4758 		pm = ps->ps_pmc;
4759 
4760 		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4761 		    ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
4762 			 (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4763 
4764 		po = pm->pm_owner;
4765 
4766 		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4767 		    ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4768 			pm, PMC_TO_MODE(pm)));
4769 
4770 		/* Ignore PMCs that have been switched off */
4771 		if (pm->pm_state != PMC_STATE_RUNNING)
4772 			goto entrydone;
4773 
4774 		/* If there is a pending AST wait for completion */
4775 		if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
4776 			/* Need a rescan at a later time. */
4777 			DPCPU_SET(pmc_sampled, 1);
4778 			break;
4779 		}
4780 
4781 		PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4782 		    pm, ps->ps_nsamples, ps->ps_flags,
4783 		    (int) (psb->ps_write - psb->ps_samples),
4784 		    (int) (psb->ps_read - psb->ps_samples));
4785 
4786 		/*
4787 		 * If this is a process-mode PMC that is attached to
4788 		 * its owner, and if the PC is in user mode, update
4789 		 * profiling statistics like timer-based profiling
4790 		 * would have done.
4791 		 */
4792 		if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4793 			if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4794 				td = FIRST_THREAD_IN_PROC(po->po_owner);
4795 				addupc_intr(td, ps->ps_pc[0], 1);
4796 			}
4797 			goto entrydone;
4798 		}
4799 
4800 		/*
4801 		 * Otherwise, this is either a sampling mode PMC that
4802 		 * is attached to a different process than its owner,
4803 		 * or a system-wide sampling PMC.  Dispatch a log
4804 		 * entry to the PMC's owner process.
4805 		 */
4806 		pmclog_process_callchain(pm, ps);
4807 
4808 	entrydone:
4809 		ps->ps_nsamples = 0; /* mark entry as free */
4810 		counter_u64_add(pm->pm_runcount, -1);
4811 
4812 		/* increment read pointer, modulo sample size */
4813 		if (++ps == psb->ps_fence)
4814 			psb->ps_read = psb->ps_samples;
4815 		else
4816 			psb->ps_read = ps;
4817 	}
4818 
4819 	counter_u64_add(pmc_stats.pm_log_sweeps, 1);
4820 
4821 	/* Do not re-enable stalled PMCs if we failed to process any samples */
4822 	if (n == 0)
4823 		return;
4824 
4825 	/*
4826 	 * Restart any stalled sampling PMCs on this CPU.
4827 	 *
4828 	 * If the NMI handler sets the pm_stalled field of a PMC after
4829 	 * the check below, we'll end up processing the stalled PMC at
4830 	 * the next hardclock tick.
4831 	 */
4832 	for (n = 0; n < md->pmd_npmc; n++) {
4833 		pcd = pmc_ri_to_classdep(md, n, &adjri);
4834 		KASSERT(pcd != NULL,
4835 		    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4836 		(void) (*pcd->pcd_get_config)(cpu,adjri,&pm);
4837 
4838 		if (pm == NULL ||			 /* !cfg'ed */
4839 		    pm->pm_state != PMC_STATE_RUNNING || /* !active */
4840 		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4841 			!pm->pm_pcpu_state[cpu].pps_cpustate  || /* !desired */
4842 		    !pm->pm_pcpu_state[cpu].pps_stalled) /* !stalled */
4843 			continue;
4844 
4845 		pm->pm_pcpu_state[cpu].pps_stalled = 0;
4846 		(*pcd->pcd_start_pmc)(cpu, adjri);
4847 	}
4848 }
4849 
4850 /*
4851  * Event handlers.
4852  */
4853 
4854 /*
4855  * Handle a process exit.
4856  *
4857  * Remove this process from all hash tables.  If this process
4858  * owned any PMCs, turn off those PMCs and deallocate them,
4859  * removing any associations with target processes.
4860  *
4861  * This function will be called by the last 'thread' of a
4862  * process.
4863  *
4864  * XXX This eventhandler gets called early in the exit process.
4865  * Consider using a 'hook' invocation from thread_exit() or equivalent
4866  * spot.  Another negative is that kse_exit doesn't seem to call
4867  * exit1() [??].
4868  *
4869  */
4870 
4871 static void
4872 pmc_process_exit(void *arg __unused, struct proc *p)
4873 {
4874 	struct pmc *pm;
4875 	int adjri, cpu;
4876 	unsigned int ri;
4877 	int is_using_hwpmcs;
4878 	struct pmc_owner *po;
4879 	struct pmc_process *pp;
4880 	struct pmc_classdep *pcd;
4881 	pmc_value_t newvalue, tmp;
4882 
4883 	PROC_LOCK(p);
4884 	is_using_hwpmcs = p->p_flag & P_HWPMC;
4885 	PROC_UNLOCK(p);
4886 
4887 	/*
4888 	 * Log a sysexit event to all SS PMC owners.
4889 	 */
4890 	epoch_enter_preempt(global_epoch_preempt);
4891 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4892 	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4893 		    pmclog_process_sysexit(po, p->p_pid);
4894 	epoch_exit_preempt(global_epoch_preempt);
4895 
4896 	if (!is_using_hwpmcs)
4897 		return;
4898 
4899 	PMC_GET_SX_XLOCK();
4900 	PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4901 	    p->p_comm);
4902 
4903 	/*
4904 	 * Since this code is invoked by the last thread in an exiting
4905 	 * process, we would have context switched IN at some prior
4906 	 * point.  However, with PREEMPTION, kernel mode context
4907 	 * switches may happen any time, so we want to disable a
4908 	 * context switch OUT till we get any PMCs targeting this
4909 	 * process off the hardware.
4910 	 *
4911 	 * We also need to atomically remove this process'
4912 	 * entry from our target process hash table, using
4913 	 * PMC_FLAG_REMOVE.
4914 	 */
4915 	PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4916 	    p->p_comm);
4917 
4918 	critical_enter(); /* no preemption */
4919 
4920 	cpu = curthread->td_oncpu;
4921 
4922 	if ((pp = pmc_find_process_descriptor(p,
4923 		 PMC_FLAG_REMOVE)) != NULL) {
4924 
4925 		PMCDBG2(PRC,EXT,2,
4926 		    "process-exit proc=%p pmc-process=%p", p, pp);
4927 
4928 		/*
4929 		 * The exiting process could the target of
4930 		 * some PMCs which will be running on
4931 		 * currently executing CPU.
4932 		 *
4933 		 * We need to turn these PMCs off like we
4934 		 * would do at context switch OUT time.
4935 		 */
4936 		for (ri = 0; ri < md->pmd_npmc; ri++) {
4937 
4938 			/*
4939 			 * Pick up the pmc pointer from hardware
4940 			 * state similar to the CSW_OUT code.
4941 			 */
4942 			pm = NULL;
4943 
4944 			pcd = pmc_ri_to_classdep(md, ri, &adjri);
4945 
4946 			(void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
4947 
4948 			PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4949 
4950 			if (pm == NULL ||
4951 			    !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4952 				continue;
4953 
4954 			PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4955 			    "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4956 			    pm, pm->pm_state);
4957 
4958 			KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4959 			    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4960 				__LINE__, PMC_TO_ROWINDEX(pm), ri));
4961 
4962 			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4963 			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4964 				__LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4965 
4966 			KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4967 			    ("[pmc,%d] bad runcount ri %d rc %ld",
4968 				 __LINE__, ri, (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4969 
4970 			/*
4971 			 * Change desired state, and then stop if not
4972 			 * stalled. This two-step dance should avoid
4973 			 * race conditions where an interrupt re-enables
4974 			 * the PMC after this code has already checked
4975 			 * the pm_stalled flag.
4976 			 */
4977 			if (pm->pm_pcpu_state[cpu].pps_cpustate) {
4978 				pm->pm_pcpu_state[cpu].pps_cpustate = 0;
4979 				if (!pm->pm_pcpu_state[cpu].pps_stalled) {
4980 					(void) pcd->pcd_stop_pmc(cpu, adjri);
4981 
4982 					if (PMC_TO_MODE(pm) == PMC_MODE_TC) {
4983 						pcd->pcd_read_pmc(cpu, adjri,
4984 						    &newvalue);
4985 						tmp = newvalue -
4986 						    PMC_PCPU_SAVED(cpu,ri);
4987 
4988 						mtx_pool_lock_spin(pmc_mtxpool,
4989 						    pm);
4990 						pm->pm_gv.pm_savedvalue += tmp;
4991 						pp->pp_pmcs[ri].pp_pmcval +=
4992 						    tmp;
4993 						mtx_pool_unlock_spin(
4994 						    pmc_mtxpool, pm);
4995 					}
4996 				}
4997 			}
4998 
4999 			counter_u64_add(pm->pm_runcount, -1);
5000 
5001 			KASSERT((int) counter_u64_fetch(pm->pm_runcount) >= 0,
5002 			    ("[pmc,%d] runcount is %d", __LINE__, ri));
5003 
5004 			(void) pcd->pcd_config_pmc(cpu, adjri, NULL);
5005 		}
5006 
5007 		/*
5008 		 * Inform the MD layer of this pseudo "context switch
5009 		 * out"
5010 		 */
5011 		(void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
5012 
5013 		critical_exit(); /* ok to be pre-empted now */
5014 
5015 		/*
5016 		 * Unlink this process from the PMCs that are
5017 		 * targeting it.  This will send a signal to
5018 		 * all PMC owner's whose PMCs are orphaned.
5019 		 *
5020 		 * Log PMC value at exit time if requested.
5021 		 */
5022 		for (ri = 0; ri < md->pmd_npmc; ri++)
5023 			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
5024 				if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
5025 				    PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
5026 					pmclog_process_procexit(pm, pp);
5027 				pmc_unlink_target_process(pm, pp);
5028 			}
5029 		free(pp, M_PMC);
5030 
5031 	} else
5032 		critical_exit(); /* pp == NULL */
5033 
5034 
5035 	/*
5036 	 * If the process owned PMCs, free them up and free up
5037 	 * memory.
5038 	 */
5039 	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
5040 		pmc_remove_owner(po);
5041 		pmc_destroy_owner_descriptor(po);
5042 	}
5043 
5044 	sx_xunlock(&pmc_sx);
5045 }
5046 
5047 /*
5048  * Handle a process fork.
5049  *
5050  * If the parent process 'p1' is under HWPMC monitoring, then copy
5051  * over any attached PMCs that have 'do_descendants' semantics.
5052  */
5053 
5054 static void
5055 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
5056     int flags)
5057 {
5058 	int is_using_hwpmcs;
5059 	unsigned int ri;
5060 	uint32_t do_descendants;
5061 	struct pmc *pm;
5062 	struct pmc_owner *po;
5063 	struct pmc_process *ppnew, *ppold;
5064 
5065 	(void) flags;		/* unused parameter */
5066 
5067 	PROC_LOCK(p1);
5068 	is_using_hwpmcs = p1->p_flag & P_HWPMC;
5069 	PROC_UNLOCK(p1);
5070 
5071 	/*
5072 	 * If there are system-wide sampling PMCs active, we need to
5073 	 * log all fork events to their owner's logs.
5074 	 */
5075 	epoch_enter_preempt(global_epoch_preempt);
5076 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5077 	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5078 		    pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
5079 	epoch_exit_preempt(global_epoch_preempt);
5080 
5081 	if (!is_using_hwpmcs)
5082 		return;
5083 
5084 	PMC_GET_SX_XLOCK();
5085 	PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
5086 	    p1->p_pid, p1->p_comm, newproc);
5087 
5088 	/*
5089 	 * If the parent process (curthread->td_proc) is a
5090 	 * target of any PMCs, look for PMCs that are to be
5091 	 * inherited, and link these into the new process
5092 	 * descriptor.
5093 	 */
5094 	if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
5095 		 PMC_FLAG_NONE)) == NULL)
5096 		goto done;		/* nothing to do */
5097 
5098 	do_descendants = 0;
5099 	for (ri = 0; ri < md->pmd_npmc; ri++)
5100 		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
5101 			do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
5102 	if (do_descendants == 0) /* nothing to do */
5103 		goto done;
5104 
5105 	/*
5106 	 * Now mark the new process as being tracked by this driver.
5107 	 */
5108 	PROC_LOCK(newproc);
5109 	newproc->p_flag |= P_HWPMC;
5110 	PROC_UNLOCK(newproc);
5111 
5112 	/* allocate a descriptor for the new process  */
5113 	if ((ppnew = pmc_find_process_descriptor(newproc,
5114 		 PMC_FLAG_ALLOCATE)) == NULL)
5115 		goto done;
5116 
5117 	/*
5118 	 * Run through all PMCs that were targeting the old process
5119 	 * and which specified F_DESCENDANTS and attach them to the
5120 	 * new process.
5121 	 *
5122 	 * Log the fork event to all owners of PMCs attached to this
5123 	 * process, if not already logged.
5124 	 */
5125 	for (ri = 0; ri < md->pmd_npmc; ri++)
5126 		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
5127 		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
5128 			pmc_link_target_process(pm, ppnew);
5129 			po = pm->pm_owner;
5130 			if (po->po_sscount == 0 &&
5131 			    po->po_flags & PMC_PO_OWNS_LOGFILE)
5132 				pmclog_process_procfork(po, p1->p_pid,
5133 				    newproc->p_pid);
5134 		}
5135 
5136  done:
5137 	sx_xunlock(&pmc_sx);
5138 }
5139 
5140 static void
5141 pmc_kld_load(void *arg __unused, linker_file_t lf)
5142 {
5143 	struct pmc_owner *po;
5144 
5145 	/*
5146 	 * Notify owners of system sampling PMCs about KLD operations.
5147 	 */
5148 	epoch_enter_preempt(global_epoch_preempt);
5149 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5150 		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5151 			pmclog_process_map_in(po, (pid_t) -1,
5152 			    (uintfptr_t) lf->address, lf->filename);
5153 	epoch_exit_preempt(global_epoch_preempt);
5154 
5155 	/*
5156 	 * TODO: Notify owners of (all) process-sampling PMCs too.
5157 	 */
5158 }
5159 
5160 static void
5161 pmc_kld_unload(void *arg __unused, const char *filename __unused,
5162     caddr_t address, size_t size)
5163 {
5164 	struct pmc_owner *po;
5165 
5166 	epoch_enter_preempt(global_epoch_preempt);
5167 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5168 		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5169 			pmclog_process_map_out(po, (pid_t) -1,
5170 			    (uintfptr_t) address, (uintfptr_t) address + size);
5171 	epoch_exit_preempt(global_epoch_preempt);
5172 
5173 	/*
5174 	 * TODO: Notify owners of process-sampling PMCs.
5175 	 */
5176 }
5177 
5178 /*
5179  * initialization
5180  */
5181 static const char *
5182 pmc_name_of_pmcclass(enum pmc_class class)
5183 {
5184 
5185 	switch (class) {
5186 #undef	__PMC_CLASS
5187 #define	__PMC_CLASS(S,V,D)						\
5188 	case PMC_CLASS_##S:						\
5189 		return #S;
5190 	__PMC_CLASSES();
5191 	default:
5192 		return ("<unknown>");
5193 	}
5194 }
5195 
5196 /*
5197  * Base class initializer: allocate structure and set default classes.
5198  */
5199 struct pmc_mdep *
5200 pmc_mdep_alloc(int nclasses)
5201 {
5202 	struct pmc_mdep *md;
5203 	int	n;
5204 
5205 	/* SOFT + md classes */
5206 	n = 1 + nclasses;
5207 	md = malloc(sizeof(struct pmc_mdep) + n *
5208 	    sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
5209 	md->pmd_nclass = n;
5210 
5211 	/* Add base class. */
5212 	pmc_soft_initialize(md);
5213 	return md;
5214 }
5215 
5216 void
5217 pmc_mdep_free(struct pmc_mdep *md)
5218 {
5219 	pmc_soft_finalize(md);
5220 	free(md, M_PMC);
5221 }
5222 
5223 static int
5224 generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
5225 {
5226 	(void) pc; (void) pp;
5227 
5228 	return (0);
5229 }
5230 
5231 static int
5232 generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
5233 {
5234 	(void) pc; (void) pp;
5235 
5236 	return (0);
5237 }
5238 
5239 static struct pmc_mdep *
5240 pmc_generic_cpu_initialize(void)
5241 {
5242 	struct pmc_mdep *md;
5243 
5244 	md = pmc_mdep_alloc(0);
5245 
5246 	md->pmd_cputype    = PMC_CPU_GENERIC;
5247 
5248 	md->pmd_pcpu_init  = NULL;
5249 	md->pmd_pcpu_fini  = NULL;
5250 	md->pmd_switch_in  = generic_switch_in;
5251 	md->pmd_switch_out = generic_switch_out;
5252 
5253 	return (md);
5254 }
5255 
5256 static void
5257 pmc_generic_cpu_finalize(struct pmc_mdep *md)
5258 {
5259 	(void) md;
5260 }
5261 
5262 
5263 static int
5264 pmc_initialize(void)
5265 {
5266 	int c, cpu, error, n, ri;
5267 	unsigned int maxcpu, domain;
5268 	struct pcpu *pc;
5269 	struct pmc_binding pb;
5270 	struct pmc_sample *ps;
5271 	struct pmc_classdep *pcd;
5272 	struct pmc_samplebuffer *sb;
5273 
5274 	md = NULL;
5275 	error = 0;
5276 
5277 	pmc_stats.pm_intr_ignored = counter_u64_alloc(M_WAITOK);
5278 	pmc_stats.pm_intr_processed = counter_u64_alloc(M_WAITOK);
5279 	pmc_stats.pm_intr_bufferfull = counter_u64_alloc(M_WAITOK);
5280 	pmc_stats.pm_syscalls = counter_u64_alloc(M_WAITOK);
5281 	pmc_stats.pm_syscall_errors = counter_u64_alloc(M_WAITOK);
5282 	pmc_stats.pm_buffer_requests = counter_u64_alloc(M_WAITOK);
5283 	pmc_stats.pm_buffer_requests_failed = counter_u64_alloc(M_WAITOK);
5284 	pmc_stats.pm_log_sweeps = counter_u64_alloc(M_WAITOK);
5285 
5286 #ifdef	HWPMC_DEBUG
5287 	/* parse debug flags first */
5288 	if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
5289 		pmc_debugstr, sizeof(pmc_debugstr)))
5290 		pmc_debugflags_parse(pmc_debugstr,
5291 		    pmc_debugstr+strlen(pmc_debugstr));
5292 #endif
5293 
5294 	PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
5295 
5296 	/* check kernel version */
5297 	if (pmc_kernel_version != PMC_VERSION) {
5298 		if (pmc_kernel_version == 0)
5299 			printf("hwpmc: this kernel has not been compiled with "
5300 			    "'options HWPMC_HOOKS'.\n");
5301 		else
5302 			printf("hwpmc: kernel version (0x%x) does not match "
5303 			    "module version (0x%x).\n", pmc_kernel_version,
5304 			    PMC_VERSION);
5305 		return EPROGMISMATCH;
5306 	}
5307 
5308 	/*
5309 	 * check sysctl parameters
5310 	 */
5311 
5312 	if (pmc_hashsize <= 0) {
5313 		(void) printf("hwpmc: tunable \"hashsize\"=%d must be "
5314 		    "greater than zero.\n", pmc_hashsize);
5315 		pmc_hashsize = PMC_HASH_SIZE;
5316 	}
5317 
5318 	if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
5319 		(void) printf("hwpmc: tunable \"nsamples\"=%d out of "
5320 		    "range.\n", pmc_nsamples);
5321 		pmc_nsamples = PMC_NSAMPLES;
5322 	}
5323 
5324 	if (pmc_callchaindepth <= 0 ||
5325 	    pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
5326 		(void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
5327 		    "range - using %d.\n", pmc_callchaindepth,
5328 		    PMC_CALLCHAIN_DEPTH_MAX);
5329 		pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX;
5330 	}
5331 
5332 	md = pmc_md_initialize();
5333 	if (md == NULL) {
5334 		/* Default to generic CPU. */
5335 		md = pmc_generic_cpu_initialize();
5336 		if (md == NULL)
5337 			return (ENOSYS);
5338         }
5339 
5340 	KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
5341 	    ("[pmc,%d] no classes or pmcs", __LINE__));
5342 
5343 	/* Compute the map from row-indices to classdep pointers. */
5344 	pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
5345 	    md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);
5346 
5347 	for (n = 0; n < md->pmd_npmc; n++)
5348 		pmc_rowindex_to_classdep[n] = NULL;
5349 	for (ri = c = 0; c < md->pmd_nclass; c++) {
5350 		pcd = &md->pmd_classdep[c];
5351 		for (n = 0; n < pcd->pcd_num; n++, ri++)
5352 			pmc_rowindex_to_classdep[ri] = pcd;
5353 	}
5354 
5355 	KASSERT(ri == md->pmd_npmc,
5356 	    ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
5357 	    ri, md->pmd_npmc));
5358 
5359 	maxcpu = pmc_cpu_max();
5360 
5361 	/* allocate space for the per-cpu array */
5362 	pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
5363 	    M_WAITOK|M_ZERO);
5364 
5365 	/* per-cpu 'saved values' for managing process-mode PMCs */
5366 	pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
5367 	    M_PMC, M_WAITOK);
5368 
5369 	/* Perform CPU-dependent initialization. */
5370 	pmc_save_cpu_binding(&pb);
5371 	error = 0;
5372 	for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
5373 		if (!pmc_cpu_is_active(cpu))
5374 			continue;
5375 		pmc_select_cpu(cpu);
5376 		pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
5377 		    md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
5378 		    M_WAITOK|M_ZERO);
5379 		if (md->pmd_pcpu_init)
5380 			error = md->pmd_pcpu_init(md, cpu);
5381 		for (n = 0; error == 0 && n < md->pmd_nclass; n++)
5382 			error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
5383 	}
5384 	pmc_restore_cpu_binding(&pb);
5385 
5386 	if (error)
5387 		return (error);
5388 
5389 	/* allocate space for the sample array */
5390 	for (cpu = 0; cpu < maxcpu; cpu++) {
5391 		if (!pmc_cpu_is_active(cpu))
5392 			continue;
5393 		pc = pcpu_find(cpu);
5394 		domain = pc->pc_domain;
5395 		sb = malloc_domain(sizeof(struct pmc_samplebuffer) +
5396 			pmc_nsamples * sizeof(struct pmc_sample), M_PMC, domain,
5397 		    M_WAITOK|M_ZERO);
5398 		sb->ps_read = sb->ps_write = sb->ps_samples;
5399 		sb->ps_fence = sb->ps_samples + pmc_nsamples;
5400 
5401 		KASSERT(pmc_pcpu[cpu] != NULL,
5402 		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
5403 
5404 		sb->ps_callchains = malloc_domain(pmc_callchaindepth * pmc_nsamples *
5405 			sizeof(uintptr_t), M_PMC, domain, M_WAITOK|M_ZERO);
5406 
5407 		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5408 			ps->ps_pc = sb->ps_callchains +
5409 			    (n * pmc_callchaindepth);
5410 
5411 		pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
5412 
5413 		sb = malloc_domain(sizeof(struct pmc_samplebuffer) +
5414 			pmc_nsamples * sizeof(struct pmc_sample), M_PMC, domain,
5415 		    M_WAITOK|M_ZERO);
5416 		sb->ps_read = sb->ps_write = sb->ps_samples;
5417 		sb->ps_fence = sb->ps_samples + pmc_nsamples;
5418 
5419 		KASSERT(pmc_pcpu[cpu] != NULL,
5420 		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
5421 
5422 		sb->ps_callchains = malloc_domain(pmc_callchaindepth * pmc_nsamples *
5423 			sizeof(uintptr_t), M_PMC, domain, M_WAITOK|M_ZERO);
5424 
5425 		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5426 			ps->ps_pc = sb->ps_callchains +
5427 			    (n * pmc_callchaindepth);
5428 
5429 		pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
5430 	}
5431 
5432 	/* allocate space for the row disposition array */
5433 	pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
5434 	    M_PMC, M_WAITOK|M_ZERO);
5435 
5436 	/* mark all PMCs as available */
5437 	for (n = 0; n < (int) md->pmd_npmc; n++)
5438 		PMC_MARK_ROW_FREE(n);
5439 
5440 	/* allocate thread hash tables */
5441 	pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
5442 	    &pmc_ownerhashmask);
5443 
5444 	pmc_processhash = hashinit(pmc_hashsize, M_PMC,
5445 	    &pmc_processhashmask);
5446 	mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
5447 	    MTX_SPIN);
5448 
5449 	CK_LIST_INIT(&pmc_ss_owners);
5450 	pmc_ss_count = 0;
5451 
5452 	/* allocate a pool of spin mutexes */
5453 	pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
5454 	    MTX_SPIN);
5455 
5456 	PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
5457 	    "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
5458 	    pmc_processhash, pmc_processhashmask);
5459 
5460 	/* Initialize a spin mutex for the thread free list. */
5461 	mtx_init(&pmc_threadfreelist_mtx, "pmc-threadfreelist", "pmc-leaf",
5462 	    MTX_SPIN);
5463 
5464 	/*
5465 	 * Initialize the callout to monitor the thread free list.
5466 	 * This callout will also handle the initial population of the list.
5467 	 */
5468 	taskqgroup_config_gtask_init(NULL, &free_gtask, pmc_thread_descriptor_pool_free_task, "thread descriptor pool free task");
5469 
5470 	/* register process {exit,fork,exec} handlers */
5471 	pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
5472 	    pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
5473 	pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
5474 	    pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
5475 
5476 	/* register kld event handlers */
5477 	pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
5478 	    NULL, EVENTHANDLER_PRI_ANY);
5479 	pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
5480 	    NULL, EVENTHANDLER_PRI_ANY);
5481 
5482 	/* initialize logging */
5483 	pmclog_initialize();
5484 
5485 	/* set hook functions */
5486 	pmc_intr = md->pmd_intr;
5487 	wmb();
5488 	pmc_hook = pmc_hook_handler;
5489 
5490 	if (error == 0) {
5491 		printf(PMC_MODULE_NAME ":");
5492 		for (n = 0; n < (int) md->pmd_nclass; n++) {
5493 			pcd = &md->pmd_classdep[n];
5494 			printf(" %s/%d/%d/0x%b",
5495 			    pmc_name_of_pmcclass(pcd->pcd_class),
5496 			    pcd->pcd_num,
5497 			    pcd->pcd_width,
5498 			    pcd->pcd_caps,
5499 			    "\20"
5500 			    "\1INT\2USR\3SYS\4EDG\5THR"
5501 			    "\6REA\7WRI\10INV\11QUA\12PRC"
5502 			    "\13TAG\14CSC");
5503 		}
5504 		printf("\n");
5505 	}
5506 
5507 	return (error);
5508 }
5509 
5510 /* prepare to be unloaded */
5511 static void
5512 pmc_cleanup(void)
5513 {
5514 	int c, cpu;
5515 	unsigned int maxcpu;
5516 	struct pmc_ownerhash *ph;
5517 	struct pmc_owner *po, *tmp;
5518 	struct pmc_binding pb;
5519 #ifdef	HWPMC_DEBUG
5520 	struct pmc_processhash *prh;
5521 #endif
5522 
5523 	PMCDBG0(MOD,INI,0, "cleanup");
5524 
5525 	/* switch off sampling */
5526 	CPU_FOREACH(cpu)
5527 		DPCPU_ID_SET(cpu, pmc_sampled, 0);
5528 	pmc_intr = NULL;
5529 
5530 	sx_xlock(&pmc_sx);
5531 	if (pmc_hook == NULL) {	/* being unloaded already */
5532 		sx_xunlock(&pmc_sx);
5533 		return;
5534 	}
5535 
5536 	pmc_hook = NULL; /* prevent new threads from entering module */
5537 
5538 	/* deregister event handlers */
5539 	EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
5540 	EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
5541 	EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
5542 	EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);
5543 
5544 	/* send SIGBUS to all owner threads, free up allocations */
5545 	if (pmc_ownerhash)
5546 		for (ph = pmc_ownerhash;
5547 		     ph <= &pmc_ownerhash[pmc_ownerhashmask];
5548 		     ph++) {
5549 			LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
5550 				pmc_remove_owner(po);
5551 
5552 				/* send SIGBUS to owner processes */
5553 				PMCDBG3(MOD,INI,2, "cleanup signal proc=%p "
5554 				    "(%d, %s)", po->po_owner,
5555 				    po->po_owner->p_pid,
5556 				    po->po_owner->p_comm);
5557 
5558 				PROC_LOCK(po->po_owner);
5559 				kern_psignal(po->po_owner, SIGBUS);
5560 				PROC_UNLOCK(po->po_owner);
5561 
5562 				pmc_destroy_owner_descriptor(po);
5563 			}
5564 		}
5565 
5566 	/* reclaim allocated data structures */
5567 	mtx_destroy(&pmc_threadfreelist_mtx);
5568 	pmc_thread_descriptor_pool_drain();
5569 
5570 	if (pmc_mtxpool)
5571 		mtx_pool_destroy(&pmc_mtxpool);
5572 
5573 	mtx_destroy(&pmc_processhash_mtx);
5574 	taskqgroup_config_gtask_deinit(&free_gtask);
5575 	if (pmc_processhash) {
5576 #ifdef	HWPMC_DEBUG
5577 		struct pmc_process *pp;
5578 
5579 		PMCDBG0(MOD,INI,3, "destroy process hash");
5580 		for (prh = pmc_processhash;
5581 		     prh <= &pmc_processhash[pmc_processhashmask];
5582 		     prh++)
5583 			LIST_FOREACH(pp, prh, pp_next)
5584 			    PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5585 #endif
5586 
5587 		hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5588 		pmc_processhash = NULL;
5589 	}
5590 
5591 	if (pmc_ownerhash) {
5592 		PMCDBG0(MOD,INI,3, "destroy owner hash");
5593 		hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5594 		pmc_ownerhash = NULL;
5595 	}
5596 
5597 	KASSERT(CK_LIST_EMPTY(&pmc_ss_owners),
5598 	    ("[pmc,%d] Global SS owner list not empty", __LINE__));
5599 	KASSERT(pmc_ss_count == 0,
5600 	    ("[pmc,%d] Global SS count not empty", __LINE__));
5601 
5602  	/* do processor and pmc-class dependent cleanup */
5603 	maxcpu = pmc_cpu_max();
5604 
5605 	PMCDBG0(MOD,INI,3, "md cleanup");
5606 	if (md) {
5607 		pmc_save_cpu_binding(&pb);
5608 		for (cpu = 0; cpu < maxcpu; cpu++) {
5609 			PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5610 			    cpu, pmc_pcpu[cpu]);
5611 			if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5612 				continue;
5613 			pmc_select_cpu(cpu);
5614 			for (c = 0; c < md->pmd_nclass; c++)
5615 				md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
5616 			if (md->pmd_pcpu_fini)
5617 				md->pmd_pcpu_fini(md, cpu);
5618 		}
5619 
5620 		if (md->pmd_cputype == PMC_CPU_GENERIC)
5621 			pmc_generic_cpu_finalize(md);
5622 		else
5623 			pmc_md_finalize(md);
5624 
5625 		pmc_mdep_free(md);
5626 		md = NULL;
5627 		pmc_restore_cpu_binding(&pb);
5628 	}
5629 
5630 	/* Free per-cpu descriptors. */
5631 	for (cpu = 0; cpu < maxcpu; cpu++) {
5632 		if (!pmc_cpu_is_active(cpu))
5633 			continue;
5634 		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5635 		    ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5636 			cpu));
5637 		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5638 		    ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5639 			cpu));
5640 		free_domain(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
5641 		free_domain(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
5642 		free_domain(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
5643 		free_domain(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
5644 		free_domain(pmc_pcpu[cpu], M_PMC);
5645 	}
5646 
5647 	free(pmc_pcpu, M_PMC);
5648 	pmc_pcpu = NULL;
5649 
5650 	free(pmc_pcpu_saved, M_PMC);
5651 	pmc_pcpu_saved = NULL;
5652 
5653 	if (pmc_pmcdisp) {
5654 		free(pmc_pmcdisp, M_PMC);
5655 		pmc_pmcdisp = NULL;
5656 	}
5657 
5658 	if (pmc_rowindex_to_classdep) {
5659 		free(pmc_rowindex_to_classdep, M_PMC);
5660 		pmc_rowindex_to_classdep = NULL;
5661 	}
5662 
5663 	pmclog_shutdown();
5664 	counter_u64_free(pmc_stats.pm_intr_ignored);
5665 	counter_u64_free(pmc_stats.pm_intr_processed);
5666 	counter_u64_free(pmc_stats.pm_intr_bufferfull);
5667 	counter_u64_free(pmc_stats.pm_syscalls);
5668 	counter_u64_free(pmc_stats.pm_syscall_errors);
5669 	counter_u64_free(pmc_stats.pm_buffer_requests);
5670 	counter_u64_free(pmc_stats.pm_buffer_requests_failed);
5671 	counter_u64_free(pmc_stats.pm_log_sweeps);
5672 	sx_xunlock(&pmc_sx); 	/* we are done */
5673 }
5674 
5675 /*
5676  * The function called at load/unload.
5677  */
5678 
5679 static int
5680 load (struct module *module __unused, int cmd, void *arg __unused)
5681 {
5682 	int error;
5683 
5684 	error = 0;
5685 
5686 	switch (cmd) {
5687 	case MOD_LOAD :
5688 		/* initialize the subsystem */
5689 		error = pmc_initialize();
5690 		if (error != 0)
5691 			break;
5692 		PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d",
5693 		    pmc_syscall_num, pmc_cpu_max());
5694 		break;
5695 
5696 
5697 	case MOD_UNLOAD :
5698 	case MOD_SHUTDOWN:
5699 		pmc_cleanup();
5700 		PMCDBG0(MOD,INI,1, "unloaded");
5701 		break;
5702 
5703 	default :
5704 		error = EINVAL;	/* XXX should panic(9) */
5705 		break;
5706 	}
5707 
5708 	return error;
5709 }
5710