xref: /freebsd/sys/dev/hwpmc/hwpmc_mod.c (revision 42e70f4283e2f8f003e2cd9dd0774c35ab5c09b4)
1ebccf1e3SJoseph Koshy /*-
24d846d26SWarner Losh  * SPDX-License-Identifier: BSD-2-Clause
3718cf2ccSPedro F. Giffuni  *
4122ccdc1SJoseph Koshy  * Copyright (c) 2003-2008 Joseph Koshy
5d07f36b0SJoseph Koshy  * Copyright (c) 2007 The FreeBSD Foundation
6e6b475e0SMatt Macy  * Copyright (c) 2018 Matthew Macy
7ebccf1e3SJoseph Koshy  * All rights reserved.
8ebccf1e3SJoseph Koshy  *
9d07f36b0SJoseph Koshy  * Portions of this software were developed by A. Joseph Koshy under
10d07f36b0SJoseph Koshy  * sponsorship from the FreeBSD Foundation and Google, Inc.
11d07f36b0SJoseph Koshy  *
12ebccf1e3SJoseph Koshy  * Redistribution and use in source and binary forms, with or without
13ebccf1e3SJoseph Koshy  * modification, are permitted provided that the following conditions
14ebccf1e3SJoseph Koshy  * are met:
15ebccf1e3SJoseph Koshy  * 1. Redistributions of source code must retain the above copyright
16ebccf1e3SJoseph Koshy  *    notice, this list of conditions and the following disclaimer.
17ebccf1e3SJoseph Koshy  * 2. Redistributions in binary form must reproduce the above copyright
18ebccf1e3SJoseph Koshy  *    notice, this list of conditions and the following disclaimer in the
19ebccf1e3SJoseph Koshy  *    documentation and/or other materials provided with the distribution.
20ebccf1e3SJoseph Koshy  *
21ebccf1e3SJoseph Koshy  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22ebccf1e3SJoseph Koshy  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23ebccf1e3SJoseph Koshy  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24ebccf1e3SJoseph Koshy  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25ebccf1e3SJoseph Koshy  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26ebccf1e3SJoseph Koshy  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27ebccf1e3SJoseph Koshy  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28ebccf1e3SJoseph Koshy  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29ebccf1e3SJoseph Koshy  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30ebccf1e3SJoseph Koshy  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31ebccf1e3SJoseph Koshy  * SUCH DAMAGE.
32ebccf1e3SJoseph Koshy  */
33ebccf1e3SJoseph Koshy 
34ebccf1e3SJoseph Koshy #include <sys/cdefs.h>
35ebccf1e3SJoseph Koshy #include <sys/param.h>
369b1d850bSMark Johnston #include <sys/systm.h>
379978bd99SMark Johnston #include <sys/domainset.h>
38ebccf1e3SJoseph Koshy #include <sys/eventhandler.h>
39ebccf1e3SJoseph Koshy #include <sys/jail.h>
40ebccf1e3SJoseph Koshy #include <sys/kernel.h>
41f263522aSJoseph Koshy #include <sys/kthread.h>
42ebccf1e3SJoseph Koshy #include <sys/limits.h>
43ebccf1e3SJoseph Koshy #include <sys/lock.h>
44ebccf1e3SJoseph Koshy #include <sys/malloc.h>
45ebccf1e3SJoseph Koshy #include <sys/module.h>
46e9b5dc16SJoseph Koshy #include <sys/mount.h>
47ebccf1e3SJoseph Koshy #include <sys/mutex.h>
48ebccf1e3SJoseph Koshy #include <sys/pmc.h>
49ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
50f263522aSJoseph Koshy #include <sys/pmclog.h>
51acd3428bSRobert Watson #include <sys/priv.h>
52ebccf1e3SJoseph Koshy #include <sys/proc.h>
53ebccf1e3SJoseph Koshy #include <sys/queue.h>
54f263522aSJoseph Koshy #include <sys/resourcevar.h>
5589f6b863SAttilio Rao #include <sys/rwlock.h>
56ebccf1e3SJoseph Koshy #include <sys/sched.h>
57ebccf1e3SJoseph Koshy #include <sys/signalvar.h>
58ebccf1e3SJoseph Koshy #include <sys/smp.h>
59ebccf1e3SJoseph Koshy #include <sys/sx.h>
60ebccf1e3SJoseph Koshy #include <sys/sysctl.h>
61ebccf1e3SJoseph Koshy #include <sys/sysent.h>
620204d85aSMatt Macy #include <sys/syslog.h>
639b1d850bSMark Johnston #include <sys/taskqueue.h>
64f263522aSJoseph Koshy #include <sys/vnode.h>
65ebccf1e3SJoseph Koshy 
6649874f6eSJoseph Koshy #include <sys/linker.h>		/* needs to be after <sys/malloc.h> */
6749874f6eSJoseph Koshy 
68f263522aSJoseph Koshy #include <machine/atomic.h>
69ebccf1e3SJoseph Koshy #include <machine/md_var.h>
70ebccf1e3SJoseph Koshy 
71bf792d68SJoseph Koshy #include <vm/vm.h>
72bf792d68SJoseph Koshy #include <vm/vm_extern.h>
73bf792d68SJoseph Koshy #include <vm/pmap.h>
74bf792d68SJoseph Koshy #include <vm/vm_map.h>
75bf792d68SJoseph Koshy #include <vm/vm_object.h>
76bf792d68SJoseph Koshy 
77f5f9340bSFabien Thomas #include "hwpmc_soft.h"
78f5f9340bSFabien Thomas 
79693cd307SMitchell Horne #define PMC_EPOCH_ENTER()						\
80693cd307SMitchell Horne     struct epoch_tracker pmc_et;					\
81693cd307SMitchell Horne     epoch_enter_preempt(global_epoch_preempt, &pmc_et)
82693cd307SMitchell Horne 
83693cd307SMitchell Horne #define PMC_EPOCH_EXIT()						\
84693cd307SMitchell Horne     epoch_exit_preempt(global_epoch_preempt, &pmc_et)
856573d758SMatt Macy 
86ebccf1e3SJoseph Koshy /*
87ebccf1e3SJoseph Koshy  * Types
88ebccf1e3SJoseph Koshy  */
89ebccf1e3SJoseph Koshy 
90ebccf1e3SJoseph Koshy enum pmc_flags {
91ebccf1e3SJoseph Koshy 	PMC_FLAG_NONE	  = 0x00, /* do nothing */
92ebccf1e3SJoseph Koshy 	PMC_FLAG_REMOVE   = 0x01, /* atomically remove entry from hash */
93ebccf1e3SJoseph Koshy 	PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
946161b98cSMatt Macy 	PMC_FLAG_NOWAIT   = 0x04, /* do not wait for mallocs */
95ebccf1e3SJoseph Koshy };
96ebccf1e3SJoseph Koshy 
97ebccf1e3SJoseph Koshy /*
98ebccf1e3SJoseph Koshy  * The offset in sysent where the syscall is allocated.
99ebccf1e3SJoseph Koshy  */
100ebccf1e3SJoseph Koshy static int pmc_syscall_num = NO_SYSCALL;
101693cd307SMitchell Horne 
102ebccf1e3SJoseph Koshy struct pmc_cpu		**pmc_pcpu;	 /* per-cpu state */
103ebccf1e3SJoseph Koshy pmc_value_t		*pmc_pcpu_saved; /* saved PMC values: CSW handling */
104ebccf1e3SJoseph Koshy 
105ebccf1e3SJoseph Koshy #define	PMC_PCPU_SAVED(C, R)	pmc_pcpu_saved[(R) + md->pmd_npmc * (C)]
106ebccf1e3SJoseph Koshy 
107ebccf1e3SJoseph Koshy struct mtx_pool		*pmc_mtxpool;
108ebccf1e3SJoseph Koshy static int		*pmc_pmcdisp;	 /* PMC row dispositions */
109ebccf1e3SJoseph Koshy 
110ebccf1e3SJoseph Koshy #define	PMC_ROW_DISP_IS_FREE(R)		(pmc_pmcdisp[(R)] == 0)
111ebccf1e3SJoseph Koshy #define	PMC_ROW_DISP_IS_THREAD(R)	(pmc_pmcdisp[(R)] > 0)
112ebccf1e3SJoseph Koshy #define	PMC_ROW_DISP_IS_STANDALONE(R)	(pmc_pmcdisp[(R)] < 0)
113ebccf1e3SJoseph Koshy 
114ebccf1e3SJoseph Koshy #define	PMC_MARK_ROW_FREE(R) do {					  \
115ebccf1e3SJoseph Koshy 	pmc_pmcdisp[(R)] = 0;						  \
116ebccf1e3SJoseph Koshy } while (0)
117ebccf1e3SJoseph Koshy 
118ebccf1e3SJoseph Koshy #define	PMC_MARK_ROW_STANDALONE(R) do {					  \
119ebccf1e3SJoseph Koshy 	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
120ebccf1e3SJoseph Koshy 		    __LINE__));						  \
121ebccf1e3SJoseph Koshy 	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
122122ccdc1SJoseph Koshy 	KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()),		  \
123122ccdc1SJoseph Koshy 		("[pmc,%d] row disposition error", __LINE__));		  \
124ebccf1e3SJoseph Koshy } while (0)
125ebccf1e3SJoseph Koshy 
126ebccf1e3SJoseph Koshy #define	PMC_UNMARK_ROW_STANDALONE(R) do { 				  \
127ebccf1e3SJoseph Koshy 	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
128ebccf1e3SJoseph Koshy 	KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
129ebccf1e3SJoseph Koshy 		    __LINE__));						  \
130ebccf1e3SJoseph Koshy } while (0)
131ebccf1e3SJoseph Koshy 
132ebccf1e3SJoseph Koshy #define	PMC_MARK_ROW_THREAD(R) do {					  \
133ebccf1e3SJoseph Koshy 	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
134ebccf1e3SJoseph Koshy 		    __LINE__));						  \
135ebccf1e3SJoseph Koshy 	atomic_add_int(&pmc_pmcdisp[(R)], 1);				  \
136ebccf1e3SJoseph Koshy } while (0)
137ebccf1e3SJoseph Koshy 
138ebccf1e3SJoseph Koshy #define	PMC_UNMARK_ROW_THREAD(R) do {					  \
139ebccf1e3SJoseph Koshy 	atomic_add_int(&pmc_pmcdisp[(R)], -1);				  \
140ebccf1e3SJoseph Koshy 	KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
141ebccf1e3SJoseph Koshy 		    __LINE__));						  \
142ebccf1e3SJoseph Koshy } while (0)
143ebccf1e3SJoseph Koshy 
144ebccf1e3SJoseph Koshy /* various event handlers */
14529f4e216SMark Johnston static eventhandler_tag	pmc_exit_tag, pmc_fork_tag, pmc_kld_load_tag,
14629f4e216SMark Johnston     pmc_kld_unload_tag;
147ebccf1e3SJoseph Koshy 
148ebccf1e3SJoseph Koshy /* Module statistics */
149e6b475e0SMatt Macy struct pmc_driverstats pmc_stats;
150e6b475e0SMatt Macy 
151ebccf1e3SJoseph Koshy /* Machine/processor dependent operations */
1520cfab8ddSJoseph Koshy static struct pmc_mdep  *md;
153ebccf1e3SJoseph Koshy 
154ebccf1e3SJoseph Koshy /*
155ebccf1e3SJoseph Koshy  * Hash tables mapping owner processes and target threads to PMCs.
156ebccf1e3SJoseph Koshy  */
157ebccf1e3SJoseph Koshy struct mtx pmc_processhash_mtx;		/* spin mutex */
158ebccf1e3SJoseph Koshy static u_long pmc_processhashmask;
159ebccf1e3SJoseph Koshy static LIST_HEAD(pmc_processhash, pmc_process) *pmc_processhash;
160ebccf1e3SJoseph Koshy 
161ebccf1e3SJoseph Koshy /*
162ebccf1e3SJoseph Koshy  * Hash table of PMC owner descriptors.  This table is protected by
163ebccf1e3SJoseph Koshy  * the shared PMC "sx" lock.
164ebccf1e3SJoseph Koshy  */
165ebccf1e3SJoseph Koshy static u_long pmc_ownerhashmask;
166ebccf1e3SJoseph Koshy static LIST_HEAD(pmc_ownerhash, pmc_owner) *pmc_ownerhash;
167ebccf1e3SJoseph Koshy 
168ebccf1e3SJoseph Koshy /*
169f263522aSJoseph Koshy  * List of PMC owners with system-wide sampling PMCs.
170f263522aSJoseph Koshy  */
1710f8d79d9SMatt Macy static CK_LIST_HEAD(, pmc_owner) pmc_ss_owners;
172f263522aSJoseph Koshy 
1736161b98cSMatt Macy /*
1746161b98cSMatt Macy  * List of free thread entries. This is protected by the spin
1756161b98cSMatt Macy  * mutex.
1766161b98cSMatt Macy  */
1776161b98cSMatt Macy static struct mtx pmc_threadfreelist_mtx;	/* spin mutex */
1786161b98cSMatt Macy static LIST_HEAD(, pmc_thread) pmc_threadfreelist;
1796161b98cSMatt Macy static int pmc_threadfreelist_entries = 0;
180693cd307SMitchell Horne #define	THREADENTRY_SIZE	(sizeof(struct pmc_thread) +		\
181693cd307SMitchell Horne     (md->pmd_npmc * sizeof(struct pmc_threadpmcstate)))
1826161b98cSMatt Macy 
1836161b98cSMatt Macy /*
1846161b98cSMatt Macy  * Task to free thread descriptors
1856161b98cSMatt Macy  */
1869b1d850bSMark Johnston static struct task free_task;
187f263522aSJoseph Koshy 
188f263522aSJoseph Koshy /*
189e829eb6dSJoseph Koshy  * A map of row indices to classdep structures.
190e829eb6dSJoseph Koshy  */
191e829eb6dSJoseph Koshy static struct pmc_classdep **pmc_rowindex_to_classdep;
192e829eb6dSJoseph Koshy 
193e829eb6dSJoseph Koshy /*
194ebccf1e3SJoseph Koshy  * Prototypes
195ebccf1e3SJoseph Koshy  */
196ebccf1e3SJoseph Koshy 
197680f1afdSJohn Baldwin #ifdef HWPMC_DEBUG
198ebccf1e3SJoseph Koshy static int	pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
199ebccf1e3SJoseph Koshy static int	pmc_debugflags_parse(char *newstr, char *fence);
200ebccf1e3SJoseph Koshy #endif
201ebccf1e3SJoseph Koshy 
202ebccf1e3SJoseph Koshy static int	load(struct module *module, int cmd, void *arg);
203693cd307SMitchell Horne static int	pmc_add_sample(ring_type_t ring, struct pmc *pm,
204693cd307SMitchell Horne     struct trapframe *tf);
2056161b98cSMatt Macy static void	pmc_add_thread_descriptors_from_proc(struct proc *p,
2066161b98cSMatt Macy     struct pmc_process *pp);
207f263522aSJoseph Koshy static int	pmc_attach_process(struct proc *p, struct pmc *pm);
208ebccf1e3SJoseph Koshy static struct pmc *pmc_allocate_pmc_descriptor(void);
209f263522aSJoseph Koshy static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
210f263522aSJoseph Koshy static int	pmc_attach_one_process(struct proc *p, struct pmc *pm);
211c514a571SMitchell Horne static bool	pmc_can_allocate_row(int ri, enum pmc_mode mode);
212c514a571SMitchell Horne static bool	pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
213c5153e19SJoseph Koshy     int cpu);
214f263522aSJoseph Koshy static int	pmc_can_attach(struct pmc *pm, struct proc *p);
215693cd307SMitchell Horne static void	pmc_capture_user_callchain(int cpu, int soft,
216693cd307SMitchell Horne     struct trapframe *tf);
217f263522aSJoseph Koshy static void	pmc_cleanup(void);
218f263522aSJoseph Koshy static int	pmc_detach_process(struct proc *p, struct pmc *pm);
219f263522aSJoseph Koshy static int	pmc_detach_one_process(struct proc *p, struct pmc *pm,
220f263522aSJoseph Koshy     int flags);
221f263522aSJoseph Koshy static void	pmc_destroy_owner_descriptor(struct pmc_owner *po);
22206796b67SMark Johnston static void	pmc_destroy_pmc_descriptor(struct pmc *pm);
2236161b98cSMatt Macy static void	pmc_destroy_process_descriptor(struct pmc_process *pp);
224ebccf1e3SJoseph Koshy static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
225ebccf1e3SJoseph Koshy static int	pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
226f263522aSJoseph Koshy static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
227f263522aSJoseph Koshy     pmc_id_t pmc);
228f263522aSJoseph Koshy static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
229f263522aSJoseph Koshy     uint32_t mode);
2306161b98cSMatt Macy static struct pmc_thread *pmc_find_thread_descriptor(struct pmc_process *pp,
2316161b98cSMatt Macy     struct thread *td, uint32_t mode);
232c5153e19SJoseph Koshy static void	pmc_force_context_switch(void);
233ebccf1e3SJoseph Koshy static void	pmc_link_target_process(struct pmc *pm,
234ebccf1e3SJoseph Koshy     struct pmc_process *pp);
235d07f36b0SJoseph Koshy static void	pmc_log_all_process_mappings(struct pmc_owner *po);
236d07f36b0SJoseph Koshy static void	pmc_log_kernel_mappings(struct pmc *pm);
237d07f36b0SJoseph Koshy static void	pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
238f263522aSJoseph Koshy static void	pmc_maybe_remove_owner(struct pmc_owner *po);
239e4fbd039SMitchell Horne static void	pmc_post_callchain_callback(void);
240e4fbd039SMitchell Horne static void	pmc_process_allproc(struct pmc *pm);
241f263522aSJoseph Koshy static void	pmc_process_csw_in(struct thread *td);
242f263522aSJoseph Koshy static void	pmc_process_csw_out(struct thread *td);
243c4981694SMitchell Horne static void	pmc_process_exec(struct thread *td,
244c4981694SMitchell Horne     struct pmckern_procexec *pk);
245ebccf1e3SJoseph Koshy static void	pmc_process_exit(void *arg, struct proc *p);
246ebccf1e3SJoseph Koshy static void	pmc_process_fork(void *arg, struct proc *p1,
247ebccf1e3SJoseph Koshy     struct proc *p2, int n);
248e4fbd039SMitchell Horne static void	pmc_process_proccreate(struct proc *p);
249d9f1b8dbSMatt Macy static void	pmc_process_samples(int cpu, ring_type_t soft);
250e4fbd039SMitchell Horne static void	pmc_process_threadcreate(struct thread *td);
251e4fbd039SMitchell Horne static void	pmc_process_threadexit(struct thread *td);
2526161b98cSMatt Macy static void	pmc_process_thread_add(struct thread *td);
2536161b98cSMatt Macy static void	pmc_process_thread_delete(struct thread *td);
2545de96e33SMatt Macy static void	pmc_process_thread_userret(struct thread *td);
255e4fbd039SMitchell Horne static void	pmc_release_pmc_descriptor(struct pmc *pmc);
256f263522aSJoseph Koshy static void	pmc_remove_owner(struct pmc_owner *po);
257f263522aSJoseph Koshy static void	pmc_remove_process_descriptor(struct pmc_process *pp);
258ebccf1e3SJoseph Koshy static int	pmc_start(struct pmc *pm);
259ebccf1e3SJoseph Koshy static int	pmc_stop(struct pmc *pm);
260f263522aSJoseph Koshy static int	pmc_syscall_handler(struct thread *td, void *syscall_args);
2616161b98cSMatt Macy static struct pmc_thread *pmc_thread_descriptor_pool_alloc(void);
2626161b98cSMatt Macy static void	pmc_thread_descriptor_pool_drain(void);
2636161b98cSMatt Macy static void	pmc_thread_descriptor_pool_free(struct pmc_thread *pt);
264f263522aSJoseph Koshy static void	pmc_unlink_target_process(struct pmc *pmc,
265f263522aSJoseph Koshy     struct pmc_process *pp);
266e4fbd039SMitchell Horne 
267f5f9340bSFabien Thomas static int	generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
268f5f9340bSFabien Thomas static int	generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
269f5f9340bSFabien Thomas static struct pmc_mdep *pmc_generic_cpu_initialize(void);
270f5f9340bSFabien Thomas static void	pmc_generic_cpu_finalize(struct pmc_mdep *md);
271ebfaf69cSMatt Macy 
272ebccf1e3SJoseph Koshy /*
273ebccf1e3SJoseph Koshy  * Kernel tunables and sysctl(8) interface.
274ebccf1e3SJoseph Koshy  */
275ebccf1e3SJoseph Koshy 
276f5f9340bSFabien Thomas SYSCTL_DECL(_kern_hwpmc);
2777029da5cSPawel Biernacki SYSCTL_NODE(_kern_hwpmc, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
2787029da5cSPawel Biernacki     "HWPMC stats");
279e6b475e0SMatt Macy 
280e6b475e0SMatt Macy /* Stats. */
281e6b475e0SMatt Macy SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_ignored, CTLFLAG_RW,
282693cd307SMitchell Horne     &pmc_stats.pm_intr_ignored,
283693cd307SMitchell Horne     "# of interrupts ignored");
284e6b475e0SMatt Macy SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_processed, CTLFLAG_RW,
285693cd307SMitchell Horne     &pmc_stats.pm_intr_processed,
286693cd307SMitchell Horne     "# of interrupts processed");
287e6b475e0SMatt Macy SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_bufferfull, CTLFLAG_RW,
288693cd307SMitchell Horne     &pmc_stats.pm_intr_bufferfull,
289693cd307SMitchell Horne     "# of interrupts where buffer was full");
290e6b475e0SMatt Macy SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscalls, CTLFLAG_RW,
291693cd307SMitchell Horne     &pmc_stats.pm_syscalls,
292693cd307SMitchell Horne     "# of syscalls");
293e6b475e0SMatt Macy SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscall_errors, CTLFLAG_RW,
294693cd307SMitchell Horne     &pmc_stats.pm_syscall_errors,
295693cd307SMitchell Horne     "# of syscall_errors");
296e6b475e0SMatt Macy SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests, CTLFLAG_RW,
297693cd307SMitchell Horne     &pmc_stats.pm_buffer_requests,
298693cd307SMitchell Horne     "# of buffer requests");
299693cd307SMitchell Horne SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests_failed,
300693cd307SMitchell Horne     CTLFLAG_RW, &pmc_stats.pm_buffer_requests_failed,
301693cd307SMitchell Horne     "# of buffer requests which failed");
302e6b475e0SMatt Macy SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, log_sweeps, CTLFLAG_RW,
303693cd307SMitchell Horne     &pmc_stats.pm_log_sweeps,
304693cd307SMitchell Horne     "# of times samples were processed");
3055de96e33SMatt Macy SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, merges, CTLFLAG_RW,
306693cd307SMitchell Horne     &pmc_stats.pm_merges,
307693cd307SMitchell Horne     "# of times kernel stack was found for user trace");
3085de96e33SMatt Macy SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, overwrites, CTLFLAG_RW,
309693cd307SMitchell Horne     &pmc_stats.pm_overwrites,
310693cd307SMitchell Horne     "# of times a sample was overwritten before being logged");
311ebccf1e3SJoseph Koshy 
312d07f36b0SJoseph Koshy static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
313af3b2549SHans Petter Selasky SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_RDTUN,
314693cd307SMitchell Horne     &pmc_callchaindepth, 0,
315693cd307SMitchell Horne     "depth of call chain records");
316d07f36b0SJoseph Koshy 
31724e337beSRyan Moeller char pmc_cpuid[PMC_CPUID_LEN];
318e6b475e0SMatt Macy SYSCTL_STRING(_kern_hwpmc, OID_AUTO, cpuid, CTLFLAG_RD,
319693cd307SMitchell Horne     pmc_cpuid, 0,
320693cd307SMitchell Horne     "cpu version string");
321693cd307SMitchell Horne 
322680f1afdSJohn Baldwin #ifdef HWPMC_DEBUG
323f263522aSJoseph Koshy struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
324ebccf1e3SJoseph Koshy char	pmc_debugstr[PMC_DEBUG_STRSIZE];
325ebccf1e3SJoseph Koshy TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
326ebccf1e3SJoseph Koshy     sizeof(pmc_debugstr));
327ebccf1e3SJoseph Koshy SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
3281886cef6SAlexander Motin     CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE,
3297029da5cSPawel Biernacki     0, 0, pmc_debugflags_sysctl_handler, "A",
3307029da5cSPawel Biernacki     "debug flags");
331ebccf1e3SJoseph Koshy #endif
332ebccf1e3SJoseph Koshy 
333ebccf1e3SJoseph Koshy /*
33401c35b67SMitchell Horne  * kern.hwpmc.hashsize -- determines the number of rows in the
335ebccf1e3SJoseph Koshy  * of the hash table used to look up threads
336ebccf1e3SJoseph Koshy  */
337ebccf1e3SJoseph Koshy static int pmc_hashsize = PMC_HASH_SIZE;
338af3b2549SHans Petter Selasky SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_RDTUN,
339693cd307SMitchell Horne     &pmc_hashsize, 0,
340693cd307SMitchell Horne     "rows in hash tables");
341ebccf1e3SJoseph Koshy 
342ebccf1e3SJoseph Koshy /*
343d07f36b0SJoseph Koshy  * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
344ebccf1e3SJoseph Koshy  */
345f263522aSJoseph Koshy static int pmc_nsamples = PMC_NSAMPLES;
346af3b2549SHans Petter Selasky SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_RDTUN,
347693cd307SMitchell Horne     &pmc_nsamples, 0,
348693cd307SMitchell Horne     "number of PC samples per CPU");
349ebccf1e3SJoseph Koshy 
350d9f1b8dbSMatt Macy static uint64_t pmc_sample_mask = PMC_NSAMPLES - 1;
351d07f36b0SJoseph Koshy 
352ebccf1e3SJoseph Koshy /*
353f263522aSJoseph Koshy  * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
354ebccf1e3SJoseph Koshy  */
355ebccf1e3SJoseph Koshy static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
356af3b2549SHans Petter Selasky SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_RDTUN,
357693cd307SMitchell Horne     &pmc_mtxpool_size, 0,
358693cd307SMitchell Horne     "size of spin mutex pool");
359ebccf1e3SJoseph Koshy 
360ebccf1e3SJoseph Koshy /*
3616161b98cSMatt Macy  * kern.hwpmc.threadfreelist_entries -- number of free entries
3626161b98cSMatt Macy  */
3636161b98cSMatt Macy SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_entries, CTLFLAG_RD,
364693cd307SMitchell Horne     &pmc_threadfreelist_entries, 0,
365693cd307SMitchell Horne     "number of available thread entries");
3666161b98cSMatt Macy 
3676161b98cSMatt Macy /*
3686161b98cSMatt Macy  * kern.hwpmc.threadfreelist_max -- maximum number of free entries
3696161b98cSMatt Macy  */
3706161b98cSMatt Macy static int pmc_threadfreelist_max = PMC_THREADLIST_MAX;
3716161b98cSMatt Macy SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_max, CTLFLAG_RW,
3726161b98cSMatt Macy     &pmc_threadfreelist_max, 0,
3736161b98cSMatt Macy     "maximum number of available thread entries before freeing some");
3746161b98cSMatt Macy 
3756161b98cSMatt Macy /*
376ca341f3cSJohn Baldwin  * kern.hwpmc.mincount -- minimum sample count
377ca341f3cSJohn Baldwin  */
378ca341f3cSJohn Baldwin static u_int pmc_mincount = 1000;
379ca341f3cSJohn Baldwin SYSCTL_INT(_kern_hwpmc, OID_AUTO, mincount, CTLFLAG_RWTUN,
380ca341f3cSJohn Baldwin     &pmc_mincount, 0,
381ca341f3cSJohn Baldwin     "minimum count for sampling counters");
382ca341f3cSJohn Baldwin 
383ca341f3cSJohn Baldwin /*
384ebccf1e3SJoseph Koshy  * security.bsd.unprivileged_syspmcs -- allow non-root processes to
385ebccf1e3SJoseph Koshy  * allocate system-wide PMCs.
386ebccf1e3SJoseph Koshy  *
387ebccf1e3SJoseph Koshy  * Allowing unprivileged processes to allocate system PMCs is convenient
388ebccf1e3SJoseph Koshy  * if system-wide measurements need to be taken concurrently with other
389ebccf1e3SJoseph Koshy  * per-process measurements.  This feature is turned off by default.
390ebccf1e3SJoseph Koshy  */
391ebccf1e3SJoseph Koshy static int pmc_unprivileged_syspmcs = 0;
392af3b2549SHans Petter Selasky SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RWTUN,
393ebccf1e3SJoseph Koshy     &pmc_unprivileged_syspmcs, 0,
394ebccf1e3SJoseph Koshy     "allow unprivileged process to allocate system PMCs");
395ebccf1e3SJoseph Koshy 
396f263522aSJoseph Koshy /*
397f263522aSJoseph Koshy  * Hash function.  Discard the lower 2 bits of the pointer since
398f263522aSJoseph Koshy  * these are always zero for our uses.  The hash multiplier is
399f263522aSJoseph Koshy  * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
400f263522aSJoseph Koshy  */
401ebccf1e3SJoseph Koshy #if	LONG_BIT == 64
402ebccf1e3SJoseph Koshy #define	_PMC_HM		11400714819323198486u
403ebccf1e3SJoseph Koshy #elif	LONG_BIT == 32
404ebccf1e3SJoseph Koshy #define	_PMC_HM		2654435769u
405ebccf1e3SJoseph Koshy #else
406ebccf1e3SJoseph Koshy #error 	Must know the size of 'long' to compile
407ebccf1e3SJoseph Koshy #endif
408ebccf1e3SJoseph Koshy 
409ebccf1e3SJoseph Koshy #define	PMC_HASH_PTR(P,M)	((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
410ebccf1e3SJoseph Koshy 
411ebccf1e3SJoseph Koshy /*
412ebccf1e3SJoseph Koshy  * Syscall structures
413ebccf1e3SJoseph Koshy  */
414ebccf1e3SJoseph Koshy 
415ebccf1e3SJoseph Koshy /* The `sysent' for the new syscall */
416ebccf1e3SJoseph Koshy static struct sysent pmc_sysent = {
4171cfbc451SKonstantin Belousov 	.sy_narg =	2,
4181cfbc451SKonstantin Belousov 	.sy_call =	pmc_syscall_handler,
419ebccf1e3SJoseph Koshy };
420ebccf1e3SJoseph Koshy 
421ebccf1e3SJoseph Koshy static struct syscall_module_data pmc_syscall_mod = {
4221cfbc451SKonstantin Belousov 	.chainevh =	load,
4231cfbc451SKonstantin Belousov 	.chainarg =	NULL,
4241cfbc451SKonstantin Belousov 	.offset =	&pmc_syscall_num,
4251cfbc451SKonstantin Belousov 	.new_sysent =	&pmc_sysent,
4261cfbc451SKonstantin Belousov 	.old_sysent =	{ .sy_narg = 0, .sy_call = NULL },
4271cfbc451SKonstantin Belousov 	.flags =	SY_THR_STATIC_KLD,
428ebccf1e3SJoseph Koshy };
429ebccf1e3SJoseph Koshy 
430ebccf1e3SJoseph Koshy static moduledata_t pmc_mod = {
4311cfbc451SKonstantin Belousov 	.name =		PMC_MODULE_NAME,
4321cfbc451SKonstantin Belousov 	.evhand =	syscall_module_handler,
4331cfbc451SKonstantin Belousov 	.priv =		&pmc_syscall_mod,
434ebccf1e3SJoseph Koshy };
435ebccf1e3SJoseph Koshy 
436fdce57a0SJohn Baldwin #ifdef EARLY_AP_STARTUP
437fdce57a0SJohn Baldwin DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SYSCALLS, SI_ORDER_ANY);
438fdce57a0SJohn Baldwin #else
439ebccf1e3SJoseph Koshy DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
440fdce57a0SJohn Baldwin #endif
441ebccf1e3SJoseph Koshy MODULE_VERSION(pmc, PMC_VERSION);
442ebccf1e3SJoseph Koshy 
443680f1afdSJohn Baldwin #ifdef HWPMC_DEBUG
444f263522aSJoseph Koshy enum pmc_dbgparse_state {
445f263522aSJoseph Koshy 	PMCDS_WS,		/* in whitespace */
446f263522aSJoseph Koshy 	PMCDS_MAJOR,		/* seen a major keyword */
447f263522aSJoseph Koshy 	PMCDS_MINOR
448f263522aSJoseph Koshy };
449f263522aSJoseph Koshy 
450ebccf1e3SJoseph Koshy static int
451ebccf1e3SJoseph Koshy pmc_debugflags_parse(char *newstr, char *fence)
452ebccf1e3SJoseph Koshy {
453f263522aSJoseph Koshy 	struct pmc_debugflags *tmpflags;
454f263522aSJoseph Koshy 	size_t kwlen;
45501c35b67SMitchell Horne 	char c, *p, *q;
45601c35b67SMitchell Horne 	int error, *newbits, tmp;
45701c35b67SMitchell Horne 	int found;
458ebccf1e3SJoseph Koshy 
459e11e3f18SDag-Erling Smørgrav 	tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK | M_ZERO);
460ebccf1e3SJoseph Koshy 
461f263522aSJoseph Koshy 	error = 0;
462d5ee4074SMitchell Horne 	for (p = newstr; p < fence && (c = *p); p++) {
463f263522aSJoseph Koshy 		/* skip white space */
464f263522aSJoseph Koshy 		if (c == ' ' || c == '\t')
465f263522aSJoseph Koshy 			continue;
466f263522aSJoseph Koshy 
467f263522aSJoseph Koshy 		/* look for a keyword followed by "=" */
468f263522aSJoseph Koshy 		for (q = p; p < fence && (c = *p) && c != '='; p++)
469f263522aSJoseph Koshy 			;
470f263522aSJoseph Koshy 		if (c != '=') {
471f263522aSJoseph Koshy 			error = EINVAL;
472f263522aSJoseph Koshy 			goto done;
473ebccf1e3SJoseph Koshy 		}
474ebccf1e3SJoseph Koshy 
475f263522aSJoseph Koshy 		kwlen = p - q;
476f263522aSJoseph Koshy 		newbits = NULL;
477ebccf1e3SJoseph Koshy 
478f263522aSJoseph Koshy 		/* lookup flag group name */
479f263522aSJoseph Koshy #define	DBG_SET_FLAG_MAJ(S,F)						\
480f263522aSJoseph Koshy 		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
481f263522aSJoseph Koshy 			newbits = &tmpflags->pdb_ ## F;
482ebccf1e3SJoseph Koshy 
483f263522aSJoseph Koshy 		DBG_SET_FLAG_MAJ("cpu",		CPU);
484f263522aSJoseph Koshy 		DBG_SET_FLAG_MAJ("csw",		CSW);
485f263522aSJoseph Koshy 		DBG_SET_FLAG_MAJ("logging",	LOG);
486f263522aSJoseph Koshy 		DBG_SET_FLAG_MAJ("module",	MOD);
487f263522aSJoseph Koshy 		DBG_SET_FLAG_MAJ("md", 		MDP);
488f263522aSJoseph Koshy 		DBG_SET_FLAG_MAJ("owner",	OWN);
489f263522aSJoseph Koshy 		DBG_SET_FLAG_MAJ("pmc",		PMC);
490f263522aSJoseph Koshy 		DBG_SET_FLAG_MAJ("process",	PRC);
491f263522aSJoseph Koshy 		DBG_SET_FLAG_MAJ("sampling", 	SAM);
49201c35b67SMitchell Horne #undef DBG_SET_FLAG_MAJ
493ebccf1e3SJoseph Koshy 
494f263522aSJoseph Koshy 		if (newbits == NULL) {
495f263522aSJoseph Koshy 			error = EINVAL;
496f263522aSJoseph Koshy 			goto done;
497ebccf1e3SJoseph Koshy 		}
498ebccf1e3SJoseph Koshy 
499f263522aSJoseph Koshy 		p++;		/* skip the '=' */
500ebccf1e3SJoseph Koshy 
501f263522aSJoseph Koshy 		/* Now parse the individual flags */
502f263522aSJoseph Koshy 		tmp = 0;
503f263522aSJoseph Koshy 	newflag:
504f263522aSJoseph Koshy 		for (q = p; p < fence && (c = *p); p++)
505f263522aSJoseph Koshy 			if (c == ' ' || c == '\t' || c == ',')
506f263522aSJoseph Koshy 				break;
507f263522aSJoseph Koshy 
508f263522aSJoseph Koshy 		/* p == fence or c == ws or c == "," or c == 0 */
509f263522aSJoseph Koshy 
510f263522aSJoseph Koshy 		if ((kwlen = p - q) == 0) {
511f263522aSJoseph Koshy 			*newbits = tmp;
512f263522aSJoseph Koshy 			continue;
513f263522aSJoseph Koshy 		}
514f263522aSJoseph Koshy 
515f263522aSJoseph Koshy 		found = 0;
516f263522aSJoseph Koshy #define	DBG_SET_FLAG_MIN(S,F)						\
517f263522aSJoseph Koshy 		if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)	\
518f263522aSJoseph Koshy 			tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
519f263522aSJoseph Koshy 
520f263522aSJoseph Koshy 		/* a '*' denotes all possible flags in the group */
521f263522aSJoseph Koshy 		if (kwlen == 1 && *q == '*')
522f263522aSJoseph Koshy 			tmp = found = ~0;
523f263522aSJoseph Koshy 		/* look for individual flag names */
524f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("allocaterow", ALR);
525f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("allocate",	ALL);
526f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("attach",	ATT);
527f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("bind",	BND);
528f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("config",	CFG);
529f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("exec",	EXC);
530f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("exit",	EXT);
531f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("find",	FND);
532f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("flush",	FLS);
533f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("fork",	FRK);
534f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("getbuf",	GTB);
535f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("hook",	PMH);
536f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("init",	INI);
537f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("intr",	INT);
538f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("linktarget",	TLK);
539f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("mayberemove", OMR);
540f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("ops",		OPS);
541f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("read",	REA);
542f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("register",	REG);
543f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("release",	REL);
544f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("remove",	ORM);
545f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("sample",	SAM);
546f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("scheduleio",	SIO);
547f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("select",	SEL);
548f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("signal",	SIG);
549f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("swi",		SWI);
550f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("swo",		SWO);
551f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("start",	STA);
552f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("stop",	STO);
553f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("syscall",	PMS);
554f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("unlinktarget", TUL);
555f263522aSJoseph Koshy 		DBG_SET_FLAG_MIN("write",	WRI);
55601c35b67SMitchell Horne #undef DBG_SET_FLAG_MIN
557f263522aSJoseph Koshy 		if (found == 0) {
558f263522aSJoseph Koshy 			/* unrecognized flag name */
559f263522aSJoseph Koshy 			error = EINVAL;
560f263522aSJoseph Koshy 			goto done;
561f263522aSJoseph Koshy 		}
562f263522aSJoseph Koshy 
563f263522aSJoseph Koshy 		if (c == 0 || c == ' ' || c == '\t') {	/* end of flag group */
564f263522aSJoseph Koshy 			*newbits = tmp;
565f263522aSJoseph Koshy 			continue;
566f263522aSJoseph Koshy 		}
567f263522aSJoseph Koshy 
568f263522aSJoseph Koshy 		p++;
569f263522aSJoseph Koshy 		goto newflag;
570f263522aSJoseph Koshy 	}
571f263522aSJoseph Koshy 
572f263522aSJoseph Koshy 	/* save the new flag set */
573f263522aSJoseph Koshy 	bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
574f263522aSJoseph Koshy done:
5751ede983cSDag-Erling Smørgrav 	free(tmpflags, M_PMC);
57652ebac7fSMitchell Horne 	return (error);
577ebccf1e3SJoseph Koshy }
578ebccf1e3SJoseph Koshy 
579ebccf1e3SJoseph Koshy static int
580ebccf1e3SJoseph Koshy pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
581ebccf1e3SJoseph Koshy {
582ebccf1e3SJoseph Koshy 	char *fence, *newstr;
583ebccf1e3SJoseph Koshy 	int error;
58401c35b67SMitchell Horne 	u_int n;
585ebccf1e3SJoseph Koshy 
586ebccf1e3SJoseph Koshy 	n = sizeof(pmc_debugstr);
587e829eb6dSJoseph Koshy 	newstr = malloc(n, M_PMC, M_WAITOK | M_ZERO);
58801c35b67SMitchell Horne 	strlcpy(newstr, pmc_debugstr, n);
589ebccf1e3SJoseph Koshy 
590ebccf1e3SJoseph Koshy 	error = sysctl_handle_string(oidp, newstr, n, req);
591ebccf1e3SJoseph Koshy 
592ebccf1e3SJoseph Koshy 	/* if there is a new string, parse and copy it */
593ebccf1e3SJoseph Koshy 	if (error == 0 && req->newptr != NULL) {
594f263522aSJoseph Koshy 		fence = newstr + (n < req->newlen ? n : req->newlen + 1);
595d5ee4074SMitchell Horne 		error = pmc_debugflags_parse(newstr, fence);
596d5ee4074SMitchell Horne 		if (error == 0)
597d5ee4074SMitchell Horne 			strlcpy(pmc_debugstr, newstr, sizeof(pmc_debugstr));
598ebccf1e3SJoseph Koshy 	}
5991ede983cSDag-Erling Smørgrav 	free(newstr, M_PMC);
600ebccf1e3SJoseph Koshy 
60152ebac7fSMitchell Horne 	return (error);
602ebccf1e3SJoseph Koshy }
603ebccf1e3SJoseph Koshy #endif
604ebccf1e3SJoseph Koshy 
605ebccf1e3SJoseph Koshy /*
606e829eb6dSJoseph Koshy  * Map a row index to a classdep structure and return the adjusted row
607e829eb6dSJoseph Koshy  * index for the PMC class index.
608e829eb6dSJoseph Koshy  */
609e829eb6dSJoseph Koshy static struct pmc_classdep *
61001c35b67SMitchell Horne pmc_ri_to_classdep(struct pmc_mdep *md __unused, int ri, int *adjri)
611e829eb6dSJoseph Koshy {
612e829eb6dSJoseph Koshy 	struct pmc_classdep *pcd;
613e829eb6dSJoseph Koshy 
614e829eb6dSJoseph Koshy 	KASSERT(ri >= 0 && ri < md->pmd_npmc,
615e829eb6dSJoseph Koshy 	    ("[pmc,%d] illegal row-index %d", __LINE__, ri));
616e829eb6dSJoseph Koshy 
617e829eb6dSJoseph Koshy 	pcd = pmc_rowindex_to_classdep[ri];
618e829eb6dSJoseph Koshy 	KASSERT(pcd != NULL,
619e5087dd8SRui Paulo 	    ("[pmc,%d] ri %d null pcd", __LINE__, ri));
620e829eb6dSJoseph Koshy 
621e829eb6dSJoseph Koshy 	*adjri = ri - pcd->pcd_ri;
622e829eb6dSJoseph Koshy 	KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
623e829eb6dSJoseph Koshy 	    ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));
624e829eb6dSJoseph Koshy 
625e829eb6dSJoseph Koshy 	return (pcd);
626e829eb6dSJoseph Koshy }
627e829eb6dSJoseph Koshy 
628e829eb6dSJoseph Koshy /*
629ebccf1e3SJoseph Koshy  * Concurrency Control
630ebccf1e3SJoseph Koshy  *
631ebccf1e3SJoseph Koshy  * The driver manages the following data structures:
632ebccf1e3SJoseph Koshy  *
633ebccf1e3SJoseph Koshy  *   - target process descriptors, one per target process
634ebccf1e3SJoseph Koshy  *   - owner process descriptors (and attached lists), one per owner process
635ebccf1e3SJoseph Koshy  *   - lookup hash tables for owner and target processes
636ebccf1e3SJoseph Koshy  *   - PMC descriptors (and attached lists)
637ebccf1e3SJoseph Koshy  *   - per-cpu hardware state
638ebccf1e3SJoseph Koshy  *   - the 'hook' variable through which the kernel calls into
639ebccf1e3SJoseph Koshy  *     this module
640ebccf1e3SJoseph Koshy  *   - the machine hardware state (managed by the MD layer)
641ebccf1e3SJoseph Koshy  *
642ebccf1e3SJoseph Koshy  * These data structures are accessed from:
643ebccf1e3SJoseph Koshy  *
644ebccf1e3SJoseph Koshy  * - thread context-switch code
645ebccf1e3SJoseph Koshy  * - interrupt handlers (possibly on multiple cpus)
646ebccf1e3SJoseph Koshy  * - kernel threads on multiple cpus running on behalf of user
647ebccf1e3SJoseph Koshy  *   processes doing system calls
648ebccf1e3SJoseph Koshy  * - this driver's private kernel threads
649ebccf1e3SJoseph Koshy  *
650ebccf1e3SJoseph Koshy  * = Locks and Locking strategy =
651ebccf1e3SJoseph Koshy  *
652ebccf1e3SJoseph Koshy  * The driver uses four locking strategies for its operation:
653ebccf1e3SJoseph Koshy  *
654382d30cdSJoseph Koshy  * - The global SX lock "pmc_sx" is used to protect internal
655382d30cdSJoseph Koshy  *   data structures.
656ebccf1e3SJoseph Koshy  *
657382d30cdSJoseph Koshy  *   Calls into the module by syscall() start with this lock being
658382d30cdSJoseph Koshy  *   held in exclusive mode.  Depending on the requested operation,
659382d30cdSJoseph Koshy  *   the lock may be downgraded to 'shared' mode to allow more
660382d30cdSJoseph Koshy  *   concurrent readers into the module.  Calls into the module from
661382d30cdSJoseph Koshy  *   other parts of the kernel acquire the lock in shared mode.
662ebccf1e3SJoseph Koshy  *
663ebccf1e3SJoseph Koshy  *   This SX lock is held in exclusive mode for any operations that
664ebccf1e3SJoseph Koshy  *   modify the linkages between the driver's internal data structures.
665ebccf1e3SJoseph Koshy  *
666ebccf1e3SJoseph Koshy  *   The 'pmc_hook' function pointer is also protected by this lock.
667ebccf1e3SJoseph Koshy  *   It is only examined with the sx lock held in exclusive mode.  The
668382d30cdSJoseph Koshy  *   kernel module is allowed to be unloaded only with the sx lock held
669382d30cdSJoseph Koshy  *   in exclusive mode.  In normal syscall handling, after acquiring the
670382d30cdSJoseph Koshy  *   pmc_sx lock we first check that 'pmc_hook' is non-null before
671382d30cdSJoseph Koshy  *   proceeding.  This prevents races between the thread unloading the module
672382d30cdSJoseph Koshy  *   and other threads seeking to use the module.
673ebccf1e3SJoseph Koshy  *
674ebccf1e3SJoseph Koshy  * - Lookups of target process structures and owner process structures
675ebccf1e3SJoseph Koshy  *   cannot use the global "pmc_sx" SX lock because these lookups need
676ebccf1e3SJoseph Koshy  *   to happen during context switches and in other critical sections
677ebccf1e3SJoseph Koshy  *   where sleeping is not allowed.  We protect these lookup tables
678ebccf1e3SJoseph Koshy  *   with their own private spin-mutexes, "pmc_processhash_mtx" and
679382d30cdSJoseph Koshy  *   "pmc_ownerhash_mtx".
680ebccf1e3SJoseph Koshy  *
681ebccf1e3SJoseph Koshy  * - Interrupt handlers work in a lock free manner.  At interrupt
682ebccf1e3SJoseph Koshy  *   time, handlers look at the PMC pointer (phw->phw_pmc) configured
683ebccf1e3SJoseph Koshy  *   when the PMC was started.  If this pointer is NULL, the interrupt
684ebccf1e3SJoseph Koshy  *   is ignored after updating driver statistics.  We ensure that this
685ebccf1e3SJoseph Koshy  *   pointer is set (using an atomic operation if necessary) before the
686ebccf1e3SJoseph Koshy  *   PMC hardware is started.  Conversely, this pointer is unset atomically
687ebccf1e3SJoseph Koshy  *   only after the PMC hardware is stopped.
688ebccf1e3SJoseph Koshy  *
689ebccf1e3SJoseph Koshy  *   We ensure that everything needed for the operation of an
690ebccf1e3SJoseph Koshy  *   interrupt handler is available without it needing to acquire any
691ebccf1e3SJoseph Koshy  *   locks.  We also ensure that a PMC's software state is destroyed only
692ebccf1e3SJoseph Koshy  *   after the PMC is taken off hardware (on all CPUs).
693ebccf1e3SJoseph Koshy  *
694ebccf1e3SJoseph Koshy  * - Context-switch handling with process-private PMCs needs more
695ebccf1e3SJoseph Koshy  *   care.
696ebccf1e3SJoseph Koshy  *
697ebccf1e3SJoseph Koshy  *   A given process may be the target of multiple PMCs.  For example,
698ebccf1e3SJoseph Koshy  *   PMCATTACH and PMCDETACH may be requested by a process on one CPU
699ebccf1e3SJoseph Koshy  *   while the target process is running on another.  A PMC could also
700ebccf1e3SJoseph Koshy  *   be getting released because its owner is exiting.  We tackle
701ebccf1e3SJoseph Koshy  *   these situations in the following manner:
702ebccf1e3SJoseph Koshy  *
703ebccf1e3SJoseph Koshy  *   - each target process structure 'pmc_process' has an array
704ebccf1e3SJoseph Koshy  *     of 'struct pmc *' pointers, one for each hardware PMC.
705ebccf1e3SJoseph Koshy  *
706ebccf1e3SJoseph Koshy  *   - At context switch IN time, each "target" PMC in RUNNING state
707ebccf1e3SJoseph Koshy  *     gets started on hardware and a pointer to each PMC is copied into
708ebccf1e3SJoseph Koshy  *     the per-cpu phw array.  The 'runcount' for the PMC is
709ebccf1e3SJoseph Koshy  *     incremented.
710ebccf1e3SJoseph Koshy  *
711ebccf1e3SJoseph Koshy  *   - At context switch OUT time, all process-virtual PMCs are stopped
712ebccf1e3SJoseph Koshy  *     on hardware.  The saved value is added to the PMCs value field
713ebccf1e3SJoseph Koshy  *     only if the PMC is in a non-deleted state (the PMCs state could
714ebccf1e3SJoseph Koshy  *     have changed during the current time slice).
715ebccf1e3SJoseph Koshy  *
716ebccf1e3SJoseph Koshy  *     Note that since in-between a switch IN on a processor and a switch
717ebccf1e3SJoseph Koshy  *     OUT, the PMC could have been released on another CPU.  Therefore
718ebccf1e3SJoseph Koshy  *     context switch OUT always looks at the hardware state to turn
719ebccf1e3SJoseph Koshy  *     OFF PMCs and will update a PMC's saved value only if reachable
720ebccf1e3SJoseph Koshy  *     from the target process record.
721ebccf1e3SJoseph Koshy  *
722ebccf1e3SJoseph Koshy  *   - OP PMCRELEASE could be called on a PMC at any time (the PMC could
723ebccf1e3SJoseph Koshy  *     be attached to many processes at the time of the call and could
724ebccf1e3SJoseph Koshy  *     be active on multiple CPUs).
725ebccf1e3SJoseph Koshy  *
726ebccf1e3SJoseph Koshy  *     We prevent further scheduling of the PMC by marking it as in
727ebccf1e3SJoseph Koshy  *     state 'DELETED'.  If the runcount of the PMC is non-zero then
728ebccf1e3SJoseph Koshy  *     this PMC is currently running on a CPU somewhere.  The thread
7294d70511aSJohn Baldwin  *     doing the PMCRELEASE operation waits by repeatedly doing a
7304d70511aSJohn Baldwin  *     pause() till the runcount comes to zero.
731ebccf1e3SJoseph Koshy  *
732382d30cdSJoseph Koshy  * The contents of a PMC descriptor (struct pmc) are protected using
733382d30cdSJoseph Koshy  * a spin-mutex.  In order to save space, we use a mutex pool.
734382d30cdSJoseph Koshy  *
735382d30cdSJoseph Koshy  * In terms of lock types used by witness(4), we use:
736382d30cdSJoseph Koshy  * - Type "pmc-sx", used by the global SX lock.
737382d30cdSJoseph Koshy  * - Type "pmc-sleep", for sleep mutexes used by logger threads.
738382d30cdSJoseph Koshy  * - Type "pmc-per-proc", for protecting PMC owner descriptors.
739382d30cdSJoseph Koshy  * - Type "pmc-leaf", used for all other spin mutexes.
740ebccf1e3SJoseph Koshy  */
741ebccf1e3SJoseph Koshy 
742ebccf1e3SJoseph Koshy /*
74301c35b67SMitchell Horne  * Save the CPU binding of the current kthread.
744ebccf1e3SJoseph Koshy  */
745eff9ee7cSAlexander Motin void
746ebccf1e3SJoseph Koshy pmc_save_cpu_binding(struct pmc_binding *pb)
747ebccf1e3SJoseph Koshy {
7484a3690dfSJohn Baldwin 	PMCDBG0(CPU,BND,2, "save-cpu");
749982d11f8SJeff Roberson 	thread_lock(curthread);
750ebccf1e3SJoseph Koshy 	pb->pb_bound = sched_is_bound(curthread);
751ebccf1e3SJoseph Koshy 	pb->pb_cpu   = curthread->td_oncpu;
752eff9ee7cSAlexander Motin 	pb->pb_priority = curthread->td_priority;
753982d11f8SJeff Roberson 	thread_unlock(curthread);
7544a3690dfSJohn Baldwin 	PMCDBG1(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
755ebccf1e3SJoseph Koshy }
756ebccf1e3SJoseph Koshy 
757ebccf1e3SJoseph Koshy /*
75801c35b67SMitchell Horne  * Restore the CPU binding of the current thread.
759ebccf1e3SJoseph Koshy  */
760eff9ee7cSAlexander Motin void
761ebccf1e3SJoseph Koshy pmc_restore_cpu_binding(struct pmc_binding *pb)
762ebccf1e3SJoseph Koshy {
7634a3690dfSJohn Baldwin 	PMCDBG2(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
764ebccf1e3SJoseph Koshy 	    curthread->td_oncpu, pb->pb_cpu);
765982d11f8SJeff Roberson 	thread_lock(curthread);
766ebccf1e3SJoseph Koshy 	sched_bind(curthread, pb->pb_cpu);
767eff9ee7cSAlexander Motin 	if (!pb->pb_bound)
768ebccf1e3SJoseph Koshy 		sched_unbind(curthread);
769eff9ee7cSAlexander Motin 	sched_prio(curthread, pb->pb_priority);
770982d11f8SJeff Roberson 	thread_unlock(curthread);
7714a3690dfSJohn Baldwin 	PMCDBG0(CPU,BND,2, "restore-cpu done");
772ebccf1e3SJoseph Koshy }
773ebccf1e3SJoseph Koshy 
774ebccf1e3SJoseph Koshy /*
77501c35b67SMitchell Horne  * Move execution over to the specified CPU and bind it there.
776ebccf1e3SJoseph Koshy  */
777eff9ee7cSAlexander Motin void
778ebccf1e3SJoseph Koshy pmc_select_cpu(int cpu)
779ebccf1e3SJoseph Koshy {
780122ccdc1SJoseph Koshy 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
781ebccf1e3SJoseph Koshy 	    ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
782ebccf1e3SJoseph Koshy 
783122ccdc1SJoseph Koshy 	/* Never move to an inactive CPU. */
784122ccdc1SJoseph Koshy 	KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
785122ccdc1SJoseph Koshy 	    "CPU %d", __LINE__, cpu));
786ebccf1e3SJoseph Koshy 
7874a3690dfSJohn Baldwin 	PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d", cpu);
788982d11f8SJeff Roberson 	thread_lock(curthread);
789eff9ee7cSAlexander Motin 	sched_prio(curthread, PRI_MIN);
790ebccf1e3SJoseph Koshy 	sched_bind(curthread, cpu);
791982d11f8SJeff Roberson 	thread_unlock(curthread);
792ebccf1e3SJoseph Koshy 
793ebccf1e3SJoseph Koshy 	KASSERT(curthread->td_oncpu == cpu,
794ebccf1e3SJoseph Koshy 	    ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
795ebccf1e3SJoseph Koshy 		cpu, curthread->td_oncpu));
796ebccf1e3SJoseph Koshy 
7974a3690dfSJohn Baldwin 	PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
798ebccf1e3SJoseph Koshy }
799ebccf1e3SJoseph Koshy 
800ebccf1e3SJoseph Koshy /*
801c5153e19SJoseph Koshy  * Force a context switch.
802c5153e19SJoseph Koshy  *
8034d70511aSJohn Baldwin  * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
804c5153e19SJoseph Koshy  * guaranteed to force a context switch.
805c5153e19SJoseph Koshy  */
806c5153e19SJoseph Koshy static void
807c5153e19SJoseph Koshy pmc_force_context_switch(void)
808c5153e19SJoseph Koshy {
809c5153e19SJoseph Koshy 
8104d70511aSJohn Baldwin 	pause("pmcctx", 1);
811c5153e19SJoseph Koshy }
812c5153e19SJoseph Koshy 
813f992dd4bSMatt Macy uint64_t
814f992dd4bSMatt Macy pmc_rdtsc(void)
815f992dd4bSMatt Macy {
816f992dd4bSMatt Macy #if defined(__i386__) || defined(__amd64__)
817f992dd4bSMatt Macy 	if (__predict_true(amd_feature & AMDID_RDTSCP))
81852ebac7fSMitchell Horne 		return (rdtscp());
819f992dd4bSMatt Macy 	else
82052ebac7fSMitchell Horne 		return (rdtsc());
821f992dd4bSMatt Macy #else
82252ebac7fSMitchell Horne 	return (get_cyclecount());
823f992dd4bSMatt Macy #endif
824f992dd4bSMatt Macy }
825f992dd4bSMatt Macy 
826c5153e19SJoseph Koshy /*
827f263522aSJoseph Koshy  * Get the file name for an executable.  This is a simple wrapper
828f263522aSJoseph Koshy  * around vn_fullpath(9).
829ebccf1e3SJoseph Koshy  */
830f263522aSJoseph Koshy static void
83115139246SJoseph Koshy pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
832ebccf1e3SJoseph Koshy {
833ebccf1e3SJoseph Koshy 
834f263522aSJoseph Koshy 	*fullpath = "unknown";
835f263522aSJoseph Koshy 	*freepath = NULL;
836feabaaf9SMateusz Guzik 	vn_fullpath(v, fullpath, freepath);
837ebccf1e3SJoseph Koshy }
838ebccf1e3SJoseph Koshy 
839ebccf1e3SJoseph Koshy /*
84001c35b67SMitchell Horne  * Remove a process owning PMCs.
841ebccf1e3SJoseph Koshy  */
842ebccf1e3SJoseph Koshy void
843ebccf1e3SJoseph Koshy pmc_remove_owner(struct pmc_owner *po)
844ebccf1e3SJoseph Koshy {
845f263522aSJoseph Koshy 	struct pmc *pm, *tmp;
846ebccf1e3SJoseph Koshy 
847ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
848ebccf1e3SJoseph Koshy 
8494a3690dfSJohn Baldwin 	PMCDBG1(OWN,ORM,1, "remove-owner po=%p", po);
850ebccf1e3SJoseph Koshy 
851ebccf1e3SJoseph Koshy 	/* Remove descriptor from the owner hash table */
852ebccf1e3SJoseph Koshy 	LIST_REMOVE(po, po_next);
853ebccf1e3SJoseph Koshy 
854f263522aSJoseph Koshy 	/* release all owned PMC descriptors */
855f263522aSJoseph Koshy 	LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
8564a3690dfSJohn Baldwin 		PMCDBG1(OWN,ORM,2, "pmc=%p", pm);
857f263522aSJoseph Koshy 		KASSERT(pm->pm_owner == po,
858f263522aSJoseph Koshy 		    ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
859ebccf1e3SJoseph Koshy 
860f263522aSJoseph Koshy 		pmc_release_pmc_descriptor(pm);	/* will unlink from the list */
86106796b67SMark Johnston 		pmc_destroy_pmc_descriptor(pm);
862ebccf1e3SJoseph Koshy 	}
863ebccf1e3SJoseph Koshy 
864f263522aSJoseph Koshy 	KASSERT(po->po_sscount == 0,
865f263522aSJoseph Koshy 	    ("[pmc,%d] SS count not zero", __LINE__));
866ebccf1e3SJoseph Koshy 	KASSERT(LIST_EMPTY(&po->po_pmcs),
867ebccf1e3SJoseph Koshy 	    ("[pmc,%d] PMC list not empty", __LINE__));
868ebccf1e3SJoseph Koshy 
869f263522aSJoseph Koshy 	/* de-configure the log file if present */
870c5153e19SJoseph Koshy 	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
871f263522aSJoseph Koshy 		pmclog_deconfigure_log(po);
872ebccf1e3SJoseph Koshy }
873ebccf1e3SJoseph Koshy 
874ebccf1e3SJoseph Koshy /*
87501c35b67SMitchell Horne  * Remove an owner process record if all conditions are met.
876ebccf1e3SJoseph Koshy  */
877ebccf1e3SJoseph Koshy static void
878ebccf1e3SJoseph Koshy pmc_maybe_remove_owner(struct pmc_owner *po)
879ebccf1e3SJoseph Koshy {
880ebccf1e3SJoseph Koshy 
8814a3690dfSJohn Baldwin 	PMCDBG1(OWN,OMR,1, "maybe-remove-owner po=%p", po);
882ebccf1e3SJoseph Koshy 
883ebccf1e3SJoseph Koshy 	/*
884ebccf1e3SJoseph Koshy 	 * Remove owner record if
885ebccf1e3SJoseph Koshy 	 * - this process does not own any PMCs
886ebccf1e3SJoseph Koshy 	 * - this process has not allocated a system-wide sampling buffer
887ebccf1e3SJoseph Koshy 	 */
888ebccf1e3SJoseph Koshy 	if (LIST_EMPTY(&po->po_pmcs) &&
889c5153e19SJoseph Koshy 	    ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
890ebccf1e3SJoseph Koshy 		pmc_remove_owner(po);
891f263522aSJoseph Koshy 		pmc_destroy_owner_descriptor(po);
892ebccf1e3SJoseph Koshy 	}
893ebccf1e3SJoseph Koshy }
894ebccf1e3SJoseph Koshy 
895ebccf1e3SJoseph Koshy /*
896ebccf1e3SJoseph Koshy  * Add an association between a target process and a PMC.
897ebccf1e3SJoseph Koshy  */
898ebccf1e3SJoseph Koshy static void
899ebccf1e3SJoseph Koshy pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
900ebccf1e3SJoseph Koshy {
901ebccf1e3SJoseph Koshy 	struct pmc_target *pt;
90201c35b67SMitchell Horne 	struct pmc_thread *pt_td __diagused;
90301c35b67SMitchell Horne 	int ri;
904ebccf1e3SJoseph Koshy 
905ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
906ebccf1e3SJoseph Koshy 	KASSERT(pm != NULL && pp != NULL,
907ebccf1e3SJoseph Koshy 	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
908f263522aSJoseph Koshy 	KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
909f263522aSJoseph Koshy 	    ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
910f263522aSJoseph Koshy 		__LINE__, pm, pp->pp_proc->p_pid));
911fa630f35SFabien Thomas 	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1),
912ebccf1e3SJoseph Koshy 	    ("[pmc,%d] Illegal reference count %d for process record %p",
913ebccf1e3SJoseph Koshy 		__LINE__, pp->pp_refcnt, (void *) pp));
914ebccf1e3SJoseph Koshy 
915c5153e19SJoseph Koshy 	ri = PMC_TO_ROWINDEX(pm);
916ebccf1e3SJoseph Koshy 
9174a3690dfSJohn Baldwin 	PMCDBG3(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
918ebccf1e3SJoseph Koshy 	    pm, ri, pp);
919ebccf1e3SJoseph Koshy 
920680f1afdSJohn Baldwin #ifdef HWPMC_DEBUG
921d5ee4074SMitchell Horne 	LIST_FOREACH(pt, &pm->pm_targets, pt_next) {
922ebccf1e3SJoseph Koshy 		if (pt->pt_process == pp)
923ebccf1e3SJoseph Koshy 			KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
924ebccf1e3SJoseph Koshy 			    __LINE__, pp, pm));
925d5ee4074SMitchell Horne 	}
926ebccf1e3SJoseph Koshy #endif
927e829eb6dSJoseph Koshy 	pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK | M_ZERO);
928ebccf1e3SJoseph Koshy 	pt->pt_process = pp;
929ebccf1e3SJoseph Koshy 
930ebccf1e3SJoseph Koshy 	LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
931ebccf1e3SJoseph Koshy 
932122eceefSJohn Baldwin 	atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
933122eceefSJohn Baldwin 	    (uintptr_t)pm);
934ebccf1e3SJoseph Koshy 
9356b8c8cd8SJoseph Koshy 	if (pm->pm_owner->po_owner == pp->pp_proc)
936c5153e19SJoseph Koshy 		pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
9376b8c8cd8SJoseph Koshy 
938f263522aSJoseph Koshy 	/*
939f263522aSJoseph Koshy 	 * Initialize the per-process values at this row index.
940f263522aSJoseph Koshy 	 */
941f263522aSJoseph Koshy 	pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
942f263522aSJoseph Koshy 	    pm->pm_sc.pm_reloadcount : 0;
943ebccf1e3SJoseph Koshy 	pp->pp_refcnt++;
944ebccf1e3SJoseph Koshy 
9456161b98cSMatt Macy #ifdef INVARIANTS
9466161b98cSMatt Macy 	/* Confirm that the per-thread values at this row index are cleared. */
9476161b98cSMatt Macy 	if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
9486161b98cSMatt Macy 		mtx_lock_spin(pp->pp_tdslock);
9496161b98cSMatt Macy 		LIST_FOREACH(pt_td, &pp->pp_tds, pt_next) {
9506161b98cSMatt Macy 			KASSERT(pt_td->pt_pmcs[ri].pt_pmcval == (pmc_value_t) 0,
9516161b98cSMatt Macy 			    ("[pmc,%d] pt_pmcval not cleared for pid=%d at "
9526161b98cSMatt Macy 			    "ri=%d", __LINE__, pp->pp_proc->p_pid, ri));
9536161b98cSMatt Macy 		}
9546161b98cSMatt Macy 		mtx_unlock_spin(pp->pp_tdslock);
9556161b98cSMatt Macy 	}
9566161b98cSMatt Macy #endif
957ebccf1e3SJoseph Koshy }
958ebccf1e3SJoseph Koshy 
959ebccf1e3SJoseph Koshy /*
960ebccf1e3SJoseph Koshy  * Removes the association between a target process and a PMC.
961ebccf1e3SJoseph Koshy  */
962ebccf1e3SJoseph Koshy static void
963ebccf1e3SJoseph Koshy pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
964ebccf1e3SJoseph Koshy {
965ebccf1e3SJoseph Koshy 	int ri;
966f263522aSJoseph Koshy 	struct proc *p;
967ebccf1e3SJoseph Koshy 	struct pmc_target *ptgt;
9686161b98cSMatt Macy 	struct pmc_thread *pt;
969ebccf1e3SJoseph Koshy 
970ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
971ebccf1e3SJoseph Koshy 
972ebccf1e3SJoseph Koshy 	KASSERT(pm != NULL && pp != NULL,
973ebccf1e3SJoseph Koshy 	    ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
974ebccf1e3SJoseph Koshy 
975fa630f35SFabien Thomas 	KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc,
976ebccf1e3SJoseph Koshy 	    ("[pmc,%d] Illegal ref count %d on process record %p",
977ebccf1e3SJoseph Koshy 		__LINE__, pp->pp_refcnt, (void *) pp));
978ebccf1e3SJoseph Koshy 
979c5153e19SJoseph Koshy 	ri = PMC_TO_ROWINDEX(pm);
980ebccf1e3SJoseph Koshy 
9814a3690dfSJohn Baldwin 	PMCDBG3(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
982ebccf1e3SJoseph Koshy 	    pm, ri, pp);
983ebccf1e3SJoseph Koshy 
984ebccf1e3SJoseph Koshy 	KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
985ebccf1e3SJoseph Koshy 	    ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
986ebccf1e3SJoseph Koshy 		ri, pm, pp->pp_pmcs[ri].pp_pmc));
987ebccf1e3SJoseph Koshy 
988ebccf1e3SJoseph Koshy 	pp->pp_pmcs[ri].pp_pmc = NULL;
989ebccf1e3SJoseph Koshy 	pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t)0;
990ebccf1e3SJoseph Koshy 
9916161b98cSMatt Macy 	/* Clear the per-thread values at this row index. */
9926161b98cSMatt Macy 	if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
9936161b98cSMatt Macy 		mtx_lock_spin(pp->pp_tdslock);
9946161b98cSMatt Macy 		LIST_FOREACH(pt, &pp->pp_tds, pt_next)
9956161b98cSMatt Macy 			pt->pt_pmcs[ri].pt_pmcval = (pmc_value_t)0;
9966161b98cSMatt Macy 		mtx_unlock_spin(pp->pp_tdslock);
9976161b98cSMatt Macy 	}
9986161b98cSMatt Macy 
999c5153e19SJoseph Koshy 	/* Remove owner-specific flags */
1000c5153e19SJoseph Koshy 	if (pm->pm_owner->po_owner == pp->pp_proc) {
1001c5153e19SJoseph Koshy 		pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
1002c5153e19SJoseph Koshy 		pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
1003c5153e19SJoseph Koshy 	}
10046b8c8cd8SJoseph Koshy 
1005ebccf1e3SJoseph Koshy 	pp->pp_refcnt--;
1006ebccf1e3SJoseph Koshy 
1007ebccf1e3SJoseph Koshy 	/* Remove the target process from the PMC structure */
1008ebccf1e3SJoseph Koshy 	LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
1009ebccf1e3SJoseph Koshy 		if (ptgt->pt_process == pp)
1010ebccf1e3SJoseph Koshy 			break;
1011ebccf1e3SJoseph Koshy 
1012ebccf1e3SJoseph Koshy 	KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
1013ebccf1e3SJoseph Koshy 		    "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
1014ebccf1e3SJoseph Koshy 
1015ebccf1e3SJoseph Koshy 	LIST_REMOVE(ptgt, pt_next);
10161ede983cSDag-Erling Smørgrav 	free(ptgt, M_PMC);
1017f263522aSJoseph Koshy 
1018f263522aSJoseph Koshy 	/* if the PMC now lacks targets, send the owner a SIGIO */
1019f263522aSJoseph Koshy 	if (LIST_EMPTY(&pm->pm_targets)) {
1020f263522aSJoseph Koshy 		p = pm->pm_owner->po_owner;
1021f263522aSJoseph Koshy 		PROC_LOCK(p);
10228451d0ddSKip Macy 		kern_psignal(p, SIGIO);
1023f263522aSJoseph Koshy 		PROC_UNLOCK(p);
1024f263522aSJoseph Koshy 
1025693cd307SMitchell Horne 		PMCDBG2(PRC,SIG,2, "signalling proc=%p signal=%d", p, SIGIO);
1026ebccf1e3SJoseph Koshy 	}
1027ebccf1e3SJoseph Koshy }
1028ebccf1e3SJoseph Koshy 
1029ebccf1e3SJoseph Koshy /*
1030ebccf1e3SJoseph Koshy  * Check if PMC 'pm' may be attached to target process 't'.
1031ebccf1e3SJoseph Koshy  */
1032ebccf1e3SJoseph Koshy 
1033ebccf1e3SJoseph Koshy static int
1034ebccf1e3SJoseph Koshy pmc_can_attach(struct pmc *pm, struct proc *t)
1035ebccf1e3SJoseph Koshy {
1036ebccf1e3SJoseph Koshy 	struct proc *o;		/* pmc owner */
1037ebccf1e3SJoseph Koshy 	struct ucred *oc, *tc;	/* owner, target credentials */
1038ebccf1e3SJoseph Koshy 	int decline_attach, i;
1039ebccf1e3SJoseph Koshy 
1040ebccf1e3SJoseph Koshy 	/*
1041ebccf1e3SJoseph Koshy 	 * A PMC's owner can always attach that PMC to itself.
1042ebccf1e3SJoseph Koshy 	 */
1043ebccf1e3SJoseph Koshy 
1044ebccf1e3SJoseph Koshy 	if ((o = pm->pm_owner->po_owner) == t)
1045ebccf1e3SJoseph Koshy 		return 0;
1046ebccf1e3SJoseph Koshy 
1047ebccf1e3SJoseph Koshy 	PROC_LOCK(o);
1048ebccf1e3SJoseph Koshy 	oc = o->p_ucred;
1049ebccf1e3SJoseph Koshy 	crhold(oc);
1050ebccf1e3SJoseph Koshy 	PROC_UNLOCK(o);
1051ebccf1e3SJoseph Koshy 
1052ebccf1e3SJoseph Koshy 	PROC_LOCK(t);
1053ebccf1e3SJoseph Koshy 	tc = t->p_ucred;
1054ebccf1e3SJoseph Koshy 	crhold(tc);
1055ebccf1e3SJoseph Koshy 	PROC_UNLOCK(t);
1056ebccf1e3SJoseph Koshy 
1057ebccf1e3SJoseph Koshy 	/*
1058ebccf1e3SJoseph Koshy 	 * The effective uid of the PMC owner should match at least one
1059ebccf1e3SJoseph Koshy 	 * of the {effective,real,saved} uids of the target process.
1060ebccf1e3SJoseph Koshy 	 */
1061ebccf1e3SJoseph Koshy 
1062ebccf1e3SJoseph Koshy 	decline_attach = oc->cr_uid != tc->cr_uid &&
1063ebccf1e3SJoseph Koshy 	    oc->cr_uid != tc->cr_svuid &&
1064ebccf1e3SJoseph Koshy 	    oc->cr_uid != tc->cr_ruid;
1065ebccf1e3SJoseph Koshy 
1066ebccf1e3SJoseph Koshy 	/*
1067ebccf1e3SJoseph Koshy 	 * Every one of the target's group ids, must be in the owner's
1068ebccf1e3SJoseph Koshy 	 * group list.
1069ebccf1e3SJoseph Koshy 	 */
1070ebccf1e3SJoseph Koshy 	for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
1071ebccf1e3SJoseph Koshy 		decline_attach = !groupmember(tc->cr_groups[i], oc);
1072ebccf1e3SJoseph Koshy 
1073ebccf1e3SJoseph Koshy 	/* check the read and saved gids too */
1074ebccf1e3SJoseph Koshy 	if (decline_attach == 0)
1075ebccf1e3SJoseph Koshy 		decline_attach = !groupmember(tc->cr_rgid, oc) ||
1076ebccf1e3SJoseph Koshy 		    !groupmember(tc->cr_svgid, oc);
1077ebccf1e3SJoseph Koshy 
1078ebccf1e3SJoseph Koshy 	crfree(tc);
1079ebccf1e3SJoseph Koshy 	crfree(oc);
1080ebccf1e3SJoseph Koshy 
1081ebccf1e3SJoseph Koshy 	return !decline_attach;
1082ebccf1e3SJoseph Koshy }
1083ebccf1e3SJoseph Koshy 
1084ebccf1e3SJoseph Koshy /*
1085ebccf1e3SJoseph Koshy  * Attach a process to a PMC.
1086ebccf1e3SJoseph Koshy  */
1087ebccf1e3SJoseph Koshy static int
1088ebccf1e3SJoseph Koshy pmc_attach_one_process(struct proc *p, struct pmc *pm)
1089ebccf1e3SJoseph Koshy {
10906161b98cSMatt Macy 	int ri, error;
1091f263522aSJoseph Koshy 	char *fullpath, *freepath;
1092ebccf1e3SJoseph Koshy 	struct pmc_process	*pp;
1093ebccf1e3SJoseph Koshy 
1094ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
1095ebccf1e3SJoseph Koshy 
10964a3690dfSJohn Baldwin 	PMCDBG5(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
1097c5153e19SJoseph Koshy 	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1098ebccf1e3SJoseph Koshy 
1099ebccf1e3SJoseph Koshy 	/*
1100ebccf1e3SJoseph Koshy 	 * Locate the process descriptor corresponding to process 'p',
1101ebccf1e3SJoseph Koshy 	 * allocating space as needed.
1102ebccf1e3SJoseph Koshy 	 *
1103ebccf1e3SJoseph Koshy 	 * Verify that rowindex 'pm_rowindex' is free in the process
1104ebccf1e3SJoseph Koshy 	 * descriptor.
1105ebccf1e3SJoseph Koshy 	 *
1106ebccf1e3SJoseph Koshy 	 * If not, allocate space for a descriptor and link the
1107ebccf1e3SJoseph Koshy 	 * process descriptor and PMC.
1108ebccf1e3SJoseph Koshy 	 */
1109c5153e19SJoseph Koshy 	ri = PMC_TO_ROWINDEX(pm);
1110ebccf1e3SJoseph Koshy 
11116161b98cSMatt Macy 	/* mark process as using HWPMCs */
11126161b98cSMatt Macy 	PROC_LOCK(p);
11136161b98cSMatt Macy 	p->p_flag |= P_HWPMC;
11146161b98cSMatt Macy 	PROC_UNLOCK(p);
1115ebccf1e3SJoseph Koshy 
11166161b98cSMatt Macy 	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL) {
11176161b98cSMatt Macy 		error = ENOMEM;
11186161b98cSMatt Macy 		goto fail;
11196161b98cSMatt Macy 	}
1120ebccf1e3SJoseph Koshy 
11216161b98cSMatt Macy 	if (pp->pp_pmcs[ri].pp_pmc == pm) {/* already present at slot [ri] */
11226161b98cSMatt Macy 		error = EEXIST;
11236161b98cSMatt Macy 		goto fail;
11246161b98cSMatt Macy 	}
11256161b98cSMatt Macy 
11266161b98cSMatt Macy 	if (pp->pp_pmcs[ri].pp_pmc != NULL) {
11276161b98cSMatt Macy 		error = EBUSY;
11286161b98cSMatt Macy 		goto fail;
11296161b98cSMatt Macy 	}
1130ebccf1e3SJoseph Koshy 
1131ebccf1e3SJoseph Koshy 	pmc_link_target_process(pm, pp);
1132ebccf1e3SJoseph Koshy 
1133f263522aSJoseph Koshy 	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
1134f263522aSJoseph Koshy 	    (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
1135f263522aSJoseph Koshy 		pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
1136f263522aSJoseph Koshy 
1137f263522aSJoseph Koshy 	pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
1138f263522aSJoseph Koshy 
1139f263522aSJoseph Koshy 	/* issue an attach event to a configured log file */
1140f263522aSJoseph Koshy 	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
1141db57c70aSKonstantin Belousov 		if (p->p_flag & P_KPROC) {
1142d67023a1SJeff Roberson 			fullpath = kernelname;
1143d67023a1SJeff Roberson 			freepath = NULL;
11440fb2c5d6SKonstantin Belousov 		} else {
11450fb2c5d6SKonstantin Belousov 			pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1146f263522aSJoseph Koshy 			pmclog_process_pmcattach(pm, p->p_pid, fullpath);
11470fb2c5d6SKonstantin Belousov 		}
11481ede983cSDag-Erling Smørgrav 		free(freepath, M_TEMP);
1149d07f36b0SJoseph Koshy 		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1150d07f36b0SJoseph Koshy 			pmc_log_process_mappings(pm->pm_owner, p);
1151f263522aSJoseph Koshy 	}
1152ebccf1e3SJoseph Koshy 
11536161b98cSMatt Macy 	return (0);
11546161b98cSMatt Macy fail:
11556161b98cSMatt Macy 	PROC_LOCK(p);
11566161b98cSMatt Macy 	p->p_flag &= ~P_HWPMC;
11576161b98cSMatt Macy 	PROC_UNLOCK(p);
11586161b98cSMatt Macy 	return (error);
1159ebccf1e3SJoseph Koshy }
1160ebccf1e3SJoseph Koshy 
1161ebccf1e3SJoseph Koshy /*
1162ebccf1e3SJoseph Koshy  * Attach a process and optionally its children
1163ebccf1e3SJoseph Koshy  */
1164ebccf1e3SJoseph Koshy static int
1165ebccf1e3SJoseph Koshy pmc_attach_process(struct proc *p, struct pmc *pm)
1166ebccf1e3SJoseph Koshy {
1167ebccf1e3SJoseph Koshy 	int error;
1168ebccf1e3SJoseph Koshy 	struct proc *top;
1169ebccf1e3SJoseph Koshy 
1170ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
1171ebccf1e3SJoseph Koshy 
11724a3690dfSJohn Baldwin 	PMCDBG5(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1173c5153e19SJoseph Koshy 	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1174c5153e19SJoseph Koshy 
1175c5153e19SJoseph Koshy 	/*
1176c5153e19SJoseph Koshy 	 * If this PMC successfully allowed a GETMSR operation
1177c5153e19SJoseph Koshy 	 * in the past, disallow further ATTACHes.
1178c5153e19SJoseph Koshy 	 */
1179c5153e19SJoseph Koshy 	if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
118052ebac7fSMitchell Horne 		return (EPERM);
1181ebccf1e3SJoseph Koshy 
1182ebccf1e3SJoseph Koshy 	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
118352ebac7fSMitchell Horne 		return (pmc_attach_one_process(p, pm));
1184ebccf1e3SJoseph Koshy 
1185ebccf1e3SJoseph Koshy 	/*
1186ebccf1e3SJoseph Koshy 	 * Traverse all child processes, attaching them to
1187ebccf1e3SJoseph Koshy 	 * this PMC.
1188ebccf1e3SJoseph Koshy 	 */
1189ebccf1e3SJoseph Koshy 	sx_slock(&proctree_lock);
1190ebccf1e3SJoseph Koshy 
1191ebccf1e3SJoseph Koshy 	top = p;
1192ebccf1e3SJoseph Koshy 	for (;;) {
1193ebccf1e3SJoseph Koshy 		if ((error = pmc_attach_one_process(p, pm)) != 0)
1194ebccf1e3SJoseph Koshy 			break;
1195ebccf1e3SJoseph Koshy 		if (!LIST_EMPTY(&p->p_children))
1196ebccf1e3SJoseph Koshy 			p = LIST_FIRST(&p->p_children);
1197ebccf1e3SJoseph Koshy 		else for (;;) {
1198ebccf1e3SJoseph Koshy 			if (p == top)
1199ebccf1e3SJoseph Koshy 				goto done;
1200ebccf1e3SJoseph Koshy 			if (LIST_NEXT(p, p_sibling)) {
1201ebccf1e3SJoseph Koshy 				p = LIST_NEXT(p, p_sibling);
1202ebccf1e3SJoseph Koshy 				break;
1203ebccf1e3SJoseph Koshy 			}
1204ebccf1e3SJoseph Koshy 			p = p->p_pptr;
1205ebccf1e3SJoseph Koshy 		}
1206ebccf1e3SJoseph Koshy 	}
1207ebccf1e3SJoseph Koshy 
1208d5ee4074SMitchell Horne 	if (error != 0)
1209ebccf1e3SJoseph Koshy 		(void)pmc_detach_process(top, pm);
1210ebccf1e3SJoseph Koshy 
1211ebccf1e3SJoseph Koshy done:
1212ebccf1e3SJoseph Koshy 	sx_sunlock(&proctree_lock);
121352ebac7fSMitchell Horne 	return (error);
1214ebccf1e3SJoseph Koshy }
1215ebccf1e3SJoseph Koshy 
1216ebccf1e3SJoseph Koshy /*
1217ebccf1e3SJoseph Koshy  * Detach a process from a PMC.  If there are no other PMCs tracking
1218ebccf1e3SJoseph Koshy  * this process, remove the process structure from its hash table.  If
1219ebccf1e3SJoseph Koshy  * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1220ebccf1e3SJoseph Koshy  */
1221ebccf1e3SJoseph Koshy static int
1222ebccf1e3SJoseph Koshy pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1223ebccf1e3SJoseph Koshy {
1224ebccf1e3SJoseph Koshy 	int ri;
1225ebccf1e3SJoseph Koshy 	struct pmc_process *pp;
1226ebccf1e3SJoseph Koshy 
1227ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
1228ebccf1e3SJoseph Koshy 
1229ebccf1e3SJoseph Koshy 	KASSERT(pm != NULL,
1230ebccf1e3SJoseph Koshy 	    ("[pmc,%d] null pm pointer", __LINE__));
1231ebccf1e3SJoseph Koshy 
1232c5153e19SJoseph Koshy 	ri = PMC_TO_ROWINDEX(pm);
1233ebccf1e3SJoseph Koshy 
12344a3690dfSJohn Baldwin 	PMCDBG6(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1235c5153e19SJoseph Koshy 	    pm, ri, p, p->p_pid, p->p_comm, flags);
1236ebccf1e3SJoseph Koshy 
1237ebccf1e3SJoseph Koshy 	if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
123852ebac7fSMitchell Horne 		return (ESRCH);
1239ebccf1e3SJoseph Koshy 
1240ebccf1e3SJoseph Koshy 	if (pp->pp_pmcs[ri].pp_pmc != pm)
124152ebac7fSMitchell Horne 		return (EINVAL);
1242ebccf1e3SJoseph Koshy 
1243ebccf1e3SJoseph Koshy 	pmc_unlink_target_process(pm, pp);
1244ebccf1e3SJoseph Koshy 
1245f263522aSJoseph Koshy 	/* Issue a detach entry if a log file is configured */
1246f263522aSJoseph Koshy 	if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1247f263522aSJoseph Koshy 		pmclog_process_pmcdetach(pm, p->p_pid);
1248f263522aSJoseph Koshy 
1249ebccf1e3SJoseph Koshy 	/*
1250b790c193SPedro F. Giffuni 	 * If there are no PMCs targeting this process, we remove its
1251ebccf1e3SJoseph Koshy 	 * descriptor from the target hash table and unset the P_HWPMC
1252ebccf1e3SJoseph Koshy 	 * flag in the struct proc.
1253ebccf1e3SJoseph Koshy 	 */
1254fa630f35SFabien Thomas 	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1255ebccf1e3SJoseph Koshy 	    ("[pmc,%d] Illegal refcnt %d for process struct %p",
1256ebccf1e3SJoseph Koshy 		__LINE__, pp->pp_refcnt, pp));
1257ebccf1e3SJoseph Koshy 
1258ebccf1e3SJoseph Koshy 	if (pp->pp_refcnt != 0)	/* still a target of some PMC */
125952ebac7fSMitchell Horne 		return (0);
1260ebccf1e3SJoseph Koshy 
1261ebccf1e3SJoseph Koshy 	pmc_remove_process_descriptor(pp);
1262ebccf1e3SJoseph Koshy 
1263ebccf1e3SJoseph Koshy 	if (flags & PMC_FLAG_REMOVE)
12646161b98cSMatt Macy 		pmc_destroy_process_descriptor(pp);
1265ebccf1e3SJoseph Koshy 
1266ebccf1e3SJoseph Koshy 	PROC_LOCK(p);
1267ebccf1e3SJoseph Koshy 	p->p_flag &= ~P_HWPMC;
1268ebccf1e3SJoseph Koshy 	PROC_UNLOCK(p);
1269ebccf1e3SJoseph Koshy 
127052ebac7fSMitchell Horne 	return (0);
1271ebccf1e3SJoseph Koshy }
1272ebccf1e3SJoseph Koshy 
1273ebccf1e3SJoseph Koshy /*
1274ebccf1e3SJoseph Koshy  * Detach a process and optionally its descendants from a PMC.
1275ebccf1e3SJoseph Koshy  */
1276ebccf1e3SJoseph Koshy static int
1277ebccf1e3SJoseph Koshy pmc_detach_process(struct proc *p, struct pmc *pm)
1278ebccf1e3SJoseph Koshy {
1279ebccf1e3SJoseph Koshy 	struct proc *top;
1280ebccf1e3SJoseph Koshy 
1281ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
1282ebccf1e3SJoseph Koshy 
12834a3690dfSJohn Baldwin 	PMCDBG5(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1284c5153e19SJoseph Koshy 	    PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1285ebccf1e3SJoseph Koshy 
1286ebccf1e3SJoseph Koshy 	if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
128752ebac7fSMitchell Horne 		return (pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE));
1288ebccf1e3SJoseph Koshy 
1289ebccf1e3SJoseph Koshy 	/*
1290ebccf1e3SJoseph Koshy 	 * Traverse all children, detaching them from this PMC.  We
1291ebccf1e3SJoseph Koshy 	 * ignore errors since we could be detaching a PMC from a
1292ebccf1e3SJoseph Koshy 	 * partially attached proc tree.
1293ebccf1e3SJoseph Koshy 	 */
1294ebccf1e3SJoseph Koshy 	sx_slock(&proctree_lock);
1295ebccf1e3SJoseph Koshy 
1296ebccf1e3SJoseph Koshy 	top = p;
1297ebccf1e3SJoseph Koshy 	for (;;) {
1298ebccf1e3SJoseph Koshy 		(void)pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1299ebccf1e3SJoseph Koshy 
1300d5ee4074SMitchell Horne 		if (!LIST_EMPTY(&p->p_children)) {
1301ebccf1e3SJoseph Koshy 			p = LIST_FIRST(&p->p_children);
1302d5ee4074SMitchell Horne 		} else {
1303d5ee4074SMitchell Horne 			for (;;) {
1304ebccf1e3SJoseph Koshy 				if (p == top)
1305ebccf1e3SJoseph Koshy 					goto done;
1306ebccf1e3SJoseph Koshy 				if (LIST_NEXT(p, p_sibling)) {
1307ebccf1e3SJoseph Koshy 					p = LIST_NEXT(p, p_sibling);
1308ebccf1e3SJoseph Koshy 					break;
1309ebccf1e3SJoseph Koshy 				}
1310ebccf1e3SJoseph Koshy 				p = p->p_pptr;
1311ebccf1e3SJoseph Koshy 			}
1312ebccf1e3SJoseph Koshy 		}
1313d5ee4074SMitchell Horne 	}
1314ebccf1e3SJoseph Koshy done:
1315ebccf1e3SJoseph Koshy 	sx_sunlock(&proctree_lock);
1316f263522aSJoseph Koshy 	if (LIST_EMPTY(&pm->pm_targets))
1317f263522aSJoseph Koshy 		pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1318f263522aSJoseph Koshy 
131952ebac7fSMitchell Horne 	return (0);
1320ebccf1e3SJoseph Koshy }
1321ebccf1e3SJoseph Koshy 
1322ebccf1e3SJoseph Koshy /*
1323c4981694SMitchell Horne  * Handle events after an exec() for a process:
1324c4981694SMitchell Horne  *  - Inform log owners of the new exec() event
1325c4981694SMitchell Horne  *  - Release any PMCs owned by the process before the exec()
1326c4981694SMitchell Horne  *  - Detach PMCs from the target if required
1327c4981694SMitchell Horne  */
1328c4981694SMitchell Horne static void
1329c4981694SMitchell Horne pmc_process_exec(struct thread *td, struct pmckern_procexec *pk)
1330c4981694SMitchell Horne {
1331c4981694SMitchell Horne 	struct pmc *pm;
1332c4981694SMitchell Horne 	struct pmc_owner *po;
1333c4981694SMitchell Horne 	struct pmc_process *pp;
1334c4981694SMitchell Horne 	struct proc *p;
1335c4981694SMitchell Horne 	char *fullpath, *freepath;
1336c4981694SMitchell Horne 	u_int ri;
1337c4981694SMitchell Horne 	bool is_using_hwpmcs;
1338c4981694SMitchell Horne 
1339c4981694SMitchell Horne 	sx_assert(&pmc_sx, SX_XLOCKED);
1340c4981694SMitchell Horne 
1341c4981694SMitchell Horne 	p = td->td_proc;
1342c4981694SMitchell Horne 	pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1343c4981694SMitchell Horne 
1344c4981694SMitchell Horne 	PMC_EPOCH_ENTER();
1345c4981694SMitchell Horne 	/* Inform owners of SS mode PMCs of the exec event. */
1346c4981694SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
1347c4981694SMitchell Horne 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) {
1348c4981694SMitchell Horne 			pmclog_process_procexec(po, PMC_ID_INVALID, p->p_pid,
1349c4981694SMitchell Horne 			    pk->pm_baseaddr, pk->pm_dynaddr, fullpath);
1350c4981694SMitchell Horne 		}
1351c4981694SMitchell Horne 	}
1352c4981694SMitchell Horne 	PMC_EPOCH_EXIT();
1353c4981694SMitchell Horne 
1354c4981694SMitchell Horne 	PROC_LOCK(p);
1355c4981694SMitchell Horne 	is_using_hwpmcs = (p->p_flag & P_HWPMC) != 0;
1356c4981694SMitchell Horne 	PROC_UNLOCK(p);
1357c4981694SMitchell Horne 
1358c4981694SMitchell Horne 	if (!is_using_hwpmcs) {
1359c4981694SMitchell Horne 		if (freepath != NULL)
1360c4981694SMitchell Horne 			free(freepath, M_TEMP);
1361c4981694SMitchell Horne 		return;
1362c4981694SMitchell Horne 	}
1363c4981694SMitchell Horne 
1364c4981694SMitchell Horne 	/*
1365c4981694SMitchell Horne 	 * PMCs are not inherited across an exec(): remove any PMCs that this
1366c4981694SMitchell Horne 	 * process is the owner of.
1367c4981694SMitchell Horne 	 */
1368c4981694SMitchell Horne 	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1369c4981694SMitchell Horne 		pmc_remove_owner(po);
1370c4981694SMitchell Horne 		pmc_destroy_owner_descriptor(po);
1371c4981694SMitchell Horne 	}
1372c4981694SMitchell Horne 
1373c4981694SMitchell Horne 	/*
1374c4981694SMitchell Horne 	 * If the process being exec'ed is not the target of any PMC, we are
1375c4981694SMitchell Horne 	 * done.
1376c4981694SMitchell Horne 	 */
1377c4981694SMitchell Horne 	if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1378c4981694SMitchell Horne 		if (freepath != NULL)
1379c4981694SMitchell Horne 			free(freepath, M_TEMP);
1380c4981694SMitchell Horne 		return;
1381c4981694SMitchell Horne 	}
1382c4981694SMitchell Horne 
1383c4981694SMitchell Horne 	/*
1384c4981694SMitchell Horne 	 * Log the exec event to all monitoring owners. Skip owners who have
1385c4981694SMitchell Horne 	 * already received the event because they had system sampling PMCs
1386c4981694SMitchell Horne 	 * active.
1387c4981694SMitchell Horne 	 */
1388c4981694SMitchell Horne 	for (ri = 0; ri < md->pmd_npmc; ri++) {
1389c4981694SMitchell Horne 		if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1390c4981694SMitchell Horne 			continue;
1391c4981694SMitchell Horne 
1392c4981694SMitchell Horne 		po = pm->pm_owner;
1393c4981694SMitchell Horne 		if (po->po_sscount == 0 &&
1394c4981694SMitchell Horne 		    (po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) {
1395c4981694SMitchell Horne 			pmclog_process_procexec(po, pm->pm_id, p->p_pid,
1396c4981694SMitchell Horne 			    pk->pm_baseaddr, pk->pm_dynaddr, fullpath);
1397c4981694SMitchell Horne 		}
1398c4981694SMitchell Horne 	}
1399c4981694SMitchell Horne 
1400c4981694SMitchell Horne 	if (freepath != NULL)
1401c4981694SMitchell Horne 		free(freepath, M_TEMP);
1402c4981694SMitchell Horne 
1403c4981694SMitchell Horne 	PMCDBG4(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1404c4981694SMitchell Horne 	    p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1405c4981694SMitchell Horne 
1406c4981694SMitchell Horne 	if (pk->pm_credentialschanged == 0) /* no change */
1407c4981694SMitchell Horne 		return;
1408c4981694SMitchell Horne 
1409c4981694SMitchell Horne 	/*
1410c4981694SMitchell Horne 	 * If the newly exec()'ed process has a different credential
1411c4981694SMitchell Horne 	 * than before, allow it to be the target of a PMC only if
1412c4981694SMitchell Horne 	 * the PMC's owner has sufficient privilege.
1413c4981694SMitchell Horne 	 */
1414c4981694SMitchell Horne 	for (ri = 0; ri < md->pmd_npmc; ri++) {
1415c4981694SMitchell Horne 		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1416c4981694SMitchell Horne 			if (pmc_can_attach(pm, td->td_proc) != 0) {
1417c4981694SMitchell Horne 				pmc_detach_one_process(td->td_proc, pm,
1418c4981694SMitchell Horne 				    PMC_FLAG_NONE);
1419c4981694SMitchell Horne 			}
1420c4981694SMitchell Horne 		}
1421c4981694SMitchell Horne 	}
1422c4981694SMitchell Horne 
1423c4981694SMitchell Horne 	KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= md->pmd_npmc,
1424c4981694SMitchell Horne 	    ("[pmc,%d] Illegal ref count %u on pp %p", __LINE__,
1425c4981694SMitchell Horne 		pp->pp_refcnt, pp));
1426c4981694SMitchell Horne 
1427c4981694SMitchell Horne 	/*
1428c4981694SMitchell Horne 	 * If this process is no longer the target of any
1429c4981694SMitchell Horne 	 * PMCs, we can remove the process entry and free
1430c4981694SMitchell Horne 	 * up space.
1431c4981694SMitchell Horne 	 */
1432c4981694SMitchell Horne 	if (pp->pp_refcnt == 0) {
1433c4981694SMitchell Horne 		pmc_remove_process_descriptor(pp);
1434c4981694SMitchell Horne 		pmc_destroy_process_descriptor(pp);
1435c4981694SMitchell Horne 	}
1436c4981694SMitchell Horne }
1437c4981694SMitchell Horne 
1438c4981694SMitchell Horne /*
143901c35b67SMitchell Horne  * Thread context switch IN.
1440ebccf1e3SJoseph Koshy  */
1441f263522aSJoseph Koshy static void
1442f263522aSJoseph Koshy pmc_process_csw_in(struct thread *td)
1443ebccf1e3SJoseph Koshy {
1444ebccf1e3SJoseph Koshy 	struct pmc *pm;
144501c35b67SMitchell Horne 	struct pmc_classdep *pcd;
1446ebccf1e3SJoseph Koshy 	struct pmc_cpu *pc;
1447aee6e7dcSMateusz Guzik 	struct pmc_hw *phw __diagused;
1448e829eb6dSJoseph Koshy 	struct pmc_process *pp;
14496161b98cSMatt Macy 	struct pmc_thread *pt;
145001c35b67SMitchell Horne 	struct proc *p;
145101c35b67SMitchell Horne 	pmc_value_t newvalue;
145201c35b67SMitchell Horne 	int cpu;
145301c35b67SMitchell Horne 	u_int adjri, ri;
1454ebccf1e3SJoseph Koshy 
1455ebccf1e3SJoseph Koshy 	p = td->td_proc;
14566161b98cSMatt Macy 	pt = NULL;
1457ebccf1e3SJoseph Koshy 	if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1458f263522aSJoseph Koshy 		return;
1459ebccf1e3SJoseph Koshy 
1460ebccf1e3SJoseph Koshy 	KASSERT(pp->pp_proc == td->td_proc,
1461ebccf1e3SJoseph Koshy 	    ("[pmc,%d] not my thread state", __LINE__));
1462ebccf1e3SJoseph Koshy 
1463f263522aSJoseph Koshy 	critical_enter(); /* no preemption from this point */
1464ebccf1e3SJoseph Koshy 
1465ebccf1e3SJoseph Koshy 	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1466ebccf1e3SJoseph Koshy 
14674a3690dfSJohn Baldwin 	PMCDBG5(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1468ebccf1e3SJoseph Koshy 	    p->p_pid, p->p_comm, pp);
1469ebccf1e3SJoseph Koshy 
1470122ccdc1SJoseph Koshy 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1471b790c193SPedro F. Giffuni 	    ("[pmc,%d] weird CPU id %d", __LINE__, cpu));
1472ebccf1e3SJoseph Koshy 
1473ebccf1e3SJoseph Koshy 	pc = pmc_pcpu[cpu];
1474ebccf1e3SJoseph Koshy 	for (ri = 0; ri < md->pmd_npmc; ri++) {
1475ebccf1e3SJoseph Koshy 		if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1476ebccf1e3SJoseph Koshy 			continue;
1477ebccf1e3SJoseph Koshy 
1478c5153e19SJoseph Koshy 		KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1479ebccf1e3SJoseph Koshy 		    ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1480c5153e19SJoseph Koshy 		    __LINE__, PMC_TO_MODE(pm)));
1481c5153e19SJoseph Koshy 		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1482ebccf1e3SJoseph Koshy 		    ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1483c5153e19SJoseph Koshy 		    __LINE__, PMC_TO_ROWINDEX(pm), ri));
1484ebccf1e3SJoseph Koshy 
1485ebccf1e3SJoseph Koshy 		/*
1486ebccf1e3SJoseph Koshy 		 * Only PMCs that are marked as 'RUNNING' need
1487ebccf1e3SJoseph Koshy 		 * be placed on hardware.
1488ebccf1e3SJoseph Koshy 		 */
1489ebccf1e3SJoseph Koshy 		if (pm->pm_state != PMC_STATE_RUNNING)
1490ebccf1e3SJoseph Koshy 			continue;
1491ebccf1e3SJoseph Koshy 
1492d9f1b8dbSMatt Macy 		KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
149301c35b67SMitchell Horne 		    ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
149401c35b67SMitchell Horne 		    (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
1495d9f1b8dbSMatt Macy 
1496ebccf1e3SJoseph Koshy 		/* increment PMC runcount */
1497e6b475e0SMatt Macy 		counter_u64_add(pm->pm_runcount, 1);
1498ebccf1e3SJoseph Koshy 
1499ebccf1e3SJoseph Koshy 		/* configure the HWPMC we are going to use. */
1500e829eb6dSJoseph Koshy 		pcd = pmc_ri_to_classdep(md, ri, &adjri);
150101c35b67SMitchell Horne 		(void)pcd->pcd_config_pmc(cpu, adjri, pm);
1502ebccf1e3SJoseph Koshy 
1503ebccf1e3SJoseph Koshy 		phw = pc->pc_hwpmcs[ri];
1504ebccf1e3SJoseph Koshy 
1505ebccf1e3SJoseph Koshy 		KASSERT(phw != NULL,
1506ebccf1e3SJoseph Koshy 		    ("[pmc,%d] null hw pointer", __LINE__));
1507ebccf1e3SJoseph Koshy 
1508ebccf1e3SJoseph Koshy 		KASSERT(phw->phw_pmc == pm,
1509ebccf1e3SJoseph Koshy 		    ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1510ebccf1e3SJoseph Koshy 			phw->phw_pmc, pm));
1511ebccf1e3SJoseph Koshy 
1512f263522aSJoseph Koshy 		/*
1513f263522aSJoseph Koshy 		 * Write out saved value and start the PMC.
1514f263522aSJoseph Koshy 		 *
15156161b98cSMatt Macy 		 * Sampling PMCs use a per-thread value, while
1516f263522aSJoseph Koshy 		 * counting mode PMCs use a per-pmc value that is
1517f263522aSJoseph Koshy 		 * inherited across descendants.
1518f263522aSJoseph Koshy 		 */
1519f263522aSJoseph Koshy 		if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
15206161b98cSMatt Macy 			if (pt == NULL)
15216161b98cSMatt Macy 				pt = pmc_find_thread_descriptor(pp, td,
15226161b98cSMatt Macy 				    PMC_FLAG_NONE);
15236161b98cSMatt Macy 
15246161b98cSMatt Macy 			KASSERT(pt != NULL,
15256161b98cSMatt Macy 			    ("[pmc,%d] No thread found for td=%p", __LINE__,
15266161b98cSMatt Macy 			    td));
15276161b98cSMatt Macy 
1528f263522aSJoseph Koshy 			mtx_pool_lock_spin(pmc_mtxpool, pm);
15295eaa6f01SJonathan T. Looney 
15305eaa6f01SJonathan T. Looney 			/*
15316161b98cSMatt Macy 			 * If we have a thread descriptor, use the per-thread
15326161b98cSMatt Macy 			 * counter in the descriptor. If not, we will use
15336161b98cSMatt Macy 			 * a per-process counter.
15346161b98cSMatt Macy 			 *
15356161b98cSMatt Macy 			 * TODO: Remove the per-process "safety net" once
15366161b98cSMatt Macy 			 * we have thoroughly tested that we don't hit the
15376161b98cSMatt Macy 			 * above assert.
15385eaa6f01SJonathan T. Looney 			 */
15396161b98cSMatt Macy 			if (pt != NULL) {
15406161b98cSMatt Macy 				if (pt->pt_pmcs[ri].pt_pmcval > 0)
15416161b98cSMatt Macy 					newvalue = pt->pt_pmcs[ri].pt_pmcval;
15426161b98cSMatt Macy 				else
15436161b98cSMatt Macy 					newvalue = pm->pm_sc.pm_reloadcount;
15446161b98cSMatt Macy 			} else {
15456161b98cSMatt Macy 				/*
15466161b98cSMatt Macy 				 * Use the saved value calculated after the most
15476161b98cSMatt Macy 				 * recent time a thread using the shared counter
15486161b98cSMatt Macy 				 * switched out. Reset the saved count in case
15496161b98cSMatt Macy 				 * another thread from this process switches in
15506161b98cSMatt Macy 				 * before any threads switch out.
15516161b98cSMatt Macy 				 */
15526161b98cSMatt Macy 				newvalue = pp->pp_pmcs[ri].pp_pmcval;
15536161b98cSMatt Macy 				pp->pp_pmcs[ri].pp_pmcval =
15546161b98cSMatt Macy 				    pm->pm_sc.pm_reloadcount;
15556161b98cSMatt Macy 			}
1556f263522aSJoseph Koshy 			mtx_pool_unlock_spin(pmc_mtxpool, pm);
15576161b98cSMatt Macy 			KASSERT(newvalue > 0 && newvalue <=
15586161b98cSMatt Macy 			    pm->pm_sc.pm_reloadcount,
15596161b98cSMatt Macy 			    ("[pmc,%d] pmcval outside of expected range cpu=%d "
15606161b98cSMatt Macy 			    "ri=%d pmcval=%jx pm_reloadcount=%jx", __LINE__,
15616161b98cSMatt Macy 			    cpu, ri, newvalue, pm->pm_sc.pm_reloadcount));
1562f263522aSJoseph Koshy 		} else {
1563f263522aSJoseph Koshy 			KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1564f263522aSJoseph Koshy 			    ("[pmc,%d] illegal mode=%d", __LINE__,
1565f263522aSJoseph Koshy 			    PMC_TO_MODE(pm)));
1566ebccf1e3SJoseph Koshy 			mtx_pool_lock_spin(pmc_mtxpool, pm);
1567ebccf1e3SJoseph Koshy 			newvalue = PMC_PCPU_SAVED(cpu, ri) =
1568ebccf1e3SJoseph Koshy 			    pm->pm_gv.pm_savedvalue;
1569ebccf1e3SJoseph Koshy 			mtx_pool_unlock_spin(pmc_mtxpool, pm);
1570f263522aSJoseph Koshy 		}
1571f263522aSJoseph Koshy 
15724a3690dfSJohn Baldwin 		PMCDBG3(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1573ebccf1e3SJoseph Koshy 
157401c35b67SMitchell Horne 		(void)pcd->pcd_write_pmc(cpu, adjri, pm, newvalue);
1575a3924968SJonathan T. Looney 
1576a3924968SJonathan T. Looney 		/* If a sampling mode PMC, reset stalled state. */
1577a3924968SJonathan T. Looney 		if (PMC_TO_MODE(pm) == PMC_MODE_TS)
1578e6b475e0SMatt Macy 			pm->pm_pcpu_state[cpu].pps_stalled = 0;
1579a3924968SJonathan T. Looney 
1580a3924968SJonathan T. Looney 		/* Indicate that we desire this to run. */
1581e6b475e0SMatt Macy 		pm->pm_pcpu_state[cpu].pps_cpustate = 1;
1582a3924968SJonathan T. Looney 
1583a3924968SJonathan T. Looney 		/* Start the PMC. */
158401c35b67SMitchell Horne 		(void)pcd->pcd_start_pmc(cpu, adjri, pm);
1585ebccf1e3SJoseph Koshy 	}
1586ebccf1e3SJoseph Koshy 
1587ebccf1e3SJoseph Koshy 	/*
158801c35b67SMitchell Horne 	 * Perform any other architecture/cpu dependent thread
1589ebccf1e3SJoseph Koshy 	 * switch-in actions.
1590ebccf1e3SJoseph Koshy 	 */
15916b8c8cd8SJoseph Koshy 	(void)(*md->pmd_switch_in)(pc, pp);
1592ebccf1e3SJoseph Koshy 
1593ebccf1e3SJoseph Koshy 	critical_exit();
1594ebccf1e3SJoseph Koshy }
1595ebccf1e3SJoseph Koshy 
1596ebccf1e3SJoseph Koshy /*
1597ebccf1e3SJoseph Koshy  * Thread context switch OUT.
1598ebccf1e3SJoseph Koshy  */
1599f263522aSJoseph Koshy static void
1600f263522aSJoseph Koshy pmc_process_csw_out(struct thread *td)
1601ebccf1e3SJoseph Koshy {
1602ebccf1e3SJoseph Koshy 	struct pmc *pm;
160301c35b67SMitchell Horne 	struct pmc_classdep *pcd;
1604ebccf1e3SJoseph Koshy 	struct pmc_cpu *pc;
1605e829eb6dSJoseph Koshy 	struct pmc_process *pp;
16066161b98cSMatt Macy 	struct pmc_thread *pt = NULL;
160701c35b67SMitchell Horne 	struct proc *p;
160801c35b67SMitchell Horne 	pmc_value_t newvalue;
160901c35b67SMitchell Horne 	int64_t tmp;
161001c35b67SMitchell Horne 	enum pmc_mode mode;
161101c35b67SMitchell Horne 	int cpu;
161201c35b67SMitchell Horne 	u_int adjri, ri;
1613ebccf1e3SJoseph Koshy 
1614ebccf1e3SJoseph Koshy 	/*
1615ebccf1e3SJoseph Koshy 	 * Locate our process descriptor; this may be NULL if
1616ebccf1e3SJoseph Koshy 	 * this process is exiting and we have already removed
1617ebccf1e3SJoseph Koshy 	 * the process from the target process table.
1618ebccf1e3SJoseph Koshy 	 *
1619ebccf1e3SJoseph Koshy 	 * Note that due to kernel preemption, multiple
1620ebccf1e3SJoseph Koshy 	 * context switches may happen while the process is
1621ebccf1e3SJoseph Koshy 	 * exiting.
1622ebccf1e3SJoseph Koshy 	 *
1623ebccf1e3SJoseph Koshy 	 * Note also that if the target process cannot be
1624ebccf1e3SJoseph Koshy 	 * found we still need to deconfigure any PMCs that
1625ebccf1e3SJoseph Koshy 	 * are currently running on hardware.
1626ebccf1e3SJoseph Koshy 	 */
1627ebccf1e3SJoseph Koshy 	p = td->td_proc;
1628ebccf1e3SJoseph Koshy 	pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1629ebccf1e3SJoseph Koshy 
1630ebccf1e3SJoseph Koshy 	critical_enter();
1631ebccf1e3SJoseph Koshy 
1632ebccf1e3SJoseph Koshy 	cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1633ebccf1e3SJoseph Koshy 
16344a3690dfSJohn Baldwin 	PMCDBG5(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1635ebccf1e3SJoseph Koshy 	    p->p_pid, p->p_comm, pp);
1636ebccf1e3SJoseph Koshy 
1637122ccdc1SJoseph Koshy 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1638b790c193SPedro F. Giffuni 	    ("[pmc,%d weird CPU id %d", __LINE__, cpu));
1639ebccf1e3SJoseph Koshy 
1640ebccf1e3SJoseph Koshy 	pc = pmc_pcpu[cpu];
1641ebccf1e3SJoseph Koshy 
1642ebccf1e3SJoseph Koshy 	/*
1643ebccf1e3SJoseph Koshy 	 * When a PMC gets unlinked from a target PMC, it will
1644ebccf1e3SJoseph Koshy 	 * be removed from the target's pp_pmc[] array.
1645ebccf1e3SJoseph Koshy 	 *
1646ebccf1e3SJoseph Koshy 	 * However, on a MP system, the target could have been
1647ebccf1e3SJoseph Koshy 	 * executing on another CPU at the time of the unlink.
1648ebccf1e3SJoseph Koshy 	 * So, at context switch OUT time, we need to look at
1649ebccf1e3SJoseph Koshy 	 * the hardware to determine if a PMC is scheduled on
1650ebccf1e3SJoseph Koshy 	 * it.
1651ebccf1e3SJoseph Koshy 	 */
1652ebccf1e3SJoseph Koshy 	for (ri = 0; ri < md->pmd_npmc; ri++) {
1653e829eb6dSJoseph Koshy 		pcd = pmc_ri_to_classdep(md, ri, &adjri);
1654c5153e19SJoseph Koshy 		pm  = NULL;
1655e829eb6dSJoseph Koshy 		(void)(*pcd->pcd_get_config)(cpu, adjri, &pm);
1656ebccf1e3SJoseph Koshy 
1657ebccf1e3SJoseph Koshy 		if (pm == NULL)	/* nothing at this row index */
1658ebccf1e3SJoseph Koshy 			continue;
1659ebccf1e3SJoseph Koshy 
1660f263522aSJoseph Koshy 		mode = PMC_TO_MODE(pm);
1661f263522aSJoseph Koshy 		if (!PMC_IS_VIRTUAL_MODE(mode))
1662ebccf1e3SJoseph Koshy 			continue; /* not a process virtual PMC */
1663ebccf1e3SJoseph Koshy 
1664c5153e19SJoseph Koshy 		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1665ebccf1e3SJoseph Koshy 		    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1666c5153e19SJoseph Koshy 			__LINE__, PMC_TO_ROWINDEX(pm), ri));
1667ebccf1e3SJoseph Koshy 
1668a3924968SJonathan T. Looney 		/*
1669a3924968SJonathan T. Looney 		 * Change desired state, and then stop if not stalled.
1670a3924968SJonathan T. Looney 		 * This two-step dance should avoid race conditions where
1671a3924968SJonathan T. Looney 		 * an interrupt re-enables the PMC after this code has
1672a3924968SJonathan T. Looney 		 * already checked the pm_stalled flag.
1673a3924968SJonathan T. Looney 		 */
1674e6b475e0SMatt Macy 		pm->pm_pcpu_state[cpu].pps_cpustate = 0;
1675e6b475e0SMatt Macy 		if (pm->pm_pcpu_state[cpu].pps_stalled == 0)
167601c35b67SMitchell Horne 			(void)pcd->pcd_stop_pmc(cpu, adjri, pm);
1677ebccf1e3SJoseph Koshy 
1678d9f1b8dbSMatt Macy 		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
167901c35b67SMitchell Horne 		    ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
168001c35b67SMitchell Horne 		    (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
1681d9f1b8dbSMatt Macy 
1682ebccf1e3SJoseph Koshy 		/* reduce this PMC's runcount */
1683e6b475e0SMatt Macy 		counter_u64_add(pm->pm_runcount, -1);
1684ebccf1e3SJoseph Koshy 
1685ebccf1e3SJoseph Koshy 		/*
1686ebccf1e3SJoseph Koshy 		 * If this PMC is associated with this process,
1687ebccf1e3SJoseph Koshy 		 * save the reading.
1688ebccf1e3SJoseph Koshy 		 */
1689593077d6SAndriy Gapon 		if (pm->pm_state != PMC_STATE_DELETED && pp != NULL &&
1690593077d6SAndriy Gapon 		    pp->pp_pmcs[ri].pp_pmc != NULL) {
1691ebccf1e3SJoseph Koshy 			KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1692f263522aSJoseph Koshy 			    ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1693f263522aSJoseph Koshy 				pm, ri, pp->pp_pmcs[ri].pp_pmc));
1694ebccf1e3SJoseph Koshy 			KASSERT(pp->pp_refcnt > 0,
1695ebccf1e3SJoseph Koshy 			    ("[pmc,%d] pp refcnt = %d", __LINE__,
1696ebccf1e3SJoseph Koshy 				pp->pp_refcnt));
1697ebccf1e3SJoseph Koshy 
169801c35b67SMitchell Horne 			(void)pcd->pcd_read_pmc(cpu, adjri, pm, &newvalue);
1699ebccf1e3SJoseph Koshy 
1700f263522aSJoseph Koshy 			if (mode == PMC_MODE_TS) {
17016161b98cSMatt Macy 				PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d val=%jd (samp)",
17026161b98cSMatt Macy 				    cpu, ri, newvalue);
1703f263522aSJoseph Koshy 
17046161b98cSMatt Macy 				if (pt == NULL)
17056161b98cSMatt Macy 					pt = pmc_find_thread_descriptor(pp, td,
17066161b98cSMatt Macy 					    PMC_FLAG_NONE);
17076161b98cSMatt Macy 
17086161b98cSMatt Macy 				KASSERT(pt != NULL,
17096161b98cSMatt Macy 				    ("[pmc,%d] No thread found for td=%p",
17106161b98cSMatt Macy 				    __LINE__, td));
17116161b98cSMatt Macy 
1712f263522aSJoseph Koshy 				mtx_pool_lock_spin(pmc_mtxpool, pm);
17135eaa6f01SJonathan T. Looney 
17146161b98cSMatt Macy 				/*
17156161b98cSMatt Macy 				 * If we have a thread descriptor, save the
17166161b98cSMatt Macy 				 * per-thread counter in the descriptor. If not,
17176161b98cSMatt Macy 				 * we will update the per-process counter.
17186161b98cSMatt Macy 				 *
17196161b98cSMatt Macy 				 * TODO: Remove the per-process "safety net"
17206161b98cSMatt Macy 				 * once we have thoroughly tested that we
17216161b98cSMatt Macy 				 * don't hit the above assert.
17226161b98cSMatt Macy 				 */
1723d5ee4074SMitchell Horne 				if (pt != NULL) {
17246161b98cSMatt Macy 					pt->pt_pmcs[ri].pt_pmcval = newvalue;
1725d5ee4074SMitchell Horne 				} else {
17266161b98cSMatt Macy 					/*
17276161b98cSMatt Macy 					 * For sampling process-virtual PMCs,
17286161b98cSMatt Macy 					 * newvalue is the number of events to
17296161b98cSMatt Macy 					 * be seen until the next sampling
17306161b98cSMatt Macy 					 * interrupt. We can just add the events
17316161b98cSMatt Macy 					 * left from this invocation to the
17326161b98cSMatt Macy 					 * counter, then adjust in case we
17336161b98cSMatt Macy 					 * overflow our range.
17346161b98cSMatt Macy 					 *
17356161b98cSMatt Macy 					 * (Recall that we reload the counter
17366161b98cSMatt Macy 					 * every time we use it.)
17376161b98cSMatt Macy 					 */
17385eaa6f01SJonathan T. Looney 					pp->pp_pmcs[ri].pp_pmcval += newvalue;
17395eaa6f01SJonathan T. Looney 					if (pp->pp_pmcs[ri].pp_pmcval >
1740d5ee4074SMitchell Horne 					    pm->pm_sc.pm_reloadcount) {
17415eaa6f01SJonathan T. Looney 						pp->pp_pmcs[ri].pp_pmcval -=
1742f263522aSJoseph Koshy 						    pm->pm_sc.pm_reloadcount;
17436161b98cSMatt Macy 					}
1744d5ee4074SMitchell Horne 				}
1745f263522aSJoseph Koshy 				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1746f263522aSJoseph Koshy 			} else {
17475eaa6f01SJonathan T. Looney 				tmp = newvalue - PMC_PCPU_SAVED(cpu, ri);
17485eaa6f01SJonathan T. Looney 
17495eaa6f01SJonathan T. Looney 				PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd (count)",
17505eaa6f01SJonathan T. Looney 				    cpu, ri, tmp);
1751f263522aSJoseph Koshy 
1752f263522aSJoseph Koshy 				/*
1753f263522aSJoseph Koshy 				 * For counting process-virtual PMCs,
1754f263522aSJoseph Koshy 				 * we expect the count to be
1755f263522aSJoseph Koshy 				 * increasing monotonically, modulo a 64
1756f263522aSJoseph Koshy 				 * bit wraparound.
1757f263522aSJoseph Koshy 				 */
17580c8cc7b0SKonstantin Belousov 				KASSERT(tmp >= 0,
1759ebccf1e3SJoseph Koshy 				    ("[pmc,%d] negative increment cpu=%d "
1760ebccf1e3SJoseph Koshy 				     "ri=%d newvalue=%jx saved=%jx "
1761ebccf1e3SJoseph Koshy 				     "incr=%jx", __LINE__, cpu, ri,
1762f263522aSJoseph Koshy 				     newvalue, PMC_PCPU_SAVED(cpu, ri), tmp));
1763ebccf1e3SJoseph Koshy 
1764ebccf1e3SJoseph Koshy 				mtx_pool_lock_spin(pmc_mtxpool, pm);
1765ebccf1e3SJoseph Koshy 				pm->pm_gv.pm_savedvalue += tmp;
1766ebccf1e3SJoseph Koshy 				pp->pp_pmcs[ri].pp_pmcval += tmp;
1767ebccf1e3SJoseph Koshy 				mtx_pool_unlock_spin(pmc_mtxpool, pm);
1768ebccf1e3SJoseph Koshy 
1769f263522aSJoseph Koshy 				if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1770a85289cfSMatt Macy 					pmclog_process_proccsw(pm, pp, tmp, td);
1771f263522aSJoseph Koshy 			}
1772ebccf1e3SJoseph Koshy 		}
1773ebccf1e3SJoseph Koshy 
177401c35b67SMitchell Horne 		/* Mark hardware as free. */
177501c35b67SMitchell Horne 		(void)pcd->pcd_config_pmc(cpu, adjri, NULL);
1776ebccf1e3SJoseph Koshy 	}
1777ebccf1e3SJoseph Koshy 
1778ebccf1e3SJoseph Koshy 	/*
177901c35b67SMitchell Horne 	 * Perform any other architecture/cpu dependent thread
1780ebccf1e3SJoseph Koshy 	 * switch out functions.
1781ebccf1e3SJoseph Koshy 	 */
17826b8c8cd8SJoseph Koshy 	(void)(*md->pmd_switch_out)(pc, pp);
1783ebccf1e3SJoseph Koshy 
1784ebccf1e3SJoseph Koshy 	critical_exit();
1785f263522aSJoseph Koshy }
1786f263522aSJoseph Koshy 
1787f263522aSJoseph Koshy /*
17886161b98cSMatt Macy  * A new thread for a process.
17896161b98cSMatt Macy  */
17906161b98cSMatt Macy static void
17916161b98cSMatt Macy pmc_process_thread_add(struct thread *td)
17926161b98cSMatt Macy {
17936161b98cSMatt Macy 	struct pmc_process *pmc;
17946161b98cSMatt Macy 
17956161b98cSMatt Macy 	pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
17966161b98cSMatt Macy 	if (pmc != NULL)
17976161b98cSMatt Macy 		pmc_find_thread_descriptor(pmc, td, PMC_FLAG_ALLOCATE);
17986161b98cSMatt Macy }
17996161b98cSMatt Macy 
18006161b98cSMatt Macy /*
18016161b98cSMatt Macy  * A thread delete for a process.
18026161b98cSMatt Macy  */
18036161b98cSMatt Macy static void
18046161b98cSMatt Macy pmc_process_thread_delete(struct thread *td)
18056161b98cSMatt Macy {
18066161b98cSMatt Macy 	struct pmc_process *pmc;
18076161b98cSMatt Macy 
18086161b98cSMatt Macy 	pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
18096161b98cSMatt Macy 	if (pmc != NULL)
18106161b98cSMatt Macy 		pmc_thread_descriptor_pool_free(pmc_find_thread_descriptor(pmc,
18116161b98cSMatt Macy 		    td, PMC_FLAG_REMOVE));
18126161b98cSMatt Macy }
18136161b98cSMatt Macy 
18146161b98cSMatt Macy /*
18155de96e33SMatt Macy  * A userret() call for a thread.
18165de96e33SMatt Macy  */
18175de96e33SMatt Macy static void
18185de96e33SMatt Macy pmc_process_thread_userret(struct thread *td)
18195de96e33SMatt Macy {
1820ac7012d2SMatt Macy 	sched_pin();
1821ac7012d2SMatt Macy 	pmc_capture_user_callchain(curcpu, PMC_UR, td->td_frame);
1822ac7012d2SMatt Macy 	sched_unpin();
18235de96e33SMatt Macy }
18245de96e33SMatt Macy 
18255de96e33SMatt Macy /*
182649874f6eSJoseph Koshy  * A mapping change for a process.
182749874f6eSJoseph Koshy  */
182849874f6eSJoseph Koshy static void
182949874f6eSJoseph Koshy pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
183049874f6eSJoseph Koshy {
183149874f6eSJoseph Koshy 	const struct pmc *pm;
183249874f6eSJoseph Koshy 	const struct pmc_process *pp;
183301c35b67SMitchell Horne 	struct pmc_owner *po;
183401c35b67SMitchell Horne 	char *fullpath, *freepath;
183501c35b67SMitchell Horne 	pid_t pid;
183601c35b67SMitchell Horne 	int ri;
183701c35b67SMitchell Horne 
183801c35b67SMitchell Horne 	MPASS(!in_epoch(global_epoch_preempt));
183949874f6eSJoseph Koshy 
184049874f6eSJoseph Koshy 	freepath = fullpath = NULL;
184149874f6eSJoseph Koshy 	pmc_getfilename((struct vnode *)pkm->pm_file, &fullpath, &freepath);
184249874f6eSJoseph Koshy 
184349874f6eSJoseph Koshy 	pid = td->td_proc->p_pid;
184449874f6eSJoseph Koshy 
18456573d758SMatt Macy 	PMC_EPOCH_ENTER();
184649874f6eSJoseph Koshy 	/* Inform owners of all system-wide sampling PMCs. */
1847d5ee4074SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
184849874f6eSJoseph Koshy 		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1849d5ee4074SMitchell Horne 			pmclog_process_map_in(po, pid, pkm->pm_address,
1850d5ee4074SMitchell Horne 			    fullpath);
1851d5ee4074SMitchell Horne 	}
185249874f6eSJoseph Koshy 
185349874f6eSJoseph Koshy 	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
185449874f6eSJoseph Koshy 		goto done;
185549874f6eSJoseph Koshy 
185649874f6eSJoseph Koshy 	/*
185749874f6eSJoseph Koshy 	 * Inform sampling PMC owners tracking this process.
185849874f6eSJoseph Koshy 	 */
1859d5ee4074SMitchell Horne 	for (ri = 0; ri < md->pmd_npmc; ri++) {
186049874f6eSJoseph Koshy 		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1861d5ee4074SMitchell Horne 		    PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
186249874f6eSJoseph Koshy 			pmclog_process_map_in(pm->pm_owner,
186349874f6eSJoseph Koshy 			    pid, pkm->pm_address, fullpath);
1864d5ee4074SMitchell Horne 		}
1865d5ee4074SMitchell Horne 	}
186649874f6eSJoseph Koshy 
186749874f6eSJoseph Koshy done:
1868d5ee4074SMitchell Horne 	if (freepath != NULL)
18691ede983cSDag-Erling Smørgrav 		free(freepath, M_TEMP);
18706573d758SMatt Macy 	PMC_EPOCH_EXIT();
187149874f6eSJoseph Koshy }
187249874f6eSJoseph Koshy 
187349874f6eSJoseph Koshy /*
187449874f6eSJoseph Koshy  * Log an munmap request.
187549874f6eSJoseph Koshy  */
187649874f6eSJoseph Koshy static void
187749874f6eSJoseph Koshy pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
187849874f6eSJoseph Koshy {
187949874f6eSJoseph Koshy 	const struct pmc *pm;
188049874f6eSJoseph Koshy 	const struct pmc_process *pp;
188101c35b67SMitchell Horne 	struct pmc_owner *po;
188201c35b67SMitchell Horne 	pid_t pid;
188301c35b67SMitchell Horne 	int ri;
188449874f6eSJoseph Koshy 
188549874f6eSJoseph Koshy 	pid = td->td_proc->p_pid;
188649874f6eSJoseph Koshy 
18876573d758SMatt Macy 	PMC_EPOCH_ENTER();
1888d5ee4074SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
188949874f6eSJoseph Koshy 		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
189049874f6eSJoseph Koshy 			pmclog_process_map_out(po, pid, pkm->pm_address,
189149874f6eSJoseph Koshy 			    pkm->pm_address + pkm->pm_size);
1892d5ee4074SMitchell Horne 	}
18936573d758SMatt Macy 	PMC_EPOCH_EXIT();
189449874f6eSJoseph Koshy 
189549874f6eSJoseph Koshy 	if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
189649874f6eSJoseph Koshy 		return;
189749874f6eSJoseph Koshy 
1898d5ee4074SMitchell Horne 	for (ri = 0; ri < md->pmd_npmc; ri++) {
1899d5ee4074SMitchell Horne 		pm = pp->pp_pmcs[ri].pp_pmc;
1900d5ee4074SMitchell Horne 		if (pm != NULL && PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
19017c9f60e3SJoseph Koshy 			pmclog_process_map_out(pm->pm_owner, pid,
19027c9f60e3SJoseph Koshy 			    pkm->pm_address, pkm->pm_address + pkm->pm_size);
190349874f6eSJoseph Koshy 		}
1904d5ee4074SMitchell Horne 	}
1905d5ee4074SMitchell Horne }
190649874f6eSJoseph Koshy 
190749874f6eSJoseph Koshy /*
1908d07f36b0SJoseph Koshy  * Log mapping information about the kernel.
1909d07f36b0SJoseph Koshy  */
1910d07f36b0SJoseph Koshy static void
1911d07f36b0SJoseph Koshy pmc_log_kernel_mappings(struct pmc *pm)
1912d07f36b0SJoseph Koshy {
1913d07f36b0SJoseph Koshy 	struct pmc_owner *po;
1914d07f36b0SJoseph Koshy 	struct pmckern_map_in *km, *kmbase;
1915d07f36b0SJoseph Koshy 
19166573d758SMatt Macy 	MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx));
1917d07f36b0SJoseph Koshy 	KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1918d07f36b0SJoseph Koshy 	    ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1919d07f36b0SJoseph Koshy 		__LINE__, (void *) pm));
1920d07f36b0SJoseph Koshy 
1921d07f36b0SJoseph Koshy 	po = pm->pm_owner;
1922d5ee4074SMitchell Horne 	if ((po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE) != 0)
1923d07f36b0SJoseph Koshy 		return;
1924693cd307SMitchell Horne 
192541abd7afSMatt Macy 	if (PMC_TO_MODE(pm) == PMC_MODE_SS)
192641abd7afSMatt Macy 		pmc_process_allproc(pm);
1927693cd307SMitchell Horne 
1928d07f36b0SJoseph Koshy 	/*
1929d07f36b0SJoseph Koshy 	 * Log the current set of kernel modules.
1930d07f36b0SJoseph Koshy 	 */
1931d07f36b0SJoseph Koshy 	kmbase = linker_hwpmc_list_objects();
1932d07f36b0SJoseph Koshy 	for (km = kmbase; km->pm_file != NULL; km++) {
19334a3690dfSJohn Baldwin 		PMCDBG2(LOG,REG,1,"%s %p", (char *)km->pm_file,
1934d07f36b0SJoseph Koshy 		    (void *)km->pm_address);
1935d07f36b0SJoseph Koshy 		pmclog_process_map_in(po, (pid_t)-1, km->pm_address,
1936d07f36b0SJoseph Koshy 		    km->pm_file);
1937d07f36b0SJoseph Koshy 	}
19381ede983cSDag-Erling Smørgrav 	free(kmbase, M_LINKER);
1939d07f36b0SJoseph Koshy 
1940d07f36b0SJoseph Koshy 	po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1941d07f36b0SJoseph Koshy }
1942d07f36b0SJoseph Koshy 
1943d07f36b0SJoseph Koshy /*
1944d07f36b0SJoseph Koshy  * Log the mappings for a single process.
1945d07f36b0SJoseph Koshy  */
1946d07f36b0SJoseph Koshy static void
1947d07f36b0SJoseph Koshy pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1948d07f36b0SJoseph Koshy {
1949bf792d68SJoseph Koshy 	vm_map_t map;
1950bf792d68SJoseph Koshy 	vm_map_entry_t entry;
1951bf792d68SJoseph Koshy 	vm_object_t obj, lobj, tobj;
195201c35b67SMitchell Horne 	vm_offset_t last_end;
195301c35b67SMitchell Horne 	vm_offset_t start_addr;
195401c35b67SMitchell Horne 	struct vnode *vp, *last_vp;
195501c35b67SMitchell Horne 	struct vmspace *vm;
1956bf792d68SJoseph Koshy 	char *fullpath, *freepath;
195701c35b67SMitchell Horne 	u_int last_timestamp;
1958bf792d68SJoseph Koshy 
1959bf792d68SJoseph Koshy 	last_vp = NULL;
1960bf792d68SJoseph Koshy 	last_end = (vm_offset_t)0;
1961bf792d68SJoseph Koshy 	fullpath = freepath = NULL;
1962bf792d68SJoseph Koshy 
1963bf792d68SJoseph Koshy 	if ((vm = vmspace_acquire_ref(p)) == NULL)
1964bf792d68SJoseph Koshy 		return;
1965bf792d68SJoseph Koshy 
1966bf792d68SJoseph Koshy 	map = &vm->vm_map;
1967bf792d68SJoseph Koshy 	vm_map_lock_read(map);
19682288078cSDoug Moore 	VM_MAP_ENTRY_FOREACH(entry, map) {
1969bf792d68SJoseph Koshy 		if (entry == NULL) {
19704a3690dfSJohn Baldwin 			PMCDBG2(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly "
1971bf792d68SJoseph Koshy 			    "NULL! pid=%d vm_map=%p\n", p->p_pid, map);
1972bf792d68SJoseph Koshy 			break;
1973bf792d68SJoseph Koshy 		}
1974bf792d68SJoseph Koshy 
1975bf792d68SJoseph Koshy 		/*
1976bf792d68SJoseph Koshy 		 * We only care about executable map entries.
1977bf792d68SJoseph Koshy 		 */
1978d5ee4074SMitchell Horne 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
1979d5ee4074SMitchell Horne 		    (entry->protection & VM_PROT_EXECUTE) == 0 ||
1980d5ee4074SMitchell Horne 		    entry->object.vm_object == NULL) {
1981bf792d68SJoseph Koshy 			continue;
1982bf792d68SJoseph Koshy 		}
1983bf792d68SJoseph Koshy 
1984bf792d68SJoseph Koshy 		obj = entry->object.vm_object;
198566c392dfSAlan Cox 		VM_OBJECT_RLOCK(obj);
1986bf792d68SJoseph Koshy 
1987bf792d68SJoseph Koshy 		/*
198801c35b67SMitchell Horne 		 * Walk the backing_object list to find the base (non-shadowed)
198901c35b67SMitchell Horne 		 * vm_object.
1990bf792d68SJoseph Koshy 		 */
1991d5ee4074SMitchell Horne 		for (lobj = tobj = obj; tobj != NULL;
1992d5ee4074SMitchell Horne 		    tobj = tobj->backing_object) {
1993bf792d68SJoseph Koshy 			if (tobj != obj)
199466c392dfSAlan Cox 				VM_OBJECT_RLOCK(tobj);
1995bf792d68SJoseph Koshy 			if (lobj != obj)
199666c392dfSAlan Cox 				VM_OBJECT_RUNLOCK(lobj);
1997bf792d68SJoseph Koshy 			lobj = tobj;
1998bf792d68SJoseph Koshy 		}
1999bf792d68SJoseph Koshy 
2000bf792d68SJoseph Koshy 		/*
2001bf792d68SJoseph Koshy 		 * At this point lobj is the base vm_object and it is locked.
2002bf792d68SJoseph Koshy 		 */
2003bf792d68SJoseph Koshy 		if (lobj == NULL) {
2004693cd307SMitchell Horne 			PMCDBG3(LOG,OPS,2,
2005693cd307SMitchell Horne 			    "hwpmc: lobj unexpectedly NULL! pid=%d "
2006bf792d68SJoseph Koshy 			    "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj);
200766c392dfSAlan Cox 			VM_OBJECT_RUNLOCK(obj);
2008bf792d68SJoseph Koshy 			continue;
2009bf792d68SJoseph Koshy 		}
2010bf792d68SJoseph Koshy 
201163e4c6cdSEric van Gyzen 		vp = vm_object_vnode(lobj);
201263e4c6cdSEric van Gyzen 		if (vp == NULL) {
2013bf792d68SJoseph Koshy 			if (lobj != obj)
201466c392dfSAlan Cox 				VM_OBJECT_RUNLOCK(lobj);
201566c392dfSAlan Cox 			VM_OBJECT_RUNLOCK(obj);
2016bf792d68SJoseph Koshy 			continue;
2017bf792d68SJoseph Koshy 		}
2018bf792d68SJoseph Koshy 
2019bf792d68SJoseph Koshy 		/*
202001c35b67SMitchell Horne 		 * Skip contiguous regions that point to the same vnode, so we
202101c35b67SMitchell Horne 		 * don't emit redundant MAP-IN directives.
2022bf792d68SJoseph Koshy 		 */
202363e4c6cdSEric van Gyzen 		if (entry->start == last_end && vp == last_vp) {
2024bf792d68SJoseph Koshy 			last_end = entry->end;
2025bf792d68SJoseph Koshy 			if (lobj != obj)
202666c392dfSAlan Cox 				VM_OBJECT_RUNLOCK(lobj);
202766c392dfSAlan Cox 			VM_OBJECT_RUNLOCK(obj);
2028bf792d68SJoseph Koshy 			continue;
2029bf792d68SJoseph Koshy 		}
2030bf792d68SJoseph Koshy 
2031bf792d68SJoseph Koshy 		/*
203201c35b67SMitchell Horne 		 * We don't want to keep the proc's vm_map or this vm_object
203301c35b67SMitchell Horne 		 * locked while we walk the pathname, since vn_fullpath() can
203401c35b67SMitchell Horne 		 * sleep.  However, if we drop the lock, it's possible for
203501c35b67SMitchell Horne 		 * concurrent activity to modify the vm_map list.  To protect
203601c35b67SMitchell Horne 		 * against this, we save the vm_map timestamp before we release
203701c35b67SMitchell Horne 		 * the lock, and check it after we reacquire the lock below.
2038bf792d68SJoseph Koshy 		 */
2039bf792d68SJoseph Koshy 		start_addr = entry->start;
2040bf792d68SJoseph Koshy 		last_end = entry->end;
2041bf792d68SJoseph Koshy 		last_timestamp = map->timestamp;
2042bf792d68SJoseph Koshy 		vm_map_unlock_read(map);
2043bf792d68SJoseph Koshy 
2044bf792d68SJoseph Koshy 		vref(vp);
2045bf792d68SJoseph Koshy 		if (lobj != obj)
204666c392dfSAlan Cox 			VM_OBJECT_RUNLOCK(lobj);
204766c392dfSAlan Cox 		VM_OBJECT_RUNLOCK(obj);
2048bf792d68SJoseph Koshy 
2049bf792d68SJoseph Koshy 		freepath = NULL;
2050bf792d68SJoseph Koshy 		pmc_getfilename(vp, &fullpath, &freepath);
2051bf792d68SJoseph Koshy 		last_vp = vp;
2052e9b5dc16SJoseph Koshy 
2053bf792d68SJoseph Koshy 		vrele(vp);
2054e9b5dc16SJoseph Koshy 
2055bf792d68SJoseph Koshy 		vp = NULL;
2056bf792d68SJoseph Koshy 		pmclog_process_map_in(po, p->p_pid, start_addr, fullpath);
2057d5ee4074SMitchell Horne 		if (freepath != NULL)
2058bf792d68SJoseph Koshy 			free(freepath, M_TEMP);
2059bf792d68SJoseph Koshy 
2060bf792d68SJoseph Koshy 		vm_map_lock_read(map);
2061bf792d68SJoseph Koshy 
2062bf792d68SJoseph Koshy 		/*
2063bf792d68SJoseph Koshy 		 * If our saved timestamp doesn't match, this means
2064bf792d68SJoseph Koshy 		 * that the vm_map was modified out from under us and
2065bf792d68SJoseph Koshy 		 * we can't trust our current "entry" pointer.  Do a
2066bf792d68SJoseph Koshy 		 * new lookup for this entry.  If there is no entry
2067bf792d68SJoseph Koshy 		 * for this address range, vm_map_lookup_entry() will
2068bf792d68SJoseph Koshy 		 * return the previous one, so we always want to go to
20692288078cSDoug Moore 		 * the next entry on the next loop iteration.
2070bf792d68SJoseph Koshy 		 *
2071bf792d68SJoseph Koshy 		 * There is an edge condition here that can occur if
2072bf792d68SJoseph Koshy 		 * there is no entry at or before this address.  In
2073bf792d68SJoseph Koshy 		 * this situation, vm_map_lookup_entry returns
2074bf792d68SJoseph Koshy 		 * &map->header, which would cause our loop to abort
2075bf792d68SJoseph Koshy 		 * without processing the rest of the map.  However,
2076bf792d68SJoseph Koshy 		 * in practice this will never happen for process
2077bf792d68SJoseph Koshy 		 * vm_map.  This is because the executable's text
2078bf792d68SJoseph Koshy 		 * segment is the first mapping in the proc's address
2079bf792d68SJoseph Koshy 		 * space, and this mapping is never removed until the
2080bf792d68SJoseph Koshy 		 * process exits, so there will always be a non-header
2081bf792d68SJoseph Koshy 		 * entry at or before the requested address for
2082bf792d68SJoseph Koshy 		 * vm_map_lookup_entry to return.
2083bf792d68SJoseph Koshy 		 */
2084bf792d68SJoseph Koshy 		if (map->timestamp != last_timestamp)
2085bf792d68SJoseph Koshy 			vm_map_lookup_entry(map, last_end - 1, &entry);
2086bf792d68SJoseph Koshy 	}
2087bf792d68SJoseph Koshy 
2088bf792d68SJoseph Koshy 	vm_map_unlock_read(map);
2089bf792d68SJoseph Koshy 	vmspace_free(vm);
2090bf792d68SJoseph Koshy 	return;
2091d07f36b0SJoseph Koshy }
2092d07f36b0SJoseph Koshy 
2093d07f36b0SJoseph Koshy /*
2094d07f36b0SJoseph Koshy  * Log mappings for all processes in the system.
2095d07f36b0SJoseph Koshy  */
2096d07f36b0SJoseph Koshy static void
2097d07f36b0SJoseph Koshy pmc_log_all_process_mappings(struct pmc_owner *po)
2098d07f36b0SJoseph Koshy {
2099d07f36b0SJoseph Koshy 	struct proc *p, *top;
2100d07f36b0SJoseph Koshy 
2101d07f36b0SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
2102d07f36b0SJoseph Koshy 
2103d07f36b0SJoseph Koshy 	if ((p = pfind(1)) == NULL)
2104d07f36b0SJoseph Koshy 		panic("[pmc,%d] Cannot find init", __LINE__);
2105d07f36b0SJoseph Koshy 
2106d07f36b0SJoseph Koshy 	PROC_UNLOCK(p);
2107d07f36b0SJoseph Koshy 
2108d07f36b0SJoseph Koshy 	sx_slock(&proctree_lock);
2109d07f36b0SJoseph Koshy 
2110d07f36b0SJoseph Koshy 	top = p;
2111d07f36b0SJoseph Koshy 	for (;;) {
2112d07f36b0SJoseph Koshy 		pmc_log_process_mappings(po, p);
2113d07f36b0SJoseph Koshy 		if (!LIST_EMPTY(&p->p_children))
2114d07f36b0SJoseph Koshy 			p = LIST_FIRST(&p->p_children);
2115d07f36b0SJoseph Koshy 		else for (;;) {
2116d07f36b0SJoseph Koshy 			if (p == top)
2117d07f36b0SJoseph Koshy 				goto done;
2118d07f36b0SJoseph Koshy 			if (LIST_NEXT(p, p_sibling)) {
2119d07f36b0SJoseph Koshy 				p = LIST_NEXT(p, p_sibling);
2120d07f36b0SJoseph Koshy 				break;
2121d07f36b0SJoseph Koshy 			}
2122d07f36b0SJoseph Koshy 			p = p->p_pptr;
2123d07f36b0SJoseph Koshy 		}
2124d07f36b0SJoseph Koshy 	}
2125d07f36b0SJoseph Koshy done:
2126d07f36b0SJoseph Koshy 	sx_sunlock(&proctree_lock);
2127d07f36b0SJoseph Koshy }
2128d07f36b0SJoseph Koshy 
2129680f1afdSJohn Baldwin #ifdef HWPMC_DEBUG
2130f263522aSJoseph Koshy const char *pmc_hooknames[] = {
213149874f6eSJoseph Koshy 	/* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
2132f263522aSJoseph Koshy 	"",
2133f263522aSJoseph Koshy 	"EXEC",
2134f263522aSJoseph Koshy 	"CSW-IN",
2135f263522aSJoseph Koshy 	"CSW-OUT",
213649874f6eSJoseph Koshy 	"SAMPLE",
213729f4e216SMark Johnston 	"UNUSED1",
213829f4e216SMark Johnston 	"UNUSED2",
213949874f6eSJoseph Koshy 	"MMAP",
2140d07f36b0SJoseph Koshy 	"MUNMAP",
2141f5f9340bSFabien Thomas 	"CALLCHAIN-NMI",
2142f5f9340bSFabien Thomas 	"CALLCHAIN-SOFT",
21436161b98cSMatt Macy 	"SOFTSAMPLING",
21446161b98cSMatt Macy 	"THR-CREATE",
21456161b98cSMatt Macy 	"THR-EXIT",
21465de96e33SMatt Macy 	"THR-USERRET",
2147ebfaf69cSMatt Macy 	"THR-CREATE-LOG",
2148ebfaf69cSMatt Macy 	"THR-EXIT-LOG",
2149ebfaf69cSMatt Macy 	"PROC-CREATE-LOG"
2150f263522aSJoseph Koshy };
2151f263522aSJoseph Koshy #endif
2152f263522aSJoseph Koshy 
215301c35b67SMitchell Horne /*
215401c35b67SMitchell Horne  * The 'hook' invoked from the kernel proper
215501c35b67SMitchell Horne  */
2156f263522aSJoseph Koshy static int
2157f263522aSJoseph Koshy pmc_hook_handler(struct thread *td, int function, void *arg)
2158f263522aSJoseph Koshy {
21596161b98cSMatt Macy 	int cpu;
2160f263522aSJoseph Koshy 
21614a3690dfSJohn Baldwin 	PMCDBG4(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
2162f263522aSJoseph Koshy 	    pmc_hooknames[function], arg);
2163f263522aSJoseph Koshy 
2164d5ee4074SMitchell Horne 	switch (function) {
2165f263522aSJoseph Koshy 	case PMC_FN_PROCESS_EXEC:
2166c4981694SMitchell Horne 		pmc_process_exec(td, (struct pmckern_procexec *)arg);
2167ebccf1e3SJoseph Koshy 		break;
2168ebccf1e3SJoseph Koshy 
2169f263522aSJoseph Koshy 	case PMC_FN_CSW_IN:
2170f263522aSJoseph Koshy 		pmc_process_csw_in(td);
2171f263522aSJoseph Koshy 		break;
2172f263522aSJoseph Koshy 
2173f263522aSJoseph Koshy 	case PMC_FN_CSW_OUT:
2174f263522aSJoseph Koshy 		pmc_process_csw_out(td);
2175f263522aSJoseph Koshy 		break;
2176f263522aSJoseph Koshy 
2177f263522aSJoseph Koshy 	/*
2178f263522aSJoseph Koshy 	 * Process accumulated PC samples.
2179f263522aSJoseph Koshy 	 *
2180f263522aSJoseph Koshy 	 * This function is expected to be called by hardclock() for
2181f263522aSJoseph Koshy 	 * each CPU that has accumulated PC samples.
2182f263522aSJoseph Koshy 	 *
2183f263522aSJoseph Koshy 	 * This function is to be executed on the CPU whose samples
2184f263522aSJoseph Koshy 	 * are being processed.
2185f263522aSJoseph Koshy 	 */
2186f263522aSJoseph Koshy 	case PMC_FN_DO_SAMPLES:
2187f263522aSJoseph Koshy 		/*
2188f263522aSJoseph Koshy 		 * Clear the cpu specific bit in the CPU mask before
2189f263522aSJoseph Koshy 		 * do the rest of the processing.  If the NMI handler
2190f263522aSJoseph Koshy 		 * gets invoked after the "atomic_clear_int()" call
2191f263522aSJoseph Koshy 		 * below but before "pmc_process_samples()" gets
2192f263522aSJoseph Koshy 		 * around to processing the interrupt, then we will
2193f263522aSJoseph Koshy 		 * come back here at the next hardclock() tick (and
2194f263522aSJoseph Koshy 		 * may find nothing to do if "pmc_process_samples()"
2195f263522aSJoseph Koshy 		 * had already processed the interrupt).  We don't
2196f263522aSJoseph Koshy 		 * lose the interrupt sample.
2197f263522aSJoseph Koshy 		 */
2198e6b475e0SMatt Macy 		DPCPU_SET(pmc_sampled, 0);
21996161b98cSMatt Macy 		cpu = PCPU_GET(cpuid);
22006161b98cSMatt Macy 		pmc_process_samples(cpu, PMC_HR);
22016161b98cSMatt Macy 		pmc_process_samples(cpu, PMC_SR);
22025de96e33SMatt Macy 		pmc_process_samples(cpu, PMC_UR);
2203f263522aSJoseph Koshy 		break;
2204f263522aSJoseph Koshy 
220549874f6eSJoseph Koshy 	case PMC_FN_MMAP:
220649874f6eSJoseph Koshy 		pmc_process_mmap(td, (struct pmckern_map_in *)arg);
220749874f6eSJoseph Koshy 		break;
220849874f6eSJoseph Koshy 
220949874f6eSJoseph Koshy 	case PMC_FN_MUNMAP:
22106573d758SMatt Macy 		MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx));
221149874f6eSJoseph Koshy 		pmc_process_munmap(td, (struct pmckern_map_out *)arg);
221249874f6eSJoseph Koshy 		break;
221349874f6eSJoseph Koshy 
2214ebfaf69cSMatt Macy 	case PMC_FN_PROC_CREATE_LOG:
2215ebfaf69cSMatt Macy 		pmc_process_proccreate((struct proc *)arg);
2216ebfaf69cSMatt Macy 		break;
2217ebfaf69cSMatt Macy 
2218d07f36b0SJoseph Koshy 	case PMC_FN_USER_CALLCHAIN:
2219d07f36b0SJoseph Koshy 		/*
2220d07f36b0SJoseph Koshy 		 * Record a call chain.
2221d07f36b0SJoseph Koshy 		 */
22226fe00c78SJoseph Koshy 		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
22236fe00c78SJoseph Koshy 		    __LINE__));
2224f5f9340bSFabien Thomas 
2225f5f9340bSFabien Thomas 		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
2226d07f36b0SJoseph Koshy 		    (struct trapframe *)arg);
22275de96e33SMatt Macy 
22285de96e33SMatt Macy 		KASSERT(td->td_pinned == 1,
22295de96e33SMatt Macy 		    ("[pmc,%d] invalid td_pinned value", __LINE__));
22305de96e33SMatt Macy 		sched_unpin();  /* Can migrate safely now. */
22315de96e33SMatt Macy 
22326fe00c78SJoseph Koshy 		td->td_pflags &= ~TDP_CALLCHAIN;
2233d07f36b0SJoseph Koshy 		break;
2234d07f36b0SJoseph Koshy 
2235f5f9340bSFabien Thomas 	case PMC_FN_USER_CALLCHAIN_SOFT:
2236f5f9340bSFabien Thomas 		/*
2237f5f9340bSFabien Thomas 		 * Record a call chain.
2238f5f9340bSFabien Thomas 		 */
2239f5f9340bSFabien Thomas 		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2240f5f9340bSFabien Thomas 		    __LINE__));
22415de96e33SMatt Macy 
22425de96e33SMatt Macy 		cpu = PCPU_GET(cpuid);
22435de96e33SMatt Macy 		pmc_capture_user_callchain(cpu, PMC_SR,
2244f5f9340bSFabien Thomas 		    (struct trapframe *) arg);
22455de96e33SMatt Macy 
22465de96e33SMatt Macy 		KASSERT(td->td_pinned == 1,
22475de96e33SMatt Macy 		    ("[pmc,%d] invalid td_pinned value", __LINE__));
22485de96e33SMatt Macy 
22495de96e33SMatt Macy 		sched_unpin();  /* Can migrate safely now. */
22505de96e33SMatt Macy 
2251f5f9340bSFabien Thomas 		td->td_pflags &= ~TDP_CALLCHAIN;
2252f5f9340bSFabien Thomas 		break;
2253f5f9340bSFabien Thomas 
2254f5f9340bSFabien Thomas 	case PMC_FN_SOFT_SAMPLING:
2255f5f9340bSFabien Thomas 		/*
2256f5f9340bSFabien Thomas 		 * Call soft PMC sampling intr.
2257f5f9340bSFabien Thomas 		 */
2258f5f9340bSFabien Thomas 		pmc_soft_intr((struct pmckern_soft *)arg);
2259f5f9340bSFabien Thomas 		break;
2260f5f9340bSFabien Thomas 
22616161b98cSMatt Macy 	case PMC_FN_THR_CREATE:
22626161b98cSMatt Macy 		pmc_process_thread_add(td);
2263ebfaf69cSMatt Macy 		pmc_process_threadcreate(td);
2264ebfaf69cSMatt Macy 		break;
2265ebfaf69cSMatt Macy 
2266ebfaf69cSMatt Macy 	case PMC_FN_THR_CREATE_LOG:
2267ebfaf69cSMatt Macy 		pmc_process_threadcreate(td);
22686161b98cSMatt Macy 		break;
22696161b98cSMatt Macy 
22706161b98cSMatt Macy 	case PMC_FN_THR_EXIT:
22716161b98cSMatt Macy 		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
22726161b98cSMatt Macy 		    __LINE__));
22736161b98cSMatt Macy 		pmc_process_thread_delete(td);
2274ebfaf69cSMatt Macy 		pmc_process_threadexit(td);
22756161b98cSMatt Macy 		break;
2276ebfaf69cSMatt Macy 	case PMC_FN_THR_EXIT_LOG:
2277ebfaf69cSMatt Macy 		pmc_process_threadexit(td);
2278ebfaf69cSMatt Macy 		break;
22795de96e33SMatt Macy 	case PMC_FN_THR_USERRET:
22805de96e33SMatt Macy 		KASSERT(td == curthread, ("[pmc,%d] td != curthread",
22815de96e33SMatt Macy 		    __LINE__));
22825de96e33SMatt Macy 		pmc_process_thread_userret(td);
22835de96e33SMatt Macy 		break;
2284ebccf1e3SJoseph Koshy 	default:
2285680f1afdSJohn Baldwin #ifdef HWPMC_DEBUG
2286ebccf1e3SJoseph Koshy 		KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
2287ebccf1e3SJoseph Koshy #endif
2288ebccf1e3SJoseph Koshy 		break;
2289ebccf1e3SJoseph Koshy 	}
2290ebccf1e3SJoseph Koshy 
229152ebac7fSMitchell Horne 	return (0);
2292ebccf1e3SJoseph Koshy }
2293ebccf1e3SJoseph Koshy 
2294ebccf1e3SJoseph Koshy /*
229501c35b67SMitchell Horne  * Allocate a 'struct pmc_owner' descriptor in the owner hash table.
2296ebccf1e3SJoseph Koshy  */
2297ebccf1e3SJoseph Koshy static struct pmc_owner *
2298ebccf1e3SJoseph Koshy pmc_allocate_owner_descriptor(struct proc *p)
2299ebccf1e3SJoseph Koshy {
2300ebccf1e3SJoseph Koshy 	struct pmc_owner *po;
2301ebccf1e3SJoseph Koshy 	struct pmc_ownerhash *poh;
230201c35b67SMitchell Horne 	uint32_t hindex;
2303ebccf1e3SJoseph Koshy 
2304ebccf1e3SJoseph Koshy 	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2305ebccf1e3SJoseph Koshy 	poh = &pmc_ownerhash[hindex];
2306ebccf1e3SJoseph Koshy 
230701c35b67SMitchell Horne 	/* Allocate space for N pointers and one descriptor struct. */
2308e829eb6dSJoseph Koshy 	po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK | M_ZERO);
2309ebccf1e3SJoseph Koshy 	po->po_owner = p;
2310ebccf1e3SJoseph Koshy 	LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
2311ebccf1e3SJoseph Koshy 
2312f263522aSJoseph Koshy 	TAILQ_INIT(&po->po_logbuffers);
2313382d30cdSJoseph Koshy 	mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
2314f263522aSJoseph Koshy 
23154a3690dfSJohn Baldwin 	PMCDBG4(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
2316ebccf1e3SJoseph Koshy 	    p, p->p_pid, p->p_comm, po);
2317ebccf1e3SJoseph Koshy 
231852ebac7fSMitchell Horne 	return (po);
2319ebccf1e3SJoseph Koshy }
2320ebccf1e3SJoseph Koshy 
2321f263522aSJoseph Koshy static void
2322f263522aSJoseph Koshy pmc_destroy_owner_descriptor(struct pmc_owner *po)
2323f263522aSJoseph Koshy {
2324f263522aSJoseph Koshy 
23254a3690dfSJohn Baldwin 	PMCDBG4(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
2326f263522aSJoseph Koshy 	    po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
2327f263522aSJoseph Koshy 
2328f263522aSJoseph Koshy 	mtx_destroy(&po->po_mtx);
23291ede983cSDag-Erling Smørgrav 	free(po, M_PMC);
2330f263522aSJoseph Koshy }
2331f263522aSJoseph Koshy 
2332ebccf1e3SJoseph Koshy /*
23336161b98cSMatt Macy  * Allocate a thread descriptor from the free pool.
23346161b98cSMatt Macy  *
23356161b98cSMatt Macy  * NOTE: This *can* return NULL.
23366161b98cSMatt Macy  */
23376161b98cSMatt Macy static struct pmc_thread *
23386161b98cSMatt Macy pmc_thread_descriptor_pool_alloc(void)
23396161b98cSMatt Macy {
23406161b98cSMatt Macy 	struct pmc_thread *pt;
23416161b98cSMatt Macy 
23426161b98cSMatt Macy 	mtx_lock_spin(&pmc_threadfreelist_mtx);
23436161b98cSMatt Macy 	if ((pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
23446161b98cSMatt Macy 		LIST_REMOVE(pt, pt_next);
23456161b98cSMatt Macy 		pmc_threadfreelist_entries--;
23466161b98cSMatt Macy 	}
23476161b98cSMatt Macy 	mtx_unlock_spin(&pmc_threadfreelist_mtx);
23486161b98cSMatt Macy 
23496161b98cSMatt Macy 	return (pt);
23506161b98cSMatt Macy }
23516161b98cSMatt Macy 
23526161b98cSMatt Macy /*
23536161b98cSMatt Macy  * Add a thread descriptor to the free pool. We use this instead of free()
23546161b98cSMatt Macy  * to maintain a cache of free entries. Additionally, we can safely call
23556161b98cSMatt Macy  * this function when we cannot call free(), such as in a critical section.
23566161b98cSMatt Macy  */
23576161b98cSMatt Macy static void
23586161b98cSMatt Macy pmc_thread_descriptor_pool_free(struct pmc_thread *pt)
23596161b98cSMatt Macy {
23606161b98cSMatt Macy 
23616161b98cSMatt Macy 	if (pt == NULL)
23626161b98cSMatt Macy 		return;
23636161b98cSMatt Macy 
23646161b98cSMatt Macy 	memset(pt, 0, THREADENTRY_SIZE);
23656161b98cSMatt Macy 	mtx_lock_spin(&pmc_threadfreelist_mtx);
23666161b98cSMatt Macy 	LIST_INSERT_HEAD(&pmc_threadfreelist, pt, pt_next);
23676161b98cSMatt Macy 	pmc_threadfreelist_entries++;
23686161b98cSMatt Macy 	if (pmc_threadfreelist_entries > pmc_threadfreelist_max)
23699b1d850bSMark Johnston 		taskqueue_enqueue(taskqueue_fast, &free_task);
23706161b98cSMatt Macy 	mtx_unlock_spin(&pmc_threadfreelist_mtx);
23716161b98cSMatt Macy }
23726161b98cSMatt Macy 
23736161b98cSMatt Macy /*
23749b1d850bSMark Johnston  * An asynchronous task to manage the free list.
23756161b98cSMatt Macy  */
23766161b98cSMatt Macy static void
23779b1d850bSMark Johnston pmc_thread_descriptor_pool_free_task(void *arg __unused, int pending __unused)
23786161b98cSMatt Macy {
23796161b98cSMatt Macy 	struct pmc_thread *pt;
23806161b98cSMatt Macy 	LIST_HEAD(, pmc_thread) tmplist;
23816161b98cSMatt Macy 	int delta;
23826161b98cSMatt Macy 
23836161b98cSMatt Macy 	LIST_INIT(&tmplist);
23849893ab3fSMark Johnston 
23856161b98cSMatt Macy 	/* Determine what changes, if any, we need to make. */
23866161b98cSMatt Macy 	mtx_lock_spin(&pmc_threadfreelist_mtx);
23876161b98cSMatt Macy 	delta = pmc_threadfreelist_entries - pmc_threadfreelist_max;
23889893ab3fSMark Johnston 	while (delta > 0 && (pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
23893de22849SMatt Macy 		delta--;
23909893ab3fSMark Johnston 		pmc_threadfreelist_entries--;
23916161b98cSMatt Macy 		LIST_REMOVE(pt, pt_next);
23926161b98cSMatt Macy 		LIST_INSERT_HEAD(&tmplist, pt, pt_next);
23936161b98cSMatt Macy 	}
23946161b98cSMatt Macy 	mtx_unlock_spin(&pmc_threadfreelist_mtx);
23956161b98cSMatt Macy 
23966161b98cSMatt Macy 	/* If there are entries to free, free them. */
23976161b98cSMatt Macy 	while (!LIST_EMPTY(&tmplist)) {
23983de22849SMatt Macy 		pt = LIST_FIRST(&tmplist);
23996161b98cSMatt Macy 		LIST_REMOVE(pt, pt_next);
24006161b98cSMatt Macy 		free(pt, M_PMC);
24016161b98cSMatt Macy 	}
24026161b98cSMatt Macy }
24036161b98cSMatt Macy 
24046161b98cSMatt Macy /*
24056161b98cSMatt Macy  * Drain the thread free pool, freeing all allocations.
24066161b98cSMatt Macy  */
24076161b98cSMatt Macy static void
2408555d2c93SDimitry Andric pmc_thread_descriptor_pool_drain(void)
24096161b98cSMatt Macy {
24106161b98cSMatt Macy 	struct pmc_thread *pt, *next;
24116161b98cSMatt Macy 
24126161b98cSMatt Macy 	LIST_FOREACH_SAFE(pt, &pmc_threadfreelist, pt_next, next) {
24136161b98cSMatt Macy 		LIST_REMOVE(pt, pt_next);
24146161b98cSMatt Macy 		free(pt, M_PMC);
24156161b98cSMatt Macy 	}
24166161b98cSMatt Macy }
24176161b98cSMatt Macy 
24186161b98cSMatt Macy /*
24196161b98cSMatt Macy  * find the descriptor corresponding to thread 'td', adding or removing it
24206161b98cSMatt Macy  * as specified by 'mode'.
24216161b98cSMatt Macy  *
24226161b98cSMatt Macy  * Note that this supports additional mode flags in addition to those
24236161b98cSMatt Macy  * supported by pmc_find_process_descriptor():
24246161b98cSMatt Macy  * PMC_FLAG_NOWAIT: Causes the function to not wait for mallocs.
24256161b98cSMatt Macy  *     This makes it safe to call while holding certain other locks.
24266161b98cSMatt Macy  */
24276161b98cSMatt Macy static struct pmc_thread *
24286161b98cSMatt Macy pmc_find_thread_descriptor(struct pmc_process *pp, struct thread *td,
24296161b98cSMatt Macy     uint32_t mode)
24306161b98cSMatt Macy {
24316161b98cSMatt Macy 	struct pmc_thread *pt = NULL, *ptnew = NULL;
24326161b98cSMatt Macy 	int wait_flag;
24336161b98cSMatt Macy 
24346161b98cSMatt Macy 	KASSERT(td != NULL, ("[pmc,%d] called to add NULL td", __LINE__));
24356161b98cSMatt Macy 
24366161b98cSMatt Macy 	/*
24376161b98cSMatt Macy 	 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case prior to
24386161b98cSMatt Macy 	 * acquiring the lock.
24396161b98cSMatt Macy 	 */
2440d5ee4074SMitchell Horne 	if ((mode & PMC_FLAG_ALLOCATE) != 0) {
24416161b98cSMatt Macy 		if ((ptnew = pmc_thread_descriptor_pool_alloc()) == NULL) {
244239446ce5SMatt Macy 			wait_flag = M_WAITOK;
2443693cd307SMitchell Horne 			if ((mode & PMC_FLAG_NOWAIT) != 0 ||
2444693cd307SMitchell Horne 			    in_epoch(global_epoch_preempt))
244539446ce5SMatt Macy 				wait_flag = M_NOWAIT;
244639446ce5SMatt Macy 
24476161b98cSMatt Macy 			ptnew = malloc(THREADENTRY_SIZE, M_PMC,
24486161b98cSMatt Macy 			    wait_flag | M_ZERO);
24496161b98cSMatt Macy 		}
24506161b98cSMatt Macy 	}
24516161b98cSMatt Macy 
24526161b98cSMatt Macy 	mtx_lock_spin(pp->pp_tdslock);
2453d5ee4074SMitchell Horne 	LIST_FOREACH(pt, &pp->pp_tds, pt_next) {
24546161b98cSMatt Macy 		if (pt->pt_td == td)
24556161b98cSMatt Macy 			break;
2456d5ee4074SMitchell Horne 	}
24576161b98cSMatt Macy 
2458d5ee4074SMitchell Horne 	if ((mode & PMC_FLAG_REMOVE) != 0 && pt != NULL)
24596161b98cSMatt Macy 		LIST_REMOVE(pt, pt_next);
24606161b98cSMatt Macy 
2461d5ee4074SMitchell Horne 	if ((mode & PMC_FLAG_ALLOCATE) != 0 && pt == NULL && ptnew != NULL) {
24626161b98cSMatt Macy 		pt = ptnew;
24636161b98cSMatt Macy 		ptnew = NULL;
24646161b98cSMatt Macy 		pt->pt_td = td;
24656161b98cSMatt Macy 		LIST_INSERT_HEAD(&pp->pp_tds, pt, pt_next);
24666161b98cSMatt Macy 	}
24676161b98cSMatt Macy 
24686161b98cSMatt Macy 	mtx_unlock_spin(pp->pp_tdslock);
24696161b98cSMatt Macy 
24706161b98cSMatt Macy 	if (ptnew != NULL) {
24716161b98cSMatt Macy 		free(ptnew, M_PMC);
24726161b98cSMatt Macy 	}
24736161b98cSMatt Macy 
247452ebac7fSMitchell Horne 	return (pt);
24756161b98cSMatt Macy }
24766161b98cSMatt Macy 
24776161b98cSMatt Macy /*
24786161b98cSMatt Macy  * Try to add thread descriptors for each thread in a process.
24796161b98cSMatt Macy  */
24806161b98cSMatt Macy static void
24816161b98cSMatt Macy pmc_add_thread_descriptors_from_proc(struct proc *p, struct pmc_process *pp)
24826161b98cSMatt Macy {
24836161b98cSMatt Macy 	struct pmc_thread **tdlist;
248401c35b67SMitchell Horne 	struct thread *curtd;
24856161b98cSMatt Macy 	int i, tdcnt, tdlistsz;
24866161b98cSMatt Macy 
24876161b98cSMatt Macy 	KASSERT(!PROC_LOCKED(p), ("[pmc,%d] proc unexpectedly locked",
24886161b98cSMatt Macy 	    __LINE__));
24896161b98cSMatt Macy 	tdcnt = 32;
24906161b98cSMatt Macy restart:
24916161b98cSMatt Macy 	tdlistsz = roundup2(tdcnt, 32);
24926161b98cSMatt Macy 
24936161b98cSMatt Macy 	tdcnt = 0;
2494693cd307SMitchell Horne 	tdlist = malloc(sizeof(struct pmc_thread *) * tdlistsz, M_TEMP,
2495693cd307SMitchell Horne 	    M_WAITOK);
24966161b98cSMatt Macy 
24976161b98cSMatt Macy 	PROC_LOCK(p);
24986161b98cSMatt Macy 	FOREACH_THREAD_IN_PROC(p, curtd)
24996161b98cSMatt Macy 		tdcnt++;
25006161b98cSMatt Macy 	if (tdcnt >= tdlistsz) {
25016161b98cSMatt Macy 		PROC_UNLOCK(p);
25026161b98cSMatt Macy 		free(tdlist, M_TEMP);
25036161b98cSMatt Macy 		goto restart;
25046161b98cSMatt Macy 	}
2505693cd307SMitchell Horne 
25066161b98cSMatt Macy 	/*
25076161b98cSMatt Macy 	 * Try to add each thread to the list without sleeping. If unable,
25086161b98cSMatt Macy 	 * add to a queue to retry after dropping the process lock.
25096161b98cSMatt Macy 	 */
25106161b98cSMatt Macy 	tdcnt = 0;
25116161b98cSMatt Macy 	FOREACH_THREAD_IN_PROC(p, curtd) {
25126161b98cSMatt Macy 		tdlist[tdcnt] = pmc_find_thread_descriptor(pp, curtd,
25136161b98cSMatt Macy 		    PMC_FLAG_ALLOCATE | PMC_FLAG_NOWAIT);
25146161b98cSMatt Macy 		if (tdlist[tdcnt] == NULL) {
25156161b98cSMatt Macy 			PROC_UNLOCK(p);
25166161b98cSMatt Macy 			for (i = 0; i <= tdcnt; i++)
25176161b98cSMatt Macy 				pmc_thread_descriptor_pool_free(tdlist[i]);
25186161b98cSMatt Macy 			free(tdlist, M_TEMP);
25196161b98cSMatt Macy 			goto restart;
25206161b98cSMatt Macy 		}
25216161b98cSMatt Macy 		tdcnt++;
25226161b98cSMatt Macy 	}
25236161b98cSMatt Macy 	PROC_UNLOCK(p);
25246161b98cSMatt Macy 	free(tdlist, M_TEMP);
25256161b98cSMatt Macy }
25266161b98cSMatt Macy 
25276161b98cSMatt Macy /*
252801c35b67SMitchell Horne  * Find the descriptor corresponding to process 'p', adding or removing it
2529ebccf1e3SJoseph Koshy  * as specified by 'mode'.
2530ebccf1e3SJoseph Koshy  */
2531ebccf1e3SJoseph Koshy static struct pmc_process *
2532ebccf1e3SJoseph Koshy pmc_find_process_descriptor(struct proc *p, uint32_t mode)
2533ebccf1e3SJoseph Koshy {
2534ebccf1e3SJoseph Koshy 	struct pmc_process *pp, *ppnew;
2535ebccf1e3SJoseph Koshy 	struct pmc_processhash *pph;
253601c35b67SMitchell Horne 	uint32_t hindex;
2537ebccf1e3SJoseph Koshy 
2538ebccf1e3SJoseph Koshy 	hindex = PMC_HASH_PTR(p, pmc_processhashmask);
2539ebccf1e3SJoseph Koshy 	pph = &pmc_processhash[hindex];
2540ebccf1e3SJoseph Koshy 
2541ebccf1e3SJoseph Koshy 	ppnew = NULL;
2542ebccf1e3SJoseph Koshy 
2543ebccf1e3SJoseph Koshy 	/*
25446161b98cSMatt Macy 	 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case since we
2545ebccf1e3SJoseph Koshy 	 * cannot call malloc(9) once we hold a spin lock.
2546ebccf1e3SJoseph Koshy 	 */
2547d5ee4074SMitchell Horne 	if ((mode & PMC_FLAG_ALLOCATE) != 0)
25481ede983cSDag-Erling Smørgrav 		ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
2549e829eb6dSJoseph Koshy 		    sizeof(struct pmc_targetstate), M_PMC, M_WAITOK | M_ZERO);
2550ebccf1e3SJoseph Koshy 
2551ebccf1e3SJoseph Koshy 	mtx_lock_spin(&pmc_processhash_mtx);
2552d5ee4074SMitchell Horne 	LIST_FOREACH(pp, pph, pp_next) {
2553ebccf1e3SJoseph Koshy 		if (pp->pp_proc == p)
2554ebccf1e3SJoseph Koshy 			break;
2555d5ee4074SMitchell Horne 	}
2556ebccf1e3SJoseph Koshy 
2557d5ee4074SMitchell Horne 	if ((mode & PMC_FLAG_REMOVE) != 0 && pp != NULL)
2558ebccf1e3SJoseph Koshy 		LIST_REMOVE(pp, pp_next);
2559ebccf1e3SJoseph Koshy 
2560d5ee4074SMitchell Horne 	if ((mode & PMC_FLAG_ALLOCATE) != 0 && pp == NULL && ppnew != NULL) {
2561ebccf1e3SJoseph Koshy 		ppnew->pp_proc = p;
25626161b98cSMatt Macy 		LIST_INIT(&ppnew->pp_tds);
25636161b98cSMatt Macy 		ppnew->pp_tdslock = mtx_pool_find(pmc_mtxpool, ppnew);
2564ebccf1e3SJoseph Koshy 		LIST_INSERT_HEAD(pph, ppnew, pp_next);
25656161b98cSMatt Macy 		mtx_unlock_spin(&pmc_processhash_mtx);
2566ebccf1e3SJoseph Koshy 		pp = ppnew;
2567ebccf1e3SJoseph Koshy 		ppnew = NULL;
25686161b98cSMatt Macy 
25696161b98cSMatt Macy 		/* Add thread descriptors for this process' current threads. */
25706161b98cSMatt Macy 		pmc_add_thread_descriptors_from_proc(p, pp);
2571693cd307SMitchell Horne 	} else
2572ebccf1e3SJoseph Koshy 		mtx_unlock_spin(&pmc_processhash_mtx);
2573ebccf1e3SJoseph Koshy 
25746161b98cSMatt Macy 	if (ppnew != NULL)
25751ede983cSDag-Erling Smørgrav 		free(ppnew, M_PMC);
257652ebac7fSMitchell Horne 	return (pp);
2577ebccf1e3SJoseph Koshy }
2578ebccf1e3SJoseph Koshy 
2579ebccf1e3SJoseph Koshy /*
258001c35b67SMitchell Horne  * Remove a process descriptor from the process hash table.
2581ebccf1e3SJoseph Koshy  */
2582ebccf1e3SJoseph Koshy static void
2583ebccf1e3SJoseph Koshy pmc_remove_process_descriptor(struct pmc_process *pp)
2584ebccf1e3SJoseph Koshy {
2585ebccf1e3SJoseph Koshy 	KASSERT(pp->pp_refcnt == 0,
2586ebccf1e3SJoseph Koshy 	    ("[pmc,%d] Removing process descriptor %p with count %d",
2587ebccf1e3SJoseph Koshy 	     __LINE__, pp, pp->pp_refcnt));
2588ebccf1e3SJoseph Koshy 
2589ebccf1e3SJoseph Koshy 	mtx_lock_spin(&pmc_processhash_mtx);
2590ebccf1e3SJoseph Koshy 	LIST_REMOVE(pp, pp_next);
2591ebccf1e3SJoseph Koshy 	mtx_unlock_spin(&pmc_processhash_mtx);
2592ebccf1e3SJoseph Koshy }
2593ebccf1e3SJoseph Koshy 
25946161b98cSMatt Macy /*
259501c35b67SMitchell Horne  * Destroy a process descriptor.
25966161b98cSMatt Macy  */
25976161b98cSMatt Macy static void
25986161b98cSMatt Macy pmc_destroy_process_descriptor(struct pmc_process *pp)
25996161b98cSMatt Macy {
26006161b98cSMatt Macy 	struct pmc_thread *pmc_td;
26016161b98cSMatt Macy 
26026161b98cSMatt Macy 	while ((pmc_td = LIST_FIRST(&pp->pp_tds)) != NULL) {
26036161b98cSMatt Macy 		LIST_REMOVE(pmc_td, pt_next);
26046161b98cSMatt Macy 		pmc_thread_descriptor_pool_free(pmc_td);
26056161b98cSMatt Macy 	}
26066161b98cSMatt Macy 	free(pp, M_PMC);
26076161b98cSMatt Macy }
26086161b98cSMatt Macy 
2609ebccf1e3SJoseph Koshy /*
261001c35b67SMitchell Horne  * Find an owner descriptor corresponding to proc 'p'.
2611ebccf1e3SJoseph Koshy  */
2612ebccf1e3SJoseph Koshy static struct pmc_owner *
2613ebccf1e3SJoseph Koshy pmc_find_owner_descriptor(struct proc *p)
2614ebccf1e3SJoseph Koshy {
2615ebccf1e3SJoseph Koshy 	struct pmc_owner *po;
2616ebccf1e3SJoseph Koshy 	struct pmc_ownerhash *poh;
261701c35b67SMitchell Horne 	uint32_t hindex;
2618ebccf1e3SJoseph Koshy 
2619ebccf1e3SJoseph Koshy 	hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2620ebccf1e3SJoseph Koshy 	poh = &pmc_ownerhash[hindex];
2621ebccf1e3SJoseph Koshy 
2622ebccf1e3SJoseph Koshy 	po = NULL;
2623d5ee4074SMitchell Horne 	LIST_FOREACH(po, poh, po_next) {
2624ebccf1e3SJoseph Koshy 		if (po->po_owner == p)
2625ebccf1e3SJoseph Koshy 			break;
2626d5ee4074SMitchell Horne 	}
2627ebccf1e3SJoseph Koshy 
26284a3690dfSJohn Baldwin 	PMCDBG5(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2629ebccf1e3SJoseph Koshy 	    "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2630ebccf1e3SJoseph Koshy 
263152ebac7fSMitchell Horne 	return (po);
2632ebccf1e3SJoseph Koshy }
2633ebccf1e3SJoseph Koshy 
2634ebccf1e3SJoseph Koshy /*
263501c35b67SMitchell Horne  * Allocate a pmc descriptor and initialize its fields.
2636ebccf1e3SJoseph Koshy  */
2637ebccf1e3SJoseph Koshy static struct pmc *
2638ebccf1e3SJoseph Koshy pmc_allocate_pmc_descriptor(void)
2639ebccf1e3SJoseph Koshy {
2640ebccf1e3SJoseph Koshy 	struct pmc *pmc;
2641ebccf1e3SJoseph Koshy 
2642e829eb6dSJoseph Koshy 	pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK | M_ZERO);
2643e6b475e0SMatt Macy 	pmc->pm_runcount = counter_u64_alloc(M_WAITOK);
2644693cd307SMitchell Horne 	pmc->pm_pcpu_state = malloc(sizeof(struct pmc_pcpu_state) * mp_ncpus,
2645693cd307SMitchell Horne 	    M_PMC, M_WAITOK | M_ZERO);
26464a3690dfSJohn Baldwin 	PMCDBG1(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2647ebccf1e3SJoseph Koshy 
264852ebac7fSMitchell Horne 	return (pmc);
2649ebccf1e3SJoseph Koshy }
2650ebccf1e3SJoseph Koshy 
2651ebccf1e3SJoseph Koshy /*
2652ebccf1e3SJoseph Koshy  * Destroy a pmc descriptor.
2653ebccf1e3SJoseph Koshy  */
2654ebccf1e3SJoseph Koshy static void
2655ebccf1e3SJoseph Koshy pmc_destroy_pmc_descriptor(struct pmc *pm)
2656ebccf1e3SJoseph Koshy {
2657ebccf1e3SJoseph Koshy 
2658ebccf1e3SJoseph Koshy 	KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2659ebccf1e3SJoseph Koshy 	    pm->pm_state == PMC_STATE_FREE,
2660ebccf1e3SJoseph Koshy 	    ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2661ebccf1e3SJoseph Koshy 	KASSERT(LIST_EMPTY(&pm->pm_targets),
2662ebccf1e3SJoseph Koshy 	    ("[pmc,%d] destroying pmc with targets", __LINE__));
2663ebccf1e3SJoseph Koshy 	KASSERT(pm->pm_owner == NULL,
2664ebccf1e3SJoseph Koshy 	    ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2665e6b475e0SMatt Macy 	KASSERT(counter_u64_fetch(pm->pm_runcount) == 0,
266601c35b67SMitchell Horne 	    ("[pmc,%d] pmc has non-zero run count %ju", __LINE__,
266701c35b67SMitchell Horne 	    (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
266806796b67SMark Johnston 
2669e6b475e0SMatt Macy 	counter_u64_free(pm->pm_runcount);
2670e6b475e0SMatt Macy 	free(pm->pm_pcpu_state, M_PMC);
267106796b67SMark Johnston 	free(pm, M_PMC);
2672ebccf1e3SJoseph Koshy }
2673ebccf1e3SJoseph Koshy 
2674f263522aSJoseph Koshy static void
2675f263522aSJoseph Koshy pmc_wait_for_pmc_idle(struct pmc *pm)
2676f263522aSJoseph Koshy {
2677d9f1b8dbSMatt Macy #ifdef INVARIANTS
2678f263522aSJoseph Koshy 	volatile int maxloop;
2679f263522aSJoseph Koshy 
2680122ccdc1SJoseph Koshy 	maxloop = 100 * pmc_cpu_max();
2681f263522aSJoseph Koshy #endif
2682f263522aSJoseph Koshy 	/*
2683f263522aSJoseph Koshy 	 * Loop (with a forced context switch) till the PMC's runcount
2684f263522aSJoseph Koshy 	 * comes down to zero.
2685f263522aSJoseph Koshy 	 */
2686ebfaf69cSMatt Macy 	pmclog_flush(pm->pm_owner, 1);
2687e6b475e0SMatt Macy 	while (counter_u64_fetch(pm->pm_runcount) > 0) {
2688ebfaf69cSMatt Macy 		pmclog_flush(pm->pm_owner, 1);
2689d9f1b8dbSMatt Macy #ifdef INVARIANTS
2690f263522aSJoseph Koshy 		maxloop--;
2691f263522aSJoseph Koshy 		KASSERT(maxloop > 0,
269201c35b67SMitchell Horne 		    ("[pmc,%d] (ri%d, rc%ju) waiting too long for "
269301c35b67SMitchell Horne 		     "pmc to be free", __LINE__, PMC_TO_ROWINDEX(pm),
269401c35b67SMitchell Horne 		     (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
2695f263522aSJoseph Koshy #endif
2696f263522aSJoseph Koshy 		pmc_force_context_switch();
2697f263522aSJoseph Koshy 	}
2698f263522aSJoseph Koshy }
2699f263522aSJoseph Koshy 
2700ebccf1e3SJoseph Koshy /*
2701ebccf1e3SJoseph Koshy  * This function does the following things:
2702ebccf1e3SJoseph Koshy  *
2703ebccf1e3SJoseph Koshy  *  - detaches the PMC from hardware
2704ebccf1e3SJoseph Koshy  *  - unlinks all target threads that were attached to it
2705ebccf1e3SJoseph Koshy  *  - removes the PMC from its owner's list
270606796b67SMark Johnston  *  - destroys the PMC private mutex
2707ebccf1e3SJoseph Koshy  *
270806796b67SMark Johnston  * Once this function completes, the given pmc pointer can be freed by
270906796b67SMark Johnston  * calling pmc_destroy_pmc_descriptor().
2710ebccf1e3SJoseph Koshy  */
2711ebccf1e3SJoseph Koshy static void
2712ebccf1e3SJoseph Koshy pmc_release_pmc_descriptor(struct pmc *pm)
2713ebccf1e3SJoseph Koshy {
2714ebccf1e3SJoseph Koshy 	struct pmc_binding pb;
2715e829eb6dSJoseph Koshy 	struct pmc_classdep *pcd;
271601c35b67SMitchell Horne 	struct pmc_hw *phw __diagused;
271701c35b67SMitchell Horne 	struct pmc_owner *po;
271801c35b67SMitchell Horne 	struct pmc_process *pp;
2719e829eb6dSJoseph Koshy 	struct pmc_target *ptgt, *tmp;
272001c35b67SMitchell Horne 	enum pmc_mode mode;
272101c35b67SMitchell Horne 	u_int adjri, ri, cpu;
2722ebccf1e3SJoseph Koshy 
2723ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
2724ebccf1e3SJoseph Koshy 	KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2725ebccf1e3SJoseph Koshy 
2726c5153e19SJoseph Koshy 	ri   = PMC_TO_ROWINDEX(pm);
2727e829eb6dSJoseph Koshy 	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
2728c5153e19SJoseph Koshy 	mode = PMC_TO_MODE(pm);
2729ebccf1e3SJoseph Koshy 
27304a3690dfSJohn Baldwin 	PMCDBG3(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2731c5153e19SJoseph Koshy 	    mode);
2732ebccf1e3SJoseph Koshy 
2733ebccf1e3SJoseph Koshy 	/*
2734ebccf1e3SJoseph Koshy 	 * First, we take the PMC off hardware.
2735ebccf1e3SJoseph Koshy 	 */
2736869f4a8bSWarner Losh 	cpu = 0;
2737c5153e19SJoseph Koshy 	if (PMC_IS_SYSTEM_MODE(mode)) {
2738ebccf1e3SJoseph Koshy 		/*
2739ebccf1e3SJoseph Koshy 		 * A system mode PMC runs on a specific CPU. Switch
2740ebccf1e3SJoseph Koshy 		 * to this CPU and turn hardware off.
2741ebccf1e3SJoseph Koshy 		 */
2742ebccf1e3SJoseph Koshy 		pmc_save_cpu_binding(&pb);
2743c5153e19SJoseph Koshy 		cpu = PMC_TO_CPU(pm);
2744ebccf1e3SJoseph Koshy 		pmc_select_cpu(cpu);
2745ebccf1e3SJoseph Koshy 
2746f263522aSJoseph Koshy 		/* switch off non-stalled CPUs */
2747e6b475e0SMatt Macy 		pm->pm_pcpu_state[cpu].pps_cpustate = 0;
2748f263522aSJoseph Koshy 		if (pm->pm_state == PMC_STATE_RUNNING &&
2749e6b475e0SMatt Macy 			pm->pm_pcpu_state[cpu].pps_stalled == 0) {
2750f263522aSJoseph Koshy 
2751ebccf1e3SJoseph Koshy 			phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2752ebccf1e3SJoseph Koshy 
2753ebccf1e3SJoseph Koshy 			KASSERT(phw->phw_pmc == pm,
2754ebccf1e3SJoseph Koshy 			    ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2755ebccf1e3SJoseph Koshy 				__LINE__, ri, phw->phw_pmc, pm));
27564a3690dfSJohn Baldwin 			PMCDBG2(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2757ebccf1e3SJoseph Koshy 
2758ebccf1e3SJoseph Koshy 			critical_enter();
275901c35b67SMitchell Horne 			(void)pcd->pcd_stop_pmc(cpu, adjri, pm);
2760ebccf1e3SJoseph Koshy 			critical_exit();
2761ebccf1e3SJoseph Koshy 		}
2762ebccf1e3SJoseph Koshy 
27634a3690dfSJohn Baldwin 		PMCDBG2(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2764ebccf1e3SJoseph Koshy 
2765ebccf1e3SJoseph Koshy 		critical_enter();
276601c35b67SMitchell Horne 		(void)pcd->pcd_config_pmc(cpu, adjri, NULL);
2767ebccf1e3SJoseph Koshy 		critical_exit();
2768ebccf1e3SJoseph Koshy 
2769f263522aSJoseph Koshy 		/* adjust the global and process count of SS mode PMCs */
2770f263522aSJoseph Koshy 		if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2771f263522aSJoseph Koshy 			po = pm->pm_owner;
2772f263522aSJoseph Koshy 			po->po_sscount--;
2773f263522aSJoseph Koshy 			if (po->po_sscount == 0) {
2774f263522aSJoseph Koshy 				atomic_subtract_rel_int(&pmc_ss_count, 1);
27750f00315cSMatt Macy 				CK_LIST_REMOVE(po, po_ssnext);
277670398c2fSMatt Macy 				epoch_wait_preempt(global_epoch_preempt);
2777f263522aSJoseph Koshy 			}
2778f263522aSJoseph Koshy 		}
2779ebccf1e3SJoseph Koshy 		pm->pm_state = PMC_STATE_DELETED;
2780ebccf1e3SJoseph Koshy 
2781ebccf1e3SJoseph Koshy 		pmc_restore_cpu_binding(&pb);
2782ebccf1e3SJoseph Koshy 
2783f263522aSJoseph Koshy 		/*
278401c35b67SMitchell Horne 		 * We could have references to this PMC structure in the
278501c35b67SMitchell Horne 		 * per-cpu sample queues.  Wait for the queue to drain.
2786f263522aSJoseph Koshy 		 */
2787f263522aSJoseph Koshy 		pmc_wait_for_pmc_idle(pm);
2788f263522aSJoseph Koshy 
2789c5153e19SJoseph Koshy 	} else if (PMC_IS_VIRTUAL_MODE(mode)) {
2790ebccf1e3SJoseph Koshy 		/*
279101c35b67SMitchell Horne 		 * A virtual PMC could be running on multiple CPUs at a given
279201c35b67SMitchell Horne 		 * instant.
2793ebccf1e3SJoseph Koshy 		 *
279401c35b67SMitchell Horne 		 * By marking its state as DELETED, we ensure that this PMC is
279501c35b67SMitchell Horne 		 * never further scheduled on hardware.
2796ebccf1e3SJoseph Koshy 		 *
2797ebccf1e3SJoseph Koshy 		 * Then we wait till all CPUs are done with this PMC.
2798ebccf1e3SJoseph Koshy 		 */
2799ebccf1e3SJoseph Koshy 		pm->pm_state = PMC_STATE_DELETED;
2800ebccf1e3SJoseph Koshy 
2801f263522aSJoseph Koshy 		/* Wait for the PMCs runcount to come to zero. */
2802f263522aSJoseph Koshy 		pmc_wait_for_pmc_idle(pm);
2803ebccf1e3SJoseph Koshy 
2804ebccf1e3SJoseph Koshy 		/*
280501c35b67SMitchell Horne 		 * At this point the PMC is off all CPUs and cannot be freshly
280601c35b67SMitchell Horne 		 * scheduled onto a CPU. It is now safe to unlink all targets
280701c35b67SMitchell Horne 		 * from this PMC. If a process-record's refcount falls to zero,
280801c35b67SMitchell Horne 		 * we remove it from the hash table. The module-wide SX lock
2809ebccf1e3SJoseph Koshy 		 * protects us from races.
2810ebccf1e3SJoseph Koshy 		 */
2811ebccf1e3SJoseph Koshy 		LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2812ebccf1e3SJoseph Koshy 			pp = ptgt->pt_process;
2813ebccf1e3SJoseph Koshy 			pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2814ebccf1e3SJoseph Koshy 
28154a3690dfSJohn Baldwin 			PMCDBG1(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2816ebccf1e3SJoseph Koshy 
2817ebccf1e3SJoseph Koshy 			/*
281801c35b67SMitchell Horne 			 * If the target process record shows that no PMCs are
281901c35b67SMitchell Horne 			 * attached to it, reclaim its space.
2820ebccf1e3SJoseph Koshy 			 */
2821ebccf1e3SJoseph Koshy 			if (pp->pp_refcnt == 0) {
2822ebccf1e3SJoseph Koshy 				pmc_remove_process_descriptor(pp);
28236161b98cSMatt Macy 				pmc_destroy_process_descriptor(pp);
2824ebccf1e3SJoseph Koshy 			}
2825ebccf1e3SJoseph Koshy 		}
2826ebccf1e3SJoseph Koshy 
2827ebccf1e3SJoseph Koshy 		cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2828ebccf1e3SJoseph Koshy 	}
2829ebccf1e3SJoseph Koshy 
2830ebccf1e3SJoseph Koshy 	/*
283101c35b67SMitchell Horne 	 * Release any MD resources.
2832ebccf1e3SJoseph Koshy 	 */
2833e829eb6dSJoseph Koshy 	(void)pcd->pcd_release_pmc(cpu, adjri, pm);
2834ebccf1e3SJoseph Koshy 
2835ebccf1e3SJoseph Koshy 	/*
283601c35b67SMitchell Horne 	 * Update row disposition.
2837ebccf1e3SJoseph Koshy 	 */
2838c5153e19SJoseph Koshy 	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2839ebccf1e3SJoseph Koshy 		PMC_UNMARK_ROW_STANDALONE(ri);
2840ebccf1e3SJoseph Koshy 	else
2841ebccf1e3SJoseph Koshy 		PMC_UNMARK_ROW_THREAD(ri);
2842ebccf1e3SJoseph Koshy 
284301c35b67SMitchell Horne 	/* Unlink from the owner's list. */
2844d5ee4074SMitchell Horne 	if (pm->pm_owner != NULL) {
2845f263522aSJoseph Koshy 		LIST_REMOVE(pm, pm_next);
2846f263522aSJoseph Koshy 		pm->pm_owner = NULL;
2847f263522aSJoseph Koshy 	}
2848ebccf1e3SJoseph Koshy }
2849ebccf1e3SJoseph Koshy 
2850ebccf1e3SJoseph Koshy /*
2851ebccf1e3SJoseph Koshy  * Register an owner and a pmc.
2852ebccf1e3SJoseph Koshy  */
2853ebccf1e3SJoseph Koshy static int
2854ebccf1e3SJoseph Koshy pmc_register_owner(struct proc *p, struct pmc *pmc)
2855ebccf1e3SJoseph Koshy {
2856ebccf1e3SJoseph Koshy 	struct pmc_owner *po;
2857ebccf1e3SJoseph Koshy 
2858ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
2859ebccf1e3SJoseph Koshy 
2860d5ee4074SMitchell Horne 	if ((po = pmc_find_owner_descriptor(p)) == NULL) {
2861f263522aSJoseph Koshy 		if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
286252ebac7fSMitchell Horne 			return (ENOMEM);
2863d5ee4074SMitchell Horne 	}
2864ebccf1e3SJoseph Koshy 
2865ebccf1e3SJoseph Koshy 	KASSERT(pmc->pm_owner == NULL,
2866ebccf1e3SJoseph Koshy 	    ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2867ebccf1e3SJoseph Koshy 	pmc->pm_owner = po;
2868ebccf1e3SJoseph Koshy 
2869f263522aSJoseph Koshy 	LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2870ebccf1e3SJoseph Koshy 
2871ebccf1e3SJoseph Koshy 	PROC_LOCK(p);
2872ebccf1e3SJoseph Koshy 	p->p_flag |= P_HWPMC;
2873ebccf1e3SJoseph Koshy 	PROC_UNLOCK(p);
2874ebccf1e3SJoseph Koshy 
2875d5ee4074SMitchell Horne 	if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
2876f263522aSJoseph Koshy 		pmclog_process_pmcallocate(pmc);
2877f263522aSJoseph Koshy 
28784a3690dfSJohn Baldwin 	PMCDBG2(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2879f263522aSJoseph Koshy 	    po, pmc);
2880ebccf1e3SJoseph Koshy 
288152ebac7fSMitchell Horne 	return (0);
2882ebccf1e3SJoseph Koshy }
2883ebccf1e3SJoseph Koshy 
2884ebccf1e3SJoseph Koshy /*
2885ebccf1e3SJoseph Koshy  * Return the current row disposition:
2886ebccf1e3SJoseph Koshy  * == 0 => FREE
2887ebccf1e3SJoseph Koshy  *  > 0 => PROCESS MODE
2888ebccf1e3SJoseph Koshy  *  < 0 => SYSTEM MODE
2889ebccf1e3SJoseph Koshy  */
2890ebccf1e3SJoseph Koshy int
2891ebccf1e3SJoseph Koshy pmc_getrowdisp(int ri)
2892ebccf1e3SJoseph Koshy {
289352ebac7fSMitchell Horne 	return (pmc_pmcdisp[ri]);
2894ebccf1e3SJoseph Koshy }
2895ebccf1e3SJoseph Koshy 
2896ebccf1e3SJoseph Koshy /*
2897ebccf1e3SJoseph Koshy  * Check if a PMC at row index 'ri' can be allocated to the current
2898ebccf1e3SJoseph Koshy  * process.
2899ebccf1e3SJoseph Koshy  *
2900ebccf1e3SJoseph Koshy  * Allocation can fail if:
2901ebccf1e3SJoseph Koshy  *   - the current process is already being profiled by a PMC at index 'ri',
2902ebccf1e3SJoseph Koshy  *     attached to it via OP_PMCATTACH.
2903ebccf1e3SJoseph Koshy  *   - the current process has already allocated a PMC at index 'ri'
2904ebccf1e3SJoseph Koshy  *     via OP_ALLOCATE.
2905ebccf1e3SJoseph Koshy  */
2906c514a571SMitchell Horne static bool
2907c5153e19SJoseph Koshy pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2908ebccf1e3SJoseph Koshy {
2909c5153e19SJoseph Koshy 	struct pmc *pm;
2910ebccf1e3SJoseph Koshy 	struct pmc_owner *po;
2911ebccf1e3SJoseph Koshy 	struct pmc_process *pp;
291201c35b67SMitchell Horne 	enum pmc_mode mode;
2913ebccf1e3SJoseph Koshy 
29144a3690dfSJohn Baldwin 	PMCDBG5(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2915c5153e19SJoseph Koshy 	    "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2916ebccf1e3SJoseph Koshy 
2917c5153e19SJoseph Koshy 	/*
2918c5153e19SJoseph Koshy 	 * We shouldn't have already allocated a process-mode PMC at
2919c5153e19SJoseph Koshy 	 * row index 'ri'.
2920c5153e19SJoseph Koshy 	 *
2921c5153e19SJoseph Koshy 	 * We shouldn't have allocated a system-wide PMC on the same
2922c5153e19SJoseph Koshy 	 * CPU and same RI.
2923c5153e19SJoseph Koshy 	 */
2924d5ee4074SMitchell Horne 	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
2925f263522aSJoseph Koshy 		LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2926c5153e19SJoseph Koshy 			if (PMC_TO_ROWINDEX(pm) == ri) {
2927c5153e19SJoseph Koshy 				mode = PMC_TO_MODE(pm);
2928c5153e19SJoseph Koshy 				if (PMC_IS_VIRTUAL_MODE(mode))
2929c514a571SMitchell Horne 					return (false);
2930c5153e19SJoseph Koshy 				if (PMC_IS_SYSTEM_MODE(mode) &&
2931d5ee4074SMitchell Horne 				    PMC_TO_CPU(pm) == cpu)
2932c514a571SMitchell Horne 					return (false);
2933d5ee4074SMitchell Horne 			}
2934c5153e19SJoseph Koshy 		}
2935c5153e19SJoseph Koshy 	}
2936ebccf1e3SJoseph Koshy 
2937c5153e19SJoseph Koshy 	/*
2938c5153e19SJoseph Koshy 	 * We also shouldn't be the target of any PMC at this index
2939c5153e19SJoseph Koshy 	 * since otherwise a PMC_ATTACH to ourselves will fail.
2940c5153e19SJoseph Koshy 	 */
2941ebccf1e3SJoseph Koshy 	if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2942d5ee4074SMitchell Horne 		if (pp->pp_pmcs[ri].pp_pmc != NULL)
2943c514a571SMitchell Horne 			return (false);
2944ebccf1e3SJoseph Koshy 
29454a3690dfSJohn Baldwin 	PMCDBG4(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2946ebccf1e3SJoseph Koshy 	    p, p->p_pid, p->p_comm, ri);
2947c514a571SMitchell Horne 	return (true);
2948ebccf1e3SJoseph Koshy }
2949ebccf1e3SJoseph Koshy 
2950ebccf1e3SJoseph Koshy /*
2951ebccf1e3SJoseph Koshy  * Check if a given PMC at row index 'ri' can be currently used in
2952ebccf1e3SJoseph Koshy  * mode 'mode'.
2953ebccf1e3SJoseph Koshy  */
2954c514a571SMitchell Horne static bool
2955ebccf1e3SJoseph Koshy pmc_can_allocate_row(int ri, enum pmc_mode mode)
2956ebccf1e3SJoseph Koshy {
2957ebccf1e3SJoseph Koshy 	enum pmc_disp disp;
2958ebccf1e3SJoseph Koshy 
2959ebccf1e3SJoseph Koshy 	sx_assert(&pmc_sx, SX_XLOCKED);
2960ebccf1e3SJoseph Koshy 
29614a3690dfSJohn Baldwin 	PMCDBG2(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2962ebccf1e3SJoseph Koshy 
2963ebccf1e3SJoseph Koshy 	if (PMC_IS_SYSTEM_MODE(mode))
2964ebccf1e3SJoseph Koshy 		disp = PMC_DISP_STANDALONE;
2965ebccf1e3SJoseph Koshy 	else
2966ebccf1e3SJoseph Koshy 		disp = PMC_DISP_THREAD;
2967ebccf1e3SJoseph Koshy 
2968ebccf1e3SJoseph Koshy 	/*
2969ebccf1e3SJoseph Koshy 	 * check disposition for PMC row 'ri':
2970ebccf1e3SJoseph Koshy 	 *
2971ebccf1e3SJoseph Koshy 	 * Expected disposition		Row-disposition		Result
2972ebccf1e3SJoseph Koshy 	 *
2973ebccf1e3SJoseph Koshy 	 * STANDALONE			STANDALONE or FREE	proceed
2974ebccf1e3SJoseph Koshy 	 * STANDALONE			THREAD			fail
2975ebccf1e3SJoseph Koshy 	 * THREAD			THREAD or FREE		proceed
2976ebccf1e3SJoseph Koshy 	 * THREAD			STANDALONE		fail
2977ebccf1e3SJoseph Koshy 	 */
2978ebccf1e3SJoseph Koshy 	if (!PMC_ROW_DISP_IS_FREE(ri) &&
2979ebccf1e3SJoseph Koshy 	    !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2980ebccf1e3SJoseph Koshy 	    !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2981c514a571SMitchell Horne 		return (false);
2982ebccf1e3SJoseph Koshy 
2983ebccf1e3SJoseph Koshy 	/*
2984ebccf1e3SJoseph Koshy 	 * All OK
2985ebccf1e3SJoseph Koshy 	 */
29864a3690dfSJohn Baldwin 	PMCDBG2(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2987c514a571SMitchell Horne 	return (true);
2988ebccf1e3SJoseph Koshy }
2989ebccf1e3SJoseph Koshy 
2990ebccf1e3SJoseph Koshy /*
2991c5153e19SJoseph Koshy  * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2992ebccf1e3SJoseph Koshy  */
2993ebccf1e3SJoseph Koshy static struct pmc *
2994ebccf1e3SJoseph Koshy pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2995ebccf1e3SJoseph Koshy {
2996f263522aSJoseph Koshy 	struct pmc *pm;
2997ebccf1e3SJoseph Koshy 
2998c5153e19SJoseph Koshy 	KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2999c5153e19SJoseph Koshy 	    ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
3000c5153e19SJoseph Koshy 	    PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
3001ebccf1e3SJoseph Koshy 
3002d5ee4074SMitchell Horne 	LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
3003f263522aSJoseph Koshy 		if (pm->pm_id == pmcid)
3004d5ee4074SMitchell Horne 			return (pm);
3005d5ee4074SMitchell Horne 	}
3006ebccf1e3SJoseph Koshy 
300752ebac7fSMitchell Horne 	return (NULL);
3008ebccf1e3SJoseph Koshy }
3009ebccf1e3SJoseph Koshy 
3010ebccf1e3SJoseph Koshy static int
3011ebccf1e3SJoseph Koshy pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
3012ebccf1e3SJoseph Koshy {
3013e6f47577SBjoern A. Zeeb 	struct pmc *pm, *opm;
3014ebccf1e3SJoseph Koshy 	struct pmc_owner *po;
3015e6f47577SBjoern A. Zeeb 	struct pmc_process *pp;
3016ebccf1e3SJoseph Koshy 
30174a3690dfSJohn Baldwin 	PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid);
3018d2cd6388SKonstantin Belousov 	if (PMC_ID_TO_ROWINDEX(pmcid) >= md->pmd_npmc)
3019d2cd6388SKonstantin Belousov 		return (EINVAL);
3020ebccf1e3SJoseph Koshy 
3021e6f47577SBjoern A. Zeeb 	if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL) {
3022e6f47577SBjoern A. Zeeb 		/*
3023e6f47577SBjoern A. Zeeb 		 * In case of PMC_F_DESCENDANTS child processes we will not find
3024e6f47577SBjoern A. Zeeb 		 * the current process in the owners hash list.  Find the owner
3025e6f47577SBjoern A. Zeeb 		 * process first and from there lookup the po.
3026e6f47577SBjoern A. Zeeb 		 */
3027d5ee4074SMitchell Horne 		pp = pmc_find_process_descriptor(curthread->td_proc,
3028d5ee4074SMitchell Horne 		    PMC_FLAG_NONE);
3029d5ee4074SMitchell Horne 		if (pp == NULL)
303052ebac7fSMitchell Horne 			return (ESRCH);
3031e6f47577SBjoern A. Zeeb 		opm = pp->pp_pmcs[PMC_ID_TO_ROWINDEX(pmcid)].pp_pmc;
3032e6f47577SBjoern A. Zeeb 		if (opm == NULL)
303352ebac7fSMitchell Horne 			return (ESRCH);
3034d5ee4074SMitchell Horne 		if ((opm->pm_flags &
3035d5ee4074SMitchell Horne 		    (PMC_F_ATTACHED_TO_OWNER | PMC_F_DESCENDANTS)) !=
3036d5ee4074SMitchell Horne 		    (PMC_F_ATTACHED_TO_OWNER | PMC_F_DESCENDANTS))
303752ebac7fSMitchell Horne 			return (ESRCH);
3038d5ee4074SMitchell Horne 
3039e6f47577SBjoern A. Zeeb 		po = opm->pm_owner;
3040e6f47577SBjoern A. Zeeb 	}
3041ebccf1e3SJoseph Koshy 
3042ebccf1e3SJoseph Koshy 	if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
304352ebac7fSMitchell Horne 		return (EINVAL);
3044ebccf1e3SJoseph Koshy 
30454a3690dfSJohn Baldwin 	PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
3046ebccf1e3SJoseph Koshy 
3047ebccf1e3SJoseph Koshy 	*pmc = pm;
304852ebac7fSMitchell Horne 	return (0);
3049ebccf1e3SJoseph Koshy }
3050ebccf1e3SJoseph Koshy 
3051ebccf1e3SJoseph Koshy /*
3052ebccf1e3SJoseph Koshy  * Start a PMC.
3053ebccf1e3SJoseph Koshy  */
3054ebccf1e3SJoseph Koshy static int
3055ebccf1e3SJoseph Koshy pmc_start(struct pmc *pm)
3056ebccf1e3SJoseph Koshy {
3057ebccf1e3SJoseph Koshy 	struct pmc_binding pb;
3058e829eb6dSJoseph Koshy 	struct pmc_classdep *pcd;
305901c35b67SMitchell Horne 	struct pmc_owner *po;
3060d5ee4074SMitchell Horne 	pmc_value_t v;
306101c35b67SMitchell Horne 	enum pmc_mode mode;
3062e829eb6dSJoseph Koshy 	int adjri, error, cpu, ri;
3063ebccf1e3SJoseph Koshy 
3064ebccf1e3SJoseph Koshy 	KASSERT(pm != NULL,
3065ebccf1e3SJoseph Koshy 	    ("[pmc,%d] null pm", __LINE__));
3066ebccf1e3SJoseph Koshy 
3067c5153e19SJoseph Koshy 	mode = PMC_TO_MODE(pm);
3068c5153e19SJoseph Koshy 	ri   = PMC_TO_ROWINDEX(pm);
3069e829eb6dSJoseph Koshy 	pcd  = pmc_ri_to_classdep(md, ri, &adjri);
3070e829eb6dSJoseph Koshy 
3071c5153e19SJoseph Koshy 	error = 0;
307201c35b67SMitchell Horne 	po = pm->pm_owner;
3073c5153e19SJoseph Koshy 
30744a3690dfSJohn Baldwin 	PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
3075ebccf1e3SJoseph Koshy 
3076f263522aSJoseph Koshy 	po = pm->pm_owner;
3077ebccf1e3SJoseph Koshy 
3078d07f36b0SJoseph Koshy 	/*
3079d07f36b0SJoseph Koshy 	 * Disallow PMCSTART if a logfile is required but has not been
3080d07f36b0SJoseph Koshy 	 * configured yet.
3081d07f36b0SJoseph Koshy 	 */
3082d5ee4074SMitchell Horne 	if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) != 0 &&
3083d07f36b0SJoseph Koshy 	    (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
3084e829eb6dSJoseph Koshy 		return (EDOOFUS);	/* programming error */
3085d07f36b0SJoseph Koshy 
3086d07f36b0SJoseph Koshy 	/*
3087d07f36b0SJoseph Koshy 	 * If this is a sampling mode PMC, log mapping information for
3088d07f36b0SJoseph Koshy 	 * the kernel modules that are currently loaded.
3089d07f36b0SJoseph Koshy 	 */
3090d07f36b0SJoseph Koshy 	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3091d07f36b0SJoseph Koshy 		pmc_log_kernel_mappings(pm);
3092d07f36b0SJoseph Koshy 
3093c5153e19SJoseph Koshy 	if (PMC_IS_VIRTUAL_MODE(mode)) {
3094ebccf1e3SJoseph Koshy 		/*
3095f263522aSJoseph Koshy 		 * If a PMCATTACH has never been done on this PMC,
3096f263522aSJoseph Koshy 		 * attach it to its owner process.
3097ebccf1e3SJoseph Koshy 		 */
3098d5ee4074SMitchell Horne 		if (LIST_EMPTY(&pm->pm_targets)) {
3099d5ee4074SMitchell Horne 			error = (pm->pm_flags & PMC_F_ATTACH_DONE) != 0 ?
3100d5ee4074SMitchell Horne 			    ESRCH : pmc_attach_process(po->po_owner, pm);
3101d5ee4074SMitchell Horne 		}
3102f263522aSJoseph Koshy 
3103f263522aSJoseph Koshy 		/*
3104c5153e19SJoseph Koshy 		 * If the PMC is attached to its owner, then force a context
3105c5153e19SJoseph Koshy 		 * switch to ensure that the MD state gets set correctly.
3106c5153e19SJoseph Koshy 		 */
3107f263522aSJoseph Koshy 		if (error == 0) {
3108f263522aSJoseph Koshy 			pm->pm_state = PMC_STATE_RUNNING;
3109d5ee4074SMitchell Horne 			if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) != 0)
3110f263522aSJoseph Koshy 				pmc_force_context_switch();
3111f263522aSJoseph Koshy 		}
3112ebccf1e3SJoseph Koshy 
3113e829eb6dSJoseph Koshy 		return (error);
3114f263522aSJoseph Koshy 	}
3115ebccf1e3SJoseph Koshy 
3116f263522aSJoseph Koshy 	/*
3117f263522aSJoseph Koshy 	 * A system-wide PMC.
3118d07f36b0SJoseph Koshy 	 *
3119f263522aSJoseph Koshy 	 * Add the owner to the global list if this is a system-wide
3120f263522aSJoseph Koshy 	 * sampling PMC.
3121f263522aSJoseph Koshy 	 */
3122f263522aSJoseph Koshy 	if (mode == PMC_MODE_SS) {
3123bf792d68SJoseph Koshy 		/*
3124bf792d68SJoseph Koshy 		 * Log mapping information for all existing processes in the
3125bf792d68SJoseph Koshy 		 * system.  Subsequent mappings are logged as they happen;
3126bf792d68SJoseph Koshy 		 * see pmc_process_mmap().
3127bf792d68SJoseph Koshy 		 */
3128bf792d68SJoseph Koshy 		if (po->po_logprocmaps == 0) {
3129d07f36b0SJoseph Koshy 			pmc_log_all_process_mappings(po);
3130bf792d68SJoseph Koshy 			po->po_logprocmaps = 1;
3131bf792d68SJoseph Koshy 		}
31328fa7df36SMatt Macy 		po->po_sscount++;
31338fa7df36SMatt Macy 		if (po->po_sscount == 1) {
31348fa7df36SMatt Macy 			atomic_add_rel_int(&pmc_ss_count, 1);
31358fa7df36SMatt Macy 			CK_LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
31368fa7df36SMatt Macy 			PMCDBG1(PMC,OPS,1, "po=%p in global list", po);
31378fa7df36SMatt Macy 		}
313804001891SRyan Stone 	}
313949874f6eSJoseph Koshy 
3140ebccf1e3SJoseph Koshy 	/*
3141f263522aSJoseph Koshy 	 * Move to the CPU associated with this
3142ebccf1e3SJoseph Koshy 	 * PMC, and start the hardware.
3143ebccf1e3SJoseph Koshy 	 */
3144ebccf1e3SJoseph Koshy 	pmc_save_cpu_binding(&pb);
3145c5153e19SJoseph Koshy 	cpu = PMC_TO_CPU(pm);
3146122ccdc1SJoseph Koshy 	if (!pmc_cpu_is_active(cpu))
3147e829eb6dSJoseph Koshy 		return (ENXIO);
3148ebccf1e3SJoseph Koshy 	pmc_select_cpu(cpu);
3149ebccf1e3SJoseph Koshy 
3150ebccf1e3SJoseph Koshy 	/*
3151ebccf1e3SJoseph Koshy 	 * global PMCs are configured at allocation time
3152ebccf1e3SJoseph Koshy 	 * so write out the initial value and start the PMC.
3153ebccf1e3SJoseph Koshy 	 */
3154f263522aSJoseph Koshy 	pm->pm_state = PMC_STATE_RUNNING;
3155f263522aSJoseph Koshy 
3156c5153e19SJoseph Koshy 	critical_enter();
3157d5ee4074SMitchell Horne 	v = PMC_IS_SAMPLING_MODE(mode) ? pm->pm_sc.pm_reloadcount :
3158d5ee4074SMitchell Horne 	    pm->pm_sc.pm_initial;
3159d5ee4074SMitchell Horne 	if ((error = pcd->pcd_write_pmc(cpu, adjri, pm, v)) == 0) {
3160a3924968SJonathan T. Looney 		/* If a sampling mode PMC, reset stalled state. */
3161a3924968SJonathan T. Looney 		if (PMC_IS_SAMPLING_MODE(mode))
3162e6b475e0SMatt Macy 			pm->pm_pcpu_state[cpu].pps_stalled = 0;
3163a3924968SJonathan T. Looney 
3164a3924968SJonathan T. Looney 		/* Indicate that we desire this to run. Start it. */
3165e6b475e0SMatt Macy 		pm->pm_pcpu_state[cpu].pps_cpustate = 1;
316639f92a76SMitchell Horne 		error = pcd->pcd_start_pmc(cpu, adjri, pm);
3167a3924968SJonathan T. Looney 	}
3168c5153e19SJoseph Koshy 	critical_exit();
3169ebccf1e3SJoseph Koshy 
3170ebccf1e3SJoseph Koshy 	pmc_restore_cpu_binding(&pb);
3171e829eb6dSJoseph Koshy 	return (error);
3172ebccf1e3SJoseph Koshy }
3173ebccf1e3SJoseph Koshy 
3174ebccf1e3SJoseph Koshy /*
3175ebccf1e3SJoseph Koshy  * Stop a PMC.
3176ebccf1e3SJoseph Koshy  */
3177ebccf1e3SJoseph Koshy static int
3178ebccf1e3SJoseph Koshy pmc_stop(struct pmc *pm)
3179ebccf1e3SJoseph Koshy {
3180ebccf1e3SJoseph Koshy 	struct pmc_binding pb;
3181e829eb6dSJoseph Koshy 	struct pmc_classdep *pcd;
318201c35b67SMitchell Horne 	struct pmc_owner *po;
3183e829eb6dSJoseph Koshy 	int adjri, cpu, error, ri;
3184ebccf1e3SJoseph Koshy 
3185ebccf1e3SJoseph Koshy 	KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
3186ebccf1e3SJoseph Koshy 
3187693cd307SMitchell Horne 	PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm, PMC_TO_MODE(pm),
3188693cd307SMitchell Horne 	    PMC_TO_ROWINDEX(pm));
3189ebccf1e3SJoseph Koshy 
3190ebccf1e3SJoseph Koshy 	pm->pm_state = PMC_STATE_STOPPED;
3191ebccf1e3SJoseph Koshy 
3192ebccf1e3SJoseph Koshy 	/*
319301c35b67SMitchell Horne 	 * If the PMC is a virtual mode one, changing the state to non-RUNNING
319401c35b67SMitchell Horne 	 * is enough to ensure that the PMC never gets scheduled.
3195ebccf1e3SJoseph Koshy 	 *
319601c35b67SMitchell Horne 	 * If this PMC is current running on a CPU, then it will handled
319701c35b67SMitchell Horne 	 * correctly at the time its target process is context switched out.
3198ebccf1e3SJoseph Koshy 	 */
3199c5153e19SJoseph Koshy 	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
320052ebac7fSMitchell Horne 		return (0);
3201ebccf1e3SJoseph Koshy 
3202ebccf1e3SJoseph Koshy 	/*
320301c35b67SMitchell Horne 	 * A system-mode PMC. Move to the CPU associated with this PMC, and
320401c35b67SMitchell Horne 	 * stop the hardware. We update the 'initial count' so that a
320501c35b67SMitchell Horne 	 * subsequent PMCSTART will resume counting from the current hardware
320601c35b67SMitchell Horne 	 * count.
3207ebccf1e3SJoseph Koshy 	 */
3208ebccf1e3SJoseph Koshy 	pmc_save_cpu_binding(&pb);
3209ebccf1e3SJoseph Koshy 
3210c5153e19SJoseph Koshy 	cpu = PMC_TO_CPU(pm);
3211122ccdc1SJoseph Koshy 	KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
3212c5153e19SJoseph Koshy 	    ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
3213122ccdc1SJoseph Koshy 	if (!pmc_cpu_is_active(cpu))
321452ebac7fSMitchell Horne 		return (ENXIO);
3215ebccf1e3SJoseph Koshy 
3216ebccf1e3SJoseph Koshy 	pmc_select_cpu(cpu);
3217ebccf1e3SJoseph Koshy 
3218c5153e19SJoseph Koshy 	ri = PMC_TO_ROWINDEX(pm);
3219e829eb6dSJoseph Koshy 	pcd = pmc_ri_to_classdep(md, ri, &adjri);
3220c5153e19SJoseph Koshy 
3221e6b475e0SMatt Macy 	pm->pm_pcpu_state[cpu].pps_cpustate = 0;
3222c5153e19SJoseph Koshy 	critical_enter();
3223d5ee4074SMitchell Horne 	if ((error = pcd->pcd_stop_pmc(cpu, adjri, pm)) == 0) {
322439f92a76SMitchell Horne 		error = pcd->pcd_read_pmc(cpu, adjri, pm,
322539f92a76SMitchell Horne 		    &pm->pm_sc.pm_initial);
3226d5ee4074SMitchell Horne 	}
3227c5153e19SJoseph Koshy 	critical_exit();
3228ebccf1e3SJoseph Koshy 
3229ebccf1e3SJoseph Koshy 	pmc_restore_cpu_binding(&pb);
3230ebccf1e3SJoseph Koshy 
323101c35b67SMitchell Horne 	/* Remove this owner from the global list of SS PMC owners. */
3232f263522aSJoseph Koshy 	po = pm->pm_owner;
3233f263522aSJoseph Koshy 	if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
3234f263522aSJoseph Koshy 		po->po_sscount--;
3235f263522aSJoseph Koshy 		if (po->po_sscount == 0) {
3236f263522aSJoseph Koshy 			atomic_subtract_rel_int(&pmc_ss_count, 1);
32370f00315cSMatt Macy 			CK_LIST_REMOVE(po, po_ssnext);
323870398c2fSMatt Macy 			epoch_wait_preempt(global_epoch_preempt);
32394a3690dfSJohn Baldwin 			PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po);
3240f263522aSJoseph Koshy 		}
3241f263522aSJoseph Koshy 	}
3242f263522aSJoseph Koshy 
3243e829eb6dSJoseph Koshy 	return (error);
3244ebccf1e3SJoseph Koshy }
3245ebccf1e3SJoseph Koshy 
3246ba32b203SMatt Macy static struct pmc_classdep *
3247ba32b203SMatt Macy pmc_class_to_classdep(enum pmc_class class)
3248ba32b203SMatt Macy {
3249ba32b203SMatt Macy 	int n;
3250ba32b203SMatt Macy 
3251d5ee4074SMitchell Horne 	for (n = 0; n < md->pmd_nclass; n++) {
3252ba32b203SMatt Macy 		if (md->pmd_classdep[n].pcd_class == class)
3253ba32b203SMatt Macy 			return (&md->pmd_classdep[n]);
3254d5ee4074SMitchell Horne 	}
3255ba32b203SMatt Macy 	return (NULL);
3256ba32b203SMatt Macy }
3257ebccf1e3SJoseph Koshy 
32585de96e33SMatt Macy #if defined(HWPMC_DEBUG) && defined(KTR)
3259ebccf1e3SJoseph Koshy static const char *pmc_op_to_name[] = {
3260ebccf1e3SJoseph Koshy #undef	__PMC_OP
3261ebccf1e3SJoseph Koshy #define	__PMC_OP(N, D)	#N ,
3262ebccf1e3SJoseph Koshy 	__PMC_OPS()
3263ebccf1e3SJoseph Koshy 	NULL
3264ebccf1e3SJoseph Koshy };
3265ebccf1e3SJoseph Koshy #endif
3266ebccf1e3SJoseph Koshy 
3267ebccf1e3SJoseph Koshy /*
3268ebccf1e3SJoseph Koshy  * The syscall interface
3269ebccf1e3SJoseph Koshy  */
3270ebccf1e3SJoseph Koshy 
3271ebccf1e3SJoseph Koshy #define	PMC_GET_SX_XLOCK(...) do {		\
3272ebccf1e3SJoseph Koshy 	sx_xlock(&pmc_sx);			\
3273ebccf1e3SJoseph Koshy 	if (pmc_hook == NULL) {			\
3274ebccf1e3SJoseph Koshy 		sx_xunlock(&pmc_sx);		\
3275ebccf1e3SJoseph Koshy 		return __VA_ARGS__;		\
3276ebccf1e3SJoseph Koshy 	}					\
3277ebccf1e3SJoseph Koshy } while (0)
3278ebccf1e3SJoseph Koshy 
3279ebccf1e3SJoseph Koshy #define	PMC_DOWNGRADE_SX() do {			\
3280ebccf1e3SJoseph Koshy 	sx_downgrade(&pmc_sx);			\
328101c35b67SMitchell Horne 	is_sx_downgraded = true;		\
3282ebccf1e3SJoseph Koshy } while (0)
3283ebccf1e3SJoseph Koshy 
3284a133f642SMitchell Horne /*
3285c514a571SMitchell Horne  * Main body of PMC_OP_PMCALLOCATE.
3286c514a571SMitchell Horne  */
3287c514a571SMitchell Horne static int
3288c514a571SMitchell Horne pmc_do_op_pmcallocate(struct thread *td, struct pmc_op_pmcallocate *pa)
3289c514a571SMitchell Horne {
3290c514a571SMitchell Horne 	struct proc *p;
3291c514a571SMitchell Horne 	struct pmc *pmc;
3292c514a571SMitchell Horne 	struct pmc_binding pb;
3293c514a571SMitchell Horne 	struct pmc_classdep *pcd;
3294c514a571SMitchell Horne 	struct pmc_hw *phw;
3295c514a571SMitchell Horne 	enum pmc_mode mode;
3296c514a571SMitchell Horne 	enum pmc_class class;
329717e97d41SMitchell Horne 	uint32_t caps, flags;
3298c514a571SMitchell Horne 	u_int cpu;
3299c514a571SMitchell Horne 	int adjri, n;
3300c514a571SMitchell Horne 	int error;
3301c514a571SMitchell Horne 
3302c514a571SMitchell Horne 	class = pa->pm_class;
3303c514a571SMitchell Horne 	caps  = pa->pm_caps;
330417e97d41SMitchell Horne 	flags = pa->pm_flags;
3305c514a571SMitchell Horne 	mode  = pa->pm_mode;
3306c514a571SMitchell Horne 	cpu   = pa->pm_cpu;
3307c514a571SMitchell Horne 
3308c514a571SMitchell Horne 	p = td->td_proc;
3309c514a571SMitchell Horne 
3310c514a571SMitchell Horne 	/* Requested mode must exist. */
3311c514a571SMitchell Horne 	if ((mode != PMC_MODE_SS && mode != PMC_MODE_SC &&
3312c514a571SMitchell Horne 	     mode != PMC_MODE_TS && mode != PMC_MODE_TC))
3313c514a571SMitchell Horne 		return (EINVAL);
3314c514a571SMitchell Horne 
3315c514a571SMitchell Horne 	/* Requested CPU must be valid. */
3316c514a571SMitchell Horne 	if (cpu != PMC_CPU_ANY && cpu >= pmc_cpu_max())
3317c514a571SMitchell Horne 		return (EINVAL);
3318c514a571SMitchell Horne 
3319c514a571SMitchell Horne 	/*
3320c514a571SMitchell Horne 	 * Virtual PMCs should only ask for a default CPU.
3321c514a571SMitchell Horne 	 * System mode PMCs need to specify a non-default CPU.
3322c514a571SMitchell Horne 	 */
3323c514a571SMitchell Horne 	if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != PMC_CPU_ANY) ||
3324c514a571SMitchell Horne 	    (PMC_IS_SYSTEM_MODE(mode) && cpu == PMC_CPU_ANY))
3325c514a571SMitchell Horne 		return (EINVAL);
3326c514a571SMitchell Horne 
3327c514a571SMitchell Horne 	/*
3328c514a571SMitchell Horne 	 * Check that an inactive CPU is not being asked for.
3329c514a571SMitchell Horne 	 */
3330c514a571SMitchell Horne 	if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu))
3331c514a571SMitchell Horne 		return (ENXIO);
3332c514a571SMitchell Horne 
3333c514a571SMitchell Horne 	/*
3334c514a571SMitchell Horne 	 * Refuse an allocation for a system-wide PMC if this process has been
3335c514a571SMitchell Horne 	 * jailed, or if this process lacks super-user credentials and the
3336c514a571SMitchell Horne 	 * sysctl tunable 'security.bsd.unprivileged_syspmcs' is zero.
3337c514a571SMitchell Horne 	 */
3338c514a571SMitchell Horne 	if (PMC_IS_SYSTEM_MODE(mode)) {
3339c514a571SMitchell Horne 		if (jailed(td->td_ucred))
3340c514a571SMitchell Horne 			return (EPERM);
3341c514a571SMitchell Horne 		if (!pmc_unprivileged_syspmcs) {
3342c514a571SMitchell Horne 			error = priv_check(td, PRIV_PMC_SYSTEM);
3343c514a571SMitchell Horne 			if (error != 0)
3344c514a571SMitchell Horne 				return (error);
3345c514a571SMitchell Horne 		}
3346c514a571SMitchell Horne 	}
3347c514a571SMitchell Horne 
3348c514a571SMitchell Horne 	/*
3349c514a571SMitchell Horne 	 * Look for valid values for 'pm_flags'.
3350c514a571SMitchell Horne 	 */
335117e97d41SMitchell Horne 	if ((flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3352c514a571SMitchell Horne 	    PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN | PMC_F_USERCALLCHAIN)) != 0)
3353c514a571SMitchell Horne 		return (EINVAL);
3354c514a571SMitchell Horne 
3355c514a571SMitchell Horne 	/* PMC_F_USERCALLCHAIN is only valid with PMC_F_CALLCHAIN. */
335617e97d41SMitchell Horne 	if ((flags & (PMC_F_CALLCHAIN | PMC_F_USERCALLCHAIN)) ==
3357c514a571SMitchell Horne 	    PMC_F_USERCALLCHAIN)
3358c514a571SMitchell Horne 		return (EINVAL);
3359c514a571SMitchell Horne 
3360c514a571SMitchell Horne 	/* PMC_F_USERCALLCHAIN is only valid for sampling mode. */
336117e97d41SMitchell Horne 	if ((flags & PMC_F_USERCALLCHAIN) != 0 && mode != PMC_MODE_TS &&
3362c514a571SMitchell Horne 	    mode != PMC_MODE_SS)
3363c514a571SMitchell Horne 		return (EINVAL);
3364c514a571SMitchell Horne 
3365c514a571SMitchell Horne 	/* Process logging options are not allowed for system PMCs. */
3366c514a571SMitchell Horne 	if (PMC_IS_SYSTEM_MODE(mode) &&
336717e97d41SMitchell Horne 	    (flags & (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT)) != 0)
3368c514a571SMitchell Horne 		return (EINVAL);
3369c514a571SMitchell Horne 
3370c514a571SMitchell Horne 	/*
3371c514a571SMitchell Horne 	 * All sampling mode PMCs need to be able to interrupt the CPU.
3372c514a571SMitchell Horne 	 */
3373c514a571SMitchell Horne 	if (PMC_IS_SAMPLING_MODE(mode))
3374c514a571SMitchell Horne 		caps |= PMC_CAP_INTERRUPT;
3375c514a571SMitchell Horne 
3376c514a571SMitchell Horne 	/* A valid class specifier should have been passed in. */
3377c514a571SMitchell Horne 	pcd = pmc_class_to_classdep(class);
3378c514a571SMitchell Horne 	if (pcd == NULL)
3379c514a571SMitchell Horne 		return (EINVAL);
3380c514a571SMitchell Horne 
3381c514a571SMitchell Horne 	/* The requested PMC capabilities should be feasible. */
3382c514a571SMitchell Horne 	if ((pcd->pcd_caps & caps) != caps)
3383c514a571SMitchell Horne 		return (EOPNOTSUPP);
3384c514a571SMitchell Horne 
3385c514a571SMitchell Horne 	PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d", pa->pm_ev,
3386c514a571SMitchell Horne 	    caps, mode, cpu);
3387c514a571SMitchell Horne 
3388c514a571SMitchell Horne 	pmc = pmc_allocate_pmc_descriptor();
3389c514a571SMitchell Horne 	pmc->pm_id    = PMC_ID_MAKE_ID(cpu, pa->pm_mode, class, PMC_ID_INVALID);
3390c514a571SMitchell Horne 	pmc->pm_event = pa->pm_ev;
3391c514a571SMitchell Horne 	pmc->pm_state = PMC_STATE_FREE;
3392c514a571SMitchell Horne 	pmc->pm_caps  = caps;
339317e97d41SMitchell Horne 	pmc->pm_flags = flags;
3394c514a571SMitchell Horne 
3395c514a571SMitchell Horne 	/* XXX set lower bound on sampling for process counters */
3396c514a571SMitchell Horne 	if (PMC_IS_SAMPLING_MODE(mode)) {
3397c514a571SMitchell Horne 		/*
3398c514a571SMitchell Horne 		 * Don't permit requested sample rate to be less than
3399c514a571SMitchell Horne 		 * pmc_mincount.
3400c514a571SMitchell Horne 		 */
3401c514a571SMitchell Horne 		if (pa->pm_count < MAX(1, pmc_mincount))
3402c514a571SMitchell Horne 			log(LOG_WARNING, "pmcallocate: passed sample "
3403c514a571SMitchell Horne 			    "rate %ju - setting to %u\n",
3404c514a571SMitchell Horne 			    (uintmax_t)pa->pm_count,
3405c514a571SMitchell Horne 			    MAX(1, pmc_mincount));
3406c514a571SMitchell Horne 		pmc->pm_sc.pm_reloadcount = MAX(MAX(1, pmc_mincount),
3407c514a571SMitchell Horne 		    pa->pm_count);
3408c514a571SMitchell Horne 	} else
3409c514a571SMitchell Horne 		pmc->pm_sc.pm_initial = pa->pm_count;
3410c514a571SMitchell Horne 
3411c514a571SMitchell Horne 	/* switch thread to CPU 'cpu' */
3412c514a571SMitchell Horne 	pmc_save_cpu_binding(&pb);
3413c514a571SMitchell Horne 
3414c514a571SMitchell Horne #define	PMC_IS_SHAREABLE_PMC(cpu, n)				\
3415c514a571SMitchell Horne 	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &		\
3416c514a571SMitchell Horne 	 PMC_PHW_FLAG_IS_SHAREABLE)
3417c514a571SMitchell Horne #define	PMC_IS_UNALLOCATED(cpu, n)				\
3418c514a571SMitchell Horne 	(pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3419c514a571SMitchell Horne 
3420c514a571SMitchell Horne 	if (PMC_IS_SYSTEM_MODE(mode)) {
3421c514a571SMitchell Horne 		pmc_select_cpu(cpu);
3422c514a571SMitchell Horne 		for (n = pcd->pcd_ri; n < md->pmd_npmc; n++) {
3423c514a571SMitchell Horne 			pcd = pmc_ri_to_classdep(md, n, &adjri);
3424c514a571SMitchell Horne 
3425c514a571SMitchell Horne 			if (!pmc_can_allocate_row(n, mode) ||
3426c514a571SMitchell Horne 			    !pmc_can_allocate_rowindex(p, n, cpu))
3427c514a571SMitchell Horne 				continue;
3428c514a571SMitchell Horne 			if (!PMC_IS_UNALLOCATED(cpu, n) &&
3429c514a571SMitchell Horne 			    !PMC_IS_SHAREABLE_PMC(cpu, n))
3430c514a571SMitchell Horne 				continue;
3431c514a571SMitchell Horne 
3432c514a571SMitchell Horne 			if (pcd->pcd_allocate_pmc(cpu, adjri, pmc, pa) == 0) {
3433c514a571SMitchell Horne 				/* Success. */
3434c514a571SMitchell Horne 				break;
3435c514a571SMitchell Horne 			}
3436c514a571SMitchell Horne 		}
3437c514a571SMitchell Horne 	} else {
3438c514a571SMitchell Horne 		/* Process virtual mode */
3439c514a571SMitchell Horne 		for (n = pcd->pcd_ri; n < md->pmd_npmc; n++) {
3440c514a571SMitchell Horne 			pcd = pmc_ri_to_classdep(md, n, &adjri);
3441c514a571SMitchell Horne 
3442c514a571SMitchell Horne 			if (!pmc_can_allocate_row(n, mode) ||
3443c514a571SMitchell Horne 			    !pmc_can_allocate_rowindex(p, n, PMC_CPU_ANY))
3444c514a571SMitchell Horne 				continue;
3445c514a571SMitchell Horne 
3446c514a571SMitchell Horne 			if (pcd->pcd_allocate_pmc(td->td_oncpu, adjri, pmc,
3447c514a571SMitchell Horne 			    pa) == 0) {
3448c514a571SMitchell Horne 				/* Success. */
3449c514a571SMitchell Horne 				break;
3450c514a571SMitchell Horne 			}
3451c514a571SMitchell Horne 		}
3452c514a571SMitchell Horne 	}
3453c514a571SMitchell Horne 
3454c514a571SMitchell Horne #undef	PMC_IS_UNALLOCATED
3455c514a571SMitchell Horne #undef	PMC_IS_SHAREABLE_PMC
3456c514a571SMitchell Horne 
3457c514a571SMitchell Horne 	pmc_restore_cpu_binding(&pb);
3458c514a571SMitchell Horne 
3459c514a571SMitchell Horne 	if (n == md->pmd_npmc) {
3460c514a571SMitchell Horne 		pmc_destroy_pmc_descriptor(pmc);
3461c514a571SMitchell Horne 		return (EINVAL);
3462c514a571SMitchell Horne 	}
3463c514a571SMitchell Horne 
3464c514a571SMitchell Horne 	/* Fill in the correct value in the ID field. */
3465c514a571SMitchell Horne 	pmc->pm_id = PMC_ID_MAKE_ID(cpu, mode, class, n);
3466c514a571SMitchell Horne 
3467c514a571SMitchell Horne 	PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3468c514a571SMitchell Horne 	    pmc->pm_event, class, mode, n, pmc->pm_id);
3469c514a571SMitchell Horne 
3470c514a571SMitchell Horne 	/* Process mode PMCs with logging enabled need log files. */
3471c514a571SMitchell Horne 	if ((pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW)) != 0)
3472c514a571SMitchell Horne 		pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3473c514a571SMitchell Horne 
3474c514a571SMitchell Horne 	/* All system mode sampling PMCs require a log file. */
3475c514a571SMitchell Horne 	if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3476c514a571SMitchell Horne 		pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3477c514a571SMitchell Horne 
3478c514a571SMitchell Horne 	/*
3479c514a571SMitchell Horne 	 * Configure global pmc's immediately.
3480c514a571SMitchell Horne 	 */
3481c514a571SMitchell Horne 	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3482c514a571SMitchell Horne 		pmc_save_cpu_binding(&pb);
3483c514a571SMitchell Horne 		pmc_select_cpu(cpu);
3484c514a571SMitchell Horne 
3485c514a571SMitchell Horne 		phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3486c514a571SMitchell Horne 		pcd = pmc_ri_to_classdep(md, n, &adjri);
3487c514a571SMitchell Horne 
3488c514a571SMitchell Horne 		if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3489c514a571SMitchell Horne 		    (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3490c514a571SMitchell Horne 			(void)pcd->pcd_release_pmc(cpu, adjri, pmc);
3491c514a571SMitchell Horne 			pmc_destroy_pmc_descriptor(pmc);
3492c514a571SMitchell Horne 			pmc_restore_cpu_binding(&pb);
3493c514a571SMitchell Horne 			return (EPERM);
3494c514a571SMitchell Horne 		}
3495c514a571SMitchell Horne 
3496c514a571SMitchell Horne 		pmc_restore_cpu_binding(&pb);
3497c514a571SMitchell Horne 	}
3498c514a571SMitchell Horne 
3499c514a571SMitchell Horne 	pmc->pm_state = PMC_STATE_ALLOCATED;
3500c514a571SMitchell Horne 	pmc->pm_class = class;
3501c514a571SMitchell Horne 
3502c514a571SMitchell Horne 	/*
3503c514a571SMitchell Horne 	 * Mark row disposition.
3504c514a571SMitchell Horne 	 */
3505c514a571SMitchell Horne 	if (PMC_IS_SYSTEM_MODE(mode))
3506c514a571SMitchell Horne 		PMC_MARK_ROW_STANDALONE(n);
3507c514a571SMitchell Horne 	else
3508c514a571SMitchell Horne 		PMC_MARK_ROW_THREAD(n);
3509c514a571SMitchell Horne 
3510c514a571SMitchell Horne 	/*
3511c514a571SMitchell Horne 	 * Register this PMC with the current thread as its owner.
3512c514a571SMitchell Horne 	 */
3513c514a571SMitchell Horne 	error = pmc_register_owner(p, pmc);
3514c514a571SMitchell Horne 	if (error != 0) {
3515c514a571SMitchell Horne 		pmc_release_pmc_descriptor(pmc);
3516c514a571SMitchell Horne 		pmc_destroy_pmc_descriptor(pmc);
3517c514a571SMitchell Horne 		return (error);
3518c514a571SMitchell Horne 	}
3519c514a571SMitchell Horne 
3520c514a571SMitchell Horne 	/*
3521c514a571SMitchell Horne 	 * Return the allocated index.
3522c514a571SMitchell Horne 	 */
3523c514a571SMitchell Horne 	pa->pm_pmcid = pmc->pm_id;
3524c514a571SMitchell Horne 	return (0);
3525c514a571SMitchell Horne }
3526c514a571SMitchell Horne 
3527c514a571SMitchell Horne /*
3528a133f642SMitchell Horne  * Main body of PMC_OP_PMCATTACH.
3529a133f642SMitchell Horne  */
3530a133f642SMitchell Horne static int
3531a133f642SMitchell Horne pmc_do_op_pmcattach(struct thread *td, struct pmc_op_pmcattach a)
3532a133f642SMitchell Horne {
3533a133f642SMitchell Horne 	struct pmc *pm;
3534a133f642SMitchell Horne 	struct proc *p;
3535a133f642SMitchell Horne 	int error;
3536a133f642SMitchell Horne 
3537a133f642SMitchell Horne 	sx_assert(&pmc_sx, SX_XLOCKED);
3538a133f642SMitchell Horne 
3539a133f642SMitchell Horne 	if (a.pm_pid < 0) {
3540a133f642SMitchell Horne 		return (EINVAL);
3541a133f642SMitchell Horne 	} else if (a.pm_pid == 0) {
3542a133f642SMitchell Horne 		a.pm_pid = td->td_proc->p_pid;
3543a133f642SMitchell Horne 	}
3544a133f642SMitchell Horne 
3545a133f642SMitchell Horne 	error = pmc_find_pmc(a.pm_pmc, &pm);
3546a133f642SMitchell Horne 	if (error != 0)
3547a133f642SMitchell Horne 		return (error);
3548a133f642SMitchell Horne 
3549a133f642SMitchell Horne 	if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
3550a133f642SMitchell Horne 		return (EINVAL);
3551a133f642SMitchell Horne 
3552a133f642SMitchell Horne 	/* PMCs may be (re)attached only when allocated or stopped */
3553a133f642SMitchell Horne 	if (pm->pm_state == PMC_STATE_RUNNING) {
3554a133f642SMitchell Horne 		return (EBUSY);
3555a133f642SMitchell Horne 	} else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3556a133f642SMitchell Horne 	    pm->pm_state != PMC_STATE_STOPPED) {
3557a133f642SMitchell Horne 		return (EINVAL);
3558a133f642SMitchell Horne 	}
3559a133f642SMitchell Horne 
3560a133f642SMitchell Horne 	/* lookup pid */
3561a133f642SMitchell Horne 	if ((p = pfind(a.pm_pid)) == NULL)
3562a133f642SMitchell Horne 		return (ESRCH);
3563a133f642SMitchell Horne 
3564a133f642SMitchell Horne 	/*
3565a133f642SMitchell Horne 	 * Ignore processes that are working on exiting.
3566a133f642SMitchell Horne 	 */
3567a133f642SMitchell Horne 	if ((p->p_flag & P_WEXIT) != 0) {
3568a133f642SMitchell Horne 		PROC_UNLOCK(p);	/* pfind() returns a locked process */
3569a133f642SMitchell Horne 		return (ESRCH);
3570a133f642SMitchell Horne 	}
3571a133f642SMitchell Horne 
3572a133f642SMitchell Horne 	/*
3573a133f642SMitchell Horne 	 * We are allowed to attach a PMC to a process if we can debug it.
3574a133f642SMitchell Horne 	 */
3575a133f642SMitchell Horne 	error = p_candebug(curthread, p);
3576a133f642SMitchell Horne 
3577a133f642SMitchell Horne 	PROC_UNLOCK(p);
3578a133f642SMitchell Horne 
3579a133f642SMitchell Horne 	if (error == 0)
3580a133f642SMitchell Horne 		error = pmc_attach_process(p, pm);
3581a133f642SMitchell Horne 
3582a133f642SMitchell Horne 	return (error);
3583a133f642SMitchell Horne }
3584a133f642SMitchell Horne 
3585a133f642SMitchell Horne /*
3586a133f642SMitchell Horne  * Main body of PMC_OP_PMCDETACH.
3587a133f642SMitchell Horne  */
3588a133f642SMitchell Horne static int
3589a133f642SMitchell Horne pmc_do_op_pmcdetach(struct thread *td, struct pmc_op_pmcattach a)
3590a133f642SMitchell Horne {
3591a133f642SMitchell Horne 	struct pmc *pm;
3592a133f642SMitchell Horne 	struct proc *p;
3593a133f642SMitchell Horne 	int error;
3594a133f642SMitchell Horne 
3595a133f642SMitchell Horne 	if (a.pm_pid < 0) {
3596a133f642SMitchell Horne 		return (EINVAL);
3597a133f642SMitchell Horne 	} else if (a.pm_pid == 0)
3598a133f642SMitchell Horne 		a.pm_pid = td->td_proc->p_pid;
3599a133f642SMitchell Horne 
3600a133f642SMitchell Horne 	error = pmc_find_pmc(a.pm_pmc, &pm);
3601a133f642SMitchell Horne 	if (error != 0)
3602a133f642SMitchell Horne 		return (error);
3603a133f642SMitchell Horne 
3604a133f642SMitchell Horne 	if ((p = pfind(a.pm_pid)) == NULL)
3605a133f642SMitchell Horne 		return (ESRCH);
3606a133f642SMitchell Horne 
3607a133f642SMitchell Horne 	/*
3608a133f642SMitchell Horne 	 * Treat processes that are in the process of exiting as if they were
3609a133f642SMitchell Horne 	 * not present.
3610a133f642SMitchell Horne 	 */
3611a133f642SMitchell Horne 	if ((p->p_flag & P_WEXIT) != 0) {
3612a133f642SMitchell Horne 		PROC_UNLOCK(p);
3613a133f642SMitchell Horne 		return (ESRCH);
3614a133f642SMitchell Horne 	}
3615a133f642SMitchell Horne 
3616a133f642SMitchell Horne 	PROC_UNLOCK(p);	/* pfind() returns a locked process */
3617a133f642SMitchell Horne 
3618a133f642SMitchell Horne 	if (error == 0)
3619a133f642SMitchell Horne 		error = pmc_detach_process(p, pm);
3620a133f642SMitchell Horne 
3621a133f642SMitchell Horne 	return (error);
3622a133f642SMitchell Horne }
3623a133f642SMitchell Horne 
3624f4fac946SMitchell Horne /*
3625f4fac946SMitchell Horne  * Main body of PMC_OP_PMCRELEASE.
3626f4fac946SMitchell Horne  */
3627f4fac946SMitchell Horne static int
3628f4fac946SMitchell Horne pmc_do_op_pmcrelease(pmc_id_t pmcid)
3629f4fac946SMitchell Horne {
3630f4fac946SMitchell Horne 	struct pmc_owner *po;
3631f4fac946SMitchell Horne 	struct pmc *pm;
3632f4fac946SMitchell Horne 	int error;
3633f4fac946SMitchell Horne 
3634f4fac946SMitchell Horne 	/*
3635f4fac946SMitchell Horne 	 * Find PMC pointer for the named PMC.
3636f4fac946SMitchell Horne 	 *
3637f4fac946SMitchell Horne 	 * Use pmc_release_pmc_descriptor() to switch off the
3638f4fac946SMitchell Horne 	 * PMC, remove all its target threads, and remove the
3639f4fac946SMitchell Horne 	 * PMC from its owner's list.
3640f4fac946SMitchell Horne 	 *
3641f4fac946SMitchell Horne 	 * Remove the owner record if this is the last PMC
3642f4fac946SMitchell Horne 	 * owned.
3643f4fac946SMitchell Horne 	 *
3644f4fac946SMitchell Horne 	 * Free up space.
3645f4fac946SMitchell Horne 	 */
3646f4fac946SMitchell Horne 	error = pmc_find_pmc(pmcid, &pm);
3647f4fac946SMitchell Horne 	if (error != 0)
3648f4fac946SMitchell Horne 		return (error);
3649f4fac946SMitchell Horne 
3650f4fac946SMitchell Horne 	po = pm->pm_owner;
3651f4fac946SMitchell Horne 	pmc_release_pmc_descriptor(pm);
3652f4fac946SMitchell Horne 	pmc_maybe_remove_owner(po);
3653f4fac946SMitchell Horne 	pmc_destroy_pmc_descriptor(pm);
3654f4fac946SMitchell Horne 
3655f4fac946SMitchell Horne 	return (error);
3656f4fac946SMitchell Horne }
3657f4fac946SMitchell Horne 
365893fe5909SMitchell Horne /*
365993fe5909SMitchell Horne  * Main body of PMC_OP_PMCRW.
366093fe5909SMitchell Horne  */
366193fe5909SMitchell Horne static int
366293fe5909SMitchell Horne pmc_do_op_pmcrw(const struct pmc_op_pmcrw *prw, pmc_value_t *valp)
366393fe5909SMitchell Horne {
366493fe5909SMitchell Horne 	struct pmc_binding pb;
366593fe5909SMitchell Horne 	struct pmc_classdep *pcd;
366693fe5909SMitchell Horne 	struct pmc *pm;
366793fe5909SMitchell Horne 	u_int cpu, ri, adjri;
366893fe5909SMitchell Horne 	int error;
366993fe5909SMitchell Horne 
367093fe5909SMitchell Horne 	PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw->pm_pmcid, prw->pm_flags);
367193fe5909SMitchell Horne 
367293fe5909SMitchell Horne 	/* Must have at least one flag set. */
367393fe5909SMitchell Horne 	if ((prw->pm_flags & (PMC_F_OLDVALUE | PMC_F_NEWVALUE)) == 0)
367493fe5909SMitchell Horne 		return (EINVAL);
367593fe5909SMitchell Horne 
367693fe5909SMitchell Horne 	/* Locate PMC descriptor. */
367793fe5909SMitchell Horne 	error = pmc_find_pmc(prw->pm_pmcid, &pm);
367893fe5909SMitchell Horne 	if (error != 0)
367993fe5909SMitchell Horne 		return (error);
368093fe5909SMitchell Horne 
368193fe5909SMitchell Horne 	/* Can't read a PMC that hasn't been started. */
368293fe5909SMitchell Horne 	if (pm->pm_state != PMC_STATE_ALLOCATED &&
368393fe5909SMitchell Horne 	    pm->pm_state != PMC_STATE_STOPPED &&
368493fe5909SMitchell Horne 	    pm->pm_state != PMC_STATE_RUNNING)
368593fe5909SMitchell Horne 		return (EINVAL);
368693fe5909SMitchell Horne 
368793fe5909SMitchell Horne 	/* Writing a new value is allowed only for 'STOPPED' PMCs. */
368893fe5909SMitchell Horne 	if (pm->pm_state == PMC_STATE_RUNNING &&
368993fe5909SMitchell Horne 	    (prw->pm_flags & PMC_F_NEWVALUE) != 0)
369093fe5909SMitchell Horne 		return (EBUSY);
369193fe5909SMitchell Horne 
369293fe5909SMitchell Horne 	if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
369393fe5909SMitchell Horne 		/*
369493fe5909SMitchell Horne 		 * If this PMC is attached to its owner (i.e., the process
369593fe5909SMitchell Horne 		 * requesting this operation) and is running, then attempt to
369693fe5909SMitchell Horne 		 * get an upto-date reading from hardware for a READ. Writes
369793fe5909SMitchell Horne 		 * are only allowed when the PMC is stopped, so only update the
369893fe5909SMitchell Horne 		 * saved value field.
369993fe5909SMitchell Horne 		 *
370093fe5909SMitchell Horne 		 * If the PMC is not running, or is not attached to its owner,
370193fe5909SMitchell Horne 		 * read/write to the savedvalue field.
370293fe5909SMitchell Horne 		 */
370393fe5909SMitchell Horne 
370493fe5909SMitchell Horne 		ri = PMC_TO_ROWINDEX(pm);
370593fe5909SMitchell Horne 		pcd = pmc_ri_to_classdep(md, ri, &adjri);
370693fe5909SMitchell Horne 
370793fe5909SMitchell Horne 		mtx_pool_lock_spin(pmc_mtxpool, pm);
370893fe5909SMitchell Horne 		cpu = curthread->td_oncpu;
370993fe5909SMitchell Horne 
371093fe5909SMitchell Horne 		if ((prw->pm_flags & PMC_F_OLDVALUE) != 0) {
371193fe5909SMitchell Horne 			if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
371293fe5909SMitchell Horne 			    (pm->pm_state == PMC_STATE_RUNNING)) {
371393fe5909SMitchell Horne 				error = (*pcd->pcd_read_pmc)(cpu, adjri, pm,
371493fe5909SMitchell Horne 				    valp);
371593fe5909SMitchell Horne 			} else {
371693fe5909SMitchell Horne 				*valp = pm->pm_gv.pm_savedvalue;
371793fe5909SMitchell Horne 			}
371893fe5909SMitchell Horne 		}
371993fe5909SMitchell Horne 
372093fe5909SMitchell Horne 		if ((prw->pm_flags & PMC_F_NEWVALUE) != 0)
372193fe5909SMitchell Horne 			pm->pm_gv.pm_savedvalue = prw->pm_value;
372293fe5909SMitchell Horne 
372393fe5909SMitchell Horne 		mtx_pool_unlock_spin(pmc_mtxpool, pm);
372493fe5909SMitchell Horne 	} else { /* System mode PMCs */
372593fe5909SMitchell Horne 		cpu = PMC_TO_CPU(pm);
372693fe5909SMitchell Horne 		ri  = PMC_TO_ROWINDEX(pm);
372793fe5909SMitchell Horne 		pcd = pmc_ri_to_classdep(md, ri, &adjri);
372893fe5909SMitchell Horne 
372993fe5909SMitchell Horne 		if (!pmc_cpu_is_active(cpu))
373093fe5909SMitchell Horne 			return (ENXIO);
373193fe5909SMitchell Horne 
373293fe5909SMitchell Horne 		/* Move this thread to CPU 'cpu'. */
373393fe5909SMitchell Horne 		pmc_save_cpu_binding(&pb);
373493fe5909SMitchell Horne 		pmc_select_cpu(cpu);
373593fe5909SMitchell Horne 		critical_enter();
373693fe5909SMitchell Horne 
373793fe5909SMitchell Horne 		/* Save old value. */
373893fe5909SMitchell Horne 		if ((prw->pm_flags & PMC_F_OLDVALUE) != 0)
373993fe5909SMitchell Horne 			error = (*pcd->pcd_read_pmc)(cpu, adjri, pm, valp);
374093fe5909SMitchell Horne 
374193fe5909SMitchell Horne 		/* Write out new value. */
374293fe5909SMitchell Horne 		if (error == 0 && (prw->pm_flags & PMC_F_NEWVALUE) != 0)
374393fe5909SMitchell Horne 			error = (*pcd->pcd_write_pmc)(cpu, adjri, pm,
374493fe5909SMitchell Horne 			    prw->pm_value);
374593fe5909SMitchell Horne 
374693fe5909SMitchell Horne 		critical_exit();
374793fe5909SMitchell Horne 		pmc_restore_cpu_binding(&pb);
374893fe5909SMitchell Horne 		if (error != 0)
374993fe5909SMitchell Horne 			return (error);
375093fe5909SMitchell Horne 	}
375193fe5909SMitchell Horne 
375293fe5909SMitchell Horne #ifdef HWPMC_DEBUG
375393fe5909SMitchell Horne 	if ((prw->pm_flags & PMC_F_NEWVALUE) != 0)
375493fe5909SMitchell Horne 		PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
375593fe5909SMitchell Horne 		    ri, prw->pm_value, *valp);
375693fe5909SMitchell Horne 	else
375793fe5909SMitchell Horne 		PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, *valp);
375893fe5909SMitchell Horne #endif
375993fe5909SMitchell Horne 	return (error);
376093fe5909SMitchell Horne }
376193fe5909SMitchell Horne 
3762ebccf1e3SJoseph Koshy static int
3763ebccf1e3SJoseph Koshy pmc_syscall_handler(struct thread *td, void *syscall_args)
3764ebccf1e3SJoseph Koshy {
3765ebccf1e3SJoseph Koshy 	struct pmc_syscall_args *c;
376620b555e1SKonstantin Belousov 	void *pmclog_proc_handle;
3767ebccf1e3SJoseph Koshy 	void *arg;
376801c35b67SMitchell Horne 	int error, op;
376901c35b67SMitchell Horne 	bool is_sx_downgraded;
3770ebccf1e3SJoseph Koshy 
3771ebccf1e3SJoseph Koshy 	c = (struct pmc_syscall_args *)syscall_args;
3772ebccf1e3SJoseph Koshy 	op = c->pmop_code;
3773ebccf1e3SJoseph Koshy 	arg = c->pmop_data;
3774693cd307SMitchell Horne 
37750f00315cSMatt Macy 	/* PMC isn't set up yet */
37760f00315cSMatt Macy 	if (pmc_hook == NULL)
37770f00315cSMatt Macy 		return (EINVAL);
3778693cd307SMitchell Horne 
377920b555e1SKonstantin Belousov 	if (op == PMC_OP_CONFIGURELOG) {
378020b555e1SKonstantin Belousov 		/*
378120b555e1SKonstantin Belousov 		 * We cannot create the logging process inside
378220b555e1SKonstantin Belousov 		 * pmclog_configure_log() because there is a LOR
378320b555e1SKonstantin Belousov 		 * between pmc_sx and process structure locks.
378420b555e1SKonstantin Belousov 		 * Instead, pre-create the process and ignite the loop
378520b555e1SKonstantin Belousov 		 * if everything is fine, otherwise direct the process
378620b555e1SKonstantin Belousov 		 * to exit.
378720b555e1SKonstantin Belousov 		 */
378820b555e1SKonstantin Belousov 		error = pmclog_proc_create(td, &pmclog_proc_handle);
378920b555e1SKonstantin Belousov 		if (error != 0)
379020b555e1SKonstantin Belousov 			goto done_syscall;
379120b555e1SKonstantin Belousov 	}
379220b555e1SKonstantin Belousov 
379320b555e1SKonstantin Belousov 	PMC_GET_SX_XLOCK(ENOSYS);
379401c35b67SMitchell Horne 	is_sx_downgraded = false;
37954a3690dfSJohn Baldwin 	PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
3796ebccf1e3SJoseph Koshy 	    pmc_op_to_name[op], arg);
3797ebccf1e3SJoseph Koshy 
3798ebccf1e3SJoseph Koshy 	error = 0;
3799e6b475e0SMatt Macy 	counter_u64_add(pmc_stats.pm_syscalls, 1);
3800ebccf1e3SJoseph Koshy 
3801cf9ef806SKonstantin Belousov 	switch (op) {
3802ebccf1e3SJoseph Koshy 
3803ebccf1e3SJoseph Koshy 
3804ebccf1e3SJoseph Koshy 	/*
3805ebccf1e3SJoseph Koshy 	 * Configure a log file.
3806ebccf1e3SJoseph Koshy 	 *
3807ebccf1e3SJoseph Koshy 	 * XXX This OP will be reworked.
3808ebccf1e3SJoseph Koshy 	 */
3809ebccf1e3SJoseph Koshy 
3810ebccf1e3SJoseph Koshy 	case PMC_OP_CONFIGURELOG:
3811ebccf1e3SJoseph Koshy 	{
381249874f6eSJoseph Koshy 		struct proc *p;
3813fc9a2b80SJoseph Koshy 		struct pmc *pm;
3814ebccf1e3SJoseph Koshy 		struct pmc_owner *po;
3815ebccf1e3SJoseph Koshy 		struct pmc_op_configurelog cl;
3816ebccf1e3SJoseph Koshy 
381720b555e1SKonstantin Belousov 		if ((error = copyin(arg, &cl, sizeof(cl))) != 0) {
381820b555e1SKonstantin Belousov 			pmclog_proc_ignite(pmclog_proc_handle, NULL);
3819ebccf1e3SJoseph Koshy 			break;
382020b555e1SKonstantin Belousov 		}
3821ebccf1e3SJoseph Koshy 
38228e63e787SJessica Clarke 		/* No flags currently implemented */
38238e63e787SJessica Clarke 		if (cl.pm_flags != 0) {
3824*42e70f42SKonstantin Belousov 			pmclog_proc_ignite(pmclog_proc_handle, NULL);
38258e63e787SJessica Clarke 			error = EINVAL;
38268e63e787SJessica Clarke 			break;
38278e63e787SJessica Clarke 		}
38288e63e787SJessica Clarke 
3829ebccf1e3SJoseph Koshy 		/* mark this process as owning a log file */
3830ebccf1e3SJoseph Koshy 		p = td->td_proc;
3831ebccf1e3SJoseph Koshy 		if ((po = pmc_find_owner_descriptor(p)) == NULL)
3832f263522aSJoseph Koshy 			if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
383320b555e1SKonstantin Belousov 				pmclog_proc_ignite(pmclog_proc_handle, NULL);
3834f263522aSJoseph Koshy 				error = ENOMEM;
3835ebccf1e3SJoseph Koshy 				break;
3836f263522aSJoseph Koshy 			}
3837ebccf1e3SJoseph Koshy 
3838f263522aSJoseph Koshy 		/*
3839f263522aSJoseph Koshy 		 * If a valid fd was passed in, try to configure that,
3840f263522aSJoseph Koshy 		 * otherwise if 'fd' was less than zero and there was
3841f263522aSJoseph Koshy 		 * a log file configured, flush its buffers and
3842f263522aSJoseph Koshy 		 * de-configure it.
3843f263522aSJoseph Koshy 		 */
3844ca2d94beSAttilio Rao 		if (cl.pm_logfd >= 0) {
38450cfab8ddSJoseph Koshy 			error = pmclog_configure_log(md, po, cl.pm_logfd);
384620b555e1SKonstantin Belousov 			pmclog_proc_ignite(pmclog_proc_handle, error == 0 ?
384720b555e1SKonstantin Belousov 			    po : NULL);
3848ca2d94beSAttilio Rao 		} else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
384920b555e1SKonstantin Belousov 			pmclog_proc_ignite(pmclog_proc_handle, NULL);
3850dceed24aSFabien Thomas 			error = pmclog_close(po);
3851fc9a2b80SJoseph Koshy 			if (error == 0) {
3852fc9a2b80SJoseph Koshy 				LIST_FOREACH(pm, &po->po_pmcs, pm_next)
385366f3bc78SJoseph Koshy 				    if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
385466f3bc78SJoseph Koshy 					pm->pm_state == PMC_STATE_RUNNING)
3855fc9a2b80SJoseph Koshy 					    pmc_stop(pm);
3856f263522aSJoseph Koshy 				error = pmclog_deconfigure_log(po);
3857fc9a2b80SJoseph Koshy 			}
385820b555e1SKonstantin Belousov 		} else {
385920b555e1SKonstantin Belousov 			pmclog_proc_ignite(pmclog_proc_handle, NULL);
3860f263522aSJoseph Koshy 			error = EINVAL;
386120b555e1SKonstantin Belousov 		}
3862ebccf1e3SJoseph Koshy 	}
3863ebccf1e3SJoseph Koshy 	break;
3864ebccf1e3SJoseph Koshy 
3865ebccf1e3SJoseph Koshy 	/*
3866f263522aSJoseph Koshy 	 * Flush a log file.
3867f263522aSJoseph Koshy 	 */
3868f263522aSJoseph Koshy 
3869f263522aSJoseph Koshy 	case PMC_OP_FLUSHLOG:
3870f263522aSJoseph Koshy 	{
3871f263522aSJoseph Koshy 		struct pmc_owner *po;
3872f263522aSJoseph Koshy 
3873f263522aSJoseph Koshy 		sx_assert(&pmc_sx, SX_XLOCKED);
3874f263522aSJoseph Koshy 
3875f263522aSJoseph Koshy 		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3876f263522aSJoseph Koshy 			error = EINVAL;
3877f263522aSJoseph Koshy 			break;
3878f263522aSJoseph Koshy 		}
3879f263522aSJoseph Koshy 
3880ebfaf69cSMatt Macy 		error = pmclog_flush(po, 0);
3881f263522aSJoseph Koshy 	}
3882f263522aSJoseph Koshy 	break;
3883f263522aSJoseph Koshy 
3884f263522aSJoseph Koshy 	/*
3885dceed24aSFabien Thomas 	 * Close a log file.
3886dceed24aSFabien Thomas 	 */
3887dceed24aSFabien Thomas 
3888dceed24aSFabien Thomas 	case PMC_OP_CLOSELOG:
3889dceed24aSFabien Thomas 	{
3890dceed24aSFabien Thomas 		struct pmc_owner *po;
3891dceed24aSFabien Thomas 
3892dceed24aSFabien Thomas 		sx_assert(&pmc_sx, SX_XLOCKED);
3893dceed24aSFabien Thomas 
3894dceed24aSFabien Thomas 		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3895dceed24aSFabien Thomas 			error = EINVAL;
3896dceed24aSFabien Thomas 			break;
3897dceed24aSFabien Thomas 		}
3898dceed24aSFabien Thomas 
3899dceed24aSFabien Thomas 		error = pmclog_close(po);
3900dceed24aSFabien Thomas 	}
3901dceed24aSFabien Thomas 	break;
3902dceed24aSFabien Thomas 
3903dceed24aSFabien Thomas 	/*
3904ebccf1e3SJoseph Koshy 	 * Retrieve hardware configuration.
3905ebccf1e3SJoseph Koshy 	 */
3906ebccf1e3SJoseph Koshy 
3907ebccf1e3SJoseph Koshy 	case PMC_OP_GETCPUINFO:	/* CPU information */
3908ebccf1e3SJoseph Koshy 	{
3909ebccf1e3SJoseph Koshy 		struct pmc_op_getcpuinfo gci;
3910e829eb6dSJoseph Koshy 		struct pmc_classinfo *pci;
3911e829eb6dSJoseph Koshy 		struct pmc_classdep *pcd;
3912e829eb6dSJoseph Koshy 		int cl;
3913ebccf1e3SJoseph Koshy 
39148f77f60fSMark Johnston 		memset(&gci, 0, sizeof(gci));
3915ebccf1e3SJoseph Koshy 		gci.pm_cputype = md->pmd_cputype;
3916122ccdc1SJoseph Koshy 		gci.pm_ncpu    = pmc_cpu_max();
3917ebccf1e3SJoseph Koshy 		gci.pm_npmc    = md->pmd_npmc;
3918ebccf1e3SJoseph Koshy 		gci.pm_nclass  = md->pmd_nclass;
3919e829eb6dSJoseph Koshy 		pci = gci.pm_classes;
3920e829eb6dSJoseph Koshy 		pcd = md->pmd_classdep;
3921e829eb6dSJoseph Koshy 		for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
3922e829eb6dSJoseph Koshy 			pci->pm_caps  = pcd->pcd_caps;
3923e829eb6dSJoseph Koshy 			pci->pm_class = pcd->pcd_class;
3924e829eb6dSJoseph Koshy 			pci->pm_width = pcd->pcd_width;
3925e829eb6dSJoseph Koshy 			pci->pm_num   = pcd->pcd_num;
3926e829eb6dSJoseph Koshy 		}
3927ebccf1e3SJoseph Koshy 		error = copyout(&gci, arg, sizeof(gci));
3928ebccf1e3SJoseph Koshy 	}
3929ebccf1e3SJoseph Koshy 	break;
3930ebccf1e3SJoseph Koshy 
3931f5f9340bSFabien Thomas 	/*
3932f5f9340bSFabien Thomas 	 * Retrieve soft events list.
3933f5f9340bSFabien Thomas 	 */
3934f5f9340bSFabien Thomas 	case PMC_OP_GETDYNEVENTINFO:
3935f5f9340bSFabien Thomas 	{
3936f5f9340bSFabien Thomas 		enum pmc_class			cl;
3937f5f9340bSFabien Thomas 		enum pmc_event			ev;
3938f5f9340bSFabien Thomas 		struct pmc_op_getdyneventinfo	*gei;
3939f5f9340bSFabien Thomas 		struct pmc_dyn_event_descr	dev;
3940f5f9340bSFabien Thomas 		struct pmc_soft			*ps;
3941f5f9340bSFabien Thomas 		uint32_t			nevent;
3942f5f9340bSFabien Thomas 
3943f5f9340bSFabien Thomas 		sx_assert(&pmc_sx, SX_LOCKED);
3944f5f9340bSFabien Thomas 
3945f5f9340bSFabien Thomas 		gei = (struct pmc_op_getdyneventinfo *) arg;
3946f5f9340bSFabien Thomas 
3947f5f9340bSFabien Thomas 		if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
3948f5f9340bSFabien Thomas 			break;
3949f5f9340bSFabien Thomas 
3950f5f9340bSFabien Thomas 		/* Only SOFT class is dynamic. */
3951f5f9340bSFabien Thomas 		if (cl != PMC_CLASS_SOFT) {
3952f5f9340bSFabien Thomas 			error = EINVAL;
3953f5f9340bSFabien Thomas 			break;
3954f5f9340bSFabien Thomas 		}
3955f5f9340bSFabien Thomas 
3956f5f9340bSFabien Thomas 		nevent = 0;
3957ca57f64fSSean Bruno 		for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) {
3958f5f9340bSFabien Thomas 			ps = pmc_soft_ev_acquire(ev);
3959f5f9340bSFabien Thomas 			if (ps == NULL)
3960f5f9340bSFabien Thomas 				continue;
3961f5f9340bSFabien Thomas 			bcopy(&ps->ps_ev, &dev, sizeof(dev));
3962f5f9340bSFabien Thomas 			pmc_soft_ev_release(ps);
3963f5f9340bSFabien Thomas 
3964f5f9340bSFabien Thomas 			error = copyout(&dev,
3965f5f9340bSFabien Thomas 			    &gei->pm_events[nevent],
3966f5f9340bSFabien Thomas 			    sizeof(struct pmc_dyn_event_descr));
3967f5f9340bSFabien Thomas 			if (error != 0)
3968f5f9340bSFabien Thomas 				break;
3969f5f9340bSFabien Thomas 			nevent++;
3970f5f9340bSFabien Thomas 		}
3971f5f9340bSFabien Thomas 		if (error != 0)
3972f5f9340bSFabien Thomas 			break;
3973f5f9340bSFabien Thomas 
3974f5f9340bSFabien Thomas 		error = copyout(&nevent, &gei->pm_nevent,
3975f5f9340bSFabien Thomas 		    sizeof(nevent));
3976f5f9340bSFabien Thomas 	}
3977f5f9340bSFabien Thomas 	break;
3978ebccf1e3SJoseph Koshy 
3979ebccf1e3SJoseph Koshy 	/*
3980ebccf1e3SJoseph Koshy 	 * Get module statistics
3981ebccf1e3SJoseph Koshy 	 */
3982ebccf1e3SJoseph Koshy 
3983ebccf1e3SJoseph Koshy 	case PMC_OP_GETDRIVERSTATS:
3984ebccf1e3SJoseph Koshy 	{
3985ebccf1e3SJoseph Koshy 		struct pmc_op_getdriverstats gms;
3986e6b475e0SMatt Macy #define CFETCH(a, b, field) a.field = counter_u64_fetch(b.field)
3987e6b475e0SMatt Macy 		CFETCH(gms, pmc_stats, pm_intr_ignored);
3988e6b475e0SMatt Macy 		CFETCH(gms, pmc_stats, pm_intr_processed);
3989e6b475e0SMatt Macy 		CFETCH(gms, pmc_stats, pm_intr_bufferfull);
3990e6b475e0SMatt Macy 		CFETCH(gms, pmc_stats, pm_syscalls);
3991e6b475e0SMatt Macy 		CFETCH(gms, pmc_stats, pm_syscall_errors);
3992e6b475e0SMatt Macy 		CFETCH(gms, pmc_stats, pm_buffer_requests);
3993e6b475e0SMatt Macy 		CFETCH(gms, pmc_stats, pm_buffer_requests_failed);
3994e6b475e0SMatt Macy 		CFETCH(gms, pmc_stats, pm_log_sweeps);
3995e6b475e0SMatt Macy #undef CFETCH
3996ebccf1e3SJoseph Koshy 		error = copyout(&gms, arg, sizeof(gms));
3997ebccf1e3SJoseph Koshy 	}
3998ebccf1e3SJoseph Koshy 	break;
3999ebccf1e3SJoseph Koshy 
4000ebccf1e3SJoseph Koshy 
4001ebccf1e3SJoseph Koshy 	/*
4002ebccf1e3SJoseph Koshy 	 * Retrieve module version number
4003ebccf1e3SJoseph Koshy 	 */
4004ebccf1e3SJoseph Koshy 
4005ebccf1e3SJoseph Koshy 	case PMC_OP_GETMODULEVERSION:
4006ebccf1e3SJoseph Koshy 	{
4007f263522aSJoseph Koshy 		uint32_t cv, modv;
4008f263522aSJoseph Koshy 
4009f263522aSJoseph Koshy 		/* retrieve the client's idea of the ABI version */
4010f263522aSJoseph Koshy 		if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
4011f263522aSJoseph Koshy 			break;
4012f263522aSJoseph Koshy 		/* don't service clients newer than our driver */
4013f263522aSJoseph Koshy 		modv = PMC_VERSION;
4014f263522aSJoseph Koshy 		if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
4015f263522aSJoseph Koshy 			error = EPROGMISMATCH;
4016f263522aSJoseph Koshy 			break;
4017f263522aSJoseph Koshy 		}
4018f263522aSJoseph Koshy 		error = copyout(&modv, arg, sizeof(int));
4019ebccf1e3SJoseph Koshy 	}
4020ebccf1e3SJoseph Koshy 	break;
4021ebccf1e3SJoseph Koshy 
4022ebccf1e3SJoseph Koshy 
4023ebccf1e3SJoseph Koshy 	/*
4024ebccf1e3SJoseph Koshy 	 * Retrieve the state of all the PMCs on a given
4025ebccf1e3SJoseph Koshy 	 * CPU.
4026ebccf1e3SJoseph Koshy 	 */
4027ebccf1e3SJoseph Koshy 
4028ebccf1e3SJoseph Koshy 	case PMC_OP_GETPMCINFO:
4029ebccf1e3SJoseph Koshy 	{
4030e829eb6dSJoseph Koshy 		int ari;
4031ebccf1e3SJoseph Koshy 		struct pmc *pm;
4032e829eb6dSJoseph Koshy 		size_t pmcinfo_size;
4033e829eb6dSJoseph Koshy 		uint32_t cpu, n, npmc;
4034ebccf1e3SJoseph Koshy 		struct pmc_owner *po;
4035ebccf1e3SJoseph Koshy 		struct pmc_binding pb;
4036e829eb6dSJoseph Koshy 		struct pmc_classdep *pcd;
4037e829eb6dSJoseph Koshy 		struct pmc_info *p, *pmcinfo;
4038e829eb6dSJoseph Koshy 		struct pmc_op_getpmcinfo *gpi;
4039ebccf1e3SJoseph Koshy 
4040ebccf1e3SJoseph Koshy 		PMC_DOWNGRADE_SX();
4041ebccf1e3SJoseph Koshy 
4042ebccf1e3SJoseph Koshy 		gpi = (struct pmc_op_getpmcinfo *) arg;
4043ebccf1e3SJoseph Koshy 
4044ebccf1e3SJoseph Koshy 		if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
4045ebccf1e3SJoseph Koshy 			break;
4046ebccf1e3SJoseph Koshy 
4047122ccdc1SJoseph Koshy 		if (cpu >= pmc_cpu_max()) {
4048ebccf1e3SJoseph Koshy 			error = EINVAL;
4049ebccf1e3SJoseph Koshy 			break;
4050ebccf1e3SJoseph Koshy 		}
4051ebccf1e3SJoseph Koshy 
4052122ccdc1SJoseph Koshy 		if (!pmc_cpu_is_active(cpu)) {
4053ebccf1e3SJoseph Koshy 			error = ENXIO;
4054ebccf1e3SJoseph Koshy 			break;
4055ebccf1e3SJoseph Koshy 		}
4056ebccf1e3SJoseph Koshy 
4057ebccf1e3SJoseph Koshy 		/* switch to CPU 'cpu' */
4058ebccf1e3SJoseph Koshy 		pmc_save_cpu_binding(&pb);
4059ebccf1e3SJoseph Koshy 		pmc_select_cpu(cpu);
4060ebccf1e3SJoseph Koshy 
4061ebccf1e3SJoseph Koshy 		npmc = md->pmd_npmc;
4062ebccf1e3SJoseph Koshy 
4063ebccf1e3SJoseph Koshy 		pmcinfo_size = npmc * sizeof(struct pmc_info);
40648f77f60fSMark Johnston 		pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK | M_ZERO);
4065ebccf1e3SJoseph Koshy 
4066ebccf1e3SJoseph Koshy 		p = pmcinfo;
4067ebccf1e3SJoseph Koshy 
4068ebccf1e3SJoseph Koshy 		for (n = 0; n < md->pmd_npmc; n++, p++) {
4069ebccf1e3SJoseph Koshy 
4070e829eb6dSJoseph Koshy 			pcd = pmc_ri_to_classdep(md, n, &ari);
4071e829eb6dSJoseph Koshy 
4072e829eb6dSJoseph Koshy 			KASSERT(pcd != NULL,
4073e829eb6dSJoseph Koshy 			    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4074e829eb6dSJoseph Koshy 
4075e829eb6dSJoseph Koshy 			if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
4076ebccf1e3SJoseph Koshy 				break;
4077ebccf1e3SJoseph Koshy 
4078ebccf1e3SJoseph Koshy 			if (PMC_ROW_DISP_IS_STANDALONE(n))
4079ebccf1e3SJoseph Koshy 				p->pm_rowdisp = PMC_DISP_STANDALONE;
4080ebccf1e3SJoseph Koshy 			else if (PMC_ROW_DISP_IS_THREAD(n))
4081ebccf1e3SJoseph Koshy 				p->pm_rowdisp = PMC_DISP_THREAD;
4082ebccf1e3SJoseph Koshy 			else
4083ebccf1e3SJoseph Koshy 				p->pm_rowdisp = PMC_DISP_FREE;
4084ebccf1e3SJoseph Koshy 
4085ebccf1e3SJoseph Koshy 			p->pm_ownerpid = -1;
4086ebccf1e3SJoseph Koshy 
4087ebccf1e3SJoseph Koshy 			if (pm == NULL)	/* no PMC associated */
4088ebccf1e3SJoseph Koshy 				continue;
4089ebccf1e3SJoseph Koshy 
4090ebccf1e3SJoseph Koshy 			po = pm->pm_owner;
4091ebccf1e3SJoseph Koshy 
4092ebccf1e3SJoseph Koshy 			KASSERT(po->po_owner != NULL,
4093ebccf1e3SJoseph Koshy 			    ("[pmc,%d] pmc_owner had a null proc pointer",
4094ebccf1e3SJoseph Koshy 				__LINE__));
4095ebccf1e3SJoseph Koshy 
4096ebccf1e3SJoseph Koshy 			p->pm_ownerpid = po->po_owner->p_pid;
4097c5153e19SJoseph Koshy 			p->pm_mode     = PMC_TO_MODE(pm);
4098ebccf1e3SJoseph Koshy 			p->pm_event    = pm->pm_event;
4099ebccf1e3SJoseph Koshy 			p->pm_flags    = pm->pm_flags;
4100ebccf1e3SJoseph Koshy 
4101c5153e19SJoseph Koshy 			if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
4102ebccf1e3SJoseph Koshy 				p->pm_reloadcount =
4103ebccf1e3SJoseph Koshy 				    pm->pm_sc.pm_reloadcount;
4104ebccf1e3SJoseph Koshy 		}
4105ebccf1e3SJoseph Koshy 
4106ebccf1e3SJoseph Koshy 		pmc_restore_cpu_binding(&pb);
4107ebccf1e3SJoseph Koshy 
4108ebccf1e3SJoseph Koshy 		/* now copy out the PMC info collected */
4109ebccf1e3SJoseph Koshy 		if (error == 0)
4110ebccf1e3SJoseph Koshy 			error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
4111ebccf1e3SJoseph Koshy 
41121ede983cSDag-Erling Smørgrav 		free(pmcinfo, M_PMC);
4113ebccf1e3SJoseph Koshy 	}
4114ebccf1e3SJoseph Koshy 	break;
4115ebccf1e3SJoseph Koshy 
4116ebccf1e3SJoseph Koshy 
4117ebccf1e3SJoseph Koshy 	/*
4118ebccf1e3SJoseph Koshy 	 * Set the administrative state of a PMC.  I.e. whether
4119ebccf1e3SJoseph Koshy 	 * the PMC is to be used or not.
4120ebccf1e3SJoseph Koshy 	 */
4121ebccf1e3SJoseph Koshy 
4122ebccf1e3SJoseph Koshy 	case PMC_OP_PMCADMIN:
4123ebccf1e3SJoseph Koshy 	{
4124ebccf1e3SJoseph Koshy 		int cpu, ri;
4125ebccf1e3SJoseph Koshy 		enum pmc_state request;
4126ebccf1e3SJoseph Koshy 		struct pmc_cpu *pc;
4127ebccf1e3SJoseph Koshy 		struct pmc_hw *phw;
4128ebccf1e3SJoseph Koshy 		struct pmc_op_pmcadmin pma;
4129ebccf1e3SJoseph Koshy 		struct pmc_binding pb;
4130ebccf1e3SJoseph Koshy 
4131ebccf1e3SJoseph Koshy 		sx_assert(&pmc_sx, SX_XLOCKED);
4132ebccf1e3SJoseph Koshy 
4133ebccf1e3SJoseph Koshy 		KASSERT(td == curthread,
4134ebccf1e3SJoseph Koshy 		    ("[pmc,%d] td != curthread", __LINE__));
4135ebccf1e3SJoseph Koshy 
4136acd3428bSRobert Watson 		error = priv_check(td, PRIV_PMC_MANAGE);
4137acd3428bSRobert Watson 		if (error)
4138ebccf1e3SJoseph Koshy 			break;
4139ebccf1e3SJoseph Koshy 
4140ebccf1e3SJoseph Koshy 		if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
4141ebccf1e3SJoseph Koshy 			break;
4142ebccf1e3SJoseph Koshy 
4143ebccf1e3SJoseph Koshy 		cpu = pma.pm_cpu;
4144ebccf1e3SJoseph Koshy 
4145122ccdc1SJoseph Koshy 		if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
4146ebccf1e3SJoseph Koshy 			error = EINVAL;
4147ebccf1e3SJoseph Koshy 			break;
4148ebccf1e3SJoseph Koshy 		}
4149ebccf1e3SJoseph Koshy 
4150122ccdc1SJoseph Koshy 		if (!pmc_cpu_is_active(cpu)) {
4151ebccf1e3SJoseph Koshy 			error = ENXIO;
4152ebccf1e3SJoseph Koshy 			break;
4153ebccf1e3SJoseph Koshy 		}
4154ebccf1e3SJoseph Koshy 
4155ebccf1e3SJoseph Koshy 		request = pma.pm_state;
4156ebccf1e3SJoseph Koshy 
4157ebccf1e3SJoseph Koshy 		if (request != PMC_STATE_DISABLED &&
4158ebccf1e3SJoseph Koshy 		    request != PMC_STATE_FREE) {
4159ebccf1e3SJoseph Koshy 			error = EINVAL;
4160ebccf1e3SJoseph Koshy 			break;
4161ebccf1e3SJoseph Koshy 		}
4162ebccf1e3SJoseph Koshy 
4163ebccf1e3SJoseph Koshy 		ri = pma.pm_pmc; /* pmc id == row index */
4164ebccf1e3SJoseph Koshy 		if (ri < 0 || ri >= (int) md->pmd_npmc) {
4165ebccf1e3SJoseph Koshy 			error = EINVAL;
4166ebccf1e3SJoseph Koshy 			break;
4167ebccf1e3SJoseph Koshy 		}
4168ebccf1e3SJoseph Koshy 
4169ebccf1e3SJoseph Koshy 		/*
4170ebccf1e3SJoseph Koshy 		 * We can't disable a PMC with a row-index allocated
4171ebccf1e3SJoseph Koshy 		 * for process virtual PMCs.
4172ebccf1e3SJoseph Koshy 		 */
4173ebccf1e3SJoseph Koshy 
4174ebccf1e3SJoseph Koshy 		if (PMC_ROW_DISP_IS_THREAD(ri) &&
4175ebccf1e3SJoseph Koshy 		    request == PMC_STATE_DISABLED) {
4176ebccf1e3SJoseph Koshy 			error = EBUSY;
4177ebccf1e3SJoseph Koshy 			break;
4178ebccf1e3SJoseph Koshy 		}
4179ebccf1e3SJoseph Koshy 
4180ebccf1e3SJoseph Koshy 		/*
4181ebccf1e3SJoseph Koshy 		 * otherwise, this PMC on this CPU is either free or
4182ebccf1e3SJoseph Koshy 		 * in system-wide mode.
4183ebccf1e3SJoseph Koshy 		 */
4184ebccf1e3SJoseph Koshy 
4185ebccf1e3SJoseph Koshy 		pmc_save_cpu_binding(&pb);
4186ebccf1e3SJoseph Koshy 		pmc_select_cpu(cpu);
4187ebccf1e3SJoseph Koshy 
4188ebccf1e3SJoseph Koshy 		pc  = pmc_pcpu[cpu];
4189ebccf1e3SJoseph Koshy 		phw = pc->pc_hwpmcs[ri];
4190ebccf1e3SJoseph Koshy 
4191ebccf1e3SJoseph Koshy 		/*
4192ebccf1e3SJoseph Koshy 		 * XXX do we need some kind of 'forced' disable?
4193ebccf1e3SJoseph Koshy 		 */
4194ebccf1e3SJoseph Koshy 
4195ebccf1e3SJoseph Koshy 		if (phw->phw_pmc == NULL) {
4196ebccf1e3SJoseph Koshy 			if (request == PMC_STATE_DISABLED &&
4197ebccf1e3SJoseph Koshy 			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
4198ebccf1e3SJoseph Koshy 				phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
4199ebccf1e3SJoseph Koshy 				PMC_MARK_ROW_STANDALONE(ri);
4200ebccf1e3SJoseph Koshy 			} else if (request == PMC_STATE_FREE &&
4201ebccf1e3SJoseph Koshy 			    (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
4202ebccf1e3SJoseph Koshy 				phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
4203ebccf1e3SJoseph Koshy 				PMC_UNMARK_ROW_STANDALONE(ri);
4204ebccf1e3SJoseph Koshy 			}
4205ebccf1e3SJoseph Koshy 			/* other cases are a no-op */
4206ebccf1e3SJoseph Koshy 		} else
4207ebccf1e3SJoseph Koshy 			error = EBUSY;
4208ebccf1e3SJoseph Koshy 
4209ebccf1e3SJoseph Koshy 		pmc_restore_cpu_binding(&pb);
4210ebccf1e3SJoseph Koshy 	}
4211ebccf1e3SJoseph Koshy 	break;
4212ebccf1e3SJoseph Koshy 
4213ebccf1e3SJoseph Koshy 
4214ebccf1e3SJoseph Koshy 	/*
4215ebccf1e3SJoseph Koshy 	 * Allocate a PMC.
4216ebccf1e3SJoseph Koshy 	 */
4217ebccf1e3SJoseph Koshy 	case PMC_OP_PMCALLOCATE:
4218ebccf1e3SJoseph Koshy 	{
4219e829eb6dSJoseph Koshy 		struct pmc_op_pmcallocate pa;
4220ebccf1e3SJoseph Koshy 
4221c514a571SMitchell Horne 		error = copyin(arg, &pa, sizeof(pa));
4222c514a571SMitchell Horne 		if (error != 0)
4223ebccf1e3SJoseph Koshy 			break;
4224ebccf1e3SJoseph Koshy 
4225c514a571SMitchell Horne 		error = pmc_do_op_pmcallocate(td, &pa);
4226c514a571SMitchell Horne 		if (error != 0)
4227ebccf1e3SJoseph Koshy 			break;
4228ebccf1e3SJoseph Koshy 
4229ebccf1e3SJoseph Koshy 		error = copyout(&pa, arg, sizeof(pa));
4230ebccf1e3SJoseph Koshy 	}
4231ebccf1e3SJoseph Koshy 	break;
4232ebccf1e3SJoseph Koshy 
4233ebccf1e3SJoseph Koshy 	/*
4234ebccf1e3SJoseph Koshy 	 * Attach a PMC to a process.
4235ebccf1e3SJoseph Koshy 	 */
4236ebccf1e3SJoseph Koshy 	case PMC_OP_PMCATTACH:
4237ebccf1e3SJoseph Koshy 	{
4238ebccf1e3SJoseph Koshy 		struct pmc_op_pmcattach a;
4239ebccf1e3SJoseph Koshy 
4240a133f642SMitchell Horne 		error = copyin(arg, &a, sizeof(a));
4241a133f642SMitchell Horne 		if (error != 0)
4242ebccf1e3SJoseph Koshy 			break;
4243ebccf1e3SJoseph Koshy 
4244a133f642SMitchell Horne 		error = pmc_do_op_pmcattach(td, a);
4245ebccf1e3SJoseph Koshy 	}
4246ebccf1e3SJoseph Koshy 	break;
4247ebccf1e3SJoseph Koshy 
4248ebccf1e3SJoseph Koshy 	/*
4249ebccf1e3SJoseph Koshy 	 * Detach an attached PMC from a process.
4250ebccf1e3SJoseph Koshy 	 */
4251ebccf1e3SJoseph Koshy 	case PMC_OP_PMCDETACH:
4252ebccf1e3SJoseph Koshy 	{
4253ebccf1e3SJoseph Koshy 		struct pmc_op_pmcattach a;
4254ebccf1e3SJoseph Koshy 
4255a133f642SMitchell Horne 		error = copyin(arg, &a, sizeof(a));
4256a133f642SMitchell Horne 		if (error != 0)
4257ebccf1e3SJoseph Koshy 			break;
4258ebccf1e3SJoseph Koshy 
4259a133f642SMitchell Horne 		error = pmc_do_op_pmcdetach(td, a);
4260ebccf1e3SJoseph Koshy 	}
4261ebccf1e3SJoseph Koshy 	break;
4262ebccf1e3SJoseph Koshy 
4263ebccf1e3SJoseph Koshy 
4264ebccf1e3SJoseph Koshy 	/*
4265f263522aSJoseph Koshy 	 * Retrieve the MSR number associated with the counter
4266f263522aSJoseph Koshy 	 * 'pmc_id'.  This allows processes to directly use RDPMC
4267f263522aSJoseph Koshy 	 * instructions to read their PMCs, without the overhead of a
4268f263522aSJoseph Koshy 	 * system call.
4269f263522aSJoseph Koshy 	 */
4270f263522aSJoseph Koshy 
4271f263522aSJoseph Koshy 	case PMC_OP_PMCGETMSR:
4272f263522aSJoseph Koshy 	{
4273e829eb6dSJoseph Koshy 		int adjri, ri;
4274f263522aSJoseph Koshy 		struct pmc *pm;
4275f263522aSJoseph Koshy 		struct pmc_target *pt;
4276f263522aSJoseph Koshy 		struct pmc_op_getmsr gm;
4277e829eb6dSJoseph Koshy 		struct pmc_classdep *pcd;
4278f263522aSJoseph Koshy 
4279f263522aSJoseph Koshy 		PMC_DOWNGRADE_SX();
4280f263522aSJoseph Koshy 
4281f263522aSJoseph Koshy 		if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
4282f263522aSJoseph Koshy 			break;
4283f263522aSJoseph Koshy 
4284f263522aSJoseph Koshy 		if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
4285f263522aSJoseph Koshy 			break;
4286f263522aSJoseph Koshy 
4287f263522aSJoseph Koshy 		/*
4288f263522aSJoseph Koshy 		 * The allocated PMC has to be a process virtual PMC,
4289f263522aSJoseph Koshy 		 * i.e., of type MODE_T[CS].  Global PMCs can only be
4290f263522aSJoseph Koshy 		 * read using the PMCREAD operation since they may be
4291f263522aSJoseph Koshy 		 * allocated on a different CPU than the one we could
4292f263522aSJoseph Koshy 		 * be running on at the time of the RDPMC instruction.
4293f263522aSJoseph Koshy 		 *
4294f263522aSJoseph Koshy 		 * The GETMSR operation is not allowed for PMCs that
4295f263522aSJoseph Koshy 		 * are inherited across processes.
4296f263522aSJoseph Koshy 		 */
4297f263522aSJoseph Koshy 
4298f263522aSJoseph Koshy 		if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
4299f263522aSJoseph Koshy 		    (pm->pm_flags & PMC_F_DESCENDANTS)) {
4300f263522aSJoseph Koshy 			error = EINVAL;
4301f263522aSJoseph Koshy 			break;
4302f263522aSJoseph Koshy 		}
4303f263522aSJoseph Koshy 
4304f263522aSJoseph Koshy 		/*
4305f263522aSJoseph Koshy 		 * It only makes sense to use a RDPMC (or its
4306f263522aSJoseph Koshy 		 * equivalent instruction on non-x86 architectures) on
4307f263522aSJoseph Koshy 		 * a process that has allocated and attached a PMC to
4308f263522aSJoseph Koshy 		 * itself.  Conversely the PMC is only allowed to have
4309f263522aSJoseph Koshy 		 * one process attached to it -- its owner.
4310f263522aSJoseph Koshy 		 */
4311f263522aSJoseph Koshy 
4312f263522aSJoseph Koshy 		if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
4313f263522aSJoseph Koshy 		    LIST_NEXT(pt, pt_next) != NULL ||
4314f263522aSJoseph Koshy 		    pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
4315f263522aSJoseph Koshy 			error = EINVAL;
4316f263522aSJoseph Koshy 			break;
4317f263522aSJoseph Koshy 		}
4318f263522aSJoseph Koshy 
4319f263522aSJoseph Koshy 		ri = PMC_TO_ROWINDEX(pm);
4320e829eb6dSJoseph Koshy 		pcd = pmc_ri_to_classdep(md, ri, &adjri);
4321f263522aSJoseph Koshy 
4322e829eb6dSJoseph Koshy 		/* PMC class has no 'GETMSR' support */
4323e829eb6dSJoseph Koshy 		if (pcd->pcd_get_msr == NULL) {
4324e829eb6dSJoseph Koshy 			error = ENOSYS;
4325e829eb6dSJoseph Koshy 			break;
4326e829eb6dSJoseph Koshy 		}
4327e829eb6dSJoseph Koshy 
4328e829eb6dSJoseph Koshy 		if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
4329f263522aSJoseph Koshy 			break;
4330f263522aSJoseph Koshy 
4331f263522aSJoseph Koshy 		if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
4332f263522aSJoseph Koshy 			break;
4333f263522aSJoseph Koshy 
4334f263522aSJoseph Koshy 		/*
4335f263522aSJoseph Koshy 		 * Mark our process as using MSRs.  Update machine
4336f263522aSJoseph Koshy 		 * state using a forced context switch.
4337f263522aSJoseph Koshy 		 */
4338f263522aSJoseph Koshy 
4339f263522aSJoseph Koshy 		pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
4340f263522aSJoseph Koshy 		pmc_force_context_switch();
4341f263522aSJoseph Koshy 
4342f263522aSJoseph Koshy 	}
4343f263522aSJoseph Koshy 	break;
4344f263522aSJoseph Koshy 
4345f263522aSJoseph Koshy 	/*
4346f4fac946SMitchell Horne 	 * Release an allocated PMC.
4347ebccf1e3SJoseph Koshy 	 */
4348ebccf1e3SJoseph Koshy 	case PMC_OP_PMCRELEASE:
4349ebccf1e3SJoseph Koshy 	{
4350ebccf1e3SJoseph Koshy 		struct pmc_op_simple sp;
4351ebccf1e3SJoseph Koshy 
4352f4fac946SMitchell Horne 		error = copyin(arg, &sp, sizeof(sp));
4353f4fac946SMitchell Horne 		if (error != 0)
4354ebccf1e3SJoseph Koshy 			break;
4355ebccf1e3SJoseph Koshy 
4356f4fac946SMitchell Horne 		error = pmc_do_op_pmcrelease(sp.pm_pmcid);
4357ebccf1e3SJoseph Koshy 	}
4358ebccf1e3SJoseph Koshy 	break;
4359ebccf1e3SJoseph Koshy 
4360ebccf1e3SJoseph Koshy 	/*
4361ebccf1e3SJoseph Koshy 	 * Read and/or write a PMC.
4362ebccf1e3SJoseph Koshy 	 */
4363ebccf1e3SJoseph Koshy 	case PMC_OP_PMCRW:
4364ebccf1e3SJoseph Koshy 	{
4365e829eb6dSJoseph Koshy 		struct pmc_op_pmcrw prw;
4366e829eb6dSJoseph Koshy 		struct pmc_op_pmcrw *pprw;
436793fe5909SMitchell Horne 		pmc_value_t oldvalue;
4368ebccf1e3SJoseph Koshy 
4369ebccf1e3SJoseph Koshy 		PMC_DOWNGRADE_SX();
4370ebccf1e3SJoseph Koshy 
437193fe5909SMitchell Horne 		error = copyin(arg, &prw, sizeof(prw));
437293fe5909SMitchell Horne 		if (error != 0)
4373ebccf1e3SJoseph Koshy 			break;
4374ebccf1e3SJoseph Koshy 
437593fe5909SMitchell Horne 		error = pmc_do_op_pmcrw(&prw, &oldvalue);
437693fe5909SMitchell Horne 		if (error != 0)
4377ebccf1e3SJoseph Koshy 			break;
437893fe5909SMitchell Horne 
437993fe5909SMitchell Horne 		/* Return old value if requested. */
438093fe5909SMitchell Horne 		if ((prw.pm_flags & PMC_F_OLDVALUE) != 0) {
438193fe5909SMitchell Horne 			pprw = arg;
438293fe5909SMitchell Horne 			error = copyout(&oldvalue, &pprw->pm_value,
438393fe5909SMitchell Horne 			    sizeof(prw.pm_value));
4384ebccf1e3SJoseph Koshy 		}
4385ebccf1e3SJoseph Koshy 	}
4386ebccf1e3SJoseph Koshy 	break;
4387ebccf1e3SJoseph Koshy 
4388ebccf1e3SJoseph Koshy 
4389ebccf1e3SJoseph Koshy 	/*
4390ebccf1e3SJoseph Koshy 	 * Set the sampling rate for a sampling mode PMC and the
4391ebccf1e3SJoseph Koshy 	 * initial count for a counting mode PMC.
4392ebccf1e3SJoseph Koshy 	 */
4393ebccf1e3SJoseph Koshy 
4394ebccf1e3SJoseph Koshy 	case PMC_OP_PMCSETCOUNT:
4395ebccf1e3SJoseph Koshy 	{
4396ebccf1e3SJoseph Koshy 		struct pmc *pm;
4397ebccf1e3SJoseph Koshy 		struct pmc_op_pmcsetcount sc;
4398ebccf1e3SJoseph Koshy 
4399ebccf1e3SJoseph Koshy 		PMC_DOWNGRADE_SX();
4400ebccf1e3SJoseph Koshy 
4401ebccf1e3SJoseph Koshy 		if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
4402ebccf1e3SJoseph Koshy 			break;
4403ebccf1e3SJoseph Koshy 
4404ebccf1e3SJoseph Koshy 		if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
4405ebccf1e3SJoseph Koshy 			break;
4406ebccf1e3SJoseph Koshy 
4407ebccf1e3SJoseph Koshy 		if (pm->pm_state == PMC_STATE_RUNNING) {
4408ebccf1e3SJoseph Koshy 			error = EBUSY;
4409ebccf1e3SJoseph Koshy 			break;
4410ebccf1e3SJoseph Koshy 		}
4411ebccf1e3SJoseph Koshy 
44120204d85aSMatt Macy 		if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
44130204d85aSMatt Macy 			/*
4414ca341f3cSJohn Baldwin 			 * Don't permit requested sample rate to be
4415ca341f3cSJohn Baldwin 			 * less than pmc_mincount.
44160204d85aSMatt Macy 			 */
4417ca341f3cSJohn Baldwin 			if (sc.pm_count < MAX(1, pmc_mincount))
4418ca341f3cSJohn Baldwin 				log(LOG_WARNING, "pmcsetcount: passed sample "
4419ca341f3cSJohn Baldwin 				    "rate %ju - setting to %u\n",
4420ca341f3cSJohn Baldwin 				    (uintmax_t)sc.pm_count,
4421ca341f3cSJohn Baldwin 				    MAX(1, pmc_mincount));
4422ca341f3cSJohn Baldwin 			pm->pm_sc.pm_reloadcount = MAX(MAX(1, pmc_mincount),
4423ca341f3cSJohn Baldwin 			    sc.pm_count);
44240204d85aSMatt Macy 		} else
4425ebccf1e3SJoseph Koshy 			pm->pm_sc.pm_initial = sc.pm_count;
4426ebccf1e3SJoseph Koshy 	}
4427ebccf1e3SJoseph Koshy 	break;
4428ebccf1e3SJoseph Koshy 
4429ebccf1e3SJoseph Koshy 
4430ebccf1e3SJoseph Koshy 	/*
4431ebccf1e3SJoseph Koshy 	 * Start a PMC.
4432ebccf1e3SJoseph Koshy 	 */
4433ebccf1e3SJoseph Koshy 
4434ebccf1e3SJoseph Koshy 	case PMC_OP_PMCSTART:
4435ebccf1e3SJoseph Koshy 	{
4436ebccf1e3SJoseph Koshy 		pmc_id_t pmcid;
4437ebccf1e3SJoseph Koshy 		struct pmc *pm;
4438ebccf1e3SJoseph Koshy 		struct pmc_op_simple sp;
4439ebccf1e3SJoseph Koshy 
4440ebccf1e3SJoseph Koshy 		sx_assert(&pmc_sx, SX_XLOCKED);
4441ebccf1e3SJoseph Koshy 
4442ebccf1e3SJoseph Koshy 		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4443ebccf1e3SJoseph Koshy 			break;
4444ebccf1e3SJoseph Koshy 
4445ebccf1e3SJoseph Koshy 		pmcid = sp.pm_pmcid;
4446ebccf1e3SJoseph Koshy 
4447ebccf1e3SJoseph Koshy 		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4448ebccf1e3SJoseph Koshy 			break;
4449ebccf1e3SJoseph Koshy 
4450c5153e19SJoseph Koshy 		KASSERT(pmcid == pm->pm_id,
4451c5153e19SJoseph Koshy 		    ("[pmc,%d] pmcid %x != id %x", __LINE__,
4452c5153e19SJoseph Koshy 			pm->pm_id, pmcid));
4453ebccf1e3SJoseph Koshy 
4454ebccf1e3SJoseph Koshy 		if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
4455ebccf1e3SJoseph Koshy 			break;
4456ebccf1e3SJoseph Koshy 		else if (pm->pm_state != PMC_STATE_STOPPED &&
4457ebccf1e3SJoseph Koshy 		    pm->pm_state != PMC_STATE_ALLOCATED) {
4458ebccf1e3SJoseph Koshy 			error = EINVAL;
4459ebccf1e3SJoseph Koshy 			break;
4460ebccf1e3SJoseph Koshy 		}
4461ebccf1e3SJoseph Koshy 
4462ebccf1e3SJoseph Koshy 		error = pmc_start(pm);
4463ebccf1e3SJoseph Koshy 	}
4464ebccf1e3SJoseph Koshy 	break;
4465ebccf1e3SJoseph Koshy 
4466ebccf1e3SJoseph Koshy 
4467ebccf1e3SJoseph Koshy 	/*
4468ebccf1e3SJoseph Koshy 	 * Stop a PMC.
4469ebccf1e3SJoseph Koshy 	 */
4470ebccf1e3SJoseph Koshy 
4471ebccf1e3SJoseph Koshy 	case PMC_OP_PMCSTOP:
4472ebccf1e3SJoseph Koshy 	{
4473ebccf1e3SJoseph Koshy 		pmc_id_t pmcid;
4474ebccf1e3SJoseph Koshy 		struct pmc *pm;
4475ebccf1e3SJoseph Koshy 		struct pmc_op_simple sp;
4476ebccf1e3SJoseph Koshy 
4477ebccf1e3SJoseph Koshy 		PMC_DOWNGRADE_SX();
4478ebccf1e3SJoseph Koshy 
4479ebccf1e3SJoseph Koshy 		if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4480ebccf1e3SJoseph Koshy 			break;
4481ebccf1e3SJoseph Koshy 
4482ebccf1e3SJoseph Koshy 		pmcid = sp.pm_pmcid;
4483ebccf1e3SJoseph Koshy 
4484ebccf1e3SJoseph Koshy 		/*
4485ebccf1e3SJoseph Koshy 		 * Mark the PMC as inactive and invoke the MD stop
4486ebccf1e3SJoseph Koshy 		 * routines if needed.
4487ebccf1e3SJoseph Koshy 		 */
4488ebccf1e3SJoseph Koshy 
4489ebccf1e3SJoseph Koshy 		if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4490ebccf1e3SJoseph Koshy 			break;
4491ebccf1e3SJoseph Koshy 
4492c5153e19SJoseph Koshy 		KASSERT(pmcid == pm->pm_id,
4493c5153e19SJoseph Koshy 		    ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
4494c5153e19SJoseph Koshy 			pm->pm_id, pmcid));
4495ebccf1e3SJoseph Koshy 
4496ebccf1e3SJoseph Koshy 		if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
4497ebccf1e3SJoseph Koshy 			break;
4498ebccf1e3SJoseph Koshy 		else if (pm->pm_state != PMC_STATE_RUNNING) {
4499ebccf1e3SJoseph Koshy 			error = EINVAL;
4500ebccf1e3SJoseph Koshy 			break;
4501ebccf1e3SJoseph Koshy 		}
4502ebccf1e3SJoseph Koshy 
4503ebccf1e3SJoseph Koshy 		error = pmc_stop(pm);
4504ebccf1e3SJoseph Koshy 	}
4505ebccf1e3SJoseph Koshy 	break;
4506ebccf1e3SJoseph Koshy 
4507ebccf1e3SJoseph Koshy 
4508ebccf1e3SJoseph Koshy 	/*
4509fbf1556dSJoseph Koshy 	 * Write a user supplied value to the log file.
4510ebccf1e3SJoseph Koshy 	 */
4511ebccf1e3SJoseph Koshy 
4512ebccf1e3SJoseph Koshy 	case PMC_OP_WRITELOG:
4513ebccf1e3SJoseph Koshy 	{
4514f263522aSJoseph Koshy 		struct pmc_op_writelog wl;
4515f263522aSJoseph Koshy 		struct pmc_owner *po;
4516ebccf1e3SJoseph Koshy 
4517ebccf1e3SJoseph Koshy 		PMC_DOWNGRADE_SX();
4518ebccf1e3SJoseph Koshy 
4519f263522aSJoseph Koshy 		if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
4520ebccf1e3SJoseph Koshy 			break;
4521ebccf1e3SJoseph Koshy 
4522f263522aSJoseph Koshy 		if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
4523ebccf1e3SJoseph Koshy 			error = EINVAL;
4524ebccf1e3SJoseph Koshy 			break;
4525ebccf1e3SJoseph Koshy 		}
4526ebccf1e3SJoseph Koshy 
4527f263522aSJoseph Koshy 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
4528c5153e19SJoseph Koshy 			error = EINVAL;
4529c5153e19SJoseph Koshy 			break;
4530c5153e19SJoseph Koshy 		}
4531c5153e19SJoseph Koshy 
4532f263522aSJoseph Koshy 		error = pmclog_process_userlog(po, &wl);
4533ebccf1e3SJoseph Koshy 	}
4534ebccf1e3SJoseph Koshy 	break;
4535f263522aSJoseph Koshy 
4536ebccf1e3SJoseph Koshy 
4537ebccf1e3SJoseph Koshy 	default:
4538ebccf1e3SJoseph Koshy 		error = EINVAL;
4539ebccf1e3SJoseph Koshy 		break;
4540ebccf1e3SJoseph Koshy 	}
4541ebccf1e3SJoseph Koshy 
4542ebccf1e3SJoseph Koshy 	if (is_sx_downgraded)
4543ebccf1e3SJoseph Koshy 		sx_sunlock(&pmc_sx);
4544ebccf1e3SJoseph Koshy 	else
4545ebccf1e3SJoseph Koshy 		sx_xunlock(&pmc_sx);
454620b555e1SKonstantin Belousov done_syscall:
4547ebccf1e3SJoseph Koshy 	if (error)
4548e6b475e0SMatt Macy 		counter_u64_add(pmc_stats.pm_syscall_errors, 1);
4549ebccf1e3SJoseph Koshy 
4550cf9ef806SKonstantin Belousov 	return (error);
4551ebccf1e3SJoseph Koshy }
4552ebccf1e3SJoseph Koshy 
4553ebccf1e3SJoseph Koshy /*
4554ebccf1e3SJoseph Koshy  * Helper functions
4555ebccf1e3SJoseph Koshy  */
4556ebccf1e3SJoseph Koshy 
4557ebccf1e3SJoseph Koshy /*
4558d07f36b0SJoseph Koshy  * Mark the thread as needing callchain capture and post an AST.  The
4559d07f36b0SJoseph Koshy  * actual callchain capture will be done in a context where it is safe
4560d07f36b0SJoseph Koshy  * to take page faults.
4561d07f36b0SJoseph Koshy  */
4562d07f36b0SJoseph Koshy static void
45636fe00c78SJoseph Koshy pmc_post_callchain_callback(void)
4564d07f36b0SJoseph Koshy {
4565d07f36b0SJoseph Koshy 	struct thread *td;
4566d07f36b0SJoseph Koshy 
4567d07f36b0SJoseph Koshy 	td = curthread;
4568d07f36b0SJoseph Koshy 
45690e031404SFabien Thomas 	/*
45700e031404SFabien Thomas 	 * If there is multiple PMCs for the same interrupt ignore new post
45710e031404SFabien Thomas 	 */
4572d5ee4074SMitchell Horne 	if ((td->td_pflags & TDP_CALLCHAIN) != 0)
45730e031404SFabien Thomas 		return;
45746fe00c78SJoseph Koshy 
4575d07f36b0SJoseph Koshy 	/*
45766fe00c78SJoseph Koshy 	 * Mark this thread as needing callchain capture.
45776fe00c78SJoseph Koshy 	 * `td->td_pflags' will be safe to touch because this thread
45786fe00c78SJoseph Koshy 	 * was in user space when it was interrupted.
4579d07f36b0SJoseph Koshy 	 */
4580d07f36b0SJoseph Koshy 	td->td_pflags |= TDP_CALLCHAIN;
4581d07f36b0SJoseph Koshy 
4582d07f36b0SJoseph Koshy 	/*
45836fe00c78SJoseph Koshy 	 * Don't let this thread migrate between CPUs until callchain
45846fe00c78SJoseph Koshy 	 * capture completes.
4585d07f36b0SJoseph Koshy 	 */
45866fe00c78SJoseph Koshy 	sched_pin();
4587d07f36b0SJoseph Koshy 
4588d07f36b0SJoseph Koshy 	return;
4589d07f36b0SJoseph Koshy }
4590d07f36b0SJoseph Koshy 
4591d07f36b0SJoseph Koshy /*
4592d07f36b0SJoseph Koshy  * Find a free slot in the per-cpu array of samples and capture the
4593d07f36b0SJoseph Koshy  * current callchain there.  If a sample was successfully added, a bit
4594d07f36b0SJoseph Koshy  * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4595d07f36b0SJoseph Koshy  * needs to be invoked from the clock handler.
4596f263522aSJoseph Koshy  *
4597f263522aSJoseph Koshy  * This function is meant to be called from an NMI handler.  It cannot
4598f263522aSJoseph Koshy  * use any of the locking primitives supplied by the OS.
4599ebccf1e3SJoseph Koshy  */
46005de96e33SMatt Macy static int
4601d9f1b8dbSMatt Macy pmc_add_sample(ring_type_t ring, struct pmc *pm, struct trapframe *tf)
4602ebccf1e3SJoseph Koshy {
4603f263522aSJoseph Koshy 	struct pmc_sample *ps;
4604f263522aSJoseph Koshy 	struct pmc_samplebuffer *psb;
460501c35b67SMitchell Horne 	struct thread *td;
460601c35b67SMitchell Horne 	int error, cpu, callchaindepth;
460701c35b67SMitchell Horne 	bool inuserspace;
4608ebccf1e3SJoseph Koshy 
4609f263522aSJoseph Koshy 	error = 0;
4610ebccf1e3SJoseph Koshy 
4611d07f36b0SJoseph Koshy 	/*
4612d07f36b0SJoseph Koshy 	 * Allocate space for a sample buffer.
4613d07f36b0SJoseph Koshy 	 */
4614eb7c9019SMatt Macy 	cpu = curcpu;
4615f5f9340bSFabien Thomas 	psb = pmc_pcpu[cpu]->pc_sb[ring];
4616eb7c9019SMatt Macy 	inuserspace = TRAPF_USERMODE(tf);
4617d9f1b8dbSMatt Macy 	ps = PMC_PROD_SAMPLE(psb);
4618d9f1b8dbSMatt Macy 	if (psb->ps_considx != psb->ps_prodidx &&
4619d9f1b8dbSMatt Macy 		ps->ps_nsamples) {	/* in use, reader hasn't caught up */
4620e6b475e0SMatt Macy 		pm->pm_pcpu_state[cpu].pps_stalled = 1;
4621e6b475e0SMatt Macy 		counter_u64_add(pmc_stats.pm_intr_bufferfull, 1);
46224a3690dfSJohn Baldwin 		PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
462301c35b67SMitchell Horne 		    cpu, pm, tf, inuserspace,
4624d9f1b8dbSMatt Macy 		    (int)(psb->ps_prodidx & pmc_sample_mask),
4625d9f1b8dbSMatt Macy 		    (int)(psb->ps_considx & pmc_sample_mask));
4626c66ea2eeSJonathan T. Looney 		callchaindepth = 1;
4627f263522aSJoseph Koshy 		error = ENOMEM;
4628f263522aSJoseph Koshy 		goto done;
4629ebccf1e3SJoseph Koshy 	}
4630ebccf1e3SJoseph Koshy 
4631d07f36b0SJoseph Koshy 	/* Fill in entry. */
4632693cd307SMitchell Horne 	PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm, tf,
4633693cd307SMitchell Horne 	    inuserspace, (int)(psb->ps_prodidx & pmc_sample_mask),
4634d9f1b8dbSMatt Macy 	    (int)(psb->ps_considx & pmc_sample_mask));
4635f5f9340bSFabien Thomas 
4636cf823003SMatt Macy 	td = curthread;
4637f263522aSJoseph Koshy 	ps->ps_pmc = pm;
46386fe00c78SJoseph Koshy 	ps->ps_td = td;
4639cf823003SMatt Macy 	ps->ps_pid = td->td_proc->p_pid;
4640cf823003SMatt Macy 	ps->ps_tid = td->td_tid;
4641f992dd4bSMatt Macy 	ps->ps_tsc = pmc_rdtsc();
4642d9f1b8dbSMatt Macy 	ps->ps_ticks = ticks;
4643cf823003SMatt Macy 	ps->ps_cpu = cpu;
4644d07f36b0SJoseph Koshy 	ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4645d07f36b0SJoseph Koshy 
4646d07f36b0SJoseph Koshy 	callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4647d07f36b0SJoseph Koshy 	    pmc_callchaindepth : 1;
4648d07f36b0SJoseph Koshy 
4649d9f1b8dbSMatt Macy 	MPASS(ps->ps_pc != NULL);
4650d5ee4074SMitchell Horne 	if (callchaindepth == 1) {
4651d07f36b0SJoseph Koshy 		ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
4652d5ee4074SMitchell Horne 	} else {
4653d07f36b0SJoseph Koshy 		/*
465401c35b67SMitchell Horne 		 * Kernel stack traversals can be done immediately, while we
465501c35b67SMitchell Horne 		 * defer to an AST for user space traversals.
4656d07f36b0SJoseph Koshy 		 */
4657f5f9340bSFabien Thomas 		if (!inuserspace) {
4658693cd307SMitchell Horne 			callchaindepth = pmc_save_kernel_callchain(ps->ps_pc,
4659d07f36b0SJoseph Koshy 			    callchaindepth, tf);
4660f5f9340bSFabien Thomas 		} else {
46616fe00c78SJoseph Koshy 			pmc_post_callchain_callback();
4662d9f1b8dbSMatt Macy 			callchaindepth = PMC_USER_CALLCHAIN_PENDING;
4663d07f36b0SJoseph Koshy 		}
4664d07f36b0SJoseph Koshy 	}
4665d07f36b0SJoseph Koshy 
4666d5ee4074SMitchell Horne 	ps->ps_nsamples = callchaindepth; /* mark entry as in-use */
46675de96e33SMatt Macy 	if (ring == PMC_UR) {
4668d5ee4074SMitchell Horne 		ps->ps_nsamples_actual = callchaindepth;
4669d9f1b8dbSMatt Macy 		ps->ps_nsamples = PMC_USER_CALLCHAIN_PENDING;
4670d5ee4074SMitchell Horne 	}
4671f263522aSJoseph Koshy 
4672d9f1b8dbSMatt Macy 	KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
467301c35b67SMitchell Horne 	    ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
467401c35b67SMitchell Horne 	    (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
4675d9f1b8dbSMatt Macy 
4676d9f1b8dbSMatt Macy 	counter_u64_add(pm->pm_runcount, 1);	/* hold onto PMC */
4677d9f1b8dbSMatt Macy 	/* increment write pointer */
4678d9f1b8dbSMatt Macy 	psb->ps_prodidx++;
4679f263522aSJoseph Koshy done:
4680f263522aSJoseph Koshy 	/* mark CPU as needing processing */
4681d9f1b8dbSMatt Macy 	if (callchaindepth != PMC_USER_CALLCHAIN_PENDING)
4682e6b475e0SMatt Macy 		DPCPU_SET(pmc_sampled, 1);
4683f263522aSJoseph Koshy 
4684d07f36b0SJoseph Koshy 	return (error);
4685d07f36b0SJoseph Koshy }
4686d07f36b0SJoseph Koshy 
4687d07f36b0SJoseph Koshy /*
46885de96e33SMatt Macy  * Interrupt processing.
46895de96e33SMatt Macy  *
469001c35b67SMitchell Horne  * This function may be called from an NMI handler. It cannot use any of the
469101c35b67SMitchell Horne  * locking primitives supplied by the OS.
46925de96e33SMatt Macy  */
46935de96e33SMatt Macy int
4694eb7c9019SMatt Macy pmc_process_interrupt(int ring, struct pmc *pm, struct trapframe *tf)
46955de96e33SMatt Macy {
46965de96e33SMatt Macy 	struct thread *td;
46975de96e33SMatt Macy 
46985de96e33SMatt Macy 	td = curthread;
46995de96e33SMatt Macy 	if ((pm->pm_flags & PMC_F_USERCALLCHAIN) &&
4700d5ee4074SMitchell Horne 	    (td->td_proc->p_flag & P_KPROC) == 0 && !TRAPF_USERMODE(tf)) {
4701a9336cefSMark Johnston 		atomic_add_int(&td->td_pmcpend, 1);
4702eb7c9019SMatt Macy 		return (pmc_add_sample(PMC_UR, pm, tf));
47035de96e33SMatt Macy 	}
4704eb7c9019SMatt Macy 	return (pmc_add_sample(ring, pm, tf));
47055de96e33SMatt Macy }
47065de96e33SMatt Macy 
47075de96e33SMatt Macy /*
4708d07f36b0SJoseph Koshy  * Capture a user call chain. This function will be called from ast()
4709d07f36b0SJoseph Koshy  * before control returns to userland and before the process gets
4710d07f36b0SJoseph Koshy  * rescheduled.
4711d07f36b0SJoseph Koshy  */
4712d07f36b0SJoseph Koshy static void
4713f5f9340bSFabien Thomas pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4714d07f36b0SJoseph Koshy {
4715d07f36b0SJoseph Koshy 	struct pmc *pm;
4716d9f1b8dbSMatt Macy 	struct pmc_sample *ps;
4717d07f36b0SJoseph Koshy 	struct pmc_samplebuffer *psb;
471801c35b67SMitchell Horne 	struct thread *td;
4719d9f1b8dbSMatt Macy 	uint64_t considx, prodidx;
4720d9f1b8dbSMatt Macy 	int nsamples, nrecords, pass, iter;
472101c35b67SMitchell Horne 	int start_ticks __diagused;
472201c35b67SMitchell Horne 
4723f5f9340bSFabien Thomas 	psb = pmc_pcpu[cpu]->pc_sb[ring];
47246fe00c78SJoseph Koshy 	td = curthread;
472501c35b67SMitchell Horne 	nrecords = INT_MAX;
472601c35b67SMitchell Horne 	pass = 0;
472701c35b67SMitchell Horne 	start_ticks = ticks;
47286fe00c78SJoseph Koshy 
47296fe00c78SJoseph Koshy 	KASSERT(td->td_pflags & TDP_CALLCHAIN,
47306fe00c78SJoseph Koshy 	    ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
47316fe00c78SJoseph Koshy 	    __LINE__));
47325de96e33SMatt Macy restart:
47335de96e33SMatt Macy 	if (ring == PMC_UR)
47345de96e33SMatt Macy 		nrecords = atomic_readandclear_32(&td->td_pmcpend);
4735d07f36b0SJoseph Koshy 
4736d9f1b8dbSMatt Macy 	for (iter = 0, considx = psb->ps_considx, prodidx = psb->ps_prodidx;
4737d9f1b8dbSMatt Macy 	    considx < prodidx && iter < pmc_nsamples; considx++, iter++) {
4738d9f1b8dbSMatt Macy 		ps = PMC_CONS_SAMPLE_OFF(psb, considx);
4739d9f1b8dbSMatt Macy 
4740d07f36b0SJoseph Koshy 		/*
474101c35b67SMitchell Horne 		 * Iterate through all deferred callchain requests. Walk from
474201c35b67SMitchell Horne 		 * the current read pointer to the current write pointer.
4743d07f36b0SJoseph Koshy 		 */
47447bc7e3cdSAndrew Turner #ifdef INVARIANTS
47455de96e33SMatt Macy 		if (ps->ps_nsamples == PMC_SAMPLE_FREE) {
4746d9f1b8dbSMatt Macy 			continue;
47475de96e33SMatt Macy 		}
47487bc7e3cdSAndrew Turner #endif
4749d9f1b8dbSMatt Macy 		if (ps->ps_td != td ||
47501bb4eefaSMatt Macy 		    ps->ps_nsamples != PMC_USER_CALLCHAIN_PENDING ||
4751d9f1b8dbSMatt Macy 		    ps->ps_pmc->pm_state != PMC_STATE_RUNNING)
4752d9f1b8dbSMatt Macy 			continue;
47536fe00c78SJoseph Koshy 
47546fe00c78SJoseph Koshy 		KASSERT(ps->ps_cpu == cpu,
47556fe00c78SJoseph Koshy 		    ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
47566fe00c78SJoseph Koshy 		    ps->ps_cpu, PCPU_GET(cpuid)));
4757d07f36b0SJoseph Koshy 
4758d07f36b0SJoseph Koshy 		pm = ps->ps_pmc;
4759d07f36b0SJoseph Koshy 		KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
4760d07f36b0SJoseph Koshy 		    ("[pmc,%d] Retrieving callchain for PMC that doesn't "
4761d07f36b0SJoseph Koshy 		    "want it", __LINE__));
4762e6b475e0SMatt Macy 		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
476301c35b67SMitchell Horne 		    ("[pmc,%d] runcount %ju", __LINE__,
476401c35b67SMitchell Horne 		    (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
47656fe00c78SJoseph Koshy 
47665de96e33SMatt Macy 		if (ring == PMC_UR) {
47675de96e33SMatt Macy 			nsamples = ps->ps_nsamples_actual;
47685de96e33SMatt Macy 			counter_u64_add(pmc_stats.pm_merges, 1);
47695de96e33SMatt Macy 		} else
47705de96e33SMatt Macy 			nsamples = 0;
47715de96e33SMatt Macy 
4772d07f36b0SJoseph Koshy 		/*
4773d07f36b0SJoseph Koshy 		 * Retrieve the callchain and mark the sample buffer
4774d07f36b0SJoseph Koshy 		 * as 'processable' by the timer tick sweep code.
4775d07f36b0SJoseph Koshy 		 */
47765de96e33SMatt Macy 		if (__predict_true(nsamples < pmc_callchaindepth - 1))
47775de96e33SMatt Macy 			nsamples += pmc_save_user_callchain(ps->ps_pc + nsamples,
47785de96e33SMatt Macy 			    pmc_callchaindepth - nsamples - 1, tf);
4779d9f1b8dbSMatt Macy 
4780d9f1b8dbSMatt Macy 		/*
4781d9f1b8dbSMatt Macy 		 * We have to prevent hardclock from potentially overwriting
4782d9f1b8dbSMatt Macy 		 * this sample between when we read the value and when we set
478301c35b67SMitchell Horne 		 * it.
4784d9f1b8dbSMatt Macy 		 */
4785d9f1b8dbSMatt Macy 		spinlock_enter();
4786693cd307SMitchell Horne 
4787d9f1b8dbSMatt Macy 		/*
478801c35b67SMitchell Horne 		 * Verify that the sample hasn't been dropped in the meantime.
4789d9f1b8dbSMatt Macy 		 */
4790d9f1b8dbSMatt Macy 		if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) {
47915de96e33SMatt Macy 			ps->ps_nsamples = nsamples;
4792d9f1b8dbSMatt Macy 			/*
479301c35b67SMitchell Horne 			 * If we couldn't get a sample, simply drop the
479401c35b67SMitchell Horne 			 * reference.
4795d9f1b8dbSMatt Macy 			 */
4796d9f1b8dbSMatt Macy 			if (nsamples == 0)
4797d9f1b8dbSMatt Macy 				counter_u64_add(pm->pm_runcount, -1);
4798d9f1b8dbSMatt Macy 		}
4799d9f1b8dbSMatt Macy 		spinlock_exit();
48005de96e33SMatt Macy 		if (nrecords-- == 1)
48015de96e33SMatt Macy 			break;
4802d9f1b8dbSMatt Macy 	}
48035de96e33SMatt Macy 	if (__predict_false(ring == PMC_UR && td->td_pmcpend)) {
48045de96e33SMatt Macy 		if (pass == 0) {
48055de96e33SMatt Macy 			pass = 1;
48065de96e33SMatt Macy 			goto restart;
48075de96e33SMatt Macy 		}
48085de96e33SMatt Macy 		/* only collect samples for this part once */
48095de96e33SMatt Macy 		td->td_pmcpend = 0;
48105de96e33SMatt Macy 	}
4811d07f36b0SJoseph Koshy 
48126cb40391SZbigniew Bodek #ifdef INVARIANTS
4813d9f1b8dbSMatt Macy 	if ((ticks - start_ticks) > hz)
4814d9f1b8dbSMatt Macy 		log(LOG_ERR, "%s took %d ticks\n", __func__, (ticks - start_ticks));
48156cb40391SZbigniew Bodek #endif
4816c66ea2eeSJonathan T. Looney 	/* mark CPU as needing processing */
4817e6b475e0SMatt Macy 	DPCPU_SET(pmc_sampled, 1);
4818f263522aSJoseph Koshy }
4819f263522aSJoseph Koshy 
4820ebccf1e3SJoseph Koshy /*
4821f263522aSJoseph Koshy  * Process saved PC samples.
4822ebccf1e3SJoseph Koshy  */
4823ebccf1e3SJoseph Koshy static void
4824d9f1b8dbSMatt Macy pmc_process_samples(int cpu, ring_type_t ring)
4825ebccf1e3SJoseph Koshy {
4826f263522aSJoseph Koshy 	struct pmc *pm;
4827f263522aSJoseph Koshy 	struct thread *td;
4828f263522aSJoseph Koshy 	struct pmc_owner *po;
4829f263522aSJoseph Koshy 	struct pmc_sample *ps;
4830e829eb6dSJoseph Koshy 	struct pmc_classdep *pcd;
4831f263522aSJoseph Koshy 	struct pmc_samplebuffer *psb;
4832aee6e7dcSMateusz Guzik 	uint64_t delta __diagused;
483301c35b67SMitchell Horne 	int adjri, n;
4834ebccf1e3SJoseph Koshy 
4835f263522aSJoseph Koshy 	KASSERT(PCPU_GET(cpuid) == cpu,
4836f263522aSJoseph Koshy 	    ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4837f263522aSJoseph Koshy 		PCPU_GET(cpuid), cpu));
4838ebccf1e3SJoseph Koshy 
4839f5f9340bSFabien Thomas 	psb = pmc_pcpu[cpu]->pc_sb[ring];
4840d9f1b8dbSMatt Macy 	delta = psb->ps_prodidx - psb->ps_considx;
4841d9f1b8dbSMatt Macy 	MPASS(delta <= pmc_nsamples);
4842d9f1b8dbSMatt Macy 	MPASS(psb->ps_considx <= psb->ps_prodidx);
4843d9f1b8dbSMatt Macy 	for (n = 0; psb->ps_considx < psb->ps_prodidx; psb->ps_considx++, n++) {
4844d9f1b8dbSMatt Macy 		ps = PMC_CONS_SAMPLE(psb);
4845f263522aSJoseph Koshy 
4846d9f1b8dbSMatt Macy 		if (__predict_false(ps->ps_nsamples == PMC_SAMPLE_FREE))
4847d9f1b8dbSMatt Macy 			continue;
484801c35b67SMitchell Horne 
4849d9f1b8dbSMatt Macy 		/* skip non-running samples */
485001c35b67SMitchell Horne 		pm = ps->ps_pmc;
4851d9f1b8dbSMatt Macy 		if (pm->pm_state != PMC_STATE_RUNNING)
4852d9f1b8dbSMatt Macy 			goto entrydone;
48536fe00c78SJoseph Koshy 
4854e6b475e0SMatt Macy 		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
485501c35b67SMitchell Horne 		    ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
485601c35b67SMitchell Horne 		    (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
4857f263522aSJoseph Koshy 		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4858f263522aSJoseph Koshy 		    ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4859f263522aSJoseph Koshy 		    pm, PMC_TO_MODE(pm)));
4860f263522aSJoseph Koshy 
486101c35b67SMitchell Horne 		po = pm->pm_owner;
4862f263522aSJoseph Koshy 
4863f5f9340bSFabien Thomas 		/* If there is a pending AST wait for completion */
4864d9f1b8dbSMatt Macy 		if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) {
486501c35b67SMitchell Horne 			/*
486601c35b67SMitchell Horne 			 * If we've been waiting more than 1 tick to
4867acf50a7fSMatt Macy 			 * collect a callchain for this record then
4868acf50a7fSMatt Macy 			 * drop it and move on.
4869acf50a7fSMatt Macy 			 */
4870acf50a7fSMatt Macy 			if (ticks - ps->ps_ticks > 1) {
4871d9f1b8dbSMatt Macy 				/*
487201c35b67SMitchell Horne 				 * Track how often we hit this as it will
4873d9f1b8dbSMatt Macy 				 * preferentially lose user samples
487401c35b67SMitchell Horne 				 * for long running system calls.
4875d9f1b8dbSMatt Macy 				 */
4876d9f1b8dbSMatt Macy 				counter_u64_add(pmc_stats.pm_overwrites, 1);
4877d9f1b8dbSMatt Macy 				goto entrydone;
4878d9f1b8dbSMatt Macy 			}
4879f5f9340bSFabien Thomas 			/* Need a rescan at a later time. */
4880e6b475e0SMatt Macy 			DPCPU_SET(pmc_sampled, 1);
4881f5f9340bSFabien Thomas 			break;
4882f5f9340bSFabien Thomas 		}
4883f5f9340bSFabien Thomas 
48844a3690dfSJohn Baldwin 		PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4885d07f36b0SJoseph Koshy 		    pm, ps->ps_nsamples, ps->ps_flags,
4886d9f1b8dbSMatt Macy 		    (int)(psb->ps_prodidx & pmc_sample_mask),
4887d9f1b8dbSMatt Macy 		    (int)(psb->ps_considx & pmc_sample_mask));
4888f263522aSJoseph Koshy 
4889f263522aSJoseph Koshy 		/*
4890f263522aSJoseph Koshy 		 * If this is a process-mode PMC that is attached to
4891f263522aSJoseph Koshy 		 * its owner, and if the PC is in user mode, update
4892f263522aSJoseph Koshy 		 * profiling statistics like timer-based profiling
4893f263522aSJoseph Koshy 		 * would have done.
48945de96e33SMatt Macy 		 *
48955de96e33SMatt Macy 		 * Otherwise, this is either a sampling-mode PMC that
48965de96e33SMatt Macy 		 * is attached to a different process than its owner,
48975de96e33SMatt Macy 		 * or a system-wide sampling PMC. Dispatch a log
48985de96e33SMatt Macy 		 * entry to the PMC's owner process.
4899f263522aSJoseph Koshy 		 */
4900f263522aSJoseph Koshy 		if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4901d07f36b0SJoseph Koshy 			if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4902f263522aSJoseph Koshy 				td = FIRST_THREAD_IN_PROC(po->po_owner);
4903d07f36b0SJoseph Koshy 				addupc_intr(td, ps->ps_pc[0], 1);
4904f263522aSJoseph Koshy 			}
49055de96e33SMatt Macy 		} else
4906d07f36b0SJoseph Koshy 			pmclog_process_callchain(pm, ps);
4907f263522aSJoseph Koshy 
4908f263522aSJoseph Koshy entrydone:
4909d07f36b0SJoseph Koshy 		ps->ps_nsamples = 0; /* mark entry as free */
4910d9f1b8dbSMatt Macy 		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
491101c35b67SMitchell Horne 		    ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
491201c35b67SMitchell Horne 		    (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
4913f263522aSJoseph Koshy 
4914d9f1b8dbSMatt Macy 		counter_u64_add(pm->pm_runcount, -1);
4915f263522aSJoseph Koshy 	}
4916f263522aSJoseph Koshy 
4917e6b475e0SMatt Macy 	counter_u64_add(pmc_stats.pm_log_sweeps, 1);
4918f263522aSJoseph Koshy 
4919f263522aSJoseph Koshy 	/* Do not re-enable stalled PMCs if we failed to process any samples */
4920f263522aSJoseph Koshy 	if (n == 0)
4921ebccf1e3SJoseph Koshy 		return;
4922f263522aSJoseph Koshy 
4923f263522aSJoseph Koshy 	/*
4924f263522aSJoseph Koshy 	 * Restart any stalled sampling PMCs on this CPU.
4925f263522aSJoseph Koshy 	 *
4926fbf1556dSJoseph Koshy 	 * If the NMI handler sets the pm_stalled field of a PMC after
4927fbf1556dSJoseph Koshy 	 * the check below, we'll end up processing the stalled PMC at
4928fbf1556dSJoseph Koshy 	 * the next hardclock tick.
4929f263522aSJoseph Koshy 	 */
4930f263522aSJoseph Koshy 	for (n = 0; n < md->pmd_npmc; n++) {
4931e829eb6dSJoseph Koshy 		pcd = pmc_ri_to_classdep(md, n, &adjri);
4932e829eb6dSJoseph Koshy 		KASSERT(pcd != NULL,
4933e829eb6dSJoseph Koshy 		    ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4934e829eb6dSJoseph Koshy 		(void)(*pcd->pcd_get_config)(cpu, adjri, &pm);
4935e829eb6dSJoseph Koshy 
4936f263522aSJoseph Koshy 		if (pm == NULL ||				/* !cfg'ed */
4937f263522aSJoseph Koshy 		    pm->pm_state != PMC_STATE_RUNNING ||	/* !active */
4938f263522aSJoseph Koshy 		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) ||	/* !sampling */
4939e6b475e0SMatt Macy 		    !pm->pm_pcpu_state[cpu].pps_cpustate ||	/* !desired */
4940e6b475e0SMatt Macy 		    !pm->pm_pcpu_state[cpu].pps_stalled)	/* !stalled */
4941f263522aSJoseph Koshy 			continue;
4942f263522aSJoseph Koshy 
4943e6b475e0SMatt Macy 		pm->pm_pcpu_state[cpu].pps_stalled = 0;
494401c35b67SMitchell Horne 		(void)(*pcd->pcd_start_pmc)(cpu, adjri, pm);
4945f263522aSJoseph Koshy 	}
4946ebccf1e3SJoseph Koshy }
4947ebccf1e3SJoseph Koshy 
4948ebccf1e3SJoseph Koshy /*
4949ebccf1e3SJoseph Koshy  * Event handlers.
4950ebccf1e3SJoseph Koshy  */
4951ebccf1e3SJoseph Koshy 
4952ebccf1e3SJoseph Koshy /*
4953ebccf1e3SJoseph Koshy  * Handle a process exit.
4954ebccf1e3SJoseph Koshy  *
4955f263522aSJoseph Koshy  * Remove this process from all hash tables.  If this process
4956f263522aSJoseph Koshy  * owned any PMCs, turn off those PMCs and deallocate them,
4957f263522aSJoseph Koshy  * removing any associations with target processes.
4958f263522aSJoseph Koshy  *
4959f263522aSJoseph Koshy  * This function will be called by the last 'thread' of a
4960f263522aSJoseph Koshy  * process.
4961f263522aSJoseph Koshy  *
4962ebccf1e3SJoseph Koshy  * XXX This eventhandler gets called early in the exit process.
4963ebccf1e3SJoseph Koshy  * Consider using a 'hook' invocation from thread_exit() or equivalent
4964ebccf1e3SJoseph Koshy  * spot.  Another negative is that kse_exit doesn't seem to call
4965ebccf1e3SJoseph Koshy  * exit1() [??].
4966ebccf1e3SJoseph Koshy  */
4967ebccf1e3SJoseph Koshy static void
4968ebccf1e3SJoseph Koshy pmc_process_exit(void *arg __unused, struct proc *p)
4969ebccf1e3SJoseph Koshy {
4970f263522aSJoseph Koshy 	struct pmc *pm;
4971f263522aSJoseph Koshy 	struct pmc_owner *po;
4972e829eb6dSJoseph Koshy 	struct pmc_process *pp;
4973e829eb6dSJoseph Koshy 	struct pmc_classdep *pcd;
4974f263522aSJoseph Koshy 	pmc_value_t newvalue, tmp;
497501c35b67SMitchell Horne 	int ri, adjri, cpu;
497601c35b67SMitchell Horne 	bool is_using_hwpmcs;
4977ebccf1e3SJoseph Koshy 
4978ebccf1e3SJoseph Koshy 	PROC_LOCK(p);
4979d5ee4074SMitchell Horne 	is_using_hwpmcs = (p->p_flag & P_HWPMC) != 0;
4980ebccf1e3SJoseph Koshy 	PROC_UNLOCK(p);
4981ebccf1e3SJoseph Koshy 
4982f263522aSJoseph Koshy 	/*
4983f263522aSJoseph Koshy 	 * Log a sysexit event to all SS PMC owners.
4984f263522aSJoseph Koshy 	 */
49856573d758SMatt Macy 	PMC_EPOCH_ENTER();
4986d5ee4074SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
4987d5ee4074SMitchell Horne 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
4988f263522aSJoseph Koshy 			pmclog_process_sysexit(po, p->p_pid);
4989d5ee4074SMitchell Horne 	}
49906573d758SMatt Macy 	PMC_EPOCH_EXIT();
4991f263522aSJoseph Koshy 
4992f263522aSJoseph Koshy 	if (!is_using_hwpmcs)
4993f263522aSJoseph Koshy 		return;
4994f263522aSJoseph Koshy 
4995f263522aSJoseph Koshy 	PMC_GET_SX_XLOCK();
49964a3690dfSJohn Baldwin 	PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4997ebccf1e3SJoseph Koshy 	    p->p_comm);
4998ebccf1e3SJoseph Koshy 
4999f263522aSJoseph Koshy 	/*
5000104e8215SMitchell Horne 	 * Since this code is invoked by the last thread in an exiting process,
5001104e8215SMitchell Horne 	 * we would have context switched IN at some prior point. However, with
5002104e8215SMitchell Horne 	 * PREEMPTION, kernel mode context switches may happen any time, so we
5003104e8215SMitchell Horne 	 * want to disable a context switch OUT till we get any PMCs targeting
5004104e8215SMitchell Horne 	 * this process off the hardware.
5005f263522aSJoseph Koshy 	 *
5006104e8215SMitchell Horne 	 * We also need to atomically remove this process' entry from our
5007104e8215SMitchell Horne 	 * target process hash table, using PMC_FLAG_REMOVE.
5008f263522aSJoseph Koshy 	 */
50094a3690dfSJohn Baldwin 	PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
5010f263522aSJoseph Koshy 	    p->p_comm);
5011f263522aSJoseph Koshy 
5012f263522aSJoseph Koshy 	critical_enter(); /* no preemption */
5013f263522aSJoseph Koshy 
5014f263522aSJoseph Koshy 	cpu = curthread->td_oncpu;
5015f263522aSJoseph Koshy 
5016104e8215SMitchell Horne 	pp = pmc_find_process_descriptor(p, PMC_FLAG_REMOVE);
5017104e8215SMitchell Horne 	if (pp == NULL) {
5018104e8215SMitchell Horne 		critical_exit();
5019104e8215SMitchell Horne 		goto out;
5020104e8215SMitchell Horne 	}
5021104e8215SMitchell Horne 
5022104e8215SMitchell Horne 	PMCDBG2(PRC,EXT,2, "process-exit proc=%p pmc-process=%p", p, pp);
5023f263522aSJoseph Koshy 
5024f263522aSJoseph Koshy 	/*
5025104e8215SMitchell Horne 	 * The exiting process could be the target of some PMCs which will be
5026104e8215SMitchell Horne 	 * running on currently executing CPU.
5027f263522aSJoseph Koshy 	 *
5028104e8215SMitchell Horne 	 * We need to turn these PMCs off like we would do at context switch
5029104e8215SMitchell Horne 	 * OUT time.
5030f263522aSJoseph Koshy 	 */
5031f263522aSJoseph Koshy 	for (ri = 0; ri < md->pmd_npmc; ri++) {
5032f263522aSJoseph Koshy 		/*
5033104e8215SMitchell Horne 		 * Pick up the pmc pointer from hardware state similar to the
5034104e8215SMitchell Horne 		 * CSW_OUT code.
5035f263522aSJoseph Koshy 		 */
5036f263522aSJoseph Koshy 		pm = NULL;
5037e829eb6dSJoseph Koshy 		pcd = pmc_ri_to_classdep(md, ri, &adjri);
5038e829eb6dSJoseph Koshy 
5039e829eb6dSJoseph Koshy 		(void)(*pcd->pcd_get_config)(cpu, adjri, &pm);
5040f263522aSJoseph Koshy 
50414a3690dfSJohn Baldwin 		PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
5042f263522aSJoseph Koshy 
5043693cd307SMitchell Horne 		if (pm == NULL || !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
5044f263522aSJoseph Koshy 			continue;
5045f263522aSJoseph Koshy 
5046104e8215SMitchell Horne 		PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p state=%d", ri,
5047104e8215SMitchell Horne 		    pp->pp_pmcs[ri].pp_pmc, pm, pm->pm_state);
5048f263522aSJoseph Koshy 
5049f263522aSJoseph Koshy 		KASSERT(PMC_TO_ROWINDEX(pm) == ri,
5050104e8215SMitchell Horne 		    ("[pmc,%d] ri mismatch pmc(%d) ri(%d)", __LINE__,
5051104e8215SMitchell Horne 		    PMC_TO_ROWINDEX(pm), ri));
5052f263522aSJoseph Koshy 		KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
5053104e8215SMitchell Horne 		    ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__, pm, ri,
5054104e8215SMitchell Horne 		    pp->pp_pmcs[ri].pp_pmc));
5055e6b475e0SMatt Macy 		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
5056104e8215SMitchell Horne 		    ("[pmc,%d] bad runcount ri %d rc %ju", __LINE__, ri,
505701c35b67SMitchell Horne 		    (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
5058f263522aSJoseph Koshy 
5059a3924968SJonathan T. Looney 		/*
5060104e8215SMitchell Horne 		 * Change desired state, and then stop if not stalled. This
5061104e8215SMitchell Horne 		 * two-step dance should avoid race conditions where an
5062104e8215SMitchell Horne 		 * interrupt re-enables the PMC after this code has already
5063104e8215SMitchell Horne 		 * checked the pm_stalled flag.
5064a3924968SJonathan T. Looney 		 */
5065e6b475e0SMatt Macy 		if (pm->pm_pcpu_state[cpu].pps_cpustate) {
5066e6b475e0SMatt Macy 			pm->pm_pcpu_state[cpu].pps_cpustate = 0;
5067e6b475e0SMatt Macy 			if (!pm->pm_pcpu_state[cpu].pps_stalled) {
506839f92a76SMitchell Horne 				(void)pcd->pcd_stop_pmc(cpu, adjri, pm);
50696161b98cSMatt Macy 
50706161b98cSMatt Macy 				if (PMC_TO_MODE(pm) == PMC_MODE_TC) {
5071104e8215SMitchell Horne 					pcd->pcd_read_pmc(cpu, adjri, pm,
5072104e8215SMitchell Horne 					    &newvalue);
5073104e8215SMitchell Horne 					tmp = newvalue - PMC_PCPU_SAVED(cpu, ri);
5074f263522aSJoseph Koshy 
5075104e8215SMitchell Horne 					mtx_pool_lock_spin(pmc_mtxpool, pm);
5076f263522aSJoseph Koshy 					pm->pm_gv.pm_savedvalue += tmp;
5077104e8215SMitchell Horne 					pp->pp_pmcs[ri].pp_pmcval += tmp;
5078104e8215SMitchell Horne 					mtx_pool_unlock_spin(pmc_mtxpool, pm);
50796161b98cSMatt Macy 				}
5080ebccf1e3SJoseph Koshy 			}
5081a3924968SJonathan T. Looney 		}
5082f263522aSJoseph Koshy 
508301c35b67SMitchell Horne 		KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
5084f263522aSJoseph Koshy 		    ("[pmc,%d] runcount is %d", __LINE__, ri));
5085f263522aSJoseph Koshy 
5086d9f1b8dbSMatt Macy 		counter_u64_add(pm->pm_runcount, -1);
5087e829eb6dSJoseph Koshy 		(void)pcd->pcd_config_pmc(cpu, adjri, NULL);
5088f263522aSJoseph Koshy 	}
5089f263522aSJoseph Koshy 
5090f263522aSJoseph Koshy 	/*
5091104e8215SMitchell Horne 	 * Inform the MD layer of this pseudo "context switch out".
5092f263522aSJoseph Koshy 	 */
5093f263522aSJoseph Koshy 	(void)md->pmd_switch_out(pmc_pcpu[cpu], pp);
5094f263522aSJoseph Koshy 
5095f263522aSJoseph Koshy 	critical_exit(); /* ok to be pre-empted now */
5096f263522aSJoseph Koshy 
5097f263522aSJoseph Koshy 	/*
5098104e8215SMitchell Horne 	 * Unlink this process from the PMCs that are targeting it. This will
5099104e8215SMitchell Horne 	 * send a signal to all PMC owner's whose PMCs are orphaned.
5100f263522aSJoseph Koshy 	 *
5101f263522aSJoseph Koshy 	 * Log PMC value at exit time if requested.
5102f263522aSJoseph Koshy 	 */
5103d5ee4074SMitchell Horne 	for (ri = 0; ri < md->pmd_npmc; ri++) {
5104f263522aSJoseph Koshy 		if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
5105d5ee4074SMitchell Horne 			if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) != 0 &&
5106d5ee4074SMitchell Horne 			    PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm))) {
5107f263522aSJoseph Koshy 				pmclog_process_procexit(pm, pp);
5108d5ee4074SMitchell Horne 			}
5109f263522aSJoseph Koshy 			pmc_unlink_target_process(pm, pp);
5110f263522aSJoseph Koshy 		}
5111d5ee4074SMitchell Horne 	}
51121ede983cSDag-Erling Smørgrav 	free(pp, M_PMC);
5113f263522aSJoseph Koshy 
5114104e8215SMitchell Horne out:
5115f263522aSJoseph Koshy 	/*
5116104e8215SMitchell Horne 	 * If the process owned PMCs, free them up and free up memory.
5117f263522aSJoseph Koshy 	 */
5118f263522aSJoseph Koshy 	if ((po = pmc_find_owner_descriptor(p)) != NULL) {
5119f263522aSJoseph Koshy 		pmc_remove_owner(po);
5120f263522aSJoseph Koshy 		pmc_destroy_owner_descriptor(po);
5121f263522aSJoseph Koshy 	}
5122f263522aSJoseph Koshy 
5123f263522aSJoseph Koshy 	sx_xunlock(&pmc_sx);
5124ebccf1e3SJoseph Koshy }
5125ebccf1e3SJoseph Koshy 
5126ebccf1e3SJoseph Koshy /*
5127ebccf1e3SJoseph Koshy  * Handle a process fork.
5128ebccf1e3SJoseph Koshy  *
5129ebccf1e3SJoseph Koshy  * If the parent process 'p1' is under HWPMC monitoring, then copy
5130ebccf1e3SJoseph Koshy  * over any attached PMCs that have 'do_descendants' semantics.
5131ebccf1e3SJoseph Koshy  */
5132ebccf1e3SJoseph Koshy static void
5133f263522aSJoseph Koshy pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
513401c35b67SMitchell Horne     int flags __unused)
5135ebccf1e3SJoseph Koshy {
5136f263522aSJoseph Koshy 	struct pmc *pm;
5137f263522aSJoseph Koshy 	struct pmc_owner *po;
5138f263522aSJoseph Koshy 	struct pmc_process *ppnew, *ppold;
513901c35b67SMitchell Horne 	unsigned int ri;
514001c35b67SMitchell Horne 	bool is_using_hwpmcs, do_descendants;
5141ebccf1e3SJoseph Koshy 
5142ebccf1e3SJoseph Koshy 	PROC_LOCK(p1);
5143d5ee4074SMitchell Horne 	is_using_hwpmcs = (p1->p_flag & P_HWPMC) != 0;
5144ebccf1e3SJoseph Koshy 	PROC_UNLOCK(p1);
5145ebccf1e3SJoseph Koshy 
5146f263522aSJoseph Koshy 	/*
5147f263522aSJoseph Koshy 	 * If there are system-wide sampling PMCs active, we need to
5148f263522aSJoseph Koshy 	 * log all fork events to their owner's logs.
5149f263522aSJoseph Koshy 	 */
51506573d758SMatt Macy 	PMC_EPOCH_ENTER();
5151d5ee4074SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5152ebfaf69cSMatt Macy 		if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
5153f263522aSJoseph Koshy 			pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
5154ebfaf69cSMatt Macy 			pmclog_process_proccreate(po, newproc, 1);
5155ebfaf69cSMatt Macy 		}
5156d5ee4074SMitchell Horne 	}
51576573d758SMatt Macy 	PMC_EPOCH_EXIT();
5158f263522aSJoseph Koshy 
5159f263522aSJoseph Koshy 	if (!is_using_hwpmcs)
5160f263522aSJoseph Koshy 		return;
5161f263522aSJoseph Koshy 
5162ebccf1e3SJoseph Koshy 	PMC_GET_SX_XLOCK();
51634a3690dfSJohn Baldwin 	PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
5164f263522aSJoseph Koshy 	    p1->p_pid, p1->p_comm, newproc);
5165f263522aSJoseph Koshy 
5166f263522aSJoseph Koshy 	/*
5167f263522aSJoseph Koshy 	 * If the parent process (curthread->td_proc) is a
5168f263522aSJoseph Koshy 	 * target of any PMCs, look for PMCs that are to be
5169f263522aSJoseph Koshy 	 * inherited, and link these into the new process
5170f263522aSJoseph Koshy 	 * descriptor.
5171f263522aSJoseph Koshy 	 */
5172d5ee4074SMitchell Horne 	ppold = pmc_find_process_descriptor(curthread->td_proc, PMC_FLAG_NONE);
5173d5ee4074SMitchell Horne 	if (ppold == NULL)
5174f263522aSJoseph Koshy 		goto done; /* nothing to do */
5175f263522aSJoseph Koshy 
517601c35b67SMitchell Horne 	do_descendants = false;
5177d5ee4074SMitchell Horne 	for (ri = 0; ri < md->pmd_npmc; ri++) {
5178d5ee4074SMitchell Horne 		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
5179d5ee4074SMitchell Horne 		    (pm->pm_flags & PMC_F_DESCENDANTS) != 0) {
5180d5ee4074SMitchell Horne 			do_descendants = true;
5181d5ee4074SMitchell Horne 			break;
5182d5ee4074SMitchell Horne 		}
5183d5ee4074SMitchell Horne 	}
518401c35b67SMitchell Horne 	if (!do_descendants) /* nothing to do */
5185f263522aSJoseph Koshy 		goto done;
5186f263522aSJoseph Koshy 
51876161b98cSMatt Macy 	/*
51886161b98cSMatt Macy 	 * Now mark the new process as being tracked by this driver.
51896161b98cSMatt Macy 	 */
51906161b98cSMatt Macy 	PROC_LOCK(newproc);
51916161b98cSMatt Macy 	newproc->p_flag |= P_HWPMC;
51926161b98cSMatt Macy 	PROC_UNLOCK(newproc);
51936161b98cSMatt Macy 
519401c35b67SMitchell Horne 	/* Allocate a descriptor for the new process. */
5195d5ee4074SMitchell Horne 	ppnew = pmc_find_process_descriptor(newproc, PMC_FLAG_ALLOCATE);
5196d5ee4074SMitchell Horne 	if (ppnew == NULL)
5197f263522aSJoseph Koshy 		goto done;
5198f263522aSJoseph Koshy 
5199f263522aSJoseph Koshy 	/*
5200f263522aSJoseph Koshy 	 * Run through all PMCs that were targeting the old process
5201f263522aSJoseph Koshy 	 * and which specified F_DESCENDANTS and attach them to the
5202f263522aSJoseph Koshy 	 * new process.
5203f263522aSJoseph Koshy 	 *
5204f263522aSJoseph Koshy 	 * Log the fork event to all owners of PMCs attached to this
5205f263522aSJoseph Koshy 	 * process, if not already logged.
5206f263522aSJoseph Koshy 	 */
5207d5ee4074SMitchell Horne 	for (ri = 0; ri < md->pmd_npmc; ri++) {
5208f263522aSJoseph Koshy 		if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
5209d5ee4074SMitchell Horne 		    (pm->pm_flags & PMC_F_DESCENDANTS) != 0) {
5210f263522aSJoseph Koshy 			pmc_link_target_process(pm, ppnew);
5211f263522aSJoseph Koshy 			po = pm->pm_owner;
5212f263522aSJoseph Koshy 			if (po->po_sscount == 0 &&
5213d5ee4074SMitchell Horne 			    (po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) {
5214f263522aSJoseph Koshy 				pmclog_process_procfork(po, p1->p_pid,
5215f263522aSJoseph Koshy 				    newproc->p_pid);
5216ebccf1e3SJoseph Koshy 			}
5217d5ee4074SMitchell Horne 		}
5218d5ee4074SMitchell Horne 	}
5219f263522aSJoseph Koshy 
5220f263522aSJoseph Koshy done:
5221f263522aSJoseph Koshy 	sx_xunlock(&pmc_sx);
5222ebccf1e3SJoseph Koshy }
5223ebccf1e3SJoseph Koshy 
522429f4e216SMark Johnston static void
5225ebfaf69cSMatt Macy pmc_process_threadcreate(struct thread *td)
5226ebfaf69cSMatt Macy {
5227ebfaf69cSMatt Macy 	struct pmc_owner *po;
5228ebfaf69cSMatt Macy 
52296573d758SMatt Macy 	PMC_EPOCH_ENTER();
5230d5ee4074SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5231d5ee4074SMitchell Horne 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
5232ebfaf69cSMatt Macy 			pmclog_process_threadcreate(po, td, 1);
5233d5ee4074SMitchell Horne 	}
52346573d758SMatt Macy 	PMC_EPOCH_EXIT();
5235ebfaf69cSMatt Macy }
5236ebfaf69cSMatt Macy 
5237ebfaf69cSMatt Macy static void
5238ebfaf69cSMatt Macy pmc_process_threadexit(struct thread *td)
5239ebfaf69cSMatt Macy {
5240ebfaf69cSMatt Macy 	struct pmc_owner *po;
5241ebfaf69cSMatt Macy 
52426573d758SMatt Macy 	PMC_EPOCH_ENTER();
5243d5ee4074SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5244d5ee4074SMitchell Horne 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
5245ebfaf69cSMatt Macy 			pmclog_process_threadexit(po, td);
5246d5ee4074SMitchell Horne 	}
52476573d758SMatt Macy 	PMC_EPOCH_EXIT();
5248ebfaf69cSMatt Macy }
5249ebfaf69cSMatt Macy 
5250ebfaf69cSMatt Macy static void
5251ebfaf69cSMatt Macy pmc_process_proccreate(struct proc *p)
5252ebfaf69cSMatt Macy {
5253ebfaf69cSMatt Macy 	struct pmc_owner *po;
5254ebfaf69cSMatt Macy 
52556573d758SMatt Macy 	PMC_EPOCH_ENTER();
5256d5ee4074SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5257d5ee4074SMitchell Horne 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
5258ebfaf69cSMatt Macy 			pmclog_process_proccreate(po, p, 1 /* sync */);
5259d5ee4074SMitchell Horne 	}
52606573d758SMatt Macy 	PMC_EPOCH_EXIT();
5261ebfaf69cSMatt Macy }
5262ebfaf69cSMatt Macy 
5263ebfaf69cSMatt Macy static void
5264ebfaf69cSMatt Macy pmc_process_allproc(struct pmc *pm)
5265ebfaf69cSMatt Macy {
5266ebfaf69cSMatt Macy 	struct pmc_owner *po;
5267ebfaf69cSMatt Macy 	struct thread *td;
5268ebfaf69cSMatt Macy 	struct proc *p;
5269ebfaf69cSMatt Macy 
5270ebfaf69cSMatt Macy 	po = pm->pm_owner;
5271ebfaf69cSMatt Macy 	if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
5272ebfaf69cSMatt Macy 		return;
5273693cd307SMitchell Horne 
5274ebfaf69cSMatt Macy 	sx_slock(&allproc_lock);
5275ebfaf69cSMatt Macy 	FOREACH_PROC_IN_SYSTEM(p) {
5276ebfaf69cSMatt Macy 		pmclog_process_proccreate(po, p, 0 /* sync */);
5277ebfaf69cSMatt Macy 		PROC_LOCK(p);
5278ebfaf69cSMatt Macy 		FOREACH_THREAD_IN_PROC(p, td)
5279ebfaf69cSMatt Macy 			pmclog_process_threadcreate(po, td, 0 /* sync */);
5280ebfaf69cSMatt Macy 		PROC_UNLOCK(p);
5281ebfaf69cSMatt Macy 	}
5282ebfaf69cSMatt Macy 	sx_sunlock(&allproc_lock);
5283ebfaf69cSMatt Macy 	pmclog_flush(po, 0);
5284ebfaf69cSMatt Macy }
5285ebfaf69cSMatt Macy 
5286ebfaf69cSMatt Macy static void
528729f4e216SMark Johnston pmc_kld_load(void *arg __unused, linker_file_t lf)
528829f4e216SMark Johnston {
528929f4e216SMark Johnston 	struct pmc_owner *po;
529029f4e216SMark Johnston 
529129f4e216SMark Johnston 	/*
529229f4e216SMark Johnston 	 * Notify owners of system sampling PMCs about KLD operations.
529329f4e216SMark Johnston 	 */
52946573d758SMatt Macy 	PMC_EPOCH_ENTER();
5295d5ee4074SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
529629f4e216SMark Johnston 		if (po->po_flags & PMC_PO_OWNS_LOGFILE)
529729f4e216SMark Johnston 			pmclog_process_map_in(po, (pid_t) -1,
529853d0b9e4SJessica Clarke 			    (uintfptr_t) lf->address, lf->pathname);
5299d5ee4074SMitchell Horne 	}
53006573d758SMatt Macy 	PMC_EPOCH_EXIT();
530129f4e216SMark Johnston 
530229f4e216SMark Johnston 	/*
530329f4e216SMark Johnston 	 * TODO: Notify owners of (all) process-sampling PMCs too.
530429f4e216SMark Johnston 	 */
530529f4e216SMark Johnston }
530629f4e216SMark Johnston 
530729f4e216SMark Johnston static void
530829f4e216SMark Johnston pmc_kld_unload(void *arg __unused, const char *filename __unused,
530929f4e216SMark Johnston     caddr_t address, size_t size)
531029f4e216SMark Johnston {
531129f4e216SMark Johnston 	struct pmc_owner *po;
531229f4e216SMark Johnston 
53136573d758SMatt Macy 	PMC_EPOCH_ENTER();
5314d5ee4074SMitchell Horne 	CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5315d5ee4074SMitchell Horne 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) {
531629f4e216SMark Johnston 			pmclog_process_map_out(po, (pid_t)-1,
531729f4e216SMark Johnston 			    (uintfptr_t)address, (uintfptr_t)address + size);
5318d5ee4074SMitchell Horne 		}
5319d5ee4074SMitchell Horne 	}
53206573d758SMatt Macy 	PMC_EPOCH_EXIT();
532129f4e216SMark Johnston 
532229f4e216SMark Johnston 	/*
532329f4e216SMark Johnston 	 * TODO: Notify owners of process-sampling PMCs.
532429f4e216SMark Johnston 	 */
532529f4e216SMark Johnston }
5326ebccf1e3SJoseph Koshy 
5327ebccf1e3SJoseph Koshy /*
5328ebccf1e3SJoseph Koshy  * initialization
5329ebccf1e3SJoseph Koshy  */
53300ceb54c2SJohn Baldwin static const char *
53310ceb54c2SJohn Baldwin pmc_name_of_pmcclass(enum pmc_class class)
53320ceb54c2SJohn Baldwin {
5333ebccf1e3SJoseph Koshy 
53340ceb54c2SJohn Baldwin 	switch (class) {
5335ebccf1e3SJoseph Koshy #undef	__PMC_CLASS
53360ceb54c2SJohn Baldwin #define	__PMC_CLASS(S,V,D)						\
53370ceb54c2SJohn Baldwin 	case PMC_CLASS_##S:						\
53380ceb54c2SJohn Baldwin 		return #S;
53390ceb54c2SJohn Baldwin 	__PMC_CLASSES();
53400ceb54c2SJohn Baldwin 	default:
53410ceb54c2SJohn Baldwin 		return ("<unknown>");
53420ceb54c2SJohn Baldwin 	}
53430ceb54c2SJohn Baldwin }
5344ebccf1e3SJoseph Koshy 
5345f5f9340bSFabien Thomas /*
5346f5f9340bSFabien Thomas  * Base class initializer: allocate structure and set default classes.
5347f5f9340bSFabien Thomas  */
5348f5f9340bSFabien Thomas struct pmc_mdep *
5349f5f9340bSFabien Thomas pmc_mdep_alloc(int nclasses)
5350f5f9340bSFabien Thomas {
5351f5f9340bSFabien Thomas 	struct pmc_mdep *md;
5352f5f9340bSFabien Thomas 	int n;
5353f5f9340bSFabien Thomas 
5354f5f9340bSFabien Thomas 	/* SOFT + md classes */
5355f5f9340bSFabien Thomas 	n = 1 + nclasses;
5356693cd307SMitchell Horne 	md = malloc(sizeof(struct pmc_mdep) + n * sizeof(struct pmc_classdep),
5357693cd307SMitchell Horne 	    M_PMC, M_WAITOK | M_ZERO);
5358f5f9340bSFabien Thomas 	md->pmd_nclass = n;
5359f5f9340bSFabien Thomas 
5360fa88954fSMitchell Horne 	/* Default methods */
5361fa88954fSMitchell Horne 	md->pmd_switch_in = generic_switch_in;
5362fa88954fSMitchell Horne 	md->pmd_switch_out = generic_switch_out;
5363fa88954fSMitchell Horne 
5364f5f9340bSFabien Thomas 	/* Add base class. */
5365f5f9340bSFabien Thomas 	pmc_soft_initialize(md);
536652ebac7fSMitchell Horne 	return (md);
5367f5f9340bSFabien Thomas }
5368f5f9340bSFabien Thomas 
5369f5f9340bSFabien Thomas void
5370f5f9340bSFabien Thomas pmc_mdep_free(struct pmc_mdep *md)
5371f5f9340bSFabien Thomas {
5372f5f9340bSFabien Thomas 	pmc_soft_finalize(md);
5373f5f9340bSFabien Thomas 	free(md, M_PMC);
5374f5f9340bSFabien Thomas }
5375f5f9340bSFabien Thomas 
5376f5f9340bSFabien Thomas static int
537701c35b67SMitchell Horne generic_switch_in(struct pmc_cpu *pc __unused, struct pmc_process *pp __unused)
5378f5f9340bSFabien Thomas {
5379f5f9340bSFabien Thomas 
5380f5f9340bSFabien Thomas 	return (0);
5381f5f9340bSFabien Thomas }
5382f5f9340bSFabien Thomas 
5383f5f9340bSFabien Thomas static int
538401c35b67SMitchell Horne generic_switch_out(struct pmc_cpu *pc __unused, struct pmc_process *pp __unused)
5385f5f9340bSFabien Thomas {
5386f5f9340bSFabien Thomas 
5387f5f9340bSFabien Thomas 	return (0);
5388f5f9340bSFabien Thomas }
5389f5f9340bSFabien Thomas 
5390f5f9340bSFabien Thomas static struct pmc_mdep *
5391f5f9340bSFabien Thomas pmc_generic_cpu_initialize(void)
5392f5f9340bSFabien Thomas {
5393f5f9340bSFabien Thomas 	struct pmc_mdep *md;
5394f5f9340bSFabien Thomas 
5395f5f9340bSFabien Thomas 	md = pmc_mdep_alloc(0);
5396f5f9340bSFabien Thomas 
5397f5f9340bSFabien Thomas 	md->pmd_cputype = PMC_CPU_GENERIC;
5398f5f9340bSFabien Thomas 
5399f5f9340bSFabien Thomas 	return (md);
5400f5f9340bSFabien Thomas }
5401f5f9340bSFabien Thomas 
5402f5f9340bSFabien Thomas static void
540301c35b67SMitchell Horne pmc_generic_cpu_finalize(struct pmc_mdep *md __unused)
5404f5f9340bSFabien Thomas {
5405f5f9340bSFabien Thomas 
540601c35b67SMitchell Horne }
5407f5f9340bSFabien Thomas 
5408ebccf1e3SJoseph Koshy static int
5409ebccf1e3SJoseph Koshy pmc_initialize(void)
5410ebccf1e3SJoseph Koshy {
5411e6b475e0SMatt Macy 	struct pcpu *pc;
5412ebccf1e3SJoseph Koshy 	struct pmc_binding pb;
5413e829eb6dSJoseph Koshy 	struct pmc_classdep *pcd;
541401c35b67SMitchell Horne 	struct pmc_sample *ps;
5415f263522aSJoseph Koshy 	struct pmc_samplebuffer *sb;
541601c35b67SMitchell Horne 	int c, cpu, error, n, ri;
541701c35b67SMitchell Horne 	u_int maxcpu, domain;
5418ebccf1e3SJoseph Koshy 
5419ebccf1e3SJoseph Koshy 	md = NULL;
5420ebccf1e3SJoseph Koshy 	error = 0;
5421ebccf1e3SJoseph Koshy 
5422e6b475e0SMatt Macy 	pmc_stats.pm_intr_ignored = counter_u64_alloc(M_WAITOK);
5423e6b475e0SMatt Macy 	pmc_stats.pm_intr_processed = counter_u64_alloc(M_WAITOK);
5424e6b475e0SMatt Macy 	pmc_stats.pm_intr_bufferfull = counter_u64_alloc(M_WAITOK);
5425e6b475e0SMatt Macy 	pmc_stats.pm_syscalls = counter_u64_alloc(M_WAITOK);
5426e6b475e0SMatt Macy 	pmc_stats.pm_syscall_errors = counter_u64_alloc(M_WAITOK);
5427e6b475e0SMatt Macy 	pmc_stats.pm_buffer_requests = counter_u64_alloc(M_WAITOK);
5428e6b475e0SMatt Macy 	pmc_stats.pm_buffer_requests_failed = counter_u64_alloc(M_WAITOK);
5429e6b475e0SMatt Macy 	pmc_stats.pm_log_sweeps = counter_u64_alloc(M_WAITOK);
54305de96e33SMatt Macy 	pmc_stats.pm_merges = counter_u64_alloc(M_WAITOK);
54315de96e33SMatt Macy 	pmc_stats.pm_overwrites = counter_u64_alloc(M_WAITOK);
5432e6b475e0SMatt Macy 
5433680f1afdSJohn Baldwin #ifdef HWPMC_DEBUG
5434ebccf1e3SJoseph Koshy 	/* parse debug flags first */
5435ebccf1e3SJoseph Koshy 	if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
543601c35b67SMitchell Horne 	    pmc_debugstr, sizeof(pmc_debugstr))) {
543701c35b67SMitchell Horne 		pmc_debugflags_parse(pmc_debugstr, pmc_debugstr +
543801c35b67SMitchell Horne 		    strlen(pmc_debugstr));
543901c35b67SMitchell Horne 	}
5440ebccf1e3SJoseph Koshy #endif
5441ebccf1e3SJoseph Koshy 
54424a3690dfSJohn Baldwin 	PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
5443ebccf1e3SJoseph Koshy 
5444fadcc6e2SJoseph Koshy 	/* check kernel version */
5445fadcc6e2SJoseph Koshy 	if (pmc_kernel_version != PMC_VERSION) {
5446fadcc6e2SJoseph Koshy 		if (pmc_kernel_version == 0)
5447fadcc6e2SJoseph Koshy 			printf("hwpmc: this kernel has not been compiled with "
5448fadcc6e2SJoseph Koshy 			    "'options HWPMC_HOOKS'.\n");
5449fadcc6e2SJoseph Koshy 		else
5450fadcc6e2SJoseph Koshy 			printf("hwpmc: kernel version (0x%x) does not match "
5451fadcc6e2SJoseph Koshy 			    "module version (0x%x).\n", pmc_kernel_version,
5452fadcc6e2SJoseph Koshy 			    PMC_VERSION);
545352ebac7fSMitchell Horne 		return (EPROGMISMATCH);
5454fadcc6e2SJoseph Koshy 	}
5455fadcc6e2SJoseph Koshy 
5456ebccf1e3SJoseph Koshy 	/*
5457ebccf1e3SJoseph Koshy 	 * check sysctl parameters
5458ebccf1e3SJoseph Koshy 	 */
5459ebccf1e3SJoseph Koshy 	if (pmc_hashsize <= 0) {
546001c35b67SMitchell Horne 		printf("hwpmc: tunable \"hashsize\"=%d must be "
5461d07f36b0SJoseph Koshy 		    "greater than zero.\n", pmc_hashsize);
5462ebccf1e3SJoseph Koshy 		pmc_hashsize = PMC_HASH_SIZE;
5463ebccf1e3SJoseph Koshy 	}
5464ebccf1e3SJoseph Koshy 
5465f263522aSJoseph Koshy 	if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
546601c35b67SMitchell Horne 		printf("hwpmc: tunable \"nsamples\"=%d out of "
5467d07f36b0SJoseph Koshy 		    "range.\n", pmc_nsamples);
5468f263522aSJoseph Koshy 		pmc_nsamples = PMC_NSAMPLES;
5469f263522aSJoseph Koshy 	}
5470d9f1b8dbSMatt Macy 	pmc_sample_mask = pmc_nsamples - 1;
5471f263522aSJoseph Koshy 
5472d07f36b0SJoseph Koshy 	if (pmc_callchaindepth <= 0 ||
5473d07f36b0SJoseph Koshy 	    pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
547401c35b67SMitchell Horne 		printf("hwpmc: tunable \"callchaindepth\"=%d out of "
5475201b654eSEd Maste 		    "range - using %d.\n", pmc_callchaindepth,
5476201b654eSEd Maste 		    PMC_CALLCHAIN_DEPTH_MAX);
5477201b654eSEd Maste 		pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX;
5478d07f36b0SJoseph Koshy 	}
5479d07f36b0SJoseph Koshy 
5480f263522aSJoseph Koshy 	md = pmc_md_initialize();
5481f5f9340bSFabien Thomas 	if (md == NULL) {
5482f5f9340bSFabien Thomas 		/* Default to generic CPU. */
5483f5f9340bSFabien Thomas 		md = pmc_generic_cpu_initialize();
5484e829eb6dSJoseph Koshy 		if (md == NULL)
5485e829eb6dSJoseph Koshy 			return (ENOSYS);
5486f5f9340bSFabien Thomas         }
5487e829eb6dSJoseph Koshy 
5488fdfeaa66SAleksandr Rybalko 	/*
5489fdfeaa66SAleksandr Rybalko 	 * Refresh classes base ri. Optional classes may come in different
5490fdfeaa66SAleksandr Rybalko 	 * order.
5491fdfeaa66SAleksandr Rybalko 	 */
5492fdfeaa66SAleksandr Rybalko 	for (ri = c = 0; c < md->pmd_nclass; c++) {
5493fdfeaa66SAleksandr Rybalko 		pcd = &md->pmd_classdep[c];
5494fdfeaa66SAleksandr Rybalko 		pcd->pcd_ri = ri;
5495fdfeaa66SAleksandr Rybalko 		ri += pcd->pcd_num;
5496fdfeaa66SAleksandr Rybalko 	}
5497fdfeaa66SAleksandr Rybalko 
5498e829eb6dSJoseph Koshy 	KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
5499e829eb6dSJoseph Koshy 	    ("[pmc,%d] no classes or pmcs", __LINE__));
5500e829eb6dSJoseph Koshy 
5501e829eb6dSJoseph Koshy 	/* Compute the map from row-indices to classdep pointers. */
5502e829eb6dSJoseph Koshy 	pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
5503e829eb6dSJoseph Koshy 	    md->pmd_npmc, M_PMC, M_WAITOK | M_ZERO);
5504e829eb6dSJoseph Koshy 
5505e829eb6dSJoseph Koshy 	for (n = 0; n < md->pmd_npmc; n++)
5506e829eb6dSJoseph Koshy 		pmc_rowindex_to_classdep[n] = NULL;
5507693cd307SMitchell Horne 
5508e829eb6dSJoseph Koshy 	for (ri = c = 0; c < md->pmd_nclass; c++) {
5509e829eb6dSJoseph Koshy 		pcd = &md->pmd_classdep[c];
5510e829eb6dSJoseph Koshy 		for (n = 0; n < pcd->pcd_num; n++, ri++)
5511e829eb6dSJoseph Koshy 			pmc_rowindex_to_classdep[ri] = pcd;
5512e829eb6dSJoseph Koshy 	}
5513e829eb6dSJoseph Koshy 
5514e829eb6dSJoseph Koshy 	KASSERT(ri == md->pmd_npmc,
5515e829eb6dSJoseph Koshy 	    ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
5516e829eb6dSJoseph Koshy 	    ri, md->pmd_npmc));
5517ebccf1e3SJoseph Koshy 
5518122ccdc1SJoseph Koshy 	maxcpu = pmc_cpu_max();
5519122ccdc1SJoseph Koshy 
5520ebccf1e3SJoseph Koshy 	/* allocate space for the per-cpu array */
5521e829eb6dSJoseph Koshy 	pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
5522e829eb6dSJoseph Koshy 	    M_WAITOK | M_ZERO);
5523ebccf1e3SJoseph Koshy 
5524ebccf1e3SJoseph Koshy 	/* per-cpu 'saved values' for managing process-mode PMCs */
5525e11e3f18SDag-Erling Smørgrav 	pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
5526e11e3f18SDag-Erling Smørgrav 	    M_PMC, M_WAITOK);
5527ebccf1e3SJoseph Koshy 
5528122ccdc1SJoseph Koshy 	/* Perform CPU-dependent initialization. */
5529ebccf1e3SJoseph Koshy 	pmc_save_cpu_binding(&pb);
5530e829eb6dSJoseph Koshy 	error = 0;
5531e829eb6dSJoseph Koshy 	for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
5532122ccdc1SJoseph Koshy 		if (!pmc_cpu_is_active(cpu))
5533ebccf1e3SJoseph Koshy 			continue;
5534ebccf1e3SJoseph Koshy 		pmc_select_cpu(cpu);
5535e829eb6dSJoseph Koshy 		pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
5536e829eb6dSJoseph Koshy 		    md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
5537e829eb6dSJoseph Koshy 		    M_WAITOK | M_ZERO);
5538e829eb6dSJoseph Koshy 		for (n = 0; error == 0 && n < md->pmd_nclass; n++)
5539fdfeaa66SAleksandr Rybalko 			if (md->pmd_classdep[n].pcd_num > 0)
5540fdfeaa66SAleksandr Rybalko 				error = md->pmd_classdep[n].pcd_pcpu_init(md,
5541fdfeaa66SAleksandr Rybalko 				    cpu);
5542ebccf1e3SJoseph Koshy 	}
5543ebccf1e3SJoseph Koshy 	pmc_restore_cpu_binding(&pb);
5544ebccf1e3SJoseph Koshy 
5545d5ee4074SMitchell Horne 	if (error != 0)
5546e829eb6dSJoseph Koshy 		return (error);
5547ebccf1e3SJoseph Koshy 
5548f263522aSJoseph Koshy 	/* allocate space for the sample array */
5549122ccdc1SJoseph Koshy 	for (cpu = 0; cpu < maxcpu; cpu++) {
5550122ccdc1SJoseph Koshy 		if (!pmc_cpu_is_active(cpu))
5551f263522aSJoseph Koshy 			continue;
5552e6b475e0SMatt Macy 		pc = pcpu_find(cpu);
5553e6b475e0SMatt Macy 		domain = pc->pc_domain;
55549978bd99SMark Johnston 		sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
55559978bd99SMark Johnston 		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
55569978bd99SMark Johnston 		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5557e829eb6dSJoseph Koshy 
5558f263522aSJoseph Koshy 		KASSERT(pmc_pcpu[cpu] != NULL,
5559f263522aSJoseph Koshy 		    ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
5560f263522aSJoseph Koshy 
55619978bd99SMark Johnston 		sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
55629978bd99SMark Johnston 		    pmc_nsamples * sizeof(uintptr_t), M_PMC,
55639978bd99SMark Johnston 		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5564d07f36b0SJoseph Koshy 
5565d07f36b0SJoseph Koshy 		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5566d07f36b0SJoseph Koshy 			ps->ps_pc = sb->ps_callchains +
5567d07f36b0SJoseph Koshy 			    (n * pmc_callchaindepth);
5568d07f36b0SJoseph Koshy 
5569f5f9340bSFabien Thomas 		pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
5570f5f9340bSFabien Thomas 
55719978bd99SMark Johnston 		sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
55729978bd99SMark Johnston 		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
55739978bd99SMark Johnston 		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5574f5f9340bSFabien Thomas 
55759978bd99SMark Johnston 		sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
55769978bd99SMark Johnston 		    pmc_nsamples * sizeof(uintptr_t), M_PMC,
55779978bd99SMark Johnston 		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5578f5f9340bSFabien Thomas 		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5579f5f9340bSFabien Thomas 			ps->ps_pc = sb->ps_callchains +
5580f5f9340bSFabien Thomas 			    (n * pmc_callchaindepth);
5581f5f9340bSFabien Thomas 
5582f5f9340bSFabien Thomas 		pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
55835de96e33SMatt Macy 
55849978bd99SMark Johnston 		sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
55859978bd99SMark Johnston 		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
55869978bd99SMark Johnston 		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
55879978bd99SMark Johnston 		sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
55889978bd99SMark Johnston 		    pmc_nsamples * sizeof(uintptr_t), M_PMC,
55899978bd99SMark Johnston 		    DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
55905de96e33SMatt Macy 		for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
55919978bd99SMark Johnston 			ps->ps_pc = sb->ps_callchains + n * pmc_callchaindepth;
55925de96e33SMatt Macy 
55935de96e33SMatt Macy 		pmc_pcpu[cpu]->pc_sb[PMC_UR] = sb;
5594f263522aSJoseph Koshy 	}
5595f263522aSJoseph Koshy 
5596ebccf1e3SJoseph Koshy 	/* allocate space for the row disposition array */
5597ebccf1e3SJoseph Koshy 	pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
5598ebccf1e3SJoseph Koshy 	    M_PMC, M_WAITOK | M_ZERO);
5599ebccf1e3SJoseph Koshy 
5600ebccf1e3SJoseph Koshy 	/* mark all PMCs as available */
560101c35b67SMitchell Horne 	for (n = 0; n < md->pmd_npmc; n++)
5602ebccf1e3SJoseph Koshy 		PMC_MARK_ROW_FREE(n);
5603ebccf1e3SJoseph Koshy 
5604ebccf1e3SJoseph Koshy 	/* allocate thread hash tables */
5605ebccf1e3SJoseph Koshy 	pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
5606ebccf1e3SJoseph Koshy 	    &pmc_ownerhashmask);
5607ebccf1e3SJoseph Koshy 
5608ebccf1e3SJoseph Koshy 	pmc_processhash = hashinit(pmc_hashsize, M_PMC,
5609ebccf1e3SJoseph Koshy 	    &pmc_processhashmask);
5610382d30cdSJoseph Koshy 	mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
5611382d30cdSJoseph Koshy 	    MTX_SPIN);
5612ebccf1e3SJoseph Koshy 
56130f8d79d9SMatt Macy 	CK_LIST_INIT(&pmc_ss_owners);
5614f263522aSJoseph Koshy 	pmc_ss_count = 0;
5615f263522aSJoseph Koshy 
5616ebccf1e3SJoseph Koshy 	/* allocate a pool of spin mutexes */
5617382d30cdSJoseph Koshy 	pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
5618382d30cdSJoseph Koshy 	    MTX_SPIN);
5619ebccf1e3SJoseph Koshy 
56204a3690dfSJohn Baldwin 	PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
5621ebccf1e3SJoseph Koshy 	    "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
5622ebccf1e3SJoseph Koshy 	    pmc_processhash, pmc_processhashmask);
5623ebccf1e3SJoseph Koshy 
56246161b98cSMatt Macy 	/* Initialize a spin mutex for the thread free list. */
56256161b98cSMatt Macy 	mtx_init(&pmc_threadfreelist_mtx, "pmc-threadfreelist", "pmc-leaf",
56266161b98cSMatt Macy 	    MTX_SPIN);
56276161b98cSMatt Macy 
56289b1d850bSMark Johnston 	/* Initialize the task to prune the thread free list. */
56299b1d850bSMark Johnston 	TASK_INIT(&free_task, 0, pmc_thread_descriptor_pool_free_task, NULL);
56306161b98cSMatt Macy 
5631ebccf1e3SJoseph Koshy 	/* register process {exit,fork,exec} handlers */
5632ebccf1e3SJoseph Koshy 	pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
5633ebccf1e3SJoseph Koshy 	    pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
5634ebccf1e3SJoseph Koshy 	pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
5635ebccf1e3SJoseph Koshy 	    pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
5636ebccf1e3SJoseph Koshy 
563729f4e216SMark Johnston 	/* register kld event handlers */
563829f4e216SMark Johnston 	pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
563929f4e216SMark Johnston 	    NULL, EVENTHANDLER_PRI_ANY);
564029f4e216SMark Johnston 	pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
564129f4e216SMark Johnston 	    NULL, EVENTHANDLER_PRI_ANY);
564229f4e216SMark Johnston 
5643f263522aSJoseph Koshy 	/* initialize logging */
5644f263522aSJoseph Koshy 	pmclog_initialize();
5645f263522aSJoseph Koshy 
5646ebccf1e3SJoseph Koshy 	/* set hook functions */
5647ebccf1e3SJoseph Koshy 	pmc_intr = md->pmd_intr;
56480f00315cSMatt Macy 	wmb();
5649ebccf1e3SJoseph Koshy 	pmc_hook = pmc_hook_handler;
5650ebccf1e3SJoseph Koshy 
5651ebccf1e3SJoseph Koshy 	if (error == 0) {
5652ebccf1e3SJoseph Koshy 		printf(PMC_MODULE_NAME ":");
565301c35b67SMitchell Horne 		for (n = 0; n < md->pmd_nclass; n++) {
5654fdfeaa66SAleksandr Rybalko 			if (md->pmd_classdep[n].pcd_num == 0)
5655fdfeaa66SAleksandr Rybalko 				continue;
5656e829eb6dSJoseph Koshy 			pcd = &md->pmd_classdep[n];
56577dada264SJoseph Koshy 			printf(" %s/%d/%d/0x%b",
56580ceb54c2SJohn Baldwin 			    pmc_name_of_pmcclass(pcd->pcd_class),
5659e829eb6dSJoseph Koshy 			    pcd->pcd_num,
56607dada264SJoseph Koshy 			    pcd->pcd_width,
5661e829eb6dSJoseph Koshy 			    pcd->pcd_caps,
5662a8eb16c5SJoseph Koshy 			    "\20"
5663a8eb16c5SJoseph Koshy 			    "\1INT\2USR\3SYS\4EDG\5THR"
5664a8eb16c5SJoseph Koshy 			    "\6REA\7WRI\10INV\11QUA\12PRC"
5665a8eb16c5SJoseph Koshy 			    "\13TAG\14CSC");
5666a8eb16c5SJoseph Koshy 		}
5667ebccf1e3SJoseph Koshy 		printf("\n");
5668ebccf1e3SJoseph Koshy 	}
5669ebccf1e3SJoseph Koshy 
5670e829eb6dSJoseph Koshy 	return (error);
5671ebccf1e3SJoseph Koshy }
5672ebccf1e3SJoseph Koshy 
5673ebccf1e3SJoseph Koshy /* prepare to be unloaded */
5674ebccf1e3SJoseph Koshy static void
5675ebccf1e3SJoseph Koshy pmc_cleanup(void)
5676ebccf1e3SJoseph Koshy {
5677ebccf1e3SJoseph Koshy 	struct pmc_binding pb;
567801c35b67SMitchell Horne 	struct pmc_owner *po, *tmp;
567901c35b67SMitchell Horne 	struct pmc_ownerhash *ph;
568001c35b67SMitchell Horne 	struct pmc_processhash *prh __pmcdbg_used;
568101c35b67SMitchell Horne 	u_int maxcpu;
568201c35b67SMitchell Horne 	int cpu, c;
5683ebccf1e3SJoseph Koshy 
56844a3690dfSJohn Baldwin 	PMCDBG0(MOD,INI,0, "cleanup");
5685ebccf1e3SJoseph Koshy 
5686f263522aSJoseph Koshy 	/* switch off sampling */
5687e6b475e0SMatt Macy 	CPU_FOREACH(cpu)
5688e6b475e0SMatt Macy 		DPCPU_ID_SET(cpu, pmc_sampled, 0);
5689f263522aSJoseph Koshy 	pmc_intr = NULL;
5690ebccf1e3SJoseph Koshy 
5691ebccf1e3SJoseph Koshy 	sx_xlock(&pmc_sx);
5692ebccf1e3SJoseph Koshy 	if (pmc_hook == NULL) {	/* being unloaded already */
5693ebccf1e3SJoseph Koshy 		sx_xunlock(&pmc_sx);
5694ebccf1e3SJoseph Koshy 		return;
5695ebccf1e3SJoseph Koshy 	}
5696ebccf1e3SJoseph Koshy 
5697ebccf1e3SJoseph Koshy 	pmc_hook = NULL; /* prevent new threads from entering module */
5698ebccf1e3SJoseph Koshy 
5699ebccf1e3SJoseph Koshy 	/* deregister event handlers */
5700ebccf1e3SJoseph Koshy 	EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
5701ebccf1e3SJoseph Koshy 	EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
570229f4e216SMark Johnston 	EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
570329f4e216SMark Johnston 	EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);
5704ebccf1e3SJoseph Koshy 
5705ebccf1e3SJoseph Koshy 	/* send SIGBUS to all owner threads, free up allocations */
5706d5ee4074SMitchell Horne 	if (pmc_ownerhash != NULL) {
5707ebccf1e3SJoseph Koshy 		for (ph = pmc_ownerhash;
5708ebccf1e3SJoseph Koshy 		     ph <= &pmc_ownerhash[pmc_ownerhashmask];
5709ebccf1e3SJoseph Koshy 		     ph++) {
5710ebccf1e3SJoseph Koshy 			LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
5711ebccf1e3SJoseph Koshy 				pmc_remove_owner(po);
5712ebccf1e3SJoseph Koshy 
571301c35b67SMitchell Horne 				PMCDBG3(MOD,INI,2,
571401c35b67SMitchell Horne 				    "cleanup signal proc=%p (%d, %s)",
571501c35b67SMitchell Horne 				    po->po_owner, po->po_owner->p_pid,
5716ebccf1e3SJoseph Koshy 				    po->po_owner->p_comm);
5717ebccf1e3SJoseph Koshy 
5718ebccf1e3SJoseph Koshy 				PROC_LOCK(po->po_owner);
57198451d0ddSKip Macy 				kern_psignal(po->po_owner, SIGBUS);
5720ebccf1e3SJoseph Koshy 				PROC_UNLOCK(po->po_owner);
5721f263522aSJoseph Koshy 
5722f263522aSJoseph Koshy 				pmc_destroy_owner_descriptor(po);
5723ebccf1e3SJoseph Koshy 			}
5724ebccf1e3SJoseph Koshy 		}
5725d5ee4074SMitchell Horne 	}
5726ebccf1e3SJoseph Koshy 
5727ebccf1e3SJoseph Koshy 	/* reclaim allocated data structures */
57289b1d850bSMark Johnston 	taskqueue_drain(taskqueue_fast, &free_task);
57296161b98cSMatt Macy 	mtx_destroy(&pmc_threadfreelist_mtx);
57306161b98cSMatt Macy 	pmc_thread_descriptor_pool_drain();
57316161b98cSMatt Macy 
5732d5ee4074SMitchell Horne 	if (pmc_mtxpool != NULL)
5733ebccf1e3SJoseph Koshy 		mtx_pool_destroy(&pmc_mtxpool);
5734ebccf1e3SJoseph Koshy 
5735ebccf1e3SJoseph Koshy 	mtx_destroy(&pmc_processhash_mtx);
5736d5ee4074SMitchell Horne 	if (pmc_processhash != NULL) {
5737680f1afdSJohn Baldwin #ifdef HWPMC_DEBUG
5738ebccf1e3SJoseph Koshy 		struct pmc_process *pp;
5739ebccf1e3SJoseph Koshy 
57404a3690dfSJohn Baldwin 		PMCDBG0(MOD,INI,3, "destroy process hash");
5741ebccf1e3SJoseph Koshy 		for (prh = pmc_processhash;
5742ebccf1e3SJoseph Koshy 		     prh <= &pmc_processhash[pmc_processhashmask];
5743ebccf1e3SJoseph Koshy 		     prh++)
5744ebccf1e3SJoseph Koshy 			LIST_FOREACH(pp, prh, pp_next)
57454a3690dfSJohn Baldwin 			    PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5746ebccf1e3SJoseph Koshy #endif
5747ebccf1e3SJoseph Koshy 
5748ebccf1e3SJoseph Koshy 		hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5749ebccf1e3SJoseph Koshy 		pmc_processhash = NULL;
5750ebccf1e3SJoseph Koshy 	}
5751ebccf1e3SJoseph Koshy 
5752d5ee4074SMitchell Horne 	if (pmc_ownerhash != NULL) {
57534a3690dfSJohn Baldwin 		PMCDBG0(MOD,INI,3, "destroy owner hash");
5754ebccf1e3SJoseph Koshy 		hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5755ebccf1e3SJoseph Koshy 		pmc_ownerhash = NULL;
5756ebccf1e3SJoseph Koshy 	}
5757ebccf1e3SJoseph Koshy 
57580f8d79d9SMatt Macy 	KASSERT(CK_LIST_EMPTY(&pmc_ss_owners),
5759f263522aSJoseph Koshy 	    ("[pmc,%d] Global SS owner list not empty", __LINE__));
5760f263522aSJoseph Koshy 	KASSERT(pmc_ss_count == 0,
5761f263522aSJoseph Koshy 	    ("[pmc,%d] Global SS count not empty", __LINE__));
5762f263522aSJoseph Koshy 
5763e829eb6dSJoseph Koshy  	/* do processor and pmc-class dependent cleanup */
5764122ccdc1SJoseph Koshy 	maxcpu = pmc_cpu_max();
5765ba8ae2deSJoseph Koshy 
57664a3690dfSJohn Baldwin 	PMCDBG0(MOD,INI,3, "md cleanup");
5767ebccf1e3SJoseph Koshy 	if (md) {
5768ebccf1e3SJoseph Koshy 		pmc_save_cpu_binding(&pb);
5769122ccdc1SJoseph Koshy 		for (cpu = 0; cpu < maxcpu; cpu++) {
57704a3690dfSJohn Baldwin 			PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5771ebccf1e3SJoseph Koshy 			    cpu, pmc_pcpu[cpu]);
5772122ccdc1SJoseph Koshy 			if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5773ebccf1e3SJoseph Koshy 				continue;
5774693cd307SMitchell Horne 
5775ebccf1e3SJoseph Koshy 			pmc_select_cpu(cpu);
5776d5ee4074SMitchell Horne 			for (c = 0; c < md->pmd_nclass; c++) {
5777d5ee4074SMitchell Horne 				if (md->pmd_classdep[c].pcd_num > 0) {
5778fdfeaa66SAleksandr Rybalko 					md->pmd_classdep[c].pcd_pcpu_fini(md,
5779fdfeaa66SAleksandr Rybalko 					    cpu);
5780ebccf1e3SJoseph Koshy 				}
5781d5ee4074SMitchell Horne 			}
5782d5ee4074SMitchell Horne 		}
5783bc4f0adeSJoseph Koshy 
5784f5f9340bSFabien Thomas 		if (md->pmd_cputype == PMC_CPU_GENERIC)
5785f5f9340bSFabien Thomas 			pmc_generic_cpu_finalize(md);
5786f5f9340bSFabien Thomas 		else
5787bc4f0adeSJoseph Koshy 			pmc_md_finalize(md);
5788bc4f0adeSJoseph Koshy 
5789f5f9340bSFabien Thomas 		pmc_mdep_free(md);
5790ebccf1e3SJoseph Koshy 		md = NULL;
5791ebccf1e3SJoseph Koshy 		pmc_restore_cpu_binding(&pb);
5792ebccf1e3SJoseph Koshy 	}
5793ebccf1e3SJoseph Koshy 
5794e829eb6dSJoseph Koshy 	/* Free per-cpu descriptors. */
5795e829eb6dSJoseph Koshy 	for (cpu = 0; cpu < maxcpu; cpu++) {
5796e829eb6dSJoseph Koshy 		if (!pmc_cpu_is_active(cpu))
5797e829eb6dSJoseph Koshy 			continue;
5798f5f9340bSFabien Thomas 		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5799f5f9340bSFabien Thomas 		    ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5800e829eb6dSJoseph Koshy 			cpu));
5801f5f9340bSFabien Thomas 		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5802f5f9340bSFabien Thomas 		    ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5803f5f9340bSFabien Thomas 			cpu));
58045de96e33SMatt Macy 		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_UR] != NULL,
58055de96e33SMatt Macy 		    ("[pmc,%d] Null userret cpu sample buffer cpu=%d", __LINE__,
58065de96e33SMatt Macy 			cpu));
580796ad26eeSMark Johnston 		free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
580896ad26eeSMark Johnston 		free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
580996ad26eeSMark Johnston 		free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
581096ad26eeSMark Johnston 		free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
581196ad26eeSMark Johnston 		free(pmc_pcpu[cpu]->pc_sb[PMC_UR]->ps_callchains, M_PMC);
581296ad26eeSMark Johnston 		free(pmc_pcpu[cpu]->pc_sb[PMC_UR], M_PMC);
581396ad26eeSMark Johnston 		free(pmc_pcpu[cpu], M_PMC);
5814e829eb6dSJoseph Koshy 	}
5815e829eb6dSJoseph Koshy 
58161ede983cSDag-Erling Smørgrav 	free(pmc_pcpu, M_PMC);
5817ebccf1e3SJoseph Koshy 	pmc_pcpu = NULL;
5818ebccf1e3SJoseph Koshy 
58191ede983cSDag-Erling Smørgrav 	free(pmc_pcpu_saved, M_PMC);
5820ebccf1e3SJoseph Koshy 	pmc_pcpu_saved = NULL;
5821ebccf1e3SJoseph Koshy 
5822d5ee4074SMitchell Horne 	if (pmc_pmcdisp != NULL) {
58231ede983cSDag-Erling Smørgrav 		free(pmc_pmcdisp, M_PMC);
5824ebccf1e3SJoseph Koshy 		pmc_pmcdisp = NULL;
5825ebccf1e3SJoseph Koshy 	}
5826ebccf1e3SJoseph Koshy 
5827d5ee4074SMitchell Horne 	if (pmc_rowindex_to_classdep != NULL) {
5828e829eb6dSJoseph Koshy 		free(pmc_rowindex_to_classdep, M_PMC);
5829e829eb6dSJoseph Koshy 		pmc_rowindex_to_classdep = NULL;
5830e829eb6dSJoseph Koshy 	}
5831e829eb6dSJoseph Koshy 
5832f263522aSJoseph Koshy 	pmclog_shutdown();
5833e6b475e0SMatt Macy 	counter_u64_free(pmc_stats.pm_intr_ignored);
5834e6b475e0SMatt Macy 	counter_u64_free(pmc_stats.pm_intr_processed);
5835e6b475e0SMatt Macy 	counter_u64_free(pmc_stats.pm_intr_bufferfull);
5836e6b475e0SMatt Macy 	counter_u64_free(pmc_stats.pm_syscalls);
5837e6b475e0SMatt Macy 	counter_u64_free(pmc_stats.pm_syscall_errors);
5838e6b475e0SMatt Macy 	counter_u64_free(pmc_stats.pm_buffer_requests);
5839e6b475e0SMatt Macy 	counter_u64_free(pmc_stats.pm_buffer_requests_failed);
5840e6b475e0SMatt Macy 	counter_u64_free(pmc_stats.pm_log_sweeps);
58415de96e33SMatt Macy 	counter_u64_free(pmc_stats.pm_merges);
58425de96e33SMatt Macy 	counter_u64_free(pmc_stats.pm_overwrites);
5843ebccf1e3SJoseph Koshy 	sx_xunlock(&pmc_sx);	/* we are done */
5844ebccf1e3SJoseph Koshy }
5845ebccf1e3SJoseph Koshy 
5846ebccf1e3SJoseph Koshy /*
5847ebccf1e3SJoseph Koshy  * The function called at load/unload.
5848ebccf1e3SJoseph Koshy  */
5849ebccf1e3SJoseph Koshy static int
5850ebccf1e3SJoseph Koshy load(struct module *module __unused, int cmd, void *arg __unused)
5851ebccf1e3SJoseph Koshy {
5852ebccf1e3SJoseph Koshy 	int error;
5853ebccf1e3SJoseph Koshy 
5854ebccf1e3SJoseph Koshy 	error = 0;
5855ebccf1e3SJoseph Koshy 
5856ebccf1e3SJoseph Koshy 	switch (cmd) {
5857ebccf1e3SJoseph Koshy 	case MOD_LOAD:
5858ebccf1e3SJoseph Koshy 		/* initialize the subsystem */
5859ebccf1e3SJoseph Koshy 		error = pmc_initialize();
5860ebccf1e3SJoseph Koshy 		if (error != 0)
5861ebccf1e3SJoseph Koshy 			break;
5862693cd307SMitchell Horne 		PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d", pmc_syscall_num,
5863693cd307SMitchell Horne 		    pmc_cpu_max());
5864ebccf1e3SJoseph Koshy 		break;
5865ebccf1e3SJoseph Koshy 	case MOD_UNLOAD:
5866ebccf1e3SJoseph Koshy 	case MOD_SHUTDOWN:
5867ebccf1e3SJoseph Koshy 		pmc_cleanup();
58684a3690dfSJohn Baldwin 		PMCDBG0(MOD,INI,1, "unloaded");
5869ebccf1e3SJoseph Koshy 		break;
5870ebccf1e3SJoseph Koshy 	default:
5871693cd307SMitchell Horne 		error = EINVAL;
5872ebccf1e3SJoseph Koshy 		break;
5873ebccf1e3SJoseph Koshy 	}
5874ebccf1e3SJoseph Koshy 
587552ebac7fSMitchell Horne 	return (error);
5876ebccf1e3SJoseph Koshy }
5877