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