2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2003-2008 Joseph Koshy
5 * Copyright (c) 2007 The FreeBSD Foundation
6 * Copyright (c) 2018 Matthew Macy
9 * Portions of this software were developed by A. Joseph Koshy under
10 * sponsorship from the FreeBSD Foundation and Google, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
38 #include <sys/param.h>
39 #include <sys/eventhandler.h>
40 #include <sys/gtaskqueue.h>
42 #include <sys/kernel.h>
43 #include <sys/kthread.h>
44 #include <sys/limits.h>
46 #include <sys/malloc.h>
47 #include <sys/module.h>
48 #include <sys/mount.h>
49 #include <sys/mutex.h>
51 #include <sys/pmckern.h>
52 #include <sys/pmclog.h>
55 #include <sys/queue.h>
56 #include <sys/resourcevar.h>
57 #include <sys/rwlock.h>
58 #include <sys/sched.h>
59 #include <sys/signalvar.h>
62 #include <sys/sysctl.h>
63 #include <sys/sysent.h>
64 #include <sys/systm.h>
65 #include <sys/vnode.h>
67 #include <sys/linker.h> /* needs to be after <sys/malloc.h> */
69 #include <machine/atomic.h>
70 #include <machine/md_var.h>
73 #include <vm/vm_extern.h>
75 #include <vm/vm_map.h>
76 #include <vm/vm_object.h>
78 #include "hwpmc_soft.h"
81 #define NDOMAINS vm_ndomains
84 #define malloc_domain(size, type, domain, flags) malloc((size), (type), (flags))
85 #define free_domain(addr, type) free(addr, type)
93 PMC_FLAG_NONE = 0x00, /* do nothing */
94 PMC_FLAG_REMOVE = 0x01, /* atomically remove entry from hash */
95 PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
96 PMC_FLAG_NOWAIT = 0x04, /* do not wait for mallocs */
100 * The offset in sysent where the syscall is allocated.
103 static int pmc_syscall_num = NO_SYSCALL;
104 struct pmc_cpu **pmc_pcpu; /* per-cpu state */
105 pmc_value_t *pmc_pcpu_saved; /* saved PMC values: CSW handling */
107 #define PMC_PCPU_SAVED(C,R) pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
109 struct mtx_pool *pmc_mtxpool;
110 static int *pmc_pmcdisp; /* PMC row dispositions */
112 #define PMC_ROW_DISP_IS_FREE(R) (pmc_pmcdisp[(R)] == 0)
113 #define PMC_ROW_DISP_IS_THREAD(R) (pmc_pmcdisp[(R)] > 0)
114 #define PMC_ROW_DISP_IS_STANDALONE(R) (pmc_pmcdisp[(R)] < 0)
116 #define PMC_MARK_ROW_FREE(R) do { \
117 pmc_pmcdisp[(R)] = 0; \
120 #define PMC_MARK_ROW_STANDALONE(R) do { \
121 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
123 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
124 KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()), \
125 ("[pmc,%d] row disposition error", __LINE__)); \
128 #define PMC_UNMARK_ROW_STANDALONE(R) do { \
129 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
130 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
134 #define PMC_MARK_ROW_THREAD(R) do { \
135 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
137 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
140 #define PMC_UNMARK_ROW_THREAD(R) do { \
141 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
142 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
147 /* various event handlers */
148 static eventhandler_tag pmc_exit_tag, pmc_fork_tag, pmc_kld_load_tag,
151 /* Module statistics */
152 struct pmc_driverstats pmc_stats;
155 /* Machine/processor dependent operations */
156 static struct pmc_mdep *md;
159 * Hash tables mapping owner processes and target threads to PMCs.
162 struct mtx pmc_processhash_mtx; /* spin mutex */
163 static u_long pmc_processhashmask;
164 static LIST_HEAD(pmc_processhash, pmc_process) *pmc_processhash;
167 * Hash table of PMC owner descriptors. This table is protected by
168 * the shared PMC "sx" lock.
171 static u_long pmc_ownerhashmask;
172 static LIST_HEAD(pmc_ownerhash, pmc_owner) *pmc_ownerhash;
175 * List of PMC owners with system-wide sampling PMCs.
178 static CK_LIST_HEAD(, pmc_owner) pmc_ss_owners;
181 * List of free thread entries. This is protected by the spin
184 static struct mtx pmc_threadfreelist_mtx; /* spin mutex */
185 static LIST_HEAD(, pmc_thread) pmc_threadfreelist;
186 static int pmc_threadfreelist_entries=0;
187 #define THREADENTRY_SIZE \
188 (sizeof(struct pmc_thread) + (md->pmd_npmc * sizeof(struct pmc_threadpmcstate)))
191 * Task to free thread descriptors
193 static struct grouptask free_gtask;
196 * A map of row indices to classdep structures.
198 static struct pmc_classdep **pmc_rowindex_to_classdep;
205 static int pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
206 static int pmc_debugflags_parse(char *newstr, char *fence);
209 static int load(struct module *module, int cmd, void *arg);
210 static void pmc_add_thread_descriptors_from_proc(struct proc *p,
211 struct pmc_process *pp);
212 static int pmc_attach_process(struct proc *p, struct pmc *pm);
213 static struct pmc *pmc_allocate_pmc_descriptor(void);
214 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
215 static int pmc_attach_one_process(struct proc *p, struct pmc *pm);
216 static int pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
218 static int pmc_can_attach(struct pmc *pm, struct proc *p);
219 static void pmc_capture_user_callchain(int cpu, int soft, struct trapframe *tf);
220 static void pmc_cleanup(void);
221 static int pmc_detach_process(struct proc *p, struct pmc *pm);
222 static int pmc_detach_one_process(struct proc *p, struct pmc *pm,
224 static void pmc_destroy_owner_descriptor(struct pmc_owner *po);
225 static void pmc_destroy_pmc_descriptor(struct pmc *pm);
226 static void pmc_destroy_process_descriptor(struct pmc_process *pp);
227 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
228 static int pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
229 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
231 static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
233 static struct pmc_thread *pmc_find_thread_descriptor(struct pmc_process *pp,
234 struct thread *td, uint32_t mode);
235 static void pmc_force_context_switch(void);
236 static void pmc_link_target_process(struct pmc *pm,
237 struct pmc_process *pp);
238 static void pmc_log_all_process_mappings(struct pmc_owner *po);
239 static void pmc_log_kernel_mappings(struct pmc *pm);
240 static void pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
241 static void pmc_maybe_remove_owner(struct pmc_owner *po);
242 static void pmc_process_csw_in(struct thread *td);
243 static void pmc_process_csw_out(struct thread *td);
244 static void pmc_process_exit(void *arg, struct proc *p);
245 static void pmc_process_fork(void *arg, struct proc *p1,
246 struct proc *p2, int n);
247 static void pmc_process_samples(int cpu, int soft);
248 static void pmc_release_pmc_descriptor(struct pmc *pmc);
249 static void pmc_process_thread_add(struct thread *td);
250 static void pmc_process_thread_delete(struct thread *td);
251 static void pmc_remove_owner(struct pmc_owner *po);
252 static void pmc_remove_process_descriptor(struct pmc_process *pp);
253 static void pmc_restore_cpu_binding(struct pmc_binding *pb);
254 static void pmc_save_cpu_binding(struct pmc_binding *pb);
255 static void pmc_select_cpu(int cpu);
256 static int pmc_start(struct pmc *pm);
257 static int pmc_stop(struct pmc *pm);
258 static int pmc_syscall_handler(struct thread *td, void *syscall_args);
259 static struct pmc_thread *pmc_thread_descriptor_pool_alloc(void);
260 static void pmc_thread_descriptor_pool_drain(void);
261 static void pmc_thread_descriptor_pool_free(struct pmc_thread *pt);
262 static void pmc_unlink_target_process(struct pmc *pmc,
263 struct pmc_process *pp);
264 static int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
265 static int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
266 static struct pmc_mdep *pmc_generic_cpu_initialize(void);
267 static void pmc_generic_cpu_finalize(struct pmc_mdep *md);
270 * Kernel tunables and sysctl(8) interface.
273 SYSCTL_DECL(_kern_hwpmc);
274 SYSCTL_NODE(_kern_hwpmc, OID_AUTO, stats, CTLFLAG_RW, 0, "HWPMC stats");
278 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_ignored, CTLFLAG_RW,
279 &pmc_stats.pm_intr_ignored, "# of interrupts ignored");
280 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_processed, CTLFLAG_RW,
281 &pmc_stats.pm_intr_processed, "# of interrupts processed");
282 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_bufferfull, CTLFLAG_RW,
283 &pmc_stats.pm_intr_bufferfull, "# of interrupts where buffer was full");
284 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscalls, CTLFLAG_RW,
285 &pmc_stats.pm_syscalls, "# of syscalls");
286 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscall_errors, CTLFLAG_RW,
287 &pmc_stats.pm_syscall_errors, "# of syscall_errors");
288 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests, CTLFLAG_RW,
289 &pmc_stats.pm_buffer_requests, "# of buffer requests");
290 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests_failed, CTLFLAG_RW,
291 &pmc_stats.pm_buffer_requests_failed, "# of buffer requests which failed");
292 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, log_sweeps, CTLFLAG_RW,
293 &pmc_stats.pm_log_sweeps, "# of ?");
295 static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
296 SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_RDTUN,
297 &pmc_callchaindepth, 0, "depth of call chain records");
300 SYSCTL_STRING(_kern_hwpmc, OID_AUTO, cpuid, CTLFLAG_RD,
301 pmc_cpuid, 0, "cpu version string");
303 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
304 char pmc_debugstr[PMC_DEBUG_STRSIZE];
305 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
306 sizeof(pmc_debugstr));
307 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
308 CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
309 0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
314 * kern.hwpmc.hashrows -- determines the number of rows in the
315 * of the hash table used to look up threads
318 static int pmc_hashsize = PMC_HASH_SIZE;
319 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_RDTUN,
320 &pmc_hashsize, 0, "rows in hash tables");
323 * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
326 static int pmc_nsamples = PMC_NSAMPLES;
327 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_RDTUN,
328 &pmc_nsamples, 0, "number of PC samples per CPU");
332 * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
335 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
336 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_RDTUN,
337 &pmc_mtxpool_size, 0, "size of spin mutex pool");
341 * kern.hwpmc.threadfreelist_entries -- number of free entries
344 SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_entries, CTLFLAG_RD,
345 &pmc_threadfreelist_entries, 0, "number of avalable thread entries");
349 * kern.hwpmc.threadfreelist_max -- maximum number of free entries
352 static int pmc_threadfreelist_max = PMC_THREADLIST_MAX;
353 SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_max, CTLFLAG_RW,
354 &pmc_threadfreelist_max, 0,
355 "maximum number of available thread entries before freeing some");
359 * security.bsd.unprivileged_syspmcs -- allow non-root processes to
360 * allocate system-wide PMCs.
362 * Allowing unprivileged processes to allocate system PMCs is convenient
363 * if system-wide measurements need to be taken concurrently with other
364 * per-process measurements. This feature is turned off by default.
367 static int pmc_unprivileged_syspmcs = 0;
368 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RWTUN,
369 &pmc_unprivileged_syspmcs, 0,
370 "allow unprivileged process to allocate system PMCs");
373 * Hash function. Discard the lower 2 bits of the pointer since
374 * these are always zero for our uses. The hash multiplier is
375 * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
379 #define _PMC_HM 11400714819323198486u
381 #define _PMC_HM 2654435769u
383 #error Must know the size of 'long' to compile
386 #define PMC_HASH_PTR(P,M) ((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
392 /* The `sysent' for the new syscall */
393 static struct sysent pmc_sysent = {
395 .sy_call = pmc_syscall_handler,
398 static struct syscall_module_data pmc_syscall_mod = {
401 .offset = &pmc_syscall_num,
402 .new_sysent = &pmc_sysent,
403 .old_sysent = { .sy_narg = 0, .sy_call = NULL },
404 .flags = SY_THR_STATIC_KLD,
407 static moduledata_t pmc_mod = {
408 .name = PMC_MODULE_NAME,
409 .evhand = syscall_module_handler,
410 .priv = &pmc_syscall_mod,
413 #ifdef EARLY_AP_STARTUP
414 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SYSCALLS, SI_ORDER_ANY);
416 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
418 MODULE_VERSION(pmc, PMC_VERSION);
421 enum pmc_dbgparse_state {
422 PMCDS_WS, /* in whitespace */
423 PMCDS_MAJOR, /* seen a major keyword */
428 pmc_debugflags_parse(char *newstr, char *fence)
431 struct pmc_debugflags *tmpflags;
432 int error, found, *newbits, tmp;
435 tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK|M_ZERO);
440 for (; p < fence && (c = *p); p++) {
442 /* skip white space */
443 if (c == ' ' || c == '\t')
446 /* look for a keyword followed by "=" */
447 for (q = p; p < fence && (c = *p) && c != '='; p++)
457 /* lookup flag group name */
458 #define DBG_SET_FLAG_MAJ(S,F) \
459 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
460 newbits = &tmpflags->pdb_ ## F;
462 DBG_SET_FLAG_MAJ("cpu", CPU);
463 DBG_SET_FLAG_MAJ("csw", CSW);
464 DBG_SET_FLAG_MAJ("logging", LOG);
465 DBG_SET_FLAG_MAJ("module", MOD);
466 DBG_SET_FLAG_MAJ("md", MDP);
467 DBG_SET_FLAG_MAJ("owner", OWN);
468 DBG_SET_FLAG_MAJ("pmc", PMC);
469 DBG_SET_FLAG_MAJ("process", PRC);
470 DBG_SET_FLAG_MAJ("sampling", SAM);
472 if (newbits == NULL) {
477 p++; /* skip the '=' */
479 /* Now parse the individual flags */
482 for (q = p; p < fence && (c = *p); p++)
483 if (c == ' ' || c == '\t' || c == ',')
486 /* p == fence or c == ws or c == "," or c == 0 */
488 if ((kwlen = p - q) == 0) {
494 #define DBG_SET_FLAG_MIN(S,F) \
495 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
496 tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
498 /* a '*' denotes all possible flags in the group */
499 if (kwlen == 1 && *q == '*')
501 /* look for individual flag names */
502 DBG_SET_FLAG_MIN("allocaterow", ALR);
503 DBG_SET_FLAG_MIN("allocate", ALL);
504 DBG_SET_FLAG_MIN("attach", ATT);
505 DBG_SET_FLAG_MIN("bind", BND);
506 DBG_SET_FLAG_MIN("config", CFG);
507 DBG_SET_FLAG_MIN("exec", EXC);
508 DBG_SET_FLAG_MIN("exit", EXT);
509 DBG_SET_FLAG_MIN("find", FND);
510 DBG_SET_FLAG_MIN("flush", FLS);
511 DBG_SET_FLAG_MIN("fork", FRK);
512 DBG_SET_FLAG_MIN("getbuf", GTB);
513 DBG_SET_FLAG_MIN("hook", PMH);
514 DBG_SET_FLAG_MIN("init", INI);
515 DBG_SET_FLAG_MIN("intr", INT);
516 DBG_SET_FLAG_MIN("linktarget", TLK);
517 DBG_SET_FLAG_MIN("mayberemove", OMR);
518 DBG_SET_FLAG_MIN("ops", OPS);
519 DBG_SET_FLAG_MIN("read", REA);
520 DBG_SET_FLAG_MIN("register", REG);
521 DBG_SET_FLAG_MIN("release", REL);
522 DBG_SET_FLAG_MIN("remove", ORM);
523 DBG_SET_FLAG_MIN("sample", SAM);
524 DBG_SET_FLAG_MIN("scheduleio", SIO);
525 DBG_SET_FLAG_MIN("select", SEL);
526 DBG_SET_FLAG_MIN("signal", SIG);
527 DBG_SET_FLAG_MIN("swi", SWI);
528 DBG_SET_FLAG_MIN("swo", SWO);
529 DBG_SET_FLAG_MIN("start", STA);
530 DBG_SET_FLAG_MIN("stop", STO);
531 DBG_SET_FLAG_MIN("syscall", PMS);
532 DBG_SET_FLAG_MIN("unlinktarget", TUL);
533 DBG_SET_FLAG_MIN("write", WRI);
535 /* unrecognized flag name */
540 if (c == 0 || c == ' ' || c == '\t') { /* end of flag group */
549 /* save the new flag set */
550 bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
553 free(tmpflags, M_PMC);
558 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
560 char *fence, *newstr;
564 (void) arg1; (void) arg2; /* unused parameters */
566 n = sizeof(pmc_debugstr);
567 newstr = malloc(n, M_PMC, M_WAITOK|M_ZERO);
568 (void) strlcpy(newstr, pmc_debugstr, n);
570 error = sysctl_handle_string(oidp, newstr, n, req);
572 /* if there is a new string, parse and copy it */
573 if (error == 0 && req->newptr != NULL) {
574 fence = newstr + (n < req->newlen ? n : req->newlen + 1);
575 if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
576 (void) strlcpy(pmc_debugstr, newstr,
577 sizeof(pmc_debugstr));
587 * Map a row index to a classdep structure and return the adjusted row
588 * index for the PMC class index.
590 static struct pmc_classdep *
591 pmc_ri_to_classdep(struct pmc_mdep *md, int ri, int *adjri)
593 struct pmc_classdep *pcd;
597 KASSERT(ri >= 0 && ri < md->pmd_npmc,
598 ("[pmc,%d] illegal row-index %d", __LINE__, ri));
600 pcd = pmc_rowindex_to_classdep[ri];
603 ("[pmc,%d] ri %d null pcd", __LINE__, ri));
605 *adjri = ri - pcd->pcd_ri;
607 KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
608 ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));
614 * Concurrency Control
616 * The driver manages the following data structures:
618 * - target process descriptors, one per target process
619 * - owner process descriptors (and attached lists), one per owner process
620 * - lookup hash tables for owner and target processes
621 * - PMC descriptors (and attached lists)
622 * - per-cpu hardware state
623 * - the 'hook' variable through which the kernel calls into
625 * - the machine hardware state (managed by the MD layer)
627 * These data structures are accessed from:
629 * - thread context-switch code
630 * - interrupt handlers (possibly on multiple cpus)
631 * - kernel threads on multiple cpus running on behalf of user
632 * processes doing system calls
633 * - this driver's private kernel threads
635 * = Locks and Locking strategy =
637 * The driver uses four locking strategies for its operation:
639 * - The global SX lock "pmc_sx" is used to protect internal
642 * Calls into the module by syscall() start with this lock being
643 * held in exclusive mode. Depending on the requested operation,
644 * the lock may be downgraded to 'shared' mode to allow more
645 * concurrent readers into the module. Calls into the module from
646 * other parts of the kernel acquire the lock in shared mode.
648 * This SX lock is held in exclusive mode for any operations that
649 * modify the linkages between the driver's internal data structures.
651 * The 'pmc_hook' function pointer is also protected by this lock.
652 * It is only examined with the sx lock held in exclusive mode. The
653 * kernel module is allowed to be unloaded only with the sx lock held
654 * in exclusive mode. In normal syscall handling, after acquiring the
655 * pmc_sx lock we first check that 'pmc_hook' is non-null before
656 * proceeding. This prevents races between the thread unloading the module
657 * and other threads seeking to use the module.
659 * - Lookups of target process structures and owner process structures
660 * cannot use the global "pmc_sx" SX lock because these lookups need
661 * to happen during context switches and in other critical sections
662 * where sleeping is not allowed. We protect these lookup tables
663 * with their own private spin-mutexes, "pmc_processhash_mtx" and
664 * "pmc_ownerhash_mtx".
666 * - Interrupt handlers work in a lock free manner. At interrupt
667 * time, handlers look at the PMC pointer (phw->phw_pmc) configured
668 * when the PMC was started. If this pointer is NULL, the interrupt
669 * is ignored after updating driver statistics. We ensure that this
670 * pointer is set (using an atomic operation if necessary) before the
671 * PMC hardware is started. Conversely, this pointer is unset atomically
672 * only after the PMC hardware is stopped.
674 * We ensure that everything needed for the operation of an
675 * interrupt handler is available without it needing to acquire any
676 * locks. We also ensure that a PMC's software state is destroyed only
677 * after the PMC is taken off hardware (on all CPUs).
679 * - Context-switch handling with process-private PMCs needs more
682 * A given process may be the target of multiple PMCs. For example,
683 * PMCATTACH and PMCDETACH may be requested by a process on one CPU
684 * while the target process is running on another. A PMC could also
685 * be getting released because its owner is exiting. We tackle
686 * these situations in the following manner:
688 * - each target process structure 'pmc_process' has an array
689 * of 'struct pmc *' pointers, one for each hardware PMC.
691 * - At context switch IN time, each "target" PMC in RUNNING state
692 * gets started on hardware and a pointer to each PMC is copied into
693 * the per-cpu phw array. The 'runcount' for the PMC is
696 * - At context switch OUT time, all process-virtual PMCs are stopped
697 * on hardware. The saved value is added to the PMCs value field
698 * only if the PMC is in a non-deleted state (the PMCs state could
699 * have changed during the current time slice).
701 * Note that since in-between a switch IN on a processor and a switch
702 * OUT, the PMC could have been released on another CPU. Therefore
703 * context switch OUT always looks at the hardware state to turn
704 * OFF PMCs and will update a PMC's saved value only if reachable
705 * from the target process record.
707 * - OP PMCRELEASE could be called on a PMC at any time (the PMC could
708 * be attached to many processes at the time of the call and could
709 * be active on multiple CPUs).
711 * We prevent further scheduling of the PMC by marking it as in
712 * state 'DELETED'. If the runcount of the PMC is non-zero then
713 * this PMC is currently running on a CPU somewhere. The thread
714 * doing the PMCRELEASE operation waits by repeatedly doing a
715 * pause() till the runcount comes to zero.
717 * The contents of a PMC descriptor (struct pmc) are protected using
718 * a spin-mutex. In order to save space, we use a mutex pool.
720 * In terms of lock types used by witness(4), we use:
721 * - Type "pmc-sx", used by the global SX lock.
722 * - Type "pmc-sleep", for sleep mutexes used by logger threads.
723 * - Type "pmc-per-proc", for protecting PMC owner descriptors.
724 * - Type "pmc-leaf", used for all other spin mutexes.
728 * save the cpu binding of the current kthread
732 pmc_save_cpu_binding(struct pmc_binding *pb)
734 PMCDBG0(CPU,BND,2, "save-cpu");
735 thread_lock(curthread);
736 pb->pb_bound = sched_is_bound(curthread);
737 pb->pb_cpu = curthread->td_oncpu;
738 thread_unlock(curthread);
739 PMCDBG1(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
743 * restore the cpu binding of the current thread
747 pmc_restore_cpu_binding(struct pmc_binding *pb)
749 PMCDBG2(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
750 curthread->td_oncpu, pb->pb_cpu);
751 thread_lock(curthread);
753 sched_bind(curthread, pb->pb_cpu);
755 sched_unbind(curthread);
756 thread_unlock(curthread);
757 PMCDBG0(CPU,BND,2, "restore-cpu done");
761 * move execution over the specified cpu and bind it there.
765 pmc_select_cpu(int cpu)
767 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
768 ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
770 /* Never move to an inactive CPU. */
771 KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
772 "CPU %d", __LINE__, cpu));
774 PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d", cpu);
775 thread_lock(curthread);
776 sched_bind(curthread, cpu);
777 thread_unlock(curthread);
779 KASSERT(curthread->td_oncpu == cpu,
780 ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
781 cpu, curthread->td_oncpu));
783 PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
787 * Force a context switch.
789 * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
790 * guaranteed to force a context switch.
794 pmc_force_context_switch(void)
801 * Get the file name for an executable. This is a simple wrapper
802 * around vn_fullpath(9).
806 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
809 *fullpath = "unknown";
811 vn_fullpath(curthread, v, fullpath, freepath);
815 * remove an process owning PMCs
819 pmc_remove_owner(struct pmc_owner *po)
821 struct pmc *pm, *tmp;
823 sx_assert(&pmc_sx, SX_XLOCKED);
825 PMCDBG1(OWN,ORM,1, "remove-owner po=%p", po);
827 /* Remove descriptor from the owner hash table */
828 LIST_REMOVE(po, po_next);
830 /* release all owned PMC descriptors */
831 LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
832 PMCDBG1(OWN,ORM,2, "pmc=%p", pm);
833 KASSERT(pm->pm_owner == po,
834 ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
836 pmc_release_pmc_descriptor(pm); /* will unlink from the list */
837 pmc_destroy_pmc_descriptor(pm);
840 KASSERT(po->po_sscount == 0,
841 ("[pmc,%d] SS count not zero", __LINE__));
842 KASSERT(LIST_EMPTY(&po->po_pmcs),
843 ("[pmc,%d] PMC list not empty", __LINE__));
845 /* de-configure the log file if present */
846 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
847 pmclog_deconfigure_log(po);
851 * remove an owner process record if all conditions are met.
855 pmc_maybe_remove_owner(struct pmc_owner *po)
858 PMCDBG1(OWN,OMR,1, "maybe-remove-owner po=%p", po);
861 * Remove owner record if
862 * - this process does not own any PMCs
863 * - this process has not allocated a system-wide sampling buffer
866 if (LIST_EMPTY(&po->po_pmcs) &&
867 ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
868 pmc_remove_owner(po);
869 pmc_destroy_owner_descriptor(po);
874 * Add an association between a target process and a PMC.
878 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
881 struct pmc_target *pt;
883 struct pmc_thread *pt_td;
886 sx_assert(&pmc_sx, SX_XLOCKED);
888 KASSERT(pm != NULL && pp != NULL,
889 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
890 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
891 ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
892 __LINE__, pm, pp->pp_proc->p_pid));
893 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1),
894 ("[pmc,%d] Illegal reference count %d for process record %p",
895 __LINE__, pp->pp_refcnt, (void *) pp));
897 ri = PMC_TO_ROWINDEX(pm);
899 PMCDBG3(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
903 LIST_FOREACH(pt, &pm->pm_targets, pt_next)
904 if (pt->pt_process == pp)
905 KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
909 pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK|M_ZERO);
912 LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
914 atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
917 if (pm->pm_owner->po_owner == pp->pp_proc)
918 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
921 * Initialize the per-process values at this row index.
923 pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
924 pm->pm_sc.pm_reloadcount : 0;
929 /* Confirm that the per-thread values at this row index are cleared. */
930 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
931 mtx_lock_spin(pp->pp_tdslock);
932 LIST_FOREACH(pt_td, &pp->pp_tds, pt_next) {
933 KASSERT(pt_td->pt_pmcs[ri].pt_pmcval == (pmc_value_t) 0,
934 ("[pmc,%d] pt_pmcval not cleared for pid=%d at "
935 "ri=%d", __LINE__, pp->pp_proc->p_pid, ri));
937 mtx_unlock_spin(pp->pp_tdslock);
943 * Removes the association between a target process and a PMC.
947 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
951 struct pmc_target *ptgt;
952 struct pmc_thread *pt;
954 sx_assert(&pmc_sx, SX_XLOCKED);
956 KASSERT(pm != NULL && pp != NULL,
957 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
959 KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc,
960 ("[pmc,%d] Illegal ref count %d on process record %p",
961 __LINE__, pp->pp_refcnt, (void *) pp));
963 ri = PMC_TO_ROWINDEX(pm);
965 PMCDBG3(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
968 KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
969 ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
970 ri, pm, pp->pp_pmcs[ri].pp_pmc));
972 pp->pp_pmcs[ri].pp_pmc = NULL;
973 pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
975 /* Clear the per-thread values at this row index. */
976 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
977 mtx_lock_spin(pp->pp_tdslock);
978 LIST_FOREACH(pt, &pp->pp_tds, pt_next)
979 pt->pt_pmcs[ri].pt_pmcval = (pmc_value_t) 0;
980 mtx_unlock_spin(pp->pp_tdslock);
983 /* Remove owner-specific flags */
984 if (pm->pm_owner->po_owner == pp->pp_proc) {
985 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
986 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
991 /* Remove the target process from the PMC structure */
992 LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
993 if (ptgt->pt_process == pp)
996 KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
997 "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
999 LIST_REMOVE(ptgt, pt_next);
1002 /* if the PMC now lacks targets, send the owner a SIGIO */
1003 if (LIST_EMPTY(&pm->pm_targets)) {
1004 p = pm->pm_owner->po_owner;
1006 kern_psignal(p, SIGIO);
1009 PMCDBG2(PRC,SIG,2, "signalling proc=%p signal=%d", p,
1015 * Check if PMC 'pm' may be attached to target process 't'.
1019 pmc_can_attach(struct pmc *pm, struct proc *t)
1021 struct proc *o; /* pmc owner */
1022 struct ucred *oc, *tc; /* owner, target credentials */
1023 int decline_attach, i;
1026 * A PMC's owner can always attach that PMC to itself.
1029 if ((o = pm->pm_owner->po_owner) == t)
1043 * The effective uid of the PMC owner should match at least one
1044 * of the {effective,real,saved} uids of the target process.
1047 decline_attach = oc->cr_uid != tc->cr_uid &&
1048 oc->cr_uid != tc->cr_svuid &&
1049 oc->cr_uid != tc->cr_ruid;
1052 * Every one of the target's group ids, must be in the owner's
1055 for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
1056 decline_attach = !groupmember(tc->cr_groups[i], oc);
1058 /* check the read and saved gids too */
1059 if (decline_attach == 0)
1060 decline_attach = !groupmember(tc->cr_rgid, oc) ||
1061 !groupmember(tc->cr_svgid, oc);
1066 return !decline_attach;
1070 * Attach a process to a PMC.
1074 pmc_attach_one_process(struct proc *p, struct pmc *pm)
1077 char *fullpath, *freepath;
1078 struct pmc_process *pp;
1080 sx_assert(&pmc_sx, SX_XLOCKED);
1082 PMCDBG5(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
1083 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1086 * Locate the process descriptor corresponding to process 'p',
1087 * allocating space as needed.
1089 * Verify that rowindex 'pm_rowindex' is free in the process
1092 * If not, allocate space for a descriptor and link the
1093 * process descriptor and PMC.
1095 ri = PMC_TO_ROWINDEX(pm);
1097 /* mark process as using HWPMCs */
1099 p->p_flag |= P_HWPMC;
1102 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL) {
1107 if (pp->pp_pmcs[ri].pp_pmc == pm) {/* already present at slot [ri] */
1112 if (pp->pp_pmcs[ri].pp_pmc != NULL) {
1117 pmc_link_target_process(pm, pp);
1119 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
1120 (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
1121 pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
1123 pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
1125 /* issue an attach event to a configured log file */
1126 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
1127 if (p->p_flag & P_KPROC) {
1128 fullpath = kernelname;
1131 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1132 pmclog_process_pmcattach(pm, p->p_pid, fullpath);
1134 free(freepath, M_TEMP);
1135 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1136 pmc_log_process_mappings(pm->pm_owner, p);
1142 p->p_flag &= ~P_HWPMC;
1148 * Attach a process and optionally its children
1152 pmc_attach_process(struct proc *p, struct pmc *pm)
1157 sx_assert(&pmc_sx, SX_XLOCKED);
1159 PMCDBG5(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1160 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1164 * If this PMC successfully allowed a GETMSR operation
1165 * in the past, disallow further ATTACHes.
1168 if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1171 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1172 return pmc_attach_one_process(p, pm);
1175 * Traverse all child processes, attaching them to
1179 sx_slock(&proctree_lock);
1184 if ((error = pmc_attach_one_process(p, pm)) != 0)
1186 if (!LIST_EMPTY(&p->p_children))
1187 p = LIST_FIRST(&p->p_children);
1191 if (LIST_NEXT(p, p_sibling)) {
1192 p = LIST_NEXT(p, p_sibling);
1200 (void) pmc_detach_process(top, pm);
1203 sx_sunlock(&proctree_lock);
1208 * Detach a process from a PMC. If there are no other PMCs tracking
1209 * this process, remove the process structure from its hash table. If
1210 * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1214 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1217 struct pmc_process *pp;
1219 sx_assert(&pmc_sx, SX_XLOCKED);
1222 ("[pmc,%d] null pm pointer", __LINE__));
1224 ri = PMC_TO_ROWINDEX(pm);
1226 PMCDBG6(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1227 pm, ri, p, p->p_pid, p->p_comm, flags);
1229 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1232 if (pp->pp_pmcs[ri].pp_pmc != pm)
1235 pmc_unlink_target_process(pm, pp);
1237 /* Issue a detach entry if a log file is configured */
1238 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1239 pmclog_process_pmcdetach(pm, p->p_pid);
1242 * If there are no PMCs targeting this process, we remove its
1243 * descriptor from the target hash table and unset the P_HWPMC
1244 * flag in the struct proc.
1246 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1247 ("[pmc,%d] Illegal refcnt %d for process struct %p",
1248 __LINE__, pp->pp_refcnt, pp));
1250 if (pp->pp_refcnt != 0) /* still a target of some PMC */
1253 pmc_remove_process_descriptor(pp);
1255 if (flags & PMC_FLAG_REMOVE)
1256 pmc_destroy_process_descriptor(pp);
1259 p->p_flag &= ~P_HWPMC;
1266 * Detach a process and optionally its descendants from a PMC.
1270 pmc_detach_process(struct proc *p, struct pmc *pm)
1274 sx_assert(&pmc_sx, SX_XLOCKED);
1276 PMCDBG5(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1277 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1279 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1280 return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1283 * Traverse all children, detaching them from this PMC. We
1284 * ignore errors since we could be detaching a PMC from a
1285 * partially attached proc tree.
1288 sx_slock(&proctree_lock);
1293 (void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1295 if (!LIST_EMPTY(&p->p_children))
1296 p = LIST_FIRST(&p->p_children);
1300 if (LIST_NEXT(p, p_sibling)) {
1301 p = LIST_NEXT(p, p_sibling);
1309 sx_sunlock(&proctree_lock);
1311 if (LIST_EMPTY(&pm->pm_targets))
1312 pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1319 * Thread context switch IN
1323 pmc_process_csw_in(struct thread *td)
1326 unsigned int adjri, ri;
1331 pmc_value_t newvalue;
1332 struct pmc_process *pp;
1333 struct pmc_thread *pt;
1334 struct pmc_classdep *pcd;
1338 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1341 KASSERT(pp->pp_proc == td->td_proc,
1342 ("[pmc,%d] not my thread state", __LINE__));
1344 critical_enter(); /* no preemption from this point */
1346 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1348 PMCDBG5(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1349 p->p_pid, p->p_comm, pp);
1351 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1352 ("[pmc,%d] weird CPU id %d", __LINE__, cpu));
1356 for (ri = 0; ri < md->pmd_npmc; ri++) {
1358 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1361 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1362 ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1363 __LINE__, PMC_TO_MODE(pm)));
1365 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1366 ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1367 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1370 * Only PMCs that are marked as 'RUNNING' need
1371 * be placed on hardware.
1374 if (pm->pm_state != PMC_STATE_RUNNING)
1377 /* increment PMC runcount */
1378 counter_u64_add(pm->pm_runcount, 1);
1380 /* configure the HWPMC we are going to use. */
1381 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1382 pcd->pcd_config_pmc(cpu, adjri, pm);
1384 phw = pc->pc_hwpmcs[ri];
1386 KASSERT(phw != NULL,
1387 ("[pmc,%d] null hw pointer", __LINE__));
1389 KASSERT(phw->phw_pmc == pm,
1390 ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1394 * Write out saved value and start the PMC.
1396 * Sampling PMCs use a per-thread value, while
1397 * counting mode PMCs use a per-pmc value that is
1398 * inherited across descendants.
1400 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1402 pt = pmc_find_thread_descriptor(pp, td,
1406 ("[pmc,%d] No thread found for td=%p", __LINE__,
1409 mtx_pool_lock_spin(pmc_mtxpool, pm);
1412 * If we have a thread descriptor, use the per-thread
1413 * counter in the descriptor. If not, we will use
1414 * a per-process counter.
1416 * TODO: Remove the per-process "safety net" once
1417 * we have thoroughly tested that we don't hit the
1421 if (pt->pt_pmcs[ri].pt_pmcval > 0)
1422 newvalue = pt->pt_pmcs[ri].pt_pmcval;
1424 newvalue = pm->pm_sc.pm_reloadcount;
1427 * Use the saved value calculated after the most
1428 * recent time a thread using the shared counter
1429 * switched out. Reset the saved count in case
1430 * another thread from this process switches in
1431 * before any threads switch out.
1434 newvalue = pp->pp_pmcs[ri].pp_pmcval;
1435 pp->pp_pmcs[ri].pp_pmcval =
1436 pm->pm_sc.pm_reloadcount;
1438 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1439 KASSERT(newvalue > 0 && newvalue <=
1440 pm->pm_sc.pm_reloadcount,
1441 ("[pmc,%d] pmcval outside of expected range cpu=%d "
1442 "ri=%d pmcval=%jx pm_reloadcount=%jx", __LINE__,
1443 cpu, ri, newvalue, pm->pm_sc.pm_reloadcount));
1445 KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1446 ("[pmc,%d] illegal mode=%d", __LINE__,
1448 mtx_pool_lock_spin(pmc_mtxpool, pm);
1449 newvalue = PMC_PCPU_SAVED(cpu, ri) =
1450 pm->pm_gv.pm_savedvalue;
1451 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1454 PMCDBG3(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1456 pcd->pcd_write_pmc(cpu, adjri, newvalue);
1458 /* If a sampling mode PMC, reset stalled state. */
1459 if (PMC_TO_MODE(pm) == PMC_MODE_TS)
1460 pm->pm_pcpu_state[cpu].pps_stalled = 0;
1462 /* Indicate that we desire this to run. */
1463 pm->pm_pcpu_state[cpu].pps_cpustate = 1;
1465 /* Start the PMC. */
1466 pcd->pcd_start_pmc(cpu, adjri);
1470 * perform any other architecture/cpu dependent thread
1471 * switch-in actions.
1474 (void) (*md->pmd_switch_in)(pc, pp);
1481 * Thread context switch OUT.
1485 pmc_process_csw_out(struct thread *td)
1493 pmc_value_t newvalue;
1494 unsigned int adjri, ri;
1495 struct pmc_process *pp;
1496 struct pmc_thread *pt = NULL;
1497 struct pmc_classdep *pcd;
1501 * Locate our process descriptor; this may be NULL if
1502 * this process is exiting and we have already removed
1503 * the process from the target process table.
1505 * Note that due to kernel preemption, multiple
1506 * context switches may happen while the process is
1509 * Note also that if the target process cannot be
1510 * found we still need to deconfigure any PMCs that
1511 * are currently running on hardware.
1515 pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1523 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1525 PMCDBG5(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1526 p->p_pid, p->p_comm, pp);
1528 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1529 ("[pmc,%d weird CPU id %d", __LINE__, cpu));
1534 * When a PMC gets unlinked from a target PMC, it will
1535 * be removed from the target's pp_pmc[] array.
1537 * However, on a MP system, the target could have been
1538 * executing on another CPU at the time of the unlink.
1539 * So, at context switch OUT time, we need to look at
1540 * the hardware to determine if a PMC is scheduled on
1544 for (ri = 0; ri < md->pmd_npmc; ri++) {
1546 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1548 (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
1550 if (pm == NULL) /* nothing at this row index */
1553 mode = PMC_TO_MODE(pm);
1554 if (!PMC_IS_VIRTUAL_MODE(mode))
1555 continue; /* not a process virtual PMC */
1557 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1558 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1559 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1562 * Change desired state, and then stop if not stalled.
1563 * This two-step dance should avoid race conditions where
1564 * an interrupt re-enables the PMC after this code has
1565 * already checked the pm_stalled flag.
1567 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
1568 if (pm->pm_pcpu_state[cpu].pps_stalled == 0)
1569 pcd->pcd_stop_pmc(cpu, adjri);
1571 /* reduce this PMC's runcount */
1572 counter_u64_add(pm->pm_runcount, -1);
1575 * If this PMC is associated with this process,
1579 if (pm->pm_state != PMC_STATE_DELETED && pp != NULL &&
1580 pp->pp_pmcs[ri].pp_pmc != NULL) {
1581 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1582 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1583 pm, ri, pp->pp_pmcs[ri].pp_pmc));
1585 KASSERT(pp->pp_refcnt > 0,
1586 ("[pmc,%d] pp refcnt = %d", __LINE__,
1589 pcd->pcd_read_pmc(cpu, adjri, &newvalue);
1591 if (mode == PMC_MODE_TS) {
1592 PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d val=%jd (samp)",
1596 pt = pmc_find_thread_descriptor(pp, td,
1600 ("[pmc,%d] No thread found for td=%p",
1603 mtx_pool_lock_spin(pmc_mtxpool, pm);
1606 * If we have a thread descriptor, save the
1607 * per-thread counter in the descriptor. If not,
1608 * we will update the per-process counter.
1610 * TODO: Remove the per-process "safety net"
1611 * once we have thoroughly tested that we
1612 * don't hit the above assert.
1615 pt->pt_pmcs[ri].pt_pmcval = newvalue;
1618 * For sampling process-virtual PMCs,
1619 * newvalue is the number of events to
1620 * be seen until the next sampling
1621 * interrupt. We can just add the events
1622 * left from this invocation to the
1623 * counter, then adjust in case we
1624 * overflow our range.
1626 * (Recall that we reload the counter
1627 * every time we use it.)
1629 pp->pp_pmcs[ri].pp_pmcval += newvalue;
1630 if (pp->pp_pmcs[ri].pp_pmcval >
1631 pm->pm_sc.pm_reloadcount)
1632 pp->pp_pmcs[ri].pp_pmcval -=
1633 pm->pm_sc.pm_reloadcount;
1635 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1637 tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1639 PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd (count)",
1643 * For counting process-virtual PMCs,
1644 * we expect the count to be
1645 * increasing monotonically, modulo a 64
1649 ("[pmc,%d] negative increment cpu=%d "
1650 "ri=%d newvalue=%jx saved=%jx "
1651 "incr=%jx", __LINE__, cpu, ri,
1652 newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1654 mtx_pool_lock_spin(pmc_mtxpool, pm);
1655 pm->pm_gv.pm_savedvalue += tmp;
1656 pp->pp_pmcs[ri].pp_pmcval += tmp;
1657 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1659 if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1660 pmclog_process_proccsw(pm, pp, tmp, td);
1664 /* mark hardware as free */
1665 pcd->pcd_config_pmc(cpu, adjri, NULL);
1669 * perform any other architecture/cpu dependent thread
1670 * switch out functions.
1673 (void) (*md->pmd_switch_out)(pc, pp);
1679 * A new thread for a process.
1682 pmc_process_thread_add(struct thread *td)
1684 struct pmc_process *pmc;
1686 pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
1688 pmc_find_thread_descriptor(pmc, td, PMC_FLAG_ALLOCATE);
1692 * A thread delete for a process.
1695 pmc_process_thread_delete(struct thread *td)
1697 struct pmc_process *pmc;
1699 pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
1701 pmc_thread_descriptor_pool_free(pmc_find_thread_descriptor(pmc,
1702 td, PMC_FLAG_REMOVE));
1706 * A mapping change for a process.
1710 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1714 char *fullpath, *freepath;
1715 const struct pmc *pm;
1716 struct pmc_owner *po;
1717 const struct pmc_process *pp;
1719 freepath = fullpath = NULL;
1720 epoch_exit_preempt(global_epoch_preempt);
1721 pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1723 pid = td->td_proc->p_pid;
1725 epoch_enter_preempt(global_epoch_preempt);
1726 /* Inform owners of all system-wide sampling PMCs. */
1727 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1728 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1729 pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1731 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1735 * Inform sampling PMC owners tracking this process.
1737 for (ri = 0; ri < md->pmd_npmc; ri++)
1738 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1739 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1740 pmclog_process_map_in(pm->pm_owner,
1741 pid, pkm->pm_address, fullpath);
1745 free(freepath, M_TEMP);
1750 * Log an munmap request.
1754 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1758 struct pmc_owner *po;
1759 const struct pmc *pm;
1760 const struct pmc_process *pp;
1762 pid = td->td_proc->p_pid;
1764 epoch_enter_preempt(global_epoch_preempt);
1765 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1766 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1767 pmclog_process_map_out(po, pid, pkm->pm_address,
1768 pkm->pm_address + pkm->pm_size);
1769 epoch_exit_preempt(global_epoch_preempt);
1771 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1774 for (ri = 0; ri < md->pmd_npmc; ri++)
1775 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1776 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1777 pmclog_process_map_out(pm->pm_owner, pid,
1778 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1782 * Log mapping information about the kernel.
1786 pmc_log_kernel_mappings(struct pmc *pm)
1788 struct pmc_owner *po;
1789 struct pmckern_map_in *km, *kmbase;
1791 MPASS(in_epoch() || sx_xlocked(&pmc_sx));
1792 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1793 ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1794 __LINE__, (void *) pm));
1798 if (po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE)
1802 * Log the current set of kernel modules.
1804 kmbase = linker_hwpmc_list_objects();
1805 for (km = kmbase; km->pm_file != NULL; km++) {
1806 PMCDBG2(LOG,REG,1,"%s %p", (char *) km->pm_file,
1807 (void *) km->pm_address);
1808 pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
1811 free(kmbase, M_LINKER);
1813 po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1817 * Log the mappings for a single process.
1821 pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1826 vm_map_entry_t entry;
1827 vm_offset_t last_end;
1828 u_int last_timestamp;
1829 struct vnode *last_vp;
1830 vm_offset_t start_addr;
1831 vm_object_t obj, lobj, tobj;
1832 char *fullpath, *freepath;
1835 last_end = (vm_offset_t) 0;
1836 fullpath = freepath = NULL;
1838 if ((vm = vmspace_acquire_ref(p)) == NULL)
1842 vm_map_lock_read(map);
1844 for (entry = map->header.next; entry != &map->header; entry = entry->next) {
1846 if (entry == NULL) {
1847 PMCDBG2(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly "
1848 "NULL! pid=%d vm_map=%p\n", p->p_pid, map);
1853 * We only care about executable map entries.
1855 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) ||
1856 !(entry->protection & VM_PROT_EXECUTE) ||
1857 (entry->object.vm_object == NULL)) {
1861 obj = entry->object.vm_object;
1862 VM_OBJECT_RLOCK(obj);
1865 * Walk the backing_object list to find the base
1866 * (non-shadowed) vm_object.
1868 for (lobj = tobj = obj; tobj != NULL; tobj = tobj->backing_object) {
1870 VM_OBJECT_RLOCK(tobj);
1872 VM_OBJECT_RUNLOCK(lobj);
1877 * At this point lobj is the base vm_object and it is locked.
1880 PMCDBG3(LOG,OPS,2, "hwpmc: lobj unexpectedly NULL! pid=%d "
1881 "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj);
1882 VM_OBJECT_RUNLOCK(obj);
1886 vp = vm_object_vnode(lobj);
1889 VM_OBJECT_RUNLOCK(lobj);
1890 VM_OBJECT_RUNLOCK(obj);
1895 * Skip contiguous regions that point to the same
1896 * vnode, so we don't emit redundant MAP-IN
1899 if (entry->start == last_end && vp == last_vp) {
1900 last_end = entry->end;
1902 VM_OBJECT_RUNLOCK(lobj);
1903 VM_OBJECT_RUNLOCK(obj);
1908 * We don't want to keep the proc's vm_map or this
1909 * vm_object locked while we walk the pathname, since
1910 * vn_fullpath() can sleep. However, if we drop the
1911 * lock, it's possible for concurrent activity to
1912 * modify the vm_map list. To protect against this,
1913 * we save the vm_map timestamp before we release the
1914 * lock, and check it after we reacquire the lock
1917 start_addr = entry->start;
1918 last_end = entry->end;
1919 last_timestamp = map->timestamp;
1920 vm_map_unlock_read(map);
1924 VM_OBJECT_RUNLOCK(lobj);
1926 VM_OBJECT_RUNLOCK(obj);
1929 pmc_getfilename(vp, &fullpath, &freepath);
1935 pmclog_process_map_in(po, p->p_pid, start_addr, fullpath);
1937 free(freepath, M_TEMP);
1939 vm_map_lock_read(map);
1942 * If our saved timestamp doesn't match, this means
1943 * that the vm_map was modified out from under us and
1944 * we can't trust our current "entry" pointer. Do a
1945 * new lookup for this entry. If there is no entry
1946 * for this address range, vm_map_lookup_entry() will
1947 * return the previous one, so we always want to go to
1948 * entry->next on the next loop iteration.
1950 * There is an edge condition here that can occur if
1951 * there is no entry at or before this address. In
1952 * this situation, vm_map_lookup_entry returns
1953 * &map->header, which would cause our loop to abort
1954 * without processing the rest of the map. However,
1955 * in practice this will never happen for process
1956 * vm_map. This is because the executable's text
1957 * segment is the first mapping in the proc's address
1958 * space, and this mapping is never removed until the
1959 * process exits, so there will always be a non-header
1960 * entry at or before the requested address for
1961 * vm_map_lookup_entry to return.
1963 if (map->timestamp != last_timestamp)
1964 vm_map_lookup_entry(map, last_end - 1, &entry);
1967 vm_map_unlock_read(map);
1973 * Log mappings for all processes in the system.
1977 pmc_log_all_process_mappings(struct pmc_owner *po)
1979 struct proc *p, *top;
1981 sx_assert(&pmc_sx, SX_XLOCKED);
1983 if ((p = pfind(1)) == NULL)
1984 panic("[pmc,%d] Cannot find init", __LINE__);
1988 sx_slock(&proctree_lock);
1993 pmc_log_process_mappings(po, p);
1994 if (!LIST_EMPTY(&p->p_children))
1995 p = LIST_FIRST(&p->p_children);
1999 if (LIST_NEXT(p, p_sibling)) {
2000 p = LIST_NEXT(p, p_sibling);
2007 sx_sunlock(&proctree_lock);
2011 * The 'hook' invoked from the kernel proper
2016 const char *pmc_hooknames[] = {
2017 /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
2036 pmc_hook_handler(struct thread *td, int function, void *arg)
2040 PMCDBG4(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
2041 pmc_hooknames[function], arg);
2050 case PMC_FN_PROCESS_EXEC:
2052 char *fullpath, *freepath;
2054 int is_using_hwpmcs;
2057 struct pmc_owner *po;
2058 struct pmc_process *pp;
2059 struct pmckern_procexec *pk;
2061 sx_assert(&pmc_sx, SX_XLOCKED);
2064 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
2066 pk = (struct pmckern_procexec *) arg;
2068 epoch_enter_preempt(global_epoch_preempt);
2069 /* Inform owners of SS mode PMCs of the exec event. */
2070 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
2071 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2072 pmclog_process_procexec(po, PMC_ID_INVALID,
2073 p->p_pid, pk->pm_entryaddr, fullpath);
2074 epoch_exit_preempt(global_epoch_preempt);
2077 is_using_hwpmcs = p->p_flag & P_HWPMC;
2080 if (!is_using_hwpmcs) {
2082 free(freepath, M_TEMP);
2087 * PMCs are not inherited across an exec(): remove any
2088 * PMCs that this process is the owner of.
2091 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
2092 pmc_remove_owner(po);
2093 pmc_destroy_owner_descriptor(po);
2097 * If the process being exec'ed is not the target of any
2100 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
2102 free(freepath, M_TEMP);
2107 * Log the exec event to all monitoring owners. Skip
2108 * owners who have already received the event because
2109 * they had system sampling PMCs active.
2111 for (ri = 0; ri < md->pmd_npmc; ri++)
2112 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
2114 if (po->po_sscount == 0 &&
2115 po->po_flags & PMC_PO_OWNS_LOGFILE)
2116 pmclog_process_procexec(po, pm->pm_id,
2117 p->p_pid, pk->pm_entryaddr,
2122 free(freepath, M_TEMP);
2125 PMCDBG4(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
2126 p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
2128 if (pk->pm_credentialschanged == 0) /* no change */
2132 * If the newly exec()'ed process has a different credential
2133 * than before, allow it to be the target of a PMC only if
2134 * the PMC's owner has sufficient privilege.
2137 for (ri = 0; ri < md->pmd_npmc; ri++)
2138 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
2139 if (pmc_can_attach(pm, td->td_proc) != 0)
2140 pmc_detach_one_process(td->td_proc,
2143 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
2144 ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
2145 pp->pp_refcnt, pp));
2148 * If this process is no longer the target of any
2149 * PMCs, we can remove the process entry and free
2153 if (pp->pp_refcnt == 0) {
2154 pmc_remove_process_descriptor(pp);
2155 pmc_destroy_process_descriptor(pp);
2163 pmc_process_csw_in(td);
2166 case PMC_FN_CSW_OUT:
2167 pmc_process_csw_out(td);
2171 * Process accumulated PC samples.
2173 * This function is expected to be called by hardclock() for
2174 * each CPU that has accumulated PC samples.
2176 * This function is to be executed on the CPU whose samples
2177 * are being processed.
2179 case PMC_FN_DO_SAMPLES:
2182 * Clear the cpu specific bit in the CPU mask before
2183 * do the rest of the processing. If the NMI handler
2184 * gets invoked after the "atomic_clear_int()" call
2185 * below but before "pmc_process_samples()" gets
2186 * around to processing the interrupt, then we will
2187 * come back here at the next hardclock() tick (and
2188 * may find nothing to do if "pmc_process_samples()"
2189 * had already processed the interrupt). We don't
2190 * lose the interrupt sample.
2192 DPCPU_SET(pmc_sampled, 0);
2193 cpu = PCPU_GET(cpuid);
2194 pmc_process_samples(cpu, PMC_HR);
2195 pmc_process_samples(cpu, PMC_SR);
2199 MPASS(in_epoch() || sx_xlocked(&pmc_sx));
2200 pmc_process_mmap(td, (struct pmckern_map_in *) arg);
2204 MPASS(in_epoch() || sx_xlocked(&pmc_sx));
2205 pmc_process_munmap(td, (struct pmckern_map_out *) arg);
2208 case PMC_FN_USER_CALLCHAIN:
2210 * Record a call chain.
2212 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2215 pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
2216 (struct trapframe *) arg);
2217 td->td_pflags &= ~TDP_CALLCHAIN;
2220 case PMC_FN_USER_CALLCHAIN_SOFT:
2222 * Record a call chain.
2224 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2226 pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_SR,
2227 (struct trapframe *) arg);
2228 td->td_pflags &= ~TDP_CALLCHAIN;
2231 case PMC_FN_SOFT_SAMPLING:
2233 * Call soft PMC sampling intr.
2235 pmc_soft_intr((struct pmckern_soft *) arg);
2238 case PMC_FN_THR_CREATE:
2239 pmc_process_thread_add(td);
2242 case PMC_FN_THR_EXIT:
2243 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2245 pmc_process_thread_delete(td);
2250 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
2260 * allocate a 'struct pmc_owner' descriptor in the owner hash table.
2263 static struct pmc_owner *
2264 pmc_allocate_owner_descriptor(struct proc *p)
2267 struct pmc_owner *po;
2268 struct pmc_ownerhash *poh;
2270 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2271 poh = &pmc_ownerhash[hindex];
2273 /* allocate space for N pointers and one descriptor struct */
2274 po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK|M_ZERO);
2276 LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
2278 TAILQ_INIT(&po->po_logbuffers);
2279 mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
2281 PMCDBG4(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
2282 p, p->p_pid, p->p_comm, po);
2288 pmc_destroy_owner_descriptor(struct pmc_owner *po)
2291 PMCDBG4(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
2292 po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
2294 mtx_destroy(&po->po_mtx);
2299 * Allocate a thread descriptor from the free pool.
2301 * NOTE: This *can* return NULL.
2303 static struct pmc_thread *
2304 pmc_thread_descriptor_pool_alloc(void)
2306 struct pmc_thread *pt;
2308 mtx_lock_spin(&pmc_threadfreelist_mtx);
2309 if ((pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
2310 LIST_REMOVE(pt, pt_next);
2311 pmc_threadfreelist_entries--;
2313 mtx_unlock_spin(&pmc_threadfreelist_mtx);
2319 * Add a thread descriptor to the free pool. We use this instead of free()
2320 * to maintain a cache of free entries. Additionally, we can safely call
2321 * this function when we cannot call free(), such as in a critical section.
2325 pmc_thread_descriptor_pool_free(struct pmc_thread *pt)
2331 memset(pt, 0, THREADENTRY_SIZE);
2332 mtx_lock_spin(&pmc_threadfreelist_mtx);
2333 LIST_INSERT_HEAD(&pmc_threadfreelist, pt, pt_next);
2334 pmc_threadfreelist_entries++;
2335 if (pmc_threadfreelist_entries > pmc_threadfreelist_max)
2336 GROUPTASK_ENQUEUE(&free_gtask);
2337 mtx_unlock_spin(&pmc_threadfreelist_mtx);
2341 * A callout to manage the free list.
2344 pmc_thread_descriptor_pool_free_task(void *arg __unused)
2346 struct pmc_thread *pt;
2347 LIST_HEAD(, pmc_thread) tmplist;
2350 LIST_INIT(&tmplist);
2351 /* Determine what changes, if any, we need to make. */
2352 mtx_lock_spin(&pmc_threadfreelist_mtx);
2353 delta = pmc_threadfreelist_entries - pmc_threadfreelist_max;
2355 (pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
2357 LIST_REMOVE(pt, pt_next);
2358 LIST_INSERT_HEAD(&tmplist, pt, pt_next);
2360 mtx_unlock_spin(&pmc_threadfreelist_mtx);
2362 /* If there are entries to free, free them. */
2363 while (!LIST_EMPTY(&tmplist)) {
2364 pt = LIST_FIRST(&tmplist);
2365 LIST_REMOVE(pt, pt_next);
2371 * Drain the thread free pool, freeing all allocations.
2374 pmc_thread_descriptor_pool_drain()
2376 struct pmc_thread *pt, *next;
2378 LIST_FOREACH_SAFE(pt, &pmc_threadfreelist, pt_next, next) {
2379 LIST_REMOVE(pt, pt_next);
2385 * find the descriptor corresponding to thread 'td', adding or removing it
2386 * as specified by 'mode'.
2388 * Note that this supports additional mode flags in addition to those
2389 * supported by pmc_find_process_descriptor():
2390 * PMC_FLAG_NOWAIT: Causes the function to not wait for mallocs.
2391 * This makes it safe to call while holding certain other locks.
2394 static struct pmc_thread *
2395 pmc_find_thread_descriptor(struct pmc_process *pp, struct thread *td,
2398 struct pmc_thread *pt = NULL, *ptnew = NULL;
2401 KASSERT(td != NULL, ("[pmc,%d] called to add NULL td", __LINE__));
2404 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case prior to
2405 * acquiring the lock.
2407 if (mode & PMC_FLAG_ALLOCATE) {
2408 if ((ptnew = pmc_thread_descriptor_pool_alloc()) == NULL) {
2409 wait_flag = M_WAITOK;
2410 if ((mode & PMC_FLAG_NOWAIT) || in_epoch())
2411 wait_flag = M_NOWAIT;
2413 ptnew = malloc(THREADENTRY_SIZE, M_PMC,
2418 mtx_lock_spin(pp->pp_tdslock);
2420 LIST_FOREACH(pt, &pp->pp_tds, pt_next)
2421 if (pt->pt_td == td)
2424 if ((mode & PMC_FLAG_REMOVE) && pt != NULL)
2425 LIST_REMOVE(pt, pt_next);
2427 if ((mode & PMC_FLAG_ALLOCATE) && pt == NULL && ptnew != NULL) {
2431 LIST_INSERT_HEAD(&pp->pp_tds, pt, pt_next);
2434 mtx_unlock_spin(pp->pp_tdslock);
2436 if (ptnew != NULL) {
2444 * Try to add thread descriptors for each thread in a process.
2448 pmc_add_thread_descriptors_from_proc(struct proc *p, struct pmc_process *pp)
2450 struct thread *curtd;
2451 struct pmc_thread **tdlist;
2452 int i, tdcnt, tdlistsz;
2454 KASSERT(!PROC_LOCKED(p), ("[pmc,%d] proc unexpectedly locked",
2458 tdlistsz = roundup2(tdcnt, 32);
2461 tdlist = malloc(sizeof(struct pmc_thread*) * tdlistsz, M_TEMP, M_WAITOK);
2464 FOREACH_THREAD_IN_PROC(p, curtd)
2466 if (tdcnt >= tdlistsz) {
2468 free(tdlist, M_TEMP);
2472 * Try to add each thread to the list without sleeping. If unable,
2473 * add to a queue to retry after dropping the process lock.
2476 FOREACH_THREAD_IN_PROC(p, curtd) {
2477 tdlist[tdcnt] = pmc_find_thread_descriptor(pp, curtd,
2478 PMC_FLAG_ALLOCATE|PMC_FLAG_NOWAIT);
2479 if (tdlist[tdcnt] == NULL) {
2481 for (i = 0; i <= tdcnt; i++)
2482 pmc_thread_descriptor_pool_free(tdlist[i]);
2483 free(tdlist, M_TEMP);
2489 free(tdlist, M_TEMP);
2493 * find the descriptor corresponding to process 'p', adding or removing it
2494 * as specified by 'mode'.
2497 static struct pmc_process *
2498 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
2501 struct pmc_process *pp, *ppnew;
2502 struct pmc_processhash *pph;
2504 hindex = PMC_HASH_PTR(p, pmc_processhashmask);
2505 pph = &pmc_processhash[hindex];
2510 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case since we
2511 * cannot call malloc(9) once we hold a spin lock.
2513 if (mode & PMC_FLAG_ALLOCATE)
2514 ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
2515 sizeof(struct pmc_targetstate), M_PMC, M_WAITOK|M_ZERO);
2517 mtx_lock_spin(&pmc_processhash_mtx);
2518 LIST_FOREACH(pp, pph, pp_next)
2519 if (pp->pp_proc == p)
2522 if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
2523 LIST_REMOVE(pp, pp_next);
2525 if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
2528 LIST_INIT(&ppnew->pp_tds);
2529 ppnew->pp_tdslock = mtx_pool_find(pmc_mtxpool, ppnew);
2530 LIST_INSERT_HEAD(pph, ppnew, pp_next);
2531 mtx_unlock_spin(&pmc_processhash_mtx);
2535 /* Add thread descriptors for this process' current threads. */
2536 pmc_add_thread_descriptors_from_proc(p, pp);
2539 mtx_unlock_spin(&pmc_processhash_mtx);
2548 * remove a process descriptor from the process hash table.
2552 pmc_remove_process_descriptor(struct pmc_process *pp)
2554 KASSERT(pp->pp_refcnt == 0,
2555 ("[pmc,%d] Removing process descriptor %p with count %d",
2556 __LINE__, pp, pp->pp_refcnt));
2558 mtx_lock_spin(&pmc_processhash_mtx);
2559 LIST_REMOVE(pp, pp_next);
2560 mtx_unlock_spin(&pmc_processhash_mtx);
2564 * destroy a process descriptor.
2568 pmc_destroy_process_descriptor(struct pmc_process *pp)
2570 struct pmc_thread *pmc_td;
2572 while ((pmc_td = LIST_FIRST(&pp->pp_tds)) != NULL) {
2573 LIST_REMOVE(pmc_td, pt_next);
2574 pmc_thread_descriptor_pool_free(pmc_td);
2581 * find an owner descriptor corresponding to proc 'p'
2584 static struct pmc_owner *
2585 pmc_find_owner_descriptor(struct proc *p)
2588 struct pmc_owner *po;
2589 struct pmc_ownerhash *poh;
2591 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2592 poh = &pmc_ownerhash[hindex];
2595 LIST_FOREACH(po, poh, po_next)
2596 if (po->po_owner == p)
2599 PMCDBG5(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2600 "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2606 * pmc_allocate_pmc_descriptor
2608 * Allocate a pmc descriptor and initialize its
2613 pmc_allocate_pmc_descriptor(void)
2617 pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK|M_ZERO);
2618 pmc->pm_runcount = counter_u64_alloc(M_WAITOK);
2619 pmc->pm_pcpu_state = malloc(sizeof(struct pmc_pcpu_state)*mp_ncpus, M_PMC, M_WAITOK|M_ZERO);
2620 PMCDBG1(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2626 * Destroy a pmc descriptor.
2630 pmc_destroy_pmc_descriptor(struct pmc *pm)
2633 KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2634 pm->pm_state == PMC_STATE_FREE,
2635 ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2636 KASSERT(LIST_EMPTY(&pm->pm_targets),
2637 ("[pmc,%d] destroying pmc with targets", __LINE__));
2638 KASSERT(pm->pm_owner == NULL,
2639 ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2640 KASSERT(counter_u64_fetch(pm->pm_runcount) == 0,
2641 ("[pmc,%d] pmc has non-zero run count %ld", __LINE__,
2642 (unsigned long)counter_u64_fetch(pm->pm_runcount)));
2644 counter_u64_free(pm->pm_runcount);
2645 free(pm->pm_pcpu_state, M_PMC);
2650 pmc_wait_for_pmc_idle(struct pmc *pm)
2653 volatile int maxloop;
2655 maxloop = 100 * pmc_cpu_max();
2658 * Loop (with a forced context switch) till the PMC's runcount
2659 * comes down to zero.
2661 while (counter_u64_fetch(pm->pm_runcount) > 0) {
2664 KASSERT(maxloop > 0,
2665 ("[pmc,%d] (ri%d, rc%ld) waiting too long for "
2666 "pmc to be free", __LINE__,
2667 PMC_TO_ROWINDEX(pm), (unsigned long)counter_u64_fetch(pm->pm_runcount)));
2669 pmc_force_context_switch();
2674 * This function does the following things:
2676 * - detaches the PMC from hardware
2677 * - unlinks all target threads that were attached to it
2678 * - removes the PMC from its owner's list
2679 * - destroys the PMC private mutex
2681 * Once this function completes, the given pmc pointer can be freed by
2682 * calling pmc_destroy_pmc_descriptor().
2686 pmc_release_pmc_descriptor(struct pmc *pm)
2690 u_int adjri, ri, cpu;
2691 struct pmc_owner *po;
2692 struct pmc_binding pb;
2693 struct pmc_process *pp;
2694 struct pmc_classdep *pcd;
2695 struct pmc_target *ptgt, *tmp;
2697 sx_assert(&pmc_sx, SX_XLOCKED);
2699 KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2701 ri = PMC_TO_ROWINDEX(pm);
2702 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2703 mode = PMC_TO_MODE(pm);
2705 PMCDBG3(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2709 * First, we take the PMC off hardware.
2712 if (PMC_IS_SYSTEM_MODE(mode)) {
2715 * A system mode PMC runs on a specific CPU. Switch
2716 * to this CPU and turn hardware off.
2718 pmc_save_cpu_binding(&pb);
2720 cpu = PMC_TO_CPU(pm);
2722 pmc_select_cpu(cpu);
2724 /* switch off non-stalled CPUs */
2725 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
2726 if (pm->pm_state == PMC_STATE_RUNNING &&
2727 pm->pm_pcpu_state[cpu].pps_stalled == 0) {
2729 phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2731 KASSERT(phw->phw_pmc == pm,
2732 ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2733 __LINE__, ri, phw->phw_pmc, pm));
2734 PMCDBG2(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2737 pcd->pcd_stop_pmc(cpu, adjri);
2741 PMCDBG2(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2744 pcd->pcd_config_pmc(cpu, adjri, NULL);
2747 /* adjust the global and process count of SS mode PMCs */
2748 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2751 if (po->po_sscount == 0) {
2752 atomic_subtract_rel_int(&pmc_ss_count, 1);
2753 CK_LIST_REMOVE(po, po_ssnext);
2754 epoch_wait_preempt(global_epoch_preempt);
2758 pm->pm_state = PMC_STATE_DELETED;
2760 pmc_restore_cpu_binding(&pb);
2763 * We could have references to this PMC structure in
2764 * the per-cpu sample queues. Wait for the queue to
2767 pmc_wait_for_pmc_idle(pm);
2769 } else if (PMC_IS_VIRTUAL_MODE(mode)) {
2772 * A virtual PMC could be running on multiple CPUs at
2775 * By marking its state as DELETED, we ensure that
2776 * this PMC is never further scheduled on hardware.
2778 * Then we wait till all CPUs are done with this PMC.
2780 pm->pm_state = PMC_STATE_DELETED;
2783 /* Wait for the PMCs runcount to come to zero. */
2784 pmc_wait_for_pmc_idle(pm);
2787 * At this point the PMC is off all CPUs and cannot be
2788 * freshly scheduled onto a CPU. It is now safe to
2789 * unlink all targets from this PMC. If a
2790 * process-record's refcount falls to zero, we remove
2791 * it from the hash table. The module-wide SX lock
2792 * protects us from races.
2794 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2795 pp = ptgt->pt_process;
2796 pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2798 PMCDBG1(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2801 * If the target process record shows that no
2802 * PMCs are attached to it, reclaim its space.
2805 if (pp->pp_refcnt == 0) {
2806 pmc_remove_process_descriptor(pp);
2807 pmc_destroy_process_descriptor(pp);
2811 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2816 * Release any MD resources
2818 (void) pcd->pcd_release_pmc(cpu, adjri, pm);
2821 * Update row disposition
2824 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2825 PMC_UNMARK_ROW_STANDALONE(ri);
2827 PMC_UNMARK_ROW_THREAD(ri);
2829 /* unlink from the owner's list */
2831 LIST_REMOVE(pm, pm_next);
2832 pm->pm_owner = NULL;
2837 * Register an owner and a pmc.
2841 pmc_register_owner(struct proc *p, struct pmc *pmc)
2843 struct pmc_owner *po;
2845 sx_assert(&pmc_sx, SX_XLOCKED);
2847 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2848 if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2851 KASSERT(pmc->pm_owner == NULL,
2852 ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2855 LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2858 p->p_flag |= P_HWPMC;
2861 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2862 pmclog_process_pmcallocate(pmc);
2864 PMCDBG2(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2871 * Return the current row disposition:
2873 * > 0 => PROCESS MODE
2874 * < 0 => SYSTEM MODE
2878 pmc_getrowdisp(int ri)
2880 return pmc_pmcdisp[ri];
2884 * Check if a PMC at row index 'ri' can be allocated to the current
2887 * Allocation can fail if:
2888 * - the current process is already being profiled by a PMC at index 'ri',
2889 * attached to it via OP_PMCATTACH.
2890 * - the current process has already allocated a PMC at index 'ri'
2895 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2899 struct pmc_owner *po;
2900 struct pmc_process *pp;
2902 PMCDBG5(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2903 "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2906 * We shouldn't have already allocated a process-mode PMC at
2909 * We shouldn't have allocated a system-wide PMC on the same
2912 if ((po = pmc_find_owner_descriptor(p)) != NULL)
2913 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2914 if (PMC_TO_ROWINDEX(pm) == ri) {
2915 mode = PMC_TO_MODE(pm);
2916 if (PMC_IS_VIRTUAL_MODE(mode))
2918 if (PMC_IS_SYSTEM_MODE(mode) &&
2919 (int) PMC_TO_CPU(pm) == cpu)
2925 * We also shouldn't be the target of any PMC at this index
2926 * since otherwise a PMC_ATTACH to ourselves will fail.
2928 if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2929 if (pp->pp_pmcs[ri].pp_pmc)
2932 PMCDBG4(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2933 p, p->p_pid, p->p_comm, ri);
2939 * Check if a given PMC at row index 'ri' can be currently used in
2944 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2948 sx_assert(&pmc_sx, SX_XLOCKED);
2950 PMCDBG2(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2952 if (PMC_IS_SYSTEM_MODE(mode))
2953 disp = PMC_DISP_STANDALONE;
2955 disp = PMC_DISP_THREAD;
2958 * check disposition for PMC row 'ri':
2960 * Expected disposition Row-disposition Result
2962 * STANDALONE STANDALONE or FREE proceed
2963 * STANDALONE THREAD fail
2964 * THREAD THREAD or FREE proceed
2965 * THREAD STANDALONE fail
2968 if (!PMC_ROW_DISP_IS_FREE(ri) &&
2969 !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2970 !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2977 PMCDBG2(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2984 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2988 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2992 KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2993 ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2994 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2996 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2997 if (pm->pm_id == pmcid)
3004 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
3007 struct pmc *pm, *opm;
3008 struct pmc_owner *po;
3009 struct pmc_process *pp;
3011 PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid);
3012 if (PMC_ID_TO_ROWINDEX(pmcid) >= md->pmd_npmc)
3015 if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL) {
3017 * In case of PMC_F_DESCENDANTS child processes we will not find
3018 * the current process in the owners hash list. Find the owner
3019 * process first and from there lookup the po.
3021 if ((pp = pmc_find_process_descriptor(curthread->td_proc,
3022 PMC_FLAG_NONE)) == NULL) {
3025 opm = pp->pp_pmcs[PMC_ID_TO_ROWINDEX(pmcid)].pp_pmc;
3028 if ((opm->pm_flags & (PMC_F_ATTACHED_TO_OWNER|
3029 PMC_F_DESCENDANTS)) != (PMC_F_ATTACHED_TO_OWNER|
3036 if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
3039 PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
3050 pmc_start(struct pmc *pm)
3053 struct pmc_owner *po;
3054 struct pmc_binding pb;
3055 struct pmc_classdep *pcd;
3056 int adjri, error, cpu, ri;
3059 ("[pmc,%d] null pm", __LINE__));
3061 mode = PMC_TO_MODE(pm);
3062 ri = PMC_TO_ROWINDEX(pm);
3063 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3067 PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
3072 * Disallow PMCSTART if a logfile is required but has not been
3075 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
3076 (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
3077 return (EDOOFUS); /* programming error */
3080 * If this is a sampling mode PMC, log mapping information for
3081 * the kernel modules that are currently loaded.
3083 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3084 pmc_log_kernel_mappings(pm);
3086 if (PMC_IS_VIRTUAL_MODE(mode)) {
3089 * If a PMCATTACH has never been done on this PMC,
3090 * attach it to its owner process.
3093 if (LIST_EMPTY(&pm->pm_targets))
3094 error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
3095 pmc_attach_process(po->po_owner, pm);
3098 * If the PMC is attached to its owner, then force a context
3099 * switch to ensure that the MD state gets set correctly.
3103 pm->pm_state = PMC_STATE_RUNNING;
3104 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
3105 pmc_force_context_switch();
3113 * A system-wide PMC.
3115 * Add the owner to the global list if this is a system-wide
3119 if (mode == PMC_MODE_SS) {
3121 * Log mapping information for all existing processes in the
3122 * system. Subsequent mappings are logged as they happen;
3123 * see pmc_process_mmap().
3125 if (po->po_logprocmaps == 0) {
3126 pmc_log_all_process_mappings(po);
3127 po->po_logprocmaps = 1;
3130 if (po->po_sscount == 1) {
3131 atomic_add_rel_int(&pmc_ss_count, 1);
3132 CK_LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
3133 PMCDBG1(PMC,OPS,1, "po=%p in global list", po);
3138 * Move to the CPU associated with this
3139 * PMC, and start the hardware.
3142 pmc_save_cpu_binding(&pb);
3144 cpu = PMC_TO_CPU(pm);
3146 if (!pmc_cpu_is_active(cpu))
3149 pmc_select_cpu(cpu);
3152 * global PMCs are configured at allocation time
3153 * so write out the initial value and start the PMC.
3156 pm->pm_state = PMC_STATE_RUNNING;
3159 if ((error = pcd->pcd_write_pmc(cpu, adjri,
3160 PMC_IS_SAMPLING_MODE(mode) ?
3161 pm->pm_sc.pm_reloadcount :
3162 pm->pm_sc.pm_initial)) == 0) {
3163 /* If a sampling mode PMC, reset stalled state. */
3164 if (PMC_IS_SAMPLING_MODE(mode))
3165 pm->pm_pcpu_state[cpu].pps_stalled = 0;
3167 /* Indicate that we desire this to run. Start it. */
3168 pm->pm_pcpu_state[cpu].pps_cpustate = 1;
3169 error = pcd->pcd_start_pmc(cpu, adjri);
3173 pmc_restore_cpu_binding(&pb);
3183 pmc_stop(struct pmc *pm)
3185 struct pmc_owner *po;
3186 struct pmc_binding pb;
3187 struct pmc_classdep *pcd;
3188 int adjri, cpu, error, ri;
3190 KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
3192 PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
3193 PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
3195 pm->pm_state = PMC_STATE_STOPPED;
3198 * If the PMC is a virtual mode one, changing the state to
3199 * non-RUNNING is enough to ensure that the PMC never gets
3202 * If this PMC is current running on a CPU, then it will
3203 * handled correctly at the time its target process is context
3207 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
3211 * A system-mode PMC. Move to the CPU associated with
3212 * this PMC, and stop the hardware. We update the
3213 * 'initial count' so that a subsequent PMCSTART will
3214 * resume counting from the current hardware count.
3217 pmc_save_cpu_binding(&pb);
3219 cpu = PMC_TO_CPU(pm);
3221 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
3222 ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
3224 if (!pmc_cpu_is_active(cpu))
3227 pmc_select_cpu(cpu);
3229 ri = PMC_TO_ROWINDEX(pm);
3230 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3232 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
3234 if ((error = pcd->pcd_stop_pmc(cpu, adjri)) == 0)
3235 error = pcd->pcd_read_pmc(cpu, adjri, &pm->pm_sc.pm_initial);
3238 pmc_restore_cpu_binding(&pb);
3242 /* remove this owner from the global list of SS PMC owners */
3243 if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
3245 if (po->po_sscount == 0) {
3246 atomic_subtract_rel_int(&pmc_ss_count, 1);
3247 CK_LIST_REMOVE(po, po_ssnext);
3248 epoch_wait_preempt(global_epoch_preempt);
3249 PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po);
3256 static struct pmc_classdep *
3257 pmc_class_to_classdep(enum pmc_class class)
3261 for (n = 0; n < md->pmd_nclass; n++)
3262 if (md->pmd_classdep[n].pcd_class == class)
3263 return (&md->pmd_classdep[n]);
3268 static const char *pmc_op_to_name[] = {
3270 #define __PMC_OP(N, D) #N ,
3277 * The syscall interface
3280 #define PMC_GET_SX_XLOCK(...) do { \
3281 sx_xlock(&pmc_sx); \
3282 if (pmc_hook == NULL) { \
3283 sx_xunlock(&pmc_sx); \
3284 return __VA_ARGS__; \
3288 #define PMC_DOWNGRADE_SX() do { \
3289 sx_downgrade(&pmc_sx); \
3290 is_sx_downgraded = 1; \
3294 pmc_syscall_handler(struct thread *td, void *syscall_args)
3296 int error, is_sx_downgraded, op;
3297 struct pmc_syscall_args *c;
3298 void *pmclog_proc_handle;
3301 c = (struct pmc_syscall_args *)syscall_args;
3304 /* PMC isn't set up yet */
3305 if (pmc_hook == NULL)
3307 if (op == PMC_OP_CONFIGURELOG) {
3309 * We cannot create the logging process inside
3310 * pmclog_configure_log() because there is a LOR
3311 * between pmc_sx and process structure locks.
3312 * Instead, pre-create the process and ignite the loop
3313 * if everything is fine, otherwise direct the process
3316 error = pmclog_proc_create(td, &pmclog_proc_handle);
3321 PMC_GET_SX_XLOCK(ENOSYS);
3322 is_sx_downgraded = 0;
3323 PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
3324 pmc_op_to_name[op], arg);
3327 counter_u64_add(pmc_stats.pm_syscalls, 1);
3333 * Configure a log file.
3335 * XXX This OP will be reworked.
3338 case PMC_OP_CONFIGURELOG:
3342 struct pmc_owner *po;
3343 struct pmc_op_configurelog cl;
3345 if ((error = copyin(arg, &cl, sizeof(cl))) != 0) {
3346 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3350 /* mark this process as owning a log file */
3352 if ((po = pmc_find_owner_descriptor(p)) == NULL)
3353 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
3354 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3360 * If a valid fd was passed in, try to configure that,
3361 * otherwise if 'fd' was less than zero and there was
3362 * a log file configured, flush its buffers and
3365 if (cl.pm_logfd >= 0) {
3366 error = pmclog_configure_log(md, po, cl.pm_logfd);
3367 pmclog_proc_ignite(pmclog_proc_handle, error == 0 ?
3369 } else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
3370 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3371 error = pmclog_close(po);
3373 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
3374 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
3375 pm->pm_state == PMC_STATE_RUNNING)
3377 error = pmclog_deconfigure_log(po);
3380 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3390 case PMC_OP_FLUSHLOG:
3392 struct pmc_owner *po;
3394 sx_assert(&pmc_sx, SX_XLOCKED);
3396 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3401 error = pmclog_flush(po);
3409 case PMC_OP_CLOSELOG:
3411 struct pmc_owner *po;
3413 sx_assert(&pmc_sx, SX_XLOCKED);
3415 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3420 error = pmclog_close(po);
3425 * Retrieve hardware configuration.
3428 case PMC_OP_GETCPUINFO: /* CPU information */
3430 struct pmc_op_getcpuinfo gci;
3431 struct pmc_classinfo *pci;
3432 struct pmc_classdep *pcd;
3435 gci.pm_cputype = md->pmd_cputype;
3436 gci.pm_ncpu = pmc_cpu_max();
3437 gci.pm_npmc = md->pmd_npmc;
3438 gci.pm_nclass = md->pmd_nclass;
3439 pci = gci.pm_classes;
3440 pcd = md->pmd_classdep;
3441 for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
3442 pci->pm_caps = pcd->pcd_caps;
3443 pci->pm_class = pcd->pcd_class;
3444 pci->pm_width = pcd->pcd_width;
3445 pci->pm_num = pcd->pcd_num;
3447 error = copyout(&gci, arg, sizeof(gci));
3452 * Retrieve soft events list.
3454 case PMC_OP_GETDYNEVENTINFO:
3458 struct pmc_op_getdyneventinfo *gei;
3459 struct pmc_dyn_event_descr dev;
3460 struct pmc_soft *ps;
3463 sx_assert(&pmc_sx, SX_LOCKED);
3465 gei = (struct pmc_op_getdyneventinfo *) arg;
3467 if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
3470 /* Only SOFT class is dynamic. */
3471 if (cl != PMC_CLASS_SOFT) {
3477 for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) {
3478 ps = pmc_soft_ev_acquire(ev);
3481 bcopy(&ps->ps_ev, &dev, sizeof(dev));
3482 pmc_soft_ev_release(ps);
3484 error = copyout(&dev,
3485 &gei->pm_events[nevent],
3486 sizeof(struct pmc_dyn_event_descr));
3494 error = copyout(&nevent, &gei->pm_nevent,
3500 * Get module statistics
3503 case PMC_OP_GETDRIVERSTATS:
3505 struct pmc_op_getdriverstats gms;
3506 #define CFETCH(a, b, field) a.field = counter_u64_fetch(b.field)
3507 CFETCH(gms, pmc_stats, pm_intr_ignored);
3508 CFETCH(gms, pmc_stats, pm_intr_processed);
3509 CFETCH(gms, pmc_stats, pm_intr_bufferfull);
3510 CFETCH(gms, pmc_stats, pm_syscalls);
3511 CFETCH(gms, pmc_stats, pm_syscall_errors);
3512 CFETCH(gms, pmc_stats, pm_buffer_requests);
3513 CFETCH(gms, pmc_stats, pm_buffer_requests_failed);
3514 CFETCH(gms, pmc_stats, pm_log_sweeps);
3516 error = copyout(&gms, arg, sizeof(gms));
3522 * Retrieve module version number
3525 case PMC_OP_GETMODULEVERSION:
3529 /* retrieve the client's idea of the ABI version */
3530 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
3532 /* don't service clients newer than our driver */
3534 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
3535 error = EPROGMISMATCH;
3538 error = copyout(&modv, arg, sizeof(int));
3544 * Retrieve the state of all the PMCs on a given
3548 case PMC_OP_GETPMCINFO:
3552 size_t pmcinfo_size;
3553 uint32_t cpu, n, npmc;
3554 struct pmc_owner *po;
3555 struct pmc_binding pb;
3556 struct pmc_classdep *pcd;
3557 struct pmc_info *p, *pmcinfo;
3558 struct pmc_op_getpmcinfo *gpi;
3562 gpi = (struct pmc_op_getpmcinfo *) arg;
3564 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
3567 if (cpu >= pmc_cpu_max()) {
3572 if (!pmc_cpu_is_active(cpu)) {
3577 /* switch to CPU 'cpu' */
3578 pmc_save_cpu_binding(&pb);
3579 pmc_select_cpu(cpu);
3581 npmc = md->pmd_npmc;
3583 pmcinfo_size = npmc * sizeof(struct pmc_info);
3584 pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK);
3588 for (n = 0; n < md->pmd_npmc; n++, p++) {
3590 pcd = pmc_ri_to_classdep(md, n, &ari);
3592 KASSERT(pcd != NULL,
3593 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
3595 if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
3598 if (PMC_ROW_DISP_IS_STANDALONE(n))
3599 p->pm_rowdisp = PMC_DISP_STANDALONE;
3600 else if (PMC_ROW_DISP_IS_THREAD(n))
3601 p->pm_rowdisp = PMC_DISP_THREAD;
3603 p->pm_rowdisp = PMC_DISP_FREE;
3605 p->pm_ownerpid = -1;
3607 if (pm == NULL) /* no PMC associated */
3612 KASSERT(po->po_owner != NULL,
3613 ("[pmc,%d] pmc_owner had a null proc pointer",
3616 p->pm_ownerpid = po->po_owner->p_pid;
3617 p->pm_mode = PMC_TO_MODE(pm);
3618 p->pm_event = pm->pm_event;
3619 p->pm_flags = pm->pm_flags;
3621 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3623 pm->pm_sc.pm_reloadcount;
3626 pmc_restore_cpu_binding(&pb);
3628 /* now copy out the PMC info collected */
3630 error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
3632 free(pmcinfo, M_PMC);
3638 * Set the administrative state of a PMC. I.e. whether
3639 * the PMC is to be used or not.
3642 case PMC_OP_PMCADMIN:
3645 enum pmc_state request;
3648 struct pmc_op_pmcadmin pma;
3649 struct pmc_binding pb;
3651 sx_assert(&pmc_sx, SX_XLOCKED);
3653 KASSERT(td == curthread,
3654 ("[pmc,%d] td != curthread", __LINE__));
3656 error = priv_check(td, PRIV_PMC_MANAGE);
3660 if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
3665 if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
3670 if (!pmc_cpu_is_active(cpu)) {
3675 request = pma.pm_state;
3677 if (request != PMC_STATE_DISABLED &&
3678 request != PMC_STATE_FREE) {
3683 ri = pma.pm_pmc; /* pmc id == row index */
3684 if (ri < 0 || ri >= (int) md->pmd_npmc) {
3690 * We can't disable a PMC with a row-index allocated
3691 * for process virtual PMCs.
3694 if (PMC_ROW_DISP_IS_THREAD(ri) &&
3695 request == PMC_STATE_DISABLED) {
3701 * otherwise, this PMC on this CPU is either free or
3702 * in system-wide mode.
3705 pmc_save_cpu_binding(&pb);
3706 pmc_select_cpu(cpu);
3709 phw = pc->pc_hwpmcs[ri];
3712 * XXX do we need some kind of 'forced' disable?
3715 if (phw->phw_pmc == NULL) {
3716 if (request == PMC_STATE_DISABLED &&
3717 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
3718 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
3719 PMC_MARK_ROW_STANDALONE(ri);
3720 } else if (request == PMC_STATE_FREE &&
3721 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
3722 phw->phw_state |= PMC_PHW_FLAG_IS_ENABLED;
3723 PMC_UNMARK_ROW_STANDALONE(ri);
3725 /* other cases are a no-op */
3729 pmc_restore_cpu_binding(&pb);
3738 case PMC_OP_PMCALLOCATE:
3746 struct pmc_binding pb;
3747 struct pmc_classdep *pcd;
3748 struct pmc_op_pmcallocate pa;
3750 if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
3757 if ((mode != PMC_MODE_SS && mode != PMC_MODE_SC &&
3758 mode != PMC_MODE_TS && mode != PMC_MODE_TC) ||
3759 (cpu != (u_int) PMC_CPU_ANY && cpu >= pmc_cpu_max())) {
3765 * Virtual PMCs should only ask for a default CPU.
3766 * System mode PMCs need to specify a non-default CPU.
3769 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
3770 (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
3776 * Check that an inactive CPU is not being asked for.
3779 if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) {
3785 * Refuse an allocation for a system-wide PMC if this
3786 * process has been jailed, or if this process lacks
3787 * super-user credentials and the sysctl tunable
3788 * 'security.bsd.unprivileged_syspmcs' is zero.
3791 if (PMC_IS_SYSTEM_MODE(mode)) {
3792 if (jailed(curthread->td_ucred)) {
3796 if (!pmc_unprivileged_syspmcs) {
3797 error = priv_check(curthread,
3805 * Look for valid values for 'pm_flags'
3808 if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3809 PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN)) != 0) {
3814 /* process logging options are not allowed for system PMCs */
3815 if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
3816 (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
3822 * All sampling mode PMCs need to be able to interrupt the
3825 if (PMC_IS_SAMPLING_MODE(mode))
3826 caps |= PMC_CAP_INTERRUPT;
3828 /* A valid class specifier should have been passed in. */
3829 pcd = pmc_class_to_classdep(pa.pm_class);
3835 /* The requested PMC capabilities should be feasible. */
3836 if ((pcd->pcd_caps & caps) != caps) {
3841 PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
3842 pa.pm_ev, caps, mode, cpu);
3844 pmc = pmc_allocate_pmc_descriptor();
3845 pmc->pm_id = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
3847 pmc->pm_event = pa.pm_ev;
3848 pmc->pm_state = PMC_STATE_FREE;
3849 pmc->pm_caps = caps;
3850 pmc->pm_flags = pa.pm_flags;
3852 /* switch thread to CPU 'cpu' */
3853 pmc_save_cpu_binding(&pb);
3855 #define PMC_IS_SHAREABLE_PMC(cpu, n) \
3856 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state & \
3857 PMC_PHW_FLAG_IS_SHAREABLE)
3858 #define PMC_IS_UNALLOCATED(cpu, n) \
3859 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3861 if (PMC_IS_SYSTEM_MODE(mode)) {
3862 pmc_select_cpu(cpu);
3863 for (n = pcd->pcd_ri; n < (int) md->pmd_npmc; n++) {
3864 pcd = pmc_ri_to_classdep(md, n, &adjri);
3865 if (pmc_can_allocate_row(n, mode) == 0 &&
3866 pmc_can_allocate_rowindex(
3867 curthread->td_proc, n, cpu) == 0 &&
3868 (PMC_IS_UNALLOCATED(cpu, n) ||
3869 PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3870 pcd->pcd_allocate_pmc(cpu, adjri, pmc,
3875 /* Process virtual mode */
3876 for (n = pcd->pcd_ri; n < (int) md->pmd_npmc; n++) {
3877 pcd = pmc_ri_to_classdep(md, n, &adjri);
3878 if (pmc_can_allocate_row(n, mode) == 0 &&
3879 pmc_can_allocate_rowindex(
3880 curthread->td_proc, n,
3881 PMC_CPU_ANY) == 0 &&
3882 pcd->pcd_allocate_pmc(curthread->td_oncpu,
3883 adjri, pmc, &pa) == 0)
3888 #undef PMC_IS_UNALLOCATED
3889 #undef PMC_IS_SHAREABLE_PMC
3891 pmc_restore_cpu_binding(&pb);
3893 if (n == (int) md->pmd_npmc) {
3894 pmc_destroy_pmc_descriptor(pmc);
3900 /* Fill in the correct value in the ID field */
3901 pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3903 PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3904 pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3906 /* Process mode PMCs with logging enabled need log files */
3907 if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3908 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3910 /* All system mode sampling PMCs require a log file */
3911 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3912 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3915 * Configure global pmc's immediately
3918 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3920 pmc_save_cpu_binding(&pb);
3921 pmc_select_cpu(cpu);
3923 phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3924 pcd = pmc_ri_to_classdep(md, n, &adjri);
3926 if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3927 (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3928 (void) pcd->pcd_release_pmc(cpu, adjri, pmc);
3929 pmc_destroy_pmc_descriptor(pmc);
3931 pmc_restore_cpu_binding(&pb);
3936 pmc_restore_cpu_binding(&pb);
3939 pmc->pm_state = PMC_STATE_ALLOCATED;
3940 pmc->pm_class = pa.pm_class;
3943 * mark row disposition
3946 if (PMC_IS_SYSTEM_MODE(mode))
3947 PMC_MARK_ROW_STANDALONE(n);
3949 PMC_MARK_ROW_THREAD(n);
3952 * Register this PMC with the current thread as its owner.
3956 pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3957 pmc_release_pmc_descriptor(pmc);
3958 pmc_destroy_pmc_descriptor(pmc);
3964 * Return the allocated index.
3967 pa.pm_pmcid = pmc->pm_id;
3969 error = copyout(&pa, arg, sizeof(pa));
3975 * Attach a PMC to a process.
3978 case PMC_OP_PMCATTACH:
3982 struct pmc_op_pmcattach a;
3984 sx_assert(&pmc_sx, SX_XLOCKED);
3986 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3992 } else if (a.pm_pid == 0)
3993 a.pm_pid = td->td_proc->p_pid;
3995 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3998 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
4003 /* PMCs may be (re)attached only when allocated or stopped */
4004 if (pm->pm_state == PMC_STATE_RUNNING) {
4007 } else if (pm->pm_state != PMC_STATE_ALLOCATED &&
4008 pm->pm_state != PMC_STATE_STOPPED) {
4014 if ((p = pfind(a.pm_pid)) == NULL) {
4020 * Ignore processes that are working on exiting.
4022 if (p->p_flag & P_WEXIT) {
4024 PROC_UNLOCK(p); /* pfind() returns a locked process */
4029 * we are allowed to attach a PMC to a process if
4032 error = p_candebug(curthread, p);
4037 error = pmc_attach_process(p, pm);
4043 * Detach an attached PMC from a process.
4046 case PMC_OP_PMCDETACH:
4050 struct pmc_op_pmcattach a;
4052 if ((error = copyin(arg, &a, sizeof(a))) != 0)
4058 } else if (a.pm_pid == 0)
4059 a.pm_pid = td->td_proc->p_pid;
4061 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
4064 if ((p = pfind(a.pm_pid)) == NULL) {
4070 * Treat processes that are in the process of exiting
4071 * as if they were not present.
4074 if (p->p_flag & P_WEXIT)
4077 PROC_UNLOCK(p); /* pfind() returns a locked process */
4080 error = pmc_detach_process(p, pm);
4086 * Retrieve the MSR number associated with the counter
4087 * 'pmc_id'. This allows processes to directly use RDPMC
4088 * instructions to read their PMCs, without the overhead of a
4092 case PMC_OP_PMCGETMSR:
4096 struct pmc_target *pt;
4097 struct pmc_op_getmsr gm;
4098 struct pmc_classdep *pcd;
4102 if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
4105 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
4109 * The allocated PMC has to be a process virtual PMC,
4110 * i.e., of type MODE_T[CS]. Global PMCs can only be
4111 * read using the PMCREAD operation since they may be
4112 * allocated on a different CPU than the one we could
4113 * be running on at the time of the RDPMC instruction.
4115 * The GETMSR operation is not allowed for PMCs that
4116 * are inherited across processes.
4119 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
4120 (pm->pm_flags & PMC_F_DESCENDANTS)) {
4126 * It only makes sense to use a RDPMC (or its
4127 * equivalent instruction on non-x86 architectures) on
4128 * a process that has allocated and attached a PMC to
4129 * itself. Conversely the PMC is only allowed to have
4130 * one process attached to it -- its owner.
4133 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
4134 LIST_NEXT(pt, pt_next) != NULL ||
4135 pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
4140 ri = PMC_TO_ROWINDEX(pm);
4141 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4143 /* PMC class has no 'GETMSR' support */
4144 if (pcd->pcd_get_msr == NULL) {
4149 if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
4152 if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
4156 * Mark our process as using MSRs. Update machine
4157 * state using a forced context switch.
4160 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
4161 pmc_force_context_switch();
4167 * Release an allocated PMC
4170 case PMC_OP_PMCRELEASE:
4174 struct pmc_owner *po;
4175 struct pmc_op_simple sp;
4178 * Find PMC pointer for the named PMC.
4180 * Use pmc_release_pmc_descriptor() to switch off the
4181 * PMC, remove all its target threads, and remove the
4182 * PMC from its owner's list.
4184 * Remove the owner record if this is the last PMC
4190 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4193 pmcid = sp.pm_pmcid;
4195 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4199 pmc_release_pmc_descriptor(pm);
4200 pmc_maybe_remove_owner(po);
4201 pmc_destroy_pmc_descriptor(pm);
4207 * Read and/or write a PMC.
4215 pmc_value_t oldvalue;
4216 struct pmc_binding pb;
4217 struct pmc_op_pmcrw prw;
4218 struct pmc_classdep *pcd;
4219 struct pmc_op_pmcrw *pprw;
4223 if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
4227 PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
4230 /* must have at least one flag set */
4231 if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
4236 /* locate pmc descriptor */
4237 if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
4240 /* Can't read a PMC that hasn't been started. */
4241 if (pm->pm_state != PMC_STATE_ALLOCATED &&
4242 pm->pm_state != PMC_STATE_STOPPED &&
4243 pm->pm_state != PMC_STATE_RUNNING) {
4248 /* writing a new value is allowed only for 'STOPPED' pmcs */
4249 if (pm->pm_state == PMC_STATE_RUNNING &&
4250 (prw.pm_flags & PMC_F_NEWVALUE)) {
4255 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
4258 * If this PMC is attached to its owner (i.e.,
4259 * the process requesting this operation) and
4260 * is running, then attempt to get an
4261 * upto-date reading from hardware for a READ.
4262 * Writes are only allowed when the PMC is
4263 * stopped, so only update the saved value
4266 * If the PMC is not running, or is not
4267 * attached to its owner, read/write to the
4271 ri = PMC_TO_ROWINDEX(pm);
4272 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4274 mtx_pool_lock_spin(pmc_mtxpool, pm);
4275 cpu = curthread->td_oncpu;
4277 if (prw.pm_flags & PMC_F_OLDVALUE) {
4278 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
4279 (pm->pm_state == PMC_STATE_RUNNING))
4280 error = (*pcd->pcd_read_pmc)(cpu, adjri,
4283 oldvalue = pm->pm_gv.pm_savedvalue;
4285 if (prw.pm_flags & PMC_F_NEWVALUE)
4286 pm->pm_gv.pm_savedvalue = prw.pm_value;
4288 mtx_pool_unlock_spin(pmc_mtxpool, pm);
4290 } else { /* System mode PMCs */
4291 cpu = PMC_TO_CPU(pm);
4292 ri = PMC_TO_ROWINDEX(pm);
4293 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4295 if (!pmc_cpu_is_active(cpu)) {
4300 /* move this thread to CPU 'cpu' */
4301 pmc_save_cpu_binding(&pb);
4302 pmc_select_cpu(cpu);
4305 /* save old value */
4306 if (prw.pm_flags & PMC_F_OLDVALUE)
4307 if ((error = (*pcd->pcd_read_pmc)(cpu, adjri,
4310 /* write out new value */
4311 if (prw.pm_flags & PMC_F_NEWVALUE)
4312 error = (*pcd->pcd_write_pmc)(cpu, adjri,
4316 pmc_restore_cpu_binding(&pb);
4321 pprw = (struct pmc_op_pmcrw *) arg;
4324 if (prw.pm_flags & PMC_F_NEWVALUE)
4325 PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
4326 ri, prw.pm_value, oldvalue);
4327 else if (prw.pm_flags & PMC_F_OLDVALUE)
4328 PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
4331 /* return old value if requested */
4332 if (prw.pm_flags & PMC_F_OLDVALUE)
4333 if ((error = copyout(&oldvalue, &pprw->pm_value,
4334 sizeof(prw.pm_value))))
4342 * Set the sampling rate for a sampling mode PMC and the
4343 * initial count for a counting mode PMC.
4346 case PMC_OP_PMCSETCOUNT:
4349 struct pmc_op_pmcsetcount sc;
4353 if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
4356 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
4359 if (pm->pm_state == PMC_STATE_RUNNING) {
4364 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
4365 pm->pm_sc.pm_reloadcount = sc.pm_count;
4367 pm->pm_sc.pm_initial = sc.pm_count;
4376 case PMC_OP_PMCSTART:
4380 struct pmc_op_simple sp;
4382 sx_assert(&pmc_sx, SX_XLOCKED);
4384 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4387 pmcid = sp.pm_pmcid;
4389 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4392 KASSERT(pmcid == pm->pm_id,
4393 ("[pmc,%d] pmcid %x != id %x", __LINE__,
4396 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
4398 else if (pm->pm_state != PMC_STATE_STOPPED &&
4399 pm->pm_state != PMC_STATE_ALLOCATED) {
4404 error = pmc_start(pm);
4413 case PMC_OP_PMCSTOP:
4417 struct pmc_op_simple sp;
4421 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4424 pmcid = sp.pm_pmcid;
4427 * Mark the PMC as inactive and invoke the MD stop
4428 * routines if needed.
4431 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4434 KASSERT(pmcid == pm->pm_id,
4435 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
4438 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
4440 else if (pm->pm_state != PMC_STATE_RUNNING) {
4445 error = pmc_stop(pm);
4451 * Write a user supplied value to the log file.
4454 case PMC_OP_WRITELOG:
4456 struct pmc_op_writelog wl;
4457 struct pmc_owner *po;
4461 if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
4464 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
4469 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
4474 error = pmclog_process_userlog(po, &wl);
4484 if (is_sx_downgraded)
4485 sx_sunlock(&pmc_sx);
4487 sx_xunlock(&pmc_sx);
4490 counter_u64_add(pmc_stats.pm_syscall_errors, 1);
4501 * Mark the thread as needing callchain capture and post an AST. The
4502 * actual callchain capture will be done in a context where it is safe
4503 * to take page faults.
4507 pmc_post_callchain_callback(void)
4514 * If there is multiple PMCs for the same interrupt ignore new post
4516 if (td->td_pflags & TDP_CALLCHAIN)
4520 * Mark this thread as needing callchain capture.
4521 * `td->td_pflags' will be safe to touch because this thread
4522 * was in user space when it was interrupted.
4524 td->td_pflags |= TDP_CALLCHAIN;
4527 * Don't let this thread migrate between CPUs until callchain
4528 * capture completes.
4536 * Interrupt processing.
4538 * Find a free slot in the per-cpu array of samples and capture the
4539 * current callchain there. If a sample was successfully added, a bit
4540 * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4541 * needs to be invoked from the clock handler.
4543 * This function is meant to be called from an NMI handler. It cannot
4544 * use any of the locking primitives supplied by the OS.
4548 pmc_process_interrupt(int cpu, int ring, struct pmc *pm, struct trapframe *tf,
4551 int error, callchaindepth;
4553 struct pmc_sample *ps;
4554 struct pmc_samplebuffer *psb;
4559 * Allocate space for a sample buffer.
4561 psb = pmc_pcpu[cpu]->pc_sb[ring];
4564 if (ps->ps_nsamples) { /* in use, reader hasn't caught up */
4565 pm->pm_pcpu_state[cpu].pps_stalled = 1;
4566 counter_u64_add(pmc_stats.pm_intr_bufferfull, 1);
4567 PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
4568 cpu, pm, (void *) tf, inuserspace,
4569 (int) (psb->ps_write - psb->ps_samples),
4570 (int) (psb->ps_read - psb->ps_samples));
4577 /* Fill in entry. */
4578 PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm,
4579 (void *) tf, inuserspace,
4580 (int) (psb->ps_write - psb->ps_samples),
4581 (int) (psb->ps_read - psb->ps_samples));
4583 KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
4584 ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
4585 (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4587 counter_u64_add(pm->pm_runcount, 1); /* hold onto PMC */
4592 if ((td = curthread) != NULL) {
4593 ps->ps_tid = td->td_tid;
4595 ps->ps_pid = td->td_proc->p_pid;
4599 ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4601 callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4602 pmc_callchaindepth : 1;
4604 if (callchaindepth == 1)
4605 ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf);
4608 * Kernel stack traversals can be done immediately,
4609 * while we defer to an AST for user space traversals.
4613 pmc_save_kernel_callchain(ps->ps_pc,
4614 callchaindepth, tf);
4616 pmc_post_callchain_callback();
4617 callchaindepth = PMC_SAMPLE_INUSE;
4621 ps->ps_nsamples = callchaindepth; /* mark entry as in use */
4623 /* increment write pointer, modulo ring buffer size */
4625 if (ps == psb->ps_fence)
4626 psb->ps_write = psb->ps_samples;
4631 /* mark CPU as needing processing */
4632 if (callchaindepth != PMC_SAMPLE_INUSE)
4633 DPCPU_SET(pmc_sampled, 1);
4639 * Capture a user call chain. This function will be called from ast()
4640 * before control returns to userland and before the process gets
4645 pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4649 struct pmc_sample *ps, *ps_end;
4650 struct pmc_samplebuffer *psb;
4656 psb = pmc_pcpu[cpu]->pc_sb[ring];
4659 KASSERT(td->td_pflags & TDP_CALLCHAIN,
4660 ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
4669 * Iterate through all deferred callchain requests.
4670 * Walk from the current read pointer to the current
4675 ps_end = psb->ps_write;
4678 if ((ps->ps_pmc == NULL) ||
4679 (ps->ps_pmc->pm_state != PMC_STATE_RUNNING))
4682 if (ps->ps_nsamples != PMC_SAMPLE_INUSE)
4684 if (ps->ps_td != td)
4687 KASSERT(ps->ps_cpu == cpu,
4688 ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
4689 ps->ps_cpu, PCPU_GET(cpuid)));
4693 KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
4694 ("[pmc,%d] Retrieving callchain for PMC that doesn't "
4695 "want it", __LINE__));
4697 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4698 ("[pmc,%d] runcount %ld", __LINE__, (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4701 * Retrieve the callchain and mark the sample buffer
4702 * as 'processable' by the timer tick sweep code.
4704 ps->ps_nsamples = pmc_save_user_callchain(ps->ps_pc,
4705 pmc_callchaindepth, tf);
4712 /* increment the pointer, modulo sample ring size */
4713 if (++ps == psb->ps_fence)
4714 ps = psb->ps_samples;
4715 } while (ps != ps_end);
4718 KASSERT(ncallchains > 0 || nfree > 0,
4719 ("[pmc,%d] cpu %d didn't find a sample to collect", __LINE__,
4723 KASSERT(td->td_pinned == 1,
4724 ("[pmc,%d] invalid td_pinned value", __LINE__));
4725 sched_unpin(); /* Can migrate safely now. */
4727 /* mark CPU as needing processing */
4728 DPCPU_SET(pmc_sampled, 1);
4732 * Process saved PC samples.
4736 pmc_process_samples(int cpu, int ring)
4741 struct pmc_owner *po;
4742 struct pmc_sample *ps;
4743 struct pmc_classdep *pcd;
4744 struct pmc_samplebuffer *psb;
4746 KASSERT(PCPU_GET(cpuid) == cpu,
4747 ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4748 PCPU_GET(cpuid), cpu));
4750 psb = pmc_pcpu[cpu]->pc_sb[ring];
4752 for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
4755 if (ps->ps_nsamples == PMC_SAMPLE_FREE)
4760 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4761 ("[pmc,%d] pm=%p runcount %ld", __LINE__, (void *) pm,
4762 (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4766 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4767 ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4768 pm, PMC_TO_MODE(pm)));
4770 /* Ignore PMCs that have been switched off */
4771 if (pm->pm_state != PMC_STATE_RUNNING)
4774 /* If there is a pending AST wait for completion */
4775 if (ps->ps_nsamples == PMC_SAMPLE_INUSE) {
4776 /* Need a rescan at a later time. */
4777 DPCPU_SET(pmc_sampled, 1);
4781 PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4782 pm, ps->ps_nsamples, ps->ps_flags,
4783 (int) (psb->ps_write - psb->ps_samples),
4784 (int) (psb->ps_read - psb->ps_samples));
4787 * If this is a process-mode PMC that is attached to
4788 * its owner, and if the PC is in user mode, update
4789 * profiling statistics like timer-based profiling
4792 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
4793 if (ps->ps_flags & PMC_CC_F_USERSPACE) {
4794 td = FIRST_THREAD_IN_PROC(po->po_owner);
4795 addupc_intr(td, ps->ps_pc[0], 1);
4801 * Otherwise, this is either a sampling mode PMC that
4802 * is attached to a different process than its owner,
4803 * or a system-wide sampling PMC. Dispatch a log
4804 * entry to the PMC's owner process.
4806 pmclog_process_callchain(pm, ps);
4809 ps->ps_nsamples = 0; /* mark entry as free */
4810 counter_u64_add(pm->pm_runcount, -1);
4812 /* increment read pointer, modulo sample size */
4813 if (++ps == psb->ps_fence)
4814 psb->ps_read = psb->ps_samples;
4819 counter_u64_add(pmc_stats.pm_log_sweeps, 1);
4821 /* Do not re-enable stalled PMCs if we failed to process any samples */
4826 * Restart any stalled sampling PMCs on this CPU.
4828 * If the NMI handler sets the pm_stalled field of a PMC after
4829 * the check below, we'll end up processing the stalled PMC at
4830 * the next hardclock tick.
4832 for (n = 0; n < md->pmd_npmc; n++) {
4833 pcd = pmc_ri_to_classdep(md, n, &adjri);
4834 KASSERT(pcd != NULL,
4835 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4836 (void) (*pcd->pcd_get_config)(cpu,adjri,&pm);
4838 if (pm == NULL || /* !cfg'ed */
4839 pm->pm_state != PMC_STATE_RUNNING || /* !active */
4840 !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
4841 !pm->pm_pcpu_state[cpu].pps_cpustate || /* !desired */
4842 !pm->pm_pcpu_state[cpu].pps_stalled) /* !stalled */
4845 pm->pm_pcpu_state[cpu].pps_stalled = 0;
4846 (*pcd->pcd_start_pmc)(cpu, adjri);
4855 * Handle a process exit.
4857 * Remove this process from all hash tables. If this process
4858 * owned any PMCs, turn off those PMCs and deallocate them,
4859 * removing any associations with target processes.
4861 * This function will be called by the last 'thread' of a
4864 * XXX This eventhandler gets called early in the exit process.
4865 * Consider using a 'hook' invocation from thread_exit() or equivalent
4866 * spot. Another negative is that kse_exit doesn't seem to call
4872 pmc_process_exit(void *arg __unused, struct proc *p)
4877 int is_using_hwpmcs;
4878 struct pmc_owner *po;
4879 struct pmc_process *pp;
4880 struct pmc_classdep *pcd;
4881 pmc_value_t newvalue, tmp;
4884 is_using_hwpmcs = p->p_flag & P_HWPMC;
4888 * Log a sysexit event to all SS PMC owners.
4890 epoch_enter_preempt(global_epoch_preempt);
4891 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4892 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4893 pmclog_process_sysexit(po, p->p_pid);
4894 epoch_exit_preempt(global_epoch_preempt);
4896 if (!is_using_hwpmcs)
4900 PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
4904 * Since this code is invoked by the last thread in an exiting
4905 * process, we would have context switched IN at some prior
4906 * point. However, with PREEMPTION, kernel mode context
4907 * switches may happen any time, so we want to disable a
4908 * context switch OUT till we get any PMCs targeting this
4909 * process off the hardware.
4911 * We also need to atomically remove this process'
4912 * entry from our target process hash table, using
4915 PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
4918 critical_enter(); /* no preemption */
4920 cpu = curthread->td_oncpu;
4922 if ((pp = pmc_find_process_descriptor(p,
4923 PMC_FLAG_REMOVE)) != NULL) {
4926 "process-exit proc=%p pmc-process=%p", p, pp);
4929 * The exiting process could the target of
4930 * some PMCs which will be running on
4931 * currently executing CPU.
4933 * We need to turn these PMCs off like we
4934 * would do at context switch OUT time.
4936 for (ri = 0; ri < md->pmd_npmc; ri++) {
4939 * Pick up the pmc pointer from hardware
4940 * state similar to the CSW_OUT code.
4944 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4946 (void) (*pcd->pcd_get_config)(cpu, adjri, &pm);
4948 PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
4951 !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
4954 PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
4955 "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
4958 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
4959 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
4960 __LINE__, PMC_TO_ROWINDEX(pm), ri));
4962 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
4963 ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
4964 __LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
4966 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4967 ("[pmc,%d] bad runcount ri %d rc %ld",
4968 __LINE__, ri, (unsigned long)counter_u64_fetch(pm->pm_runcount)));
4971 * Change desired state, and then stop if not
4972 * stalled. This two-step dance should avoid
4973 * race conditions where an interrupt re-enables
4974 * the PMC after this code has already checked
4975 * the pm_stalled flag.
4977 if (pm->pm_pcpu_state[cpu].pps_cpustate) {
4978 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
4979 if (!pm->pm_pcpu_state[cpu].pps_stalled) {
4980 (void) pcd->pcd_stop_pmc(cpu, adjri);
4982 if (PMC_TO_MODE(pm) == PMC_MODE_TC) {
4983 pcd->pcd_read_pmc(cpu, adjri,
4986 PMC_PCPU_SAVED(cpu,ri);
4988 mtx_pool_lock_spin(pmc_mtxpool,
4990 pm->pm_gv.pm_savedvalue += tmp;
4991 pp->pp_pmcs[ri].pp_pmcval +=
4993 mtx_pool_unlock_spin(
4999 counter_u64_add(pm->pm_runcount, -1);
5001 KASSERT((int) counter_u64_fetch(pm->pm_runcount) >= 0,
5002 ("[pmc,%d] runcount is %d", __LINE__, ri));
5004 (void) pcd->pcd_config_pmc(cpu, adjri, NULL);
5008 * Inform the MD layer of this pseudo "context switch
5011 (void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
5013 critical_exit(); /* ok to be pre-empted now */
5016 * Unlink this process from the PMCs that are
5017 * targeting it. This will send a signal to
5018 * all PMC owner's whose PMCs are orphaned.
5020 * Log PMC value at exit time if requested.
5022 for (ri = 0; ri < md->pmd_npmc; ri++)
5023 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
5024 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
5025 PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
5026 pmclog_process_procexit(pm, pp);
5027 pmc_unlink_target_process(pm, pp);
5032 critical_exit(); /* pp == NULL */
5036 * If the process owned PMCs, free them up and free up
5039 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
5040 pmc_remove_owner(po);
5041 pmc_destroy_owner_descriptor(po);
5044 sx_xunlock(&pmc_sx);
5048 * Handle a process fork.
5050 * If the parent process 'p1' is under HWPMC monitoring, then copy
5051 * over any attached PMCs that have 'do_descendants' semantics.
5055 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
5058 int is_using_hwpmcs;
5060 uint32_t do_descendants;
5062 struct pmc_owner *po;
5063 struct pmc_process *ppnew, *ppold;
5065 (void) flags; /* unused parameter */
5068 is_using_hwpmcs = p1->p_flag & P_HWPMC;
5072 * If there are system-wide sampling PMCs active, we need to
5073 * log all fork events to their owner's logs.
5075 epoch_enter_preempt(global_epoch_preempt);
5076 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5077 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5078 pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
5079 epoch_exit_preempt(global_epoch_preempt);
5081 if (!is_using_hwpmcs)
5085 PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
5086 p1->p_pid, p1->p_comm, newproc);
5089 * If the parent process (curthread->td_proc) is a
5090 * target of any PMCs, look for PMCs that are to be
5091 * inherited, and link these into the new process
5094 if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
5095 PMC_FLAG_NONE)) == NULL)
5096 goto done; /* nothing to do */
5099 for (ri = 0; ri < md->pmd_npmc; ri++)
5100 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
5101 do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
5102 if (do_descendants == 0) /* nothing to do */
5106 * Now mark the new process as being tracked by this driver.
5109 newproc->p_flag |= P_HWPMC;
5110 PROC_UNLOCK(newproc);
5112 /* allocate a descriptor for the new process */
5113 if ((ppnew = pmc_find_process_descriptor(newproc,
5114 PMC_FLAG_ALLOCATE)) == NULL)
5118 * Run through all PMCs that were targeting the old process
5119 * and which specified F_DESCENDANTS and attach them to the
5122 * Log the fork event to all owners of PMCs attached to this
5123 * process, if not already logged.
5125 for (ri = 0; ri < md->pmd_npmc; ri++)
5126 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
5127 (pm->pm_flags & PMC_F_DESCENDANTS)) {
5128 pmc_link_target_process(pm, ppnew);
5130 if (po->po_sscount == 0 &&
5131 po->po_flags & PMC_PO_OWNS_LOGFILE)
5132 pmclog_process_procfork(po, p1->p_pid,
5137 sx_xunlock(&pmc_sx);
5141 pmc_kld_load(void *arg __unused, linker_file_t lf)
5143 struct pmc_owner *po;
5146 * Notify owners of system sampling PMCs about KLD operations.
5148 epoch_enter_preempt(global_epoch_preempt);
5149 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5150 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5151 pmclog_process_map_in(po, (pid_t) -1,
5152 (uintfptr_t) lf->address, lf->filename);
5153 epoch_exit_preempt(global_epoch_preempt);
5156 * TODO: Notify owners of (all) process-sampling PMCs too.
5161 pmc_kld_unload(void *arg __unused, const char *filename __unused,
5162 caddr_t address, size_t size)
5164 struct pmc_owner *po;
5166 epoch_enter_preempt(global_epoch_preempt);
5167 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
5168 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5169 pmclog_process_map_out(po, (pid_t) -1,
5170 (uintfptr_t) address, (uintfptr_t) address + size);
5171 epoch_exit_preempt(global_epoch_preempt);
5174 * TODO: Notify owners of process-sampling PMCs.
5182 pmc_name_of_pmcclass(enum pmc_class class)
5187 #define __PMC_CLASS(S,V,D) \
5188 case PMC_CLASS_##S: \
5192 return ("<unknown>");
5197 * Base class initializer: allocate structure and set default classes.
5200 pmc_mdep_alloc(int nclasses)
5202 struct pmc_mdep *md;
5205 /* SOFT + md classes */
5207 md = malloc(sizeof(struct pmc_mdep) + n *
5208 sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
5211 /* Add base class. */
5212 pmc_soft_initialize(md);
5217 pmc_mdep_free(struct pmc_mdep *md)
5219 pmc_soft_finalize(md);
5224 generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
5226 (void) pc; (void) pp;
5232 generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
5234 (void) pc; (void) pp;
5239 static struct pmc_mdep *
5240 pmc_generic_cpu_initialize(void)
5242 struct pmc_mdep *md;
5244 md = pmc_mdep_alloc(0);
5246 md->pmd_cputype = PMC_CPU_GENERIC;
5248 md->pmd_pcpu_init = NULL;
5249 md->pmd_pcpu_fini = NULL;
5250 md->pmd_switch_in = generic_switch_in;
5251 md->pmd_switch_out = generic_switch_out;
5257 pmc_generic_cpu_finalize(struct pmc_mdep *md)
5264 pmc_initialize(void)
5266 int c, cpu, error, n, ri;
5267 unsigned int maxcpu, domain;
5269 struct pmc_binding pb;
5270 struct pmc_sample *ps;
5271 struct pmc_classdep *pcd;
5272 struct pmc_samplebuffer *sb;
5277 pmc_stats.pm_intr_ignored = counter_u64_alloc(M_WAITOK);
5278 pmc_stats.pm_intr_processed = counter_u64_alloc(M_WAITOK);
5279 pmc_stats.pm_intr_bufferfull = counter_u64_alloc(M_WAITOK);
5280 pmc_stats.pm_syscalls = counter_u64_alloc(M_WAITOK);
5281 pmc_stats.pm_syscall_errors = counter_u64_alloc(M_WAITOK);
5282 pmc_stats.pm_buffer_requests = counter_u64_alloc(M_WAITOK);
5283 pmc_stats.pm_buffer_requests_failed = counter_u64_alloc(M_WAITOK);
5284 pmc_stats.pm_log_sweeps = counter_u64_alloc(M_WAITOK);
5287 /* parse debug flags first */
5288 if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
5289 pmc_debugstr, sizeof(pmc_debugstr)))
5290 pmc_debugflags_parse(pmc_debugstr,
5291 pmc_debugstr+strlen(pmc_debugstr));
5294 PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
5296 /* check kernel version */
5297 if (pmc_kernel_version != PMC_VERSION) {
5298 if (pmc_kernel_version == 0)
5299 printf("hwpmc: this kernel has not been compiled with "
5300 "'options HWPMC_HOOKS'.\n");
5302 printf("hwpmc: kernel version (0x%x) does not match "
5303 "module version (0x%x).\n", pmc_kernel_version,
5305 return EPROGMISMATCH;
5309 * check sysctl parameters
5312 if (pmc_hashsize <= 0) {
5313 (void) printf("hwpmc: tunable \"hashsize\"=%d must be "
5314 "greater than zero.\n", pmc_hashsize);
5315 pmc_hashsize = PMC_HASH_SIZE;
5318 if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
5319 (void) printf("hwpmc: tunable \"nsamples\"=%d out of "
5320 "range.\n", pmc_nsamples);
5321 pmc_nsamples = PMC_NSAMPLES;
5324 if (pmc_callchaindepth <= 0 ||
5325 pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
5326 (void) printf("hwpmc: tunable \"callchaindepth\"=%d out of "
5327 "range - using %d.\n", pmc_callchaindepth,
5328 PMC_CALLCHAIN_DEPTH_MAX);
5329 pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX;
5332 md = pmc_md_initialize();
5334 /* Default to generic CPU. */
5335 md = pmc_generic_cpu_initialize();
5340 KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
5341 ("[pmc,%d] no classes or pmcs", __LINE__));
5343 /* Compute the map from row-indices to classdep pointers. */
5344 pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
5345 md->pmd_npmc, M_PMC, M_WAITOK|M_ZERO);
5347 for (n = 0; n < md->pmd_npmc; n++)
5348 pmc_rowindex_to_classdep[n] = NULL;
5349 for (ri = c = 0; c < md->pmd_nclass; c++) {
5350 pcd = &md->pmd_classdep[c];
5351 for (n = 0; n < pcd->pcd_num; n++, ri++)
5352 pmc_rowindex_to_classdep[ri] = pcd;
5355 KASSERT(ri == md->pmd_npmc,
5356 ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
5359 maxcpu = pmc_cpu_max();
5361 /* allocate space for the per-cpu array */
5362 pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
5365 /* per-cpu 'saved values' for managing process-mode PMCs */
5366 pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
5369 /* Perform CPU-dependent initialization. */
5370 pmc_save_cpu_binding(&pb);
5372 for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
5373 if (!pmc_cpu_is_active(cpu))
5375 pmc_select_cpu(cpu);
5376 pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
5377 md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
5379 if (md->pmd_pcpu_init)
5380 error = md->pmd_pcpu_init(md, cpu);
5381 for (n = 0; error == 0 && n < md->pmd_nclass; n++)
5382 error = md->pmd_classdep[n].pcd_pcpu_init(md, cpu);
5384 pmc_restore_cpu_binding(&pb);
5389 /* allocate space for the sample array */
5390 for (cpu = 0; cpu < maxcpu; cpu++) {
5391 if (!pmc_cpu_is_active(cpu))
5393 pc = pcpu_find(cpu);
5394 domain = pc->pc_domain;
5395 sb = malloc_domain(sizeof(struct pmc_samplebuffer) +
5396 pmc_nsamples * sizeof(struct pmc_sample), M_PMC, domain,
5398 sb->ps_read = sb->ps_write = sb->ps_samples;
5399 sb->ps_fence = sb->ps_samples + pmc_nsamples;
5401 KASSERT(pmc_pcpu[cpu] != NULL,
5402 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
5404 sb->ps_callchains = malloc_domain(pmc_callchaindepth * pmc_nsamples *
5405 sizeof(uintptr_t), M_PMC, domain, M_WAITOK|M_ZERO);
5407 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5408 ps->ps_pc = sb->ps_callchains +
5409 (n * pmc_callchaindepth);
5411 pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
5413 sb = malloc_domain(sizeof(struct pmc_samplebuffer) +
5414 pmc_nsamples * sizeof(struct pmc_sample), M_PMC, domain,
5416 sb->ps_read = sb->ps_write = sb->ps_samples;
5417 sb->ps_fence = sb->ps_samples + pmc_nsamples;
5419 KASSERT(pmc_pcpu[cpu] != NULL,
5420 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
5422 sb->ps_callchains = malloc_domain(pmc_callchaindepth * pmc_nsamples *
5423 sizeof(uintptr_t), M_PMC, domain, M_WAITOK|M_ZERO);
5425 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5426 ps->ps_pc = sb->ps_callchains +
5427 (n * pmc_callchaindepth);
5429 pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
5432 /* allocate space for the row disposition array */
5433 pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
5434 M_PMC, M_WAITOK|M_ZERO);
5436 /* mark all PMCs as available */
5437 for (n = 0; n < (int) md->pmd_npmc; n++)
5438 PMC_MARK_ROW_FREE(n);
5440 /* allocate thread hash tables */
5441 pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
5442 &pmc_ownerhashmask);
5444 pmc_processhash = hashinit(pmc_hashsize, M_PMC,
5445 &pmc_processhashmask);
5446 mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
5449 CK_LIST_INIT(&pmc_ss_owners);
5452 /* allocate a pool of spin mutexes */
5453 pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
5456 PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
5457 "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
5458 pmc_processhash, pmc_processhashmask);
5460 /* Initialize a spin mutex for the thread free list. */
5461 mtx_init(&pmc_threadfreelist_mtx, "pmc-threadfreelist", "pmc-leaf",
5465 * Initialize the callout to monitor the thread free list.
5466 * This callout will also handle the initial population of the list.
5468 taskqgroup_config_gtask_init(NULL, &free_gtask, pmc_thread_descriptor_pool_free_task, "thread descriptor pool free task");
5470 /* register process {exit,fork,exec} handlers */
5471 pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
5472 pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
5473 pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
5474 pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
5476 /* register kld event handlers */
5477 pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
5478 NULL, EVENTHANDLER_PRI_ANY);
5479 pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
5480 NULL, EVENTHANDLER_PRI_ANY);
5482 /* initialize logging */
5483 pmclog_initialize();
5485 /* set hook functions */
5486 pmc_intr = md->pmd_intr;
5488 pmc_hook = pmc_hook_handler;
5491 printf(PMC_MODULE_NAME ":");
5492 for (n = 0; n < (int) md->pmd_nclass; n++) {
5493 pcd = &md->pmd_classdep[n];
5494 printf(" %s/%d/%d/0x%b",
5495 pmc_name_of_pmcclass(pcd->pcd_class),
5500 "\1INT\2USR\3SYS\4EDG\5THR"
5501 "\6REA\7WRI\10INV\11QUA\12PRC"
5510 /* prepare to be unloaded */
5515 unsigned int maxcpu;
5516 struct pmc_ownerhash *ph;
5517 struct pmc_owner *po, *tmp;
5518 struct pmc_binding pb;
5520 struct pmc_processhash *prh;
5523 PMCDBG0(MOD,INI,0, "cleanup");
5525 /* switch off sampling */
5527 DPCPU_ID_SET(cpu, pmc_sampled, 0);
5531 if (pmc_hook == NULL) { /* being unloaded already */
5532 sx_xunlock(&pmc_sx);
5536 pmc_hook = NULL; /* prevent new threads from entering module */
5538 /* deregister event handlers */
5539 EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
5540 EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
5541 EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
5542 EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);
5544 /* send SIGBUS to all owner threads, free up allocations */
5546 for (ph = pmc_ownerhash;
5547 ph <= &pmc_ownerhash[pmc_ownerhashmask];
5549 LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
5550 pmc_remove_owner(po);
5552 /* send SIGBUS to owner processes */
5553 PMCDBG3(MOD,INI,2, "cleanup signal proc=%p "
5554 "(%d, %s)", po->po_owner,
5555 po->po_owner->p_pid,
5556 po->po_owner->p_comm);
5558 PROC_LOCK(po->po_owner);
5559 kern_psignal(po->po_owner, SIGBUS);
5560 PROC_UNLOCK(po->po_owner);
5562 pmc_destroy_owner_descriptor(po);
5566 /* reclaim allocated data structures */
5567 mtx_destroy(&pmc_threadfreelist_mtx);
5568 pmc_thread_descriptor_pool_drain();
5571 mtx_pool_destroy(&pmc_mtxpool);
5573 mtx_destroy(&pmc_processhash_mtx);
5574 taskqgroup_config_gtask_deinit(&free_gtask);
5575 if (pmc_processhash) {
5577 struct pmc_process *pp;
5579 PMCDBG0(MOD,INI,3, "destroy process hash");
5580 for (prh = pmc_processhash;
5581 prh <= &pmc_processhash[pmc_processhashmask];
5583 LIST_FOREACH(pp, prh, pp_next)
5584 PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5587 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5588 pmc_processhash = NULL;
5591 if (pmc_ownerhash) {
5592 PMCDBG0(MOD,INI,3, "destroy owner hash");
5593 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5594 pmc_ownerhash = NULL;
5597 KASSERT(CK_LIST_EMPTY(&pmc_ss_owners),
5598 ("[pmc,%d] Global SS owner list not empty", __LINE__));
5599 KASSERT(pmc_ss_count == 0,
5600 ("[pmc,%d] Global SS count not empty", __LINE__));
5602 /* do processor and pmc-class dependent cleanup */
5603 maxcpu = pmc_cpu_max();
5605 PMCDBG0(MOD,INI,3, "md cleanup");
5607 pmc_save_cpu_binding(&pb);
5608 for (cpu = 0; cpu < maxcpu; cpu++) {
5609 PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5610 cpu, pmc_pcpu[cpu]);
5611 if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5613 pmc_select_cpu(cpu);
5614 for (c = 0; c < md->pmd_nclass; c++)
5615 md->pmd_classdep[c].pcd_pcpu_fini(md, cpu);
5616 if (md->pmd_pcpu_fini)
5617 md->pmd_pcpu_fini(md, cpu);
5620 if (md->pmd_cputype == PMC_CPU_GENERIC)
5621 pmc_generic_cpu_finalize(md);
5623 pmc_md_finalize(md);
5627 pmc_restore_cpu_binding(&pb);
5630 /* Free per-cpu descriptors. */
5631 for (cpu = 0; cpu < maxcpu; cpu++) {
5632 if (!pmc_cpu_is_active(cpu))
5634 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5635 ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5637 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5638 ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5640 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
5641 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
5642 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
5643 free_domain(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
5644 free_domain(pmc_pcpu[cpu], M_PMC);
5647 free(pmc_pcpu, M_PMC);
5650 free(pmc_pcpu_saved, M_PMC);
5651 pmc_pcpu_saved = NULL;
5654 free(pmc_pmcdisp, M_PMC);
5658 if (pmc_rowindex_to_classdep) {
5659 free(pmc_rowindex_to_classdep, M_PMC);
5660 pmc_rowindex_to_classdep = NULL;
5664 counter_u64_free(pmc_stats.pm_intr_ignored);
5665 counter_u64_free(pmc_stats.pm_intr_processed);
5666 counter_u64_free(pmc_stats.pm_intr_bufferfull);
5667 counter_u64_free(pmc_stats.pm_syscalls);
5668 counter_u64_free(pmc_stats.pm_syscall_errors);
5669 counter_u64_free(pmc_stats.pm_buffer_requests);
5670 counter_u64_free(pmc_stats.pm_buffer_requests_failed);
5671 counter_u64_free(pmc_stats.pm_log_sweeps);
5672 sx_xunlock(&pmc_sx); /* we are done */
5676 * The function called at load/unload.
5680 load (struct module *module __unused, int cmd, void *arg __unused)
5688 /* initialize the subsystem */
5689 error = pmc_initialize();
5692 PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d",
5693 pmc_syscall_num, pmc_cpu_max());
5700 PMCDBG0(MOD,INI,1, "unloaded");
5704 error = EINVAL; /* XXX should panic(9) */