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