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