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: stable/11/sys/dev/hwpmc/hwpmc_mod.c 343350 2019-01-23 17:36:58Z markj $");
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 = {
314325546Skib	.sy_narg =	2,
315325546Skib	.sy_call =	pmc_syscall_handler,
316145256Sjkoshy};
317145256Sjkoshy
318145256Sjkoshystatic struct syscall_module_data pmc_syscall_mod = {
319325546Skib	.chainevh =	load,
320325546Skib	.chainarg =	NULL,
321325546Skib	.offset =	&pmc_syscall_num,
322325546Skib	.new_sysent =	&pmc_sysent,
323325546Skib	.old_sysent =	{ .sy_narg = 0, .sy_call = NULL },
324325546Skib	.flags =	SY_THR_STATIC_KLD,
325145256Sjkoshy};
326145256Sjkoshy
327145256Sjkoshystatic moduledata_t pmc_mod = {
328325546Skib	.name =		PMC_MODULE_NAME,
329325546Skib	.evhand =	syscall_module_handler,
330325546Skib	.priv =		&pmc_syscall_mod,
331145256Sjkoshy};
332145256Sjkoshy
333299746Sjhb#ifdef EARLY_AP_STARTUP
334299746SjhbDECLARE_MODULE(pmc, pmc_mod, SI_SUB_SYSCALLS, SI_ORDER_ANY);
335299746Sjhb#else
336145256SjkoshyDECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
337299746Sjhb#endif
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
1430310064Savg		if (pm->pm_state != PMC_STATE_DELETED && pp != NULL &&
1431310064Savg		    pp->pp_pmcs[ri].pp_pmc != NULL) {
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
2581282658Sjhb	PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid);
2582325756Skib	if (PMC_ID_TO_ROWINDEX(pmcid) >= md->pmd_npmc)
2583325756Skib		return (EINVAL);
2584145256Sjkoshy
2585287115Sbz	if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL) {
2586287115Sbz		/*
2587287115Sbz		 * In case of PMC_F_DESCENDANTS child processes we will not find
2588287115Sbz		 * the current process in the owners hash list.  Find the owner
2589287115Sbz		 * process first and from there lookup the po.
2590287115Sbz		 */
2591287115Sbz		if ((pp = pmc_find_process_descriptor(curthread->td_proc,
2592287115Sbz		    PMC_FLAG_NONE)) == NULL) {
2593287115Sbz			return ESRCH;
2594287115Sbz		} else {
2595287115Sbz			opm = pp->pp_pmcs[PMC_ID_TO_ROWINDEX(pmcid)].pp_pmc;
2596287115Sbz			if (opm == NULL)
2597287115Sbz				return ESRCH;
2598287115Sbz			if ((opm->pm_flags & (PMC_F_ATTACHED_TO_OWNER|
2599287115Sbz			    PMC_F_DESCENDANTS)) != (PMC_F_ATTACHED_TO_OWNER|
2600287115Sbz			    PMC_F_DESCENDANTS))
2601287115Sbz				return ESRCH;
2602287115Sbz			po = opm->pm_owner;
2603287115Sbz		}
2604287115Sbz	}
2605145256Sjkoshy
2606145256Sjkoshy	if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2607145256Sjkoshy		return EINVAL;
2608145256Sjkoshy
2609282658Sjhb	PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2610145256Sjkoshy
2611145256Sjkoshy	*pmc = pm;
2612145256Sjkoshy	return 0;
2613145256Sjkoshy}
2614145256Sjkoshy
2615145256Sjkoshy/*
2616145256Sjkoshy * Start a PMC.
2617145256Sjkoshy */
2618145256Sjkoshy
2619145256Sjkoshystatic int
2620145256Sjkoshypmc_start(struct pmc *pm)
2621145256Sjkoshy{
2622145774Sjkoshy	enum pmc_mode mode;
2623147191Sjkoshy	struct pmc_owner *po;
2624145256Sjkoshy	struct pmc_binding pb;
2625184802Sjkoshy	struct pmc_classdep *pcd;
2626184802Sjkoshy	int adjri, error, cpu, ri;
2627145256Sjkoshy
2628145256Sjkoshy	KASSERT(pm != NULL,
2629145256Sjkoshy	    ("[pmc,%d] null pm", __LINE__));
2630145256Sjkoshy
2631145774Sjkoshy	mode = PMC_TO_MODE(pm);
2632145774Sjkoshy	ri   = PMC_TO_ROWINDEX(pm);
2633184802Sjkoshy	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
2634184802Sjkoshy
2635145774Sjkoshy	error = 0;
2636145256Sjkoshy
2637282658Sjhb	PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2638145774Sjkoshy
2639147191Sjkoshy	po = pm->pm_owner;
2640145256Sjkoshy
2641174395Sjkoshy	/*
2642174395Sjkoshy	 * Disallow PMCSTART if a logfile is required but has not been
2643174395Sjkoshy	 * configured yet.
2644174395Sjkoshy	 */
2645174395Sjkoshy	if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2646174395Sjkoshy	    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2647184802Sjkoshy		return (EDOOFUS);	/* programming error */
2648174395Sjkoshy
2649174395Sjkoshy	/*
2650174395Sjkoshy	 * If this is a sampling mode PMC, log mapping information for
2651174395Sjkoshy	 * the kernel modules that are currently loaded.
2652174395Sjkoshy	 */
2653174395Sjkoshy	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2654174395Sjkoshy	    pmc_log_kernel_mappings(pm);
2655174395Sjkoshy
2656145774Sjkoshy	if (PMC_IS_VIRTUAL_MODE(mode)) {
2657145256Sjkoshy
2658145256Sjkoshy		/*
2659147191Sjkoshy		 * If a PMCATTACH has never been done on this PMC,
2660147191Sjkoshy		 * attach it to its owner process.
2661145256Sjkoshy		 */
2662145256Sjkoshy
2663145256Sjkoshy		if (LIST_EMPTY(&pm->pm_targets))
2664147191Sjkoshy			error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2665147191Sjkoshy			    pmc_attach_process(po->po_owner, pm);
2666145256Sjkoshy
2667145774Sjkoshy		/*
2668147191Sjkoshy		 * If the PMC is attached to its owner, then force a context
2669147191Sjkoshy		 * switch to ensure that the MD state gets set correctly.
2670145256Sjkoshy		 */
2671145256Sjkoshy
2672147191Sjkoshy		if (error == 0) {
2673147191Sjkoshy			pm->pm_state = PMC_STATE_RUNNING;
2674147191Sjkoshy			if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2675147191Sjkoshy				pmc_force_context_switch();
2676147191Sjkoshy		}
2677147191Sjkoshy
2678184802Sjkoshy		return (error);
2679147191Sjkoshy	}
2680145256Sjkoshy
2681147191Sjkoshy
2682147191Sjkoshy	/*
2683147191Sjkoshy	 * A system-wide PMC.
2684174395Sjkoshy	 *
2685147191Sjkoshy	 * Add the owner to the global list if this is a system-wide
2686147191Sjkoshy	 * sampling PMC.
2687147191Sjkoshy	 */
2688147191Sjkoshy
2689147191Sjkoshy	if (mode == PMC_MODE_SS) {
2690147191Sjkoshy		if (po->po_sscount == 0) {
2691147191Sjkoshy			LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2692147191Sjkoshy			atomic_add_rel_int(&pmc_ss_count, 1);
2693282658Sjhb			PMCDBG1(PMC,OPS,1, "po=%p in global list", po);
2694147191Sjkoshy		}
2695147191Sjkoshy		po->po_sscount++;
2696145256Sjkoshy
2697207484Srstone		/*
2698207484Srstone		 * Log mapping information for all existing processes in the
2699207484Srstone		 * system.  Subsequent mappings are logged as they happen;
2700207484Srstone		 * see pmc_process_mmap().
2701207484Srstone		 */
2702207484Srstone		if (po->po_logprocmaps == 0) {
2703207484Srstone			pmc_log_all_process_mappings(po);
2704207484Srstone			po->po_logprocmaps = 1;
2705207484Srstone		}
2706201021Sjkoshy	}
2707157144Sjkoshy
2708145256Sjkoshy	/*
2709147191Sjkoshy	 * Move to the CPU associated with this
2710145256Sjkoshy	 * PMC, and start the hardware.
2711145256Sjkoshy	 */
2712145256Sjkoshy
2713145256Sjkoshy	pmc_save_cpu_binding(&pb);
2714145256Sjkoshy
2715145774Sjkoshy	cpu = PMC_TO_CPU(pm);
2716145256Sjkoshy
2717183266Sjkoshy	if (!pmc_cpu_is_active(cpu))
2718184802Sjkoshy		return (ENXIO);
2719145256Sjkoshy
2720145256Sjkoshy	pmc_select_cpu(cpu);
2721145256Sjkoshy
2722145256Sjkoshy	/*
2723145256Sjkoshy	 * global PMCs are configured at allocation time
2724145256Sjkoshy	 * so write out the initial value and start the PMC.
2725145256Sjkoshy	 */
2726145256Sjkoshy
2727147191Sjkoshy	pm->pm_state = PMC_STATE_RUNNING;
2728147191Sjkoshy
2729145774Sjkoshy	critical_enter();
2730184802Sjkoshy	if ((error = pcd->pcd_write_pmc(cpu, adjri,
2731145774Sjkoshy		 PMC_IS_SAMPLING_MODE(mode) ?
2732145256Sjkoshy		 pm->pm_sc.pm_reloadcount :
2733290811Sjtl		 pm->pm_sc.pm_initial)) == 0) {
2734290811Sjtl		/* If a sampling mode PMC, reset stalled state. */
2735290811Sjtl		if (PMC_IS_SAMPLING_MODE(mode))
2736290811Sjtl			CPU_CLR_ATOMIC(cpu, &pm->pm_stalled);
2737290811Sjtl
2738290811Sjtl		/* Indicate that we desire this to run. Start it. */
2739290811Sjtl		CPU_SET_ATOMIC(cpu, &pm->pm_cpustate);
2740184802Sjkoshy		error = pcd->pcd_start_pmc(cpu, adjri);
2741290811Sjtl	}
2742145774Sjkoshy	critical_exit();
2743145256Sjkoshy
2744145256Sjkoshy	pmc_restore_cpu_binding(&pb);
2745145256Sjkoshy
2746184802Sjkoshy	return (error);
2747145256Sjkoshy}
2748145256Sjkoshy
2749145256Sjkoshy/*
2750145256Sjkoshy * Stop a PMC.
2751145256Sjkoshy */
2752145256Sjkoshy
2753145256Sjkoshystatic int
2754145256Sjkoshypmc_stop(struct pmc *pm)
2755145256Sjkoshy{
2756147191Sjkoshy	struct pmc_owner *po;
2757145256Sjkoshy	struct pmc_binding pb;
2758184802Sjkoshy	struct pmc_classdep *pcd;
2759184802Sjkoshy	int adjri, cpu, error, ri;
2760145256Sjkoshy
2761145256Sjkoshy	KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2762145256Sjkoshy
2763282658Sjhb	PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2764145774Sjkoshy	    PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2765145256Sjkoshy
2766145256Sjkoshy	pm->pm_state = PMC_STATE_STOPPED;
2767145256Sjkoshy
2768145256Sjkoshy	/*
2769145256Sjkoshy	 * If the PMC is a virtual mode one, changing the state to
2770145256Sjkoshy	 * non-RUNNING is enough to ensure that the PMC never gets
2771145256Sjkoshy	 * scheduled.
2772145256Sjkoshy	 *
2773145256Sjkoshy	 * If this PMC is current running on a CPU, then it will
2774145256Sjkoshy	 * handled correctly at the time its target process is context
2775145256Sjkoshy	 * switched out.
2776145256Sjkoshy	 */
2777145256Sjkoshy
2778145774Sjkoshy	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2779145256Sjkoshy		return 0;
2780145256Sjkoshy
2781145256Sjkoshy	/*
2782145256Sjkoshy	 * A system-mode PMC.  Move to the CPU associated with
2783145256Sjkoshy	 * this PMC, and stop the hardware.  We update the
2784145256Sjkoshy	 * 'initial count' so that a subsequent PMCSTART will
2785145256Sjkoshy	 * resume counting from the current hardware count.
2786145256Sjkoshy	 */
2787145256Sjkoshy
2788145256Sjkoshy	pmc_save_cpu_binding(&pb);
2789145256Sjkoshy
2790145774Sjkoshy	cpu = PMC_TO_CPU(pm);
2791145256Sjkoshy
2792183266Sjkoshy	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
2793145774Sjkoshy	    ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2794145774Sjkoshy
2795183266Sjkoshy	if (!pmc_cpu_is_active(cpu))
2796145256Sjkoshy		return ENXIO;
2797145256Sjkoshy
2798145256Sjkoshy	pmc_select_cpu(cpu);
2799145256Sjkoshy
2800145774Sjkoshy	ri = PMC_TO_ROWINDEX(pm);
2801184802Sjkoshy	pcd = pmc_ri_to_classdep(md, ri, &adjri);
2802145256Sjkoshy
2803290811Sjtl	CPU_CLR_ATOMIC(cpu, &pm->pm_cpustate);
2804145774Sjkoshy	critical_enter();
2805184802Sjkoshy	if ((error = pcd->pcd_stop_pmc(cpu, adjri)) == 0)
2806184802Sjkoshy		error = pcd->pcd_read_pmc(cpu, adjri, &pm->pm_sc.pm_initial);
2807145774Sjkoshy	critical_exit();
2808145774Sjkoshy
2809145256Sjkoshy	pmc_restore_cpu_binding(&pb);
2810145256Sjkoshy
2811147191Sjkoshy	po = pm->pm_owner;
2812147191Sjkoshy
2813147191Sjkoshy	/* remove this owner from the global list of SS PMC owners */
2814147191Sjkoshy	if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2815147191Sjkoshy		po->po_sscount--;
2816147191Sjkoshy		if (po->po_sscount == 0) {
2817147191Sjkoshy			atomic_subtract_rel_int(&pmc_ss_count, 1);
2818147191Sjkoshy			LIST_REMOVE(po, po_ssnext);
2819282658Sjhb			PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po);
2820147191Sjkoshy		}
2821147191Sjkoshy	}
2822147191Sjkoshy
2823184802Sjkoshy	return (error);
2824145256Sjkoshy}
2825145256Sjkoshy
2826145256Sjkoshy
2827282641Sjhb#ifdef	HWPMC_DEBUG
2828145256Sjkoshystatic const char *pmc_op_to_name[] = {
2829145256Sjkoshy#undef	__PMC_OP
2830145256Sjkoshy#define	__PMC_OP(N, D)	#N ,
2831145256Sjkoshy	__PMC_OPS()
2832145256Sjkoshy	NULL
2833145256Sjkoshy};
2834145256Sjkoshy#endif
2835145256Sjkoshy
2836145256Sjkoshy/*
2837145256Sjkoshy * The syscall interface
2838145256Sjkoshy */
2839145256Sjkoshy
2840145256Sjkoshy#define	PMC_GET_SX_XLOCK(...) do {		\
2841145256Sjkoshy	sx_xlock(&pmc_sx);			\
2842145256Sjkoshy	if (pmc_hook == NULL) {			\
2843145256Sjkoshy		sx_xunlock(&pmc_sx);		\
2844145256Sjkoshy		return __VA_ARGS__;		\
2845145256Sjkoshy	}					\
2846145256Sjkoshy} while (0)
2847145256Sjkoshy
2848145256Sjkoshy#define	PMC_DOWNGRADE_SX() do {			\
2849145256Sjkoshy	sx_downgrade(&pmc_sx);			\
2850145256Sjkoshy	is_sx_downgraded = 1;			\
2851145256Sjkoshy} while (0)
2852145256Sjkoshy
2853145256Sjkoshystatic int
2854145256Sjkoshypmc_syscall_handler(struct thread *td, void *syscall_args)
2855145256Sjkoshy{
2856325551Skib	int error, is_sx_downgraded, op;
2857145256Sjkoshy	struct pmc_syscall_args *c;
2858325551Skib	void *pmclog_proc_handle;
2859145256Sjkoshy	void *arg;
2860145256Sjkoshy
2861325551Skib	c = (struct pmc_syscall_args *)syscall_args;
2862325551Skib	op = c->pmop_code;
2863325551Skib	arg = c->pmop_data;
2864325551Skib	if (op == PMC_OP_CONFIGURELOG) {
2865325551Skib		/*
2866325551Skib		 * We cannot create the logging process inside
2867325551Skib		 * pmclog_configure_log() because there is a LOR
2868325551Skib		 * between pmc_sx and process structure locks.
2869325551Skib		 * Instead, pre-create the process and ignite the loop
2870325551Skib		 * if everything is fine, otherwise direct the process
2871325551Skib		 * to exit.
2872325551Skib		 */
2873325551Skib		error = pmclog_proc_create(td, &pmclog_proc_handle);
2874325551Skib		if (error != 0)
2875325551Skib			goto done_syscall;
2876325551Skib	}
2877325551Skib
2878145256Sjkoshy	PMC_GET_SX_XLOCK(ENOSYS);
2879145256Sjkoshy	is_sx_downgraded = 0;
2880145256Sjkoshy
2881282658Sjhb	PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2882145256Sjkoshy	    pmc_op_to_name[op], arg);
2883145256Sjkoshy
2884145256Sjkoshy	error = 0;
2885145256Sjkoshy	atomic_add_int(&pmc_stats.pm_syscalls, 1);
2886145256Sjkoshy
2887325547Skib	switch (op) {
2888145256Sjkoshy
2889145256Sjkoshy
2890145256Sjkoshy	/*
2891145256Sjkoshy	 * Configure a log file.
2892145256Sjkoshy	 *
2893145256Sjkoshy	 * XXX This OP will be reworked.
2894145256Sjkoshy	 */
2895145256Sjkoshy
2896145256Sjkoshy	case PMC_OP_CONFIGURELOG:
2897145256Sjkoshy	{
2898157144Sjkoshy		struct proc *p;
2899156466Sjkoshy		struct pmc *pm;
2900145256Sjkoshy		struct pmc_owner *po;
2901145256Sjkoshy		struct pmc_op_configurelog cl;
2902145256Sjkoshy
2903325551Skib		if ((error = copyin(arg, &cl, sizeof(cl))) != 0) {
2904325551Skib			pmclog_proc_ignite(pmclog_proc_handle, NULL);
2905145256Sjkoshy			break;
2906325551Skib		}
2907145256Sjkoshy
2908145256Sjkoshy		/* mark this process as owning a log file */
2909145256Sjkoshy		p = td->td_proc;
2910145256Sjkoshy		if ((po = pmc_find_owner_descriptor(p)) == NULL)
2911147191Sjkoshy			if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2912325551Skib				pmclog_proc_ignite(pmclog_proc_handle, NULL);
2913147191Sjkoshy				error = ENOMEM;
2914147191Sjkoshy				break;
2915147191Sjkoshy			}
2916145256Sjkoshy
2917147191Sjkoshy		/*
2918147191Sjkoshy		 * If a valid fd was passed in, try to configure that,
2919147191Sjkoshy		 * otherwise if 'fd' was less than zero and there was
2920147191Sjkoshy		 * a log file configured, flush its buffers and
2921147191Sjkoshy		 * de-configure it.
2922147191Sjkoshy		 */
2923195005Sattilio		if (cl.pm_logfd >= 0) {
2924185363Sjkoshy			error = pmclog_configure_log(md, po, cl.pm_logfd);
2925325551Skib			pmclog_proc_ignite(pmclog_proc_handle, error == 0 ?
2926325551Skib			    po : NULL);
2927195005Sattilio		} else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2928325551Skib			pmclog_proc_ignite(pmclog_proc_handle, NULL);
2929226514Sfabient			error = pmclog_close(po);
2930156466Sjkoshy			if (error == 0) {
2931156466Sjkoshy				LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2932156834Sjkoshy				    if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2933156834Sjkoshy					pm->pm_state == PMC_STATE_RUNNING)
2934156466Sjkoshy					    pmc_stop(pm);
2935147191Sjkoshy				error = pmclog_deconfigure_log(po);
2936156466Sjkoshy			}
2937325551Skib		} else {
2938325551Skib			pmclog_proc_ignite(pmclog_proc_handle, NULL);
2939147191Sjkoshy			error = EINVAL;
2940325551Skib		}
2941147191Sjkoshy	}
2942147191Sjkoshy	break;
2943147191Sjkoshy
2944147191Sjkoshy	/*
2945147191Sjkoshy	 * Flush a log file.
2946147191Sjkoshy	 */
2947147191Sjkoshy
2948147191Sjkoshy	case PMC_OP_FLUSHLOG:
2949147191Sjkoshy	{
2950147191Sjkoshy		struct pmc_owner *po;
2951147191Sjkoshy
2952147191Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
2953147191Sjkoshy
2954147191Sjkoshy		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2955147191Sjkoshy			error = EINVAL;
2956145256Sjkoshy			break;
2957147191Sjkoshy		}
2958145256Sjkoshy
2959147191Sjkoshy		error = pmclog_flush(po);
2960145256Sjkoshy	}
2961145256Sjkoshy	break;
2962145256Sjkoshy
2963145256Sjkoshy	/*
2964226514Sfabient	 * Close a log file.
2965226514Sfabient	 */
2966226514Sfabient
2967226514Sfabient	case PMC_OP_CLOSELOG:
2968226514Sfabient	{
2969226514Sfabient		struct pmc_owner *po;
2970226514Sfabient
2971226514Sfabient		sx_assert(&pmc_sx, SX_XLOCKED);
2972226514Sfabient
2973226514Sfabient		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2974226514Sfabient			error = EINVAL;
2975226514Sfabient			break;
2976226514Sfabient		}
2977226514Sfabient
2978226514Sfabient		error = pmclog_close(po);
2979226514Sfabient	}
2980226514Sfabient	break;
2981226514Sfabient
2982226514Sfabient	/*
2983145256Sjkoshy	 * Retrieve hardware configuration.
2984145256Sjkoshy	 */
2985145256Sjkoshy
2986145256Sjkoshy	case PMC_OP_GETCPUINFO:	/* CPU information */
2987145256Sjkoshy	{
2988145256Sjkoshy		struct pmc_op_getcpuinfo gci;
2989184802Sjkoshy		struct pmc_classinfo *pci;
2990184802Sjkoshy		struct pmc_classdep *pcd;
2991184802Sjkoshy		int cl;
2992145256Sjkoshy
2993343350Smarkj		memset(&gci, 0, sizeof(gci));
2994145256Sjkoshy		gci.pm_cputype = md->pmd_cputype;
2995183266Sjkoshy		gci.pm_ncpu    = pmc_cpu_max();
2996145256Sjkoshy		gci.pm_npmc    = md->pmd_npmc;
2997145256Sjkoshy		gci.pm_nclass  = md->pmd_nclass;
2998184802Sjkoshy		pci = gci.pm_classes;
2999184802Sjkoshy		pcd = md->pmd_classdep;
3000184802Sjkoshy		for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
3001184802Sjkoshy			pci->pm_caps  = pcd->pcd_caps;
3002184802Sjkoshy			pci->pm_class = pcd->pcd_class;
3003184802Sjkoshy			pci->pm_width = pcd->pcd_width;
3004184802Sjkoshy			pci->pm_num   = pcd->pcd_num;
3005184802Sjkoshy		}
3006145256Sjkoshy		error = copyout(&gci, arg, sizeof(gci));
3007145256Sjkoshy	}
3008145256Sjkoshy	break;
3009145256Sjkoshy
3010233628Sfabient	/*
3011233628Sfabient	 * Retrieve soft events list.
3012233628Sfabient	 */
3013233628Sfabient	case PMC_OP_GETDYNEVENTINFO:
3014233628Sfabient	{
3015233628Sfabient		enum pmc_class			cl;
3016233628Sfabient		enum pmc_event			ev;
3017233628Sfabient		struct pmc_op_getdyneventinfo	*gei;
3018233628Sfabient		struct pmc_dyn_event_descr	dev;
3019233628Sfabient		struct pmc_soft			*ps;
3020233628Sfabient		uint32_t			nevent;
3021145256Sjkoshy
3022233628Sfabient		sx_assert(&pmc_sx, SX_LOCKED);
3023233628Sfabient
3024233628Sfabient		gei = (struct pmc_op_getdyneventinfo *) arg;
3025233628Sfabient
3026233628Sfabient		if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
3027233628Sfabient			break;
3028233628Sfabient
3029233628Sfabient		/* Only SOFT class is dynamic. */
3030233628Sfabient		if (cl != PMC_CLASS_SOFT) {
3031233628Sfabient			error = EINVAL;
3032233628Sfabient			break;
3033233628Sfabient		}
3034233628Sfabient
3035233628Sfabient		nevent = 0;
3036245339Ssbruno		for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) {
3037233628Sfabient			ps = pmc_soft_ev_acquire(ev);
3038233628Sfabient			if (ps == NULL)
3039233628Sfabient				continue;
3040233628Sfabient			bcopy(&ps->ps_ev, &dev, sizeof(dev));
3041233628Sfabient			pmc_soft_ev_release(ps);
3042233628Sfabient
3043233628Sfabient			error = copyout(&dev,
3044233628Sfabient			    &gei->pm_events[nevent],
3045233628Sfabient			    sizeof(struct pmc_dyn_event_descr));
3046233628Sfabient			if (error != 0)
3047233628Sfabient				break;
3048233628Sfabient			nevent++;
3049233628Sfabient		}
3050233628Sfabient		if (error != 0)
3051233628Sfabient			break;
3052233628Sfabient
3053233628Sfabient		error = copyout(&nevent, &gei->pm_nevent,
3054233628Sfabient		    sizeof(nevent));
3055233628Sfabient	}
3056233628Sfabient	break;
3057233628Sfabient
3058145256Sjkoshy	/*
3059145256Sjkoshy	 * Get module statistics
3060145256Sjkoshy	 */
3061145256Sjkoshy
3062145256Sjkoshy	case PMC_OP_GETDRIVERSTATS:
3063145256Sjkoshy	{
3064145256Sjkoshy		struct pmc_op_getdriverstats gms;
3065145256Sjkoshy
3066145256Sjkoshy		bcopy(&pmc_stats, &gms, sizeof(gms));
3067145256Sjkoshy		error = copyout(&gms, arg, sizeof(gms));
3068145256Sjkoshy	}
3069145256Sjkoshy	break;
3070145256Sjkoshy
3071145256Sjkoshy
3072145256Sjkoshy	/*
3073145256Sjkoshy	 * Retrieve module version number
3074145256Sjkoshy	 */
3075145256Sjkoshy
3076145256Sjkoshy	case PMC_OP_GETMODULEVERSION:
3077145256Sjkoshy	{
3078147191Sjkoshy		uint32_t cv, modv;
3079147191Sjkoshy
3080147191Sjkoshy		/* retrieve the client's idea of the ABI version */
3081147191Sjkoshy		if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
3082147191Sjkoshy			break;
3083147191Sjkoshy		/* don't service clients newer than our driver */
3084147191Sjkoshy		modv = PMC_VERSION;
3085147191Sjkoshy		if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
3086147191Sjkoshy			error = EPROGMISMATCH;
3087147191Sjkoshy			break;
3088147191Sjkoshy		}
3089147191Sjkoshy		error = copyout(&modv, arg, sizeof(int));
3090145256Sjkoshy	}
3091145256Sjkoshy	break;
3092145256Sjkoshy
3093145256Sjkoshy
3094145256Sjkoshy	/*
3095145256Sjkoshy	 * Retrieve the state of all the PMCs on a given
3096145256Sjkoshy	 * CPU.
3097145256Sjkoshy	 */
3098145256Sjkoshy
3099145256Sjkoshy	case PMC_OP_GETPMCINFO:
3100145256Sjkoshy	{
3101184802Sjkoshy		int ari;
3102184802Sjkoshy		struct pmc *pm;
3103184802Sjkoshy		size_t pmcinfo_size;
3104145256Sjkoshy		uint32_t cpu, n, npmc;
3105184802Sjkoshy		struct pmc_owner *po;
3106184802Sjkoshy		struct pmc_binding pb;
3107184802Sjkoshy		struct pmc_classdep *pcd;
3108145256Sjkoshy		struct pmc_info *p, *pmcinfo;
3109145256Sjkoshy		struct pmc_op_getpmcinfo *gpi;
3110145256Sjkoshy
3111145256Sjkoshy		PMC_DOWNGRADE_SX();
3112145256Sjkoshy
3113145256Sjkoshy		gpi = (struct pmc_op_getpmcinfo *) arg;
3114145256Sjkoshy
3115145256Sjkoshy		if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
3116145256Sjkoshy			break;
3117145256Sjkoshy
3118183266Sjkoshy		if (cpu >= pmc_cpu_max()) {
3119145256Sjkoshy			error = EINVAL;
3120145256Sjkoshy			break;
3121145256Sjkoshy		}
3122145256Sjkoshy
3123183266Sjkoshy		if (!pmc_cpu_is_active(cpu)) {
3124145256Sjkoshy			error = ENXIO;
3125145256Sjkoshy			break;
3126145256Sjkoshy		}
3127145256Sjkoshy
3128145256Sjkoshy		/* switch to CPU 'cpu' */
3129145256Sjkoshy		pmc_save_cpu_binding(&pb);
3130145256Sjkoshy		pmc_select_cpu(cpu);
3131145256Sjkoshy
3132145256Sjkoshy		npmc = md->pmd_npmc;
3133145256Sjkoshy
3134145256Sjkoshy		pmcinfo_size = npmc * sizeof(struct pmc_info);
3135343350Smarkj		pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK | M_ZERO);
3136145256Sjkoshy
3137145256Sjkoshy		p = pmcinfo;
3138145256Sjkoshy
3139145256Sjkoshy		for (n = 0; n < md->pmd_npmc; n++, p++) {
3140145256Sjkoshy
3141184802Sjkoshy			pcd = pmc_ri_to_classdep(md, n, &ari);
3142184802Sjkoshy
3143184802Sjkoshy			KASSERT(pcd != NULL,
3144184802Sjkoshy			    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
3145184802Sjkoshy
3146184802Sjkoshy			if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
3147145256Sjkoshy				break;
3148145256Sjkoshy
3149145256Sjkoshy			if (PMC_ROW_DISP_IS_STANDALONE(n))
3150145256Sjkoshy				p->pm_rowdisp = PMC_DISP_STANDALONE;
3151145256Sjkoshy			else if (PMC_ROW_DISP_IS_THREAD(n))
3152145256Sjkoshy				p->pm_rowdisp = PMC_DISP_THREAD;
3153145256Sjkoshy			else
3154145256Sjkoshy				p->pm_rowdisp = PMC_DISP_FREE;
3155145256Sjkoshy
3156145256Sjkoshy			p->pm_ownerpid = -1;
3157145256Sjkoshy
3158145256Sjkoshy			if (pm == NULL)	/* no PMC associated */
3159145256Sjkoshy				continue;
3160145256Sjkoshy
3161145256Sjkoshy			po = pm->pm_owner;
3162145256Sjkoshy
3163145256Sjkoshy			KASSERT(po->po_owner != NULL,
3164145256Sjkoshy			    ("[pmc,%d] pmc_owner had a null proc pointer",
3165145256Sjkoshy				__LINE__));
3166145256Sjkoshy
3167145256Sjkoshy			p->pm_ownerpid = po->po_owner->p_pid;
3168145774Sjkoshy			p->pm_mode     = PMC_TO_MODE(pm);
3169145256Sjkoshy			p->pm_event    = pm->pm_event;
3170145256Sjkoshy			p->pm_flags    = pm->pm_flags;
3171145256Sjkoshy
3172145774Sjkoshy			if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3173145256Sjkoshy				p->pm_reloadcount =
3174145256Sjkoshy				    pm->pm_sc.pm_reloadcount;
3175145256Sjkoshy		}
3176145256Sjkoshy
3177145256Sjkoshy		pmc_restore_cpu_binding(&pb);
3178145256Sjkoshy
3179145256Sjkoshy		/* now copy out the PMC info collected */
3180145256Sjkoshy		if (error == 0)
3181145256Sjkoshy			error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
3182145256Sjkoshy
3183184205Sdes		free(pmcinfo, M_PMC);
3184145256Sjkoshy	}
3185145256Sjkoshy	break;
3186145256Sjkoshy
3187145256Sjkoshy
3188145256Sjkoshy	/*
3189145256Sjkoshy	 * Set the administrative state of a PMC.  I.e. whether
3190145256Sjkoshy	 * the PMC is to be used or not.
3191145256Sjkoshy	 */
3192145256Sjkoshy
3193145256Sjkoshy	case PMC_OP_PMCADMIN:
3194145256Sjkoshy	{
3195145256Sjkoshy		int cpu, ri;
3196145256Sjkoshy		enum pmc_state request;
3197145256Sjkoshy		struct pmc_cpu *pc;
3198145256Sjkoshy		struct pmc_hw *phw;
3199145256Sjkoshy		struct pmc_op_pmcadmin pma;
3200145256Sjkoshy		struct pmc_binding pb;
3201145256Sjkoshy
3202145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3203145256Sjkoshy
3204145256Sjkoshy		KASSERT(td == curthread,
3205145256Sjkoshy		    ("[pmc,%d] td != curthread", __LINE__));
3206145256Sjkoshy
3207164033Srwatson		error = priv_check(td, PRIV_PMC_MANAGE);
3208164033Srwatson		if (error)
3209145256Sjkoshy			break;
3210145256Sjkoshy
3211145256Sjkoshy		if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
3212145256Sjkoshy			break;
3213145256Sjkoshy
3214145256Sjkoshy		cpu = pma.pm_cpu;
3215145256Sjkoshy
3216183266Sjkoshy		if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
3217145256Sjkoshy			error = EINVAL;
3218145256Sjkoshy			break;
3219145256Sjkoshy		}
3220145256Sjkoshy
3221183266Sjkoshy		if (!pmc_cpu_is_active(cpu)) {
3222145256Sjkoshy			error = ENXIO;
3223145256Sjkoshy			break;
3224145256Sjkoshy		}
3225145256Sjkoshy
3226145256Sjkoshy		request = pma.pm_state;
3227145256Sjkoshy
3228145256Sjkoshy		if (request != PMC_STATE_DISABLED &&
3229145256Sjkoshy		    request != PMC_STATE_FREE) {
3230145256Sjkoshy			error = EINVAL;
3231145256Sjkoshy			break;
3232145256Sjkoshy		}
3233145256Sjkoshy
3234145256Sjkoshy		ri = pma.pm_pmc; /* pmc id == row index */
3235145256Sjkoshy		if (ri < 0 || ri >= (int) md->pmd_npmc) {
3236145256Sjkoshy			error = EINVAL;
3237145256Sjkoshy			break;
3238145256Sjkoshy		}
3239145256Sjkoshy
3240145256Sjkoshy		/*
3241145256Sjkoshy		 * We can't disable a PMC with a row-index allocated
3242145256Sjkoshy		 * for process virtual PMCs.
3243145256Sjkoshy		 */
3244145256Sjkoshy
3245145256Sjkoshy		if (PMC_ROW_DISP_IS_THREAD(ri) &&
3246145256Sjkoshy		    request == PMC_STATE_DISABLED) {
3247145256Sjkoshy			error = EBUSY;
3248145256Sjkoshy			break;
3249145256Sjkoshy		}
3250145256Sjkoshy
3251145256Sjkoshy		/*
3252145256Sjkoshy		 * otherwise, this PMC on this CPU is either free or
3253145256Sjkoshy		 * in system-wide mode.
3254145256Sjkoshy		 */
3255145256Sjkoshy
3256145256Sjkoshy		pmc_save_cpu_binding(&pb);
3257145256Sjkoshy		pmc_select_cpu(cpu);
3258145256Sjkoshy
3259145256Sjkoshy		pc  = pmc_pcpu[cpu];
3260145256Sjkoshy		phw = pc->pc_hwpmcs[ri];
3261145256Sjkoshy
3262145256Sjkoshy		/*
3263145256Sjkoshy		 * XXX do we need some kind of 'forced' disable?
3264145256Sjkoshy		 */
3265145256Sjkoshy
3266145256Sjkoshy		if (phw->phw_pmc == NULL) {
3267145256Sjkoshy			if (request == PMC_STATE_DISABLED &&
3268145256Sjkoshy			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
3269145256Sjkoshy				phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
3270145256Sjkoshy				PMC_MARK_ROW_STANDALONE(ri);
3271145256Sjkoshy			} else if (request == PMC_STATE_FREE &&
3272145256Sjkoshy			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
3273145256Sjkoshy				phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
3274145256Sjkoshy				PMC_UNMARK_ROW_STANDALONE(ri);
3275145256Sjkoshy			}
3276145256Sjkoshy			/* other cases are a no-op */
3277145256Sjkoshy		} else
3278145256Sjkoshy			error = EBUSY;
3279145256Sjkoshy
3280145256Sjkoshy		pmc_restore_cpu_binding(&pb);
3281145256Sjkoshy	}
3282145256Sjkoshy	break;
3283145256Sjkoshy
3284145256Sjkoshy
3285145256Sjkoshy	/*
3286145256Sjkoshy	 * Allocate a PMC.
3287145256Sjkoshy	 */
3288145256Sjkoshy
3289145256Sjkoshy	case PMC_OP_PMCALLOCATE:
3290145256Sjkoshy	{
3291184802Sjkoshy		int adjri, n;
3292184802Sjkoshy		u_int cpu;
3293145256Sjkoshy		uint32_t caps;
3294184802Sjkoshy		struct pmc *pmc;
3295145256Sjkoshy		enum pmc_mode mode;
3296145774Sjkoshy		struct pmc_hw *phw;
3297184802Sjkoshy		struct pmc_binding pb;
3298184802Sjkoshy		struct pmc_classdep *pcd;
3299145256Sjkoshy		struct pmc_op_pmcallocate pa;
3300145256Sjkoshy
3301145256Sjkoshy		if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
3302145256Sjkoshy			break;
3303145256Sjkoshy
3304145256Sjkoshy		caps = pa.pm_caps;
3305145256Sjkoshy		mode = pa.pm_mode;
3306145256Sjkoshy		cpu  = pa.pm_cpu;
3307145256Sjkoshy
3308145256Sjkoshy		if ((mode != PMC_MODE_SS  &&  mode != PMC_MODE_SC  &&
3309145256Sjkoshy		     mode != PMC_MODE_TS  &&  mode != PMC_MODE_TC) ||
3310183266Sjkoshy		    (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
3311145256Sjkoshy			error = EINVAL;
3312145256Sjkoshy			break;
3313145256Sjkoshy		}
3314145256Sjkoshy
3315145256Sjkoshy		/*
3316145256Sjkoshy		 * Virtual PMCs should only ask for a default CPU.
3317145256Sjkoshy		 * System mode PMCs need to specify a non-default CPU.
3318145256Sjkoshy		 */
3319145256Sjkoshy
3320145256Sjkoshy		if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3321145256Sjkoshy		    (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3322145256Sjkoshy			error = EINVAL;
3323145256Sjkoshy			break;
3324145256Sjkoshy		}
3325145256Sjkoshy
3326145256Sjkoshy		/*
3327183266Sjkoshy		 * Check that an inactive CPU is not being asked for.
3328145256Sjkoshy		 */
3329145256Sjkoshy
3330183266Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3331145256Sjkoshy			error = ENXIO;
3332145256Sjkoshy			break;
3333145256Sjkoshy		}
3334145256Sjkoshy
3335145256Sjkoshy		/*
3336145256Sjkoshy		 * Refuse an allocation for a system-wide PMC if this
3337145256Sjkoshy		 * process has been jailed, or if this process lacks
3338145256Sjkoshy		 * super-user credentials and the sysctl tunable
3339145256Sjkoshy		 * 'security.bsd.unprivileged_syspmcs' is zero.
3340145256Sjkoshy		 */
3341145256Sjkoshy
3342145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode)) {
3343164033Srwatson			if (jailed(curthread->td_ucred)) {
3344145256Sjkoshy				error = EPERM;
3345164033Srwatson				break;
3346164033Srwatson			}
3347164033Srwatson			if (!pmc_unprivileged_syspmcs) {
3348164033Srwatson				error = priv_check(curthread,
3349164033Srwatson				    PRIV_PMC_SYSTEM);
3350164033Srwatson				if (error)
3351164033Srwatson					break;
3352164033Srwatson			}
3353145256Sjkoshy		}
3354145256Sjkoshy
3355145256Sjkoshy		/*
3356145256Sjkoshy		 * Look for valid values for 'pm_flags'
3357145256Sjkoshy		 */
3358145256Sjkoshy
3359147191Sjkoshy		if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3360174395Sjkoshy		    PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3361145256Sjkoshy			error = EINVAL;
3362145256Sjkoshy			break;
3363145256Sjkoshy		}
3364145256Sjkoshy
3365147191Sjkoshy		/* process logging options are not allowed for system PMCs */
3366147191Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3367147191Sjkoshy		    (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3368147191Sjkoshy			error = EINVAL;
3369147191Sjkoshy			break;
3370147191Sjkoshy		}
3371147191Sjkoshy
3372145256Sjkoshy		/*
3373145256Sjkoshy		 * All sampling mode PMCs need to be able to interrupt the
3374145256Sjkoshy		 * CPU.
3375145256Sjkoshy		 */
3376147191Sjkoshy		if (PMC_IS_SAMPLING_MODE(mode))
3377145256Sjkoshy			caps |= PMC_CAP_INTERRUPT;
3378145256Sjkoshy
3379149374Sjkoshy		/* A valid class specifier should have been passed in. */
3380149374Sjkoshy		for (n = 0; n < md->pmd_nclass; n++)
3381184802Sjkoshy			if (md->pmd_classdep[n].pcd_class == pa.pm_class)
3382149374Sjkoshy				break;
3383149374Sjkoshy		if (n == md->pmd_nclass) {
3384149374Sjkoshy			error = EINVAL;
3385149374Sjkoshy			break;
3386149374Sjkoshy		}
3387149374Sjkoshy
3388149374Sjkoshy		/* The requested PMC capabilities should be feasible. */
3389184802Sjkoshy		if ((md->pmd_classdep[n].pcd_caps & caps) != caps) {
3390149374Sjkoshy			error = EOPNOTSUPP;
3391149374Sjkoshy			break;
3392149374Sjkoshy		}
3393149374Sjkoshy
3394282658Sjhb		PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3395145256Sjkoshy		    pa.pm_ev, caps, mode, cpu);
3396145256Sjkoshy
3397145256Sjkoshy		pmc = pmc_allocate_pmc_descriptor();
3398145774Sjkoshy		pmc->pm_id    = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3399145774Sjkoshy		    PMC_ID_INVALID);
3400145256Sjkoshy		pmc->pm_event = pa.pm_ev;
3401145256Sjkoshy		pmc->pm_state = PMC_STATE_FREE;
3402145256Sjkoshy		pmc->pm_caps  = caps;
3403145256Sjkoshy		pmc->pm_flags = pa.pm_flags;
3404145256Sjkoshy
3405145256Sjkoshy		/* switch thread to CPU 'cpu' */
3406145256Sjkoshy		pmc_save_cpu_binding(&pb);
3407145256Sjkoshy
3408145256Sjkoshy#define	PMC_IS_SHAREABLE_PMC(cpu, n)				\
3409145256Sjkoshy	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &		\
3410145256Sjkoshy	 PMC_PHW_FLAG_IS_SHAREABLE)
3411145256Sjkoshy#define	PMC_IS_UNALLOCATED(cpu, n)				\
3412145256Sjkoshy	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3413145256Sjkoshy
3414145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode)) {
3415145256Sjkoshy			pmc_select_cpu(cpu);
3416184802Sjkoshy			for (n = 0; n < (int) md->pmd_npmc; n++) {
3417184802Sjkoshy				pcd = pmc_ri_to_classdep(md, n, &adjri);
3418145256Sjkoshy				if (pmc_can_allocate_row(n, mode) == 0 &&
3419145256Sjkoshy				    pmc_can_allocate_rowindex(
3420145774Sjkoshy					    curthread->td_proc, n, cpu) == 0 &&
3421145256Sjkoshy				    (PMC_IS_UNALLOCATED(cpu, n) ||
3422145256Sjkoshy				     PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3423184802Sjkoshy				    pcd->pcd_allocate_pmc(cpu, adjri, pmc,
3424145256Sjkoshy					&pa) == 0)
3425145256Sjkoshy					break;
3426184802Sjkoshy			}
3427145256Sjkoshy		} else {
3428145256Sjkoshy			/* Process virtual mode */
3429145256Sjkoshy			for (n = 0; n < (int) md->pmd_npmc; n++) {
3430184802Sjkoshy				pcd = pmc_ri_to_classdep(md, n, &adjri);
3431145256Sjkoshy				if (pmc_can_allocate_row(n, mode) == 0 &&
3432145256Sjkoshy				    pmc_can_allocate_rowindex(
3433145774Sjkoshy					    curthread->td_proc, n,
3434145774Sjkoshy					    PMC_CPU_ANY) == 0 &&
3435184802Sjkoshy				    pcd->pcd_allocate_pmc(curthread->td_oncpu,
3436184802Sjkoshy					adjri, pmc, &pa) == 0)
3437145256Sjkoshy					break;
3438145256Sjkoshy			}
3439145256Sjkoshy		}
3440145256Sjkoshy
3441145256Sjkoshy#undef	PMC_IS_UNALLOCATED
3442145256Sjkoshy#undef	PMC_IS_SHAREABLE_PMC
3443145256Sjkoshy
3444145256Sjkoshy		pmc_restore_cpu_binding(&pb);
3445145256Sjkoshy
3446145256Sjkoshy		if (n == (int) md->pmd_npmc) {
3447145256Sjkoshy			pmc_destroy_pmc_descriptor(pmc);
3448145256Sjkoshy			pmc = NULL;
3449145256Sjkoshy			error = EINVAL;
3450145256Sjkoshy			break;
3451145256Sjkoshy		}
3452145256Sjkoshy
3453145774Sjkoshy		/* Fill in the correct value in the ID field */
3454145774Sjkoshy		pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3455145256Sjkoshy
3456282658Sjhb		PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3457145774Sjkoshy		    pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3458145774Sjkoshy
3459147191Sjkoshy		/* Process mode PMCs with logging enabled need log files */
3460147191Sjkoshy		if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3461147191Sjkoshy			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3462147191Sjkoshy
3463147191Sjkoshy		/* All system mode sampling PMCs require a log file */
3464147191Sjkoshy		if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3465147191Sjkoshy			pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3466147191Sjkoshy
3467145256Sjkoshy		/*
3468145256Sjkoshy		 * Configure global pmc's immediately
3469145256Sjkoshy		 */
3470145256Sjkoshy
3471145774Sjkoshy		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3472145774Sjkoshy
3473145774Sjkoshy			pmc_save_cpu_binding(&pb);
3474145774Sjkoshy			pmc_select_cpu(cpu);
3475145774Sjkoshy
3476145774Sjkoshy			phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3477184802Sjkoshy			pcd = pmc_ri_to_classdep(md, n, &adjri);
3478145774Sjkoshy
3479145774Sjkoshy			if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3480184802Sjkoshy			    (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3481184802Sjkoshy				(void) pcd->pcd_release_pmc(cpu, adjri, pmc);
3482145256Sjkoshy				pmc_destroy_pmc_descriptor(pmc);
3483145256Sjkoshy				pmc = NULL;
3484145774Sjkoshy				pmc_restore_cpu_binding(&pb);
3485145774Sjkoshy				error = EPERM;
3486145256Sjkoshy				break;
3487145256Sjkoshy			}
3488145256Sjkoshy
3489145774Sjkoshy			pmc_restore_cpu_binding(&pb);
3490145774Sjkoshy		}
3491145256Sjkoshy
3492145256Sjkoshy		pmc->pm_state    = PMC_STATE_ALLOCATED;
3493145256Sjkoshy
3494145256Sjkoshy		/*
3495145256Sjkoshy		 * mark row disposition
3496145256Sjkoshy		 */
3497145256Sjkoshy
3498145256Sjkoshy		if (PMC_IS_SYSTEM_MODE(mode))
3499145256Sjkoshy			PMC_MARK_ROW_STANDALONE(n);
3500145256Sjkoshy		else
3501145256Sjkoshy			PMC_MARK_ROW_THREAD(n);
3502145256Sjkoshy
3503145256Sjkoshy		/*
3504145256Sjkoshy		 * Register this PMC with the current thread as its owner.
3505145256Sjkoshy		 */
3506145256Sjkoshy
3507145256Sjkoshy		if ((error =
3508145256Sjkoshy		    pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3509145256Sjkoshy			pmc_release_pmc_descriptor(pmc);
3510273236Smarkj			pmc_destroy_pmc_descriptor(pmc);
3511145256Sjkoshy			pmc = NULL;
3512145256Sjkoshy			break;
3513145256Sjkoshy		}
3514145256Sjkoshy
3515145256Sjkoshy		/*
3516145256Sjkoshy		 * Return the allocated index.
3517145256Sjkoshy		 */
3518145256Sjkoshy
3519145774Sjkoshy		pa.pm_pmcid = pmc->pm_id;
3520145256Sjkoshy
3521145256Sjkoshy		error = copyout(&pa, arg, sizeof(pa));
3522145256Sjkoshy	}
3523145256Sjkoshy	break;
3524145256Sjkoshy
3525145256Sjkoshy
3526145256Sjkoshy	/*
3527145256Sjkoshy	 * Attach a PMC to a process.
3528145256Sjkoshy	 */
3529145256Sjkoshy
3530145256Sjkoshy	case PMC_OP_PMCATTACH:
3531145256Sjkoshy	{
3532145256Sjkoshy		struct pmc *pm;
3533145256Sjkoshy		struct proc *p;
3534145256Sjkoshy		struct pmc_op_pmcattach a;
3535145256Sjkoshy
3536145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3537145256Sjkoshy
3538145256Sjkoshy		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3539145256Sjkoshy			break;
3540145256Sjkoshy
3541145256Sjkoshy		if (a.pm_pid < 0) {
3542145256Sjkoshy			error = EINVAL;
3543145256Sjkoshy			break;
3544145256Sjkoshy		} else if (a.pm_pid == 0)
3545145256Sjkoshy			a.pm_pid = td->td_proc->p_pid;
3546145256Sjkoshy
3547145256Sjkoshy		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3548145256Sjkoshy			break;
3549145256Sjkoshy
3550145774Sjkoshy		if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3551145256Sjkoshy			error = EINVAL;
3552145256Sjkoshy			break;
3553145256Sjkoshy		}
3554145256Sjkoshy
3555145256Sjkoshy		/* PMCs may be (re)attached only when allocated or stopped */
3556145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) {
3557145256Sjkoshy			error = EBUSY;
3558145256Sjkoshy			break;
3559145256Sjkoshy		} else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3560145256Sjkoshy		    pm->pm_state != PMC_STATE_STOPPED) {
3561145256Sjkoshy			error = EINVAL;
3562145256Sjkoshy			break;
3563145256Sjkoshy		}
3564145256Sjkoshy
3565145256Sjkoshy		/* lookup pid */
3566145256Sjkoshy		if ((p = pfind(a.pm_pid)) == NULL) {
3567145256Sjkoshy			error = ESRCH;
3568145256Sjkoshy			break;
3569145256Sjkoshy		}
3570145256Sjkoshy
3571145256Sjkoshy		/*
3572145256Sjkoshy		 * Ignore processes that are working on exiting.
3573145256Sjkoshy		 */
3574145256Sjkoshy		if (p->p_flag & P_WEXIT) {
3575145256Sjkoshy			error = ESRCH;
3576145256Sjkoshy			PROC_UNLOCK(p);	/* pfind() returns a locked process */
3577145256Sjkoshy			break;
3578145256Sjkoshy		}
3579145256Sjkoshy
3580145256Sjkoshy		/*
3581145256Sjkoshy		 * we are allowed to attach a PMC to a process if
3582145256Sjkoshy		 * we can debug it.
3583145256Sjkoshy		 */
3584145256Sjkoshy		error = p_candebug(curthread, p);
3585145256Sjkoshy
3586145256Sjkoshy		PROC_UNLOCK(p);
3587145256Sjkoshy
3588145256Sjkoshy		if (error == 0)
3589145256Sjkoshy			error = pmc_attach_process(p, pm);
3590145256Sjkoshy	}
3591145256Sjkoshy	break;
3592145256Sjkoshy
3593145256Sjkoshy
3594145256Sjkoshy	/*
3595145256Sjkoshy	 * Detach an attached PMC from a process.
3596145256Sjkoshy	 */
3597145256Sjkoshy
3598145256Sjkoshy	case PMC_OP_PMCDETACH:
3599145256Sjkoshy	{
3600145256Sjkoshy		struct pmc *pm;
3601145256Sjkoshy		struct proc *p;
3602145256Sjkoshy		struct pmc_op_pmcattach a;
3603145256Sjkoshy
3604145256Sjkoshy		if ((error = copyin(arg, &a, sizeof(a))) != 0)
3605145256Sjkoshy			break;
3606145256Sjkoshy
3607145256Sjkoshy		if (a.pm_pid < 0) {
3608145256Sjkoshy			error = EINVAL;
3609145256Sjkoshy			break;
3610145256Sjkoshy		} else if (a.pm_pid == 0)
3611145256Sjkoshy			a.pm_pid = td->td_proc->p_pid;
3612145256Sjkoshy
3613145256Sjkoshy		if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3614145256Sjkoshy			break;
3615145256Sjkoshy
3616145256Sjkoshy		if ((p = pfind(a.pm_pid)) == NULL) {
3617145256Sjkoshy			error = ESRCH;
3618145256Sjkoshy			break;
3619145256Sjkoshy		}
3620145256Sjkoshy
3621145256Sjkoshy		/*
3622145256Sjkoshy		 * Treat processes that are in the process of exiting
3623145256Sjkoshy		 * as if they were not present.
3624145256Sjkoshy		 */
3625145256Sjkoshy
3626145256Sjkoshy		if (p->p_flag & P_WEXIT)
3627145256Sjkoshy			error = ESRCH;
3628145256Sjkoshy
3629145256Sjkoshy		PROC_UNLOCK(p);	/* pfind() returns a locked process */
3630145256Sjkoshy
3631145256Sjkoshy		if (error == 0)
3632145256Sjkoshy			error = pmc_detach_process(p, pm);
3633145256Sjkoshy	}
3634145256Sjkoshy	break;
3635145256Sjkoshy
3636145256Sjkoshy
3637145256Sjkoshy	/*
3638147191Sjkoshy	 * Retrieve the MSR number associated with the counter
3639147191Sjkoshy	 * 'pmc_id'.  This allows processes to directly use RDPMC
3640147191Sjkoshy	 * instructions to read their PMCs, without the overhead of a
3641147191Sjkoshy	 * system call.
3642147191Sjkoshy	 */
3643147191Sjkoshy
3644147191Sjkoshy	case PMC_OP_PMCGETMSR:
3645147191Sjkoshy	{
3646184802Sjkoshy		int adjri, ri;
3647184802Sjkoshy		struct pmc *pm;
3648147191Sjkoshy		struct pmc_target *pt;
3649147191Sjkoshy		struct pmc_op_getmsr gm;
3650184802Sjkoshy		struct pmc_classdep *pcd;
3651147191Sjkoshy
3652147191Sjkoshy		PMC_DOWNGRADE_SX();
3653147191Sjkoshy
3654147191Sjkoshy		if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3655147191Sjkoshy			break;
3656147191Sjkoshy
3657147191Sjkoshy		if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3658147191Sjkoshy			break;
3659147191Sjkoshy
3660147191Sjkoshy		/*
3661147191Sjkoshy		 * The allocated PMC has to be a process virtual PMC,
3662147191Sjkoshy		 * i.e., of type MODE_T[CS].  Global PMCs can only be
3663147191Sjkoshy		 * read using the PMCREAD operation since they may be
3664147191Sjkoshy		 * allocated on a different CPU than the one we could
3665147191Sjkoshy		 * be running on at the time of the RDPMC instruction.
3666147191Sjkoshy		 *
3667147191Sjkoshy		 * The GETMSR operation is not allowed for PMCs that
3668147191Sjkoshy		 * are inherited across processes.
3669147191Sjkoshy		 */
3670147191Sjkoshy
3671147191Sjkoshy		if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3672147191Sjkoshy		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
3673147191Sjkoshy			error = EINVAL;
3674147191Sjkoshy			break;
3675147191Sjkoshy		}
3676147191Sjkoshy
3677147191Sjkoshy		/*
3678147191Sjkoshy		 * It only makes sense to use a RDPMC (or its
3679147191Sjkoshy		 * equivalent instruction on non-x86 architectures) on
3680147191Sjkoshy		 * a process that has allocated and attached a PMC to
3681147191Sjkoshy		 * itself.  Conversely the PMC is only allowed to have
3682147191Sjkoshy		 * one process attached to it -- its owner.
3683147191Sjkoshy		 */
3684147191Sjkoshy
3685147191Sjkoshy		if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3686147191Sjkoshy		    LIST_NEXT(pt, pt_next) != NULL ||
3687147191Sjkoshy		    pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3688147191Sjkoshy			error = EINVAL;
3689147191Sjkoshy			break;
3690147191Sjkoshy		}
3691147191Sjkoshy
3692147191Sjkoshy		ri = PMC_TO_ROWINDEX(pm);
3693184802Sjkoshy		pcd = pmc_ri_to_classdep(md, ri, &adjri);
3694147191Sjkoshy
3695184802Sjkoshy		/* PMC class has no 'GETMSR' support */
3696184802Sjkoshy		if (pcd->pcd_get_msr == NULL) {
3697184802Sjkoshy			error = ENOSYS;
3698147191Sjkoshy			break;
3699184802Sjkoshy		}
3700147191Sjkoshy
3701184802Sjkoshy		if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
3702184802Sjkoshy			break;
3703184802Sjkoshy
3704147191Sjkoshy		if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3705147191Sjkoshy			break;
3706147191Sjkoshy
3707147191Sjkoshy		/*
3708147191Sjkoshy		 * Mark our process as using MSRs.  Update machine
3709147191Sjkoshy		 * state using a forced context switch.
3710147191Sjkoshy		 */
3711147191Sjkoshy
3712147191Sjkoshy		pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3713147191Sjkoshy		pmc_force_context_switch();
3714147191Sjkoshy
3715147191Sjkoshy	}
3716147191Sjkoshy	break;
3717147191Sjkoshy
3718147191Sjkoshy	/*
3719145256Sjkoshy	 * Release an allocated PMC
3720145256Sjkoshy	 */
3721145256Sjkoshy
3722145256Sjkoshy	case PMC_OP_PMCRELEASE:
3723145256Sjkoshy	{
3724145256Sjkoshy		pmc_id_t pmcid;
3725145256Sjkoshy		struct pmc *pm;
3726145256Sjkoshy		struct pmc_owner *po;
3727145256Sjkoshy		struct pmc_op_simple sp;
3728145256Sjkoshy
3729145256Sjkoshy		/*
3730145256Sjkoshy		 * Find PMC pointer for the named PMC.
3731145256Sjkoshy		 *
3732145256Sjkoshy		 * Use pmc_release_pmc_descriptor() to switch off the
3733145256Sjkoshy		 * PMC, remove all its target threads, and remove the
3734145256Sjkoshy		 * PMC from its owner's list.
3735145256Sjkoshy		 *
3736145256Sjkoshy		 * Remove the owner record if this is the last PMC
3737145256Sjkoshy		 * owned.
3738145256Sjkoshy		 *
3739145256Sjkoshy		 * Free up space.
3740145256Sjkoshy		 */
3741145256Sjkoshy
3742145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3743145256Sjkoshy			break;
3744145256Sjkoshy
3745145256Sjkoshy		pmcid = sp.pm_pmcid;
3746145256Sjkoshy
3747145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3748145256Sjkoshy			break;
3749145256Sjkoshy
3750145256Sjkoshy		po = pm->pm_owner;
3751145256Sjkoshy		pmc_release_pmc_descriptor(pm);
3752145256Sjkoshy		pmc_maybe_remove_owner(po);
3753273236Smarkj		pmc_destroy_pmc_descriptor(pm);
3754145256Sjkoshy	}
3755145256Sjkoshy	break;
3756145256Sjkoshy
3757145256Sjkoshy
3758145256Sjkoshy	/*
3759145256Sjkoshy	 * Read and/or write a PMC.
3760145256Sjkoshy	 */
3761145256Sjkoshy
3762145256Sjkoshy	case PMC_OP_PMCRW:
3763145256Sjkoshy	{
3764184802Sjkoshy		int adjri;
3765184802Sjkoshy		struct pmc *pm;
3766145256Sjkoshy		uint32_t cpu, ri;
3767184802Sjkoshy		pmc_value_t oldvalue;
3768184802Sjkoshy		struct pmc_binding pb;
3769184802Sjkoshy		struct pmc_op_pmcrw prw;
3770184802Sjkoshy		struct pmc_classdep *pcd;
3771145256Sjkoshy		struct pmc_op_pmcrw *pprw;
3772145256Sjkoshy
3773145256Sjkoshy		PMC_DOWNGRADE_SX();
3774145256Sjkoshy
3775145256Sjkoshy		if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3776145256Sjkoshy			break;
3777145256Sjkoshy
3778145301Simp		ri = 0;
3779282658Sjhb		PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3780145256Sjkoshy		    prw.pm_flags);
3781145256Sjkoshy
3782145256Sjkoshy		/* must have at least one flag set */
3783145256Sjkoshy		if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3784145256Sjkoshy			error = EINVAL;
3785145256Sjkoshy			break;
3786145256Sjkoshy		}
3787145256Sjkoshy
3788145256Sjkoshy		/* locate pmc descriptor */
3789145256Sjkoshy		if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3790145256Sjkoshy			break;
3791145256Sjkoshy
3792145256Sjkoshy		/* Can't read a PMC that hasn't been started. */
3793145256Sjkoshy		if (pm->pm_state != PMC_STATE_ALLOCATED &&
3794145256Sjkoshy		    pm->pm_state != PMC_STATE_STOPPED &&
3795145256Sjkoshy		    pm->pm_state != PMC_STATE_RUNNING) {
3796145256Sjkoshy			error = EINVAL;
3797145256Sjkoshy			break;
3798145256Sjkoshy		}
3799145256Sjkoshy
3800145256Sjkoshy		/* writing a new value is allowed only for 'STOPPED' pmcs */
3801145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING &&
3802145256Sjkoshy		    (prw.pm_flags & PMC_F_NEWVALUE)) {
3803145256Sjkoshy			error = EBUSY;
3804145256Sjkoshy			break;
3805145256Sjkoshy		}
3806145256Sjkoshy
3807145774Sjkoshy		if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3808145256Sjkoshy
3809145774Sjkoshy			/*
3810145774Sjkoshy			 * If this PMC is attached to its owner (i.e.,
3811145774Sjkoshy			 * the process requesting this operation) and
3812145774Sjkoshy			 * is running, then attempt to get an
3813145774Sjkoshy			 * upto-date reading from hardware for a READ.
3814145774Sjkoshy			 * Writes are only allowed when the PMC is
3815145774Sjkoshy			 * stopped, so only update the saved value
3816145774Sjkoshy			 * field.
3817145774Sjkoshy			 *
3818145774Sjkoshy			 * If the PMC is not running, or is not
3819145774Sjkoshy			 * attached to its owner, read/write to the
3820145774Sjkoshy			 * savedvalue field.
3821145774Sjkoshy			 */
3822145774Sjkoshy
3823145774Sjkoshy			ri = PMC_TO_ROWINDEX(pm);
3824184802Sjkoshy			pcd = pmc_ri_to_classdep(md, ri, &adjri);
3825145774Sjkoshy
3826145256Sjkoshy			mtx_pool_lock_spin(pmc_mtxpool, pm);
3827145774Sjkoshy			cpu = curthread->td_oncpu;
3828145774Sjkoshy
3829145774Sjkoshy			if (prw.pm_flags & PMC_F_OLDVALUE) {
3830145774Sjkoshy				if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3831145774Sjkoshy				    (pm->pm_state == PMC_STATE_RUNNING))
3832184802Sjkoshy					error = (*pcd->pcd_read_pmc)(cpu, adjri,
3833145774Sjkoshy					    &oldvalue);
3834145774Sjkoshy				else
3835145774Sjkoshy					oldvalue = pm->pm_gv.pm_savedvalue;
3836145774Sjkoshy			}
3837145256Sjkoshy			if (prw.pm_flags & PMC_F_NEWVALUE)
3838145256Sjkoshy				pm->pm_gv.pm_savedvalue = prw.pm_value;
3839145774Sjkoshy
3840145256Sjkoshy			mtx_pool_unlock_spin(pmc_mtxpool, pm);
3841145256Sjkoshy
3842145256Sjkoshy		} else { /* System mode PMCs */
3843145774Sjkoshy			cpu = PMC_TO_CPU(pm);
3844145774Sjkoshy			ri  = PMC_TO_ROWINDEX(pm);
3845184802Sjkoshy			pcd = pmc_ri_to_classdep(md, ri, &adjri);
3846145256Sjkoshy
3847183266Sjkoshy			if (!pmc_cpu_is_active(cpu)) {
3848145256Sjkoshy				error = ENXIO;
3849145256Sjkoshy				break;
3850145256Sjkoshy			}
3851145256Sjkoshy
3852145256Sjkoshy			/* move this thread to CPU 'cpu' */
3853145256Sjkoshy			pmc_save_cpu_binding(&pb);
3854145256Sjkoshy			pmc_select_cpu(cpu);
3855145256Sjkoshy
3856145774Sjkoshy			critical_enter();
3857145256Sjkoshy			/* save old value */
3858145256Sjkoshy			if (prw.pm_flags & PMC_F_OLDVALUE)
3859184802Sjkoshy				if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
3860145256Sjkoshy					 &oldvalue)))
3861145256Sjkoshy					goto error;
3862145256Sjkoshy			/* write out new value */
3863145256Sjkoshy			if (prw.pm_flags & PMC_F_NEWVALUE)
3864184802Sjkoshy				error = (*pcd->pcd_write_pmc)(cpu, adjri,
3865145256Sjkoshy				    prw.pm_value);
3866145256Sjkoshy		error:
3867145774Sjkoshy			critical_exit();
3868145256Sjkoshy			pmc_restore_cpu_binding(&pb);
3869145256Sjkoshy			if (error)
3870145256Sjkoshy				break;
3871145256Sjkoshy		}
3872145256Sjkoshy
3873145256Sjkoshy		pprw = (struct pmc_op_pmcrw *) arg;
3874145256Sjkoshy
3875282641Sjhb#ifdef	HWPMC_DEBUG
3876145256Sjkoshy		if (prw.pm_flags & PMC_F_NEWVALUE)
3877282658Sjhb			PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3878145256Sjkoshy			    ri, prw.pm_value, oldvalue);
3879156778Sjkoshy		else if (prw.pm_flags & PMC_F_OLDVALUE)
3880282658Sjhb			PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3881145256Sjkoshy#endif
3882145256Sjkoshy
3883145256Sjkoshy		/* return old value if requested */
3884145256Sjkoshy		if (prw.pm_flags & PMC_F_OLDVALUE)
3885145256Sjkoshy			if ((error = copyout(&oldvalue, &pprw->pm_value,
3886145256Sjkoshy				 sizeof(prw.pm_value))))
3887145256Sjkoshy				break;
3888145256Sjkoshy
3889145256Sjkoshy	}
3890145256Sjkoshy	break;
3891145256Sjkoshy
3892145256Sjkoshy
3893145256Sjkoshy	/*
3894145256Sjkoshy	 * Set the sampling rate for a sampling mode PMC and the
3895145256Sjkoshy	 * initial count for a counting mode PMC.
3896145256Sjkoshy	 */
3897145256Sjkoshy
3898145256Sjkoshy	case PMC_OP_PMCSETCOUNT:
3899145256Sjkoshy	{
3900145256Sjkoshy		struct pmc *pm;
3901145256Sjkoshy		struct pmc_op_pmcsetcount sc;
3902145256Sjkoshy
3903145256Sjkoshy		PMC_DOWNGRADE_SX();
3904145256Sjkoshy
3905145256Sjkoshy		if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3906145256Sjkoshy			break;
3907145256Sjkoshy
3908145256Sjkoshy		if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3909145256Sjkoshy			break;
3910145256Sjkoshy
3911145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) {
3912145256Sjkoshy			error = EBUSY;
3913145256Sjkoshy			break;
3914145256Sjkoshy		}
3915145256Sjkoshy
3916145774Sjkoshy		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3917145256Sjkoshy			pm->pm_sc.pm_reloadcount = sc.pm_count;
3918145256Sjkoshy		else
3919145256Sjkoshy			pm->pm_sc.pm_initial = sc.pm_count;
3920145256Sjkoshy	}
3921145256Sjkoshy	break;
3922145256Sjkoshy
3923145256Sjkoshy
3924145256Sjkoshy	/*
3925145256Sjkoshy	 * Start a PMC.
3926145256Sjkoshy	 */
3927145256Sjkoshy
3928145256Sjkoshy	case PMC_OP_PMCSTART:
3929145256Sjkoshy	{
3930145256Sjkoshy		pmc_id_t pmcid;
3931145256Sjkoshy		struct pmc *pm;
3932145256Sjkoshy		struct pmc_op_simple sp;
3933145256Sjkoshy
3934145256Sjkoshy		sx_assert(&pmc_sx, SX_XLOCKED);
3935145256Sjkoshy
3936145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3937145256Sjkoshy			break;
3938145256Sjkoshy
3939145256Sjkoshy		pmcid = sp.pm_pmcid;
3940145256Sjkoshy
3941145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3942145256Sjkoshy			break;
3943145256Sjkoshy
3944145774Sjkoshy		KASSERT(pmcid == pm->pm_id,
3945145774Sjkoshy		    ("[pmc,%d] pmcid %x != id %x", __LINE__,
3946145774Sjkoshy			pm->pm_id, pmcid));
3947145256Sjkoshy
3948145256Sjkoshy		if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3949145256Sjkoshy			break;
3950145256Sjkoshy		else if (pm->pm_state != PMC_STATE_STOPPED &&
3951145256Sjkoshy		    pm->pm_state != PMC_STATE_ALLOCATED) {
3952145256Sjkoshy			error = EINVAL;
3953145256Sjkoshy			break;
3954145256Sjkoshy		}
3955145256Sjkoshy
3956145256Sjkoshy		error = pmc_start(pm);
3957145256Sjkoshy	}
3958145256Sjkoshy	break;
3959145256Sjkoshy
3960145256Sjkoshy
3961145256Sjkoshy	/*
3962145256Sjkoshy	 * Stop a PMC.
3963145256Sjkoshy	 */
3964145256Sjkoshy
3965145256Sjkoshy	case PMC_OP_PMCSTOP:
3966145256Sjkoshy	{
3967145256Sjkoshy		pmc_id_t pmcid;
3968145256Sjkoshy		struct pmc *pm;
3969145256Sjkoshy		struct pmc_op_simple sp;
3970145256Sjkoshy
3971145256Sjkoshy		PMC_DOWNGRADE_SX();
3972145256Sjkoshy
3973145256Sjkoshy		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3974145256Sjkoshy			break;
3975145256Sjkoshy
3976145256Sjkoshy		pmcid = sp.pm_pmcid;
3977145256Sjkoshy
3978145256Sjkoshy		/*
3979145256Sjkoshy		 * Mark the PMC as inactive and invoke the MD stop
3980145256Sjkoshy		 * routines if needed.
3981145256Sjkoshy		 */
3982145256Sjkoshy
3983145256Sjkoshy		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3984145256Sjkoshy			break;
3985145256Sjkoshy
3986145774Sjkoshy		KASSERT(pmcid == pm->pm_id,
3987145774Sjkoshy		    ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3988145774Sjkoshy			pm->pm_id, pmcid));
3989145256Sjkoshy
3990145256Sjkoshy		if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3991145256Sjkoshy			break;
3992145256Sjkoshy		else if (pm->pm_state != PMC_STATE_RUNNING) {
3993145256Sjkoshy			error = EINVAL;
3994145256Sjkoshy			break;
3995145256Sjkoshy		}
3996145256Sjkoshy
3997145256Sjkoshy		error = pmc_stop(pm);
3998145256Sjkoshy	}
3999145256Sjkoshy	break;
4000145256Sjkoshy
4001145256Sjkoshy
4002145256Sjkoshy	/*
4003147867Sjkoshy	 * Write a user supplied value to the log file.
4004145256Sjkoshy	 */
4005145256Sjkoshy
4006145256Sjkoshy	case PMC_OP_WRITELOG:
4007145256Sjkoshy	{
4008147191Sjkoshy		struct pmc_op_writelog wl;
4009147191Sjkoshy		struct pmc_owner *po;
4010145256Sjkoshy
4011145256Sjkoshy		PMC_DOWNGRADE_SX();
4012145256Sjkoshy
4013147191Sjkoshy		if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
4014145256Sjkoshy			break;
4015145256Sjkoshy
4016147191Sjkoshy		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
4017145256Sjkoshy			error = EINVAL;
4018145256Sjkoshy			break;
4019145256Sjkoshy		}
4020145256Sjkoshy
4021147191Sjkoshy		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
4022145774Sjkoshy			error = EINVAL;
4023145774Sjkoshy			break;
4024145774Sjkoshy		}
4025145774Sjkoshy
4026147191Sjkoshy		error = pmclog_process_userlog(po, &wl);
4027145256Sjkoshy	}
4028145256Sjkoshy	break;
4029145256Sjkoshy
4030147191Sjkoshy
4031145256Sjkoshy	default:
4032145256Sjkoshy		error = EINVAL;
4033145256Sjkoshy		break;
4034145256Sjkoshy	}
4035145256Sjkoshy
4036325551Skib	if (is_sx_downgraded)
4037325551Skib		sx_sunlock(&pmc_sx);
4038325551Skib	else
4039325551Skib		sx_xunlock(&pmc_sx);
4040325551Skibdone_syscall:
4041145256Sjkoshy	if (error)
4042145256Sjkoshy		atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
4043145256Sjkoshy
4044325547Skib	return (error);
4045145256Sjkoshy}
4046145256Sjkoshy
4047145256Sjkoshy/*
4048145256Sjkoshy * Helper functions
4049145256Sjkoshy */
4050145256Sjkoshy
4051147191Sjkoshy
4052145256Sjkoshy/*
4053174395Sjkoshy * Mark the thread as needing callchain capture and post an AST.  The
4054174395Sjkoshy * actual callchain capture will be done in a context where it is safe
4055174395Sjkoshy * to take page faults.
4056174395Sjkoshy */
4057174395Sjkoshy
4058174395Sjkoshystatic void
4059186037Sjkoshypmc_post_callchain_callback(void)
4060174395Sjkoshy{
4061174395Sjkoshy	struct thread *td;
4062174395Sjkoshy
4063174395Sjkoshy	td = curthread;
4064174395Sjkoshy
4065205998Sfabient	/*
4066205998Sfabient	 * If there is multiple PMCs for the same interrupt ignore new post
4067205998Sfabient	 */
4068205998Sfabient	if (td->td_pflags & TDP_CALLCHAIN)
4069205998Sfabient		return;
4070186037Sjkoshy
4071174395Sjkoshy	/*
4072186037Sjkoshy	 * Mark this thread as needing callchain capture.
4073186037Sjkoshy	 * `td->td_pflags' will be safe to touch because this thread
4074186037Sjkoshy	 * was in user space when it was interrupted.
4075174395Sjkoshy	 */
4076174395Sjkoshy	td->td_pflags |= TDP_CALLCHAIN;
4077174395Sjkoshy
4078174395Sjkoshy	/*
4079186037Sjkoshy	 * Don't let this thread migrate between CPUs until callchain
4080186037Sjkoshy	 * capture completes.
4081174395Sjkoshy	 */
4082186037Sjkoshy	sched_pin();
4083174395Sjkoshy
4084174395Sjkoshy	return;
4085174395Sjkoshy}
4086174395Sjkoshy
4087174395Sjkoshy/*
4088147191Sjkoshy * Interrupt processing.
4089147191Sjkoshy *
4090174395Sjkoshy * Find a free slot in the per-cpu array of samples and capture the
4091174395Sjkoshy * current callchain there.  If a sample was successfully added, a bit
4092174395Sjkoshy * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4093174395Sjkoshy * needs to be invoked from the clock handler.
4094147191Sjkoshy *
4095147191Sjkoshy * This function is meant to be called from an NMI handler.  It cannot
4096147191Sjkoshy * use any of the locking primitives supplied by the OS.
4097145256Sjkoshy */
4098145256Sjkoshy
4099147191Sjkoshyint
4100233628Sfabientpmc_process_interrupt(int cpu, int ring, struct pmc *pm, struct trapframe *tf,
4101174395Sjkoshy    int inuserspace)
4102145256Sjkoshy{
4103174395Sjkoshy	int error, callchaindepth;
4104147191Sjkoshy	struct thread *td;
4105147191Sjkoshy	struct pmc_sample *ps;
4106147191Sjkoshy	struct pmc_samplebuffer *psb;
4107145256Sjkoshy
4108147191Sjkoshy	error = 0;
4109145256Sjkoshy
4110174395Sjkoshy	/*
4111174395Sjkoshy	 * Allocate space for a sample buffer.
4112174395Sjkoshy	 */
4113233628Sfabient	psb = pmc_pcpu[cpu]->pc_sb[ring];
4114145256Sjkoshy
4115147191Sjkoshy	ps = psb->ps_write;
4116174395Sjkoshy	if (ps->ps_nsamples) {	/* in use, reader hasn't caught up */
4117290811Sjtl		CPU_SET_ATOMIC(cpu, &pm->pm_stalled);
4118147191Sjkoshy		atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
4119282658Sjhb		PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
4120174395Sjkoshy		    cpu, pm, (void *) tf, inuserspace,
4121147191Sjkoshy		    (int) (psb->ps_write - psb->ps_samples),
4122147191Sjkoshy		    (int) (psb->ps_read - psb->ps_samples));
4123290813Sjtl		callchaindepth = 1;
4124147191Sjkoshy		error = ENOMEM;
4125147191Sjkoshy		goto done;
4126147191Sjkoshy	}
4127145256Sjkoshy
4128174395Sjkoshy
4129174395Sjkoshy	/* Fill in entry. */
4130282658Sjhb	PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
4131174395Sjkoshy	    (void *) tf, inuserspace,
4132147191Sjkoshy	    (int) (psb->ps_write - psb->ps_samples),
4133147191Sjkoshy	    (int) (psb->ps_read - psb->ps_samples));
4134145256Sjkoshy
4135186037Sjkoshy	KASSERT(pm->pm_runcount >= 0,
4136186037Sjkoshy	    ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4137186037Sjkoshy		pm->pm_runcount));
4138186037Sjkoshy
4139208861Sfabient	atomic_add_rel_int(&pm->pm_runcount, 1);	/* hold onto PMC */
4140233628Sfabient
4141147191Sjkoshy	ps->ps_pmc = pm;
4142147191Sjkoshy	if ((td = curthread) && td->td_proc)
4143147191Sjkoshy		ps->ps_pid = td->td_proc->p_pid;
4144147191Sjkoshy	else
4145147191Sjkoshy		ps->ps_pid = -1;
4146174395Sjkoshy	ps->ps_cpu = cpu;
4147186037Sjkoshy	ps->ps_td = td;
4148174395Sjkoshy	ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4149145256Sjkoshy
4150174395Sjkoshy	callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4151174395Sjkoshy	    pmc_callchaindepth : 1;
4152174395Sjkoshy
4153174395Sjkoshy	if (callchaindepth == 1)
4154174395Sjkoshy		ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
4155174395Sjkoshy	else {
4156174395Sjkoshy		/*
4157174395Sjkoshy		 * Kernel stack traversals can be done immediately,
4158174395Sjkoshy		 * while we defer to an AST for user space traversals.
4159174395Sjkoshy		 */
4160233628Sfabient		if (!inuserspace) {
4161174395Sjkoshy			callchaindepth =
4162174395Sjkoshy			    pmc_save_kernel_callchain(ps->ps_pc,
4163174395Sjkoshy				callchaindepth, tf);
4164233628Sfabient		} else {
4165186037Sjkoshy			pmc_post_callchain_callback();
4166174395Sjkoshy			callchaindepth = PMC_SAMPLE_INUSE;
4167174395Sjkoshy		}
4168174395Sjkoshy	}
4169174395Sjkoshy
4170174395Sjkoshy	ps->ps_nsamples = callchaindepth;	/* mark entry as in use */
4171174395Sjkoshy
4172147191Sjkoshy	/* increment write pointer, modulo ring buffer size */
4173147191Sjkoshy	ps++;
4174147191Sjkoshy	if (ps == psb->ps_fence)
4175147191Sjkoshy		psb->ps_write = psb->ps_samples;
4176147191Sjkoshy	else
4177147191Sjkoshy		psb->ps_write = ps;
4178145256Sjkoshy
4179147191Sjkoshy done:
4180147191Sjkoshy	/* mark CPU as needing processing */
4181290813Sjtl	if (callchaindepth != PMC_SAMPLE_INUSE)
4182290813Sjtl		CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4183147191Sjkoshy
4184174395Sjkoshy	return (error);
4185145256Sjkoshy}
4186145256Sjkoshy
4187174395Sjkoshy/*
4188174395Sjkoshy * Capture a user call chain.  This function will be called from ast()
4189174395Sjkoshy * before control returns to userland and before the process gets
4190174395Sjkoshy * rescheduled.
4191174395Sjkoshy */
4192147191Sjkoshy
4193174395Sjkoshystatic void
4194233628Sfabientpmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4195174395Sjkoshy{
4196174395Sjkoshy	struct pmc *pm;
4197186037Sjkoshy	struct thread *td;
4198290813Sjtl	struct pmc_sample *ps, *ps_end;
4199174395Sjkoshy	struct pmc_samplebuffer *psb;
4200186037Sjkoshy#ifdef	INVARIANTS
4201186037Sjkoshy	int ncallchains;
4202300902Sandrew	int nfree;
4203186037Sjkoshy#endif
4204174395Sjkoshy
4205233628Sfabient	psb = pmc_pcpu[cpu]->pc_sb[ring];
4206186037Sjkoshy	td = curthread;
4207174395Sjkoshy
4208186037Sjkoshy	KASSERT(td->td_pflags & TDP_CALLCHAIN,
4209186037Sjkoshy	    ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
4210186037Sjkoshy		__LINE__));
4211186037Sjkoshy
4212186037Sjkoshy#ifdef	INVARIANTS
4213186037Sjkoshy	ncallchains = 0;
4214300902Sandrew	nfree = 0;
4215186037Sjkoshy#endif
4216186037Sjkoshy
4217174395Sjkoshy	/*
4218174395Sjkoshy	 * Iterate through all deferred callchain requests.
4219290813Sjtl	 * Walk from the current read pointer to the current
4220290813Sjtl	 * write pointer.
4221174395Sjkoshy	 */
4222174395Sjkoshy
4223290813Sjtl	ps = psb->ps_read;
4224290813Sjtl	ps_end = psb->ps_write;
4225290813Sjtl	do {
4226300902Sandrew#ifdef	INVARIANTS
4227300902Sandrew		if (ps->ps_pmc->pm_state != PMC_STATE_RUNNING)
4228300902Sandrew			nfree++;
4229300902Sandrew#endif
4230174395Sjkoshy		if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
4231290813Sjtl			goto next;
4232186037Sjkoshy		if (ps->ps_td != td)
4233290813Sjtl			goto next;
4234174395Sjkoshy
4235186037Sjkoshy		KASSERT(ps->ps_cpu == cpu,
4236186037Sjkoshy		    ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
4237186037Sjkoshy			ps->ps_cpu, PCPU_GET(cpuid)));
4238186037Sjkoshy
4239174395Sjkoshy		pm = ps->ps_pmc;
4240174395Sjkoshy
4241174395Sjkoshy		KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
4242174395Sjkoshy		    ("[pmc,%d] Retrieving callchain for PMC that doesn't "
4243174395Sjkoshy			"want it", __LINE__));
4244174395Sjkoshy
4245186037Sjkoshy		KASSERT(pm->pm_runcount > 0,
4246186037Sjkoshy		    ("[pmc,%d] runcount %d", __LINE__, pm->pm_runcount));
4247186037Sjkoshy
4248174395Sjkoshy		/*
4249174395Sjkoshy		 * Retrieve the callchain and mark the sample buffer
4250174395Sjkoshy		 * as 'processable' by the timer tick sweep code.
4251174395Sjkoshy		 */
4252174395Sjkoshy		ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
4253174395Sjkoshy		    pmc_callchaindepth, tf);
4254186037Sjkoshy
4255186037Sjkoshy#ifdef	INVARIANTS
4256186037Sjkoshy		ncallchains++;
4257186037Sjkoshy#endif
4258174395Sjkoshy
4259290813Sjtlnext:
4260290813Sjtl		/* increment the pointer, modulo sample ring size */
4261290813Sjtl		if (++ps == psb->ps_fence)
4262290813Sjtl			ps = psb->ps_samples;
4263290813Sjtl	} while (ps != ps_end);
4264290813Sjtl
4265300902Sandrew	KASSERT(ncallchains > 0 || nfree > 0,
4266186037Sjkoshy	    ("[pmc,%d] cpu %d didn't find a sample to collect", __LINE__,
4267186037Sjkoshy		cpu));
4268186037Sjkoshy
4269242361Sattilio	KASSERT(td->td_pinned == 1,
4270233628Sfabient	    ("[pmc,%d] invalid td_pinned value", __LINE__));
4271233628Sfabient	sched_unpin();	/* Can migrate safely now. */
4272233628Sfabient
4273290813Sjtl	/* mark CPU as needing processing */
4274290813Sjtl	CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4275290813Sjtl
4276174395Sjkoshy	return;
4277174395Sjkoshy}
4278174395Sjkoshy
4279145256Sjkoshy/*
4280147191Sjkoshy * Process saved PC samples.
4281145256Sjkoshy */
4282145256Sjkoshy
4283145256Sjkoshystatic void
4284233628Sfabientpmc_process_samples(int cpu, int ring)
4285145256Sjkoshy{
4286147191Sjkoshy	struct pmc *pm;
4287185363Sjkoshy	int adjri, n;
4288147191Sjkoshy	struct thread *td;
4289147191Sjkoshy	struct pmc_owner *po;
4290147191Sjkoshy	struct pmc_sample *ps;
4291184802Sjkoshy	struct pmc_classdep *pcd;
4292147191Sjkoshy	struct pmc_samplebuffer *psb;
4293145256Sjkoshy
4294147191Sjkoshy	KASSERT(PCPU_GET(cpuid) == cpu,
4295147191Sjkoshy	    ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4296147191Sjkoshy		PCPU_GET(cpuid), cpu));
4297145256Sjkoshy
4298233628Sfabient	psb = pmc_pcpu[cpu]->pc_sb[ring];
4299147191Sjkoshy
4300147191Sjkoshy	for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
4301147191Sjkoshy
4302147191Sjkoshy		ps = psb->ps_read;
4303174395Sjkoshy		if (ps->ps_nsamples == PMC_SAMPLE_FREE)
4304147191Sjkoshy			break;
4305147191Sjkoshy
4306147191Sjkoshy		pm = ps->ps_pmc;
4307186037Sjkoshy
4308186037Sjkoshy		KASSERT(pm->pm_runcount > 0,
4309186037Sjkoshy		    ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4310186037Sjkoshy			pm->pm_runcount));
4311186037Sjkoshy
4312147191Sjkoshy		po = pm->pm_owner;
4313147191Sjkoshy
4314147191Sjkoshy		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4315147191Sjkoshy		    ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4316147191Sjkoshy			pm, PMC_TO_MODE(pm)));
4317147191Sjkoshy
4318147191Sjkoshy		/* Ignore PMCs that have been switched off */
4319147191Sjkoshy		if (pm->pm_state != PMC_STATE_RUNNING)
4320147191Sjkoshy			goto entrydone;
4321147191Sjkoshy
4322233628Sfabient		/* If there is a pending AST wait for completion */
4323233628Sfabient		if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
4324233628Sfabient			/* Need a rescan at a later time. */
4325233628Sfabient			CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4326233628Sfabient			break;
4327233628Sfabient		}
4328233628Sfabient
4329282658Sjhb		PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4330174395Sjkoshy		    pm, ps->ps_nsamples, ps->ps_flags,
4331147191Sjkoshy		    (int) (psb->ps_write - psb->ps_samples),
4332147191Sjkoshy		    (int) (psb->ps_read - psb->ps_samples));
4333147191Sjkoshy
4334147191Sjkoshy		/*
4335147191Sjkoshy		 * If this is a process-mode PMC that is attached to
4336147191Sjkoshy		 * its owner, and if the PC is in user mode, update
4337147191Sjkoshy		 * profiling statistics like timer-based profiling
4338147191Sjkoshy		 * would have done.
4339147191Sjkoshy		 */
4340147191Sjkoshy		if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4341174395Sjkoshy			if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4342147191Sjkoshy				td = FIRST_THREAD_IN_PROC(po->po_owner);
4343174395Sjkoshy				addupc_intr(td, ps->ps_pc[0], 1);
4344147191Sjkoshy			}
4345147191Sjkoshy			goto entrydone;
4346147191Sjkoshy		}
4347147191Sjkoshy
4348147191Sjkoshy		/*
4349147191Sjkoshy		 * Otherwise, this is either a sampling mode PMC that
4350147191Sjkoshy		 * is attached to a different process than its owner,
4351147191Sjkoshy		 * or a system-wide sampling PMC.  Dispatch a log
4352147191Sjkoshy		 * entry to the PMC's owner process.
4353147191Sjkoshy		 */
4354174395Sjkoshy		pmclog_process_callchain(pm, ps);
4355147191Sjkoshy
4356147191Sjkoshy	entrydone:
4357233628Sfabient		ps->ps_nsamples = 0; /* mark entry as free */
4358208861Sfabient		atomic_subtract_rel_int(&pm->pm_runcount, 1);
4359147191Sjkoshy
4360147191Sjkoshy		/* increment read pointer, modulo sample size */
4361147191Sjkoshy		if (++ps == psb->ps_fence)
4362147191Sjkoshy			psb->ps_read = psb->ps_samples;
4363147191Sjkoshy		else
4364147191Sjkoshy			psb->ps_read = ps;
4365147191Sjkoshy	}
4366147191Sjkoshy
4367147191Sjkoshy	atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
4368147191Sjkoshy
4369147191Sjkoshy	/* Do not re-enable stalled PMCs if we failed to process any samples */
4370147191Sjkoshy	if (n == 0)
4371147191Sjkoshy		return;
4372147191Sjkoshy
4373147191Sjkoshy	/*
4374147191Sjkoshy	 * Restart any stalled sampling PMCs on this CPU.
4375147191Sjkoshy	 *
4376147867Sjkoshy	 * If the NMI handler sets the pm_stalled field of a PMC after
4377147867Sjkoshy	 * the check below, we'll end up processing the stalled PMC at
4378147867Sjkoshy	 * the next hardclock tick.
4379147191Sjkoshy	 */
4380147191Sjkoshy	for (n = 0; n < md->pmd_npmc; n++) {
4381184802Sjkoshy		pcd = pmc_ri_to_classdep(md, n, &adjri);
4382184802Sjkoshy		KASSERT(pcd != NULL,
4383184802Sjkoshy		    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4384184802Sjkoshy		(void) (*pcd->pcd_get_config)(cpu,adjri,&pm);
4385184802Sjkoshy
4386147191Sjkoshy		if (pm == NULL ||			 /* !cfg'ed */
4387147191Sjkoshy		    pm->pm_state != PMC_STATE_RUNNING || /* !active */
4388147191Sjkoshy		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4389290811Sjtl		    !CPU_ISSET(cpu, &pm->pm_cpustate) || /* !desired */
4390290811Sjtl		    !CPU_ISSET(cpu, &pm->pm_stalled)) /* !stalled */
4391147191Sjkoshy			continue;
4392147191Sjkoshy
4393290811Sjtl		CPU_CLR_ATOMIC(cpu, &pm->pm_stalled);
4394184802Sjkoshy		(*pcd->pcd_start_pmc)(cpu, adjri);
4395147191Sjkoshy	}
4396145256Sjkoshy}
4397145256Sjkoshy
4398145256Sjkoshy/*
4399145256Sjkoshy * Event handlers.
4400145256Sjkoshy */
4401145256Sjkoshy
4402145256Sjkoshy/*
4403145256Sjkoshy * Handle a process exit.
4404145256Sjkoshy *
4405147191Sjkoshy * Remove this process from all hash tables.  If this process
4406147191Sjkoshy * owned any PMCs, turn off those PMCs and deallocate them,
4407147191Sjkoshy * removing any associations with target processes.
4408147191Sjkoshy *
4409147191Sjkoshy * This function will be called by the last 'thread' of a
4410147191Sjkoshy * process.
4411147191Sjkoshy *
4412145256Sjkoshy * XXX This eventhandler gets called early in the exit process.
4413145256Sjkoshy * Consider using a 'hook' invocation from thread_exit() or equivalent
4414145256Sjkoshy * spot.  Another negative is that kse_exit doesn't seem to call
4415145256Sjkoshy * exit1() [??].
4416147191Sjkoshy *
4417145256Sjkoshy */
4418145256Sjkoshy
4419145256Sjkoshystatic void
4420145256Sjkoshypmc_process_exit(void *arg __unused, struct proc *p)
4421145256Sjkoshy{
4422184802Sjkoshy	struct pmc *pm;
4423184802Sjkoshy	int adjri, cpu;
4424184802Sjkoshy	unsigned int ri;
4425145256Sjkoshy	int is_using_hwpmcs;
4426184802Sjkoshy	struct pmc_owner *po;
4427147191Sjkoshy	struct pmc_process *pp;
4428184802Sjkoshy	struct pmc_classdep *pcd;
4429147191Sjkoshy	pmc_value_t newvalue, tmp;
4430145256Sjkoshy
4431145256Sjkoshy	PROC_LOCK(p);
4432145256Sjkoshy	is_using_hwpmcs = p->p_flag & P_HWPMC;
4433145256Sjkoshy	PROC_UNLOCK(p);
4434145256Sjkoshy
4435147191Sjkoshy	/*
4436147191Sjkoshy	 * Log a sysexit event to all SS PMC owners.
4437147191Sjkoshy	 */
4438147191Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4439147191Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4440147191Sjkoshy		    pmclog_process_sysexit(po, p->p_pid);
4441145256Sjkoshy
4442147191Sjkoshy	if (!is_using_hwpmcs)
4443147191Sjkoshy		return;
4444147191Sjkoshy
4445147191Sjkoshy	PMC_GET_SX_XLOCK();
4446282658Sjhb	PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4447147191Sjkoshy	    p->p_comm);
4448147191Sjkoshy
4449147191Sjkoshy	/*
4450147191Sjkoshy	 * Since this code is invoked by the last thread in an exiting
4451147191Sjkoshy	 * process, we would have context switched IN at some prior
4452147191Sjkoshy	 * point.  However, with PREEMPTION, kernel mode context
4453147191Sjkoshy	 * switches may happen any time, so we want to disable a
4454298931Spfg	 * context switch OUT till we get any PMCs targeting this
4455147191Sjkoshy	 * process off the hardware.
4456147191Sjkoshy	 *
4457147191Sjkoshy	 * We also need to atomically remove this process'
4458147191Sjkoshy	 * entry from our target process hash table, using
4459147191Sjkoshy	 * PMC_FLAG_REMOVE.
4460147191Sjkoshy	 */
4461282658Sjhb	PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4462147191Sjkoshy	    p->p_comm);
4463147191Sjkoshy
4464147191Sjkoshy	critical_enter(); /* no preemption */
4465147191Sjkoshy
4466147191Sjkoshy	cpu = curthread->td_oncpu;
4467147191Sjkoshy
4468147191Sjkoshy	if ((pp = pmc_find_process_descriptor(p,
4469147191Sjkoshy		 PMC_FLAG_REMOVE)) != NULL) {
4470147191Sjkoshy
4471282658Sjhb		PMCDBG2(PRC,EXT,2,
4472147191Sjkoshy		    "process-exit proc=%p pmc-process=%p", p, pp);
4473147191Sjkoshy
4474147191Sjkoshy		/*
4475147191Sjkoshy		 * The exiting process could the target of
4476147191Sjkoshy		 * some PMCs which will be running on
4477147191Sjkoshy		 * currently executing CPU.
4478147191Sjkoshy		 *
4479147191Sjkoshy		 * We need to turn these PMCs off like we
4480147191Sjkoshy		 * would do at context switch OUT time.
4481147191Sjkoshy		 */
4482147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++) {
4483147191Sjkoshy
4484147191Sjkoshy			/*
4485147191Sjkoshy			 * Pick up the pmc pointer from hardware
4486147191Sjkoshy			 * state similar to the CSW_OUT code.
4487147191Sjkoshy			 */
4488147191Sjkoshy			pm = NULL;
4489147191Sjkoshy
4490184802Sjkoshy			pcd = pmc_ri_to_classdep(md, ri, &adjri);
4491184802Sjkoshy
4492184802Sjkoshy			(void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
4493184802Sjkoshy
4494282658Sjhb			PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4495147191Sjkoshy
4496147191Sjkoshy			if (pm == NULL ||
4497147191Sjkoshy			    !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4498147191Sjkoshy				continue;
4499147191Sjkoshy
4500282658Sjhb			PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4501147191Sjkoshy			    "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4502147191Sjkoshy			    pm, pm->pm_state);
4503147191Sjkoshy
4504147191Sjkoshy			KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4505147191Sjkoshy			    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4506147191Sjkoshy				__LINE__, PMC_TO_ROWINDEX(pm), ri));
4507147191Sjkoshy
4508147191Sjkoshy			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4509147191Sjkoshy			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4510147191Sjkoshy				__LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4511147191Sjkoshy
4512147191Sjkoshy			KASSERT(pm->pm_runcount > 0,
4513147191Sjkoshy			    ("[pmc,%d] bad runcount ri %d rc %d",
4514147191Sjkoshy				__LINE__, ri, pm->pm_runcount));
4515147191Sjkoshy
4516290811Sjtl			/*
4517290811Sjtl			 * Change desired state, and then stop if not
4518290811Sjtl			 * stalled. This two-step dance should avoid
4519290811Sjtl			 * race conditions where an interrupt re-enables
4520290811Sjtl			 * the PMC after this code has already checked
4521290811Sjtl			 * the pm_stalled flag.
4522290811Sjtl			 */
4523290811Sjtl			if (CPU_ISSET(cpu, &pm->pm_cpustate)) {
4524290811Sjtl				CPU_CLR_ATOMIC(cpu, &pm->pm_cpustate);
4525290811Sjtl				if (!CPU_ISSET(cpu, &pm->pm_stalled)) {
4526290811Sjtl					(void) pcd->pcd_stop_pmc(cpu, adjri);
4527290811Sjtl					pcd->pcd_read_pmc(cpu, adjri,
4528290811Sjtl					    &newvalue);
4529290811Sjtl					tmp = newvalue -
4530290811Sjtl					    PMC_PCPU_SAVED(cpu,ri);
4531147191Sjkoshy
4532290811Sjtl					mtx_pool_lock_spin(pmc_mtxpool, pm);
4533290811Sjtl					pm->pm_gv.pm_savedvalue += tmp;
4534290811Sjtl					pp->pp_pmcs[ri].pp_pmcval += tmp;
4535290811Sjtl					mtx_pool_unlock_spin(pmc_mtxpool, pm);
4536290811Sjtl				}
4537147191Sjkoshy			}
4538147191Sjkoshy
4539208861Sfabient			atomic_subtract_rel_int(&pm->pm_runcount,1);
4540147191Sjkoshy
4541147191Sjkoshy			KASSERT((int) pm->pm_runcount >= 0,
4542147191Sjkoshy			    ("[pmc,%d] runcount is %d", __LINE__, ri));
4543147191Sjkoshy
4544184802Sjkoshy			(void) pcd->pcd_config_pmc(cpu, adjri, NULL);
4545147191Sjkoshy		}
4546147191Sjkoshy
4547147191Sjkoshy		/*
4548147191Sjkoshy		 * Inform the MD layer of this pseudo "context switch
4549147191Sjkoshy		 * out"
4550147191Sjkoshy		 */
4551147191Sjkoshy		(void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
4552147191Sjkoshy
4553147191Sjkoshy		critical_exit(); /* ok to be pre-empted now */
4554147191Sjkoshy
4555147191Sjkoshy		/*
4556147191Sjkoshy		 * Unlink this process from the PMCs that are
4557298931Spfg		 * targeting it.  This will send a signal to
4558147191Sjkoshy		 * all PMC owner's whose PMCs are orphaned.
4559147191Sjkoshy		 *
4560147191Sjkoshy		 * Log PMC value at exit time if requested.
4561147191Sjkoshy		 */
4562147191Sjkoshy		for (ri = 0; ri < md->pmd_npmc; ri++)
4563147191Sjkoshy			if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
4564147867Sjkoshy				if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
4565147867Sjkoshy				    PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
4566147191Sjkoshy					pmclog_process_procexit(pm, pp);
4567147191Sjkoshy				pmc_unlink_target_process(pm, pp);
4568147191Sjkoshy			}
4569184205Sdes		free(pp, M_PMC);
4570147191Sjkoshy
4571147191Sjkoshy	} else
4572147191Sjkoshy		critical_exit(); /* pp == NULL */
4573147191Sjkoshy
4574147191Sjkoshy
4575147191Sjkoshy	/*
4576147191Sjkoshy	 * If the process owned PMCs, free them up and free up
4577147191Sjkoshy	 * memory.
4578147191Sjkoshy	 */
4579147191Sjkoshy	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
4580147191Sjkoshy		pmc_remove_owner(po);
4581147191Sjkoshy		pmc_destroy_owner_descriptor(po);
4582145256Sjkoshy	}
4583147191Sjkoshy
4584147191Sjkoshy	sx_xunlock(&pmc_sx);
4585145256Sjkoshy}
4586145256Sjkoshy
4587145256Sjkoshy/*
4588145256Sjkoshy * Handle a process fork.
4589145256Sjkoshy *
4590145256Sjkoshy * If the parent process 'p1' is under HWPMC monitoring, then copy
4591145256Sjkoshy * over any attached PMCs that have 'do_descendants' semantics.
4592145256Sjkoshy */
4593145256Sjkoshy
4594145256Sjkoshystatic void
4595147191Sjkoshypmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
4596145256Sjkoshy    int flags)
4597145256Sjkoshy{
4598145256Sjkoshy	int is_using_hwpmcs;
4599147191Sjkoshy	unsigned int ri;
4600147191Sjkoshy	uint32_t do_descendants;
4601147191Sjkoshy	struct pmc *pm;
4602147191Sjkoshy	struct pmc_owner *po;
4603147191Sjkoshy	struct pmc_process *ppnew, *ppold;
4604145256Sjkoshy
4605145256Sjkoshy	(void) flags;		/* unused parameter */
4606145256Sjkoshy
4607145256Sjkoshy	PROC_LOCK(p1);
4608145256Sjkoshy	is_using_hwpmcs = p1->p_flag & P_HWPMC;
4609145256Sjkoshy	PROC_UNLOCK(p1);
4610145256Sjkoshy
4611147191Sjkoshy	/*
4612147191Sjkoshy	 * If there are system-wide sampling PMCs active, we need to
4613147191Sjkoshy	 * log all fork events to their owner's logs.
4614147191Sjkoshy	 */
4615147191Sjkoshy
4616147191Sjkoshy	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4617147191Sjkoshy	    if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4618147191Sjkoshy		    pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4619147191Sjkoshy
4620147191Sjkoshy	if (!is_using_hwpmcs)
4621147191Sjkoshy		return;
4622147191Sjkoshy
4623147191Sjkoshy	PMC_GET_SX_XLOCK();
4624282658Sjhb	PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4625147191Sjkoshy	    p1->p_pid, p1->p_comm, newproc);
4626147191Sjkoshy
4627147191Sjkoshy	/*
4628147191Sjkoshy	 * If the parent process (curthread->td_proc) is a
4629147191Sjkoshy	 * target of any PMCs, look for PMCs that are to be
4630147191Sjkoshy	 * inherited, and link these into the new process
4631147191Sjkoshy	 * descriptor.
4632147191Sjkoshy	 */
4633147191Sjkoshy	if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4634147191Sjkoshy		 PMC_FLAG_NONE)) == NULL)
4635147191Sjkoshy		goto done;		/* nothing to do */
4636147191Sjkoshy
4637147191Sjkoshy	do_descendants = 0;
4638147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
4639147191Sjkoshy		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4640147191Sjkoshy			do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4641147191Sjkoshy	if (do_descendants == 0) /* nothing to do */
4642147191Sjkoshy		goto done;
4643147191Sjkoshy
4644147191Sjkoshy	/* allocate a descriptor for the new process  */
4645147191Sjkoshy	if ((ppnew = pmc_find_process_descriptor(newproc,
4646147191Sjkoshy		 PMC_FLAG_ALLOCATE)) == NULL)
4647147191Sjkoshy		goto done;
4648147191Sjkoshy
4649147191Sjkoshy	/*
4650147191Sjkoshy	 * Run through all PMCs that were targeting the old process
4651147191Sjkoshy	 * and which specified F_DESCENDANTS and attach them to the
4652147191Sjkoshy	 * new process.
4653147191Sjkoshy	 *
4654147191Sjkoshy	 * Log the fork event to all owners of PMCs attached to this
4655147191Sjkoshy	 * process, if not already logged.
4656147191Sjkoshy	 */
4657147191Sjkoshy	for (ri = 0; ri < md->pmd_npmc; ri++)
4658147191Sjkoshy		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4659147191Sjkoshy		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
4660147191Sjkoshy			pmc_link_target_process(pm, ppnew);
4661147191Sjkoshy			po = pm->pm_owner;
4662147191Sjkoshy			if (po->po_sscount == 0 &&
4663147191Sjkoshy			    po->po_flags & PMC_PO_OWNS_LOGFILE)
4664147191Sjkoshy				pmclog_process_procfork(po, p1->p_pid,
4665147191Sjkoshy				    newproc->p_pid);
4666147191Sjkoshy		}
4667147191Sjkoshy
4668147191Sjkoshy	/*
4669147191Sjkoshy	 * Now mark the new process as being tracked by this driver.
4670147191Sjkoshy	 */
4671147191Sjkoshy	PROC_LOCK(newproc);
4672147191Sjkoshy	newproc->p_flag |= P_HWPMC;
4673147191Sjkoshy	PROC_UNLOCK(newproc);
4674147191Sjkoshy
4675147191Sjkoshy done:
4676147191Sjkoshy	sx_xunlock(&pmc_sx);
4677145256Sjkoshy}
4678145256Sjkoshy
4679254813Smarkjstatic void
4680254813Smarkjpmc_kld_load(void *arg __unused, linker_file_t lf)
4681254813Smarkj{
4682254813Smarkj	struct pmc_owner *po;
4683145256Sjkoshy
4684254813Smarkj	sx_slock(&pmc_sx);
4685254813Smarkj
4686254813Smarkj	/*
4687254813Smarkj	 * Notify owners of system sampling PMCs about KLD operations.
4688254813Smarkj	 */
4689254813Smarkj	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4690254813Smarkj		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4691254813Smarkj			pmclog_process_map_in(po, (pid_t) -1,
4692254813Smarkj			    (uintfptr_t) lf->address, lf->filename);
4693254813Smarkj
4694254813Smarkj	/*
4695254813Smarkj	 * TODO: Notify owners of (all) process-sampling PMCs too.
4696254813Smarkj	 */
4697254813Smarkj
4698254813Smarkj	sx_sunlock(&pmc_sx);
4699254813Smarkj}
4700254813Smarkj
4701254813Smarkjstatic void
4702254813Smarkjpmc_kld_unload(void *arg __unused, const char *filename __unused,
4703254813Smarkj    caddr_t address, size_t size)
4704254813Smarkj{
4705254813Smarkj	struct pmc_owner *po;
4706254813Smarkj
4707254813Smarkj	sx_slock(&pmc_sx);
4708254813Smarkj
4709254813Smarkj	LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4710254813Smarkj		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4711254813Smarkj			pmclog_process_map_out(po, (pid_t) -1,
4712254813Smarkj			    (uintfptr_t) address, (uintfptr_t) address + size);
4713254813Smarkj
4714254813Smarkj	/*
4715254813Smarkj	 * TODO: Notify owners of process-sampling PMCs.
4716254813Smarkj	 */
4717254813Smarkj
4718254813Smarkj	sx_sunlock(&pmc_sx);
4719254813Smarkj}
4720254813Smarkj
4721145256Sjkoshy/*
4722145256Sjkoshy * initialization
4723145256Sjkoshy */
4724283120Sjhbstatic const char *
4725283120Sjhbpmc_name_of_pmcclass(enum pmc_class class)
4726283120Sjhb{
4727145256Sjkoshy
4728283120Sjhb	switch (class) {
4729145256Sjkoshy#undef	__PMC_CLASS
4730283120Sjhb#define	__PMC_CLASS(S,V,D)						\
4731283120Sjhb	case PMC_CLASS_##S:						\
4732283120Sjhb		return #S;
4733283120Sjhb	__PMC_CLASSES();
4734283120Sjhb	default:
4735283120Sjhb		return ("<unknown>");
4736283120Sjhb	}
4737283120Sjhb}
4738145256Sjkoshy
4739233628Sfabient/*
4740233628Sfabient * Base class initializer: allocate structure and set default classes.
4741233628Sfabient */
4742233628Sfabientstruct pmc_mdep *
4743233628Sfabientpmc_mdep_alloc(int nclasses)
4744233628Sfabient{
4745233628Sfabient	struct pmc_mdep *md;
4746233628Sfabient	int	n;
4747233628Sfabient
4748233628Sfabient	/* SOFT + md classes */
4749233628Sfabient	n = 1 + nclasses;
4750233628Sfabient	md = malloc(sizeof(struct pmc_mdep) + n *
4751233628Sfabient	    sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
4752250105Sdavide	md->pmd_nclass = n;
4753233628Sfabient
4754250105Sdavide	/* Add base class. */
4755250105Sdavide	pmc_soft_initialize(md);
4756233628Sfabient	return md;
4757233628Sfabient}
4758233628Sfabient
4759233628Sfabientvoid
4760233628Sfabientpmc_mdep_free(struct pmc_mdep *md)
4761233628Sfabient{
4762233628Sfabient	pmc_soft_finalize(md);
4763233628Sfabient	free(md, M_PMC);
4764233628Sfabient}
4765233628Sfabient
4766145256Sjkoshystatic int
4767233628Sfabientgeneric_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
4768233628Sfabient{
4769233628Sfabient	(void) pc; (void) pp;
4770233628Sfabient
4771233628Sfabient	return (0);
4772233628Sfabient}
4773233628Sfabient
4774233628Sfabientstatic int
4775233628Sfabientgeneric_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
4776233628Sfabient{
4777233628Sfabient	(void) pc; (void) pp;
4778233628Sfabient
4779233628Sfabient	return (0);
4780233628Sfabient}
4781233628Sfabient
4782233628Sfabientstatic struct pmc_mdep *
4783233628Sfabientpmc_generic_cpu_initialize(void)
4784233628Sfabient{
4785233628Sfabient	struct pmc_mdep *md;
4786233628Sfabient
4787233628Sfabient	md = pmc_mdep_alloc(0);
4788233628Sfabient
4789233628Sfabient	md->pmd_cputype    = PMC_CPU_GENERIC;
4790233628Sfabient
4791233628Sfabient	md->pmd_pcpu_init  = NULL;
4792233628Sfabient	md->pmd_pcpu_fini  = NULL;
4793233628Sfabient	md->pmd_switch_in  = generic_switch_in;
4794233628Sfabient	md->pmd_switch_out = generic_switch_out;
4795233628Sfabient
4796233628Sfabient	return (md);
4797233628Sfabient}
4798233628Sfabient
4799233628Sfabientstatic void
4800233628Sfabientpmc_generic_cpu_finalize(struct pmc_mdep *md)
4801233628Sfabient{
4802233628Sfabient	(void) md;
4803233628Sfabient}
4804233628Sfabient
4805233628Sfabient
4806233628Sfabientstatic int
4807145256Sjkoshypmc_initialize(void)
4808145256Sjkoshy{
4809184802Sjkoshy	int c, cpu, error, n, ri;
4810183266Sjkoshy	unsigned int maxcpu;
4811145256Sjkoshy	struct pmc_binding pb;
4812174395Sjkoshy	struct pmc_sample *ps;
4813184802Sjkoshy	struct pmc_classdep *pcd;
4814147191Sjkoshy	struct pmc_samplebuffer *sb;
4815145256Sjkoshy
4816145256Sjkoshy	md = NULL;
4817145256Sjkoshy	error = 0;
4818145256Sjkoshy
4819282641Sjhb#ifdef	HWPMC_DEBUG
4820145256Sjkoshy	/* parse debug flags first */
4821145256Sjkoshy	if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4822145256Sjkoshy		pmc_debugstr, sizeof(pmc_debugstr)))
4823145256Sjkoshy		pmc_debugflags_parse(pmc_debugstr,
4824145256Sjkoshy		    pmc_debugstr+strlen(pmc_debugstr));
4825145256Sjkoshy#endif
4826145256Sjkoshy
4827282658Sjhb	PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4828145256Sjkoshy
4829148562Sjkoshy	/* check kernel version */
4830148562Sjkoshy	if (pmc_kernel_version != PMC_VERSION) {
4831148562Sjkoshy		if (pmc_kernel_version == 0)
4832148562Sjkoshy			printf("hwpmc: this kernel has not been compiled with "
4833148562Sjkoshy			    "'options HWPMC_HOOKS'.\n");
4834148562Sjkoshy		else
4835148562Sjkoshy			printf("hwpmc: kernel version (0x%x) does not match "
4836148562Sjkoshy			    "module version (0x%x).\n", pmc_kernel_version,
4837148562Sjkoshy			    PMC_VERSION);
4838148562Sjkoshy		return EPROGMISMATCH;
4839148562Sjkoshy	}
4840148562Sjkoshy
4841145256Sjkoshy	/*
4842145256Sjkoshy	 * check sysctl parameters
4843145256Sjkoshy	 */
4844145256Sjkoshy
4845145256Sjkoshy	if (pmc_hashsize <= 0) {
4846174395Sjkoshy		(void) printf("hwpmc: tunable \"hashsize\"=%d must be "
4847174395Sjkoshy		    "greater than zero.\n", pmc_hashsize);
4848145256Sjkoshy		pmc_hashsize = PMC_HASH_SIZE;
4849145256Sjkoshy	}
4850145256Sjkoshy
4851147191Sjkoshy	if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4852174395Sjkoshy		(void) printf("hwpmc: tunable \"nsamples\"=%d out of "
4853174395Sjkoshy		    "range.\n", pmc_nsamples);
4854147191Sjkoshy		pmc_nsamples = PMC_NSAMPLES;
4855147191Sjkoshy	}
4856145256Sjkoshy
4857174395Sjkoshy	if (pmc_callchaindepth <= 0 ||
4858174395Sjkoshy	    pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
4859174395Sjkoshy		(void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
4860274766Semaste		    "range - using %d.\n", pmc_callchaindepth,
4861274766Semaste		    PMC_CALLCHAIN_DEPTH_MAX);
4862274766Semaste		pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX;
4863174395Sjkoshy	}
4864174395Sjkoshy
4865147191Sjkoshy	md = pmc_md_initialize();
4866233628Sfabient	if (md == NULL) {
4867233628Sfabient		/* Default to generic CPU. */
4868233628Sfabient		md = pmc_generic_cpu_initialize();
4869233628Sfabient		if (md == NULL)
4870233628Sfabient			return (ENOSYS);
4871233628Sfabient        }
4872147191Sjkoshy
4873184802Sjkoshy	KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
4874184802Sjkoshy	    ("[pmc,%d] no classes or pmcs", __LINE__));
4875184802Sjkoshy
4876184802Sjkoshy	/* Compute the map from row-indices to classdep pointers. */
4877184802Sjkoshy	pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
4878184802Sjkoshy	    md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);
4879184802Sjkoshy
4880184802Sjkoshy	for (n = 0; n < md->pmd_npmc; n++)
4881184802Sjkoshy		pmc_rowindex_to_classdep[n] = NULL;
4882184802Sjkoshy	for (ri = c = 0; c < md->pmd_nclass; c++) {
4883184802Sjkoshy		pcd = &md->pmd_classdep[c];
4884184802Sjkoshy		for (n = 0; n < pcd->pcd_num; n++, ri++)
4885184802Sjkoshy			pmc_rowindex_to_classdep[ri] = pcd;
4886184802Sjkoshy	}
4887184802Sjkoshy
4888184802Sjkoshy	KASSERT(ri == md->pmd_npmc,
4889184802Sjkoshy	    ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
4890184802Sjkoshy	    ri, md->pmd_npmc));
4891184802Sjkoshy
4892183266Sjkoshy	maxcpu = pmc_cpu_max();
4893183266Sjkoshy
4894145256Sjkoshy	/* allocate space for the per-cpu array */
4895184802Sjkoshy	pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
4896184802Sjkoshy	    M_WAITOK|M_ZERO);
4897145256Sjkoshy
4898145256Sjkoshy	/* per-cpu 'saved values' for managing process-mode PMCs */
4899184214Sdes	pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
4900184214Sdes	    M_PMC, M_WAITOK);
4901145256Sjkoshy
4902183266Sjkoshy	/* Perform CPU-dependent initialization. */
4903145256Sjkoshy	pmc_save_cpu_binding(&pb);
4904184802Sjkoshy	error = 0;
4905184802Sjkoshy	for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
4906183266Sjkoshy		if (!pmc_cpu_is_active(cpu))
4907145256Sjkoshy			continue;
4908145256Sjkoshy		pmc_select_cpu(cpu);
4909184802Sjkoshy		pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
4910184802Sjkoshy		    md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
4911184802Sjkoshy		    M_WAITOK|M_ZERO);
4912184802Sjkoshy		if (md->pmd_pcpu_init)
4913185363Sjkoshy			error = md->pmd_pcpu_init(md, cpu);
4914184802Sjkoshy		for (n = 0; error == 0 && n < md->pmd_nclass; n++)
4915184802Sjkoshy			error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
4916145256Sjkoshy	}
4917145256Sjkoshy	pmc_restore_cpu_binding(&pb);
4918145256Sjkoshy
4919184802Sjkoshy	if (error)
4920184802Sjkoshy		return (error);
4921145256Sjkoshy
4922147191Sjkoshy	/* allocate space for the sample array */
4923183266Sjkoshy	for (cpu = 0; cpu < maxcpu; cpu++) {
4924183266Sjkoshy		if (!pmc_cpu_is_active(cpu))
4925147191Sjkoshy			continue;
4926184802Sjkoshy
4927184214Sdes		sb = malloc(sizeof(struct pmc_samplebuffer) +
4928147191Sjkoshy		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4929147191Sjkoshy		    M_WAITOK|M_ZERO);
4930147191Sjkoshy		sb->ps_read = sb->ps_write = sb->ps_samples;
4931153735Sjkoshy		sb->ps_fence = sb->ps_samples + pmc_nsamples;
4932184802Sjkoshy
4933147191Sjkoshy		KASSERT(pmc_pcpu[cpu] != NULL,
4934147191Sjkoshy		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4935147191Sjkoshy
4936184802Sjkoshy		sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4937184802Sjkoshy		    sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4938174395Sjkoshy
4939174395Sjkoshy		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4940174395Sjkoshy			ps->ps_pc = sb->ps_callchains +
4941174395Sjkoshy			    (n * pmc_callchaindepth);
4942174395Sjkoshy
4943233628Sfabient		pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
4944233628Sfabient
4945233628Sfabient		sb = malloc(sizeof(struct pmc_samplebuffer) +
4946233628Sfabient		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4947233628Sfabient		    M_WAITOK|M_ZERO);
4948233628Sfabient		sb->ps_read = sb->ps_write = sb->ps_samples;
4949233628Sfabient		sb->ps_fence = sb->ps_samples + pmc_nsamples;
4950233628Sfabient
4951233628Sfabient		KASSERT(pmc_pcpu[cpu] != NULL,
4952233628Sfabient		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4953233628Sfabient
4954233628Sfabient		sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4955233628Sfabient		    sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4956233628Sfabient
4957233628Sfabient		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4958233628Sfabient			ps->ps_pc = sb->ps_callchains +
4959233628Sfabient			    (n * pmc_callchaindepth);
4960233628Sfabient
4961233628Sfabient		pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
4962147191Sjkoshy	}
4963147191Sjkoshy
4964145256Sjkoshy	/* allocate space for the row disposition array */
4965145256Sjkoshy	pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4966145256Sjkoshy	    M_PMC, M_WAITOK|M_ZERO);
4967145256Sjkoshy
4968145256Sjkoshy	/* mark all PMCs as available */
4969145256Sjkoshy	for (n = 0; n < (int) md->pmd_npmc; n++)
4970145256Sjkoshy		PMC_MARK_ROW_FREE(n);
4971145256Sjkoshy
4972145256Sjkoshy	/* allocate thread hash tables */
4973145256Sjkoshy	pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4974145256Sjkoshy	    &pmc_ownerhashmask);
4975145256Sjkoshy
4976145256Sjkoshy	pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4977145256Sjkoshy	    &pmc_processhashmask);
4978168856Sjkoshy	mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4979168856Sjkoshy	    MTX_SPIN);
4980145256Sjkoshy
4981147191Sjkoshy	LIST_INIT(&pmc_ss_owners);
4982147191Sjkoshy	pmc_ss_count = 0;
4983147191Sjkoshy
4984145256Sjkoshy	/* allocate a pool of spin mutexes */
4985168856Sjkoshy	pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4986168856Sjkoshy	    MTX_SPIN);
4987145256Sjkoshy
4988282658Sjhb	PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4989145256Sjkoshy	    "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4990145256Sjkoshy	    pmc_processhash, pmc_processhashmask);
4991145256Sjkoshy
4992145256Sjkoshy	/* register process {exit,fork,exec} handlers */
4993145256Sjkoshy	pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4994145256Sjkoshy	    pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4995145256Sjkoshy	pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4996145256Sjkoshy	    pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4997145256Sjkoshy
4998254813Smarkj	/* register kld event handlers */
4999254813Smarkj	pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
5000254813Smarkj	    NULL, EVENTHANDLER_PRI_ANY);
5001254813Smarkj	pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
5002254813Smarkj	    NULL, EVENTHANDLER_PRI_ANY);
5003254813Smarkj
5004147191Sjkoshy	/* initialize logging */
5005147191Sjkoshy	pmclog_initialize();
5006147191Sjkoshy
5007145256Sjkoshy	/* set hook functions */
5008145256Sjkoshy	pmc_intr = md->pmd_intr;
5009145256Sjkoshy	pmc_hook = pmc_hook_handler;
5010145256Sjkoshy
5011145256Sjkoshy	if (error == 0) {
5012145256Sjkoshy		printf(PMC_MODULE_NAME ":");
5013149373Sjkoshy		for (n = 0; n < (int) md->pmd_nclass; n++) {
5014184802Sjkoshy			pcd = &md->pmd_classdep[n];
5015184997Sjkoshy			printf(" %s/%d/%d/0x%b",
5016283120Sjhb			    pmc_name_of_pmcclass(pcd->pcd_class),
5017184802Sjkoshy			    pcd->pcd_num,
5018184997Sjkoshy			    pcd->pcd_width,
5019184802Sjkoshy			    pcd->pcd_caps,
5020149373Sjkoshy			    "\20"
5021149373Sjkoshy			    "\1INT\2USR\3SYS\4EDG\5THR"
5022149373Sjkoshy			    "\6REA\7WRI\10INV\11QUA\12PRC"
5023149373Sjkoshy			    "\13TAG\14CSC");
5024149373Sjkoshy		}
5025145256Sjkoshy		printf("\n");
5026145256Sjkoshy	}
5027145256Sjkoshy
5028184802Sjkoshy	return (error);
5029145256Sjkoshy}
5030145256Sjkoshy
5031145256Sjkoshy/* prepare to be unloaded */
5032145256Sjkoshystatic void
5033145256Sjkoshypmc_cleanup(void)
5034145256Sjkoshy{
5035184802Sjkoshy	int c, cpu;
5036183266Sjkoshy	unsigned int maxcpu;
5037145256Sjkoshy	struct pmc_ownerhash *ph;
5038145256Sjkoshy	struct pmc_owner *po, *tmp;
5039145256Sjkoshy	struct pmc_binding pb;
5040282641Sjhb#ifdef	HWPMC_DEBUG
5041145256Sjkoshy	struct pmc_processhash *prh;
5042145256Sjkoshy#endif
5043145256Sjkoshy
5044282658Sjhb	PMCDBG0(MOD,INI,0, "cleanup");
5045145256Sjkoshy
5046147191Sjkoshy	/* switch off sampling */
5047222813Sattilio	CPU_ZERO(&pmc_cpumask);
5048147191Sjkoshy	pmc_intr = NULL;
5049145256Sjkoshy
5050145256Sjkoshy	sx_xlock(&pmc_sx);
5051145256Sjkoshy	if (pmc_hook == NULL) {	/* being unloaded already */
5052145256Sjkoshy		sx_xunlock(&pmc_sx);
5053145256Sjkoshy		return;
5054145256Sjkoshy	}
5055145256Sjkoshy
5056145256Sjkoshy	pmc_hook = NULL; /* prevent new threads from entering module */
5057145256Sjkoshy
5058145256Sjkoshy	/* deregister event handlers */
5059145256Sjkoshy	EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
5060145256Sjkoshy	EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
5061254813Smarkj	EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
5062254813Smarkj	EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);
5063145256Sjkoshy
5064145256Sjkoshy	/* send SIGBUS to all owner threads, free up allocations */
5065145256Sjkoshy	if (pmc_ownerhash)
5066145256Sjkoshy		for (ph = pmc_ownerhash;
5067145256Sjkoshy		     ph <= &pmc_ownerhash[pmc_ownerhashmask];
5068145256Sjkoshy		     ph++) {
5069145256Sjkoshy			LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
5070145256Sjkoshy				pmc_remove_owner(po);
5071145256Sjkoshy
5072145256Sjkoshy				/* send SIGBUS to owner processes */
5073282658Sjhb				PMCDBG3(MOD,INI,2, "cleanup signal proc=%p "
5074145256Sjkoshy				    "(%d, %s)", po->po_owner,
5075145256Sjkoshy				    po->po_owner->p_pid,
5076145256Sjkoshy				    po->po_owner->p_comm);
5077145256Sjkoshy
5078145256Sjkoshy				PROC_LOCK(po->po_owner);
5079225617Skmacy				kern_psignal(po->po_owner, SIGBUS);
5080145256Sjkoshy				PROC_UNLOCK(po->po_owner);
5081147191Sjkoshy
5082147191Sjkoshy				pmc_destroy_owner_descriptor(po);
5083145256Sjkoshy			}
5084145256Sjkoshy		}
5085145256Sjkoshy
5086145256Sjkoshy	/* reclaim allocated data structures */
5087145256Sjkoshy	if (pmc_mtxpool)
5088145256Sjkoshy		mtx_pool_destroy(&pmc_mtxpool);
5089145256Sjkoshy
5090145256Sjkoshy	mtx_destroy(&pmc_processhash_mtx);
5091145256Sjkoshy	if (pmc_processhash) {
5092282641Sjhb#ifdef	HWPMC_DEBUG
5093145256Sjkoshy		struct pmc_process *pp;
5094145256Sjkoshy
5095282658Sjhb		PMCDBG0(MOD,INI,3, "destroy process hash");
5096145256Sjkoshy		for (prh = pmc_processhash;
5097145256Sjkoshy		     prh <= &pmc_processhash[pmc_processhashmask];
5098145256Sjkoshy		     prh++)
5099145256Sjkoshy			LIST_FOREACH(pp, prh, pp_next)
5100282658Sjhb			    PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5101145256Sjkoshy#endif
5102145256Sjkoshy
5103145256Sjkoshy		hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5104145256Sjkoshy		pmc_processhash = NULL;
5105145256Sjkoshy	}
5106145256Sjkoshy
5107145256Sjkoshy	if (pmc_ownerhash) {
5108282658Sjhb		PMCDBG0(MOD,INI,3, "destroy owner hash");
5109145256Sjkoshy		hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5110145256Sjkoshy		pmc_ownerhash = NULL;
5111145256Sjkoshy	}
5112145256Sjkoshy
5113147191Sjkoshy	KASSERT(LIST_EMPTY(&pmc_ss_owners),
5114147191Sjkoshy	    ("[pmc,%d] Global SS owner list not empty", __LINE__));
5115147191Sjkoshy	KASSERT(pmc_ss_count == 0,
5116147191Sjkoshy	    ("[pmc,%d] Global SS count not empty", __LINE__));
5117147191Sjkoshy
5118184802Sjkoshy 	/* do processor and pmc-class dependent cleanup */
5119183266Sjkoshy	maxcpu = pmc_cpu_max();
5120153735Sjkoshy
5121282658Sjhb	PMCDBG0(MOD,INI,3, "md cleanup");
5122145256Sjkoshy	if (md) {
5123145256Sjkoshy		pmc_save_cpu_binding(&pb);
5124183266Sjkoshy		for (cpu = 0; cpu < maxcpu; cpu++) {
5125282658Sjhb			PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5126145256Sjkoshy			    cpu, pmc_pcpu[cpu]);
5127183266Sjkoshy			if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5128145256Sjkoshy				continue;
5129145256Sjkoshy			pmc_select_cpu(cpu);
5130184802Sjkoshy			for (c = 0; c < md->pmd_nclass; c++)
5131184802Sjkoshy				md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
5132184802Sjkoshy			if (md->pmd_pcpu_fini)
5133185363Sjkoshy				md->pmd_pcpu_fini(md, cpu);
5134145256Sjkoshy		}
5135184994Sjkoshy
5136233628Sfabient		if (md->pmd_cputype == PMC_CPU_GENERIC)
5137233628Sfabient			pmc_generic_cpu_finalize(md);
5138233628Sfabient		else
5139233628Sfabient			pmc_md_finalize(md);
5140184994Sjkoshy
5141233628Sfabient		pmc_mdep_free(md);
5142145256Sjkoshy		md = NULL;
5143145256Sjkoshy		pmc_restore_cpu_binding(&pb);
5144145256Sjkoshy	}
5145145256Sjkoshy
5146184802Sjkoshy	/* Free per-cpu descriptors. */
5147184802Sjkoshy	for (cpu = 0; cpu < maxcpu; cpu++) {
5148184802Sjkoshy		if (!pmc_cpu_is_active(cpu))
5149184802Sjkoshy			continue;
5150233628Sfabient		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5151233628Sfabient		    ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5152184802Sjkoshy			cpu));
5153233628Sfabient		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5154233628Sfabient		    ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5155233628Sfabient			cpu));
5156233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
5157233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
5158233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
5159233628Sfabient		free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
5160184802Sjkoshy		free(pmc_pcpu[cpu], M_PMC);
5161184802Sjkoshy	}
5162184802Sjkoshy
5163184205Sdes	free(pmc_pcpu, M_PMC);
5164145256Sjkoshy	pmc_pcpu = NULL;
5165145256Sjkoshy
5166184205Sdes	free(pmc_pcpu_saved, M_PMC);
5167145256Sjkoshy	pmc_pcpu_saved = NULL;
5168145256Sjkoshy
5169145256Sjkoshy	if (pmc_pmcdisp) {
5170184205Sdes		free(pmc_pmcdisp, M_PMC);
5171145256Sjkoshy		pmc_pmcdisp = NULL;
5172145256Sjkoshy	}
5173145256Sjkoshy
5174184802Sjkoshy	if (pmc_rowindex_to_classdep) {
5175184802Sjkoshy		free(pmc_rowindex_to_classdep, M_PMC);
5176184802Sjkoshy		pmc_rowindex_to_classdep = NULL;
5177184802Sjkoshy	}
5178184802Sjkoshy
5179147191Sjkoshy	pmclog_shutdown();
5180147191Sjkoshy
5181145256Sjkoshy	sx_xunlock(&pmc_sx); 	/* we are done */
5182145256Sjkoshy}
5183145256Sjkoshy
5184145256Sjkoshy/*
5185145256Sjkoshy * The function called at load/unload.
5186145256Sjkoshy */
5187145256Sjkoshy
5188145256Sjkoshystatic int
5189145256Sjkoshyload (struct module *module __unused, int cmd, void *arg __unused)
5190145256Sjkoshy{
5191145256Sjkoshy	int error;
5192145256Sjkoshy
5193145256Sjkoshy	error = 0;
5194145256Sjkoshy
5195145256Sjkoshy	switch (cmd) {
5196145256Sjkoshy	case MOD_LOAD :
5197145256Sjkoshy		/* initialize the subsystem */
5198145256Sjkoshy		error = pmc_initialize();
5199145256Sjkoshy		if (error != 0)
5200145256Sjkoshy			break;
5201282658Sjhb		PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d",
5202183266Sjkoshy		    pmc_syscall_num, pmc_cpu_max());
5203145256Sjkoshy		break;
5204145256Sjkoshy
5205145256Sjkoshy
5206145256Sjkoshy	case MOD_UNLOAD :
5207145256Sjkoshy	case MOD_SHUTDOWN:
5208145256Sjkoshy		pmc_cleanup();
5209282658Sjhb		PMCDBG0(MOD,INI,1, "unloaded");
5210145256Sjkoshy		break;
5211145256Sjkoshy
5212145256Sjkoshy	default :
5213145256Sjkoshy		error = EINVAL;	/* XXX should panic(9) */
5214145256Sjkoshy		break;
5215145256Sjkoshy	}
5216145256Sjkoshy
5217145256Sjkoshy	return error;
5218145256Sjkoshy}
5219145256Sjkoshy
5220145256Sjkoshy/* memory pool */
5221145256SjkoshyMALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");
5222