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