xref: /freebsd/usr.sbin/pmcstat/pmcstat.c (revision 716dfa4cb85cd32e18ed3a8b01404f7c540bbf6d)
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 -n rate\t set sampling rate\n"
329 	    "\t -o file\t send print output to \"file\"\n"
330 	    "\t -p spec\t allocate a process-private counting PMC\n"
331 	    "\t -s spec\t allocate a system-wide counting PMC\n"
332 	    "\t -t pid\t\t attach to running process with pid \"pid\"\n"
333 	    "\t -w secs\t set printing time interval"
334 	);
335 }
336 
337 /*
338  * Main
339  */
340 
341 int
342 main(int argc, char **argv)
343 {
344 	double interval;
345 	int option, npmc, ncpu;
346 	int c, current_cpu, current_sampling_count;
347 	int do_print, do_descendants;
348 	int do_logproccsw, do_logprocexit;
349 	int pipefd[2];
350 	int use_cumulative_counts;
351 	pid_t pid;
352 	char *end;
353 	const char *errmsg;
354 	enum pmcstat_state runstate;
355 	struct pmcstat_ev *ev;
356 	struct sigaction sa;
357 	struct kevent kev;
358 	struct winsize ws;
359 	struct stat sb;
360 
361 	current_cpu 		= 0;
362 	current_sampling_count  = DEFAULT_SAMPLE_COUNT;
363 	do_descendants          = 0;
364 	do_logproccsw           = 0;
365 	do_logprocexit          = 0;
366 	use_cumulative_counts   = 0;
367 	args.pa_required	= 0;
368 	args.pa_flags		= 0;
369 	args.pa_pid		= (pid_t) -1;
370 	args.pa_logfd		= -1;
371 	args.pa_samplesdir	= ".";
372 	args.pa_kernel		= "/boot/kernel/kernel";
373 	args.pa_printfile	= stderr;
374 	args.pa_interval	= DEFAULT_WAIT_INTERVAL;
375 	STAILQ_INIT(&args.pa_head);
376 
377 	ev = NULL;
378 
379 	while ((option = getopt(argc, argv, "CD:EO:P:R:S:Wc:dgk:n:o:p:s:t:w:"))
380 	    != -1)
381 		switch (option) {
382 		case 'C':	/* cumulative values */
383 			use_cumulative_counts = !use_cumulative_counts;
384 			args.pa_required |= FLAG_HAS_COUNTING_PMCS;
385 			break;
386 
387 		case 'c':	/* CPU */
388 			current_cpu = strtol(optarg, &end, 0);
389 			if (*end != '\0' || current_cpu < 0)
390 				errx(EX_USAGE,
391 				    "ERROR: Illegal CPU number \"%s\".",
392 				    optarg);
393 			args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
394 			break;
395 
396 		case 'D':
397 			if (stat(optarg, &sb) < 0)
398 				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
399 				    optarg);
400 			if (!S_ISDIR(sb.st_mode))
401 				errx(EX_USAGE, "ERROR: \"%s\" is not a "
402 				    "directory", optarg);
403 			args.pa_samplesdir = optarg;
404 			args.pa_flags     |= FLAG_HAS_SAMPLESDIR;
405 			args.pa_required  |= FLAG_DO_GPROF;
406 			break;
407 
408 		case 'd':	/* toggle descendents */
409 			do_descendants = !do_descendants;
410 			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
411 			break;
412 
413 		case 'g':	/* produce gprof compatible profiles */
414 			args.pa_flags |= FLAG_DO_GPROF;
415 			break;
416 
417 		case 'k':	/* pathname to the kernel */
418 			args.pa_kernel = optarg;
419 			args.pa_required |= FLAG_DO_GPROF;
420 			args.pa_flags    |= FLAG_HAS_KERNELPATH;
421 			break;
422 
423 		case 'E':	/* log process exit */
424 			do_logprocexit = !do_logprocexit;
425 			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
426 			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
427 			break;
428 
429 		case 'p':	/* process virtual counting PMC */
430 		case 's':	/* system-wide counting PMC */
431 		case 'P':	/* process virtual sampling PMC */
432 		case 'S':	/* system-wide sampling PMC */
433 			if ((ev = malloc(sizeof(*ev))) == NULL)
434 				errx(EX_SOFTWARE, "ERROR: Out of memory.");
435 
436 			switch (option) {
437 			case 'p': ev->ev_mode = PMC_MODE_TC; break;
438 			case 's': ev->ev_mode = PMC_MODE_SC; break;
439 			case 'P': ev->ev_mode = PMC_MODE_TS; break;
440 			case 'S': ev->ev_mode = PMC_MODE_SS; break;
441 			}
442 
443 			if (option == 'P' || option == 'p') {
444 				args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
445 				args.pa_required |= (FLAG_HAS_COMMANDLINE |
446 				    FLAG_HAS_PID);
447 			}
448 
449 			if (option == 'P' || option == 'S') {
450 				args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
451 				args.pa_required |= (FLAG_HAS_PIPE |
452 				    FLAG_HAS_OUTPUT_LOGFILE);
453 			}
454 
455 			if (option == 'p' || option == 's')
456 				args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
457 
458 			if (option == 's' || option == 'S')
459 				args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
460 
461 			ev->ev_spec  = strdup(optarg);
462 
463 			if (option == 'S' || option == 'P')
464 				ev->ev_count = current_sampling_count;
465 			else
466 				ev->ev_count = -1;
467 
468 			if (option == 'S' || option == 's')
469 				ev->ev_cpu = current_cpu;
470 			else
471 				ev->ev_cpu = PMC_CPU_ANY;
472 
473 			ev->ev_flags = 0;
474 			if (do_descendants)
475 				ev->ev_flags |= PMC_F_DESCENDANTS;
476 			if (do_logprocexit)
477 				ev->ev_flags |= PMC_F_LOG_PROCEXIT;
478 			if (do_logproccsw)
479 				ev->ev_flags |= PMC_F_LOG_PROCCSW;
480 
481 			ev->ev_cumulative  = use_cumulative_counts;
482 
483 			ev->ev_saved = 0LL;
484 			ev->ev_pmcid = PMC_ID_INVALID;
485 
486 			/* extract event name */
487 			c = strcspn(optarg, ", \t");
488 			ev->ev_name = malloc(c + 1);
489 			(void) strncpy(ev->ev_name, optarg, c);
490 			*(ev->ev_name + c) = '\0';
491 
492 			STAILQ_INSERT_TAIL(&args.pa_head, ev, ev_next);
493 
494 			break;
495 
496 		case 'n':	/* sampling count */
497 			current_sampling_count = strtol(optarg, &end, 0);
498 			if (*end != '\0' || current_sampling_count <= 0)
499 				errx(EX_USAGE,
500 				    "ERROR: Illegal count value \"%s\".",
501 				    optarg);
502 			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
503 			break;
504 
505 		case 'o':	/* outputfile */
506 			if (args.pa_printfile != NULL)
507 				(void) fclose(args.pa_printfile);
508 			if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
509 				errx(EX_OSERR, "ERROR: cannot open \"%s\" for "
510 				    "writing.", optarg);
511 			args.pa_flags |= FLAG_DO_PRINT;
512 			break;
513 
514 		case 'O':	/* sampling output */
515 			if (args.pa_outputpath)
516 				errx(EX_USAGE, "ERROR: option -O may only be "
517 				    "specified once.");
518 			args.pa_outputpath = optarg;
519 			args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
520 			break;
521 
522 		case 'R':	/* read an existing log file */
523 			if (args.pa_logparser != NULL)
524 				errx(EX_USAGE, "ERROR: option -R may only be "
525 				    "specified once.");
526 			args.pa_inputpath = optarg;
527 			if (args.pa_printfile == stderr)
528 				args.pa_printfile = stdout;
529 			args.pa_flags |= FLAG_READ_LOGFILE;
530 			break;
531 
532 		case 't':	/* target pid */
533 			pid = strtol(optarg, &end, 0);
534 			if (*end != '\0' || pid <= 0)
535 				errx(EX_USAGE, "ERROR: Illegal pid value "
536 				    "\"%s\".", optarg);
537 
538 			args.pa_flags |= FLAG_HAS_PID;
539 			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
540 			args.pa_pid = pid;
541 			break;
542 
543 		case 'w':	/* wait interval */
544 			interval = strtod(optarg, &end);
545 			if (*end != '\0' || interval <= 0)
546 				errx(EX_USAGE, "ERROR: Illegal wait interval "
547 				    "value \"%s\".", optarg);
548 			args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
549 			args.pa_required |= FLAG_HAS_COUNTING_PMCS;
550 			args.pa_interval = interval;
551 			break;
552 
553 		case 'W':	/* toggle LOG_CSW */
554 			do_logproccsw = !do_logproccsw;
555 			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
556 			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
557 			break;
558 
559 		case '?':
560 		default:
561 			pmcstat_show_usage();
562 			break;
563 
564 		}
565 
566 	args.pa_argc = (argc -= optind);
567 	args.pa_argv = (argv += optind);
568 
569 	if (argc)	/* command line present */
570 		args.pa_flags |= FLAG_HAS_COMMANDLINE;
571 
572 	/*
573 	 * Check invocation syntax.
574 	 */
575 
576 	/* disallow -O and -R together */
577 	if (args.pa_outputpath && args.pa_inputpath)
578 		errx(EX_USAGE, "ERROR: options -O and -R are mutually "
579 		    "exclusive.");
580 
581 	if (args.pa_flags & FLAG_READ_LOGFILE) {
582 		errmsg = NULL;
583 		if (args.pa_flags & FLAG_HAS_COMMANDLINE)
584 			errmsg = "a command line specification";
585 		else if (args.pa_flags & FLAG_HAS_PID)
586 			errmsg = "option -t";
587 		else if (!STAILQ_EMPTY(&args.pa_head))
588 			errmsg = "a PMC event specification";
589 		if (errmsg)
590 			errx(EX_USAGE, "ERROR: option -R may not be used with "
591 			    "%s.", errmsg);
592 	} else if (STAILQ_EMPTY(&args.pa_head))
593 		/* All other uses require a PMC spec. */
594 		pmcstat_show_usage();
595 
596 	/* check for -t pid without a process PMC spec */
597 	if ((args.pa_required & FLAG_HAS_PID) &&
598 	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
599 		errx(EX_USAGE, "ERROR: option -t requires a process mode PMC "
600 		    "to be specified.");
601 
602 	/* check for process-mode options without a command or -t pid */
603 	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
604 	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_PID)) == 0)
605 		errx(EX_USAGE, "ERROR: options -d, -E, -p, -P, and -W require "
606 		    "a command line or target process.");
607 
608 	/* check for -p | -P without a target process of some sort */
609 	if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_PID)) &&
610 	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_PID)) == 0)
611 		errx(EX_USAGE, "ERROR: options -P and -p require a "
612 		    "target process or a command line.");
613 
614 	/* check for process-mode options without a process-mode PMC */
615 	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
616 	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
617 		errx(EX_USAGE, "ERROR: options -d, -E, and -W require a "
618 		    "process mode PMC to be specified.");
619 
620 	/* check for -c cpu and not system mode PMCs */
621 	if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
622 	    (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0)
623 		errx(EX_USAGE, "ERROR: option -c requires at least one "
624 		    "system mode PMC to be specified.");
625 
626 	/* check for counting mode options without a counting PMC */
627 	if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
628 	    (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
629 		errx(EX_USAGE, "ERROR: options -C, -o and -W require at least "
630 		    "one counting mode PMC to be specified.");
631 
632 	/* check for sampling mode options without a sampling PMC spec */
633 	if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
634 	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
635 		errx(EX_USAGE, "ERROR: options -n and -O require at least "
636 		    "one sampling mode PMC to be specified.");
637 
638 	if ((args.pa_flags & (FLAG_HAS_PID | FLAG_HAS_COMMANDLINE)) ==
639 	    (FLAG_HAS_PID | FLAG_HAS_COMMANDLINE))
640 		errx(EX_USAGE,
641 		    "ERROR: option -t cannot be specified with a command "
642 		    "line.");
643 
644 	/* check if -g is being used correctly */
645 	if ((args.pa_flags & FLAG_DO_GPROF) &&
646 	    !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
647 		errx(EX_USAGE, "ERROR: option -g requires sampling PMCs or -R "
648 		    "to be specified.");
649 
650 	/* check if -O was spuriously specified */
651 	if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
652 	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
653 		errx(EX_USAGE,
654 		    "ERROR: option -O is used only with options "
655 		    "-E, -P, -S and -W.");
656 
657 	/* -D dir and -k kernel path require -g */
658 	if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
659 	    ((args.pa_flags & FLAG_DO_GPROF) == 0))
660 	    errx(EX_USAGE, "ERROR: option -k is only used with -g.");
661 
662 	if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
663 	    ((args.pa_flags & FLAG_DO_GPROF) == 0))
664 	    errx(EX_USAGE, "ERROR: option -D is only used with -g.");
665 
666 	/*
667 	 * Disallow textual output of sampling PMCs if counting PMCs
668 	 * have also been asked for, mostly because the combined output
669 	 * is difficult to make sense of.
670 	 */
671 	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
672 	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
673 	    ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0))
674 		errx(EX_USAGE, "ERROR: option -O is required if counting and "
675 		    "sampling PMCs are specified together.");
676 
677 	/* if we've been asked to process a log file, do that and exit */
678 	if (args.pa_flags & FLAG_READ_LOGFILE) {
679 		/*
680 		 * Print the log in textual form if we haven't been
681 		 * asked to generate gmon.out files.
682 		 */
683 		if ((args.pa_flags & FLAG_DO_GPROF) == 0)
684 			args.pa_flags |= FLAG_DO_PRINT;
685 
686 		pmcstat_initialize_logging(&args);
687 		if ((args.pa_logfd = pmcstat_open(args.pa_inputpath,
688 		    PMCSTAT_OPEN_FOR_READ)) < 0)
689 			err(EX_OSERR, "ERROR: Cannot open \"%s\" for "
690 			    "reading", args.pa_inputpath);
691 		if ((args.pa_logparser = pmclog_open(args.pa_logfd)) == NULL)
692 			err(EX_OSERR, "ERROR: Cannot create parser");
693 		pmcstat_process_log(&args);
694 		exit(EX_OK);
695 	}
696 
697 	/* otherwise, we've been asked to collect data */
698 	if (pmc_init() < 0)
699 		err(EX_UNAVAILABLE,
700 		    "ERROR: Initialization of the pmc(3) library failed");
701 
702 	if ((ncpu = pmc_ncpu()) < 0)
703 		err(EX_OSERR, "ERROR: Cannot determine the number CPUs "
704 		    "on the system");
705 
706 	if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
707 		err(EX_OSERR, "ERROR: Cannot determine the number of PMCs "
708 		    "on CPU %d", 0);
709 
710 	/* Allocate a kqueue */
711 	if ((pmcstat_kq = kqueue()) < 0)
712 		err(EX_OSERR, "ERROR: Cannot allocate kqueue");
713 
714 	/*
715 	 * Configure the specified log file or setup a default log
716 	 * consumer via a pipe.
717 	 */
718 	if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
719 		if (args.pa_outputpath) {
720 			if ((args.pa_logfd = pmcstat_open(args.pa_outputpath,
721 			    PMCSTAT_OPEN_FOR_WRITE)) < 0)
722 				err(EX_OSERR, "ERROR: Cannot open \"%s\" for "
723 				    "writing", args.pa_outputpath);
724 		} else {
725 			/*
726 			 * process the log on the fly by reading it in
727 			 * through a pipe.
728 			 */
729 			if (pipe(pipefd) < 0)
730 				err(EX_OSERR, "ERROR: pipe(2) failed");
731 
732 			if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
733 				err(EX_OSERR, "ERROR: fcntl(2) failed");
734 
735 			EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
736 			    0, 0, NULL);
737 
738 			if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
739 				err(EX_OSERR, "ERROR: Cannot register kevent");
740 
741 			args.pa_logfd = pipefd[WRITEPIPEFD];
742 
743 			args.pa_flags |= (FLAG_HAS_PIPE | FLAG_DO_PRINT);
744 			args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
745 		}
746 
747 		if (pmc_configure_logfile(args.pa_logfd) < 0)
748 			err(EX_OSERR, "ERROR: Cannot configure log file");
749 	}
750 
751 	/*
752 	 * Allocate PMCs.
753 	 */
754 
755 	STAILQ_FOREACH(ev, &args.pa_head, ev_next) {
756 	    if (pmc_allocate(ev->ev_spec, ev->ev_mode,
757 		    ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
758 		    err(EX_OSERR, "ERROR: Cannot allocate %s-mode pmc with "
759 			"specification \"%s\"",
760 			PMC_IS_SYSTEM_MODE(ev->ev_mode) ? "system" : "process",
761 			ev->ev_spec);
762 
763 	    if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
764 		pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
765 		    err(EX_OSERR, "ERROR: Cannot set sampling count "
766 			"for PMC \"%s\"", ev->ev_name);
767 	}
768 
769 	/* compute printout widths */
770 	STAILQ_FOREACH(ev, &args.pa_head, ev_next) {
771 		int counter_width;
772 		int display_width;
773 		int header_width;
774 
775 		(void) pmc_width(ev->ev_pmcid, &counter_width);
776 		header_width = strlen(ev->ev_name) + 2; /* prefix '%c|' */
777 		display_width = (int) floor(counter_width / 3.32193) + 1;
778 
779 		if (header_width > display_width) {
780 			ev->ev_fieldskip = 0;
781 			ev->ev_fieldwidth = header_width;
782 		} else {
783 			ev->ev_fieldskip = display_width -
784 			    header_width;
785 			ev->ev_fieldwidth = display_width;
786 		}
787 	}
788 
789 	/*
790 	 * If our output is being set to a terminal, register a handler
791 	 * for window size changes.
792 	 */
793 
794 	if (isatty(fileno(args.pa_printfile))) {
795 
796 		if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
797 			err(EX_OSERR, "ERROR: Cannot determine window size");
798 
799 		pmcstat_displayheight = ws.ws_row - 1;
800 
801 		EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
802 
803 		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
804 			err(EX_OSERR, "ERROR: Cannot register kevent for "
805 			    "SIGWINCH");
806 	}
807 
808 	EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
809 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
810 		err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
811 
812 	EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
813 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
814 		err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
815 
816 	/*
817 	 * An exec() failure of a forked child is signalled by the
818 	 * child sending the parent a SIGCHLD.  We don't register an
819 	 * actual signal handler for SIGCHLD, but instead use our
820 	 * kqueue to pick up the signal.
821 	 */
822 	EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
823 	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
824 		err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
825 
826 	/* setup a timer if we have counting mode PMCs needing to be printed */
827 	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
828 	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
829 		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
830 		    args.pa_interval * 1000, NULL);
831 
832 		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
833 			err(EX_OSERR, "ERROR: Cannot register kevent for "
834 			    "timer");
835 	}
836 
837 	/* attach PMCs to the target process, starting it if specified */
838 	if (args.pa_flags & (FLAG_HAS_PID | FLAG_HAS_COMMANDLINE))
839 		pmcstat_setup_process(&args);
840 
841 	/* start the pmcs */
842 	pmcstat_start_pmcs(&args);
843 
844 	/* start the (commandline) process if needed */
845 	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
846 		pmcstat_start_process(&args);
847 
848 	/* initialize logging if printing the configured log */
849 	if ((args.pa_flags & FLAG_DO_PRINT) &&
850 	    (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE)))
851 		pmcstat_initialize_logging(&args);
852 
853 	/* Handle SIGINT using the kqueue loop */
854 	sa.sa_handler = SIG_IGN;
855 	sa.sa_flags   = 0;
856 	(void) sigemptyset(&sa.sa_mask);
857 
858 	if (sigaction(SIGINT, &sa, NULL) < 0)
859 		err(EX_OSERR, "ERROR: Cannot install signal handler");
860 
861 	/*
862 	 * loop till either the target process (if any) exits, or we
863 	 * are killed by a SIGINT.
864 	 */
865 	runstate = PMCSTAT_RUNNING;
866 	do_print = 0;
867 	do {
868 		if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
869 			if (errno != EINTR)
870 				err(EX_OSERR, "ERROR: kevent failed");
871 			else
872 				continue;
873 		}
874 
875 		if (kev.flags & EV_ERROR)
876 			errc(EX_OSERR, kev.data, "ERROR: kevent failed");
877 
878 		switch (kev.filter) {
879 		case EVFILT_PROC:  /* target has exited */
880 			if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE |
881 				FLAG_HAS_PIPE))
882 				runstate = pmcstat_close_log(&args);
883 			break;
884 
885 		case EVFILT_READ:  /* log file data is present */
886 			runstate = pmcstat_process_log(&args);
887 			break;
888 
889 		case EVFILT_SIGNAL:
890 			if (kev.ident == SIGCHLD) {
891 				/*
892 				 * The child process sends us a
893 				 * SIGCHLD if its exec() failed.  We
894 				 * wait for it to exit and then exit
895 				 * ourselves.
896 				 */
897 				(void) wait(&c);
898 				runstate = PMCSTAT_FINISHED;
899 			} else if (kev.ident == SIGIO) {
900 				/*
901 				 * We get a SIGIO if a PMC loses all
902 				 * of its targets, or if logfile
903 				 * writes encounter an error.
904 				 */
905 				if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE |
906 				    FLAG_HAS_PIPE)) {
907 					runstate = pmcstat_close_log(&args);
908 					if (args.pa_flags &
909 					    (FLAG_DO_PRINT|FLAG_DO_GPROF))
910 						pmcstat_process_log(&args);
911 				}
912 				do_print = 1; /* print PMCs at exit */
913 				runstate = PMCSTAT_FINISHED;
914 			} else if (kev.ident == SIGINT) {
915 				/* Kill the child process if we started it */
916 				if (args.pa_flags & FLAG_HAS_COMMANDLINE)
917 					if (kill(args.pa_pid, SIGINT) != 0)
918 						err(EX_OSERR, "ERROR: cannot "
919 						    "signal child process");
920 				runstate = PMCSTAT_FINISHED;
921 			} else if (kev.ident == SIGWINCH) {
922 				if (ioctl(fileno(args.pa_printfile),
923 					TIOCGWINSZ, &ws) < 0)
924 				    err(EX_OSERR, "ERROR: Cannot determine "
925 					"window size");
926 				pmcstat_displayheight = ws.ws_row - 1;
927 			} else
928 				assert(0);
929 
930 			break;
931 
932 		case EVFILT_TIMER: /* print out counting PMCs */
933 			do_print = 1;
934 			break;
935 
936 		}
937 
938 		if (do_print &&
939 		    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
940 			pmcstat_print_pmcs(&args);
941 			if (runstate == PMCSTAT_FINISHED && /* final newline */
942 			    (args.pa_flags & FLAG_DO_PRINT) == 0)
943 				(void) fprintf(args.pa_printfile, "\n");
944 			do_print = 0;
945 		}
946 
947 	} while (runstate != PMCSTAT_FINISHED);
948 
949 	/* flush any pending log entries */
950 	if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
951 		pmc_flush_logfile();
952 
953 	pmcstat_cleanup(&args);
954 
955 	return 0;
956 }
957