1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause 3 * 4 * Copyright (c) 2003-2008 Joseph Koshy 5 * Copyright (c) 2007 The FreeBSD Foundation 6 * Copyright (c) 2018 Matthew Macy 7 * All rights reserved. 8 * 9 * Portions of this software were developed by A. Joseph Koshy under 10 * sponsorship from the FreeBSD Foundation and Google, Inc. 11 * 12 * Redistribution and use in source and binary forms, with or without 13 * modification, are permitted provided that the following conditions 14 * are met: 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. 20 * 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 31 * SUCH DAMAGE. 32 */ 33 34 #include <sys/cdefs.h> 35 #include <sys/param.h> 36 #include <sys/systm.h> 37 #include <sys/domainset.h> 38 #include <sys/eventhandler.h> 39 #include <sys/jail.h> 40 #include <sys/kernel.h> 41 #include <sys/kthread.h> 42 #include <sys/limits.h> 43 #include <sys/lock.h> 44 #include <sys/malloc.h> 45 #include <sys/module.h> 46 #include <sys/mount.h> 47 #include <sys/mutex.h> 48 #include <sys/pmc.h> 49 #include <sys/pmckern.h> 50 #include <sys/pmclog.h> 51 #include <sys/priv.h> 52 #include <sys/proc.h> 53 #include <sys/queue.h> 54 #include <sys/resourcevar.h> 55 #include <sys/rwlock.h> 56 #include <sys/sched.h> 57 #include <sys/signalvar.h> 58 #include <sys/smp.h> 59 #include <sys/sx.h> 60 #include <sys/sysctl.h> 61 #include <sys/sysent.h> 62 #include <sys/syslog.h> 63 #include <sys/taskqueue.h> 64 #include <sys/vnode.h> 65 66 #include <sys/linker.h> /* needs to be after <sys/malloc.h> */ 67 68 #include <machine/atomic.h> 69 #include <machine/md_var.h> 70 71 #include <vm/vm.h> 72 #include <vm/vm_extern.h> 73 #include <vm/pmap.h> 74 #include <vm/vm_map.h> 75 #include <vm/vm_object.h> 76 77 #include "hwpmc_soft.h" 78 79 #define PMC_EPOCH_ENTER() \ 80 struct epoch_tracker pmc_et; \ 81 epoch_enter_preempt(global_epoch_preempt, &pmc_et) 82 83 #define PMC_EPOCH_EXIT() \ 84 epoch_exit_preempt(global_epoch_preempt, &pmc_et) 85 86 /* 87 * Types 88 */ 89 90 enum pmc_flags { 91 PMC_FLAG_NONE = 0x00, /* do nothing */ 92 PMC_FLAG_REMOVE = 0x01, /* atomically remove entry from hash */ 93 PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */ 94 PMC_FLAG_NOWAIT = 0x04, /* do not wait for mallocs */ 95 }; 96 97 /* 98 * The offset in sysent where the syscall is allocated. 99 */ 100 static int pmc_syscall_num = NO_SYSCALL; 101 102 struct pmc_cpu **pmc_pcpu; /* per-cpu state */ 103 pmc_value_t *pmc_pcpu_saved; /* saved PMC values: CSW handling */ 104 105 #define PMC_PCPU_SAVED(C, R) pmc_pcpu_saved[(R) + md->pmd_npmc * (C)] 106 107 struct mtx_pool *pmc_mtxpool; 108 static int *pmc_pmcdisp; /* PMC row dispositions */ 109 110 #define PMC_ROW_DISP_IS_FREE(R) (pmc_pmcdisp[(R)] == 0) 111 #define PMC_ROW_DISP_IS_THREAD(R) (pmc_pmcdisp[(R)] > 0) 112 #define PMC_ROW_DISP_IS_STANDALONE(R) (pmc_pmcdisp[(R)] < 0) 113 114 #define PMC_MARK_ROW_FREE(R) do { \ 115 pmc_pmcdisp[(R)] = 0; \ 116 } while (0) 117 118 #define PMC_MARK_ROW_STANDALONE(R) do { \ 119 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \ 120 __LINE__)); \ 121 atomic_add_int(&pmc_pmcdisp[(R)], -1); \ 122 KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()), \ 123 ("[pmc,%d] row disposition error", __LINE__)); \ 124 } while (0) 125 126 #define PMC_UNMARK_ROW_STANDALONE(R) do { \ 127 atomic_add_int(&pmc_pmcdisp[(R)], 1); \ 128 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \ 129 __LINE__)); \ 130 } while (0) 131 132 #define PMC_MARK_ROW_THREAD(R) do { \ 133 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \ 134 __LINE__)); \ 135 atomic_add_int(&pmc_pmcdisp[(R)], 1); \ 136 } while (0) 137 138 #define PMC_UNMARK_ROW_THREAD(R) do { \ 139 atomic_add_int(&pmc_pmcdisp[(R)], -1); \ 140 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \ 141 __LINE__)); \ 142 } while (0) 143 144 /* various event handlers */ 145 static eventhandler_tag pmc_exit_tag, pmc_fork_tag, pmc_kld_load_tag, 146 pmc_kld_unload_tag; 147 148 /* Module statistics */ 149 struct pmc_driverstats pmc_stats; 150 151 /* Machine/processor dependent operations */ 152 static struct pmc_mdep *md; 153 154 /* 155 * Hash tables mapping owner processes and target threads to PMCs. 156 */ 157 struct mtx pmc_processhash_mtx; /* spin mutex */ 158 static u_long pmc_processhashmask; 159 static LIST_HEAD(pmc_processhash, pmc_process) *pmc_processhash; 160 161 /* 162 * Hash table of PMC owner descriptors. This table is protected by 163 * the shared PMC "sx" lock. 164 */ 165 static u_long pmc_ownerhashmask; 166 static LIST_HEAD(pmc_ownerhash, pmc_owner) *pmc_ownerhash; 167 168 /* 169 * List of PMC owners with system-wide sampling PMCs. 170 */ 171 static CK_LIST_HEAD(, pmc_owner) pmc_ss_owners; 172 173 /* 174 * List of free thread entries. This is protected by the spin 175 * mutex. 176 */ 177 static struct mtx pmc_threadfreelist_mtx; /* spin mutex */ 178 static LIST_HEAD(, pmc_thread) pmc_threadfreelist; 179 static int pmc_threadfreelist_entries = 0; 180 #define THREADENTRY_SIZE (sizeof(struct pmc_thread) + \ 181 (md->pmd_npmc * sizeof(struct pmc_threadpmcstate))) 182 183 /* 184 * Task to free thread descriptors 185 */ 186 static struct task free_task; 187 188 /* 189 * A map of row indices to classdep structures. 190 */ 191 static struct pmc_classdep **pmc_rowindex_to_classdep; 192 193 /* 194 * Prototypes 195 */ 196 197 #ifdef HWPMC_DEBUG 198 static int pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS); 199 static int pmc_debugflags_parse(char *newstr, char *fence); 200 #endif 201 202 static int load(struct module *module, int cmd, void *arg); 203 static int pmc_add_sample(ring_type_t ring, struct pmc *pm, 204 struct trapframe *tf); 205 static void pmc_add_thread_descriptors_from_proc(struct proc *p, 206 struct pmc_process *pp); 207 static int pmc_attach_process(struct proc *p, struct pmc *pm); 208 static struct pmc *pmc_allocate_pmc_descriptor(void); 209 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p); 210 static int pmc_attach_one_process(struct proc *p, struct pmc *pm); 211 static bool pmc_can_allocate_row(int ri, enum pmc_mode mode); 212 static bool pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, 213 int cpu); 214 static int pmc_can_attach(struct pmc *pm, struct proc *p); 215 static void pmc_capture_user_callchain(int cpu, int soft, 216 struct trapframe *tf); 217 static void pmc_cleanup(void); 218 static int pmc_detach_process(struct proc *p, struct pmc *pm); 219 static int pmc_detach_one_process(struct proc *p, struct pmc *pm, 220 int flags); 221 static void pmc_destroy_owner_descriptor(struct pmc_owner *po); 222 static void pmc_destroy_pmc_descriptor(struct pmc *pm); 223 static void pmc_destroy_process_descriptor(struct pmc_process *pp); 224 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p); 225 static int pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm); 226 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, 227 pmc_id_t pmc); 228 static struct pmc_process *pmc_find_process_descriptor(struct proc *p, 229 uint32_t mode); 230 static struct pmc_thread *pmc_find_thread_descriptor(struct pmc_process *pp, 231 struct thread *td, uint32_t mode); 232 static void pmc_force_context_switch(void); 233 static void pmc_link_target_process(struct pmc *pm, 234 struct pmc_process *pp); 235 static void pmc_log_all_process_mappings(struct pmc_owner *po); 236 static void pmc_log_kernel_mappings(struct pmc *pm); 237 static void pmc_log_process_mappings(struct pmc_owner *po, struct proc *p); 238 static void pmc_maybe_remove_owner(struct pmc_owner *po); 239 static void pmc_post_callchain_callback(void); 240 static void pmc_process_allproc(struct pmc *pm); 241 static void pmc_process_csw_in(struct thread *td); 242 static void pmc_process_csw_out(struct thread *td); 243 static void pmc_process_exec(struct thread *td, 244 struct pmckern_procexec *pk); 245 static void pmc_process_exit(void *arg, struct proc *p); 246 static void pmc_process_fork(void *arg, struct proc *p1, 247 struct proc *p2, int n); 248 static void pmc_process_proccreate(struct proc *p); 249 static void pmc_process_samples(int cpu, ring_type_t soft); 250 static void pmc_process_threadcreate(struct thread *td); 251 static void pmc_process_threadexit(struct thread *td); 252 static void pmc_process_thread_add(struct thread *td); 253 static void pmc_process_thread_delete(struct thread *td); 254 static void pmc_process_thread_userret(struct thread *td); 255 static void pmc_release_pmc_descriptor(struct pmc *pmc); 256 static void pmc_remove_owner(struct pmc_owner *po); 257 static void pmc_remove_process_descriptor(struct pmc_process *pp); 258 static int pmc_start(struct pmc *pm); 259 static int pmc_stop(struct pmc *pm); 260 static int pmc_syscall_handler(struct thread *td, void *syscall_args); 261 static struct pmc_thread *pmc_thread_descriptor_pool_alloc(void); 262 static void pmc_thread_descriptor_pool_drain(void); 263 static void pmc_thread_descriptor_pool_free(struct pmc_thread *pt); 264 static void pmc_unlink_target_process(struct pmc *pmc, 265 struct pmc_process *pp); 266 267 static int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp); 268 static int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp); 269 static struct pmc_mdep *pmc_generic_cpu_initialize(void); 270 static void pmc_generic_cpu_finalize(struct pmc_mdep *md); 271 272 /* 273 * Kernel tunables and sysctl(8) interface. 274 */ 275 276 SYSCTL_DECL(_kern_hwpmc); 277 SYSCTL_NODE(_kern_hwpmc, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 278 "HWPMC stats"); 279 280 /* Stats. */ 281 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_ignored, CTLFLAG_RW, 282 &pmc_stats.pm_intr_ignored, 283 "# of interrupts ignored"); 284 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_processed, CTLFLAG_RW, 285 &pmc_stats.pm_intr_processed, 286 "# of interrupts processed"); 287 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_bufferfull, CTLFLAG_RW, 288 &pmc_stats.pm_intr_bufferfull, 289 "# of interrupts where buffer was full"); 290 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscalls, CTLFLAG_RW, 291 &pmc_stats.pm_syscalls, 292 "# of syscalls"); 293 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscall_errors, CTLFLAG_RW, 294 &pmc_stats.pm_syscall_errors, 295 "# of syscall_errors"); 296 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests, CTLFLAG_RW, 297 &pmc_stats.pm_buffer_requests, 298 "# of buffer requests"); 299 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests_failed, 300 CTLFLAG_RW, &pmc_stats.pm_buffer_requests_failed, 301 "# of buffer requests which failed"); 302 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, log_sweeps, CTLFLAG_RW, 303 &pmc_stats.pm_log_sweeps, 304 "# of times samples were processed"); 305 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, merges, CTLFLAG_RW, 306 &pmc_stats.pm_merges, 307 "# of times kernel stack was found for user trace"); 308 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, overwrites, CTLFLAG_RW, 309 &pmc_stats.pm_overwrites, 310 "# of times a sample was overwritten before being logged"); 311 312 static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH; 313 SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_RDTUN, 314 &pmc_callchaindepth, 0, 315 "depth of call chain records"); 316 317 char pmc_cpuid[PMC_CPUID_LEN]; 318 SYSCTL_STRING(_kern_hwpmc, OID_AUTO, cpuid, CTLFLAG_RD, 319 pmc_cpuid, 0, 320 "cpu version string"); 321 322 #ifdef HWPMC_DEBUG 323 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS; 324 char pmc_debugstr[PMC_DEBUG_STRSIZE]; 325 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr, 326 sizeof(pmc_debugstr)); 327 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags, 328 CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, 329 0, 0, pmc_debugflags_sysctl_handler, "A", 330 "debug flags"); 331 #endif 332 333 /* 334 * kern.hwpmc.hashsize -- determines the number of rows in the 335 * of the hash table used to look up threads 336 */ 337 static int pmc_hashsize = PMC_HASH_SIZE; 338 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_RDTUN, 339 &pmc_hashsize, 0, 340 "rows in hash tables"); 341 342 /* 343 * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU 344 */ 345 static int pmc_nsamples = PMC_NSAMPLES; 346 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_RDTUN, 347 &pmc_nsamples, 0, 348 "number of PC samples per CPU"); 349 350 static uint64_t pmc_sample_mask = PMC_NSAMPLES - 1; 351 352 /* 353 * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool. 354 */ 355 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE; 356 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_RDTUN, 357 &pmc_mtxpool_size, 0, 358 "size of spin mutex pool"); 359 360 /* 361 * kern.hwpmc.threadfreelist_entries -- number of free entries 362 */ 363 SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_entries, CTLFLAG_RD, 364 &pmc_threadfreelist_entries, 0, 365 "number of available thread entries"); 366 367 /* 368 * kern.hwpmc.threadfreelist_max -- maximum number of free entries 369 */ 370 static int pmc_threadfreelist_max = PMC_THREADLIST_MAX; 371 SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_max, CTLFLAG_RW, 372 &pmc_threadfreelist_max, 0, 373 "maximum number of available thread entries before freeing some"); 374 375 /* 376 * kern.hwpmc.mincount -- minimum sample count 377 */ 378 static u_int pmc_mincount = 1000; 379 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mincount, CTLFLAG_RWTUN, 380 &pmc_mincount, 0, 381 "minimum count for sampling counters"); 382 383 /* 384 * security.bsd.unprivileged_syspmcs -- allow non-root processes to 385 * allocate system-wide PMCs. 386 * 387 * Allowing unprivileged processes to allocate system PMCs is convenient 388 * if system-wide measurements need to be taken concurrently with other 389 * per-process measurements. This feature is turned off by default. 390 */ 391 static int pmc_unprivileged_syspmcs = 0; 392 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RWTUN, 393 &pmc_unprivileged_syspmcs, 0, 394 "allow unprivileged process to allocate system PMCs"); 395 396 /* 397 * Hash function. Discard the lower 2 bits of the pointer since 398 * these are always zero for our uses. The hash multiplier is 399 * round((2^LONG_BIT) * ((sqrt(5)-1)/2)). 400 */ 401 #if LONG_BIT == 64 402 #define _PMC_HM 11400714819323198486u 403 #elif LONG_BIT == 32 404 #define _PMC_HM 2654435769u 405 #else 406 #error Must know the size of 'long' to compile 407 #endif 408 409 #define PMC_HASH_PTR(P,M) ((((unsigned long) (P) >> 2) * _PMC_HM) & (M)) 410 411 /* 412 * Syscall structures 413 */ 414 415 /* The `sysent' for the new syscall */ 416 static struct sysent pmc_sysent = { 417 .sy_narg = 2, 418 .sy_call = pmc_syscall_handler, 419 }; 420 421 static struct syscall_module_data pmc_syscall_mod = { 422 .chainevh = load, 423 .chainarg = NULL, 424 .offset = &pmc_syscall_num, 425 .new_sysent = &pmc_sysent, 426 .old_sysent = { .sy_narg = 0, .sy_call = NULL }, 427 .flags = SY_THR_STATIC_KLD, 428 }; 429 430 static moduledata_t pmc_mod = { 431 .name = PMC_MODULE_NAME, 432 .evhand = syscall_module_handler, 433 .priv = &pmc_syscall_mod, 434 }; 435 436 #ifdef EARLY_AP_STARTUP 437 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SYSCALLS, SI_ORDER_ANY); 438 #else 439 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY); 440 #endif 441 MODULE_VERSION(pmc, PMC_VERSION); 442 443 #ifdef HWPMC_DEBUG 444 enum pmc_dbgparse_state { 445 PMCDS_WS, /* in whitespace */ 446 PMCDS_MAJOR, /* seen a major keyword */ 447 PMCDS_MINOR 448 }; 449 450 static int 451 pmc_debugflags_parse(char *newstr, char *fence) 452 { 453 struct pmc_debugflags *tmpflags; 454 size_t kwlen; 455 char c, *p, *q; 456 int error, *newbits, tmp; 457 int found; 458 459 tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK | M_ZERO); 460 461 error = 0; 462 for (p = newstr; p < fence && (c = *p); p++) { 463 /* skip white space */ 464 if (c == ' ' || c == '\t') 465 continue; 466 467 /* look for a keyword followed by "=" */ 468 for (q = p; p < fence && (c = *p) && c != '='; p++) 469 ; 470 if (c != '=') { 471 error = EINVAL; 472 goto done; 473 } 474 475 kwlen = p - q; 476 newbits = NULL; 477 478 /* lookup flag group name */ 479 #define DBG_SET_FLAG_MAJ(S,F) \ 480 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \ 481 newbits = &tmpflags->pdb_ ## F; 482 483 DBG_SET_FLAG_MAJ("cpu", CPU); 484 DBG_SET_FLAG_MAJ("csw", CSW); 485 DBG_SET_FLAG_MAJ("logging", LOG); 486 DBG_SET_FLAG_MAJ("module", MOD); 487 DBG_SET_FLAG_MAJ("md", MDP); 488 DBG_SET_FLAG_MAJ("owner", OWN); 489 DBG_SET_FLAG_MAJ("pmc", PMC); 490 DBG_SET_FLAG_MAJ("process", PRC); 491 DBG_SET_FLAG_MAJ("sampling", SAM); 492 #undef DBG_SET_FLAG_MAJ 493 494 if (newbits == NULL) { 495 error = EINVAL; 496 goto done; 497 } 498 499 p++; /* skip the '=' */ 500 501 /* Now parse the individual flags */ 502 tmp = 0; 503 newflag: 504 for (q = p; p < fence && (c = *p); p++) 505 if (c == ' ' || c == '\t' || c == ',') 506 break; 507 508 /* p == fence or c == ws or c == "," or c == 0 */ 509 510 if ((kwlen = p - q) == 0) { 511 *newbits = tmp; 512 continue; 513 } 514 515 found = 0; 516 #define DBG_SET_FLAG_MIN(S,F) \ 517 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \ 518 tmp |= found = (1 << PMC_DEBUG_MIN_ ## F) 519 520 /* a '*' denotes all possible flags in the group */ 521 if (kwlen == 1 && *q == '*') 522 tmp = found = ~0; 523 /* look for individual flag names */ 524 DBG_SET_FLAG_MIN("allocaterow", ALR); 525 DBG_SET_FLAG_MIN("allocate", ALL); 526 DBG_SET_FLAG_MIN("attach", ATT); 527 DBG_SET_FLAG_MIN("bind", BND); 528 DBG_SET_FLAG_MIN("config", CFG); 529 DBG_SET_FLAG_MIN("exec", EXC); 530 DBG_SET_FLAG_MIN("exit", EXT); 531 DBG_SET_FLAG_MIN("find", FND); 532 DBG_SET_FLAG_MIN("flush", FLS); 533 DBG_SET_FLAG_MIN("fork", FRK); 534 DBG_SET_FLAG_MIN("getbuf", GTB); 535 DBG_SET_FLAG_MIN("hook", PMH); 536 DBG_SET_FLAG_MIN("init", INI); 537 DBG_SET_FLAG_MIN("intr", INT); 538 DBG_SET_FLAG_MIN("linktarget", TLK); 539 DBG_SET_FLAG_MIN("mayberemove", OMR); 540 DBG_SET_FLAG_MIN("ops", OPS); 541 DBG_SET_FLAG_MIN("read", REA); 542 DBG_SET_FLAG_MIN("register", REG); 543 DBG_SET_FLAG_MIN("release", REL); 544 DBG_SET_FLAG_MIN("remove", ORM); 545 DBG_SET_FLAG_MIN("sample", SAM); 546 DBG_SET_FLAG_MIN("scheduleio", SIO); 547 DBG_SET_FLAG_MIN("select", SEL); 548 DBG_SET_FLAG_MIN("signal", SIG); 549 DBG_SET_FLAG_MIN("swi", SWI); 550 DBG_SET_FLAG_MIN("swo", SWO); 551 DBG_SET_FLAG_MIN("start", STA); 552 DBG_SET_FLAG_MIN("stop", STO); 553 DBG_SET_FLAG_MIN("syscall", PMS); 554 DBG_SET_FLAG_MIN("unlinktarget", TUL); 555 DBG_SET_FLAG_MIN("write", WRI); 556 #undef DBG_SET_FLAG_MIN 557 if (found == 0) { 558 /* unrecognized flag name */ 559 error = EINVAL; 560 goto done; 561 } 562 563 if (c == 0 || c == ' ' || c == '\t') { /* end of flag group */ 564 *newbits = tmp; 565 continue; 566 } 567 568 p++; 569 goto newflag; 570 } 571 572 /* save the new flag set */ 573 bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags)); 574 done: 575 free(tmpflags, M_PMC); 576 return (error); 577 } 578 579 static int 580 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS) 581 { 582 char *fence, *newstr; 583 int error; 584 u_int n; 585 586 n = sizeof(pmc_debugstr); 587 newstr = malloc(n, M_PMC, M_WAITOK | M_ZERO); 588 strlcpy(newstr, pmc_debugstr, n); 589 590 error = sysctl_handle_string(oidp, newstr, n, req); 591 592 /* if there is a new string, parse and copy it */ 593 if (error == 0 && req->newptr != NULL) { 594 fence = newstr + (n < req->newlen ? n : req->newlen + 1); 595 error = pmc_debugflags_parse(newstr, fence); 596 if (error == 0) 597 strlcpy(pmc_debugstr, newstr, sizeof(pmc_debugstr)); 598 } 599 free(newstr, M_PMC); 600 601 return (error); 602 } 603 #endif 604 605 /* 606 * Map a row index to a classdep structure and return the adjusted row 607 * index for the PMC class index. 608 */ 609 static struct pmc_classdep * 610 pmc_ri_to_classdep(struct pmc_mdep *md __unused, int ri, int *adjri) 611 { 612 struct pmc_classdep *pcd; 613 614 KASSERT(ri >= 0 && ri < md->pmd_npmc, 615 ("[pmc,%d] illegal row-index %d", __LINE__, ri)); 616 617 pcd = pmc_rowindex_to_classdep[ri]; 618 KASSERT(pcd != NULL, 619 ("[pmc,%d] ri %d null pcd", __LINE__, ri)); 620 621 *adjri = ri - pcd->pcd_ri; 622 KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num, 623 ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri)); 624 625 return (pcd); 626 } 627 628 /* 629 * Concurrency Control 630 * 631 * The driver manages the following data structures: 632 * 633 * - target process descriptors, one per target process 634 * - owner process descriptors (and attached lists), one per owner process 635 * - lookup hash tables for owner and target processes 636 * - PMC descriptors (and attached lists) 637 * - per-cpu hardware state 638 * - the 'hook' variable through which the kernel calls into 639 * this module 640 * - the machine hardware state (managed by the MD layer) 641 * 642 * These data structures are accessed from: 643 * 644 * - thread context-switch code 645 * - interrupt handlers (possibly on multiple cpus) 646 * - kernel threads on multiple cpus running on behalf of user 647 * processes doing system calls 648 * - this driver's private kernel threads 649 * 650 * = Locks and Locking strategy = 651 * 652 * The driver uses four locking strategies for its operation: 653 * 654 * - The global SX lock "pmc_sx" is used to protect internal 655 * data structures. 656 * 657 * Calls into the module by syscall() start with this lock being 658 * held in exclusive mode. Depending on the requested operation, 659 * the lock may be downgraded to 'shared' mode to allow more 660 * concurrent readers into the module. Calls into the module from 661 * other parts of the kernel acquire the lock in shared mode. 662 * 663 * This SX lock is held in exclusive mode for any operations that 664 * modify the linkages between the driver's internal data structures. 665 * 666 * The 'pmc_hook' function pointer is also protected by this lock. 667 * It is only examined with the sx lock held in exclusive mode. The 668 * kernel module is allowed to be unloaded only with the sx lock held 669 * in exclusive mode. In normal syscall handling, after acquiring the 670 * pmc_sx lock we first check that 'pmc_hook' is non-null before 671 * proceeding. This prevents races between the thread unloading the module 672 * and other threads seeking to use the module. 673 * 674 * - Lookups of target process structures and owner process structures 675 * cannot use the global "pmc_sx" SX lock because these lookups need 676 * to happen during context switches and in other critical sections 677 * where sleeping is not allowed. We protect these lookup tables 678 * with their own private spin-mutexes, "pmc_processhash_mtx" and 679 * "pmc_ownerhash_mtx". 680 * 681 * - Interrupt handlers work in a lock free manner. At interrupt 682 * time, handlers look at the PMC pointer (phw->phw_pmc) configured 683 * when the PMC was started. If this pointer is NULL, the interrupt 684 * is ignored after updating driver statistics. We ensure that this 685 * pointer is set (using an atomic operation if necessary) before the 686 * PMC hardware is started. Conversely, this pointer is unset atomically 687 * only after the PMC hardware is stopped. 688 * 689 * We ensure that everything needed for the operation of an 690 * interrupt handler is available without it needing to acquire any 691 * locks. We also ensure that a PMC's software state is destroyed only 692 * after the PMC is taken off hardware (on all CPUs). 693 * 694 * - Context-switch handling with process-private PMCs needs more 695 * care. 696 * 697 * A given process may be the target of multiple PMCs. For example, 698 * PMCATTACH and PMCDETACH may be requested by a process on one CPU 699 * while the target process is running on another. A PMC could also 700 * be getting released because its owner is exiting. We tackle 701 * these situations in the following manner: 702 * 703 * - each target process structure 'pmc_process' has an array 704 * of 'struct pmc *' pointers, one for each hardware PMC. 705 * 706 * - At context switch IN time, each "target" PMC in RUNNING state 707 * gets started on hardware and a pointer to each PMC is copied into 708 * the per-cpu phw array. The 'runcount' for the PMC is 709 * incremented. 710 * 711 * - At context switch OUT time, all process-virtual PMCs are stopped 712 * on hardware. The saved value is added to the PMCs value field 713 * only if the PMC is in a non-deleted state (the PMCs state could 714 * have changed during the current time slice). 715 * 716 * Note that since in-between a switch IN on a processor and a switch 717 * OUT, the PMC could have been released on another CPU. Therefore 718 * context switch OUT always looks at the hardware state to turn 719 * OFF PMCs and will update a PMC's saved value only if reachable 720 * from the target process record. 721 * 722 * - OP PMCRELEASE could be called on a PMC at any time (the PMC could 723 * be attached to many processes at the time of the call and could 724 * be active on multiple CPUs). 725 * 726 * We prevent further scheduling of the PMC by marking it as in 727 * state 'DELETED'. If the runcount of the PMC is non-zero then 728 * this PMC is currently running on a CPU somewhere. The thread 729 * doing the PMCRELEASE operation waits by repeatedly doing a 730 * pause() till the runcount comes to zero. 731 * 732 * The contents of a PMC descriptor (struct pmc) are protected using 733 * a spin-mutex. In order to save space, we use a mutex pool. 734 * 735 * In terms of lock types used by witness(4), we use: 736 * - Type "pmc-sx", used by the global SX lock. 737 * - Type "pmc-sleep", for sleep mutexes used by logger threads. 738 * - Type "pmc-per-proc", for protecting PMC owner descriptors. 739 * - Type "pmc-leaf", used for all other spin mutexes. 740 */ 741 742 /* 743 * Save the CPU binding of the current kthread. 744 */ 745 void 746 pmc_save_cpu_binding(struct pmc_binding *pb) 747 { 748 PMCDBG0(CPU,BND,2, "save-cpu"); 749 thread_lock(curthread); 750 pb->pb_bound = sched_is_bound(curthread); 751 pb->pb_cpu = curthread->td_oncpu; 752 pb->pb_priority = curthread->td_priority; 753 thread_unlock(curthread); 754 PMCDBG1(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu); 755 } 756 757 /* 758 * Restore the CPU binding of the current thread. 759 */ 760 void 761 pmc_restore_cpu_binding(struct pmc_binding *pb) 762 { 763 PMCDBG2(CPU,BND,2, "restore-cpu curcpu=%d restore=%d", 764 curthread->td_oncpu, pb->pb_cpu); 765 thread_lock(curthread); 766 sched_bind(curthread, pb->pb_cpu); 767 if (!pb->pb_bound) 768 sched_unbind(curthread); 769 sched_prio(curthread, pb->pb_priority); 770 thread_unlock(curthread); 771 PMCDBG0(CPU,BND,2, "restore-cpu done"); 772 } 773 774 /* 775 * Move execution over to the specified CPU and bind it there. 776 */ 777 void 778 pmc_select_cpu(int cpu) 779 { 780 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(), 781 ("[pmc,%d] bad cpu number %d", __LINE__, cpu)); 782 783 /* Never move to an inactive CPU. */ 784 KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive " 785 "CPU %d", __LINE__, cpu)); 786 787 PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d", cpu); 788 thread_lock(curthread); 789 sched_prio(curthread, PRI_MIN); 790 sched_bind(curthread, cpu); 791 thread_unlock(curthread); 792 793 KASSERT(curthread->td_oncpu == cpu, 794 ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__, 795 cpu, curthread->td_oncpu)); 796 797 PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d ok", cpu); 798 } 799 800 /* 801 * Force a context switch. 802 * 803 * We do this by pause'ing for 1 tick -- invoking mi_switch() is not 804 * guaranteed to force a context switch. 805 */ 806 static void 807 pmc_force_context_switch(void) 808 { 809 810 pause("pmcctx", 1); 811 } 812 813 uint64_t 814 pmc_rdtsc(void) 815 { 816 #if defined(__i386__) || defined(__amd64__) 817 if (__predict_true(amd_feature & AMDID_RDTSCP)) 818 return (rdtscp()); 819 else 820 return (rdtsc()); 821 #else 822 return (get_cyclecount()); 823 #endif 824 } 825 826 /* 827 * Get the file name for an executable. This is a simple wrapper 828 * around vn_fullpath(9). 829 */ 830 static void 831 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath) 832 { 833 834 *fullpath = "unknown"; 835 *freepath = NULL; 836 vn_fullpath(v, fullpath, freepath); 837 } 838 839 /* 840 * Remove a process owning PMCs. 841 */ 842 void 843 pmc_remove_owner(struct pmc_owner *po) 844 { 845 struct pmc *pm, *tmp; 846 847 sx_assert(&pmc_sx, SX_XLOCKED); 848 849 PMCDBG1(OWN,ORM,1, "remove-owner po=%p", po); 850 851 /* Remove descriptor from the owner hash table */ 852 LIST_REMOVE(po, po_next); 853 854 /* release all owned PMC descriptors */ 855 LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) { 856 PMCDBG1(OWN,ORM,2, "pmc=%p", pm); 857 KASSERT(pm->pm_owner == po, 858 ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po)); 859 860 pmc_release_pmc_descriptor(pm); /* will unlink from the list */ 861 pmc_destroy_pmc_descriptor(pm); 862 } 863 864 KASSERT(po->po_sscount == 0, 865 ("[pmc,%d] SS count not zero", __LINE__)); 866 KASSERT(LIST_EMPTY(&po->po_pmcs), 867 ("[pmc,%d] PMC list not empty", __LINE__)); 868 869 /* de-configure the log file if present */ 870 if (po->po_flags & PMC_PO_OWNS_LOGFILE) 871 pmclog_deconfigure_log(po); 872 } 873 874 /* 875 * Remove an owner process record if all conditions are met. 876 */ 877 static void 878 pmc_maybe_remove_owner(struct pmc_owner *po) 879 { 880 881 PMCDBG1(OWN,OMR,1, "maybe-remove-owner po=%p", po); 882 883 /* 884 * Remove owner record if 885 * - this process does not own any PMCs 886 * - this process has not allocated a system-wide sampling buffer 887 */ 888 if (LIST_EMPTY(&po->po_pmcs) && 889 ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) { 890 pmc_remove_owner(po); 891 pmc_destroy_owner_descriptor(po); 892 } 893 } 894 895 /* 896 * Add an association between a target process and a PMC. 897 */ 898 static void 899 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp) 900 { 901 struct pmc_target *pt; 902 struct pmc_thread *pt_td __diagused; 903 int ri; 904 905 sx_assert(&pmc_sx, SX_XLOCKED); 906 KASSERT(pm != NULL && pp != NULL, 907 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp)); 908 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)), 909 ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d", 910 __LINE__, pm, pp->pp_proc->p_pid)); 911 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1), 912 ("[pmc,%d] Illegal reference count %d for process record %p", 913 __LINE__, pp->pp_refcnt, (void *) pp)); 914 915 ri = PMC_TO_ROWINDEX(pm); 916 917 PMCDBG3(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p", 918 pm, ri, pp); 919 920 #ifdef HWPMC_DEBUG 921 LIST_FOREACH(pt, &pm->pm_targets, pt_next) { 922 if (pt->pt_process == pp) 923 KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets", 924 __LINE__, pp, pm)); 925 } 926 #endif 927 pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK | M_ZERO); 928 pt->pt_process = pp; 929 930 LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next); 931 932 atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc, 933 (uintptr_t)pm); 934 935 if (pm->pm_owner->po_owner == pp->pp_proc) 936 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER; 937 938 /* 939 * Initialize the per-process values at this row index. 940 */ 941 pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ? 942 pm->pm_sc.pm_reloadcount : 0; 943 pp->pp_refcnt++; 944 945 #ifdef INVARIANTS 946 /* Confirm that the per-thread values at this row index are cleared. */ 947 if (PMC_TO_MODE(pm) == PMC_MODE_TS) { 948 mtx_lock_spin(pp->pp_tdslock); 949 LIST_FOREACH(pt_td, &pp->pp_tds, pt_next) { 950 KASSERT(pt_td->pt_pmcs[ri].pt_pmcval == (pmc_value_t) 0, 951 ("[pmc,%d] pt_pmcval not cleared for pid=%d at " 952 "ri=%d", __LINE__, pp->pp_proc->p_pid, ri)); 953 } 954 mtx_unlock_spin(pp->pp_tdslock); 955 } 956 #endif 957 } 958 959 /* 960 * Removes the association between a target process and a PMC. 961 */ 962 static void 963 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp) 964 { 965 int ri; 966 struct proc *p; 967 struct pmc_target *ptgt; 968 struct pmc_thread *pt; 969 970 sx_assert(&pmc_sx, SX_XLOCKED); 971 972 KASSERT(pm != NULL && pp != NULL, 973 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp)); 974 975 KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc, 976 ("[pmc,%d] Illegal ref count %d on process record %p", 977 __LINE__, pp->pp_refcnt, (void *) pp)); 978 979 ri = PMC_TO_ROWINDEX(pm); 980 981 PMCDBG3(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p", 982 pm, ri, pp); 983 984 KASSERT(pp->pp_pmcs[ri].pp_pmc == pm, 985 ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__, 986 ri, pm, pp->pp_pmcs[ri].pp_pmc)); 987 988 pp->pp_pmcs[ri].pp_pmc = NULL; 989 pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t)0; 990 991 /* Clear the per-thread values at this row index. */ 992 if (PMC_TO_MODE(pm) == PMC_MODE_TS) { 993 mtx_lock_spin(pp->pp_tdslock); 994 LIST_FOREACH(pt, &pp->pp_tds, pt_next) 995 pt->pt_pmcs[ri].pt_pmcval = (pmc_value_t)0; 996 mtx_unlock_spin(pp->pp_tdslock); 997 } 998 999 /* Remove owner-specific flags */ 1000 if (pm->pm_owner->po_owner == pp->pp_proc) { 1001 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS; 1002 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER; 1003 } 1004 1005 pp->pp_refcnt--; 1006 1007 /* Remove the target process from the PMC structure */ 1008 LIST_FOREACH(ptgt, &pm->pm_targets, pt_next) 1009 if (ptgt->pt_process == pp) 1010 break; 1011 1012 KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found " 1013 "in pmc %p", __LINE__, pp->pp_proc, pp, pm)); 1014 1015 LIST_REMOVE(ptgt, pt_next); 1016 free(ptgt, M_PMC); 1017 1018 /* if the PMC now lacks targets, send the owner a SIGIO */ 1019 if (LIST_EMPTY(&pm->pm_targets)) { 1020 p = pm->pm_owner->po_owner; 1021 PROC_LOCK(p); 1022 kern_psignal(p, SIGIO); 1023 PROC_UNLOCK(p); 1024 1025 PMCDBG2(PRC,SIG,2, "signalling proc=%p signal=%d", p, SIGIO); 1026 } 1027 } 1028 1029 /* 1030 * Check if PMC 'pm' may be attached to target process 't'. 1031 */ 1032 1033 static int 1034 pmc_can_attach(struct pmc *pm, struct proc *t) 1035 { 1036 struct proc *o; /* pmc owner */ 1037 struct ucred *oc, *tc; /* owner, target credentials */ 1038 int decline_attach, i; 1039 1040 /* 1041 * A PMC's owner can always attach that PMC to itself. 1042 */ 1043 1044 if ((o = pm->pm_owner->po_owner) == t) 1045 return 0; 1046 1047 PROC_LOCK(o); 1048 oc = o->p_ucred; 1049 crhold(oc); 1050 PROC_UNLOCK(o); 1051 1052 PROC_LOCK(t); 1053 tc = t->p_ucred; 1054 crhold(tc); 1055 PROC_UNLOCK(t); 1056 1057 /* 1058 * The effective uid of the PMC owner should match at least one 1059 * of the {effective,real,saved} uids of the target process. 1060 */ 1061 1062 decline_attach = oc->cr_uid != tc->cr_uid && 1063 oc->cr_uid != tc->cr_svuid && 1064 oc->cr_uid != tc->cr_ruid; 1065 1066 /* 1067 * Every one of the target's group ids, must be in the owner's 1068 * group list. 1069 */ 1070 for (i = 0; !decline_attach && i < tc->cr_ngroups; i++) 1071 decline_attach = !groupmember(tc->cr_groups[i], oc); 1072 1073 /* check the read and saved gids too */ 1074 if (decline_attach == 0) 1075 decline_attach = !groupmember(tc->cr_rgid, oc) || 1076 !groupmember(tc->cr_svgid, oc); 1077 1078 crfree(tc); 1079 crfree(oc); 1080 1081 return !decline_attach; 1082 } 1083 1084 /* 1085 * Attach a process to a PMC. 1086 */ 1087 static int 1088 pmc_attach_one_process(struct proc *p, struct pmc *pm) 1089 { 1090 int ri, error; 1091 char *fullpath, *freepath; 1092 struct pmc_process *pp; 1093 1094 sx_assert(&pmc_sx, SX_XLOCKED); 1095 1096 PMCDBG5(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm, 1097 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm); 1098 1099 /* 1100 * Locate the process descriptor corresponding to process 'p', 1101 * allocating space as needed. 1102 * 1103 * Verify that rowindex 'pm_rowindex' is free in the process 1104 * descriptor. 1105 * 1106 * If not, allocate space for a descriptor and link the 1107 * process descriptor and PMC. 1108 */ 1109 ri = PMC_TO_ROWINDEX(pm); 1110 1111 /* mark process as using HWPMCs */ 1112 PROC_LOCK(p); 1113 p->p_flag |= P_HWPMC; 1114 PROC_UNLOCK(p); 1115 1116 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL) { 1117 error = ENOMEM; 1118 goto fail; 1119 } 1120 1121 if (pp->pp_pmcs[ri].pp_pmc == pm) {/* already present at slot [ri] */ 1122 error = EEXIST; 1123 goto fail; 1124 } 1125 1126 if (pp->pp_pmcs[ri].pp_pmc != NULL) { 1127 error = EBUSY; 1128 goto fail; 1129 } 1130 1131 pmc_link_target_process(pm, pp); 1132 1133 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) && 1134 (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0) 1135 pm->pm_flags |= PMC_F_NEEDS_LOGFILE; 1136 1137 pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */ 1138 1139 /* issue an attach event to a configured log file */ 1140 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) { 1141 if (p->p_flag & P_KPROC) { 1142 fullpath = kernelname; 1143 freepath = NULL; 1144 } else { 1145 pmc_getfilename(p->p_textvp, &fullpath, &freepath); 1146 pmclog_process_pmcattach(pm, p->p_pid, fullpath); 1147 } 1148 free(freepath, M_TEMP); 1149 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) 1150 pmc_log_process_mappings(pm->pm_owner, p); 1151 } 1152 1153 return (0); 1154 fail: 1155 PROC_LOCK(p); 1156 p->p_flag &= ~P_HWPMC; 1157 PROC_UNLOCK(p); 1158 return (error); 1159 } 1160 1161 /* 1162 * Attach a process and optionally its children 1163 */ 1164 static int 1165 pmc_attach_process(struct proc *p, struct pmc *pm) 1166 { 1167 int error; 1168 struct proc *top; 1169 1170 sx_assert(&pmc_sx, SX_XLOCKED); 1171 1172 PMCDBG5(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm, 1173 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm); 1174 1175 /* 1176 * If this PMC successfully allowed a GETMSR operation 1177 * in the past, disallow further ATTACHes. 1178 */ 1179 if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0) 1180 return (EPERM); 1181 1182 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0) 1183 return (pmc_attach_one_process(p, pm)); 1184 1185 /* 1186 * Traverse all child processes, attaching them to 1187 * this PMC. 1188 */ 1189 sx_slock(&proctree_lock); 1190 1191 top = p; 1192 for (;;) { 1193 if ((error = pmc_attach_one_process(p, pm)) != 0) 1194 break; 1195 if (!LIST_EMPTY(&p->p_children)) 1196 p = LIST_FIRST(&p->p_children); 1197 else for (;;) { 1198 if (p == top) 1199 goto done; 1200 if (LIST_NEXT(p, p_sibling)) { 1201 p = LIST_NEXT(p, p_sibling); 1202 break; 1203 } 1204 p = p->p_pptr; 1205 } 1206 } 1207 1208 if (error != 0) 1209 (void)pmc_detach_process(top, pm); 1210 1211 done: 1212 sx_sunlock(&proctree_lock); 1213 return (error); 1214 } 1215 1216 /* 1217 * Detach a process from a PMC. If there are no other PMCs tracking 1218 * this process, remove the process structure from its hash table. If 1219 * 'flags' contains PMC_FLAG_REMOVE, then free the process structure. 1220 */ 1221 static int 1222 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags) 1223 { 1224 int ri; 1225 struct pmc_process *pp; 1226 1227 sx_assert(&pmc_sx, SX_XLOCKED); 1228 1229 KASSERT(pm != NULL, 1230 ("[pmc,%d] null pm pointer", __LINE__)); 1231 1232 ri = PMC_TO_ROWINDEX(pm); 1233 1234 PMCDBG6(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x", 1235 pm, ri, p, p->p_pid, p->p_comm, flags); 1236 1237 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) 1238 return (ESRCH); 1239 1240 if (pp->pp_pmcs[ri].pp_pmc != pm) 1241 return (EINVAL); 1242 1243 pmc_unlink_target_process(pm, pp); 1244 1245 /* Issue a detach entry if a log file is configured */ 1246 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) 1247 pmclog_process_pmcdetach(pm, p->p_pid); 1248 1249 /* 1250 * If there are no PMCs targeting this process, we remove its 1251 * descriptor from the target hash table and unset the P_HWPMC 1252 * flag in the struct proc. 1253 */ 1254 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc, 1255 ("[pmc,%d] Illegal refcnt %d for process struct %p", 1256 __LINE__, pp->pp_refcnt, pp)); 1257 1258 if (pp->pp_refcnt != 0) /* still a target of some PMC */ 1259 return (0); 1260 1261 pmc_remove_process_descriptor(pp); 1262 1263 if (flags & PMC_FLAG_REMOVE) 1264 pmc_destroy_process_descriptor(pp); 1265 1266 PROC_LOCK(p); 1267 p->p_flag &= ~P_HWPMC; 1268 PROC_UNLOCK(p); 1269 1270 return (0); 1271 } 1272 1273 /* 1274 * Detach a process and optionally its descendants from a PMC. 1275 */ 1276 static int 1277 pmc_detach_process(struct proc *p, struct pmc *pm) 1278 { 1279 struct proc *top; 1280 1281 sx_assert(&pmc_sx, SX_XLOCKED); 1282 1283 PMCDBG5(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm, 1284 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm); 1285 1286 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0) 1287 return (pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE)); 1288 1289 /* 1290 * Traverse all children, detaching them from this PMC. We 1291 * ignore errors since we could be detaching a PMC from a 1292 * partially attached proc tree. 1293 */ 1294 sx_slock(&proctree_lock); 1295 1296 top = p; 1297 for (;;) { 1298 (void)pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE); 1299 1300 if (!LIST_EMPTY(&p->p_children)) { 1301 p = LIST_FIRST(&p->p_children); 1302 } else { 1303 for (;;) { 1304 if (p == top) 1305 goto done; 1306 if (LIST_NEXT(p, p_sibling)) { 1307 p = LIST_NEXT(p, p_sibling); 1308 break; 1309 } 1310 p = p->p_pptr; 1311 } 1312 } 1313 } 1314 done: 1315 sx_sunlock(&proctree_lock); 1316 if (LIST_EMPTY(&pm->pm_targets)) 1317 pm->pm_flags &= ~PMC_F_ATTACH_DONE; 1318 1319 return (0); 1320 } 1321 1322 /* 1323 * Handle events after an exec() for a process: 1324 * - Inform log owners of the new exec() event 1325 * - Release any PMCs owned by the process before the exec() 1326 * - Detach PMCs from the target if required 1327 */ 1328 static void 1329 pmc_process_exec(struct thread *td, struct pmckern_procexec *pk) 1330 { 1331 struct pmc *pm; 1332 struct pmc_owner *po; 1333 struct pmc_process *pp; 1334 struct proc *p; 1335 char *fullpath, *freepath; 1336 u_int ri; 1337 bool is_using_hwpmcs; 1338 1339 sx_assert(&pmc_sx, SX_XLOCKED); 1340 1341 p = td->td_proc; 1342 pmc_getfilename(p->p_textvp, &fullpath, &freepath); 1343 1344 PMC_EPOCH_ENTER(); 1345 /* Inform owners of SS mode PMCs of the exec event. */ 1346 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 1347 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) { 1348 pmclog_process_procexec(po, PMC_ID_INVALID, p->p_pid, 1349 pk->pm_baseaddr, pk->pm_dynaddr, fullpath); 1350 } 1351 } 1352 PMC_EPOCH_EXIT(); 1353 1354 PROC_LOCK(p); 1355 is_using_hwpmcs = (p->p_flag & P_HWPMC) != 0; 1356 PROC_UNLOCK(p); 1357 1358 if (!is_using_hwpmcs) { 1359 if (freepath != NULL) 1360 free(freepath, M_TEMP); 1361 return; 1362 } 1363 1364 /* 1365 * PMCs are not inherited across an exec(): remove any PMCs that this 1366 * process is the owner of. 1367 */ 1368 if ((po = pmc_find_owner_descriptor(p)) != NULL) { 1369 pmc_remove_owner(po); 1370 pmc_destroy_owner_descriptor(po); 1371 } 1372 1373 /* 1374 * If the process being exec'ed is not the target of any PMC, we are 1375 * done. 1376 */ 1377 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) { 1378 if (freepath != NULL) 1379 free(freepath, M_TEMP); 1380 return; 1381 } 1382 1383 /* 1384 * Log the exec event to all monitoring owners. Skip owners who have 1385 * already received the event because they had system sampling PMCs 1386 * active. 1387 */ 1388 for (ri = 0; ri < md->pmd_npmc; ri++) { 1389 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL) 1390 continue; 1391 1392 po = pm->pm_owner; 1393 if (po->po_sscount == 0 && 1394 (po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) { 1395 pmclog_process_procexec(po, pm->pm_id, p->p_pid, 1396 pk->pm_baseaddr, pk->pm_dynaddr, fullpath); 1397 } 1398 } 1399 1400 if (freepath != NULL) 1401 free(freepath, M_TEMP); 1402 1403 PMCDBG4(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d", 1404 p, p->p_pid, p->p_comm, pk->pm_credentialschanged); 1405 1406 if (pk->pm_credentialschanged == 0) /* no change */ 1407 return; 1408 1409 /* 1410 * If the newly exec()'ed process has a different credential 1411 * than before, allow it to be the target of a PMC only if 1412 * the PMC's owner has sufficient privilege. 1413 */ 1414 for (ri = 0; ri < md->pmd_npmc; ri++) { 1415 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) { 1416 if (pmc_can_attach(pm, td->td_proc) != 0) { 1417 pmc_detach_one_process(td->td_proc, pm, 1418 PMC_FLAG_NONE); 1419 } 1420 } 1421 } 1422 1423 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= md->pmd_npmc, 1424 ("[pmc,%d] Illegal ref count %u on pp %p", __LINE__, 1425 pp->pp_refcnt, pp)); 1426 1427 /* 1428 * If this process is no longer the target of any 1429 * PMCs, we can remove the process entry and free 1430 * up space. 1431 */ 1432 if (pp->pp_refcnt == 0) { 1433 pmc_remove_process_descriptor(pp); 1434 pmc_destroy_process_descriptor(pp); 1435 } 1436 } 1437 1438 /* 1439 * Thread context switch IN. 1440 */ 1441 static void 1442 pmc_process_csw_in(struct thread *td) 1443 { 1444 struct pmc *pm; 1445 struct pmc_classdep *pcd; 1446 struct pmc_cpu *pc; 1447 struct pmc_hw *phw __diagused; 1448 struct pmc_process *pp; 1449 struct pmc_thread *pt; 1450 struct proc *p; 1451 pmc_value_t newvalue; 1452 int cpu; 1453 u_int adjri, ri; 1454 1455 p = td->td_proc; 1456 pt = NULL; 1457 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL) 1458 return; 1459 1460 KASSERT(pp->pp_proc == td->td_proc, 1461 ("[pmc,%d] not my thread state", __LINE__)); 1462 1463 critical_enter(); /* no preemption from this point */ 1464 1465 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */ 1466 1467 PMCDBG5(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p, 1468 p->p_pid, p->p_comm, pp); 1469 1470 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(), 1471 ("[pmc,%d] weird CPU id %d", __LINE__, cpu)); 1472 1473 pc = pmc_pcpu[cpu]; 1474 for (ri = 0; ri < md->pmd_npmc; ri++) { 1475 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL) 1476 continue; 1477 1478 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)), 1479 ("[pmc,%d] Target PMC in non-virtual mode (%d)", 1480 __LINE__, PMC_TO_MODE(pm))); 1481 KASSERT(PMC_TO_ROWINDEX(pm) == ri, 1482 ("[pmc,%d] Row index mismatch pmc %d != ri %d", 1483 __LINE__, PMC_TO_ROWINDEX(pm), ri)); 1484 1485 /* 1486 * Only PMCs that are marked as 'RUNNING' need 1487 * be placed on hardware. 1488 */ 1489 if (pm->pm_state != PMC_STATE_RUNNING) 1490 continue; 1491 1492 KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0, 1493 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm, 1494 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 1495 1496 /* increment PMC runcount */ 1497 counter_u64_add(pm->pm_runcount, 1); 1498 1499 /* configure the HWPMC we are going to use. */ 1500 pcd = pmc_ri_to_classdep(md, ri, &adjri); 1501 (void)pcd->pcd_config_pmc(cpu, adjri, pm); 1502 1503 phw = pc->pc_hwpmcs[ri]; 1504 1505 KASSERT(phw != NULL, 1506 ("[pmc,%d] null hw pointer", __LINE__)); 1507 1508 KASSERT(phw->phw_pmc == pm, 1509 ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__, 1510 phw->phw_pmc, pm)); 1511 1512 /* 1513 * Write out saved value and start the PMC. 1514 * 1515 * Sampling PMCs use a per-thread value, while 1516 * counting mode PMCs use a per-pmc value that is 1517 * inherited across descendants. 1518 */ 1519 if (PMC_TO_MODE(pm) == PMC_MODE_TS) { 1520 if (pt == NULL) 1521 pt = pmc_find_thread_descriptor(pp, td, 1522 PMC_FLAG_NONE); 1523 1524 KASSERT(pt != NULL, 1525 ("[pmc,%d] No thread found for td=%p", __LINE__, 1526 td)); 1527 1528 mtx_pool_lock_spin(pmc_mtxpool, pm); 1529 1530 /* 1531 * If we have a thread descriptor, use the per-thread 1532 * counter in the descriptor. If not, we will use 1533 * a per-process counter. 1534 * 1535 * TODO: Remove the per-process "safety net" once 1536 * we have thoroughly tested that we don't hit the 1537 * above assert. 1538 */ 1539 if (pt != NULL) { 1540 if (pt->pt_pmcs[ri].pt_pmcval > 0) 1541 newvalue = pt->pt_pmcs[ri].pt_pmcval; 1542 else 1543 newvalue = pm->pm_sc.pm_reloadcount; 1544 } else { 1545 /* 1546 * Use the saved value calculated after the most 1547 * recent time a thread using the shared counter 1548 * switched out. Reset the saved count in case 1549 * another thread from this process switches in 1550 * before any threads switch out. 1551 */ 1552 newvalue = pp->pp_pmcs[ri].pp_pmcval; 1553 pp->pp_pmcs[ri].pp_pmcval = 1554 pm->pm_sc.pm_reloadcount; 1555 } 1556 mtx_pool_unlock_spin(pmc_mtxpool, pm); 1557 KASSERT(newvalue > 0 && newvalue <= 1558 pm->pm_sc.pm_reloadcount, 1559 ("[pmc,%d] pmcval outside of expected range cpu=%d " 1560 "ri=%d pmcval=%jx pm_reloadcount=%jx", __LINE__, 1561 cpu, ri, newvalue, pm->pm_sc.pm_reloadcount)); 1562 } else { 1563 KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC, 1564 ("[pmc,%d] illegal mode=%d", __LINE__, 1565 PMC_TO_MODE(pm))); 1566 mtx_pool_lock_spin(pmc_mtxpool, pm); 1567 newvalue = PMC_PCPU_SAVED(cpu, ri) = 1568 pm->pm_gv.pm_savedvalue; 1569 mtx_pool_unlock_spin(pmc_mtxpool, pm); 1570 } 1571 1572 PMCDBG3(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue); 1573 1574 (void)pcd->pcd_write_pmc(cpu, adjri, pm, newvalue); 1575 1576 /* If a sampling mode PMC, reset stalled state. */ 1577 if (PMC_TO_MODE(pm) == PMC_MODE_TS) 1578 pm->pm_pcpu_state[cpu].pps_stalled = 0; 1579 1580 /* Indicate that we desire this to run. */ 1581 pm->pm_pcpu_state[cpu].pps_cpustate = 1; 1582 1583 /* Start the PMC. */ 1584 (void)pcd->pcd_start_pmc(cpu, adjri, pm); 1585 } 1586 1587 /* 1588 * Perform any other architecture/cpu dependent thread 1589 * switch-in actions. 1590 */ 1591 (void)(*md->pmd_switch_in)(pc, pp); 1592 1593 critical_exit(); 1594 } 1595 1596 /* 1597 * Thread context switch OUT. 1598 */ 1599 static void 1600 pmc_process_csw_out(struct thread *td) 1601 { 1602 struct pmc *pm; 1603 struct pmc_classdep *pcd; 1604 struct pmc_cpu *pc; 1605 struct pmc_process *pp; 1606 struct pmc_thread *pt = NULL; 1607 struct proc *p; 1608 pmc_value_t newvalue; 1609 int64_t tmp; 1610 enum pmc_mode mode; 1611 int cpu; 1612 u_int adjri, ri; 1613 1614 /* 1615 * Locate our process descriptor; this may be NULL if 1616 * this process is exiting and we have already removed 1617 * the process from the target process table. 1618 * 1619 * Note that due to kernel preemption, multiple 1620 * context switches may happen while the process is 1621 * exiting. 1622 * 1623 * Note also that if the target process cannot be 1624 * found we still need to deconfigure any PMCs that 1625 * are currently running on hardware. 1626 */ 1627 p = td->td_proc; 1628 pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE); 1629 1630 critical_enter(); 1631 1632 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */ 1633 1634 PMCDBG5(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p, 1635 p->p_pid, p->p_comm, pp); 1636 1637 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(), 1638 ("[pmc,%d weird CPU id %d", __LINE__, cpu)); 1639 1640 pc = pmc_pcpu[cpu]; 1641 1642 /* 1643 * When a PMC gets unlinked from a target PMC, it will 1644 * be removed from the target's pp_pmc[] array. 1645 * 1646 * However, on a MP system, the target could have been 1647 * executing on another CPU at the time of the unlink. 1648 * So, at context switch OUT time, we need to look at 1649 * the hardware to determine if a PMC is scheduled on 1650 * it. 1651 */ 1652 for (ri = 0; ri < md->pmd_npmc; ri++) { 1653 pcd = pmc_ri_to_classdep(md, ri, &adjri); 1654 pm = NULL; 1655 (void)(*pcd->pcd_get_config)(cpu, adjri, &pm); 1656 1657 if (pm == NULL) /* nothing at this row index */ 1658 continue; 1659 1660 mode = PMC_TO_MODE(pm); 1661 if (!PMC_IS_VIRTUAL_MODE(mode)) 1662 continue; /* not a process virtual PMC */ 1663 1664 KASSERT(PMC_TO_ROWINDEX(pm) == ri, 1665 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)", 1666 __LINE__, PMC_TO_ROWINDEX(pm), ri)); 1667 1668 /* 1669 * Change desired state, and then stop if not stalled. 1670 * This two-step dance should avoid race conditions where 1671 * an interrupt re-enables the PMC after this code has 1672 * already checked the pm_stalled flag. 1673 */ 1674 pm->pm_pcpu_state[cpu].pps_cpustate = 0; 1675 if (pm->pm_pcpu_state[cpu].pps_stalled == 0) 1676 (void)pcd->pcd_stop_pmc(cpu, adjri, pm); 1677 1678 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 1679 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm, 1680 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 1681 1682 /* reduce this PMC's runcount */ 1683 counter_u64_add(pm->pm_runcount, -1); 1684 1685 /* 1686 * If this PMC is associated with this process, 1687 * save the reading. 1688 */ 1689 if (pm->pm_state != PMC_STATE_DELETED && pp != NULL && 1690 pp->pp_pmcs[ri].pp_pmc != NULL) { 1691 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc, 1692 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__, 1693 pm, ri, pp->pp_pmcs[ri].pp_pmc)); 1694 KASSERT(pp->pp_refcnt > 0, 1695 ("[pmc,%d] pp refcnt = %d", __LINE__, 1696 pp->pp_refcnt)); 1697 1698 (void)pcd->pcd_read_pmc(cpu, adjri, pm, &newvalue); 1699 1700 if (mode == PMC_MODE_TS) { 1701 PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d val=%jd (samp)", 1702 cpu, ri, newvalue); 1703 1704 if (pt == NULL) 1705 pt = pmc_find_thread_descriptor(pp, td, 1706 PMC_FLAG_NONE); 1707 1708 KASSERT(pt != NULL, 1709 ("[pmc,%d] No thread found for td=%p", 1710 __LINE__, td)); 1711 1712 mtx_pool_lock_spin(pmc_mtxpool, pm); 1713 1714 /* 1715 * If we have a thread descriptor, save the 1716 * per-thread counter in the descriptor. If not, 1717 * we will update the per-process counter. 1718 * 1719 * TODO: Remove the per-process "safety net" 1720 * once we have thoroughly tested that we 1721 * don't hit the above assert. 1722 */ 1723 if (pt != NULL) { 1724 pt->pt_pmcs[ri].pt_pmcval = newvalue; 1725 } else { 1726 /* 1727 * For sampling process-virtual PMCs, 1728 * newvalue is the number of events to 1729 * be seen until the next sampling 1730 * interrupt. We can just add the events 1731 * left from this invocation to the 1732 * counter, then adjust in case we 1733 * overflow our range. 1734 * 1735 * (Recall that we reload the counter 1736 * every time we use it.) 1737 */ 1738 pp->pp_pmcs[ri].pp_pmcval += newvalue; 1739 if (pp->pp_pmcs[ri].pp_pmcval > 1740 pm->pm_sc.pm_reloadcount) { 1741 pp->pp_pmcs[ri].pp_pmcval -= 1742 pm->pm_sc.pm_reloadcount; 1743 } 1744 } 1745 mtx_pool_unlock_spin(pmc_mtxpool, pm); 1746 } else { 1747 tmp = newvalue - PMC_PCPU_SAVED(cpu, ri); 1748 1749 PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd (count)", 1750 cpu, ri, tmp); 1751 1752 /* 1753 * For counting process-virtual PMCs, 1754 * we expect the count to be 1755 * increasing monotonically, modulo a 64 1756 * bit wraparound. 1757 */ 1758 KASSERT(tmp >= 0, 1759 ("[pmc,%d] negative increment cpu=%d " 1760 "ri=%d newvalue=%jx saved=%jx " 1761 "incr=%jx", __LINE__, cpu, ri, 1762 newvalue, PMC_PCPU_SAVED(cpu, ri), tmp)); 1763 1764 mtx_pool_lock_spin(pmc_mtxpool, pm); 1765 pm->pm_gv.pm_savedvalue += tmp; 1766 pp->pp_pmcs[ri].pp_pmcval += tmp; 1767 mtx_pool_unlock_spin(pmc_mtxpool, pm); 1768 1769 if (pm->pm_flags & PMC_F_LOG_PROCCSW) 1770 pmclog_process_proccsw(pm, pp, tmp, td); 1771 } 1772 } 1773 1774 /* Mark hardware as free. */ 1775 (void)pcd->pcd_config_pmc(cpu, adjri, NULL); 1776 } 1777 1778 /* 1779 * Perform any other architecture/cpu dependent thread 1780 * switch out functions. 1781 */ 1782 (void)(*md->pmd_switch_out)(pc, pp); 1783 1784 critical_exit(); 1785 } 1786 1787 /* 1788 * A new thread for a process. 1789 */ 1790 static void 1791 pmc_process_thread_add(struct thread *td) 1792 { 1793 struct pmc_process *pmc; 1794 1795 pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE); 1796 if (pmc != NULL) 1797 pmc_find_thread_descriptor(pmc, td, PMC_FLAG_ALLOCATE); 1798 } 1799 1800 /* 1801 * A thread delete for a process. 1802 */ 1803 static void 1804 pmc_process_thread_delete(struct thread *td) 1805 { 1806 struct pmc_process *pmc; 1807 1808 pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE); 1809 if (pmc != NULL) 1810 pmc_thread_descriptor_pool_free(pmc_find_thread_descriptor(pmc, 1811 td, PMC_FLAG_REMOVE)); 1812 } 1813 1814 /* 1815 * A userret() call for a thread. 1816 */ 1817 static void 1818 pmc_process_thread_userret(struct thread *td) 1819 { 1820 sched_pin(); 1821 pmc_capture_user_callchain(curcpu, PMC_UR, td->td_frame); 1822 sched_unpin(); 1823 } 1824 1825 /* 1826 * A mapping change for a process. 1827 */ 1828 static void 1829 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm) 1830 { 1831 const struct pmc *pm; 1832 const struct pmc_process *pp; 1833 struct pmc_owner *po; 1834 char *fullpath, *freepath; 1835 pid_t pid; 1836 int ri; 1837 1838 MPASS(!in_epoch(global_epoch_preempt)); 1839 1840 freepath = fullpath = NULL; 1841 pmc_getfilename((struct vnode *)pkm->pm_file, &fullpath, &freepath); 1842 1843 pid = td->td_proc->p_pid; 1844 1845 PMC_EPOCH_ENTER(); 1846 /* Inform owners of all system-wide sampling PMCs. */ 1847 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 1848 if (po->po_flags & PMC_PO_OWNS_LOGFILE) 1849 pmclog_process_map_in(po, pid, pkm->pm_address, 1850 fullpath); 1851 } 1852 1853 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL) 1854 goto done; 1855 1856 /* 1857 * Inform sampling PMC owners tracking this process. 1858 */ 1859 for (ri = 0; ri < md->pmd_npmc; ri++) { 1860 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL && 1861 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) { 1862 pmclog_process_map_in(pm->pm_owner, 1863 pid, pkm->pm_address, fullpath); 1864 } 1865 } 1866 1867 done: 1868 if (freepath != NULL) 1869 free(freepath, M_TEMP); 1870 PMC_EPOCH_EXIT(); 1871 } 1872 1873 /* 1874 * Log an munmap request. 1875 */ 1876 static void 1877 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm) 1878 { 1879 const struct pmc *pm; 1880 const struct pmc_process *pp; 1881 struct pmc_owner *po; 1882 pid_t pid; 1883 int ri; 1884 1885 pid = td->td_proc->p_pid; 1886 1887 PMC_EPOCH_ENTER(); 1888 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 1889 if (po->po_flags & PMC_PO_OWNS_LOGFILE) 1890 pmclog_process_map_out(po, pid, pkm->pm_address, 1891 pkm->pm_address + pkm->pm_size); 1892 } 1893 PMC_EPOCH_EXIT(); 1894 1895 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL) 1896 return; 1897 1898 for (ri = 0; ri < md->pmd_npmc; ri++) { 1899 pm = pp->pp_pmcs[ri].pp_pmc; 1900 if (pm != NULL && PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) { 1901 pmclog_process_map_out(pm->pm_owner, pid, 1902 pkm->pm_address, pkm->pm_address + pkm->pm_size); 1903 } 1904 } 1905 } 1906 1907 /* 1908 * Log mapping information about the kernel. 1909 */ 1910 static void 1911 pmc_log_kernel_mappings(struct pmc *pm) 1912 { 1913 struct pmc_owner *po; 1914 struct pmckern_map_in *km, *kmbase; 1915 1916 MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx)); 1917 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)), 1918 ("[pmc,%d] non-sampling PMC (%p) desires mapping information", 1919 __LINE__, (void *) pm)); 1920 1921 po = pm->pm_owner; 1922 if ((po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE) != 0) 1923 return; 1924 1925 if (PMC_TO_MODE(pm) == PMC_MODE_SS) 1926 pmc_process_allproc(pm); 1927 1928 /* 1929 * Log the current set of kernel modules. 1930 */ 1931 kmbase = linker_hwpmc_list_objects(); 1932 for (km = kmbase; km->pm_file != NULL; km++) { 1933 PMCDBG2(LOG,REG,1,"%s %p", (char *)km->pm_file, 1934 (void *)km->pm_address); 1935 pmclog_process_map_in(po, (pid_t)-1, km->pm_address, 1936 km->pm_file); 1937 } 1938 free(kmbase, M_LINKER); 1939 1940 po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE; 1941 } 1942 1943 /* 1944 * Log the mappings for a single process. 1945 */ 1946 static void 1947 pmc_log_process_mappings(struct pmc_owner *po, struct proc *p) 1948 { 1949 vm_map_t map; 1950 vm_map_entry_t entry; 1951 vm_object_t obj, lobj, tobj; 1952 vm_offset_t last_end; 1953 vm_offset_t start_addr; 1954 struct vnode *vp, *last_vp; 1955 struct vmspace *vm; 1956 char *fullpath, *freepath; 1957 u_int last_timestamp; 1958 1959 last_vp = NULL; 1960 last_end = (vm_offset_t)0; 1961 fullpath = freepath = NULL; 1962 1963 if ((vm = vmspace_acquire_ref(p)) == NULL) 1964 return; 1965 1966 map = &vm->vm_map; 1967 vm_map_lock_read(map); 1968 VM_MAP_ENTRY_FOREACH(entry, map) { 1969 if (entry == NULL) { 1970 PMCDBG2(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly " 1971 "NULL! pid=%d vm_map=%p\n", p->p_pid, map); 1972 break; 1973 } 1974 1975 /* 1976 * We only care about executable map entries. 1977 */ 1978 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 || 1979 (entry->protection & VM_PROT_EXECUTE) == 0 || 1980 entry->object.vm_object == NULL) { 1981 continue; 1982 } 1983 1984 obj = entry->object.vm_object; 1985 VM_OBJECT_RLOCK(obj); 1986 1987 /* 1988 * Walk the backing_object list to find the base (non-shadowed) 1989 * vm_object. 1990 */ 1991 for (lobj = tobj = obj; tobj != NULL; 1992 tobj = tobj->backing_object) { 1993 if (tobj != obj) 1994 VM_OBJECT_RLOCK(tobj); 1995 if (lobj != obj) 1996 VM_OBJECT_RUNLOCK(lobj); 1997 lobj = tobj; 1998 } 1999 2000 /* 2001 * At this point lobj is the base vm_object and it is locked. 2002 */ 2003 if (lobj == NULL) { 2004 PMCDBG3(LOG,OPS,2, 2005 "hwpmc: lobj unexpectedly NULL! pid=%d " 2006 "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj); 2007 VM_OBJECT_RUNLOCK(obj); 2008 continue; 2009 } 2010 2011 vp = vm_object_vnode(lobj); 2012 if (vp == NULL) { 2013 if (lobj != obj) 2014 VM_OBJECT_RUNLOCK(lobj); 2015 VM_OBJECT_RUNLOCK(obj); 2016 continue; 2017 } 2018 2019 /* 2020 * Skip contiguous regions that point to the same vnode, so we 2021 * don't emit redundant MAP-IN directives. 2022 */ 2023 if (entry->start == last_end && vp == last_vp) { 2024 last_end = entry->end; 2025 if (lobj != obj) 2026 VM_OBJECT_RUNLOCK(lobj); 2027 VM_OBJECT_RUNLOCK(obj); 2028 continue; 2029 } 2030 2031 /* 2032 * We don't want to keep the proc's vm_map or this vm_object 2033 * locked while we walk the pathname, since vn_fullpath() can 2034 * sleep. However, if we drop the lock, it's possible for 2035 * concurrent activity to modify the vm_map list. To protect 2036 * against this, we save the vm_map timestamp before we release 2037 * the lock, and check it after we reacquire the lock below. 2038 */ 2039 start_addr = entry->start; 2040 last_end = entry->end; 2041 last_timestamp = map->timestamp; 2042 vm_map_unlock_read(map); 2043 2044 vref(vp); 2045 if (lobj != obj) 2046 VM_OBJECT_RUNLOCK(lobj); 2047 VM_OBJECT_RUNLOCK(obj); 2048 2049 freepath = NULL; 2050 pmc_getfilename(vp, &fullpath, &freepath); 2051 last_vp = vp; 2052 2053 vrele(vp); 2054 2055 vp = NULL; 2056 pmclog_process_map_in(po, p->p_pid, start_addr, fullpath); 2057 if (freepath != NULL) 2058 free(freepath, M_TEMP); 2059 2060 vm_map_lock_read(map); 2061 2062 /* 2063 * If our saved timestamp doesn't match, this means 2064 * that the vm_map was modified out from under us and 2065 * we can't trust our current "entry" pointer. Do a 2066 * new lookup for this entry. If there is no entry 2067 * for this address range, vm_map_lookup_entry() will 2068 * return the previous one, so we always want to go to 2069 * the next entry on the next loop iteration. 2070 * 2071 * There is an edge condition here that can occur if 2072 * there is no entry at or before this address. In 2073 * this situation, vm_map_lookup_entry returns 2074 * &map->header, which would cause our loop to abort 2075 * without processing the rest of the map. However, 2076 * in practice this will never happen for process 2077 * vm_map. This is because the executable's text 2078 * segment is the first mapping in the proc's address 2079 * space, and this mapping is never removed until the 2080 * process exits, so there will always be a non-header 2081 * entry at or before the requested address for 2082 * vm_map_lookup_entry to return. 2083 */ 2084 if (map->timestamp != last_timestamp) 2085 vm_map_lookup_entry(map, last_end - 1, &entry); 2086 } 2087 2088 vm_map_unlock_read(map); 2089 vmspace_free(vm); 2090 return; 2091 } 2092 2093 /* 2094 * Log mappings for all processes in the system. 2095 */ 2096 static void 2097 pmc_log_all_process_mappings(struct pmc_owner *po) 2098 { 2099 struct proc *p, *top; 2100 2101 sx_assert(&pmc_sx, SX_XLOCKED); 2102 2103 if ((p = pfind(1)) == NULL) 2104 panic("[pmc,%d] Cannot find init", __LINE__); 2105 2106 PROC_UNLOCK(p); 2107 2108 sx_slock(&proctree_lock); 2109 2110 top = p; 2111 for (;;) { 2112 pmc_log_process_mappings(po, p); 2113 if (!LIST_EMPTY(&p->p_children)) 2114 p = LIST_FIRST(&p->p_children); 2115 else for (;;) { 2116 if (p == top) 2117 goto done; 2118 if (LIST_NEXT(p, p_sibling)) { 2119 p = LIST_NEXT(p, p_sibling); 2120 break; 2121 } 2122 p = p->p_pptr; 2123 } 2124 } 2125 done: 2126 sx_sunlock(&proctree_lock); 2127 } 2128 2129 #ifdef HWPMC_DEBUG 2130 const char *pmc_hooknames[] = { 2131 /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */ 2132 "", 2133 "EXEC", 2134 "CSW-IN", 2135 "CSW-OUT", 2136 "SAMPLE", 2137 "UNUSED1", 2138 "UNUSED2", 2139 "MMAP", 2140 "MUNMAP", 2141 "CALLCHAIN-NMI", 2142 "CALLCHAIN-SOFT", 2143 "SOFTSAMPLING", 2144 "THR-CREATE", 2145 "THR-EXIT", 2146 "THR-USERRET", 2147 "THR-CREATE-LOG", 2148 "THR-EXIT-LOG", 2149 "PROC-CREATE-LOG" 2150 }; 2151 #endif 2152 2153 /* 2154 * The 'hook' invoked from the kernel proper 2155 */ 2156 static int 2157 pmc_hook_handler(struct thread *td, int function, void *arg) 2158 { 2159 int cpu; 2160 2161 PMCDBG4(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function, 2162 pmc_hooknames[function], arg); 2163 2164 switch (function) { 2165 case PMC_FN_PROCESS_EXEC: 2166 pmc_process_exec(td, (struct pmckern_procexec *)arg); 2167 break; 2168 2169 case PMC_FN_CSW_IN: 2170 pmc_process_csw_in(td); 2171 break; 2172 2173 case PMC_FN_CSW_OUT: 2174 pmc_process_csw_out(td); 2175 break; 2176 2177 /* 2178 * Process accumulated PC samples. 2179 * 2180 * This function is expected to be called by hardclock() for 2181 * each CPU that has accumulated PC samples. 2182 * 2183 * This function is to be executed on the CPU whose samples 2184 * are being processed. 2185 */ 2186 case PMC_FN_DO_SAMPLES: 2187 /* 2188 * Clear the cpu specific bit in the CPU mask before 2189 * do the rest of the processing. If the NMI handler 2190 * gets invoked after the "atomic_clear_int()" call 2191 * below but before "pmc_process_samples()" gets 2192 * around to processing the interrupt, then we will 2193 * come back here at the next hardclock() tick (and 2194 * may find nothing to do if "pmc_process_samples()" 2195 * had already processed the interrupt). We don't 2196 * lose the interrupt sample. 2197 */ 2198 DPCPU_SET(pmc_sampled, 0); 2199 cpu = PCPU_GET(cpuid); 2200 pmc_process_samples(cpu, PMC_HR); 2201 pmc_process_samples(cpu, PMC_SR); 2202 pmc_process_samples(cpu, PMC_UR); 2203 break; 2204 2205 case PMC_FN_MMAP: 2206 pmc_process_mmap(td, (struct pmckern_map_in *)arg); 2207 break; 2208 2209 case PMC_FN_MUNMAP: 2210 MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx)); 2211 pmc_process_munmap(td, (struct pmckern_map_out *)arg); 2212 break; 2213 2214 case PMC_FN_PROC_CREATE_LOG: 2215 pmc_process_proccreate((struct proc *)arg); 2216 break; 2217 2218 case PMC_FN_USER_CALLCHAIN: 2219 /* 2220 * Record a call chain. 2221 */ 2222 KASSERT(td == curthread, ("[pmc,%d] td != curthread", 2223 __LINE__)); 2224 2225 pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR, 2226 (struct trapframe *)arg); 2227 2228 KASSERT(td->td_pinned == 1, 2229 ("[pmc,%d] invalid td_pinned value", __LINE__)); 2230 sched_unpin(); /* Can migrate safely now. */ 2231 2232 td->td_pflags &= ~TDP_CALLCHAIN; 2233 break; 2234 2235 case PMC_FN_USER_CALLCHAIN_SOFT: 2236 /* 2237 * Record a call chain. 2238 */ 2239 KASSERT(td == curthread, ("[pmc,%d] td != curthread", 2240 __LINE__)); 2241 2242 cpu = PCPU_GET(cpuid); 2243 pmc_capture_user_callchain(cpu, PMC_SR, 2244 (struct trapframe *) arg); 2245 2246 KASSERT(td->td_pinned == 1, 2247 ("[pmc,%d] invalid td_pinned value", __LINE__)); 2248 2249 sched_unpin(); /* Can migrate safely now. */ 2250 2251 td->td_pflags &= ~TDP_CALLCHAIN; 2252 break; 2253 2254 case PMC_FN_SOFT_SAMPLING: 2255 /* 2256 * Call soft PMC sampling intr. 2257 */ 2258 pmc_soft_intr((struct pmckern_soft *)arg); 2259 break; 2260 2261 case PMC_FN_THR_CREATE: 2262 pmc_process_thread_add(td); 2263 pmc_process_threadcreate(td); 2264 break; 2265 2266 case PMC_FN_THR_CREATE_LOG: 2267 pmc_process_threadcreate(td); 2268 break; 2269 2270 case PMC_FN_THR_EXIT: 2271 KASSERT(td == curthread, ("[pmc,%d] td != curthread", 2272 __LINE__)); 2273 pmc_process_thread_delete(td); 2274 pmc_process_threadexit(td); 2275 break; 2276 case PMC_FN_THR_EXIT_LOG: 2277 pmc_process_threadexit(td); 2278 break; 2279 case PMC_FN_THR_USERRET: 2280 KASSERT(td == curthread, ("[pmc,%d] td != curthread", 2281 __LINE__)); 2282 pmc_process_thread_userret(td); 2283 break; 2284 default: 2285 #ifdef HWPMC_DEBUG 2286 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function)); 2287 #endif 2288 break; 2289 } 2290 2291 return (0); 2292 } 2293 2294 /* 2295 * Allocate a 'struct pmc_owner' descriptor in the owner hash table. 2296 */ 2297 static struct pmc_owner * 2298 pmc_allocate_owner_descriptor(struct proc *p) 2299 { 2300 struct pmc_owner *po; 2301 struct pmc_ownerhash *poh; 2302 uint32_t hindex; 2303 2304 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask); 2305 poh = &pmc_ownerhash[hindex]; 2306 2307 /* Allocate space for N pointers and one descriptor struct. */ 2308 po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK | M_ZERO); 2309 po->po_owner = p; 2310 LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */ 2311 2312 TAILQ_INIT(&po->po_logbuffers); 2313 mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN); 2314 2315 PMCDBG4(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p", 2316 p, p->p_pid, p->p_comm, po); 2317 2318 return (po); 2319 } 2320 2321 static void 2322 pmc_destroy_owner_descriptor(struct pmc_owner *po) 2323 { 2324 2325 PMCDBG4(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)", 2326 po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm); 2327 2328 mtx_destroy(&po->po_mtx); 2329 free(po, M_PMC); 2330 } 2331 2332 /* 2333 * Allocate a thread descriptor from the free pool. 2334 * 2335 * NOTE: This *can* return NULL. 2336 */ 2337 static struct pmc_thread * 2338 pmc_thread_descriptor_pool_alloc(void) 2339 { 2340 struct pmc_thread *pt; 2341 2342 mtx_lock_spin(&pmc_threadfreelist_mtx); 2343 if ((pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) { 2344 LIST_REMOVE(pt, pt_next); 2345 pmc_threadfreelist_entries--; 2346 } 2347 mtx_unlock_spin(&pmc_threadfreelist_mtx); 2348 2349 return (pt); 2350 } 2351 2352 /* 2353 * Add a thread descriptor to the free pool. We use this instead of free() 2354 * to maintain a cache of free entries. Additionally, we can safely call 2355 * this function when we cannot call free(), such as in a critical section. 2356 */ 2357 static void 2358 pmc_thread_descriptor_pool_free(struct pmc_thread *pt) 2359 { 2360 2361 if (pt == NULL) 2362 return; 2363 2364 memset(pt, 0, THREADENTRY_SIZE); 2365 mtx_lock_spin(&pmc_threadfreelist_mtx); 2366 LIST_INSERT_HEAD(&pmc_threadfreelist, pt, pt_next); 2367 pmc_threadfreelist_entries++; 2368 if (pmc_threadfreelist_entries > pmc_threadfreelist_max) 2369 taskqueue_enqueue(taskqueue_fast, &free_task); 2370 mtx_unlock_spin(&pmc_threadfreelist_mtx); 2371 } 2372 2373 /* 2374 * An asynchronous task to manage the free list. 2375 */ 2376 static void 2377 pmc_thread_descriptor_pool_free_task(void *arg __unused, int pending __unused) 2378 { 2379 struct pmc_thread *pt; 2380 LIST_HEAD(, pmc_thread) tmplist; 2381 int delta; 2382 2383 LIST_INIT(&tmplist); 2384 2385 /* Determine what changes, if any, we need to make. */ 2386 mtx_lock_spin(&pmc_threadfreelist_mtx); 2387 delta = pmc_threadfreelist_entries - pmc_threadfreelist_max; 2388 while (delta > 0 && (pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) { 2389 delta--; 2390 pmc_threadfreelist_entries--; 2391 LIST_REMOVE(pt, pt_next); 2392 LIST_INSERT_HEAD(&tmplist, pt, pt_next); 2393 } 2394 mtx_unlock_spin(&pmc_threadfreelist_mtx); 2395 2396 /* If there are entries to free, free them. */ 2397 while (!LIST_EMPTY(&tmplist)) { 2398 pt = LIST_FIRST(&tmplist); 2399 LIST_REMOVE(pt, pt_next); 2400 free(pt, M_PMC); 2401 } 2402 } 2403 2404 /* 2405 * Drain the thread free pool, freeing all allocations. 2406 */ 2407 static void 2408 pmc_thread_descriptor_pool_drain(void) 2409 { 2410 struct pmc_thread *pt, *next; 2411 2412 LIST_FOREACH_SAFE(pt, &pmc_threadfreelist, pt_next, next) { 2413 LIST_REMOVE(pt, pt_next); 2414 free(pt, M_PMC); 2415 } 2416 } 2417 2418 /* 2419 * find the descriptor corresponding to thread 'td', adding or removing it 2420 * as specified by 'mode'. 2421 * 2422 * Note that this supports additional mode flags in addition to those 2423 * supported by pmc_find_process_descriptor(): 2424 * PMC_FLAG_NOWAIT: Causes the function to not wait for mallocs. 2425 * This makes it safe to call while holding certain other locks. 2426 */ 2427 static struct pmc_thread * 2428 pmc_find_thread_descriptor(struct pmc_process *pp, struct thread *td, 2429 uint32_t mode) 2430 { 2431 struct pmc_thread *pt = NULL, *ptnew = NULL; 2432 int wait_flag; 2433 2434 KASSERT(td != NULL, ("[pmc,%d] called to add NULL td", __LINE__)); 2435 2436 /* 2437 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case prior to 2438 * acquiring the lock. 2439 */ 2440 if ((mode & PMC_FLAG_ALLOCATE) != 0) { 2441 if ((ptnew = pmc_thread_descriptor_pool_alloc()) == NULL) { 2442 wait_flag = M_WAITOK; 2443 if ((mode & PMC_FLAG_NOWAIT) != 0 || 2444 in_epoch(global_epoch_preempt)) 2445 wait_flag = M_NOWAIT; 2446 2447 ptnew = malloc(THREADENTRY_SIZE, M_PMC, 2448 wait_flag | M_ZERO); 2449 } 2450 } 2451 2452 mtx_lock_spin(pp->pp_tdslock); 2453 LIST_FOREACH(pt, &pp->pp_tds, pt_next) { 2454 if (pt->pt_td == td) 2455 break; 2456 } 2457 2458 if ((mode & PMC_FLAG_REMOVE) != 0 && pt != NULL) 2459 LIST_REMOVE(pt, pt_next); 2460 2461 if ((mode & PMC_FLAG_ALLOCATE) != 0 && pt == NULL && ptnew != NULL) { 2462 pt = ptnew; 2463 ptnew = NULL; 2464 pt->pt_td = td; 2465 LIST_INSERT_HEAD(&pp->pp_tds, pt, pt_next); 2466 } 2467 2468 mtx_unlock_spin(pp->pp_tdslock); 2469 2470 if (ptnew != NULL) { 2471 free(ptnew, M_PMC); 2472 } 2473 2474 return (pt); 2475 } 2476 2477 /* 2478 * Try to add thread descriptors for each thread in a process. 2479 */ 2480 static void 2481 pmc_add_thread_descriptors_from_proc(struct proc *p, struct pmc_process *pp) 2482 { 2483 struct pmc_thread **tdlist; 2484 struct thread *curtd; 2485 int i, tdcnt, tdlistsz; 2486 2487 KASSERT(!PROC_LOCKED(p), ("[pmc,%d] proc unexpectedly locked", 2488 __LINE__)); 2489 tdcnt = 32; 2490 restart: 2491 tdlistsz = roundup2(tdcnt, 32); 2492 2493 tdcnt = 0; 2494 tdlist = malloc(sizeof(struct pmc_thread *) * tdlistsz, M_TEMP, 2495 M_WAITOK); 2496 2497 PROC_LOCK(p); 2498 FOREACH_THREAD_IN_PROC(p, curtd) 2499 tdcnt++; 2500 if (tdcnt >= tdlistsz) { 2501 PROC_UNLOCK(p); 2502 free(tdlist, M_TEMP); 2503 goto restart; 2504 } 2505 2506 /* 2507 * Try to add each thread to the list without sleeping. If unable, 2508 * add to a queue to retry after dropping the process lock. 2509 */ 2510 tdcnt = 0; 2511 FOREACH_THREAD_IN_PROC(p, curtd) { 2512 tdlist[tdcnt] = pmc_find_thread_descriptor(pp, curtd, 2513 PMC_FLAG_ALLOCATE | PMC_FLAG_NOWAIT); 2514 if (tdlist[tdcnt] == NULL) { 2515 PROC_UNLOCK(p); 2516 for (i = 0; i <= tdcnt; i++) 2517 pmc_thread_descriptor_pool_free(tdlist[i]); 2518 free(tdlist, M_TEMP); 2519 goto restart; 2520 } 2521 tdcnt++; 2522 } 2523 PROC_UNLOCK(p); 2524 free(tdlist, M_TEMP); 2525 } 2526 2527 /* 2528 * Find the descriptor corresponding to process 'p', adding or removing it 2529 * as specified by 'mode'. 2530 */ 2531 static struct pmc_process * 2532 pmc_find_process_descriptor(struct proc *p, uint32_t mode) 2533 { 2534 struct pmc_process *pp, *ppnew; 2535 struct pmc_processhash *pph; 2536 uint32_t hindex; 2537 2538 hindex = PMC_HASH_PTR(p, pmc_processhashmask); 2539 pph = &pmc_processhash[hindex]; 2540 2541 ppnew = NULL; 2542 2543 /* 2544 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case since we 2545 * cannot call malloc(9) once we hold a spin lock. 2546 */ 2547 if ((mode & PMC_FLAG_ALLOCATE) != 0) 2548 ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc * 2549 sizeof(struct pmc_targetstate), M_PMC, M_WAITOK | M_ZERO); 2550 2551 mtx_lock_spin(&pmc_processhash_mtx); 2552 LIST_FOREACH(pp, pph, pp_next) { 2553 if (pp->pp_proc == p) 2554 break; 2555 } 2556 2557 if ((mode & PMC_FLAG_REMOVE) != 0 && pp != NULL) 2558 LIST_REMOVE(pp, pp_next); 2559 2560 if ((mode & PMC_FLAG_ALLOCATE) != 0 && pp == NULL && ppnew != NULL) { 2561 ppnew->pp_proc = p; 2562 LIST_INIT(&ppnew->pp_tds); 2563 ppnew->pp_tdslock = mtx_pool_find(pmc_mtxpool, ppnew); 2564 LIST_INSERT_HEAD(pph, ppnew, pp_next); 2565 mtx_unlock_spin(&pmc_processhash_mtx); 2566 pp = ppnew; 2567 ppnew = NULL; 2568 2569 /* Add thread descriptors for this process' current threads. */ 2570 pmc_add_thread_descriptors_from_proc(p, pp); 2571 } else 2572 mtx_unlock_spin(&pmc_processhash_mtx); 2573 2574 if (ppnew != NULL) 2575 free(ppnew, M_PMC); 2576 return (pp); 2577 } 2578 2579 /* 2580 * Remove a process descriptor from the process hash table. 2581 */ 2582 static void 2583 pmc_remove_process_descriptor(struct pmc_process *pp) 2584 { 2585 KASSERT(pp->pp_refcnt == 0, 2586 ("[pmc,%d] Removing process descriptor %p with count %d", 2587 __LINE__, pp, pp->pp_refcnt)); 2588 2589 mtx_lock_spin(&pmc_processhash_mtx); 2590 LIST_REMOVE(pp, pp_next); 2591 mtx_unlock_spin(&pmc_processhash_mtx); 2592 } 2593 2594 /* 2595 * Destroy a process descriptor. 2596 */ 2597 static void 2598 pmc_destroy_process_descriptor(struct pmc_process *pp) 2599 { 2600 struct pmc_thread *pmc_td; 2601 2602 while ((pmc_td = LIST_FIRST(&pp->pp_tds)) != NULL) { 2603 LIST_REMOVE(pmc_td, pt_next); 2604 pmc_thread_descriptor_pool_free(pmc_td); 2605 } 2606 free(pp, M_PMC); 2607 } 2608 2609 /* 2610 * Find an owner descriptor corresponding to proc 'p'. 2611 */ 2612 static struct pmc_owner * 2613 pmc_find_owner_descriptor(struct proc *p) 2614 { 2615 struct pmc_owner *po; 2616 struct pmc_ownerhash *poh; 2617 uint32_t hindex; 2618 2619 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask); 2620 poh = &pmc_ownerhash[hindex]; 2621 2622 po = NULL; 2623 LIST_FOREACH(po, poh, po_next) { 2624 if (po->po_owner == p) 2625 break; 2626 } 2627 2628 PMCDBG5(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> " 2629 "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po); 2630 2631 return (po); 2632 } 2633 2634 /* 2635 * Allocate a pmc descriptor and initialize its fields. 2636 */ 2637 static struct pmc * 2638 pmc_allocate_pmc_descriptor(void) 2639 { 2640 struct pmc *pmc; 2641 2642 pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK | M_ZERO); 2643 pmc->pm_runcount = counter_u64_alloc(M_WAITOK); 2644 pmc->pm_pcpu_state = malloc(sizeof(struct pmc_pcpu_state) * mp_ncpus, 2645 M_PMC, M_WAITOK | M_ZERO); 2646 PMCDBG1(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc); 2647 2648 return (pmc); 2649 } 2650 2651 /* 2652 * Destroy a pmc descriptor. 2653 */ 2654 static void 2655 pmc_destroy_pmc_descriptor(struct pmc *pm) 2656 { 2657 2658 KASSERT(pm->pm_state == PMC_STATE_DELETED || 2659 pm->pm_state == PMC_STATE_FREE, 2660 ("[pmc,%d] destroying non-deleted PMC", __LINE__)); 2661 KASSERT(LIST_EMPTY(&pm->pm_targets), 2662 ("[pmc,%d] destroying pmc with targets", __LINE__)); 2663 KASSERT(pm->pm_owner == NULL, 2664 ("[pmc,%d] destroying pmc attached to an owner", __LINE__)); 2665 KASSERT(counter_u64_fetch(pm->pm_runcount) == 0, 2666 ("[pmc,%d] pmc has non-zero run count %ju", __LINE__, 2667 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 2668 2669 counter_u64_free(pm->pm_runcount); 2670 free(pm->pm_pcpu_state, M_PMC); 2671 free(pm, M_PMC); 2672 } 2673 2674 static void 2675 pmc_wait_for_pmc_idle(struct pmc *pm) 2676 { 2677 #ifdef INVARIANTS 2678 volatile int maxloop; 2679 2680 maxloop = 100 * pmc_cpu_max(); 2681 #endif 2682 /* 2683 * Loop (with a forced context switch) till the PMC's runcount 2684 * comes down to zero. 2685 */ 2686 pmclog_flush(pm->pm_owner, 1); 2687 while (counter_u64_fetch(pm->pm_runcount) > 0) { 2688 pmclog_flush(pm->pm_owner, 1); 2689 #ifdef INVARIANTS 2690 maxloop--; 2691 KASSERT(maxloop > 0, 2692 ("[pmc,%d] (ri%d, rc%ju) waiting too long for " 2693 "pmc to be free", __LINE__, PMC_TO_ROWINDEX(pm), 2694 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 2695 #endif 2696 pmc_force_context_switch(); 2697 } 2698 } 2699 2700 /* 2701 * This function does the following things: 2702 * 2703 * - detaches the PMC from hardware 2704 * - unlinks all target threads that were attached to it 2705 * - removes the PMC from its owner's list 2706 * - destroys the PMC private mutex 2707 * 2708 * Once this function completes, the given pmc pointer can be freed by 2709 * calling pmc_destroy_pmc_descriptor(). 2710 */ 2711 static void 2712 pmc_release_pmc_descriptor(struct pmc *pm) 2713 { 2714 struct pmc_binding pb; 2715 struct pmc_classdep *pcd; 2716 struct pmc_hw *phw __diagused; 2717 struct pmc_owner *po; 2718 struct pmc_process *pp; 2719 struct pmc_target *ptgt, *tmp; 2720 enum pmc_mode mode; 2721 u_int adjri, ri, cpu; 2722 2723 sx_assert(&pmc_sx, SX_XLOCKED); 2724 KASSERT(pm, ("[pmc,%d] null pmc", __LINE__)); 2725 2726 ri = PMC_TO_ROWINDEX(pm); 2727 pcd = pmc_ri_to_classdep(md, ri, &adjri); 2728 mode = PMC_TO_MODE(pm); 2729 2730 PMCDBG3(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri, 2731 mode); 2732 2733 /* 2734 * First, we take the PMC off hardware. 2735 */ 2736 cpu = 0; 2737 if (PMC_IS_SYSTEM_MODE(mode)) { 2738 /* 2739 * A system mode PMC runs on a specific CPU. Switch 2740 * to this CPU and turn hardware off. 2741 */ 2742 pmc_save_cpu_binding(&pb); 2743 cpu = PMC_TO_CPU(pm); 2744 pmc_select_cpu(cpu); 2745 2746 /* switch off non-stalled CPUs */ 2747 pm->pm_pcpu_state[cpu].pps_cpustate = 0; 2748 if (pm->pm_state == PMC_STATE_RUNNING && 2749 pm->pm_pcpu_state[cpu].pps_stalled == 0) { 2750 2751 phw = pmc_pcpu[cpu]->pc_hwpmcs[ri]; 2752 2753 KASSERT(phw->phw_pmc == pm, 2754 ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)", 2755 __LINE__, ri, phw->phw_pmc, pm)); 2756 PMCDBG2(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri); 2757 2758 critical_enter(); 2759 (void)pcd->pcd_stop_pmc(cpu, adjri, pm); 2760 critical_exit(); 2761 } 2762 2763 PMCDBG2(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri); 2764 2765 critical_enter(); 2766 (void)pcd->pcd_config_pmc(cpu, adjri, NULL); 2767 critical_exit(); 2768 2769 /* adjust the global and process count of SS mode PMCs */ 2770 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) { 2771 po = pm->pm_owner; 2772 po->po_sscount--; 2773 if (po->po_sscount == 0) { 2774 atomic_subtract_rel_int(&pmc_ss_count, 1); 2775 CK_LIST_REMOVE(po, po_ssnext); 2776 epoch_wait_preempt(global_epoch_preempt); 2777 } 2778 } 2779 pm->pm_state = PMC_STATE_DELETED; 2780 2781 pmc_restore_cpu_binding(&pb); 2782 2783 /* 2784 * We could have references to this PMC structure in the 2785 * per-cpu sample queues. Wait for the queue to drain. 2786 */ 2787 pmc_wait_for_pmc_idle(pm); 2788 2789 } else if (PMC_IS_VIRTUAL_MODE(mode)) { 2790 /* 2791 * A virtual PMC could be running on multiple CPUs at a given 2792 * instant. 2793 * 2794 * By marking its state as DELETED, we ensure that this PMC is 2795 * never further scheduled on hardware. 2796 * 2797 * Then we wait till all CPUs are done with this PMC. 2798 */ 2799 pm->pm_state = PMC_STATE_DELETED; 2800 2801 /* Wait for the PMCs runcount to come to zero. */ 2802 pmc_wait_for_pmc_idle(pm); 2803 2804 /* 2805 * At this point the PMC is off all CPUs and cannot be freshly 2806 * scheduled onto a CPU. It is now safe to unlink all targets 2807 * from this PMC. If a process-record's refcount falls to zero, 2808 * we remove it from the hash table. The module-wide SX lock 2809 * protects us from races. 2810 */ 2811 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) { 2812 pp = ptgt->pt_process; 2813 pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */ 2814 2815 PMCDBG1(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt); 2816 2817 /* 2818 * If the target process record shows that no PMCs are 2819 * attached to it, reclaim its space. 2820 */ 2821 if (pp->pp_refcnt == 0) { 2822 pmc_remove_process_descriptor(pp); 2823 pmc_destroy_process_descriptor(pp); 2824 } 2825 } 2826 2827 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */ 2828 } 2829 2830 /* 2831 * Release any MD resources. 2832 */ 2833 (void)pcd->pcd_release_pmc(cpu, adjri, pm); 2834 2835 /* 2836 * Update row disposition. 2837 */ 2838 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) 2839 PMC_UNMARK_ROW_STANDALONE(ri); 2840 else 2841 PMC_UNMARK_ROW_THREAD(ri); 2842 2843 /* Unlink from the owner's list. */ 2844 if (pm->pm_owner != NULL) { 2845 LIST_REMOVE(pm, pm_next); 2846 pm->pm_owner = NULL; 2847 } 2848 } 2849 2850 /* 2851 * Register an owner and a pmc. 2852 */ 2853 static int 2854 pmc_register_owner(struct proc *p, struct pmc *pmc) 2855 { 2856 struct pmc_owner *po; 2857 2858 sx_assert(&pmc_sx, SX_XLOCKED); 2859 2860 if ((po = pmc_find_owner_descriptor(p)) == NULL) { 2861 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) 2862 return (ENOMEM); 2863 } 2864 2865 KASSERT(pmc->pm_owner == NULL, 2866 ("[pmc,%d] attempting to own an initialized PMC", __LINE__)); 2867 pmc->pm_owner = po; 2868 2869 LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next); 2870 2871 PROC_LOCK(p); 2872 p->p_flag |= P_HWPMC; 2873 PROC_UNLOCK(p); 2874 2875 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 2876 pmclog_process_pmcallocate(pmc); 2877 2878 PMCDBG2(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p", 2879 po, pmc); 2880 2881 return (0); 2882 } 2883 2884 /* 2885 * Return the current row disposition: 2886 * == 0 => FREE 2887 * > 0 => PROCESS MODE 2888 * < 0 => SYSTEM MODE 2889 */ 2890 int 2891 pmc_getrowdisp(int ri) 2892 { 2893 return (pmc_pmcdisp[ri]); 2894 } 2895 2896 /* 2897 * Check if a PMC at row index 'ri' can be allocated to the current 2898 * process. 2899 * 2900 * Allocation can fail if: 2901 * - the current process is already being profiled by a PMC at index 'ri', 2902 * attached to it via OP_PMCATTACH. 2903 * - the current process has already allocated a PMC at index 'ri' 2904 * via OP_ALLOCATE. 2905 */ 2906 static bool 2907 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu) 2908 { 2909 struct pmc *pm; 2910 struct pmc_owner *po; 2911 struct pmc_process *pp; 2912 enum pmc_mode mode; 2913 2914 PMCDBG5(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d " 2915 "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu); 2916 2917 /* 2918 * We shouldn't have already allocated a process-mode PMC at 2919 * row index 'ri'. 2920 * 2921 * We shouldn't have allocated a system-wide PMC on the same 2922 * CPU and same RI. 2923 */ 2924 if ((po = pmc_find_owner_descriptor(p)) != NULL) { 2925 LIST_FOREACH(pm, &po->po_pmcs, pm_next) { 2926 if (PMC_TO_ROWINDEX(pm) == ri) { 2927 mode = PMC_TO_MODE(pm); 2928 if (PMC_IS_VIRTUAL_MODE(mode)) 2929 return (false); 2930 if (PMC_IS_SYSTEM_MODE(mode) && 2931 PMC_TO_CPU(pm) == cpu) 2932 return (false); 2933 } 2934 } 2935 } 2936 2937 /* 2938 * We also shouldn't be the target of any PMC at this index 2939 * since otherwise a PMC_ATTACH to ourselves will fail. 2940 */ 2941 if ((pp = pmc_find_process_descriptor(p, 0)) != NULL) 2942 if (pp->pp_pmcs[ri].pp_pmc != NULL) 2943 return (false); 2944 2945 PMCDBG4(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok", 2946 p, p->p_pid, p->p_comm, ri); 2947 return (true); 2948 } 2949 2950 /* 2951 * Check if a given PMC at row index 'ri' can be currently used in 2952 * mode 'mode'. 2953 */ 2954 static bool 2955 pmc_can_allocate_row(int ri, enum pmc_mode mode) 2956 { 2957 enum pmc_disp disp; 2958 2959 sx_assert(&pmc_sx, SX_XLOCKED); 2960 2961 PMCDBG2(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode); 2962 2963 if (PMC_IS_SYSTEM_MODE(mode)) 2964 disp = PMC_DISP_STANDALONE; 2965 else 2966 disp = PMC_DISP_THREAD; 2967 2968 /* 2969 * check disposition for PMC row 'ri': 2970 * 2971 * Expected disposition Row-disposition Result 2972 * 2973 * STANDALONE STANDALONE or FREE proceed 2974 * STANDALONE THREAD fail 2975 * THREAD THREAD or FREE proceed 2976 * THREAD STANDALONE fail 2977 */ 2978 if (!PMC_ROW_DISP_IS_FREE(ri) && 2979 !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) && 2980 !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri))) 2981 return (false); 2982 2983 /* 2984 * All OK 2985 */ 2986 PMCDBG2(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode); 2987 return (true); 2988 } 2989 2990 /* 2991 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'. 2992 */ 2993 static struct pmc * 2994 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid) 2995 { 2996 struct pmc *pm; 2997 2998 KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc, 2999 ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__, 3000 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc)); 3001 3002 LIST_FOREACH(pm, &po->po_pmcs, pm_next) { 3003 if (pm->pm_id == pmcid) 3004 return (pm); 3005 } 3006 3007 return (NULL); 3008 } 3009 3010 static int 3011 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc) 3012 { 3013 struct pmc *pm, *opm; 3014 struct pmc_owner *po; 3015 struct pmc_process *pp; 3016 3017 PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid); 3018 if (PMC_ID_TO_ROWINDEX(pmcid) >= md->pmd_npmc) 3019 return (EINVAL); 3020 3021 if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL) { 3022 /* 3023 * In case of PMC_F_DESCENDANTS child processes we will not find 3024 * the current process in the owners hash list. Find the owner 3025 * process first and from there lookup the po. 3026 */ 3027 pp = pmc_find_process_descriptor(curthread->td_proc, 3028 PMC_FLAG_NONE); 3029 if (pp == NULL) 3030 return (ESRCH); 3031 opm = pp->pp_pmcs[PMC_ID_TO_ROWINDEX(pmcid)].pp_pmc; 3032 if (opm == NULL) 3033 return (ESRCH); 3034 if ((opm->pm_flags & 3035 (PMC_F_ATTACHED_TO_OWNER | PMC_F_DESCENDANTS)) != 3036 (PMC_F_ATTACHED_TO_OWNER | PMC_F_DESCENDANTS)) 3037 return (ESRCH); 3038 3039 po = opm->pm_owner; 3040 } 3041 3042 if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL) 3043 return (EINVAL); 3044 3045 PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm); 3046 3047 *pmc = pm; 3048 return (0); 3049 } 3050 3051 /* 3052 * Start a PMC. 3053 */ 3054 static int 3055 pmc_start(struct pmc *pm) 3056 { 3057 struct pmc_binding pb; 3058 struct pmc_classdep *pcd; 3059 struct pmc_owner *po; 3060 pmc_value_t v; 3061 enum pmc_mode mode; 3062 int adjri, error, cpu, ri; 3063 3064 KASSERT(pm != NULL, 3065 ("[pmc,%d] null pm", __LINE__)); 3066 3067 mode = PMC_TO_MODE(pm); 3068 ri = PMC_TO_ROWINDEX(pm); 3069 pcd = pmc_ri_to_classdep(md, ri, &adjri); 3070 3071 error = 0; 3072 po = pm->pm_owner; 3073 3074 PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri); 3075 3076 po = pm->pm_owner; 3077 3078 /* 3079 * Disallow PMCSTART if a logfile is required but has not been 3080 * configured yet. 3081 */ 3082 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) != 0 && 3083 (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) 3084 return (EDOOFUS); /* programming error */ 3085 3086 /* 3087 * If this is a sampling mode PMC, log mapping information for 3088 * the kernel modules that are currently loaded. 3089 */ 3090 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) 3091 pmc_log_kernel_mappings(pm); 3092 3093 if (PMC_IS_VIRTUAL_MODE(mode)) { 3094 /* 3095 * If a PMCATTACH has never been done on this PMC, 3096 * attach it to its owner process. 3097 */ 3098 if (LIST_EMPTY(&pm->pm_targets)) { 3099 error = (pm->pm_flags & PMC_F_ATTACH_DONE) != 0 ? 3100 ESRCH : pmc_attach_process(po->po_owner, pm); 3101 } 3102 3103 /* 3104 * If the PMC is attached to its owner, then force a context 3105 * switch to ensure that the MD state gets set correctly. 3106 */ 3107 if (error == 0) { 3108 pm->pm_state = PMC_STATE_RUNNING; 3109 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) != 0) 3110 pmc_force_context_switch(); 3111 } 3112 3113 return (error); 3114 } 3115 3116 /* 3117 * A system-wide PMC. 3118 * 3119 * Add the owner to the global list if this is a system-wide 3120 * sampling PMC. 3121 */ 3122 if (mode == PMC_MODE_SS) { 3123 /* 3124 * Log mapping information for all existing processes in the 3125 * system. Subsequent mappings are logged as they happen; 3126 * see pmc_process_mmap(). 3127 */ 3128 if (po->po_logprocmaps == 0) { 3129 pmc_log_all_process_mappings(po); 3130 po->po_logprocmaps = 1; 3131 } 3132 po->po_sscount++; 3133 if (po->po_sscount == 1) { 3134 atomic_add_rel_int(&pmc_ss_count, 1); 3135 CK_LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext); 3136 PMCDBG1(PMC,OPS,1, "po=%p in global list", po); 3137 } 3138 } 3139 3140 /* 3141 * Move to the CPU associated with this 3142 * PMC, and start the hardware. 3143 */ 3144 pmc_save_cpu_binding(&pb); 3145 cpu = PMC_TO_CPU(pm); 3146 if (!pmc_cpu_is_active(cpu)) 3147 return (ENXIO); 3148 pmc_select_cpu(cpu); 3149 3150 /* 3151 * global PMCs are configured at allocation time 3152 * so write out the initial value and start the PMC. 3153 */ 3154 pm->pm_state = PMC_STATE_RUNNING; 3155 3156 critical_enter(); 3157 v = PMC_IS_SAMPLING_MODE(mode) ? pm->pm_sc.pm_reloadcount : 3158 pm->pm_sc.pm_initial; 3159 if ((error = pcd->pcd_write_pmc(cpu, adjri, pm, v)) == 0) { 3160 /* If a sampling mode PMC, reset stalled state. */ 3161 if (PMC_IS_SAMPLING_MODE(mode)) 3162 pm->pm_pcpu_state[cpu].pps_stalled = 0; 3163 3164 /* Indicate that we desire this to run. Start it. */ 3165 pm->pm_pcpu_state[cpu].pps_cpustate = 1; 3166 error = pcd->pcd_start_pmc(cpu, adjri, pm); 3167 } 3168 critical_exit(); 3169 3170 pmc_restore_cpu_binding(&pb); 3171 return (error); 3172 } 3173 3174 /* 3175 * Stop a PMC. 3176 */ 3177 static int 3178 pmc_stop(struct pmc *pm) 3179 { 3180 struct pmc_binding pb; 3181 struct pmc_classdep *pcd; 3182 struct pmc_owner *po; 3183 int adjri, cpu, error, ri; 3184 3185 KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__)); 3186 3187 PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm, PMC_TO_MODE(pm), 3188 PMC_TO_ROWINDEX(pm)); 3189 3190 pm->pm_state = PMC_STATE_STOPPED; 3191 3192 /* 3193 * If the PMC is a virtual mode one, changing the state to non-RUNNING 3194 * is enough to ensure that the PMC never gets scheduled. 3195 * 3196 * If this PMC is current running on a CPU, then it will handled 3197 * correctly at the time its target process is context switched out. 3198 */ 3199 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) 3200 return (0); 3201 3202 /* 3203 * A system-mode PMC. Move to the CPU associated with this PMC, and 3204 * stop the hardware. We update the 'initial count' so that a 3205 * subsequent PMCSTART will resume counting from the current hardware 3206 * count. 3207 */ 3208 pmc_save_cpu_binding(&pb); 3209 3210 cpu = PMC_TO_CPU(pm); 3211 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(), 3212 ("[pmc,%d] illegal cpu=%d", __LINE__, cpu)); 3213 if (!pmc_cpu_is_active(cpu)) 3214 return (ENXIO); 3215 3216 pmc_select_cpu(cpu); 3217 3218 ri = PMC_TO_ROWINDEX(pm); 3219 pcd = pmc_ri_to_classdep(md, ri, &adjri); 3220 3221 pm->pm_pcpu_state[cpu].pps_cpustate = 0; 3222 critical_enter(); 3223 if ((error = pcd->pcd_stop_pmc(cpu, adjri, pm)) == 0) { 3224 error = pcd->pcd_read_pmc(cpu, adjri, pm, 3225 &pm->pm_sc.pm_initial); 3226 } 3227 critical_exit(); 3228 3229 pmc_restore_cpu_binding(&pb); 3230 3231 /* Remove this owner from the global list of SS PMC owners. */ 3232 po = pm->pm_owner; 3233 if (PMC_TO_MODE(pm) == PMC_MODE_SS) { 3234 po->po_sscount--; 3235 if (po->po_sscount == 0) { 3236 atomic_subtract_rel_int(&pmc_ss_count, 1); 3237 CK_LIST_REMOVE(po, po_ssnext); 3238 epoch_wait_preempt(global_epoch_preempt); 3239 PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po); 3240 } 3241 } 3242 3243 return (error); 3244 } 3245 3246 static struct pmc_classdep * 3247 pmc_class_to_classdep(enum pmc_class class) 3248 { 3249 int n; 3250 3251 for (n = 0; n < md->pmd_nclass; n++) { 3252 if (md->pmd_classdep[n].pcd_class == class) 3253 return (&md->pmd_classdep[n]); 3254 } 3255 return (NULL); 3256 } 3257 3258 #if defined(HWPMC_DEBUG) && defined(KTR) 3259 static const char *pmc_op_to_name[] = { 3260 #undef __PMC_OP 3261 #define __PMC_OP(N, D) #N , 3262 __PMC_OPS() 3263 NULL 3264 }; 3265 #endif 3266 3267 /* 3268 * The syscall interface 3269 */ 3270 3271 #define PMC_GET_SX_XLOCK(...) do { \ 3272 sx_xlock(&pmc_sx); \ 3273 if (pmc_hook == NULL) { \ 3274 sx_xunlock(&pmc_sx); \ 3275 return __VA_ARGS__; \ 3276 } \ 3277 } while (0) 3278 3279 #define PMC_DOWNGRADE_SX() do { \ 3280 sx_downgrade(&pmc_sx); \ 3281 is_sx_downgraded = true; \ 3282 } while (0) 3283 3284 /* 3285 * Main body of PMC_OP_PMCALLOCATE. 3286 */ 3287 static int 3288 pmc_do_op_pmcallocate(struct thread *td, struct pmc_op_pmcallocate *pa) 3289 { 3290 struct proc *p; 3291 struct pmc *pmc; 3292 struct pmc_binding pb; 3293 struct pmc_classdep *pcd; 3294 struct pmc_hw *phw; 3295 enum pmc_mode mode; 3296 enum pmc_class class; 3297 uint32_t caps, flags; 3298 u_int cpu; 3299 int adjri, n; 3300 int error; 3301 3302 class = pa->pm_class; 3303 caps = pa->pm_caps; 3304 flags = pa->pm_flags; 3305 mode = pa->pm_mode; 3306 cpu = pa->pm_cpu; 3307 3308 p = td->td_proc; 3309 3310 /* Requested mode must exist. */ 3311 if ((mode != PMC_MODE_SS && mode != PMC_MODE_SC && 3312 mode != PMC_MODE_TS && mode != PMC_MODE_TC)) 3313 return (EINVAL); 3314 3315 /* Requested CPU must be valid. */ 3316 if (cpu != PMC_CPU_ANY && cpu >= pmc_cpu_max()) 3317 return (EINVAL); 3318 3319 /* 3320 * Virtual PMCs should only ask for a default CPU. 3321 * System mode PMCs need to specify a non-default CPU. 3322 */ 3323 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != PMC_CPU_ANY) || 3324 (PMC_IS_SYSTEM_MODE(mode) && cpu == PMC_CPU_ANY)) 3325 return (EINVAL); 3326 3327 /* 3328 * Check that an inactive CPU is not being asked for. 3329 */ 3330 if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu)) 3331 return (ENXIO); 3332 3333 /* 3334 * Refuse an allocation for a system-wide PMC if this process has been 3335 * jailed, or if this process lacks super-user credentials and the 3336 * sysctl tunable 'security.bsd.unprivileged_syspmcs' is zero. 3337 */ 3338 if (PMC_IS_SYSTEM_MODE(mode)) { 3339 if (jailed(td->td_ucred)) 3340 return (EPERM); 3341 if (!pmc_unprivileged_syspmcs) { 3342 error = priv_check(td, PRIV_PMC_SYSTEM); 3343 if (error != 0) 3344 return (error); 3345 } 3346 } 3347 3348 /* 3349 * Look for valid values for 'pm_flags'. 3350 */ 3351 if ((flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW | 3352 PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN | PMC_F_USERCALLCHAIN)) != 0) 3353 return (EINVAL); 3354 3355 /* PMC_F_USERCALLCHAIN is only valid with PMC_F_CALLCHAIN. */ 3356 if ((flags & (PMC_F_CALLCHAIN | PMC_F_USERCALLCHAIN)) == 3357 PMC_F_USERCALLCHAIN) 3358 return (EINVAL); 3359 3360 /* PMC_F_USERCALLCHAIN is only valid for sampling mode. */ 3361 if ((flags & PMC_F_USERCALLCHAIN) != 0 && mode != PMC_MODE_TS && 3362 mode != PMC_MODE_SS) 3363 return (EINVAL); 3364 3365 /* Process logging options are not allowed for system PMCs. */ 3366 if (PMC_IS_SYSTEM_MODE(mode) && 3367 (flags & (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT)) != 0) 3368 return (EINVAL); 3369 3370 /* 3371 * All sampling mode PMCs need to be able to interrupt the CPU. 3372 */ 3373 if (PMC_IS_SAMPLING_MODE(mode)) 3374 caps |= PMC_CAP_INTERRUPT; 3375 3376 /* A valid class specifier should have been passed in. */ 3377 pcd = pmc_class_to_classdep(class); 3378 if (pcd == NULL) 3379 return (EINVAL); 3380 3381 /* The requested PMC capabilities should be feasible. */ 3382 if ((pcd->pcd_caps & caps) != caps) 3383 return (EOPNOTSUPP); 3384 3385 PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d", pa->pm_ev, 3386 caps, mode, cpu); 3387 3388 pmc = pmc_allocate_pmc_descriptor(); 3389 pmc->pm_id = PMC_ID_MAKE_ID(cpu, pa->pm_mode, class, PMC_ID_INVALID); 3390 pmc->pm_event = pa->pm_ev; 3391 pmc->pm_state = PMC_STATE_FREE; 3392 pmc->pm_caps = caps; 3393 pmc->pm_flags = flags; 3394 3395 /* XXX set lower bound on sampling for process counters */ 3396 if (PMC_IS_SAMPLING_MODE(mode)) { 3397 /* 3398 * Don't permit requested sample rate to be less than 3399 * pmc_mincount. 3400 */ 3401 if (pa->pm_count < MAX(1, pmc_mincount)) 3402 log(LOG_WARNING, "pmcallocate: passed sample " 3403 "rate %ju - setting to %u\n", 3404 (uintmax_t)pa->pm_count, 3405 MAX(1, pmc_mincount)); 3406 pmc->pm_sc.pm_reloadcount = MAX(MAX(1, pmc_mincount), 3407 pa->pm_count); 3408 } else 3409 pmc->pm_sc.pm_initial = pa->pm_count; 3410 3411 /* switch thread to CPU 'cpu' */ 3412 pmc_save_cpu_binding(&pb); 3413 3414 #define PMC_IS_SHAREABLE_PMC(cpu, n) \ 3415 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state & \ 3416 PMC_PHW_FLAG_IS_SHAREABLE) 3417 #define PMC_IS_UNALLOCATED(cpu, n) \ 3418 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL) 3419 3420 if (PMC_IS_SYSTEM_MODE(mode)) { 3421 pmc_select_cpu(cpu); 3422 for (n = pcd->pcd_ri; n < md->pmd_npmc; n++) { 3423 pcd = pmc_ri_to_classdep(md, n, &adjri); 3424 3425 if (!pmc_can_allocate_row(n, mode) || 3426 !pmc_can_allocate_rowindex(p, n, cpu)) 3427 continue; 3428 if (!PMC_IS_UNALLOCATED(cpu, n) && 3429 !PMC_IS_SHAREABLE_PMC(cpu, n)) 3430 continue; 3431 3432 if (pcd->pcd_allocate_pmc(cpu, adjri, pmc, pa) == 0) { 3433 /* Success. */ 3434 break; 3435 } 3436 } 3437 } else { 3438 /* Process virtual mode */ 3439 for (n = pcd->pcd_ri; n < md->pmd_npmc; n++) { 3440 pcd = pmc_ri_to_classdep(md, n, &adjri); 3441 3442 if (!pmc_can_allocate_row(n, mode) || 3443 !pmc_can_allocate_rowindex(p, n, PMC_CPU_ANY)) 3444 continue; 3445 3446 if (pcd->pcd_allocate_pmc(td->td_oncpu, adjri, pmc, 3447 pa) == 0) { 3448 /* Success. */ 3449 break; 3450 } 3451 } 3452 } 3453 3454 #undef PMC_IS_UNALLOCATED 3455 #undef PMC_IS_SHAREABLE_PMC 3456 3457 pmc_restore_cpu_binding(&pb); 3458 3459 if (n == md->pmd_npmc) { 3460 pmc_destroy_pmc_descriptor(pmc); 3461 return (EINVAL); 3462 } 3463 3464 /* Fill in the correct value in the ID field. */ 3465 pmc->pm_id = PMC_ID_MAKE_ID(cpu, mode, class, n); 3466 3467 PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x", 3468 pmc->pm_event, class, mode, n, pmc->pm_id); 3469 3470 /* Process mode PMCs with logging enabled need log files. */ 3471 if ((pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW)) != 0) 3472 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE; 3473 3474 /* All system mode sampling PMCs require a log file. */ 3475 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode)) 3476 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE; 3477 3478 /* 3479 * Configure global pmc's immediately. 3480 */ 3481 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) { 3482 pmc_save_cpu_binding(&pb); 3483 pmc_select_cpu(cpu); 3484 3485 phw = pmc_pcpu[cpu]->pc_hwpmcs[n]; 3486 pcd = pmc_ri_to_classdep(md, n, &adjri); 3487 3488 if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 || 3489 (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) { 3490 (void)pcd->pcd_release_pmc(cpu, adjri, pmc); 3491 pmc_destroy_pmc_descriptor(pmc); 3492 pmc_restore_cpu_binding(&pb); 3493 return (EPERM); 3494 } 3495 3496 pmc_restore_cpu_binding(&pb); 3497 } 3498 3499 pmc->pm_state = PMC_STATE_ALLOCATED; 3500 pmc->pm_class = class; 3501 3502 /* 3503 * Mark row disposition. 3504 */ 3505 if (PMC_IS_SYSTEM_MODE(mode)) 3506 PMC_MARK_ROW_STANDALONE(n); 3507 else 3508 PMC_MARK_ROW_THREAD(n); 3509 3510 /* 3511 * Register this PMC with the current thread as its owner. 3512 */ 3513 error = pmc_register_owner(p, pmc); 3514 if (error != 0) { 3515 pmc_release_pmc_descriptor(pmc); 3516 pmc_destroy_pmc_descriptor(pmc); 3517 return (error); 3518 } 3519 3520 /* 3521 * Return the allocated index. 3522 */ 3523 pa->pm_pmcid = pmc->pm_id; 3524 return (0); 3525 } 3526 3527 /* 3528 * Main body of PMC_OP_PMCATTACH. 3529 */ 3530 static int 3531 pmc_do_op_pmcattach(struct thread *td, struct pmc_op_pmcattach a) 3532 { 3533 struct pmc *pm; 3534 struct proc *p; 3535 int error; 3536 3537 sx_assert(&pmc_sx, SX_XLOCKED); 3538 3539 if (a.pm_pid < 0) { 3540 return (EINVAL); 3541 } else if (a.pm_pid == 0) { 3542 a.pm_pid = td->td_proc->p_pid; 3543 } 3544 3545 error = pmc_find_pmc(a.pm_pmc, &pm); 3546 if (error != 0) 3547 return (error); 3548 3549 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) 3550 return (EINVAL); 3551 3552 /* PMCs may be (re)attached only when allocated or stopped */ 3553 if (pm->pm_state == PMC_STATE_RUNNING) { 3554 return (EBUSY); 3555 } else if (pm->pm_state != PMC_STATE_ALLOCATED && 3556 pm->pm_state != PMC_STATE_STOPPED) { 3557 return (EINVAL); 3558 } 3559 3560 /* lookup pid */ 3561 if ((p = pfind(a.pm_pid)) == NULL) 3562 return (ESRCH); 3563 3564 /* 3565 * Ignore processes that are working on exiting. 3566 */ 3567 if ((p->p_flag & P_WEXIT) != 0) { 3568 PROC_UNLOCK(p); /* pfind() returns a locked process */ 3569 return (ESRCH); 3570 } 3571 3572 /* 3573 * We are allowed to attach a PMC to a process if we can debug it. 3574 */ 3575 error = p_candebug(curthread, p); 3576 3577 PROC_UNLOCK(p); 3578 3579 if (error == 0) 3580 error = pmc_attach_process(p, pm); 3581 3582 return (error); 3583 } 3584 3585 /* 3586 * Main body of PMC_OP_PMCDETACH. 3587 */ 3588 static int 3589 pmc_do_op_pmcdetach(struct thread *td, struct pmc_op_pmcattach a) 3590 { 3591 struct pmc *pm; 3592 struct proc *p; 3593 int error; 3594 3595 if (a.pm_pid < 0) { 3596 return (EINVAL); 3597 } else if (a.pm_pid == 0) 3598 a.pm_pid = td->td_proc->p_pid; 3599 3600 error = pmc_find_pmc(a.pm_pmc, &pm); 3601 if (error != 0) 3602 return (error); 3603 3604 if ((p = pfind(a.pm_pid)) == NULL) 3605 return (ESRCH); 3606 3607 /* 3608 * Treat processes that are in the process of exiting as if they were 3609 * not present. 3610 */ 3611 if ((p->p_flag & P_WEXIT) != 0) { 3612 PROC_UNLOCK(p); 3613 return (ESRCH); 3614 } 3615 3616 PROC_UNLOCK(p); /* pfind() returns a locked process */ 3617 3618 if (error == 0) 3619 error = pmc_detach_process(p, pm); 3620 3621 return (error); 3622 } 3623 3624 /* 3625 * Main body of PMC_OP_PMCRELEASE. 3626 */ 3627 static int 3628 pmc_do_op_pmcrelease(pmc_id_t pmcid) 3629 { 3630 struct pmc_owner *po; 3631 struct pmc *pm; 3632 int error; 3633 3634 /* 3635 * Find PMC pointer for the named PMC. 3636 * 3637 * Use pmc_release_pmc_descriptor() to switch off the 3638 * PMC, remove all its target threads, and remove the 3639 * PMC from its owner's list. 3640 * 3641 * Remove the owner record if this is the last PMC 3642 * owned. 3643 * 3644 * Free up space. 3645 */ 3646 error = pmc_find_pmc(pmcid, &pm); 3647 if (error != 0) 3648 return (error); 3649 3650 po = pm->pm_owner; 3651 pmc_release_pmc_descriptor(pm); 3652 pmc_maybe_remove_owner(po); 3653 pmc_destroy_pmc_descriptor(pm); 3654 3655 return (error); 3656 } 3657 3658 /* 3659 * Main body of PMC_OP_PMCRW. 3660 */ 3661 static int 3662 pmc_do_op_pmcrw(const struct pmc_op_pmcrw *prw, pmc_value_t *valp) 3663 { 3664 struct pmc_binding pb; 3665 struct pmc_classdep *pcd; 3666 struct pmc *pm; 3667 u_int cpu, ri, adjri; 3668 int error; 3669 3670 PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw->pm_pmcid, prw->pm_flags); 3671 3672 /* Must have at least one flag set. */ 3673 if ((prw->pm_flags & (PMC_F_OLDVALUE | PMC_F_NEWVALUE)) == 0) 3674 return (EINVAL); 3675 3676 /* Locate PMC descriptor. */ 3677 error = pmc_find_pmc(prw->pm_pmcid, &pm); 3678 if (error != 0) 3679 return (error); 3680 3681 /* Can't read a PMC that hasn't been started. */ 3682 if (pm->pm_state != PMC_STATE_ALLOCATED && 3683 pm->pm_state != PMC_STATE_STOPPED && 3684 pm->pm_state != PMC_STATE_RUNNING) 3685 return (EINVAL); 3686 3687 /* Writing a new value is allowed only for 'STOPPED' PMCs. */ 3688 if (pm->pm_state == PMC_STATE_RUNNING && 3689 (prw->pm_flags & PMC_F_NEWVALUE) != 0) 3690 return (EBUSY); 3691 3692 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) { 3693 /* 3694 * If this PMC is attached to its owner (i.e., the process 3695 * requesting this operation) and is running, then attempt to 3696 * get an upto-date reading from hardware for a READ. Writes 3697 * are only allowed when the PMC is stopped, so only update the 3698 * saved value field. 3699 * 3700 * If the PMC is not running, or is not attached to its owner, 3701 * read/write to the savedvalue field. 3702 */ 3703 3704 ri = PMC_TO_ROWINDEX(pm); 3705 pcd = pmc_ri_to_classdep(md, ri, &adjri); 3706 3707 mtx_pool_lock_spin(pmc_mtxpool, pm); 3708 cpu = curthread->td_oncpu; 3709 3710 if ((prw->pm_flags & PMC_F_OLDVALUE) != 0) { 3711 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) && 3712 (pm->pm_state == PMC_STATE_RUNNING)) { 3713 error = (*pcd->pcd_read_pmc)(cpu, adjri, pm, 3714 valp); 3715 } else { 3716 *valp = pm->pm_gv.pm_savedvalue; 3717 } 3718 } 3719 3720 if ((prw->pm_flags & PMC_F_NEWVALUE) != 0) 3721 pm->pm_gv.pm_savedvalue = prw->pm_value; 3722 3723 mtx_pool_unlock_spin(pmc_mtxpool, pm); 3724 } else { /* System mode PMCs */ 3725 cpu = PMC_TO_CPU(pm); 3726 ri = PMC_TO_ROWINDEX(pm); 3727 pcd = pmc_ri_to_classdep(md, ri, &adjri); 3728 3729 if (!pmc_cpu_is_active(cpu)) 3730 return (ENXIO); 3731 3732 /* Move this thread to CPU 'cpu'. */ 3733 pmc_save_cpu_binding(&pb); 3734 pmc_select_cpu(cpu); 3735 critical_enter(); 3736 3737 /* Save old value. */ 3738 if ((prw->pm_flags & PMC_F_OLDVALUE) != 0) 3739 error = (*pcd->pcd_read_pmc)(cpu, adjri, pm, valp); 3740 3741 /* Write out new value. */ 3742 if (error == 0 && (prw->pm_flags & PMC_F_NEWVALUE) != 0) 3743 error = (*pcd->pcd_write_pmc)(cpu, adjri, pm, 3744 prw->pm_value); 3745 3746 critical_exit(); 3747 pmc_restore_cpu_binding(&pb); 3748 if (error != 0) 3749 return (error); 3750 } 3751 3752 #ifdef HWPMC_DEBUG 3753 if ((prw->pm_flags & PMC_F_NEWVALUE) != 0) 3754 PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx", 3755 ri, prw->pm_value, *valp); 3756 else 3757 PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, *valp); 3758 #endif 3759 return (error); 3760 } 3761 3762 static int 3763 pmc_syscall_handler(struct thread *td, void *syscall_args) 3764 { 3765 struct pmc_syscall_args *c; 3766 void *pmclog_proc_handle; 3767 void *arg; 3768 int error, op; 3769 bool is_sx_downgraded; 3770 3771 c = (struct pmc_syscall_args *)syscall_args; 3772 op = c->pmop_code; 3773 arg = c->pmop_data; 3774 3775 /* PMC isn't set up yet */ 3776 if (pmc_hook == NULL) 3777 return (EINVAL); 3778 3779 if (op == PMC_OP_CONFIGURELOG) { 3780 /* 3781 * We cannot create the logging process inside 3782 * pmclog_configure_log() because there is a LOR 3783 * between pmc_sx and process structure locks. 3784 * Instead, pre-create the process and ignite the loop 3785 * if everything is fine, otherwise direct the process 3786 * to exit. 3787 */ 3788 error = pmclog_proc_create(td, &pmclog_proc_handle); 3789 if (error != 0) 3790 goto done_syscall; 3791 } 3792 3793 PMC_GET_SX_XLOCK(ENOSYS); 3794 is_sx_downgraded = false; 3795 PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op, 3796 pmc_op_to_name[op], arg); 3797 3798 error = 0; 3799 counter_u64_add(pmc_stats.pm_syscalls, 1); 3800 3801 switch (op) { 3802 3803 3804 /* 3805 * Configure a log file. 3806 * 3807 * XXX This OP will be reworked. 3808 */ 3809 3810 case PMC_OP_CONFIGURELOG: 3811 { 3812 struct proc *p; 3813 struct pmc *pm; 3814 struct pmc_owner *po; 3815 struct pmc_op_configurelog cl; 3816 3817 if ((error = copyin(arg, &cl, sizeof(cl))) != 0) { 3818 pmclog_proc_ignite(pmclog_proc_handle, NULL); 3819 break; 3820 } 3821 3822 /* No flags currently implemented */ 3823 if (cl.pm_flags != 0) { 3824 error = EINVAL; 3825 break; 3826 } 3827 3828 /* mark this process as owning a log file */ 3829 p = td->td_proc; 3830 if ((po = pmc_find_owner_descriptor(p)) == NULL) 3831 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) { 3832 pmclog_proc_ignite(pmclog_proc_handle, NULL); 3833 error = ENOMEM; 3834 break; 3835 } 3836 3837 /* 3838 * If a valid fd was passed in, try to configure that, 3839 * otherwise if 'fd' was less than zero and there was 3840 * a log file configured, flush its buffers and 3841 * de-configure it. 3842 */ 3843 if (cl.pm_logfd >= 0) { 3844 error = pmclog_configure_log(md, po, cl.pm_logfd); 3845 pmclog_proc_ignite(pmclog_proc_handle, error == 0 ? 3846 po : NULL); 3847 } else if (po->po_flags & PMC_PO_OWNS_LOGFILE) { 3848 pmclog_proc_ignite(pmclog_proc_handle, NULL); 3849 error = pmclog_close(po); 3850 if (error == 0) { 3851 LIST_FOREACH(pm, &po->po_pmcs, pm_next) 3852 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE && 3853 pm->pm_state == PMC_STATE_RUNNING) 3854 pmc_stop(pm); 3855 error = pmclog_deconfigure_log(po); 3856 } 3857 } else { 3858 pmclog_proc_ignite(pmclog_proc_handle, NULL); 3859 error = EINVAL; 3860 } 3861 } 3862 break; 3863 3864 /* 3865 * Flush a log file. 3866 */ 3867 3868 case PMC_OP_FLUSHLOG: 3869 { 3870 struct pmc_owner *po; 3871 3872 sx_assert(&pmc_sx, SX_XLOCKED); 3873 3874 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) { 3875 error = EINVAL; 3876 break; 3877 } 3878 3879 error = pmclog_flush(po, 0); 3880 } 3881 break; 3882 3883 /* 3884 * Close a log file. 3885 */ 3886 3887 case PMC_OP_CLOSELOG: 3888 { 3889 struct pmc_owner *po; 3890 3891 sx_assert(&pmc_sx, SX_XLOCKED); 3892 3893 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) { 3894 error = EINVAL; 3895 break; 3896 } 3897 3898 error = pmclog_close(po); 3899 } 3900 break; 3901 3902 /* 3903 * Retrieve hardware configuration. 3904 */ 3905 3906 case PMC_OP_GETCPUINFO: /* CPU information */ 3907 { 3908 struct pmc_op_getcpuinfo gci; 3909 struct pmc_classinfo *pci; 3910 struct pmc_classdep *pcd; 3911 int cl; 3912 3913 memset(&gci, 0, sizeof(gci)); 3914 gci.pm_cputype = md->pmd_cputype; 3915 gci.pm_ncpu = pmc_cpu_max(); 3916 gci.pm_npmc = md->pmd_npmc; 3917 gci.pm_nclass = md->pmd_nclass; 3918 pci = gci.pm_classes; 3919 pcd = md->pmd_classdep; 3920 for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) { 3921 pci->pm_caps = pcd->pcd_caps; 3922 pci->pm_class = pcd->pcd_class; 3923 pci->pm_width = pcd->pcd_width; 3924 pci->pm_num = pcd->pcd_num; 3925 } 3926 error = copyout(&gci, arg, sizeof(gci)); 3927 } 3928 break; 3929 3930 /* 3931 * Retrieve soft events list. 3932 */ 3933 case PMC_OP_GETDYNEVENTINFO: 3934 { 3935 enum pmc_class cl; 3936 enum pmc_event ev; 3937 struct pmc_op_getdyneventinfo *gei; 3938 struct pmc_dyn_event_descr dev; 3939 struct pmc_soft *ps; 3940 uint32_t nevent; 3941 3942 sx_assert(&pmc_sx, SX_LOCKED); 3943 3944 gei = (struct pmc_op_getdyneventinfo *) arg; 3945 3946 if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0) 3947 break; 3948 3949 /* Only SOFT class is dynamic. */ 3950 if (cl != PMC_CLASS_SOFT) { 3951 error = EINVAL; 3952 break; 3953 } 3954 3955 nevent = 0; 3956 for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) { 3957 ps = pmc_soft_ev_acquire(ev); 3958 if (ps == NULL) 3959 continue; 3960 bcopy(&ps->ps_ev, &dev, sizeof(dev)); 3961 pmc_soft_ev_release(ps); 3962 3963 error = copyout(&dev, 3964 &gei->pm_events[nevent], 3965 sizeof(struct pmc_dyn_event_descr)); 3966 if (error != 0) 3967 break; 3968 nevent++; 3969 } 3970 if (error != 0) 3971 break; 3972 3973 error = copyout(&nevent, &gei->pm_nevent, 3974 sizeof(nevent)); 3975 } 3976 break; 3977 3978 /* 3979 * Get module statistics 3980 */ 3981 3982 case PMC_OP_GETDRIVERSTATS: 3983 { 3984 struct pmc_op_getdriverstats gms; 3985 #define CFETCH(a, b, field) a.field = counter_u64_fetch(b.field) 3986 CFETCH(gms, pmc_stats, pm_intr_ignored); 3987 CFETCH(gms, pmc_stats, pm_intr_processed); 3988 CFETCH(gms, pmc_stats, pm_intr_bufferfull); 3989 CFETCH(gms, pmc_stats, pm_syscalls); 3990 CFETCH(gms, pmc_stats, pm_syscall_errors); 3991 CFETCH(gms, pmc_stats, pm_buffer_requests); 3992 CFETCH(gms, pmc_stats, pm_buffer_requests_failed); 3993 CFETCH(gms, pmc_stats, pm_log_sweeps); 3994 #undef CFETCH 3995 error = copyout(&gms, arg, sizeof(gms)); 3996 } 3997 break; 3998 3999 4000 /* 4001 * Retrieve module version number 4002 */ 4003 4004 case PMC_OP_GETMODULEVERSION: 4005 { 4006 uint32_t cv, modv; 4007 4008 /* retrieve the client's idea of the ABI version */ 4009 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0) 4010 break; 4011 /* don't service clients newer than our driver */ 4012 modv = PMC_VERSION; 4013 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) { 4014 error = EPROGMISMATCH; 4015 break; 4016 } 4017 error = copyout(&modv, arg, sizeof(int)); 4018 } 4019 break; 4020 4021 4022 /* 4023 * Retrieve the state of all the PMCs on a given 4024 * CPU. 4025 */ 4026 4027 case PMC_OP_GETPMCINFO: 4028 { 4029 int ari; 4030 struct pmc *pm; 4031 size_t pmcinfo_size; 4032 uint32_t cpu, n, npmc; 4033 struct pmc_owner *po; 4034 struct pmc_binding pb; 4035 struct pmc_classdep *pcd; 4036 struct pmc_info *p, *pmcinfo; 4037 struct pmc_op_getpmcinfo *gpi; 4038 4039 PMC_DOWNGRADE_SX(); 4040 4041 gpi = (struct pmc_op_getpmcinfo *) arg; 4042 4043 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0) 4044 break; 4045 4046 if (cpu >= pmc_cpu_max()) { 4047 error = EINVAL; 4048 break; 4049 } 4050 4051 if (!pmc_cpu_is_active(cpu)) { 4052 error = ENXIO; 4053 break; 4054 } 4055 4056 /* switch to CPU 'cpu' */ 4057 pmc_save_cpu_binding(&pb); 4058 pmc_select_cpu(cpu); 4059 4060 npmc = md->pmd_npmc; 4061 4062 pmcinfo_size = npmc * sizeof(struct pmc_info); 4063 pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK | M_ZERO); 4064 4065 p = pmcinfo; 4066 4067 for (n = 0; n < md->pmd_npmc; n++, p++) { 4068 4069 pcd = pmc_ri_to_classdep(md, n, &ari); 4070 4071 KASSERT(pcd != NULL, 4072 ("[pmc,%d] null pcd ri=%d", __LINE__, n)); 4073 4074 if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0) 4075 break; 4076 4077 if (PMC_ROW_DISP_IS_STANDALONE(n)) 4078 p->pm_rowdisp = PMC_DISP_STANDALONE; 4079 else if (PMC_ROW_DISP_IS_THREAD(n)) 4080 p->pm_rowdisp = PMC_DISP_THREAD; 4081 else 4082 p->pm_rowdisp = PMC_DISP_FREE; 4083 4084 p->pm_ownerpid = -1; 4085 4086 if (pm == NULL) /* no PMC associated */ 4087 continue; 4088 4089 po = pm->pm_owner; 4090 4091 KASSERT(po->po_owner != NULL, 4092 ("[pmc,%d] pmc_owner had a null proc pointer", 4093 __LINE__)); 4094 4095 p->pm_ownerpid = po->po_owner->p_pid; 4096 p->pm_mode = PMC_TO_MODE(pm); 4097 p->pm_event = pm->pm_event; 4098 p->pm_flags = pm->pm_flags; 4099 4100 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) 4101 p->pm_reloadcount = 4102 pm->pm_sc.pm_reloadcount; 4103 } 4104 4105 pmc_restore_cpu_binding(&pb); 4106 4107 /* now copy out the PMC info collected */ 4108 if (error == 0) 4109 error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size); 4110 4111 free(pmcinfo, M_PMC); 4112 } 4113 break; 4114 4115 4116 /* 4117 * Set the administrative state of a PMC. I.e. whether 4118 * the PMC is to be used or not. 4119 */ 4120 4121 case PMC_OP_PMCADMIN: 4122 { 4123 int cpu, ri; 4124 enum pmc_state request; 4125 struct pmc_cpu *pc; 4126 struct pmc_hw *phw; 4127 struct pmc_op_pmcadmin pma; 4128 struct pmc_binding pb; 4129 4130 sx_assert(&pmc_sx, SX_XLOCKED); 4131 4132 KASSERT(td == curthread, 4133 ("[pmc,%d] td != curthread", __LINE__)); 4134 4135 error = priv_check(td, PRIV_PMC_MANAGE); 4136 if (error) 4137 break; 4138 4139 if ((error = copyin(arg, &pma, sizeof(pma))) != 0) 4140 break; 4141 4142 cpu = pma.pm_cpu; 4143 4144 if (cpu < 0 || cpu >= (int) pmc_cpu_max()) { 4145 error = EINVAL; 4146 break; 4147 } 4148 4149 if (!pmc_cpu_is_active(cpu)) { 4150 error = ENXIO; 4151 break; 4152 } 4153 4154 request = pma.pm_state; 4155 4156 if (request != PMC_STATE_DISABLED && 4157 request != PMC_STATE_FREE) { 4158 error = EINVAL; 4159 break; 4160 } 4161 4162 ri = pma.pm_pmc; /* pmc id == row index */ 4163 if (ri < 0 || ri >= (int) md->pmd_npmc) { 4164 error = EINVAL; 4165 break; 4166 } 4167 4168 /* 4169 * We can't disable a PMC with a row-index allocated 4170 * for process virtual PMCs. 4171 */ 4172 4173 if (PMC_ROW_DISP_IS_THREAD(ri) && 4174 request == PMC_STATE_DISABLED) { 4175 error = EBUSY; 4176 break; 4177 } 4178 4179 /* 4180 * otherwise, this PMC on this CPU is either free or 4181 * in system-wide mode. 4182 */ 4183 4184 pmc_save_cpu_binding(&pb); 4185 pmc_select_cpu(cpu); 4186 4187 pc = pmc_pcpu[cpu]; 4188 phw = pc->pc_hwpmcs[ri]; 4189 4190 /* 4191 * XXX do we need some kind of 'forced' disable? 4192 */ 4193 4194 if (phw->phw_pmc == NULL) { 4195 if (request == PMC_STATE_DISABLED && 4196 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) { 4197 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED; 4198 PMC_MARK_ROW_STANDALONE(ri); 4199 } else if (request == PMC_STATE_FREE && 4200 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) { 4201 phw->phw_state |= PMC_PHW_FLAG_IS_ENABLED; 4202 PMC_UNMARK_ROW_STANDALONE(ri); 4203 } 4204 /* other cases are a no-op */ 4205 } else 4206 error = EBUSY; 4207 4208 pmc_restore_cpu_binding(&pb); 4209 } 4210 break; 4211 4212 4213 /* 4214 * Allocate a PMC. 4215 */ 4216 case PMC_OP_PMCALLOCATE: 4217 { 4218 struct pmc_op_pmcallocate pa; 4219 4220 error = copyin(arg, &pa, sizeof(pa)); 4221 if (error != 0) 4222 break; 4223 4224 error = pmc_do_op_pmcallocate(td, &pa); 4225 if (error != 0) 4226 break; 4227 4228 error = copyout(&pa, arg, sizeof(pa)); 4229 } 4230 break; 4231 4232 /* 4233 * Attach a PMC to a process. 4234 */ 4235 case PMC_OP_PMCATTACH: 4236 { 4237 struct pmc_op_pmcattach a; 4238 4239 error = copyin(arg, &a, sizeof(a)); 4240 if (error != 0) 4241 break; 4242 4243 error = pmc_do_op_pmcattach(td, a); 4244 } 4245 break; 4246 4247 /* 4248 * Detach an attached PMC from a process. 4249 */ 4250 case PMC_OP_PMCDETACH: 4251 { 4252 struct pmc_op_pmcattach a; 4253 4254 error = copyin(arg, &a, sizeof(a)); 4255 if (error != 0) 4256 break; 4257 4258 error = pmc_do_op_pmcdetach(td, a); 4259 } 4260 break; 4261 4262 4263 /* 4264 * Retrieve the MSR number associated with the counter 4265 * 'pmc_id'. This allows processes to directly use RDPMC 4266 * instructions to read their PMCs, without the overhead of a 4267 * system call. 4268 */ 4269 4270 case PMC_OP_PMCGETMSR: 4271 { 4272 int adjri, ri; 4273 struct pmc *pm; 4274 struct pmc_target *pt; 4275 struct pmc_op_getmsr gm; 4276 struct pmc_classdep *pcd; 4277 4278 PMC_DOWNGRADE_SX(); 4279 4280 if ((error = copyin(arg, &gm, sizeof(gm))) != 0) 4281 break; 4282 4283 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0) 4284 break; 4285 4286 /* 4287 * The allocated PMC has to be a process virtual PMC, 4288 * i.e., of type MODE_T[CS]. Global PMCs can only be 4289 * read using the PMCREAD operation since they may be 4290 * allocated on a different CPU than the one we could 4291 * be running on at the time of the RDPMC instruction. 4292 * 4293 * The GETMSR operation is not allowed for PMCs that 4294 * are inherited across processes. 4295 */ 4296 4297 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) || 4298 (pm->pm_flags & PMC_F_DESCENDANTS)) { 4299 error = EINVAL; 4300 break; 4301 } 4302 4303 /* 4304 * It only makes sense to use a RDPMC (or its 4305 * equivalent instruction on non-x86 architectures) on 4306 * a process that has allocated and attached a PMC to 4307 * itself. Conversely the PMC is only allowed to have 4308 * one process attached to it -- its owner. 4309 */ 4310 4311 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL || 4312 LIST_NEXT(pt, pt_next) != NULL || 4313 pt->pt_process->pp_proc != pm->pm_owner->po_owner) { 4314 error = EINVAL; 4315 break; 4316 } 4317 4318 ri = PMC_TO_ROWINDEX(pm); 4319 pcd = pmc_ri_to_classdep(md, ri, &adjri); 4320 4321 /* PMC class has no 'GETMSR' support */ 4322 if (pcd->pcd_get_msr == NULL) { 4323 error = ENOSYS; 4324 break; 4325 } 4326 4327 if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0) 4328 break; 4329 4330 if ((error = copyout(&gm, arg, sizeof(gm))) < 0) 4331 break; 4332 4333 /* 4334 * Mark our process as using MSRs. Update machine 4335 * state using a forced context switch. 4336 */ 4337 4338 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS; 4339 pmc_force_context_switch(); 4340 4341 } 4342 break; 4343 4344 /* 4345 * Release an allocated PMC. 4346 */ 4347 case PMC_OP_PMCRELEASE: 4348 { 4349 struct pmc_op_simple sp; 4350 4351 error = copyin(arg, &sp, sizeof(sp)); 4352 if (error != 0) 4353 break; 4354 4355 error = pmc_do_op_pmcrelease(sp.pm_pmcid); 4356 } 4357 break; 4358 4359 /* 4360 * Read and/or write a PMC. 4361 */ 4362 case PMC_OP_PMCRW: 4363 { 4364 struct pmc_op_pmcrw prw; 4365 struct pmc_op_pmcrw *pprw; 4366 pmc_value_t oldvalue; 4367 4368 PMC_DOWNGRADE_SX(); 4369 4370 error = copyin(arg, &prw, sizeof(prw)); 4371 if (error != 0) 4372 break; 4373 4374 error = pmc_do_op_pmcrw(&prw, &oldvalue); 4375 if (error != 0) 4376 break; 4377 4378 /* Return old value if requested. */ 4379 if ((prw.pm_flags & PMC_F_OLDVALUE) != 0) { 4380 pprw = arg; 4381 error = copyout(&oldvalue, &pprw->pm_value, 4382 sizeof(prw.pm_value)); 4383 } 4384 } 4385 break; 4386 4387 4388 /* 4389 * Set the sampling rate for a sampling mode PMC and the 4390 * initial count for a counting mode PMC. 4391 */ 4392 4393 case PMC_OP_PMCSETCOUNT: 4394 { 4395 struct pmc *pm; 4396 struct pmc_op_pmcsetcount sc; 4397 4398 PMC_DOWNGRADE_SX(); 4399 4400 if ((error = copyin(arg, &sc, sizeof(sc))) != 0) 4401 break; 4402 4403 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0) 4404 break; 4405 4406 if (pm->pm_state == PMC_STATE_RUNNING) { 4407 error = EBUSY; 4408 break; 4409 } 4410 4411 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) { 4412 /* 4413 * Don't permit requested sample rate to be 4414 * less than pmc_mincount. 4415 */ 4416 if (sc.pm_count < MAX(1, pmc_mincount)) 4417 log(LOG_WARNING, "pmcsetcount: passed sample " 4418 "rate %ju - setting to %u\n", 4419 (uintmax_t)sc.pm_count, 4420 MAX(1, pmc_mincount)); 4421 pm->pm_sc.pm_reloadcount = MAX(MAX(1, pmc_mincount), 4422 sc.pm_count); 4423 } else 4424 pm->pm_sc.pm_initial = sc.pm_count; 4425 } 4426 break; 4427 4428 4429 /* 4430 * Start a PMC. 4431 */ 4432 4433 case PMC_OP_PMCSTART: 4434 { 4435 pmc_id_t pmcid; 4436 struct pmc *pm; 4437 struct pmc_op_simple sp; 4438 4439 sx_assert(&pmc_sx, SX_XLOCKED); 4440 4441 if ((error = copyin(arg, &sp, sizeof(sp))) != 0) 4442 break; 4443 4444 pmcid = sp.pm_pmcid; 4445 4446 if ((error = pmc_find_pmc(pmcid, &pm)) != 0) 4447 break; 4448 4449 KASSERT(pmcid == pm->pm_id, 4450 ("[pmc,%d] pmcid %x != id %x", __LINE__, 4451 pm->pm_id, pmcid)); 4452 4453 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */ 4454 break; 4455 else if (pm->pm_state != PMC_STATE_STOPPED && 4456 pm->pm_state != PMC_STATE_ALLOCATED) { 4457 error = EINVAL; 4458 break; 4459 } 4460 4461 error = pmc_start(pm); 4462 } 4463 break; 4464 4465 4466 /* 4467 * Stop a PMC. 4468 */ 4469 4470 case PMC_OP_PMCSTOP: 4471 { 4472 pmc_id_t pmcid; 4473 struct pmc *pm; 4474 struct pmc_op_simple sp; 4475 4476 PMC_DOWNGRADE_SX(); 4477 4478 if ((error = copyin(arg, &sp, sizeof(sp))) != 0) 4479 break; 4480 4481 pmcid = sp.pm_pmcid; 4482 4483 /* 4484 * Mark the PMC as inactive and invoke the MD stop 4485 * routines if needed. 4486 */ 4487 4488 if ((error = pmc_find_pmc(pmcid, &pm)) != 0) 4489 break; 4490 4491 KASSERT(pmcid == pm->pm_id, 4492 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__, 4493 pm->pm_id, pmcid)); 4494 4495 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */ 4496 break; 4497 else if (pm->pm_state != PMC_STATE_RUNNING) { 4498 error = EINVAL; 4499 break; 4500 } 4501 4502 error = pmc_stop(pm); 4503 } 4504 break; 4505 4506 4507 /* 4508 * Write a user supplied value to the log file. 4509 */ 4510 4511 case PMC_OP_WRITELOG: 4512 { 4513 struct pmc_op_writelog wl; 4514 struct pmc_owner *po; 4515 4516 PMC_DOWNGRADE_SX(); 4517 4518 if ((error = copyin(arg, &wl, sizeof(wl))) != 0) 4519 break; 4520 4521 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) { 4522 error = EINVAL; 4523 break; 4524 } 4525 4526 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) { 4527 error = EINVAL; 4528 break; 4529 } 4530 4531 error = pmclog_process_userlog(po, &wl); 4532 } 4533 break; 4534 4535 4536 default: 4537 error = EINVAL; 4538 break; 4539 } 4540 4541 if (is_sx_downgraded) 4542 sx_sunlock(&pmc_sx); 4543 else 4544 sx_xunlock(&pmc_sx); 4545 done_syscall: 4546 if (error) 4547 counter_u64_add(pmc_stats.pm_syscall_errors, 1); 4548 4549 return (error); 4550 } 4551 4552 /* 4553 * Helper functions 4554 */ 4555 4556 /* 4557 * Mark the thread as needing callchain capture and post an AST. The 4558 * actual callchain capture will be done in a context where it is safe 4559 * to take page faults. 4560 */ 4561 static void 4562 pmc_post_callchain_callback(void) 4563 { 4564 struct thread *td; 4565 4566 td = curthread; 4567 4568 /* 4569 * If there is multiple PMCs for the same interrupt ignore new post 4570 */ 4571 if ((td->td_pflags & TDP_CALLCHAIN) != 0) 4572 return; 4573 4574 /* 4575 * Mark this thread as needing callchain capture. 4576 * `td->td_pflags' will be safe to touch because this thread 4577 * was in user space when it was interrupted. 4578 */ 4579 td->td_pflags |= TDP_CALLCHAIN; 4580 4581 /* 4582 * Don't let this thread migrate between CPUs until callchain 4583 * capture completes. 4584 */ 4585 sched_pin(); 4586 4587 return; 4588 } 4589 4590 /* 4591 * Find a free slot in the per-cpu array of samples and capture the 4592 * current callchain there. If a sample was successfully added, a bit 4593 * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook 4594 * needs to be invoked from the clock handler. 4595 * 4596 * This function is meant to be called from an NMI handler. It cannot 4597 * use any of the locking primitives supplied by the OS. 4598 */ 4599 static int 4600 pmc_add_sample(ring_type_t ring, struct pmc *pm, struct trapframe *tf) 4601 { 4602 struct pmc_sample *ps; 4603 struct pmc_samplebuffer *psb; 4604 struct thread *td; 4605 int error, cpu, callchaindepth; 4606 bool inuserspace; 4607 4608 error = 0; 4609 4610 /* 4611 * Allocate space for a sample buffer. 4612 */ 4613 cpu = curcpu; 4614 psb = pmc_pcpu[cpu]->pc_sb[ring]; 4615 inuserspace = TRAPF_USERMODE(tf); 4616 ps = PMC_PROD_SAMPLE(psb); 4617 if (psb->ps_considx != psb->ps_prodidx && 4618 ps->ps_nsamples) { /* in use, reader hasn't caught up */ 4619 pm->pm_pcpu_state[cpu].pps_stalled = 1; 4620 counter_u64_add(pmc_stats.pm_intr_bufferfull, 1); 4621 PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", 4622 cpu, pm, tf, inuserspace, 4623 (int)(psb->ps_prodidx & pmc_sample_mask), 4624 (int)(psb->ps_considx & pmc_sample_mask)); 4625 callchaindepth = 1; 4626 error = ENOMEM; 4627 goto done; 4628 } 4629 4630 /* Fill in entry. */ 4631 PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm, tf, 4632 inuserspace, (int)(psb->ps_prodidx & pmc_sample_mask), 4633 (int)(psb->ps_considx & pmc_sample_mask)); 4634 4635 td = curthread; 4636 ps->ps_pmc = pm; 4637 ps->ps_td = td; 4638 ps->ps_pid = td->td_proc->p_pid; 4639 ps->ps_tid = td->td_tid; 4640 ps->ps_tsc = pmc_rdtsc(); 4641 ps->ps_ticks = ticks; 4642 ps->ps_cpu = cpu; 4643 ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0; 4644 4645 callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ? 4646 pmc_callchaindepth : 1; 4647 4648 MPASS(ps->ps_pc != NULL); 4649 if (callchaindepth == 1) { 4650 ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf); 4651 } else { 4652 /* 4653 * Kernel stack traversals can be done immediately, while we 4654 * defer to an AST for user space traversals. 4655 */ 4656 if (!inuserspace) { 4657 callchaindepth = pmc_save_kernel_callchain(ps->ps_pc, 4658 callchaindepth, tf); 4659 } else { 4660 pmc_post_callchain_callback(); 4661 callchaindepth = PMC_USER_CALLCHAIN_PENDING; 4662 } 4663 } 4664 4665 ps->ps_nsamples = callchaindepth; /* mark entry as in-use */ 4666 if (ring == PMC_UR) { 4667 ps->ps_nsamples_actual = callchaindepth; 4668 ps->ps_nsamples = PMC_USER_CALLCHAIN_PENDING; 4669 } 4670 4671 KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0, 4672 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm, 4673 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 4674 4675 counter_u64_add(pm->pm_runcount, 1); /* hold onto PMC */ 4676 /* increment write pointer */ 4677 psb->ps_prodidx++; 4678 done: 4679 /* mark CPU as needing processing */ 4680 if (callchaindepth != PMC_USER_CALLCHAIN_PENDING) 4681 DPCPU_SET(pmc_sampled, 1); 4682 4683 return (error); 4684 } 4685 4686 /* 4687 * Interrupt processing. 4688 * 4689 * This function may be called from an NMI handler. It cannot use any of the 4690 * locking primitives supplied by the OS. 4691 */ 4692 int 4693 pmc_process_interrupt(int ring, struct pmc *pm, struct trapframe *tf) 4694 { 4695 struct thread *td; 4696 4697 td = curthread; 4698 if ((pm->pm_flags & PMC_F_USERCALLCHAIN) && 4699 (td->td_proc->p_flag & P_KPROC) == 0 && !TRAPF_USERMODE(tf)) { 4700 atomic_add_int(&td->td_pmcpend, 1); 4701 return (pmc_add_sample(PMC_UR, pm, tf)); 4702 } 4703 return (pmc_add_sample(ring, pm, tf)); 4704 } 4705 4706 /* 4707 * Capture a user call chain. This function will be called from ast() 4708 * before control returns to userland and before the process gets 4709 * rescheduled. 4710 */ 4711 static void 4712 pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf) 4713 { 4714 struct pmc *pm; 4715 struct pmc_sample *ps; 4716 struct pmc_samplebuffer *psb; 4717 struct thread *td; 4718 uint64_t considx, prodidx; 4719 int nsamples, nrecords, pass, iter; 4720 int start_ticks __diagused; 4721 4722 psb = pmc_pcpu[cpu]->pc_sb[ring]; 4723 td = curthread; 4724 nrecords = INT_MAX; 4725 pass = 0; 4726 start_ticks = ticks; 4727 4728 KASSERT(td->td_pflags & TDP_CALLCHAIN, 4729 ("[pmc,%d] Retrieving callchain for thread that doesn't want it", 4730 __LINE__)); 4731 restart: 4732 if (ring == PMC_UR) 4733 nrecords = atomic_readandclear_32(&td->td_pmcpend); 4734 4735 for (iter = 0, considx = psb->ps_considx, prodidx = psb->ps_prodidx; 4736 considx < prodidx && iter < pmc_nsamples; considx++, iter++) { 4737 ps = PMC_CONS_SAMPLE_OFF(psb, considx); 4738 4739 /* 4740 * Iterate through all deferred callchain requests. Walk from 4741 * the current read pointer to the current write pointer. 4742 */ 4743 #ifdef INVARIANTS 4744 if (ps->ps_nsamples == PMC_SAMPLE_FREE) { 4745 continue; 4746 } 4747 #endif 4748 if (ps->ps_td != td || 4749 ps->ps_nsamples != PMC_USER_CALLCHAIN_PENDING || 4750 ps->ps_pmc->pm_state != PMC_STATE_RUNNING) 4751 continue; 4752 4753 KASSERT(ps->ps_cpu == cpu, 4754 ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__, 4755 ps->ps_cpu, PCPU_GET(cpuid))); 4756 4757 pm = ps->ps_pmc; 4758 KASSERT(pm->pm_flags & PMC_F_CALLCHAIN, 4759 ("[pmc,%d] Retrieving callchain for PMC that doesn't " 4760 "want it", __LINE__)); 4761 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 4762 ("[pmc,%d] runcount %ju", __LINE__, 4763 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 4764 4765 if (ring == PMC_UR) { 4766 nsamples = ps->ps_nsamples_actual; 4767 counter_u64_add(pmc_stats.pm_merges, 1); 4768 } else 4769 nsamples = 0; 4770 4771 /* 4772 * Retrieve the callchain and mark the sample buffer 4773 * as 'processable' by the timer tick sweep code. 4774 */ 4775 if (__predict_true(nsamples < pmc_callchaindepth - 1)) 4776 nsamples += pmc_save_user_callchain(ps->ps_pc + nsamples, 4777 pmc_callchaindepth - nsamples - 1, tf); 4778 4779 /* 4780 * We have to prevent hardclock from potentially overwriting 4781 * this sample between when we read the value and when we set 4782 * it. 4783 */ 4784 spinlock_enter(); 4785 4786 /* 4787 * Verify that the sample hasn't been dropped in the meantime. 4788 */ 4789 if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) { 4790 ps->ps_nsamples = nsamples; 4791 /* 4792 * If we couldn't get a sample, simply drop the 4793 * reference. 4794 */ 4795 if (nsamples == 0) 4796 counter_u64_add(pm->pm_runcount, -1); 4797 } 4798 spinlock_exit(); 4799 if (nrecords-- == 1) 4800 break; 4801 } 4802 if (__predict_false(ring == PMC_UR && td->td_pmcpend)) { 4803 if (pass == 0) { 4804 pass = 1; 4805 goto restart; 4806 } 4807 /* only collect samples for this part once */ 4808 td->td_pmcpend = 0; 4809 } 4810 4811 #ifdef INVARIANTS 4812 if ((ticks - start_ticks) > hz) 4813 log(LOG_ERR, "%s took %d ticks\n", __func__, (ticks - start_ticks)); 4814 #endif 4815 /* mark CPU as needing processing */ 4816 DPCPU_SET(pmc_sampled, 1); 4817 } 4818 4819 /* 4820 * Process saved PC samples. 4821 */ 4822 static void 4823 pmc_process_samples(int cpu, ring_type_t ring) 4824 { 4825 struct pmc *pm; 4826 struct thread *td; 4827 struct pmc_owner *po; 4828 struct pmc_sample *ps; 4829 struct pmc_classdep *pcd; 4830 struct pmc_samplebuffer *psb; 4831 uint64_t delta __diagused; 4832 int adjri, n; 4833 4834 KASSERT(PCPU_GET(cpuid) == cpu, 4835 ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__, 4836 PCPU_GET(cpuid), cpu)); 4837 4838 psb = pmc_pcpu[cpu]->pc_sb[ring]; 4839 delta = psb->ps_prodidx - psb->ps_considx; 4840 MPASS(delta <= pmc_nsamples); 4841 MPASS(psb->ps_considx <= psb->ps_prodidx); 4842 for (n = 0; psb->ps_considx < psb->ps_prodidx; psb->ps_considx++, n++) { 4843 ps = PMC_CONS_SAMPLE(psb); 4844 4845 if (__predict_false(ps->ps_nsamples == PMC_SAMPLE_FREE)) 4846 continue; 4847 4848 /* skip non-running samples */ 4849 pm = ps->ps_pmc; 4850 if (pm->pm_state != PMC_STATE_RUNNING) 4851 goto entrydone; 4852 4853 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 4854 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm, 4855 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 4856 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)), 4857 ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__, 4858 pm, PMC_TO_MODE(pm))); 4859 4860 po = pm->pm_owner; 4861 4862 /* If there is a pending AST wait for completion */ 4863 if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) { 4864 /* 4865 * If we've been waiting more than 1 tick to 4866 * collect a callchain for this record then 4867 * drop it and move on. 4868 */ 4869 if (ticks - ps->ps_ticks > 1) { 4870 /* 4871 * Track how often we hit this as it will 4872 * preferentially lose user samples 4873 * for long running system calls. 4874 */ 4875 counter_u64_add(pmc_stats.pm_overwrites, 1); 4876 goto entrydone; 4877 } 4878 /* Need a rescan at a later time. */ 4879 DPCPU_SET(pmc_sampled, 1); 4880 break; 4881 } 4882 4883 PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu, 4884 pm, ps->ps_nsamples, ps->ps_flags, 4885 (int)(psb->ps_prodidx & pmc_sample_mask), 4886 (int)(psb->ps_considx & pmc_sample_mask)); 4887 4888 /* 4889 * If this is a process-mode PMC that is attached to 4890 * its owner, and if the PC is in user mode, update 4891 * profiling statistics like timer-based profiling 4892 * would have done. 4893 * 4894 * Otherwise, this is either a sampling-mode PMC that 4895 * is attached to a different process than its owner, 4896 * or a system-wide sampling PMC. Dispatch a log 4897 * entry to the PMC's owner process. 4898 */ 4899 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) { 4900 if (ps->ps_flags & PMC_CC_F_USERSPACE) { 4901 td = FIRST_THREAD_IN_PROC(po->po_owner); 4902 addupc_intr(td, ps->ps_pc[0], 1); 4903 } 4904 } else 4905 pmclog_process_callchain(pm, ps); 4906 4907 entrydone: 4908 ps->ps_nsamples = 0; /* mark entry as free */ 4909 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 4910 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm, 4911 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 4912 4913 counter_u64_add(pm->pm_runcount, -1); 4914 } 4915 4916 counter_u64_add(pmc_stats.pm_log_sweeps, 1); 4917 4918 /* Do not re-enable stalled PMCs if we failed to process any samples */ 4919 if (n == 0) 4920 return; 4921 4922 /* 4923 * Restart any stalled sampling PMCs on this CPU. 4924 * 4925 * If the NMI handler sets the pm_stalled field of a PMC after 4926 * the check below, we'll end up processing the stalled PMC at 4927 * the next hardclock tick. 4928 */ 4929 for (n = 0; n < md->pmd_npmc; n++) { 4930 pcd = pmc_ri_to_classdep(md, n, &adjri); 4931 KASSERT(pcd != NULL, 4932 ("[pmc,%d] null pcd ri=%d", __LINE__, n)); 4933 (void)(*pcd->pcd_get_config)(cpu, adjri, &pm); 4934 4935 if (pm == NULL || /* !cfg'ed */ 4936 pm->pm_state != PMC_STATE_RUNNING || /* !active */ 4937 !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */ 4938 !pm->pm_pcpu_state[cpu].pps_cpustate || /* !desired */ 4939 !pm->pm_pcpu_state[cpu].pps_stalled) /* !stalled */ 4940 continue; 4941 4942 pm->pm_pcpu_state[cpu].pps_stalled = 0; 4943 (void)(*pcd->pcd_start_pmc)(cpu, adjri, pm); 4944 } 4945 } 4946 4947 /* 4948 * Event handlers. 4949 */ 4950 4951 /* 4952 * Handle a process exit. 4953 * 4954 * Remove this process from all hash tables. If this process 4955 * owned any PMCs, turn off those PMCs and deallocate them, 4956 * removing any associations with target processes. 4957 * 4958 * This function will be called by the last 'thread' of a 4959 * process. 4960 * 4961 * XXX This eventhandler gets called early in the exit process. 4962 * Consider using a 'hook' invocation from thread_exit() or equivalent 4963 * spot. Another negative is that kse_exit doesn't seem to call 4964 * exit1() [??]. 4965 */ 4966 static void 4967 pmc_process_exit(void *arg __unused, struct proc *p) 4968 { 4969 struct pmc *pm; 4970 struct pmc_owner *po; 4971 struct pmc_process *pp; 4972 struct pmc_classdep *pcd; 4973 pmc_value_t newvalue, tmp; 4974 int ri, adjri, cpu; 4975 bool is_using_hwpmcs; 4976 4977 PROC_LOCK(p); 4978 is_using_hwpmcs = (p->p_flag & P_HWPMC) != 0; 4979 PROC_UNLOCK(p); 4980 4981 /* 4982 * Log a sysexit event to all SS PMC owners. 4983 */ 4984 PMC_EPOCH_ENTER(); 4985 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 4986 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 4987 pmclog_process_sysexit(po, p->p_pid); 4988 } 4989 PMC_EPOCH_EXIT(); 4990 4991 if (!is_using_hwpmcs) 4992 return; 4993 4994 PMC_GET_SX_XLOCK(); 4995 PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid, 4996 p->p_comm); 4997 4998 /* 4999 * Since this code is invoked by the last thread in an exiting process, 5000 * we would have context switched IN at some prior point. However, with 5001 * PREEMPTION, kernel mode context switches may happen any time, so we 5002 * want to disable a context switch OUT till we get any PMCs targeting 5003 * this process off the hardware. 5004 * 5005 * We also need to atomically remove this process' entry from our 5006 * target process hash table, using PMC_FLAG_REMOVE. 5007 */ 5008 PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid, 5009 p->p_comm); 5010 5011 critical_enter(); /* no preemption */ 5012 5013 cpu = curthread->td_oncpu; 5014 5015 pp = pmc_find_process_descriptor(p, PMC_FLAG_REMOVE); 5016 if (pp == NULL) { 5017 critical_exit(); 5018 goto out; 5019 } 5020 5021 PMCDBG2(PRC,EXT,2, "process-exit proc=%p pmc-process=%p", p, pp); 5022 5023 /* 5024 * The exiting process could be the target of some PMCs which will be 5025 * running on currently executing CPU. 5026 * 5027 * We need to turn these PMCs off like we would do at context switch 5028 * OUT time. 5029 */ 5030 for (ri = 0; ri < md->pmd_npmc; ri++) { 5031 /* 5032 * Pick up the pmc pointer from hardware state similar to the 5033 * CSW_OUT code. 5034 */ 5035 pm = NULL; 5036 pcd = pmc_ri_to_classdep(md, ri, &adjri); 5037 5038 (void)(*pcd->pcd_get_config)(cpu, adjri, &pm); 5039 5040 PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm); 5041 5042 if (pm == NULL || !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) 5043 continue; 5044 5045 PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p state=%d", ri, 5046 pp->pp_pmcs[ri].pp_pmc, pm, pm->pm_state); 5047 5048 KASSERT(PMC_TO_ROWINDEX(pm) == ri, 5049 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)", __LINE__, 5050 PMC_TO_ROWINDEX(pm), ri)); 5051 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc, 5052 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__, pm, ri, 5053 pp->pp_pmcs[ri].pp_pmc)); 5054 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 5055 ("[pmc,%d] bad runcount ri %d rc %ju", __LINE__, ri, 5056 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 5057 5058 /* 5059 * Change desired state, and then stop if not stalled. This 5060 * two-step dance should avoid race conditions where an 5061 * interrupt re-enables the PMC after this code has already 5062 * checked the pm_stalled flag. 5063 */ 5064 if (pm->pm_pcpu_state[cpu].pps_cpustate) { 5065 pm->pm_pcpu_state[cpu].pps_cpustate = 0; 5066 if (!pm->pm_pcpu_state[cpu].pps_stalled) { 5067 (void)pcd->pcd_stop_pmc(cpu, adjri, pm); 5068 5069 if (PMC_TO_MODE(pm) == PMC_MODE_TC) { 5070 pcd->pcd_read_pmc(cpu, adjri, pm, 5071 &newvalue); 5072 tmp = newvalue - PMC_PCPU_SAVED(cpu, ri); 5073 5074 mtx_pool_lock_spin(pmc_mtxpool, pm); 5075 pm->pm_gv.pm_savedvalue += tmp; 5076 pp->pp_pmcs[ri].pp_pmcval += tmp; 5077 mtx_pool_unlock_spin(pmc_mtxpool, pm); 5078 } 5079 } 5080 } 5081 5082 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 5083 ("[pmc,%d] runcount is %d", __LINE__, ri)); 5084 5085 counter_u64_add(pm->pm_runcount, -1); 5086 (void)pcd->pcd_config_pmc(cpu, adjri, NULL); 5087 } 5088 5089 /* 5090 * Inform the MD layer of this pseudo "context switch out". 5091 */ 5092 (void)md->pmd_switch_out(pmc_pcpu[cpu], pp); 5093 5094 critical_exit(); /* ok to be pre-empted now */ 5095 5096 /* 5097 * Unlink this process from the PMCs that are targeting it. This will 5098 * send a signal to all PMC owner's whose PMCs are orphaned. 5099 * 5100 * Log PMC value at exit time if requested. 5101 */ 5102 for (ri = 0; ri < md->pmd_npmc; ri++) { 5103 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) { 5104 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) != 0 && 5105 PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm))) { 5106 pmclog_process_procexit(pm, pp); 5107 } 5108 pmc_unlink_target_process(pm, pp); 5109 } 5110 } 5111 free(pp, M_PMC); 5112 5113 out: 5114 /* 5115 * If the process owned PMCs, free them up and free up memory. 5116 */ 5117 if ((po = pmc_find_owner_descriptor(p)) != NULL) { 5118 pmc_remove_owner(po); 5119 pmc_destroy_owner_descriptor(po); 5120 } 5121 5122 sx_xunlock(&pmc_sx); 5123 } 5124 5125 /* 5126 * Handle a process fork. 5127 * 5128 * If the parent process 'p1' is under HWPMC monitoring, then copy 5129 * over any attached PMCs that have 'do_descendants' semantics. 5130 */ 5131 static void 5132 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc, 5133 int flags __unused) 5134 { 5135 struct pmc *pm; 5136 struct pmc_owner *po; 5137 struct pmc_process *ppnew, *ppold; 5138 unsigned int ri; 5139 bool is_using_hwpmcs, do_descendants; 5140 5141 PROC_LOCK(p1); 5142 is_using_hwpmcs = (p1->p_flag & P_HWPMC) != 0; 5143 PROC_UNLOCK(p1); 5144 5145 /* 5146 * If there are system-wide sampling PMCs active, we need to 5147 * log all fork events to their owner's logs. 5148 */ 5149 PMC_EPOCH_ENTER(); 5150 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5151 if (po->po_flags & PMC_PO_OWNS_LOGFILE) { 5152 pmclog_process_procfork(po, p1->p_pid, newproc->p_pid); 5153 pmclog_process_proccreate(po, newproc, 1); 5154 } 5155 } 5156 PMC_EPOCH_EXIT(); 5157 5158 if (!is_using_hwpmcs) 5159 return; 5160 5161 PMC_GET_SX_XLOCK(); 5162 PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1, 5163 p1->p_pid, p1->p_comm, newproc); 5164 5165 /* 5166 * If the parent process (curthread->td_proc) is a 5167 * target of any PMCs, look for PMCs that are to be 5168 * inherited, and link these into the new process 5169 * descriptor. 5170 */ 5171 ppold = pmc_find_process_descriptor(curthread->td_proc, PMC_FLAG_NONE); 5172 if (ppold == NULL) 5173 goto done; /* nothing to do */ 5174 5175 do_descendants = false; 5176 for (ri = 0; ri < md->pmd_npmc; ri++) { 5177 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL && 5178 (pm->pm_flags & PMC_F_DESCENDANTS) != 0) { 5179 do_descendants = true; 5180 break; 5181 } 5182 } 5183 if (!do_descendants) /* nothing to do */ 5184 goto done; 5185 5186 /* 5187 * Now mark the new process as being tracked by this driver. 5188 */ 5189 PROC_LOCK(newproc); 5190 newproc->p_flag |= P_HWPMC; 5191 PROC_UNLOCK(newproc); 5192 5193 /* Allocate a descriptor for the new process. */ 5194 ppnew = pmc_find_process_descriptor(newproc, PMC_FLAG_ALLOCATE); 5195 if (ppnew == NULL) 5196 goto done; 5197 5198 /* 5199 * Run through all PMCs that were targeting the old process 5200 * and which specified F_DESCENDANTS and attach them to the 5201 * new process. 5202 * 5203 * Log the fork event to all owners of PMCs attached to this 5204 * process, if not already logged. 5205 */ 5206 for (ri = 0; ri < md->pmd_npmc; ri++) { 5207 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL && 5208 (pm->pm_flags & PMC_F_DESCENDANTS) != 0) { 5209 pmc_link_target_process(pm, ppnew); 5210 po = pm->pm_owner; 5211 if (po->po_sscount == 0 && 5212 (po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) { 5213 pmclog_process_procfork(po, p1->p_pid, 5214 newproc->p_pid); 5215 } 5216 } 5217 } 5218 5219 done: 5220 sx_xunlock(&pmc_sx); 5221 } 5222 5223 static void 5224 pmc_process_threadcreate(struct thread *td) 5225 { 5226 struct pmc_owner *po; 5227 5228 PMC_EPOCH_ENTER(); 5229 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5230 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 5231 pmclog_process_threadcreate(po, td, 1); 5232 } 5233 PMC_EPOCH_EXIT(); 5234 } 5235 5236 static void 5237 pmc_process_threadexit(struct thread *td) 5238 { 5239 struct pmc_owner *po; 5240 5241 PMC_EPOCH_ENTER(); 5242 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5243 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 5244 pmclog_process_threadexit(po, td); 5245 } 5246 PMC_EPOCH_EXIT(); 5247 } 5248 5249 static void 5250 pmc_process_proccreate(struct proc *p) 5251 { 5252 struct pmc_owner *po; 5253 5254 PMC_EPOCH_ENTER(); 5255 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5256 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 5257 pmclog_process_proccreate(po, p, 1 /* sync */); 5258 } 5259 PMC_EPOCH_EXIT(); 5260 } 5261 5262 static void 5263 pmc_process_allproc(struct pmc *pm) 5264 { 5265 struct pmc_owner *po; 5266 struct thread *td; 5267 struct proc *p; 5268 5269 po = pm->pm_owner; 5270 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) 5271 return; 5272 5273 sx_slock(&allproc_lock); 5274 FOREACH_PROC_IN_SYSTEM(p) { 5275 pmclog_process_proccreate(po, p, 0 /* sync */); 5276 PROC_LOCK(p); 5277 FOREACH_THREAD_IN_PROC(p, td) 5278 pmclog_process_threadcreate(po, td, 0 /* sync */); 5279 PROC_UNLOCK(p); 5280 } 5281 sx_sunlock(&allproc_lock); 5282 pmclog_flush(po, 0); 5283 } 5284 5285 static void 5286 pmc_kld_load(void *arg __unused, linker_file_t lf) 5287 { 5288 struct pmc_owner *po; 5289 5290 /* 5291 * Notify owners of system sampling PMCs about KLD operations. 5292 */ 5293 PMC_EPOCH_ENTER(); 5294 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5295 if (po->po_flags & PMC_PO_OWNS_LOGFILE) 5296 pmclog_process_map_in(po, (pid_t) -1, 5297 (uintfptr_t) lf->address, lf->pathname); 5298 } 5299 PMC_EPOCH_EXIT(); 5300 5301 /* 5302 * TODO: Notify owners of (all) process-sampling PMCs too. 5303 */ 5304 } 5305 5306 static void 5307 pmc_kld_unload(void *arg __unused, const char *filename __unused, 5308 caddr_t address, size_t size) 5309 { 5310 struct pmc_owner *po; 5311 5312 PMC_EPOCH_ENTER(); 5313 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5314 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) { 5315 pmclog_process_map_out(po, (pid_t)-1, 5316 (uintfptr_t)address, (uintfptr_t)address + size); 5317 } 5318 } 5319 PMC_EPOCH_EXIT(); 5320 5321 /* 5322 * TODO: Notify owners of process-sampling PMCs. 5323 */ 5324 } 5325 5326 /* 5327 * initialization 5328 */ 5329 static const char * 5330 pmc_name_of_pmcclass(enum pmc_class class) 5331 { 5332 5333 switch (class) { 5334 #undef __PMC_CLASS 5335 #define __PMC_CLASS(S,V,D) \ 5336 case PMC_CLASS_##S: \ 5337 return #S; 5338 __PMC_CLASSES(); 5339 default: 5340 return ("<unknown>"); 5341 } 5342 } 5343 5344 /* 5345 * Base class initializer: allocate structure and set default classes. 5346 */ 5347 struct pmc_mdep * 5348 pmc_mdep_alloc(int nclasses) 5349 { 5350 struct pmc_mdep *md; 5351 int n; 5352 5353 /* SOFT + md classes */ 5354 n = 1 + nclasses; 5355 md = malloc(sizeof(struct pmc_mdep) + n * sizeof(struct pmc_classdep), 5356 M_PMC, M_WAITOK | M_ZERO); 5357 md->pmd_nclass = n; 5358 5359 /* Default methods */ 5360 md->pmd_switch_in = generic_switch_in; 5361 md->pmd_switch_out = generic_switch_out; 5362 5363 /* Add base class. */ 5364 pmc_soft_initialize(md); 5365 return (md); 5366 } 5367 5368 void 5369 pmc_mdep_free(struct pmc_mdep *md) 5370 { 5371 pmc_soft_finalize(md); 5372 free(md, M_PMC); 5373 } 5374 5375 static int 5376 generic_switch_in(struct pmc_cpu *pc __unused, struct pmc_process *pp __unused) 5377 { 5378 5379 return (0); 5380 } 5381 5382 static int 5383 generic_switch_out(struct pmc_cpu *pc __unused, struct pmc_process *pp __unused) 5384 { 5385 5386 return (0); 5387 } 5388 5389 static struct pmc_mdep * 5390 pmc_generic_cpu_initialize(void) 5391 { 5392 struct pmc_mdep *md; 5393 5394 md = pmc_mdep_alloc(0); 5395 5396 md->pmd_cputype = PMC_CPU_GENERIC; 5397 5398 return (md); 5399 } 5400 5401 static void 5402 pmc_generic_cpu_finalize(struct pmc_mdep *md __unused) 5403 { 5404 5405 } 5406 5407 static int 5408 pmc_initialize(void) 5409 { 5410 struct pcpu *pc; 5411 struct pmc_binding pb; 5412 struct pmc_classdep *pcd; 5413 struct pmc_sample *ps; 5414 struct pmc_samplebuffer *sb; 5415 int c, cpu, error, n, ri; 5416 u_int maxcpu, domain; 5417 5418 md = NULL; 5419 error = 0; 5420 5421 pmc_stats.pm_intr_ignored = counter_u64_alloc(M_WAITOK); 5422 pmc_stats.pm_intr_processed = counter_u64_alloc(M_WAITOK); 5423 pmc_stats.pm_intr_bufferfull = counter_u64_alloc(M_WAITOK); 5424 pmc_stats.pm_syscalls = counter_u64_alloc(M_WAITOK); 5425 pmc_stats.pm_syscall_errors = counter_u64_alloc(M_WAITOK); 5426 pmc_stats.pm_buffer_requests = counter_u64_alloc(M_WAITOK); 5427 pmc_stats.pm_buffer_requests_failed = counter_u64_alloc(M_WAITOK); 5428 pmc_stats.pm_log_sweeps = counter_u64_alloc(M_WAITOK); 5429 pmc_stats.pm_merges = counter_u64_alloc(M_WAITOK); 5430 pmc_stats.pm_overwrites = counter_u64_alloc(M_WAITOK); 5431 5432 #ifdef HWPMC_DEBUG 5433 /* parse debug flags first */ 5434 if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags", 5435 pmc_debugstr, sizeof(pmc_debugstr))) { 5436 pmc_debugflags_parse(pmc_debugstr, pmc_debugstr + 5437 strlen(pmc_debugstr)); 5438 } 5439 #endif 5440 5441 PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION); 5442 5443 /* check kernel version */ 5444 if (pmc_kernel_version != PMC_VERSION) { 5445 if (pmc_kernel_version == 0) 5446 printf("hwpmc: this kernel has not been compiled with " 5447 "'options HWPMC_HOOKS'.\n"); 5448 else 5449 printf("hwpmc: kernel version (0x%x) does not match " 5450 "module version (0x%x).\n", pmc_kernel_version, 5451 PMC_VERSION); 5452 return (EPROGMISMATCH); 5453 } 5454 5455 /* 5456 * check sysctl parameters 5457 */ 5458 if (pmc_hashsize <= 0) { 5459 printf("hwpmc: tunable \"hashsize\"=%d must be " 5460 "greater than zero.\n", pmc_hashsize); 5461 pmc_hashsize = PMC_HASH_SIZE; 5462 } 5463 5464 if (pmc_nsamples <= 0 || pmc_nsamples > 65535) { 5465 printf("hwpmc: tunable \"nsamples\"=%d out of " 5466 "range.\n", pmc_nsamples); 5467 pmc_nsamples = PMC_NSAMPLES; 5468 } 5469 pmc_sample_mask = pmc_nsamples - 1; 5470 5471 if (pmc_callchaindepth <= 0 || 5472 pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) { 5473 printf("hwpmc: tunable \"callchaindepth\"=%d out of " 5474 "range - using %d.\n", pmc_callchaindepth, 5475 PMC_CALLCHAIN_DEPTH_MAX); 5476 pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX; 5477 } 5478 5479 md = pmc_md_initialize(); 5480 if (md == NULL) { 5481 /* Default to generic CPU. */ 5482 md = pmc_generic_cpu_initialize(); 5483 if (md == NULL) 5484 return (ENOSYS); 5485 } 5486 5487 /* 5488 * Refresh classes base ri. Optional classes may come in different 5489 * order. 5490 */ 5491 for (ri = c = 0; c < md->pmd_nclass; c++) { 5492 pcd = &md->pmd_classdep[c]; 5493 pcd->pcd_ri = ri; 5494 ri += pcd->pcd_num; 5495 } 5496 5497 KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1, 5498 ("[pmc,%d] no classes or pmcs", __LINE__)); 5499 5500 /* Compute the map from row-indices to classdep pointers. */ 5501 pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) * 5502 md->pmd_npmc, M_PMC, M_WAITOK | M_ZERO); 5503 5504 for (n = 0; n < md->pmd_npmc; n++) 5505 pmc_rowindex_to_classdep[n] = NULL; 5506 5507 for (ri = c = 0; c < md->pmd_nclass; c++) { 5508 pcd = &md->pmd_classdep[c]; 5509 for (n = 0; n < pcd->pcd_num; n++, ri++) 5510 pmc_rowindex_to_classdep[ri] = pcd; 5511 } 5512 5513 KASSERT(ri == md->pmd_npmc, 5514 ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__, 5515 ri, md->pmd_npmc)); 5516 5517 maxcpu = pmc_cpu_max(); 5518 5519 /* allocate space for the per-cpu array */ 5520 pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC, 5521 M_WAITOK | M_ZERO); 5522 5523 /* per-cpu 'saved values' for managing process-mode PMCs */ 5524 pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc, 5525 M_PMC, M_WAITOK); 5526 5527 /* Perform CPU-dependent initialization. */ 5528 pmc_save_cpu_binding(&pb); 5529 error = 0; 5530 for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) { 5531 if (!pmc_cpu_is_active(cpu)) 5532 continue; 5533 pmc_select_cpu(cpu); 5534 pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) + 5535 md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC, 5536 M_WAITOK | M_ZERO); 5537 for (n = 0; error == 0 && n < md->pmd_nclass; n++) 5538 if (md->pmd_classdep[n].pcd_num > 0) 5539 error = md->pmd_classdep[n].pcd_pcpu_init(md, 5540 cpu); 5541 } 5542 pmc_restore_cpu_binding(&pb); 5543 5544 if (error != 0) 5545 return (error); 5546 5547 /* allocate space for the sample array */ 5548 for (cpu = 0; cpu < maxcpu; cpu++) { 5549 if (!pmc_cpu_is_active(cpu)) 5550 continue; 5551 pc = pcpu_find(cpu); 5552 domain = pc->pc_domain; 5553 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) + 5554 pmc_nsamples * sizeof(struct pmc_sample), M_PMC, 5555 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5556 5557 KASSERT(pmc_pcpu[cpu] != NULL, 5558 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu)); 5559 5560 sb->ps_callchains = malloc_domainset(pmc_callchaindepth * 5561 pmc_nsamples * sizeof(uintptr_t), M_PMC, 5562 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5563 5564 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++) 5565 ps->ps_pc = sb->ps_callchains + 5566 (n * pmc_callchaindepth); 5567 5568 pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb; 5569 5570 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) + 5571 pmc_nsamples * sizeof(struct pmc_sample), M_PMC, 5572 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5573 5574 sb->ps_callchains = malloc_domainset(pmc_callchaindepth * 5575 pmc_nsamples * sizeof(uintptr_t), M_PMC, 5576 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5577 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++) 5578 ps->ps_pc = sb->ps_callchains + 5579 (n * pmc_callchaindepth); 5580 5581 pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb; 5582 5583 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) + 5584 pmc_nsamples * sizeof(struct pmc_sample), M_PMC, 5585 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5586 sb->ps_callchains = malloc_domainset(pmc_callchaindepth * 5587 pmc_nsamples * sizeof(uintptr_t), M_PMC, 5588 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5589 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++) 5590 ps->ps_pc = sb->ps_callchains + n * pmc_callchaindepth; 5591 5592 pmc_pcpu[cpu]->pc_sb[PMC_UR] = sb; 5593 } 5594 5595 /* allocate space for the row disposition array */ 5596 pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc, 5597 M_PMC, M_WAITOK | M_ZERO); 5598 5599 /* mark all PMCs as available */ 5600 for (n = 0; n < md->pmd_npmc; n++) 5601 PMC_MARK_ROW_FREE(n); 5602 5603 /* allocate thread hash tables */ 5604 pmc_ownerhash = hashinit(pmc_hashsize, M_PMC, 5605 &pmc_ownerhashmask); 5606 5607 pmc_processhash = hashinit(pmc_hashsize, M_PMC, 5608 &pmc_processhashmask); 5609 mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf", 5610 MTX_SPIN); 5611 5612 CK_LIST_INIT(&pmc_ss_owners); 5613 pmc_ss_count = 0; 5614 5615 /* allocate a pool of spin mutexes */ 5616 pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size, 5617 MTX_SPIN); 5618 5619 PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx " 5620 "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask, 5621 pmc_processhash, pmc_processhashmask); 5622 5623 /* Initialize a spin mutex for the thread free list. */ 5624 mtx_init(&pmc_threadfreelist_mtx, "pmc-threadfreelist", "pmc-leaf", 5625 MTX_SPIN); 5626 5627 /* Initialize the task to prune the thread free list. */ 5628 TASK_INIT(&free_task, 0, pmc_thread_descriptor_pool_free_task, NULL); 5629 5630 /* register process {exit,fork,exec} handlers */ 5631 pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit, 5632 pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY); 5633 pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork, 5634 pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY); 5635 5636 /* register kld event handlers */ 5637 pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load, 5638 NULL, EVENTHANDLER_PRI_ANY); 5639 pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload, 5640 NULL, EVENTHANDLER_PRI_ANY); 5641 5642 /* initialize logging */ 5643 pmclog_initialize(); 5644 5645 /* set hook functions */ 5646 pmc_intr = md->pmd_intr; 5647 wmb(); 5648 pmc_hook = pmc_hook_handler; 5649 5650 if (error == 0) { 5651 printf(PMC_MODULE_NAME ":"); 5652 for (n = 0; n < md->pmd_nclass; n++) { 5653 if (md->pmd_classdep[n].pcd_num == 0) 5654 continue; 5655 pcd = &md->pmd_classdep[n]; 5656 printf(" %s/%d/%d/0x%b", 5657 pmc_name_of_pmcclass(pcd->pcd_class), 5658 pcd->pcd_num, 5659 pcd->pcd_width, 5660 pcd->pcd_caps, 5661 "\20" 5662 "\1INT\2USR\3SYS\4EDG\5THR" 5663 "\6REA\7WRI\10INV\11QUA\12PRC" 5664 "\13TAG\14CSC"); 5665 } 5666 printf("\n"); 5667 } 5668 5669 return (error); 5670 } 5671 5672 /* prepare to be unloaded */ 5673 static void 5674 pmc_cleanup(void) 5675 { 5676 struct pmc_binding pb; 5677 struct pmc_owner *po, *tmp; 5678 struct pmc_ownerhash *ph; 5679 struct pmc_processhash *prh __pmcdbg_used; 5680 u_int maxcpu; 5681 int cpu, c; 5682 5683 PMCDBG0(MOD,INI,0, "cleanup"); 5684 5685 /* switch off sampling */ 5686 CPU_FOREACH(cpu) 5687 DPCPU_ID_SET(cpu, pmc_sampled, 0); 5688 pmc_intr = NULL; 5689 5690 sx_xlock(&pmc_sx); 5691 if (pmc_hook == NULL) { /* being unloaded already */ 5692 sx_xunlock(&pmc_sx); 5693 return; 5694 } 5695 5696 pmc_hook = NULL; /* prevent new threads from entering module */ 5697 5698 /* deregister event handlers */ 5699 EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag); 5700 EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag); 5701 EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag); 5702 EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag); 5703 5704 /* send SIGBUS to all owner threads, free up allocations */ 5705 if (pmc_ownerhash != NULL) { 5706 for (ph = pmc_ownerhash; 5707 ph <= &pmc_ownerhash[pmc_ownerhashmask]; 5708 ph++) { 5709 LIST_FOREACH_SAFE(po, ph, po_next, tmp) { 5710 pmc_remove_owner(po); 5711 5712 PMCDBG3(MOD,INI,2, 5713 "cleanup signal proc=%p (%d, %s)", 5714 po->po_owner, po->po_owner->p_pid, 5715 po->po_owner->p_comm); 5716 5717 PROC_LOCK(po->po_owner); 5718 kern_psignal(po->po_owner, SIGBUS); 5719 PROC_UNLOCK(po->po_owner); 5720 5721 pmc_destroy_owner_descriptor(po); 5722 } 5723 } 5724 } 5725 5726 /* reclaim allocated data structures */ 5727 taskqueue_drain(taskqueue_fast, &free_task); 5728 mtx_destroy(&pmc_threadfreelist_mtx); 5729 pmc_thread_descriptor_pool_drain(); 5730 5731 if (pmc_mtxpool != NULL) 5732 mtx_pool_destroy(&pmc_mtxpool); 5733 5734 mtx_destroy(&pmc_processhash_mtx); 5735 if (pmc_processhash != NULL) { 5736 #ifdef HWPMC_DEBUG 5737 struct pmc_process *pp; 5738 5739 PMCDBG0(MOD,INI,3, "destroy process hash"); 5740 for (prh = pmc_processhash; 5741 prh <= &pmc_processhash[pmc_processhashmask]; 5742 prh++) 5743 LIST_FOREACH(pp, prh, pp_next) 5744 PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid); 5745 #endif 5746 5747 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask); 5748 pmc_processhash = NULL; 5749 } 5750 5751 if (pmc_ownerhash != NULL) { 5752 PMCDBG0(MOD,INI,3, "destroy owner hash"); 5753 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask); 5754 pmc_ownerhash = NULL; 5755 } 5756 5757 KASSERT(CK_LIST_EMPTY(&pmc_ss_owners), 5758 ("[pmc,%d] Global SS owner list not empty", __LINE__)); 5759 KASSERT(pmc_ss_count == 0, 5760 ("[pmc,%d] Global SS count not empty", __LINE__)); 5761 5762 /* do processor and pmc-class dependent cleanup */ 5763 maxcpu = pmc_cpu_max(); 5764 5765 PMCDBG0(MOD,INI,3, "md cleanup"); 5766 if (md) { 5767 pmc_save_cpu_binding(&pb); 5768 for (cpu = 0; cpu < maxcpu; cpu++) { 5769 PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p", 5770 cpu, pmc_pcpu[cpu]); 5771 if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL) 5772 continue; 5773 5774 pmc_select_cpu(cpu); 5775 for (c = 0; c < md->pmd_nclass; c++) { 5776 if (md->pmd_classdep[c].pcd_num > 0) { 5777 md->pmd_classdep[c].pcd_pcpu_fini(md, 5778 cpu); 5779 } 5780 } 5781 } 5782 5783 if (md->pmd_cputype == PMC_CPU_GENERIC) 5784 pmc_generic_cpu_finalize(md); 5785 else 5786 pmc_md_finalize(md); 5787 5788 pmc_mdep_free(md); 5789 md = NULL; 5790 pmc_restore_cpu_binding(&pb); 5791 } 5792 5793 /* Free per-cpu descriptors. */ 5794 for (cpu = 0; cpu < maxcpu; cpu++) { 5795 if (!pmc_cpu_is_active(cpu)) 5796 continue; 5797 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL, 5798 ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__, 5799 cpu)); 5800 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL, 5801 ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__, 5802 cpu)); 5803 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_UR] != NULL, 5804 ("[pmc,%d] Null userret cpu sample buffer cpu=%d", __LINE__, 5805 cpu)); 5806 free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC); 5807 free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC); 5808 free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC); 5809 free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC); 5810 free(pmc_pcpu[cpu]->pc_sb[PMC_UR]->ps_callchains, M_PMC); 5811 free(pmc_pcpu[cpu]->pc_sb[PMC_UR], M_PMC); 5812 free(pmc_pcpu[cpu], M_PMC); 5813 } 5814 5815 free(pmc_pcpu, M_PMC); 5816 pmc_pcpu = NULL; 5817 5818 free(pmc_pcpu_saved, M_PMC); 5819 pmc_pcpu_saved = NULL; 5820 5821 if (pmc_pmcdisp != NULL) { 5822 free(pmc_pmcdisp, M_PMC); 5823 pmc_pmcdisp = NULL; 5824 } 5825 5826 if (pmc_rowindex_to_classdep != NULL) { 5827 free(pmc_rowindex_to_classdep, M_PMC); 5828 pmc_rowindex_to_classdep = NULL; 5829 } 5830 5831 pmclog_shutdown(); 5832 counter_u64_free(pmc_stats.pm_intr_ignored); 5833 counter_u64_free(pmc_stats.pm_intr_processed); 5834 counter_u64_free(pmc_stats.pm_intr_bufferfull); 5835 counter_u64_free(pmc_stats.pm_syscalls); 5836 counter_u64_free(pmc_stats.pm_syscall_errors); 5837 counter_u64_free(pmc_stats.pm_buffer_requests); 5838 counter_u64_free(pmc_stats.pm_buffer_requests_failed); 5839 counter_u64_free(pmc_stats.pm_log_sweeps); 5840 counter_u64_free(pmc_stats.pm_merges); 5841 counter_u64_free(pmc_stats.pm_overwrites); 5842 sx_xunlock(&pmc_sx); /* we are done */ 5843 } 5844 5845 /* 5846 * The function called at load/unload. 5847 */ 5848 static int 5849 load(struct module *module __unused, int cmd, void *arg __unused) 5850 { 5851 int error; 5852 5853 error = 0; 5854 5855 switch (cmd) { 5856 case MOD_LOAD: 5857 /* initialize the subsystem */ 5858 error = pmc_initialize(); 5859 if (error != 0) 5860 break; 5861 PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d", pmc_syscall_num, 5862 pmc_cpu_max()); 5863 break; 5864 case MOD_UNLOAD: 5865 case MOD_SHUTDOWN: 5866 pmc_cleanup(); 5867 PMCDBG0(MOD,INI,1, "unloaded"); 5868 break; 5869 default: 5870 error = EINVAL; 5871 break; 5872 } 5873 5874 return (error); 5875 } 5876