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