1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD 3 * 4 * Copyright (c) 2003-2008, Joseph Koshy 5 * Copyright (c) 2007 The FreeBSD Foundation 6 * All rights reserved. 7 * 8 * Portions of this software were developed by A. Joseph Koshy under 9 * sponsorship from the FreeBSD Foundation and Google, Inc. 10 * 11 * Redistribution and use in source and binary forms, with or without 12 * modification, are permitted provided that the following conditions 13 * are met: 14 * 1. Redistributions of source code must retain the above copyright 15 * notice, this list of conditions and the following disclaimer. 16 * 2. Redistributions in binary form must reproduce the above copyright 17 * notice, this list of conditions and the following disclaimer in the 18 * documentation and/or other materials provided with the distribution. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 30 * SUCH DAMAGE. 31 */ 32 33 #include <sys/cdefs.h> 34 __FBSDID("$FreeBSD$"); 35 36 #include <sys/param.h> 37 #include <sys/cpuset.h> 38 #include <sys/event.h> 39 #include <sys/queue.h> 40 #include <sys/socket.h> 41 #include <sys/stat.h> 42 #include <sys/sysctl.h> 43 #include <sys/time.h> 44 #include <sys/ttycom.h> 45 #include <sys/user.h> 46 #include <sys/wait.h> 47 48 #include <assert.h> 49 #include <curses.h> 50 #include <err.h> 51 #include <errno.h> 52 #include <fcntl.h> 53 #include <kvm.h> 54 #include <libgen.h> 55 #include <limits.h> 56 #include <math.h> 57 #include <pmc.h> 58 #include <pmclog.h> 59 #include <regex.h> 60 #include <signal.h> 61 #include <stdarg.h> 62 #include <stdint.h> 63 #include <stdio.h> 64 #include <stdlib.h> 65 #include <string.h> 66 #include <sysexits.h> 67 #include <unistd.h> 68 69 #include <libpmcstat.h> 70 71 #include "pmcstat.h" 72 73 /* 74 * A given invocation of pmcstat(8) can manage multiple PMCs of both 75 * the system-wide and per-process variety. Each of these could be in 76 * 'counting mode' or in 'sampling mode'. 77 * 78 * For 'counting mode' PMCs, pmcstat(8) will periodically issue a 79 * pmc_read() at the configured time interval and print out the value 80 * of the requested PMCs. 81 * 82 * For 'sampling mode' PMCs it can log to a file for offline analysis, 83 * or can analyse sampling data "on the fly", either by converting 84 * samples to printed textual form or by creating gprof(1) compatible 85 * profiles, one per program executed. When creating gprof(1) 86 * profiles it can optionally merge entries from multiple processes 87 * for a given executable into a single profile file. 88 * 89 * pmcstat(8) can also execute a command line and attach PMCs to the 90 * resulting child process. The protocol used is as follows: 91 * 92 * - parent creates a socketpair for two way communication and 93 * fork()s. 94 * - subsequently: 95 * 96 * /Parent/ /Child/ 97 * 98 * - Wait for childs token. 99 * - Sends token. 100 * - Awaits signal to start. 101 * - Attaches PMCs to the child's pid 102 * and starts them. Sets up 103 * monitoring for the child. 104 * - Signals child to start. 105 * - Receives signal, attempts exec(). 106 * 107 * After this point normal processing can happen. 108 */ 109 110 /* Globals */ 111 112 int pmcstat_displayheight = DEFAULT_DISPLAY_HEIGHT; 113 int pmcstat_displaywidth = DEFAULT_DISPLAY_WIDTH; 114 static int pmcstat_sockpair[NSOCKPAIRFD]; 115 static int pmcstat_kq; 116 static kvm_t *pmcstat_kvm; 117 static struct kinfo_proc *pmcstat_plist; 118 struct pmcstat_args args; 119 120 static void 121 pmcstat_get_cpumask(const char *cpuspec, cpuset_t *cpumask) 122 { 123 int cpu; 124 const char *s; 125 char *end; 126 127 CPU_ZERO(cpumask); 128 s = cpuspec; 129 130 do { 131 cpu = strtol(s, &end, 0); 132 if (cpu < 0 || end == s) 133 errx(EX_USAGE, 134 "ERROR: Illegal CPU specification \"%s\".", 135 cpuspec); 136 CPU_SET(cpu, cpumask); 137 s = end + strspn(end, ", \t"); 138 } while (*s); 139 assert(!CPU_EMPTY(cpumask)); 140 } 141 142 void 143 pmcstat_cleanup(void) 144 { 145 struct pmcstat_ev *ev; 146 147 /* release allocated PMCs. */ 148 STAILQ_FOREACH(ev, &args.pa_events, ev_next) 149 if (ev->ev_pmcid != PMC_ID_INVALID) { 150 if (pmc_stop(ev->ev_pmcid) < 0) 151 err(EX_OSERR, 152 "ERROR: cannot stop pmc 0x%x \"%s\"", 153 ev->ev_pmcid, ev->ev_name); 154 if (pmc_release(ev->ev_pmcid) < 0) 155 err(EX_OSERR, 156 "ERROR: cannot release pmc 0x%x \"%s\"", 157 ev->ev_pmcid, ev->ev_name); 158 } 159 160 /* de-configure the log file if present. */ 161 if (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE)) 162 (void) pmc_configure_logfile(-1); 163 164 if (args.pa_logparser) { 165 pmclog_close(args.pa_logparser); 166 args.pa_logparser = NULL; 167 } 168 169 pmcstat_log_shutdown_logging(); 170 } 171 172 void 173 pmcstat_find_targets(const char *spec) 174 { 175 int n, nproc, pid, rv; 176 struct pmcstat_target *pt; 177 char errbuf[_POSIX2_LINE_MAX], *end; 178 static struct kinfo_proc *kp; 179 regex_t reg; 180 regmatch_t regmatch; 181 182 /* First check if we've been given a process id. */ 183 pid = strtol(spec, &end, 0); 184 if (end != spec && pid >= 0) { 185 if ((pt = malloc(sizeof(*pt))) == NULL) 186 goto outofmemory; 187 pt->pt_pid = pid; 188 SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next); 189 return; 190 } 191 192 /* Otherwise treat arg as a regular expression naming processes. */ 193 if (pmcstat_kvm == NULL) { 194 if ((pmcstat_kvm = kvm_openfiles(NULL, "/dev/null", NULL, 0, 195 errbuf)) == NULL) 196 err(EX_OSERR, "ERROR: Cannot open kernel \"%s\"", 197 errbuf); 198 if ((pmcstat_plist = kvm_getprocs(pmcstat_kvm, KERN_PROC_PROC, 199 0, &nproc)) == NULL) 200 err(EX_OSERR, "ERROR: Cannot get process list: %s", 201 kvm_geterr(pmcstat_kvm)); 202 } else 203 nproc = 0; 204 205 if ((rv = regcomp(®, spec, REG_EXTENDED|REG_NOSUB)) != 0) { 206 regerror(rv, ®, errbuf, sizeof(errbuf)); 207 err(EX_DATAERR, "ERROR: Failed to compile regex \"%s\": %s", 208 spec, errbuf); 209 } 210 211 for (n = 0, kp = pmcstat_plist; n < nproc; n++, kp++) { 212 if ((rv = regexec(®, kp->ki_comm, 1, ®match, 0)) == 0) { 213 if ((pt = malloc(sizeof(*pt))) == NULL) 214 goto outofmemory; 215 pt->pt_pid = kp->ki_pid; 216 SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next); 217 } else if (rv != REG_NOMATCH) { 218 regerror(rv, ®, errbuf, sizeof(errbuf)); 219 errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s", 220 errbuf); 221 } 222 } 223 224 regfree(®); 225 226 return; 227 228 outofmemory: 229 errx(EX_SOFTWARE, "Out of memory."); 230 /*NOTREACHED*/ 231 } 232 233 void 234 pmcstat_kill_process(void) 235 { 236 struct pmcstat_target *pt; 237 238 assert(args.pa_flags & FLAG_HAS_COMMANDLINE); 239 240 /* 241 * If a command line was specified, it would be the very first 242 * in the list, before any other processes specified by -t. 243 */ 244 pt = SLIST_FIRST(&args.pa_targets); 245 assert(pt != NULL); 246 247 if (kill(pt->pt_pid, SIGINT) != 0) 248 err(EX_OSERR, "ERROR: cannot signal child process"); 249 } 250 251 void 252 pmcstat_start_pmcs(void) 253 { 254 struct pmcstat_ev *ev; 255 256 STAILQ_FOREACH(ev, &args.pa_events, ev_next) { 257 258 assert(ev->ev_pmcid != PMC_ID_INVALID); 259 260 if (pmc_start(ev->ev_pmcid) < 0) { 261 warn("ERROR: Cannot start pmc 0x%x \"%s\"", 262 ev->ev_pmcid, ev->ev_name); 263 pmcstat_cleanup(); 264 exit(EX_OSERR); 265 } 266 } 267 } 268 269 void 270 pmcstat_print_headers(void) 271 { 272 struct pmcstat_ev *ev; 273 int c, w; 274 275 (void) fprintf(args.pa_printfile, PRINT_HEADER_PREFIX); 276 277 STAILQ_FOREACH(ev, &args.pa_events, ev_next) { 278 if (PMC_IS_SAMPLING_MODE(ev->ev_mode)) 279 continue; 280 281 c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p'; 282 283 if (ev->ev_fieldskip != 0) 284 (void) fprintf(args.pa_printfile, "%*s", 285 ev->ev_fieldskip, ""); 286 w = ev->ev_fieldwidth - ev->ev_fieldskip - 2; 287 288 if (c == 's') 289 (void) fprintf(args.pa_printfile, "s/%02d/%-*s ", 290 ev->ev_cpu, w-3, ev->ev_name); 291 else 292 (void) fprintf(args.pa_printfile, "p/%*s ", w, 293 ev->ev_name); 294 } 295 296 (void) fflush(args.pa_printfile); 297 } 298 299 void 300 pmcstat_print_counters(void) 301 { 302 int extra_width; 303 struct pmcstat_ev *ev; 304 pmc_value_t value; 305 306 extra_width = sizeof(PRINT_HEADER_PREFIX) - 1; 307 308 STAILQ_FOREACH(ev, &args.pa_events, ev_next) { 309 310 /* skip sampling mode counters */ 311 if (PMC_IS_SAMPLING_MODE(ev->ev_mode)) 312 continue; 313 314 if (pmc_read(ev->ev_pmcid, &value) < 0) 315 err(EX_OSERR, "ERROR: Cannot read pmc \"%s\"", 316 ev->ev_name); 317 318 (void) fprintf(args.pa_printfile, "%*ju ", 319 ev->ev_fieldwidth + extra_width, 320 (uintmax_t) ev->ev_cumulative ? value : 321 (value - ev->ev_saved)); 322 323 if (ev->ev_cumulative == 0) 324 ev->ev_saved = value; 325 extra_width = 0; 326 } 327 328 (void) fflush(args.pa_printfile); 329 } 330 331 /* 332 * Print output 333 */ 334 335 void 336 pmcstat_print_pmcs(void) 337 { 338 static int linecount = 0; 339 340 /* check if we need to print a header line */ 341 if (++linecount > pmcstat_displayheight) { 342 (void) fprintf(args.pa_printfile, "\n"); 343 linecount = 1; 344 } 345 if (linecount == 1) 346 pmcstat_print_headers(); 347 (void) fprintf(args.pa_printfile, "\n"); 348 349 pmcstat_print_counters(); 350 351 return; 352 } 353 354 void 355 pmcstat_show_usage(void) 356 { 357 errx(EX_USAGE, 358 "[options] [commandline]\n" 359 "\t Measure process and/or system performance using hardware\n" 360 "\t performance monitoring counters.\n" 361 "\t Options include:\n" 362 "\t -C\t\t (toggle) show cumulative counts\n" 363 "\t -D path\t create profiles in directory \"path\"\n" 364 "\t -E\t\t (toggle) show counts at process exit\n" 365 "\t -F file\t write a system-wide callgraph (Kcachegrind format)" 366 " to \"file\"\n" 367 "\t -G file\t write a system-wide callgraph to \"file\"\n" 368 "\t -I\t\t don't resolve leaf function name, show address instead\n" 369 "\t -L\t\t list all counters available on this host\n" 370 "\t -M file\t print executable/gmon file map to \"file\"\n" 371 "\t -N\t\t (toggle) capture callchains\n" 372 "\t -O file\t send log output to \"file\"\n" 373 "\t -P spec\t allocate a process-private sampling PMC\n" 374 "\t -R file\t read events from \"file\"\n" 375 "\t -S spec\t allocate a system-wide sampling PMC\n" 376 "\t -T\t\t start in top mode\n" 377 "\t -U spec \t provide long description of counters matching spec\n" 378 "\t -W\t\t (toggle) show counts per context switch\n" 379 "\t -a file\t print sampled PCs and callgraph to \"file\"\n" 380 "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n" 381 "\t -d\t\t (toggle) track descendants\n" 382 "\t -e\t\t use wide history counter for gprof(1) output\n" 383 "\t -f spec\t pass \"spec\" to as plugin option\n" 384 "\t -g\t\t produce gprof(1) compatible profiles\n" 385 "\t -i lwp\t\t filter on thread id \"lwp\" in post-processing\n" 386 "\t -k dir\t\t set the path to the kernel\n" 387 "\t -l secs\t set duration time\n" 388 "\t -m file\t print sampled PCs to \"file\"\n" 389 "\t -n rate\t set sampling rate\n" 390 "\t -o file\t send print output to \"file\"\n" 391 "\t -p spec\t allocate a process-private counting PMC\n" 392 "\t -q\t\t suppress verbosity\n" 393 "\t -r fsroot\t specify FS root directory\n" 394 "\t -s spec\t allocate a system-wide counting PMC\n" 395 "\t -t process-spec attach to running processes matching " 396 "\"process-spec\"\n" 397 "\t -u spec \t provide short description of counters matching spec\n" 398 "\t -v\t\t increase verbosity\n" 399 "\t -w secs\t set printing time interval\n" 400 "\t -z depth\t limit callchain display depth" 401 ); 402 } 403 404 /* 405 * At exit handler for top mode 406 */ 407 408 void 409 pmcstat_topexit(void) 410 { 411 if (!args.pa_toptty) 412 return; 413 414 /* 415 * Shutdown ncurses. 416 */ 417 clrtoeol(); 418 refresh(); 419 endwin(); 420 } 421 422 /* 423 * Main 424 */ 425 426 int 427 main(int argc, char **argv) 428 { 429 cpuset_t cpumask, rootmask; 430 double interval; 431 double duration; 432 int option, npmc; 433 int c, check_driver_stats; 434 int do_callchain, do_descendants, do_logproccsw, do_logprocexit; 435 int do_print, do_read, do_listcounters, do_descr, do_long_descr; 436 size_t len; 437 int graphdepth; 438 int pipefd[2], rfd; 439 int use_cumulative_counts; 440 short cf, cb; 441 uint64_t current_sampling_count; 442 char *end, *tmp, *event; 443 const char *errmsg, *graphfilename; 444 enum pmcstat_state runstate; 445 struct pmc_driverstats ds_start, ds_end; 446 struct pmcstat_ev *ev; 447 struct sigaction sa; 448 struct kevent kev; 449 struct winsize ws; 450 struct stat sb; 451 char buffer[PATH_MAX]; 452 453 check_driver_stats = 0; 454 current_sampling_count = 0; 455 do_callchain = 1; 456 do_descr = 0; 457 do_descendants = 0; 458 do_long_descr = 0; 459 do_logproccsw = 0; 460 do_logprocexit = 0; 461 do_listcounters = 0; 462 use_cumulative_counts = 0; 463 graphfilename = "-"; 464 args.pa_required = 0; 465 args.pa_flags = 0; 466 args.pa_verbosity = 1; 467 args.pa_logfd = -1; 468 args.pa_fsroot = ""; 469 args.pa_samplesdir = "."; 470 args.pa_printfile = stderr; 471 args.pa_graphdepth = DEFAULT_CALLGRAPH_DEPTH; 472 args.pa_graphfile = NULL; 473 args.pa_interval = DEFAULT_WAIT_INTERVAL; 474 args.pa_mapfilename = NULL; 475 args.pa_inputpath = NULL; 476 args.pa_outputpath = NULL; 477 args.pa_pplugin = PMCSTAT_PL_NONE; 478 args.pa_plugin = PMCSTAT_PL_NONE; 479 args.pa_ctdumpinstr = 1; 480 args.pa_topmode = PMCSTAT_TOP_DELTA; 481 args.pa_toptty = 0; 482 args.pa_topcolor = 0; 483 args.pa_mergepmc = 0; 484 args.pa_duration = 0.0; 485 STAILQ_INIT(&args.pa_events); 486 SLIST_INIT(&args.pa_targets); 487 bzero(&ds_start, sizeof(ds_start)); 488 bzero(&ds_end, sizeof(ds_end)); 489 ev = NULL; 490 CPU_ZERO(&cpumask); 491 492 /* Default to using the running system kernel. */ 493 len = 0; 494 if (sysctlbyname("kern.bootfile", NULL, &len, NULL, 0) == -1) 495 err(EX_OSERR, "ERROR: Cannot determine path of running kernel"); 496 args.pa_kernel = malloc(len); 497 if (args.pa_kernel == NULL) 498 errx(EX_SOFTWARE, "ERROR: Out of memory."); 499 if (sysctlbyname("kern.bootfile", args.pa_kernel, &len, NULL, 0) == -1) 500 err(EX_OSERR, "ERROR: Cannot determine path of running kernel"); 501 502 /* 503 * The initial CPU mask specifies the root mask of this process 504 * which is usually all CPUs in the system. 505 */ 506 if (cpuset_getaffinity(CPU_LEVEL_ROOT, CPU_WHICH_PID, -1, 507 sizeof(rootmask), &rootmask) == -1) 508 err(EX_OSERR, "ERROR: Cannot determine the root set of CPUs"); 509 CPU_COPY(&rootmask, &cpumask); 510 511 while ((option = getopt(argc, argv, 512 "CD:EF:G:ILM:NO:P:R:S:TU:WZa:c:def:gi:k:l:m:n:o:p:qr:s:t:u:vw:z:")) != -1) 513 switch (option) { 514 case 'a': /* Annotate + callgraph */ 515 args.pa_flags |= FLAG_DO_ANNOTATE; 516 args.pa_plugin = PMCSTAT_PL_ANNOTATE_CG; 517 graphfilename = optarg; 518 break; 519 520 case 'C': /* cumulative values */ 521 use_cumulative_counts = !use_cumulative_counts; 522 args.pa_required |= FLAG_HAS_COUNTING_PMCS; 523 break; 524 525 case 'c': /* CPU */ 526 if (optarg[0] == '*' && optarg[1] == '\0') 527 CPU_COPY(&rootmask, &cpumask); 528 else 529 pmcstat_get_cpumask(optarg, &cpumask); 530 531 args.pa_flags |= FLAGS_HAS_CPUMASK; 532 args.pa_required |= FLAG_HAS_SYSTEM_PMCS; 533 break; 534 535 case 'D': 536 if (stat(optarg, &sb) < 0) 537 err(EX_OSERR, "ERROR: Cannot stat \"%s\"", 538 optarg); 539 if (!S_ISDIR(sb.st_mode)) 540 errx(EX_USAGE, 541 "ERROR: \"%s\" is not a directory.", 542 optarg); 543 args.pa_samplesdir = optarg; 544 args.pa_flags |= FLAG_HAS_SAMPLESDIR; 545 args.pa_required |= FLAG_DO_GPROF; 546 break; 547 548 case 'd': /* toggle descendents */ 549 do_descendants = !do_descendants; 550 args.pa_required |= FLAG_HAS_PROCESS_PMCS; 551 break; 552 553 case 'E': /* log process exit */ 554 do_logprocexit = !do_logprocexit; 555 args.pa_required |= (FLAG_HAS_PROCESS_PMCS | 556 FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE); 557 break; 558 559 case 'e': /* wide gprof metrics */ 560 args.pa_flags |= FLAG_DO_WIDE_GPROF_HC; 561 break; 562 563 case 'F': /* produce a system-wide calltree */ 564 args.pa_flags |= FLAG_DO_CALLGRAPHS; 565 args.pa_plugin = PMCSTAT_PL_CALLTREE; 566 graphfilename = optarg; 567 break; 568 569 case 'f': /* plugins options */ 570 if (args.pa_plugin == PMCSTAT_PL_NONE) 571 err(EX_USAGE, "ERROR: Need -g/-G/-m/-T."); 572 pmcstat_pluginconfigure_log(optarg); 573 break; 574 575 case 'G': /* produce a system-wide callgraph */ 576 args.pa_flags |= FLAG_DO_CALLGRAPHS; 577 args.pa_plugin = PMCSTAT_PL_CALLGRAPH; 578 graphfilename = optarg; 579 break; 580 581 case 'g': /* produce gprof compatible profiles */ 582 args.pa_flags |= FLAG_DO_GPROF; 583 args.pa_pplugin = PMCSTAT_PL_CALLGRAPH; 584 args.pa_plugin = PMCSTAT_PL_GPROF; 585 break; 586 587 case 'I': 588 args.pa_flags |= FLAG_SKIP_TOP_FN_RES; 589 break; 590 case 'i': 591 args.pa_flags |= FLAG_FILTER_THREAD_ID; 592 args.pa_tid = strtol(optarg, &end, 0); 593 break; 594 595 case 'k': /* pathname to the kernel */ 596 free(args.pa_kernel); 597 args.pa_kernel = strdup(optarg); 598 if (args.pa_kernel == NULL) 599 errx(EX_SOFTWARE, "ERROR: Out of memory"); 600 args.pa_required |= FLAG_DO_ANALYSIS; 601 args.pa_flags |= FLAG_HAS_KERNELPATH; 602 break; 603 604 case 'L': 605 do_listcounters = 1; 606 break; 607 608 case 'l': /* time duration in seconds */ 609 duration = strtod(optarg, &end); 610 if (*end != '\0' || duration <= 0) 611 errx(EX_USAGE, "ERROR: Illegal duration time " 612 "value \"%s\".", optarg); 613 args.pa_flags |= FLAG_HAS_DURATION; 614 args.pa_duration = duration; 615 break; 616 617 case 'm': 618 args.pa_flags |= FLAG_DO_ANNOTATE; 619 args.pa_plugin = PMCSTAT_PL_ANNOTATE; 620 graphfilename = optarg; 621 break; 622 623 case 'M': /* mapfile */ 624 args.pa_mapfilename = optarg; 625 break; 626 627 case 'N': 628 do_callchain = !do_callchain; 629 args.pa_required |= FLAG_HAS_SAMPLING_PMCS; 630 break; 631 632 case 'p': /* process virtual counting PMC */ 633 case 's': /* system-wide counting PMC */ 634 case 'P': /* process virtual sampling PMC */ 635 case 'S': /* system-wide sampling PMC */ 636 if ((ev = malloc(sizeof(*ev))) == NULL) 637 errx(EX_SOFTWARE, "ERROR: Out of memory."); 638 639 switch (option) { 640 case 'p': ev->ev_mode = PMC_MODE_TC; break; 641 case 's': ev->ev_mode = PMC_MODE_SC; break; 642 case 'P': ev->ev_mode = PMC_MODE_TS; break; 643 case 'S': ev->ev_mode = PMC_MODE_SS; break; 644 } 645 646 if (option == 'P' || option == 'p') { 647 args.pa_flags |= FLAG_HAS_PROCESS_PMCS; 648 args.pa_required |= (FLAG_HAS_COMMANDLINE | 649 FLAG_HAS_TARGET); 650 } 651 652 if (option == 'P' || option == 'S') { 653 args.pa_flags |= FLAG_HAS_SAMPLING_PMCS; 654 args.pa_required |= (FLAG_HAS_PIPE | 655 FLAG_HAS_OUTPUT_LOGFILE); 656 } 657 658 if (option == 'p' || option == 's') 659 args.pa_flags |= FLAG_HAS_COUNTING_PMCS; 660 661 if (option == 's' || option == 'S') 662 args.pa_flags |= FLAG_HAS_SYSTEM_PMCS; 663 664 ev->ev_spec = strdup(optarg); 665 if (ev->ev_spec == NULL) 666 errx(EX_SOFTWARE, "ERROR: Out of memory."); 667 668 if (option == 'S' || option == 'P') 669 ev->ev_count = current_sampling_count ? current_sampling_count : pmc_pmu_sample_rate_get(ev->ev_spec); 670 else 671 ev->ev_count = -1; 672 673 if (option == 'S' || option == 's') 674 ev->ev_cpu = CPU_FFS(&cpumask) - 1; 675 else 676 ev->ev_cpu = PMC_CPU_ANY; 677 678 ev->ev_flags = 0; 679 if (do_callchain) 680 ev->ev_flags |= PMC_F_CALLCHAIN; 681 if (do_descendants) 682 ev->ev_flags |= PMC_F_DESCENDANTS; 683 if (do_logprocexit) 684 ev->ev_flags |= PMC_F_LOG_PROCEXIT; 685 if (do_logproccsw) 686 ev->ev_flags |= PMC_F_LOG_PROCCSW; 687 688 ev->ev_cumulative = use_cumulative_counts; 689 690 ev->ev_saved = 0LL; 691 ev->ev_pmcid = PMC_ID_INVALID; 692 693 /* extract event name */ 694 c = strcspn(optarg, ", \t"); 695 ev->ev_name = malloc(c + 1); 696 if (ev->ev_name == NULL) 697 errx(EX_SOFTWARE, "ERROR: Out of memory."); 698 (void) strncpy(ev->ev_name, optarg, c); 699 *(ev->ev_name + c) = '\0'; 700 701 STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next); 702 703 if (option == 's' || option == 'S') { 704 CPU_CLR(ev->ev_cpu, &cpumask); 705 pmcstat_clone_event_descriptor(ev, &cpumask, &args); 706 CPU_SET(ev->ev_cpu, &cpumask); 707 } 708 709 break; 710 711 case 'n': /* sampling count */ 712 current_sampling_count = strtol(optarg, &end, 0); 713 if (*end != '\0' || current_sampling_count <= 0) 714 errx(EX_USAGE, 715 "ERROR: Illegal count value \"%s\".", 716 optarg); 717 args.pa_required |= FLAG_HAS_SAMPLING_PMCS; 718 break; 719 720 case 'o': /* outputfile */ 721 if (args.pa_printfile != NULL && 722 args.pa_printfile != stdout && 723 args.pa_printfile != stderr) 724 (void) fclose(args.pa_printfile); 725 if ((args.pa_printfile = fopen(optarg, "w")) == NULL) 726 errx(EX_OSERR, 727 "ERROR: cannot open \"%s\" for writing.", 728 optarg); 729 args.pa_flags |= FLAG_DO_PRINT; 730 break; 731 732 case 'O': /* sampling output */ 733 if (args.pa_outputpath) 734 errx(EX_USAGE, 735 "ERROR: option -O may only be specified once."); 736 args.pa_outputpath = optarg; 737 args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE; 738 break; 739 740 case 'q': /* quiet mode */ 741 args.pa_verbosity = 0; 742 break; 743 744 case 'r': /* root FS path */ 745 args.pa_fsroot = optarg; 746 break; 747 748 case 'R': /* read an existing log file */ 749 if (args.pa_inputpath != NULL) 750 errx(EX_USAGE, 751 "ERROR: option -R may only be specified once."); 752 args.pa_inputpath = optarg; 753 if (args.pa_printfile == stderr) 754 args.pa_printfile = stdout; 755 args.pa_flags |= FLAG_READ_LOGFILE; 756 break; 757 758 case 't': /* target pid or process name */ 759 pmcstat_find_targets(optarg); 760 761 args.pa_flags |= FLAG_HAS_TARGET; 762 args.pa_required |= FLAG_HAS_PROCESS_PMCS; 763 break; 764 765 case 'T': /* top mode */ 766 args.pa_flags |= FLAG_DO_TOP; 767 args.pa_plugin = PMCSTAT_PL_CALLGRAPH; 768 args.pa_ctdumpinstr = 0; 769 args.pa_mergepmc = 1; 770 if (args.pa_printfile == stderr) 771 args.pa_printfile = stdout; 772 break; 773 774 case 'u': 775 do_descr = 1; 776 event = optarg; 777 break; 778 case 'U': 779 do_long_descr = 1; 780 event = optarg; 781 break; 782 case 'v': /* verbose */ 783 args.pa_verbosity++; 784 break; 785 786 case 'w': /* wait interval */ 787 interval = strtod(optarg, &end); 788 if (*end != '\0' || interval <= 0) 789 errx(EX_USAGE, 790 "ERROR: Illegal wait interval value \"%s\".", 791 optarg); 792 args.pa_flags |= FLAG_HAS_WAIT_INTERVAL; 793 args.pa_interval = interval; 794 break; 795 796 case 'W': /* toggle LOG_CSW */ 797 do_logproccsw = !do_logproccsw; 798 args.pa_required |= (FLAG_HAS_PROCESS_PMCS | 799 FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE); 800 break; 801 802 case 'z': 803 graphdepth = strtod(optarg, &end); 804 if (*end != '\0' || graphdepth <= 0) 805 errx(EX_USAGE, 806 "ERROR: Illegal callchain depth \"%s\".", 807 optarg); 808 args.pa_graphdepth = graphdepth; 809 args.pa_required |= FLAG_DO_CALLGRAPHS; 810 break; 811 812 case '?': 813 default: 814 pmcstat_show_usage(); 815 break; 816 817 } 818 if ((do_listcounters | do_descr | do_long_descr) && 819 pmc_pmu_enabled() == 0) 820 errx(EX_USAGE, "pmu features not supported on host or hwpmc not loaded"); 821 if (do_listcounters) { 822 pmc_pmu_print_counters(); 823 } else if (do_descr) { 824 pmc_pmu_print_counter_desc(event); 825 } else if (do_long_descr) { 826 pmc_pmu_print_counter_desc_long(event); 827 } 828 if (do_listcounters | do_descr | do_long_descr) 829 exit(0); 830 831 args.pa_argc = (argc -= optind); 832 args.pa_argv = (argv += optind); 833 834 /* If we read from logfile and no specified CPU mask use 835 * the maximum CPU count. 836 */ 837 if ((args.pa_flags & FLAG_READ_LOGFILE) && 838 (args.pa_flags & FLAGS_HAS_CPUMASK) == 0) 839 CPU_FILL(&cpumask); 840 841 args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */ 842 843 if (argc) /* command line present */ 844 args.pa_flags |= FLAG_HAS_COMMANDLINE; 845 846 if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS | 847 FLAG_DO_ANNOTATE | FLAG_DO_TOP)) 848 args.pa_flags |= FLAG_DO_ANALYSIS; 849 850 /* 851 * Check invocation syntax. 852 */ 853 854 /* disallow -O and -R together */ 855 if (args.pa_outputpath && args.pa_inputpath) 856 errx(EX_USAGE, 857 "ERROR: options -O and -R are mutually exclusive."); 858 859 /* disallow -T and -l together */ 860 if ((args.pa_flags & FLAG_HAS_DURATION) && 861 (args.pa_flags & FLAG_DO_TOP)) 862 errx(EX_USAGE, "ERROR: options -T and -l are mutually " 863 "exclusive."); 864 865 /* -a and -m require -R */ 866 if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL) 867 errx(EX_USAGE, "ERROR: option %s requires an input file", 868 args.pa_plugin == PMCSTAT_PL_ANNOTATE ? "-m" : "-a"); 869 870 /* -m option is not allowed combined with -g or -G. */ 871 if (args.pa_flags & FLAG_DO_ANNOTATE && 872 args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS)) 873 errx(EX_USAGE, 874 "ERROR: option -m and -g | -G are mutually exclusive"); 875 876 if (args.pa_flags & FLAG_READ_LOGFILE) { 877 errmsg = NULL; 878 if (args.pa_flags & FLAG_HAS_COMMANDLINE) 879 errmsg = "a command line specification"; 880 else if (args.pa_flags & FLAG_HAS_TARGET) 881 errmsg = "option -t"; 882 else if (!STAILQ_EMPTY(&args.pa_events)) 883 errmsg = "a PMC event specification"; 884 if (errmsg) 885 errx(EX_USAGE, 886 "ERROR: option -R may not be used with %s.", 887 errmsg); 888 } else if (STAILQ_EMPTY(&args.pa_events)) 889 /* All other uses require a PMC spec. */ 890 pmcstat_show_usage(); 891 892 /* check for -t pid without a process PMC spec */ 893 if ((args.pa_required & FLAG_HAS_TARGET) && 894 (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0) 895 errx(EX_USAGE, 896 "ERROR: option -t requires a process mode PMC to be specified." 897 ); 898 899 /* check for process-mode options without a command or -t pid */ 900 if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) && 901 (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0) 902 errx(EX_USAGE, 903 "ERROR: options -d, -E, -p, -P, and -W require a command line or target process." 904 ); 905 906 /* check for -p | -P without a target process of some sort */ 907 if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) && 908 (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0) 909 errx(EX_USAGE, 910 "ERROR: options -P and -p require a target process or a command line." 911 ); 912 913 /* check for process-mode options without a process-mode PMC */ 914 if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) && 915 (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0) 916 errx(EX_USAGE, 917 "ERROR: options -d, -E, and -W require a process mode PMC to be specified." 918 ); 919 920 /* check for -c cpu with no system mode PMCs or logfile. */ 921 if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) && 922 (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 && 923 (args.pa_flags & FLAG_READ_LOGFILE) == 0) 924 errx(EX_USAGE, 925 "ERROR: option -c requires at least one system mode PMC to be specified." 926 ); 927 928 /* check for counting mode options without a counting PMC */ 929 if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) && 930 (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0) 931 errx(EX_USAGE, 932 "ERROR: options -C, -W and -o require at least one counting mode PMC to be specified." 933 ); 934 935 /* check for sampling mode options without a sampling PMC spec */ 936 if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) && 937 (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0) 938 errx(EX_USAGE, 939 "ERROR: options -N, -n and -O require at least one sampling mode PMC to be specified." 940 ); 941 942 /* check if -g/-G/-m/-T are being used correctly */ 943 if ((args.pa_flags & FLAG_DO_ANALYSIS) && 944 !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE))) 945 errx(EX_USAGE, 946 "ERROR: options -g/-G/-m/-T require sampling PMCs or -R to be specified." 947 ); 948 949 /* check if -e was specified without -g */ 950 if ((args.pa_flags & FLAG_DO_WIDE_GPROF_HC) && 951 !(args.pa_flags & FLAG_DO_GPROF)) 952 errx(EX_USAGE, 953 "ERROR: option -e requires gprof mode to be specified." 954 ); 955 956 /* check if -O was spuriously specified */ 957 if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) && 958 (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) 959 errx(EX_USAGE, 960 "ERROR: option -O is used only with options -E, -P, -S and -W." 961 ); 962 963 /* -k kernel path require -g/-G/-m/-T or -R */ 964 if ((args.pa_flags & FLAG_HAS_KERNELPATH) && 965 (args.pa_flags & FLAG_DO_ANALYSIS) == 0 && 966 (args.pa_flags & FLAG_READ_LOGFILE) == 0) 967 errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T."); 968 969 /* -D only applies to gprof output mode (-g) */ 970 if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) && 971 (args.pa_flags & FLAG_DO_GPROF) == 0) 972 errx(EX_USAGE, "ERROR: option -D is only used with -g."); 973 974 /* -M mapfile requires -g or -R */ 975 if (args.pa_mapfilename != NULL && 976 (args.pa_flags & FLAG_DO_GPROF) == 0 && 977 (args.pa_flags & FLAG_READ_LOGFILE) == 0) 978 errx(EX_USAGE, "ERROR: option -M is only used with -g/-R."); 979 980 /* 981 * Disallow textual output of sampling PMCs if counting PMCs 982 * have also been asked for, mostly because the combined output 983 * is difficult to make sense of. 984 */ 985 if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) && 986 (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) && 987 ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0)) 988 errx(EX_USAGE, 989 "ERROR: option -O is required if counting and sampling PMCs are specified together." 990 ); 991 992 /* 993 * Check if 'kerneldir' refers to a file rather than a 994 * directory. If so, use `dirname path` to determine the 995 * kernel directory. 996 */ 997 (void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot, 998 args.pa_kernel); 999 if (stat(buffer, &sb) < 0) 1000 err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"", 1001 buffer); 1002 if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode)) 1003 errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.", 1004 buffer); 1005 if (!S_ISDIR(sb.st_mode)) { 1006 tmp = args.pa_kernel; 1007 args.pa_kernel = strdup(dirname(args.pa_kernel)); 1008 if (args.pa_kernel == NULL) 1009 errx(EX_SOFTWARE, "ERROR: Out of memory"); 1010 free(tmp); 1011 (void) snprintf(buffer, sizeof(buffer), "%s%s", 1012 args.pa_fsroot, args.pa_kernel); 1013 if (stat(buffer, &sb) < 0) 1014 err(EX_OSERR, "ERROR: Cannot stat \"%s\"", 1015 buffer); 1016 if (!S_ISDIR(sb.st_mode)) 1017 errx(EX_USAGE, 1018 "ERROR: \"%s\" is not a directory.", 1019 buffer); 1020 } 1021 1022 /* 1023 * If we have a callgraph be created, select the outputfile. 1024 */ 1025 if (args.pa_flags & FLAG_DO_CALLGRAPHS) { 1026 if (strcmp(graphfilename, "-") == 0) 1027 args.pa_graphfile = args.pa_printfile; 1028 else { 1029 args.pa_graphfile = fopen(graphfilename, "w"); 1030 if (args.pa_graphfile == NULL) 1031 err(EX_OSERR, 1032 "ERROR: cannot open \"%s\" for writing", 1033 graphfilename); 1034 } 1035 } 1036 if (args.pa_flags & FLAG_DO_ANNOTATE) { 1037 args.pa_graphfile = fopen(graphfilename, "w"); 1038 if (args.pa_graphfile == NULL) 1039 err(EX_OSERR, "ERROR: cannot open \"%s\" for writing", 1040 graphfilename); 1041 } 1042 1043 /* if we've been asked to process a log file, skip init */ 1044 if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) { 1045 if (pmc_init() < 0) 1046 err(EX_UNAVAILABLE, 1047 "ERROR: Initialization of the pmc(3) library failed" 1048 ); 1049 1050 if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */ 1051 err(EX_OSERR, 1052 "ERROR: Cannot determine the number of PMCs on CPU %d", 1053 0); 1054 } 1055 1056 /* Allocate a kqueue */ 1057 if ((pmcstat_kq = kqueue()) < 0) 1058 err(EX_OSERR, "ERROR: Cannot allocate kqueue"); 1059 1060 /* Setup the logfile as the source. */ 1061 if (args.pa_flags & FLAG_READ_LOGFILE) { 1062 /* 1063 * Print the log in textual form if we haven't been 1064 * asked to generate profiling information. 1065 */ 1066 if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0) 1067 args.pa_flags |= FLAG_DO_PRINT; 1068 1069 pmcstat_log_initialize_logging(); 1070 rfd = pmcstat_open_log(args.pa_inputpath, 1071 PMCSTAT_OPEN_FOR_READ); 1072 if ((args.pa_logparser = pmclog_open(rfd)) == NULL) 1073 err(EX_OSERR, "ERROR: Cannot create parser"); 1074 if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0) 1075 err(EX_OSERR, "ERROR: fcntl(2) failed"); 1076 EV_SET(&kev, rfd, EVFILT_READ, EV_ADD, 1077 0, 0, NULL); 1078 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0) 1079 err(EX_OSERR, "ERROR: Cannot register kevent"); 1080 } 1081 /* 1082 * Configure the specified log file or setup a default log 1083 * consumer via a pipe. 1084 */ 1085 if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) { 1086 if (args.pa_outputpath) 1087 args.pa_logfd = pmcstat_open_log(args.pa_outputpath, 1088 PMCSTAT_OPEN_FOR_WRITE); 1089 else { 1090 /* 1091 * process the log on the fly by reading it in 1092 * through a pipe. 1093 */ 1094 if (pipe(pipefd) < 0) 1095 err(EX_OSERR, "ERROR: pipe(2) failed"); 1096 1097 if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0) 1098 err(EX_OSERR, "ERROR: fcntl(2) failed"); 1099 1100 EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD, 1101 0, 0, NULL); 1102 1103 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0) 1104 err(EX_OSERR, "ERROR: Cannot register kevent"); 1105 1106 args.pa_logfd = pipefd[WRITEPIPEFD]; 1107 1108 args.pa_flags |= FLAG_HAS_PIPE; 1109 if ((args.pa_flags & FLAG_DO_TOP) == 0) 1110 args.pa_flags |= FLAG_DO_PRINT; 1111 args.pa_logparser = pmclog_open(pipefd[READPIPEFD]); 1112 } 1113 1114 if (pmc_configure_logfile(args.pa_logfd) < 0) 1115 err(EX_OSERR, "ERROR: Cannot configure log file"); 1116 } 1117 1118 /* remember to check for driver errors if we are sampling or logging */ 1119 check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) || 1120 (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE); 1121 1122 /* 1123 if (args.pa_flags & FLAG_READ_LOGFILE) { 1124 * Allocate PMCs. 1125 */ 1126 1127 STAILQ_FOREACH(ev, &args.pa_events, ev_next) { 1128 if (pmc_allocate(ev->ev_spec, ev->ev_mode, 1129 ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0) 1130 err(EX_OSERR, 1131 "ERROR: Cannot allocate %s-mode pmc with specification \"%s\"", 1132 PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 1133 "system" : "process", ev->ev_spec); 1134 1135 if (PMC_IS_SAMPLING_MODE(ev->ev_mode) && 1136 pmc_set(ev->ev_pmcid, ev->ev_count) < 0) 1137 err(EX_OSERR, 1138 "ERROR: Cannot set sampling count for PMC \"%s\"", 1139 ev->ev_name); 1140 } 1141 1142 /* compute printout widths */ 1143 STAILQ_FOREACH(ev, &args.pa_events, ev_next) { 1144 int counter_width; 1145 int display_width; 1146 int header_width; 1147 1148 (void) pmc_width(ev->ev_pmcid, &counter_width); 1149 header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */ 1150 display_width = (int) floor(counter_width / 3.32193) + 1; 1151 1152 if (PMC_IS_SYSTEM_MODE(ev->ev_mode)) 1153 header_width += 3; /* 2 digit CPU number + '/' */ 1154 1155 if (header_width > display_width) { 1156 ev->ev_fieldskip = 0; 1157 ev->ev_fieldwidth = header_width; 1158 } else { 1159 ev->ev_fieldskip = display_width - 1160 header_width; 1161 ev->ev_fieldwidth = display_width; 1162 } 1163 } 1164 1165 /* 1166 * If our output is being set to a terminal, register a handler 1167 * for window size changes. 1168 */ 1169 1170 if (isatty(fileno(args.pa_printfile))) { 1171 1172 if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0) 1173 err(EX_OSERR, "ERROR: Cannot determine window size"); 1174 1175 pmcstat_displayheight = ws.ws_row - 1; 1176 pmcstat_displaywidth = ws.ws_col - 1; 1177 1178 EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); 1179 1180 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0) 1181 err(EX_OSERR, 1182 "ERROR: Cannot register kevent for SIGWINCH"); 1183 1184 args.pa_toptty = 1; 1185 } 1186 1187 /* 1188 * Listen to key input in top mode. 1189 */ 1190 if (args.pa_flags & FLAG_DO_TOP) { 1191 EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL); 1192 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0) 1193 err(EX_OSERR, "ERROR: Cannot register kevent"); 1194 } 1195 1196 EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); 1197 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0) 1198 err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT"); 1199 1200 EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); 1201 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0) 1202 err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO"); 1203 1204 /* 1205 * An exec() failure of a forked child is signalled by the 1206 * child sending the parent a SIGCHLD. We don't register an 1207 * actual signal handler for SIGCHLD, but instead use our 1208 * kqueue to pick up the signal. 1209 */ 1210 EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); 1211 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0) 1212 err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD"); 1213 1214 /* 1215 * Setup a timer if we have counting mode PMCs needing to be printed or 1216 * top mode plugin is active. 1217 */ 1218 if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) && 1219 (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) || 1220 (args.pa_flags & FLAG_DO_TOP)) { 1221 EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0, 1222 args.pa_interval * 1000, NULL); 1223 1224 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0) 1225 err(EX_OSERR, 1226 "ERROR: Cannot register kevent for timer"); 1227 } 1228 1229 /* 1230 * Setup a duration timer if we have sampling mode PMCs and 1231 * a duration time is set 1232 */ 1233 if ((args.pa_flags & FLAG_HAS_SAMPLING_PMCS) && 1234 (args.pa_flags & FLAG_HAS_DURATION)) { 1235 EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0, 1236 args.pa_duration * 1000, NULL); 1237 1238 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0) 1239 err(EX_OSERR, "ERROR: Cannot register kevent for " 1240 "time duration"); 1241 } 1242 1243 /* attach PMCs to the target process, starting it if specified */ 1244 if (args.pa_flags & FLAG_HAS_COMMANDLINE) 1245 pmcstat_create_process(pmcstat_sockpair, &args, pmcstat_kq); 1246 1247 if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0) 1248 err(EX_OSERR, "ERROR: Cannot retrieve driver statistics"); 1249 1250 /* Attach process pmcs to the target process. */ 1251 if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) { 1252 if (SLIST_EMPTY(&args.pa_targets)) 1253 errx(EX_DATAERR, 1254 "ERROR: No matching target processes."); 1255 if (args.pa_flags & FLAG_HAS_PROCESS_PMCS) 1256 pmcstat_attach_pmcs(&args); 1257 1258 if (pmcstat_kvm) { 1259 kvm_close(pmcstat_kvm); 1260 pmcstat_kvm = NULL; 1261 } 1262 } 1263 1264 /* start the pmcs */ 1265 pmcstat_start_pmcs(); 1266 1267 /* start the (commandline) process if needed */ 1268 if (args.pa_flags & FLAG_HAS_COMMANDLINE) 1269 pmcstat_start_process(pmcstat_sockpair); 1270 1271 /* initialize logging */ 1272 pmcstat_log_initialize_logging(); 1273 1274 /* Handle SIGINT using the kqueue loop */ 1275 sa.sa_handler = SIG_IGN; 1276 sa.sa_flags = 0; 1277 (void) sigemptyset(&sa.sa_mask); 1278 1279 if (sigaction(SIGINT, &sa, NULL) < 0) 1280 err(EX_OSERR, "ERROR: Cannot install signal handler"); 1281 1282 /* 1283 * Setup the top mode display. 1284 */ 1285 if (args.pa_flags & FLAG_DO_TOP) { 1286 args.pa_flags &= ~FLAG_DO_PRINT; 1287 1288 if (args.pa_toptty) { 1289 /* 1290 * Init ncurses. 1291 */ 1292 initscr(); 1293 if(has_colors() == TRUE) { 1294 args.pa_topcolor = 1; 1295 start_color(); 1296 use_default_colors(); 1297 pair_content(0, &cf, &cb); 1298 init_pair(1, COLOR_RED, cb); 1299 init_pair(2, COLOR_YELLOW, cb); 1300 init_pair(3, COLOR_GREEN, cb); 1301 } 1302 cbreak(); 1303 noecho(); 1304 nonl(); 1305 nodelay(stdscr, 1); 1306 intrflush(stdscr, FALSE); 1307 keypad(stdscr, TRUE); 1308 clear(); 1309 /* Get terminal width / height with ncurses. */ 1310 getmaxyx(stdscr, 1311 pmcstat_displayheight, pmcstat_displaywidth); 1312 pmcstat_displayheight--; pmcstat_displaywidth--; 1313 atexit(pmcstat_topexit); 1314 } 1315 } 1316 1317 /* 1318 * loop till either the target process (if any) exits, or we 1319 * are killed by a SIGINT or we reached the time duration. 1320 */ 1321 runstate = PMCSTAT_RUNNING; 1322 do_print = do_read = 0; 1323 do { 1324 if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) { 1325 if (errno != EINTR) 1326 err(EX_OSERR, "ERROR: kevent failed"); 1327 else 1328 continue; 1329 } 1330 1331 if (kev.flags & EV_ERROR) 1332 errc(EX_OSERR, kev.data, "ERROR: kevent failed"); 1333 1334 switch (kev.filter) { 1335 case EVFILT_PROC: /* target has exited */ 1336 runstate = pmcstat_close_log(&args); 1337 do_print = 1; 1338 break; 1339 1340 case EVFILT_READ: /* log file data is present */ 1341 if (kev.ident == (unsigned)fileno(stdin) && 1342 (args.pa_flags & FLAG_DO_TOP)) { 1343 if (pmcstat_keypress_log()) 1344 runstate = pmcstat_close_log(&args); 1345 } else { 1346 do_read = 0; 1347 runstate = pmcstat_process_log(); 1348 } 1349 break; 1350 1351 case EVFILT_SIGNAL: 1352 if (kev.ident == SIGCHLD) { 1353 /* 1354 * The child process sends us a 1355 * SIGCHLD if its exec() failed. We 1356 * wait for it to exit and then exit 1357 * ourselves. 1358 */ 1359 (void) wait(&c); 1360 runstate = PMCSTAT_FINISHED; 1361 } else if (kev.ident == SIGIO) { 1362 /* 1363 * We get a SIGIO if a PMC loses all 1364 * of its targets, or if logfile 1365 * writes encounter an error. 1366 */ 1367 runstate = pmcstat_close_log(&args); 1368 do_print = 1; /* print PMCs at exit */ 1369 } else if (kev.ident == SIGINT) { 1370 /* Kill the child process if we started it */ 1371 if (args.pa_flags & FLAG_HAS_COMMANDLINE) 1372 pmcstat_kill_process(); 1373 runstate = pmcstat_close_log(&args); 1374 } else if (kev.ident == SIGWINCH) { 1375 if (ioctl(fileno(args.pa_printfile), 1376 TIOCGWINSZ, &ws) < 0) 1377 err(EX_OSERR, 1378 "ERROR: Cannot determine window size"); 1379 pmcstat_displayheight = ws.ws_row - 1; 1380 pmcstat_displaywidth = ws.ws_col - 1; 1381 } else 1382 assert(0); 1383 1384 break; 1385 1386 case EVFILT_TIMER: 1387 /* time duration reached, exit */ 1388 if (args.pa_flags & FLAG_HAS_DURATION) { 1389 runstate = PMCSTAT_FINISHED; 1390 break; 1391 } 1392 /* print out counting PMCs */ 1393 if ((args.pa_flags & FLAG_DO_TOP) && 1394 (args.pa_flags & FLAG_HAS_PIPE) && 1395 pmc_flush_logfile() == 0) 1396 do_read = 1; 1397 do_print = 1; 1398 break; 1399 1400 } 1401 1402 if (do_print && !do_read) { 1403 if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) { 1404 pmcstat_print_pmcs(); 1405 if (runstate == PMCSTAT_FINISHED && 1406 /* final newline */ 1407 (args.pa_flags & FLAG_DO_PRINT) == 0) 1408 (void) fprintf(args.pa_printfile, "\n"); 1409 } 1410 if (args.pa_flags & FLAG_DO_TOP) 1411 pmcstat_display_log(); 1412 do_print = 0; 1413 } 1414 1415 } while (runstate != PMCSTAT_FINISHED); 1416 1417 if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) { 1418 pmcstat_topexit(); 1419 args.pa_toptty = 0; 1420 } 1421 1422 /* flush any pending log entries */ 1423 if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE)) 1424 pmc_close_logfile(); 1425 1426 pmcstat_cleanup(); 1427 1428 /* check if the driver lost any samples or events */ 1429 if (check_driver_stats) { 1430 if (pmc_get_driver_stats(&ds_end) < 0) 1431 err(EX_OSERR, 1432 "ERROR: Cannot retrieve driver statistics"); 1433 if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull && 1434 args.pa_verbosity > 0) 1435 warnx( 1436 "WARNING: sampling was paused at least %u time%s.\n" 1437 "Please consider tuning the \"kern.hwpmc.nsamples\" tunable.", 1438 ds_end.pm_intr_bufferfull - 1439 ds_start.pm_intr_bufferfull, 1440 ((ds_end.pm_intr_bufferfull - 1441 ds_start.pm_intr_bufferfull) != 1) ? "s" : "" 1442 ); 1443 if (ds_start.pm_buffer_requests_failed != 1444 ds_end.pm_buffer_requests_failed && 1445 args.pa_verbosity > 0) 1446 warnx( 1447 "WARNING: at least %u event%s were discarded while running.\n" 1448 "Please consider tuning the \"kern.hwpmc.nbuffers\" tunable.", 1449 ds_end.pm_buffer_requests_failed - 1450 ds_start.pm_buffer_requests_failed, 1451 ((ds_end.pm_buffer_requests_failed - 1452 ds_start.pm_buffer_requests_failed) != 1) ? "s" : "" 1453 ); 1454 } 1455 1456 exit(EX_OK); 1457 } 1458