1145256Sjkoshy/*-
2180148Sjkoshy * Copyright (c) 2003-2008, Joseph Koshy
3174396Sjkoshy * Copyright (c) 2007 The FreeBSD Foundation
4145256Sjkoshy * All rights reserved.
5145256Sjkoshy *
6174396Sjkoshy * Portions of this software were developed by A. Joseph Koshy under
7174396Sjkoshy * sponsorship from the FreeBSD Foundation and Google, Inc.
8174396Sjkoshy *
9145256Sjkoshy * Redistribution and use in source and binary forms, with or without
10145256Sjkoshy * modification, are permitted provided that the following conditions
11145256Sjkoshy * are met:
12145256Sjkoshy * 1. Redistributions of source code must retain the above copyright
13145256Sjkoshy *    notice, this list of conditions and the following disclaimer.
14145256Sjkoshy * 2. Redistributions in binary form must reproduce the above copyright
15145256Sjkoshy *    notice, this list of conditions and the following disclaimer in the
16145256Sjkoshy *    documentation and/or other materials provided with the distribution.
17145256Sjkoshy *
18145256Sjkoshy * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19145256Sjkoshy * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20145256Sjkoshy * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21145256Sjkoshy * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22145256Sjkoshy * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23145256Sjkoshy * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24145256Sjkoshy * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25145256Sjkoshy * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26145256Sjkoshy * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27145256Sjkoshy * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28145256Sjkoshy * SUCH DAMAGE.
29145256Sjkoshy */
30145256Sjkoshy
31145256Sjkoshy#include <sys/cdefs.h>
32145256Sjkoshy__FBSDID("$FreeBSD$");
33145256Sjkoshy
34224698Sattilio#include <sys/param.h>
35224698Sattilio#include <sys/cpuset.h>
36145256Sjkoshy#include <sys/event.h>
37145256Sjkoshy#include <sys/queue.h>
38147708Sjkoshy#include <sys/socket.h>
39147708Sjkoshy#include <sys/stat.h>
40168949Sjkoshy#include <sys/sysctl.h>
41145256Sjkoshy#include <sys/time.h>
42145256Sjkoshy#include <sys/ttycom.h>
43169069Sjkoshy#include <sys/user.h>
44145256Sjkoshy#include <sys/wait.h>
45145256Sjkoshy
46145256Sjkoshy#include <assert.h>
47203790Sfabient#include <curses.h>
48145256Sjkoshy#include <err.h>
49145256Sjkoshy#include <errno.h>
50145256Sjkoshy#include <fcntl.h>
51169069Sjkoshy#include <kvm.h>
52157144Sjkoshy#include <libgen.h>
53145256Sjkoshy#include <limits.h>
54145256Sjkoshy#include <math.h>
55145256Sjkoshy#include <pmc.h>
56147191Sjkoshy#include <pmclog.h>
57169069Sjkoshy#include <regex.h>
58145256Sjkoshy#include <signal.h>
59145256Sjkoshy#include <stdarg.h>
60147708Sjkoshy#include <stdint.h>
61145256Sjkoshy#include <stdio.h>
62145256Sjkoshy#include <stdlib.h>
63145256Sjkoshy#include <string.h>
64145256Sjkoshy#include <sysexits.h>
65145256Sjkoshy#include <unistd.h>
66145256Sjkoshy
67147708Sjkoshy#include "pmcstat.h"
68147708Sjkoshy
69147191Sjkoshy/*
70147191Sjkoshy * A given invocation of pmcstat(8) can manage multiple PMCs of both
71147191Sjkoshy * the system-wide and per-process variety.  Each of these could be in
72147191Sjkoshy * 'counting mode' or in 'sampling mode'.
73147191Sjkoshy *
74147191Sjkoshy * For 'counting mode' PMCs, pmcstat(8) will periodically issue a
75147191Sjkoshy * pmc_read() at the configured time interval and print out the value
76147191Sjkoshy * of the requested PMCs.
77147191Sjkoshy *
78147191Sjkoshy * For 'sampling mode' PMCs it can log to a file for offline analysis,
79147191Sjkoshy * or can analyse sampling data "on the fly", either by converting
80147191Sjkoshy * samples to printed textual form or by creating gprof(1) compatible
81147191Sjkoshy * profiles, one per program executed.  When creating gprof(1)
82147191Sjkoshy * profiles it can optionally merge entries from multiple processes
83147191Sjkoshy * for a given executable into a single profile file.
84168949Sjkoshy *
85168949Sjkoshy * pmcstat(8) can also execute a command line and attach PMCs to the
86168949Sjkoshy * resulting child process.  The protocol used is as follows:
87168949Sjkoshy *
88168949Sjkoshy * - parent creates a socketpair for two way communication and
89168949Sjkoshy *   fork()s.
90168949Sjkoshy * - subsequently:
91168949Sjkoshy *
92168949Sjkoshy *   /Parent/				/Child/
93168949Sjkoshy *
94168949Sjkoshy *   - Wait for childs token.
95168949Sjkoshy *					- Sends token.
96168949Sjkoshy *					- Awaits signal to start.
97168949Sjkoshy *  - Attaches PMCs to the child's pid
98168949Sjkoshy *    and starts them. Sets up
99168949Sjkoshy *    monitoring for the child.
100168949Sjkoshy *  - Signals child to start.
101228990Suqs *					- Receives signal, attempts exec().
102168949Sjkoshy *
103168949Sjkoshy * After this point normal processing can happen.
104147191Sjkoshy */
105147191Sjkoshy
106147708Sjkoshy/* Globals */
107145256Sjkoshy
108241737Sedint		pmcstat_displayheight = DEFAULT_DISPLAY_HEIGHT;
109241737Sedint		pmcstat_displaywidth  = DEFAULT_DISPLAY_WIDTH;
110241737Sedstatic int	pmcstat_sockpair[NSOCKPAIRFD];
111241737Sedstatic int	pmcstat_kq;
112241737Sedstatic kvm_t	*pmcstat_kvm;
113241737Sedstatic struct kinfo_proc *pmcstat_plist;
114203790Sfabientstruct pmcstat_args args;
115145256Sjkoshy
116224698Sattiliostatic void
117224698Sattiliopmcstat_clone_event_descriptor(struct pmcstat_ev *ev, const cpuset_t *cpumask)
118224698Sattilio{
119224698Sattilio	int cpu, mcpu;
120224698Sattilio	struct pmcstat_ev *ev_clone;
121224698Sattilio
122224698Sattilio	mcpu = sizeof(*cpumask) * NBBY;
123224698Sattilio	for (cpu = 0; cpu < mcpu; cpu++) {
124224698Sattilio		if (!CPU_ISSET(cpu, cpumask))
125224698Sattilio			continue;
126224698Sattilio
127224698Sattilio		if ((ev_clone = malloc(sizeof(*ev_clone))) == NULL)
128224698Sattilio			errx(EX_SOFTWARE, "ERROR: Out of memory");
129224698Sattilio		(void) memset(ev_clone, 0, sizeof(*ev_clone));
130224698Sattilio
131224698Sattilio		ev_clone->ev_count = ev->ev_count;
132224698Sattilio		ev_clone->ev_cpu   = cpu;
133224698Sattilio		ev_clone->ev_cumulative = ev->ev_cumulative;
134224698Sattilio		ev_clone->ev_flags = ev->ev_flags;
135224698Sattilio		ev_clone->ev_mode  = ev->ev_mode;
136224698Sattilio		ev_clone->ev_name  = strdup(ev->ev_name);
137224698Sattilio		ev_clone->ev_pmcid = ev->ev_pmcid;
138224698Sattilio		ev_clone->ev_saved = ev->ev_saved;
139224698Sattilio		ev_clone->ev_spec  = strdup(ev->ev_spec);
140224698Sattilio
141224698Sattilio		STAILQ_INSERT_TAIL(&args.pa_events, ev_clone, ev_next);
142224698Sattilio	}
143224698Sattilio}
144224698Sattilio
145224698Sattiliostatic void
146224698Sattiliopmcstat_get_cpumask(const char *cpuspec, cpuset_t *cpumask)
147224698Sattilio{
148224698Sattilio	int cpu;
149224698Sattilio	const char *s;
150224698Sattilio	char *end;
151224698Sattilio
152224698Sattilio	CPU_ZERO(cpumask);
153224698Sattilio	s = cpuspec;
154224698Sattilio
155224698Sattilio	do {
156224698Sattilio		cpu = strtol(s, &end, 0);
157224698Sattilio		if (cpu < 0 || end == s)
158227524Sobrien			errx(EX_USAGE,
159227524Sobrien			    "ERROR: Illegal CPU specification \"%s\".",
160227524Sobrien			    cpuspec);
161224698Sattilio		CPU_SET(cpu, cpumask);
162224698Sattilio		s = end + strspn(end, ", \t");
163224698Sattilio	} while (*s);
164224698Sattilio}
165224698Sattilio
166168949Sjkoshyvoid
167203790Sfabientpmcstat_attach_pmcs(void)
168168949Sjkoshy{
169168949Sjkoshy	struct pmcstat_ev *ev;
170169069Sjkoshy	struct pmcstat_target *pt;
171169069Sjkoshy	int count;
172145256Sjkoshy
173169069Sjkoshy	/* Attach all process PMCs to target processes. */
174169069Sjkoshy	count = 0;
175203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
176169069Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
177169069Sjkoshy			continue;
178203790Sfabient		SLIST_FOREACH(pt, &args.pa_targets, pt_next)
179169069Sjkoshy			if (pmc_attach(ev->ev_pmcid, pt->pt_pid) == 0)
180169069Sjkoshy				count++;
181169069Sjkoshy			else if (errno != ESRCH)
182227524Sobrien				err(EX_OSERR,
183227524Sobrien"ERROR: cannot attach pmc \"%s\" to process %d",
184227524Sobrien				    ev->ev_name, (int)pt->pt_pid);
185169069Sjkoshy	}
186168949Sjkoshy
187169069Sjkoshy	if (count == 0)
188169069Sjkoshy		errx(EX_DATAERR, "ERROR: No processes were attached to.");
189168949Sjkoshy}
190168949Sjkoshy
191168949Sjkoshy
192145256Sjkoshyvoid
193203790Sfabientpmcstat_cleanup(void)
194145256Sjkoshy{
195145256Sjkoshy	struct pmcstat_ev *ev, *tmp;
196145256Sjkoshy
197145256Sjkoshy	/* release allocated PMCs. */
198203790Sfabient	STAILQ_FOREACH_SAFE(ev, &args.pa_events, ev_next, tmp)
199145256Sjkoshy	    if (ev->ev_pmcid != PMC_ID_INVALID) {
200185079Sjkoshy		if (pmc_stop(ev->ev_pmcid) < 0)
201227524Sobrien			err(EX_OSERR, "ERROR: cannot stop pmc 0x%x \"%s\"",
202227524Sobrien			    ev->ev_pmcid, ev->ev_name);
203145256Sjkoshy		if (pmc_release(ev->ev_pmcid) < 0)
204227524Sobrien			err(EX_OSERR, "ERROR: cannot release pmc 0x%x \"%s\"",
205227524Sobrien			    ev->ev_pmcid, ev->ev_name);
206145256Sjkoshy		free(ev->ev_name);
207145256Sjkoshy		free(ev->ev_spec);
208203790Sfabient		STAILQ_REMOVE(&args.pa_events, ev, pmcstat_ev, ev_next);
209145256Sjkoshy		free(ev);
210145256Sjkoshy	    }
211147191Sjkoshy
212147863Sjkoshy	/* de-configure the log file if present. */
213203790Sfabient	if (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
214147863Sjkoshy		(void) pmc_configure_logfile(-1);
215147863Sjkoshy
216203790Sfabient	if (args.pa_logparser) {
217203790Sfabient		pmclog_close(args.pa_logparser);
218203790Sfabient		args.pa_logparser = NULL;
219147191Sjkoshy	}
220147708Sjkoshy
221210794Sfabient	pmcstat_shutdown_logging();
222145256Sjkoshy}
223145256Sjkoshy
224145256Sjkoshyvoid
225203790Sfabientpmcstat_create_process(void)
226168949Sjkoshy{
227168949Sjkoshy	char token;
228169069Sjkoshy	pid_t pid;
229168949Sjkoshy	struct kevent kev;
230169069Sjkoshy	struct pmcstat_target *pt;
231168949Sjkoshy
232168949Sjkoshy	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pmcstat_sockpair) < 0)
233168949Sjkoshy		err(EX_OSERR, "ERROR: cannot create socket pair");
234168949Sjkoshy
235169069Sjkoshy	switch (pid = fork()) {
236168949Sjkoshy	case -1:
237168949Sjkoshy		err(EX_OSERR, "ERROR: cannot fork");
238168949Sjkoshy		/*NOTREACHED*/
239168949Sjkoshy
240168949Sjkoshy	case 0:		/* child */
241168949Sjkoshy		(void) close(pmcstat_sockpair[PARENTSOCKET]);
242168949Sjkoshy
243168949Sjkoshy		/* Write a token to tell our parent we've started executing. */
244168949Sjkoshy		if (write(pmcstat_sockpair[CHILDSOCKET], "+", 1) != 1)
245168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot write token");
246168949Sjkoshy
247168949Sjkoshy		/* Wait for our parent to signal us to start. */
248168949Sjkoshy		if (read(pmcstat_sockpair[CHILDSOCKET], &token, 1) < 0)
249168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot read token");
250168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
251168949Sjkoshy
252168949Sjkoshy		/* exec() the program requested */
253203790Sfabient		execvp(*args.pa_argv, args.pa_argv);
254168949Sjkoshy		/* and if that fails, notify the parent */
255168949Sjkoshy		kill(getppid(), SIGCHLD);
256203790Sfabient		err(EX_OSERR, "ERROR: execvp \"%s\" failed", *args.pa_argv);
257168949Sjkoshy		/*NOTREACHED*/
258168949Sjkoshy
259168949Sjkoshy	default:	/* parent */
260168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
261168949Sjkoshy		break;
262168949Sjkoshy	}
263168949Sjkoshy
264168949Sjkoshy	/* Ask to be notified via a kevent when the target process exits. */
265169069Sjkoshy	EV_SET(&kev, pid, EVFILT_PROC, EV_ADD|EV_ONESHOT, NOTE_EXIT, 0,
266168949Sjkoshy	    NULL);
267168949Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
268169069Sjkoshy		err(EX_OSERR, "ERROR: cannot monitor child process %d", pid);
269168949Sjkoshy
270169069Sjkoshy	if ((pt = malloc(sizeof(*pt))) == NULL)
271169069Sjkoshy		errx(EX_SOFTWARE, "ERROR: Out of memory.");
272169069Sjkoshy
273169069Sjkoshy	pt->pt_pid = pid;
274203790Sfabient	SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
275169069Sjkoshy
276168949Sjkoshy	/* Wait for the child to signal that its ready to go. */
277168949Sjkoshy	if (read(pmcstat_sockpair[PARENTSOCKET], &token, 1) < 0)
278168949Sjkoshy		err(EX_OSERR, "ERROR (parent): cannot read token");
279168949Sjkoshy
280168949Sjkoshy	return;
281168949Sjkoshy}
282168949Sjkoshy
283169069Sjkoshyvoid
284203790Sfabientpmcstat_find_targets(const char *spec)
285169069Sjkoshy{
286169069Sjkoshy	int n, nproc, pid, rv;
287169069Sjkoshy	struct pmcstat_target *pt;
288169069Sjkoshy	char errbuf[_POSIX2_LINE_MAX], *end;
289169069Sjkoshy	static struct kinfo_proc *kp;
290169069Sjkoshy	regex_t reg;
291169069Sjkoshy	regmatch_t regmatch;
292169069Sjkoshy
293169069Sjkoshy	/* First check if we've been given a process id. */
294169069Sjkoshy      	pid = strtol(spec, &end, 0);
295169069Sjkoshy	if (end != spec && pid >= 0) {
296169069Sjkoshy		if ((pt = malloc(sizeof(*pt))) == NULL)
297169069Sjkoshy			goto outofmemory;
298169069Sjkoshy		pt->pt_pid = pid;
299203790Sfabient		SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
300169069Sjkoshy		return;
301169069Sjkoshy	}
302169069Sjkoshy
303169069Sjkoshy	/* Otherwise treat arg as a regular expression naming processes. */
304169069Sjkoshy	if (pmcstat_kvm == NULL) {
305169069Sjkoshy		if ((pmcstat_kvm = kvm_openfiles(NULL, "/dev/null", NULL, 0,
306169069Sjkoshy		    errbuf)) == NULL)
307169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot open kernel \"%s\"",
308169069Sjkoshy			    errbuf);
309169069Sjkoshy		if ((pmcstat_plist = kvm_getprocs(pmcstat_kvm, KERN_PROC_PROC,
310169069Sjkoshy		    0, &nproc)) == NULL)
311169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot get process list: %s",
312169069Sjkoshy			    kvm_geterr(pmcstat_kvm));
313208858Sfabient	} else
314208858Sfabient		nproc = 0;
315169069Sjkoshy
316169069Sjkoshy	if ((rv = regcomp(&reg, spec, REG_EXTENDED|REG_NOSUB)) != 0) {
317169069Sjkoshy		regerror(rv, &reg, errbuf, sizeof(errbuf));
318169069Sjkoshy		err(EX_DATAERR, "ERROR: Failed to compile regex \"%s\": %s",
319169069Sjkoshy		    spec, errbuf);
320169069Sjkoshy	}
321169069Sjkoshy
322169069Sjkoshy	for (n = 0, kp = pmcstat_plist; n < nproc; n++, kp++) {
323169069Sjkoshy		if ((rv = regexec(&reg, kp->ki_comm, 1, &regmatch, 0)) == 0) {
324169069Sjkoshy			if ((pt = malloc(sizeof(*pt))) == NULL)
325169069Sjkoshy				goto outofmemory;
326169069Sjkoshy			pt->pt_pid = kp->ki_pid;
327203790Sfabient			SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
328169069Sjkoshy		} else if (rv != REG_NOMATCH) {
329169069Sjkoshy			regerror(rv, &reg, errbuf, sizeof(errbuf));
330169069Sjkoshy			errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s",
331169069Sjkoshy			    errbuf);
332169069Sjkoshy		}
333169069Sjkoshy	}
334169069Sjkoshy
335169069Sjkoshy	regfree(&reg);
336169069Sjkoshy
337169069Sjkoshy	return;
338169069Sjkoshy
339169069Sjkoshy outofmemory:
340169069Sjkoshy	errx(EX_SOFTWARE, "Out of memory.");
341169069Sjkoshy	/*NOTREACHED*/
342169069Sjkoshy}
343169069Sjkoshy
344168949Sjkoshyvoid
345203790Sfabientpmcstat_kill_process(void)
346169069Sjkoshy{
347169069Sjkoshy	struct pmcstat_target *pt;
348169069Sjkoshy
349203790Sfabient	assert(args.pa_flags & FLAG_HAS_COMMANDLINE);
350169069Sjkoshy
351169069Sjkoshy	/*
352169069Sjkoshy	 * If a command line was specified, it would be the very first
353169069Sjkoshy	 * in the list, before any other processes specified by -t.
354169069Sjkoshy	 */
355203790Sfabient	pt = SLIST_FIRST(&args.pa_targets);
356169069Sjkoshy	assert(pt != NULL);
357169069Sjkoshy
358169069Sjkoshy	if (kill(pt->pt_pid, SIGINT) != 0)
359169069Sjkoshy		err(EX_OSERR, "ERROR: cannot signal child process");
360169069Sjkoshy}
361169069Sjkoshy
362169069Sjkoshyvoid
363203790Sfabientpmcstat_start_pmcs(void)
364145256Sjkoshy{
365145256Sjkoshy	struct pmcstat_ev *ev;
366145256Sjkoshy
367169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
368145256Sjkoshy
369145256Sjkoshy	    assert(ev->ev_pmcid != PMC_ID_INVALID);
370145256Sjkoshy
371145256Sjkoshy	    if (pmc_start(ev->ev_pmcid) < 0) {
372147191Sjkoshy	        warn("ERROR: Cannot start pmc 0x%x \"%s\"",
373145256Sjkoshy		    ev->ev_pmcid, ev->ev_name);
374203790Sfabient		pmcstat_cleanup();
375147191Sjkoshy		exit(EX_OSERR);
376145256Sjkoshy	    }
377145256Sjkoshy	}
378145256Sjkoshy
379145256Sjkoshy}
380145256Sjkoshy
381145256Sjkoshyvoid
382203790Sfabientpmcstat_print_headers(void)
383145256Sjkoshy{
384145256Sjkoshy	struct pmcstat_ev *ev;
385168949Sjkoshy	int c, w;
386145256Sjkoshy
387203790Sfabient	(void) fprintf(args.pa_printfile, PRINT_HEADER_PREFIX);
388145256Sjkoshy
389203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
390145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
391145256Sjkoshy			continue;
392145256Sjkoshy
393145256Sjkoshy		c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p';
394145256Sjkoshy
395168949Sjkoshy		if (ev->ev_fieldskip != 0)
396203790Sfabient			(void) fprintf(args.pa_printfile, "%*s",
397168949Sjkoshy			    ev->ev_fieldskip, "");
398168949Sjkoshy		w = ev->ev_fieldwidth - ev->ev_fieldskip - 2;
399168949Sjkoshy
400168949Sjkoshy		if (c == 's')
401203790Sfabient			(void) fprintf(args.pa_printfile, "s/%02d/%-*s ",
402168949Sjkoshy			    ev->ev_cpu, w-3, ev->ev_name);
403168949Sjkoshy		else
404203790Sfabient			(void) fprintf(args.pa_printfile, "p/%*s ", w,
405145256Sjkoshy			    ev->ev_name);
406145256Sjkoshy	}
407145256Sjkoshy
408203790Sfabient	(void) fflush(args.pa_printfile);
409145256Sjkoshy}
410145256Sjkoshy
411145256Sjkoshyvoid
412203790Sfabientpmcstat_print_counters(void)
413145256Sjkoshy{
414145256Sjkoshy	int extra_width;
415145256Sjkoshy	struct pmcstat_ev *ev;
416145256Sjkoshy	pmc_value_t value;
417145256Sjkoshy
418145256Sjkoshy	extra_width = sizeof(PRINT_HEADER_PREFIX) - 1;
419145256Sjkoshy
420203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
421145256Sjkoshy
422145256Sjkoshy		/* skip sampling mode counters */
423145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
424145256Sjkoshy			continue;
425145256Sjkoshy
426145256Sjkoshy		if (pmc_read(ev->ev_pmcid, &value) < 0)
427227524Sobrien			err(EX_OSERR, "ERROR: Cannot read pmc \"%s\"",
428227524Sobrien			    ev->ev_name);
429145256Sjkoshy
430203790Sfabient		(void) fprintf(args.pa_printfile, "%*ju ",
431147708Sjkoshy		    ev->ev_fieldwidth + extra_width,
432147708Sjkoshy		    (uintmax_t) ev->ev_cumulative ? value :
433147708Sjkoshy		    (value - ev->ev_saved));
434147708Sjkoshy
435145256Sjkoshy		if (ev->ev_cumulative == 0)
436145256Sjkoshy			ev->ev_saved = value;
437145256Sjkoshy		extra_width = 0;
438145256Sjkoshy	}
439145256Sjkoshy
440203790Sfabient	(void) fflush(args.pa_printfile);
441145256Sjkoshy}
442145256Sjkoshy
443145256Sjkoshy/*
444145256Sjkoshy * Print output
445145256Sjkoshy */
446145256Sjkoshy
447145256Sjkoshyvoid
448203790Sfabientpmcstat_print_pmcs(void)
449145256Sjkoshy{
450145256Sjkoshy	static int linecount = 0;
451145256Sjkoshy
452147708Sjkoshy	/* check if we need to print a header line */
453145256Sjkoshy	if (++linecount > pmcstat_displayheight) {
454203790Sfabient		(void) fprintf(args.pa_printfile, "\n");
455145256Sjkoshy		linecount = 1;
456145256Sjkoshy	}
457145256Sjkoshy	if (linecount == 1)
458203790Sfabient		pmcstat_print_headers();
459203790Sfabient	(void) fprintf(args.pa_printfile, "\n");
460145256Sjkoshy
461203790Sfabient	pmcstat_print_counters();
462145256Sjkoshy
463145256Sjkoshy	return;
464145256Sjkoshy}
465145256Sjkoshy
466145256Sjkoshy/*
467145256Sjkoshy * Do process profiling
468145256Sjkoshy *
469145256Sjkoshy * If a pid was specified, attach each allocated PMC to the target
470145256Sjkoshy * process.  Otherwise, fork a child and attach the PMCs to the child,
471145256Sjkoshy * and have the child exec() the target program.
472145256Sjkoshy */
473145256Sjkoshy
474145256Sjkoshyvoid
475168949Sjkoshypmcstat_start_process(void)
476145256Sjkoshy{
477168949Sjkoshy	/* Signal the child to proceed. */
478168949Sjkoshy	if (write(pmcstat_sockpair[PARENTSOCKET], "!", 1) != 1)
479168949Sjkoshy		err(EX_OSERR, "ERROR (parent): write of token failed");
480145256Sjkoshy
481168949Sjkoshy	(void) close(pmcstat_sockpair[PARENTSOCKET]);
482145256Sjkoshy}
483145256Sjkoshy
484145256Sjkoshyvoid
485145256Sjkoshypmcstat_show_usage(void)
486145256Sjkoshy{
487145256Sjkoshy	errx(EX_USAGE,
488145256Sjkoshy	    "[options] [commandline]\n"
489145256Sjkoshy	    "\t Measure process and/or system performance using hardware\n"
490145256Sjkoshy	    "\t performance monitoring counters.\n"
491145256Sjkoshy	    "\t Options include:\n"
492147191Sjkoshy	    "\t -C\t\t (toggle) show cumulative counts\n"
493147191Sjkoshy	    "\t -D path\t create profiles in directory \"path\"\n"
494147191Sjkoshy	    "\t -E\t\t (toggle) show counts at process exit\n"
495203790Sfabient	    "\t -F file\t write a system-wide callgraph (Kcachegrind format)"
496203790Sfabient		" to \"file\"\n"
497174396Sjkoshy	    "\t -G file\t write a system-wide callgraph to \"file\"\n"
498157144Sjkoshy	    "\t -M file\t print executable/gmon file map to \"file\"\n"
499174396Sjkoshy	    "\t -N\t\t (toggle) capture callchains\n"
500147191Sjkoshy	    "\t -O file\t send log output to \"file\"\n"
501147191Sjkoshy	    "\t -P spec\t allocate a process-private sampling PMC\n"
502147191Sjkoshy	    "\t -R file\t read events from \"file\"\n"
503147191Sjkoshy	    "\t -S spec\t allocate a system-wide sampling PMC\n"
504203790Sfabient	    "\t -T\t\t start in top mode\n"
505147191Sjkoshy	    "\t -W\t\t (toggle) show counts per context switch\n"
506265604Sscottl	    "\t -a <file>\t print sampled PCs and callgraph to \"file\"\n"
507168949Sjkoshy	    "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n"
508147191Sjkoshy	    "\t -d\t\t (toggle) track descendants\n"
509203790Sfabient	    "\t -f spec\t pass \"spec\" to as plugin option\n"
510147191Sjkoshy	    "\t -g\t\t produce gprof(1) compatible profiles\n"
511162804Sru	    "\t -k dir\t\t set the path to the kernel\n"
512266890Sgnn	    "\t -l secs\t set duration time\n"
513239571Sjimharris	    "\t -m file\t print sampled PCs to \"file\"\n"
514145256Sjkoshy	    "\t -n rate\t set sampling rate\n"
515145256Sjkoshy	    "\t -o file\t send print output to \"file\"\n"
516147191Sjkoshy	    "\t -p spec\t allocate a process-private counting PMC\n"
517157144Sjkoshy	    "\t -q\t\t suppress verbosity\n"
518157144Sjkoshy	    "\t -r fsroot\t specify FS root directory\n"
519147191Sjkoshy	    "\t -s spec\t allocate a system-wide counting PMC\n"
520183186Sjkoshy	    "\t -t process-spec attach to running processes matching "
521183186Sjkoshy		"\"process-spec\"\n"
522157144Sjkoshy	    "\t -v\t\t increase verbosity\n"
523174396Sjkoshy	    "\t -w secs\t set printing time interval\n"
524174396Sjkoshy	    "\t -z depth\t limit callchain display depth"
525145256Sjkoshy	);
526145256Sjkoshy}
527145256Sjkoshy
528145256Sjkoshy/*
529203790Sfabient * At exit handler for top mode
530203790Sfabient */
531203790Sfabient
532203790Sfabientvoid
533203790Sfabientpmcstat_topexit(void)
534203790Sfabient{
535203790Sfabient	if (!args.pa_toptty)
536203790Sfabient		return;
537203790Sfabient
538203790Sfabient	/*
539203790Sfabient	 * Shutdown ncurses.
540203790Sfabient	 */
541203790Sfabient	clrtoeol();
542203790Sfabient	refresh();
543203790Sfabient	endwin();
544203790Sfabient}
545203790Sfabient
546203790Sfabient/*
547145256Sjkoshy * Main
548145256Sjkoshy */
549145256Sjkoshy
550145256Sjkoshyint
551145256Sjkoshymain(int argc, char **argv)
552145256Sjkoshy{
553224698Sattilio	cpuset_t cpumask;
554145256Sjkoshy	double interval;
555266890Sgnn	double duration;
556224698Sattilio	int hcpu, option, npmc, ncpu;
557230350Seadler	int c, check_driver_stats, current_sampling_count;
558174396Sjkoshy	int do_callchain, do_descendants, do_logproccsw, do_logprocexit;
559226514Sfabient	int do_print, do_read;
560168949Sjkoshy	size_t dummy;
561174396Sjkoshy	int graphdepth;
562210794Sfabient	int pipefd[2], rfd;
563147191Sjkoshy	int use_cumulative_counts;
564203790Sfabient	short cf, cb;
565157144Sjkoshy	char *end, *tmp;
566174396Sjkoshy	const char *errmsg, *graphfilename;
567147191Sjkoshy	enum pmcstat_state runstate;
568151542Sjkoshy	struct pmc_driverstats ds_start, ds_end;
569145256Sjkoshy	struct pmcstat_ev *ev;
570145256Sjkoshy	struct sigaction sa;
571145256Sjkoshy	struct kevent kev;
572145256Sjkoshy	struct winsize ws;
573147708Sjkoshy	struct stat sb;
574157144Sjkoshy	char buffer[PATH_MAX];
575145256Sjkoshy
576151542Sjkoshy	check_driver_stats      = 0;
577145256Sjkoshy	current_sampling_count  = DEFAULT_SAMPLE_COUNT;
578174396Sjkoshy	do_callchain		= 1;
579145256Sjkoshy	do_descendants          = 0;
580147191Sjkoshy	do_logproccsw           = 0;
581147191Sjkoshy	do_logprocexit          = 0;
582145256Sjkoshy	use_cumulative_counts   = 0;
583174396Sjkoshy	graphfilename		= "-";
584147191Sjkoshy	args.pa_required	= 0;
585145256Sjkoshy	args.pa_flags		= 0;
586157144Sjkoshy	args.pa_verbosity	= 1;
587147708Sjkoshy	args.pa_logfd		= -1;
588157144Sjkoshy	args.pa_fsroot		= "";
589157144Sjkoshy	args.pa_kernel		= strdup("/boot/kernel");
590147708Sjkoshy	args.pa_samplesdir	= ".";
591147708Sjkoshy	args.pa_printfile	= stderr;
592174396Sjkoshy	args.pa_graphdepth	= DEFAULT_CALLGRAPH_DEPTH;
593174396Sjkoshy	args.pa_graphfile	= NULL;
594145256Sjkoshy	args.pa_interval	= DEFAULT_WAIT_INTERVAL;
595157144Sjkoshy	args.pa_mapfilename	= NULL;
596174396Sjkoshy	args.pa_inputpath	= NULL;
597174396Sjkoshy	args.pa_outputpath	= NULL;
598203790Sfabient	args.pa_pplugin		= PMCSTAT_PL_NONE;
599203790Sfabient	args.pa_plugin		= PMCSTAT_PL_NONE;
600203790Sfabient	args.pa_ctdumpinstr	= 1;
601203790Sfabient	args.pa_topmode		= PMCSTAT_TOP_DELTA;
602203790Sfabient	args.pa_toptty		= 0;
603203790Sfabient	args.pa_topcolor	= 0;
604203790Sfabient	args.pa_mergepmc	= 0;
605266890Sgnn	args.pa_duration	= 0.0;
606169069Sjkoshy	STAILQ_INIT(&args.pa_events);
607169069Sjkoshy	SLIST_INIT(&args.pa_targets);
608153704Sjkoshy	bzero(&ds_start, sizeof(ds_start));
609153704Sjkoshy	bzero(&ds_end, sizeof(ds_end));
610145256Sjkoshy	ev = NULL;
611224698Sattilio	CPU_ZERO(&cpumask);
612145256Sjkoshy
613174396Sjkoshy	/*
614174396Sjkoshy	 * The initial CPU mask specifies all non-halted CPUS in the
615174396Sjkoshy	 * system.
616174396Sjkoshy	 */
617174396Sjkoshy	dummy = sizeof(int);
618168949Sjkoshy	if (sysctlbyname("hw.ncpu", &ncpu, &dummy, NULL, 0) < 0)
619174396Sjkoshy		err(EX_OSERR, "ERROR: Cannot determine the number of CPUs");
620224698Sattilio	for (hcpu = 0; hcpu < ncpu; hcpu++)
621224698Sattilio		CPU_SET(hcpu, &cpumask);
622168949Sjkoshy
623157144Sjkoshy	while ((option = getopt(argc, argv,
624266890Sgnn	    "CD:EF:G:M:NO:P:R:S:TWa:c:df:gk:l:m:n:o:p:qr:s:t:vw:z:")) != -1)
625145256Sjkoshy		switch (option) {
626265604Sscottl		case 'a':	/* Annotate + callgraph */
627265604Sscottl			args.pa_flags |= FLAG_DO_ANNOTATE;
628265604Sscottl			args.pa_plugin = PMCSTAT_PL_ANNOTATE_CG;
629265604Sscottl			graphfilename  = optarg;
630265604Sscottl			break;
631265604Sscottl
632145256Sjkoshy		case 'C':	/* cumulative values */
633145256Sjkoshy			use_cumulative_counts = !use_cumulative_counts;
634147191Sjkoshy			args.pa_required |= FLAG_HAS_COUNTING_PMCS;
635145256Sjkoshy			break;
636145256Sjkoshy
637145256Sjkoshy		case 'c':	/* CPU */
638168949Sjkoshy
639224698Sattilio			if (optarg[0] == '*' && optarg[1] == '\0') {
640224698Sattilio				for (hcpu = 0; hcpu < ncpu; hcpu++)
641224698Sattilio					CPU_SET(hcpu, &cpumask);
642224698Sattilio			} else
643224698Sattilio				pmcstat_get_cpumask(optarg, &cpumask);
644168949Sjkoshy
645210797Sfabient			args.pa_flags	 |= FLAGS_HAS_CPUMASK;
646147191Sjkoshy			args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
647145256Sjkoshy			break;
648145256Sjkoshy
649147708Sjkoshy		case 'D':
650147708Sjkoshy			if (stat(optarg, &sb) < 0)
651147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
652147708Sjkoshy				    optarg);
653147708Sjkoshy			if (!S_ISDIR(sb.st_mode))
654227524Sobrien				errx(EX_USAGE,
655227524Sobrien				    "ERROR: \"%s\" is not a directory.",
656227524Sobrien				    optarg);
657147708Sjkoshy			args.pa_samplesdir = optarg;
658147708Sjkoshy			args.pa_flags     |= FLAG_HAS_SAMPLESDIR;
659147708Sjkoshy			args.pa_required  |= FLAG_DO_GPROF;
660147708Sjkoshy			break;
661147708Sjkoshy
662145256Sjkoshy		case 'd':	/* toggle descendents */
663145256Sjkoshy			do_descendants = !do_descendants;
664147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
665145256Sjkoshy			break;
666145256Sjkoshy
667203790Sfabient		case 'F':	/* produce a system-wide calltree */
668203790Sfabient			args.pa_flags |= FLAG_DO_CALLGRAPHS;
669203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLTREE;
670203790Sfabient			graphfilename = optarg;
671203790Sfabient			break;
672203790Sfabient
673203790Sfabient		case 'f':	/* plugins options */
674203790Sfabient			if (args.pa_plugin == PMCSTAT_PL_NONE)
675203790Sfabient				err(EX_USAGE, "ERROR: Need -g/-G/-m/-T.");
676203790Sfabient			pmcstat_pluginconfigure_log(optarg);
677203790Sfabient			break;
678203790Sfabient
679174396Sjkoshy		case 'G':	/* produce a system-wide callgraph */
680174396Sjkoshy			args.pa_flags |= FLAG_DO_CALLGRAPHS;
681203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
682174396Sjkoshy			graphfilename = optarg;
683174396Sjkoshy			break;
684174396Sjkoshy
685147191Sjkoshy		case 'g':	/* produce gprof compatible profiles */
686147191Sjkoshy			args.pa_flags |= FLAG_DO_GPROF;
687203790Sfabient			args.pa_pplugin = PMCSTAT_PL_CALLGRAPH;
688203790Sfabient			args.pa_plugin	= PMCSTAT_PL_GPROF;
689147191Sjkoshy			break;
690147191Sjkoshy
691147708Sjkoshy		case 'k':	/* pathname to the kernel */
692157144Sjkoshy			free(args.pa_kernel);
693157144Sjkoshy			args.pa_kernel = strdup(optarg);
694174396Sjkoshy			args.pa_required |= FLAG_DO_ANALYSIS;
695147708Sjkoshy			args.pa_flags    |= FLAG_HAS_KERNELPATH;
696147191Sjkoshy			break;
697147191Sjkoshy
698266890Sgnn		case 'l':	/* time duration in seconds */
699266890Sgnn			duration = strtod(optarg, &end);
700266890Sgnn			if (*end != '\0' || duration <= 0)
701266890Sgnn				errx(EX_USAGE, "ERROR: Illegal duration time "
702266890Sgnn				    "value \"%s\".", optarg);
703266890Sgnn			args.pa_flags |= FLAG_HAS_DURATION;
704266890Sgnn			args.pa_duration = duration;
705266890Sgnn			break;
706266890Sgnn
707185322Sattilio		case 'm':
708203790Sfabient			args.pa_flags |= FLAG_DO_ANNOTATE;
709203790Sfabient			args.pa_plugin = PMCSTAT_PL_ANNOTATE;
710203790Sfabient			graphfilename  = optarg;
711185322Sattilio			break;
712185322Sattilio
713147191Sjkoshy		case 'E':	/* log process exit */
714147191Sjkoshy			do_logprocexit = !do_logprocexit;
715147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
716147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
717147191Sjkoshy			break;
718147191Sjkoshy
719157144Sjkoshy		case 'M':	/* mapfile */
720157144Sjkoshy			args.pa_mapfilename = optarg;
721157144Sjkoshy			break;
722157144Sjkoshy
723174396Sjkoshy		case 'N':
724174396Sjkoshy			do_callchain = !do_callchain;
725174396Sjkoshy			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
726174396Sjkoshy			break;
727174396Sjkoshy
728145256Sjkoshy		case 'p':	/* process virtual counting PMC */
729145256Sjkoshy		case 's':	/* system-wide counting PMC */
730145256Sjkoshy		case 'P':	/* process virtual sampling PMC */
731145256Sjkoshy		case 'S':	/* system-wide sampling PMC */
732145256Sjkoshy			if ((ev = malloc(sizeof(*ev))) == NULL)
733147191Sjkoshy				errx(EX_SOFTWARE, "ERROR: Out of memory.");
734145256Sjkoshy
735145256Sjkoshy			switch (option) {
736145256Sjkoshy			case 'p': ev->ev_mode = PMC_MODE_TC; break;
737145256Sjkoshy			case 's': ev->ev_mode = PMC_MODE_SC; break;
738145256Sjkoshy			case 'P': ev->ev_mode = PMC_MODE_TS; break;
739145256Sjkoshy			case 'S': ev->ev_mode = PMC_MODE_SS; break;
740145256Sjkoshy			}
741145256Sjkoshy
742147191Sjkoshy			if (option == 'P' || option == 'p') {
743147191Sjkoshy				args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
744147708Sjkoshy				args.pa_required |= (FLAG_HAS_COMMANDLINE |
745169069Sjkoshy				    FLAG_HAS_TARGET);
746147191Sjkoshy			}
747145256Sjkoshy
748147191Sjkoshy			if (option == 'P' || option == 'S') {
749147191Sjkoshy				args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
750147708Sjkoshy				args.pa_required |= (FLAG_HAS_PIPE |
751147708Sjkoshy				    FLAG_HAS_OUTPUT_LOGFILE);
752147191Sjkoshy			}
753145256Sjkoshy
754145256Sjkoshy			if (option == 'p' || option == 's')
755147191Sjkoshy				args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
756145256Sjkoshy
757147191Sjkoshy			if (option == 's' || option == 'S')
758147191Sjkoshy				args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
759147191Sjkoshy
760145256Sjkoshy			ev->ev_spec  = strdup(optarg);
761145256Sjkoshy
762145256Sjkoshy			if (option == 'S' || option == 'P')
763145256Sjkoshy				ev->ev_count = current_sampling_count;
764145256Sjkoshy			else
765145256Sjkoshy				ev->ev_count = -1;
766145256Sjkoshy
767224698Sattilio			if (option == 'S' || option == 's') {
768224698Sattilio				hcpu = sizeof(cpumask) * NBBY;
769224698Sattilio				for (hcpu--; hcpu >= 0; hcpu--)
770224698Sattilio					if (CPU_ISSET(hcpu, &cpumask))
771224698Sattilio						break;
772224698Sattilio				ev->ev_cpu = hcpu;
773224698Sattilio			} else
774145256Sjkoshy				ev->ev_cpu = PMC_CPU_ANY;
775145256Sjkoshy
776147191Sjkoshy			ev->ev_flags = 0;
777174396Sjkoshy			if (do_callchain)
778174396Sjkoshy				ev->ev_flags |= PMC_F_CALLCHAIN;
779147191Sjkoshy			if (do_descendants)
780147191Sjkoshy				ev->ev_flags |= PMC_F_DESCENDANTS;
781147191Sjkoshy			if (do_logprocexit)
782147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCEXIT;
783147191Sjkoshy			if (do_logproccsw)
784147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCCSW;
785147191Sjkoshy
786145256Sjkoshy			ev->ev_cumulative  = use_cumulative_counts;
787145256Sjkoshy
788145256Sjkoshy			ev->ev_saved = 0LL;
789145256Sjkoshy			ev->ev_pmcid = PMC_ID_INVALID;
790145256Sjkoshy
791145256Sjkoshy			/* extract event name */
792145256Sjkoshy			c = strcspn(optarg, ", \t");
793145256Sjkoshy			ev->ev_name = malloc(c + 1);
794145256Sjkoshy			(void) strncpy(ev->ev_name, optarg, c);
795145256Sjkoshy			*(ev->ev_name + c) = '\0';
796145256Sjkoshy
797169069Sjkoshy			STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
798145256Sjkoshy
799224698Sattilio			if (option == 's' || option == 'S') {
800224698Sattilio				hcpu = CPU_ISSET(ev->ev_cpu, &cpumask);
801224698Sattilio				CPU_CLR(ev->ev_cpu, &cpumask);
802224698Sattilio				pmcstat_clone_event_descriptor(ev, &cpumask);
803224698Sattilio				if (hcpu != 0)
804224698Sattilio					CPU_SET(ev->ev_cpu, &cpumask);
805224698Sattilio			}
806168949Sjkoshy
807145256Sjkoshy			break;
808145256Sjkoshy
809145256Sjkoshy		case 'n':	/* sampling count */
810145256Sjkoshy			current_sampling_count = strtol(optarg, &end, 0);
811145256Sjkoshy			if (*end != '\0' || current_sampling_count <= 0)
812145256Sjkoshy				errx(EX_USAGE,
813147191Sjkoshy				    "ERROR: Illegal count value \"%s\".",
814145256Sjkoshy				    optarg);
815147191Sjkoshy			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
816145256Sjkoshy			break;
817145256Sjkoshy
818145256Sjkoshy		case 'o':	/* outputfile */
819226986Sfabient			if (args.pa_printfile != NULL &&
820226986Sfabient			    args.pa_printfile != stdout &&
821226986Sfabient			    args.pa_printfile != stderr)
822147708Sjkoshy				(void) fclose(args.pa_printfile);
823147708Sjkoshy			if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
824227524Sobrien				errx(EX_OSERR,
825227524Sobrien				    "ERROR: cannot open \"%s\" for writing.",
826227524Sobrien				    optarg);
827147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
828147191Sjkoshy			break;
829145256Sjkoshy
830145256Sjkoshy		case 'O':	/* sampling output */
831147708Sjkoshy			if (args.pa_outputpath)
832227524Sobrien				errx(EX_USAGE,
833227524Sobrien"ERROR: option -O may only be specified once.");
834147708Sjkoshy			args.pa_outputpath = optarg;
835147708Sjkoshy			args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
836145256Sjkoshy			break;
837145256Sjkoshy
838157144Sjkoshy		case 'q':	/* quiet mode */
839157144Sjkoshy			args.pa_verbosity = 0;
840157144Sjkoshy			break;
841157144Sjkoshy
842157144Sjkoshy		case 'r':	/* root FS path */
843157144Sjkoshy			args.pa_fsroot = optarg;
844157144Sjkoshy			break;
845157144Sjkoshy
846147708Sjkoshy		case 'R':	/* read an existing log file */
847174396Sjkoshy			if (args.pa_inputpath != NULL)
848227524Sobrien				errx(EX_USAGE,
849227524Sobrien"ERROR: option -R may only be specified once.");
850147708Sjkoshy			args.pa_inputpath = optarg;
851147708Sjkoshy			if (args.pa_printfile == stderr)
852147708Sjkoshy				args.pa_printfile = stdout;
853147708Sjkoshy			args.pa_flags |= FLAG_READ_LOGFILE;
854147708Sjkoshy			break;
855147708Sjkoshy
856169069Sjkoshy		case 't':	/* target pid or process name */
857203790Sfabient			pmcstat_find_targets(optarg);
858145256Sjkoshy
859169069Sjkoshy			args.pa_flags |= FLAG_HAS_TARGET;
860147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
861145256Sjkoshy			break;
862145256Sjkoshy
863203790Sfabient		case 'T':	/* top mode */
864203790Sfabient			args.pa_flags |= FLAG_DO_TOP;
865203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
866203790Sfabient			args.pa_ctdumpinstr = 0;
867203790Sfabient			args.pa_mergepmc = 1;
868203790Sfabient			if (args.pa_printfile == stderr)
869203790Sfabient				args.pa_printfile = stdout;
870203790Sfabient			break;
871203790Sfabient
872157144Sjkoshy		case 'v':	/* verbose */
873157144Sjkoshy			args.pa_verbosity++;
874157144Sjkoshy			break;
875157144Sjkoshy
876145256Sjkoshy		case 'w':	/* wait interval */
877145256Sjkoshy			interval = strtod(optarg, &end);
878145256Sjkoshy			if (*end != '\0' || interval <= 0)
879227524Sobrien				errx(EX_USAGE,
880227524Sobrien"ERROR: Illegal wait interval value \"%s\".",
881227524Sobrien				    optarg);
882145256Sjkoshy			args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
883145256Sjkoshy			args.pa_interval = interval;
884147191Sjkoshy			break;
885145256Sjkoshy
886147191Sjkoshy		case 'W':	/* toggle LOG_CSW */
887147191Sjkoshy			do_logproccsw = !do_logproccsw;
888147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
889147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
890145256Sjkoshy			break;
891145256Sjkoshy
892174396Sjkoshy		case 'z':
893174396Sjkoshy			graphdepth = strtod(optarg, &end);
894174396Sjkoshy			if (*end != '\0' || graphdepth <= 0)
895227524Sobrien				errx(EX_USAGE,
896227524Sobrien				    "ERROR: Illegal callchain depth \"%s\".",
897227524Sobrien				    optarg);
898174396Sjkoshy			args.pa_graphdepth = graphdepth;
899174396Sjkoshy			args.pa_required |= FLAG_DO_CALLGRAPHS;
900174396Sjkoshy			break;
901174396Sjkoshy
902145256Sjkoshy		case '?':
903145256Sjkoshy		default:
904145256Sjkoshy			pmcstat_show_usage();
905145256Sjkoshy			break;
906145256Sjkoshy
907145256Sjkoshy		}
908145256Sjkoshy
909145256Sjkoshy	args.pa_argc = (argc -= optind);
910145256Sjkoshy	args.pa_argv = (argv += optind);
911145256Sjkoshy
912210797Sfabient	/* If we read from logfile and no specified CPU mask use
913210797Sfabient	 * the maximum CPU count.
914210797Sfabient	 */
915210797Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) &&
916210797Sfabient	    (args.pa_flags & FLAGS_HAS_CPUMASK) == 0)
917224698Sattilio		CPU_FILL(&cpumask);
918210797Sfabient
919174396Sjkoshy	args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
920174396Sjkoshy
921147708Sjkoshy	if (argc)	/* command line present */
922147708Sjkoshy		args.pa_flags |= FLAG_HAS_COMMANDLINE;
923145256Sjkoshy
924185322Sattilio	if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
925203790Sfabient	    FLAG_DO_ANNOTATE | FLAG_DO_TOP))
926174396Sjkoshy		args.pa_flags |= FLAG_DO_ANALYSIS;
927174396Sjkoshy
928145256Sjkoshy	/*
929145256Sjkoshy	 * Check invocation syntax.
930145256Sjkoshy	 */
931145256Sjkoshy
932147708Sjkoshy	/* disallow -O and -R together */
933147708Sjkoshy	if (args.pa_outputpath && args.pa_inputpath)
934227524Sobrien		errx(EX_USAGE,
935227524Sobrien		    "ERROR: options -O and -R are mutually exclusive.");
936147708Sjkoshy
937266890Sgnn	/* disallow -T and -l together */
938266890Sgnn	if ((args.pa_flags & FLAG_HAS_DURATION) &&
939266890Sgnn	    (args.pa_flags & FLAG_DO_TOP))
940266890Sgnn		errx(EX_USAGE, "ERROR: options -T and -l are mutually "
941266890Sgnn		    "exclusive.");
942266890Sgnn
943185322Sattilio	/* -m option is allowed with -R only. */
944203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
945265604Sscottl		errx(EX_USAGE, "ERROR: option %s requires an input file",
946265604Sscottl		    args.pa_plugin == PMCSTAT_PL_ANNOTATE ? "-m" : "-a");
947185322Sattilio
948185322Sattilio	/* -m option is not allowed combined with -g or -G. */
949203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE &&
950185322Sattilio	    args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
951227524Sobrien		errx(EX_USAGE,
952227524Sobrien		    "ERROR: option -m and -g | -G are mutually exclusive");
953185322Sattilio
954147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
955147191Sjkoshy		errmsg = NULL;
956147708Sjkoshy		if (args.pa_flags & FLAG_HAS_COMMANDLINE)
957147191Sjkoshy			errmsg = "a command line specification";
958169069Sjkoshy		else if (args.pa_flags & FLAG_HAS_TARGET)
959147191Sjkoshy			errmsg = "option -t";
960169069Sjkoshy		else if (!STAILQ_EMPTY(&args.pa_events))
961147191Sjkoshy			errmsg = "a PMC event specification";
962147191Sjkoshy		if (errmsg)
963227524Sobrien			errx(EX_USAGE,
964227524Sobrien			    "ERROR: option -R may not be used with %s.",
965227524Sobrien			    errmsg);
966169069Sjkoshy	} else if (STAILQ_EMPTY(&args.pa_events))
967147708Sjkoshy		/* All other uses require a PMC spec. */
968145256Sjkoshy		pmcstat_show_usage();
969145256Sjkoshy
970147191Sjkoshy	/* check for -t pid without a process PMC spec */
971169069Sjkoshy	if ((args.pa_required & FLAG_HAS_TARGET) &&
972147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
973227524Sobrien		errx(EX_USAGE,
974227524Sobrien"ERROR: option -t requires a process mode PMC to be specified."
975227524Sobrien		    );
976147191Sjkoshy
977147191Sjkoshy	/* check for process-mode options without a command or -t pid */
978147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
979169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
980227524Sobrien		errx(EX_USAGE,
981227524Sobrien"ERROR: options -d, -E, -p, -P, and -W require a command line or target process."
982227524Sobrien		    );
983147191Sjkoshy
984147191Sjkoshy	/* check for -p | -P without a target process of some sort */
985169069Sjkoshy	if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
986169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
987227524Sobrien		errx(EX_USAGE,
988227524Sobrien"ERROR: options -P and -p require a target process or a command line."
989227524Sobrien		    );
990147191Sjkoshy
991147191Sjkoshy	/* check for process-mode options without a process-mode PMC */
992147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
993147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
994227524Sobrien		errx(EX_USAGE,
995227524Sobrien"ERROR: options -d, -E, and -W require a process mode PMC to be specified."
996227524Sobrien		    );
997147191Sjkoshy
998174396Sjkoshy	/* check for -c cpu with no system mode PMCs or logfile. */
999147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
1000174396Sjkoshy	    (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
1001174396Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1002227524Sobrien		errx(EX_USAGE,
1003227524Sobrien"ERROR: option -c requires at least one system mode PMC to be specified."
1004227524Sobrien		    );
1005147191Sjkoshy
1006147191Sjkoshy	/* check for counting mode options without a counting PMC */
1007147191Sjkoshy	if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
1008147191Sjkoshy	    (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
1009227524Sobrien		errx(EX_USAGE,
1010227524Sobrien"ERROR: options -C, -W and -o require at least one counting mode PMC to be specified."
1011227524Sobrien		    );
1012147191Sjkoshy
1013147191Sjkoshy	/* check for sampling mode options without a sampling PMC spec */
1014147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
1015147191Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
1016227524Sobrien		errx(EX_USAGE,
1017227524Sobrien"ERROR: options -N, -n and -O require at least one sampling mode PMC to be specified."
1018227524Sobrien		    );
1019147191Sjkoshy
1020203790Sfabient	/* check if -g/-G/-m/-T are being used correctly */
1021174396Sjkoshy	if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
1022147708Sjkoshy	    !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
1023227524Sobrien		errx(EX_USAGE,
1024227524Sobrien"ERROR: options -g/-G/-m/-T require sampling PMCs or -R to be specified."
1025227524Sobrien		    );
1026147708Sjkoshy
1027147191Sjkoshy	/* check if -O was spuriously specified */
1028147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
1029147708Sjkoshy	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
1030147191Sjkoshy		errx(EX_USAGE,
1031227524Sobrien"ERROR: option -O is used only with options -E, -P, -S and -W."
1032227524Sobrien		    );
1033147191Sjkoshy
1034203790Sfabient	/* -k kernel path require -g/-G/-m/-T or -R */
1035147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
1036174396Sjkoshy	    (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
1037157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1038203790Sfabient	    errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
1039147708Sjkoshy
1040174396Sjkoshy	/* -D only applies to gprof output mode (-g) */
1041147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
1042174396Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0)
1043174396Sjkoshy	    errx(EX_USAGE, "ERROR: option -D is only used with -g.");
1044147708Sjkoshy
1045157144Sjkoshy	/* -M mapfile requires -g or -R */
1046157144Sjkoshy	if (args.pa_mapfilename != NULL &&
1047157144Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0 &&
1048157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1049157144Sjkoshy	    errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
1050157144Sjkoshy
1051147708Sjkoshy	/*
1052147708Sjkoshy	 * Disallow textual output of sampling PMCs if counting PMCs
1053147708Sjkoshy	 * have also been asked for, mostly because the combined output
1054147708Sjkoshy	 * is difficult to make sense of.
1055147708Sjkoshy	 */
1056147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1057147708Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1058168927Sjkoshy	    ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
1059227524Sobrien		errx(EX_USAGE,
1060227524Sobrien"ERROR: option -O is required if counting and sampling PMCs are specified together."
1061227524Sobrien		    );
1062147708Sjkoshy
1063157144Sjkoshy	/*
1064174396Sjkoshy	 * Check if "-k kerneldir" was specified, and if whether
1065227489Seadler	 * 'kerneldir' actually refers to a file.  If so, use
1066174396Sjkoshy	 * `dirname path` to determine the kernel directory.
1067157144Sjkoshy	 */
1068157144Sjkoshy	if (args.pa_flags & FLAG_HAS_KERNELPATH) {
1069157144Sjkoshy		(void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
1070157144Sjkoshy		    args.pa_kernel);
1071157144Sjkoshy		if (stat(buffer, &sb) < 0)
1072157144Sjkoshy			err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
1073157144Sjkoshy			    buffer);
1074157144Sjkoshy		if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
1075157144Sjkoshy			errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
1076157144Sjkoshy			    buffer);
1077157144Sjkoshy		if (!S_ISDIR(sb.st_mode)) {
1078157144Sjkoshy			tmp = args.pa_kernel;
1079157144Sjkoshy			args.pa_kernel = strdup(dirname(args.pa_kernel));
1080157144Sjkoshy			free(tmp);
1081157144Sjkoshy			(void) snprintf(buffer, sizeof(buffer), "%s%s",
1082157144Sjkoshy			    args.pa_fsroot, args.pa_kernel);
1083157144Sjkoshy			if (stat(buffer, &sb) < 0)
1084157144Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
1085157144Sjkoshy				    buffer);
1086157144Sjkoshy			if (!S_ISDIR(sb.st_mode))
1087227524Sobrien				errx(EX_USAGE,
1088227524Sobrien				    "ERROR: \"%s\" is not a directory.",
1089227524Sobrien				    buffer);
1090157144Sjkoshy		}
1091157144Sjkoshy	}
1092168949Sjkoshy
1093174396Sjkoshy	/*
1094174396Sjkoshy	 * If we have a callgraph be created, select the outputfile.
1095174396Sjkoshy	 */
1096174396Sjkoshy	if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
1097174396Sjkoshy		if (strcmp(graphfilename, "-") == 0)
1098174396Sjkoshy		    args.pa_graphfile = args.pa_printfile;
1099174396Sjkoshy		else {
1100174396Sjkoshy			args.pa_graphfile = fopen(graphfilename, "w");
1101174396Sjkoshy			if (args.pa_graphfile == NULL)
1102227524Sobrien				err(EX_OSERR,
1103227524Sobrien				    "ERROR: cannot open \"%s\" for writing",
1104227524Sobrien				    graphfilename);
1105174396Sjkoshy		}
1106174396Sjkoshy	}
1107203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE) {
1108185322Sattilio		args.pa_graphfile = fopen(graphfilename, "w");
1109185322Sattilio		if (args.pa_graphfile == NULL)
1110185322Sattilio			err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
1111185322Sattilio			    graphfilename);
1112185322Sattilio	}
1113174396Sjkoshy
1114210794Sfabient	/* if we've been asked to process a log file, skip init */
1115210794Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) {
1116210794Sfabient		if (pmc_init() < 0)
1117210794Sfabient			err(EX_UNAVAILABLE,
1118227524Sobrien			    "ERROR: Initialization of the pmc(3) library failed"
1119227524Sobrien			    );
1120210794Sfabient
1121210794Sfabient		if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1122227524Sobrien			err(EX_OSERR,
1123227524Sobrien"ERROR: Cannot determine the number of PMCs on CPU %d",
1124227524Sobrien			    0);
1125210794Sfabient	}
1126210794Sfabient
1127210794Sfabient	/* Allocate a kqueue */
1128210794Sfabient	if ((pmcstat_kq = kqueue()) < 0)
1129210794Sfabient		err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1130210794Sfabient
1131210794Sfabient	/* Setup the logfile as the source. */
1132147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
1133147708Sjkoshy		/*
1134147708Sjkoshy		 * Print the log in textual form if we haven't been
1135174396Sjkoshy		 * asked to generate profiling information.
1136147708Sjkoshy		 */
1137174396Sjkoshy		if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1138147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
1139147708Sjkoshy
1140203790Sfabient		pmcstat_initialize_logging();
1141210794Sfabient		rfd = pmcstat_open_log(args.pa_inputpath,
1142157406Sjkoshy		    PMCSTAT_OPEN_FOR_READ);
1143210794Sfabient		if ((args.pa_logparser = pmclog_open(rfd)) == NULL)
1144147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot create parser");
1145210794Sfabient		if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0)
1146210794Sfabient			err(EX_OSERR, "ERROR: fcntl(2) failed");
1147210794Sfabient		EV_SET(&kev, rfd, EVFILT_READ, EV_ADD,
1148210794Sfabient		    0, 0, NULL);
1149210794Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1150210794Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1151147191Sjkoshy	}
1152145256Sjkoshy	/*
1153147708Sjkoshy	 * Configure the specified log file or setup a default log
1154147708Sjkoshy	 * consumer via a pipe.
1155147708Sjkoshy	 */
1156147708Sjkoshy	if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1157157406Sjkoshy		if (args.pa_outputpath)
1158157406Sjkoshy			args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1159157406Sjkoshy			    PMCSTAT_OPEN_FOR_WRITE);
1160157406Sjkoshy		else {
1161147708Sjkoshy			/*
1162147708Sjkoshy			 * process the log on the fly by reading it in
1163147708Sjkoshy			 * through a pipe.
1164147708Sjkoshy			 */
1165147708Sjkoshy			if (pipe(pipefd) < 0)
1166147708Sjkoshy				err(EX_OSERR, "ERROR: pipe(2) failed");
1167147708Sjkoshy
1168147708Sjkoshy			if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1169147708Sjkoshy				err(EX_OSERR, "ERROR: fcntl(2) failed");
1170147708Sjkoshy
1171147708Sjkoshy			EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1172147708Sjkoshy			    0, 0, NULL);
1173147708Sjkoshy
1174147708Sjkoshy			if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1175147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot register kevent");
1176147708Sjkoshy
1177147708Sjkoshy			args.pa_logfd = pipefd[WRITEPIPEFD];
1178147708Sjkoshy
1179203790Sfabient			args.pa_flags |= FLAG_HAS_PIPE;
1180203790Sfabient			if ((args.pa_flags & FLAG_DO_TOP) == 0)
1181203790Sfabient				args.pa_flags |= FLAG_DO_PRINT;
1182147708Sjkoshy			args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1183147708Sjkoshy		}
1184147708Sjkoshy
1185147708Sjkoshy		if (pmc_configure_logfile(args.pa_logfd) < 0)
1186147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot configure log file");
1187147708Sjkoshy	}
1188147708Sjkoshy
1189151542Sjkoshy	/* remember to check for driver errors if we are sampling or logging */
1190151542Sjkoshy	check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1191151542Sjkoshy	    (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1192151542Sjkoshy
1193147708Sjkoshy	/*
1194210794Sfabient	if (args.pa_flags & FLAG_READ_LOGFILE) {
1195145256Sjkoshy	 * Allocate PMCs.
1196145256Sjkoshy	 */
1197145256Sjkoshy
1198169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1199227524Sobrien		if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1200147191Sjkoshy		    ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1201227524Sobrien			err(EX_OSERR,
1202227524Sobrien"ERROR: Cannot allocate %s-mode pmc with specification \"%s\"",
1203227524Sobrien			    PMC_IS_SYSTEM_MODE(ev->ev_mode) ?
1204227524Sobrien			    "system" : "process", ev->ev_spec);
1205145256Sjkoshy
1206227524Sobrien		if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1207227524Sobrien		    pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1208227524Sobrien			err(EX_OSERR,
1209227524Sobrien			    "ERROR: Cannot set sampling count for PMC \"%s\"",
1210227524Sobrien			    ev->ev_name);
1211147708Sjkoshy	}
1212147708Sjkoshy
1213145256Sjkoshy	/* compute printout widths */
1214169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1215145774Sjkoshy		int counter_width;
1216145774Sjkoshy		int display_width;
1217145774Sjkoshy		int header_width;
1218145256Sjkoshy
1219145774Sjkoshy		(void) pmc_width(ev->ev_pmcid, &counter_width);
1220168949Sjkoshy		header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1221145774Sjkoshy		display_width = (int) floor(counter_width / 3.32193) + 1;
1222145256Sjkoshy
1223168949Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1224168949Sjkoshy			header_width += 3; /* 2 digit CPU number + '/' */
1225168949Sjkoshy
1226145774Sjkoshy		if (header_width > display_width) {
1227145256Sjkoshy			ev->ev_fieldskip = 0;
1228145774Sjkoshy			ev->ev_fieldwidth = header_width;
1229145256Sjkoshy		} else {
1230145774Sjkoshy			ev->ev_fieldskip = display_width -
1231145774Sjkoshy			    header_width;
1232145774Sjkoshy			ev->ev_fieldwidth = display_width;
1233145256Sjkoshy		}
1234145256Sjkoshy	}
1235145256Sjkoshy
1236145256Sjkoshy	/*
1237145256Sjkoshy	 * If our output is being set to a terminal, register a handler
1238145256Sjkoshy	 * for window size changes.
1239145256Sjkoshy	 */
1240145256Sjkoshy
1241147708Sjkoshy	if (isatty(fileno(args.pa_printfile))) {
1242145256Sjkoshy
1243147708Sjkoshy		if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1244145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot determine window size");
1245145256Sjkoshy
1246145256Sjkoshy		pmcstat_displayheight = ws.ws_row - 1;
1247203790Sfabient		pmcstat_displaywidth  = ws.ws_col - 1;
1248145256Sjkoshy
1249145256Sjkoshy		EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1250145256Sjkoshy
1251145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1252227524Sobrien			err(EX_OSERR,
1253227524Sobrien			    "ERROR: Cannot register kevent for SIGWINCH");
1254203790Sfabient
1255203790Sfabient		args.pa_toptty = 1;
1256145256Sjkoshy	}
1257145256Sjkoshy
1258203790Sfabient	/*
1259203790Sfabient	 * Listen to key input in top mode.
1260203790Sfabient	 */
1261203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1262203790Sfabient		EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1263203790Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1264203790Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1265203790Sfabient	}
1266203790Sfabient
1267145256Sjkoshy	EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1268145256Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1269145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1270145256Sjkoshy
1271147191Sjkoshy	EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1272147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1273147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1274145256Sjkoshy
1275147191Sjkoshy	/*
1276147191Sjkoshy	 * An exec() failure of a forked child is signalled by the
1277147191Sjkoshy	 * child sending the parent a SIGCHLD.  We don't register an
1278147191Sjkoshy	 * actual signal handler for SIGCHLD, but instead use our
1279147191Sjkoshy	 * kqueue to pick up the signal.
1280147191Sjkoshy	 */
1281147191Sjkoshy	EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1282147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1283147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1284145256Sjkoshy
1285203790Sfabient	/*
1286203790Sfabient	 * Setup a timer if we have counting mode PMCs needing to be printed or
1287203790Sfabient	 * top mode plugin is active.
1288203790Sfabient	 */
1289203790Sfabient	if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1290203790Sfabient	     (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1291203790Sfabient	    (args.pa_flags & FLAG_DO_TOP)) {
1292145256Sjkoshy		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1293145256Sjkoshy		    args.pa_interval * 1000, NULL);
1294145256Sjkoshy
1295145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1296227524Sobrien			err(EX_OSERR,
1297227524Sobrien			    "ERROR: Cannot register kevent for timer");
1298145256Sjkoshy	}
1299145256Sjkoshy
1300266890Sgnn	/*
1301266890Sgnn	 * Setup a duration timer if we have sampling mode PMCs and
1302266890Sgnn	 * a duration time is set
1303266890Sgnn	 */
1304266890Sgnn	if ((args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1305266890Sgnn	    (args.pa_flags & FLAG_HAS_DURATION)) {
1306266890Sgnn		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1307266890Sgnn		    args.pa_duration * 1000, NULL);
1308266890Sgnn
1309266890Sgnn		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1310266890Sgnn			err(EX_OSERR, "ERROR: Cannot register kevent for "
1311266890Sgnn			    "time duration");
1312266890Sgnn	}
1313266890Sgnn
1314145256Sjkoshy	/* attach PMCs to the target process, starting it if specified */
1315168949Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1316203790Sfabient		pmcstat_create_process();
1317145256Sjkoshy
1318151542Sjkoshy	if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1319151542Sjkoshy		err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1320151542Sjkoshy
1321168949Sjkoshy	/* Attach process pmcs to the target process. */
1322180148Sjkoshy	if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1323169069Sjkoshy		if (SLIST_EMPTY(&args.pa_targets))
1324227524Sobrien			errx(EX_DATAERR,
1325227524Sobrien			    "ERROR: No matching target processes.");
1326183672Sjkoshy		if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1327203790Sfabient			pmcstat_attach_pmcs();
1328168949Sjkoshy
1329169069Sjkoshy		if (pmcstat_kvm) {
1330169069Sjkoshy			kvm_close(pmcstat_kvm);
1331169069Sjkoshy			pmcstat_kvm = NULL;
1332169069Sjkoshy		}
1333169069Sjkoshy	}
1334169069Sjkoshy
1335145256Sjkoshy	/* start the pmcs */
1336203790Sfabient	pmcstat_start_pmcs();
1337145256Sjkoshy
1338145256Sjkoshy	/* start the (commandline) process if needed */
1339147708Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1340168949Sjkoshy		pmcstat_start_process();
1341145256Sjkoshy
1342210794Sfabient	/* initialize logging */
1343210794Sfabient	pmcstat_initialize_logging();
1344147708Sjkoshy
1345145256Sjkoshy	/* Handle SIGINT using the kqueue loop */
1346145256Sjkoshy	sa.sa_handler = SIG_IGN;
1347145256Sjkoshy	sa.sa_flags   = 0;
1348145256Sjkoshy	(void) sigemptyset(&sa.sa_mask);
1349145256Sjkoshy
1350145256Sjkoshy	if (sigaction(SIGINT, &sa, NULL) < 0)
1351145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot install signal handler");
1352145256Sjkoshy
1353145256Sjkoshy	/*
1354203790Sfabient	 * Setup the top mode display.
1355203790Sfabient	 */
1356203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1357203790Sfabient		args.pa_flags &= ~FLAG_DO_PRINT;
1358203790Sfabient
1359203790Sfabient		if (args.pa_toptty) {
1360203790Sfabient			/*
1361203790Sfabient			 * Init ncurses.
1362203790Sfabient			 */
1363203790Sfabient			initscr();
1364203790Sfabient			if(has_colors() == TRUE) {
1365203790Sfabient				args.pa_topcolor = 1;
1366203790Sfabient				start_color();
1367203790Sfabient				use_default_colors();
1368203790Sfabient				pair_content(0, &cf, &cb);
1369203790Sfabient				init_pair(1, COLOR_RED, cb);
1370203790Sfabient				init_pair(2, COLOR_YELLOW, cb);
1371203790Sfabient				init_pair(3, COLOR_GREEN, cb);
1372203790Sfabient			}
1373203790Sfabient			cbreak();
1374203790Sfabient			noecho();
1375203790Sfabient			nonl();
1376203790Sfabient			nodelay(stdscr, 1);
1377203790Sfabient			intrflush(stdscr, FALSE);
1378203790Sfabient			keypad(stdscr, TRUE);
1379203790Sfabient			clear();
1380204783Sfabient			/* Get terminal width / height with ncurses. */
1381227524Sobrien			getmaxyx(stdscr,
1382227524Sobrien			    pmcstat_displayheight, pmcstat_displaywidth);
1383204783Sfabient			pmcstat_displayheight--; pmcstat_displaywidth--;
1384203790Sfabient			atexit(pmcstat_topexit);
1385203790Sfabient		}
1386203790Sfabient	}
1387203790Sfabient
1388203790Sfabient	/*
1389145256Sjkoshy	 * loop till either the target process (if any) exits, or we
1390266890Sgnn	 * are killed by a SIGINT or we reached the time duration.
1391145256Sjkoshy	 */
1392147191Sjkoshy	runstate = PMCSTAT_RUNNING;
1393226514Sfabient	do_print = do_read = 0;
1394145256Sjkoshy	do {
1395145256Sjkoshy		if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1396145256Sjkoshy			if (errno != EINTR)
1397145256Sjkoshy				err(EX_OSERR, "ERROR: kevent failed");
1398145256Sjkoshy			else
1399145256Sjkoshy				continue;
1400145256Sjkoshy		}
1401145256Sjkoshy
1402145256Sjkoshy		if (kev.flags & EV_ERROR)
1403145256Sjkoshy			errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1404145256Sjkoshy
1405145256Sjkoshy		switch (kev.filter) {
1406147191Sjkoshy		case EVFILT_PROC:  /* target has exited */
1407210794Sfabient			runstate = pmcstat_close_log();
1408148688Sjkoshy			do_print = 1;
1409147191Sjkoshy			break;
1410145256Sjkoshy
1411147191Sjkoshy		case EVFILT_READ:  /* log file data is present */
1412210794Sfabient			if (kev.ident == (unsigned)fileno(stdin) &&
1413210794Sfabient			    (args.pa_flags & FLAG_DO_TOP)) {
1414203790Sfabient				if (pmcstat_keypress_log())
1415203790Sfabient					runstate = pmcstat_close_log();
1416226514Sfabient			} else {
1417226514Sfabient				do_read = 0;
1418203790Sfabient				runstate = pmcstat_process_log();
1419226514Sfabient			}
1420145256Sjkoshy			break;
1421145256Sjkoshy
1422145256Sjkoshy		case EVFILT_SIGNAL:
1423147191Sjkoshy			if (kev.ident == SIGCHLD) {
1424147191Sjkoshy				/*
1425147191Sjkoshy				 * The child process sends us a
1426147191Sjkoshy				 * SIGCHLD if its exec() failed.  We
1427147191Sjkoshy				 * wait for it to exit and then exit
1428147191Sjkoshy				 * ourselves.
1429147191Sjkoshy				 */
1430147191Sjkoshy				(void) wait(&c);
1431147191Sjkoshy				runstate = PMCSTAT_FINISHED;
1432147191Sjkoshy			} else if (kev.ident == SIGIO) {
1433147191Sjkoshy				/*
1434147191Sjkoshy				 * We get a SIGIO if a PMC loses all
1435147191Sjkoshy				 * of its targets, or if logfile
1436147191Sjkoshy				 * writes encounter an error.
1437147191Sjkoshy				 */
1438210794Sfabient				runstate = pmcstat_close_log();
1439147191Sjkoshy				do_print = 1; /* print PMCs at exit */
1440147191Sjkoshy			} else if (kev.ident == SIGINT) {
1441147708Sjkoshy				/* Kill the child process if we started it */
1442147708Sjkoshy				if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1443203790Sfabient					pmcstat_kill_process();
1444210794Sfabient				runstate = pmcstat_close_log();
1445145256Sjkoshy			} else if (kev.ident == SIGWINCH) {
1446147708Sjkoshy				if (ioctl(fileno(args.pa_printfile),
1447145256Sjkoshy					TIOCGWINSZ, &ws) < 0)
1448227524Sobrien				    err(EX_OSERR,
1449227524Sobrien				        "ERROR: Cannot determine window size");
1450145256Sjkoshy				pmcstat_displayheight = ws.ws_row - 1;
1451203790Sfabient				pmcstat_displaywidth  = ws.ws_col - 1;
1452145256Sjkoshy			} else
1453145256Sjkoshy				assert(0);
1454145256Sjkoshy
1455145256Sjkoshy			break;
1456147191Sjkoshy
1457266890Sgnn		case EVFILT_TIMER:
1458266890Sgnn			/* time duration reached, exit */
1459266890Sgnn			if (args.pa_flags & FLAG_HAS_DURATION) {
1460266890Sgnn				runstate = PMCSTAT_FINISHED;
1461266890Sgnn				break;
1462266890Sgnn			}
1463266890Sgnn			/* print out counting PMCs */
1464226514Sfabient			if ((args.pa_flags & FLAG_DO_TOP) &&
1465226986Sfabient			     pmc_flush_logfile() == 0)
1466226514Sfabient				do_read = 1;
1467147191Sjkoshy			do_print = 1;
1468147191Sjkoshy			break;
1469147191Sjkoshy
1470145256Sjkoshy		}
1471145256Sjkoshy
1472226514Sfabient		if (do_print && !do_read) {
1473203790Sfabient			if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1474203790Sfabient				pmcstat_print_pmcs();
1475227524Sobrien				if (runstate == PMCSTAT_FINISHED &&
1476227524Sobrien				    /* final newline */
1477203790Sfabient				    (args.pa_flags & FLAG_DO_PRINT) == 0)
1478203790Sfabient					(void) fprintf(args.pa_printfile, "\n");
1479203790Sfabient			}
1480203790Sfabient			if (args.pa_flags & FLAG_DO_TOP)
1481203790Sfabient				pmcstat_display_log();
1482147191Sjkoshy			do_print = 0;
1483147191Sjkoshy		}
1484145256Sjkoshy
1485147191Sjkoshy	} while (runstate != PMCSTAT_FINISHED);
1486147191Sjkoshy
1487203790Sfabient	if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1488203790Sfabient		pmcstat_topexit();
1489203790Sfabient		args.pa_toptty = 0;
1490203790Sfabient	}
1491203790Sfabient
1492147191Sjkoshy	/* flush any pending log entries */
1493147708Sjkoshy	if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1494226514Sfabient		pmc_close_logfile();
1495147191Sjkoshy
1496203790Sfabient	pmcstat_cleanup();
1497145256Sjkoshy
1498157144Sjkoshy	free(args.pa_kernel);
1499157144Sjkoshy
1500151542Sjkoshy	/* check if the driver lost any samples or events */
1501151542Sjkoshy	if (check_driver_stats) {
1502151542Sjkoshy		if (pmc_get_driver_stats(&ds_end) < 0)
1503227524Sobrien			err(EX_OSERR,
1504227524Sobrien			    "ERROR: Cannot retrieve driver statistics");
1505157144Sjkoshy		if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1506157144Sjkoshy		    args.pa_verbosity > 0)
1507227524Sobrien			warnx("WARNING: some samples were dropped.\n"
1508227524Sobrien"Please consider tuning the \"kern.hwpmc.nsamples\" tunable."
1509227524Sobrien			    );
1510151542Sjkoshy		if (ds_start.pm_buffer_requests_failed !=
1511157144Sjkoshy		    ds_end.pm_buffer_requests_failed &&
1512157144Sjkoshy		    args.pa_verbosity > 0)
1513227524Sobrien			warnx("WARNING: some events were discarded.\n"
1514227524Sobrien"Please consider tuning the \"kern.hwpmc.nbuffers\" tunable."
1515227524Sobrien			    );
1516151542Sjkoshy	}
1517151542Sjkoshy
1518151542Sjkoshy	exit(EX_OK);
1519145256Sjkoshy}
1520