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