xref: /freebsd/usr.sbin/pmcstat/pmcstat.c (revision 262e143bd46171a6415a5b28af260a5efa2a3db8)
1 /*-
2  * Copyright (c) 2003-2005, Joseph Koshy
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/types.h>
31 #include <sys/event.h>
32 #include <sys/queue.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36 #include <sys/ttycom.h>
37 #include <sys/wait.h>
38 
39 #include <assert.h>
40 #include <err.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <limits.h>
44 #include <math.h>
45 #include <pmc.h>
46 #include <pmclog.h>
47 #include <signal.h>
48 #include <stdarg.h>
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <sysexits.h>
54 #include <unistd.h>
55 
56 #include "pmcstat.h"
57 
58 /*
59  * A given invocation of pmcstat(8) can manage multiple PMCs of both
60  * the system-wide and per-process variety.  Each of these could be in
61  * 'counting mode' or in 'sampling mode'.
62  *
63  * For 'counting mode' PMCs, pmcstat(8) will periodically issue a
64  * pmc_read() at the configured time interval and print out the value
65  * of the requested PMCs.
66  *
67  * For 'sampling mode' PMCs it can log to a file for offline analysis,
68  * or can analyse sampling data "on the fly", either by converting
69  * samples to printed textual form or by creating gprof(1) compatible
70  * profiles, one per program executed.  When creating gprof(1)
71  * profiles it can optionally merge entries from multiple processes
72  * for a given executable into a single profile file.
73  */
74 
75 /* Globals */
76 
77 int	pmcstat_interrupt = 0;
78 int	pmcstat_displayheight = DEFAULT_DISPLAY_HEIGHT;
79 int	pmcstat_pipefd[NPIPEFD];
80 int	pmcstat_kq;
81 
82 /*
83  * cleanup
84  */
85 
86 void
87 pmcstat_cleanup(struct pmcstat_args *a)
88 {
89 	struct pmcstat_ev *ev, *tmp;
90 
91 	/* release allocated PMCs. */
92 	STAILQ_FOREACH_SAFE(ev, &a->pa_head, ev_next, tmp)
93 	    if (ev->ev_pmcid != PMC_ID_INVALID) {
94 		if (pmc_release(ev->ev_pmcid) < 0)
95 			err(EX_OSERR, "ERROR: cannot release pmc "
96 			    "0x%x \"%s\"", ev->ev_pmcid, ev->ev_name);
97 		free(ev->ev_name);
98 		free(ev->ev_spec);
99 		STAILQ_REMOVE(&a->pa_head, ev, pmcstat_ev, ev_next);
100 		free(ev);
101 	    }
102 
103 	/* de-configure the log file if present. */
104 	if (a->pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
105 		(void) pmc_configure_logfile(-1);
106 
107 	if (a->pa_logparser) {
108 		pmclog_close(a->pa_logparser);
109 		a->pa_logparser = NULL;
110 	}
111 
112 	if (a->pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
113 		pmcstat_shutdown_logging();
114 }
115 
116 void
117 pmcstat_start_pmcs(struct pmcstat_args *a)
118 {
119 	struct pmcstat_ev *ev;
120 
121 	STAILQ_FOREACH(ev, &args.pa_head, ev_next) {
122 
123 	    assert(ev->ev_pmcid != PMC_ID_INVALID);
124 
125 	    if (pmc_start(ev->ev_pmcid) < 0) {
126 	        warn("ERROR: Cannot start pmc 0x%x \"%s\"",
127 		    ev->ev_pmcid, ev->ev_name);
128 		pmcstat_cleanup(a);
129 		exit(EX_OSERR);
130 	    }
131 	}
132 
133 }
134 
135 void
136 pmcstat_print_headers(struct pmcstat_args *a)
137 {
138 	struct pmcstat_ev *ev;
139 	int c;
140 
141 	(void) fprintf(a->pa_printfile, PRINT_HEADER_PREFIX);
142 
143 	STAILQ_FOREACH(ev, &a->pa_head, ev_next) {
144 		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
145 			continue;
146 
147 		c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p';
148 
149 		if (ev->ev_fieldskip != 0) {
150 			(void) fprintf(a->pa_printfile, "%*s%c/%*s ",
151 			    ev->ev_fieldskip, "", c,
152 			    ev->ev_fieldwidth - ev->ev_fieldskip - 2,
153 			    ev->ev_name);
154 		} else
155 			(void) fprintf(a->pa_printfile, "%c/%*s ",
156 			    c, ev->ev_fieldwidth - 2, ev->ev_name);
157 	}
158 
159 	(void) fflush(a->pa_printfile);
160 }
161 
162 void
163 pmcstat_print_counters(struct pmcstat_args *a)
164 {
165 	int extra_width;
166 	struct pmcstat_ev *ev;
167 	pmc_value_t value;
168 
169 	extra_width = sizeof(PRINT_HEADER_PREFIX) - 1;
170 
171 	STAILQ_FOREACH(ev, &a->pa_head, ev_next) {
172 
173 		/* skip sampling mode counters */
174 		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
175 			continue;
176 
177 		if (pmc_read(ev->ev_pmcid, &value) < 0)
178 			err(EX_OSERR, "ERROR: Cannot read pmc "
179 			    "\"%s\"", ev->ev_name);
180 
181 		(void) fprintf(a->pa_printfile, "%*ju ",
182 		    ev->ev_fieldwidth + extra_width,
183 		    (uintmax_t) ev->ev_cumulative ? value :
184 		    (value - ev->ev_saved));
185 
186 		if (ev->ev_cumulative == 0)
187 			ev->ev_saved = value;
188 		extra_width = 0;
189 	}
190 
191 	(void) fflush(a->pa_printfile);
192 }
193 
194 /*
195  * Print output
196  */
197 
198 void
199 pmcstat_print_pmcs(struct pmcstat_args *a)
200 {
201 	static int linecount = 0;
202 
203 	/* check if we need to print a header line */
204 	if (++linecount > pmcstat_displayheight) {
205 		(void) fprintf(a->pa_printfile, "\n");
206 		linecount = 1;
207 	}
208 	if (linecount == 1)
209 		pmcstat_print_headers(a);
210 	(void) fprintf(a->pa_printfile, "\n");
211 
212 	pmcstat_print_counters(a);
213 
214 	return;
215 }
216 
217 /*
218  * Do process profiling
219  *
220  * If a pid was specified, attach each allocated PMC to the target
221  * process.  Otherwise, fork a child and attach the PMCs to the child,
222  * and have the child exec() the target program.
223  */
224 
225 void
226 pmcstat_setup_process(struct pmcstat_args *a)
227 {
228 	char token;
229 	struct pmcstat_ev *ev;
230 	struct kevent kev;
231 
232 	if (a->pa_flags & FLAG_HAS_PID) {
233 		STAILQ_FOREACH(ev, &a->pa_head, ev_next)
234 		    if (pmc_attach(ev->ev_pmcid, a->pa_pid) != 0)
235 			    err(EX_OSERR, "ERROR: cannot attach pmc \"%s\" to "
236 				"process %d", ev->ev_name, (int) a->pa_pid);
237 	} else {
238 
239 		/*
240 		 * We need to fork a new process and startup the child
241 		 * using execvp().  Before doing the exec() the child
242 		 * process reads its pipe for a token so that the parent
243 		 * can finish doing its pmc_attach() calls.
244 		 */
245 		if (pipe(pmcstat_pipefd) < 0)
246 			err(EX_OSERR, "ERROR: cannot create pipe");
247 
248 		switch (a->pa_pid = fork()) {
249 		case -1:
250 			err(EX_OSERR, "ERROR: cannot fork");
251 			/*NOTREACHED*/
252 
253 		case 0:		/* child */
254 
255 			/* wait for our parent to signal us */
256 			(void) close(pmcstat_pipefd[WRITEPIPEFD]);
257 			if (read(pmcstat_pipefd[READPIPEFD], &token, 1) < 0)
258 				err(EX_OSERR, "ERROR (child): cannot read "
259 				    "token");
260 			(void) close(pmcstat_pipefd[READPIPEFD]);
261 
262 			/* exec() the program requested */
263 			execvp(*a->pa_argv, a->pa_argv);
264 			/* and if that fails, notify the parent */
265 			kill(getppid(), SIGCHLD);
266 			err(EX_OSERR, "ERROR: execvp \"%s\" failed",
267 			    *a->pa_argv);
268 			/*NOTREACHED*/
269 
270 		default:	/* parent */
271 
272 			(void) close(pmcstat_pipefd[READPIPEFD]);
273 
274 			/* attach all our PMCs to the child */
275 			STAILQ_FOREACH(ev, &args.pa_head, ev_next)
276 			    if (PMC_IS_VIRTUAL_MODE(ev->ev_mode) &&
277 				pmc_attach(ev->ev_pmcid, a->pa_pid) != 0)
278 				    err(EX_OSERR, "ERROR: cannot attach pmc "
279 					"\"%s\" to process %d", ev->ev_name,
280 					(int) a->pa_pid);
281 
282 		}
283 	}
284 
285 	/* Ask to be notified via a kevent when the target process exits */
286 	EV_SET(&kev, a->pa_pid, EVFILT_PROC, EV_ADD|EV_ONESHOT, NOTE_EXIT, 0,
287 	    NULL);
288 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
289 		err(EX_OSERR, "ERROR: cannot monitor child process %d",
290 		    a->pa_pid);
291 	return;
292 }
293 
294 void
295 pmcstat_start_process(struct pmcstat_args *a)
296 {
297 
298 	/* nothing to do: target is already running */
299 	if (a->pa_flags & FLAG_HAS_PID)
300 		return;
301 
302 	/* write token to child to state that we are ready */
303 	if (write(pmcstat_pipefd[WRITEPIPEFD], "+", 1) != 1)
304 		err(EX_OSERR, "ERROR: write failed");
305 
306 	(void) close(pmcstat_pipefd[WRITEPIPEFD]);
307 }
308 
309 void
310 pmcstat_show_usage(void)
311 {
312 	errx(EX_USAGE,
313 	    "[options] [commandline]\n"
314 	    "\t Measure process and/or system performance using hardware\n"
315 	    "\t performance monitoring counters.\n"
316 	    "\t Options include:\n"
317 	    "\t -C\t\t (toggle) show cumulative counts\n"
318 	    "\t -D path\t create profiles in directory \"path\"\n"
319 	    "\t -E\t\t (toggle) show counts at process exit\n"
320 	    "\t -O file\t send log output to \"file\"\n"
321 	    "\t -P spec\t allocate a process-private sampling PMC\n"
322 	    "\t -R file\t read events from \"file\"\n"
323 	    "\t -S spec\t allocate a system-wide sampling PMC\n"
324 	    "\t -W\t\t (toggle) show counts per context switch\n"
325 	    "\t -c cpu\t\t set cpu for subsequent system-wide PMCs\n"
326 	    "\t -d\t\t (toggle) track descendants\n"
327 	    "\t -g\t\t produce gprof(1) compatible profiles\n"
328 	    "\t -k file\t set the path to the kernel\n"
329 	    "\t -n rate\t set sampling rate\n"
330 	    "\t -o file\t send print output to \"file\"\n"
331 	    "\t -p spec\t allocate a process-private counting PMC\n"
332 	    "\t -s spec\t allocate a system-wide counting PMC\n"
333 	    "\t -t pid\t\t attach to running process with pid \"pid\"\n"
334 	    "\t -w secs\t set printing time interval"
335 	);
336 }
337 
338 /*
339  * Main
340  */
341 
342 int
343 main(int argc, char **argv)
344 {
345 	double interval;
346 	int option, npmc, ncpu;
347 	int c, check_driver_stats, current_cpu, current_sampling_count;
348 	int do_print, do_descendants;
349 	int do_logproccsw, do_logprocexit;
350 	int pipefd[2];
351 	int use_cumulative_counts;
352 	pid_t pid;
353 	char *end;
354 	const char *errmsg;
355 	enum pmcstat_state runstate;
356 	struct pmc_driverstats ds_start, ds_end;
357 	struct pmcstat_ev *ev;
358 	struct sigaction sa;
359 	struct kevent kev;
360 	struct winsize ws;
361 	struct stat sb;
362 
363 	check_driver_stats      = 0;
364 	current_cpu 		= 0;
365 	current_sampling_count  = DEFAULT_SAMPLE_COUNT;
366 	do_descendants          = 0;
367 	do_logproccsw           = 0;
368 	do_logprocexit          = 0;
369 	use_cumulative_counts   = 0;
370 	args.pa_required	= 0;
371 	args.pa_flags		= 0;
372 	args.pa_pid		= (pid_t) -1;
373 	args.pa_logfd		= -1;
374 	args.pa_samplesdir	= ".";
375 	args.pa_kernel		= "/boot/kernel/kernel";
376 	args.pa_printfile	= stderr;
377 	args.pa_interval	= DEFAULT_WAIT_INTERVAL;
378 	STAILQ_INIT(&args.pa_head);
379 
380 	ev = NULL;
381 
382 	while ((option = getopt(argc, argv, "CD:EO:P:R:S:Wc:dgk:n:o:p:s:t:w:"))
383 	    != -1)
384 		switch (option) {
385 		case 'C':	/* cumulative values */
386 			use_cumulative_counts = !use_cumulative_counts;
387 			args.pa_required |= FLAG_HAS_COUNTING_PMCS;
388 			break;
389 
390 		case 'c':	/* CPU */
391 			current_cpu = strtol(optarg, &end, 0);
392 			if (*end != '\0' || current_cpu < 0)
393 				errx(EX_USAGE,
394 				    "ERROR: Illegal CPU number \"%s\".",
395 				    optarg);
396 			args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
397 			break;
398 
399 		case 'D':
400 			if (stat(optarg, &sb) < 0)
401 				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
402 				    optarg);
403 			if (!S_ISDIR(sb.st_mode))
404 				errx(EX_USAGE, "ERROR: \"%s\" is not a "
405 				    "directory", optarg);
406 			args.pa_samplesdir = optarg;
407 			args.pa_flags     |= FLAG_HAS_SAMPLESDIR;
408 			args.pa_required  |= FLAG_DO_GPROF;
409 			break;
410 
411 		case 'd':	/* toggle descendents */
412 			do_descendants = !do_descendants;
413 			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
414 			break;
415 
416 		case 'g':	/* produce gprof compatible profiles */
417 			args.pa_flags |= FLAG_DO_GPROF;
418 			break;
419 
420 		case 'k':	/* pathname to the kernel */
421 			args.pa_kernel = optarg;
422 			args.pa_required |= FLAG_DO_GPROF;
423 			args.pa_flags    |= FLAG_HAS_KERNELPATH;
424 			break;
425 
426 		case 'E':	/* log process exit */
427 			do_logprocexit = !do_logprocexit;
428 			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
429 			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
430 			break;
431 
432 		case 'p':	/* process virtual counting PMC */
433 		case 's':	/* system-wide counting PMC */
434 		case 'P':	/* process virtual sampling PMC */
435 		case 'S':	/* system-wide sampling PMC */
436 			if ((ev = malloc(sizeof(*ev))) == NULL)
437 				errx(EX_SOFTWARE, "ERROR: Out of memory.");
438 
439 			switch (option) {
440 			case 'p': ev->ev_mode = PMC_MODE_TC; break;
441 			case 's': ev->ev_mode = PMC_MODE_SC; break;
442 			case 'P': ev->ev_mode = PMC_MODE_TS; break;
443 			case 'S': ev->ev_mode = PMC_MODE_SS; break;
444 			}
445 
446 			if (option == 'P' || option == 'p') {
447 				args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
448 				args.pa_required |= (FLAG_HAS_COMMANDLINE |
449 				    FLAG_HAS_PID);
450 			}
451 
452 			if (option == 'P' || option == 'S') {
453 				args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
454 				args.pa_required |= (FLAG_HAS_PIPE |
455 				    FLAG_HAS_OUTPUT_LOGFILE);
456 			}
457 
458 			if (option == 'p' || option == 's')
459 				args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
460 
461 			if (option == 's' || option == 'S')
462 				args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
463 
464 			ev->ev_spec  = strdup(optarg);
465 
466 			if (option == 'S' || option == 'P')
467 				ev->ev_count = current_sampling_count;
468 			else
469 				ev->ev_count = -1;
470 
471 			if (option == 'S' || option == 's')
472 				ev->ev_cpu = current_cpu;
473 			else
474 				ev->ev_cpu = PMC_CPU_ANY;
475 
476 			ev->ev_flags = 0;
477 			if (do_descendants)
478 				ev->ev_flags |= PMC_F_DESCENDANTS;
479 			if (do_logprocexit)
480 				ev->ev_flags |= PMC_F_LOG_PROCEXIT;
481 			if (do_logproccsw)
482 				ev->ev_flags |= PMC_F_LOG_PROCCSW;
483 
484 			ev->ev_cumulative  = use_cumulative_counts;
485 
486 			ev->ev_saved = 0LL;
487 			ev->ev_pmcid = PMC_ID_INVALID;
488 
489 			/* extract event name */
490 			c = strcspn(optarg, ", \t");
491 			ev->ev_name = malloc(c + 1);
492 			(void) strncpy(ev->ev_name, optarg, c);
493 			*(ev->ev_name + c) = '\0';
494 
495 			STAILQ_INSERT_TAIL(&args.pa_head, ev, ev_next);
496 
497 			break;
498 
499 		case 'n':	/* sampling count */
500 			current_sampling_count = strtol(optarg, &end, 0);
501 			if (*end != '\0' || current_sampling_count <= 0)
502 				errx(EX_USAGE,
503 				    "ERROR: Illegal count value \"%s\".",
504 				    optarg);
505 			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
506 			break;
507 
508 		case 'o':	/* outputfile */
509 			if (args.pa_printfile != NULL)
510 				(void) fclose(args.pa_printfile);
511 			if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
512 				errx(EX_OSERR, "ERROR: cannot open \"%s\" for "
513 				    "writing.", optarg);
514 			args.pa_flags |= FLAG_DO_PRINT;
515 			break;
516 
517 		case 'O':	/* sampling output */
518 			if (args.pa_outputpath)
519 				errx(EX_USAGE, "ERROR: option -O may only be "
520 				    "specified once.");
521 			args.pa_outputpath = optarg;
522 			args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
523 			break;
524 
525 		case 'R':	/* read an existing log file */
526 			if (args.pa_logparser != NULL)
527 				errx(EX_USAGE, "ERROR: option -R may only be "
528 				    "specified once.");
529 			args.pa_inputpath = optarg;
530 			if (args.pa_printfile == stderr)
531 				args.pa_printfile = stdout;
532 			args.pa_flags |= FLAG_READ_LOGFILE;
533 			break;
534 
535 		case 't':	/* target pid */
536 			pid = strtol(optarg, &end, 0);
537 			if (*end != '\0' || pid <= 0)
538 				errx(EX_USAGE, "ERROR: Illegal pid value "
539 				    "\"%s\".", optarg);
540 
541 			args.pa_flags |= FLAG_HAS_PID;
542 			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
543 			args.pa_pid = pid;
544 			break;
545 
546 		case 'w':	/* wait interval */
547 			interval = strtod(optarg, &end);
548 			if (*end != '\0' || interval <= 0)
549 				errx(EX_USAGE, "ERROR: Illegal wait interval "
550 				    "value \"%s\".", optarg);
551 			args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
552 			args.pa_required |= FLAG_HAS_COUNTING_PMCS;
553 			args.pa_interval = interval;
554 			break;
555 
556 		case 'W':	/* toggle LOG_CSW */
557 			do_logproccsw = !do_logproccsw;
558 			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
559 			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
560 			break;
561 
562 		case '?':
563 		default:
564 			pmcstat_show_usage();
565 			break;
566 
567 		}
568 
569 	args.pa_argc = (argc -= optind);
570 	args.pa_argv = (argv += optind);
571 
572 	if (argc)	/* command line present */
573 		args.pa_flags |= FLAG_HAS_COMMANDLINE;
574 
575 	/*
576 	 * Check invocation syntax.
577 	 */
578 
579 	/* disallow -O and -R together */
580 	if (args.pa_outputpath && args.pa_inputpath)
581 		errx(EX_USAGE, "ERROR: options -O and -R are mutually "
582 		    "exclusive.");
583 
584 	if (args.pa_flags & FLAG_READ_LOGFILE) {
585 		errmsg = NULL;
586 		if (args.pa_flags & FLAG_HAS_COMMANDLINE)
587 			errmsg = "a command line specification";
588 		else if (args.pa_flags & FLAG_HAS_PID)
589 			errmsg = "option -t";
590 		else if (!STAILQ_EMPTY(&args.pa_head))
591 			errmsg = "a PMC event specification";
592 		if (errmsg)
593 			errx(EX_USAGE, "ERROR: option -R may not be used with "
594 			    "%s.", errmsg);
595 	} else if (STAILQ_EMPTY(&args.pa_head))
596 		/* All other uses require a PMC spec. */
597 		pmcstat_show_usage();
598 
599 	/* check for -t pid without a process PMC spec */
600 	if ((args.pa_required & FLAG_HAS_PID) &&
601 	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
602 		errx(EX_USAGE, "ERROR: option -t requires a process mode PMC "
603 		    "to be specified.");
604 
605 	/* check for process-mode options without a command or -t pid */
606 	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
607 	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_PID)) == 0)
608 		errx(EX_USAGE, "ERROR: options -d, -E, -p, -P, and -W require "
609 		    "a command line or target process.");
610 
611 	/* check for -p | -P without a target process of some sort */
612 	if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_PID)) &&
613 	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_PID)) == 0)
614 		errx(EX_USAGE, "ERROR: options -P and -p require a "
615 		    "target process or a command line.");
616 
617 	/* check for process-mode options without a process-mode PMC */
618 	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
619 	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
620 		errx(EX_USAGE, "ERROR: options -d, -E, and -W require a "
621 		    "process mode PMC to be specified.");
622 
623 	/* check for -c cpu and not system mode PMCs */
624 	if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
625 	    (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0)
626 		errx(EX_USAGE, "ERROR: option -c requires at least one "
627 		    "system mode PMC to be specified.");
628 
629 	/* check for counting mode options without a counting PMC */
630 	if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
631 	    (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
632 		errx(EX_USAGE, "ERROR: options -C, -W, -o and -w require at "
633 		    "least one counting mode PMC to be specified.");
634 
635 	/* check for sampling mode options without a sampling PMC spec */
636 	if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
637 	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
638 		errx(EX_USAGE, "ERROR: options -n and -O require at least "
639 		    "one sampling mode PMC to be specified.");
640 
641 	if ((args.pa_flags & (FLAG_HAS_PID | FLAG_HAS_COMMANDLINE)) ==
642 	    (FLAG_HAS_PID | FLAG_HAS_COMMANDLINE))
643 		errx(EX_USAGE,
644 		    "ERROR: option -t cannot be specified with a command "
645 		    "line.");
646 
647 	/* check if -g is being used correctly */
648 	if ((args.pa_flags & FLAG_DO_GPROF) &&
649 	    !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
650 		errx(EX_USAGE, "ERROR: option -g requires sampling PMCs or -R "
651 		    "to be specified.");
652 
653 	/* check if -O was spuriously specified */
654 	if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
655 	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
656 		errx(EX_USAGE,
657 		    "ERROR: option -O is used only with options "
658 		    "-E, -P, -S and -W.");
659 
660 	/* -D dir and -k kernel path require -g */
661 	if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
662 	    ((args.pa_flags & FLAG_DO_GPROF) == 0))
663 	    errx(EX_USAGE, "ERROR: option -k is only used with -g.");
664 
665 	if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
666 	    ((args.pa_flags & FLAG_DO_GPROF) == 0))
667 	    errx(EX_USAGE, "ERROR: option -D is only used with -g.");
668 
669 	/*
670 	 * Disallow textual output of sampling PMCs if counting PMCs
671 	 * have also been asked for, mostly because the combined output
672 	 * is difficult to make sense of.
673 	 */
674 	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
675 	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
676 	    ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0))
677 		errx(EX_USAGE, "ERROR: option -O is required if counting and "
678 		    "sampling PMCs are specified together.");
679 
680 	/* if we've been asked to process a log file, do that and exit */
681 	if (args.pa_flags & FLAG_READ_LOGFILE) {
682 		/*
683 		 * Print the log in textual form if we haven't been
684 		 * asked to generate gmon.out files.
685 		 */
686 		if ((args.pa_flags & FLAG_DO_GPROF) == 0)
687 			args.pa_flags |= FLAG_DO_PRINT;
688 
689 		pmcstat_initialize_logging(&args);
690 		if ((args.pa_logfd = pmcstat_open(args.pa_inputpath,
691 		    PMCSTAT_OPEN_FOR_READ)) < 0)
692 			err(EX_OSERR, "ERROR: Cannot open \"%s\" for "
693 			    "reading", args.pa_inputpath);
694 		if ((args.pa_logparser = pmclog_open(args.pa_logfd)) == NULL)
695 			err(EX_OSERR, "ERROR: Cannot create parser");
696 		pmcstat_process_log(&args);
697 		exit(EX_OK);
698 	}
699 
700 	/* otherwise, we've been asked to collect data */
701 	if (pmc_init() < 0)
702 		err(EX_UNAVAILABLE,
703 		    "ERROR: Initialization of the pmc(3) library failed");
704 
705 	if ((ncpu = pmc_ncpu()) < 0)
706 		err(EX_OSERR, "ERROR: Cannot determine the number CPUs "
707 		    "on the system");
708 
709 	if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
710 		err(EX_OSERR, "ERROR: Cannot determine the number of PMCs "
711 		    "on CPU %d", 0);
712 
713 	/* Allocate a kqueue */
714 	if ((pmcstat_kq = kqueue()) < 0)
715 		err(EX_OSERR, "ERROR: Cannot allocate kqueue");
716 
717 	/*
718 	 * Configure the specified log file or setup a default log
719 	 * consumer via a pipe.
720 	 */
721 	if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
722 		if (args.pa_outputpath) {
723 			if ((args.pa_logfd = pmcstat_open(args.pa_outputpath,
724 			    PMCSTAT_OPEN_FOR_WRITE)) < 0)
725 				err(EX_OSERR, "ERROR: Cannot open \"%s\" for "
726 				    "writing", args.pa_outputpath);
727 		} else {
728 			/*
729 			 * process the log on the fly by reading it in
730 			 * through a pipe.
731 			 */
732 			if (pipe(pipefd) < 0)
733 				err(EX_OSERR, "ERROR: pipe(2) failed");
734 
735 			if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
736 				err(EX_OSERR, "ERROR: fcntl(2) failed");
737 
738 			EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
739 			    0, 0, NULL);
740 
741 			if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
742 				err(EX_OSERR, "ERROR: Cannot register kevent");
743 
744 			args.pa_logfd = pipefd[WRITEPIPEFD];
745 
746 			args.pa_flags |= (FLAG_HAS_PIPE | FLAG_DO_PRINT);
747 			args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
748 		}
749 
750 		if (pmc_configure_logfile(args.pa_logfd) < 0)
751 			err(EX_OSERR, "ERROR: Cannot configure log file");
752 	}
753 
754 	/* remember to check for driver errors if we are sampling or logging */
755 	check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
756 	    (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
757 
758 	/*
759 	 * Allocate PMCs.
760 	 */
761 
762 	STAILQ_FOREACH(ev, &args.pa_head, ev_next) {
763 	    if (pmc_allocate(ev->ev_spec, ev->ev_mode,
764 		    ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
765 		    err(EX_OSERR, "ERROR: Cannot allocate %s-mode pmc with "
766 			"specification \"%s\"",
767 			PMC_IS_SYSTEM_MODE(ev->ev_mode) ? "system" : "process",
768 			ev->ev_spec);
769 
770 	    if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
771 		pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
772 		    err(EX_OSERR, "ERROR: Cannot set sampling count "
773 			"for PMC \"%s\"", ev->ev_name);
774 	}
775 
776 	/* compute printout widths */
777 	STAILQ_FOREACH(ev, &args.pa_head, ev_next) {
778 		int counter_width;
779 		int display_width;
780 		int header_width;
781 
782 		(void) pmc_width(ev->ev_pmcid, &counter_width);
783 		header_width = strlen(ev->ev_name) + 2; /* prefix '%c|' */
784 		display_width = (int) floor(counter_width / 3.32193) + 1;
785 
786 		if (header_width > display_width) {
787 			ev->ev_fieldskip = 0;
788 			ev->ev_fieldwidth = header_width;
789 		} else {
790 			ev->ev_fieldskip = display_width -
791 			    header_width;
792 			ev->ev_fieldwidth = display_width;
793 		}
794 	}
795 
796 	/*
797 	 * If our output is being set to a terminal, register a handler
798 	 * for window size changes.
799 	 */
800 
801 	if (isatty(fileno(args.pa_printfile))) {
802 
803 		if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
804 			err(EX_OSERR, "ERROR: Cannot determine window size");
805 
806 		pmcstat_displayheight = ws.ws_row - 1;
807 
808 		EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
809 
810 		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
811 			err(EX_OSERR, "ERROR: Cannot register kevent for "
812 			    "SIGWINCH");
813 	}
814 
815 	EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
816 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
817 		err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
818 
819 	EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
820 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
821 		err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
822 
823 	/*
824 	 * An exec() failure of a forked child is signalled by the
825 	 * child sending the parent a SIGCHLD.  We don't register an
826 	 * actual signal handler for SIGCHLD, but instead use our
827 	 * kqueue to pick up the signal.
828 	 */
829 	EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
830 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
831 		err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
832 
833 	/* setup a timer if we have counting mode PMCs needing to be printed */
834 	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
835 	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
836 		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
837 		    args.pa_interval * 1000, NULL);
838 
839 		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
840 			err(EX_OSERR, "ERROR: Cannot register kevent for "
841 			    "timer");
842 	}
843 
844 	/* attach PMCs to the target process, starting it if specified */
845 	if (args.pa_flags & (FLAG_HAS_PID | FLAG_HAS_COMMANDLINE))
846 		pmcstat_setup_process(&args);
847 
848 	if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
849 		err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
850 
851 	/* start the pmcs */
852 	pmcstat_start_pmcs(&args);
853 
854 	/* start the (commandline) process if needed */
855 	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
856 		pmcstat_start_process(&args);
857 
858 	/* initialize logging if printing the configured log */
859 	if ((args.pa_flags & FLAG_DO_PRINT) &&
860 	    (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE)))
861 		pmcstat_initialize_logging(&args);
862 
863 	/* Handle SIGINT using the kqueue loop */
864 	sa.sa_handler = SIG_IGN;
865 	sa.sa_flags   = 0;
866 	(void) sigemptyset(&sa.sa_mask);
867 
868 	if (sigaction(SIGINT, &sa, NULL) < 0)
869 		err(EX_OSERR, "ERROR: Cannot install signal handler");
870 
871 	/*
872 	 * loop till either the target process (if any) exits, or we
873 	 * are killed by a SIGINT.
874 	 */
875 	runstate = PMCSTAT_RUNNING;
876 	do_print = 0;
877 	do {
878 		if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
879 			if (errno != EINTR)
880 				err(EX_OSERR, "ERROR: kevent failed");
881 			else
882 				continue;
883 		}
884 
885 		if (kev.flags & EV_ERROR)
886 			errc(EX_OSERR, kev.data, "ERROR: kevent failed");
887 
888 		switch (kev.filter) {
889 		case EVFILT_PROC:  /* target has exited */
890 			if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE |
891 				FLAG_HAS_PIPE))
892 				runstate = pmcstat_close_log(&args);
893 			else
894 				runstate = PMCSTAT_FINISHED;
895 			do_print = 1;
896 			break;
897 
898 		case EVFILT_READ:  /* log file data is present */
899 			runstate = pmcstat_process_log(&args);
900 			break;
901 
902 		case EVFILT_SIGNAL:
903 			if (kev.ident == SIGCHLD) {
904 				/*
905 				 * The child process sends us a
906 				 * SIGCHLD if its exec() failed.  We
907 				 * wait for it to exit and then exit
908 				 * ourselves.
909 				 */
910 				(void) wait(&c);
911 				runstate = PMCSTAT_FINISHED;
912 			} else if (kev.ident == SIGIO) {
913 				/*
914 				 * We get a SIGIO if a PMC loses all
915 				 * of its targets, or if logfile
916 				 * writes encounter an error.
917 				 */
918 				if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE |
919 				    FLAG_HAS_PIPE)) {
920 					runstate = pmcstat_close_log(&args);
921 					if (args.pa_flags &
922 					    (FLAG_DO_PRINT|FLAG_DO_GPROF))
923 						pmcstat_process_log(&args);
924 				}
925 				do_print = 1; /* print PMCs at exit */
926 				runstate = PMCSTAT_FINISHED;
927 			} else if (kev.ident == SIGINT) {
928 				/* Kill the child process if we started it */
929 				if (args.pa_flags & FLAG_HAS_COMMANDLINE)
930 					if (kill(args.pa_pid, SIGINT) != 0)
931 						err(EX_OSERR, "ERROR: cannot "
932 						    "signal child process");
933 				runstate = PMCSTAT_FINISHED;
934 			} else if (kev.ident == SIGWINCH) {
935 				if (ioctl(fileno(args.pa_printfile),
936 					TIOCGWINSZ, &ws) < 0)
937 				    err(EX_OSERR, "ERROR: Cannot determine "
938 					"window size");
939 				pmcstat_displayheight = ws.ws_row - 1;
940 			} else
941 				assert(0);
942 
943 			break;
944 
945 		case EVFILT_TIMER: /* print out counting PMCs */
946 			do_print = 1;
947 			break;
948 
949 		}
950 
951 		if (do_print &&
952 		    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
953 			pmcstat_print_pmcs(&args);
954 			if (runstate == PMCSTAT_FINISHED && /* final newline */
955 			    (args.pa_flags & FLAG_DO_PRINT) == 0)
956 				(void) fprintf(args.pa_printfile, "\n");
957 			do_print = 0;
958 		}
959 
960 	} while (runstate != PMCSTAT_FINISHED);
961 
962 	/* flush any pending log entries */
963 	if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
964 		pmc_flush_logfile();
965 
966 	pmcstat_cleanup(&args);
967 
968 	/* check if the driver lost any samples or events */
969 	if (check_driver_stats) {
970 		if (pmc_get_driver_stats(&ds_end) < 0)
971 			err(EX_OSERR, "ERROR: Cannot retrieve driver "
972 			    "statistics");
973 		if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull)
974 			warn("WARNING: some samples were dropped.  Please "
975 			    "consider tuning the \"kern.hwpmc.nsamples\" "
976 			    "tunable.");
977 		if (ds_start.pm_buffer_requests_failed !=
978 		    ds_end.pm_buffer_requests_failed)
979 			warn("WARNING: some events were discarded.  Please "
980 			    "consider tuning the \"kern.hwpmc.nbuffers\" "
981 			    "tunable.");
982 	}
983 
984 	exit(EX_OK);
985 }
986