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