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