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/mount.h>
45 #include <sys/mutex.h>
47 #include <sys/pmckern.h>
48 #include <sys/pmclog.h>
51 #include <sys/queue.h>
52 #include <sys/resourcevar.h>
53 #include <sys/sched.h>
54 #include <sys/signalvar.h>
57 #include <sys/sysctl.h>
58 #include <sys/sysent.h>
59 #include <sys/systm.h>
60 #include <sys/vnode.h>
62 #include <sys/linker.h> /* needs to be after <sys/malloc.h> */
64 #include <machine/atomic.h>
65 #include <machine/md_var.h>
68 #include <vm/vm_extern.h>
70 #include <vm/vm_map.h>
71 #include <vm/vm_object.h>
73 #include "hwpmc_soft.h"
80 PMC_FLAG_NONE = 0x00, /* do nothing */
81 PMC_FLAG_REMOVE = 0x01, /* atomically remove entry from hash */
82 PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
86 * The offset in sysent where the syscall is allocated.
89 static int pmc_syscall_num = NO_SYSCALL;
90 struct pmc_cpu **pmc_pcpu; /* per-cpu state */
91 pmc_value_t *pmc_pcpu_saved; /* saved PMC values: CSW handling */
93 #define PMC_PCPU_SAVED(C,R) pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
95 struct mtx_pool *pmc_mtxpool;
96 static int *pmc_pmcdisp; /* PMC row dispositions */
98 #define PMC_ROW_DISP_IS_FREE(R) (pmc_pmcdisp[(R)] == 0)
99 #define PMC_ROW_DISP_IS_THREAD(R) (pmc_pmcdisp[(R)] > 0)
100 #define PMC_ROW_DISP_IS_STANDALONE(R) (pmc_pmcdisp[(R)] < 0)
102 #define PMC_MARK_ROW_FREE(R) do { \
103 pmc_pmcdisp[(R)] = 0; \
106 #define PMC_MARK_ROW_STANDALONE(R) do { \
107 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
109 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
110 KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()), \
111 ("[pmc,%d] row disposition error", __LINE__)); \
114 #define PMC_UNMARK_ROW_STANDALONE(R) do { \
115 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
116 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
120 #define PMC_MARK_ROW_THREAD(R) do { \
121 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
123 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
126 #define PMC_UNMARK_ROW_THREAD(R) do { \
127 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
128 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
133 /* various event handlers */
134 static eventhandler_tag pmc_exit_tag, pmc_fork_tag, pmc_kld_load_tag,
137 /* Module statistics */
138 struct pmc_op_getdriverstats pmc_stats;
140 /* Machine/processor dependent operations */
141 static struct pmc_mdep *md;
144 * Hash tables mapping owner processes and target threads to PMCs.
147 struct mtx pmc_processhash_mtx; /* spin mutex */
148 static u_long pmc_processhashmask;
149 static LIST_HEAD(pmc_processhash, pmc_process) *pmc_processhash;
152 * Hash table of PMC owner descriptors. This table is protected by
153 * the shared PMC "sx" lock.
156 static u_long pmc_ownerhashmask;
157 static LIST_HEAD(pmc_ownerhash, pmc_owner) *pmc_ownerhash;
160 * List of PMC owners with system-wide sampling PMCs.
163 static LIST_HEAD(, pmc_owner) pmc_ss_owners;
167 * A map of row indices to classdep structures.
169 static struct pmc_classdep **pmc_rowindex_to_classdep;
176 static int pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
177 static int pmc_debugflags_parse(char *newstr, char *fence);
180 static int load(struct module *module, int cmd, void *arg);
181 static int pmc_attach_process(struct proc *p, struct pmc *pm);
182 static struct pmc *pmc_allocate_pmc_descriptor(void);
183 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
184 static int pmc_attach_one_process(struct proc *p, struct pmc *pm);
185 static int pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
187 static int pmc_can_attach(struct pmc *pm, struct proc *p);
188 static void pmc_capture_user_callchain(int cpu, int soft, struct trapframe *tf);
189 static void pmc_cleanup(void);
190 static int pmc_detach_process(struct proc *p, struct pmc *pm);
191 static int pmc_detach_one_process(struct proc *p, struct pmc *pm,
193 static void pmc_destroy_owner_descriptor(struct pmc_owner *po);
194 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
195 static int pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
196 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
198 static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
200 static void pmc_force_context_switch(void);
201 static void pmc_link_target_process(struct pmc *pm,
202 struct pmc_process *pp);
203 static void pmc_log_all_process_mappings(struct pmc_owner *po);
204 static void pmc_log_kernel_mappings(struct pmc *pm);
205 static void pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
206 static void pmc_maybe_remove_owner(struct pmc_owner *po);
207 static void pmc_process_csw_in(struct thread *td);
208 static void pmc_process_csw_out(struct thread *td);
209 static void pmc_process_exit(void *arg, struct proc *p);
210 static void pmc_process_fork(void *arg, struct proc *p1,
211 struct proc *p2, int n);
212 static void pmc_process_samples(int cpu, int soft);
213 static void pmc_release_pmc_descriptor(struct pmc *pmc);
214 static void pmc_remove_owner(struct pmc_owner *po);
215 static void pmc_remove_process_descriptor(struct pmc_process *pp);
216 static void pmc_restore_cpu_binding(struct pmc_binding *pb);
217 static void pmc_save_cpu_binding(struct pmc_binding *pb);
218 static void pmc_select_cpu(int cpu);
219 static int pmc_start(struct pmc *pm);
220 static int pmc_stop(struct pmc *pm);
221 static int pmc_syscall_handler(struct thread *td, void *syscall_args);
222 static void pmc_unlink_target_process(struct pmc *pmc,
223 struct pmc_process *pp);
224 static int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
225 static int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
226 static struct pmc_mdep *pmc_generic_cpu_initialize(void);
227 static void pmc_generic_cpu_finalize(struct pmc_mdep *md);
230 * Kernel tunables and sysctl(8) interface.
233 SYSCTL_DECL(_kern_hwpmc);
235 static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
236 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "callchaindepth", &pmc_callchaindepth);
237 SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_TUN|CTLFLAG_RD,
238 &pmc_callchaindepth, 0, "depth of call chain records");
241 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
242 char pmc_debugstr[PMC_DEBUG_STRSIZE];
243 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
244 sizeof(pmc_debugstr));
245 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
246 CTLTYPE_STRING|CTLFLAG_RW|CTLFLAG_TUN,
247 0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
251 * kern.hwpmc.hashrows -- determines the number of rows in the
252 * of the hash table used to look up threads
255 static int pmc_hashsize = PMC_HASH_SIZE;
256 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "hashsize", &pmc_hashsize);
257 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_TUN|CTLFLAG_RD,
258 &pmc_hashsize, 0, "rows in hash tables");
261 * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
264 static int pmc_nsamples = PMC_NSAMPLES;
265 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nsamples", &pmc_nsamples);
266 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_TUN|CTLFLAG_RD,
267 &pmc_nsamples, 0, "number of PC samples per CPU");
271 * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
274 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
275 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "mtxpoolsize", &pmc_mtxpool_size);
276 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_TUN|CTLFLAG_RD,
277 &pmc_mtxpool_size, 0, "size of spin mutex pool");
281 * security.bsd.unprivileged_syspmcs -- allow non-root processes to
282 * allocate system-wide PMCs.
284 * Allowing unprivileged processes to allocate system PMCs is convenient
285 * if system-wide measurements need to be taken concurrently with other
286 * per-process measurements. This feature is turned off by default.
289 static int pmc_unprivileged_syspmcs = 0;
290 TUNABLE_INT("security.bsd.unprivileged_syspmcs", &pmc_unprivileged_syspmcs);
291 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RW,
292 &pmc_unprivileged_syspmcs, 0,
293 "allow unprivileged process to allocate system PMCs");
296 * Hash function. Discard the lower 2 bits of the pointer since
297 * these are always zero for our uses. The hash multiplier is
298 * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
302 #define _PMC_HM 11400714819323198486u
304 #define _PMC_HM 2654435769u
306 #error Must know the size of 'long' to compile
309 #define PMC_HASH_PTR(P,M) ((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
315 /* The `sysent' for the new syscall */
316 static struct sysent pmc_sysent = {
318 pmc_syscall_handler /* sy_call */
321 static struct syscall_module_data pmc_syscall_mod = {
329 static moduledata_t pmc_mod = {
331 syscall_module_handler,
335 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
336 MODULE_VERSION(pmc, PMC_VERSION);
339 enum pmc_dbgparse_state {
340 PMCDS_WS, /* in whitespace */
341 PMCDS_MAJOR, /* seen a major keyword */
346 pmc_debugflags_parse(char *newstr, char *fence)
349 struct pmc_debugflags *tmpflags;
350 int error, found, *newbits, tmp;
353 tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK|M_ZERO);
358 for (; p < fence && (c = *p); p++) {
360 /* skip white space */
361 if (c == ' ' || c == '\t')
364 /* look for a keyword followed by "=" */
365 for (q = p; p < fence && (c = *p) && c != '='; p++)
375 /* lookup flag group name */
376 #define DBG_SET_FLAG_MAJ(S,F) \
377 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
378 newbits = &tmpflags->pdb_ ## F;
380 DBG_SET_FLAG_MAJ("cpu", CPU);
381 DBG_SET_FLAG_MAJ("csw", CSW);
382 DBG_SET_FLAG_MAJ("logging", LOG);
383 DBG_SET_FLAG_MAJ("module", MOD);
384 DBG_SET_FLAG_MAJ("md", MDP);
385 DBG_SET_FLAG_MAJ("owner", OWN);
386 DBG_SET_FLAG_MAJ("pmc", PMC);
387 DBG_SET_FLAG_MAJ("process", PRC);
388 DBG_SET_FLAG_MAJ("sampling", SAM);
390 if (newbits == NULL) {
395 p++; /* skip the '=' */
397 /* Now parse the individual flags */
400 for (q = p; p < fence && (c = *p); p++)
401 if (c == ' ' || c == '\t' || c == ',')
404 /* p == fence or c == ws or c == "," or c == 0 */
406 if ((kwlen = p - q) == 0) {
412 #define DBG_SET_FLAG_MIN(S,F) \
413 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
414 tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
416 /* a '*' denotes all possible flags in the group */
417 if (kwlen == 1 && *q == '*')
419 /* look for individual flag names */
420 DBG_SET_FLAG_MIN("allocaterow", ALR);
421 DBG_SET_FLAG_MIN("allocate", ALL);
422 DBG_SET_FLAG_MIN("attach", ATT);
423 DBG_SET_FLAG_MIN("bind", BND);
424 DBG_SET_FLAG_MIN("config", CFG);
425 DBG_SET_FLAG_MIN("exec", EXC);
426 DBG_SET_FLAG_MIN("exit", EXT);
427 DBG_SET_FLAG_MIN("find", FND);
428 DBG_SET_FLAG_MIN("flush", FLS);
429 DBG_SET_FLAG_MIN("fork", FRK);
430 DBG_SET_FLAG_MIN("getbuf", GTB);
431 DBG_SET_FLAG_MIN("hook", PMH);
432 DBG_SET_FLAG_MIN("init", INI);
433 DBG_SET_FLAG_MIN("intr", INT);
434 DBG_SET_FLAG_MIN("linktarget", TLK);
435 DBG_SET_FLAG_MIN("mayberemove", OMR);
436 DBG_SET_FLAG_MIN("ops", OPS);
437 DBG_SET_FLAG_MIN("read", REA);
438 DBG_SET_FLAG_MIN("register", REG);
439 DBG_SET_FLAG_MIN("release", REL);
440 DBG_SET_FLAG_MIN("remove", ORM);
441 DBG_SET_FLAG_MIN("sample", SAM);
442 DBG_SET_FLAG_MIN("scheduleio", SIO);
443 DBG_SET_FLAG_MIN("select", SEL);
444 DBG_SET_FLAG_MIN("signal", SIG);
445 DBG_SET_FLAG_MIN("swi", SWI);
446 DBG_SET_FLAG_MIN("swo", SWO);
447 DBG_SET_FLAG_MIN("start", STA);
448 DBG_SET_FLAG_MIN("stop", STO);
449 DBG_SET_FLAG_MIN("syscall", PMS);
450 DBG_SET_FLAG_MIN("unlinktarget", TUL);
451 DBG_SET_FLAG_MIN("write", WRI);
453 /* unrecognized flag name */
458 if (c == 0 || c == ' ' || c == '\t') { /* end of flag group */
467 /* save the new flag set */
468 bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
471 free(tmpflags, M_PMC);
476 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
478 char *fence, *newstr;
482 (void) arg1; (void) arg2; /* unused parameters */
484 n = sizeof(pmc_debugstr);
485 newstr = malloc(n, M_PMC, M_WAITOK|M_ZERO);
486 (void) strlcpy(newstr, pmc_debugstr, n);
488 error = sysctl_handle_string(oidp, newstr, n, req);
490 /* if there is a new string, parse and copy it */
491 if (error == 0 && req->newptr != NULL) {
492 fence = newstr + (n < req->newlen ? n : req->newlen + 1);
493 if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
494 (void) strlcpy(pmc_debugstr, newstr,
495 sizeof(pmc_debugstr));
505 * Map a row index to a classdep structure and return the adjusted row
506 * index for the PMC class index.
508 static struct pmc_classdep *
509 pmc_ri_to_classdep(struct pmc_mdep *md, int ri, int *adjri)
511 struct pmc_classdep *pcd;
515 KASSERT(ri >= 0 && ri < md->pmd_npmc,
516 ("[pmc,%d] illegal row-index %d", __LINE__, ri));
518 pcd = pmc_rowindex_to_classdep[ri];
521 ("[pmc,%d] ri %d null pcd", __LINE__, ri));
523 *adjri = ri - pcd->pcd_ri;
525 KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
526 ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));
532 * Concurrency Control
534 * The driver manages the following data structures:
536 * - target process descriptors, one per target process
537 * - owner process descriptors (and attached lists), one per owner process
538 * - lookup hash tables for owner and target processes
539 * - PMC descriptors (and attached lists)
540 * - per-cpu hardware state
541 * - the 'hook' variable through which the kernel calls into
543 * - the machine hardware state (managed by the MD layer)
545 * These data structures are accessed from:
547 * - thread context-switch code
548 * - interrupt handlers (possibly on multiple cpus)
549 * - kernel threads on multiple cpus running on behalf of user
550 * processes doing system calls
551 * - this driver's private kernel threads
553 * = Locks and Locking strategy =
555 * The driver uses four locking strategies for its operation:
557 * - The global SX lock "pmc_sx" is used to protect internal
560 * Calls into the module by syscall() start with this lock being
561 * held in exclusive mode. Depending on the requested operation,
562 * the lock may be downgraded to 'shared' mode to allow more
563 * concurrent readers into the module. Calls into the module from
564 * other parts of the kernel acquire the lock in shared mode.
566 * This SX lock is held in exclusive mode for any operations that
567 * modify the linkages between the driver's internal data structures.
569 * The 'pmc_hook' function pointer is also protected by this lock.
570 * It is only examined with the sx lock held in exclusive mode. The
571 * kernel module is allowed to be unloaded only with the sx lock held
572 * in exclusive mode. In normal syscall handling, after acquiring the
573 * pmc_sx lock we first check that 'pmc_hook' is non-null before
574 * proceeding. This prevents races between the thread unloading the module
575 * and other threads seeking to use the module.
577 * - Lookups of target process structures and owner process structures
578 * cannot use the global "pmc_sx" SX lock because these lookups need
579 * to happen during context switches and in other critical sections
580 * where sleeping is not allowed. We protect these lookup tables
581 * with their own private spin-mutexes, "pmc_processhash_mtx" and
582 * "pmc_ownerhash_mtx".
584 * - Interrupt handlers work in a lock free manner. At interrupt
585 * time, handlers look at the PMC pointer (phw->phw_pmc) configured
586 * when the PMC was started. If this pointer is NULL, the interrupt
587 * is ignored after updating driver statistics. We ensure that this
588 * pointer is set (using an atomic operation if necessary) before the
589 * PMC hardware is started. Conversely, this pointer is unset atomically
590 * only after the PMC hardware is stopped.
592 * We ensure that everything needed for the operation of an
593 * interrupt handler is available without it needing to acquire any
594 * locks. We also ensure that a PMC's software state is destroyed only
595 * after the PMC is taken off hardware (on all CPUs).
597 * - Context-switch handling with process-private PMCs needs more
600 * A given process may be the target of multiple PMCs. For example,
601 * PMCATTACH and PMCDETACH may be requested by a process on one CPU
602 * while the target process is running on another. A PMC could also
603 * be getting released because its owner is exiting. We tackle
604 * these situations in the following manner:
606 * - each target process structure 'pmc_process' has an array
607 * of 'struct pmc *' pointers, one for each hardware PMC.
609 * - At context switch IN time, each "target" PMC in RUNNING state
610 * gets started on hardware and a pointer to each PMC is copied into
611 * the per-cpu phw array. The 'runcount' for the PMC is
614 * - At context switch OUT time, all process-virtual PMCs are stopped
615 * on hardware. The saved value is added to the PMCs value field
616 * only if the PMC is in a non-deleted state (the PMCs state could
617 * have changed during the current time slice).
619 * Note that since in-between a switch IN on a processor and a switch
620 * OUT, the PMC could have been released on another CPU. Therefore
621 * context switch OUT always looks at the hardware state to turn
622 * OFF PMCs and will update a PMC's saved value only if reachable
623 * from the target process record.
625 * - OP PMCRELEASE could be called on a PMC at any time (the PMC could
626 * be attached to many processes at the time of the call and could
627 * be active on multiple CPUs).
629 * We prevent further scheduling of the PMC by marking it as in
630 * state 'DELETED'. If the runcount of the PMC is non-zero then
631 * this PMC is currently running on a CPU somewhere. The thread
632 * doing the PMCRELEASE operation waits by repeatedly doing a
633 * pause() till the runcount comes to zero.
635 * The contents of a PMC descriptor (struct pmc) are protected using
636 * a spin-mutex. In order to save space, we use a mutex pool.
638 * In terms of lock types used by witness(4), we use:
639 * - Type "pmc-sx", used by the global SX lock.
640 * - Type "pmc-sleep", for sleep mutexes used by logger threads.
641 * - Type "pmc-per-proc", for protecting PMC owner descriptors.
642 * - Type "pmc-leaf", used for all other spin mutexes.
646 * save the cpu binding of the current kthread
650 pmc_save_cpu_binding(struct pmc_binding *pb)
652 PMCDBG(CPU,BND,2, "%s", "save-cpu");
653 thread_lock(curthread);
654 pb->pb_bound = sched_is_bound(curthread);
655 pb->pb_cpu = curthread->td_oncpu;
656 thread_unlock(curthread);
657 PMCDBG(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
661 * restore the cpu binding of the current thread
665 pmc_restore_cpu_binding(struct pmc_binding *pb)
667 PMCDBG(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
668 curthread->td_oncpu, pb->pb_cpu);
669 thread_lock(curthread);
671 sched_bind(curthread, pb->pb_cpu);
673 sched_unbind(curthread);
674 thread_unlock(curthread);
675 PMCDBG(CPU,BND,2, "%s", "restore-cpu done");
679 * move execution over the specified cpu and bind it there.
683 pmc_select_cpu(int cpu)
685 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
686 ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
688 /* Never move to an inactive CPU. */
689 KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
690 "CPU %d", __LINE__, cpu));
692 PMCDBG(CPU,SEL,2, "select-cpu cpu=%d", cpu);
693 thread_lock(curthread);
694 sched_bind(curthread, cpu);
695 thread_unlock(curthread);
697 KASSERT(curthread->td_oncpu == cpu,
698 ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
699 cpu, curthread->td_oncpu));
701 PMCDBG(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
705 * Force a context switch.
707 * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
708 * guaranteed to force a context switch.
712 pmc_force_context_switch(void)
719 * Get the file name for an executable. This is a simple wrapper
720 * around vn_fullpath(9).
724 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
727 *fullpath = "unknown";
729 vn_fullpath(curthread, v, fullpath, freepath);
733 * remove an process owning PMCs
737 pmc_remove_owner(struct pmc_owner *po)
739 struct pmc *pm, *tmp;
741 sx_assert(&pmc_sx, SX_XLOCKED);
743 PMCDBG(OWN,ORM,1, "remove-owner po=%p", po);
745 /* Remove descriptor from the owner hash table */
746 LIST_REMOVE(po, po_next);
748 /* release all owned PMC descriptors */
749 LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
750 PMCDBG(OWN,ORM,2, "pmc=%p", pm);
751 KASSERT(pm->pm_owner == po,
752 ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
754 pmc_release_pmc_descriptor(pm); /* will unlink from the list */
757 KASSERT(po->po_sscount == 0,
758 ("[pmc,%d] SS count not zero", __LINE__));
759 KASSERT(LIST_EMPTY(&po->po_pmcs),
760 ("[pmc,%d] PMC list not empty", __LINE__));
762 /* de-configure the log file if present */
763 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
764 pmclog_deconfigure_log(po);
768 * remove an owner process record if all conditions are met.
772 pmc_maybe_remove_owner(struct pmc_owner *po)
775 PMCDBG(OWN,OMR,1, "maybe-remove-owner po=%p", po);
778 * Remove owner record if
779 * - this process does not own any PMCs
780 * - this process has not allocated a system-wide sampling buffer
783 if (LIST_EMPTY(&po->po_pmcs) &&
784 ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
785 pmc_remove_owner(po);
786 pmc_destroy_owner_descriptor(po);
791 * Add an association between a target process and a PMC.
795 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
798 struct pmc_target *pt;
800 sx_assert(&pmc_sx, SX_XLOCKED);
802 KASSERT(pm != NULL && pp != NULL,
803 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
804 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
805 ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
806 __LINE__, pm, pp->pp_proc->p_pid));
807 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1),
808 ("[pmc,%d] Illegal reference count %d for process record %p",
809 __LINE__, pp->pp_refcnt, (void *) pp));
811 ri = PMC_TO_ROWINDEX(pm);
813 PMCDBG(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
817 LIST_FOREACH(pt, &pm->pm_targets, pt_next)
818 if (pt->pt_process == pp)
819 KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
823 pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK|M_ZERO);
826 LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
828 atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
831 if (pm->pm_owner->po_owner == pp->pp_proc)
832 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
835 * Initialize the per-process values at this row index.
837 pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
838 pm->pm_sc.pm_reloadcount : 0;
845 * Removes the association between a target process and a PMC.
849 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
853 struct pmc_target *ptgt;
855 sx_assert(&pmc_sx, SX_XLOCKED);
857 KASSERT(pm != NULL && pp != NULL,
858 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
860 KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc,
861 ("[pmc,%d] Illegal ref count %d on process record %p",
862 __LINE__, pp->pp_refcnt, (void *) pp));
864 ri = PMC_TO_ROWINDEX(pm);
866 PMCDBG(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
869 KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
870 ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
871 ri, pm, pp->pp_pmcs[ri].pp_pmc));
873 pp->pp_pmcs[ri].pp_pmc = NULL;
874 pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
876 /* Remove owner-specific flags */
877 if (pm->pm_owner->po_owner == pp->pp_proc) {
878 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
879 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
884 /* Remove the target process from the PMC structure */
885 LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
886 if (ptgt->pt_process == pp)
889 KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
890 "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
892 LIST_REMOVE(ptgt, pt_next);
895 /* if the PMC now lacks targets, send the owner a SIGIO */
896 if (LIST_EMPTY(&pm->pm_targets)) {
897 p = pm->pm_owner->po_owner;
899 kern_psignal(p, SIGIO);
902 PMCDBG(PRC,SIG,2, "signalling proc=%p signal=%d", p,
908 * Check if PMC 'pm' may be attached to target process 't'.
912 pmc_can_attach(struct pmc *pm, struct proc *t)
914 struct proc *o; /* pmc owner */
915 struct ucred *oc, *tc; /* owner, target credentials */
916 int decline_attach, i;
919 * A PMC's owner can always attach that PMC to itself.
922 if ((o = pm->pm_owner->po_owner) == t)
936 * The effective uid of the PMC owner should match at least one
937 * of the {effective,real,saved} uids of the target process.
940 decline_attach = oc->cr_uid != tc->cr_uid &&
941 oc->cr_uid != tc->cr_svuid &&
942 oc->cr_uid != tc->cr_ruid;
945 * Every one of the target's group ids, must be in the owner's
948 for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
949 decline_attach = !groupmember(tc->cr_groups[i], oc);
951 /* check the read and saved gids too */
952 if (decline_attach == 0)
953 decline_attach = !groupmember(tc->cr_rgid, oc) ||
954 !groupmember(tc->cr_svgid, oc);
959 return !decline_attach;
963 * Attach a process to a PMC.
967 pmc_attach_one_process(struct proc *p, struct pmc *pm)
970 char *fullpath, *freepath;
971 struct pmc_process *pp;
973 sx_assert(&pmc_sx, SX_XLOCKED);
975 PMCDBG(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
976 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
979 * Locate the process descriptor corresponding to process 'p',
980 * allocating space as needed.
982 * Verify that rowindex 'pm_rowindex' is free in the process
985 * If not, allocate space for a descriptor and link the
986 * process descriptor and PMC.
988 ri = PMC_TO_ROWINDEX(pm);
990 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
993 if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
996 if (pp->pp_pmcs[ri].pp_pmc != NULL)
999 pmc_link_target_process(pm, pp);
1001 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
1002 (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
1003 pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
1005 pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
1007 /* issue an attach event to a configured log file */
1008 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
1009 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1010 if (p->p_flag & P_KTHREAD) {
1011 fullpath = kernelname;
1014 pmclog_process_pmcattach(pm, p->p_pid, fullpath);
1016 free(freepath, M_TEMP);
1017 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1018 pmc_log_process_mappings(pm->pm_owner, p);
1020 /* mark process as using HWPMCs */
1022 p->p_flag |= P_HWPMC;
1029 * Attach a process and optionally its children
1033 pmc_attach_process(struct proc *p, struct pmc *pm)
1038 sx_assert(&pmc_sx, SX_XLOCKED);
1040 PMCDBG(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1041 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1045 * If this PMC successfully allowed a GETMSR operation
1046 * in the past, disallow further ATTACHes.
1049 if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1052 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1053 return pmc_attach_one_process(p, pm);
1056 * Traverse all child processes, attaching them to
1060 sx_slock(&proctree_lock);
1065 if ((error = pmc_attach_one_process(p, pm)) != 0)
1067 if (!LIST_EMPTY(&p->p_children))
1068 p = LIST_FIRST(&p->p_children);
1072 if (LIST_NEXT(p, p_sibling)) {
1073 p = LIST_NEXT(p, p_sibling);
1081 (void) pmc_detach_process(top, pm);
1084 sx_sunlock(&proctree_lock);
1089 * Detach a process from a PMC. If there are no other PMCs tracking
1090 * this process, remove the process structure from its hash table. If
1091 * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1095 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1098 struct pmc_process *pp;
1100 sx_assert(&pmc_sx, SX_XLOCKED);
1103 ("[pmc,%d] null pm pointer", __LINE__));
1105 ri = PMC_TO_ROWINDEX(pm);
1107 PMCDBG(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1108 pm, ri, p, p->p_pid, p->p_comm, flags);
1110 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1113 if (pp->pp_pmcs[ri].pp_pmc != pm)
1116 pmc_unlink_target_process(pm, pp);
1118 /* Issue a detach entry if a log file is configured */
1119 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1120 pmclog_process_pmcdetach(pm, p->p_pid);
1123 * If there are no PMCs targetting this process, we remove its
1124 * descriptor from the target hash table and unset the P_HWPMC
1125 * flag in the struct proc.
1127 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1128 ("[pmc,%d] Illegal refcnt %d for process struct %p",
1129 __LINE__, pp->pp_refcnt, pp));
1131 if (pp->pp_refcnt != 0) /* still a target of some PMC */
1134 pmc_remove_process_descriptor(pp);
1136 if (flags & PMC_FLAG_REMOVE)
1140 p->p_flag &= ~P_HWPMC;
1147 * Detach a process and optionally its descendants from a PMC.
1151 pmc_detach_process(struct proc *p, struct pmc *pm)
1155 sx_assert(&pmc_sx, SX_XLOCKED);
1157 PMCDBG(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1158 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1160 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1161 return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1164 * Traverse all children, detaching them from this PMC. We
1165 * ignore errors since we could be detaching a PMC from a
1166 * partially attached proc tree.
1169 sx_slock(&proctree_lock);
1174 (void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1176 if (!LIST_EMPTY(&p->p_children))
1177 p = LIST_FIRST(&p->p_children);
1181 if (LIST_NEXT(p, p_sibling)) {
1182 p = LIST_NEXT(p, p_sibling);
1190 sx_sunlock(&proctree_lock);
1192 if (LIST_EMPTY(&pm->pm_targets))
1193 pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1200 * Thread context switch IN
1204 pmc_process_csw_in(struct thread *td)
1207 unsigned int adjri, ri;
1212 pmc_value_t newvalue;
1213 struct pmc_process *pp;
1214 struct pmc_classdep *pcd;
1218 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1221 KASSERT(pp->pp_proc == td->td_proc,
1222 ("[pmc,%d] not my thread state", __LINE__));
1224 critical_enter(); /* no preemption from this point */
1226 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1228 PMCDBG(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1229 p->p_pid, p->p_comm, pp);
1231 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1232 ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
1236 for (ri = 0; ri < md->pmd_npmc; ri++) {
1238 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1241 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1242 ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1243 __LINE__, PMC_TO_MODE(pm)));
1245 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1246 ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1247 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1250 * Only PMCs that are marked as 'RUNNING' need
1251 * be placed on hardware.
1254 if (pm->pm_state != PMC_STATE_RUNNING)
1257 /* increment PMC runcount */
1258 atomic_add_rel_int(&pm->pm_runcount, 1);
1260 /* configure the HWPMC we are going to use. */
1261 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1262 pcd->pcd_config_pmc(cpu, adjri, pm);
1264 phw = pc->pc_hwpmcs[ri];
1266 KASSERT(phw != NULL,
1267 ("[pmc,%d] null hw pointer", __LINE__));
1269 KASSERT(phw->phw_pmc == pm,
1270 ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1274 * Write out saved value and start the PMC.
1276 * Sampling PMCs use a per-process value, while
1277 * counting mode PMCs use a per-pmc value that is
1278 * inherited across descendants.
1280 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1281 mtx_pool_lock_spin(pmc_mtxpool, pm);
1282 newvalue = PMC_PCPU_SAVED(cpu,ri) =
1283 pp->pp_pmcs[ri].pp_pmcval;
1284 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1286 KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1287 ("[pmc,%d] illegal mode=%d", __LINE__,
1289 mtx_pool_lock_spin(pmc_mtxpool, pm);
1290 newvalue = PMC_PCPU_SAVED(cpu, ri) =
1291 pm->pm_gv.pm_savedvalue;
1292 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1295 PMCDBG(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1297 pcd->pcd_write_pmc(cpu, adjri, newvalue);
1298 pcd->pcd_start_pmc(cpu, adjri);
1302 * perform any other architecture/cpu dependent thread
1303 * switch-in actions.
1306 (void) (*md->pmd_switch_in)(pc, pp);
1313 * Thread context switch OUT.
1317 pmc_process_csw_out(struct thread *td)
1325 pmc_value_t newvalue;
1326 unsigned int adjri, ri;
1327 struct pmc_process *pp;
1328 struct pmc_classdep *pcd;
1332 * Locate our process descriptor; this may be NULL if
1333 * this process is exiting and we have already removed
1334 * the process from the target process table.
1336 * Note that due to kernel preemption, multiple
1337 * context switches may happen while the process is
1340 * Note also that if the target process cannot be
1341 * found we still need to deconfigure any PMCs that
1342 * are currently running on hardware.
1346 pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1354 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1356 PMCDBG(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1357 p->p_pid, p->p_comm, pp);
1359 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1360 ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1365 * When a PMC gets unlinked from a target PMC, it will
1366 * be removed from the target's pp_pmc[] array.
1368 * However, on a MP system, the target could have been
1369 * executing on another CPU at the time of the unlink.
1370 * So, at context switch OUT time, we need to look at
1371 * the hardware to determine if a PMC is scheduled on
1375 for (ri = 0; ri < md->pmd_npmc; ri++) {
1377 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1379 (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
1381 if (pm == NULL) /* nothing at this row index */
1384 mode = PMC_TO_MODE(pm);
1385 if (!PMC_IS_VIRTUAL_MODE(mode))
1386 continue; /* not a process virtual PMC */
1388 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1389 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1390 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1392 /* Stop hardware if not already stopped */
1393 if (pm->pm_stalled == 0)
1394 pcd->pcd_stop_pmc(cpu, adjri);
1396 /* reduce this PMC's runcount */
1397 atomic_subtract_rel_int(&pm->pm_runcount, 1);
1400 * If this PMC is associated with this process,
1404 if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1406 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1407 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1408 pm, ri, pp->pp_pmcs[ri].pp_pmc));
1410 KASSERT(pp->pp_refcnt > 0,
1411 ("[pmc,%d] pp refcnt = %d", __LINE__,
1414 pcd->pcd_read_pmc(cpu, adjri, &newvalue);
1416 tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1418 PMCDBG(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
1421 if (mode == PMC_MODE_TS) {
1424 * For sampling process-virtual PMCs,
1425 * we expect the count to be
1426 * decreasing as the 'value'
1427 * programmed into the PMC is the
1428 * number of events to be seen till
1429 * the next sampling interrupt.
1432 tmp += pm->pm_sc.pm_reloadcount;
1433 mtx_pool_lock_spin(pmc_mtxpool, pm);
1434 pp->pp_pmcs[ri].pp_pmcval -= tmp;
1435 if ((int64_t) pp->pp_pmcs[ri].pp_pmcval < 0)
1436 pp->pp_pmcs[ri].pp_pmcval +=
1437 pm->pm_sc.pm_reloadcount;
1438 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1443 * For counting process-virtual PMCs,
1444 * we expect the count to be
1445 * increasing monotonically, modulo a 64
1448 KASSERT((int64_t) tmp >= 0,
1449 ("[pmc,%d] negative increment cpu=%d "
1450 "ri=%d newvalue=%jx saved=%jx "
1451 "incr=%jx", __LINE__, cpu, ri,
1452 newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1454 mtx_pool_lock_spin(pmc_mtxpool, pm);
1455 pm->pm_gv.pm_savedvalue += tmp;
1456 pp->pp_pmcs[ri].pp_pmcval += tmp;
1457 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1459 if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1460 pmclog_process_proccsw(pm, pp, tmp);
1464 /* mark hardware as free */
1465 pcd->pcd_config_pmc(cpu, adjri, NULL);
1469 * perform any other architecture/cpu dependent thread
1470 * switch out functions.
1473 (void) (*md->pmd_switch_out)(pc, pp);
1479 * A mapping change for a process.
1483 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1487 char *fullpath, *freepath;
1488 const struct pmc *pm;
1489 struct pmc_owner *po;
1490 const struct pmc_process *pp;
1492 freepath = fullpath = NULL;
1493 pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1495 pid = td->td_proc->p_pid;
1497 /* Inform owners of all system-wide sampling PMCs. */
1498 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1499 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1500 pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1502 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1506 * Inform sampling PMC owners tracking this process.
1508 for (ri = 0; ri < md->pmd_npmc; ri++)
1509 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1510 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1511 pmclog_process_map_in(pm->pm_owner,
1512 pid, pkm->pm_address, fullpath);
1516 free(freepath, M_TEMP);
1521 * Log an munmap request.
1525 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1529 struct pmc_owner *po;
1530 const struct pmc *pm;
1531 const struct pmc_process *pp;
1533 pid = td->td_proc->p_pid;
1535 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1536 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1537 pmclog_process_map_out(po, pid, pkm->pm_address,
1538 pkm->pm_address + pkm->pm_size);
1540 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1543 for (ri = 0; ri < md->pmd_npmc; ri++)
1544 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1545 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1546 pmclog_process_map_out(pm->pm_owner, pid,
1547 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1551 * Log mapping information about the kernel.
1555 pmc_log_kernel_mappings(struct pmc *pm)
1557 struct pmc_owner *po;
1558 struct pmckern_map_in *km, *kmbase;
1560 sx_assert(&pmc_sx, SX_LOCKED);
1561 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1562 ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1563 __LINE__, (void *) pm));
1567 if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1571 * Log the current set of kernel modules.
1573 kmbase = linker_hwpmc_list_objects();
1574 for (km = kmbase; km->pm_file != NULL; km++) {
1575 PMCDBG(LOG,REG,1,"%s %p", (char *) km->pm_file,
1576 (void *) km->pm_address);
1577 pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1580 free(kmbase, M_LINKER);
1582 po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1586 * Log the mappings for a single process.
1590 pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1596 vm_map_entry_t entry;
1597 vm_offset_t last_end;
1598 u_int last_timestamp;
1599 struct vnode *last_vp;
1600 vm_offset_t start_addr;
1601 vm_object_t obj, lobj, tobj;
1602 char *fullpath, *freepath;
1605 last_end = (vm_offset_t) 0;
1606 fullpath = freepath = NULL;
1608 if ((vm = vmspace_acquire_ref(p)) == NULL)
1612 vm_map_lock_read(map);
1614 for (entry = map->header.next; entry != &map->header; entry = entry->next) {
1616 if (entry == NULL) {
1617 PMCDBG(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly "
1618 "NULL! pid=%d vm_map=%p\n", p->p_pid, map);
1623 * We only care about executable map entries.
1625 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) ||
1626 !(entry->protection & VM_PROT_EXECUTE) ||
1627 (entry->object.vm_object == NULL)) {
1631 obj = entry->object.vm_object;
1632 VM_OBJECT_LOCK(obj);
1635 * Walk the backing_object list to find the base
1636 * (non-shadowed) vm_object.
1638 for (lobj = tobj = obj; tobj != NULL; tobj = tobj->backing_object) {
1640 VM_OBJECT_LOCK(tobj);
1642 VM_OBJECT_UNLOCK(lobj);
1647 * At this point lobj is the base vm_object and it is locked.
1650 PMCDBG(LOG,OPS,2, "hwpmc: lobj unexpectedly NULL! pid=%d "
1651 "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj);
1652 VM_OBJECT_UNLOCK(obj);
1656 if (lobj->type != OBJT_VNODE || lobj->handle == NULL) {
1658 VM_OBJECT_UNLOCK(lobj);
1659 VM_OBJECT_UNLOCK(obj);
1664 * Skip contiguous regions that point to the same
1665 * vnode, so we don't emit redundant MAP-IN
1668 if (entry->start == last_end && lobj->handle == last_vp) {
1669 last_end = entry->end;
1671 VM_OBJECT_UNLOCK(lobj);
1672 VM_OBJECT_UNLOCK(obj);
1677 * We don't want to keep the proc's vm_map or this
1678 * vm_object locked while we walk the pathname, since
1679 * vn_fullpath() can sleep. However, if we drop the
1680 * lock, it's possible for concurrent activity to
1681 * modify the vm_map list. To protect against this,
1682 * we save the vm_map timestamp before we release the
1683 * lock, and check it after we reacquire the lock
1686 start_addr = entry->start;
1687 last_end = entry->end;
1688 last_timestamp = map->timestamp;
1689 vm_map_unlock_read(map);
1694 VM_OBJECT_UNLOCK(lobj);
1696 VM_OBJECT_UNLOCK(obj);
1699 pmc_getfilename(vp, &fullpath, &freepath);
1702 locked = VFS_LOCK_GIANT(vp->v_mount);
1704 VFS_UNLOCK_GIANT(locked);
1707 pmclog_process_map_in(po, p->p_pid, start_addr, fullpath);
1709 free(freepath, M_TEMP);
1711 vm_map_lock_read(map);
1714 * If our saved timestamp doesn't match, this means
1715 * that the vm_map was modified out from under us and
1716 * we can't trust our current "entry" pointer. Do a
1717 * new lookup for this entry. If there is no entry
1718 * for this address range, vm_map_lookup_entry() will
1719 * return the previous one, so we always want to go to
1720 * entry->next on the next loop iteration.
1722 * There is an edge condition here that can occur if
1723 * there is no entry at or before this address. In
1724 * this situation, vm_map_lookup_entry returns
1725 * &map->header, which would cause our loop to abort
1726 * without processing the rest of the map. However,
1727 * in practice this will never happen for process
1728 * vm_map. This is because the executable's text
1729 * segment is the first mapping in the proc's address
1730 * space, and this mapping is never removed until the
1731 * process exits, so there will always be a non-header
1732 * entry at or before the requested address for
1733 * vm_map_lookup_entry to return.
1735 if (map->timestamp != last_timestamp)
1736 vm_map_lookup_entry(map, last_end - 1, &entry);
1739 vm_map_unlock_read(map);
1745 * Log mappings for all processes in the system.
1749 pmc_log_all_process_mappings(struct pmc_owner *po)
1751 struct proc *p, *top;
1753 sx_assert(&pmc_sx, SX_XLOCKED);
1755 if ((p = pfind(1)) == NULL)
1756 panic("[pmc,%d] Cannot find init", __LINE__);
1760 sx_slock(&proctree_lock);
1765 pmc_log_process_mappings(po, p);
1766 if (!LIST_EMPTY(&p->p_children))
1767 p = LIST_FIRST(&p->p_children);
1771 if (LIST_NEXT(p, p_sibling)) {
1772 p = LIST_NEXT(p, p_sibling);
1779 sx_sunlock(&proctree_lock);
1783 * The 'hook' invoked from the kernel proper
1788 const char *pmc_hooknames[] = {
1789 /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1806 pmc_hook_handler(struct thread *td, int function, void *arg)
1809 PMCDBG(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1810 pmc_hooknames[function], arg);
1819 case PMC_FN_PROCESS_EXEC:
1821 char *fullpath, *freepath;
1823 int is_using_hwpmcs;
1826 struct pmc_owner *po;
1827 struct pmc_process *pp;
1828 struct pmckern_procexec *pk;
1830 sx_assert(&pmc_sx, SX_XLOCKED);
1833 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1835 pk = (struct pmckern_procexec *) arg;
1837 /* Inform owners of SS mode PMCs of the exec event. */
1838 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1839 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1840 pmclog_process_procexec(po, PMC_ID_INVALID,
1841 p->p_pid, pk->pm_entryaddr, fullpath);
1844 is_using_hwpmcs = p->p_flag & P_HWPMC;
1847 if (!is_using_hwpmcs) {
1849 free(freepath, M_TEMP);
1854 * PMCs are not inherited across an exec(): remove any
1855 * PMCs that this process is the owner of.
1858 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1859 pmc_remove_owner(po);
1860 pmc_destroy_owner_descriptor(po);
1864 * If the process being exec'ed is not the target of any
1867 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1869 free(freepath, M_TEMP);
1874 * Log the exec event to all monitoring owners. Skip
1875 * owners who have already recieved the event because
1876 * they had system sampling PMCs active.
1878 for (ri = 0; ri < md->pmd_npmc; ri++)
1879 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1881 if (po->po_sscount == 0 &&
1882 po->po_flags & PMC_PO_OWNS_LOGFILE)
1883 pmclog_process_procexec(po, pm->pm_id,
1884 p->p_pid, pk->pm_entryaddr,
1889 free(freepath, M_TEMP);
1892 PMCDBG(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1893 p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1895 if (pk->pm_credentialschanged == 0) /* no change */
1899 * If the newly exec()'ed process has a different credential
1900 * than before, allow it to be the target of a PMC only if
1901 * the PMC's owner has sufficient priviledge.
1904 for (ri = 0; ri < md->pmd_npmc; ri++)
1905 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1906 if (pmc_can_attach(pm, td->td_proc) != 0)
1907 pmc_detach_one_process(td->td_proc,
1910 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1911 ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1912 pp->pp_refcnt, pp));
1915 * If this process is no longer the target of any
1916 * PMCs, we can remove the process entry and free
1920 if (pp->pp_refcnt == 0) {
1921 pmc_remove_process_descriptor(pp);
1930 pmc_process_csw_in(td);
1933 case PMC_FN_CSW_OUT:
1934 pmc_process_csw_out(td);
1938 * Process accumulated PC samples.
1940 * This function is expected to be called by hardclock() for
1941 * each CPU that has accumulated PC samples.
1943 * This function is to be executed on the CPU whose samples
1944 * are being processed.
1946 case PMC_FN_DO_SAMPLES:
1949 * Clear the cpu specific bit in the CPU mask before
1950 * do the rest of the processing. If the NMI handler
1951 * gets invoked after the "atomic_clear_int()" call
1952 * below but before "pmc_process_samples()" gets
1953 * around to processing the interrupt, then we will
1954 * come back here at the next hardclock() tick (and
1955 * may find nothing to do if "pmc_process_samples()"
1956 * had already processed the interrupt). We don't
1957 * lose the interrupt sample.
1959 CPU_CLR_ATOMIC(PCPU_GET(cpuid), &pmc_cpumask);
1960 pmc_process_samples(PCPU_GET(cpuid), PMC_HR);
1961 pmc_process_samples(PCPU_GET(cpuid), PMC_SR);
1965 sx_assert(&pmc_sx, SX_LOCKED);
1966 pmc_process_mmap(td, (struct pmckern_map_in *) arg);
1970 sx_assert(&pmc_sx, SX_LOCKED);
1971 pmc_process_munmap(td, (struct pmckern_map_out *) arg);
1974 case PMC_FN_USER_CALLCHAIN:
1976 * Record a call chain.
1978 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
1981 pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
1982 (struct trapframe *) arg);
1983 td->td_pflags &= ~TDP_CALLCHAIN;
1986 case PMC_FN_USER_CALLCHAIN_SOFT:
1988 * Record a call chain.
1990 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
1992 pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_SR,
1993 (struct trapframe *) arg);
1994 td->td_pflags &= ~TDP_CALLCHAIN;
1997 case PMC_FN_SOFT_SAMPLING:
1999 * Call soft PMC sampling intr.
2001 pmc_soft_intr((struct pmckern_soft *) arg);
2006 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
2016 * allocate a 'struct pmc_owner' descriptor in the owner hash table.
2019 static struct pmc_owner *
2020 pmc_allocate_owner_descriptor(struct proc *p)
2023 struct pmc_owner *po;
2024 struct pmc_ownerhash *poh;
2026 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2027 poh = &pmc_ownerhash[hindex];
2029 /* allocate space for N pointers and one descriptor struct */
2030 po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK|M_ZERO);
2031 po->po_sscount = po->po_error = po->po_flags = po->po_logprocmaps = 0;
2034 po->po_kthread = NULL;
2035 LIST_INIT(&po->po_pmcs);
2036 LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
2038 TAILQ_INIT(&po->po_logbuffers);
2039 mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
2041 PMCDBG(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
2042 p, p->p_pid, p->p_comm, po);
2048 pmc_destroy_owner_descriptor(struct pmc_owner *po)
2051 PMCDBG(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
2052 po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
2054 mtx_destroy(&po->po_mtx);
2059 * find the descriptor corresponding to process 'p', adding or removing it
2060 * as specified by 'mode'.
2063 static struct pmc_process *
2064 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
2067 struct pmc_process *pp, *ppnew;
2068 struct pmc_processhash *pph;
2070 hindex = PMC_HASH_PTR(p, pmc_processhashmask);
2071 pph = &pmc_processhash[hindex];
2076 * Pre-allocate memory in the FIND_ALLOCATE case since we
2077 * cannot call malloc(9) once we hold a spin lock.
2079 if (mode & PMC_FLAG_ALLOCATE)
2080 ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
2081 sizeof(struct pmc_targetstate), M_PMC, M_WAITOK|M_ZERO);
2083 mtx_lock_spin(&pmc_processhash_mtx);
2084 LIST_FOREACH(pp, pph, pp_next)
2085 if (pp->pp_proc == p)
2088 if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
2089 LIST_REMOVE(pp, pp_next);
2091 if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
2094 LIST_INSERT_HEAD(pph, ppnew, pp_next);
2098 mtx_unlock_spin(&pmc_processhash_mtx);
2100 if (pp != NULL && ppnew != NULL)
2107 * remove a process descriptor from the process hash table.
2111 pmc_remove_process_descriptor(struct pmc_process *pp)
2113 KASSERT(pp->pp_refcnt == 0,
2114 ("[pmc,%d] Removing process descriptor %p with count %d",
2115 __LINE__, pp, pp->pp_refcnt));
2117 mtx_lock_spin(&pmc_processhash_mtx);
2118 LIST_REMOVE(pp, pp_next);
2119 mtx_unlock_spin(&pmc_processhash_mtx);
2124 * find an owner descriptor corresponding to proc 'p'
2127 static struct pmc_owner *
2128 pmc_find_owner_descriptor(struct proc *p)
2131 struct pmc_owner *po;
2132 struct pmc_ownerhash *poh;
2134 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2135 poh = &pmc_ownerhash[hindex];
2138 LIST_FOREACH(po, poh, po_next)
2139 if (po->po_owner == p)
2142 PMCDBG(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2143 "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2149 * pmc_allocate_pmc_descriptor
2151 * Allocate a pmc descriptor and initialize its
2156 pmc_allocate_pmc_descriptor(void)
2160 pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK|M_ZERO);
2163 pmc->pm_owner = NULL;
2164 LIST_INIT(&pmc->pm_targets);
2167 PMCDBG(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2173 * Destroy a pmc descriptor.
2177 pmc_destroy_pmc_descriptor(struct pmc *pm)
2182 KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2183 pm->pm_state == PMC_STATE_FREE,
2184 ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2185 KASSERT(LIST_EMPTY(&pm->pm_targets),
2186 ("[pmc,%d] destroying pmc with targets", __LINE__));
2187 KASSERT(pm->pm_owner == NULL,
2188 ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2189 KASSERT(pm->pm_runcount == 0,
2190 ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
2196 pmc_wait_for_pmc_idle(struct pmc *pm)
2199 volatile int maxloop;
2201 maxloop = 100 * pmc_cpu_max();
2204 * Loop (with a forced context switch) till the PMC's runcount
2205 * comes down to zero.
2207 while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
2210 KASSERT(maxloop > 0,
2211 ("[pmc,%d] (ri%d, rc%d) waiting too long for "
2212 "pmc to be free", __LINE__,
2213 PMC_TO_ROWINDEX(pm), pm->pm_runcount));
2215 pmc_force_context_switch();
2220 * This function does the following things:
2222 * - detaches the PMC from hardware
2223 * - unlinks all target threads that were attached to it
2224 * - removes the PMC from its owner's list
2225 * - destroy's the PMC private mutex
2227 * Once this function completes, the given pmc pointer can be safely
2228 * FREE'd by the caller.
2232 pmc_release_pmc_descriptor(struct pmc *pm)
2236 u_int adjri, ri, cpu;
2237 struct pmc_owner *po;
2238 struct pmc_binding pb;
2239 struct pmc_process *pp;
2240 struct pmc_classdep *pcd;
2241 struct pmc_target *ptgt, *tmp;
2243 sx_assert(&pmc_sx, SX_XLOCKED);
2245 KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2247 ri = PMC_TO_ROWINDEX(pm);
2248 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2249 mode = PMC_TO_MODE(pm);
2251 PMCDBG(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2255 * First, we take the PMC off hardware.
2258 if (PMC_IS_SYSTEM_MODE(mode)) {
2261 * A system mode PMC runs on a specific CPU. Switch
2262 * to this CPU and turn hardware off.
2264 pmc_save_cpu_binding(&pb);
2266 cpu = PMC_TO_CPU(pm);
2268 pmc_select_cpu(cpu);
2270 /* switch off non-stalled CPUs */
2271 if (pm->pm_state == PMC_STATE_RUNNING &&
2272 pm->pm_stalled == 0) {
2274 phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2276 KASSERT(phw->phw_pmc == pm,
2277 ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2278 __LINE__, ri, phw->phw_pmc, pm));
2279 PMCDBG(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2282 pcd->pcd_stop_pmc(cpu, adjri);
2286 PMCDBG(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2289 pcd->pcd_config_pmc(cpu, adjri, NULL);
2292 /* adjust the global and process count of SS mode PMCs */
2293 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2296 if (po->po_sscount == 0) {
2297 atomic_subtract_rel_int(&pmc_ss_count, 1);
2298 LIST_REMOVE(po, po_ssnext);
2302 pm->pm_state = PMC_STATE_DELETED;
2304 pmc_restore_cpu_binding(&pb);
2307 * We could have references to this PMC structure in
2308 * the per-cpu sample queues. Wait for the queue to
2311 pmc_wait_for_pmc_idle(pm);
2313 } else if (PMC_IS_VIRTUAL_MODE(mode)) {
2316 * A virtual PMC could be running on multiple CPUs at
2319 * By marking its state as DELETED, we ensure that
2320 * this PMC is never further scheduled on hardware.
2322 * Then we wait till all CPUs are done with this PMC.
2324 pm->pm_state = PMC_STATE_DELETED;
2327 /* Wait for the PMCs runcount to come to zero. */
2328 pmc_wait_for_pmc_idle(pm);
2331 * At this point the PMC is off all CPUs and cannot be
2332 * freshly scheduled onto a CPU. It is now safe to
2333 * unlink all targets from this PMC. If a
2334 * process-record's refcount falls to zero, we remove
2335 * it from the hash table. The module-wide SX lock
2336 * protects us from races.
2338 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2339 pp = ptgt->pt_process;
2340 pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2342 PMCDBG(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2345 * If the target process record shows that no
2346 * PMCs are attached to it, reclaim its space.
2349 if (pp->pp_refcnt == 0) {
2350 pmc_remove_process_descriptor(pp);
2355 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2360 * Release any MD resources
2362 (void) pcd->pcd_release_pmc(cpu, adjri, pm);
2365 * Update row disposition
2368 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2369 PMC_UNMARK_ROW_STANDALONE(ri);
2371 PMC_UNMARK_ROW_THREAD(ri);
2373 /* unlink from the owner's list */
2375 LIST_REMOVE(pm, pm_next);
2376 pm->pm_owner = NULL;
2379 pmc_destroy_pmc_descriptor(pm);
2383 * Register an owner and a pmc.
2387 pmc_register_owner(struct proc *p, struct pmc *pmc)
2389 struct pmc_owner *po;
2391 sx_assert(&pmc_sx, SX_XLOCKED);
2393 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2394 if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2397 KASSERT(pmc->pm_owner == NULL,
2398 ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2401 LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2404 p->p_flag |= P_HWPMC;
2407 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2408 pmclog_process_pmcallocate(pmc);
2410 PMCDBG(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2417 * Return the current row disposition:
2419 * > 0 => PROCESS MODE
2420 * < 0 => SYSTEM MODE
2424 pmc_getrowdisp(int ri)
2426 return pmc_pmcdisp[ri];
2430 * Check if a PMC at row index 'ri' can be allocated to the current
2433 * Allocation can fail if:
2434 * - the current process is already being profiled by a PMC at index 'ri',
2435 * attached to it via OP_PMCATTACH.
2436 * - the current process has already allocated a PMC at index 'ri'
2441 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2445 struct pmc_owner *po;
2446 struct pmc_process *pp;
2448 PMCDBG(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2449 "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2452 * We shouldn't have already allocated a process-mode PMC at
2455 * We shouldn't have allocated a system-wide PMC on the same
2458 if ((po = pmc_find_owner_descriptor(p)) != NULL)
2459 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2460 if (PMC_TO_ROWINDEX(pm) == ri) {
2461 mode = PMC_TO_MODE(pm);
2462 if (PMC_IS_VIRTUAL_MODE(mode))
2464 if (PMC_IS_SYSTEM_MODE(mode) &&
2465 (int) PMC_TO_CPU(pm) == cpu)
2471 * We also shouldn't be the target of any PMC at this index
2472 * since otherwise a PMC_ATTACH to ourselves will fail.
2474 if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2475 if (pp->pp_pmcs[ri].pp_pmc)
2478 PMCDBG(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2479 p, p->p_pid, p->p_comm, ri);
2485 * Check if a given PMC at row index 'ri' can be currently used in
2490 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2494 sx_assert(&pmc_sx, SX_XLOCKED);
2496 PMCDBG(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2498 if (PMC_IS_SYSTEM_MODE(mode))
2499 disp = PMC_DISP_STANDALONE;
2501 disp = PMC_DISP_THREAD;
2504 * check disposition for PMC row 'ri':
2506 * Expected disposition Row-disposition Result
2508 * STANDALONE STANDALONE or FREE proceed
2509 * STANDALONE THREAD fail
2510 * THREAD THREAD or FREE proceed
2511 * THREAD STANDALONE fail
2514 if (!PMC_ROW_DISP_IS_FREE(ri) &&
2515 !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2516 !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2523 PMCDBG(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2530 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2534 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2538 KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2539 ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2540 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2542 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2543 if (pm->pm_id == pmcid)
2550 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2554 struct pmc_owner *po;
2556 PMCDBG(PMC,FND,1, "find-pmc id=%d", pmcid);
2558 if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2561 if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2564 PMCDBG(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2575 pmc_start(struct pmc *pm)
2578 struct pmc_owner *po;
2579 struct pmc_binding pb;
2580 struct pmc_classdep *pcd;
2581 int adjri, error, cpu, ri;
2584 ("[pmc,%d] null pm", __LINE__));
2586 mode = PMC_TO_MODE(pm);
2587 ri = PMC_TO_ROWINDEX(pm);
2588 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2592 PMCDBG(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2597 * Disallow PMCSTART if a logfile is required but has not been
2600 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2601 (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2602 return (EDOOFUS); /* programming error */
2605 * If this is a sampling mode PMC, log mapping information for
2606 * the kernel modules that are currently loaded.
2608 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2609 pmc_log_kernel_mappings(pm);
2611 if (PMC_IS_VIRTUAL_MODE(mode)) {
2614 * If a PMCATTACH has never been done on this PMC,
2615 * attach it to its owner process.
2618 if (LIST_EMPTY(&pm->pm_targets))
2619 error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2620 pmc_attach_process(po->po_owner, pm);
2623 * If the PMC is attached to its owner, then force a context
2624 * switch to ensure that the MD state gets set correctly.
2628 pm->pm_state = PMC_STATE_RUNNING;
2629 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2630 pmc_force_context_switch();
2638 * A system-wide PMC.
2640 * Add the owner to the global list if this is a system-wide
2644 if (mode == PMC_MODE_SS) {
2645 if (po->po_sscount == 0) {
2646 LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2647 atomic_add_rel_int(&pmc_ss_count, 1);
2648 PMCDBG(PMC,OPS,1, "po=%p in global list", po);
2653 * Log mapping information for all existing processes in the
2654 * system. Subsequent mappings are logged as they happen;
2655 * see pmc_process_mmap().
2657 if (po->po_logprocmaps == 0) {
2658 pmc_log_all_process_mappings(po);
2659 po->po_logprocmaps = 1;
2664 * Move to the CPU associated with this
2665 * PMC, and start the hardware.
2668 pmc_save_cpu_binding(&pb);
2670 cpu = PMC_TO_CPU(pm);
2672 if (!pmc_cpu_is_active(cpu))
2675 pmc_select_cpu(cpu);
2678 * global PMCs are configured at allocation time
2679 * so write out the initial value and start the PMC.
2682 pm->pm_state = PMC_STATE_RUNNING;
2685 if ((error = pcd->pcd_write_pmc(cpu, adjri,
2686 PMC_IS_SAMPLING_MODE(mode) ?
2687 pm->pm_sc.pm_reloadcount :
2688 pm->pm_sc.pm_initial)) == 0)
2689 error = pcd->pcd_start_pmc(cpu, adjri);
2692 pmc_restore_cpu_binding(&pb);
2702 pmc_stop(struct pmc *pm)
2704 struct pmc_owner *po;
2705 struct pmc_binding pb;
2706 struct pmc_classdep *pcd;
2707 int adjri, cpu, error, ri;
2709 KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2711 PMCDBG(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2712 PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2714 pm->pm_state = PMC_STATE_STOPPED;
2717 * If the PMC is a virtual mode one, changing the state to
2718 * non-RUNNING is enough to ensure that the PMC never gets
2721 * If this PMC is current running on a CPU, then it will
2722 * handled correctly at the time its target process is context
2726 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2730 * A system-mode PMC. Move to the CPU associated with
2731 * this PMC, and stop the hardware. We update the
2732 * 'initial count' so that a subsequent PMCSTART will
2733 * resume counting from the current hardware count.
2736 pmc_save_cpu_binding(&pb);
2738 cpu = PMC_TO_CPU(pm);
2740 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
2741 ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2743 if (!pmc_cpu_is_active(cpu))
2746 pmc_select_cpu(cpu);
2748 ri = PMC_TO_ROWINDEX(pm);
2749 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2752 if ((error = pcd->pcd_stop_pmc(cpu, adjri)) == 0)
2753 error = pcd->pcd_read_pmc(cpu, adjri, &pm->pm_sc.pm_initial);
2756 pmc_restore_cpu_binding(&pb);
2760 /* remove this owner from the global list of SS PMC owners */
2761 if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2763 if (po->po_sscount == 0) {
2764 atomic_subtract_rel_int(&pmc_ss_count, 1);
2765 LIST_REMOVE(po, po_ssnext);
2766 PMCDBG(PMC,OPS,2,"po=%p removed from global list", po);
2775 static const char *pmc_op_to_name[] = {
2777 #define __PMC_OP(N, D) #N ,
2784 * The syscall interface
2787 #define PMC_GET_SX_XLOCK(...) do { \
2788 sx_xlock(&pmc_sx); \
2789 if (pmc_hook == NULL) { \
2790 sx_xunlock(&pmc_sx); \
2791 return __VA_ARGS__; \
2795 #define PMC_DOWNGRADE_SX() do { \
2796 sx_downgrade(&pmc_sx); \
2797 is_sx_downgraded = 1; \
2801 pmc_syscall_handler(struct thread *td, void *syscall_args)
2803 int error, is_sx_downgraded, is_sx_locked, op;
2804 struct pmc_syscall_args *c;
2807 PMC_GET_SX_XLOCK(ENOSYS);
2811 is_sx_downgraded = 0;
2814 c = (struct pmc_syscall_args *) syscall_args;
2819 PMCDBG(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2820 pmc_op_to_name[op], arg);
2823 atomic_add_int(&pmc_stats.pm_syscalls, 1);
2830 * Configure a log file.
2832 * XXX This OP will be reworked.
2835 case PMC_OP_CONFIGURELOG:
2839 struct pmc_owner *po;
2840 struct pmc_op_configurelog cl;
2842 sx_assert(&pmc_sx, SX_XLOCKED);
2844 if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2847 /* mark this process as owning a log file */
2849 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2850 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2856 * If a valid fd was passed in, try to configure that,
2857 * otherwise if 'fd' was less than zero and there was
2858 * a log file configured, flush its buffers and
2861 if (cl.pm_logfd >= 0) {
2862 sx_xunlock(&pmc_sx);
2864 error = pmclog_configure_log(md, po, cl.pm_logfd);
2865 } else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2866 pmclog_process_closelog(po);
2867 error = pmclog_close(po);
2869 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2870 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2871 pm->pm_state == PMC_STATE_RUNNING)
2873 error = pmclog_deconfigure_log(po);
2887 case PMC_OP_FLUSHLOG:
2889 struct pmc_owner *po;
2891 sx_assert(&pmc_sx, SX_XLOCKED);
2893 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2898 error = pmclog_flush(po);
2906 case PMC_OP_CLOSELOG:
2908 struct pmc_owner *po;
2910 sx_assert(&pmc_sx, SX_XLOCKED);
2912 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2917 error = pmclog_close(po);
2922 * Retrieve hardware configuration.
2925 case PMC_OP_GETCPUINFO: /* CPU information */
2927 struct pmc_op_getcpuinfo gci;
2928 struct pmc_classinfo *pci;
2929 struct pmc_classdep *pcd;
2932 gci.pm_cputype = md->pmd_cputype;
2933 gci.pm_ncpu = pmc_cpu_max();
2934 gci.pm_npmc = md->pmd_npmc;
2935 gci.pm_nclass = md->pmd_nclass;
2936 pci = gci.pm_classes;
2937 pcd = md->pmd_classdep;
2938 for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
2939 pci->pm_caps = pcd->pcd_caps;
2940 pci->pm_class = pcd->pcd_class;
2941 pci->pm_width = pcd->pcd_width;
2942 pci->pm_num = pcd->pcd_num;
2944 error = copyout(&gci, arg, sizeof(gci));
2949 * Retrieve soft events list.
2951 case PMC_OP_GETDYNEVENTINFO:
2955 struct pmc_op_getdyneventinfo *gei;
2956 struct pmc_dyn_event_descr dev;
2957 struct pmc_soft *ps;
2960 sx_assert(&pmc_sx, SX_LOCKED);
2962 gei = (struct pmc_op_getdyneventinfo *) arg;
2964 if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
2967 /* Only SOFT class is dynamic. */
2968 if (cl != PMC_CLASS_SOFT) {
2974 for (ev = PMC_EV_SOFT_FIRST; ev <= PMC_EV_SOFT_LAST; ev++) {
2975 ps = pmc_soft_ev_acquire(ev);
2978 bcopy(&ps->ps_ev, &dev, sizeof(dev));
2979 pmc_soft_ev_release(ps);
2981 error = copyout(&dev,
2982 &gei->pm_events[nevent],
2983 sizeof(struct pmc_dyn_event_descr));
2991 error = copyout(&nevent, &gei->pm_nevent,
2997 * Get module statistics
3000 case PMC_OP_GETDRIVERSTATS:
3002 struct pmc_op_getdriverstats gms;
3004 bcopy(&pmc_stats, &gms, sizeof(gms));
3005 error = copyout(&gms, arg, sizeof(gms));
3011 * Retrieve module version number
3014 case PMC_OP_GETMODULEVERSION:
3018 /* retrieve the client's idea of the ABI version */
3019 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
3021 /* don't service clients newer than our driver */
3023 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
3024 error = EPROGMISMATCH;
3027 error = copyout(&modv, arg, sizeof(int));
3033 * Retrieve the state of all the PMCs on a given
3037 case PMC_OP_GETPMCINFO:
3041 size_t pmcinfo_size;
3042 uint32_t cpu, n, npmc;
3043 struct pmc_owner *po;
3044 struct pmc_binding pb;
3045 struct pmc_classdep *pcd;
3046 struct pmc_info *p, *pmcinfo;
3047 struct pmc_op_getpmcinfo *gpi;
3051 gpi = (struct pmc_op_getpmcinfo *) arg;
3053 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
3056 if (cpu >= pmc_cpu_max()) {
3061 if (!pmc_cpu_is_active(cpu)) {
3066 /* switch to CPU 'cpu' */
3067 pmc_save_cpu_binding(&pb);
3068 pmc_select_cpu(cpu);
3070 npmc = md->pmd_npmc;
3072 pmcinfo_size = npmc * sizeof(struct pmc_info);
3073 pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK);
3077 for (n = 0; n < md->pmd_npmc; n++, p++) {
3079 pcd = pmc_ri_to_classdep(md, n, &ari);
3081 KASSERT(pcd != NULL,
3082 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
3084 if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
3087 if (PMC_ROW_DISP_IS_STANDALONE(n))
3088 p->pm_rowdisp = PMC_DISP_STANDALONE;
3089 else if (PMC_ROW_DISP_IS_THREAD(n))
3090 p->pm_rowdisp = PMC_DISP_THREAD;
3092 p->pm_rowdisp = PMC_DISP_FREE;
3094 p->pm_ownerpid = -1;
3096 if (pm == NULL) /* no PMC associated */
3101 KASSERT(po->po_owner != NULL,
3102 ("[pmc,%d] pmc_owner had a null proc pointer",
3105 p->pm_ownerpid = po->po_owner->p_pid;
3106 p->pm_mode = PMC_TO_MODE(pm);
3107 p->pm_event = pm->pm_event;
3108 p->pm_flags = pm->pm_flags;
3110 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3112 pm->pm_sc.pm_reloadcount;
3115 pmc_restore_cpu_binding(&pb);
3117 /* now copy out the PMC info collected */
3119 error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
3121 free(pmcinfo, M_PMC);
3127 * Set the administrative state of a PMC. I.e. whether
3128 * the PMC is to be used or not.
3131 case PMC_OP_PMCADMIN:
3134 enum pmc_state request;
3137 struct pmc_op_pmcadmin pma;
3138 struct pmc_binding pb;
3140 sx_assert(&pmc_sx, SX_XLOCKED);
3142 KASSERT(td == curthread,
3143 ("[pmc,%d] td != curthread", __LINE__));
3145 error = priv_check(td, PRIV_PMC_MANAGE);
3149 if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
3154 if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
3159 if (!pmc_cpu_is_active(cpu)) {
3164 request = pma.pm_state;
3166 if (request != PMC_STATE_DISABLED &&
3167 request != PMC_STATE_FREE) {
3172 ri = pma.pm_pmc; /* pmc id == row index */
3173 if (ri < 0 || ri >= (int) md->pmd_npmc) {
3179 * We can't disable a PMC with a row-index allocated
3180 * for process virtual PMCs.
3183 if (PMC_ROW_DISP_IS_THREAD(ri) &&
3184 request == PMC_STATE_DISABLED) {
3190 * otherwise, this PMC on this CPU is either free or
3191 * in system-wide mode.
3194 pmc_save_cpu_binding(&pb);
3195 pmc_select_cpu(cpu);
3198 phw = pc->pc_hwpmcs[ri];
3201 * XXX do we need some kind of 'forced' disable?
3204 if (phw->phw_pmc == NULL) {
3205 if (request == PMC_STATE_DISABLED &&
3206 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
3207 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
3208 PMC_MARK_ROW_STANDALONE(ri);
3209 } else if (request == PMC_STATE_FREE &&
3210 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
3211 phw->phw_state |= PMC_PHW_FLAG_IS_ENABLED;
3212 PMC_UNMARK_ROW_STANDALONE(ri);
3214 /* other cases are a no-op */
3218 pmc_restore_cpu_binding(&pb);
3227 case PMC_OP_PMCALLOCATE:
3235 struct pmc_binding pb;
3236 struct pmc_classdep *pcd;
3237 struct pmc_op_pmcallocate pa;
3239 if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
3246 if ((mode != PMC_MODE_SS && mode != PMC_MODE_SC &&
3247 mode != PMC_MODE_TS && mode != PMC_MODE_TC) ||
3248 (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
3254 * Virtual PMCs should only ask for a default CPU.
3255 * System mode PMCs need to specify a non-default CPU.
3258 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3259 (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3265 * Check that an inactive CPU is not being asked for.
3268 if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3274 * Refuse an allocation for a system-wide PMC if this
3275 * process has been jailed, or if this process lacks
3276 * super-user credentials and the sysctl tunable
3277 * 'security.bsd.unprivileged_syspmcs' is zero.
3280 if (PMC_IS_SYSTEM_MODE(mode)) {
3281 if (jailed(curthread->td_ucred)) {
3285 if (!pmc_unprivileged_syspmcs) {
3286 error = priv_check(curthread,
3294 * Look for valid values for 'pm_flags'
3297 if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3298 PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3303 /* process logging options are not allowed for system PMCs */
3304 if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3305 (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3311 * All sampling mode PMCs need to be able to interrupt the
3314 if (PMC_IS_SAMPLING_MODE(mode))
3315 caps |= PMC_CAP_INTERRUPT;
3317 /* A valid class specifier should have been passed in. */
3318 for (n = 0; n < md->pmd_nclass; n++)
3319 if (md->pmd_classdep[n].pcd_class == pa.pm_class)
3321 if (n == md->pmd_nclass) {
3326 /* The requested PMC capabilities should be feasible. */
3327 if ((md->pmd_classdep[n].pcd_caps & caps) != caps) {
3332 PMCDBG(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3333 pa.pm_ev, caps, mode, cpu);
3335 pmc = pmc_allocate_pmc_descriptor();
3336 pmc->pm_id = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3338 pmc->pm_event = pa.pm_ev;
3339 pmc->pm_state = PMC_STATE_FREE;
3340 pmc->pm_caps = caps;
3341 pmc->pm_flags = pa.pm_flags;
3343 /* switch thread to CPU 'cpu' */
3344 pmc_save_cpu_binding(&pb);
3346 #define PMC_IS_SHAREABLE_PMC(cpu, n) \
3347 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state & \
3348 PMC_PHW_FLAG_IS_SHAREABLE)
3349 #define PMC_IS_UNALLOCATED(cpu, n) \
3350 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3352 if (PMC_IS_SYSTEM_MODE(mode)) {
3353 pmc_select_cpu(cpu);
3354 for (n = 0; n < (int) md->pmd_npmc; n++) {
3355 pcd = pmc_ri_to_classdep(md, n, &adjri);
3356 if (pmc_can_allocate_row(n, mode) == 0 &&
3357 pmc_can_allocate_rowindex(
3358 curthread->td_proc, n, cpu) == 0 &&
3359 (PMC_IS_UNALLOCATED(cpu, n) ||
3360 PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3361 pcd->pcd_allocate_pmc(cpu, adjri, pmc,
3366 /* Process virtual mode */
3367 for (n = 0; n < (int) md->pmd_npmc; n++) {
3368 pcd = pmc_ri_to_classdep(md, n, &adjri);
3369 if (pmc_can_allocate_row(n, mode) == 0 &&
3370 pmc_can_allocate_rowindex(
3371 curthread->td_proc, n,
3372 PMC_CPU_ANY) == 0 &&
3373 pcd->pcd_allocate_pmc(curthread->td_oncpu,
3374 adjri, pmc, &pa) == 0)
3379 #undef PMC_IS_UNALLOCATED
3380 #undef PMC_IS_SHAREABLE_PMC
3382 pmc_restore_cpu_binding(&pb);
3384 if (n == (int) md->pmd_npmc) {
3385 pmc_destroy_pmc_descriptor(pmc);
3392 /* Fill in the correct value in the ID field */
3393 pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3395 PMCDBG(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3396 pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3398 /* Process mode PMCs with logging enabled need log files */
3399 if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3400 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3402 /* All system mode sampling PMCs require a log file */
3403 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3404 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3407 * Configure global pmc's immediately
3410 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3412 pmc_save_cpu_binding(&pb);
3413 pmc_select_cpu(cpu);
3415 phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3416 pcd = pmc_ri_to_classdep(md, n, &adjri);
3418 if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3419 (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3420 (void) pcd->pcd_release_pmc(cpu, adjri, pmc);
3421 pmc_destroy_pmc_descriptor(pmc);
3424 pmc_restore_cpu_binding(&pb);
3429 pmc_restore_cpu_binding(&pb);
3432 pmc->pm_state = PMC_STATE_ALLOCATED;
3435 * mark row disposition
3438 if (PMC_IS_SYSTEM_MODE(mode))
3439 PMC_MARK_ROW_STANDALONE(n);
3441 PMC_MARK_ROW_THREAD(n);
3444 * Register this PMC with the current thread as its owner.
3448 pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3449 pmc_release_pmc_descriptor(pmc);
3456 * Return the allocated index.
3459 pa.pm_pmcid = pmc->pm_id;
3461 error = copyout(&pa, arg, sizeof(pa));
3467 * Attach a PMC to a process.
3470 case PMC_OP_PMCATTACH:
3474 struct pmc_op_pmcattach a;
3476 sx_assert(&pmc_sx, SX_XLOCKED);
3478 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3484 } else if (a.pm_pid == 0)
3485 a.pm_pid = td->td_proc->p_pid;
3487 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3490 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3495 /* PMCs may be (re)attached only when allocated or stopped */
3496 if (pm->pm_state == PMC_STATE_RUNNING) {
3499 } else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3500 pm->pm_state != PMC_STATE_STOPPED) {
3506 if ((p = pfind(a.pm_pid)) == NULL) {
3512 * Ignore processes that are working on exiting.
3514 if (p->p_flag & P_WEXIT) {
3516 PROC_UNLOCK(p); /* pfind() returns a locked process */
3521 * we are allowed to attach a PMC to a process if
3524 error = p_candebug(curthread, p);
3529 error = pmc_attach_process(p, pm);
3535 * Detach an attached PMC from a process.
3538 case PMC_OP_PMCDETACH:
3542 struct pmc_op_pmcattach a;
3544 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3550 } else if (a.pm_pid == 0)
3551 a.pm_pid = td->td_proc->p_pid;
3553 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3556 if ((p = pfind(a.pm_pid)) == NULL) {
3562 * Treat processes that are in the process of exiting
3563 * as if they were not present.
3566 if (p->p_flag & P_WEXIT)
3569 PROC_UNLOCK(p); /* pfind() returns a locked process */
3572 error = pmc_detach_process(p, pm);
3578 * Retrieve the MSR number associated with the counter
3579 * 'pmc_id'. This allows processes to directly use RDPMC
3580 * instructions to read their PMCs, without the overhead of a
3584 case PMC_OP_PMCGETMSR:
3588 struct pmc_target *pt;
3589 struct pmc_op_getmsr gm;
3590 struct pmc_classdep *pcd;
3594 if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3597 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3601 * The allocated PMC has to be a process virtual PMC,
3602 * i.e., of type MODE_T[CS]. Global PMCs can only be
3603 * read using the PMCREAD operation since they may be
3604 * allocated on a different CPU than the one we could
3605 * be running on at the time of the RDPMC instruction.
3607 * The GETMSR operation is not allowed for PMCs that
3608 * are inherited across processes.
3611 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3612 (pm->pm_flags & PMC_F_DESCENDANTS)) {
3618 * It only makes sense to use a RDPMC (or its
3619 * equivalent instruction on non-x86 architectures) on
3620 * a process that has allocated and attached a PMC to
3621 * itself. Conversely the PMC is only allowed to have
3622 * one process attached to it -- its owner.
3625 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3626 LIST_NEXT(pt, pt_next) != NULL ||
3627 pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3632 ri = PMC_TO_ROWINDEX(pm);
3633 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3635 /* PMC class has no 'GETMSR' support */
3636 if (pcd->pcd_get_msr == NULL) {
3641 if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
3644 if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3648 * Mark our process as using MSRs. Update machine
3649 * state using a forced context switch.
3652 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3653 pmc_force_context_switch();
3659 * Release an allocated PMC
3662 case PMC_OP_PMCRELEASE:
3666 struct pmc_owner *po;
3667 struct pmc_op_simple sp;
3670 * Find PMC pointer for the named PMC.
3672 * Use pmc_release_pmc_descriptor() to switch off the
3673 * PMC, remove all its target threads, and remove the
3674 * PMC from its owner's list.
3676 * Remove the owner record if this is the last PMC
3682 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3685 pmcid = sp.pm_pmcid;
3687 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3691 pmc_release_pmc_descriptor(pm);
3692 pmc_maybe_remove_owner(po);
3700 * Read and/or write a PMC.
3708 pmc_value_t oldvalue;
3709 struct pmc_binding pb;
3710 struct pmc_op_pmcrw prw;
3711 struct pmc_classdep *pcd;
3712 struct pmc_op_pmcrw *pprw;
3716 if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3720 PMCDBG(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3723 /* must have at least one flag set */
3724 if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3729 /* locate pmc descriptor */
3730 if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3733 /* Can't read a PMC that hasn't been started. */
3734 if (pm->pm_state != PMC_STATE_ALLOCATED &&
3735 pm->pm_state != PMC_STATE_STOPPED &&
3736 pm->pm_state != PMC_STATE_RUNNING) {
3741 /* writing a new value is allowed only for 'STOPPED' pmcs */
3742 if (pm->pm_state == PMC_STATE_RUNNING &&
3743 (prw.pm_flags & PMC_F_NEWVALUE)) {
3748 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3751 * If this PMC is attached to its owner (i.e.,
3752 * the process requesting this operation) and
3753 * is running, then attempt to get an
3754 * upto-date reading from hardware for a READ.
3755 * Writes are only allowed when the PMC is
3756 * stopped, so only update the saved value
3759 * If the PMC is not running, or is not
3760 * attached to its owner, read/write to the
3764 ri = PMC_TO_ROWINDEX(pm);
3765 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3767 mtx_pool_lock_spin(pmc_mtxpool, pm);
3768 cpu = curthread->td_oncpu;
3770 if (prw.pm_flags & PMC_F_OLDVALUE) {
3771 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3772 (pm->pm_state == PMC_STATE_RUNNING))
3773 error = (*pcd->pcd_read_pmc)(cpu, adjri,
3776 oldvalue = pm->pm_gv.pm_savedvalue;
3778 if (prw.pm_flags & PMC_F_NEWVALUE)
3779 pm->pm_gv.pm_savedvalue = prw.pm_value;
3781 mtx_pool_unlock_spin(pmc_mtxpool, pm);
3783 } else { /* System mode PMCs */
3784 cpu = PMC_TO_CPU(pm);
3785 ri = PMC_TO_ROWINDEX(pm);
3786 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3788 if (!pmc_cpu_is_active(cpu)) {
3793 /* move this thread to CPU 'cpu' */
3794 pmc_save_cpu_binding(&pb);
3795 pmc_select_cpu(cpu);
3798 /* save old value */
3799 if (prw.pm_flags & PMC_F_OLDVALUE)
3800 if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
3803 /* write out new value */
3804 if (prw.pm_flags & PMC_F_NEWVALUE)
3805 error = (*pcd->pcd_write_pmc)(cpu, adjri,
3809 pmc_restore_cpu_binding(&pb);
3814 pprw = (struct pmc_op_pmcrw *) arg;
3817 if (prw.pm_flags & PMC_F_NEWVALUE)
3818 PMCDBG(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3819 ri, prw.pm_value, oldvalue);
3820 else if (prw.pm_flags & PMC_F_OLDVALUE)
3821 PMCDBG(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3824 /* return old value if requested */
3825 if (prw.pm_flags & PMC_F_OLDVALUE)
3826 if ((error = copyout(&oldvalue, &pprw->pm_value,
3827 sizeof(prw.pm_value))))
3835 * Set the sampling rate for a sampling mode PMC and the
3836 * initial count for a counting mode PMC.
3839 case PMC_OP_PMCSETCOUNT:
3842 struct pmc_op_pmcsetcount sc;
3846 if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3849 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3852 if (pm->pm_state == PMC_STATE_RUNNING) {
3857 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3858 pm->pm_sc.pm_reloadcount = sc.pm_count;
3860 pm->pm_sc.pm_initial = sc.pm_count;
3869 case PMC_OP_PMCSTART:
3873 struct pmc_op_simple sp;
3875 sx_assert(&pmc_sx, SX_XLOCKED);
3877 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3880 pmcid = sp.pm_pmcid;
3882 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3885 KASSERT(pmcid == pm->pm_id,
3886 ("[pmc,%d] pmcid %x != id %x", __LINE__,
3889 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3891 else if (pm->pm_state != PMC_STATE_STOPPED &&
3892 pm->pm_state != PMC_STATE_ALLOCATED) {
3897 error = pmc_start(pm);
3906 case PMC_OP_PMCSTOP:
3910 struct pmc_op_simple sp;
3914 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3917 pmcid = sp.pm_pmcid;
3920 * Mark the PMC as inactive and invoke the MD stop
3921 * routines if needed.
3924 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3927 KASSERT(pmcid == pm->pm_id,
3928 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3931 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3933 else if (pm->pm_state != PMC_STATE_RUNNING) {
3938 error = pmc_stop(pm);
3944 * Write a user supplied value to the log file.
3947 case PMC_OP_WRITELOG:
3949 struct pmc_op_writelog wl;
3950 struct pmc_owner *po;
3954 if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
3957 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3962 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
3967 error = pmclog_process_userlog(po, &wl);
3977 if (is_sx_locked != 0) {
3978 if (is_sx_downgraded)
3979 sx_sunlock(&pmc_sx);
3981 sx_xunlock(&pmc_sx);
3985 atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
3998 * Mark the thread as needing callchain capture and post an AST. The
3999 * actual callchain capture will be done in a context where it is safe
4000 * to take page faults.
4004 pmc_post_callchain_callback(void)
4011 * If there is multiple PMCs for the same interrupt ignore new post
4013 if (td->td_pflags & TDP_CALLCHAIN)
4017 * Mark this thread as needing callchain capture.
4018 * `td->td_pflags' will be safe to touch because this thread
4019 * was in user space when it was interrupted.
4021 td->td_pflags |= TDP_CALLCHAIN;
4024 * Don't let this thread migrate between CPUs until callchain
4025 * capture completes.
4033 * Interrupt processing.
4035 * Find a free slot in the per-cpu array of samples and capture the
4036 * current callchain there. If a sample was successfully added, a bit
4037 * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4038 * needs to be invoked from the clock handler.
4040 * This function is meant to be called from an NMI handler. It cannot
4041 * use any of the locking primitives supplied by the OS.
4045 pmc_process_interrupt(int cpu, int ring, struct pmc *pm, struct trapframe *tf,
4048 int error, callchaindepth;
4050 struct pmc_sample *ps;
4051 struct pmc_samplebuffer *psb;
4056 * Allocate space for a sample buffer.
4058 psb = pmc_pcpu[cpu]->pc_sb[ring];
4061 if (ps->ps_nsamples) { /* in use, reader hasn't caught up */
4063 atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
4064 PMCDBG(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
4065 cpu, pm, (void *) tf, inuserspace,
4066 (int) (psb->ps_write - psb->ps_samples),
4067 (int) (psb->ps_read - psb->ps_samples));
4073 /* Fill in entry. */
4074 PMCDBG(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
4075 (void *) tf, inuserspace,
4076 (int) (psb->ps_write - psb->ps_samples),
4077 (int) (psb->ps_read - psb->ps_samples));
4079 KASSERT(pm->pm_runcount >= 0,
4080 ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4083 atomic_add_rel_int(&pm->pm_runcount, 1); /* hold onto PMC */
4086 if ((td = curthread) && td->td_proc)
4087 ps->ps_pid = td->td_proc->p_pid;
4092 ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4094 callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4095 pmc_callchaindepth : 1;
4097 if (callchaindepth == 1)
4098 ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
4101 * Kernel stack traversals can be done immediately,
4102 * while we defer to an AST for user space traversals.
4106 pmc_save_kernel_callchain(ps->ps_pc,
4107 callchaindepth, tf);
4109 pmc_post_callchain_callback();
4110 callchaindepth = PMC_SAMPLE_INUSE;
4114 ps->ps_nsamples = callchaindepth; /* mark entry as in use */
4116 /* increment write pointer, modulo ring buffer size */
4118 if (ps == psb->ps_fence)
4119 psb->ps_write = psb->ps_samples;
4124 /* mark CPU as needing processing */
4125 CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4131 * Capture a user call chain. This function will be called from ast()
4132 * before control returns to userland and before the process gets
4137 pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4142 struct pmc_sample *ps;
4143 struct pmc_samplebuffer *psb;
4148 psb = pmc_pcpu[cpu]->pc_sb[ring];
4151 KASSERT(td->td_pflags & TDP_CALLCHAIN,
4152 ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
4160 * Iterate through all deferred callchain requests.
4163 ps = psb->ps_samples;
4164 for (i = 0; i < pmc_nsamples; i++, ps++) {
4166 if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
4168 if (ps->ps_td != td)
4171 KASSERT(ps->ps_cpu == cpu,
4172 ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
4173 ps->ps_cpu, PCPU_GET(cpuid)));
4177 KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
4178 ("[pmc,%d] Retrieving callchain for PMC that doesn't "
4179 "want it", __LINE__));
4181 KASSERT(pm->pm_runcount > 0,
4182 ("[pmc,%d] runcount %d", __LINE__, pm->pm_runcount));
4185 * Retrieve the callchain and mark the sample buffer
4186 * as 'processable' by the timer tick sweep code.
4188 ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
4189 pmc_callchaindepth, tf);
4196 KASSERT(ncallchains > 0,
4197 ("[pmc,%d] cpu %d didn't find a sample to collect", __LINE__,
4200 KASSERT(td->td_pinned > 0,
4201 ("[pmc,%d] invalid td_pinned value", __LINE__));
4202 sched_unpin(); /* Can migrate safely now. */
4208 * Process saved PC samples.
4212 pmc_process_samples(int cpu, int ring)
4217 struct pmc_owner *po;
4218 struct pmc_sample *ps;
4219 struct pmc_classdep *pcd;
4220 struct pmc_samplebuffer *psb;
4222 KASSERT(PCPU_GET(cpuid) == cpu,
4223 ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4224 PCPU_GET(cpuid), cpu));
4226 psb = pmc_pcpu[cpu]->pc_sb[ring];
4228 for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
4231 if (ps->ps_nsamples == PMC_SAMPLE_FREE)
4236 KASSERT(pm->pm_runcount > 0,
4237 ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4242 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4243 ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4244 pm, PMC_TO_MODE(pm)));
4246 /* Ignore PMCs that have been switched off */
4247 if (pm->pm_state != PMC_STATE_RUNNING)
4250 /* If there is a pending AST wait for completion */
4251 if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
4252 /* Need a rescan at a later time. */
4253 CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4257 PMCDBG(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4258 pm, ps->ps_nsamples, ps->ps_flags,
4259 (int) (psb->ps_write - psb->ps_samples),
4260 (int) (psb->ps_read - psb->ps_samples));
4263 * If this is a process-mode PMC that is attached to
4264 * its owner, and if the PC is in user mode, update
4265 * profiling statistics like timer-based profiling
4268 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4269 if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4270 td = FIRST_THREAD_IN_PROC(po->po_owner);
4271 addupc_intr(td, ps->ps_pc[0], 1);
4277 * Otherwise, this is either a sampling mode PMC that
4278 * is attached to a different process than its owner,
4279 * or a system-wide sampling PMC. Dispatch a log
4280 * entry to the PMC's owner process.
4282 pmclog_process_callchain(pm, ps);
4285 ps->ps_nsamples = 0; /* mark entry as free */
4286 atomic_subtract_rel_int(&pm->pm_runcount, 1);
4288 /* increment read pointer, modulo sample size */
4289 if (++ps == psb->ps_fence)
4290 psb->ps_read = psb->ps_samples;
4295 atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
4297 /* Do not re-enable stalled PMCs if we failed to process any samples */
4302 * Restart any stalled sampling PMCs on this CPU.
4304 * If the NMI handler sets the pm_stalled field of a PMC after
4305 * the check below, we'll end up processing the stalled PMC at
4306 * the next hardclock tick.
4308 for (n = 0; n < md->pmd_npmc; n++) {
4309 pcd = pmc_ri_to_classdep(md, n, &adjri);
4310 KASSERT(pcd != NULL,
4311 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4312 (void) (*pcd->pcd_get_config)(cpu,adjri,&pm);
4314 if (pm == NULL || /* !cfg'ed */
4315 pm->pm_state != PMC_STATE_RUNNING || /* !active */
4316 !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4317 pm->pm_stalled == 0) /* !stalled */
4321 (*pcd->pcd_start_pmc)(cpu, adjri);
4330 * Handle a process exit.
4332 * Remove this process from all hash tables. If this process
4333 * owned any PMCs, turn off those PMCs and deallocate them,
4334 * removing any associations with target processes.
4336 * This function will be called by the last 'thread' of a
4339 * XXX This eventhandler gets called early in the exit process.
4340 * Consider using a 'hook' invocation from thread_exit() or equivalent
4341 * spot. Another negative is that kse_exit doesn't seem to call
4347 pmc_process_exit(void *arg __unused, struct proc *p)
4352 int is_using_hwpmcs;
4353 struct pmc_owner *po;
4354 struct pmc_process *pp;
4355 struct pmc_classdep *pcd;
4356 pmc_value_t newvalue, tmp;
4359 is_using_hwpmcs = p->p_flag & P_HWPMC;
4363 * Log a sysexit event to all SS PMC owners.
4365 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4366 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4367 pmclog_process_sysexit(po, p->p_pid);
4369 if (!is_using_hwpmcs)
4373 PMCDBG(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4377 * Since this code is invoked by the last thread in an exiting
4378 * process, we would have context switched IN at some prior
4379 * point. However, with PREEMPTION, kernel mode context
4380 * switches may happen any time, so we want to disable a
4381 * context switch OUT till we get any PMCs targetting this
4382 * process off the hardware.
4384 * We also need to atomically remove this process'
4385 * entry from our target process hash table, using
4388 PMCDBG(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4391 critical_enter(); /* no preemption */
4393 cpu = curthread->td_oncpu;
4395 if ((pp = pmc_find_process_descriptor(p,
4396 PMC_FLAG_REMOVE)) != NULL) {
4399 "process-exit proc=%p pmc-process=%p", p, pp);
4402 * The exiting process could the target of
4403 * some PMCs which will be running on
4404 * currently executing CPU.
4406 * We need to turn these PMCs off like we
4407 * would do at context switch OUT time.
4409 for (ri = 0; ri < md->pmd_npmc; ri++) {
4412 * Pick up the pmc pointer from hardware
4413 * state similar to the CSW_OUT code.
4417 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4419 (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
4421 PMCDBG(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4424 !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4427 PMCDBG(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4428 "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4431 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4432 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4433 __LINE__, PMC_TO_ROWINDEX(pm), ri));
4435 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4436 ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4437 __LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4439 (void) pcd->pcd_stop_pmc(cpu, adjri);
4441 KASSERT(pm->pm_runcount > 0,
4442 ("[pmc,%d] bad runcount ri %d rc %d",
4443 __LINE__, ri, pm->pm_runcount));
4445 /* Stop hardware only if it is actually running */
4446 if (pm->pm_state == PMC_STATE_RUNNING &&
4447 pm->pm_stalled == 0) {
4448 pcd->pcd_read_pmc(cpu, adjri, &newvalue);
4450 PMC_PCPU_SAVED(cpu,ri);
4452 mtx_pool_lock_spin(pmc_mtxpool, pm);
4453 pm->pm_gv.pm_savedvalue += tmp;
4454 pp->pp_pmcs[ri].pp_pmcval += tmp;
4455 mtx_pool_unlock_spin(pmc_mtxpool, pm);
4458 atomic_subtract_rel_int(&pm->pm_runcount,1);
4460 KASSERT((int) pm->pm_runcount >= 0,
4461 ("[pmc,%d] runcount is %d", __LINE__, ri));
4463 (void) pcd->pcd_config_pmc(cpu, adjri, NULL);
4467 * Inform the MD layer of this pseudo "context switch
4470 (void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
4472 critical_exit(); /* ok to be pre-empted now */
4475 * Unlink this process from the PMCs that are
4476 * targetting it. This will send a signal to
4477 * all PMC owner's whose PMCs are orphaned.
4479 * Log PMC value at exit time if requested.
4481 for (ri = 0; ri < md->pmd_npmc; ri++)
4482 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
4483 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
4484 PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
4485 pmclog_process_procexit(pm, pp);
4486 pmc_unlink_target_process(pm, pp);
4491 critical_exit(); /* pp == NULL */
4495 * If the process owned PMCs, free them up and free up
4498 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
4499 pmc_remove_owner(po);
4500 pmc_destroy_owner_descriptor(po);
4503 sx_xunlock(&pmc_sx);
4507 * Handle a process fork.
4509 * If the parent process 'p1' is under HWPMC monitoring, then copy
4510 * over any attached PMCs that have 'do_descendants' semantics.
4514 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
4517 int is_using_hwpmcs;
4519 uint32_t do_descendants;
4521 struct pmc_owner *po;
4522 struct pmc_process *ppnew, *ppold;
4524 (void) flags; /* unused parameter */
4527 is_using_hwpmcs = p1->p_flag & P_HWPMC;
4531 * If there are system-wide sampling PMCs active, we need to
4532 * log all fork events to their owner's logs.
4535 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4536 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4537 pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4539 if (!is_using_hwpmcs)
4543 PMCDBG(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4544 p1->p_pid, p1->p_comm, newproc);
4547 * If the parent process (curthread->td_proc) is a
4548 * target of any PMCs, look for PMCs that are to be
4549 * inherited, and link these into the new process
4552 if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4553 PMC_FLAG_NONE)) == NULL)
4554 goto done; /* nothing to do */
4557 for (ri = 0; ri < md->pmd_npmc; ri++)
4558 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4559 do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4560 if (do_descendants == 0) /* nothing to do */
4563 /* allocate a descriptor for the new process */
4564 if ((ppnew = pmc_find_process_descriptor(newproc,
4565 PMC_FLAG_ALLOCATE)) == NULL)
4569 * Run through all PMCs that were targeting the old process
4570 * and which specified F_DESCENDANTS and attach them to the
4573 * Log the fork event to all owners of PMCs attached to this
4574 * process, if not already logged.
4576 for (ri = 0; ri < md->pmd_npmc; ri++)
4577 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4578 (pm->pm_flags & PMC_F_DESCENDANTS)) {
4579 pmc_link_target_process(pm, ppnew);
4581 if (po->po_sscount == 0 &&
4582 po->po_flags & PMC_PO_OWNS_LOGFILE)
4583 pmclog_process_procfork(po, p1->p_pid,
4588 * Now mark the new process as being tracked by this driver.
4591 newproc->p_flag |= P_HWPMC;
4592 PROC_UNLOCK(newproc);
4595 sx_xunlock(&pmc_sx);
4599 pmc_kld_load(void *arg __unused, linker_file_t lf)
4601 struct pmc_owner *po;
4606 * Notify owners of system sampling PMCs about KLD operations.
4608 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4609 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4610 pmclog_process_map_in(po, (pid_t) -1,
4611 (uintfptr_t) lf->address, lf->filename);
4614 * TODO: Notify owners of (all) process-sampling PMCs too.
4617 sx_sunlock(&pmc_sx);
4621 pmc_kld_unload(void *arg __unused, const char *filename __unused,
4622 caddr_t address, size_t size)
4624 struct pmc_owner *po;
4628 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4629 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4630 pmclog_process_map_out(po, (pid_t) -1,
4631 (uintfptr_t) address, (uintfptr_t) address + size);
4634 * TODO: Notify owners of process-sampling PMCs.
4637 sx_sunlock(&pmc_sx);
4644 static const char *pmc_name_of_pmcclass[] = {
4646 #define __PMC_CLASS(N) #N ,
4651 * Base class initializer: allocate structure and set default classes.
4654 pmc_mdep_alloc(int nclasses)
4656 struct pmc_mdep *md;
4659 /* SOFT + md classes */
4661 md = malloc(sizeof(struct pmc_mdep) + n *
4662 sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
4666 /* Add base class. */
4667 pmc_soft_initialize(md);
4674 pmc_mdep_free(struct pmc_mdep *md)
4676 pmc_soft_finalize(md);
4681 generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
4683 (void) pc; (void) pp;
4689 generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
4691 (void) pc; (void) pp;
4696 static struct pmc_mdep *
4697 pmc_generic_cpu_initialize(void)
4699 struct pmc_mdep *md;
4701 md = pmc_mdep_alloc(0);
4703 md->pmd_cputype = PMC_CPU_GENERIC;
4705 md->pmd_pcpu_init = NULL;
4706 md->pmd_pcpu_fini = NULL;
4707 md->pmd_switch_in = generic_switch_in;
4708 md->pmd_switch_out = generic_switch_out;
4714 pmc_generic_cpu_finalize(struct pmc_mdep *md)
4721 pmc_initialize(void)
4723 int c, cpu, error, n, ri;
4724 unsigned int maxcpu;
4725 struct pmc_binding pb;
4726 struct pmc_sample *ps;
4727 struct pmc_classdep *pcd;
4728 struct pmc_samplebuffer *sb;
4734 /* parse debug flags first */
4735 if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4736 pmc_debugstr, sizeof(pmc_debugstr)))
4737 pmc_debugflags_parse(pmc_debugstr,
4738 pmc_debugstr+strlen(pmc_debugstr));
4741 PMCDBG(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4743 /* check kernel version */
4744 if (pmc_kernel_version != PMC_VERSION) {
4745 if (pmc_kernel_version == 0)
4746 printf("hwpmc: this kernel has not been compiled with "
4747 "'options HWPMC_HOOKS'.\n");
4749 printf("hwpmc: kernel version (0x%x) does not match "
4750 "module version (0x%x).\n", pmc_kernel_version,
4752 return EPROGMISMATCH;
4756 * check sysctl parameters
4759 if (pmc_hashsize <= 0) {
4760 (void) printf("hwpmc: tunable \"hashsize\"=%d must be "
4761 "greater than zero.\n", pmc_hashsize);
4762 pmc_hashsize = PMC_HASH_SIZE;
4765 if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4766 (void) printf("hwpmc: tunable \"nsamples\"=%d out of "
4767 "range.\n", pmc_nsamples);
4768 pmc_nsamples = PMC_NSAMPLES;
4771 if (pmc_callchaindepth <= 0 ||
4772 pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
4773 (void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
4774 "range.\n", pmc_callchaindepth);
4775 pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
4778 md = pmc_md_initialize();
4780 /* Default to generic CPU. */
4781 md = pmc_generic_cpu_initialize();
4786 KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
4787 ("[pmc,%d] no classes or pmcs", __LINE__));
4789 /* Compute the map from row-indices to classdep pointers. */
4790 pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
4791 md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);
4793 for (n = 0; n < md->pmd_npmc; n++)
4794 pmc_rowindex_to_classdep[n] = NULL;
4795 for (ri = c = 0; c < md->pmd_nclass; c++) {
4796 pcd = &md->pmd_classdep[c];
4797 for (n = 0; n < pcd->pcd_num; n++, ri++)
4798 pmc_rowindex_to_classdep[ri] = pcd;
4801 KASSERT(ri == md->pmd_npmc,
4802 ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
4805 maxcpu = pmc_cpu_max();
4807 /* allocate space for the per-cpu array */
4808 pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
4811 /* per-cpu 'saved values' for managing process-mode PMCs */
4812 pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
4815 /* Perform CPU-dependent initialization. */
4816 pmc_save_cpu_binding(&pb);
4818 for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
4819 if (!pmc_cpu_is_active(cpu))
4821 pmc_select_cpu(cpu);
4822 pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
4823 md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
4825 if (md->pmd_pcpu_init)
4826 error = md->pmd_pcpu_init(md, cpu);
4827 for (n = 0; error == 0 && n < md->pmd_nclass; n++)
4828 error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
4830 pmc_restore_cpu_binding(&pb);
4835 /* allocate space for the sample array */
4836 for (cpu = 0; cpu < maxcpu; cpu++) {
4837 if (!pmc_cpu_is_active(cpu))
4840 sb = malloc(sizeof(struct pmc_samplebuffer) +
4841 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4843 sb->ps_read = sb->ps_write = sb->ps_samples;
4844 sb->ps_fence = sb->ps_samples + pmc_nsamples;
4846 KASSERT(pmc_pcpu[cpu] != NULL,
4847 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4849 sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4850 sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4852 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4853 ps->ps_pc = sb->ps_callchains +
4854 (n * pmc_callchaindepth);
4856 pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
4858 sb = malloc(sizeof(struct pmc_samplebuffer) +
4859 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4861 sb->ps_read = sb->ps_write = sb->ps_samples;
4862 sb->ps_fence = sb->ps_samples + pmc_nsamples;
4864 KASSERT(pmc_pcpu[cpu] != NULL,
4865 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4867 sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4868 sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4870 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4871 ps->ps_pc = sb->ps_callchains +
4872 (n * pmc_callchaindepth);
4874 pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
4877 /* allocate space for the row disposition array */
4878 pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4879 M_PMC, M_WAITOK|M_ZERO);
4881 KASSERT(pmc_pmcdisp != NULL,
4882 ("[pmc,%d] pmcdisp allocation returned NULL", __LINE__));
4884 /* mark all PMCs as available */
4885 for (n = 0; n < (int) md->pmd_npmc; n++)
4886 PMC_MARK_ROW_FREE(n);
4888 /* allocate thread hash tables */
4889 pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4890 &pmc_ownerhashmask);
4892 pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4893 &pmc_processhashmask);
4894 mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4897 LIST_INIT(&pmc_ss_owners);
4900 /* allocate a pool of spin mutexes */
4901 pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4904 PMCDBG(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4905 "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4906 pmc_processhash, pmc_processhashmask);
4908 /* register process {exit,fork,exec} handlers */
4909 pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4910 pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4911 pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4912 pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4914 /* register kld event handlers */
4915 pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
4916 NULL, EVENTHANDLER_PRI_ANY);
4917 pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
4918 NULL, EVENTHANDLER_PRI_ANY);
4920 /* initialize logging */
4921 pmclog_initialize();
4923 /* set hook functions */
4924 pmc_intr = md->pmd_intr;
4925 pmc_hook = pmc_hook_handler;
4928 printf(PMC_MODULE_NAME ":");
4929 for (n = 0; n < (int) md->pmd_nclass; n++) {
4930 pcd = &md->pmd_classdep[n];
4931 printf(" %s/%d/%d/0x%b",
4932 pmc_name_of_pmcclass[pcd->pcd_class],
4937 "\1INT\2USR\3SYS\4EDG\5THR"
4938 "\6REA\7WRI\10INV\11QUA\12PRC"
4947 /* prepare to be unloaded */
4952 unsigned int maxcpu;
4953 struct pmc_ownerhash *ph;
4954 struct pmc_owner *po, *tmp;
4955 struct pmc_binding pb;
4957 struct pmc_processhash *prh;
4960 PMCDBG(MOD,INI,0, "%s", "cleanup");
4962 /* switch off sampling */
4963 CPU_ZERO(&pmc_cpumask);
4967 if (pmc_hook == NULL) { /* being unloaded already */
4968 sx_xunlock(&pmc_sx);
4972 pmc_hook = NULL; /* prevent new threads from entering module */
4974 /* deregister event handlers */
4975 EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4976 EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4977 EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
4978 EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);
4980 /* send SIGBUS to all owner threads, free up allocations */
4982 for (ph = pmc_ownerhash;
4983 ph <= &pmc_ownerhash[pmc_ownerhashmask];
4985 LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4986 pmc_remove_owner(po);
4988 /* send SIGBUS to owner processes */
4989 PMCDBG(MOD,INI,2, "cleanup signal proc=%p "
4990 "(%d, %s)", po->po_owner,
4991 po->po_owner->p_pid,
4992 po->po_owner->p_comm);
4994 PROC_LOCK(po->po_owner);
4995 kern_psignal(po->po_owner, SIGBUS);
4996 PROC_UNLOCK(po->po_owner);
4998 pmc_destroy_owner_descriptor(po);
5002 /* reclaim allocated data structures */
5004 mtx_pool_destroy(&pmc_mtxpool);
5006 mtx_destroy(&pmc_processhash_mtx);
5007 if (pmc_processhash) {
5009 struct pmc_process *pp;
5011 PMCDBG(MOD,INI,3, "%s", "destroy process hash");
5012 for (prh = pmc_processhash;
5013 prh <= &pmc_processhash[pmc_processhashmask];
5015 LIST_FOREACH(pp, prh, pp_next)
5016 PMCDBG(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5019 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5020 pmc_processhash = NULL;
5023 if (pmc_ownerhash) {
5024 PMCDBG(MOD,INI,3, "%s", "destroy owner hash");
5025 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5026 pmc_ownerhash = NULL;
5029 KASSERT(LIST_EMPTY(&pmc_ss_owners),
5030 ("[pmc,%d] Global SS owner list not empty", __LINE__));
5031 KASSERT(pmc_ss_count == 0,
5032 ("[pmc,%d] Global SS count not empty", __LINE__));
5034 /* do processor and pmc-class dependent cleanup */
5035 maxcpu = pmc_cpu_max();
5037 PMCDBG(MOD,INI,3, "%s", "md cleanup");
5039 pmc_save_cpu_binding(&pb);
5040 for (cpu = 0; cpu < maxcpu; cpu++) {
5041 PMCDBG(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5042 cpu, pmc_pcpu[cpu]);
5043 if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5045 pmc_select_cpu(cpu);
5046 for (c = 0; c < md->pmd_nclass; c++)
5047 md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
5048 if (md->pmd_pcpu_fini)
5049 md->pmd_pcpu_fini(md, cpu);
5052 if (md->pmd_cputype == PMC_CPU_GENERIC)
5053 pmc_generic_cpu_finalize(md);
5055 pmc_md_finalize(md);
5059 pmc_restore_cpu_binding(&pb);
5062 /* Free per-cpu descriptors. */
5063 for (cpu = 0; cpu < maxcpu; cpu++) {
5064 if (!pmc_cpu_is_active(cpu))
5066 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5067 ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5069 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5070 ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5072 free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
5073 free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
5074 free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
5075 free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
5076 free(pmc_pcpu[cpu], M_PMC);
5079 free(pmc_pcpu, M_PMC);
5082 free(pmc_pcpu_saved, M_PMC);
5083 pmc_pcpu_saved = NULL;
5086 free(pmc_pmcdisp, M_PMC);
5090 if (pmc_rowindex_to_classdep) {
5091 free(pmc_rowindex_to_classdep, M_PMC);
5092 pmc_rowindex_to_classdep = NULL;
5097 sx_xunlock(&pmc_sx); /* we are done */
5101 * The function called at load/unload.
5105 load (struct module *module __unused, int cmd, void *arg __unused)
5113 /* initialize the subsystem */
5114 error = pmc_initialize();
5117 PMCDBG(MOD,INI,1, "syscall=%d maxcpu=%d",
5118 pmc_syscall_num, pmc_cpu_max());
5125 PMCDBG(MOD,INI,1, "%s", "unloaded");
5129 error = EINVAL; /* XXX should panic(9) */
5137 MALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");