2 * Copyright (c) 2003-2008 Joseph Koshy
3 * Copyright (c) 2007 The FreeBSD Foundation
6 * Portions of this software were developed by A. Joseph Koshy under
7 * sponsorship from the FreeBSD Foundation and Google, Inc.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/eventhandler.h>
38 #include <sys/kernel.h>
39 #include <sys/kthread.h>
40 #include <sys/limits.h>
42 #include <sys/malloc.h>
43 #include <sys/module.h>
44 #include <sys/mutex.h>
46 #include <sys/pmckern.h>
47 #include <sys/pmclog.h>
50 #include <sys/queue.h>
51 #include <sys/resourcevar.h>
52 #include <sys/sched.h>
53 #include <sys/signalvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysent.h>
58 #include <sys/systm.h>
59 #include <sys/vnode.h>
61 #include <sys/linker.h> /* needs to be after <sys/malloc.h> */
63 #include <machine/atomic.h>
64 #include <machine/md_var.h>
71 PMC_FLAG_NONE = 0x00, /* do nothing */
72 PMC_FLAG_REMOVE = 0x01, /* atomically remove entry from hash */
73 PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
77 * The offset in sysent where the syscall is allocated.
80 static int pmc_syscall_num = NO_SYSCALL;
81 struct pmc_cpu **pmc_pcpu; /* per-cpu state */
82 pmc_value_t *pmc_pcpu_saved; /* saved PMC values: CSW handling */
84 #define PMC_PCPU_SAVED(C,R) pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
86 struct mtx_pool *pmc_mtxpool;
87 static int *pmc_pmcdisp; /* PMC row dispositions */
89 #define PMC_ROW_DISP_IS_FREE(R) (pmc_pmcdisp[(R)] == 0)
90 #define PMC_ROW_DISP_IS_THREAD(R) (pmc_pmcdisp[(R)] > 0)
91 #define PMC_ROW_DISP_IS_STANDALONE(R) (pmc_pmcdisp[(R)] < 0)
93 #define PMC_MARK_ROW_FREE(R) do { \
94 pmc_pmcdisp[(R)] = 0; \
97 #define PMC_MARK_ROW_STANDALONE(R) do { \
98 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
100 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
101 KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()), \
102 ("[pmc,%d] row disposition error", __LINE__)); \
105 #define PMC_UNMARK_ROW_STANDALONE(R) do { \
106 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
107 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
111 #define PMC_MARK_ROW_THREAD(R) do { \
112 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
114 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
117 #define PMC_UNMARK_ROW_THREAD(R) do { \
118 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
119 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
124 /* various event handlers */
125 static eventhandler_tag pmc_exit_tag, pmc_fork_tag;
127 /* Module statistics */
128 struct pmc_op_getdriverstats pmc_stats;
130 /* Machine/processor dependent operations */
134 * Hash tables mapping owner processes and target threads to PMCs.
137 struct mtx pmc_processhash_mtx; /* spin mutex */
138 static u_long pmc_processhashmask;
139 static LIST_HEAD(pmc_processhash, pmc_process) *pmc_processhash;
142 * Hash table of PMC owner descriptors. This table is protected by
143 * the shared PMC "sx" lock.
146 static u_long pmc_ownerhashmask;
147 static LIST_HEAD(pmc_ownerhash, pmc_owner) *pmc_ownerhash;
150 * List of PMC owners with system-wide sampling PMCs.
153 static LIST_HEAD(, pmc_owner) pmc_ss_owners;
161 static int pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
162 static int pmc_debugflags_parse(char *newstr, char *fence);
165 static int load(struct module *module, int cmd, void *arg);
166 static int pmc_attach_process(struct proc *p, struct pmc *pm);
167 static struct pmc *pmc_allocate_pmc_descriptor(void);
168 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
169 static int pmc_attach_one_process(struct proc *p, struct pmc *pm);
170 static int pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
172 static int pmc_can_attach(struct pmc *pm, struct proc *p);
173 static void pmc_capture_user_callchain(int cpu, struct trapframe *tf);
174 static void pmc_cleanup(void);
175 static int pmc_detach_process(struct proc *p, struct pmc *pm);
176 static int pmc_detach_one_process(struct proc *p, struct pmc *pm,
178 static void pmc_destroy_owner_descriptor(struct pmc_owner *po);
179 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
180 static int pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
181 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
183 static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
185 static void pmc_force_context_switch(void);
186 static void pmc_link_target_process(struct pmc *pm,
187 struct pmc_process *pp);
188 static void pmc_log_all_process_mappings(struct pmc_owner *po);
189 static void pmc_log_kernel_mappings(struct pmc *pm);
190 static void pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
191 static void pmc_maybe_remove_owner(struct pmc_owner *po);
192 static void pmc_process_csw_in(struct thread *td);
193 static void pmc_process_csw_out(struct thread *td);
194 static void pmc_process_exit(void *arg, struct proc *p);
195 static void pmc_process_fork(void *arg, struct proc *p1,
196 struct proc *p2, int n);
197 static void pmc_process_samples(int cpu);
198 static void pmc_release_pmc_descriptor(struct pmc *pmc);
199 static void pmc_remove_owner(struct pmc_owner *po);
200 static void pmc_remove_process_descriptor(struct pmc_process *pp);
201 static void pmc_restore_cpu_binding(struct pmc_binding *pb);
202 static void pmc_save_cpu_binding(struct pmc_binding *pb);
203 static void pmc_select_cpu(int cpu);
204 static int pmc_start(struct pmc *pm);
205 static int pmc_stop(struct pmc *pm);
206 static int pmc_syscall_handler(struct thread *td, void *syscall_args);
207 static void pmc_unlink_target_process(struct pmc *pmc,
208 struct pmc_process *pp);
211 * Kernel tunables and sysctl(8) interface.
214 SYSCTL_NODE(_kern, OID_AUTO, hwpmc, CTLFLAG_RW, 0, "HWPMC parameters");
216 static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
217 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "callchaindepth", &pmc_callchaindepth);
218 SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_TUN|CTLFLAG_RD,
219 &pmc_callchaindepth, 0, "depth of call chain records");
222 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
223 char pmc_debugstr[PMC_DEBUG_STRSIZE];
224 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
225 sizeof(pmc_debugstr));
226 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
227 CTLTYPE_STRING|CTLFLAG_RW|CTLFLAG_TUN,
228 0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
232 * kern.hwpmc.hashrows -- determines the number of rows in the
233 * of the hash table used to look up threads
236 static int pmc_hashsize = PMC_HASH_SIZE;
237 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "hashsize", &pmc_hashsize);
238 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_TUN|CTLFLAG_RD,
239 &pmc_hashsize, 0, "rows in hash tables");
242 * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
245 static int pmc_nsamples = PMC_NSAMPLES;
246 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nsamples", &pmc_nsamples);
247 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_TUN|CTLFLAG_RD,
248 &pmc_nsamples, 0, "number of PC samples per CPU");
252 * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
255 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
256 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "mtxpoolsize", &pmc_mtxpool_size);
257 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_TUN|CTLFLAG_RD,
258 &pmc_mtxpool_size, 0, "size of spin mutex pool");
262 * security.bsd.unprivileged_syspmcs -- allow non-root processes to
263 * allocate system-wide PMCs.
265 * Allowing unprivileged processes to allocate system PMCs is convenient
266 * if system-wide measurements need to be taken concurrently with other
267 * per-process measurements. This feature is turned off by default.
270 static int pmc_unprivileged_syspmcs = 0;
271 TUNABLE_INT("security.bsd.unprivileged_syspmcs", &pmc_unprivileged_syspmcs);
272 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RW,
273 &pmc_unprivileged_syspmcs, 0,
274 "allow unprivileged process to allocate system PMCs");
277 * Hash function. Discard the lower 2 bits of the pointer since
278 * these are always zero for our uses. The hash multiplier is
279 * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
283 #define _PMC_HM 11400714819323198486u
285 #define _PMC_HM 2654435769u
287 #error Must know the size of 'long' to compile
290 #define PMC_HASH_PTR(P,M) ((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
296 /* The `sysent' for the new syscall */
297 static struct sysent pmc_sysent = {
299 pmc_syscall_handler /* sy_call */
302 static struct syscall_module_data pmc_syscall_mod = {
310 static moduledata_t pmc_mod = {
312 syscall_module_handler,
316 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
317 MODULE_VERSION(pmc, PMC_VERSION);
320 enum pmc_dbgparse_state {
321 PMCDS_WS, /* in whitespace */
322 PMCDS_MAJOR, /* seen a major keyword */
327 pmc_debugflags_parse(char *newstr, char *fence)
330 struct pmc_debugflags *tmpflags;
331 int error, found, *newbits, tmp;
334 MALLOC(tmpflags, struct pmc_debugflags *, sizeof(*tmpflags),
335 M_PMC, M_WAITOK|M_ZERO);
340 for (; p < fence && (c = *p); p++) {
342 /* skip white space */
343 if (c == ' ' || c == '\t')
346 /* look for a keyword followed by "=" */
347 for (q = p; p < fence && (c = *p) && c != '='; p++)
357 /* lookup flag group name */
358 #define DBG_SET_FLAG_MAJ(S,F) \
359 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
360 newbits = &tmpflags->pdb_ ## F;
362 DBG_SET_FLAG_MAJ("cpu", CPU);
363 DBG_SET_FLAG_MAJ("csw", CSW);
364 DBG_SET_FLAG_MAJ("logging", LOG);
365 DBG_SET_FLAG_MAJ("module", MOD);
366 DBG_SET_FLAG_MAJ("md", MDP);
367 DBG_SET_FLAG_MAJ("owner", OWN);
368 DBG_SET_FLAG_MAJ("pmc", PMC);
369 DBG_SET_FLAG_MAJ("process", PRC);
370 DBG_SET_FLAG_MAJ("sampling", SAM);
372 if (newbits == NULL) {
377 p++; /* skip the '=' */
379 /* Now parse the individual flags */
382 for (q = p; p < fence && (c = *p); p++)
383 if (c == ' ' || c == '\t' || c == ',')
386 /* p == fence or c == ws or c == "," or c == 0 */
388 if ((kwlen = p - q) == 0) {
394 #define DBG_SET_FLAG_MIN(S,F) \
395 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
396 tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
398 /* a '*' denotes all possible flags in the group */
399 if (kwlen == 1 && *q == '*')
401 /* look for individual flag names */
402 DBG_SET_FLAG_MIN("allocaterow", ALR);
403 DBG_SET_FLAG_MIN("allocate", ALL);
404 DBG_SET_FLAG_MIN("attach", ATT);
405 DBG_SET_FLAG_MIN("bind", BND);
406 DBG_SET_FLAG_MIN("config", CFG);
407 DBG_SET_FLAG_MIN("exec", EXC);
408 DBG_SET_FLAG_MIN("exit", EXT);
409 DBG_SET_FLAG_MIN("find", FND);
410 DBG_SET_FLAG_MIN("flush", FLS);
411 DBG_SET_FLAG_MIN("fork", FRK);
412 DBG_SET_FLAG_MIN("getbuf", GTB);
413 DBG_SET_FLAG_MIN("hook", PMH);
414 DBG_SET_FLAG_MIN("init", INI);
415 DBG_SET_FLAG_MIN("intr", INT);
416 DBG_SET_FLAG_MIN("linktarget", TLK);
417 DBG_SET_FLAG_MIN("mayberemove", OMR);
418 DBG_SET_FLAG_MIN("ops", OPS);
419 DBG_SET_FLAG_MIN("read", REA);
420 DBG_SET_FLAG_MIN("register", REG);
421 DBG_SET_FLAG_MIN("release", REL);
422 DBG_SET_FLAG_MIN("remove", ORM);
423 DBG_SET_FLAG_MIN("sample", SAM);
424 DBG_SET_FLAG_MIN("scheduleio", SIO);
425 DBG_SET_FLAG_MIN("select", SEL);
426 DBG_SET_FLAG_MIN("signal", SIG);
427 DBG_SET_FLAG_MIN("swi", SWI);
428 DBG_SET_FLAG_MIN("swo", SWO);
429 DBG_SET_FLAG_MIN("start", STA);
430 DBG_SET_FLAG_MIN("stop", STO);
431 DBG_SET_FLAG_MIN("syscall", PMS);
432 DBG_SET_FLAG_MIN("unlinktarget", TUL);
433 DBG_SET_FLAG_MIN("write", WRI);
435 /* unrecognized flag name */
440 if (c == 0 || c == ' ' || c == '\t') { /* end of flag group */
449 /* save the new flag set */
450 bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
453 FREE(tmpflags, M_PMC);
458 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
460 char *fence, *newstr;
464 (void) arg1; (void) arg2; /* unused parameters */
466 n = sizeof(pmc_debugstr);
467 MALLOC(newstr, char *, n, M_PMC, M_ZERO|M_WAITOK);
468 (void) strlcpy(newstr, pmc_debugstr, n);
470 error = sysctl_handle_string(oidp, newstr, n, req);
472 /* if there is a new string, parse and copy it */
473 if (error == 0 && req->newptr != NULL) {
474 fence = newstr + (n < req->newlen ? n : req->newlen + 1);
475 if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
476 (void) strlcpy(pmc_debugstr, newstr,
477 sizeof(pmc_debugstr));
487 * Concurrency Control
489 * The driver manages the following data structures:
491 * - target process descriptors, one per target process
492 * - owner process descriptors (and attached lists), one per owner process
493 * - lookup hash tables for owner and target processes
494 * - PMC descriptors (and attached lists)
495 * - per-cpu hardware state
496 * - the 'hook' variable through which the kernel calls into
498 * - the machine hardware state (managed by the MD layer)
500 * These data structures are accessed from:
502 * - thread context-switch code
503 * - interrupt handlers (possibly on multiple cpus)
504 * - kernel threads on multiple cpus running on behalf of user
505 * processes doing system calls
506 * - this driver's private kernel threads
508 * = Locks and Locking strategy =
510 * The driver uses four locking strategies for its operation:
512 * - The global SX lock "pmc_sx" is used to protect internal
515 * Calls into the module by syscall() start with this lock being
516 * held in exclusive mode. Depending on the requested operation,
517 * the lock may be downgraded to 'shared' mode to allow more
518 * concurrent readers into the module. Calls into the module from
519 * other parts of the kernel acquire the lock in shared mode.
521 * This SX lock is held in exclusive mode for any operations that
522 * modify the linkages between the driver's internal data structures.
524 * The 'pmc_hook' function pointer is also protected by this lock.
525 * It is only examined with the sx lock held in exclusive mode. The
526 * kernel module is allowed to be unloaded only with the sx lock held
527 * in exclusive mode. In normal syscall handling, after acquiring the
528 * pmc_sx lock we first check that 'pmc_hook' is non-null before
529 * proceeding. This prevents races between the thread unloading the module
530 * and other threads seeking to use the module.
532 * - Lookups of target process structures and owner process structures
533 * cannot use the global "pmc_sx" SX lock because these lookups need
534 * to happen during context switches and in other critical sections
535 * where sleeping is not allowed. We protect these lookup tables
536 * with their own private spin-mutexes, "pmc_processhash_mtx" and
537 * "pmc_ownerhash_mtx".
539 * - Interrupt handlers work in a lock free manner. At interrupt
540 * time, handlers look at the PMC pointer (phw->phw_pmc) configured
541 * when the PMC was started. If this pointer is NULL, the interrupt
542 * is ignored after updating driver statistics. We ensure that this
543 * pointer is set (using an atomic operation if necessary) before the
544 * PMC hardware is started. Conversely, this pointer is unset atomically
545 * only after the PMC hardware is stopped.
547 * We ensure that everything needed for the operation of an
548 * interrupt handler is available without it needing to acquire any
549 * locks. We also ensure that a PMC's software state is destroyed only
550 * after the PMC is taken off hardware (on all CPUs).
552 * - Context-switch handling with process-private PMCs needs more
555 * A given process may be the target of multiple PMCs. For example,
556 * PMCATTACH and PMCDETACH may be requested by a process on one CPU
557 * while the target process is running on another. A PMC could also
558 * be getting released because its owner is exiting. We tackle
559 * these situations in the following manner:
561 * - each target process structure 'pmc_process' has an array
562 * of 'struct pmc *' pointers, one for each hardware PMC.
564 * - At context switch IN time, each "target" PMC in RUNNING state
565 * gets started on hardware and a pointer to each PMC is copied into
566 * the per-cpu phw array. The 'runcount' for the PMC is
569 * - At context switch OUT time, all process-virtual PMCs are stopped
570 * on hardware. The saved value is added to the PMCs value field
571 * only if the PMC is in a non-deleted state (the PMCs state could
572 * have changed during the current time slice).
574 * Note that since in-between a switch IN on a processor and a switch
575 * OUT, the PMC could have been released on another CPU. Therefore
576 * context switch OUT always looks at the hardware state to turn
577 * OFF PMCs and will update a PMC's saved value only if reachable
578 * from the target process record.
580 * - OP PMCRELEASE could be called on a PMC at any time (the PMC could
581 * be attached to many processes at the time of the call and could
582 * be active on multiple CPUs).
584 * We prevent further scheduling of the PMC by marking it as in
585 * state 'DELETED'. If the runcount of the PMC is non-zero then
586 * this PMC is currently running on a CPU somewhere. The thread
587 * doing the PMCRELEASE operation waits by repeatedly doing a
588 * pause() till the runcount comes to zero.
590 * The contents of a PMC descriptor (struct pmc) are protected using
591 * a spin-mutex. In order to save space, we use a mutex pool.
593 * In terms of lock types used by witness(4), we use:
594 * - Type "pmc-sx", used by the global SX lock.
595 * - Type "pmc-sleep", for sleep mutexes used by logger threads.
596 * - Type "pmc-per-proc", for protecting PMC owner descriptors.
597 * - Type "pmc-leaf", used for all other spin mutexes.
601 * save the cpu binding of the current kthread
605 pmc_save_cpu_binding(struct pmc_binding *pb)
607 PMCDBG(CPU,BND,2, "%s", "save-cpu");
608 thread_lock(curthread);
609 pb->pb_bound = sched_is_bound(curthread);
610 pb->pb_cpu = curthread->td_oncpu;
611 thread_unlock(curthread);
612 PMCDBG(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
616 * restore the cpu binding of the current thread
620 pmc_restore_cpu_binding(struct pmc_binding *pb)
622 PMCDBG(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
623 curthread->td_oncpu, pb->pb_cpu);
624 thread_lock(curthread);
626 sched_bind(curthread, pb->pb_cpu);
628 sched_unbind(curthread);
629 thread_unlock(curthread);
630 PMCDBG(CPU,BND,2, "%s", "restore-cpu done");
634 * move execution over the specified cpu and bind it there.
638 pmc_select_cpu(int cpu)
640 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
641 ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
643 /* Never move to an inactive CPU. */
644 KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
645 "CPU %d", __LINE__, cpu));
647 PMCDBG(CPU,SEL,2, "select-cpu cpu=%d", cpu);
648 thread_lock(curthread);
649 sched_bind(curthread, cpu);
650 thread_unlock(curthread);
652 KASSERT(curthread->td_oncpu == cpu,
653 ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
654 cpu, curthread->td_oncpu));
656 PMCDBG(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
660 * Force a context switch.
662 * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
663 * guaranteed to force a context switch.
667 pmc_force_context_switch(void)
674 * Get the file name for an executable. This is a simple wrapper
675 * around vn_fullpath(9).
679 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
682 *fullpath = "unknown";
684 vn_lock(v, LK_CANRECURSE | LK_EXCLUSIVE | LK_RETRY);
685 vn_fullpath(curthread, v, fullpath, freepath);
690 * remove an process owning PMCs
694 pmc_remove_owner(struct pmc_owner *po)
696 struct pmc *pm, *tmp;
698 sx_assert(&pmc_sx, SX_XLOCKED);
700 PMCDBG(OWN,ORM,1, "remove-owner po=%p", po);
702 /* Remove descriptor from the owner hash table */
703 LIST_REMOVE(po, po_next);
705 /* release all owned PMC descriptors */
706 LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
707 PMCDBG(OWN,ORM,2, "pmc=%p", pm);
708 KASSERT(pm->pm_owner == po,
709 ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
711 pmc_release_pmc_descriptor(pm); /* will unlink from the list */
714 KASSERT(po->po_sscount == 0,
715 ("[pmc,%d] SS count not zero", __LINE__));
716 KASSERT(LIST_EMPTY(&po->po_pmcs),
717 ("[pmc,%d] PMC list not empty", __LINE__));
719 /* de-configure the log file if present */
720 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
721 pmclog_deconfigure_log(po);
725 * remove an owner process record if all conditions are met.
729 pmc_maybe_remove_owner(struct pmc_owner *po)
732 PMCDBG(OWN,OMR,1, "maybe-remove-owner po=%p", po);
735 * Remove owner record if
736 * - this process does not own any PMCs
737 * - this process has not allocated a system-wide sampling buffer
740 if (LIST_EMPTY(&po->po_pmcs) &&
741 ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
742 pmc_remove_owner(po);
743 pmc_destroy_owner_descriptor(po);
748 * Add an association between a target process and a PMC.
752 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
755 struct pmc_target *pt;
757 sx_assert(&pmc_sx, SX_XLOCKED);
759 KASSERT(pm != NULL && pp != NULL,
760 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
761 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
762 ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
763 __LINE__, pm, pp->pp_proc->p_pid));
764 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < ((int) md->pmd_npmc - 1),
765 ("[pmc,%d] Illegal reference count %d for process record %p",
766 __LINE__, pp->pp_refcnt, (void *) pp));
768 ri = PMC_TO_ROWINDEX(pm);
770 PMCDBG(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
774 LIST_FOREACH(pt, &pm->pm_targets, pt_next)
775 if (pt->pt_process == pp)
776 KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
780 MALLOC(pt, struct pmc_target *, sizeof(struct pmc_target),
781 M_PMC, M_ZERO|M_WAITOK);
785 LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
787 atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
790 if (pm->pm_owner->po_owner == pp->pp_proc)
791 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
794 * Initialize the per-process values at this row index.
796 pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
797 pm->pm_sc.pm_reloadcount : 0;
804 * Removes the association between a target process and a PMC.
808 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
812 struct pmc_target *ptgt;
814 sx_assert(&pmc_sx, SX_XLOCKED);
816 KASSERT(pm != NULL && pp != NULL,
817 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
819 KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt < (int) md->pmd_npmc,
820 ("[pmc,%d] Illegal ref count %d on process record %p",
821 __LINE__, pp->pp_refcnt, (void *) pp));
823 ri = PMC_TO_ROWINDEX(pm);
825 PMCDBG(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
828 KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
829 ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
830 ri, pm, pp->pp_pmcs[ri].pp_pmc));
832 pp->pp_pmcs[ri].pp_pmc = NULL;
833 pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
835 /* Remove owner-specific flags */
836 if (pm->pm_owner->po_owner == pp->pp_proc) {
837 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
838 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
843 /* Remove the target process from the PMC structure */
844 LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
845 if (ptgt->pt_process == pp)
848 KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
849 "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
851 LIST_REMOVE(ptgt, pt_next);
854 /* if the PMC now lacks targets, send the owner a SIGIO */
855 if (LIST_EMPTY(&pm->pm_targets)) {
856 p = pm->pm_owner->po_owner;
861 PMCDBG(PRC,SIG,2, "signalling proc=%p signal=%d", p,
867 * Check if PMC 'pm' may be attached to target process 't'.
871 pmc_can_attach(struct pmc *pm, struct proc *t)
873 struct proc *o; /* pmc owner */
874 struct ucred *oc, *tc; /* owner, target credentials */
875 int decline_attach, i;
878 * A PMC's owner can always attach that PMC to itself.
881 if ((o = pm->pm_owner->po_owner) == t)
895 * The effective uid of the PMC owner should match at least one
896 * of the {effective,real,saved} uids of the target process.
899 decline_attach = oc->cr_uid != tc->cr_uid &&
900 oc->cr_uid != tc->cr_svuid &&
901 oc->cr_uid != tc->cr_ruid;
904 * Every one of the target's group ids, must be in the owner's
907 for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
908 decline_attach = !groupmember(tc->cr_groups[i], oc);
910 /* check the read and saved gids too */
911 if (decline_attach == 0)
912 decline_attach = !groupmember(tc->cr_rgid, oc) ||
913 !groupmember(tc->cr_svgid, oc);
918 return !decline_attach;
922 * Attach a process to a PMC.
926 pmc_attach_one_process(struct proc *p, struct pmc *pm)
929 char *fullpath, *freepath;
930 struct pmc_process *pp;
932 sx_assert(&pmc_sx, SX_XLOCKED);
934 PMCDBG(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
935 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
938 * Locate the process descriptor corresponding to process 'p',
939 * allocating space as needed.
941 * Verify that rowindex 'pm_rowindex' is free in the process
944 * If not, allocate space for a descriptor and link the
945 * process descriptor and PMC.
947 ri = PMC_TO_ROWINDEX(pm);
949 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
952 if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
955 if (pp->pp_pmcs[ri].pp_pmc != NULL)
958 pmc_link_target_process(pm, pp);
960 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
961 (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
962 pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
964 pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
966 /* issue an attach event to a configured log file */
967 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
968 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
969 if (p->p_flag & P_KTHREAD) {
970 fullpath = kernelname;
973 pmclog_process_pmcattach(pm, p->p_pid, fullpath);
975 FREE(freepath, M_TEMP);
976 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
977 pmc_log_process_mappings(pm->pm_owner, p);
979 /* mark process as using HWPMCs */
981 p->p_flag |= P_HWPMC;
988 * Attach a process and optionally its children
992 pmc_attach_process(struct proc *p, struct pmc *pm)
997 sx_assert(&pmc_sx, SX_XLOCKED);
999 PMCDBG(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1000 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1004 * If this PMC successfully allowed a GETMSR operation
1005 * in the past, disallow further ATTACHes.
1008 if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1011 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1012 return pmc_attach_one_process(p, pm);
1015 * Traverse all child processes, attaching them to
1019 sx_slock(&proctree_lock);
1024 if ((error = pmc_attach_one_process(p, pm)) != 0)
1026 if (!LIST_EMPTY(&p->p_children))
1027 p = LIST_FIRST(&p->p_children);
1031 if (LIST_NEXT(p, p_sibling)) {
1032 p = LIST_NEXT(p, p_sibling);
1040 (void) pmc_detach_process(top, pm);
1043 sx_sunlock(&proctree_lock);
1048 * Detach a process from a PMC. If there are no other PMCs tracking
1049 * this process, remove the process structure from its hash table. If
1050 * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1054 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1057 struct pmc_process *pp;
1059 sx_assert(&pmc_sx, SX_XLOCKED);
1062 ("[pmc,%d] null pm pointer", __LINE__));
1064 ri = PMC_TO_ROWINDEX(pm);
1066 PMCDBG(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1067 pm, ri, p, p->p_pid, p->p_comm, flags);
1069 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1072 if (pp->pp_pmcs[ri].pp_pmc != pm)
1075 pmc_unlink_target_process(pm, pp);
1077 /* Issue a detach entry if a log file is configured */
1078 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1079 pmclog_process_pmcdetach(pm, p->p_pid);
1082 * If there are no PMCs targetting this process, we remove its
1083 * descriptor from the target hash table and unset the P_HWPMC
1084 * flag in the struct proc.
1086 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1087 ("[pmc,%d] Illegal refcnt %d for process struct %p",
1088 __LINE__, pp->pp_refcnt, pp));
1090 if (pp->pp_refcnt != 0) /* still a target of some PMC */
1093 pmc_remove_process_descriptor(pp);
1095 if (flags & PMC_FLAG_REMOVE)
1099 p->p_flag &= ~P_HWPMC;
1106 * Detach a process and optionally its descendants from a PMC.
1110 pmc_detach_process(struct proc *p, struct pmc *pm)
1114 sx_assert(&pmc_sx, SX_XLOCKED);
1116 PMCDBG(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1117 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1119 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1120 return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1123 * Traverse all children, detaching them from this PMC. We
1124 * ignore errors since we could be detaching a PMC from a
1125 * partially attached proc tree.
1128 sx_slock(&proctree_lock);
1133 (void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1135 if (!LIST_EMPTY(&p->p_children))
1136 p = LIST_FIRST(&p->p_children);
1140 if (LIST_NEXT(p, p_sibling)) {
1141 p = LIST_NEXT(p, p_sibling);
1149 sx_sunlock(&proctree_lock);
1151 if (LIST_EMPTY(&pm->pm_targets))
1152 pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1159 * Thread context switch IN
1163 pmc_process_csw_in(struct thread *td)
1171 struct pmc_process *pp;
1172 pmc_value_t newvalue;
1176 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1179 KASSERT(pp->pp_proc == td->td_proc,
1180 ("[pmc,%d] not my thread state", __LINE__));
1182 critical_enter(); /* no preemption from this point */
1184 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1186 PMCDBG(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1187 p->p_pid, p->p_comm, pp);
1189 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1190 ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
1194 for (ri = 0; ri < md->pmd_npmc; ri++) {
1196 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1199 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1200 ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1201 __LINE__, PMC_TO_MODE(pm)));
1203 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1204 ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1205 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1208 * Only PMCs that are marked as 'RUNNING' need
1209 * be placed on hardware.
1212 if (pm->pm_state != PMC_STATE_RUNNING)
1215 /* increment PMC runcount */
1216 atomic_add_rel_32(&pm->pm_runcount, 1);
1218 /* configure the HWPMC we are going to use. */
1219 md->pmd_config_pmc(cpu, ri, pm);
1221 phw = pc->pc_hwpmcs[ri];
1223 KASSERT(phw != NULL,
1224 ("[pmc,%d] null hw pointer", __LINE__));
1226 KASSERT(phw->phw_pmc == pm,
1227 ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1231 * Write out saved value and start the PMC.
1233 * Sampling PMCs use a per-process value, while
1234 * counting mode PMCs use a per-pmc value that is
1235 * inherited across descendants.
1237 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1238 mtx_pool_lock_spin(pmc_mtxpool, pm);
1239 newvalue = PMC_PCPU_SAVED(cpu,ri) =
1240 pp->pp_pmcs[ri].pp_pmcval;
1241 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1243 KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1244 ("[pmc,%d] illegal mode=%d", __LINE__,
1246 mtx_pool_lock_spin(pmc_mtxpool, pm);
1247 newvalue = PMC_PCPU_SAVED(cpu, ri) =
1248 pm->pm_gv.pm_savedvalue;
1249 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1252 PMCDBG(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1254 md->pmd_write_pmc(cpu, ri, newvalue);
1255 md->pmd_start_pmc(cpu, ri);
1259 * perform any other architecture/cpu dependent thread
1260 * switch-in actions.
1263 (void) (*md->pmd_switch_in)(pc, pp);
1270 * Thread context switch OUT.
1274 pmc_process_csw_out(struct thread *td)
1282 struct pmc_process *pp;
1284 pmc_value_t newvalue;
1287 * Locate our process descriptor; this may be NULL if
1288 * this process is exiting and we have already removed
1289 * the process from the target process table.
1291 * Note that due to kernel preemption, multiple
1292 * context switches may happen while the process is
1295 * Note also that if the target process cannot be
1296 * found we still need to deconfigure any PMCs that
1297 * are currently running on hardware.
1301 pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1309 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1311 PMCDBG(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1312 p->p_pid, p->p_comm, pp);
1314 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1315 ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1320 * When a PMC gets unlinked from a target PMC, it will
1321 * be removed from the target's pp_pmc[] array.
1323 * However, on a MP system, the target could have been
1324 * executing on another CPU at the time of the unlink.
1325 * So, at context switch OUT time, we need to look at
1326 * the hardware to determine if a PMC is scheduled on
1330 for (ri = 0; ri < md->pmd_npmc; ri++) {
1333 (void) (*md->pmd_get_config)(cpu, ri, &pm);
1335 if (pm == NULL) /* nothing at this row index */
1338 mode = PMC_TO_MODE(pm);
1339 if (!PMC_IS_VIRTUAL_MODE(mode))
1340 continue; /* not a process virtual PMC */
1342 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1343 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1344 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1346 /* Stop hardware if not already stopped */
1347 if (pm->pm_stalled == 0)
1348 md->pmd_stop_pmc(cpu, ri);
1350 /* reduce this PMC's runcount */
1351 atomic_subtract_rel_32(&pm->pm_runcount, 1);
1354 * If this PMC is associated with this process,
1358 if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1360 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1361 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1362 pm, ri, pp->pp_pmcs[ri].pp_pmc));
1364 KASSERT(pp->pp_refcnt > 0,
1365 ("[pmc,%d] pp refcnt = %d", __LINE__,
1368 md->pmd_read_pmc(cpu, ri, &newvalue);
1370 tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1372 PMCDBG(CSW,SWI,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
1375 if (mode == PMC_MODE_TS) {
1378 * For sampling process-virtual PMCs,
1379 * we expect the count to be
1380 * decreasing as the 'value'
1381 * programmed into the PMC is the
1382 * number of events to be seen till
1383 * the next sampling interrupt.
1386 tmp += pm->pm_sc.pm_reloadcount;
1387 mtx_pool_lock_spin(pmc_mtxpool, pm);
1388 pp->pp_pmcs[ri].pp_pmcval -= tmp;
1389 if ((int64_t) pp->pp_pmcs[ri].pp_pmcval < 0)
1390 pp->pp_pmcs[ri].pp_pmcval +=
1391 pm->pm_sc.pm_reloadcount;
1392 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1397 * For counting process-virtual PMCs,
1398 * we expect the count to be
1399 * increasing monotonically, modulo a 64
1402 KASSERT((int64_t) tmp >= 0,
1403 ("[pmc,%d] negative increment cpu=%d "
1404 "ri=%d newvalue=%jx saved=%jx "
1405 "incr=%jx", __LINE__, cpu, ri,
1406 newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1408 mtx_pool_lock_spin(pmc_mtxpool, pm);
1409 pm->pm_gv.pm_savedvalue += tmp;
1410 pp->pp_pmcs[ri].pp_pmcval += tmp;
1411 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1413 if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1414 pmclog_process_proccsw(pm, pp, tmp);
1418 /* mark hardware as free */
1419 md->pmd_config_pmc(cpu, ri, NULL);
1423 * perform any other architecture/cpu dependent thread
1424 * switch out functions.
1427 (void) (*md->pmd_switch_out)(pc, pp);
1433 * Log a KLD operation.
1437 pmc_process_kld_load(struct pmckern_map_in *pkm)
1439 struct pmc_owner *po;
1441 sx_assert(&pmc_sx, SX_LOCKED);
1444 * Notify owners of system sampling PMCs about KLD operations.
1447 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1448 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1449 pmclog_process_map_in(po, (pid_t) -1, pkm->pm_address,
1450 (char *) pkm->pm_file);
1453 * TODO: Notify owners of (all) process-sampling PMCs too.
1460 pmc_process_kld_unload(struct pmckern_map_out *pkm)
1462 struct pmc_owner *po;
1464 sx_assert(&pmc_sx, SX_LOCKED);
1466 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1467 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1468 pmclog_process_map_out(po, (pid_t) -1,
1469 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1472 * TODO: Notify owners of process-sampling PMCs.
1477 * A mapping change for a process.
1481 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1485 char *fullpath, *freepath;
1486 const struct pmc *pm;
1487 struct pmc_owner *po;
1488 const struct pmc_process *pp;
1490 freepath = fullpath = NULL;
1491 pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1493 pid = td->td_proc->p_pid;
1495 /* Inform owners of all system-wide sampling PMCs. */
1496 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1497 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1498 pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1500 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1504 * Inform sampling PMC owners tracking this process.
1506 for (ri = 0; ri < md->pmd_npmc; ri++)
1507 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1508 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1509 pmclog_process_map_in(pm->pm_owner,
1510 pid, pkm->pm_address, fullpath);
1514 FREE(freepath, M_TEMP);
1519 * Log an munmap request.
1523 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1527 struct pmc_owner *po;
1528 const struct pmc *pm;
1529 const struct pmc_process *pp;
1531 pid = td->td_proc->p_pid;
1533 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1534 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1535 pmclog_process_map_out(po, pid, pkm->pm_address,
1536 pkm->pm_address + pkm->pm_size);
1538 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1541 for (ri = 0; ri < md->pmd_npmc; ri++)
1542 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1543 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1544 pmclog_process_map_out(pm->pm_owner, pid,
1545 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1549 * Log mapping information about the kernel.
1553 pmc_log_kernel_mappings(struct pmc *pm)
1555 struct pmc_owner *po;
1556 struct pmckern_map_in *km, *kmbase;
1558 sx_assert(&pmc_sx, SX_LOCKED);
1559 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1560 ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1561 __LINE__, (void *) pm));
1565 if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1569 * Log the current set of kernel modules.
1571 kmbase = linker_hwpmc_list_objects();
1572 for (km = kmbase; km->pm_file != NULL; km++) {
1573 PMCDBG(LOG,REG,1,"%s %p", (char *) km->pm_file,
1574 (void *) km->pm_address);
1575 pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1578 FREE(kmbase, M_LINKER);
1580 po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1584 * Log the mappings for a single process.
1588 pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1593 * Log mappings for all processes in the system.
1597 pmc_log_all_process_mappings(struct pmc_owner *po)
1599 struct proc *p, *top;
1601 sx_assert(&pmc_sx, SX_XLOCKED);
1603 if ((p = pfind(1)) == NULL)
1604 panic("[pmc,%d] Cannot find init", __LINE__);
1608 sx_slock(&proctree_lock);
1613 pmc_log_process_mappings(po, p);
1614 if (!LIST_EMPTY(&p->p_children))
1615 p = LIST_FIRST(&p->p_children);
1619 if (LIST_NEXT(p, p_sibling)) {
1620 p = LIST_NEXT(p, p_sibling);
1627 sx_sunlock(&proctree_lock);
1631 * The 'hook' invoked from the kernel proper
1636 const char *pmc_hooknames[] = {
1637 /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1652 pmc_hook_handler(struct thread *td, int function, void *arg)
1655 PMCDBG(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1656 pmc_hooknames[function], arg);
1665 case PMC_FN_PROCESS_EXEC:
1667 char *fullpath, *freepath;
1669 int is_using_hwpmcs;
1672 struct pmc_owner *po;
1673 struct pmc_process *pp;
1674 struct pmckern_procexec *pk;
1676 sx_assert(&pmc_sx, SX_XLOCKED);
1679 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1681 pk = (struct pmckern_procexec *) arg;
1683 /* Inform owners of SS mode PMCs of the exec event. */
1684 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1685 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1686 pmclog_process_procexec(po, PMC_ID_INVALID,
1687 p->p_pid, pk->pm_entryaddr, fullpath);
1690 is_using_hwpmcs = p->p_flag & P_HWPMC;
1693 if (!is_using_hwpmcs) {
1695 FREE(freepath, M_TEMP);
1700 * PMCs are not inherited across an exec(): remove any
1701 * PMCs that this process is the owner of.
1704 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1705 pmc_remove_owner(po);
1706 pmc_destroy_owner_descriptor(po);
1710 * If the process being exec'ed is not the target of any
1713 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1715 FREE(freepath, M_TEMP);
1720 * Log the exec event to all monitoring owners. Skip
1721 * owners who have already recieved the event because
1722 * they had system sampling PMCs active.
1724 for (ri = 0; ri < md->pmd_npmc; ri++)
1725 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1727 if (po->po_sscount == 0 &&
1728 po->po_flags & PMC_PO_OWNS_LOGFILE)
1729 pmclog_process_procexec(po, pm->pm_id,
1730 p->p_pid, pk->pm_entryaddr,
1735 FREE(freepath, M_TEMP);
1738 PMCDBG(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1739 p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1741 if (pk->pm_credentialschanged == 0) /* no change */
1745 * If the newly exec()'ed process has a different credential
1746 * than before, allow it to be the target of a PMC only if
1747 * the PMC's owner has sufficient priviledge.
1750 for (ri = 0; ri < md->pmd_npmc; ri++)
1751 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1752 if (pmc_can_attach(pm, td->td_proc) != 0)
1753 pmc_detach_one_process(td->td_proc,
1756 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1757 ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1758 pp->pp_refcnt, pp));
1761 * If this process is no longer the target of any
1762 * PMCs, we can remove the process entry and free
1766 if (pp->pp_refcnt == 0) {
1767 pmc_remove_process_descriptor(pp);
1776 pmc_process_csw_in(td);
1779 case PMC_FN_CSW_OUT:
1780 pmc_process_csw_out(td);
1784 * Process accumulated PC samples.
1786 * This function is expected to be called by hardclock() for
1787 * each CPU that has accumulated PC samples.
1789 * This function is to be executed on the CPU whose samples
1790 * are being processed.
1792 case PMC_FN_DO_SAMPLES:
1795 * Clear the cpu specific bit in the CPU mask before
1796 * do the rest of the processing. If the NMI handler
1797 * gets invoked after the "atomic_clear_int()" call
1798 * below but before "pmc_process_samples()" gets
1799 * around to processing the interrupt, then we will
1800 * come back here at the next hardclock() tick (and
1801 * may find nothing to do if "pmc_process_samples()"
1802 * had already processed the interrupt). We don't
1803 * lose the interrupt sample.
1805 atomic_clear_int(&pmc_cpumask, (1 << PCPU_GET(cpuid)));
1806 pmc_process_samples(PCPU_GET(cpuid));
1810 case PMC_FN_KLD_LOAD:
1811 sx_assert(&pmc_sx, SX_LOCKED);
1812 pmc_process_kld_load((struct pmckern_map_in *) arg);
1815 case PMC_FN_KLD_UNLOAD:
1816 sx_assert(&pmc_sx, SX_LOCKED);
1817 pmc_process_kld_unload((struct pmckern_map_out *) arg);
1821 sx_assert(&pmc_sx, SX_LOCKED);
1822 pmc_process_mmap(td, (struct pmckern_map_in *) arg);
1826 sx_assert(&pmc_sx, SX_LOCKED);
1827 pmc_process_munmap(td, (struct pmckern_map_out *) arg);
1830 case PMC_FN_USER_CALLCHAIN:
1832 * Record a call chain.
1834 pmc_capture_user_callchain(PCPU_GET(cpuid),
1835 (struct trapframe *) arg);
1840 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
1850 * allocate a 'struct pmc_owner' descriptor in the owner hash table.
1853 static struct pmc_owner *
1854 pmc_allocate_owner_descriptor(struct proc *p)
1857 struct pmc_owner *po;
1858 struct pmc_ownerhash *poh;
1860 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1861 poh = &pmc_ownerhash[hindex];
1863 /* allocate space for N pointers and one descriptor struct */
1864 MALLOC(po, struct pmc_owner *, sizeof(struct pmc_owner),
1865 M_PMC, M_ZERO|M_WAITOK);
1867 po->po_sscount = po->po_error = po->po_flags = 0;
1870 po->po_kthread = NULL;
1871 LIST_INIT(&po->po_pmcs);
1872 LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
1874 TAILQ_INIT(&po->po_logbuffers);
1875 mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
1877 PMCDBG(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
1878 p, p->p_pid, p->p_comm, po);
1884 pmc_destroy_owner_descriptor(struct pmc_owner *po)
1887 PMCDBG(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
1888 po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
1890 mtx_destroy(&po->po_mtx);
1895 * find the descriptor corresponding to process 'p', adding or removing it
1896 * as specified by 'mode'.
1899 static struct pmc_process *
1900 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
1903 struct pmc_process *pp, *ppnew;
1904 struct pmc_processhash *pph;
1906 hindex = PMC_HASH_PTR(p, pmc_processhashmask);
1907 pph = &pmc_processhash[hindex];
1912 * Pre-allocate memory in the FIND_ALLOCATE case since we
1913 * cannot call malloc(9) once we hold a spin lock.
1916 if (mode & PMC_FLAG_ALLOCATE) {
1917 /* allocate additional space for 'n' pmc pointers */
1918 MALLOC(ppnew, struct pmc_process *,
1919 sizeof(struct pmc_process) + md->pmd_npmc *
1920 sizeof(struct pmc_targetstate), M_PMC, M_ZERO|M_WAITOK);
1923 mtx_lock_spin(&pmc_processhash_mtx);
1924 LIST_FOREACH(pp, pph, pp_next)
1925 if (pp->pp_proc == p)
1928 if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
1929 LIST_REMOVE(pp, pp_next);
1931 if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
1934 LIST_INSERT_HEAD(pph, ppnew, pp_next);
1938 mtx_unlock_spin(&pmc_processhash_mtx);
1940 if (pp != NULL && ppnew != NULL)
1947 * remove a process descriptor from the process hash table.
1951 pmc_remove_process_descriptor(struct pmc_process *pp)
1953 KASSERT(pp->pp_refcnt == 0,
1954 ("[pmc,%d] Removing process descriptor %p with count %d",
1955 __LINE__, pp, pp->pp_refcnt));
1957 mtx_lock_spin(&pmc_processhash_mtx);
1958 LIST_REMOVE(pp, pp_next);
1959 mtx_unlock_spin(&pmc_processhash_mtx);
1964 * find an owner descriptor corresponding to proc 'p'
1967 static struct pmc_owner *
1968 pmc_find_owner_descriptor(struct proc *p)
1971 struct pmc_owner *po;
1972 struct pmc_ownerhash *poh;
1974 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1975 poh = &pmc_ownerhash[hindex];
1978 LIST_FOREACH(po, poh, po_next)
1979 if (po->po_owner == p)
1982 PMCDBG(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
1983 "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
1989 * pmc_allocate_pmc_descriptor
1991 * Allocate a pmc descriptor and initialize its
1996 pmc_allocate_pmc_descriptor(void)
2000 MALLOC(pmc, struct pmc *, sizeof(struct pmc), M_PMC, M_ZERO|M_WAITOK);
2003 pmc->pm_owner = NULL;
2004 LIST_INIT(&pmc->pm_targets);
2007 PMCDBG(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2013 * Destroy a pmc descriptor.
2017 pmc_destroy_pmc_descriptor(struct pmc *pm)
2022 KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2023 pm->pm_state == PMC_STATE_FREE,
2024 ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2025 KASSERT(LIST_EMPTY(&pm->pm_targets),
2026 ("[pmc,%d] destroying pmc with targets", __LINE__));
2027 KASSERT(pm->pm_owner == NULL,
2028 ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2029 KASSERT(pm->pm_runcount == 0,
2030 ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
2036 pmc_wait_for_pmc_idle(struct pmc *pm)
2039 volatile int maxloop;
2041 maxloop = 100 * pmc_cpu_max();
2045 * Loop (with a forced context switch) till the PMC's runcount
2046 * comes down to zero.
2048 while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
2051 KASSERT(maxloop > 0,
2052 ("[pmc,%d] (ri%d, rc%d) waiting too long for "
2053 "pmc to be free", __LINE__,
2054 PMC_TO_ROWINDEX(pm), pm->pm_runcount));
2056 pmc_force_context_switch();
2061 * This function does the following things:
2063 * - detaches the PMC from hardware
2064 * - unlinks all target threads that were attached to it
2065 * - removes the PMC from its owner's list
2066 * - destroy's the PMC private mutex
2068 * Once this function completes, the given pmc pointer can be safely
2069 * FREE'd by the caller.
2073 pmc_release_pmc_descriptor(struct pmc *pm)
2078 struct pmc_owner *po;
2079 struct pmc_process *pp;
2080 struct pmc_target *ptgt, *tmp;
2081 struct pmc_binding pb;
2083 sx_assert(&pmc_sx, SX_XLOCKED);
2085 KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2087 ri = PMC_TO_ROWINDEX(pm);
2088 mode = PMC_TO_MODE(pm);
2090 PMCDBG(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2094 * First, we take the PMC off hardware.
2097 if (PMC_IS_SYSTEM_MODE(mode)) {
2100 * A system mode PMC runs on a specific CPU. Switch
2101 * to this CPU and turn hardware off.
2103 pmc_save_cpu_binding(&pb);
2105 cpu = PMC_TO_CPU(pm);
2107 pmc_select_cpu(cpu);
2109 /* switch off non-stalled CPUs */
2110 if (pm->pm_state == PMC_STATE_RUNNING &&
2111 pm->pm_stalled == 0) {
2113 phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2115 KASSERT(phw->phw_pmc == pm,
2116 ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2117 __LINE__, ri, phw->phw_pmc, pm));
2118 PMCDBG(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2121 md->pmd_stop_pmc(cpu, ri);
2125 PMCDBG(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2128 md->pmd_config_pmc(cpu, ri, NULL);
2131 /* adjust the global and process count of SS mode PMCs */
2132 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2135 if (po->po_sscount == 0) {
2136 atomic_subtract_rel_int(&pmc_ss_count, 1);
2137 LIST_REMOVE(po, po_ssnext);
2141 pm->pm_state = PMC_STATE_DELETED;
2143 pmc_restore_cpu_binding(&pb);
2146 * We could have references to this PMC structure in
2147 * the per-cpu sample queues. Wait for the queue to
2150 pmc_wait_for_pmc_idle(pm);
2152 } else if (PMC_IS_VIRTUAL_MODE(mode)) {
2155 * A virtual PMC could be running on multiple CPUs at
2158 * By marking its state as DELETED, we ensure that
2159 * this PMC is never further scheduled on hardware.
2161 * Then we wait till all CPUs are done with this PMC.
2163 pm->pm_state = PMC_STATE_DELETED;
2166 /* Wait for the PMCs runcount to come to zero. */
2167 pmc_wait_for_pmc_idle(pm);
2170 * At this point the PMC is off all CPUs and cannot be
2171 * freshly scheduled onto a CPU. It is now safe to
2172 * unlink all targets from this PMC. If a
2173 * process-record's refcount falls to zero, we remove
2174 * it from the hash table. The module-wide SX lock
2175 * protects us from races.
2177 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2178 pp = ptgt->pt_process;
2179 pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2181 PMCDBG(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2184 * If the target process record shows that no
2185 * PMCs are attached to it, reclaim its space.
2188 if (pp->pp_refcnt == 0) {
2189 pmc_remove_process_descriptor(pp);
2194 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2199 * Release any MD resources
2202 (void) md->pmd_release_pmc(cpu, ri, pm);
2205 * Update row disposition
2208 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2209 PMC_UNMARK_ROW_STANDALONE(ri);
2211 PMC_UNMARK_ROW_THREAD(ri);
2213 /* unlink from the owner's list */
2215 LIST_REMOVE(pm, pm_next);
2216 pm->pm_owner = NULL;
2219 pmc_destroy_pmc_descriptor(pm);
2223 * Register an owner and a pmc.
2227 pmc_register_owner(struct proc *p, struct pmc *pmc)
2229 struct pmc_owner *po;
2231 sx_assert(&pmc_sx, SX_XLOCKED);
2233 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2234 if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2237 KASSERT(pmc->pm_owner == NULL,
2238 ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2241 LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2244 p->p_flag |= P_HWPMC;
2247 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2248 pmclog_process_pmcallocate(pmc);
2250 PMCDBG(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2257 * Return the current row disposition:
2259 * > 0 => PROCESS MODE
2260 * < 0 => SYSTEM MODE
2264 pmc_getrowdisp(int ri)
2266 return pmc_pmcdisp[ri];
2270 * Check if a PMC at row index 'ri' can be allocated to the current
2273 * Allocation can fail if:
2274 * - the current process is already being profiled by a PMC at index 'ri',
2275 * attached to it via OP_PMCATTACH.
2276 * - the current process has already allocated a PMC at index 'ri'
2281 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2285 struct pmc_owner *po;
2286 struct pmc_process *pp;
2288 PMCDBG(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2289 "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2292 * We shouldn't have already allocated a process-mode PMC at
2295 * We shouldn't have allocated a system-wide PMC on the same
2298 if ((po = pmc_find_owner_descriptor(p)) != NULL)
2299 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2300 if (PMC_TO_ROWINDEX(pm) == ri) {
2301 mode = PMC_TO_MODE(pm);
2302 if (PMC_IS_VIRTUAL_MODE(mode))
2304 if (PMC_IS_SYSTEM_MODE(mode) &&
2305 (int) PMC_TO_CPU(pm) == cpu)
2311 * We also shouldn't be the target of any PMC at this index
2312 * since otherwise a PMC_ATTACH to ourselves will fail.
2314 if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2315 if (pp->pp_pmcs[ri].pp_pmc)
2318 PMCDBG(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2319 p, p->p_pid, p->p_comm, ri);
2325 * Check if a given PMC at row index 'ri' can be currently used in
2330 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2334 sx_assert(&pmc_sx, SX_XLOCKED);
2336 PMCDBG(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2338 if (PMC_IS_SYSTEM_MODE(mode))
2339 disp = PMC_DISP_STANDALONE;
2341 disp = PMC_DISP_THREAD;
2344 * check disposition for PMC row 'ri':
2346 * Expected disposition Row-disposition Result
2348 * STANDALONE STANDALONE or FREE proceed
2349 * STANDALONE THREAD fail
2350 * THREAD THREAD or FREE proceed
2351 * THREAD STANDALONE fail
2354 if (!PMC_ROW_DISP_IS_FREE(ri) &&
2355 !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2356 !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2363 PMCDBG(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2370 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2374 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2378 KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2379 ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2380 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2382 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2383 if (pm->pm_id == pmcid)
2390 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2394 struct pmc_owner *po;
2396 PMCDBG(PMC,FND,1, "find-pmc id=%d", pmcid);
2398 if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2401 if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2404 PMCDBG(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2415 pmc_start(struct pmc *pm)
2419 struct pmc_owner *po;
2420 struct pmc_binding pb;
2423 ("[pmc,%d] null pm", __LINE__));
2425 mode = PMC_TO_MODE(pm);
2426 ri = PMC_TO_ROWINDEX(pm);
2429 PMCDBG(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2434 * Disallow PMCSTART if a logfile is required but has not been
2437 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2438 (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2439 return EDOOFUS; /* programming error */
2442 * If this is a sampling mode PMC, log mapping information for
2443 * the kernel modules that are currently loaded.
2445 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2446 pmc_log_kernel_mappings(pm);
2448 if (PMC_IS_VIRTUAL_MODE(mode)) {
2451 * If a PMCATTACH has never been done on this PMC,
2452 * attach it to its owner process.
2455 if (LIST_EMPTY(&pm->pm_targets))
2456 error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2457 pmc_attach_process(po->po_owner, pm);
2460 * If the PMC is attached to its owner, then force a context
2461 * switch to ensure that the MD state gets set correctly.
2465 pm->pm_state = PMC_STATE_RUNNING;
2466 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2467 pmc_force_context_switch();
2475 * A system-wide PMC.
2477 * Add the owner to the global list if this is a system-wide
2481 if (mode == PMC_MODE_SS) {
2482 if (po->po_sscount == 0) {
2483 LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2484 atomic_add_rel_int(&pmc_ss_count, 1);
2485 PMCDBG(PMC,OPS,1, "po=%p in global list", po);
2490 /* Log mapping information for all processes in the system. */
2491 pmc_log_all_process_mappings(po);
2494 * Move to the CPU associated with this
2495 * PMC, and start the hardware.
2498 pmc_save_cpu_binding(&pb);
2500 cpu = PMC_TO_CPU(pm);
2502 if (!pmc_cpu_is_active(cpu))
2505 pmc_select_cpu(cpu);
2508 * global PMCs are configured at allocation time
2509 * so write out the initial value and start the PMC.
2512 pm->pm_state = PMC_STATE_RUNNING;
2515 if ((error = md->pmd_write_pmc(cpu, ri,
2516 PMC_IS_SAMPLING_MODE(mode) ?
2517 pm->pm_sc.pm_reloadcount :
2518 pm->pm_sc.pm_initial)) == 0)
2519 error = md->pmd_start_pmc(cpu, ri);
2522 pmc_restore_cpu_binding(&pb);
2532 pmc_stop(struct pmc *pm)
2535 struct pmc_owner *po;
2536 struct pmc_binding pb;
2538 KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2540 PMCDBG(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2541 PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2543 pm->pm_state = PMC_STATE_STOPPED;
2546 * If the PMC is a virtual mode one, changing the state to
2547 * non-RUNNING is enough to ensure that the PMC never gets
2550 * If this PMC is current running on a CPU, then it will
2551 * handled correctly at the time its target process is context
2555 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2559 * A system-mode PMC. Move to the CPU associated with
2560 * this PMC, and stop the hardware. We update the
2561 * 'initial count' so that a subsequent PMCSTART will
2562 * resume counting from the current hardware count.
2565 pmc_save_cpu_binding(&pb);
2567 cpu = PMC_TO_CPU(pm);
2569 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
2570 ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2572 if (!pmc_cpu_is_active(cpu))
2575 pmc_select_cpu(cpu);
2577 ri = PMC_TO_ROWINDEX(pm);
2580 if ((error = md->pmd_stop_pmc(cpu, ri)) == 0)
2581 error = md->pmd_read_pmc(cpu, ri, &pm->pm_sc.pm_initial);
2584 pmc_restore_cpu_binding(&pb);
2588 /* remove this owner from the global list of SS PMC owners */
2589 if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2591 if (po->po_sscount == 0) {
2592 atomic_subtract_rel_int(&pmc_ss_count, 1);
2593 LIST_REMOVE(po, po_ssnext);
2594 PMCDBG(PMC,OPS,2,"po=%p removed from global list", po);
2603 static const char *pmc_op_to_name[] = {
2605 #define __PMC_OP(N, D) #N ,
2612 * The syscall interface
2615 #define PMC_GET_SX_XLOCK(...) do { \
2616 sx_xlock(&pmc_sx); \
2617 if (pmc_hook == NULL) { \
2618 sx_xunlock(&pmc_sx); \
2619 return __VA_ARGS__; \
2623 #define PMC_DOWNGRADE_SX() do { \
2624 sx_downgrade(&pmc_sx); \
2625 is_sx_downgraded = 1; \
2629 pmc_syscall_handler(struct thread *td, void *syscall_args)
2631 int error, is_sx_downgraded, op;
2632 struct pmc_syscall_args *c;
2635 PMC_GET_SX_XLOCK(ENOSYS);
2639 is_sx_downgraded = 0;
2641 c = (struct pmc_syscall_args *) syscall_args;
2646 PMCDBG(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2647 pmc_op_to_name[op], arg);
2650 atomic_add_int(&pmc_stats.pm_syscalls, 1);
2657 * Configure a log file.
2659 * XXX This OP will be reworked.
2662 case PMC_OP_CONFIGURELOG:
2666 struct pmc_owner *po;
2667 struct pmc_op_configurelog cl;
2669 sx_assert(&pmc_sx, SX_XLOCKED);
2671 if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2674 /* mark this process as owning a log file */
2676 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2677 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2683 * If a valid fd was passed in, try to configure that,
2684 * otherwise if 'fd' was less than zero and there was
2685 * a log file configured, flush its buffers and
2688 if (cl.pm_logfd >= 0)
2689 error = pmclog_configure_log(po, cl.pm_logfd);
2690 else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2691 pmclog_process_closelog(po);
2692 error = pmclog_flush(po);
2694 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2695 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2696 pm->pm_state == PMC_STATE_RUNNING)
2698 error = pmclog_deconfigure_log(po);
2713 case PMC_OP_FLUSHLOG:
2715 struct pmc_owner *po;
2717 sx_assert(&pmc_sx, SX_XLOCKED);
2719 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2724 error = pmclog_flush(po);
2729 * Retrieve hardware configuration.
2732 case PMC_OP_GETCPUINFO: /* CPU information */
2734 struct pmc_op_getcpuinfo gci;
2736 gci.pm_cputype = md->pmd_cputype;
2737 gci.pm_ncpu = pmc_cpu_max();
2738 gci.pm_npmc = md->pmd_npmc;
2739 gci.pm_nclass = md->pmd_nclass;
2740 bcopy(md->pmd_classes, &gci.pm_classes,
2741 sizeof(gci.pm_classes));
2742 error = copyout(&gci, arg, sizeof(gci));
2748 * Get module statistics
2751 case PMC_OP_GETDRIVERSTATS:
2753 struct pmc_op_getdriverstats gms;
2755 bcopy(&pmc_stats, &gms, sizeof(gms));
2756 error = copyout(&gms, arg, sizeof(gms));
2762 * Retrieve module version number
2765 case PMC_OP_GETMODULEVERSION:
2769 /* retrieve the client's idea of the ABI version */
2770 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
2772 /* don't service clients newer than our driver */
2774 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
2775 error = EPROGMISMATCH;
2778 error = copyout(&modv, arg, sizeof(int));
2784 * Retrieve the state of all the PMCs on a given
2788 case PMC_OP_GETPMCINFO:
2790 uint32_t cpu, n, npmc;
2791 size_t pmcinfo_size;
2793 struct pmc_info *p, *pmcinfo;
2794 struct pmc_op_getpmcinfo *gpi;
2795 struct pmc_owner *po;
2796 struct pmc_binding pb;
2800 gpi = (struct pmc_op_getpmcinfo *) arg;
2802 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
2805 if (cpu >= pmc_cpu_max()) {
2810 if (!pmc_cpu_is_active(cpu)) {
2815 /* switch to CPU 'cpu' */
2816 pmc_save_cpu_binding(&pb);
2817 pmc_select_cpu(cpu);
2819 npmc = md->pmd_npmc;
2821 pmcinfo_size = npmc * sizeof(struct pmc_info);
2822 MALLOC(pmcinfo, struct pmc_info *, pmcinfo_size, M_PMC,
2827 for (n = 0; n < md->pmd_npmc; n++, p++) {
2829 if ((error = md->pmd_describe(cpu, n, p, &pm)) != 0)
2832 if (PMC_ROW_DISP_IS_STANDALONE(n))
2833 p->pm_rowdisp = PMC_DISP_STANDALONE;
2834 else if (PMC_ROW_DISP_IS_THREAD(n))
2835 p->pm_rowdisp = PMC_DISP_THREAD;
2837 p->pm_rowdisp = PMC_DISP_FREE;
2839 p->pm_ownerpid = -1;
2841 if (pm == NULL) /* no PMC associated */
2846 KASSERT(po->po_owner != NULL,
2847 ("[pmc,%d] pmc_owner had a null proc pointer",
2850 p->pm_ownerpid = po->po_owner->p_pid;
2851 p->pm_mode = PMC_TO_MODE(pm);
2852 p->pm_event = pm->pm_event;
2853 p->pm_flags = pm->pm_flags;
2855 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2857 pm->pm_sc.pm_reloadcount;
2860 pmc_restore_cpu_binding(&pb);
2862 /* now copy out the PMC info collected */
2864 error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
2866 FREE(pmcinfo, M_PMC);
2872 * Set the administrative state of a PMC. I.e. whether
2873 * the PMC is to be used or not.
2876 case PMC_OP_PMCADMIN:
2879 enum pmc_state request;
2882 struct pmc_op_pmcadmin pma;
2883 struct pmc_binding pb;
2885 sx_assert(&pmc_sx, SX_XLOCKED);
2887 KASSERT(td == curthread,
2888 ("[pmc,%d] td != curthread", __LINE__));
2890 error = priv_check(td, PRIV_PMC_MANAGE);
2894 if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
2899 if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
2904 if (!pmc_cpu_is_active(cpu)) {
2909 request = pma.pm_state;
2911 if (request != PMC_STATE_DISABLED &&
2912 request != PMC_STATE_FREE) {
2917 ri = pma.pm_pmc; /* pmc id == row index */
2918 if (ri < 0 || ri >= (int) md->pmd_npmc) {
2924 * We can't disable a PMC with a row-index allocated
2925 * for process virtual PMCs.
2928 if (PMC_ROW_DISP_IS_THREAD(ri) &&
2929 request == PMC_STATE_DISABLED) {
2935 * otherwise, this PMC on this CPU is either free or
2936 * in system-wide mode.
2939 pmc_save_cpu_binding(&pb);
2940 pmc_select_cpu(cpu);
2943 phw = pc->pc_hwpmcs[ri];
2946 * XXX do we need some kind of 'forced' disable?
2949 if (phw->phw_pmc == NULL) {
2950 if (request == PMC_STATE_DISABLED &&
2951 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
2952 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
2953 PMC_MARK_ROW_STANDALONE(ri);
2954 } else if (request == PMC_STATE_FREE &&
2955 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
2956 phw->phw_state |= PMC_PHW_FLAG_IS_ENABLED;
2957 PMC_UNMARK_ROW_STANDALONE(ri);
2959 /* other cases are a no-op */
2963 pmc_restore_cpu_binding(&pb);
2972 case PMC_OP_PMCALLOCATE:
2980 struct pmc_op_pmcallocate pa;
2981 struct pmc_binding pb;
2983 if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
2990 if ((mode != PMC_MODE_SS && mode != PMC_MODE_SC &&
2991 mode != PMC_MODE_TS && mode != PMC_MODE_TC) ||
2992 (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
2998 * Virtual PMCs should only ask for a default CPU.
2999 * System mode PMCs need to specify a non-default CPU.
3002 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3003 (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3009 * Check that an inactive CPU is not being asked for.
3012 if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3018 * Refuse an allocation for a system-wide PMC if this
3019 * process has been jailed, or if this process lacks
3020 * super-user credentials and the sysctl tunable
3021 * 'security.bsd.unprivileged_syspmcs' is zero.
3024 if (PMC_IS_SYSTEM_MODE(mode)) {
3025 if (jailed(curthread->td_ucred)) {
3029 if (!pmc_unprivileged_syspmcs) {
3030 error = priv_check(curthread,
3041 * Look for valid values for 'pm_flags'
3044 if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3045 PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3050 /* process logging options are not allowed for system PMCs */
3051 if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3052 (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3058 * All sampling mode PMCs need to be able to interrupt the
3061 if (PMC_IS_SAMPLING_MODE(mode))
3062 caps |= PMC_CAP_INTERRUPT;
3064 /* A valid class specifier should have been passed in. */
3065 for (n = 0; n < md->pmd_nclass; n++)
3066 if (md->pmd_classes[n].pm_class == pa.pm_class)
3068 if (n == md->pmd_nclass) {
3073 /* The requested PMC capabilities should be feasible. */
3074 if ((md->pmd_classes[n].pm_caps & caps) != caps) {
3079 PMCDBG(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3080 pa.pm_ev, caps, mode, cpu);
3082 pmc = pmc_allocate_pmc_descriptor();
3083 pmc->pm_id = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3085 pmc->pm_event = pa.pm_ev;
3086 pmc->pm_state = PMC_STATE_FREE;
3087 pmc->pm_caps = caps;
3088 pmc->pm_flags = pa.pm_flags;
3090 /* switch thread to CPU 'cpu' */
3091 pmc_save_cpu_binding(&pb);
3093 #define PMC_IS_SHAREABLE_PMC(cpu, n) \
3094 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state & \
3095 PMC_PHW_FLAG_IS_SHAREABLE)
3096 #define PMC_IS_UNALLOCATED(cpu, n) \
3097 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3099 if (PMC_IS_SYSTEM_MODE(mode)) {
3100 pmc_select_cpu(cpu);
3101 for (n = 0; n < (int) md->pmd_npmc; n++)
3102 if (pmc_can_allocate_row(n, mode) == 0 &&
3103 pmc_can_allocate_rowindex(
3104 curthread->td_proc, n, cpu) == 0 &&
3105 (PMC_IS_UNALLOCATED(cpu, n) ||
3106 PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3107 md->pmd_allocate_pmc(cpu, n, pmc,
3111 /* Process virtual mode */
3112 for (n = 0; n < (int) md->pmd_npmc; n++) {
3113 if (pmc_can_allocate_row(n, mode) == 0 &&
3114 pmc_can_allocate_rowindex(
3115 curthread->td_proc, n,
3116 PMC_CPU_ANY) == 0 &&
3117 md->pmd_allocate_pmc(curthread->td_oncpu,
3123 #undef PMC_IS_UNALLOCATED
3124 #undef PMC_IS_SHAREABLE_PMC
3126 pmc_restore_cpu_binding(&pb);
3128 if (n == (int) md->pmd_npmc) {
3129 pmc_destroy_pmc_descriptor(pmc);
3136 /* Fill in the correct value in the ID field */
3137 pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3139 PMCDBG(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3140 pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3142 /* Process mode PMCs with logging enabled need log files */
3143 if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3144 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3146 /* All system mode sampling PMCs require a log file */
3147 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3148 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3151 * Configure global pmc's immediately
3154 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3156 pmc_save_cpu_binding(&pb);
3157 pmc_select_cpu(cpu);
3159 phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3161 if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3162 (error = md->pmd_config_pmc(cpu, n, pmc)) != 0) {
3163 (void) md->pmd_release_pmc(cpu, n, pmc);
3164 pmc_destroy_pmc_descriptor(pmc);
3167 pmc_restore_cpu_binding(&pb);
3172 pmc_restore_cpu_binding(&pb);
3175 pmc->pm_state = PMC_STATE_ALLOCATED;
3178 * mark row disposition
3181 if (PMC_IS_SYSTEM_MODE(mode))
3182 PMC_MARK_ROW_STANDALONE(n);
3184 PMC_MARK_ROW_THREAD(n);
3187 * Register this PMC with the current thread as its owner.
3191 pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3192 pmc_release_pmc_descriptor(pmc);
3199 * Return the allocated index.
3202 pa.pm_pmcid = pmc->pm_id;
3204 error = copyout(&pa, arg, sizeof(pa));
3210 * Attach a PMC to a process.
3213 case PMC_OP_PMCATTACH:
3217 struct pmc_op_pmcattach a;
3219 sx_assert(&pmc_sx, SX_XLOCKED);
3221 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3227 } else if (a.pm_pid == 0)
3228 a.pm_pid = td->td_proc->p_pid;
3230 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3233 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3238 /* PMCs may be (re)attached only when allocated or stopped */
3239 if (pm->pm_state == PMC_STATE_RUNNING) {
3242 } else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3243 pm->pm_state != PMC_STATE_STOPPED) {
3249 if ((p = pfind(a.pm_pid)) == NULL) {
3255 * Ignore processes that are working on exiting.
3257 if (p->p_flag & P_WEXIT) {
3259 PROC_UNLOCK(p); /* pfind() returns a locked process */
3264 * we are allowed to attach a PMC to a process if
3267 error = p_candebug(curthread, p);
3272 error = pmc_attach_process(p, pm);
3278 * Detach an attached PMC from a process.
3281 case PMC_OP_PMCDETACH:
3285 struct pmc_op_pmcattach a;
3287 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3293 } else if (a.pm_pid == 0)
3294 a.pm_pid = td->td_proc->p_pid;
3296 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3299 if ((p = pfind(a.pm_pid)) == NULL) {
3305 * Treat processes that are in the process of exiting
3306 * as if they were not present.
3309 if (p->p_flag & P_WEXIT)
3312 PROC_UNLOCK(p); /* pfind() returns a locked process */
3315 error = pmc_detach_process(p, pm);
3321 * Retrieve the MSR number associated with the counter
3322 * 'pmc_id'. This allows processes to directly use RDPMC
3323 * instructions to read their PMCs, without the overhead of a
3327 case PMC_OP_PMCGETMSR:
3331 struct pmc_target *pt;
3332 struct pmc_op_getmsr gm;
3336 /* CPU has no 'GETMSR' support */
3337 if (md->pmd_get_msr == NULL) {
3342 if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3345 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3349 * The allocated PMC has to be a process virtual PMC,
3350 * i.e., of type MODE_T[CS]. Global PMCs can only be
3351 * read using the PMCREAD operation since they may be
3352 * allocated on a different CPU than the one we could
3353 * be running on at the time of the RDPMC instruction.
3355 * The GETMSR operation is not allowed for PMCs that
3356 * are inherited across processes.
3359 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3360 (pm->pm_flags & PMC_F_DESCENDANTS)) {
3366 * It only makes sense to use a RDPMC (or its
3367 * equivalent instruction on non-x86 architectures) on
3368 * a process that has allocated and attached a PMC to
3369 * itself. Conversely the PMC is only allowed to have
3370 * one process attached to it -- its owner.
3373 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3374 LIST_NEXT(pt, pt_next) != NULL ||
3375 pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3380 ri = PMC_TO_ROWINDEX(pm);
3382 if ((error = (*md->pmd_get_msr)(ri, &gm.pm_msr)) < 0)
3385 if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3389 * Mark our process as using MSRs. Update machine
3390 * state using a forced context switch.
3393 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3394 pmc_force_context_switch();
3400 * Release an allocated PMC
3403 case PMC_OP_PMCRELEASE:
3407 struct pmc_owner *po;
3408 struct pmc_op_simple sp;
3411 * Find PMC pointer for the named PMC.
3413 * Use pmc_release_pmc_descriptor() to switch off the
3414 * PMC, remove all its target threads, and remove the
3415 * PMC from its owner's list.
3417 * Remove the owner record if this is the last PMC
3423 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3426 pmcid = sp.pm_pmcid;
3428 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3432 pmc_release_pmc_descriptor(pm);
3433 pmc_maybe_remove_owner(po);
3441 * Read and/or write a PMC.
3448 struct pmc_op_pmcrw *pprw;
3449 struct pmc_op_pmcrw prw;
3450 struct pmc_binding pb;
3451 pmc_value_t oldvalue;
3455 if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3459 PMCDBG(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3462 /* must have at least one flag set */
3463 if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3468 /* locate pmc descriptor */
3469 if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3472 /* Can't read a PMC that hasn't been started. */
3473 if (pm->pm_state != PMC_STATE_ALLOCATED &&
3474 pm->pm_state != PMC_STATE_STOPPED &&
3475 pm->pm_state != PMC_STATE_RUNNING) {
3480 /* writing a new value is allowed only for 'STOPPED' pmcs */
3481 if (pm->pm_state == PMC_STATE_RUNNING &&
3482 (prw.pm_flags & PMC_F_NEWVALUE)) {
3487 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3490 * If this PMC is attached to its owner (i.e.,
3491 * the process requesting this operation) and
3492 * is running, then attempt to get an
3493 * upto-date reading from hardware for a READ.
3494 * Writes are only allowed when the PMC is
3495 * stopped, so only update the saved value
3498 * If the PMC is not running, or is not
3499 * attached to its owner, read/write to the
3503 ri = PMC_TO_ROWINDEX(pm);
3505 mtx_pool_lock_spin(pmc_mtxpool, pm);
3506 cpu = curthread->td_oncpu;
3508 if (prw.pm_flags & PMC_F_OLDVALUE) {
3509 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3510 (pm->pm_state == PMC_STATE_RUNNING))
3511 error = (*md->pmd_read_pmc)(cpu, ri,
3514 oldvalue = pm->pm_gv.pm_savedvalue;
3516 if (prw.pm_flags & PMC_F_NEWVALUE)
3517 pm->pm_gv.pm_savedvalue = prw.pm_value;
3519 mtx_pool_unlock_spin(pmc_mtxpool, pm);
3521 } else { /* System mode PMCs */
3522 cpu = PMC_TO_CPU(pm);
3523 ri = PMC_TO_ROWINDEX(pm);
3525 if (!pmc_cpu_is_active(cpu)) {
3530 /* move this thread to CPU 'cpu' */
3531 pmc_save_cpu_binding(&pb);
3532 pmc_select_cpu(cpu);
3535 /* save old value */
3536 if (prw.pm_flags & PMC_F_OLDVALUE)
3537 if ((error = (*md->pmd_read_pmc)(cpu, ri,
3540 /* write out new value */
3541 if (prw.pm_flags & PMC_F_NEWVALUE)
3542 error = (*md->pmd_write_pmc)(cpu, ri,
3546 pmc_restore_cpu_binding(&pb);
3551 pprw = (struct pmc_op_pmcrw *) arg;
3554 if (prw.pm_flags & PMC_F_NEWVALUE)
3555 PMCDBG(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3556 ri, prw.pm_value, oldvalue);
3557 else if (prw.pm_flags & PMC_F_OLDVALUE)
3558 PMCDBG(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3561 /* return old value if requested */
3562 if (prw.pm_flags & PMC_F_OLDVALUE)
3563 if ((error = copyout(&oldvalue, &pprw->pm_value,
3564 sizeof(prw.pm_value))))
3572 * Set the sampling rate for a sampling mode PMC and the
3573 * initial count for a counting mode PMC.
3576 case PMC_OP_PMCSETCOUNT:
3579 struct pmc_op_pmcsetcount sc;
3583 if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3586 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3589 if (pm->pm_state == PMC_STATE_RUNNING) {
3594 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3595 pm->pm_sc.pm_reloadcount = sc.pm_count;
3597 pm->pm_sc.pm_initial = sc.pm_count;
3606 case PMC_OP_PMCSTART:
3610 struct pmc_op_simple sp;
3612 sx_assert(&pmc_sx, SX_XLOCKED);
3614 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3617 pmcid = sp.pm_pmcid;
3619 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3622 KASSERT(pmcid == pm->pm_id,
3623 ("[pmc,%d] pmcid %x != id %x", __LINE__,
3626 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3628 else if (pm->pm_state != PMC_STATE_STOPPED &&
3629 pm->pm_state != PMC_STATE_ALLOCATED) {
3634 error = pmc_start(pm);
3643 case PMC_OP_PMCSTOP:
3647 struct pmc_op_simple sp;
3651 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3654 pmcid = sp.pm_pmcid;
3657 * Mark the PMC as inactive and invoke the MD stop
3658 * routines if needed.
3661 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3664 KASSERT(pmcid == pm->pm_id,
3665 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3668 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3670 else if (pm->pm_state != PMC_STATE_RUNNING) {
3675 error = pmc_stop(pm);
3681 * Write a user supplied value to the log file.
3684 case PMC_OP_WRITELOG:
3686 struct pmc_op_writelog wl;
3687 struct pmc_owner *po;
3691 if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
3694 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3699 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
3704 error = pmclog_process_userlog(po, &wl);
3714 if (is_sx_downgraded)
3715 sx_sunlock(&pmc_sx);
3717 sx_xunlock(&pmc_sx);
3720 atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
3733 * Mark the thread as needing callchain capture and post an AST. The
3734 * actual callchain capture will be done in a context where it is safe
3735 * to take page faults.
3739 pmc_post_callchain_ast(void)
3746 * Mark this thread as needing processing in ast().
3747 * td->td_pflags will be safe to touch as the process was in
3748 * user space when it was interrupted.
3750 td->td_pflags |= TDP_CALLCHAIN;
3753 * Again, since we've entered this function directly from
3754 * userland, `td' is guaranteed to be not locked by this CPU,
3755 * so its safe to try acquire the thread lock even though we
3756 * are executing in an NMI context. We need to acquire this
3757 * lock before touching `td_flags' because other CPUs may be
3758 * in the process of touching this field.
3761 td->td_flags |= TDF_ASTPENDING;
3768 * Interrupt processing.
3770 * Find a free slot in the per-cpu array of samples and capture the
3771 * current callchain there. If a sample was successfully added, a bit
3772 * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
3773 * needs to be invoked from the clock handler.
3775 * This function is meant to be called from an NMI handler. It cannot
3776 * use any of the locking primitives supplied by the OS.
3780 pmc_process_interrupt(int cpu, struct pmc *pm, struct trapframe *tf,
3783 int error, callchaindepth;
3785 struct pmc_sample *ps;
3786 struct pmc_samplebuffer *psb;
3791 * Allocate space for a sample buffer.
3793 psb = pmc_pcpu[cpu]->pc_sb;
3796 if (ps->ps_nsamples) { /* in use, reader hasn't caught up */
3798 atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
3799 PMCDBG(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
3800 cpu, pm, (void *) tf, inuserspace,
3801 (int) (psb->ps_write - psb->ps_samples),
3802 (int) (psb->ps_read - psb->ps_samples));
3808 /* Fill in entry. */
3809 PMCDBG(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
3810 (void *) tf, inuserspace,
3811 (int) (psb->ps_write - psb->ps_samples),
3812 (int) (psb->ps_read - psb->ps_samples));
3814 atomic_add_rel_32(&pm->pm_runcount, 1); /* hold onto PMC */
3816 if ((td = curthread) && td->td_proc)
3817 ps->ps_pid = td->td_proc->p_pid;
3821 ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
3823 callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
3824 pmc_callchaindepth : 1;
3826 if (callchaindepth == 1)
3827 ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
3830 * Kernel stack traversals can be done immediately,
3831 * while we defer to an AST for user space traversals.
3835 pmc_save_kernel_callchain(ps->ps_pc,
3836 callchaindepth, tf);
3838 pmc_post_callchain_ast();
3839 callchaindepth = PMC_SAMPLE_INUSE;
3843 ps->ps_nsamples = callchaindepth; /* mark entry as in use */
3845 /* increment write pointer, modulo ring buffer size */
3847 if (ps == psb->ps_fence)
3848 psb->ps_write = psb->ps_samples;
3853 /* mark CPU as needing processing */
3854 atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3860 * Capture a user call chain. This function will be called from ast()
3861 * before control returns to userland and before the process gets
3866 pmc_capture_user_callchain(int cpu, struct trapframe *tf)
3870 struct pmc_sample *ps;
3871 struct pmc_samplebuffer *psb;
3873 psb = pmc_pcpu[cpu]->pc_sb;
3876 * Iterate through all deferred callchain requests.
3879 for (i = 0; i < pmc_nsamples; i++) {
3881 ps = &psb->ps_samples[i];
3882 if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
3887 KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
3888 ("[pmc,%d] Retrieving callchain for PMC that doesn't "
3889 "want it", __LINE__));
3892 * Retrieve the callchain and mark the sample buffer
3893 * as 'processable' by the timer tick sweep code.
3895 ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
3896 pmc_callchaindepth, tf);
3904 * Process saved PC samples.
3908 pmc_process_samples(int cpu)
3913 struct pmc_owner *po;
3914 struct pmc_sample *ps;
3915 struct pmc_samplebuffer *psb;
3917 KASSERT(PCPU_GET(cpuid) == cpu,
3918 ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
3919 PCPU_GET(cpuid), cpu));
3921 psb = pmc_pcpu[cpu]->pc_sb;
3923 for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
3926 if (ps->ps_nsamples == PMC_SAMPLE_FREE)
3928 if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
3929 /* Need a rescan at a later time. */
3930 atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3937 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
3938 ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
3939 pm, PMC_TO_MODE(pm)));
3941 /* Ignore PMCs that have been switched off */
3942 if (pm->pm_state != PMC_STATE_RUNNING)
3945 PMCDBG(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
3946 pm, ps->ps_nsamples, ps->ps_flags,
3947 (int) (psb->ps_write - psb->ps_samples),
3948 (int) (psb->ps_read - psb->ps_samples));
3951 * If this is a process-mode PMC that is attached to
3952 * its owner, and if the PC is in user mode, update
3953 * profiling statistics like timer-based profiling
3956 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
3957 if (ps->ps_flags & PMC_CC_F_USERSPACE) {
3958 td = FIRST_THREAD_IN_PROC(po->po_owner);
3959 addupc_intr(td, ps->ps_pc[0], 1);
3965 * Otherwise, this is either a sampling mode PMC that
3966 * is attached to a different process than its owner,
3967 * or a system-wide sampling PMC. Dispatch a log
3968 * entry to the PMC's owner process.
3971 pmclog_process_callchain(pm, ps);
3974 ps->ps_nsamples = 0; /* mark entry as free */
3975 atomic_subtract_rel_32(&pm->pm_runcount, 1);
3977 /* increment read pointer, modulo sample size */
3978 if (++ps == psb->ps_fence)
3979 psb->ps_read = psb->ps_samples;
3984 atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
3986 /* Do not re-enable stalled PMCs if we failed to process any samples */
3991 * Restart any stalled sampling PMCs on this CPU.
3993 * If the NMI handler sets the pm_stalled field of a PMC after
3994 * the check below, we'll end up processing the stalled PMC at
3995 * the next hardclock tick.
3997 for (n = 0; n < md->pmd_npmc; n++) {
3998 (void) (*md->pmd_get_config)(cpu,n,&pm);
3999 if (pm == NULL || /* !cfg'ed */
4000 pm->pm_state != PMC_STATE_RUNNING || /* !active */
4001 !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4002 pm->pm_stalled == 0) /* !stalled */
4006 ri = PMC_TO_ROWINDEX(pm);
4007 (*md->pmd_start_pmc)(cpu, ri);
4016 * Handle a process exit.
4018 * Remove this process from all hash tables. If this process
4019 * owned any PMCs, turn off those PMCs and deallocate them,
4020 * removing any associations with target processes.
4022 * This function will be called by the last 'thread' of a
4025 * XXX This eventhandler gets called early in the exit process.
4026 * Consider using a 'hook' invocation from thread_exit() or equivalent
4027 * spot. Another negative is that kse_exit doesn't seem to call
4033 pmc_process_exit(void *arg __unused, struct proc *p)
4035 int is_using_hwpmcs;
4039 struct pmc_process *pp;
4040 struct pmc_owner *po;
4041 pmc_value_t newvalue, tmp;
4044 is_using_hwpmcs = p->p_flag & P_HWPMC;
4048 * Log a sysexit event to all SS PMC owners.
4050 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4051 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4052 pmclog_process_sysexit(po, p->p_pid);
4054 if (!is_using_hwpmcs)
4058 PMCDBG(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4062 * Since this code is invoked by the last thread in an exiting
4063 * process, we would have context switched IN at some prior
4064 * point. However, with PREEMPTION, kernel mode context
4065 * switches may happen any time, so we want to disable a
4066 * context switch OUT till we get any PMCs targetting this
4067 * process off the hardware.
4069 * We also need to atomically remove this process'
4070 * entry from our target process hash table, using
4073 PMCDBG(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4076 critical_enter(); /* no preemption */
4078 cpu = curthread->td_oncpu;
4080 if ((pp = pmc_find_process_descriptor(p,
4081 PMC_FLAG_REMOVE)) != NULL) {
4084 "process-exit proc=%p pmc-process=%p", p, pp);
4087 * The exiting process could the target of
4088 * some PMCs which will be running on
4089 * currently executing CPU.
4091 * We need to turn these PMCs off like we
4092 * would do at context switch OUT time.
4094 for (ri = 0; ri < md->pmd_npmc; ri++) {
4097 * Pick up the pmc pointer from hardware
4098 * state similar to the CSW_OUT code.
4101 (void) (*md->pmd_get_config)(cpu, ri, &pm);
4103 PMCDBG(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4106 !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4109 PMCDBG(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4110 "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4113 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4114 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4115 __LINE__, PMC_TO_ROWINDEX(pm), ri));
4117 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4118 ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4119 __LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4121 (void) md->pmd_stop_pmc(cpu, ri);
4123 KASSERT(pm->pm_runcount > 0,
4124 ("[pmc,%d] bad runcount ri %d rc %d",
4125 __LINE__, ri, pm->pm_runcount));
4127 /* Stop hardware only if it is actually running */
4128 if (pm->pm_state == PMC_STATE_RUNNING &&
4129 pm->pm_stalled == 0) {
4130 md->pmd_read_pmc(cpu, ri, &newvalue);
4132 PMC_PCPU_SAVED(cpu,ri);
4134 mtx_pool_lock_spin(pmc_mtxpool, pm);
4135 pm->pm_gv.pm_savedvalue += tmp;
4136 pp->pp_pmcs[ri].pp_pmcval += tmp;
4137 mtx_pool_unlock_spin(pmc_mtxpool, pm);
4140 atomic_subtract_rel_32(&pm->pm_runcount,1);
4142 KASSERT((int) pm->pm_runcount >= 0,
4143 ("[pmc,%d] runcount is %d", __LINE__, ri));
4145 (void) md->pmd_config_pmc(cpu, ri, NULL);
4149 * Inform the MD layer of this pseudo "context switch
4152 (void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
4154 critical_exit(); /* ok to be pre-empted now */
4157 * Unlink this process from the PMCs that are
4158 * targetting it. This will send a signal to
4159 * all PMC owner's whose PMCs are orphaned.
4161 * Log PMC value at exit time if requested.
4163 for (ri = 0; ri < md->pmd_npmc; ri++)
4164 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
4165 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
4166 PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
4167 pmclog_process_procexit(pm, pp);
4168 pmc_unlink_target_process(pm, pp);
4173 critical_exit(); /* pp == NULL */
4177 * If the process owned PMCs, free them up and free up
4180 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
4181 pmc_remove_owner(po);
4182 pmc_destroy_owner_descriptor(po);
4185 sx_xunlock(&pmc_sx);
4189 * Handle a process fork.
4191 * If the parent process 'p1' is under HWPMC monitoring, then copy
4192 * over any attached PMCs that have 'do_descendants' semantics.
4196 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
4199 int is_using_hwpmcs;
4201 uint32_t do_descendants;
4203 struct pmc_owner *po;
4204 struct pmc_process *ppnew, *ppold;
4206 (void) flags; /* unused parameter */
4209 is_using_hwpmcs = p1->p_flag & P_HWPMC;
4213 * If there are system-wide sampling PMCs active, we need to
4214 * log all fork events to their owner's logs.
4217 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4218 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4219 pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4221 if (!is_using_hwpmcs)
4225 PMCDBG(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4226 p1->p_pid, p1->p_comm, newproc);
4229 * If the parent process (curthread->td_proc) is a
4230 * target of any PMCs, look for PMCs that are to be
4231 * inherited, and link these into the new process
4234 if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4235 PMC_FLAG_NONE)) == NULL)
4236 goto done; /* nothing to do */
4239 for (ri = 0; ri < md->pmd_npmc; ri++)
4240 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4241 do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4242 if (do_descendants == 0) /* nothing to do */
4245 /* allocate a descriptor for the new process */
4246 if ((ppnew = pmc_find_process_descriptor(newproc,
4247 PMC_FLAG_ALLOCATE)) == NULL)
4251 * Run through all PMCs that were targeting the old process
4252 * and which specified F_DESCENDANTS and attach them to the
4255 * Log the fork event to all owners of PMCs attached to this
4256 * process, if not already logged.
4258 for (ri = 0; ri < md->pmd_npmc; ri++)
4259 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4260 (pm->pm_flags & PMC_F_DESCENDANTS)) {
4261 pmc_link_target_process(pm, ppnew);
4263 if (po->po_sscount == 0 &&
4264 po->po_flags & PMC_PO_OWNS_LOGFILE)
4265 pmclog_process_procfork(po, p1->p_pid,
4270 * Now mark the new process as being tracked by this driver.
4273 newproc->p_flag |= P_HWPMC;
4274 PROC_UNLOCK(newproc);
4277 sx_xunlock(&pmc_sx);
4285 static const char *pmc_name_of_pmcclass[] = {
4287 #define __PMC_CLASS(N) #N ,
4292 pmc_initialize(void)
4295 unsigned int maxcpu;
4296 struct pmc_binding pb;
4297 struct pmc_sample *ps;
4298 struct pmc_samplebuffer *sb;
4304 /* parse debug flags first */
4305 if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4306 pmc_debugstr, sizeof(pmc_debugstr)))
4307 pmc_debugflags_parse(pmc_debugstr,
4308 pmc_debugstr+strlen(pmc_debugstr));
4311 PMCDBG(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4313 /* check kernel version */
4314 if (pmc_kernel_version != PMC_VERSION) {
4315 if (pmc_kernel_version == 0)
4316 printf("hwpmc: this kernel has not been compiled with "
4317 "'options HWPMC_HOOKS'.\n");
4319 printf("hwpmc: kernel version (0x%x) does not match "
4320 "module version (0x%x).\n", pmc_kernel_version,
4322 return EPROGMISMATCH;
4326 * check sysctl parameters
4329 if (pmc_hashsize <= 0) {
4330 (void) printf("hwpmc: tunable \"hashsize\"=%d must be "
4331 "greater than zero.\n", pmc_hashsize);
4332 pmc_hashsize = PMC_HASH_SIZE;
4335 if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4336 (void) printf("hwpmc: tunable \"nsamples\"=%d out of "
4337 "range.\n", pmc_nsamples);
4338 pmc_nsamples = PMC_NSAMPLES;
4341 if (pmc_callchaindepth <= 0 ||
4342 pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
4343 (void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
4344 "range.\n", pmc_callchaindepth);
4345 pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
4348 md = pmc_md_initialize();
4350 if (md == NULL || md->pmd_init == NULL)
4353 maxcpu = pmc_cpu_max();
4355 /* allocate space for the per-cpu array */
4356 MALLOC(pmc_pcpu, struct pmc_cpu **, maxcpu * sizeof(struct pmc_cpu *),
4357 M_PMC, M_WAITOK|M_ZERO);
4359 /* per-cpu 'saved values' for managing process-mode PMCs */
4360 MALLOC(pmc_pcpu_saved, pmc_value_t *,
4361 sizeof(pmc_value_t) * maxcpu * md->pmd_npmc, M_PMC, M_WAITOK);
4363 /* Perform CPU-dependent initialization. */
4364 pmc_save_cpu_binding(&pb);
4365 for (cpu = 0; cpu < maxcpu; cpu++) {
4366 if (!pmc_cpu_is_active(cpu))
4368 pmc_select_cpu(cpu);
4369 if ((error = md->pmd_init(cpu)) != 0)
4372 pmc_restore_cpu_binding(&pb);
4377 /* allocate space for the sample array */
4378 for (cpu = 0; cpu < maxcpu; cpu++) {
4379 if (!pmc_cpu_is_active(cpu))
4381 MALLOC(sb, struct pmc_samplebuffer *,
4382 sizeof(struct pmc_samplebuffer) +
4383 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4386 sb->ps_read = sb->ps_write = sb->ps_samples;
4387 sb->ps_fence = sb->ps_samples + pmc_nsamples;
4388 KASSERT(pmc_pcpu[cpu] != NULL,
4389 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4391 MALLOC(sb->ps_callchains, uintptr_t *,
4392 pmc_callchaindepth * pmc_nsamples * sizeof(uintptr_t),
4393 M_PMC, M_WAITOK|M_ZERO);
4395 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
4396 ps->ps_pc = sb->ps_callchains +
4397 (n * pmc_callchaindepth);
4399 pmc_pcpu[cpu]->pc_sb = sb;
4402 /* allocate space for the row disposition array */
4403 pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4404 M_PMC, M_WAITOK|M_ZERO);
4406 KASSERT(pmc_pmcdisp != NULL,
4407 ("[pmc,%d] pmcdisp allocation returned NULL", __LINE__));
4409 /* mark all PMCs as available */
4410 for (n = 0; n < (int) md->pmd_npmc; n++)
4411 PMC_MARK_ROW_FREE(n);
4413 /* allocate thread hash tables */
4414 pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4415 &pmc_ownerhashmask);
4417 pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4418 &pmc_processhashmask);
4419 mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4422 LIST_INIT(&pmc_ss_owners);
4425 /* allocate a pool of spin mutexes */
4426 pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4429 PMCDBG(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4430 "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4431 pmc_processhash, pmc_processhashmask);
4433 /* register process {exit,fork,exec} handlers */
4434 pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4435 pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4436 pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4437 pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4439 /* initialize logging */
4440 pmclog_initialize();
4442 /* set hook functions */
4443 pmc_intr = md->pmd_intr;
4444 pmc_hook = pmc_hook_handler;
4447 printf(PMC_MODULE_NAME ":");
4448 for (n = 0; n < (int) md->pmd_nclass; n++) {
4449 printf(" %s/%d/0x%b",
4450 pmc_name_of_pmcclass[md->pmd_classes[n].pm_class],
4451 md->pmd_nclasspmcs[n],
4452 md->pmd_classes[n].pm_caps,
4454 "\1INT\2USR\3SYS\4EDG\5THR"
4455 "\6REA\7WRI\10INV\11QUA\12PRC"
4464 /* prepare to be unloaded */
4469 unsigned int maxcpu;
4470 struct pmc_ownerhash *ph;
4471 struct pmc_owner *po, *tmp;
4472 struct pmc_binding pb;
4474 struct pmc_processhash *prh;
4477 PMCDBG(MOD,INI,0, "%s", "cleanup");
4479 /* switch off sampling */
4480 atomic_store_rel_int(&pmc_cpumask, 0);
4484 if (pmc_hook == NULL) { /* being unloaded already */
4485 sx_xunlock(&pmc_sx);
4489 pmc_hook = NULL; /* prevent new threads from entering module */
4491 /* deregister event handlers */
4492 EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4493 EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4495 /* send SIGBUS to all owner threads, free up allocations */
4497 for (ph = pmc_ownerhash;
4498 ph <= &pmc_ownerhash[pmc_ownerhashmask];
4500 LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4501 pmc_remove_owner(po);
4503 /* send SIGBUS to owner processes */
4504 PMCDBG(MOD,INI,2, "cleanup signal proc=%p "
4505 "(%d, %s)", po->po_owner,
4506 po->po_owner->p_pid,
4507 po->po_owner->p_comm);
4509 PROC_LOCK(po->po_owner);
4510 psignal(po->po_owner, SIGBUS);
4511 PROC_UNLOCK(po->po_owner);
4513 pmc_destroy_owner_descriptor(po);
4517 /* reclaim allocated data structures */
4519 mtx_pool_destroy(&pmc_mtxpool);
4521 mtx_destroy(&pmc_processhash_mtx);
4522 if (pmc_processhash) {
4524 struct pmc_process *pp;
4526 PMCDBG(MOD,INI,3, "%s", "destroy process hash");
4527 for (prh = pmc_processhash;
4528 prh <= &pmc_processhash[pmc_processhashmask];
4530 LIST_FOREACH(pp, prh, pp_next)
4531 PMCDBG(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
4534 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
4535 pmc_processhash = NULL;
4538 if (pmc_ownerhash) {
4539 PMCDBG(MOD,INI,3, "%s", "destroy owner hash");
4540 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
4541 pmc_ownerhash = NULL;
4544 KASSERT(LIST_EMPTY(&pmc_ss_owners),
4545 ("[pmc,%d] Global SS owner list not empty", __LINE__));
4546 KASSERT(pmc_ss_count == 0,
4547 ("[pmc,%d] Global SS count not empty", __LINE__));
4549 /* Free the per-cpu sample buffers. */
4550 maxcpu = pmc_cpu_max();
4551 for (cpu = 0; cpu < maxcpu; cpu++) {
4552 if (!pmc_cpu_is_active(cpu))
4554 KASSERT(pmc_pcpu[cpu]->pc_sb != NULL,
4555 ("[pmc,%d] Null cpu sample buffer cpu=%d", __LINE__,
4557 FREE(pmc_pcpu[cpu]->pc_sb->ps_callchains, M_PMC);
4558 FREE(pmc_pcpu[cpu]->pc_sb, M_PMC);
4559 pmc_pcpu[cpu]->pc_sb = NULL;
4562 /* do processor dependent cleanup */
4563 PMCDBG(MOD,INI,3, "%s", "md cleanup");
4565 pmc_save_cpu_binding(&pb);
4566 for (cpu = 0; cpu < maxcpu; cpu++) {
4567 PMCDBG(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
4568 cpu, pmc_pcpu[cpu]);
4569 if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
4571 pmc_select_cpu(cpu);
4572 if (md->pmd_cleanup)
4573 md->pmd_cleanup(cpu);
4577 pmc_restore_cpu_binding(&pb);
4580 /* deallocate per-cpu structures */
4581 FREE(pmc_pcpu, M_PMC);
4584 FREE(pmc_pcpu_saved, M_PMC);
4585 pmc_pcpu_saved = NULL;
4588 FREE(pmc_pmcdisp, M_PMC);
4594 sx_xunlock(&pmc_sx); /* we are done */
4598 * The function called at load/unload.
4602 load (struct module *module __unused, int cmd, void *arg __unused)
4610 /* initialize the subsystem */
4611 error = pmc_initialize();
4614 PMCDBG(MOD,INI,1, "syscall=%d maxcpu=%d",
4615 pmc_syscall_num, pmc_cpu_max());
4622 PMCDBG(MOD,INI,1, "%s", "unloaded");
4626 error = EINVAL; /* XXX should panic(9) */
4634 MALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");