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