pmcstat.c revision 210797
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 210797 2010-08-03 13:46:25Z 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
172210794Sfabient	pmcstat_shutdown_logging();
173145256Sjkoshy}
174145256Sjkoshy
175145256Sjkoshyvoid
176203790Sfabientpmcstat_clone_event_descriptor(struct pmcstat_ev *ev,
177168949Sjkoshy    uint32_t cpumask)
178168949Sjkoshy{
179168949Sjkoshy	int cpu;
180168949Sjkoshy	struct pmcstat_ev *ev_clone;
181168949Sjkoshy
182168949Sjkoshy	while ((cpu = ffs(cpumask)) > 0) {
183168949Sjkoshy		cpu--;
184168949Sjkoshy
185168949Sjkoshy		if ((ev_clone = malloc(sizeof(*ev_clone))) == NULL)
186168949Sjkoshy			errx(EX_SOFTWARE, "ERROR: Out of memory");
187168949Sjkoshy		(void) memset(ev_clone, 0, sizeof(*ev_clone));
188168949Sjkoshy
189168949Sjkoshy		ev_clone->ev_count = ev->ev_count;
190168949Sjkoshy		ev_clone->ev_cpu   = cpu;
191168949Sjkoshy		ev_clone->ev_cumulative = ev->ev_cumulative;
192168949Sjkoshy		ev_clone->ev_flags = ev->ev_flags;
193168949Sjkoshy		ev_clone->ev_mode  = ev->ev_mode;
194168949Sjkoshy		ev_clone->ev_name  = strdup(ev->ev_name);
195168949Sjkoshy		ev_clone->ev_pmcid = ev->ev_pmcid;
196168949Sjkoshy		ev_clone->ev_saved = ev->ev_saved;
197168949Sjkoshy		ev_clone->ev_spec  = strdup(ev->ev_spec);
198168949Sjkoshy
199203790Sfabient		STAILQ_INSERT_TAIL(&args.pa_events, ev_clone, ev_next);
200168949Sjkoshy
201168949Sjkoshy		cpumask &= ~(1 << cpu);
202168949Sjkoshy	}
203168949Sjkoshy}
204168949Sjkoshy
205168949Sjkoshyvoid
206203790Sfabientpmcstat_create_process(void)
207168949Sjkoshy{
208168949Sjkoshy	char token;
209169069Sjkoshy	pid_t pid;
210168949Sjkoshy	struct kevent kev;
211169069Sjkoshy	struct pmcstat_target *pt;
212168949Sjkoshy
213168949Sjkoshy	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pmcstat_sockpair) < 0)
214168949Sjkoshy		err(EX_OSERR, "ERROR: cannot create socket pair");
215168949Sjkoshy
216169069Sjkoshy	switch (pid = fork()) {
217168949Sjkoshy	case -1:
218168949Sjkoshy		err(EX_OSERR, "ERROR: cannot fork");
219168949Sjkoshy		/*NOTREACHED*/
220168949Sjkoshy
221168949Sjkoshy	case 0:		/* child */
222168949Sjkoshy		(void) close(pmcstat_sockpair[PARENTSOCKET]);
223168949Sjkoshy
224168949Sjkoshy		/* Write a token to tell our parent we've started executing. */
225168949Sjkoshy		if (write(pmcstat_sockpair[CHILDSOCKET], "+", 1) != 1)
226168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot write token");
227168949Sjkoshy
228168949Sjkoshy		/* Wait for our parent to signal us to start. */
229168949Sjkoshy		if (read(pmcstat_sockpair[CHILDSOCKET], &token, 1) < 0)
230168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot read token");
231168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
232168949Sjkoshy
233168949Sjkoshy		/* exec() the program requested */
234203790Sfabient		execvp(*args.pa_argv, args.pa_argv);
235168949Sjkoshy		/* and if that fails, notify the parent */
236168949Sjkoshy		kill(getppid(), SIGCHLD);
237203790Sfabient		err(EX_OSERR, "ERROR: execvp \"%s\" failed", *args.pa_argv);
238168949Sjkoshy		/*NOTREACHED*/
239168949Sjkoshy
240168949Sjkoshy	default:	/* parent */
241168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
242168949Sjkoshy		break;
243168949Sjkoshy	}
244168949Sjkoshy
245168949Sjkoshy	/* Ask to be notified via a kevent when the target process exits. */
246169069Sjkoshy	EV_SET(&kev, pid, EVFILT_PROC, EV_ADD|EV_ONESHOT, NOTE_EXIT, 0,
247168949Sjkoshy	    NULL);
248168949Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
249169069Sjkoshy		err(EX_OSERR, "ERROR: cannot monitor child process %d", pid);
250168949Sjkoshy
251169069Sjkoshy	if ((pt = malloc(sizeof(*pt))) == NULL)
252169069Sjkoshy		errx(EX_SOFTWARE, "ERROR: Out of memory.");
253169069Sjkoshy
254169069Sjkoshy	pt->pt_pid = pid;
255203790Sfabient	SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
256169069Sjkoshy
257168949Sjkoshy	/* Wait for the child to signal that its ready to go. */
258168949Sjkoshy	if (read(pmcstat_sockpair[PARENTSOCKET], &token, 1) < 0)
259168949Sjkoshy		err(EX_OSERR, "ERROR (parent): cannot read token");
260168949Sjkoshy
261168949Sjkoshy	return;
262168949Sjkoshy}
263168949Sjkoshy
264169069Sjkoshyvoid
265203790Sfabientpmcstat_find_targets(const char *spec)
266169069Sjkoshy{
267169069Sjkoshy	int n, nproc, pid, rv;
268169069Sjkoshy	struct pmcstat_target *pt;
269169069Sjkoshy	char errbuf[_POSIX2_LINE_MAX], *end;
270169069Sjkoshy	static struct kinfo_proc *kp;
271169069Sjkoshy	regex_t reg;
272169069Sjkoshy	regmatch_t regmatch;
273169069Sjkoshy
274169069Sjkoshy	/* First check if we've been given a process id. */
275169069Sjkoshy      	pid = strtol(spec, &end, 0);
276169069Sjkoshy	if (end != spec && pid >= 0) {
277169069Sjkoshy		if ((pt = malloc(sizeof(*pt))) == NULL)
278169069Sjkoshy			goto outofmemory;
279169069Sjkoshy		pt->pt_pid = pid;
280203790Sfabient		SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
281169069Sjkoshy		return;
282169069Sjkoshy	}
283169069Sjkoshy
284169069Sjkoshy	/* Otherwise treat arg as a regular expression naming processes. */
285169069Sjkoshy	if (pmcstat_kvm == NULL) {
286169069Sjkoshy		if ((pmcstat_kvm = kvm_openfiles(NULL, "/dev/null", NULL, 0,
287169069Sjkoshy		    errbuf)) == NULL)
288169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot open kernel \"%s\"",
289169069Sjkoshy			    errbuf);
290169069Sjkoshy		if ((pmcstat_plist = kvm_getprocs(pmcstat_kvm, KERN_PROC_PROC,
291169069Sjkoshy		    0, &nproc)) == NULL)
292169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot get process list: %s",
293169069Sjkoshy			    kvm_geterr(pmcstat_kvm));
294208858Sfabient	} else
295208858Sfabient		nproc = 0;
296169069Sjkoshy
297169069Sjkoshy	if ((rv = regcomp(&reg, spec, REG_EXTENDED|REG_NOSUB)) != 0) {
298169069Sjkoshy		regerror(rv, &reg, errbuf, sizeof(errbuf));
299169069Sjkoshy		err(EX_DATAERR, "ERROR: Failed to compile regex \"%s\": %s",
300169069Sjkoshy		    spec, errbuf);
301169069Sjkoshy	}
302169069Sjkoshy
303169069Sjkoshy	for (n = 0, kp = pmcstat_plist; n < nproc; n++, kp++) {
304169069Sjkoshy		if ((rv = regexec(&reg, kp->ki_comm, 1, &regmatch, 0)) == 0) {
305169069Sjkoshy			if ((pt = malloc(sizeof(*pt))) == NULL)
306169069Sjkoshy				goto outofmemory;
307169069Sjkoshy			pt->pt_pid = kp->ki_pid;
308203790Sfabient			SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
309169069Sjkoshy		} else if (rv != REG_NOMATCH) {
310169069Sjkoshy			regerror(rv, &reg, errbuf, sizeof(errbuf));
311169069Sjkoshy			errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s",
312169069Sjkoshy			    errbuf);
313169069Sjkoshy		}
314169069Sjkoshy	}
315169069Sjkoshy
316169069Sjkoshy	regfree(&reg);
317169069Sjkoshy
318169069Sjkoshy	return;
319169069Sjkoshy
320169069Sjkoshy outofmemory:
321169069Sjkoshy	errx(EX_SOFTWARE, "Out of memory.");
322169069Sjkoshy	/*NOTREACHED*/
323169069Sjkoshy}
324169069Sjkoshy
325168949Sjkoshyuint32_t
326168949Sjkoshypmcstat_get_cpumask(const char *cpuspec)
327168949Sjkoshy{
328168949Sjkoshy	uint32_t cpumask;
329168949Sjkoshy	int cpu;
330168949Sjkoshy	const char *s;
331168949Sjkoshy	char *end;
332168949Sjkoshy
333168949Sjkoshy	s = cpuspec;
334168949Sjkoshy	cpumask = 0ULL;
335168949Sjkoshy
336168949Sjkoshy	do {
337168949Sjkoshy		cpu = strtol(s, &end, 0);
338168949Sjkoshy		if (cpu < 0 || end == s)
339168949Sjkoshy			errx(EX_USAGE, "ERROR: Illegal CPU specification "
340168949Sjkoshy			    "\"%s\".", cpuspec);
341168949Sjkoshy		cpumask |= (1 << cpu);
342168949Sjkoshy		s = end + strspn(end, ", \t");
343168949Sjkoshy	} while (*s);
344168949Sjkoshy
345168949Sjkoshy	return (cpumask);
346168949Sjkoshy}
347168949Sjkoshy
348168949Sjkoshyvoid
349203790Sfabientpmcstat_kill_process(void)
350169069Sjkoshy{
351169069Sjkoshy	struct pmcstat_target *pt;
352169069Sjkoshy
353203790Sfabient	assert(args.pa_flags & FLAG_HAS_COMMANDLINE);
354169069Sjkoshy
355169069Sjkoshy	/*
356169069Sjkoshy	 * If a command line was specified, it would be the very first
357169069Sjkoshy	 * in the list, before any other processes specified by -t.
358169069Sjkoshy	 */
359203790Sfabient	pt = SLIST_FIRST(&args.pa_targets);
360169069Sjkoshy	assert(pt != NULL);
361169069Sjkoshy
362169069Sjkoshy	if (kill(pt->pt_pid, SIGINT) != 0)
363169069Sjkoshy		err(EX_OSERR, "ERROR: cannot signal child process");
364169069Sjkoshy}
365169069Sjkoshy
366169069Sjkoshyvoid
367203790Sfabientpmcstat_start_pmcs(void)
368145256Sjkoshy{
369145256Sjkoshy	struct pmcstat_ev *ev;
370145256Sjkoshy
371169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
372145256Sjkoshy
373145256Sjkoshy	    assert(ev->ev_pmcid != PMC_ID_INVALID);
374145256Sjkoshy
375145256Sjkoshy	    if (pmc_start(ev->ev_pmcid) < 0) {
376147191Sjkoshy	        warn("ERROR: Cannot start pmc 0x%x \"%s\"",
377145256Sjkoshy		    ev->ev_pmcid, ev->ev_name);
378203790Sfabient		pmcstat_cleanup();
379147191Sjkoshy		exit(EX_OSERR);
380145256Sjkoshy	    }
381145256Sjkoshy	}
382145256Sjkoshy
383145256Sjkoshy}
384145256Sjkoshy
385145256Sjkoshyvoid
386203790Sfabientpmcstat_print_headers(void)
387145256Sjkoshy{
388145256Sjkoshy	struct pmcstat_ev *ev;
389168949Sjkoshy	int c, w;
390145256Sjkoshy
391203790Sfabient	(void) fprintf(args.pa_printfile, PRINT_HEADER_PREFIX);
392145256Sjkoshy
393203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
394145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
395145256Sjkoshy			continue;
396145256Sjkoshy
397145256Sjkoshy		c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p';
398145256Sjkoshy
399168949Sjkoshy		if (ev->ev_fieldskip != 0)
400203790Sfabient			(void) fprintf(args.pa_printfile, "%*s",
401168949Sjkoshy			    ev->ev_fieldskip, "");
402168949Sjkoshy		w = ev->ev_fieldwidth - ev->ev_fieldskip - 2;
403168949Sjkoshy
404168949Sjkoshy		if (c == 's')
405203790Sfabient			(void) fprintf(args.pa_printfile, "s/%02d/%-*s ",
406168949Sjkoshy			    ev->ev_cpu, w-3, ev->ev_name);
407168949Sjkoshy		else
408203790Sfabient			(void) fprintf(args.pa_printfile, "p/%*s ", w,
409145256Sjkoshy			    ev->ev_name);
410145256Sjkoshy	}
411145256Sjkoshy
412203790Sfabient	(void) fflush(args.pa_printfile);
413145256Sjkoshy}
414145256Sjkoshy
415145256Sjkoshyvoid
416203790Sfabientpmcstat_print_counters(void)
417145256Sjkoshy{
418145256Sjkoshy	int extra_width;
419145256Sjkoshy	struct pmcstat_ev *ev;
420145256Sjkoshy	pmc_value_t value;
421145256Sjkoshy
422145256Sjkoshy	extra_width = sizeof(PRINT_HEADER_PREFIX) - 1;
423145256Sjkoshy
424203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
425145256Sjkoshy
426145256Sjkoshy		/* skip sampling mode counters */
427145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
428145256Sjkoshy			continue;
429145256Sjkoshy
430145256Sjkoshy		if (pmc_read(ev->ev_pmcid, &value) < 0)
431145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot read pmc "
432145256Sjkoshy			    "\"%s\"", ev->ev_name);
433145256Sjkoshy
434203790Sfabient		(void) fprintf(args.pa_printfile, "%*ju ",
435147708Sjkoshy		    ev->ev_fieldwidth + extra_width,
436147708Sjkoshy		    (uintmax_t) ev->ev_cumulative ? value :
437147708Sjkoshy		    (value - ev->ev_saved));
438147708Sjkoshy
439145256Sjkoshy		if (ev->ev_cumulative == 0)
440145256Sjkoshy			ev->ev_saved = value;
441145256Sjkoshy		extra_width = 0;
442145256Sjkoshy	}
443145256Sjkoshy
444203790Sfabient	(void) fflush(args.pa_printfile);
445145256Sjkoshy}
446145256Sjkoshy
447145256Sjkoshy/*
448145256Sjkoshy * Print output
449145256Sjkoshy */
450145256Sjkoshy
451145256Sjkoshyvoid
452203790Sfabientpmcstat_print_pmcs(void)
453145256Sjkoshy{
454145256Sjkoshy	static int linecount = 0;
455145256Sjkoshy
456147708Sjkoshy	/* check if we need to print a header line */
457145256Sjkoshy	if (++linecount > pmcstat_displayheight) {
458203790Sfabient		(void) fprintf(args.pa_printfile, "\n");
459145256Sjkoshy		linecount = 1;
460145256Sjkoshy	}
461145256Sjkoshy	if (linecount == 1)
462203790Sfabient		pmcstat_print_headers();
463203790Sfabient	(void) fprintf(args.pa_printfile, "\n");
464145256Sjkoshy
465203790Sfabient	pmcstat_print_counters();
466145256Sjkoshy
467145256Sjkoshy	return;
468145256Sjkoshy}
469145256Sjkoshy
470145256Sjkoshy/*
471145256Sjkoshy * Do process profiling
472145256Sjkoshy *
473145256Sjkoshy * If a pid was specified, attach each allocated PMC to the target
474145256Sjkoshy * process.  Otherwise, fork a child and attach the PMCs to the child,
475145256Sjkoshy * and have the child exec() the target program.
476145256Sjkoshy */
477145256Sjkoshy
478145256Sjkoshyvoid
479168949Sjkoshypmcstat_start_process(void)
480145256Sjkoshy{
481168949Sjkoshy	/* Signal the child to proceed. */
482168949Sjkoshy	if (write(pmcstat_sockpair[PARENTSOCKET], "!", 1) != 1)
483168949Sjkoshy		err(EX_OSERR, "ERROR (parent): write of token failed");
484145256Sjkoshy
485168949Sjkoshy	(void) close(pmcstat_sockpair[PARENTSOCKET]);
486145256Sjkoshy}
487145256Sjkoshy
488145256Sjkoshyvoid
489145256Sjkoshypmcstat_show_usage(void)
490145256Sjkoshy{
491145256Sjkoshy	errx(EX_USAGE,
492145256Sjkoshy	    "[options] [commandline]\n"
493145256Sjkoshy	    "\t Measure process and/or system performance using hardware\n"
494145256Sjkoshy	    "\t performance monitoring counters.\n"
495145256Sjkoshy	    "\t Options include:\n"
496147191Sjkoshy	    "\t -C\t\t (toggle) show cumulative counts\n"
497147191Sjkoshy	    "\t -D path\t create profiles in directory \"path\"\n"
498147191Sjkoshy	    "\t -E\t\t (toggle) show counts at process exit\n"
499203790Sfabient	    "\t -F file\t write a system-wide callgraph (Kcachegrind format)"
500203790Sfabient		" to \"file\"\n"
501174396Sjkoshy	    "\t -G file\t write a system-wide callgraph to \"file\"\n"
502157144Sjkoshy	    "\t -M file\t print executable/gmon file map to \"file\"\n"
503174396Sjkoshy	    "\t -N\t\t (toggle) capture callchains\n"
504147191Sjkoshy	    "\t -O file\t send log output to \"file\"\n"
505147191Sjkoshy	    "\t -P spec\t allocate a process-private sampling PMC\n"
506147191Sjkoshy	    "\t -R file\t read events from \"file\"\n"
507147191Sjkoshy	    "\t -S spec\t allocate a system-wide sampling PMC\n"
508203790Sfabient	    "\t -T\t\t start in top mode\n"
509147191Sjkoshy	    "\t -W\t\t (toggle) show counts per context switch\n"
510168949Sjkoshy	    "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n"
511147191Sjkoshy	    "\t -d\t\t (toggle) track descendants\n"
512203790Sfabient	    "\t -f spec\t pass \"spec\" to as plugin option\n"
513147191Sjkoshy	    "\t -g\t\t produce gprof(1) compatible profiles\n"
514162804Sru	    "\t -k dir\t\t set the path to the kernel\n"
515145256Sjkoshy	    "\t -n rate\t set sampling rate\n"
516145256Sjkoshy	    "\t -o file\t send print output to \"file\"\n"
517147191Sjkoshy	    "\t -p spec\t allocate a process-private counting PMC\n"
518157144Sjkoshy	    "\t -q\t\t suppress verbosity\n"
519157144Sjkoshy	    "\t -r fsroot\t specify FS root directory\n"
520147191Sjkoshy	    "\t -s spec\t allocate a system-wide counting PMC\n"
521183186Sjkoshy	    "\t -t process-spec attach to running processes matching "
522183186Sjkoshy		"\"process-spec\"\n"
523157144Sjkoshy	    "\t -v\t\t increase verbosity\n"
524174396Sjkoshy	    "\t -w secs\t set printing time interval\n"
525174396Sjkoshy	    "\t -z depth\t limit callchain display depth"
526145256Sjkoshy	);
527145256Sjkoshy}
528145256Sjkoshy
529145256Sjkoshy/*
530203790Sfabient * At exit handler for top mode
531203790Sfabient */
532203790Sfabient
533203790Sfabientvoid
534203790Sfabientpmcstat_topexit(void)
535203790Sfabient{
536203790Sfabient	if (!args.pa_toptty)
537203790Sfabient		return;
538203790Sfabient
539203790Sfabient	/*
540203790Sfabient	 * Shutdown ncurses.
541203790Sfabient	 */
542203790Sfabient	clrtoeol();
543203790Sfabient	refresh();
544203790Sfabient	endwin();
545203790Sfabient}
546203790Sfabient
547203790Sfabient/*
548145256Sjkoshy * Main
549145256Sjkoshy */
550145256Sjkoshy
551145256Sjkoshyint
552145256Sjkoshymain(int argc, char **argv)
553145256Sjkoshy{
554145256Sjkoshy	double interval;
555174396Sjkoshy	int option, npmc, ncpu, haltedcpus;
556151542Sjkoshy	int c, check_driver_stats, current_cpu, current_sampling_count;
557174396Sjkoshy	int do_callchain, do_descendants, do_logproccsw, do_logprocexit;
558174396Sjkoshy	int do_print;
559168949Sjkoshy	size_t dummy;
560174396Sjkoshy	int graphdepth;
561210794Sfabient	int pipefd[2], rfd;
562147191Sjkoshy	int use_cumulative_counts;
563203790Sfabient	short cf, cb;
564168949Sjkoshy	uint32_t cpumask;
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_cpu 		= 0;
578145256Sjkoshy	current_sampling_count  = DEFAULT_SAMPLE_COUNT;
579174396Sjkoshy	do_callchain		= 1;
580145256Sjkoshy	do_descendants          = 0;
581147191Sjkoshy	do_logproccsw           = 0;
582147191Sjkoshy	do_logprocexit          = 0;
583145256Sjkoshy	use_cumulative_counts   = 0;
584174396Sjkoshy	graphfilename		= "-";
585147191Sjkoshy	args.pa_required	= 0;
586145256Sjkoshy	args.pa_flags		= 0;
587157144Sjkoshy	args.pa_verbosity	= 1;
588147708Sjkoshy	args.pa_logfd		= -1;
589157144Sjkoshy	args.pa_fsroot		= "";
590157144Sjkoshy	args.pa_kernel		= strdup("/boot/kernel");
591147708Sjkoshy	args.pa_samplesdir	= ".";
592147708Sjkoshy	args.pa_printfile	= stderr;
593174396Sjkoshy	args.pa_graphdepth	= DEFAULT_CALLGRAPH_DEPTH;
594174396Sjkoshy	args.pa_graphfile	= NULL;
595145256Sjkoshy	args.pa_interval	= DEFAULT_WAIT_INTERVAL;
596157144Sjkoshy	args.pa_mapfilename	= NULL;
597174396Sjkoshy	args.pa_inputpath	= NULL;
598174396Sjkoshy	args.pa_outputpath	= NULL;
599203790Sfabient	args.pa_pplugin		= PMCSTAT_PL_NONE;
600203790Sfabient	args.pa_plugin		= PMCSTAT_PL_NONE;
601203790Sfabient	args.pa_ctdumpinstr	= 1;
602203790Sfabient	args.pa_topmode		= PMCSTAT_TOP_DELTA;
603203790Sfabient	args.pa_toptty		= 0;
604203790Sfabient	args.pa_topcolor	= 0;
605203790Sfabient	args.pa_mergepmc	= 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;
611145256Sjkoshy
612174396Sjkoshy	/*
613174396Sjkoshy	 * The initial CPU mask specifies all non-halted CPUS in the
614174396Sjkoshy	 * system.
615174396Sjkoshy	 */
616174396Sjkoshy	dummy = sizeof(int);
617168949Sjkoshy	if (sysctlbyname("hw.ncpu", &ncpu, &dummy, NULL, 0) < 0)
618174396Sjkoshy		err(EX_OSERR, "ERROR: Cannot determine the number of CPUs");
619168949Sjkoshy	cpumask = (1 << ncpu) - 1;
620183672Sjkoshy	haltedcpus = 0;
621175215Sjkim	if (ncpu > 1) {
622175215Sjkim		if (sysctlbyname("machdep.hlt_cpus", &haltedcpus, &dummy,
623175215Sjkim		    NULL, 0) < 0)
624175215Sjkim			err(EX_OSERR, "ERROR: Cannot determine which CPUs are "
625175215Sjkim			    "halted");
626175215Sjkim		cpumask &= ~haltedcpus;
627175215Sjkim	}
628168949Sjkoshy
629157144Sjkoshy	while ((option = getopt(argc, argv,
630203790Sfabient	    "CD:EF:G:M:NO:P:R:S:TWc:df:gk:m:n:o:p:qr:s:t:vw:z:")) != -1)
631145256Sjkoshy		switch (option) {
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
639168949Sjkoshy			if (optarg[0] == '*' && optarg[1] == '\0')
640183672Sjkoshy				cpumask = ((1 << ncpu) - 1) & ~haltedcpus;
641168949Sjkoshy			else
642168949Sjkoshy				cpumask = pmcstat_get_cpumask(optarg);
643168949Sjkoshy
644210797Sfabient			args.pa_flags	 |= FLAGS_HAS_CPUMASK;
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
888210797Sfabient	/* If we read from logfile and no specified CPU mask use
889210797Sfabient	 * the maximum CPU count.
890210797Sfabient	 */
891210797Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) &&
892210797Sfabient	    (args.pa_flags & FLAGS_HAS_CPUMASK) == 0)
893210797Sfabient		cpumask = 0xffffffff;
894210797Sfabient
895174396Sjkoshy	args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
896174396Sjkoshy
897147708Sjkoshy	if (argc)	/* command line present */
898147708Sjkoshy		args.pa_flags |= FLAG_HAS_COMMANDLINE;
899145256Sjkoshy
900185322Sattilio	if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
901203790Sfabient	    FLAG_DO_ANNOTATE | FLAG_DO_TOP))
902174396Sjkoshy		args.pa_flags |= FLAG_DO_ANALYSIS;
903174396Sjkoshy
904145256Sjkoshy	/*
905145256Sjkoshy	 * Check invocation syntax.
906145256Sjkoshy	 */
907145256Sjkoshy
908147708Sjkoshy	/* disallow -O and -R together */
909147708Sjkoshy	if (args.pa_outputpath && args.pa_inputpath)
910147708Sjkoshy		errx(EX_USAGE, "ERROR: options -O and -R are mutually "
911147708Sjkoshy		    "exclusive.");
912147708Sjkoshy
913185322Sattilio	/* -m option is allowed with -R only. */
914203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
915185322Sattilio		errx(EX_USAGE, "ERROR: option -m requires an input file");
916185322Sattilio
917185322Sattilio	/* -m option is not allowed combined with -g or -G. */
918203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE &&
919185322Sattilio	    args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
920185322Sattilio		errx(EX_USAGE, "ERROR: option -m and -g | -G are mutually "
921185322Sattilio		    "exclusive");
922185322Sattilio
923147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
924147191Sjkoshy		errmsg = NULL;
925147708Sjkoshy		if (args.pa_flags & FLAG_HAS_COMMANDLINE)
926147191Sjkoshy			errmsg = "a command line specification";
927169069Sjkoshy		else if (args.pa_flags & FLAG_HAS_TARGET)
928147191Sjkoshy			errmsg = "option -t";
929169069Sjkoshy		else if (!STAILQ_EMPTY(&args.pa_events))
930147191Sjkoshy			errmsg = "a PMC event specification";
931147191Sjkoshy		if (errmsg)
932147191Sjkoshy			errx(EX_USAGE, "ERROR: option -R may not be used with "
933147191Sjkoshy			    "%s.", errmsg);
934169069Sjkoshy	} else if (STAILQ_EMPTY(&args.pa_events))
935147708Sjkoshy		/* All other uses require a PMC spec. */
936145256Sjkoshy		pmcstat_show_usage();
937145256Sjkoshy
938147191Sjkoshy	/* check for -t pid without a process PMC spec */
939169069Sjkoshy	if ((args.pa_required & FLAG_HAS_TARGET) &&
940147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
941147191Sjkoshy		errx(EX_USAGE, "ERROR: option -t requires a process mode PMC "
942147191Sjkoshy		    "to be specified.");
943147191Sjkoshy
944147191Sjkoshy	/* check for process-mode options without a command or -t pid */
945147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
946169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
947147708Sjkoshy		errx(EX_USAGE, "ERROR: options -d, -E, -p, -P, and -W require "
948147708Sjkoshy		    "a command line or target process.");
949147191Sjkoshy
950147191Sjkoshy	/* check for -p | -P without a target process of some sort */
951169069Sjkoshy	if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
952169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
953147708Sjkoshy		errx(EX_USAGE, "ERROR: options -P and -p require a "
954147191Sjkoshy		    "target process or a command line.");
955147191Sjkoshy
956147191Sjkoshy	/* check for process-mode options without a process-mode PMC */
957147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
958147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
959147708Sjkoshy		errx(EX_USAGE, "ERROR: options -d, -E, and -W require a "
960147191Sjkoshy		    "process mode PMC to be specified.");
961147191Sjkoshy
962174396Sjkoshy	/* check for -c cpu with no system mode PMCs or logfile. */
963147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
964174396Sjkoshy	    (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
965174396Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
966147191Sjkoshy		errx(EX_USAGE, "ERROR: option -c requires at least one "
967147191Sjkoshy		    "system mode PMC to be specified.");
968147191Sjkoshy
969147191Sjkoshy	/* check for counting mode options without a counting PMC */
970147191Sjkoshy	if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
971147191Sjkoshy	    (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
972203790Sfabient		errx(EX_USAGE, "ERROR: options -C, -W and -o require at "
973149805Sjkoshy		    "least one counting mode PMC to be specified.");
974147191Sjkoshy
975147191Sjkoshy	/* check for sampling mode options without a sampling PMC spec */
976147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
977147191Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
978174396Sjkoshy		errx(EX_USAGE, "ERROR: options -N, -n and -O require at "
979174396Sjkoshy		    "least one sampling mode PMC to be specified.");
980147191Sjkoshy
981203790Sfabient	/* check if -g/-G/-m/-T are being used correctly */
982174396Sjkoshy	if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
983147708Sjkoshy	    !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
984203790Sfabient		errx(EX_USAGE, "ERROR: options -g/-G/-m/-T require sampling PMCs "
985174396Sjkoshy		    "or -R to be specified.");
986147708Sjkoshy
987147191Sjkoshy	/* check if -O was spuriously specified */
988147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
989147708Sjkoshy	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
990147191Sjkoshy		errx(EX_USAGE,
991147191Sjkoshy		    "ERROR: option -O is used only with options "
992147708Sjkoshy		    "-E, -P, -S and -W.");
993147191Sjkoshy
994203790Sfabient	/* -k kernel path require -g/-G/-m/-T or -R */
995147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
996174396Sjkoshy	    (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
997157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
998203790Sfabient	    errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
999147708Sjkoshy
1000174396Sjkoshy	/* -D only applies to gprof output mode (-g) */
1001147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
1002174396Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0)
1003174396Sjkoshy	    errx(EX_USAGE, "ERROR: option -D is only used with -g.");
1004147708Sjkoshy
1005157144Sjkoshy	/* -M mapfile requires -g or -R */
1006157144Sjkoshy	if (args.pa_mapfilename != NULL &&
1007157144Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0 &&
1008157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1009157144Sjkoshy	    errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
1010157144Sjkoshy
1011147708Sjkoshy	/*
1012147708Sjkoshy	 * Disallow textual output of sampling PMCs if counting PMCs
1013147708Sjkoshy	 * have also been asked for, mostly because the combined output
1014147708Sjkoshy	 * is difficult to make sense of.
1015147708Sjkoshy	 */
1016147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1017147708Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1018168927Sjkoshy	    ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
1019147708Sjkoshy		errx(EX_USAGE, "ERROR: option -O is required if counting and "
1020147708Sjkoshy		    "sampling PMCs are specified together.");
1021147708Sjkoshy
1022157144Sjkoshy	/*
1023174396Sjkoshy	 * Check if "-k kerneldir" was specified, and if whether
1024174396Sjkoshy	 * 'kerneldir' actually refers to a a file.  If so, use
1025174396Sjkoshy	 * `dirname path` to determine the kernel directory.
1026157144Sjkoshy	 */
1027157144Sjkoshy	if (args.pa_flags & FLAG_HAS_KERNELPATH) {
1028157144Sjkoshy		(void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
1029157144Sjkoshy		    args.pa_kernel);
1030157144Sjkoshy		if (stat(buffer, &sb) < 0)
1031157144Sjkoshy			err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
1032157144Sjkoshy			    buffer);
1033157144Sjkoshy		if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
1034157144Sjkoshy			errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
1035157144Sjkoshy			    buffer);
1036157144Sjkoshy		if (!S_ISDIR(sb.st_mode)) {
1037157144Sjkoshy			tmp = args.pa_kernel;
1038157144Sjkoshy			args.pa_kernel = strdup(dirname(args.pa_kernel));
1039157144Sjkoshy			free(tmp);
1040157144Sjkoshy			(void) snprintf(buffer, sizeof(buffer), "%s%s",
1041157144Sjkoshy			    args.pa_fsroot, args.pa_kernel);
1042157144Sjkoshy			if (stat(buffer, &sb) < 0)
1043157144Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
1044157144Sjkoshy				    buffer);
1045157144Sjkoshy			if (!S_ISDIR(sb.st_mode))
1046157144Sjkoshy				errx(EX_USAGE, "ERROR: \"%s\" is not a "
1047157144Sjkoshy				    "directory.", buffer);
1048157144Sjkoshy		}
1049157144Sjkoshy	}
1050168949Sjkoshy
1051174396Sjkoshy	/*
1052174396Sjkoshy	 * If we have a callgraph be created, select the outputfile.
1053174396Sjkoshy	 */
1054174396Sjkoshy	if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
1055174396Sjkoshy		if (strcmp(graphfilename, "-") == 0)
1056174396Sjkoshy		    args.pa_graphfile = args.pa_printfile;
1057174396Sjkoshy		else {
1058174396Sjkoshy			args.pa_graphfile = fopen(graphfilename, "w");
1059174396Sjkoshy			if (args.pa_graphfile == NULL)
1060174396Sjkoshy				err(EX_OSERR, "ERROR: cannot open \"%s\" "
1061174396Sjkoshy				    "for writing", graphfilename);
1062174396Sjkoshy		}
1063174396Sjkoshy	}
1064203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE) {
1065185322Sattilio		args.pa_graphfile = fopen(graphfilename, "w");
1066185322Sattilio		if (args.pa_graphfile == NULL)
1067185322Sattilio			err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
1068185322Sattilio			    graphfilename);
1069185322Sattilio	}
1070174396Sjkoshy
1071210794Sfabient	/* if we've been asked to process a log file, skip init */
1072210794Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) {
1073210794Sfabient		if (pmc_init() < 0)
1074210794Sfabient			err(EX_UNAVAILABLE,
1075210794Sfabient			    "ERROR: Initialization of the pmc(3) library failed");
1076210794Sfabient
1077210794Sfabient		if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1078210794Sfabient			err(EX_OSERR, "ERROR: Cannot determine the number of PMCs "
1079210794Sfabient			    "on CPU %d", 0);
1080210794Sfabient	}
1081210794Sfabient
1082210794Sfabient	/* Allocate a kqueue */
1083210794Sfabient	if ((pmcstat_kq = kqueue()) < 0)
1084210794Sfabient		err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1085210794Sfabient
1086210794Sfabient	/* Setup the logfile as the source. */
1087147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
1088147708Sjkoshy		/*
1089147708Sjkoshy		 * Print the log in textual form if we haven't been
1090174396Sjkoshy		 * asked to generate profiling information.
1091147708Sjkoshy		 */
1092174396Sjkoshy		if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1093147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
1094147708Sjkoshy
1095203790Sfabient		pmcstat_initialize_logging();
1096210794Sfabient		rfd = pmcstat_open_log(args.pa_inputpath,
1097157406Sjkoshy		    PMCSTAT_OPEN_FOR_READ);
1098210794Sfabient		if ((args.pa_logparser = pmclog_open(rfd)) == NULL)
1099147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot create parser");
1100210794Sfabient		if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0)
1101210794Sfabient			err(EX_OSERR, "ERROR: fcntl(2) failed");
1102210794Sfabient		EV_SET(&kev, rfd, EVFILT_READ, EV_ADD,
1103210794Sfabient		    0, 0, NULL);
1104210794Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1105210794Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1106147191Sjkoshy	}
1107145256Sjkoshy	/*
1108147708Sjkoshy	 * Configure the specified log file or setup a default log
1109147708Sjkoshy	 * consumer via a pipe.
1110147708Sjkoshy	 */
1111147708Sjkoshy	if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1112157406Sjkoshy		if (args.pa_outputpath)
1113157406Sjkoshy			args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1114157406Sjkoshy			    PMCSTAT_OPEN_FOR_WRITE);
1115157406Sjkoshy		else {
1116147708Sjkoshy			/*
1117147708Sjkoshy			 * process the log on the fly by reading it in
1118147708Sjkoshy			 * through a pipe.
1119147708Sjkoshy			 */
1120147708Sjkoshy			if (pipe(pipefd) < 0)
1121147708Sjkoshy				err(EX_OSERR, "ERROR: pipe(2) failed");
1122147708Sjkoshy
1123147708Sjkoshy			if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1124147708Sjkoshy				err(EX_OSERR, "ERROR: fcntl(2) failed");
1125147708Sjkoshy
1126147708Sjkoshy			EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1127147708Sjkoshy			    0, 0, NULL);
1128147708Sjkoshy
1129147708Sjkoshy			if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1130147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot register kevent");
1131147708Sjkoshy
1132147708Sjkoshy			args.pa_logfd = pipefd[WRITEPIPEFD];
1133147708Sjkoshy
1134203790Sfabient			args.pa_flags |= FLAG_HAS_PIPE;
1135203790Sfabient			if ((args.pa_flags & FLAG_DO_TOP) == 0)
1136203790Sfabient				args.pa_flags |= FLAG_DO_PRINT;
1137147708Sjkoshy			args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1138147708Sjkoshy		}
1139147708Sjkoshy
1140147708Sjkoshy		if (pmc_configure_logfile(args.pa_logfd) < 0)
1141147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot configure log file");
1142147708Sjkoshy	}
1143147708Sjkoshy
1144151542Sjkoshy	/* remember to check for driver errors if we are sampling or logging */
1145151542Sjkoshy	check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1146151542Sjkoshy	    (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1147151542Sjkoshy
1148147708Sjkoshy	/*
1149210794Sfabient	if (args.pa_flags & FLAG_READ_LOGFILE) {
1150145256Sjkoshy	 * Allocate PMCs.
1151145256Sjkoshy	 */
1152145256Sjkoshy
1153169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1154145256Sjkoshy	    if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1155147191Sjkoshy		    ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1156145256Sjkoshy		    err(EX_OSERR, "ERROR: Cannot allocate %s-mode pmc with "
1157145256Sjkoshy			"specification \"%s\"",
1158145256Sjkoshy			PMC_IS_SYSTEM_MODE(ev->ev_mode) ? "system" : "process",
1159145256Sjkoshy			ev->ev_spec);
1160145256Sjkoshy
1161147708Sjkoshy	    if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1162147708Sjkoshy		pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1163147708Sjkoshy		    err(EX_OSERR, "ERROR: Cannot set sampling count "
1164147708Sjkoshy			"for PMC \"%s\"", ev->ev_name);
1165147708Sjkoshy	}
1166147708Sjkoshy
1167145256Sjkoshy	/* compute printout widths */
1168169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1169145774Sjkoshy		int counter_width;
1170145774Sjkoshy		int display_width;
1171145774Sjkoshy		int header_width;
1172145256Sjkoshy
1173145774Sjkoshy		(void) pmc_width(ev->ev_pmcid, &counter_width);
1174168949Sjkoshy		header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1175145774Sjkoshy		display_width = (int) floor(counter_width / 3.32193) + 1;
1176145256Sjkoshy
1177168949Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1178168949Sjkoshy			header_width += 3; /* 2 digit CPU number + '/' */
1179168949Sjkoshy
1180145774Sjkoshy		if (header_width > display_width) {
1181145256Sjkoshy			ev->ev_fieldskip = 0;
1182145774Sjkoshy			ev->ev_fieldwidth = header_width;
1183145256Sjkoshy		} else {
1184145774Sjkoshy			ev->ev_fieldskip = display_width -
1185145774Sjkoshy			    header_width;
1186145774Sjkoshy			ev->ev_fieldwidth = display_width;
1187145256Sjkoshy		}
1188145256Sjkoshy	}
1189145256Sjkoshy
1190145256Sjkoshy	/*
1191145256Sjkoshy	 * If our output is being set to a terminal, register a handler
1192145256Sjkoshy	 * for window size changes.
1193145256Sjkoshy	 */
1194145256Sjkoshy
1195147708Sjkoshy	if (isatty(fileno(args.pa_printfile))) {
1196145256Sjkoshy
1197147708Sjkoshy		if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1198145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot determine window size");
1199145256Sjkoshy
1200145256Sjkoshy		pmcstat_displayheight = ws.ws_row - 1;
1201203790Sfabient		pmcstat_displaywidth  = ws.ws_col - 1;
1202145256Sjkoshy
1203145256Sjkoshy		EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1204145256Sjkoshy
1205145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1206145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot register kevent for "
1207145256Sjkoshy			    "SIGWINCH");
1208203790Sfabient
1209203790Sfabient		args.pa_toptty = 1;
1210145256Sjkoshy	}
1211145256Sjkoshy
1212203790Sfabient	/*
1213203790Sfabient	 * Listen to key input in top mode.
1214203790Sfabient	 */
1215203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1216203790Sfabient		EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1217203790Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1218203790Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1219203790Sfabient	}
1220203790Sfabient
1221145256Sjkoshy	EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1222145256Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1223145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1224145256Sjkoshy
1225147191Sjkoshy	EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1226147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1227147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1228145256Sjkoshy
1229147191Sjkoshy	/*
1230147191Sjkoshy	 * An exec() failure of a forked child is signalled by the
1231147191Sjkoshy	 * child sending the parent a SIGCHLD.  We don't register an
1232147191Sjkoshy	 * actual signal handler for SIGCHLD, but instead use our
1233147191Sjkoshy	 * kqueue to pick up the signal.
1234147191Sjkoshy	 */
1235147191Sjkoshy	EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1236147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1237147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1238145256Sjkoshy
1239203790Sfabient	/*
1240203790Sfabient	 * Setup a timer if we have counting mode PMCs needing to be printed or
1241203790Sfabient	 * top mode plugin is active.
1242203790Sfabient	 */
1243203790Sfabient	if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1244203790Sfabient	     (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1245203790Sfabient	    (args.pa_flags & FLAG_DO_TOP)) {
1246145256Sjkoshy		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1247145256Sjkoshy		    args.pa_interval * 1000, NULL);
1248145256Sjkoshy
1249145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1250145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot register kevent for "
1251145256Sjkoshy			    "timer");
1252145256Sjkoshy	}
1253145256Sjkoshy
1254145256Sjkoshy	/* attach PMCs to the target process, starting it if specified */
1255168949Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1256203790Sfabient		pmcstat_create_process();
1257145256Sjkoshy
1258151542Sjkoshy	if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1259151542Sjkoshy		err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1260151542Sjkoshy
1261168949Sjkoshy	/* Attach process pmcs to the target process. */
1262180148Sjkoshy	if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1263169069Sjkoshy		if (SLIST_EMPTY(&args.pa_targets))
1264169069Sjkoshy			errx(EX_DATAERR, "ERROR: No matching target "
1265169069Sjkoshy			    "processes.");
1266183672Sjkoshy		if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1267203790Sfabient			pmcstat_attach_pmcs();
1268168949Sjkoshy
1269169069Sjkoshy		if (pmcstat_kvm) {
1270169069Sjkoshy			kvm_close(pmcstat_kvm);
1271169069Sjkoshy			pmcstat_kvm = NULL;
1272169069Sjkoshy		}
1273169069Sjkoshy	}
1274169069Sjkoshy
1275145256Sjkoshy	/* start the pmcs */
1276203790Sfabient	pmcstat_start_pmcs();
1277145256Sjkoshy
1278145256Sjkoshy	/* start the (commandline) process if needed */
1279147708Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1280168949Sjkoshy		pmcstat_start_process();
1281145256Sjkoshy
1282210794Sfabient	/* initialize logging */
1283210794Sfabient	pmcstat_initialize_logging();
1284147708Sjkoshy
1285145256Sjkoshy	/* Handle SIGINT using the kqueue loop */
1286145256Sjkoshy	sa.sa_handler = SIG_IGN;
1287145256Sjkoshy	sa.sa_flags   = 0;
1288145256Sjkoshy	(void) sigemptyset(&sa.sa_mask);
1289145256Sjkoshy
1290145256Sjkoshy	if (sigaction(SIGINT, &sa, NULL) < 0)
1291145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot install signal handler");
1292145256Sjkoshy
1293145256Sjkoshy	/*
1294203790Sfabient	 * Setup the top mode display.
1295203790Sfabient	 */
1296203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1297203790Sfabient		args.pa_flags &= ~FLAG_DO_PRINT;
1298203790Sfabient
1299203790Sfabient		if (args.pa_toptty) {
1300203790Sfabient			/*
1301203790Sfabient			 * Init ncurses.
1302203790Sfabient			 */
1303203790Sfabient			initscr();
1304203790Sfabient			if(has_colors() == TRUE) {
1305203790Sfabient				args.pa_topcolor = 1;
1306203790Sfabient				start_color();
1307203790Sfabient				use_default_colors();
1308203790Sfabient				pair_content(0, &cf, &cb);
1309203790Sfabient				init_pair(1, COLOR_RED, cb);
1310203790Sfabient				init_pair(2, COLOR_YELLOW, cb);
1311203790Sfabient				init_pair(3, COLOR_GREEN, cb);
1312203790Sfabient			}
1313203790Sfabient			cbreak();
1314203790Sfabient			noecho();
1315203790Sfabient			nonl();
1316203790Sfabient			nodelay(stdscr, 1);
1317203790Sfabient			intrflush(stdscr, FALSE);
1318203790Sfabient			keypad(stdscr, TRUE);
1319203790Sfabient			clear();
1320204783Sfabient			/* Get terminal width / height with ncurses. */
1321204783Sfabient			getmaxyx(stdscr, pmcstat_displayheight, pmcstat_displaywidth);
1322204783Sfabient			pmcstat_displayheight--; pmcstat_displaywidth--;
1323203790Sfabient			atexit(pmcstat_topexit);
1324203790Sfabient		}
1325203790Sfabient	}
1326203790Sfabient
1327203790Sfabient	/*
1328145256Sjkoshy	 * loop till either the target process (if any) exits, or we
1329145256Sjkoshy	 * are killed by a SIGINT.
1330145256Sjkoshy	 */
1331147191Sjkoshy	runstate = PMCSTAT_RUNNING;
1332147191Sjkoshy	do_print = 0;
1333145256Sjkoshy	do {
1334145256Sjkoshy		if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1335145256Sjkoshy			if (errno != EINTR)
1336145256Sjkoshy				err(EX_OSERR, "ERROR: kevent failed");
1337145256Sjkoshy			else
1338145256Sjkoshy				continue;
1339145256Sjkoshy		}
1340145256Sjkoshy
1341145256Sjkoshy		if (kev.flags & EV_ERROR)
1342145256Sjkoshy			errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1343145256Sjkoshy
1344145256Sjkoshy		switch (kev.filter) {
1345147191Sjkoshy		case EVFILT_PROC:  /* target has exited */
1346210794Sfabient			runstate = pmcstat_close_log();
1347148688Sjkoshy			do_print = 1;
1348147191Sjkoshy			break;
1349145256Sjkoshy
1350147191Sjkoshy		case EVFILT_READ:  /* log file data is present */
1351210794Sfabient			if (kev.ident == (unsigned)fileno(stdin) &&
1352210794Sfabient			    (args.pa_flags & FLAG_DO_TOP)) {
1353203790Sfabient				if (pmcstat_keypress_log())
1354203790Sfabient					runstate = pmcstat_close_log();
1355203790Sfabient			} else
1356203790Sfabient				runstate = pmcstat_process_log();
1357145256Sjkoshy			break;
1358145256Sjkoshy
1359145256Sjkoshy		case EVFILT_SIGNAL:
1360147191Sjkoshy			if (kev.ident == SIGCHLD) {
1361147191Sjkoshy				/*
1362147191Sjkoshy				 * The child process sends us a
1363147191Sjkoshy				 * SIGCHLD if its exec() failed.  We
1364147191Sjkoshy				 * wait for it to exit and then exit
1365147191Sjkoshy				 * ourselves.
1366147191Sjkoshy				 */
1367147191Sjkoshy				(void) wait(&c);
1368147191Sjkoshy				runstate = PMCSTAT_FINISHED;
1369147191Sjkoshy			} else if (kev.ident == SIGIO) {
1370147191Sjkoshy				/*
1371147191Sjkoshy				 * We get a SIGIO if a PMC loses all
1372147191Sjkoshy				 * of its targets, or if logfile
1373147191Sjkoshy				 * writes encounter an error.
1374147191Sjkoshy				 */
1375210794Sfabient				runstate = pmcstat_close_log();
1376147191Sjkoshy				do_print = 1; /* print PMCs at exit */
1377147191Sjkoshy			} else if (kev.ident == SIGINT) {
1378147708Sjkoshy				/* Kill the child process if we started it */
1379147708Sjkoshy				if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1380203790Sfabient					pmcstat_kill_process();
1381186425Sjkoshy				/* Close the pipe to self, if present. */
1382186425Sjkoshy				if (args.pa_flags & FLAG_HAS_PIPE)
1383186425Sjkoshy					(void) close(pipefd[READPIPEFD]);
1384210794Sfabient				runstate = pmcstat_close_log();
1385145256Sjkoshy			} else if (kev.ident == SIGWINCH) {
1386147708Sjkoshy				if (ioctl(fileno(args.pa_printfile),
1387145256Sjkoshy					TIOCGWINSZ, &ws) < 0)
1388145256Sjkoshy				    err(EX_OSERR, "ERROR: Cannot determine "
1389145256Sjkoshy					"window size");
1390145256Sjkoshy				pmcstat_displayheight = ws.ws_row - 1;
1391203790Sfabient				pmcstat_displaywidth  = ws.ws_col - 1;
1392145256Sjkoshy			} else
1393145256Sjkoshy				assert(0);
1394145256Sjkoshy
1395145256Sjkoshy			break;
1396147191Sjkoshy
1397147191Sjkoshy		case EVFILT_TIMER: /* print out counting PMCs */
1398147191Sjkoshy			do_print = 1;
1399147191Sjkoshy			break;
1400147191Sjkoshy
1401145256Sjkoshy		}
1402145256Sjkoshy
1403203790Sfabient		if (do_print) {
1404203790Sfabient			if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1405203790Sfabient				pmcstat_print_pmcs();
1406203790Sfabient				if (runstate == PMCSTAT_FINISHED && /* final newline */
1407203790Sfabient				    (args.pa_flags & FLAG_DO_PRINT) == 0)
1408203790Sfabient					(void) fprintf(args.pa_printfile, "\n");
1409203790Sfabient			}
1410203790Sfabient			if (args.pa_flags & FLAG_DO_TOP)
1411203790Sfabient				pmcstat_display_log();
1412147191Sjkoshy			do_print = 0;
1413147191Sjkoshy		}
1414145256Sjkoshy
1415147191Sjkoshy	} while (runstate != PMCSTAT_FINISHED);
1416147191Sjkoshy
1417203790Sfabient	if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1418203790Sfabient		pmcstat_topexit();
1419203790Sfabient		args.pa_toptty = 0;
1420203790Sfabient	}
1421203790Sfabient
1422147191Sjkoshy	/* flush any pending log entries */
1423147708Sjkoshy	if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1424147191Sjkoshy		pmc_flush_logfile();
1425147191Sjkoshy
1426203790Sfabient	pmcstat_cleanup();
1427145256Sjkoshy
1428157144Sjkoshy	free(args.pa_kernel);
1429157144Sjkoshy
1430151542Sjkoshy	/* check if the driver lost any samples or events */
1431151542Sjkoshy	if (check_driver_stats) {
1432151542Sjkoshy		if (pmc_get_driver_stats(&ds_end) < 0)
1433151542Sjkoshy			err(EX_OSERR, "ERROR: Cannot retrieve driver "
1434151542Sjkoshy			    "statistics");
1435157144Sjkoshy		if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1436157144Sjkoshy		    args.pa_verbosity > 0)
1437153704Sjkoshy			warnx("WARNING: some samples were dropped.  Please "
1438151542Sjkoshy			    "consider tuning the \"kern.hwpmc.nsamples\" "
1439151542Sjkoshy			    "tunable.");
1440151542Sjkoshy		if (ds_start.pm_buffer_requests_failed !=
1441157144Sjkoshy		    ds_end.pm_buffer_requests_failed &&
1442157144Sjkoshy		    args.pa_verbosity > 0)
1443153704Sjkoshy			warnx("WARNING: some events were discarded.  Please "
1444151542Sjkoshy			    "consider tuning the \"kern.hwpmc.nbuffers\" "
1445151542Sjkoshy			    "tunable.");
1446151542Sjkoshy	}
1447151542Sjkoshy
1448151542Sjkoshy	exit(EX_OK);
1449145256Sjkoshy}
1450