pmcstat.c revision 208858
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: head/usr.sbin/pmcstat/pmcstat.c 208858 2010-06-05 22:57:53Z fabient $");
33145256Sjkoshy
34145256Sjkoshy#include <sys/types.h>
35145256Sjkoshy#include <sys/event.h>
36169069Sjkoshy#include <sys/param.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.
101168949Sjkoshy *					- Recieves signal, attempts exec().
102168949Sjkoshy *
103168949Sjkoshy * After this point normal processing can happen.
104147191Sjkoshy */
105147191Sjkoshy
106147708Sjkoshy/* Globals */
107145256Sjkoshy
108145256Sjkoshyint	pmcstat_interrupt = 0;
109145256Sjkoshyint	pmcstat_displayheight = DEFAULT_DISPLAY_HEIGHT;
110203790Sfabientint	pmcstat_displaywidth  = DEFAULT_DISPLAY_WIDTH;
111168949Sjkoshyint	pmcstat_sockpair[NSOCKPAIRFD];
112145256Sjkoshyint	pmcstat_kq;
113169069Sjkoshykvm_t	*pmcstat_kvm;
114169069Sjkoshystruct kinfo_proc *pmcstat_plist;
115203790Sfabientstruct pmcstat_args args;
116145256Sjkoshy
117168949Sjkoshyvoid
118203790Sfabientpmcstat_attach_pmcs(void)
119168949Sjkoshy{
120168949Sjkoshy	struct pmcstat_ev *ev;
121169069Sjkoshy	struct pmcstat_target *pt;
122169069Sjkoshy	int count;
123145256Sjkoshy
124169069Sjkoshy	/* Attach all process PMCs to target processes. */
125169069Sjkoshy	count = 0;
126203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
127169069Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
128169069Sjkoshy			continue;
129203790Sfabient		SLIST_FOREACH(pt, &args.pa_targets, pt_next)
130169069Sjkoshy			if (pmc_attach(ev->ev_pmcid, pt->pt_pid) == 0)
131169069Sjkoshy				count++;
132169069Sjkoshy			else if (errno != ESRCH)
133169069Sjkoshy				err(EX_OSERR, "ERROR: cannot attach pmc "
134169069Sjkoshy				    "\"%s\" to process %d", ev->ev_name,
135169069Sjkoshy				    (int) pt->pt_pid);
136169069Sjkoshy	}
137168949Sjkoshy
138169069Sjkoshy	if (count == 0)
139169069Sjkoshy		errx(EX_DATAERR, "ERROR: No processes were attached to.");
140168949Sjkoshy}
141168949Sjkoshy
142168949Sjkoshy
143145256Sjkoshyvoid
144203790Sfabientpmcstat_cleanup(void)
145145256Sjkoshy{
146145256Sjkoshy	struct pmcstat_ev *ev, *tmp;
147145256Sjkoshy
148145256Sjkoshy	/* release allocated PMCs. */
149203790Sfabient	STAILQ_FOREACH_SAFE(ev, &args.pa_events, ev_next, tmp)
150145256Sjkoshy	    if (ev->ev_pmcid != PMC_ID_INVALID) {
151185079Sjkoshy		if (pmc_stop(ev->ev_pmcid) < 0)
152185079Sjkoshy			err(EX_OSERR, "ERROR: cannot stop pmc 0x%x "
153185079Sjkoshy			    "\"%s\"", ev->ev_pmcid, ev->ev_name);
154145256Sjkoshy		if (pmc_release(ev->ev_pmcid) < 0)
155145256Sjkoshy			err(EX_OSERR, "ERROR: cannot release pmc "
156147191Sjkoshy			    "0x%x \"%s\"", ev->ev_pmcid, ev->ev_name);
157145256Sjkoshy		free(ev->ev_name);
158145256Sjkoshy		free(ev->ev_spec);
159203790Sfabient		STAILQ_REMOVE(&args.pa_events, ev, pmcstat_ev, ev_next);
160145256Sjkoshy		free(ev);
161145256Sjkoshy	    }
162147191Sjkoshy
163147863Sjkoshy	/* de-configure the log file if present. */
164203790Sfabient	if (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
165147863Sjkoshy		(void) pmc_configure_logfile(-1);
166147863Sjkoshy
167203790Sfabient	if (args.pa_logparser) {
168203790Sfabient		pmclog_close(args.pa_logparser);
169203790Sfabient		args.pa_logparser = NULL;
170147191Sjkoshy	}
171147708Sjkoshy
172203790Sfabient	if (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
173203790Sfabient		pmcstat_shutdown_logging();
174145256Sjkoshy}
175145256Sjkoshy
176145256Sjkoshyvoid
177203790Sfabientpmcstat_clone_event_descriptor(struct pmcstat_ev *ev,
178168949Sjkoshy    uint32_t cpumask)
179168949Sjkoshy{
180168949Sjkoshy	int cpu;
181168949Sjkoshy	struct pmcstat_ev *ev_clone;
182168949Sjkoshy
183168949Sjkoshy	while ((cpu = ffs(cpumask)) > 0) {
184168949Sjkoshy		cpu--;
185168949Sjkoshy
186168949Sjkoshy		if ((ev_clone = malloc(sizeof(*ev_clone))) == NULL)
187168949Sjkoshy			errx(EX_SOFTWARE, "ERROR: Out of memory");
188168949Sjkoshy		(void) memset(ev_clone, 0, sizeof(*ev_clone));
189168949Sjkoshy
190168949Sjkoshy		ev_clone->ev_count = ev->ev_count;
191168949Sjkoshy		ev_clone->ev_cpu   = cpu;
192168949Sjkoshy		ev_clone->ev_cumulative = ev->ev_cumulative;
193168949Sjkoshy		ev_clone->ev_flags = ev->ev_flags;
194168949Sjkoshy		ev_clone->ev_mode  = ev->ev_mode;
195168949Sjkoshy		ev_clone->ev_name  = strdup(ev->ev_name);
196168949Sjkoshy		ev_clone->ev_pmcid = ev->ev_pmcid;
197168949Sjkoshy		ev_clone->ev_saved = ev->ev_saved;
198168949Sjkoshy		ev_clone->ev_spec  = strdup(ev->ev_spec);
199168949Sjkoshy
200203790Sfabient		STAILQ_INSERT_TAIL(&args.pa_events, ev_clone, ev_next);
201168949Sjkoshy
202168949Sjkoshy		cpumask &= ~(1 << cpu);
203168949Sjkoshy	}
204168949Sjkoshy}
205168949Sjkoshy
206168949Sjkoshyvoid
207203790Sfabientpmcstat_create_process(void)
208168949Sjkoshy{
209168949Sjkoshy	char token;
210169069Sjkoshy	pid_t pid;
211168949Sjkoshy	struct kevent kev;
212169069Sjkoshy	struct pmcstat_target *pt;
213168949Sjkoshy
214168949Sjkoshy	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pmcstat_sockpair) < 0)
215168949Sjkoshy		err(EX_OSERR, "ERROR: cannot create socket pair");
216168949Sjkoshy
217169069Sjkoshy	switch (pid = fork()) {
218168949Sjkoshy	case -1:
219168949Sjkoshy		err(EX_OSERR, "ERROR: cannot fork");
220168949Sjkoshy		/*NOTREACHED*/
221168949Sjkoshy
222168949Sjkoshy	case 0:		/* child */
223168949Sjkoshy		(void) close(pmcstat_sockpair[PARENTSOCKET]);
224168949Sjkoshy
225168949Sjkoshy		/* Write a token to tell our parent we've started executing. */
226168949Sjkoshy		if (write(pmcstat_sockpair[CHILDSOCKET], "+", 1) != 1)
227168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot write token");
228168949Sjkoshy
229168949Sjkoshy		/* Wait for our parent to signal us to start. */
230168949Sjkoshy		if (read(pmcstat_sockpair[CHILDSOCKET], &token, 1) < 0)
231168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot read token");
232168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
233168949Sjkoshy
234168949Sjkoshy		/* exec() the program requested */
235203790Sfabient		execvp(*args.pa_argv, args.pa_argv);
236168949Sjkoshy		/* and if that fails, notify the parent */
237168949Sjkoshy		kill(getppid(), SIGCHLD);
238203790Sfabient		err(EX_OSERR, "ERROR: execvp \"%s\" failed", *args.pa_argv);
239168949Sjkoshy		/*NOTREACHED*/
240168949Sjkoshy
241168949Sjkoshy	default:	/* parent */
242168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
243168949Sjkoshy		break;
244168949Sjkoshy	}
245168949Sjkoshy
246168949Sjkoshy	/* Ask to be notified via a kevent when the target process exits. */
247169069Sjkoshy	EV_SET(&kev, pid, EVFILT_PROC, EV_ADD|EV_ONESHOT, NOTE_EXIT, 0,
248168949Sjkoshy	    NULL);
249168949Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
250169069Sjkoshy		err(EX_OSERR, "ERROR: cannot monitor child process %d", pid);
251168949Sjkoshy
252169069Sjkoshy	if ((pt = malloc(sizeof(*pt))) == NULL)
253169069Sjkoshy		errx(EX_SOFTWARE, "ERROR: Out of memory.");
254169069Sjkoshy
255169069Sjkoshy	pt->pt_pid = pid;
256203790Sfabient	SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
257169069Sjkoshy
258168949Sjkoshy	/* Wait for the child to signal that its ready to go. */
259168949Sjkoshy	if (read(pmcstat_sockpair[PARENTSOCKET], &token, 1) < 0)
260168949Sjkoshy		err(EX_OSERR, "ERROR (parent): cannot read token");
261168949Sjkoshy
262168949Sjkoshy	return;
263168949Sjkoshy}
264168949Sjkoshy
265169069Sjkoshyvoid
266203790Sfabientpmcstat_find_targets(const char *spec)
267169069Sjkoshy{
268169069Sjkoshy	int n, nproc, pid, rv;
269169069Sjkoshy	struct pmcstat_target *pt;
270169069Sjkoshy	char errbuf[_POSIX2_LINE_MAX], *end;
271169069Sjkoshy	static struct kinfo_proc *kp;
272169069Sjkoshy	regex_t reg;
273169069Sjkoshy	regmatch_t regmatch;
274169069Sjkoshy
275169069Sjkoshy	/* First check if we've been given a process id. */
276169069Sjkoshy      	pid = strtol(spec, &end, 0);
277169069Sjkoshy	if (end != spec && pid >= 0) {
278169069Sjkoshy		if ((pt = malloc(sizeof(*pt))) == NULL)
279169069Sjkoshy			goto outofmemory;
280169069Sjkoshy		pt->pt_pid = pid;
281203790Sfabient		SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
282169069Sjkoshy		return;
283169069Sjkoshy	}
284169069Sjkoshy
285169069Sjkoshy	/* Otherwise treat arg as a regular expression naming processes. */
286169069Sjkoshy	if (pmcstat_kvm == NULL) {
287169069Sjkoshy		if ((pmcstat_kvm = kvm_openfiles(NULL, "/dev/null", NULL, 0,
288169069Sjkoshy		    errbuf)) == NULL)
289169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot open kernel \"%s\"",
290169069Sjkoshy			    errbuf);
291169069Sjkoshy		if ((pmcstat_plist = kvm_getprocs(pmcstat_kvm, KERN_PROC_PROC,
292169069Sjkoshy		    0, &nproc)) == NULL)
293169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot get process list: %s",
294169069Sjkoshy			    kvm_geterr(pmcstat_kvm));
295208858Sfabient	} else
296208858Sfabient		nproc = 0;
297169069Sjkoshy
298169069Sjkoshy	if ((rv = regcomp(&reg, spec, REG_EXTENDED|REG_NOSUB)) != 0) {
299169069Sjkoshy		regerror(rv, &reg, errbuf, sizeof(errbuf));
300169069Sjkoshy		err(EX_DATAERR, "ERROR: Failed to compile regex \"%s\": %s",
301169069Sjkoshy		    spec, errbuf);
302169069Sjkoshy	}
303169069Sjkoshy
304169069Sjkoshy	for (n = 0, kp = pmcstat_plist; n < nproc; n++, kp++) {
305169069Sjkoshy		if ((rv = regexec(&reg, kp->ki_comm, 1, &regmatch, 0)) == 0) {
306169069Sjkoshy			if ((pt = malloc(sizeof(*pt))) == NULL)
307169069Sjkoshy				goto outofmemory;
308169069Sjkoshy			pt->pt_pid = kp->ki_pid;
309203790Sfabient			SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
310169069Sjkoshy		} else if (rv != REG_NOMATCH) {
311169069Sjkoshy			regerror(rv, &reg, errbuf, sizeof(errbuf));
312169069Sjkoshy			errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s",
313169069Sjkoshy			    errbuf);
314169069Sjkoshy		}
315169069Sjkoshy	}
316169069Sjkoshy
317169069Sjkoshy	regfree(&reg);
318169069Sjkoshy
319169069Sjkoshy	return;
320169069Sjkoshy
321169069Sjkoshy outofmemory:
322169069Sjkoshy	errx(EX_SOFTWARE, "Out of memory.");
323169069Sjkoshy	/*NOTREACHED*/
324169069Sjkoshy}
325169069Sjkoshy
326168949Sjkoshyuint32_t
327168949Sjkoshypmcstat_get_cpumask(const char *cpuspec)
328168949Sjkoshy{
329168949Sjkoshy	uint32_t cpumask;
330168949Sjkoshy	int cpu;
331168949Sjkoshy	const char *s;
332168949Sjkoshy	char *end;
333168949Sjkoshy
334168949Sjkoshy	s = cpuspec;
335168949Sjkoshy	cpumask = 0ULL;
336168949Sjkoshy
337168949Sjkoshy	do {
338168949Sjkoshy		cpu = strtol(s, &end, 0);
339168949Sjkoshy		if (cpu < 0 || end == s)
340168949Sjkoshy			errx(EX_USAGE, "ERROR: Illegal CPU specification "
341168949Sjkoshy			    "\"%s\".", cpuspec);
342168949Sjkoshy		cpumask |= (1 << cpu);
343168949Sjkoshy		s = end + strspn(end, ", \t");
344168949Sjkoshy	} while (*s);
345168949Sjkoshy
346168949Sjkoshy	return (cpumask);
347168949Sjkoshy}
348168949Sjkoshy
349168949Sjkoshyvoid
350203790Sfabientpmcstat_kill_process(void)
351169069Sjkoshy{
352169069Sjkoshy	struct pmcstat_target *pt;
353169069Sjkoshy
354203790Sfabient	assert(args.pa_flags & FLAG_HAS_COMMANDLINE);
355169069Sjkoshy
356169069Sjkoshy	/*
357169069Sjkoshy	 * If a command line was specified, it would be the very first
358169069Sjkoshy	 * in the list, before any other processes specified by -t.
359169069Sjkoshy	 */
360203790Sfabient	pt = SLIST_FIRST(&args.pa_targets);
361169069Sjkoshy	assert(pt != NULL);
362169069Sjkoshy
363169069Sjkoshy	if (kill(pt->pt_pid, SIGINT) != 0)
364169069Sjkoshy		err(EX_OSERR, "ERROR: cannot signal child process");
365169069Sjkoshy}
366169069Sjkoshy
367169069Sjkoshyvoid
368203790Sfabientpmcstat_start_pmcs(void)
369145256Sjkoshy{
370145256Sjkoshy	struct pmcstat_ev *ev;
371145256Sjkoshy
372169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
373145256Sjkoshy
374145256Sjkoshy	    assert(ev->ev_pmcid != PMC_ID_INVALID);
375145256Sjkoshy
376145256Sjkoshy	    if (pmc_start(ev->ev_pmcid) < 0) {
377147191Sjkoshy	        warn("ERROR: Cannot start pmc 0x%x \"%s\"",
378145256Sjkoshy		    ev->ev_pmcid, ev->ev_name);
379203790Sfabient		pmcstat_cleanup();
380147191Sjkoshy		exit(EX_OSERR);
381145256Sjkoshy	    }
382145256Sjkoshy	}
383145256Sjkoshy
384145256Sjkoshy}
385145256Sjkoshy
386145256Sjkoshyvoid
387203790Sfabientpmcstat_print_headers(void)
388145256Sjkoshy{
389145256Sjkoshy	struct pmcstat_ev *ev;
390168949Sjkoshy	int c, w;
391145256Sjkoshy
392203790Sfabient	(void) fprintf(args.pa_printfile, PRINT_HEADER_PREFIX);
393145256Sjkoshy
394203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
395145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
396145256Sjkoshy			continue;
397145256Sjkoshy
398145256Sjkoshy		c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p';
399145256Sjkoshy
400168949Sjkoshy		if (ev->ev_fieldskip != 0)
401203790Sfabient			(void) fprintf(args.pa_printfile, "%*s",
402168949Sjkoshy			    ev->ev_fieldskip, "");
403168949Sjkoshy		w = ev->ev_fieldwidth - ev->ev_fieldskip - 2;
404168949Sjkoshy
405168949Sjkoshy		if (c == 's')
406203790Sfabient			(void) fprintf(args.pa_printfile, "s/%02d/%-*s ",
407168949Sjkoshy			    ev->ev_cpu, w-3, ev->ev_name);
408168949Sjkoshy		else
409203790Sfabient			(void) fprintf(args.pa_printfile, "p/%*s ", w,
410145256Sjkoshy			    ev->ev_name);
411145256Sjkoshy	}
412145256Sjkoshy
413203790Sfabient	(void) fflush(args.pa_printfile);
414145256Sjkoshy}
415145256Sjkoshy
416145256Sjkoshyvoid
417203790Sfabientpmcstat_print_counters(void)
418145256Sjkoshy{
419145256Sjkoshy	int extra_width;
420145256Sjkoshy	struct pmcstat_ev *ev;
421145256Sjkoshy	pmc_value_t value;
422145256Sjkoshy
423145256Sjkoshy	extra_width = sizeof(PRINT_HEADER_PREFIX) - 1;
424145256Sjkoshy
425203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
426145256Sjkoshy
427145256Sjkoshy		/* skip sampling mode counters */
428145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
429145256Sjkoshy			continue;
430145256Sjkoshy
431145256Sjkoshy		if (pmc_read(ev->ev_pmcid, &value) < 0)
432145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot read pmc "
433145256Sjkoshy			    "\"%s\"", ev->ev_name);
434145256Sjkoshy
435203790Sfabient		(void) fprintf(args.pa_printfile, "%*ju ",
436147708Sjkoshy		    ev->ev_fieldwidth + extra_width,
437147708Sjkoshy		    (uintmax_t) ev->ev_cumulative ? value :
438147708Sjkoshy		    (value - ev->ev_saved));
439147708Sjkoshy
440145256Sjkoshy		if (ev->ev_cumulative == 0)
441145256Sjkoshy			ev->ev_saved = value;
442145256Sjkoshy		extra_width = 0;
443145256Sjkoshy	}
444145256Sjkoshy
445203790Sfabient	(void) fflush(args.pa_printfile);
446145256Sjkoshy}
447145256Sjkoshy
448145256Sjkoshy/*
449145256Sjkoshy * Print output
450145256Sjkoshy */
451145256Sjkoshy
452145256Sjkoshyvoid
453203790Sfabientpmcstat_print_pmcs(void)
454145256Sjkoshy{
455145256Sjkoshy	static int linecount = 0;
456145256Sjkoshy
457147708Sjkoshy	/* check if we need to print a header line */
458145256Sjkoshy	if (++linecount > pmcstat_displayheight) {
459203790Sfabient		(void) fprintf(args.pa_printfile, "\n");
460145256Sjkoshy		linecount = 1;
461145256Sjkoshy	}
462145256Sjkoshy	if (linecount == 1)
463203790Sfabient		pmcstat_print_headers();
464203790Sfabient	(void) fprintf(args.pa_printfile, "\n");
465145256Sjkoshy
466203790Sfabient	pmcstat_print_counters();
467145256Sjkoshy
468145256Sjkoshy	return;
469145256Sjkoshy}
470145256Sjkoshy
471145256Sjkoshy/*
472145256Sjkoshy * Do process profiling
473145256Sjkoshy *
474145256Sjkoshy * If a pid was specified, attach each allocated PMC to the target
475145256Sjkoshy * process.  Otherwise, fork a child and attach the PMCs to the child,
476145256Sjkoshy * and have the child exec() the target program.
477145256Sjkoshy */
478145256Sjkoshy
479145256Sjkoshyvoid
480168949Sjkoshypmcstat_start_process(void)
481145256Sjkoshy{
482168949Sjkoshy	/* Signal the child to proceed. */
483168949Sjkoshy	if (write(pmcstat_sockpair[PARENTSOCKET], "!", 1) != 1)
484168949Sjkoshy		err(EX_OSERR, "ERROR (parent): write of token failed");
485145256Sjkoshy
486168949Sjkoshy	(void) close(pmcstat_sockpair[PARENTSOCKET]);
487145256Sjkoshy}
488145256Sjkoshy
489145256Sjkoshyvoid
490145256Sjkoshypmcstat_show_usage(void)
491145256Sjkoshy{
492145256Sjkoshy	errx(EX_USAGE,
493145256Sjkoshy	    "[options] [commandline]\n"
494145256Sjkoshy	    "\t Measure process and/or system performance using hardware\n"
495145256Sjkoshy	    "\t performance monitoring counters.\n"
496145256Sjkoshy	    "\t Options include:\n"
497147191Sjkoshy	    "\t -C\t\t (toggle) show cumulative counts\n"
498147191Sjkoshy	    "\t -D path\t create profiles in directory \"path\"\n"
499147191Sjkoshy	    "\t -E\t\t (toggle) show counts at process exit\n"
500203790Sfabient	    "\t -F file\t write a system-wide callgraph (Kcachegrind format)"
501203790Sfabient		" to \"file\"\n"
502174396Sjkoshy	    "\t -G file\t write a system-wide callgraph to \"file\"\n"
503157144Sjkoshy	    "\t -M file\t print executable/gmon file map to \"file\"\n"
504174396Sjkoshy	    "\t -N\t\t (toggle) capture callchains\n"
505147191Sjkoshy	    "\t -O file\t send log output to \"file\"\n"
506147191Sjkoshy	    "\t -P spec\t allocate a process-private sampling PMC\n"
507147191Sjkoshy	    "\t -R file\t read events from \"file\"\n"
508147191Sjkoshy	    "\t -S spec\t allocate a system-wide sampling PMC\n"
509203790Sfabient	    "\t -T\t\t start in top mode\n"
510147191Sjkoshy	    "\t -W\t\t (toggle) show counts per context switch\n"
511168949Sjkoshy	    "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n"
512147191Sjkoshy	    "\t -d\t\t (toggle) track descendants\n"
513203790Sfabient	    "\t -f spec\t pass \"spec\" to as plugin option\n"
514147191Sjkoshy	    "\t -g\t\t produce gprof(1) compatible profiles\n"
515162804Sru	    "\t -k dir\t\t set the path to the kernel\n"
516145256Sjkoshy	    "\t -n rate\t set sampling rate\n"
517145256Sjkoshy	    "\t -o file\t send print output to \"file\"\n"
518147191Sjkoshy	    "\t -p spec\t allocate a process-private counting PMC\n"
519157144Sjkoshy	    "\t -q\t\t suppress verbosity\n"
520157144Sjkoshy	    "\t -r fsroot\t specify FS root directory\n"
521147191Sjkoshy	    "\t -s spec\t allocate a system-wide counting PMC\n"
522183186Sjkoshy	    "\t -t process-spec attach to running processes matching "
523183186Sjkoshy		"\"process-spec\"\n"
524157144Sjkoshy	    "\t -v\t\t increase verbosity\n"
525174396Sjkoshy	    "\t -w secs\t set printing time interval\n"
526174396Sjkoshy	    "\t -z depth\t limit callchain display depth"
527145256Sjkoshy	);
528145256Sjkoshy}
529145256Sjkoshy
530145256Sjkoshy/*
531203790Sfabient * At exit handler for top mode
532203790Sfabient */
533203790Sfabient
534203790Sfabientvoid
535203790Sfabientpmcstat_topexit(void)
536203790Sfabient{
537203790Sfabient	if (!args.pa_toptty)
538203790Sfabient		return;
539203790Sfabient
540203790Sfabient	/*
541203790Sfabient	 * Shutdown ncurses.
542203790Sfabient	 */
543203790Sfabient	clrtoeol();
544203790Sfabient	refresh();
545203790Sfabient	endwin();
546203790Sfabient}
547203790Sfabient
548203790Sfabient/*
549145256Sjkoshy * Main
550145256Sjkoshy */
551145256Sjkoshy
552145256Sjkoshyint
553145256Sjkoshymain(int argc, char **argv)
554145256Sjkoshy{
555145256Sjkoshy	double interval;
556174396Sjkoshy	int option, npmc, ncpu, haltedcpus;
557151542Sjkoshy	int c, check_driver_stats, current_cpu, current_sampling_count;
558174396Sjkoshy	int do_callchain, do_descendants, do_logproccsw, do_logprocexit;
559174396Sjkoshy	int do_print;
560168949Sjkoshy	size_t dummy;
561174396Sjkoshy	int graphdepth;
562147191Sjkoshy	int pipefd[2];
563147191Sjkoshy	int use_cumulative_counts;
564203790Sfabient	short cf, cb;
565168949Sjkoshy	uint32_t cpumask;
566157144Sjkoshy	char *end, *tmp;
567174396Sjkoshy	const char *errmsg, *graphfilename;
568147191Sjkoshy	enum pmcstat_state runstate;
569151542Sjkoshy	struct pmc_driverstats ds_start, ds_end;
570145256Sjkoshy	struct pmcstat_ev *ev;
571145256Sjkoshy	struct sigaction sa;
572145256Sjkoshy	struct kevent kev;
573145256Sjkoshy	struct winsize ws;
574147708Sjkoshy	struct stat sb;
575157144Sjkoshy	char buffer[PATH_MAX];
576145256Sjkoshy
577151542Sjkoshy	check_driver_stats      = 0;
578145256Sjkoshy	current_cpu 		= 0;
579145256Sjkoshy	current_sampling_count  = DEFAULT_SAMPLE_COUNT;
580174396Sjkoshy	do_callchain		= 1;
581145256Sjkoshy	do_descendants          = 0;
582147191Sjkoshy	do_logproccsw           = 0;
583147191Sjkoshy	do_logprocexit          = 0;
584145256Sjkoshy	use_cumulative_counts   = 0;
585174396Sjkoshy	graphfilename		= "-";
586147191Sjkoshy	args.pa_required	= 0;
587145256Sjkoshy	args.pa_flags		= 0;
588157144Sjkoshy	args.pa_verbosity	= 1;
589147708Sjkoshy	args.pa_logfd		= -1;
590157144Sjkoshy	args.pa_fsroot		= "";
591157144Sjkoshy	args.pa_kernel		= strdup("/boot/kernel");
592147708Sjkoshy	args.pa_samplesdir	= ".";
593147708Sjkoshy	args.pa_printfile	= stderr;
594174396Sjkoshy	args.pa_graphdepth	= DEFAULT_CALLGRAPH_DEPTH;
595174396Sjkoshy	args.pa_graphfile	= NULL;
596145256Sjkoshy	args.pa_interval	= DEFAULT_WAIT_INTERVAL;
597157144Sjkoshy	args.pa_mapfilename	= NULL;
598174396Sjkoshy	args.pa_inputpath	= NULL;
599174396Sjkoshy	args.pa_outputpath	= NULL;
600203790Sfabient	args.pa_pplugin		= PMCSTAT_PL_NONE;
601203790Sfabient	args.pa_plugin		= PMCSTAT_PL_NONE;
602203790Sfabient	args.pa_ctdumpinstr	= 1;
603203790Sfabient	args.pa_topmode		= PMCSTAT_TOP_DELTA;
604203790Sfabient	args.pa_toptty		= 0;
605203790Sfabient	args.pa_topcolor	= 0;
606203790Sfabient	args.pa_mergepmc	= 0;
607169069Sjkoshy	STAILQ_INIT(&args.pa_events);
608169069Sjkoshy	SLIST_INIT(&args.pa_targets);
609153704Sjkoshy	bzero(&ds_start, sizeof(ds_start));
610153704Sjkoshy	bzero(&ds_end, sizeof(ds_end));
611145256Sjkoshy	ev = NULL;
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");
620168949Sjkoshy	cpumask = (1 << ncpu) - 1;
621183672Sjkoshy	haltedcpus = 0;
622175215Sjkim	if (ncpu > 1) {
623175215Sjkim		if (sysctlbyname("machdep.hlt_cpus", &haltedcpus, &dummy,
624175215Sjkim		    NULL, 0) < 0)
625175215Sjkim			err(EX_OSERR, "ERROR: Cannot determine which CPUs are "
626175215Sjkim			    "halted");
627175215Sjkim		cpumask &= ~haltedcpus;
628175215Sjkim	}
629168949Sjkoshy
630157144Sjkoshy	while ((option = getopt(argc, argv,
631203790Sfabient	    "CD:EF:G:M:NO:P:R:S:TWc:df:gk:m:n:o:p:qr:s:t:vw:z:")) != -1)
632145256Sjkoshy		switch (option) {
633145256Sjkoshy		case 'C':	/* cumulative values */
634145256Sjkoshy			use_cumulative_counts = !use_cumulative_counts;
635147191Sjkoshy			args.pa_required |= FLAG_HAS_COUNTING_PMCS;
636145256Sjkoshy			break;
637145256Sjkoshy
638145256Sjkoshy		case 'c':	/* CPU */
639168949Sjkoshy
640168949Sjkoshy			if (optarg[0] == '*' && optarg[1] == '\0')
641183672Sjkoshy				cpumask = ((1 << ncpu) - 1) & ~haltedcpus;
642168949Sjkoshy			else
643168949Sjkoshy				cpumask = pmcstat_get_cpumask(optarg);
644168949Sjkoshy
645147191Sjkoshy			args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
646145256Sjkoshy			break;
647145256Sjkoshy
648147708Sjkoshy		case 'D':
649147708Sjkoshy			if (stat(optarg, &sb) < 0)
650147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
651147708Sjkoshy				    optarg);
652147708Sjkoshy			if (!S_ISDIR(sb.st_mode))
653147708Sjkoshy				errx(EX_USAGE, "ERROR: \"%s\" is not a "
654168949Sjkoshy				    "directory.", optarg);
655147708Sjkoshy			args.pa_samplesdir = optarg;
656147708Sjkoshy			args.pa_flags     |= FLAG_HAS_SAMPLESDIR;
657147708Sjkoshy			args.pa_required  |= FLAG_DO_GPROF;
658147708Sjkoshy			break;
659147708Sjkoshy
660145256Sjkoshy		case 'd':	/* toggle descendents */
661145256Sjkoshy			do_descendants = !do_descendants;
662147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
663145256Sjkoshy			break;
664145256Sjkoshy
665203790Sfabient		case 'F':	/* produce a system-wide calltree */
666203790Sfabient			args.pa_flags |= FLAG_DO_CALLGRAPHS;
667203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLTREE;
668203790Sfabient			graphfilename = optarg;
669203790Sfabient			break;
670203790Sfabient
671203790Sfabient		case 'f':	/* plugins options */
672203790Sfabient			if (args.pa_plugin == PMCSTAT_PL_NONE)
673203790Sfabient				err(EX_USAGE, "ERROR: Need -g/-G/-m/-T.");
674203790Sfabient			pmcstat_pluginconfigure_log(optarg);
675203790Sfabient			break;
676203790Sfabient
677174396Sjkoshy		case 'G':	/* produce a system-wide callgraph */
678174396Sjkoshy			args.pa_flags |= FLAG_DO_CALLGRAPHS;
679203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
680174396Sjkoshy			graphfilename = optarg;
681174396Sjkoshy			break;
682174396Sjkoshy
683147191Sjkoshy		case 'g':	/* produce gprof compatible profiles */
684147191Sjkoshy			args.pa_flags |= FLAG_DO_GPROF;
685203790Sfabient			args.pa_pplugin = PMCSTAT_PL_CALLGRAPH;
686203790Sfabient			args.pa_plugin	= PMCSTAT_PL_GPROF;
687147191Sjkoshy			break;
688147191Sjkoshy
689147708Sjkoshy		case 'k':	/* pathname to the kernel */
690157144Sjkoshy			free(args.pa_kernel);
691157144Sjkoshy			args.pa_kernel = strdup(optarg);
692174396Sjkoshy			args.pa_required |= FLAG_DO_ANALYSIS;
693147708Sjkoshy			args.pa_flags    |= FLAG_HAS_KERNELPATH;
694147191Sjkoshy			break;
695147191Sjkoshy
696185322Sattilio		case 'm':
697203790Sfabient			args.pa_flags |= FLAG_DO_ANNOTATE;
698203790Sfabient			args.pa_plugin = PMCSTAT_PL_ANNOTATE;
699203790Sfabient			graphfilename  = optarg;
700185322Sattilio			break;
701185322Sattilio
702147191Sjkoshy		case 'E':	/* log process exit */
703147191Sjkoshy			do_logprocexit = !do_logprocexit;
704147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
705147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
706147191Sjkoshy			break;
707147191Sjkoshy
708157144Sjkoshy		case 'M':	/* mapfile */
709157144Sjkoshy			args.pa_mapfilename = optarg;
710157144Sjkoshy			break;
711157144Sjkoshy
712174396Sjkoshy		case 'N':
713174396Sjkoshy			do_callchain = !do_callchain;
714174396Sjkoshy			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
715174396Sjkoshy			break;
716174396Sjkoshy
717145256Sjkoshy		case 'p':	/* process virtual counting PMC */
718145256Sjkoshy		case 's':	/* system-wide counting PMC */
719145256Sjkoshy		case 'P':	/* process virtual sampling PMC */
720145256Sjkoshy		case 'S':	/* system-wide sampling PMC */
721145256Sjkoshy			if ((ev = malloc(sizeof(*ev))) == NULL)
722147191Sjkoshy				errx(EX_SOFTWARE, "ERROR: Out of memory.");
723145256Sjkoshy
724145256Sjkoshy			switch (option) {
725145256Sjkoshy			case 'p': ev->ev_mode = PMC_MODE_TC; break;
726145256Sjkoshy			case 's': ev->ev_mode = PMC_MODE_SC; break;
727145256Sjkoshy			case 'P': ev->ev_mode = PMC_MODE_TS; break;
728145256Sjkoshy			case 'S': ev->ev_mode = PMC_MODE_SS; break;
729145256Sjkoshy			}
730145256Sjkoshy
731147191Sjkoshy			if (option == 'P' || option == 'p') {
732147191Sjkoshy				args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
733147708Sjkoshy				args.pa_required |= (FLAG_HAS_COMMANDLINE |
734169069Sjkoshy				    FLAG_HAS_TARGET);
735147191Sjkoshy			}
736145256Sjkoshy
737147191Sjkoshy			if (option == 'P' || option == 'S') {
738147191Sjkoshy				args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
739147708Sjkoshy				args.pa_required |= (FLAG_HAS_PIPE |
740147708Sjkoshy				    FLAG_HAS_OUTPUT_LOGFILE);
741147191Sjkoshy			}
742145256Sjkoshy
743145256Sjkoshy			if (option == 'p' || option == 's')
744147191Sjkoshy				args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
745145256Sjkoshy
746147191Sjkoshy			if (option == 's' || option == 'S')
747147191Sjkoshy				args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
748147191Sjkoshy
749145256Sjkoshy			ev->ev_spec  = strdup(optarg);
750145256Sjkoshy
751145256Sjkoshy			if (option == 'S' || option == 'P')
752145256Sjkoshy				ev->ev_count = current_sampling_count;
753145256Sjkoshy			else
754145256Sjkoshy				ev->ev_count = -1;
755145256Sjkoshy
756145256Sjkoshy			if (option == 'S' || option == 's')
757168949Sjkoshy				ev->ev_cpu = ffs(cpumask) - 1;
758145256Sjkoshy			else
759145256Sjkoshy				ev->ev_cpu = PMC_CPU_ANY;
760145256Sjkoshy
761147191Sjkoshy			ev->ev_flags = 0;
762174396Sjkoshy			if (do_callchain)
763174396Sjkoshy				ev->ev_flags |= PMC_F_CALLCHAIN;
764147191Sjkoshy			if (do_descendants)
765147191Sjkoshy				ev->ev_flags |= PMC_F_DESCENDANTS;
766147191Sjkoshy			if (do_logprocexit)
767147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCEXIT;
768147191Sjkoshy			if (do_logproccsw)
769147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCCSW;
770147191Sjkoshy
771145256Sjkoshy			ev->ev_cumulative  = use_cumulative_counts;
772145256Sjkoshy
773145256Sjkoshy			ev->ev_saved = 0LL;
774145256Sjkoshy			ev->ev_pmcid = PMC_ID_INVALID;
775145256Sjkoshy
776145256Sjkoshy			/* extract event name */
777145256Sjkoshy			c = strcspn(optarg, ", \t");
778145256Sjkoshy			ev->ev_name = malloc(c + 1);
779145256Sjkoshy			(void) strncpy(ev->ev_name, optarg, c);
780145256Sjkoshy			*(ev->ev_name + c) = '\0';
781145256Sjkoshy
782169069Sjkoshy			STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
783145256Sjkoshy
784168949Sjkoshy			if (option == 's' || option == 'S')
785203790Sfabient				pmcstat_clone_event_descriptor(ev,
786168949Sjkoshy				    cpumask & ~(1 << ev->ev_cpu));
787168949Sjkoshy
788145256Sjkoshy			break;
789145256Sjkoshy
790145256Sjkoshy		case 'n':	/* sampling count */
791145256Sjkoshy			current_sampling_count = strtol(optarg, &end, 0);
792145256Sjkoshy			if (*end != '\0' || current_sampling_count <= 0)
793145256Sjkoshy				errx(EX_USAGE,
794147191Sjkoshy				    "ERROR: Illegal count value \"%s\".",
795145256Sjkoshy				    optarg);
796147191Sjkoshy			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
797145256Sjkoshy			break;
798145256Sjkoshy
799145256Sjkoshy		case 'o':	/* outputfile */
800147708Sjkoshy			if (args.pa_printfile != NULL)
801147708Sjkoshy				(void) fclose(args.pa_printfile);
802147708Sjkoshy			if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
803145256Sjkoshy				errx(EX_OSERR, "ERROR: cannot open \"%s\" for "
804147191Sjkoshy				    "writing.", optarg);
805147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
806147191Sjkoshy			break;
807145256Sjkoshy
808145256Sjkoshy		case 'O':	/* sampling output */
809147708Sjkoshy			if (args.pa_outputpath)
810147708Sjkoshy				errx(EX_USAGE, "ERROR: option -O may only be "
811147191Sjkoshy				    "specified once.");
812147708Sjkoshy			args.pa_outputpath = optarg;
813147708Sjkoshy			args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
814145256Sjkoshy			break;
815145256Sjkoshy
816157144Sjkoshy		case 'q':	/* quiet mode */
817157144Sjkoshy			args.pa_verbosity = 0;
818157144Sjkoshy			break;
819157144Sjkoshy
820157144Sjkoshy		case 'r':	/* root FS path */
821157144Sjkoshy			args.pa_fsroot = optarg;
822157144Sjkoshy			break;
823157144Sjkoshy
824147708Sjkoshy		case 'R':	/* read an existing log file */
825174396Sjkoshy			if (args.pa_inputpath != NULL)
826147708Sjkoshy				errx(EX_USAGE, "ERROR: option -R may only be "
827147708Sjkoshy				    "specified once.");
828147708Sjkoshy			args.pa_inputpath = optarg;
829147708Sjkoshy			if (args.pa_printfile == stderr)
830147708Sjkoshy				args.pa_printfile = stdout;
831147708Sjkoshy			args.pa_flags |= FLAG_READ_LOGFILE;
832147708Sjkoshy			break;
833147708Sjkoshy
834169069Sjkoshy		case 't':	/* target pid or process name */
835203790Sfabient			pmcstat_find_targets(optarg);
836145256Sjkoshy
837169069Sjkoshy			args.pa_flags |= FLAG_HAS_TARGET;
838147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
839145256Sjkoshy			break;
840145256Sjkoshy
841203790Sfabient		case 'T':	/* top mode */
842203790Sfabient			args.pa_flags |= FLAG_DO_TOP;
843203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
844203790Sfabient			args.pa_ctdumpinstr = 0;
845203790Sfabient			args.pa_mergepmc = 1;
846203790Sfabient			if (args.pa_printfile == stderr)
847203790Sfabient				args.pa_printfile = stdout;
848203790Sfabient			break;
849203790Sfabient
850157144Sjkoshy		case 'v':	/* verbose */
851157144Sjkoshy			args.pa_verbosity++;
852157144Sjkoshy			break;
853157144Sjkoshy
854145256Sjkoshy		case 'w':	/* wait interval */
855145256Sjkoshy			interval = strtod(optarg, &end);
856145256Sjkoshy			if (*end != '\0' || interval <= 0)
857145256Sjkoshy				errx(EX_USAGE, "ERROR: Illegal wait interval "
858147191Sjkoshy				    "value \"%s\".", optarg);
859145256Sjkoshy			args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
860145256Sjkoshy			args.pa_interval = interval;
861147191Sjkoshy			break;
862145256Sjkoshy
863147191Sjkoshy		case 'W':	/* toggle LOG_CSW */
864147191Sjkoshy			do_logproccsw = !do_logproccsw;
865147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
866147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
867145256Sjkoshy			break;
868145256Sjkoshy
869174396Sjkoshy		case 'z':
870174396Sjkoshy			graphdepth = strtod(optarg, &end);
871174396Sjkoshy			if (*end != '\0' || graphdepth <= 0)
872174396Sjkoshy				errx(EX_USAGE, "ERROR: Illegal callchain "
873174396Sjkoshy				    "depth \"%s\".", optarg);
874174396Sjkoshy			args.pa_graphdepth = graphdepth;
875174396Sjkoshy			args.pa_required |= FLAG_DO_CALLGRAPHS;
876174396Sjkoshy			break;
877174396Sjkoshy
878145256Sjkoshy		case '?':
879145256Sjkoshy		default:
880145256Sjkoshy			pmcstat_show_usage();
881145256Sjkoshy			break;
882145256Sjkoshy
883145256Sjkoshy		}
884145256Sjkoshy
885145256Sjkoshy	args.pa_argc = (argc -= optind);
886145256Sjkoshy	args.pa_argv = (argv += optind);
887145256Sjkoshy
888174396Sjkoshy	args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
889174396Sjkoshy
890147708Sjkoshy	if (argc)	/* command line present */
891147708Sjkoshy		args.pa_flags |= FLAG_HAS_COMMANDLINE;
892145256Sjkoshy
893185322Sattilio	if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
894203790Sfabient	    FLAG_DO_ANNOTATE | FLAG_DO_TOP))
895174396Sjkoshy		args.pa_flags |= FLAG_DO_ANALYSIS;
896174396Sjkoshy
897145256Sjkoshy	/*
898145256Sjkoshy	 * Check invocation syntax.
899145256Sjkoshy	 */
900145256Sjkoshy
901147708Sjkoshy	/* disallow -O and -R together */
902147708Sjkoshy	if (args.pa_outputpath && args.pa_inputpath)
903147708Sjkoshy		errx(EX_USAGE, "ERROR: options -O and -R are mutually "
904147708Sjkoshy		    "exclusive.");
905147708Sjkoshy
906185322Sattilio	/* -m option is allowed with -R only. */
907203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
908185322Sattilio		errx(EX_USAGE, "ERROR: option -m requires an input file");
909185322Sattilio
910185322Sattilio	/* -m option is not allowed combined with -g or -G. */
911203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE &&
912185322Sattilio	    args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
913185322Sattilio		errx(EX_USAGE, "ERROR: option -m and -g | -G are mutually "
914185322Sattilio		    "exclusive");
915185322Sattilio
916147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
917147191Sjkoshy		errmsg = NULL;
918147708Sjkoshy		if (args.pa_flags & FLAG_HAS_COMMANDLINE)
919147191Sjkoshy			errmsg = "a command line specification";
920169069Sjkoshy		else if (args.pa_flags & FLAG_HAS_TARGET)
921147191Sjkoshy			errmsg = "option -t";
922169069Sjkoshy		else if (!STAILQ_EMPTY(&args.pa_events))
923147191Sjkoshy			errmsg = "a PMC event specification";
924147191Sjkoshy		if (errmsg)
925147191Sjkoshy			errx(EX_USAGE, "ERROR: option -R may not be used with "
926147191Sjkoshy			    "%s.", errmsg);
927169069Sjkoshy	} else if (STAILQ_EMPTY(&args.pa_events))
928147708Sjkoshy		/* All other uses require a PMC spec. */
929145256Sjkoshy		pmcstat_show_usage();
930145256Sjkoshy
931147191Sjkoshy	/* check for -t pid without a process PMC spec */
932169069Sjkoshy	if ((args.pa_required & FLAG_HAS_TARGET) &&
933147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
934147191Sjkoshy		errx(EX_USAGE, "ERROR: option -t requires a process mode PMC "
935147191Sjkoshy		    "to be specified.");
936147191Sjkoshy
937147191Sjkoshy	/* check for process-mode options without a command or -t pid */
938147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
939169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
940147708Sjkoshy		errx(EX_USAGE, "ERROR: options -d, -E, -p, -P, and -W require "
941147708Sjkoshy		    "a command line or target process.");
942147191Sjkoshy
943147191Sjkoshy	/* check for -p | -P without a target process of some sort */
944169069Sjkoshy	if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
945169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
946147708Sjkoshy		errx(EX_USAGE, "ERROR: options -P and -p require a "
947147191Sjkoshy		    "target process or a command line.");
948147191Sjkoshy
949147191Sjkoshy	/* check for process-mode options without a process-mode PMC */
950147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
951147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
952147708Sjkoshy		errx(EX_USAGE, "ERROR: options -d, -E, and -W require a "
953147191Sjkoshy		    "process mode PMC to be specified.");
954147191Sjkoshy
955174396Sjkoshy	/* check for -c cpu with no system mode PMCs or logfile. */
956147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
957174396Sjkoshy	    (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
958174396Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
959147191Sjkoshy		errx(EX_USAGE, "ERROR: option -c requires at least one "
960147191Sjkoshy		    "system mode PMC to be specified.");
961147191Sjkoshy
962147191Sjkoshy	/* check for counting mode options without a counting PMC */
963147191Sjkoshy	if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
964147191Sjkoshy	    (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
965203790Sfabient		errx(EX_USAGE, "ERROR: options -C, -W and -o require at "
966149805Sjkoshy		    "least one counting mode PMC to be specified.");
967147191Sjkoshy
968147191Sjkoshy	/* check for sampling mode options without a sampling PMC spec */
969147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
970147191Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
971174396Sjkoshy		errx(EX_USAGE, "ERROR: options -N, -n and -O require at "
972174396Sjkoshy		    "least one sampling mode PMC to be specified.");
973147191Sjkoshy
974203790Sfabient	/* check if -g/-G/-m/-T are being used correctly */
975174396Sjkoshy	if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
976147708Sjkoshy	    !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
977203790Sfabient		errx(EX_USAGE, "ERROR: options -g/-G/-m/-T require sampling PMCs "
978174396Sjkoshy		    "or -R to be specified.");
979147708Sjkoshy
980147191Sjkoshy	/* check if -O was spuriously specified */
981147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
982147708Sjkoshy	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
983147191Sjkoshy		errx(EX_USAGE,
984147191Sjkoshy		    "ERROR: option -O is used only with options "
985147708Sjkoshy		    "-E, -P, -S and -W.");
986147191Sjkoshy
987203790Sfabient	/* -k kernel path require -g/-G/-m/-T or -R */
988147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
989174396Sjkoshy	    (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
990157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
991203790Sfabient	    errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
992147708Sjkoshy
993174396Sjkoshy	/* -D only applies to gprof output mode (-g) */
994147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
995174396Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0)
996174396Sjkoshy	    errx(EX_USAGE, "ERROR: option -D is only used with -g.");
997147708Sjkoshy
998157144Sjkoshy	/* -M mapfile requires -g or -R */
999157144Sjkoshy	if (args.pa_mapfilename != NULL &&
1000157144Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0 &&
1001157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1002157144Sjkoshy	    errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
1003157144Sjkoshy
1004203790Sfabient	/* -T is incompatible with -R (replay logfile is a TODO) */
1005203790Sfabient	if ((args.pa_flags & FLAG_DO_TOP) &&
1006203790Sfabient	    (args.pa_flags & FLAG_READ_LOGFILE))
1007203790Sfabient		errx(EX_USAGE, "ERROR: option -T is incompatible with -R.");
1008203790Sfabient
1009147708Sjkoshy	/*
1010147708Sjkoshy	 * Disallow textual output of sampling PMCs if counting PMCs
1011147708Sjkoshy	 * have also been asked for, mostly because the combined output
1012147708Sjkoshy	 * is difficult to make sense of.
1013147708Sjkoshy	 */
1014147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1015147708Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1016168927Sjkoshy	    ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
1017147708Sjkoshy		errx(EX_USAGE, "ERROR: option -O is required if counting and "
1018147708Sjkoshy		    "sampling PMCs are specified together.");
1019147708Sjkoshy
1020157144Sjkoshy	/*
1021174396Sjkoshy	 * Check if "-k kerneldir" was specified, and if whether
1022174396Sjkoshy	 * 'kerneldir' actually refers to a a file.  If so, use
1023174396Sjkoshy	 * `dirname path` to determine the kernel directory.
1024157144Sjkoshy	 */
1025157144Sjkoshy	if (args.pa_flags & FLAG_HAS_KERNELPATH) {
1026157144Sjkoshy		(void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
1027157144Sjkoshy		    args.pa_kernel);
1028157144Sjkoshy		if (stat(buffer, &sb) < 0)
1029157144Sjkoshy			err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
1030157144Sjkoshy			    buffer);
1031157144Sjkoshy		if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
1032157144Sjkoshy			errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
1033157144Sjkoshy			    buffer);
1034157144Sjkoshy		if (!S_ISDIR(sb.st_mode)) {
1035157144Sjkoshy			tmp = args.pa_kernel;
1036157144Sjkoshy			args.pa_kernel = strdup(dirname(args.pa_kernel));
1037157144Sjkoshy			free(tmp);
1038157144Sjkoshy			(void) snprintf(buffer, sizeof(buffer), "%s%s",
1039157144Sjkoshy			    args.pa_fsroot, args.pa_kernel);
1040157144Sjkoshy			if (stat(buffer, &sb) < 0)
1041157144Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
1042157144Sjkoshy				    buffer);
1043157144Sjkoshy			if (!S_ISDIR(sb.st_mode))
1044157144Sjkoshy				errx(EX_USAGE, "ERROR: \"%s\" is not a "
1045157144Sjkoshy				    "directory.", buffer);
1046157144Sjkoshy		}
1047157144Sjkoshy	}
1048168949Sjkoshy
1049174396Sjkoshy	/*
1050174396Sjkoshy	 * If we have a callgraph be created, select the outputfile.
1051174396Sjkoshy	 */
1052174396Sjkoshy	if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
1053174396Sjkoshy		if (strcmp(graphfilename, "-") == 0)
1054174396Sjkoshy		    args.pa_graphfile = args.pa_printfile;
1055174396Sjkoshy		else {
1056174396Sjkoshy			args.pa_graphfile = fopen(graphfilename, "w");
1057174396Sjkoshy			if (args.pa_graphfile == NULL)
1058174396Sjkoshy				err(EX_OSERR, "ERROR: cannot open \"%s\" "
1059174396Sjkoshy				    "for writing", graphfilename);
1060174396Sjkoshy		}
1061174396Sjkoshy	}
1062203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE) {
1063185322Sattilio		args.pa_graphfile = fopen(graphfilename, "w");
1064185322Sattilio		if (args.pa_graphfile == NULL)
1065185322Sattilio			err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
1066185322Sattilio			    graphfilename);
1067185322Sattilio	}
1068174396Sjkoshy
1069147191Sjkoshy	/* if we've been asked to process a log file, do that and exit */
1070147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
1071147708Sjkoshy		/*
1072147708Sjkoshy		 * Print the log in textual form if we haven't been
1073174396Sjkoshy		 * asked to generate profiling information.
1074147708Sjkoshy		 */
1075174396Sjkoshy		if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1076147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
1077147708Sjkoshy
1078203790Sfabient		pmcstat_initialize_logging();
1079157406Sjkoshy		args.pa_logfd = pmcstat_open_log(args.pa_inputpath,
1080157406Sjkoshy		    PMCSTAT_OPEN_FOR_READ);
1081147708Sjkoshy		if ((args.pa_logparser = pmclog_open(args.pa_logfd)) == NULL)
1082147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot create parser");
1083203790Sfabient		pmcstat_process_log();
1084203790Sfabient		pmcstat_shutdown_logging();
1085147191Sjkoshy		exit(EX_OK);
1086147191Sjkoshy	}
1087147191Sjkoshy
1088147191Sjkoshy	/* otherwise, we've been asked to collect data */
1089145256Sjkoshy	if (pmc_init() < 0)
1090145256Sjkoshy		err(EX_UNAVAILABLE,
1091145256Sjkoshy		    "ERROR: Initialization of the pmc(3) library failed");
1092145256Sjkoshy
1093145256Sjkoshy	if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1094145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot determine the number of PMCs "
1095145256Sjkoshy		    "on CPU %d", 0);
1096145256Sjkoshy
1097147708Sjkoshy	/* Allocate a kqueue */
1098147708Sjkoshy	if ((pmcstat_kq = kqueue()) < 0)
1099147708Sjkoshy		err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1100147708Sjkoshy
1101145256Sjkoshy	/*
1102147708Sjkoshy	 * Configure the specified log file or setup a default log
1103147708Sjkoshy	 * consumer via a pipe.
1104147708Sjkoshy	 */
1105147708Sjkoshy	if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1106157406Sjkoshy		if (args.pa_outputpath)
1107157406Sjkoshy			args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1108157406Sjkoshy			    PMCSTAT_OPEN_FOR_WRITE);
1109157406Sjkoshy		else {
1110147708Sjkoshy			/*
1111147708Sjkoshy			 * process the log on the fly by reading it in
1112147708Sjkoshy			 * through a pipe.
1113147708Sjkoshy			 */
1114147708Sjkoshy			if (pipe(pipefd) < 0)
1115147708Sjkoshy				err(EX_OSERR, "ERROR: pipe(2) failed");
1116147708Sjkoshy
1117147708Sjkoshy			if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1118147708Sjkoshy				err(EX_OSERR, "ERROR: fcntl(2) failed");
1119147708Sjkoshy
1120147708Sjkoshy			EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1121147708Sjkoshy			    0, 0, NULL);
1122147708Sjkoshy
1123147708Sjkoshy			if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1124147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot register kevent");
1125147708Sjkoshy
1126147708Sjkoshy			args.pa_logfd = pipefd[WRITEPIPEFD];
1127147708Sjkoshy
1128203790Sfabient			args.pa_flags |= FLAG_HAS_PIPE;
1129203790Sfabient			if ((args.pa_flags & FLAG_DO_TOP) == 0)
1130203790Sfabient				args.pa_flags |= FLAG_DO_PRINT;
1131147708Sjkoshy			args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1132147708Sjkoshy		}
1133147708Sjkoshy
1134147708Sjkoshy		if (pmc_configure_logfile(args.pa_logfd) < 0)
1135147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot configure log file");
1136147708Sjkoshy	}
1137147708Sjkoshy
1138151542Sjkoshy	/* remember to check for driver errors if we are sampling or logging */
1139151542Sjkoshy	check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1140151542Sjkoshy	    (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1141151542Sjkoshy
1142147708Sjkoshy	/*
1143145256Sjkoshy	 * Allocate PMCs.
1144145256Sjkoshy	 */
1145145256Sjkoshy
1146169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1147145256Sjkoshy	    if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1148147191Sjkoshy		    ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1149145256Sjkoshy		    err(EX_OSERR, "ERROR: Cannot allocate %s-mode pmc with "
1150145256Sjkoshy			"specification \"%s\"",
1151145256Sjkoshy			PMC_IS_SYSTEM_MODE(ev->ev_mode) ? "system" : "process",
1152145256Sjkoshy			ev->ev_spec);
1153145256Sjkoshy
1154147708Sjkoshy	    if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1155147708Sjkoshy		pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1156147708Sjkoshy		    err(EX_OSERR, "ERROR: Cannot set sampling count "
1157147708Sjkoshy			"for PMC \"%s\"", ev->ev_name);
1158147708Sjkoshy	}
1159147708Sjkoshy
1160145256Sjkoshy	/* compute printout widths */
1161169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1162145774Sjkoshy		int counter_width;
1163145774Sjkoshy		int display_width;
1164145774Sjkoshy		int header_width;
1165145256Sjkoshy
1166145774Sjkoshy		(void) pmc_width(ev->ev_pmcid, &counter_width);
1167168949Sjkoshy		header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1168145774Sjkoshy		display_width = (int) floor(counter_width / 3.32193) + 1;
1169145256Sjkoshy
1170168949Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1171168949Sjkoshy			header_width += 3; /* 2 digit CPU number + '/' */
1172168949Sjkoshy
1173145774Sjkoshy		if (header_width > display_width) {
1174145256Sjkoshy			ev->ev_fieldskip = 0;
1175145774Sjkoshy			ev->ev_fieldwidth = header_width;
1176145256Sjkoshy		} else {
1177145774Sjkoshy			ev->ev_fieldskip = display_width -
1178145774Sjkoshy			    header_width;
1179145774Sjkoshy			ev->ev_fieldwidth = display_width;
1180145256Sjkoshy		}
1181145256Sjkoshy	}
1182145256Sjkoshy
1183145256Sjkoshy	/*
1184145256Sjkoshy	 * If our output is being set to a terminal, register a handler
1185145256Sjkoshy	 * for window size changes.
1186145256Sjkoshy	 */
1187145256Sjkoshy
1188147708Sjkoshy	if (isatty(fileno(args.pa_printfile))) {
1189145256Sjkoshy
1190147708Sjkoshy		if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1191145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot determine window size");
1192145256Sjkoshy
1193145256Sjkoshy		pmcstat_displayheight = ws.ws_row - 1;
1194203790Sfabient		pmcstat_displaywidth  = ws.ws_col - 1;
1195145256Sjkoshy
1196145256Sjkoshy		EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1197145256Sjkoshy
1198145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1199145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot register kevent for "
1200145256Sjkoshy			    "SIGWINCH");
1201203790Sfabient
1202203790Sfabient		args.pa_toptty = 1;
1203145256Sjkoshy	}
1204145256Sjkoshy
1205203790Sfabient	/*
1206203790Sfabient	 * Listen to key input in top mode.
1207203790Sfabient	 */
1208203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1209203790Sfabient		EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1210203790Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1211203790Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1212203790Sfabient	}
1213203790Sfabient
1214145256Sjkoshy	EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1215145256Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1216145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1217145256Sjkoshy
1218147191Sjkoshy	EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1219147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1220147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1221145256Sjkoshy
1222147191Sjkoshy	/*
1223147191Sjkoshy	 * An exec() failure of a forked child is signalled by the
1224147191Sjkoshy	 * child sending the parent a SIGCHLD.  We don't register an
1225147191Sjkoshy	 * actual signal handler for SIGCHLD, but instead use our
1226147191Sjkoshy	 * kqueue to pick up the signal.
1227147191Sjkoshy	 */
1228147191Sjkoshy	EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1229147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1230147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1231145256Sjkoshy
1232203790Sfabient	/*
1233203790Sfabient	 * Setup a timer if we have counting mode PMCs needing to be printed or
1234203790Sfabient	 * top mode plugin is active.
1235203790Sfabient	 */
1236203790Sfabient	if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1237203790Sfabient	     (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1238203790Sfabient	    (args.pa_flags & FLAG_DO_TOP)) {
1239145256Sjkoshy		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1240145256Sjkoshy		    args.pa_interval * 1000, NULL);
1241145256Sjkoshy
1242145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1243145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot register kevent for "
1244145256Sjkoshy			    "timer");
1245145256Sjkoshy	}
1246145256Sjkoshy
1247145256Sjkoshy	/* attach PMCs to the target process, starting it if specified */
1248168949Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1249203790Sfabient		pmcstat_create_process();
1250145256Sjkoshy
1251151542Sjkoshy	if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1252151542Sjkoshy		err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1253151542Sjkoshy
1254168949Sjkoshy	/* Attach process pmcs to the target process. */
1255180148Sjkoshy	if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1256169069Sjkoshy		if (SLIST_EMPTY(&args.pa_targets))
1257169069Sjkoshy			errx(EX_DATAERR, "ERROR: No matching target "
1258169069Sjkoshy			    "processes.");
1259183672Sjkoshy		if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1260203790Sfabient			pmcstat_attach_pmcs();
1261168949Sjkoshy
1262169069Sjkoshy		if (pmcstat_kvm) {
1263169069Sjkoshy			kvm_close(pmcstat_kvm);
1264169069Sjkoshy			pmcstat_kvm = NULL;
1265169069Sjkoshy		}
1266169069Sjkoshy	}
1267169069Sjkoshy
1268145256Sjkoshy	/* start the pmcs */
1269203790Sfabient	pmcstat_start_pmcs();
1270145256Sjkoshy
1271145256Sjkoshy	/* start the (commandline) process if needed */
1272147708Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1273168949Sjkoshy		pmcstat_start_process();
1274145256Sjkoshy
1275147708Sjkoshy	/* initialize logging if printing the configured log */
1276203790Sfabient	if ((args.pa_flags & (FLAG_DO_PRINT | FLAG_DO_TOP)) &&
1277147708Sjkoshy	    (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE)))
1278203790Sfabient		pmcstat_initialize_logging();
1279147708Sjkoshy
1280145256Sjkoshy	/* Handle SIGINT using the kqueue loop */
1281145256Sjkoshy	sa.sa_handler = SIG_IGN;
1282145256Sjkoshy	sa.sa_flags   = 0;
1283145256Sjkoshy	(void) sigemptyset(&sa.sa_mask);
1284145256Sjkoshy
1285145256Sjkoshy	if (sigaction(SIGINT, &sa, NULL) < 0)
1286145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot install signal handler");
1287145256Sjkoshy
1288145256Sjkoshy	/*
1289203790Sfabient	 * Setup the top mode display.
1290203790Sfabient	 */
1291203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1292203790Sfabient		args.pa_flags &= ~FLAG_DO_PRINT;
1293203790Sfabient
1294203790Sfabient		if (args.pa_toptty) {
1295203790Sfabient			/*
1296203790Sfabient			 * Init ncurses.
1297203790Sfabient			 */
1298203790Sfabient			initscr();
1299203790Sfabient			if(has_colors() == TRUE) {
1300203790Sfabient				args.pa_topcolor = 1;
1301203790Sfabient				start_color();
1302203790Sfabient				use_default_colors();
1303203790Sfabient				pair_content(0, &cf, &cb);
1304203790Sfabient				init_pair(1, COLOR_RED, cb);
1305203790Sfabient				init_pair(2, COLOR_YELLOW, cb);
1306203790Sfabient				init_pair(3, COLOR_GREEN, cb);
1307203790Sfabient			}
1308203790Sfabient			cbreak();
1309203790Sfabient			noecho();
1310203790Sfabient			nonl();
1311203790Sfabient			nodelay(stdscr, 1);
1312203790Sfabient			intrflush(stdscr, FALSE);
1313203790Sfabient			keypad(stdscr, TRUE);
1314203790Sfabient			clear();
1315204783Sfabient			/* Get terminal width / height with ncurses. */
1316204783Sfabient			getmaxyx(stdscr, pmcstat_displayheight, pmcstat_displaywidth);
1317204783Sfabient			pmcstat_displayheight--; pmcstat_displaywidth--;
1318203790Sfabient			atexit(pmcstat_topexit);
1319203790Sfabient		}
1320203790Sfabient	}
1321203790Sfabient
1322203790Sfabient	/*
1323145256Sjkoshy	 * loop till either the target process (if any) exits, or we
1324145256Sjkoshy	 * are killed by a SIGINT.
1325145256Sjkoshy	 */
1326147191Sjkoshy	runstate = PMCSTAT_RUNNING;
1327147191Sjkoshy	do_print = 0;
1328145256Sjkoshy	do {
1329145256Sjkoshy		if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1330145256Sjkoshy			if (errno != EINTR)
1331145256Sjkoshy				err(EX_OSERR, "ERROR: kevent failed");
1332145256Sjkoshy			else
1333145256Sjkoshy				continue;
1334145256Sjkoshy		}
1335145256Sjkoshy
1336145256Sjkoshy		if (kev.flags & EV_ERROR)
1337145256Sjkoshy			errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1338145256Sjkoshy
1339145256Sjkoshy		switch (kev.filter) {
1340147191Sjkoshy		case EVFILT_PROC:  /* target has exited */
1341147708Sjkoshy			if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE |
1342147708Sjkoshy				FLAG_HAS_PIPE))
1343203790Sfabient				runstate = pmcstat_close_log();
1344148688Sjkoshy			else
1345148688Sjkoshy				runstate = PMCSTAT_FINISHED;
1346148688Sjkoshy			do_print = 1;
1347147191Sjkoshy			break;
1348145256Sjkoshy
1349147191Sjkoshy		case EVFILT_READ:  /* log file data is present */
1350203790Sfabient			if (kev.ident == (unsigned)fileno(stdin)) {
1351203790Sfabient				if (pmcstat_keypress_log())
1352203790Sfabient					runstate = pmcstat_close_log();
1353203790Sfabient			} else
1354203790Sfabient				runstate = pmcstat_process_log();
1355145256Sjkoshy			break;
1356145256Sjkoshy
1357145256Sjkoshy		case EVFILT_SIGNAL:
1358147191Sjkoshy			if (kev.ident == SIGCHLD) {
1359147191Sjkoshy				/*
1360147191Sjkoshy				 * The child process sends us a
1361147191Sjkoshy				 * SIGCHLD if its exec() failed.  We
1362147191Sjkoshy				 * wait for it to exit and then exit
1363147191Sjkoshy				 * ourselves.
1364147191Sjkoshy				 */
1365147191Sjkoshy				(void) wait(&c);
1366147191Sjkoshy				runstate = PMCSTAT_FINISHED;
1367147191Sjkoshy			} else if (kev.ident == SIGIO) {
1368147191Sjkoshy				/*
1369147191Sjkoshy				 * We get a SIGIO if a PMC loses all
1370147191Sjkoshy				 * of its targets, or if logfile
1371147191Sjkoshy				 * writes encounter an error.
1372147191Sjkoshy				 */
1373147708Sjkoshy				if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE |
1374147708Sjkoshy				    FLAG_HAS_PIPE)) {
1375203790Sfabient					runstate = pmcstat_close_log();
1376147708Sjkoshy					if (args.pa_flags &
1377174396Sjkoshy					    (FLAG_DO_PRINT|FLAG_DO_ANALYSIS))
1378203790Sfabient						pmcstat_process_log();
1379147708Sjkoshy				}
1380147191Sjkoshy				do_print = 1; /* print PMCs at exit */
1381147191Sjkoshy				runstate = PMCSTAT_FINISHED;
1382147191Sjkoshy			} else if (kev.ident == SIGINT) {
1383147708Sjkoshy				/* Kill the child process if we started it */
1384147708Sjkoshy				if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1385203790Sfabient					pmcstat_kill_process();
1386186425Sjkoshy				/* Close the pipe to self, if present. */
1387186425Sjkoshy				if (args.pa_flags & FLAG_HAS_PIPE)
1388186425Sjkoshy					(void) close(pipefd[READPIPEFD]);
1389147191Sjkoshy				runstate = PMCSTAT_FINISHED;
1390145256Sjkoshy			} else if (kev.ident == SIGWINCH) {
1391147708Sjkoshy				if (ioctl(fileno(args.pa_printfile),
1392145256Sjkoshy					TIOCGWINSZ, &ws) < 0)
1393145256Sjkoshy				    err(EX_OSERR, "ERROR: Cannot determine "
1394145256Sjkoshy					"window size");
1395145256Sjkoshy				pmcstat_displayheight = ws.ws_row - 1;
1396203790Sfabient				pmcstat_displaywidth  = ws.ws_col - 1;
1397145256Sjkoshy			} else
1398145256Sjkoshy				assert(0);
1399145256Sjkoshy
1400145256Sjkoshy			break;
1401147191Sjkoshy
1402147191Sjkoshy		case EVFILT_TIMER: /* print out counting PMCs */
1403147191Sjkoshy			do_print = 1;
1404147191Sjkoshy			break;
1405147191Sjkoshy
1406145256Sjkoshy		}
1407145256Sjkoshy
1408203790Sfabient		if (do_print) {
1409203790Sfabient			if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1410203790Sfabient				pmcstat_print_pmcs();
1411203790Sfabient				if (runstate == PMCSTAT_FINISHED && /* final newline */
1412203790Sfabient				    (args.pa_flags & FLAG_DO_PRINT) == 0)
1413203790Sfabient					(void) fprintf(args.pa_printfile, "\n");
1414203790Sfabient			}
1415203790Sfabient			if (args.pa_flags & FLAG_DO_TOP)
1416203790Sfabient				pmcstat_display_log();
1417147191Sjkoshy			do_print = 0;
1418147191Sjkoshy		}
1419145256Sjkoshy
1420147191Sjkoshy	} while (runstate != PMCSTAT_FINISHED);
1421147191Sjkoshy
1422203790Sfabient	if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1423203790Sfabient		pmcstat_topexit();
1424203790Sfabient		args.pa_toptty = 0;
1425203790Sfabient	}
1426203790Sfabient
1427147191Sjkoshy	/* flush any pending log entries */
1428147708Sjkoshy	if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1429147191Sjkoshy		pmc_flush_logfile();
1430147191Sjkoshy
1431203790Sfabient	pmcstat_cleanup();
1432145256Sjkoshy
1433157144Sjkoshy	free(args.pa_kernel);
1434157144Sjkoshy
1435151542Sjkoshy	/* check if the driver lost any samples or events */
1436151542Sjkoshy	if (check_driver_stats) {
1437151542Sjkoshy		if (pmc_get_driver_stats(&ds_end) < 0)
1438151542Sjkoshy			err(EX_OSERR, "ERROR: Cannot retrieve driver "
1439151542Sjkoshy			    "statistics");
1440157144Sjkoshy		if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1441157144Sjkoshy		    args.pa_verbosity > 0)
1442153704Sjkoshy			warnx("WARNING: some samples were dropped.  Please "
1443151542Sjkoshy			    "consider tuning the \"kern.hwpmc.nsamples\" "
1444151542Sjkoshy			    "tunable.");
1445151542Sjkoshy		if (ds_start.pm_buffer_requests_failed !=
1446157144Sjkoshy		    ds_end.pm_buffer_requests_failed &&
1447157144Sjkoshy		    args.pa_verbosity > 0)
1448153704Sjkoshy			warnx("WARNING: some events were discarded.  Please "
1449151542Sjkoshy			    "consider tuning the \"kern.hwpmc.nbuffers\" "
1450151542Sjkoshy			    "tunable.");
1451151542Sjkoshy	}
1452151542Sjkoshy
1453151542Sjkoshy	exit(EX_OK);
1454145256Sjkoshy}
1455