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