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 | 3353 PMC_F_EV_PMU)) != 0) 3354 return (EINVAL); 3355 3356 /* PMC_F_USERCALLCHAIN is only valid with PMC_F_CALLCHAIN. */ 3357 if ((flags & (PMC_F_CALLCHAIN | PMC_F_USERCALLCHAIN)) == 3358 PMC_F_USERCALLCHAIN) 3359 return (EINVAL); 3360 3361 /* PMC_F_USERCALLCHAIN is only valid for sampling mode. */ 3362 if ((flags & PMC_F_USERCALLCHAIN) != 0 && mode != PMC_MODE_TS && 3363 mode != PMC_MODE_SS) 3364 return (EINVAL); 3365 3366 /* Process logging options are not allowed for system PMCs. */ 3367 if (PMC_IS_SYSTEM_MODE(mode) && 3368 (flags & (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT)) != 0) 3369 return (EINVAL); 3370 3371 /* 3372 * All sampling mode PMCs need to be able to interrupt the CPU. 3373 */ 3374 if (PMC_IS_SAMPLING_MODE(mode)) 3375 caps |= PMC_CAP_INTERRUPT; 3376 3377 /* A valid class specifier should have been passed in. */ 3378 pcd = pmc_class_to_classdep(class); 3379 if (pcd == NULL) 3380 return (EINVAL); 3381 3382 /* The requested PMC capabilities should be feasible. */ 3383 if ((pcd->pcd_caps & caps) != caps) 3384 return (EOPNOTSUPP); 3385 3386 PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d", pa->pm_ev, 3387 caps, mode, cpu); 3388 3389 pmc = pmc_allocate_pmc_descriptor(); 3390 pmc->pm_id = PMC_ID_MAKE_ID(cpu, pa->pm_mode, class, PMC_ID_INVALID); 3391 pmc->pm_event = pa->pm_ev; 3392 pmc->pm_state = PMC_STATE_FREE; 3393 pmc->pm_caps = caps; 3394 pmc->pm_flags = flags; 3395 3396 /* XXX set lower bound on sampling for process counters */ 3397 if (PMC_IS_SAMPLING_MODE(mode)) { 3398 /* 3399 * Don't permit requested sample rate to be less than 3400 * pmc_mincount. 3401 */ 3402 if (pa->pm_count < MAX(1, pmc_mincount)) 3403 log(LOG_WARNING, "pmcallocate: passed sample " 3404 "rate %ju - setting to %u\n", 3405 (uintmax_t)pa->pm_count, 3406 MAX(1, pmc_mincount)); 3407 pmc->pm_sc.pm_reloadcount = MAX(MAX(1, pmc_mincount), 3408 pa->pm_count); 3409 } else 3410 pmc->pm_sc.pm_initial = pa->pm_count; 3411 3412 /* switch thread to CPU 'cpu' */ 3413 pmc_save_cpu_binding(&pb); 3414 3415 #define PMC_IS_SHAREABLE_PMC(cpu, n) \ 3416 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state & \ 3417 PMC_PHW_FLAG_IS_SHAREABLE) 3418 #define PMC_IS_UNALLOCATED(cpu, n) \ 3419 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL) 3420 3421 if (PMC_IS_SYSTEM_MODE(mode)) { 3422 pmc_select_cpu(cpu); 3423 for (n = pcd->pcd_ri; n < md->pmd_npmc; n++) { 3424 pcd = pmc_ri_to_classdep(md, n, &adjri); 3425 3426 if (!pmc_can_allocate_row(n, mode) || 3427 !pmc_can_allocate_rowindex(p, n, cpu)) 3428 continue; 3429 if (!PMC_IS_UNALLOCATED(cpu, n) && 3430 !PMC_IS_SHAREABLE_PMC(cpu, n)) 3431 continue; 3432 3433 if (pcd->pcd_allocate_pmc(cpu, adjri, pmc, pa) == 0) { 3434 /* Success. */ 3435 break; 3436 } 3437 } 3438 } else { 3439 /* Process virtual mode */ 3440 for (n = pcd->pcd_ri; n < md->pmd_npmc; n++) { 3441 pcd = pmc_ri_to_classdep(md, n, &adjri); 3442 3443 if (!pmc_can_allocate_row(n, mode) || 3444 !pmc_can_allocate_rowindex(p, n, PMC_CPU_ANY)) 3445 continue; 3446 3447 if (pcd->pcd_allocate_pmc(td->td_oncpu, adjri, pmc, 3448 pa) == 0) { 3449 /* Success. */ 3450 break; 3451 } 3452 } 3453 } 3454 3455 #undef PMC_IS_UNALLOCATED 3456 #undef PMC_IS_SHAREABLE_PMC 3457 3458 pmc_restore_cpu_binding(&pb); 3459 3460 if (n == md->pmd_npmc) { 3461 pmc_destroy_pmc_descriptor(pmc); 3462 return (EINVAL); 3463 } 3464 3465 /* Fill in the correct value in the ID field. */ 3466 pmc->pm_id = PMC_ID_MAKE_ID(cpu, mode, class, n); 3467 3468 PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x", 3469 pmc->pm_event, class, mode, n, pmc->pm_id); 3470 3471 /* Process mode PMCs with logging enabled need log files. */ 3472 if ((pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW)) != 0) 3473 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE; 3474 3475 /* All system mode sampling PMCs require a log file. */ 3476 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode)) 3477 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE; 3478 3479 /* 3480 * Configure global pmc's immediately. 3481 */ 3482 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) { 3483 pmc_save_cpu_binding(&pb); 3484 pmc_select_cpu(cpu); 3485 3486 phw = pmc_pcpu[cpu]->pc_hwpmcs[n]; 3487 pcd = pmc_ri_to_classdep(md, n, &adjri); 3488 3489 if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 || 3490 (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) { 3491 (void)pcd->pcd_release_pmc(cpu, adjri, pmc); 3492 pmc_destroy_pmc_descriptor(pmc); 3493 pmc_restore_cpu_binding(&pb); 3494 return (EPERM); 3495 } 3496 3497 pmc_restore_cpu_binding(&pb); 3498 } 3499 3500 pmc->pm_state = PMC_STATE_ALLOCATED; 3501 pmc->pm_class = class; 3502 3503 /* 3504 * Mark row disposition. 3505 */ 3506 if (PMC_IS_SYSTEM_MODE(mode)) 3507 PMC_MARK_ROW_STANDALONE(n); 3508 else 3509 PMC_MARK_ROW_THREAD(n); 3510 3511 /* 3512 * Register this PMC with the current thread as its owner. 3513 */ 3514 error = pmc_register_owner(p, pmc); 3515 if (error != 0) { 3516 pmc_release_pmc_descriptor(pmc); 3517 pmc_destroy_pmc_descriptor(pmc); 3518 return (error); 3519 } 3520 3521 /* 3522 * Return the allocated index. 3523 */ 3524 pa->pm_pmcid = pmc->pm_id; 3525 return (0); 3526 } 3527 3528 /* 3529 * Main body of PMC_OP_PMCATTACH. 3530 */ 3531 static int 3532 pmc_do_op_pmcattach(struct thread *td, struct pmc_op_pmcattach a) 3533 { 3534 struct pmc *pm; 3535 struct proc *p; 3536 int error; 3537 3538 sx_assert(&pmc_sx, SX_XLOCKED); 3539 3540 if (a.pm_pid < 0) { 3541 return (EINVAL); 3542 } else if (a.pm_pid == 0) { 3543 a.pm_pid = td->td_proc->p_pid; 3544 } 3545 3546 error = pmc_find_pmc(a.pm_pmc, &pm); 3547 if (error != 0) 3548 return (error); 3549 3550 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) 3551 return (EINVAL); 3552 3553 /* PMCs may be (re)attached only when allocated or stopped */ 3554 if (pm->pm_state == PMC_STATE_RUNNING) { 3555 return (EBUSY); 3556 } else if (pm->pm_state != PMC_STATE_ALLOCATED && 3557 pm->pm_state != PMC_STATE_STOPPED) { 3558 return (EINVAL); 3559 } 3560 3561 /* lookup pid */ 3562 if ((p = pfind(a.pm_pid)) == NULL) 3563 return (ESRCH); 3564 3565 /* 3566 * Ignore processes that are working on exiting. 3567 */ 3568 if ((p->p_flag & P_WEXIT) != 0) { 3569 PROC_UNLOCK(p); /* pfind() returns a locked process */ 3570 return (ESRCH); 3571 } 3572 3573 /* 3574 * We are allowed to attach a PMC to a process if we can debug it. 3575 */ 3576 error = p_candebug(curthread, p); 3577 3578 PROC_UNLOCK(p); 3579 3580 if (error == 0) 3581 error = pmc_attach_process(p, pm); 3582 3583 return (error); 3584 } 3585 3586 /* 3587 * Main body of PMC_OP_PMCDETACH. 3588 */ 3589 static int 3590 pmc_do_op_pmcdetach(struct thread *td, struct pmc_op_pmcattach a) 3591 { 3592 struct pmc *pm; 3593 struct proc *p; 3594 int error; 3595 3596 if (a.pm_pid < 0) { 3597 return (EINVAL); 3598 } else if (a.pm_pid == 0) 3599 a.pm_pid = td->td_proc->p_pid; 3600 3601 error = pmc_find_pmc(a.pm_pmc, &pm); 3602 if (error != 0) 3603 return (error); 3604 3605 if ((p = pfind(a.pm_pid)) == NULL) 3606 return (ESRCH); 3607 3608 /* 3609 * Treat processes that are in the process of exiting as if they were 3610 * not present. 3611 */ 3612 if ((p->p_flag & P_WEXIT) != 0) { 3613 PROC_UNLOCK(p); 3614 return (ESRCH); 3615 } 3616 3617 PROC_UNLOCK(p); /* pfind() returns a locked process */ 3618 3619 if (error == 0) 3620 error = pmc_detach_process(p, pm); 3621 3622 return (error); 3623 } 3624 3625 /* 3626 * Main body of PMC_OP_PMCRELEASE. 3627 */ 3628 static int 3629 pmc_do_op_pmcrelease(pmc_id_t pmcid) 3630 { 3631 struct pmc_owner *po; 3632 struct pmc *pm; 3633 int error; 3634 3635 /* 3636 * Find PMC pointer for the named PMC. 3637 * 3638 * Use pmc_release_pmc_descriptor() to switch off the 3639 * PMC, remove all its target threads, and remove the 3640 * PMC from its owner's list. 3641 * 3642 * Remove the owner record if this is the last PMC 3643 * owned. 3644 * 3645 * Free up space. 3646 */ 3647 error = pmc_find_pmc(pmcid, &pm); 3648 if (error != 0) 3649 return (error); 3650 3651 po = pm->pm_owner; 3652 pmc_release_pmc_descriptor(pm); 3653 pmc_maybe_remove_owner(po); 3654 pmc_destroy_pmc_descriptor(pm); 3655 3656 return (error); 3657 } 3658 3659 /* 3660 * Main body of PMC_OP_PMCRW. 3661 */ 3662 static int 3663 pmc_do_op_pmcrw(const struct pmc_op_pmcrw *prw, pmc_value_t *valp) 3664 { 3665 struct pmc_binding pb; 3666 struct pmc_classdep *pcd; 3667 struct pmc *pm; 3668 u_int cpu, ri, adjri; 3669 int error; 3670 3671 PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw->pm_pmcid, prw->pm_flags); 3672 3673 /* Must have at least one flag set. */ 3674 if ((prw->pm_flags & (PMC_F_OLDVALUE | PMC_F_NEWVALUE)) == 0) 3675 return (EINVAL); 3676 3677 /* Locate PMC descriptor. */ 3678 error = pmc_find_pmc(prw->pm_pmcid, &pm); 3679 if (error != 0) 3680 return (error); 3681 3682 /* Can't read a PMC that hasn't been started. */ 3683 if (pm->pm_state != PMC_STATE_ALLOCATED && 3684 pm->pm_state != PMC_STATE_STOPPED && 3685 pm->pm_state != PMC_STATE_RUNNING) 3686 return (EINVAL); 3687 3688 /* Writing a new value is allowed only for 'STOPPED' PMCs. */ 3689 if (pm->pm_state == PMC_STATE_RUNNING && 3690 (prw->pm_flags & PMC_F_NEWVALUE) != 0) 3691 return (EBUSY); 3692 3693 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) { 3694 /* 3695 * If this PMC is attached to its owner (i.e., the process 3696 * requesting this operation) and is running, then attempt to 3697 * get an upto-date reading from hardware for a READ. Writes 3698 * are only allowed when the PMC is stopped, so only update the 3699 * saved value field. 3700 * 3701 * If the PMC is not running, or is not attached to its owner, 3702 * read/write to the savedvalue field. 3703 */ 3704 3705 ri = PMC_TO_ROWINDEX(pm); 3706 pcd = pmc_ri_to_classdep(md, ri, &adjri); 3707 3708 mtx_pool_lock_spin(pmc_mtxpool, pm); 3709 cpu = curthread->td_oncpu; 3710 3711 if ((prw->pm_flags & PMC_F_OLDVALUE) != 0) { 3712 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) && 3713 (pm->pm_state == PMC_STATE_RUNNING)) { 3714 error = (*pcd->pcd_read_pmc)(cpu, adjri, pm, 3715 valp); 3716 } else { 3717 *valp = pm->pm_gv.pm_savedvalue; 3718 } 3719 } 3720 3721 if ((prw->pm_flags & PMC_F_NEWVALUE) != 0) 3722 pm->pm_gv.pm_savedvalue = prw->pm_value; 3723 3724 mtx_pool_unlock_spin(pmc_mtxpool, pm); 3725 } else { /* System mode PMCs */ 3726 cpu = PMC_TO_CPU(pm); 3727 ri = PMC_TO_ROWINDEX(pm); 3728 pcd = pmc_ri_to_classdep(md, ri, &adjri); 3729 3730 if (!pmc_cpu_is_active(cpu)) 3731 return (ENXIO); 3732 3733 /* Move this thread to CPU 'cpu'. */ 3734 pmc_save_cpu_binding(&pb); 3735 pmc_select_cpu(cpu); 3736 critical_enter(); 3737 3738 /* Save old value. */ 3739 if ((prw->pm_flags & PMC_F_OLDVALUE) != 0) 3740 error = (*pcd->pcd_read_pmc)(cpu, adjri, pm, valp); 3741 3742 /* Write out new value. */ 3743 if (error == 0 && (prw->pm_flags & PMC_F_NEWVALUE) != 0) 3744 error = (*pcd->pcd_write_pmc)(cpu, adjri, pm, 3745 prw->pm_value); 3746 3747 critical_exit(); 3748 pmc_restore_cpu_binding(&pb); 3749 if (error != 0) 3750 return (error); 3751 } 3752 3753 #ifdef HWPMC_DEBUG 3754 if ((prw->pm_flags & PMC_F_NEWVALUE) != 0) 3755 PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx", 3756 ri, prw->pm_value, *valp); 3757 else 3758 PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, *valp); 3759 #endif 3760 return (error); 3761 } 3762 3763 static int 3764 pmc_syscall_handler(struct thread *td, void *syscall_args) 3765 { 3766 struct pmc_syscall_args *c; 3767 void *pmclog_proc_handle; 3768 void *arg; 3769 int error, op; 3770 bool is_sx_downgraded; 3771 3772 c = (struct pmc_syscall_args *)syscall_args; 3773 op = c->pmop_code; 3774 arg = c->pmop_data; 3775 3776 /* PMC isn't set up yet */ 3777 if (pmc_hook == NULL) 3778 return (EINVAL); 3779 3780 if (op == PMC_OP_CONFIGURELOG) { 3781 /* 3782 * We cannot create the logging process inside 3783 * pmclog_configure_log() because there is a LOR 3784 * between pmc_sx and process structure locks. 3785 * Instead, pre-create the process and ignite the loop 3786 * if everything is fine, otherwise direct the process 3787 * to exit. 3788 */ 3789 error = pmclog_proc_create(td, &pmclog_proc_handle); 3790 if (error != 0) 3791 goto done_syscall; 3792 } 3793 3794 PMC_GET_SX_XLOCK(ENOSYS); 3795 is_sx_downgraded = false; 3796 PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op, 3797 pmc_op_to_name[op], arg); 3798 3799 error = 0; 3800 counter_u64_add(pmc_stats.pm_syscalls, 1); 3801 3802 switch (op) { 3803 3804 3805 /* 3806 * Configure a log file. 3807 * 3808 * XXX This OP will be reworked. 3809 */ 3810 3811 case PMC_OP_CONFIGURELOG: 3812 { 3813 struct proc *p; 3814 struct pmc *pm; 3815 struct pmc_owner *po; 3816 struct pmc_op_configurelog cl; 3817 3818 if ((error = copyin(arg, &cl, sizeof(cl))) != 0) { 3819 pmclog_proc_ignite(pmclog_proc_handle, NULL); 3820 break; 3821 } 3822 3823 /* No flags currently implemented */ 3824 if (cl.pm_flags != 0) { 3825 pmclog_proc_ignite(pmclog_proc_handle, NULL); 3826 error = EINVAL; 3827 break; 3828 } 3829 3830 /* mark this process as owning a log file */ 3831 p = td->td_proc; 3832 if ((po = pmc_find_owner_descriptor(p)) == NULL) 3833 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) { 3834 pmclog_proc_ignite(pmclog_proc_handle, NULL); 3835 error = ENOMEM; 3836 break; 3837 } 3838 3839 /* 3840 * If a valid fd was passed in, try to configure that, 3841 * otherwise if 'fd' was less than zero and there was 3842 * a log file configured, flush its buffers and 3843 * de-configure it. 3844 */ 3845 if (cl.pm_logfd >= 0) { 3846 error = pmclog_configure_log(md, po, cl.pm_logfd); 3847 pmclog_proc_ignite(pmclog_proc_handle, error == 0 ? 3848 po : NULL); 3849 } else if (po->po_flags & PMC_PO_OWNS_LOGFILE) { 3850 pmclog_proc_ignite(pmclog_proc_handle, NULL); 3851 error = pmclog_close(po); 3852 if (error == 0) { 3853 LIST_FOREACH(pm, &po->po_pmcs, pm_next) 3854 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE && 3855 pm->pm_state == PMC_STATE_RUNNING) 3856 pmc_stop(pm); 3857 error = pmclog_deconfigure_log(po); 3858 } 3859 } else { 3860 pmclog_proc_ignite(pmclog_proc_handle, NULL); 3861 error = EINVAL; 3862 } 3863 } 3864 break; 3865 3866 /* 3867 * Flush a log file. 3868 */ 3869 3870 case PMC_OP_FLUSHLOG: 3871 { 3872 struct pmc_owner *po; 3873 3874 sx_assert(&pmc_sx, SX_XLOCKED); 3875 3876 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) { 3877 error = EINVAL; 3878 break; 3879 } 3880 3881 error = pmclog_flush(po, 0); 3882 } 3883 break; 3884 3885 /* 3886 * Close a log file. 3887 */ 3888 3889 case PMC_OP_CLOSELOG: 3890 { 3891 struct pmc_owner *po; 3892 3893 sx_assert(&pmc_sx, SX_XLOCKED); 3894 3895 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) { 3896 error = EINVAL; 3897 break; 3898 } 3899 3900 error = pmclog_close(po); 3901 } 3902 break; 3903 3904 /* 3905 * Retrieve hardware configuration. 3906 */ 3907 3908 case PMC_OP_GETCPUINFO: /* CPU information */ 3909 { 3910 struct pmc_op_getcpuinfo gci; 3911 struct pmc_classinfo *pci; 3912 struct pmc_classdep *pcd; 3913 int cl; 3914 3915 memset(&gci, 0, sizeof(gci)); 3916 gci.pm_cputype = md->pmd_cputype; 3917 gci.pm_ncpu = pmc_cpu_max(); 3918 gci.pm_npmc = md->pmd_npmc; 3919 gci.pm_nclass = md->pmd_nclass; 3920 pci = gci.pm_classes; 3921 pcd = md->pmd_classdep; 3922 for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) { 3923 pci->pm_caps = pcd->pcd_caps; 3924 pci->pm_class = pcd->pcd_class; 3925 pci->pm_width = pcd->pcd_width; 3926 pci->pm_num = pcd->pcd_num; 3927 } 3928 error = copyout(&gci, arg, sizeof(gci)); 3929 } 3930 break; 3931 3932 /* 3933 * Retrieve soft events list. 3934 */ 3935 case PMC_OP_GETDYNEVENTINFO: 3936 { 3937 enum pmc_class cl; 3938 enum pmc_event ev; 3939 struct pmc_op_getdyneventinfo *gei; 3940 struct pmc_dyn_event_descr dev; 3941 struct pmc_soft *ps; 3942 uint32_t nevent; 3943 3944 sx_assert(&pmc_sx, SX_LOCKED); 3945 3946 gei = (struct pmc_op_getdyneventinfo *) arg; 3947 3948 if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0) 3949 break; 3950 3951 /* Only SOFT class is dynamic. */ 3952 if (cl != PMC_CLASS_SOFT) { 3953 error = EINVAL; 3954 break; 3955 } 3956 3957 nevent = 0; 3958 for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) { 3959 ps = pmc_soft_ev_acquire(ev); 3960 if (ps == NULL) 3961 continue; 3962 bcopy(&ps->ps_ev, &dev, sizeof(dev)); 3963 pmc_soft_ev_release(ps); 3964 3965 error = copyout(&dev, 3966 &gei->pm_events[nevent], 3967 sizeof(struct pmc_dyn_event_descr)); 3968 if (error != 0) 3969 break; 3970 nevent++; 3971 } 3972 if (error != 0) 3973 break; 3974 3975 error = copyout(&nevent, &gei->pm_nevent, 3976 sizeof(nevent)); 3977 } 3978 break; 3979 3980 /* 3981 * Get module statistics 3982 */ 3983 3984 case PMC_OP_GETDRIVERSTATS: 3985 { 3986 struct pmc_op_getdriverstats gms; 3987 #define CFETCH(a, b, field) a.field = counter_u64_fetch(b.field) 3988 CFETCH(gms, pmc_stats, pm_intr_ignored); 3989 CFETCH(gms, pmc_stats, pm_intr_processed); 3990 CFETCH(gms, pmc_stats, pm_intr_bufferfull); 3991 CFETCH(gms, pmc_stats, pm_syscalls); 3992 CFETCH(gms, pmc_stats, pm_syscall_errors); 3993 CFETCH(gms, pmc_stats, pm_buffer_requests); 3994 CFETCH(gms, pmc_stats, pm_buffer_requests_failed); 3995 CFETCH(gms, pmc_stats, pm_log_sweeps); 3996 #undef CFETCH 3997 error = copyout(&gms, arg, sizeof(gms)); 3998 } 3999 break; 4000 4001 4002 /* 4003 * Retrieve module version number 4004 */ 4005 4006 case PMC_OP_GETMODULEVERSION: 4007 { 4008 uint32_t cv, modv; 4009 4010 /* retrieve the client's idea of the ABI version */ 4011 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0) 4012 break; 4013 /* don't service clients newer than our driver */ 4014 modv = PMC_VERSION; 4015 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) { 4016 error = EPROGMISMATCH; 4017 break; 4018 } 4019 error = copyout(&modv, arg, sizeof(int)); 4020 } 4021 break; 4022 4023 4024 /* 4025 * Retrieve the state of all the PMCs on a given 4026 * CPU. 4027 */ 4028 4029 case PMC_OP_GETPMCINFO: 4030 { 4031 int ari; 4032 struct pmc *pm; 4033 size_t pmcinfo_size; 4034 uint32_t cpu, n, npmc; 4035 struct pmc_owner *po; 4036 struct pmc_binding pb; 4037 struct pmc_classdep *pcd; 4038 struct pmc_info *p, *pmcinfo; 4039 struct pmc_op_getpmcinfo *gpi; 4040 4041 PMC_DOWNGRADE_SX(); 4042 4043 gpi = (struct pmc_op_getpmcinfo *) arg; 4044 4045 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0) 4046 break; 4047 4048 if (cpu >= pmc_cpu_max()) { 4049 error = EINVAL; 4050 break; 4051 } 4052 4053 if (!pmc_cpu_is_active(cpu)) { 4054 error = ENXIO; 4055 break; 4056 } 4057 4058 /* switch to CPU 'cpu' */ 4059 pmc_save_cpu_binding(&pb); 4060 pmc_select_cpu(cpu); 4061 4062 npmc = md->pmd_npmc; 4063 4064 pmcinfo_size = npmc * sizeof(struct pmc_info); 4065 pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK | M_ZERO); 4066 4067 p = pmcinfo; 4068 4069 for (n = 0; n < md->pmd_npmc; n++, p++) { 4070 4071 pcd = pmc_ri_to_classdep(md, n, &ari); 4072 4073 KASSERT(pcd != NULL, 4074 ("[pmc,%d] null pcd ri=%d", __LINE__, n)); 4075 4076 if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0) 4077 break; 4078 4079 if (PMC_ROW_DISP_IS_STANDALONE(n)) 4080 p->pm_rowdisp = PMC_DISP_STANDALONE; 4081 else if (PMC_ROW_DISP_IS_THREAD(n)) 4082 p->pm_rowdisp = PMC_DISP_THREAD; 4083 else 4084 p->pm_rowdisp = PMC_DISP_FREE; 4085 4086 p->pm_ownerpid = -1; 4087 4088 if (pm == NULL) /* no PMC associated */ 4089 continue; 4090 4091 po = pm->pm_owner; 4092 4093 KASSERT(po->po_owner != NULL, 4094 ("[pmc,%d] pmc_owner had a null proc pointer", 4095 __LINE__)); 4096 4097 p->pm_ownerpid = po->po_owner->p_pid; 4098 p->pm_mode = PMC_TO_MODE(pm); 4099 p->pm_event = pm->pm_event; 4100 p->pm_flags = pm->pm_flags; 4101 4102 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) 4103 p->pm_reloadcount = 4104 pm->pm_sc.pm_reloadcount; 4105 } 4106 4107 pmc_restore_cpu_binding(&pb); 4108 4109 /* now copy out the PMC info collected */ 4110 if (error == 0) 4111 error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size); 4112 4113 free(pmcinfo, M_PMC); 4114 } 4115 break; 4116 4117 4118 /* 4119 * Set the administrative state of a PMC. I.e. whether 4120 * the PMC is to be used or not. 4121 */ 4122 4123 case PMC_OP_PMCADMIN: 4124 { 4125 int cpu, ri; 4126 enum pmc_state request; 4127 struct pmc_cpu *pc; 4128 struct pmc_hw *phw; 4129 struct pmc_op_pmcadmin pma; 4130 struct pmc_binding pb; 4131 4132 sx_assert(&pmc_sx, SX_XLOCKED); 4133 4134 KASSERT(td == curthread, 4135 ("[pmc,%d] td != curthread", __LINE__)); 4136 4137 error = priv_check(td, PRIV_PMC_MANAGE); 4138 if (error) 4139 break; 4140 4141 if ((error = copyin(arg, &pma, sizeof(pma))) != 0) 4142 break; 4143 4144 cpu = pma.pm_cpu; 4145 4146 if (cpu < 0 || cpu >= (int) pmc_cpu_max()) { 4147 error = EINVAL; 4148 break; 4149 } 4150 4151 if (!pmc_cpu_is_active(cpu)) { 4152 error = ENXIO; 4153 break; 4154 } 4155 4156 request = pma.pm_state; 4157 4158 if (request != PMC_STATE_DISABLED && 4159 request != PMC_STATE_FREE) { 4160 error = EINVAL; 4161 break; 4162 } 4163 4164 ri = pma.pm_pmc; /* pmc id == row index */ 4165 if (ri < 0 || ri >= (int) md->pmd_npmc) { 4166 error = EINVAL; 4167 break; 4168 } 4169 4170 /* 4171 * We can't disable a PMC with a row-index allocated 4172 * for process virtual PMCs. 4173 */ 4174 4175 if (PMC_ROW_DISP_IS_THREAD(ri) && 4176 request == PMC_STATE_DISABLED) { 4177 error = EBUSY; 4178 break; 4179 } 4180 4181 /* 4182 * otherwise, this PMC on this CPU is either free or 4183 * in system-wide mode. 4184 */ 4185 4186 pmc_save_cpu_binding(&pb); 4187 pmc_select_cpu(cpu); 4188 4189 pc = pmc_pcpu[cpu]; 4190 phw = pc->pc_hwpmcs[ri]; 4191 4192 /* 4193 * XXX do we need some kind of 'forced' disable? 4194 */ 4195 4196 if (phw->phw_pmc == NULL) { 4197 if (request == PMC_STATE_DISABLED && 4198 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) { 4199 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED; 4200 PMC_MARK_ROW_STANDALONE(ri); 4201 } else if (request == PMC_STATE_FREE && 4202 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) { 4203 phw->phw_state |= PMC_PHW_FLAG_IS_ENABLED; 4204 PMC_UNMARK_ROW_STANDALONE(ri); 4205 } 4206 /* other cases are a no-op */ 4207 } else 4208 error = EBUSY; 4209 4210 pmc_restore_cpu_binding(&pb); 4211 } 4212 break; 4213 4214 4215 /* 4216 * Allocate a PMC. 4217 */ 4218 case PMC_OP_PMCALLOCATE: 4219 { 4220 struct pmc_op_pmcallocate pa; 4221 4222 error = copyin(arg, &pa, sizeof(pa)); 4223 if (error != 0) 4224 break; 4225 4226 error = pmc_do_op_pmcallocate(td, &pa); 4227 if (error != 0) 4228 break; 4229 4230 error = copyout(&pa, arg, sizeof(pa)); 4231 } 4232 break; 4233 4234 /* 4235 * Attach a PMC to a process. 4236 */ 4237 case PMC_OP_PMCATTACH: 4238 { 4239 struct pmc_op_pmcattach a; 4240 4241 error = copyin(arg, &a, sizeof(a)); 4242 if (error != 0) 4243 break; 4244 4245 error = pmc_do_op_pmcattach(td, a); 4246 } 4247 break; 4248 4249 /* 4250 * Detach an attached PMC from a process. 4251 */ 4252 case PMC_OP_PMCDETACH: 4253 { 4254 struct pmc_op_pmcattach a; 4255 4256 error = copyin(arg, &a, sizeof(a)); 4257 if (error != 0) 4258 break; 4259 4260 error = pmc_do_op_pmcdetach(td, a); 4261 } 4262 break; 4263 4264 4265 /* 4266 * Retrieve the MSR number associated with the counter 4267 * 'pmc_id'. This allows processes to directly use RDPMC 4268 * instructions to read their PMCs, without the overhead of a 4269 * system call. 4270 */ 4271 4272 case PMC_OP_PMCGETMSR: 4273 { 4274 int adjri, ri; 4275 struct pmc *pm; 4276 struct pmc_target *pt; 4277 struct pmc_op_getmsr gm; 4278 struct pmc_classdep *pcd; 4279 4280 PMC_DOWNGRADE_SX(); 4281 4282 if ((error = copyin(arg, &gm, sizeof(gm))) != 0) 4283 break; 4284 4285 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0) 4286 break; 4287 4288 /* 4289 * The allocated PMC has to be a process virtual PMC, 4290 * i.e., of type MODE_T[CS]. Global PMCs can only be 4291 * read using the PMCREAD operation since they may be 4292 * allocated on a different CPU than the one we could 4293 * be running on at the time of the RDPMC instruction. 4294 * 4295 * The GETMSR operation is not allowed for PMCs that 4296 * are inherited across processes. 4297 */ 4298 4299 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) || 4300 (pm->pm_flags & PMC_F_DESCENDANTS)) { 4301 error = EINVAL; 4302 break; 4303 } 4304 4305 /* 4306 * It only makes sense to use a RDPMC (or its 4307 * equivalent instruction on non-x86 architectures) on 4308 * a process that has allocated and attached a PMC to 4309 * itself. Conversely the PMC is only allowed to have 4310 * one process attached to it -- its owner. 4311 */ 4312 4313 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL || 4314 LIST_NEXT(pt, pt_next) != NULL || 4315 pt->pt_process->pp_proc != pm->pm_owner->po_owner) { 4316 error = EINVAL; 4317 break; 4318 } 4319 4320 ri = PMC_TO_ROWINDEX(pm); 4321 pcd = pmc_ri_to_classdep(md, ri, &adjri); 4322 4323 /* PMC class has no 'GETMSR' support */ 4324 if (pcd->pcd_get_msr == NULL) { 4325 error = ENOSYS; 4326 break; 4327 } 4328 4329 if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0) 4330 break; 4331 4332 if ((error = copyout(&gm, arg, sizeof(gm))) < 0) 4333 break; 4334 4335 /* 4336 * Mark our process as using MSRs. Update machine 4337 * state using a forced context switch. 4338 */ 4339 4340 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS; 4341 pmc_force_context_switch(); 4342 4343 } 4344 break; 4345 4346 /* 4347 * Release an allocated PMC. 4348 */ 4349 case PMC_OP_PMCRELEASE: 4350 { 4351 struct pmc_op_simple sp; 4352 4353 error = copyin(arg, &sp, sizeof(sp)); 4354 if (error != 0) 4355 break; 4356 4357 error = pmc_do_op_pmcrelease(sp.pm_pmcid); 4358 } 4359 break; 4360 4361 /* 4362 * Read and/or write a PMC. 4363 */ 4364 case PMC_OP_PMCRW: 4365 { 4366 struct pmc_op_pmcrw prw; 4367 struct pmc_op_pmcrw *pprw; 4368 pmc_value_t oldvalue; 4369 4370 PMC_DOWNGRADE_SX(); 4371 4372 error = copyin(arg, &prw, sizeof(prw)); 4373 if (error != 0) 4374 break; 4375 4376 error = pmc_do_op_pmcrw(&prw, &oldvalue); 4377 if (error != 0) 4378 break; 4379 4380 /* Return old value if requested. */ 4381 if ((prw.pm_flags & PMC_F_OLDVALUE) != 0) { 4382 pprw = arg; 4383 error = copyout(&oldvalue, &pprw->pm_value, 4384 sizeof(prw.pm_value)); 4385 } 4386 } 4387 break; 4388 4389 4390 /* 4391 * Set the sampling rate for a sampling mode PMC and the 4392 * initial count for a counting mode PMC. 4393 */ 4394 4395 case PMC_OP_PMCSETCOUNT: 4396 { 4397 struct pmc *pm; 4398 struct pmc_op_pmcsetcount sc; 4399 4400 PMC_DOWNGRADE_SX(); 4401 4402 if ((error = copyin(arg, &sc, sizeof(sc))) != 0) 4403 break; 4404 4405 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0) 4406 break; 4407 4408 if (pm->pm_state == PMC_STATE_RUNNING) { 4409 error = EBUSY; 4410 break; 4411 } 4412 4413 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) { 4414 /* 4415 * Don't permit requested sample rate to be 4416 * less than pmc_mincount. 4417 */ 4418 if (sc.pm_count < MAX(1, pmc_mincount)) 4419 log(LOG_WARNING, "pmcsetcount: passed sample " 4420 "rate %ju - setting to %u\n", 4421 (uintmax_t)sc.pm_count, 4422 MAX(1, pmc_mincount)); 4423 pm->pm_sc.pm_reloadcount = MAX(MAX(1, pmc_mincount), 4424 sc.pm_count); 4425 } else 4426 pm->pm_sc.pm_initial = sc.pm_count; 4427 } 4428 break; 4429 4430 4431 /* 4432 * Start a PMC. 4433 */ 4434 4435 case PMC_OP_PMCSTART: 4436 { 4437 pmc_id_t pmcid; 4438 struct pmc *pm; 4439 struct pmc_op_simple sp; 4440 4441 sx_assert(&pmc_sx, SX_XLOCKED); 4442 4443 if ((error = copyin(arg, &sp, sizeof(sp))) != 0) 4444 break; 4445 4446 pmcid = sp.pm_pmcid; 4447 4448 if ((error = pmc_find_pmc(pmcid, &pm)) != 0) 4449 break; 4450 4451 KASSERT(pmcid == pm->pm_id, 4452 ("[pmc,%d] pmcid %x != id %x", __LINE__, 4453 pm->pm_id, pmcid)); 4454 4455 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */ 4456 break; 4457 else if (pm->pm_state != PMC_STATE_STOPPED && 4458 pm->pm_state != PMC_STATE_ALLOCATED) { 4459 error = EINVAL; 4460 break; 4461 } 4462 4463 error = pmc_start(pm); 4464 } 4465 break; 4466 4467 4468 /* 4469 * Stop a PMC. 4470 */ 4471 4472 case PMC_OP_PMCSTOP: 4473 { 4474 pmc_id_t pmcid; 4475 struct pmc *pm; 4476 struct pmc_op_simple sp; 4477 4478 PMC_DOWNGRADE_SX(); 4479 4480 if ((error = copyin(arg, &sp, sizeof(sp))) != 0) 4481 break; 4482 4483 pmcid = sp.pm_pmcid; 4484 4485 /* 4486 * Mark the PMC as inactive and invoke the MD stop 4487 * routines if needed. 4488 */ 4489 4490 if ((error = pmc_find_pmc(pmcid, &pm)) != 0) 4491 break; 4492 4493 KASSERT(pmcid == pm->pm_id, 4494 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__, 4495 pm->pm_id, pmcid)); 4496 4497 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */ 4498 break; 4499 else if (pm->pm_state != PMC_STATE_RUNNING) { 4500 error = EINVAL; 4501 break; 4502 } 4503 4504 error = pmc_stop(pm); 4505 } 4506 break; 4507 4508 4509 /* 4510 * Write a user supplied value to the log file. 4511 */ 4512 4513 case PMC_OP_WRITELOG: 4514 { 4515 struct pmc_op_writelog wl; 4516 struct pmc_owner *po; 4517 4518 PMC_DOWNGRADE_SX(); 4519 4520 if ((error = copyin(arg, &wl, sizeof(wl))) != 0) 4521 break; 4522 4523 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) { 4524 error = EINVAL; 4525 break; 4526 } 4527 4528 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) { 4529 error = EINVAL; 4530 break; 4531 } 4532 4533 error = pmclog_process_userlog(po, &wl); 4534 } 4535 break; 4536 4537 4538 default: 4539 error = EINVAL; 4540 break; 4541 } 4542 4543 if (is_sx_downgraded) 4544 sx_sunlock(&pmc_sx); 4545 else 4546 sx_xunlock(&pmc_sx); 4547 done_syscall: 4548 if (error) 4549 counter_u64_add(pmc_stats.pm_syscall_errors, 1); 4550 4551 return (error); 4552 } 4553 4554 /* 4555 * Helper functions 4556 */ 4557 4558 /* 4559 * Mark the thread as needing callchain capture and post an AST. The 4560 * actual callchain capture will be done in a context where it is safe 4561 * to take page faults. 4562 */ 4563 static void 4564 pmc_post_callchain_callback(void) 4565 { 4566 struct thread *td; 4567 4568 td = curthread; 4569 4570 /* 4571 * If there is multiple PMCs for the same interrupt ignore new post 4572 */ 4573 if ((td->td_pflags & TDP_CALLCHAIN) != 0) 4574 return; 4575 4576 /* 4577 * Mark this thread as needing callchain capture. 4578 * `td->td_pflags' will be safe to touch because this thread 4579 * was in user space when it was interrupted. 4580 */ 4581 td->td_pflags |= TDP_CALLCHAIN; 4582 4583 /* 4584 * Don't let this thread migrate between CPUs until callchain 4585 * capture completes. 4586 */ 4587 sched_pin(); 4588 4589 return; 4590 } 4591 4592 /* 4593 * Find a free slot in the per-cpu array of samples and capture the 4594 * current callchain there. If a sample was successfully added, a bit 4595 * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook 4596 * needs to be invoked from the clock handler. 4597 * 4598 * This function is meant to be called from an NMI handler. It cannot 4599 * use any of the locking primitives supplied by the OS. 4600 */ 4601 static int 4602 pmc_add_sample(ring_type_t ring, struct pmc *pm, struct trapframe *tf) 4603 { 4604 struct pmc_sample *ps; 4605 struct pmc_samplebuffer *psb; 4606 struct thread *td; 4607 int error, cpu, callchaindepth; 4608 bool inuserspace; 4609 4610 error = 0; 4611 4612 /* 4613 * Allocate space for a sample buffer. 4614 */ 4615 cpu = curcpu; 4616 psb = pmc_pcpu[cpu]->pc_sb[ring]; 4617 inuserspace = TRAPF_USERMODE(tf); 4618 ps = PMC_PROD_SAMPLE(psb); 4619 if (psb->ps_considx != psb->ps_prodidx && 4620 ps->ps_nsamples) { /* in use, reader hasn't caught up */ 4621 pm->pm_pcpu_state[cpu].pps_stalled = 1; 4622 counter_u64_add(pmc_stats.pm_intr_bufferfull, 1); 4623 PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", 4624 cpu, pm, tf, inuserspace, 4625 (int)(psb->ps_prodidx & pmc_sample_mask), 4626 (int)(psb->ps_considx & pmc_sample_mask)); 4627 callchaindepth = 1; 4628 error = ENOMEM; 4629 goto done; 4630 } 4631 4632 /* Fill in entry. */ 4633 PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm, tf, 4634 inuserspace, (int)(psb->ps_prodidx & pmc_sample_mask), 4635 (int)(psb->ps_considx & pmc_sample_mask)); 4636 4637 td = curthread; 4638 ps->ps_pmc = pm; 4639 ps->ps_td = td; 4640 ps->ps_pid = td->td_proc->p_pid; 4641 ps->ps_tid = td->td_tid; 4642 ps->ps_tsc = pmc_rdtsc(); 4643 ps->ps_ticks = ticks; 4644 ps->ps_cpu = cpu; 4645 ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0; 4646 4647 callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ? 4648 pmc_callchaindepth : 1; 4649 4650 MPASS(ps->ps_pc != NULL); 4651 if (callchaindepth == 1) { 4652 ps->ps_pc[0] = PMC_TRAPFRAME_TO_PC(tf); 4653 } else { 4654 /* 4655 * Kernel stack traversals can be done immediately, while we 4656 * defer to an AST for user space traversals. 4657 */ 4658 if (!inuserspace) { 4659 callchaindepth = pmc_save_kernel_callchain(ps->ps_pc, 4660 callchaindepth, tf); 4661 } else { 4662 pmc_post_callchain_callback(); 4663 callchaindepth = PMC_USER_CALLCHAIN_PENDING; 4664 } 4665 } 4666 4667 ps->ps_nsamples = callchaindepth; /* mark entry as in-use */ 4668 if (ring == PMC_UR) { 4669 ps->ps_nsamples_actual = callchaindepth; 4670 ps->ps_nsamples = PMC_USER_CALLCHAIN_PENDING; 4671 } 4672 4673 KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0, 4674 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm, 4675 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 4676 4677 counter_u64_add(pm->pm_runcount, 1); /* hold onto PMC */ 4678 /* increment write pointer */ 4679 psb->ps_prodidx++; 4680 done: 4681 /* mark CPU as needing processing */ 4682 if (callchaindepth != PMC_USER_CALLCHAIN_PENDING) 4683 DPCPU_SET(pmc_sampled, 1); 4684 4685 return (error); 4686 } 4687 4688 /* 4689 * Interrupt processing. 4690 * 4691 * This function may be called from an NMI handler. It cannot use any of the 4692 * locking primitives supplied by the OS. 4693 */ 4694 int 4695 pmc_process_interrupt(int ring, struct pmc *pm, struct trapframe *tf) 4696 { 4697 struct thread *td; 4698 4699 td = curthread; 4700 if ((pm->pm_flags & PMC_F_USERCALLCHAIN) && 4701 (td->td_proc->p_flag & P_KPROC) == 0 && !TRAPF_USERMODE(tf)) { 4702 atomic_add_int(&td->td_pmcpend, 1); 4703 return (pmc_add_sample(PMC_UR, pm, tf)); 4704 } 4705 return (pmc_add_sample(ring, pm, tf)); 4706 } 4707 4708 /* 4709 * Capture a user call chain. This function will be called from ast() 4710 * before control returns to userland and before the process gets 4711 * rescheduled. 4712 */ 4713 static void 4714 pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf) 4715 { 4716 struct pmc *pm; 4717 struct pmc_sample *ps; 4718 struct pmc_samplebuffer *psb; 4719 struct thread *td; 4720 uint64_t considx, prodidx; 4721 int nsamples, nrecords, pass, iter; 4722 int start_ticks __diagused; 4723 4724 psb = pmc_pcpu[cpu]->pc_sb[ring]; 4725 td = curthread; 4726 nrecords = INT_MAX; 4727 pass = 0; 4728 start_ticks = ticks; 4729 4730 KASSERT(td->td_pflags & TDP_CALLCHAIN, 4731 ("[pmc,%d] Retrieving callchain for thread that doesn't want it", 4732 __LINE__)); 4733 restart: 4734 if (ring == PMC_UR) 4735 nrecords = atomic_readandclear_32(&td->td_pmcpend); 4736 4737 for (iter = 0, considx = psb->ps_considx, prodidx = psb->ps_prodidx; 4738 considx < prodidx && iter < pmc_nsamples; considx++, iter++) { 4739 ps = PMC_CONS_SAMPLE_OFF(psb, considx); 4740 4741 /* 4742 * Iterate through all deferred callchain requests. Walk from 4743 * the current read pointer to the current write pointer. 4744 */ 4745 #ifdef INVARIANTS 4746 if (ps->ps_nsamples == PMC_SAMPLE_FREE) { 4747 continue; 4748 } 4749 #endif 4750 if (ps->ps_td != td || 4751 ps->ps_nsamples != PMC_USER_CALLCHAIN_PENDING || 4752 ps->ps_pmc->pm_state != PMC_STATE_RUNNING) 4753 continue; 4754 4755 KASSERT(ps->ps_cpu == cpu, 4756 ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__, 4757 ps->ps_cpu, PCPU_GET(cpuid))); 4758 4759 pm = ps->ps_pmc; 4760 KASSERT(pm->pm_flags & PMC_F_CALLCHAIN, 4761 ("[pmc,%d] Retrieving callchain for PMC that doesn't " 4762 "want it", __LINE__)); 4763 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 4764 ("[pmc,%d] runcount %ju", __LINE__, 4765 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 4766 4767 if (ring == PMC_UR) { 4768 nsamples = ps->ps_nsamples_actual; 4769 counter_u64_add(pmc_stats.pm_merges, 1); 4770 } else 4771 nsamples = 0; 4772 4773 /* 4774 * Retrieve the callchain and mark the sample buffer 4775 * as 'processable' by the timer tick sweep code. 4776 */ 4777 if (__predict_true(nsamples < pmc_callchaindepth - 1)) 4778 nsamples += pmc_save_user_callchain(ps->ps_pc + nsamples, 4779 pmc_callchaindepth - nsamples - 1, tf); 4780 4781 /* 4782 * We have to prevent hardclock from potentially overwriting 4783 * this sample between when we read the value and when we set 4784 * it. 4785 */ 4786 spinlock_enter(); 4787 4788 /* 4789 * Verify that the sample hasn't been dropped in the meantime. 4790 */ 4791 if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) { 4792 ps->ps_nsamples = nsamples; 4793 /* 4794 * If we couldn't get a sample, simply drop the 4795 * reference. 4796 */ 4797 if (nsamples == 0) 4798 counter_u64_add(pm->pm_runcount, -1); 4799 } 4800 spinlock_exit(); 4801 if (nrecords-- == 1) 4802 break; 4803 } 4804 if (__predict_false(ring == PMC_UR && td->td_pmcpend)) { 4805 if (pass == 0) { 4806 pass = 1; 4807 goto restart; 4808 } 4809 /* only collect samples for this part once */ 4810 td->td_pmcpend = 0; 4811 } 4812 4813 #ifdef INVARIANTS 4814 if ((ticks - start_ticks) > hz) 4815 log(LOG_ERR, "%s took %d ticks\n", __func__, (ticks - start_ticks)); 4816 #endif 4817 /* mark CPU as needing processing */ 4818 DPCPU_SET(pmc_sampled, 1); 4819 } 4820 4821 /* 4822 * Process saved PC samples. 4823 */ 4824 static void 4825 pmc_process_samples(int cpu, ring_type_t ring) 4826 { 4827 struct pmc *pm; 4828 struct thread *td; 4829 struct pmc_owner *po; 4830 struct pmc_sample *ps; 4831 struct pmc_classdep *pcd; 4832 struct pmc_samplebuffer *psb; 4833 uint64_t delta __diagused; 4834 int adjri, n; 4835 4836 KASSERT(PCPU_GET(cpuid) == cpu, 4837 ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__, 4838 PCPU_GET(cpuid), cpu)); 4839 4840 psb = pmc_pcpu[cpu]->pc_sb[ring]; 4841 delta = psb->ps_prodidx - psb->ps_considx; 4842 MPASS(delta <= pmc_nsamples); 4843 MPASS(psb->ps_considx <= psb->ps_prodidx); 4844 for (n = 0; psb->ps_considx < psb->ps_prodidx; psb->ps_considx++, n++) { 4845 ps = PMC_CONS_SAMPLE(psb); 4846 4847 if (__predict_false(ps->ps_nsamples == PMC_SAMPLE_FREE)) 4848 continue; 4849 4850 /* skip non-running samples */ 4851 pm = ps->ps_pmc; 4852 if (pm->pm_state != PMC_STATE_RUNNING) 4853 goto entrydone; 4854 4855 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 4856 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm, 4857 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 4858 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)), 4859 ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__, 4860 pm, PMC_TO_MODE(pm))); 4861 4862 po = pm->pm_owner; 4863 4864 /* If there is a pending AST wait for completion */ 4865 if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) { 4866 /* 4867 * If we've been waiting more than 1 tick to 4868 * collect a callchain for this record then 4869 * drop it and move on. 4870 */ 4871 if (ticks - ps->ps_ticks > 1) { 4872 /* 4873 * Track how often we hit this as it will 4874 * preferentially lose user samples 4875 * for long running system calls. 4876 */ 4877 counter_u64_add(pmc_stats.pm_overwrites, 1); 4878 goto entrydone; 4879 } 4880 /* Need a rescan at a later time. */ 4881 DPCPU_SET(pmc_sampled, 1); 4882 break; 4883 } 4884 4885 PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu, 4886 pm, ps->ps_nsamples, ps->ps_flags, 4887 (int)(psb->ps_prodidx & pmc_sample_mask), 4888 (int)(psb->ps_considx & pmc_sample_mask)); 4889 4890 /* 4891 * If this is a process-mode PMC that is attached to 4892 * its owner, and if the PC is in user mode, update 4893 * profiling statistics like timer-based profiling 4894 * would have done. 4895 * 4896 * Otherwise, this is either a sampling-mode PMC that 4897 * is attached to a different process than its owner, 4898 * or a system-wide sampling PMC. Dispatch a log 4899 * entry to the PMC's owner process. 4900 */ 4901 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) { 4902 if (ps->ps_flags & PMC_CC_F_USERSPACE) { 4903 td = FIRST_THREAD_IN_PROC(po->po_owner); 4904 addupc_intr(td, ps->ps_pc[0], 1); 4905 } 4906 } else 4907 pmclog_process_callchain(pm, ps); 4908 4909 entrydone: 4910 ps->ps_nsamples = 0; /* mark entry as free */ 4911 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 4912 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm, 4913 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 4914 4915 counter_u64_add(pm->pm_runcount, -1); 4916 } 4917 4918 counter_u64_add(pmc_stats.pm_log_sweeps, 1); 4919 4920 /* Do not re-enable stalled PMCs if we failed to process any samples */ 4921 if (n == 0) 4922 return; 4923 4924 /* 4925 * Restart any stalled sampling PMCs on this CPU. 4926 * 4927 * If the NMI handler sets the pm_stalled field of a PMC after 4928 * the check below, we'll end up processing the stalled PMC at 4929 * the next hardclock tick. 4930 */ 4931 for (n = 0; n < md->pmd_npmc; n++) { 4932 pcd = pmc_ri_to_classdep(md, n, &adjri); 4933 KASSERT(pcd != NULL, 4934 ("[pmc,%d] null pcd ri=%d", __LINE__, n)); 4935 (void)(*pcd->pcd_get_config)(cpu, adjri, &pm); 4936 4937 if (pm == NULL || /* !cfg'ed */ 4938 pm->pm_state != PMC_STATE_RUNNING || /* !active */ 4939 !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */ 4940 !pm->pm_pcpu_state[cpu].pps_cpustate || /* !desired */ 4941 !pm->pm_pcpu_state[cpu].pps_stalled) /* !stalled */ 4942 continue; 4943 4944 pm->pm_pcpu_state[cpu].pps_stalled = 0; 4945 (void)(*pcd->pcd_start_pmc)(cpu, adjri, pm); 4946 } 4947 } 4948 4949 /* 4950 * Event handlers. 4951 */ 4952 4953 /* 4954 * Handle a process exit. 4955 * 4956 * Remove this process from all hash tables. If this process 4957 * owned any PMCs, turn off those PMCs and deallocate them, 4958 * removing any associations with target processes. 4959 * 4960 * This function will be called by the last 'thread' of a 4961 * process. 4962 * 4963 * XXX This eventhandler gets called early in the exit process. 4964 * Consider using a 'hook' invocation from thread_exit() or equivalent 4965 * spot. Another negative is that kse_exit doesn't seem to call 4966 * exit1() [??]. 4967 */ 4968 static void 4969 pmc_process_exit(void *arg __unused, struct proc *p) 4970 { 4971 struct pmc *pm; 4972 struct pmc_owner *po; 4973 struct pmc_process *pp; 4974 struct pmc_classdep *pcd; 4975 pmc_value_t newvalue, tmp; 4976 int ri, adjri, cpu; 4977 bool is_using_hwpmcs; 4978 4979 PROC_LOCK(p); 4980 is_using_hwpmcs = (p->p_flag & P_HWPMC) != 0; 4981 PROC_UNLOCK(p); 4982 4983 /* 4984 * Log a sysexit event to all SS PMC owners. 4985 */ 4986 PMC_EPOCH_ENTER(); 4987 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 4988 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 4989 pmclog_process_sysexit(po, p->p_pid); 4990 } 4991 PMC_EPOCH_EXIT(); 4992 4993 PMC_GET_SX_XLOCK(); 4994 PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid, 4995 p->p_comm); 4996 4997 if (!is_using_hwpmcs) 4998 goto out; 4999 5000 /* 5001 * Since this code is invoked by the last thread in an exiting process, 5002 * we would have context switched IN at some prior point. However, with 5003 * PREEMPTION, kernel mode context switches may happen any time, so we 5004 * want to disable a context switch OUT till we get any PMCs targeting 5005 * this process off the hardware. 5006 * 5007 * We also need to atomically remove this process' entry from our 5008 * target process hash table, using PMC_FLAG_REMOVE. 5009 */ 5010 PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid, 5011 p->p_comm); 5012 5013 critical_enter(); /* no preemption */ 5014 5015 cpu = curthread->td_oncpu; 5016 5017 pp = pmc_find_process_descriptor(p, PMC_FLAG_REMOVE); 5018 if (pp == NULL) { 5019 critical_exit(); 5020 goto out; 5021 } 5022 5023 PMCDBG2(PRC,EXT,2, "process-exit proc=%p pmc-process=%p", p, pp); 5024 5025 /* 5026 * The exiting process could be the target of some PMCs which will be 5027 * running on currently executing CPU. 5028 * 5029 * We need to turn these PMCs off like we would do at context switch 5030 * OUT time. 5031 */ 5032 for (ri = 0; ri < md->pmd_npmc; ri++) { 5033 /* 5034 * Pick up the pmc pointer from hardware state similar to the 5035 * CSW_OUT code. 5036 */ 5037 pm = NULL; 5038 pcd = pmc_ri_to_classdep(md, ri, &adjri); 5039 5040 (void)(*pcd->pcd_get_config)(cpu, adjri, &pm); 5041 5042 PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm); 5043 5044 if (pm == NULL || !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) 5045 continue; 5046 5047 PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p state=%d", ri, 5048 pp->pp_pmcs[ri].pp_pmc, pm, pm->pm_state); 5049 5050 KASSERT(PMC_TO_ROWINDEX(pm) == ri, 5051 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)", __LINE__, 5052 PMC_TO_ROWINDEX(pm), ri)); 5053 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc, 5054 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__, pm, ri, 5055 pp->pp_pmcs[ri].pp_pmc)); 5056 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 5057 ("[pmc,%d] bad runcount ri %d rc %ju", __LINE__, ri, 5058 (uintmax_t)counter_u64_fetch(pm->pm_runcount))); 5059 5060 /* 5061 * Change desired state, and then stop if not stalled. This 5062 * two-step dance should avoid race conditions where an 5063 * interrupt re-enables the PMC after this code has already 5064 * checked the pm_stalled flag. 5065 */ 5066 if (pm->pm_pcpu_state[cpu].pps_cpustate) { 5067 pm->pm_pcpu_state[cpu].pps_cpustate = 0; 5068 if (!pm->pm_pcpu_state[cpu].pps_stalled) { 5069 (void)pcd->pcd_stop_pmc(cpu, adjri, pm); 5070 5071 if (PMC_TO_MODE(pm) == PMC_MODE_TC) { 5072 pcd->pcd_read_pmc(cpu, adjri, pm, 5073 &newvalue); 5074 tmp = newvalue - PMC_PCPU_SAVED(cpu, ri); 5075 5076 mtx_pool_lock_spin(pmc_mtxpool, pm); 5077 pm->pm_gv.pm_savedvalue += tmp; 5078 pp->pp_pmcs[ri].pp_pmcval += tmp; 5079 mtx_pool_unlock_spin(pmc_mtxpool, pm); 5080 } 5081 } 5082 } 5083 5084 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0, 5085 ("[pmc,%d] runcount is %d", __LINE__, ri)); 5086 5087 counter_u64_add(pm->pm_runcount, -1); 5088 (void)pcd->pcd_config_pmc(cpu, adjri, NULL); 5089 } 5090 5091 /* 5092 * Inform the MD layer of this pseudo "context switch out". 5093 */ 5094 (void)md->pmd_switch_out(pmc_pcpu[cpu], pp); 5095 5096 critical_exit(); /* ok to be pre-empted now */ 5097 5098 /* 5099 * Unlink this process from the PMCs that are targeting it. This will 5100 * send a signal to all PMC owner's whose PMCs are orphaned. 5101 * 5102 * Log PMC value at exit time if requested. 5103 */ 5104 for (ri = 0; ri < md->pmd_npmc; ri++) { 5105 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) { 5106 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) != 0 && 5107 PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm))) { 5108 pmclog_process_procexit(pm, pp); 5109 } 5110 pmc_unlink_target_process(pm, pp); 5111 } 5112 } 5113 free(pp, M_PMC); 5114 5115 out: 5116 /* 5117 * If the process owned PMCs, free them up and free up memory. 5118 */ 5119 if ((po = pmc_find_owner_descriptor(p)) != NULL) { 5120 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 5121 pmclog_close(po); 5122 pmc_remove_owner(po); 5123 pmc_destroy_owner_descriptor(po); 5124 } 5125 5126 sx_xunlock(&pmc_sx); 5127 } 5128 5129 /* 5130 * Handle a process fork. 5131 * 5132 * If the parent process 'p1' is under HWPMC monitoring, then copy 5133 * over any attached PMCs that have 'do_descendants' semantics. 5134 */ 5135 static void 5136 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc, 5137 int flags __unused) 5138 { 5139 struct pmc *pm; 5140 struct pmc_owner *po; 5141 struct pmc_process *ppnew, *ppold; 5142 unsigned int ri; 5143 bool is_using_hwpmcs, do_descendants; 5144 5145 PROC_LOCK(p1); 5146 is_using_hwpmcs = (p1->p_flag & P_HWPMC) != 0; 5147 PROC_UNLOCK(p1); 5148 5149 /* 5150 * If there are system-wide sampling PMCs active, we need to 5151 * log all fork events to their owner's logs. 5152 */ 5153 PMC_EPOCH_ENTER(); 5154 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5155 if (po->po_flags & PMC_PO_OWNS_LOGFILE) { 5156 pmclog_process_procfork(po, p1->p_pid, newproc->p_pid); 5157 pmclog_process_proccreate(po, newproc, 1); 5158 } 5159 } 5160 PMC_EPOCH_EXIT(); 5161 5162 if (!is_using_hwpmcs) 5163 return; 5164 5165 PMC_GET_SX_XLOCK(); 5166 PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1, 5167 p1->p_pid, p1->p_comm, newproc); 5168 5169 /* 5170 * If the parent process (curthread->td_proc) is a 5171 * target of any PMCs, look for PMCs that are to be 5172 * inherited, and link these into the new process 5173 * descriptor. 5174 */ 5175 ppold = pmc_find_process_descriptor(curthread->td_proc, PMC_FLAG_NONE); 5176 if (ppold == NULL) 5177 goto done; /* nothing to do */ 5178 5179 do_descendants = false; 5180 for (ri = 0; ri < md->pmd_npmc; ri++) { 5181 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL && 5182 (pm->pm_flags & PMC_F_DESCENDANTS) != 0) { 5183 do_descendants = true; 5184 break; 5185 } 5186 } 5187 if (!do_descendants) /* nothing to do */ 5188 goto done; 5189 5190 /* 5191 * Now mark the new process as being tracked by this driver. 5192 */ 5193 PROC_LOCK(newproc); 5194 newproc->p_flag |= P_HWPMC; 5195 PROC_UNLOCK(newproc); 5196 5197 /* Allocate a descriptor for the new process. */ 5198 ppnew = pmc_find_process_descriptor(newproc, PMC_FLAG_ALLOCATE); 5199 if (ppnew == NULL) 5200 goto done; 5201 5202 /* 5203 * Run through all PMCs that were targeting the old process 5204 * and which specified F_DESCENDANTS and attach them to the 5205 * new process. 5206 * 5207 * Log the fork event to all owners of PMCs attached to this 5208 * process, if not already logged. 5209 */ 5210 for (ri = 0; ri < md->pmd_npmc; ri++) { 5211 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL && 5212 (pm->pm_flags & PMC_F_DESCENDANTS) != 0) { 5213 pmc_link_target_process(pm, ppnew); 5214 po = pm->pm_owner; 5215 if (po->po_sscount == 0 && 5216 (po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) { 5217 pmclog_process_procfork(po, p1->p_pid, 5218 newproc->p_pid); 5219 } 5220 } 5221 } 5222 5223 done: 5224 sx_xunlock(&pmc_sx); 5225 } 5226 5227 static void 5228 pmc_process_threadcreate(struct thread *td) 5229 { 5230 struct pmc_owner *po; 5231 5232 PMC_EPOCH_ENTER(); 5233 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5234 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 5235 pmclog_process_threadcreate(po, td, 1); 5236 } 5237 PMC_EPOCH_EXIT(); 5238 } 5239 5240 static void 5241 pmc_process_threadexit(struct thread *td) 5242 { 5243 struct pmc_owner *po; 5244 5245 PMC_EPOCH_ENTER(); 5246 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5247 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 5248 pmclog_process_threadexit(po, td); 5249 } 5250 PMC_EPOCH_EXIT(); 5251 } 5252 5253 static void 5254 pmc_process_proccreate(struct proc *p) 5255 { 5256 struct pmc_owner *po; 5257 5258 PMC_EPOCH_ENTER(); 5259 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5260 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) 5261 pmclog_process_proccreate(po, p, 1 /* sync */); 5262 } 5263 PMC_EPOCH_EXIT(); 5264 } 5265 5266 static void 5267 pmc_process_allproc(struct pmc *pm) 5268 { 5269 struct pmc_owner *po; 5270 struct thread *td; 5271 struct proc *p; 5272 5273 po = pm->pm_owner; 5274 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) 5275 return; 5276 5277 sx_slock(&allproc_lock); 5278 FOREACH_PROC_IN_SYSTEM(p) { 5279 pmclog_process_proccreate(po, p, 0 /* sync */); 5280 PROC_LOCK(p); 5281 FOREACH_THREAD_IN_PROC(p, td) 5282 pmclog_process_threadcreate(po, td, 0 /* sync */); 5283 PROC_UNLOCK(p); 5284 } 5285 sx_sunlock(&allproc_lock); 5286 pmclog_flush(po, 0); 5287 } 5288 5289 static void 5290 pmc_kld_load(void *arg __unused, linker_file_t lf) 5291 { 5292 struct pmc_owner *po; 5293 5294 /* 5295 * Notify owners of system sampling PMCs about KLD operations. 5296 */ 5297 PMC_EPOCH_ENTER(); 5298 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5299 if (po->po_flags & PMC_PO_OWNS_LOGFILE) 5300 pmclog_process_map_in(po, (pid_t) -1, 5301 (uintfptr_t) lf->address, lf->pathname); 5302 } 5303 PMC_EPOCH_EXIT(); 5304 5305 /* 5306 * TODO: Notify owners of (all) process-sampling PMCs too. 5307 */ 5308 } 5309 5310 static void 5311 pmc_kld_unload(void *arg __unused, const char *filename __unused, 5312 caddr_t address, size_t size) 5313 { 5314 struct pmc_owner *po; 5315 5316 PMC_EPOCH_ENTER(); 5317 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) { 5318 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) { 5319 pmclog_process_map_out(po, (pid_t)-1, 5320 (uintfptr_t)address, (uintfptr_t)address + size); 5321 } 5322 } 5323 PMC_EPOCH_EXIT(); 5324 5325 /* 5326 * TODO: Notify owners of process-sampling PMCs. 5327 */ 5328 } 5329 5330 /* 5331 * initialization 5332 */ 5333 static const char * 5334 pmc_name_of_pmcclass(enum pmc_class class) 5335 { 5336 5337 switch (class) { 5338 #undef __PMC_CLASS 5339 #define __PMC_CLASS(S,V,D) \ 5340 case PMC_CLASS_##S: \ 5341 return #S; 5342 __PMC_CLASSES(); 5343 default: 5344 return ("<unknown>"); 5345 } 5346 } 5347 5348 /* 5349 * Base class initializer: allocate structure and set default classes. 5350 */ 5351 struct pmc_mdep * 5352 pmc_mdep_alloc(int nclasses) 5353 { 5354 struct pmc_mdep *md; 5355 int n; 5356 5357 /* SOFT + md classes */ 5358 n = 1 + nclasses; 5359 md = malloc(sizeof(struct pmc_mdep) + n * sizeof(struct pmc_classdep), 5360 M_PMC, M_WAITOK | M_ZERO); 5361 md->pmd_nclass = n; 5362 5363 /* Default methods */ 5364 md->pmd_switch_in = generic_switch_in; 5365 md->pmd_switch_out = generic_switch_out; 5366 5367 /* Add base class. */ 5368 pmc_soft_initialize(md); 5369 return (md); 5370 } 5371 5372 void 5373 pmc_mdep_free(struct pmc_mdep *md) 5374 { 5375 pmc_soft_finalize(md); 5376 free(md, M_PMC); 5377 } 5378 5379 static int 5380 generic_switch_in(struct pmc_cpu *pc __unused, struct pmc_process *pp __unused) 5381 { 5382 5383 return (0); 5384 } 5385 5386 static int 5387 generic_switch_out(struct pmc_cpu *pc __unused, struct pmc_process *pp __unused) 5388 { 5389 5390 return (0); 5391 } 5392 5393 static struct pmc_mdep * 5394 pmc_generic_cpu_initialize(void) 5395 { 5396 struct pmc_mdep *md; 5397 5398 md = pmc_mdep_alloc(0); 5399 5400 md->pmd_cputype = PMC_CPU_GENERIC; 5401 5402 return (md); 5403 } 5404 5405 static void 5406 pmc_generic_cpu_finalize(struct pmc_mdep *md __unused) 5407 { 5408 5409 } 5410 5411 static int 5412 pmc_initialize(void) 5413 { 5414 struct pcpu *pc; 5415 struct pmc_binding pb; 5416 struct pmc_classdep *pcd; 5417 struct pmc_sample *ps; 5418 struct pmc_samplebuffer *sb; 5419 int c, cpu, error, n, ri; 5420 u_int maxcpu, domain; 5421 5422 md = NULL; 5423 error = 0; 5424 5425 pmc_stats.pm_intr_ignored = counter_u64_alloc(M_WAITOK); 5426 pmc_stats.pm_intr_processed = counter_u64_alloc(M_WAITOK); 5427 pmc_stats.pm_intr_bufferfull = counter_u64_alloc(M_WAITOK); 5428 pmc_stats.pm_syscalls = counter_u64_alloc(M_WAITOK); 5429 pmc_stats.pm_syscall_errors = counter_u64_alloc(M_WAITOK); 5430 pmc_stats.pm_buffer_requests = counter_u64_alloc(M_WAITOK); 5431 pmc_stats.pm_buffer_requests_failed = counter_u64_alloc(M_WAITOK); 5432 pmc_stats.pm_log_sweeps = counter_u64_alloc(M_WAITOK); 5433 pmc_stats.pm_merges = counter_u64_alloc(M_WAITOK); 5434 pmc_stats.pm_overwrites = counter_u64_alloc(M_WAITOK); 5435 5436 #ifdef HWPMC_DEBUG 5437 /* parse debug flags first */ 5438 if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags", 5439 pmc_debugstr, sizeof(pmc_debugstr))) { 5440 pmc_debugflags_parse(pmc_debugstr, pmc_debugstr + 5441 strlen(pmc_debugstr)); 5442 } 5443 #endif 5444 5445 PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION); 5446 5447 /* check kernel version */ 5448 if (pmc_kernel_version != PMC_VERSION) { 5449 if (pmc_kernel_version == 0) 5450 printf("hwpmc: this kernel has not been compiled with " 5451 "'options HWPMC_HOOKS'.\n"); 5452 else 5453 printf("hwpmc: kernel version (0x%x) does not match " 5454 "module version (0x%x).\n", pmc_kernel_version, 5455 PMC_VERSION); 5456 return (EPROGMISMATCH); 5457 } 5458 5459 /* 5460 * check sysctl parameters 5461 */ 5462 if (pmc_hashsize <= 0) { 5463 printf("hwpmc: tunable \"hashsize\"=%d must be " 5464 "greater than zero.\n", pmc_hashsize); 5465 pmc_hashsize = PMC_HASH_SIZE; 5466 } 5467 5468 if (pmc_nsamples <= 0 || pmc_nsamples > 65535) { 5469 printf("hwpmc: tunable \"nsamples\"=%d out of " 5470 "range.\n", pmc_nsamples); 5471 pmc_nsamples = PMC_NSAMPLES; 5472 } 5473 pmc_sample_mask = pmc_nsamples - 1; 5474 5475 if (pmc_callchaindepth <= 0 || 5476 pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) { 5477 printf("hwpmc: tunable \"callchaindepth\"=%d out of " 5478 "range - using %d.\n", pmc_callchaindepth, 5479 PMC_CALLCHAIN_DEPTH_MAX); 5480 pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX; 5481 } 5482 5483 md = pmc_md_initialize(); 5484 if (md == NULL) { 5485 /* Default to generic CPU. */ 5486 md = pmc_generic_cpu_initialize(); 5487 if (md == NULL) 5488 return (ENOSYS); 5489 } 5490 5491 /* 5492 * Refresh classes base ri. Optional classes may come in different 5493 * order. 5494 */ 5495 for (ri = c = 0; c < md->pmd_nclass; c++) { 5496 pcd = &md->pmd_classdep[c]; 5497 pcd->pcd_ri = ri; 5498 ri += pcd->pcd_num; 5499 } 5500 5501 KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1, 5502 ("[pmc,%d] no classes or pmcs", __LINE__)); 5503 5504 /* Compute the map from row-indices to classdep pointers. */ 5505 pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) * 5506 md->pmd_npmc, M_PMC, M_WAITOK | M_ZERO); 5507 5508 for (n = 0; n < md->pmd_npmc; n++) 5509 pmc_rowindex_to_classdep[n] = NULL; 5510 5511 for (ri = c = 0; c < md->pmd_nclass; c++) { 5512 pcd = &md->pmd_classdep[c]; 5513 for (n = 0; n < pcd->pcd_num; n++, ri++) 5514 pmc_rowindex_to_classdep[ri] = pcd; 5515 } 5516 5517 KASSERT(ri == md->pmd_npmc, 5518 ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__, 5519 ri, md->pmd_npmc)); 5520 5521 maxcpu = pmc_cpu_max(); 5522 5523 /* allocate space for the per-cpu array */ 5524 pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC, 5525 M_WAITOK | M_ZERO); 5526 5527 /* per-cpu 'saved values' for managing process-mode PMCs */ 5528 pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc, 5529 M_PMC, M_WAITOK); 5530 5531 /* Perform CPU-dependent initialization. */ 5532 pmc_save_cpu_binding(&pb); 5533 error = 0; 5534 for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) { 5535 if (!pmc_cpu_is_active(cpu)) 5536 continue; 5537 pmc_select_cpu(cpu); 5538 pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) + 5539 md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC, 5540 M_WAITOK | M_ZERO); 5541 for (n = 0; error == 0 && n < md->pmd_nclass; n++) 5542 if (md->pmd_classdep[n].pcd_num > 0) 5543 error = md->pmd_classdep[n].pcd_pcpu_init(md, 5544 cpu); 5545 } 5546 pmc_restore_cpu_binding(&pb); 5547 5548 if (error != 0) 5549 return (error); 5550 5551 /* allocate space for the sample array */ 5552 for (cpu = 0; cpu < maxcpu; cpu++) { 5553 if (!pmc_cpu_is_active(cpu)) 5554 continue; 5555 pc = pcpu_find(cpu); 5556 domain = pc->pc_domain; 5557 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) + 5558 pmc_nsamples * sizeof(struct pmc_sample), M_PMC, 5559 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5560 5561 KASSERT(pmc_pcpu[cpu] != NULL, 5562 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu)); 5563 5564 sb->ps_callchains = malloc_domainset(pmc_callchaindepth * 5565 pmc_nsamples * sizeof(uintptr_t), M_PMC, 5566 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5567 5568 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++) 5569 ps->ps_pc = sb->ps_callchains + 5570 (n * pmc_callchaindepth); 5571 5572 pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb; 5573 5574 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) + 5575 pmc_nsamples * sizeof(struct pmc_sample), M_PMC, 5576 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5577 5578 sb->ps_callchains = malloc_domainset(pmc_callchaindepth * 5579 pmc_nsamples * sizeof(uintptr_t), M_PMC, 5580 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5581 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++) 5582 ps->ps_pc = sb->ps_callchains + 5583 (n * pmc_callchaindepth); 5584 5585 pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb; 5586 5587 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) + 5588 pmc_nsamples * sizeof(struct pmc_sample), M_PMC, 5589 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5590 sb->ps_callchains = malloc_domainset(pmc_callchaindepth * 5591 pmc_nsamples * sizeof(uintptr_t), M_PMC, 5592 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO); 5593 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++) 5594 ps->ps_pc = sb->ps_callchains + n * pmc_callchaindepth; 5595 5596 pmc_pcpu[cpu]->pc_sb[PMC_UR] = sb; 5597 } 5598 5599 /* allocate space for the row disposition array */ 5600 pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc, 5601 M_PMC, M_WAITOK | M_ZERO); 5602 5603 /* mark all PMCs as available */ 5604 for (n = 0; n < md->pmd_npmc; n++) 5605 PMC_MARK_ROW_FREE(n); 5606 5607 /* allocate thread hash tables */ 5608 pmc_ownerhash = hashinit(pmc_hashsize, M_PMC, 5609 &pmc_ownerhashmask); 5610 5611 pmc_processhash = hashinit(pmc_hashsize, M_PMC, 5612 &pmc_processhashmask); 5613 mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf", 5614 MTX_SPIN); 5615 5616 CK_LIST_INIT(&pmc_ss_owners); 5617 pmc_ss_count = 0; 5618 5619 /* allocate a pool of spin mutexes */ 5620 pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size, 5621 MTX_SPIN); 5622 5623 PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx " 5624 "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask, 5625 pmc_processhash, pmc_processhashmask); 5626 5627 /* Initialize a spin mutex for the thread free list. */ 5628 mtx_init(&pmc_threadfreelist_mtx, "pmc-threadfreelist", "pmc-leaf", 5629 MTX_SPIN); 5630 5631 /* Initialize the task to prune the thread free list. */ 5632 TASK_INIT(&free_task, 0, pmc_thread_descriptor_pool_free_task, NULL); 5633 5634 /* register process {exit,fork,exec} handlers */ 5635 pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit, 5636 pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY); 5637 pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork, 5638 pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY); 5639 5640 /* register kld event handlers */ 5641 pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load, 5642 NULL, EVENTHANDLER_PRI_ANY); 5643 pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload, 5644 NULL, EVENTHANDLER_PRI_ANY); 5645 5646 /* initialize logging */ 5647 pmclog_initialize(); 5648 5649 /* set hook functions */ 5650 pmc_intr = md->pmd_intr; 5651 wmb(); 5652 pmc_hook = pmc_hook_handler; 5653 5654 if (error == 0) { 5655 printf(PMC_MODULE_NAME ":"); 5656 for (n = 0; n < md->pmd_nclass; n++) { 5657 if (md->pmd_classdep[n].pcd_num == 0) 5658 continue; 5659 pcd = &md->pmd_classdep[n]; 5660 printf(" %s/%d/%d/0x%b", 5661 pmc_name_of_pmcclass(pcd->pcd_class), 5662 pcd->pcd_num, 5663 pcd->pcd_width, 5664 pcd->pcd_caps, 5665 "\20" 5666 "\1INT\2USR\3SYS\4EDG\5THR" 5667 "\6REA\7WRI\10INV\11QUA\12PRC" 5668 "\13TAG\14CSC"); 5669 } 5670 printf("\n"); 5671 } 5672 5673 return (error); 5674 } 5675 5676 /* prepare to be unloaded */ 5677 static void 5678 pmc_cleanup(void) 5679 { 5680 struct pmc_binding pb; 5681 struct pmc_owner *po, *tmp; 5682 struct pmc_ownerhash *ph; 5683 struct pmc_processhash *prh __pmcdbg_used; 5684 u_int maxcpu; 5685 int cpu, c; 5686 5687 PMCDBG0(MOD,INI,0, "cleanup"); 5688 5689 /* switch off sampling */ 5690 CPU_FOREACH(cpu) 5691 DPCPU_ID_SET(cpu, pmc_sampled, 0); 5692 pmc_intr = NULL; 5693 5694 sx_xlock(&pmc_sx); 5695 if (pmc_hook == NULL) { /* being unloaded already */ 5696 sx_xunlock(&pmc_sx); 5697 return; 5698 } 5699 5700 pmc_hook = NULL; /* prevent new threads from entering module */ 5701 5702 /* deregister event handlers */ 5703 EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag); 5704 EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag); 5705 EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag); 5706 EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag); 5707 5708 /* send SIGBUS to all owner threads, free up allocations */ 5709 if (pmc_ownerhash != NULL) { 5710 for (ph = pmc_ownerhash; 5711 ph <= &pmc_ownerhash[pmc_ownerhashmask]; 5712 ph++) { 5713 LIST_FOREACH_SAFE(po, ph, po_next, tmp) { 5714 pmc_remove_owner(po); 5715 5716 PMCDBG3(MOD,INI,2, 5717 "cleanup signal proc=%p (%d, %s)", 5718 po->po_owner, po->po_owner->p_pid, 5719 po->po_owner->p_comm); 5720 5721 PROC_LOCK(po->po_owner); 5722 kern_psignal(po->po_owner, SIGBUS); 5723 PROC_UNLOCK(po->po_owner); 5724 5725 pmc_destroy_owner_descriptor(po); 5726 } 5727 } 5728 } 5729 5730 /* reclaim allocated data structures */ 5731 taskqueue_drain(taskqueue_fast, &free_task); 5732 mtx_destroy(&pmc_threadfreelist_mtx); 5733 pmc_thread_descriptor_pool_drain(); 5734 5735 if (pmc_mtxpool != NULL) 5736 mtx_pool_destroy(&pmc_mtxpool); 5737 5738 mtx_destroy(&pmc_processhash_mtx); 5739 if (pmc_processhash != NULL) { 5740 #ifdef HWPMC_DEBUG 5741 struct pmc_process *pp; 5742 5743 PMCDBG0(MOD,INI,3, "destroy process hash"); 5744 for (prh = pmc_processhash; 5745 prh <= &pmc_processhash[pmc_processhashmask]; 5746 prh++) 5747 LIST_FOREACH(pp, prh, pp_next) 5748 PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid); 5749 #endif 5750 5751 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask); 5752 pmc_processhash = NULL; 5753 } 5754 5755 if (pmc_ownerhash != NULL) { 5756 PMCDBG0(MOD,INI,3, "destroy owner hash"); 5757 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask); 5758 pmc_ownerhash = NULL; 5759 } 5760 5761 KASSERT(CK_LIST_EMPTY(&pmc_ss_owners), 5762 ("[pmc,%d] Global SS owner list not empty", __LINE__)); 5763 KASSERT(pmc_ss_count == 0, 5764 ("[pmc,%d] Global SS count not empty", __LINE__)); 5765 5766 /* do processor and pmc-class dependent cleanup */ 5767 maxcpu = pmc_cpu_max(); 5768 5769 PMCDBG0(MOD,INI,3, "md cleanup"); 5770 if (md) { 5771 pmc_save_cpu_binding(&pb); 5772 for (cpu = 0; cpu < maxcpu; cpu++) { 5773 PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p", 5774 cpu, pmc_pcpu[cpu]); 5775 if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL) 5776 continue; 5777 5778 pmc_select_cpu(cpu); 5779 for (c = 0; c < md->pmd_nclass; c++) { 5780 if (md->pmd_classdep[c].pcd_num > 0) { 5781 md->pmd_classdep[c].pcd_pcpu_fini(md, 5782 cpu); 5783 } 5784 } 5785 } 5786 5787 if (md->pmd_cputype == PMC_CPU_GENERIC) 5788 pmc_generic_cpu_finalize(md); 5789 else 5790 pmc_md_finalize(md); 5791 5792 pmc_mdep_free(md); 5793 md = NULL; 5794 pmc_restore_cpu_binding(&pb); 5795 } 5796 5797 /* Free per-cpu descriptors. */ 5798 for (cpu = 0; cpu < maxcpu; cpu++) { 5799 if (!pmc_cpu_is_active(cpu)) 5800 continue; 5801 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL, 5802 ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__, 5803 cpu)); 5804 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL, 5805 ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__, 5806 cpu)); 5807 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_UR] != NULL, 5808 ("[pmc,%d] Null userret cpu sample buffer cpu=%d", __LINE__, 5809 cpu)); 5810 free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC); 5811 free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC); 5812 free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC); 5813 free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC); 5814 free(pmc_pcpu[cpu]->pc_sb[PMC_UR]->ps_callchains, M_PMC); 5815 free(pmc_pcpu[cpu]->pc_sb[PMC_UR], M_PMC); 5816 free(pmc_pcpu[cpu], M_PMC); 5817 } 5818 5819 free(pmc_pcpu, M_PMC); 5820 pmc_pcpu = NULL; 5821 5822 free(pmc_pcpu_saved, M_PMC); 5823 pmc_pcpu_saved = NULL; 5824 5825 if (pmc_pmcdisp != NULL) { 5826 free(pmc_pmcdisp, M_PMC); 5827 pmc_pmcdisp = NULL; 5828 } 5829 5830 if (pmc_rowindex_to_classdep != NULL) { 5831 free(pmc_rowindex_to_classdep, M_PMC); 5832 pmc_rowindex_to_classdep = NULL; 5833 } 5834 5835 pmclog_shutdown(); 5836 counter_u64_free(pmc_stats.pm_intr_ignored); 5837 counter_u64_free(pmc_stats.pm_intr_processed); 5838 counter_u64_free(pmc_stats.pm_intr_bufferfull); 5839 counter_u64_free(pmc_stats.pm_syscalls); 5840 counter_u64_free(pmc_stats.pm_syscall_errors); 5841 counter_u64_free(pmc_stats.pm_buffer_requests); 5842 counter_u64_free(pmc_stats.pm_buffer_requests_failed); 5843 counter_u64_free(pmc_stats.pm_log_sweeps); 5844 counter_u64_free(pmc_stats.pm_merges); 5845 counter_u64_free(pmc_stats.pm_overwrites); 5846 sx_xunlock(&pmc_sx); /* we are done */ 5847 } 5848 5849 /* 5850 * The function called at load/unload. 5851 */ 5852 static int 5853 load(struct module *module __unused, int cmd, void *arg __unused) 5854 { 5855 int error; 5856 5857 error = 0; 5858 5859 switch (cmd) { 5860 case MOD_LOAD: 5861 /* initialize the subsystem */ 5862 error = pmc_initialize(); 5863 if (error != 0) 5864 break; 5865 PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d", pmc_syscall_num, 5866 pmc_cpu_max()); 5867 break; 5868 case MOD_UNLOAD: 5869 case MOD_SHUTDOWN: 5870 pmc_cleanup(); 5871 PMCDBG0(MOD,INI,1, "unloaded"); 5872 break; 5873 default: 5874 error = EINVAL; 5875 break; 5876 } 5877 5878 return (error); 5879 } 5880