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