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