1145256Sjkoshy/*-
2180148Sjkoshy * Copyright (c) 2003-2008, Joseph Koshy
3174396Sjkoshy * Copyright (c) 2007 The FreeBSD Foundation
4145256Sjkoshy * All rights reserved.
5145256Sjkoshy *
6174396Sjkoshy * Portions of this software were developed by A. Joseph Koshy under
7174396Sjkoshy * sponsorship from the FreeBSD Foundation and Google, Inc.
8174396Sjkoshy *
9145256Sjkoshy * Redistribution and use in source and binary forms, with or without
10145256Sjkoshy * modification, are permitted provided that the following conditions
11145256Sjkoshy * are met:
12145256Sjkoshy * 1. Redistributions of source code must retain the above copyright
13145256Sjkoshy *    notice, this list of conditions and the following disclaimer.
14145256Sjkoshy * 2. Redistributions in binary form must reproduce the above copyright
15145256Sjkoshy *    notice, this list of conditions and the following disclaimer in the
16145256Sjkoshy *    documentation and/or other materials provided with the distribution.
17145256Sjkoshy *
18145256Sjkoshy * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19145256Sjkoshy * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20145256Sjkoshy * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21145256Sjkoshy * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22145256Sjkoshy * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23145256Sjkoshy * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24145256Sjkoshy * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25145256Sjkoshy * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26145256Sjkoshy * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27145256Sjkoshy * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28145256Sjkoshy * SUCH DAMAGE.
29145256Sjkoshy */
30145256Sjkoshy
31145256Sjkoshy#include <sys/cdefs.h>
32145256Sjkoshy__FBSDID("$FreeBSD$");
33145256Sjkoshy
34224698Sattilio#include <sys/param.h>
35224698Sattilio#include <sys/cpuset.h>
36145256Sjkoshy#include <sys/event.h>
37145256Sjkoshy#include <sys/queue.h>
38147708Sjkoshy#include <sys/socket.h>
39147708Sjkoshy#include <sys/stat.h>
40168949Sjkoshy#include <sys/sysctl.h>
41145256Sjkoshy#include <sys/time.h>
42145256Sjkoshy#include <sys/ttycom.h>
43169069Sjkoshy#include <sys/user.h>
44145256Sjkoshy#include <sys/wait.h>
45145256Sjkoshy
46145256Sjkoshy#include <assert.h>
47203790Sfabient#include <curses.h>
48145256Sjkoshy#include <err.h>
49145256Sjkoshy#include <errno.h>
50145256Sjkoshy#include <fcntl.h>
51169069Sjkoshy#include <kvm.h>
52157144Sjkoshy#include <libgen.h>
53145256Sjkoshy#include <limits.h>
54145256Sjkoshy#include <math.h>
55145256Sjkoshy#include <pmc.h>
56147191Sjkoshy#include <pmclog.h>
57169069Sjkoshy#include <regex.h>
58145256Sjkoshy#include <signal.h>
59145256Sjkoshy#include <stdarg.h>
60147708Sjkoshy#include <stdint.h>
61145256Sjkoshy#include <stdio.h>
62145256Sjkoshy#include <stdlib.h>
63145256Sjkoshy#include <string.h>
64145256Sjkoshy#include <sysexits.h>
65145256Sjkoshy#include <unistd.h>
66145256Sjkoshy
67147708Sjkoshy#include "pmcstat.h"
68147708Sjkoshy
69147191Sjkoshy/*
70147191Sjkoshy * A given invocation of pmcstat(8) can manage multiple PMCs of both
71147191Sjkoshy * the system-wide and per-process variety.  Each of these could be in
72147191Sjkoshy * 'counting mode' or in 'sampling mode'.
73147191Sjkoshy *
74147191Sjkoshy * For 'counting mode' PMCs, pmcstat(8) will periodically issue a
75147191Sjkoshy * pmc_read() at the configured time interval and print out the value
76147191Sjkoshy * of the requested PMCs.
77147191Sjkoshy *
78147191Sjkoshy * For 'sampling mode' PMCs it can log to a file for offline analysis,
79147191Sjkoshy * or can analyse sampling data "on the fly", either by converting
80147191Sjkoshy * samples to printed textual form or by creating gprof(1) compatible
81147191Sjkoshy * profiles, one per program executed.  When creating gprof(1)
82147191Sjkoshy * profiles it can optionally merge entries from multiple processes
83147191Sjkoshy * for a given executable into a single profile file.
84168949Sjkoshy *
85168949Sjkoshy * pmcstat(8) can also execute a command line and attach PMCs to the
86168949Sjkoshy * resulting child process.  The protocol used is as follows:
87168949Sjkoshy *
88168949Sjkoshy * - parent creates a socketpair for two way communication and
89168949Sjkoshy *   fork()s.
90168949Sjkoshy * - subsequently:
91168949Sjkoshy *
92168949Sjkoshy *   /Parent/				/Child/
93168949Sjkoshy *
94168949Sjkoshy *   - Wait for childs token.
95168949Sjkoshy *					- Sends token.
96168949Sjkoshy *					- Awaits signal to start.
97168949Sjkoshy *  - Attaches PMCs to the child's pid
98168949Sjkoshy *    and starts them. Sets up
99168949Sjkoshy *    monitoring for the child.
100168949Sjkoshy *  - Signals child to start.
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)
159237969Sobrien			errx(EX_USAGE,
160237969Sobrien			    "ERROR: Illegal CPU specification \"%s\".",
161237969Sobrien			    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)
183237969Sobrien				err(EX_OSERR,
184237969Sobrien"ERROR: cannot attach pmc \"%s\" to process %d",
185237969Sobrien				    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)
202237969Sobrien			err(EX_OSERR, "ERROR: cannot stop pmc 0x%x \"%s\"",
203237969Sobrien			    ev->ev_pmcid, ev->ev_name);
204145256Sjkoshy		if (pmc_release(ev->ev_pmcid) < 0)
205237969Sobrien			err(EX_OSERR, "ERROR: cannot release pmc 0x%x \"%s\"",
206237969Sobrien			    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)
428237969Sobrien			err(EX_OSERR, "ERROR: Cannot read pmc \"%s\"",
429237969Sobrien			    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"
512267411Semaste	    "\t -l secs\t set duration time\n"
513240093Sjimharris	    "\t -m file\t print sampled PCs to \"file\"\n"
514145256Sjkoshy	    "\t -n rate\t set sampling rate\n"
515145256Sjkoshy	    "\t -o file\t send print output to \"file\"\n"
516147191Sjkoshy	    "\t -p spec\t allocate a process-private counting PMC\n"
517157144Sjkoshy	    "\t -q\t\t suppress verbosity\n"
518157144Sjkoshy	    "\t -r fsroot\t specify FS root directory\n"
519147191Sjkoshy	    "\t -s spec\t allocate a system-wide counting PMC\n"
520183186Sjkoshy	    "\t -t process-spec attach to running processes matching "
521183186Sjkoshy		"\"process-spec\"\n"
522157144Sjkoshy	    "\t -v\t\t increase verbosity\n"
523174396Sjkoshy	    "\t -w secs\t set printing time interval\n"
524174396Sjkoshy	    "\t -z depth\t limit callchain display depth"
525145256Sjkoshy	);
526145256Sjkoshy}
527145256Sjkoshy
528145256Sjkoshy/*
529203790Sfabient * At exit handler for top mode
530203790Sfabient */
531203790Sfabient
532203790Sfabientvoid
533203790Sfabientpmcstat_topexit(void)
534203790Sfabient{
535203790Sfabient	if (!args.pa_toptty)
536203790Sfabient		return;
537203790Sfabient
538203790Sfabient	/*
539203790Sfabient	 * Shutdown ncurses.
540203790Sfabient	 */
541203790Sfabient	clrtoeol();
542203790Sfabient	refresh();
543203790Sfabient	endwin();
544203790Sfabient}
545203790Sfabient
546203790Sfabient/*
547145256Sjkoshy * Main
548145256Sjkoshy */
549145256Sjkoshy
550145256Sjkoshyint
551145256Sjkoshymain(int argc, char **argv)
552145256Sjkoshy{
553224698Sattilio	cpuset_t cpumask;
554145256Sjkoshy	double interval;
555267411Semaste	double duration;
556224698Sattilio	int hcpu, option, npmc, ncpu;
557151542Sjkoshy	int c, check_driver_stats, current_cpu, current_sampling_count;
558174396Sjkoshy	int do_callchain, do_descendants, do_logproccsw, do_logprocexit;
559229392Sfabient	int do_print, do_read;
560168949Sjkoshy	size_t dummy;
561174396Sjkoshy	int graphdepth;
562210794Sfabient	int pipefd[2], rfd;
563147191Sjkoshy	int use_cumulative_counts;
564203790Sfabient	short cf, cb;
565157144Sjkoshy	char *end, *tmp;
566174396Sjkoshy	const char *errmsg, *graphfilename;
567147191Sjkoshy	enum pmcstat_state runstate;
568151542Sjkoshy	struct pmc_driverstats ds_start, ds_end;
569145256Sjkoshy	struct pmcstat_ev *ev;
570145256Sjkoshy	struct sigaction sa;
571145256Sjkoshy	struct kevent kev;
572145256Sjkoshy	struct winsize ws;
573147708Sjkoshy	struct stat sb;
574157144Sjkoshy	char buffer[PATH_MAX];
575145256Sjkoshy
576151542Sjkoshy	check_driver_stats      = 0;
577145256Sjkoshy	current_cpu 		= 0;
578145256Sjkoshy	current_sampling_count  = DEFAULT_SAMPLE_COUNT;
579174396Sjkoshy	do_callchain		= 1;
580145256Sjkoshy	do_descendants          = 0;
581147191Sjkoshy	do_logproccsw           = 0;
582147191Sjkoshy	do_logprocexit          = 0;
583145256Sjkoshy	use_cumulative_counts   = 0;
584174396Sjkoshy	graphfilename		= "-";
585147191Sjkoshy	args.pa_required	= 0;
586145256Sjkoshy	args.pa_flags		= 0;
587157144Sjkoshy	args.pa_verbosity	= 1;
588147708Sjkoshy	args.pa_logfd		= -1;
589157144Sjkoshy	args.pa_fsroot		= "";
590157144Sjkoshy	args.pa_kernel		= strdup("/boot/kernel");
591147708Sjkoshy	args.pa_samplesdir	= ".";
592147708Sjkoshy	args.pa_printfile	= stderr;
593174396Sjkoshy	args.pa_graphdepth	= DEFAULT_CALLGRAPH_DEPTH;
594174396Sjkoshy	args.pa_graphfile	= NULL;
595145256Sjkoshy	args.pa_interval	= DEFAULT_WAIT_INTERVAL;
596157144Sjkoshy	args.pa_mapfilename	= NULL;
597174396Sjkoshy	args.pa_inputpath	= NULL;
598174396Sjkoshy	args.pa_outputpath	= NULL;
599203790Sfabient	args.pa_pplugin		= PMCSTAT_PL_NONE;
600203790Sfabient	args.pa_plugin		= PMCSTAT_PL_NONE;
601203790Sfabient	args.pa_ctdumpinstr	= 1;
602203790Sfabient	args.pa_topmode		= PMCSTAT_TOP_DELTA;
603203790Sfabient	args.pa_toptty		= 0;
604203790Sfabient	args.pa_topcolor	= 0;
605203790Sfabient	args.pa_mergepmc	= 0;
606267411Semaste	args.pa_duration	= 0.0;
607169069Sjkoshy	STAILQ_INIT(&args.pa_events);
608169069Sjkoshy	SLIST_INIT(&args.pa_targets);
609153704Sjkoshy	bzero(&ds_start, sizeof(ds_start));
610153704Sjkoshy	bzero(&ds_end, sizeof(ds_end));
611145256Sjkoshy	ev = NULL;
612224698Sattilio	CPU_ZERO(&cpumask);
613145256Sjkoshy
614174396Sjkoshy	/*
615174396Sjkoshy	 * The initial CPU mask specifies all non-halted CPUS in the
616174396Sjkoshy	 * system.
617174396Sjkoshy	 */
618174396Sjkoshy	dummy = sizeof(int);
619168949Sjkoshy	if (sysctlbyname("hw.ncpu", &ncpu, &dummy, NULL, 0) < 0)
620174396Sjkoshy		err(EX_OSERR, "ERROR: Cannot determine the number of CPUs");
621224698Sattilio	for (hcpu = 0; hcpu < ncpu; hcpu++)
622224698Sattilio		CPU_SET(hcpu, &cpumask);
623168949Sjkoshy
624157144Sjkoshy	while ((option = getopt(argc, argv,
625267411Semaste	    "CD:EF:G:M:NO:P:R:S:TWc:df:gk:l:m:n:o:p:qr:s:t:vw:z:")) != -1)
626145256Sjkoshy		switch (option) {
627145256Sjkoshy		case 'C':	/* cumulative values */
628145256Sjkoshy			use_cumulative_counts = !use_cumulative_counts;
629147191Sjkoshy			args.pa_required |= FLAG_HAS_COUNTING_PMCS;
630145256Sjkoshy			break;
631145256Sjkoshy
632145256Sjkoshy		case 'c':	/* CPU */
633168949Sjkoshy
634224698Sattilio			if (optarg[0] == '*' && optarg[1] == '\0') {
635224698Sattilio				for (hcpu = 0; hcpu < ncpu; hcpu++)
636224698Sattilio					CPU_SET(hcpu, &cpumask);
637224698Sattilio			} else
638224698Sattilio				pmcstat_get_cpumask(optarg, &cpumask);
639168949Sjkoshy
640210797Sfabient			args.pa_flags	 |= FLAGS_HAS_CPUMASK;
641147191Sjkoshy			args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
642145256Sjkoshy			break;
643145256Sjkoshy
644147708Sjkoshy		case 'D':
645147708Sjkoshy			if (stat(optarg, &sb) < 0)
646147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
647147708Sjkoshy				    optarg);
648147708Sjkoshy			if (!S_ISDIR(sb.st_mode))
649237969Sobrien				errx(EX_USAGE,
650237969Sobrien				    "ERROR: \"%s\" is not a directory.",
651237969Sobrien				    optarg);
652147708Sjkoshy			args.pa_samplesdir = optarg;
653147708Sjkoshy			args.pa_flags     |= FLAG_HAS_SAMPLESDIR;
654147708Sjkoshy			args.pa_required  |= FLAG_DO_GPROF;
655147708Sjkoshy			break;
656147708Sjkoshy
657145256Sjkoshy		case 'd':	/* toggle descendents */
658145256Sjkoshy			do_descendants = !do_descendants;
659147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
660145256Sjkoshy			break;
661145256Sjkoshy
662203790Sfabient		case 'F':	/* produce a system-wide calltree */
663203790Sfabient			args.pa_flags |= FLAG_DO_CALLGRAPHS;
664203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLTREE;
665203790Sfabient			graphfilename = optarg;
666203790Sfabient			break;
667203790Sfabient
668203790Sfabient		case 'f':	/* plugins options */
669203790Sfabient			if (args.pa_plugin == PMCSTAT_PL_NONE)
670203790Sfabient				err(EX_USAGE, "ERROR: Need -g/-G/-m/-T.");
671203790Sfabient			pmcstat_pluginconfigure_log(optarg);
672203790Sfabient			break;
673203790Sfabient
674174396Sjkoshy		case 'G':	/* produce a system-wide callgraph */
675174396Sjkoshy			args.pa_flags |= FLAG_DO_CALLGRAPHS;
676203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
677174396Sjkoshy			graphfilename = optarg;
678174396Sjkoshy			break;
679174396Sjkoshy
680147191Sjkoshy		case 'g':	/* produce gprof compatible profiles */
681147191Sjkoshy			args.pa_flags |= FLAG_DO_GPROF;
682203790Sfabient			args.pa_pplugin = PMCSTAT_PL_CALLGRAPH;
683203790Sfabient			args.pa_plugin	= PMCSTAT_PL_GPROF;
684147191Sjkoshy			break;
685147191Sjkoshy
686147708Sjkoshy		case 'k':	/* pathname to the kernel */
687157144Sjkoshy			free(args.pa_kernel);
688157144Sjkoshy			args.pa_kernel = strdup(optarg);
689174396Sjkoshy			args.pa_required |= FLAG_DO_ANALYSIS;
690147708Sjkoshy			args.pa_flags    |= FLAG_HAS_KERNELPATH;
691147191Sjkoshy			break;
692147191Sjkoshy
693267411Semaste		case 'l':	/* time duration in seconds */
694267411Semaste			duration = strtod(optarg, &end);
695267411Semaste			if (*end != '\0' || duration <= 0)
696267411Semaste				errx(EX_USAGE, "ERROR: Illegal duration time "
697267411Semaste				    "value \"%s\".", optarg);
698267411Semaste			args.pa_flags |= FLAG_HAS_DURATION;
699267411Semaste			args.pa_duration = duration;
700267411Semaste			break;
701267411Semaste
702185322Sattilio		case 'm':
703203790Sfabient			args.pa_flags |= FLAG_DO_ANNOTATE;
704203790Sfabient			args.pa_plugin = PMCSTAT_PL_ANNOTATE;
705203790Sfabient			graphfilename  = optarg;
706185322Sattilio			break;
707185322Sattilio
708147191Sjkoshy		case 'E':	/* log process exit */
709147191Sjkoshy			do_logprocexit = !do_logprocexit;
710147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
711147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
712147191Sjkoshy			break;
713147191Sjkoshy
714157144Sjkoshy		case 'M':	/* mapfile */
715157144Sjkoshy			args.pa_mapfilename = optarg;
716157144Sjkoshy			break;
717157144Sjkoshy
718174396Sjkoshy		case 'N':
719174396Sjkoshy			do_callchain = !do_callchain;
720174396Sjkoshy			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
721174396Sjkoshy			break;
722174396Sjkoshy
723145256Sjkoshy		case 'p':	/* process virtual counting PMC */
724145256Sjkoshy		case 's':	/* system-wide counting PMC */
725145256Sjkoshy		case 'P':	/* process virtual sampling PMC */
726145256Sjkoshy		case 'S':	/* system-wide sampling PMC */
727145256Sjkoshy			if ((ev = malloc(sizeof(*ev))) == NULL)
728147191Sjkoshy				errx(EX_SOFTWARE, "ERROR: Out of memory.");
729145256Sjkoshy
730145256Sjkoshy			switch (option) {
731145256Sjkoshy			case 'p': ev->ev_mode = PMC_MODE_TC; break;
732145256Sjkoshy			case 's': ev->ev_mode = PMC_MODE_SC; break;
733145256Sjkoshy			case 'P': ev->ev_mode = PMC_MODE_TS; break;
734145256Sjkoshy			case 'S': ev->ev_mode = PMC_MODE_SS; break;
735145256Sjkoshy			}
736145256Sjkoshy
737147191Sjkoshy			if (option == 'P' || option == 'p') {
738147191Sjkoshy				args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
739147708Sjkoshy				args.pa_required |= (FLAG_HAS_COMMANDLINE |
740169069Sjkoshy				    FLAG_HAS_TARGET);
741147191Sjkoshy			}
742145256Sjkoshy
743147191Sjkoshy			if (option == 'P' || option == 'S') {
744147191Sjkoshy				args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
745147708Sjkoshy				args.pa_required |= (FLAG_HAS_PIPE |
746147708Sjkoshy				    FLAG_HAS_OUTPUT_LOGFILE);
747147191Sjkoshy			}
748145256Sjkoshy
749145256Sjkoshy			if (option == 'p' || option == 's')
750147191Sjkoshy				args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
751145256Sjkoshy
752147191Sjkoshy			if (option == 's' || option == 'S')
753147191Sjkoshy				args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
754147191Sjkoshy
755145256Sjkoshy			ev->ev_spec  = strdup(optarg);
756145256Sjkoshy
757145256Sjkoshy			if (option == 'S' || option == 'P')
758145256Sjkoshy				ev->ev_count = current_sampling_count;
759145256Sjkoshy			else
760145256Sjkoshy				ev->ev_count = -1;
761145256Sjkoshy
762224698Sattilio			if (option == 'S' || option == 's') {
763224698Sattilio				hcpu = sizeof(cpumask) * NBBY;
764224698Sattilio				for (hcpu--; hcpu >= 0; hcpu--)
765224698Sattilio					if (CPU_ISSET(hcpu, &cpumask))
766224698Sattilio						break;
767224698Sattilio				ev->ev_cpu = hcpu;
768224698Sattilio			} else
769145256Sjkoshy				ev->ev_cpu = PMC_CPU_ANY;
770145256Sjkoshy
771147191Sjkoshy			ev->ev_flags = 0;
772174396Sjkoshy			if (do_callchain)
773174396Sjkoshy				ev->ev_flags |= PMC_F_CALLCHAIN;
774147191Sjkoshy			if (do_descendants)
775147191Sjkoshy				ev->ev_flags |= PMC_F_DESCENDANTS;
776147191Sjkoshy			if (do_logprocexit)
777147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCEXIT;
778147191Sjkoshy			if (do_logproccsw)
779147191Sjkoshy				ev->ev_flags |= PMC_F_LOG_PROCCSW;
780147191Sjkoshy
781145256Sjkoshy			ev->ev_cumulative  = use_cumulative_counts;
782145256Sjkoshy
783145256Sjkoshy			ev->ev_saved = 0LL;
784145256Sjkoshy			ev->ev_pmcid = PMC_ID_INVALID;
785145256Sjkoshy
786145256Sjkoshy			/* extract event name */
787145256Sjkoshy			c = strcspn(optarg, ", \t");
788145256Sjkoshy			ev->ev_name = malloc(c + 1);
789145256Sjkoshy			(void) strncpy(ev->ev_name, optarg, c);
790145256Sjkoshy			*(ev->ev_name + c) = '\0';
791145256Sjkoshy
792169069Sjkoshy			STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
793145256Sjkoshy
794224698Sattilio			if (option == 's' || option == 'S') {
795224698Sattilio				hcpu = CPU_ISSET(ev->ev_cpu, &cpumask);
796224698Sattilio				CPU_CLR(ev->ev_cpu, &cpumask);
797224698Sattilio				pmcstat_clone_event_descriptor(ev, &cpumask);
798224698Sattilio				if (hcpu != 0)
799224698Sattilio					CPU_SET(ev->ev_cpu, &cpumask);
800224698Sattilio			}
801168949Sjkoshy
802145256Sjkoshy			break;
803145256Sjkoshy
804145256Sjkoshy		case 'n':	/* sampling count */
805145256Sjkoshy			current_sampling_count = strtol(optarg, &end, 0);
806145256Sjkoshy			if (*end != '\0' || current_sampling_count <= 0)
807145256Sjkoshy				errx(EX_USAGE,
808147191Sjkoshy				    "ERROR: Illegal count value \"%s\".",
809145256Sjkoshy				    optarg);
810147191Sjkoshy			args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
811145256Sjkoshy			break;
812145256Sjkoshy
813145256Sjkoshy		case 'o':	/* outputfile */
814236238Sfabient			if (args.pa_printfile != NULL &&
815236238Sfabient			    args.pa_printfile != stdout &&
816236238Sfabient			    args.pa_printfile != stderr)
817147708Sjkoshy				(void) fclose(args.pa_printfile);
818147708Sjkoshy			if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
819237969Sobrien				errx(EX_OSERR,
820237969Sobrien				    "ERROR: cannot open \"%s\" for writing.",
821237969Sobrien				    optarg);
822147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
823147191Sjkoshy			break;
824145256Sjkoshy
825145256Sjkoshy		case 'O':	/* sampling output */
826147708Sjkoshy			if (args.pa_outputpath)
827237969Sobrien				errx(EX_USAGE,
828237969Sobrien"ERROR: option -O may only be specified once.");
829147708Sjkoshy			args.pa_outputpath = optarg;
830147708Sjkoshy			args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
831145256Sjkoshy			break;
832145256Sjkoshy
833157144Sjkoshy		case 'q':	/* quiet mode */
834157144Sjkoshy			args.pa_verbosity = 0;
835157144Sjkoshy			break;
836157144Sjkoshy
837157144Sjkoshy		case 'r':	/* root FS path */
838157144Sjkoshy			args.pa_fsroot = optarg;
839157144Sjkoshy			break;
840157144Sjkoshy
841147708Sjkoshy		case 'R':	/* read an existing log file */
842174396Sjkoshy			if (args.pa_inputpath != NULL)
843237969Sobrien				errx(EX_USAGE,
844237969Sobrien"ERROR: option -R may only be specified once.");
845147708Sjkoshy			args.pa_inputpath = optarg;
846147708Sjkoshy			if (args.pa_printfile == stderr)
847147708Sjkoshy				args.pa_printfile = stdout;
848147708Sjkoshy			args.pa_flags |= FLAG_READ_LOGFILE;
849147708Sjkoshy			break;
850147708Sjkoshy
851169069Sjkoshy		case 't':	/* target pid or process name */
852203790Sfabient			pmcstat_find_targets(optarg);
853145256Sjkoshy
854169069Sjkoshy			args.pa_flags |= FLAG_HAS_TARGET;
855147191Sjkoshy			args.pa_required |= FLAG_HAS_PROCESS_PMCS;
856145256Sjkoshy			break;
857145256Sjkoshy
858203790Sfabient		case 'T':	/* top mode */
859203790Sfabient			args.pa_flags |= FLAG_DO_TOP;
860203790Sfabient			args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
861203790Sfabient			args.pa_ctdumpinstr = 0;
862203790Sfabient			args.pa_mergepmc = 1;
863203790Sfabient			if (args.pa_printfile == stderr)
864203790Sfabient				args.pa_printfile = stdout;
865203790Sfabient			break;
866203790Sfabient
867157144Sjkoshy		case 'v':	/* verbose */
868157144Sjkoshy			args.pa_verbosity++;
869157144Sjkoshy			break;
870157144Sjkoshy
871145256Sjkoshy		case 'w':	/* wait interval */
872145256Sjkoshy			interval = strtod(optarg, &end);
873145256Sjkoshy			if (*end != '\0' || interval <= 0)
874237969Sobrien				errx(EX_USAGE,
875237969Sobrien"ERROR: Illegal wait interval value \"%s\".",
876237969Sobrien				    optarg);
877145256Sjkoshy			args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
878145256Sjkoshy			args.pa_interval = interval;
879147191Sjkoshy			break;
880145256Sjkoshy
881147191Sjkoshy		case 'W':	/* toggle LOG_CSW */
882147191Sjkoshy			do_logproccsw = !do_logproccsw;
883147191Sjkoshy			args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
884147708Sjkoshy			    FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
885145256Sjkoshy			break;
886145256Sjkoshy
887174396Sjkoshy		case 'z':
888174396Sjkoshy			graphdepth = strtod(optarg, &end);
889174396Sjkoshy			if (*end != '\0' || graphdepth <= 0)
890237969Sobrien				errx(EX_USAGE,
891237969Sobrien				    "ERROR: Illegal callchain depth \"%s\".",
892237969Sobrien				    optarg);
893174396Sjkoshy			args.pa_graphdepth = graphdepth;
894174396Sjkoshy			args.pa_required |= FLAG_DO_CALLGRAPHS;
895174396Sjkoshy			break;
896174396Sjkoshy
897145256Sjkoshy		case '?':
898145256Sjkoshy		default:
899145256Sjkoshy			pmcstat_show_usage();
900145256Sjkoshy			break;
901145256Sjkoshy
902145256Sjkoshy		}
903145256Sjkoshy
904145256Sjkoshy	args.pa_argc = (argc -= optind);
905145256Sjkoshy	args.pa_argv = (argv += optind);
906145256Sjkoshy
907210797Sfabient	/* If we read from logfile and no specified CPU mask use
908210797Sfabient	 * the maximum CPU count.
909210797Sfabient	 */
910210797Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) &&
911210797Sfabient	    (args.pa_flags & FLAGS_HAS_CPUMASK) == 0)
912224698Sattilio		CPU_FILL(&cpumask);
913210797Sfabient
914174396Sjkoshy	args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
915174396Sjkoshy
916147708Sjkoshy	if (argc)	/* command line present */
917147708Sjkoshy		args.pa_flags |= FLAG_HAS_COMMANDLINE;
918145256Sjkoshy
919185322Sattilio	if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
920203790Sfabient	    FLAG_DO_ANNOTATE | FLAG_DO_TOP))
921174396Sjkoshy		args.pa_flags |= FLAG_DO_ANALYSIS;
922174396Sjkoshy
923145256Sjkoshy	/*
924145256Sjkoshy	 * Check invocation syntax.
925145256Sjkoshy	 */
926145256Sjkoshy
927147708Sjkoshy	/* disallow -O and -R together */
928147708Sjkoshy	if (args.pa_outputpath && args.pa_inputpath)
929237969Sobrien		errx(EX_USAGE,
930237969Sobrien		    "ERROR: options -O and -R are mutually exclusive.");
931147708Sjkoshy
932267411Semaste	/* disallow -T and -l together */
933267411Semaste	if ((args.pa_flags & FLAG_HAS_DURATION) &&
934267411Semaste	    (args.pa_flags & FLAG_DO_TOP))
935267411Semaste		errx(EX_USAGE, "ERROR: options -T and -l are mutually "
936267411Semaste		    "exclusive.");
937267411Semaste
938185322Sattilio	/* -m option is allowed with -R only. */
939203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
940185322Sattilio		errx(EX_USAGE, "ERROR: option -m requires an input file");
941185322Sattilio
942185322Sattilio	/* -m option is not allowed combined with -g or -G. */
943203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE &&
944185322Sattilio	    args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
945237969Sobrien		errx(EX_USAGE,
946237969Sobrien		    "ERROR: option -m and -g | -G are mutually exclusive");
947185322Sattilio
948147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
949147191Sjkoshy		errmsg = NULL;
950147708Sjkoshy		if (args.pa_flags & FLAG_HAS_COMMANDLINE)
951147191Sjkoshy			errmsg = "a command line specification";
952169069Sjkoshy		else if (args.pa_flags & FLAG_HAS_TARGET)
953147191Sjkoshy			errmsg = "option -t";
954169069Sjkoshy		else if (!STAILQ_EMPTY(&args.pa_events))
955147191Sjkoshy			errmsg = "a PMC event specification";
956147191Sjkoshy		if (errmsg)
957237969Sobrien			errx(EX_USAGE,
958237969Sobrien			    "ERROR: option -R may not be used with %s.",
959237969Sobrien			    errmsg);
960169069Sjkoshy	} else if (STAILQ_EMPTY(&args.pa_events))
961147708Sjkoshy		/* All other uses require a PMC spec. */
962145256Sjkoshy		pmcstat_show_usage();
963145256Sjkoshy
964147191Sjkoshy	/* check for -t pid without a process PMC spec */
965169069Sjkoshy	if ((args.pa_required & FLAG_HAS_TARGET) &&
966147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
967237969Sobrien		errx(EX_USAGE,
968237969Sobrien"ERROR: option -t requires a process mode PMC to be specified."
969237969Sobrien		    );
970147191Sjkoshy
971147191Sjkoshy	/* check for process-mode options without a command or -t pid */
972147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
973169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
974237969Sobrien		errx(EX_USAGE,
975237969Sobrien"ERROR: options -d, -E, -p, -P, and -W require a command line or target process."
976237969Sobrien		    );
977147191Sjkoshy
978147191Sjkoshy	/* check for -p | -P without a target process of some sort */
979169069Sjkoshy	if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
980169069Sjkoshy	    (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
981237969Sobrien		errx(EX_USAGE,
982237969Sobrien"ERROR: options -P and -p require a target process or a command line."
983237969Sobrien		    );
984147191Sjkoshy
985147191Sjkoshy	/* check for process-mode options without a process-mode PMC */
986147191Sjkoshy	if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
987147191Sjkoshy	    (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
988237969Sobrien		errx(EX_USAGE,
989237969Sobrien"ERROR: options -d, -E, and -W require a process mode PMC to be specified."
990237969Sobrien		    );
991147191Sjkoshy
992174396Sjkoshy	/* check for -c cpu with no system mode PMCs or logfile. */
993147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
994174396Sjkoshy	    (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
995174396Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
996237969Sobrien		errx(EX_USAGE,
997237969Sobrien"ERROR: option -c requires at least one system mode PMC to be specified."
998237969Sobrien		    );
999147191Sjkoshy
1000147191Sjkoshy	/* check for counting mode options without a counting PMC */
1001147191Sjkoshy	if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
1002147191Sjkoshy	    (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
1003237969Sobrien		errx(EX_USAGE,
1004237969Sobrien"ERROR: options -C, -W and -o require at least one counting mode PMC to be specified."
1005237969Sobrien		    );
1006147191Sjkoshy
1007147191Sjkoshy	/* check for sampling mode options without a sampling PMC spec */
1008147191Sjkoshy	if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
1009147191Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
1010237969Sobrien		errx(EX_USAGE,
1011237969Sobrien"ERROR: options -N, -n and -O require at least one sampling mode PMC to be specified."
1012237969Sobrien		    );
1013147191Sjkoshy
1014203790Sfabient	/* check if -g/-G/-m/-T are being used correctly */
1015174396Sjkoshy	if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
1016147708Sjkoshy	    !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
1017237969Sobrien		errx(EX_USAGE,
1018237969Sobrien"ERROR: options -g/-G/-m/-T require sampling PMCs or -R to be specified."
1019237969Sobrien		    );
1020147708Sjkoshy
1021147191Sjkoshy	/* check if -O was spuriously specified */
1022147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
1023147708Sjkoshy	    (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
1024147191Sjkoshy		errx(EX_USAGE,
1025237969Sobrien"ERROR: option -O is used only with options -E, -P, -S and -W."
1026237969Sobrien		    );
1027147191Sjkoshy
1028203790Sfabient	/* -k kernel path require -g/-G/-m/-T or -R */
1029147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
1030174396Sjkoshy	    (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
1031157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1032203790Sfabient	    errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
1033147708Sjkoshy
1034174396Sjkoshy	/* -D only applies to gprof output mode (-g) */
1035147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
1036174396Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0)
1037174396Sjkoshy	    errx(EX_USAGE, "ERROR: option -D is only used with -g.");
1038147708Sjkoshy
1039157144Sjkoshy	/* -M mapfile requires -g or -R */
1040157144Sjkoshy	if (args.pa_mapfilename != NULL &&
1041157144Sjkoshy	    (args.pa_flags & FLAG_DO_GPROF) == 0 &&
1042157144Sjkoshy	    (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1043157144Sjkoshy	    errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
1044157144Sjkoshy
1045147708Sjkoshy	/*
1046147708Sjkoshy	 * Disallow textual output of sampling PMCs if counting PMCs
1047147708Sjkoshy	 * have also been asked for, mostly because the combined output
1048147708Sjkoshy	 * is difficult to make sense of.
1049147708Sjkoshy	 */
1050147708Sjkoshy	if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1051147708Sjkoshy	    (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1052168927Sjkoshy	    ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
1053237969Sobrien		errx(EX_USAGE,
1054237969Sobrien"ERROR: option -O is required if counting and sampling PMCs are specified together."
1055237969Sobrien		    );
1056147708Sjkoshy
1057157144Sjkoshy	/*
1058174396Sjkoshy	 * Check if "-k kerneldir" was specified, and if whether
1059229888Seadler	 * 'kerneldir' actually refers to a file.  If so, use
1060174396Sjkoshy	 * `dirname path` to determine the kernel directory.
1061157144Sjkoshy	 */
1062157144Sjkoshy	if (args.pa_flags & FLAG_HAS_KERNELPATH) {
1063157144Sjkoshy		(void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
1064157144Sjkoshy		    args.pa_kernel);
1065157144Sjkoshy		if (stat(buffer, &sb) < 0)
1066157144Sjkoshy			err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
1067157144Sjkoshy			    buffer);
1068157144Sjkoshy		if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
1069157144Sjkoshy			errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
1070157144Sjkoshy			    buffer);
1071157144Sjkoshy		if (!S_ISDIR(sb.st_mode)) {
1072157144Sjkoshy			tmp = args.pa_kernel;
1073157144Sjkoshy			args.pa_kernel = strdup(dirname(args.pa_kernel));
1074157144Sjkoshy			free(tmp);
1075157144Sjkoshy			(void) snprintf(buffer, sizeof(buffer), "%s%s",
1076157144Sjkoshy			    args.pa_fsroot, args.pa_kernel);
1077157144Sjkoshy			if (stat(buffer, &sb) < 0)
1078157144Sjkoshy				err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
1079157144Sjkoshy				    buffer);
1080157144Sjkoshy			if (!S_ISDIR(sb.st_mode))
1081237969Sobrien				errx(EX_USAGE,
1082237969Sobrien				    "ERROR: \"%s\" is not a directory.",
1083237969Sobrien				    buffer);
1084157144Sjkoshy		}
1085157144Sjkoshy	}
1086168949Sjkoshy
1087174396Sjkoshy	/*
1088174396Sjkoshy	 * If we have a callgraph be created, select the outputfile.
1089174396Sjkoshy	 */
1090174396Sjkoshy	if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
1091174396Sjkoshy		if (strcmp(graphfilename, "-") == 0)
1092174396Sjkoshy		    args.pa_graphfile = args.pa_printfile;
1093174396Sjkoshy		else {
1094174396Sjkoshy			args.pa_graphfile = fopen(graphfilename, "w");
1095174396Sjkoshy			if (args.pa_graphfile == NULL)
1096237969Sobrien				err(EX_OSERR,
1097237969Sobrien				    "ERROR: cannot open \"%s\" for writing",
1098237969Sobrien				    graphfilename);
1099174396Sjkoshy		}
1100174396Sjkoshy	}
1101203790Sfabient	if (args.pa_flags & FLAG_DO_ANNOTATE) {
1102185322Sattilio		args.pa_graphfile = fopen(graphfilename, "w");
1103185322Sattilio		if (args.pa_graphfile == NULL)
1104185322Sattilio			err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
1105185322Sattilio			    graphfilename);
1106185322Sattilio	}
1107174396Sjkoshy
1108210794Sfabient	/* if we've been asked to process a log file, skip init */
1109210794Sfabient	if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) {
1110210794Sfabient		if (pmc_init() < 0)
1111210794Sfabient			err(EX_UNAVAILABLE,
1112237969Sobrien			    "ERROR: Initialization of the pmc(3) library failed"
1113237969Sobrien			    );
1114210794Sfabient
1115210794Sfabient		if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1116237969Sobrien			err(EX_OSERR,
1117237969Sobrien"ERROR: Cannot determine the number of PMCs on CPU %d",
1118237969Sobrien			    0);
1119210794Sfabient	}
1120210794Sfabient
1121210794Sfabient	/* Allocate a kqueue */
1122210794Sfabient	if ((pmcstat_kq = kqueue()) < 0)
1123210794Sfabient		err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1124210794Sfabient
1125210794Sfabient	/* Setup the logfile as the source. */
1126147708Sjkoshy	if (args.pa_flags & FLAG_READ_LOGFILE) {
1127147708Sjkoshy		/*
1128147708Sjkoshy		 * Print the log in textual form if we haven't been
1129174396Sjkoshy		 * asked to generate profiling information.
1130147708Sjkoshy		 */
1131174396Sjkoshy		if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1132147708Sjkoshy			args.pa_flags |= FLAG_DO_PRINT;
1133147708Sjkoshy
1134203790Sfabient		pmcstat_initialize_logging();
1135210794Sfabient		rfd = pmcstat_open_log(args.pa_inputpath,
1136157406Sjkoshy		    PMCSTAT_OPEN_FOR_READ);
1137210794Sfabient		if ((args.pa_logparser = pmclog_open(rfd)) == NULL)
1138147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot create parser");
1139210794Sfabient		if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0)
1140210794Sfabient			err(EX_OSERR, "ERROR: fcntl(2) failed");
1141210794Sfabient		EV_SET(&kev, rfd, EVFILT_READ, EV_ADD,
1142210794Sfabient		    0, 0, NULL);
1143210794Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1144210794Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1145147191Sjkoshy	}
1146145256Sjkoshy	/*
1147147708Sjkoshy	 * Configure the specified log file or setup a default log
1148147708Sjkoshy	 * consumer via a pipe.
1149147708Sjkoshy	 */
1150147708Sjkoshy	if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1151157406Sjkoshy		if (args.pa_outputpath)
1152157406Sjkoshy			args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1153157406Sjkoshy			    PMCSTAT_OPEN_FOR_WRITE);
1154157406Sjkoshy		else {
1155147708Sjkoshy			/*
1156147708Sjkoshy			 * process the log on the fly by reading it in
1157147708Sjkoshy			 * through a pipe.
1158147708Sjkoshy			 */
1159147708Sjkoshy			if (pipe(pipefd) < 0)
1160147708Sjkoshy				err(EX_OSERR, "ERROR: pipe(2) failed");
1161147708Sjkoshy
1162147708Sjkoshy			if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1163147708Sjkoshy				err(EX_OSERR, "ERROR: fcntl(2) failed");
1164147708Sjkoshy
1165147708Sjkoshy			EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1166147708Sjkoshy			    0, 0, NULL);
1167147708Sjkoshy
1168147708Sjkoshy			if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1169147708Sjkoshy				err(EX_OSERR, "ERROR: Cannot register kevent");
1170147708Sjkoshy
1171147708Sjkoshy			args.pa_logfd = pipefd[WRITEPIPEFD];
1172147708Sjkoshy
1173203790Sfabient			args.pa_flags |= FLAG_HAS_PIPE;
1174203790Sfabient			if ((args.pa_flags & FLAG_DO_TOP) == 0)
1175203790Sfabient				args.pa_flags |= FLAG_DO_PRINT;
1176147708Sjkoshy			args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1177147708Sjkoshy		}
1178147708Sjkoshy
1179147708Sjkoshy		if (pmc_configure_logfile(args.pa_logfd) < 0)
1180147708Sjkoshy			err(EX_OSERR, "ERROR: Cannot configure log file");
1181147708Sjkoshy	}
1182147708Sjkoshy
1183151542Sjkoshy	/* remember to check for driver errors if we are sampling or logging */
1184151542Sjkoshy	check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1185151542Sjkoshy	    (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1186151542Sjkoshy
1187147708Sjkoshy	/*
1188210794Sfabient	if (args.pa_flags & FLAG_READ_LOGFILE) {
1189145256Sjkoshy	 * Allocate PMCs.
1190145256Sjkoshy	 */
1191145256Sjkoshy
1192169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1193237969Sobrien		if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1194147191Sjkoshy		    ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1195237969Sobrien			err(EX_OSERR,
1196237969Sobrien"ERROR: Cannot allocate %s-mode pmc with specification \"%s\"",
1197237969Sobrien			    PMC_IS_SYSTEM_MODE(ev->ev_mode) ?
1198237969Sobrien			    "system" : "process", ev->ev_spec);
1199145256Sjkoshy
1200237969Sobrien		if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1201237969Sobrien		    pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1202237969Sobrien			err(EX_OSERR,
1203237969Sobrien			    "ERROR: Cannot set sampling count for PMC \"%s\"",
1204237969Sobrien			    ev->ev_name);
1205147708Sjkoshy	}
1206147708Sjkoshy
1207145256Sjkoshy	/* compute printout widths */
1208169069Sjkoshy	STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1209145774Sjkoshy		int counter_width;
1210145774Sjkoshy		int display_width;
1211145774Sjkoshy		int header_width;
1212145256Sjkoshy
1213145774Sjkoshy		(void) pmc_width(ev->ev_pmcid, &counter_width);
1214168949Sjkoshy		header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1215145774Sjkoshy		display_width = (int) floor(counter_width / 3.32193) + 1;
1216145256Sjkoshy
1217168949Sjkoshy		if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1218168949Sjkoshy			header_width += 3; /* 2 digit CPU number + '/' */
1219168949Sjkoshy
1220145774Sjkoshy		if (header_width > display_width) {
1221145256Sjkoshy			ev->ev_fieldskip = 0;
1222145774Sjkoshy			ev->ev_fieldwidth = header_width;
1223145256Sjkoshy		} else {
1224145774Sjkoshy			ev->ev_fieldskip = display_width -
1225145774Sjkoshy			    header_width;
1226145774Sjkoshy			ev->ev_fieldwidth = display_width;
1227145256Sjkoshy		}
1228145256Sjkoshy	}
1229145256Sjkoshy
1230145256Sjkoshy	/*
1231145256Sjkoshy	 * If our output is being set to a terminal, register a handler
1232145256Sjkoshy	 * for window size changes.
1233145256Sjkoshy	 */
1234145256Sjkoshy
1235147708Sjkoshy	if (isatty(fileno(args.pa_printfile))) {
1236145256Sjkoshy
1237147708Sjkoshy		if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1238145256Sjkoshy			err(EX_OSERR, "ERROR: Cannot determine window size");
1239145256Sjkoshy
1240145256Sjkoshy		pmcstat_displayheight = ws.ws_row - 1;
1241203790Sfabient		pmcstat_displaywidth  = ws.ws_col - 1;
1242145256Sjkoshy
1243145256Sjkoshy		EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1244145256Sjkoshy
1245145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1246237969Sobrien			err(EX_OSERR,
1247237969Sobrien			    "ERROR: Cannot register kevent for SIGWINCH");
1248203790Sfabient
1249203790Sfabient		args.pa_toptty = 1;
1250145256Sjkoshy	}
1251145256Sjkoshy
1252203790Sfabient	/*
1253203790Sfabient	 * Listen to key input in top mode.
1254203790Sfabient	 */
1255203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1256203790Sfabient		EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1257203790Sfabient		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1258203790Sfabient			err(EX_OSERR, "ERROR: Cannot register kevent");
1259203790Sfabient	}
1260203790Sfabient
1261145256Sjkoshy	EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1262145256Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1263145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1264145256Sjkoshy
1265147191Sjkoshy	EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1266147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1267147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1268145256Sjkoshy
1269147191Sjkoshy	/*
1270147191Sjkoshy	 * An exec() failure of a forked child is signalled by the
1271147191Sjkoshy	 * child sending the parent a SIGCHLD.  We don't register an
1272147191Sjkoshy	 * actual signal handler for SIGCHLD, but instead use our
1273147191Sjkoshy	 * kqueue to pick up the signal.
1274147191Sjkoshy	 */
1275147191Sjkoshy	EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1276147191Sjkoshy	if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1277147191Sjkoshy		err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1278145256Sjkoshy
1279203790Sfabient	/*
1280203790Sfabient	 * Setup a timer if we have counting mode PMCs needing to be printed or
1281203790Sfabient	 * top mode plugin is active.
1282203790Sfabient	 */
1283203790Sfabient	if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1284203790Sfabient	     (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1285203790Sfabient	    (args.pa_flags & FLAG_DO_TOP)) {
1286145256Sjkoshy		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1287145256Sjkoshy		    args.pa_interval * 1000, NULL);
1288145256Sjkoshy
1289145256Sjkoshy		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1290237969Sobrien			err(EX_OSERR,
1291237969Sobrien			    "ERROR: Cannot register kevent for timer");
1292145256Sjkoshy	}
1293145256Sjkoshy
1294267411Semaste	/*
1295267411Semaste	 * Setup a duration timer if we have sampling mode PMCs and
1296267411Semaste	 * a duration time is set
1297267411Semaste	 */
1298267411Semaste	if ((args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1299267411Semaste	    (args.pa_flags & FLAG_HAS_DURATION)) {
1300267411Semaste		EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1301267411Semaste		    args.pa_duration * 1000, NULL);
1302267411Semaste
1303267411Semaste		if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1304267411Semaste			err(EX_OSERR, "ERROR: Cannot register kevent for "
1305267411Semaste			    "time duration");
1306267411Semaste	}
1307267411Semaste
1308145256Sjkoshy	/* attach PMCs to the target process, starting it if specified */
1309168949Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1310203790Sfabient		pmcstat_create_process();
1311145256Sjkoshy
1312151542Sjkoshy	if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1313151542Sjkoshy		err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1314151542Sjkoshy
1315168949Sjkoshy	/* Attach process pmcs to the target process. */
1316180148Sjkoshy	if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1317169069Sjkoshy		if (SLIST_EMPTY(&args.pa_targets))
1318237969Sobrien			errx(EX_DATAERR,
1319237969Sobrien			    "ERROR: No matching target processes.");
1320183672Sjkoshy		if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1321203790Sfabient			pmcstat_attach_pmcs();
1322168949Sjkoshy
1323169069Sjkoshy		if (pmcstat_kvm) {
1324169069Sjkoshy			kvm_close(pmcstat_kvm);
1325169069Sjkoshy			pmcstat_kvm = NULL;
1326169069Sjkoshy		}
1327169069Sjkoshy	}
1328169069Sjkoshy
1329145256Sjkoshy	/* start the pmcs */
1330203790Sfabient	pmcstat_start_pmcs();
1331145256Sjkoshy
1332145256Sjkoshy	/* start the (commandline) process if needed */
1333147708Sjkoshy	if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1334168949Sjkoshy		pmcstat_start_process();
1335145256Sjkoshy
1336210794Sfabient	/* initialize logging */
1337210794Sfabient	pmcstat_initialize_logging();
1338147708Sjkoshy
1339145256Sjkoshy	/* Handle SIGINT using the kqueue loop */
1340145256Sjkoshy	sa.sa_handler = SIG_IGN;
1341145256Sjkoshy	sa.sa_flags   = 0;
1342145256Sjkoshy	(void) sigemptyset(&sa.sa_mask);
1343145256Sjkoshy
1344145256Sjkoshy	if (sigaction(SIGINT, &sa, NULL) < 0)
1345145256Sjkoshy		err(EX_OSERR, "ERROR: Cannot install signal handler");
1346145256Sjkoshy
1347145256Sjkoshy	/*
1348203790Sfabient	 * Setup the top mode display.
1349203790Sfabient	 */
1350203790Sfabient	if (args.pa_flags & FLAG_DO_TOP) {
1351203790Sfabient		args.pa_flags &= ~FLAG_DO_PRINT;
1352203790Sfabient
1353203790Sfabient		if (args.pa_toptty) {
1354203790Sfabient			/*
1355203790Sfabient			 * Init ncurses.
1356203790Sfabient			 */
1357203790Sfabient			initscr();
1358203790Sfabient			if(has_colors() == TRUE) {
1359203790Sfabient				args.pa_topcolor = 1;
1360203790Sfabient				start_color();
1361203790Sfabient				use_default_colors();
1362203790Sfabient				pair_content(0, &cf, &cb);
1363203790Sfabient				init_pair(1, COLOR_RED, cb);
1364203790Sfabient				init_pair(2, COLOR_YELLOW, cb);
1365203790Sfabient				init_pair(3, COLOR_GREEN, cb);
1366203790Sfabient			}
1367203790Sfabient			cbreak();
1368203790Sfabient			noecho();
1369203790Sfabient			nonl();
1370203790Sfabient			nodelay(stdscr, 1);
1371203790Sfabient			intrflush(stdscr, FALSE);
1372203790Sfabient			keypad(stdscr, TRUE);
1373203790Sfabient			clear();
1374204783Sfabient			/* Get terminal width / height with ncurses. */
1375237969Sobrien			getmaxyx(stdscr,
1376237969Sobrien			    pmcstat_displayheight, pmcstat_displaywidth);
1377204783Sfabient			pmcstat_displayheight--; pmcstat_displaywidth--;
1378203790Sfabient			atexit(pmcstat_topexit);
1379203790Sfabient		}
1380203790Sfabient	}
1381203790Sfabient
1382203790Sfabient	/*
1383145256Sjkoshy	 * loop till either the target process (if any) exits, or we
1384267411Semaste	 * are killed by a SIGINT or we reached the time duration.
1385145256Sjkoshy	 */
1386147191Sjkoshy	runstate = PMCSTAT_RUNNING;
1387229392Sfabient	do_print = do_read = 0;
1388145256Sjkoshy	do {
1389145256Sjkoshy		if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1390145256Sjkoshy			if (errno != EINTR)
1391145256Sjkoshy				err(EX_OSERR, "ERROR: kevent failed");
1392145256Sjkoshy			else
1393145256Sjkoshy				continue;
1394145256Sjkoshy		}
1395145256Sjkoshy
1396145256Sjkoshy		if (kev.flags & EV_ERROR)
1397145256Sjkoshy			errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1398145256Sjkoshy
1399145256Sjkoshy		switch (kev.filter) {
1400147191Sjkoshy		case EVFILT_PROC:  /* target has exited */
1401210794Sfabient			runstate = pmcstat_close_log();
1402148688Sjkoshy			do_print = 1;
1403147191Sjkoshy			break;
1404145256Sjkoshy
1405147191Sjkoshy		case EVFILT_READ:  /* log file data is present */
1406210794Sfabient			if (kev.ident == (unsigned)fileno(stdin) &&
1407210794Sfabient			    (args.pa_flags & FLAG_DO_TOP)) {
1408203790Sfabient				if (pmcstat_keypress_log())
1409203790Sfabient					runstate = pmcstat_close_log();
1410229392Sfabient			} else {
1411229392Sfabient				do_read = 0;
1412203790Sfabient				runstate = pmcstat_process_log();
1413229392Sfabient			}
1414145256Sjkoshy			break;
1415145256Sjkoshy
1416145256Sjkoshy		case EVFILT_SIGNAL:
1417147191Sjkoshy			if (kev.ident == SIGCHLD) {
1418147191Sjkoshy				/*
1419147191Sjkoshy				 * The child process sends us a
1420147191Sjkoshy				 * SIGCHLD if its exec() failed.  We
1421147191Sjkoshy				 * wait for it to exit and then exit
1422147191Sjkoshy				 * ourselves.
1423147191Sjkoshy				 */
1424147191Sjkoshy				(void) wait(&c);
1425147191Sjkoshy				runstate = PMCSTAT_FINISHED;
1426147191Sjkoshy			} else if (kev.ident == SIGIO) {
1427147191Sjkoshy				/*
1428147191Sjkoshy				 * We get a SIGIO if a PMC loses all
1429147191Sjkoshy				 * of its targets, or if logfile
1430147191Sjkoshy				 * writes encounter an error.
1431147191Sjkoshy				 */
1432210794Sfabient				runstate = pmcstat_close_log();
1433147191Sjkoshy				do_print = 1; /* print PMCs at exit */
1434147191Sjkoshy			} else if (kev.ident == SIGINT) {
1435147708Sjkoshy				/* Kill the child process if we started it */
1436147708Sjkoshy				if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1437203790Sfabient					pmcstat_kill_process();
1438210794Sfabient				runstate = pmcstat_close_log();
1439145256Sjkoshy			} else if (kev.ident == SIGWINCH) {
1440147708Sjkoshy				if (ioctl(fileno(args.pa_printfile),
1441145256Sjkoshy					TIOCGWINSZ, &ws) < 0)
1442237969Sobrien				    err(EX_OSERR,
1443237969Sobrien				        "ERROR: Cannot determine window size");
1444145256Sjkoshy				pmcstat_displayheight = ws.ws_row - 1;
1445203790Sfabient				pmcstat_displaywidth  = ws.ws_col - 1;
1446145256Sjkoshy			} else
1447145256Sjkoshy				assert(0);
1448145256Sjkoshy
1449145256Sjkoshy			break;
1450147191Sjkoshy
1451267411Semaste		case EVFILT_TIMER:
1452267411Semaste			/* time duration reached, exit */
1453267411Semaste			if (args.pa_flags & FLAG_HAS_DURATION) {
1454267411Semaste				runstate = PMCSTAT_FINISHED;
1455267411Semaste				break;
1456267411Semaste			}
1457267411Semaste			/* print out counting PMCs */
1458229392Sfabient			if ((args.pa_flags & FLAG_DO_TOP) &&
1459236238Sfabient			     pmc_flush_logfile() == 0)
1460229392Sfabient				do_read = 1;
1461147191Sjkoshy			do_print = 1;
1462147191Sjkoshy			break;
1463147191Sjkoshy
1464145256Sjkoshy		}
1465145256Sjkoshy
1466229392Sfabient		if (do_print && !do_read) {
1467203790Sfabient			if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1468203790Sfabient				pmcstat_print_pmcs();
1469237969Sobrien				if (runstate == PMCSTAT_FINISHED &&
1470237969Sobrien				    /* final newline */
1471203790Sfabient				    (args.pa_flags & FLAG_DO_PRINT) == 0)
1472203790Sfabient					(void) fprintf(args.pa_printfile, "\n");
1473203790Sfabient			}
1474203790Sfabient			if (args.pa_flags & FLAG_DO_TOP)
1475203790Sfabient				pmcstat_display_log();
1476147191Sjkoshy			do_print = 0;
1477147191Sjkoshy		}
1478145256Sjkoshy
1479147191Sjkoshy	} while (runstate != PMCSTAT_FINISHED);
1480147191Sjkoshy
1481203790Sfabient	if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1482203790Sfabient		pmcstat_topexit();
1483203790Sfabient		args.pa_toptty = 0;
1484203790Sfabient	}
1485203790Sfabient
1486147191Sjkoshy	/* flush any pending log entries */
1487147708Sjkoshy	if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1488229392Sfabient		pmc_close_logfile();
1489147191Sjkoshy
1490203790Sfabient	pmcstat_cleanup();
1491145256Sjkoshy
1492157144Sjkoshy	free(args.pa_kernel);
1493157144Sjkoshy
1494151542Sjkoshy	/* check if the driver lost any samples or events */
1495151542Sjkoshy	if (check_driver_stats) {
1496151542Sjkoshy		if (pmc_get_driver_stats(&ds_end) < 0)
1497237969Sobrien			err(EX_OSERR,
1498237969Sobrien			    "ERROR: Cannot retrieve driver statistics");
1499157144Sjkoshy		if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1500157144Sjkoshy		    args.pa_verbosity > 0)
1501237969Sobrien			warnx("WARNING: some samples were dropped.\n"
1502237969Sobrien"Please consider tuning the \"kern.hwpmc.nsamples\" tunable."
1503237969Sobrien			    );
1504151542Sjkoshy		if (ds_start.pm_buffer_requests_failed !=
1505157144Sjkoshy		    ds_end.pm_buffer_requests_failed &&
1506157144Sjkoshy		    args.pa_verbosity > 0)
1507237969Sobrien			warnx("WARNING: some events were discarded.\n"
1508237969Sobrien"Please consider tuning the \"kern.hwpmc.nbuffers\" tunable."
1509237969Sobrien			    );
1510151542Sjkoshy	}
1511151542Sjkoshy
1512151542Sjkoshy	exit(EX_OK);
1513145256Sjkoshy}
1514