hwpmc_mod.c revision 298931
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 298931 2016-05-02 16:47:28Z pfg $");
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>
53248084Sattilio#include <sys/rwlock.h>
54145256Sjkoshy#include <sys/sched.h>
55145256Sjkoshy#include <sys/signalvar.h>
56145256Sjkoshy#include <sys/smp.h>
57145256Sjkoshy#include <sys/sx.h>
58145256Sjkoshy#include <sys/sysctl.h>
59145256Sjkoshy#include <sys/sysent.h>
60145256Sjkoshy#include <sys/systm.h>
61147191Sjkoshy#include <sys/vnode.h>
62145256Sjkoshy
63157144Sjkoshy#include <sys/linker.h>		/* needs to be after <sys/malloc.h> */
64157144Sjkoshy
65147191Sjkoshy#include <machine/atomic.h>
66145256Sjkoshy#include <machine/md_var.h>
67145256Sjkoshy
68201021Sjkoshy#include <vm/vm.h>
69201021Sjkoshy#include <vm/vm_extern.h>
70201021Sjkoshy#include <vm/pmap.h>
71201021Sjkoshy#include <vm/vm_map.h>
72201021Sjkoshy#include <vm/vm_object.h>
73201021Sjkoshy
74233628Sfabient#include "hwpmc_soft.h"
75233628Sfabient
76145256Sjkoshy/*
77145256Sjkoshy * Types
78145256Sjkoshy */
79145256Sjkoshy
80145256Sjkoshyenum pmc_flags {
81145256Sjkoshy	PMC_FLAG_NONE	  = 0x00, /* do nothing */
82145256Sjkoshy	PMC_FLAG_REMOVE   = 0x01, /* atomically remove entry from hash */
83145256Sjkoshy	PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
84145256Sjkoshy};
85145256Sjkoshy
86145256Sjkoshy/*
87145256Sjkoshy * The offset in sysent where the syscall is allocated.
88145256Sjkoshy */
89145256Sjkoshy
90145256Sjkoshystatic int pmc_syscall_num = NO_SYSCALL;
91145256Sjkoshystruct pmc_cpu		**pmc_pcpu;	 /* per-cpu state */
92145256Sjkoshypmc_value_t		*pmc_pcpu_saved; /* saved PMC values: CSW handling */
93145256Sjkoshy
94145256Sjkoshy#define	PMC_PCPU_SAVED(C,R)	pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
95145256Sjkoshy
96145256Sjkoshystruct mtx_pool		*pmc_mtxpool;
97145256Sjkoshystatic int		*pmc_pmcdisp;	 /* PMC row dispositions */
98145256Sjkoshy
99145256Sjkoshy#define	PMC_ROW_DISP_IS_FREE(R)		(pmc_pmcdisp[(R)] == 0)
100145256Sjkoshy#define	PMC_ROW_DISP_IS_THREAD(R)	(pmc_pmcdisp[(R)] > 0)
101145256Sjkoshy#define	PMC_ROW_DISP_IS_STANDALONE(R)	(pmc_pmcdisp[(R)] < 0)
102145256Sjkoshy
103145256Sjkoshy#define	PMC_MARK_ROW_FREE(R) do {					  \
104145256Sjkoshy	pmc_pmcdisp[(R)] = 0;						  \
105145256Sjkoshy} while (0)
106145256Sjkoshy
107145256Sjkoshy#define	PMC_MARK_ROW_STANDALONE(R) do {					  \
108145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
109145256Sjkoshy		    __LINE__));						  \
110145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
111183266Sjkoshy	KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()),		  \
112183266Sjkoshy		("[pmc,%d] row disposition error", __LINE__));		  \
113145256Sjkoshy} while (0)
114145256Sjkoshy
115145256Sjkoshy#define	PMC_UNMARK_ROW_STANDALONE(R) do { 				  \
116145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
117145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
118145256Sjkoshy		    __LINE__));						  \
119145256Sjkoshy} while (0)
120145256Sjkoshy
121145256Sjkoshy#define	PMC_MARK_ROW_THREAD(R) do {					  \
122145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
123145256Sjkoshy		    __LINE__));						  \
124145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
125145256Sjkoshy} while (0)
126145256Sjkoshy
127145256Sjkoshy#define	PMC_UNMARK_ROW_THREAD(R) do {					  \
128145256Sjkoshy	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
129145256Sjkoshy	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
130145256Sjkoshy		    __LINE__));						  \
131145256Sjkoshy} while (0)
132145256Sjkoshy
133145256Sjkoshy
134145256Sjkoshy/* various event handlers */
135254813Smarkjstatic eventhandler_tag	pmc_exit_tag, pmc_fork_tag, pmc_kld_load_tag,
136254813Smarkj    pmc_kld_unload_tag;
137145256Sjkoshy
138145256Sjkoshy/* Module statistics */
139145256Sjkoshystruct pmc_op_getdriverstats pmc_stats;
140145256Sjkoshy
141145256Sjkoshy/* Machine/processor dependent operations */
142185363Sjkoshystatic struct pmc_mdep  *md;
143145256Sjkoshy
144145256Sjkoshy/*
145145256Sjkoshy * Hash tables mapping owner processes and target threads to PMCs.
146145256Sjkoshy */
147145256Sjkoshy
148145256Sjkoshystruct mtx pmc_processhash_mtx;		/* spin mutex */
149145256Sjkoshystatic u_long pmc_processhashmask;
150145256Sjkoshystatic LIST_HEAD(pmc_processhash, pmc_process)	*pmc_processhash;
151145256Sjkoshy
152145256Sjkoshy/*
153145256Sjkoshy * Hash table of PMC owner descriptors.  This table is protected by
154145256Sjkoshy * the shared PMC "sx" lock.
155145256Sjkoshy */
156145256Sjkoshy
157145256Sjkoshystatic u_long pmc_ownerhashmask;
158145256Sjkoshystatic LIST_HEAD(pmc_ownerhash, pmc_owner)	*pmc_ownerhash;
159145256Sjkoshy
160145256Sjkoshy/*
161147191Sjkoshy * List of PMC owners with system-wide sampling PMCs.
162147191Sjkoshy */
163147191Sjkoshy
164147191Sjkoshystatic LIST_HEAD(, pmc_owner)			pmc_ss_owners;
165147191Sjkoshy
166147191Sjkoshy
167147191Sjkoshy/*
168184802Sjkoshy * A map of row indices to classdep structures.
169184802Sjkoshy */
170184802Sjkoshystatic struct pmc_classdep **pmc_rowindex_to_classdep;
171184802Sjkoshy
172184802Sjkoshy/*
173145256Sjkoshy * Prototypes
174145256Sjkoshy */
175145256Sjkoshy
176282641Sjhb#ifdef	HWPMC_DEBUG
177145256Sjkoshystatic int	pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
178145256Sjkoshystatic int	pmc_debugflags_parse(char *newstr, char *fence);
179145256Sjkoshy#endif
180145256Sjkoshy
181145256Sjkoshystatic int	load(struct module *module, int cmd, void *arg);
182147191Sjkoshystatic int	pmc_attach_process(struct proc *p, struct pmc *pm);
183145256Sjkoshystatic struct pmc *pmc_allocate_pmc_descriptor(void);
184147191Sjkoshystatic struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
185147191Sjkoshystatic int	pmc_attach_one_process(struct proc *p, struct pmc *pm);
186147191Sjkoshystatic int	pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
187147191Sjkoshy    int cpu);
188147191Sjkoshystatic int	pmc_can_attach(struct pmc *pm, struct proc *p);
189233628Sfabientstatic void	pmc_capture_user_callchain(int cpu, int soft, struct trapframe *tf);
190147191Sjkoshystatic void	pmc_cleanup(void);
191147191Sjkoshystatic int	pmc_detach_process(struct proc *p, struct pmc *pm);
192147191Sjkoshystatic int	pmc_detach_one_process(struct proc *p, struct pmc *pm,
193147191Sjkoshy    int flags);
194147191Sjkoshystatic void	pmc_destroy_owner_descriptor(struct pmc_owner *po);
195273236Smarkjstatic void	pmc_destroy_pmc_descriptor(struct pmc *pm);
196147191Sjkoshystatic struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
197147191Sjkoshystatic int	pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
198145256Sjkoshystatic struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
199145256Sjkoshy    pmc_id_t pmc);
200145256Sjkoshystatic struct pmc_process *pmc_find_process_descriptor(struct proc *p,
201145256Sjkoshy    uint32_t mode);
202145774Sjkoshystatic void	pmc_force_context_switch(void);
203145256Sjkoshystatic void	pmc_link_target_process(struct pmc *pm,
204145256Sjkoshy    struct pmc_process *pp);
205174395Sjkoshystatic void	pmc_log_all_process_mappings(struct pmc_owner *po);
206174395Sjkoshystatic void	pmc_log_kernel_mappings(struct pmc *pm);
207174395Sjkoshystatic void	pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
208147191Sjkoshystatic void	pmc_maybe_remove_owner(struct pmc_owner *po);
209147191Sjkoshystatic void	pmc_process_csw_in(struct thread *td);
210147191Sjkoshystatic void	pmc_process_csw_out(struct thread *td);
211145256Sjkoshystatic void	pmc_process_exit(void *arg, struct proc *p);
212145256Sjkoshystatic void	pmc_process_fork(void *arg, struct proc *p1,
213145256Sjkoshy    struct proc *p2, int n);
214233628Sfabientstatic void	pmc_process_samples(int cpu, int soft);
215147191Sjkoshystatic void	pmc_release_pmc_descriptor(struct pmc *pmc);
216147191Sjkoshystatic void	pmc_remove_owner(struct pmc_owner *po);
217147191Sjkoshystatic void	pmc_remove_process_descriptor(struct pmc_process *pp);
218147191Sjkoshystatic void	pmc_restore_cpu_binding(struct pmc_binding *pb);
219147191Sjkoshystatic void	pmc_save_cpu_binding(struct pmc_binding *pb);
220147191Sjkoshystatic void	pmc_select_cpu(int cpu);
221145256Sjkoshystatic int	pmc_start(struct pmc *pm);
222145256Sjkoshystatic int	pmc_stop(struct pmc *pm);
223147191Sjkoshystatic int	pmc_syscall_handler(struct thread *td, void *syscall_args);
224147191Sjkoshystatic void	pmc_unlink_target_process(struct pmc *pmc,
225147191Sjkoshy    struct pmc_process *pp);
226233628Sfabientstatic int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
227233628Sfabientstatic int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
228233628Sfabientstatic struct pmc_mdep *pmc_generic_cpu_initialize(void);
229233628Sfabientstatic void pmc_generic_cpu_finalize(struct pmc_mdep *md);
230145256Sjkoshy
231145256Sjkoshy/*
232145256Sjkoshy * Kernel tunables and sysctl(8) interface.
233145256Sjkoshy */
234145256Sjkoshy
235233628SfabientSYSCTL_DECL(_kern_hwpmc);
236145256Sjkoshy
237174395Sjkoshystatic int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
238267992ShselaskySYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_RDTUN,
239174395Sjkoshy    &pmc_callchaindepth, 0, "depth of call chain records");
240174395Sjkoshy
241282641Sjhb#ifdef	HWPMC_DEBUG
242147191Sjkoshystruct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
243145256Sjkoshychar	pmc_debugstr[PMC_DEBUG_STRSIZE];
244145256SjkoshyTUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
245145256Sjkoshy    sizeof(pmc_debugstr));
246145256SjkoshySYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
247267992Shselasky    CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
248145256Sjkoshy    0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
249145256Sjkoshy#endif
250145256Sjkoshy
251145256Sjkoshy/*
252147191Sjkoshy * kern.hwpmc.hashrows -- determines the number of rows in the
253145256Sjkoshy * of the hash table used to look up threads
254145256Sjkoshy */
255145256Sjkoshy
256145256Sjkoshystatic int pmc_hashsize = PMC_HASH_SIZE;
257267992ShselaskySYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_RDTUN,
258145256Sjkoshy    &pmc_hashsize, 0, "rows in hash tables");
259145256Sjkoshy
260145256Sjkoshy/*
261174395Sjkoshy * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
262145256Sjkoshy */
263145256Sjkoshy
264147191Sjkoshystatic int pmc_nsamples = PMC_NSAMPLES;
265267992ShselaskySYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_RDTUN,
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;
274267992ShselaskySYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_RDTUN,
275145256Sjkoshy    &pmc_mtxpool_size, 0, "size of spin mutex pool");
276145256Sjkoshy
277145256Sjkoshy
278145256Sjkoshy/*
279145256Sjkoshy * security.bsd.unprivileged_syspmcs -- allow non-root processes to
280145256Sjkoshy * allocate system-wide PMCs.
281145256Sjkoshy *
282145256Sjkoshy * Allowing unprivileged processes to allocate system PMCs is convenient
283145256Sjkoshy * if system-wide measurements need to be taken concurrently with other
284145256Sjkoshy * per-process measurements.  This feature is turned off by default.
285145256Sjkoshy */
286145256Sjkoshy
287145256Sjkoshystatic int pmc_unprivileged_syspmcs = 0;
288267992ShselaskySYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RWTUN,
289145256Sjkoshy    &pmc_unprivileged_syspmcs, 0,
290145256Sjkoshy    "allow unprivileged process to allocate system PMCs");
291145256Sjkoshy
292147191Sjkoshy/*
293147191Sjkoshy * Hash function.  Discard the lower 2 bits of the pointer since
294147191Sjkoshy * these are always zero for our uses.  The hash multiplier is
295147191Sjkoshy * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
296147191Sjkoshy */
297145256Sjkoshy
298145256Sjkoshy#if	LONG_BIT == 64
299145256Sjkoshy#define	_PMC_HM		11400714819323198486u
300145256Sjkoshy#elif	LONG_BIT == 32
301145256Sjkoshy#define	_PMC_HM		2654435769u
302145256Sjkoshy#else
303145256Sjkoshy#error 	Must know the size of 'long' to compile
304145256Sjkoshy#endif
305145256Sjkoshy
306145256Sjkoshy#define	PMC_HASH_PTR(P,M)	((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
307145256Sjkoshy
308145256Sjkoshy/*
309145256Sjkoshy * Syscall structures
310145256Sjkoshy */
311145256Sjkoshy
312145256Sjkoshy/* The `sysent' for the new syscall */
313145256Sjkoshystatic struct sysent pmc_sysent = {
314145256Sjkoshy	2,			/* sy_narg */
315145256Sjkoshy	pmc_syscall_handler	/* sy_call */
316145256Sjkoshy};
317145256Sjkoshy
318145256Sjkoshystatic struct syscall_module_data pmc_syscall_mod = {
319145256Sjkoshy	load,
320145256Sjkoshy	NULL,
321145256Sjkoshy	&pmc_syscall_num,
322145256Sjkoshy	&pmc_sysent,
323277177Srrs#if (__FreeBSD_version >= 1100000)
324273953Smjg	{ 0, NULL },
325273953Smjg	SY_THR_STATIC_KLD,
326277177Srrs#else
327277177Srrs	{ 0, NULL }
328277177Srrs#endif
329145256Sjkoshy};
330145256Sjkoshy
331145256Sjkoshystatic moduledata_t pmc_mod = {
332145256Sjkoshy	PMC_MODULE_NAME,
333145256Sjkoshy	syscall_module_handler,
334145256Sjkoshy	&pmc_syscall_mod
335145256Sjkoshy};
336145256Sjkoshy
337145256SjkoshyDECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
338145256SjkoshyMODULE_VERSION(pmc, PMC_VERSION);
339145256Sjkoshy
340282641Sjhb#ifdef	HWPMC_DEBUG
341147191Sjkoshyenum pmc_dbgparse_state {
342147191Sjkoshy	PMCDS_WS,		/* in whitespace */
343147191Sjkoshy	PMCDS_MAJOR,		/* seen a major keyword */
344147191Sjkoshy	PMCDS_MINOR
345147191Sjkoshy};
346147191Sjkoshy
347145256Sjkoshystatic int
348145256Sjkoshypmc_debugflags_parse(char *newstr, char *fence)
349145256Sjkoshy{
350145313Sjkoshy	char c, *p, *q;
351147191Sjkoshy	struct pmc_debugflags *tmpflags;
352147191Sjkoshy	int error, found, *newbits, tmp;
353147191Sjkoshy	size_t kwlen;
354145256Sjkoshy
355184214Sdes	tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK|M_ZERO);
356145256Sjkoshy
357145256Sjkoshy	p = newstr;
358147191Sjkoshy	error = 0;
359145256Sjkoshy
360147191Sjkoshy	for (; p < fence && (c = *p); p++) {
361145256Sjkoshy
362147191Sjkoshy		/* skip white space */
363147191Sjkoshy		if (c == ' ' || c == '\t')
364147191Sjkoshy			continue;
365147191Sjkoshy
366147191Sjkoshy		/* look for a keyword followed by "=" */
367147191Sjkoshy		for (q = p; p < fence && (c = *p) && c != '='; p++)
368147191Sjkoshy			;
369147191Sjkoshy		if (c != '=') {
370147191Sjkoshy			error = EINVAL;
371147191Sjkoshy			goto done;
372145256Sjkoshy		}
373145256Sjkoshy
374147191Sjkoshy		kwlen = p - q;
375147191Sjkoshy		newbits = NULL;
376145256Sjkoshy
377147191Sjkoshy		/* lookup flag group name */
378147191Sjkoshy#define	DBG_SET_FLAG_MAJ(S,F)						\
379147191Sjkoshy		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
380147191Sjkoshy			newbits = &tmpflags->pdb_ ## F;
381145256Sjkoshy
382147191Sjkoshy		DBG_SET_FLAG_MAJ("cpu",		CPU);
383147191Sjkoshy		DBG_SET_FLAG_MAJ("csw",		CSW);
384147191Sjkoshy		DBG_SET_FLAG_MAJ("logging",	LOG);
385147191Sjkoshy		DBG_SET_FLAG_MAJ("module",	MOD);
386147191Sjkoshy		DBG_SET_FLAG_MAJ("md", 		MDP);
387147191Sjkoshy		DBG_SET_FLAG_MAJ("owner",	OWN);
388147191Sjkoshy		DBG_SET_FLAG_MAJ("pmc",		PMC);
389147191Sjkoshy		DBG_SET_FLAG_MAJ("process",	PRC);
390147191Sjkoshy		DBG_SET_FLAG_MAJ("sampling", 	SAM);
391145256Sjkoshy
392147191Sjkoshy		if (newbits == NULL) {
393147191Sjkoshy			error = EINVAL;
394147191Sjkoshy			goto done;
395145256Sjkoshy		}
396145256Sjkoshy
397147191Sjkoshy		p++;		/* skip the '=' */
398145256Sjkoshy
399147191Sjkoshy		/* Now parse the individual flags */
400147191Sjkoshy		tmp = 0;
401147191Sjkoshy	newflag:
402147191Sjkoshy		for (q = p; p < fence && (c = *p); p++)
403147191Sjkoshy			if (c == ' ' || c == '\t' || c == ',')
404147191Sjkoshy				break;
405147191Sjkoshy
406147191Sjkoshy		/* p == fence or c == ws or c == "," or c == 0 */
407147191Sjkoshy
408147191Sjkoshy		if ((kwlen = p - q) == 0) {
409147191Sjkoshy			*newbits = tmp;
410147191Sjkoshy			continue;
411147191Sjkoshy		}
412147191Sjkoshy
413147191Sjkoshy		found = 0;
414147191Sjkoshy#define	DBG_SET_FLAG_MIN(S,F)						\
415147191Sjkoshy		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
416147191Sjkoshy			tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
417147191Sjkoshy
418147191Sjkoshy		/* a '*' denotes all possible flags in the group */
419147191Sjkoshy		if (kwlen == 1 && *q == '*')
420147191Sjkoshy			tmp = found = ~0;
421147191Sjkoshy		/* look for individual flag names */
422147191Sjkoshy		DBG_SET_FLAG_MIN("allocaterow", ALR);
423147191Sjkoshy		DBG_SET_FLAG_MIN("allocate",	ALL);
424147191Sjkoshy		DBG_SET_FLAG_MIN("attach",	ATT);
425147191Sjkoshy		DBG_SET_FLAG_MIN("bind",	BND);
426147191Sjkoshy		DBG_SET_FLAG_MIN("config",	CFG);
427147191Sjkoshy		DBG_SET_FLAG_MIN("exec",	EXC);
428147191Sjkoshy		DBG_SET_FLAG_MIN("exit",	EXT);
429147191Sjkoshy		DBG_SET_FLAG_MIN("find",	FND);
430147191Sjkoshy		DBG_SET_FLAG_MIN("flush",	FLS);
431147191Sjkoshy		DBG_SET_FLAG_MIN("fork",	FRK);
432147191Sjkoshy		DBG_SET_FLAG_MIN("getbuf",	GTB);
433147191Sjkoshy		DBG_SET_FLAG_MIN("hook",	PMH);
434147191Sjkoshy		DBG_SET_FLAG_MIN("init",	INI);
435147191Sjkoshy		DBG_SET_FLAG_MIN("intr",	INT);
436147191Sjkoshy		DBG_SET_FLAG_MIN("linktarget",	TLK);
437147191Sjkoshy		DBG_SET_FLAG_MIN("mayberemove", OMR);
438147191Sjkoshy		DBG_SET_FLAG_MIN("ops",		OPS);
439147191Sjkoshy		DBG_SET_FLAG_MIN("read",	REA);
440147191Sjkoshy		DBG_SET_FLAG_MIN("register",	REG);
441147191Sjkoshy		DBG_SET_FLAG_MIN("release",	REL);
442147191Sjkoshy		DBG_SET_FLAG_MIN("remove",	ORM);
443147191Sjkoshy		DBG_SET_FLAG_MIN("sample",	SAM);
444147191Sjkoshy		DBG_SET_FLAG_MIN("scheduleio",	SIO);
445147191Sjkoshy		DBG_SET_FLAG_MIN("select",	SEL);
446147191Sjkoshy		DBG_SET_FLAG_MIN("signal",	SIG);
447147191Sjkoshy		DBG_SET_FLAG_MIN("swi",		SWI);
448147191Sjkoshy		DBG_SET_FLAG_MIN("swo",		SWO);
449147191Sjkoshy		DBG_SET_FLAG_MIN("start",	STA);
450147191Sjkoshy		DBG_SET_FLAG_MIN("stop",	STO);
451147191Sjkoshy		DBG_SET_FLAG_MIN("syscall",	PMS);
452147191Sjkoshy		DBG_SET_FLAG_MIN("unlinktarget", TUL);
453147191Sjkoshy		DBG_SET_FLAG_MIN("write",	WRI);
454147191Sjkoshy		if (found == 0) {
455147191Sjkoshy			/* unrecognized flag name */
456147191Sjkoshy			error = EINVAL;
457147191Sjkoshy			goto done;
458147191Sjkoshy		}
459147191Sjkoshy
460147191Sjkoshy		if (c == 0 || c == ' ' || c == '\t') {	/* end of flag group */
461147191Sjkoshy			*newbits = tmp;
462147191Sjkoshy			continue;
463147191Sjkoshy		}
464147191Sjkoshy
465147191Sjkoshy		p++;
466147191Sjkoshy		goto newflag;
467145256Sjkoshy	}
468145256Sjkoshy
469147191Sjkoshy	/* save the new flag set */
470147191Sjkoshy	bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
471145256Sjkoshy
472147191Sjkoshy done:
473184205Sdes	free(tmpflags, M_PMC);
474147191Sjkoshy	return error;
475145256Sjkoshy}
476145256Sjkoshy
477145256Sjkoshystatic int
478145256Sjkoshypmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
479145256Sjkoshy{
480145256Sjkoshy	char *fence, *newstr;
481145256Sjkoshy	int error;
482145256Sjkoshy	unsigned int n;
483145256Sjkoshy
484145256Sjkoshy	(void) arg1; (void) arg2; /* unused parameters */
485145256Sjkoshy
486145256Sjkoshy	n = sizeof(pmc_debugstr);
487184802Sjkoshy	newstr = malloc(n, M_PMC, M_WAITOK|M_ZERO);
488147191Sjkoshy	(void) strlcpy(newstr, pmc_debugstr, n);
489145256Sjkoshy
490145256Sjkoshy	error = sysctl_handle_string(oidp, newstr, n, req);
491145256Sjkoshy
492145256Sjkoshy	/* if there is a new string, parse and copy it */
493145256Sjkoshy	if (error == 0 && req->newptr != NULL) {
494147191Sjkoshy		fence = newstr + (n < req->newlen ? n : req->newlen + 1);
495145256Sjkoshy		if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
496145256Sjkoshy			(void) strlcpy(pmc_debugstr, newstr,
497145256Sjkoshy			    sizeof(pmc_debugstr));
498145256Sjkoshy	}
499145256Sjkoshy
500184205Sdes	free(newstr, M_PMC);
501145256Sjkoshy
502145256Sjkoshy	return error;
503145256Sjkoshy}
504145256Sjkoshy#endif
505145256Sjkoshy
506145256Sjkoshy/*
507184802Sjkoshy * Map a row index to a classdep structure and return the adjusted row
508184802Sjkoshy * index for the PMC class index.
509184802Sjkoshy */
510184802Sjkoshystatic struct pmc_classdep *
511184802Sjkoshypmc_ri_to_classdep(struct pmc_mdep *md, int ri, int *adjri)
512184802Sjkoshy{
513184802Sjkoshy	struct pmc_classdep *pcd;
514184802Sjkoshy
515184802Sjkoshy	(void) md;
516184802Sjkoshy
517184802Sjkoshy	KASSERT(ri >= 0 && ri < md->pmd_npmc,
518184802Sjkoshy	    ("[pmc,%d] illegal row-index %d", __LINE__, ri));
519184802Sjkoshy
520184802Sjkoshy	pcd = pmc_rowindex_to_classdep[ri];
521184802Sjkoshy
522184802Sjkoshy	KASSERT(pcd != NULL,
523198204Srpaulo	    ("[pmc,%d] ri %d null pcd", __LINE__, ri));
524184802Sjkoshy
525184802Sjkoshy	*adjri = ri - pcd->pcd_ri;
526184802Sjkoshy
527184802Sjkoshy	KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
528184802Sjkoshy	    ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));
529184802Sjkoshy
530184802Sjkoshy	return (pcd);
531184802Sjkoshy}
532184802Sjkoshy
533184802Sjkoshy/*
534145256Sjkoshy * Concurrency Control
535145256Sjkoshy *
536145256Sjkoshy * The driver manages the following data structures:
537145256Sjkoshy *
538145256Sjkoshy *   - target process descriptors, one per target process
539145256Sjkoshy *   - owner process descriptors (and attached lists), one per owner process
540145256Sjkoshy *   - lookup hash tables for owner and target processes
541145256Sjkoshy *   - PMC descriptors (and attached lists)
542145256Sjkoshy *   - per-cpu hardware state
543145256Sjkoshy *   - the 'hook' variable through which the kernel calls into
544145256Sjkoshy *     this module
545145256Sjkoshy *   - the machine hardware state (managed by the MD layer)
546145256Sjkoshy *
547145256Sjkoshy * These data structures are accessed from:
548145256Sjkoshy *
549145256Sjkoshy * - thread context-switch code
550145256Sjkoshy * - interrupt handlers (possibly on multiple cpus)
551145256Sjkoshy * - kernel threads on multiple cpus running on behalf of user
552145256Sjkoshy *   processes doing system calls
553145256Sjkoshy * - this driver's private kernel threads
554145256Sjkoshy *
555145256Sjkoshy * = Locks and Locking strategy =
556145256Sjkoshy *
557145256Sjkoshy * The driver uses four locking strategies for its operation:
558145256Sjkoshy *
559168856Sjkoshy * - The global SX lock "pmc_sx" is used to protect internal
560168856Sjkoshy *   data structures.
561145256Sjkoshy *
562168856Sjkoshy *   Calls into the module by syscall() start with this lock being
563168856Sjkoshy *   held in exclusive mode.  Depending on the requested operation,
564168856Sjkoshy *   the lock may be downgraded to 'shared' mode to allow more
565168856Sjkoshy *   concurrent readers into the module.  Calls into the module from
566168856Sjkoshy *   other parts of the kernel acquire the lock in shared mode.
567145256Sjkoshy *
568145256Sjkoshy *   This SX lock is held in exclusive mode for any operations that
569145256Sjkoshy *   modify the linkages between the driver's internal data structures.
570145256Sjkoshy *
571145256Sjkoshy *   The 'pmc_hook' function pointer is also protected by this lock.
572145256Sjkoshy *   It is only examined with the sx lock held in exclusive mode.  The
573168856Sjkoshy *   kernel module is allowed to be unloaded only with the sx lock held
574168856Sjkoshy *   in exclusive mode.  In normal syscall handling, after acquiring the
575168856Sjkoshy *   pmc_sx lock we first check that 'pmc_hook' is non-null before
576168856Sjkoshy *   proceeding.  This prevents races between the thread unloading the module
577168856Sjkoshy *   and other threads seeking to use the module.
578145256Sjkoshy *
579145256Sjkoshy * - Lookups of target process structures and owner process structures
580145256Sjkoshy *   cannot use the global "pmc_sx" SX lock because these lookups need
581145256Sjkoshy *   to happen during context switches and in other critical sections
582145256Sjkoshy *   where sleeping is not allowed.  We protect these lookup tables
583145256Sjkoshy *   with their own private spin-mutexes, "pmc_processhash_mtx" and
584168856Sjkoshy *   "pmc_ownerhash_mtx".
585145256Sjkoshy *
586145256Sjkoshy * - Interrupt handlers work in a lock free manner.  At interrupt
587145256Sjkoshy *   time, handlers look at the PMC pointer (phw->phw_pmc) configured
588145256Sjkoshy *   when the PMC was started.  If this pointer is NULL, the interrupt
589145256Sjkoshy *   is ignored after updating driver statistics.  We ensure that this
590145256Sjkoshy *   pointer is set (using an atomic operation if necessary) before the
591145256Sjkoshy *   PMC hardware is started.  Conversely, this pointer is unset atomically
592145256Sjkoshy *   only after the PMC hardware is stopped.
593145256Sjkoshy *
594145256Sjkoshy *   We ensure that everything needed for the operation of an
595145256Sjkoshy *   interrupt handler is available without it needing to acquire any
596145256Sjkoshy *   locks.  We also ensure that a PMC's software state is destroyed only
597145256Sjkoshy *   after the PMC is taken off hardware (on all CPUs).
598145256Sjkoshy *
599145256Sjkoshy * - Context-switch handling with process-private PMCs needs more
600145256Sjkoshy *   care.
601145256Sjkoshy *
602145256Sjkoshy *   A given process may be the target of multiple PMCs.  For example,
603145256Sjkoshy *   PMCATTACH and PMCDETACH may be requested by a process on one CPU
604145256Sjkoshy *   while the target process is running on another.  A PMC could also
605145256Sjkoshy *   be getting released because its owner is exiting.  We tackle
606145256Sjkoshy *   these situations in the following manner:
607145256Sjkoshy *
608145256Sjkoshy *   - each target process structure 'pmc_process' has an array
609145256Sjkoshy *     of 'struct pmc *' pointers, one for each hardware PMC.
610145256Sjkoshy *
611145256Sjkoshy *   - At context switch IN time, each "target" PMC in RUNNING state
612145256Sjkoshy *     gets started on hardware and a pointer to each PMC is copied into
613145256Sjkoshy *     the per-cpu phw array.  The 'runcount' for the PMC is
614145256Sjkoshy *     incremented.
615145256Sjkoshy *
616145256Sjkoshy *   - At context switch OUT time, all process-virtual PMCs are stopped
617145256Sjkoshy *     on hardware.  The saved value is added to the PMCs value field
618145256Sjkoshy *     only if the PMC is in a non-deleted state (the PMCs state could
619145256Sjkoshy *     have changed during the current time slice).
620145256Sjkoshy *
621145256Sjkoshy *     Note that since in-between a switch IN on a processor and a switch
622145256Sjkoshy *     OUT, the PMC could have been released on another CPU.  Therefore
623145256Sjkoshy *     context switch OUT always looks at the hardware state to turn
624145256Sjkoshy *     OFF PMCs and will update a PMC's saved value only if reachable
625145256Sjkoshy *     from the target process record.
626145256Sjkoshy *
627145256Sjkoshy *   - OP PMCRELEASE could be called on a PMC at any time (the PMC could
628145256Sjkoshy *     be attached to many processes at the time of the call and could
629145256Sjkoshy *     be active on multiple CPUs).
630145256Sjkoshy *
631145256Sjkoshy *     We prevent further scheduling of the PMC by marking it as in
632145256Sjkoshy *     state 'DELETED'.  If the runcount of the PMC is non-zero then
633145256Sjkoshy *     this PMC is currently running on a CPU somewhere.  The thread
634167086Sjhb *     doing the PMCRELEASE operation waits by repeatedly doing a
635167086Sjhb *     pause() till the runcount comes to zero.
636145256Sjkoshy *
637168856Sjkoshy * The contents of a PMC descriptor (struct pmc) are protected using
638168856Sjkoshy * a spin-mutex.  In order to save space, we use a mutex pool.
639168856Sjkoshy *
640168856Sjkoshy * In terms of lock types used by witness(4), we use:
641168856Sjkoshy * - Type "pmc-sx", used by the global SX lock.
642168856Sjkoshy * - Type "pmc-sleep", for sleep mutexes used by logger threads.
643168856Sjkoshy * - Type "pmc-per-proc", for protecting PMC owner descriptors.
644168856Sjkoshy * - Type "pmc-leaf", used for all other spin mutexes.
645145256Sjkoshy */
646145256Sjkoshy
647145256Sjkoshy/*
648145256Sjkoshy * save the cpu binding of the current kthread
649145256Sjkoshy */
650145256Sjkoshy
651145256Sjkoshystatic void
652145256Sjkoshypmc_save_cpu_binding(struct pmc_binding *pb)
653145256Sjkoshy{
654282658Sjhb	PMCDBG0(CPU,BND,2, "save-cpu");
655170307Sjeff	thread_lock(curthread);
656145256Sjkoshy	pb->pb_bound = sched_is_bound(curthread);
657145256Sjkoshy	pb->pb_cpu   = curthread->td_oncpu;
658170307Sjeff	thread_unlock(curthread);
659282658Sjhb	PMCDBG1(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
660145256Sjkoshy}
661145256Sjkoshy
662145256Sjkoshy/*
663145256Sjkoshy * restore the cpu binding of the current thread
664145256Sjkoshy */
665145256Sjkoshy
666145256Sjkoshystatic void
667145256Sjkoshypmc_restore_cpu_binding(struct pmc_binding *pb)
668145256Sjkoshy{
669282658Sjhb	PMCDBG2(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
670145256Sjkoshy	    curthread->td_oncpu, pb->pb_cpu);
671170307Sjeff	thread_lock(curthread);
672145256Sjkoshy	if (pb->pb_bound)
673145256Sjkoshy		sched_bind(curthread, pb->pb_cpu);
674145256Sjkoshy	else
675145256Sjkoshy		sched_unbind(curthread);
676170307Sjeff	thread_unlock(curthread);
677282658Sjhb	PMCDBG0(CPU,BND,2, "restore-cpu done");
678145256Sjkoshy}
679145256Sjkoshy
680145256Sjkoshy/*
681145256Sjkoshy * move execution over the specified cpu and bind it there.
682145256Sjkoshy */
683145256Sjkoshy
684145256Sjkoshystatic void
685145256Sjkoshypmc_select_cpu(int cpu)
686145256Sjkoshy{
687183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
688145256Sjkoshy	    ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
689145256Sjkoshy
690183266Sjkoshy	/* Never move to an inactive CPU. */
691183266Sjkoshy	KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
692183266Sjkoshy	    "CPU %d", __LINE__, cpu));
693145256Sjkoshy
694282658Sjhb	PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d", cpu);
695170307Sjeff	thread_lock(curthread);
696145256Sjkoshy	sched_bind(curthread, cpu);
697170307Sjeff	thread_unlock(curthread);
698145256Sjkoshy
699145256Sjkoshy	KASSERT(curthread->td_oncpu == cpu,
700145256Sjkoshy	    ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
701145256Sjkoshy		cpu, curthread->td_oncpu));
702145256Sjkoshy
703282658Sjhb	PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
704145256Sjkoshy}
705145256Sjkoshy
706145256Sjkoshy/*
707145774Sjkoshy * Force a context switch.
708145774Sjkoshy *
709167086Sjhb * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
710145774Sjkoshy * guaranteed to force a context switch.
711145774Sjkoshy */
712145774Sjkoshy
713145774Sjkoshystatic void
714145774Sjkoshypmc_force_context_switch(void)
715145774Sjkoshy{
716145774Sjkoshy
717167086Sjhb	pause("pmcctx", 1);
718145774Sjkoshy}
719145774Sjkoshy
720145774Sjkoshy/*
721147191Sjkoshy * Get the file name for an executable.  This is a simple wrapper
722147191Sjkoshy * around vn_fullpath(9).
723145256Sjkoshy */
724145256Sjkoshy
725147191Sjkoshystatic void
726147708Sjkoshypmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
727145256Sjkoshy{
728145256Sjkoshy
729147191Sjkoshy	*fullpath = "unknown";
730147191Sjkoshy	*freepath = NULL;
731175294Sattilio	vn_fullpath(curthread, v, fullpath, freepath);
732145256Sjkoshy}
733145256Sjkoshy
734145256Sjkoshy/*
735145256Sjkoshy * remove an process owning PMCs
736145256Sjkoshy */
737145256Sjkoshy
738145256Sjkoshyvoid
739145256Sjkoshypmc_remove_owner(struct pmc_owner *po)
740145256Sjkoshy{
741147191Sjkoshy	struct pmc *pm, *tmp;
742145256Sjkoshy
743145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
744145256Sjkoshy
745282658Sjhb	PMCDBG1(OWN,ORM,1, "remove-owner po=%p", po);
746145256Sjkoshy
747145256Sjkoshy	/* Remove descriptor from the owner hash table */
748145256Sjkoshy	LIST_REMOVE(po, po_next);
749145256Sjkoshy
750147191Sjkoshy	/* release all owned PMC descriptors */
751147191Sjkoshy	LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
752282658Sjhb		PMCDBG1(OWN,ORM,2, "pmc=%p", pm);
753147191Sjkoshy		KASSERT(pm->pm_owner == po,
754147191Sjkoshy		    ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
755145256Sjkoshy
756147191Sjkoshy		pmc_release_pmc_descriptor(pm);	/* will unlink from the list */
757273236Smarkj		pmc_destroy_pmc_descriptor(pm);
758145256Sjkoshy	}
759145256Sjkoshy
760147191Sjkoshy	KASSERT(po->po_sscount == 0,
761147191Sjkoshy	    ("[pmc,%d] SS count not zero", __LINE__));
762145256Sjkoshy	KASSERT(LIST_EMPTY(&po->po_pmcs),
763147191Sjkoshy	    ("[pmc,%d] PMC list not empty", __LINE__));
764145256Sjkoshy
765147191Sjkoshy	/* de-configure the log file if present */
766145774Sjkoshy	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
767147191Sjkoshy		pmclog_deconfigure_log(po);
768145256Sjkoshy}
769145256Sjkoshy
770145256Sjkoshy/*
771145256Sjkoshy * remove an owner process record if all conditions are met.
772145256Sjkoshy */
773145256Sjkoshy
774145256Sjkoshystatic void
775145256Sjkoshypmc_maybe_remove_owner(struct pmc_owner *po)
776145256Sjkoshy{
777145256Sjkoshy
778282658Sjhb	PMCDBG1(OWN,OMR,1, "maybe-remove-owner po=%p", po);
779145256Sjkoshy
780145256Sjkoshy	/*
781145256Sjkoshy	 * Remove owner record if
782145256Sjkoshy	 * - this process does not own any PMCs
783145256Sjkoshy	 * - this process has not allocated a system-wide sampling buffer
784145256Sjkoshy	 */
785145256Sjkoshy
786145256Sjkoshy	if (LIST_EMPTY(&po->po_pmcs) &&
787145774Sjkoshy	    ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
788145256Sjkoshy		pmc_remove_owner(po);
789147191Sjkoshy		pmc_destroy_owner_descriptor(po);
790145256Sjkoshy	}
791145256Sjkoshy}
792145256Sjkoshy
793145256Sjkoshy/*
794145256Sjkoshy * Add an association between a target process and a PMC.
795145256Sjkoshy */
796145256Sjkoshy
797145256Sjkoshystatic void
798145256Sjkoshypmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
799145256Sjkoshy{
800145256Sjkoshy	int ri;
801145256Sjkoshy	struct pmc_target *pt;
802145256Sjkoshy
803145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
804145256Sjkoshy
805145256Sjkoshy	KASSERT(pm != NULL && pp != NULL,
806145256Sjkoshy	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
807147191Sjkoshy	KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
808147191Sjkoshy	    ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
809147191Sjkoshy		__LINE__, pm, pp->pp_proc->p_pid));
810198343Sfabient	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1),
811145256Sjkoshy	    ("[pmc,%d] Illegal reference count %d for process record %p",
812145256Sjkoshy		__LINE__, pp->pp_refcnt, (void *) pp));
813145256Sjkoshy
814145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
815145256Sjkoshy
816282658Sjhb	PMCDBG3(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
817145256Sjkoshy	    pm, ri, pp);
818145256Sjkoshy
819282641Sjhb#ifdef	HWPMC_DEBUG
820145256Sjkoshy	LIST_FOREACH(pt, &pm->pm_targets, pt_next)
821145256Sjkoshy	    if (pt->pt_process == pp)
822145256Sjkoshy		    KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
823145256Sjkoshy				__LINE__, pp, pm));
824145256Sjkoshy#endif
825145256Sjkoshy
826184802Sjkoshy	pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK|M_ZERO);
827145256Sjkoshy	pt->pt_process = pp;
828145256Sjkoshy
829145256Sjkoshy	LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
830145256Sjkoshy
831148067Sjhb	atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
832148067Sjhb	    (uintptr_t)pm);
833145256Sjkoshy
834145615Sjkoshy	if (pm->pm_owner->po_owner == pp->pp_proc)
835145774Sjkoshy		pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
836145615Sjkoshy
837147191Sjkoshy	/*
838147191Sjkoshy	 * Initialize the per-process values at this row index.
839147191Sjkoshy	 */
840147191Sjkoshy	pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
841147191Sjkoshy	    pm->pm_sc.pm_reloadcount : 0;
842147191Sjkoshy
843145256Sjkoshy	pp->pp_refcnt++;
844145256Sjkoshy
845145256Sjkoshy}
846145256Sjkoshy
847145256Sjkoshy/*
848145256Sjkoshy * Removes the association between a target process and a PMC.
849145256Sjkoshy */
850145256Sjkoshy
851145256Sjkoshystatic void
852145256Sjkoshypmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
853145256Sjkoshy{
854145256Sjkoshy	int ri;
855147191Sjkoshy	struct proc *p;
856145256Sjkoshy	struct pmc_target *ptgt;
857145256Sjkoshy
858145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
859145256Sjkoshy
860145256Sjkoshy	KASSERT(pm != NULL && pp != NULL,
861145256Sjkoshy	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
862145256Sjkoshy
863198343Sfabient	KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc,
864145256Sjkoshy	    ("[pmc,%d] Illegal ref count %d on process record %p",
865145256Sjkoshy		__LINE__, pp->pp_refcnt, (void *) pp));
866145256Sjkoshy
867145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
868145256Sjkoshy
869282658Sjhb	PMCDBG3(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
870145256Sjkoshy	    pm, ri, pp);
871145256Sjkoshy
872145256Sjkoshy	KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
873145256Sjkoshy	    ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
874145256Sjkoshy		ri, pm, pp->pp_pmcs[ri].pp_pmc));
875145256Sjkoshy
876145256Sjkoshy	pp->pp_pmcs[ri].pp_pmc = NULL;
877145256Sjkoshy	pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
878145256Sjkoshy
879145774Sjkoshy	/* Remove owner-specific flags */
880145774Sjkoshy	if (pm->pm_owner->po_owner == pp->pp_proc) {
881145774Sjkoshy		pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
882145774Sjkoshy		pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
883145774Sjkoshy	}
884145615Sjkoshy
885145256Sjkoshy	pp->pp_refcnt--;
886145256Sjkoshy
887145256Sjkoshy	/* Remove the target process from the PMC structure */
888145256Sjkoshy	LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
889145256Sjkoshy		if (ptgt->pt_process == pp)
890145256Sjkoshy			break;
891145256Sjkoshy
892145256Sjkoshy	KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
893145256Sjkoshy		    "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
894145256Sjkoshy
895145256Sjkoshy	LIST_REMOVE(ptgt, pt_next);
896184205Sdes	free(ptgt, M_PMC);
897145256Sjkoshy
898147191Sjkoshy	/* if the PMC now lacks targets, send the owner a SIGIO */
899147191Sjkoshy	if (LIST_EMPTY(&pm->pm_targets)) {
900147191Sjkoshy		p = pm->pm_owner->po_owner;
901147191Sjkoshy		PROC_LOCK(p);
902225617Skmacy		kern_psignal(p, SIGIO);
903147191Sjkoshy		PROC_UNLOCK(p);
904145256Sjkoshy
905282658Sjhb		PMCDBG2(PRC,SIG,2, "signalling proc=%p signal=%d", p,
906147191Sjkoshy		    SIGIO);
907145256Sjkoshy	}
908145256Sjkoshy}
909145256Sjkoshy
910145256Sjkoshy/*
911145256Sjkoshy * Check if PMC 'pm' may be attached to target process 't'.
912145256Sjkoshy */
913145256Sjkoshy
914145256Sjkoshystatic int
915145256Sjkoshypmc_can_attach(struct pmc *pm, struct proc *t)
916145256Sjkoshy{
917145256Sjkoshy	struct proc *o;		/* pmc owner */
918145256Sjkoshy	struct ucred *oc, *tc;	/* owner, target credentials */
919145256Sjkoshy	int decline_attach, i;
920145256Sjkoshy
921145256Sjkoshy	/*
922145256Sjkoshy	 * A PMC's owner can always attach that PMC to itself.
923145256Sjkoshy	 */
924145256Sjkoshy
925145256Sjkoshy	if ((o = pm->pm_owner->po_owner) == t)
926145256Sjkoshy		return 0;
927145256Sjkoshy
928145256Sjkoshy	PROC_LOCK(o);
929145256Sjkoshy	oc = o->p_ucred;
930145256Sjkoshy	crhold(oc);
931145256Sjkoshy	PROC_UNLOCK(o);
932145256Sjkoshy
933145256Sjkoshy	PROC_LOCK(t);
934145256Sjkoshy	tc = t->p_ucred;
935145256Sjkoshy	crhold(tc);
936145256Sjkoshy	PROC_UNLOCK(t);
937145256Sjkoshy
938145256Sjkoshy	/*
939145256Sjkoshy	 * The effective uid of the PMC owner should match at least one
940145256Sjkoshy	 * of the {effective,real,saved} uids of the target process.
941145256Sjkoshy	 */
942145256Sjkoshy
943145256Sjkoshy	decline_attach = oc->cr_uid != tc->cr_uid &&
944145256Sjkoshy	    oc->cr_uid != tc->cr_svuid &&
945145256Sjkoshy	    oc->cr_uid != tc->cr_ruid;
946145256Sjkoshy
947145256Sjkoshy	/*
948145256Sjkoshy	 * Every one of the target's group ids, must be in the owner's
949145256Sjkoshy	 * group list.
950145256Sjkoshy	 */
951145256Sjkoshy	for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
952145256Sjkoshy		decline_attach = !groupmember(tc->cr_groups[i], oc);
953145256Sjkoshy
954145256Sjkoshy	/* check the read and saved gids too */
955145256Sjkoshy	if (decline_attach == 0)
956145256Sjkoshy		decline_attach = !groupmember(tc->cr_rgid, oc) ||
957145256Sjkoshy		    !groupmember(tc->cr_svgid, oc);
958145256Sjkoshy
959145256Sjkoshy	crfree(tc);
960145256Sjkoshy	crfree(oc);
961145256Sjkoshy
962145256Sjkoshy	return !decline_attach;
963145256Sjkoshy}
964145256Sjkoshy
965145256Sjkoshy/*
966145256Sjkoshy * Attach a process to a PMC.
967145256Sjkoshy */
968145256Sjkoshy
969145256Sjkoshystatic int
970145256Sjkoshypmc_attach_one_process(struct proc *p, struct pmc *pm)
971145256Sjkoshy{
972145256Sjkoshy	int ri;
973147191Sjkoshy	char *fullpath, *freepath;
974145256Sjkoshy	struct pmc_process	*pp;
975145256Sjkoshy
976145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
977145256Sjkoshy
978282658Sjhb	PMCDBG5(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
979145774Sjkoshy	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
980145256Sjkoshy
981145256Sjkoshy	/*
982145256Sjkoshy	 * Locate the process descriptor corresponding to process 'p',
983145256Sjkoshy	 * allocating space as needed.
984145256Sjkoshy	 *
985145256Sjkoshy	 * Verify that rowindex 'pm_rowindex' is free in the process
986145256Sjkoshy	 * descriptor.
987145256Sjkoshy	 *
988145256Sjkoshy	 * If not, allocate space for a descriptor and link the
989145256Sjkoshy	 * process descriptor and PMC.
990145256Sjkoshy	 */
991145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
992145256Sjkoshy
993145256Sjkoshy	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
994145256Sjkoshy		return ENOMEM;
995145256Sjkoshy
996145256Sjkoshy	if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
997145256Sjkoshy		return EEXIST;
998145256Sjkoshy
999145256Sjkoshy	if (pp->pp_pmcs[ri].pp_pmc != NULL)
1000145256Sjkoshy		return EBUSY;
1001145256Sjkoshy
1002145256Sjkoshy	pmc_link_target_process(pm, pp);
1003145256Sjkoshy
1004147191Sjkoshy	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
1005147191Sjkoshy	    (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
1006147191Sjkoshy		pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
1007147191Sjkoshy
1008147191Sjkoshy	pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
1009147191Sjkoshy
1010147191Sjkoshy	/* issue an attach event to a configured log file */
1011147191Sjkoshy	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
1012295435Skib		if (p->p_flag & P_KPROC) {
1013180794Sjeff			fullpath = kernelname;
1014180794Sjeff			freepath = NULL;
1015295352Skib		} else {
1016295352Skib			pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1017180794Sjeff			pmclog_process_pmcattach(pm, p->p_pid, fullpath);
1018295352Skib		}
1019295352Skib		free(freepath, M_TEMP);
1020174395Sjkoshy		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1021174395Sjkoshy			pmc_log_process_mappings(pm->pm_owner, p);
1022147191Sjkoshy	}
1023145256Sjkoshy	/* mark process as using HWPMCs */
1024145256Sjkoshy	PROC_LOCK(p);
1025145256Sjkoshy	p->p_flag |= P_HWPMC;
1026145256Sjkoshy	PROC_UNLOCK(p);
1027145256Sjkoshy
1028145256Sjkoshy	return 0;
1029145256Sjkoshy}
1030145256Sjkoshy
1031145256Sjkoshy/*
1032145256Sjkoshy * Attach a process and optionally its children
1033145256Sjkoshy */
1034145256Sjkoshy
1035145256Sjkoshystatic int
1036145256Sjkoshypmc_attach_process(struct proc *p, struct pmc *pm)
1037145256Sjkoshy{
1038145256Sjkoshy	int error;
1039145256Sjkoshy	struct proc *top;
1040145256Sjkoshy
1041145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1042145256Sjkoshy
1043282658Sjhb	PMCDBG5(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1044145774Sjkoshy	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1045145256Sjkoshy
1046145774Sjkoshy
1047145774Sjkoshy	/*
1048145774Sjkoshy	 * If this PMC successfully allowed a GETMSR operation
1049145774Sjkoshy	 * in the past, disallow further ATTACHes.
1050145774Sjkoshy	 */
1051145774Sjkoshy
1052145774Sjkoshy	if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1053145774Sjkoshy		return EPERM;
1054145774Sjkoshy
1055145256Sjkoshy	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1056145256Sjkoshy		return pmc_attach_one_process(p, pm);
1057145256Sjkoshy
1058145256Sjkoshy	/*
1059145256Sjkoshy	 * Traverse all child processes, attaching them to
1060145256Sjkoshy	 * this PMC.
1061145256Sjkoshy	 */
1062145256Sjkoshy
1063145256Sjkoshy	sx_slock(&proctree_lock);
1064145256Sjkoshy
1065145256Sjkoshy	top = p;
1066145256Sjkoshy
1067145256Sjkoshy	for (;;) {
1068145256Sjkoshy		if ((error = pmc_attach_one_process(p, pm)) != 0)
1069145256Sjkoshy			break;
1070145256Sjkoshy		if (!LIST_EMPTY(&p->p_children))
1071145256Sjkoshy			p = LIST_FIRST(&p->p_children);
1072145256Sjkoshy		else for (;;) {
1073145256Sjkoshy			if (p == top)
1074145256Sjkoshy				goto done;
1075145256Sjkoshy			if (LIST_NEXT(p, p_sibling)) {
1076145256Sjkoshy				p = LIST_NEXT(p, p_sibling);
1077145256Sjkoshy				break;
1078145256Sjkoshy			}
1079145256Sjkoshy			p = p->p_pptr;
1080145256Sjkoshy		}
1081145256Sjkoshy	}
1082145256Sjkoshy
1083145256Sjkoshy	if (error)
1084145256Sjkoshy		(void) pmc_detach_process(top, pm);
1085145256Sjkoshy
1086145256Sjkoshy done:
1087145256Sjkoshy	sx_sunlock(&proctree_lock);
1088145256Sjkoshy	return error;
1089145256Sjkoshy}
1090145256Sjkoshy
1091145256Sjkoshy/*
1092145256Sjkoshy * Detach a process from a PMC.  If there are no other PMCs tracking
1093145256Sjkoshy * this process, remove the process structure from its hash table.  If
1094145256Sjkoshy * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1095145256Sjkoshy */
1096145256Sjkoshy
1097145256Sjkoshystatic int
1098145256Sjkoshypmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1099145256Sjkoshy{
1100145256Sjkoshy	int ri;
1101145256Sjkoshy	struct pmc_process *pp;
1102145256Sjkoshy
1103145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1104145256Sjkoshy
1105145256Sjkoshy	KASSERT(pm != NULL,
1106145256Sjkoshy	    ("[pmc,%d] null pm pointer", __LINE__));
1107145256Sjkoshy
1108145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
1109145774Sjkoshy
1110282658Sjhb	PMCDBG6(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1111145774Sjkoshy	    pm, ri, p, p->p_pid, p->p_comm, flags);
1112145256Sjkoshy
1113145256Sjkoshy	if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1114145256Sjkoshy		return ESRCH;
1115145256Sjkoshy
1116145256Sjkoshy	if (pp->pp_pmcs[ri].pp_pmc != pm)
1117145256Sjkoshy		return EINVAL;
1118145256Sjkoshy
1119145256Sjkoshy	pmc_unlink_target_process(pm, pp);
1120145256Sjkoshy
1121147191Sjkoshy	/* Issue a detach entry if a log file is configured */
1122147191Sjkoshy	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1123147191Sjkoshy		pmclog_process_pmcdetach(pm, p->p_pid);
1124147191Sjkoshy
1125145256Sjkoshy	/*
1126298931Spfg	 * If there are no PMCs targeting this process, we remove its
1127145256Sjkoshy	 * descriptor from the target hash table and unset the P_HWPMC
1128145256Sjkoshy	 * flag in the struct proc.
1129145256Sjkoshy	 */
1130198343Sfabient	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1131145256Sjkoshy	    ("[pmc,%d] Illegal refcnt %d for process struct %p",
1132145256Sjkoshy		__LINE__, pp->pp_refcnt, pp));
1133145256Sjkoshy
1134145256Sjkoshy	if (pp->pp_refcnt != 0)	/* still a target of some PMC */
1135145256Sjkoshy		return 0;
1136145256Sjkoshy
1137145256Sjkoshy	pmc_remove_process_descriptor(pp);
1138145256Sjkoshy
1139145256Sjkoshy	if (flags & PMC_FLAG_REMOVE)
1140184205Sdes		free(pp, M_PMC);
1141145256Sjkoshy
1142145256Sjkoshy	PROC_LOCK(p);
1143145256Sjkoshy	p->p_flag &= ~P_HWPMC;
1144145256Sjkoshy	PROC_UNLOCK(p);
1145145256Sjkoshy
1146145256Sjkoshy	return 0;
1147145256Sjkoshy}
1148145256Sjkoshy
1149145256Sjkoshy/*
1150145256Sjkoshy * Detach a process and optionally its descendants from a PMC.
1151145256Sjkoshy */
1152145256Sjkoshy
1153145256Sjkoshystatic int
1154145256Sjkoshypmc_detach_process(struct proc *p, struct pmc *pm)
1155145256Sjkoshy{
1156145256Sjkoshy	struct proc *top;
1157145256Sjkoshy
1158145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1159145256Sjkoshy
1160282658Sjhb	PMCDBG5(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1161145774Sjkoshy	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1162145256Sjkoshy
1163145256Sjkoshy	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1164145256Sjkoshy		return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1165145256Sjkoshy
1166145256Sjkoshy	/*
1167145256Sjkoshy	 * Traverse all children, detaching them from this PMC.  We
1168145256Sjkoshy	 * ignore errors since we could be detaching a PMC from a
1169145256Sjkoshy	 * partially attached proc tree.
1170145256Sjkoshy	 */
1171145256Sjkoshy
1172145256Sjkoshy	sx_slock(&proctree_lock);
1173145256Sjkoshy
1174145256Sjkoshy	top = p;
1175145256Sjkoshy
1176145256Sjkoshy	for (;;) {
1177145256Sjkoshy		(void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1178145256Sjkoshy
1179145256Sjkoshy		if (!LIST_EMPTY(&p->p_children))
1180145256Sjkoshy			p = LIST_FIRST(&p->p_children);
1181145256Sjkoshy		else for (;;) {
1182145256Sjkoshy			if (p == top)
1183145256Sjkoshy				goto done;
1184145256Sjkoshy			if (LIST_NEXT(p, p_sibling)) {
1185145256Sjkoshy				p = LIST_NEXT(p, p_sibling);
1186145256Sjkoshy				break;
1187145256Sjkoshy			}
1188145256Sjkoshy			p = p->p_pptr;
1189145256Sjkoshy		}
1190145256Sjkoshy	}
1191145256Sjkoshy
1192145256Sjkoshy done:
1193145256Sjkoshy	sx_sunlock(&proctree_lock);
1194147191Sjkoshy
1195147191Sjkoshy	if (LIST_EMPTY(&pm->pm_targets))
1196147191Sjkoshy		pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1197147191Sjkoshy
1198145256Sjkoshy	return 0;
1199145256Sjkoshy}
1200145256Sjkoshy
1201147191Sjkoshy
1202145256Sjkoshy/*
1203147191Sjkoshy * Thread context switch IN
1204145256Sjkoshy */
1205145256Sjkoshy
1206147191Sjkoshystatic void
1207147191Sjkoshypmc_process_csw_in(struct thread *td)
1208147191Sjkoshy{
1209147191Sjkoshy	int cpu;
1210184802Sjkoshy	unsigned int adjri, ri;
1211147191Sjkoshy	struct pmc *pm;
1212147191Sjkoshy	struct proc *p;
1213147191Sjkoshy	struct pmc_cpu *pc;
1214147191Sjkoshy	struct pmc_hw *phw;
1215184802Sjkoshy	pmc_value_t newvalue;
1216147191Sjkoshy	struct pmc_process *pp;
1217184802Sjkoshy	struct pmc_classdep *pcd;
1218145256Sjkoshy
1219147191Sjkoshy	p = td->td_proc;
1220145256Sjkoshy
1221147191Sjkoshy	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1222147191Sjkoshy		return;
1223145256Sjkoshy
1224147191Sjkoshy	KASSERT(pp->pp_proc == td->td_proc,
1225147191Sjkoshy	    ("[pmc,%d] not my thread state", __LINE__));
1226145256Sjkoshy
1227147191Sjkoshy	critical_enter(); /* no preemption from this point */
1228145256Sjkoshy
1229147191Sjkoshy	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1230145256Sjkoshy
1231282658Sjhb	PMCDBG5(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1232147191Sjkoshy	    p->p_pid, p->p_comm, pp);
1233145256Sjkoshy
1234183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1235298931Spfg	    ("[pmc,%d] weird CPU id %d", __LINE__, cpu));
1236145256Sjkoshy
1237147191Sjkoshy	pc = pmc_pcpu[cpu];
1238145256Sjkoshy
1239147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++) {
1240145256Sjkoshy
1241147191Sjkoshy		if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1242147191Sjkoshy			continue;
1243147191Sjkoshy
1244147191Sjkoshy		KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1245147191Sjkoshy		    ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1246147191Sjkoshy			__LINE__, PMC_TO_MODE(pm)));
1247147191Sjkoshy
1248147191Sjkoshy		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1249147191Sjkoshy		    ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1250147191Sjkoshy			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1251147191Sjkoshy
1252145256Sjkoshy		/*
1253147191Sjkoshy		 * Only PMCs that are marked as 'RUNNING' need
1254147191Sjkoshy		 * be placed on hardware.
1255145256Sjkoshy		 */
1256145256Sjkoshy
1257147191Sjkoshy		if (pm->pm_state != PMC_STATE_RUNNING)
1258147191Sjkoshy			continue;
1259145256Sjkoshy
1260147191Sjkoshy		/* increment PMC runcount */
1261208861Sfabient		atomic_add_rel_int(&pm->pm_runcount, 1);
1262145256Sjkoshy
1263147191Sjkoshy		/* configure the HWPMC we are going to use. */
1264184802Sjkoshy		pcd = pmc_ri_to_classdep(md, ri, &adjri);
1265184802Sjkoshy		pcd->pcd_config_pmc(cpu, adjri, pm);
1266145256Sjkoshy
1267147191Sjkoshy		phw = pc->pc_hwpmcs[ri];
1268145256Sjkoshy
1269147191Sjkoshy		KASSERT(phw != NULL,
1270147191Sjkoshy		    ("[pmc,%d] null hw pointer", __LINE__));
1271145256Sjkoshy
1272147191Sjkoshy		KASSERT(phw->phw_pmc == pm,
1273147191Sjkoshy		    ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1274147191Sjkoshy			phw->phw_pmc, pm));
1275145256Sjkoshy
1276147191Sjkoshy		/*
1277147191Sjkoshy		 * Write out saved value and start the PMC.
1278147191Sjkoshy		 *
1279147191Sjkoshy		 * Sampling PMCs use a per-process value, while
1280147191Sjkoshy		 * counting mode PMCs use a per-pmc value that is
1281147191Sjkoshy		 * inherited across descendants.
1282147191Sjkoshy		 */
1283147191Sjkoshy		if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1284147191Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
1285290930Sjtl
1286290930Sjtl			/*
1287290930Sjtl			 * Use the saved value calculated after the most recent
1288290930Sjtl			 * thread switch out to start this counter.  Reset
1289290930Sjtl			 * the saved count in case another thread from this
1290290930Sjtl			 * process switches in before any threads switch out.
1291290930Sjtl			 */
1292147191Sjkoshy			newvalue = PMC_PCPU_SAVED(cpu,ri) =
1293147191Sjkoshy			    pp->pp_pmcs[ri].pp_pmcval;
1294290930Sjtl			pp->pp_pmcs[ri].pp_pmcval = pm->pm_sc.pm_reloadcount;
1295147191Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1296147191Sjkoshy		} else {
1297147191Sjkoshy			KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1298147191Sjkoshy			    ("[pmc,%d] illegal mode=%d", __LINE__,
1299147191Sjkoshy			    PMC_TO_MODE(pm)));
1300147191Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
1301147191Sjkoshy			newvalue = PMC_PCPU_SAVED(cpu, ri) =
1302147191Sjkoshy			    pm->pm_gv.pm_savedvalue;
1303147191Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1304147191Sjkoshy		}
1305145256Sjkoshy
1306282658Sjhb		PMCDBG3(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1307145256Sjkoshy
1308184802Sjkoshy		pcd->pcd_write_pmc(cpu, adjri, newvalue);
1309290811Sjtl
1310290811Sjtl		/* If a sampling mode PMC, reset stalled state. */
1311290811Sjtl		if (PMC_TO_MODE(pm) == PMC_MODE_TS)
1312290811Sjtl			CPU_CLR_ATOMIC(cpu, &pm->pm_stalled);
1313290811Sjtl
1314290811Sjtl		/* Indicate that we desire this to run. */
1315290811Sjtl		CPU_SET_ATOMIC(cpu, &pm->pm_cpustate);
1316290811Sjtl
1317290811Sjtl		/* Start the PMC. */
1318184802Sjkoshy		pcd->pcd_start_pmc(cpu, adjri);
1319147191Sjkoshy	}
1320145256Sjkoshy
1321147191Sjkoshy	/*
1322147191Sjkoshy	 * perform any other architecture/cpu dependent thread
1323147191Sjkoshy	 * switch-in actions.
1324147191Sjkoshy	 */
1325145256Sjkoshy
1326147191Sjkoshy	(void) (*md->pmd_switch_in)(pc, pp);
1327145256Sjkoshy
1328147191Sjkoshy	critical_exit();
1329145256Sjkoshy
1330147191Sjkoshy}
1331145256Sjkoshy
1332147191Sjkoshy/*
1333147191Sjkoshy * Thread context switch OUT.
1334147191Sjkoshy */
1335145256Sjkoshy
1336147191Sjkoshystatic void
1337147191Sjkoshypmc_process_csw_out(struct thread *td)
1338147191Sjkoshy{
1339147191Sjkoshy	int cpu;
1340184802Sjkoshy	int64_t tmp;
1341147191Sjkoshy	struct pmc *pm;
1342147191Sjkoshy	struct proc *p;
1343184802Sjkoshy	enum pmc_mode mode;
1344147191Sjkoshy	struct pmc_cpu *pc;
1345184802Sjkoshy	pmc_value_t newvalue;
1346184802Sjkoshy	unsigned int adjri, ri;
1347147191Sjkoshy	struct pmc_process *pp;
1348184802Sjkoshy	struct pmc_classdep *pcd;
1349145256Sjkoshy
1350184802Sjkoshy
1351147191Sjkoshy	/*
1352147191Sjkoshy	 * Locate our process descriptor; this may be NULL if
1353147191Sjkoshy	 * this process is exiting and we have already removed
1354147191Sjkoshy	 * the process from the target process table.
1355147191Sjkoshy	 *
1356147191Sjkoshy	 * Note that due to kernel preemption, multiple
1357147191Sjkoshy	 * context switches may happen while the process is
1358147191Sjkoshy	 * exiting.
1359147191Sjkoshy	 *
1360147191Sjkoshy	 * Note also that if the target process cannot be
1361147191Sjkoshy	 * found we still need to deconfigure any PMCs that
1362147191Sjkoshy	 * are currently running on hardware.
1363147191Sjkoshy	 */
1364145256Sjkoshy
1365147191Sjkoshy	p = td->td_proc;
1366147191Sjkoshy	pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1367145256Sjkoshy
1368147191Sjkoshy	/*
1369147191Sjkoshy	 * save PMCs
1370147191Sjkoshy	 */
1371145256Sjkoshy
1372147191Sjkoshy	critical_enter();
1373145774Sjkoshy
1374147191Sjkoshy	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1375145256Sjkoshy
1376282658Sjhb	PMCDBG5(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1377147191Sjkoshy	    p->p_pid, p->p_comm, pp);
1378145615Sjkoshy
1379183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1380298931Spfg	    ("[pmc,%d weird CPU id %d", __LINE__, cpu));
1381145615Sjkoshy
1382147191Sjkoshy	pc = pmc_pcpu[cpu];
1383145615Sjkoshy
1384147191Sjkoshy	/*
1385147191Sjkoshy	 * When a PMC gets unlinked from a target PMC, it will
1386147191Sjkoshy	 * be removed from the target's pp_pmc[] array.
1387147191Sjkoshy	 *
1388147191Sjkoshy	 * However, on a MP system, the target could have been
1389147191Sjkoshy	 * executing on another CPU at the time of the unlink.
1390147191Sjkoshy	 * So, at context switch OUT time, we need to look at
1391147191Sjkoshy	 * the hardware to determine if a PMC is scheduled on
1392147191Sjkoshy	 * it.
1393147191Sjkoshy	 */
1394145256Sjkoshy
1395147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++) {
1396145256Sjkoshy
1397184802Sjkoshy		pcd = pmc_ri_to_classdep(md, ri, &adjri);
1398184802Sjkoshy		pm  = NULL;
1399184802Sjkoshy		(void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
1400145256Sjkoshy
1401147191Sjkoshy		if (pm == NULL)	/* nothing at this row index */
1402147191Sjkoshy			continue;
1403145256Sjkoshy
1404147191Sjkoshy		mode = PMC_TO_MODE(pm);
1405147191Sjkoshy		if (!PMC_IS_VIRTUAL_MODE(mode))
1406147191Sjkoshy			continue; /* not a process virtual PMC */
1407145774Sjkoshy
1408147191Sjkoshy		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1409147191Sjkoshy		    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1410147191Sjkoshy			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1411145256Sjkoshy
1412290811Sjtl		/*
1413290811Sjtl		 * Change desired state, and then stop if not stalled.
1414290811Sjtl		 * This two-step dance should avoid race conditions where
1415290811Sjtl		 * an interrupt re-enables the PMC after this code has
1416290811Sjtl		 * already checked the pm_stalled flag.
1417290811Sjtl		 */
1418290811Sjtl		CPU_CLR_ATOMIC(cpu, &pm->pm_cpustate);
1419290811Sjtl		if (!CPU_ISSET(cpu, &pm->pm_stalled))
1420184802Sjkoshy			pcd->pcd_stop_pmc(cpu, adjri);
1421147191Sjkoshy
1422147191Sjkoshy		/* reduce this PMC's runcount */
1423208861Sfabient		atomic_subtract_rel_int(&pm->pm_runcount, 1);
1424147191Sjkoshy
1425145256Sjkoshy		/*
1426147191Sjkoshy		 * If this PMC is associated with this process,
1427147191Sjkoshy		 * save the reading.
1428145256Sjkoshy		 */
1429145256Sjkoshy
1430147191Sjkoshy		if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1431147191Sjkoshy
1432147191Sjkoshy			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1433147191Sjkoshy			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1434147191Sjkoshy				pm, ri, pp->pp_pmcs[ri].pp_pmc));
1435147191Sjkoshy
1436147191Sjkoshy			KASSERT(pp->pp_refcnt > 0,
1437147191Sjkoshy			    ("[pmc,%d] pp refcnt = %d", __LINE__,
1438147191Sjkoshy				pp->pp_refcnt));
1439147191Sjkoshy
1440184802Sjkoshy			pcd->pcd_read_pmc(cpu, adjri, &newvalue);
1441147191Sjkoshy
1442147191Sjkoshy			if (mode == PMC_MODE_TS) {
1443290930Sjtl				PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd (samp)",
1444290930Sjtl				    cpu, ri, PMC_PCPU_SAVED(cpu,ri) - newvalue);
1445147191Sjkoshy
1446147191Sjkoshy				/*
1447147191Sjkoshy				 * For sampling process-virtual PMCs,
1448290930Sjtl				 * newvalue is the number of events to be seen
1449290930Sjtl				 * until the next sampling interrupt.
1450290930Sjtl				 * We can just add the events left from this
1451290930Sjtl				 * invocation to the counter, then adjust
1452290930Sjtl				 * in case we overflow our range.
1453290930Sjtl				 *
1454290930Sjtl				 * (Recall that we reload the counter every
1455290930Sjtl				 * time we use it.)
1456147191Sjkoshy				 */
1457147191Sjkoshy				mtx_pool_lock_spin(pmc_mtxpool, pm);
1458290930Sjtl
1459290930Sjtl				pp->pp_pmcs[ri].pp_pmcval += newvalue;
1460290930Sjtl				if (pp->pp_pmcs[ri].pp_pmcval >
1461290930Sjtl				    pm->pm_sc.pm_reloadcount)
1462290930Sjtl					pp->pp_pmcs[ri].pp_pmcval -=
1463147191Sjkoshy					    pm->pm_sc.pm_reloadcount;
1464290930Sjtl				KASSERT(pp->pp_pmcs[ri].pp_pmcval > 0 &&
1465290930Sjtl				    pp->pp_pmcs[ri].pp_pmcval <=
1466290930Sjtl				    pm->pm_sc.pm_reloadcount,
1467290930Sjtl				    ("[pmc,%d] pp_pmcval outside of expected "
1468290930Sjtl				    "range cpu=%d ri=%d pp_pmcval=%jx "
1469290930Sjtl				    "pm_reloadcount=%jx", __LINE__, cpu, ri,
1470290930Sjtl				    pp->pp_pmcs[ri].pp_pmcval,
1471290930Sjtl				    pm->pm_sc.pm_reloadcount));
1472147191Sjkoshy				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1473147191Sjkoshy
1474147191Sjkoshy			} else {
1475290930Sjtl				tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1476147191Sjkoshy
1477290930Sjtl				PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd (count)",
1478290930Sjtl				    cpu, ri, tmp);
1479290930Sjtl
1480147191Sjkoshy				/*
1481147191Sjkoshy				 * For counting process-virtual PMCs,
1482147191Sjkoshy				 * we expect the count to be
1483147191Sjkoshy				 * increasing monotonically, modulo a 64
1484147191Sjkoshy				 * bit wraparound.
1485147191Sjkoshy				 */
1486295558Skib				KASSERT(tmp >= 0,
1487147191Sjkoshy				    ("[pmc,%d] negative increment cpu=%d "
1488147191Sjkoshy				     "ri=%d newvalue=%jx saved=%jx "
1489147191Sjkoshy				     "incr=%jx", __LINE__, cpu, ri,
1490147191Sjkoshy				     newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1491147191Sjkoshy
1492147191Sjkoshy				mtx_pool_lock_spin(pmc_mtxpool, pm);
1493147191Sjkoshy				pm->pm_gv.pm_savedvalue += tmp;
1494147191Sjkoshy				pp->pp_pmcs[ri].pp_pmcval += tmp;
1495147191Sjkoshy				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1496147191Sjkoshy
1497147191Sjkoshy				if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1498147191Sjkoshy					pmclog_process_proccsw(pm, pp, tmp);
1499147191Sjkoshy			}
1500145256Sjkoshy		}
1501145256Sjkoshy
1502147191Sjkoshy		/* mark hardware as free */
1503184802Sjkoshy		pcd->pcd_config_pmc(cpu, adjri, NULL);
1504145256Sjkoshy	}
1505145256Sjkoshy
1506145256Sjkoshy	/*
1507147191Sjkoshy	 * perform any other architecture/cpu dependent thread
1508147191Sjkoshy	 * switch out functions.
1509147191Sjkoshy	 */
1510147191Sjkoshy
1511147191Sjkoshy	(void) (*md->pmd_switch_out)(pc, pp);
1512147191Sjkoshy
1513147191Sjkoshy	critical_exit();
1514147191Sjkoshy}
1515147191Sjkoshy
1516147191Sjkoshy/*
1517157144Sjkoshy * A mapping change for a process.
1518157144Sjkoshy */
1519157144Sjkoshy
1520157144Sjkoshystatic void
1521157144Sjkoshypmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1522157144Sjkoshy{
1523157144Sjkoshy	int ri;
1524157144Sjkoshy	pid_t pid;
1525157144Sjkoshy	char *fullpath, *freepath;
1526157144Sjkoshy	const struct pmc *pm;
1527157144Sjkoshy	struct pmc_owner *po;
1528157144Sjkoshy	const struct pmc_process *pp;
1529157144Sjkoshy
1530157144Sjkoshy	freepath = fullpath = NULL;
1531157144Sjkoshy	pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1532157144Sjkoshy
1533157144Sjkoshy	pid = td->td_proc->p_pid;
1534157144Sjkoshy
1535157144Sjkoshy	/* Inform owners of all system-wide sampling PMCs. */
1536157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1537157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1538157144Sjkoshy		pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1539157144Sjkoshy
1540157144Sjkoshy	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1541157144Sjkoshy		goto done;
1542157144Sjkoshy
1543157144Sjkoshy	/*
1544157144Sjkoshy	 * Inform sampling PMC owners tracking this process.
1545157144Sjkoshy	 */
1546157144Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
1547157144Sjkoshy		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1548157144Sjkoshy		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1549157144Sjkoshy			pmclog_process_map_in(pm->pm_owner,
1550157144Sjkoshy			    pid, pkm->pm_address, fullpath);
1551157144Sjkoshy
1552157144Sjkoshy  done:
1553157144Sjkoshy	if (freepath)
1554184205Sdes		free(freepath, M_TEMP);
1555157144Sjkoshy}
1556157144Sjkoshy
1557157144Sjkoshy
1558157144Sjkoshy/*
1559157144Sjkoshy * Log an munmap request.
1560157144Sjkoshy */
1561157144Sjkoshy
1562157144Sjkoshystatic void
1563157144Sjkoshypmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1564157144Sjkoshy{
1565157144Sjkoshy	int ri;
1566157144Sjkoshy	pid_t pid;
1567157144Sjkoshy	struct pmc_owner *po;
1568157144Sjkoshy	const struct pmc *pm;
1569157144Sjkoshy	const struct pmc_process *pp;
1570157144Sjkoshy
1571157144Sjkoshy	pid = td->td_proc->p_pid;
1572157144Sjkoshy
1573157144Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1574157144Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1575157144Sjkoshy		pmclog_process_map_out(po, pid, pkm->pm_address,
1576157144Sjkoshy		    pkm->pm_address + pkm->pm_size);
1577157144Sjkoshy
1578157144Sjkoshy	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1579157144Sjkoshy		return;
1580157144Sjkoshy
1581157144Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
1582157144Sjkoshy		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1583157144Sjkoshy		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1584157651Sjkoshy			pmclog_process_map_out(pm->pm_owner, pid,
1585157651Sjkoshy			    pkm->pm_address, pkm->pm_address + pkm->pm_size);
1586157144Sjkoshy}
1587157144Sjkoshy
1588157144Sjkoshy/*
1589174395Sjkoshy * Log mapping information about the kernel.
1590174395Sjkoshy */
1591174395Sjkoshy
1592174395Sjkoshystatic void
1593174395Sjkoshypmc_log_kernel_mappings(struct pmc *pm)
1594174395Sjkoshy{
1595174395Sjkoshy	struct pmc_owner *po;
1596174395Sjkoshy	struct pmckern_map_in *km, *kmbase;
1597174395Sjkoshy
1598174395Sjkoshy	sx_assert(&pmc_sx, SX_LOCKED);
1599174395Sjkoshy	KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1600174395Sjkoshy	    ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1601174395Sjkoshy		__LINE__, (void *) pm));
1602174395Sjkoshy
1603174395Sjkoshy	po = pm->pm_owner;
1604174395Sjkoshy
1605174395Sjkoshy	if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1606174395Sjkoshy		return;
1607174395Sjkoshy
1608174395Sjkoshy	/*
1609174395Sjkoshy	 * Log the current set of kernel modules.
1610174395Sjkoshy	 */
1611174395Sjkoshy	kmbase = linker_hwpmc_list_objects();
1612174395Sjkoshy	for (km = kmbase; km->pm_file != NULL; km++) {
1613282658Sjhb		PMCDBG2(LOG,REG,1,"%s %p", (char *) km->pm_file,
1614174395Sjkoshy		    (void *) km->pm_address);
1615174395Sjkoshy		pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1616174395Sjkoshy		    km->pm_file);
1617174395Sjkoshy	}
1618184205Sdes	free(kmbase, M_LINKER);
1619174395Sjkoshy
1620174395Sjkoshy	po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1621174395Sjkoshy}
1622174395Sjkoshy
1623174395Sjkoshy/*
1624174395Sjkoshy * Log the mappings for a single process.
1625174395Sjkoshy */
1626174395Sjkoshy
1627174395Sjkoshystatic void
1628174395Sjkoshypmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1629174395Sjkoshy{
1630201021Sjkoshy	vm_map_t map;
1631201021Sjkoshy	struct vnode *vp;
1632201021Sjkoshy	struct vmspace *vm;
1633201021Sjkoshy	vm_map_entry_t entry;
1634201021Sjkoshy	vm_offset_t last_end;
1635201021Sjkoshy	u_int last_timestamp;
1636201021Sjkoshy	struct vnode *last_vp;
1637201021Sjkoshy	vm_offset_t start_addr;
1638201021Sjkoshy	vm_object_t obj, lobj, tobj;
1639201021Sjkoshy	char *fullpath, *freepath;
1640201021Sjkoshy
1641201021Sjkoshy	last_vp = NULL;
1642201021Sjkoshy	last_end = (vm_offset_t) 0;
1643201021Sjkoshy	fullpath = freepath = NULL;
1644201021Sjkoshy
1645201021Sjkoshy	if ((vm = vmspace_acquire_ref(p)) == NULL)
1646201021Sjkoshy		return;
1647201021Sjkoshy
1648201021Sjkoshy	map = &vm->vm_map;
1649201021Sjkoshy	vm_map_lock_read(map);
1650201021Sjkoshy
1651201021Sjkoshy	for (entry = map->header.next; entry != &map->header; entry = entry->next) {
1652201021Sjkoshy
1653201021Sjkoshy		if (entry == NULL) {
1654282658Sjhb			PMCDBG2(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly "
1655201021Sjkoshy			    "NULL! pid=%d vm_map=%p\n", p->p_pid, map);
1656201021Sjkoshy			break;
1657201021Sjkoshy		}
1658201021Sjkoshy
1659201021Sjkoshy		/*
1660201021Sjkoshy		 * We only care about executable map entries.
1661201021Sjkoshy		 */
1662201021Sjkoshy		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) ||
1663201021Sjkoshy		    !(entry->protection & VM_PROT_EXECUTE) ||
1664201021Sjkoshy		    (entry->object.vm_object == NULL)) {
1665201021Sjkoshy			continue;
1666201021Sjkoshy		}
1667201021Sjkoshy
1668201021Sjkoshy		obj = entry->object.vm_object;
1669251423Salc		VM_OBJECT_RLOCK(obj);
1670201021Sjkoshy
1671201021Sjkoshy		/*
1672201021Sjkoshy		 * Walk the backing_object list to find the base
1673201021Sjkoshy		 * (non-shadowed) vm_object.
1674201021Sjkoshy		 */
1675201021Sjkoshy		for (lobj = tobj = obj; tobj != NULL; tobj = tobj->backing_object) {
1676201021Sjkoshy			if (tobj != obj)
1677251423Salc				VM_OBJECT_RLOCK(tobj);
1678201021Sjkoshy			if (lobj != obj)
1679251423Salc				VM_OBJECT_RUNLOCK(lobj);
1680201021Sjkoshy			lobj = tobj;
1681201021Sjkoshy		}
1682201021Sjkoshy
1683201021Sjkoshy		/*
1684201021Sjkoshy		 * At this point lobj is the base vm_object and it is locked.
1685201021Sjkoshy		 */
1686201021Sjkoshy		if (lobj == NULL) {
1687282658Sjhb			PMCDBG3(LOG,OPS,2, "hwpmc: lobj unexpectedly NULL! pid=%d "
1688201021Sjkoshy			    "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj);
1689251423Salc			VM_OBJECT_RUNLOCK(obj);
1690201021Sjkoshy			continue;
1691201021Sjkoshy		}
1692201021Sjkoshy
1693283924Svangyzen		vp = vm_object_vnode(lobj);
1694283924Svangyzen		if (vp == NULL) {
1695201021Sjkoshy			if (lobj != obj)
1696251423Salc				VM_OBJECT_RUNLOCK(lobj);
1697251423Salc			VM_OBJECT_RUNLOCK(obj);
1698201021Sjkoshy			continue;
1699201021Sjkoshy		}
1700201021Sjkoshy
1701201021Sjkoshy		/*
1702201021Sjkoshy		 * Skip contiguous regions that point to the same
1703201021Sjkoshy		 * vnode, so we don't emit redundant MAP-IN
1704201021Sjkoshy		 * directives.
1705201021Sjkoshy		 */
1706283924Svangyzen		if (entry->start == last_end && vp == last_vp) {
1707201021Sjkoshy			last_end = entry->end;
1708201021Sjkoshy			if (lobj != obj)
1709251423Salc				VM_OBJECT_RUNLOCK(lobj);
1710251423Salc			VM_OBJECT_RUNLOCK(obj);
1711201021Sjkoshy			continue;
1712201021Sjkoshy		}
1713201021Sjkoshy
1714201021Sjkoshy		/*
1715201021Sjkoshy		 * We don't want to keep the proc's vm_map or this
1716201021Sjkoshy		 * vm_object locked while we walk the pathname, since
1717201021Sjkoshy		 * vn_fullpath() can sleep.  However, if we drop the
1718201021Sjkoshy		 * lock, it's possible for concurrent activity to
1719201021Sjkoshy		 * modify the vm_map list.  To protect against this,
1720201021Sjkoshy		 * we save the vm_map timestamp before we release the
1721201021Sjkoshy		 * lock, and check it after we reacquire the lock
1722201021Sjkoshy		 * below.
1723201021Sjkoshy		 */
1724201021Sjkoshy		start_addr = entry->start;
1725201021Sjkoshy		last_end = entry->end;
1726201021Sjkoshy		last_timestamp = map->timestamp;
1727201021Sjkoshy		vm_map_unlock_read(map);
1728201021Sjkoshy
1729201021Sjkoshy		vref(vp);
1730201021Sjkoshy		if (lobj != obj)
1731251423Salc			VM_OBJECT_RUNLOCK(lobj);
1732201021Sjkoshy
1733251423Salc		VM_OBJECT_RUNLOCK(obj);
1734201021Sjkoshy
1735201021Sjkoshy		freepath = NULL;
1736201021Sjkoshy		pmc_getfilename(vp, &fullpath, &freepath);
1737201021Sjkoshy		last_vp = vp;
1738201151Sjkoshy
1739201021Sjkoshy		vrele(vp);
1740201151Sjkoshy
1741201021Sjkoshy		vp = NULL;
1742201021Sjkoshy		pmclog_process_map_in(po, p->p_pid, start_addr, fullpath);
1743201021Sjkoshy		if (freepath)
1744201021Sjkoshy			free(freepath, M_TEMP);
1745201021Sjkoshy
1746201021Sjkoshy		vm_map_lock_read(map);
1747201021Sjkoshy
1748201021Sjkoshy		/*
1749201021Sjkoshy		 * If our saved timestamp doesn't match, this means
1750201021Sjkoshy		 * that the vm_map was modified out from under us and
1751201021Sjkoshy		 * we can't trust our current "entry" pointer.  Do a
1752201021Sjkoshy		 * new lookup for this entry.  If there is no entry
1753201021Sjkoshy		 * for this address range, vm_map_lookup_entry() will
1754201021Sjkoshy		 * return the previous one, so we always want to go to
1755201021Sjkoshy		 * entry->next on the next loop iteration.
1756201021Sjkoshy		 *
1757201021Sjkoshy		 * There is an edge condition here that can occur if
1758201021Sjkoshy		 * there is no entry at or before this address.  In
1759201021Sjkoshy		 * this situation, vm_map_lookup_entry returns
1760201021Sjkoshy		 * &map->header, which would cause our loop to abort
1761201021Sjkoshy		 * without processing the rest of the map.  However,
1762201021Sjkoshy		 * in practice this will never happen for process
1763201021Sjkoshy		 * vm_map.  This is because the executable's text
1764201021Sjkoshy		 * segment is the first mapping in the proc's address
1765201021Sjkoshy		 * space, and this mapping is never removed until the
1766201021Sjkoshy		 * process exits, so there will always be a non-header
1767201021Sjkoshy		 * entry at or before the requested address for
1768201021Sjkoshy		 * vm_map_lookup_entry to return.
1769201021Sjkoshy		 */
1770201021Sjkoshy		if (map->timestamp != last_timestamp)
1771201021Sjkoshy			vm_map_lookup_entry(map, last_end - 1, &entry);
1772201021Sjkoshy	}
1773201021Sjkoshy
1774201021Sjkoshy	vm_map_unlock_read(map);
1775201021Sjkoshy	vmspace_free(vm);
1776201021Sjkoshy	return;
1777174395Sjkoshy}
1778174395Sjkoshy
1779174395Sjkoshy/*
1780174395Sjkoshy * Log mappings for all processes in the system.
1781174395Sjkoshy */
1782174395Sjkoshy
1783174395Sjkoshystatic void
1784174395Sjkoshypmc_log_all_process_mappings(struct pmc_owner *po)
1785174395Sjkoshy{
1786174395Sjkoshy	struct proc *p, *top;
1787174395Sjkoshy
1788174395Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
1789174395Sjkoshy
1790174395Sjkoshy	if ((p = pfind(1)) == NULL)
1791174395Sjkoshy		panic("[pmc,%d] Cannot find init", __LINE__);
1792174395Sjkoshy
1793174395Sjkoshy	PROC_UNLOCK(p);
1794174395Sjkoshy
1795174395Sjkoshy	sx_slock(&proctree_lock);
1796174395Sjkoshy
1797174395Sjkoshy	top = p;
1798174395Sjkoshy
1799174395Sjkoshy	for (;;) {
1800174395Sjkoshy		pmc_log_process_mappings(po, p);
1801174395Sjkoshy		if (!LIST_EMPTY(&p->p_children))
1802174395Sjkoshy			p = LIST_FIRST(&p->p_children);
1803174395Sjkoshy		else for (;;) {
1804174395Sjkoshy			if (p == top)
1805174395Sjkoshy				goto done;
1806174395Sjkoshy			if (LIST_NEXT(p, p_sibling)) {
1807174395Sjkoshy				p = LIST_NEXT(p, p_sibling);
1808174395Sjkoshy				break;
1809174395Sjkoshy			}
1810174395Sjkoshy			p = p->p_pptr;
1811174395Sjkoshy		}
1812174395Sjkoshy	}
1813174395Sjkoshy done:
1814174395Sjkoshy	sx_sunlock(&proctree_lock);
1815174395Sjkoshy}
1816174395Sjkoshy
1817174395Sjkoshy/*
1818147191Sjkoshy * The 'hook' invoked from the kernel proper
1819147191Sjkoshy */
1820147191Sjkoshy
1821147191Sjkoshy
1822282641Sjhb#ifdef	HWPMC_DEBUG
1823147191Sjkoshyconst char *pmc_hooknames[] = {
1824157144Sjkoshy	/* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1825147191Sjkoshy	"",
1826147191Sjkoshy	"EXEC",
1827147191Sjkoshy	"CSW-IN",
1828147191Sjkoshy	"CSW-OUT",
1829157144Sjkoshy	"SAMPLE",
1830254813Smarkj	"UNUSED1",
1831254813Smarkj	"UNUSED2",
1832157144Sjkoshy	"MMAP",
1833174395Sjkoshy	"MUNMAP",
1834233628Sfabient	"CALLCHAIN-NMI",
1835233628Sfabient	"CALLCHAIN-SOFT",
1836233628Sfabient	"SOFTSAMPLING"
1837147191Sjkoshy};
1838147191Sjkoshy#endif
1839147191Sjkoshy
1840147191Sjkoshystatic int
1841147191Sjkoshypmc_hook_handler(struct thread *td, int function, void *arg)
1842147191Sjkoshy{
1843147191Sjkoshy
1844282658Sjhb	PMCDBG4(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1845147191Sjkoshy	    pmc_hooknames[function], arg);
1846147191Sjkoshy
1847147191Sjkoshy	switch (function)
1848147191Sjkoshy	{
1849147191Sjkoshy
1850147191Sjkoshy	/*
1851145256Sjkoshy	 * Process exec()
1852145256Sjkoshy	 */
1853145256Sjkoshy
1854145256Sjkoshy	case PMC_FN_PROCESS_EXEC:
1855145256Sjkoshy	{
1856147191Sjkoshy		char *fullpath, *freepath;
1857145256Sjkoshy		unsigned int ri;
1858147191Sjkoshy		int is_using_hwpmcs;
1859145256Sjkoshy		struct pmc *pm;
1860145256Sjkoshy		struct proc *p;
1861145256Sjkoshy		struct pmc_owner *po;
1862145256Sjkoshy		struct pmc_process *pp;
1863147708Sjkoshy		struct pmckern_procexec *pk;
1864145256Sjkoshy
1865145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
1866145256Sjkoshy
1867147191Sjkoshy		p = td->td_proc;
1868147708Sjkoshy		pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1869147191Sjkoshy
1870147708Sjkoshy		pk = (struct pmckern_procexec *) arg;
1871147708Sjkoshy
1872147191Sjkoshy		/* Inform owners of SS mode PMCs of the exec event. */
1873147191Sjkoshy		LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1874147191Sjkoshy		    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1875147708Sjkoshy			    pmclog_process_procexec(po, PMC_ID_INVALID,
1876147708Sjkoshy				p->p_pid, pk->pm_entryaddr, fullpath);
1877147191Sjkoshy
1878147191Sjkoshy		PROC_LOCK(p);
1879147191Sjkoshy		is_using_hwpmcs = p->p_flag & P_HWPMC;
1880147191Sjkoshy		PROC_UNLOCK(p);
1881147191Sjkoshy
1882147191Sjkoshy		if (!is_using_hwpmcs) {
1883147191Sjkoshy			if (freepath)
1884184205Sdes				free(freepath, M_TEMP);
1885147191Sjkoshy			break;
1886147191Sjkoshy		}
1887147191Sjkoshy
1888145256Sjkoshy		/*
1889145256Sjkoshy		 * PMCs are not inherited across an exec():  remove any
1890145256Sjkoshy		 * PMCs that this process is the owner of.
1891145256Sjkoshy		 */
1892145256Sjkoshy
1893145256Sjkoshy		if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1894145256Sjkoshy			pmc_remove_owner(po);
1895147191Sjkoshy			pmc_destroy_owner_descriptor(po);
1896145256Sjkoshy		}
1897145256Sjkoshy
1898145256Sjkoshy		/*
1899154483Sjkoshy		 * If the process being exec'ed is not the target of any
1900154483Sjkoshy		 * PMC, we are done.
1901145256Sjkoshy		 */
1902154483Sjkoshy		if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1903154483Sjkoshy			if (freepath)
1904184205Sdes				free(freepath, M_TEMP);
1905145256Sjkoshy			break;
1906154483Sjkoshy		}
1907145256Sjkoshy
1908147191Sjkoshy		/*
1909147191Sjkoshy		 * Log the exec event to all monitoring owners.  Skip
1910298931Spfg		 * owners who have already received the event because
1911154483Sjkoshy		 * they had system sampling PMCs active.
1912147191Sjkoshy		 */
1913147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
1914147191Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1915147191Sjkoshy				po = pm->pm_owner;
1916147191Sjkoshy				if (po->po_sscount == 0 &&
1917147191Sjkoshy				    po->po_flags & PMC_PO_OWNS_LOGFILE)
1918147708Sjkoshy					pmclog_process_procexec(po, pm->pm_id,
1919147708Sjkoshy					    p->p_pid, pk->pm_entryaddr,
1920147191Sjkoshy					    fullpath);
1921147191Sjkoshy			}
1922147191Sjkoshy
1923147191Sjkoshy		if (freepath)
1924184205Sdes			free(freepath, M_TEMP);
1925147191Sjkoshy
1926145256Sjkoshy
1927282658Sjhb		PMCDBG4(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1928147708Sjkoshy		    p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1929145256Sjkoshy
1930147708Sjkoshy		if (pk->pm_credentialschanged == 0) /* no change */
1931145256Sjkoshy			break;
1932145256Sjkoshy
1933145256Sjkoshy		/*
1934145256Sjkoshy		 * If the newly exec()'ed process has a different credential
1935145256Sjkoshy		 * than before, allow it to be the target of a PMC only if
1936298931Spfg		 * the PMC's owner has sufficient privilege.
1937145256Sjkoshy		 */
1938145256Sjkoshy
1939145256Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
1940145256Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1941145256Sjkoshy				if (pmc_can_attach(pm, td->td_proc) != 0)
1942145256Sjkoshy					pmc_detach_one_process(td->td_proc,
1943145256Sjkoshy					    pm, PMC_FLAG_NONE);
1944145256Sjkoshy
1945198343Sfabient		KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1946145256Sjkoshy		    ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1947145256Sjkoshy			pp->pp_refcnt, pp));
1948145256Sjkoshy
1949145256Sjkoshy		/*
1950145256Sjkoshy		 * If this process is no longer the target of any
1951145256Sjkoshy		 * PMCs, we can remove the process entry and free
1952145256Sjkoshy		 * up space.
1953145256Sjkoshy		 */
1954145256Sjkoshy
1955145256Sjkoshy		if (pp->pp_refcnt == 0) {
1956145256Sjkoshy			pmc_remove_process_descriptor(pp);
1957184205Sdes			free(pp, M_PMC);
1958147191Sjkoshy			break;
1959145256Sjkoshy		}
1960145256Sjkoshy
1961145256Sjkoshy	}
1962145256Sjkoshy	break;
1963145256Sjkoshy
1964145256Sjkoshy	case PMC_FN_CSW_IN:
1965147191Sjkoshy		pmc_process_csw_in(td);
1966147191Sjkoshy		break;
1967145256Sjkoshy
1968147191Sjkoshy	case PMC_FN_CSW_OUT:
1969147191Sjkoshy		pmc_process_csw_out(td);
1970147191Sjkoshy		break;
1971145256Sjkoshy
1972145256Sjkoshy	/*
1973147191Sjkoshy	 * Process accumulated PC samples.
1974147191Sjkoshy	 *
1975147191Sjkoshy	 * This function is expected to be called by hardclock() for
1976147191Sjkoshy	 * each CPU that has accumulated PC samples.
1977147191Sjkoshy	 *
1978147191Sjkoshy	 * This function is to be executed on the CPU whose samples
1979147191Sjkoshy	 * are being processed.
1980145256Sjkoshy	 */
1981147191Sjkoshy	case PMC_FN_DO_SAMPLES:
1982145256Sjkoshy
1983145256Sjkoshy		/*
1984147191Sjkoshy		 * Clear the cpu specific bit in the CPU mask before
1985147191Sjkoshy		 * do the rest of the processing.  If the NMI handler
1986147191Sjkoshy		 * gets invoked after the "atomic_clear_int()" call
1987147191Sjkoshy		 * below but before "pmc_process_samples()" gets
1988147191Sjkoshy		 * around to processing the interrupt, then we will
1989147191Sjkoshy		 * come back here at the next hardclock() tick (and
1990147191Sjkoshy		 * may find nothing to do if "pmc_process_samples()"
1991147191Sjkoshy		 * had already processed the interrupt).  We don't
1992147191Sjkoshy		 * lose the interrupt sample.
1993145256Sjkoshy		 */
1994222813Sattilio		CPU_CLR_ATOMIC(PCPU_GET(cpuid), &pmc_cpumask);
1995233628Sfabient		pmc_process_samples(PCPU_GET(cpuid), PMC_HR);
1996233628Sfabient		pmc_process_samples(PCPU_GET(cpuid), PMC_SR);
1997147191Sjkoshy		break;
1998145256Sjkoshy
1999157144Sjkoshy	case PMC_FN_MMAP:
2000157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
2001157144Sjkoshy		pmc_process_mmap(td, (struct pmckern_map_in *) arg);
2002157144Sjkoshy		break;
2003157144Sjkoshy
2004157144Sjkoshy	case PMC_FN_MUNMAP:
2005157144Sjkoshy		sx_assert(&pmc_sx, SX_LOCKED);
2006157144Sjkoshy		pmc_process_munmap(td, (struct pmckern_map_out *) arg);
2007157144Sjkoshy		break;
2008157144Sjkoshy
2009174395Sjkoshy	case PMC_FN_USER_CALLCHAIN:
2010174395Sjkoshy		/*
2011174395Sjkoshy		 * Record a call chain.
2012174395Sjkoshy		 */
2013186037Sjkoshy		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2014186037Sjkoshy		    __LINE__));
2015233628Sfabient
2016233628Sfabient		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
2017174395Sjkoshy		    (struct trapframe *) arg);
2018186037Sjkoshy		td->td_pflags &= ~TDP_CALLCHAIN;
2019174395Sjkoshy		break;
2020174395Sjkoshy
2021233628Sfabient	case PMC_FN_USER_CALLCHAIN_SOFT:
2022233628Sfabient		/*
2023233628Sfabient		 * Record a call chain.
2024233628Sfabient		 */
2025233628Sfabient		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2026233628Sfabient		    __LINE__));
2027233628Sfabient		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_SR,
2028233628Sfabient		    (struct trapframe *) arg);
2029233628Sfabient		td->td_pflags &= ~TDP_CALLCHAIN;
2030233628Sfabient		break;
2031233628Sfabient
2032233628Sfabient	case PMC_FN_SOFT_SAMPLING:
2033233628Sfabient		/*
2034233628Sfabient		 * Call soft PMC sampling intr.
2035233628Sfabient		 */
2036233628Sfabient		pmc_soft_intr((struct pmckern_soft *) arg);
2037233628Sfabient		break;
2038233628Sfabient
2039145256Sjkoshy	default:
2040282641Sjhb#ifdef	HWPMC_DEBUG
2041145256Sjkoshy		KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
2042145256Sjkoshy#endif
2043145256Sjkoshy		break;
2044145256Sjkoshy
2045145256Sjkoshy	}
2046145256Sjkoshy
2047145256Sjkoshy	return 0;
2048145256Sjkoshy}
2049145256Sjkoshy
2050145256Sjkoshy/*
2051145256Sjkoshy * allocate a 'struct pmc_owner' descriptor in the owner hash table.
2052145256Sjkoshy */
2053145256Sjkoshy
2054145256Sjkoshystatic struct pmc_owner *
2055145256Sjkoshypmc_allocate_owner_descriptor(struct proc *p)
2056145256Sjkoshy{
2057145256Sjkoshy	uint32_t hindex;
2058145256Sjkoshy	struct pmc_owner *po;
2059145256Sjkoshy	struct pmc_ownerhash *poh;
2060145256Sjkoshy
2061145256Sjkoshy	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2062145256Sjkoshy	poh = &pmc_ownerhash[hindex];
2063145256Sjkoshy
2064145256Sjkoshy	/* allocate space for N pointers and one descriptor struct */
2065184802Sjkoshy	po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK|M_ZERO);
2066145256Sjkoshy	po->po_owner = p;
2067145256Sjkoshy	LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
2068145256Sjkoshy
2069147191Sjkoshy	TAILQ_INIT(&po->po_logbuffers);
2070168856Sjkoshy	mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
2071147191Sjkoshy
2072282658Sjhb	PMCDBG4(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
2073145256Sjkoshy	    p, p->p_pid, p->p_comm, po);
2074145256Sjkoshy
2075145256Sjkoshy	return po;
2076145256Sjkoshy}
2077145256Sjkoshy
2078147191Sjkoshystatic void
2079147191Sjkoshypmc_destroy_owner_descriptor(struct pmc_owner *po)
2080147191Sjkoshy{
2081147191Sjkoshy
2082282658Sjhb	PMCDBG4(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
2083147191Sjkoshy	    po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
2084147191Sjkoshy
2085147191Sjkoshy	mtx_destroy(&po->po_mtx);
2086184205Sdes	free(po, M_PMC);
2087147191Sjkoshy}
2088147191Sjkoshy
2089145256Sjkoshy/*
2090145256Sjkoshy * find the descriptor corresponding to process 'p', adding or removing it
2091145256Sjkoshy * as specified by 'mode'.
2092145256Sjkoshy */
2093145256Sjkoshy
2094145256Sjkoshystatic struct pmc_process *
2095145256Sjkoshypmc_find_process_descriptor(struct proc *p, uint32_t mode)
2096145256Sjkoshy{
2097145256Sjkoshy	uint32_t hindex;
2098145256Sjkoshy	struct pmc_process *pp, *ppnew;
2099145256Sjkoshy	struct pmc_processhash *pph;
2100145256Sjkoshy
2101145256Sjkoshy	hindex = PMC_HASH_PTR(p, pmc_processhashmask);
2102145256Sjkoshy	pph = &pmc_processhash[hindex];
2103145256Sjkoshy
2104145256Sjkoshy	ppnew = NULL;
2105145256Sjkoshy
2106145256Sjkoshy	/*
2107145256Sjkoshy	 * Pre-allocate memory in the FIND_ALLOCATE case since we
2108145256Sjkoshy	 * cannot call malloc(9) once we hold a spin lock.
2109145256Sjkoshy	 */
2110184802Sjkoshy	if (mode & PMC_FLAG_ALLOCATE)
2111184214Sdes		ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
2112184802Sjkoshy		    sizeof(struct pmc_targetstate), M_PMC, M_WAITOK|M_ZERO);
2113145256Sjkoshy
2114145256Sjkoshy	mtx_lock_spin(&pmc_processhash_mtx);
2115145256Sjkoshy	LIST_FOREACH(pp, pph, pp_next)
2116145256Sjkoshy	    if (pp->pp_proc == p)
2117145256Sjkoshy		    break;
2118145256Sjkoshy
2119145256Sjkoshy	if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
2120145256Sjkoshy		LIST_REMOVE(pp, pp_next);
2121145256Sjkoshy
2122145256Sjkoshy	if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
2123145256Sjkoshy	    ppnew != NULL) {
2124145256Sjkoshy		ppnew->pp_proc = p;
2125145256Sjkoshy		LIST_INSERT_HEAD(pph, ppnew, pp_next);
2126145256Sjkoshy		pp = ppnew;
2127145256Sjkoshy		ppnew = NULL;
2128145256Sjkoshy	}
2129145256Sjkoshy	mtx_unlock_spin(&pmc_processhash_mtx);
2130145256Sjkoshy
2131145256Sjkoshy	if (pp != NULL && ppnew != NULL)
2132184205Sdes		free(ppnew, M_PMC);
2133145256Sjkoshy
2134145256Sjkoshy	return pp;
2135145256Sjkoshy}
2136145256Sjkoshy
2137145256Sjkoshy/*
2138145256Sjkoshy * remove a process descriptor from the process hash table.
2139145256Sjkoshy */
2140145256Sjkoshy
2141145256Sjkoshystatic void
2142145256Sjkoshypmc_remove_process_descriptor(struct pmc_process *pp)
2143145256Sjkoshy{
2144145256Sjkoshy	KASSERT(pp->pp_refcnt == 0,
2145145256Sjkoshy	    ("[pmc,%d] Removing process descriptor %p with count %d",
2146145256Sjkoshy		__LINE__, pp, pp->pp_refcnt));
2147145256Sjkoshy
2148145256Sjkoshy	mtx_lock_spin(&pmc_processhash_mtx);
2149145256Sjkoshy	LIST_REMOVE(pp, pp_next);
2150145256Sjkoshy	mtx_unlock_spin(&pmc_processhash_mtx);
2151145256Sjkoshy}
2152145256Sjkoshy
2153145256Sjkoshy
2154145256Sjkoshy/*
2155145256Sjkoshy * find an owner descriptor corresponding to proc 'p'
2156145256Sjkoshy */
2157145256Sjkoshy
2158145256Sjkoshystatic struct pmc_owner *
2159145256Sjkoshypmc_find_owner_descriptor(struct proc *p)
2160145256Sjkoshy{
2161145256Sjkoshy	uint32_t hindex;
2162145256Sjkoshy	struct pmc_owner *po;
2163145256Sjkoshy	struct pmc_ownerhash *poh;
2164145256Sjkoshy
2165145256Sjkoshy	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2166145256Sjkoshy	poh = &pmc_ownerhash[hindex];
2167145256Sjkoshy
2168145256Sjkoshy	po = NULL;
2169145256Sjkoshy	LIST_FOREACH(po, poh, po_next)
2170145256Sjkoshy	    if (po->po_owner == p)
2171145256Sjkoshy		    break;
2172145256Sjkoshy
2173282658Sjhb	PMCDBG5(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2174145256Sjkoshy	    "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2175145256Sjkoshy
2176145256Sjkoshy	return po;
2177145256Sjkoshy}
2178145256Sjkoshy
2179145256Sjkoshy/*
2180145256Sjkoshy * pmc_allocate_pmc_descriptor
2181145256Sjkoshy *
2182145256Sjkoshy * Allocate a pmc descriptor and initialize its
2183145256Sjkoshy * fields.
2184145256Sjkoshy */
2185145256Sjkoshy
2186145256Sjkoshystatic struct pmc *
2187145256Sjkoshypmc_allocate_pmc_descriptor(void)
2188145256Sjkoshy{
2189145256Sjkoshy	struct pmc *pmc;
2190145256Sjkoshy
2191184802Sjkoshy	pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK|M_ZERO);
2192145256Sjkoshy
2193282658Sjhb	PMCDBG1(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2194145256Sjkoshy
2195145256Sjkoshy	return pmc;
2196145256Sjkoshy}
2197145256Sjkoshy
2198145256Sjkoshy/*
2199145256Sjkoshy * Destroy a pmc descriptor.
2200145256Sjkoshy */
2201145256Sjkoshy
2202145256Sjkoshystatic void
2203145256Sjkoshypmc_destroy_pmc_descriptor(struct pmc *pm)
2204145256Sjkoshy{
2205145256Sjkoshy
2206145256Sjkoshy	KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2207145256Sjkoshy	    pm->pm_state == PMC_STATE_FREE,
2208145256Sjkoshy	    ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2209145256Sjkoshy	KASSERT(LIST_EMPTY(&pm->pm_targets),
2210145256Sjkoshy	    ("[pmc,%d] destroying pmc with targets", __LINE__));
2211145256Sjkoshy	KASSERT(pm->pm_owner == NULL,
2212145256Sjkoshy	    ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2213145256Sjkoshy	KASSERT(pm->pm_runcount == 0,
2214145256Sjkoshy	    ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
2215145256Sjkoshy		pm->pm_runcount));
2216273236Smarkj
2217273236Smarkj	free(pm, M_PMC);
2218145256Sjkoshy}
2219145256Sjkoshy
2220147191Sjkoshystatic void
2221147191Sjkoshypmc_wait_for_pmc_idle(struct pmc *pm)
2222147191Sjkoshy{
2223282641Sjhb#ifdef HWPMC_DEBUG
2224147191Sjkoshy	volatile int maxloop;
2225147191Sjkoshy
2226183266Sjkoshy	maxloop = 100 * pmc_cpu_max();
2227147191Sjkoshy#endif
2228147191Sjkoshy	/*
2229147191Sjkoshy	 * Loop (with a forced context switch) till the PMC's runcount
2230147191Sjkoshy	 * comes down to zero.
2231147191Sjkoshy	 */
2232147191Sjkoshy	while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
2233282641Sjhb#ifdef HWPMC_DEBUG
2234147191Sjkoshy		maxloop--;
2235147191Sjkoshy		KASSERT(maxloop > 0,
2236147191Sjkoshy		    ("[pmc,%d] (ri%d, rc%d) waiting too long for "
2237147191Sjkoshy			"pmc to be free", __LINE__,
2238147191Sjkoshy			PMC_TO_ROWINDEX(pm), pm->pm_runcount));
2239147191Sjkoshy#endif
2240147191Sjkoshy		pmc_force_context_switch();
2241147191Sjkoshy	}
2242147191Sjkoshy}
2243147191Sjkoshy
2244145256Sjkoshy/*
2245145256Sjkoshy * This function does the following things:
2246145256Sjkoshy *
2247145256Sjkoshy *  - detaches the PMC from hardware
2248145256Sjkoshy *  - unlinks all target threads that were attached to it
2249145256Sjkoshy *  - removes the PMC from its owner's list
2250273236Smarkj *  - destroys the PMC private mutex
2251145256Sjkoshy *
2252273236Smarkj * Once this function completes, the given pmc pointer can be freed by
2253273236Smarkj * calling pmc_destroy_pmc_descriptor().
2254145256Sjkoshy */
2255145256Sjkoshy
2256145256Sjkoshystatic void
2257145256Sjkoshypmc_release_pmc_descriptor(struct pmc *pm)
2258145256Sjkoshy{
2259145774Sjkoshy	enum pmc_mode mode;
2260145256Sjkoshy	struct pmc_hw *phw;
2261184802Sjkoshy	u_int adjri, ri, cpu;
2262147191Sjkoshy	struct pmc_owner *po;
2263184802Sjkoshy	struct pmc_binding pb;
2264145256Sjkoshy	struct pmc_process *pp;
2265184802Sjkoshy	struct pmc_classdep *pcd;
2266145256Sjkoshy	struct pmc_target *ptgt, *tmp;
2267145256Sjkoshy
2268145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
2269145256Sjkoshy
2270145256Sjkoshy	KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2271145256Sjkoshy
2272145774Sjkoshy	ri   = PMC_TO_ROWINDEX(pm);
2273184802Sjkoshy	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
2274145774Sjkoshy	mode = PMC_TO_MODE(pm);
2275145256Sjkoshy
2276282658Sjhb	PMCDBG3(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2277145774Sjkoshy	    mode);
2278145256Sjkoshy
2279145256Sjkoshy	/*
2280145256Sjkoshy	 * First, we take the PMC off hardware.
2281145256Sjkoshy	 */
2282145301Simp	cpu = 0;
2283145774Sjkoshy	if (PMC_IS_SYSTEM_MODE(mode)) {
2284145256Sjkoshy
2285145256Sjkoshy		/*
2286145256Sjkoshy		 * A system mode PMC runs on a specific CPU.  Switch
2287145256Sjkoshy		 * to this CPU and turn hardware off.
2288145256Sjkoshy		 */
2289145256Sjkoshy		pmc_save_cpu_binding(&pb);
2290145256Sjkoshy
2291145774Sjkoshy		cpu = PMC_TO_CPU(pm);
2292145256Sjkoshy
2293147191Sjkoshy		pmc_select_cpu(cpu);
2294145256Sjkoshy
2295147191Sjkoshy		/* switch off non-stalled CPUs */
2296290811Sjtl		CPU_CLR_ATOMIC(cpu, &pm->pm_cpustate);
2297147191Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING &&
2298290811Sjtl		    !CPU_ISSET(cpu, &pm->pm_stalled)) {
2299145256Sjkoshy
2300145256Sjkoshy			phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2301145256Sjkoshy
2302145256Sjkoshy			KASSERT(phw->phw_pmc == pm,
2303145256Sjkoshy			    ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2304145256Sjkoshy				__LINE__, ri, phw->phw_pmc, pm));
2305282658Sjhb			PMCDBG2(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2306145256Sjkoshy
2307145256Sjkoshy			critical_enter();
2308184802Sjkoshy			pcd->pcd_stop_pmc(cpu, adjri);
2309145256Sjkoshy			critical_exit();
2310145256Sjkoshy		}
2311145256Sjkoshy
2312282658Sjhb		PMCDBG2(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2313145256Sjkoshy
2314145256Sjkoshy		critical_enter();
2315184802Sjkoshy		pcd->pcd_config_pmc(cpu, adjri, NULL);
2316145256Sjkoshy		critical_exit();
2317145256Sjkoshy
2318147191Sjkoshy		/* adjust the global and process count of SS mode PMCs */
2319147191Sjkoshy		if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2320147191Sjkoshy			po = pm->pm_owner;
2321147191Sjkoshy			po->po_sscount--;
2322147191Sjkoshy			if (po->po_sscount == 0) {
2323147191Sjkoshy				atomic_subtract_rel_int(&pmc_ss_count, 1);
2324147191Sjkoshy				LIST_REMOVE(po, po_ssnext);
2325147191Sjkoshy			}
2326147191Sjkoshy		}
2327147191Sjkoshy
2328145256Sjkoshy		pm->pm_state = PMC_STATE_DELETED;
2329145256Sjkoshy
2330145256Sjkoshy		pmc_restore_cpu_binding(&pb);
2331145256Sjkoshy
2332147191Sjkoshy		/*
2333147191Sjkoshy		 * We could have references to this PMC structure in
2334147191Sjkoshy		 * the per-cpu sample queues.  Wait for the queue to
2335147191Sjkoshy		 * drain.
2336147191Sjkoshy		 */
2337147191Sjkoshy		pmc_wait_for_pmc_idle(pm);
2338147191Sjkoshy
2339145774Sjkoshy	} else if (PMC_IS_VIRTUAL_MODE(mode)) {
2340145256Sjkoshy
2341145256Sjkoshy		/*
2342145256Sjkoshy		 * A virtual PMC could be running on multiple CPUs at
2343145256Sjkoshy		 * a given instant.
2344145256Sjkoshy		 *
2345145256Sjkoshy		 * By marking its state as DELETED, we ensure that
2346145256Sjkoshy		 * this PMC is never further scheduled on hardware.
2347145256Sjkoshy		 *
2348145256Sjkoshy		 * Then we wait till all CPUs are done with this PMC.
2349145256Sjkoshy		 */
2350145256Sjkoshy		pm->pm_state = PMC_STATE_DELETED;
2351145256Sjkoshy
2352145256Sjkoshy
2353147191Sjkoshy		/* Wait for the PMCs runcount to come to zero. */
2354147191Sjkoshy		pmc_wait_for_pmc_idle(pm);
2355145256Sjkoshy
2356145256Sjkoshy		/*
2357145256Sjkoshy		 * At this point the PMC is off all CPUs and cannot be
2358145256Sjkoshy		 * freshly scheduled onto a CPU.  It is now safe to
2359145256Sjkoshy		 * unlink all targets from this PMC.  If a
2360145256Sjkoshy		 * process-record's refcount falls to zero, we remove
2361145256Sjkoshy		 * it from the hash table.  The module-wide SX lock
2362145256Sjkoshy		 * protects us from races.
2363145256Sjkoshy		 */
2364145256Sjkoshy		LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2365145256Sjkoshy			pp = ptgt->pt_process;
2366145256Sjkoshy			pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2367145256Sjkoshy
2368282658Sjhb			PMCDBG1(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2369145256Sjkoshy
2370145256Sjkoshy			/*
2371145256Sjkoshy			 * If the target process record shows that no
2372145256Sjkoshy			 * PMCs are attached to it, reclaim its space.
2373145256Sjkoshy			 */
2374145256Sjkoshy
2375145256Sjkoshy			if (pp->pp_refcnt == 0) {
2376145256Sjkoshy				pmc_remove_process_descriptor(pp);
2377184205Sdes				free(pp, M_PMC);
2378145256Sjkoshy			}
2379145256Sjkoshy		}
2380145256Sjkoshy
2381145256Sjkoshy		cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2382145256Sjkoshy
2383145256Sjkoshy	}
2384145256Sjkoshy
2385145256Sjkoshy	/*
2386145256Sjkoshy	 * Release any MD resources
2387145256Sjkoshy	 */
2388184802Sjkoshy	(void) pcd->pcd_release_pmc(cpu, adjri, pm);
2389145256Sjkoshy
2390145256Sjkoshy	/*
2391145256Sjkoshy	 * Update row disposition
2392145256Sjkoshy	 */
2393145256Sjkoshy
2394145774Sjkoshy	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2395145256Sjkoshy		PMC_UNMARK_ROW_STANDALONE(ri);
2396145256Sjkoshy	else
2397145256Sjkoshy		PMC_UNMARK_ROW_THREAD(ri);
2398145256Sjkoshy
2399145256Sjkoshy	/* unlink from the owner's list */
2400147191Sjkoshy	if (pm->pm_owner) {
2401147191Sjkoshy		LIST_REMOVE(pm, pm_next);
2402147191Sjkoshy		pm->pm_owner = NULL;
2403147191Sjkoshy	}
2404145256Sjkoshy}
2405145256Sjkoshy
2406145256Sjkoshy/*
2407145256Sjkoshy * Register an owner and a pmc.
2408145256Sjkoshy */
2409145256Sjkoshy
2410145256Sjkoshystatic int
2411145256Sjkoshypmc_register_owner(struct proc *p, struct pmc *pmc)
2412145256Sjkoshy{
2413145256Sjkoshy	struct pmc_owner *po;
2414145256Sjkoshy
2415145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
2416145256Sjkoshy
2417145774Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) == NULL)
2418147191Sjkoshy		if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2419145256Sjkoshy			return ENOMEM;
2420145256Sjkoshy
2421145256Sjkoshy	KASSERT(pmc->pm_owner == NULL,
2422145256Sjkoshy	    ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2423145256Sjkoshy	pmc->pm_owner  = po;
2424145256Sjkoshy
2425147191Sjkoshy	LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2426145256Sjkoshy
2427145256Sjkoshy	PROC_LOCK(p);
2428145256Sjkoshy	p->p_flag |= P_HWPMC;
2429145256Sjkoshy	PROC_UNLOCK(p);
2430145256Sjkoshy
2431147191Sjkoshy	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2432147191Sjkoshy		pmclog_process_pmcallocate(pmc);
2433145256Sjkoshy
2434282658Sjhb	PMCDBG2(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2435147191Sjkoshy	    po, pmc);
2436147191Sjkoshy
2437145256Sjkoshy	return 0;
2438145256Sjkoshy}
2439145256Sjkoshy
2440145256Sjkoshy/*
2441145256Sjkoshy * Return the current row disposition:
2442145256Sjkoshy * == 0 => FREE
2443145256Sjkoshy *  > 0 => PROCESS MODE
2444145256Sjkoshy *  < 0 => SYSTEM MODE
2445145256Sjkoshy */
2446145256Sjkoshy
2447145256Sjkoshyint
2448145256Sjkoshypmc_getrowdisp(int ri)
2449145256Sjkoshy{
2450145256Sjkoshy	return pmc_pmcdisp[ri];
2451145256Sjkoshy}
2452145256Sjkoshy
2453145256Sjkoshy/*
2454145256Sjkoshy * Check if a PMC at row index 'ri' can be allocated to the current
2455145256Sjkoshy * process.
2456145256Sjkoshy *
2457145256Sjkoshy * Allocation can fail if:
2458145256Sjkoshy *   - the current process is already being profiled by a PMC at index 'ri',
2459145256Sjkoshy *     attached to it via OP_PMCATTACH.
2460145256Sjkoshy *   - the current process has already allocated a PMC at index 'ri'
2461145256Sjkoshy *     via OP_ALLOCATE.
2462145256Sjkoshy */
2463145256Sjkoshy
2464145256Sjkoshystatic int
2465145774Sjkoshypmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2466145256Sjkoshy{
2467145774Sjkoshy	enum pmc_mode mode;
2468145774Sjkoshy	struct pmc *pm;
2469145256Sjkoshy	struct pmc_owner *po;
2470145256Sjkoshy	struct pmc_process *pp;
2471145256Sjkoshy
2472282658Sjhb	PMCDBG5(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2473145774Sjkoshy	    "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2474145256Sjkoshy
2475145774Sjkoshy	/*
2476145774Sjkoshy	 * We shouldn't have already allocated a process-mode PMC at
2477145774Sjkoshy	 * row index 'ri'.
2478145774Sjkoshy	 *
2479145774Sjkoshy	 * We shouldn't have allocated a system-wide PMC on the same
2480145774Sjkoshy	 * CPU and same RI.
2481145774Sjkoshy	 */
2482145256Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) != NULL)
2483147191Sjkoshy		LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2484145774Sjkoshy		    if (PMC_TO_ROWINDEX(pm) == ri) {
2485145774Sjkoshy			    mode = PMC_TO_MODE(pm);
2486145774Sjkoshy			    if (PMC_IS_VIRTUAL_MODE(mode))
2487145774Sjkoshy				    return EEXIST;
2488145774Sjkoshy			    if (PMC_IS_SYSTEM_MODE(mode) &&
2489145774Sjkoshy				(int) PMC_TO_CPU(pm) == cpu)
2490145774Sjkoshy				    return EEXIST;
2491145774Sjkoshy		    }
2492145774Sjkoshy	        }
2493145256Sjkoshy
2494145774Sjkoshy	/*
2495145774Sjkoshy	 * We also shouldn't be the target of any PMC at this index
2496145774Sjkoshy	 * since otherwise a PMC_ATTACH to ourselves will fail.
2497145774Sjkoshy	 */
2498145256Sjkoshy	if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2499145256Sjkoshy		if (pp->pp_pmcs[ri].pp_pmc)
2500145256Sjkoshy			return EEXIST;
2501145256Sjkoshy
2502282658Sjhb	PMCDBG4(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2503145256Sjkoshy	    p, p->p_pid, p->p_comm, ri);
2504145256Sjkoshy
2505145256Sjkoshy	return 0;
2506145256Sjkoshy}
2507145256Sjkoshy
2508145256Sjkoshy/*
2509145256Sjkoshy * Check if a given PMC at row index 'ri' can be currently used in
2510145256Sjkoshy * mode 'mode'.
2511145256Sjkoshy */
2512145256Sjkoshy
2513145256Sjkoshystatic int
2514145256Sjkoshypmc_can_allocate_row(int ri, enum pmc_mode mode)
2515145256Sjkoshy{
2516145256Sjkoshy	enum pmc_disp	disp;
2517145256Sjkoshy
2518145256Sjkoshy	sx_assert(&pmc_sx, SX_XLOCKED);
2519145256Sjkoshy
2520282658Sjhb	PMCDBG2(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2521145256Sjkoshy
2522145256Sjkoshy	if (PMC_IS_SYSTEM_MODE(mode))
2523145256Sjkoshy		disp = PMC_DISP_STANDALONE;
2524145256Sjkoshy	else
2525145256Sjkoshy		disp = PMC_DISP_THREAD;
2526145256Sjkoshy
2527145256Sjkoshy	/*
2528145256Sjkoshy	 * check disposition for PMC row 'ri':
2529145256Sjkoshy	 *
2530145256Sjkoshy	 * Expected disposition		Row-disposition		Result
2531145256Sjkoshy	 *
2532145256Sjkoshy	 * STANDALONE			STANDALONE or FREE	proceed
2533145256Sjkoshy	 * STANDALONE			THREAD			fail
2534145256Sjkoshy	 * THREAD			THREAD or FREE		proceed
2535145256Sjkoshy	 * THREAD			STANDALONE		fail
2536145256Sjkoshy	 */
2537145256Sjkoshy
2538145256Sjkoshy	if (!PMC_ROW_DISP_IS_FREE(ri) &&
2539145256Sjkoshy	    !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2540145256Sjkoshy	    !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2541145256Sjkoshy		return EBUSY;
2542145256Sjkoshy
2543145256Sjkoshy	/*
2544145256Sjkoshy	 * All OK
2545145256Sjkoshy	 */
2546145256Sjkoshy
2547282658Sjhb	PMCDBG2(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2548145256Sjkoshy
2549145256Sjkoshy	return 0;
2550145256Sjkoshy
2551145256Sjkoshy}
2552145256Sjkoshy
2553145256Sjkoshy/*
2554145774Sjkoshy * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2555145256Sjkoshy */
2556145256Sjkoshy
2557145256Sjkoshystatic struct pmc *
2558145256Sjkoshypmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2559145256Sjkoshy{
2560147191Sjkoshy	struct pmc *pm;
2561145256Sjkoshy
2562145774Sjkoshy	KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2563145774Sjkoshy	    ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2564145774Sjkoshy		PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2565145256Sjkoshy
2566147191Sjkoshy	LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2567147191Sjkoshy	    if (pm->pm_id == pmcid)
2568147191Sjkoshy		    return pm;
2569145256Sjkoshy
2570145256Sjkoshy	return NULL;
2571145256Sjkoshy}
2572145256Sjkoshy
2573145256Sjkoshystatic int
2574145256Sjkoshypmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2575145256Sjkoshy{
2576145256Sjkoshy
2577287115Sbz	struct pmc *pm, *opm;
2578145256Sjkoshy	struct pmc_owner *po;
2579287115Sbz	struct pmc_process *pp;
2580145256Sjkoshy
2581287115Sbz	KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2582287115Sbz	    ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2583287115Sbz		PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2584282658Sjhb	PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid);
2585145256Sjkoshy
2586287115Sbz	if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL) {
2587287115Sbz		/*
2588287115Sbz		 * In case of PMC_F_DESCENDANTS child processes we will not find
2589287115Sbz		 * the current process in the owners hash list.  Find the owner
2590287115Sbz		 * process first and from there lookup the po.
2591287115Sbz		 */
2592287115Sbz		if ((pp = pmc_find_process_descriptor(curthread->td_proc,
2593287115Sbz		    PMC_FLAG_NONE)) == NULL) {
2594287115Sbz			return ESRCH;
2595287115Sbz		} else {
2596287115Sbz			opm = pp->pp_pmcs[PMC_ID_TO_ROWINDEX(pmcid)].pp_pmc;
2597287115Sbz			if (opm == NULL)
2598287115Sbz				return ESRCH;
2599287115Sbz			if ((opm->pm_flags & (PMC_F_ATTACHED_TO_OWNER|
2600287115Sbz			    PMC_F_DESCENDANTS)) != (PMC_F_ATTACHED_TO_OWNER|
2601287115Sbz			    PMC_F_DESCENDANTS))
2602287115Sbz				return ESRCH;
2603287115Sbz			po = opm->pm_owner;
2604287115Sbz		}
2605287115Sbz	}
2606145256Sjkoshy
2607145256Sjkoshy	if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2608145256Sjkoshy		return EINVAL;
2609145256Sjkoshy
2610282658Sjhb	PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2611145256Sjkoshy
2612145256Sjkoshy	*pmc = pm;
2613145256Sjkoshy	return 0;
2614145256Sjkoshy}
2615145256Sjkoshy
2616145256Sjkoshy/*
2617145256Sjkoshy * Start a PMC.
2618145256Sjkoshy */
2619145256Sjkoshy
2620145256Sjkoshystatic int
2621145256Sjkoshypmc_start(struct pmc *pm)
2622145256Sjkoshy{
2623145774Sjkoshy	enum pmc_mode mode;
2624147191Sjkoshy	struct pmc_owner *po;
2625145256Sjkoshy	struct pmc_binding pb;
2626184802Sjkoshy	struct pmc_classdep *pcd;
2627184802Sjkoshy	int adjri, error, cpu, ri;
2628145256Sjkoshy
2629145256Sjkoshy	KASSERT(pm != NULL,
2630145256Sjkoshy	    ("[pmc,%d] null pm", __LINE__));
2631145256Sjkoshy
2632145774Sjkoshy	mode = PMC_TO_MODE(pm);
2633145774Sjkoshy	ri   = PMC_TO_ROWINDEX(pm);
2634184802Sjkoshy	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
2635184802Sjkoshy
2636145774Sjkoshy	error = 0;
2637145256Sjkoshy
2638282658Sjhb	PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2639145774Sjkoshy
2640147191Sjkoshy	po = pm->pm_owner;
2641145256Sjkoshy
2642174395Sjkoshy	/*
2643174395Sjkoshy	 * Disallow PMCSTART if a logfile is required but has not been
2644174395Sjkoshy	 * configured yet.
2645174395Sjkoshy	 */
2646174395Sjkoshy	if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2647174395Sjkoshy	    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2648184802Sjkoshy		return (EDOOFUS);	/* programming error */
2649174395Sjkoshy
2650174395Sjkoshy	/*
2651174395Sjkoshy	 * If this is a sampling mode PMC, log mapping information for
2652174395Sjkoshy	 * the kernel modules that are currently loaded.
2653174395Sjkoshy	 */
2654174395Sjkoshy	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2655174395Sjkoshy	    pmc_log_kernel_mappings(pm);
2656174395Sjkoshy
2657145774Sjkoshy	if (PMC_IS_VIRTUAL_MODE(mode)) {
2658145256Sjkoshy
2659145256Sjkoshy		/*
2660147191Sjkoshy		 * If a PMCATTACH has never been done on this PMC,
2661147191Sjkoshy		 * attach it to its owner process.
2662145256Sjkoshy		 */
2663145256Sjkoshy
2664145256Sjkoshy		if (LIST_EMPTY(&pm->pm_targets))
2665147191Sjkoshy			error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2666147191Sjkoshy			    pmc_attach_process(po->po_owner, pm);
2667145256Sjkoshy
2668145774Sjkoshy		/*
2669147191Sjkoshy		 * If the PMC is attached to its owner, then force a context
2670147191Sjkoshy		 * switch to ensure that the MD state gets set correctly.
2671145256Sjkoshy		 */
2672145256Sjkoshy
2673147191Sjkoshy		if (error == 0) {
2674147191Sjkoshy			pm->pm_state = PMC_STATE_RUNNING;
2675147191Sjkoshy			if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2676147191Sjkoshy				pmc_force_context_switch();
2677147191Sjkoshy		}
2678147191Sjkoshy
2679184802Sjkoshy		return (error);
2680147191Sjkoshy	}
2681145256Sjkoshy
2682147191Sjkoshy
2683147191Sjkoshy	/*
2684147191Sjkoshy	 * A system-wide PMC.
2685174395Sjkoshy	 *
2686147191Sjkoshy	 * Add the owner to the global list if this is a system-wide
2687147191Sjkoshy	 * sampling PMC.
2688147191Sjkoshy	 */
2689147191Sjkoshy
2690147191Sjkoshy	if (mode == PMC_MODE_SS) {
2691147191Sjkoshy		if (po->po_sscount == 0) {
2692147191Sjkoshy			LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2693147191Sjkoshy			atomic_add_rel_int(&pmc_ss_count, 1);
2694282658Sjhb			PMCDBG1(PMC,OPS,1, "po=%p in global list", po);
2695147191Sjkoshy		}
2696147191Sjkoshy		po->po_sscount++;
2697145256Sjkoshy
2698207484Srstone		/*
2699207484Srstone		 * Log mapping information for all existing processes in the
2700207484Srstone		 * system.  Subsequent mappings are logged as they happen;
2701207484Srstone		 * see pmc_process_mmap().
2702207484Srstone		 */
2703207484Srstone		if (po->po_logprocmaps == 0) {
2704207484Srstone			pmc_log_all_process_mappings(po);
2705207484Srstone			po->po_logprocmaps = 1;
2706207484Srstone		}
2707201021Sjkoshy	}
2708157144Sjkoshy
2709145256Sjkoshy	/*
2710147191Sjkoshy	 * Move to the CPU associated with this
2711145256Sjkoshy	 * PMC, and start the hardware.
2712145256Sjkoshy	 */
2713145256Sjkoshy
2714145256Sjkoshy	pmc_save_cpu_binding(&pb);
2715145256Sjkoshy
2716145774Sjkoshy	cpu = PMC_TO_CPU(pm);
2717145256Sjkoshy
2718183266Sjkoshy	if (!pmc_cpu_is_active(cpu))
2719184802Sjkoshy		return (ENXIO);
2720145256Sjkoshy
2721145256Sjkoshy	pmc_select_cpu(cpu);
2722145256Sjkoshy
2723145256Sjkoshy	/*
2724145256Sjkoshy	 * global PMCs are configured at allocation time
2725145256Sjkoshy	 * so write out the initial value and start the PMC.
2726145256Sjkoshy	 */
2727145256Sjkoshy
2728147191Sjkoshy	pm->pm_state = PMC_STATE_RUNNING;
2729147191Sjkoshy
2730145774Sjkoshy	critical_enter();
2731184802Sjkoshy	if ((error = pcd->pcd_write_pmc(cpu, adjri,
2732145774Sjkoshy		 PMC_IS_SAMPLING_MODE(mode) ?
2733145256Sjkoshy		 pm->pm_sc.pm_reloadcount :
2734290811Sjtl		 pm->pm_sc.pm_initial)) == 0) {
2735290811Sjtl		/* If a sampling mode PMC, reset stalled state. */
2736290811Sjtl		if (PMC_IS_SAMPLING_MODE(mode))
2737290811Sjtl			CPU_CLR_ATOMIC(cpu, &pm->pm_stalled);
2738290811Sjtl
2739290811Sjtl		/* Indicate that we desire this to run. Start it. */
2740290811Sjtl		CPU_SET_ATOMIC(cpu, &pm->pm_cpustate);
2741184802Sjkoshy		error = pcd->pcd_start_pmc(cpu, adjri);
2742290811Sjtl	}
2743145774Sjkoshy	critical_exit();
2744145256Sjkoshy
2745145256Sjkoshy	pmc_restore_cpu_binding(&pb);
2746145256Sjkoshy
2747184802Sjkoshy	return (error);
2748145256Sjkoshy}
2749145256Sjkoshy
2750145256Sjkoshy/*
2751145256Sjkoshy * Stop a PMC.
2752145256Sjkoshy */
2753145256Sjkoshy
2754145256Sjkoshystatic int
2755145256Sjkoshypmc_stop(struct pmc *pm)
2756145256Sjkoshy{
2757147191Sjkoshy	struct pmc_owner *po;
2758145256Sjkoshy	struct pmc_binding pb;
2759184802Sjkoshy	struct pmc_classdep *pcd;
2760184802Sjkoshy	int adjri, cpu, error, ri;
2761145256Sjkoshy
2762145256Sjkoshy	KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2763145256Sjkoshy
2764282658Sjhb	PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2765145774Sjkoshy	    PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2766145256Sjkoshy
2767145256Sjkoshy	pm->pm_state = PMC_STATE_STOPPED;
2768145256Sjkoshy
2769145256Sjkoshy	/*
2770145256Sjkoshy	 * If the PMC is a virtual mode one, changing the state to
2771145256Sjkoshy	 * non-RUNNING is enough to ensure that the PMC never gets
2772145256Sjkoshy	 * scheduled.
2773145256Sjkoshy	 *
2774145256Sjkoshy	 * If this PMC is current running on a CPU, then it will
2775145256Sjkoshy	 * handled correctly at the time its target process is context
2776145256Sjkoshy	 * switched out.
2777145256Sjkoshy	 */
2778145256Sjkoshy
2779145774Sjkoshy	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2780145256Sjkoshy		return 0;
2781145256Sjkoshy
2782145256Sjkoshy	/*
2783145256Sjkoshy	 * A system-mode PMC.  Move to the CPU associated with
2784145256Sjkoshy	 * this PMC, and stop the hardware.  We update the
2785145256Sjkoshy	 * 'initial count' so that a subsequent PMCSTART will
2786145256Sjkoshy	 * resume counting from the current hardware count.
2787145256Sjkoshy	 */
2788145256Sjkoshy
2789145256Sjkoshy	pmc_save_cpu_binding(&pb);
2790145256Sjkoshy
2791145774Sjkoshy	cpu = PMC_TO_CPU(pm);
2792145256Sjkoshy
2793183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
2794145774Sjkoshy	    ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2795145774Sjkoshy
2796183266Sjkoshy	if (!pmc_cpu_is_active(cpu))
2797145256Sjkoshy		return ENXIO;
2798145256Sjkoshy
2799145256Sjkoshy	pmc_select_cpu(cpu);
2800145256Sjkoshy
2801145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
2802184802Sjkoshy	pcd = pmc_ri_to_classdep(md, ri, &adjri);
2803145256Sjkoshy
2804290811Sjtl	CPU_CLR_ATOMIC(cpu, &pm->pm_cpustate);
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);
2820282658Sjhb			PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po);
2821147191Sjkoshy		}
2822147191Sjkoshy	}
2823147191Sjkoshy
2824184802Sjkoshy	return (error);
2825145256Sjkoshy}
2826145256Sjkoshy
2827145256Sjkoshy
2828282641Sjhb#ifdef	HWPMC_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
2873282658Sjhb	PMCDBG3(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;
3028245339Ssbruno		for (ev = PMC_EV_SOFT_FIRST; (int)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
3386282658Sjhb		PMCDBG4(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);
3440145256Sjkoshy			pmc = NULL;
3441145256Sjkoshy			error = EINVAL;
3442145256Sjkoshy			break;
3443145256Sjkoshy		}
3444145256Sjkoshy
3445145774Sjkoshy		/* Fill in the correct value in the ID field */
3446145774Sjkoshy		pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3447145256Sjkoshy
3448282658Sjhb		PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3449145774Sjkoshy		    pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3450145774Sjkoshy
3451147191Sjkoshy		/* Process mode PMCs with logging enabled need log files */
3452147191Sjkoshy		if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3453147191Sjkoshy			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3454147191Sjkoshy
3455147191Sjkoshy		/* All system mode sampling PMCs require a log file */
3456147191Sjkoshy		if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3457147191Sjkoshy			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3458147191Sjkoshy
3459145256Sjkoshy		/*
3460145256Sjkoshy		 * Configure global pmc's immediately
3461145256Sjkoshy		 */
3462145256Sjkoshy
3463145774Sjkoshy		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3464145774Sjkoshy
3465145774Sjkoshy			pmc_save_cpu_binding(&pb);
3466145774Sjkoshy			pmc_select_cpu(cpu);
3467145774Sjkoshy
3468145774Sjkoshy			phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3469184802Sjkoshy			pcd = pmc_ri_to_classdep(md, n, &adjri);
3470145774Sjkoshy
3471145774Sjkoshy			if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3472184802Sjkoshy			    (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3473184802Sjkoshy				(void) pcd->pcd_release_pmc(cpu, adjri, pmc);
3474145256Sjkoshy				pmc_destroy_pmc_descriptor(pmc);
3475145256Sjkoshy				pmc = NULL;
3476145774Sjkoshy				pmc_restore_cpu_binding(&pb);
3477145774Sjkoshy				error = EPERM;
3478145256Sjkoshy				break;
3479145256Sjkoshy			}
3480145256Sjkoshy
3481145774Sjkoshy			pmc_restore_cpu_binding(&pb);
3482145774Sjkoshy		}
3483145256Sjkoshy
3484145256Sjkoshy		pmc->pm_state    = PMC_STATE_ALLOCATED;
3485145256Sjkoshy
3486145256Sjkoshy		/*
3487145256Sjkoshy		 * mark row disposition
3488145256Sjkoshy		 */
3489145256Sjkoshy
3490145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode))
3491145256Sjkoshy			PMC_MARK_ROW_STANDALONE(n);
3492145256Sjkoshy		else
3493145256Sjkoshy			PMC_MARK_ROW_THREAD(n);
3494145256Sjkoshy
3495145256Sjkoshy		/*
3496145256Sjkoshy		 * Register this PMC with the current thread as its owner.
3497145256Sjkoshy		 */
3498145256Sjkoshy
3499145256Sjkoshy		if ((error =
3500145256Sjkoshy		    pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3501145256Sjkoshy			pmc_release_pmc_descriptor(pmc);
3502273236Smarkj			pmc_destroy_pmc_descriptor(pmc);
3503145256Sjkoshy			pmc = NULL;
3504145256Sjkoshy			break;
3505145256Sjkoshy		}
3506145256Sjkoshy
3507145256Sjkoshy		/*
3508145256Sjkoshy		 * Return the allocated index.
3509145256Sjkoshy		 */
3510145256Sjkoshy
3511145774Sjkoshy		pa.pm_pmcid = pmc->pm_id;
3512145256Sjkoshy
3513145256Sjkoshy		error = copyout(&pa, arg, sizeof(pa));
3514145256Sjkoshy	}
3515145256Sjkoshy	break;
3516145256Sjkoshy
3517145256Sjkoshy
3518145256Sjkoshy	/*
3519145256Sjkoshy	 * Attach a PMC to a process.
3520145256Sjkoshy	 */
3521145256Sjkoshy
3522145256Sjkoshy	case PMC_OP_PMCATTACH:
3523145256Sjkoshy	{
3524145256Sjkoshy		struct pmc *pm;
3525145256Sjkoshy		struct proc *p;
3526145256Sjkoshy		struct pmc_op_pmcattach a;
3527145256Sjkoshy
3528145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3529145256Sjkoshy
3530145256Sjkoshy		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3531145256Sjkoshy			break;
3532145256Sjkoshy
3533145256Sjkoshy		if (a.pm_pid < 0) {
3534145256Sjkoshy			error = EINVAL;
3535145256Sjkoshy			break;
3536145256Sjkoshy		} else if (a.pm_pid == 0)
3537145256Sjkoshy			a.pm_pid = td->td_proc->p_pid;
3538145256Sjkoshy
3539145256Sjkoshy		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3540145256Sjkoshy			break;
3541145256Sjkoshy
3542145774Sjkoshy		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3543145256Sjkoshy			error = EINVAL;
3544145256Sjkoshy			break;
3545145256Sjkoshy		}
3546145256Sjkoshy
3547145256Sjkoshy		/* PMCs may be (re)attached only when allocated or stopped */
3548145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) {
3549145256Sjkoshy			error = EBUSY;
3550145256Sjkoshy			break;
3551145256Sjkoshy		} else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3552145256Sjkoshy		    pm->pm_state != PMC_STATE_STOPPED) {
3553145256Sjkoshy			error = EINVAL;
3554145256Sjkoshy			break;
3555145256Sjkoshy		}
3556145256Sjkoshy
3557145256Sjkoshy		/* lookup pid */
3558145256Sjkoshy		if ((p = pfind(a.pm_pid)) == NULL) {
3559145256Sjkoshy			error = ESRCH;
3560145256Sjkoshy			break;
3561145256Sjkoshy		}
3562145256Sjkoshy
3563145256Sjkoshy		/*
3564145256Sjkoshy		 * Ignore processes that are working on exiting.
3565145256Sjkoshy		 */
3566145256Sjkoshy		if (p->p_flag & P_WEXIT) {
3567145256Sjkoshy			error = ESRCH;
3568145256Sjkoshy			PROC_UNLOCK(p);	/* pfind() returns a locked process */
3569145256Sjkoshy			break;
3570145256Sjkoshy		}
3571145256Sjkoshy
3572145256Sjkoshy		/*
3573145256Sjkoshy		 * we are allowed to attach a PMC to a process if
3574145256Sjkoshy		 * we can debug it.
3575145256Sjkoshy		 */
3576145256Sjkoshy		error = p_candebug(curthread, p);
3577145256Sjkoshy
3578145256Sjkoshy		PROC_UNLOCK(p);
3579145256Sjkoshy
3580145256Sjkoshy		if (error == 0)
3581145256Sjkoshy			error = pmc_attach_process(p, pm);
3582145256Sjkoshy	}
3583145256Sjkoshy	break;
3584145256Sjkoshy
3585145256Sjkoshy
3586145256Sjkoshy	/*
3587145256Sjkoshy	 * Detach an attached PMC from a process.
3588145256Sjkoshy	 */
3589145256Sjkoshy
3590145256Sjkoshy	case PMC_OP_PMCDETACH:
3591145256Sjkoshy	{
3592145256Sjkoshy		struct pmc *pm;
3593145256Sjkoshy		struct proc *p;
3594145256Sjkoshy		struct pmc_op_pmcattach a;
3595145256Sjkoshy
3596145256Sjkoshy		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3597145256Sjkoshy			break;
3598145256Sjkoshy
3599145256Sjkoshy		if (a.pm_pid < 0) {
3600145256Sjkoshy			error = EINVAL;
3601145256Sjkoshy			break;
3602145256Sjkoshy		} else if (a.pm_pid == 0)
3603145256Sjkoshy			a.pm_pid = td->td_proc->p_pid;
3604145256Sjkoshy
3605145256Sjkoshy		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3606145256Sjkoshy			break;
3607145256Sjkoshy
3608145256Sjkoshy		if ((p = pfind(a.pm_pid)) == NULL) {
3609145256Sjkoshy			error = ESRCH;
3610145256Sjkoshy			break;
3611145256Sjkoshy		}
3612145256Sjkoshy
3613145256Sjkoshy		/*
3614145256Sjkoshy		 * Treat processes that are in the process of exiting
3615145256Sjkoshy		 * as if they were not present.
3616145256Sjkoshy		 */
3617145256Sjkoshy
3618145256Sjkoshy		if (p->p_flag & P_WEXIT)
3619145256Sjkoshy			error = ESRCH;
3620145256Sjkoshy
3621145256Sjkoshy		PROC_UNLOCK(p);	/* pfind() returns a locked process */
3622145256Sjkoshy
3623145256Sjkoshy		if (error == 0)
3624145256Sjkoshy			error = pmc_detach_process(p, pm);
3625145256Sjkoshy	}
3626145256Sjkoshy	break;
3627145256Sjkoshy
3628145256Sjkoshy
3629145256Sjkoshy	/*
3630147191Sjkoshy	 * Retrieve the MSR number associated with the counter
3631147191Sjkoshy	 * 'pmc_id'.  This allows processes to directly use RDPMC
3632147191Sjkoshy	 * instructions to read their PMCs, without the overhead of a
3633147191Sjkoshy	 * system call.
3634147191Sjkoshy	 */
3635147191Sjkoshy
3636147191Sjkoshy	case PMC_OP_PMCGETMSR:
3637147191Sjkoshy	{
3638184802Sjkoshy		int adjri, ri;
3639184802Sjkoshy		struct pmc *pm;
3640147191Sjkoshy		struct pmc_target *pt;
3641147191Sjkoshy		struct pmc_op_getmsr gm;
3642184802Sjkoshy		struct pmc_classdep *pcd;
3643147191Sjkoshy
3644147191Sjkoshy		PMC_DOWNGRADE_SX();
3645147191Sjkoshy
3646147191Sjkoshy		if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3647147191Sjkoshy			break;
3648147191Sjkoshy
3649147191Sjkoshy		if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3650147191Sjkoshy			break;
3651147191Sjkoshy
3652147191Sjkoshy		/*
3653147191Sjkoshy		 * The allocated PMC has to be a process virtual PMC,
3654147191Sjkoshy		 * i.e., of type MODE_T[CS].  Global PMCs can only be
3655147191Sjkoshy		 * read using the PMCREAD operation since they may be
3656147191Sjkoshy		 * allocated on a different CPU than the one we could
3657147191Sjkoshy		 * be running on at the time of the RDPMC instruction.
3658147191Sjkoshy		 *
3659147191Sjkoshy		 * The GETMSR operation is not allowed for PMCs that
3660147191Sjkoshy		 * are inherited across processes.
3661147191Sjkoshy		 */
3662147191Sjkoshy
3663147191Sjkoshy		if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3664147191Sjkoshy		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
3665147191Sjkoshy			error = EINVAL;
3666147191Sjkoshy			break;
3667147191Sjkoshy		}
3668147191Sjkoshy
3669147191Sjkoshy		/*
3670147191Sjkoshy		 * It only makes sense to use a RDPMC (or its
3671147191Sjkoshy		 * equivalent instruction on non-x86 architectures) on
3672147191Sjkoshy		 * a process that has allocated and attached a PMC to
3673147191Sjkoshy		 * itself.  Conversely the PMC is only allowed to have
3674147191Sjkoshy		 * one process attached to it -- its owner.
3675147191Sjkoshy		 */
3676147191Sjkoshy
3677147191Sjkoshy		if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3678147191Sjkoshy		    LIST_NEXT(pt, pt_next) != NULL ||
3679147191Sjkoshy		    pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3680147191Sjkoshy			error = EINVAL;
3681147191Sjkoshy			break;
3682147191Sjkoshy		}
3683147191Sjkoshy
3684147191Sjkoshy		ri = PMC_TO_ROWINDEX(pm);
3685184802Sjkoshy		pcd = pmc_ri_to_classdep(md, ri, &adjri);
3686147191Sjkoshy
3687184802Sjkoshy		/* PMC class has no 'GETMSR' support */
3688184802Sjkoshy		if (pcd->pcd_get_msr == NULL) {
3689184802Sjkoshy			error = ENOSYS;
3690147191Sjkoshy			break;
3691184802Sjkoshy		}
3692147191Sjkoshy
3693184802Sjkoshy		if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
3694184802Sjkoshy			break;
3695184802Sjkoshy
3696147191Sjkoshy		if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3697147191Sjkoshy			break;
3698147191Sjkoshy
3699147191Sjkoshy		/*
3700147191Sjkoshy		 * Mark our process as using MSRs.  Update machine
3701147191Sjkoshy		 * state using a forced context switch.
3702147191Sjkoshy		 */
3703147191Sjkoshy
3704147191Sjkoshy		pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3705147191Sjkoshy		pmc_force_context_switch();
3706147191Sjkoshy
3707147191Sjkoshy	}
3708147191Sjkoshy	break;
3709147191Sjkoshy
3710147191Sjkoshy	/*
3711145256Sjkoshy	 * Release an allocated PMC
3712145256Sjkoshy	 */
3713145256Sjkoshy
3714145256Sjkoshy	case PMC_OP_PMCRELEASE:
3715145256Sjkoshy	{
3716145256Sjkoshy		pmc_id_t pmcid;
3717145256Sjkoshy		struct pmc *pm;
3718145256Sjkoshy		struct pmc_owner *po;
3719145256Sjkoshy		struct pmc_op_simple sp;
3720145256Sjkoshy
3721145256Sjkoshy		/*
3722145256Sjkoshy		 * Find PMC pointer for the named PMC.
3723145256Sjkoshy		 *
3724145256Sjkoshy		 * Use pmc_release_pmc_descriptor() to switch off the
3725145256Sjkoshy		 * PMC, remove all its target threads, and remove the
3726145256Sjkoshy		 * PMC from its owner's list.
3727145256Sjkoshy		 *
3728145256Sjkoshy		 * Remove the owner record if this is the last PMC
3729145256Sjkoshy		 * owned.
3730145256Sjkoshy		 *
3731145256Sjkoshy		 * Free up space.
3732145256Sjkoshy		 */
3733145256Sjkoshy
3734145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3735145256Sjkoshy			break;
3736145256Sjkoshy
3737145256Sjkoshy		pmcid = sp.pm_pmcid;
3738145256Sjkoshy
3739145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3740145256Sjkoshy			break;
3741145256Sjkoshy
3742145256Sjkoshy		po = pm->pm_owner;
3743145256Sjkoshy		pmc_release_pmc_descriptor(pm);
3744145256Sjkoshy		pmc_maybe_remove_owner(po);
3745273236Smarkj		pmc_destroy_pmc_descriptor(pm);
3746145256Sjkoshy	}
3747145256Sjkoshy	break;
3748145256Sjkoshy
3749145256Sjkoshy
3750145256Sjkoshy	/*
3751145256Sjkoshy	 * Read and/or write a PMC.
3752145256Sjkoshy	 */
3753145256Sjkoshy
3754145256Sjkoshy	case PMC_OP_PMCRW:
3755145256Sjkoshy	{
3756184802Sjkoshy		int adjri;
3757184802Sjkoshy		struct pmc *pm;
3758145256Sjkoshy		uint32_t cpu, ri;
3759184802Sjkoshy		pmc_value_t oldvalue;
3760184802Sjkoshy		struct pmc_binding pb;
3761184802Sjkoshy		struct pmc_op_pmcrw prw;
3762184802Sjkoshy		struct pmc_classdep *pcd;
3763145256Sjkoshy		struct pmc_op_pmcrw *pprw;
3764145256Sjkoshy
3765145256Sjkoshy		PMC_DOWNGRADE_SX();
3766145256Sjkoshy
3767145256Sjkoshy		if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3768145256Sjkoshy			break;
3769145256Sjkoshy
3770145301Simp		ri = 0;
3771282658Sjhb		PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3772145256Sjkoshy		    prw.pm_flags);
3773145256Sjkoshy
3774145256Sjkoshy		/* must have at least one flag set */
3775145256Sjkoshy		if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3776145256Sjkoshy			error = EINVAL;
3777145256Sjkoshy			break;
3778145256Sjkoshy		}
3779145256Sjkoshy
3780145256Sjkoshy		/* locate pmc descriptor */
3781145256Sjkoshy		if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3782145256Sjkoshy			break;
3783145256Sjkoshy
3784145256Sjkoshy		/* Can't read a PMC that hasn't been started. */
3785145256Sjkoshy		if (pm->pm_state != PMC_STATE_ALLOCATED &&
3786145256Sjkoshy		    pm->pm_state != PMC_STATE_STOPPED &&
3787145256Sjkoshy		    pm->pm_state != PMC_STATE_RUNNING) {
3788145256Sjkoshy			error = EINVAL;
3789145256Sjkoshy			break;
3790145256Sjkoshy		}
3791145256Sjkoshy
3792145256Sjkoshy		/* writing a new value is allowed only for 'STOPPED' pmcs */
3793145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING &&
3794145256Sjkoshy		    (prw.pm_flags & PMC_F_NEWVALUE)) {
3795145256Sjkoshy			error = EBUSY;
3796145256Sjkoshy			break;
3797145256Sjkoshy		}
3798145256Sjkoshy
3799145774Sjkoshy		if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3800145256Sjkoshy
3801145774Sjkoshy			/*
3802145774Sjkoshy			 * If this PMC is attached to its owner (i.e.,
3803145774Sjkoshy			 * the process requesting this operation) and
3804145774Sjkoshy			 * is running, then attempt to get an
3805145774Sjkoshy			 * upto-date reading from hardware for a READ.
3806145774Sjkoshy			 * Writes are only allowed when the PMC is
3807145774Sjkoshy			 * stopped, so only update the saved value
3808145774Sjkoshy			 * field.
3809145774Sjkoshy			 *
3810145774Sjkoshy			 * If the PMC is not running, or is not
3811145774Sjkoshy			 * attached to its owner, read/write to the
3812145774Sjkoshy			 * savedvalue field.
3813145774Sjkoshy			 */
3814145774Sjkoshy
3815145774Sjkoshy			ri = PMC_TO_ROWINDEX(pm);
3816184802Sjkoshy			pcd = pmc_ri_to_classdep(md, ri, &adjri);
3817145774Sjkoshy
3818145256Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
3819145774Sjkoshy			cpu = curthread->td_oncpu;
3820145774Sjkoshy
3821145774Sjkoshy			if (prw.pm_flags & PMC_F_OLDVALUE) {
3822145774Sjkoshy				if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3823145774Sjkoshy				    (pm->pm_state == PMC_STATE_RUNNING))
3824184802Sjkoshy					error = (*pcd->pcd_read_pmc)(cpu, adjri,
3825145774Sjkoshy					    &oldvalue);
3826145774Sjkoshy				else
3827145774Sjkoshy					oldvalue = pm->pm_gv.pm_savedvalue;
3828145774Sjkoshy			}
3829145256Sjkoshy			if (prw.pm_flags & PMC_F_NEWVALUE)
3830145256Sjkoshy				pm->pm_gv.pm_savedvalue = prw.pm_value;
3831145774Sjkoshy
3832145256Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
3833145256Sjkoshy
3834145256Sjkoshy		} else { /* System mode PMCs */
3835145774Sjkoshy			cpu = PMC_TO_CPU(pm);
3836145774Sjkoshy			ri  = PMC_TO_ROWINDEX(pm);
3837184802Sjkoshy			pcd = pmc_ri_to_classdep(md, ri, &adjri);
3838145256Sjkoshy
3839183266Sjkoshy			if (!pmc_cpu_is_active(cpu)) {
3840145256Sjkoshy				error = ENXIO;
3841145256Sjkoshy				break;
3842145256Sjkoshy			}
3843145256Sjkoshy
3844145256Sjkoshy			/* move this thread to CPU 'cpu' */
3845145256Sjkoshy			pmc_save_cpu_binding(&pb);
3846145256Sjkoshy			pmc_select_cpu(cpu);
3847145256Sjkoshy
3848145774Sjkoshy			critical_enter();
3849145256Sjkoshy			/* save old value */
3850145256Sjkoshy			if (prw.pm_flags & PMC_F_OLDVALUE)
3851184802Sjkoshy				if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
3852145256Sjkoshy					 &oldvalue)))
3853145256Sjkoshy					goto error;
3854145256Sjkoshy			/* write out new value */
3855145256Sjkoshy			if (prw.pm_flags & PMC_F_NEWVALUE)
3856184802Sjkoshy				error = (*pcd->pcd_write_pmc)(cpu, adjri,
3857145256Sjkoshy				    prw.pm_value);
3858145256Sjkoshy		error:
3859145774Sjkoshy			critical_exit();
3860145256Sjkoshy			pmc_restore_cpu_binding(&pb);
3861145256Sjkoshy			if (error)
3862145256Sjkoshy				break;
3863145256Sjkoshy		}
3864145256Sjkoshy
3865145256Sjkoshy		pprw = (struct pmc_op_pmcrw *) arg;
3866145256Sjkoshy
3867282641Sjhb#ifdef	HWPMC_DEBUG
3868145256Sjkoshy		if (prw.pm_flags & PMC_F_NEWVALUE)
3869282658Sjhb			PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3870145256Sjkoshy			    ri, prw.pm_value, oldvalue);
3871156778Sjkoshy		else if (prw.pm_flags & PMC_F_OLDVALUE)
3872282658Sjhb			PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3873145256Sjkoshy#endif
3874145256Sjkoshy
3875145256Sjkoshy		/* return old value if requested */
3876145256Sjkoshy		if (prw.pm_flags & PMC_F_OLDVALUE)
3877145256Sjkoshy			if ((error = copyout(&oldvalue, &pprw->pm_value,
3878145256Sjkoshy				 sizeof(prw.pm_value))))
3879145256Sjkoshy				break;
3880145256Sjkoshy
3881145256Sjkoshy	}
3882145256Sjkoshy	break;
3883145256Sjkoshy
3884145256Sjkoshy
3885145256Sjkoshy	/*
3886145256Sjkoshy	 * Set the sampling rate for a sampling mode PMC and the
3887145256Sjkoshy	 * initial count for a counting mode PMC.
3888145256Sjkoshy	 */
3889145256Sjkoshy
3890145256Sjkoshy	case PMC_OP_PMCSETCOUNT:
3891145256Sjkoshy	{
3892145256Sjkoshy		struct pmc *pm;
3893145256Sjkoshy		struct pmc_op_pmcsetcount sc;
3894145256Sjkoshy
3895145256Sjkoshy		PMC_DOWNGRADE_SX();
3896145256Sjkoshy
3897145256Sjkoshy		if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3898145256Sjkoshy			break;
3899145256Sjkoshy
3900145256Sjkoshy		if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3901145256Sjkoshy			break;
3902145256Sjkoshy
3903145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) {
3904145256Sjkoshy			error = EBUSY;
3905145256Sjkoshy			break;
3906145256Sjkoshy		}
3907145256Sjkoshy
3908145774Sjkoshy		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3909145256Sjkoshy			pm->pm_sc.pm_reloadcount = sc.pm_count;
3910145256Sjkoshy		else
3911145256Sjkoshy			pm->pm_sc.pm_initial = sc.pm_count;
3912145256Sjkoshy	}
3913145256Sjkoshy	break;
3914145256Sjkoshy
3915145256Sjkoshy
3916145256Sjkoshy	/*
3917145256Sjkoshy	 * Start a PMC.
3918145256Sjkoshy	 */
3919145256Sjkoshy
3920145256Sjkoshy	case PMC_OP_PMCSTART:
3921145256Sjkoshy	{
3922145256Sjkoshy		pmc_id_t pmcid;
3923145256Sjkoshy		struct pmc *pm;
3924145256Sjkoshy		struct pmc_op_simple sp;
3925145256Sjkoshy
3926145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3927145256Sjkoshy
3928145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3929145256Sjkoshy			break;
3930145256Sjkoshy
3931145256Sjkoshy		pmcid = sp.pm_pmcid;
3932145256Sjkoshy
3933145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3934145256Sjkoshy			break;
3935145256Sjkoshy
3936145774Sjkoshy		KASSERT(pmcid == pm->pm_id,
3937145774Sjkoshy		    ("[pmc,%d] pmcid %x != id %x", __LINE__,
3938145774Sjkoshy			pm->pm_id, pmcid));
3939145256Sjkoshy
3940145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3941145256Sjkoshy			break;
3942145256Sjkoshy		else if (pm->pm_state != PMC_STATE_STOPPED &&
3943145256Sjkoshy		    pm->pm_state != PMC_STATE_ALLOCATED) {
3944145256Sjkoshy			error = EINVAL;
3945145256Sjkoshy			break;
3946145256Sjkoshy		}
3947145256Sjkoshy
3948145256Sjkoshy		error = pmc_start(pm);
3949145256Sjkoshy	}
3950145256Sjkoshy	break;
3951145256Sjkoshy
3952145256Sjkoshy
3953145256Sjkoshy	/*
3954145256Sjkoshy	 * Stop a PMC.
3955145256Sjkoshy	 */
3956145256Sjkoshy
3957145256Sjkoshy	case PMC_OP_PMCSTOP:
3958145256Sjkoshy	{
3959145256Sjkoshy		pmc_id_t pmcid;
3960145256Sjkoshy		struct pmc *pm;
3961145256Sjkoshy		struct pmc_op_simple sp;
3962145256Sjkoshy
3963145256Sjkoshy		PMC_DOWNGRADE_SX();
3964145256Sjkoshy
3965145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3966145256Sjkoshy			break;
3967145256Sjkoshy
3968145256Sjkoshy		pmcid = sp.pm_pmcid;
3969145256Sjkoshy
3970145256Sjkoshy		/*
3971145256Sjkoshy		 * Mark the PMC as inactive and invoke the MD stop
3972145256Sjkoshy		 * routines if needed.
3973145256Sjkoshy		 */
3974145256Sjkoshy
3975145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3976145256Sjkoshy			break;
3977145256Sjkoshy
3978145774Sjkoshy		KASSERT(pmcid == pm->pm_id,
3979145774Sjkoshy		    ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3980145774Sjkoshy			pm->pm_id, pmcid));
3981145256Sjkoshy
3982145256Sjkoshy		if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3983145256Sjkoshy			break;
3984145256Sjkoshy		else if (pm->pm_state != PMC_STATE_RUNNING) {
3985145256Sjkoshy			error = EINVAL;
3986145256Sjkoshy			break;
3987145256Sjkoshy		}
3988145256Sjkoshy
3989145256Sjkoshy		error = pmc_stop(pm);
3990145256Sjkoshy	}
3991145256Sjkoshy	break;
3992145256Sjkoshy
3993145256Sjkoshy
3994145256Sjkoshy	/*
3995147867Sjkoshy	 * Write a user supplied value to the log file.
3996145256Sjkoshy	 */
3997145256Sjkoshy
3998145256Sjkoshy	case PMC_OP_WRITELOG:
3999145256Sjkoshy	{
4000147191Sjkoshy		struct pmc_op_writelog wl;
4001147191Sjkoshy		struct pmc_owner *po;
4002145256Sjkoshy
4003145256Sjkoshy		PMC_DOWNGRADE_SX();
4004145256Sjkoshy
4005147191Sjkoshy		if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
4006145256Sjkoshy			break;
4007145256Sjkoshy
4008147191Sjkoshy		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
4009145256Sjkoshy			error = EINVAL;
4010145256Sjkoshy			break;
4011145256Sjkoshy		}
4012145256Sjkoshy
4013147191Sjkoshy		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
4014145774Sjkoshy			error = EINVAL;
4015145774Sjkoshy			break;
4016145774Sjkoshy		}
4017145774Sjkoshy
4018147191Sjkoshy		error = pmclog_process_userlog(po, &wl);
4019145256Sjkoshy	}
4020145256Sjkoshy	break;
4021145256Sjkoshy
4022147191Sjkoshy
4023145256Sjkoshy	default:
4024145256Sjkoshy		error = EINVAL;
4025145256Sjkoshy		break;
4026145256Sjkoshy	}
4027145256Sjkoshy
4028195005Sattilio	if (is_sx_locked != 0) {
4029195005Sattilio		if (is_sx_downgraded)
4030195005Sattilio			sx_sunlock(&pmc_sx);
4031195005Sattilio		else
4032195005Sattilio			sx_xunlock(&pmc_sx);
4033195005Sattilio	}
4034145256Sjkoshy
4035145256Sjkoshy	if (error)
4036145256Sjkoshy		atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
4037145256Sjkoshy
4038147191Sjkoshy	PICKUP_GIANT();
4039147191Sjkoshy
4040145256Sjkoshy	return error;
4041145256Sjkoshy}
4042145256Sjkoshy
4043145256Sjkoshy/*
4044145256Sjkoshy * Helper functions
4045145256Sjkoshy */
4046145256Sjkoshy
4047147191Sjkoshy
4048145256Sjkoshy/*
4049174395Sjkoshy * Mark the thread as needing callchain capture and post an AST.  The
4050174395Sjkoshy * actual callchain capture will be done in a context where it is safe
4051174395Sjkoshy * to take page faults.
4052174395Sjkoshy */
4053174395Sjkoshy
4054174395Sjkoshystatic void
4055186037Sjkoshypmc_post_callchain_callback(void)
4056174395Sjkoshy{
4057174395Sjkoshy	struct thread *td;
4058174395Sjkoshy
4059174395Sjkoshy	td = curthread;
4060174395Sjkoshy
4061205998Sfabient	/*
4062205998Sfabient	 * If there is multiple PMCs for the same interrupt ignore new post
4063205998Sfabient	 */
4064205998Sfabient	if (td->td_pflags & TDP_CALLCHAIN)
4065205998Sfabient		return;
4066186037Sjkoshy
4067174395Sjkoshy	/*
4068186037Sjkoshy	 * Mark this thread as needing callchain capture.
4069186037Sjkoshy	 * `td->td_pflags' will be safe to touch because this thread
4070186037Sjkoshy	 * was in user space when it was interrupted.
4071174395Sjkoshy	 */
4072174395Sjkoshy	td->td_pflags |= TDP_CALLCHAIN;
4073174395Sjkoshy
4074174395Sjkoshy	/*
4075186037Sjkoshy	 * Don't let this thread migrate between CPUs until callchain
4076186037Sjkoshy	 * capture completes.
4077174395Sjkoshy	 */
4078186037Sjkoshy	sched_pin();
4079174395Sjkoshy
4080174395Sjkoshy	return;
4081174395Sjkoshy}
4082174395Sjkoshy
4083174395Sjkoshy/*
4084147191Sjkoshy * Interrupt processing.
4085147191Sjkoshy *
4086174395Sjkoshy * Find a free slot in the per-cpu array of samples and capture the
4087174395Sjkoshy * current callchain there.  If a sample was successfully added, a bit
4088174395Sjkoshy * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4089174395Sjkoshy * needs to be invoked from the clock handler.
4090147191Sjkoshy *
4091147191Sjkoshy * This function is meant to be called from an NMI handler.  It cannot
4092147191Sjkoshy * use any of the locking primitives supplied by the OS.
4093145256Sjkoshy */
4094145256Sjkoshy
4095147191Sjkoshyint
4096233628Sfabientpmc_process_interrupt(int cpu, int ring, struct pmc *pm, struct trapframe *tf,
4097174395Sjkoshy    int inuserspace)
4098145256Sjkoshy{
4099174395Sjkoshy	int error, callchaindepth;
4100147191Sjkoshy	struct thread *td;
4101147191Sjkoshy	struct pmc_sample *ps;
4102147191Sjkoshy	struct pmc_samplebuffer *psb;
4103145256Sjkoshy
4104147191Sjkoshy	error = 0;
4105145256Sjkoshy
4106174395Sjkoshy	/*
4107174395Sjkoshy	 * Allocate space for a sample buffer.
4108174395Sjkoshy	 */
4109233628Sfabient	psb = pmc_pcpu[cpu]->pc_sb[ring];
4110145256Sjkoshy
4111147191Sjkoshy	ps = psb->ps_write;
4112174395Sjkoshy	if (ps->ps_nsamples) {	/* in use, reader hasn't caught up */
4113290811Sjtl		CPU_SET_ATOMIC(cpu, &pm->pm_stalled);
4114147191Sjkoshy		atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
4115282658Sjhb		PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
4116174395Sjkoshy		    cpu, pm, (void *) tf, inuserspace,
4117147191Sjkoshy		    (int) (psb->ps_write - psb->ps_samples),
4118147191Sjkoshy		    (int) (psb->ps_read - psb->ps_samples));
4119290813Sjtl		callchaindepth = 1;
4120147191Sjkoshy		error = ENOMEM;
4121147191Sjkoshy		goto done;
4122147191Sjkoshy	}
4123145256Sjkoshy
4124174395Sjkoshy
4125174395Sjkoshy	/* Fill in entry. */
4126282658Sjhb	PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
4127174395Sjkoshy	    (void *) tf, inuserspace,
4128147191Sjkoshy	    (int) (psb->ps_write - psb->ps_samples),
4129147191Sjkoshy	    (int) (psb->ps_read - psb->ps_samples));
4130145256Sjkoshy
4131186037Sjkoshy	KASSERT(pm->pm_runcount >= 0,
4132186037Sjkoshy	    ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4133186037Sjkoshy		pm->pm_runcount));
4134186037Sjkoshy
4135208861Sfabient	atomic_add_rel_int(&pm->pm_runcount, 1);	/* hold onto PMC */
4136233628Sfabient
4137147191Sjkoshy	ps->ps_pmc = pm;
4138147191Sjkoshy	if ((td = curthread) && td->td_proc)
4139147191Sjkoshy		ps->ps_pid = td->td_proc->p_pid;
4140147191Sjkoshy	else
4141147191Sjkoshy		ps->ps_pid = -1;
4142174395Sjkoshy	ps->ps_cpu = cpu;
4143186037Sjkoshy	ps->ps_td = td;
4144174395Sjkoshy	ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4145145256Sjkoshy
4146174395Sjkoshy	callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4147174395Sjkoshy	    pmc_callchaindepth : 1;
4148174395Sjkoshy
4149174395Sjkoshy	if (callchaindepth == 1)
4150174395Sjkoshy		ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
4151174395Sjkoshy	else {
4152174395Sjkoshy		/*
4153174395Sjkoshy		 * Kernel stack traversals can be done immediately,
4154174395Sjkoshy		 * while we defer to an AST for user space traversals.
4155174395Sjkoshy		 */
4156233628Sfabient		if (!inuserspace) {
4157174395Sjkoshy			callchaindepth =
4158174395Sjkoshy			    pmc_save_kernel_callchain(ps->ps_pc,
4159174395Sjkoshy				callchaindepth, tf);
4160233628Sfabient		} else {
4161186037Sjkoshy			pmc_post_callchain_callback();
4162174395Sjkoshy			callchaindepth = PMC_SAMPLE_INUSE;
4163174395Sjkoshy		}
4164174395Sjkoshy	}
4165174395Sjkoshy
4166174395Sjkoshy	ps->ps_nsamples = callchaindepth;	/* mark entry as in use */
4167174395Sjkoshy
4168147191Sjkoshy	/* increment write pointer, modulo ring buffer size */
4169147191Sjkoshy	ps++;
4170147191Sjkoshy	if (ps == psb->ps_fence)
4171147191Sjkoshy		psb->ps_write = psb->ps_samples;
4172147191Sjkoshy	else
4173147191Sjkoshy		psb->ps_write = ps;
4174145256Sjkoshy
4175147191Sjkoshy done:
4176147191Sjkoshy	/* mark CPU as needing processing */
4177290813Sjtl	if (callchaindepth != PMC_SAMPLE_INUSE)
4178290813Sjtl		CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4179147191Sjkoshy
4180174395Sjkoshy	return (error);
4181145256Sjkoshy}
4182145256Sjkoshy
4183174395Sjkoshy/*
4184174395Sjkoshy * Capture a user call chain.  This function will be called from ast()
4185174395Sjkoshy * before control returns to userland and before the process gets
4186174395Sjkoshy * rescheduled.
4187174395Sjkoshy */
4188147191Sjkoshy
4189174395Sjkoshystatic void
4190233628Sfabientpmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4191174395Sjkoshy{
4192174395Sjkoshy	struct pmc *pm;
4193186037Sjkoshy	struct thread *td;
4194290813Sjtl	struct pmc_sample *ps, *ps_end;
4195174395Sjkoshy	struct pmc_samplebuffer *psb;
4196186037Sjkoshy#ifdef	INVARIANTS
4197186037Sjkoshy	int ncallchains;
4198186037Sjkoshy#endif
4199174395Sjkoshy
4200233628Sfabient	psb = pmc_pcpu[cpu]->pc_sb[ring];
4201186037Sjkoshy	td = curthread;
4202174395Sjkoshy
4203186037Sjkoshy	KASSERT(td->td_pflags & TDP_CALLCHAIN,
4204186037Sjkoshy	    ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
4205186037Sjkoshy		__LINE__));
4206186037Sjkoshy
4207186037Sjkoshy#ifdef	INVARIANTS
4208186037Sjkoshy	ncallchains = 0;
4209186037Sjkoshy#endif
4210186037Sjkoshy
4211174395Sjkoshy	/*
4212174395Sjkoshy	 * Iterate through all deferred callchain requests.
4213290813Sjtl	 * Walk from the current read pointer to the current
4214290813Sjtl	 * write pointer.
4215174395Sjkoshy	 */
4216174395Sjkoshy
4217290813Sjtl	ps = psb->ps_read;
4218290813Sjtl	ps_end = psb->ps_write;
4219290813Sjtl	do {
4220174395Sjkoshy		if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
4221290813Sjtl			goto next;
4222186037Sjkoshy		if (ps->ps_td != td)
4223290813Sjtl			goto next;
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
4249290813Sjtlnext:
4250290813Sjtl		/* increment the pointer, modulo sample ring size */
4251290813Sjtl		if (++ps == psb->ps_fence)
4252290813Sjtl			ps = psb->ps_samples;
4253290813Sjtl	} while (ps != ps_end);
4254290813Sjtl
4255186037Sjkoshy	KASSERT(ncallchains > 0,
4256186037Sjkoshy	    ("[pmc,%d] cpu %d didn't find a sample to collect", __LINE__,
4257186037Sjkoshy		cpu));
4258186037Sjkoshy
4259242361Sattilio	KASSERT(td->td_pinned == 1,
4260233628Sfabient	    ("[pmc,%d] invalid td_pinned value", __LINE__));
4261233628Sfabient	sched_unpin();	/* Can migrate safely now. */
4262233628Sfabient
4263290813Sjtl	/* mark CPU as needing processing */
4264290813Sjtl	CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4265290813Sjtl
4266174395Sjkoshy	return;
4267174395Sjkoshy}
4268174395Sjkoshy
4269145256Sjkoshy/*
4270147191Sjkoshy * Process saved PC samples.
4271145256Sjkoshy */
4272145256Sjkoshy
4273145256Sjkoshystatic void
4274233628Sfabientpmc_process_samples(int cpu, int ring)
4275145256Sjkoshy{
4276147191Sjkoshy	struct pmc *pm;
4277185363Sjkoshy	int adjri, n;
4278147191Sjkoshy	struct thread *td;
4279147191Sjkoshy	struct pmc_owner *po;
4280147191Sjkoshy	struct pmc_sample *ps;
4281184802Sjkoshy	struct pmc_classdep *pcd;
4282147191Sjkoshy	struct pmc_samplebuffer *psb;
4283145256Sjkoshy
4284147191Sjkoshy	KASSERT(PCPU_GET(cpuid) == cpu,
4285147191Sjkoshy	    ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4286147191Sjkoshy		PCPU_GET(cpuid), cpu));
4287145256Sjkoshy
4288233628Sfabient	psb = pmc_pcpu[cpu]->pc_sb[ring];
4289147191Sjkoshy
4290147191Sjkoshy	for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
4291147191Sjkoshy
4292147191Sjkoshy		ps = psb->ps_read;
4293174395Sjkoshy		if (ps->ps_nsamples == PMC_SAMPLE_FREE)
4294147191Sjkoshy			break;
4295147191Sjkoshy
4296147191Sjkoshy		pm = ps->ps_pmc;
4297186037Sjkoshy
4298186037Sjkoshy		KASSERT(pm->pm_runcount > 0,
4299186037Sjkoshy		    ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4300186037Sjkoshy			pm->pm_runcount));
4301186037Sjkoshy
4302147191Sjkoshy		po = pm->pm_owner;
4303147191Sjkoshy
4304147191Sjkoshy		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4305147191Sjkoshy		    ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4306147191Sjkoshy			pm, PMC_TO_MODE(pm)));
4307147191Sjkoshy
4308147191Sjkoshy		/* Ignore PMCs that have been switched off */
4309147191Sjkoshy		if (pm->pm_state != PMC_STATE_RUNNING)
4310147191Sjkoshy			goto entrydone;
4311147191Sjkoshy
4312233628Sfabient		/* If there is a pending AST wait for completion */
4313233628Sfabient		if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
4314233628Sfabient			/* Need a rescan at a later time. */
4315233628Sfabient			CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4316233628Sfabient			break;
4317233628Sfabient		}
4318233628Sfabient
4319282658Sjhb		PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4320174395Sjkoshy		    pm, ps->ps_nsamples, ps->ps_flags,
4321147191Sjkoshy		    (int) (psb->ps_write - psb->ps_samples),
4322147191Sjkoshy		    (int) (psb->ps_read - psb->ps_samples));
4323147191Sjkoshy
4324147191Sjkoshy		/*
4325147191Sjkoshy		 * If this is a process-mode PMC that is attached to
4326147191Sjkoshy		 * its owner, and if the PC is in user mode, update
4327147191Sjkoshy		 * profiling statistics like timer-based profiling
4328147191Sjkoshy		 * would have done.
4329147191Sjkoshy		 */
4330147191Sjkoshy		if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4331174395Sjkoshy			if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4332147191Sjkoshy				td = FIRST_THREAD_IN_PROC(po->po_owner);
4333174395Sjkoshy				addupc_intr(td, ps->ps_pc[0], 1);
4334147191Sjkoshy			}
4335147191Sjkoshy			goto entrydone;
4336147191Sjkoshy		}
4337147191Sjkoshy
4338147191Sjkoshy		/*
4339147191Sjkoshy		 * Otherwise, this is either a sampling mode PMC that
4340147191Sjkoshy		 * is attached to a different process than its owner,
4341147191Sjkoshy		 * or a system-wide sampling PMC.  Dispatch a log
4342147191Sjkoshy		 * entry to the PMC's owner process.
4343147191Sjkoshy		 */
4344174395Sjkoshy		pmclog_process_callchain(pm, ps);
4345147191Sjkoshy
4346147191Sjkoshy	entrydone:
4347233628Sfabient		ps->ps_nsamples = 0; /* mark entry as free */
4348208861Sfabient		atomic_subtract_rel_int(&pm->pm_runcount, 1);
4349147191Sjkoshy
4350147191Sjkoshy		/* increment read pointer, modulo sample size */
4351147191Sjkoshy		if (++ps == psb->ps_fence)
4352147191Sjkoshy			psb->ps_read = psb->ps_samples;
4353147191Sjkoshy		else
4354147191Sjkoshy			psb->ps_read = ps;
4355147191Sjkoshy	}
4356147191Sjkoshy
4357147191Sjkoshy	atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
4358147191Sjkoshy
4359147191Sjkoshy	/* Do not re-enable stalled PMCs if we failed to process any samples */
4360147191Sjkoshy	if (n == 0)
4361147191Sjkoshy		return;
4362147191Sjkoshy
4363147191Sjkoshy	/*
4364147191Sjkoshy	 * Restart any stalled sampling PMCs on this CPU.
4365147191Sjkoshy	 *
4366147867Sjkoshy	 * If the NMI handler sets the pm_stalled field of a PMC after
4367147867Sjkoshy	 * the check below, we'll end up processing the stalled PMC at
4368147867Sjkoshy	 * the next hardclock tick.
4369147191Sjkoshy	 */
4370147191Sjkoshy	for (n = 0; n < md->pmd_npmc; n++) {
4371184802Sjkoshy		pcd = pmc_ri_to_classdep(md, n, &adjri);
4372184802Sjkoshy		KASSERT(pcd != NULL,
4373184802Sjkoshy		    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4374184802Sjkoshy		(void) (*pcd->pcd_get_config)(cpu,adjri,&pm);
4375184802Sjkoshy
4376147191Sjkoshy		if (pm == NULL ||			 /* !cfg'ed */
4377147191Sjkoshy		    pm->pm_state != PMC_STATE_RUNNING || /* !active */
4378147191Sjkoshy		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4379290811Sjtl		    !CPU_ISSET(cpu, &pm->pm_cpustate) || /* !desired */
4380290811Sjtl		    !CPU_ISSET(cpu, &pm->pm_stalled)) /* !stalled */
4381147191Sjkoshy			continue;
4382147191Sjkoshy
4383290811Sjtl		CPU_CLR_ATOMIC(cpu, &pm->pm_stalled);
4384184802Sjkoshy		(*pcd->pcd_start_pmc)(cpu, adjri);
4385147191Sjkoshy	}
4386145256Sjkoshy}
4387145256Sjkoshy
4388145256Sjkoshy/*
4389145256Sjkoshy * Event handlers.
4390145256Sjkoshy */
4391145256Sjkoshy
4392145256Sjkoshy/*
4393145256Sjkoshy * Handle a process exit.
4394145256Sjkoshy *
4395147191Sjkoshy * Remove this process from all hash tables.  If this process
4396147191Sjkoshy * owned any PMCs, turn off those PMCs and deallocate them,
4397147191Sjkoshy * removing any associations with target processes.
4398147191Sjkoshy *
4399147191Sjkoshy * This function will be called by the last 'thread' of a
4400147191Sjkoshy * process.
4401147191Sjkoshy *
4402145256Sjkoshy * XXX This eventhandler gets called early in the exit process.
4403145256Sjkoshy * Consider using a 'hook' invocation from thread_exit() or equivalent
4404145256Sjkoshy * spot.  Another negative is that kse_exit doesn't seem to call
4405145256Sjkoshy * exit1() [??].
4406147191Sjkoshy *
4407145256Sjkoshy */
4408145256Sjkoshy
4409145256Sjkoshystatic void
4410145256Sjkoshypmc_process_exit(void *arg __unused, struct proc *p)
4411145256Sjkoshy{
4412184802Sjkoshy	struct pmc *pm;
4413184802Sjkoshy	int adjri, cpu;
4414184802Sjkoshy	unsigned int ri;
4415145256Sjkoshy	int is_using_hwpmcs;
4416184802Sjkoshy	struct pmc_owner *po;
4417147191Sjkoshy	struct pmc_process *pp;
4418184802Sjkoshy	struct pmc_classdep *pcd;
4419147191Sjkoshy	pmc_value_t newvalue, tmp;
4420145256Sjkoshy
4421145256Sjkoshy	PROC_LOCK(p);
4422145256Sjkoshy	is_using_hwpmcs = p->p_flag & P_HWPMC;
4423145256Sjkoshy	PROC_UNLOCK(p);
4424145256Sjkoshy
4425147191Sjkoshy	/*
4426147191Sjkoshy	 * Log a sysexit event to all SS PMC owners.
4427147191Sjkoshy	 */
4428147191Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4429147191Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4430147191Sjkoshy		    pmclog_process_sysexit(po, p->p_pid);
4431145256Sjkoshy
4432147191Sjkoshy	if (!is_using_hwpmcs)
4433147191Sjkoshy		return;
4434147191Sjkoshy
4435147191Sjkoshy	PMC_GET_SX_XLOCK();
4436282658Sjhb	PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4437147191Sjkoshy	    p->p_comm);
4438147191Sjkoshy
4439147191Sjkoshy	/*
4440147191Sjkoshy	 * Since this code is invoked by the last thread in an exiting
4441147191Sjkoshy	 * process, we would have context switched IN at some prior
4442147191Sjkoshy	 * point.  However, with PREEMPTION, kernel mode context
4443147191Sjkoshy	 * switches may happen any time, so we want to disable a
4444298931Spfg	 * context switch OUT till we get any PMCs targeting this
4445147191Sjkoshy	 * process off the hardware.
4446147191Sjkoshy	 *
4447147191Sjkoshy	 * We also need to atomically remove this process'
4448147191Sjkoshy	 * entry from our target process hash table, using
4449147191Sjkoshy	 * PMC_FLAG_REMOVE.
4450147191Sjkoshy	 */
4451282658Sjhb	PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4452147191Sjkoshy	    p->p_comm);
4453147191Sjkoshy
4454147191Sjkoshy	critical_enter(); /* no preemption */
4455147191Sjkoshy
4456147191Sjkoshy	cpu = curthread->td_oncpu;
4457147191Sjkoshy
4458147191Sjkoshy	if ((pp = pmc_find_process_descriptor(p,
4459147191Sjkoshy		 PMC_FLAG_REMOVE)) != NULL) {
4460147191Sjkoshy
4461282658Sjhb		PMCDBG2(PRC,EXT,2,
4462147191Sjkoshy		    "process-exit proc=%p pmc-process=%p", p, pp);
4463147191Sjkoshy
4464147191Sjkoshy		/*
4465147191Sjkoshy		 * The exiting process could the target of
4466147191Sjkoshy		 * some PMCs which will be running on
4467147191Sjkoshy		 * currently executing CPU.
4468147191Sjkoshy		 *
4469147191Sjkoshy		 * We need to turn these PMCs off like we
4470147191Sjkoshy		 * would do at context switch OUT time.
4471147191Sjkoshy		 */
4472147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++) {
4473147191Sjkoshy
4474147191Sjkoshy			/*
4475147191Sjkoshy			 * Pick up the pmc pointer from hardware
4476147191Sjkoshy			 * state similar to the CSW_OUT code.
4477147191Sjkoshy			 */
4478147191Sjkoshy			pm = NULL;
4479147191Sjkoshy
4480184802Sjkoshy			pcd = pmc_ri_to_classdep(md, ri, &adjri);
4481184802Sjkoshy
4482184802Sjkoshy			(void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
4483184802Sjkoshy
4484282658Sjhb			PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4485147191Sjkoshy
4486147191Sjkoshy			if (pm == NULL ||
4487147191Sjkoshy			    !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4488147191Sjkoshy				continue;
4489147191Sjkoshy
4490282658Sjhb			PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4491147191Sjkoshy			    "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4492147191Sjkoshy			    pm, pm->pm_state);
4493147191Sjkoshy
4494147191Sjkoshy			KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4495147191Sjkoshy			    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4496147191Sjkoshy				__LINE__, PMC_TO_ROWINDEX(pm), ri));
4497147191Sjkoshy
4498147191Sjkoshy			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4499147191Sjkoshy			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4500147191Sjkoshy				__LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4501147191Sjkoshy
4502147191Sjkoshy			KASSERT(pm->pm_runcount > 0,
4503147191Sjkoshy			    ("[pmc,%d] bad runcount ri %d rc %d",
4504147191Sjkoshy				__LINE__, ri, pm->pm_runcount));
4505147191Sjkoshy
4506290811Sjtl			/*
4507290811Sjtl			 * Change desired state, and then stop if not
4508290811Sjtl			 * stalled. This two-step dance should avoid
4509290811Sjtl			 * race conditions where an interrupt re-enables
4510290811Sjtl			 * the PMC after this code has already checked
4511290811Sjtl			 * the pm_stalled flag.
4512290811Sjtl			 */
4513290811Sjtl			if (CPU_ISSET(cpu, &pm->pm_cpustate)) {
4514290811Sjtl				CPU_CLR_ATOMIC(cpu, &pm->pm_cpustate);
4515290811Sjtl				if (!CPU_ISSET(cpu, &pm->pm_stalled)) {
4516290811Sjtl					(void) pcd->pcd_stop_pmc(cpu, adjri);
4517290811Sjtl					pcd->pcd_read_pmc(cpu, adjri,
4518290811Sjtl					    &newvalue);
4519290811Sjtl					tmp = newvalue -
4520290811Sjtl					    PMC_PCPU_SAVED(cpu,ri);
4521147191Sjkoshy
4522290811Sjtl					mtx_pool_lock_spin(pmc_mtxpool, pm);
4523290811Sjtl					pm->pm_gv.pm_savedvalue += tmp;
4524290811Sjtl					pp->pp_pmcs[ri].pp_pmcval += tmp;
4525290811Sjtl					mtx_pool_unlock_spin(pmc_mtxpool, pm);
4526290811Sjtl				}
4527147191Sjkoshy			}
4528147191Sjkoshy
4529208861Sfabient			atomic_subtract_rel_int(&pm->pm_runcount,1);
4530147191Sjkoshy
4531147191Sjkoshy			KASSERT((int) pm->pm_runcount >= 0,
4532147191Sjkoshy			    ("[pmc,%d] runcount is %d", __LINE__, ri));
4533147191Sjkoshy
4534184802Sjkoshy			(void) pcd->pcd_config_pmc(cpu, adjri, NULL);
4535147191Sjkoshy		}
4536147191Sjkoshy
4537147191Sjkoshy		/*
4538147191Sjkoshy		 * Inform the MD layer of this pseudo "context switch
4539147191Sjkoshy		 * out"
4540147191Sjkoshy		 */
4541147191Sjkoshy		(void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
4542147191Sjkoshy
4543147191Sjkoshy		critical_exit(); /* ok to be pre-empted now */
4544147191Sjkoshy
4545147191Sjkoshy		/*
4546147191Sjkoshy		 * Unlink this process from the PMCs that are
4547298931Spfg		 * targeting it.  This will send a signal to
4548147191Sjkoshy		 * all PMC owner's whose PMCs are orphaned.
4549147191Sjkoshy		 *
4550147191Sjkoshy		 * Log PMC value at exit time if requested.
4551147191Sjkoshy		 */
4552147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
4553147191Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
4554147867Sjkoshy				if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
4555147867Sjkoshy				    PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
4556147191Sjkoshy					pmclog_process_procexit(pm, pp);
4557147191Sjkoshy				pmc_unlink_target_process(pm, pp);
4558147191Sjkoshy			}
4559184205Sdes		free(pp, M_PMC);
4560147191Sjkoshy
4561147191Sjkoshy	} else
4562147191Sjkoshy		critical_exit(); /* pp == NULL */
4563147191Sjkoshy
4564147191Sjkoshy
4565147191Sjkoshy	/*
4566147191Sjkoshy	 * If the process owned PMCs, free them up and free up
4567147191Sjkoshy	 * memory.
4568147191Sjkoshy	 */
4569147191Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
4570147191Sjkoshy		pmc_remove_owner(po);
4571147191Sjkoshy		pmc_destroy_owner_descriptor(po);
4572145256Sjkoshy	}
4573147191Sjkoshy
4574147191Sjkoshy	sx_xunlock(&pmc_sx);
4575145256Sjkoshy}
4576145256Sjkoshy
4577145256Sjkoshy/*
4578145256Sjkoshy * Handle a process fork.
4579145256Sjkoshy *
4580145256Sjkoshy * If the parent process 'p1' is under HWPMC monitoring, then copy
4581145256Sjkoshy * over any attached PMCs that have 'do_descendants' semantics.
4582145256Sjkoshy */
4583145256Sjkoshy
4584145256Sjkoshystatic void
4585147191Sjkoshypmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
4586145256Sjkoshy    int flags)
4587145256Sjkoshy{
4588145256Sjkoshy	int is_using_hwpmcs;
4589147191Sjkoshy	unsigned int ri;
4590147191Sjkoshy	uint32_t do_descendants;
4591147191Sjkoshy	struct pmc *pm;
4592147191Sjkoshy	struct pmc_owner *po;
4593147191Sjkoshy	struct pmc_process *ppnew, *ppold;
4594145256Sjkoshy
4595145256Sjkoshy	(void) flags;		/* unused parameter */
4596145256Sjkoshy
4597145256Sjkoshy	PROC_LOCK(p1);
4598145256Sjkoshy	is_using_hwpmcs = p1->p_flag & P_HWPMC;
4599145256Sjkoshy	PROC_UNLOCK(p1);
4600145256Sjkoshy
4601147191Sjkoshy	/*
4602147191Sjkoshy	 * If there are system-wide sampling PMCs active, we need to
4603147191Sjkoshy	 * log all fork events to their owner's logs.
4604147191Sjkoshy	 */
4605147191Sjkoshy
4606147191Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4607147191Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4608147191Sjkoshy		    pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4609147191Sjkoshy
4610147191Sjkoshy	if (!is_using_hwpmcs)
4611147191Sjkoshy		return;
4612147191Sjkoshy
4613147191Sjkoshy	PMC_GET_SX_XLOCK();
4614282658Sjhb	PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4615147191Sjkoshy	    p1->p_pid, p1->p_comm, newproc);
4616147191Sjkoshy
4617147191Sjkoshy	/*
4618147191Sjkoshy	 * If the parent process (curthread->td_proc) is a
4619147191Sjkoshy	 * target of any PMCs, look for PMCs that are to be
4620147191Sjkoshy	 * inherited, and link these into the new process
4621147191Sjkoshy	 * descriptor.
4622147191Sjkoshy	 */
4623147191Sjkoshy	if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4624147191Sjkoshy		 PMC_FLAG_NONE)) == NULL)
4625147191Sjkoshy		goto done;		/* nothing to do */
4626147191Sjkoshy
4627147191Sjkoshy	do_descendants = 0;
4628147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
4629147191Sjkoshy		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4630147191Sjkoshy			do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4631147191Sjkoshy	if (do_descendants == 0) /* nothing to do */
4632147191Sjkoshy		goto done;
4633147191Sjkoshy
4634147191Sjkoshy	/* allocate a descriptor for the new process  */
4635147191Sjkoshy	if ((ppnew = pmc_find_process_descriptor(newproc,
4636147191Sjkoshy		 PMC_FLAG_ALLOCATE)) == NULL)
4637147191Sjkoshy		goto done;
4638147191Sjkoshy
4639147191Sjkoshy	/*
4640147191Sjkoshy	 * Run through all PMCs that were targeting the old process
4641147191Sjkoshy	 * and which specified F_DESCENDANTS and attach them to the
4642147191Sjkoshy	 * new process.
4643147191Sjkoshy	 *
4644147191Sjkoshy	 * Log the fork event to all owners of PMCs attached to this
4645147191Sjkoshy	 * process, if not already logged.
4646147191Sjkoshy	 */
4647147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
4648147191Sjkoshy		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4649147191Sjkoshy		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
4650147191Sjkoshy			pmc_link_target_process(pm, ppnew);
4651147191Sjkoshy			po = pm->pm_owner;
4652147191Sjkoshy			if (po->po_sscount == 0 &&
4653147191Sjkoshy			    po->po_flags & PMC_PO_OWNS_LOGFILE)
4654147191Sjkoshy				pmclog_process_procfork(po, p1->p_pid,
4655147191Sjkoshy				    newproc->p_pid);
4656147191Sjkoshy		}
4657147191Sjkoshy
4658147191Sjkoshy	/*
4659147191Sjkoshy	 * Now mark the new process as being tracked by this driver.
4660147191Sjkoshy	 */
4661147191Sjkoshy	PROC_LOCK(newproc);
4662147191Sjkoshy	newproc->p_flag |= P_HWPMC;
4663147191Sjkoshy	PROC_UNLOCK(newproc);
4664147191Sjkoshy
4665147191Sjkoshy done:
4666147191Sjkoshy	sx_xunlock(&pmc_sx);
4667145256Sjkoshy}
4668145256Sjkoshy
4669254813Smarkjstatic void
4670254813Smarkjpmc_kld_load(void *arg __unused, linker_file_t lf)
4671254813Smarkj{
4672254813Smarkj	struct pmc_owner *po;
4673145256Sjkoshy
4674254813Smarkj	sx_slock(&pmc_sx);
4675254813Smarkj
4676254813Smarkj	/*
4677254813Smarkj	 * Notify owners of system sampling PMCs about KLD operations.
4678254813Smarkj	 */
4679254813Smarkj	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4680254813Smarkj		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4681254813Smarkj			pmclog_process_map_in(po, (pid_t) -1,
4682254813Smarkj			    (uintfptr_t) lf->address, lf->filename);
4683254813Smarkj
4684254813Smarkj	/*
4685254813Smarkj	 * TODO: Notify owners of (all) process-sampling PMCs too.
4686254813Smarkj	 */
4687254813Smarkj
4688254813Smarkj	sx_sunlock(&pmc_sx);
4689254813Smarkj}
4690254813Smarkj
4691254813Smarkjstatic void
4692254813Smarkjpmc_kld_unload(void *arg __unused, const char *filename __unused,
4693254813Smarkj    caddr_t address, size_t size)
4694254813Smarkj{
4695254813Smarkj	struct pmc_owner *po;
4696254813Smarkj
4697254813Smarkj	sx_slock(&pmc_sx);
4698254813Smarkj
4699254813Smarkj	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4700254813Smarkj		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4701254813Smarkj			pmclog_process_map_out(po, (pid_t) -1,
4702254813Smarkj			    (uintfptr_t) address, (uintfptr_t) address + size);
4703254813Smarkj
4704254813Smarkj	/*
4705254813Smarkj	 * TODO: Notify owners of process-sampling PMCs.
4706254813Smarkj	 */
4707254813Smarkj
4708254813Smarkj	sx_sunlock(&pmc_sx);
4709254813Smarkj}
4710254813Smarkj
4711145256Sjkoshy/*
4712145256Sjkoshy * initialization
4713145256Sjkoshy */
4714283120Sjhbstatic const char *
4715283120Sjhbpmc_name_of_pmcclass(enum pmc_class class)
4716283120Sjhb{
4717145256Sjkoshy
4718283120Sjhb	switch (class) {
4719145256Sjkoshy#undef	__PMC_CLASS
4720283120Sjhb#define	__PMC_CLASS(S,V,D)						\
4721283120Sjhb	case PMC_CLASS_##S:						\
4722283120Sjhb		return #S;
4723283120Sjhb	__PMC_CLASSES();
4724283120Sjhb	default:
4725283120Sjhb		return ("<unknown>");
4726283120Sjhb	}
4727283120Sjhb}
4728145256Sjkoshy
4729233628Sfabient/*
4730233628Sfabient * Base class initializer: allocate structure and set default classes.
4731233628Sfabient */
4732233628Sfabientstruct pmc_mdep *
4733233628Sfabientpmc_mdep_alloc(int nclasses)
4734233628Sfabient{
4735233628Sfabient	struct pmc_mdep *md;
4736233628Sfabient	int	n;
4737233628Sfabient
4738233628Sfabient	/* SOFT + md classes */
4739233628Sfabient	n = 1 + nclasses;
4740233628Sfabient	md = malloc(sizeof(struct pmc_mdep) + n *
4741233628Sfabient	    sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
4742250105Sdavide	md->pmd_nclass = n;
4743233628Sfabient
4744250105Sdavide	/* Add base class. */
4745250105Sdavide	pmc_soft_initialize(md);
4746233628Sfabient	return md;
4747233628Sfabient}
4748233628Sfabient
4749233628Sfabientvoid
4750233628Sfabientpmc_mdep_free(struct pmc_mdep *md)
4751233628Sfabient{
4752233628Sfabient	pmc_soft_finalize(md);
4753233628Sfabient	free(md, M_PMC);
4754233628Sfabient}
4755233628Sfabient
4756145256Sjkoshystatic int
4757233628Sfabientgeneric_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
4758233628Sfabient{
4759233628Sfabient	(void) pc; (void) pp;
4760233628Sfabient
4761233628Sfabient	return (0);
4762233628Sfabient}
4763233628Sfabient
4764233628Sfabientstatic int
4765233628Sfabientgeneric_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
4766233628Sfabient{
4767233628Sfabient	(void) pc; (void) pp;
4768233628Sfabient
4769233628Sfabient	return (0);
4770233628Sfabient}
4771233628Sfabient
4772233628Sfabientstatic struct pmc_mdep *
4773233628Sfabientpmc_generic_cpu_initialize(void)
4774233628Sfabient{
4775233628Sfabient	struct pmc_mdep *md;
4776233628Sfabient
4777233628Sfabient	md = pmc_mdep_alloc(0);
4778233628Sfabient
4779233628Sfabient	md->pmd_cputype    = PMC_CPU_GENERIC;
4780233628Sfabient
4781233628Sfabient	md->pmd_pcpu_init  = NULL;
4782233628Sfabient	md->pmd_pcpu_fini  = NULL;
4783233628Sfabient	md->pmd_switch_in  = generic_switch_in;
4784233628Sfabient	md->pmd_switch_out = generic_switch_out;
4785233628Sfabient
4786233628Sfabient	return (md);
4787233628Sfabient}
4788233628Sfabient
4789233628Sfabientstatic void
4790233628Sfabientpmc_generic_cpu_finalize(struct pmc_mdep *md)
4791233628Sfabient{
4792233628Sfabient	(void) md;
4793233628Sfabient}
4794233628Sfabient
4795233628Sfabient
4796233628Sfabientstatic int
4797145256Sjkoshypmc_initialize(void)
4798145256Sjkoshy{
4799184802Sjkoshy	int c, cpu, error, n, ri;
4800183266Sjkoshy	unsigned int maxcpu;
4801145256Sjkoshy	struct pmc_binding pb;
4802174395Sjkoshy	struct pmc_sample *ps;
4803184802Sjkoshy	struct pmc_classdep *pcd;
4804147191Sjkoshy	struct pmc_samplebuffer *sb;
4805145256Sjkoshy
4806145256Sjkoshy	md = NULL;
4807145256Sjkoshy	error = 0;
4808145256Sjkoshy
4809282641Sjhb#ifdef	HWPMC_DEBUG
4810145256Sjkoshy	/* parse debug flags first */
4811145256Sjkoshy	if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4812145256Sjkoshy		pmc_debugstr, sizeof(pmc_debugstr)))
4813145256Sjkoshy		pmc_debugflags_parse(pmc_debugstr,
4814145256Sjkoshy		    pmc_debugstr+strlen(pmc_debugstr));
4815145256Sjkoshy#endif
4816145256Sjkoshy
4817282658Sjhb	PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4818145256Sjkoshy
4819148562Sjkoshy	/* check kernel version */
4820148562Sjkoshy	if (pmc_kernel_version != PMC_VERSION) {
4821148562Sjkoshy		if (pmc_kernel_version == 0)
4822148562Sjkoshy			printf("hwpmc: this kernel has not been compiled with "
4823148562Sjkoshy			    "'options HWPMC_HOOKS'.\n");
4824148562Sjkoshy		else
4825148562Sjkoshy			printf("hwpmc: kernel version (0x%x) does not match "
4826148562Sjkoshy			    "module version (0x%x).\n", pmc_kernel_version,
4827148562Sjkoshy			    PMC_VERSION);
4828148562Sjkoshy		return EPROGMISMATCH;
4829148562Sjkoshy	}
4830148562Sjkoshy
4831145256Sjkoshy	/*
4832145256Sjkoshy	 * check sysctl parameters
4833145256Sjkoshy	 */
4834145256Sjkoshy
4835145256Sjkoshy	if (pmc_hashsize <= 0) {
4836174395Sjkoshy		(void) printf("hwpmc: tunable \"hashsize\"=%d must be "
4837174395Sjkoshy		    "greater than zero.\n", pmc_hashsize);
4838145256Sjkoshy		pmc_hashsize = PMC_HASH_SIZE;
4839145256Sjkoshy	}
4840145256Sjkoshy
4841147191Sjkoshy	if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4842174395Sjkoshy		(void) printf("hwpmc: tunable \"nsamples\"=%d out of "
4843174395Sjkoshy		    "range.\n", pmc_nsamples);
4844147191Sjkoshy		pmc_nsamples = PMC_NSAMPLES;
4845147191Sjkoshy	}
4846145256Sjkoshy
4847174395Sjkoshy	if (pmc_callchaindepth <= 0 ||
4848174395Sjkoshy	    pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
4849174395Sjkoshy		(void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
4850274766Semaste		    "range - using %d.\n", pmc_callchaindepth,
4851274766Semaste		    PMC_CALLCHAIN_DEPTH_MAX);
4852274766Semaste		pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX;
4853174395Sjkoshy	}
4854174395Sjkoshy
4855147191Sjkoshy	md = pmc_md_initialize();
4856233628Sfabient	if (md == NULL) {
4857233628Sfabient		/* Default to generic CPU. */
4858233628Sfabient		md = pmc_generic_cpu_initialize();
4859233628Sfabient		if (md == NULL)
4860233628Sfabient			return (ENOSYS);
4861233628Sfabient        }
4862147191Sjkoshy
4863184802Sjkoshy	KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
4864184802Sjkoshy	    ("[pmc,%d] no classes or pmcs", __LINE__));
4865184802Sjkoshy
4866184802Sjkoshy	/* Compute the map from row-indices to classdep pointers. */
4867184802Sjkoshy	pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
4868184802Sjkoshy	    md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);
4869184802Sjkoshy
4870184802Sjkoshy	for (n = 0; n < md->pmd_npmc; n++)
4871184802Sjkoshy		pmc_rowindex_to_classdep[n] = NULL;
4872184802Sjkoshy	for (ri = c = 0; c < md->pmd_nclass; c++) {
4873184802Sjkoshy		pcd = &md->pmd_classdep[c];
4874184802Sjkoshy		for (n = 0; n < pcd->pcd_num; n++, ri++)
4875184802Sjkoshy			pmc_rowindex_to_classdep[ri] = pcd;
4876184802Sjkoshy	}
4877184802Sjkoshy
4878184802Sjkoshy	KASSERT(ri == md->pmd_npmc,
4879184802Sjkoshy	    ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
4880184802Sjkoshy	    ri, md->pmd_npmc));
4881184802Sjkoshy
4882183266Sjkoshy	maxcpu = pmc_cpu_max();
4883183266Sjkoshy
4884145256Sjkoshy	/* allocate space for the per-cpu array */
4885184802Sjkoshy	pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
4886184802Sjkoshy	    M_WAITOK|M_ZERO);
4887145256Sjkoshy
4888145256Sjkoshy	/* per-cpu 'saved values' for managing process-mode PMCs */
4889184214Sdes	pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
4890184214Sdes	    M_PMC, M_WAITOK);
4891145256Sjkoshy
4892183266Sjkoshy	/* Perform CPU-dependent initialization. */
4893145256Sjkoshy	pmc_save_cpu_binding(&pb);
4894184802Sjkoshy	error = 0;
4895184802Sjkoshy	for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
4896183266Sjkoshy		if (!pmc_cpu_is_active(cpu))
4897145256Sjkoshy			continue;
4898145256Sjkoshy		pmc_select_cpu(cpu);
4899184802Sjkoshy		pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
4900184802Sjkoshy		    md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
4901184802Sjkoshy		    M_WAITOK|M_ZERO);
4902184802Sjkoshy		if (md->pmd_pcpu_init)
4903185363Sjkoshy			error = md->pmd_pcpu_init(md, cpu);
4904184802Sjkoshy		for (n = 0; error == 0 && n < md->pmd_nclass; n++)
4905184802Sjkoshy			error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
4906145256Sjkoshy	}
4907145256Sjkoshy	pmc_restore_cpu_binding(&pb);
4908145256Sjkoshy
4909184802Sjkoshy	if (error)
4910184802Sjkoshy		return (error);
4911145256Sjkoshy
4912147191Sjkoshy	/* allocate space for the sample array */
4913183266Sjkoshy	for (cpu = 0; cpu < maxcpu; cpu++) {
4914183266Sjkoshy		if (!pmc_cpu_is_active(cpu))
4915147191Sjkoshy			continue;
4916184802Sjkoshy
4917184214Sdes		sb = malloc(sizeof(struct pmc_samplebuffer) +
4918147191Sjkoshy		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4919147191Sjkoshy		    M_WAITOK|M_ZERO);
4920147191Sjkoshy		sb->ps_read = sb->ps_write = sb->ps_samples;
4921153735Sjkoshy		sb->ps_fence = sb->ps_samples + pmc_nsamples;
4922184802Sjkoshy
4923147191Sjkoshy		KASSERT(pmc_pcpu[cpu] != NULL,
4924147191Sjkoshy		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4925147191Sjkoshy
4926184802Sjkoshy		sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4927184802Sjkoshy		    sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4928174395Sjkoshy
4929174395Sjkoshy		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4930174395Sjkoshy			ps->ps_pc = sb->ps_callchains +
4931174395Sjkoshy			    (n * pmc_callchaindepth);
4932174395Sjkoshy
4933233628Sfabient		pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
4934233628Sfabient
4935233628Sfabient		sb = malloc(sizeof(struct pmc_samplebuffer) +
4936233628Sfabient		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4937233628Sfabient		    M_WAITOK|M_ZERO);
4938233628Sfabient		sb->ps_read = sb->ps_write = sb->ps_samples;
4939233628Sfabient		sb->ps_fence = sb->ps_samples + pmc_nsamples;
4940233628Sfabient
4941233628Sfabient		KASSERT(pmc_pcpu[cpu] != NULL,
4942233628Sfabient		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4943233628Sfabient
4944233628Sfabient		sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4945233628Sfabient		    sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4946233628Sfabient
4947233628Sfabient		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4948233628Sfabient			ps->ps_pc = sb->ps_callchains +
4949233628Sfabient			    (n * pmc_callchaindepth);
4950233628Sfabient
4951233628Sfabient		pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
4952147191Sjkoshy	}
4953147191Sjkoshy
4954145256Sjkoshy	/* allocate space for the row disposition array */
4955145256Sjkoshy	pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4956145256Sjkoshy	    M_PMC, M_WAITOK|M_ZERO);
4957145256Sjkoshy
4958145256Sjkoshy	/* mark all PMCs as available */
4959145256Sjkoshy	for (n = 0; n < (int) md->pmd_npmc; n++)
4960145256Sjkoshy		PMC_MARK_ROW_FREE(n);
4961145256Sjkoshy
4962145256Sjkoshy	/* allocate thread hash tables */
4963145256Sjkoshy	pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4964145256Sjkoshy	    &pmc_ownerhashmask);
4965145256Sjkoshy
4966145256Sjkoshy	pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4967145256Sjkoshy	    &pmc_processhashmask);
4968168856Sjkoshy	mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4969168856Sjkoshy	    MTX_SPIN);
4970145256Sjkoshy
4971147191Sjkoshy	LIST_INIT(&pmc_ss_owners);
4972147191Sjkoshy	pmc_ss_count = 0;
4973147191Sjkoshy
4974145256Sjkoshy	/* allocate a pool of spin mutexes */
4975168856Sjkoshy	pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4976168856Sjkoshy	    MTX_SPIN);
4977145256Sjkoshy
4978282658Sjhb	PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4979145256Sjkoshy	    "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4980145256Sjkoshy	    pmc_processhash, pmc_processhashmask);
4981145256Sjkoshy
4982145256Sjkoshy	/* register process {exit,fork,exec} handlers */
4983145256Sjkoshy	pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4984145256Sjkoshy	    pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4985145256Sjkoshy	pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4986145256Sjkoshy	    pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4987145256Sjkoshy
4988254813Smarkj	/* register kld event handlers */
4989254813Smarkj	pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
4990254813Smarkj	    NULL, EVENTHANDLER_PRI_ANY);
4991254813Smarkj	pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
4992254813Smarkj	    NULL, EVENTHANDLER_PRI_ANY);
4993254813Smarkj
4994147191Sjkoshy	/* initialize logging */
4995147191Sjkoshy	pmclog_initialize();
4996147191Sjkoshy
4997145256Sjkoshy	/* set hook functions */
4998145256Sjkoshy	pmc_intr = md->pmd_intr;
4999145256Sjkoshy	pmc_hook = pmc_hook_handler;
5000145256Sjkoshy
5001145256Sjkoshy	if (error == 0) {
5002145256Sjkoshy		printf(PMC_MODULE_NAME ":");
5003149373Sjkoshy		for (n = 0; n < (int) md->pmd_nclass; n++) {
5004184802Sjkoshy			pcd = &md->pmd_classdep[n];
5005184997Sjkoshy			printf(" %s/%d/%d/0x%b",
5006283120Sjhb			    pmc_name_of_pmcclass(pcd->pcd_class),
5007184802Sjkoshy			    pcd->pcd_num,
5008184997Sjkoshy			    pcd->pcd_width,
5009184802Sjkoshy			    pcd->pcd_caps,
5010149373Sjkoshy			    "\20"
5011149373Sjkoshy			    "\1INT\2USR\3SYS\4EDG\5THR"
5012149373Sjkoshy			    "\6REA\7WRI\10INV\11QUA\12PRC"
5013149373Sjkoshy			    "\13TAG\14CSC");
5014149373Sjkoshy		}
5015145256Sjkoshy		printf("\n");
5016145256Sjkoshy	}
5017145256Sjkoshy
5018184802Sjkoshy	return (error);
5019145256Sjkoshy}
5020145256Sjkoshy
5021145256Sjkoshy/* prepare to be unloaded */
5022145256Sjkoshystatic void
5023145256Sjkoshypmc_cleanup(void)
5024145256Sjkoshy{
5025184802Sjkoshy	int c, cpu;
5026183266Sjkoshy	unsigned int maxcpu;
5027145256Sjkoshy	struct pmc_ownerhash *ph;
5028145256Sjkoshy	struct pmc_owner *po, *tmp;
5029145256Sjkoshy	struct pmc_binding pb;
5030282641Sjhb#ifdef	HWPMC_DEBUG
5031145256Sjkoshy	struct pmc_processhash *prh;
5032145256Sjkoshy#endif
5033145256Sjkoshy
5034282658Sjhb	PMCDBG0(MOD,INI,0, "cleanup");
5035145256Sjkoshy
5036147191Sjkoshy	/* switch off sampling */
5037222813Sattilio	CPU_ZERO(&pmc_cpumask);
5038147191Sjkoshy	pmc_intr = NULL;
5039145256Sjkoshy
5040145256Sjkoshy	sx_xlock(&pmc_sx);
5041145256Sjkoshy	if (pmc_hook == NULL) {	/* being unloaded already */
5042145256Sjkoshy		sx_xunlock(&pmc_sx);
5043145256Sjkoshy		return;
5044145256Sjkoshy	}
5045145256Sjkoshy
5046145256Sjkoshy	pmc_hook = NULL; /* prevent new threads from entering module */
5047145256Sjkoshy
5048145256Sjkoshy	/* deregister event handlers */
5049145256Sjkoshy	EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
5050145256Sjkoshy	EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
5051254813Smarkj	EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
5052254813Smarkj	EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);
5053145256Sjkoshy
5054145256Sjkoshy	/* send SIGBUS to all owner threads, free up allocations */
5055145256Sjkoshy	if (pmc_ownerhash)
5056145256Sjkoshy		for (ph = pmc_ownerhash;
5057145256Sjkoshy		     ph <= &pmc_ownerhash[pmc_ownerhashmask];
5058145256Sjkoshy		     ph++) {
5059145256Sjkoshy			LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
5060145256Sjkoshy				pmc_remove_owner(po);
5061145256Sjkoshy
5062145256Sjkoshy				/* send SIGBUS to owner processes */
5063282658Sjhb				PMCDBG3(MOD,INI,2, "cleanup signal proc=%p "
5064145256Sjkoshy				    "(%d, %s)", po->po_owner,
5065145256Sjkoshy				    po->po_owner->p_pid,
5066145256Sjkoshy				    po->po_owner->p_comm);
5067145256Sjkoshy
5068145256Sjkoshy				PROC_LOCK(po->po_owner);
5069225617Skmacy				kern_psignal(po->po_owner, SIGBUS);
5070145256Sjkoshy				PROC_UNLOCK(po->po_owner);
5071147191Sjkoshy
5072147191Sjkoshy				pmc_destroy_owner_descriptor(po);
5073145256Sjkoshy			}
5074145256Sjkoshy		}
5075145256Sjkoshy
5076145256Sjkoshy	/* reclaim allocated data structures */
5077145256Sjkoshy	if (pmc_mtxpool)
5078145256Sjkoshy		mtx_pool_destroy(&pmc_mtxpool);
5079145256Sjkoshy
5080145256Sjkoshy	mtx_destroy(&pmc_processhash_mtx);
5081145256Sjkoshy	if (pmc_processhash) {
5082282641Sjhb#ifdef	HWPMC_DEBUG
5083145256Sjkoshy		struct pmc_process *pp;
5084145256Sjkoshy
5085282658Sjhb		PMCDBG0(MOD,INI,3, "destroy process hash");
5086145256Sjkoshy		for (prh = pmc_processhash;
5087145256Sjkoshy		     prh <= &pmc_processhash[pmc_processhashmask];
5088145256Sjkoshy		     prh++)
5089145256Sjkoshy			LIST_FOREACH(pp, prh, pp_next)
5090282658Sjhb			    PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5091145256Sjkoshy#endif
5092145256Sjkoshy
5093145256Sjkoshy		hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5094145256Sjkoshy		pmc_processhash = NULL;
5095145256Sjkoshy	}
5096145256Sjkoshy
5097145256Sjkoshy	if (pmc_ownerhash) {
5098282658Sjhb		PMCDBG0(MOD,INI,3, "destroy owner hash");
5099145256Sjkoshy		hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5100145256Sjkoshy		pmc_ownerhash = NULL;
5101145256Sjkoshy	}
5102145256Sjkoshy
5103147191Sjkoshy	KASSERT(LIST_EMPTY(&pmc_ss_owners),
5104147191Sjkoshy	    ("[pmc,%d] Global SS owner list not empty", __LINE__));
5105147191Sjkoshy	KASSERT(pmc_ss_count == 0,
5106147191Sjkoshy	    ("[pmc,%d] Global SS count not empty", __LINE__));
5107147191Sjkoshy
5108184802Sjkoshy 	/* do processor and pmc-class dependent cleanup */
5109183266Sjkoshy	maxcpu = pmc_cpu_max();
5110153735Sjkoshy
5111282658Sjhb	PMCDBG0(MOD,INI,3, "md cleanup");
5112145256Sjkoshy	if (md) {
5113145256Sjkoshy		pmc_save_cpu_binding(&pb);
5114183266Sjkoshy		for (cpu = 0; cpu < maxcpu; cpu++) {
5115282658Sjhb			PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5116145256Sjkoshy			    cpu, pmc_pcpu[cpu]);
5117183266Sjkoshy			if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5118145256Sjkoshy				continue;
5119145256Sjkoshy			pmc_select_cpu(cpu);
5120184802Sjkoshy			for (c = 0; c < md->pmd_nclass; c++)
5121184802Sjkoshy				md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
5122184802Sjkoshy			if (md->pmd_pcpu_fini)
5123185363Sjkoshy				md->pmd_pcpu_fini(md, cpu);
5124145256Sjkoshy		}
5125184994Sjkoshy
5126233628Sfabient		if (md->pmd_cputype == PMC_CPU_GENERIC)
5127233628Sfabient			pmc_generic_cpu_finalize(md);
5128233628Sfabient		else
5129233628Sfabient			pmc_md_finalize(md);
5130184994Sjkoshy
5131233628Sfabient		pmc_mdep_free(md);
5132145256Sjkoshy		md = NULL;
5133145256Sjkoshy		pmc_restore_cpu_binding(&pb);
5134145256Sjkoshy	}
5135145256Sjkoshy
5136184802Sjkoshy	/* Free per-cpu descriptors. */
5137184802Sjkoshy	for (cpu = 0; cpu < maxcpu; cpu++) {
5138184802Sjkoshy		if (!pmc_cpu_is_active(cpu))
5139184802Sjkoshy			continue;
5140233628Sfabient		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5141233628Sfabient		    ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5142184802Sjkoshy			cpu));
5143233628Sfabient		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5144233628Sfabient		    ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5145233628Sfabient			cpu));
5146233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
5147233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
5148233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
5149233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
5150184802Sjkoshy		free(pmc_pcpu[cpu], M_PMC);
5151184802Sjkoshy	}
5152184802Sjkoshy
5153184205Sdes	free(pmc_pcpu, M_PMC);
5154145256Sjkoshy	pmc_pcpu = NULL;
5155145256Sjkoshy
5156184205Sdes	free(pmc_pcpu_saved, M_PMC);
5157145256Sjkoshy	pmc_pcpu_saved = NULL;
5158145256Sjkoshy
5159145256Sjkoshy	if (pmc_pmcdisp) {
5160184205Sdes		free(pmc_pmcdisp, M_PMC);
5161145256Sjkoshy		pmc_pmcdisp = NULL;
5162145256Sjkoshy	}
5163145256Sjkoshy
5164184802Sjkoshy	if (pmc_rowindex_to_classdep) {
5165184802Sjkoshy		free(pmc_rowindex_to_classdep, M_PMC);
5166184802Sjkoshy		pmc_rowindex_to_classdep = NULL;
5167184802Sjkoshy	}
5168184802Sjkoshy
5169147191Sjkoshy	pmclog_shutdown();
5170147191Sjkoshy
5171145256Sjkoshy	sx_xunlock(&pmc_sx); 	/* we are done */
5172145256Sjkoshy}
5173145256Sjkoshy
5174145256Sjkoshy/*
5175145256Sjkoshy * The function called at load/unload.
5176145256Sjkoshy */
5177145256Sjkoshy
5178145256Sjkoshystatic int
5179145256Sjkoshyload (struct module *module __unused, int cmd, void *arg __unused)
5180145256Sjkoshy{
5181145256Sjkoshy	int error;
5182145256Sjkoshy
5183145256Sjkoshy	error = 0;
5184145256Sjkoshy
5185145256Sjkoshy	switch (cmd) {
5186145256Sjkoshy	case MOD_LOAD :
5187145256Sjkoshy		/* initialize the subsystem */
5188145256Sjkoshy		error = pmc_initialize();
5189145256Sjkoshy		if (error != 0)
5190145256Sjkoshy			break;
5191282658Sjhb		PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d",
5192183266Sjkoshy		    pmc_syscall_num, pmc_cpu_max());
5193145256Sjkoshy		break;
5194145256Sjkoshy
5195145256Sjkoshy
5196145256Sjkoshy	case MOD_UNLOAD :
5197145256Sjkoshy	case MOD_SHUTDOWN:
5198145256Sjkoshy		pmc_cleanup();
5199282658Sjhb		PMCDBG0(MOD,INI,1, "unloaded");
5200145256Sjkoshy		break;
5201145256Sjkoshy
5202145256Sjkoshy	default :
5203145256Sjkoshy		error = EINVAL;	/* XXX should panic(9) */
5204145256Sjkoshy		break;
5205145256Sjkoshy	}
5206145256Sjkoshy
5207145256Sjkoshy	return error;
5208145256Sjkoshy}
5209145256Sjkoshy
5210145256Sjkoshy/* memory pool */
5211145256SjkoshyMALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");
5212