hwpmc_mod.c revision 233628
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 233628 2012-03-28 20:58:30Z fabient $");
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>
44201151Sjkoshy#include <sys/mount.h>
45145256Sjkoshy#include <sys/mutex.h>
46145256Sjkoshy#include <sys/pmc.h>
47145256Sjkoshy#include <sys/pmckern.h>
48147191Sjkoshy#include <sys/pmclog.h>
49164033Srwatson#include <sys/priv.h>
50145256Sjkoshy#include <sys/proc.h>
51145256Sjkoshy#include <sys/queue.h>
52147191Sjkoshy#include <sys/resourcevar.h>
53145256Sjkoshy#include <sys/sched.h>
54145256Sjkoshy#include <sys/signalvar.h>
55145256Sjkoshy#include <sys/smp.h>
56145256Sjkoshy#include <sys/sx.h>
57145256Sjkoshy#include <sys/sysctl.h>
58145256Sjkoshy#include <sys/sysent.h>
59145256Sjkoshy#include <sys/systm.h>
60147191Sjkoshy#include <sys/vnode.h>
61145256Sjkoshy
62157144Sjkoshy#include <sys/linker.h>		/* needs to be after <sys/malloc.h> */
63157144Sjkoshy
64147191Sjkoshy#include <machine/atomic.h>
65145256Sjkoshy#include <machine/md_var.h>
66145256Sjkoshy
67201021Sjkoshy#include <vm/vm.h>
68201021Sjkoshy#include <vm/vm_extern.h>
69201021Sjkoshy#include <vm/pmap.h>
70201021Sjkoshy#include <vm/vm_map.h>
71201021Sjkoshy#include <vm/vm_object.h>
72201021Sjkoshy
73233628Sfabient#include "hwpmc_soft.h"
74233628Sfabient
75145256Sjkoshy/*
76145256Sjkoshy * Types
77145256Sjkoshy */
78145256Sjkoshy
79145256Sjkoshyenum pmc_flags {
80145256Sjkoshy	PMC_FLAG_NONE	  = 0x00, /* do nothing */
81145256Sjkoshy	PMC_FLAG_REMOVE   = 0x01, /* atomically remove entry from hash */
82145256Sjkoshy	PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
83145256Sjkoshy};
84145256Sjkoshy
85145256Sjkoshy/*
86145256Sjkoshy * The offset in sysent where the syscall is allocated.
87145256Sjkoshy */
88145256Sjkoshy
89145256Sjkoshystatic int pmc_syscall_num = NO_SYSCALL;
90145256Sjkoshystruct pmc_cpu		**pmc_pcpu;	 /* per-cpu state */
91145256Sjkoshypmc_value_t		*pmc_pcpu_saved; /* saved PMC values: CSW handling */
92145256Sjkoshy
93145256Sjkoshy#define	PMC_PCPU_SAVED(C,R)	pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
94145256Sjkoshy
95145256Sjkoshystruct mtx_pool		*pmc_mtxpool;
96145256Sjkoshystatic int		*pmc_pmcdisp;	 /* PMC row dispositions */
97145256Sjkoshy
98145256Sjkoshy#define	PMC_ROW_DISP_IS_FREE(R)		(pmc_pmcdisp[(R)] == 0)
99145256Sjkoshy#define	PMC_ROW_DISP_IS_THREAD(R)	(pmc_pmcdisp[(R)] > 0)
100145256Sjkoshy#define	PMC_ROW_DISP_IS_STANDALONE(R)	(pmc_pmcdisp[(R)] < 0)
101145256Sjkoshy
102145256Sjkoshy#define	PMC_MARK_ROW_FREE(R) do {					  \
103145256Sjkoshy	pmc_pmcdisp[(R)] = 0;						  \
104145256Sjkoshy} while (0)
105145256Sjkoshy
106145256Sjkoshy#define	PMC_MARK_ROW_STANDALONE(R) do {					  \
107145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
108145256Sjkoshy		    __LINE__));						  \
109145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
110183266Sjkoshy	KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()),		  \
111183266Sjkoshy		("[pmc,%d] row disposition error", __LINE__));		  \
112145256Sjkoshy} while (0)
113145256Sjkoshy
114145256Sjkoshy#define	PMC_UNMARK_ROW_STANDALONE(R) do { 				  \
115145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
116145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
117145256Sjkoshy		    __LINE__));						  \
118145256Sjkoshy} while (0)
119145256Sjkoshy
120145256Sjkoshy#define	PMC_MARK_ROW_THREAD(R) do {					  \
121145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
122145256Sjkoshy		    __LINE__));						  \
123145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
124145256Sjkoshy} while (0)
125145256Sjkoshy
126145256Sjkoshy#define	PMC_UNMARK_ROW_THREAD(R) do {					  \
127145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
128145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
129145256Sjkoshy		    __LINE__));						  \
130145256Sjkoshy} while (0)
131145256Sjkoshy
132145256Sjkoshy
133145256Sjkoshy/* various event handlers */
134145256Sjkoshystatic eventhandler_tag	pmc_exit_tag, pmc_fork_tag;
135145256Sjkoshy
136145256Sjkoshy/* Module statistics */
137145256Sjkoshystruct pmc_op_getdriverstats pmc_stats;
138145256Sjkoshy
139145256Sjkoshy/* Machine/processor dependent operations */
140185363Sjkoshystatic struct pmc_mdep  *md;
141145256Sjkoshy
142145256Sjkoshy/*
143145256Sjkoshy * Hash tables mapping owner processes and target threads to PMCs.
144145256Sjkoshy */
145145256Sjkoshy
146145256Sjkoshystruct mtx pmc_processhash_mtx;		/* spin mutex */
147145256Sjkoshystatic u_long pmc_processhashmask;
148145256Sjkoshystatic LIST_HEAD(pmc_processhash, pmc_process)	*pmc_processhash;
149145256Sjkoshy
150145256Sjkoshy/*
151145256Sjkoshy * Hash table of PMC owner descriptors.  This table is protected by
152145256Sjkoshy * the shared PMC "sx" lock.
153145256Sjkoshy */
154145256Sjkoshy
155145256Sjkoshystatic u_long pmc_ownerhashmask;
156145256Sjkoshystatic LIST_HEAD(pmc_ownerhash, pmc_owner)	*pmc_ownerhash;
157145256Sjkoshy
158145256Sjkoshy/*
159147191Sjkoshy * List of PMC owners with system-wide sampling PMCs.
160147191Sjkoshy */
161147191Sjkoshy
162147191Sjkoshystatic LIST_HEAD(, pmc_owner)			pmc_ss_owners;
163147191Sjkoshy
164147191Sjkoshy
165147191Sjkoshy/*
166184802Sjkoshy * A map of row indices to classdep structures.
167184802Sjkoshy */
168184802Sjkoshystatic struct pmc_classdep **pmc_rowindex_to_classdep;
169184802Sjkoshy
170184802Sjkoshy/*
171145256Sjkoshy * Prototypes
172145256Sjkoshy */
173145256Sjkoshy
174153110Sru#ifdef	DEBUG
175145256Sjkoshystatic int	pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
176145256Sjkoshystatic int	pmc_debugflags_parse(char *newstr, char *fence);
177145256Sjkoshy#endif
178145256Sjkoshy
179145256Sjkoshystatic int	load(struct module *module, int cmd, void *arg);
180147191Sjkoshystatic int	pmc_attach_process(struct proc *p, struct pmc *pm);
181145256Sjkoshystatic struct pmc *pmc_allocate_pmc_descriptor(void);
182147191Sjkoshystatic struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
183147191Sjkoshystatic int	pmc_attach_one_process(struct proc *p, struct pmc *pm);
184147191Sjkoshystatic int	pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
185147191Sjkoshy    int cpu);
186147191Sjkoshystatic int	pmc_can_attach(struct pmc *pm, struct proc *p);
187233628Sfabientstatic void	pmc_capture_user_callchain(int cpu, int soft, struct trapframe *tf);
188147191Sjkoshystatic void	pmc_cleanup(void);
189147191Sjkoshystatic int	pmc_detach_process(struct proc *p, struct pmc *pm);
190147191Sjkoshystatic int	pmc_detach_one_process(struct proc *p, struct pmc *pm,
191147191Sjkoshy    int flags);
192147191Sjkoshystatic void	pmc_destroy_owner_descriptor(struct pmc_owner *po);
193147191Sjkoshystatic struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
194147191Sjkoshystatic int	pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
195145256Sjkoshystatic struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
196145256Sjkoshy    pmc_id_t pmc);
197145256Sjkoshystatic struct pmc_process *pmc_find_process_descriptor(struct proc *p,
198145256Sjkoshy    uint32_t mode);
199145774Sjkoshystatic void	pmc_force_context_switch(void);
200145256Sjkoshystatic void	pmc_link_target_process(struct pmc *pm,
201145256Sjkoshy    struct pmc_process *pp);
202174395Sjkoshystatic void	pmc_log_all_process_mappings(struct pmc_owner *po);
203174395Sjkoshystatic void	pmc_log_kernel_mappings(struct pmc *pm);
204174395Sjkoshystatic void	pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
205147191Sjkoshystatic void	pmc_maybe_remove_owner(struct pmc_owner *po);
206147191Sjkoshystatic void	pmc_process_csw_in(struct thread *td);
207147191Sjkoshystatic void	pmc_process_csw_out(struct thread *td);
208145256Sjkoshystatic void	pmc_process_exit(void *arg, struct proc *p);
209145256Sjkoshystatic void	pmc_process_fork(void *arg, struct proc *p1,
210145256Sjkoshy    struct proc *p2, int n);
211233628Sfabientstatic void	pmc_process_samples(int cpu, int soft);
212147191Sjkoshystatic void	pmc_release_pmc_descriptor(struct pmc *pmc);
213147191Sjkoshystatic void	pmc_remove_owner(struct pmc_owner *po);
214147191Sjkoshystatic void	pmc_remove_process_descriptor(struct pmc_process *pp);
215147191Sjkoshystatic void	pmc_restore_cpu_binding(struct pmc_binding *pb);
216147191Sjkoshystatic void	pmc_save_cpu_binding(struct pmc_binding *pb);
217147191Sjkoshystatic void	pmc_select_cpu(int cpu);
218145256Sjkoshystatic int	pmc_start(struct pmc *pm);
219145256Sjkoshystatic int	pmc_stop(struct pmc *pm);
220147191Sjkoshystatic int	pmc_syscall_handler(struct thread *td, void *syscall_args);
221147191Sjkoshystatic void	pmc_unlink_target_process(struct pmc *pmc,
222147191Sjkoshy    struct pmc_process *pp);
223233628Sfabientstatic int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
224233628Sfabientstatic int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
225233628Sfabientstatic struct pmc_mdep *pmc_generic_cpu_initialize(void);
226233628Sfabientstatic void pmc_generic_cpu_finalize(struct pmc_mdep *md);
227145256Sjkoshy
228145256Sjkoshy/*
229145256Sjkoshy * Kernel tunables and sysctl(8) interface.
230145256Sjkoshy */
231145256Sjkoshy
232233628SfabientSYSCTL_DECL(_kern_hwpmc);
233145256Sjkoshy
234174395Sjkoshystatic int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
235174395SjkoshyTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "callchaindepth", &pmc_callchaindepth);
236174395SjkoshySYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_TUN|CTLFLAG_RD,
237174395Sjkoshy    &pmc_callchaindepth, 0, "depth of call chain records");
238174395Sjkoshy
239153110Sru#ifdef	DEBUG
240147191Sjkoshystruct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
241145256Sjkoshychar	pmc_debugstr[PMC_DEBUG_STRSIZE];
242145256SjkoshyTUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
243145256Sjkoshy    sizeof(pmc_debugstr));
244145256SjkoshySYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
245145256Sjkoshy    CTLTYPE_STRING|CTLFLAG_RW|CTLFLAG_TUN,
246145256Sjkoshy    0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
247145256Sjkoshy#endif
248145256Sjkoshy
249145256Sjkoshy/*
250147191Sjkoshy * kern.hwpmc.hashrows -- determines the number of rows in the
251145256Sjkoshy * of the hash table used to look up threads
252145256Sjkoshy */
253145256Sjkoshy
254145256Sjkoshystatic int pmc_hashsize = PMC_HASH_SIZE;
255145256SjkoshyTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "hashsize", &pmc_hashsize);
256145256SjkoshySYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_TUN|CTLFLAG_RD,
257145256Sjkoshy    &pmc_hashsize, 0, "rows in hash tables");
258145256Sjkoshy
259145256Sjkoshy/*
260174395Sjkoshy * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
261145256Sjkoshy */
262145256Sjkoshy
263147191Sjkoshystatic int pmc_nsamples = PMC_NSAMPLES;
264147191SjkoshyTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nsamples", &pmc_nsamples);
265147191SjkoshySYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_TUN|CTLFLAG_RD,
266147191Sjkoshy    &pmc_nsamples, 0, "number of PC samples per CPU");
267145256Sjkoshy
268174395Sjkoshy
269145256Sjkoshy/*
270147191Sjkoshy * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
271145256Sjkoshy */
272145256Sjkoshy
273145256Sjkoshystatic int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
274145256SjkoshyTUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "mtxpoolsize", &pmc_mtxpool_size);
275145256SjkoshySYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_TUN|CTLFLAG_RD,
276145256Sjkoshy    &pmc_mtxpool_size, 0, "size of spin mutex pool");
277145256Sjkoshy
278145256Sjkoshy
279145256Sjkoshy/*
280145256Sjkoshy * security.bsd.unprivileged_syspmcs -- allow non-root processes to
281145256Sjkoshy * allocate system-wide PMCs.
282145256Sjkoshy *
283145256Sjkoshy * Allowing unprivileged processes to allocate system PMCs is convenient
284145256Sjkoshy * if system-wide measurements need to be taken concurrently with other
285145256Sjkoshy * per-process measurements.  This feature is turned off by default.
286145256Sjkoshy */
287145256Sjkoshy
288145256Sjkoshystatic int pmc_unprivileged_syspmcs = 0;
289145256SjkoshyTUNABLE_INT("security.bsd.unprivileged_syspmcs", &pmc_unprivileged_syspmcs);
290145256SjkoshySYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RW,
291145256Sjkoshy    &pmc_unprivileged_syspmcs, 0,
292145256Sjkoshy    "allow unprivileged process to allocate system PMCs");
293145256Sjkoshy
294147191Sjkoshy/*
295147191Sjkoshy * Hash function.  Discard the lower 2 bits of the pointer since
296147191Sjkoshy * these are always zero for our uses.  The hash multiplier is
297147191Sjkoshy * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
298147191Sjkoshy */
299145256Sjkoshy
300145256Sjkoshy#if	LONG_BIT == 64
301145256Sjkoshy#define	_PMC_HM		11400714819323198486u
302145256Sjkoshy#elif	LONG_BIT == 32
303145256Sjkoshy#define	_PMC_HM		2654435769u
304145256Sjkoshy#else
305145256Sjkoshy#error 	Must know the size of 'long' to compile
306145256Sjkoshy#endif
307145256Sjkoshy
308145256Sjkoshy#define	PMC_HASH_PTR(P,M)	((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
309145256Sjkoshy
310145256Sjkoshy/*
311145256Sjkoshy * Syscall structures
312145256Sjkoshy */
313145256Sjkoshy
314145256Sjkoshy/* The `sysent' for the new syscall */
315145256Sjkoshystatic struct sysent pmc_sysent = {
316145256Sjkoshy	2,			/* sy_narg */
317145256Sjkoshy	pmc_syscall_handler	/* sy_call */
318145256Sjkoshy};
319145256Sjkoshy
320145256Sjkoshystatic struct syscall_module_data pmc_syscall_mod = {
321145256Sjkoshy	load,
322145256Sjkoshy	NULL,
323145256Sjkoshy	&pmc_syscall_num,
324145256Sjkoshy	&pmc_sysent,
325145256Sjkoshy	{ 0, NULL }
326145256Sjkoshy};
327145256Sjkoshy
328145256Sjkoshystatic moduledata_t pmc_mod = {
329145256Sjkoshy	PMC_MODULE_NAME,
330145256Sjkoshy	syscall_module_handler,
331145256Sjkoshy	&pmc_syscall_mod
332145256Sjkoshy};
333145256Sjkoshy
334145256SjkoshyDECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
335145256SjkoshyMODULE_VERSION(pmc, PMC_VERSION);
336145256Sjkoshy
337153110Sru#ifdef	DEBUG
338147191Sjkoshyenum pmc_dbgparse_state {
339147191Sjkoshy	PMCDS_WS,		/* in whitespace */
340147191Sjkoshy	PMCDS_MAJOR,		/* seen a major keyword */
341147191Sjkoshy	PMCDS_MINOR
342147191Sjkoshy};
343147191Sjkoshy
344145256Sjkoshystatic int
345145256Sjkoshypmc_debugflags_parse(char *newstr, char *fence)
346145256Sjkoshy{
347145313Sjkoshy	char c, *p, *q;
348147191Sjkoshy	struct pmc_debugflags *tmpflags;
349147191Sjkoshy	int error, found, *newbits, tmp;
350147191Sjkoshy	size_t kwlen;
351145256Sjkoshy
352184214Sdes	tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK|M_ZERO);
353145256Sjkoshy
354145256Sjkoshy	p = newstr;
355147191Sjkoshy	error = 0;
356145256Sjkoshy
357147191Sjkoshy	for (; p < fence && (c = *p); p++) {
358145256Sjkoshy
359147191Sjkoshy		/* skip white space */
360147191Sjkoshy		if (c == ' ' || c == '\t')
361147191Sjkoshy			continue;
362147191Sjkoshy
363147191Sjkoshy		/* look for a keyword followed by "=" */
364147191Sjkoshy		for (q = p; p < fence && (c = *p) && c != '='; p++)
365147191Sjkoshy			;
366147191Sjkoshy		if (c != '=') {
367147191Sjkoshy			error = EINVAL;
368147191Sjkoshy			goto done;
369145256Sjkoshy		}
370145256Sjkoshy
371147191Sjkoshy		kwlen = p - q;
372147191Sjkoshy		newbits = NULL;
373145256Sjkoshy
374147191Sjkoshy		/* lookup flag group name */
375147191Sjkoshy#define	DBG_SET_FLAG_MAJ(S,F)						\
376147191Sjkoshy		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
377147191Sjkoshy			newbits = &tmpflags->pdb_ ## F;
378145256Sjkoshy
379147191Sjkoshy		DBG_SET_FLAG_MAJ("cpu",		CPU);
380147191Sjkoshy		DBG_SET_FLAG_MAJ("csw",		CSW);
381147191Sjkoshy		DBG_SET_FLAG_MAJ("logging",	LOG);
382147191Sjkoshy		DBG_SET_FLAG_MAJ("module",	MOD);
383147191Sjkoshy		DBG_SET_FLAG_MAJ("md", 		MDP);
384147191Sjkoshy		DBG_SET_FLAG_MAJ("owner",	OWN);
385147191Sjkoshy		DBG_SET_FLAG_MAJ("pmc",		PMC);
386147191Sjkoshy		DBG_SET_FLAG_MAJ("process",	PRC);
387147191Sjkoshy		DBG_SET_FLAG_MAJ("sampling", 	SAM);
388145256Sjkoshy
389147191Sjkoshy		if (newbits == NULL) {
390147191Sjkoshy			error = EINVAL;
391147191Sjkoshy			goto done;
392145256Sjkoshy		}
393145256Sjkoshy
394147191Sjkoshy		p++;		/* skip the '=' */
395145256Sjkoshy
396147191Sjkoshy		/* Now parse the individual flags */
397147191Sjkoshy		tmp = 0;
398147191Sjkoshy	newflag:
399147191Sjkoshy		for (q = p; p < fence && (c = *p); p++)
400147191Sjkoshy			if (c == ' ' || c == '\t' || c == ',')
401147191Sjkoshy				break;
402147191Sjkoshy
403147191Sjkoshy		/* p == fence or c == ws or c == "," or c == 0 */
404147191Sjkoshy
405147191Sjkoshy		if ((kwlen = p - q) == 0) {
406147191Sjkoshy			*newbits = tmp;
407147191Sjkoshy			continue;
408147191Sjkoshy		}
409147191Sjkoshy
410147191Sjkoshy		found = 0;
411147191Sjkoshy#define	DBG_SET_FLAG_MIN(S,F)						\
412147191Sjkoshy		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
413147191Sjkoshy			tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
414147191Sjkoshy
415147191Sjkoshy		/* a '*' denotes all possible flags in the group */
416147191Sjkoshy		if (kwlen == 1 && *q == '*')
417147191Sjkoshy			tmp = found = ~0;
418147191Sjkoshy		/* look for individual flag names */
419147191Sjkoshy		DBG_SET_FLAG_MIN("allocaterow", ALR);
420147191Sjkoshy		DBG_SET_FLAG_MIN("allocate",	ALL);
421147191Sjkoshy		DBG_SET_FLAG_MIN("attach",	ATT);
422147191Sjkoshy		DBG_SET_FLAG_MIN("bind",	BND);
423147191Sjkoshy		DBG_SET_FLAG_MIN("config",	CFG);
424147191Sjkoshy		DBG_SET_FLAG_MIN("exec",	EXC);
425147191Sjkoshy		DBG_SET_FLAG_MIN("exit",	EXT);
426147191Sjkoshy		DBG_SET_FLAG_MIN("find",	FND);
427147191Sjkoshy		DBG_SET_FLAG_MIN("flush",	FLS);
428147191Sjkoshy		DBG_SET_FLAG_MIN("fork",	FRK);
429147191Sjkoshy		DBG_SET_FLAG_MIN("getbuf",	GTB);
430147191Sjkoshy		DBG_SET_FLAG_MIN("hook",	PMH);
431147191Sjkoshy		DBG_SET_FLAG_MIN("init",	INI);
432147191Sjkoshy		DBG_SET_FLAG_MIN("intr",	INT);
433147191Sjkoshy		DBG_SET_FLAG_MIN("linktarget",	TLK);
434147191Sjkoshy		DBG_SET_FLAG_MIN("mayberemove", OMR);
435147191Sjkoshy		DBG_SET_FLAG_MIN("ops",		OPS);
436147191Sjkoshy		DBG_SET_FLAG_MIN("read",	REA);
437147191Sjkoshy		DBG_SET_FLAG_MIN("register",	REG);
438147191Sjkoshy		DBG_SET_FLAG_MIN("release",	REL);
439147191Sjkoshy		DBG_SET_FLAG_MIN("remove",	ORM);
440147191Sjkoshy		DBG_SET_FLAG_MIN("sample",	SAM);
441147191Sjkoshy		DBG_SET_FLAG_MIN("scheduleio",	SIO);
442147191Sjkoshy		DBG_SET_FLAG_MIN("select",	SEL);
443147191Sjkoshy		DBG_SET_FLAG_MIN("signal",	SIG);
444147191Sjkoshy		DBG_SET_FLAG_MIN("swi",		SWI);
445147191Sjkoshy		DBG_SET_FLAG_MIN("swo",		SWO);
446147191Sjkoshy		DBG_SET_FLAG_MIN("start",	STA);
447147191Sjkoshy		DBG_SET_FLAG_MIN("stop",	STO);
448147191Sjkoshy		DBG_SET_FLAG_MIN("syscall",	PMS);
449147191Sjkoshy		DBG_SET_FLAG_MIN("unlinktarget", TUL);
450147191Sjkoshy		DBG_SET_FLAG_MIN("write",	WRI);
451147191Sjkoshy		if (found == 0) {
452147191Sjkoshy			/* unrecognized flag name */
453147191Sjkoshy			error = EINVAL;
454147191Sjkoshy			goto done;
455147191Sjkoshy		}
456147191Sjkoshy
457147191Sjkoshy		if (c == 0 || c == ' ' || c == '\t') {	/* end of flag group */
458147191Sjkoshy			*newbits = tmp;
459147191Sjkoshy			continue;
460147191Sjkoshy		}
461147191Sjkoshy
462147191Sjkoshy		p++;
463147191Sjkoshy		goto newflag;
464145256Sjkoshy	}
465145256Sjkoshy
466147191Sjkoshy	/* save the new flag set */
467147191Sjkoshy	bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
468145256Sjkoshy
469147191Sjkoshy done:
470184205Sdes	free(tmpflags, M_PMC);
471147191Sjkoshy	return error;
472145256Sjkoshy}
473145256Sjkoshy
474145256Sjkoshystatic int
475145256Sjkoshypmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
476145256Sjkoshy{
477145256Sjkoshy	char *fence, *newstr;
478145256Sjkoshy	int error;
479145256Sjkoshy	unsigned int n;
480145256Sjkoshy
481145256Sjkoshy	(void) arg1; (void) arg2; /* unused parameters */
482145256Sjkoshy
483145256Sjkoshy	n = sizeof(pmc_debugstr);
484184802Sjkoshy	newstr = malloc(n, M_PMC, M_WAITOK|M_ZERO);
485147191Sjkoshy	(void) strlcpy(newstr, pmc_debugstr, n);
486145256Sjkoshy
487145256Sjkoshy	error = sysctl_handle_string(oidp, newstr, n, req);
488145256Sjkoshy
489145256Sjkoshy	/* if there is a new string, parse and copy it */
490145256Sjkoshy	if (error == 0 && req->newptr != NULL) {
491147191Sjkoshy		fence = newstr + (n < req->newlen ? n : req->newlen + 1);
492145256Sjkoshy		if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
493145256Sjkoshy			(void) strlcpy(pmc_debugstr, newstr,
494145256Sjkoshy			    sizeof(pmc_debugstr));
495145256Sjkoshy	}
496145256Sjkoshy
497184205Sdes	free(newstr, M_PMC);
498145256Sjkoshy
499145256Sjkoshy	return error;
500145256Sjkoshy}
501145256Sjkoshy#endif
502145256Sjkoshy
503145256Sjkoshy/*
504184802Sjkoshy * Map a row index to a classdep structure and return the adjusted row
505184802Sjkoshy * index for the PMC class index.
506184802Sjkoshy */
507184802Sjkoshystatic struct pmc_classdep *
508184802Sjkoshypmc_ri_to_classdep(struct pmc_mdep *md, int ri, int *adjri)
509184802Sjkoshy{
510184802Sjkoshy	struct pmc_classdep *pcd;
511184802Sjkoshy
512184802Sjkoshy	(void) md;
513184802Sjkoshy
514184802Sjkoshy	KASSERT(ri >= 0 && ri < md->pmd_npmc,
515184802Sjkoshy	    ("[pmc,%d] illegal row-index %d", __LINE__, ri));
516184802Sjkoshy
517184802Sjkoshy	pcd = pmc_rowindex_to_classdep[ri];
518184802Sjkoshy
519184802Sjkoshy	KASSERT(pcd != NULL,
520198204Srpaulo	    ("[pmc,%d] ri %d null pcd", __LINE__, ri));
521184802Sjkoshy
522184802Sjkoshy	*adjri = ri - pcd->pcd_ri;
523184802Sjkoshy
524184802Sjkoshy	KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
525184802Sjkoshy	    ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));
526184802Sjkoshy
527184802Sjkoshy	return (pcd);
528184802Sjkoshy}
529184802Sjkoshy
530184802Sjkoshy/*
531145256Sjkoshy * Concurrency Control
532145256Sjkoshy *
533145256Sjkoshy * The driver manages the following data structures:
534145256Sjkoshy *
535145256Sjkoshy *   - target process descriptors, one per target process
536145256Sjkoshy *   - owner process descriptors (and attached lists), one per owner process
537145256Sjkoshy *   - lookup hash tables for owner and target processes
538145256Sjkoshy *   - PMC descriptors (and attached lists)
539145256Sjkoshy *   - per-cpu hardware state
540145256Sjkoshy *   - the 'hook' variable through which the kernel calls into
541145256Sjkoshy *     this module
542145256Sjkoshy *   - the machine hardware state (managed by the MD layer)
543145256Sjkoshy *
544145256Sjkoshy * These data structures are accessed from:
545145256Sjkoshy *
546145256Sjkoshy * - thread context-switch code
547145256Sjkoshy * - interrupt handlers (possibly on multiple cpus)
548145256Sjkoshy * - kernel threads on multiple cpus running on behalf of user
549145256Sjkoshy *   processes doing system calls
550145256Sjkoshy * - this driver's private kernel threads
551145256Sjkoshy *
552145256Sjkoshy * = Locks and Locking strategy =
553145256Sjkoshy *
554145256Sjkoshy * The driver uses four locking strategies for its operation:
555145256Sjkoshy *
556168856Sjkoshy * - The global SX lock "pmc_sx" is used to protect internal
557168856Sjkoshy *   data structures.
558145256Sjkoshy *
559168856Sjkoshy *   Calls into the module by syscall() start with this lock being
560168856Sjkoshy *   held in exclusive mode.  Depending on the requested operation,
561168856Sjkoshy *   the lock may be downgraded to 'shared' mode to allow more
562168856Sjkoshy *   concurrent readers into the module.  Calls into the module from
563168856Sjkoshy *   other parts of the kernel acquire the lock in shared mode.
564145256Sjkoshy *
565145256Sjkoshy *   This SX lock is held in exclusive mode for any operations that
566145256Sjkoshy *   modify the linkages between the driver's internal data structures.
567145256Sjkoshy *
568145256Sjkoshy *   The 'pmc_hook' function pointer is also protected by this lock.
569145256Sjkoshy *   It is only examined with the sx lock held in exclusive mode.  The
570168856Sjkoshy *   kernel module is allowed to be unloaded only with the sx lock held
571168856Sjkoshy *   in exclusive mode.  In normal syscall handling, after acquiring the
572168856Sjkoshy *   pmc_sx lock we first check that 'pmc_hook' is non-null before
573168856Sjkoshy *   proceeding.  This prevents races between the thread unloading the module
574168856Sjkoshy *   and other threads seeking to use the module.
575145256Sjkoshy *
576145256Sjkoshy * - Lookups of target process structures and owner process structures
577145256Sjkoshy *   cannot use the global "pmc_sx" SX lock because these lookups need
578145256Sjkoshy *   to happen during context switches and in other critical sections
579145256Sjkoshy *   where sleeping is not allowed.  We protect these lookup tables
580145256Sjkoshy *   with their own private spin-mutexes, "pmc_processhash_mtx" and
581168856Sjkoshy *   "pmc_ownerhash_mtx".
582145256Sjkoshy *
583145256Sjkoshy * - Interrupt handlers work in a lock free manner.  At interrupt
584145256Sjkoshy *   time, handlers look at the PMC pointer (phw->phw_pmc) configured
585145256Sjkoshy *   when the PMC was started.  If this pointer is NULL, the interrupt
586145256Sjkoshy *   is ignored after updating driver statistics.  We ensure that this
587145256Sjkoshy *   pointer is set (using an atomic operation if necessary) before the
588145256Sjkoshy *   PMC hardware is started.  Conversely, this pointer is unset atomically
589145256Sjkoshy *   only after the PMC hardware is stopped.
590145256Sjkoshy *
591145256Sjkoshy *   We ensure that everything needed for the operation of an
592145256Sjkoshy *   interrupt handler is available without it needing to acquire any
593145256Sjkoshy *   locks.  We also ensure that a PMC's software state is destroyed only
594145256Sjkoshy *   after the PMC is taken off hardware (on all CPUs).
595145256Sjkoshy *
596145256Sjkoshy * - Context-switch handling with process-private PMCs needs more
597145256Sjkoshy *   care.
598145256Sjkoshy *
599145256Sjkoshy *   A given process may be the target of multiple PMCs.  For example,
600145256Sjkoshy *   PMCATTACH and PMCDETACH may be requested by a process on one CPU
601145256Sjkoshy *   while the target process is running on another.  A PMC could also
602145256Sjkoshy *   be getting released because its owner is exiting.  We tackle
603145256Sjkoshy *   these situations in the following manner:
604145256Sjkoshy *
605145256Sjkoshy *   - each target process structure 'pmc_process' has an array
606145256Sjkoshy *     of 'struct pmc *' pointers, one for each hardware PMC.
607145256Sjkoshy *
608145256Sjkoshy *   - At context switch IN time, each "target" PMC in RUNNING state
609145256Sjkoshy *     gets started on hardware and a pointer to each PMC is copied into
610145256Sjkoshy *     the per-cpu phw array.  The 'runcount' for the PMC is
611145256Sjkoshy *     incremented.
612145256Sjkoshy *
613145256Sjkoshy *   - At context switch OUT time, all process-virtual PMCs are stopped
614145256Sjkoshy *     on hardware.  The saved value is added to the PMCs value field
615145256Sjkoshy *     only if the PMC is in a non-deleted state (the PMCs state could
616145256Sjkoshy *     have changed during the current time slice).
617145256Sjkoshy *
618145256Sjkoshy *     Note that since in-between a switch IN on a processor and a switch
619145256Sjkoshy *     OUT, the PMC could have been released on another CPU.  Therefore
620145256Sjkoshy *     context switch OUT always looks at the hardware state to turn
621145256Sjkoshy *     OFF PMCs and will update a PMC's saved value only if reachable
622145256Sjkoshy *     from the target process record.
623145256Sjkoshy *
624145256Sjkoshy *   - OP PMCRELEASE could be called on a PMC at any time (the PMC could
625145256Sjkoshy *     be attached to many processes at the time of the call and could
626145256Sjkoshy *     be active on multiple CPUs).
627145256Sjkoshy *
628145256Sjkoshy *     We prevent further scheduling of the PMC by marking it as in
629145256Sjkoshy *     state 'DELETED'.  If the runcount of the PMC is non-zero then
630145256Sjkoshy *     this PMC is currently running on a CPU somewhere.  The thread
631167086Sjhb *     doing the PMCRELEASE operation waits by repeatedly doing a
632167086Sjhb *     pause() till the runcount comes to zero.
633145256Sjkoshy *
634168856Sjkoshy * The contents of a PMC descriptor (struct pmc) are protected using
635168856Sjkoshy * a spin-mutex.  In order to save space, we use a mutex pool.
636168856Sjkoshy *
637168856Sjkoshy * In terms of lock types used by witness(4), we use:
638168856Sjkoshy * - Type "pmc-sx", used by the global SX lock.
639168856Sjkoshy * - Type "pmc-sleep", for sleep mutexes used by logger threads.
640168856Sjkoshy * - Type "pmc-per-proc", for protecting PMC owner descriptors.
641168856Sjkoshy * - Type "pmc-leaf", used for all other spin mutexes.
642145256Sjkoshy */
643145256Sjkoshy
644145256Sjkoshy/*
645145256Sjkoshy * save the cpu binding of the current kthread
646145256Sjkoshy */
647145256Sjkoshy
648145256Sjkoshystatic void
649145256Sjkoshypmc_save_cpu_binding(struct pmc_binding *pb)
650145256Sjkoshy{
651145256Sjkoshy	PMCDBG(CPU,BND,2, "%s", "save-cpu");
652170307Sjeff	thread_lock(curthread);
653145256Sjkoshy	pb->pb_bound = sched_is_bound(curthread);
654145256Sjkoshy	pb->pb_cpu   = curthread->td_oncpu;
655170307Sjeff	thread_unlock(curthread);
656145256Sjkoshy	PMCDBG(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
657145256Sjkoshy}
658145256Sjkoshy
659145256Sjkoshy/*
660145256Sjkoshy * restore the cpu binding of the current thread
661145256Sjkoshy */
662145256Sjkoshy
663145256Sjkoshystatic void
664145256Sjkoshypmc_restore_cpu_binding(struct pmc_binding *pb)
665145256Sjkoshy{
666145256Sjkoshy	PMCDBG(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
667145256Sjkoshy	    curthread->td_oncpu, pb->pb_cpu);
668170307Sjeff	thread_lock(curthread);
669145256Sjkoshy	if (pb->pb_bound)
670145256Sjkoshy		sched_bind(curthread, pb->pb_cpu);
671145256Sjkoshy	else
672145256Sjkoshy		sched_unbind(curthread);
673170307Sjeff	thread_unlock(curthread);
674145256Sjkoshy	PMCDBG(CPU,BND,2, "%s", "restore-cpu done");
675145256Sjkoshy}
676145256Sjkoshy
677145256Sjkoshy/*
678145256Sjkoshy * move execution over the specified cpu and bind it there.
679145256Sjkoshy */
680145256Sjkoshy
681145256Sjkoshystatic void
682145256Sjkoshypmc_select_cpu(int cpu)
683145256Sjkoshy{
684183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
685145256Sjkoshy	    ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
686145256Sjkoshy
687183266Sjkoshy	/* Never move to an inactive CPU. */
688183266Sjkoshy	KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
689183266Sjkoshy	    "CPU %d", __LINE__, cpu));
690145256Sjkoshy
691145256Sjkoshy	PMCDBG(CPU,SEL,2, "select-cpu cpu=%d", cpu);
692170307Sjeff	thread_lock(curthread);
693145256Sjkoshy	sched_bind(curthread, cpu);
694170307Sjeff	thread_unlock(curthread);
695145256Sjkoshy
696145256Sjkoshy	KASSERT(curthread->td_oncpu == cpu,
697145256Sjkoshy	    ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
698145256Sjkoshy		cpu, curthread->td_oncpu));
699145256Sjkoshy
700145256Sjkoshy	PMCDBG(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
701145256Sjkoshy}
702145256Sjkoshy
703145256Sjkoshy/*
704145774Sjkoshy * Force a context switch.
705145774Sjkoshy *
706167086Sjhb * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
707145774Sjkoshy * guaranteed to force a context switch.
708145774Sjkoshy */
709145774Sjkoshy
710145774Sjkoshystatic void
711145774Sjkoshypmc_force_context_switch(void)
712145774Sjkoshy{
713145774Sjkoshy
714167086Sjhb	pause("pmcctx", 1);
715145774Sjkoshy}
716145774Sjkoshy
717145774Sjkoshy/*
718147191Sjkoshy * Get the file name for an executable.  This is a simple wrapper
719147191Sjkoshy * around vn_fullpath(9).
720145256Sjkoshy */
721145256Sjkoshy
722147191Sjkoshystatic void
723147708Sjkoshypmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
724145256Sjkoshy{
725145256Sjkoshy
726147191Sjkoshy	*fullpath = "unknown";
727147191Sjkoshy	*freepath = NULL;
728175294Sattilio	vn_fullpath(curthread, v, fullpath, freepath);
729145256Sjkoshy}
730145256Sjkoshy
731145256Sjkoshy/*
732145256Sjkoshy * remove an process owning PMCs
733145256Sjkoshy */
734145256Sjkoshy
735145256Sjkoshyvoid
736145256Sjkoshypmc_remove_owner(struct pmc_owner *po)
737145256Sjkoshy{
738147191Sjkoshy	struct pmc *pm, *tmp;
739145256Sjkoshy
740145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
741145256Sjkoshy
742145256Sjkoshy	PMCDBG(OWN,ORM,1, "remove-owner po=%p", po);
743145256Sjkoshy
744145256Sjkoshy	/* Remove descriptor from the owner hash table */
745145256Sjkoshy	LIST_REMOVE(po, po_next);
746145256Sjkoshy
747147191Sjkoshy	/* release all owned PMC descriptors */
748147191Sjkoshy	LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
749147191Sjkoshy		PMCDBG(OWN,ORM,2, "pmc=%p", pm);
750147191Sjkoshy		KASSERT(pm->pm_owner == po,
751147191Sjkoshy		    ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
752145256Sjkoshy
753147191Sjkoshy		pmc_release_pmc_descriptor(pm);	/* will unlink from the list */
754145256Sjkoshy	}
755145256Sjkoshy
756147191Sjkoshy	KASSERT(po->po_sscount == 0,
757147191Sjkoshy	    ("[pmc,%d] SS count not zero", __LINE__));
758145256Sjkoshy	KASSERT(LIST_EMPTY(&po->po_pmcs),
759147191Sjkoshy	    ("[pmc,%d] PMC list not empty", __LINE__));
760145256Sjkoshy
761147191Sjkoshy	/* de-configure the log file if present */
762145774Sjkoshy	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
763147191Sjkoshy		pmclog_deconfigure_log(po);
764145256Sjkoshy}
765145256Sjkoshy
766145256Sjkoshy/*
767145256Sjkoshy * remove an owner process record if all conditions are met.
768145256Sjkoshy */
769145256Sjkoshy
770145256Sjkoshystatic void
771145256Sjkoshypmc_maybe_remove_owner(struct pmc_owner *po)
772145256Sjkoshy{
773145256Sjkoshy
774145256Sjkoshy	PMCDBG(OWN,OMR,1, "maybe-remove-owner po=%p", po);
775145256Sjkoshy
776145256Sjkoshy	/*
777145256Sjkoshy	 * Remove owner record if
778145256Sjkoshy	 * - this process does not own any PMCs
779145256Sjkoshy	 * - this process has not allocated a system-wide sampling buffer
780145256Sjkoshy	 */
781145256Sjkoshy
782145256Sjkoshy	if (LIST_EMPTY(&po->po_pmcs) &&
783145774Sjkoshy	    ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
784145256Sjkoshy		pmc_remove_owner(po);
785147191Sjkoshy		pmc_destroy_owner_descriptor(po);
786145256Sjkoshy	}
787145256Sjkoshy}
788145256Sjkoshy
789145256Sjkoshy/*
790145256Sjkoshy * Add an association between a target process and a PMC.
791145256Sjkoshy */
792145256Sjkoshy
793145256Sjkoshystatic void
794145256Sjkoshypmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
795145256Sjkoshy{
796145256Sjkoshy	int ri;
797145256Sjkoshy	struct pmc_target *pt;
798145256Sjkoshy
799145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
800145256Sjkoshy
801145256Sjkoshy	KASSERT(pm != NULL && pp != NULL,
802145256Sjkoshy	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
803147191Sjkoshy	KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
804147191Sjkoshy	    ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
805147191Sjkoshy		__LINE__, pm, pp->pp_proc->p_pid));
806198343Sfabient	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1),
807145256Sjkoshy	    ("[pmc,%d] Illegal reference count %d for process record %p",
808145256Sjkoshy		__LINE__, pp->pp_refcnt, (void *) pp));
809145256Sjkoshy
810145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
811145256Sjkoshy
812145256Sjkoshy	PMCDBG(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
813145256Sjkoshy	    pm, ri, pp);
814145256Sjkoshy
815153110Sru#ifdef	DEBUG
816145256Sjkoshy	LIST_FOREACH(pt, &pm->pm_targets, pt_next)
817145256Sjkoshy	    if (pt->pt_process == pp)
818145256Sjkoshy		    KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
819145256Sjkoshy				__LINE__, pp, pm));
820145256Sjkoshy#endif
821145256Sjkoshy
822184802Sjkoshy	pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK|M_ZERO);
823145256Sjkoshy	pt->pt_process = pp;
824145256Sjkoshy
825145256Sjkoshy	LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
826145256Sjkoshy
827148067Sjhb	atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
828148067Sjhb	    (uintptr_t)pm);
829145256Sjkoshy
830145615Sjkoshy	if (pm->pm_owner->po_owner == pp->pp_proc)
831145774Sjkoshy		pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
832145615Sjkoshy
833147191Sjkoshy	/*
834147191Sjkoshy	 * Initialize the per-process values at this row index.
835147191Sjkoshy	 */
836147191Sjkoshy	pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
837147191Sjkoshy	    pm->pm_sc.pm_reloadcount : 0;
838147191Sjkoshy
839145256Sjkoshy	pp->pp_refcnt++;
840145256Sjkoshy
841145256Sjkoshy}
842145256Sjkoshy
843145256Sjkoshy/*
844145256Sjkoshy * Removes the association between a target process and a PMC.
845145256Sjkoshy */
846145256Sjkoshy
847145256Sjkoshystatic void
848145256Sjkoshypmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
849145256Sjkoshy{
850145256Sjkoshy	int ri;
851147191Sjkoshy	struct proc *p;
852145256Sjkoshy	struct pmc_target *ptgt;
853145256Sjkoshy
854145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
855145256Sjkoshy
856145256Sjkoshy	KASSERT(pm != NULL && pp != NULL,
857145256Sjkoshy	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
858145256Sjkoshy
859198343Sfabient	KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc,
860145256Sjkoshy	    ("[pmc,%d] Illegal ref count %d on process record %p",
861145256Sjkoshy		__LINE__, pp->pp_refcnt, (void *) pp));
862145256Sjkoshy
863145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
864145256Sjkoshy
865145256Sjkoshy	PMCDBG(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
866145256Sjkoshy	    pm, ri, pp);
867145256Sjkoshy
868145256Sjkoshy	KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
869145256Sjkoshy	    ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
870145256Sjkoshy		ri, pm, pp->pp_pmcs[ri].pp_pmc));
871145256Sjkoshy
872145256Sjkoshy	pp->pp_pmcs[ri].pp_pmc = NULL;
873145256Sjkoshy	pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
874145256Sjkoshy
875145774Sjkoshy	/* Remove owner-specific flags */
876145774Sjkoshy	if (pm->pm_owner->po_owner == pp->pp_proc) {
877145774Sjkoshy		pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
878145774Sjkoshy		pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
879145774Sjkoshy	}
880145615Sjkoshy
881145256Sjkoshy	pp->pp_refcnt--;
882145256Sjkoshy
883145256Sjkoshy	/* Remove the target process from the PMC structure */
884145256Sjkoshy	LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
885145256Sjkoshy		if (ptgt->pt_process == pp)
886145256Sjkoshy			break;
887145256Sjkoshy
888145256Sjkoshy	KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
889145256Sjkoshy		    "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
890145256Sjkoshy
891145256Sjkoshy	LIST_REMOVE(ptgt, pt_next);
892184205Sdes	free(ptgt, M_PMC);
893145256Sjkoshy
894147191Sjkoshy	/* if the PMC now lacks targets, send the owner a SIGIO */
895147191Sjkoshy	if (LIST_EMPTY(&pm->pm_targets)) {
896147191Sjkoshy		p = pm->pm_owner->po_owner;
897147191Sjkoshy		PROC_LOCK(p);
898225617Skmacy		kern_psignal(p, SIGIO);
899147191Sjkoshy		PROC_UNLOCK(p);
900145256Sjkoshy
901147191Sjkoshy		PMCDBG(PRC,SIG,2, "signalling proc=%p signal=%d", p,
902147191Sjkoshy		    SIGIO);
903145256Sjkoshy	}
904145256Sjkoshy}
905145256Sjkoshy
906145256Sjkoshy/*
907145256Sjkoshy * Check if PMC 'pm' may be attached to target process 't'.
908145256Sjkoshy */
909145256Sjkoshy
910145256Sjkoshystatic int
911145256Sjkoshypmc_can_attach(struct pmc *pm, struct proc *t)
912145256Sjkoshy{
913145256Sjkoshy	struct proc *o;		/* pmc owner */
914145256Sjkoshy	struct ucred *oc, *tc;	/* owner, target credentials */
915145256Sjkoshy	int decline_attach, i;
916145256Sjkoshy
917145256Sjkoshy	/*
918145256Sjkoshy	 * A PMC's owner can always attach that PMC to itself.
919145256Sjkoshy	 */
920145256Sjkoshy
921145256Sjkoshy	if ((o = pm->pm_owner->po_owner) == t)
922145256Sjkoshy		return 0;
923145256Sjkoshy
924145256Sjkoshy	PROC_LOCK(o);
925145256Sjkoshy	oc = o->p_ucred;
926145256Sjkoshy	crhold(oc);
927145256Sjkoshy	PROC_UNLOCK(o);
928145256Sjkoshy
929145256Sjkoshy	PROC_LOCK(t);
930145256Sjkoshy	tc = t->p_ucred;
931145256Sjkoshy	crhold(tc);
932145256Sjkoshy	PROC_UNLOCK(t);
933145256Sjkoshy
934145256Sjkoshy	/*
935145256Sjkoshy	 * The effective uid of the PMC owner should match at least one
936145256Sjkoshy	 * of the {effective,real,saved} uids of the target process.
937145256Sjkoshy	 */
938145256Sjkoshy
939145256Sjkoshy	decline_attach = oc->cr_uid != tc->cr_uid &&
940145256Sjkoshy	    oc->cr_uid != tc->cr_svuid &&
941145256Sjkoshy	    oc->cr_uid != tc->cr_ruid;
942145256Sjkoshy
943145256Sjkoshy	/*
944145256Sjkoshy	 * Every one of the target's group ids, must be in the owner's
945145256Sjkoshy	 * group list.
946145256Sjkoshy	 */
947145256Sjkoshy	for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
948145256Sjkoshy		decline_attach = !groupmember(tc->cr_groups[i], oc);
949145256Sjkoshy
950145256Sjkoshy	/* check the read and saved gids too */
951145256Sjkoshy	if (decline_attach == 0)
952145256Sjkoshy		decline_attach = !groupmember(tc->cr_rgid, oc) ||
953145256Sjkoshy		    !groupmember(tc->cr_svgid, oc);
954145256Sjkoshy
955145256Sjkoshy	crfree(tc);
956145256Sjkoshy	crfree(oc);
957145256Sjkoshy
958145256Sjkoshy	return !decline_attach;
959145256Sjkoshy}
960145256Sjkoshy
961145256Sjkoshy/*
962145256Sjkoshy * Attach a process to a PMC.
963145256Sjkoshy */
964145256Sjkoshy
965145256Sjkoshystatic int
966145256Sjkoshypmc_attach_one_process(struct proc *p, struct pmc *pm)
967145256Sjkoshy{
968145256Sjkoshy	int ri;
969147191Sjkoshy	char *fullpath, *freepath;
970145256Sjkoshy	struct pmc_process	*pp;
971145256Sjkoshy
972145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
973145256Sjkoshy
974145256Sjkoshy	PMCDBG(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
975145774Sjkoshy	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
976145256Sjkoshy
977145256Sjkoshy	/*
978145256Sjkoshy	 * Locate the process descriptor corresponding to process 'p',
979145256Sjkoshy	 * allocating space as needed.
980145256Sjkoshy	 *
981145256Sjkoshy	 * Verify that rowindex 'pm_rowindex' is free in the process
982145256Sjkoshy	 * descriptor.
983145256Sjkoshy	 *
984145256Sjkoshy	 * If not, allocate space for a descriptor and link the
985145256Sjkoshy	 * process descriptor and PMC.
986145256Sjkoshy	 */
987145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
988145256Sjkoshy
989145256Sjkoshy	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
990145256Sjkoshy		return ENOMEM;
991145256Sjkoshy
992145256Sjkoshy	if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
993145256Sjkoshy		return EEXIST;
994145256Sjkoshy
995145256Sjkoshy	if (pp->pp_pmcs[ri].pp_pmc != NULL)
996145256Sjkoshy		return EBUSY;
997145256Sjkoshy
998145256Sjkoshy	pmc_link_target_process(pm, pp);
999145256Sjkoshy
1000147191Sjkoshy	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
1001147191Sjkoshy	    (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
1002147191Sjkoshy		pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
1003147191Sjkoshy
1004147191Sjkoshy	pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
1005147191Sjkoshy
1006147191Sjkoshy	/* issue an attach event to a configured log file */
1007147191Sjkoshy	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
1008147708Sjkoshy		pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1009180794Sjeff		if (p->p_flag & P_KTHREAD) {
1010180794Sjeff			fullpath = kernelname;
1011180794Sjeff			freepath = NULL;
1012180794Sjeff		} else
1013180794Sjeff			pmclog_process_pmcattach(pm, p->p_pid, fullpath);
1014147191Sjkoshy		if (freepath)
1015184205Sdes			free(freepath, M_TEMP);
1016174395Sjkoshy		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1017174395Sjkoshy			pmc_log_process_mappings(pm->pm_owner, p);
1018147191Sjkoshy	}
1019145256Sjkoshy	/* mark process as using HWPMCs */
1020145256Sjkoshy	PROC_LOCK(p);
1021145256Sjkoshy	p->p_flag |= P_HWPMC;
1022145256Sjkoshy	PROC_UNLOCK(p);
1023145256Sjkoshy
1024145256Sjkoshy	return 0;
1025145256Sjkoshy}
1026145256Sjkoshy
1027145256Sjkoshy/*
1028145256Sjkoshy * Attach a process and optionally its children
1029145256Sjkoshy */
1030145256Sjkoshy
1031145256Sjkoshystatic int
1032145256Sjkoshypmc_attach_process(struct proc *p, struct pmc *pm)
1033145256Sjkoshy{
1034145256Sjkoshy	int error;
1035145256Sjkoshy	struct proc *top;
1036145256Sjkoshy
1037145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1038145256Sjkoshy
1039145256Sjkoshy	PMCDBG(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1040145774Sjkoshy	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1041145256Sjkoshy
1042145774Sjkoshy
1043145774Sjkoshy	/*
1044145774Sjkoshy	 * If this PMC successfully allowed a GETMSR operation
1045145774Sjkoshy	 * in the past, disallow further ATTACHes.
1046145774Sjkoshy	 */
1047145774Sjkoshy
1048145774Sjkoshy	if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1049145774Sjkoshy		return EPERM;
1050145774Sjkoshy
1051145256Sjkoshy	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1052145256Sjkoshy		return pmc_attach_one_process(p, pm);
1053145256Sjkoshy
1054145256Sjkoshy	/*
1055145256Sjkoshy	 * Traverse all child processes, attaching them to
1056145256Sjkoshy	 * this PMC.
1057145256Sjkoshy	 */
1058145256Sjkoshy
1059145256Sjkoshy	sx_slock(&proctree_lock);
1060145256Sjkoshy
1061145256Sjkoshy	top = p;
1062145256Sjkoshy
1063145256Sjkoshy	for (;;) {
1064145256Sjkoshy		if ((error = pmc_attach_one_process(p, pm)) != 0)
1065145256Sjkoshy			break;
1066145256Sjkoshy		if (!LIST_EMPTY(&p->p_children))
1067145256Sjkoshy			p = LIST_FIRST(&p->p_children);
1068145256Sjkoshy		else for (;;) {
1069145256Sjkoshy			if (p == top)
1070145256Sjkoshy				goto done;
1071145256Sjkoshy			if (LIST_NEXT(p, p_sibling)) {
1072145256Sjkoshy				p = LIST_NEXT(p, p_sibling);
1073145256Sjkoshy				break;
1074145256Sjkoshy			}
1075145256Sjkoshy			p = p->p_pptr;
1076145256Sjkoshy		}
1077145256Sjkoshy	}
1078145256Sjkoshy
1079145256Sjkoshy	if (error)
1080145256Sjkoshy		(void) pmc_detach_process(top, pm);
1081145256Sjkoshy
1082145256Sjkoshy done:
1083145256Sjkoshy	sx_sunlock(&proctree_lock);
1084145256Sjkoshy	return error;
1085145256Sjkoshy}
1086145256Sjkoshy
1087145256Sjkoshy/*
1088145256Sjkoshy * Detach a process from a PMC.  If there are no other PMCs tracking
1089145256Sjkoshy * this process, remove the process structure from its hash table.  If
1090145256Sjkoshy * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1091145256Sjkoshy */
1092145256Sjkoshy
1093145256Sjkoshystatic int
1094145256Sjkoshypmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1095145256Sjkoshy{
1096145256Sjkoshy	int ri;
1097145256Sjkoshy	struct pmc_process *pp;
1098145256Sjkoshy
1099145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1100145256Sjkoshy
1101145256Sjkoshy	KASSERT(pm != NULL,
1102145256Sjkoshy	    ("[pmc,%d] null pm pointer", __LINE__));
1103145256Sjkoshy
1104145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
1105145774Sjkoshy
1106145256Sjkoshy	PMCDBG(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1107145774Sjkoshy	    pm, ri, p, p->p_pid, p->p_comm, flags);
1108145256Sjkoshy
1109145256Sjkoshy	if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1110145256Sjkoshy		return ESRCH;
1111145256Sjkoshy
1112145256Sjkoshy	if (pp->pp_pmcs[ri].pp_pmc != pm)
1113145256Sjkoshy		return EINVAL;
1114145256Sjkoshy
1115145256Sjkoshy	pmc_unlink_target_process(pm, pp);
1116145256Sjkoshy
1117147191Sjkoshy	/* Issue a detach entry if a log file is configured */
1118147191Sjkoshy	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1119147191Sjkoshy		pmclog_process_pmcdetach(pm, p->p_pid);
1120147191Sjkoshy
1121145256Sjkoshy	/*
1122145256Sjkoshy	 * If there are no PMCs targetting this process, we remove its
1123145256Sjkoshy	 * descriptor from the target hash table and unset the P_HWPMC
1124145256Sjkoshy	 * flag in the struct proc.
1125145256Sjkoshy	 */
1126198343Sfabient	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1127145256Sjkoshy	    ("[pmc,%d] Illegal refcnt %d for process struct %p",
1128145256Sjkoshy		__LINE__, pp->pp_refcnt, pp));
1129145256Sjkoshy
1130145256Sjkoshy	if (pp->pp_refcnt != 0)	/* still a target of some PMC */
1131145256Sjkoshy		return 0;
1132145256Sjkoshy
1133145256Sjkoshy	pmc_remove_process_descriptor(pp);
1134145256Sjkoshy
1135145256Sjkoshy	if (flags & PMC_FLAG_REMOVE)
1136184205Sdes		free(pp, M_PMC);
1137145256Sjkoshy
1138145256Sjkoshy	PROC_LOCK(p);
1139145256Sjkoshy	p->p_flag &= ~P_HWPMC;
1140145256Sjkoshy	PROC_UNLOCK(p);
1141145256Sjkoshy
1142145256Sjkoshy	return 0;
1143145256Sjkoshy}
1144145256Sjkoshy
1145145256Sjkoshy/*
1146145256Sjkoshy * Detach a process and optionally its descendants from a PMC.
1147145256Sjkoshy */
1148145256Sjkoshy
1149145256Sjkoshystatic int
1150145256Sjkoshypmc_detach_process(struct proc *p, struct pmc *pm)
1151145256Sjkoshy{
1152145256Sjkoshy	struct proc *top;
1153145256Sjkoshy
1154145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1155145256Sjkoshy
1156145256Sjkoshy	PMCDBG(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1157145774Sjkoshy	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1158145256Sjkoshy
1159145256Sjkoshy	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1160145256Sjkoshy		return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1161145256Sjkoshy
1162145256Sjkoshy	/*
1163145256Sjkoshy	 * Traverse all children, detaching them from this PMC.  We
1164145256Sjkoshy	 * ignore errors since we could be detaching a PMC from a
1165145256Sjkoshy	 * partially attached proc tree.
1166145256Sjkoshy	 */
1167145256Sjkoshy
1168145256Sjkoshy	sx_slock(&proctree_lock);
1169145256Sjkoshy
1170145256Sjkoshy	top = p;
1171145256Sjkoshy
1172145256Sjkoshy	for (;;) {
1173145256Sjkoshy		(void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1174145256Sjkoshy
1175145256Sjkoshy		if (!LIST_EMPTY(&p->p_children))
1176145256Sjkoshy			p = LIST_FIRST(&p->p_children);
1177145256Sjkoshy		else for (;;) {
1178145256Sjkoshy			if (p == top)
1179145256Sjkoshy				goto done;
1180145256Sjkoshy			if (LIST_NEXT(p, p_sibling)) {
1181145256Sjkoshy				p = LIST_NEXT(p, p_sibling);
1182145256Sjkoshy				break;
1183145256Sjkoshy			}
1184145256Sjkoshy			p = p->p_pptr;
1185145256Sjkoshy		}
1186145256Sjkoshy	}
1187145256Sjkoshy
1188145256Sjkoshy done:
1189145256Sjkoshy	sx_sunlock(&proctree_lock);
1190147191Sjkoshy
1191147191Sjkoshy	if (LIST_EMPTY(&pm->pm_targets))
1192147191Sjkoshy		pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1193147191Sjkoshy
1194145256Sjkoshy	return 0;
1195145256Sjkoshy}
1196145256Sjkoshy
1197147191Sjkoshy
1198145256Sjkoshy/*
1199147191Sjkoshy * Thread context switch IN
1200145256Sjkoshy */
1201145256Sjkoshy
1202147191Sjkoshystatic void
1203147191Sjkoshypmc_process_csw_in(struct thread *td)
1204147191Sjkoshy{
1205147191Sjkoshy	int cpu;
1206184802Sjkoshy	unsigned int adjri, ri;
1207147191Sjkoshy	struct pmc *pm;
1208147191Sjkoshy	struct proc *p;
1209147191Sjkoshy	struct pmc_cpu *pc;
1210147191Sjkoshy	struct pmc_hw *phw;
1211184802Sjkoshy	pmc_value_t newvalue;
1212147191Sjkoshy	struct pmc_process *pp;
1213184802Sjkoshy	struct pmc_classdep *pcd;
1214145256Sjkoshy
1215147191Sjkoshy	p = td->td_proc;
1216145256Sjkoshy
1217147191Sjkoshy	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1218147191Sjkoshy		return;
1219145256Sjkoshy
1220147191Sjkoshy	KASSERT(pp->pp_proc == td->td_proc,
1221147191Sjkoshy	    ("[pmc,%d] not my thread state", __LINE__));
1222145256Sjkoshy
1223147191Sjkoshy	critical_enter(); /* no preemption from this point */
1224145256Sjkoshy
1225147191Sjkoshy	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1226145256Sjkoshy
1227147191Sjkoshy	PMCDBG(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1228147191Sjkoshy	    p->p_pid, p->p_comm, pp);
1229145256Sjkoshy
1230183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1231147191Sjkoshy	    ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
1232145256Sjkoshy
1233147191Sjkoshy	pc = pmc_pcpu[cpu];
1234145256Sjkoshy
1235147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++) {
1236145256Sjkoshy
1237147191Sjkoshy		if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1238147191Sjkoshy			continue;
1239147191Sjkoshy
1240147191Sjkoshy		KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1241147191Sjkoshy		    ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1242147191Sjkoshy			__LINE__, PMC_TO_MODE(pm)));
1243147191Sjkoshy
1244147191Sjkoshy		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1245147191Sjkoshy		    ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1246147191Sjkoshy			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1247147191Sjkoshy
1248145256Sjkoshy		/*
1249147191Sjkoshy		 * Only PMCs that are marked as 'RUNNING' need
1250147191Sjkoshy		 * be placed on hardware.
1251145256Sjkoshy		 */
1252145256Sjkoshy
1253147191Sjkoshy		if (pm->pm_state != PMC_STATE_RUNNING)
1254147191Sjkoshy			continue;
1255145256Sjkoshy
1256147191Sjkoshy		/* increment PMC runcount */
1257208861Sfabient		atomic_add_rel_int(&pm->pm_runcount, 1);
1258145256Sjkoshy
1259147191Sjkoshy		/* configure the HWPMC we are going to use. */
1260184802Sjkoshy		pcd = pmc_ri_to_classdep(md, ri, &adjri);
1261184802Sjkoshy		pcd->pcd_config_pmc(cpu, adjri, pm);
1262145256Sjkoshy
1263147191Sjkoshy		phw = pc->pc_hwpmcs[ri];
1264145256Sjkoshy
1265147191Sjkoshy		KASSERT(phw != NULL,
1266147191Sjkoshy		    ("[pmc,%d] null hw pointer", __LINE__));
1267145256Sjkoshy
1268147191Sjkoshy		KASSERT(phw->phw_pmc == pm,
1269147191Sjkoshy		    ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1270147191Sjkoshy			phw->phw_pmc, pm));
1271145256Sjkoshy
1272147191Sjkoshy		/*
1273147191Sjkoshy		 * Write out saved value and start the PMC.
1274147191Sjkoshy		 *
1275147191Sjkoshy		 * Sampling PMCs use a per-process value, while
1276147191Sjkoshy		 * counting mode PMCs use a per-pmc value that is
1277147191Sjkoshy		 * inherited across descendants.
1278147191Sjkoshy		 */
1279147191Sjkoshy		if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1280147191Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
1281147191Sjkoshy			newvalue = PMC_PCPU_SAVED(cpu,ri) =
1282147191Sjkoshy			    pp->pp_pmcs[ri].pp_pmcval;
1283147191Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1284147191Sjkoshy		} else {
1285147191Sjkoshy			KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1286147191Sjkoshy			    ("[pmc,%d] illegal mode=%d", __LINE__,
1287147191Sjkoshy			    PMC_TO_MODE(pm)));
1288147191Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
1289147191Sjkoshy			newvalue = PMC_PCPU_SAVED(cpu, ri) =
1290147191Sjkoshy			    pm->pm_gv.pm_savedvalue;
1291147191Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1292147191Sjkoshy		}
1293145256Sjkoshy
1294147191Sjkoshy		PMCDBG(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1295145256Sjkoshy
1296184802Sjkoshy		pcd->pcd_write_pmc(cpu, adjri, newvalue);
1297184802Sjkoshy		pcd->pcd_start_pmc(cpu, adjri);
1298147191Sjkoshy	}
1299145256Sjkoshy
1300147191Sjkoshy	/*
1301147191Sjkoshy	 * perform any other architecture/cpu dependent thread
1302147191Sjkoshy	 * switch-in actions.
1303147191Sjkoshy	 */
1304145256Sjkoshy
1305147191Sjkoshy	(void) (*md->pmd_switch_in)(pc, pp);
1306145256Sjkoshy
1307147191Sjkoshy	critical_exit();
1308145256Sjkoshy
1309147191Sjkoshy}
1310145256Sjkoshy
1311147191Sjkoshy/*
1312147191Sjkoshy * Thread context switch OUT.
1313147191Sjkoshy */
1314145256Sjkoshy
1315147191Sjkoshystatic void
1316147191Sjkoshypmc_process_csw_out(struct thread *td)
1317147191Sjkoshy{
1318147191Sjkoshy	int cpu;
1319184802Sjkoshy	int64_t tmp;
1320147191Sjkoshy	struct pmc *pm;
1321147191Sjkoshy	struct proc *p;
1322184802Sjkoshy	enum pmc_mode mode;
1323147191Sjkoshy	struct pmc_cpu *pc;
1324184802Sjkoshy	pmc_value_t newvalue;
1325184802Sjkoshy	unsigned int adjri, ri;
1326147191Sjkoshy	struct pmc_process *pp;
1327184802Sjkoshy	struct pmc_classdep *pcd;
1328145256Sjkoshy
1329184802Sjkoshy
1330147191Sjkoshy	/*
1331147191Sjkoshy	 * Locate our process descriptor; this may be NULL if
1332147191Sjkoshy	 * this process is exiting and we have already removed
1333147191Sjkoshy	 * the process from the target process table.
1334147191Sjkoshy	 *
1335147191Sjkoshy	 * Note that due to kernel preemption, multiple
1336147191Sjkoshy	 * context switches may happen while the process is
1337147191Sjkoshy	 * exiting.
1338147191Sjkoshy	 *
1339147191Sjkoshy	 * Note also that if the target process cannot be
1340147191Sjkoshy	 * found we still need to deconfigure any PMCs that
1341147191Sjkoshy	 * are currently running on hardware.
1342147191Sjkoshy	 */
1343145256Sjkoshy
1344147191Sjkoshy	p = td->td_proc;
1345147191Sjkoshy	pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1346145256Sjkoshy
1347147191Sjkoshy	/*
1348147191Sjkoshy	 * save PMCs
1349147191Sjkoshy	 */
1350145256Sjkoshy
1351147191Sjkoshy	critical_enter();
1352145774Sjkoshy
1353147191Sjkoshy	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1354145256Sjkoshy
1355147191Sjkoshy	PMCDBG(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1356147191Sjkoshy	    p->p_pid, p->p_comm, pp);
1357145615Sjkoshy
1358183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1359147191Sjkoshy	    ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1360145615Sjkoshy
1361147191Sjkoshy	pc = pmc_pcpu[cpu];
1362145615Sjkoshy
1363147191Sjkoshy	/*
1364147191Sjkoshy	 * When a PMC gets unlinked from a target PMC, it will
1365147191Sjkoshy	 * be removed from the target's pp_pmc[] array.
1366147191Sjkoshy	 *
1367147191Sjkoshy	 * However, on a MP system, the target could have been
1368147191Sjkoshy	 * executing on another CPU at the time of the unlink.
1369147191Sjkoshy	 * So, at context switch OUT time, we need to look at
1370147191Sjkoshy	 * the hardware to determine if a PMC is scheduled on
1371147191Sjkoshy	 * it.
1372147191Sjkoshy	 */
1373145256Sjkoshy
1374147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++) {
1375145256Sjkoshy
1376184802Sjkoshy		pcd = pmc_ri_to_classdep(md, ri, &adjri);
1377184802Sjkoshy		pm  = NULL;
1378184802Sjkoshy		(void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
1379145256Sjkoshy
1380147191Sjkoshy		if (pm == NULL)	/* nothing at this row index */
1381147191Sjkoshy			continue;
1382145256Sjkoshy
1383147191Sjkoshy		mode = PMC_TO_MODE(pm);
1384147191Sjkoshy		if (!PMC_IS_VIRTUAL_MODE(mode))
1385147191Sjkoshy			continue; /* not a process virtual PMC */
1386145774Sjkoshy
1387147191Sjkoshy		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1388147191Sjkoshy		    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1389147191Sjkoshy			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1390145256Sjkoshy
1391147191Sjkoshy		/* Stop hardware if not already stopped */
1392147867Sjkoshy		if (pm->pm_stalled == 0)
1393184802Sjkoshy			pcd->pcd_stop_pmc(cpu, adjri);
1394147191Sjkoshy
1395147191Sjkoshy		/* reduce this PMC's runcount */
1396208861Sfabient		atomic_subtract_rel_int(&pm->pm_runcount, 1);
1397147191Sjkoshy
1398145256Sjkoshy		/*
1399147191Sjkoshy		 * If this PMC is associated with this process,
1400147191Sjkoshy		 * save the reading.
1401145256Sjkoshy		 */
1402145256Sjkoshy
1403147191Sjkoshy		if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1404147191Sjkoshy
1405147191Sjkoshy			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1406147191Sjkoshy			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1407147191Sjkoshy				pm, ri, pp->pp_pmcs[ri].pp_pmc));
1408147191Sjkoshy
1409147191Sjkoshy			KASSERT(pp->pp_refcnt > 0,
1410147191Sjkoshy			    ("[pmc,%d] pp refcnt = %d", __LINE__,
1411147191Sjkoshy				pp->pp_refcnt));
1412147191Sjkoshy
1413184802Sjkoshy			pcd->pcd_read_pmc(cpu, adjri, &newvalue);
1414147191Sjkoshy
1415147191Sjkoshy			tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1416147191Sjkoshy
1417199972Semaste			PMCDBG(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
1418147191Sjkoshy			    tmp);
1419147191Sjkoshy
1420147191Sjkoshy			if (mode == PMC_MODE_TS) {
1421147191Sjkoshy
1422147191Sjkoshy				/*
1423147191Sjkoshy				 * For sampling process-virtual PMCs,
1424147191Sjkoshy				 * we expect the count to be
1425147191Sjkoshy				 * decreasing as the 'value'
1426147191Sjkoshy				 * programmed into the PMC is the
1427147191Sjkoshy				 * number of events to be seen till
1428147191Sjkoshy				 * the next sampling interrupt.
1429147191Sjkoshy				 */
1430147191Sjkoshy				if (tmp < 0)
1431147191Sjkoshy					tmp += pm->pm_sc.pm_reloadcount;
1432147191Sjkoshy				mtx_pool_lock_spin(pmc_mtxpool, pm);
1433147191Sjkoshy				pp->pp_pmcs[ri].pp_pmcval -= tmp;
1434147191Sjkoshy				if ((int64_t) pp->pp_pmcs[ri].pp_pmcval < 0)
1435147191Sjkoshy					pp->pp_pmcs[ri].pp_pmcval +=
1436147191Sjkoshy					    pm->pm_sc.pm_reloadcount;
1437147191Sjkoshy				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1438147191Sjkoshy
1439147191Sjkoshy			} else {
1440147191Sjkoshy
1441147191Sjkoshy				/*
1442147191Sjkoshy				 * For counting process-virtual PMCs,
1443147191Sjkoshy				 * we expect the count to be
1444147191Sjkoshy				 * increasing monotonically, modulo a 64
1445147191Sjkoshy				 * bit wraparound.
1446147191Sjkoshy				 */
1447147191Sjkoshy				KASSERT((int64_t) tmp >= 0,
1448147191Sjkoshy				    ("[pmc,%d] negative increment cpu=%d "
1449147191Sjkoshy				     "ri=%d newvalue=%jx saved=%jx "
1450147191Sjkoshy				     "incr=%jx", __LINE__, cpu, ri,
1451147191Sjkoshy				     newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1452147191Sjkoshy
1453147191Sjkoshy				mtx_pool_lock_spin(pmc_mtxpool, pm);
1454147191Sjkoshy				pm->pm_gv.pm_savedvalue += tmp;
1455147191Sjkoshy				pp->pp_pmcs[ri].pp_pmcval += tmp;
1456147191Sjkoshy				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1457147191Sjkoshy
1458147191Sjkoshy				if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1459147191Sjkoshy					pmclog_process_proccsw(pm, pp, tmp);
1460147191Sjkoshy			}
1461145256Sjkoshy		}
1462145256Sjkoshy
1463147191Sjkoshy		/* mark hardware as free */
1464184802Sjkoshy		pcd->pcd_config_pmc(cpu, adjri, NULL);
1465145256Sjkoshy	}
1466145256Sjkoshy
1467145256Sjkoshy	/*
1468147191Sjkoshy	 * perform any other architecture/cpu dependent thread
1469147191Sjkoshy	 * switch out functions.
1470147191Sjkoshy	 */
1471147191Sjkoshy
1472147191Sjkoshy	(void) (*md->pmd_switch_out)(pc, pp);
1473147191Sjkoshy
1474147191Sjkoshy	critical_exit();
1475147191Sjkoshy}
1476147191Sjkoshy
1477147191Sjkoshy/*
1478157144Sjkoshy * Log a KLD operation.
1479157144Sjkoshy */
1480157144Sjkoshy
1481157144Sjkoshystatic void
1482157144Sjkoshypmc_process_kld_load(struct pmckern_map_in *pkm)
1483157144Sjkoshy{
1484157144Sjkoshy	struct pmc_owner *po;
1485157144Sjkoshy
1486157144Sjkoshy	sx_assert(&pmc_sx, SX_LOCKED);
1487157144Sjkoshy
1488157144Sjkoshy	/*
1489157144Sjkoshy	 * Notify owners of system sampling PMCs about KLD operations.
1490157144Sjkoshy	 */
1491157144Sjkoshy
1492157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1493157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1494157144Sjkoshy	    	pmclog_process_map_in(po, (pid_t) -1, pkm->pm_address,
1495157144Sjkoshy		    (char *) pkm->pm_file);
1496157144Sjkoshy
1497157144Sjkoshy	/*
1498157144Sjkoshy	 * TODO: Notify owners of (all) process-sampling PMCs too.
1499157144Sjkoshy	 */
1500157144Sjkoshy
1501157144Sjkoshy	return;
1502157144Sjkoshy}
1503157144Sjkoshy
1504157144Sjkoshystatic void
1505157144Sjkoshypmc_process_kld_unload(struct pmckern_map_out *pkm)
1506157144Sjkoshy{
1507157144Sjkoshy	struct pmc_owner *po;
1508157144Sjkoshy
1509157144Sjkoshy	sx_assert(&pmc_sx, SX_LOCKED);
1510157144Sjkoshy
1511157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1512157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1513157144Sjkoshy		pmclog_process_map_out(po, (pid_t) -1,
1514157144Sjkoshy		    pkm->pm_address, pkm->pm_address + pkm->pm_size);
1515174395Sjkoshy
1516157144Sjkoshy	/*
1517157144Sjkoshy	 * TODO: Notify owners of process-sampling PMCs.
1518157144Sjkoshy	 */
1519157144Sjkoshy}
1520157144Sjkoshy
1521157144Sjkoshy/*
1522157144Sjkoshy * A mapping change for a process.
1523157144Sjkoshy */
1524157144Sjkoshy
1525157144Sjkoshystatic void
1526157144Sjkoshypmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1527157144Sjkoshy{
1528157144Sjkoshy	int ri;
1529157144Sjkoshy	pid_t pid;
1530157144Sjkoshy	char *fullpath, *freepath;
1531157144Sjkoshy	const struct pmc *pm;
1532157144Sjkoshy	struct pmc_owner *po;
1533157144Sjkoshy	const struct pmc_process *pp;
1534157144Sjkoshy
1535157144Sjkoshy	freepath = fullpath = NULL;
1536157144Sjkoshy	pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1537157144Sjkoshy
1538157144Sjkoshy	pid = td->td_proc->p_pid;
1539157144Sjkoshy
1540157144Sjkoshy	/* Inform owners of all system-wide sampling PMCs. */
1541157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1542157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1543157144Sjkoshy		pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1544157144Sjkoshy
1545157144Sjkoshy	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1546157144Sjkoshy		goto done;
1547157144Sjkoshy
1548157144Sjkoshy	/*
1549157144Sjkoshy	 * Inform sampling PMC owners tracking this process.
1550157144Sjkoshy	 */
1551157144Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
1552157144Sjkoshy		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1553157144Sjkoshy		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1554157144Sjkoshy			pmclog_process_map_in(pm->pm_owner,
1555157144Sjkoshy			    pid, pkm->pm_address, fullpath);
1556157144Sjkoshy
1557157144Sjkoshy  done:
1558157144Sjkoshy	if (freepath)
1559184205Sdes		free(freepath, M_TEMP);
1560157144Sjkoshy}
1561157144Sjkoshy
1562157144Sjkoshy
1563157144Sjkoshy/*
1564157144Sjkoshy * Log an munmap request.
1565157144Sjkoshy */
1566157144Sjkoshy
1567157144Sjkoshystatic void
1568157144Sjkoshypmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1569157144Sjkoshy{
1570157144Sjkoshy	int ri;
1571157144Sjkoshy	pid_t pid;
1572157144Sjkoshy	struct pmc_owner *po;
1573157144Sjkoshy	const struct pmc *pm;
1574157144Sjkoshy	const struct pmc_process *pp;
1575157144Sjkoshy
1576157144Sjkoshy	pid = td->td_proc->p_pid;
1577157144Sjkoshy
1578157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1579157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1580157144Sjkoshy		pmclog_process_map_out(po, pid, pkm->pm_address,
1581157144Sjkoshy		    pkm->pm_address + pkm->pm_size);
1582157144Sjkoshy
1583157144Sjkoshy	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1584157144Sjkoshy		return;
1585157144Sjkoshy
1586157144Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
1587157144Sjkoshy		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1588157144Sjkoshy		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1589157651Sjkoshy			pmclog_process_map_out(pm->pm_owner, pid,
1590157651Sjkoshy			    pkm->pm_address, pkm->pm_address + pkm->pm_size);
1591157144Sjkoshy}
1592157144Sjkoshy
1593157144Sjkoshy/*
1594174395Sjkoshy * Log mapping information about the kernel.
1595174395Sjkoshy */
1596174395Sjkoshy
1597174395Sjkoshystatic void
1598174395Sjkoshypmc_log_kernel_mappings(struct pmc *pm)
1599174395Sjkoshy{
1600174395Sjkoshy	struct pmc_owner *po;
1601174395Sjkoshy	struct pmckern_map_in *km, *kmbase;
1602174395Sjkoshy
1603174395Sjkoshy	sx_assert(&pmc_sx, SX_LOCKED);
1604174395Sjkoshy	KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1605174395Sjkoshy	    ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1606174395Sjkoshy		__LINE__, (void *) pm));
1607174395Sjkoshy
1608174395Sjkoshy	po = pm->pm_owner;
1609174395Sjkoshy
1610174395Sjkoshy	if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1611174395Sjkoshy		return;
1612174395Sjkoshy
1613174395Sjkoshy	/*
1614174395Sjkoshy	 * Log the current set of kernel modules.
1615174395Sjkoshy	 */
1616174395Sjkoshy	kmbase = linker_hwpmc_list_objects();
1617174395Sjkoshy	for (km = kmbase; km->pm_file != NULL; km++) {
1618174395Sjkoshy		PMCDBG(LOG,REG,1,"%s %p", (char *) km->pm_file,
1619174395Sjkoshy		    (void *) km->pm_address);
1620174395Sjkoshy		pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1621174395Sjkoshy		    km->pm_file);
1622174395Sjkoshy	}
1623184205Sdes	free(kmbase, M_LINKER);
1624174395Sjkoshy
1625174395Sjkoshy	po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1626174395Sjkoshy}
1627174395Sjkoshy
1628174395Sjkoshy/*
1629174395Sjkoshy * Log the mappings for a single process.
1630174395Sjkoshy */
1631174395Sjkoshy
1632174395Sjkoshystatic void
1633174395Sjkoshypmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1634174395Sjkoshy{
1635201151Sjkoshy	int locked;
1636201021Sjkoshy	vm_map_t map;
1637201021Sjkoshy	struct vnode *vp;
1638201021Sjkoshy	struct vmspace *vm;
1639201021Sjkoshy	vm_map_entry_t entry;
1640201021Sjkoshy	vm_offset_t last_end;
1641201021Sjkoshy	u_int last_timestamp;
1642201021Sjkoshy	struct vnode *last_vp;
1643201021Sjkoshy	vm_offset_t start_addr;
1644201021Sjkoshy	vm_object_t obj, lobj, tobj;
1645201021Sjkoshy	char *fullpath, *freepath;
1646201021Sjkoshy
1647201021Sjkoshy	last_vp = NULL;
1648201021Sjkoshy	last_end = (vm_offset_t) 0;
1649201021Sjkoshy	fullpath = freepath = NULL;
1650201021Sjkoshy
1651201021Sjkoshy	if ((vm = vmspace_acquire_ref(p)) == NULL)
1652201021Sjkoshy		return;
1653201021Sjkoshy
1654201021Sjkoshy	map = &vm->vm_map;
1655201021Sjkoshy	vm_map_lock_read(map);
1656201021Sjkoshy
1657201021Sjkoshy	for (entry = map->header.next; entry != &map->header; entry = entry->next) {
1658201021Sjkoshy
1659201021Sjkoshy		if (entry == NULL) {
1660201021Sjkoshy			PMCDBG(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly "
1661201021Sjkoshy			    "NULL! pid=%d vm_map=%p\n", p->p_pid, map);
1662201021Sjkoshy			break;
1663201021Sjkoshy		}
1664201021Sjkoshy
1665201021Sjkoshy		/*
1666201021Sjkoshy		 * We only care about executable map entries.
1667201021Sjkoshy		 */
1668201021Sjkoshy		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) ||
1669201021Sjkoshy		    !(entry->protection & VM_PROT_EXECUTE) ||
1670201021Sjkoshy		    (entry->object.vm_object == NULL)) {
1671201021Sjkoshy			continue;
1672201021Sjkoshy		}
1673201021Sjkoshy
1674201021Sjkoshy		obj = entry->object.vm_object;
1675201021Sjkoshy		VM_OBJECT_LOCK(obj);
1676201021Sjkoshy
1677201021Sjkoshy		/*
1678201021Sjkoshy		 * Walk the backing_object list to find the base
1679201021Sjkoshy		 * (non-shadowed) vm_object.
1680201021Sjkoshy		 */
1681201021Sjkoshy		for (lobj = tobj = obj; tobj != NULL; tobj = tobj->backing_object) {
1682201021Sjkoshy			if (tobj != obj)
1683201021Sjkoshy				VM_OBJECT_LOCK(tobj);
1684201021Sjkoshy			if (lobj != obj)
1685201021Sjkoshy				VM_OBJECT_UNLOCK(lobj);
1686201021Sjkoshy			lobj = tobj;
1687201021Sjkoshy		}
1688201021Sjkoshy
1689201021Sjkoshy		/*
1690201021Sjkoshy		 * At this point lobj is the base vm_object and it is locked.
1691201021Sjkoshy		 */
1692201021Sjkoshy		if (lobj == NULL) {
1693201021Sjkoshy			PMCDBG(LOG,OPS,2, "hwpmc: lobj unexpectedly NULL! pid=%d "
1694201021Sjkoshy			    "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj);
1695201021Sjkoshy			VM_OBJECT_UNLOCK(obj);
1696201021Sjkoshy			continue;
1697201021Sjkoshy		}
1698201021Sjkoshy
1699201021Sjkoshy		if (lobj->type != OBJT_VNODE || lobj->handle == NULL) {
1700201021Sjkoshy			if (lobj != obj)
1701201021Sjkoshy				VM_OBJECT_UNLOCK(lobj);
1702201021Sjkoshy			VM_OBJECT_UNLOCK(obj);
1703201021Sjkoshy			continue;
1704201021Sjkoshy		}
1705201021Sjkoshy
1706201021Sjkoshy		/*
1707201021Sjkoshy		 * Skip contiguous regions that point to the same
1708201021Sjkoshy		 * vnode, so we don't emit redundant MAP-IN
1709201021Sjkoshy		 * directives.
1710201021Sjkoshy		 */
1711201021Sjkoshy		if (entry->start == last_end && lobj->handle == last_vp) {
1712201021Sjkoshy			last_end = entry->end;
1713201021Sjkoshy			if (lobj != obj)
1714201021Sjkoshy				VM_OBJECT_UNLOCK(lobj);
1715201021Sjkoshy			VM_OBJECT_UNLOCK(obj);
1716201021Sjkoshy			continue;
1717201021Sjkoshy		}
1718201021Sjkoshy
1719201021Sjkoshy		/*
1720201021Sjkoshy		 * We don't want to keep the proc's vm_map or this
1721201021Sjkoshy		 * vm_object locked while we walk the pathname, since
1722201021Sjkoshy		 * vn_fullpath() can sleep.  However, if we drop the
1723201021Sjkoshy		 * lock, it's possible for concurrent activity to
1724201021Sjkoshy		 * modify the vm_map list.  To protect against this,
1725201021Sjkoshy		 * we save the vm_map timestamp before we release the
1726201021Sjkoshy		 * lock, and check it after we reacquire the lock
1727201021Sjkoshy		 * below.
1728201021Sjkoshy		 */
1729201021Sjkoshy		start_addr = entry->start;
1730201021Sjkoshy		last_end = entry->end;
1731201021Sjkoshy		last_timestamp = map->timestamp;
1732201021Sjkoshy		vm_map_unlock_read(map);
1733201021Sjkoshy
1734201021Sjkoshy		vp = lobj->handle;
1735201021Sjkoshy		vref(vp);
1736201021Sjkoshy		if (lobj != obj)
1737201021Sjkoshy			VM_OBJECT_UNLOCK(lobj);
1738201021Sjkoshy
1739201021Sjkoshy		VM_OBJECT_UNLOCK(obj);
1740201021Sjkoshy
1741201021Sjkoshy		freepath = NULL;
1742201021Sjkoshy		pmc_getfilename(vp, &fullpath, &freepath);
1743201021Sjkoshy		last_vp = vp;
1744201151Sjkoshy
1745201151Sjkoshy		locked = VFS_LOCK_GIANT(vp->v_mount);
1746201021Sjkoshy		vrele(vp);
1747201151Sjkoshy		VFS_UNLOCK_GIANT(locked);
1748201151Sjkoshy
1749201021Sjkoshy		vp = NULL;
1750201021Sjkoshy		pmclog_process_map_in(po, p->p_pid, start_addr, fullpath);
1751201021Sjkoshy		if (freepath)
1752201021Sjkoshy			free(freepath, M_TEMP);
1753201021Sjkoshy
1754201021Sjkoshy		vm_map_lock_read(map);
1755201021Sjkoshy
1756201021Sjkoshy		/*
1757201021Sjkoshy		 * If our saved timestamp doesn't match, this means
1758201021Sjkoshy		 * that the vm_map was modified out from under us and
1759201021Sjkoshy		 * we can't trust our current "entry" pointer.  Do a
1760201021Sjkoshy		 * new lookup for this entry.  If there is no entry
1761201021Sjkoshy		 * for this address range, vm_map_lookup_entry() will
1762201021Sjkoshy		 * return the previous one, so we always want to go to
1763201021Sjkoshy		 * entry->next on the next loop iteration.
1764201021Sjkoshy		 *
1765201021Sjkoshy		 * There is an edge condition here that can occur if
1766201021Sjkoshy		 * there is no entry at or before this address.  In
1767201021Sjkoshy		 * this situation, vm_map_lookup_entry returns
1768201021Sjkoshy		 * &map->header, which would cause our loop to abort
1769201021Sjkoshy		 * without processing the rest of the map.  However,
1770201021Sjkoshy		 * in practice this will never happen for process
1771201021Sjkoshy		 * vm_map.  This is because the executable's text
1772201021Sjkoshy		 * segment is the first mapping in the proc's address
1773201021Sjkoshy		 * space, and this mapping is never removed until the
1774201021Sjkoshy		 * process exits, so there will always be a non-header
1775201021Sjkoshy		 * entry at or before the requested address for
1776201021Sjkoshy		 * vm_map_lookup_entry to return.
1777201021Sjkoshy		 */
1778201021Sjkoshy		if (map->timestamp != last_timestamp)
1779201021Sjkoshy			vm_map_lookup_entry(map, last_end - 1, &entry);
1780201021Sjkoshy	}
1781201021Sjkoshy
1782201021Sjkoshy	vm_map_unlock_read(map);
1783201021Sjkoshy	vmspace_free(vm);
1784201021Sjkoshy	return;
1785174395Sjkoshy}
1786174395Sjkoshy
1787174395Sjkoshy/*
1788174395Sjkoshy * Log mappings for all processes in the system.
1789174395Sjkoshy */
1790174395Sjkoshy
1791174395Sjkoshystatic void
1792174395Sjkoshypmc_log_all_process_mappings(struct pmc_owner *po)
1793174395Sjkoshy{
1794174395Sjkoshy	struct proc *p, *top;
1795174395Sjkoshy
1796174395Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1797174395Sjkoshy
1798174395Sjkoshy	if ((p = pfind(1)) == NULL)
1799174395Sjkoshy		panic("[pmc,%d] Cannot find init", __LINE__);
1800174395Sjkoshy
1801174395Sjkoshy	PROC_UNLOCK(p);
1802174395Sjkoshy
1803174395Sjkoshy	sx_slock(&proctree_lock);
1804174395Sjkoshy
1805174395Sjkoshy	top = p;
1806174395Sjkoshy
1807174395Sjkoshy	for (;;) {
1808174395Sjkoshy		pmc_log_process_mappings(po, p);
1809174395Sjkoshy		if (!LIST_EMPTY(&p->p_children))
1810174395Sjkoshy			p = LIST_FIRST(&p->p_children);
1811174395Sjkoshy		else for (;;) {
1812174395Sjkoshy			if (p == top)
1813174395Sjkoshy				goto done;
1814174395Sjkoshy			if (LIST_NEXT(p, p_sibling)) {
1815174395Sjkoshy				p = LIST_NEXT(p, p_sibling);
1816174395Sjkoshy				break;
1817174395Sjkoshy			}
1818174395Sjkoshy			p = p->p_pptr;
1819174395Sjkoshy		}
1820174395Sjkoshy	}
1821174395Sjkoshy done:
1822174395Sjkoshy	sx_sunlock(&proctree_lock);
1823174395Sjkoshy}
1824174395Sjkoshy
1825174395Sjkoshy/*
1826147191Sjkoshy * The 'hook' invoked from the kernel proper
1827147191Sjkoshy */
1828147191Sjkoshy
1829147191Sjkoshy
1830153110Sru#ifdef	DEBUG
1831147191Sjkoshyconst char *pmc_hooknames[] = {
1832157144Sjkoshy	/* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1833147191Sjkoshy	"",
1834147191Sjkoshy	"EXEC",
1835147191Sjkoshy	"CSW-IN",
1836147191Sjkoshy	"CSW-OUT",
1837157144Sjkoshy	"SAMPLE",
1838157144Sjkoshy	"KLDLOAD",
1839157144Sjkoshy	"KLDUNLOAD",
1840157144Sjkoshy	"MMAP",
1841174395Sjkoshy	"MUNMAP",
1842233628Sfabient	"CALLCHAIN-NMI",
1843233628Sfabient	"CALLCHAIN-SOFT",
1844233628Sfabient	"SOFTSAMPLING"
1845147191Sjkoshy};
1846147191Sjkoshy#endif
1847147191Sjkoshy
1848147191Sjkoshystatic int
1849147191Sjkoshypmc_hook_handler(struct thread *td, int function, void *arg)
1850147191Sjkoshy{
1851147191Sjkoshy
1852147191Sjkoshy	PMCDBG(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1853147191Sjkoshy	    pmc_hooknames[function], arg);
1854147191Sjkoshy
1855147191Sjkoshy	switch (function)
1856147191Sjkoshy	{
1857147191Sjkoshy
1858147191Sjkoshy	/*
1859145256Sjkoshy	 * Process exec()
1860145256Sjkoshy	 */
1861145256Sjkoshy
1862145256Sjkoshy	case PMC_FN_PROCESS_EXEC:
1863145256Sjkoshy	{
1864147191Sjkoshy		char *fullpath, *freepath;
1865145256Sjkoshy		unsigned int ri;
1866147191Sjkoshy		int is_using_hwpmcs;
1867145256Sjkoshy		struct pmc *pm;
1868145256Sjkoshy		struct proc *p;
1869145256Sjkoshy		struct pmc_owner *po;
1870145256Sjkoshy		struct pmc_process *pp;
1871147708Sjkoshy		struct pmckern_procexec *pk;
1872145256Sjkoshy
1873145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
1874145256Sjkoshy
1875147191Sjkoshy		p = td->td_proc;
1876147708Sjkoshy		pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1877147191Sjkoshy
1878147708Sjkoshy		pk = (struct pmckern_procexec *) arg;
1879147708Sjkoshy
1880147191Sjkoshy		/* Inform owners of SS mode PMCs of the exec event. */
1881147191Sjkoshy		LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1882147191Sjkoshy		    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1883147708Sjkoshy			    pmclog_process_procexec(po, PMC_ID_INVALID,
1884147708Sjkoshy				p->p_pid, pk->pm_entryaddr, fullpath);
1885147191Sjkoshy
1886147191Sjkoshy		PROC_LOCK(p);
1887147191Sjkoshy		is_using_hwpmcs = p->p_flag & P_HWPMC;
1888147191Sjkoshy		PROC_UNLOCK(p);
1889147191Sjkoshy
1890147191Sjkoshy		if (!is_using_hwpmcs) {
1891147191Sjkoshy			if (freepath)
1892184205Sdes				free(freepath, M_TEMP);
1893147191Sjkoshy			break;
1894147191Sjkoshy		}
1895147191Sjkoshy
1896145256Sjkoshy		/*
1897145256Sjkoshy		 * PMCs are not inherited across an exec():  remove any
1898145256Sjkoshy		 * PMCs that this process is the owner of.
1899145256Sjkoshy		 */
1900145256Sjkoshy
1901145256Sjkoshy		if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1902145256Sjkoshy			pmc_remove_owner(po);
1903147191Sjkoshy			pmc_destroy_owner_descriptor(po);
1904145256Sjkoshy		}
1905145256Sjkoshy
1906145256Sjkoshy		/*
1907154483Sjkoshy		 * If the process being exec'ed is not the target of any
1908154483Sjkoshy		 * PMC, we are done.
1909145256Sjkoshy		 */
1910154483Sjkoshy		if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1911154483Sjkoshy			if (freepath)
1912184205Sdes				free(freepath, M_TEMP);
1913145256Sjkoshy			break;
1914154483Sjkoshy		}
1915145256Sjkoshy
1916147191Sjkoshy		/*
1917147191Sjkoshy		 * Log the exec event to all monitoring owners.  Skip
1918147191Sjkoshy		 * owners who have already recieved the event because
1919154483Sjkoshy		 * they had system sampling PMCs active.
1920147191Sjkoshy		 */
1921147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
1922147191Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1923147191Sjkoshy				po = pm->pm_owner;
1924147191Sjkoshy				if (po->po_sscount == 0 &&
1925147191Sjkoshy				    po->po_flags & PMC_PO_OWNS_LOGFILE)
1926147708Sjkoshy					pmclog_process_procexec(po, pm->pm_id,
1927147708Sjkoshy					    p->p_pid, pk->pm_entryaddr,
1928147191Sjkoshy					    fullpath);
1929147191Sjkoshy			}
1930147191Sjkoshy
1931147191Sjkoshy		if (freepath)
1932184205Sdes			free(freepath, M_TEMP);
1933147191Sjkoshy
1934145256Sjkoshy
1935145256Sjkoshy		PMCDBG(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1936147708Sjkoshy		    p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1937145256Sjkoshy
1938147708Sjkoshy		if (pk->pm_credentialschanged == 0) /* no change */
1939145256Sjkoshy			break;
1940145256Sjkoshy
1941145256Sjkoshy		/*
1942145256Sjkoshy		 * If the newly exec()'ed process has a different credential
1943145256Sjkoshy		 * than before, allow it to be the target of a PMC only if
1944145256Sjkoshy		 * the PMC's owner has sufficient priviledge.
1945145256Sjkoshy		 */
1946145256Sjkoshy
1947145256Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
1948145256Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1949145256Sjkoshy				if (pmc_can_attach(pm, td->td_proc) != 0)
1950145256Sjkoshy					pmc_detach_one_process(td->td_proc,
1951145256Sjkoshy					    pm, PMC_FLAG_NONE);
1952145256Sjkoshy
1953198343Sfabient		KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1954145256Sjkoshy		    ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1955145256Sjkoshy			pp->pp_refcnt, pp));
1956145256Sjkoshy
1957145256Sjkoshy		/*
1958145256Sjkoshy		 * If this process is no longer the target of any
1959145256Sjkoshy		 * PMCs, we can remove the process entry and free
1960145256Sjkoshy		 * up space.
1961145256Sjkoshy		 */
1962145256Sjkoshy
1963145256Sjkoshy		if (pp->pp_refcnt == 0) {
1964145256Sjkoshy			pmc_remove_process_descriptor(pp);
1965184205Sdes			free(pp, M_PMC);
1966147191Sjkoshy			break;
1967145256Sjkoshy		}
1968145256Sjkoshy
1969145256Sjkoshy	}
1970145256Sjkoshy	break;
1971145256Sjkoshy
1972145256Sjkoshy	case PMC_FN_CSW_IN:
1973147191Sjkoshy		pmc_process_csw_in(td);
1974147191Sjkoshy		break;
1975145256Sjkoshy
1976147191Sjkoshy	case PMC_FN_CSW_OUT:
1977147191Sjkoshy		pmc_process_csw_out(td);
1978147191Sjkoshy		break;
1979145256Sjkoshy
1980145256Sjkoshy	/*
1981147191Sjkoshy	 * Process accumulated PC samples.
1982147191Sjkoshy	 *
1983147191Sjkoshy	 * This function is expected to be called by hardclock() for
1984147191Sjkoshy	 * each CPU that has accumulated PC samples.
1985147191Sjkoshy	 *
1986147191Sjkoshy	 * This function is to be executed on the CPU whose samples
1987147191Sjkoshy	 * are being processed.
1988145256Sjkoshy	 */
1989147191Sjkoshy	case PMC_FN_DO_SAMPLES:
1990145256Sjkoshy
1991145256Sjkoshy		/*
1992147191Sjkoshy		 * Clear the cpu specific bit in the CPU mask before
1993147191Sjkoshy		 * do the rest of the processing.  If the NMI handler
1994147191Sjkoshy		 * gets invoked after the "atomic_clear_int()" call
1995147191Sjkoshy		 * below but before "pmc_process_samples()" gets
1996147191Sjkoshy		 * around to processing the interrupt, then we will
1997147191Sjkoshy		 * come back here at the next hardclock() tick (and
1998147191Sjkoshy		 * may find nothing to do if "pmc_process_samples()"
1999147191Sjkoshy		 * had already processed the interrupt).  We don't
2000147191Sjkoshy		 * lose the interrupt sample.
2001145256Sjkoshy		 */
2002222813Sattilio		CPU_CLR_ATOMIC(PCPU_GET(cpuid), &pmc_cpumask);
2003233628Sfabient		pmc_process_samples(PCPU_GET(cpuid), PMC_HR);
2004233628Sfabient		pmc_process_samples(PCPU_GET(cpuid), PMC_SR);
2005147191Sjkoshy		break;
2006145256Sjkoshy
2007157144Sjkoshy
2008157144Sjkoshy	case PMC_FN_KLD_LOAD:
2009157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
2010157144Sjkoshy		pmc_process_kld_load((struct pmckern_map_in *) arg);
2011157144Sjkoshy		break;
2012157144Sjkoshy
2013157144Sjkoshy	case PMC_FN_KLD_UNLOAD:
2014157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
2015157144Sjkoshy		pmc_process_kld_unload((struct pmckern_map_out *) arg);
2016157144Sjkoshy		break;
2017157144Sjkoshy
2018157144Sjkoshy	case PMC_FN_MMAP:
2019157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
2020157144Sjkoshy		pmc_process_mmap(td, (struct pmckern_map_in *) arg);
2021157144Sjkoshy		break;
2022157144Sjkoshy
2023157144Sjkoshy	case PMC_FN_MUNMAP:
2024157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
2025157144Sjkoshy		pmc_process_munmap(td, (struct pmckern_map_out *) arg);
2026157144Sjkoshy		break;
2027157144Sjkoshy
2028174395Sjkoshy	case PMC_FN_USER_CALLCHAIN:
2029174395Sjkoshy		/*
2030174395Sjkoshy		 * Record a call chain.
2031174395Sjkoshy		 */
2032186037Sjkoshy		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2033186037Sjkoshy		    __LINE__));
2034233628Sfabient
2035233628Sfabient		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
2036174395Sjkoshy		    (struct trapframe *) arg);
2037186037Sjkoshy		td->td_pflags &= ~TDP_CALLCHAIN;
2038174395Sjkoshy		break;
2039174395Sjkoshy
2040233628Sfabient	case PMC_FN_USER_CALLCHAIN_SOFT:
2041233628Sfabient		/*
2042233628Sfabient		 * Record a call chain.
2043233628Sfabient		 */
2044233628Sfabient		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2045233628Sfabient		    __LINE__));
2046233628Sfabient		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_SR,
2047233628Sfabient		    (struct trapframe *) arg);
2048233628Sfabient		td->td_pflags &= ~TDP_CALLCHAIN;
2049233628Sfabient		break;
2050233628Sfabient
2051233628Sfabient	case PMC_FN_SOFT_SAMPLING:
2052233628Sfabient		/*
2053233628Sfabient		 * Call soft PMC sampling intr.
2054233628Sfabient		 */
2055233628Sfabient		pmc_soft_intr((struct pmckern_soft *) arg);
2056233628Sfabient		break;
2057233628Sfabient
2058145256Sjkoshy	default:
2059153110Sru#ifdef	DEBUG
2060145256Sjkoshy		KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
2061145256Sjkoshy#endif
2062145256Sjkoshy		break;
2063145256Sjkoshy
2064145256Sjkoshy	}
2065145256Sjkoshy
2066145256Sjkoshy	return 0;
2067145256Sjkoshy}
2068145256Sjkoshy
2069145256Sjkoshy/*
2070145256Sjkoshy * allocate a 'struct pmc_owner' descriptor in the owner hash table.
2071145256Sjkoshy */
2072145256Sjkoshy
2073145256Sjkoshystatic struct pmc_owner *
2074145256Sjkoshypmc_allocate_owner_descriptor(struct proc *p)
2075145256Sjkoshy{
2076145256Sjkoshy	uint32_t hindex;
2077145256Sjkoshy	struct pmc_owner *po;
2078145256Sjkoshy	struct pmc_ownerhash *poh;
2079145256Sjkoshy
2080145256Sjkoshy	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2081145256Sjkoshy	poh = &pmc_ownerhash[hindex];
2082145256Sjkoshy
2083145256Sjkoshy	/* allocate space for N pointers and one descriptor struct */
2084184802Sjkoshy	po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK|M_ZERO);
2085201021Sjkoshy	po->po_sscount = po->po_error = po->po_flags = po->po_logprocmaps = 0;
2086147191Sjkoshy	po->po_file  = NULL;
2087145256Sjkoshy	po->po_owner = p;
2088147191Sjkoshy	po->po_kthread = NULL;
2089145256Sjkoshy	LIST_INIT(&po->po_pmcs);
2090145256Sjkoshy	LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
2091145256Sjkoshy
2092147191Sjkoshy	TAILQ_INIT(&po->po_logbuffers);
2093168856Sjkoshy	mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
2094147191Sjkoshy
2095145256Sjkoshy	PMCDBG(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
2096145256Sjkoshy	    p, p->p_pid, p->p_comm, po);
2097145256Sjkoshy
2098145256Sjkoshy	return po;
2099145256Sjkoshy}
2100145256Sjkoshy
2101147191Sjkoshystatic void
2102147191Sjkoshypmc_destroy_owner_descriptor(struct pmc_owner *po)
2103147191Sjkoshy{
2104147191Sjkoshy
2105147191Sjkoshy	PMCDBG(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
2106147191Sjkoshy	    po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
2107147191Sjkoshy
2108147191Sjkoshy	mtx_destroy(&po->po_mtx);
2109184205Sdes	free(po, M_PMC);
2110147191Sjkoshy}
2111147191Sjkoshy
2112145256Sjkoshy/*
2113145256Sjkoshy * find the descriptor corresponding to process 'p', adding or removing it
2114145256Sjkoshy * as specified by 'mode'.
2115145256Sjkoshy */
2116145256Sjkoshy
2117145256Sjkoshystatic struct pmc_process *
2118145256Sjkoshypmc_find_process_descriptor(struct proc *p, uint32_t mode)
2119145256Sjkoshy{
2120145256Sjkoshy	uint32_t hindex;
2121145256Sjkoshy	struct pmc_process *pp, *ppnew;
2122145256Sjkoshy	struct pmc_processhash *pph;
2123145256Sjkoshy
2124145256Sjkoshy	hindex = PMC_HASH_PTR(p, pmc_processhashmask);
2125145256Sjkoshy	pph = &pmc_processhash[hindex];
2126145256Sjkoshy
2127145256Sjkoshy	ppnew = NULL;
2128145256Sjkoshy
2129145256Sjkoshy	/*
2130145256Sjkoshy	 * Pre-allocate memory in the FIND_ALLOCATE case since we
2131145256Sjkoshy	 * cannot call malloc(9) once we hold a spin lock.
2132145256Sjkoshy	 */
2133184802Sjkoshy	if (mode & PMC_FLAG_ALLOCATE)
2134184214Sdes		ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
2135184802Sjkoshy		    sizeof(struct pmc_targetstate), M_PMC, M_WAITOK|M_ZERO);
2136145256Sjkoshy
2137145256Sjkoshy	mtx_lock_spin(&pmc_processhash_mtx);
2138145256Sjkoshy	LIST_FOREACH(pp, pph, pp_next)
2139145256Sjkoshy	    if (pp->pp_proc == p)
2140145256Sjkoshy		    break;
2141145256Sjkoshy
2142145256Sjkoshy	if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
2143145256Sjkoshy		LIST_REMOVE(pp, pp_next);
2144145256Sjkoshy
2145145256Sjkoshy	if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
2146145256Sjkoshy	    ppnew != NULL) {
2147145256Sjkoshy		ppnew->pp_proc = p;
2148145256Sjkoshy		LIST_INSERT_HEAD(pph, ppnew, pp_next);
2149145256Sjkoshy		pp = ppnew;
2150145256Sjkoshy		ppnew = NULL;
2151145256Sjkoshy	}
2152145256Sjkoshy	mtx_unlock_spin(&pmc_processhash_mtx);
2153145256Sjkoshy
2154145256Sjkoshy	if (pp != NULL && ppnew != NULL)
2155184205Sdes		free(ppnew, M_PMC);
2156145256Sjkoshy
2157145256Sjkoshy	return pp;
2158145256Sjkoshy}
2159145256Sjkoshy
2160145256Sjkoshy/*
2161145256Sjkoshy * remove a process descriptor from the process hash table.
2162145256Sjkoshy */
2163145256Sjkoshy
2164145256Sjkoshystatic void
2165145256Sjkoshypmc_remove_process_descriptor(struct pmc_process *pp)
2166145256Sjkoshy{
2167145256Sjkoshy	KASSERT(pp->pp_refcnt == 0,
2168145256Sjkoshy	    ("[pmc,%d] Removing process descriptor %p with count %d",
2169145256Sjkoshy		__LINE__, pp, pp->pp_refcnt));
2170145256Sjkoshy
2171145256Sjkoshy	mtx_lock_spin(&pmc_processhash_mtx);
2172145256Sjkoshy	LIST_REMOVE(pp, pp_next);
2173145256Sjkoshy	mtx_unlock_spin(&pmc_processhash_mtx);
2174145256Sjkoshy}
2175145256Sjkoshy
2176145256Sjkoshy
2177145256Sjkoshy/*
2178145256Sjkoshy * find an owner descriptor corresponding to proc 'p'
2179145256Sjkoshy */
2180145256Sjkoshy
2181145256Sjkoshystatic struct pmc_owner *
2182145256Sjkoshypmc_find_owner_descriptor(struct proc *p)
2183145256Sjkoshy{
2184145256Sjkoshy	uint32_t hindex;
2185145256Sjkoshy	struct pmc_owner *po;
2186145256Sjkoshy	struct pmc_ownerhash *poh;
2187145256Sjkoshy
2188145256Sjkoshy	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2189145256Sjkoshy	poh = &pmc_ownerhash[hindex];
2190145256Sjkoshy
2191145256Sjkoshy	po = NULL;
2192145256Sjkoshy	LIST_FOREACH(po, poh, po_next)
2193145256Sjkoshy	    if (po->po_owner == p)
2194145256Sjkoshy		    break;
2195145256Sjkoshy
2196145256Sjkoshy	PMCDBG(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2197145256Sjkoshy	    "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2198145256Sjkoshy
2199145256Sjkoshy	return po;
2200145256Sjkoshy}
2201145256Sjkoshy
2202145256Sjkoshy/*
2203145256Sjkoshy * pmc_allocate_pmc_descriptor
2204145256Sjkoshy *
2205145256Sjkoshy * Allocate a pmc descriptor and initialize its
2206145256Sjkoshy * fields.
2207145256Sjkoshy */
2208145256Sjkoshy
2209145256Sjkoshystatic struct pmc *
2210145256Sjkoshypmc_allocate_pmc_descriptor(void)
2211145256Sjkoshy{
2212145256Sjkoshy	struct pmc *pmc;
2213145256Sjkoshy
2214184802Sjkoshy	pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK|M_ZERO);
2215145256Sjkoshy
2216145256Sjkoshy	if (pmc != NULL) {
2217145256Sjkoshy		pmc->pm_owner = NULL;
2218145256Sjkoshy		LIST_INIT(&pmc->pm_targets);
2219145256Sjkoshy	}
2220145256Sjkoshy
2221145256Sjkoshy	PMCDBG(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2222145256Sjkoshy
2223145256Sjkoshy	return pmc;
2224145256Sjkoshy}
2225145256Sjkoshy
2226145256Sjkoshy/*
2227145256Sjkoshy * Destroy a pmc descriptor.
2228145256Sjkoshy */
2229145256Sjkoshy
2230145256Sjkoshystatic void
2231145256Sjkoshypmc_destroy_pmc_descriptor(struct pmc *pm)
2232145256Sjkoshy{
2233145256Sjkoshy	(void) pm;
2234145256Sjkoshy
2235153110Sru#ifdef	DEBUG
2236145256Sjkoshy	KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2237145256Sjkoshy	    pm->pm_state == PMC_STATE_FREE,
2238145256Sjkoshy	    ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2239145256Sjkoshy	KASSERT(LIST_EMPTY(&pm->pm_targets),
2240145256Sjkoshy	    ("[pmc,%d] destroying pmc with targets", __LINE__));
2241145256Sjkoshy	KASSERT(pm->pm_owner == NULL,
2242145256Sjkoshy	    ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2243145256Sjkoshy	KASSERT(pm->pm_runcount == 0,
2244145256Sjkoshy	    ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
2245145256Sjkoshy		pm->pm_runcount));
2246145256Sjkoshy#endif
2247145256Sjkoshy}
2248145256Sjkoshy
2249147191Sjkoshystatic void
2250147191Sjkoshypmc_wait_for_pmc_idle(struct pmc *pm)
2251147191Sjkoshy{
2252233628Sfabient#ifdef DEBUG
2253147191Sjkoshy	volatile int maxloop;
2254147191Sjkoshy
2255183266Sjkoshy	maxloop = 100 * pmc_cpu_max();
2256147191Sjkoshy#endif
2257147191Sjkoshy	/*
2258147191Sjkoshy	 * Loop (with a forced context switch) till the PMC's runcount
2259147191Sjkoshy	 * comes down to zero.
2260147191Sjkoshy	 */
2261147191Sjkoshy	while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
2262233628Sfabient#ifdef DEBUG
2263147191Sjkoshy		maxloop--;
2264147191Sjkoshy		KASSERT(maxloop > 0,
2265147191Sjkoshy		    ("[pmc,%d] (ri%d, rc%d) waiting too long for "
2266147191Sjkoshy			"pmc to be free", __LINE__,
2267147191Sjkoshy			PMC_TO_ROWINDEX(pm), pm->pm_runcount));
2268147191Sjkoshy#endif
2269147191Sjkoshy		pmc_force_context_switch();
2270147191Sjkoshy	}
2271147191Sjkoshy}
2272147191Sjkoshy
2273145256Sjkoshy/*
2274145256Sjkoshy * This function does the following things:
2275145256Sjkoshy *
2276145256Sjkoshy *  - detaches the PMC from hardware
2277145256Sjkoshy *  - unlinks all target threads that were attached to it
2278145256Sjkoshy *  - removes the PMC from its owner's list
2279145256Sjkoshy *  - destroy's the PMC private mutex
2280145256Sjkoshy *
2281145256Sjkoshy * Once this function completes, the given pmc pointer can be safely
2282145256Sjkoshy * FREE'd by the caller.
2283145256Sjkoshy */
2284145256Sjkoshy
2285145256Sjkoshystatic void
2286145256Sjkoshypmc_release_pmc_descriptor(struct pmc *pm)
2287145256Sjkoshy{
2288145774Sjkoshy	enum pmc_mode mode;
2289145256Sjkoshy	struct pmc_hw *phw;
2290184802Sjkoshy	u_int adjri, ri, cpu;
2291147191Sjkoshy	struct pmc_owner *po;
2292184802Sjkoshy	struct pmc_binding pb;
2293145256Sjkoshy	struct pmc_process *pp;
2294184802Sjkoshy	struct pmc_classdep *pcd;
2295145256Sjkoshy	struct pmc_target *ptgt, *tmp;
2296145256Sjkoshy
2297145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
2298145256Sjkoshy
2299145256Sjkoshy	KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2300145256Sjkoshy
2301145774Sjkoshy	ri   = PMC_TO_ROWINDEX(pm);
2302184802Sjkoshy	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
2303145774Sjkoshy	mode = PMC_TO_MODE(pm);
2304145256Sjkoshy
2305145256Sjkoshy	PMCDBG(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2306145774Sjkoshy	    mode);
2307145256Sjkoshy
2308145256Sjkoshy	/*
2309145256Sjkoshy	 * First, we take the PMC off hardware.
2310145256Sjkoshy	 */
2311145301Simp	cpu = 0;
2312145774Sjkoshy	if (PMC_IS_SYSTEM_MODE(mode)) {
2313145256Sjkoshy
2314145256Sjkoshy		/*
2315145256Sjkoshy		 * A system mode PMC runs on a specific CPU.  Switch
2316145256Sjkoshy		 * to this CPU and turn hardware off.
2317145256Sjkoshy		 */
2318145256Sjkoshy		pmc_save_cpu_binding(&pb);
2319145256Sjkoshy
2320145774Sjkoshy		cpu = PMC_TO_CPU(pm);
2321145256Sjkoshy
2322147191Sjkoshy		pmc_select_cpu(cpu);
2323145256Sjkoshy
2324147191Sjkoshy		/* switch off non-stalled CPUs */
2325147191Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING &&
2326147867Sjkoshy		    pm->pm_stalled == 0) {
2327145256Sjkoshy
2328145256Sjkoshy			phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2329145256Sjkoshy
2330145256Sjkoshy			KASSERT(phw->phw_pmc == pm,
2331145256Sjkoshy			    ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2332145256Sjkoshy				__LINE__, ri, phw->phw_pmc, pm));
2333145256Sjkoshy			PMCDBG(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2334145256Sjkoshy
2335145256Sjkoshy			critical_enter();
2336184802Sjkoshy			pcd->pcd_stop_pmc(cpu, adjri);
2337145256Sjkoshy			critical_exit();
2338145256Sjkoshy		}
2339145256Sjkoshy
2340145256Sjkoshy		PMCDBG(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2341145256Sjkoshy
2342145256Sjkoshy		critical_enter();
2343184802Sjkoshy		pcd->pcd_config_pmc(cpu, adjri, NULL);
2344145256Sjkoshy		critical_exit();
2345145256Sjkoshy
2346147191Sjkoshy		/* adjust the global and process count of SS mode PMCs */
2347147191Sjkoshy		if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2348147191Sjkoshy			po = pm->pm_owner;
2349147191Sjkoshy			po->po_sscount--;
2350147191Sjkoshy			if (po->po_sscount == 0) {
2351147191Sjkoshy				atomic_subtract_rel_int(&pmc_ss_count, 1);
2352147191Sjkoshy				LIST_REMOVE(po, po_ssnext);
2353147191Sjkoshy			}
2354147191Sjkoshy		}
2355147191Sjkoshy
2356145256Sjkoshy		pm->pm_state = PMC_STATE_DELETED;
2357145256Sjkoshy
2358145256Sjkoshy		pmc_restore_cpu_binding(&pb);
2359145256Sjkoshy
2360147191Sjkoshy		/*
2361147191Sjkoshy		 * We could have references to this PMC structure in
2362147191Sjkoshy		 * the per-cpu sample queues.  Wait for the queue to
2363147191Sjkoshy		 * drain.
2364147191Sjkoshy		 */
2365147191Sjkoshy		pmc_wait_for_pmc_idle(pm);
2366147191Sjkoshy
2367145774Sjkoshy	} else if (PMC_IS_VIRTUAL_MODE(mode)) {
2368145256Sjkoshy
2369145256Sjkoshy		/*
2370145256Sjkoshy		 * A virtual PMC could be running on multiple CPUs at
2371145256Sjkoshy		 * a given instant.
2372145256Sjkoshy		 *
2373145256Sjkoshy		 * By marking its state as DELETED, we ensure that
2374145256Sjkoshy		 * this PMC is never further scheduled on hardware.
2375145256Sjkoshy		 *
2376145256Sjkoshy		 * Then we wait till all CPUs are done with this PMC.
2377145256Sjkoshy		 */
2378145256Sjkoshy		pm->pm_state = PMC_STATE_DELETED;
2379145256Sjkoshy
2380145256Sjkoshy
2381147191Sjkoshy		/* Wait for the PMCs runcount to come to zero. */
2382147191Sjkoshy		pmc_wait_for_pmc_idle(pm);
2383145256Sjkoshy
2384145256Sjkoshy		/*
2385145256Sjkoshy		 * At this point the PMC is off all CPUs and cannot be
2386145256Sjkoshy		 * freshly scheduled onto a CPU.  It is now safe to
2387145256Sjkoshy		 * unlink all targets from this PMC.  If a
2388145256Sjkoshy		 * process-record's refcount falls to zero, we remove
2389145256Sjkoshy		 * it from the hash table.  The module-wide SX lock
2390145256Sjkoshy		 * protects us from races.
2391145256Sjkoshy		 */
2392145256Sjkoshy		LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2393145256Sjkoshy			pp = ptgt->pt_process;
2394145256Sjkoshy			pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2395145256Sjkoshy
2396145256Sjkoshy			PMCDBG(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2397145256Sjkoshy
2398145256Sjkoshy			/*
2399145256Sjkoshy			 * If the target process record shows that no
2400145256Sjkoshy			 * PMCs are attached to it, reclaim its space.
2401145256Sjkoshy			 */
2402145256Sjkoshy
2403145256Sjkoshy			if (pp->pp_refcnt == 0) {
2404145256Sjkoshy				pmc_remove_process_descriptor(pp);
2405184205Sdes				free(pp, M_PMC);
2406145256Sjkoshy			}
2407145256Sjkoshy		}
2408145256Sjkoshy
2409145256Sjkoshy		cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2410145256Sjkoshy
2411145256Sjkoshy	}
2412145256Sjkoshy
2413145256Sjkoshy	/*
2414145256Sjkoshy	 * Release any MD resources
2415145256Sjkoshy	 */
2416184802Sjkoshy	(void) pcd->pcd_release_pmc(cpu, adjri, pm);
2417145256Sjkoshy
2418145256Sjkoshy	/*
2419145256Sjkoshy	 * Update row disposition
2420145256Sjkoshy	 */
2421145256Sjkoshy
2422145774Sjkoshy	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2423145256Sjkoshy		PMC_UNMARK_ROW_STANDALONE(ri);
2424145256Sjkoshy	else
2425145256Sjkoshy		PMC_UNMARK_ROW_THREAD(ri);
2426145256Sjkoshy
2427145256Sjkoshy	/* unlink from the owner's list */
2428147191Sjkoshy	if (pm->pm_owner) {
2429147191Sjkoshy		LIST_REMOVE(pm, pm_next);
2430147191Sjkoshy		pm->pm_owner = NULL;
2431147191Sjkoshy	}
2432145256Sjkoshy
2433145256Sjkoshy	pmc_destroy_pmc_descriptor(pm);
2434145256Sjkoshy}
2435145256Sjkoshy
2436145256Sjkoshy/*
2437145256Sjkoshy * Register an owner and a pmc.
2438145256Sjkoshy */
2439145256Sjkoshy
2440145256Sjkoshystatic int
2441145256Sjkoshypmc_register_owner(struct proc *p, struct pmc *pmc)
2442145256Sjkoshy{
2443145256Sjkoshy	struct pmc_owner *po;
2444145256Sjkoshy
2445145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
2446145256Sjkoshy
2447145774Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) == NULL)
2448147191Sjkoshy		if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2449145256Sjkoshy			return ENOMEM;
2450145256Sjkoshy
2451145256Sjkoshy	KASSERT(pmc->pm_owner == NULL,
2452145256Sjkoshy	    ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2453145256Sjkoshy	pmc->pm_owner  = po;
2454145256Sjkoshy
2455147191Sjkoshy	LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2456145256Sjkoshy
2457145256Sjkoshy	PROC_LOCK(p);
2458145256Sjkoshy	p->p_flag |= P_HWPMC;
2459145256Sjkoshy	PROC_UNLOCK(p);
2460145256Sjkoshy
2461147191Sjkoshy	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2462147191Sjkoshy		pmclog_process_pmcallocate(pmc);
2463145256Sjkoshy
2464147191Sjkoshy	PMCDBG(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2465147191Sjkoshy	    po, pmc);
2466147191Sjkoshy
2467145256Sjkoshy	return 0;
2468145256Sjkoshy}
2469145256Sjkoshy
2470145256Sjkoshy/*
2471145256Sjkoshy * Return the current row disposition:
2472145256Sjkoshy * == 0 => FREE
2473145256Sjkoshy *  > 0 => PROCESS MODE
2474145256Sjkoshy *  < 0 => SYSTEM MODE
2475145256Sjkoshy */
2476145256Sjkoshy
2477145256Sjkoshyint
2478145256Sjkoshypmc_getrowdisp(int ri)
2479145256Sjkoshy{
2480145256Sjkoshy	return pmc_pmcdisp[ri];
2481145256Sjkoshy}
2482145256Sjkoshy
2483145256Sjkoshy/*
2484145256Sjkoshy * Check if a PMC at row index 'ri' can be allocated to the current
2485145256Sjkoshy * process.
2486145256Sjkoshy *
2487145256Sjkoshy * Allocation can fail if:
2488145256Sjkoshy *   - the current process is already being profiled by a PMC at index 'ri',
2489145256Sjkoshy *     attached to it via OP_PMCATTACH.
2490145256Sjkoshy *   - the current process has already allocated a PMC at index 'ri'
2491145256Sjkoshy *     via OP_ALLOCATE.
2492145256Sjkoshy */
2493145256Sjkoshy
2494145256Sjkoshystatic int
2495145774Sjkoshypmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2496145256Sjkoshy{
2497145774Sjkoshy	enum pmc_mode mode;
2498145774Sjkoshy	struct pmc *pm;
2499145256Sjkoshy	struct pmc_owner *po;
2500145256Sjkoshy	struct pmc_process *pp;
2501145256Sjkoshy
2502145774Sjkoshy	PMCDBG(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2503145774Sjkoshy	    "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2504145256Sjkoshy
2505145774Sjkoshy	/*
2506145774Sjkoshy	 * We shouldn't have already allocated a process-mode PMC at
2507145774Sjkoshy	 * row index 'ri'.
2508145774Sjkoshy	 *
2509145774Sjkoshy	 * We shouldn't have allocated a system-wide PMC on the same
2510145774Sjkoshy	 * CPU and same RI.
2511145774Sjkoshy	 */
2512145256Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) != NULL)
2513147191Sjkoshy		LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2514145774Sjkoshy		    if (PMC_TO_ROWINDEX(pm) == ri) {
2515145774Sjkoshy			    mode = PMC_TO_MODE(pm);
2516145774Sjkoshy			    if (PMC_IS_VIRTUAL_MODE(mode))
2517145774Sjkoshy				    return EEXIST;
2518145774Sjkoshy			    if (PMC_IS_SYSTEM_MODE(mode) &&
2519145774Sjkoshy				(int) PMC_TO_CPU(pm) == cpu)
2520145774Sjkoshy				    return EEXIST;
2521145774Sjkoshy		    }
2522145774Sjkoshy	        }
2523145256Sjkoshy
2524145774Sjkoshy	/*
2525145774Sjkoshy	 * We also shouldn't be the target of any PMC at this index
2526145774Sjkoshy	 * since otherwise a PMC_ATTACH to ourselves will fail.
2527145774Sjkoshy	 */
2528145256Sjkoshy	if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2529145256Sjkoshy		if (pp->pp_pmcs[ri].pp_pmc)
2530145256Sjkoshy			return EEXIST;
2531145256Sjkoshy
2532145256Sjkoshy	PMCDBG(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2533145256Sjkoshy	    p, p->p_pid, p->p_comm, ri);
2534145256Sjkoshy
2535145256Sjkoshy	return 0;
2536145256Sjkoshy}
2537145256Sjkoshy
2538145256Sjkoshy/*
2539145256Sjkoshy * Check if a given PMC at row index 'ri' can be currently used in
2540145256Sjkoshy * mode 'mode'.
2541145256Sjkoshy */
2542145256Sjkoshy
2543145256Sjkoshystatic int
2544145256Sjkoshypmc_can_allocate_row(int ri, enum pmc_mode mode)
2545145256Sjkoshy{
2546145256Sjkoshy	enum pmc_disp	disp;
2547145256Sjkoshy
2548145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
2549145256Sjkoshy
2550145256Sjkoshy	PMCDBG(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2551145256Sjkoshy
2552145256Sjkoshy	if (PMC_IS_SYSTEM_MODE(mode))
2553145256Sjkoshy		disp = PMC_DISP_STANDALONE;
2554145256Sjkoshy	else
2555145256Sjkoshy		disp = PMC_DISP_THREAD;
2556145256Sjkoshy
2557145256Sjkoshy	/*
2558145256Sjkoshy	 * check disposition for PMC row 'ri':
2559145256Sjkoshy	 *
2560145256Sjkoshy	 * Expected disposition		Row-disposition		Result
2561145256Sjkoshy	 *
2562145256Sjkoshy	 * STANDALONE			STANDALONE or FREE	proceed
2563145256Sjkoshy	 * STANDALONE			THREAD			fail
2564145256Sjkoshy	 * THREAD			THREAD or FREE		proceed
2565145256Sjkoshy	 * THREAD			STANDALONE		fail
2566145256Sjkoshy	 */
2567145256Sjkoshy
2568145256Sjkoshy	if (!PMC_ROW_DISP_IS_FREE(ri) &&
2569145256Sjkoshy	    !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2570145256Sjkoshy	    !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2571145256Sjkoshy		return EBUSY;
2572145256Sjkoshy
2573145256Sjkoshy	/*
2574145256Sjkoshy	 * All OK
2575145256Sjkoshy	 */
2576145256Sjkoshy
2577145256Sjkoshy	PMCDBG(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2578145256Sjkoshy
2579145256Sjkoshy	return 0;
2580145256Sjkoshy
2581145256Sjkoshy}
2582145256Sjkoshy
2583145256Sjkoshy/*
2584145774Sjkoshy * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2585145256Sjkoshy */
2586145256Sjkoshy
2587145256Sjkoshystatic struct pmc *
2588145256Sjkoshypmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2589145256Sjkoshy{
2590147191Sjkoshy	struct pmc *pm;
2591145256Sjkoshy
2592145774Sjkoshy	KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2593145774Sjkoshy	    ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2594145774Sjkoshy		PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2595145256Sjkoshy
2596147191Sjkoshy	LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2597147191Sjkoshy	    if (pm->pm_id == pmcid)
2598147191Sjkoshy		    return pm;
2599145256Sjkoshy
2600145256Sjkoshy	return NULL;
2601145256Sjkoshy}
2602145256Sjkoshy
2603145256Sjkoshystatic int
2604145256Sjkoshypmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2605145256Sjkoshy{
2606145256Sjkoshy
2607145256Sjkoshy	struct pmc *pm;
2608145256Sjkoshy	struct pmc_owner *po;
2609145256Sjkoshy
2610145256Sjkoshy	PMCDBG(PMC,FND,1, "find-pmc id=%d", pmcid);
2611145256Sjkoshy
2612145256Sjkoshy	if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2613145256Sjkoshy		return ESRCH;
2614145256Sjkoshy
2615145256Sjkoshy	if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2616145256Sjkoshy		return EINVAL;
2617145256Sjkoshy
2618145256Sjkoshy	PMCDBG(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2619145256Sjkoshy
2620145256Sjkoshy	*pmc = pm;
2621145256Sjkoshy	return 0;
2622145256Sjkoshy}
2623145256Sjkoshy
2624145256Sjkoshy/*
2625145256Sjkoshy * Start a PMC.
2626145256Sjkoshy */
2627145256Sjkoshy
2628145256Sjkoshystatic int
2629145256Sjkoshypmc_start(struct pmc *pm)
2630145256Sjkoshy{
2631145774Sjkoshy	enum pmc_mode mode;
2632147191Sjkoshy	struct pmc_owner *po;
2633145256Sjkoshy	struct pmc_binding pb;
2634184802Sjkoshy	struct pmc_classdep *pcd;
2635184802Sjkoshy	int adjri, error, cpu, ri;
2636145256Sjkoshy
2637145256Sjkoshy	KASSERT(pm != NULL,
2638145256Sjkoshy	    ("[pmc,%d] null pm", __LINE__));
2639145256Sjkoshy
2640145774Sjkoshy	mode = PMC_TO_MODE(pm);
2641145774Sjkoshy	ri   = PMC_TO_ROWINDEX(pm);
2642184802Sjkoshy	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
2643184802Sjkoshy
2644145774Sjkoshy	error = 0;
2645145256Sjkoshy
2646145774Sjkoshy	PMCDBG(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2647145774Sjkoshy
2648147191Sjkoshy	po = pm->pm_owner;
2649145256Sjkoshy
2650174395Sjkoshy	/*
2651174395Sjkoshy	 * Disallow PMCSTART if a logfile is required but has not been
2652174395Sjkoshy	 * configured yet.
2653174395Sjkoshy	 */
2654174395Sjkoshy	if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2655174395Sjkoshy	    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2656184802Sjkoshy		return (EDOOFUS);	/* programming error */
2657174395Sjkoshy
2658174395Sjkoshy	/*
2659174395Sjkoshy	 * If this is a sampling mode PMC, log mapping information for
2660174395Sjkoshy	 * the kernel modules that are currently loaded.
2661174395Sjkoshy	 */
2662174395Sjkoshy	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2663174395Sjkoshy	    pmc_log_kernel_mappings(pm);
2664174395Sjkoshy
2665145774Sjkoshy	if (PMC_IS_VIRTUAL_MODE(mode)) {
2666145256Sjkoshy
2667145256Sjkoshy		/*
2668147191Sjkoshy		 * If a PMCATTACH has never been done on this PMC,
2669147191Sjkoshy		 * attach it to its owner process.
2670145256Sjkoshy		 */
2671145256Sjkoshy
2672145256Sjkoshy		if (LIST_EMPTY(&pm->pm_targets))
2673147191Sjkoshy			error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2674147191Sjkoshy			    pmc_attach_process(po->po_owner, pm);
2675145256Sjkoshy
2676145774Sjkoshy		/*
2677147191Sjkoshy		 * If the PMC is attached to its owner, then force a context
2678147191Sjkoshy		 * switch to ensure that the MD state gets set correctly.
2679145256Sjkoshy		 */
2680145256Sjkoshy
2681147191Sjkoshy		if (error == 0) {
2682147191Sjkoshy			pm->pm_state = PMC_STATE_RUNNING;
2683147191Sjkoshy			if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2684147191Sjkoshy				pmc_force_context_switch();
2685147191Sjkoshy		}
2686147191Sjkoshy
2687184802Sjkoshy		return (error);
2688147191Sjkoshy	}
2689145256Sjkoshy
2690147191Sjkoshy
2691147191Sjkoshy	/*
2692147191Sjkoshy	 * A system-wide PMC.
2693174395Sjkoshy	 *
2694147191Sjkoshy	 * Add the owner to the global list if this is a system-wide
2695147191Sjkoshy	 * sampling PMC.
2696147191Sjkoshy	 */
2697147191Sjkoshy
2698147191Sjkoshy	if (mode == PMC_MODE_SS) {
2699147191Sjkoshy		if (po->po_sscount == 0) {
2700147191Sjkoshy			LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2701147191Sjkoshy			atomic_add_rel_int(&pmc_ss_count, 1);
2702147191Sjkoshy			PMCDBG(PMC,OPS,1, "po=%p in global list", po);
2703147191Sjkoshy		}
2704147191Sjkoshy		po->po_sscount++;
2705145256Sjkoshy
2706207484Srstone		/*
2707207484Srstone		 * Log mapping information for all existing processes in the
2708207484Srstone		 * system.  Subsequent mappings are logged as they happen;
2709207484Srstone		 * see pmc_process_mmap().
2710207484Srstone		 */
2711207484Srstone		if (po->po_logprocmaps == 0) {
2712207484Srstone			pmc_log_all_process_mappings(po);
2713207484Srstone			po->po_logprocmaps = 1;
2714207484Srstone		}
2715201021Sjkoshy	}
2716157144Sjkoshy
2717145256Sjkoshy	/*
2718147191Sjkoshy	 * Move to the CPU associated with this
2719145256Sjkoshy	 * PMC, and start the hardware.
2720145256Sjkoshy	 */
2721145256Sjkoshy
2722145256Sjkoshy	pmc_save_cpu_binding(&pb);
2723145256Sjkoshy
2724145774Sjkoshy	cpu = PMC_TO_CPU(pm);
2725145256Sjkoshy
2726183266Sjkoshy	if (!pmc_cpu_is_active(cpu))
2727184802Sjkoshy		return (ENXIO);
2728145256Sjkoshy
2729145256Sjkoshy	pmc_select_cpu(cpu);
2730145256Sjkoshy
2731145256Sjkoshy	/*
2732145256Sjkoshy	 * global PMCs are configured at allocation time
2733145256Sjkoshy	 * so write out the initial value and start the PMC.
2734145256Sjkoshy	 */
2735145256Sjkoshy
2736147191Sjkoshy	pm->pm_state = PMC_STATE_RUNNING;
2737147191Sjkoshy
2738145774Sjkoshy	critical_enter();
2739184802Sjkoshy	if ((error = pcd->pcd_write_pmc(cpu, adjri,
2740145774Sjkoshy		 PMC_IS_SAMPLING_MODE(mode) ?
2741145256Sjkoshy		 pm->pm_sc.pm_reloadcount :
2742145256Sjkoshy		 pm->pm_sc.pm_initial)) == 0)
2743184802Sjkoshy		error = pcd->pcd_start_pmc(cpu, adjri);
2744145774Sjkoshy	critical_exit();
2745145256Sjkoshy
2746145256Sjkoshy	pmc_restore_cpu_binding(&pb);
2747145256Sjkoshy
2748184802Sjkoshy	return (error);
2749145256Sjkoshy}
2750145256Sjkoshy
2751145256Sjkoshy/*
2752145256Sjkoshy * Stop a PMC.
2753145256Sjkoshy */
2754145256Sjkoshy
2755145256Sjkoshystatic int
2756145256Sjkoshypmc_stop(struct pmc *pm)
2757145256Sjkoshy{
2758147191Sjkoshy	struct pmc_owner *po;
2759145256Sjkoshy	struct pmc_binding pb;
2760184802Sjkoshy	struct pmc_classdep *pcd;
2761184802Sjkoshy	int adjri, cpu, error, ri;
2762145256Sjkoshy
2763145256Sjkoshy	KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2764145256Sjkoshy
2765145774Sjkoshy	PMCDBG(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2766145774Sjkoshy	    PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2767145256Sjkoshy
2768145256Sjkoshy	pm->pm_state = PMC_STATE_STOPPED;
2769145256Sjkoshy
2770145256Sjkoshy	/*
2771145256Sjkoshy	 * If the PMC is a virtual mode one, changing the state to
2772145256Sjkoshy	 * non-RUNNING is enough to ensure that the PMC never gets
2773145256Sjkoshy	 * scheduled.
2774145256Sjkoshy	 *
2775145256Sjkoshy	 * If this PMC is current running on a CPU, then it will
2776145256Sjkoshy	 * handled correctly at the time its target process is context
2777145256Sjkoshy	 * switched out.
2778145256Sjkoshy	 */
2779145256Sjkoshy
2780145774Sjkoshy	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2781145256Sjkoshy		return 0;
2782145256Sjkoshy
2783145256Sjkoshy	/*
2784145256Sjkoshy	 * A system-mode PMC.  Move to the CPU associated with
2785145256Sjkoshy	 * this PMC, and stop the hardware.  We update the
2786145256Sjkoshy	 * 'initial count' so that a subsequent PMCSTART will
2787145256Sjkoshy	 * resume counting from the current hardware count.
2788145256Sjkoshy	 */
2789145256Sjkoshy
2790145256Sjkoshy	pmc_save_cpu_binding(&pb);
2791145256Sjkoshy
2792145774Sjkoshy	cpu = PMC_TO_CPU(pm);
2793145256Sjkoshy
2794183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
2795145774Sjkoshy	    ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2796145774Sjkoshy
2797183266Sjkoshy	if (!pmc_cpu_is_active(cpu))
2798145256Sjkoshy		return ENXIO;
2799145256Sjkoshy
2800145256Sjkoshy	pmc_select_cpu(cpu);
2801145256Sjkoshy
2802145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
2803184802Sjkoshy	pcd = pmc_ri_to_classdep(md, ri, &adjri);
2804145256Sjkoshy
2805145774Sjkoshy	critical_enter();
2806184802Sjkoshy	if ((error = pcd->pcd_stop_pmc(cpu, adjri)) == 0)
2807184802Sjkoshy		error = pcd->pcd_read_pmc(cpu, adjri, &pm->pm_sc.pm_initial);
2808145774Sjkoshy	critical_exit();
2809145774Sjkoshy
2810145256Sjkoshy	pmc_restore_cpu_binding(&pb);
2811145256Sjkoshy
2812147191Sjkoshy	po = pm->pm_owner;
2813147191Sjkoshy
2814147191Sjkoshy	/* remove this owner from the global list of SS PMC owners */
2815147191Sjkoshy	if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2816147191Sjkoshy		po->po_sscount--;
2817147191Sjkoshy		if (po->po_sscount == 0) {
2818147191Sjkoshy			atomic_subtract_rel_int(&pmc_ss_count, 1);
2819147191Sjkoshy			LIST_REMOVE(po, po_ssnext);
2820147191Sjkoshy			PMCDBG(PMC,OPS,2,"po=%p removed from global list", po);
2821147191Sjkoshy		}
2822147191Sjkoshy	}
2823147191Sjkoshy
2824184802Sjkoshy	return (error);
2825145256Sjkoshy}
2826145256Sjkoshy
2827145256Sjkoshy
2828153110Sru#ifdef	DEBUG
2829145256Sjkoshystatic const char *pmc_op_to_name[] = {
2830145256Sjkoshy#undef	__PMC_OP
2831145256Sjkoshy#define	__PMC_OP(N, D)	#N ,
2832145256Sjkoshy	__PMC_OPS()
2833145256Sjkoshy	NULL
2834145256Sjkoshy};
2835145256Sjkoshy#endif
2836145256Sjkoshy
2837145256Sjkoshy/*
2838145256Sjkoshy * The syscall interface
2839145256Sjkoshy */
2840145256Sjkoshy
2841145256Sjkoshy#define	PMC_GET_SX_XLOCK(...) do {		\
2842145256Sjkoshy	sx_xlock(&pmc_sx);			\
2843145256Sjkoshy	if (pmc_hook == NULL) {			\
2844145256Sjkoshy		sx_xunlock(&pmc_sx);		\
2845145256Sjkoshy		return __VA_ARGS__;		\
2846145256Sjkoshy	}					\
2847145256Sjkoshy} while (0)
2848145256Sjkoshy
2849145256Sjkoshy#define	PMC_DOWNGRADE_SX() do {			\
2850145256Sjkoshy	sx_downgrade(&pmc_sx);			\
2851145256Sjkoshy	is_sx_downgraded = 1;			\
2852145256Sjkoshy} while (0)
2853145256Sjkoshy
2854145256Sjkoshystatic int
2855145256Sjkoshypmc_syscall_handler(struct thread *td, void *syscall_args)
2856145256Sjkoshy{
2857195005Sattilio	int error, is_sx_downgraded, is_sx_locked, op;
2858145256Sjkoshy	struct pmc_syscall_args *c;
2859145256Sjkoshy	void *arg;
2860145256Sjkoshy
2861145256Sjkoshy	PMC_GET_SX_XLOCK(ENOSYS);
2862145256Sjkoshy
2863147191Sjkoshy	DROP_GIANT();
2864147191Sjkoshy
2865145256Sjkoshy	is_sx_downgraded = 0;
2866195005Sattilio	is_sx_locked = 1;
2867145256Sjkoshy
2868145256Sjkoshy	c = (struct pmc_syscall_args *) syscall_args;
2869145256Sjkoshy
2870145256Sjkoshy	op = c->pmop_code;
2871145256Sjkoshy	arg = c->pmop_data;
2872145256Sjkoshy
2873145256Sjkoshy	PMCDBG(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2874145256Sjkoshy	    pmc_op_to_name[op], arg);
2875145256Sjkoshy
2876145256Sjkoshy	error = 0;
2877145256Sjkoshy	atomic_add_int(&pmc_stats.pm_syscalls, 1);
2878145256Sjkoshy
2879145256Sjkoshy	switch(op)
2880145256Sjkoshy	{
2881145256Sjkoshy
2882145256Sjkoshy
2883145256Sjkoshy	/*
2884145256Sjkoshy	 * Configure a log file.
2885145256Sjkoshy	 *
2886145256Sjkoshy	 * XXX This OP will be reworked.
2887145256Sjkoshy	 */
2888145256Sjkoshy
2889145256Sjkoshy	case PMC_OP_CONFIGURELOG:
2890145256Sjkoshy	{
2891157144Sjkoshy		struct proc *p;
2892156466Sjkoshy		struct pmc *pm;
2893145256Sjkoshy		struct pmc_owner *po;
2894145256Sjkoshy		struct pmc_op_configurelog cl;
2895145256Sjkoshy
2896145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
2897145256Sjkoshy
2898145256Sjkoshy		if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2899145256Sjkoshy			break;
2900145256Sjkoshy
2901145256Sjkoshy		/* mark this process as owning a log file */
2902145256Sjkoshy		p = td->td_proc;
2903145256Sjkoshy		if ((po = pmc_find_owner_descriptor(p)) == NULL)
2904147191Sjkoshy			if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2905147191Sjkoshy				error = ENOMEM;
2906147191Sjkoshy				break;
2907147191Sjkoshy			}
2908145256Sjkoshy
2909147191Sjkoshy		/*
2910147191Sjkoshy		 * If a valid fd was passed in, try to configure that,
2911147191Sjkoshy		 * otherwise if 'fd' was less than zero and there was
2912147191Sjkoshy		 * a log file configured, flush its buffers and
2913147191Sjkoshy		 * de-configure it.
2914147191Sjkoshy		 */
2915195005Sattilio		if (cl.pm_logfd >= 0) {
2916195005Sattilio			sx_xunlock(&pmc_sx);
2917195005Sattilio			is_sx_locked = 0;
2918185363Sjkoshy			error = pmclog_configure_log(md, po, cl.pm_logfd);
2919195005Sattilio		} else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2920147191Sjkoshy			pmclog_process_closelog(po);
2921226514Sfabient			error = pmclog_close(po);
2922156466Sjkoshy			if (error == 0) {
2923156466Sjkoshy				LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2924156834Sjkoshy				    if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2925156834Sjkoshy					pm->pm_state == PMC_STATE_RUNNING)
2926156466Sjkoshy					    pmc_stop(pm);
2927147191Sjkoshy				error = pmclog_deconfigure_log(po);
2928156466Sjkoshy			}
2929147191Sjkoshy		} else
2930147191Sjkoshy			error = EINVAL;
2931157144Sjkoshy
2932157144Sjkoshy		if (error)
2933157144Sjkoshy			break;
2934147191Sjkoshy	}
2935147191Sjkoshy	break;
2936147191Sjkoshy
2937147191Sjkoshy	/*
2938147191Sjkoshy	 * Flush a log file.
2939147191Sjkoshy	 */
2940147191Sjkoshy
2941147191Sjkoshy	case PMC_OP_FLUSHLOG:
2942147191Sjkoshy	{
2943147191Sjkoshy		struct pmc_owner *po;
2944147191Sjkoshy
2945147191Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
2946147191Sjkoshy
2947147191Sjkoshy		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2948147191Sjkoshy			error = EINVAL;
2949145256Sjkoshy			break;
2950147191Sjkoshy		}
2951145256Sjkoshy
2952147191Sjkoshy		error = pmclog_flush(po);
2953145256Sjkoshy	}
2954145256Sjkoshy	break;
2955145256Sjkoshy
2956145256Sjkoshy	/*
2957226514Sfabient	 * Close a log file.
2958226514Sfabient	 */
2959226514Sfabient
2960226514Sfabient	case PMC_OP_CLOSELOG:
2961226514Sfabient	{
2962226514Sfabient		struct pmc_owner *po;
2963226514Sfabient
2964226514Sfabient		sx_assert(&pmc_sx, SX_XLOCKED);
2965226514Sfabient
2966226514Sfabient		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2967226514Sfabient			error = EINVAL;
2968226514Sfabient			break;
2969226514Sfabient		}
2970226514Sfabient
2971226514Sfabient		error = pmclog_close(po);
2972226514Sfabient	}
2973226514Sfabient	break;
2974226514Sfabient
2975226514Sfabient	/*
2976145256Sjkoshy	 * Retrieve hardware configuration.
2977145256Sjkoshy	 */
2978145256Sjkoshy
2979145256Sjkoshy	case PMC_OP_GETCPUINFO:	/* CPU information */
2980145256Sjkoshy	{
2981145256Sjkoshy		struct pmc_op_getcpuinfo gci;
2982184802Sjkoshy		struct pmc_classinfo *pci;
2983184802Sjkoshy		struct pmc_classdep *pcd;
2984184802Sjkoshy		int cl;
2985145256Sjkoshy
2986145256Sjkoshy		gci.pm_cputype = md->pmd_cputype;
2987183266Sjkoshy		gci.pm_ncpu    = pmc_cpu_max();
2988145256Sjkoshy		gci.pm_npmc    = md->pmd_npmc;
2989145256Sjkoshy		gci.pm_nclass  = md->pmd_nclass;
2990184802Sjkoshy		pci = gci.pm_classes;
2991184802Sjkoshy		pcd = md->pmd_classdep;
2992184802Sjkoshy		for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
2993184802Sjkoshy			pci->pm_caps  = pcd->pcd_caps;
2994184802Sjkoshy			pci->pm_class = pcd->pcd_class;
2995184802Sjkoshy			pci->pm_width = pcd->pcd_width;
2996184802Sjkoshy			pci->pm_num   = pcd->pcd_num;
2997184802Sjkoshy		}
2998145256Sjkoshy		error = copyout(&gci, arg, sizeof(gci));
2999145256Sjkoshy	}
3000145256Sjkoshy	break;
3001145256Sjkoshy
3002233628Sfabient	/*
3003233628Sfabient	 * Retrieve soft events list.
3004233628Sfabient	 */
3005233628Sfabient	case PMC_OP_GETDYNEVENTINFO:
3006233628Sfabient	{
3007233628Sfabient		enum pmc_class			cl;
3008233628Sfabient		enum pmc_event			ev;
3009233628Sfabient		struct pmc_op_getdyneventinfo	*gei;
3010233628Sfabient		struct pmc_dyn_event_descr	dev;
3011233628Sfabient		struct pmc_soft			*ps;
3012233628Sfabient		uint32_t			nevent;
3013145256Sjkoshy
3014233628Sfabient		sx_assert(&pmc_sx, SX_LOCKED);
3015233628Sfabient
3016233628Sfabient		gei = (struct pmc_op_getdyneventinfo *) arg;
3017233628Sfabient
3018233628Sfabient		if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
3019233628Sfabient			break;
3020233628Sfabient
3021233628Sfabient		/* Only SOFT class is dynamic. */
3022233628Sfabient		if (cl != PMC_CLASS_SOFT) {
3023233628Sfabient			error = EINVAL;
3024233628Sfabient			break;
3025233628Sfabient		}
3026233628Sfabient
3027233628Sfabient		nevent = 0;
3028233628Sfabient		for (ev = PMC_EV_SOFT_FIRST; ev <= PMC_EV_SOFT_LAST; ev++) {
3029233628Sfabient			ps = pmc_soft_ev_acquire(ev);
3030233628Sfabient			if (ps == NULL)
3031233628Sfabient				continue;
3032233628Sfabient			bcopy(&ps->ps_ev, &dev, sizeof(dev));
3033233628Sfabient			pmc_soft_ev_release(ps);
3034233628Sfabient
3035233628Sfabient			error = copyout(&dev,
3036233628Sfabient			    &gei->pm_events[nevent],
3037233628Sfabient			    sizeof(struct pmc_dyn_event_descr));
3038233628Sfabient			if (error != 0)
3039233628Sfabient				break;
3040233628Sfabient			nevent++;
3041233628Sfabient		}
3042233628Sfabient		if (error != 0)
3043233628Sfabient			break;
3044233628Sfabient
3045233628Sfabient		error = copyout(&nevent, &gei->pm_nevent,
3046233628Sfabient		    sizeof(nevent));
3047233628Sfabient	}
3048233628Sfabient	break;
3049233628Sfabient
3050145256Sjkoshy	/*
3051145256Sjkoshy	 * Get module statistics
3052145256Sjkoshy	 */
3053145256Sjkoshy
3054145256Sjkoshy	case PMC_OP_GETDRIVERSTATS:
3055145256Sjkoshy	{
3056145256Sjkoshy		struct pmc_op_getdriverstats gms;
3057145256Sjkoshy
3058145256Sjkoshy		bcopy(&pmc_stats, &gms, sizeof(gms));
3059145256Sjkoshy		error = copyout(&gms, arg, sizeof(gms));
3060145256Sjkoshy	}
3061145256Sjkoshy	break;
3062145256Sjkoshy
3063145256Sjkoshy
3064145256Sjkoshy	/*
3065145256Sjkoshy	 * Retrieve module version number
3066145256Sjkoshy	 */
3067145256Sjkoshy
3068145256Sjkoshy	case PMC_OP_GETMODULEVERSION:
3069145256Sjkoshy	{
3070147191Sjkoshy		uint32_t cv, modv;
3071147191Sjkoshy
3072147191Sjkoshy		/* retrieve the client's idea of the ABI version */
3073147191Sjkoshy		if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
3074147191Sjkoshy			break;
3075147191Sjkoshy		/* don't service clients newer than our driver */
3076147191Sjkoshy		modv = PMC_VERSION;
3077147191Sjkoshy		if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
3078147191Sjkoshy			error = EPROGMISMATCH;
3079147191Sjkoshy			break;
3080147191Sjkoshy		}
3081147191Sjkoshy		error = copyout(&modv, arg, sizeof(int));
3082145256Sjkoshy	}
3083145256Sjkoshy	break;
3084145256Sjkoshy
3085145256Sjkoshy
3086145256Sjkoshy	/*
3087145256Sjkoshy	 * Retrieve the state of all the PMCs on a given
3088145256Sjkoshy	 * CPU.
3089145256Sjkoshy	 */
3090145256Sjkoshy
3091145256Sjkoshy	case PMC_OP_GETPMCINFO:
3092145256Sjkoshy	{
3093184802Sjkoshy		int ari;
3094184802Sjkoshy		struct pmc *pm;
3095184802Sjkoshy		size_t pmcinfo_size;
3096145256Sjkoshy		uint32_t cpu, n, npmc;
3097184802Sjkoshy		struct pmc_owner *po;
3098184802Sjkoshy		struct pmc_binding pb;
3099184802Sjkoshy		struct pmc_classdep *pcd;
3100145256Sjkoshy		struct pmc_info *p, *pmcinfo;
3101145256Sjkoshy		struct pmc_op_getpmcinfo *gpi;
3102145256Sjkoshy
3103145256Sjkoshy		PMC_DOWNGRADE_SX();
3104145256Sjkoshy
3105145256Sjkoshy		gpi = (struct pmc_op_getpmcinfo *) arg;
3106145256Sjkoshy
3107145256Sjkoshy		if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
3108145256Sjkoshy			break;
3109145256Sjkoshy
3110183266Sjkoshy		if (cpu >= pmc_cpu_max()) {
3111145256Sjkoshy			error = EINVAL;
3112145256Sjkoshy			break;
3113145256Sjkoshy		}
3114145256Sjkoshy
3115183266Sjkoshy		if (!pmc_cpu_is_active(cpu)) {
3116145256Sjkoshy			error = ENXIO;
3117145256Sjkoshy			break;
3118145256Sjkoshy		}
3119145256Sjkoshy
3120145256Sjkoshy		/* switch to CPU 'cpu' */
3121145256Sjkoshy		pmc_save_cpu_binding(&pb);
3122145256Sjkoshy		pmc_select_cpu(cpu);
3123145256Sjkoshy
3124145256Sjkoshy		npmc = md->pmd_npmc;
3125145256Sjkoshy
3126145256Sjkoshy		pmcinfo_size = npmc * sizeof(struct pmc_info);
3127184214Sdes		pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK);
3128145256Sjkoshy
3129145256Sjkoshy		p = pmcinfo;
3130145256Sjkoshy
3131145256Sjkoshy		for (n = 0; n < md->pmd_npmc; n++, p++) {
3132145256Sjkoshy
3133184802Sjkoshy			pcd = pmc_ri_to_classdep(md, n, &ari);
3134184802Sjkoshy
3135184802Sjkoshy			KASSERT(pcd != NULL,
3136184802Sjkoshy			    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
3137184802Sjkoshy
3138184802Sjkoshy			if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
3139145256Sjkoshy				break;
3140145256Sjkoshy
3141145256Sjkoshy			if (PMC_ROW_DISP_IS_STANDALONE(n))
3142145256Sjkoshy				p->pm_rowdisp = PMC_DISP_STANDALONE;
3143145256Sjkoshy			else if (PMC_ROW_DISP_IS_THREAD(n))
3144145256Sjkoshy				p->pm_rowdisp = PMC_DISP_THREAD;
3145145256Sjkoshy			else
3146145256Sjkoshy				p->pm_rowdisp = PMC_DISP_FREE;
3147145256Sjkoshy
3148145256Sjkoshy			p->pm_ownerpid = -1;
3149145256Sjkoshy
3150145256Sjkoshy			if (pm == NULL)	/* no PMC associated */
3151145256Sjkoshy				continue;
3152145256Sjkoshy
3153145256Sjkoshy			po = pm->pm_owner;
3154145256Sjkoshy
3155145256Sjkoshy			KASSERT(po->po_owner != NULL,
3156145256Sjkoshy			    ("[pmc,%d] pmc_owner had a null proc pointer",
3157145256Sjkoshy				__LINE__));
3158145256Sjkoshy
3159145256Sjkoshy			p->pm_ownerpid = po->po_owner->p_pid;
3160145774Sjkoshy			p->pm_mode     = PMC_TO_MODE(pm);
3161145256Sjkoshy			p->pm_event    = pm->pm_event;
3162145256Sjkoshy			p->pm_flags    = pm->pm_flags;
3163145256Sjkoshy
3164145774Sjkoshy			if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3165145256Sjkoshy				p->pm_reloadcount =
3166145256Sjkoshy				    pm->pm_sc.pm_reloadcount;
3167145256Sjkoshy		}
3168145256Sjkoshy
3169145256Sjkoshy		pmc_restore_cpu_binding(&pb);
3170145256Sjkoshy
3171145256Sjkoshy		/* now copy out the PMC info collected */
3172145256Sjkoshy		if (error == 0)
3173145256Sjkoshy			error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
3174145256Sjkoshy
3175184205Sdes		free(pmcinfo, M_PMC);
3176145256Sjkoshy	}
3177145256Sjkoshy	break;
3178145256Sjkoshy
3179145256Sjkoshy
3180145256Sjkoshy	/*
3181145256Sjkoshy	 * Set the administrative state of a PMC.  I.e. whether
3182145256Sjkoshy	 * the PMC is to be used or not.
3183145256Sjkoshy	 */
3184145256Sjkoshy
3185145256Sjkoshy	case PMC_OP_PMCADMIN:
3186145256Sjkoshy	{
3187145256Sjkoshy		int cpu, ri;
3188145256Sjkoshy		enum pmc_state request;
3189145256Sjkoshy		struct pmc_cpu *pc;
3190145256Sjkoshy		struct pmc_hw *phw;
3191145256Sjkoshy		struct pmc_op_pmcadmin pma;
3192145256Sjkoshy		struct pmc_binding pb;
3193145256Sjkoshy
3194145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3195145256Sjkoshy
3196145256Sjkoshy		KASSERT(td == curthread,
3197145256Sjkoshy		    ("[pmc,%d] td != curthread", __LINE__));
3198145256Sjkoshy
3199164033Srwatson		error = priv_check(td, PRIV_PMC_MANAGE);
3200164033Srwatson		if (error)
3201145256Sjkoshy			break;
3202145256Sjkoshy
3203145256Sjkoshy		if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
3204145256Sjkoshy			break;
3205145256Sjkoshy
3206145256Sjkoshy		cpu = pma.pm_cpu;
3207145256Sjkoshy
3208183266Sjkoshy		if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
3209145256Sjkoshy			error = EINVAL;
3210145256Sjkoshy			break;
3211145256Sjkoshy		}
3212145256Sjkoshy
3213183266Sjkoshy		if (!pmc_cpu_is_active(cpu)) {
3214145256Sjkoshy			error = ENXIO;
3215145256Sjkoshy			break;
3216145256Sjkoshy		}
3217145256Sjkoshy
3218145256Sjkoshy		request = pma.pm_state;
3219145256Sjkoshy
3220145256Sjkoshy		if (request != PMC_STATE_DISABLED &&
3221145256Sjkoshy		    request != PMC_STATE_FREE) {
3222145256Sjkoshy			error = EINVAL;
3223145256Sjkoshy			break;
3224145256Sjkoshy		}
3225145256Sjkoshy
3226145256Sjkoshy		ri = pma.pm_pmc; /* pmc id == row index */
3227145256Sjkoshy		if (ri < 0 || ri >= (int) md->pmd_npmc) {
3228145256Sjkoshy			error = EINVAL;
3229145256Sjkoshy			break;
3230145256Sjkoshy		}
3231145256Sjkoshy
3232145256Sjkoshy		/*
3233145256Sjkoshy		 * We can't disable a PMC with a row-index allocated
3234145256Sjkoshy		 * for process virtual PMCs.
3235145256Sjkoshy		 */
3236145256Sjkoshy
3237145256Sjkoshy		if (PMC_ROW_DISP_IS_THREAD(ri) &&
3238145256Sjkoshy		    request == PMC_STATE_DISABLED) {
3239145256Sjkoshy			error = EBUSY;
3240145256Sjkoshy			break;
3241145256Sjkoshy		}
3242145256Sjkoshy
3243145256Sjkoshy		/*
3244145256Sjkoshy		 * otherwise, this PMC on this CPU is either free or
3245145256Sjkoshy		 * in system-wide mode.
3246145256Sjkoshy		 */
3247145256Sjkoshy
3248145256Sjkoshy		pmc_save_cpu_binding(&pb);
3249145256Sjkoshy		pmc_select_cpu(cpu);
3250145256Sjkoshy
3251145256Sjkoshy		pc  = pmc_pcpu[cpu];
3252145256Sjkoshy		phw = pc->pc_hwpmcs[ri];
3253145256Sjkoshy
3254145256Sjkoshy		/*
3255145256Sjkoshy		 * XXX do we need some kind of 'forced' disable?
3256145256Sjkoshy		 */
3257145256Sjkoshy
3258145256Sjkoshy		if (phw->phw_pmc == NULL) {
3259145256Sjkoshy			if (request == PMC_STATE_DISABLED &&
3260145256Sjkoshy			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
3261145256Sjkoshy				phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
3262145256Sjkoshy				PMC_MARK_ROW_STANDALONE(ri);
3263145256Sjkoshy			} else if (request == PMC_STATE_FREE &&
3264145256Sjkoshy			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
3265145256Sjkoshy				phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
3266145256Sjkoshy				PMC_UNMARK_ROW_STANDALONE(ri);
3267145256Sjkoshy			}
3268145256Sjkoshy			/* other cases are a no-op */
3269145256Sjkoshy		} else
3270145256Sjkoshy			error = EBUSY;
3271145256Sjkoshy
3272145256Sjkoshy		pmc_restore_cpu_binding(&pb);
3273145256Sjkoshy	}
3274145256Sjkoshy	break;
3275145256Sjkoshy
3276145256Sjkoshy
3277145256Sjkoshy	/*
3278145256Sjkoshy	 * Allocate a PMC.
3279145256Sjkoshy	 */
3280145256Sjkoshy
3281145256Sjkoshy	case PMC_OP_PMCALLOCATE:
3282145256Sjkoshy	{
3283184802Sjkoshy		int adjri, n;
3284184802Sjkoshy		u_int cpu;
3285145256Sjkoshy		uint32_t caps;
3286184802Sjkoshy		struct pmc *pmc;
3287145256Sjkoshy		enum pmc_mode mode;
3288145774Sjkoshy		struct pmc_hw *phw;
3289184802Sjkoshy		struct pmc_binding pb;
3290184802Sjkoshy		struct pmc_classdep *pcd;
3291145256Sjkoshy		struct pmc_op_pmcallocate pa;
3292145256Sjkoshy
3293145256Sjkoshy		if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
3294145256Sjkoshy			break;
3295145256Sjkoshy
3296145256Sjkoshy		caps = pa.pm_caps;
3297145256Sjkoshy		mode = pa.pm_mode;
3298145256Sjkoshy		cpu  = pa.pm_cpu;
3299145256Sjkoshy
3300145256Sjkoshy		if ((mode != PMC_MODE_SS  &&  mode != PMC_MODE_SC  &&
3301145256Sjkoshy		     mode != PMC_MODE_TS  &&  mode != PMC_MODE_TC) ||
3302183266Sjkoshy		    (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
3303145256Sjkoshy			error = EINVAL;
3304145256Sjkoshy			break;
3305145256Sjkoshy		}
3306145256Sjkoshy
3307145256Sjkoshy		/*
3308145256Sjkoshy		 * Virtual PMCs should only ask for a default CPU.
3309145256Sjkoshy		 * System mode PMCs need to specify a non-default CPU.
3310145256Sjkoshy		 */
3311145256Sjkoshy
3312145256Sjkoshy		if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3313145256Sjkoshy		    (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3314145256Sjkoshy			error = EINVAL;
3315145256Sjkoshy			break;
3316145256Sjkoshy		}
3317145256Sjkoshy
3318145256Sjkoshy		/*
3319183266Sjkoshy		 * Check that an inactive CPU is not being asked for.
3320145256Sjkoshy		 */
3321145256Sjkoshy
3322183266Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3323145256Sjkoshy			error = ENXIO;
3324145256Sjkoshy			break;
3325145256Sjkoshy		}
3326145256Sjkoshy
3327145256Sjkoshy		/*
3328145256Sjkoshy		 * Refuse an allocation for a system-wide PMC if this
3329145256Sjkoshy		 * process has been jailed, or if this process lacks
3330145256Sjkoshy		 * super-user credentials and the sysctl tunable
3331145256Sjkoshy		 * 'security.bsd.unprivileged_syspmcs' is zero.
3332145256Sjkoshy		 */
3333145256Sjkoshy
3334145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode)) {
3335164033Srwatson			if (jailed(curthread->td_ucred)) {
3336145256Sjkoshy				error = EPERM;
3337164033Srwatson				break;
3338164033Srwatson			}
3339164033Srwatson			if (!pmc_unprivileged_syspmcs) {
3340164033Srwatson				error = priv_check(curthread,
3341164033Srwatson				    PRIV_PMC_SYSTEM);
3342164033Srwatson				if (error)
3343164033Srwatson					break;
3344164033Srwatson			}
3345145256Sjkoshy		}
3346145256Sjkoshy
3347145256Sjkoshy		/*
3348145256Sjkoshy		 * Look for valid values for 'pm_flags'
3349145256Sjkoshy		 */
3350145256Sjkoshy
3351147191Sjkoshy		if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3352174395Sjkoshy		    PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3353145256Sjkoshy			error = EINVAL;
3354145256Sjkoshy			break;
3355145256Sjkoshy		}
3356145256Sjkoshy
3357147191Sjkoshy		/* process logging options are not allowed for system PMCs */
3358147191Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3359147191Sjkoshy		    (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3360147191Sjkoshy			error = EINVAL;
3361147191Sjkoshy			break;
3362147191Sjkoshy		}
3363147191Sjkoshy
3364145256Sjkoshy		/*
3365145256Sjkoshy		 * All sampling mode PMCs need to be able to interrupt the
3366145256Sjkoshy		 * CPU.
3367145256Sjkoshy		 */
3368147191Sjkoshy		if (PMC_IS_SAMPLING_MODE(mode))
3369145256Sjkoshy			caps |= PMC_CAP_INTERRUPT;
3370145256Sjkoshy
3371149374Sjkoshy		/* A valid class specifier should have been passed in. */
3372149374Sjkoshy		for (n = 0; n < md->pmd_nclass; n++)
3373184802Sjkoshy			if (md->pmd_classdep[n].pcd_class == pa.pm_class)
3374149374Sjkoshy				break;
3375149374Sjkoshy		if (n == md->pmd_nclass) {
3376149374Sjkoshy			error = EINVAL;
3377149374Sjkoshy			break;
3378149374Sjkoshy		}
3379149374Sjkoshy
3380149374Sjkoshy		/* The requested PMC capabilities should be feasible. */
3381184802Sjkoshy		if ((md->pmd_classdep[n].pcd_caps & caps) != caps) {
3382149374Sjkoshy			error = EOPNOTSUPP;
3383149374Sjkoshy			break;
3384149374Sjkoshy		}
3385149374Sjkoshy
3386145256Sjkoshy		PMCDBG(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3387145256Sjkoshy		    pa.pm_ev, caps, mode, cpu);
3388145256Sjkoshy
3389145256Sjkoshy		pmc = pmc_allocate_pmc_descriptor();
3390145774Sjkoshy		pmc->pm_id    = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3391145774Sjkoshy		    PMC_ID_INVALID);
3392145256Sjkoshy		pmc->pm_event = pa.pm_ev;
3393145256Sjkoshy		pmc->pm_state = PMC_STATE_FREE;
3394145256Sjkoshy		pmc->pm_caps  = caps;
3395145256Sjkoshy		pmc->pm_flags = pa.pm_flags;
3396145256Sjkoshy
3397145256Sjkoshy		/* switch thread to CPU 'cpu' */
3398145256Sjkoshy		pmc_save_cpu_binding(&pb);
3399145256Sjkoshy
3400145256Sjkoshy#define	PMC_IS_SHAREABLE_PMC(cpu, n)				\
3401145256Sjkoshy	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &		\
3402145256Sjkoshy	 PMC_PHW_FLAG_IS_SHAREABLE)
3403145256Sjkoshy#define	PMC_IS_UNALLOCATED(cpu, n)				\
3404145256Sjkoshy	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3405145256Sjkoshy
3406145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode)) {
3407145256Sjkoshy			pmc_select_cpu(cpu);
3408184802Sjkoshy			for (n = 0; n < (int) md->pmd_npmc; n++) {
3409184802Sjkoshy				pcd = pmc_ri_to_classdep(md, n, &adjri);
3410145256Sjkoshy				if (pmc_can_allocate_row(n, mode) == 0 &&
3411145256Sjkoshy				    pmc_can_allocate_rowindex(
3412145774Sjkoshy					    curthread->td_proc, n, cpu) == 0 &&
3413145256Sjkoshy				    (PMC_IS_UNALLOCATED(cpu, n) ||
3414145256Sjkoshy				     PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3415184802Sjkoshy				    pcd->pcd_allocate_pmc(cpu, adjri, pmc,
3416145256Sjkoshy					&pa) == 0)
3417145256Sjkoshy					break;
3418184802Sjkoshy			}
3419145256Sjkoshy		} else {
3420145256Sjkoshy			/* Process virtual mode */
3421145256Sjkoshy			for (n = 0; n < (int) md->pmd_npmc; n++) {
3422184802Sjkoshy				pcd = pmc_ri_to_classdep(md, n, &adjri);
3423145256Sjkoshy				if (pmc_can_allocate_row(n, mode) == 0 &&
3424145256Sjkoshy				    pmc_can_allocate_rowindex(
3425145774Sjkoshy					    curthread->td_proc, n,
3426145774Sjkoshy					    PMC_CPU_ANY) == 0 &&
3427184802Sjkoshy				    pcd->pcd_allocate_pmc(curthread->td_oncpu,
3428184802Sjkoshy					adjri, pmc, &pa) == 0)
3429145256Sjkoshy					break;
3430145256Sjkoshy			}
3431145256Sjkoshy		}
3432145256Sjkoshy
3433145256Sjkoshy#undef	PMC_IS_UNALLOCATED
3434145256Sjkoshy#undef	PMC_IS_SHAREABLE_PMC
3435145256Sjkoshy
3436145256Sjkoshy		pmc_restore_cpu_binding(&pb);
3437145256Sjkoshy
3438145256Sjkoshy		if (n == (int) md->pmd_npmc) {
3439145256Sjkoshy			pmc_destroy_pmc_descriptor(pmc);
3440184205Sdes			free(pmc, M_PMC);
3441145256Sjkoshy			pmc = NULL;
3442145256Sjkoshy			error = EINVAL;
3443145256Sjkoshy			break;
3444145256Sjkoshy		}
3445145256Sjkoshy
3446145774Sjkoshy		/* Fill in the correct value in the ID field */
3447145774Sjkoshy		pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3448145256Sjkoshy
3449145774Sjkoshy		PMCDBG(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3450145774Sjkoshy		    pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3451145774Sjkoshy
3452147191Sjkoshy		/* Process mode PMCs with logging enabled need log files */
3453147191Sjkoshy		if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3454147191Sjkoshy			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3455147191Sjkoshy
3456147191Sjkoshy		/* All system mode sampling PMCs require a log file */
3457147191Sjkoshy		if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3458147191Sjkoshy			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3459147191Sjkoshy
3460145256Sjkoshy		/*
3461145256Sjkoshy		 * Configure global pmc's immediately
3462145256Sjkoshy		 */
3463145256Sjkoshy
3464145774Sjkoshy		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3465145774Sjkoshy
3466145774Sjkoshy			pmc_save_cpu_binding(&pb);
3467145774Sjkoshy			pmc_select_cpu(cpu);
3468145774Sjkoshy
3469145774Sjkoshy			phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3470184802Sjkoshy			pcd = pmc_ri_to_classdep(md, n, &adjri);
3471145774Sjkoshy
3472145774Sjkoshy			if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3473184802Sjkoshy			    (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3474184802Sjkoshy				(void) pcd->pcd_release_pmc(cpu, adjri, pmc);
3475145256Sjkoshy				pmc_destroy_pmc_descriptor(pmc);
3476184205Sdes				free(pmc, M_PMC);
3477145256Sjkoshy				pmc = NULL;
3478145774Sjkoshy				pmc_restore_cpu_binding(&pb);
3479145774Sjkoshy				error = EPERM;
3480145256Sjkoshy				break;
3481145256Sjkoshy			}
3482145256Sjkoshy
3483145774Sjkoshy			pmc_restore_cpu_binding(&pb);
3484145774Sjkoshy		}
3485145256Sjkoshy
3486145256Sjkoshy		pmc->pm_state    = PMC_STATE_ALLOCATED;
3487145256Sjkoshy
3488145256Sjkoshy		/*
3489145256Sjkoshy		 * mark row disposition
3490145256Sjkoshy		 */
3491145256Sjkoshy
3492145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode))
3493145256Sjkoshy			PMC_MARK_ROW_STANDALONE(n);
3494145256Sjkoshy		else
3495145256Sjkoshy			PMC_MARK_ROW_THREAD(n);
3496145256Sjkoshy
3497145256Sjkoshy		/*
3498145256Sjkoshy		 * Register this PMC with the current thread as its owner.
3499145256Sjkoshy		 */
3500145256Sjkoshy
3501145256Sjkoshy		if ((error =
3502145256Sjkoshy		    pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3503145256Sjkoshy			pmc_release_pmc_descriptor(pmc);
3504184205Sdes			free(pmc, M_PMC);
3505145256Sjkoshy			pmc = NULL;
3506145256Sjkoshy			break;
3507145256Sjkoshy		}
3508145256Sjkoshy
3509145256Sjkoshy		/*
3510145256Sjkoshy		 * Return the allocated index.
3511145256Sjkoshy		 */
3512145256Sjkoshy
3513145774Sjkoshy		pa.pm_pmcid = pmc->pm_id;
3514145256Sjkoshy
3515145256Sjkoshy		error = copyout(&pa, arg, sizeof(pa));
3516145256Sjkoshy	}
3517145256Sjkoshy	break;
3518145256Sjkoshy
3519145256Sjkoshy
3520145256Sjkoshy	/*
3521145256Sjkoshy	 * Attach a PMC to a process.
3522145256Sjkoshy	 */
3523145256Sjkoshy
3524145256Sjkoshy	case PMC_OP_PMCATTACH:
3525145256Sjkoshy	{
3526145256Sjkoshy		struct pmc *pm;
3527145256Sjkoshy		struct proc *p;
3528145256Sjkoshy		struct pmc_op_pmcattach a;
3529145256Sjkoshy
3530145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3531145256Sjkoshy
3532145256Sjkoshy		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3533145256Sjkoshy			break;
3534145256Sjkoshy
3535145256Sjkoshy		if (a.pm_pid < 0) {
3536145256Sjkoshy			error = EINVAL;
3537145256Sjkoshy			break;
3538145256Sjkoshy		} else if (a.pm_pid == 0)
3539145256Sjkoshy			a.pm_pid = td->td_proc->p_pid;
3540145256Sjkoshy
3541145256Sjkoshy		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3542145256Sjkoshy			break;
3543145256Sjkoshy
3544145774Sjkoshy		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3545145256Sjkoshy			error = EINVAL;
3546145256Sjkoshy			break;
3547145256Sjkoshy		}
3548145256Sjkoshy
3549145256Sjkoshy		/* PMCs may be (re)attached only when allocated or stopped */
3550145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) {
3551145256Sjkoshy			error = EBUSY;
3552145256Sjkoshy			break;
3553145256Sjkoshy		} else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3554145256Sjkoshy		    pm->pm_state != PMC_STATE_STOPPED) {
3555145256Sjkoshy			error = EINVAL;
3556145256Sjkoshy			break;
3557145256Sjkoshy		}
3558145256Sjkoshy
3559145256Sjkoshy		/* lookup pid */
3560145256Sjkoshy		if ((p = pfind(a.pm_pid)) == NULL) {
3561145256Sjkoshy			error = ESRCH;
3562145256Sjkoshy			break;
3563145256Sjkoshy		}
3564145256Sjkoshy
3565145256Sjkoshy		/*
3566145256Sjkoshy		 * Ignore processes that are working on exiting.
3567145256Sjkoshy		 */
3568145256Sjkoshy		if (p->p_flag & P_WEXIT) {
3569145256Sjkoshy			error = ESRCH;
3570145256Sjkoshy			PROC_UNLOCK(p);	/* pfind() returns a locked process */
3571145256Sjkoshy			break;
3572145256Sjkoshy		}
3573145256Sjkoshy
3574145256Sjkoshy		/*
3575145256Sjkoshy		 * we are allowed to attach a PMC to a process if
3576145256Sjkoshy		 * we can debug it.
3577145256Sjkoshy		 */
3578145256Sjkoshy		error = p_candebug(curthread, p);
3579145256Sjkoshy
3580145256Sjkoshy		PROC_UNLOCK(p);
3581145256Sjkoshy
3582145256Sjkoshy		if (error == 0)
3583145256Sjkoshy			error = pmc_attach_process(p, pm);
3584145256Sjkoshy	}
3585145256Sjkoshy	break;
3586145256Sjkoshy
3587145256Sjkoshy
3588145256Sjkoshy	/*
3589145256Sjkoshy	 * Detach an attached PMC from a process.
3590145256Sjkoshy	 */
3591145256Sjkoshy
3592145256Sjkoshy	case PMC_OP_PMCDETACH:
3593145256Sjkoshy	{
3594145256Sjkoshy		struct pmc *pm;
3595145256Sjkoshy		struct proc *p;
3596145256Sjkoshy		struct pmc_op_pmcattach a;
3597145256Sjkoshy
3598145256Sjkoshy		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3599145256Sjkoshy			break;
3600145256Sjkoshy
3601145256Sjkoshy		if (a.pm_pid < 0) {
3602145256Sjkoshy			error = EINVAL;
3603145256Sjkoshy			break;
3604145256Sjkoshy		} else if (a.pm_pid == 0)
3605145256Sjkoshy			a.pm_pid = td->td_proc->p_pid;
3606145256Sjkoshy
3607145256Sjkoshy		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3608145256Sjkoshy			break;
3609145256Sjkoshy
3610145256Sjkoshy		if ((p = pfind(a.pm_pid)) == NULL) {
3611145256Sjkoshy			error = ESRCH;
3612145256Sjkoshy			break;
3613145256Sjkoshy		}
3614145256Sjkoshy
3615145256Sjkoshy		/*
3616145256Sjkoshy		 * Treat processes that are in the process of exiting
3617145256Sjkoshy		 * as if they were not present.
3618145256Sjkoshy		 */
3619145256Sjkoshy
3620145256Sjkoshy		if (p->p_flag & P_WEXIT)
3621145256Sjkoshy			error = ESRCH;
3622145256Sjkoshy
3623145256Sjkoshy		PROC_UNLOCK(p);	/* pfind() returns a locked process */
3624145256Sjkoshy
3625145256Sjkoshy		if (error == 0)
3626145256Sjkoshy			error = pmc_detach_process(p, pm);
3627145256Sjkoshy	}
3628145256Sjkoshy	break;
3629145256Sjkoshy
3630145256Sjkoshy
3631145256Sjkoshy	/*
3632147191Sjkoshy	 * Retrieve the MSR number associated with the counter
3633147191Sjkoshy	 * 'pmc_id'.  This allows processes to directly use RDPMC
3634147191Sjkoshy	 * instructions to read their PMCs, without the overhead of a
3635147191Sjkoshy	 * system call.
3636147191Sjkoshy	 */
3637147191Sjkoshy
3638147191Sjkoshy	case PMC_OP_PMCGETMSR:
3639147191Sjkoshy	{
3640184802Sjkoshy		int adjri, ri;
3641184802Sjkoshy		struct pmc *pm;
3642147191Sjkoshy		struct pmc_target *pt;
3643147191Sjkoshy		struct pmc_op_getmsr gm;
3644184802Sjkoshy		struct pmc_classdep *pcd;
3645147191Sjkoshy
3646147191Sjkoshy		PMC_DOWNGRADE_SX();
3647147191Sjkoshy
3648147191Sjkoshy		if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3649147191Sjkoshy			break;
3650147191Sjkoshy
3651147191Sjkoshy		if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3652147191Sjkoshy			break;
3653147191Sjkoshy
3654147191Sjkoshy		/*
3655147191Sjkoshy		 * The allocated PMC has to be a process virtual PMC,
3656147191Sjkoshy		 * i.e., of type MODE_T[CS].  Global PMCs can only be
3657147191Sjkoshy		 * read using the PMCREAD operation since they may be
3658147191Sjkoshy		 * allocated on a different CPU than the one we could
3659147191Sjkoshy		 * be running on at the time of the RDPMC instruction.
3660147191Sjkoshy		 *
3661147191Sjkoshy		 * The GETMSR operation is not allowed for PMCs that
3662147191Sjkoshy		 * are inherited across processes.
3663147191Sjkoshy		 */
3664147191Sjkoshy
3665147191Sjkoshy		if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3666147191Sjkoshy		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
3667147191Sjkoshy			error = EINVAL;
3668147191Sjkoshy			break;
3669147191Sjkoshy		}
3670147191Sjkoshy
3671147191Sjkoshy		/*
3672147191Sjkoshy		 * It only makes sense to use a RDPMC (or its
3673147191Sjkoshy		 * equivalent instruction on non-x86 architectures) on
3674147191Sjkoshy		 * a process that has allocated and attached a PMC to
3675147191Sjkoshy		 * itself.  Conversely the PMC is only allowed to have
3676147191Sjkoshy		 * one process attached to it -- its owner.
3677147191Sjkoshy		 */
3678147191Sjkoshy
3679147191Sjkoshy		if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3680147191Sjkoshy		    LIST_NEXT(pt, pt_next) != NULL ||
3681147191Sjkoshy		    pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3682147191Sjkoshy			error = EINVAL;
3683147191Sjkoshy			break;
3684147191Sjkoshy		}
3685147191Sjkoshy
3686147191Sjkoshy		ri = PMC_TO_ROWINDEX(pm);
3687184802Sjkoshy		pcd = pmc_ri_to_classdep(md, ri, &adjri);
3688147191Sjkoshy
3689184802Sjkoshy		/* PMC class has no 'GETMSR' support */
3690184802Sjkoshy		if (pcd->pcd_get_msr == NULL) {
3691184802Sjkoshy			error = ENOSYS;
3692147191Sjkoshy			break;
3693184802Sjkoshy		}
3694147191Sjkoshy
3695184802Sjkoshy		if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
3696184802Sjkoshy			break;
3697184802Sjkoshy
3698147191Sjkoshy		if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3699147191Sjkoshy			break;
3700147191Sjkoshy
3701147191Sjkoshy		/*
3702147191Sjkoshy		 * Mark our process as using MSRs.  Update machine
3703147191Sjkoshy		 * state using a forced context switch.
3704147191Sjkoshy		 */
3705147191Sjkoshy
3706147191Sjkoshy		pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3707147191Sjkoshy		pmc_force_context_switch();
3708147191Sjkoshy
3709147191Sjkoshy	}
3710147191Sjkoshy	break;
3711147191Sjkoshy
3712147191Sjkoshy	/*
3713145256Sjkoshy	 * Release an allocated PMC
3714145256Sjkoshy	 */
3715145256Sjkoshy
3716145256Sjkoshy	case PMC_OP_PMCRELEASE:
3717145256Sjkoshy	{
3718145256Sjkoshy		pmc_id_t pmcid;
3719145256Sjkoshy		struct pmc *pm;
3720145256Sjkoshy		struct pmc_owner *po;
3721145256Sjkoshy		struct pmc_op_simple sp;
3722145256Sjkoshy
3723145256Sjkoshy		/*
3724145256Sjkoshy		 * Find PMC pointer for the named PMC.
3725145256Sjkoshy		 *
3726145256Sjkoshy		 * Use pmc_release_pmc_descriptor() to switch off the
3727145256Sjkoshy		 * PMC, remove all its target threads, and remove the
3728145256Sjkoshy		 * PMC from its owner's list.
3729145256Sjkoshy		 *
3730145256Sjkoshy		 * Remove the owner record if this is the last PMC
3731145256Sjkoshy		 * owned.
3732145256Sjkoshy		 *
3733145256Sjkoshy		 * Free up space.
3734145256Sjkoshy		 */
3735145256Sjkoshy
3736145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3737145256Sjkoshy			break;
3738145256Sjkoshy
3739145256Sjkoshy		pmcid = sp.pm_pmcid;
3740145256Sjkoshy
3741145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3742145256Sjkoshy			break;
3743145256Sjkoshy
3744145256Sjkoshy		po = pm->pm_owner;
3745145256Sjkoshy		pmc_release_pmc_descriptor(pm);
3746145256Sjkoshy		pmc_maybe_remove_owner(po);
3747145256Sjkoshy
3748184205Sdes		free(pm, M_PMC);
3749145256Sjkoshy	}
3750145256Sjkoshy	break;
3751145256Sjkoshy
3752145256Sjkoshy
3753145256Sjkoshy	/*
3754145256Sjkoshy	 * Read and/or write a PMC.
3755145256Sjkoshy	 */
3756145256Sjkoshy
3757145256Sjkoshy	case PMC_OP_PMCRW:
3758145256Sjkoshy	{
3759184802Sjkoshy		int adjri;
3760184802Sjkoshy		struct pmc *pm;
3761145256Sjkoshy		uint32_t cpu, ri;
3762184802Sjkoshy		pmc_value_t oldvalue;
3763184802Sjkoshy		struct pmc_binding pb;
3764184802Sjkoshy		struct pmc_op_pmcrw prw;
3765184802Sjkoshy		struct pmc_classdep *pcd;
3766145256Sjkoshy		struct pmc_op_pmcrw *pprw;
3767145256Sjkoshy
3768145256Sjkoshy		PMC_DOWNGRADE_SX();
3769145256Sjkoshy
3770145256Sjkoshy		if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3771145256Sjkoshy			break;
3772145256Sjkoshy
3773145301Simp		ri = 0;
3774145256Sjkoshy		PMCDBG(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3775145256Sjkoshy		    prw.pm_flags);
3776145256Sjkoshy
3777145256Sjkoshy		/* must have at least one flag set */
3778145256Sjkoshy		if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3779145256Sjkoshy			error = EINVAL;
3780145256Sjkoshy			break;
3781145256Sjkoshy		}
3782145256Sjkoshy
3783145256Sjkoshy		/* locate pmc descriptor */
3784145256Sjkoshy		if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3785145256Sjkoshy			break;
3786145256Sjkoshy
3787145256Sjkoshy		/* Can't read a PMC that hasn't been started. */
3788145256Sjkoshy		if (pm->pm_state != PMC_STATE_ALLOCATED &&
3789145256Sjkoshy		    pm->pm_state != PMC_STATE_STOPPED &&
3790145256Sjkoshy		    pm->pm_state != PMC_STATE_RUNNING) {
3791145256Sjkoshy			error = EINVAL;
3792145256Sjkoshy			break;
3793145256Sjkoshy		}
3794145256Sjkoshy
3795145256Sjkoshy		/* writing a new value is allowed only for 'STOPPED' pmcs */
3796145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING &&
3797145256Sjkoshy		    (prw.pm_flags & PMC_F_NEWVALUE)) {
3798145256Sjkoshy			error = EBUSY;
3799145256Sjkoshy			break;
3800145256Sjkoshy		}
3801145256Sjkoshy
3802145774Sjkoshy		if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3803145256Sjkoshy
3804145774Sjkoshy			/*
3805145774Sjkoshy			 * If this PMC is attached to its owner (i.e.,
3806145774Sjkoshy			 * the process requesting this operation) and
3807145774Sjkoshy			 * is running, then attempt to get an
3808145774Sjkoshy			 * upto-date reading from hardware for a READ.
3809145774Sjkoshy			 * Writes are only allowed when the PMC is
3810145774Sjkoshy			 * stopped, so only update the saved value
3811145774Sjkoshy			 * field.
3812145774Sjkoshy			 *
3813145774Sjkoshy			 * If the PMC is not running, or is not
3814145774Sjkoshy			 * attached to its owner, read/write to the
3815145774Sjkoshy			 * savedvalue field.
3816145774Sjkoshy			 */
3817145774Sjkoshy
3818145774Sjkoshy			ri = PMC_TO_ROWINDEX(pm);
3819184802Sjkoshy			pcd = pmc_ri_to_classdep(md, ri, &adjri);
3820145774Sjkoshy
3821145256Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
3822145774Sjkoshy			cpu = curthread->td_oncpu;
3823145774Sjkoshy
3824145774Sjkoshy			if (prw.pm_flags & PMC_F_OLDVALUE) {
3825145774Sjkoshy				if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3826145774Sjkoshy				    (pm->pm_state == PMC_STATE_RUNNING))
3827184802Sjkoshy					error = (*pcd->pcd_read_pmc)(cpu, adjri,
3828145774Sjkoshy					    &oldvalue);
3829145774Sjkoshy				else
3830145774Sjkoshy					oldvalue = pm->pm_gv.pm_savedvalue;
3831145774Sjkoshy			}
3832145256Sjkoshy			if (prw.pm_flags & PMC_F_NEWVALUE)
3833145256Sjkoshy				pm->pm_gv.pm_savedvalue = prw.pm_value;
3834145774Sjkoshy
3835145256Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
3836145256Sjkoshy
3837145256Sjkoshy		} else { /* System mode PMCs */
3838145774Sjkoshy			cpu = PMC_TO_CPU(pm);
3839145774Sjkoshy			ri  = PMC_TO_ROWINDEX(pm);
3840184802Sjkoshy			pcd = pmc_ri_to_classdep(md, ri, &adjri);
3841145256Sjkoshy
3842183266Sjkoshy			if (!pmc_cpu_is_active(cpu)) {
3843145256Sjkoshy				error = ENXIO;
3844145256Sjkoshy				break;
3845145256Sjkoshy			}
3846145256Sjkoshy
3847145256Sjkoshy			/* move this thread to CPU 'cpu' */
3848145256Sjkoshy			pmc_save_cpu_binding(&pb);
3849145256Sjkoshy			pmc_select_cpu(cpu);
3850145256Sjkoshy
3851145774Sjkoshy			critical_enter();
3852145256Sjkoshy			/* save old value */
3853145256Sjkoshy			if (prw.pm_flags & PMC_F_OLDVALUE)
3854184802Sjkoshy				if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
3855145256Sjkoshy					 &oldvalue)))
3856145256Sjkoshy					goto error;
3857145256Sjkoshy			/* write out new value */
3858145256Sjkoshy			if (prw.pm_flags & PMC_F_NEWVALUE)
3859184802Sjkoshy				error = (*pcd->pcd_write_pmc)(cpu, adjri,
3860145256Sjkoshy				    prw.pm_value);
3861145256Sjkoshy		error:
3862145774Sjkoshy			critical_exit();
3863145256Sjkoshy			pmc_restore_cpu_binding(&pb);
3864145256Sjkoshy			if (error)
3865145256Sjkoshy				break;
3866145256Sjkoshy		}
3867145256Sjkoshy
3868145256Sjkoshy		pprw = (struct pmc_op_pmcrw *) arg;
3869145256Sjkoshy
3870153110Sru#ifdef	DEBUG
3871145256Sjkoshy		if (prw.pm_flags & PMC_F_NEWVALUE)
3872145256Sjkoshy			PMCDBG(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3873145256Sjkoshy			    ri, prw.pm_value, oldvalue);
3874156778Sjkoshy		else if (prw.pm_flags & PMC_F_OLDVALUE)
3875145256Sjkoshy			PMCDBG(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3876145256Sjkoshy#endif
3877145256Sjkoshy
3878145256Sjkoshy		/* return old value if requested */
3879145256Sjkoshy		if (prw.pm_flags & PMC_F_OLDVALUE)
3880145256Sjkoshy			if ((error = copyout(&oldvalue, &pprw->pm_value,
3881145256Sjkoshy				 sizeof(prw.pm_value))))
3882145256Sjkoshy				break;
3883145256Sjkoshy
3884145256Sjkoshy	}
3885145256Sjkoshy	break;
3886145256Sjkoshy
3887145256Sjkoshy
3888145256Sjkoshy	/*
3889145256Sjkoshy	 * Set the sampling rate for a sampling mode PMC and the
3890145256Sjkoshy	 * initial count for a counting mode PMC.
3891145256Sjkoshy	 */
3892145256Sjkoshy
3893145256Sjkoshy	case PMC_OP_PMCSETCOUNT:
3894145256Sjkoshy	{
3895145256Sjkoshy		struct pmc *pm;
3896145256Sjkoshy		struct pmc_op_pmcsetcount sc;
3897145256Sjkoshy
3898145256Sjkoshy		PMC_DOWNGRADE_SX();
3899145256Sjkoshy
3900145256Sjkoshy		if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3901145256Sjkoshy			break;
3902145256Sjkoshy
3903145256Sjkoshy		if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3904145256Sjkoshy			break;
3905145256Sjkoshy
3906145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) {
3907145256Sjkoshy			error = EBUSY;
3908145256Sjkoshy			break;
3909145256Sjkoshy		}
3910145256Sjkoshy
3911145774Sjkoshy		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3912145256Sjkoshy			pm->pm_sc.pm_reloadcount = sc.pm_count;
3913145256Sjkoshy		else
3914145256Sjkoshy			pm->pm_sc.pm_initial = sc.pm_count;
3915145256Sjkoshy	}
3916145256Sjkoshy	break;
3917145256Sjkoshy
3918145256Sjkoshy
3919145256Sjkoshy	/*
3920145256Sjkoshy	 * Start a PMC.
3921145256Sjkoshy	 */
3922145256Sjkoshy
3923145256Sjkoshy	case PMC_OP_PMCSTART:
3924145256Sjkoshy	{
3925145256Sjkoshy		pmc_id_t pmcid;
3926145256Sjkoshy		struct pmc *pm;
3927145256Sjkoshy		struct pmc_op_simple sp;
3928145256Sjkoshy
3929145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3930145256Sjkoshy
3931145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3932145256Sjkoshy			break;
3933145256Sjkoshy
3934145256Sjkoshy		pmcid = sp.pm_pmcid;
3935145256Sjkoshy
3936145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3937145256Sjkoshy			break;
3938145256Sjkoshy
3939145774Sjkoshy		KASSERT(pmcid == pm->pm_id,
3940145774Sjkoshy		    ("[pmc,%d] pmcid %x != id %x", __LINE__,
3941145774Sjkoshy			pm->pm_id, pmcid));
3942145256Sjkoshy
3943145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3944145256Sjkoshy			break;
3945145256Sjkoshy		else if (pm->pm_state != PMC_STATE_STOPPED &&
3946145256Sjkoshy		    pm->pm_state != PMC_STATE_ALLOCATED) {
3947145256Sjkoshy			error = EINVAL;
3948145256Sjkoshy			break;
3949145256Sjkoshy		}
3950145256Sjkoshy
3951145256Sjkoshy		error = pmc_start(pm);
3952145256Sjkoshy	}
3953145256Sjkoshy	break;
3954145256Sjkoshy
3955145256Sjkoshy
3956145256Sjkoshy	/*
3957145256Sjkoshy	 * Stop a PMC.
3958145256Sjkoshy	 */
3959145256Sjkoshy
3960145256Sjkoshy	case PMC_OP_PMCSTOP:
3961145256Sjkoshy	{
3962145256Sjkoshy		pmc_id_t pmcid;
3963145256Sjkoshy		struct pmc *pm;
3964145256Sjkoshy		struct pmc_op_simple sp;
3965145256Sjkoshy
3966145256Sjkoshy		PMC_DOWNGRADE_SX();
3967145256Sjkoshy
3968145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3969145256Sjkoshy			break;
3970145256Sjkoshy
3971145256Sjkoshy		pmcid = sp.pm_pmcid;
3972145256Sjkoshy
3973145256Sjkoshy		/*
3974145256Sjkoshy		 * Mark the PMC as inactive and invoke the MD stop
3975145256Sjkoshy		 * routines if needed.
3976145256Sjkoshy		 */
3977145256Sjkoshy
3978145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3979145256Sjkoshy			break;
3980145256Sjkoshy
3981145774Sjkoshy		KASSERT(pmcid == pm->pm_id,
3982145774Sjkoshy		    ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3983145774Sjkoshy			pm->pm_id, pmcid));
3984145256Sjkoshy
3985145256Sjkoshy		if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3986145256Sjkoshy			break;
3987145256Sjkoshy		else if (pm->pm_state != PMC_STATE_RUNNING) {
3988145256Sjkoshy			error = EINVAL;
3989145256Sjkoshy			break;
3990145256Sjkoshy		}
3991145256Sjkoshy
3992145256Sjkoshy		error = pmc_stop(pm);
3993145256Sjkoshy	}
3994145256Sjkoshy	break;
3995145256Sjkoshy
3996145256Sjkoshy
3997145256Sjkoshy	/*
3998147867Sjkoshy	 * Write a user supplied value to the log file.
3999145256Sjkoshy	 */
4000145256Sjkoshy
4001145256Sjkoshy	case PMC_OP_WRITELOG:
4002145256Sjkoshy	{
4003147191Sjkoshy		struct pmc_op_writelog wl;
4004147191Sjkoshy		struct pmc_owner *po;
4005145256Sjkoshy
4006145256Sjkoshy		PMC_DOWNGRADE_SX();
4007145256Sjkoshy
4008147191Sjkoshy		if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
4009145256Sjkoshy			break;
4010145256Sjkoshy
4011147191Sjkoshy		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
4012145256Sjkoshy			error = EINVAL;
4013145256Sjkoshy			break;
4014145256Sjkoshy		}
4015145256Sjkoshy
4016147191Sjkoshy		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
4017145774Sjkoshy			error = EINVAL;
4018145774Sjkoshy			break;
4019145774Sjkoshy		}
4020145774Sjkoshy
4021147191Sjkoshy		error = pmclog_process_userlog(po, &wl);
4022145256Sjkoshy	}
4023145256Sjkoshy	break;
4024145256Sjkoshy
4025147191Sjkoshy
4026145256Sjkoshy	default:
4027145256Sjkoshy		error = EINVAL;
4028145256Sjkoshy		break;
4029145256Sjkoshy	}
4030145256Sjkoshy
4031195005Sattilio	if (is_sx_locked != 0) {
4032195005Sattilio		if (is_sx_downgraded)
4033195005Sattilio			sx_sunlock(&pmc_sx);
4034195005Sattilio		else
4035195005Sattilio			sx_xunlock(&pmc_sx);
4036195005Sattilio	}
4037145256Sjkoshy
4038145256Sjkoshy	if (error)
4039145256Sjkoshy		atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
4040145256Sjkoshy
4041147191Sjkoshy	PICKUP_GIANT();
4042147191Sjkoshy
4043145256Sjkoshy	return error;
4044145256Sjkoshy}
4045145256Sjkoshy
4046145256Sjkoshy/*
4047145256Sjkoshy * Helper functions
4048145256Sjkoshy */
4049145256Sjkoshy
4050147191Sjkoshy
4051145256Sjkoshy/*
4052174395Sjkoshy * Mark the thread as needing callchain capture and post an AST.  The
4053174395Sjkoshy * actual callchain capture will be done in a context where it is safe
4054174395Sjkoshy * to take page faults.
4055174395Sjkoshy */
4056174395Sjkoshy
4057174395Sjkoshystatic void
4058186037Sjkoshypmc_post_callchain_callback(void)
4059174395Sjkoshy{
4060174395Sjkoshy	struct thread *td;
4061174395Sjkoshy
4062174395Sjkoshy	td = curthread;
4063174395Sjkoshy
4064205998Sfabient	/*
4065205998Sfabient	 * If there is multiple PMCs for the same interrupt ignore new post
4066205998Sfabient	 */
4067205998Sfabient	if (td->td_pflags & TDP_CALLCHAIN)
4068205998Sfabient		return;
4069186037Sjkoshy
4070174395Sjkoshy	/*
4071186037Sjkoshy	 * Mark this thread as needing callchain capture.
4072186037Sjkoshy	 * `td->td_pflags' will be safe to touch because this thread
4073186037Sjkoshy	 * was in user space when it was interrupted.
4074174395Sjkoshy	 */
4075174395Sjkoshy	td->td_pflags |= TDP_CALLCHAIN;
4076174395Sjkoshy
4077174395Sjkoshy	/*
4078186037Sjkoshy	 * Don't let this thread migrate between CPUs until callchain
4079186037Sjkoshy	 * capture completes.
4080174395Sjkoshy	 */
4081186037Sjkoshy	sched_pin();
4082174395Sjkoshy
4083174395Sjkoshy	return;
4084174395Sjkoshy}
4085174395Sjkoshy
4086174395Sjkoshy/*
4087147191Sjkoshy * Interrupt processing.
4088147191Sjkoshy *
4089174395Sjkoshy * Find a free slot in the per-cpu array of samples and capture the
4090174395Sjkoshy * current callchain there.  If a sample was successfully added, a bit
4091174395Sjkoshy * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4092174395Sjkoshy * needs to be invoked from the clock handler.
4093147191Sjkoshy *
4094147191Sjkoshy * This function is meant to be called from an NMI handler.  It cannot
4095147191Sjkoshy * use any of the locking primitives supplied by the OS.
4096145256Sjkoshy */
4097145256Sjkoshy
4098147191Sjkoshyint
4099233628Sfabientpmc_process_interrupt(int cpu, int ring, struct pmc *pm, struct trapframe *tf,
4100174395Sjkoshy    int inuserspace)
4101145256Sjkoshy{
4102174395Sjkoshy	int error, callchaindepth;
4103147191Sjkoshy	struct thread *td;
4104147191Sjkoshy	struct pmc_sample *ps;
4105147191Sjkoshy	struct pmc_samplebuffer *psb;
4106145256Sjkoshy
4107147191Sjkoshy	error = 0;
4108145256Sjkoshy
4109174395Sjkoshy	/*
4110174395Sjkoshy	 * Allocate space for a sample buffer.
4111174395Sjkoshy	 */
4112233628Sfabient	psb = pmc_pcpu[cpu]->pc_sb[ring];
4113145256Sjkoshy
4114147191Sjkoshy	ps = psb->ps_write;
4115174395Sjkoshy	if (ps->ps_nsamples) {	/* in use, reader hasn't caught up */
4116147867Sjkoshy		pm->pm_stalled = 1;
4117147191Sjkoshy		atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
4118174395Sjkoshy		PMCDBG(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
4119174395Sjkoshy		    cpu, pm, (void *) tf, inuserspace,
4120147191Sjkoshy		    (int) (psb->ps_write - psb->ps_samples),
4121147191Sjkoshy		    (int) (psb->ps_read - psb->ps_samples));
4122147191Sjkoshy		error = ENOMEM;
4123147191Sjkoshy		goto done;
4124147191Sjkoshy	}
4125145256Sjkoshy
4126174395Sjkoshy
4127174395Sjkoshy	/* Fill in entry. */
4128174395Sjkoshy	PMCDBG(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
4129174395Sjkoshy	    (void *) tf, inuserspace,
4130147191Sjkoshy	    (int) (psb->ps_write - psb->ps_samples),
4131147191Sjkoshy	    (int) (psb->ps_read - psb->ps_samples));
4132145256Sjkoshy
4133186037Sjkoshy	KASSERT(pm->pm_runcount >= 0,
4134186037Sjkoshy	    ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4135186037Sjkoshy		pm->pm_runcount));
4136186037Sjkoshy
4137208861Sfabient	atomic_add_rel_int(&pm->pm_runcount, 1);	/* hold onto PMC */
4138233628Sfabient
4139147191Sjkoshy	ps->ps_pmc = pm;
4140147191Sjkoshy	if ((td = curthread) && td->td_proc)
4141147191Sjkoshy		ps->ps_pid = td->td_proc->p_pid;
4142147191Sjkoshy	else
4143147191Sjkoshy		ps->ps_pid = -1;
4144174395Sjkoshy	ps->ps_cpu = cpu;
4145186037Sjkoshy	ps->ps_td = td;
4146174395Sjkoshy	ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4147145256Sjkoshy
4148174395Sjkoshy	callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4149174395Sjkoshy	    pmc_callchaindepth : 1;
4150174395Sjkoshy
4151174395Sjkoshy	if (callchaindepth == 1)
4152174395Sjkoshy		ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
4153174395Sjkoshy	else {
4154174395Sjkoshy		/*
4155174395Sjkoshy		 * Kernel stack traversals can be done immediately,
4156174395Sjkoshy		 * while we defer to an AST for user space traversals.
4157174395Sjkoshy		 */
4158233628Sfabient		if (!inuserspace) {
4159174395Sjkoshy			callchaindepth =
4160174395Sjkoshy			    pmc_save_kernel_callchain(ps->ps_pc,
4161174395Sjkoshy				callchaindepth, tf);
4162233628Sfabient		} else {
4163186037Sjkoshy			pmc_post_callchain_callback();
4164174395Sjkoshy			callchaindepth = PMC_SAMPLE_INUSE;
4165174395Sjkoshy		}
4166174395Sjkoshy	}
4167174395Sjkoshy
4168174395Sjkoshy	ps->ps_nsamples = callchaindepth;	/* mark entry as in use */
4169174395Sjkoshy
4170147191Sjkoshy	/* increment write pointer, modulo ring buffer size */
4171147191Sjkoshy	ps++;
4172147191Sjkoshy	if (ps == psb->ps_fence)
4173147191Sjkoshy		psb->ps_write = psb->ps_samples;
4174147191Sjkoshy	else
4175147191Sjkoshy		psb->ps_write = ps;
4176145256Sjkoshy
4177147191Sjkoshy done:
4178147191Sjkoshy	/* mark CPU as needing processing */
4179222813Sattilio	CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4180147191Sjkoshy
4181174395Sjkoshy	return (error);
4182145256Sjkoshy}
4183145256Sjkoshy
4184174395Sjkoshy/*
4185174395Sjkoshy * Capture a user call chain.  This function will be called from ast()
4186174395Sjkoshy * before control returns to userland and before the process gets
4187174395Sjkoshy * rescheduled.
4188174395Sjkoshy */
4189147191Sjkoshy
4190174395Sjkoshystatic void
4191233628Sfabientpmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4192174395Sjkoshy{
4193174395Sjkoshy	int i;
4194174395Sjkoshy	struct pmc *pm;
4195186037Sjkoshy	struct thread *td;
4196174395Sjkoshy	struct pmc_sample *ps;
4197174395Sjkoshy	struct pmc_samplebuffer *psb;
4198186037Sjkoshy#ifdef	INVARIANTS
4199186037Sjkoshy	int ncallchains;
4200186037Sjkoshy#endif
4201174395Sjkoshy
4202233628Sfabient	psb = pmc_pcpu[cpu]->pc_sb[ring];
4203186037Sjkoshy	td = curthread;
4204174395Sjkoshy
4205186037Sjkoshy	KASSERT(td->td_pflags & TDP_CALLCHAIN,
4206186037Sjkoshy	    ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
4207186037Sjkoshy		__LINE__));
4208186037Sjkoshy
4209186037Sjkoshy#ifdef	INVARIANTS
4210186037Sjkoshy	ncallchains = 0;
4211186037Sjkoshy#endif
4212186037Sjkoshy
4213174395Sjkoshy	/*
4214174395Sjkoshy	 * Iterate through all deferred callchain requests.
4215174395Sjkoshy	 */
4216174395Sjkoshy
4217186037Sjkoshy	ps = psb->ps_samples;
4218186037Sjkoshy	for (i = 0; i < pmc_nsamples; i++, ps++) {
4219174395Sjkoshy
4220174395Sjkoshy		if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
4221174395Sjkoshy			continue;
4222186037Sjkoshy		if (ps->ps_td != td)
4223186037Sjkoshy			continue;
4224174395Sjkoshy
4225186037Sjkoshy		KASSERT(ps->ps_cpu == cpu,
4226186037Sjkoshy		    ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
4227186037Sjkoshy			ps->ps_cpu, PCPU_GET(cpuid)));
4228186037Sjkoshy
4229174395Sjkoshy		pm = ps->ps_pmc;
4230174395Sjkoshy
4231174395Sjkoshy		KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
4232174395Sjkoshy		    ("[pmc,%d] Retrieving callchain for PMC that doesn't "
4233174395Sjkoshy			"want it", __LINE__));
4234174395Sjkoshy
4235186037Sjkoshy		KASSERT(pm->pm_runcount > 0,
4236186037Sjkoshy		    ("[pmc,%d] runcount %d", __LINE__, pm->pm_runcount));
4237186037Sjkoshy
4238174395Sjkoshy		/*
4239174395Sjkoshy		 * Retrieve the callchain and mark the sample buffer
4240174395Sjkoshy		 * as 'processable' by the timer tick sweep code.
4241174395Sjkoshy		 */
4242174395Sjkoshy		ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
4243174395Sjkoshy		    pmc_callchaindepth, tf);
4244186037Sjkoshy
4245186037Sjkoshy#ifdef	INVARIANTS
4246186037Sjkoshy		ncallchains++;
4247186037Sjkoshy#endif
4248174395Sjkoshy	}
4249174395Sjkoshy
4250186037Sjkoshy	KASSERT(ncallchains > 0,
4251186037Sjkoshy	    ("[pmc,%d] cpu %d didn't find a sample to collect", __LINE__,
4252186037Sjkoshy		cpu));
4253186037Sjkoshy
4254233628Sfabient	KASSERT(td->td_pinned > 0,
4255233628Sfabient	    ("[pmc,%d] invalid td_pinned value", __LINE__));
4256233628Sfabient	sched_unpin();	/* Can migrate safely now. */
4257233628Sfabient
4258174395Sjkoshy	return;
4259174395Sjkoshy}
4260174395Sjkoshy
4261145256Sjkoshy/*
4262147191Sjkoshy * Process saved PC samples.
4263145256Sjkoshy */
4264145256Sjkoshy
4265145256Sjkoshystatic void
4266233628Sfabientpmc_process_samples(int cpu, int ring)
4267145256Sjkoshy{
4268147191Sjkoshy	struct pmc *pm;
4269185363Sjkoshy	int adjri, n;
4270147191Sjkoshy	struct thread *td;
4271147191Sjkoshy	struct pmc_owner *po;
4272147191Sjkoshy	struct pmc_sample *ps;
4273184802Sjkoshy	struct pmc_classdep *pcd;
4274147191Sjkoshy	struct pmc_samplebuffer *psb;
4275145256Sjkoshy
4276147191Sjkoshy	KASSERT(PCPU_GET(cpuid) == cpu,
4277147191Sjkoshy	    ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4278147191Sjkoshy		PCPU_GET(cpuid), cpu));
4279145256Sjkoshy
4280233628Sfabient	psb = pmc_pcpu[cpu]->pc_sb[ring];
4281147191Sjkoshy
4282147191Sjkoshy	for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
4283147191Sjkoshy
4284147191Sjkoshy		ps = psb->ps_read;
4285174395Sjkoshy		if (ps->ps_nsamples == PMC_SAMPLE_FREE)
4286147191Sjkoshy			break;
4287147191Sjkoshy
4288147191Sjkoshy		pm = ps->ps_pmc;
4289186037Sjkoshy
4290186037Sjkoshy		KASSERT(pm->pm_runcount > 0,
4291186037Sjkoshy		    ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4292186037Sjkoshy			pm->pm_runcount));
4293186037Sjkoshy
4294147191Sjkoshy		po = pm->pm_owner;
4295147191Sjkoshy
4296147191Sjkoshy		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4297147191Sjkoshy		    ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4298147191Sjkoshy			pm, PMC_TO_MODE(pm)));
4299147191Sjkoshy
4300147191Sjkoshy		/* Ignore PMCs that have been switched off */
4301147191Sjkoshy		if (pm->pm_state != PMC_STATE_RUNNING)
4302147191Sjkoshy			goto entrydone;
4303147191Sjkoshy
4304233628Sfabient		/* If there is a pending AST wait for completion */
4305233628Sfabient		if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
4306233628Sfabient			/* Need a rescan at a later time. */
4307233628Sfabient			CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4308233628Sfabient			break;
4309233628Sfabient		}
4310233628Sfabient
4311174395Sjkoshy		PMCDBG(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4312174395Sjkoshy		    pm, ps->ps_nsamples, ps->ps_flags,
4313147191Sjkoshy		    (int) (psb->ps_write - psb->ps_samples),
4314147191Sjkoshy		    (int) (psb->ps_read - psb->ps_samples));
4315147191Sjkoshy
4316147191Sjkoshy		/*
4317147191Sjkoshy		 * If this is a process-mode PMC that is attached to
4318147191Sjkoshy		 * its owner, and if the PC is in user mode, update
4319147191Sjkoshy		 * profiling statistics like timer-based profiling
4320147191Sjkoshy		 * would have done.
4321147191Sjkoshy		 */
4322147191Sjkoshy		if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4323174395Sjkoshy			if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4324147191Sjkoshy				td = FIRST_THREAD_IN_PROC(po->po_owner);
4325174395Sjkoshy				addupc_intr(td, ps->ps_pc[0], 1);
4326147191Sjkoshy			}
4327147191Sjkoshy			goto entrydone;
4328147191Sjkoshy		}
4329147191Sjkoshy
4330147191Sjkoshy		/*
4331147191Sjkoshy		 * Otherwise, this is either a sampling mode PMC that
4332147191Sjkoshy		 * is attached to a different process than its owner,
4333147191Sjkoshy		 * or a system-wide sampling PMC.  Dispatch a log
4334147191Sjkoshy		 * entry to the PMC's owner process.
4335147191Sjkoshy		 */
4336174395Sjkoshy		pmclog_process_callchain(pm, ps);
4337147191Sjkoshy
4338147191Sjkoshy	entrydone:
4339233628Sfabient		ps->ps_nsamples = 0; /* mark entry as free */
4340208861Sfabient		atomic_subtract_rel_int(&pm->pm_runcount, 1);
4341147191Sjkoshy
4342147191Sjkoshy		/* increment read pointer, modulo sample size */
4343147191Sjkoshy		if (++ps == psb->ps_fence)
4344147191Sjkoshy			psb->ps_read = psb->ps_samples;
4345147191Sjkoshy		else
4346147191Sjkoshy			psb->ps_read = ps;
4347147191Sjkoshy	}
4348147191Sjkoshy
4349147191Sjkoshy	atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
4350147191Sjkoshy
4351147191Sjkoshy	/* Do not re-enable stalled PMCs if we failed to process any samples */
4352147191Sjkoshy	if (n == 0)
4353147191Sjkoshy		return;
4354147191Sjkoshy
4355147191Sjkoshy	/*
4356147191Sjkoshy	 * Restart any stalled sampling PMCs on this CPU.
4357147191Sjkoshy	 *
4358147867Sjkoshy	 * If the NMI handler sets the pm_stalled field of a PMC after
4359147867Sjkoshy	 * the check below, we'll end up processing the stalled PMC at
4360147867Sjkoshy	 * the next hardclock tick.
4361147191Sjkoshy	 */
4362147191Sjkoshy	for (n = 0; n < md->pmd_npmc; n++) {
4363184802Sjkoshy		pcd = pmc_ri_to_classdep(md, n, &adjri);
4364184802Sjkoshy		KASSERT(pcd != NULL,
4365184802Sjkoshy		    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4366184802Sjkoshy		(void) (*pcd->pcd_get_config)(cpu,adjri,&pm);
4367184802Sjkoshy
4368147191Sjkoshy		if (pm == NULL ||			 /* !cfg'ed */
4369147191Sjkoshy		    pm->pm_state != PMC_STATE_RUNNING || /* !active */
4370147191Sjkoshy		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4371147867Sjkoshy		    pm->pm_stalled == 0) /* !stalled */
4372147191Sjkoshy			continue;
4373147191Sjkoshy
4374147867Sjkoshy		pm->pm_stalled = 0;
4375184802Sjkoshy		(*pcd->pcd_start_pmc)(cpu, adjri);
4376147191Sjkoshy	}
4377145256Sjkoshy}
4378145256Sjkoshy
4379145256Sjkoshy/*
4380145256Sjkoshy * Event handlers.
4381145256Sjkoshy */
4382145256Sjkoshy
4383145256Sjkoshy/*
4384145256Sjkoshy * Handle a process exit.
4385145256Sjkoshy *
4386147191Sjkoshy * Remove this process from all hash tables.  If this process
4387147191Sjkoshy * owned any PMCs, turn off those PMCs and deallocate them,
4388147191Sjkoshy * removing any associations with target processes.
4389147191Sjkoshy *
4390147191Sjkoshy * This function will be called by the last 'thread' of a
4391147191Sjkoshy * process.
4392147191Sjkoshy *
4393145256Sjkoshy * XXX This eventhandler gets called early in the exit process.
4394145256Sjkoshy * Consider using a 'hook' invocation from thread_exit() or equivalent
4395145256Sjkoshy * spot.  Another negative is that kse_exit doesn't seem to call
4396145256Sjkoshy * exit1() [??].
4397147191Sjkoshy *
4398145256Sjkoshy */
4399145256Sjkoshy
4400145256Sjkoshystatic void
4401145256Sjkoshypmc_process_exit(void *arg __unused, struct proc *p)
4402145256Sjkoshy{
4403184802Sjkoshy	struct pmc *pm;
4404184802Sjkoshy	int adjri, cpu;
4405184802Sjkoshy	unsigned int ri;
4406145256Sjkoshy	int is_using_hwpmcs;
4407184802Sjkoshy	struct pmc_owner *po;
4408147191Sjkoshy	struct pmc_process *pp;
4409184802Sjkoshy	struct pmc_classdep *pcd;
4410147191Sjkoshy	pmc_value_t newvalue, tmp;
4411145256Sjkoshy
4412145256Sjkoshy	PROC_LOCK(p);
4413145256Sjkoshy	is_using_hwpmcs = p->p_flag & P_HWPMC;
4414145256Sjkoshy	PROC_UNLOCK(p);
4415145256Sjkoshy
4416147191Sjkoshy	/*
4417147191Sjkoshy	 * Log a sysexit event to all SS PMC owners.
4418147191Sjkoshy	 */
4419147191Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4420147191Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4421147191Sjkoshy		    pmclog_process_sysexit(po, p->p_pid);
4422145256Sjkoshy
4423147191Sjkoshy	if (!is_using_hwpmcs)
4424147191Sjkoshy		return;
4425147191Sjkoshy
4426147191Sjkoshy	PMC_GET_SX_XLOCK();
4427147191Sjkoshy	PMCDBG(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4428147191Sjkoshy	    p->p_comm);
4429147191Sjkoshy
4430147191Sjkoshy	/*
4431147191Sjkoshy	 * Since this code is invoked by the last thread in an exiting
4432147191Sjkoshy	 * process, we would have context switched IN at some prior
4433147191Sjkoshy	 * point.  However, with PREEMPTION, kernel mode context
4434147191Sjkoshy	 * switches may happen any time, so we want to disable a
4435147191Sjkoshy	 * context switch OUT till we get any PMCs targetting this
4436147191Sjkoshy	 * process off the hardware.
4437147191Sjkoshy	 *
4438147191Sjkoshy	 * We also need to atomically remove this process'
4439147191Sjkoshy	 * entry from our target process hash table, using
4440147191Sjkoshy	 * PMC_FLAG_REMOVE.
4441147191Sjkoshy	 */
4442147191Sjkoshy	PMCDBG(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4443147191Sjkoshy	    p->p_comm);
4444147191Sjkoshy
4445147191Sjkoshy	critical_enter(); /* no preemption */
4446147191Sjkoshy
4447147191Sjkoshy	cpu = curthread->td_oncpu;
4448147191Sjkoshy
4449147191Sjkoshy	if ((pp = pmc_find_process_descriptor(p,
4450147191Sjkoshy		 PMC_FLAG_REMOVE)) != NULL) {
4451147191Sjkoshy
4452147191Sjkoshy		PMCDBG(PRC,EXT,2,
4453147191Sjkoshy		    "process-exit proc=%p pmc-process=%p", p, pp);
4454147191Sjkoshy
4455147191Sjkoshy		/*
4456147191Sjkoshy		 * The exiting process could the target of
4457147191Sjkoshy		 * some PMCs which will be running on
4458147191Sjkoshy		 * currently executing CPU.
4459147191Sjkoshy		 *
4460147191Sjkoshy		 * We need to turn these PMCs off like we
4461147191Sjkoshy		 * would do at context switch OUT time.
4462147191Sjkoshy		 */
4463147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++) {
4464147191Sjkoshy
4465147191Sjkoshy			/*
4466147191Sjkoshy			 * Pick up the pmc pointer from hardware
4467147191Sjkoshy			 * state similar to the CSW_OUT code.
4468147191Sjkoshy			 */
4469147191Sjkoshy			pm = NULL;
4470147191Sjkoshy
4471184802Sjkoshy			pcd = pmc_ri_to_classdep(md, ri, &adjri);
4472184802Sjkoshy
4473184802Sjkoshy			(void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
4474184802Sjkoshy
4475147191Sjkoshy			PMCDBG(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4476147191Sjkoshy
4477147191Sjkoshy			if (pm == NULL ||
4478147191Sjkoshy			    !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4479147191Sjkoshy				continue;
4480147191Sjkoshy
4481147191Sjkoshy			PMCDBG(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4482147191Sjkoshy			    "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4483147191Sjkoshy			    pm, pm->pm_state);
4484147191Sjkoshy
4485147191Sjkoshy			KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4486147191Sjkoshy			    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4487147191Sjkoshy				__LINE__, PMC_TO_ROWINDEX(pm), ri));
4488147191Sjkoshy
4489147191Sjkoshy			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4490147191Sjkoshy			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4491147191Sjkoshy				__LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4492147191Sjkoshy
4493184802Sjkoshy			(void) pcd->pcd_stop_pmc(cpu, adjri);
4494147191Sjkoshy
4495147191Sjkoshy			KASSERT(pm->pm_runcount > 0,
4496147191Sjkoshy			    ("[pmc,%d] bad runcount ri %d rc %d",
4497147191Sjkoshy				__LINE__, ri, pm->pm_runcount));
4498147191Sjkoshy
4499147867Sjkoshy			/* Stop hardware only if it is actually running */
4500147191Sjkoshy			if (pm->pm_state == PMC_STATE_RUNNING &&
4501147867Sjkoshy			    pm->pm_stalled == 0) {
4502184802Sjkoshy				pcd->pcd_read_pmc(cpu, adjri, &newvalue);
4503147191Sjkoshy				tmp = newvalue -
4504147191Sjkoshy				    PMC_PCPU_SAVED(cpu,ri);
4505147191Sjkoshy
4506147191Sjkoshy				mtx_pool_lock_spin(pmc_mtxpool, pm);
4507147191Sjkoshy				pm->pm_gv.pm_savedvalue += tmp;
4508147191Sjkoshy				pp->pp_pmcs[ri].pp_pmcval += tmp;
4509147191Sjkoshy				mtx_pool_unlock_spin(pmc_mtxpool, pm);
4510147191Sjkoshy			}
4511147191Sjkoshy
4512208861Sfabient			atomic_subtract_rel_int(&pm->pm_runcount,1);
4513147191Sjkoshy
4514147191Sjkoshy			KASSERT((int) pm->pm_runcount >= 0,
4515147191Sjkoshy			    ("[pmc,%d] runcount is %d", __LINE__, ri));
4516147191Sjkoshy
4517184802Sjkoshy			(void) pcd->pcd_config_pmc(cpu, adjri, NULL);
4518147191Sjkoshy		}
4519147191Sjkoshy
4520147191Sjkoshy		/*
4521147191Sjkoshy		 * Inform the MD layer of this pseudo "context switch
4522147191Sjkoshy		 * out"
4523147191Sjkoshy		 */
4524147191Sjkoshy		(void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
4525147191Sjkoshy
4526147191Sjkoshy		critical_exit(); /* ok to be pre-empted now */
4527147191Sjkoshy
4528147191Sjkoshy		/*
4529147191Sjkoshy		 * Unlink this process from the PMCs that are
4530147191Sjkoshy		 * targetting it.  This will send a signal to
4531147191Sjkoshy		 * all PMC owner's whose PMCs are orphaned.
4532147191Sjkoshy		 *
4533147191Sjkoshy		 * Log PMC value at exit time if requested.
4534147191Sjkoshy		 */
4535147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
4536147191Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
4537147867Sjkoshy				if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
4538147867Sjkoshy				    PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
4539147191Sjkoshy					pmclog_process_procexit(pm, pp);
4540147191Sjkoshy				pmc_unlink_target_process(pm, pp);
4541147191Sjkoshy			}
4542184205Sdes		free(pp, M_PMC);
4543147191Sjkoshy
4544147191Sjkoshy	} else
4545147191Sjkoshy		critical_exit(); /* pp == NULL */
4546147191Sjkoshy
4547147191Sjkoshy
4548147191Sjkoshy	/*
4549147191Sjkoshy	 * If the process owned PMCs, free them up and free up
4550147191Sjkoshy	 * memory.
4551147191Sjkoshy	 */
4552147191Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
4553147191Sjkoshy		pmc_remove_owner(po);
4554147191Sjkoshy		pmc_destroy_owner_descriptor(po);
4555145256Sjkoshy	}
4556147191Sjkoshy
4557147191Sjkoshy	sx_xunlock(&pmc_sx);
4558145256Sjkoshy}
4559145256Sjkoshy
4560145256Sjkoshy/*
4561145256Sjkoshy * Handle a process fork.
4562145256Sjkoshy *
4563145256Sjkoshy * If the parent process 'p1' is under HWPMC monitoring, then copy
4564145256Sjkoshy * over any attached PMCs that have 'do_descendants' semantics.
4565145256Sjkoshy */
4566145256Sjkoshy
4567145256Sjkoshystatic void
4568147191Sjkoshypmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
4569145256Sjkoshy    int flags)
4570145256Sjkoshy{
4571145256Sjkoshy	int is_using_hwpmcs;
4572147191Sjkoshy	unsigned int ri;
4573147191Sjkoshy	uint32_t do_descendants;
4574147191Sjkoshy	struct pmc *pm;
4575147191Sjkoshy	struct pmc_owner *po;
4576147191Sjkoshy	struct pmc_process *ppnew, *ppold;
4577145256Sjkoshy
4578145256Sjkoshy	(void) flags;		/* unused parameter */
4579145256Sjkoshy
4580145256Sjkoshy	PROC_LOCK(p1);
4581145256Sjkoshy	is_using_hwpmcs = p1->p_flag & P_HWPMC;
4582145256Sjkoshy	PROC_UNLOCK(p1);
4583145256Sjkoshy
4584147191Sjkoshy	/*
4585147191Sjkoshy	 * If there are system-wide sampling PMCs active, we need to
4586147191Sjkoshy	 * log all fork events to their owner's logs.
4587147191Sjkoshy	 */
4588147191Sjkoshy
4589147191Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4590147191Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4591147191Sjkoshy		    pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4592147191Sjkoshy
4593147191Sjkoshy	if (!is_using_hwpmcs)
4594147191Sjkoshy		return;
4595147191Sjkoshy
4596147191Sjkoshy	PMC_GET_SX_XLOCK();
4597147191Sjkoshy	PMCDBG(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4598147191Sjkoshy	    p1->p_pid, p1->p_comm, newproc);
4599147191Sjkoshy
4600147191Sjkoshy	/*
4601147191Sjkoshy	 * If the parent process (curthread->td_proc) is a
4602147191Sjkoshy	 * target of any PMCs, look for PMCs that are to be
4603147191Sjkoshy	 * inherited, and link these into the new process
4604147191Sjkoshy	 * descriptor.
4605147191Sjkoshy	 */
4606147191Sjkoshy	if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4607147191Sjkoshy		 PMC_FLAG_NONE)) == NULL)
4608147191Sjkoshy		goto done;		/* nothing to do */
4609147191Sjkoshy
4610147191Sjkoshy	do_descendants = 0;
4611147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
4612147191Sjkoshy		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4613147191Sjkoshy			do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4614147191Sjkoshy	if (do_descendants == 0) /* nothing to do */
4615147191Sjkoshy		goto done;
4616147191Sjkoshy
4617147191Sjkoshy	/* allocate a descriptor for the new process  */
4618147191Sjkoshy	if ((ppnew = pmc_find_process_descriptor(newproc,
4619147191Sjkoshy		 PMC_FLAG_ALLOCATE)) == NULL)
4620147191Sjkoshy		goto done;
4621147191Sjkoshy
4622147191Sjkoshy	/*
4623147191Sjkoshy	 * Run through all PMCs that were targeting the old process
4624147191Sjkoshy	 * and which specified F_DESCENDANTS and attach them to the
4625147191Sjkoshy	 * new process.
4626147191Sjkoshy	 *
4627147191Sjkoshy	 * Log the fork event to all owners of PMCs attached to this
4628147191Sjkoshy	 * process, if not already logged.
4629147191Sjkoshy	 */
4630147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
4631147191Sjkoshy		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4632147191Sjkoshy		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
4633147191Sjkoshy			pmc_link_target_process(pm, ppnew);
4634147191Sjkoshy			po = pm->pm_owner;
4635147191Sjkoshy			if (po->po_sscount == 0 &&
4636147191Sjkoshy			    po->po_flags & PMC_PO_OWNS_LOGFILE)
4637147191Sjkoshy				pmclog_process_procfork(po, p1->p_pid,
4638147191Sjkoshy				    newproc->p_pid);
4639147191Sjkoshy		}
4640147191Sjkoshy
4641147191Sjkoshy	/*
4642147191Sjkoshy	 * Now mark the new process as being tracked by this driver.
4643147191Sjkoshy	 */
4644147191Sjkoshy	PROC_LOCK(newproc);
4645147191Sjkoshy	newproc->p_flag |= P_HWPMC;
4646147191Sjkoshy	PROC_UNLOCK(newproc);
4647147191Sjkoshy
4648147191Sjkoshy done:
4649147191Sjkoshy	sx_xunlock(&pmc_sx);
4650145256Sjkoshy}
4651145256Sjkoshy
4652145256Sjkoshy
4653145256Sjkoshy/*
4654145256Sjkoshy * initialization
4655145256Sjkoshy */
4656145256Sjkoshy
4657145256Sjkoshystatic const char *pmc_name_of_pmcclass[] = {
4658145256Sjkoshy#undef	__PMC_CLASS
4659145256Sjkoshy#define	__PMC_CLASS(N) #N ,
4660145256Sjkoshy	__PMC_CLASSES()
4661145256Sjkoshy};
4662145256Sjkoshy
4663233628Sfabient/*
4664233628Sfabient * Base class initializer: allocate structure and set default classes.
4665233628Sfabient */
4666233628Sfabientstruct pmc_mdep *
4667233628Sfabientpmc_mdep_alloc(int nclasses)
4668233628Sfabient{
4669233628Sfabient	struct pmc_mdep *md;
4670233628Sfabient	int	n;
4671233628Sfabient
4672233628Sfabient	/* SOFT + md classes */
4673233628Sfabient	n = 1 + nclasses;
4674233628Sfabient	md = malloc(sizeof(struct pmc_mdep) + n *
4675233628Sfabient	    sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
4676233628Sfabient	if (md != NULL) {
4677233628Sfabient		md->pmd_nclass = n;
4678233628Sfabient
4679233628Sfabient		/* Add base class. */
4680233628Sfabient		pmc_soft_initialize(md);
4681233628Sfabient	}
4682233628Sfabient
4683233628Sfabient	return md;
4684233628Sfabient}
4685233628Sfabient
4686233628Sfabientvoid
4687233628Sfabientpmc_mdep_free(struct pmc_mdep *md)
4688233628Sfabient{
4689233628Sfabient	pmc_soft_finalize(md);
4690233628Sfabient	free(md, M_PMC);
4691233628Sfabient}
4692233628Sfabient
4693145256Sjkoshystatic int
4694233628Sfabientgeneric_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
4695233628Sfabient{
4696233628Sfabient	(void) pc; (void) pp;
4697233628Sfabient
4698233628Sfabient	return (0);
4699233628Sfabient}
4700233628Sfabient
4701233628Sfabientstatic int
4702233628Sfabientgeneric_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
4703233628Sfabient{
4704233628Sfabient	(void) pc; (void) pp;
4705233628Sfabient
4706233628Sfabient	return (0);
4707233628Sfabient}
4708233628Sfabient
4709233628Sfabientstatic struct pmc_mdep *
4710233628Sfabientpmc_generic_cpu_initialize(void)
4711233628Sfabient{
4712233628Sfabient	struct pmc_mdep *md;
4713233628Sfabient
4714233628Sfabient	md = pmc_mdep_alloc(0);
4715233628Sfabient
4716233628Sfabient	md->pmd_cputype    = PMC_CPU_GENERIC;
4717233628Sfabient
4718233628Sfabient	md->pmd_pcpu_init  = NULL;
4719233628Sfabient	md->pmd_pcpu_fini  = NULL;
4720233628Sfabient	md->pmd_switch_in  = generic_switch_in;
4721233628Sfabient	md->pmd_switch_out = generic_switch_out;
4722233628Sfabient
4723233628Sfabient	return (md);
4724233628Sfabient}
4725233628Sfabient
4726233628Sfabientstatic void
4727233628Sfabientpmc_generic_cpu_finalize(struct pmc_mdep *md)
4728233628Sfabient{
4729233628Sfabient	(void) md;
4730233628Sfabient}
4731233628Sfabient
4732233628Sfabient
4733233628Sfabientstatic int
4734145256Sjkoshypmc_initialize(void)
4735145256Sjkoshy{
4736184802Sjkoshy	int c, cpu, error, n, ri;
4737183266Sjkoshy	unsigned int maxcpu;
4738145256Sjkoshy	struct pmc_binding pb;
4739174395Sjkoshy	struct pmc_sample *ps;
4740184802Sjkoshy	struct pmc_classdep *pcd;
4741147191Sjkoshy	struct pmc_samplebuffer *sb;
4742145256Sjkoshy
4743145256Sjkoshy	md = NULL;
4744145256Sjkoshy	error = 0;
4745145256Sjkoshy
4746153110Sru#ifdef	DEBUG
4747145256Sjkoshy	/* parse debug flags first */
4748145256Sjkoshy	if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4749145256Sjkoshy		pmc_debugstr, sizeof(pmc_debugstr)))
4750145256Sjkoshy		pmc_debugflags_parse(pmc_debugstr,
4751145256Sjkoshy		    pmc_debugstr+strlen(pmc_debugstr));
4752145256Sjkoshy#endif
4753145256Sjkoshy
4754145256Sjkoshy	PMCDBG(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4755145256Sjkoshy
4756148562Sjkoshy	/* check kernel version */
4757148562Sjkoshy	if (pmc_kernel_version != PMC_VERSION) {
4758148562Sjkoshy		if (pmc_kernel_version == 0)
4759148562Sjkoshy			printf("hwpmc: this kernel has not been compiled with "
4760148562Sjkoshy			    "'options HWPMC_HOOKS'.\n");
4761148562Sjkoshy		else
4762148562Sjkoshy			printf("hwpmc: kernel version (0x%x) does not match "
4763148562Sjkoshy			    "module version (0x%x).\n", pmc_kernel_version,
4764148562Sjkoshy			    PMC_VERSION);
4765148562Sjkoshy		return EPROGMISMATCH;
4766148562Sjkoshy	}
4767148562Sjkoshy
4768145256Sjkoshy	/*
4769145256Sjkoshy	 * check sysctl parameters
4770145256Sjkoshy	 */
4771145256Sjkoshy
4772145256Sjkoshy	if (pmc_hashsize <= 0) {
4773174395Sjkoshy		(void) printf("hwpmc: tunable \"hashsize\"=%d must be "
4774174395Sjkoshy		    "greater than zero.\n", pmc_hashsize);
4775145256Sjkoshy		pmc_hashsize = PMC_HASH_SIZE;
4776145256Sjkoshy	}
4777145256Sjkoshy
4778147191Sjkoshy	if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4779174395Sjkoshy		(void) printf("hwpmc: tunable \"nsamples\"=%d out of "
4780174395Sjkoshy		    "range.\n", pmc_nsamples);
4781147191Sjkoshy		pmc_nsamples = PMC_NSAMPLES;
4782147191Sjkoshy	}
4783145256Sjkoshy
4784174395Sjkoshy	if (pmc_callchaindepth <= 0 ||
4785174395Sjkoshy	    pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
4786174395Sjkoshy		(void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
4787174395Sjkoshy		    "range.\n", pmc_callchaindepth);
4788174395Sjkoshy		pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
4789174395Sjkoshy	}
4790174395Sjkoshy
4791147191Sjkoshy	md = pmc_md_initialize();
4792233628Sfabient	if (md == NULL) {
4793233628Sfabient		/* Default to generic CPU. */
4794233628Sfabient		md = pmc_generic_cpu_initialize();
4795233628Sfabient		if (md == NULL)
4796233628Sfabient			return (ENOSYS);
4797233628Sfabient        }
4798147191Sjkoshy
4799184802Sjkoshy	KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
4800184802Sjkoshy	    ("[pmc,%d] no classes or pmcs", __LINE__));
4801184802Sjkoshy
4802184802Sjkoshy	/* Compute the map from row-indices to classdep pointers. */
4803184802Sjkoshy	pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
4804184802Sjkoshy	    md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);
4805184802Sjkoshy
4806184802Sjkoshy	for (n = 0; n < md->pmd_npmc; n++)
4807184802Sjkoshy		pmc_rowindex_to_classdep[n] = NULL;
4808184802Sjkoshy	for (ri = c = 0; c < md->pmd_nclass; c++) {
4809184802Sjkoshy		pcd = &md->pmd_classdep[c];
4810184802Sjkoshy		for (n = 0; n < pcd->pcd_num; n++, ri++)
4811184802Sjkoshy			pmc_rowindex_to_classdep[ri] = pcd;
4812184802Sjkoshy	}
4813184802Sjkoshy
4814184802Sjkoshy	KASSERT(ri == md->pmd_npmc,
4815184802Sjkoshy	    ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
4816184802Sjkoshy	    ri, md->pmd_npmc));
4817184802Sjkoshy
4818183266Sjkoshy	maxcpu = pmc_cpu_max();
4819183266Sjkoshy
4820145256Sjkoshy	/* allocate space for the per-cpu array */
4821184802Sjkoshy	pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
4822184802Sjkoshy	    M_WAITOK|M_ZERO);
4823145256Sjkoshy
4824145256Sjkoshy	/* per-cpu 'saved values' for managing process-mode PMCs */
4825184214Sdes	pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
4826184214Sdes	    M_PMC, M_WAITOK);
4827145256Sjkoshy
4828183266Sjkoshy	/* Perform CPU-dependent initialization. */
4829145256Sjkoshy	pmc_save_cpu_binding(&pb);
4830184802Sjkoshy	error = 0;
4831184802Sjkoshy	for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
4832183266Sjkoshy		if (!pmc_cpu_is_active(cpu))
4833145256Sjkoshy			continue;
4834145256Sjkoshy		pmc_select_cpu(cpu);
4835184802Sjkoshy		pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
4836184802Sjkoshy		    md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
4837184802Sjkoshy		    M_WAITOK|M_ZERO);
4838184802Sjkoshy		if (md->pmd_pcpu_init)
4839185363Sjkoshy			error = md->pmd_pcpu_init(md, cpu);
4840184802Sjkoshy		for (n = 0; error == 0 && n < md->pmd_nclass; n++)
4841184802Sjkoshy			error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
4842145256Sjkoshy	}
4843145256Sjkoshy	pmc_restore_cpu_binding(&pb);
4844145256Sjkoshy
4845184802Sjkoshy	if (error)
4846184802Sjkoshy		return (error);
4847145256Sjkoshy
4848147191Sjkoshy	/* allocate space for the sample array */
4849183266Sjkoshy	for (cpu = 0; cpu < maxcpu; cpu++) {
4850183266Sjkoshy		if (!pmc_cpu_is_active(cpu))
4851147191Sjkoshy			continue;
4852184802Sjkoshy
4853184214Sdes		sb = malloc(sizeof(struct pmc_samplebuffer) +
4854147191Sjkoshy		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4855147191Sjkoshy		    M_WAITOK|M_ZERO);
4856147191Sjkoshy		sb->ps_read = sb->ps_write = sb->ps_samples;
4857153735Sjkoshy		sb->ps_fence = sb->ps_samples + pmc_nsamples;
4858184802Sjkoshy
4859147191Sjkoshy		KASSERT(pmc_pcpu[cpu] != NULL,
4860147191Sjkoshy		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4861147191Sjkoshy
4862184802Sjkoshy		sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4863184802Sjkoshy		    sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4864174395Sjkoshy
4865174395Sjkoshy		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4866174395Sjkoshy			ps->ps_pc = sb->ps_callchains +
4867174395Sjkoshy			    (n * pmc_callchaindepth);
4868174395Sjkoshy
4869233628Sfabient		pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
4870233628Sfabient
4871233628Sfabient		sb = malloc(sizeof(struct pmc_samplebuffer) +
4872233628Sfabient		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4873233628Sfabient		    M_WAITOK|M_ZERO);
4874233628Sfabient		sb->ps_read = sb->ps_write = sb->ps_samples;
4875233628Sfabient		sb->ps_fence = sb->ps_samples + pmc_nsamples;
4876233628Sfabient
4877233628Sfabient		KASSERT(pmc_pcpu[cpu] != NULL,
4878233628Sfabient		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4879233628Sfabient
4880233628Sfabient		sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4881233628Sfabient		    sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4882233628Sfabient
4883233628Sfabient		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4884233628Sfabient			ps->ps_pc = sb->ps_callchains +
4885233628Sfabient			    (n * pmc_callchaindepth);
4886233628Sfabient
4887233628Sfabient		pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
4888147191Sjkoshy	}
4889147191Sjkoshy
4890145256Sjkoshy	/* allocate space for the row disposition array */
4891145256Sjkoshy	pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4892145256Sjkoshy	    M_PMC, M_WAITOK|M_ZERO);
4893145256Sjkoshy
4894145256Sjkoshy	KASSERT(pmc_pmcdisp != NULL,
4895145256Sjkoshy	    ("[pmc,%d] pmcdisp allocation returned NULL", __LINE__));
4896145256Sjkoshy
4897145256Sjkoshy	/* mark all PMCs as available */
4898145256Sjkoshy	for (n = 0; n < (int) md->pmd_npmc; n++)
4899145256Sjkoshy		PMC_MARK_ROW_FREE(n);
4900145256Sjkoshy
4901145256Sjkoshy	/* allocate thread hash tables */
4902145256Sjkoshy	pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4903145256Sjkoshy	    &pmc_ownerhashmask);
4904145256Sjkoshy
4905145256Sjkoshy	pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4906145256Sjkoshy	    &pmc_processhashmask);
4907168856Sjkoshy	mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4908168856Sjkoshy	    MTX_SPIN);
4909145256Sjkoshy
4910147191Sjkoshy	LIST_INIT(&pmc_ss_owners);
4911147191Sjkoshy	pmc_ss_count = 0;
4912147191Sjkoshy
4913145256Sjkoshy	/* allocate a pool of spin mutexes */
4914168856Sjkoshy	pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4915168856Sjkoshy	    MTX_SPIN);
4916145256Sjkoshy
4917145256Sjkoshy	PMCDBG(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4918145256Sjkoshy	    "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4919145256Sjkoshy	    pmc_processhash, pmc_processhashmask);
4920145256Sjkoshy
4921145256Sjkoshy	/* register process {exit,fork,exec} handlers */
4922145256Sjkoshy	pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4923145256Sjkoshy	    pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4924145256Sjkoshy	pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4925145256Sjkoshy	    pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4926145256Sjkoshy
4927147191Sjkoshy	/* initialize logging */
4928147191Sjkoshy	pmclog_initialize();
4929147191Sjkoshy
4930145256Sjkoshy	/* set hook functions */
4931145256Sjkoshy	pmc_intr = md->pmd_intr;
4932145256Sjkoshy	pmc_hook = pmc_hook_handler;
4933145256Sjkoshy
4934145256Sjkoshy	if (error == 0) {
4935145256Sjkoshy		printf(PMC_MODULE_NAME ":");
4936149373Sjkoshy		for (n = 0; n < (int) md->pmd_nclass; n++) {
4937184802Sjkoshy			pcd = &md->pmd_classdep[n];
4938184997Sjkoshy			printf(" %s/%d/%d/0x%b",
4939184802Sjkoshy			    pmc_name_of_pmcclass[pcd->pcd_class],
4940184802Sjkoshy			    pcd->pcd_num,
4941184997Sjkoshy			    pcd->pcd_width,
4942184802Sjkoshy			    pcd->pcd_caps,
4943149373Sjkoshy			    "\20"
4944149373Sjkoshy			    "\1INT\2USR\3SYS\4EDG\5THR"
4945149373Sjkoshy			    "\6REA\7WRI\10INV\11QUA\12PRC"
4946149373Sjkoshy			    "\13TAG\14CSC");
4947149373Sjkoshy		}
4948145256Sjkoshy		printf("\n");
4949145256Sjkoshy	}
4950145256Sjkoshy
4951184802Sjkoshy	return (error);
4952145256Sjkoshy}
4953145256Sjkoshy
4954145256Sjkoshy/* prepare to be unloaded */
4955145256Sjkoshystatic void
4956145256Sjkoshypmc_cleanup(void)
4957145256Sjkoshy{
4958184802Sjkoshy	int c, cpu;
4959183266Sjkoshy	unsigned int maxcpu;
4960145256Sjkoshy	struct pmc_ownerhash *ph;
4961145256Sjkoshy	struct pmc_owner *po, *tmp;
4962145256Sjkoshy	struct pmc_binding pb;
4963153110Sru#ifdef	DEBUG
4964145256Sjkoshy	struct pmc_processhash *prh;
4965145256Sjkoshy#endif
4966145256Sjkoshy
4967145256Sjkoshy	PMCDBG(MOD,INI,0, "%s", "cleanup");
4968145256Sjkoshy
4969147191Sjkoshy	/* switch off sampling */
4970222813Sattilio	CPU_ZERO(&pmc_cpumask);
4971147191Sjkoshy	pmc_intr = NULL;
4972145256Sjkoshy
4973145256Sjkoshy	sx_xlock(&pmc_sx);
4974145256Sjkoshy	if (pmc_hook == NULL) {	/* being unloaded already */
4975145256Sjkoshy		sx_xunlock(&pmc_sx);
4976145256Sjkoshy		return;
4977145256Sjkoshy	}
4978145256Sjkoshy
4979145256Sjkoshy	pmc_hook = NULL; /* prevent new threads from entering module */
4980145256Sjkoshy
4981145256Sjkoshy	/* deregister event handlers */
4982145256Sjkoshy	EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4983145256Sjkoshy	EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4984145256Sjkoshy
4985145256Sjkoshy	/* send SIGBUS to all owner threads, free up allocations */
4986145256Sjkoshy	if (pmc_ownerhash)
4987145256Sjkoshy		for (ph = pmc_ownerhash;
4988145256Sjkoshy		     ph <= &pmc_ownerhash[pmc_ownerhashmask];
4989145256Sjkoshy		     ph++) {
4990145256Sjkoshy			LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4991145256Sjkoshy				pmc_remove_owner(po);
4992145256Sjkoshy
4993145256Sjkoshy				/* send SIGBUS to owner processes */
4994145256Sjkoshy				PMCDBG(MOD,INI,2, "cleanup signal proc=%p "
4995145256Sjkoshy				    "(%d, %s)", po->po_owner,
4996145256Sjkoshy				    po->po_owner->p_pid,
4997145256Sjkoshy				    po->po_owner->p_comm);
4998145256Sjkoshy
4999145256Sjkoshy				PROC_LOCK(po->po_owner);
5000225617Skmacy				kern_psignal(po->po_owner, SIGBUS);
5001145256Sjkoshy				PROC_UNLOCK(po->po_owner);
5002147191Sjkoshy
5003147191Sjkoshy				pmc_destroy_owner_descriptor(po);
5004145256Sjkoshy			}
5005145256Sjkoshy		}
5006145256Sjkoshy
5007145256Sjkoshy	/* reclaim allocated data structures */
5008145256Sjkoshy	if (pmc_mtxpool)
5009145256Sjkoshy		mtx_pool_destroy(&pmc_mtxpool);
5010145256Sjkoshy
5011145256Sjkoshy	mtx_destroy(&pmc_processhash_mtx);
5012145256Sjkoshy	if (pmc_processhash) {
5013153110Sru#ifdef	DEBUG
5014145256Sjkoshy		struct pmc_process *pp;
5015145256Sjkoshy
5016145256Sjkoshy		PMCDBG(MOD,INI,3, "%s", "destroy process hash");
5017145256Sjkoshy		for (prh = pmc_processhash;
5018145256Sjkoshy		     prh <= &pmc_processhash[pmc_processhashmask];
5019145256Sjkoshy		     prh++)
5020145256Sjkoshy			LIST_FOREACH(pp, prh, pp_next)
5021145256Sjkoshy			    PMCDBG(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5022145256Sjkoshy#endif
5023145256Sjkoshy
5024145256Sjkoshy		hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5025145256Sjkoshy		pmc_processhash = NULL;
5026145256Sjkoshy	}
5027145256Sjkoshy
5028145256Sjkoshy	if (pmc_ownerhash) {
5029145256Sjkoshy		PMCDBG(MOD,INI,3, "%s", "destroy owner hash");
5030145256Sjkoshy		hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5031145256Sjkoshy		pmc_ownerhash = NULL;
5032145256Sjkoshy	}
5033145256Sjkoshy
5034147191Sjkoshy	KASSERT(LIST_EMPTY(&pmc_ss_owners),
5035147191Sjkoshy	    ("[pmc,%d] Global SS owner list not empty", __LINE__));
5036147191Sjkoshy	KASSERT(pmc_ss_count == 0,
5037147191Sjkoshy	    ("[pmc,%d] Global SS count not empty", __LINE__));
5038147191Sjkoshy
5039184802Sjkoshy 	/* do processor and pmc-class dependent cleanup */
5040183266Sjkoshy	maxcpu = pmc_cpu_max();
5041153735Sjkoshy
5042145256Sjkoshy	PMCDBG(MOD,INI,3, "%s", "md cleanup");
5043145256Sjkoshy	if (md) {
5044145256Sjkoshy		pmc_save_cpu_binding(&pb);
5045183266Sjkoshy		for (cpu = 0; cpu < maxcpu; cpu++) {
5046145256Sjkoshy			PMCDBG(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5047145256Sjkoshy			    cpu, pmc_pcpu[cpu]);
5048183266Sjkoshy			if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5049145256Sjkoshy				continue;
5050145256Sjkoshy			pmc_select_cpu(cpu);
5051184802Sjkoshy			for (c = 0; c < md->pmd_nclass; c++)
5052184802Sjkoshy				md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
5053184802Sjkoshy			if (md->pmd_pcpu_fini)
5054185363Sjkoshy				md->pmd_pcpu_fini(md, cpu);
5055145256Sjkoshy		}
5056184994Sjkoshy
5057233628Sfabient		if (md->pmd_cputype == PMC_CPU_GENERIC)
5058233628Sfabient			pmc_generic_cpu_finalize(md);
5059233628Sfabient		else
5060233628Sfabient			pmc_md_finalize(md);
5061184994Sjkoshy
5062233628Sfabient		pmc_mdep_free(md);
5063145256Sjkoshy		md = NULL;
5064145256Sjkoshy		pmc_restore_cpu_binding(&pb);
5065145256Sjkoshy	}
5066145256Sjkoshy
5067184802Sjkoshy	/* Free per-cpu descriptors. */
5068184802Sjkoshy	for (cpu = 0; cpu < maxcpu; cpu++) {
5069184802Sjkoshy		if (!pmc_cpu_is_active(cpu))
5070184802Sjkoshy			continue;
5071233628Sfabient		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5072233628Sfabient		    ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5073184802Sjkoshy			cpu));
5074233628Sfabient		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5075233628Sfabient		    ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5076233628Sfabient			cpu));
5077233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
5078233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
5079233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
5080233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
5081184802Sjkoshy		free(pmc_pcpu[cpu], M_PMC);
5082184802Sjkoshy	}
5083184802Sjkoshy
5084184205Sdes	free(pmc_pcpu, M_PMC);
5085145256Sjkoshy	pmc_pcpu = NULL;
5086145256Sjkoshy
5087184205Sdes	free(pmc_pcpu_saved, M_PMC);
5088145256Sjkoshy	pmc_pcpu_saved = NULL;
5089145256Sjkoshy
5090145256Sjkoshy	if (pmc_pmcdisp) {
5091184205Sdes		free(pmc_pmcdisp, M_PMC);
5092145256Sjkoshy		pmc_pmcdisp = NULL;
5093145256Sjkoshy	}
5094145256Sjkoshy
5095184802Sjkoshy	if (pmc_rowindex_to_classdep) {
5096184802Sjkoshy		free(pmc_rowindex_to_classdep, M_PMC);
5097184802Sjkoshy		pmc_rowindex_to_classdep = NULL;
5098184802Sjkoshy	}
5099184802Sjkoshy
5100147191Sjkoshy	pmclog_shutdown();
5101147191Sjkoshy
5102145256Sjkoshy	sx_xunlock(&pmc_sx); 	/* we are done */
5103145256Sjkoshy}
5104145256Sjkoshy
5105145256Sjkoshy/*
5106145256Sjkoshy * The function called at load/unload.
5107145256Sjkoshy */
5108145256Sjkoshy
5109145256Sjkoshystatic int
5110145256Sjkoshyload (struct module *module __unused, int cmd, void *arg __unused)
5111145256Sjkoshy{
5112145256Sjkoshy	int error;
5113145256Sjkoshy
5114145256Sjkoshy	error = 0;
5115145256Sjkoshy
5116145256Sjkoshy	switch (cmd) {
5117145256Sjkoshy	case MOD_LOAD :
5118145256Sjkoshy		/* initialize the subsystem */
5119145256Sjkoshy		error = pmc_initialize();
5120145256Sjkoshy		if (error != 0)
5121145256Sjkoshy			break;
5122183266Sjkoshy		PMCDBG(MOD,INI,1, "syscall=%d maxcpu=%d",
5123183266Sjkoshy		    pmc_syscall_num, pmc_cpu_max());
5124145256Sjkoshy		break;
5125145256Sjkoshy
5126145256Sjkoshy
5127145256Sjkoshy	case MOD_UNLOAD :
5128145256Sjkoshy	case MOD_SHUTDOWN:
5129145256Sjkoshy		pmc_cleanup();
5130145256Sjkoshy		PMCDBG(MOD,INI,1, "%s", "unloaded");
5131145256Sjkoshy		break;
5132145256Sjkoshy
5133145256Sjkoshy	default :
5134145256Sjkoshy		error = EINVAL;	/* XXX should panic(9) */
5135145256Sjkoshy		break;
5136145256Sjkoshy	}
5137145256Sjkoshy
5138145256Sjkoshy	return error;
5139145256Sjkoshy}
5140145256Sjkoshy
5141145256Sjkoshy/* memory pool */
5142145256SjkoshyMALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");
5143