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