xref: /freebsd/usr.sbin/pmcstat/pmcstat.c (revision 224e0c2f)
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(&reg, spec, REG_EXTENDED|REG_NOSUB)) != 0) {
206 		regerror(rv, &reg, 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(&reg, kp->ki_comm, 1, &regmatch, 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, &reg, errbuf, sizeof(errbuf));
219 			errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s",
220 			    errbuf);
221 		}
222 	}
223 
224 	regfree(&reg);
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 -M file\t print executable/gmon file map to \"file\"\n"
369 	    "\t -N\t\t (toggle) capture callchains\n"
370 	    "\t -O file\t send log output to \"file\"\n"
371 	    "\t -P spec\t allocate a process-private sampling PMC\n"
372 	    "\t -R file\t read events from \"file\"\n"
373 	    "\t -S spec\t allocate a system-wide sampling PMC\n"
374 	    "\t -T\t\t start in top mode\n"
375 	    "\t -W\t\t (toggle) show counts per context switch\n"
376 	    "\t -a file\t print sampled PCs and callgraph to \"file\"\n"
377 	    "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n"
378 	    "\t -d\t\t (toggle) track descendants\n"
379 	    "\t -e\t\t use wide history counter for gprof(1) output\n"
380 	    "\t -f spec\t pass \"spec\" to as plugin option\n"
381 	    "\t -g\t\t produce gprof(1) compatible profiles\n"
382 	    "\t -k dir\t\t set the path to the kernel\n"
383 	    "\t -l secs\t set duration time\n"
384 	    "\t -m file\t print sampled PCs to \"file\"\n"
385 	    "\t -n rate\t set sampling rate\n"
386 	    "\t -o file\t send print output to \"file\"\n"
387 	    "\t -p spec\t allocate a process-private counting PMC\n"
388 	    "\t -q\t\t suppress verbosity\n"
389 	    "\t -r fsroot\t specify FS root directory\n"
390 	    "\t -s spec\t allocate a system-wide counting PMC\n"
391 	    "\t -t process-spec attach to running processes matching "
392 		"\"process-spec\"\n"
393 	    "\t -v\t\t increase verbosity\n"
394 	    "\t -w secs\t set printing time interval\n"
395 	    "\t -z depth\t limit callchain display depth"
396 	);
397 }
398 
399 /*
400  * At exit handler for top mode
401  */
402 
403 void
404 pmcstat_topexit(void)
405 {
406 	if (!args.pa_toptty)
407 		return;
408 
409 	/*
410 	 * Shutdown ncurses.
411 	 */
412 	clrtoeol();
413 	refresh();
414 	endwin();
415 }
416 
417 /*
418  * Main
419  */
420 
421 int
422 main(int argc, char **argv)
423 {
424 	cpuset_t cpumask, rootmask;
425 	double interval;
426 	double duration;
427 	int option, npmc;
428 	int c, check_driver_stats, current_sampling_count;
429 	int do_callchain, do_descendants, do_logproccsw, do_logprocexit;
430 	int do_print, do_read;
431 	size_t len;
432 	int graphdepth;
433 	int pipefd[2], rfd;
434 	int use_cumulative_counts;
435 	short cf, cb;
436 	char *end, *tmp;
437 	const char *errmsg, *graphfilename;
438 	enum pmcstat_state runstate;
439 	struct pmc_driverstats ds_start, ds_end;
440 	struct pmcstat_ev *ev;
441 	struct sigaction sa;
442 	struct kevent kev;
443 	struct winsize ws;
444 	struct stat sb;
445 	char buffer[PATH_MAX];
446 
447 	check_driver_stats      = 0;
448 	current_sampling_count  = DEFAULT_SAMPLE_COUNT;
449 	do_callchain		= 1;
450 	do_descendants          = 0;
451 	do_logproccsw           = 0;
452 	do_logprocexit          = 0;
453 	use_cumulative_counts   = 0;
454 	graphfilename		= "-";
455 	args.pa_required	= 0;
456 	args.pa_flags		= 0;
457 	args.pa_verbosity	= 1;
458 	args.pa_logfd		= -1;
459 	args.pa_fsroot		= "";
460 	args.pa_samplesdir	= ".";
461 	args.pa_printfile	= stderr;
462 	args.pa_graphdepth	= DEFAULT_CALLGRAPH_DEPTH;
463 	args.pa_graphfile	= NULL;
464 	args.pa_interval	= DEFAULT_WAIT_INTERVAL;
465 	args.pa_mapfilename	= NULL;
466 	args.pa_inputpath	= NULL;
467 	args.pa_outputpath	= NULL;
468 	args.pa_pplugin		= PMCSTAT_PL_NONE;
469 	args.pa_plugin		= PMCSTAT_PL_NONE;
470 	args.pa_ctdumpinstr	= 1;
471 	args.pa_topmode		= PMCSTAT_TOP_DELTA;
472 	args.pa_toptty		= 0;
473 	args.pa_topcolor	= 0;
474 	args.pa_mergepmc	= 0;
475 	args.pa_duration	= 0.0;
476 	STAILQ_INIT(&args.pa_events);
477 	SLIST_INIT(&args.pa_targets);
478 	bzero(&ds_start, sizeof(ds_start));
479 	bzero(&ds_end, sizeof(ds_end));
480 	ev = NULL;
481 	CPU_ZERO(&cpumask);
482 
483 	/* Default to using the running system kernel. */
484 	len = 0;
485 	if (sysctlbyname("kern.bootfile", NULL, &len, NULL, 0) == -1)
486 		err(EX_OSERR, "ERROR: Cannot determine path of running kernel");
487 	args.pa_kernel = malloc(len);
488 	if (args.pa_kernel == NULL)
489 		errx(EX_SOFTWARE, "ERROR: Out of memory.");
490 	if (sysctlbyname("kern.bootfile", args.pa_kernel, &len, NULL, 0) == -1)
491 		err(EX_OSERR, "ERROR: Cannot determine path of running kernel");
492 
493 	/*
494 	 * The initial CPU mask specifies the root mask of this process
495 	 * which is usually all CPUs in the system.
496 	 */
497 	if (cpuset_getaffinity(CPU_LEVEL_ROOT, CPU_WHICH_PID, -1,
498 	    sizeof(rootmask), &rootmask) == -1)
499 		err(EX_OSERR, "ERROR: Cannot determine the root set of CPUs");
500 	CPU_COPY(&rootmask, &cpumask);
501 
502 	while ((option = getopt(argc, argv,
503 	    "CD:EF:G:M:NO:P:R:S:TWa:c:def:gk:l:m:n:o:p:qr:s:t:vw:z:")) != -1)
504 		switch (option) {
505 		case 'a':	/* Annotate + callgraph */
506 			args.pa_flags |= FLAG_DO_ANNOTATE;
507 			args.pa_plugin = PMCSTAT_PL_ANNOTATE_CG;
508 			graphfilename  = optarg;
509 			break;
510 
511 		case 'C':	/* cumulative values */
512 			use_cumulative_counts = !use_cumulative_counts;
513 			args.pa_required |= FLAG_HAS_COUNTING_PMCS;
514 			break;
515 
516 		case 'c':	/* CPU */
517 			if (optarg[0] == '*' && optarg[1] == '\0')
518 				CPU_COPY(&rootmask, &cpumask);
519 			else
520 				pmcstat_get_cpumask(optarg, &cpumask);
521 
522 			args.pa_flags	 |= FLAGS_HAS_CPUMASK;
523 			args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
524 			break;
525 
526 		case 'D':
527 			if (stat(optarg, &sb) < 0)
528 				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
529 				    optarg);
530 			if (!S_ISDIR(sb.st_mode))
531 				errx(EX_USAGE,
532 				    "ERROR: \"%s\" is not a directory.",
533 				    optarg);
534 			args.pa_samplesdir = optarg;
535 			args.pa_flags     |= FLAG_HAS_SAMPLESDIR;
536 			args.pa_required  |= FLAG_DO_GPROF;
537 			break;
538 
539 		case 'd':	/* toggle descendents */
540 			do_descendants = !do_descendants;
541 			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
542 			break;
543 
544 		case 'e':	/* wide gprof metrics */
545 			args.pa_flags |= FLAG_DO_WIDE_GPROF_HC;
546 			break;
547 
548 		case 'F':	/* produce a system-wide calltree */
549 			args.pa_flags |= FLAG_DO_CALLGRAPHS;
550 			args.pa_plugin = PMCSTAT_PL_CALLTREE;
551 			graphfilename = optarg;
552 			break;
553 
554 		case 'f':	/* plugins options */
555 			if (args.pa_plugin == PMCSTAT_PL_NONE)
556 				err(EX_USAGE, "ERROR: Need -g/-G/-m/-T.");
557 			pmcstat_pluginconfigure_log(optarg);
558 			break;
559 
560 		case 'G':	/* produce a system-wide callgraph */
561 			args.pa_flags |= FLAG_DO_CALLGRAPHS;
562 			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
563 			graphfilename = optarg;
564 			break;
565 
566 		case 'g':	/* produce gprof compatible profiles */
567 			args.pa_flags |= FLAG_DO_GPROF;
568 			args.pa_pplugin = PMCSTAT_PL_CALLGRAPH;
569 			args.pa_plugin	= PMCSTAT_PL_GPROF;
570 			break;
571 
572 		case 'k':	/* pathname to the kernel */
573 			free(args.pa_kernel);
574 			args.pa_kernel = strdup(optarg);
575 			if (args.pa_kernel == NULL)
576 				errx(EX_SOFTWARE, "ERROR: Out of memory");
577 			args.pa_required |= FLAG_DO_ANALYSIS;
578 			args.pa_flags    |= FLAG_HAS_KERNELPATH;
579 			break;
580 
581 		case 'l':	/* time duration in seconds */
582 			duration = strtod(optarg, &end);
583 			if (*end != '\0' || duration <= 0)
584 				errx(EX_USAGE, "ERROR: Illegal duration time "
585 				    "value \"%s\".", optarg);
586 			args.pa_flags |= FLAG_HAS_DURATION;
587 			args.pa_duration = duration;
588 			break;
589 
590 		case 'm':
591 			args.pa_flags |= FLAG_DO_ANNOTATE;
592 			args.pa_plugin = PMCSTAT_PL_ANNOTATE;
593 			graphfilename  = optarg;
594 			break;
595 
596 		case 'E':	/* log process exit */
597 			do_logprocexit = !do_logprocexit;
598 			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
599 			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
600 			break;
601 
602 		case 'M':	/* mapfile */
603 			args.pa_mapfilename = optarg;
604 			break;
605 
606 		case 'N':
607 			do_callchain = !do_callchain;
608 			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
609 			break;
610 
611 		case 'p':	/* process virtual counting PMC */
612 		case 's':	/* system-wide counting PMC */
613 		case 'P':	/* process virtual sampling PMC */
614 		case 'S':	/* system-wide sampling PMC */
615 			if ((ev = malloc(sizeof(*ev))) == NULL)
616 				errx(EX_SOFTWARE, "ERROR: Out of memory.");
617 
618 			switch (option) {
619 			case 'p': ev->ev_mode = PMC_MODE_TC; break;
620 			case 's': ev->ev_mode = PMC_MODE_SC; break;
621 			case 'P': ev->ev_mode = PMC_MODE_TS; break;
622 			case 'S': ev->ev_mode = PMC_MODE_SS; break;
623 			}
624 
625 			if (option == 'P' || option == 'p') {
626 				args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
627 				args.pa_required |= (FLAG_HAS_COMMANDLINE |
628 				    FLAG_HAS_TARGET);
629 			}
630 
631 			if (option == 'P' || option == 'S') {
632 				args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
633 				args.pa_required |= (FLAG_HAS_PIPE |
634 				    FLAG_HAS_OUTPUT_LOGFILE);
635 			}
636 
637 			if (option == 'p' || option == 's')
638 				args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
639 
640 			if (option == 's' || option == 'S')
641 				args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
642 
643 			ev->ev_spec = strdup(optarg);
644 			if (ev->ev_spec == NULL)
645 				errx(EX_SOFTWARE, "ERROR: Out of memory.");
646 
647 			if (option == 'S' || option == 'P')
648 				ev->ev_count = current_sampling_count;
649 			else
650 				ev->ev_count = -1;
651 
652 			if (option == 'S' || option == 's')
653 				ev->ev_cpu = CPU_FFS(&cpumask) - 1;
654 			else
655 				ev->ev_cpu = PMC_CPU_ANY;
656 
657 			ev->ev_flags = 0;
658 			if (do_callchain)
659 				ev->ev_flags |= PMC_F_CALLCHAIN;
660 			if (do_descendants)
661 				ev->ev_flags |= PMC_F_DESCENDANTS;
662 			if (do_logprocexit)
663 				ev->ev_flags |= PMC_F_LOG_PROCEXIT;
664 			if (do_logproccsw)
665 				ev->ev_flags |= PMC_F_LOG_PROCCSW;
666 
667 			ev->ev_cumulative  = use_cumulative_counts;
668 
669 			ev->ev_saved = 0LL;
670 			ev->ev_pmcid = PMC_ID_INVALID;
671 
672 			/* extract event name */
673 			c = strcspn(optarg, ", \t");
674 			ev->ev_name = malloc(c + 1);
675 			if (ev->ev_name == NULL)
676 				errx(EX_SOFTWARE, "ERROR: Out of memory.");
677 			(void) strncpy(ev->ev_name, optarg, c);
678 			*(ev->ev_name + c) = '\0';
679 
680 			STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
681 
682 			if (option == 's' || option == 'S') {
683 				CPU_CLR(ev->ev_cpu, &cpumask);
684 				pmcstat_clone_event_descriptor(ev, &cpumask, &args);
685 				CPU_SET(ev->ev_cpu, &cpumask);
686 			}
687 
688 			break;
689 
690 		case 'n':	/* sampling count */
691 			current_sampling_count = strtol(optarg, &end, 0);
692 			if (*end != '\0' || current_sampling_count <= 0)
693 				errx(EX_USAGE,
694 				    "ERROR: Illegal count value \"%s\".",
695 				    optarg);
696 			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
697 			break;
698 
699 		case 'o':	/* outputfile */
700 			if (args.pa_printfile != NULL &&
701 			    args.pa_printfile != stdout &&
702 			    args.pa_printfile != stderr)
703 				(void) fclose(args.pa_printfile);
704 			if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
705 				errx(EX_OSERR,
706 				    "ERROR: cannot open \"%s\" for writing.",
707 				    optarg);
708 			args.pa_flags |= FLAG_DO_PRINT;
709 			break;
710 
711 		case 'O':	/* sampling output */
712 			if (args.pa_outputpath)
713 				errx(EX_USAGE,
714 "ERROR: option -O may only be specified once.");
715 			args.pa_outputpath = optarg;
716 			args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
717 			break;
718 
719 		case 'q':	/* quiet mode */
720 			args.pa_verbosity = 0;
721 			break;
722 
723 		case 'r':	/* root FS path */
724 			args.pa_fsroot = optarg;
725 			break;
726 
727 		case 'R':	/* read an existing log file */
728 			if (args.pa_inputpath != NULL)
729 				errx(EX_USAGE,
730 "ERROR: option -R may only be specified once.");
731 			args.pa_inputpath = optarg;
732 			if (args.pa_printfile == stderr)
733 				args.pa_printfile = stdout;
734 			args.pa_flags |= FLAG_READ_LOGFILE;
735 			break;
736 
737 		case 't':	/* target pid or process name */
738 			pmcstat_find_targets(optarg);
739 
740 			args.pa_flags |= FLAG_HAS_TARGET;
741 			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
742 			break;
743 
744 		case 'T':	/* top mode */
745 			args.pa_flags |= FLAG_DO_TOP;
746 			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
747 			args.pa_ctdumpinstr = 0;
748 			args.pa_mergepmc = 1;
749 			if (args.pa_printfile == stderr)
750 				args.pa_printfile = stdout;
751 			break;
752 
753 		case 'v':	/* verbose */
754 			args.pa_verbosity++;
755 			break;
756 
757 		case 'w':	/* wait interval */
758 			interval = strtod(optarg, &end);
759 			if (*end != '\0' || interval <= 0)
760 				errx(EX_USAGE,
761 "ERROR: Illegal wait interval value \"%s\".",
762 				    optarg);
763 			args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
764 			args.pa_interval = interval;
765 			break;
766 
767 		case 'W':	/* toggle LOG_CSW */
768 			do_logproccsw = !do_logproccsw;
769 			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
770 			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
771 			break;
772 
773 		case 'z':
774 			graphdepth = strtod(optarg, &end);
775 			if (*end != '\0' || graphdepth <= 0)
776 				errx(EX_USAGE,
777 				    "ERROR: Illegal callchain depth \"%s\".",
778 				    optarg);
779 			args.pa_graphdepth = graphdepth;
780 			args.pa_required |= FLAG_DO_CALLGRAPHS;
781 			break;
782 
783 		case '?':
784 		default:
785 			pmcstat_show_usage();
786 			break;
787 
788 		}
789 
790 	args.pa_argc = (argc -= optind);
791 	args.pa_argv = (argv += optind);
792 
793 	/* If we read from logfile and no specified CPU mask use
794 	 * the maximum CPU count.
795 	 */
796 	if ((args.pa_flags & FLAG_READ_LOGFILE) &&
797 	    (args.pa_flags & FLAGS_HAS_CPUMASK) == 0)
798 		CPU_FILL(&cpumask);
799 
800 	args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
801 
802 	if (argc)	/* command line present */
803 		args.pa_flags |= FLAG_HAS_COMMANDLINE;
804 
805 	if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
806 	    FLAG_DO_ANNOTATE | FLAG_DO_TOP))
807 		args.pa_flags |= FLAG_DO_ANALYSIS;
808 
809 	/*
810 	 * Check invocation syntax.
811 	 */
812 
813 	/* disallow -O and -R together */
814 	if (args.pa_outputpath && args.pa_inputpath)
815 		errx(EX_USAGE,
816 		    "ERROR: options -O and -R are mutually exclusive.");
817 
818 	/* disallow -T and -l together */
819 	if ((args.pa_flags & FLAG_HAS_DURATION) &&
820 	    (args.pa_flags & FLAG_DO_TOP))
821 		errx(EX_USAGE, "ERROR: options -T and -l are mutually "
822 		    "exclusive.");
823 
824 	/* -a and -m require -R */
825 	if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
826 		errx(EX_USAGE, "ERROR: option %s requires an input file",
827 		    args.pa_plugin == PMCSTAT_PL_ANNOTATE ? "-m" : "-a");
828 
829 	/* -m option is not allowed combined with -g or -G. */
830 	if (args.pa_flags & FLAG_DO_ANNOTATE &&
831 	    args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
832 		errx(EX_USAGE,
833 		    "ERROR: option -m and -g | -G are mutually exclusive");
834 
835 	if (args.pa_flags & FLAG_READ_LOGFILE) {
836 		errmsg = NULL;
837 		if (args.pa_flags & FLAG_HAS_COMMANDLINE)
838 			errmsg = "a command line specification";
839 		else if (args.pa_flags & FLAG_HAS_TARGET)
840 			errmsg = "option -t";
841 		else if (!STAILQ_EMPTY(&args.pa_events))
842 			errmsg = "a PMC event specification";
843 		if (errmsg)
844 			errx(EX_USAGE,
845 			    "ERROR: option -R may not be used with %s.",
846 			    errmsg);
847 	} else if (STAILQ_EMPTY(&args.pa_events))
848 		/* All other uses require a PMC spec. */
849 		pmcstat_show_usage();
850 
851 	/* check for -t pid without a process PMC spec */
852 	if ((args.pa_required & FLAG_HAS_TARGET) &&
853 	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
854 		errx(EX_USAGE,
855 "ERROR: option -t requires a process mode PMC to be specified."
856 		    );
857 
858 	/* check for process-mode options without a command or -t pid */
859 	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
860 	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
861 		errx(EX_USAGE,
862 "ERROR: options -d, -E, -p, -P, and -W require a command line or target process."
863 		    );
864 
865 	/* check for -p | -P without a target process of some sort */
866 	if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
867 	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
868 		errx(EX_USAGE,
869 "ERROR: options -P and -p require a target process or a command line."
870 		    );
871 
872 	/* check for process-mode options without a process-mode PMC */
873 	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
874 	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
875 		errx(EX_USAGE,
876 "ERROR: options -d, -E, and -W require a process mode PMC to be specified."
877 		    );
878 
879 	/* check for -c cpu with no system mode PMCs or logfile. */
880 	if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
881 	    (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
882 	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
883 		errx(EX_USAGE,
884 "ERROR: option -c requires at least one system mode PMC to be specified."
885 		    );
886 
887 	/* check for counting mode options without a counting PMC */
888 	if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
889 	    (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
890 		errx(EX_USAGE,
891 "ERROR: options -C, -W and -o require at least one counting mode PMC to be specified."
892 		    );
893 
894 	/* check for sampling mode options without a sampling PMC spec */
895 	if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
896 	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
897 		errx(EX_USAGE,
898 "ERROR: options -N, -n and -O require at least one sampling mode PMC to be specified."
899 		    );
900 
901 	/* check if -g/-G/-m/-T are being used correctly */
902 	if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
903 	    !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
904 		errx(EX_USAGE,
905 "ERROR: options -g/-G/-m/-T require sampling PMCs or -R to be specified."
906 		    );
907 
908 	/* check if -e was specified without -g */
909 	if ((args.pa_flags & FLAG_DO_WIDE_GPROF_HC) &&
910 	    !(args.pa_flags & FLAG_DO_GPROF))
911 		errx(EX_USAGE,
912 "ERROR: option -e requires gprof mode to be specified."
913 		    );
914 
915 	/* check if -O was spuriously specified */
916 	if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
917 	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
918 		errx(EX_USAGE,
919 "ERROR: option -O is used only with options -E, -P, -S and -W."
920 		    );
921 
922 	/* -k kernel path require -g/-G/-m/-T or -R */
923 	if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
924 	    (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
925 	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
926 	    errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
927 
928 	/* -D only applies to gprof output mode (-g) */
929 	if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
930 	    (args.pa_flags & FLAG_DO_GPROF) == 0)
931 	    errx(EX_USAGE, "ERROR: option -D is only used with -g.");
932 
933 	/* -M mapfile requires -g or -R */
934 	if (args.pa_mapfilename != NULL &&
935 	    (args.pa_flags & FLAG_DO_GPROF) == 0 &&
936 	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
937 	    errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
938 
939 	/*
940 	 * Disallow textual output of sampling PMCs if counting PMCs
941 	 * have also been asked for, mostly because the combined output
942 	 * is difficult to make sense of.
943 	 */
944 	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
945 	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
946 	    ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
947 		errx(EX_USAGE,
948 "ERROR: option -O is required if counting and sampling PMCs are specified together."
949 		    );
950 
951 	/*
952 	 * Check if 'kerneldir' refers to a file rather than a
953 	 * directory.  If so, use `dirname path` to determine the
954 	 * kernel directory.
955 	 */
956 	(void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
957 	    args.pa_kernel);
958 	if (stat(buffer, &sb) < 0)
959 		err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
960 		    buffer);
961 	if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
962 		errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
963 		    buffer);
964 	if (!S_ISDIR(sb.st_mode)) {
965 		tmp = args.pa_kernel;
966 		args.pa_kernel = strdup(dirname(args.pa_kernel));
967 		if (args.pa_kernel == NULL)
968 			errx(EX_SOFTWARE, "ERROR: Out of memory");
969 		free(tmp);
970 		(void) snprintf(buffer, sizeof(buffer), "%s%s",
971 		    args.pa_fsroot, args.pa_kernel);
972 		if (stat(buffer, &sb) < 0)
973 			err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
974 			    buffer);
975 		if (!S_ISDIR(sb.st_mode))
976 			errx(EX_USAGE,
977 			    "ERROR: \"%s\" is not a directory.",
978 			    buffer);
979 	}
980 
981 	/*
982 	 * If we have a callgraph be created, select the outputfile.
983 	 */
984 	if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
985 		if (strcmp(graphfilename, "-") == 0)
986 		    args.pa_graphfile = args.pa_printfile;
987 		else {
988 			args.pa_graphfile = fopen(graphfilename, "w");
989 			if (args.pa_graphfile == NULL)
990 				err(EX_OSERR,
991 				    "ERROR: cannot open \"%s\" for writing",
992 				    graphfilename);
993 		}
994 	}
995 	if (args.pa_flags & FLAG_DO_ANNOTATE) {
996 		args.pa_graphfile = fopen(graphfilename, "w");
997 		if (args.pa_graphfile == NULL)
998 			err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
999 			    graphfilename);
1000 	}
1001 
1002 	/* if we've been asked to process a log file, skip init */
1003 	if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) {
1004 		if (pmc_init() < 0)
1005 			err(EX_UNAVAILABLE,
1006 			    "ERROR: Initialization of the pmc(3) library failed"
1007 			    );
1008 
1009 		if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1010 			err(EX_OSERR,
1011 "ERROR: Cannot determine the number of PMCs on CPU %d",
1012 			    0);
1013 	}
1014 
1015 	/* Allocate a kqueue */
1016 	if ((pmcstat_kq = kqueue()) < 0)
1017 		err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1018 
1019 	/* Setup the logfile as the source. */
1020 	if (args.pa_flags & FLAG_READ_LOGFILE) {
1021 		/*
1022 		 * Print the log in textual form if we haven't been
1023 		 * asked to generate profiling information.
1024 		 */
1025 		if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1026 			args.pa_flags |= FLAG_DO_PRINT;
1027 
1028 		pmcstat_log_initialize_logging();
1029 		rfd = pmcstat_open_log(args.pa_inputpath,
1030 		    PMCSTAT_OPEN_FOR_READ);
1031 		if ((args.pa_logparser = pmclog_open(rfd)) == NULL)
1032 			err(EX_OSERR, "ERROR: Cannot create parser");
1033 		if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0)
1034 			err(EX_OSERR, "ERROR: fcntl(2) failed");
1035 		EV_SET(&kev, rfd, EVFILT_READ, EV_ADD,
1036 		    0, 0, NULL);
1037 		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1038 			err(EX_OSERR, "ERROR: Cannot register kevent");
1039 	}
1040 	/*
1041 	 * Configure the specified log file or setup a default log
1042 	 * consumer via a pipe.
1043 	 */
1044 	if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1045 		if (args.pa_outputpath)
1046 			args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1047 			    PMCSTAT_OPEN_FOR_WRITE);
1048 		else {
1049 			/*
1050 			 * process the log on the fly by reading it in
1051 			 * through a pipe.
1052 			 */
1053 			if (pipe(pipefd) < 0)
1054 				err(EX_OSERR, "ERROR: pipe(2) failed");
1055 
1056 			if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1057 				err(EX_OSERR, "ERROR: fcntl(2) failed");
1058 
1059 			EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1060 			    0, 0, NULL);
1061 
1062 			if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1063 				err(EX_OSERR, "ERROR: Cannot register kevent");
1064 
1065 			args.pa_logfd = pipefd[WRITEPIPEFD];
1066 
1067 			args.pa_flags |= FLAG_HAS_PIPE;
1068 			if ((args.pa_flags & FLAG_DO_TOP) == 0)
1069 				args.pa_flags |= FLAG_DO_PRINT;
1070 			args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1071 		}
1072 
1073 		if (pmc_configure_logfile(args.pa_logfd) < 0)
1074 			err(EX_OSERR, "ERROR: Cannot configure log file");
1075 	}
1076 
1077 	/* remember to check for driver errors if we are sampling or logging */
1078 	check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1079 	    (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1080 
1081 	/*
1082 	if (args.pa_flags & FLAG_READ_LOGFILE) {
1083 	 * Allocate PMCs.
1084 	 */
1085 
1086 	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1087 		if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1088 		    ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1089 			err(EX_OSERR,
1090 "ERROR: Cannot allocate %s-mode pmc with specification \"%s\"",
1091 			    PMC_IS_SYSTEM_MODE(ev->ev_mode) ?
1092 			    "system" : "process", ev->ev_spec);
1093 
1094 		if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1095 		    pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1096 			err(EX_OSERR,
1097 			    "ERROR: Cannot set sampling count for PMC \"%s\"",
1098 			    ev->ev_name);
1099 	}
1100 
1101 	/* compute printout widths */
1102 	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1103 		int counter_width;
1104 		int display_width;
1105 		int header_width;
1106 
1107 		(void) pmc_width(ev->ev_pmcid, &counter_width);
1108 		header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1109 		display_width = (int) floor(counter_width / 3.32193) + 1;
1110 
1111 		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1112 			header_width += 3; /* 2 digit CPU number + '/' */
1113 
1114 		if (header_width > display_width) {
1115 			ev->ev_fieldskip = 0;
1116 			ev->ev_fieldwidth = header_width;
1117 		} else {
1118 			ev->ev_fieldskip = display_width -
1119 			    header_width;
1120 			ev->ev_fieldwidth = display_width;
1121 		}
1122 	}
1123 
1124 	/*
1125 	 * If our output is being set to a terminal, register a handler
1126 	 * for window size changes.
1127 	 */
1128 
1129 	if (isatty(fileno(args.pa_printfile))) {
1130 
1131 		if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1132 			err(EX_OSERR, "ERROR: Cannot determine window size");
1133 
1134 		pmcstat_displayheight = ws.ws_row - 1;
1135 		pmcstat_displaywidth  = ws.ws_col - 1;
1136 
1137 		EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1138 
1139 		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1140 			err(EX_OSERR,
1141 			    "ERROR: Cannot register kevent for SIGWINCH");
1142 
1143 		args.pa_toptty = 1;
1144 	}
1145 
1146 	/*
1147 	 * Listen to key input in top mode.
1148 	 */
1149 	if (args.pa_flags & FLAG_DO_TOP) {
1150 		EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1151 		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1152 			err(EX_OSERR, "ERROR: Cannot register kevent");
1153 	}
1154 
1155 	EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1156 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1157 		err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1158 
1159 	EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1160 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1161 		err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1162 
1163 	/*
1164 	 * An exec() failure of a forked child is signalled by the
1165 	 * child sending the parent a SIGCHLD.  We don't register an
1166 	 * actual signal handler for SIGCHLD, but instead use our
1167 	 * kqueue to pick up the signal.
1168 	 */
1169 	EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1170 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1171 		err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1172 
1173 	/*
1174 	 * Setup a timer if we have counting mode PMCs needing to be printed or
1175 	 * top mode plugin is active.
1176 	 */
1177 	if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1178 	     (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1179 	    (args.pa_flags & FLAG_DO_TOP)) {
1180 		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1181 		    args.pa_interval * 1000, NULL);
1182 
1183 		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1184 			err(EX_OSERR,
1185 			    "ERROR: Cannot register kevent for timer");
1186 	}
1187 
1188 	/*
1189 	 * Setup a duration timer if we have sampling mode PMCs and
1190 	 * a duration time is set
1191 	 */
1192 	if ((args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1193 	    (args.pa_flags & FLAG_HAS_DURATION)) {
1194 		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1195 		    args.pa_duration * 1000, NULL);
1196 
1197 		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1198 			err(EX_OSERR, "ERROR: Cannot register kevent for "
1199 			    "time duration");
1200 	}
1201 
1202 	/* attach PMCs to the target process, starting it if specified */
1203 	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1204 		pmcstat_create_process(pmcstat_sockpair, &args, pmcstat_kq);
1205 
1206 	if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1207 		err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1208 
1209 	/* Attach process pmcs to the target process. */
1210 	if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1211 		if (SLIST_EMPTY(&args.pa_targets))
1212 			errx(EX_DATAERR,
1213 			    "ERROR: No matching target processes.");
1214 		if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1215 			pmcstat_attach_pmcs(&args);
1216 
1217 		if (pmcstat_kvm) {
1218 			kvm_close(pmcstat_kvm);
1219 			pmcstat_kvm = NULL;
1220 		}
1221 	}
1222 
1223 	/* start the pmcs */
1224 	pmcstat_start_pmcs();
1225 
1226 	/* start the (commandline) process if needed */
1227 	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1228 		pmcstat_start_process(pmcstat_sockpair);
1229 
1230 	/* initialize logging */
1231 	pmcstat_log_initialize_logging();
1232 
1233 	/* Handle SIGINT using the kqueue loop */
1234 	sa.sa_handler = SIG_IGN;
1235 	sa.sa_flags   = 0;
1236 	(void) sigemptyset(&sa.sa_mask);
1237 
1238 	if (sigaction(SIGINT, &sa, NULL) < 0)
1239 		err(EX_OSERR, "ERROR: Cannot install signal handler");
1240 
1241 	/*
1242 	 * Setup the top mode display.
1243 	 */
1244 	if (args.pa_flags & FLAG_DO_TOP) {
1245 		args.pa_flags &= ~FLAG_DO_PRINT;
1246 
1247 		if (args.pa_toptty) {
1248 			/*
1249 			 * Init ncurses.
1250 			 */
1251 			initscr();
1252 			if(has_colors() == TRUE) {
1253 				args.pa_topcolor = 1;
1254 				start_color();
1255 				use_default_colors();
1256 				pair_content(0, &cf, &cb);
1257 				init_pair(1, COLOR_RED, cb);
1258 				init_pair(2, COLOR_YELLOW, cb);
1259 				init_pair(3, COLOR_GREEN, cb);
1260 			}
1261 			cbreak();
1262 			noecho();
1263 			nonl();
1264 			nodelay(stdscr, 1);
1265 			intrflush(stdscr, FALSE);
1266 			keypad(stdscr, TRUE);
1267 			clear();
1268 			/* Get terminal width / height with ncurses. */
1269 			getmaxyx(stdscr,
1270 			    pmcstat_displayheight, pmcstat_displaywidth);
1271 			pmcstat_displayheight--; pmcstat_displaywidth--;
1272 			atexit(pmcstat_topexit);
1273 		}
1274 	}
1275 
1276 	/*
1277 	 * loop till either the target process (if any) exits, or we
1278 	 * are killed by a SIGINT or we reached the time duration.
1279 	 */
1280 	runstate = PMCSTAT_RUNNING;
1281 	do_print = do_read = 0;
1282 	do {
1283 		if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1284 			if (errno != EINTR)
1285 				err(EX_OSERR, "ERROR: kevent failed");
1286 			else
1287 				continue;
1288 		}
1289 
1290 		if (kev.flags & EV_ERROR)
1291 			errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1292 
1293 		switch (kev.filter) {
1294 		case EVFILT_PROC:  /* target has exited */
1295 			runstate = pmcstat_close_log(&args);
1296 			do_print = 1;
1297 			break;
1298 
1299 		case EVFILT_READ:  /* log file data is present */
1300 			if (kev.ident == (unsigned)fileno(stdin) &&
1301 			    (args.pa_flags & FLAG_DO_TOP)) {
1302 				if (pmcstat_keypress_log())
1303 					runstate = pmcstat_close_log(&args);
1304 			} else {
1305 				do_read = 0;
1306 				runstate = pmcstat_process_log();
1307 			}
1308 			break;
1309 
1310 		case EVFILT_SIGNAL:
1311 			if (kev.ident == SIGCHLD) {
1312 				/*
1313 				 * The child process sends us a
1314 				 * SIGCHLD if its exec() failed.  We
1315 				 * wait for it to exit and then exit
1316 				 * ourselves.
1317 				 */
1318 				(void) wait(&c);
1319 				runstate = PMCSTAT_FINISHED;
1320 			} else if (kev.ident == SIGIO) {
1321 				/*
1322 				 * We get a SIGIO if a PMC loses all
1323 				 * of its targets, or if logfile
1324 				 * writes encounter an error.
1325 				 */
1326 				runstate = pmcstat_close_log(&args);
1327 				do_print = 1; /* print PMCs at exit */
1328 			} else if (kev.ident == SIGINT) {
1329 				/* Kill the child process if we started it */
1330 				if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1331 					pmcstat_kill_process();
1332 				runstate = pmcstat_close_log(&args);
1333 			} else if (kev.ident == SIGWINCH) {
1334 				if (ioctl(fileno(args.pa_printfile),
1335 					TIOCGWINSZ, &ws) < 0)
1336 				    err(EX_OSERR,
1337 				        "ERROR: Cannot determine window size");
1338 				pmcstat_displayheight = ws.ws_row - 1;
1339 				pmcstat_displaywidth  = ws.ws_col - 1;
1340 			} else
1341 				assert(0);
1342 
1343 			break;
1344 
1345 		case EVFILT_TIMER:
1346 			/* time duration reached, exit */
1347 			if (args.pa_flags & FLAG_HAS_DURATION) {
1348 				runstate = PMCSTAT_FINISHED;
1349 				break;
1350 			}
1351 			/* print out counting PMCs */
1352 			if ((args.pa_flags & FLAG_DO_TOP) &&
1353 			     pmc_flush_logfile() == 0)
1354 				do_read = 1;
1355 			do_print = 1;
1356 			break;
1357 
1358 		}
1359 
1360 		if (do_print && !do_read) {
1361 			if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1362 				pmcstat_print_pmcs();
1363 				if (runstate == PMCSTAT_FINISHED &&
1364 				    /* final newline */
1365 				    (args.pa_flags & FLAG_DO_PRINT) == 0)
1366 					(void) fprintf(args.pa_printfile, "\n");
1367 			}
1368 			if (args.pa_flags & FLAG_DO_TOP)
1369 				pmcstat_display_log();
1370 			do_print = 0;
1371 		}
1372 
1373 	} while (runstate != PMCSTAT_FINISHED);
1374 
1375 	if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1376 		pmcstat_topexit();
1377 		args.pa_toptty = 0;
1378 	}
1379 
1380 	/* flush any pending log entries */
1381 	if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1382 		pmc_close_logfile();
1383 
1384 	pmcstat_cleanup();
1385 
1386 	/* check if the driver lost any samples or events */
1387 	if (check_driver_stats) {
1388 		if (pmc_get_driver_stats(&ds_end) < 0)
1389 			err(EX_OSERR,
1390 			    "ERROR: Cannot retrieve driver statistics");
1391 		if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1392 		    args.pa_verbosity > 0)
1393 			warnx(
1394 "WARNING: sampling was paused at least %u time%s.\n"
1395 "Please consider tuning the \"kern.hwpmc.nsamples\" tunable.",
1396 			    ds_end.pm_intr_bufferfull -
1397 			    ds_start.pm_intr_bufferfull,
1398 			    ((ds_end.pm_intr_bufferfull -
1399 			    ds_start.pm_intr_bufferfull) != 1) ? "s" : ""
1400 			    );
1401 		if (ds_start.pm_buffer_requests_failed !=
1402 		    ds_end.pm_buffer_requests_failed &&
1403 		    args.pa_verbosity > 0)
1404 			warnx(
1405 "WARNING: at least %u event%s were discarded while running.\n"
1406 "Please consider tuning the \"kern.hwpmc.nbuffers\" tunable.",
1407 	 		    ds_end.pm_buffer_requests_failed -
1408 			    ds_start.pm_buffer_requests_failed,
1409 			    ((ds_end.pm_buffer_requests_failed -
1410 			    ds_start.pm_buffer_requests_failed) != 1) ? "s" : ""
1411 			    );
1412 	}
1413 
1414 	exit(EX_OK);
1415 }
1416