2 * Copyright (c) 2003-2008 Joseph Koshy
3 * Copyright (c) 2007 The FreeBSD Foundation
6 * Portions of this software were developed by A. Joseph Koshy under
7 * sponsorship from the FreeBSD Foundation and Google, Inc.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/eventhandler.h>
38 #include <sys/kernel.h>
39 #include <sys/kthread.h>
40 #include <sys/limits.h>
42 #include <sys/malloc.h>
43 #include <sys/module.h>
44 #include <sys/mutex.h>
46 #include <sys/pmckern.h>
47 #include <sys/pmclog.h>
50 #include <sys/queue.h>
51 #include <sys/resourcevar.h>
52 #include <sys/sched.h>
53 #include <sys/signalvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysent.h>
58 #include <sys/systm.h>
59 #include <sys/vnode.h>
61 #include <sys/linker.h> /* needs to be after <sys/malloc.h> */
63 #include <machine/atomic.h>
64 #include <machine/md_var.h>
71 PMC_FLAG_NONE = 0x00, /* do nothing */
72 PMC_FLAG_REMOVE = 0x01, /* atomically remove entry from hash */
73 PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
77 * The offset in sysent where the syscall is allocated.
80 static int pmc_syscall_num = NO_SYSCALL;
81 struct pmc_cpu **pmc_pcpu; /* per-cpu state */
82 pmc_value_t *pmc_pcpu_saved; /* saved PMC values: CSW handling */
84 #define PMC_PCPU_SAVED(C,R) pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
86 struct mtx_pool *pmc_mtxpool;
87 static int *pmc_pmcdisp; /* PMC row dispositions */
89 #define PMC_ROW_DISP_IS_FREE(R) (pmc_pmcdisp[(R)] == 0)
90 #define PMC_ROW_DISP_IS_THREAD(R) (pmc_pmcdisp[(R)] > 0)
91 #define PMC_ROW_DISP_IS_STANDALONE(R) (pmc_pmcdisp[(R)] < 0)
93 #define PMC_MARK_ROW_FREE(R) do { \
94 pmc_pmcdisp[(R)] = 0; \
97 #define PMC_MARK_ROW_STANDALONE(R) do { \
98 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
100 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
101 KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()), \
102 ("[pmc,%d] row disposition error", __LINE__)); \
105 #define PMC_UNMARK_ROW_STANDALONE(R) do { \
106 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
107 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
111 #define PMC_MARK_ROW_THREAD(R) do { \
112 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
114 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
117 #define PMC_UNMARK_ROW_THREAD(R) do { \
118 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
119 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
124 /* various event handlers */
125 static eventhandler_tag pmc_exit_tag, pmc_fork_tag;
127 /* Module statistics */
128 struct pmc_op_getdriverstats pmc_stats;
130 /* Machine/processor dependent operations */
131 static struct pmc_mdep *md;
134 * Hash tables mapping owner processes and target threads to PMCs.
137 struct mtx pmc_processhash_mtx; /* spin mutex */
138 static u_long pmc_processhashmask;
139 static LIST_HEAD(pmc_processhash, pmc_process) *pmc_processhash;
142 * Hash table of PMC owner descriptors. This table is protected by
143 * the shared PMC "sx" lock.
146 static u_long pmc_ownerhashmask;
147 static LIST_HEAD(pmc_ownerhash, pmc_owner) *pmc_ownerhash;
150 * List of PMC owners with system-wide sampling PMCs.
153 static LIST_HEAD(, pmc_owner) pmc_ss_owners;
157 * A map of row indices to classdep structures.
159 static struct pmc_classdep **pmc_rowindex_to_classdep;
166 static int pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
167 static int pmc_debugflags_parse(char *newstr, char *fence);
170 static int load(struct module *module, int cmd, void *arg);
171 static int pmc_attach_process(struct proc *p, struct pmc *pm);
172 static struct pmc *pmc_allocate_pmc_descriptor(void);
173 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
174 static int pmc_attach_one_process(struct proc *p, struct pmc *pm);
175 static int pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
177 static int pmc_can_attach(struct pmc *pm, struct proc *p);
178 static void pmc_capture_user_callchain(int cpu, struct trapframe *tf);
179 static void pmc_cleanup(void);
180 static int pmc_detach_process(struct proc *p, struct pmc *pm);
181 static int pmc_detach_one_process(struct proc *p, struct pmc *pm,
183 static void pmc_destroy_owner_descriptor(struct pmc_owner *po);
184 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
185 static int pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
186 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
188 static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
190 static void pmc_force_context_switch(void);
191 static void pmc_link_target_process(struct pmc *pm,
192 struct pmc_process *pp);
193 static void pmc_log_all_process_mappings(struct pmc_owner *po);
194 static void pmc_log_kernel_mappings(struct pmc *pm);
195 static void pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
196 static void pmc_maybe_remove_owner(struct pmc_owner *po);
197 static void pmc_process_csw_in(struct thread *td);
198 static void pmc_process_csw_out(struct thread *td);
199 static void pmc_process_exit(void *arg, struct proc *p);
200 static void pmc_process_fork(void *arg, struct proc *p1,
201 struct proc *p2, int n);
202 static void pmc_process_samples(int cpu);
203 static void pmc_release_pmc_descriptor(struct pmc *pmc);
204 static void pmc_remove_owner(struct pmc_owner *po);
205 static void pmc_remove_process_descriptor(struct pmc_process *pp);
206 static void pmc_restore_cpu_binding(struct pmc_binding *pb);
207 static void pmc_save_cpu_binding(struct pmc_binding *pb);
208 static void pmc_select_cpu(int cpu);
209 static int pmc_start(struct pmc *pm);
210 static int pmc_stop(struct pmc *pm);
211 static int pmc_syscall_handler(struct thread *td, void *syscall_args);
212 static void pmc_unlink_target_process(struct pmc *pmc,
213 struct pmc_process *pp);
216 * Kernel tunables and sysctl(8) interface.
219 SYSCTL_NODE(_kern, OID_AUTO, hwpmc, CTLFLAG_RW, 0, "HWPMC parameters");
221 static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
222 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "callchaindepth", &pmc_callchaindepth);
223 SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_TUN|CTLFLAG_RD,
224 &pmc_callchaindepth, 0, "depth of call chain records");
227 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
228 char pmc_debugstr[PMC_DEBUG_STRSIZE];
229 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
230 sizeof(pmc_debugstr));
231 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
232 CTLTYPE_STRING|CTLFLAG_RW|CTLFLAG_TUN,
233 0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
237 * kern.hwpmc.hashrows -- determines the number of rows in the
238 * of the hash table used to look up threads
241 static int pmc_hashsize = PMC_HASH_SIZE;
242 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "hashsize", &pmc_hashsize);
243 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_TUN|CTLFLAG_RD,
244 &pmc_hashsize, 0, "rows in hash tables");
247 * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
250 static int pmc_nsamples = PMC_NSAMPLES;
251 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nsamples", &pmc_nsamples);
252 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_TUN|CTLFLAG_RD,
253 &pmc_nsamples, 0, "number of PC samples per CPU");
257 * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
260 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
261 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "mtxpoolsize", &pmc_mtxpool_size);
262 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_TUN|CTLFLAG_RD,
263 &pmc_mtxpool_size, 0, "size of spin mutex pool");
267 * security.bsd.unprivileged_syspmcs -- allow non-root processes to
268 * allocate system-wide PMCs.
270 * Allowing unprivileged processes to allocate system PMCs is convenient
271 * if system-wide measurements need to be taken concurrently with other
272 * per-process measurements. This feature is turned off by default.
275 static int pmc_unprivileged_syspmcs = 0;
276 TUNABLE_INT("security.bsd.unprivileged_syspmcs", &pmc_unprivileged_syspmcs);
277 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RW,
278 &pmc_unprivileged_syspmcs, 0,
279 "allow unprivileged process to allocate system PMCs");
282 * Hash function. Discard the lower 2 bits of the pointer since
283 * these are always zero for our uses. The hash multiplier is
284 * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
288 #define _PMC_HM 11400714819323198486u
290 #define _PMC_HM 2654435769u
292 #error Must know the size of 'long' to compile
295 #define PMC_HASH_PTR(P,M) ((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
301 /* The `sysent' for the new syscall */
302 static struct sysent pmc_sysent = {
304 pmc_syscall_handler /* sy_call */
307 static struct syscall_module_data pmc_syscall_mod = {
315 static moduledata_t pmc_mod = {
317 syscall_module_handler,
321 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
322 MODULE_VERSION(pmc, PMC_VERSION);
325 enum pmc_dbgparse_state {
326 PMCDS_WS, /* in whitespace */
327 PMCDS_MAJOR, /* seen a major keyword */
332 pmc_debugflags_parse(char *newstr, char *fence)
335 struct pmc_debugflags *tmpflags;
336 int error, found, *newbits, tmp;
339 tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK|M_ZERO);
344 for (; p < fence && (c = *p); p++) {
346 /* skip white space */
347 if (c == ' ' || c == '\t')
350 /* look for a keyword followed by "=" */
351 for (q = p; p < fence && (c = *p) && c != '='; p++)
361 /* lookup flag group name */
362 #define DBG_SET_FLAG_MAJ(S,F) \
363 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
364 newbits = &tmpflags->pdb_ ## F;
366 DBG_SET_FLAG_MAJ("cpu", CPU);
367 DBG_SET_FLAG_MAJ("csw", CSW);
368 DBG_SET_FLAG_MAJ("logging", LOG);
369 DBG_SET_FLAG_MAJ("module", MOD);
370 DBG_SET_FLAG_MAJ("md", MDP);
371 DBG_SET_FLAG_MAJ("owner", OWN);
372 DBG_SET_FLAG_MAJ("pmc", PMC);
373 DBG_SET_FLAG_MAJ("process", PRC);
374 DBG_SET_FLAG_MAJ("sampling", SAM);
376 if (newbits == NULL) {
381 p++; /* skip the '=' */
383 /* Now parse the individual flags */
386 for (q = p; p < fence && (c = *p); p++)
387 if (c == ' ' || c == '\t' || c == ',')
390 /* p == fence or c == ws or c == "," or c == 0 */
392 if ((kwlen = p - q) == 0) {
398 #define DBG_SET_FLAG_MIN(S,F) \
399 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
400 tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
402 /* a '*' denotes all possible flags in the group */
403 if (kwlen == 1 && *q == '*')
405 /* look for individual flag names */
406 DBG_SET_FLAG_MIN("allocaterow", ALR);
407 DBG_SET_FLAG_MIN("allocate", ALL);
408 DBG_SET_FLAG_MIN("attach", ATT);
409 DBG_SET_FLAG_MIN("bind", BND);
410 DBG_SET_FLAG_MIN("config", CFG);
411 DBG_SET_FLAG_MIN("exec", EXC);
412 DBG_SET_FLAG_MIN("exit", EXT);
413 DBG_SET_FLAG_MIN("find", FND);
414 DBG_SET_FLAG_MIN("flush", FLS);
415 DBG_SET_FLAG_MIN("fork", FRK);
416 DBG_SET_FLAG_MIN("getbuf", GTB);
417 DBG_SET_FLAG_MIN("hook", PMH);
418 DBG_SET_FLAG_MIN("init", INI);
419 DBG_SET_FLAG_MIN("intr", INT);
420 DBG_SET_FLAG_MIN("linktarget", TLK);
421 DBG_SET_FLAG_MIN("mayberemove", OMR);
422 DBG_SET_FLAG_MIN("ops", OPS);
423 DBG_SET_FLAG_MIN("read", REA);
424 DBG_SET_FLAG_MIN("register", REG);
425 DBG_SET_FLAG_MIN("release", REL);
426 DBG_SET_FLAG_MIN("remove", ORM);
427 DBG_SET_FLAG_MIN("sample", SAM);
428 DBG_SET_FLAG_MIN("scheduleio", SIO);
429 DBG_SET_FLAG_MIN("select", SEL);
430 DBG_SET_FLAG_MIN("signal", SIG);
431 DBG_SET_FLAG_MIN("swi", SWI);
432 DBG_SET_FLAG_MIN("swo", SWO);
433 DBG_SET_FLAG_MIN("start", STA);
434 DBG_SET_FLAG_MIN("stop", STO);
435 DBG_SET_FLAG_MIN("syscall", PMS);
436 DBG_SET_FLAG_MIN("unlinktarget", TUL);
437 DBG_SET_FLAG_MIN("write", WRI);
439 /* unrecognized flag name */
444 if (c == 0 || c == ' ' || c == '\t') { /* end of flag group */
453 /* save the new flag set */
454 bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
457 free(tmpflags, M_PMC);
462 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
464 char *fence, *newstr;
468 (void) arg1; (void) arg2; /* unused parameters */
470 n = sizeof(pmc_debugstr);
471 newstr = malloc(n, M_PMC, M_WAITOK|M_ZERO);
472 (void) strlcpy(newstr, pmc_debugstr, n);
474 error = sysctl_handle_string(oidp, newstr, n, req);
476 /* if there is a new string, parse and copy it */
477 if (error == 0 && req->newptr != NULL) {
478 fence = newstr + (n < req->newlen ? n : req->newlen + 1);
479 if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
480 (void) strlcpy(pmc_debugstr, newstr,
481 sizeof(pmc_debugstr));
491 * Map a row index to a classdep structure and return the adjusted row
492 * index for the PMC class index.
494 static struct pmc_classdep *
495 pmc_ri_to_classdep(struct pmc_mdep *md, int ri, int *adjri)
497 struct pmc_classdep *pcd;
501 KASSERT(ri >= 0 && ri < md->pmd_npmc,
502 ("[pmc,%d] illegal row-index %d", __LINE__, ri));
504 pcd = pmc_rowindex_to_classdep[ri];
507 ("[amd,%d] ri %d null pcd", __LINE__, ri));
509 *adjri = ri - pcd->pcd_ri;
511 KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
512 ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));
518 * Concurrency Control
520 * The driver manages the following data structures:
522 * - target process descriptors, one per target process
523 * - owner process descriptors (and attached lists), one per owner process
524 * - lookup hash tables for owner and target processes
525 * - PMC descriptors (and attached lists)
526 * - per-cpu hardware state
527 * - the 'hook' variable through which the kernel calls into
529 * - the machine hardware state (managed by the MD layer)
531 * These data structures are accessed from:
533 * - thread context-switch code
534 * - interrupt handlers (possibly on multiple cpus)
535 * - kernel threads on multiple cpus running on behalf of user
536 * processes doing system calls
537 * - this driver's private kernel threads
539 * = Locks and Locking strategy =
541 * The driver uses four locking strategies for its operation:
543 * - The global SX lock "pmc_sx" is used to protect internal
546 * Calls into the module by syscall() start with this lock being
547 * held in exclusive mode. Depending on the requested operation,
548 * the lock may be downgraded to 'shared' mode to allow more
549 * concurrent readers into the module. Calls into the module from
550 * other parts of the kernel acquire the lock in shared mode.
552 * This SX lock is held in exclusive mode for any operations that
553 * modify the linkages between the driver's internal data structures.
555 * The 'pmc_hook' function pointer is also protected by this lock.
556 * It is only examined with the sx lock held in exclusive mode. The
557 * kernel module is allowed to be unloaded only with the sx lock held
558 * in exclusive mode. In normal syscall handling, after acquiring the
559 * pmc_sx lock we first check that 'pmc_hook' is non-null before
560 * proceeding. This prevents races between the thread unloading the module
561 * and other threads seeking to use the module.
563 * - Lookups of target process structures and owner process structures
564 * cannot use the global "pmc_sx" SX lock because these lookups need
565 * to happen during context switches and in other critical sections
566 * where sleeping is not allowed. We protect these lookup tables
567 * with their own private spin-mutexes, "pmc_processhash_mtx" and
568 * "pmc_ownerhash_mtx".
570 * - Interrupt handlers work in a lock free manner. At interrupt
571 * time, handlers look at the PMC pointer (phw->phw_pmc) configured
572 * when the PMC was started. If this pointer is NULL, the interrupt
573 * is ignored after updating driver statistics. We ensure that this
574 * pointer is set (using an atomic operation if necessary) before the
575 * PMC hardware is started. Conversely, this pointer is unset atomically
576 * only after the PMC hardware is stopped.
578 * We ensure that everything needed for the operation of an
579 * interrupt handler is available without it needing to acquire any
580 * locks. We also ensure that a PMC's software state is destroyed only
581 * after the PMC is taken off hardware (on all CPUs).
583 * - Context-switch handling with process-private PMCs needs more
586 * A given process may be the target of multiple PMCs. For example,
587 * PMCATTACH and PMCDETACH may be requested by a process on one CPU
588 * while the target process is running on another. A PMC could also
589 * be getting released because its owner is exiting. We tackle
590 * these situations in the following manner:
592 * - each target process structure 'pmc_process' has an array
593 * of 'struct pmc *' pointers, one for each hardware PMC.
595 * - At context switch IN time, each "target" PMC in RUNNING state
596 * gets started on hardware and a pointer to each PMC is copied into
597 * the per-cpu phw array. The 'runcount' for the PMC is
600 * - At context switch OUT time, all process-virtual PMCs are stopped
601 * on hardware. The saved value is added to the PMCs value field
602 * only if the PMC is in a non-deleted state (the PMCs state could
603 * have changed during the current time slice).
605 * Note that since in-between a switch IN on a processor and a switch
606 * OUT, the PMC could have been released on another CPU. Therefore
607 * context switch OUT always looks at the hardware state to turn
608 * OFF PMCs and will update a PMC's saved value only if reachable
609 * from the target process record.
611 * - OP PMCRELEASE could be called on a PMC at any time (the PMC could
612 * be attached to many processes at the time of the call and could
613 * be active on multiple CPUs).
615 * We prevent further scheduling of the PMC by marking it as in
616 * state 'DELETED'. If the runcount of the PMC is non-zero then
617 * this PMC is currently running on a CPU somewhere. The thread
618 * doing the PMCRELEASE operation waits by repeatedly doing a
619 * pause() till the runcount comes to zero.
621 * The contents of a PMC descriptor (struct pmc) are protected using
622 * a spin-mutex. In order to save space, we use a mutex pool.
624 * In terms of lock types used by witness(4), we use:
625 * - Type "pmc-sx", used by the global SX lock.
626 * - Type "pmc-sleep", for sleep mutexes used by logger threads.
627 * - Type "pmc-per-proc", for protecting PMC owner descriptors.
628 * - Type "pmc-leaf", used for all other spin mutexes.
632 * save the cpu binding of the current kthread
636 pmc_save_cpu_binding(struct pmc_binding *pb)
638 PMCDBG(CPU,BND,2, "%s", "save-cpu");
639 thread_lock(curthread);
640 pb->pb_bound = sched_is_bound(curthread);
641 pb->pb_cpu = curthread->td_oncpu;
642 thread_unlock(curthread);
643 PMCDBG(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
647 * restore the cpu binding of the current thread
651 pmc_restore_cpu_binding(struct pmc_binding *pb)
653 PMCDBG(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
654 curthread->td_oncpu, pb->pb_cpu);
655 thread_lock(curthread);
657 sched_bind(curthread, pb->pb_cpu);
659 sched_unbind(curthread);
660 thread_unlock(curthread);
661 PMCDBG(CPU,BND,2, "%s", "restore-cpu done");
665 * move execution over the specified cpu and bind it there.
669 pmc_select_cpu(int cpu)
671 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
672 ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
674 /* Never move to an inactive CPU. */
675 KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
676 "CPU %d", __LINE__, cpu));
678 PMCDBG(CPU,SEL,2, "select-cpu cpu=%d", cpu);
679 thread_lock(curthread);
680 sched_bind(curthread, cpu);
681 thread_unlock(curthread);
683 KASSERT(curthread->td_oncpu == cpu,
684 ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
685 cpu, curthread->td_oncpu));
687 PMCDBG(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
691 * Force a context switch.
693 * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
694 * guaranteed to force a context switch.
698 pmc_force_context_switch(void)
705 * Get the file name for an executable. This is a simple wrapper
706 * around vn_fullpath(9).
710 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
713 *fullpath = "unknown";
715 vn_fullpath(curthread, v, fullpath, freepath);
719 * remove an process owning PMCs
723 pmc_remove_owner(struct pmc_owner *po)
725 struct pmc *pm, *tmp;
727 sx_assert(&pmc_sx, SX_XLOCKED);
729 PMCDBG(OWN,ORM,1, "remove-owner po=%p", po);
731 /* Remove descriptor from the owner hash table */
732 LIST_REMOVE(po, po_next);
734 /* release all owned PMC descriptors */
735 LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
736 PMCDBG(OWN,ORM,2, "pmc=%p", pm);
737 KASSERT(pm->pm_owner == po,
738 ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
740 pmc_release_pmc_descriptor(pm); /* will unlink from the list */
743 KASSERT(po->po_sscount == 0,
744 ("[pmc,%d] SS count not zero", __LINE__));
745 KASSERT(LIST_EMPTY(&po->po_pmcs),
746 ("[pmc,%d] PMC list not empty", __LINE__));
748 /* de-configure the log file if present */
749 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
750 pmclog_deconfigure_log(po);
754 * remove an owner process record if all conditions are met.
758 pmc_maybe_remove_owner(struct pmc_owner *po)
761 PMCDBG(OWN,OMR,1, "maybe-remove-owner po=%p", po);
764 * Remove owner record if
765 * - this process does not own any PMCs
766 * - this process has not allocated a system-wide sampling buffer
769 if (LIST_EMPTY(&po->po_pmcs) &&
770 ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
771 pmc_remove_owner(po);
772 pmc_destroy_owner_descriptor(po);
777 * Add an association between a target process and a PMC.
781 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
784 struct pmc_target *pt;
786 sx_assert(&pmc_sx, SX_XLOCKED);
788 KASSERT(pm != NULL && pp != NULL,
789 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
790 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
791 ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
792 __LINE__, pm, pp->pp_proc->p_pid));
793 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < ((int) md->pmd_npmc - 1),
794 ("[pmc,%d] Illegal reference count %d for process record %p",
795 __LINE__, pp->pp_refcnt, (void *) pp));
797 ri = PMC_TO_ROWINDEX(pm);
799 PMCDBG(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
803 LIST_FOREACH(pt, &pm->pm_targets, pt_next)
804 if (pt->pt_process == pp)
805 KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
809 pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK|M_ZERO);
812 LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
814 atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
817 if (pm->pm_owner->po_owner == pp->pp_proc)
818 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
821 * Initialize the per-process values at this row index.
823 pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
824 pm->pm_sc.pm_reloadcount : 0;
831 * Removes the association between a target process and a PMC.
835 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
839 struct pmc_target *ptgt;
841 sx_assert(&pmc_sx, SX_XLOCKED);
843 KASSERT(pm != NULL && pp != NULL,
844 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
846 KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt < (int) md->pmd_npmc,
847 ("[pmc,%d] Illegal ref count %d on process record %p",
848 __LINE__, pp->pp_refcnt, (void *) pp));
850 ri = PMC_TO_ROWINDEX(pm);
852 PMCDBG(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
855 KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
856 ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
857 ri, pm, pp->pp_pmcs[ri].pp_pmc));
859 pp->pp_pmcs[ri].pp_pmc = NULL;
860 pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
862 /* Remove owner-specific flags */
863 if (pm->pm_owner->po_owner == pp->pp_proc) {
864 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
865 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
870 /* Remove the target process from the PMC structure */
871 LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
872 if (ptgt->pt_process == pp)
875 KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
876 "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
878 LIST_REMOVE(ptgt, pt_next);
881 /* if the PMC now lacks targets, send the owner a SIGIO */
882 if (LIST_EMPTY(&pm->pm_targets)) {
883 p = pm->pm_owner->po_owner;
888 PMCDBG(PRC,SIG,2, "signalling proc=%p signal=%d", p,
894 * Check if PMC 'pm' may be attached to target process 't'.
898 pmc_can_attach(struct pmc *pm, struct proc *t)
900 struct proc *o; /* pmc owner */
901 struct ucred *oc, *tc; /* owner, target credentials */
902 int decline_attach, i;
905 * A PMC's owner can always attach that PMC to itself.
908 if ((o = pm->pm_owner->po_owner) == t)
922 * The effective uid of the PMC owner should match at least one
923 * of the {effective,real,saved} uids of the target process.
926 decline_attach = oc->cr_uid != tc->cr_uid &&
927 oc->cr_uid != tc->cr_svuid &&
928 oc->cr_uid != tc->cr_ruid;
931 * Every one of the target's group ids, must be in the owner's
934 for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
935 decline_attach = !groupmember(tc->cr_groups[i], oc);
937 /* check the read and saved gids too */
938 if (decline_attach == 0)
939 decline_attach = !groupmember(tc->cr_rgid, oc) ||
940 !groupmember(tc->cr_svgid, oc);
945 return !decline_attach;
949 * Attach a process to a PMC.
953 pmc_attach_one_process(struct proc *p, struct pmc *pm)
956 char *fullpath, *freepath;
957 struct pmc_process *pp;
959 sx_assert(&pmc_sx, SX_XLOCKED);
961 PMCDBG(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
962 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
965 * Locate the process descriptor corresponding to process 'p',
966 * allocating space as needed.
968 * Verify that rowindex 'pm_rowindex' is free in the process
971 * If not, allocate space for a descriptor and link the
972 * process descriptor and PMC.
974 ri = PMC_TO_ROWINDEX(pm);
976 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
979 if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
982 if (pp->pp_pmcs[ri].pp_pmc != NULL)
985 pmc_link_target_process(pm, pp);
987 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
988 (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
989 pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
991 pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
993 /* issue an attach event to a configured log file */
994 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
995 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
996 if (p->p_flag & P_KTHREAD) {
997 fullpath = kernelname;
1000 pmclog_process_pmcattach(pm, p->p_pid, fullpath);
1002 free(freepath, M_TEMP);
1003 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1004 pmc_log_process_mappings(pm->pm_owner, p);
1006 /* mark process as using HWPMCs */
1008 p->p_flag |= P_HWPMC;
1015 * Attach a process and optionally its children
1019 pmc_attach_process(struct proc *p, struct pmc *pm)
1024 sx_assert(&pmc_sx, SX_XLOCKED);
1026 PMCDBG(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1027 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1031 * If this PMC successfully allowed a GETMSR operation
1032 * in the past, disallow further ATTACHes.
1035 if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1038 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1039 return pmc_attach_one_process(p, pm);
1042 * Traverse all child processes, attaching them to
1046 sx_slock(&proctree_lock);
1051 if ((error = pmc_attach_one_process(p, pm)) != 0)
1053 if (!LIST_EMPTY(&p->p_children))
1054 p = LIST_FIRST(&p->p_children);
1058 if (LIST_NEXT(p, p_sibling)) {
1059 p = LIST_NEXT(p, p_sibling);
1067 (void) pmc_detach_process(top, pm);
1070 sx_sunlock(&proctree_lock);
1075 * Detach a process from a PMC. If there are no other PMCs tracking
1076 * this process, remove the process structure from its hash table. If
1077 * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1081 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1084 struct pmc_process *pp;
1086 sx_assert(&pmc_sx, SX_XLOCKED);
1089 ("[pmc,%d] null pm pointer", __LINE__));
1091 ri = PMC_TO_ROWINDEX(pm);
1093 PMCDBG(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1094 pm, ri, p, p->p_pid, p->p_comm, flags);
1096 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1099 if (pp->pp_pmcs[ri].pp_pmc != pm)
1102 pmc_unlink_target_process(pm, pp);
1104 /* Issue a detach entry if a log file is configured */
1105 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1106 pmclog_process_pmcdetach(pm, p->p_pid);
1109 * If there are no PMCs targetting this process, we remove its
1110 * descriptor from the target hash table and unset the P_HWPMC
1111 * flag in the struct proc.
1113 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1114 ("[pmc,%d] Illegal refcnt %d for process struct %p",
1115 __LINE__, pp->pp_refcnt, pp));
1117 if (pp->pp_refcnt != 0) /* still a target of some PMC */
1120 pmc_remove_process_descriptor(pp);
1122 if (flags & PMC_FLAG_REMOVE)
1126 p->p_flag &= ~P_HWPMC;
1133 * Detach a process and optionally its descendants from a PMC.
1137 pmc_detach_process(struct proc *p, struct pmc *pm)
1141 sx_assert(&pmc_sx, SX_XLOCKED);
1143 PMCDBG(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1144 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1146 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1147 return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1150 * Traverse all children, detaching them from this PMC. We
1151 * ignore errors since we could be detaching a PMC from a
1152 * partially attached proc tree.
1155 sx_slock(&proctree_lock);
1160 (void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1162 if (!LIST_EMPTY(&p->p_children))
1163 p = LIST_FIRST(&p->p_children);
1167 if (LIST_NEXT(p, p_sibling)) {
1168 p = LIST_NEXT(p, p_sibling);
1176 sx_sunlock(&proctree_lock);
1178 if (LIST_EMPTY(&pm->pm_targets))
1179 pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1186 * Thread context switch IN
1190 pmc_process_csw_in(struct thread *td)
1193 unsigned int adjri, ri;
1198 pmc_value_t newvalue;
1199 struct pmc_process *pp;
1200 struct pmc_classdep *pcd;
1204 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1207 KASSERT(pp->pp_proc == td->td_proc,
1208 ("[pmc,%d] not my thread state", __LINE__));
1210 critical_enter(); /* no preemption from this point */
1212 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1214 PMCDBG(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1215 p->p_pid, p->p_comm, pp);
1217 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1218 ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
1222 for (ri = 0; ri < md->pmd_npmc; ri++) {
1224 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1227 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1228 ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1229 __LINE__, PMC_TO_MODE(pm)));
1231 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1232 ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1233 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1236 * Only PMCs that are marked as 'RUNNING' need
1237 * be placed on hardware.
1240 if (pm->pm_state != PMC_STATE_RUNNING)
1243 /* increment PMC runcount */
1244 atomic_add_rel_32(&pm->pm_runcount, 1);
1246 /* configure the HWPMC we are going to use. */
1247 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1248 pcd->pcd_config_pmc(cpu, adjri, pm);
1250 phw = pc->pc_hwpmcs[ri];
1252 KASSERT(phw != NULL,
1253 ("[pmc,%d] null hw pointer", __LINE__));
1255 KASSERT(phw->phw_pmc == pm,
1256 ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1260 * Write out saved value and start the PMC.
1262 * Sampling PMCs use a per-process value, while
1263 * counting mode PMCs use a per-pmc value that is
1264 * inherited across descendants.
1266 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1267 mtx_pool_lock_spin(pmc_mtxpool, pm);
1268 newvalue = PMC_PCPU_SAVED(cpu,ri) =
1269 pp->pp_pmcs[ri].pp_pmcval;
1270 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1272 KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1273 ("[pmc,%d] illegal mode=%d", __LINE__,
1275 mtx_pool_lock_spin(pmc_mtxpool, pm);
1276 newvalue = PMC_PCPU_SAVED(cpu, ri) =
1277 pm->pm_gv.pm_savedvalue;
1278 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1281 PMCDBG(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1283 pcd->pcd_write_pmc(cpu, adjri, newvalue);
1284 pcd->pcd_start_pmc(cpu, adjri);
1288 * perform any other architecture/cpu dependent thread
1289 * switch-in actions.
1292 (void) (*md->pmd_switch_in)(pc, pp);
1299 * Thread context switch OUT.
1303 pmc_process_csw_out(struct thread *td)
1311 pmc_value_t newvalue;
1312 unsigned int adjri, ri;
1313 struct pmc_process *pp;
1314 struct pmc_classdep *pcd;
1318 * Locate our process descriptor; this may be NULL if
1319 * this process is exiting and we have already removed
1320 * the process from the target process table.
1322 * Note that due to kernel preemption, multiple
1323 * context switches may happen while the process is
1326 * Note also that if the target process cannot be
1327 * found we still need to deconfigure any PMCs that
1328 * are currently running on hardware.
1332 pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1340 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1342 PMCDBG(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1343 p->p_pid, p->p_comm, pp);
1345 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1346 ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1351 * When a PMC gets unlinked from a target PMC, it will
1352 * be removed from the target's pp_pmc[] array.
1354 * However, on a MP system, the target could have been
1355 * executing on another CPU at the time of the unlink.
1356 * So, at context switch OUT time, we need to look at
1357 * the hardware to determine if a PMC is scheduled on
1361 for (ri = 0; ri < md->pmd_npmc; ri++) {
1363 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1365 (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
1367 if (pm == NULL) /* nothing at this row index */
1370 mode = PMC_TO_MODE(pm);
1371 if (!PMC_IS_VIRTUAL_MODE(mode))
1372 continue; /* not a process virtual PMC */
1374 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1375 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1376 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1378 /* Stop hardware if not already stopped */
1379 if (pm->pm_stalled == 0)
1380 pcd->pcd_stop_pmc(cpu, adjri);
1382 /* reduce this PMC's runcount */
1383 atomic_subtract_rel_32(&pm->pm_runcount, 1);
1386 * If this PMC is associated with this process,
1390 if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1392 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1393 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1394 pm, ri, pp->pp_pmcs[ri].pp_pmc));
1396 KASSERT(pp->pp_refcnt > 0,
1397 ("[pmc,%d] pp refcnt = %d", __LINE__,
1400 pcd->pcd_read_pmc(cpu, adjri, &newvalue);
1402 tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1404 PMCDBG(CSW,SWI,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
1407 if (mode == PMC_MODE_TS) {
1410 * For sampling process-virtual PMCs,
1411 * we expect the count to be
1412 * decreasing as the 'value'
1413 * programmed into the PMC is the
1414 * number of events to be seen till
1415 * the next sampling interrupt.
1418 tmp += pm->pm_sc.pm_reloadcount;
1419 mtx_pool_lock_spin(pmc_mtxpool, pm);
1420 pp->pp_pmcs[ri].pp_pmcval -= tmp;
1421 if ((int64_t) pp->pp_pmcs[ri].pp_pmcval < 0)
1422 pp->pp_pmcs[ri].pp_pmcval +=
1423 pm->pm_sc.pm_reloadcount;
1424 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1429 * For counting process-virtual PMCs,
1430 * we expect the count to be
1431 * increasing monotonically, modulo a 64
1434 KASSERT((int64_t) tmp >= 0,
1435 ("[pmc,%d] negative increment cpu=%d "
1436 "ri=%d newvalue=%jx saved=%jx "
1437 "incr=%jx", __LINE__, cpu, ri,
1438 newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1440 mtx_pool_lock_spin(pmc_mtxpool, pm);
1441 pm->pm_gv.pm_savedvalue += tmp;
1442 pp->pp_pmcs[ri].pp_pmcval += tmp;
1443 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1445 if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1446 pmclog_process_proccsw(pm, pp, tmp);
1450 /* mark hardware as free */
1451 pcd->pcd_config_pmc(cpu, adjri, NULL);
1455 * perform any other architecture/cpu dependent thread
1456 * switch out functions.
1459 (void) (*md->pmd_switch_out)(pc, pp);
1465 * Log a KLD operation.
1469 pmc_process_kld_load(struct pmckern_map_in *pkm)
1471 struct pmc_owner *po;
1473 sx_assert(&pmc_sx, SX_LOCKED);
1476 * Notify owners of system sampling PMCs about KLD operations.
1479 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1480 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1481 pmclog_process_map_in(po, (pid_t) -1, pkm->pm_address,
1482 (char *) pkm->pm_file);
1485 * TODO: Notify owners of (all) process-sampling PMCs too.
1492 pmc_process_kld_unload(struct pmckern_map_out *pkm)
1494 struct pmc_owner *po;
1496 sx_assert(&pmc_sx, SX_LOCKED);
1498 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1499 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1500 pmclog_process_map_out(po, (pid_t) -1,
1501 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1504 * TODO: Notify owners of process-sampling PMCs.
1509 * A mapping change for a process.
1513 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1517 char *fullpath, *freepath;
1518 const struct pmc *pm;
1519 struct pmc_owner *po;
1520 const struct pmc_process *pp;
1522 freepath = fullpath = NULL;
1523 pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1525 pid = td->td_proc->p_pid;
1527 /* Inform owners of all system-wide sampling PMCs. */
1528 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1529 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1530 pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1532 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1536 * Inform sampling PMC owners tracking this process.
1538 for (ri = 0; ri < md->pmd_npmc; ri++)
1539 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1540 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1541 pmclog_process_map_in(pm->pm_owner,
1542 pid, pkm->pm_address, fullpath);
1546 free(freepath, M_TEMP);
1551 * Log an munmap request.
1555 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1559 struct pmc_owner *po;
1560 const struct pmc *pm;
1561 const struct pmc_process *pp;
1563 pid = td->td_proc->p_pid;
1565 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1566 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1567 pmclog_process_map_out(po, pid, pkm->pm_address,
1568 pkm->pm_address + pkm->pm_size);
1570 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1573 for (ri = 0; ri < md->pmd_npmc; ri++)
1574 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1575 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1576 pmclog_process_map_out(pm->pm_owner, pid,
1577 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1581 * Log mapping information about the kernel.
1585 pmc_log_kernel_mappings(struct pmc *pm)
1587 struct pmc_owner *po;
1588 struct pmckern_map_in *km, *kmbase;
1590 sx_assert(&pmc_sx, SX_LOCKED);
1591 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1592 ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1593 __LINE__, (void *) pm));
1597 if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1601 * Log the current set of kernel modules.
1603 kmbase = linker_hwpmc_list_objects();
1604 for (km = kmbase; km->pm_file != NULL; km++) {
1605 PMCDBG(LOG,REG,1,"%s %p", (char *) km->pm_file,
1606 (void *) km->pm_address);
1607 pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1610 free(kmbase, M_LINKER);
1612 po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1616 * Log the mappings for a single process.
1620 pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1625 * Log mappings for all processes in the system.
1629 pmc_log_all_process_mappings(struct pmc_owner *po)
1631 struct proc *p, *top;
1633 sx_assert(&pmc_sx, SX_XLOCKED);
1635 if ((p = pfind(1)) == NULL)
1636 panic("[pmc,%d] Cannot find init", __LINE__);
1640 sx_slock(&proctree_lock);
1645 pmc_log_process_mappings(po, p);
1646 if (!LIST_EMPTY(&p->p_children))
1647 p = LIST_FIRST(&p->p_children);
1651 if (LIST_NEXT(p, p_sibling)) {
1652 p = LIST_NEXT(p, p_sibling);
1659 sx_sunlock(&proctree_lock);
1663 * The 'hook' invoked from the kernel proper
1668 const char *pmc_hooknames[] = {
1669 /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1684 pmc_hook_handler(struct thread *td, int function, void *arg)
1687 PMCDBG(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1688 pmc_hooknames[function], arg);
1697 case PMC_FN_PROCESS_EXEC:
1699 char *fullpath, *freepath;
1701 int is_using_hwpmcs;
1704 struct pmc_owner *po;
1705 struct pmc_process *pp;
1706 struct pmckern_procexec *pk;
1708 sx_assert(&pmc_sx, SX_XLOCKED);
1711 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1713 pk = (struct pmckern_procexec *) arg;
1715 /* Inform owners of SS mode PMCs of the exec event. */
1716 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1717 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1718 pmclog_process_procexec(po, PMC_ID_INVALID,
1719 p->p_pid, pk->pm_entryaddr, fullpath);
1722 is_using_hwpmcs = p->p_flag & P_HWPMC;
1725 if (!is_using_hwpmcs) {
1727 free(freepath, M_TEMP);
1732 * PMCs are not inherited across an exec(): remove any
1733 * PMCs that this process is the owner of.
1736 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1737 pmc_remove_owner(po);
1738 pmc_destroy_owner_descriptor(po);
1742 * If the process being exec'ed is not the target of any
1745 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1747 free(freepath, M_TEMP);
1752 * Log the exec event to all monitoring owners. Skip
1753 * owners who have already recieved the event because
1754 * they had system sampling PMCs active.
1756 for (ri = 0; ri < md->pmd_npmc; ri++)
1757 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1759 if (po->po_sscount == 0 &&
1760 po->po_flags & PMC_PO_OWNS_LOGFILE)
1761 pmclog_process_procexec(po, pm->pm_id,
1762 p->p_pid, pk->pm_entryaddr,
1767 free(freepath, M_TEMP);
1770 PMCDBG(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1771 p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1773 if (pk->pm_credentialschanged == 0) /* no change */
1777 * If the newly exec()'ed process has a different credential
1778 * than before, allow it to be the target of a PMC only if
1779 * the PMC's owner has sufficient priviledge.
1782 for (ri = 0; ri < md->pmd_npmc; ri++)
1783 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1784 if (pmc_can_attach(pm, td->td_proc) != 0)
1785 pmc_detach_one_process(td->td_proc,
1788 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1789 ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1790 pp->pp_refcnt, pp));
1793 * If this process is no longer the target of any
1794 * PMCs, we can remove the process entry and free
1798 if (pp->pp_refcnt == 0) {
1799 pmc_remove_process_descriptor(pp);
1808 pmc_process_csw_in(td);
1811 case PMC_FN_CSW_OUT:
1812 pmc_process_csw_out(td);
1816 * Process accumulated PC samples.
1818 * This function is expected to be called by hardclock() for
1819 * each CPU that has accumulated PC samples.
1821 * This function is to be executed on the CPU whose samples
1822 * are being processed.
1824 case PMC_FN_DO_SAMPLES:
1827 * Clear the cpu specific bit in the CPU mask before
1828 * do the rest of the processing. If the NMI handler
1829 * gets invoked after the "atomic_clear_int()" call
1830 * below but before "pmc_process_samples()" gets
1831 * around to processing the interrupt, then we will
1832 * come back here at the next hardclock() tick (and
1833 * may find nothing to do if "pmc_process_samples()"
1834 * had already processed the interrupt). We don't
1835 * lose the interrupt sample.
1837 atomic_clear_int(&pmc_cpumask, (1 << PCPU_GET(cpuid)));
1838 pmc_process_samples(PCPU_GET(cpuid));
1842 case PMC_FN_KLD_LOAD:
1843 sx_assert(&pmc_sx, SX_LOCKED);
1844 pmc_process_kld_load((struct pmckern_map_in *) arg);
1847 case PMC_FN_KLD_UNLOAD:
1848 sx_assert(&pmc_sx, SX_LOCKED);
1849 pmc_process_kld_unload((struct pmckern_map_out *) arg);
1853 sx_assert(&pmc_sx, SX_LOCKED);
1854 pmc_process_mmap(td, (struct pmckern_map_in *) arg);
1858 sx_assert(&pmc_sx, SX_LOCKED);
1859 pmc_process_munmap(td, (struct pmckern_map_out *) arg);
1862 case PMC_FN_USER_CALLCHAIN:
1864 * Record a call chain.
1866 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
1868 pmc_capture_user_callchain(PCPU_GET(cpuid),
1869 (struct trapframe *) arg);
1870 td->td_pflags &= ~TDP_CALLCHAIN;
1875 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
1885 * allocate a 'struct pmc_owner' descriptor in the owner hash table.
1888 static struct pmc_owner *
1889 pmc_allocate_owner_descriptor(struct proc *p)
1892 struct pmc_owner *po;
1893 struct pmc_ownerhash *poh;
1895 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1896 poh = &pmc_ownerhash[hindex];
1898 /* allocate space for N pointers and one descriptor struct */
1899 po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK|M_ZERO);
1900 po->po_sscount = po->po_error = po->po_flags = 0;
1903 po->po_kthread = NULL;
1904 LIST_INIT(&po->po_pmcs);
1905 LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
1907 TAILQ_INIT(&po->po_logbuffers);
1908 mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
1910 PMCDBG(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
1911 p, p->p_pid, p->p_comm, po);
1917 pmc_destroy_owner_descriptor(struct pmc_owner *po)
1920 PMCDBG(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
1921 po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
1923 mtx_destroy(&po->po_mtx);
1928 * find the descriptor corresponding to process 'p', adding or removing it
1929 * as specified by 'mode'.
1932 static struct pmc_process *
1933 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
1936 struct pmc_process *pp, *ppnew;
1937 struct pmc_processhash *pph;
1939 hindex = PMC_HASH_PTR(p, pmc_processhashmask);
1940 pph = &pmc_processhash[hindex];
1945 * Pre-allocate memory in the FIND_ALLOCATE case since we
1946 * cannot call malloc(9) once we hold a spin lock.
1948 if (mode & PMC_FLAG_ALLOCATE)
1949 ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
1950 sizeof(struct pmc_targetstate), M_PMC, M_WAITOK|M_ZERO);
1952 mtx_lock_spin(&pmc_processhash_mtx);
1953 LIST_FOREACH(pp, pph, pp_next)
1954 if (pp->pp_proc == p)
1957 if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
1958 LIST_REMOVE(pp, pp_next);
1960 if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
1963 LIST_INSERT_HEAD(pph, ppnew, pp_next);
1967 mtx_unlock_spin(&pmc_processhash_mtx);
1969 if (pp != NULL && ppnew != NULL)
1976 * remove a process descriptor from the process hash table.
1980 pmc_remove_process_descriptor(struct pmc_process *pp)
1982 KASSERT(pp->pp_refcnt == 0,
1983 ("[pmc,%d] Removing process descriptor %p with count %d",
1984 __LINE__, pp, pp->pp_refcnt));
1986 mtx_lock_spin(&pmc_processhash_mtx);
1987 LIST_REMOVE(pp, pp_next);
1988 mtx_unlock_spin(&pmc_processhash_mtx);
1993 * find an owner descriptor corresponding to proc 'p'
1996 static struct pmc_owner *
1997 pmc_find_owner_descriptor(struct proc *p)
2000 struct pmc_owner *po;
2001 struct pmc_ownerhash *poh;
2003 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2004 poh = &pmc_ownerhash[hindex];
2007 LIST_FOREACH(po, poh, po_next)
2008 if (po->po_owner == p)
2011 PMCDBG(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2012 "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2018 * pmc_allocate_pmc_descriptor
2020 * Allocate a pmc descriptor and initialize its
2025 pmc_allocate_pmc_descriptor(void)
2029 pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK|M_ZERO);
2032 pmc->pm_owner = NULL;
2033 LIST_INIT(&pmc->pm_targets);
2036 PMCDBG(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2042 * Destroy a pmc descriptor.
2046 pmc_destroy_pmc_descriptor(struct pmc *pm)
2051 KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2052 pm->pm_state == PMC_STATE_FREE,
2053 ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2054 KASSERT(LIST_EMPTY(&pm->pm_targets),
2055 ("[pmc,%d] destroying pmc with targets", __LINE__));
2056 KASSERT(pm->pm_owner == NULL,
2057 ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2058 KASSERT(pm->pm_runcount == 0,
2059 ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
2065 pmc_wait_for_pmc_idle(struct pmc *pm)
2068 volatile int maxloop;
2070 maxloop = 100 * pmc_cpu_max();
2074 * Loop (with a forced context switch) till the PMC's runcount
2075 * comes down to zero.
2077 while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
2080 KASSERT(maxloop > 0,
2081 ("[pmc,%d] (ri%d, rc%d) waiting too long for "
2082 "pmc to be free", __LINE__,
2083 PMC_TO_ROWINDEX(pm), pm->pm_runcount));
2085 pmc_force_context_switch();
2090 * This function does the following things:
2092 * - detaches the PMC from hardware
2093 * - unlinks all target threads that were attached to it
2094 * - removes the PMC from its owner's list
2095 * - destroy's the PMC private mutex
2097 * Once this function completes, the given pmc pointer can be safely
2098 * FREE'd by the caller.
2102 pmc_release_pmc_descriptor(struct pmc *pm)
2106 u_int adjri, ri, cpu;
2107 struct pmc_owner *po;
2108 struct pmc_binding pb;
2109 struct pmc_process *pp;
2110 struct pmc_classdep *pcd;
2111 struct pmc_target *ptgt, *tmp;
2113 sx_assert(&pmc_sx, SX_XLOCKED);
2115 KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2117 ri = PMC_TO_ROWINDEX(pm);
2118 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2119 mode = PMC_TO_MODE(pm);
2121 PMCDBG(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2125 * First, we take the PMC off hardware.
2128 if (PMC_IS_SYSTEM_MODE(mode)) {
2131 * A system mode PMC runs on a specific CPU. Switch
2132 * to this CPU and turn hardware off.
2134 pmc_save_cpu_binding(&pb);
2136 cpu = PMC_TO_CPU(pm);
2138 pmc_select_cpu(cpu);
2140 /* switch off non-stalled CPUs */
2141 if (pm->pm_state == PMC_STATE_RUNNING &&
2142 pm->pm_stalled == 0) {
2144 phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2146 KASSERT(phw->phw_pmc == pm,
2147 ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2148 __LINE__, ri, phw->phw_pmc, pm));
2149 PMCDBG(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2152 pcd->pcd_stop_pmc(cpu, adjri);
2156 PMCDBG(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2159 pcd->pcd_config_pmc(cpu, adjri, NULL);
2162 /* adjust the global and process count of SS mode PMCs */
2163 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2166 if (po->po_sscount == 0) {
2167 atomic_subtract_rel_int(&pmc_ss_count, 1);
2168 LIST_REMOVE(po, po_ssnext);
2172 pm->pm_state = PMC_STATE_DELETED;
2174 pmc_restore_cpu_binding(&pb);
2177 * We could have references to this PMC structure in
2178 * the per-cpu sample queues. Wait for the queue to
2181 pmc_wait_for_pmc_idle(pm);
2183 } else if (PMC_IS_VIRTUAL_MODE(mode)) {
2186 * A virtual PMC could be running on multiple CPUs at
2189 * By marking its state as DELETED, we ensure that
2190 * this PMC is never further scheduled on hardware.
2192 * Then we wait till all CPUs are done with this PMC.
2194 pm->pm_state = PMC_STATE_DELETED;
2197 /* Wait for the PMCs runcount to come to zero. */
2198 pmc_wait_for_pmc_idle(pm);
2201 * At this point the PMC is off all CPUs and cannot be
2202 * freshly scheduled onto a CPU. It is now safe to
2203 * unlink all targets from this PMC. If a
2204 * process-record's refcount falls to zero, we remove
2205 * it from the hash table. The module-wide SX lock
2206 * protects us from races.
2208 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2209 pp = ptgt->pt_process;
2210 pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2212 PMCDBG(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2215 * If the target process record shows that no
2216 * PMCs are attached to it, reclaim its space.
2219 if (pp->pp_refcnt == 0) {
2220 pmc_remove_process_descriptor(pp);
2225 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2230 * Release any MD resources
2232 (void) pcd->pcd_release_pmc(cpu, adjri, pm);
2235 * Update row disposition
2238 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2239 PMC_UNMARK_ROW_STANDALONE(ri);
2241 PMC_UNMARK_ROW_THREAD(ri);
2243 /* unlink from the owner's list */
2245 LIST_REMOVE(pm, pm_next);
2246 pm->pm_owner = NULL;
2249 pmc_destroy_pmc_descriptor(pm);
2253 * Register an owner and a pmc.
2257 pmc_register_owner(struct proc *p, struct pmc *pmc)
2259 struct pmc_owner *po;
2261 sx_assert(&pmc_sx, SX_XLOCKED);
2263 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2264 if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2267 KASSERT(pmc->pm_owner == NULL,
2268 ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2271 LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2274 p->p_flag |= P_HWPMC;
2277 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2278 pmclog_process_pmcallocate(pmc);
2280 PMCDBG(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2287 * Return the current row disposition:
2289 * > 0 => PROCESS MODE
2290 * < 0 => SYSTEM MODE
2294 pmc_getrowdisp(int ri)
2296 return pmc_pmcdisp[ri];
2300 * Check if a PMC at row index 'ri' can be allocated to the current
2303 * Allocation can fail if:
2304 * - the current process is already being profiled by a PMC at index 'ri',
2305 * attached to it via OP_PMCATTACH.
2306 * - the current process has already allocated a PMC at index 'ri'
2311 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2315 struct pmc_owner *po;
2316 struct pmc_process *pp;
2318 PMCDBG(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2319 "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2322 * We shouldn't have already allocated a process-mode PMC at
2325 * We shouldn't have allocated a system-wide PMC on the same
2328 if ((po = pmc_find_owner_descriptor(p)) != NULL)
2329 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2330 if (PMC_TO_ROWINDEX(pm) == ri) {
2331 mode = PMC_TO_MODE(pm);
2332 if (PMC_IS_VIRTUAL_MODE(mode))
2334 if (PMC_IS_SYSTEM_MODE(mode) &&
2335 (int) PMC_TO_CPU(pm) == cpu)
2341 * We also shouldn't be the target of any PMC at this index
2342 * since otherwise a PMC_ATTACH to ourselves will fail.
2344 if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2345 if (pp->pp_pmcs[ri].pp_pmc)
2348 PMCDBG(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2349 p, p->p_pid, p->p_comm, ri);
2355 * Check if a given PMC at row index 'ri' can be currently used in
2360 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2364 sx_assert(&pmc_sx, SX_XLOCKED);
2366 PMCDBG(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2368 if (PMC_IS_SYSTEM_MODE(mode))
2369 disp = PMC_DISP_STANDALONE;
2371 disp = PMC_DISP_THREAD;
2374 * check disposition for PMC row 'ri':
2376 * Expected disposition Row-disposition Result
2378 * STANDALONE STANDALONE or FREE proceed
2379 * STANDALONE THREAD fail
2380 * THREAD THREAD or FREE proceed
2381 * THREAD STANDALONE fail
2384 if (!PMC_ROW_DISP_IS_FREE(ri) &&
2385 !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2386 !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2393 PMCDBG(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2400 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2404 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2408 KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2409 ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2410 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2412 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2413 if (pm->pm_id == pmcid)
2420 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2424 struct pmc_owner *po;
2426 PMCDBG(PMC,FND,1, "find-pmc id=%d", pmcid);
2428 if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2431 if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2434 PMCDBG(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2445 pmc_start(struct pmc *pm)
2448 struct pmc_owner *po;
2449 struct pmc_binding pb;
2450 struct pmc_classdep *pcd;
2451 int adjri, error, cpu, ri;
2454 ("[pmc,%d] null pm", __LINE__));
2456 mode = PMC_TO_MODE(pm);
2457 ri = PMC_TO_ROWINDEX(pm);
2458 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2462 PMCDBG(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2467 * Disallow PMCSTART if a logfile is required but has not been
2470 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2471 (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2472 return (EDOOFUS); /* programming error */
2475 * If this is a sampling mode PMC, log mapping information for
2476 * the kernel modules that are currently loaded.
2478 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2479 pmc_log_kernel_mappings(pm);
2481 if (PMC_IS_VIRTUAL_MODE(mode)) {
2484 * If a PMCATTACH has never been done on this PMC,
2485 * attach it to its owner process.
2488 if (LIST_EMPTY(&pm->pm_targets))
2489 error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2490 pmc_attach_process(po->po_owner, pm);
2493 * If the PMC is attached to its owner, then force a context
2494 * switch to ensure that the MD state gets set correctly.
2498 pm->pm_state = PMC_STATE_RUNNING;
2499 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2500 pmc_force_context_switch();
2508 * A system-wide PMC.
2510 * Add the owner to the global list if this is a system-wide
2514 if (mode == PMC_MODE_SS) {
2515 if (po->po_sscount == 0) {
2516 LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2517 atomic_add_rel_int(&pmc_ss_count, 1);
2518 PMCDBG(PMC,OPS,1, "po=%p in global list", po);
2523 /* Log mapping information for all processes in the system. */
2524 pmc_log_all_process_mappings(po);
2527 * Move to the CPU associated with this
2528 * PMC, and start the hardware.
2531 pmc_save_cpu_binding(&pb);
2533 cpu = PMC_TO_CPU(pm);
2535 if (!pmc_cpu_is_active(cpu))
2538 pmc_select_cpu(cpu);
2541 * global PMCs are configured at allocation time
2542 * so write out the initial value and start the PMC.
2545 pm->pm_state = PMC_STATE_RUNNING;
2548 if ((error = pcd->pcd_write_pmc(cpu, adjri,
2549 PMC_IS_SAMPLING_MODE(mode) ?
2550 pm->pm_sc.pm_reloadcount :
2551 pm->pm_sc.pm_initial)) == 0)
2552 error = pcd->pcd_start_pmc(cpu, adjri);
2555 pmc_restore_cpu_binding(&pb);
2565 pmc_stop(struct pmc *pm)
2567 struct pmc_owner *po;
2568 struct pmc_binding pb;
2569 struct pmc_classdep *pcd;
2570 int adjri, cpu, error, ri;
2572 KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2574 PMCDBG(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2575 PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2577 pm->pm_state = PMC_STATE_STOPPED;
2580 * If the PMC is a virtual mode one, changing the state to
2581 * non-RUNNING is enough to ensure that the PMC never gets
2584 * If this PMC is current running on a CPU, then it will
2585 * handled correctly at the time its target process is context
2589 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2593 * A system-mode PMC. Move to the CPU associated with
2594 * this PMC, and stop the hardware. We update the
2595 * 'initial count' so that a subsequent PMCSTART will
2596 * resume counting from the current hardware count.
2599 pmc_save_cpu_binding(&pb);
2601 cpu = PMC_TO_CPU(pm);
2603 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
2604 ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2606 if (!pmc_cpu_is_active(cpu))
2609 pmc_select_cpu(cpu);
2611 ri = PMC_TO_ROWINDEX(pm);
2612 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2615 if ((error = pcd->pcd_stop_pmc(cpu, adjri)) == 0)
2616 error = pcd->pcd_read_pmc(cpu, adjri, &pm->pm_sc.pm_initial);
2619 pmc_restore_cpu_binding(&pb);
2623 /* remove this owner from the global list of SS PMC owners */
2624 if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2626 if (po->po_sscount == 0) {
2627 atomic_subtract_rel_int(&pmc_ss_count, 1);
2628 LIST_REMOVE(po, po_ssnext);
2629 PMCDBG(PMC,OPS,2,"po=%p removed from global list", po);
2638 static const char *pmc_op_to_name[] = {
2640 #define __PMC_OP(N, D) #N ,
2647 * The syscall interface
2650 #define PMC_GET_SX_XLOCK(...) do { \
2651 sx_xlock(&pmc_sx); \
2652 if (pmc_hook == NULL) { \
2653 sx_xunlock(&pmc_sx); \
2654 return __VA_ARGS__; \
2658 #define PMC_DOWNGRADE_SX() do { \
2659 sx_downgrade(&pmc_sx); \
2660 is_sx_downgraded = 1; \
2664 pmc_syscall_handler(struct thread *td, void *syscall_args)
2666 int error, is_sx_downgraded, is_sx_locked, op;
2667 struct pmc_syscall_args *c;
2670 PMC_GET_SX_XLOCK(ENOSYS);
2674 is_sx_downgraded = 0;
2677 c = (struct pmc_syscall_args *) syscall_args;
2682 PMCDBG(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2683 pmc_op_to_name[op], arg);
2686 atomic_add_int(&pmc_stats.pm_syscalls, 1);
2693 * Configure a log file.
2695 * XXX This OP will be reworked.
2698 case PMC_OP_CONFIGURELOG:
2702 struct pmc_owner *po;
2703 struct pmc_op_configurelog cl;
2705 sx_assert(&pmc_sx, SX_XLOCKED);
2707 if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2710 /* mark this process as owning a log file */
2712 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2713 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2719 * If a valid fd was passed in, try to configure that,
2720 * otherwise if 'fd' was less than zero and there was
2721 * a log file configured, flush its buffers and
2724 if (cl.pm_logfd >= 0) {
2725 sx_xunlock(&pmc_sx);
2727 error = pmclog_configure_log(md, po, cl.pm_logfd);
2728 } else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2729 pmclog_process_closelog(po);
2730 error = pmclog_flush(po);
2732 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2733 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2734 pm->pm_state == PMC_STATE_RUNNING)
2736 error = pmclog_deconfigure_log(po);
2751 case PMC_OP_FLUSHLOG:
2753 struct pmc_owner *po;
2755 sx_assert(&pmc_sx, SX_XLOCKED);
2757 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2762 error = pmclog_flush(po);
2767 * Retrieve hardware configuration.
2770 case PMC_OP_GETCPUINFO: /* CPU information */
2772 struct pmc_op_getcpuinfo gci;
2773 struct pmc_classinfo *pci;
2774 struct pmc_classdep *pcd;
2777 gci.pm_cputype = md->pmd_cputype;
2778 gci.pm_ncpu = pmc_cpu_max();
2779 gci.pm_npmc = md->pmd_npmc;
2780 gci.pm_nclass = md->pmd_nclass;
2781 pci = gci.pm_classes;
2782 pcd = md->pmd_classdep;
2783 for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
2784 pci->pm_caps = pcd->pcd_caps;
2785 pci->pm_class = pcd->pcd_class;
2786 pci->pm_width = pcd->pcd_width;
2787 pci->pm_num = pcd->pcd_num;
2789 error = copyout(&gci, arg, sizeof(gci));
2795 * Get module statistics
2798 case PMC_OP_GETDRIVERSTATS:
2800 struct pmc_op_getdriverstats gms;
2802 bcopy(&pmc_stats, &gms, sizeof(gms));
2803 error = copyout(&gms, arg, sizeof(gms));
2809 * Retrieve module version number
2812 case PMC_OP_GETMODULEVERSION:
2816 /* retrieve the client's idea of the ABI version */
2817 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
2819 /* don't service clients newer than our driver */
2821 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
2822 error = EPROGMISMATCH;
2825 error = copyout(&modv, arg, sizeof(int));
2831 * Retrieve the state of all the PMCs on a given
2835 case PMC_OP_GETPMCINFO:
2839 size_t pmcinfo_size;
2840 uint32_t cpu, n, npmc;
2841 struct pmc_owner *po;
2842 struct pmc_binding pb;
2843 struct pmc_classdep *pcd;
2844 struct pmc_info *p, *pmcinfo;
2845 struct pmc_op_getpmcinfo *gpi;
2849 gpi = (struct pmc_op_getpmcinfo *) arg;
2851 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
2854 if (cpu >= pmc_cpu_max()) {
2859 if (!pmc_cpu_is_active(cpu)) {
2864 /* switch to CPU 'cpu' */
2865 pmc_save_cpu_binding(&pb);
2866 pmc_select_cpu(cpu);
2868 npmc = md->pmd_npmc;
2870 pmcinfo_size = npmc * sizeof(struct pmc_info);
2871 pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK);
2875 for (n = 0; n < md->pmd_npmc; n++, p++) {
2877 pcd = pmc_ri_to_classdep(md, n, &ari);
2879 KASSERT(pcd != NULL,
2880 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
2882 if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
2885 if (PMC_ROW_DISP_IS_STANDALONE(n))
2886 p->pm_rowdisp = PMC_DISP_STANDALONE;
2887 else if (PMC_ROW_DISP_IS_THREAD(n))
2888 p->pm_rowdisp = PMC_DISP_THREAD;
2890 p->pm_rowdisp = PMC_DISP_FREE;
2892 p->pm_ownerpid = -1;
2894 if (pm == NULL) /* no PMC associated */
2899 KASSERT(po->po_owner != NULL,
2900 ("[pmc,%d] pmc_owner had a null proc pointer",
2903 p->pm_ownerpid = po->po_owner->p_pid;
2904 p->pm_mode = PMC_TO_MODE(pm);
2905 p->pm_event = pm->pm_event;
2906 p->pm_flags = pm->pm_flags;
2908 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2910 pm->pm_sc.pm_reloadcount;
2913 pmc_restore_cpu_binding(&pb);
2915 /* now copy out the PMC info collected */
2917 error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
2919 free(pmcinfo, M_PMC);
2925 * Set the administrative state of a PMC. I.e. whether
2926 * the PMC is to be used or not.
2929 case PMC_OP_PMCADMIN:
2932 enum pmc_state request;
2935 struct pmc_op_pmcadmin pma;
2936 struct pmc_binding pb;
2938 sx_assert(&pmc_sx, SX_XLOCKED);
2940 KASSERT(td == curthread,
2941 ("[pmc,%d] td != curthread", __LINE__));
2943 error = priv_check(td, PRIV_PMC_MANAGE);
2947 if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
2952 if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
2957 if (!pmc_cpu_is_active(cpu)) {
2962 request = pma.pm_state;
2964 if (request != PMC_STATE_DISABLED &&
2965 request != PMC_STATE_FREE) {
2970 ri = pma.pm_pmc; /* pmc id == row index */
2971 if (ri < 0 || ri >= (int) md->pmd_npmc) {
2977 * We can't disable a PMC with a row-index allocated
2978 * for process virtual PMCs.
2981 if (PMC_ROW_DISP_IS_THREAD(ri) &&
2982 request == PMC_STATE_DISABLED) {
2988 * otherwise, this PMC on this CPU is either free or
2989 * in system-wide mode.
2992 pmc_save_cpu_binding(&pb);
2993 pmc_select_cpu(cpu);
2996 phw = pc->pc_hwpmcs[ri];
2999 * XXX do we need some kind of 'forced' disable?
3002 if (phw->phw_pmc == NULL) {
3003 if (request == PMC_STATE_DISABLED &&
3004 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
3005 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
3006 PMC_MARK_ROW_STANDALONE(ri);
3007 } else if (request == PMC_STATE_FREE &&
3008 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
3009 phw->phw_state |= PMC_PHW_FLAG_IS_ENABLED;
3010 PMC_UNMARK_ROW_STANDALONE(ri);
3012 /* other cases are a no-op */
3016 pmc_restore_cpu_binding(&pb);
3025 case PMC_OP_PMCALLOCATE:
3033 struct pmc_binding pb;
3034 struct pmc_classdep *pcd;
3035 struct pmc_op_pmcallocate pa;
3037 if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
3044 if ((mode != PMC_MODE_SS && mode != PMC_MODE_SC &&
3045 mode != PMC_MODE_TS && mode != PMC_MODE_TC) ||
3046 (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
3052 * Virtual PMCs should only ask for a default CPU.
3053 * System mode PMCs need to specify a non-default CPU.
3056 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3057 (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3063 * Check that an inactive CPU is not being asked for.
3066 if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3072 * Refuse an allocation for a system-wide PMC if this
3073 * process has been jailed, or if this process lacks
3074 * super-user credentials and the sysctl tunable
3075 * 'security.bsd.unprivileged_syspmcs' is zero.
3078 if (PMC_IS_SYSTEM_MODE(mode)) {
3079 if (jailed(curthread->td_ucred)) {
3083 if (!pmc_unprivileged_syspmcs) {
3084 error = priv_check(curthread,
3095 * Look for valid values for 'pm_flags'
3098 if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3099 PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3104 /* process logging options are not allowed for system PMCs */
3105 if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3106 (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3112 * All sampling mode PMCs need to be able to interrupt the
3115 if (PMC_IS_SAMPLING_MODE(mode))
3116 caps |= PMC_CAP_INTERRUPT;
3118 /* A valid class specifier should have been passed in. */
3119 for (n = 0; n < md->pmd_nclass; n++)
3120 if (md->pmd_classdep[n].pcd_class == pa.pm_class)
3122 if (n == md->pmd_nclass) {
3127 /* The requested PMC capabilities should be feasible. */
3128 if ((md->pmd_classdep[n].pcd_caps & caps) != caps) {
3133 PMCDBG(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3134 pa.pm_ev, caps, mode, cpu);
3136 pmc = pmc_allocate_pmc_descriptor();
3137 pmc->pm_id = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3139 pmc->pm_event = pa.pm_ev;
3140 pmc->pm_state = PMC_STATE_FREE;
3141 pmc->pm_caps = caps;
3142 pmc->pm_flags = pa.pm_flags;
3144 /* switch thread to CPU 'cpu' */
3145 pmc_save_cpu_binding(&pb);
3147 #define PMC_IS_SHAREABLE_PMC(cpu, n) \
3148 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state & \
3149 PMC_PHW_FLAG_IS_SHAREABLE)
3150 #define PMC_IS_UNALLOCATED(cpu, n) \
3151 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3153 if (PMC_IS_SYSTEM_MODE(mode)) {
3154 pmc_select_cpu(cpu);
3155 for (n = 0; n < (int) md->pmd_npmc; n++) {
3156 pcd = pmc_ri_to_classdep(md, n, &adjri);
3157 if (pmc_can_allocate_row(n, mode) == 0 &&
3158 pmc_can_allocate_rowindex(
3159 curthread->td_proc, n, cpu) == 0 &&
3160 (PMC_IS_UNALLOCATED(cpu, n) ||
3161 PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3162 pcd->pcd_allocate_pmc(cpu, adjri, pmc,
3167 /* Process virtual mode */
3168 for (n = 0; n < (int) md->pmd_npmc; n++) {
3169 pcd = pmc_ri_to_classdep(md, n, &adjri);
3170 if (pmc_can_allocate_row(n, mode) == 0 &&
3171 pmc_can_allocate_rowindex(
3172 curthread->td_proc, n,
3173 PMC_CPU_ANY) == 0 &&
3174 pcd->pcd_allocate_pmc(curthread->td_oncpu,
3175 adjri, pmc, &pa) == 0)
3180 #undef PMC_IS_UNALLOCATED
3181 #undef PMC_IS_SHAREABLE_PMC
3183 pmc_restore_cpu_binding(&pb);
3185 if (n == (int) md->pmd_npmc) {
3186 pmc_destroy_pmc_descriptor(pmc);
3193 /* Fill in the correct value in the ID field */
3194 pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3196 PMCDBG(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3197 pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3199 /* Process mode PMCs with logging enabled need log files */
3200 if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3201 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3203 /* All system mode sampling PMCs require a log file */
3204 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3205 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3208 * Configure global pmc's immediately
3211 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3213 pmc_save_cpu_binding(&pb);
3214 pmc_select_cpu(cpu);
3216 phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3217 pcd = pmc_ri_to_classdep(md, n, &adjri);
3219 if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3220 (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3221 (void) pcd->pcd_release_pmc(cpu, adjri, pmc);
3222 pmc_destroy_pmc_descriptor(pmc);
3225 pmc_restore_cpu_binding(&pb);
3230 pmc_restore_cpu_binding(&pb);
3233 pmc->pm_state = PMC_STATE_ALLOCATED;
3236 * mark row disposition
3239 if (PMC_IS_SYSTEM_MODE(mode))
3240 PMC_MARK_ROW_STANDALONE(n);
3242 PMC_MARK_ROW_THREAD(n);
3245 * Register this PMC with the current thread as its owner.
3249 pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3250 pmc_release_pmc_descriptor(pmc);
3257 * Return the allocated index.
3260 pa.pm_pmcid = pmc->pm_id;
3262 error = copyout(&pa, arg, sizeof(pa));
3268 * Attach a PMC to a process.
3271 case PMC_OP_PMCATTACH:
3275 struct pmc_op_pmcattach a;
3277 sx_assert(&pmc_sx, SX_XLOCKED);
3279 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3285 } else if (a.pm_pid == 0)
3286 a.pm_pid = td->td_proc->p_pid;
3288 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3291 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3296 /* PMCs may be (re)attached only when allocated or stopped */
3297 if (pm->pm_state == PMC_STATE_RUNNING) {
3300 } else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3301 pm->pm_state != PMC_STATE_STOPPED) {
3307 if ((p = pfind(a.pm_pid)) == NULL) {
3313 * Ignore processes that are working on exiting.
3315 if (p->p_flag & P_WEXIT) {
3317 PROC_UNLOCK(p); /* pfind() returns a locked process */
3322 * we are allowed to attach a PMC to a process if
3325 error = p_candebug(curthread, p);
3330 error = pmc_attach_process(p, pm);
3336 * Detach an attached PMC from a process.
3339 case PMC_OP_PMCDETACH:
3343 struct pmc_op_pmcattach a;
3345 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3351 } else if (a.pm_pid == 0)
3352 a.pm_pid = td->td_proc->p_pid;
3354 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3357 if ((p = pfind(a.pm_pid)) == NULL) {
3363 * Treat processes that are in the process of exiting
3364 * as if they were not present.
3367 if (p->p_flag & P_WEXIT)
3370 PROC_UNLOCK(p); /* pfind() returns a locked process */
3373 error = pmc_detach_process(p, pm);
3379 * Retrieve the MSR number associated with the counter
3380 * 'pmc_id'. This allows processes to directly use RDPMC
3381 * instructions to read their PMCs, without the overhead of a
3385 case PMC_OP_PMCGETMSR:
3389 struct pmc_target *pt;
3390 struct pmc_op_getmsr gm;
3391 struct pmc_classdep *pcd;
3395 if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3398 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3402 * The allocated PMC has to be a process virtual PMC,
3403 * i.e., of type MODE_T[CS]. Global PMCs can only be
3404 * read using the PMCREAD operation since they may be
3405 * allocated on a different CPU than the one we could
3406 * be running on at the time of the RDPMC instruction.
3408 * The GETMSR operation is not allowed for PMCs that
3409 * are inherited across processes.
3412 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3413 (pm->pm_flags & PMC_F_DESCENDANTS)) {
3419 * It only makes sense to use a RDPMC (or its
3420 * equivalent instruction on non-x86 architectures) on
3421 * a process that has allocated and attached a PMC to
3422 * itself. Conversely the PMC is only allowed to have
3423 * one process attached to it -- its owner.
3426 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3427 LIST_NEXT(pt, pt_next) != NULL ||
3428 pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3433 ri = PMC_TO_ROWINDEX(pm);
3434 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3436 /* PMC class has no 'GETMSR' support */
3437 if (pcd->pcd_get_msr == NULL) {
3442 if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
3445 if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3449 * Mark our process as using MSRs. Update machine
3450 * state using a forced context switch.
3453 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3454 pmc_force_context_switch();
3460 * Release an allocated PMC
3463 case PMC_OP_PMCRELEASE:
3467 struct pmc_owner *po;
3468 struct pmc_op_simple sp;
3471 * Find PMC pointer for the named PMC.
3473 * Use pmc_release_pmc_descriptor() to switch off the
3474 * PMC, remove all its target threads, and remove the
3475 * PMC from its owner's list.
3477 * Remove the owner record if this is the last PMC
3483 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3486 pmcid = sp.pm_pmcid;
3488 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3492 pmc_release_pmc_descriptor(pm);
3493 pmc_maybe_remove_owner(po);
3501 * Read and/or write a PMC.
3509 pmc_value_t oldvalue;
3510 struct pmc_binding pb;
3511 struct pmc_op_pmcrw prw;
3512 struct pmc_classdep *pcd;
3513 struct pmc_op_pmcrw *pprw;
3517 if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3521 PMCDBG(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3524 /* must have at least one flag set */
3525 if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3530 /* locate pmc descriptor */
3531 if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3534 /* Can't read a PMC that hasn't been started. */
3535 if (pm->pm_state != PMC_STATE_ALLOCATED &&
3536 pm->pm_state != PMC_STATE_STOPPED &&
3537 pm->pm_state != PMC_STATE_RUNNING) {
3542 /* writing a new value is allowed only for 'STOPPED' pmcs */
3543 if (pm->pm_state == PMC_STATE_RUNNING &&
3544 (prw.pm_flags & PMC_F_NEWVALUE)) {
3549 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3552 * If this PMC is attached to its owner (i.e.,
3553 * the process requesting this operation) and
3554 * is running, then attempt to get an
3555 * upto-date reading from hardware for a READ.
3556 * Writes are only allowed when the PMC is
3557 * stopped, so only update the saved value
3560 * If the PMC is not running, or is not
3561 * attached to its owner, read/write to the
3565 ri = PMC_TO_ROWINDEX(pm);
3566 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3568 mtx_pool_lock_spin(pmc_mtxpool, pm);
3569 cpu = curthread->td_oncpu;
3571 if (prw.pm_flags & PMC_F_OLDVALUE) {
3572 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3573 (pm->pm_state == PMC_STATE_RUNNING))
3574 error = (*pcd->pcd_read_pmc)(cpu, adjri,
3577 oldvalue = pm->pm_gv.pm_savedvalue;
3579 if (prw.pm_flags & PMC_F_NEWVALUE)
3580 pm->pm_gv.pm_savedvalue = prw.pm_value;
3582 mtx_pool_unlock_spin(pmc_mtxpool, pm);
3584 } else { /* System mode PMCs */
3585 cpu = PMC_TO_CPU(pm);
3586 ri = PMC_TO_ROWINDEX(pm);
3587 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3589 if (!pmc_cpu_is_active(cpu)) {
3594 /* move this thread to CPU 'cpu' */
3595 pmc_save_cpu_binding(&pb);
3596 pmc_select_cpu(cpu);
3599 /* save old value */
3600 if (prw.pm_flags & PMC_F_OLDVALUE)
3601 if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
3604 /* write out new value */
3605 if (prw.pm_flags & PMC_F_NEWVALUE)
3606 error = (*pcd->pcd_write_pmc)(cpu, adjri,
3610 pmc_restore_cpu_binding(&pb);
3615 pprw = (struct pmc_op_pmcrw *) arg;
3618 if (prw.pm_flags & PMC_F_NEWVALUE)
3619 PMCDBG(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3620 ri, prw.pm_value, oldvalue);
3621 else if (prw.pm_flags & PMC_F_OLDVALUE)
3622 PMCDBG(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3625 /* return old value if requested */
3626 if (prw.pm_flags & PMC_F_OLDVALUE)
3627 if ((error = copyout(&oldvalue, &pprw->pm_value,
3628 sizeof(prw.pm_value))))
3636 * Set the sampling rate for a sampling mode PMC and the
3637 * initial count for a counting mode PMC.
3640 case PMC_OP_PMCSETCOUNT:
3643 struct pmc_op_pmcsetcount sc;
3647 if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3650 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3653 if (pm->pm_state == PMC_STATE_RUNNING) {
3658 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3659 pm->pm_sc.pm_reloadcount = sc.pm_count;
3661 pm->pm_sc.pm_initial = sc.pm_count;
3670 case PMC_OP_PMCSTART:
3674 struct pmc_op_simple sp;
3676 sx_assert(&pmc_sx, SX_XLOCKED);
3678 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3681 pmcid = sp.pm_pmcid;
3683 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3686 KASSERT(pmcid == pm->pm_id,
3687 ("[pmc,%d] pmcid %x != id %x", __LINE__,
3690 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3692 else if (pm->pm_state != PMC_STATE_STOPPED &&
3693 pm->pm_state != PMC_STATE_ALLOCATED) {
3698 error = pmc_start(pm);
3707 case PMC_OP_PMCSTOP:
3711 struct pmc_op_simple sp;
3715 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3718 pmcid = sp.pm_pmcid;
3721 * Mark the PMC as inactive and invoke the MD stop
3722 * routines if needed.
3725 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3728 KASSERT(pmcid == pm->pm_id,
3729 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3732 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3734 else if (pm->pm_state != PMC_STATE_RUNNING) {
3739 error = pmc_stop(pm);
3745 * Write a user supplied value to the log file.
3748 case PMC_OP_WRITELOG:
3750 struct pmc_op_writelog wl;
3751 struct pmc_owner *po;
3755 if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
3758 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3763 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
3768 error = pmclog_process_userlog(po, &wl);
3778 if (is_sx_locked != 0) {
3779 if (is_sx_downgraded)
3780 sx_sunlock(&pmc_sx);
3782 sx_xunlock(&pmc_sx);
3786 atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
3799 * Mark the thread as needing callchain capture and post an AST. The
3800 * actual callchain capture will be done in a context where it is safe
3801 * to take page faults.
3805 pmc_post_callchain_callback(void)
3811 KASSERT((td->td_pflags & TDP_CALLCHAIN) == 0,
3812 ("[pmc,%d] thread %p already marked for callchain capture",
3813 __LINE__, (void *) td));
3816 * Mark this thread as needing callchain capture.
3817 * `td->td_pflags' will be safe to touch because this thread
3818 * was in user space when it was interrupted.
3820 td->td_pflags |= TDP_CALLCHAIN;
3823 * Don't let this thread migrate between CPUs until callchain
3824 * capture completes.
3832 * Interrupt processing.
3834 * Find a free slot in the per-cpu array of samples and capture the
3835 * current callchain there. If a sample was successfully added, a bit
3836 * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
3837 * needs to be invoked from the clock handler.
3839 * This function is meant to be called from an NMI handler. It cannot
3840 * use any of the locking primitives supplied by the OS.
3844 pmc_process_interrupt(int cpu, struct pmc *pm, struct trapframe *tf,
3847 int error, callchaindepth;
3849 struct pmc_sample *ps;
3850 struct pmc_samplebuffer *psb;
3855 * Allocate space for a sample buffer.
3857 psb = pmc_pcpu[cpu]->pc_sb;
3860 if (ps->ps_nsamples) { /* in use, reader hasn't caught up */
3862 atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
3863 PMCDBG(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
3864 cpu, pm, (void *) tf, inuserspace,
3865 (int) (psb->ps_write - psb->ps_samples),
3866 (int) (psb->ps_read - psb->ps_samples));
3872 /* Fill in entry. */
3873 PMCDBG(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
3874 (void *) tf, inuserspace,
3875 (int) (psb->ps_write - psb->ps_samples),
3876 (int) (psb->ps_read - psb->ps_samples));
3878 KASSERT(pm->pm_runcount >= 0,
3879 ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
3882 atomic_add_rel_32(&pm->pm_runcount, 1); /* hold onto PMC */
3884 if ((td = curthread) && td->td_proc)
3885 ps->ps_pid = td->td_proc->p_pid;
3890 ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
3892 callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
3893 pmc_callchaindepth : 1;
3895 if (callchaindepth == 1)
3896 ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
3899 * Kernel stack traversals can be done immediately,
3900 * while we defer to an AST for user space traversals.
3904 pmc_save_kernel_callchain(ps->ps_pc,
3905 callchaindepth, tf);
3907 pmc_post_callchain_callback();
3908 callchaindepth = PMC_SAMPLE_INUSE;
3912 ps->ps_nsamples = callchaindepth; /* mark entry as in use */
3914 /* increment write pointer, modulo ring buffer size */
3916 if (ps == psb->ps_fence)
3917 psb->ps_write = psb->ps_samples;
3922 /* mark CPU as needing processing */
3923 atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3929 * Capture a user call chain. This function will be called from ast()
3930 * before control returns to userland and before the process gets
3935 pmc_capture_user_callchain(int cpu, struct trapframe *tf)
3940 struct pmc_sample *ps;
3941 struct pmc_samplebuffer *psb;
3946 sched_unpin(); /* Can migrate safely now. */
3948 psb = pmc_pcpu[cpu]->pc_sb;
3951 KASSERT(td->td_pflags & TDP_CALLCHAIN,
3952 ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
3960 * Iterate through all deferred callchain requests.
3963 ps = psb->ps_samples;
3964 for (i = 0; i < pmc_nsamples; i++, ps++) {
3966 if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
3968 if (ps->ps_td != td)
3971 KASSERT(ps->ps_cpu == cpu,
3972 ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
3973 ps->ps_cpu, PCPU_GET(cpuid)));
3977 KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
3978 ("[pmc,%d] Retrieving callchain for PMC that doesn't "
3979 "want it", __LINE__));
3981 KASSERT(pm->pm_runcount > 0,
3982 ("[pmc,%d] runcount %d", __LINE__, pm->pm_runcount));
3985 * Retrieve the callchain and mark the sample buffer
3986 * as 'processable' by the timer tick sweep code.
3988 ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
3989 pmc_callchaindepth, tf);
3997 KASSERT(ncallchains > 0,
3998 ("[pmc,%d] cpu %d didn't find a sample to collect", __LINE__,
4006 * Process saved PC samples.
4010 pmc_process_samples(int cpu)
4015 struct pmc_owner *po;
4016 struct pmc_sample *ps;
4017 struct pmc_classdep *pcd;
4018 struct pmc_samplebuffer *psb;
4020 KASSERT(PCPU_GET(cpuid) == cpu,
4021 ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4022 PCPU_GET(cpuid), cpu));
4024 psb = pmc_pcpu[cpu]->pc_sb;
4026 for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
4029 if (ps->ps_nsamples == PMC_SAMPLE_FREE)
4031 if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
4032 /* Need a rescan at a later time. */
4033 atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
4039 KASSERT(pm->pm_runcount > 0,
4040 ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4045 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4046 ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4047 pm, PMC_TO_MODE(pm)));
4049 /* Ignore PMCs that have been switched off */
4050 if (pm->pm_state != PMC_STATE_RUNNING)
4053 PMCDBG(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4054 pm, ps->ps_nsamples, ps->ps_flags,
4055 (int) (psb->ps_write - psb->ps_samples),
4056 (int) (psb->ps_read - psb->ps_samples));
4059 * If this is a process-mode PMC that is attached to
4060 * its owner, and if the PC is in user mode, update
4061 * profiling statistics like timer-based profiling
4064 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4065 if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4066 td = FIRST_THREAD_IN_PROC(po->po_owner);
4067 addupc_intr(td, ps->ps_pc[0], 1);
4073 * Otherwise, this is either a sampling mode PMC that
4074 * is attached to a different process than its owner,
4075 * or a system-wide sampling PMC. Dispatch a log
4076 * entry to the PMC's owner process.
4079 pmclog_process_callchain(pm, ps);
4082 ps->ps_nsamples = 0; /* mark entry as free */
4083 atomic_subtract_rel_32(&pm->pm_runcount, 1);
4085 /* increment read pointer, modulo sample size */
4086 if (++ps == psb->ps_fence)
4087 psb->ps_read = psb->ps_samples;
4092 atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
4094 /* Do not re-enable stalled PMCs if we failed to process any samples */
4099 * Restart any stalled sampling PMCs on this CPU.
4101 * If the NMI handler sets the pm_stalled field of a PMC after
4102 * the check below, we'll end up processing the stalled PMC at
4103 * the next hardclock tick.
4105 for (n = 0; n < md->pmd_npmc; n++) {
4106 pcd = pmc_ri_to_classdep(md, n, &adjri);
4107 KASSERT(pcd != NULL,
4108 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4109 (void) (*pcd->pcd_get_config)(cpu,adjri,&pm);
4111 if (pm == NULL || /* !cfg'ed */
4112 pm->pm_state != PMC_STATE_RUNNING || /* !active */
4113 !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4114 pm->pm_stalled == 0) /* !stalled */
4118 (*pcd->pcd_start_pmc)(cpu, adjri);
4127 * Handle a process exit.
4129 * Remove this process from all hash tables. If this process
4130 * owned any PMCs, turn off those PMCs and deallocate them,
4131 * removing any associations with target processes.
4133 * This function will be called by the last 'thread' of a
4136 * XXX This eventhandler gets called early in the exit process.
4137 * Consider using a 'hook' invocation from thread_exit() or equivalent
4138 * spot. Another negative is that kse_exit doesn't seem to call
4144 pmc_process_exit(void *arg __unused, struct proc *p)
4149 int is_using_hwpmcs;
4150 struct pmc_owner *po;
4151 struct pmc_process *pp;
4152 struct pmc_classdep *pcd;
4153 pmc_value_t newvalue, tmp;
4156 is_using_hwpmcs = p->p_flag & P_HWPMC;
4160 * Log a sysexit event to all SS PMC owners.
4162 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4163 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4164 pmclog_process_sysexit(po, p->p_pid);
4166 if (!is_using_hwpmcs)
4170 PMCDBG(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4174 * Since this code is invoked by the last thread in an exiting
4175 * process, we would have context switched IN at some prior
4176 * point. However, with PREEMPTION, kernel mode context
4177 * switches may happen any time, so we want to disable a
4178 * context switch OUT till we get any PMCs targetting this
4179 * process off the hardware.
4181 * We also need to atomically remove this process'
4182 * entry from our target process hash table, using
4185 PMCDBG(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4188 critical_enter(); /* no preemption */
4190 cpu = curthread->td_oncpu;
4192 if ((pp = pmc_find_process_descriptor(p,
4193 PMC_FLAG_REMOVE)) != NULL) {
4196 "process-exit proc=%p pmc-process=%p", p, pp);
4199 * The exiting process could the target of
4200 * some PMCs which will be running on
4201 * currently executing CPU.
4203 * We need to turn these PMCs off like we
4204 * would do at context switch OUT time.
4206 for (ri = 0; ri < md->pmd_npmc; ri++) {
4209 * Pick up the pmc pointer from hardware
4210 * state similar to the CSW_OUT code.
4214 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4216 (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
4218 PMCDBG(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4221 !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4224 PMCDBG(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4225 "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4228 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4229 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4230 __LINE__, PMC_TO_ROWINDEX(pm), ri));
4232 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4233 ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4234 __LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4236 (void) pcd->pcd_stop_pmc(cpu, adjri);
4238 KASSERT(pm->pm_runcount > 0,
4239 ("[pmc,%d] bad runcount ri %d rc %d",
4240 __LINE__, ri, pm->pm_runcount));
4242 /* Stop hardware only if it is actually running */
4243 if (pm->pm_state == PMC_STATE_RUNNING &&
4244 pm->pm_stalled == 0) {
4245 pcd->pcd_read_pmc(cpu, adjri, &newvalue);
4247 PMC_PCPU_SAVED(cpu,ri);
4249 mtx_pool_lock_spin(pmc_mtxpool, pm);
4250 pm->pm_gv.pm_savedvalue += tmp;
4251 pp->pp_pmcs[ri].pp_pmcval += tmp;
4252 mtx_pool_unlock_spin(pmc_mtxpool, pm);
4255 atomic_subtract_rel_32(&pm->pm_runcount,1);
4257 KASSERT((int) pm->pm_runcount >= 0,
4258 ("[pmc,%d] runcount is %d", __LINE__, ri));
4260 (void) pcd->pcd_config_pmc(cpu, adjri, NULL);
4264 * Inform the MD layer of this pseudo "context switch
4267 (void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
4269 critical_exit(); /* ok to be pre-empted now */
4272 * Unlink this process from the PMCs that are
4273 * targetting it. This will send a signal to
4274 * all PMC owner's whose PMCs are orphaned.
4276 * Log PMC value at exit time if requested.
4278 for (ri = 0; ri < md->pmd_npmc; ri++)
4279 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
4280 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
4281 PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
4282 pmclog_process_procexit(pm, pp);
4283 pmc_unlink_target_process(pm, pp);
4288 critical_exit(); /* pp == NULL */
4292 * If the process owned PMCs, free them up and free up
4295 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
4296 pmc_remove_owner(po);
4297 pmc_destroy_owner_descriptor(po);
4300 sx_xunlock(&pmc_sx);
4304 * Handle a process fork.
4306 * If the parent process 'p1' is under HWPMC monitoring, then copy
4307 * over any attached PMCs that have 'do_descendants' semantics.
4311 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
4314 int is_using_hwpmcs;
4316 uint32_t do_descendants;
4318 struct pmc_owner *po;
4319 struct pmc_process *ppnew, *ppold;
4321 (void) flags; /* unused parameter */
4324 is_using_hwpmcs = p1->p_flag & P_HWPMC;
4328 * If there are system-wide sampling PMCs active, we need to
4329 * log all fork events to their owner's logs.
4332 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4333 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4334 pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4336 if (!is_using_hwpmcs)
4340 PMCDBG(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4341 p1->p_pid, p1->p_comm, newproc);
4344 * If the parent process (curthread->td_proc) is a
4345 * target of any PMCs, look for PMCs that are to be
4346 * inherited, and link these into the new process
4349 if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4350 PMC_FLAG_NONE)) == NULL)
4351 goto done; /* nothing to do */
4354 for (ri = 0; ri < md->pmd_npmc; ri++)
4355 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4356 do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4357 if (do_descendants == 0) /* nothing to do */
4360 /* allocate a descriptor for the new process */
4361 if ((ppnew = pmc_find_process_descriptor(newproc,
4362 PMC_FLAG_ALLOCATE)) == NULL)
4366 * Run through all PMCs that were targeting the old process
4367 * and which specified F_DESCENDANTS and attach them to the
4370 * Log the fork event to all owners of PMCs attached to this
4371 * process, if not already logged.
4373 for (ri = 0; ri < md->pmd_npmc; ri++)
4374 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4375 (pm->pm_flags & PMC_F_DESCENDANTS)) {
4376 pmc_link_target_process(pm, ppnew);
4378 if (po->po_sscount == 0 &&
4379 po->po_flags & PMC_PO_OWNS_LOGFILE)
4380 pmclog_process_procfork(po, p1->p_pid,
4385 * Now mark the new process as being tracked by this driver.
4388 newproc->p_flag |= P_HWPMC;
4389 PROC_UNLOCK(newproc);
4392 sx_xunlock(&pmc_sx);
4400 static const char *pmc_name_of_pmcclass[] = {
4402 #define __PMC_CLASS(N) #N ,
4407 pmc_initialize(void)
4409 int c, cpu, error, n, ri;
4410 unsigned int maxcpu;
4411 struct pmc_binding pb;
4412 struct pmc_sample *ps;
4413 struct pmc_classdep *pcd;
4414 struct pmc_samplebuffer *sb;
4420 /* parse debug flags first */
4421 if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4422 pmc_debugstr, sizeof(pmc_debugstr)))
4423 pmc_debugflags_parse(pmc_debugstr,
4424 pmc_debugstr+strlen(pmc_debugstr));
4427 PMCDBG(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4429 /* check kernel version */
4430 if (pmc_kernel_version != PMC_VERSION) {
4431 if (pmc_kernel_version == 0)
4432 printf("hwpmc: this kernel has not been compiled with "
4433 "'options HWPMC_HOOKS'.\n");
4435 printf("hwpmc: kernel version (0x%x) does not match "
4436 "module version (0x%x).\n", pmc_kernel_version,
4438 return EPROGMISMATCH;
4442 * check sysctl parameters
4445 if (pmc_hashsize <= 0) {
4446 (void) printf("hwpmc: tunable \"hashsize\"=%d must be "
4447 "greater than zero.\n", pmc_hashsize);
4448 pmc_hashsize = PMC_HASH_SIZE;
4451 if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4452 (void) printf("hwpmc: tunable \"nsamples\"=%d out of "
4453 "range.\n", pmc_nsamples);
4454 pmc_nsamples = PMC_NSAMPLES;
4457 if (pmc_callchaindepth <= 0 ||
4458 pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
4459 (void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
4460 "range.\n", pmc_callchaindepth);
4461 pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
4464 md = pmc_md_initialize();
4469 KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
4470 ("[pmc,%d] no classes or pmcs", __LINE__));
4472 /* Compute the map from row-indices to classdep pointers. */
4473 pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
4474 md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);
4476 for (n = 0; n < md->pmd_npmc; n++)
4477 pmc_rowindex_to_classdep[n] = NULL;
4478 for (ri = c = 0; c < md->pmd_nclass; c++) {
4479 pcd = &md->pmd_classdep[c];
4480 for (n = 0; n < pcd->pcd_num; n++, ri++)
4481 pmc_rowindex_to_classdep[ri] = pcd;
4484 KASSERT(ri == md->pmd_npmc,
4485 ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
4488 maxcpu = pmc_cpu_max();
4490 /* allocate space for the per-cpu array */
4491 pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
4494 /* per-cpu 'saved values' for managing process-mode PMCs */
4495 pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
4498 /* Perform CPU-dependent initialization. */
4499 pmc_save_cpu_binding(&pb);
4501 for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
4502 if (!pmc_cpu_is_active(cpu))
4504 pmc_select_cpu(cpu);
4505 pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
4506 md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
4508 if (md->pmd_pcpu_init)
4509 error = md->pmd_pcpu_init(md, cpu);
4510 for (n = 0; error == 0 && n < md->pmd_nclass; n++)
4511 error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
4513 pmc_restore_cpu_binding(&pb);
4518 /* allocate space for the sample array */
4519 for (cpu = 0; cpu < maxcpu; cpu++) {
4520 if (!pmc_cpu_is_active(cpu))
4523 sb = malloc(sizeof(struct pmc_samplebuffer) +
4524 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4526 sb->ps_read = sb->ps_write = sb->ps_samples;
4527 sb->ps_fence = sb->ps_samples + pmc_nsamples;
4529 KASSERT(pmc_pcpu[cpu] != NULL,
4530 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4532 sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4533 sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4535 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4536 ps->ps_pc = sb->ps_callchains +
4537 (n * pmc_callchaindepth);
4539 pmc_pcpu[cpu]->pc_sb = sb;
4542 /* allocate space for the row disposition array */
4543 pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4544 M_PMC, M_WAITOK|M_ZERO);
4546 KASSERT(pmc_pmcdisp != NULL,
4547 ("[pmc,%d] pmcdisp allocation returned NULL", __LINE__));
4549 /* mark all PMCs as available */
4550 for (n = 0; n < (int) md->pmd_npmc; n++)
4551 PMC_MARK_ROW_FREE(n);
4553 /* allocate thread hash tables */
4554 pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4555 &pmc_ownerhashmask);
4557 pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4558 &pmc_processhashmask);
4559 mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4562 LIST_INIT(&pmc_ss_owners);
4565 /* allocate a pool of spin mutexes */
4566 pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4569 PMCDBG(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4570 "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4571 pmc_processhash, pmc_processhashmask);
4573 /* register process {exit,fork,exec} handlers */
4574 pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4575 pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4576 pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4577 pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4579 /* initialize logging */
4580 pmclog_initialize();
4582 /* set hook functions */
4583 pmc_intr = md->pmd_intr;
4584 pmc_hook = pmc_hook_handler;
4587 printf(PMC_MODULE_NAME ":");
4588 for (n = 0; n < (int) md->pmd_nclass; n++) {
4589 pcd = &md->pmd_classdep[n];
4590 printf(" %s/%d/%d/0x%b",
4591 pmc_name_of_pmcclass[pcd->pcd_class],
4596 "\1INT\2USR\3SYS\4EDG\5THR"
4597 "\6REA\7WRI\10INV\11QUA\12PRC"
4606 /* prepare to be unloaded */
4611 unsigned int maxcpu;
4612 struct pmc_ownerhash *ph;
4613 struct pmc_owner *po, *tmp;
4614 struct pmc_binding pb;
4616 struct pmc_processhash *prh;
4619 PMCDBG(MOD,INI,0, "%s", "cleanup");
4621 /* switch off sampling */
4622 atomic_store_rel_int(&pmc_cpumask, 0);
4626 if (pmc_hook == NULL) { /* being unloaded already */
4627 sx_xunlock(&pmc_sx);
4631 pmc_hook = NULL; /* prevent new threads from entering module */
4633 /* deregister event handlers */
4634 EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4635 EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4637 /* send SIGBUS to all owner threads, free up allocations */
4639 for (ph = pmc_ownerhash;
4640 ph <= &pmc_ownerhash[pmc_ownerhashmask];
4642 LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4643 pmc_remove_owner(po);
4645 /* send SIGBUS to owner processes */
4646 PMCDBG(MOD,INI,2, "cleanup signal proc=%p "
4647 "(%d, %s)", po->po_owner,
4648 po->po_owner->p_pid,
4649 po->po_owner->p_comm);
4651 PROC_LOCK(po->po_owner);
4652 psignal(po->po_owner, SIGBUS);
4653 PROC_UNLOCK(po->po_owner);
4655 pmc_destroy_owner_descriptor(po);
4659 /* reclaim allocated data structures */
4661 mtx_pool_destroy(&pmc_mtxpool);
4663 mtx_destroy(&pmc_processhash_mtx);
4664 if (pmc_processhash) {
4666 struct pmc_process *pp;
4668 PMCDBG(MOD,INI,3, "%s", "destroy process hash");
4669 for (prh = pmc_processhash;
4670 prh <= &pmc_processhash[pmc_processhashmask];
4672 LIST_FOREACH(pp, prh, pp_next)
4673 PMCDBG(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
4676 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
4677 pmc_processhash = NULL;
4680 if (pmc_ownerhash) {
4681 PMCDBG(MOD,INI,3, "%s", "destroy owner hash");
4682 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
4683 pmc_ownerhash = NULL;
4686 KASSERT(LIST_EMPTY(&pmc_ss_owners),
4687 ("[pmc,%d] Global SS owner list not empty", __LINE__));
4688 KASSERT(pmc_ss_count == 0,
4689 ("[pmc,%d] Global SS count not empty", __LINE__));
4691 /* do processor and pmc-class dependent cleanup */
4692 maxcpu = pmc_cpu_max();
4694 PMCDBG(MOD,INI,3, "%s", "md cleanup");
4696 pmc_save_cpu_binding(&pb);
4697 for (cpu = 0; cpu < maxcpu; cpu++) {
4698 PMCDBG(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
4699 cpu, pmc_pcpu[cpu]);
4700 if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
4702 pmc_select_cpu(cpu);
4703 for (c = 0; c < md->pmd_nclass; c++)
4704 md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
4705 if (md->pmd_pcpu_fini)
4706 md->pmd_pcpu_fini(md, cpu);
4709 pmc_md_finalize(md);
4713 pmc_restore_cpu_binding(&pb);
4716 /* Free per-cpu descriptors. */
4717 for (cpu = 0; cpu < maxcpu; cpu++) {
4718 if (!pmc_cpu_is_active(cpu))
4720 KASSERT(pmc_pcpu[cpu]->pc_sb != NULL,
4721 ("[pmc,%d] Null cpu sample buffer cpu=%d", __LINE__,
4723 free(pmc_pcpu[cpu]->pc_sb->ps_callchains, M_PMC);
4724 free(pmc_pcpu[cpu]->pc_sb, M_PMC);
4725 free(pmc_pcpu[cpu], M_PMC);
4728 free(pmc_pcpu, M_PMC);
4731 free(pmc_pcpu_saved, M_PMC);
4732 pmc_pcpu_saved = NULL;
4735 free(pmc_pmcdisp, M_PMC);
4739 if (pmc_rowindex_to_classdep) {
4740 free(pmc_rowindex_to_classdep, M_PMC);
4741 pmc_rowindex_to_classdep = NULL;
4746 sx_xunlock(&pmc_sx); /* we are done */
4750 * The function called at load/unload.
4754 load (struct module *module __unused, int cmd, void *arg __unused)
4762 /* initialize the subsystem */
4763 error = pmc_initialize();
4766 PMCDBG(MOD,INI,1, "syscall=%d maxcpu=%d",
4767 pmc_syscall_num, pmc_cpu_max());
4774 PMCDBG(MOD,INI,1, "%s", "unloaded");
4778 error = EINVAL; /* XXX should panic(9) */
4786 MALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");