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