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