pmcstat.c revision 226986
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 226986 2011-11-01 09:28:47Z fabient $");
33145256Sjkoshy
34224698Sattilio#include <sys/param.h>
35224698Sattilio#include <sys/cpuset.h>
36145256Sjkoshy#include <sys/event.h>
37145256Sjkoshy#include <sys/queue.h>
38147708Sjkoshy#include <sys/socket.h>
39147708Sjkoshy#include <sys/stat.h>
40168949Sjkoshy#include <sys/sysctl.h>
41145256Sjkoshy#include <sys/time.h>
42145256Sjkoshy#include <sys/ttycom.h>
43169069Sjkoshy#include <sys/user.h>
44145256Sjkoshy#include <sys/wait.h>
45145256Sjkoshy
46145256Sjkoshy#include <assert.h>
47203790Sfabient#include <curses.h>
48145256Sjkoshy#include <err.h>
49145256Sjkoshy#include <errno.h>
50145256Sjkoshy#include <fcntl.h>
51169069Sjkoshy#include <kvm.h>
52157144Sjkoshy#include <libgen.h>
53145256Sjkoshy#include <limits.h>
54145256Sjkoshy#include <math.h>
55145256Sjkoshy#include <pmc.h>
56147191Sjkoshy#include <pmclog.h>
57169069Sjkoshy#include <regex.h>
58145256Sjkoshy#include <signal.h>
59145256Sjkoshy#include <stdarg.h>
60147708Sjkoshy#include <stdint.h>
61145256Sjkoshy#include <stdio.h>
62145256Sjkoshy#include <stdlib.h>
63145256Sjkoshy#include <string.h>
64145256Sjkoshy#include <sysexits.h>
65145256Sjkoshy#include <unistd.h>
66145256Sjkoshy
67147708Sjkoshy#include "pmcstat.h"
68147708Sjkoshy
69147191Sjkoshy/*
70147191Sjkoshy * A given invocation of pmcstat(8) can manage multiple PMCs of both
71147191Sjkoshy * the system-wide and per-process variety.  Each of these could be in
72147191Sjkoshy * 'counting mode' or in 'sampling mode'.
73147191Sjkoshy *
74147191Sjkoshy * For 'counting mode' PMCs, pmcstat(8) will periodically issue a
75147191Sjkoshy * pmc_read() at the configured time interval and print out the value
76147191Sjkoshy * of the requested PMCs.
77147191Sjkoshy *
78147191Sjkoshy * For 'sampling mode' PMCs it can log to a file for offline analysis,
79147191Sjkoshy * or can analyse sampling data "on the fly", either by converting
80147191Sjkoshy * samples to printed textual form or by creating gprof(1) compatible
81147191Sjkoshy * profiles, one per program executed.  When creating gprof(1)
82147191Sjkoshy * profiles it can optionally merge entries from multiple processes
83147191Sjkoshy * for a given executable into a single profile file.
84168949Sjkoshy *
85168949Sjkoshy * pmcstat(8) can also execute a command line and attach PMCs to the
86168949Sjkoshy * resulting child process.  The protocol used is as follows:
87168949Sjkoshy *
88168949Sjkoshy * - parent creates a socketpair for two way communication and
89168949Sjkoshy *   fork()s.
90168949Sjkoshy * - subsequently:
91168949Sjkoshy *
92168949Sjkoshy *   /Parent/				/Child/
93168949Sjkoshy *
94168949Sjkoshy *   - Wait for childs token.
95168949Sjkoshy *					- Sends token.
96168949Sjkoshy *					- Awaits signal to start.
97168949Sjkoshy *  - Attaches PMCs to the child's pid
98168949Sjkoshy *    and starts them. Sets up
99168949Sjkoshy *    monitoring for the child.
100168949Sjkoshy *  - Signals child to start.
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
117224698Sattiliostatic void
118224698Sattiliopmcstat_clone_event_descriptor(struct pmcstat_ev *ev, const cpuset_t *cpumask)
119224698Sattilio{
120224698Sattilio	int cpu, mcpu;
121224698Sattilio	struct pmcstat_ev *ev_clone;
122224698Sattilio
123224698Sattilio	mcpu = sizeof(*cpumask) * NBBY;
124224698Sattilio	for (cpu = 0; cpu < mcpu; cpu++) {
125224698Sattilio		if (!CPU_ISSET(cpu, cpumask))
126224698Sattilio			continue;
127224698Sattilio
128224698Sattilio		if ((ev_clone = malloc(sizeof(*ev_clone))) == NULL)
129224698Sattilio			errx(EX_SOFTWARE, "ERROR: Out of memory");
130224698Sattilio		(void) memset(ev_clone, 0, sizeof(*ev_clone));
131224698Sattilio
132224698Sattilio		ev_clone->ev_count = ev->ev_count;
133224698Sattilio		ev_clone->ev_cpu   = cpu;
134224698Sattilio		ev_clone->ev_cumulative = ev->ev_cumulative;
135224698Sattilio		ev_clone->ev_flags = ev->ev_flags;
136224698Sattilio		ev_clone->ev_mode  = ev->ev_mode;
137224698Sattilio		ev_clone->ev_name  = strdup(ev->ev_name);
138224698Sattilio		ev_clone->ev_pmcid = ev->ev_pmcid;
139224698Sattilio		ev_clone->ev_saved = ev->ev_saved;
140224698Sattilio		ev_clone->ev_spec  = strdup(ev->ev_spec);
141224698Sattilio
142224698Sattilio		STAILQ_INSERT_TAIL(&args.pa_events, ev_clone, ev_next);
143224698Sattilio	}
144224698Sattilio}
145224698Sattilio
146224698Sattiliostatic void
147224698Sattiliopmcstat_get_cpumask(const char *cpuspec, cpuset_t *cpumask)
148224698Sattilio{
149224698Sattilio	int cpu;
150224698Sattilio	const char *s;
151224698Sattilio	char *end;
152224698Sattilio
153224698Sattilio	CPU_ZERO(cpumask);
154224698Sattilio	s = cpuspec;
155224698Sattilio
156224698Sattilio	do {
157224698Sattilio		cpu = strtol(s, &end, 0);
158224698Sattilio		if (cpu < 0 || end == s)
159224698Sattilio			errx(EX_USAGE, "ERROR: Illegal CPU specification "
160224698Sattilio			    "\"%s\".", cpuspec);
161224698Sattilio		CPU_SET(cpu, cpumask);
162224698Sattilio		s = end + strspn(end, ", \t");
163224698Sattilio	} while (*s);
164224698Sattilio}
165224698Sattilio
166168949Sjkoshyvoid
167203790Sfabientpmcstat_attach_pmcs(void)
168168949Sjkoshy{
169168949Sjkoshy	struct pmcstat_ev *ev;
170169069Sjkoshy	struct pmcstat_target *pt;
171169069Sjkoshy	int count;
172145256Sjkoshy
173169069Sjkoshy	/* Attach all process PMCs to target processes. */
174169069Sjkoshy	count = 0;
175203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
176169069Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
177169069Sjkoshy			continue;
178203790Sfabient		SLIST_FOREACH(pt, &args.pa_targets, pt_next)
179169069Sjkoshy			if (pmc_attach(ev->ev_pmcid, pt->pt_pid) == 0)
180169069Sjkoshy				count++;
181169069Sjkoshy			else if (errno != ESRCH)
182169069Sjkoshy				err(EX_OSERR, "ERROR: cannot attach pmc "
183169069Sjkoshy				    "\"%s\" to process %d", ev->ev_name,
184169069Sjkoshy				    (int) pt->pt_pid);
185169069Sjkoshy	}
186168949Sjkoshy
187169069Sjkoshy	if (count == 0)
188169069Sjkoshy		errx(EX_DATAERR, "ERROR: No processes were attached to.");
189168949Sjkoshy}
190168949Sjkoshy
191168949Sjkoshy
192145256Sjkoshyvoid
193203790Sfabientpmcstat_cleanup(void)
194145256Sjkoshy{
195145256Sjkoshy	struct pmcstat_ev *ev, *tmp;
196145256Sjkoshy
197145256Sjkoshy	/* release allocated PMCs. */
198203790Sfabient	STAILQ_FOREACH_SAFE(ev, &args.pa_events, ev_next, tmp)
199145256Sjkoshy	    if (ev->ev_pmcid != PMC_ID_INVALID) {
200185079Sjkoshy		if (pmc_stop(ev->ev_pmcid) < 0)
201185079Sjkoshy			err(EX_OSERR, "ERROR: cannot stop pmc 0x%x "
202185079Sjkoshy			    "\"%s\"", ev->ev_pmcid, ev->ev_name);
203145256Sjkoshy		if (pmc_release(ev->ev_pmcid) < 0)
204145256Sjkoshy			err(EX_OSERR, "ERROR: cannot release pmc "
205147191Sjkoshy			    "0x%x \"%s\"", ev->ev_pmcid, ev->ev_name);
206145256Sjkoshy		free(ev->ev_name);
207145256Sjkoshy		free(ev->ev_spec);
208203790Sfabient		STAILQ_REMOVE(&args.pa_events, ev, pmcstat_ev, ev_next);
209145256Sjkoshy		free(ev);
210145256Sjkoshy	    }
211147191Sjkoshy
212147863Sjkoshy	/* de-configure the log file if present. */
213203790Sfabient	if (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
214147863Sjkoshy		(void) pmc_configure_logfile(-1);
215147863Sjkoshy
216203790Sfabient	if (args.pa_logparser) {
217203790Sfabient		pmclog_close(args.pa_logparser);
218203790Sfabient		args.pa_logparser = NULL;
219147191Sjkoshy	}
220147708Sjkoshy
221210794Sfabient	pmcstat_shutdown_logging();
222145256Sjkoshy}
223145256Sjkoshy
224145256Sjkoshyvoid
225203790Sfabientpmcstat_create_process(void)
226168949Sjkoshy{
227168949Sjkoshy	char token;
228169069Sjkoshy	pid_t pid;
229168949Sjkoshy	struct kevent kev;
230169069Sjkoshy	struct pmcstat_target *pt;
231168949Sjkoshy
232168949Sjkoshy	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pmcstat_sockpair) < 0)
233168949Sjkoshy		err(EX_OSERR, "ERROR: cannot create socket pair");
234168949Sjkoshy
235169069Sjkoshy	switch (pid = fork()) {
236168949Sjkoshy	case -1:
237168949Sjkoshy		err(EX_OSERR, "ERROR: cannot fork");
238168949Sjkoshy		/*NOTREACHED*/
239168949Sjkoshy
240168949Sjkoshy	case 0:		/* child */
241168949Sjkoshy		(void) close(pmcstat_sockpair[PARENTSOCKET]);
242168949Sjkoshy
243168949Sjkoshy		/* Write a token to tell our parent we've started executing. */
244168949Sjkoshy		if (write(pmcstat_sockpair[CHILDSOCKET], "+", 1) != 1)
245168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot write token");
246168949Sjkoshy
247168949Sjkoshy		/* Wait for our parent to signal us to start. */
248168949Sjkoshy		if (read(pmcstat_sockpair[CHILDSOCKET], &token, 1) < 0)
249168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot read token");
250168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
251168949Sjkoshy
252168949Sjkoshy		/* exec() the program requested */
253203790Sfabient		execvp(*args.pa_argv, args.pa_argv);
254168949Sjkoshy		/* and if that fails, notify the parent */
255168949Sjkoshy		kill(getppid(), SIGCHLD);
256203790Sfabient		err(EX_OSERR, "ERROR: execvp \"%s\" failed", *args.pa_argv);
257168949Sjkoshy		/*NOTREACHED*/
258168949Sjkoshy
259168949Sjkoshy	default:	/* parent */
260168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
261168949Sjkoshy		break;
262168949Sjkoshy	}
263168949Sjkoshy
264168949Sjkoshy	/* Ask to be notified via a kevent when the target process exits. */
265169069Sjkoshy	EV_SET(&kev, pid, EVFILT_PROC, EV_ADD|EV_ONESHOT, NOTE_EXIT, 0,
266168949Sjkoshy	    NULL);
267168949Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
268169069Sjkoshy		err(EX_OSERR, "ERROR: cannot monitor child process %d", pid);
269168949Sjkoshy
270169069Sjkoshy	if ((pt = malloc(sizeof(*pt))) == NULL)
271169069Sjkoshy		errx(EX_SOFTWARE, "ERROR: Out of memory.");
272169069Sjkoshy
273169069Sjkoshy	pt->pt_pid = pid;
274203790Sfabient	SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
275169069Sjkoshy
276168949Sjkoshy	/* Wait for the child to signal that its ready to go. */
277168949Sjkoshy	if (read(pmcstat_sockpair[PARENTSOCKET], &token, 1) < 0)
278168949Sjkoshy		err(EX_OSERR, "ERROR (parent): cannot read token");
279168949Sjkoshy
280168949Sjkoshy	return;
281168949Sjkoshy}
282168949Sjkoshy
283169069Sjkoshyvoid
284203790Sfabientpmcstat_find_targets(const char *spec)
285169069Sjkoshy{
286169069Sjkoshy	int n, nproc, pid, rv;
287169069Sjkoshy	struct pmcstat_target *pt;
288169069Sjkoshy	char errbuf[_POSIX2_LINE_MAX], *end;
289169069Sjkoshy	static struct kinfo_proc *kp;
290169069Sjkoshy	regex_t reg;
291169069Sjkoshy	regmatch_t regmatch;
292169069Sjkoshy
293169069Sjkoshy	/* First check if we've been given a process id. */
294169069Sjkoshy      	pid = strtol(spec, &end, 0);
295169069Sjkoshy	if (end != spec && pid >= 0) {
296169069Sjkoshy		if ((pt = malloc(sizeof(*pt))) == NULL)
297169069Sjkoshy			goto outofmemory;
298169069Sjkoshy		pt->pt_pid = pid;
299203790Sfabient		SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
300169069Sjkoshy		return;
301169069Sjkoshy	}
302169069Sjkoshy
303169069Sjkoshy	/* Otherwise treat arg as a regular expression naming processes. */
304169069Sjkoshy	if (pmcstat_kvm == NULL) {
305169069Sjkoshy		if ((pmcstat_kvm = kvm_openfiles(NULL, "/dev/null", NULL, 0,
306169069Sjkoshy		    errbuf)) == NULL)
307169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot open kernel \"%s\"",
308169069Sjkoshy			    errbuf);
309169069Sjkoshy		if ((pmcstat_plist = kvm_getprocs(pmcstat_kvm, KERN_PROC_PROC,
310169069Sjkoshy		    0, &nproc)) == NULL)
311169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot get process list: %s",
312169069Sjkoshy			    kvm_geterr(pmcstat_kvm));
313208858Sfabient	} else
314208858Sfabient		nproc = 0;
315169069Sjkoshy
316169069Sjkoshy	if ((rv = regcomp(&reg, spec, REG_EXTENDED|REG_NOSUB)) != 0) {
317169069Sjkoshy		regerror(rv, &reg, errbuf, sizeof(errbuf));
318169069Sjkoshy		err(EX_DATAERR, "ERROR: Failed to compile regex \"%s\": %s",
319169069Sjkoshy		    spec, errbuf);
320169069Sjkoshy	}
321169069Sjkoshy
322169069Sjkoshy	for (n = 0, kp = pmcstat_plist; n < nproc; n++, kp++) {
323169069Sjkoshy		if ((rv = regexec(&reg, kp->ki_comm, 1, &regmatch, 0)) == 0) {
324169069Sjkoshy			if ((pt = malloc(sizeof(*pt))) == NULL)
325169069Sjkoshy				goto outofmemory;
326169069Sjkoshy			pt->pt_pid = kp->ki_pid;
327203790Sfabient			SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
328169069Sjkoshy		} else if (rv != REG_NOMATCH) {
329169069Sjkoshy			regerror(rv, &reg, errbuf, sizeof(errbuf));
330169069Sjkoshy			errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s",
331169069Sjkoshy			    errbuf);
332169069Sjkoshy		}
333169069Sjkoshy	}
334169069Sjkoshy
335169069Sjkoshy	regfree(&reg);
336169069Sjkoshy
337169069Sjkoshy	return;
338169069Sjkoshy
339169069Sjkoshy outofmemory:
340169069Sjkoshy	errx(EX_SOFTWARE, "Out of memory.");
341169069Sjkoshy	/*NOTREACHED*/
342169069Sjkoshy}
343169069Sjkoshy
344168949Sjkoshyvoid
345203790Sfabientpmcstat_kill_process(void)
346169069Sjkoshy{
347169069Sjkoshy	struct pmcstat_target *pt;
348169069Sjkoshy
349203790Sfabient	assert(args.pa_flags & FLAG_HAS_COMMANDLINE);
350169069Sjkoshy
351169069Sjkoshy	/*
352169069Sjkoshy	 * If a command line was specified, it would be the very first
353169069Sjkoshy	 * in the list, before any other processes specified by -t.
354169069Sjkoshy	 */
355203790Sfabient	pt = SLIST_FIRST(&args.pa_targets);
356169069Sjkoshy	assert(pt != NULL);
357169069Sjkoshy
358169069Sjkoshy	if (kill(pt->pt_pid, SIGINT) != 0)
359169069Sjkoshy		err(EX_OSERR, "ERROR: cannot signal child process");
360169069Sjkoshy}
361169069Sjkoshy
362169069Sjkoshyvoid
363203790Sfabientpmcstat_start_pmcs(void)
364145256Sjkoshy{
365145256Sjkoshy	struct pmcstat_ev *ev;
366145256Sjkoshy
367169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
368145256Sjkoshy
369145256Sjkoshy	    assert(ev->ev_pmcid != PMC_ID_INVALID);
370145256Sjkoshy
371145256Sjkoshy	    if (pmc_start(ev->ev_pmcid) < 0) {
372147191Sjkoshy	        warn("ERROR: Cannot start pmc 0x%x \"%s\"",
373145256Sjkoshy		    ev->ev_pmcid, ev->ev_name);
374203790Sfabient		pmcstat_cleanup();
375147191Sjkoshy		exit(EX_OSERR);
376145256Sjkoshy	    }
377145256Sjkoshy	}
378145256Sjkoshy
379145256Sjkoshy}
380145256Sjkoshy
381145256Sjkoshyvoid
382203790Sfabientpmcstat_print_headers(void)
383145256Sjkoshy{
384145256Sjkoshy	struct pmcstat_ev *ev;
385168949Sjkoshy	int c, w;
386145256Sjkoshy
387203790Sfabient	(void) fprintf(args.pa_printfile, PRINT_HEADER_PREFIX);
388145256Sjkoshy
389203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
390145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
391145256Sjkoshy			continue;
392145256Sjkoshy
393145256Sjkoshy		c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p';
394145256Sjkoshy
395168949Sjkoshy		if (ev->ev_fieldskip != 0)
396203790Sfabient			(void) fprintf(args.pa_printfile, "%*s",
397168949Sjkoshy			    ev->ev_fieldskip, "");
398168949Sjkoshy		w = ev->ev_fieldwidth - ev->ev_fieldskip - 2;
399168949Sjkoshy
400168949Sjkoshy		if (c == 's')
401203790Sfabient			(void) fprintf(args.pa_printfile, "s/%02d/%-*s ",
402168949Sjkoshy			    ev->ev_cpu, w-3, ev->ev_name);
403168949Sjkoshy		else
404203790Sfabient			(void) fprintf(args.pa_printfile, "p/%*s ", w,
405145256Sjkoshy			    ev->ev_name);
406145256Sjkoshy	}
407145256Sjkoshy
408203790Sfabient	(void) fflush(args.pa_printfile);
409145256Sjkoshy}
410145256Sjkoshy
411145256Sjkoshyvoid
412203790Sfabientpmcstat_print_counters(void)
413145256Sjkoshy{
414145256Sjkoshy	int extra_width;
415145256Sjkoshy	struct pmcstat_ev *ev;
416145256Sjkoshy	pmc_value_t value;
417145256Sjkoshy
418145256Sjkoshy	extra_width = sizeof(PRINT_HEADER_PREFIX) - 1;
419145256Sjkoshy
420203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
421145256Sjkoshy
422145256Sjkoshy		/* skip sampling mode counters */
423145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
424145256Sjkoshy			continue;
425145256Sjkoshy
426145256Sjkoshy		if (pmc_read(ev->ev_pmcid, &value) < 0)
427145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot read pmc "
428145256Sjkoshy			    "\"%s\"", ev->ev_name);
429145256Sjkoshy
430203790Sfabient		(void) fprintf(args.pa_printfile, "%*ju ",
431147708Sjkoshy		    ev->ev_fieldwidth + extra_width,
432147708Sjkoshy		    (uintmax_t) ev->ev_cumulative ? value :
433147708Sjkoshy		    (value - ev->ev_saved));
434147708Sjkoshy
435145256Sjkoshy		if (ev->ev_cumulative == 0)
436145256Sjkoshy			ev->ev_saved = value;
437145256Sjkoshy		extra_width = 0;
438145256Sjkoshy	}
439145256Sjkoshy
440203790Sfabient	(void) fflush(args.pa_printfile);
441145256Sjkoshy}
442145256Sjkoshy
443145256Sjkoshy/*
444145256Sjkoshy * Print output
445145256Sjkoshy */
446145256Sjkoshy
447145256Sjkoshyvoid
448203790Sfabientpmcstat_print_pmcs(void)
449145256Sjkoshy{
450145256Sjkoshy	static int linecount = 0;
451145256Sjkoshy
452147708Sjkoshy	/* check if we need to print a header line */
453145256Sjkoshy	if (++linecount > pmcstat_displayheight) {
454203790Sfabient		(void) fprintf(args.pa_printfile, "\n");
455145256Sjkoshy		linecount = 1;
456145256Sjkoshy	}
457145256Sjkoshy	if (linecount == 1)
458203790Sfabient		pmcstat_print_headers();
459203790Sfabient	(void) fprintf(args.pa_printfile, "\n");
460145256Sjkoshy
461203790Sfabient	pmcstat_print_counters();
462145256Sjkoshy
463145256Sjkoshy	return;
464145256Sjkoshy}
465145256Sjkoshy
466145256Sjkoshy/*
467145256Sjkoshy * Do process profiling
468145256Sjkoshy *
469145256Sjkoshy * If a pid was specified, attach each allocated PMC to the target
470145256Sjkoshy * process.  Otherwise, fork a child and attach the PMCs to the child,
471145256Sjkoshy * and have the child exec() the target program.
472145256Sjkoshy */
473145256Sjkoshy
474145256Sjkoshyvoid
475168949Sjkoshypmcstat_start_process(void)
476145256Sjkoshy{
477168949Sjkoshy	/* Signal the child to proceed. */
478168949Sjkoshy	if (write(pmcstat_sockpair[PARENTSOCKET], "!", 1) != 1)
479168949Sjkoshy		err(EX_OSERR, "ERROR (parent): write of token failed");
480145256Sjkoshy
481168949Sjkoshy	(void) close(pmcstat_sockpair[PARENTSOCKET]);
482145256Sjkoshy}
483145256Sjkoshy
484145256Sjkoshyvoid
485145256Sjkoshypmcstat_show_usage(void)
486145256Sjkoshy{
487145256Sjkoshy	errx(EX_USAGE,
488145256Sjkoshy	    "[options] [commandline]\n"
489145256Sjkoshy	    "\t Measure process and/or system performance using hardware\n"
490145256Sjkoshy	    "\t performance monitoring counters.\n"
491145256Sjkoshy	    "\t Options include:\n"
492147191Sjkoshy	    "\t -C\t\t (toggle) show cumulative counts\n"
493147191Sjkoshy	    "\t -D path\t create profiles in directory \"path\"\n"
494147191Sjkoshy	    "\t -E\t\t (toggle) show counts at process exit\n"
495203790Sfabient	    "\t -F file\t write a system-wide callgraph (Kcachegrind format)"
496203790Sfabient		" to \"file\"\n"
497174396Sjkoshy	    "\t -G file\t write a system-wide callgraph to \"file\"\n"
498157144Sjkoshy	    "\t -M file\t print executable/gmon file map to \"file\"\n"
499174396Sjkoshy	    "\t -N\t\t (toggle) capture callchains\n"
500147191Sjkoshy	    "\t -O file\t send log output to \"file\"\n"
501147191Sjkoshy	    "\t -P spec\t allocate a process-private sampling PMC\n"
502147191Sjkoshy	    "\t -R file\t read events from \"file\"\n"
503147191Sjkoshy	    "\t -S spec\t allocate a system-wide sampling PMC\n"
504203790Sfabient	    "\t -T\t\t start in top mode\n"
505147191Sjkoshy	    "\t -W\t\t (toggle) show counts per context switch\n"
506168949Sjkoshy	    "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n"
507147191Sjkoshy	    "\t -d\t\t (toggle) track descendants\n"
508203790Sfabient	    "\t -f spec\t pass \"spec\" to as plugin option\n"
509147191Sjkoshy	    "\t -g\t\t produce gprof(1) compatible profiles\n"
510162804Sru	    "\t -k dir\t\t set the path to the kernel\n"
511145256Sjkoshy	    "\t -n rate\t set sampling rate\n"
512145256Sjkoshy	    "\t -o file\t send print output to \"file\"\n"
513147191Sjkoshy	    "\t -p spec\t allocate a process-private counting PMC\n"
514157144Sjkoshy	    "\t -q\t\t suppress verbosity\n"
515157144Sjkoshy	    "\t -r fsroot\t specify FS root directory\n"
516147191Sjkoshy	    "\t -s spec\t allocate a system-wide counting PMC\n"
517183186Sjkoshy	    "\t -t process-spec attach to running processes matching "
518183186Sjkoshy		"\"process-spec\"\n"
519157144Sjkoshy	    "\t -v\t\t increase verbosity\n"
520174396Sjkoshy	    "\t -w secs\t set printing time interval\n"
521174396Sjkoshy	    "\t -z depth\t limit callchain display depth"
522145256Sjkoshy	);
523145256Sjkoshy}
524145256Sjkoshy
525145256Sjkoshy/*
526203790Sfabient * At exit handler for top mode
527203790Sfabient */
528203790Sfabient
529203790Sfabientvoid
530203790Sfabientpmcstat_topexit(void)
531203790Sfabient{
532203790Sfabient	if (!args.pa_toptty)
533203790Sfabient		return;
534203790Sfabient
535203790Sfabient	/*
536203790Sfabient	 * Shutdown ncurses.
537203790Sfabient	 */
538203790Sfabient	clrtoeol();
539203790Sfabient	refresh();
540203790Sfabient	endwin();
541203790Sfabient}
542203790Sfabient
543203790Sfabient/*
544145256Sjkoshy * Main
545145256Sjkoshy */
546145256Sjkoshy
547145256Sjkoshyint
548145256Sjkoshymain(int argc, char **argv)
549145256Sjkoshy{
550224698Sattilio	cpuset_t cpumask;
551145256Sjkoshy	double interval;
552224698Sattilio	int hcpu, option, npmc, ncpu;
553151542Sjkoshy	int c, check_driver_stats, current_cpu, current_sampling_count;
554174396Sjkoshy	int do_callchain, do_descendants, do_logproccsw, do_logprocexit;
555226514Sfabient	int do_print, do_read;
556168949Sjkoshy	size_t dummy;
557174396Sjkoshy	int graphdepth;
558210794Sfabient	int pipefd[2], rfd;
559147191Sjkoshy	int use_cumulative_counts;
560203790Sfabient	short cf, cb;
561157144Sjkoshy	char *end, *tmp;
562174396Sjkoshy	const char *errmsg, *graphfilename;
563147191Sjkoshy	enum pmcstat_state runstate;
564151542Sjkoshy	struct pmc_driverstats ds_start, ds_end;
565145256Sjkoshy	struct pmcstat_ev *ev;
566145256Sjkoshy	struct sigaction sa;
567145256Sjkoshy	struct kevent kev;
568145256Sjkoshy	struct winsize ws;
569147708Sjkoshy	struct stat sb;
570157144Sjkoshy	char buffer[PATH_MAX];
571145256Sjkoshy
572151542Sjkoshy	check_driver_stats      = 0;
573145256Sjkoshy	current_cpu 		= 0;
574145256Sjkoshy	current_sampling_count  = DEFAULT_SAMPLE_COUNT;
575174396Sjkoshy	do_callchain		= 1;
576145256Sjkoshy	do_descendants          = 0;
577147191Sjkoshy	do_logproccsw           = 0;
578147191Sjkoshy	do_logprocexit          = 0;
579145256Sjkoshy	use_cumulative_counts   = 0;
580174396Sjkoshy	graphfilename		= "-";
581147191Sjkoshy	args.pa_required	= 0;
582145256Sjkoshy	args.pa_flags		= 0;
583157144Sjkoshy	args.pa_verbosity	= 1;
584147708Sjkoshy	args.pa_logfd		= -1;
585157144Sjkoshy	args.pa_fsroot		= "";
586157144Sjkoshy	args.pa_kernel		= strdup("/boot/kernel");
587147708Sjkoshy	args.pa_samplesdir	= ".";
588147708Sjkoshy	args.pa_printfile	= stderr;
589174396Sjkoshy	args.pa_graphdepth	= DEFAULT_CALLGRAPH_DEPTH;
590174396Sjkoshy	args.pa_graphfile	= NULL;
591145256Sjkoshy	args.pa_interval	= DEFAULT_WAIT_INTERVAL;
592157144Sjkoshy	args.pa_mapfilename	= NULL;
593174396Sjkoshy	args.pa_inputpath	= NULL;
594174396Sjkoshy	args.pa_outputpath	= NULL;
595203790Sfabient	args.pa_pplugin		= PMCSTAT_PL_NONE;
596203790Sfabient	args.pa_plugin		= PMCSTAT_PL_NONE;
597203790Sfabient	args.pa_ctdumpinstr	= 1;
598203790Sfabient	args.pa_topmode		= PMCSTAT_TOP_DELTA;
599203790Sfabient	args.pa_toptty		= 0;
600203790Sfabient	args.pa_topcolor	= 0;
601203790Sfabient	args.pa_mergepmc	= 0;
602169069Sjkoshy	STAILQ_INIT(&args.pa_events);
603169069Sjkoshy	SLIST_INIT(&args.pa_targets);
604153704Sjkoshy	bzero(&ds_start, sizeof(ds_start));
605153704Sjkoshy	bzero(&ds_end, sizeof(ds_end));
606145256Sjkoshy	ev = NULL;
607224698Sattilio	CPU_ZERO(&cpumask);
608145256Sjkoshy
609174396Sjkoshy	/*
610174396Sjkoshy	 * The initial CPU mask specifies all non-halted CPUS in the
611174396Sjkoshy	 * system.
612174396Sjkoshy	 */
613174396Sjkoshy	dummy = sizeof(int);
614168949Sjkoshy	if (sysctlbyname("hw.ncpu", &ncpu, &dummy, NULL, 0) < 0)
615174396Sjkoshy		err(EX_OSERR, "ERROR: Cannot determine the number of CPUs");
616224698Sattilio	for (hcpu = 0; hcpu < ncpu; hcpu++)
617224698Sattilio		CPU_SET(hcpu, &cpumask);
618168949Sjkoshy
619157144Sjkoshy	while ((option = getopt(argc, argv,
620203790Sfabient	    "CD:EF:G:M:NO:P:R:S:TWc:df:gk:m:n:o:p:qr:s:t:vw:z:")) != -1)
621145256Sjkoshy		switch (option) {
622145256Sjkoshy		case 'C':	/* cumulative values */
623145256Sjkoshy			use_cumulative_counts = !use_cumulative_counts;
624147191Sjkoshy			args.pa_required |= FLAG_HAS_COUNTING_PMCS;
625145256Sjkoshy			break;
626145256Sjkoshy
627145256Sjkoshy		case 'c':	/* CPU */
628168949Sjkoshy
629224698Sattilio			if (optarg[0] == '*' && optarg[1] == '\0') {
630224698Sattilio				for (hcpu = 0; hcpu < ncpu; hcpu++)
631224698Sattilio					CPU_SET(hcpu, &cpumask);
632224698Sattilio			} else
633224698Sattilio				pmcstat_get_cpumask(optarg, &cpumask);
634168949Sjkoshy
635210797Sfabient			args.pa_flags	 |= FLAGS_HAS_CPUMASK;
636147191Sjkoshy			args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
637145256Sjkoshy			break;
638145256Sjkoshy
639147708Sjkoshy		case 'D':
640147708Sjkoshy			if (stat(optarg, &sb) < 0)
641147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
642147708Sjkoshy				    optarg);
643147708Sjkoshy			if (!S_ISDIR(sb.st_mode))
644147708Sjkoshy				errx(EX_USAGE, "ERROR: \"%s\" is not a "
645168949Sjkoshy				    "directory.", optarg);
646147708Sjkoshy			args.pa_samplesdir = optarg;
647147708Sjkoshy			args.pa_flags     |= FLAG_HAS_SAMPLESDIR;
648147708Sjkoshy			args.pa_required  |= FLAG_DO_GPROF;
649147708Sjkoshy			break;
650147708Sjkoshy
651145256Sjkoshy		case 'd':	/* toggle descendents */
652145256Sjkoshy			do_descendants = !do_descendants;
653147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
654145256Sjkoshy			break;
655145256Sjkoshy
656203790Sfabient		case 'F':	/* produce a system-wide calltree */
657203790Sfabient			args.pa_flags |= FLAG_DO_CALLGRAPHS;
658203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLTREE;
659203790Sfabient			graphfilename = optarg;
660203790Sfabient			break;
661203790Sfabient
662203790Sfabient		case 'f':	/* plugins options */
663203790Sfabient			if (args.pa_plugin == PMCSTAT_PL_NONE)
664203790Sfabient				err(EX_USAGE, "ERROR: Need -g/-G/-m/-T.");
665203790Sfabient			pmcstat_pluginconfigure_log(optarg);
666203790Sfabient			break;
667203790Sfabient
668174396Sjkoshy		case 'G':	/* produce a system-wide callgraph */
669174396Sjkoshy			args.pa_flags |= FLAG_DO_CALLGRAPHS;
670203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
671174396Sjkoshy			graphfilename = optarg;
672174396Sjkoshy			break;
673174396Sjkoshy
674147191Sjkoshy		case 'g':	/* produce gprof compatible profiles */
675147191Sjkoshy			args.pa_flags |= FLAG_DO_GPROF;
676203790Sfabient			args.pa_pplugin = PMCSTAT_PL_CALLGRAPH;
677203790Sfabient			args.pa_plugin	= PMCSTAT_PL_GPROF;
678147191Sjkoshy			break;
679147191Sjkoshy
680147708Sjkoshy		case 'k':	/* pathname to the kernel */
681157144Sjkoshy			free(args.pa_kernel);
682157144Sjkoshy			args.pa_kernel = strdup(optarg);
683174396Sjkoshy			args.pa_required |= FLAG_DO_ANALYSIS;
684147708Sjkoshy			args.pa_flags    |= FLAG_HAS_KERNELPATH;
685147191Sjkoshy			break;
686147191Sjkoshy
687185322Sattilio		case 'm':
688203790Sfabient			args.pa_flags |= FLAG_DO_ANNOTATE;
689203790Sfabient			args.pa_plugin = PMCSTAT_PL_ANNOTATE;
690203790Sfabient			graphfilename  = optarg;
691185322Sattilio			break;
692185322Sattilio
693147191Sjkoshy		case 'E':	/* log process exit */
694147191Sjkoshy			do_logprocexit = !do_logprocexit;
695147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
696147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
697147191Sjkoshy			break;
698147191Sjkoshy
699157144Sjkoshy		case 'M':	/* mapfile */
700157144Sjkoshy			args.pa_mapfilename = optarg;
701157144Sjkoshy			break;
702157144Sjkoshy
703174396Sjkoshy		case 'N':
704174396Sjkoshy			do_callchain = !do_callchain;
705174396Sjkoshy			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
706174396Sjkoshy			break;
707174396Sjkoshy
708145256Sjkoshy		case 'p':	/* process virtual counting PMC */
709145256Sjkoshy		case 's':	/* system-wide counting PMC */
710145256Sjkoshy		case 'P':	/* process virtual sampling PMC */
711145256Sjkoshy		case 'S':	/* system-wide sampling PMC */
712145256Sjkoshy			if ((ev = malloc(sizeof(*ev))) == NULL)
713147191Sjkoshy				errx(EX_SOFTWARE, "ERROR: Out of memory.");
714145256Sjkoshy
715145256Sjkoshy			switch (option) {
716145256Sjkoshy			case 'p': ev->ev_mode = PMC_MODE_TC; break;
717145256Sjkoshy			case 's': ev->ev_mode = PMC_MODE_SC; break;
718145256Sjkoshy			case 'P': ev->ev_mode = PMC_MODE_TS; break;
719145256Sjkoshy			case 'S': ev->ev_mode = PMC_MODE_SS; break;
720145256Sjkoshy			}
721145256Sjkoshy
722147191Sjkoshy			if (option == 'P' || option == 'p') {
723147191Sjkoshy				args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
724147708Sjkoshy				args.pa_required |= (FLAG_HAS_COMMANDLINE |
725169069Sjkoshy				    FLAG_HAS_TARGET);
726147191Sjkoshy			}
727145256Sjkoshy
728147191Sjkoshy			if (option == 'P' || option == 'S') {
729147191Sjkoshy				args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
730147708Sjkoshy				args.pa_required |= (FLAG_HAS_PIPE |
731147708Sjkoshy				    FLAG_HAS_OUTPUT_LOGFILE);
732147191Sjkoshy			}
733145256Sjkoshy
734145256Sjkoshy			if (option == 'p' || option == 's')
735147191Sjkoshy				args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
736145256Sjkoshy
737147191Sjkoshy			if (option == 's' || option == 'S')
738147191Sjkoshy				args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
739147191Sjkoshy
740145256Sjkoshy			ev->ev_spec  = strdup(optarg);
741145256Sjkoshy
742145256Sjkoshy			if (option == 'S' || option == 'P')
743145256Sjkoshy				ev->ev_count = current_sampling_count;
744145256Sjkoshy			else
745145256Sjkoshy				ev->ev_count = -1;
746145256Sjkoshy
747224698Sattilio			if (option == 'S' || option == 's') {
748224698Sattilio				hcpu = sizeof(cpumask) * NBBY;
749224698Sattilio				for (hcpu--; hcpu >= 0; hcpu--)
750224698Sattilio					if (CPU_ISSET(hcpu, &cpumask))
751224698Sattilio						break;
752224698Sattilio				ev->ev_cpu = hcpu;
753224698Sattilio			} else
754145256Sjkoshy				ev->ev_cpu = PMC_CPU_ANY;
755145256Sjkoshy
756147191Sjkoshy			ev->ev_flags = 0;
757174396Sjkoshy			if (do_callchain)
758174396Sjkoshy				ev->ev_flags |= PMC_F_CALLCHAIN;
759147191Sjkoshy			if (do_descendants)
760147191Sjkoshy				ev->ev_flags |= PMC_F_DESCENDANTS;
761147191Sjkoshy			if (do_logprocexit)
762147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCEXIT;
763147191Sjkoshy			if (do_logproccsw)
764147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCCSW;
765147191Sjkoshy
766145256Sjkoshy			ev->ev_cumulative  = use_cumulative_counts;
767145256Sjkoshy
768145256Sjkoshy			ev->ev_saved = 0LL;
769145256Sjkoshy			ev->ev_pmcid = PMC_ID_INVALID;
770145256Sjkoshy
771145256Sjkoshy			/* extract event name */
772145256Sjkoshy			c = strcspn(optarg, ", \t");
773145256Sjkoshy			ev->ev_name = malloc(c + 1);
774145256Sjkoshy			(void) strncpy(ev->ev_name, optarg, c);
775145256Sjkoshy			*(ev->ev_name + c) = '\0';
776145256Sjkoshy
777169069Sjkoshy			STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
778145256Sjkoshy
779224698Sattilio			if (option == 's' || option == 'S') {
780224698Sattilio				hcpu = CPU_ISSET(ev->ev_cpu, &cpumask);
781224698Sattilio				CPU_CLR(ev->ev_cpu, &cpumask);
782224698Sattilio				pmcstat_clone_event_descriptor(ev, &cpumask);
783224698Sattilio				if (hcpu != 0)
784224698Sattilio					CPU_SET(ev->ev_cpu, &cpumask);
785224698Sattilio			}
786168949Sjkoshy
787145256Sjkoshy			break;
788145256Sjkoshy
789145256Sjkoshy		case 'n':	/* sampling count */
790145256Sjkoshy			current_sampling_count = strtol(optarg, &end, 0);
791145256Sjkoshy			if (*end != '\0' || current_sampling_count <= 0)
792145256Sjkoshy				errx(EX_USAGE,
793147191Sjkoshy				    "ERROR: Illegal count value \"%s\".",
794145256Sjkoshy				    optarg);
795147191Sjkoshy			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
796145256Sjkoshy			break;
797145256Sjkoshy
798145256Sjkoshy		case 'o':	/* outputfile */
799226986Sfabient			if (args.pa_printfile != NULL &&
800226986Sfabient			    args.pa_printfile != stdout &&
801226986Sfabient			    args.pa_printfile != stderr)
802147708Sjkoshy				(void) fclose(args.pa_printfile);
803147708Sjkoshy			if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
804145256Sjkoshy				errx(EX_OSERR, "ERROR: cannot open \"%s\" for "
805147191Sjkoshy				    "writing.", optarg);
806147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
807147191Sjkoshy			break;
808145256Sjkoshy
809145256Sjkoshy		case 'O':	/* sampling output */
810147708Sjkoshy			if (args.pa_outputpath)
811147708Sjkoshy				errx(EX_USAGE, "ERROR: option -O may only be "
812147191Sjkoshy				    "specified once.");
813147708Sjkoshy			args.pa_outputpath = optarg;
814147708Sjkoshy			args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
815145256Sjkoshy			break;
816145256Sjkoshy
817157144Sjkoshy		case 'q':	/* quiet mode */
818157144Sjkoshy			args.pa_verbosity = 0;
819157144Sjkoshy			break;
820157144Sjkoshy
821157144Sjkoshy		case 'r':	/* root FS path */
822157144Sjkoshy			args.pa_fsroot = optarg;
823157144Sjkoshy			break;
824157144Sjkoshy
825147708Sjkoshy		case 'R':	/* read an existing log file */
826174396Sjkoshy			if (args.pa_inputpath != NULL)
827147708Sjkoshy				errx(EX_USAGE, "ERROR: option -R may only be "
828147708Sjkoshy				    "specified once.");
829147708Sjkoshy			args.pa_inputpath = optarg;
830147708Sjkoshy			if (args.pa_printfile == stderr)
831147708Sjkoshy				args.pa_printfile = stdout;
832147708Sjkoshy			args.pa_flags |= FLAG_READ_LOGFILE;
833147708Sjkoshy			break;
834147708Sjkoshy
835169069Sjkoshy		case 't':	/* target pid or process name */
836203790Sfabient			pmcstat_find_targets(optarg);
837145256Sjkoshy
838169069Sjkoshy			args.pa_flags |= FLAG_HAS_TARGET;
839147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
840145256Sjkoshy			break;
841145256Sjkoshy
842203790Sfabient		case 'T':	/* top mode */
843203790Sfabient			args.pa_flags |= FLAG_DO_TOP;
844203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
845203790Sfabient			args.pa_ctdumpinstr = 0;
846203790Sfabient			args.pa_mergepmc = 1;
847203790Sfabient			if (args.pa_printfile == stderr)
848203790Sfabient				args.pa_printfile = stdout;
849203790Sfabient			break;
850203790Sfabient
851157144Sjkoshy		case 'v':	/* verbose */
852157144Sjkoshy			args.pa_verbosity++;
853157144Sjkoshy			break;
854157144Sjkoshy
855145256Sjkoshy		case 'w':	/* wait interval */
856145256Sjkoshy			interval = strtod(optarg, &end);
857145256Sjkoshy			if (*end != '\0' || interval <= 0)
858145256Sjkoshy				errx(EX_USAGE, "ERROR: Illegal wait interval "
859147191Sjkoshy				    "value \"%s\".", optarg);
860145256Sjkoshy			args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
861145256Sjkoshy			args.pa_interval = interval;
862147191Sjkoshy			break;
863145256Sjkoshy
864147191Sjkoshy		case 'W':	/* toggle LOG_CSW */
865147191Sjkoshy			do_logproccsw = !do_logproccsw;
866147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
867147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
868145256Sjkoshy			break;
869145256Sjkoshy
870174396Sjkoshy		case 'z':
871174396Sjkoshy			graphdepth = strtod(optarg, &end);
872174396Sjkoshy			if (*end != '\0' || graphdepth <= 0)
873174396Sjkoshy				errx(EX_USAGE, "ERROR: Illegal callchain "
874174396Sjkoshy				    "depth \"%s\".", optarg);
875174396Sjkoshy			args.pa_graphdepth = graphdepth;
876174396Sjkoshy			args.pa_required |= FLAG_DO_CALLGRAPHS;
877174396Sjkoshy			break;
878174396Sjkoshy
879145256Sjkoshy		case '?':
880145256Sjkoshy		default:
881145256Sjkoshy			pmcstat_show_usage();
882145256Sjkoshy			break;
883145256Sjkoshy
884145256Sjkoshy		}
885145256Sjkoshy
886145256Sjkoshy	args.pa_argc = (argc -= optind);
887145256Sjkoshy	args.pa_argv = (argv += optind);
888145256Sjkoshy
889210797Sfabient	/* If we read from logfile and no specified CPU mask use
890210797Sfabient	 * the maximum CPU count.
891210797Sfabient	 */
892210797Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) &&
893210797Sfabient	    (args.pa_flags & FLAGS_HAS_CPUMASK) == 0)
894224698Sattilio		CPU_FILL(&cpumask);
895210797Sfabient
896174396Sjkoshy	args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
897174396Sjkoshy
898147708Sjkoshy	if (argc)	/* command line present */
899147708Sjkoshy		args.pa_flags |= FLAG_HAS_COMMANDLINE;
900145256Sjkoshy
901185322Sattilio	if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
902203790Sfabient	    FLAG_DO_ANNOTATE | FLAG_DO_TOP))
903174396Sjkoshy		args.pa_flags |= FLAG_DO_ANALYSIS;
904174396Sjkoshy
905145256Sjkoshy	/*
906145256Sjkoshy	 * Check invocation syntax.
907145256Sjkoshy	 */
908145256Sjkoshy
909147708Sjkoshy	/* disallow -O and -R together */
910147708Sjkoshy	if (args.pa_outputpath && args.pa_inputpath)
911147708Sjkoshy		errx(EX_USAGE, "ERROR: options -O and -R are mutually "
912147708Sjkoshy		    "exclusive.");
913147708Sjkoshy
914185322Sattilio	/* -m option is allowed with -R only. */
915203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
916185322Sattilio		errx(EX_USAGE, "ERROR: option -m requires an input file");
917185322Sattilio
918185322Sattilio	/* -m option is not allowed combined with -g or -G. */
919203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE &&
920185322Sattilio	    args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
921185322Sattilio		errx(EX_USAGE, "ERROR: option -m and -g | -G are mutually "
922185322Sattilio		    "exclusive");
923185322Sattilio
924147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
925147191Sjkoshy		errmsg = NULL;
926147708Sjkoshy		if (args.pa_flags & FLAG_HAS_COMMANDLINE)
927147191Sjkoshy			errmsg = "a command line specification";
928169069Sjkoshy		else if (args.pa_flags & FLAG_HAS_TARGET)
929147191Sjkoshy			errmsg = "option -t";
930169069Sjkoshy		else if (!STAILQ_EMPTY(&args.pa_events))
931147191Sjkoshy			errmsg = "a PMC event specification";
932147191Sjkoshy		if (errmsg)
933147191Sjkoshy			errx(EX_USAGE, "ERROR: option -R may not be used with "
934147191Sjkoshy			    "%s.", errmsg);
935169069Sjkoshy	} else if (STAILQ_EMPTY(&args.pa_events))
936147708Sjkoshy		/* All other uses require a PMC spec. */
937145256Sjkoshy		pmcstat_show_usage();
938145256Sjkoshy
939147191Sjkoshy	/* check for -t pid without a process PMC spec */
940169069Sjkoshy	if ((args.pa_required & FLAG_HAS_TARGET) &&
941147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
942147191Sjkoshy		errx(EX_USAGE, "ERROR: option -t requires a process mode PMC "
943147191Sjkoshy		    "to be specified.");
944147191Sjkoshy
945147191Sjkoshy	/* check for process-mode options without a command or -t pid */
946147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
947169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
948147708Sjkoshy		errx(EX_USAGE, "ERROR: options -d, -E, -p, -P, and -W require "
949147708Sjkoshy		    "a command line or target process.");
950147191Sjkoshy
951147191Sjkoshy	/* check for -p | -P without a target process of some sort */
952169069Sjkoshy	if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
953169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
954147708Sjkoshy		errx(EX_USAGE, "ERROR: options -P and -p require a "
955147191Sjkoshy		    "target process or a command line.");
956147191Sjkoshy
957147191Sjkoshy	/* check for process-mode options without a process-mode PMC */
958147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
959147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
960147708Sjkoshy		errx(EX_USAGE, "ERROR: options -d, -E, and -W require a "
961147191Sjkoshy		    "process mode PMC to be specified.");
962147191Sjkoshy
963174396Sjkoshy	/* check for -c cpu with no system mode PMCs or logfile. */
964147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
965174396Sjkoshy	    (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
966174396Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
967147191Sjkoshy		errx(EX_USAGE, "ERROR: option -c requires at least one "
968147191Sjkoshy		    "system mode PMC to be specified.");
969147191Sjkoshy
970147191Sjkoshy	/* check for counting mode options without a counting PMC */
971147191Sjkoshy	if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
972147191Sjkoshy	    (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
973203790Sfabient		errx(EX_USAGE, "ERROR: options -C, -W and -o require at "
974149805Sjkoshy		    "least one counting mode PMC to be specified.");
975147191Sjkoshy
976147191Sjkoshy	/* check for sampling mode options without a sampling PMC spec */
977147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
978147191Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
979174396Sjkoshy		errx(EX_USAGE, "ERROR: options -N, -n and -O require at "
980174396Sjkoshy		    "least one sampling mode PMC to be specified.");
981147191Sjkoshy
982203790Sfabient	/* check if -g/-G/-m/-T are being used correctly */
983174396Sjkoshy	if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
984147708Sjkoshy	    !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
985203790Sfabient		errx(EX_USAGE, "ERROR: options -g/-G/-m/-T require sampling PMCs "
986174396Sjkoshy		    "or -R to be specified.");
987147708Sjkoshy
988147191Sjkoshy	/* check if -O was spuriously specified */
989147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
990147708Sjkoshy	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
991147191Sjkoshy		errx(EX_USAGE,
992147191Sjkoshy		    "ERROR: option -O is used only with options "
993147708Sjkoshy		    "-E, -P, -S and -W.");
994147191Sjkoshy
995203790Sfabient	/* -k kernel path require -g/-G/-m/-T or -R */
996147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
997174396Sjkoshy	    (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
998157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
999203790Sfabient	    errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
1000147708Sjkoshy
1001174396Sjkoshy	/* -D only applies to gprof output mode (-g) */
1002147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
1003174396Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0)
1004174396Sjkoshy	    errx(EX_USAGE, "ERROR: option -D is only used with -g.");
1005147708Sjkoshy
1006157144Sjkoshy	/* -M mapfile requires -g or -R */
1007157144Sjkoshy	if (args.pa_mapfilename != NULL &&
1008157144Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0 &&
1009157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1010157144Sjkoshy	    errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
1011157144Sjkoshy
1012147708Sjkoshy	/*
1013147708Sjkoshy	 * Disallow textual output of sampling PMCs if counting PMCs
1014147708Sjkoshy	 * have also been asked for, mostly because the combined output
1015147708Sjkoshy	 * is difficult to make sense of.
1016147708Sjkoshy	 */
1017147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1018147708Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1019168927Sjkoshy	    ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
1020147708Sjkoshy		errx(EX_USAGE, "ERROR: option -O is required if counting and "
1021147708Sjkoshy		    "sampling PMCs are specified together.");
1022147708Sjkoshy
1023157144Sjkoshy	/*
1024174396Sjkoshy	 * Check if "-k kerneldir" was specified, and if whether
1025174396Sjkoshy	 * 'kerneldir' actually refers to a a file.  If so, use
1026174396Sjkoshy	 * `dirname path` to determine the kernel directory.
1027157144Sjkoshy	 */
1028157144Sjkoshy	if (args.pa_flags & FLAG_HAS_KERNELPATH) {
1029157144Sjkoshy		(void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
1030157144Sjkoshy		    args.pa_kernel);
1031157144Sjkoshy		if (stat(buffer, &sb) < 0)
1032157144Sjkoshy			err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
1033157144Sjkoshy			    buffer);
1034157144Sjkoshy		if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
1035157144Sjkoshy			errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
1036157144Sjkoshy			    buffer);
1037157144Sjkoshy		if (!S_ISDIR(sb.st_mode)) {
1038157144Sjkoshy			tmp = args.pa_kernel;
1039157144Sjkoshy			args.pa_kernel = strdup(dirname(args.pa_kernel));
1040157144Sjkoshy			free(tmp);
1041157144Sjkoshy			(void) snprintf(buffer, sizeof(buffer), "%s%s",
1042157144Sjkoshy			    args.pa_fsroot, args.pa_kernel);
1043157144Sjkoshy			if (stat(buffer, &sb) < 0)
1044157144Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
1045157144Sjkoshy				    buffer);
1046157144Sjkoshy			if (!S_ISDIR(sb.st_mode))
1047157144Sjkoshy				errx(EX_USAGE, "ERROR: \"%s\" is not a "
1048157144Sjkoshy				    "directory.", buffer);
1049157144Sjkoshy		}
1050157144Sjkoshy	}
1051168949Sjkoshy
1052174396Sjkoshy	/*
1053174396Sjkoshy	 * If we have a callgraph be created, select the outputfile.
1054174396Sjkoshy	 */
1055174396Sjkoshy	if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
1056174396Sjkoshy		if (strcmp(graphfilename, "-") == 0)
1057174396Sjkoshy		    args.pa_graphfile = args.pa_printfile;
1058174396Sjkoshy		else {
1059174396Sjkoshy			args.pa_graphfile = fopen(graphfilename, "w");
1060174396Sjkoshy			if (args.pa_graphfile == NULL)
1061174396Sjkoshy				err(EX_OSERR, "ERROR: cannot open \"%s\" "
1062174396Sjkoshy				    "for writing", graphfilename);
1063174396Sjkoshy		}
1064174396Sjkoshy	}
1065203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE) {
1066185322Sattilio		args.pa_graphfile = fopen(graphfilename, "w");
1067185322Sattilio		if (args.pa_graphfile == NULL)
1068185322Sattilio			err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
1069185322Sattilio			    graphfilename);
1070185322Sattilio	}
1071174396Sjkoshy
1072210794Sfabient	/* if we've been asked to process a log file, skip init */
1073210794Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) {
1074210794Sfabient		if (pmc_init() < 0)
1075210794Sfabient			err(EX_UNAVAILABLE,
1076210794Sfabient			    "ERROR: Initialization of the pmc(3) library failed");
1077210794Sfabient
1078210794Sfabient		if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1079210794Sfabient			err(EX_OSERR, "ERROR: Cannot determine the number of PMCs "
1080210794Sfabient			    "on CPU %d", 0);
1081210794Sfabient	}
1082210794Sfabient
1083210794Sfabient	/* Allocate a kqueue */
1084210794Sfabient	if ((pmcstat_kq = kqueue()) < 0)
1085210794Sfabient		err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1086210794Sfabient
1087210794Sfabient	/* Setup the logfile as the source. */
1088147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
1089147708Sjkoshy		/*
1090147708Sjkoshy		 * Print the log in textual form if we haven't been
1091174396Sjkoshy		 * asked to generate profiling information.
1092147708Sjkoshy		 */
1093174396Sjkoshy		if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1094147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
1095147708Sjkoshy
1096203790Sfabient		pmcstat_initialize_logging();
1097210794Sfabient		rfd = pmcstat_open_log(args.pa_inputpath,
1098157406Sjkoshy		    PMCSTAT_OPEN_FOR_READ);
1099210794Sfabient		if ((args.pa_logparser = pmclog_open(rfd)) == NULL)
1100147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot create parser");
1101210794Sfabient		if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0)
1102210794Sfabient			err(EX_OSERR, "ERROR: fcntl(2) failed");
1103210794Sfabient		EV_SET(&kev, rfd, EVFILT_READ, EV_ADD,
1104210794Sfabient		    0, 0, NULL);
1105210794Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1106210794Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1107147191Sjkoshy	}
1108145256Sjkoshy	/*
1109147708Sjkoshy	 * Configure the specified log file or setup a default log
1110147708Sjkoshy	 * consumer via a pipe.
1111147708Sjkoshy	 */
1112147708Sjkoshy	if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1113157406Sjkoshy		if (args.pa_outputpath)
1114157406Sjkoshy			args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1115157406Sjkoshy			    PMCSTAT_OPEN_FOR_WRITE);
1116157406Sjkoshy		else {
1117147708Sjkoshy			/*
1118147708Sjkoshy			 * process the log on the fly by reading it in
1119147708Sjkoshy			 * through a pipe.
1120147708Sjkoshy			 */
1121147708Sjkoshy			if (pipe(pipefd) < 0)
1122147708Sjkoshy				err(EX_OSERR, "ERROR: pipe(2) failed");
1123147708Sjkoshy
1124147708Sjkoshy			if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1125147708Sjkoshy				err(EX_OSERR, "ERROR: fcntl(2) failed");
1126147708Sjkoshy
1127147708Sjkoshy			EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1128147708Sjkoshy			    0, 0, NULL);
1129147708Sjkoshy
1130147708Sjkoshy			if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1131147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot register kevent");
1132147708Sjkoshy
1133147708Sjkoshy			args.pa_logfd = pipefd[WRITEPIPEFD];
1134147708Sjkoshy
1135203790Sfabient			args.pa_flags |= FLAG_HAS_PIPE;
1136203790Sfabient			if ((args.pa_flags & FLAG_DO_TOP) == 0)
1137203790Sfabient				args.pa_flags |= FLAG_DO_PRINT;
1138147708Sjkoshy			args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1139147708Sjkoshy		}
1140147708Sjkoshy
1141147708Sjkoshy		if (pmc_configure_logfile(args.pa_logfd) < 0)
1142147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot configure log file");
1143147708Sjkoshy	}
1144147708Sjkoshy
1145151542Sjkoshy	/* remember to check for driver errors if we are sampling or logging */
1146151542Sjkoshy	check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1147151542Sjkoshy	    (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1148151542Sjkoshy
1149147708Sjkoshy	/*
1150210794Sfabient	if (args.pa_flags & FLAG_READ_LOGFILE) {
1151145256Sjkoshy	 * Allocate PMCs.
1152145256Sjkoshy	 */
1153145256Sjkoshy
1154169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1155145256Sjkoshy	    if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1156147191Sjkoshy		    ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1157145256Sjkoshy		    err(EX_OSERR, "ERROR: Cannot allocate %s-mode pmc with "
1158145256Sjkoshy			"specification \"%s\"",
1159145256Sjkoshy			PMC_IS_SYSTEM_MODE(ev->ev_mode) ? "system" : "process",
1160145256Sjkoshy			ev->ev_spec);
1161145256Sjkoshy
1162147708Sjkoshy	    if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1163147708Sjkoshy		pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1164147708Sjkoshy		    err(EX_OSERR, "ERROR: Cannot set sampling count "
1165147708Sjkoshy			"for PMC \"%s\"", ev->ev_name);
1166147708Sjkoshy	}
1167147708Sjkoshy
1168145256Sjkoshy	/* compute printout widths */
1169169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1170145774Sjkoshy		int counter_width;
1171145774Sjkoshy		int display_width;
1172145774Sjkoshy		int header_width;
1173145256Sjkoshy
1174145774Sjkoshy		(void) pmc_width(ev->ev_pmcid, &counter_width);
1175168949Sjkoshy		header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1176145774Sjkoshy		display_width = (int) floor(counter_width / 3.32193) + 1;
1177145256Sjkoshy
1178168949Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1179168949Sjkoshy			header_width += 3; /* 2 digit CPU number + '/' */
1180168949Sjkoshy
1181145774Sjkoshy		if (header_width > display_width) {
1182145256Sjkoshy			ev->ev_fieldskip = 0;
1183145774Sjkoshy			ev->ev_fieldwidth = header_width;
1184145256Sjkoshy		} else {
1185145774Sjkoshy			ev->ev_fieldskip = display_width -
1186145774Sjkoshy			    header_width;
1187145774Sjkoshy			ev->ev_fieldwidth = display_width;
1188145256Sjkoshy		}
1189145256Sjkoshy	}
1190145256Sjkoshy
1191145256Sjkoshy	/*
1192145256Sjkoshy	 * If our output is being set to a terminal, register a handler
1193145256Sjkoshy	 * for window size changes.
1194145256Sjkoshy	 */
1195145256Sjkoshy
1196147708Sjkoshy	if (isatty(fileno(args.pa_printfile))) {
1197145256Sjkoshy
1198147708Sjkoshy		if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1199145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot determine window size");
1200145256Sjkoshy
1201145256Sjkoshy		pmcstat_displayheight = ws.ws_row - 1;
1202203790Sfabient		pmcstat_displaywidth  = ws.ws_col - 1;
1203145256Sjkoshy
1204145256Sjkoshy		EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1205145256Sjkoshy
1206145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1207145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot register kevent for "
1208145256Sjkoshy			    "SIGWINCH");
1209203790Sfabient
1210203790Sfabient		args.pa_toptty = 1;
1211145256Sjkoshy	}
1212145256Sjkoshy
1213203790Sfabient	/*
1214203790Sfabient	 * Listen to key input in top mode.
1215203790Sfabient	 */
1216203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1217203790Sfabient		EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1218203790Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1219203790Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1220203790Sfabient	}
1221203790Sfabient
1222145256Sjkoshy	EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1223145256Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1224145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1225145256Sjkoshy
1226147191Sjkoshy	EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1227147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1228147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1229145256Sjkoshy
1230147191Sjkoshy	/*
1231147191Sjkoshy	 * An exec() failure of a forked child is signalled by the
1232147191Sjkoshy	 * child sending the parent a SIGCHLD.  We don't register an
1233147191Sjkoshy	 * actual signal handler for SIGCHLD, but instead use our
1234147191Sjkoshy	 * kqueue to pick up the signal.
1235147191Sjkoshy	 */
1236147191Sjkoshy	EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1237147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1238147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1239145256Sjkoshy
1240203790Sfabient	/*
1241203790Sfabient	 * Setup a timer if we have counting mode PMCs needing to be printed or
1242203790Sfabient	 * top mode plugin is active.
1243203790Sfabient	 */
1244203790Sfabient	if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1245203790Sfabient	     (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1246203790Sfabient	    (args.pa_flags & FLAG_DO_TOP)) {
1247145256Sjkoshy		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1248145256Sjkoshy		    args.pa_interval * 1000, NULL);
1249145256Sjkoshy
1250145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1251145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot register kevent for "
1252145256Sjkoshy			    "timer");
1253145256Sjkoshy	}
1254145256Sjkoshy
1255145256Sjkoshy	/* attach PMCs to the target process, starting it if specified */
1256168949Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1257203790Sfabient		pmcstat_create_process();
1258145256Sjkoshy
1259151542Sjkoshy	if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1260151542Sjkoshy		err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1261151542Sjkoshy
1262168949Sjkoshy	/* Attach process pmcs to the target process. */
1263180148Sjkoshy	if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1264169069Sjkoshy		if (SLIST_EMPTY(&args.pa_targets))
1265169069Sjkoshy			errx(EX_DATAERR, "ERROR: No matching target "
1266169069Sjkoshy			    "processes.");
1267183672Sjkoshy		if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1268203790Sfabient			pmcstat_attach_pmcs();
1269168949Sjkoshy
1270169069Sjkoshy		if (pmcstat_kvm) {
1271169069Sjkoshy			kvm_close(pmcstat_kvm);
1272169069Sjkoshy			pmcstat_kvm = NULL;
1273169069Sjkoshy		}
1274169069Sjkoshy	}
1275169069Sjkoshy
1276145256Sjkoshy	/* start the pmcs */
1277203790Sfabient	pmcstat_start_pmcs();
1278145256Sjkoshy
1279145256Sjkoshy	/* start the (commandline) process if needed */
1280147708Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1281168949Sjkoshy		pmcstat_start_process();
1282145256Sjkoshy
1283210794Sfabient	/* initialize logging */
1284210794Sfabient	pmcstat_initialize_logging();
1285147708Sjkoshy
1286145256Sjkoshy	/* Handle SIGINT using the kqueue loop */
1287145256Sjkoshy	sa.sa_handler = SIG_IGN;
1288145256Sjkoshy	sa.sa_flags   = 0;
1289145256Sjkoshy	(void) sigemptyset(&sa.sa_mask);
1290145256Sjkoshy
1291145256Sjkoshy	if (sigaction(SIGINT, &sa, NULL) < 0)
1292145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot install signal handler");
1293145256Sjkoshy
1294145256Sjkoshy	/*
1295203790Sfabient	 * Setup the top mode display.
1296203790Sfabient	 */
1297203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1298203790Sfabient		args.pa_flags &= ~FLAG_DO_PRINT;
1299203790Sfabient
1300203790Sfabient		if (args.pa_toptty) {
1301203790Sfabient			/*
1302203790Sfabient			 * Init ncurses.
1303203790Sfabient			 */
1304203790Sfabient			initscr();
1305203790Sfabient			if(has_colors() == TRUE) {
1306203790Sfabient				args.pa_topcolor = 1;
1307203790Sfabient				start_color();
1308203790Sfabient				use_default_colors();
1309203790Sfabient				pair_content(0, &cf, &cb);
1310203790Sfabient				init_pair(1, COLOR_RED, cb);
1311203790Sfabient				init_pair(2, COLOR_YELLOW, cb);
1312203790Sfabient				init_pair(3, COLOR_GREEN, cb);
1313203790Sfabient			}
1314203790Sfabient			cbreak();
1315203790Sfabient			noecho();
1316203790Sfabient			nonl();
1317203790Sfabient			nodelay(stdscr, 1);
1318203790Sfabient			intrflush(stdscr, FALSE);
1319203790Sfabient			keypad(stdscr, TRUE);
1320203790Sfabient			clear();
1321204783Sfabient			/* Get terminal width / height with ncurses. */
1322204783Sfabient			getmaxyx(stdscr, pmcstat_displayheight, pmcstat_displaywidth);
1323204783Sfabient			pmcstat_displayheight--; pmcstat_displaywidth--;
1324203790Sfabient			atexit(pmcstat_topexit);
1325203790Sfabient		}
1326203790Sfabient	}
1327203790Sfabient
1328203790Sfabient	/*
1329145256Sjkoshy	 * loop till either the target process (if any) exits, or we
1330145256Sjkoshy	 * are killed by a SIGINT.
1331145256Sjkoshy	 */
1332147191Sjkoshy	runstate = PMCSTAT_RUNNING;
1333226514Sfabient	do_print = do_read = 0;
1334145256Sjkoshy	do {
1335145256Sjkoshy		if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1336145256Sjkoshy			if (errno != EINTR)
1337145256Sjkoshy				err(EX_OSERR, "ERROR: kevent failed");
1338145256Sjkoshy			else
1339145256Sjkoshy				continue;
1340145256Sjkoshy		}
1341145256Sjkoshy
1342145256Sjkoshy		if (kev.flags & EV_ERROR)
1343145256Sjkoshy			errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1344145256Sjkoshy
1345145256Sjkoshy		switch (kev.filter) {
1346147191Sjkoshy		case EVFILT_PROC:  /* target has exited */
1347210794Sfabient			runstate = pmcstat_close_log();
1348148688Sjkoshy			do_print = 1;
1349147191Sjkoshy			break;
1350145256Sjkoshy
1351147191Sjkoshy		case EVFILT_READ:  /* log file data is present */
1352210794Sfabient			if (kev.ident == (unsigned)fileno(stdin) &&
1353210794Sfabient			    (args.pa_flags & FLAG_DO_TOP)) {
1354203790Sfabient				if (pmcstat_keypress_log())
1355203790Sfabient					runstate = pmcstat_close_log();
1356226514Sfabient			} else {
1357226514Sfabient				do_read = 0;
1358203790Sfabient				runstate = pmcstat_process_log();
1359226514Sfabient			}
1360145256Sjkoshy			break;
1361145256Sjkoshy
1362145256Sjkoshy		case EVFILT_SIGNAL:
1363147191Sjkoshy			if (kev.ident == SIGCHLD) {
1364147191Sjkoshy				/*
1365147191Sjkoshy				 * The child process sends us a
1366147191Sjkoshy				 * SIGCHLD if its exec() failed.  We
1367147191Sjkoshy				 * wait for it to exit and then exit
1368147191Sjkoshy				 * ourselves.
1369147191Sjkoshy				 */
1370147191Sjkoshy				(void) wait(&c);
1371147191Sjkoshy				runstate = PMCSTAT_FINISHED;
1372147191Sjkoshy			} else if (kev.ident == SIGIO) {
1373147191Sjkoshy				/*
1374147191Sjkoshy				 * We get a SIGIO if a PMC loses all
1375147191Sjkoshy				 * of its targets, or if logfile
1376147191Sjkoshy				 * writes encounter an error.
1377147191Sjkoshy				 */
1378210794Sfabient				runstate = pmcstat_close_log();
1379147191Sjkoshy				do_print = 1; /* print PMCs at exit */
1380147191Sjkoshy			} else if (kev.ident == SIGINT) {
1381147708Sjkoshy				/* Kill the child process if we started it */
1382147708Sjkoshy				if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1383203790Sfabient					pmcstat_kill_process();
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 */
1398226514Sfabient			if ((args.pa_flags & FLAG_DO_TOP) &&
1399226986Sfabient			     pmc_flush_logfile() == 0)
1400226514Sfabient				do_read = 1;
1401147191Sjkoshy			do_print = 1;
1402147191Sjkoshy			break;
1403147191Sjkoshy
1404145256Sjkoshy		}
1405145256Sjkoshy
1406226514Sfabient		if (do_print && !do_read) {
1407203790Sfabient			if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1408203790Sfabient				pmcstat_print_pmcs();
1409203790Sfabient				if (runstate == PMCSTAT_FINISHED && /* final newline */
1410203790Sfabient				    (args.pa_flags & FLAG_DO_PRINT) == 0)
1411203790Sfabient					(void) fprintf(args.pa_printfile, "\n");
1412203790Sfabient			}
1413203790Sfabient			if (args.pa_flags & FLAG_DO_TOP)
1414203790Sfabient				pmcstat_display_log();
1415147191Sjkoshy			do_print = 0;
1416147191Sjkoshy		}
1417145256Sjkoshy
1418147191Sjkoshy	} while (runstate != PMCSTAT_FINISHED);
1419147191Sjkoshy
1420203790Sfabient	if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1421203790Sfabient		pmcstat_topexit();
1422203790Sfabient		args.pa_toptty = 0;
1423203790Sfabient	}
1424203790Sfabient
1425147191Sjkoshy	/* flush any pending log entries */
1426147708Sjkoshy	if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1427226514Sfabient		pmc_close_logfile();
1428147191Sjkoshy
1429203790Sfabient	pmcstat_cleanup();
1430145256Sjkoshy
1431157144Sjkoshy	free(args.pa_kernel);
1432157144Sjkoshy
1433151542Sjkoshy	/* check if the driver lost any samples or events */
1434151542Sjkoshy	if (check_driver_stats) {
1435151542Sjkoshy		if (pmc_get_driver_stats(&ds_end) < 0)
1436151542Sjkoshy			err(EX_OSERR, "ERROR: Cannot retrieve driver "
1437151542Sjkoshy			    "statistics");
1438157144Sjkoshy		if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1439157144Sjkoshy		    args.pa_verbosity > 0)
1440153704Sjkoshy			warnx("WARNING: some samples were dropped.  Please "
1441151542Sjkoshy			    "consider tuning the \"kern.hwpmc.nsamples\" "
1442151542Sjkoshy			    "tunable.");
1443151542Sjkoshy		if (ds_start.pm_buffer_requests_failed !=
1444157144Sjkoshy		    ds_end.pm_buffer_requests_failed &&
1445157144Sjkoshy		    args.pa_verbosity > 0)
1446153704Sjkoshy			warnx("WARNING: some events were discarded.  Please "
1447151542Sjkoshy			    "consider tuning the \"kern.hwpmc.nbuffers\" "
1448151542Sjkoshy			    "tunable.");
1449151542Sjkoshy	}
1450151542Sjkoshy
1451151542Sjkoshy	exit(EX_OK);
1452145256Sjkoshy}
1453