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