2 * Copyright (c) 2003-2006 Joseph Koshy
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/param.h>
32 #include <sys/eventhandler.h>
34 #include <sys/kernel.h>
35 #include <sys/kthread.h>
36 #include <sys/limits.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/mutex.h>
42 #include <sys/pmckern.h>
43 #include <sys/pmclog.h>
46 #include <sys/queue.h>
47 #include <sys/resourcevar.h>
48 #include <sys/sched.h>
49 #include <sys/signalvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/sysent.h>
54 #include <sys/systm.h>
55 #include <sys/vnode.h>
57 #include <sys/linker.h> /* needs to be after <sys/malloc.h> */
59 #include <machine/atomic.h>
60 #include <machine/md_var.h>
67 PMC_FLAG_NONE = 0x00, /* do nothing */
68 PMC_FLAG_REMOVE = 0x01, /* atomically remove entry from hash */
69 PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
73 * The offset in sysent where the syscall is allocated.
76 static int pmc_syscall_num = NO_SYSCALL;
77 struct pmc_cpu **pmc_pcpu; /* per-cpu state */
78 pmc_value_t *pmc_pcpu_saved; /* saved PMC values: CSW handling */
80 #define PMC_PCPU_SAVED(C,R) pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
82 struct mtx_pool *pmc_mtxpool;
83 static int *pmc_pmcdisp; /* PMC row dispositions */
85 #define PMC_ROW_DISP_IS_FREE(R) (pmc_pmcdisp[(R)] == 0)
86 #define PMC_ROW_DISP_IS_THREAD(R) (pmc_pmcdisp[(R)] > 0)
87 #define PMC_ROW_DISP_IS_STANDALONE(R) (pmc_pmcdisp[(R)] < 0)
89 #define PMC_MARK_ROW_FREE(R) do { \
90 pmc_pmcdisp[(R)] = 0; \
93 #define PMC_MARK_ROW_STANDALONE(R) do { \
94 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
96 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
97 KASSERT(pmc_pmcdisp[(R)] >= (-mp_ncpus), ("[pmc,%d] row " \
98 "disposition error", __LINE__)); \
101 #define PMC_UNMARK_ROW_STANDALONE(R) do { \
102 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
103 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
107 #define PMC_MARK_ROW_THREAD(R) do { \
108 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
110 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
113 #define PMC_UNMARK_ROW_THREAD(R) do { \
114 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
115 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
120 /* various event handlers */
121 static eventhandler_tag pmc_exit_tag, pmc_fork_tag;
123 /* Module statistics */
124 struct pmc_op_getdriverstats pmc_stats;
126 /* Machine/processor dependent operations */
130 * Hash tables mapping owner processes and target threads to PMCs.
133 struct mtx pmc_processhash_mtx; /* spin mutex */
134 static u_long pmc_processhashmask;
135 static LIST_HEAD(pmc_processhash, pmc_process) *pmc_processhash;
138 * Hash table of PMC owner descriptors. This table is protected by
139 * the shared PMC "sx" lock.
142 static u_long pmc_ownerhashmask;
143 static LIST_HEAD(pmc_ownerhash, pmc_owner) *pmc_ownerhash;
146 * List of PMC owners with system-wide sampling PMCs.
149 static LIST_HEAD(, pmc_owner) pmc_ss_owners;
157 static int pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
158 static int pmc_debugflags_parse(char *newstr, char *fence);
161 static int load(struct module *module, int cmd, void *arg);
162 static int pmc_attach_process(struct proc *p, struct pmc *pm);
163 static struct pmc *pmc_allocate_pmc_descriptor(void);
164 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
165 static int pmc_attach_one_process(struct proc *p, struct pmc *pm);
166 static int pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
168 static int pmc_can_attach(struct pmc *pm, struct proc *p);
169 static void pmc_cleanup(void);
170 static int pmc_detach_process(struct proc *p, struct pmc *pm);
171 static int pmc_detach_one_process(struct proc *p, struct pmc *pm,
173 static void pmc_destroy_owner_descriptor(struct pmc_owner *po);
174 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
175 static int pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
176 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
178 static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
180 static void pmc_force_context_switch(void);
181 static void pmc_link_target_process(struct pmc *pm,
182 struct pmc_process *pp);
183 static void pmc_maybe_remove_owner(struct pmc_owner *po);
184 static void pmc_process_csw_in(struct thread *td);
185 static void pmc_process_csw_out(struct thread *td);
186 static void pmc_process_exit(void *arg, struct proc *p);
187 static void pmc_process_fork(void *arg, struct proc *p1,
188 struct proc *p2, int n);
189 static void pmc_process_samples(int cpu);
190 static void pmc_release_pmc_descriptor(struct pmc *pmc);
191 static void pmc_remove_owner(struct pmc_owner *po);
192 static void pmc_remove_process_descriptor(struct pmc_process *pp);
193 static void pmc_restore_cpu_binding(struct pmc_binding *pb);
194 static void pmc_save_cpu_binding(struct pmc_binding *pb);
195 static void pmc_select_cpu(int cpu);
196 static int pmc_start(struct pmc *pm);
197 static int pmc_stop(struct pmc *pm);
198 static int pmc_syscall_handler(struct thread *td, void *syscall_args);
199 static void pmc_unlink_target_process(struct pmc *pmc,
200 struct pmc_process *pp);
203 * Kernel tunables and sysctl(8) interface.
206 SYSCTL_NODE(_kern, OID_AUTO, hwpmc, CTLFLAG_RW, 0, "HWPMC parameters");
209 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
210 char pmc_debugstr[PMC_DEBUG_STRSIZE];
211 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
212 sizeof(pmc_debugstr));
213 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
214 CTLTYPE_STRING|CTLFLAG_RW|CTLFLAG_TUN,
215 0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
219 * kern.hwpmc.hashrows -- determines the number of rows in the
220 * of the hash table used to look up threads
223 static int pmc_hashsize = PMC_HASH_SIZE;
224 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "hashsize", &pmc_hashsize);
225 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_TUN|CTLFLAG_RD,
226 &pmc_hashsize, 0, "rows in hash tables");
229 * kern.hwpmc.nsamples --- number of PC samples per CPU
232 static int pmc_nsamples = PMC_NSAMPLES;
233 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nsamples", &pmc_nsamples);
234 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_TUN|CTLFLAG_RD,
235 &pmc_nsamples, 0, "number of PC samples per CPU");
238 * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
241 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
242 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "mtxpoolsize", &pmc_mtxpool_size);
243 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_TUN|CTLFLAG_RD,
244 &pmc_mtxpool_size, 0, "size of spin mutex pool");
248 * security.bsd.unprivileged_syspmcs -- allow non-root processes to
249 * allocate system-wide PMCs.
251 * Allowing unprivileged processes to allocate system PMCs is convenient
252 * if system-wide measurements need to be taken concurrently with other
253 * per-process measurements. This feature is turned off by default.
256 static int pmc_unprivileged_syspmcs = 0;
257 TUNABLE_INT("security.bsd.unprivileged_syspmcs", &pmc_unprivileged_syspmcs);
258 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RW,
259 &pmc_unprivileged_syspmcs, 0,
260 "allow unprivileged process to allocate system PMCs");
263 * Hash function. Discard the lower 2 bits of the pointer since
264 * these are always zero for our uses. The hash multiplier is
265 * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
269 #define _PMC_HM 11400714819323198486u
271 #define _PMC_HM 2654435769u
273 #error Must know the size of 'long' to compile
276 #define PMC_HASH_PTR(P,M) ((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
282 /* The `sysent' for the new syscall */
283 static struct sysent pmc_sysent = {
285 pmc_syscall_handler /* sy_call */
288 static struct syscall_module_data pmc_syscall_mod = {
296 static moduledata_t pmc_mod = {
298 syscall_module_handler,
302 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
303 MODULE_VERSION(pmc, PMC_VERSION);
306 enum pmc_dbgparse_state {
307 PMCDS_WS, /* in whitespace */
308 PMCDS_MAJOR, /* seen a major keyword */
313 pmc_debugflags_parse(char *newstr, char *fence)
316 struct pmc_debugflags *tmpflags;
317 int error, found, *newbits, tmp;
320 MALLOC(tmpflags, struct pmc_debugflags *, sizeof(*tmpflags),
321 M_PMC, M_WAITOK|M_ZERO);
326 for (; p < fence && (c = *p); p++) {
328 /* skip white space */
329 if (c == ' ' || c == '\t')
332 /* look for a keyword followed by "=" */
333 for (q = p; p < fence && (c = *p) && c != '='; p++)
343 /* lookup flag group name */
344 #define DBG_SET_FLAG_MAJ(S,F) \
345 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
346 newbits = &tmpflags->pdb_ ## F;
348 DBG_SET_FLAG_MAJ("cpu", CPU);
349 DBG_SET_FLAG_MAJ("csw", CSW);
350 DBG_SET_FLAG_MAJ("logging", LOG);
351 DBG_SET_FLAG_MAJ("module", MOD);
352 DBG_SET_FLAG_MAJ("md", MDP);
353 DBG_SET_FLAG_MAJ("owner", OWN);
354 DBG_SET_FLAG_MAJ("pmc", PMC);
355 DBG_SET_FLAG_MAJ("process", PRC);
356 DBG_SET_FLAG_MAJ("sampling", SAM);
358 if (newbits == NULL) {
363 p++; /* skip the '=' */
365 /* Now parse the individual flags */
368 for (q = p; p < fence && (c = *p); p++)
369 if (c == ' ' || c == '\t' || c == ',')
372 /* p == fence or c == ws or c == "," or c == 0 */
374 if ((kwlen = p - q) == 0) {
380 #define DBG_SET_FLAG_MIN(S,F) \
381 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
382 tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
384 /* a '*' denotes all possible flags in the group */
385 if (kwlen == 1 && *q == '*')
387 /* look for individual flag names */
388 DBG_SET_FLAG_MIN("allocaterow", ALR);
389 DBG_SET_FLAG_MIN("allocate", ALL);
390 DBG_SET_FLAG_MIN("attach", ATT);
391 DBG_SET_FLAG_MIN("bind", BND);
392 DBG_SET_FLAG_MIN("config", CFG);
393 DBG_SET_FLAG_MIN("exec", EXC);
394 DBG_SET_FLAG_MIN("exit", EXT);
395 DBG_SET_FLAG_MIN("find", FND);
396 DBG_SET_FLAG_MIN("flush", FLS);
397 DBG_SET_FLAG_MIN("fork", FRK);
398 DBG_SET_FLAG_MIN("getbuf", GTB);
399 DBG_SET_FLAG_MIN("hook", PMH);
400 DBG_SET_FLAG_MIN("init", INI);
401 DBG_SET_FLAG_MIN("intr", INT);
402 DBG_SET_FLAG_MIN("linktarget", TLK);
403 DBG_SET_FLAG_MIN("mayberemove", OMR);
404 DBG_SET_FLAG_MIN("ops", OPS);
405 DBG_SET_FLAG_MIN("read", REA);
406 DBG_SET_FLAG_MIN("register", REG);
407 DBG_SET_FLAG_MIN("release", REL);
408 DBG_SET_FLAG_MIN("remove", ORM);
409 DBG_SET_FLAG_MIN("sample", SAM);
410 DBG_SET_FLAG_MIN("scheduleio", SIO);
411 DBG_SET_FLAG_MIN("select", SEL);
412 DBG_SET_FLAG_MIN("signal", SIG);
413 DBG_SET_FLAG_MIN("swi", SWI);
414 DBG_SET_FLAG_MIN("swo", SWO);
415 DBG_SET_FLAG_MIN("start", STA);
416 DBG_SET_FLAG_MIN("stop", STO);
417 DBG_SET_FLAG_MIN("syscall", PMS);
418 DBG_SET_FLAG_MIN("unlinktarget", TUL);
419 DBG_SET_FLAG_MIN("write", WRI);
421 /* unrecognized flag name */
426 if (c == 0 || c == ' ' || c == '\t') { /* end of flag group */
435 /* save the new flag set */
436 bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
439 FREE(tmpflags, M_PMC);
444 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
446 char *fence, *newstr;
450 (void) arg1; (void) arg2; /* unused parameters */
452 n = sizeof(pmc_debugstr);
453 MALLOC(newstr, char *, n, M_PMC, M_ZERO|M_WAITOK);
454 (void) strlcpy(newstr, pmc_debugstr, n);
456 error = sysctl_handle_string(oidp, newstr, n, req);
458 /* if there is a new string, parse and copy it */
459 if (error == 0 && req->newptr != NULL) {
460 fence = newstr + (n < req->newlen ? n : req->newlen + 1);
461 if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
462 (void) strlcpy(pmc_debugstr, newstr,
463 sizeof(pmc_debugstr));
473 * Concurrency Control
475 * The driver manages the following data structures:
477 * - target process descriptors, one per target process
478 * - owner process descriptors (and attached lists), one per owner process
479 * - lookup hash tables for owner and target processes
480 * - PMC descriptors (and attached lists)
481 * - per-cpu hardware state
482 * - the 'hook' variable through which the kernel calls into
484 * - the machine hardware state (managed by the MD layer)
486 * These data structures are accessed from:
488 * - thread context-switch code
489 * - interrupt handlers (possibly on multiple cpus)
490 * - kernel threads on multiple cpus running on behalf of user
491 * processes doing system calls
492 * - this driver's private kernel threads
494 * = Locks and Locking strategy =
496 * The driver uses four locking strategies for its operation:
498 * - The global SX lock "pmc_sx" is used to protect internal
501 * Calls into the module by syscall() start with this lock being
502 * held in exclusive mode. Depending on the requested operation,
503 * the lock may be downgraded to 'shared' mode to allow more
504 * concurrent readers into the module. Calls into the module from
505 * other parts of the kernel acquire the lock in shared mode.
507 * This SX lock is held in exclusive mode for any operations that
508 * modify the linkages between the driver's internal data structures.
510 * The 'pmc_hook' function pointer is also protected by this lock.
511 * It is only examined with the sx lock held in exclusive mode. The
512 * kernel module is allowed to be unloaded only with the sx lock held
513 * in exclusive mode. In normal syscall handling, after acquiring the
514 * pmc_sx lock we first check that 'pmc_hook' is non-null before
515 * proceeding. This prevents races between the thread unloading the module
516 * and other threads seeking to use the module.
518 * - Lookups of target process structures and owner process structures
519 * cannot use the global "pmc_sx" SX lock because these lookups need
520 * to happen during context switches and in other critical sections
521 * where sleeping is not allowed. We protect these lookup tables
522 * with their own private spin-mutexes, "pmc_processhash_mtx" and
523 * "pmc_ownerhash_mtx".
525 * - Interrupt handlers work in a lock free manner. At interrupt
526 * time, handlers look at the PMC pointer (phw->phw_pmc) configured
527 * when the PMC was started. If this pointer is NULL, the interrupt
528 * is ignored after updating driver statistics. We ensure that this
529 * pointer is set (using an atomic operation if necessary) before the
530 * PMC hardware is started. Conversely, this pointer is unset atomically
531 * only after the PMC hardware is stopped.
533 * We ensure that everything needed for the operation of an
534 * interrupt handler is available without it needing to acquire any
535 * locks. We also ensure that a PMC's software state is destroyed only
536 * after the PMC is taken off hardware (on all CPUs).
538 * - Context-switch handling with process-private PMCs needs more
541 * A given process may be the target of multiple PMCs. For example,
542 * PMCATTACH and PMCDETACH may be requested by a process on one CPU
543 * while the target process is running on another. A PMC could also
544 * be getting released because its owner is exiting. We tackle
545 * these situations in the following manner:
547 * - each target process structure 'pmc_process' has an array
548 * of 'struct pmc *' pointers, one for each hardware PMC.
550 * - At context switch IN time, each "target" PMC in RUNNING state
551 * gets started on hardware and a pointer to each PMC is copied into
552 * the per-cpu phw array. The 'runcount' for the PMC is
555 * - At context switch OUT time, all process-virtual PMCs are stopped
556 * on hardware. The saved value is added to the PMCs value field
557 * only if the PMC is in a non-deleted state (the PMCs state could
558 * have changed during the current time slice).
560 * Note that since in-between a switch IN on a processor and a switch
561 * OUT, the PMC could have been released on another CPU. Therefore
562 * context switch OUT always looks at the hardware state to turn
563 * OFF PMCs and will update a PMC's saved value only if reachable
564 * from the target process record.
566 * - OP PMCRELEASE could be called on a PMC at any time (the PMC could
567 * be attached to many processes at the time of the call and could
568 * be active on multiple CPUs).
570 * We prevent further scheduling of the PMC by marking it as in
571 * state 'DELETED'. If the runcount of the PMC is non-zero then
572 * this PMC is currently running on a CPU somewhere. The thread
573 * doing the PMCRELEASE operation waits by repeatedly doing a
574 * pause() till the runcount comes to zero.
576 * The contents of a PMC descriptor (struct pmc) are protected using
577 * a spin-mutex. In order to save space, we use a mutex pool.
579 * In terms of lock types used by witness(4), we use:
580 * - Type "pmc-sx", used by the global SX lock.
581 * - Type "pmc-sleep", for sleep mutexes used by logger threads.
582 * - Type "pmc-per-proc", for protecting PMC owner descriptors.
583 * - Type "pmc-leaf", used for all other spin mutexes.
587 * save the cpu binding of the current kthread
591 pmc_save_cpu_binding(struct pmc_binding *pb)
593 PMCDBG(CPU,BND,2, "%s", "save-cpu");
594 thread_lock(curthread);
595 pb->pb_bound = sched_is_bound(curthread);
596 pb->pb_cpu = curthread->td_oncpu;
597 thread_unlock(curthread);
598 PMCDBG(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
602 * restore the cpu binding of the current thread
606 pmc_restore_cpu_binding(struct pmc_binding *pb)
608 PMCDBG(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
609 curthread->td_oncpu, pb->pb_cpu);
610 thread_lock(curthread);
612 sched_bind(curthread, pb->pb_cpu);
614 sched_unbind(curthread);
615 thread_unlock(curthread);
616 PMCDBG(CPU,BND,2, "%s", "restore-cpu done");
620 * move execution over the specified cpu and bind it there.
624 pmc_select_cpu(int cpu)
626 KASSERT(cpu >= 0 && cpu < mp_ncpus,
627 ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
629 /* never move to a disabled CPU */
630 KASSERT(pmc_cpu_is_disabled(cpu) == 0, ("[pmc,%d] selecting "
631 "disabled CPU %d", __LINE__, cpu));
633 PMCDBG(CPU,SEL,2, "select-cpu cpu=%d", cpu);
634 thread_lock(curthread);
635 sched_bind(curthread, cpu);
636 thread_unlock(curthread);
638 KASSERT(curthread->td_oncpu == cpu,
639 ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
640 cpu, curthread->td_oncpu));
642 PMCDBG(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
646 * Force a context switch.
648 * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
649 * guaranteed to force a context switch.
653 pmc_force_context_switch(void)
660 * Get the file name for an executable. This is a simple wrapper
661 * around vn_fullpath(9).
665 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
670 *fullpath = "unknown";
672 vn_fullpath(td, v, fullpath, freepath);
676 * remove an process owning PMCs
680 pmc_remove_owner(struct pmc_owner *po)
682 struct pmc *pm, *tmp;
684 sx_assert(&pmc_sx, SX_XLOCKED);
686 PMCDBG(OWN,ORM,1, "remove-owner po=%p", po);
688 /* Remove descriptor from the owner hash table */
689 LIST_REMOVE(po, po_next);
691 /* release all owned PMC descriptors */
692 LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
693 PMCDBG(OWN,ORM,2, "pmc=%p", pm);
694 KASSERT(pm->pm_owner == po,
695 ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
697 pmc_release_pmc_descriptor(pm); /* will unlink from the list */
700 KASSERT(po->po_sscount == 0,
701 ("[pmc,%d] SS count not zero", __LINE__));
702 KASSERT(LIST_EMPTY(&po->po_pmcs),
703 ("[pmc,%d] PMC list not empty", __LINE__));
705 /* de-configure the log file if present */
706 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
707 pmclog_deconfigure_log(po);
711 * remove an owner process record if all conditions are met.
715 pmc_maybe_remove_owner(struct pmc_owner *po)
718 PMCDBG(OWN,OMR,1, "maybe-remove-owner po=%p", po);
721 * Remove owner record if
722 * - this process does not own any PMCs
723 * - this process has not allocated a system-wide sampling buffer
726 if (LIST_EMPTY(&po->po_pmcs) &&
727 ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
728 pmc_remove_owner(po);
729 pmc_destroy_owner_descriptor(po);
734 * Add an association between a target process and a PMC.
738 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
741 struct pmc_target *pt;
743 sx_assert(&pmc_sx, SX_XLOCKED);
745 KASSERT(pm != NULL && pp != NULL,
746 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
747 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
748 ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
749 __LINE__, pm, pp->pp_proc->p_pid));
750 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < ((int) md->pmd_npmc - 1),
751 ("[pmc,%d] Illegal reference count %d for process record %p",
752 __LINE__, pp->pp_refcnt, (void *) pp));
754 ri = PMC_TO_ROWINDEX(pm);
756 PMCDBG(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
760 LIST_FOREACH(pt, &pm->pm_targets, pt_next)
761 if (pt->pt_process == pp)
762 KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
766 MALLOC(pt, struct pmc_target *, sizeof(struct pmc_target),
767 M_PMC, M_ZERO|M_WAITOK);
771 LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
773 atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
776 if (pm->pm_owner->po_owner == pp->pp_proc)
777 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
780 * Initialize the per-process values at this row index.
782 pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
783 pm->pm_sc.pm_reloadcount : 0;
790 * Removes the association between a target process and a PMC.
794 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
798 struct pmc_target *ptgt;
800 sx_assert(&pmc_sx, SX_XLOCKED);
802 KASSERT(pm != NULL && pp != NULL,
803 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
805 KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt < (int) md->pmd_npmc,
806 ("[pmc,%d] Illegal ref count %d on process record %p",
807 __LINE__, pp->pp_refcnt, (void *) pp));
809 ri = PMC_TO_ROWINDEX(pm);
811 PMCDBG(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
814 KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
815 ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
816 ri, pm, pp->pp_pmcs[ri].pp_pmc));
818 pp->pp_pmcs[ri].pp_pmc = NULL;
819 pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
821 /* Remove owner-specific flags */
822 if (pm->pm_owner->po_owner == pp->pp_proc) {
823 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
824 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
829 /* Remove the target process from the PMC structure */
830 LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
831 if (ptgt->pt_process == pp)
834 KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
835 "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
837 LIST_REMOVE(ptgt, pt_next);
840 /* if the PMC now lacks targets, send the owner a SIGIO */
841 if (LIST_EMPTY(&pm->pm_targets)) {
842 p = pm->pm_owner->po_owner;
847 PMCDBG(PRC,SIG,2, "signalling proc=%p signal=%d", p,
853 * Check if PMC 'pm' may be attached to target process 't'.
857 pmc_can_attach(struct pmc *pm, struct proc *t)
859 struct proc *o; /* pmc owner */
860 struct ucred *oc, *tc; /* owner, target credentials */
861 int decline_attach, i;
864 * A PMC's owner can always attach that PMC to itself.
867 if ((o = pm->pm_owner->po_owner) == t)
881 * The effective uid of the PMC owner should match at least one
882 * of the {effective,real,saved} uids of the target process.
885 decline_attach = oc->cr_uid != tc->cr_uid &&
886 oc->cr_uid != tc->cr_svuid &&
887 oc->cr_uid != tc->cr_ruid;
890 * Every one of the target's group ids, must be in the owner's
893 for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
894 decline_attach = !groupmember(tc->cr_groups[i], oc);
896 /* check the read and saved gids too */
897 if (decline_attach == 0)
898 decline_attach = !groupmember(tc->cr_rgid, oc) ||
899 !groupmember(tc->cr_svgid, oc);
904 return !decline_attach;
908 * Attach a process to a PMC.
912 pmc_attach_one_process(struct proc *p, struct pmc *pm)
915 char *fullpath, *freepath;
916 struct pmc_process *pp;
918 sx_assert(&pmc_sx, SX_XLOCKED);
920 PMCDBG(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
921 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
924 * Locate the process descriptor corresponding to process 'p',
925 * allocating space as needed.
927 * Verify that rowindex 'pm_rowindex' is free in the process
930 * If not, allocate space for a descriptor and link the
931 * process descriptor and PMC.
933 ri = PMC_TO_ROWINDEX(pm);
935 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
938 if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
941 if (pp->pp_pmcs[ri].pp_pmc != NULL)
944 pmc_link_target_process(pm, pp);
946 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
947 (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
948 pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
950 pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
952 /* issue an attach event to a configured log file */
953 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
954 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
955 pmclog_process_pmcattach(pm, p->p_pid, fullpath);
957 FREE(freepath, M_TEMP);
959 /* mark process as using HWPMCs */
961 p->p_flag |= P_HWPMC;
968 * Attach a process and optionally its children
972 pmc_attach_process(struct proc *p, struct pmc *pm)
977 sx_assert(&pmc_sx, SX_XLOCKED);
979 PMCDBG(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
980 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
984 * If this PMC successfully allowed a GETMSR operation
985 * in the past, disallow further ATTACHes.
988 if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
991 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
992 return pmc_attach_one_process(p, pm);
995 * Traverse all child processes, attaching them to
999 sx_slock(&proctree_lock);
1004 if ((error = pmc_attach_one_process(p, pm)) != 0)
1006 if (!LIST_EMPTY(&p->p_children))
1007 p = LIST_FIRST(&p->p_children);
1011 if (LIST_NEXT(p, p_sibling)) {
1012 p = LIST_NEXT(p, p_sibling);
1020 (void) pmc_detach_process(top, pm);
1023 sx_sunlock(&proctree_lock);
1028 * Detach a process from a PMC. If there are no other PMCs tracking
1029 * this process, remove the process structure from its hash table. If
1030 * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1034 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1037 struct pmc_process *pp;
1039 sx_assert(&pmc_sx, SX_XLOCKED);
1042 ("[pmc,%d] null pm pointer", __LINE__));
1044 ri = PMC_TO_ROWINDEX(pm);
1046 PMCDBG(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1047 pm, ri, p, p->p_pid, p->p_comm, flags);
1049 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1052 if (pp->pp_pmcs[ri].pp_pmc != pm)
1055 pmc_unlink_target_process(pm, pp);
1057 /* Issue a detach entry if a log file is configured */
1058 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1059 pmclog_process_pmcdetach(pm, p->p_pid);
1062 * If there are no PMCs targetting this process, we remove its
1063 * descriptor from the target hash table and unset the P_HWPMC
1064 * flag in the struct proc.
1066 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1067 ("[pmc,%d] Illegal refcnt %d for process struct %p",
1068 __LINE__, pp->pp_refcnt, pp));
1070 if (pp->pp_refcnt != 0) /* still a target of some PMC */
1073 pmc_remove_process_descriptor(pp);
1075 if (flags & PMC_FLAG_REMOVE)
1079 p->p_flag &= ~P_HWPMC;
1086 * Detach a process and optionally its descendants from a PMC.
1090 pmc_detach_process(struct proc *p, struct pmc *pm)
1094 sx_assert(&pmc_sx, SX_XLOCKED);
1096 PMCDBG(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1097 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1099 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1100 return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1103 * Traverse all children, detaching them from this PMC. We
1104 * ignore errors since we could be detaching a PMC from a
1105 * partially attached proc tree.
1108 sx_slock(&proctree_lock);
1113 (void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1115 if (!LIST_EMPTY(&p->p_children))
1116 p = LIST_FIRST(&p->p_children);
1120 if (LIST_NEXT(p, p_sibling)) {
1121 p = LIST_NEXT(p, p_sibling);
1129 sx_sunlock(&proctree_lock);
1131 if (LIST_EMPTY(&pm->pm_targets))
1132 pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1139 * Thread context switch IN
1143 pmc_process_csw_in(struct thread *td)
1151 struct pmc_process *pp;
1152 pmc_value_t newvalue;
1156 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1159 KASSERT(pp->pp_proc == td->td_proc,
1160 ("[pmc,%d] not my thread state", __LINE__));
1162 critical_enter(); /* no preemption from this point */
1164 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1166 PMCDBG(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1167 p->p_pid, p->p_comm, pp);
1169 KASSERT(cpu >= 0 && cpu < mp_ncpus,
1170 ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
1174 for (ri = 0; ri < md->pmd_npmc; ri++) {
1176 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1179 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1180 ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1181 __LINE__, PMC_TO_MODE(pm)));
1183 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1184 ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1185 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1188 * Only PMCs that are marked as 'RUNNING' need
1189 * be placed on hardware.
1192 if (pm->pm_state != PMC_STATE_RUNNING)
1195 /* increment PMC runcount */
1196 atomic_add_rel_32(&pm->pm_runcount, 1);
1198 /* configure the HWPMC we are going to use. */
1199 md->pmd_config_pmc(cpu, ri, pm);
1201 phw = pc->pc_hwpmcs[ri];
1203 KASSERT(phw != NULL,
1204 ("[pmc,%d] null hw pointer", __LINE__));
1206 KASSERT(phw->phw_pmc == pm,
1207 ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1211 * Write out saved value and start the PMC.
1213 * Sampling PMCs use a per-process value, while
1214 * counting mode PMCs use a per-pmc value that is
1215 * inherited across descendants.
1217 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1218 mtx_pool_lock_spin(pmc_mtxpool, pm);
1219 newvalue = PMC_PCPU_SAVED(cpu,ri) =
1220 pp->pp_pmcs[ri].pp_pmcval;
1221 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1223 KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1224 ("[pmc,%d] illegal mode=%d", __LINE__,
1226 mtx_pool_lock_spin(pmc_mtxpool, pm);
1227 newvalue = PMC_PCPU_SAVED(cpu, ri) =
1228 pm->pm_gv.pm_savedvalue;
1229 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1232 PMCDBG(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1234 md->pmd_write_pmc(cpu, ri, newvalue);
1235 md->pmd_start_pmc(cpu, ri);
1239 * perform any other architecture/cpu dependent thread
1240 * switch-in actions.
1243 (void) (*md->pmd_switch_in)(pc, pp);
1250 * Thread context switch OUT.
1254 pmc_process_csw_out(struct thread *td)
1262 struct pmc_process *pp;
1264 pmc_value_t newvalue;
1267 * Locate our process descriptor; this may be NULL if
1268 * this process is exiting and we have already removed
1269 * the process from the target process table.
1271 * Note that due to kernel preemption, multiple
1272 * context switches may happen while the process is
1275 * Note also that if the target process cannot be
1276 * found we still need to deconfigure any PMCs that
1277 * are currently running on hardware.
1281 pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1289 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1291 PMCDBG(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1292 p->p_pid, p->p_comm, pp);
1294 KASSERT(cpu >= 0 && cpu < mp_ncpus,
1295 ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1300 * When a PMC gets unlinked from a target PMC, it will
1301 * be removed from the target's pp_pmc[] array.
1303 * However, on a MP system, the target could have been
1304 * executing on another CPU at the time of the unlink.
1305 * So, at context switch OUT time, we need to look at
1306 * the hardware to determine if a PMC is scheduled on
1310 for (ri = 0; ri < md->pmd_npmc; ri++) {
1313 (void) (*md->pmd_get_config)(cpu, ri, &pm);
1315 if (pm == NULL) /* nothing at this row index */
1318 mode = PMC_TO_MODE(pm);
1319 if (!PMC_IS_VIRTUAL_MODE(mode))
1320 continue; /* not a process virtual PMC */
1322 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1323 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1324 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1326 /* Stop hardware if not already stopped */
1327 if (pm->pm_stalled == 0)
1328 md->pmd_stop_pmc(cpu, ri);
1330 /* reduce this PMC's runcount */
1331 atomic_subtract_rel_32(&pm->pm_runcount, 1);
1334 * If this PMC is associated with this process,
1338 if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1340 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1341 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1342 pm, ri, pp->pp_pmcs[ri].pp_pmc));
1344 KASSERT(pp->pp_refcnt > 0,
1345 ("[pmc,%d] pp refcnt = %d", __LINE__,
1348 md->pmd_read_pmc(cpu, ri, &newvalue);
1350 tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1352 PMCDBG(CSW,SWI,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
1355 if (mode == PMC_MODE_TS) {
1358 * For sampling process-virtual PMCs,
1359 * we expect the count to be
1360 * decreasing as the 'value'
1361 * programmed into the PMC is the
1362 * number of events to be seen till
1363 * the next sampling interrupt.
1366 tmp += pm->pm_sc.pm_reloadcount;
1367 mtx_pool_lock_spin(pmc_mtxpool, pm);
1368 pp->pp_pmcs[ri].pp_pmcval -= tmp;
1369 if ((int64_t) pp->pp_pmcs[ri].pp_pmcval < 0)
1370 pp->pp_pmcs[ri].pp_pmcval +=
1371 pm->pm_sc.pm_reloadcount;
1372 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1377 * For counting process-virtual PMCs,
1378 * we expect the count to be
1379 * increasing monotonically, modulo a 64
1382 KASSERT((int64_t) tmp >= 0,
1383 ("[pmc,%d] negative increment cpu=%d "
1384 "ri=%d newvalue=%jx saved=%jx "
1385 "incr=%jx", __LINE__, cpu, ri,
1386 newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1388 mtx_pool_lock_spin(pmc_mtxpool, pm);
1389 pm->pm_gv.pm_savedvalue += tmp;
1390 pp->pp_pmcs[ri].pp_pmcval += tmp;
1391 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1393 if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1394 pmclog_process_proccsw(pm, pp, tmp);
1398 /* mark hardware as free */
1399 md->pmd_config_pmc(cpu, ri, NULL);
1403 * perform any other architecture/cpu dependent thread
1404 * switch out functions.
1407 (void) (*md->pmd_switch_out)(pc, pp);
1413 * Log a KLD operation.
1417 pmc_process_kld_load(struct pmckern_map_in *pkm)
1419 struct pmc_owner *po;
1421 sx_assert(&pmc_sx, SX_LOCKED);
1424 * Notify owners of system sampling PMCs about KLD operations.
1427 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1428 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1429 pmclog_process_map_in(po, (pid_t) -1, pkm->pm_address,
1430 (char *) pkm->pm_file);
1433 * TODO: Notify owners of (all) process-sampling PMCs too.
1440 pmc_process_kld_unload(struct pmckern_map_out *pkm)
1442 struct pmc_owner *po;
1444 sx_assert(&pmc_sx, SX_LOCKED);
1446 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1447 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1448 pmclog_process_map_out(po, (pid_t) -1,
1449 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1452 * TODO: Notify owners of process-sampling PMCs.
1457 * A mapping change for a process.
1461 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1465 char *fullpath, *freepath;
1466 const struct pmc *pm;
1467 struct pmc_owner *po;
1468 const struct pmc_process *pp;
1470 freepath = fullpath = NULL;
1471 pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1473 pid = td->td_proc->p_pid;
1475 /* Inform owners of all system-wide sampling PMCs. */
1476 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1477 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1478 pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1480 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1484 * Inform sampling PMC owners tracking this process.
1486 for (ri = 0; ri < md->pmd_npmc; ri++)
1487 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1488 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1489 pmclog_process_map_in(pm->pm_owner,
1490 pid, pkm->pm_address, fullpath);
1494 FREE(freepath, M_TEMP);
1499 * Log an munmap request.
1503 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1507 struct pmc_owner *po;
1508 const struct pmc *pm;
1509 const struct pmc_process *pp;
1511 pid = td->td_proc->p_pid;
1513 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1514 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1515 pmclog_process_map_out(po, pid, pkm->pm_address,
1516 pkm->pm_address + pkm->pm_size);
1518 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1521 for (ri = 0; ri < md->pmd_npmc; ri++)
1522 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1523 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1524 pmclog_process_map_out(pm->pm_owner, pid,
1525 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1529 * The 'hook' invoked from the kernel proper
1534 const char *pmc_hooknames[] = {
1535 /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1549 pmc_hook_handler(struct thread *td, int function, void *arg)
1552 PMCDBG(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1553 pmc_hooknames[function], arg);
1562 case PMC_FN_PROCESS_EXEC:
1564 char *fullpath, *freepath;
1566 int is_using_hwpmcs;
1569 struct pmc_owner *po;
1570 struct pmc_process *pp;
1571 struct pmckern_procexec *pk;
1573 sx_assert(&pmc_sx, SX_XLOCKED);
1576 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1578 pk = (struct pmckern_procexec *) arg;
1580 /* Inform owners of SS mode PMCs of the exec event. */
1581 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1582 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1583 pmclog_process_procexec(po, PMC_ID_INVALID,
1584 p->p_pid, pk->pm_entryaddr, fullpath);
1587 is_using_hwpmcs = p->p_flag & P_HWPMC;
1590 if (!is_using_hwpmcs) {
1592 FREE(freepath, M_TEMP);
1597 * PMCs are not inherited across an exec(): remove any
1598 * PMCs that this process is the owner of.
1601 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1602 pmc_remove_owner(po);
1603 pmc_destroy_owner_descriptor(po);
1607 * If the process being exec'ed is not the target of any
1610 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1612 FREE(freepath, M_TEMP);
1617 * Log the exec event to all monitoring owners. Skip
1618 * owners who have already recieved the event because
1619 * they had system sampling PMCs active.
1621 for (ri = 0; ri < md->pmd_npmc; ri++)
1622 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1624 if (po->po_sscount == 0 &&
1625 po->po_flags & PMC_PO_OWNS_LOGFILE)
1626 pmclog_process_procexec(po, pm->pm_id,
1627 p->p_pid, pk->pm_entryaddr,
1632 FREE(freepath, M_TEMP);
1635 PMCDBG(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1636 p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1638 if (pk->pm_credentialschanged == 0) /* no change */
1642 * If the newly exec()'ed process has a different credential
1643 * than before, allow it to be the target of a PMC only if
1644 * the PMC's owner has sufficient priviledge.
1647 for (ri = 0; ri < md->pmd_npmc; ri++)
1648 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1649 if (pmc_can_attach(pm, td->td_proc) != 0)
1650 pmc_detach_one_process(td->td_proc,
1653 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1654 ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1655 pp->pp_refcnt, pp));
1658 * If this process is no longer the target of any
1659 * PMCs, we can remove the process entry and free
1663 if (pp->pp_refcnt == 0) {
1664 pmc_remove_process_descriptor(pp);
1673 pmc_process_csw_in(td);
1676 case PMC_FN_CSW_OUT:
1677 pmc_process_csw_out(td);
1681 * Process accumulated PC samples.
1683 * This function is expected to be called by hardclock() for
1684 * each CPU that has accumulated PC samples.
1686 * This function is to be executed on the CPU whose samples
1687 * are being processed.
1689 case PMC_FN_DO_SAMPLES:
1692 * Clear the cpu specific bit in the CPU mask before
1693 * do the rest of the processing. If the NMI handler
1694 * gets invoked after the "atomic_clear_int()" call
1695 * below but before "pmc_process_samples()" gets
1696 * around to processing the interrupt, then we will
1697 * come back here at the next hardclock() tick (and
1698 * may find nothing to do if "pmc_process_samples()"
1699 * had already processed the interrupt). We don't
1700 * lose the interrupt sample.
1702 atomic_clear_int(&pmc_cpumask, (1 << PCPU_GET(cpuid)));
1703 pmc_process_samples(PCPU_GET(cpuid));
1707 case PMC_FN_KLD_LOAD:
1708 sx_assert(&pmc_sx, SX_LOCKED);
1709 pmc_process_kld_load((struct pmckern_map_in *) arg);
1712 case PMC_FN_KLD_UNLOAD:
1713 sx_assert(&pmc_sx, SX_LOCKED);
1714 pmc_process_kld_unload((struct pmckern_map_out *) arg);
1718 sx_assert(&pmc_sx, SX_LOCKED);
1719 pmc_process_mmap(td, (struct pmckern_map_in *) arg);
1723 sx_assert(&pmc_sx, SX_LOCKED);
1724 pmc_process_munmap(td, (struct pmckern_map_out *) arg);
1729 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
1739 * allocate a 'struct pmc_owner' descriptor in the owner hash table.
1742 static struct pmc_owner *
1743 pmc_allocate_owner_descriptor(struct proc *p)
1746 struct pmc_owner *po;
1747 struct pmc_ownerhash *poh;
1749 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1750 poh = &pmc_ownerhash[hindex];
1752 /* allocate space for N pointers and one descriptor struct */
1753 MALLOC(po, struct pmc_owner *, sizeof(struct pmc_owner),
1754 M_PMC, M_ZERO|M_WAITOK);
1756 po->po_sscount = po->po_error = po->po_flags = 0;
1759 po->po_kthread = NULL;
1760 LIST_INIT(&po->po_pmcs);
1761 LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
1763 TAILQ_INIT(&po->po_logbuffers);
1764 mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
1766 PMCDBG(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
1767 p, p->p_pid, p->p_comm, po);
1773 pmc_destroy_owner_descriptor(struct pmc_owner *po)
1776 PMCDBG(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
1777 po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
1779 mtx_destroy(&po->po_mtx);
1784 * find the descriptor corresponding to process 'p', adding or removing it
1785 * as specified by 'mode'.
1788 static struct pmc_process *
1789 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
1792 struct pmc_process *pp, *ppnew;
1793 struct pmc_processhash *pph;
1795 hindex = PMC_HASH_PTR(p, pmc_processhashmask);
1796 pph = &pmc_processhash[hindex];
1801 * Pre-allocate memory in the FIND_ALLOCATE case since we
1802 * cannot call malloc(9) once we hold a spin lock.
1805 if (mode & PMC_FLAG_ALLOCATE) {
1806 /* allocate additional space for 'n' pmc pointers */
1807 MALLOC(ppnew, struct pmc_process *,
1808 sizeof(struct pmc_process) + md->pmd_npmc *
1809 sizeof(struct pmc_targetstate), M_PMC, M_ZERO|M_WAITOK);
1812 mtx_lock_spin(&pmc_processhash_mtx);
1813 LIST_FOREACH(pp, pph, pp_next)
1814 if (pp->pp_proc == p)
1817 if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
1818 LIST_REMOVE(pp, pp_next);
1820 if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
1823 LIST_INSERT_HEAD(pph, ppnew, pp_next);
1827 mtx_unlock_spin(&pmc_processhash_mtx);
1829 if (pp != NULL && ppnew != NULL)
1836 * remove a process descriptor from the process hash table.
1840 pmc_remove_process_descriptor(struct pmc_process *pp)
1842 KASSERT(pp->pp_refcnt == 0,
1843 ("[pmc,%d] Removing process descriptor %p with count %d",
1844 __LINE__, pp, pp->pp_refcnt));
1846 mtx_lock_spin(&pmc_processhash_mtx);
1847 LIST_REMOVE(pp, pp_next);
1848 mtx_unlock_spin(&pmc_processhash_mtx);
1853 * find an owner descriptor corresponding to proc 'p'
1856 static struct pmc_owner *
1857 pmc_find_owner_descriptor(struct proc *p)
1860 struct pmc_owner *po;
1861 struct pmc_ownerhash *poh;
1863 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1864 poh = &pmc_ownerhash[hindex];
1867 LIST_FOREACH(po, poh, po_next)
1868 if (po->po_owner == p)
1871 PMCDBG(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
1872 "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
1878 * pmc_allocate_pmc_descriptor
1880 * Allocate a pmc descriptor and initialize its
1885 pmc_allocate_pmc_descriptor(void)
1889 MALLOC(pmc, struct pmc *, sizeof(struct pmc), M_PMC, M_ZERO|M_WAITOK);
1892 pmc->pm_owner = NULL;
1893 LIST_INIT(&pmc->pm_targets);
1896 PMCDBG(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
1902 * Destroy a pmc descriptor.
1906 pmc_destroy_pmc_descriptor(struct pmc *pm)
1911 KASSERT(pm->pm_state == PMC_STATE_DELETED ||
1912 pm->pm_state == PMC_STATE_FREE,
1913 ("[pmc,%d] destroying non-deleted PMC", __LINE__));
1914 KASSERT(LIST_EMPTY(&pm->pm_targets),
1915 ("[pmc,%d] destroying pmc with targets", __LINE__));
1916 KASSERT(pm->pm_owner == NULL,
1917 ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
1918 KASSERT(pm->pm_runcount == 0,
1919 ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
1925 pmc_wait_for_pmc_idle(struct pmc *pm)
1928 volatile int maxloop;
1930 maxloop = 100 * mp_ncpus;
1934 * Loop (with a forced context switch) till the PMC's runcount
1935 * comes down to zero.
1937 while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
1940 KASSERT(maxloop > 0,
1941 ("[pmc,%d] (ri%d, rc%d) waiting too long for "
1942 "pmc to be free", __LINE__,
1943 PMC_TO_ROWINDEX(pm), pm->pm_runcount));
1945 pmc_force_context_switch();
1950 * This function does the following things:
1952 * - detaches the PMC from hardware
1953 * - unlinks all target threads that were attached to it
1954 * - removes the PMC from its owner's list
1955 * - destroy's the PMC private mutex
1957 * Once this function completes, the given pmc pointer can be safely
1958 * FREE'd by the caller.
1962 pmc_release_pmc_descriptor(struct pmc *pm)
1967 struct pmc_owner *po;
1968 struct pmc_process *pp;
1969 struct pmc_target *ptgt, *tmp;
1970 struct pmc_binding pb;
1972 sx_assert(&pmc_sx, SX_XLOCKED);
1974 KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
1976 ri = PMC_TO_ROWINDEX(pm);
1977 mode = PMC_TO_MODE(pm);
1979 PMCDBG(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
1983 * First, we take the PMC off hardware.
1986 if (PMC_IS_SYSTEM_MODE(mode)) {
1989 * A system mode PMC runs on a specific CPU. Switch
1990 * to this CPU and turn hardware off.
1992 pmc_save_cpu_binding(&pb);
1994 cpu = PMC_TO_CPU(pm);
1996 pmc_select_cpu(cpu);
1998 /* switch off non-stalled CPUs */
1999 if (pm->pm_state == PMC_STATE_RUNNING &&
2000 pm->pm_stalled == 0) {
2002 phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2004 KASSERT(phw->phw_pmc == pm,
2005 ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2006 __LINE__, ri, phw->phw_pmc, pm));
2007 PMCDBG(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2010 md->pmd_stop_pmc(cpu, ri);
2014 PMCDBG(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2017 md->pmd_config_pmc(cpu, ri, NULL);
2020 /* adjust the global and process count of SS mode PMCs */
2021 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2024 if (po->po_sscount == 0) {
2025 atomic_subtract_rel_int(&pmc_ss_count, 1);
2026 LIST_REMOVE(po, po_ssnext);
2030 pm->pm_state = PMC_STATE_DELETED;
2032 pmc_restore_cpu_binding(&pb);
2035 * We could have references to this PMC structure in
2036 * the per-cpu sample queues. Wait for the queue to
2039 pmc_wait_for_pmc_idle(pm);
2041 } else if (PMC_IS_VIRTUAL_MODE(mode)) {
2044 * A virtual PMC could be running on multiple CPUs at
2047 * By marking its state as DELETED, we ensure that
2048 * this PMC is never further scheduled on hardware.
2050 * Then we wait till all CPUs are done with this PMC.
2052 pm->pm_state = PMC_STATE_DELETED;
2055 /* Wait for the PMCs runcount to come to zero. */
2056 pmc_wait_for_pmc_idle(pm);
2059 * At this point the PMC is off all CPUs and cannot be
2060 * freshly scheduled onto a CPU. It is now safe to
2061 * unlink all targets from this PMC. If a
2062 * process-record's refcount falls to zero, we remove
2063 * it from the hash table. The module-wide SX lock
2064 * protects us from races.
2066 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2067 pp = ptgt->pt_process;
2068 pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2070 PMCDBG(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2073 * If the target process record shows that no
2074 * PMCs are attached to it, reclaim its space.
2077 if (pp->pp_refcnt == 0) {
2078 pmc_remove_process_descriptor(pp);
2083 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2088 * Release any MD resources
2091 (void) md->pmd_release_pmc(cpu, ri, pm);
2094 * Update row disposition
2097 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2098 PMC_UNMARK_ROW_STANDALONE(ri);
2100 PMC_UNMARK_ROW_THREAD(ri);
2102 /* unlink from the owner's list */
2104 LIST_REMOVE(pm, pm_next);
2105 pm->pm_owner = NULL;
2108 pmc_destroy_pmc_descriptor(pm);
2112 * Register an owner and a pmc.
2116 pmc_register_owner(struct proc *p, struct pmc *pmc)
2118 struct pmc_owner *po;
2120 sx_assert(&pmc_sx, SX_XLOCKED);
2122 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2123 if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2126 KASSERT(pmc->pm_owner == NULL,
2127 ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2130 LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2133 p->p_flag |= P_HWPMC;
2136 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2137 pmclog_process_pmcallocate(pmc);
2139 PMCDBG(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2146 * Return the current row disposition:
2148 * > 0 => PROCESS MODE
2149 * < 0 => SYSTEM MODE
2153 pmc_getrowdisp(int ri)
2155 return pmc_pmcdisp[ri];
2159 * Check if a PMC at row index 'ri' can be allocated to the current
2162 * Allocation can fail if:
2163 * - the current process is already being profiled by a PMC at index 'ri',
2164 * attached to it via OP_PMCATTACH.
2165 * - the current process has already allocated a PMC at index 'ri'
2170 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2174 struct pmc_owner *po;
2175 struct pmc_process *pp;
2177 PMCDBG(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2178 "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2181 * We shouldn't have already allocated a process-mode PMC at
2184 * We shouldn't have allocated a system-wide PMC on the same
2187 if ((po = pmc_find_owner_descriptor(p)) != NULL)
2188 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2189 if (PMC_TO_ROWINDEX(pm) == ri) {
2190 mode = PMC_TO_MODE(pm);
2191 if (PMC_IS_VIRTUAL_MODE(mode))
2193 if (PMC_IS_SYSTEM_MODE(mode) &&
2194 (int) PMC_TO_CPU(pm) == cpu)
2200 * We also shouldn't be the target of any PMC at this index
2201 * since otherwise a PMC_ATTACH to ourselves will fail.
2203 if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2204 if (pp->pp_pmcs[ri].pp_pmc)
2207 PMCDBG(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2208 p, p->p_pid, p->p_comm, ri);
2214 * Check if a given PMC at row index 'ri' can be currently used in
2219 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2223 sx_assert(&pmc_sx, SX_XLOCKED);
2225 PMCDBG(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2227 if (PMC_IS_SYSTEM_MODE(mode))
2228 disp = PMC_DISP_STANDALONE;
2230 disp = PMC_DISP_THREAD;
2233 * check disposition for PMC row 'ri':
2235 * Expected disposition Row-disposition Result
2237 * STANDALONE STANDALONE or FREE proceed
2238 * STANDALONE THREAD fail
2239 * THREAD THREAD or FREE proceed
2240 * THREAD STANDALONE fail
2243 if (!PMC_ROW_DISP_IS_FREE(ri) &&
2244 !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2245 !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2252 PMCDBG(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2259 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2263 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2267 KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2268 ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2269 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2271 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2272 if (pm->pm_id == pmcid)
2279 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2283 struct pmc_owner *po;
2285 PMCDBG(PMC,FND,1, "find-pmc id=%d", pmcid);
2287 if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2290 if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2293 PMCDBG(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2304 pmc_start(struct pmc *pm)
2308 struct pmc_owner *po;
2309 struct pmc_binding pb;
2312 ("[pmc,%d] null pm", __LINE__));
2314 mode = PMC_TO_MODE(pm);
2315 ri = PMC_TO_ROWINDEX(pm);
2318 PMCDBG(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2322 if (PMC_IS_VIRTUAL_MODE(mode)) {
2325 * If a PMCATTACH has never been done on this PMC,
2326 * attach it to its owner process.
2329 if (LIST_EMPTY(&pm->pm_targets))
2330 error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2331 pmc_attach_process(po->po_owner, pm);
2334 * Disallow PMCSTART if a logfile is required but has not
2335 * been configured yet.
2338 if (error == 0 && (pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2339 (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2343 * If the PMC is attached to its owner, then force a context
2344 * switch to ensure that the MD state gets set correctly.
2348 pm->pm_state = PMC_STATE_RUNNING;
2349 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2350 pmc_force_context_switch();
2358 * A system-wide PMC.
2361 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2362 (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2363 return EDOOFUS; /* programming error */
2366 * Add the owner to the global list if this is a system-wide
2370 if (mode == PMC_MODE_SS) {
2371 if (po->po_sscount == 0) {
2372 LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2373 atomic_add_rel_int(&pmc_ss_count, 1);
2374 PMCDBG(PMC,OPS,1, "po=%p in global list", po);
2379 /* TODO: dump system wide process mappings to the log? */
2382 * Move to the CPU associated with this
2383 * PMC, and start the hardware.
2386 pmc_save_cpu_binding(&pb);
2388 cpu = PMC_TO_CPU(pm);
2390 if (pmc_cpu_is_disabled(cpu))
2393 pmc_select_cpu(cpu);
2396 * global PMCs are configured at allocation time
2397 * so write out the initial value and start the PMC.
2400 pm->pm_state = PMC_STATE_RUNNING;
2403 if ((error = md->pmd_write_pmc(cpu, ri,
2404 PMC_IS_SAMPLING_MODE(mode) ?
2405 pm->pm_sc.pm_reloadcount :
2406 pm->pm_sc.pm_initial)) == 0)
2407 error = md->pmd_start_pmc(cpu, ri);
2410 pmc_restore_cpu_binding(&pb);
2420 pmc_stop(struct pmc *pm)
2423 struct pmc_owner *po;
2424 struct pmc_binding pb;
2426 KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2428 PMCDBG(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2429 PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2431 pm->pm_state = PMC_STATE_STOPPED;
2434 * If the PMC is a virtual mode one, changing the state to
2435 * non-RUNNING is enough to ensure that the PMC never gets
2438 * If this PMC is current running on a CPU, then it will
2439 * handled correctly at the time its target process is context
2443 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2447 * A system-mode PMC. Move to the CPU associated with
2448 * this PMC, and stop the hardware. We update the
2449 * 'initial count' so that a subsequent PMCSTART will
2450 * resume counting from the current hardware count.
2453 pmc_save_cpu_binding(&pb);
2455 cpu = PMC_TO_CPU(pm);
2457 KASSERT(cpu >= 0 && cpu < mp_ncpus,
2458 ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2460 if (pmc_cpu_is_disabled(cpu))
2463 pmc_select_cpu(cpu);
2465 ri = PMC_TO_ROWINDEX(pm);
2468 if ((error = md->pmd_stop_pmc(cpu, ri)) == 0)
2469 error = md->pmd_read_pmc(cpu, ri, &pm->pm_sc.pm_initial);
2472 pmc_restore_cpu_binding(&pb);
2476 /* remove this owner from the global list of SS PMC owners */
2477 if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2479 if (po->po_sscount == 0) {
2480 atomic_subtract_rel_int(&pmc_ss_count, 1);
2481 LIST_REMOVE(po, po_ssnext);
2482 PMCDBG(PMC,OPS,2,"po=%p removed from global list", po);
2491 static const char *pmc_op_to_name[] = {
2493 #define __PMC_OP(N, D) #N ,
2500 * The syscall interface
2503 #define PMC_GET_SX_XLOCK(...) do { \
2504 sx_xlock(&pmc_sx); \
2505 if (pmc_hook == NULL) { \
2506 sx_xunlock(&pmc_sx); \
2507 return __VA_ARGS__; \
2511 #define PMC_DOWNGRADE_SX() do { \
2512 sx_downgrade(&pmc_sx); \
2513 is_sx_downgraded = 1; \
2517 pmc_syscall_handler(struct thread *td, void *syscall_args)
2519 int error, is_sx_downgraded, op;
2520 struct pmc_syscall_args *c;
2523 PMC_GET_SX_XLOCK(ENOSYS);
2527 is_sx_downgraded = 0;
2529 c = (struct pmc_syscall_args *) syscall_args;
2534 PMCDBG(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2535 pmc_op_to_name[op], arg);
2538 atomic_add_int(&pmc_stats.pm_syscalls, 1);
2545 * Configure a log file.
2547 * XXX This OP will be reworked.
2550 case PMC_OP_CONFIGURELOG:
2554 struct pmc_owner *po;
2555 struct pmckern_map_in *km, *kmbase;
2556 struct pmc_op_configurelog cl;
2558 sx_assert(&pmc_sx, SX_XLOCKED);
2560 if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2563 /* mark this process as owning a log file */
2565 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2566 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2572 * If a valid fd was passed in, try to configure that,
2573 * otherwise if 'fd' was less than zero and there was
2574 * a log file configured, flush its buffers and
2577 if (cl.pm_logfd >= 0)
2578 error = pmclog_configure_log(po, cl.pm_logfd);
2579 else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2580 pmclog_process_closelog(po);
2581 error = pmclog_flush(po);
2583 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2584 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2585 pm->pm_state == PMC_STATE_RUNNING)
2587 error = pmclog_deconfigure_log(po);
2596 * Log the current set of kernel modules.
2598 kmbase = linker_hwpmc_list_objects();
2599 for (km = kmbase; km->pm_file != NULL; km++) {
2600 PMCDBG(LOG,REG,1,"%s %p", (char *) km->pm_file,
2601 (void *) km->pm_address);
2602 pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
2605 FREE(kmbase, M_LINKER);
2614 case PMC_OP_FLUSHLOG:
2616 struct pmc_owner *po;
2618 sx_assert(&pmc_sx, SX_XLOCKED);
2620 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2625 error = pmclog_flush(po);
2630 * Retrieve hardware configuration.
2633 case PMC_OP_GETCPUINFO: /* CPU information */
2635 struct pmc_op_getcpuinfo gci;
2637 gci.pm_cputype = md->pmd_cputype;
2638 gci.pm_ncpu = mp_ncpus;
2639 gci.pm_npmc = md->pmd_npmc;
2640 gci.pm_nclass = md->pmd_nclass;
2641 bcopy(md->pmd_classes, &gci.pm_classes,
2642 sizeof(gci.pm_classes));
2643 error = copyout(&gci, arg, sizeof(gci));
2649 * Get module statistics
2652 case PMC_OP_GETDRIVERSTATS:
2654 struct pmc_op_getdriverstats gms;
2656 bcopy(&pmc_stats, &gms, sizeof(gms));
2657 error = copyout(&gms, arg, sizeof(gms));
2663 * Retrieve module version number
2666 case PMC_OP_GETMODULEVERSION:
2670 /* retrieve the client's idea of the ABI version */
2671 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
2673 /* don't service clients newer than our driver */
2675 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
2676 error = EPROGMISMATCH;
2679 error = copyout(&modv, arg, sizeof(int));
2685 * Retrieve the state of all the PMCs on a given
2689 case PMC_OP_GETPMCINFO:
2691 uint32_t cpu, n, npmc;
2692 size_t pmcinfo_size;
2694 struct pmc_info *p, *pmcinfo;
2695 struct pmc_op_getpmcinfo *gpi;
2696 struct pmc_owner *po;
2697 struct pmc_binding pb;
2701 gpi = (struct pmc_op_getpmcinfo *) arg;
2703 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
2706 if (cpu >= (unsigned int) mp_ncpus) {
2711 if (pmc_cpu_is_disabled(cpu)) {
2716 /* switch to CPU 'cpu' */
2717 pmc_save_cpu_binding(&pb);
2718 pmc_select_cpu(cpu);
2720 npmc = md->pmd_npmc;
2722 pmcinfo_size = npmc * sizeof(struct pmc_info);
2723 MALLOC(pmcinfo, struct pmc_info *, pmcinfo_size, M_PMC,
2728 for (n = 0; n < md->pmd_npmc; n++, p++) {
2730 if ((error = md->pmd_describe(cpu, n, p, &pm)) != 0)
2733 if (PMC_ROW_DISP_IS_STANDALONE(n))
2734 p->pm_rowdisp = PMC_DISP_STANDALONE;
2735 else if (PMC_ROW_DISP_IS_THREAD(n))
2736 p->pm_rowdisp = PMC_DISP_THREAD;
2738 p->pm_rowdisp = PMC_DISP_FREE;
2740 p->pm_ownerpid = -1;
2742 if (pm == NULL) /* no PMC associated */
2747 KASSERT(po->po_owner != NULL,
2748 ("[pmc,%d] pmc_owner had a null proc pointer",
2751 p->pm_ownerpid = po->po_owner->p_pid;
2752 p->pm_mode = PMC_TO_MODE(pm);
2753 p->pm_event = pm->pm_event;
2754 p->pm_flags = pm->pm_flags;
2756 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2758 pm->pm_sc.pm_reloadcount;
2761 pmc_restore_cpu_binding(&pb);
2763 /* now copy out the PMC info collected */
2765 error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
2767 FREE(pmcinfo, M_PMC);
2773 * Set the administrative state of a PMC. I.e. whether
2774 * the PMC is to be used or not.
2777 case PMC_OP_PMCADMIN:
2780 enum pmc_state request;
2783 struct pmc_op_pmcadmin pma;
2784 struct pmc_binding pb;
2786 sx_assert(&pmc_sx, SX_XLOCKED);
2788 KASSERT(td == curthread,
2789 ("[pmc,%d] td != curthread", __LINE__));
2791 error = priv_check(td, PRIV_PMC_MANAGE);
2795 if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
2800 if (cpu < 0 || cpu >= mp_ncpus) {
2805 if (pmc_cpu_is_disabled(cpu)) {
2810 request = pma.pm_state;
2812 if (request != PMC_STATE_DISABLED &&
2813 request != PMC_STATE_FREE) {
2818 ri = pma.pm_pmc; /* pmc id == row index */
2819 if (ri < 0 || ri >= (int) md->pmd_npmc) {
2825 * We can't disable a PMC with a row-index allocated
2826 * for process virtual PMCs.
2829 if (PMC_ROW_DISP_IS_THREAD(ri) &&
2830 request == PMC_STATE_DISABLED) {
2836 * otherwise, this PMC on this CPU is either free or
2837 * in system-wide mode.
2840 pmc_save_cpu_binding(&pb);
2841 pmc_select_cpu(cpu);
2844 phw = pc->pc_hwpmcs[ri];
2847 * XXX do we need some kind of 'forced' disable?
2850 if (phw->phw_pmc == NULL) {
2851 if (request == PMC_STATE_DISABLED &&
2852 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
2853 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
2854 PMC_MARK_ROW_STANDALONE(ri);
2855 } else if (request == PMC_STATE_FREE &&
2856 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
2857 phw->phw_state |= PMC_PHW_FLAG_IS_ENABLED;
2858 PMC_UNMARK_ROW_STANDALONE(ri);
2860 /* other cases are a no-op */
2864 pmc_restore_cpu_binding(&pb);
2873 case PMC_OP_PMCALLOCATE:
2881 struct pmc_op_pmcallocate pa;
2882 struct pmc_binding pb;
2884 if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
2891 if ((mode != PMC_MODE_SS && mode != PMC_MODE_SC &&
2892 mode != PMC_MODE_TS && mode != PMC_MODE_TC) ||
2893 (cpu != (u_int) PMC_CPU_ANY && cpu >= (u_int) mp_ncpus)) {
2899 * Virtual PMCs should only ask for a default CPU.
2900 * System mode PMCs need to specify a non-default CPU.
2903 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
2904 (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
2910 * Check that a disabled CPU is not being asked for.
2913 if (PMC_IS_SYSTEM_MODE(mode) && pmc_cpu_is_disabled(cpu)) {
2919 * Refuse an allocation for a system-wide PMC if this
2920 * process has been jailed, or if this process lacks
2921 * super-user credentials and the sysctl tunable
2922 * 'security.bsd.unprivileged_syspmcs' is zero.
2925 if (PMC_IS_SYSTEM_MODE(mode)) {
2926 if (jailed(curthread->td_ucred)) {
2930 if (!pmc_unprivileged_syspmcs) {
2931 error = priv_check(curthread,
2942 * Look for valid values for 'pm_flags'
2945 if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
2946 PMC_F_LOG_PROCEXIT)) != 0) {
2951 /* process logging options are not allowed for system PMCs */
2952 if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
2953 (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
2959 * All sampling mode PMCs need to be able to interrupt the
2962 if (PMC_IS_SAMPLING_MODE(mode))
2963 caps |= PMC_CAP_INTERRUPT;
2965 /* A valid class specifier should have been passed in. */
2966 for (n = 0; n < md->pmd_nclass; n++)
2967 if (md->pmd_classes[n].pm_class == pa.pm_class)
2969 if (n == md->pmd_nclass) {
2974 /* The requested PMC capabilities should be feasible. */
2975 if ((md->pmd_classes[n].pm_caps & caps) != caps) {
2980 PMCDBG(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
2981 pa.pm_ev, caps, mode, cpu);
2983 pmc = pmc_allocate_pmc_descriptor();
2984 pmc->pm_id = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
2986 pmc->pm_event = pa.pm_ev;
2987 pmc->pm_state = PMC_STATE_FREE;
2988 pmc->pm_caps = caps;
2989 pmc->pm_flags = pa.pm_flags;
2991 /* switch thread to CPU 'cpu' */
2992 pmc_save_cpu_binding(&pb);
2994 #define PMC_IS_SHAREABLE_PMC(cpu, n) \
2995 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state & \
2996 PMC_PHW_FLAG_IS_SHAREABLE)
2997 #define PMC_IS_UNALLOCATED(cpu, n) \
2998 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3000 if (PMC_IS_SYSTEM_MODE(mode)) {
3001 pmc_select_cpu(cpu);
3002 for (n = 0; n < (int) md->pmd_npmc; n++)
3003 if (pmc_can_allocate_row(n, mode) == 0 &&
3004 pmc_can_allocate_rowindex(
3005 curthread->td_proc, n, cpu) == 0 &&
3006 (PMC_IS_UNALLOCATED(cpu, n) ||
3007 PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3008 md->pmd_allocate_pmc(cpu, n, pmc,
3012 /* Process virtual mode */
3013 for (n = 0; n < (int) md->pmd_npmc; n++) {
3014 if (pmc_can_allocate_row(n, mode) == 0 &&
3015 pmc_can_allocate_rowindex(
3016 curthread->td_proc, n,
3017 PMC_CPU_ANY) == 0 &&
3018 md->pmd_allocate_pmc(curthread->td_oncpu,
3024 #undef PMC_IS_UNALLOCATED
3025 #undef PMC_IS_SHAREABLE_PMC
3027 pmc_restore_cpu_binding(&pb);
3029 if (n == (int) md->pmd_npmc) {
3030 pmc_destroy_pmc_descriptor(pmc);
3037 /* Fill in the correct value in the ID field */
3038 pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3040 PMCDBG(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3041 pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3043 /* Process mode PMCs with logging enabled need log files */
3044 if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3045 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3047 /* All system mode sampling PMCs require a log file */
3048 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3049 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3052 * Configure global pmc's immediately
3055 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3057 pmc_save_cpu_binding(&pb);
3058 pmc_select_cpu(cpu);
3060 phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3062 if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3063 (error = md->pmd_config_pmc(cpu, n, pmc)) != 0) {
3064 (void) md->pmd_release_pmc(cpu, n, pmc);
3065 pmc_destroy_pmc_descriptor(pmc);
3068 pmc_restore_cpu_binding(&pb);
3073 pmc_restore_cpu_binding(&pb);
3076 pmc->pm_state = PMC_STATE_ALLOCATED;
3079 * mark row disposition
3082 if (PMC_IS_SYSTEM_MODE(mode))
3083 PMC_MARK_ROW_STANDALONE(n);
3085 PMC_MARK_ROW_THREAD(n);
3088 * Register this PMC with the current thread as its owner.
3092 pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3093 pmc_release_pmc_descriptor(pmc);
3100 * Return the allocated index.
3103 pa.pm_pmcid = pmc->pm_id;
3105 error = copyout(&pa, arg, sizeof(pa));
3111 * Attach a PMC to a process.
3114 case PMC_OP_PMCATTACH:
3118 struct pmc_op_pmcattach a;
3120 sx_assert(&pmc_sx, SX_XLOCKED);
3122 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3128 } else if (a.pm_pid == 0)
3129 a.pm_pid = td->td_proc->p_pid;
3131 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3134 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3139 /* PMCs may be (re)attached only when allocated or stopped */
3140 if (pm->pm_state == PMC_STATE_RUNNING) {
3143 } else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3144 pm->pm_state != PMC_STATE_STOPPED) {
3150 if ((p = pfind(a.pm_pid)) == NULL) {
3156 * Ignore processes that are working on exiting.
3158 if (p->p_flag & P_WEXIT) {
3160 PROC_UNLOCK(p); /* pfind() returns a locked process */
3165 * we are allowed to attach a PMC to a process if
3168 error = p_candebug(curthread, p);
3173 error = pmc_attach_process(p, pm);
3179 * Detach an attached PMC from a process.
3182 case PMC_OP_PMCDETACH:
3186 struct pmc_op_pmcattach a;
3188 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3194 } else if (a.pm_pid == 0)
3195 a.pm_pid = td->td_proc->p_pid;
3197 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3200 if ((p = pfind(a.pm_pid)) == NULL) {
3206 * Treat processes that are in the process of exiting
3207 * as if they were not present.
3210 if (p->p_flag & P_WEXIT)
3213 PROC_UNLOCK(p); /* pfind() returns a locked process */
3216 error = pmc_detach_process(p, pm);
3222 * Retrieve the MSR number associated with the counter
3223 * 'pmc_id'. This allows processes to directly use RDPMC
3224 * instructions to read their PMCs, without the overhead of a
3228 case PMC_OP_PMCGETMSR:
3232 struct pmc_target *pt;
3233 struct pmc_op_getmsr gm;
3237 /* CPU has no 'GETMSR' support */
3238 if (md->pmd_get_msr == NULL) {
3243 if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3246 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3250 * The allocated PMC has to be a process virtual PMC,
3251 * i.e., of type MODE_T[CS]. Global PMCs can only be
3252 * read using the PMCREAD operation since they may be
3253 * allocated on a different CPU than the one we could
3254 * be running on at the time of the RDPMC instruction.
3256 * The GETMSR operation is not allowed for PMCs that
3257 * are inherited across processes.
3260 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3261 (pm->pm_flags & PMC_F_DESCENDANTS)) {
3267 * It only makes sense to use a RDPMC (or its
3268 * equivalent instruction on non-x86 architectures) on
3269 * a process that has allocated and attached a PMC to
3270 * itself. Conversely the PMC is only allowed to have
3271 * one process attached to it -- its owner.
3274 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3275 LIST_NEXT(pt, pt_next) != NULL ||
3276 pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3281 ri = PMC_TO_ROWINDEX(pm);
3283 if ((error = (*md->pmd_get_msr)(ri, &gm.pm_msr)) < 0)
3286 if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3290 * Mark our process as using MSRs. Update machine
3291 * state using a forced context switch.
3294 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3295 pmc_force_context_switch();
3301 * Release an allocated PMC
3304 case PMC_OP_PMCRELEASE:
3308 struct pmc_owner *po;
3309 struct pmc_op_simple sp;
3312 * Find PMC pointer for the named PMC.
3314 * Use pmc_release_pmc_descriptor() to switch off the
3315 * PMC, remove all its target threads, and remove the
3316 * PMC from its owner's list.
3318 * Remove the owner record if this is the last PMC
3324 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3327 pmcid = sp.pm_pmcid;
3329 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3333 pmc_release_pmc_descriptor(pm);
3334 pmc_maybe_remove_owner(po);
3342 * Read and/or write a PMC.
3349 struct pmc_op_pmcrw *pprw;
3350 struct pmc_op_pmcrw prw;
3351 struct pmc_binding pb;
3352 pmc_value_t oldvalue;
3356 if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3360 PMCDBG(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3363 /* must have at least one flag set */
3364 if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3369 /* locate pmc descriptor */
3370 if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3373 /* Can't read a PMC that hasn't been started. */
3374 if (pm->pm_state != PMC_STATE_ALLOCATED &&
3375 pm->pm_state != PMC_STATE_STOPPED &&
3376 pm->pm_state != PMC_STATE_RUNNING) {
3381 /* writing a new value is allowed only for 'STOPPED' pmcs */
3382 if (pm->pm_state == PMC_STATE_RUNNING &&
3383 (prw.pm_flags & PMC_F_NEWVALUE)) {
3388 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3391 * If this PMC is attached to its owner (i.e.,
3392 * the process requesting this operation) and
3393 * is running, then attempt to get an
3394 * upto-date reading from hardware for a READ.
3395 * Writes are only allowed when the PMC is
3396 * stopped, so only update the saved value
3399 * If the PMC is not running, or is not
3400 * attached to its owner, read/write to the
3404 ri = PMC_TO_ROWINDEX(pm);
3406 mtx_pool_lock_spin(pmc_mtxpool, pm);
3407 cpu = curthread->td_oncpu;
3409 if (prw.pm_flags & PMC_F_OLDVALUE) {
3410 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3411 (pm->pm_state == PMC_STATE_RUNNING))
3412 error = (*md->pmd_read_pmc)(cpu, ri,
3415 oldvalue = pm->pm_gv.pm_savedvalue;
3417 if (prw.pm_flags & PMC_F_NEWVALUE)
3418 pm->pm_gv.pm_savedvalue = prw.pm_value;
3420 mtx_pool_unlock_spin(pmc_mtxpool, pm);
3422 } else { /* System mode PMCs */
3423 cpu = PMC_TO_CPU(pm);
3424 ri = PMC_TO_ROWINDEX(pm);
3426 if (pmc_cpu_is_disabled(cpu)) {
3431 /* move this thread to CPU 'cpu' */
3432 pmc_save_cpu_binding(&pb);
3433 pmc_select_cpu(cpu);
3436 /* save old value */
3437 if (prw.pm_flags & PMC_F_OLDVALUE)
3438 if ((error = (*md->pmd_read_pmc)(cpu, ri,
3441 /* write out new value */
3442 if (prw.pm_flags & PMC_F_NEWVALUE)
3443 error = (*md->pmd_write_pmc)(cpu, ri,
3447 pmc_restore_cpu_binding(&pb);
3452 pprw = (struct pmc_op_pmcrw *) arg;
3455 if (prw.pm_flags & PMC_F_NEWVALUE)
3456 PMCDBG(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3457 ri, prw.pm_value, oldvalue);
3458 else if (prw.pm_flags & PMC_F_OLDVALUE)
3459 PMCDBG(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3462 /* return old value if requested */
3463 if (prw.pm_flags & PMC_F_OLDVALUE)
3464 if ((error = copyout(&oldvalue, &pprw->pm_value,
3465 sizeof(prw.pm_value))))
3473 * Set the sampling rate for a sampling mode PMC and the
3474 * initial count for a counting mode PMC.
3477 case PMC_OP_PMCSETCOUNT:
3480 struct pmc_op_pmcsetcount sc;
3484 if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3487 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3490 if (pm->pm_state == PMC_STATE_RUNNING) {
3495 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3496 pm->pm_sc.pm_reloadcount = sc.pm_count;
3498 pm->pm_sc.pm_initial = sc.pm_count;
3507 case PMC_OP_PMCSTART:
3511 struct pmc_op_simple sp;
3513 sx_assert(&pmc_sx, SX_XLOCKED);
3515 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3518 pmcid = sp.pm_pmcid;
3520 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3523 KASSERT(pmcid == pm->pm_id,
3524 ("[pmc,%d] pmcid %x != id %x", __LINE__,
3527 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3529 else if (pm->pm_state != PMC_STATE_STOPPED &&
3530 pm->pm_state != PMC_STATE_ALLOCATED) {
3535 error = pmc_start(pm);
3544 case PMC_OP_PMCSTOP:
3548 struct pmc_op_simple sp;
3552 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3555 pmcid = sp.pm_pmcid;
3558 * Mark the PMC as inactive and invoke the MD stop
3559 * routines if needed.
3562 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3565 KASSERT(pmcid == pm->pm_id,
3566 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3569 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3571 else if (pm->pm_state != PMC_STATE_RUNNING) {
3576 error = pmc_stop(pm);
3582 * Write a user supplied value to the log file.
3585 case PMC_OP_WRITELOG:
3587 struct pmc_op_writelog wl;
3588 struct pmc_owner *po;
3592 if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
3595 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3600 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
3605 error = pmclog_process_userlog(po, &wl);
3615 if (is_sx_downgraded)
3616 sx_sunlock(&pmc_sx);
3618 sx_xunlock(&pmc_sx);
3621 atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
3634 * Interrupt processing.
3636 * Find a free slot in the per-cpu array of PC samples and write the
3637 * current (PMC,PID,PC) triple to it. If an event was successfully
3638 * added, a bit is set in mask 'pmc_cpumask' denoting that the
3639 * DO_SAMPLES hook needs to be invoked from the clock handler.
3641 * This function is meant to be called from an NMI handler. It cannot
3642 * use any of the locking primitives supplied by the OS.
3646 pmc_process_interrupt(int cpu, struct pmc *pm, uintfptr_t pc, int usermode)
3650 struct pmc_sample *ps;
3651 struct pmc_samplebuffer *psb;
3654 ri = PMC_TO_ROWINDEX(pm);
3656 psb = pmc_pcpu[cpu]->pc_sb;
3659 if (ps->ps_pc) { /* in use, reader hasn't caught up */
3661 atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
3662 PMCDBG(SAM,INT,1,"(spc) cpu=%d pm=%p pc=%jx um=%d wr=%d rd=%d",
3663 cpu, pm, (uint64_t) pc, usermode,
3664 (int) (psb->ps_write - psb->ps_samples),
3665 (int) (psb->ps_read - psb->ps_samples));
3671 PMCDBG(SAM,INT,1,"cpu=%d pm=%p pc=%jx um=%d wr=%d rd=%d", cpu, pm,
3672 (uint64_t) pc, usermode,
3673 (int) (psb->ps_write - psb->ps_samples),
3674 (int) (psb->ps_read - psb->ps_samples));
3676 atomic_add_rel_32(&pm->pm_runcount, 1); /* hold onto PMC */
3678 if ((td = curthread) && td->td_proc)
3679 ps->ps_pid = td->td_proc->p_pid;
3682 ps->ps_usermode = usermode;
3683 ps->ps_pc = pc; /* mark entry as in use */
3685 /* increment write pointer, modulo ring buffer size */
3687 if (ps == psb->ps_fence)
3688 psb->ps_write = psb->ps_samples;
3693 /* mark CPU as needing processing */
3694 atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3701 * Process saved PC samples.
3705 pmc_process_samples(int cpu)
3710 struct pmc_owner *po;
3711 struct pmc_sample *ps;
3712 struct pmc_samplebuffer *psb;
3714 KASSERT(PCPU_GET(cpuid) == cpu,
3715 ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
3716 PCPU_GET(cpuid), cpu));
3718 psb = pmc_pcpu[cpu]->pc_sb;
3720 for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
3723 if (ps->ps_pc == (uintfptr_t) 0) /* no data */
3729 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
3730 ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
3731 pm, PMC_TO_MODE(pm)));
3733 /* Ignore PMCs that have been switched off */
3734 if (pm->pm_state != PMC_STATE_RUNNING)
3737 PMCDBG(SAM,OPS,1,"cpu=%d pm=%p pc=%jx um=%d wr=%d rd=%d", cpu,
3738 pm, (uint64_t) ps->ps_pc, ps->ps_usermode,
3739 (int) (psb->ps_write - psb->ps_samples),
3740 (int) (psb->ps_read - psb->ps_samples));
3743 * If this is a process-mode PMC that is attached to
3744 * its owner, and if the PC is in user mode, update
3745 * profiling statistics like timer-based profiling
3748 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
3749 if (ps->ps_usermode) {
3750 td = FIRST_THREAD_IN_PROC(po->po_owner);
3751 addupc_intr(td, ps->ps_pc, 1);
3757 * Otherwise, this is either a sampling mode PMC that
3758 * is attached to a different process than its owner,
3759 * or a system-wide sampling PMC. Dispatch a log
3760 * entry to the PMC's owner process.
3763 pmclog_process_pcsample(pm, ps);
3766 ps->ps_pc = (uintfptr_t) 0; /* mark entry as free */
3767 atomic_subtract_rel_32(&pm->pm_runcount, 1);
3769 /* increment read pointer, modulo sample size */
3770 if (++ps == psb->ps_fence)
3771 psb->ps_read = psb->ps_samples;
3776 atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
3778 /* Do not re-enable stalled PMCs if we failed to process any samples */
3783 * Restart any stalled sampling PMCs on this CPU.
3785 * If the NMI handler sets the pm_stalled field of a PMC after
3786 * the check below, we'll end up processing the stalled PMC at
3787 * the next hardclock tick.
3789 for (n = 0; n < md->pmd_npmc; n++) {
3790 (void) (*md->pmd_get_config)(cpu,n,&pm);
3791 if (pm == NULL || /* !cfg'ed */
3792 pm->pm_state != PMC_STATE_RUNNING || /* !active */
3793 !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
3794 pm->pm_stalled == 0) /* !stalled */
3798 ri = PMC_TO_ROWINDEX(pm);
3799 (*md->pmd_start_pmc)(cpu, ri);
3808 * Handle a process exit.
3810 * Remove this process from all hash tables. If this process
3811 * owned any PMCs, turn off those PMCs and deallocate them,
3812 * removing any associations with target processes.
3814 * This function will be called by the last 'thread' of a
3817 * XXX This eventhandler gets called early in the exit process.
3818 * Consider using a 'hook' invocation from thread_exit() or equivalent
3819 * spot. Another negative is that kse_exit doesn't seem to call
3825 pmc_process_exit(void *arg __unused, struct proc *p)
3827 int is_using_hwpmcs;
3831 struct pmc_process *pp;
3832 struct pmc_owner *po;
3833 pmc_value_t newvalue, tmp;
3836 is_using_hwpmcs = p->p_flag & P_HWPMC;
3840 * Log a sysexit event to all SS PMC owners.
3842 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
3843 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
3844 pmclog_process_sysexit(po, p->p_pid);
3846 if (!is_using_hwpmcs)
3850 PMCDBG(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
3854 * Since this code is invoked by the last thread in an exiting
3855 * process, we would have context switched IN at some prior
3856 * point. However, with PREEMPTION, kernel mode context
3857 * switches may happen any time, so we want to disable a
3858 * context switch OUT till we get any PMCs targetting this
3859 * process off the hardware.
3861 * We also need to atomically remove this process'
3862 * entry from our target process hash table, using
3865 PMCDBG(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
3868 critical_enter(); /* no preemption */
3870 cpu = curthread->td_oncpu;
3872 if ((pp = pmc_find_process_descriptor(p,
3873 PMC_FLAG_REMOVE)) != NULL) {
3876 "process-exit proc=%p pmc-process=%p", p, pp);
3879 * The exiting process could the target of
3880 * some PMCs which will be running on
3881 * currently executing CPU.
3883 * We need to turn these PMCs off like we
3884 * would do at context switch OUT time.
3886 for (ri = 0; ri < md->pmd_npmc; ri++) {
3889 * Pick up the pmc pointer from hardware
3890 * state similar to the CSW_OUT code.
3893 (void) (*md->pmd_get_config)(cpu, ri, &pm);
3895 PMCDBG(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
3898 !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
3901 PMCDBG(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
3902 "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
3905 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
3906 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
3907 __LINE__, PMC_TO_ROWINDEX(pm), ri));
3909 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
3910 ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
3911 __LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
3913 (void) md->pmd_stop_pmc(cpu, ri);
3915 KASSERT(pm->pm_runcount > 0,
3916 ("[pmc,%d] bad runcount ri %d rc %d",
3917 __LINE__, ri, pm->pm_runcount));
3919 /* Stop hardware only if it is actually running */
3920 if (pm->pm_state == PMC_STATE_RUNNING &&
3921 pm->pm_stalled == 0) {
3922 md->pmd_read_pmc(cpu, ri, &newvalue);
3924 PMC_PCPU_SAVED(cpu,ri);
3926 mtx_pool_lock_spin(pmc_mtxpool, pm);
3927 pm->pm_gv.pm_savedvalue += tmp;
3928 pp->pp_pmcs[ri].pp_pmcval += tmp;
3929 mtx_pool_unlock_spin(pmc_mtxpool, pm);
3932 atomic_subtract_rel_32(&pm->pm_runcount,1);
3934 KASSERT((int) pm->pm_runcount >= 0,
3935 ("[pmc,%d] runcount is %d", __LINE__, ri));
3937 (void) md->pmd_config_pmc(cpu, ri, NULL);
3941 * Inform the MD layer of this pseudo "context switch
3944 (void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
3946 critical_exit(); /* ok to be pre-empted now */
3949 * Unlink this process from the PMCs that are
3950 * targetting it. This will send a signal to
3951 * all PMC owner's whose PMCs are orphaned.
3953 * Log PMC value at exit time if requested.
3955 for (ri = 0; ri < md->pmd_npmc; ri++)
3956 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
3957 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
3958 PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
3959 pmclog_process_procexit(pm, pp);
3960 pmc_unlink_target_process(pm, pp);
3965 critical_exit(); /* pp == NULL */
3969 * If the process owned PMCs, free them up and free up
3972 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
3973 pmc_remove_owner(po);
3974 pmc_destroy_owner_descriptor(po);
3977 sx_xunlock(&pmc_sx);
3981 * Handle a process fork.
3983 * If the parent process 'p1' is under HWPMC monitoring, then copy
3984 * over any attached PMCs that have 'do_descendants' semantics.
3988 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
3991 int is_using_hwpmcs;
3993 uint32_t do_descendants;
3995 struct pmc_owner *po;
3996 struct pmc_process *ppnew, *ppold;
3998 (void) flags; /* unused parameter */
4001 is_using_hwpmcs = p1->p_flag & P_HWPMC;
4005 * If there are system-wide sampling PMCs active, we need to
4006 * log all fork events to their owner's logs.
4009 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4010 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4011 pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4013 if (!is_using_hwpmcs)
4017 PMCDBG(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4018 p1->p_pid, p1->p_comm, newproc);
4021 * If the parent process (curthread->td_proc) is a
4022 * target of any PMCs, look for PMCs that are to be
4023 * inherited, and link these into the new process
4026 if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4027 PMC_FLAG_NONE)) == NULL)
4028 goto done; /* nothing to do */
4031 for (ri = 0; ri < md->pmd_npmc; ri++)
4032 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4033 do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4034 if (do_descendants == 0) /* nothing to do */
4037 /* allocate a descriptor for the new process */
4038 if ((ppnew = pmc_find_process_descriptor(newproc,
4039 PMC_FLAG_ALLOCATE)) == NULL)
4043 * Run through all PMCs that were targeting the old process
4044 * and which specified F_DESCENDANTS and attach them to the
4047 * Log the fork event to all owners of PMCs attached to this
4048 * process, if not already logged.
4050 for (ri = 0; ri < md->pmd_npmc; ri++)
4051 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4052 (pm->pm_flags & PMC_F_DESCENDANTS)) {
4053 pmc_link_target_process(pm, ppnew);
4055 if (po->po_sscount == 0 &&
4056 po->po_flags & PMC_PO_OWNS_LOGFILE)
4057 pmclog_process_procfork(po, p1->p_pid,
4062 * Now mark the new process as being tracked by this driver.
4065 newproc->p_flag |= P_HWPMC;
4066 PROC_UNLOCK(newproc);
4069 sx_xunlock(&pmc_sx);
4077 static const char *pmc_name_of_pmcclass[] = {
4079 #define __PMC_CLASS(N) #N ,
4084 pmc_initialize(void)
4087 struct pmc_binding pb;
4088 struct pmc_samplebuffer *sb;
4094 /* parse debug flags first */
4095 if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4096 pmc_debugstr, sizeof(pmc_debugstr)))
4097 pmc_debugflags_parse(pmc_debugstr,
4098 pmc_debugstr+strlen(pmc_debugstr));
4101 PMCDBG(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4103 /* check kernel version */
4104 if (pmc_kernel_version != PMC_VERSION) {
4105 if (pmc_kernel_version == 0)
4106 printf("hwpmc: this kernel has not been compiled with "
4107 "'options HWPMC_HOOKS'.\n");
4109 printf("hwpmc: kernel version (0x%x) does not match "
4110 "module version (0x%x).\n", pmc_kernel_version,
4112 return EPROGMISMATCH;
4116 * check sysctl parameters
4119 if (pmc_hashsize <= 0) {
4120 (void) printf("hwpmc: tunable hashsize=%d must be greater "
4121 "than zero.\n", pmc_hashsize);
4122 pmc_hashsize = PMC_HASH_SIZE;
4125 if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4126 (void) printf("hwpmc: tunable nsamples=%d out of range.\n",
4128 pmc_nsamples = PMC_NSAMPLES;
4131 md = pmc_md_initialize();
4133 if (md == NULL || md->pmd_init == NULL)
4136 /* allocate space for the per-cpu array */
4137 MALLOC(pmc_pcpu, struct pmc_cpu **, mp_ncpus * sizeof(struct pmc_cpu *),
4138 M_PMC, M_WAITOK|M_ZERO);
4140 /* per-cpu 'saved values' for managing process-mode PMCs */
4141 MALLOC(pmc_pcpu_saved, pmc_value_t *,
4142 sizeof(pmc_value_t) * mp_ncpus * md->pmd_npmc, M_PMC, M_WAITOK);
4144 /* perform cpu dependent initialization */
4145 pmc_save_cpu_binding(&pb);
4146 for (cpu = 0; cpu < mp_ncpus; cpu++) {
4147 if (pmc_cpu_is_disabled(cpu))
4149 pmc_select_cpu(cpu);
4150 if ((error = md->pmd_init(cpu)) != 0)
4153 pmc_restore_cpu_binding(&pb);
4158 /* allocate space for the sample array */
4159 for (cpu = 0; cpu < mp_ncpus; cpu++) {
4160 if (pmc_cpu_is_disabled(cpu))
4162 MALLOC(sb, struct pmc_samplebuffer *,
4163 sizeof(struct pmc_samplebuffer) +
4164 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4167 sb->ps_read = sb->ps_write = sb->ps_samples;
4168 sb->ps_fence = sb->ps_samples + pmc_nsamples;
4169 KASSERT(pmc_pcpu[cpu] != NULL,
4170 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4172 pmc_pcpu[cpu]->pc_sb = sb;
4175 /* allocate space for the row disposition array */
4176 pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4177 M_PMC, M_WAITOK|M_ZERO);
4179 KASSERT(pmc_pmcdisp != NULL,
4180 ("[pmc,%d] pmcdisp allocation returned NULL", __LINE__));
4182 /* mark all PMCs as available */
4183 for (n = 0; n < (int) md->pmd_npmc; n++)
4184 PMC_MARK_ROW_FREE(n);
4186 /* allocate thread hash tables */
4187 pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4188 &pmc_ownerhashmask);
4190 pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4191 &pmc_processhashmask);
4192 mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4195 LIST_INIT(&pmc_ss_owners);
4198 /* allocate a pool of spin mutexes */
4199 pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4202 PMCDBG(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4203 "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4204 pmc_processhash, pmc_processhashmask);
4206 /* register process {exit,fork,exec} handlers */
4207 pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4208 pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4209 pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4210 pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4212 /* initialize logging */
4213 pmclog_initialize();
4215 /* set hook functions */
4216 pmc_intr = md->pmd_intr;
4217 pmc_hook = pmc_hook_handler;
4220 printf(PMC_MODULE_NAME ":");
4221 for (n = 0; n < (int) md->pmd_nclass; n++) {
4222 printf(" %s/%d/0x%b",
4223 pmc_name_of_pmcclass[md->pmd_classes[n].pm_class],
4224 md->pmd_nclasspmcs[n],
4225 md->pmd_classes[n].pm_caps,
4227 "\1INT\2USR\3SYS\4EDG\5THR"
4228 "\6REA\7WRI\10INV\11QUA\12PRC"
4237 /* prepare to be unloaded */
4242 struct pmc_ownerhash *ph;
4243 struct pmc_owner *po, *tmp;
4244 struct pmc_binding pb;
4246 struct pmc_processhash *prh;
4249 PMCDBG(MOD,INI,0, "%s", "cleanup");
4251 /* switch off sampling */
4252 atomic_store_rel_int(&pmc_cpumask, 0);
4256 if (pmc_hook == NULL) { /* being unloaded already */
4257 sx_xunlock(&pmc_sx);
4261 pmc_hook = NULL; /* prevent new threads from entering module */
4263 /* deregister event handlers */
4264 EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4265 EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4267 /* send SIGBUS to all owner threads, free up allocations */
4269 for (ph = pmc_ownerhash;
4270 ph <= &pmc_ownerhash[pmc_ownerhashmask];
4272 LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4273 pmc_remove_owner(po);
4275 /* send SIGBUS to owner processes */
4276 PMCDBG(MOD,INI,2, "cleanup signal proc=%p "
4277 "(%d, %s)", po->po_owner,
4278 po->po_owner->p_pid,
4279 po->po_owner->p_comm);
4281 PROC_LOCK(po->po_owner);
4282 psignal(po->po_owner, SIGBUS);
4283 PROC_UNLOCK(po->po_owner);
4285 pmc_destroy_owner_descriptor(po);
4289 /* reclaim allocated data structures */
4291 mtx_pool_destroy(&pmc_mtxpool);
4293 mtx_destroy(&pmc_processhash_mtx);
4294 if (pmc_processhash) {
4296 struct pmc_process *pp;
4298 PMCDBG(MOD,INI,3, "%s", "destroy process hash");
4299 for (prh = pmc_processhash;
4300 prh <= &pmc_processhash[pmc_processhashmask];
4302 LIST_FOREACH(pp, prh, pp_next)
4303 PMCDBG(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
4306 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
4307 pmc_processhash = NULL;
4310 if (pmc_ownerhash) {
4311 PMCDBG(MOD,INI,3, "%s", "destroy owner hash");
4312 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
4313 pmc_ownerhash = NULL;
4316 KASSERT(LIST_EMPTY(&pmc_ss_owners),
4317 ("[pmc,%d] Global SS owner list not empty", __LINE__));
4318 KASSERT(pmc_ss_count == 0,
4319 ("[pmc,%d] Global SS count not empty", __LINE__));
4321 /* free the per-cpu sample buffers */
4322 for (cpu = 0; cpu < mp_ncpus; cpu++) {
4323 if (pmc_cpu_is_disabled(cpu))
4325 KASSERT(pmc_pcpu[cpu]->pc_sb != NULL,
4326 ("[pmc,%d] Null cpu sample buffer cpu=%d", __LINE__,
4328 FREE(pmc_pcpu[cpu]->pc_sb, M_PMC);
4329 pmc_pcpu[cpu]->pc_sb = NULL;
4332 /* do processor dependent cleanup */
4333 PMCDBG(MOD,INI,3, "%s", "md cleanup");
4335 pmc_save_cpu_binding(&pb);
4336 for (cpu = 0; cpu < mp_ncpus; cpu++) {
4337 PMCDBG(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
4338 cpu, pmc_pcpu[cpu]);
4339 if (pmc_cpu_is_disabled(cpu))
4341 pmc_select_cpu(cpu);
4343 (void) md->pmd_cleanup(cpu);
4347 pmc_restore_cpu_binding(&pb);
4350 /* deallocate per-cpu structures */
4351 FREE(pmc_pcpu, M_PMC);
4354 FREE(pmc_pcpu_saved, M_PMC);
4355 pmc_pcpu_saved = NULL;
4358 FREE(pmc_pmcdisp, M_PMC);
4364 sx_xunlock(&pmc_sx); /* we are done */
4368 * The function called at load/unload.
4372 load (struct module *module __unused, int cmd, void *arg __unused)
4380 /* initialize the subsystem */
4381 error = pmc_initialize();
4384 PMCDBG(MOD,INI,1, "syscall=%d ncpus=%d",
4385 pmc_syscall_num, mp_ncpus);
4392 PMCDBG(MOD,INI,1, "%s", "unloaded");
4396 error = EINVAL; /* XXX should panic(9) */
4404 MALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");