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