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