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