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