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