pmcstat.c revision 230350
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 230350 2012-01-20 01:37:56Z eadler $");
33145256Sjkoshy
34224698Sattilio#include <sys/param.h>
35224698Sattilio#include <sys/cpuset.h>
36145256Sjkoshy#include <sys/event.h>
37145256Sjkoshy#include <sys/queue.h>
38147708Sjkoshy#include <sys/socket.h>
39147708Sjkoshy#include <sys/stat.h>
40168949Sjkoshy#include <sys/sysctl.h>
41145256Sjkoshy#include <sys/time.h>
42145256Sjkoshy#include <sys/ttycom.h>
43169069Sjkoshy#include <sys/user.h>
44145256Sjkoshy#include <sys/wait.h>
45145256Sjkoshy
46145256Sjkoshy#include <assert.h>
47203790Sfabient#include <curses.h>
48145256Sjkoshy#include <err.h>
49145256Sjkoshy#include <errno.h>
50145256Sjkoshy#include <fcntl.h>
51169069Sjkoshy#include <kvm.h>
52157144Sjkoshy#include <libgen.h>
53145256Sjkoshy#include <limits.h>
54145256Sjkoshy#include <math.h>
55145256Sjkoshy#include <pmc.h>
56147191Sjkoshy#include <pmclog.h>
57169069Sjkoshy#include <regex.h>
58145256Sjkoshy#include <signal.h>
59145256Sjkoshy#include <stdarg.h>
60147708Sjkoshy#include <stdint.h>
61145256Sjkoshy#include <stdio.h>
62145256Sjkoshy#include <stdlib.h>
63145256Sjkoshy#include <string.h>
64145256Sjkoshy#include <sysexits.h>
65145256Sjkoshy#include <unistd.h>
66145256Sjkoshy
67147708Sjkoshy#include "pmcstat.h"
68147708Sjkoshy
69147191Sjkoshy/*
70147191Sjkoshy * A given invocation of pmcstat(8) can manage multiple PMCs of both
71147191Sjkoshy * the system-wide and per-process variety.  Each of these could be in
72147191Sjkoshy * 'counting mode' or in 'sampling mode'.
73147191Sjkoshy *
74147191Sjkoshy * For 'counting mode' PMCs, pmcstat(8) will periodically issue a
75147191Sjkoshy * pmc_read() at the configured time interval and print out the value
76147191Sjkoshy * of the requested PMCs.
77147191Sjkoshy *
78147191Sjkoshy * For 'sampling mode' PMCs it can log to a file for offline analysis,
79147191Sjkoshy * or can analyse sampling data "on the fly", either by converting
80147191Sjkoshy * samples to printed textual form or by creating gprof(1) compatible
81147191Sjkoshy * profiles, one per program executed.  When creating gprof(1)
82147191Sjkoshy * profiles it can optionally merge entries from multiple processes
83147191Sjkoshy * for a given executable into a single profile file.
84168949Sjkoshy *
85168949Sjkoshy * pmcstat(8) can also execute a command line and attach PMCs to the
86168949Sjkoshy * resulting child process.  The protocol used is as follows:
87168949Sjkoshy *
88168949Sjkoshy * - parent creates a socketpair for two way communication and
89168949Sjkoshy *   fork()s.
90168949Sjkoshy * - subsequently:
91168949Sjkoshy *
92168949Sjkoshy *   /Parent/				/Child/
93168949Sjkoshy *
94168949Sjkoshy *   - Wait for childs token.
95168949Sjkoshy *					- Sends token.
96168949Sjkoshy *					- Awaits signal to start.
97168949Sjkoshy *  - Attaches PMCs to the child's pid
98168949Sjkoshy *    and starts them. Sets up
99168949Sjkoshy *    monitoring for the child.
100168949Sjkoshy *  - Signals child to start.
101228990Suqs *					- Receives signal, attempts exec().
102168949Sjkoshy *
103168949Sjkoshy * After this point normal processing can happen.
104147191Sjkoshy */
105147191Sjkoshy
106147708Sjkoshy/* Globals */
107145256Sjkoshy
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)
159227524Sobrien			errx(EX_USAGE,
160227524Sobrien			    "ERROR: Illegal CPU specification \"%s\".",
161227524Sobrien			    cpuspec);
162224698Sattilio		CPU_SET(cpu, cpumask);
163224698Sattilio		s = end + strspn(end, ", \t");
164224698Sattilio	} while (*s);
165224698Sattilio}
166224698Sattilio
167168949Sjkoshyvoid
168203790Sfabientpmcstat_attach_pmcs(void)
169168949Sjkoshy{
170168949Sjkoshy	struct pmcstat_ev *ev;
171169069Sjkoshy	struct pmcstat_target *pt;
172169069Sjkoshy	int count;
173145256Sjkoshy
174169069Sjkoshy	/* Attach all process PMCs to target processes. */
175169069Sjkoshy	count = 0;
176203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
177169069Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
178169069Sjkoshy			continue;
179203790Sfabient		SLIST_FOREACH(pt, &args.pa_targets, pt_next)
180169069Sjkoshy			if (pmc_attach(ev->ev_pmcid, pt->pt_pid) == 0)
181169069Sjkoshy				count++;
182169069Sjkoshy			else if (errno != ESRCH)
183227524Sobrien				err(EX_OSERR,
184227524Sobrien"ERROR: cannot attach pmc \"%s\" to process %d",
185227524Sobrien				    ev->ev_name, (int)pt->pt_pid);
186169069Sjkoshy	}
187168949Sjkoshy
188169069Sjkoshy	if (count == 0)
189169069Sjkoshy		errx(EX_DATAERR, "ERROR: No processes were attached to.");
190168949Sjkoshy}
191168949Sjkoshy
192168949Sjkoshy
193145256Sjkoshyvoid
194203790Sfabientpmcstat_cleanup(void)
195145256Sjkoshy{
196145256Sjkoshy	struct pmcstat_ev *ev, *tmp;
197145256Sjkoshy
198145256Sjkoshy	/* release allocated PMCs. */
199203790Sfabient	STAILQ_FOREACH_SAFE(ev, &args.pa_events, ev_next, tmp)
200145256Sjkoshy	    if (ev->ev_pmcid != PMC_ID_INVALID) {
201185079Sjkoshy		if (pmc_stop(ev->ev_pmcid) < 0)
202227524Sobrien			err(EX_OSERR, "ERROR: cannot stop pmc 0x%x \"%s\"",
203227524Sobrien			    ev->ev_pmcid, ev->ev_name);
204145256Sjkoshy		if (pmc_release(ev->ev_pmcid) < 0)
205227524Sobrien			err(EX_OSERR, "ERROR: cannot release pmc 0x%x \"%s\"",
206227524Sobrien			    ev->ev_pmcid, ev->ev_name);
207145256Sjkoshy		free(ev->ev_name);
208145256Sjkoshy		free(ev->ev_spec);
209203790Sfabient		STAILQ_REMOVE(&args.pa_events, ev, pmcstat_ev, ev_next);
210145256Sjkoshy		free(ev);
211145256Sjkoshy	    }
212147191Sjkoshy
213147863Sjkoshy	/* de-configure the log file if present. */
214203790Sfabient	if (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
215147863Sjkoshy		(void) pmc_configure_logfile(-1);
216147863Sjkoshy
217203790Sfabient	if (args.pa_logparser) {
218203790Sfabient		pmclog_close(args.pa_logparser);
219203790Sfabient		args.pa_logparser = NULL;
220147191Sjkoshy	}
221147708Sjkoshy
222210794Sfabient	pmcstat_shutdown_logging();
223145256Sjkoshy}
224145256Sjkoshy
225145256Sjkoshyvoid
226203790Sfabientpmcstat_create_process(void)
227168949Sjkoshy{
228168949Sjkoshy	char token;
229169069Sjkoshy	pid_t pid;
230168949Sjkoshy	struct kevent kev;
231169069Sjkoshy	struct pmcstat_target *pt;
232168949Sjkoshy
233168949Sjkoshy	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pmcstat_sockpair) < 0)
234168949Sjkoshy		err(EX_OSERR, "ERROR: cannot create socket pair");
235168949Sjkoshy
236169069Sjkoshy	switch (pid = fork()) {
237168949Sjkoshy	case -1:
238168949Sjkoshy		err(EX_OSERR, "ERROR: cannot fork");
239168949Sjkoshy		/*NOTREACHED*/
240168949Sjkoshy
241168949Sjkoshy	case 0:		/* child */
242168949Sjkoshy		(void) close(pmcstat_sockpair[PARENTSOCKET]);
243168949Sjkoshy
244168949Sjkoshy		/* Write a token to tell our parent we've started executing. */
245168949Sjkoshy		if (write(pmcstat_sockpair[CHILDSOCKET], "+", 1) != 1)
246168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot write token");
247168949Sjkoshy
248168949Sjkoshy		/* Wait for our parent to signal us to start. */
249168949Sjkoshy		if (read(pmcstat_sockpair[CHILDSOCKET], &token, 1) < 0)
250168949Sjkoshy			err(EX_OSERR, "ERROR (child): cannot read token");
251168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
252168949Sjkoshy
253168949Sjkoshy		/* exec() the program requested */
254203790Sfabient		execvp(*args.pa_argv, args.pa_argv);
255168949Sjkoshy		/* and if that fails, notify the parent */
256168949Sjkoshy		kill(getppid(), SIGCHLD);
257203790Sfabient		err(EX_OSERR, "ERROR: execvp \"%s\" failed", *args.pa_argv);
258168949Sjkoshy		/*NOTREACHED*/
259168949Sjkoshy
260168949Sjkoshy	default:	/* parent */
261168949Sjkoshy		(void) close(pmcstat_sockpair[CHILDSOCKET]);
262168949Sjkoshy		break;
263168949Sjkoshy	}
264168949Sjkoshy
265168949Sjkoshy	/* Ask to be notified via a kevent when the target process exits. */
266169069Sjkoshy	EV_SET(&kev, pid, EVFILT_PROC, EV_ADD|EV_ONESHOT, NOTE_EXIT, 0,
267168949Sjkoshy	    NULL);
268168949Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
269169069Sjkoshy		err(EX_OSERR, "ERROR: cannot monitor child process %d", pid);
270168949Sjkoshy
271169069Sjkoshy	if ((pt = malloc(sizeof(*pt))) == NULL)
272169069Sjkoshy		errx(EX_SOFTWARE, "ERROR: Out of memory.");
273169069Sjkoshy
274169069Sjkoshy	pt->pt_pid = pid;
275203790Sfabient	SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
276169069Sjkoshy
277168949Sjkoshy	/* Wait for the child to signal that its ready to go. */
278168949Sjkoshy	if (read(pmcstat_sockpair[PARENTSOCKET], &token, 1) < 0)
279168949Sjkoshy		err(EX_OSERR, "ERROR (parent): cannot read token");
280168949Sjkoshy
281168949Sjkoshy	return;
282168949Sjkoshy}
283168949Sjkoshy
284169069Sjkoshyvoid
285203790Sfabientpmcstat_find_targets(const char *spec)
286169069Sjkoshy{
287169069Sjkoshy	int n, nproc, pid, rv;
288169069Sjkoshy	struct pmcstat_target *pt;
289169069Sjkoshy	char errbuf[_POSIX2_LINE_MAX], *end;
290169069Sjkoshy	static struct kinfo_proc *kp;
291169069Sjkoshy	regex_t reg;
292169069Sjkoshy	regmatch_t regmatch;
293169069Sjkoshy
294169069Sjkoshy	/* First check if we've been given a process id. */
295169069Sjkoshy      	pid = strtol(spec, &end, 0);
296169069Sjkoshy	if (end != spec && pid >= 0) {
297169069Sjkoshy		if ((pt = malloc(sizeof(*pt))) == NULL)
298169069Sjkoshy			goto outofmemory;
299169069Sjkoshy		pt->pt_pid = pid;
300203790Sfabient		SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
301169069Sjkoshy		return;
302169069Sjkoshy	}
303169069Sjkoshy
304169069Sjkoshy	/* Otherwise treat arg as a regular expression naming processes. */
305169069Sjkoshy	if (pmcstat_kvm == NULL) {
306169069Sjkoshy		if ((pmcstat_kvm = kvm_openfiles(NULL, "/dev/null", NULL, 0,
307169069Sjkoshy		    errbuf)) == NULL)
308169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot open kernel \"%s\"",
309169069Sjkoshy			    errbuf);
310169069Sjkoshy		if ((pmcstat_plist = kvm_getprocs(pmcstat_kvm, KERN_PROC_PROC,
311169069Sjkoshy		    0, &nproc)) == NULL)
312169069Sjkoshy			err(EX_OSERR, "ERROR: Cannot get process list: %s",
313169069Sjkoshy			    kvm_geterr(pmcstat_kvm));
314208858Sfabient	} else
315208858Sfabient		nproc = 0;
316169069Sjkoshy
317169069Sjkoshy	if ((rv = regcomp(&reg, spec, REG_EXTENDED|REG_NOSUB)) != 0) {
318169069Sjkoshy		regerror(rv, &reg, errbuf, sizeof(errbuf));
319169069Sjkoshy		err(EX_DATAERR, "ERROR: Failed to compile regex \"%s\": %s",
320169069Sjkoshy		    spec, errbuf);
321169069Sjkoshy	}
322169069Sjkoshy
323169069Sjkoshy	for (n = 0, kp = pmcstat_plist; n < nproc; n++, kp++) {
324169069Sjkoshy		if ((rv = regexec(&reg, kp->ki_comm, 1, &regmatch, 0)) == 0) {
325169069Sjkoshy			if ((pt = malloc(sizeof(*pt))) == NULL)
326169069Sjkoshy				goto outofmemory;
327169069Sjkoshy			pt->pt_pid = kp->ki_pid;
328203790Sfabient			SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
329169069Sjkoshy		} else if (rv != REG_NOMATCH) {
330169069Sjkoshy			regerror(rv, &reg, errbuf, sizeof(errbuf));
331169069Sjkoshy			errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s",
332169069Sjkoshy			    errbuf);
333169069Sjkoshy		}
334169069Sjkoshy	}
335169069Sjkoshy
336169069Sjkoshy	regfree(&reg);
337169069Sjkoshy
338169069Sjkoshy	return;
339169069Sjkoshy
340169069Sjkoshy outofmemory:
341169069Sjkoshy	errx(EX_SOFTWARE, "Out of memory.");
342169069Sjkoshy	/*NOTREACHED*/
343169069Sjkoshy}
344169069Sjkoshy
345168949Sjkoshyvoid
346203790Sfabientpmcstat_kill_process(void)
347169069Sjkoshy{
348169069Sjkoshy	struct pmcstat_target *pt;
349169069Sjkoshy
350203790Sfabient	assert(args.pa_flags & FLAG_HAS_COMMANDLINE);
351169069Sjkoshy
352169069Sjkoshy	/*
353169069Sjkoshy	 * If a command line was specified, it would be the very first
354169069Sjkoshy	 * in the list, before any other processes specified by -t.
355169069Sjkoshy	 */
356203790Sfabient	pt = SLIST_FIRST(&args.pa_targets);
357169069Sjkoshy	assert(pt != NULL);
358169069Sjkoshy
359169069Sjkoshy	if (kill(pt->pt_pid, SIGINT) != 0)
360169069Sjkoshy		err(EX_OSERR, "ERROR: cannot signal child process");
361169069Sjkoshy}
362169069Sjkoshy
363169069Sjkoshyvoid
364203790Sfabientpmcstat_start_pmcs(void)
365145256Sjkoshy{
366145256Sjkoshy	struct pmcstat_ev *ev;
367145256Sjkoshy
368169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
369145256Sjkoshy
370145256Sjkoshy	    assert(ev->ev_pmcid != PMC_ID_INVALID);
371145256Sjkoshy
372145256Sjkoshy	    if (pmc_start(ev->ev_pmcid) < 0) {
373147191Sjkoshy	        warn("ERROR: Cannot start pmc 0x%x \"%s\"",
374145256Sjkoshy		    ev->ev_pmcid, ev->ev_name);
375203790Sfabient		pmcstat_cleanup();
376147191Sjkoshy		exit(EX_OSERR);
377145256Sjkoshy	    }
378145256Sjkoshy	}
379145256Sjkoshy
380145256Sjkoshy}
381145256Sjkoshy
382145256Sjkoshyvoid
383203790Sfabientpmcstat_print_headers(void)
384145256Sjkoshy{
385145256Sjkoshy	struct pmcstat_ev *ev;
386168949Sjkoshy	int c, w;
387145256Sjkoshy
388203790Sfabient	(void) fprintf(args.pa_printfile, PRINT_HEADER_PREFIX);
389145256Sjkoshy
390203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
391145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
392145256Sjkoshy			continue;
393145256Sjkoshy
394145256Sjkoshy		c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p';
395145256Sjkoshy
396168949Sjkoshy		if (ev->ev_fieldskip != 0)
397203790Sfabient			(void) fprintf(args.pa_printfile, "%*s",
398168949Sjkoshy			    ev->ev_fieldskip, "");
399168949Sjkoshy		w = ev->ev_fieldwidth - ev->ev_fieldskip - 2;
400168949Sjkoshy
401168949Sjkoshy		if (c == 's')
402203790Sfabient			(void) fprintf(args.pa_printfile, "s/%02d/%-*s ",
403168949Sjkoshy			    ev->ev_cpu, w-3, ev->ev_name);
404168949Sjkoshy		else
405203790Sfabient			(void) fprintf(args.pa_printfile, "p/%*s ", w,
406145256Sjkoshy			    ev->ev_name);
407145256Sjkoshy	}
408145256Sjkoshy
409203790Sfabient	(void) fflush(args.pa_printfile);
410145256Sjkoshy}
411145256Sjkoshy
412145256Sjkoshyvoid
413203790Sfabientpmcstat_print_counters(void)
414145256Sjkoshy{
415145256Sjkoshy	int extra_width;
416145256Sjkoshy	struct pmcstat_ev *ev;
417145256Sjkoshy	pmc_value_t value;
418145256Sjkoshy
419145256Sjkoshy	extra_width = sizeof(PRINT_HEADER_PREFIX) - 1;
420145256Sjkoshy
421203790Sfabient	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
422145256Sjkoshy
423145256Sjkoshy		/* skip sampling mode counters */
424145256Sjkoshy		if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
425145256Sjkoshy			continue;
426145256Sjkoshy
427145256Sjkoshy		if (pmc_read(ev->ev_pmcid, &value) < 0)
428227524Sobrien			err(EX_OSERR, "ERROR: Cannot read pmc \"%s\"",
429227524Sobrien			    ev->ev_name);
430145256Sjkoshy
431203790Sfabient		(void) fprintf(args.pa_printfile, "%*ju ",
432147708Sjkoshy		    ev->ev_fieldwidth + extra_width,
433147708Sjkoshy		    (uintmax_t) ev->ev_cumulative ? value :
434147708Sjkoshy		    (value - ev->ev_saved));
435147708Sjkoshy
436145256Sjkoshy		if (ev->ev_cumulative == 0)
437145256Sjkoshy			ev->ev_saved = value;
438145256Sjkoshy		extra_width = 0;
439145256Sjkoshy	}
440145256Sjkoshy
441203790Sfabient	(void) fflush(args.pa_printfile);
442145256Sjkoshy}
443145256Sjkoshy
444145256Sjkoshy/*
445145256Sjkoshy * Print output
446145256Sjkoshy */
447145256Sjkoshy
448145256Sjkoshyvoid
449203790Sfabientpmcstat_print_pmcs(void)
450145256Sjkoshy{
451145256Sjkoshy	static int linecount = 0;
452145256Sjkoshy
453147708Sjkoshy	/* check if we need to print a header line */
454145256Sjkoshy	if (++linecount > pmcstat_displayheight) {
455203790Sfabient		(void) fprintf(args.pa_printfile, "\n");
456145256Sjkoshy		linecount = 1;
457145256Sjkoshy	}
458145256Sjkoshy	if (linecount == 1)
459203790Sfabient		pmcstat_print_headers();
460203790Sfabient	(void) fprintf(args.pa_printfile, "\n");
461145256Sjkoshy
462203790Sfabient	pmcstat_print_counters();
463145256Sjkoshy
464145256Sjkoshy	return;
465145256Sjkoshy}
466145256Sjkoshy
467145256Sjkoshy/*
468145256Sjkoshy * Do process profiling
469145256Sjkoshy *
470145256Sjkoshy * If a pid was specified, attach each allocated PMC to the target
471145256Sjkoshy * process.  Otherwise, fork a child and attach the PMCs to the child,
472145256Sjkoshy * and have the child exec() the target program.
473145256Sjkoshy */
474145256Sjkoshy
475145256Sjkoshyvoid
476168949Sjkoshypmcstat_start_process(void)
477145256Sjkoshy{
478168949Sjkoshy	/* Signal the child to proceed. */
479168949Sjkoshy	if (write(pmcstat_sockpair[PARENTSOCKET], "!", 1) != 1)
480168949Sjkoshy		err(EX_OSERR, "ERROR (parent): write of token failed");
481145256Sjkoshy
482168949Sjkoshy	(void) close(pmcstat_sockpair[PARENTSOCKET]);
483145256Sjkoshy}
484145256Sjkoshy
485145256Sjkoshyvoid
486145256Sjkoshypmcstat_show_usage(void)
487145256Sjkoshy{
488145256Sjkoshy	errx(EX_USAGE,
489145256Sjkoshy	    "[options] [commandline]\n"
490145256Sjkoshy	    "\t Measure process and/or system performance using hardware\n"
491145256Sjkoshy	    "\t performance monitoring counters.\n"
492145256Sjkoshy	    "\t Options include:\n"
493147191Sjkoshy	    "\t -C\t\t (toggle) show cumulative counts\n"
494147191Sjkoshy	    "\t -D path\t create profiles in directory \"path\"\n"
495147191Sjkoshy	    "\t -E\t\t (toggle) show counts at process exit\n"
496203790Sfabient	    "\t -F file\t write a system-wide callgraph (Kcachegrind format)"
497203790Sfabient		" to \"file\"\n"
498174396Sjkoshy	    "\t -G file\t write a system-wide callgraph to \"file\"\n"
499157144Sjkoshy	    "\t -M file\t print executable/gmon file map to \"file\"\n"
500174396Sjkoshy	    "\t -N\t\t (toggle) capture callchains\n"
501147191Sjkoshy	    "\t -O file\t send log output to \"file\"\n"
502147191Sjkoshy	    "\t -P spec\t allocate a process-private sampling PMC\n"
503147191Sjkoshy	    "\t -R file\t read events from \"file\"\n"
504147191Sjkoshy	    "\t -S spec\t allocate a system-wide sampling PMC\n"
505203790Sfabient	    "\t -T\t\t start in top mode\n"
506147191Sjkoshy	    "\t -W\t\t (toggle) show counts per context switch\n"
507168949Sjkoshy	    "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n"
508147191Sjkoshy	    "\t -d\t\t (toggle) track descendants\n"
509203790Sfabient	    "\t -f spec\t pass \"spec\" to as plugin option\n"
510147191Sjkoshy	    "\t -g\t\t produce gprof(1) compatible profiles\n"
511162804Sru	    "\t -k dir\t\t set the path to the kernel\n"
512145256Sjkoshy	    "\t -n rate\t set sampling rate\n"
513145256Sjkoshy	    "\t -o file\t send print output to \"file\"\n"
514147191Sjkoshy	    "\t -p spec\t allocate a process-private counting PMC\n"
515157144Sjkoshy	    "\t -q\t\t suppress verbosity\n"
516157144Sjkoshy	    "\t -r fsroot\t specify FS root directory\n"
517147191Sjkoshy	    "\t -s spec\t allocate a system-wide counting PMC\n"
518183186Sjkoshy	    "\t -t process-spec attach to running processes matching "
519183186Sjkoshy		"\"process-spec\"\n"
520157144Sjkoshy	    "\t -v\t\t increase verbosity\n"
521174396Sjkoshy	    "\t -w secs\t set printing time interval\n"
522174396Sjkoshy	    "\t -z depth\t limit callchain display depth"
523145256Sjkoshy	);
524145256Sjkoshy}
525145256Sjkoshy
526145256Sjkoshy/*
527203790Sfabient * At exit handler for top mode
528203790Sfabient */
529203790Sfabient
530203790Sfabientvoid
531203790Sfabientpmcstat_topexit(void)
532203790Sfabient{
533203790Sfabient	if (!args.pa_toptty)
534203790Sfabient		return;
535203790Sfabient
536203790Sfabient	/*
537203790Sfabient	 * Shutdown ncurses.
538203790Sfabient	 */
539203790Sfabient	clrtoeol();
540203790Sfabient	refresh();
541203790Sfabient	endwin();
542203790Sfabient}
543203790Sfabient
544203790Sfabient/*
545145256Sjkoshy * Main
546145256Sjkoshy */
547145256Sjkoshy
548145256Sjkoshyint
549145256Sjkoshymain(int argc, char **argv)
550145256Sjkoshy{
551224698Sattilio	cpuset_t cpumask;
552145256Sjkoshy	double interval;
553224698Sattilio	int hcpu, option, npmc, ncpu;
554230350Seadler	int c, check_driver_stats, current_sampling_count;
555174396Sjkoshy	int do_callchain, do_descendants, do_logproccsw, do_logprocexit;
556226514Sfabient	int do_print, do_read;
557168949Sjkoshy	size_t dummy;
558174396Sjkoshy	int graphdepth;
559210794Sfabient	int pipefd[2], rfd;
560147191Sjkoshy	int use_cumulative_counts;
561203790Sfabient	short cf, cb;
562157144Sjkoshy	char *end, *tmp;
563174396Sjkoshy	const char *errmsg, *graphfilename;
564147191Sjkoshy	enum pmcstat_state runstate;
565151542Sjkoshy	struct pmc_driverstats ds_start, ds_end;
566145256Sjkoshy	struct pmcstat_ev *ev;
567145256Sjkoshy	struct sigaction sa;
568145256Sjkoshy	struct kevent kev;
569145256Sjkoshy	struct winsize ws;
570147708Sjkoshy	struct stat sb;
571157144Sjkoshy	char buffer[PATH_MAX];
572145256Sjkoshy
573151542Sjkoshy	check_driver_stats      = 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))
644227524Sobrien				errx(EX_USAGE,
645227524Sobrien				    "ERROR: \"%s\" is not a directory.",
646227524Sobrien				    optarg);
647147708Sjkoshy			args.pa_samplesdir = optarg;
648147708Sjkoshy			args.pa_flags     |= FLAG_HAS_SAMPLESDIR;
649147708Sjkoshy			args.pa_required  |= FLAG_DO_GPROF;
650147708Sjkoshy			break;
651147708Sjkoshy
652145256Sjkoshy		case 'd':	/* toggle descendents */
653145256Sjkoshy			do_descendants = !do_descendants;
654147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
655145256Sjkoshy			break;
656145256Sjkoshy
657203790Sfabient		case 'F':	/* produce a system-wide calltree */
658203790Sfabient			args.pa_flags |= FLAG_DO_CALLGRAPHS;
659203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLTREE;
660203790Sfabient			graphfilename = optarg;
661203790Sfabient			break;
662203790Sfabient
663203790Sfabient		case 'f':	/* plugins options */
664203790Sfabient			if (args.pa_plugin == PMCSTAT_PL_NONE)
665203790Sfabient				err(EX_USAGE, "ERROR: Need -g/-G/-m/-T.");
666203790Sfabient			pmcstat_pluginconfigure_log(optarg);
667203790Sfabient			break;
668203790Sfabient
669174396Sjkoshy		case 'G':	/* produce a system-wide callgraph */
670174396Sjkoshy			args.pa_flags |= FLAG_DO_CALLGRAPHS;
671203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
672174396Sjkoshy			graphfilename = optarg;
673174396Sjkoshy			break;
674174396Sjkoshy
675147191Sjkoshy		case 'g':	/* produce gprof compatible profiles */
676147191Sjkoshy			args.pa_flags |= FLAG_DO_GPROF;
677203790Sfabient			args.pa_pplugin = PMCSTAT_PL_CALLGRAPH;
678203790Sfabient			args.pa_plugin	= PMCSTAT_PL_GPROF;
679147191Sjkoshy			break;
680147191Sjkoshy
681147708Sjkoshy		case 'k':	/* pathname to the kernel */
682157144Sjkoshy			free(args.pa_kernel);
683157144Sjkoshy			args.pa_kernel = strdup(optarg);
684174396Sjkoshy			args.pa_required |= FLAG_DO_ANALYSIS;
685147708Sjkoshy			args.pa_flags    |= FLAG_HAS_KERNELPATH;
686147191Sjkoshy			break;
687147191Sjkoshy
688185322Sattilio		case 'm':
689203790Sfabient			args.pa_flags |= FLAG_DO_ANNOTATE;
690203790Sfabient			args.pa_plugin = PMCSTAT_PL_ANNOTATE;
691203790Sfabient			graphfilename  = optarg;
692185322Sattilio			break;
693185322Sattilio
694147191Sjkoshy		case 'E':	/* log process exit */
695147191Sjkoshy			do_logprocexit = !do_logprocexit;
696147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
697147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
698147191Sjkoshy			break;
699147191Sjkoshy
700157144Sjkoshy		case 'M':	/* mapfile */
701157144Sjkoshy			args.pa_mapfilename = optarg;
702157144Sjkoshy			break;
703157144Sjkoshy
704174396Sjkoshy		case 'N':
705174396Sjkoshy			do_callchain = !do_callchain;
706174396Sjkoshy			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
707174396Sjkoshy			break;
708174396Sjkoshy
709145256Sjkoshy		case 'p':	/* process virtual counting PMC */
710145256Sjkoshy		case 's':	/* system-wide counting PMC */
711145256Sjkoshy		case 'P':	/* process virtual sampling PMC */
712145256Sjkoshy		case 'S':	/* system-wide sampling PMC */
713145256Sjkoshy			if ((ev = malloc(sizeof(*ev))) == NULL)
714147191Sjkoshy				errx(EX_SOFTWARE, "ERROR: Out of memory.");
715145256Sjkoshy
716145256Sjkoshy			switch (option) {
717145256Sjkoshy			case 'p': ev->ev_mode = PMC_MODE_TC; break;
718145256Sjkoshy			case 's': ev->ev_mode = PMC_MODE_SC; break;
719145256Sjkoshy			case 'P': ev->ev_mode = PMC_MODE_TS; break;
720145256Sjkoshy			case 'S': ev->ev_mode = PMC_MODE_SS; break;
721145256Sjkoshy			}
722145256Sjkoshy
723147191Sjkoshy			if (option == 'P' || option == 'p') {
724147191Sjkoshy				args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
725147708Sjkoshy				args.pa_required |= (FLAG_HAS_COMMANDLINE |
726169069Sjkoshy				    FLAG_HAS_TARGET);
727147191Sjkoshy			}
728145256Sjkoshy
729147191Sjkoshy			if (option == 'P' || option == 'S') {
730147191Sjkoshy				args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
731147708Sjkoshy				args.pa_required |= (FLAG_HAS_PIPE |
732147708Sjkoshy				    FLAG_HAS_OUTPUT_LOGFILE);
733147191Sjkoshy			}
734145256Sjkoshy
735145256Sjkoshy			if (option == 'p' || option == 's')
736147191Sjkoshy				args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
737145256Sjkoshy
738147191Sjkoshy			if (option == 's' || option == 'S')
739147191Sjkoshy				args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
740147191Sjkoshy
741145256Sjkoshy			ev->ev_spec  = strdup(optarg);
742145256Sjkoshy
743145256Sjkoshy			if (option == 'S' || option == 'P')
744145256Sjkoshy				ev->ev_count = current_sampling_count;
745145256Sjkoshy			else
746145256Sjkoshy				ev->ev_count = -1;
747145256Sjkoshy
748224698Sattilio			if (option == 'S' || option == 's') {
749224698Sattilio				hcpu = sizeof(cpumask) * NBBY;
750224698Sattilio				for (hcpu--; hcpu >= 0; hcpu--)
751224698Sattilio					if (CPU_ISSET(hcpu, &cpumask))
752224698Sattilio						break;
753224698Sattilio				ev->ev_cpu = hcpu;
754224698Sattilio			} else
755145256Sjkoshy				ev->ev_cpu = PMC_CPU_ANY;
756145256Sjkoshy
757147191Sjkoshy			ev->ev_flags = 0;
758174396Sjkoshy			if (do_callchain)
759174396Sjkoshy				ev->ev_flags |= PMC_F_CALLCHAIN;
760147191Sjkoshy			if (do_descendants)
761147191Sjkoshy				ev->ev_flags |= PMC_F_DESCENDANTS;
762147191Sjkoshy			if (do_logprocexit)
763147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCEXIT;
764147191Sjkoshy			if (do_logproccsw)
765147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCCSW;
766147191Sjkoshy
767145256Sjkoshy			ev->ev_cumulative  = use_cumulative_counts;
768145256Sjkoshy
769145256Sjkoshy			ev->ev_saved = 0LL;
770145256Sjkoshy			ev->ev_pmcid = PMC_ID_INVALID;
771145256Sjkoshy
772145256Sjkoshy			/* extract event name */
773145256Sjkoshy			c = strcspn(optarg, ", \t");
774145256Sjkoshy			ev->ev_name = malloc(c + 1);
775145256Sjkoshy			(void) strncpy(ev->ev_name, optarg, c);
776145256Sjkoshy			*(ev->ev_name + c) = '\0';
777145256Sjkoshy
778169069Sjkoshy			STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
779145256Sjkoshy
780224698Sattilio			if (option == 's' || option == 'S') {
781224698Sattilio				hcpu = CPU_ISSET(ev->ev_cpu, &cpumask);
782224698Sattilio				CPU_CLR(ev->ev_cpu, &cpumask);
783224698Sattilio				pmcstat_clone_event_descriptor(ev, &cpumask);
784224698Sattilio				if (hcpu != 0)
785224698Sattilio					CPU_SET(ev->ev_cpu, &cpumask);
786224698Sattilio			}
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 */
800226986Sfabient			if (args.pa_printfile != NULL &&
801226986Sfabient			    args.pa_printfile != stdout &&
802226986Sfabient			    args.pa_printfile != stderr)
803147708Sjkoshy				(void) fclose(args.pa_printfile);
804147708Sjkoshy			if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
805227524Sobrien				errx(EX_OSERR,
806227524Sobrien				    "ERROR: cannot open \"%s\" for writing.",
807227524Sobrien				    optarg);
808147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
809147191Sjkoshy			break;
810145256Sjkoshy
811145256Sjkoshy		case 'O':	/* sampling output */
812147708Sjkoshy			if (args.pa_outputpath)
813227524Sobrien				errx(EX_USAGE,
814227524Sobrien"ERROR: option -O may only be specified once.");
815147708Sjkoshy			args.pa_outputpath = optarg;
816147708Sjkoshy			args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
817145256Sjkoshy			break;
818145256Sjkoshy
819157144Sjkoshy		case 'q':	/* quiet mode */
820157144Sjkoshy			args.pa_verbosity = 0;
821157144Sjkoshy			break;
822157144Sjkoshy
823157144Sjkoshy		case 'r':	/* root FS path */
824157144Sjkoshy			args.pa_fsroot = optarg;
825157144Sjkoshy			break;
826157144Sjkoshy
827147708Sjkoshy		case 'R':	/* read an existing log file */
828174396Sjkoshy			if (args.pa_inputpath != NULL)
829227524Sobrien				errx(EX_USAGE,
830227524Sobrien"ERROR: option -R may only be specified once.");
831147708Sjkoshy			args.pa_inputpath = optarg;
832147708Sjkoshy			if (args.pa_printfile == stderr)
833147708Sjkoshy				args.pa_printfile = stdout;
834147708Sjkoshy			args.pa_flags |= FLAG_READ_LOGFILE;
835147708Sjkoshy			break;
836147708Sjkoshy
837169069Sjkoshy		case 't':	/* target pid or process name */
838203790Sfabient			pmcstat_find_targets(optarg);
839145256Sjkoshy
840169069Sjkoshy			args.pa_flags |= FLAG_HAS_TARGET;
841147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
842145256Sjkoshy			break;
843145256Sjkoshy
844203790Sfabient		case 'T':	/* top mode */
845203790Sfabient			args.pa_flags |= FLAG_DO_TOP;
846203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
847203790Sfabient			args.pa_ctdumpinstr = 0;
848203790Sfabient			args.pa_mergepmc = 1;
849203790Sfabient			if (args.pa_printfile == stderr)
850203790Sfabient				args.pa_printfile = stdout;
851203790Sfabient			break;
852203790Sfabient
853157144Sjkoshy		case 'v':	/* verbose */
854157144Sjkoshy			args.pa_verbosity++;
855157144Sjkoshy			break;
856157144Sjkoshy
857145256Sjkoshy		case 'w':	/* wait interval */
858145256Sjkoshy			interval = strtod(optarg, &end);
859145256Sjkoshy			if (*end != '\0' || interval <= 0)
860227524Sobrien				errx(EX_USAGE,
861227524Sobrien"ERROR: Illegal wait interval value \"%s\".",
862227524Sobrien				    optarg);
863145256Sjkoshy			args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
864145256Sjkoshy			args.pa_interval = interval;
865147191Sjkoshy			break;
866145256Sjkoshy
867147191Sjkoshy		case 'W':	/* toggle LOG_CSW */
868147191Sjkoshy			do_logproccsw = !do_logproccsw;
869147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
870147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
871145256Sjkoshy			break;
872145256Sjkoshy
873174396Sjkoshy		case 'z':
874174396Sjkoshy			graphdepth = strtod(optarg, &end);
875174396Sjkoshy			if (*end != '\0' || graphdepth <= 0)
876227524Sobrien				errx(EX_USAGE,
877227524Sobrien				    "ERROR: Illegal callchain depth \"%s\".",
878227524Sobrien				    optarg);
879174396Sjkoshy			args.pa_graphdepth = graphdepth;
880174396Sjkoshy			args.pa_required |= FLAG_DO_CALLGRAPHS;
881174396Sjkoshy			break;
882174396Sjkoshy
883145256Sjkoshy		case '?':
884145256Sjkoshy		default:
885145256Sjkoshy			pmcstat_show_usage();
886145256Sjkoshy			break;
887145256Sjkoshy
888145256Sjkoshy		}
889145256Sjkoshy
890145256Sjkoshy	args.pa_argc = (argc -= optind);
891145256Sjkoshy	args.pa_argv = (argv += optind);
892145256Sjkoshy
893210797Sfabient	/* If we read from logfile and no specified CPU mask use
894210797Sfabient	 * the maximum CPU count.
895210797Sfabient	 */
896210797Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) &&
897210797Sfabient	    (args.pa_flags & FLAGS_HAS_CPUMASK) == 0)
898224698Sattilio		CPU_FILL(&cpumask);
899210797Sfabient
900174396Sjkoshy	args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
901174396Sjkoshy
902147708Sjkoshy	if (argc)	/* command line present */
903147708Sjkoshy		args.pa_flags |= FLAG_HAS_COMMANDLINE;
904145256Sjkoshy
905185322Sattilio	if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
906203790Sfabient	    FLAG_DO_ANNOTATE | FLAG_DO_TOP))
907174396Sjkoshy		args.pa_flags |= FLAG_DO_ANALYSIS;
908174396Sjkoshy
909145256Sjkoshy	/*
910145256Sjkoshy	 * Check invocation syntax.
911145256Sjkoshy	 */
912145256Sjkoshy
913147708Sjkoshy	/* disallow -O and -R together */
914147708Sjkoshy	if (args.pa_outputpath && args.pa_inputpath)
915227524Sobrien		errx(EX_USAGE,
916227524Sobrien		    "ERROR: options -O and -R are mutually exclusive.");
917147708Sjkoshy
918185322Sattilio	/* -m option is allowed with -R only. */
919203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
920185322Sattilio		errx(EX_USAGE, "ERROR: option -m requires an input file");
921185322Sattilio
922185322Sattilio	/* -m option is not allowed combined with -g or -G. */
923203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE &&
924185322Sattilio	    args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
925227524Sobrien		errx(EX_USAGE,
926227524Sobrien		    "ERROR: option -m and -g | -G are mutually exclusive");
927185322Sattilio
928147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
929147191Sjkoshy		errmsg = NULL;
930147708Sjkoshy		if (args.pa_flags & FLAG_HAS_COMMANDLINE)
931147191Sjkoshy			errmsg = "a command line specification";
932169069Sjkoshy		else if (args.pa_flags & FLAG_HAS_TARGET)
933147191Sjkoshy			errmsg = "option -t";
934169069Sjkoshy		else if (!STAILQ_EMPTY(&args.pa_events))
935147191Sjkoshy			errmsg = "a PMC event specification";
936147191Sjkoshy		if (errmsg)
937227524Sobrien			errx(EX_USAGE,
938227524Sobrien			    "ERROR: option -R may not be used with %s.",
939227524Sobrien			    errmsg);
940169069Sjkoshy	} else if (STAILQ_EMPTY(&args.pa_events))
941147708Sjkoshy		/* All other uses require a PMC spec. */
942145256Sjkoshy		pmcstat_show_usage();
943145256Sjkoshy
944147191Sjkoshy	/* check for -t pid without a process PMC spec */
945169069Sjkoshy	if ((args.pa_required & FLAG_HAS_TARGET) &&
946147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
947227524Sobrien		errx(EX_USAGE,
948227524Sobrien"ERROR: option -t requires a process mode PMC to be specified."
949227524Sobrien		    );
950147191Sjkoshy
951147191Sjkoshy	/* check for process-mode options without a command or -t pid */
952147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
953169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
954227524Sobrien		errx(EX_USAGE,
955227524Sobrien"ERROR: options -d, -E, -p, -P, and -W require a command line or target process."
956227524Sobrien		    );
957147191Sjkoshy
958147191Sjkoshy	/* check for -p | -P without a target process of some sort */
959169069Sjkoshy	if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
960169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
961227524Sobrien		errx(EX_USAGE,
962227524Sobrien"ERROR: options -P and -p require a target process or a command line."
963227524Sobrien		    );
964147191Sjkoshy
965147191Sjkoshy	/* check for process-mode options without a process-mode PMC */
966147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
967147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
968227524Sobrien		errx(EX_USAGE,
969227524Sobrien"ERROR: options -d, -E, and -W require a process mode PMC to be specified."
970227524Sobrien		    );
971147191Sjkoshy
972174396Sjkoshy	/* check for -c cpu with no system mode PMCs or logfile. */
973147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
974174396Sjkoshy	    (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
975174396Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
976227524Sobrien		errx(EX_USAGE,
977227524Sobrien"ERROR: option -c requires at least one system mode PMC to be specified."
978227524Sobrien		    );
979147191Sjkoshy
980147191Sjkoshy	/* check for counting mode options without a counting PMC */
981147191Sjkoshy	if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
982147191Sjkoshy	    (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
983227524Sobrien		errx(EX_USAGE,
984227524Sobrien"ERROR: options -C, -W and -o require at least one counting mode PMC to be specified."
985227524Sobrien		    );
986147191Sjkoshy
987147191Sjkoshy	/* check for sampling mode options without a sampling PMC spec */
988147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
989147191Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
990227524Sobrien		errx(EX_USAGE,
991227524Sobrien"ERROR: options -N, -n and -O require at least one sampling mode PMC to be specified."
992227524Sobrien		    );
993147191Sjkoshy
994203790Sfabient	/* check if -g/-G/-m/-T are being used correctly */
995174396Sjkoshy	if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
996147708Sjkoshy	    !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
997227524Sobrien		errx(EX_USAGE,
998227524Sobrien"ERROR: options -g/-G/-m/-T require sampling PMCs or -R to be specified."
999227524Sobrien		    );
1000147708Sjkoshy
1001147191Sjkoshy	/* check if -O was spuriously specified */
1002147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
1003147708Sjkoshy	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
1004147191Sjkoshy		errx(EX_USAGE,
1005227524Sobrien"ERROR: option -O is used only with options -E, -P, -S and -W."
1006227524Sobrien		    );
1007147191Sjkoshy
1008203790Sfabient	/* -k kernel path require -g/-G/-m/-T or -R */
1009147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
1010174396Sjkoshy	    (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
1011157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1012203790Sfabient	    errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
1013147708Sjkoshy
1014174396Sjkoshy	/* -D only applies to gprof output mode (-g) */
1015147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
1016174396Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0)
1017174396Sjkoshy	    errx(EX_USAGE, "ERROR: option -D is only used with -g.");
1018147708Sjkoshy
1019157144Sjkoshy	/* -M mapfile requires -g or -R */
1020157144Sjkoshy	if (args.pa_mapfilename != NULL &&
1021157144Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0 &&
1022157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1023157144Sjkoshy	    errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
1024157144Sjkoshy
1025147708Sjkoshy	/*
1026147708Sjkoshy	 * Disallow textual output of sampling PMCs if counting PMCs
1027147708Sjkoshy	 * have also been asked for, mostly because the combined output
1028147708Sjkoshy	 * is difficult to make sense of.
1029147708Sjkoshy	 */
1030147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1031147708Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1032168927Sjkoshy	    ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
1033227524Sobrien		errx(EX_USAGE,
1034227524Sobrien"ERROR: option -O is required if counting and sampling PMCs are specified together."
1035227524Sobrien		    );
1036147708Sjkoshy
1037157144Sjkoshy	/*
1038174396Sjkoshy	 * Check if "-k kerneldir" was specified, and if whether
1039227489Seadler	 * 'kerneldir' actually refers to a file.  If so, use
1040174396Sjkoshy	 * `dirname path` to determine the kernel directory.
1041157144Sjkoshy	 */
1042157144Sjkoshy	if (args.pa_flags & FLAG_HAS_KERNELPATH) {
1043157144Sjkoshy		(void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
1044157144Sjkoshy		    args.pa_kernel);
1045157144Sjkoshy		if (stat(buffer, &sb) < 0)
1046157144Sjkoshy			err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
1047157144Sjkoshy			    buffer);
1048157144Sjkoshy		if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
1049157144Sjkoshy			errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
1050157144Sjkoshy			    buffer);
1051157144Sjkoshy		if (!S_ISDIR(sb.st_mode)) {
1052157144Sjkoshy			tmp = args.pa_kernel;
1053157144Sjkoshy			args.pa_kernel = strdup(dirname(args.pa_kernel));
1054157144Sjkoshy			free(tmp);
1055157144Sjkoshy			(void) snprintf(buffer, sizeof(buffer), "%s%s",
1056157144Sjkoshy			    args.pa_fsroot, args.pa_kernel);
1057157144Sjkoshy			if (stat(buffer, &sb) < 0)
1058157144Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
1059157144Sjkoshy				    buffer);
1060157144Sjkoshy			if (!S_ISDIR(sb.st_mode))
1061227524Sobrien				errx(EX_USAGE,
1062227524Sobrien				    "ERROR: \"%s\" is not a directory.",
1063227524Sobrien				    buffer);
1064157144Sjkoshy		}
1065157144Sjkoshy	}
1066168949Sjkoshy
1067174396Sjkoshy	/*
1068174396Sjkoshy	 * If we have a callgraph be created, select the outputfile.
1069174396Sjkoshy	 */
1070174396Sjkoshy	if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
1071174396Sjkoshy		if (strcmp(graphfilename, "-") == 0)
1072174396Sjkoshy		    args.pa_graphfile = args.pa_printfile;
1073174396Sjkoshy		else {
1074174396Sjkoshy			args.pa_graphfile = fopen(graphfilename, "w");
1075174396Sjkoshy			if (args.pa_graphfile == NULL)
1076227524Sobrien				err(EX_OSERR,
1077227524Sobrien				    "ERROR: cannot open \"%s\" for writing",
1078227524Sobrien				    graphfilename);
1079174396Sjkoshy		}
1080174396Sjkoshy	}
1081203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE) {
1082185322Sattilio		args.pa_graphfile = fopen(graphfilename, "w");
1083185322Sattilio		if (args.pa_graphfile == NULL)
1084185322Sattilio			err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
1085185322Sattilio			    graphfilename);
1086185322Sattilio	}
1087174396Sjkoshy
1088210794Sfabient	/* if we've been asked to process a log file, skip init */
1089210794Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) {
1090210794Sfabient		if (pmc_init() < 0)
1091210794Sfabient			err(EX_UNAVAILABLE,
1092227524Sobrien			    "ERROR: Initialization of the pmc(3) library failed"
1093227524Sobrien			    );
1094210794Sfabient
1095210794Sfabient		if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1096227524Sobrien			err(EX_OSERR,
1097227524Sobrien"ERROR: Cannot determine the number of PMCs on CPU %d",
1098227524Sobrien			    0);
1099210794Sfabient	}
1100210794Sfabient
1101210794Sfabient	/* Allocate a kqueue */
1102210794Sfabient	if ((pmcstat_kq = kqueue()) < 0)
1103210794Sfabient		err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1104210794Sfabient
1105210794Sfabient	/* Setup the logfile as the source. */
1106147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
1107147708Sjkoshy		/*
1108147708Sjkoshy		 * Print the log in textual form if we haven't been
1109174396Sjkoshy		 * asked to generate profiling information.
1110147708Sjkoshy		 */
1111174396Sjkoshy		if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1112147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
1113147708Sjkoshy
1114203790Sfabient		pmcstat_initialize_logging();
1115210794Sfabient		rfd = pmcstat_open_log(args.pa_inputpath,
1116157406Sjkoshy		    PMCSTAT_OPEN_FOR_READ);
1117210794Sfabient		if ((args.pa_logparser = pmclog_open(rfd)) == NULL)
1118147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot create parser");
1119210794Sfabient		if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0)
1120210794Sfabient			err(EX_OSERR, "ERROR: fcntl(2) failed");
1121210794Sfabient		EV_SET(&kev, rfd, EVFILT_READ, EV_ADD,
1122210794Sfabient		    0, 0, NULL);
1123210794Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1124210794Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1125147191Sjkoshy	}
1126145256Sjkoshy	/*
1127147708Sjkoshy	 * Configure the specified log file or setup a default log
1128147708Sjkoshy	 * consumer via a pipe.
1129147708Sjkoshy	 */
1130147708Sjkoshy	if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1131157406Sjkoshy		if (args.pa_outputpath)
1132157406Sjkoshy			args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1133157406Sjkoshy			    PMCSTAT_OPEN_FOR_WRITE);
1134157406Sjkoshy		else {
1135147708Sjkoshy			/*
1136147708Sjkoshy			 * process the log on the fly by reading it in
1137147708Sjkoshy			 * through a pipe.
1138147708Sjkoshy			 */
1139147708Sjkoshy			if (pipe(pipefd) < 0)
1140147708Sjkoshy				err(EX_OSERR, "ERROR: pipe(2) failed");
1141147708Sjkoshy
1142147708Sjkoshy			if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1143147708Sjkoshy				err(EX_OSERR, "ERROR: fcntl(2) failed");
1144147708Sjkoshy
1145147708Sjkoshy			EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1146147708Sjkoshy			    0, 0, NULL);
1147147708Sjkoshy
1148147708Sjkoshy			if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1149147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot register kevent");
1150147708Sjkoshy
1151147708Sjkoshy			args.pa_logfd = pipefd[WRITEPIPEFD];
1152147708Sjkoshy
1153203790Sfabient			args.pa_flags |= FLAG_HAS_PIPE;
1154203790Sfabient			if ((args.pa_flags & FLAG_DO_TOP) == 0)
1155203790Sfabient				args.pa_flags |= FLAG_DO_PRINT;
1156147708Sjkoshy			args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1157147708Sjkoshy		}
1158147708Sjkoshy
1159147708Sjkoshy		if (pmc_configure_logfile(args.pa_logfd) < 0)
1160147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot configure log file");
1161147708Sjkoshy	}
1162147708Sjkoshy
1163151542Sjkoshy	/* remember to check for driver errors if we are sampling or logging */
1164151542Sjkoshy	check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1165151542Sjkoshy	    (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1166151542Sjkoshy
1167147708Sjkoshy	/*
1168210794Sfabient	if (args.pa_flags & FLAG_READ_LOGFILE) {
1169145256Sjkoshy	 * Allocate PMCs.
1170145256Sjkoshy	 */
1171145256Sjkoshy
1172169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1173227524Sobrien		if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1174147191Sjkoshy		    ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1175227524Sobrien			err(EX_OSERR,
1176227524Sobrien"ERROR: Cannot allocate %s-mode pmc with specification \"%s\"",
1177227524Sobrien			    PMC_IS_SYSTEM_MODE(ev->ev_mode) ?
1178227524Sobrien			    "system" : "process", ev->ev_spec);
1179145256Sjkoshy
1180227524Sobrien		if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1181227524Sobrien		    pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1182227524Sobrien			err(EX_OSERR,
1183227524Sobrien			    "ERROR: Cannot set sampling count for PMC \"%s\"",
1184227524Sobrien			    ev->ev_name);
1185147708Sjkoshy	}
1186147708Sjkoshy
1187145256Sjkoshy	/* compute printout widths */
1188169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1189145774Sjkoshy		int counter_width;
1190145774Sjkoshy		int display_width;
1191145774Sjkoshy		int header_width;
1192145256Sjkoshy
1193145774Sjkoshy		(void) pmc_width(ev->ev_pmcid, &counter_width);
1194168949Sjkoshy		header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1195145774Sjkoshy		display_width = (int) floor(counter_width / 3.32193) + 1;
1196145256Sjkoshy
1197168949Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1198168949Sjkoshy			header_width += 3; /* 2 digit CPU number + '/' */
1199168949Sjkoshy
1200145774Sjkoshy		if (header_width > display_width) {
1201145256Sjkoshy			ev->ev_fieldskip = 0;
1202145774Sjkoshy			ev->ev_fieldwidth = header_width;
1203145256Sjkoshy		} else {
1204145774Sjkoshy			ev->ev_fieldskip = display_width -
1205145774Sjkoshy			    header_width;
1206145774Sjkoshy			ev->ev_fieldwidth = display_width;
1207145256Sjkoshy		}
1208145256Sjkoshy	}
1209145256Sjkoshy
1210145256Sjkoshy	/*
1211145256Sjkoshy	 * If our output is being set to a terminal, register a handler
1212145256Sjkoshy	 * for window size changes.
1213145256Sjkoshy	 */
1214145256Sjkoshy
1215147708Sjkoshy	if (isatty(fileno(args.pa_printfile))) {
1216145256Sjkoshy
1217147708Sjkoshy		if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1218145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot determine window size");
1219145256Sjkoshy
1220145256Sjkoshy		pmcstat_displayheight = ws.ws_row - 1;
1221203790Sfabient		pmcstat_displaywidth  = ws.ws_col - 1;
1222145256Sjkoshy
1223145256Sjkoshy		EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1224145256Sjkoshy
1225145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1226227524Sobrien			err(EX_OSERR,
1227227524Sobrien			    "ERROR: Cannot register kevent for SIGWINCH");
1228203790Sfabient
1229203790Sfabient		args.pa_toptty = 1;
1230145256Sjkoshy	}
1231145256Sjkoshy
1232203790Sfabient	/*
1233203790Sfabient	 * Listen to key input in top mode.
1234203790Sfabient	 */
1235203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1236203790Sfabient		EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1237203790Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1238203790Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1239203790Sfabient	}
1240203790Sfabient
1241145256Sjkoshy	EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1242145256Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1243145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1244145256Sjkoshy
1245147191Sjkoshy	EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1246147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1247147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1248145256Sjkoshy
1249147191Sjkoshy	/*
1250147191Sjkoshy	 * An exec() failure of a forked child is signalled by the
1251147191Sjkoshy	 * child sending the parent a SIGCHLD.  We don't register an
1252147191Sjkoshy	 * actual signal handler for SIGCHLD, but instead use our
1253147191Sjkoshy	 * kqueue to pick up the signal.
1254147191Sjkoshy	 */
1255147191Sjkoshy	EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1256147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1257147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1258145256Sjkoshy
1259203790Sfabient	/*
1260203790Sfabient	 * Setup a timer if we have counting mode PMCs needing to be printed or
1261203790Sfabient	 * top mode plugin is active.
1262203790Sfabient	 */
1263203790Sfabient	if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1264203790Sfabient	     (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1265203790Sfabient	    (args.pa_flags & FLAG_DO_TOP)) {
1266145256Sjkoshy		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1267145256Sjkoshy		    args.pa_interval * 1000, NULL);
1268145256Sjkoshy
1269145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1270227524Sobrien			err(EX_OSERR,
1271227524Sobrien			    "ERROR: Cannot register kevent for timer");
1272145256Sjkoshy	}
1273145256Sjkoshy
1274145256Sjkoshy	/* attach PMCs to the target process, starting it if specified */
1275168949Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1276203790Sfabient		pmcstat_create_process();
1277145256Sjkoshy
1278151542Sjkoshy	if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1279151542Sjkoshy		err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1280151542Sjkoshy
1281168949Sjkoshy	/* Attach process pmcs to the target process. */
1282180148Sjkoshy	if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1283169069Sjkoshy		if (SLIST_EMPTY(&args.pa_targets))
1284227524Sobrien			errx(EX_DATAERR,
1285227524Sobrien			    "ERROR: No matching target processes.");
1286183672Sjkoshy		if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1287203790Sfabient			pmcstat_attach_pmcs();
1288168949Sjkoshy
1289169069Sjkoshy		if (pmcstat_kvm) {
1290169069Sjkoshy			kvm_close(pmcstat_kvm);
1291169069Sjkoshy			pmcstat_kvm = NULL;
1292169069Sjkoshy		}
1293169069Sjkoshy	}
1294169069Sjkoshy
1295145256Sjkoshy	/* start the pmcs */
1296203790Sfabient	pmcstat_start_pmcs();
1297145256Sjkoshy
1298145256Sjkoshy	/* start the (commandline) process if needed */
1299147708Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1300168949Sjkoshy		pmcstat_start_process();
1301145256Sjkoshy
1302210794Sfabient	/* initialize logging */
1303210794Sfabient	pmcstat_initialize_logging();
1304147708Sjkoshy
1305145256Sjkoshy	/* Handle SIGINT using the kqueue loop */
1306145256Sjkoshy	sa.sa_handler = SIG_IGN;
1307145256Sjkoshy	sa.sa_flags   = 0;
1308145256Sjkoshy	(void) sigemptyset(&sa.sa_mask);
1309145256Sjkoshy
1310145256Sjkoshy	if (sigaction(SIGINT, &sa, NULL) < 0)
1311145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot install signal handler");
1312145256Sjkoshy
1313145256Sjkoshy	/*
1314203790Sfabient	 * Setup the top mode display.
1315203790Sfabient	 */
1316203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1317203790Sfabient		args.pa_flags &= ~FLAG_DO_PRINT;
1318203790Sfabient
1319203790Sfabient		if (args.pa_toptty) {
1320203790Sfabient			/*
1321203790Sfabient			 * Init ncurses.
1322203790Sfabient			 */
1323203790Sfabient			initscr();
1324203790Sfabient			if(has_colors() == TRUE) {
1325203790Sfabient				args.pa_topcolor = 1;
1326203790Sfabient				start_color();
1327203790Sfabient				use_default_colors();
1328203790Sfabient				pair_content(0, &cf, &cb);
1329203790Sfabient				init_pair(1, COLOR_RED, cb);
1330203790Sfabient				init_pair(2, COLOR_YELLOW, cb);
1331203790Sfabient				init_pair(3, COLOR_GREEN, cb);
1332203790Sfabient			}
1333203790Sfabient			cbreak();
1334203790Sfabient			noecho();
1335203790Sfabient			nonl();
1336203790Sfabient			nodelay(stdscr, 1);
1337203790Sfabient			intrflush(stdscr, FALSE);
1338203790Sfabient			keypad(stdscr, TRUE);
1339203790Sfabient			clear();
1340204783Sfabient			/* Get terminal width / height with ncurses. */
1341227524Sobrien			getmaxyx(stdscr,
1342227524Sobrien			    pmcstat_displayheight, pmcstat_displaywidth);
1343204783Sfabient			pmcstat_displayheight--; pmcstat_displaywidth--;
1344203790Sfabient			atexit(pmcstat_topexit);
1345203790Sfabient		}
1346203790Sfabient	}
1347203790Sfabient
1348203790Sfabient	/*
1349145256Sjkoshy	 * loop till either the target process (if any) exits, or we
1350145256Sjkoshy	 * are killed by a SIGINT.
1351145256Sjkoshy	 */
1352147191Sjkoshy	runstate = PMCSTAT_RUNNING;
1353226514Sfabient	do_print = do_read = 0;
1354145256Sjkoshy	do {
1355145256Sjkoshy		if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1356145256Sjkoshy			if (errno != EINTR)
1357145256Sjkoshy				err(EX_OSERR, "ERROR: kevent failed");
1358145256Sjkoshy			else
1359145256Sjkoshy				continue;
1360145256Sjkoshy		}
1361145256Sjkoshy
1362145256Sjkoshy		if (kev.flags & EV_ERROR)
1363145256Sjkoshy			errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1364145256Sjkoshy
1365145256Sjkoshy		switch (kev.filter) {
1366147191Sjkoshy		case EVFILT_PROC:  /* target has exited */
1367210794Sfabient			runstate = pmcstat_close_log();
1368148688Sjkoshy			do_print = 1;
1369147191Sjkoshy			break;
1370145256Sjkoshy
1371147191Sjkoshy		case EVFILT_READ:  /* log file data is present */
1372210794Sfabient			if (kev.ident == (unsigned)fileno(stdin) &&
1373210794Sfabient			    (args.pa_flags & FLAG_DO_TOP)) {
1374203790Sfabient				if (pmcstat_keypress_log())
1375203790Sfabient					runstate = pmcstat_close_log();
1376226514Sfabient			} else {
1377226514Sfabient				do_read = 0;
1378203790Sfabient				runstate = pmcstat_process_log();
1379226514Sfabient			}
1380145256Sjkoshy			break;
1381145256Sjkoshy
1382145256Sjkoshy		case EVFILT_SIGNAL:
1383147191Sjkoshy			if (kev.ident == SIGCHLD) {
1384147191Sjkoshy				/*
1385147191Sjkoshy				 * The child process sends us a
1386147191Sjkoshy				 * SIGCHLD if its exec() failed.  We
1387147191Sjkoshy				 * wait for it to exit and then exit
1388147191Sjkoshy				 * ourselves.
1389147191Sjkoshy				 */
1390147191Sjkoshy				(void) wait(&c);
1391147191Sjkoshy				runstate = PMCSTAT_FINISHED;
1392147191Sjkoshy			} else if (kev.ident == SIGIO) {
1393147191Sjkoshy				/*
1394147191Sjkoshy				 * We get a SIGIO if a PMC loses all
1395147191Sjkoshy				 * of its targets, or if logfile
1396147191Sjkoshy				 * writes encounter an error.
1397147191Sjkoshy				 */
1398210794Sfabient				runstate = pmcstat_close_log();
1399147191Sjkoshy				do_print = 1; /* print PMCs at exit */
1400147191Sjkoshy			} else if (kev.ident == SIGINT) {
1401147708Sjkoshy				/* Kill the child process if we started it */
1402147708Sjkoshy				if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1403203790Sfabient					pmcstat_kill_process();
1404210794Sfabient				runstate = pmcstat_close_log();
1405145256Sjkoshy			} else if (kev.ident == SIGWINCH) {
1406147708Sjkoshy				if (ioctl(fileno(args.pa_printfile),
1407145256Sjkoshy					TIOCGWINSZ, &ws) < 0)
1408227524Sobrien				    err(EX_OSERR,
1409227524Sobrien				        "ERROR: Cannot determine window size");
1410145256Sjkoshy				pmcstat_displayheight = ws.ws_row - 1;
1411203790Sfabient				pmcstat_displaywidth  = ws.ws_col - 1;
1412145256Sjkoshy			} else
1413145256Sjkoshy				assert(0);
1414145256Sjkoshy
1415145256Sjkoshy			break;
1416147191Sjkoshy
1417147191Sjkoshy		case EVFILT_TIMER: /* print out counting PMCs */
1418226514Sfabient			if ((args.pa_flags & FLAG_DO_TOP) &&
1419226986Sfabient			     pmc_flush_logfile() == 0)
1420226514Sfabient				do_read = 1;
1421147191Sjkoshy			do_print = 1;
1422147191Sjkoshy			break;
1423147191Sjkoshy
1424145256Sjkoshy		}
1425145256Sjkoshy
1426226514Sfabient		if (do_print && !do_read) {
1427203790Sfabient			if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1428203790Sfabient				pmcstat_print_pmcs();
1429227524Sobrien				if (runstate == PMCSTAT_FINISHED &&
1430227524Sobrien				    /* final newline */
1431203790Sfabient				    (args.pa_flags & FLAG_DO_PRINT) == 0)
1432203790Sfabient					(void) fprintf(args.pa_printfile, "\n");
1433203790Sfabient			}
1434203790Sfabient			if (args.pa_flags & FLAG_DO_TOP)
1435203790Sfabient				pmcstat_display_log();
1436147191Sjkoshy			do_print = 0;
1437147191Sjkoshy		}
1438145256Sjkoshy
1439147191Sjkoshy	} while (runstate != PMCSTAT_FINISHED);
1440147191Sjkoshy
1441203790Sfabient	if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1442203790Sfabient		pmcstat_topexit();
1443203790Sfabient		args.pa_toptty = 0;
1444203790Sfabient	}
1445203790Sfabient
1446147191Sjkoshy	/* flush any pending log entries */
1447147708Sjkoshy	if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1448226514Sfabient		pmc_close_logfile();
1449147191Sjkoshy
1450203790Sfabient	pmcstat_cleanup();
1451145256Sjkoshy
1452157144Sjkoshy	free(args.pa_kernel);
1453157144Sjkoshy
1454151542Sjkoshy	/* check if the driver lost any samples or events */
1455151542Sjkoshy	if (check_driver_stats) {
1456151542Sjkoshy		if (pmc_get_driver_stats(&ds_end) < 0)
1457227524Sobrien			err(EX_OSERR,
1458227524Sobrien			    "ERROR: Cannot retrieve driver statistics");
1459157144Sjkoshy		if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1460157144Sjkoshy		    args.pa_verbosity > 0)
1461227524Sobrien			warnx("WARNING: some samples were dropped.\n"
1462227524Sobrien"Please consider tuning the \"kern.hwpmc.nsamples\" tunable."
1463227524Sobrien			    );
1464151542Sjkoshy		if (ds_start.pm_buffer_requests_failed !=
1465157144Sjkoshy		    ds_end.pm_buffer_requests_failed &&
1466157144Sjkoshy		    args.pa_verbosity > 0)
1467227524Sobrien			warnx("WARNING: some events were discarded.\n"
1468227524Sobrien"Please consider tuning the \"kern.hwpmc.nbuffers\" tunable."
1469227524Sobrien			    );
1470151542Sjkoshy	}
1471151542Sjkoshy
1472151542Sjkoshy	exit(EX_OK);
1473145256Sjkoshy}
1474