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/rwlock.h>
54 #include <sys/sched.h>
55 #include <sys/signalvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/sysent.h>
60 #include <sys/systm.h>
61 #include <sys/vnode.h>
63 #include <sys/linker.h> /* needs to be after <sys/malloc.h> */
65 #include <machine/atomic.h>
66 #include <machine/md_var.h>
69 #include <vm/vm_extern.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_object.h>
74 #include "hwpmc_soft.h"
81 PMC_FLAG_NONE = 0x00, /* do nothing */
82 PMC_FLAG_REMOVE = 0x01, /* atomically remove entry from hash */
83 PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
87 * The offset in sysent where the syscall is allocated.
90 static int pmc_syscall_num = NO_SYSCALL;
91 struct pmc_cpu **pmc_pcpu; /* per-cpu state */
92 pmc_value_t *pmc_pcpu_saved; /* saved PMC values: CSW handling */
94 #define PMC_PCPU_SAVED(C,R) pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
96 struct mtx_pool *pmc_mtxpool;
97 static int *pmc_pmcdisp; /* PMC row dispositions */
99 #define PMC_ROW_DISP_IS_FREE(R) (pmc_pmcdisp[(R)] == 0)
100 #define PMC_ROW_DISP_IS_THREAD(R) (pmc_pmcdisp[(R)] > 0)
101 #define PMC_ROW_DISP_IS_STANDALONE(R) (pmc_pmcdisp[(R)] < 0)
103 #define PMC_MARK_ROW_FREE(R) do { \
104 pmc_pmcdisp[(R)] = 0; \
107 #define PMC_MARK_ROW_STANDALONE(R) do { \
108 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
110 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
111 KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()), \
112 ("[pmc,%d] row disposition error", __LINE__)); \
115 #define PMC_UNMARK_ROW_STANDALONE(R) do { \
116 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
117 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
121 #define PMC_MARK_ROW_THREAD(R) do { \
122 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
124 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
127 #define PMC_UNMARK_ROW_THREAD(R) do { \
128 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
129 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
134 /* various event handlers */
135 static eventhandler_tag pmc_exit_tag, pmc_fork_tag, pmc_kld_load_tag,
138 /* Module statistics */
139 struct pmc_op_getdriverstats pmc_stats;
141 /* Machine/processor dependent operations */
142 static struct pmc_mdep *md;
145 * Hash tables mapping owner processes and target threads to PMCs.
148 struct mtx pmc_processhash_mtx; /* spin mutex */
149 static u_long pmc_processhashmask;
150 static LIST_HEAD(pmc_processhash, pmc_process) *pmc_processhash;
153 * Hash table of PMC owner descriptors. This table is protected by
154 * the shared PMC "sx" lock.
157 static u_long pmc_ownerhashmask;
158 static LIST_HEAD(pmc_ownerhash, pmc_owner) *pmc_ownerhash;
161 * List of PMC owners with system-wide sampling PMCs.
164 static LIST_HEAD(, pmc_owner) pmc_ss_owners;
168 * A map of row indices to classdep structures.
170 static struct pmc_classdep **pmc_rowindex_to_classdep;
177 static int pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
178 static int pmc_debugflags_parse(char *newstr, char *fence);
181 static int load(struct module *module, int cmd, void *arg);
182 static int pmc_attach_process(struct proc *p, struct pmc *pm);
183 static struct pmc *pmc_allocate_pmc_descriptor(void);
184 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
185 static int pmc_attach_one_process(struct proc *p, struct pmc *pm);
186 static int pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
188 static int pmc_can_attach(struct pmc *pm, struct proc *p);
189 static void pmc_capture_user_callchain(int cpu, int soft, struct trapframe *tf);
190 static void pmc_cleanup(void);
191 static int pmc_detach_process(struct proc *p, struct pmc *pm);
192 static int pmc_detach_one_process(struct proc *p, struct pmc *pm,
194 static void pmc_destroy_owner_descriptor(struct pmc_owner *po);
195 static void pmc_destroy_pmc_descriptor(struct pmc *pm);
196 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
197 static int pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
198 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
200 static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
202 static void pmc_force_context_switch(void);
203 static void pmc_link_target_process(struct pmc *pm,
204 struct pmc_process *pp);
205 static void pmc_log_all_process_mappings(struct pmc_owner *po);
206 static void pmc_log_kernel_mappings(struct pmc *pm);
207 static void pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
208 static void pmc_maybe_remove_owner(struct pmc_owner *po);
209 static void pmc_process_csw_in(struct thread *td);
210 static void pmc_process_csw_out(struct thread *td);
211 static void pmc_process_exit(void *arg, struct proc *p);
212 static void pmc_process_fork(void *arg, struct proc *p1,
213 struct proc *p2, int n);
214 static void pmc_process_samples(int cpu, int soft);
215 static void pmc_release_pmc_descriptor(struct pmc *pmc);
216 static void pmc_remove_owner(struct pmc_owner *po);
217 static void pmc_remove_process_descriptor(struct pmc_process *pp);
218 static void pmc_restore_cpu_binding(struct pmc_binding *pb);
219 static void pmc_save_cpu_binding(struct pmc_binding *pb);
220 static void pmc_select_cpu(int cpu);
221 static int pmc_start(struct pmc *pm);
222 static int pmc_stop(struct pmc *pm);
223 static int pmc_syscall_handler(struct thread *td, void *syscall_args);
224 static void pmc_unlink_target_process(struct pmc *pmc,
225 struct pmc_process *pp);
226 static int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
227 static int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
228 static struct pmc_mdep *pmc_generic_cpu_initialize(void);
229 static void pmc_generic_cpu_finalize(struct pmc_mdep *md);
232 * Kernel tunables and sysctl(8) interface.
235 SYSCTL_DECL(_kern_hwpmc);
237 static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
238 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "callchaindepth", &pmc_callchaindepth);
239 SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_TUN|CTLFLAG_RD,
240 &pmc_callchaindepth, 0, "depth of call chain records");
243 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
244 char pmc_debugstr[PMC_DEBUG_STRSIZE];
245 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
246 sizeof(pmc_debugstr));
247 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
248 CTLTYPE_STRING|CTLFLAG_RW|CTLFLAG_TUN,
249 0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
253 * kern.hwpmc.hashrows -- determines the number of rows in the
254 * of the hash table used to look up threads
257 static int pmc_hashsize = PMC_HASH_SIZE;
258 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "hashsize", &pmc_hashsize);
259 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_TUN|CTLFLAG_RD,
260 &pmc_hashsize, 0, "rows in hash tables");
263 * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
266 static int pmc_nsamples = PMC_NSAMPLES;
267 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nsamples", &pmc_nsamples);
268 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_TUN|CTLFLAG_RD,
269 &pmc_nsamples, 0, "number of PC samples per CPU");
273 * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
276 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
277 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "mtxpoolsize", &pmc_mtxpool_size);
278 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_TUN|CTLFLAG_RD,
279 &pmc_mtxpool_size, 0, "size of spin mutex pool");
283 * security.bsd.unprivileged_syspmcs -- allow non-root processes to
284 * allocate system-wide PMCs.
286 * Allowing unprivileged processes to allocate system PMCs is convenient
287 * if system-wide measurements need to be taken concurrently with other
288 * per-process measurements. This feature is turned off by default.
291 static int pmc_unprivileged_syspmcs = 0;
292 TUNABLE_INT("security.bsd.unprivileged_syspmcs", &pmc_unprivileged_syspmcs);
293 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RW,
294 &pmc_unprivileged_syspmcs, 0,
295 "allow unprivileged process to allocate system PMCs");
298 * Hash function. Discard the lower 2 bits of the pointer since
299 * these are always zero for our uses. The hash multiplier is
300 * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
304 #define _PMC_HM 11400714819323198486u
306 #define _PMC_HM 2654435769u
308 #error Must know the size of 'long' to compile
311 #define PMC_HASH_PTR(P,M) ((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
317 /* The `sysent' for the new syscall */
318 static struct sysent pmc_sysent = {
320 pmc_syscall_handler /* sy_call */
323 static struct syscall_module_data pmc_syscall_mod = {
328 #if (__FreeBSD_version >= 1100000)
336 static moduledata_t pmc_mod = {
338 syscall_module_handler,
342 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
343 MODULE_VERSION(pmc, PMC_VERSION);
346 enum pmc_dbgparse_state {
347 PMCDS_WS, /* in whitespace */
348 PMCDS_MAJOR, /* seen a major keyword */
353 pmc_debugflags_parse(char *newstr, char *fence)
356 struct pmc_debugflags *tmpflags;
357 int error, found, *newbits, tmp;
360 tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK|M_ZERO);
365 for (; p < fence && (c = *p); p++) {
367 /* skip white space */
368 if (c == ' ' || c == '\t')
371 /* look for a keyword followed by "=" */
372 for (q = p; p < fence && (c = *p) && c != '='; p++)
382 /* lookup flag group name */
383 #define DBG_SET_FLAG_MAJ(S,F) \
384 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
385 newbits = &tmpflags->pdb_ ## F;
387 DBG_SET_FLAG_MAJ("cpu", CPU);
388 DBG_SET_FLAG_MAJ("csw", CSW);
389 DBG_SET_FLAG_MAJ("logging", LOG);
390 DBG_SET_FLAG_MAJ("module", MOD);
391 DBG_SET_FLAG_MAJ("md", MDP);
392 DBG_SET_FLAG_MAJ("owner", OWN);
393 DBG_SET_FLAG_MAJ("pmc", PMC);
394 DBG_SET_FLAG_MAJ("process", PRC);
395 DBG_SET_FLAG_MAJ("sampling", SAM);
397 if (newbits == NULL) {
402 p++; /* skip the '=' */
404 /* Now parse the individual flags */
407 for (q = p; p < fence && (c = *p); p++)
408 if (c == ' ' || c == '\t' || c == ',')
411 /* p == fence or c == ws or c == "," or c == 0 */
413 if ((kwlen = p - q) == 0) {
419 #define DBG_SET_FLAG_MIN(S,F) \
420 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
421 tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
423 /* a '*' denotes all possible flags in the group */
424 if (kwlen == 1 && *q == '*')
426 /* look for individual flag names */
427 DBG_SET_FLAG_MIN("allocaterow", ALR);
428 DBG_SET_FLAG_MIN("allocate", ALL);
429 DBG_SET_FLAG_MIN("attach", ATT);
430 DBG_SET_FLAG_MIN("bind", BND);
431 DBG_SET_FLAG_MIN("config", CFG);
432 DBG_SET_FLAG_MIN("exec", EXC);
433 DBG_SET_FLAG_MIN("exit", EXT);
434 DBG_SET_FLAG_MIN("find", FND);
435 DBG_SET_FLAG_MIN("flush", FLS);
436 DBG_SET_FLAG_MIN("fork", FRK);
437 DBG_SET_FLAG_MIN("getbuf", GTB);
438 DBG_SET_FLAG_MIN("hook", PMH);
439 DBG_SET_FLAG_MIN("init", INI);
440 DBG_SET_FLAG_MIN("intr", INT);
441 DBG_SET_FLAG_MIN("linktarget", TLK);
442 DBG_SET_FLAG_MIN("mayberemove", OMR);
443 DBG_SET_FLAG_MIN("ops", OPS);
444 DBG_SET_FLAG_MIN("read", REA);
445 DBG_SET_FLAG_MIN("register", REG);
446 DBG_SET_FLAG_MIN("release", REL);
447 DBG_SET_FLAG_MIN("remove", ORM);
448 DBG_SET_FLAG_MIN("sample", SAM);
449 DBG_SET_FLAG_MIN("scheduleio", SIO);
450 DBG_SET_FLAG_MIN("select", SEL);
451 DBG_SET_FLAG_MIN("signal", SIG);
452 DBG_SET_FLAG_MIN("swi", SWI);
453 DBG_SET_FLAG_MIN("swo", SWO);
454 DBG_SET_FLAG_MIN("start", STA);
455 DBG_SET_FLAG_MIN("stop", STO);
456 DBG_SET_FLAG_MIN("syscall", PMS);
457 DBG_SET_FLAG_MIN("unlinktarget", TUL);
458 DBG_SET_FLAG_MIN("write", WRI);
460 /* unrecognized flag name */
465 if (c == 0 || c == ' ' || c == '\t') { /* end of flag group */
474 /* save the new flag set */
475 bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
478 free(tmpflags, M_PMC);
483 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
485 char *fence, *newstr;
489 (void) arg1; (void) arg2; /* unused parameters */
491 n = sizeof(pmc_debugstr);
492 newstr = malloc(n, M_PMC, M_WAITOK|M_ZERO);
493 (void) strlcpy(newstr, pmc_debugstr, n);
495 error = sysctl_handle_string(oidp, newstr, n, req);
497 /* if there is a new string, parse and copy it */
498 if (error == 0 && req->newptr != NULL) {
499 fence = newstr + (n < req->newlen ? n : req->newlen + 1);
500 if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
501 (void) strlcpy(pmc_debugstr, newstr,
502 sizeof(pmc_debugstr));
512 * Map a row index to a classdep structure and return the adjusted row
513 * index for the PMC class index.
515 static struct pmc_classdep *
516 pmc_ri_to_classdep(struct pmc_mdep *md, int ri, int *adjri)
518 struct pmc_classdep *pcd;
522 KASSERT(ri >= 0 && ri < md->pmd_npmc,
523 ("[pmc,%d] illegal row-index %d", __LINE__, ri));
525 pcd = pmc_rowindex_to_classdep[ri];
528 ("[pmc,%d] ri %d null pcd", __LINE__, ri));
530 *adjri = ri - pcd->pcd_ri;
532 KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
533 ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));
539 * Concurrency Control
541 * The driver manages the following data structures:
543 * - target process descriptors, one per target process
544 * - owner process descriptors (and attached lists), one per owner process
545 * - lookup hash tables for owner and target processes
546 * - PMC descriptors (and attached lists)
547 * - per-cpu hardware state
548 * - the 'hook' variable through which the kernel calls into
550 * - the machine hardware state (managed by the MD layer)
552 * These data structures are accessed from:
554 * - thread context-switch code
555 * - interrupt handlers (possibly on multiple cpus)
556 * - kernel threads on multiple cpus running on behalf of user
557 * processes doing system calls
558 * - this driver's private kernel threads
560 * = Locks and Locking strategy =
562 * The driver uses four locking strategies for its operation:
564 * - The global SX lock "pmc_sx" is used to protect internal
567 * Calls into the module by syscall() start with this lock being
568 * held in exclusive mode. Depending on the requested operation,
569 * the lock may be downgraded to 'shared' mode to allow more
570 * concurrent readers into the module. Calls into the module from
571 * other parts of the kernel acquire the lock in shared mode.
573 * This SX lock is held in exclusive mode for any operations that
574 * modify the linkages between the driver's internal data structures.
576 * The 'pmc_hook' function pointer is also protected by this lock.
577 * It is only examined with the sx lock held in exclusive mode. The
578 * kernel module is allowed to be unloaded only with the sx lock held
579 * in exclusive mode. In normal syscall handling, after acquiring the
580 * pmc_sx lock we first check that 'pmc_hook' is non-null before
581 * proceeding. This prevents races between the thread unloading the module
582 * and other threads seeking to use the module.
584 * - Lookups of target process structures and owner process structures
585 * cannot use the global "pmc_sx" SX lock because these lookups need
586 * to happen during context switches and in other critical sections
587 * where sleeping is not allowed. We protect these lookup tables
588 * with their own private spin-mutexes, "pmc_processhash_mtx" and
589 * "pmc_ownerhash_mtx".
591 * - Interrupt handlers work in a lock free manner. At interrupt
592 * time, handlers look at the PMC pointer (phw->phw_pmc) configured
593 * when the PMC was started. If this pointer is NULL, the interrupt
594 * is ignored after updating driver statistics. We ensure that this
595 * pointer is set (using an atomic operation if necessary) before the
596 * PMC hardware is started. Conversely, this pointer is unset atomically
597 * only after the PMC hardware is stopped.
599 * We ensure that everything needed for the operation of an
600 * interrupt handler is available without it needing to acquire any
601 * locks. We also ensure that a PMC's software state is destroyed only
602 * after the PMC is taken off hardware (on all CPUs).
604 * - Context-switch handling with process-private PMCs needs more
607 * A given process may be the target of multiple PMCs. For example,
608 * PMCATTACH and PMCDETACH may be requested by a process on one CPU
609 * while the target process is running on another. A PMC could also
610 * be getting released because its owner is exiting. We tackle
611 * these situations in the following manner:
613 * - each target process structure 'pmc_process' has an array
614 * of 'struct pmc *' pointers, one for each hardware PMC.
616 * - At context switch IN time, each "target" PMC in RUNNING state
617 * gets started on hardware and a pointer to each PMC is copied into
618 * the per-cpu phw array. The 'runcount' for the PMC is
621 * - At context switch OUT time, all process-virtual PMCs are stopped
622 * on hardware. The saved value is added to the PMCs value field
623 * only if the PMC is in a non-deleted state (the PMCs state could
624 * have changed during the current time slice).
626 * Note that since in-between a switch IN on a processor and a switch
627 * OUT, the PMC could have been released on another CPU. Therefore
628 * context switch OUT always looks at the hardware state to turn
629 * OFF PMCs and will update a PMC's saved value only if reachable
630 * from the target process record.
632 * - OP PMCRELEASE could be called on a PMC at any time (the PMC could
633 * be attached to many processes at the time of the call and could
634 * be active on multiple CPUs).
636 * We prevent further scheduling of the PMC by marking it as in
637 * state 'DELETED'. If the runcount of the PMC is non-zero then
638 * this PMC is currently running on a CPU somewhere. The thread
639 * doing the PMCRELEASE operation waits by repeatedly doing a
640 * pause() till the runcount comes to zero.
642 * The contents of a PMC descriptor (struct pmc) are protected using
643 * a spin-mutex. In order to save space, we use a mutex pool.
645 * In terms of lock types used by witness(4), we use:
646 * - Type "pmc-sx", used by the global SX lock.
647 * - Type "pmc-sleep", for sleep mutexes used by logger threads.
648 * - Type "pmc-per-proc", for protecting PMC owner descriptors.
649 * - Type "pmc-leaf", used for all other spin mutexes.
653 * save the cpu binding of the current kthread
657 pmc_save_cpu_binding(struct pmc_binding *pb)
659 PMCDBG0(CPU,BND,2, "save-cpu");
660 thread_lock(curthread);
661 pb->pb_bound = sched_is_bound(curthread);
662 pb->pb_cpu = curthread->td_oncpu;
663 thread_unlock(curthread);
664 PMCDBG1(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
668 * restore the cpu binding of the current thread
672 pmc_restore_cpu_binding(struct pmc_binding *pb)
674 PMCDBG2(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
675 curthread->td_oncpu, pb->pb_cpu);
676 thread_lock(curthread);
678 sched_bind(curthread, pb->pb_cpu);
680 sched_unbind(curthread);
681 thread_unlock(curthread);
682 PMCDBG0(CPU,BND,2, "restore-cpu done");
686 * move execution over the specified cpu and bind it there.
690 pmc_select_cpu(int cpu)
692 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
693 ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
695 /* Never move to an inactive CPU. */
696 KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
697 "CPU %d", __LINE__, cpu));
699 PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d", cpu);
700 thread_lock(curthread);
701 sched_bind(curthread, cpu);
702 thread_unlock(curthread);
704 KASSERT(curthread->td_oncpu == cpu,
705 ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
706 cpu, curthread->td_oncpu));
708 PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
712 * Force a context switch.
714 * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
715 * guaranteed to force a context switch.
719 pmc_force_context_switch(void)
726 * Get the file name for an executable. This is a simple wrapper
727 * around vn_fullpath(9).
731 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
734 *fullpath = "unknown";
736 vn_fullpath(curthread, v, fullpath, freepath);
740 * remove an process owning PMCs
744 pmc_remove_owner(struct pmc_owner *po)
746 struct pmc *pm, *tmp;
748 sx_assert(&pmc_sx, SX_XLOCKED);
750 PMCDBG1(OWN,ORM,1, "remove-owner po=%p", po);
752 /* Remove descriptor from the owner hash table */
753 LIST_REMOVE(po, po_next);
755 /* release all owned PMC descriptors */
756 LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
757 PMCDBG1(OWN,ORM,2, "pmc=%p", pm);
758 KASSERT(pm->pm_owner == po,
759 ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
761 pmc_release_pmc_descriptor(pm); /* will unlink from the list */
762 pmc_destroy_pmc_descriptor(pm);
765 KASSERT(po->po_sscount == 0,
766 ("[pmc,%d] SS count not zero", __LINE__));
767 KASSERT(LIST_EMPTY(&po->po_pmcs),
768 ("[pmc,%d] PMC list not empty", __LINE__));
770 /* de-configure the log file if present */
771 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
772 pmclog_deconfigure_log(po);
776 * remove an owner process record if all conditions are met.
780 pmc_maybe_remove_owner(struct pmc_owner *po)
783 PMCDBG1(OWN,OMR,1, "maybe-remove-owner po=%p", po);
786 * Remove owner record if
787 * - this process does not own any PMCs
788 * - this process has not allocated a system-wide sampling buffer
791 if (LIST_EMPTY(&po->po_pmcs) &&
792 ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
793 pmc_remove_owner(po);
794 pmc_destroy_owner_descriptor(po);
799 * Add an association between a target process and a PMC.
803 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
806 struct pmc_target *pt;
808 sx_assert(&pmc_sx, SX_XLOCKED);
810 KASSERT(pm != NULL && pp != NULL,
811 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
812 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
813 ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
814 __LINE__, pm, pp->pp_proc->p_pid));
815 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1),
816 ("[pmc,%d] Illegal reference count %d for process record %p",
817 __LINE__, pp->pp_refcnt, (void *) pp));
819 ri = PMC_TO_ROWINDEX(pm);
821 PMCDBG3(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
825 LIST_FOREACH(pt, &pm->pm_targets, pt_next)
826 if (pt->pt_process == pp)
827 KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
831 pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK|M_ZERO);
834 LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
836 atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
839 if (pm->pm_owner->po_owner == pp->pp_proc)
840 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
843 * Initialize the per-process values at this row index.
845 pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
846 pm->pm_sc.pm_reloadcount : 0;
853 * Removes the association between a target process and a PMC.
857 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
861 struct pmc_target *ptgt;
863 sx_assert(&pmc_sx, SX_XLOCKED);
865 KASSERT(pm != NULL && pp != NULL,
866 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
868 KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc,
869 ("[pmc,%d] Illegal ref count %d on process record %p",
870 __LINE__, pp->pp_refcnt, (void *) pp));
872 ri = PMC_TO_ROWINDEX(pm);
874 PMCDBG3(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
877 KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
878 ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
879 ri, pm, pp->pp_pmcs[ri].pp_pmc));
881 pp->pp_pmcs[ri].pp_pmc = NULL;
882 pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
884 /* Remove owner-specific flags */
885 if (pm->pm_owner->po_owner == pp->pp_proc) {
886 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
887 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
892 /* Remove the target process from the PMC structure */
893 LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
894 if (ptgt->pt_process == pp)
897 KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
898 "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
900 LIST_REMOVE(ptgt, pt_next);
903 /* if the PMC now lacks targets, send the owner a SIGIO */
904 if (LIST_EMPTY(&pm->pm_targets)) {
905 p = pm->pm_owner->po_owner;
907 kern_psignal(p, SIGIO);
910 PMCDBG2(PRC,SIG,2, "signalling proc=%p signal=%d", p,
916 * Check if PMC 'pm' may be attached to target process 't'.
920 pmc_can_attach(struct pmc *pm, struct proc *t)
922 struct proc *o; /* pmc owner */
923 struct ucred *oc, *tc; /* owner, target credentials */
924 int decline_attach, i;
927 * A PMC's owner can always attach that PMC to itself.
930 if ((o = pm->pm_owner->po_owner) == t)
944 * The effective uid of the PMC owner should match at least one
945 * of the {effective,real,saved} uids of the target process.
948 decline_attach = oc->cr_uid != tc->cr_uid &&
949 oc->cr_uid != tc->cr_svuid &&
950 oc->cr_uid != tc->cr_ruid;
953 * Every one of the target's group ids, must be in the owner's
956 for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
957 decline_attach = !groupmember(tc->cr_groups[i], oc);
959 /* check the read and saved gids too */
960 if (decline_attach == 0)
961 decline_attach = !groupmember(tc->cr_rgid, oc) ||
962 !groupmember(tc->cr_svgid, oc);
967 return !decline_attach;
971 * Attach a process to a PMC.
975 pmc_attach_one_process(struct proc *p, struct pmc *pm)
978 char *fullpath, *freepath;
979 struct pmc_process *pp;
981 sx_assert(&pmc_sx, SX_XLOCKED);
983 PMCDBG5(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
984 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
987 * Locate the process descriptor corresponding to process 'p',
988 * allocating space as needed.
990 * Verify that rowindex 'pm_rowindex' is free in the process
993 * If not, allocate space for a descriptor and link the
994 * process descriptor and PMC.
996 ri = PMC_TO_ROWINDEX(pm);
998 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
1001 if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
1004 if (pp->pp_pmcs[ri].pp_pmc != NULL)
1007 pmc_link_target_process(pm, pp);
1009 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
1010 (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
1011 pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
1013 pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
1015 /* issue an attach event to a configured log file */
1016 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
1017 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1018 if (p->p_flag & P_KTHREAD) {
1019 fullpath = kernelname;
1022 pmclog_process_pmcattach(pm, p->p_pid, fullpath);
1024 free(freepath, M_TEMP);
1025 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1026 pmc_log_process_mappings(pm->pm_owner, p);
1028 /* mark process as using HWPMCs */
1030 p->p_flag |= P_HWPMC;
1037 * Attach a process and optionally its children
1041 pmc_attach_process(struct proc *p, struct pmc *pm)
1046 sx_assert(&pmc_sx, SX_XLOCKED);
1048 PMCDBG5(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1049 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1053 * If this PMC successfully allowed a GETMSR operation
1054 * in the past, disallow further ATTACHes.
1057 if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1060 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1061 return pmc_attach_one_process(p, pm);
1064 * Traverse all child processes, attaching them to
1068 sx_slock(&proctree_lock);
1073 if ((error = pmc_attach_one_process(p, pm)) != 0)
1075 if (!LIST_EMPTY(&p->p_children))
1076 p = LIST_FIRST(&p->p_children);
1080 if (LIST_NEXT(p, p_sibling)) {
1081 p = LIST_NEXT(p, p_sibling);
1089 (void) pmc_detach_process(top, pm);
1092 sx_sunlock(&proctree_lock);
1097 * Detach a process from a PMC. If there are no other PMCs tracking
1098 * this process, remove the process structure from its hash table. If
1099 * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1103 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1106 struct pmc_process *pp;
1108 sx_assert(&pmc_sx, SX_XLOCKED);
1111 ("[pmc,%d] null pm pointer", __LINE__));
1113 ri = PMC_TO_ROWINDEX(pm);
1115 PMCDBG6(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1116 pm, ri, p, p->p_pid, p->p_comm, flags);
1118 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1121 if (pp->pp_pmcs[ri].pp_pmc != pm)
1124 pmc_unlink_target_process(pm, pp);
1126 /* Issue a detach entry if a log file is configured */
1127 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1128 pmclog_process_pmcdetach(pm, p->p_pid);
1131 * If there are no PMCs targetting this process, we remove its
1132 * descriptor from the target hash table and unset the P_HWPMC
1133 * flag in the struct proc.
1135 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1136 ("[pmc,%d] Illegal refcnt %d for process struct %p",
1137 __LINE__, pp->pp_refcnt, pp));
1139 if (pp->pp_refcnt != 0) /* still a target of some PMC */
1142 pmc_remove_process_descriptor(pp);
1144 if (flags & PMC_FLAG_REMOVE)
1148 p->p_flag &= ~P_HWPMC;
1155 * Detach a process and optionally its descendants from a PMC.
1159 pmc_detach_process(struct proc *p, struct pmc *pm)
1163 sx_assert(&pmc_sx, SX_XLOCKED);
1165 PMCDBG5(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1166 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1168 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1169 return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1172 * Traverse all children, detaching them from this PMC. We
1173 * ignore errors since we could be detaching a PMC from a
1174 * partially attached proc tree.
1177 sx_slock(&proctree_lock);
1182 (void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1184 if (!LIST_EMPTY(&p->p_children))
1185 p = LIST_FIRST(&p->p_children);
1189 if (LIST_NEXT(p, p_sibling)) {
1190 p = LIST_NEXT(p, p_sibling);
1198 sx_sunlock(&proctree_lock);
1200 if (LIST_EMPTY(&pm->pm_targets))
1201 pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1208 * Thread context switch IN
1212 pmc_process_csw_in(struct thread *td)
1215 unsigned int adjri, ri;
1220 pmc_value_t newvalue;
1221 struct pmc_process *pp;
1222 struct pmc_classdep *pcd;
1226 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1229 KASSERT(pp->pp_proc == td->td_proc,
1230 ("[pmc,%d] not my thread state", __LINE__));
1232 critical_enter(); /* no preemption from this point */
1234 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1236 PMCDBG5(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1237 p->p_pid, p->p_comm, pp);
1239 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1240 ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
1244 for (ri = 0; ri < md->pmd_npmc; ri++) {
1246 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1249 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1250 ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1251 __LINE__, PMC_TO_MODE(pm)));
1253 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1254 ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1255 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1258 * Only PMCs that are marked as 'RUNNING' need
1259 * be placed on hardware.
1262 if (pm->pm_state != PMC_STATE_RUNNING)
1265 /* increment PMC runcount */
1266 atomic_add_rel_int(&pm->pm_runcount, 1);
1268 /* configure the HWPMC we are going to use. */
1269 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1270 pcd->pcd_config_pmc(cpu, adjri, pm);
1272 phw = pc->pc_hwpmcs[ri];
1274 KASSERT(phw != NULL,
1275 ("[pmc,%d] null hw pointer", __LINE__));
1277 KASSERT(phw->phw_pmc == pm,
1278 ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1282 * Write out saved value and start the PMC.
1284 * Sampling PMCs use a per-process value, while
1285 * counting mode PMCs use a per-pmc value that is
1286 * inherited across descendants.
1288 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1289 mtx_pool_lock_spin(pmc_mtxpool, pm);
1290 newvalue = PMC_PCPU_SAVED(cpu,ri) =
1291 pp->pp_pmcs[ri].pp_pmcval;
1292 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1294 KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1295 ("[pmc,%d] illegal mode=%d", __LINE__,
1297 mtx_pool_lock_spin(pmc_mtxpool, pm);
1298 newvalue = PMC_PCPU_SAVED(cpu, ri) =
1299 pm->pm_gv.pm_savedvalue;
1300 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1303 PMCDBG3(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1305 pcd->pcd_write_pmc(cpu, adjri, newvalue);
1306 pcd->pcd_start_pmc(cpu, adjri);
1310 * perform any other architecture/cpu dependent thread
1311 * switch-in actions.
1314 (void) (*md->pmd_switch_in)(pc, pp);
1321 * Thread context switch OUT.
1325 pmc_process_csw_out(struct thread *td)
1333 pmc_value_t newvalue;
1334 unsigned int adjri, ri;
1335 struct pmc_process *pp;
1336 struct pmc_classdep *pcd;
1340 * Locate our process descriptor; this may be NULL if
1341 * this process is exiting and we have already removed
1342 * the process from the target process table.
1344 * Note that due to kernel preemption, multiple
1345 * context switches may happen while the process is
1348 * Note also that if the target process cannot be
1349 * found we still need to deconfigure any PMCs that
1350 * are currently running on hardware.
1354 pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1362 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1364 PMCDBG5(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1365 p->p_pid, p->p_comm, pp);
1367 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1368 ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1373 * When a PMC gets unlinked from a target PMC, it will
1374 * be removed from the target's pp_pmc[] array.
1376 * However, on a MP system, the target could have been
1377 * executing on another CPU at the time of the unlink.
1378 * So, at context switch OUT time, we need to look at
1379 * the hardware to determine if a PMC is scheduled on
1383 for (ri = 0; ri < md->pmd_npmc; ri++) {
1385 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1387 (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
1389 if (pm == NULL) /* nothing at this row index */
1392 mode = PMC_TO_MODE(pm);
1393 if (!PMC_IS_VIRTUAL_MODE(mode))
1394 continue; /* not a process virtual PMC */
1396 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1397 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1398 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1400 /* Stop hardware if not already stopped */
1401 if (pm->pm_stalled == 0)
1402 pcd->pcd_stop_pmc(cpu, adjri);
1404 /* reduce this PMC's runcount */
1405 atomic_subtract_rel_int(&pm->pm_runcount, 1);
1408 * If this PMC is associated with this process,
1412 if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1414 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1415 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1416 pm, ri, pp->pp_pmcs[ri].pp_pmc));
1418 KASSERT(pp->pp_refcnt > 0,
1419 ("[pmc,%d] pp refcnt = %d", __LINE__,
1422 pcd->pcd_read_pmc(cpu, adjri, &newvalue);
1424 tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1426 PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
1429 if (mode == PMC_MODE_TS) {
1432 * For sampling process-virtual PMCs,
1433 * we expect the count to be
1434 * decreasing as the 'value'
1435 * programmed into the PMC is the
1436 * number of events to be seen till
1437 * the next sampling interrupt.
1440 tmp += pm->pm_sc.pm_reloadcount;
1441 mtx_pool_lock_spin(pmc_mtxpool, pm);
1442 pp->pp_pmcs[ri].pp_pmcval -= tmp;
1443 if ((int64_t) pp->pp_pmcs[ri].pp_pmcval <= 0)
1444 pp->pp_pmcs[ri].pp_pmcval +=
1445 pm->pm_sc.pm_reloadcount;
1446 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1451 * For counting process-virtual PMCs,
1452 * we expect the count to be
1453 * increasing monotonically, modulo a 64
1456 KASSERT((int64_t) tmp >= 0,
1457 ("[pmc,%d] negative increment cpu=%d "
1458 "ri=%d newvalue=%jx saved=%jx "
1459 "incr=%jx", __LINE__, cpu, ri,
1460 newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1462 mtx_pool_lock_spin(pmc_mtxpool, pm);
1463 pm->pm_gv.pm_savedvalue += tmp;
1464 pp->pp_pmcs[ri].pp_pmcval += tmp;
1465 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1467 if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1468 pmclog_process_proccsw(pm, pp, tmp);
1472 /* mark hardware as free */
1473 pcd->pcd_config_pmc(cpu, adjri, NULL);
1477 * perform any other architecture/cpu dependent thread
1478 * switch out functions.
1481 (void) (*md->pmd_switch_out)(pc, pp);
1487 * A mapping change for a process.
1491 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1495 char *fullpath, *freepath;
1496 const struct pmc *pm;
1497 struct pmc_owner *po;
1498 const struct pmc_process *pp;
1500 freepath = fullpath = NULL;
1501 pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1503 pid = td->td_proc->p_pid;
1505 /* Inform owners of all system-wide sampling PMCs. */
1506 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1507 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1508 pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1510 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1514 * Inform sampling PMC owners tracking this process.
1516 for (ri = 0; ri < md->pmd_npmc; ri++)
1517 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1518 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1519 pmclog_process_map_in(pm->pm_owner,
1520 pid, pkm->pm_address, fullpath);
1524 free(freepath, M_TEMP);
1529 * Log an munmap request.
1533 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1537 struct pmc_owner *po;
1538 const struct pmc *pm;
1539 const struct pmc_process *pp;
1541 pid = td->td_proc->p_pid;
1543 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1544 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1545 pmclog_process_map_out(po, pid, pkm->pm_address,
1546 pkm->pm_address + pkm->pm_size);
1548 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1551 for (ri = 0; ri < md->pmd_npmc; ri++)
1552 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1553 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1554 pmclog_process_map_out(pm->pm_owner, pid,
1555 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1559 * Log mapping information about the kernel.
1563 pmc_log_kernel_mappings(struct pmc *pm)
1565 struct pmc_owner *po;
1566 struct pmckern_map_in *km, *kmbase;
1568 sx_assert(&pmc_sx, SX_LOCKED);
1569 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1570 ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1571 __LINE__, (void *) pm));
1575 if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1579 * Log the current set of kernel modules.
1581 kmbase = linker_hwpmc_list_objects();
1582 for (km = kmbase; km->pm_file != NULL; km++) {
1583 PMCDBG2(LOG,REG,1,"%s %p", (char *) km->pm_file,
1584 (void *) km->pm_address);
1585 pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1588 free(kmbase, M_LINKER);
1590 po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1594 * Log the mappings for a single process.
1598 pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1603 vm_map_entry_t entry;
1604 vm_offset_t last_end;
1605 u_int last_timestamp;
1606 struct vnode *last_vp;
1607 vm_offset_t start_addr;
1608 vm_object_t obj, lobj, tobj;
1609 char *fullpath, *freepath;
1612 last_end = (vm_offset_t) 0;
1613 fullpath = freepath = NULL;
1615 if ((vm = vmspace_acquire_ref(p)) == NULL)
1619 vm_map_lock_read(map);
1621 for (entry = map->header.next; entry != &map->header; entry = entry->next) {
1623 if (entry == NULL) {
1624 PMCDBG2(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly "
1625 "NULL! pid=%d vm_map=%p\n", p->p_pid, map);
1630 * We only care about executable map entries.
1632 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) ||
1633 !(entry->protection & VM_PROT_EXECUTE) ||
1634 (entry->object.vm_object == NULL)) {
1638 obj = entry->object.vm_object;
1639 VM_OBJECT_RLOCK(obj);
1642 * Walk the backing_object list to find the base
1643 * (non-shadowed) vm_object.
1645 for (lobj = tobj = obj; tobj != NULL; tobj = tobj->backing_object) {
1647 VM_OBJECT_RLOCK(tobj);
1649 VM_OBJECT_RUNLOCK(lobj);
1654 * At this point lobj is the base vm_object and it is locked.
1657 PMCDBG3(LOG,OPS,2, "hwpmc: lobj unexpectedly NULL! pid=%d "
1658 "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj);
1659 VM_OBJECT_RUNLOCK(obj);
1663 if (lobj->type != OBJT_VNODE || lobj->handle == NULL) {
1665 VM_OBJECT_RUNLOCK(lobj);
1666 VM_OBJECT_RUNLOCK(obj);
1671 * Skip contiguous regions that point to the same
1672 * vnode, so we don't emit redundant MAP-IN
1675 if (entry->start == last_end && lobj->handle == last_vp) {
1676 last_end = entry->end;
1678 VM_OBJECT_RUNLOCK(lobj);
1679 VM_OBJECT_RUNLOCK(obj);
1684 * We don't want to keep the proc's vm_map or this
1685 * vm_object locked while we walk the pathname, since
1686 * vn_fullpath() can sleep. However, if we drop the
1687 * lock, it's possible for concurrent activity to
1688 * modify the vm_map list. To protect against this,
1689 * we save the vm_map timestamp before we release the
1690 * lock, and check it after we reacquire the lock
1693 start_addr = entry->start;
1694 last_end = entry->end;
1695 last_timestamp = map->timestamp;
1696 vm_map_unlock_read(map);
1701 VM_OBJECT_RUNLOCK(lobj);
1703 VM_OBJECT_RUNLOCK(obj);
1706 pmc_getfilename(vp, &fullpath, &freepath);
1712 pmclog_process_map_in(po, p->p_pid, start_addr, fullpath);
1714 free(freepath, M_TEMP);
1716 vm_map_lock_read(map);
1719 * If our saved timestamp doesn't match, this means
1720 * that the vm_map was modified out from under us and
1721 * we can't trust our current "entry" pointer. Do a
1722 * new lookup for this entry. If there is no entry
1723 * for this address range, vm_map_lookup_entry() will
1724 * return the previous one, so we always want to go to
1725 * entry->next on the next loop iteration.
1727 * There is an edge condition here that can occur if
1728 * there is no entry at or before this address. In
1729 * this situation, vm_map_lookup_entry returns
1730 * &map->header, which would cause our loop to abort
1731 * without processing the rest of the map. However,
1732 * in practice this will never happen for process
1733 * vm_map. This is because the executable's text
1734 * segment is the first mapping in the proc's address
1735 * space, and this mapping is never removed until the
1736 * process exits, so there will always be a non-header
1737 * entry at or before the requested address for
1738 * vm_map_lookup_entry to return.
1740 if (map->timestamp != last_timestamp)
1741 vm_map_lookup_entry(map, last_end - 1, &entry);
1744 vm_map_unlock_read(map);
1750 * Log mappings for all processes in the system.
1754 pmc_log_all_process_mappings(struct pmc_owner *po)
1756 struct proc *p, *top;
1758 sx_assert(&pmc_sx, SX_XLOCKED);
1760 if ((p = pfind(1)) == NULL)
1761 panic("[pmc,%d] Cannot find init", __LINE__);
1765 sx_slock(&proctree_lock);
1770 pmc_log_process_mappings(po, p);
1771 if (!LIST_EMPTY(&p->p_children))
1772 p = LIST_FIRST(&p->p_children);
1776 if (LIST_NEXT(p, p_sibling)) {
1777 p = LIST_NEXT(p, p_sibling);
1784 sx_sunlock(&proctree_lock);
1788 * The 'hook' invoked from the kernel proper
1793 const char *pmc_hooknames[] = {
1794 /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1811 pmc_hook_handler(struct thread *td, int function, void *arg)
1814 PMCDBG4(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1815 pmc_hooknames[function], arg);
1824 case PMC_FN_PROCESS_EXEC:
1826 char *fullpath, *freepath;
1828 int is_using_hwpmcs;
1831 struct pmc_owner *po;
1832 struct pmc_process *pp;
1833 struct pmckern_procexec *pk;
1835 sx_assert(&pmc_sx, SX_XLOCKED);
1838 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1840 pk = (struct pmckern_procexec *) arg;
1842 /* Inform owners of SS mode PMCs of the exec event. */
1843 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1844 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1845 pmclog_process_procexec(po, PMC_ID_INVALID,
1846 p->p_pid, pk->pm_entryaddr, fullpath);
1849 is_using_hwpmcs = p->p_flag & P_HWPMC;
1852 if (!is_using_hwpmcs) {
1854 free(freepath, M_TEMP);
1859 * PMCs are not inherited across an exec(): remove any
1860 * PMCs that this process is the owner of.
1863 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1864 pmc_remove_owner(po);
1865 pmc_destroy_owner_descriptor(po);
1869 * If the process being exec'ed is not the target of any
1872 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1874 free(freepath, M_TEMP);
1879 * Log the exec event to all monitoring owners. Skip
1880 * owners who have already recieved the event because
1881 * they had system sampling PMCs active.
1883 for (ri = 0; ri < md->pmd_npmc; ri++)
1884 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1886 if (po->po_sscount == 0 &&
1887 po->po_flags & PMC_PO_OWNS_LOGFILE)
1888 pmclog_process_procexec(po, pm->pm_id,
1889 p->p_pid, pk->pm_entryaddr,
1894 free(freepath, M_TEMP);
1897 PMCDBG4(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1898 p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1900 if (pk->pm_credentialschanged == 0) /* no change */
1904 * If the newly exec()'ed process has a different credential
1905 * than before, allow it to be the target of a PMC only if
1906 * the PMC's owner has sufficient priviledge.
1909 for (ri = 0; ri < md->pmd_npmc; ri++)
1910 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1911 if (pmc_can_attach(pm, td->td_proc) != 0)
1912 pmc_detach_one_process(td->td_proc,
1915 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1916 ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1917 pp->pp_refcnt, pp));
1920 * If this process is no longer the target of any
1921 * PMCs, we can remove the process entry and free
1925 if (pp->pp_refcnt == 0) {
1926 pmc_remove_process_descriptor(pp);
1935 pmc_process_csw_in(td);
1938 case PMC_FN_CSW_OUT:
1939 pmc_process_csw_out(td);
1943 * Process accumulated PC samples.
1945 * This function is expected to be called by hardclock() for
1946 * each CPU that has accumulated PC samples.
1948 * This function is to be executed on the CPU whose samples
1949 * are being processed.
1951 case PMC_FN_DO_SAMPLES:
1954 * Clear the cpu specific bit in the CPU mask before
1955 * do the rest of the processing. If the NMI handler
1956 * gets invoked after the "atomic_clear_int()" call
1957 * below but before "pmc_process_samples()" gets
1958 * around to processing the interrupt, then we will
1959 * come back here at the next hardclock() tick (and
1960 * may find nothing to do if "pmc_process_samples()"
1961 * had already processed the interrupt). We don't
1962 * lose the interrupt sample.
1964 CPU_CLR_ATOMIC(PCPU_GET(cpuid), &pmc_cpumask);
1965 pmc_process_samples(PCPU_GET(cpuid), PMC_HR);
1966 pmc_process_samples(PCPU_GET(cpuid), PMC_SR);
1970 sx_assert(&pmc_sx, SX_LOCKED);
1971 pmc_process_mmap(td, (struct pmckern_map_in *) arg);
1975 sx_assert(&pmc_sx, SX_LOCKED);
1976 pmc_process_munmap(td, (struct pmckern_map_out *) arg);
1979 case PMC_FN_USER_CALLCHAIN:
1981 * Record a call chain.
1983 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
1986 pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
1987 (struct trapframe *) arg);
1988 td->td_pflags &= ~TDP_CALLCHAIN;
1991 case PMC_FN_USER_CALLCHAIN_SOFT:
1993 * Record a call chain.
1995 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
1997 pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_SR,
1998 (struct trapframe *) arg);
1999 td->td_pflags &= ~TDP_CALLCHAIN;
2002 case PMC_FN_SOFT_SAMPLING:
2004 * Call soft PMC sampling intr.
2006 pmc_soft_intr((struct pmckern_soft *) arg);
2011 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
2021 * allocate a 'struct pmc_owner' descriptor in the owner hash table.
2024 static struct pmc_owner *
2025 pmc_allocate_owner_descriptor(struct proc *p)
2028 struct pmc_owner *po;
2029 struct pmc_ownerhash *poh;
2031 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2032 poh = &pmc_ownerhash[hindex];
2034 /* allocate space for N pointers and one descriptor struct */
2035 po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK|M_ZERO);
2037 LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
2039 TAILQ_INIT(&po->po_logbuffers);
2040 mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
2042 PMCDBG4(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
2043 p, p->p_pid, p->p_comm, po);
2049 pmc_destroy_owner_descriptor(struct pmc_owner *po)
2052 PMCDBG4(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
2053 po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
2055 mtx_destroy(&po->po_mtx);
2060 * find the descriptor corresponding to process 'p', adding or removing it
2061 * as specified by 'mode'.
2064 static struct pmc_process *
2065 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
2068 struct pmc_process *pp, *ppnew;
2069 struct pmc_processhash *pph;
2071 hindex = PMC_HASH_PTR(p, pmc_processhashmask);
2072 pph = &pmc_processhash[hindex];
2077 * Pre-allocate memory in the FIND_ALLOCATE case since we
2078 * cannot call malloc(9) once we hold a spin lock.
2080 if (mode & PMC_FLAG_ALLOCATE)
2081 ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
2082 sizeof(struct pmc_targetstate), M_PMC, M_WAITOK|M_ZERO);
2084 mtx_lock_spin(&pmc_processhash_mtx);
2085 LIST_FOREACH(pp, pph, pp_next)
2086 if (pp->pp_proc == p)
2089 if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
2090 LIST_REMOVE(pp, pp_next);
2092 if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
2095 LIST_INSERT_HEAD(pph, ppnew, pp_next);
2099 mtx_unlock_spin(&pmc_processhash_mtx);
2101 if (pp != NULL && ppnew != NULL)
2108 * remove a process descriptor from the process hash table.
2112 pmc_remove_process_descriptor(struct pmc_process *pp)
2114 KASSERT(pp->pp_refcnt == 0,
2115 ("[pmc,%d] Removing process descriptor %p with count %d",
2116 __LINE__, pp, pp->pp_refcnt));
2118 mtx_lock_spin(&pmc_processhash_mtx);
2119 LIST_REMOVE(pp, pp_next);
2120 mtx_unlock_spin(&pmc_processhash_mtx);
2125 * find an owner descriptor corresponding to proc 'p'
2128 static struct pmc_owner *
2129 pmc_find_owner_descriptor(struct proc *p)
2132 struct pmc_owner *po;
2133 struct pmc_ownerhash *poh;
2135 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2136 poh = &pmc_ownerhash[hindex];
2139 LIST_FOREACH(po, poh, po_next)
2140 if (po->po_owner == p)
2143 PMCDBG5(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2144 "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2150 * pmc_allocate_pmc_descriptor
2152 * Allocate a pmc descriptor and initialize its
2157 pmc_allocate_pmc_descriptor(void)
2161 pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK|M_ZERO);
2163 PMCDBG1(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2169 * Destroy a pmc descriptor.
2173 pmc_destroy_pmc_descriptor(struct pmc *pm)
2176 KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2177 pm->pm_state == PMC_STATE_FREE,
2178 ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2179 KASSERT(LIST_EMPTY(&pm->pm_targets),
2180 ("[pmc,%d] destroying pmc with targets", __LINE__));
2181 KASSERT(pm->pm_owner == NULL,
2182 ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2183 KASSERT(pm->pm_runcount == 0,
2184 ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
2191 pmc_wait_for_pmc_idle(struct pmc *pm)
2194 volatile int maxloop;
2196 maxloop = 100 * pmc_cpu_max();
2199 * Loop (with a forced context switch) till the PMC's runcount
2200 * comes down to zero.
2202 while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
2205 KASSERT(maxloop > 0,
2206 ("[pmc,%d] (ri%d, rc%d) waiting too long for "
2207 "pmc to be free", __LINE__,
2208 PMC_TO_ROWINDEX(pm), pm->pm_runcount));
2210 pmc_force_context_switch();
2215 * This function does the following things:
2217 * - detaches the PMC from hardware
2218 * - unlinks all target threads that were attached to it
2219 * - removes the PMC from its owner's list
2220 * - destroys the PMC private mutex
2222 * Once this function completes, the given pmc pointer can be freed by
2223 * calling pmc_destroy_pmc_descriptor().
2227 pmc_release_pmc_descriptor(struct pmc *pm)
2231 u_int adjri, ri, cpu;
2232 struct pmc_owner *po;
2233 struct pmc_binding pb;
2234 struct pmc_process *pp;
2235 struct pmc_classdep *pcd;
2236 struct pmc_target *ptgt, *tmp;
2238 sx_assert(&pmc_sx, SX_XLOCKED);
2240 KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2242 ri = PMC_TO_ROWINDEX(pm);
2243 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2244 mode = PMC_TO_MODE(pm);
2246 PMCDBG3(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2250 * First, we take the PMC off hardware.
2253 if (PMC_IS_SYSTEM_MODE(mode)) {
2256 * A system mode PMC runs on a specific CPU. Switch
2257 * to this CPU and turn hardware off.
2259 pmc_save_cpu_binding(&pb);
2261 cpu = PMC_TO_CPU(pm);
2263 pmc_select_cpu(cpu);
2265 /* switch off non-stalled CPUs */
2266 if (pm->pm_state == PMC_STATE_RUNNING &&
2267 pm->pm_stalled == 0) {
2269 phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2271 KASSERT(phw->phw_pmc == pm,
2272 ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2273 __LINE__, ri, phw->phw_pmc, pm));
2274 PMCDBG2(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2277 pcd->pcd_stop_pmc(cpu, adjri);
2281 PMCDBG2(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2284 pcd->pcd_config_pmc(cpu, adjri, NULL);
2287 /* adjust the global and process count of SS mode PMCs */
2288 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2291 if (po->po_sscount == 0) {
2292 atomic_subtract_rel_int(&pmc_ss_count, 1);
2293 LIST_REMOVE(po, po_ssnext);
2297 pm->pm_state = PMC_STATE_DELETED;
2299 pmc_restore_cpu_binding(&pb);
2302 * We could have references to this PMC structure in
2303 * the per-cpu sample queues. Wait for the queue to
2306 pmc_wait_for_pmc_idle(pm);
2308 } else if (PMC_IS_VIRTUAL_MODE(mode)) {
2311 * A virtual PMC could be running on multiple CPUs at
2314 * By marking its state as DELETED, we ensure that
2315 * this PMC is never further scheduled on hardware.
2317 * Then we wait till all CPUs are done with this PMC.
2319 pm->pm_state = PMC_STATE_DELETED;
2322 /* Wait for the PMCs runcount to come to zero. */
2323 pmc_wait_for_pmc_idle(pm);
2326 * At this point the PMC is off all CPUs and cannot be
2327 * freshly scheduled onto a CPU. It is now safe to
2328 * unlink all targets from this PMC. If a
2329 * process-record's refcount falls to zero, we remove
2330 * it from the hash table. The module-wide SX lock
2331 * protects us from races.
2333 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2334 pp = ptgt->pt_process;
2335 pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2337 PMCDBG1(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2340 * If the target process record shows that no
2341 * PMCs are attached to it, reclaim its space.
2344 if (pp->pp_refcnt == 0) {
2345 pmc_remove_process_descriptor(pp);
2350 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2355 * Release any MD resources
2357 (void) pcd->pcd_release_pmc(cpu, adjri, pm);
2360 * Update row disposition
2363 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2364 PMC_UNMARK_ROW_STANDALONE(ri);
2366 PMC_UNMARK_ROW_THREAD(ri);
2368 /* unlink from the owner's list */
2370 LIST_REMOVE(pm, pm_next);
2371 pm->pm_owner = NULL;
2376 * Register an owner and a pmc.
2380 pmc_register_owner(struct proc *p, struct pmc *pmc)
2382 struct pmc_owner *po;
2384 sx_assert(&pmc_sx, SX_XLOCKED);
2386 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2387 if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2390 KASSERT(pmc->pm_owner == NULL,
2391 ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2394 LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2397 p->p_flag |= P_HWPMC;
2400 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2401 pmclog_process_pmcallocate(pmc);
2403 PMCDBG2(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2410 * Return the current row disposition:
2412 * > 0 => PROCESS MODE
2413 * < 0 => SYSTEM MODE
2417 pmc_getrowdisp(int ri)
2419 return pmc_pmcdisp[ri];
2423 * Check if a PMC at row index 'ri' can be allocated to the current
2426 * Allocation can fail if:
2427 * - the current process is already being profiled by a PMC at index 'ri',
2428 * attached to it via OP_PMCATTACH.
2429 * - the current process has already allocated a PMC at index 'ri'
2434 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2438 struct pmc_owner *po;
2439 struct pmc_process *pp;
2441 PMCDBG5(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2442 "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2445 * We shouldn't have already allocated a process-mode PMC at
2448 * We shouldn't have allocated a system-wide PMC on the same
2451 if ((po = pmc_find_owner_descriptor(p)) != NULL)
2452 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2453 if (PMC_TO_ROWINDEX(pm) == ri) {
2454 mode = PMC_TO_MODE(pm);
2455 if (PMC_IS_VIRTUAL_MODE(mode))
2457 if (PMC_IS_SYSTEM_MODE(mode) &&
2458 (int) PMC_TO_CPU(pm) == cpu)
2464 * We also shouldn't be the target of any PMC at this index
2465 * since otherwise a PMC_ATTACH to ourselves will fail.
2467 if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2468 if (pp->pp_pmcs[ri].pp_pmc)
2471 PMCDBG4(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2472 p, p->p_pid, p->p_comm, ri);
2478 * Check if a given PMC at row index 'ri' can be currently used in
2483 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2487 sx_assert(&pmc_sx, SX_XLOCKED);
2489 PMCDBG2(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2491 if (PMC_IS_SYSTEM_MODE(mode))
2492 disp = PMC_DISP_STANDALONE;
2494 disp = PMC_DISP_THREAD;
2497 * check disposition for PMC row 'ri':
2499 * Expected disposition Row-disposition Result
2501 * STANDALONE STANDALONE or FREE proceed
2502 * STANDALONE THREAD fail
2503 * THREAD THREAD or FREE proceed
2504 * THREAD STANDALONE fail
2507 if (!PMC_ROW_DISP_IS_FREE(ri) &&
2508 !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2509 !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2516 PMCDBG2(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2523 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2527 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2531 KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2532 ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2533 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2535 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2536 if (pm->pm_id == pmcid)
2543 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2547 struct pmc_owner *po;
2549 PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid);
2551 if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2554 if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2557 PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2568 pmc_start(struct pmc *pm)
2571 struct pmc_owner *po;
2572 struct pmc_binding pb;
2573 struct pmc_classdep *pcd;
2574 int adjri, error, cpu, ri;
2577 ("[pmc,%d] null pm", __LINE__));
2579 mode = PMC_TO_MODE(pm);
2580 ri = PMC_TO_ROWINDEX(pm);
2581 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2585 PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2590 * Disallow PMCSTART if a logfile is required but has not been
2593 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2594 (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2595 return (EDOOFUS); /* programming error */
2598 * If this is a sampling mode PMC, log mapping information for
2599 * the kernel modules that are currently loaded.
2601 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2602 pmc_log_kernel_mappings(pm);
2604 if (PMC_IS_VIRTUAL_MODE(mode)) {
2607 * If a PMCATTACH has never been done on this PMC,
2608 * attach it to its owner process.
2611 if (LIST_EMPTY(&pm->pm_targets))
2612 error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2613 pmc_attach_process(po->po_owner, pm);
2616 * If the PMC is attached to its owner, then force a context
2617 * switch to ensure that the MD state gets set correctly.
2621 pm->pm_state = PMC_STATE_RUNNING;
2622 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2623 pmc_force_context_switch();
2631 * A system-wide PMC.
2633 * Add the owner to the global list if this is a system-wide
2637 if (mode == PMC_MODE_SS) {
2638 if (po->po_sscount == 0) {
2639 LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2640 atomic_add_rel_int(&pmc_ss_count, 1);
2641 PMCDBG1(PMC,OPS,1, "po=%p in global list", po);
2646 * Log mapping information for all existing processes in the
2647 * system. Subsequent mappings are logged as they happen;
2648 * see pmc_process_mmap().
2650 if (po->po_logprocmaps == 0) {
2651 pmc_log_all_process_mappings(po);
2652 po->po_logprocmaps = 1;
2657 * Move to the CPU associated with this
2658 * PMC, and start the hardware.
2661 pmc_save_cpu_binding(&pb);
2663 cpu = PMC_TO_CPU(pm);
2665 if (!pmc_cpu_is_active(cpu))
2668 pmc_select_cpu(cpu);
2671 * global PMCs are configured at allocation time
2672 * so write out the initial value and start the PMC.
2675 pm->pm_state = PMC_STATE_RUNNING;
2678 if ((error = pcd->pcd_write_pmc(cpu, adjri,
2679 PMC_IS_SAMPLING_MODE(mode) ?
2680 pm->pm_sc.pm_reloadcount :
2681 pm->pm_sc.pm_initial)) == 0)
2682 error = pcd->pcd_start_pmc(cpu, adjri);
2685 pmc_restore_cpu_binding(&pb);
2695 pmc_stop(struct pmc *pm)
2697 struct pmc_owner *po;
2698 struct pmc_binding pb;
2699 struct pmc_classdep *pcd;
2700 int adjri, cpu, error, ri;
2702 KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2704 PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2705 PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2707 pm->pm_state = PMC_STATE_STOPPED;
2710 * If the PMC is a virtual mode one, changing the state to
2711 * non-RUNNING is enough to ensure that the PMC never gets
2714 * If this PMC is current running on a CPU, then it will
2715 * handled correctly at the time its target process is context
2719 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2723 * A system-mode PMC. Move to the CPU associated with
2724 * this PMC, and stop the hardware. We update the
2725 * 'initial count' so that a subsequent PMCSTART will
2726 * resume counting from the current hardware count.
2729 pmc_save_cpu_binding(&pb);
2731 cpu = PMC_TO_CPU(pm);
2733 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
2734 ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2736 if (!pmc_cpu_is_active(cpu))
2739 pmc_select_cpu(cpu);
2741 ri = PMC_TO_ROWINDEX(pm);
2742 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2745 if ((error = pcd->pcd_stop_pmc(cpu, adjri)) == 0)
2746 error = pcd->pcd_read_pmc(cpu, adjri, &pm->pm_sc.pm_initial);
2749 pmc_restore_cpu_binding(&pb);
2753 /* remove this owner from the global list of SS PMC owners */
2754 if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2756 if (po->po_sscount == 0) {
2757 atomic_subtract_rel_int(&pmc_ss_count, 1);
2758 LIST_REMOVE(po, po_ssnext);
2759 PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po);
2768 static const char *pmc_op_to_name[] = {
2770 #define __PMC_OP(N, D) #N ,
2777 * The syscall interface
2780 #define PMC_GET_SX_XLOCK(...) do { \
2781 sx_xlock(&pmc_sx); \
2782 if (pmc_hook == NULL) { \
2783 sx_xunlock(&pmc_sx); \
2784 return __VA_ARGS__; \
2788 #define PMC_DOWNGRADE_SX() do { \
2789 sx_downgrade(&pmc_sx); \
2790 is_sx_downgraded = 1; \
2794 pmc_syscall_handler(struct thread *td, void *syscall_args)
2796 int error, is_sx_downgraded, is_sx_locked, op;
2797 struct pmc_syscall_args *c;
2800 PMC_GET_SX_XLOCK(ENOSYS);
2804 is_sx_downgraded = 0;
2807 c = (struct pmc_syscall_args *) syscall_args;
2812 PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2813 pmc_op_to_name[op], arg);
2816 atomic_add_int(&pmc_stats.pm_syscalls, 1);
2823 * Configure a log file.
2825 * XXX This OP will be reworked.
2828 case PMC_OP_CONFIGURELOG:
2832 struct pmc_owner *po;
2833 struct pmc_op_configurelog cl;
2835 sx_assert(&pmc_sx, SX_XLOCKED);
2837 if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2840 /* mark this process as owning a log file */
2842 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2843 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2849 * If a valid fd was passed in, try to configure that,
2850 * otherwise if 'fd' was less than zero and there was
2851 * a log file configured, flush its buffers and
2854 if (cl.pm_logfd >= 0) {
2855 sx_xunlock(&pmc_sx);
2857 error = pmclog_configure_log(md, po, cl.pm_logfd);
2858 } else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2859 pmclog_process_closelog(po);
2860 error = pmclog_close(po);
2862 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2863 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2864 pm->pm_state == PMC_STATE_RUNNING)
2866 error = pmclog_deconfigure_log(po);
2880 case PMC_OP_FLUSHLOG:
2882 struct pmc_owner *po;
2884 sx_assert(&pmc_sx, SX_XLOCKED);
2886 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2891 error = pmclog_flush(po);
2899 case PMC_OP_CLOSELOG:
2901 struct pmc_owner *po;
2903 sx_assert(&pmc_sx, SX_XLOCKED);
2905 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2910 error = pmclog_close(po);
2915 * Retrieve hardware configuration.
2918 case PMC_OP_GETCPUINFO: /* CPU information */
2920 struct pmc_op_getcpuinfo gci;
2921 struct pmc_classinfo *pci;
2922 struct pmc_classdep *pcd;
2925 gci.pm_cputype = md->pmd_cputype;
2926 gci.pm_ncpu = pmc_cpu_max();
2927 gci.pm_npmc = md->pmd_npmc;
2928 gci.pm_nclass = md->pmd_nclass;
2929 pci = gci.pm_classes;
2930 pcd = md->pmd_classdep;
2931 for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
2932 pci->pm_caps = pcd->pcd_caps;
2933 pci->pm_class = pcd->pcd_class;
2934 pci->pm_width = pcd->pcd_width;
2935 pci->pm_num = pcd->pcd_num;
2937 error = copyout(&gci, arg, sizeof(gci));
2942 * Retrieve soft events list.
2944 case PMC_OP_GETDYNEVENTINFO:
2948 struct pmc_op_getdyneventinfo *gei;
2949 struct pmc_dyn_event_descr dev;
2950 struct pmc_soft *ps;
2953 sx_assert(&pmc_sx, SX_LOCKED);
2955 gei = (struct pmc_op_getdyneventinfo *) arg;
2957 if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
2960 /* Only SOFT class is dynamic. */
2961 if (cl != PMC_CLASS_SOFT) {
2967 for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) {
2968 ps = pmc_soft_ev_acquire(ev);
2971 bcopy(&ps->ps_ev, &dev, sizeof(dev));
2972 pmc_soft_ev_release(ps);
2974 error = copyout(&dev,
2975 &gei->pm_events[nevent],
2976 sizeof(struct pmc_dyn_event_descr));
2984 error = copyout(&nevent, &gei->pm_nevent,
2990 * Get module statistics
2993 case PMC_OP_GETDRIVERSTATS:
2995 struct pmc_op_getdriverstats gms;
2997 bcopy(&pmc_stats, &gms, sizeof(gms));
2998 error = copyout(&gms, arg, sizeof(gms));
3004 * Retrieve module version number
3007 case PMC_OP_GETMODULEVERSION:
3011 /* retrieve the client's idea of the ABI version */
3012 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
3014 /* don't service clients newer than our driver */
3016 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
3017 error = EPROGMISMATCH;
3020 error = copyout(&modv, arg, sizeof(int));
3026 * Retrieve the state of all the PMCs on a given
3030 case PMC_OP_GETPMCINFO:
3034 size_t pmcinfo_size;
3035 uint32_t cpu, n, npmc;
3036 struct pmc_owner *po;
3037 struct pmc_binding pb;
3038 struct pmc_classdep *pcd;
3039 struct pmc_info *p, *pmcinfo;
3040 struct pmc_op_getpmcinfo *gpi;
3044 gpi = (struct pmc_op_getpmcinfo *) arg;
3046 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
3049 if (cpu >= pmc_cpu_max()) {
3054 if (!pmc_cpu_is_active(cpu)) {
3059 /* switch to CPU 'cpu' */
3060 pmc_save_cpu_binding(&pb);
3061 pmc_select_cpu(cpu);
3063 npmc = md->pmd_npmc;
3065 pmcinfo_size = npmc * sizeof(struct pmc_info);
3066 pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK);
3070 for (n = 0; n < md->pmd_npmc; n++, p++) {
3072 pcd = pmc_ri_to_classdep(md, n, &ari);
3074 KASSERT(pcd != NULL,
3075 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
3077 if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
3080 if (PMC_ROW_DISP_IS_STANDALONE(n))
3081 p->pm_rowdisp = PMC_DISP_STANDALONE;
3082 else if (PMC_ROW_DISP_IS_THREAD(n))
3083 p->pm_rowdisp = PMC_DISP_THREAD;
3085 p->pm_rowdisp = PMC_DISP_FREE;
3087 p->pm_ownerpid = -1;
3089 if (pm == NULL) /* no PMC associated */
3094 KASSERT(po->po_owner != NULL,
3095 ("[pmc,%d] pmc_owner had a null proc pointer",
3098 p->pm_ownerpid = po->po_owner->p_pid;
3099 p->pm_mode = PMC_TO_MODE(pm);
3100 p->pm_event = pm->pm_event;
3101 p->pm_flags = pm->pm_flags;
3103 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3105 pm->pm_sc.pm_reloadcount;
3108 pmc_restore_cpu_binding(&pb);
3110 /* now copy out the PMC info collected */
3112 error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
3114 free(pmcinfo, M_PMC);
3120 * Set the administrative state of a PMC. I.e. whether
3121 * the PMC is to be used or not.
3124 case PMC_OP_PMCADMIN:
3127 enum pmc_state request;
3130 struct pmc_op_pmcadmin pma;
3131 struct pmc_binding pb;
3133 sx_assert(&pmc_sx, SX_XLOCKED);
3135 KASSERT(td == curthread,
3136 ("[pmc,%d] td != curthread", __LINE__));
3138 error = priv_check(td, PRIV_PMC_MANAGE);
3142 if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
3147 if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
3152 if (!pmc_cpu_is_active(cpu)) {
3157 request = pma.pm_state;
3159 if (request != PMC_STATE_DISABLED &&
3160 request != PMC_STATE_FREE) {
3165 ri = pma.pm_pmc; /* pmc id == row index */
3166 if (ri < 0 || ri >= (int) md->pmd_npmc) {
3172 * We can't disable a PMC with a row-index allocated
3173 * for process virtual PMCs.
3176 if (PMC_ROW_DISP_IS_THREAD(ri) &&
3177 request == PMC_STATE_DISABLED) {
3183 * otherwise, this PMC on this CPU is either free or
3184 * in system-wide mode.
3187 pmc_save_cpu_binding(&pb);
3188 pmc_select_cpu(cpu);
3191 phw = pc->pc_hwpmcs[ri];
3194 * XXX do we need some kind of 'forced' disable?
3197 if (phw->phw_pmc == NULL) {
3198 if (request == PMC_STATE_DISABLED &&
3199 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
3200 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
3201 PMC_MARK_ROW_STANDALONE(ri);
3202 } else if (request == PMC_STATE_FREE &&
3203 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
3204 phw->phw_state |= PMC_PHW_FLAG_IS_ENABLED;
3205 PMC_UNMARK_ROW_STANDALONE(ri);
3207 /* other cases are a no-op */
3211 pmc_restore_cpu_binding(&pb);
3220 case PMC_OP_PMCALLOCATE:
3228 struct pmc_binding pb;
3229 struct pmc_classdep *pcd;
3230 struct pmc_op_pmcallocate pa;
3232 if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
3239 if ((mode != PMC_MODE_SS && mode != PMC_MODE_SC &&
3240 mode != PMC_MODE_TS && mode != PMC_MODE_TC) ||
3241 (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
3247 * Virtual PMCs should only ask for a default CPU.
3248 * System mode PMCs need to specify a non-default CPU.
3251 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3252 (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3258 * Check that an inactive CPU is not being asked for.
3261 if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3267 * Refuse an allocation for a system-wide PMC if this
3268 * process has been jailed, or if this process lacks
3269 * super-user credentials and the sysctl tunable
3270 * 'security.bsd.unprivileged_syspmcs' is zero.
3273 if (PMC_IS_SYSTEM_MODE(mode)) {
3274 if (jailed(curthread->td_ucred)) {
3278 if (!pmc_unprivileged_syspmcs) {
3279 error = priv_check(curthread,
3287 * Look for valid values for 'pm_flags'
3290 if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3291 PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3296 /* process logging options are not allowed for system PMCs */
3297 if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3298 (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3304 * All sampling mode PMCs need to be able to interrupt the
3307 if (PMC_IS_SAMPLING_MODE(mode))
3308 caps |= PMC_CAP_INTERRUPT;
3310 /* A valid class specifier should have been passed in. */
3311 for (n = 0; n < md->pmd_nclass; n++)
3312 if (md->pmd_classdep[n].pcd_class == pa.pm_class)
3314 if (n == md->pmd_nclass) {
3319 /* The requested PMC capabilities should be feasible. */
3320 if ((md->pmd_classdep[n].pcd_caps & caps) != caps) {
3325 PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3326 pa.pm_ev, caps, mode, cpu);
3328 pmc = pmc_allocate_pmc_descriptor();
3329 pmc->pm_id = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3331 pmc->pm_event = pa.pm_ev;
3332 pmc->pm_state = PMC_STATE_FREE;
3333 pmc->pm_caps = caps;
3334 pmc->pm_flags = pa.pm_flags;
3336 /* switch thread to CPU 'cpu' */
3337 pmc_save_cpu_binding(&pb);
3339 #define PMC_IS_SHAREABLE_PMC(cpu, n) \
3340 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state & \
3341 PMC_PHW_FLAG_IS_SHAREABLE)
3342 #define PMC_IS_UNALLOCATED(cpu, n) \
3343 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3345 if (PMC_IS_SYSTEM_MODE(mode)) {
3346 pmc_select_cpu(cpu);
3347 for (n = 0; n < (int) md->pmd_npmc; n++) {
3348 pcd = pmc_ri_to_classdep(md, n, &adjri);
3349 if (pmc_can_allocate_row(n, mode) == 0 &&
3350 pmc_can_allocate_rowindex(
3351 curthread->td_proc, n, cpu) == 0 &&
3352 (PMC_IS_UNALLOCATED(cpu, n) ||
3353 PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3354 pcd->pcd_allocate_pmc(cpu, adjri, pmc,
3359 /* Process virtual mode */
3360 for (n = 0; n < (int) md->pmd_npmc; n++) {
3361 pcd = pmc_ri_to_classdep(md, n, &adjri);
3362 if (pmc_can_allocate_row(n, mode) == 0 &&
3363 pmc_can_allocate_rowindex(
3364 curthread->td_proc, n,
3365 PMC_CPU_ANY) == 0 &&
3366 pcd->pcd_allocate_pmc(curthread->td_oncpu,
3367 adjri, pmc, &pa) == 0)
3372 #undef PMC_IS_UNALLOCATED
3373 #undef PMC_IS_SHAREABLE_PMC
3375 pmc_restore_cpu_binding(&pb);
3377 if (n == (int) md->pmd_npmc) {
3378 pmc_destroy_pmc_descriptor(pmc);
3384 /* Fill in the correct value in the ID field */
3385 pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3387 PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3388 pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3390 /* Process mode PMCs with logging enabled need log files */
3391 if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3392 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3394 /* All system mode sampling PMCs require a log file */
3395 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3396 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3399 * Configure global pmc's immediately
3402 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3404 pmc_save_cpu_binding(&pb);
3405 pmc_select_cpu(cpu);
3407 phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3408 pcd = pmc_ri_to_classdep(md, n, &adjri);
3410 if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3411 (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3412 (void) pcd->pcd_release_pmc(cpu, adjri, pmc);
3413 pmc_destroy_pmc_descriptor(pmc);
3415 pmc_restore_cpu_binding(&pb);
3420 pmc_restore_cpu_binding(&pb);
3423 pmc->pm_state = PMC_STATE_ALLOCATED;
3426 * mark row disposition
3429 if (PMC_IS_SYSTEM_MODE(mode))
3430 PMC_MARK_ROW_STANDALONE(n);
3432 PMC_MARK_ROW_THREAD(n);
3435 * Register this PMC with the current thread as its owner.
3439 pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3440 pmc_release_pmc_descriptor(pmc);
3441 pmc_destroy_pmc_descriptor(pmc);
3447 * Return the allocated index.
3450 pa.pm_pmcid = pmc->pm_id;
3452 error = copyout(&pa, arg, sizeof(pa));
3458 * Attach a PMC to a process.
3461 case PMC_OP_PMCATTACH:
3465 struct pmc_op_pmcattach a;
3467 sx_assert(&pmc_sx, SX_XLOCKED);
3469 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3475 } else if (a.pm_pid == 0)
3476 a.pm_pid = td->td_proc->p_pid;
3478 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3481 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3486 /* PMCs may be (re)attached only when allocated or stopped */
3487 if (pm->pm_state == PMC_STATE_RUNNING) {
3490 } else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3491 pm->pm_state != PMC_STATE_STOPPED) {
3497 if ((p = pfind(a.pm_pid)) == NULL) {
3503 * Ignore processes that are working on exiting.
3505 if (p->p_flag & P_WEXIT) {
3507 PROC_UNLOCK(p); /* pfind() returns a locked process */
3512 * we are allowed to attach a PMC to a process if
3515 error = p_candebug(curthread, p);
3520 error = pmc_attach_process(p, pm);
3526 * Detach an attached PMC from a process.
3529 case PMC_OP_PMCDETACH:
3533 struct pmc_op_pmcattach a;
3535 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3541 } else if (a.pm_pid == 0)
3542 a.pm_pid = td->td_proc->p_pid;
3544 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3547 if ((p = pfind(a.pm_pid)) == NULL) {
3553 * Treat processes that are in the process of exiting
3554 * as if they were not present.
3557 if (p->p_flag & P_WEXIT)
3560 PROC_UNLOCK(p); /* pfind() returns a locked process */
3563 error = pmc_detach_process(p, pm);
3569 * Retrieve the MSR number associated with the counter
3570 * 'pmc_id'. This allows processes to directly use RDPMC
3571 * instructions to read their PMCs, without the overhead of a
3575 case PMC_OP_PMCGETMSR:
3579 struct pmc_target *pt;
3580 struct pmc_op_getmsr gm;
3581 struct pmc_classdep *pcd;
3585 if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3588 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3592 * The allocated PMC has to be a process virtual PMC,
3593 * i.e., of type MODE_T[CS]. Global PMCs can only be
3594 * read using the PMCREAD operation since they may be
3595 * allocated on a different CPU than the one we could
3596 * be running on at the time of the RDPMC instruction.
3598 * The GETMSR operation is not allowed for PMCs that
3599 * are inherited across processes.
3602 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3603 (pm->pm_flags & PMC_F_DESCENDANTS)) {
3609 * It only makes sense to use a RDPMC (or its
3610 * equivalent instruction on non-x86 architectures) on
3611 * a process that has allocated and attached a PMC to
3612 * itself. Conversely the PMC is only allowed to have
3613 * one process attached to it -- its owner.
3616 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3617 LIST_NEXT(pt, pt_next) != NULL ||
3618 pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3623 ri = PMC_TO_ROWINDEX(pm);
3624 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3626 /* PMC class has no 'GETMSR' support */
3627 if (pcd->pcd_get_msr == NULL) {
3632 if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
3635 if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3639 * Mark our process as using MSRs. Update machine
3640 * state using a forced context switch.
3643 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3644 pmc_force_context_switch();
3650 * Release an allocated PMC
3653 case PMC_OP_PMCRELEASE:
3657 struct pmc_owner *po;
3658 struct pmc_op_simple sp;
3661 * Find PMC pointer for the named PMC.
3663 * Use pmc_release_pmc_descriptor() to switch off the
3664 * PMC, remove all its target threads, and remove the
3665 * PMC from its owner's list.
3667 * Remove the owner record if this is the last PMC
3673 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3676 pmcid = sp.pm_pmcid;
3678 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3682 pmc_release_pmc_descriptor(pm);
3683 pmc_maybe_remove_owner(po);
3684 pmc_destroy_pmc_descriptor(pm);
3690 * Read and/or write a PMC.
3698 pmc_value_t oldvalue;
3699 struct pmc_binding pb;
3700 struct pmc_op_pmcrw prw;
3701 struct pmc_classdep *pcd;
3702 struct pmc_op_pmcrw *pprw;
3706 if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3710 PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3713 /* must have at least one flag set */
3714 if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3719 /* locate pmc descriptor */
3720 if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3723 /* Can't read a PMC that hasn't been started. */
3724 if (pm->pm_state != PMC_STATE_ALLOCATED &&
3725 pm->pm_state != PMC_STATE_STOPPED &&
3726 pm->pm_state != PMC_STATE_RUNNING) {
3731 /* writing a new value is allowed only for 'STOPPED' pmcs */
3732 if (pm->pm_state == PMC_STATE_RUNNING &&
3733 (prw.pm_flags & PMC_F_NEWVALUE)) {
3738 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3741 * If this PMC is attached to its owner (i.e.,
3742 * the process requesting this operation) and
3743 * is running, then attempt to get an
3744 * upto-date reading from hardware for a READ.
3745 * Writes are only allowed when the PMC is
3746 * stopped, so only update the saved value
3749 * If the PMC is not running, or is not
3750 * attached to its owner, read/write to the
3754 ri = PMC_TO_ROWINDEX(pm);
3755 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3757 mtx_pool_lock_spin(pmc_mtxpool, pm);
3758 cpu = curthread->td_oncpu;
3760 if (prw.pm_flags & PMC_F_OLDVALUE) {
3761 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3762 (pm->pm_state == PMC_STATE_RUNNING))
3763 error = (*pcd->pcd_read_pmc)(cpu, adjri,
3766 oldvalue = pm->pm_gv.pm_savedvalue;
3768 if (prw.pm_flags & PMC_F_NEWVALUE)
3769 pm->pm_gv.pm_savedvalue = prw.pm_value;
3771 mtx_pool_unlock_spin(pmc_mtxpool, pm);
3773 } else { /* System mode PMCs */
3774 cpu = PMC_TO_CPU(pm);
3775 ri = PMC_TO_ROWINDEX(pm);
3776 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3778 if (!pmc_cpu_is_active(cpu)) {
3783 /* move this thread to CPU 'cpu' */
3784 pmc_save_cpu_binding(&pb);
3785 pmc_select_cpu(cpu);
3788 /* save old value */
3789 if (prw.pm_flags & PMC_F_OLDVALUE)
3790 if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
3793 /* write out new value */
3794 if (prw.pm_flags & PMC_F_NEWVALUE)
3795 error = (*pcd->pcd_write_pmc)(cpu, adjri,
3799 pmc_restore_cpu_binding(&pb);
3804 pprw = (struct pmc_op_pmcrw *) arg;
3807 if (prw.pm_flags & PMC_F_NEWVALUE)
3808 PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3809 ri, prw.pm_value, oldvalue);
3810 else if (prw.pm_flags & PMC_F_OLDVALUE)
3811 PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3814 /* return old value if requested */
3815 if (prw.pm_flags & PMC_F_OLDVALUE)
3816 if ((error = copyout(&oldvalue, &pprw->pm_value,
3817 sizeof(prw.pm_value))))
3825 * Set the sampling rate for a sampling mode PMC and the
3826 * initial count for a counting mode PMC.
3829 case PMC_OP_PMCSETCOUNT:
3832 struct pmc_op_pmcsetcount sc;
3836 if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3839 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3842 if (pm->pm_state == PMC_STATE_RUNNING) {
3847 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3848 pm->pm_sc.pm_reloadcount = sc.pm_count;
3850 pm->pm_sc.pm_initial = sc.pm_count;
3859 case PMC_OP_PMCSTART:
3863 struct pmc_op_simple sp;
3865 sx_assert(&pmc_sx, SX_XLOCKED);
3867 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3870 pmcid = sp.pm_pmcid;
3872 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3875 KASSERT(pmcid == pm->pm_id,
3876 ("[pmc,%d] pmcid %x != id %x", __LINE__,
3879 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3881 else if (pm->pm_state != PMC_STATE_STOPPED &&
3882 pm->pm_state != PMC_STATE_ALLOCATED) {
3887 error = pmc_start(pm);
3896 case PMC_OP_PMCSTOP:
3900 struct pmc_op_simple sp;
3904 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3907 pmcid = sp.pm_pmcid;
3910 * Mark the PMC as inactive and invoke the MD stop
3911 * routines if needed.
3914 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3917 KASSERT(pmcid == pm->pm_id,
3918 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3921 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3923 else if (pm->pm_state != PMC_STATE_RUNNING) {
3928 error = pmc_stop(pm);
3934 * Write a user supplied value to the log file.
3937 case PMC_OP_WRITELOG:
3939 struct pmc_op_writelog wl;
3940 struct pmc_owner *po;
3944 if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
3947 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3952 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
3957 error = pmclog_process_userlog(po, &wl);
3967 if (is_sx_locked != 0) {
3968 if (is_sx_downgraded)
3969 sx_sunlock(&pmc_sx);
3971 sx_xunlock(&pmc_sx);
3975 atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
3988 * Mark the thread as needing callchain capture and post an AST. The
3989 * actual callchain capture will be done in a context where it is safe
3990 * to take page faults.
3994 pmc_post_callchain_callback(void)
4001 * If there is multiple PMCs for the same interrupt ignore new post
4003 if (td->td_pflags & TDP_CALLCHAIN)
4007 * Mark this thread as needing callchain capture.
4008 * `td->td_pflags' will be safe to touch because this thread
4009 * was in user space when it was interrupted.
4011 td->td_pflags |= TDP_CALLCHAIN;
4014 * Don't let this thread migrate between CPUs until callchain
4015 * capture completes.
4023 * Interrupt processing.
4025 * Find a free slot in the per-cpu array of samples and capture the
4026 * current callchain there. If a sample was successfully added, a bit
4027 * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4028 * needs to be invoked from the clock handler.
4030 * This function is meant to be called from an NMI handler. It cannot
4031 * use any of the locking primitives supplied by the OS.
4035 pmc_process_interrupt(int cpu, int ring, struct pmc *pm, struct trapframe *tf,
4038 int error, callchaindepth;
4040 struct pmc_sample *ps;
4041 struct pmc_samplebuffer *psb;
4046 * Allocate space for a sample buffer.
4048 psb = pmc_pcpu[cpu]->pc_sb[ring];
4051 if (ps->ps_nsamples) { /* in use, reader hasn't caught up */
4053 atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
4054 PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
4055 cpu, pm, (void *) tf, inuserspace,
4056 (int) (psb->ps_write - psb->ps_samples),
4057 (int) (psb->ps_read - psb->ps_samples));
4063 /* Fill in entry. */
4064 PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
4065 (void *) tf, inuserspace,
4066 (int) (psb->ps_write - psb->ps_samples),
4067 (int) (psb->ps_read - psb->ps_samples));
4069 KASSERT(pm->pm_runcount >= 0,
4070 ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4073 atomic_add_rel_int(&pm->pm_runcount, 1); /* hold onto PMC */
4076 if ((td = curthread) && td->td_proc)
4077 ps->ps_pid = td->td_proc->p_pid;
4082 ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4084 callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4085 pmc_callchaindepth : 1;
4087 if (callchaindepth == 1)
4088 ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
4091 * Kernel stack traversals can be done immediately,
4092 * while we defer to an AST for user space traversals.
4096 pmc_save_kernel_callchain(ps->ps_pc,
4097 callchaindepth, tf);
4099 pmc_post_callchain_callback();
4100 callchaindepth = PMC_SAMPLE_INUSE;
4104 ps->ps_nsamples = callchaindepth; /* mark entry as in use */
4106 /* increment write pointer, modulo ring buffer size */
4108 if (ps == psb->ps_fence)
4109 psb->ps_write = psb->ps_samples;
4114 /* mark CPU as needing processing */
4115 CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4121 * Capture a user call chain. This function will be called from ast()
4122 * before control returns to userland and before the process gets
4127 pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4132 struct pmc_sample *ps;
4133 struct pmc_samplebuffer *psb;
4138 psb = pmc_pcpu[cpu]->pc_sb[ring];
4141 KASSERT(td->td_pflags & TDP_CALLCHAIN,
4142 ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
4150 * Iterate through all deferred callchain requests.
4153 ps = psb->ps_samples;
4154 for (i = 0; i < pmc_nsamples; i++, ps++) {
4156 if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
4158 if (ps->ps_td != td)
4161 KASSERT(ps->ps_cpu == cpu,
4162 ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
4163 ps->ps_cpu, PCPU_GET(cpuid)));
4167 KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
4168 ("[pmc,%d] Retrieving callchain for PMC that doesn't "
4169 "want it", __LINE__));
4171 KASSERT(pm->pm_runcount > 0,
4172 ("[pmc,%d] runcount %d", __LINE__, pm->pm_runcount));
4175 * Retrieve the callchain and mark the sample buffer
4176 * as 'processable' by the timer tick sweep code.
4178 ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
4179 pmc_callchaindepth, tf);
4186 KASSERT(ncallchains > 0,
4187 ("[pmc,%d] cpu %d didn't find a sample to collect", __LINE__,
4190 KASSERT(td->td_pinned == 1,
4191 ("[pmc,%d] invalid td_pinned value", __LINE__));
4192 sched_unpin(); /* Can migrate safely now. */
4198 * Process saved PC samples.
4202 pmc_process_samples(int cpu, int ring)
4207 struct pmc_owner *po;
4208 struct pmc_sample *ps;
4209 struct pmc_classdep *pcd;
4210 struct pmc_samplebuffer *psb;
4212 KASSERT(PCPU_GET(cpuid) == cpu,
4213 ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4214 PCPU_GET(cpuid), cpu));
4216 psb = pmc_pcpu[cpu]->pc_sb[ring];
4218 for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
4221 if (ps->ps_nsamples == PMC_SAMPLE_FREE)
4226 KASSERT(pm->pm_runcount > 0,
4227 ("[pmc,%d] pm=%p runcount %d", __LINE__, (void *) pm,
4232 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4233 ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4234 pm, PMC_TO_MODE(pm)));
4236 /* Ignore PMCs that have been switched off */
4237 if (pm->pm_state != PMC_STATE_RUNNING)
4240 /* If there is a pending AST wait for completion */
4241 if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
4242 /* Need a rescan at a later time. */
4243 CPU_SET_ATOMIC(cpu, &pmc_cpumask);
4247 PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4248 pm, ps->ps_nsamples, ps->ps_flags,
4249 (int) (psb->ps_write - psb->ps_samples),
4250 (int) (psb->ps_read - psb->ps_samples));
4253 * If this is a process-mode PMC that is attached to
4254 * its owner, and if the PC is in user mode, update
4255 * profiling statistics like timer-based profiling
4258 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4259 if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4260 td = FIRST_THREAD_IN_PROC(po->po_owner);
4261 addupc_intr(td, ps->ps_pc[0], 1);
4267 * Otherwise, this is either a sampling mode PMC that
4268 * is attached to a different process than its owner,
4269 * or a system-wide sampling PMC. Dispatch a log
4270 * entry to the PMC's owner process.
4272 pmclog_process_callchain(pm, ps);
4275 ps->ps_nsamples = 0; /* mark entry as free */
4276 atomic_subtract_rel_int(&pm->pm_runcount, 1);
4278 /* increment read pointer, modulo sample size */
4279 if (++ps == psb->ps_fence)
4280 psb->ps_read = psb->ps_samples;
4285 atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
4287 /* Do not re-enable stalled PMCs if we failed to process any samples */
4292 * Restart any stalled sampling PMCs on this CPU.
4294 * If the NMI handler sets the pm_stalled field of a PMC after
4295 * the check below, we'll end up processing the stalled PMC at
4296 * the next hardclock tick.
4298 for (n = 0; n < md->pmd_npmc; n++) {
4299 pcd = pmc_ri_to_classdep(md, n, &adjri);
4300 KASSERT(pcd != NULL,
4301 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4302 (void) (*pcd->pcd_get_config)(cpu,adjri,&pm);
4304 if (pm == NULL || /* !cfg'ed */
4305 pm->pm_state != PMC_STATE_RUNNING || /* !active */
4306 !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4307 pm->pm_stalled == 0) /* !stalled */
4311 (*pcd->pcd_start_pmc)(cpu, adjri);
4320 * Handle a process exit.
4322 * Remove this process from all hash tables. If this process
4323 * owned any PMCs, turn off those PMCs and deallocate them,
4324 * removing any associations with target processes.
4326 * This function will be called by the last 'thread' of a
4329 * XXX This eventhandler gets called early in the exit process.
4330 * Consider using a 'hook' invocation from thread_exit() or equivalent
4331 * spot. Another negative is that kse_exit doesn't seem to call
4337 pmc_process_exit(void *arg __unused, struct proc *p)
4342 int is_using_hwpmcs;
4343 struct pmc_owner *po;
4344 struct pmc_process *pp;
4345 struct pmc_classdep *pcd;
4346 pmc_value_t newvalue, tmp;
4349 is_using_hwpmcs = p->p_flag & P_HWPMC;
4353 * Log a sysexit event to all SS PMC owners.
4355 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4356 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4357 pmclog_process_sysexit(po, p->p_pid);
4359 if (!is_using_hwpmcs)
4363 PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4367 * Since this code is invoked by the last thread in an exiting
4368 * process, we would have context switched IN at some prior
4369 * point. However, with PREEMPTION, kernel mode context
4370 * switches may happen any time, so we want to disable a
4371 * context switch OUT till we get any PMCs targetting this
4372 * process off the hardware.
4374 * We also need to atomically remove this process'
4375 * entry from our target process hash table, using
4378 PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4381 critical_enter(); /* no preemption */
4383 cpu = curthread->td_oncpu;
4385 if ((pp = pmc_find_process_descriptor(p,
4386 PMC_FLAG_REMOVE)) != NULL) {
4389 "process-exit proc=%p pmc-process=%p", p, pp);
4392 * The exiting process could the target of
4393 * some PMCs which will be running on
4394 * currently executing CPU.
4396 * We need to turn these PMCs off like we
4397 * would do at context switch OUT time.
4399 for (ri = 0; ri < md->pmd_npmc; ri++) {
4402 * Pick up the pmc pointer from hardware
4403 * state similar to the CSW_OUT code.
4407 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4409 (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
4411 PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4414 !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4417 PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4418 "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4421 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4422 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4423 __LINE__, PMC_TO_ROWINDEX(pm), ri));
4425 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4426 ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4427 __LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4429 (void) pcd->pcd_stop_pmc(cpu, adjri);
4431 KASSERT(pm->pm_runcount > 0,
4432 ("[pmc,%d] bad runcount ri %d rc %d",
4433 __LINE__, ri, pm->pm_runcount));
4435 /* Stop hardware only if it is actually running */
4436 if (pm->pm_state == PMC_STATE_RUNNING &&
4437 pm->pm_stalled == 0) {
4438 pcd->pcd_read_pmc(cpu, adjri, &newvalue);
4440 PMC_PCPU_SAVED(cpu,ri);
4442 mtx_pool_lock_spin(pmc_mtxpool, pm);
4443 pm->pm_gv.pm_savedvalue += tmp;
4444 pp->pp_pmcs[ri].pp_pmcval += tmp;
4445 mtx_pool_unlock_spin(pmc_mtxpool, pm);
4448 atomic_subtract_rel_int(&pm->pm_runcount,1);
4450 KASSERT((int) pm->pm_runcount >= 0,
4451 ("[pmc,%d] runcount is %d", __LINE__, ri));
4453 (void) pcd->pcd_config_pmc(cpu, adjri, NULL);
4457 * Inform the MD layer of this pseudo "context switch
4460 (void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
4462 critical_exit(); /* ok to be pre-empted now */
4465 * Unlink this process from the PMCs that are
4466 * targetting it. This will send a signal to
4467 * all PMC owner's whose PMCs are orphaned.
4469 * Log PMC value at exit time if requested.
4471 for (ri = 0; ri < md->pmd_npmc; ri++)
4472 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
4473 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
4474 PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
4475 pmclog_process_procexit(pm, pp);
4476 pmc_unlink_target_process(pm, pp);
4481 critical_exit(); /* pp == NULL */
4485 * If the process owned PMCs, free them up and free up
4488 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
4489 pmc_remove_owner(po);
4490 pmc_destroy_owner_descriptor(po);
4493 sx_xunlock(&pmc_sx);
4497 * Handle a process fork.
4499 * If the parent process 'p1' is under HWPMC monitoring, then copy
4500 * over any attached PMCs that have 'do_descendants' semantics.
4504 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
4507 int is_using_hwpmcs;
4509 uint32_t do_descendants;
4511 struct pmc_owner *po;
4512 struct pmc_process *ppnew, *ppold;
4514 (void) flags; /* unused parameter */
4517 is_using_hwpmcs = p1->p_flag & P_HWPMC;
4521 * If there are system-wide sampling PMCs active, we need to
4522 * log all fork events to their owner's logs.
4525 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4526 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4527 pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4529 if (!is_using_hwpmcs)
4533 PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4534 p1->p_pid, p1->p_comm, newproc);
4537 * If the parent process (curthread->td_proc) is a
4538 * target of any PMCs, look for PMCs that are to be
4539 * inherited, and link these into the new process
4542 if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4543 PMC_FLAG_NONE)) == NULL)
4544 goto done; /* nothing to do */
4547 for (ri = 0; ri < md->pmd_npmc; ri++)
4548 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4549 do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4550 if (do_descendants == 0) /* nothing to do */
4553 /* allocate a descriptor for the new process */
4554 if ((ppnew = pmc_find_process_descriptor(newproc,
4555 PMC_FLAG_ALLOCATE)) == NULL)
4559 * Run through all PMCs that were targeting the old process
4560 * and which specified F_DESCENDANTS and attach them to the
4563 * Log the fork event to all owners of PMCs attached to this
4564 * process, if not already logged.
4566 for (ri = 0; ri < md->pmd_npmc; ri++)
4567 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4568 (pm->pm_flags & PMC_F_DESCENDANTS)) {
4569 pmc_link_target_process(pm, ppnew);
4571 if (po->po_sscount == 0 &&
4572 po->po_flags & PMC_PO_OWNS_LOGFILE)
4573 pmclog_process_procfork(po, p1->p_pid,
4578 * Now mark the new process as being tracked by this driver.
4581 newproc->p_flag |= P_HWPMC;
4582 PROC_UNLOCK(newproc);
4585 sx_xunlock(&pmc_sx);
4589 pmc_kld_load(void *arg __unused, linker_file_t lf)
4591 struct pmc_owner *po;
4596 * Notify owners of system sampling PMCs about KLD operations.
4598 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4599 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4600 pmclog_process_map_in(po, (pid_t) -1,
4601 (uintfptr_t) lf->address, lf->filename);
4604 * TODO: Notify owners of (all) process-sampling PMCs too.
4607 sx_sunlock(&pmc_sx);
4611 pmc_kld_unload(void *arg __unused, const char *filename __unused,
4612 caddr_t address, size_t size)
4614 struct pmc_owner *po;
4618 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4619 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4620 pmclog_process_map_out(po, (pid_t) -1,
4621 (uintfptr_t) address, (uintfptr_t) address + size);
4624 * TODO: Notify owners of process-sampling PMCs.
4627 sx_sunlock(&pmc_sx);
4634 static const char *pmc_name_of_pmcclass[] = {
4636 #define __PMC_CLASS(N) #N ,
4641 * Base class initializer: allocate structure and set default classes.
4644 pmc_mdep_alloc(int nclasses)
4646 struct pmc_mdep *md;
4649 /* SOFT + md classes */
4651 md = malloc(sizeof(struct pmc_mdep) + n *
4652 sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
4655 /* Add base class. */
4656 pmc_soft_initialize(md);
4661 pmc_mdep_free(struct pmc_mdep *md)
4663 pmc_soft_finalize(md);
4668 generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
4670 (void) pc; (void) pp;
4676 generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
4678 (void) pc; (void) pp;
4683 static struct pmc_mdep *
4684 pmc_generic_cpu_initialize(void)
4686 struct pmc_mdep *md;
4688 md = pmc_mdep_alloc(0);
4690 md->pmd_cputype = PMC_CPU_GENERIC;
4692 md->pmd_pcpu_init = NULL;
4693 md->pmd_pcpu_fini = NULL;
4694 md->pmd_switch_in = generic_switch_in;
4695 md->pmd_switch_out = generic_switch_out;
4701 pmc_generic_cpu_finalize(struct pmc_mdep *md)
4708 pmc_initialize(void)
4710 int c, cpu, error, n, ri;
4711 unsigned int maxcpu;
4712 struct pmc_binding pb;
4713 struct pmc_sample *ps;
4714 struct pmc_classdep *pcd;
4715 struct pmc_samplebuffer *sb;
4721 /* parse debug flags first */
4722 if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4723 pmc_debugstr, sizeof(pmc_debugstr)))
4724 pmc_debugflags_parse(pmc_debugstr,
4725 pmc_debugstr+strlen(pmc_debugstr));
4728 PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4730 /* check kernel version */
4731 if (pmc_kernel_version != PMC_VERSION) {
4732 if (pmc_kernel_version == 0)
4733 printf("hwpmc: this kernel has not been compiled with "
4734 "'options HWPMC_HOOKS'.\n");
4736 printf("hwpmc: kernel version (0x%x) does not match "
4737 "module version (0x%x).\n", pmc_kernel_version,
4739 return EPROGMISMATCH;
4743 * check sysctl parameters
4746 if (pmc_hashsize <= 0) {
4747 (void) printf("hwpmc: tunable \"hashsize\"=%d must be "
4748 "greater than zero.\n", pmc_hashsize);
4749 pmc_hashsize = PMC_HASH_SIZE;
4752 if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4753 (void) printf("hwpmc: tunable \"nsamples\"=%d out of "
4754 "range.\n", pmc_nsamples);
4755 pmc_nsamples = PMC_NSAMPLES;
4758 if (pmc_callchaindepth <= 0 ||
4759 pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
4760 (void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
4761 "range - using %d.\n", pmc_callchaindepth,
4762 PMC_CALLCHAIN_DEPTH_MAX);
4763 pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX;
4766 md = pmc_md_initialize();
4768 /* Default to generic CPU. */
4769 md = pmc_generic_cpu_initialize();
4774 KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
4775 ("[pmc,%d] no classes or pmcs", __LINE__));
4777 /* Compute the map from row-indices to classdep pointers. */
4778 pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
4779 md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);
4781 for (n = 0; n < md->pmd_npmc; n++)
4782 pmc_rowindex_to_classdep[n] = NULL;
4783 for (ri = c = 0; c < md->pmd_nclass; c++) {
4784 pcd = &md->pmd_classdep[c];
4785 for (n = 0; n < pcd->pcd_num; n++, ri++)
4786 pmc_rowindex_to_classdep[ri] = pcd;
4789 KASSERT(ri == md->pmd_npmc,
4790 ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
4793 maxcpu = pmc_cpu_max();
4795 /* allocate space for the per-cpu array */
4796 pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
4799 /* per-cpu 'saved values' for managing process-mode PMCs */
4800 pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
4803 /* Perform CPU-dependent initialization. */
4804 pmc_save_cpu_binding(&pb);
4806 for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
4807 if (!pmc_cpu_is_active(cpu))
4809 pmc_select_cpu(cpu);
4810 pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
4811 md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
4813 if (md->pmd_pcpu_init)
4814 error = md->pmd_pcpu_init(md, cpu);
4815 for (n = 0; error == 0 && n < md->pmd_nclass; n++)
4816 error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
4818 pmc_restore_cpu_binding(&pb);
4823 /* allocate space for the sample array */
4824 for (cpu = 0; cpu < maxcpu; cpu++) {
4825 if (!pmc_cpu_is_active(cpu))
4828 sb = malloc(sizeof(struct pmc_samplebuffer) +
4829 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4831 sb->ps_read = sb->ps_write = sb->ps_samples;
4832 sb->ps_fence = sb->ps_samples + pmc_nsamples;
4834 KASSERT(pmc_pcpu[cpu] != NULL,
4835 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4837 sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4838 sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4840 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4841 ps->ps_pc = sb->ps_callchains +
4842 (n * pmc_callchaindepth);
4844 pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
4846 sb = malloc(sizeof(struct pmc_samplebuffer) +
4847 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4849 sb->ps_read = sb->ps_write = sb->ps_samples;
4850 sb->ps_fence = sb->ps_samples + pmc_nsamples;
4852 KASSERT(pmc_pcpu[cpu] != NULL,
4853 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4855 sb->ps_callchains = malloc(pmc_callchaindepth * pmc_nsamples *
4856 sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
4858 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4859 ps->ps_pc = sb->ps_callchains +
4860 (n * pmc_callchaindepth);
4862 pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
4865 /* allocate space for the row disposition array */
4866 pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4867 M_PMC, M_WAITOK|M_ZERO);
4869 /* mark all PMCs as available */
4870 for (n = 0; n < (int) md->pmd_npmc; n++)
4871 PMC_MARK_ROW_FREE(n);
4873 /* allocate thread hash tables */
4874 pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4875 &pmc_ownerhashmask);
4877 pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4878 &pmc_processhashmask);
4879 mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4882 LIST_INIT(&pmc_ss_owners);
4885 /* allocate a pool of spin mutexes */
4886 pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4889 PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4890 "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4891 pmc_processhash, pmc_processhashmask);
4893 /* register process {exit,fork,exec} handlers */
4894 pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4895 pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4896 pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4897 pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4899 /* register kld event handlers */
4900 pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
4901 NULL, EVENTHANDLER_PRI_ANY);
4902 pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
4903 NULL, EVENTHANDLER_PRI_ANY);
4905 /* initialize logging */
4906 pmclog_initialize();
4908 /* set hook functions */
4909 pmc_intr = md->pmd_intr;
4910 pmc_hook = pmc_hook_handler;
4913 printf(PMC_MODULE_NAME ":");
4914 for (n = 0; n < (int) md->pmd_nclass; n++) {
4915 pcd = &md->pmd_classdep[n];
4916 printf(" %s/%d/%d/0x%b",
4917 pmc_name_of_pmcclass[pcd->pcd_class],
4922 "\1INT\2USR\3SYS\4EDG\5THR"
4923 "\6REA\7WRI\10INV\11QUA\12PRC"
4932 /* prepare to be unloaded */
4937 unsigned int maxcpu;
4938 struct pmc_ownerhash *ph;
4939 struct pmc_owner *po, *tmp;
4940 struct pmc_binding pb;
4942 struct pmc_processhash *prh;
4945 PMCDBG0(MOD,INI,0, "cleanup");
4947 /* switch off sampling */
4948 CPU_ZERO(&pmc_cpumask);
4952 if (pmc_hook == NULL) { /* being unloaded already */
4953 sx_xunlock(&pmc_sx);
4957 pmc_hook = NULL; /* prevent new threads from entering module */
4959 /* deregister event handlers */
4960 EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4961 EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4962 EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
4963 EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);
4965 /* send SIGBUS to all owner threads, free up allocations */
4967 for (ph = pmc_ownerhash;
4968 ph <= &pmc_ownerhash[pmc_ownerhashmask];
4970 LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4971 pmc_remove_owner(po);
4973 /* send SIGBUS to owner processes */
4974 PMCDBG3(MOD,INI,2, "cleanup signal proc=%p "
4975 "(%d, %s)", po->po_owner,
4976 po->po_owner->p_pid,
4977 po->po_owner->p_comm);
4979 PROC_LOCK(po->po_owner);
4980 kern_psignal(po->po_owner, SIGBUS);
4981 PROC_UNLOCK(po->po_owner);
4983 pmc_destroy_owner_descriptor(po);
4987 /* reclaim allocated data structures */
4989 mtx_pool_destroy(&pmc_mtxpool);
4991 mtx_destroy(&pmc_processhash_mtx);
4992 if (pmc_processhash) {
4994 struct pmc_process *pp;
4996 PMCDBG0(MOD,INI,3, "destroy process hash");
4997 for (prh = pmc_processhash;
4998 prh <= &pmc_processhash[pmc_processhashmask];
5000 LIST_FOREACH(pp, prh, pp_next)
5001 PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5004 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5005 pmc_processhash = NULL;
5008 if (pmc_ownerhash) {
5009 PMCDBG0(MOD,INI,3, "destroy owner hash");
5010 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5011 pmc_ownerhash = NULL;
5014 KASSERT(LIST_EMPTY(&pmc_ss_owners),
5015 ("[pmc,%d] Global SS owner list not empty", __LINE__));
5016 KASSERT(pmc_ss_count == 0,
5017 ("[pmc,%d] Global SS count not empty", __LINE__));
5019 /* do processor and pmc-class dependent cleanup */
5020 maxcpu = pmc_cpu_max();
5022 PMCDBG0(MOD,INI,3, "md cleanup");
5024 pmc_save_cpu_binding(&pb);
5025 for (cpu = 0; cpu < maxcpu; cpu++) {
5026 PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5027 cpu, pmc_pcpu[cpu]);
5028 if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5030 pmc_select_cpu(cpu);
5031 for (c = 0; c < md->pmd_nclass; c++)
5032 md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
5033 if (md->pmd_pcpu_fini)
5034 md->pmd_pcpu_fini(md, cpu);
5037 if (md->pmd_cputype == PMC_CPU_GENERIC)
5038 pmc_generic_cpu_finalize(md);
5040 pmc_md_finalize(md);
5044 pmc_restore_cpu_binding(&pb);
5047 /* Free per-cpu descriptors. */
5048 for (cpu = 0; cpu < maxcpu; cpu++) {
5049 if (!pmc_cpu_is_active(cpu))
5051 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5052 ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5054 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5055 ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5057 free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
5058 free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
5059 free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
5060 free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
5061 free(pmc_pcpu[cpu], M_PMC);
5064 free(pmc_pcpu, M_PMC);
5067 free(pmc_pcpu_saved, M_PMC);
5068 pmc_pcpu_saved = NULL;
5071 free(pmc_pmcdisp, M_PMC);
5075 if (pmc_rowindex_to_classdep) {
5076 free(pmc_rowindex_to_classdep, M_PMC);
5077 pmc_rowindex_to_classdep = NULL;
5082 sx_xunlock(&pmc_sx); /* we are done */
5086 * The function called at load/unload.
5090 load (struct module *module __unused, int cmd, void *arg __unused)
5098 /* initialize the subsystem */
5099 error = pmc_initialize();
5102 PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d",
5103 pmc_syscall_num, pmc_cpu_max());
5110 PMCDBG0(MOD,INI,1, "unloaded");
5114 error = EINVAL; /* XXX should panic(9) */
5122 MALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");