hwpmc_mod.c revision 184214
1145256Sjkoshy/*-
2183266Sjkoshy * Copyright (c) 2003-2008 Joseph Koshy
3174395Sjkoshy * Copyright (c) 2007 The FreeBSD Foundation
4145256Sjkoshy * All rights reserved.
5145256Sjkoshy *
6174395Sjkoshy * Portions of this software were developed by A. Joseph Koshy under
7174395Sjkoshy * sponsorship from the FreeBSD Foundation and Google, Inc.
8174395Sjkoshy *
9145256Sjkoshy * Redistribution and use in source and binary forms, with or without
10145256Sjkoshy * modification, are permitted provided that the following conditions
11145256Sjkoshy * are met:
12145256Sjkoshy * 1. Redistributions of source code must retain the above copyright
13145256Sjkoshy *    notice, this list of conditions and the following disclaimer.
14145256Sjkoshy * 2. Redistributions in binary form must reproduce the above copyright
15145256Sjkoshy *    notice, this list of conditions and the following disclaimer in the
16145256Sjkoshy *    documentation and/or other materials provided with the distribution.
17145256Sjkoshy *
18145256Sjkoshy * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19145256Sjkoshy * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20145256Sjkoshy * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21145256Sjkoshy * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22145256Sjkoshy * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23145256Sjkoshy * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24145256Sjkoshy * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25145256Sjkoshy * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26145256Sjkoshy * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27145256Sjkoshy * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28145256Sjkoshy * SUCH DAMAGE.
29145256Sjkoshy *
30145256Sjkoshy */
31145256Sjkoshy
32145256Sjkoshy#include <sys/cdefs.h>
33145256Sjkoshy__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_mod.c 184214 2008-10-23 20:26:15Z des $");
34145256Sjkoshy
35145256Sjkoshy#include <sys/param.h>
36145256Sjkoshy#include <sys/eventhandler.h>
37145256Sjkoshy#include <sys/jail.h>
38145256Sjkoshy#include <sys/kernel.h>
39147191Sjkoshy#include <sys/kthread.h>
40145256Sjkoshy#include <sys/limits.h>
41145256Sjkoshy#include <sys/lock.h>
42145256Sjkoshy#include <sys/malloc.h>
43145256Sjkoshy#include <sys/module.h>
44145256Sjkoshy#include <sys/mutex.h>
45145256Sjkoshy#include <sys/pmc.h>
46145256Sjkoshy#include <sys/pmckern.h>
47147191Sjkoshy#include <sys/pmclog.h>
48164033Srwatson#include <sys/priv.h>
49145256Sjkoshy#include <sys/proc.h>
50145256Sjkoshy#include <sys/queue.h>
51147191Sjkoshy#include <sys/resourcevar.h>
52145256Sjkoshy#include <sys/sched.h>
53145256Sjkoshy#include <sys/signalvar.h>
54145256Sjkoshy#include <sys/smp.h>
55145256Sjkoshy#include <sys/sx.h>
56145256Sjkoshy#include <sys/sysctl.h>
57145256Sjkoshy#include <sys/sysent.h>
58145256Sjkoshy#include <sys/systm.h>
59147191Sjkoshy#include <sys/vnode.h>
60145256Sjkoshy
61157144Sjkoshy#include <sys/linker.h>		/* needs to be after <sys/malloc.h> */
62157144Sjkoshy
63147191Sjkoshy#include <machine/atomic.h>
64145256Sjkoshy#include <machine/md_var.h>
65145256Sjkoshy
66145256Sjkoshy/*
67145256Sjkoshy * Types
68145256Sjkoshy */
69145256Sjkoshy
70145256Sjkoshyenum pmc_flags {
71145256Sjkoshy	PMC_FLAG_NONE	  = 0x00, /* do nothing */
72145256Sjkoshy	PMC_FLAG_REMOVE   = 0x01, /* atomically remove entry from hash */
73145256Sjkoshy	PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
74145256Sjkoshy};
75145256Sjkoshy
76145256Sjkoshy/*
77145256Sjkoshy * The offset in sysent where the syscall is allocated.
78145256Sjkoshy */
79145256Sjkoshy
80145256Sjkoshystatic int pmc_syscall_num = NO_SYSCALL;
81145256Sjkoshystruct pmc_cpu		**pmc_pcpu;	 /* per-cpu state */
82145256Sjkoshypmc_value_t		*pmc_pcpu_saved; /* saved PMC values: CSW handling */
83145256Sjkoshy
84145256Sjkoshy#define	PMC_PCPU_SAVED(C,R)	pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
85145256Sjkoshy
86145256Sjkoshystruct mtx_pool		*pmc_mtxpool;
87145256Sjkoshystatic int		*pmc_pmcdisp;	 /* PMC row dispositions */
88145256Sjkoshy
89145256Sjkoshy#define	PMC_ROW_DISP_IS_FREE(R)		(pmc_pmcdisp[(R)] == 0)
90145256Sjkoshy#define	PMC_ROW_DISP_IS_THREAD(R)	(pmc_pmcdisp[(R)] > 0)
91145256Sjkoshy#define	PMC_ROW_DISP_IS_STANDALONE(R)	(pmc_pmcdisp[(R)] < 0)
92145256Sjkoshy
93145256Sjkoshy#define	PMC_MARK_ROW_FREE(R) do {					  \
94145256Sjkoshy	pmc_pmcdisp[(R)] = 0;						  \
95145256Sjkoshy} while (0)
96145256Sjkoshy
97145256Sjkoshy#define	PMC_MARK_ROW_STANDALONE(R) do {					  \
98145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
99145256Sjkoshy		    __LINE__));						  \
100145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
101183266Sjkoshy	KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()),		  \
102183266Sjkoshy		("[pmc,%d] row disposition error", __LINE__));		  \
103145256Sjkoshy} while (0)
104145256Sjkoshy
105145256Sjkoshy#define	PMC_UNMARK_ROW_STANDALONE(R) do { 				  \
106145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
107145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
108145256Sjkoshy		    __LINE__));						  \
109145256Sjkoshy} while (0)
110145256Sjkoshy
111145256Sjkoshy#define	PMC_MARK_ROW_THREAD(R) do {					  \
112145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
113145256Sjkoshy		    __LINE__));						  \
114145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
115145256Sjkoshy} while (0)
116145256Sjkoshy
117145256Sjkoshy#define	PMC_UNMARK_ROW_THREAD(R) do {					  \
118145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
119145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
120145256Sjkoshy		    __LINE__));						  \
121145256Sjkoshy} while (0)
122145256Sjkoshy
123145256Sjkoshy
124145256Sjkoshy/* various event handlers */
125145256Sjkoshystatic eventhandler_tag	pmc_exit_tag, pmc_fork_tag;
126145256Sjkoshy
127145256Sjkoshy/* Module statistics */
128145256Sjkoshystruct pmc_op_getdriverstats pmc_stats;
129145256Sjkoshy
130145256Sjkoshy/* Machine/processor dependent operations */
131145256Sjkoshystruct pmc_mdep  *md;
132145256Sjkoshy
133145256Sjkoshy/*
134145256Sjkoshy * Hash tables mapping owner processes and target threads to PMCs.
135145256Sjkoshy */
136145256Sjkoshy
137145256Sjkoshystruct mtx pmc_processhash_mtx;		/* spin mutex */
138145256Sjkoshystatic u_long pmc_processhashmask;
139145256Sjkoshystatic LIST_HEAD(pmc_processhash, pmc_process)	*pmc_processhash;
140145256Sjkoshy
141145256Sjkoshy/*
142145256Sjkoshy * Hash table of PMC owner descriptors.  This table is protected by
143145256Sjkoshy * the shared PMC "sx" lock.
144145256Sjkoshy */
145145256Sjkoshy
146145256Sjkoshystatic u_long pmc_ownerhashmask;
147145256Sjkoshystatic LIST_HEAD(pmc_ownerhash, pmc_owner)	*pmc_ownerhash;
148145256Sjkoshy
149145256Sjkoshy/*
150147191Sjkoshy * List of PMC owners with system-wide sampling PMCs.
151147191Sjkoshy */
152147191Sjkoshy
153147191Sjkoshystatic LIST_HEAD(, pmc_owner)			pmc_ss_owners;
154147191Sjkoshy
155147191Sjkoshy
156147191Sjkoshy/*
157145256Sjkoshy * Prototypes
158145256Sjkoshy */
159145256Sjkoshy
160153110Sru#ifdef	DEBUG
161145256Sjkoshystatic int	pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
162145256Sjkoshystatic int	pmc_debugflags_parse(char *newstr, char *fence);
163145256Sjkoshy#endif
164145256Sjkoshy
165145256Sjkoshystatic int	load(struct module *module, int cmd, void *arg);
166147191Sjkoshystatic int	pmc_attach_process(struct proc *p, struct pmc *pm);
167145256Sjkoshystatic struct pmc *pmc_allocate_pmc_descriptor(void);
168147191Sjkoshystatic struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
169147191Sjkoshystatic int	pmc_attach_one_process(struct proc *p, struct pmc *pm);
170147191Sjkoshystatic int	pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
171147191Sjkoshy    int cpu);
172147191Sjkoshystatic int	pmc_can_attach(struct pmc *pm, struct proc *p);
173174395Sjkoshystatic void	pmc_capture_user_callchain(int cpu, struct trapframe *tf);
174147191Sjkoshystatic void	pmc_cleanup(void);
175147191Sjkoshystatic int	pmc_detach_process(struct proc *p, struct pmc *pm);
176147191Sjkoshystatic int	pmc_detach_one_process(struct proc *p, struct pmc *pm,
177147191Sjkoshy    int flags);
178147191Sjkoshystatic void	pmc_destroy_owner_descriptor(struct pmc_owner *po);
179147191Sjkoshystatic struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
180147191Sjkoshystatic int	pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
181145256Sjkoshystatic struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
182145256Sjkoshy    pmc_id_t pmc);
183145256Sjkoshystatic struct pmc_process *pmc_find_process_descriptor(struct proc *p,
184145256Sjkoshy    uint32_t mode);
185145774Sjkoshystatic void	pmc_force_context_switch(void);
186145256Sjkoshystatic void	pmc_link_target_process(struct pmc *pm,
187145256Sjkoshy    struct pmc_process *pp);
188174395Sjkoshystatic void	pmc_log_all_process_mappings(struct pmc_owner *po);
189174395Sjkoshystatic void	pmc_log_kernel_mappings(struct pmc *pm);
190174395Sjkoshystatic void	pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
191147191Sjkoshystatic void	pmc_maybe_remove_owner(struct pmc_owner *po);
192147191Sjkoshystatic void	pmc_process_csw_in(struct thread *td);
193147191Sjkoshystatic void	pmc_process_csw_out(struct thread *td);
194145256Sjkoshystatic void	pmc_process_exit(void *arg, struct proc *p);
195145256Sjkoshystatic void	pmc_process_fork(void *arg, struct proc *p1,
196145256Sjkoshy    struct proc *p2, int n);
197147191Sjkoshystatic void	pmc_process_samples(int cpu);
198147191Sjkoshystatic void	pmc_release_pmc_descriptor(struct pmc *pmc);
199147191Sjkoshystatic void	pmc_remove_owner(struct pmc_owner *po);
200147191Sjkoshystatic void	pmc_remove_process_descriptor(struct pmc_process *pp);
201147191Sjkoshystatic void	pmc_restore_cpu_binding(struct pmc_binding *pb);
202147191Sjkoshystatic void	pmc_save_cpu_binding(struct pmc_binding *pb);
203147191Sjkoshystatic void	pmc_select_cpu(int cpu);
204145256Sjkoshystatic int	pmc_start(struct pmc *pm);
205145256Sjkoshystatic int	pmc_stop(struct pmc *pm);
206147191Sjkoshystatic int	pmc_syscall_handler(struct thread *td, void *syscall_args);
207147191Sjkoshystatic void	pmc_unlink_target_process(struct pmc *pmc,
208147191Sjkoshy    struct pmc_process *pp);
209145256Sjkoshy
210145256Sjkoshy/*
211145256Sjkoshy * Kernel tunables and sysctl(8) interface.
212145256Sjkoshy */
213145256Sjkoshy
214145256SjkoshySYSCTL_NODE(_kern, OID_AUTO, hwpmc, CTLFLAG_RW, 0, "HWPMC parameters");
215145256Sjkoshy
216174395Sjkoshystatic int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
217174395SjkoshyTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "callchaindepth", &pmc_callchaindepth);
218174395SjkoshySYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_TUN|CTLFLAG_RD,
219174395Sjkoshy    &pmc_callchaindepth, 0, "depth of call chain records");
220174395Sjkoshy
221153110Sru#ifdef	DEBUG
222147191Sjkoshystruct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
223145256Sjkoshychar	pmc_debugstr[PMC_DEBUG_STRSIZE];
224145256SjkoshyTUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
225145256Sjkoshy    sizeof(pmc_debugstr));
226145256SjkoshySYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
227145256Sjkoshy    CTLTYPE_STRING|CTLFLAG_RW|CTLFLAG_TUN,
228145256Sjkoshy    0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
229145256Sjkoshy#endif
230145256Sjkoshy
231145256Sjkoshy/*
232147191Sjkoshy * kern.hwpmc.hashrows -- determines the number of rows in the
233145256Sjkoshy * of the hash table used to look up threads
234145256Sjkoshy */
235145256Sjkoshy
236145256Sjkoshystatic int pmc_hashsize = PMC_HASH_SIZE;
237145256SjkoshyTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "hashsize", &pmc_hashsize);
238145256SjkoshySYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_TUN|CTLFLAG_RD,
239145256Sjkoshy    &pmc_hashsize, 0, "rows in hash tables");
240145256Sjkoshy
241145256Sjkoshy/*
242174395Sjkoshy * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
243145256Sjkoshy */
244145256Sjkoshy
245147191Sjkoshystatic int pmc_nsamples = PMC_NSAMPLES;
246147191SjkoshyTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nsamples", &pmc_nsamples);
247147191SjkoshySYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_TUN|CTLFLAG_RD,
248147191Sjkoshy    &pmc_nsamples, 0, "number of PC samples per CPU");
249145256Sjkoshy
250174395Sjkoshy
251145256Sjkoshy/*
252147191Sjkoshy * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
253145256Sjkoshy */
254145256Sjkoshy
255145256Sjkoshystatic int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
256145256SjkoshyTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "mtxpoolsize", &pmc_mtxpool_size);
257145256SjkoshySYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_TUN|CTLFLAG_RD,
258145256Sjkoshy    &pmc_mtxpool_size, 0, "size of spin mutex pool");
259145256Sjkoshy
260145256Sjkoshy
261145256Sjkoshy/*
262145256Sjkoshy * security.bsd.unprivileged_syspmcs -- allow non-root processes to
263145256Sjkoshy * allocate system-wide PMCs.
264145256Sjkoshy *
265145256Sjkoshy * Allowing unprivileged processes to allocate system PMCs is convenient
266145256Sjkoshy * if system-wide measurements need to be taken concurrently with other
267145256Sjkoshy * per-process measurements.  This feature is turned off by default.
268145256Sjkoshy */
269145256Sjkoshy
270145256Sjkoshystatic int pmc_unprivileged_syspmcs = 0;
271145256SjkoshyTUNABLE_INT("security.bsd.unprivileged_syspmcs", &pmc_unprivileged_syspmcs);
272145256SjkoshySYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RW,
273145256Sjkoshy    &pmc_unprivileged_syspmcs, 0,
274145256Sjkoshy    "allow unprivileged process to allocate system PMCs");
275145256Sjkoshy
276147191Sjkoshy/*
277147191Sjkoshy * Hash function.  Discard the lower 2 bits of the pointer since
278147191Sjkoshy * these are always zero for our uses.  The hash multiplier is
279147191Sjkoshy * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
280147191Sjkoshy */
281145256Sjkoshy
282145256Sjkoshy#if	LONG_BIT == 64
283145256Sjkoshy#define	_PMC_HM		11400714819323198486u
284145256Sjkoshy#elif	LONG_BIT == 32
285145256Sjkoshy#define	_PMC_HM		2654435769u
286145256Sjkoshy#else
287145256Sjkoshy#error 	Must know the size of 'long' to compile
288145256Sjkoshy#endif
289145256Sjkoshy
290145256Sjkoshy#define	PMC_HASH_PTR(P,M)	((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
291145256Sjkoshy
292145256Sjkoshy/*
293145256Sjkoshy * Syscall structures
294145256Sjkoshy */
295145256Sjkoshy
296145256Sjkoshy/* The `sysent' for the new syscall */
297145256Sjkoshystatic struct sysent pmc_sysent = {
298145256Sjkoshy	2,			/* sy_narg */
299145256Sjkoshy	pmc_syscall_handler	/* sy_call */
300145256Sjkoshy};
301145256Sjkoshy
302145256Sjkoshystatic struct syscall_module_data pmc_syscall_mod = {
303145256Sjkoshy	load,
304145256Sjkoshy	NULL,
305145256Sjkoshy	&pmc_syscall_num,
306145256Sjkoshy	&pmc_sysent,
307145256Sjkoshy	{ 0, NULL }
308145256Sjkoshy};
309145256Sjkoshy
310145256Sjkoshystatic moduledata_t pmc_mod = {
311145256Sjkoshy	PMC_MODULE_NAME,
312145256Sjkoshy	syscall_module_handler,
313145256Sjkoshy	&pmc_syscall_mod
314145256Sjkoshy};
315145256Sjkoshy
316145256SjkoshyDECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
317145256SjkoshyMODULE_VERSION(pmc, PMC_VERSION);
318145256Sjkoshy
319153110Sru#ifdef	DEBUG
320147191Sjkoshyenum pmc_dbgparse_state {
321147191Sjkoshy	PMCDS_WS,		/* in whitespace */
322147191Sjkoshy	PMCDS_MAJOR,		/* seen a major keyword */
323147191Sjkoshy	PMCDS_MINOR
324147191Sjkoshy};
325147191Sjkoshy
326145256Sjkoshystatic int
327145256Sjkoshypmc_debugflags_parse(char *newstr, char *fence)
328145256Sjkoshy{
329145313Sjkoshy	char c, *p, *q;
330147191Sjkoshy	struct pmc_debugflags *tmpflags;
331147191Sjkoshy	int error, found, *newbits, tmp;
332147191Sjkoshy	size_t kwlen;
333145256Sjkoshy
334184214Sdes	tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK|M_ZERO);
335145256Sjkoshy
336145256Sjkoshy	p = newstr;
337147191Sjkoshy	error = 0;
338145256Sjkoshy
339147191Sjkoshy	for (; p < fence && (c = *p); p++) {
340145256Sjkoshy
341147191Sjkoshy		/* skip white space */
342147191Sjkoshy		if (c == ' ' || c == '\t')
343147191Sjkoshy			continue;
344147191Sjkoshy
345147191Sjkoshy		/* look for a keyword followed by "=" */
346147191Sjkoshy		for (q = p; p < fence && (c = *p) && c != '='; p++)
347147191Sjkoshy			;
348147191Sjkoshy		if (c != '=') {
349147191Sjkoshy			error = EINVAL;
350147191Sjkoshy			goto done;
351145256Sjkoshy		}
352145256Sjkoshy
353147191Sjkoshy		kwlen = p - q;
354147191Sjkoshy		newbits = NULL;
355145256Sjkoshy
356147191Sjkoshy		/* lookup flag group name */
357147191Sjkoshy#define	DBG_SET_FLAG_MAJ(S,F)						\
358147191Sjkoshy		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
359147191Sjkoshy			newbits = &tmpflags->pdb_ ## F;
360145256Sjkoshy
361147191Sjkoshy		DBG_SET_FLAG_MAJ("cpu",		CPU);
362147191Sjkoshy		DBG_SET_FLAG_MAJ("csw",		CSW);
363147191Sjkoshy		DBG_SET_FLAG_MAJ("logging",	LOG);
364147191Sjkoshy		DBG_SET_FLAG_MAJ("module",	MOD);
365147191Sjkoshy		DBG_SET_FLAG_MAJ("md", 		MDP);
366147191Sjkoshy		DBG_SET_FLAG_MAJ("owner",	OWN);
367147191Sjkoshy		DBG_SET_FLAG_MAJ("pmc",		PMC);
368147191Sjkoshy		DBG_SET_FLAG_MAJ("process",	PRC);
369147191Sjkoshy		DBG_SET_FLAG_MAJ("sampling", 	SAM);
370145256Sjkoshy
371147191Sjkoshy		if (newbits == NULL) {
372147191Sjkoshy			error = EINVAL;
373147191Sjkoshy			goto done;
374145256Sjkoshy		}
375145256Sjkoshy
376147191Sjkoshy		p++;		/* skip the '=' */
377145256Sjkoshy
378147191Sjkoshy		/* Now parse the individual flags */
379147191Sjkoshy		tmp = 0;
380147191Sjkoshy	newflag:
381147191Sjkoshy		for (q = p; p < fence && (c = *p); p++)
382147191Sjkoshy			if (c == ' ' || c == '\t' || c == ',')
383147191Sjkoshy				break;
384147191Sjkoshy
385147191Sjkoshy		/* p == fence or c == ws or c == "," or c == 0 */
386147191Sjkoshy
387147191Sjkoshy		if ((kwlen = p - q) == 0) {
388147191Sjkoshy			*newbits = tmp;
389147191Sjkoshy			continue;
390147191Sjkoshy		}
391147191Sjkoshy
392147191Sjkoshy		found = 0;
393147191Sjkoshy#define	DBG_SET_FLAG_MIN(S,F)						\
394147191Sjkoshy		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
395147191Sjkoshy			tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
396147191Sjkoshy
397147191Sjkoshy		/* a '*' denotes all possible flags in the group */
398147191Sjkoshy		if (kwlen == 1 && *q == '*')
399147191Sjkoshy			tmp = found = ~0;
400147191Sjkoshy		/* look for individual flag names */
401147191Sjkoshy		DBG_SET_FLAG_MIN("allocaterow", ALR);
402147191Sjkoshy		DBG_SET_FLAG_MIN("allocate",	ALL);
403147191Sjkoshy		DBG_SET_FLAG_MIN("attach",	ATT);
404147191Sjkoshy		DBG_SET_FLAG_MIN("bind",	BND);
405147191Sjkoshy		DBG_SET_FLAG_MIN("config",	CFG);
406147191Sjkoshy		DBG_SET_FLAG_MIN("exec",	EXC);
407147191Sjkoshy		DBG_SET_FLAG_MIN("exit",	EXT);
408147191Sjkoshy		DBG_SET_FLAG_MIN("find",	FND);
409147191Sjkoshy		DBG_SET_FLAG_MIN("flush",	FLS);
410147191Sjkoshy		DBG_SET_FLAG_MIN("fork",	FRK);
411147191Sjkoshy		DBG_SET_FLAG_MIN("getbuf",	GTB);
412147191Sjkoshy		DBG_SET_FLAG_MIN("hook",	PMH);
413147191Sjkoshy		DBG_SET_FLAG_MIN("init",	INI);
414147191Sjkoshy		DBG_SET_FLAG_MIN("intr",	INT);
415147191Sjkoshy		DBG_SET_FLAG_MIN("linktarget",	TLK);
416147191Sjkoshy		DBG_SET_FLAG_MIN("mayberemove", OMR);
417147191Sjkoshy		DBG_SET_FLAG_MIN("ops",		OPS);
418147191Sjkoshy		DBG_SET_FLAG_MIN("read",	REA);
419147191Sjkoshy		DBG_SET_FLAG_MIN("register",	REG);
420147191Sjkoshy		DBG_SET_FLAG_MIN("release",	REL);
421147191Sjkoshy		DBG_SET_FLAG_MIN("remove",	ORM);
422147191Sjkoshy		DBG_SET_FLAG_MIN("sample",	SAM);
423147191Sjkoshy		DBG_SET_FLAG_MIN("scheduleio",	SIO);
424147191Sjkoshy		DBG_SET_FLAG_MIN("select",	SEL);
425147191Sjkoshy		DBG_SET_FLAG_MIN("signal",	SIG);
426147191Sjkoshy		DBG_SET_FLAG_MIN("swi",		SWI);
427147191Sjkoshy		DBG_SET_FLAG_MIN("swo",		SWO);
428147191Sjkoshy		DBG_SET_FLAG_MIN("start",	STA);
429147191Sjkoshy		DBG_SET_FLAG_MIN("stop",	STO);
430147191Sjkoshy		DBG_SET_FLAG_MIN("syscall",	PMS);
431147191Sjkoshy		DBG_SET_FLAG_MIN("unlinktarget", TUL);
432147191Sjkoshy		DBG_SET_FLAG_MIN("write",	WRI);
433147191Sjkoshy		if (found == 0) {
434147191Sjkoshy			/* unrecognized flag name */
435147191Sjkoshy			error = EINVAL;
436147191Sjkoshy			goto done;
437147191Sjkoshy		}
438147191Sjkoshy
439147191Sjkoshy		if (c == 0 || c == ' ' || c == '\t') {	/* end of flag group */
440147191Sjkoshy			*newbits = tmp;
441147191Sjkoshy			continue;
442147191Sjkoshy		}
443147191Sjkoshy
444147191Sjkoshy		p++;
445147191Sjkoshy		goto newflag;
446145256Sjkoshy	}
447145256Sjkoshy
448147191Sjkoshy	/* save the new flag set */
449147191Sjkoshy	bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
450145256Sjkoshy
451147191Sjkoshy done:
452184205Sdes	free(tmpflags, M_PMC);
453147191Sjkoshy	return error;
454145256Sjkoshy}
455145256Sjkoshy
456145256Sjkoshystatic int
457145256Sjkoshypmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
458145256Sjkoshy{
459145256Sjkoshy	char *fence, *newstr;
460145256Sjkoshy	int error;
461145256Sjkoshy	unsigned int n;
462145256Sjkoshy
463145256Sjkoshy	(void) arg1; (void) arg2; /* unused parameters */
464145256Sjkoshy
465145256Sjkoshy	n = sizeof(pmc_debugstr);
466184205Sdes	newstr = malloc(n, M_PMC, M_ZERO|M_WAITOK);
467147191Sjkoshy	(void) strlcpy(newstr, pmc_debugstr, n);
468145256Sjkoshy
469145256Sjkoshy	error = sysctl_handle_string(oidp, newstr, n, req);
470145256Sjkoshy
471145256Sjkoshy	/* if there is a new string, parse and copy it */
472145256Sjkoshy	if (error == 0 && req->newptr != NULL) {
473147191Sjkoshy		fence = newstr + (n < req->newlen ? n : req->newlen + 1);
474145256Sjkoshy		if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
475145256Sjkoshy			(void) strlcpy(pmc_debugstr, newstr,
476145256Sjkoshy			    sizeof(pmc_debugstr));
477145256Sjkoshy	}
478145256Sjkoshy
479184205Sdes	free(newstr, M_PMC);
480145256Sjkoshy
481145256Sjkoshy	return error;
482145256Sjkoshy}
483145256Sjkoshy#endif
484145256Sjkoshy
485145256Sjkoshy/*
486145256Sjkoshy * Concurrency Control
487145256Sjkoshy *
488145256Sjkoshy * The driver manages the following data structures:
489145256Sjkoshy *
490145256Sjkoshy *   - target process descriptors, one per target process
491145256Sjkoshy *   - owner process descriptors (and attached lists), one per owner process
492145256Sjkoshy *   - lookup hash tables for owner and target processes
493145256Sjkoshy *   - PMC descriptors (and attached lists)
494145256Sjkoshy *   - per-cpu hardware state
495145256Sjkoshy *   - the 'hook' variable through which the kernel calls into
496145256Sjkoshy *     this module
497145256Sjkoshy *   - the machine hardware state (managed by the MD layer)
498145256Sjkoshy *
499145256Sjkoshy * These data structures are accessed from:
500145256Sjkoshy *
501145256Sjkoshy * - thread context-switch code
502145256Sjkoshy * - interrupt handlers (possibly on multiple cpus)
503145256Sjkoshy * - kernel threads on multiple cpus running on behalf of user
504145256Sjkoshy *   processes doing system calls
505145256Sjkoshy * - this driver's private kernel threads
506145256Sjkoshy *
507145256Sjkoshy * = Locks and Locking strategy =
508145256Sjkoshy *
509145256Sjkoshy * The driver uses four locking strategies for its operation:
510145256Sjkoshy *
511168856Sjkoshy * - The global SX lock "pmc_sx" is used to protect internal
512168856Sjkoshy *   data structures.
513145256Sjkoshy *
514168856Sjkoshy *   Calls into the module by syscall() start with this lock being
515168856Sjkoshy *   held in exclusive mode.  Depending on the requested operation,
516168856Sjkoshy *   the lock may be downgraded to 'shared' mode to allow more
517168856Sjkoshy *   concurrent readers into the module.  Calls into the module from
518168856Sjkoshy *   other parts of the kernel acquire the lock in shared mode.
519145256Sjkoshy *
520145256Sjkoshy *   This SX lock is held in exclusive mode for any operations that
521145256Sjkoshy *   modify the linkages between the driver's internal data structures.
522145256Sjkoshy *
523145256Sjkoshy *   The 'pmc_hook' function pointer is also protected by this lock.
524145256Sjkoshy *   It is only examined with the sx lock held in exclusive mode.  The
525168856Sjkoshy *   kernel module is allowed to be unloaded only with the sx lock held
526168856Sjkoshy *   in exclusive mode.  In normal syscall handling, after acquiring the
527168856Sjkoshy *   pmc_sx lock we first check that 'pmc_hook' is non-null before
528168856Sjkoshy *   proceeding.  This prevents races between the thread unloading the module
529168856Sjkoshy *   and other threads seeking to use the module.
530145256Sjkoshy *
531145256Sjkoshy * - Lookups of target process structures and owner process structures
532145256Sjkoshy *   cannot use the global "pmc_sx" SX lock because these lookups need
533145256Sjkoshy *   to happen during context switches and in other critical sections
534145256Sjkoshy *   where sleeping is not allowed.  We protect these lookup tables
535145256Sjkoshy *   with their own private spin-mutexes, "pmc_processhash_mtx" and
536168856Sjkoshy *   "pmc_ownerhash_mtx".
537145256Sjkoshy *
538145256Sjkoshy * - Interrupt handlers work in a lock free manner.  At interrupt
539145256Sjkoshy *   time, handlers look at the PMC pointer (phw->phw_pmc) configured
540145256Sjkoshy *   when the PMC was started.  If this pointer is NULL, the interrupt
541145256Sjkoshy *   is ignored after updating driver statistics.  We ensure that this
542145256Sjkoshy *   pointer is set (using an atomic operation if necessary) before the
543145256Sjkoshy *   PMC hardware is started.  Conversely, this pointer is unset atomically
544145256Sjkoshy *   only after the PMC hardware is stopped.
545145256Sjkoshy *
546145256Sjkoshy *   We ensure that everything needed for the operation of an
547145256Sjkoshy *   interrupt handler is available without it needing to acquire any
548145256Sjkoshy *   locks.  We also ensure that a PMC's software state is destroyed only
549145256Sjkoshy *   after the PMC is taken off hardware (on all CPUs).
550145256Sjkoshy *
551145256Sjkoshy * - Context-switch handling with process-private PMCs needs more
552145256Sjkoshy *   care.
553145256Sjkoshy *
554145256Sjkoshy *   A given process may be the target of multiple PMCs.  For example,
555145256Sjkoshy *   PMCATTACH and PMCDETACH may be requested by a process on one CPU
556145256Sjkoshy *   while the target process is running on another.  A PMC could also
557145256Sjkoshy *   be getting released because its owner is exiting.  We tackle
558145256Sjkoshy *   these situations in the following manner:
559145256Sjkoshy *
560145256Sjkoshy *   - each target process structure 'pmc_process' has an array
561145256Sjkoshy *     of 'struct pmc *' pointers, one for each hardware PMC.
562145256Sjkoshy *
563145256Sjkoshy *   - At context switch IN time, each "target" PMC in RUNNING state
564145256Sjkoshy *     gets started on hardware and a pointer to each PMC is copied into
565145256Sjkoshy *     the per-cpu phw array.  The 'runcount' for the PMC is
566145256Sjkoshy *     incremented.
567145256Sjkoshy *
568145256Sjkoshy *   - At context switch OUT time, all process-virtual PMCs are stopped
569145256Sjkoshy *     on hardware.  The saved value is added to the PMCs value field
570145256Sjkoshy *     only if the PMC is in a non-deleted state (the PMCs state could
571145256Sjkoshy *     have changed during the current time slice).
572145256Sjkoshy *
573145256Sjkoshy *     Note that since in-between a switch IN on a processor and a switch
574145256Sjkoshy *     OUT, the PMC could have been released on another CPU.  Therefore
575145256Sjkoshy *     context switch OUT always looks at the hardware state to turn
576145256Sjkoshy *     OFF PMCs and will update a PMC's saved value only if reachable
577145256Sjkoshy *     from the target process record.
578145256Sjkoshy *
579145256Sjkoshy *   - OP PMCRELEASE could be called on a PMC at any time (the PMC could
580145256Sjkoshy *     be attached to many processes at the time of the call and could
581145256Sjkoshy *     be active on multiple CPUs).
582145256Sjkoshy *
583145256Sjkoshy *     We prevent further scheduling of the PMC by marking it as in
584145256Sjkoshy *     state 'DELETED'.  If the runcount of the PMC is non-zero then
585145256Sjkoshy *     this PMC is currently running on a CPU somewhere.  The thread
586167086Sjhb *     doing the PMCRELEASE operation waits by repeatedly doing a
587167086Sjhb *     pause() till the runcount comes to zero.
588145256Sjkoshy *
589168856Sjkoshy * The contents of a PMC descriptor (struct pmc) are protected using
590168856Sjkoshy * a spin-mutex.  In order to save space, we use a mutex pool.
591168856Sjkoshy *
592168856Sjkoshy * In terms of lock types used by witness(4), we use:
593168856Sjkoshy * - Type "pmc-sx", used by the global SX lock.
594168856Sjkoshy * - Type "pmc-sleep", for sleep mutexes used by logger threads.
595168856Sjkoshy * - Type "pmc-per-proc", for protecting PMC owner descriptors.
596168856Sjkoshy * - Type "pmc-leaf", used for all other spin mutexes.
597145256Sjkoshy */
598145256Sjkoshy
599145256Sjkoshy/*
600145256Sjkoshy * save the cpu binding of the current kthread
601145256Sjkoshy */
602145256Sjkoshy
603145256Sjkoshystatic void
604145256Sjkoshypmc_save_cpu_binding(struct pmc_binding *pb)
605145256Sjkoshy{
606145256Sjkoshy	PMCDBG(CPU,BND,2, "%s", "save-cpu");
607170307Sjeff	thread_lock(curthread);
608145256Sjkoshy	pb->pb_bound = sched_is_bound(curthread);
609145256Sjkoshy	pb->pb_cpu   = curthread->td_oncpu;
610170307Sjeff	thread_unlock(curthread);
611145256Sjkoshy	PMCDBG(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
612145256Sjkoshy}
613145256Sjkoshy
614145256Sjkoshy/*
615145256Sjkoshy * restore the cpu binding of the current thread
616145256Sjkoshy */
617145256Sjkoshy
618145256Sjkoshystatic void
619145256Sjkoshypmc_restore_cpu_binding(struct pmc_binding *pb)
620145256Sjkoshy{
621145256Sjkoshy	PMCDBG(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
622145256Sjkoshy	    curthread->td_oncpu, pb->pb_cpu);
623170307Sjeff	thread_lock(curthread);
624145256Sjkoshy	if (pb->pb_bound)
625145256Sjkoshy		sched_bind(curthread, pb->pb_cpu);
626145256Sjkoshy	else
627145256Sjkoshy		sched_unbind(curthread);
628170307Sjeff	thread_unlock(curthread);
629145256Sjkoshy	PMCDBG(CPU,BND,2, "%s", "restore-cpu done");
630145256Sjkoshy}
631145256Sjkoshy
632145256Sjkoshy/*
633145256Sjkoshy * move execution over the specified cpu and bind it there.
634145256Sjkoshy */
635145256Sjkoshy
636145256Sjkoshystatic void
637145256Sjkoshypmc_select_cpu(int cpu)
638145256Sjkoshy{
639183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
640145256Sjkoshy	    ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
641145256Sjkoshy
642183266Sjkoshy	/* Never move to an inactive CPU. */
643183266Sjkoshy	KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
644183266Sjkoshy	    "CPU %d", __LINE__, cpu));
645145256Sjkoshy
646145256Sjkoshy	PMCDBG(CPU,SEL,2, "select-cpu cpu=%d", cpu);
647170307Sjeff	thread_lock(curthread);
648145256Sjkoshy	sched_bind(curthread, cpu);
649170307Sjeff	thread_unlock(curthread);
650145256Sjkoshy
651145256Sjkoshy	KASSERT(curthread->td_oncpu == cpu,
652145256Sjkoshy	    ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
653145256Sjkoshy		cpu, curthread->td_oncpu));
654145256Sjkoshy
655145256Sjkoshy	PMCDBG(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
656145256Sjkoshy}
657145256Sjkoshy
658145256Sjkoshy/*
659145774Sjkoshy * Force a context switch.
660145774Sjkoshy *
661167086Sjhb * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
662145774Sjkoshy * guaranteed to force a context switch.
663145774Sjkoshy */
664145774Sjkoshy
665145774Sjkoshystatic void
666145774Sjkoshypmc_force_context_switch(void)
667145774Sjkoshy{
668145774Sjkoshy
669167086Sjhb	pause("pmcctx", 1);
670145774Sjkoshy}
671145774Sjkoshy
672145774Sjkoshy/*
673147191Sjkoshy * Get the file name for an executable.  This is a simple wrapper
674147191Sjkoshy * around vn_fullpath(9).
675145256Sjkoshy */
676145256Sjkoshy
677147191Sjkoshystatic void
678147708Sjkoshypmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
679145256Sjkoshy{
680145256Sjkoshy
681147191Sjkoshy	*fullpath = "unknown";
682147191Sjkoshy	*freepath = NULL;
683175202Sattilio	vn_lock(v, LK_CANRECURSE | LK_EXCLUSIVE | LK_RETRY);
684175294Sattilio	vn_fullpath(curthread, v, fullpath, freepath);
685175294Sattilio	VOP_UNLOCK(v, 0);
686145256Sjkoshy}
687145256Sjkoshy
688145256Sjkoshy/*
689145256Sjkoshy * remove an process owning PMCs
690145256Sjkoshy */
691145256Sjkoshy
692145256Sjkoshyvoid
693145256Sjkoshypmc_remove_owner(struct pmc_owner *po)
694145256Sjkoshy{
695147191Sjkoshy	struct pmc *pm, *tmp;
696145256Sjkoshy
697145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
698145256Sjkoshy
699145256Sjkoshy	PMCDBG(OWN,ORM,1, "remove-owner po=%p", po);
700145256Sjkoshy
701145256Sjkoshy	/* Remove descriptor from the owner hash table */
702145256Sjkoshy	LIST_REMOVE(po, po_next);
703145256Sjkoshy
704147191Sjkoshy	/* release all owned PMC descriptors */
705147191Sjkoshy	LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
706147191Sjkoshy		PMCDBG(OWN,ORM,2, "pmc=%p", pm);
707147191Sjkoshy		KASSERT(pm->pm_owner == po,
708147191Sjkoshy		    ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
709145256Sjkoshy
710147191Sjkoshy		pmc_release_pmc_descriptor(pm);	/* will unlink from the list */
711145256Sjkoshy	}
712145256Sjkoshy
713147191Sjkoshy	KASSERT(po->po_sscount == 0,
714147191Sjkoshy	    ("[pmc,%d] SS count not zero", __LINE__));
715145256Sjkoshy	KASSERT(LIST_EMPTY(&po->po_pmcs),
716147191Sjkoshy	    ("[pmc,%d] PMC list not empty", __LINE__));
717145256Sjkoshy
718147191Sjkoshy	/* de-configure the log file if present */
719145774Sjkoshy	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
720147191Sjkoshy		pmclog_deconfigure_log(po);
721145256Sjkoshy}
722145256Sjkoshy
723145256Sjkoshy/*
724145256Sjkoshy * remove an owner process record if all conditions are met.
725145256Sjkoshy */
726145256Sjkoshy
727145256Sjkoshystatic void
728145256Sjkoshypmc_maybe_remove_owner(struct pmc_owner *po)
729145256Sjkoshy{
730145256Sjkoshy
731145256Sjkoshy	PMCDBG(OWN,OMR,1, "maybe-remove-owner po=%p", po);
732145256Sjkoshy
733145256Sjkoshy	/*
734145256Sjkoshy	 * Remove owner record if
735145256Sjkoshy	 * - this process does not own any PMCs
736145256Sjkoshy	 * - this process has not allocated a system-wide sampling buffer
737145256Sjkoshy	 */
738145256Sjkoshy
739145256Sjkoshy	if (LIST_EMPTY(&po->po_pmcs) &&
740145774Sjkoshy	    ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
741145256Sjkoshy		pmc_remove_owner(po);
742147191Sjkoshy		pmc_destroy_owner_descriptor(po);
743145256Sjkoshy	}
744145256Sjkoshy}
745145256Sjkoshy
746145256Sjkoshy/*
747145256Sjkoshy * Add an association between a target process and a PMC.
748145256Sjkoshy */
749145256Sjkoshy
750145256Sjkoshystatic void
751145256Sjkoshypmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
752145256Sjkoshy{
753145256Sjkoshy	int ri;
754145256Sjkoshy	struct pmc_target *pt;
755145256Sjkoshy
756145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
757145256Sjkoshy
758145256Sjkoshy	KASSERT(pm != NULL && pp != NULL,
759145256Sjkoshy	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
760147191Sjkoshy	KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
761147191Sjkoshy	    ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
762147191Sjkoshy		__LINE__, pm, pp->pp_proc->p_pid));
763145256Sjkoshy	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < ((int) md->pmd_npmc - 1),
764145256Sjkoshy	    ("[pmc,%d] Illegal reference count %d for process record %p",
765145256Sjkoshy		__LINE__, pp->pp_refcnt, (void *) pp));
766145256Sjkoshy
767145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
768145256Sjkoshy
769145256Sjkoshy	PMCDBG(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
770145256Sjkoshy	    pm, ri, pp);
771145256Sjkoshy
772153110Sru#ifdef	DEBUG
773145256Sjkoshy	LIST_FOREACH(pt, &pm->pm_targets, pt_next)
774145256Sjkoshy	    if (pt->pt_process == pp)
775145256Sjkoshy		    KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
776145256Sjkoshy				__LINE__, pp, pm));
777145256Sjkoshy#endif
778145256Sjkoshy
779184214Sdes	pt = malloc(sizeof(struct pmc_target), M_PMC, M_ZERO|M_WAITOK);
780145256Sjkoshy
781145256Sjkoshy	pt->pt_process = pp;
782145256Sjkoshy
783145256Sjkoshy	LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
784145256Sjkoshy
785148067Sjhb	atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
786148067Sjhb	    (uintptr_t)pm);
787145256Sjkoshy
788145615Sjkoshy	if (pm->pm_owner->po_owner == pp->pp_proc)
789145774Sjkoshy		pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
790145615Sjkoshy
791147191Sjkoshy	/*
792147191Sjkoshy	 * Initialize the per-process values at this row index.
793147191Sjkoshy	 */
794147191Sjkoshy	pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
795147191Sjkoshy	    pm->pm_sc.pm_reloadcount : 0;
796147191Sjkoshy
797145256Sjkoshy	pp->pp_refcnt++;
798145256Sjkoshy
799145256Sjkoshy}
800145256Sjkoshy
801145256Sjkoshy/*
802145256Sjkoshy * Removes the association between a target process and a PMC.
803145256Sjkoshy */
804145256Sjkoshy
805145256Sjkoshystatic void
806145256Sjkoshypmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
807145256Sjkoshy{
808145256Sjkoshy	int ri;
809147191Sjkoshy	struct proc *p;
810145256Sjkoshy	struct pmc_target *ptgt;
811145256Sjkoshy
812145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
813145256Sjkoshy
814145256Sjkoshy	KASSERT(pm != NULL && pp != NULL,
815145256Sjkoshy	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
816145256Sjkoshy
817145256Sjkoshy	KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt < (int) md->pmd_npmc,
818145256Sjkoshy	    ("[pmc,%d] Illegal ref count %d on process record %p",
819145256Sjkoshy		__LINE__, pp->pp_refcnt, (void *) pp));
820145256Sjkoshy
821145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
822145256Sjkoshy
823145256Sjkoshy	PMCDBG(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
824145256Sjkoshy	    pm, ri, pp);
825145256Sjkoshy
826145256Sjkoshy	KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
827145256Sjkoshy	    ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
828145256Sjkoshy		ri, pm, pp->pp_pmcs[ri].pp_pmc));
829145256Sjkoshy
830145256Sjkoshy	pp->pp_pmcs[ri].pp_pmc = NULL;
831145256Sjkoshy	pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
832145256Sjkoshy
833145774Sjkoshy	/* Remove owner-specific flags */
834145774Sjkoshy	if (pm->pm_owner->po_owner == pp->pp_proc) {
835145774Sjkoshy		pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
836145774Sjkoshy		pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
837145774Sjkoshy	}
838145615Sjkoshy
839145256Sjkoshy	pp->pp_refcnt--;
840145256Sjkoshy
841145256Sjkoshy	/* Remove the target process from the PMC structure */
842145256Sjkoshy	LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
843145256Sjkoshy		if (ptgt->pt_process == pp)
844145256Sjkoshy			break;
845145256Sjkoshy
846145256Sjkoshy	KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
847145256Sjkoshy		    "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
848145256Sjkoshy
849145256Sjkoshy	LIST_REMOVE(ptgt, pt_next);
850184205Sdes	free(ptgt, M_PMC);
851145256Sjkoshy
852147191Sjkoshy	/* if the PMC now lacks targets, send the owner a SIGIO */
853147191Sjkoshy	if (LIST_EMPTY(&pm->pm_targets)) {
854147191Sjkoshy		p = pm->pm_owner->po_owner;
855147191Sjkoshy		PROC_LOCK(p);
856147191Sjkoshy		psignal(p, SIGIO);
857147191Sjkoshy		PROC_UNLOCK(p);
858145256Sjkoshy
859147191Sjkoshy		PMCDBG(PRC,SIG,2, "signalling proc=%p signal=%d", p,
860147191Sjkoshy		    SIGIO);
861145256Sjkoshy	}
862145256Sjkoshy}
863145256Sjkoshy
864145256Sjkoshy/*
865145256Sjkoshy * Check if PMC 'pm' may be attached to target process 't'.
866145256Sjkoshy */
867145256Sjkoshy
868145256Sjkoshystatic int
869145256Sjkoshypmc_can_attach(struct pmc *pm, struct proc *t)
870145256Sjkoshy{
871145256Sjkoshy	struct proc *o;		/* pmc owner */
872145256Sjkoshy	struct ucred *oc, *tc;	/* owner, target credentials */
873145256Sjkoshy	int decline_attach, i;
874145256Sjkoshy
875145256Sjkoshy	/*
876145256Sjkoshy	 * A PMC's owner can always attach that PMC to itself.
877145256Sjkoshy	 */
878145256Sjkoshy
879145256Sjkoshy	if ((o = pm->pm_owner->po_owner) == t)
880145256Sjkoshy		return 0;
881145256Sjkoshy
882145256Sjkoshy	PROC_LOCK(o);
883145256Sjkoshy	oc = o->p_ucred;
884145256Sjkoshy	crhold(oc);
885145256Sjkoshy	PROC_UNLOCK(o);
886145256Sjkoshy
887145256Sjkoshy	PROC_LOCK(t);
888145256Sjkoshy	tc = t->p_ucred;
889145256Sjkoshy	crhold(tc);
890145256Sjkoshy	PROC_UNLOCK(t);
891145256Sjkoshy
892145256Sjkoshy	/*
893145256Sjkoshy	 * The effective uid of the PMC owner should match at least one
894145256Sjkoshy	 * of the {effective,real,saved} uids of the target process.
895145256Sjkoshy	 */
896145256Sjkoshy
897145256Sjkoshy	decline_attach = oc->cr_uid != tc->cr_uid &&
898145256Sjkoshy	    oc->cr_uid != tc->cr_svuid &&
899145256Sjkoshy	    oc->cr_uid != tc->cr_ruid;
900145256Sjkoshy
901145256Sjkoshy	/*
902145256Sjkoshy	 * Every one of the target's group ids, must be in the owner's
903145256Sjkoshy	 * group list.
904145256Sjkoshy	 */
905145256Sjkoshy	for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
906145256Sjkoshy		decline_attach = !groupmember(tc->cr_groups[i], oc);
907145256Sjkoshy
908145256Sjkoshy	/* check the read and saved gids too */
909145256Sjkoshy	if (decline_attach == 0)
910145256Sjkoshy		decline_attach = !groupmember(tc->cr_rgid, oc) ||
911145256Sjkoshy		    !groupmember(tc->cr_svgid, oc);
912145256Sjkoshy
913145256Sjkoshy	crfree(tc);
914145256Sjkoshy	crfree(oc);
915145256Sjkoshy
916145256Sjkoshy	return !decline_attach;
917145256Sjkoshy}
918145256Sjkoshy
919145256Sjkoshy/*
920145256Sjkoshy * Attach a process to a PMC.
921145256Sjkoshy */
922145256Sjkoshy
923145256Sjkoshystatic int
924145256Sjkoshypmc_attach_one_process(struct proc *p, struct pmc *pm)
925145256Sjkoshy{
926145256Sjkoshy	int ri;
927147191Sjkoshy	char *fullpath, *freepath;
928145256Sjkoshy	struct pmc_process	*pp;
929145256Sjkoshy
930145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
931145256Sjkoshy
932145256Sjkoshy	PMCDBG(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
933145774Sjkoshy	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
934145256Sjkoshy
935145256Sjkoshy	/*
936145256Sjkoshy	 * Locate the process descriptor corresponding to process 'p',
937145256Sjkoshy	 * allocating space as needed.
938145256Sjkoshy	 *
939145256Sjkoshy	 * Verify that rowindex 'pm_rowindex' is free in the process
940145256Sjkoshy	 * descriptor.
941145256Sjkoshy	 *
942145256Sjkoshy	 * If not, allocate space for a descriptor and link the
943145256Sjkoshy	 * process descriptor and PMC.
944145256Sjkoshy	 */
945145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
946145256Sjkoshy
947145256Sjkoshy	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
948145256Sjkoshy		return ENOMEM;
949145256Sjkoshy
950145256Sjkoshy	if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
951145256Sjkoshy		return EEXIST;
952145256Sjkoshy
953145256Sjkoshy	if (pp->pp_pmcs[ri].pp_pmc != NULL)
954145256Sjkoshy		return EBUSY;
955145256Sjkoshy
956145256Sjkoshy	pmc_link_target_process(pm, pp);
957145256Sjkoshy
958147191Sjkoshy	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
959147191Sjkoshy	    (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
960147191Sjkoshy		pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
961147191Sjkoshy
962147191Sjkoshy	pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
963147191Sjkoshy
964147191Sjkoshy	/* issue an attach event to a configured log file */
965147191Sjkoshy	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
966147708Sjkoshy		pmc_getfilename(p->p_textvp, &fullpath, &freepath);
967180794Sjeff		if (p->p_flag & P_KTHREAD) {
968180794Sjeff			fullpath = kernelname;
969180794Sjeff			freepath = NULL;
970180794Sjeff		} else
971180794Sjeff			pmclog_process_pmcattach(pm, p->p_pid, fullpath);
972147191Sjkoshy		if (freepath)
973184205Sdes			free(freepath, M_TEMP);
974174395Sjkoshy		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
975174395Sjkoshy			pmc_log_process_mappings(pm->pm_owner, p);
976147191Sjkoshy	}
977145256Sjkoshy	/* mark process as using HWPMCs */
978145256Sjkoshy	PROC_LOCK(p);
979145256Sjkoshy	p->p_flag |= P_HWPMC;
980145256Sjkoshy	PROC_UNLOCK(p);
981145256Sjkoshy
982145256Sjkoshy	return 0;
983145256Sjkoshy}
984145256Sjkoshy
985145256Sjkoshy/*
986145256Sjkoshy * Attach a process and optionally its children
987145256Sjkoshy */
988145256Sjkoshy
989145256Sjkoshystatic int
990145256Sjkoshypmc_attach_process(struct proc *p, struct pmc *pm)
991145256Sjkoshy{
992145256Sjkoshy	int error;
993145256Sjkoshy	struct proc *top;
994145256Sjkoshy
995145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
996145256Sjkoshy
997145256Sjkoshy	PMCDBG(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
998145774Sjkoshy	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
999145256Sjkoshy
1000145774Sjkoshy
1001145774Sjkoshy	/*
1002145774Sjkoshy	 * If this PMC successfully allowed a GETMSR operation
1003145774Sjkoshy	 * in the past, disallow further ATTACHes.
1004145774Sjkoshy	 */
1005145774Sjkoshy
1006145774Sjkoshy	if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1007145774Sjkoshy		return EPERM;
1008145774Sjkoshy
1009145256Sjkoshy	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1010145256Sjkoshy		return pmc_attach_one_process(p, pm);
1011145256Sjkoshy
1012145256Sjkoshy	/*
1013145256Sjkoshy	 * Traverse all child processes, attaching them to
1014145256Sjkoshy	 * this PMC.
1015145256Sjkoshy	 */
1016145256Sjkoshy
1017145256Sjkoshy	sx_slock(&proctree_lock);
1018145256Sjkoshy
1019145256Sjkoshy	top = p;
1020145256Sjkoshy
1021145256Sjkoshy	for (;;) {
1022145256Sjkoshy		if ((error = pmc_attach_one_process(p, pm)) != 0)
1023145256Sjkoshy			break;
1024145256Sjkoshy		if (!LIST_EMPTY(&p->p_children))
1025145256Sjkoshy			p = LIST_FIRST(&p->p_children);
1026145256Sjkoshy		else for (;;) {
1027145256Sjkoshy			if (p == top)
1028145256Sjkoshy				goto done;
1029145256Sjkoshy			if (LIST_NEXT(p, p_sibling)) {
1030145256Sjkoshy				p = LIST_NEXT(p, p_sibling);
1031145256Sjkoshy				break;
1032145256Sjkoshy			}
1033145256Sjkoshy			p = p->p_pptr;
1034145256Sjkoshy		}
1035145256Sjkoshy	}
1036145256Sjkoshy
1037145256Sjkoshy	if (error)
1038145256Sjkoshy		(void) pmc_detach_process(top, pm);
1039145256Sjkoshy
1040145256Sjkoshy done:
1041145256Sjkoshy	sx_sunlock(&proctree_lock);
1042145256Sjkoshy	return error;
1043145256Sjkoshy}
1044145256Sjkoshy
1045145256Sjkoshy/*
1046145256Sjkoshy * Detach a process from a PMC.  If there are no other PMCs tracking
1047145256Sjkoshy * this process, remove the process structure from its hash table.  If
1048145256Sjkoshy * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1049145256Sjkoshy */
1050145256Sjkoshy
1051145256Sjkoshystatic int
1052145256Sjkoshypmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1053145256Sjkoshy{
1054145256Sjkoshy	int ri;
1055145256Sjkoshy	struct pmc_process *pp;
1056145256Sjkoshy
1057145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1058145256Sjkoshy
1059145256Sjkoshy	KASSERT(pm != NULL,
1060145256Sjkoshy	    ("[pmc,%d] null pm pointer", __LINE__));
1061145256Sjkoshy
1062145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
1063145774Sjkoshy
1064145256Sjkoshy	PMCDBG(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1065145774Sjkoshy	    pm, ri, p, p->p_pid, p->p_comm, flags);
1066145256Sjkoshy
1067145256Sjkoshy	if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1068145256Sjkoshy		return ESRCH;
1069145256Sjkoshy
1070145256Sjkoshy	if (pp->pp_pmcs[ri].pp_pmc != pm)
1071145256Sjkoshy		return EINVAL;
1072145256Sjkoshy
1073145256Sjkoshy	pmc_unlink_target_process(pm, pp);
1074145256Sjkoshy
1075147191Sjkoshy	/* Issue a detach entry if a log file is configured */
1076147191Sjkoshy	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1077147191Sjkoshy		pmclog_process_pmcdetach(pm, p->p_pid);
1078147191Sjkoshy
1079145256Sjkoshy	/*
1080145256Sjkoshy	 * If there are no PMCs targetting this process, we remove its
1081145256Sjkoshy	 * descriptor from the target hash table and unset the P_HWPMC
1082145256Sjkoshy	 * flag in the struct proc.
1083145256Sjkoshy	 */
1084145256Sjkoshy	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1085145256Sjkoshy	    ("[pmc,%d] Illegal refcnt %d for process struct %p",
1086145256Sjkoshy		__LINE__, pp->pp_refcnt, pp));
1087145256Sjkoshy
1088145256Sjkoshy	if (pp->pp_refcnt != 0)	/* still a target of some PMC */
1089145256Sjkoshy		return 0;
1090145256Sjkoshy
1091145256Sjkoshy	pmc_remove_process_descriptor(pp);
1092145256Sjkoshy
1093145256Sjkoshy	if (flags & PMC_FLAG_REMOVE)
1094184205Sdes		free(pp, M_PMC);
1095145256Sjkoshy
1096145256Sjkoshy	PROC_LOCK(p);
1097145256Sjkoshy	p->p_flag &= ~P_HWPMC;
1098145256Sjkoshy	PROC_UNLOCK(p);
1099145256Sjkoshy
1100145256Sjkoshy	return 0;
1101145256Sjkoshy}
1102145256Sjkoshy
1103145256Sjkoshy/*
1104145256Sjkoshy * Detach a process and optionally its descendants from a PMC.
1105145256Sjkoshy */
1106145256Sjkoshy
1107145256Sjkoshystatic int
1108145256Sjkoshypmc_detach_process(struct proc *p, struct pmc *pm)
1109145256Sjkoshy{
1110145256Sjkoshy	struct proc *top;
1111145256Sjkoshy
1112145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1113145256Sjkoshy
1114145256Sjkoshy	PMCDBG(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1115145774Sjkoshy	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1116145256Sjkoshy
1117145256Sjkoshy	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1118145256Sjkoshy		return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1119145256Sjkoshy
1120145256Sjkoshy	/*
1121145256Sjkoshy	 * Traverse all children, detaching them from this PMC.  We
1122145256Sjkoshy	 * ignore errors since we could be detaching a PMC from a
1123145256Sjkoshy	 * partially attached proc tree.
1124145256Sjkoshy	 */
1125145256Sjkoshy
1126145256Sjkoshy	sx_slock(&proctree_lock);
1127145256Sjkoshy
1128145256Sjkoshy	top = p;
1129145256Sjkoshy
1130145256Sjkoshy	for (;;) {
1131145256Sjkoshy		(void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1132145256Sjkoshy
1133145256Sjkoshy		if (!LIST_EMPTY(&p->p_children))
1134145256Sjkoshy			p = LIST_FIRST(&p->p_children);
1135145256Sjkoshy		else for (;;) {
1136145256Sjkoshy			if (p == top)
1137145256Sjkoshy				goto done;
1138145256Sjkoshy			if (LIST_NEXT(p, p_sibling)) {
1139145256Sjkoshy				p = LIST_NEXT(p, p_sibling);
1140145256Sjkoshy				break;
1141145256Sjkoshy			}
1142145256Sjkoshy			p = p->p_pptr;
1143145256Sjkoshy		}
1144145256Sjkoshy	}
1145145256Sjkoshy
1146145256Sjkoshy done:
1147145256Sjkoshy	sx_sunlock(&proctree_lock);
1148147191Sjkoshy
1149147191Sjkoshy	if (LIST_EMPTY(&pm->pm_targets))
1150147191Sjkoshy		pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1151147191Sjkoshy
1152145256Sjkoshy	return 0;
1153145256Sjkoshy}
1154145256Sjkoshy
1155147191Sjkoshy
1156145256Sjkoshy/*
1157147191Sjkoshy * Thread context switch IN
1158145256Sjkoshy */
1159145256Sjkoshy
1160147191Sjkoshystatic void
1161147191Sjkoshypmc_process_csw_in(struct thread *td)
1162147191Sjkoshy{
1163147191Sjkoshy	int cpu;
1164147191Sjkoshy	unsigned int ri;
1165147191Sjkoshy	struct pmc *pm;
1166147191Sjkoshy	struct proc *p;
1167147191Sjkoshy	struct pmc_cpu *pc;
1168147191Sjkoshy	struct pmc_hw *phw;
1169147191Sjkoshy	struct pmc_process *pp;
1170147191Sjkoshy	pmc_value_t newvalue;
1171145256Sjkoshy
1172147191Sjkoshy	p = td->td_proc;
1173145256Sjkoshy
1174147191Sjkoshy	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1175147191Sjkoshy		return;
1176145256Sjkoshy
1177147191Sjkoshy	KASSERT(pp->pp_proc == td->td_proc,
1178147191Sjkoshy	    ("[pmc,%d] not my thread state", __LINE__));
1179145256Sjkoshy
1180147191Sjkoshy	critical_enter(); /* no preemption from this point */
1181145256Sjkoshy
1182147191Sjkoshy	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1183145256Sjkoshy
1184147191Sjkoshy	PMCDBG(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1185147191Sjkoshy	    p->p_pid, p->p_comm, pp);
1186145256Sjkoshy
1187183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1188147191Sjkoshy	    ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
1189145256Sjkoshy
1190147191Sjkoshy	pc = pmc_pcpu[cpu];
1191145256Sjkoshy
1192147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++) {
1193145256Sjkoshy
1194147191Sjkoshy		if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1195147191Sjkoshy			continue;
1196147191Sjkoshy
1197147191Sjkoshy		KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1198147191Sjkoshy		    ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1199147191Sjkoshy			__LINE__, PMC_TO_MODE(pm)));
1200147191Sjkoshy
1201147191Sjkoshy		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1202147191Sjkoshy		    ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1203147191Sjkoshy			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1204147191Sjkoshy
1205145256Sjkoshy		/*
1206147191Sjkoshy		 * Only PMCs that are marked as 'RUNNING' need
1207147191Sjkoshy		 * be placed on hardware.
1208145256Sjkoshy		 */
1209145256Sjkoshy
1210147191Sjkoshy		if (pm->pm_state != PMC_STATE_RUNNING)
1211147191Sjkoshy			continue;
1212145256Sjkoshy
1213147191Sjkoshy		/* increment PMC runcount */
1214147191Sjkoshy		atomic_add_rel_32(&pm->pm_runcount, 1);
1215145256Sjkoshy
1216147191Sjkoshy		/* configure the HWPMC we are going to use. */
1217147191Sjkoshy		md->pmd_config_pmc(cpu, ri, pm);
1218145256Sjkoshy
1219147191Sjkoshy		phw = pc->pc_hwpmcs[ri];
1220145256Sjkoshy
1221147191Sjkoshy		KASSERT(phw != NULL,
1222147191Sjkoshy		    ("[pmc,%d] null hw pointer", __LINE__));
1223145256Sjkoshy
1224147191Sjkoshy		KASSERT(phw->phw_pmc == pm,
1225147191Sjkoshy		    ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1226147191Sjkoshy			phw->phw_pmc, pm));
1227145256Sjkoshy
1228147191Sjkoshy		/*
1229147191Sjkoshy		 * Write out saved value and start the PMC.
1230147191Sjkoshy		 *
1231147191Sjkoshy		 * Sampling PMCs use a per-process value, while
1232147191Sjkoshy		 * counting mode PMCs use a per-pmc value that is
1233147191Sjkoshy		 * inherited across descendants.
1234147191Sjkoshy		 */
1235147191Sjkoshy		if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1236147191Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
1237147191Sjkoshy			newvalue = PMC_PCPU_SAVED(cpu,ri) =
1238147191Sjkoshy			    pp->pp_pmcs[ri].pp_pmcval;
1239147191Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1240147191Sjkoshy		} else {
1241147191Sjkoshy			KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1242147191Sjkoshy			    ("[pmc,%d] illegal mode=%d", __LINE__,
1243147191Sjkoshy			    PMC_TO_MODE(pm)));
1244147191Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
1245147191Sjkoshy			newvalue = PMC_PCPU_SAVED(cpu, ri) =
1246147191Sjkoshy			    pm->pm_gv.pm_savedvalue;
1247147191Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1248147191Sjkoshy		}
1249145256Sjkoshy
1250147191Sjkoshy		PMCDBG(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1251145256Sjkoshy
1252147191Sjkoshy		md->pmd_write_pmc(cpu, ri, newvalue);
1253147191Sjkoshy		md->pmd_start_pmc(cpu, ri);
1254147191Sjkoshy	}
1255145256Sjkoshy
1256147191Sjkoshy	/*
1257147191Sjkoshy	 * perform any other architecture/cpu dependent thread
1258147191Sjkoshy	 * switch-in actions.
1259147191Sjkoshy	 */
1260145256Sjkoshy
1261147191Sjkoshy	(void) (*md->pmd_switch_in)(pc, pp);
1262145256Sjkoshy
1263147191Sjkoshy	critical_exit();
1264145256Sjkoshy
1265147191Sjkoshy}
1266145256Sjkoshy
1267147191Sjkoshy/*
1268147191Sjkoshy * Thread context switch OUT.
1269147191Sjkoshy */
1270145256Sjkoshy
1271147191Sjkoshystatic void
1272147191Sjkoshypmc_process_csw_out(struct thread *td)
1273147191Sjkoshy{
1274147191Sjkoshy	int cpu;
1275147191Sjkoshy	enum pmc_mode mode;
1276147191Sjkoshy	unsigned int ri;
1277147191Sjkoshy	struct pmc *pm;
1278147191Sjkoshy	struct proc *p;
1279147191Sjkoshy	struct pmc_cpu *pc;
1280147191Sjkoshy	struct pmc_process *pp;
1281147191Sjkoshy	int64_t tmp;
1282147191Sjkoshy	pmc_value_t newvalue;
1283145256Sjkoshy
1284147191Sjkoshy	/*
1285147191Sjkoshy	 * Locate our process descriptor; this may be NULL if
1286147191Sjkoshy	 * this process is exiting and we have already removed
1287147191Sjkoshy	 * the process from the target process table.
1288147191Sjkoshy	 *
1289147191Sjkoshy	 * Note that due to kernel preemption, multiple
1290147191Sjkoshy	 * context switches may happen while the process is
1291147191Sjkoshy	 * exiting.
1292147191Sjkoshy	 *
1293147191Sjkoshy	 * Note also that if the target process cannot be
1294147191Sjkoshy	 * found we still need to deconfigure any PMCs that
1295147191Sjkoshy	 * are currently running on hardware.
1296147191Sjkoshy	 */
1297145256Sjkoshy
1298147191Sjkoshy	p = td->td_proc;
1299147191Sjkoshy	pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1300145256Sjkoshy
1301147191Sjkoshy	/*
1302147191Sjkoshy	 * save PMCs
1303147191Sjkoshy	 */
1304145256Sjkoshy
1305147191Sjkoshy	critical_enter();
1306145774Sjkoshy
1307147191Sjkoshy	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1308145256Sjkoshy
1309147191Sjkoshy	PMCDBG(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1310147191Sjkoshy	    p->p_pid, p->p_comm, pp);
1311145615Sjkoshy
1312183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1313147191Sjkoshy	    ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1314145615Sjkoshy
1315147191Sjkoshy	pc = pmc_pcpu[cpu];
1316145615Sjkoshy
1317147191Sjkoshy	/*
1318147191Sjkoshy	 * When a PMC gets unlinked from a target PMC, it will
1319147191Sjkoshy	 * be removed from the target's pp_pmc[] array.
1320147191Sjkoshy	 *
1321147191Sjkoshy	 * However, on a MP system, the target could have been
1322147191Sjkoshy	 * executing on another CPU at the time of the unlink.
1323147191Sjkoshy	 * So, at context switch OUT time, we need to look at
1324147191Sjkoshy	 * the hardware to determine if a PMC is scheduled on
1325147191Sjkoshy	 * it.
1326147191Sjkoshy	 */
1327145256Sjkoshy
1328147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++) {
1329145256Sjkoshy
1330147191Sjkoshy		pm = NULL;
1331147191Sjkoshy		(void) (*md->pmd_get_config)(cpu, ri, &pm);
1332145256Sjkoshy
1333147191Sjkoshy		if (pm == NULL)	/* nothing at this row index */
1334147191Sjkoshy			continue;
1335145256Sjkoshy
1336147191Sjkoshy		mode = PMC_TO_MODE(pm);
1337147191Sjkoshy		if (!PMC_IS_VIRTUAL_MODE(mode))
1338147191Sjkoshy			continue; /* not a process virtual PMC */
1339145774Sjkoshy
1340147191Sjkoshy		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1341147191Sjkoshy		    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1342147191Sjkoshy			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1343145256Sjkoshy
1344147191Sjkoshy		/* Stop hardware if not already stopped */
1345147867Sjkoshy		if (pm->pm_stalled == 0)
1346147191Sjkoshy			md->pmd_stop_pmc(cpu, ri);
1347147191Sjkoshy
1348147191Sjkoshy		/* reduce this PMC's runcount */
1349147191Sjkoshy		atomic_subtract_rel_32(&pm->pm_runcount, 1);
1350147191Sjkoshy
1351145256Sjkoshy		/*
1352147191Sjkoshy		 * If this PMC is associated with this process,
1353147191Sjkoshy		 * save the reading.
1354145256Sjkoshy		 */
1355145256Sjkoshy
1356147191Sjkoshy		if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1357147191Sjkoshy
1358147191Sjkoshy			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1359147191Sjkoshy			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1360147191Sjkoshy				pm, ri, pp->pp_pmcs[ri].pp_pmc));
1361147191Sjkoshy
1362147191Sjkoshy			KASSERT(pp->pp_refcnt > 0,
1363147191Sjkoshy			    ("[pmc,%d] pp refcnt = %d", __LINE__,
1364147191Sjkoshy				pp->pp_refcnt));
1365147191Sjkoshy
1366147191Sjkoshy			md->pmd_read_pmc(cpu, ri, &newvalue);
1367147191Sjkoshy
1368147191Sjkoshy			tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1369147191Sjkoshy
1370147191Sjkoshy			PMCDBG(CSW,SWI,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
1371147191Sjkoshy			    tmp);
1372147191Sjkoshy
1373147191Sjkoshy			if (mode == PMC_MODE_TS) {
1374147191Sjkoshy
1375147191Sjkoshy				/*
1376147191Sjkoshy				 * For sampling process-virtual PMCs,
1377147191Sjkoshy				 * we expect the count to be
1378147191Sjkoshy				 * decreasing as the 'value'
1379147191Sjkoshy				 * programmed into the PMC is the
1380147191Sjkoshy				 * number of events to be seen till
1381147191Sjkoshy				 * the next sampling interrupt.
1382147191Sjkoshy				 */
1383147191Sjkoshy				if (tmp < 0)
1384147191Sjkoshy					tmp += pm->pm_sc.pm_reloadcount;
1385147191Sjkoshy				mtx_pool_lock_spin(pmc_mtxpool, pm);
1386147191Sjkoshy				pp->pp_pmcs[ri].pp_pmcval -= tmp;
1387147191Sjkoshy				if ((int64_t) pp->pp_pmcs[ri].pp_pmcval < 0)
1388147191Sjkoshy					pp->pp_pmcs[ri].pp_pmcval +=
1389147191Sjkoshy					    pm->pm_sc.pm_reloadcount;
1390147191Sjkoshy				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1391147191Sjkoshy
1392147191Sjkoshy			} else {
1393147191Sjkoshy
1394147191Sjkoshy				/*
1395147191Sjkoshy				 * For counting process-virtual PMCs,
1396147191Sjkoshy				 * we expect the count to be
1397147191Sjkoshy				 * increasing monotonically, modulo a 64
1398147191Sjkoshy				 * bit wraparound.
1399147191Sjkoshy				 */
1400147191Sjkoshy				KASSERT((int64_t) tmp >= 0,
1401147191Sjkoshy				    ("[pmc,%d] negative increment cpu=%d "
1402147191Sjkoshy				     "ri=%d newvalue=%jx saved=%jx "
1403147191Sjkoshy				     "incr=%jx", __LINE__, cpu, ri,
1404147191Sjkoshy				     newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1405147191Sjkoshy
1406147191Sjkoshy				mtx_pool_lock_spin(pmc_mtxpool, pm);
1407147191Sjkoshy				pm->pm_gv.pm_savedvalue += tmp;
1408147191Sjkoshy				pp->pp_pmcs[ri].pp_pmcval += tmp;
1409147191Sjkoshy				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1410147191Sjkoshy
1411147191Sjkoshy				if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1412147191Sjkoshy					pmclog_process_proccsw(pm, pp, tmp);
1413147191Sjkoshy			}
1414145256Sjkoshy		}
1415145256Sjkoshy
1416147191Sjkoshy		/* mark hardware as free */
1417147191Sjkoshy		md->pmd_config_pmc(cpu, ri, NULL);
1418145256Sjkoshy	}
1419145256Sjkoshy
1420145256Sjkoshy	/*
1421147191Sjkoshy	 * perform any other architecture/cpu dependent thread
1422147191Sjkoshy	 * switch out functions.
1423147191Sjkoshy	 */
1424147191Sjkoshy
1425147191Sjkoshy	(void) (*md->pmd_switch_out)(pc, pp);
1426147191Sjkoshy
1427147191Sjkoshy	critical_exit();
1428147191Sjkoshy}
1429147191Sjkoshy
1430147191Sjkoshy/*
1431157144Sjkoshy * Log a KLD operation.
1432157144Sjkoshy */
1433157144Sjkoshy
1434157144Sjkoshystatic void
1435157144Sjkoshypmc_process_kld_load(struct pmckern_map_in *pkm)
1436157144Sjkoshy{
1437157144Sjkoshy	struct pmc_owner *po;
1438157144Sjkoshy
1439157144Sjkoshy	sx_assert(&pmc_sx, SX_LOCKED);
1440157144Sjkoshy
1441157144Sjkoshy	/*
1442157144Sjkoshy	 * Notify owners of system sampling PMCs about KLD operations.
1443157144Sjkoshy	 */
1444157144Sjkoshy
1445157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1446157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1447157144Sjkoshy	    	pmclog_process_map_in(po, (pid_t) -1, pkm->pm_address,
1448157144Sjkoshy		    (char *) pkm->pm_file);
1449157144Sjkoshy
1450157144Sjkoshy	/*
1451157144Sjkoshy	 * TODO: Notify owners of (all) process-sampling PMCs too.
1452157144Sjkoshy	 */
1453157144Sjkoshy
1454157144Sjkoshy	return;
1455157144Sjkoshy}
1456157144Sjkoshy
1457157144Sjkoshystatic void
1458157144Sjkoshypmc_process_kld_unload(struct pmckern_map_out *pkm)
1459157144Sjkoshy{
1460157144Sjkoshy	struct pmc_owner *po;
1461157144Sjkoshy
1462157144Sjkoshy	sx_assert(&pmc_sx, SX_LOCKED);
1463157144Sjkoshy
1464157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1465157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1466157144Sjkoshy		pmclog_process_map_out(po, (pid_t) -1,
1467157144Sjkoshy		    pkm->pm_address, pkm->pm_address + pkm->pm_size);
1468174395Sjkoshy
1469157144Sjkoshy	/*
1470157144Sjkoshy	 * TODO: Notify owners of process-sampling PMCs.
1471157144Sjkoshy	 */
1472157144Sjkoshy}
1473157144Sjkoshy
1474157144Sjkoshy/*
1475157144Sjkoshy * A mapping change for a process.
1476157144Sjkoshy */
1477157144Sjkoshy
1478157144Sjkoshystatic void
1479157144Sjkoshypmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1480157144Sjkoshy{
1481157144Sjkoshy	int ri;
1482157144Sjkoshy	pid_t pid;
1483157144Sjkoshy	char *fullpath, *freepath;
1484157144Sjkoshy	const struct pmc *pm;
1485157144Sjkoshy	struct pmc_owner *po;
1486157144Sjkoshy	const struct pmc_process *pp;
1487157144Sjkoshy
1488157144Sjkoshy	freepath = fullpath = NULL;
1489157144Sjkoshy	pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1490157144Sjkoshy
1491157144Sjkoshy	pid = td->td_proc->p_pid;
1492157144Sjkoshy
1493157144Sjkoshy	/* Inform owners of all system-wide sampling PMCs. */
1494157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1495157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1496157144Sjkoshy		pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1497157144Sjkoshy
1498157144Sjkoshy	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1499157144Sjkoshy		goto done;
1500157144Sjkoshy
1501157144Sjkoshy	/*
1502157144Sjkoshy	 * Inform sampling PMC owners tracking this process.
1503157144Sjkoshy	 */
1504157144Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
1505157144Sjkoshy		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1506157144Sjkoshy		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1507157144Sjkoshy			pmclog_process_map_in(pm->pm_owner,
1508157144Sjkoshy			    pid, pkm->pm_address, fullpath);
1509157144Sjkoshy
1510157144Sjkoshy  done:
1511157144Sjkoshy	if (freepath)
1512184205Sdes		free(freepath, M_TEMP);
1513157144Sjkoshy}
1514157144Sjkoshy
1515157144Sjkoshy
1516157144Sjkoshy/*
1517157144Sjkoshy * Log an munmap request.
1518157144Sjkoshy */
1519157144Sjkoshy
1520157144Sjkoshystatic void
1521157144Sjkoshypmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1522157144Sjkoshy{
1523157144Sjkoshy	int ri;
1524157144Sjkoshy	pid_t pid;
1525157144Sjkoshy	struct pmc_owner *po;
1526157144Sjkoshy	const struct pmc *pm;
1527157144Sjkoshy	const struct pmc_process *pp;
1528157144Sjkoshy
1529157144Sjkoshy	pid = td->td_proc->p_pid;
1530157144Sjkoshy
1531157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1532157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1533157144Sjkoshy		pmclog_process_map_out(po, pid, pkm->pm_address,
1534157144Sjkoshy		    pkm->pm_address + pkm->pm_size);
1535157144Sjkoshy
1536157144Sjkoshy	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1537157144Sjkoshy		return;
1538157144Sjkoshy
1539157144Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
1540157144Sjkoshy		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1541157144Sjkoshy		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1542157651Sjkoshy			pmclog_process_map_out(pm->pm_owner, pid,
1543157651Sjkoshy			    pkm->pm_address, pkm->pm_address + pkm->pm_size);
1544157144Sjkoshy}
1545157144Sjkoshy
1546157144Sjkoshy/*
1547174395Sjkoshy * Log mapping information about the kernel.
1548174395Sjkoshy */
1549174395Sjkoshy
1550174395Sjkoshystatic void
1551174395Sjkoshypmc_log_kernel_mappings(struct pmc *pm)
1552174395Sjkoshy{
1553174395Sjkoshy	struct pmc_owner *po;
1554174395Sjkoshy	struct pmckern_map_in *km, *kmbase;
1555174395Sjkoshy
1556174395Sjkoshy	sx_assert(&pmc_sx, SX_LOCKED);
1557174395Sjkoshy	KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1558174395Sjkoshy	    ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1559174395Sjkoshy		__LINE__, (void *) pm));
1560174395Sjkoshy
1561174395Sjkoshy	po = pm->pm_owner;
1562174395Sjkoshy
1563174395Sjkoshy	if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1564174395Sjkoshy		return;
1565174395Sjkoshy
1566174395Sjkoshy	/*
1567174395Sjkoshy	 * Log the current set of kernel modules.
1568174395Sjkoshy	 */
1569174395Sjkoshy	kmbase = linker_hwpmc_list_objects();
1570174395Sjkoshy	for (km = kmbase; km->pm_file != NULL; km++) {
1571174395Sjkoshy		PMCDBG(LOG,REG,1,"%s %p", (char *) km->pm_file,
1572174395Sjkoshy		    (void *) km->pm_address);
1573174395Sjkoshy		pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1574174395Sjkoshy		    km->pm_file);
1575174395Sjkoshy	}
1576184205Sdes	free(kmbase, M_LINKER);
1577174395Sjkoshy
1578174395Sjkoshy	po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1579174395Sjkoshy}
1580174395Sjkoshy
1581174395Sjkoshy/*
1582174395Sjkoshy * Log the mappings for a single process.
1583174395Sjkoshy */
1584174395Sjkoshy
1585174395Sjkoshystatic void
1586174395Sjkoshypmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1587174395Sjkoshy{
1588174395Sjkoshy}
1589174395Sjkoshy
1590174395Sjkoshy/*
1591174395Sjkoshy * Log mappings for all processes in the system.
1592174395Sjkoshy */
1593174395Sjkoshy
1594174395Sjkoshystatic void
1595174395Sjkoshypmc_log_all_process_mappings(struct pmc_owner *po)
1596174395Sjkoshy{
1597174395Sjkoshy	struct proc *p, *top;
1598174395Sjkoshy
1599174395Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1600174395Sjkoshy
1601174395Sjkoshy	if ((p = pfind(1)) == NULL)
1602174395Sjkoshy		panic("[pmc,%d] Cannot find init", __LINE__);
1603174395Sjkoshy
1604174395Sjkoshy	PROC_UNLOCK(p);
1605174395Sjkoshy
1606174395Sjkoshy	sx_slock(&proctree_lock);
1607174395Sjkoshy
1608174395Sjkoshy	top = p;
1609174395Sjkoshy
1610174395Sjkoshy	for (;;) {
1611174395Sjkoshy		pmc_log_process_mappings(po, p);
1612174395Sjkoshy		if (!LIST_EMPTY(&p->p_children))
1613174395Sjkoshy			p = LIST_FIRST(&p->p_children);
1614174395Sjkoshy		else for (;;) {
1615174395Sjkoshy			if (p == top)
1616174395Sjkoshy				goto done;
1617174395Sjkoshy			if (LIST_NEXT(p, p_sibling)) {
1618174395Sjkoshy				p = LIST_NEXT(p, p_sibling);
1619174395Sjkoshy				break;
1620174395Sjkoshy			}
1621174395Sjkoshy			p = p->p_pptr;
1622174395Sjkoshy		}
1623174395Sjkoshy	}
1624174395Sjkoshy done:
1625174395Sjkoshy	sx_sunlock(&proctree_lock);
1626174395Sjkoshy}
1627174395Sjkoshy
1628174395Sjkoshy/*
1629147191Sjkoshy * The 'hook' invoked from the kernel proper
1630147191Sjkoshy */
1631147191Sjkoshy
1632147191Sjkoshy
1633153110Sru#ifdef	DEBUG
1634147191Sjkoshyconst char *pmc_hooknames[] = {
1635157144Sjkoshy	/* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1636147191Sjkoshy	"",
1637147191Sjkoshy	"EXEC",
1638147191Sjkoshy	"CSW-IN",
1639147191Sjkoshy	"CSW-OUT",
1640157144Sjkoshy	"SAMPLE",
1641157144Sjkoshy	"KLDLOAD",
1642157144Sjkoshy	"KLDUNLOAD",
1643157144Sjkoshy	"MMAP",
1644174395Sjkoshy	"MUNMAP",
1645174395Sjkoshy	"CALLCHAIN"
1646147191Sjkoshy};
1647147191Sjkoshy#endif
1648147191Sjkoshy
1649147191Sjkoshystatic int
1650147191Sjkoshypmc_hook_handler(struct thread *td, int function, void *arg)
1651147191Sjkoshy{
1652147191Sjkoshy
1653147191Sjkoshy	PMCDBG(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1654147191Sjkoshy	    pmc_hooknames[function], arg);
1655147191Sjkoshy
1656147191Sjkoshy	switch (function)
1657147191Sjkoshy	{
1658147191Sjkoshy
1659147191Sjkoshy	/*
1660145256Sjkoshy	 * Process exec()
1661145256Sjkoshy	 */
1662145256Sjkoshy
1663145256Sjkoshy	case PMC_FN_PROCESS_EXEC:
1664145256Sjkoshy	{
1665147191Sjkoshy		char *fullpath, *freepath;
1666145256Sjkoshy		unsigned int ri;
1667147191Sjkoshy		int is_using_hwpmcs;
1668145256Sjkoshy		struct pmc *pm;
1669145256Sjkoshy		struct proc *p;
1670145256Sjkoshy		struct pmc_owner *po;
1671145256Sjkoshy		struct pmc_process *pp;
1672147708Sjkoshy		struct pmckern_procexec *pk;
1673145256Sjkoshy
1674145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
1675145256Sjkoshy
1676147191Sjkoshy		p = td->td_proc;
1677147708Sjkoshy		pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1678147191Sjkoshy
1679147708Sjkoshy		pk = (struct pmckern_procexec *) arg;
1680147708Sjkoshy
1681147191Sjkoshy		/* Inform owners of SS mode PMCs of the exec event. */
1682147191Sjkoshy		LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1683147191Sjkoshy		    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1684147708Sjkoshy			    pmclog_process_procexec(po, PMC_ID_INVALID,
1685147708Sjkoshy				p->p_pid, pk->pm_entryaddr, fullpath);
1686147191Sjkoshy
1687147191Sjkoshy		PROC_LOCK(p);
1688147191Sjkoshy		is_using_hwpmcs = p->p_flag & P_HWPMC;
1689147191Sjkoshy		PROC_UNLOCK(p);
1690147191Sjkoshy
1691147191Sjkoshy		if (!is_using_hwpmcs) {
1692147191Sjkoshy			if (freepath)
1693184205Sdes				free(freepath, M_TEMP);
1694147191Sjkoshy			break;
1695147191Sjkoshy		}
1696147191Sjkoshy
1697145256Sjkoshy		/*
1698145256Sjkoshy		 * PMCs are not inherited across an exec():  remove any
1699145256Sjkoshy		 * PMCs that this process is the owner of.
1700145256Sjkoshy		 */
1701145256Sjkoshy
1702145256Sjkoshy		if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1703145256Sjkoshy			pmc_remove_owner(po);
1704147191Sjkoshy			pmc_destroy_owner_descriptor(po);
1705145256Sjkoshy		}
1706145256Sjkoshy
1707145256Sjkoshy		/*
1708154483Sjkoshy		 * If the process being exec'ed is not the target of any
1709154483Sjkoshy		 * PMC, we are done.
1710145256Sjkoshy		 */
1711154483Sjkoshy		if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1712154483Sjkoshy			if (freepath)
1713184205Sdes				free(freepath, M_TEMP);
1714145256Sjkoshy			break;
1715154483Sjkoshy		}
1716145256Sjkoshy
1717147191Sjkoshy		/*
1718147191Sjkoshy		 * Log the exec event to all monitoring owners.  Skip
1719147191Sjkoshy		 * owners who have already recieved the event because
1720154483Sjkoshy		 * they had system sampling PMCs active.
1721147191Sjkoshy		 */
1722147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
1723147191Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1724147191Sjkoshy				po = pm->pm_owner;
1725147191Sjkoshy				if (po->po_sscount == 0 &&
1726147191Sjkoshy				    po->po_flags & PMC_PO_OWNS_LOGFILE)
1727147708Sjkoshy					pmclog_process_procexec(po, pm->pm_id,
1728147708Sjkoshy					    p->p_pid, pk->pm_entryaddr,
1729147191Sjkoshy					    fullpath);
1730147191Sjkoshy			}
1731147191Sjkoshy
1732147191Sjkoshy		if (freepath)
1733184205Sdes			free(freepath, M_TEMP);
1734147191Sjkoshy
1735145256Sjkoshy
1736145256Sjkoshy		PMCDBG(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1737147708Sjkoshy		    p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1738145256Sjkoshy
1739147708Sjkoshy		if (pk->pm_credentialschanged == 0) /* no change */
1740145256Sjkoshy			break;
1741145256Sjkoshy
1742145256Sjkoshy		/*
1743145256Sjkoshy		 * If the newly exec()'ed process has a different credential
1744145256Sjkoshy		 * than before, allow it to be the target of a PMC only if
1745145256Sjkoshy		 * the PMC's owner has sufficient priviledge.
1746145256Sjkoshy		 */
1747145256Sjkoshy
1748145256Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
1749145256Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1750145256Sjkoshy				if (pmc_can_attach(pm, td->td_proc) != 0)
1751145256Sjkoshy					pmc_detach_one_process(td->td_proc,
1752145256Sjkoshy					    pm, PMC_FLAG_NONE);
1753145256Sjkoshy
1754145256Sjkoshy		KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1755145256Sjkoshy		    ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1756145256Sjkoshy			pp->pp_refcnt, pp));
1757145256Sjkoshy
1758145256Sjkoshy		/*
1759145256Sjkoshy		 * If this process is no longer the target of any
1760145256Sjkoshy		 * PMCs, we can remove the process entry and free
1761145256Sjkoshy		 * up space.
1762145256Sjkoshy		 */
1763145256Sjkoshy
1764145256Sjkoshy		if (pp->pp_refcnt == 0) {
1765145256Sjkoshy			pmc_remove_process_descriptor(pp);
1766184205Sdes			free(pp, M_PMC);
1767147191Sjkoshy			break;
1768145256Sjkoshy		}
1769145256Sjkoshy
1770145256Sjkoshy	}
1771145256Sjkoshy	break;
1772145256Sjkoshy
1773145256Sjkoshy	case PMC_FN_CSW_IN:
1774147191Sjkoshy		pmc_process_csw_in(td);
1775147191Sjkoshy		break;
1776145256Sjkoshy
1777147191Sjkoshy	case PMC_FN_CSW_OUT:
1778147191Sjkoshy		pmc_process_csw_out(td);
1779147191Sjkoshy		break;
1780145256Sjkoshy
1781145256Sjkoshy	/*
1782147191Sjkoshy	 * Process accumulated PC samples.
1783147191Sjkoshy	 *
1784147191Sjkoshy	 * This function is expected to be called by hardclock() for
1785147191Sjkoshy	 * each CPU that has accumulated PC samples.
1786147191Sjkoshy	 *
1787147191Sjkoshy	 * This function is to be executed on the CPU whose samples
1788147191Sjkoshy	 * are being processed.
1789145256Sjkoshy	 */
1790147191Sjkoshy	case PMC_FN_DO_SAMPLES:
1791145256Sjkoshy
1792145256Sjkoshy		/*
1793147191Sjkoshy		 * Clear the cpu specific bit in the CPU mask before
1794147191Sjkoshy		 * do the rest of the processing.  If the NMI handler
1795147191Sjkoshy		 * gets invoked after the "atomic_clear_int()" call
1796147191Sjkoshy		 * below but before "pmc_process_samples()" gets
1797147191Sjkoshy		 * around to processing the interrupt, then we will
1798147191Sjkoshy		 * come back here at the next hardclock() tick (and
1799147191Sjkoshy		 * may find nothing to do if "pmc_process_samples()"
1800147191Sjkoshy		 * had already processed the interrupt).  We don't
1801147191Sjkoshy		 * lose the interrupt sample.
1802145256Sjkoshy		 */
1803147191Sjkoshy		atomic_clear_int(&pmc_cpumask, (1 << PCPU_GET(cpuid)));
1804147191Sjkoshy		pmc_process_samples(PCPU_GET(cpuid));
1805147191Sjkoshy		break;
1806145256Sjkoshy
1807157144Sjkoshy
1808157144Sjkoshy	case PMC_FN_KLD_LOAD:
1809157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
1810157144Sjkoshy		pmc_process_kld_load((struct pmckern_map_in *) arg);
1811157144Sjkoshy		break;
1812157144Sjkoshy
1813157144Sjkoshy	case PMC_FN_KLD_UNLOAD:
1814157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
1815157144Sjkoshy		pmc_process_kld_unload((struct pmckern_map_out *) arg);
1816157144Sjkoshy		break;
1817157144Sjkoshy
1818157144Sjkoshy	case PMC_FN_MMAP:
1819157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
1820157144Sjkoshy		pmc_process_mmap(td, (struct pmckern_map_in *) arg);
1821157144Sjkoshy		break;
1822157144Sjkoshy
1823157144Sjkoshy	case PMC_FN_MUNMAP:
1824157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
1825157144Sjkoshy		pmc_process_munmap(td, (struct pmckern_map_out *) arg);
1826157144Sjkoshy		break;
1827157144Sjkoshy
1828174395Sjkoshy	case PMC_FN_USER_CALLCHAIN:
1829174395Sjkoshy		/*
1830174395Sjkoshy		 * Record a call chain.
1831174395Sjkoshy		 */
1832174395Sjkoshy		pmc_capture_user_callchain(PCPU_GET(cpuid),
1833174395Sjkoshy		    (struct trapframe *) arg);
1834174395Sjkoshy		break;
1835174395Sjkoshy
1836145256Sjkoshy	default:
1837153110Sru#ifdef	DEBUG
1838145256Sjkoshy		KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
1839145256Sjkoshy#endif
1840145256Sjkoshy		break;
1841145256Sjkoshy
1842145256Sjkoshy	}
1843145256Sjkoshy
1844145256Sjkoshy	return 0;
1845145256Sjkoshy}
1846145256Sjkoshy
1847145256Sjkoshy/*
1848145256Sjkoshy * allocate a 'struct pmc_owner' descriptor in the owner hash table.
1849145256Sjkoshy */
1850145256Sjkoshy
1851145256Sjkoshystatic struct pmc_owner *
1852145256Sjkoshypmc_allocate_owner_descriptor(struct proc *p)
1853145256Sjkoshy{
1854145256Sjkoshy	uint32_t hindex;
1855145256Sjkoshy	struct pmc_owner *po;
1856145256Sjkoshy	struct pmc_ownerhash *poh;
1857145256Sjkoshy
1858145256Sjkoshy	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1859145256Sjkoshy	poh = &pmc_ownerhash[hindex];
1860145256Sjkoshy
1861145256Sjkoshy	/* allocate space for N pointers and one descriptor struct */
1862184214Sdes	po = malloc(sizeof(struct pmc_owner), M_PMC, M_ZERO|M_WAITOK);
1863145256Sjkoshy
1864147191Sjkoshy	po->po_sscount = po->po_error = po->po_flags = 0;
1865147191Sjkoshy	po->po_file  = NULL;
1866145256Sjkoshy	po->po_owner = p;
1867147191Sjkoshy	po->po_kthread = NULL;
1868145256Sjkoshy	LIST_INIT(&po->po_pmcs);
1869145256Sjkoshy	LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
1870145256Sjkoshy
1871147191Sjkoshy	TAILQ_INIT(&po->po_logbuffers);
1872168856Sjkoshy	mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
1873147191Sjkoshy
1874145256Sjkoshy	PMCDBG(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
1875145256Sjkoshy	    p, p->p_pid, p->p_comm, po);
1876145256Sjkoshy
1877145256Sjkoshy	return po;
1878145256Sjkoshy}
1879145256Sjkoshy
1880147191Sjkoshystatic void
1881147191Sjkoshypmc_destroy_owner_descriptor(struct pmc_owner *po)
1882147191Sjkoshy{
1883147191Sjkoshy
1884147191Sjkoshy	PMCDBG(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
1885147191Sjkoshy	    po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
1886147191Sjkoshy
1887147191Sjkoshy	mtx_destroy(&po->po_mtx);
1888184205Sdes	free(po, M_PMC);
1889147191Sjkoshy}
1890147191Sjkoshy
1891145256Sjkoshy/*
1892145256Sjkoshy * find the descriptor corresponding to process 'p', adding or removing it
1893145256Sjkoshy * as specified by 'mode'.
1894145256Sjkoshy */
1895145256Sjkoshy
1896145256Sjkoshystatic struct pmc_process *
1897145256Sjkoshypmc_find_process_descriptor(struct proc *p, uint32_t mode)
1898145256Sjkoshy{
1899145256Sjkoshy	uint32_t hindex;
1900145256Sjkoshy	struct pmc_process *pp, *ppnew;
1901145256Sjkoshy	struct pmc_processhash *pph;
1902145256Sjkoshy
1903145256Sjkoshy	hindex = PMC_HASH_PTR(p, pmc_processhashmask);
1904145256Sjkoshy	pph = &pmc_processhash[hindex];
1905145256Sjkoshy
1906145256Sjkoshy	ppnew = NULL;
1907145256Sjkoshy
1908145256Sjkoshy	/*
1909145256Sjkoshy	 * Pre-allocate memory in the FIND_ALLOCATE case since we
1910145256Sjkoshy	 * cannot call malloc(9) once we hold a spin lock.
1911145256Sjkoshy	 */
1912145256Sjkoshy
1913145256Sjkoshy	if (mode & PMC_FLAG_ALLOCATE) {
1914145256Sjkoshy		/* allocate additional space for 'n' pmc pointers */
1915184214Sdes		ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
1916145256Sjkoshy		    sizeof(struct pmc_targetstate), M_PMC, M_ZERO|M_WAITOK);
1917145256Sjkoshy	}
1918145256Sjkoshy
1919145256Sjkoshy	mtx_lock_spin(&pmc_processhash_mtx);
1920145256Sjkoshy	LIST_FOREACH(pp, pph, pp_next)
1921145256Sjkoshy	    if (pp->pp_proc == p)
1922145256Sjkoshy		    break;
1923145256Sjkoshy
1924145256Sjkoshy	if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
1925145256Sjkoshy		LIST_REMOVE(pp, pp_next);
1926145256Sjkoshy
1927145256Sjkoshy	if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
1928145256Sjkoshy	    ppnew != NULL) {
1929145256Sjkoshy		ppnew->pp_proc = p;
1930145256Sjkoshy		LIST_INSERT_HEAD(pph, ppnew, pp_next);
1931145256Sjkoshy		pp = ppnew;
1932145256Sjkoshy		ppnew = NULL;
1933145256Sjkoshy	}
1934145256Sjkoshy	mtx_unlock_spin(&pmc_processhash_mtx);
1935145256Sjkoshy
1936145256Sjkoshy	if (pp != NULL && ppnew != NULL)
1937184205Sdes		free(ppnew, M_PMC);
1938145256Sjkoshy
1939145256Sjkoshy	return pp;
1940145256Sjkoshy}
1941145256Sjkoshy
1942145256Sjkoshy/*
1943145256Sjkoshy * remove a process descriptor from the process hash table.
1944145256Sjkoshy */
1945145256Sjkoshy
1946145256Sjkoshystatic void
1947145256Sjkoshypmc_remove_process_descriptor(struct pmc_process *pp)
1948145256Sjkoshy{
1949145256Sjkoshy	KASSERT(pp->pp_refcnt == 0,
1950145256Sjkoshy	    ("[pmc,%d] Removing process descriptor %p with count %d",
1951145256Sjkoshy		__LINE__, pp, pp->pp_refcnt));
1952145256Sjkoshy
1953145256Sjkoshy	mtx_lock_spin(&pmc_processhash_mtx);
1954145256Sjkoshy	LIST_REMOVE(pp, pp_next);
1955145256Sjkoshy	mtx_unlock_spin(&pmc_processhash_mtx);
1956145256Sjkoshy}
1957145256Sjkoshy
1958145256Sjkoshy
1959145256Sjkoshy/*
1960145256Sjkoshy * find an owner descriptor corresponding to proc 'p'
1961145256Sjkoshy */
1962145256Sjkoshy
1963145256Sjkoshystatic struct pmc_owner *
1964145256Sjkoshypmc_find_owner_descriptor(struct proc *p)
1965145256Sjkoshy{
1966145256Sjkoshy	uint32_t hindex;
1967145256Sjkoshy	struct pmc_owner *po;
1968145256Sjkoshy	struct pmc_ownerhash *poh;
1969145256Sjkoshy
1970145256Sjkoshy	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1971145256Sjkoshy	poh = &pmc_ownerhash[hindex];
1972145256Sjkoshy
1973145256Sjkoshy	po = NULL;
1974145256Sjkoshy	LIST_FOREACH(po, poh, po_next)
1975145256Sjkoshy	    if (po->po_owner == p)
1976145256Sjkoshy		    break;
1977145256Sjkoshy
1978145256Sjkoshy	PMCDBG(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
1979145256Sjkoshy	    "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
1980145256Sjkoshy
1981145256Sjkoshy	return po;
1982145256Sjkoshy}
1983145256Sjkoshy
1984145256Sjkoshy/*
1985145256Sjkoshy * pmc_allocate_pmc_descriptor
1986145256Sjkoshy *
1987145256Sjkoshy * Allocate a pmc descriptor and initialize its
1988145256Sjkoshy * fields.
1989145256Sjkoshy */
1990145256Sjkoshy
1991145256Sjkoshystatic struct pmc *
1992145256Sjkoshypmc_allocate_pmc_descriptor(void)
1993145256Sjkoshy{
1994145256Sjkoshy	struct pmc *pmc;
1995145256Sjkoshy
1996184205Sdes	pmc = malloc(sizeof(struct pmc), M_PMC, M_ZERO|M_WAITOK);
1997145256Sjkoshy
1998145256Sjkoshy	if (pmc != NULL) {
1999145256Sjkoshy		pmc->pm_owner = NULL;
2000145256Sjkoshy		LIST_INIT(&pmc->pm_targets);
2001145256Sjkoshy	}
2002145256Sjkoshy
2003145256Sjkoshy	PMCDBG(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2004145256Sjkoshy
2005145256Sjkoshy	return pmc;
2006145256Sjkoshy}
2007145256Sjkoshy
2008145256Sjkoshy/*
2009145256Sjkoshy * Destroy a pmc descriptor.
2010145256Sjkoshy */
2011145256Sjkoshy
2012145256Sjkoshystatic void
2013145256Sjkoshypmc_destroy_pmc_descriptor(struct pmc *pm)
2014145256Sjkoshy{
2015145256Sjkoshy	(void) pm;
2016145256Sjkoshy
2017153110Sru#ifdef	DEBUG
2018145256Sjkoshy	KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2019145256Sjkoshy	    pm->pm_state == PMC_STATE_FREE,
2020145256Sjkoshy	    ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2021145256Sjkoshy	KASSERT(LIST_EMPTY(&pm->pm_targets),
2022145256Sjkoshy	    ("[pmc,%d] destroying pmc with targets", __LINE__));
2023145256Sjkoshy	KASSERT(pm->pm_owner == NULL,
2024145256Sjkoshy	    ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2025145256Sjkoshy	KASSERT(pm->pm_runcount == 0,
2026145256Sjkoshy	    ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
2027145256Sjkoshy		pm->pm_runcount));
2028145256Sjkoshy#endif
2029145256Sjkoshy}
2030145256Sjkoshy
2031147191Sjkoshystatic void
2032147191Sjkoshypmc_wait_for_pmc_idle(struct pmc *pm)
2033147191Sjkoshy{
2034153110Sru#ifdef	DEBUG
2035147191Sjkoshy	volatile int maxloop;
2036147191Sjkoshy
2037183266Sjkoshy	maxloop = 100 * pmc_cpu_max();
2038147191Sjkoshy#endif
2039147191Sjkoshy
2040147191Sjkoshy	/*
2041147191Sjkoshy	 * Loop (with a forced context switch) till the PMC's runcount
2042147191Sjkoshy	 * comes down to zero.
2043147191Sjkoshy	 */
2044147191Sjkoshy	while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
2045153110Sru#ifdef	DEBUG
2046147191Sjkoshy		maxloop--;
2047147191Sjkoshy		KASSERT(maxloop > 0,
2048147191Sjkoshy		    ("[pmc,%d] (ri%d, rc%d) waiting too long for "
2049147191Sjkoshy			"pmc to be free", __LINE__,
2050147191Sjkoshy			PMC_TO_ROWINDEX(pm), pm->pm_runcount));
2051147191Sjkoshy#endif
2052147191Sjkoshy		pmc_force_context_switch();
2053147191Sjkoshy	}
2054147191Sjkoshy}
2055147191Sjkoshy
2056145256Sjkoshy/*
2057145256Sjkoshy * This function does the following things:
2058145256Sjkoshy *
2059145256Sjkoshy *  - detaches the PMC from hardware
2060145256Sjkoshy *  - unlinks all target threads that were attached to it
2061145256Sjkoshy *  - removes the PMC from its owner's list
2062145256Sjkoshy *  - destroy's the PMC private mutex
2063145256Sjkoshy *
2064145256Sjkoshy * Once this function completes, the given pmc pointer can be safely
2065145256Sjkoshy * FREE'd by the caller.
2066145256Sjkoshy */
2067145256Sjkoshy
2068145256Sjkoshystatic void
2069145256Sjkoshypmc_release_pmc_descriptor(struct pmc *pm)
2070145256Sjkoshy{
2071145256Sjkoshy	u_int ri, cpu;
2072145774Sjkoshy	enum pmc_mode mode;
2073145256Sjkoshy	struct pmc_hw *phw;
2074147191Sjkoshy	struct pmc_owner *po;
2075145256Sjkoshy	struct pmc_process *pp;
2076145256Sjkoshy	struct pmc_target *ptgt, *tmp;
2077145256Sjkoshy	struct pmc_binding pb;
2078145256Sjkoshy
2079145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
2080145256Sjkoshy
2081145256Sjkoshy	KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2082145256Sjkoshy
2083145774Sjkoshy	ri   = PMC_TO_ROWINDEX(pm);
2084145774Sjkoshy	mode = PMC_TO_MODE(pm);
2085145256Sjkoshy
2086145256Sjkoshy	PMCDBG(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2087145774Sjkoshy	    mode);
2088145256Sjkoshy
2089145256Sjkoshy	/*
2090145256Sjkoshy	 * First, we take the PMC off hardware.
2091145256Sjkoshy	 */
2092145301Simp	cpu = 0;
2093145774Sjkoshy	if (PMC_IS_SYSTEM_MODE(mode)) {
2094145256Sjkoshy
2095145256Sjkoshy		/*
2096145256Sjkoshy		 * A system mode PMC runs on a specific CPU.  Switch
2097145256Sjkoshy		 * to this CPU and turn hardware off.
2098145256Sjkoshy		 */
2099145256Sjkoshy		pmc_save_cpu_binding(&pb);
2100145256Sjkoshy
2101145774Sjkoshy		cpu = PMC_TO_CPU(pm);
2102145256Sjkoshy
2103147191Sjkoshy		pmc_select_cpu(cpu);
2104145256Sjkoshy
2105147191Sjkoshy		/* switch off non-stalled CPUs */
2106147191Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING &&
2107147867Sjkoshy		    pm->pm_stalled == 0) {
2108145256Sjkoshy
2109145256Sjkoshy			phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2110145256Sjkoshy
2111145256Sjkoshy			KASSERT(phw->phw_pmc == pm,
2112145256Sjkoshy			    ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2113145256Sjkoshy				__LINE__, ri, phw->phw_pmc, pm));
2114145256Sjkoshy			PMCDBG(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2115145256Sjkoshy
2116145256Sjkoshy			critical_enter();
2117145256Sjkoshy			md->pmd_stop_pmc(cpu, ri);
2118145256Sjkoshy			critical_exit();
2119145256Sjkoshy		}
2120145256Sjkoshy
2121145256Sjkoshy		PMCDBG(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2122145256Sjkoshy
2123145256Sjkoshy		critical_enter();
2124145256Sjkoshy		md->pmd_config_pmc(cpu, ri, NULL);
2125145256Sjkoshy		critical_exit();
2126145256Sjkoshy
2127147191Sjkoshy		/* adjust the global and process count of SS mode PMCs */
2128147191Sjkoshy		if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2129147191Sjkoshy			po = pm->pm_owner;
2130147191Sjkoshy			po->po_sscount--;
2131147191Sjkoshy			if (po->po_sscount == 0) {
2132147191Sjkoshy				atomic_subtract_rel_int(&pmc_ss_count, 1);
2133147191Sjkoshy				LIST_REMOVE(po, po_ssnext);
2134147191Sjkoshy			}
2135147191Sjkoshy		}
2136147191Sjkoshy
2137145256Sjkoshy		pm->pm_state = PMC_STATE_DELETED;
2138145256Sjkoshy
2139145256Sjkoshy		pmc_restore_cpu_binding(&pb);
2140145256Sjkoshy
2141147191Sjkoshy		/*
2142147191Sjkoshy		 * We could have references to this PMC structure in
2143147191Sjkoshy		 * the per-cpu sample queues.  Wait for the queue to
2144147191Sjkoshy		 * drain.
2145147191Sjkoshy		 */
2146147191Sjkoshy		pmc_wait_for_pmc_idle(pm);
2147147191Sjkoshy
2148145774Sjkoshy	} else if (PMC_IS_VIRTUAL_MODE(mode)) {
2149145256Sjkoshy
2150145256Sjkoshy		/*
2151145256Sjkoshy		 * A virtual PMC could be running on multiple CPUs at
2152145256Sjkoshy		 * a given instant.
2153145256Sjkoshy		 *
2154145256Sjkoshy		 * By marking its state as DELETED, we ensure that
2155145256Sjkoshy		 * this PMC is never further scheduled on hardware.
2156145256Sjkoshy		 *
2157145256Sjkoshy		 * Then we wait till all CPUs are done with this PMC.
2158145256Sjkoshy		 */
2159145256Sjkoshy		pm->pm_state = PMC_STATE_DELETED;
2160145256Sjkoshy
2161145256Sjkoshy
2162147191Sjkoshy		/* Wait for the PMCs runcount to come to zero. */
2163147191Sjkoshy		pmc_wait_for_pmc_idle(pm);
2164145256Sjkoshy
2165145256Sjkoshy		/*
2166145256Sjkoshy		 * At this point the PMC is off all CPUs and cannot be
2167145256Sjkoshy		 * freshly scheduled onto a CPU.  It is now safe to
2168145256Sjkoshy		 * unlink all targets from this PMC.  If a
2169145256Sjkoshy		 * process-record's refcount falls to zero, we remove
2170145256Sjkoshy		 * it from the hash table.  The module-wide SX lock
2171145256Sjkoshy		 * protects us from races.
2172145256Sjkoshy		 */
2173145256Sjkoshy		LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2174145256Sjkoshy			pp = ptgt->pt_process;
2175145256Sjkoshy			pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2176145256Sjkoshy
2177145256Sjkoshy			PMCDBG(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2178145256Sjkoshy
2179145256Sjkoshy			/*
2180145256Sjkoshy			 * If the target process record shows that no
2181145256Sjkoshy			 * PMCs are attached to it, reclaim its space.
2182145256Sjkoshy			 */
2183145256Sjkoshy
2184145256Sjkoshy			if (pp->pp_refcnt == 0) {
2185145256Sjkoshy				pmc_remove_process_descriptor(pp);
2186184205Sdes				free(pp, M_PMC);
2187145256Sjkoshy			}
2188145256Sjkoshy		}
2189145256Sjkoshy
2190145256Sjkoshy		cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2191145256Sjkoshy
2192145256Sjkoshy	}
2193145256Sjkoshy
2194145256Sjkoshy	/*
2195145256Sjkoshy	 * Release any MD resources
2196145256Sjkoshy	 */
2197145256Sjkoshy
2198145256Sjkoshy	(void) md->pmd_release_pmc(cpu, ri, pm);
2199145256Sjkoshy
2200145256Sjkoshy	/*
2201145256Sjkoshy	 * Update row disposition
2202145256Sjkoshy	 */
2203145256Sjkoshy
2204145774Sjkoshy	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2205145256Sjkoshy		PMC_UNMARK_ROW_STANDALONE(ri);
2206145256Sjkoshy	else
2207145256Sjkoshy		PMC_UNMARK_ROW_THREAD(ri);
2208145256Sjkoshy
2209145256Sjkoshy	/* unlink from the owner's list */
2210147191Sjkoshy	if (pm->pm_owner) {
2211147191Sjkoshy		LIST_REMOVE(pm, pm_next);
2212147191Sjkoshy		pm->pm_owner = NULL;
2213147191Sjkoshy	}
2214145256Sjkoshy
2215145256Sjkoshy	pmc_destroy_pmc_descriptor(pm);
2216145256Sjkoshy}
2217145256Sjkoshy
2218145256Sjkoshy/*
2219145256Sjkoshy * Register an owner and a pmc.
2220145256Sjkoshy */
2221145256Sjkoshy
2222145256Sjkoshystatic int
2223145256Sjkoshypmc_register_owner(struct proc *p, struct pmc *pmc)
2224145256Sjkoshy{
2225145256Sjkoshy	struct pmc_owner *po;
2226145256Sjkoshy
2227145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
2228145256Sjkoshy
2229145774Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) == NULL)
2230147191Sjkoshy		if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2231145256Sjkoshy			return ENOMEM;
2232145256Sjkoshy
2233145256Sjkoshy	KASSERT(pmc->pm_owner == NULL,
2234145256Sjkoshy	    ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2235145256Sjkoshy	pmc->pm_owner  = po;
2236145256Sjkoshy
2237147191Sjkoshy	LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2238145256Sjkoshy
2239145256Sjkoshy	PROC_LOCK(p);
2240145256Sjkoshy	p->p_flag |= P_HWPMC;
2241145256Sjkoshy	PROC_UNLOCK(p);
2242145256Sjkoshy
2243147191Sjkoshy	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2244147191Sjkoshy		pmclog_process_pmcallocate(pmc);
2245145256Sjkoshy
2246147191Sjkoshy	PMCDBG(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2247147191Sjkoshy	    po, pmc);
2248147191Sjkoshy
2249145256Sjkoshy	return 0;
2250145256Sjkoshy}
2251145256Sjkoshy
2252145256Sjkoshy/*
2253145256Sjkoshy * Return the current row disposition:
2254145256Sjkoshy * == 0 => FREE
2255145256Sjkoshy *  > 0 => PROCESS MODE
2256145256Sjkoshy *  < 0 => SYSTEM MODE
2257145256Sjkoshy */
2258145256Sjkoshy
2259145256Sjkoshyint
2260145256Sjkoshypmc_getrowdisp(int ri)
2261145256Sjkoshy{
2262145256Sjkoshy	return pmc_pmcdisp[ri];
2263145256Sjkoshy}
2264145256Sjkoshy
2265145256Sjkoshy/*
2266145256Sjkoshy * Check if a PMC at row index 'ri' can be allocated to the current
2267145256Sjkoshy * process.
2268145256Sjkoshy *
2269145256Sjkoshy * Allocation can fail if:
2270145256Sjkoshy *   - the current process is already being profiled by a PMC at index 'ri',
2271145256Sjkoshy *     attached to it via OP_PMCATTACH.
2272145256Sjkoshy *   - the current process has already allocated a PMC at index 'ri'
2273145256Sjkoshy *     via OP_ALLOCATE.
2274145256Sjkoshy */
2275145256Sjkoshy
2276145256Sjkoshystatic int
2277145774Sjkoshypmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2278145256Sjkoshy{
2279145774Sjkoshy	enum pmc_mode mode;
2280145774Sjkoshy	struct pmc *pm;
2281145256Sjkoshy	struct pmc_owner *po;
2282145256Sjkoshy	struct pmc_process *pp;
2283145256Sjkoshy
2284145774Sjkoshy	PMCDBG(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2285145774Sjkoshy	    "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2286145256Sjkoshy
2287145774Sjkoshy	/*
2288145774Sjkoshy	 * We shouldn't have already allocated a process-mode PMC at
2289145774Sjkoshy	 * row index 'ri'.
2290145774Sjkoshy	 *
2291145774Sjkoshy	 * We shouldn't have allocated a system-wide PMC on the same
2292145774Sjkoshy	 * CPU and same RI.
2293145774Sjkoshy	 */
2294145256Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) != NULL)
2295147191Sjkoshy		LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2296145774Sjkoshy		    if (PMC_TO_ROWINDEX(pm) == ri) {
2297145774Sjkoshy			    mode = PMC_TO_MODE(pm);
2298145774Sjkoshy			    if (PMC_IS_VIRTUAL_MODE(mode))
2299145774Sjkoshy				    return EEXIST;
2300145774Sjkoshy			    if (PMC_IS_SYSTEM_MODE(mode) &&
2301145774Sjkoshy				(int) PMC_TO_CPU(pm) == cpu)
2302145774Sjkoshy				    return EEXIST;
2303145774Sjkoshy		    }
2304145774Sjkoshy	        }
2305145256Sjkoshy
2306145774Sjkoshy	/*
2307145774Sjkoshy	 * We also shouldn't be the target of any PMC at this index
2308145774Sjkoshy	 * since otherwise a PMC_ATTACH to ourselves will fail.
2309145774Sjkoshy	 */
2310145256Sjkoshy	if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2311145256Sjkoshy		if (pp->pp_pmcs[ri].pp_pmc)
2312145256Sjkoshy			return EEXIST;
2313145256Sjkoshy
2314145256Sjkoshy	PMCDBG(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2315145256Sjkoshy	    p, p->p_pid, p->p_comm, ri);
2316145256Sjkoshy
2317145256Sjkoshy	return 0;
2318145256Sjkoshy}
2319145256Sjkoshy
2320145256Sjkoshy/*
2321145256Sjkoshy * Check if a given PMC at row index 'ri' can be currently used in
2322145256Sjkoshy * mode 'mode'.
2323145256Sjkoshy */
2324145256Sjkoshy
2325145256Sjkoshystatic int
2326145256Sjkoshypmc_can_allocate_row(int ri, enum pmc_mode mode)
2327145256Sjkoshy{
2328145256Sjkoshy	enum pmc_disp	disp;
2329145256Sjkoshy
2330145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
2331145256Sjkoshy
2332145256Sjkoshy	PMCDBG(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2333145256Sjkoshy
2334145256Sjkoshy	if (PMC_IS_SYSTEM_MODE(mode))
2335145256Sjkoshy		disp = PMC_DISP_STANDALONE;
2336145256Sjkoshy	else
2337145256Sjkoshy		disp = PMC_DISP_THREAD;
2338145256Sjkoshy
2339145256Sjkoshy	/*
2340145256Sjkoshy	 * check disposition for PMC row 'ri':
2341145256Sjkoshy	 *
2342145256Sjkoshy	 * Expected disposition		Row-disposition		Result
2343145256Sjkoshy	 *
2344145256Sjkoshy	 * STANDALONE			STANDALONE or FREE	proceed
2345145256Sjkoshy	 * STANDALONE			THREAD			fail
2346145256Sjkoshy	 * THREAD			THREAD or FREE		proceed
2347145256Sjkoshy	 * THREAD			STANDALONE		fail
2348145256Sjkoshy	 */
2349145256Sjkoshy
2350145256Sjkoshy	if (!PMC_ROW_DISP_IS_FREE(ri) &&
2351145256Sjkoshy	    !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2352145256Sjkoshy	    !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2353145256Sjkoshy		return EBUSY;
2354145256Sjkoshy
2355145256Sjkoshy	/*
2356145256Sjkoshy	 * All OK
2357145256Sjkoshy	 */
2358145256Sjkoshy
2359145256Sjkoshy	PMCDBG(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2360145256Sjkoshy
2361145256Sjkoshy	return 0;
2362145256Sjkoshy
2363145256Sjkoshy}
2364145256Sjkoshy
2365145256Sjkoshy/*
2366145774Sjkoshy * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2367145256Sjkoshy */
2368145256Sjkoshy
2369145256Sjkoshystatic struct pmc *
2370145256Sjkoshypmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2371145256Sjkoshy{
2372147191Sjkoshy	struct pmc *pm;
2373145256Sjkoshy
2374145774Sjkoshy	KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2375145774Sjkoshy	    ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2376145774Sjkoshy		PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2377145256Sjkoshy
2378147191Sjkoshy	LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2379147191Sjkoshy	    if (pm->pm_id == pmcid)
2380147191Sjkoshy		    return pm;
2381145256Sjkoshy
2382145256Sjkoshy	return NULL;
2383145256Sjkoshy}
2384145256Sjkoshy
2385145256Sjkoshystatic int
2386145256Sjkoshypmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2387145256Sjkoshy{
2388145256Sjkoshy
2389145256Sjkoshy	struct pmc *pm;
2390145256Sjkoshy	struct pmc_owner *po;
2391145256Sjkoshy
2392145256Sjkoshy	PMCDBG(PMC,FND,1, "find-pmc id=%d", pmcid);
2393145256Sjkoshy
2394145256Sjkoshy	if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2395145256Sjkoshy		return ESRCH;
2396145256Sjkoshy
2397145256Sjkoshy	if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2398145256Sjkoshy		return EINVAL;
2399145256Sjkoshy
2400145256Sjkoshy	PMCDBG(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2401145256Sjkoshy
2402145256Sjkoshy	*pmc = pm;
2403145256Sjkoshy	return 0;
2404145256Sjkoshy}
2405145256Sjkoshy
2406145256Sjkoshy/*
2407145256Sjkoshy * Start a PMC.
2408145256Sjkoshy */
2409145256Sjkoshy
2410145256Sjkoshystatic int
2411145256Sjkoshypmc_start(struct pmc *pm)
2412145256Sjkoshy{
2413145256Sjkoshy	int error, cpu, ri;
2414145774Sjkoshy	enum pmc_mode mode;
2415147191Sjkoshy	struct pmc_owner *po;
2416145256Sjkoshy	struct pmc_binding pb;
2417145256Sjkoshy
2418145256Sjkoshy	KASSERT(pm != NULL,
2419145256Sjkoshy	    ("[pmc,%d] null pm", __LINE__));
2420145256Sjkoshy
2421145774Sjkoshy	mode = PMC_TO_MODE(pm);
2422145774Sjkoshy	ri   = PMC_TO_ROWINDEX(pm);
2423145774Sjkoshy	error = 0;
2424145256Sjkoshy
2425145774Sjkoshy	PMCDBG(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2426145774Sjkoshy
2427147191Sjkoshy	po = pm->pm_owner;
2428145256Sjkoshy
2429174395Sjkoshy	/*
2430174395Sjkoshy	 * Disallow PMCSTART if a logfile is required but has not been
2431174395Sjkoshy	 * configured yet.
2432174395Sjkoshy	 */
2433174395Sjkoshy	if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2434174395Sjkoshy	    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2435174395Sjkoshy		return EDOOFUS;	/* programming error */
2436174395Sjkoshy
2437174395Sjkoshy	/*
2438174395Sjkoshy	 * If this is a sampling mode PMC, log mapping information for
2439174395Sjkoshy	 * the kernel modules that are currently loaded.
2440174395Sjkoshy	 */
2441174395Sjkoshy	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2442174395Sjkoshy	    pmc_log_kernel_mappings(pm);
2443174395Sjkoshy
2444145774Sjkoshy	if (PMC_IS_VIRTUAL_MODE(mode)) {
2445145256Sjkoshy
2446145256Sjkoshy		/*
2447147191Sjkoshy		 * If a PMCATTACH has never been done on this PMC,
2448147191Sjkoshy		 * attach it to its owner process.
2449145256Sjkoshy		 */
2450145256Sjkoshy
2451145256Sjkoshy		if (LIST_EMPTY(&pm->pm_targets))
2452147191Sjkoshy			error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2453147191Sjkoshy			    pmc_attach_process(po->po_owner, pm);
2454145256Sjkoshy
2455145774Sjkoshy		/*
2456147191Sjkoshy		 * If the PMC is attached to its owner, then force a context
2457147191Sjkoshy		 * switch to ensure that the MD state gets set correctly.
2458145256Sjkoshy		 */
2459145256Sjkoshy
2460147191Sjkoshy		if (error == 0) {
2461147191Sjkoshy			pm->pm_state = PMC_STATE_RUNNING;
2462147191Sjkoshy			if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2463147191Sjkoshy				pmc_force_context_switch();
2464147191Sjkoshy		}
2465147191Sjkoshy
2466145774Sjkoshy		return error;
2467147191Sjkoshy	}
2468145256Sjkoshy
2469147191Sjkoshy
2470147191Sjkoshy	/*
2471147191Sjkoshy	 * A system-wide PMC.
2472174395Sjkoshy	 *
2473147191Sjkoshy	 * Add the owner to the global list if this is a system-wide
2474147191Sjkoshy	 * sampling PMC.
2475147191Sjkoshy	 */
2476147191Sjkoshy
2477147191Sjkoshy	if (mode == PMC_MODE_SS) {
2478147191Sjkoshy		if (po->po_sscount == 0) {
2479147191Sjkoshy			LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2480147191Sjkoshy			atomic_add_rel_int(&pmc_ss_count, 1);
2481147191Sjkoshy			PMCDBG(PMC,OPS,1, "po=%p in global list", po);
2482147191Sjkoshy		}
2483147191Sjkoshy		po->po_sscount++;
2484145256Sjkoshy	}
2485145256Sjkoshy
2486174395Sjkoshy	/* Log mapping information for all processes in the system. */
2487174395Sjkoshy	pmc_log_all_process_mappings(po);
2488157144Sjkoshy
2489145256Sjkoshy	/*
2490147191Sjkoshy	 * Move to the CPU associated with this
2491145256Sjkoshy	 * PMC, and start the hardware.
2492145256Sjkoshy	 */
2493145256Sjkoshy
2494145256Sjkoshy	pmc_save_cpu_binding(&pb);
2495145256Sjkoshy
2496145774Sjkoshy	cpu = PMC_TO_CPU(pm);
2497145256Sjkoshy
2498183266Sjkoshy	if (!pmc_cpu_is_active(cpu))
2499145256Sjkoshy		return ENXIO;
2500145256Sjkoshy
2501145256Sjkoshy	pmc_select_cpu(cpu);
2502145256Sjkoshy
2503145256Sjkoshy	/*
2504145256Sjkoshy	 * global PMCs are configured at allocation time
2505145256Sjkoshy	 * so write out the initial value and start the PMC.
2506145256Sjkoshy	 */
2507145256Sjkoshy
2508147191Sjkoshy	pm->pm_state = PMC_STATE_RUNNING;
2509147191Sjkoshy
2510145774Sjkoshy	critical_enter();
2511145256Sjkoshy	if ((error = md->pmd_write_pmc(cpu, ri,
2512145774Sjkoshy		 PMC_IS_SAMPLING_MODE(mode) ?
2513145256Sjkoshy		 pm->pm_sc.pm_reloadcount :
2514145256Sjkoshy		 pm->pm_sc.pm_initial)) == 0)
2515145256Sjkoshy		error = md->pmd_start_pmc(cpu, ri);
2516145774Sjkoshy	critical_exit();
2517145256Sjkoshy
2518145256Sjkoshy	pmc_restore_cpu_binding(&pb);
2519145256Sjkoshy
2520145256Sjkoshy	return error;
2521145256Sjkoshy}
2522145256Sjkoshy
2523145256Sjkoshy/*
2524145256Sjkoshy * Stop a PMC.
2525145256Sjkoshy */
2526145256Sjkoshy
2527145256Sjkoshystatic int
2528145256Sjkoshypmc_stop(struct pmc *pm)
2529145256Sjkoshy{
2530145774Sjkoshy	int cpu, error, ri;
2531147191Sjkoshy	struct pmc_owner *po;
2532145256Sjkoshy	struct pmc_binding pb;
2533145256Sjkoshy
2534145256Sjkoshy	KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2535145256Sjkoshy
2536145774Sjkoshy	PMCDBG(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2537145774Sjkoshy	    PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2538145256Sjkoshy
2539145256Sjkoshy	pm->pm_state = PMC_STATE_STOPPED;
2540145256Sjkoshy
2541145256Sjkoshy	/*
2542145256Sjkoshy	 * If the PMC is a virtual mode one, changing the state to
2543145256Sjkoshy	 * non-RUNNING is enough to ensure that the PMC never gets
2544145256Sjkoshy	 * scheduled.
2545145256Sjkoshy	 *
2546145256Sjkoshy	 * If this PMC is current running on a CPU, then it will
2547145256Sjkoshy	 * handled correctly at the time its target process is context
2548145256Sjkoshy	 * switched out.
2549145256Sjkoshy	 */
2550145256Sjkoshy
2551145774Sjkoshy	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2552145256Sjkoshy		return 0;
2553145256Sjkoshy
2554145256Sjkoshy	/*
2555145256Sjkoshy	 * A system-mode PMC.  Move to the CPU associated with
2556145256Sjkoshy	 * this PMC, and stop the hardware.  We update the
2557145256Sjkoshy	 * 'initial count' so that a subsequent PMCSTART will
2558145256Sjkoshy	 * resume counting from the current hardware count.
2559145256Sjkoshy	 */
2560145256Sjkoshy
2561145256Sjkoshy	pmc_save_cpu_binding(&pb);
2562145256Sjkoshy
2563145774Sjkoshy	cpu = PMC_TO_CPU(pm);
2564145256Sjkoshy
2565183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
2566145774Sjkoshy	    ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2567145774Sjkoshy
2568183266Sjkoshy	if (!pmc_cpu_is_active(cpu))
2569145256Sjkoshy		return ENXIO;
2570145256Sjkoshy
2571145256Sjkoshy	pmc_select_cpu(cpu);
2572145256Sjkoshy
2573145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
2574145256Sjkoshy
2575145774Sjkoshy	critical_enter();
2576145774Sjkoshy	if ((error = md->pmd_stop_pmc(cpu, ri)) == 0)
2577145774Sjkoshy		error = md->pmd_read_pmc(cpu, ri, &pm->pm_sc.pm_initial);
2578145774Sjkoshy	critical_exit();
2579145774Sjkoshy
2580145256Sjkoshy	pmc_restore_cpu_binding(&pb);
2581145256Sjkoshy
2582147191Sjkoshy	po = pm->pm_owner;
2583147191Sjkoshy
2584147191Sjkoshy	/* remove this owner from the global list of SS PMC owners */
2585147191Sjkoshy	if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2586147191Sjkoshy		po->po_sscount--;
2587147191Sjkoshy		if (po->po_sscount == 0) {
2588147191Sjkoshy			atomic_subtract_rel_int(&pmc_ss_count, 1);
2589147191Sjkoshy			LIST_REMOVE(po, po_ssnext);
2590147191Sjkoshy			PMCDBG(PMC,OPS,2,"po=%p removed from global list", po);
2591147191Sjkoshy		}
2592147191Sjkoshy	}
2593147191Sjkoshy
2594145256Sjkoshy	return error;
2595145256Sjkoshy}
2596145256Sjkoshy
2597145256Sjkoshy
2598153110Sru#ifdef	DEBUG
2599145256Sjkoshystatic const char *pmc_op_to_name[] = {
2600145256Sjkoshy#undef	__PMC_OP
2601145256Sjkoshy#define	__PMC_OP(N, D)	#N ,
2602145256Sjkoshy	__PMC_OPS()
2603145256Sjkoshy	NULL
2604145256Sjkoshy};
2605145256Sjkoshy#endif
2606145256Sjkoshy
2607145256Sjkoshy/*
2608145256Sjkoshy * The syscall interface
2609145256Sjkoshy */
2610145256Sjkoshy
2611145256Sjkoshy#define	PMC_GET_SX_XLOCK(...) do {		\
2612145256Sjkoshy	sx_xlock(&pmc_sx);			\
2613145256Sjkoshy	if (pmc_hook == NULL) {			\
2614145256Sjkoshy		sx_xunlock(&pmc_sx);		\
2615145256Sjkoshy		return __VA_ARGS__;		\
2616145256Sjkoshy	}					\
2617145256Sjkoshy} while (0)
2618145256Sjkoshy
2619145256Sjkoshy#define	PMC_DOWNGRADE_SX() do {			\
2620145256Sjkoshy	sx_downgrade(&pmc_sx);			\
2621145256Sjkoshy	is_sx_downgraded = 1;			\
2622145256Sjkoshy} while (0)
2623145256Sjkoshy
2624145256Sjkoshystatic int
2625145256Sjkoshypmc_syscall_handler(struct thread *td, void *syscall_args)
2626145256Sjkoshy{
2627145256Sjkoshy	int error, is_sx_downgraded, op;
2628145256Sjkoshy	struct pmc_syscall_args *c;
2629145256Sjkoshy	void *arg;
2630145256Sjkoshy
2631145256Sjkoshy	PMC_GET_SX_XLOCK(ENOSYS);
2632145256Sjkoshy
2633147191Sjkoshy	DROP_GIANT();
2634147191Sjkoshy
2635145256Sjkoshy	is_sx_downgraded = 0;
2636145256Sjkoshy
2637145256Sjkoshy	c = (struct pmc_syscall_args *) syscall_args;
2638145256Sjkoshy
2639145256Sjkoshy	op = c->pmop_code;
2640145256Sjkoshy	arg = c->pmop_data;
2641145256Sjkoshy
2642145256Sjkoshy	PMCDBG(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2643145256Sjkoshy	    pmc_op_to_name[op], arg);
2644145256Sjkoshy
2645145256Sjkoshy	error = 0;
2646145256Sjkoshy	atomic_add_int(&pmc_stats.pm_syscalls, 1);
2647145256Sjkoshy
2648145256Sjkoshy	switch(op)
2649145256Sjkoshy	{
2650145256Sjkoshy
2651145256Sjkoshy
2652145256Sjkoshy	/*
2653145256Sjkoshy	 * Configure a log file.
2654145256Sjkoshy	 *
2655145256Sjkoshy	 * XXX This OP will be reworked.
2656145256Sjkoshy	 */
2657145256Sjkoshy
2658145256Sjkoshy	case PMC_OP_CONFIGURELOG:
2659145256Sjkoshy	{
2660157144Sjkoshy		struct proc *p;
2661156466Sjkoshy		struct pmc *pm;
2662145256Sjkoshy		struct pmc_owner *po;
2663145256Sjkoshy		struct pmc_op_configurelog cl;
2664145256Sjkoshy
2665145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
2666145256Sjkoshy
2667145256Sjkoshy		if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2668145256Sjkoshy			break;
2669145256Sjkoshy
2670145256Sjkoshy		/* mark this process as owning a log file */
2671145256Sjkoshy		p = td->td_proc;
2672145256Sjkoshy		if ((po = pmc_find_owner_descriptor(p)) == NULL)
2673147191Sjkoshy			if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2674147191Sjkoshy				error = ENOMEM;
2675147191Sjkoshy				break;
2676147191Sjkoshy			}
2677145256Sjkoshy
2678147191Sjkoshy		/*
2679147191Sjkoshy		 * If a valid fd was passed in, try to configure that,
2680147191Sjkoshy		 * otherwise if 'fd' was less than zero and there was
2681147191Sjkoshy		 * a log file configured, flush its buffers and
2682147191Sjkoshy		 * de-configure it.
2683147191Sjkoshy		 */
2684147191Sjkoshy		if (cl.pm_logfd >= 0)
2685147191Sjkoshy			error = pmclog_configure_log(po, cl.pm_logfd);
2686147191Sjkoshy		else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2687147191Sjkoshy			pmclog_process_closelog(po);
2688147191Sjkoshy			error = pmclog_flush(po);
2689156466Sjkoshy			if (error == 0) {
2690156466Sjkoshy				LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2691156834Sjkoshy				    if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2692156834Sjkoshy					pm->pm_state == PMC_STATE_RUNNING)
2693156466Sjkoshy					    pmc_stop(pm);
2694147191Sjkoshy				error = pmclog_deconfigure_log(po);
2695156466Sjkoshy			}
2696147191Sjkoshy		} else
2697147191Sjkoshy			error = EINVAL;
2698157144Sjkoshy
2699157144Sjkoshy		if (error)
2700157144Sjkoshy			break;
2701147191Sjkoshy	}
2702147191Sjkoshy	break;
2703147191Sjkoshy
2704147191Sjkoshy
2705147191Sjkoshy	/*
2706147191Sjkoshy	 * Flush a log file.
2707147191Sjkoshy	 */
2708147191Sjkoshy
2709147191Sjkoshy	case PMC_OP_FLUSHLOG:
2710147191Sjkoshy	{
2711147191Sjkoshy		struct pmc_owner *po;
2712147191Sjkoshy
2713147191Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
2714147191Sjkoshy
2715147191Sjkoshy		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2716147191Sjkoshy			error = EINVAL;
2717145256Sjkoshy			break;
2718147191Sjkoshy		}
2719145256Sjkoshy
2720147191Sjkoshy		error = pmclog_flush(po);
2721145256Sjkoshy	}
2722145256Sjkoshy	break;
2723145256Sjkoshy
2724145256Sjkoshy	/*
2725145256Sjkoshy	 * Retrieve hardware configuration.
2726145256Sjkoshy	 */
2727145256Sjkoshy
2728145256Sjkoshy	case PMC_OP_GETCPUINFO:	/* CPU information */
2729145256Sjkoshy	{
2730145256Sjkoshy		struct pmc_op_getcpuinfo gci;
2731145256Sjkoshy
2732145256Sjkoshy		gci.pm_cputype = md->pmd_cputype;
2733183266Sjkoshy		gci.pm_ncpu    = pmc_cpu_max();
2734145256Sjkoshy		gci.pm_npmc    = md->pmd_npmc;
2735145256Sjkoshy		gci.pm_nclass  = md->pmd_nclass;
2736145256Sjkoshy		bcopy(md->pmd_classes, &gci.pm_classes,
2737145256Sjkoshy		    sizeof(gci.pm_classes));
2738145256Sjkoshy		error = copyout(&gci, arg, sizeof(gci));
2739145256Sjkoshy	}
2740145256Sjkoshy	break;
2741145256Sjkoshy
2742145256Sjkoshy
2743145256Sjkoshy	/*
2744145256Sjkoshy	 * Get module statistics
2745145256Sjkoshy	 */
2746145256Sjkoshy
2747145256Sjkoshy	case PMC_OP_GETDRIVERSTATS:
2748145256Sjkoshy	{
2749145256Sjkoshy		struct pmc_op_getdriverstats gms;
2750145256Sjkoshy
2751145256Sjkoshy		bcopy(&pmc_stats, &gms, sizeof(gms));
2752145256Sjkoshy		error = copyout(&gms, arg, sizeof(gms));
2753145256Sjkoshy	}
2754145256Sjkoshy	break;
2755145256Sjkoshy
2756145256Sjkoshy
2757145256Sjkoshy	/*
2758145256Sjkoshy	 * Retrieve module version number
2759145256Sjkoshy	 */
2760145256Sjkoshy
2761145256Sjkoshy	case PMC_OP_GETMODULEVERSION:
2762145256Sjkoshy	{
2763147191Sjkoshy		uint32_t cv, modv;
2764147191Sjkoshy
2765147191Sjkoshy		/* retrieve the client's idea of the ABI version */
2766147191Sjkoshy		if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
2767147191Sjkoshy			break;
2768147191Sjkoshy		/* don't service clients newer than our driver */
2769147191Sjkoshy		modv = PMC_VERSION;
2770147191Sjkoshy		if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
2771147191Sjkoshy			error = EPROGMISMATCH;
2772147191Sjkoshy			break;
2773147191Sjkoshy		}
2774147191Sjkoshy		error = copyout(&modv, arg, sizeof(int));
2775145256Sjkoshy	}
2776145256Sjkoshy	break;
2777145256Sjkoshy
2778145256Sjkoshy
2779145256Sjkoshy	/*
2780145256Sjkoshy	 * Retrieve the state of all the PMCs on a given
2781145256Sjkoshy	 * CPU.
2782145256Sjkoshy	 */
2783145256Sjkoshy
2784145256Sjkoshy	case PMC_OP_GETPMCINFO:
2785145256Sjkoshy	{
2786145256Sjkoshy		uint32_t cpu, n, npmc;
2787145256Sjkoshy		size_t pmcinfo_size;
2788145256Sjkoshy		struct pmc *pm;
2789145256Sjkoshy		struct pmc_info *p, *pmcinfo;
2790145256Sjkoshy		struct pmc_op_getpmcinfo *gpi;
2791145256Sjkoshy		struct pmc_owner *po;
2792145256Sjkoshy		struct pmc_binding pb;
2793145256Sjkoshy
2794145256Sjkoshy		PMC_DOWNGRADE_SX();
2795145256Sjkoshy
2796145256Sjkoshy		gpi = (struct pmc_op_getpmcinfo *) arg;
2797145256Sjkoshy
2798145256Sjkoshy		if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
2799145256Sjkoshy			break;
2800145256Sjkoshy
2801183266Sjkoshy		if (cpu >= pmc_cpu_max()) {
2802145256Sjkoshy			error = EINVAL;
2803145256Sjkoshy			break;
2804145256Sjkoshy		}
2805145256Sjkoshy
2806183266Sjkoshy		if (!pmc_cpu_is_active(cpu)) {
2807145256Sjkoshy			error = ENXIO;
2808145256Sjkoshy			break;
2809145256Sjkoshy		}
2810145256Sjkoshy
2811145256Sjkoshy		/* switch to CPU 'cpu' */
2812145256Sjkoshy		pmc_save_cpu_binding(&pb);
2813145256Sjkoshy		pmc_select_cpu(cpu);
2814145256Sjkoshy
2815145256Sjkoshy		npmc = md->pmd_npmc;
2816145256Sjkoshy
2817145256Sjkoshy		pmcinfo_size = npmc * sizeof(struct pmc_info);
2818184214Sdes		pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK);
2819145256Sjkoshy
2820145256Sjkoshy		p = pmcinfo;
2821145256Sjkoshy
2822145256Sjkoshy		for (n = 0; n < md->pmd_npmc; n++, p++) {
2823145256Sjkoshy
2824145256Sjkoshy			if ((error = md->pmd_describe(cpu, n, p, &pm)) != 0)
2825145256Sjkoshy				break;
2826145256Sjkoshy
2827145256Sjkoshy			if (PMC_ROW_DISP_IS_STANDALONE(n))
2828145256Sjkoshy				p->pm_rowdisp = PMC_DISP_STANDALONE;
2829145256Sjkoshy			else if (PMC_ROW_DISP_IS_THREAD(n))
2830145256Sjkoshy				p->pm_rowdisp = PMC_DISP_THREAD;
2831145256Sjkoshy			else
2832145256Sjkoshy				p->pm_rowdisp = PMC_DISP_FREE;
2833145256Sjkoshy
2834145256Sjkoshy			p->pm_ownerpid = -1;
2835145256Sjkoshy
2836145256Sjkoshy			if (pm == NULL)	/* no PMC associated */
2837145256Sjkoshy				continue;
2838145256Sjkoshy
2839145256Sjkoshy			po = pm->pm_owner;
2840145256Sjkoshy
2841145256Sjkoshy			KASSERT(po->po_owner != NULL,
2842145256Sjkoshy			    ("[pmc,%d] pmc_owner had a null proc pointer",
2843145256Sjkoshy				__LINE__));
2844145256Sjkoshy
2845145256Sjkoshy			p->pm_ownerpid = po->po_owner->p_pid;
2846145774Sjkoshy			p->pm_mode     = PMC_TO_MODE(pm);
2847145256Sjkoshy			p->pm_event    = pm->pm_event;
2848145256Sjkoshy			p->pm_flags    = pm->pm_flags;
2849145256Sjkoshy
2850145774Sjkoshy			if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2851145256Sjkoshy				p->pm_reloadcount =
2852145256Sjkoshy				    pm->pm_sc.pm_reloadcount;
2853145256Sjkoshy		}
2854145256Sjkoshy
2855145256Sjkoshy		pmc_restore_cpu_binding(&pb);
2856145256Sjkoshy
2857145256Sjkoshy		/* now copy out the PMC info collected */
2858145256Sjkoshy		if (error == 0)
2859145256Sjkoshy			error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
2860145256Sjkoshy
2861184205Sdes		free(pmcinfo, M_PMC);
2862145256Sjkoshy	}
2863145256Sjkoshy	break;
2864145256Sjkoshy
2865145256Sjkoshy
2866145256Sjkoshy	/*
2867145256Sjkoshy	 * Set the administrative state of a PMC.  I.e. whether
2868145256Sjkoshy	 * the PMC is to be used or not.
2869145256Sjkoshy	 */
2870145256Sjkoshy
2871145256Sjkoshy	case PMC_OP_PMCADMIN:
2872145256Sjkoshy	{
2873145256Sjkoshy		int cpu, ri;
2874145256Sjkoshy		enum pmc_state request;
2875145256Sjkoshy		struct pmc_cpu *pc;
2876145256Sjkoshy		struct pmc_hw *phw;
2877145256Sjkoshy		struct pmc_op_pmcadmin pma;
2878145256Sjkoshy		struct pmc_binding pb;
2879145256Sjkoshy
2880145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
2881145256Sjkoshy
2882145256Sjkoshy		KASSERT(td == curthread,
2883145256Sjkoshy		    ("[pmc,%d] td != curthread", __LINE__));
2884145256Sjkoshy
2885164033Srwatson		error = priv_check(td, PRIV_PMC_MANAGE);
2886164033Srwatson		if (error)
2887145256Sjkoshy			break;
2888145256Sjkoshy
2889145256Sjkoshy		if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
2890145256Sjkoshy			break;
2891145256Sjkoshy
2892145256Sjkoshy		cpu = pma.pm_cpu;
2893145256Sjkoshy
2894183266Sjkoshy		if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
2895145256Sjkoshy			error = EINVAL;
2896145256Sjkoshy			break;
2897145256Sjkoshy		}
2898145256Sjkoshy
2899183266Sjkoshy		if (!pmc_cpu_is_active(cpu)) {
2900145256Sjkoshy			error = ENXIO;
2901145256Sjkoshy			break;
2902145256Sjkoshy		}
2903145256Sjkoshy
2904145256Sjkoshy		request = pma.pm_state;
2905145256Sjkoshy
2906145256Sjkoshy		if (request != PMC_STATE_DISABLED &&
2907145256Sjkoshy		    request != PMC_STATE_FREE) {
2908145256Sjkoshy			error = EINVAL;
2909145256Sjkoshy			break;
2910145256Sjkoshy		}
2911145256Sjkoshy
2912145256Sjkoshy		ri = pma.pm_pmc; /* pmc id == row index */
2913145256Sjkoshy		if (ri < 0 || ri >= (int) md->pmd_npmc) {
2914145256Sjkoshy			error = EINVAL;
2915145256Sjkoshy			break;
2916145256Sjkoshy		}
2917145256Sjkoshy
2918145256Sjkoshy		/*
2919145256Sjkoshy		 * We can't disable a PMC with a row-index allocated
2920145256Sjkoshy		 * for process virtual PMCs.
2921145256Sjkoshy		 */
2922145256Sjkoshy
2923145256Sjkoshy		if (PMC_ROW_DISP_IS_THREAD(ri) &&
2924145256Sjkoshy		    request == PMC_STATE_DISABLED) {
2925145256Sjkoshy			error = EBUSY;
2926145256Sjkoshy			break;
2927145256Sjkoshy		}
2928145256Sjkoshy
2929145256Sjkoshy		/*
2930145256Sjkoshy		 * otherwise, this PMC on this CPU is either free or
2931145256Sjkoshy		 * in system-wide mode.
2932145256Sjkoshy		 */
2933145256Sjkoshy
2934145256Sjkoshy		pmc_save_cpu_binding(&pb);
2935145256Sjkoshy		pmc_select_cpu(cpu);
2936145256Sjkoshy
2937145256Sjkoshy		pc  = pmc_pcpu[cpu];
2938145256Sjkoshy		phw = pc->pc_hwpmcs[ri];
2939145256Sjkoshy
2940145256Sjkoshy		/*
2941145256Sjkoshy		 * XXX do we need some kind of 'forced' disable?
2942145256Sjkoshy		 */
2943145256Sjkoshy
2944145256Sjkoshy		if (phw->phw_pmc == NULL) {
2945145256Sjkoshy			if (request == PMC_STATE_DISABLED &&
2946145256Sjkoshy			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
2947145256Sjkoshy				phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
2948145256Sjkoshy				PMC_MARK_ROW_STANDALONE(ri);
2949145256Sjkoshy			} else if (request == PMC_STATE_FREE &&
2950145256Sjkoshy			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
2951145256Sjkoshy				phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
2952145256Sjkoshy				PMC_UNMARK_ROW_STANDALONE(ri);
2953145256Sjkoshy			}
2954145256Sjkoshy			/* other cases are a no-op */
2955145256Sjkoshy		} else
2956145256Sjkoshy			error = EBUSY;
2957145256Sjkoshy
2958145256Sjkoshy		pmc_restore_cpu_binding(&pb);
2959145256Sjkoshy	}
2960145256Sjkoshy	break;
2961145256Sjkoshy
2962145256Sjkoshy
2963145256Sjkoshy	/*
2964145256Sjkoshy	 * Allocate a PMC.
2965145256Sjkoshy	 */
2966145256Sjkoshy
2967145256Sjkoshy	case PMC_OP_PMCALLOCATE:
2968145256Sjkoshy	{
2969145256Sjkoshy		uint32_t caps;
2970145256Sjkoshy		u_int cpu;
2971145256Sjkoshy		int n;
2972145256Sjkoshy		enum pmc_mode mode;
2973145256Sjkoshy		struct pmc *pmc;
2974145774Sjkoshy		struct pmc_hw *phw;
2975145256Sjkoshy		struct pmc_op_pmcallocate pa;
2976145256Sjkoshy		struct pmc_binding pb;
2977145256Sjkoshy
2978145256Sjkoshy		if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
2979145256Sjkoshy			break;
2980145256Sjkoshy
2981145256Sjkoshy		caps = pa.pm_caps;
2982145256Sjkoshy		mode = pa.pm_mode;
2983145256Sjkoshy		cpu  = pa.pm_cpu;
2984145256Sjkoshy
2985145256Sjkoshy		if ((mode != PMC_MODE_SS  &&  mode != PMC_MODE_SC  &&
2986145256Sjkoshy		     mode != PMC_MODE_TS  &&  mode != PMC_MODE_TC) ||
2987183266Sjkoshy		    (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
2988145256Sjkoshy			error = EINVAL;
2989145256Sjkoshy			break;
2990145256Sjkoshy		}
2991145256Sjkoshy
2992145256Sjkoshy		/*
2993145256Sjkoshy		 * Virtual PMCs should only ask for a default CPU.
2994145256Sjkoshy		 * System mode PMCs need to specify a non-default CPU.
2995145256Sjkoshy		 */
2996145256Sjkoshy
2997145256Sjkoshy		if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
2998145256Sjkoshy		    (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
2999145256Sjkoshy			error = EINVAL;
3000145256Sjkoshy			break;
3001145256Sjkoshy		}
3002145256Sjkoshy
3003145256Sjkoshy		/*
3004183266Sjkoshy		 * Check that an inactive CPU is not being asked for.
3005145256Sjkoshy		 */
3006145256Sjkoshy
3007183266Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3008145256Sjkoshy			error = ENXIO;
3009145256Sjkoshy			break;
3010145256Sjkoshy		}
3011145256Sjkoshy
3012145256Sjkoshy		/*
3013145256Sjkoshy		 * Refuse an allocation for a system-wide PMC if this
3014145256Sjkoshy		 * process has been jailed, or if this process lacks
3015145256Sjkoshy		 * super-user credentials and the sysctl tunable
3016145256Sjkoshy		 * 'security.bsd.unprivileged_syspmcs' is zero.
3017145256Sjkoshy		 */
3018145256Sjkoshy
3019145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode)) {
3020164033Srwatson			if (jailed(curthread->td_ucred)) {
3021145256Sjkoshy				error = EPERM;
3022164033Srwatson				break;
3023164033Srwatson			}
3024164033Srwatson			if (!pmc_unprivileged_syspmcs) {
3025164033Srwatson				error = priv_check(curthread,
3026164033Srwatson				    PRIV_PMC_SYSTEM);
3027164033Srwatson				if (error)
3028164033Srwatson					break;
3029164033Srwatson			}
3030145256Sjkoshy		}
3031145256Sjkoshy
3032145256Sjkoshy		if (error)
3033145256Sjkoshy			break;
3034145256Sjkoshy
3035145256Sjkoshy		/*
3036145256Sjkoshy		 * Look for valid values for 'pm_flags'
3037145256Sjkoshy		 */
3038145256Sjkoshy
3039147191Sjkoshy		if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3040174395Sjkoshy		    PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3041145256Sjkoshy			error = EINVAL;
3042145256Sjkoshy			break;
3043145256Sjkoshy		}
3044145256Sjkoshy
3045147191Sjkoshy		/* process logging options are not allowed for system PMCs */
3046147191Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3047147191Sjkoshy		    (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3048147191Sjkoshy			error = EINVAL;
3049147191Sjkoshy			break;
3050147191Sjkoshy		}
3051147191Sjkoshy
3052145256Sjkoshy		/*
3053145256Sjkoshy		 * All sampling mode PMCs need to be able to interrupt the
3054145256Sjkoshy		 * CPU.
3055145256Sjkoshy		 */
3056147191Sjkoshy		if (PMC_IS_SAMPLING_MODE(mode))
3057145256Sjkoshy			caps |= PMC_CAP_INTERRUPT;
3058145256Sjkoshy
3059149374Sjkoshy		/* A valid class specifier should have been passed in. */
3060149374Sjkoshy		for (n = 0; n < md->pmd_nclass; n++)
3061149374Sjkoshy			if (md->pmd_classes[n].pm_class == pa.pm_class)
3062149374Sjkoshy				break;
3063149374Sjkoshy		if (n == md->pmd_nclass) {
3064149374Sjkoshy			error = EINVAL;
3065149374Sjkoshy			break;
3066149374Sjkoshy		}
3067149374Sjkoshy
3068149374Sjkoshy		/* The requested PMC capabilities should be feasible. */
3069149374Sjkoshy		if ((md->pmd_classes[n].pm_caps & caps) != caps) {
3070149374Sjkoshy			error = EOPNOTSUPP;
3071149374Sjkoshy			break;
3072149374Sjkoshy		}
3073149374Sjkoshy
3074145256Sjkoshy		PMCDBG(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3075145256Sjkoshy		    pa.pm_ev, caps, mode, cpu);
3076145256Sjkoshy
3077145256Sjkoshy		pmc = pmc_allocate_pmc_descriptor();
3078145774Sjkoshy		pmc->pm_id    = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3079145774Sjkoshy		    PMC_ID_INVALID);
3080145256Sjkoshy		pmc->pm_event = pa.pm_ev;
3081145256Sjkoshy		pmc->pm_state = PMC_STATE_FREE;
3082145256Sjkoshy		pmc->pm_caps  = caps;
3083145256Sjkoshy		pmc->pm_flags = pa.pm_flags;
3084145256Sjkoshy
3085145256Sjkoshy		/* switch thread to CPU 'cpu' */
3086145256Sjkoshy		pmc_save_cpu_binding(&pb);
3087145256Sjkoshy
3088145256Sjkoshy#define	PMC_IS_SHAREABLE_PMC(cpu, n)				\
3089145256Sjkoshy	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &		\
3090145256Sjkoshy	 PMC_PHW_FLAG_IS_SHAREABLE)
3091145256Sjkoshy#define	PMC_IS_UNALLOCATED(cpu, n)				\
3092145256Sjkoshy	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3093145256Sjkoshy
3094145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode)) {
3095145256Sjkoshy			pmc_select_cpu(cpu);
3096145256Sjkoshy			for (n = 0; n < (int) md->pmd_npmc; n++)
3097145256Sjkoshy				if (pmc_can_allocate_row(n, mode) == 0 &&
3098145256Sjkoshy				    pmc_can_allocate_rowindex(
3099145774Sjkoshy					    curthread->td_proc, n, cpu) == 0 &&
3100145256Sjkoshy				    (PMC_IS_UNALLOCATED(cpu, n) ||
3101145256Sjkoshy				     PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3102145256Sjkoshy				    md->pmd_allocate_pmc(cpu, n, pmc,
3103145256Sjkoshy					&pa) == 0)
3104145256Sjkoshy					break;
3105145256Sjkoshy		} else {
3106145256Sjkoshy			/* Process virtual mode */
3107145256Sjkoshy			for (n = 0; n < (int) md->pmd_npmc; n++) {
3108145256Sjkoshy				if (pmc_can_allocate_row(n, mode) == 0 &&
3109145256Sjkoshy				    pmc_can_allocate_rowindex(
3110145774Sjkoshy					    curthread->td_proc, n,
3111145774Sjkoshy					    PMC_CPU_ANY) == 0 &&
3112145256Sjkoshy				    md->pmd_allocate_pmc(curthread->td_oncpu,
3113145256Sjkoshy					n, pmc, &pa) == 0)
3114145256Sjkoshy					break;
3115145256Sjkoshy			}
3116145256Sjkoshy		}
3117145256Sjkoshy
3118145256Sjkoshy#undef	PMC_IS_UNALLOCATED
3119145256Sjkoshy#undef	PMC_IS_SHAREABLE_PMC
3120145256Sjkoshy
3121145256Sjkoshy		pmc_restore_cpu_binding(&pb);
3122145256Sjkoshy
3123145256Sjkoshy		if (n == (int) md->pmd_npmc) {
3124145256Sjkoshy			pmc_destroy_pmc_descriptor(pmc);
3125184205Sdes			free(pmc, M_PMC);
3126145256Sjkoshy			pmc = NULL;
3127145256Sjkoshy			error = EINVAL;
3128145256Sjkoshy			break;
3129145256Sjkoshy		}
3130145256Sjkoshy
3131145774Sjkoshy		/* Fill in the correct value in the ID field */
3132145774Sjkoshy		pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3133145256Sjkoshy
3134145774Sjkoshy		PMCDBG(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3135145774Sjkoshy		    pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3136145774Sjkoshy
3137147191Sjkoshy		/* Process mode PMCs with logging enabled need log files */
3138147191Sjkoshy		if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3139147191Sjkoshy			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3140147191Sjkoshy
3141147191Sjkoshy		/* All system mode sampling PMCs require a log file */
3142147191Sjkoshy		if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3143147191Sjkoshy			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3144147191Sjkoshy
3145145256Sjkoshy		/*
3146145256Sjkoshy		 * Configure global pmc's immediately
3147145256Sjkoshy		 */
3148145256Sjkoshy
3149145774Sjkoshy		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3150145774Sjkoshy
3151145774Sjkoshy			pmc_save_cpu_binding(&pb);
3152145774Sjkoshy			pmc_select_cpu(cpu);
3153145774Sjkoshy
3154145774Sjkoshy			phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3155145774Sjkoshy
3156145774Sjkoshy			if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3157145774Sjkoshy			    (error = md->pmd_config_pmc(cpu, n, pmc)) != 0) {
3158145256Sjkoshy				(void) md->pmd_release_pmc(cpu, n, pmc);
3159145256Sjkoshy				pmc_destroy_pmc_descriptor(pmc);
3160184205Sdes				free(pmc, M_PMC);
3161145256Sjkoshy				pmc = NULL;
3162145774Sjkoshy				pmc_restore_cpu_binding(&pb);
3163145774Sjkoshy				error = EPERM;
3164145256Sjkoshy				break;
3165145256Sjkoshy			}
3166145256Sjkoshy
3167145774Sjkoshy			pmc_restore_cpu_binding(&pb);
3168145774Sjkoshy		}
3169145256Sjkoshy
3170145256Sjkoshy		pmc->pm_state    = PMC_STATE_ALLOCATED;
3171145256Sjkoshy
3172145256Sjkoshy		/*
3173145256Sjkoshy		 * mark row disposition
3174145256Sjkoshy		 */
3175145256Sjkoshy
3176145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode))
3177145256Sjkoshy			PMC_MARK_ROW_STANDALONE(n);
3178145256Sjkoshy		else
3179145256Sjkoshy			PMC_MARK_ROW_THREAD(n);
3180145256Sjkoshy
3181145256Sjkoshy		/*
3182145256Sjkoshy		 * Register this PMC with the current thread as its owner.
3183145256Sjkoshy		 */
3184145256Sjkoshy
3185145256Sjkoshy		if ((error =
3186145256Sjkoshy		    pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3187145256Sjkoshy			pmc_release_pmc_descriptor(pmc);
3188184205Sdes			free(pmc, M_PMC);
3189145256Sjkoshy			pmc = NULL;
3190145256Sjkoshy			break;
3191145256Sjkoshy		}
3192145256Sjkoshy
3193145256Sjkoshy		/*
3194145256Sjkoshy		 * Return the allocated index.
3195145256Sjkoshy		 */
3196145256Sjkoshy
3197145774Sjkoshy		pa.pm_pmcid = pmc->pm_id;
3198145256Sjkoshy
3199145256Sjkoshy		error = copyout(&pa, arg, sizeof(pa));
3200145256Sjkoshy	}
3201145256Sjkoshy	break;
3202145256Sjkoshy
3203145256Sjkoshy
3204145256Sjkoshy	/*
3205145256Sjkoshy	 * Attach a PMC to a process.
3206145256Sjkoshy	 */
3207145256Sjkoshy
3208145256Sjkoshy	case PMC_OP_PMCATTACH:
3209145256Sjkoshy	{
3210145256Sjkoshy		struct pmc *pm;
3211145256Sjkoshy		struct proc *p;
3212145256Sjkoshy		struct pmc_op_pmcattach a;
3213145256Sjkoshy
3214145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3215145256Sjkoshy
3216145256Sjkoshy		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3217145256Sjkoshy			break;
3218145256Sjkoshy
3219145256Sjkoshy		if (a.pm_pid < 0) {
3220145256Sjkoshy			error = EINVAL;
3221145256Sjkoshy			break;
3222145256Sjkoshy		} else if (a.pm_pid == 0)
3223145256Sjkoshy			a.pm_pid = td->td_proc->p_pid;
3224145256Sjkoshy
3225145256Sjkoshy		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3226145256Sjkoshy			break;
3227145256Sjkoshy
3228145774Sjkoshy		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3229145256Sjkoshy			error = EINVAL;
3230145256Sjkoshy			break;
3231145256Sjkoshy		}
3232145256Sjkoshy
3233145256Sjkoshy		/* PMCs may be (re)attached only when allocated or stopped */
3234145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) {
3235145256Sjkoshy			error = EBUSY;
3236145256Sjkoshy			break;
3237145256Sjkoshy		} else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3238145256Sjkoshy		    pm->pm_state != PMC_STATE_STOPPED) {
3239145256Sjkoshy			error = EINVAL;
3240145256Sjkoshy			break;
3241145256Sjkoshy		}
3242145256Sjkoshy
3243145256Sjkoshy		/* lookup pid */
3244145256Sjkoshy		if ((p = pfind(a.pm_pid)) == NULL) {
3245145256Sjkoshy			error = ESRCH;
3246145256Sjkoshy			break;
3247145256Sjkoshy		}
3248145256Sjkoshy
3249145256Sjkoshy		/*
3250145256Sjkoshy		 * Ignore processes that are working on exiting.
3251145256Sjkoshy		 */
3252145256Sjkoshy		if (p->p_flag & P_WEXIT) {
3253145256Sjkoshy			error = ESRCH;
3254145256Sjkoshy			PROC_UNLOCK(p);	/* pfind() returns a locked process */
3255145256Sjkoshy			break;
3256145256Sjkoshy		}
3257145256Sjkoshy
3258145256Sjkoshy		/*
3259145256Sjkoshy		 * we are allowed to attach a PMC to a process if
3260145256Sjkoshy		 * we can debug it.
3261145256Sjkoshy		 */
3262145256Sjkoshy		error = p_candebug(curthread, p);
3263145256Sjkoshy
3264145256Sjkoshy		PROC_UNLOCK(p);
3265145256Sjkoshy
3266145256Sjkoshy		if (error == 0)
3267145256Sjkoshy			error = pmc_attach_process(p, pm);
3268145256Sjkoshy	}
3269145256Sjkoshy	break;
3270145256Sjkoshy
3271145256Sjkoshy
3272145256Sjkoshy	/*
3273145256Sjkoshy	 * Detach an attached PMC from a process.
3274145256Sjkoshy	 */
3275145256Sjkoshy
3276145256Sjkoshy	case PMC_OP_PMCDETACH:
3277145256Sjkoshy	{
3278145256Sjkoshy		struct pmc *pm;
3279145256Sjkoshy		struct proc *p;
3280145256Sjkoshy		struct pmc_op_pmcattach a;
3281145256Sjkoshy
3282145256Sjkoshy		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3283145256Sjkoshy			break;
3284145256Sjkoshy
3285145256Sjkoshy		if (a.pm_pid < 0) {
3286145256Sjkoshy			error = EINVAL;
3287145256Sjkoshy			break;
3288145256Sjkoshy		} else if (a.pm_pid == 0)
3289145256Sjkoshy			a.pm_pid = td->td_proc->p_pid;
3290145256Sjkoshy
3291145256Sjkoshy		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3292145256Sjkoshy			break;
3293145256Sjkoshy
3294145256Sjkoshy		if ((p = pfind(a.pm_pid)) == NULL) {
3295145256Sjkoshy			error = ESRCH;
3296145256Sjkoshy			break;
3297145256Sjkoshy		}
3298145256Sjkoshy
3299145256Sjkoshy		/*
3300145256Sjkoshy		 * Treat processes that are in the process of exiting
3301145256Sjkoshy		 * as if they were not present.
3302145256Sjkoshy		 */
3303145256Sjkoshy
3304145256Sjkoshy		if (p->p_flag & P_WEXIT)
3305145256Sjkoshy			error = ESRCH;
3306145256Sjkoshy
3307145256Sjkoshy		PROC_UNLOCK(p);	/* pfind() returns a locked process */
3308145256Sjkoshy
3309145256Sjkoshy		if (error == 0)
3310145256Sjkoshy			error = pmc_detach_process(p, pm);
3311145256Sjkoshy	}
3312145256Sjkoshy	break;
3313145256Sjkoshy
3314145256Sjkoshy
3315145256Sjkoshy	/*
3316147191Sjkoshy	 * Retrieve the MSR number associated with the counter
3317147191Sjkoshy	 * 'pmc_id'.  This allows processes to directly use RDPMC
3318147191Sjkoshy	 * instructions to read their PMCs, without the overhead of a
3319147191Sjkoshy	 * system call.
3320147191Sjkoshy	 */
3321147191Sjkoshy
3322147191Sjkoshy	case PMC_OP_PMCGETMSR:
3323147191Sjkoshy	{
3324147191Sjkoshy		int ri;
3325147191Sjkoshy		struct pmc	*pm;
3326147191Sjkoshy		struct pmc_target *pt;
3327147191Sjkoshy		struct pmc_op_getmsr gm;
3328147191Sjkoshy
3329147191Sjkoshy		PMC_DOWNGRADE_SX();
3330147191Sjkoshy
3331147191Sjkoshy		/* CPU has no 'GETMSR' support */
3332147191Sjkoshy		if (md->pmd_get_msr == NULL) {
3333147191Sjkoshy			error = ENOSYS;
3334147191Sjkoshy			break;
3335147191Sjkoshy		}
3336147191Sjkoshy
3337147191Sjkoshy		if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3338147191Sjkoshy			break;
3339147191Sjkoshy
3340147191Sjkoshy		if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3341147191Sjkoshy			break;
3342147191Sjkoshy
3343147191Sjkoshy		/*
3344147191Sjkoshy		 * The allocated PMC has to be a process virtual PMC,
3345147191Sjkoshy		 * i.e., of type MODE_T[CS].  Global PMCs can only be
3346147191Sjkoshy		 * read using the PMCREAD operation since they may be
3347147191Sjkoshy		 * allocated on a different CPU than the one we could
3348147191Sjkoshy		 * be running on at the time of the RDPMC instruction.
3349147191Sjkoshy		 *
3350147191Sjkoshy		 * The GETMSR operation is not allowed for PMCs that
3351147191Sjkoshy		 * are inherited across processes.
3352147191Sjkoshy		 */
3353147191Sjkoshy
3354147191Sjkoshy		if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3355147191Sjkoshy		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
3356147191Sjkoshy			error = EINVAL;
3357147191Sjkoshy			break;
3358147191Sjkoshy		}
3359147191Sjkoshy
3360147191Sjkoshy		/*
3361147191Sjkoshy		 * It only makes sense to use a RDPMC (or its
3362147191Sjkoshy		 * equivalent instruction on non-x86 architectures) on
3363147191Sjkoshy		 * a process that has allocated and attached a PMC to
3364147191Sjkoshy		 * itself.  Conversely the PMC is only allowed to have
3365147191Sjkoshy		 * one process attached to it -- its owner.
3366147191Sjkoshy		 */
3367147191Sjkoshy
3368147191Sjkoshy		if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3369147191Sjkoshy		    LIST_NEXT(pt, pt_next) != NULL ||
3370147191Sjkoshy		    pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3371147191Sjkoshy			error = EINVAL;
3372147191Sjkoshy			break;
3373147191Sjkoshy		}
3374147191Sjkoshy
3375147191Sjkoshy		ri = PMC_TO_ROWINDEX(pm);
3376147191Sjkoshy
3377147191Sjkoshy		if ((error = (*md->pmd_get_msr)(ri, &gm.pm_msr)) < 0)
3378147191Sjkoshy			break;
3379147191Sjkoshy
3380147191Sjkoshy		if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3381147191Sjkoshy			break;
3382147191Sjkoshy
3383147191Sjkoshy		/*
3384147191Sjkoshy		 * Mark our process as using MSRs.  Update machine
3385147191Sjkoshy		 * state using a forced context switch.
3386147191Sjkoshy		 */
3387147191Sjkoshy
3388147191Sjkoshy		pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3389147191Sjkoshy		pmc_force_context_switch();
3390147191Sjkoshy
3391147191Sjkoshy	}
3392147191Sjkoshy	break;
3393147191Sjkoshy
3394147191Sjkoshy	/*
3395145256Sjkoshy	 * Release an allocated PMC
3396145256Sjkoshy	 */
3397145256Sjkoshy
3398145256Sjkoshy	case PMC_OP_PMCRELEASE:
3399145256Sjkoshy	{
3400145256Sjkoshy		pmc_id_t pmcid;
3401145256Sjkoshy		struct pmc *pm;
3402145256Sjkoshy		struct pmc_owner *po;
3403145256Sjkoshy		struct pmc_op_simple sp;
3404145256Sjkoshy
3405145256Sjkoshy		/*
3406145256Sjkoshy		 * Find PMC pointer for the named PMC.
3407145256Sjkoshy		 *
3408145256Sjkoshy		 * Use pmc_release_pmc_descriptor() to switch off the
3409145256Sjkoshy		 * PMC, remove all its target threads, and remove the
3410145256Sjkoshy		 * PMC from its owner's list.
3411145256Sjkoshy		 *
3412145256Sjkoshy		 * Remove the owner record if this is the last PMC
3413145256Sjkoshy		 * owned.
3414145256Sjkoshy		 *
3415145256Sjkoshy		 * Free up space.
3416145256Sjkoshy		 */
3417145256Sjkoshy
3418145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3419145256Sjkoshy			break;
3420145256Sjkoshy
3421145256Sjkoshy		pmcid = sp.pm_pmcid;
3422145256Sjkoshy
3423145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3424145256Sjkoshy			break;
3425145256Sjkoshy
3426145256Sjkoshy		po = pm->pm_owner;
3427145256Sjkoshy		pmc_release_pmc_descriptor(pm);
3428145256Sjkoshy		pmc_maybe_remove_owner(po);
3429145256Sjkoshy
3430184205Sdes		free(pm, M_PMC);
3431145256Sjkoshy	}
3432145256Sjkoshy	break;
3433145256Sjkoshy
3434145256Sjkoshy
3435145256Sjkoshy	/*
3436145256Sjkoshy	 * Read and/or write a PMC.
3437145256Sjkoshy	 */
3438145256Sjkoshy
3439145256Sjkoshy	case PMC_OP_PMCRW:
3440145256Sjkoshy	{
3441145256Sjkoshy		uint32_t cpu, ri;
3442145256Sjkoshy		struct pmc *pm;
3443145256Sjkoshy		struct pmc_op_pmcrw *pprw;
3444145256Sjkoshy		struct pmc_op_pmcrw prw;
3445145256Sjkoshy		struct pmc_binding pb;
3446145256Sjkoshy		pmc_value_t oldvalue;
3447145256Sjkoshy
3448145256Sjkoshy		PMC_DOWNGRADE_SX();
3449145256Sjkoshy
3450145256Sjkoshy		if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3451145256Sjkoshy			break;
3452145256Sjkoshy
3453145301Simp		ri = 0;
3454145256Sjkoshy		PMCDBG(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3455145256Sjkoshy		    prw.pm_flags);
3456145256Sjkoshy
3457145256Sjkoshy		/* must have at least one flag set */
3458145256Sjkoshy		if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3459145256Sjkoshy			error = EINVAL;
3460145256Sjkoshy			break;
3461145256Sjkoshy		}
3462145256Sjkoshy
3463145256Sjkoshy		/* locate pmc descriptor */
3464145256Sjkoshy		if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3465145256Sjkoshy			break;
3466145256Sjkoshy
3467145256Sjkoshy		/* Can't read a PMC that hasn't been started. */
3468145256Sjkoshy		if (pm->pm_state != PMC_STATE_ALLOCATED &&
3469145256Sjkoshy		    pm->pm_state != PMC_STATE_STOPPED &&
3470145256Sjkoshy		    pm->pm_state != PMC_STATE_RUNNING) {
3471145256Sjkoshy			error = EINVAL;
3472145256Sjkoshy			break;
3473145256Sjkoshy		}
3474145256Sjkoshy
3475145256Sjkoshy		/* writing a new value is allowed only for 'STOPPED' pmcs */
3476145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING &&
3477145256Sjkoshy		    (prw.pm_flags & PMC_F_NEWVALUE)) {
3478145256Sjkoshy			error = EBUSY;
3479145256Sjkoshy			break;
3480145256Sjkoshy		}
3481145256Sjkoshy
3482145774Sjkoshy		if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3483145256Sjkoshy
3484145774Sjkoshy			/*
3485145774Sjkoshy			 * If this PMC is attached to its owner (i.e.,
3486145774Sjkoshy			 * the process requesting this operation) and
3487145774Sjkoshy			 * is running, then attempt to get an
3488145774Sjkoshy			 * upto-date reading from hardware for a READ.
3489145774Sjkoshy			 * Writes are only allowed when the PMC is
3490145774Sjkoshy			 * stopped, so only update the saved value
3491145774Sjkoshy			 * field.
3492145774Sjkoshy			 *
3493145774Sjkoshy			 * If the PMC is not running, or is not
3494145774Sjkoshy			 * attached to its owner, read/write to the
3495145774Sjkoshy			 * savedvalue field.
3496145774Sjkoshy			 */
3497145774Sjkoshy
3498145774Sjkoshy			ri = PMC_TO_ROWINDEX(pm);
3499145774Sjkoshy
3500145256Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
3501145774Sjkoshy			cpu = curthread->td_oncpu;
3502145774Sjkoshy
3503145774Sjkoshy			if (prw.pm_flags & PMC_F_OLDVALUE) {
3504145774Sjkoshy				if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3505145774Sjkoshy				    (pm->pm_state == PMC_STATE_RUNNING))
3506145774Sjkoshy					error = (*md->pmd_read_pmc)(cpu, ri,
3507145774Sjkoshy					    &oldvalue);
3508145774Sjkoshy				else
3509145774Sjkoshy					oldvalue = pm->pm_gv.pm_savedvalue;
3510145774Sjkoshy			}
3511145256Sjkoshy			if (prw.pm_flags & PMC_F_NEWVALUE)
3512145256Sjkoshy				pm->pm_gv.pm_savedvalue = prw.pm_value;
3513145774Sjkoshy
3514145256Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
3515145256Sjkoshy
3516145256Sjkoshy		} else { /* System mode PMCs */
3517145774Sjkoshy			cpu = PMC_TO_CPU(pm);
3518145774Sjkoshy			ri  = PMC_TO_ROWINDEX(pm);
3519145256Sjkoshy
3520183266Sjkoshy			if (!pmc_cpu_is_active(cpu)) {
3521145256Sjkoshy				error = ENXIO;
3522145256Sjkoshy				break;
3523145256Sjkoshy			}
3524145256Sjkoshy
3525145256Sjkoshy			/* move this thread to CPU 'cpu' */
3526145256Sjkoshy			pmc_save_cpu_binding(&pb);
3527145256Sjkoshy			pmc_select_cpu(cpu);
3528145256Sjkoshy
3529145774Sjkoshy			critical_enter();
3530145256Sjkoshy			/* save old value */
3531145256Sjkoshy			if (prw.pm_flags & PMC_F_OLDVALUE)
3532145256Sjkoshy				if ((error = (*md->pmd_read_pmc)(cpu, ri,
3533145256Sjkoshy					 &oldvalue)))
3534145256Sjkoshy					goto error;
3535145256Sjkoshy			/* write out new value */
3536145256Sjkoshy			if (prw.pm_flags & PMC_F_NEWVALUE)
3537145256Sjkoshy				error = (*md->pmd_write_pmc)(cpu, ri,
3538145256Sjkoshy				    prw.pm_value);
3539145256Sjkoshy		error:
3540145774Sjkoshy			critical_exit();
3541145256Sjkoshy			pmc_restore_cpu_binding(&pb);
3542145256Sjkoshy			if (error)
3543145256Sjkoshy				break;
3544145256Sjkoshy		}
3545145256Sjkoshy
3546145256Sjkoshy		pprw = (struct pmc_op_pmcrw *) arg;
3547145256Sjkoshy
3548153110Sru#ifdef	DEBUG
3549145256Sjkoshy		if (prw.pm_flags & PMC_F_NEWVALUE)
3550145256Sjkoshy			PMCDBG(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3551145256Sjkoshy			    ri, prw.pm_value, oldvalue);
3552156778Sjkoshy		else if (prw.pm_flags & PMC_F_OLDVALUE)
3553145256Sjkoshy			PMCDBG(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3554145256Sjkoshy#endif
3555145256Sjkoshy
3556145256Sjkoshy		/* return old value if requested */
3557145256Sjkoshy		if (prw.pm_flags & PMC_F_OLDVALUE)
3558145256Sjkoshy			if ((error = copyout(&oldvalue, &pprw->pm_value,
3559145256Sjkoshy				 sizeof(prw.pm_value))))
3560145256Sjkoshy				break;
3561145256Sjkoshy
3562145256Sjkoshy	}
3563145256Sjkoshy	break;
3564145256Sjkoshy
3565145256Sjkoshy
3566145256Sjkoshy	/*
3567145256Sjkoshy	 * Set the sampling rate for a sampling mode PMC and the
3568145256Sjkoshy	 * initial count for a counting mode PMC.
3569145256Sjkoshy	 */
3570145256Sjkoshy
3571145256Sjkoshy	case PMC_OP_PMCSETCOUNT:
3572145256Sjkoshy	{
3573145256Sjkoshy		struct pmc *pm;
3574145256Sjkoshy		struct pmc_op_pmcsetcount sc;
3575145256Sjkoshy
3576145256Sjkoshy		PMC_DOWNGRADE_SX();
3577145256Sjkoshy
3578145256Sjkoshy		if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3579145256Sjkoshy			break;
3580145256Sjkoshy
3581145256Sjkoshy		if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3582145256Sjkoshy			break;
3583145256Sjkoshy
3584145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) {
3585145256Sjkoshy			error = EBUSY;
3586145256Sjkoshy			break;
3587145256Sjkoshy		}
3588145256Sjkoshy
3589145774Sjkoshy		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3590145256Sjkoshy			pm->pm_sc.pm_reloadcount = sc.pm_count;
3591145256Sjkoshy		else
3592145256Sjkoshy			pm->pm_sc.pm_initial = sc.pm_count;
3593145256Sjkoshy	}
3594145256Sjkoshy	break;
3595145256Sjkoshy
3596145256Sjkoshy
3597145256Sjkoshy	/*
3598145256Sjkoshy	 * Start a PMC.
3599145256Sjkoshy	 */
3600145256Sjkoshy
3601145256Sjkoshy	case PMC_OP_PMCSTART:
3602145256Sjkoshy	{
3603145256Sjkoshy		pmc_id_t pmcid;
3604145256Sjkoshy		struct pmc *pm;
3605145256Sjkoshy		struct pmc_op_simple sp;
3606145256Sjkoshy
3607145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3608145256Sjkoshy
3609145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3610145256Sjkoshy			break;
3611145256Sjkoshy
3612145256Sjkoshy		pmcid = sp.pm_pmcid;
3613145256Sjkoshy
3614145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3615145256Sjkoshy			break;
3616145256Sjkoshy
3617145774Sjkoshy		KASSERT(pmcid == pm->pm_id,
3618145774Sjkoshy		    ("[pmc,%d] pmcid %x != id %x", __LINE__,
3619145774Sjkoshy			pm->pm_id, pmcid));
3620145256Sjkoshy
3621145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3622145256Sjkoshy			break;
3623145256Sjkoshy		else if (pm->pm_state != PMC_STATE_STOPPED &&
3624145256Sjkoshy		    pm->pm_state != PMC_STATE_ALLOCATED) {
3625145256Sjkoshy			error = EINVAL;
3626145256Sjkoshy			break;
3627145256Sjkoshy		}
3628145256Sjkoshy
3629145256Sjkoshy		error = pmc_start(pm);
3630145256Sjkoshy	}
3631145256Sjkoshy	break;
3632145256Sjkoshy
3633145256Sjkoshy
3634145256Sjkoshy	/*
3635145256Sjkoshy	 * Stop a PMC.
3636145256Sjkoshy	 */
3637145256Sjkoshy
3638145256Sjkoshy	case PMC_OP_PMCSTOP:
3639145256Sjkoshy	{
3640145256Sjkoshy		pmc_id_t pmcid;
3641145256Sjkoshy		struct pmc *pm;
3642145256Sjkoshy		struct pmc_op_simple sp;
3643145256Sjkoshy
3644145256Sjkoshy		PMC_DOWNGRADE_SX();
3645145256Sjkoshy
3646145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3647145256Sjkoshy			break;
3648145256Sjkoshy
3649145256Sjkoshy		pmcid = sp.pm_pmcid;
3650145256Sjkoshy
3651145256Sjkoshy		/*
3652145256Sjkoshy		 * Mark the PMC as inactive and invoke the MD stop
3653145256Sjkoshy		 * routines if needed.
3654145256Sjkoshy		 */
3655145256Sjkoshy
3656145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3657145256Sjkoshy			break;
3658145256Sjkoshy
3659145774Sjkoshy		KASSERT(pmcid == pm->pm_id,
3660145774Sjkoshy		    ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3661145774Sjkoshy			pm->pm_id, pmcid));
3662145256Sjkoshy
3663145256Sjkoshy		if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3664145256Sjkoshy			break;
3665145256Sjkoshy		else if (pm->pm_state != PMC_STATE_RUNNING) {
3666145256Sjkoshy			error = EINVAL;
3667145256Sjkoshy			break;
3668145256Sjkoshy		}
3669145256Sjkoshy
3670145256Sjkoshy		error = pmc_stop(pm);
3671145256Sjkoshy	}
3672145256Sjkoshy	break;
3673145256Sjkoshy
3674145256Sjkoshy
3675145256Sjkoshy	/*
3676147867Sjkoshy	 * Write a user supplied value to the log file.
3677145256Sjkoshy	 */
3678145256Sjkoshy
3679145256Sjkoshy	case PMC_OP_WRITELOG:
3680145256Sjkoshy	{
3681147191Sjkoshy		struct pmc_op_writelog wl;
3682147191Sjkoshy		struct pmc_owner *po;
3683145256Sjkoshy
3684145256Sjkoshy		PMC_DOWNGRADE_SX();
3685145256Sjkoshy
3686147191Sjkoshy		if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
3687145256Sjkoshy			break;
3688145256Sjkoshy
3689147191Sjkoshy		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3690145256Sjkoshy			error = EINVAL;
3691145256Sjkoshy			break;
3692145256Sjkoshy		}
3693145256Sjkoshy
3694147191Sjkoshy		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
3695145774Sjkoshy			error = EINVAL;
3696145774Sjkoshy			break;
3697145774Sjkoshy		}
3698145774Sjkoshy
3699147191Sjkoshy		error = pmclog_process_userlog(po, &wl);
3700145256Sjkoshy	}
3701145256Sjkoshy	break;
3702145256Sjkoshy
3703147191Sjkoshy
3704145256Sjkoshy	default:
3705145256Sjkoshy		error = EINVAL;
3706145256Sjkoshy		break;
3707145256Sjkoshy	}
3708145256Sjkoshy
3709145256Sjkoshy	if (is_sx_downgraded)
3710145256Sjkoshy		sx_sunlock(&pmc_sx);
3711145256Sjkoshy	else
3712145256Sjkoshy		sx_xunlock(&pmc_sx);
3713145256Sjkoshy
3714145256Sjkoshy	if (error)
3715145256Sjkoshy		atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
3716145256Sjkoshy
3717147191Sjkoshy	PICKUP_GIANT();
3718147191Sjkoshy
3719145256Sjkoshy	return error;
3720145256Sjkoshy}
3721145256Sjkoshy
3722145256Sjkoshy/*
3723145256Sjkoshy * Helper functions
3724145256Sjkoshy */
3725145256Sjkoshy
3726147191Sjkoshy
3727145256Sjkoshy/*
3728174395Sjkoshy * Mark the thread as needing callchain capture and post an AST.  The
3729174395Sjkoshy * actual callchain capture will be done in a context where it is safe
3730174395Sjkoshy * to take page faults.
3731174395Sjkoshy */
3732174395Sjkoshy
3733174395Sjkoshystatic void
3734174395Sjkoshypmc_post_callchain_ast(void)
3735174395Sjkoshy{
3736174395Sjkoshy	struct thread *td;
3737174395Sjkoshy
3738174395Sjkoshy	td = curthread;
3739174395Sjkoshy
3740174395Sjkoshy	/*
3741174395Sjkoshy	 * Mark this thread as needing processing in ast().
3742174395Sjkoshy	 * td->td_pflags will be safe to touch as the process was in
3743174395Sjkoshy	 * user space when it was interrupted.
3744174395Sjkoshy	 */
3745174395Sjkoshy	td->td_pflags |= TDP_CALLCHAIN;
3746174395Sjkoshy
3747174395Sjkoshy	/*
3748174395Sjkoshy	 * Again, since we've entered this function directly from
3749174395Sjkoshy	 * userland, `td' is guaranteed to be not locked by this CPU,
3750174395Sjkoshy	 * so its safe to try acquire the thread lock even though we
3751174395Sjkoshy	 * are executing in an NMI context.  We need to acquire this
3752174395Sjkoshy	 * lock before touching `td_flags' because other CPUs may be
3753174395Sjkoshy	 * in the process of touching this field.
3754174395Sjkoshy	 */
3755174395Sjkoshy	thread_lock(td);
3756174395Sjkoshy	td->td_flags |= TDF_ASTPENDING;
3757174395Sjkoshy	thread_unlock(td);
3758174395Sjkoshy
3759174395Sjkoshy	return;
3760174395Sjkoshy}
3761174395Sjkoshy
3762174395Sjkoshy/*
3763147191Sjkoshy * Interrupt processing.
3764147191Sjkoshy *
3765174395Sjkoshy * Find a free slot in the per-cpu array of samples and capture the
3766174395Sjkoshy * current callchain there.  If a sample was successfully added, a bit
3767174395Sjkoshy * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
3768174395Sjkoshy * needs to be invoked from the clock handler.
3769147191Sjkoshy *
3770147191Sjkoshy * This function is meant to be called from an NMI handler.  It cannot
3771147191Sjkoshy * use any of the locking primitives supplied by the OS.
3772145256Sjkoshy */
3773145256Sjkoshy
3774147191Sjkoshyint
3775174395Sjkoshypmc_process_interrupt(int cpu, struct pmc *pm, struct trapframe *tf,
3776174395Sjkoshy    int inuserspace)
3777145256Sjkoshy{
3778174395Sjkoshy	int error, callchaindepth;
3779147191Sjkoshy	struct thread *td;
3780147191Sjkoshy	struct pmc_sample *ps;
3781147191Sjkoshy	struct pmc_samplebuffer *psb;
3782145256Sjkoshy
3783147191Sjkoshy	error = 0;
3784145256Sjkoshy
3785174395Sjkoshy	/*
3786174395Sjkoshy	 * Allocate space for a sample buffer.
3787174395Sjkoshy	 */
3788147191Sjkoshy	psb = pmc_pcpu[cpu]->pc_sb;
3789145256Sjkoshy
3790147191Sjkoshy	ps = psb->ps_write;
3791174395Sjkoshy	if (ps->ps_nsamples) {	/* in use, reader hasn't caught up */
3792147867Sjkoshy		pm->pm_stalled = 1;
3793147191Sjkoshy		atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
3794174395Sjkoshy		PMCDBG(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
3795174395Sjkoshy		    cpu, pm, (void *) tf, inuserspace,
3796147191Sjkoshy		    (int) (psb->ps_write - psb->ps_samples),
3797147191Sjkoshy		    (int) (psb->ps_read - psb->ps_samples));
3798147191Sjkoshy		error = ENOMEM;
3799147191Sjkoshy		goto done;
3800147191Sjkoshy	}
3801145256Sjkoshy
3802174395Sjkoshy
3803174395Sjkoshy	/* Fill in entry. */
3804174395Sjkoshy	PMCDBG(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
3805174395Sjkoshy	    (void *) tf, inuserspace,
3806147191Sjkoshy	    (int) (psb->ps_write - psb->ps_samples),
3807147191Sjkoshy	    (int) (psb->ps_read - psb->ps_samples));
3808145256Sjkoshy
3809174395Sjkoshy	atomic_add_rel_32(&pm->pm_runcount, 1);	/* hold onto PMC */
3810147191Sjkoshy	ps->ps_pmc = pm;
3811147191Sjkoshy	if ((td = curthread) && td->td_proc)
3812147191Sjkoshy		ps->ps_pid = td->td_proc->p_pid;
3813147191Sjkoshy	else
3814147191Sjkoshy		ps->ps_pid = -1;
3815174395Sjkoshy	ps->ps_cpu = cpu;
3816174395Sjkoshy	ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
3817145256Sjkoshy
3818174395Sjkoshy	callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
3819174395Sjkoshy	    pmc_callchaindepth : 1;
3820174395Sjkoshy
3821174395Sjkoshy	if (callchaindepth == 1)
3822174395Sjkoshy		ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
3823174395Sjkoshy	else {
3824174395Sjkoshy		/*
3825174395Sjkoshy		 * Kernel stack traversals can be done immediately,
3826174395Sjkoshy		 * while we defer to an AST for user space traversals.
3827174395Sjkoshy		 */
3828174395Sjkoshy		if (!inuserspace)
3829174395Sjkoshy			callchaindepth =
3830174395Sjkoshy			    pmc_save_kernel_callchain(ps->ps_pc,
3831174395Sjkoshy				callchaindepth, tf);
3832174395Sjkoshy		else {
3833174395Sjkoshy			pmc_post_callchain_ast();
3834174395Sjkoshy			callchaindepth = PMC_SAMPLE_INUSE;
3835174395Sjkoshy		}
3836174395Sjkoshy	}
3837174395Sjkoshy
3838174395Sjkoshy	ps->ps_nsamples = callchaindepth;	/* mark entry as in use */
3839174395Sjkoshy
3840147191Sjkoshy	/* increment write pointer, modulo ring buffer size */
3841147191Sjkoshy	ps++;
3842147191Sjkoshy	if (ps == psb->ps_fence)
3843147191Sjkoshy		psb->ps_write = psb->ps_samples;
3844147191Sjkoshy	else
3845147191Sjkoshy		psb->ps_write = ps;
3846145256Sjkoshy
3847147191Sjkoshy done:
3848147191Sjkoshy	/* mark CPU as needing processing */
3849147191Sjkoshy	atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3850147191Sjkoshy
3851174395Sjkoshy	return (error);
3852145256Sjkoshy}
3853145256Sjkoshy
3854174395Sjkoshy/*
3855174395Sjkoshy * Capture a user call chain.  This function will be called from ast()
3856174395Sjkoshy * before control returns to userland and before the process gets
3857174395Sjkoshy * rescheduled.
3858174395Sjkoshy */
3859147191Sjkoshy
3860174395Sjkoshystatic void
3861174395Sjkoshypmc_capture_user_callchain(int cpu, struct trapframe *tf)
3862174395Sjkoshy{
3863174395Sjkoshy	int i;
3864174395Sjkoshy	struct pmc *pm;
3865174395Sjkoshy	struct pmc_sample *ps;
3866174395Sjkoshy	struct pmc_samplebuffer *psb;
3867174395Sjkoshy
3868174395Sjkoshy	psb = pmc_pcpu[cpu]->pc_sb;
3869174395Sjkoshy
3870174395Sjkoshy	/*
3871174395Sjkoshy	 * Iterate through all deferred callchain requests.
3872174395Sjkoshy	 */
3873174395Sjkoshy
3874174395Sjkoshy	for (i = 0; i < pmc_nsamples; i++) {
3875174395Sjkoshy
3876174395Sjkoshy		ps = &psb->ps_samples[i];
3877174395Sjkoshy		if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
3878174395Sjkoshy			continue;
3879174395Sjkoshy
3880174395Sjkoshy		pm = ps->ps_pmc;
3881174395Sjkoshy
3882174395Sjkoshy		KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
3883174395Sjkoshy		    ("[pmc,%d] Retrieving callchain for PMC that doesn't "
3884174395Sjkoshy			"want it", __LINE__));
3885174395Sjkoshy
3886174395Sjkoshy		/*
3887174395Sjkoshy		 * Retrieve the callchain and mark the sample buffer
3888174395Sjkoshy		 * as 'processable' by the timer tick sweep code.
3889174395Sjkoshy		 */
3890174395Sjkoshy		ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
3891174395Sjkoshy		    pmc_callchaindepth, tf);
3892174395Sjkoshy	}
3893174395Sjkoshy
3894174395Sjkoshy	return;
3895174395Sjkoshy}
3896174395Sjkoshy
3897174395Sjkoshy
3898145256Sjkoshy/*
3899147191Sjkoshy * Process saved PC samples.
3900145256Sjkoshy */
3901145256Sjkoshy
3902145256Sjkoshystatic void
3903147191Sjkoshypmc_process_samples(int cpu)
3904145256Sjkoshy{
3905147191Sjkoshy	int n, ri;
3906147191Sjkoshy	struct pmc *pm;
3907147191Sjkoshy	struct thread *td;
3908147191Sjkoshy	struct pmc_owner *po;
3909147191Sjkoshy	struct pmc_sample *ps;
3910147191Sjkoshy	struct pmc_samplebuffer *psb;
3911145256Sjkoshy
3912147191Sjkoshy	KASSERT(PCPU_GET(cpuid) == cpu,
3913147191Sjkoshy	    ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
3914147191Sjkoshy		PCPU_GET(cpuid), cpu));
3915145256Sjkoshy
3916147191Sjkoshy	psb = pmc_pcpu[cpu]->pc_sb;
3917147191Sjkoshy
3918147191Sjkoshy	for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
3919147191Sjkoshy
3920147191Sjkoshy		ps = psb->ps_read;
3921174395Sjkoshy		if (ps->ps_nsamples == PMC_SAMPLE_FREE)
3922147191Sjkoshy			break;
3923174395Sjkoshy		if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
3924174395Sjkoshy			/* Need a rescan at a later time. */
3925174395Sjkoshy			atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3926174395Sjkoshy			break;
3927174395Sjkoshy		}
3928147191Sjkoshy
3929147191Sjkoshy		pm = ps->ps_pmc;
3930147191Sjkoshy		po = pm->pm_owner;
3931147191Sjkoshy
3932147191Sjkoshy		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
3933147191Sjkoshy		    ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
3934147191Sjkoshy			pm, PMC_TO_MODE(pm)));
3935147191Sjkoshy
3936147191Sjkoshy		/* Ignore PMCs that have been switched off */
3937147191Sjkoshy		if (pm->pm_state != PMC_STATE_RUNNING)
3938147191Sjkoshy			goto entrydone;
3939147191Sjkoshy
3940174395Sjkoshy		PMCDBG(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
3941174395Sjkoshy		    pm, ps->ps_nsamples, ps->ps_flags,
3942147191Sjkoshy		    (int) (psb->ps_write - psb->ps_samples),
3943147191Sjkoshy		    (int) (psb->ps_read - psb->ps_samples));
3944147191Sjkoshy
3945147191Sjkoshy		/*
3946147191Sjkoshy		 * If this is a process-mode PMC that is attached to
3947147191Sjkoshy		 * its owner, and if the PC is in user mode, update
3948147191Sjkoshy		 * profiling statistics like timer-based profiling
3949147191Sjkoshy		 * would have done.
3950147191Sjkoshy		 */
3951147191Sjkoshy		if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
3952174395Sjkoshy			if (ps->ps_flags & PMC_CC_F_USERSPACE) {
3953147191Sjkoshy				td = FIRST_THREAD_IN_PROC(po->po_owner);
3954174395Sjkoshy				addupc_intr(td, ps->ps_pc[0], 1);
3955147191Sjkoshy			}
3956147191Sjkoshy			goto entrydone;
3957147191Sjkoshy		}
3958147191Sjkoshy
3959147191Sjkoshy		/*
3960147191Sjkoshy		 * Otherwise, this is either a sampling mode PMC that
3961147191Sjkoshy		 * is attached to a different process than its owner,
3962147191Sjkoshy		 * or a system-wide sampling PMC.  Dispatch a log
3963147191Sjkoshy		 * entry to the PMC's owner process.
3964147191Sjkoshy		 */
3965147191Sjkoshy
3966174395Sjkoshy		pmclog_process_callchain(pm, ps);
3967147191Sjkoshy
3968147191Sjkoshy	entrydone:
3969174395Sjkoshy		ps->ps_nsamples = 0;	/* mark entry as free */
3970147191Sjkoshy		atomic_subtract_rel_32(&pm->pm_runcount, 1);
3971147191Sjkoshy
3972147191Sjkoshy		/* increment read pointer, modulo sample size */
3973147191Sjkoshy		if (++ps == psb->ps_fence)
3974147191Sjkoshy			psb->ps_read = psb->ps_samples;
3975147191Sjkoshy		else
3976147191Sjkoshy			psb->ps_read = ps;
3977147191Sjkoshy	}
3978147191Sjkoshy
3979147191Sjkoshy	atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
3980147191Sjkoshy
3981147191Sjkoshy	/* Do not re-enable stalled PMCs if we failed to process any samples */
3982147191Sjkoshy	if (n == 0)
3983147191Sjkoshy		return;
3984147191Sjkoshy
3985147191Sjkoshy	/*
3986147191Sjkoshy	 * Restart any stalled sampling PMCs on this CPU.
3987147191Sjkoshy	 *
3988147867Sjkoshy	 * If the NMI handler sets the pm_stalled field of a PMC after
3989147867Sjkoshy	 * the check below, we'll end up processing the stalled PMC at
3990147867Sjkoshy	 * the next hardclock tick.
3991147191Sjkoshy	 */
3992147191Sjkoshy	for (n = 0; n < md->pmd_npmc; n++) {
3993147191Sjkoshy		(void) (*md->pmd_get_config)(cpu,n,&pm);
3994147191Sjkoshy		if (pm == NULL ||			 /* !cfg'ed */
3995147191Sjkoshy		    pm->pm_state != PMC_STATE_RUNNING || /* !active */
3996147191Sjkoshy		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
3997147867Sjkoshy		    pm->pm_stalled == 0) /* !stalled */
3998147191Sjkoshy			continue;
3999147191Sjkoshy
4000147867Sjkoshy		pm->pm_stalled = 0;
4001147191Sjkoshy		ri = PMC_TO_ROWINDEX(pm);
4002147191Sjkoshy		(*md->pmd_start_pmc)(cpu, ri);
4003147191Sjkoshy	}
4004145256Sjkoshy}
4005145256Sjkoshy
4006145256Sjkoshy/*
4007145256Sjkoshy * Event handlers.
4008145256Sjkoshy */
4009145256Sjkoshy
4010145256Sjkoshy/*
4011145256Sjkoshy * Handle a process exit.
4012145256Sjkoshy *
4013147191Sjkoshy * Remove this process from all hash tables.  If this process
4014147191Sjkoshy * owned any PMCs, turn off those PMCs and deallocate them,
4015147191Sjkoshy * removing any associations with target processes.
4016147191Sjkoshy *
4017147191Sjkoshy * This function will be called by the last 'thread' of a
4018147191Sjkoshy * process.
4019147191Sjkoshy *
4020145256Sjkoshy * XXX This eventhandler gets called early in the exit process.
4021145256Sjkoshy * Consider using a 'hook' invocation from thread_exit() or equivalent
4022145256Sjkoshy * spot.  Another negative is that kse_exit doesn't seem to call
4023145256Sjkoshy * exit1() [??].
4024147191Sjkoshy *
4025145256Sjkoshy */
4026145256Sjkoshy
4027145256Sjkoshystatic void
4028145256Sjkoshypmc_process_exit(void *arg __unused, struct proc *p)
4029145256Sjkoshy{
4030145256Sjkoshy	int is_using_hwpmcs;
4031147191Sjkoshy	int cpu;
4032147191Sjkoshy	unsigned int ri;
4033147191Sjkoshy	struct pmc *pm;
4034147191Sjkoshy	struct pmc_process *pp;
4035147191Sjkoshy	struct pmc_owner *po;
4036147191Sjkoshy	pmc_value_t newvalue, tmp;
4037145256Sjkoshy
4038145256Sjkoshy	PROC_LOCK(p);
4039145256Sjkoshy	is_using_hwpmcs = p->p_flag & P_HWPMC;
4040145256Sjkoshy	PROC_UNLOCK(p);
4041145256Sjkoshy
4042147191Sjkoshy	/*
4043147191Sjkoshy	 * Log a sysexit event to all SS PMC owners.
4044147191Sjkoshy	 */
4045147191Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4046147191Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4047147191Sjkoshy		    pmclog_process_sysexit(po, p->p_pid);
4048145256Sjkoshy
4049147191Sjkoshy	if (!is_using_hwpmcs)
4050147191Sjkoshy		return;
4051147191Sjkoshy
4052147191Sjkoshy	PMC_GET_SX_XLOCK();
4053147191Sjkoshy	PMCDBG(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4054147191Sjkoshy	    p->p_comm);
4055147191Sjkoshy
4056147191Sjkoshy	/*
4057147191Sjkoshy	 * Since this code is invoked by the last thread in an exiting
4058147191Sjkoshy	 * process, we would have context switched IN at some prior
4059147191Sjkoshy	 * point.  However, with PREEMPTION, kernel mode context
4060147191Sjkoshy	 * switches may happen any time, so we want to disable a
4061147191Sjkoshy	 * context switch OUT till we get any PMCs targetting this
4062147191Sjkoshy	 * process off the hardware.
4063147191Sjkoshy	 *
4064147191Sjkoshy	 * We also need to atomically remove this process'
4065147191Sjkoshy	 * entry from our target process hash table, using
4066147191Sjkoshy	 * PMC_FLAG_REMOVE.
4067147191Sjkoshy	 */
4068147191Sjkoshy	PMCDBG(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4069147191Sjkoshy	    p->p_comm);
4070147191Sjkoshy
4071147191Sjkoshy	critical_enter(); /* no preemption */
4072147191Sjkoshy
4073147191Sjkoshy	cpu = curthread->td_oncpu;
4074147191Sjkoshy
4075147191Sjkoshy	if ((pp = pmc_find_process_descriptor(p,
4076147191Sjkoshy		 PMC_FLAG_REMOVE)) != NULL) {
4077147191Sjkoshy
4078147191Sjkoshy		PMCDBG(PRC,EXT,2,
4079147191Sjkoshy		    "process-exit proc=%p pmc-process=%p", p, pp);
4080147191Sjkoshy
4081147191Sjkoshy		/*
4082147191Sjkoshy		 * The exiting process could the target of
4083147191Sjkoshy		 * some PMCs which will be running on
4084147191Sjkoshy		 * currently executing CPU.
4085147191Sjkoshy		 *
4086147191Sjkoshy		 * We need to turn these PMCs off like we
4087147191Sjkoshy		 * would do at context switch OUT time.
4088147191Sjkoshy		 */
4089147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++) {
4090147191Sjkoshy
4091147191Sjkoshy			/*
4092147191Sjkoshy			 * Pick up the pmc pointer from hardware
4093147191Sjkoshy			 * state similar to the CSW_OUT code.
4094147191Sjkoshy			 */
4095147191Sjkoshy			pm = NULL;
4096147191Sjkoshy			(void) (*md->pmd_get_config)(cpu, ri, &pm);
4097147191Sjkoshy
4098147191Sjkoshy			PMCDBG(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4099147191Sjkoshy
4100147191Sjkoshy			if (pm == NULL ||
4101147191Sjkoshy			    !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4102147191Sjkoshy				continue;
4103147191Sjkoshy
4104147191Sjkoshy			PMCDBG(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4105147191Sjkoshy			    "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4106147191Sjkoshy			    pm, pm->pm_state);
4107147191Sjkoshy
4108147191Sjkoshy			KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4109147191Sjkoshy			    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4110147191Sjkoshy				__LINE__, PMC_TO_ROWINDEX(pm), ri));
4111147191Sjkoshy
4112147191Sjkoshy			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4113147191Sjkoshy			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4114147191Sjkoshy				__LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4115147191Sjkoshy
4116147191Sjkoshy			(void) md->pmd_stop_pmc(cpu, ri);
4117147191Sjkoshy
4118147191Sjkoshy			KASSERT(pm->pm_runcount > 0,
4119147191Sjkoshy			    ("[pmc,%d] bad runcount ri %d rc %d",
4120147191Sjkoshy				__LINE__, ri, pm->pm_runcount));
4121147191Sjkoshy
4122147867Sjkoshy			/* Stop hardware only if it is actually running */
4123147191Sjkoshy			if (pm->pm_state == PMC_STATE_RUNNING &&
4124147867Sjkoshy			    pm->pm_stalled == 0) {
4125147191Sjkoshy				md->pmd_read_pmc(cpu, ri, &newvalue);
4126147191Sjkoshy				tmp = newvalue -
4127147191Sjkoshy				    PMC_PCPU_SAVED(cpu,ri);
4128147191Sjkoshy
4129147191Sjkoshy				mtx_pool_lock_spin(pmc_mtxpool, pm);
4130147191Sjkoshy				pm->pm_gv.pm_savedvalue += tmp;
4131147191Sjkoshy				pp->pp_pmcs[ri].pp_pmcval += tmp;
4132147191Sjkoshy				mtx_pool_unlock_spin(pmc_mtxpool, pm);
4133147191Sjkoshy			}
4134147191Sjkoshy
4135147191Sjkoshy			atomic_subtract_rel_32(&pm->pm_runcount,1);
4136147191Sjkoshy
4137147191Sjkoshy			KASSERT((int) pm->pm_runcount >= 0,
4138147191Sjkoshy			    ("[pmc,%d] runcount is %d", __LINE__, ri));
4139147191Sjkoshy
4140147191Sjkoshy			(void) md->pmd_config_pmc(cpu, ri, NULL);
4141147191Sjkoshy		}
4142147191Sjkoshy
4143147191Sjkoshy		/*
4144147191Sjkoshy		 * Inform the MD layer of this pseudo "context switch
4145147191Sjkoshy		 * out"
4146147191Sjkoshy		 */
4147147191Sjkoshy		(void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
4148147191Sjkoshy
4149147191Sjkoshy		critical_exit(); /* ok to be pre-empted now */
4150147191Sjkoshy
4151147191Sjkoshy		/*
4152147191Sjkoshy		 * Unlink this process from the PMCs that are
4153147191Sjkoshy		 * targetting it.  This will send a signal to
4154147191Sjkoshy		 * all PMC owner's whose PMCs are orphaned.
4155147191Sjkoshy		 *
4156147191Sjkoshy		 * Log PMC value at exit time if requested.
4157147191Sjkoshy		 */
4158147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
4159147191Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
4160147867Sjkoshy				if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
4161147867Sjkoshy				    PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
4162147191Sjkoshy					pmclog_process_procexit(pm, pp);
4163147191Sjkoshy				pmc_unlink_target_process(pm, pp);
4164147191Sjkoshy			}
4165184205Sdes		free(pp, M_PMC);
4166147191Sjkoshy
4167147191Sjkoshy	} else
4168147191Sjkoshy		critical_exit(); /* pp == NULL */
4169147191Sjkoshy
4170147191Sjkoshy
4171147191Sjkoshy	/*
4172147191Sjkoshy	 * If the process owned PMCs, free them up and free up
4173147191Sjkoshy	 * memory.
4174147191Sjkoshy	 */
4175147191Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
4176147191Sjkoshy		pmc_remove_owner(po);
4177147191Sjkoshy		pmc_destroy_owner_descriptor(po);
4178145256Sjkoshy	}
4179147191Sjkoshy
4180147191Sjkoshy	sx_xunlock(&pmc_sx);
4181145256Sjkoshy}
4182145256Sjkoshy
4183145256Sjkoshy/*
4184145256Sjkoshy * Handle a process fork.
4185145256Sjkoshy *
4186145256Sjkoshy * If the parent process 'p1' is under HWPMC monitoring, then copy
4187145256Sjkoshy * over any attached PMCs that have 'do_descendants' semantics.
4188145256Sjkoshy */
4189145256Sjkoshy
4190145256Sjkoshystatic void
4191147191Sjkoshypmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
4192145256Sjkoshy    int flags)
4193145256Sjkoshy{
4194145256Sjkoshy	int is_using_hwpmcs;
4195147191Sjkoshy	unsigned int ri;
4196147191Sjkoshy	uint32_t do_descendants;
4197147191Sjkoshy	struct pmc *pm;
4198147191Sjkoshy	struct pmc_owner *po;
4199147191Sjkoshy	struct pmc_process *ppnew, *ppold;
4200145256Sjkoshy
4201145256Sjkoshy	(void) flags;		/* unused parameter */
4202145256Sjkoshy
4203145256Sjkoshy	PROC_LOCK(p1);
4204145256Sjkoshy	is_using_hwpmcs = p1->p_flag & P_HWPMC;
4205145256Sjkoshy	PROC_UNLOCK(p1);
4206145256Sjkoshy
4207147191Sjkoshy	/*
4208147191Sjkoshy	 * If there are system-wide sampling PMCs active, we need to
4209147191Sjkoshy	 * log all fork events to their owner's logs.
4210147191Sjkoshy	 */
4211147191Sjkoshy
4212147191Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4213147191Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4214147191Sjkoshy		    pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4215147191Sjkoshy
4216147191Sjkoshy	if (!is_using_hwpmcs)
4217147191Sjkoshy		return;
4218147191Sjkoshy
4219147191Sjkoshy	PMC_GET_SX_XLOCK();
4220147191Sjkoshy	PMCDBG(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4221147191Sjkoshy	    p1->p_pid, p1->p_comm, newproc);
4222147191Sjkoshy
4223147191Sjkoshy	/*
4224147191Sjkoshy	 * If the parent process (curthread->td_proc) is a
4225147191Sjkoshy	 * target of any PMCs, look for PMCs that are to be
4226147191Sjkoshy	 * inherited, and link these into the new process
4227147191Sjkoshy	 * descriptor.
4228147191Sjkoshy	 */
4229147191Sjkoshy	if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4230147191Sjkoshy		 PMC_FLAG_NONE)) == NULL)
4231147191Sjkoshy		goto done;		/* nothing to do */
4232147191Sjkoshy
4233147191Sjkoshy	do_descendants = 0;
4234147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
4235147191Sjkoshy		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4236147191Sjkoshy			do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4237147191Sjkoshy	if (do_descendants == 0) /* nothing to do */
4238147191Sjkoshy		goto done;
4239147191Sjkoshy
4240147191Sjkoshy	/* allocate a descriptor for the new process  */
4241147191Sjkoshy	if ((ppnew = pmc_find_process_descriptor(newproc,
4242147191Sjkoshy		 PMC_FLAG_ALLOCATE)) == NULL)
4243147191Sjkoshy		goto done;
4244147191Sjkoshy
4245147191Sjkoshy	/*
4246147191Sjkoshy	 * Run through all PMCs that were targeting the old process
4247147191Sjkoshy	 * and which specified F_DESCENDANTS and attach them to the
4248147191Sjkoshy	 * new process.
4249147191Sjkoshy	 *
4250147191Sjkoshy	 * Log the fork event to all owners of PMCs attached to this
4251147191Sjkoshy	 * process, if not already logged.
4252147191Sjkoshy	 */
4253147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
4254147191Sjkoshy		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4255147191Sjkoshy		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
4256147191Sjkoshy			pmc_link_target_process(pm, ppnew);
4257147191Sjkoshy			po = pm->pm_owner;
4258147191Sjkoshy			if (po->po_sscount == 0 &&
4259147191Sjkoshy			    po->po_flags & PMC_PO_OWNS_LOGFILE)
4260147191Sjkoshy				pmclog_process_procfork(po, p1->p_pid,
4261147191Sjkoshy				    newproc->p_pid);
4262147191Sjkoshy		}
4263147191Sjkoshy
4264147191Sjkoshy	/*
4265147191Sjkoshy	 * Now mark the new process as being tracked by this driver.
4266147191Sjkoshy	 */
4267147191Sjkoshy	PROC_LOCK(newproc);
4268147191Sjkoshy	newproc->p_flag |= P_HWPMC;
4269147191Sjkoshy	PROC_UNLOCK(newproc);
4270147191Sjkoshy
4271147191Sjkoshy done:
4272147191Sjkoshy	sx_xunlock(&pmc_sx);
4273145256Sjkoshy}
4274145256Sjkoshy
4275145256Sjkoshy
4276145256Sjkoshy/*
4277145256Sjkoshy * initialization
4278145256Sjkoshy */
4279145256Sjkoshy
4280145256Sjkoshystatic const char *pmc_name_of_pmcclass[] = {
4281145256Sjkoshy#undef	__PMC_CLASS
4282145256Sjkoshy#define	__PMC_CLASS(N) #N ,
4283145256Sjkoshy	__PMC_CLASSES()
4284145256Sjkoshy};
4285145256Sjkoshy
4286145256Sjkoshystatic int
4287145256Sjkoshypmc_initialize(void)
4288145256Sjkoshy{
4289147191Sjkoshy	int cpu, error, n;
4290183266Sjkoshy	unsigned int maxcpu;
4291145256Sjkoshy	struct pmc_binding pb;
4292174395Sjkoshy	struct pmc_sample *ps;
4293147191Sjkoshy	struct pmc_samplebuffer *sb;
4294145256Sjkoshy
4295145256Sjkoshy	md = NULL;
4296145256Sjkoshy	error = 0;
4297145256Sjkoshy
4298153110Sru#ifdef	DEBUG
4299145256Sjkoshy	/* parse debug flags first */
4300145256Sjkoshy	if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4301145256Sjkoshy		pmc_debugstr, sizeof(pmc_debugstr)))
4302145256Sjkoshy		pmc_debugflags_parse(pmc_debugstr,
4303145256Sjkoshy		    pmc_debugstr+strlen(pmc_debugstr));
4304145256Sjkoshy#endif
4305145256Sjkoshy
4306145256Sjkoshy	PMCDBG(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4307145256Sjkoshy
4308148562Sjkoshy	/* check kernel version */
4309148562Sjkoshy	if (pmc_kernel_version != PMC_VERSION) {
4310148562Sjkoshy		if (pmc_kernel_version == 0)
4311148562Sjkoshy			printf("hwpmc: this kernel has not been compiled with "
4312148562Sjkoshy			    "'options HWPMC_HOOKS'.\n");
4313148562Sjkoshy		else
4314148562Sjkoshy			printf("hwpmc: kernel version (0x%x) does not match "
4315148562Sjkoshy			    "module version (0x%x).\n", pmc_kernel_version,
4316148562Sjkoshy			    PMC_VERSION);
4317148562Sjkoshy		return EPROGMISMATCH;
4318148562Sjkoshy	}
4319148562Sjkoshy
4320145256Sjkoshy	/*
4321145256Sjkoshy	 * check sysctl parameters
4322145256Sjkoshy	 */
4323145256Sjkoshy
4324145256Sjkoshy	if (pmc_hashsize <= 0) {
4325174395Sjkoshy		(void) printf("hwpmc: tunable \"hashsize\"=%d must be "
4326174395Sjkoshy		    "greater than zero.\n", pmc_hashsize);
4327145256Sjkoshy		pmc_hashsize = PMC_HASH_SIZE;
4328145256Sjkoshy	}
4329145256Sjkoshy
4330147191Sjkoshy	if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4331174395Sjkoshy		(void) printf("hwpmc: tunable \"nsamples\"=%d out of "
4332174395Sjkoshy		    "range.\n", pmc_nsamples);
4333147191Sjkoshy		pmc_nsamples = PMC_NSAMPLES;
4334147191Sjkoshy	}
4335145256Sjkoshy
4336174395Sjkoshy	if (pmc_callchaindepth <= 0 ||
4337174395Sjkoshy	    pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
4338174395Sjkoshy		(void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
4339174395Sjkoshy		    "range.\n", pmc_callchaindepth);
4340174395Sjkoshy		pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
4341174395Sjkoshy	}
4342174395Sjkoshy
4343147191Sjkoshy	md = pmc_md_initialize();
4344147191Sjkoshy
4345145256Sjkoshy	if (md == NULL || md->pmd_init == NULL)
4346145256Sjkoshy		return ENOSYS;
4347145256Sjkoshy
4348183266Sjkoshy	maxcpu = pmc_cpu_max();
4349183266Sjkoshy
4350145256Sjkoshy	/* allocate space for the per-cpu array */
4351184205Sdes	pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *),
4352145256Sjkoshy	    M_PMC, M_WAITOK|M_ZERO);
4353145256Sjkoshy
4354145256Sjkoshy	/* per-cpu 'saved values' for managing process-mode PMCs */
4355184214Sdes	pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
4356184214Sdes	    M_PMC, M_WAITOK);
4357145256Sjkoshy
4358183266Sjkoshy	/* Perform CPU-dependent initialization. */
4359145256Sjkoshy	pmc_save_cpu_binding(&pb);
4360183266Sjkoshy	for (cpu = 0; cpu < maxcpu; cpu++) {
4361183266Sjkoshy		if (!pmc_cpu_is_active(cpu))
4362145256Sjkoshy			continue;
4363145256Sjkoshy		pmc_select_cpu(cpu);
4364145256Sjkoshy		if ((error = md->pmd_init(cpu)) != 0)
4365145256Sjkoshy			break;
4366145256Sjkoshy	}
4367145256Sjkoshy	pmc_restore_cpu_binding(&pb);
4368145256Sjkoshy
4369145256Sjkoshy	if (error != 0)
4370145256Sjkoshy		return error;
4371145256Sjkoshy
4372147191Sjkoshy	/* allocate space for the sample array */
4373183266Sjkoshy	for (cpu = 0; cpu < maxcpu; cpu++) {
4374183266Sjkoshy		if (!pmc_cpu_is_active(cpu))
4375147191Sjkoshy			continue;
4376184214Sdes		sb = malloc(sizeof(struct pmc_samplebuffer) +
4377147191Sjkoshy		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4378147191Sjkoshy		    M_WAITOK|M_ZERO);
4379147191Sjkoshy
4380147191Sjkoshy		sb->ps_read = sb->ps_write = sb->ps_samples;
4381153735Sjkoshy		sb->ps_fence = sb->ps_samples + pmc_nsamples;
4382147191Sjkoshy		KASSERT(pmc_pcpu[cpu] != NULL,
4383147191Sjkoshy		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4384147191Sjkoshy
4385184214Sdes		sb->ps_callchains = malloc(pmc_callchaindepth *
4386184214Sdes		    pmc_nsamples * sizeof(uintptr_t),
4387174395Sjkoshy		    M_PMC, M_WAITOK|M_ZERO);
4388174395Sjkoshy
4389174395Sjkoshy		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4390174395Sjkoshy			ps->ps_pc = sb->ps_callchains +
4391174395Sjkoshy			    (n * pmc_callchaindepth);
4392174395Sjkoshy
4393147191Sjkoshy		pmc_pcpu[cpu]->pc_sb = sb;
4394147191Sjkoshy	}
4395147191Sjkoshy
4396145256Sjkoshy	/* allocate space for the row disposition array */
4397145256Sjkoshy	pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4398145256Sjkoshy	    M_PMC, M_WAITOK|M_ZERO);
4399145256Sjkoshy
4400145256Sjkoshy	KASSERT(pmc_pmcdisp != NULL,
4401145256Sjkoshy	    ("[pmc,%d] pmcdisp allocation returned NULL", __LINE__));
4402145256Sjkoshy
4403145256Sjkoshy	/* mark all PMCs as available */
4404145256Sjkoshy	for (n = 0; n < (int) md->pmd_npmc; n++)
4405145256Sjkoshy		PMC_MARK_ROW_FREE(n);
4406145256Sjkoshy
4407145256Sjkoshy	/* allocate thread hash tables */
4408145256Sjkoshy	pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4409145256Sjkoshy	    &pmc_ownerhashmask);
4410145256Sjkoshy
4411145256Sjkoshy	pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4412145256Sjkoshy	    &pmc_processhashmask);
4413168856Sjkoshy	mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4414168856Sjkoshy	    MTX_SPIN);
4415145256Sjkoshy
4416147191Sjkoshy	LIST_INIT(&pmc_ss_owners);
4417147191Sjkoshy	pmc_ss_count = 0;
4418147191Sjkoshy
4419145256Sjkoshy	/* allocate a pool of spin mutexes */
4420168856Sjkoshy	pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4421168856Sjkoshy	    MTX_SPIN);
4422145256Sjkoshy
4423145256Sjkoshy	PMCDBG(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4424145256Sjkoshy	    "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4425145256Sjkoshy	    pmc_processhash, pmc_processhashmask);
4426145256Sjkoshy
4427145256Sjkoshy	/* register process {exit,fork,exec} handlers */
4428145256Sjkoshy	pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4429145256Sjkoshy	    pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4430145256Sjkoshy	pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4431145256Sjkoshy	    pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4432145256Sjkoshy
4433147191Sjkoshy	/* initialize logging */
4434147191Sjkoshy	pmclog_initialize();
4435147191Sjkoshy
4436145256Sjkoshy	/* set hook functions */
4437145256Sjkoshy	pmc_intr = md->pmd_intr;
4438145256Sjkoshy	pmc_hook = pmc_hook_handler;
4439145256Sjkoshy
4440145256Sjkoshy	if (error == 0) {
4441145256Sjkoshy		printf(PMC_MODULE_NAME ":");
4442149373Sjkoshy		for (n = 0; n < (int) md->pmd_nclass; n++) {
4443149373Sjkoshy			printf(" %s/%d/0x%b",
4444145774Sjkoshy			    pmc_name_of_pmcclass[md->pmd_classes[n].pm_class],
4445149373Sjkoshy			    md->pmd_nclasspmcs[n],
4446149373Sjkoshy			    md->pmd_classes[n].pm_caps,
4447149373Sjkoshy			    "\20"
4448149373Sjkoshy			    "\1INT\2USR\3SYS\4EDG\5THR"
4449149373Sjkoshy			    "\6REA\7WRI\10INV\11QUA\12PRC"
4450149373Sjkoshy			    "\13TAG\14CSC");
4451149373Sjkoshy		}
4452145256Sjkoshy		printf("\n");
4453145256Sjkoshy	}
4454145256Sjkoshy
4455145256Sjkoshy	return error;
4456145256Sjkoshy}
4457145256Sjkoshy
4458145256Sjkoshy/* prepare to be unloaded */
4459145256Sjkoshystatic void
4460145256Sjkoshypmc_cleanup(void)
4461145256Sjkoshy{
4462145256Sjkoshy	int cpu;
4463183266Sjkoshy	unsigned int maxcpu;
4464145256Sjkoshy	struct pmc_ownerhash *ph;
4465145256Sjkoshy	struct pmc_owner *po, *tmp;
4466145256Sjkoshy	struct pmc_binding pb;
4467153110Sru#ifdef	DEBUG
4468145256Sjkoshy	struct pmc_processhash *prh;
4469145256Sjkoshy#endif
4470145256Sjkoshy
4471145256Sjkoshy	PMCDBG(MOD,INI,0, "%s", "cleanup");
4472145256Sjkoshy
4473147191Sjkoshy	/* switch off sampling */
4474147191Sjkoshy	atomic_store_rel_int(&pmc_cpumask, 0);
4475147191Sjkoshy	pmc_intr = NULL;
4476145256Sjkoshy
4477145256Sjkoshy	sx_xlock(&pmc_sx);
4478145256Sjkoshy	if (pmc_hook == NULL) {	/* being unloaded already */
4479145256Sjkoshy		sx_xunlock(&pmc_sx);
4480145256Sjkoshy		return;
4481145256Sjkoshy	}
4482145256Sjkoshy
4483145256Sjkoshy	pmc_hook = NULL; /* prevent new threads from entering module */
4484145256Sjkoshy
4485145256Sjkoshy	/* deregister event handlers */
4486145256Sjkoshy	EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4487145256Sjkoshy	EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4488145256Sjkoshy
4489145256Sjkoshy	/* send SIGBUS to all owner threads, free up allocations */
4490145256Sjkoshy	if (pmc_ownerhash)
4491145256Sjkoshy		for (ph = pmc_ownerhash;
4492145256Sjkoshy		     ph <= &pmc_ownerhash[pmc_ownerhashmask];
4493145256Sjkoshy		     ph++) {
4494145256Sjkoshy			LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4495145256Sjkoshy				pmc_remove_owner(po);
4496145256Sjkoshy
4497145256Sjkoshy				/* send SIGBUS to owner processes */
4498145256Sjkoshy				PMCDBG(MOD,INI,2, "cleanup signal proc=%p "
4499145256Sjkoshy				    "(%d, %s)", po->po_owner,
4500145256Sjkoshy				    po->po_owner->p_pid,
4501145256Sjkoshy				    po->po_owner->p_comm);
4502145256Sjkoshy
4503145256Sjkoshy				PROC_LOCK(po->po_owner);
4504145256Sjkoshy				psignal(po->po_owner, SIGBUS);
4505145256Sjkoshy				PROC_UNLOCK(po->po_owner);
4506147191Sjkoshy
4507147191Sjkoshy				pmc_destroy_owner_descriptor(po);
4508145256Sjkoshy			}
4509145256Sjkoshy		}
4510145256Sjkoshy
4511145256Sjkoshy	/* reclaim allocated data structures */
4512145256Sjkoshy	if (pmc_mtxpool)
4513145256Sjkoshy		mtx_pool_destroy(&pmc_mtxpool);
4514145256Sjkoshy
4515145256Sjkoshy	mtx_destroy(&pmc_processhash_mtx);
4516145256Sjkoshy	if (pmc_processhash) {
4517153110Sru#ifdef	DEBUG
4518145256Sjkoshy		struct pmc_process *pp;
4519145256Sjkoshy
4520145256Sjkoshy		PMCDBG(MOD,INI,3, "%s", "destroy process hash");
4521145256Sjkoshy		for (prh = pmc_processhash;
4522145256Sjkoshy		     prh <= &pmc_processhash[pmc_processhashmask];
4523145256Sjkoshy		     prh++)
4524145256Sjkoshy			LIST_FOREACH(pp, prh, pp_next)
4525145256Sjkoshy			    PMCDBG(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
4526145256Sjkoshy#endif
4527145256Sjkoshy
4528145256Sjkoshy		hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
4529145256Sjkoshy		pmc_processhash = NULL;
4530145256Sjkoshy	}
4531145256Sjkoshy
4532145256Sjkoshy	if (pmc_ownerhash) {
4533145256Sjkoshy		PMCDBG(MOD,INI,3, "%s", "destroy owner hash");
4534145256Sjkoshy		hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
4535145256Sjkoshy		pmc_ownerhash = NULL;
4536145256Sjkoshy	}
4537145256Sjkoshy
4538147191Sjkoshy	KASSERT(LIST_EMPTY(&pmc_ss_owners),
4539147191Sjkoshy	    ("[pmc,%d] Global SS owner list not empty", __LINE__));
4540147191Sjkoshy	KASSERT(pmc_ss_count == 0,
4541147191Sjkoshy	    ("[pmc,%d] Global SS count not empty", __LINE__));
4542147191Sjkoshy
4543183266Sjkoshy	/* Free the per-cpu sample buffers. */
4544183266Sjkoshy	maxcpu = pmc_cpu_max();
4545183266Sjkoshy	for (cpu = 0; cpu < maxcpu; cpu++) {
4546183266Sjkoshy		if (!pmc_cpu_is_active(cpu))
4547153735Sjkoshy			continue;
4548153735Sjkoshy		KASSERT(pmc_pcpu[cpu]->pc_sb != NULL,
4549153735Sjkoshy		    ("[pmc,%d] Null cpu sample buffer cpu=%d", __LINE__,
4550153735Sjkoshy			cpu));
4551184205Sdes		free(pmc_pcpu[cpu]->pc_sb->ps_callchains, M_PMC);
4552184205Sdes		free(pmc_pcpu[cpu]->pc_sb, M_PMC);
4553153735Sjkoshy		pmc_pcpu[cpu]->pc_sb = NULL;
4554153735Sjkoshy	}
4555153735Sjkoshy
4556145256Sjkoshy 	/* do processor dependent cleanup */
4557145256Sjkoshy	PMCDBG(MOD,INI,3, "%s", "md cleanup");
4558145256Sjkoshy	if (md) {
4559145256Sjkoshy		pmc_save_cpu_binding(&pb);
4560183266Sjkoshy		for (cpu = 0; cpu < maxcpu; cpu++) {
4561145256Sjkoshy			PMCDBG(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
4562145256Sjkoshy			    cpu, pmc_pcpu[cpu]);
4563183266Sjkoshy			if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
4564145256Sjkoshy				continue;
4565145256Sjkoshy			pmc_select_cpu(cpu);
4566183266Sjkoshy			if (md->pmd_cleanup)
4567183266Sjkoshy				md->pmd_cleanup(cpu);
4568145256Sjkoshy		}
4569184205Sdes		free(md, M_PMC);
4570145256Sjkoshy		md = NULL;
4571145256Sjkoshy		pmc_restore_cpu_binding(&pb);
4572145256Sjkoshy	}
4573145256Sjkoshy
4574145256Sjkoshy	/* deallocate per-cpu structures */
4575184205Sdes	free(pmc_pcpu, M_PMC);
4576145256Sjkoshy	pmc_pcpu = NULL;
4577145256Sjkoshy
4578184205Sdes	free(pmc_pcpu_saved, M_PMC);
4579145256Sjkoshy	pmc_pcpu_saved = NULL;
4580145256Sjkoshy
4581145256Sjkoshy	if (pmc_pmcdisp) {
4582184205Sdes		free(pmc_pmcdisp, M_PMC);
4583145256Sjkoshy		pmc_pmcdisp = NULL;
4584145256Sjkoshy	}
4585145256Sjkoshy
4586147191Sjkoshy	pmclog_shutdown();
4587147191Sjkoshy
4588145256Sjkoshy	sx_xunlock(&pmc_sx); 	/* we are done */
4589145256Sjkoshy}
4590145256Sjkoshy
4591145256Sjkoshy/*
4592145256Sjkoshy * The function called at load/unload.
4593145256Sjkoshy */
4594145256Sjkoshy
4595145256Sjkoshystatic int
4596145256Sjkoshyload (struct module *module __unused, int cmd, void *arg __unused)
4597145256Sjkoshy{
4598145256Sjkoshy	int error;
4599145256Sjkoshy
4600145256Sjkoshy	error = 0;
4601145256Sjkoshy
4602145256Sjkoshy	switch (cmd) {
4603145256Sjkoshy	case MOD_LOAD :
4604145256Sjkoshy		/* initialize the subsystem */
4605145256Sjkoshy		error = pmc_initialize();
4606145256Sjkoshy		if (error != 0)
4607145256Sjkoshy			break;
4608183266Sjkoshy		PMCDBG(MOD,INI,1, "syscall=%d maxcpu=%d",
4609183266Sjkoshy		    pmc_syscall_num, pmc_cpu_max());
4610145256Sjkoshy		break;
4611145256Sjkoshy
4612145256Sjkoshy
4613145256Sjkoshy	case MOD_UNLOAD :
4614145256Sjkoshy	case MOD_SHUTDOWN:
4615145256Sjkoshy		pmc_cleanup();
4616145256Sjkoshy		PMCDBG(MOD,INI,1, "%s", "unloaded");
4617145256Sjkoshy		break;
4618145256Sjkoshy
4619145256Sjkoshy	default :
4620145256Sjkoshy		error = EINVAL;	/* XXX should panic(9) */
4621145256Sjkoshy		break;
4622145256Sjkoshy	}
4623145256Sjkoshy
4624145256Sjkoshy	return error;
4625145256Sjkoshy}
4626145256Sjkoshy
4627145256Sjkoshy/* memory pool */
4628145256SjkoshyMALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");
4629