hwpmc_mod.c revision 156778
1132718Skan/*-
290075Sobrien * Copyright (c) 2003-2005 Joseph Koshy
3169689Skan * All rights reserved.
490075Sobrien *
5169689Skan * Redistribution and use in source and binary forms, with or without
690075Sobrien * modification, are permitted provided that the following conditions
7132718Skan * are met:
890075Sobrien * 1. Redistributions of source code must retain the above copyright
990075Sobrien *    notice, this list of conditions and the following disclaimer.
1090075Sobrien * 2. Redistributions in binary form must reproduce the above copyright
1190075Sobrien *    notice, this list of conditions and the following disclaimer in the
1290075Sobrien *    documentation and/or other materials provided with the distribution.
1390075Sobrien *
1490075Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1590075Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1690075Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1790075Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1890075Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1990075Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2090075Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21169689Skan * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22169689Skan * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2390075Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2490075Sobrien * SUCH DAMAGE.
25132718Skan *
26132718Skan */
27132718Skan
2890075Sobrien#include <sys/cdefs.h>
2990075Sobrien__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_mod.c 156778 2006-03-16 16:32:56Z jkoshy $");
3090075Sobrien
31169689Skan#include <sys/param.h>
3290075Sobrien#include <sys/eventhandler.h>
3390075Sobrien#include <sys/jail.h>
3490075Sobrien#include <sys/kernel.h>
3590075Sobrien#include <sys/kthread.h>
3690075Sobrien#include <sys/limits.h>
3790075Sobrien#include <sys/lock.h>
38117395Skan#include <sys/malloc.h>
39132718Skan#include <sys/module.h>
4090075Sobrien#include <sys/mutex.h>
4190075Sobrien#include <sys/pmc.h>
4290075Sobrien#include <sys/pmckern.h>
4390075Sobrien#include <sys/pmclog.h>
4490075Sobrien#include <sys/proc.h>
4590075Sobrien#include <sys/queue.h>
4690075Sobrien#include <sys/resourcevar.h>
4790075Sobrien#include <sys/sched.h>
4890075Sobrien#include <sys/signalvar.h>
4990075Sobrien#include <sys/smp.h>
5090075Sobrien#include <sys/sx.h>
5190075Sobrien#include <sys/sysctl.h>
5290075Sobrien#include <sys/sysent.h>
5390075Sobrien#include <sys/systm.h>
5490075Sobrien#include <sys/vnode.h>
5590075Sobrien
5690075Sobrien#include <machine/atomic.h>
5790075Sobrien#include <machine/md_var.h>
5890075Sobrien
5990075Sobrien/*
6090075Sobrien * Types
6190075Sobrien */
6290075Sobrien
6390075Sobrienenum pmc_flags {
6490075Sobrien	PMC_FLAG_NONE	  = 0x00, /* do nothing */
6590075Sobrien	PMC_FLAG_REMOVE   = 0x01, /* atomically remove entry from hash */
6690075Sobrien	PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
6790075Sobrien};
6890075Sobrien
6990075Sobrien/*
7090075Sobrien * The offset in sysent where the syscall is allocated.
7190075Sobrien */
7290075Sobrien
7390075Sobrienstatic int pmc_syscall_num = NO_SYSCALL;
7490075Sobrienstruct pmc_cpu		**pmc_pcpu;	 /* per-cpu state */
7590075Sobrienpmc_value_t		*pmc_pcpu_saved; /* saved PMC values: CSW handling */
7690075Sobrien
7790075Sobrien#define	PMC_PCPU_SAVED(C,R)	pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
7890075Sobrien
7990075Sobrienstruct mtx_pool		*pmc_mtxpool;
8090075Sobrienstatic int		*pmc_pmcdisp;	 /* PMC row dispositions */
8190075Sobrien
8290075Sobrien#define	PMC_ROW_DISP_IS_FREE(R)		(pmc_pmcdisp[(R)] == 0)
8390075Sobrien#define	PMC_ROW_DISP_IS_THREAD(R)	(pmc_pmcdisp[(R)] > 0)
8490075Sobrien#define	PMC_ROW_DISP_IS_STANDALONE(R)	(pmc_pmcdisp[(R)] < 0)
8590075Sobrien
8690075Sobrien#define	PMC_MARK_ROW_FREE(R) do {					  \
8790075Sobrien	pmc_pmcdisp[(R)] = 0;						  \
8890075Sobrien} while (0)
8990075Sobrien
9090075Sobrien#define	PMC_MARK_ROW_STANDALONE(R) do {					  \
9190075Sobrien	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
92117395Skan		    __LINE__));						  \
9390075Sobrien	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
9490075Sobrien	KASSERT(pmc_pmcdisp[(R)] >= (-mp_ncpus), ("[pmc,%d] row "	  \
9590075Sobrien		"disposition error", __LINE__));			  \
9690075Sobrien} while (0)
9790075Sobrien
9890075Sobrien#define	PMC_UNMARK_ROW_STANDALONE(R) do { 				  \
9990075Sobrien	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
10090075Sobrien	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
10190075Sobrien		    __LINE__));						  \
10290075Sobrien} while (0)
10390075Sobrien
10490075Sobrien#define	PMC_MARK_ROW_THREAD(R) do {					  \
10590075Sobrien	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
10690075Sobrien		    __LINE__));						  \
107169689Skan	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
108169689Skan} while (0)
109169689Skan
110169689Skan#define	PMC_UNMARK_ROW_THREAD(R) do {					  \
111169689Skan	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
112169689Skan	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
113169689Skan		    __LINE__));						  \
114169689Skan} while (0)
115169689Skan
116169689Skan
117169689Skan/* various event handlers */
118169689Skanstatic eventhandler_tag	pmc_exit_tag, pmc_fork_tag;
11990075Sobrien
12090075Sobrien/* Module statistics */
12190075Sobrienstruct pmc_op_getdriverstats pmc_stats;
12290075Sobrien
123169689Skan/* Machine/processor dependent operations */
124169689Skanstruct pmc_mdep  *md;
125169689Skan
126169689Skan/*
12790075Sobrien * Hash tables mapping owner processes and target threads to PMCs.
12890075Sobrien */
12990075Sobrien
13090075Sobrienstruct mtx pmc_processhash_mtx;		/* spin mutex */
13190075Sobrienstatic u_long pmc_processhashmask;
13290075Sobrienstatic LIST_HEAD(pmc_processhash, pmc_process)	*pmc_processhash;
13390075Sobrien
13490075Sobrien/*
13590075Sobrien * Hash table of PMC owner descriptors.  This table is protected by
13690075Sobrien * the shared PMC "sx" lock.
13790075Sobrien */
13890075Sobrien
13990075Sobrienstatic u_long pmc_ownerhashmask;
14090075Sobrienstatic LIST_HEAD(pmc_ownerhash, pmc_owner)	*pmc_ownerhash;
14190075Sobrien
14290075Sobrien/*
14390075Sobrien * List of PMC owners with system-wide sampling PMCs.
14490075Sobrien */
14590075Sobrien
14690075Sobrienstatic LIST_HEAD(, pmc_owner)			pmc_ss_owners;
14790075Sobrien
148132718Skan
149132718Skan/*
150132718Skan * Prototypes
151132718Skan */
152132718Skan
153132718Skan#ifdef	DEBUG
154132718Skanstatic int	pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
155132718Skanstatic int	pmc_debugflags_parse(char *newstr, char *fence);
156132718Skan#endif
157132718Skan
158132718Skanstatic int	load(struct module *module, int cmd, void *arg);
159132718Skanstatic int	pmc_attach_process(struct proc *p, struct pmc *pm);
160132718Skanstatic struct pmc *pmc_allocate_pmc_descriptor(void);
161132718Skanstatic struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
162132718Skanstatic int	pmc_attach_one_process(struct proc *p, struct pmc *pm);
163132718Skanstatic int	pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
164132718Skan    int cpu);
165132718Skanstatic int	pmc_can_attach(struct pmc *pm, struct proc *p);
16690075Sobrienstatic void	pmc_cleanup(void);
167132718Skanstatic int	pmc_detach_process(struct proc *p, struct pmc *pm);
168132718Skanstatic int	pmc_detach_one_process(struct proc *p, struct pmc *pm,
169132718Skan    int flags);
170132718Skanstatic void	pmc_destroy_owner_descriptor(struct pmc_owner *po);
171132718Skanstatic struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
172132718Skanstatic int	pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
173132718Skanstatic struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
174132718Skan    pmc_id_t pmc);
175132718Skanstatic struct pmc_process *pmc_find_process_descriptor(struct proc *p,
176132718Skan    uint32_t mode);
177132718Skanstatic void	pmc_force_context_switch(void);
178132718Skanstatic void	pmc_link_target_process(struct pmc *pm,
179132718Skan    struct pmc_process *pp);
180132718Skanstatic void	pmc_maybe_remove_owner(struct pmc_owner *po);
181132718Skanstatic void	pmc_process_csw_in(struct thread *td);
182132718Skanstatic void	pmc_process_csw_out(struct thread *td);
183132718Skanstatic void	pmc_process_exit(void *arg, struct proc *p);
184132718Skanstatic void	pmc_process_fork(void *arg, struct proc *p1,
18590075Sobrien    struct proc *p2, int n);
18690075Sobrienstatic void	pmc_process_samples(int cpu);
18790075Sobrienstatic void	pmc_release_pmc_descriptor(struct pmc *pmc);
188117395Skanstatic void	pmc_remove_owner(struct pmc_owner *po);
18990075Sobrienstatic void	pmc_remove_process_descriptor(struct pmc_process *pp);
19090075Sobrienstatic void	pmc_restore_cpu_binding(struct pmc_binding *pb);
19190075Sobrienstatic void	pmc_save_cpu_binding(struct pmc_binding *pb);
19290075Sobrienstatic void	pmc_select_cpu(int cpu);
19390075Sobrienstatic int	pmc_start(struct pmc *pm);
19490075Sobrienstatic int	pmc_stop(struct pmc *pm);
19590075Sobrienstatic int	pmc_syscall_handler(struct thread *td, void *syscall_args);
19690075Sobrienstatic void	pmc_unlink_target_process(struct pmc *pmc,
19790075Sobrien    struct pmc_process *pp);
19890075Sobrien
19990075Sobrien/*
200117395Skan * Kernel tunables and sysctl(8) interface.
201117395Skan */
202117395Skan
203117395SkanSYSCTL_NODE(_kern, OID_AUTO, hwpmc, CTLFLAG_RW, 0, "HWPMC parameters");
20490075Sobrien
20590075Sobrien#ifdef	DEBUG
206169689Skanstruct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
207169689Skanchar	pmc_debugstr[PMC_DEBUG_STRSIZE];
208169689SkanTUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
20990075Sobrien    sizeof(pmc_debugstr));
210169689SkanSYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
211169689Skan    CTLTYPE_STRING|CTLFLAG_RW|CTLFLAG_TUN,
212169689Skan    0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
213169689Skan#endif
214169689Skan
21590075Sobrien/*
21690075Sobrien * kern.hwpmc.hashrows -- determines the number of rows in the
21790075Sobrien * of the hash table used to look up threads
21890075Sobrien */
21990075Sobrien
22090075Sobrienstatic int pmc_hashsize = PMC_HASH_SIZE;
22190075SobrienTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "hashsize", &pmc_hashsize);
22290075SobrienSYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_TUN|CTLFLAG_RD,
22390075Sobrien    &pmc_hashsize, 0, "rows in hash tables");
22490075Sobrien
22590075Sobrien/*
22690075Sobrien * kern.hwpmc.nsamples --- number of PC samples per CPU
22790075Sobrien */
22890075Sobrien
22990075Sobrienstatic int pmc_nsamples = PMC_NSAMPLES;
23090075SobrienTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nsamples", &pmc_nsamples);
23190075SobrienSYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_TUN|CTLFLAG_RD,
23290075Sobrien    &pmc_nsamples, 0, "number of PC samples per CPU");
23390075Sobrien
23490075Sobrien/*
23590075Sobrien * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
23690075Sobrien */
23790075Sobrien
23890075Sobrienstatic int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
23990075SobrienTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "mtxpoolsize", &pmc_mtxpool_size);
24090075SobrienSYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_TUN|CTLFLAG_RD,
24190075Sobrien    &pmc_mtxpool_size, 0, "size of spin mutex pool");
24290075Sobrien
24390075Sobrien
24490075Sobrien/*
24590075Sobrien * security.bsd.unprivileged_syspmcs -- allow non-root processes to
24690075Sobrien * allocate system-wide PMCs.
24790075Sobrien *
24890075Sobrien * Allowing unprivileged processes to allocate system PMCs is convenient
24990075Sobrien * if system-wide measurements need to be taken concurrently with other
25090075Sobrien * per-process measurements.  This feature is turned off by default.
25190075Sobrien */
25290075Sobrien
25390075SobrienSYSCTL_DECL(_security_bsd);
25490075Sobrien
25590075Sobrienstatic int pmc_unprivileged_syspmcs = 0;
25690075SobrienTUNABLE_INT("security.bsd.unprivileged_syspmcs", &pmc_unprivileged_syspmcs);
25790075SobrienSYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RW,
25890075Sobrien    &pmc_unprivileged_syspmcs, 0,
25990075Sobrien    "allow unprivileged process to allocate system PMCs");
26090075Sobrien
26190075Sobrien/*
26290075Sobrien * Hash function.  Discard the lower 2 bits of the pointer since
26390075Sobrien * these are always zero for our uses.  The hash multiplier is
26490075Sobrien * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
26590075Sobrien */
26690075Sobrien
26790075Sobrien#if	LONG_BIT == 64
26890075Sobrien#define	_PMC_HM		11400714819323198486u
26990075Sobrien#elif	LONG_BIT == 32
27090075Sobrien#define	_PMC_HM		2654435769u
27190075Sobrien#else
27290075Sobrien#error 	Must know the size of 'long' to compile
27390075Sobrien#endif
27490075Sobrien
27590075Sobrien#define	PMC_HASH_PTR(P,M)	((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
27690075Sobrien
27790075Sobrien/*
27890075Sobrien * Syscall structures
27990075Sobrien */
28090075Sobrien
28190075Sobrien/* The `sysent' for the new syscall */
28290075Sobrienstatic struct sysent pmc_sysent = {
28390075Sobrien	2,			/* sy_narg */
28490075Sobrien	pmc_syscall_handler	/* sy_call */
28590075Sobrien};
28690075Sobrien
28790075Sobrienstatic struct syscall_module_data pmc_syscall_mod = {
28890075Sobrien	load,
28990075Sobrien	NULL,
29090075Sobrien	&pmc_syscall_num,
29190075Sobrien	&pmc_sysent,
29290075Sobrien	{ 0, NULL }
29390075Sobrien};
29490075Sobrien
29590075Sobrienstatic moduledata_t pmc_mod = {
29690075Sobrien	PMC_MODULE_NAME,
29790075Sobrien	syscall_module_handler,
29890075Sobrien	&pmc_syscall_mod
29990075Sobrien};
30090075Sobrien
30190075SobrienDECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
30290075SobrienMODULE_VERSION(pmc, PMC_VERSION);
30390075Sobrien
30490075Sobrien#ifdef	DEBUG
30590075Sobrienenum pmc_dbgparse_state {
30690075Sobrien	PMCDS_WS,		/* in whitespace */
30790075Sobrien	PMCDS_MAJOR,		/* seen a major keyword */
30890075Sobrien	PMCDS_MINOR
30990075Sobrien};
31090075Sobrien
31190075Sobrienstatic int
31290075Sobrienpmc_debugflags_parse(char *newstr, char *fence)
31390075Sobrien{
31490075Sobrien	char c, *p, *q;
31590075Sobrien	struct pmc_debugflags *tmpflags;
31690075Sobrien	int error, found, *newbits, tmp;
31790075Sobrien	size_t kwlen;
31890075Sobrien
31990075Sobrien	MALLOC(tmpflags, struct pmc_debugflags *, sizeof(*tmpflags),
32090075Sobrien	    M_PMC, M_WAITOK|M_ZERO);
32190075Sobrien
32290075Sobrien	p = newstr;
32390075Sobrien	error = 0;
32490075Sobrien
32590075Sobrien	for (; p < fence && (c = *p); p++) {
32690075Sobrien
32790075Sobrien		/* skip white space */
32890075Sobrien		if (c == ' ' || c == '\t')
32990075Sobrien			continue;
33090075Sobrien
33190075Sobrien		/* look for a keyword followed by "=" */
33290075Sobrien		for (q = p; p < fence && (c = *p) && c != '='; p++)
33390075Sobrien			;
33490075Sobrien		if (c != '=') {
33590075Sobrien			error = EINVAL;
33690075Sobrien			goto done;
33790075Sobrien		}
33890075Sobrien
33990075Sobrien		kwlen = p - q;
34090075Sobrien		newbits = NULL;
34190075Sobrien
34290075Sobrien		/* lookup flag group name */
34390075Sobrien#define	DBG_SET_FLAG_MAJ(S,F)						\
34490075Sobrien		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
34590075Sobrien			newbits = &tmpflags->pdb_ ## F;
34690075Sobrien
34790075Sobrien		DBG_SET_FLAG_MAJ("cpu",		CPU);
34890075Sobrien		DBG_SET_FLAG_MAJ("csw",		CSW);
34990075Sobrien		DBG_SET_FLAG_MAJ("logging",	LOG);
35090075Sobrien		DBG_SET_FLAG_MAJ("module",	MOD);
35190075Sobrien		DBG_SET_FLAG_MAJ("md", 		MDP);
35290075Sobrien		DBG_SET_FLAG_MAJ("owner",	OWN);
35390075Sobrien		DBG_SET_FLAG_MAJ("pmc",		PMC);
35490075Sobrien		DBG_SET_FLAG_MAJ("process",	PRC);
35590075Sobrien		DBG_SET_FLAG_MAJ("sampling", 	SAM);
35690075Sobrien
35790075Sobrien		if (newbits == NULL) {
35890075Sobrien			error = EINVAL;
35990075Sobrien			goto done;
36090075Sobrien		}
36190075Sobrien
36290075Sobrien		p++;		/* skip the '=' */
36390075Sobrien
36490075Sobrien		/* Now parse the individual flags */
36590075Sobrien		tmp = 0;
36690075Sobrien	newflag:
36790075Sobrien		for (q = p; p < fence && (c = *p); p++)
36890075Sobrien			if (c == ' ' || c == '\t' || c == ',')
36990075Sobrien				break;
37090075Sobrien
37190075Sobrien		/* p == fence or c == ws or c == "," or c == 0 */
37290075Sobrien
37390075Sobrien		if ((kwlen = p - q) == 0) {
37490075Sobrien			*newbits = tmp;
37590075Sobrien			continue;
37690075Sobrien		}
377132718Skan
37890075Sobrien		found = 0;
37990075Sobrien#define	DBG_SET_FLAG_MIN(S,F)						\
38090075Sobrien		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
38190075Sobrien			tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
38290075Sobrien
38390075Sobrien		/* a '*' denotes all possible flags in the group */
38490075Sobrien		if (kwlen == 1 && *q == '*')
38590075Sobrien			tmp = found = ~0;
38690075Sobrien		/* look for individual flag names */
38790075Sobrien		DBG_SET_FLAG_MIN("allocaterow", ALR);
38890075Sobrien		DBG_SET_FLAG_MIN("allocate",	ALL);
38990075Sobrien		DBG_SET_FLAG_MIN("attach",	ATT);
39090075Sobrien		DBG_SET_FLAG_MIN("bind",	BND);
39190075Sobrien		DBG_SET_FLAG_MIN("config",	CFG);
39290075Sobrien		DBG_SET_FLAG_MIN("exec",	EXC);
39390075Sobrien		DBG_SET_FLAG_MIN("exit",	EXT);
39490075Sobrien		DBG_SET_FLAG_MIN("find",	FND);
39590075Sobrien		DBG_SET_FLAG_MIN("flush",	FLS);
39690075Sobrien		DBG_SET_FLAG_MIN("fork",	FRK);
39790075Sobrien		DBG_SET_FLAG_MIN("getbuf",	GTB);
39890075Sobrien		DBG_SET_FLAG_MIN("hook",	PMH);
39990075Sobrien		DBG_SET_FLAG_MIN("init",	INI);
40090075Sobrien		DBG_SET_FLAG_MIN("intr",	INT);
40190075Sobrien		DBG_SET_FLAG_MIN("linktarget",	TLK);
40290075Sobrien		DBG_SET_FLAG_MIN("mayberemove", OMR);
40390075Sobrien		DBG_SET_FLAG_MIN("ops",		OPS);
40490075Sobrien		DBG_SET_FLAG_MIN("read",	REA);
40590075Sobrien		DBG_SET_FLAG_MIN("register",	REG);
406132718Skan		DBG_SET_FLAG_MIN("release",	REL);
40790075Sobrien		DBG_SET_FLAG_MIN("remove",	ORM);
40890075Sobrien		DBG_SET_FLAG_MIN("sample",	SAM);
40990075Sobrien		DBG_SET_FLAG_MIN("scheduleio",	SIO);
41090075Sobrien		DBG_SET_FLAG_MIN("select",	SEL);
41190075Sobrien		DBG_SET_FLAG_MIN("signal",	SIG);
41290075Sobrien		DBG_SET_FLAG_MIN("swi",		SWI);
41390075Sobrien		DBG_SET_FLAG_MIN("swo",		SWO);
41490075Sobrien		DBG_SET_FLAG_MIN("start",	STA);
41590075Sobrien		DBG_SET_FLAG_MIN("stop",	STO);
41690075Sobrien		DBG_SET_FLAG_MIN("syscall",	PMS);
41790075Sobrien		DBG_SET_FLAG_MIN("unlinktarget", TUL);
41890075Sobrien		DBG_SET_FLAG_MIN("write",	WRI);
41990075Sobrien		if (found == 0) {
42090075Sobrien			/* unrecognized flag name */
42190075Sobrien			error = EINVAL;
42290075Sobrien			goto done;
42390075Sobrien		}
42490075Sobrien
42590075Sobrien		if (c == 0 || c == ' ' || c == '\t') {	/* end of flag group */
42690075Sobrien			*newbits = tmp;
427132718Skan			continue;
42890075Sobrien		}
42990075Sobrien
43090075Sobrien		p++;
43190075Sobrien		goto newflag;
432169689Skan	}
43390075Sobrien
43490075Sobrien	/* save the new flag set */
43590075Sobrien	bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
43690075Sobrien
437169689Skan done:
438169689Skan	FREE(tmpflags, M_PMC);
43990075Sobrien	return error;
44090075Sobrien}
44190075Sobrien
44290075Sobrienstatic int
44390075Sobrienpmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
44490075Sobrien{
44590075Sobrien	char *fence, *newstr;
44690075Sobrien	int error;
44790075Sobrien	unsigned int n;
44890075Sobrien
44990075Sobrien	(void) arg1; (void) arg2; /* unused parameters */
45090075Sobrien
45190075Sobrien	n = sizeof(pmc_debugstr);
45290075Sobrien	MALLOC(newstr, char *, n, M_PMC, M_ZERO|M_WAITOK);
45390075Sobrien	(void) strlcpy(newstr, pmc_debugstr, n);
45490075Sobrien
45590075Sobrien	error = sysctl_handle_string(oidp, newstr, n, req);
45690075Sobrien
45790075Sobrien	/* if there is a new string, parse and copy it */
45890075Sobrien	if (error == 0 && req->newptr != NULL) {
45990075Sobrien		fence = newstr + (n < req->newlen ? n : req->newlen + 1);
46090075Sobrien		if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
46190075Sobrien			(void) strlcpy(pmc_debugstr, newstr,
46290075Sobrien			    sizeof(pmc_debugstr));
46390075Sobrien	}
464117395Skan
46590075Sobrien	FREE(newstr, M_PMC);
46690075Sobrien
46790075Sobrien	return error;
46890075Sobrien}
46990075Sobrien#endif
47090075Sobrien
47190075Sobrien/*
47290075Sobrien * Concurrency Control
47390075Sobrien *
47490075Sobrien * The driver manages the following data structures:
47590075Sobrien *
47690075Sobrien *   - target process descriptors, one per target process
47790075Sobrien *   - owner process descriptors (and attached lists), one per owner process
47890075Sobrien *   - lookup hash tables for owner and target processes
47990075Sobrien *   - PMC descriptors (and attached lists)
48090075Sobrien *   - per-cpu hardware state
48190075Sobrien *   - the 'hook' variable through which the kernel calls into
48290075Sobrien *     this module
48390075Sobrien *   - the machine hardware state (managed by the MD layer)
48490075Sobrien *
48590075Sobrien * These data structures are accessed from:
48690075Sobrien *
48790075Sobrien * - thread context-switch code
48890075Sobrien * - interrupt handlers (possibly on multiple cpus)
48990075Sobrien * - kernel threads on multiple cpus running on behalf of user
49090075Sobrien *   processes doing system calls
49190075Sobrien * - this driver's private kernel threads
49290075Sobrien *
49390075Sobrien * = Locks and Locking strategy =
49490075Sobrien *
49590075Sobrien * The driver uses four locking strategies for its operation:
49690075Sobrien *
49790075Sobrien * - There is a 'global' SX lock "pmc_sx" that is used to protect
49890075Sobrien *   the its 'meta-data'.
49990075Sobrien *
50090075Sobrien *   Calls into the module (via syscall() or by the kernel) start with
50190075Sobrien *   this lock being held in exclusive mode.  Depending on the requested
50290075Sobrien *   operation, the lock may be downgraded to 'shared' mode to allow
50390075Sobrien *   more concurrent readers into the module.
50490075Sobrien *
50590075Sobrien *   This SX lock is held in exclusive mode for any operations that
50690075Sobrien *   modify the linkages between the driver's internal data structures.
50790075Sobrien *
50890075Sobrien *   The 'pmc_hook' function pointer is also protected by this lock.
50990075Sobrien *   It is only examined with the sx lock held in exclusive mode.  The
51090075Sobrien *   kernel module is allowed to be unloaded only with the sx lock
51190075Sobrien *   held in exclusive mode.  In normal syscall handling, after
51290075Sobrien *   acquiring the pmc_sx lock we first check that 'pmc_hook' is
51390075Sobrien *   non-null before proceeding.  This prevents races between the
51490075Sobrien *   thread unloading the module and other threads seeking to use the
51590075Sobrien *   module.
51690075Sobrien *
51790075Sobrien * - Lookups of target process structures and owner process structures
51890075Sobrien *   cannot use the global "pmc_sx" SX lock because these lookups need
51990075Sobrien *   to happen during context switches and in other critical sections
52090075Sobrien *   where sleeping is not allowed.  We protect these lookup tables
52190075Sobrien *   with their own private spin-mutexes, "pmc_processhash_mtx" and
52290075Sobrien *   "pmc_ownerhash_mtx".  These are 'leaf' mutexes, in that no other
52390075Sobrien *   lock is acquired with these locks held.
52490075Sobrien *
52590075Sobrien * - Interrupt handlers work in a lock free manner.  At interrupt
52690075Sobrien *   time, handlers look at the PMC pointer (phw->phw_pmc) configured
52790075Sobrien *   when the PMC was started.  If this pointer is NULL, the interrupt
52890075Sobrien *   is ignored after updating driver statistics.  We ensure that this
52990075Sobrien *   pointer is set (using an atomic operation if necessary) before the
53090075Sobrien *   PMC hardware is started.  Conversely, this pointer is unset atomically
53190075Sobrien *   only after the PMC hardware is stopped.
53290075Sobrien *
53390075Sobrien *   We ensure that everything needed for the operation of an
53490075Sobrien *   interrupt handler is available without it needing to acquire any
53590075Sobrien *   locks.  We also ensure that a PMC's software state is destroyed only
53690075Sobrien *   after the PMC is taken off hardware (on all CPUs).
53790075Sobrien *
53890075Sobrien * - Context-switch handling with process-private PMCs needs more
53990075Sobrien *   care.
54090075Sobrien *
54190075Sobrien *   A given process may be the target of multiple PMCs.  For example,
54290075Sobrien *   PMCATTACH and PMCDETACH may be requested by a process on one CPU
54390075Sobrien *   while the target process is running on another.  A PMC could also
54490075Sobrien *   be getting released because its owner is exiting.  We tackle
54590075Sobrien *   these situations in the following manner:
54690075Sobrien *
54790075Sobrien *   - each target process structure 'pmc_process' has an array
54890075Sobrien *     of 'struct pmc *' pointers, one for each hardware PMC.
54990075Sobrien *
550117395Skan *   - At context switch IN time, each "target" PMC in RUNNING state
55190075Sobrien *     gets started on hardware and a pointer to each PMC is copied into
55290075Sobrien *     the per-cpu phw array.  The 'runcount' for the PMC is
553132718Skan *     incremented.
55490075Sobrien *
55590075Sobrien *   - At context switch OUT time, all process-virtual PMCs are stopped
55690075Sobrien *     on hardware.  The saved value is added to the PMCs value field
55790075Sobrien *     only if the PMC is in a non-deleted state (the PMCs state could
55890075Sobrien *     have changed during the current time slice).
55990075Sobrien *
56090075Sobrien *     Note that since in-between a switch IN on a processor and a switch
56190075Sobrien *     OUT, the PMC could have been released on another CPU.  Therefore
56290075Sobrien *     context switch OUT always looks at the hardware state to turn
56390075Sobrien *     OFF PMCs and will update a PMC's saved value only if reachable
56490075Sobrien *     from the target process record.
56590075Sobrien *
56690075Sobrien *   - OP PMCRELEASE could be called on a PMC at any time (the PMC could
56790075Sobrien *     be attached to many processes at the time of the call and could
56890075Sobrien *     be active on multiple CPUs).
56990075Sobrien *
57090075Sobrien *     We prevent further scheduling of the PMC by marking it as in
57190075Sobrien *     state 'DELETED'.  If the runcount of the PMC is non-zero then
57290075Sobrien *     this PMC is currently running on a CPU somewhere.  The thread
57390075Sobrien *     doing the PMCRELEASE operation waits by repeatedly doing an
57490075Sobrien *     tsleep() till the runcount comes to zero.
57590075Sobrien *
57690075Sobrien */
57790075Sobrien
57890075Sobrien/*
579117395Skan * save the cpu binding of the current kthread
58090075Sobrien */
58190075Sobrien
582132718Skanstatic void
58390075Sobrienpmc_save_cpu_binding(struct pmc_binding *pb)
58490075Sobrien{
58590075Sobrien	PMCDBG(CPU,BND,2, "%s", "save-cpu");
58690075Sobrien	mtx_lock_spin(&sched_lock);
58790075Sobrien	pb->pb_bound = sched_is_bound(curthread);
58890075Sobrien	pb->pb_cpu   = curthread->td_oncpu;
58990075Sobrien	mtx_unlock_spin(&sched_lock);
59090075Sobrien	PMCDBG(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
59190075Sobrien}
59290075Sobrien
59390075Sobrien/*
59490075Sobrien * restore the cpu binding of the current thread
59590075Sobrien */
59690075Sobrien
597117395Skanstatic void
59890075Sobrienpmc_restore_cpu_binding(struct pmc_binding *pb)
59990075Sobrien{
600132718Skan	PMCDBG(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
60190075Sobrien	    curthread->td_oncpu, pb->pb_cpu);
60290075Sobrien	mtx_lock_spin(&sched_lock);
60390075Sobrien	if (pb->pb_bound)
60490075Sobrien		sched_bind(curthread, pb->pb_cpu);
60590075Sobrien	else
60690075Sobrien		sched_unbind(curthread);
60790075Sobrien	mtx_unlock_spin(&sched_lock);
60890075Sobrien	PMCDBG(CPU,BND,2, "%s", "restore-cpu done");
60990075Sobrien}
61090075Sobrien
61190075Sobrien/*
61290075Sobrien * move execution over the specified cpu and bind it there.
61390075Sobrien */
61490075Sobrien
615117395Skanstatic void
61690075Sobrienpmc_select_cpu(int cpu)
61790075Sobrien{
618132718Skan	KASSERT(cpu >= 0 && cpu < mp_ncpus,
61990075Sobrien	    ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
62090075Sobrien
62190075Sobrien	/* never move to a disabled CPU */
62290075Sobrien	KASSERT(pmc_cpu_is_disabled(cpu) == 0, ("[pmc,%d] selecting "
62390075Sobrien	    "disabled CPU %d", __LINE__, cpu));
62490075Sobrien
62590075Sobrien	PMCDBG(CPU,SEL,2, "select-cpu cpu=%d", cpu);
62690075Sobrien	mtx_lock_spin(&sched_lock);
62790075Sobrien	sched_bind(curthread, cpu);
62890075Sobrien	mtx_unlock_spin(&sched_lock);
62990075Sobrien
63090075Sobrien	KASSERT(curthread->td_oncpu == cpu,
63190075Sobrien	    ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
632117395Skan		cpu, curthread->td_oncpu));
63390075Sobrien
63490075Sobrien	PMCDBG(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
635132718Skan}
63690075Sobrien
63790075Sobrien/*
63890075Sobrien * Force a context switch.
63990075Sobrien *
64090075Sobrien * We do this by tsleep'ing for 1 tick -- invoking mi_switch() is not
64190075Sobrien * guaranteed to force a context switch.
64290075Sobrien */
64390075Sobrien
644117395Skanstatic void
64590075Sobrienpmc_force_context_switch(void)
64690075Sobrien{
64790075Sobrien	u_char	curpri;
64890075Sobrien
649117395Skan	mtx_lock_spin(&sched_lock);
65090075Sobrien	curpri = curthread->td_priority;
65190075Sobrien	mtx_unlock_spin(&sched_lock);
652132718Skan
653132718Skan	(void) tsleep((void *) pmc_force_context_switch, curpri,
65490075Sobrien	    "pmcctx", 1);
65590075Sobrien
65690075Sobrien}
65790075Sobrien
65890075Sobrien/*
65990075Sobrien * Get the file name for an executable.  This is a simple wrapper
66090075Sobrien * around vn_fullpath(9).
66190075Sobrien */
66290075Sobrien
66390075Sobrienstatic void
66490075Sobrienpmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
66590075Sobrien{
66690075Sobrien	struct thread *td;
66790075Sobrien
668117395Skan	td = curthread;
66990075Sobrien	*fullpath = "unknown";
67090075Sobrien	*freepath = NULL;
671132718Skan	vn_lock(v, LK_CANRECURSE | LK_EXCLUSIVE | LK_RETRY, td);
672132718Skan	vn_fullpath(td, v, fullpath, freepath);
67390075Sobrien	VOP_UNLOCK(v, 0, td);
67490075Sobrien}
67590075Sobrien
67690075Sobrien/*
67790075Sobrien * remove an process owning PMCs
67890075Sobrien */
67990075Sobrien
68090075Sobrienvoid
68190075Sobrienpmc_remove_owner(struct pmc_owner *po)
68290075Sobrien{
68390075Sobrien	struct pmc *pm, *tmp;
68490075Sobrien
68590075Sobrien	sx_assert(&pmc_sx, SX_XLOCKED);
68690075Sobrien
687117395Skan	PMCDBG(OWN,ORM,1, "remove-owner po=%p", po);
68890075Sobrien
68990075Sobrien	/* Remove descriptor from the owner hash table */
690132718Skan	LIST_REMOVE(po, po_next);
69190075Sobrien
69290075Sobrien	/* release all owned PMC descriptors */
69390075Sobrien	LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
69490075Sobrien		PMCDBG(OWN,ORM,2, "pmc=%p", pm);
69590075Sobrien		KASSERT(pm->pm_owner == po,
69690075Sobrien		    ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
69790075Sobrien
69890075Sobrien		pmc_release_pmc_descriptor(pm);	/* will unlink from the list */
699117395Skan	}
70090075Sobrien
70190075Sobrien	KASSERT(po->po_sscount == 0,
70290075Sobrien	    ("[pmc,%d] SS count not zero", __LINE__));
70390075Sobrien	KASSERT(LIST_EMPTY(&po->po_pmcs),
704117395Skan	    ("[pmc,%d] PMC list not empty", __LINE__));
70590075Sobrien
70690075Sobrien	/* de-configure the log file if present */
707132718Skan	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
70890075Sobrien		pmclog_deconfigure_log(po);
70990075Sobrien}
71090075Sobrien
71190075Sobrien/*
71290075Sobrien * remove an owner process record if all conditions are met.
71390075Sobrien */
71490075Sobrien
71590075Sobrienstatic void
71690075Sobrienpmc_maybe_remove_owner(struct pmc_owner *po)
71790075Sobrien{
71890075Sobrien
71990075Sobrien	PMCDBG(OWN,OMR,1, "maybe-remove-owner po=%p", po);
72090075Sobrien
72190075Sobrien	/*
72290075Sobrien	 * Remove owner record if
72390075Sobrien	 * - this process does not own any PMCs
72490075Sobrien	 * - this process has not allocated a system-wide sampling buffer
72590075Sobrien	 */
72690075Sobrien
72790075Sobrien	if (LIST_EMPTY(&po->po_pmcs) &&
72890075Sobrien	    ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
72990075Sobrien		pmc_remove_owner(po);
73090075Sobrien		pmc_destroy_owner_descriptor(po);
73190075Sobrien	}
73290075Sobrien}
73390075Sobrien
73490075Sobrien/*
73590075Sobrien * Add an association between a target process and a PMC.
73690075Sobrien */
73790075Sobrien
73890075Sobrienstatic void
73990075Sobrienpmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
74090075Sobrien{
74190075Sobrien	int ri;
74290075Sobrien	struct pmc_target *pt;
74390075Sobrien
74490075Sobrien	sx_assert(&pmc_sx, SX_XLOCKED);
74590075Sobrien
74690075Sobrien	KASSERT(pm != NULL && pp != NULL,
74790075Sobrien	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
74890075Sobrien	KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
74990075Sobrien	    ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
75090075Sobrien		__LINE__, pm, pp->pp_proc->p_pid));
75190075Sobrien	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < ((int) md->pmd_npmc - 1),
75290075Sobrien	    ("[pmc,%d] Illegal reference count %d for process record %p",
75390075Sobrien		__LINE__, pp->pp_refcnt, (void *) pp));
75490075Sobrien
75590075Sobrien	ri = PMC_TO_ROWINDEX(pm);
75690075Sobrien
75790075Sobrien	PMCDBG(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
75890075Sobrien	    pm, ri, pp);
75990075Sobrien
76090075Sobrien#ifdef	DEBUG
76190075Sobrien	LIST_FOREACH(pt, &pm->pm_targets, pt_next)
76290075Sobrien	    if (pt->pt_process == pp)
76390075Sobrien		    KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
76490075Sobrien				__LINE__, pp, pm));
76590075Sobrien#endif
76690075Sobrien
767117395Skan	MALLOC(pt, struct pmc_target *, sizeof(struct pmc_target),
76890075Sobrien	    M_PMC, M_ZERO|M_WAITOK);
76990075Sobrien
770132718Skan	pt->pt_process = pp;
77190075Sobrien
77290075Sobrien	LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
77390075Sobrien
77490075Sobrien	atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
77590075Sobrien	    (uintptr_t)pm);
77690075Sobrien
77790075Sobrien	if (pm->pm_owner->po_owner == pp->pp_proc)
77890075Sobrien		pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
77990075Sobrien
78090075Sobrien	/*
78190075Sobrien	 * Initialize the per-process values at this row index.
78290075Sobrien	 */
78390075Sobrien	pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
78490075Sobrien	    pm->pm_sc.pm_reloadcount : 0;
78590075Sobrien
786117395Skan	pp->pp_refcnt++;
78790075Sobrien
78890075Sobrien}
789132718Skan
79090075Sobrien/*
79190075Sobrien * Removes the association between a target process and a PMC.
792117395Skan */
79390075Sobrien
79490075Sobrienstatic void
79590075Sobrienpmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
79690075Sobrien{
79790075Sobrien	int ri;
798169689Skan	struct proc *p;
79990075Sobrien	struct pmc_target *ptgt;
800169689Skan
80190075Sobrien	sx_assert(&pmc_sx, SX_XLOCKED);
802117395Skan
80390075Sobrien	KASSERT(pm != NULL && pp != NULL,
80490075Sobrien	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
80590075Sobrien
80690075Sobrien	KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt < (int) md->pmd_npmc,
80790075Sobrien	    ("[pmc,%d] Illegal ref count %d on process record %p",
80890075Sobrien		__LINE__, pp->pp_refcnt, (void *) pp));
80990075Sobrien
81090075Sobrien	ri = PMC_TO_ROWINDEX(pm);
81190075Sobrien
81290075Sobrien	PMCDBG(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
81390075Sobrien	    pm, ri, pp);
81490075Sobrien
815117395Skan	KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
81690075Sobrien	    ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
81790075Sobrien		ri, pm, pp->pp_pmcs[ri].pp_pmc));
81890075Sobrien
81990075Sobrien	pp->pp_pmcs[ri].pp_pmc = NULL;
82090075Sobrien	pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
82190075Sobrien
82290075Sobrien	/* Remove owner-specific flags */
82390075Sobrien	if (pm->pm_owner->po_owner == pp->pp_proc) {
82490075Sobrien		pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
82590075Sobrien		pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
82690075Sobrien	}
82790075Sobrien
82890075Sobrien	pp->pp_refcnt--;
82990075Sobrien
83090075Sobrien	/* Remove the target process from the PMC structure */
831132718Skan	LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
83290075Sobrien		if (ptgt->pt_process == pp)
83390075Sobrien			break;
83490075Sobrien
83590075Sobrien	KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
83690075Sobrien		    "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
83790075Sobrien
83890075Sobrien	LIST_REMOVE(ptgt, pt_next);
83990075Sobrien	FREE(ptgt, M_PMC);
84090075Sobrien
84190075Sobrien	/* if the PMC now lacks targets, send the owner a SIGIO */
84290075Sobrien	if (LIST_EMPTY(&pm->pm_targets)) {
84390075Sobrien		p = pm->pm_owner->po_owner;
84490075Sobrien		PROC_LOCK(p);
84590075Sobrien		psignal(p, SIGIO);
84690075Sobrien		PROC_UNLOCK(p);
84790075Sobrien
84890075Sobrien		PMCDBG(PRC,SIG,2, "signalling proc=%p signal=%d", p,
84990075Sobrien		    SIGIO);
85090075Sobrien	}
85190075Sobrien}
85290075Sobrien
85390075Sobrien/*
85490075Sobrien * Check if PMC 'pm' may be attached to target process 't'.
85590075Sobrien */
85690075Sobrien
85790075Sobrienstatic int
85890075Sobrienpmc_can_attach(struct pmc *pm, struct proc *t)
85990075Sobrien{
86090075Sobrien	struct proc *o;		/* pmc owner */
86190075Sobrien	struct ucred *oc, *tc;	/* owner, target credentials */
86290075Sobrien	int decline_attach, i;
86390075Sobrien
86490075Sobrien	/*
86590075Sobrien	 * A PMC's owner can always attach that PMC to itself.
86690075Sobrien	 */
86790075Sobrien
86890075Sobrien	if ((o = pm->pm_owner->po_owner) == t)
86990075Sobrien		return 0;
87090075Sobrien
871169689Skan	PROC_LOCK(o);
87290075Sobrien	oc = o->p_ucred;
87390075Sobrien	crhold(oc);
87490075Sobrien	PROC_UNLOCK(o);
87590075Sobrien
87690075Sobrien	PROC_LOCK(t);
87790075Sobrien	tc = t->p_ucred;
87890075Sobrien	crhold(tc);
87990075Sobrien	PROC_UNLOCK(t);
880117395Skan
88190075Sobrien	/*
88290075Sobrien	 * The effective uid of the PMC owner should match at least one
883132718Skan	 * of the {effective,real,saved} uids of the target process.
88490075Sobrien	 */
88590075Sobrien
88690075Sobrien	decline_attach = oc->cr_uid != tc->cr_uid &&
88790075Sobrien	    oc->cr_uid != tc->cr_svuid &&
88890075Sobrien	    oc->cr_uid != tc->cr_ruid;
889169689Skan
890169689Skan	/*
89190075Sobrien	 * Every one of the target's group ids, must be in the owner's
89290075Sobrien	 * group list.
89390075Sobrien	 */
89490075Sobrien	for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
89590075Sobrien		decline_attach = !groupmember(tc->cr_groups[i], oc);
89690075Sobrien
89790075Sobrien	/* check the read and saved gids too */
89890075Sobrien	if (decline_attach == 0)
89990075Sobrien		decline_attach = !groupmember(tc->cr_rgid, oc) ||
90090075Sobrien		    !groupmember(tc->cr_svgid, oc);
90190075Sobrien
90290075Sobrien	crfree(tc);
90390075Sobrien	crfree(oc);
90490075Sobrien
905169689Skan	return !decline_attach;
906169689Skan}
90790075Sobrien
90890075Sobrien/*
90990075Sobrien * Attach a process to a PMC.
91090075Sobrien */
91190075Sobrien
91290075Sobrienstatic int
91390075Sobrienpmc_attach_one_process(struct proc *p, struct pmc *pm)
91490075Sobrien{
91590075Sobrien	int ri;
91690075Sobrien	char *fullpath, *freepath;
91790075Sobrien	struct pmc_process	*pp;
91890075Sobrien
91990075Sobrien	sx_assert(&pmc_sx, SX_XLOCKED);
92090075Sobrien
92190075Sobrien	PMCDBG(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
92290075Sobrien	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
92390075Sobrien
924117395Skan	/*
92590075Sobrien	 * Locate the process descriptor corresponding to process 'p',
92690075Sobrien	 * allocating space as needed.
927132718Skan	 *
92890075Sobrien	 * Verify that rowindex 'pm_rowindex' is free in the process
92990075Sobrien	 * descriptor.
93090075Sobrien	 *
93190075Sobrien	 * If not, allocate space for a descriptor and link the
93290075Sobrien	 * process descriptor and PMC.
93390075Sobrien	 */
93490075Sobrien	ri = PMC_TO_ROWINDEX(pm);
93590075Sobrien
93690075Sobrien	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
93790075Sobrien		return ENOMEM;
93890075Sobrien
93990075Sobrien	if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
94090075Sobrien		return EEXIST;
94190075Sobrien
94290075Sobrien	if (pp->pp_pmcs[ri].pp_pmc != NULL)
94390075Sobrien		return EBUSY;
94490075Sobrien
94590075Sobrien	pmc_link_target_process(pm, pp);
94690075Sobrien
94790075Sobrien	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
94890075Sobrien	    (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
94990075Sobrien		pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
95090075Sobrien
95190075Sobrien	pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
952132718Skan
95390075Sobrien	/* issue an attach event to a configured log file */
95490075Sobrien	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
95590075Sobrien		pmc_getfilename(p->p_textvp, &fullpath, &freepath);
95690075Sobrien		pmclog_process_pmcattach(pm, p->p_pid, fullpath);
95790075Sobrien		if (freepath)
95890075Sobrien			FREE(freepath, M_TEMP);
95990075Sobrien	}
96090075Sobrien	/* mark process as using HWPMCs */
96190075Sobrien	PROC_LOCK(p);
96290075Sobrien	p->p_flag |= P_HWPMC;
96390075Sobrien	PROC_UNLOCK(p);
96490075Sobrien
96590075Sobrien	return 0;
96690075Sobrien}
96790075Sobrien
96890075Sobrien/*
96990075Sobrien * Attach a process and optionally its children
97090075Sobrien */
97190075Sobrien
97290075Sobrienstatic int
97390075Sobrienpmc_attach_process(struct proc *p, struct pmc *pm)
97490075Sobrien{
97590075Sobrien	int error;
97690075Sobrien	struct proc *top;
97790075Sobrien
97890075Sobrien	sx_assert(&pmc_sx, SX_XLOCKED);
97990075Sobrien
98090075Sobrien	PMCDBG(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
98190075Sobrien	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
98290075Sobrien
983117395Skan
984117395Skan	/*
98590075Sobrien	 * If this PMC successfully allowed a GETMSR operation
98690075Sobrien	 * in the past, disallow further ATTACHes.
98790075Sobrien	 */
98890075Sobrien
98990075Sobrien	if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
99090075Sobrien		return EPERM;
99190075Sobrien
99290075Sobrien	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
99390075Sobrien		return pmc_attach_one_process(p, pm);
99490075Sobrien
99590075Sobrien	/*
99690075Sobrien	 * Traverse all child processes, attaching them to
99790075Sobrien	 * this PMC.
99890075Sobrien	 */
99990075Sobrien
100090075Sobrien	sx_slock(&proctree_lock);
100190075Sobrien
100290075Sobrien	top = p;
100390075Sobrien
100490075Sobrien	for (;;) {
100590075Sobrien		if ((error = pmc_attach_one_process(p, pm)) != 0)
100690075Sobrien			break;
100790075Sobrien		if (!LIST_EMPTY(&p->p_children))
100890075Sobrien			p = LIST_FIRST(&p->p_children);
100990075Sobrien		else for (;;) {
101090075Sobrien			if (p == top)
101190075Sobrien				goto done;
101290075Sobrien			if (LIST_NEXT(p, p_sibling)) {
101390075Sobrien				p = LIST_NEXT(p, p_sibling);
101490075Sobrien				break;
101590075Sobrien			}
101690075Sobrien			p = p->p_pptr;
101790075Sobrien		}
101890075Sobrien	}
101990075Sobrien
102090075Sobrien	if (error)
102190075Sobrien		(void) pmc_detach_process(top, pm);
102290075Sobrien
102390075Sobrien done:
102490075Sobrien	sx_sunlock(&proctree_lock);
102590075Sobrien	return error;
102690075Sobrien}
102790075Sobrien
102890075Sobrien/*
102990075Sobrien * Detach a process from a PMC.  If there are no other PMCs tracking
103090075Sobrien * this process, remove the process structure from its hash table.  If
103190075Sobrien * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
103290075Sobrien */
103390075Sobrien
103490075Sobrienstatic int
103590075Sobrienpmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
103690075Sobrien{
103790075Sobrien	int ri;
103890075Sobrien	struct pmc_process *pp;
103990075Sobrien
104090075Sobrien	sx_assert(&pmc_sx, SX_XLOCKED);
104190075Sobrien
104290075Sobrien	KASSERT(pm != NULL,
104390075Sobrien	    ("[pmc,%d] null pm pointer", __LINE__));
104490075Sobrien
104590075Sobrien	ri = PMC_TO_ROWINDEX(pm);
104690075Sobrien
104790075Sobrien	PMCDBG(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
104890075Sobrien	    pm, ri, p, p->p_pid, p->p_comm, flags);
104990075Sobrien
105090075Sobrien	if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
105190075Sobrien		return ESRCH;
105290075Sobrien
105390075Sobrien	if (pp->pp_pmcs[ri].pp_pmc != pm)
1054117395Skan		return EINVAL;
105590075Sobrien
105690075Sobrien	pmc_unlink_target_process(pm, pp);
1057132718Skan
1058132718Skan	/* Issue a detach entry if a log file is configured */
105990075Sobrien	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
106090075Sobrien		pmclog_process_pmcdetach(pm, p->p_pid);
106190075Sobrien
106290075Sobrien	/*
106390075Sobrien	 * If there are no PMCs targetting this process, we remove its
106490075Sobrien	 * descriptor from the target hash table and unset the P_HWPMC
106590075Sobrien	 * flag in the struct proc.
106690075Sobrien	 */
106790075Sobrien	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
106890075Sobrien	    ("[pmc,%d] Illegal refcnt %d for process struct %p",
106990075Sobrien		__LINE__, pp->pp_refcnt, pp));
107090075Sobrien
107190075Sobrien	if (pp->pp_refcnt != 0)	/* still a target of some PMC */
107290075Sobrien		return 0;
107390075Sobrien
107490075Sobrien	pmc_remove_process_descriptor(pp);
107590075Sobrien
107690075Sobrien	if (flags & PMC_FLAG_REMOVE)
107790075Sobrien		FREE(pp, M_PMC);
107890075Sobrien
107990075Sobrien	PROC_LOCK(p);
108090075Sobrien	p->p_flag &= ~P_HWPMC;
108190075Sobrien	PROC_UNLOCK(p);
108290075Sobrien
108390075Sobrien	return 0;
108490075Sobrien}
108590075Sobrien
108690075Sobrien/*
108790075Sobrien * Detach a process and optionally its descendants from a PMC.
108890075Sobrien */
108990075Sobrien
109090075Sobrienstatic int
109190075Sobrienpmc_detach_process(struct proc *p, struct pmc *pm)
109290075Sobrien{
109390075Sobrien	struct proc *top;
109490075Sobrien
109590075Sobrien	sx_assert(&pmc_sx, SX_XLOCKED);
109690075Sobrien
109790075Sobrien	PMCDBG(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
109890075Sobrien	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
109990075Sobrien
110090075Sobrien	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
110190075Sobrien		return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
110290075Sobrien
110390075Sobrien	/*
110490075Sobrien	 * Traverse all children, detaching them from this PMC.  We
110590075Sobrien	 * ignore errors since we could be detaching a PMC from a
110690075Sobrien	 * partially attached proc tree.
110790075Sobrien	 */
110890075Sobrien
110990075Sobrien	sx_slock(&proctree_lock);
111090075Sobrien
111190075Sobrien	top = p;
111290075Sobrien
111390075Sobrien	for (;;) {
111490075Sobrien		(void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
111590075Sobrien
1116117395Skan		if (!LIST_EMPTY(&p->p_children))
111790075Sobrien			p = LIST_FIRST(&p->p_children);
111890075Sobrien		else for (;;) {
111990075Sobrien			if (p == top)
112090075Sobrien				goto done;
112190075Sobrien			if (LIST_NEXT(p, p_sibling)) {
112290075Sobrien				p = LIST_NEXT(p, p_sibling);
112390075Sobrien				break;
112490075Sobrien			}
112590075Sobrien			p = p->p_pptr;
112690075Sobrien		}
112790075Sobrien	}
112890075Sobrien
112990075Sobrien done:
113090075Sobrien	sx_sunlock(&proctree_lock);
113190075Sobrien
113290075Sobrien	if (LIST_EMPTY(&pm->pm_targets))
113390075Sobrien		pm->pm_flags &= ~PMC_F_ATTACH_DONE;
113490075Sobrien
113590075Sobrien	return 0;
1136117395Skan}
113790075Sobrien
113890075Sobrien
113990075Sobrien/*
114090075Sobrien * Thread context switch IN
114190075Sobrien */
114290075Sobrien
114390075Sobrienstatic void
114490075Sobrienpmc_process_csw_in(struct thread *td)
114590075Sobrien{
114690075Sobrien	int cpu;
114790075Sobrien	unsigned int ri;
114890075Sobrien	struct pmc *pm;
114990075Sobrien	struct proc *p;
115090075Sobrien	struct pmc_cpu *pc;
115190075Sobrien	struct pmc_hw *phw;
115290075Sobrien	struct pmc_process *pp;
115390075Sobrien	pmc_value_t newvalue;
115490075Sobrien
115590075Sobrien	p = td->td_proc;
115690075Sobrien
115790075Sobrien	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
115890075Sobrien		return;
115990075Sobrien
116090075Sobrien	KASSERT(pp->pp_proc == td->td_proc,
116190075Sobrien	    ("[pmc,%d] not my thread state", __LINE__));
116290075Sobrien
116390075Sobrien	critical_enter(); /* no preemption from this point */
116490075Sobrien
116590075Sobrien	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
116690075Sobrien
116790075Sobrien	PMCDBG(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
116890075Sobrien	    p->p_pid, p->p_comm, pp);
116990075Sobrien
117090075Sobrien	KASSERT(cpu >= 0 && cpu < mp_ncpus,
117190075Sobrien	    ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
117290075Sobrien
117390075Sobrien	pc = pmc_pcpu[cpu];
117490075Sobrien
117590075Sobrien	for (ri = 0; ri < md->pmd_npmc; ri++) {
117690075Sobrien
117790075Sobrien		if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
117890075Sobrien			continue;
117990075Sobrien
118090075Sobrien		KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1181117395Skan		    ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1182117395Skan			__LINE__, PMC_TO_MODE(pm)));
1183117395Skan
1184117395Skan		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
118590075Sobrien		    ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1186117395Skan			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1187117395Skan
118890075Sobrien		/*
1189117395Skan		 * Only PMCs that are marked as 'RUNNING' need
1190117395Skan		 * be placed on hardware.
1191117395Skan		 */
119290075Sobrien
1193117395Skan		if (pm->pm_state != PMC_STATE_RUNNING)
1194117395Skan			continue;
119590075Sobrien
1196117395Skan		/* increment PMC runcount */
1197117395Skan		atomic_add_rel_32(&pm->pm_runcount, 1);
1198117395Skan
119990075Sobrien		/* configure the HWPMC we are going to use. */
1200117395Skan		md->pmd_config_pmc(cpu, ri, pm);
1201117395Skan
120290075Sobrien		phw = pc->pc_hwpmcs[ri];
1203117395Skan
1204117395Skan		KASSERT(phw != NULL,
1205117395Skan		    ("[pmc,%d] null hw pointer", __LINE__));
120690075Sobrien
120790075Sobrien		KASSERT(phw->phw_pmc == pm,
120890075Sobrien		    ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1209117395Skan			phw->phw_pmc, pm));
121090075Sobrien
121190075Sobrien		/*
121290075Sobrien		 * Write out saved value and start the PMC.
121390075Sobrien		 *
121490075Sobrien		 * Sampling PMCs use a per-process value, while
1215117395Skan		 * counting mode PMCs use a per-pmc value that is
1216117395Skan		 * inherited across descendants.
1217117395Skan		 */
1218117395Skan		if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1219117395Skan			mtx_pool_lock_spin(pmc_mtxpool, pm);
1220117395Skan			newvalue = PMC_PCPU_SAVED(cpu,ri) =
1221117395Skan			    pp->pp_pmcs[ri].pp_pmcval;
1222117395Skan			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1223117395Skan		} else {
1224117395Skan			KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1225117395Skan			    ("[pmc,%d] illegal mode=%d", __LINE__,
1226117395Skan			    PMC_TO_MODE(pm)));
1227117395Skan			mtx_pool_lock_spin(pmc_mtxpool, pm);
1228117395Skan			newvalue = PMC_PCPU_SAVED(cpu, ri) =
1229117395Skan			    pm->pm_gv.pm_savedvalue;
1230117395Skan			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1231117395Skan		}
1232117395Skan
1233117395Skan		PMCDBG(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1234117395Skan
1235117395Skan		md->pmd_write_pmc(cpu, ri, newvalue);
1236117395Skan		md->pmd_start_pmc(cpu, ri);
1237117395Skan	}
1238117395Skan
1239117395Skan	/*
1240117395Skan	 * perform any other architecture/cpu dependent thread
124190075Sobrien	 * switch-in actions.
124290075Sobrien	 */
124390075Sobrien
124490075Sobrien	(void) (*md->pmd_switch_in)(pc, pp);
124590075Sobrien
124690075Sobrien	critical_exit();
1247117395Skan
124890075Sobrien}
124990075Sobrien
1250132718Skan/*
125190075Sobrien * Thread context switch OUT.
125290075Sobrien */
125390075Sobrien
125490075Sobrienstatic void
125590075Sobrienpmc_process_csw_out(struct thread *td)
125690075Sobrien{
125790075Sobrien	int cpu;
125890075Sobrien	enum pmc_mode mode;
1259117395Skan	unsigned int ri;
126090075Sobrien	struct pmc *pm;
126190075Sobrien	struct proc *p;
126290075Sobrien	struct pmc_cpu *pc;
126390075Sobrien	struct pmc_process *pp;
126490075Sobrien	int64_t tmp;
1265132718Skan	pmc_value_t newvalue;
126690075Sobrien
126790075Sobrien	/*
126890075Sobrien	 * Locate our process descriptor; this may be NULL if
126990075Sobrien	 * this process is exiting and we have already removed
127090075Sobrien	 * the process from the target process table.
127190075Sobrien	 *
127290075Sobrien	 * Note that due to kernel preemption, multiple
127390075Sobrien	 * context switches may happen while the process is
127490075Sobrien	 * exiting.
1275117395Skan	 *
127690075Sobrien	 * Note also that if the target process cannot be
127790075Sobrien	 * found we still need to deconfigure any PMCs that
127890075Sobrien	 * are currently running on hardware.
127990075Sobrien	 */
128090075Sobrien
128190075Sobrien	p = td->td_proc;
128290075Sobrien	pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1283117395Skan
1284132718Skan	/*
128590075Sobrien	 * save PMCs
128690075Sobrien	 */
128790075Sobrien
1288117395Skan	critical_enter();
1289117395Skan
1290117395Skan	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
129190075Sobrien
129290075Sobrien	PMCDBG(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
129390075Sobrien	    p->p_pid, p->p_comm, pp);
1294117395Skan
129590075Sobrien	KASSERT(cpu >= 0 && cpu < mp_ncpus,
1296117395Skan	    ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1297132718Skan
1298117395Skan	pc = pmc_pcpu[cpu];
129990075Sobrien
130090075Sobrien	/*
130190075Sobrien	 * When a PMC gets unlinked from a target PMC, it will
1302117395Skan	 * be removed from the target's pp_pmc[] array.
1303117395Skan	 *
1304117395Skan	 * However, on a MP system, the target could have been
1305132718Skan	 * executing on another CPU at the time of the unlink.
1306117395Skan	 * So, at context switch OUT time, we need to look at
1307117395Skan	 * the hardware to determine if a PMC is scheduled on
1308117395Skan	 * it.
1309117395Skan	 */
1310117395Skan
131190075Sobrien	for (ri = 0; ri < md->pmd_npmc; ri++) {
131290075Sobrien
131390075Sobrien		pm = NULL;
131490075Sobrien		(void) (*md->pmd_get_config)(cpu, ri, &pm);
131590075Sobrien
1316132718Skan		if (pm == NULL)	/* nothing at this row index */
131790075Sobrien			continue;
131890075Sobrien
131990075Sobrien		mode = PMC_TO_MODE(pm);
132090075Sobrien		if (!PMC_IS_VIRTUAL_MODE(mode))
1321117395Skan			continue; /* not a process virtual PMC */
132290075Sobrien
132390075Sobrien		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
132490075Sobrien		    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
132590075Sobrien			__LINE__, PMC_TO_ROWINDEX(pm), ri));
132690075Sobrien
132790075Sobrien		/* Stop hardware if not already stopped */
1328117395Skan		if (pm->pm_stalled == 0)
132990075Sobrien			md->pmd_stop_pmc(cpu, ri);
1330117395Skan
1331132718Skan		/* reduce this PMC's runcount */
1332117395Skan		atomic_subtract_rel_32(&pm->pm_runcount, 1);
133390075Sobrien
133490075Sobrien		/*
133590075Sobrien		 * If this PMC is associated with this process,
133690075Sobrien		 * save the reading.
133790075Sobrien		 */
133890075Sobrien
133990075Sobrien		if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1340132718Skan
134190075Sobrien			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
134290075Sobrien			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
134390075Sobrien				pm, ri, pp->pp_pmcs[ri].pp_pmc));
134490075Sobrien
134590075Sobrien			KASSERT(pp->pp_refcnt > 0,
1346169689Skan			    ("[pmc,%d] pp refcnt = %d", __LINE__,
134790075Sobrien				pp->pp_refcnt));
134890075Sobrien
134990075Sobrien			md->pmd_read_pmc(cpu, ri, &newvalue);
135090075Sobrien
135190075Sobrien			tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
135290075Sobrien
1353132718Skan			PMCDBG(CSW,SWI,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
135490075Sobrien			    tmp);
135590075Sobrien
135690075Sobrien			if (mode == PMC_MODE_TS) {
135790075Sobrien
135890075Sobrien				/*
1359169689Skan				 * For sampling process-virtual PMCs,
136090075Sobrien				 * we expect the count to be
136190075Sobrien				 * decreasing as the 'value'
136290075Sobrien				 * programmed into the PMC is the
136390075Sobrien				 * number of events to be seen till
136490075Sobrien				 * the next sampling interrupt.
1365132718Skan				 */
136690075Sobrien				if (tmp < 0)
136790075Sobrien					tmp += pm->pm_sc.pm_reloadcount;
136890075Sobrien				mtx_pool_lock_spin(pmc_mtxpool, pm);
136990075Sobrien				pp->pp_pmcs[ri].pp_pmcval -= tmp;
137090075Sobrien				if ((int64_t) pp->pp_pmcs[ri].pp_pmcval < 0)
137190075Sobrien					pp->pp_pmcs[ri].pp_pmcval +=
137290075Sobrien					    pm->pm_sc.pm_reloadcount;
137390075Sobrien				mtx_pool_unlock_spin(pmc_mtxpool, pm);
137490075Sobrien
137590075Sobrien			} else {
137690075Sobrien
137790075Sobrien				/*
1378132718Skan				 * For counting process-virtual PMCs,
137990075Sobrien				 * we expect the count to be
138090075Sobrien				 * increasing monotonically, modulo a 64
1381169689Skan				 * bit wraparound.
138290075Sobrien				 */
138390075Sobrien				KASSERT((int64_t) tmp >= 0,
138490075Sobrien				    ("[pmc,%d] negative increment cpu=%d "
138590075Sobrien				     "ri=%d newvalue=%jx saved=%jx "
138690075Sobrien				     "incr=%jx", __LINE__, cpu, ri,
138790075Sobrien				     newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
138890075Sobrien
1389169689Skan				mtx_pool_lock_spin(pmc_mtxpool, pm);
1390169689Skan				pm->pm_gv.pm_savedvalue += tmp;
1391169689Skan				pp->pp_pmcs[ri].pp_pmcval += tmp;
139290075Sobrien				mtx_pool_unlock_spin(pmc_mtxpool, pm);
139390075Sobrien
139490075Sobrien				if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1395169689Skan					pmclog_process_proccsw(pm, pp, tmp);
1396169689Skan			}
1397169689Skan		}
1398169689Skan
139990075Sobrien		/* mark hardware as free */
140090075Sobrien		md->pmd_config_pmc(cpu, ri, NULL);
140190075Sobrien	}
140290075Sobrien
140390075Sobrien	/*
140490075Sobrien	 * perform any other architecture/cpu dependent thread
140590075Sobrien	 * switch out functions.
140690075Sobrien	 */
1407132718Skan
140890075Sobrien	(void) (*md->pmd_switch_out)(pc, pp);
140990075Sobrien
141090075Sobrien	critical_exit();
141190075Sobrien}
141290075Sobrien
141390075Sobrien/*
141490075Sobrien * The 'hook' invoked from the kernel proper
141590075Sobrien */
141690075Sobrien
141790075Sobrien
141890075Sobrien#ifdef	DEBUG
141990075Sobrienconst char *pmc_hooknames[] = {
142090075Sobrien	"",
142190075Sobrien	"EXIT",
142290075Sobrien	"EXEC",
142390075Sobrien	"FORK",
142490075Sobrien	"CSW-IN",
142590075Sobrien	"CSW-OUT",
142690075Sobrien	"SAMPLE"
142790075Sobrien};
142890075Sobrien#endif
142990075Sobrien
143090075Sobrienstatic int
143190075Sobrienpmc_hook_handler(struct thread *td, int function, void *arg)
143290075Sobrien{
143390075Sobrien
143490075Sobrien	PMCDBG(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
143590075Sobrien	    pmc_hooknames[function], arg);
143690075Sobrien
143790075Sobrien	switch (function)
1438132718Skan	{
143990075Sobrien
144090075Sobrien	/*
144190075Sobrien	 * Process exec()
144290075Sobrien	 */
144390075Sobrien
144490075Sobrien	case PMC_FN_PROCESS_EXEC:
144590075Sobrien	{
144690075Sobrien		char *fullpath, *freepath;
144790075Sobrien		unsigned int ri;
144890075Sobrien		int is_using_hwpmcs;
144990075Sobrien		struct pmc *pm;
145090075Sobrien		struct proc *p;
145190075Sobrien		struct pmc_owner *po;
145290075Sobrien		struct pmc_process *pp;
145396263Sobrien		struct pmckern_procexec *pk;
145490075Sobrien
145596263Sobrien		sx_assert(&pmc_sx, SX_XLOCKED);
145696263Sobrien
1457132718Skan		p = td->td_proc;
145896263Sobrien		pmc_getfilename(p->p_textvp, &fullpath, &freepath);
145996263Sobrien
146096263Sobrien		pk = (struct pmckern_procexec *) arg;
1461132718Skan
146290075Sobrien		/* Inform owners of SS mode PMCs of the exec event. */
146390075Sobrien		LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
146496263Sobrien		    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
146596263Sobrien			    pmclog_process_procexec(po, PMC_ID_INVALID,
146696263Sobrien				p->p_pid, pk->pm_entryaddr, fullpath);
1467132718Skan
146890075Sobrien		PROC_LOCK(p);
146990075Sobrien		is_using_hwpmcs = p->p_flag & P_HWPMC;
147096263Sobrien		PROC_UNLOCK(p);
147196263Sobrien
147296263Sobrien		if (!is_using_hwpmcs) {
147390075Sobrien			if (freepath)
147490075Sobrien				FREE(freepath, M_TEMP);
147590075Sobrien			break;
147690075Sobrien		}
147790075Sobrien
147890075Sobrien		/*
147990075Sobrien		 * PMCs are not inherited across an exec():  remove any
148090075Sobrien		 * PMCs that this process is the owner of.
148190075Sobrien		 */
148290075Sobrien
148390075Sobrien		if ((po = pmc_find_owner_descriptor(p)) != NULL) {
148490075Sobrien			pmc_remove_owner(po);
148590075Sobrien			pmc_destroy_owner_descriptor(po);
148690075Sobrien		}
148790075Sobrien
148890075Sobrien		/*
148990075Sobrien		 * If the process being exec'ed is not the target of any
149090075Sobrien		 * PMC, we are done.
149190075Sobrien		 */
149290075Sobrien		if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
149390075Sobrien			if (freepath)
149490075Sobrien				FREE(freepath, M_TEMP);
149590075Sobrien			break;
149690075Sobrien		}
149790075Sobrien
149890075Sobrien		/*
149990075Sobrien		 * Log the exec event to all monitoring owners.  Skip
150090075Sobrien		 * owners who have already recieved the event because
150190075Sobrien		 * they had system sampling PMCs active.
150290075Sobrien		 */
150390075Sobrien		for (ri = 0; ri < md->pmd_npmc; ri++)
150490075Sobrien			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
150590075Sobrien				po = pm->pm_owner;
1506117395Skan				if (po->po_sscount == 0 &&
150790075Sobrien				    po->po_flags & PMC_PO_OWNS_LOGFILE)
150890075Sobrien					pmclog_process_procexec(po, pm->pm_id,
150990075Sobrien					    p->p_pid, pk->pm_entryaddr,
151090075Sobrien					    fullpath);
151190075Sobrien			}
1512132718Skan
1513132718Skan		if (freepath)
1514132718Skan			FREE(freepath, M_TEMP);
151590075Sobrien
151690075Sobrien
151790075Sobrien		PMCDBG(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
151890075Sobrien		    p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
151990075Sobrien
152090075Sobrien		if (pk->pm_credentialschanged == 0) /* no change */
152190075Sobrien			break;
152290075Sobrien
152390075Sobrien		/*
152490075Sobrien		 * If the newly exec()'ed process has a different credential
152590075Sobrien		 * than before, allow it to be the target of a PMC only if
152690075Sobrien		 * the PMC's owner has sufficient priviledge.
152790075Sobrien		 */
152890075Sobrien
152990075Sobrien		for (ri = 0; ri < md->pmd_npmc; ri++)
153090075Sobrien			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
153190075Sobrien				if (pmc_can_attach(pm, td->td_proc) != 0)
153290075Sobrien					pmc_detach_one_process(td->td_proc,
153390075Sobrien					    pm, PMC_FLAG_NONE);
153490075Sobrien
1535132718Skan		KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
153690075Sobrien		    ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
153790075Sobrien			pp->pp_refcnt, pp));
153890075Sobrien
153990075Sobrien		/*
154090075Sobrien		 * If this process is no longer the target of any
154190075Sobrien		 * PMCs, we can remove the process entry and free
154290075Sobrien		 * up space.
154390075Sobrien		 */
1544169689Skan
1545169689Skan		if (pp->pp_refcnt == 0) {
154690075Sobrien			pmc_remove_process_descriptor(pp);
154790075Sobrien			FREE(pp, M_PMC);
154890075Sobrien			break;
154990075Sobrien		}
155090075Sobrien
1551132718Skan	}
1552132718Skan	break;
1553132718Skan
1554117395Skan	case PMC_FN_CSW_IN:
155590075Sobrien		pmc_process_csw_in(td);
155690075Sobrien		break;
155790075Sobrien
155890075Sobrien	case PMC_FN_CSW_OUT:
155990075Sobrien		pmc_process_csw_out(td);
156090075Sobrien		break;
156190075Sobrien
156290075Sobrien	/*
156390075Sobrien	 * Process accumulated PC samples.
156490075Sobrien	 *
156590075Sobrien	 * This function is expected to be called by hardclock() for
156690075Sobrien	 * each CPU that has accumulated PC samples.
156790075Sobrien	 *
156890075Sobrien	 * This function is to be executed on the CPU whose samples
1569132718Skan	 * are being processed.
157090075Sobrien	 */
157190075Sobrien	case PMC_FN_DO_SAMPLES:
157290075Sobrien
157390075Sobrien		/*
157490075Sobrien		 * Clear the cpu specific bit in the CPU mask before
157590075Sobrien		 * do the rest of the processing.  If the NMI handler
157690075Sobrien		 * gets invoked after the "atomic_clear_int()" call
157790075Sobrien		 * below but before "pmc_process_samples()" gets
157890075Sobrien		 * around to processing the interrupt, then we will
1579132718Skan		 * come back here at the next hardclock() tick (and
158090075Sobrien		 * may find nothing to do if "pmc_process_samples()"
158190075Sobrien		 * had already processed the interrupt).  We don't
158290075Sobrien		 * lose the interrupt sample.
158390075Sobrien		 */
158490075Sobrien		atomic_clear_int(&pmc_cpumask, (1 << PCPU_GET(cpuid)));
158590075Sobrien		pmc_process_samples(PCPU_GET(cpuid));
158690075Sobrien		break;
158790075Sobrien
1588132718Skan	default:
158990075Sobrien#ifdef	DEBUG
159090075Sobrien		KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
159190075Sobrien#endif
159290075Sobrien		break;
159390075Sobrien
159490075Sobrien	}
159590075Sobrien
159690075Sobrien	return 0;
159790075Sobrien}
159890075Sobrien
159990075Sobrien/*
160090075Sobrien * allocate a 'struct pmc_owner' descriptor in the owner hash table.
160190075Sobrien */
160290075Sobrien
1603132718Skanstatic struct pmc_owner *
160490075Sobrienpmc_allocate_owner_descriptor(struct proc *p)
160590075Sobrien{
160690075Sobrien	uint32_t hindex;
160790075Sobrien	struct pmc_owner *po;
160890075Sobrien	struct pmc_ownerhash *poh;
1609169689Skan
161090075Sobrien	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
161190075Sobrien	poh = &pmc_ownerhash[hindex];
161290075Sobrien
161390075Sobrien	/* allocate space for N pointers and one descriptor struct */
161490075Sobrien	MALLOC(po, struct pmc_owner *, sizeof(struct pmc_owner),
1615132718Skan	    M_PMC, M_ZERO|M_WAITOK);
161690075Sobrien
161790075Sobrien	po->po_sscount = po->po_error = po->po_flags = 0;
161890075Sobrien	po->po_file  = NULL;
161990075Sobrien	po->po_owner = p;
162090075Sobrien	po->po_kthread = NULL;
162190075Sobrien	LIST_INIT(&po->po_pmcs);
162290075Sobrien	LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
162390075Sobrien
162490075Sobrien	TAILQ_INIT(&po->po_logbuffers);
162590075Sobrien	mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc", MTX_SPIN);
162690075Sobrien
162790075Sobrien	PMCDBG(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
162890075Sobrien	    p, p->p_pid, p->p_comm, po);
162990075Sobrien
163090075Sobrien	return po;
163190075Sobrien}
163290075Sobrien
1633117395Skanstatic void
163490075Sobrienpmc_destroy_owner_descriptor(struct pmc_owner *po)
163590075Sobrien{
163690075Sobrien
163790075Sobrien	PMCDBG(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
163890075Sobrien	    po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
163990075Sobrien
164090075Sobrien	mtx_destroy(&po->po_mtx);
164190075Sobrien	FREE(po, M_PMC);
1642132718Skan}
164390075Sobrien
164490075Sobrien/*
164590075Sobrien * find the descriptor corresponding to process 'p', adding or removing it
164690075Sobrien * as specified by 'mode'.
164790075Sobrien */
164890075Sobrien
164990075Sobrienstatic struct pmc_process *
165090075Sobrienpmc_find_process_descriptor(struct proc *p, uint32_t mode)
1651132718Skan{
165290075Sobrien	uint32_t hindex;
165390075Sobrien	struct pmc_process *pp, *ppnew;
165490075Sobrien	struct pmc_processhash *pph;
165590075Sobrien
165690075Sobrien	hindex = PMC_HASH_PTR(p, pmc_processhashmask);
165790075Sobrien	pph = &pmc_processhash[hindex];
165890075Sobrien
165990075Sobrien	ppnew = NULL;
1660132718Skan
166190075Sobrien	/*
166290075Sobrien	 * Pre-allocate memory in the FIND_ALLOCATE case since we
166390075Sobrien	 * cannot call malloc(9) once we hold a spin lock.
166490075Sobrien	 */
166590075Sobrien
166690075Sobrien	if (mode & PMC_FLAG_ALLOCATE) {
166790075Sobrien		/* allocate additional space for 'n' pmc pointers */
166890075Sobrien		MALLOC(ppnew, struct pmc_process *,
1669132718Skan		    sizeof(struct pmc_process) + md->pmd_npmc *
167090075Sobrien		    sizeof(struct pmc_targetstate), M_PMC, M_ZERO|M_WAITOK);
167190075Sobrien	}
167290075Sobrien
167390075Sobrien	mtx_lock_spin(&pmc_processhash_mtx);
167490075Sobrien	LIST_FOREACH(pp, pph, pp_next)
167590075Sobrien	    if (pp->pp_proc == p)
167690075Sobrien		    break;
167790075Sobrien
1678132718Skan	if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
167990075Sobrien		LIST_REMOVE(pp, pp_next);
168090075Sobrien
168190075Sobrien	if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
168290075Sobrien	    ppnew != NULL) {
168390075Sobrien		ppnew->pp_proc = p;
168490075Sobrien		LIST_INSERT_HEAD(pph, ppnew, pp_next);
168590075Sobrien		pp = ppnew;
168690075Sobrien		ppnew = NULL;
168790075Sobrien	}
1688132718Skan	mtx_unlock_spin(&pmc_processhash_mtx);
168990075Sobrien
169090075Sobrien	if (pp != NULL && ppnew != NULL)
169190075Sobrien		FREE(ppnew, M_PMC);
169290075Sobrien
169390075Sobrien	return pp;
1694132718Skan}
169590075Sobrien
169690075Sobrien/*
169790075Sobrien * remove a process descriptor from the process hash table.
169890075Sobrien */
169990075Sobrien
1700169689Skanstatic void
1701169689Skanpmc_remove_process_descriptor(struct pmc_process *pp)
170290075Sobrien{
170390075Sobrien	KASSERT(pp->pp_refcnt == 0,
170490075Sobrien	    ("[pmc,%d] Removing process descriptor %p with count %d",
170590075Sobrien		__LINE__, pp, pp->pp_refcnt));
1706169689Skan
170790075Sobrien	mtx_lock_spin(&pmc_processhash_mtx);
170890075Sobrien	LIST_REMOVE(pp, pp_next);
170990075Sobrien	mtx_unlock_spin(&pmc_processhash_mtx);
171090075Sobrien}
171190075Sobrien
171290075Sobrien
171390075Sobrien/*
171490075Sobrien * find an owner descriptor corresponding to proc 'p'
171590075Sobrien */
171690075Sobrien
171790075Sobrienstatic struct pmc_owner *
171890075Sobrienpmc_find_owner_descriptor(struct proc *p)
171990075Sobrien{
172090075Sobrien	uint32_t hindex;
172190075Sobrien	struct pmc_owner *po;
172290075Sobrien	struct pmc_ownerhash *poh;
172390075Sobrien
172490075Sobrien	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
172590075Sobrien	poh = &pmc_ownerhash[hindex];
172690075Sobrien
172790075Sobrien	po = NULL;
172890075Sobrien	LIST_FOREACH(po, poh, po_next)
172990075Sobrien	    if (po->po_owner == p)
173090075Sobrien		    break;
173190075Sobrien
173290075Sobrien	PMCDBG(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
173390075Sobrien	    "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
173490075Sobrien
1735	return po;
1736}
1737
1738/*
1739 * pmc_allocate_pmc_descriptor
1740 *
1741 * Allocate a pmc descriptor and initialize its
1742 * fields.
1743 */
1744
1745static struct pmc *
1746pmc_allocate_pmc_descriptor(void)
1747{
1748	struct pmc *pmc;
1749
1750	MALLOC(pmc, struct pmc *, sizeof(struct pmc), M_PMC, M_ZERO|M_WAITOK);
1751
1752	if (pmc != NULL) {
1753		pmc->pm_owner = NULL;
1754		LIST_INIT(&pmc->pm_targets);
1755	}
1756
1757	PMCDBG(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
1758
1759	return pmc;
1760}
1761
1762/*
1763 * Destroy a pmc descriptor.
1764 */
1765
1766static void
1767pmc_destroy_pmc_descriptor(struct pmc *pm)
1768{
1769	(void) pm;
1770
1771#ifdef	DEBUG
1772	KASSERT(pm->pm_state == PMC_STATE_DELETED ||
1773	    pm->pm_state == PMC_STATE_FREE,
1774	    ("[pmc,%d] destroying non-deleted PMC", __LINE__));
1775	KASSERT(LIST_EMPTY(&pm->pm_targets),
1776	    ("[pmc,%d] destroying pmc with targets", __LINE__));
1777	KASSERT(pm->pm_owner == NULL,
1778	    ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
1779	KASSERT(pm->pm_runcount == 0,
1780	    ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
1781		pm->pm_runcount));
1782#endif
1783}
1784
1785static void
1786pmc_wait_for_pmc_idle(struct pmc *pm)
1787{
1788#ifdef	DEBUG
1789	volatile int maxloop;
1790
1791	maxloop = 100 * mp_ncpus;
1792#endif
1793
1794	/*
1795	 * Loop (with a forced context switch) till the PMC's runcount
1796	 * comes down to zero.
1797	 */
1798	while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
1799#ifdef	DEBUG
1800		maxloop--;
1801		KASSERT(maxloop > 0,
1802		    ("[pmc,%d] (ri%d, rc%d) waiting too long for "
1803			"pmc to be free", __LINE__,
1804			PMC_TO_ROWINDEX(pm), pm->pm_runcount));
1805#endif
1806		pmc_force_context_switch();
1807	}
1808}
1809
1810/*
1811 * This function does the following things:
1812 *
1813 *  - detaches the PMC from hardware
1814 *  - unlinks all target threads that were attached to it
1815 *  - removes the PMC from its owner's list
1816 *  - destroy's the PMC private mutex
1817 *
1818 * Once this function completes, the given pmc pointer can be safely
1819 * FREE'd by the caller.
1820 */
1821
1822static void
1823pmc_release_pmc_descriptor(struct pmc *pm)
1824{
1825	u_int ri, cpu;
1826	enum pmc_mode mode;
1827	struct pmc_hw *phw;
1828	struct pmc_owner *po;
1829	struct pmc_process *pp;
1830	struct pmc_target *ptgt, *tmp;
1831	struct pmc_binding pb;
1832
1833	sx_assert(&pmc_sx, SX_XLOCKED);
1834
1835	KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
1836
1837	ri   = PMC_TO_ROWINDEX(pm);
1838	mode = PMC_TO_MODE(pm);
1839
1840	PMCDBG(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
1841	    mode);
1842
1843	/*
1844	 * First, we take the PMC off hardware.
1845	 */
1846	cpu = 0;
1847	if (PMC_IS_SYSTEM_MODE(mode)) {
1848
1849		/*
1850		 * A system mode PMC runs on a specific CPU.  Switch
1851		 * to this CPU and turn hardware off.
1852		 */
1853		pmc_save_cpu_binding(&pb);
1854
1855		cpu = PMC_TO_CPU(pm);
1856
1857		pmc_select_cpu(cpu);
1858
1859		/* switch off non-stalled CPUs */
1860		if (pm->pm_state == PMC_STATE_RUNNING &&
1861		    pm->pm_stalled == 0) {
1862
1863			phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
1864
1865			KASSERT(phw->phw_pmc == pm,
1866			    ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
1867				__LINE__, ri, phw->phw_pmc, pm));
1868			PMCDBG(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
1869
1870			critical_enter();
1871			md->pmd_stop_pmc(cpu, ri);
1872			critical_exit();
1873		}
1874
1875		PMCDBG(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
1876
1877		critical_enter();
1878		md->pmd_config_pmc(cpu, ri, NULL);
1879		critical_exit();
1880
1881		/* adjust the global and process count of SS mode PMCs */
1882		if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
1883			po = pm->pm_owner;
1884			po->po_sscount--;
1885			if (po->po_sscount == 0) {
1886				atomic_subtract_rel_int(&pmc_ss_count, 1);
1887				LIST_REMOVE(po, po_ssnext);
1888			}
1889		}
1890
1891		pm->pm_state = PMC_STATE_DELETED;
1892
1893		pmc_restore_cpu_binding(&pb);
1894
1895		/*
1896		 * We could have references to this PMC structure in
1897		 * the per-cpu sample queues.  Wait for the queue to
1898		 * drain.
1899		 */
1900		pmc_wait_for_pmc_idle(pm);
1901
1902	} else if (PMC_IS_VIRTUAL_MODE(mode)) {
1903
1904		/*
1905		 * A virtual PMC could be running on multiple CPUs at
1906		 * a given instant.
1907		 *
1908		 * By marking its state as DELETED, we ensure that
1909		 * this PMC is never further scheduled on hardware.
1910		 *
1911		 * Then we wait till all CPUs are done with this PMC.
1912		 */
1913		pm->pm_state = PMC_STATE_DELETED;
1914
1915
1916		/* Wait for the PMCs runcount to come to zero. */
1917		pmc_wait_for_pmc_idle(pm);
1918
1919		/*
1920		 * At this point the PMC is off all CPUs and cannot be
1921		 * freshly scheduled onto a CPU.  It is now safe to
1922		 * unlink all targets from this PMC.  If a
1923		 * process-record's refcount falls to zero, we remove
1924		 * it from the hash table.  The module-wide SX lock
1925		 * protects us from races.
1926		 */
1927		LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
1928			pp = ptgt->pt_process;
1929			pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
1930
1931			PMCDBG(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
1932
1933			/*
1934			 * If the target process record shows that no
1935			 * PMCs are attached to it, reclaim its space.
1936			 */
1937
1938			if (pp->pp_refcnt == 0) {
1939				pmc_remove_process_descriptor(pp);
1940				FREE(pp, M_PMC);
1941			}
1942		}
1943
1944		cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
1945
1946	}
1947
1948	/*
1949	 * Release any MD resources
1950	 */
1951
1952	(void) md->pmd_release_pmc(cpu, ri, pm);
1953
1954	/*
1955	 * Update row disposition
1956	 */
1957
1958	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
1959		PMC_UNMARK_ROW_STANDALONE(ri);
1960	else
1961		PMC_UNMARK_ROW_THREAD(ri);
1962
1963	/* unlink from the owner's list */
1964	if (pm->pm_owner) {
1965		LIST_REMOVE(pm, pm_next);
1966		pm->pm_owner = NULL;
1967	}
1968
1969	pmc_destroy_pmc_descriptor(pm);
1970}
1971
1972/*
1973 * Register an owner and a pmc.
1974 */
1975
1976static int
1977pmc_register_owner(struct proc *p, struct pmc *pmc)
1978{
1979	struct pmc_owner *po;
1980
1981	sx_assert(&pmc_sx, SX_XLOCKED);
1982
1983	if ((po = pmc_find_owner_descriptor(p)) == NULL)
1984		if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
1985			return ENOMEM;
1986
1987	KASSERT(pmc->pm_owner == NULL,
1988	    ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
1989	pmc->pm_owner  = po;
1990
1991	LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
1992
1993	PROC_LOCK(p);
1994	p->p_flag |= P_HWPMC;
1995	PROC_UNLOCK(p);
1996
1997	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1998		pmclog_process_pmcallocate(pmc);
1999
2000	PMCDBG(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2001	    po, pmc);
2002
2003	return 0;
2004}
2005
2006/*
2007 * Return the current row disposition:
2008 * == 0 => FREE
2009 *  > 0 => PROCESS MODE
2010 *  < 0 => SYSTEM MODE
2011 */
2012
2013int
2014pmc_getrowdisp(int ri)
2015{
2016	return pmc_pmcdisp[ri];
2017}
2018
2019/*
2020 * Check if a PMC at row index 'ri' can be allocated to the current
2021 * process.
2022 *
2023 * Allocation can fail if:
2024 *   - the current process is already being profiled by a PMC at index 'ri',
2025 *     attached to it via OP_PMCATTACH.
2026 *   - the current process has already allocated a PMC at index 'ri'
2027 *     via OP_ALLOCATE.
2028 */
2029
2030static int
2031pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2032{
2033	enum pmc_mode mode;
2034	struct pmc *pm;
2035	struct pmc_owner *po;
2036	struct pmc_process *pp;
2037
2038	PMCDBG(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2039	    "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2040
2041	/*
2042	 * We shouldn't have already allocated a process-mode PMC at
2043	 * row index 'ri'.
2044	 *
2045	 * We shouldn't have allocated a system-wide PMC on the same
2046	 * CPU and same RI.
2047	 */
2048	if ((po = pmc_find_owner_descriptor(p)) != NULL)
2049		LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2050		    if (PMC_TO_ROWINDEX(pm) == ri) {
2051			    mode = PMC_TO_MODE(pm);
2052			    if (PMC_IS_VIRTUAL_MODE(mode))
2053				    return EEXIST;
2054			    if (PMC_IS_SYSTEM_MODE(mode) &&
2055				(int) PMC_TO_CPU(pm) == cpu)
2056				    return EEXIST;
2057		    }
2058	        }
2059
2060	/*
2061	 * We also shouldn't be the target of any PMC at this index
2062	 * since otherwise a PMC_ATTACH to ourselves will fail.
2063	 */
2064	if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2065		if (pp->pp_pmcs[ri].pp_pmc)
2066			return EEXIST;
2067
2068	PMCDBG(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2069	    p, p->p_pid, p->p_comm, ri);
2070
2071	return 0;
2072}
2073
2074/*
2075 * Check if a given PMC at row index 'ri' can be currently used in
2076 * mode 'mode'.
2077 */
2078
2079static int
2080pmc_can_allocate_row(int ri, enum pmc_mode mode)
2081{
2082	enum pmc_disp	disp;
2083
2084	sx_assert(&pmc_sx, SX_XLOCKED);
2085
2086	PMCDBG(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2087
2088	if (PMC_IS_SYSTEM_MODE(mode))
2089		disp = PMC_DISP_STANDALONE;
2090	else
2091		disp = PMC_DISP_THREAD;
2092
2093	/*
2094	 * check disposition for PMC row 'ri':
2095	 *
2096	 * Expected disposition		Row-disposition		Result
2097	 *
2098	 * STANDALONE			STANDALONE or FREE	proceed
2099	 * STANDALONE			THREAD			fail
2100	 * THREAD			THREAD or FREE		proceed
2101	 * THREAD			STANDALONE		fail
2102	 */
2103
2104	if (!PMC_ROW_DISP_IS_FREE(ri) &&
2105	    !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2106	    !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2107		return EBUSY;
2108
2109	/*
2110	 * All OK
2111	 */
2112
2113	PMCDBG(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2114
2115	return 0;
2116
2117}
2118
2119/*
2120 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2121 */
2122
2123static struct pmc *
2124pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2125{
2126	struct pmc *pm;
2127
2128	KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2129	    ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2130		PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2131
2132	LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2133	    if (pm->pm_id == pmcid)
2134		    return pm;
2135
2136	return NULL;
2137}
2138
2139static int
2140pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2141{
2142
2143	struct pmc *pm;
2144	struct pmc_owner *po;
2145
2146	PMCDBG(PMC,FND,1, "find-pmc id=%d", pmcid);
2147
2148	if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2149		return ESRCH;
2150
2151	if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2152		return EINVAL;
2153
2154	PMCDBG(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2155
2156	*pmc = pm;
2157	return 0;
2158}
2159
2160/*
2161 * Start a PMC.
2162 */
2163
2164static int
2165pmc_start(struct pmc *pm)
2166{
2167	int error, cpu, ri;
2168	enum pmc_mode mode;
2169	struct pmc_owner *po;
2170	struct pmc_binding pb;
2171
2172	KASSERT(pm != NULL,
2173	    ("[pmc,%d] null pm", __LINE__));
2174
2175	mode = PMC_TO_MODE(pm);
2176	ri   = PMC_TO_ROWINDEX(pm);
2177	error = 0;
2178
2179	PMCDBG(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2180
2181	po = pm->pm_owner;
2182
2183	if (PMC_IS_VIRTUAL_MODE(mode)) {
2184
2185		/*
2186		 * If a PMCATTACH has never been done on this PMC,
2187		 * attach it to its owner process.
2188		 */
2189
2190		if (LIST_EMPTY(&pm->pm_targets))
2191			error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2192			    pmc_attach_process(po->po_owner, pm);
2193
2194		/*
2195		 * Disallow PMCSTART if a logfile is required but has not
2196		 * been configured yet.
2197		 */
2198
2199		if (error == 0 && (pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2200		    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2201			error = EDOOFUS;
2202
2203		/*
2204		 * If the PMC is attached to its owner, then force a context
2205		 * switch to ensure that the MD state gets set correctly.
2206		 */
2207
2208		if (error == 0) {
2209			pm->pm_state = PMC_STATE_RUNNING;
2210			if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2211				pmc_force_context_switch();
2212		}
2213
2214		return error;
2215	}
2216
2217
2218	/*
2219	 * A system-wide PMC.
2220	 */
2221
2222	if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2223	    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2224		return EDOOFUS;	/* programming error */
2225
2226	/*
2227	 * Add the owner to the global list if this is a system-wide
2228	 * sampling PMC.
2229	 */
2230
2231	if (mode == PMC_MODE_SS) {
2232		if (po->po_sscount == 0) {
2233			LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2234			atomic_add_rel_int(&pmc_ss_count, 1);
2235			PMCDBG(PMC,OPS,1, "po=%p in global list", po);
2236		}
2237		po->po_sscount++;
2238	}
2239
2240	/*
2241	 * Move to the CPU associated with this
2242	 * PMC, and start the hardware.
2243	 */
2244
2245	pmc_save_cpu_binding(&pb);
2246
2247	cpu = PMC_TO_CPU(pm);
2248
2249	if (pmc_cpu_is_disabled(cpu))
2250		return ENXIO;
2251
2252	pmc_select_cpu(cpu);
2253
2254	/*
2255	 * global PMCs are configured at allocation time
2256	 * so write out the initial value and start the PMC.
2257	 */
2258
2259	pm->pm_state = PMC_STATE_RUNNING;
2260
2261	critical_enter();
2262	if ((error = md->pmd_write_pmc(cpu, ri,
2263		 PMC_IS_SAMPLING_MODE(mode) ?
2264		 pm->pm_sc.pm_reloadcount :
2265		 pm->pm_sc.pm_initial)) == 0)
2266		error = md->pmd_start_pmc(cpu, ri);
2267	critical_exit();
2268
2269	pmc_restore_cpu_binding(&pb);
2270
2271	return error;
2272}
2273
2274/*
2275 * Stop a PMC.
2276 */
2277
2278static int
2279pmc_stop(struct pmc *pm)
2280{
2281	int cpu, error, ri;
2282	struct pmc_owner *po;
2283	struct pmc_binding pb;
2284
2285	KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2286
2287	PMCDBG(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2288	    PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2289
2290	pm->pm_state = PMC_STATE_STOPPED;
2291
2292	/*
2293	 * If the PMC is a virtual mode one, changing the state to
2294	 * non-RUNNING is enough to ensure that the PMC never gets
2295	 * scheduled.
2296	 *
2297	 * If this PMC is current running on a CPU, then it will
2298	 * handled correctly at the time its target process is context
2299	 * switched out.
2300	 */
2301
2302	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2303		return 0;
2304
2305	/*
2306	 * A system-mode PMC.  Move to the CPU associated with
2307	 * this PMC, and stop the hardware.  We update the
2308	 * 'initial count' so that a subsequent PMCSTART will
2309	 * resume counting from the current hardware count.
2310	 */
2311
2312	pmc_save_cpu_binding(&pb);
2313
2314	cpu = PMC_TO_CPU(pm);
2315
2316	KASSERT(cpu >= 0 && cpu < mp_ncpus,
2317	    ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2318
2319	if (pmc_cpu_is_disabled(cpu))
2320		return ENXIO;
2321
2322	pmc_select_cpu(cpu);
2323
2324	ri = PMC_TO_ROWINDEX(pm);
2325
2326	critical_enter();
2327	if ((error = md->pmd_stop_pmc(cpu, ri)) == 0)
2328		error = md->pmd_read_pmc(cpu, ri, &pm->pm_sc.pm_initial);
2329	critical_exit();
2330
2331	pmc_restore_cpu_binding(&pb);
2332
2333	po = pm->pm_owner;
2334
2335	/* remove this owner from the global list of SS PMC owners */
2336	if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2337		po->po_sscount--;
2338		if (po->po_sscount == 0) {
2339			atomic_subtract_rel_int(&pmc_ss_count, 1);
2340			LIST_REMOVE(po, po_ssnext);
2341			PMCDBG(PMC,OPS,2,"po=%p removed from global list", po);
2342		}
2343	}
2344
2345	return error;
2346}
2347
2348
2349#ifdef	DEBUG
2350static const char *pmc_op_to_name[] = {
2351#undef	__PMC_OP
2352#define	__PMC_OP(N, D)	#N ,
2353	__PMC_OPS()
2354	NULL
2355};
2356#endif
2357
2358/*
2359 * The syscall interface
2360 */
2361
2362#define	PMC_GET_SX_XLOCK(...) do {		\
2363	sx_xlock(&pmc_sx);			\
2364	if (pmc_hook == NULL) {			\
2365		sx_xunlock(&pmc_sx);		\
2366		return __VA_ARGS__;		\
2367	}					\
2368} while (0)
2369
2370#define	PMC_DOWNGRADE_SX() do {			\
2371	sx_downgrade(&pmc_sx);			\
2372	is_sx_downgraded = 1;			\
2373} while (0)
2374
2375static int
2376pmc_syscall_handler(struct thread *td, void *syscall_args)
2377{
2378	int error, is_sx_downgraded, op;
2379	struct pmc_syscall_args *c;
2380	void *arg;
2381
2382	PMC_GET_SX_XLOCK(ENOSYS);
2383
2384	DROP_GIANT();
2385
2386	is_sx_downgraded = 0;
2387
2388	c = (struct pmc_syscall_args *) syscall_args;
2389
2390	op = c->pmop_code;
2391	arg = c->pmop_data;
2392
2393	PMCDBG(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2394	    pmc_op_to_name[op], arg);
2395
2396	error = 0;
2397	atomic_add_int(&pmc_stats.pm_syscalls, 1);
2398
2399	switch(op)
2400	{
2401
2402
2403	/*
2404	 * Configure a log file.
2405	 *
2406	 * XXX This OP will be reworked.
2407	 */
2408
2409	case PMC_OP_CONFIGURELOG:
2410	{
2411		struct pmc *pm;
2412		struct pmc_owner *po;
2413		struct pmc_op_configurelog cl;
2414		struct proc *p;
2415
2416		sx_assert(&pmc_sx, SX_XLOCKED);
2417
2418		if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2419			break;
2420
2421		/* mark this process as owning a log file */
2422		p = td->td_proc;
2423		if ((po = pmc_find_owner_descriptor(p)) == NULL)
2424			if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2425				error = ENOMEM;
2426				break;
2427			}
2428
2429		/*
2430		 * If a valid fd was passed in, try to configure that,
2431		 * otherwise if 'fd' was less than zero and there was
2432		 * a log file configured, flush its buffers and
2433		 * de-configure it.
2434		 */
2435		if (cl.pm_logfd >= 0)
2436			error = pmclog_configure_log(po, cl.pm_logfd);
2437		else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2438			pmclog_process_closelog(po);
2439			error = pmclog_flush(po);
2440			if (error == 0) {
2441				LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2442				    if (pm->pm_flags & PMC_F_NEEDS_LOGFILE)
2443					    pmc_stop(pm);
2444				error = pmclog_deconfigure_log(po);
2445			}
2446		} else
2447			error = EINVAL;
2448	}
2449	break;
2450
2451
2452	/*
2453	 * Flush a log file.
2454	 */
2455
2456	case PMC_OP_FLUSHLOG:
2457	{
2458		struct pmc_owner *po;
2459
2460		sx_assert(&pmc_sx, SX_XLOCKED);
2461
2462		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2463			error = EINVAL;
2464			break;
2465		}
2466
2467		error = pmclog_flush(po);
2468	}
2469	break;
2470
2471	/*
2472	 * Retrieve hardware configuration.
2473	 */
2474
2475	case PMC_OP_GETCPUINFO:	/* CPU information */
2476	{
2477		struct pmc_op_getcpuinfo gci;
2478
2479		gci.pm_cputype = md->pmd_cputype;
2480		gci.pm_ncpu    = mp_ncpus;
2481		gci.pm_npmc    = md->pmd_npmc;
2482		gci.pm_nclass  = md->pmd_nclass;
2483		bcopy(md->pmd_classes, &gci.pm_classes,
2484		    sizeof(gci.pm_classes));
2485		error = copyout(&gci, arg, sizeof(gci));
2486	}
2487	break;
2488
2489
2490	/*
2491	 * Get module statistics
2492	 */
2493
2494	case PMC_OP_GETDRIVERSTATS:
2495	{
2496		struct pmc_op_getdriverstats gms;
2497
2498		bcopy(&pmc_stats, &gms, sizeof(gms));
2499		error = copyout(&gms, arg, sizeof(gms));
2500	}
2501	break;
2502
2503
2504	/*
2505	 * Retrieve module version number
2506	 */
2507
2508	case PMC_OP_GETMODULEVERSION:
2509	{
2510		uint32_t cv, modv;
2511
2512		/* retrieve the client's idea of the ABI version */
2513		if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
2514			break;
2515		/* don't service clients newer than our driver */
2516		modv = PMC_VERSION;
2517		if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
2518			error = EPROGMISMATCH;
2519			break;
2520		}
2521		error = copyout(&modv, arg, sizeof(int));
2522	}
2523	break;
2524
2525
2526	/*
2527	 * Retrieve the state of all the PMCs on a given
2528	 * CPU.
2529	 */
2530
2531	case PMC_OP_GETPMCINFO:
2532	{
2533		uint32_t cpu, n, npmc;
2534		size_t pmcinfo_size;
2535		struct pmc *pm;
2536		struct pmc_info *p, *pmcinfo;
2537		struct pmc_op_getpmcinfo *gpi;
2538		struct pmc_owner *po;
2539		struct pmc_binding pb;
2540
2541		PMC_DOWNGRADE_SX();
2542
2543		gpi = (struct pmc_op_getpmcinfo *) arg;
2544
2545		if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
2546			break;
2547
2548		if (cpu >= (unsigned int) mp_ncpus) {
2549			error = EINVAL;
2550			break;
2551		}
2552
2553		if (pmc_cpu_is_disabled(cpu)) {
2554			error = ENXIO;
2555			break;
2556		}
2557
2558		/* switch to CPU 'cpu' */
2559		pmc_save_cpu_binding(&pb);
2560		pmc_select_cpu(cpu);
2561
2562		npmc = md->pmd_npmc;
2563
2564		pmcinfo_size = npmc * sizeof(struct pmc_info);
2565		MALLOC(pmcinfo, struct pmc_info *, pmcinfo_size, M_PMC,
2566		    M_WAITOK);
2567
2568		p = pmcinfo;
2569
2570		for (n = 0; n < md->pmd_npmc; n++, p++) {
2571
2572			if ((error = md->pmd_describe(cpu, n, p, &pm)) != 0)
2573				break;
2574
2575			if (PMC_ROW_DISP_IS_STANDALONE(n))
2576				p->pm_rowdisp = PMC_DISP_STANDALONE;
2577			else if (PMC_ROW_DISP_IS_THREAD(n))
2578				p->pm_rowdisp = PMC_DISP_THREAD;
2579			else
2580				p->pm_rowdisp = PMC_DISP_FREE;
2581
2582			p->pm_ownerpid = -1;
2583
2584			if (pm == NULL)	/* no PMC associated */
2585				continue;
2586
2587			po = pm->pm_owner;
2588
2589			KASSERT(po->po_owner != NULL,
2590			    ("[pmc,%d] pmc_owner had a null proc pointer",
2591				__LINE__));
2592
2593			p->pm_ownerpid = po->po_owner->p_pid;
2594			p->pm_mode     = PMC_TO_MODE(pm);
2595			p->pm_event    = pm->pm_event;
2596			p->pm_flags    = pm->pm_flags;
2597
2598			if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2599				p->pm_reloadcount =
2600				    pm->pm_sc.pm_reloadcount;
2601		}
2602
2603		pmc_restore_cpu_binding(&pb);
2604
2605		/* now copy out the PMC info collected */
2606		if (error == 0)
2607			error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
2608
2609		FREE(pmcinfo, M_PMC);
2610	}
2611	break;
2612
2613
2614	/*
2615	 * Set the administrative state of a PMC.  I.e. whether
2616	 * the PMC is to be used or not.
2617	 */
2618
2619	case PMC_OP_PMCADMIN:
2620	{
2621		int cpu, ri;
2622		enum pmc_state request;
2623		struct pmc_cpu *pc;
2624		struct pmc_hw *phw;
2625		struct pmc_op_pmcadmin pma;
2626		struct pmc_binding pb;
2627
2628		sx_assert(&pmc_sx, SX_XLOCKED);
2629
2630		KASSERT(td == curthread,
2631		    ("[pmc,%d] td != curthread", __LINE__));
2632
2633		if (suser(td) || jailed(td->td_ucred)) {
2634			error =  EPERM;
2635			break;
2636		}
2637
2638		if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
2639			break;
2640
2641		cpu = pma.pm_cpu;
2642
2643		if (cpu < 0 || cpu >= mp_ncpus) {
2644			error = EINVAL;
2645			break;
2646		}
2647
2648		if (pmc_cpu_is_disabled(cpu)) {
2649			error = ENXIO;
2650			break;
2651		}
2652
2653		request = pma.pm_state;
2654
2655		if (request != PMC_STATE_DISABLED &&
2656		    request != PMC_STATE_FREE) {
2657			error = EINVAL;
2658			break;
2659		}
2660
2661		ri = pma.pm_pmc; /* pmc id == row index */
2662		if (ri < 0 || ri >= (int) md->pmd_npmc) {
2663			error = EINVAL;
2664			break;
2665		}
2666
2667		/*
2668		 * We can't disable a PMC with a row-index allocated
2669		 * for process virtual PMCs.
2670		 */
2671
2672		if (PMC_ROW_DISP_IS_THREAD(ri) &&
2673		    request == PMC_STATE_DISABLED) {
2674			error = EBUSY;
2675			break;
2676		}
2677
2678		/*
2679		 * otherwise, this PMC on this CPU is either free or
2680		 * in system-wide mode.
2681		 */
2682
2683		pmc_save_cpu_binding(&pb);
2684		pmc_select_cpu(cpu);
2685
2686		pc  = pmc_pcpu[cpu];
2687		phw = pc->pc_hwpmcs[ri];
2688
2689		/*
2690		 * XXX do we need some kind of 'forced' disable?
2691		 */
2692
2693		if (phw->phw_pmc == NULL) {
2694			if (request == PMC_STATE_DISABLED &&
2695			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
2696				phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
2697				PMC_MARK_ROW_STANDALONE(ri);
2698			} else if (request == PMC_STATE_FREE &&
2699			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
2700				phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
2701				PMC_UNMARK_ROW_STANDALONE(ri);
2702			}
2703			/* other cases are a no-op */
2704		} else
2705			error = EBUSY;
2706
2707		pmc_restore_cpu_binding(&pb);
2708	}
2709	break;
2710
2711
2712	/*
2713	 * Allocate a PMC.
2714	 */
2715
2716	case PMC_OP_PMCALLOCATE:
2717	{
2718		uint32_t caps;
2719		u_int cpu;
2720		int n;
2721		enum pmc_mode mode;
2722		struct pmc *pmc;
2723		struct pmc_hw *phw;
2724		struct pmc_op_pmcallocate pa;
2725		struct pmc_binding pb;
2726
2727		if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
2728			break;
2729
2730		caps = pa.pm_caps;
2731		mode = pa.pm_mode;
2732		cpu  = pa.pm_cpu;
2733
2734		if ((mode != PMC_MODE_SS  &&  mode != PMC_MODE_SC  &&
2735		     mode != PMC_MODE_TS  &&  mode != PMC_MODE_TC) ||
2736		    (cpu != (u_int) PMC_CPU_ANY && cpu >= (u_int) mp_ncpus)) {
2737			error = EINVAL;
2738			break;
2739		}
2740
2741		/*
2742		 * Virtual PMCs should only ask for a default CPU.
2743		 * System mode PMCs need to specify a non-default CPU.
2744		 */
2745
2746		if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
2747		    (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
2748			error = EINVAL;
2749			break;
2750		}
2751
2752		/*
2753		 * Check that a disabled CPU is not being asked for.
2754		 */
2755
2756		if (PMC_IS_SYSTEM_MODE(mode) && pmc_cpu_is_disabled(cpu)) {
2757			error = ENXIO;
2758			break;
2759		}
2760
2761		/*
2762		 * Refuse an allocation for a system-wide PMC if this
2763		 * process has been jailed, or if this process lacks
2764		 * super-user credentials and the sysctl tunable
2765		 * 'security.bsd.unprivileged_syspmcs' is zero.
2766		 */
2767
2768		if (PMC_IS_SYSTEM_MODE(mode)) {
2769			if (jailed(curthread->td_ucred))
2770				error = EPERM;
2771			else if (suser(curthread) &&
2772			    (pmc_unprivileged_syspmcs == 0))
2773				error = EPERM;
2774		}
2775
2776		if (error)
2777			break;
2778
2779		/*
2780		 * Look for valid values for 'pm_flags'
2781		 */
2782
2783		if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
2784		    PMC_F_LOG_PROCEXIT)) != 0) {
2785			error = EINVAL;
2786			break;
2787		}
2788
2789		/* process logging options are not allowed for system PMCs */
2790		if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
2791		    (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
2792			error = EINVAL;
2793			break;
2794		}
2795
2796		/*
2797		 * All sampling mode PMCs need to be able to interrupt the
2798		 * CPU.
2799		 */
2800		if (PMC_IS_SAMPLING_MODE(mode))
2801			caps |= PMC_CAP_INTERRUPT;
2802
2803		/* A valid class specifier should have been passed in. */
2804		for (n = 0; n < md->pmd_nclass; n++)
2805			if (md->pmd_classes[n].pm_class == pa.pm_class)
2806				break;
2807		if (n == md->pmd_nclass) {
2808			error = EINVAL;
2809			break;
2810		}
2811
2812		/* The requested PMC capabilities should be feasible. */
2813		if ((md->pmd_classes[n].pm_caps & caps) != caps) {
2814			error = EOPNOTSUPP;
2815			break;
2816		}
2817
2818		PMCDBG(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
2819		    pa.pm_ev, caps, mode, cpu);
2820
2821		pmc = pmc_allocate_pmc_descriptor();
2822		pmc->pm_id    = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
2823		    PMC_ID_INVALID);
2824		pmc->pm_event = pa.pm_ev;
2825		pmc->pm_state = PMC_STATE_FREE;
2826		pmc->pm_caps  = caps;
2827		pmc->pm_flags = pa.pm_flags;
2828
2829		/* switch thread to CPU 'cpu' */
2830		pmc_save_cpu_binding(&pb);
2831
2832#define	PMC_IS_SHAREABLE_PMC(cpu, n)				\
2833	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &		\
2834	 PMC_PHW_FLAG_IS_SHAREABLE)
2835#define	PMC_IS_UNALLOCATED(cpu, n)				\
2836	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
2837
2838		if (PMC_IS_SYSTEM_MODE(mode)) {
2839			pmc_select_cpu(cpu);
2840			for (n = 0; n < (int) md->pmd_npmc; n++)
2841				if (pmc_can_allocate_row(n, mode) == 0 &&
2842				    pmc_can_allocate_rowindex(
2843					    curthread->td_proc, n, cpu) == 0 &&
2844				    (PMC_IS_UNALLOCATED(cpu, n) ||
2845				     PMC_IS_SHAREABLE_PMC(cpu, n)) &&
2846				    md->pmd_allocate_pmc(cpu, n, pmc,
2847					&pa) == 0)
2848					break;
2849		} else {
2850			/* Process virtual mode */
2851			for (n = 0; n < (int) md->pmd_npmc; n++) {
2852				if (pmc_can_allocate_row(n, mode) == 0 &&
2853				    pmc_can_allocate_rowindex(
2854					    curthread->td_proc, n,
2855					    PMC_CPU_ANY) == 0 &&
2856				    md->pmd_allocate_pmc(curthread->td_oncpu,
2857					n, pmc, &pa) == 0)
2858					break;
2859			}
2860		}
2861
2862#undef	PMC_IS_UNALLOCATED
2863#undef	PMC_IS_SHAREABLE_PMC
2864
2865		pmc_restore_cpu_binding(&pb);
2866
2867		if (n == (int) md->pmd_npmc) {
2868			pmc_destroy_pmc_descriptor(pmc);
2869			FREE(pmc, M_PMC);
2870			pmc = NULL;
2871			error = EINVAL;
2872			break;
2873		}
2874
2875		/* Fill in the correct value in the ID field */
2876		pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
2877
2878		PMCDBG(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
2879		    pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
2880
2881		/* Process mode PMCs with logging enabled need log files */
2882		if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
2883			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
2884
2885		/* All system mode sampling PMCs require a log file */
2886		if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
2887			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
2888
2889		/*
2890		 * Configure global pmc's immediately
2891		 */
2892
2893		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
2894
2895			pmc_save_cpu_binding(&pb);
2896			pmc_select_cpu(cpu);
2897
2898			phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
2899
2900			if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
2901			    (error = md->pmd_config_pmc(cpu, n, pmc)) != 0) {
2902				(void) md->pmd_release_pmc(cpu, n, pmc);
2903				pmc_destroy_pmc_descriptor(pmc);
2904				FREE(pmc, M_PMC);
2905				pmc = NULL;
2906				pmc_restore_cpu_binding(&pb);
2907				error = EPERM;
2908				break;
2909			}
2910
2911			pmc_restore_cpu_binding(&pb);
2912		}
2913
2914		pmc->pm_state    = PMC_STATE_ALLOCATED;
2915
2916		/*
2917		 * mark row disposition
2918		 */
2919
2920		if (PMC_IS_SYSTEM_MODE(mode))
2921			PMC_MARK_ROW_STANDALONE(n);
2922		else
2923			PMC_MARK_ROW_THREAD(n);
2924
2925		/*
2926		 * Register this PMC with the current thread as its owner.
2927		 */
2928
2929		if ((error =
2930		    pmc_register_owner(curthread->td_proc, pmc)) != 0) {
2931			pmc_release_pmc_descriptor(pmc);
2932			FREE(pmc, M_PMC);
2933			pmc = NULL;
2934			break;
2935		}
2936
2937		/*
2938		 * Return the allocated index.
2939		 */
2940
2941		pa.pm_pmcid = pmc->pm_id;
2942
2943		error = copyout(&pa, arg, sizeof(pa));
2944	}
2945	break;
2946
2947
2948	/*
2949	 * Attach a PMC to a process.
2950	 */
2951
2952	case PMC_OP_PMCATTACH:
2953	{
2954		struct pmc *pm;
2955		struct proc *p;
2956		struct pmc_op_pmcattach a;
2957
2958		sx_assert(&pmc_sx, SX_XLOCKED);
2959
2960		if ((error = copyin(arg, &a, sizeof(a))) != 0)
2961			break;
2962
2963		if (a.pm_pid < 0) {
2964			error = EINVAL;
2965			break;
2966		} else if (a.pm_pid == 0)
2967			a.pm_pid = td->td_proc->p_pid;
2968
2969		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
2970			break;
2971
2972		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
2973			error = EINVAL;
2974			break;
2975		}
2976
2977		/* PMCs may be (re)attached only when allocated or stopped */
2978		if (pm->pm_state == PMC_STATE_RUNNING) {
2979			error = EBUSY;
2980			break;
2981		} else if (pm->pm_state != PMC_STATE_ALLOCATED &&
2982		    pm->pm_state != PMC_STATE_STOPPED) {
2983			error = EINVAL;
2984			break;
2985		}
2986
2987		/* lookup pid */
2988		if ((p = pfind(a.pm_pid)) == NULL) {
2989			error = ESRCH;
2990			break;
2991		}
2992
2993		/*
2994		 * Ignore processes that are working on exiting.
2995		 */
2996		if (p->p_flag & P_WEXIT) {
2997			error = ESRCH;
2998			PROC_UNLOCK(p);	/* pfind() returns a locked process */
2999			break;
3000		}
3001
3002		/*
3003		 * we are allowed to attach a PMC to a process if
3004		 * we can debug it.
3005		 */
3006		error = p_candebug(curthread, p);
3007
3008		PROC_UNLOCK(p);
3009
3010		if (error == 0)
3011			error = pmc_attach_process(p, pm);
3012	}
3013	break;
3014
3015
3016	/*
3017	 * Detach an attached PMC from a process.
3018	 */
3019
3020	case PMC_OP_PMCDETACH:
3021	{
3022		struct pmc *pm;
3023		struct proc *p;
3024		struct pmc_op_pmcattach a;
3025
3026		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3027			break;
3028
3029		if (a.pm_pid < 0) {
3030			error = EINVAL;
3031			break;
3032		} else if (a.pm_pid == 0)
3033			a.pm_pid = td->td_proc->p_pid;
3034
3035		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3036			break;
3037
3038		if ((p = pfind(a.pm_pid)) == NULL) {
3039			error = ESRCH;
3040			break;
3041		}
3042
3043		/*
3044		 * Treat processes that are in the process of exiting
3045		 * as if they were not present.
3046		 */
3047
3048		if (p->p_flag & P_WEXIT)
3049			error = ESRCH;
3050
3051		PROC_UNLOCK(p);	/* pfind() returns a locked process */
3052
3053		if (error == 0)
3054			error = pmc_detach_process(p, pm);
3055	}
3056	break;
3057
3058
3059	/*
3060	 * Retrieve the MSR number associated with the counter
3061	 * 'pmc_id'.  This allows processes to directly use RDPMC
3062	 * instructions to read their PMCs, without the overhead of a
3063	 * system call.
3064	 */
3065
3066	case PMC_OP_PMCGETMSR:
3067	{
3068		int ri;
3069		struct pmc	*pm;
3070		struct pmc_target *pt;
3071		struct pmc_op_getmsr gm;
3072
3073		PMC_DOWNGRADE_SX();
3074
3075		/* CPU has no 'GETMSR' support */
3076		if (md->pmd_get_msr == NULL) {
3077			error = ENOSYS;
3078			break;
3079		}
3080
3081		if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3082			break;
3083
3084		if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3085			break;
3086
3087		/*
3088		 * The allocated PMC has to be a process virtual PMC,
3089		 * i.e., of type MODE_T[CS].  Global PMCs can only be
3090		 * read using the PMCREAD operation since they may be
3091		 * allocated on a different CPU than the one we could
3092		 * be running on at the time of the RDPMC instruction.
3093		 *
3094		 * The GETMSR operation is not allowed for PMCs that
3095		 * are inherited across processes.
3096		 */
3097
3098		if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3099		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
3100			error = EINVAL;
3101			break;
3102		}
3103
3104		/*
3105		 * It only makes sense to use a RDPMC (or its
3106		 * equivalent instruction on non-x86 architectures) on
3107		 * a process that has allocated and attached a PMC to
3108		 * itself.  Conversely the PMC is only allowed to have
3109		 * one process attached to it -- its owner.
3110		 */
3111
3112		if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3113		    LIST_NEXT(pt, pt_next) != NULL ||
3114		    pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3115			error = EINVAL;
3116			break;
3117		}
3118
3119		ri = PMC_TO_ROWINDEX(pm);
3120
3121		if ((error = (*md->pmd_get_msr)(ri, &gm.pm_msr)) < 0)
3122			break;
3123
3124		if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3125			break;
3126
3127		/*
3128		 * Mark our process as using MSRs.  Update machine
3129		 * state using a forced context switch.
3130		 */
3131
3132		pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3133		pmc_force_context_switch();
3134
3135	}
3136	break;
3137
3138	/*
3139	 * Release an allocated PMC
3140	 */
3141
3142	case PMC_OP_PMCRELEASE:
3143	{
3144		pmc_id_t pmcid;
3145		struct pmc *pm;
3146		struct pmc_owner *po;
3147		struct pmc_op_simple sp;
3148
3149		/*
3150		 * Find PMC pointer for the named PMC.
3151		 *
3152		 * Use pmc_release_pmc_descriptor() to switch off the
3153		 * PMC, remove all its target threads, and remove the
3154		 * PMC from its owner's list.
3155		 *
3156		 * Remove the owner record if this is the last PMC
3157		 * owned.
3158		 *
3159		 * Free up space.
3160		 */
3161
3162		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3163			break;
3164
3165		pmcid = sp.pm_pmcid;
3166
3167		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3168			break;
3169
3170		po = pm->pm_owner;
3171		pmc_release_pmc_descriptor(pm);
3172		pmc_maybe_remove_owner(po);
3173
3174		FREE(pm, M_PMC);
3175	}
3176	break;
3177
3178
3179	/*
3180	 * Read and/or write a PMC.
3181	 */
3182
3183	case PMC_OP_PMCRW:
3184	{
3185		uint32_t cpu, ri;
3186		struct pmc *pm;
3187		struct pmc_op_pmcrw *pprw;
3188		struct pmc_op_pmcrw prw;
3189		struct pmc_binding pb;
3190		pmc_value_t oldvalue;
3191
3192		PMC_DOWNGRADE_SX();
3193
3194		if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3195			break;
3196
3197		ri = 0;
3198		PMCDBG(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3199		    prw.pm_flags);
3200
3201		/* must have at least one flag set */
3202		if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3203			error = EINVAL;
3204			break;
3205		}
3206
3207		/* locate pmc descriptor */
3208		if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3209			break;
3210
3211		/* Can't read a PMC that hasn't been started. */
3212		if (pm->pm_state != PMC_STATE_ALLOCATED &&
3213		    pm->pm_state != PMC_STATE_STOPPED &&
3214		    pm->pm_state != PMC_STATE_RUNNING) {
3215			error = EINVAL;
3216			break;
3217		}
3218
3219		/* writing a new value is allowed only for 'STOPPED' pmcs */
3220		if (pm->pm_state == PMC_STATE_RUNNING &&
3221		    (prw.pm_flags & PMC_F_NEWVALUE)) {
3222			error = EBUSY;
3223			break;
3224		}
3225
3226		if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3227
3228			/*
3229			 * If this PMC is attached to its owner (i.e.,
3230			 * the process requesting this operation) and
3231			 * is running, then attempt to get an
3232			 * upto-date reading from hardware for a READ.
3233			 * Writes are only allowed when the PMC is
3234			 * stopped, so only update the saved value
3235			 * field.
3236			 *
3237			 * If the PMC is not running, or is not
3238			 * attached to its owner, read/write to the
3239			 * savedvalue field.
3240			 */
3241
3242			ri = PMC_TO_ROWINDEX(pm);
3243
3244			mtx_pool_lock_spin(pmc_mtxpool, pm);
3245			cpu = curthread->td_oncpu;
3246
3247			if (prw.pm_flags & PMC_F_OLDVALUE) {
3248				if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3249				    (pm->pm_state == PMC_STATE_RUNNING))
3250					error = (*md->pmd_read_pmc)(cpu, ri,
3251					    &oldvalue);
3252				else
3253					oldvalue = pm->pm_gv.pm_savedvalue;
3254			}
3255			if (prw.pm_flags & PMC_F_NEWVALUE)
3256				pm->pm_gv.pm_savedvalue = prw.pm_value;
3257
3258			mtx_pool_unlock_spin(pmc_mtxpool, pm);
3259
3260		} else { /* System mode PMCs */
3261			cpu = PMC_TO_CPU(pm);
3262			ri  = PMC_TO_ROWINDEX(pm);
3263
3264			if (pmc_cpu_is_disabled(cpu)) {
3265				error = ENXIO;
3266				break;
3267			}
3268
3269			/* move this thread to CPU 'cpu' */
3270			pmc_save_cpu_binding(&pb);
3271			pmc_select_cpu(cpu);
3272
3273			critical_enter();
3274			/* save old value */
3275			if (prw.pm_flags & PMC_F_OLDVALUE)
3276				if ((error = (*md->pmd_read_pmc)(cpu, ri,
3277					 &oldvalue)))
3278					goto error;
3279			/* write out new value */
3280			if (prw.pm_flags & PMC_F_NEWVALUE)
3281				error = (*md->pmd_write_pmc)(cpu, ri,
3282				    prw.pm_value);
3283		error:
3284			critical_exit();
3285			pmc_restore_cpu_binding(&pb);
3286			if (error)
3287				break;
3288		}
3289
3290		pprw = (struct pmc_op_pmcrw *) arg;
3291
3292#ifdef	DEBUG
3293		if (prw.pm_flags & PMC_F_NEWVALUE)
3294			PMCDBG(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3295			    ri, prw.pm_value, oldvalue);
3296		else if (prw.pm_flags & PMC_F_OLDVALUE)
3297			PMCDBG(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3298#endif
3299
3300		/* return old value if requested */
3301		if (prw.pm_flags & PMC_F_OLDVALUE)
3302			if ((error = copyout(&oldvalue, &pprw->pm_value,
3303				 sizeof(prw.pm_value))))
3304				break;
3305
3306	}
3307	break;
3308
3309
3310	/*
3311	 * Set the sampling rate for a sampling mode PMC and the
3312	 * initial count for a counting mode PMC.
3313	 */
3314
3315	case PMC_OP_PMCSETCOUNT:
3316	{
3317		struct pmc *pm;
3318		struct pmc_op_pmcsetcount sc;
3319
3320		PMC_DOWNGRADE_SX();
3321
3322		if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3323			break;
3324
3325		if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3326			break;
3327
3328		if (pm->pm_state == PMC_STATE_RUNNING) {
3329			error = EBUSY;
3330			break;
3331		}
3332
3333		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3334			pm->pm_sc.pm_reloadcount = sc.pm_count;
3335		else
3336			pm->pm_sc.pm_initial = sc.pm_count;
3337	}
3338	break;
3339
3340
3341	/*
3342	 * Start a PMC.
3343	 */
3344
3345	case PMC_OP_PMCSTART:
3346	{
3347		pmc_id_t pmcid;
3348		struct pmc *pm;
3349		struct pmc_op_simple sp;
3350
3351		sx_assert(&pmc_sx, SX_XLOCKED);
3352
3353		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3354			break;
3355
3356		pmcid = sp.pm_pmcid;
3357
3358		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3359			break;
3360
3361		KASSERT(pmcid == pm->pm_id,
3362		    ("[pmc,%d] pmcid %x != id %x", __LINE__,
3363			pm->pm_id, pmcid));
3364
3365		if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3366			break;
3367		else if (pm->pm_state != PMC_STATE_STOPPED &&
3368		    pm->pm_state != PMC_STATE_ALLOCATED) {
3369			error = EINVAL;
3370			break;
3371		}
3372
3373		error = pmc_start(pm);
3374	}
3375	break;
3376
3377
3378	/*
3379	 * Stop a PMC.
3380	 */
3381
3382	case PMC_OP_PMCSTOP:
3383	{
3384		pmc_id_t pmcid;
3385		struct pmc *pm;
3386		struct pmc_op_simple sp;
3387
3388		PMC_DOWNGRADE_SX();
3389
3390		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3391			break;
3392
3393		pmcid = sp.pm_pmcid;
3394
3395		/*
3396		 * Mark the PMC as inactive and invoke the MD stop
3397		 * routines if needed.
3398		 */
3399
3400		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3401			break;
3402
3403		KASSERT(pmcid == pm->pm_id,
3404		    ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3405			pm->pm_id, pmcid));
3406
3407		if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3408			break;
3409		else if (pm->pm_state != PMC_STATE_RUNNING) {
3410			error = EINVAL;
3411			break;
3412		}
3413
3414		error = pmc_stop(pm);
3415	}
3416	break;
3417
3418
3419	/*
3420	 * Write a user supplied value to the log file.
3421	 */
3422
3423	case PMC_OP_WRITELOG:
3424	{
3425		struct pmc_op_writelog wl;
3426		struct pmc_owner *po;
3427
3428		PMC_DOWNGRADE_SX();
3429
3430		if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
3431			break;
3432
3433		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3434			error = EINVAL;
3435			break;
3436		}
3437
3438		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
3439			error = EINVAL;
3440			break;
3441		}
3442
3443		error = pmclog_process_userlog(po, &wl);
3444	}
3445	break;
3446
3447
3448	default:
3449		error = EINVAL;
3450		break;
3451	}
3452
3453	if (is_sx_downgraded)
3454		sx_sunlock(&pmc_sx);
3455	else
3456		sx_xunlock(&pmc_sx);
3457
3458	if (error)
3459		atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
3460
3461	PICKUP_GIANT();
3462
3463	return error;
3464}
3465
3466/*
3467 * Helper functions
3468 */
3469
3470
3471/*
3472 * Interrupt processing.
3473 *
3474 * Find a free slot in the per-cpu array of PC samples and write the
3475 * current (PMC,PID,PC) triple to it.  If an event was successfully
3476 * added, a bit is set in mask 'pmc_cpumask' denoting that the
3477 * DO_SAMPLES hook needs to be invoked from the clock handler.
3478 *
3479 * This function is meant to be called from an NMI handler.  It cannot
3480 * use any of the locking primitives supplied by the OS.
3481 */
3482
3483int
3484pmc_process_interrupt(int cpu, struct pmc *pm, uintfptr_t pc, int usermode)
3485{
3486	int error, ri;
3487	struct thread *td;
3488	struct pmc_sample *ps;
3489	struct pmc_samplebuffer *psb;
3490
3491	error = 0;
3492	ri = PMC_TO_ROWINDEX(pm);
3493
3494	psb = pmc_pcpu[cpu]->pc_sb;
3495
3496	ps = psb->ps_write;
3497	if (ps->ps_pc) {	/* in use, reader hasn't caught up */
3498		pm->pm_stalled = 1;
3499		atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
3500		PMCDBG(SAM,INT,1,"(spc) cpu=%d pm=%p pc=%jx um=%d wr=%d rd=%d",
3501		    cpu, pm, (uint64_t) pc, usermode,
3502		    (int) (psb->ps_write - psb->ps_samples),
3503		    (int) (psb->ps_read - psb->ps_samples));
3504		error = ENOMEM;
3505		goto done;
3506	}
3507
3508	/* fill in entry */
3509	PMCDBG(SAM,INT,1,"cpu=%d pm=%p pc=%jx um=%d wr=%d rd=%d", cpu, pm,
3510	    (uint64_t) pc, usermode,
3511	    (int) (psb->ps_write - psb->ps_samples),
3512	    (int) (psb->ps_read - psb->ps_samples));
3513
3514	atomic_add_rel_32(&pm->pm_runcount, 1);		/* hold onto PMC */
3515	ps->ps_pmc = pm;
3516	if ((td = curthread) && td->td_proc)
3517		ps->ps_pid = td->td_proc->p_pid;
3518	else
3519		ps->ps_pid = -1;
3520	ps->ps_usermode = usermode;
3521	ps->ps_pc = pc;		/* mark entry as in use */
3522
3523	/* increment write pointer, modulo ring buffer size */
3524	ps++;
3525	if (ps == psb->ps_fence)
3526		psb->ps_write = psb->ps_samples;
3527	else
3528		psb->ps_write = ps;
3529
3530 done:
3531	/* mark CPU as needing processing */
3532	atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3533
3534	return error;
3535}
3536
3537
3538/*
3539 * Process saved PC samples.
3540 */
3541
3542static void
3543pmc_process_samples(int cpu)
3544{
3545	int n, ri;
3546	struct pmc *pm;
3547	struct thread *td;
3548	struct pmc_owner *po;
3549	struct pmc_sample *ps;
3550	struct pmc_samplebuffer *psb;
3551
3552	KASSERT(PCPU_GET(cpuid) == cpu,
3553	    ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
3554		PCPU_GET(cpuid), cpu));
3555
3556	psb = pmc_pcpu[cpu]->pc_sb;
3557
3558	for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
3559
3560		ps = psb->ps_read;
3561		if (ps->ps_pc == (uintfptr_t) 0)	/* no data */
3562			break;
3563
3564		pm = ps->ps_pmc;
3565		po = pm->pm_owner;
3566
3567		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
3568		    ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
3569			pm, PMC_TO_MODE(pm)));
3570
3571		/* Ignore PMCs that have been switched off */
3572		if (pm->pm_state != PMC_STATE_RUNNING)
3573			goto entrydone;
3574
3575		PMCDBG(SAM,OPS,1,"cpu=%d pm=%p pc=%jx um=%d wr=%d rd=%d", cpu,
3576		    pm, (uint64_t) ps->ps_pc, ps->ps_usermode,
3577		    (int) (psb->ps_write - psb->ps_samples),
3578		    (int) (psb->ps_read - psb->ps_samples));
3579
3580		/*
3581		 * If this is a process-mode PMC that is attached to
3582		 * its owner, and if the PC is in user mode, update
3583		 * profiling statistics like timer-based profiling
3584		 * would have done.
3585		 */
3586		if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
3587			if (ps->ps_usermode) {
3588				td = FIRST_THREAD_IN_PROC(po->po_owner);
3589				addupc_intr(td, ps->ps_pc, 1);
3590			}
3591			goto entrydone;
3592		}
3593
3594		/*
3595		 * Otherwise, this is either a sampling mode PMC that
3596		 * is attached to a different process than its owner,
3597		 * or a system-wide sampling PMC.  Dispatch a log
3598		 * entry to the PMC's owner process.
3599		 */
3600
3601		pmclog_process_pcsample(pm, ps);
3602
3603	entrydone:
3604		ps->ps_pc = (uintfptr_t) 0;	/* mark entry as free */
3605		atomic_subtract_rel_32(&pm->pm_runcount, 1);
3606
3607		/* increment read pointer, modulo sample size */
3608		if (++ps == psb->ps_fence)
3609			psb->ps_read = psb->ps_samples;
3610		else
3611			psb->ps_read = ps;
3612	}
3613
3614	atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
3615
3616	/* Do not re-enable stalled PMCs if we failed to process any samples */
3617	if (n == 0)
3618		return;
3619
3620	/*
3621	 * Restart any stalled sampling PMCs on this CPU.
3622	 *
3623	 * If the NMI handler sets the pm_stalled field of a PMC after
3624	 * the check below, we'll end up processing the stalled PMC at
3625	 * the next hardclock tick.
3626	 */
3627	for (n = 0; n < md->pmd_npmc; n++) {
3628		(void) (*md->pmd_get_config)(cpu,n,&pm);
3629		if (pm == NULL ||			 /* !cfg'ed */
3630		    pm->pm_state != PMC_STATE_RUNNING || /* !active */
3631		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
3632		    pm->pm_stalled == 0) /* !stalled */
3633			continue;
3634
3635		pm->pm_stalled = 0;
3636		ri = PMC_TO_ROWINDEX(pm);
3637		(*md->pmd_start_pmc)(cpu, ri);
3638	}
3639}
3640
3641/*
3642 * Event handlers.
3643 */
3644
3645/*
3646 * Handle a process exit.
3647 *
3648 * Remove this process from all hash tables.  If this process
3649 * owned any PMCs, turn off those PMCs and deallocate them,
3650 * removing any associations with target processes.
3651 *
3652 * This function will be called by the last 'thread' of a
3653 * process.
3654 *
3655 * XXX This eventhandler gets called early in the exit process.
3656 * Consider using a 'hook' invocation from thread_exit() or equivalent
3657 * spot.  Another negative is that kse_exit doesn't seem to call
3658 * exit1() [??].
3659 *
3660 */
3661
3662static void
3663pmc_process_exit(void *arg __unused, struct proc *p)
3664{
3665	int is_using_hwpmcs;
3666	int cpu;
3667	unsigned int ri;
3668	struct pmc *pm;
3669	struct pmc_process *pp;
3670	struct pmc_owner *po;
3671	pmc_value_t newvalue, tmp;
3672
3673	PROC_LOCK(p);
3674	is_using_hwpmcs = p->p_flag & P_HWPMC;
3675	PROC_UNLOCK(p);
3676
3677	/*
3678	 * Log a sysexit event to all SS PMC owners.
3679	 */
3680	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
3681	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
3682		    pmclog_process_sysexit(po, p->p_pid);
3683
3684	if (!is_using_hwpmcs)
3685		return;
3686
3687	PMC_GET_SX_XLOCK();
3688	PMCDBG(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
3689	    p->p_comm);
3690
3691	/*
3692	 * Since this code is invoked by the last thread in an exiting
3693	 * process, we would have context switched IN at some prior
3694	 * point.  However, with PREEMPTION, kernel mode context
3695	 * switches may happen any time, so we want to disable a
3696	 * context switch OUT till we get any PMCs targetting this
3697	 * process off the hardware.
3698	 *
3699	 * We also need to atomically remove this process'
3700	 * entry from our target process hash table, using
3701	 * PMC_FLAG_REMOVE.
3702	 */
3703	PMCDBG(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
3704	    p->p_comm);
3705
3706	critical_enter(); /* no preemption */
3707
3708	cpu = curthread->td_oncpu;
3709
3710	if ((pp = pmc_find_process_descriptor(p,
3711		 PMC_FLAG_REMOVE)) != NULL) {
3712
3713		PMCDBG(PRC,EXT,2,
3714		    "process-exit proc=%p pmc-process=%p", p, pp);
3715
3716		/*
3717		 * The exiting process could the target of
3718		 * some PMCs which will be running on
3719		 * currently executing CPU.
3720		 *
3721		 * We need to turn these PMCs off like we
3722		 * would do at context switch OUT time.
3723		 */
3724		for (ri = 0; ri < md->pmd_npmc; ri++) {
3725
3726			/*
3727			 * Pick up the pmc pointer from hardware
3728			 * state similar to the CSW_OUT code.
3729			 */
3730			pm = NULL;
3731			(void) (*md->pmd_get_config)(cpu, ri, &pm);
3732
3733			PMCDBG(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
3734
3735			if (pm == NULL ||
3736			    !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
3737				continue;
3738
3739			PMCDBG(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
3740			    "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
3741			    pm, pm->pm_state);
3742
3743			KASSERT(PMC_TO_ROWINDEX(pm) == ri,
3744			    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
3745				__LINE__, PMC_TO_ROWINDEX(pm), ri));
3746
3747			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
3748			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
3749				__LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
3750
3751			(void) md->pmd_stop_pmc(cpu, ri);
3752
3753			KASSERT(pm->pm_runcount > 0,
3754			    ("[pmc,%d] bad runcount ri %d rc %d",
3755				__LINE__, ri, pm->pm_runcount));
3756
3757			/* Stop hardware only if it is actually running */
3758			if (pm->pm_state == PMC_STATE_RUNNING &&
3759			    pm->pm_stalled == 0) {
3760				md->pmd_read_pmc(cpu, ri, &newvalue);
3761				tmp = newvalue -
3762				    PMC_PCPU_SAVED(cpu,ri);
3763
3764				mtx_pool_lock_spin(pmc_mtxpool, pm);
3765				pm->pm_gv.pm_savedvalue += tmp;
3766				pp->pp_pmcs[ri].pp_pmcval += tmp;
3767				mtx_pool_unlock_spin(pmc_mtxpool, pm);
3768			}
3769
3770			atomic_subtract_rel_32(&pm->pm_runcount,1);
3771
3772			KASSERT((int) pm->pm_runcount >= 0,
3773			    ("[pmc,%d] runcount is %d", __LINE__, ri));
3774
3775			(void) md->pmd_config_pmc(cpu, ri, NULL);
3776		}
3777
3778		/*
3779		 * Inform the MD layer of this pseudo "context switch
3780		 * out"
3781		 */
3782		(void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
3783
3784		critical_exit(); /* ok to be pre-empted now */
3785
3786		/*
3787		 * Unlink this process from the PMCs that are
3788		 * targetting it.  This will send a signal to
3789		 * all PMC owner's whose PMCs are orphaned.
3790		 *
3791		 * Log PMC value at exit time if requested.
3792		 */
3793		for (ri = 0; ri < md->pmd_npmc; ri++)
3794			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
3795				if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
3796				    PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
3797					pmclog_process_procexit(pm, pp);
3798				pmc_unlink_target_process(pm, pp);
3799			}
3800		FREE(pp, M_PMC);
3801
3802	} else
3803		critical_exit(); /* pp == NULL */
3804
3805
3806	/*
3807	 * If the process owned PMCs, free them up and free up
3808	 * memory.
3809	 */
3810	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
3811		pmc_remove_owner(po);
3812		pmc_destroy_owner_descriptor(po);
3813	}
3814
3815	sx_xunlock(&pmc_sx);
3816}
3817
3818/*
3819 * Handle a process fork.
3820 *
3821 * If the parent process 'p1' is under HWPMC monitoring, then copy
3822 * over any attached PMCs that have 'do_descendants' semantics.
3823 */
3824
3825static void
3826pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
3827    int flags)
3828{
3829	int is_using_hwpmcs;
3830	unsigned int ri;
3831	uint32_t do_descendants;
3832	struct pmc *pm;
3833	struct pmc_owner *po;
3834	struct pmc_process *ppnew, *ppold;
3835
3836	(void) flags;		/* unused parameter */
3837
3838	PROC_LOCK(p1);
3839	is_using_hwpmcs = p1->p_flag & P_HWPMC;
3840	PROC_UNLOCK(p1);
3841
3842	/*
3843	 * If there are system-wide sampling PMCs active, we need to
3844	 * log all fork events to their owner's logs.
3845	 */
3846
3847	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
3848	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
3849		    pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
3850
3851	if (!is_using_hwpmcs)
3852		return;
3853
3854	PMC_GET_SX_XLOCK();
3855	PMCDBG(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
3856	    p1->p_pid, p1->p_comm, newproc);
3857
3858	/*
3859	 * If the parent process (curthread->td_proc) is a
3860	 * target of any PMCs, look for PMCs that are to be
3861	 * inherited, and link these into the new process
3862	 * descriptor.
3863	 */
3864	if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
3865		 PMC_FLAG_NONE)) == NULL)
3866		goto done;		/* nothing to do */
3867
3868	do_descendants = 0;
3869	for (ri = 0; ri < md->pmd_npmc; ri++)
3870		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
3871			do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
3872	if (do_descendants == 0) /* nothing to do */
3873		goto done;
3874
3875	/* allocate a descriptor for the new process  */
3876	if ((ppnew = pmc_find_process_descriptor(newproc,
3877		 PMC_FLAG_ALLOCATE)) == NULL)
3878		goto done;
3879
3880	/*
3881	 * Run through all PMCs that were targeting the old process
3882	 * and which specified F_DESCENDANTS and attach them to the
3883	 * new process.
3884	 *
3885	 * Log the fork event to all owners of PMCs attached to this
3886	 * process, if not already logged.
3887	 */
3888	for (ri = 0; ri < md->pmd_npmc; ri++)
3889		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
3890		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
3891			pmc_link_target_process(pm, ppnew);
3892			po = pm->pm_owner;
3893			if (po->po_sscount == 0 &&
3894			    po->po_flags & PMC_PO_OWNS_LOGFILE)
3895				pmclog_process_procfork(po, p1->p_pid,
3896				    newproc->p_pid);
3897		}
3898
3899	/*
3900	 * Now mark the new process as being tracked by this driver.
3901	 */
3902	PROC_LOCK(newproc);
3903	newproc->p_flag |= P_HWPMC;
3904	PROC_UNLOCK(newproc);
3905
3906 done:
3907	sx_xunlock(&pmc_sx);
3908}
3909
3910
3911/*
3912 * initialization
3913 */
3914
3915static const char *pmc_name_of_pmcclass[] = {
3916#undef	__PMC_CLASS
3917#define	__PMC_CLASS(N) #N ,
3918	__PMC_CLASSES()
3919};
3920
3921static int
3922pmc_initialize(void)
3923{
3924	int cpu, error, n;
3925	struct pmc_binding pb;
3926	struct pmc_samplebuffer *sb;
3927
3928	md = NULL;
3929	error = 0;
3930
3931#ifdef	DEBUG
3932	/* parse debug flags first */
3933	if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
3934		pmc_debugstr, sizeof(pmc_debugstr)))
3935		pmc_debugflags_parse(pmc_debugstr,
3936		    pmc_debugstr+strlen(pmc_debugstr));
3937#endif
3938
3939	PMCDBG(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
3940
3941	/* check kernel version */
3942	if (pmc_kernel_version != PMC_VERSION) {
3943		if (pmc_kernel_version == 0)
3944			printf("hwpmc: this kernel has not been compiled with "
3945			    "'options HWPMC_HOOKS'.\n");
3946		else
3947			printf("hwpmc: kernel version (0x%x) does not match "
3948			    "module version (0x%x).\n", pmc_kernel_version,
3949			    PMC_VERSION);
3950		return EPROGMISMATCH;
3951	}
3952
3953	/*
3954	 * check sysctl parameters
3955	 */
3956
3957	if (pmc_hashsize <= 0) {
3958		(void) printf("hwpmc: tunable hashsize=%d must be greater "
3959		    "than zero.\n", pmc_hashsize);
3960		pmc_hashsize = PMC_HASH_SIZE;
3961	}
3962
3963	if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
3964		(void) printf("hwpmc: tunable nsamples=%d out of range.\n",
3965		    pmc_nsamples);
3966		pmc_nsamples = PMC_NSAMPLES;
3967	}
3968
3969	md = pmc_md_initialize();
3970
3971	if (md == NULL || md->pmd_init == NULL)
3972		return ENOSYS;
3973
3974	/* allocate space for the per-cpu array */
3975	MALLOC(pmc_pcpu, struct pmc_cpu **, mp_ncpus * sizeof(struct pmc_cpu *),
3976	    M_PMC, M_WAITOK|M_ZERO);
3977
3978	/* per-cpu 'saved values' for managing process-mode PMCs */
3979	MALLOC(pmc_pcpu_saved, pmc_value_t *,
3980	    sizeof(pmc_value_t) * mp_ncpus * md->pmd_npmc, M_PMC, M_WAITOK);
3981
3982	/* perform cpu dependent initialization */
3983	pmc_save_cpu_binding(&pb);
3984	for (cpu = 0; cpu < mp_ncpus; cpu++) {
3985		if (pmc_cpu_is_disabled(cpu))
3986			continue;
3987		pmc_select_cpu(cpu);
3988		if ((error = md->pmd_init(cpu)) != 0)
3989			break;
3990	}
3991	pmc_restore_cpu_binding(&pb);
3992
3993	if (error != 0)
3994		return error;
3995
3996	/* allocate space for the sample array */
3997	for (cpu = 0; cpu < mp_ncpus; cpu++) {
3998		if (pmc_cpu_is_disabled(cpu))
3999			continue;
4000		MALLOC(sb, struct pmc_samplebuffer *,
4001		    sizeof(struct pmc_samplebuffer) +
4002		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4003		    M_WAITOK|M_ZERO);
4004
4005		sb->ps_read = sb->ps_write = sb->ps_samples;
4006		sb->ps_fence = sb->ps_samples + pmc_nsamples;
4007		KASSERT(pmc_pcpu[cpu] != NULL,
4008		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4009
4010		pmc_pcpu[cpu]->pc_sb = sb;
4011	}
4012
4013	/* allocate space for the row disposition array */
4014	pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4015	    M_PMC, M_WAITOK|M_ZERO);
4016
4017	KASSERT(pmc_pmcdisp != NULL,
4018	    ("[pmc,%d] pmcdisp allocation returned NULL", __LINE__));
4019
4020	/* mark all PMCs as available */
4021	for (n = 0; n < (int) md->pmd_npmc; n++)
4022		PMC_MARK_ROW_FREE(n);
4023
4024	/* allocate thread hash tables */
4025	pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4026	    &pmc_ownerhashmask);
4027
4028	pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4029	    &pmc_processhashmask);
4030	mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc", MTX_SPIN);
4031
4032	LIST_INIT(&pmc_ss_owners);
4033	pmc_ss_count = 0;
4034
4035	/* allocate a pool of spin mutexes */
4036	pmc_mtxpool = mtx_pool_create("pmc", pmc_mtxpool_size, MTX_SPIN);
4037
4038	PMCDBG(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4039	    "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4040	    pmc_processhash, pmc_processhashmask);
4041
4042	/* register process {exit,fork,exec} handlers */
4043	pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4044	    pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4045	pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4046	    pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4047
4048	/* initialize logging */
4049	pmclog_initialize();
4050
4051	/* set hook functions */
4052	pmc_intr = md->pmd_intr;
4053	pmc_hook = pmc_hook_handler;
4054
4055	if (error == 0) {
4056		printf(PMC_MODULE_NAME ":");
4057		for (n = 0; n < (int) md->pmd_nclass; n++) {
4058			printf(" %s/%d/0x%b",
4059			    pmc_name_of_pmcclass[md->pmd_classes[n].pm_class],
4060			    md->pmd_nclasspmcs[n],
4061			    md->pmd_classes[n].pm_caps,
4062			    "\20"
4063			    "\1INT\2USR\3SYS\4EDG\5THR"
4064			    "\6REA\7WRI\10INV\11QUA\12PRC"
4065			    "\13TAG\14CSC");
4066		}
4067		printf("\n");
4068	}
4069
4070	return error;
4071}
4072
4073/* prepare to be unloaded */
4074static void
4075pmc_cleanup(void)
4076{
4077	int cpu;
4078	struct pmc_ownerhash *ph;
4079	struct pmc_owner *po, *tmp;
4080	struct pmc_binding pb;
4081#ifdef	DEBUG
4082	struct pmc_processhash *prh;
4083#endif
4084
4085	PMCDBG(MOD,INI,0, "%s", "cleanup");
4086
4087	/* switch off sampling */
4088	atomic_store_rel_int(&pmc_cpumask, 0);
4089	pmc_intr = NULL;
4090
4091	sx_xlock(&pmc_sx);
4092	if (pmc_hook == NULL) {	/* being unloaded already */
4093		sx_xunlock(&pmc_sx);
4094		return;
4095	}
4096
4097	pmc_hook = NULL; /* prevent new threads from entering module */
4098
4099	/* deregister event handlers */
4100	EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4101	EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4102
4103	/* send SIGBUS to all owner threads, free up allocations */
4104	if (pmc_ownerhash)
4105		for (ph = pmc_ownerhash;
4106		     ph <= &pmc_ownerhash[pmc_ownerhashmask];
4107		     ph++) {
4108			LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4109				pmc_remove_owner(po);
4110
4111				/* send SIGBUS to owner processes */
4112				PMCDBG(MOD,INI,2, "cleanup signal proc=%p "
4113				    "(%d, %s)", po->po_owner,
4114				    po->po_owner->p_pid,
4115				    po->po_owner->p_comm);
4116
4117				PROC_LOCK(po->po_owner);
4118				psignal(po->po_owner, SIGBUS);
4119				PROC_UNLOCK(po->po_owner);
4120
4121				pmc_destroy_owner_descriptor(po);
4122			}
4123		}
4124
4125	/* reclaim allocated data structures */
4126	if (pmc_mtxpool)
4127		mtx_pool_destroy(&pmc_mtxpool);
4128
4129	mtx_destroy(&pmc_processhash_mtx);
4130	if (pmc_processhash) {
4131#ifdef	DEBUG
4132		struct pmc_process *pp;
4133
4134		PMCDBG(MOD,INI,3, "%s", "destroy process hash");
4135		for (prh = pmc_processhash;
4136		     prh <= &pmc_processhash[pmc_processhashmask];
4137		     prh++)
4138			LIST_FOREACH(pp, prh, pp_next)
4139			    PMCDBG(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
4140#endif
4141
4142		hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
4143		pmc_processhash = NULL;
4144	}
4145
4146	if (pmc_ownerhash) {
4147		PMCDBG(MOD,INI,3, "%s", "destroy owner hash");
4148		hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
4149		pmc_ownerhash = NULL;
4150	}
4151
4152	KASSERT(LIST_EMPTY(&pmc_ss_owners),
4153	    ("[pmc,%d] Global SS owner list not empty", __LINE__));
4154	KASSERT(pmc_ss_count == 0,
4155	    ("[pmc,%d] Global SS count not empty", __LINE__));
4156
4157	/* free the per-cpu sample buffers */
4158	for (cpu = 0; cpu < mp_ncpus; cpu++) {
4159		if (pmc_cpu_is_disabled(cpu))
4160			continue;
4161		KASSERT(pmc_pcpu[cpu]->pc_sb != NULL,
4162		    ("[pmc,%d] Null cpu sample buffer cpu=%d", __LINE__,
4163			cpu));
4164		FREE(pmc_pcpu[cpu]->pc_sb, M_PMC);
4165		pmc_pcpu[cpu]->pc_sb = NULL;
4166	}
4167
4168 	/* do processor dependent cleanup */
4169	PMCDBG(MOD,INI,3, "%s", "md cleanup");
4170	if (md) {
4171		pmc_save_cpu_binding(&pb);
4172		for (cpu = 0; cpu < mp_ncpus; cpu++) {
4173			PMCDBG(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
4174			    cpu, pmc_pcpu[cpu]);
4175			if (pmc_cpu_is_disabled(cpu))
4176				continue;
4177			pmc_select_cpu(cpu);
4178			if (pmc_pcpu[cpu])
4179				(void) md->pmd_cleanup(cpu);
4180		}
4181		FREE(md, M_PMC);
4182		md = NULL;
4183		pmc_restore_cpu_binding(&pb);
4184	}
4185
4186	/* deallocate per-cpu structures */
4187	FREE(pmc_pcpu, M_PMC);
4188	pmc_pcpu = NULL;
4189
4190	FREE(pmc_pcpu_saved, M_PMC);
4191	pmc_pcpu_saved = NULL;
4192
4193	if (pmc_pmcdisp) {
4194		FREE(pmc_pmcdisp, M_PMC);
4195		pmc_pmcdisp = NULL;
4196	}
4197
4198	pmclog_shutdown();
4199
4200	sx_xunlock(&pmc_sx); 	/* we are done */
4201}
4202
4203/*
4204 * The function called at load/unload.
4205 */
4206
4207static int
4208load (struct module *module __unused, int cmd, void *arg __unused)
4209{
4210	int error;
4211
4212	error = 0;
4213
4214	switch (cmd) {
4215	case MOD_LOAD :
4216		/* initialize the subsystem */
4217		error = pmc_initialize();
4218		if (error != 0)
4219			break;
4220		PMCDBG(MOD,INI,1, "syscall=%d ncpus=%d",
4221		    pmc_syscall_num, mp_ncpus);
4222		break;
4223
4224
4225	case MOD_UNLOAD :
4226	case MOD_SHUTDOWN:
4227		pmc_cleanup();
4228		PMCDBG(MOD,INI,1, "%s", "unloaded");
4229		break;
4230
4231	default :
4232		error = EINVAL;	/* XXX should panic(9) */
4233		break;
4234	}
4235
4236	return error;
4237}
4238
4239/* memory pool */
4240MALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");
4241