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