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