]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - usr.sbin/pmcstat/pmcstat.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / usr.sbin / pmcstat / pmcstat.c
1 /*-
2  * Copyright (c) 2003-2008, Joseph Koshy
3  * Copyright (c) 2007 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by A. Joseph Koshy under
7  * sponsorship from the FreeBSD Foundation and Google, Inc.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33
34 #include <sys/param.h>
35 #include <sys/cpuset.h>
36 #include <sys/event.h>
37 #include <sys/queue.h>
38 #include <sys/socket.h>
39 #include <sys/stat.h>
40 #include <sys/sysctl.h>
41 #include <sys/time.h>
42 #include <sys/ttycom.h>
43 #include <sys/user.h>
44 #include <sys/wait.h>
45
46 #include <assert.h>
47 #include <curses.h>
48 #include <err.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <kvm.h>
52 #include <libgen.h>
53 #include <limits.h>
54 #include <math.h>
55 #include <pmc.h>
56 #include <pmclog.h>
57 #include <regex.h>
58 #include <signal.h>
59 #include <stdarg.h>
60 #include <stdint.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <sysexits.h>
65 #include <unistd.h>
66
67 #include "pmcstat.h"
68
69 /*
70  * A given invocation of pmcstat(8) can manage multiple PMCs of both
71  * the system-wide and per-process variety.  Each of these could be in
72  * 'counting mode' or in 'sampling mode'.
73  *
74  * For 'counting mode' PMCs, pmcstat(8) will periodically issue a
75  * pmc_read() at the configured time interval and print out the value
76  * of the requested PMCs.
77  *
78  * For 'sampling mode' PMCs it can log to a file for offline analysis,
79  * or can analyse sampling data "on the fly", either by converting
80  * samples to printed textual form or by creating gprof(1) compatible
81  * profiles, one per program executed.  When creating gprof(1)
82  * profiles it can optionally merge entries from multiple processes
83  * for a given executable into a single profile file.
84  *
85  * pmcstat(8) can also execute a command line and attach PMCs to the
86  * resulting child process.  The protocol used is as follows:
87  *
88  * - parent creates a socketpair for two way communication and
89  *   fork()s.
90  * - subsequently:
91  *
92  *   /Parent/                           /Child/
93  *
94  *   - Wait for childs token.
95  *                                      - Sends token.
96  *                                      - Awaits signal to start.
97  *  - Attaches PMCs to the child's pid
98  *    and starts them. Sets up
99  *    monitoring for the child.
100  *  - Signals child to start.
101  *                                      - Recieves signal, attempts exec().
102  *
103  * After this point normal processing can happen.
104  */
105
106 /* Globals */
107
108 int     pmcstat_interrupt = 0;
109 int     pmcstat_displayheight = DEFAULT_DISPLAY_HEIGHT;
110 int     pmcstat_displaywidth  = DEFAULT_DISPLAY_WIDTH;
111 int     pmcstat_sockpair[NSOCKPAIRFD];
112 int     pmcstat_kq;
113 kvm_t   *pmcstat_kvm;
114 struct kinfo_proc *pmcstat_plist;
115 struct pmcstat_args args;
116
117 static void
118 pmcstat_clone_event_descriptor(struct pmcstat_ev *ev, const cpuset_t *cpumask)
119 {
120         int cpu, mcpu;
121         struct pmcstat_ev *ev_clone;
122
123         mcpu = sizeof(*cpumask) * NBBY;
124         for (cpu = 0; cpu < mcpu; cpu++) {
125                 if (!CPU_ISSET(cpu, cpumask))
126                         continue;
127
128                 if ((ev_clone = malloc(sizeof(*ev_clone))) == NULL)
129                         errx(EX_SOFTWARE, "ERROR: Out of memory");
130                 (void) memset(ev_clone, 0, sizeof(*ev_clone));
131
132                 ev_clone->ev_count = ev->ev_count;
133                 ev_clone->ev_cpu   = cpu;
134                 ev_clone->ev_cumulative = ev->ev_cumulative;
135                 ev_clone->ev_flags = ev->ev_flags;
136                 ev_clone->ev_mode  = ev->ev_mode;
137                 ev_clone->ev_name  = strdup(ev->ev_name);
138                 ev_clone->ev_pmcid = ev->ev_pmcid;
139                 ev_clone->ev_saved = ev->ev_saved;
140                 ev_clone->ev_spec  = strdup(ev->ev_spec);
141
142                 STAILQ_INSERT_TAIL(&args.pa_events, ev_clone, ev_next);
143         }
144 }
145
146 static void
147 pmcstat_get_cpumask(const char *cpuspec, cpuset_t *cpumask)
148 {
149         int cpu;
150         const char *s;
151         char *end;
152
153         CPU_ZERO(cpumask);
154         s = cpuspec;
155
156         do {
157                 cpu = strtol(s, &end, 0);
158                 if (cpu < 0 || end == s)
159                         errx(EX_USAGE,
160                             "ERROR: Illegal CPU specification \"%s\".",
161                             cpuspec);
162                 CPU_SET(cpu, cpumask);
163                 s = end + strspn(end, ", \t");
164         } while (*s);
165 }
166
167 void
168 pmcstat_attach_pmcs(void)
169 {
170         struct pmcstat_ev *ev;
171         struct pmcstat_target *pt;
172         int count;
173
174         /* Attach all process PMCs to target processes. */
175         count = 0;
176         STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
177                 if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
178                         continue;
179                 SLIST_FOREACH(pt, &args.pa_targets, pt_next)
180                         if (pmc_attach(ev->ev_pmcid, pt->pt_pid) == 0)
181                                 count++;
182                         else if (errno != ESRCH)
183                                 err(EX_OSERR,
184 "ERROR: cannot attach pmc \"%s\" to process %d",
185                                     ev->ev_name, (int)pt->pt_pid);
186         }
187
188         if (count == 0)
189                 errx(EX_DATAERR, "ERROR: No processes were attached to.");
190 }
191
192
193 void
194 pmcstat_cleanup(void)
195 {
196         struct pmcstat_ev *ev, *tmp;
197
198         /* release allocated PMCs. */
199         STAILQ_FOREACH_SAFE(ev, &args.pa_events, ev_next, tmp)
200             if (ev->ev_pmcid != PMC_ID_INVALID) {
201                 if (pmc_stop(ev->ev_pmcid) < 0)
202                         err(EX_OSERR, "ERROR: cannot stop pmc 0x%x \"%s\"",
203                             ev->ev_pmcid, ev->ev_name);
204                 if (pmc_release(ev->ev_pmcid) < 0)
205                         err(EX_OSERR, "ERROR: cannot release pmc 0x%x \"%s\"",
206                             ev->ev_pmcid, ev->ev_name);
207                 free(ev->ev_name);
208                 free(ev->ev_spec);
209                 STAILQ_REMOVE(&args.pa_events, ev, pmcstat_ev, ev_next);
210                 free(ev);
211             }
212
213         /* de-configure the log file if present. */
214         if (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
215                 (void) pmc_configure_logfile(-1);
216
217         if (args.pa_logparser) {
218                 pmclog_close(args.pa_logparser);
219                 args.pa_logparser = NULL;
220         }
221
222         pmcstat_shutdown_logging();
223 }
224
225 void
226 pmcstat_create_process(void)
227 {
228         char token;
229         pid_t pid;
230         struct kevent kev;
231         struct pmcstat_target *pt;
232
233         if (socketpair(AF_UNIX, SOCK_STREAM, 0, pmcstat_sockpair) < 0)
234                 err(EX_OSERR, "ERROR: cannot create socket pair");
235
236         switch (pid = fork()) {
237         case -1:
238                 err(EX_OSERR, "ERROR: cannot fork");
239                 /*NOTREACHED*/
240
241         case 0:         /* child */
242                 (void) close(pmcstat_sockpair[PARENTSOCKET]);
243
244                 /* Write a token to tell our parent we've started executing. */
245                 if (write(pmcstat_sockpair[CHILDSOCKET], "+", 1) != 1)
246                         err(EX_OSERR, "ERROR (child): cannot write token");
247
248                 /* Wait for our parent to signal us to start. */
249                 if (read(pmcstat_sockpair[CHILDSOCKET], &token, 1) < 0)
250                         err(EX_OSERR, "ERROR (child): cannot read token");
251                 (void) close(pmcstat_sockpair[CHILDSOCKET]);
252
253                 /* exec() the program requested */
254                 execvp(*args.pa_argv, args.pa_argv);
255                 /* and if that fails, notify the parent */
256                 kill(getppid(), SIGCHLD);
257                 err(EX_OSERR, "ERROR: execvp \"%s\" failed", *args.pa_argv);
258                 /*NOTREACHED*/
259
260         default:        /* parent */
261                 (void) close(pmcstat_sockpair[CHILDSOCKET]);
262                 break;
263         }
264
265         /* Ask to be notified via a kevent when the target process exits. */
266         EV_SET(&kev, pid, EVFILT_PROC, EV_ADD|EV_ONESHOT, NOTE_EXIT, 0,
267             NULL);
268         if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
269                 err(EX_OSERR, "ERROR: cannot monitor child process %d", pid);
270
271         if ((pt = malloc(sizeof(*pt))) == NULL)
272                 errx(EX_SOFTWARE, "ERROR: Out of memory.");
273
274         pt->pt_pid = pid;
275         SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
276
277         /* Wait for the child to signal that its ready to go. */
278         if (read(pmcstat_sockpair[PARENTSOCKET], &token, 1) < 0)
279                 err(EX_OSERR, "ERROR (parent): cannot read token");
280
281         return;
282 }
283
284 void
285 pmcstat_find_targets(const char *spec)
286 {
287         int n, nproc, pid, rv;
288         struct pmcstat_target *pt;
289         char errbuf[_POSIX2_LINE_MAX], *end;
290         static struct kinfo_proc *kp;
291         regex_t reg;
292         regmatch_t regmatch;
293
294         /* First check if we've been given a process id. */
295         pid = strtol(spec, &end, 0);
296         if (end != spec && pid >= 0) {
297                 if ((pt = malloc(sizeof(*pt))) == NULL)
298                         goto outofmemory;
299                 pt->pt_pid = pid;
300                 SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
301                 return;
302         }
303
304         /* Otherwise treat arg as a regular expression naming processes. */
305         if (pmcstat_kvm == NULL) {
306                 if ((pmcstat_kvm = kvm_openfiles(NULL, "/dev/null", NULL, 0,
307                     errbuf)) == NULL)
308                         err(EX_OSERR, "ERROR: Cannot open kernel \"%s\"",
309                             errbuf);
310                 if ((pmcstat_plist = kvm_getprocs(pmcstat_kvm, KERN_PROC_PROC,
311                     0, &nproc)) == NULL)
312                         err(EX_OSERR, "ERROR: Cannot get process list: %s",
313                             kvm_geterr(pmcstat_kvm));
314         } else
315                 nproc = 0;
316
317         if ((rv = regcomp(&reg, spec, REG_EXTENDED|REG_NOSUB)) != 0) {
318                 regerror(rv, &reg, errbuf, sizeof(errbuf));
319                 err(EX_DATAERR, "ERROR: Failed to compile regex \"%s\": %s",
320                     spec, errbuf);
321         }
322
323         for (n = 0, kp = pmcstat_plist; n < nproc; n++, kp++) {
324                 if ((rv = regexec(&reg, kp->ki_comm, 1, &regmatch, 0)) == 0) {
325                         if ((pt = malloc(sizeof(*pt))) == NULL)
326                                 goto outofmemory;
327                         pt->pt_pid = kp->ki_pid;
328                         SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
329                 } else if (rv != REG_NOMATCH) {
330                         regerror(rv, &reg, errbuf, sizeof(errbuf));
331                         errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s",
332                             errbuf);
333                 }
334         }
335
336         regfree(&reg);
337
338         return;
339
340  outofmemory:
341         errx(EX_SOFTWARE, "Out of memory.");
342         /*NOTREACHED*/
343 }
344
345 void
346 pmcstat_kill_process(void)
347 {
348         struct pmcstat_target *pt;
349
350         assert(args.pa_flags & FLAG_HAS_COMMANDLINE);
351
352         /*
353          * If a command line was specified, it would be the very first
354          * in the list, before any other processes specified by -t.
355          */
356         pt = SLIST_FIRST(&args.pa_targets);
357         assert(pt != NULL);
358
359         if (kill(pt->pt_pid, SIGINT) != 0)
360                 err(EX_OSERR, "ERROR: cannot signal child process");
361 }
362
363 void
364 pmcstat_start_pmcs(void)
365 {
366         struct pmcstat_ev *ev;
367
368         STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
369
370             assert(ev->ev_pmcid != PMC_ID_INVALID);
371
372             if (pmc_start(ev->ev_pmcid) < 0) {
373                 warn("ERROR: Cannot start pmc 0x%x \"%s\"",
374                     ev->ev_pmcid, ev->ev_name);
375                 pmcstat_cleanup();
376                 exit(EX_OSERR);
377             }
378         }
379
380 }
381
382 void
383 pmcstat_print_headers(void)
384 {
385         struct pmcstat_ev *ev;
386         int c, w;
387
388         (void) fprintf(args.pa_printfile, PRINT_HEADER_PREFIX);
389
390         STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
391                 if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
392                         continue;
393
394                 c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p';
395
396                 if (ev->ev_fieldskip != 0)
397                         (void) fprintf(args.pa_printfile, "%*s",
398                             ev->ev_fieldskip, "");
399                 w = ev->ev_fieldwidth - ev->ev_fieldskip - 2;
400
401                 if (c == 's')
402                         (void) fprintf(args.pa_printfile, "s/%02d/%-*s ",
403                             ev->ev_cpu, w-3, ev->ev_name);
404                 else
405                         (void) fprintf(args.pa_printfile, "p/%*s ", w,
406                             ev->ev_name);
407         }
408
409         (void) fflush(args.pa_printfile);
410 }
411
412 void
413 pmcstat_print_counters(void)
414 {
415         int extra_width;
416         struct pmcstat_ev *ev;
417         pmc_value_t value;
418
419         extra_width = sizeof(PRINT_HEADER_PREFIX) - 1;
420
421         STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
422
423                 /* skip sampling mode counters */
424                 if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
425                         continue;
426
427                 if (pmc_read(ev->ev_pmcid, &value) < 0)
428                         err(EX_OSERR, "ERROR: Cannot read pmc \"%s\"",
429                             ev->ev_name);
430
431                 (void) fprintf(args.pa_printfile, "%*ju ",
432                     ev->ev_fieldwidth + extra_width,
433                     (uintmax_t) ev->ev_cumulative ? value :
434                     (value - ev->ev_saved));
435
436                 if (ev->ev_cumulative == 0)
437                         ev->ev_saved = value;
438                 extra_width = 0;
439         }
440
441         (void) fflush(args.pa_printfile);
442 }
443
444 /*
445  * Print output
446  */
447
448 void
449 pmcstat_print_pmcs(void)
450 {
451         static int linecount = 0;
452
453         /* check if we need to print a header line */
454         if (++linecount > pmcstat_displayheight) {
455                 (void) fprintf(args.pa_printfile, "\n");
456                 linecount = 1;
457         }
458         if (linecount == 1)
459                 pmcstat_print_headers();
460         (void) fprintf(args.pa_printfile, "\n");
461
462         pmcstat_print_counters();
463
464         return;
465 }
466
467 /*
468  * Do process profiling
469  *
470  * If a pid was specified, attach each allocated PMC to the target
471  * process.  Otherwise, fork a child and attach the PMCs to the child,
472  * and have the child exec() the target program.
473  */
474
475 void
476 pmcstat_start_process(void)
477 {
478         /* Signal the child to proceed. */
479         if (write(pmcstat_sockpair[PARENTSOCKET], "!", 1) != 1)
480                 err(EX_OSERR, "ERROR (parent): write of token failed");
481
482         (void) close(pmcstat_sockpair[PARENTSOCKET]);
483 }
484
485 void
486 pmcstat_show_usage(void)
487 {
488         errx(EX_USAGE,
489             "[options] [commandline]\n"
490             "\t Measure process and/or system performance using hardware\n"
491             "\t performance monitoring counters.\n"
492             "\t Options include:\n"
493             "\t -C\t\t (toggle) show cumulative counts\n"
494             "\t -D path\t create profiles in directory \"path\"\n"
495             "\t -E\t\t (toggle) show counts at process exit\n"
496             "\t -F file\t write a system-wide callgraph (Kcachegrind format)"
497                 " to \"file\"\n"
498             "\t -G file\t write a system-wide callgraph to \"file\"\n"
499             "\t -M file\t print executable/gmon file map to \"file\"\n"
500             "\t -N\t\t (toggle) capture callchains\n"
501             "\t -O file\t send log output to \"file\"\n"
502             "\t -P spec\t allocate a process-private sampling PMC\n"
503             "\t -R file\t read events from \"file\"\n"
504             "\t -S spec\t allocate a system-wide sampling PMC\n"
505             "\t -T\t\t start in top mode\n"
506             "\t -W\t\t (toggle) show counts per context switch\n"
507             "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n"
508             "\t -d\t\t (toggle) track descendants\n"
509             "\t -f spec\t pass \"spec\" to as plugin option\n"
510             "\t -g\t\t produce gprof(1) compatible profiles\n"
511             "\t -k dir\t\t set the path to the kernel\n"
512             "\t -m file\t print sampled PCs to \"file\"\n"
513             "\t -n rate\t set sampling rate\n"
514             "\t -o file\t send print output to \"file\"\n"
515             "\t -p spec\t allocate a process-private counting PMC\n"
516             "\t -q\t\t suppress verbosity\n"
517             "\t -r fsroot\t specify FS root directory\n"
518             "\t -s spec\t allocate a system-wide counting PMC\n"
519             "\t -t process-spec attach to running processes matching "
520                 "\"process-spec\"\n"
521             "\t -v\t\t increase verbosity\n"
522             "\t -w secs\t set printing time interval\n"
523             "\t -z depth\t limit callchain display depth"
524         );
525 }
526
527 /*
528  * At exit handler for top mode
529  */
530
531 void
532 pmcstat_topexit(void)
533 {
534         if (!args.pa_toptty)
535                 return;
536
537         /*
538          * Shutdown ncurses.
539          */
540         clrtoeol();
541         refresh();
542         endwin();
543 }
544
545 /*
546  * Main
547  */
548
549 int
550 main(int argc, char **argv)
551 {
552         cpuset_t cpumask;
553         double interval;
554         int hcpu, option, npmc, ncpu;
555         int c, check_driver_stats, current_cpu, current_sampling_count;
556         int do_callchain, do_descendants, do_logproccsw, do_logprocexit;
557         int do_print, do_read;
558         size_t dummy;
559         int graphdepth;
560         int pipefd[2], rfd;
561         int use_cumulative_counts;
562         short cf, cb;
563         char *end, *tmp;
564         const char *errmsg, *graphfilename;
565         enum pmcstat_state runstate;
566         struct pmc_driverstats ds_start, ds_end;
567         struct pmcstat_ev *ev;
568         struct sigaction sa;
569         struct kevent kev;
570         struct winsize ws;
571         struct stat sb;
572         char buffer[PATH_MAX];
573
574         check_driver_stats      = 0;
575         current_cpu             = 0;
576         current_sampling_count  = DEFAULT_SAMPLE_COUNT;
577         do_callchain            = 1;
578         do_descendants          = 0;
579         do_logproccsw           = 0;
580         do_logprocexit          = 0;
581         use_cumulative_counts   = 0;
582         graphfilename           = "-";
583         args.pa_required        = 0;
584         args.pa_flags           = 0;
585         args.pa_verbosity       = 1;
586         args.pa_logfd           = -1;
587         args.pa_fsroot          = "";
588         args.pa_kernel          = strdup("/boot/kernel");
589         args.pa_samplesdir      = ".";
590         args.pa_printfile       = stderr;
591         args.pa_graphdepth      = DEFAULT_CALLGRAPH_DEPTH;
592         args.pa_graphfile       = NULL;
593         args.pa_interval        = DEFAULT_WAIT_INTERVAL;
594         args.pa_mapfilename     = NULL;
595         args.pa_inputpath       = NULL;
596         args.pa_outputpath      = NULL;
597         args.pa_pplugin         = PMCSTAT_PL_NONE;
598         args.pa_plugin          = PMCSTAT_PL_NONE;
599         args.pa_ctdumpinstr     = 1;
600         args.pa_topmode         = PMCSTAT_TOP_DELTA;
601         args.pa_toptty          = 0;
602         args.pa_topcolor        = 0;
603         args.pa_mergepmc        = 0;
604         STAILQ_INIT(&args.pa_events);
605         SLIST_INIT(&args.pa_targets);
606         bzero(&ds_start, sizeof(ds_start));
607         bzero(&ds_end, sizeof(ds_end));
608         ev = NULL;
609         CPU_ZERO(&cpumask);
610
611         /*
612          * The initial CPU mask specifies all non-halted CPUS in the
613          * system.
614          */
615         dummy = sizeof(int);
616         if (sysctlbyname("hw.ncpu", &ncpu, &dummy, NULL, 0) < 0)
617                 err(EX_OSERR, "ERROR: Cannot determine the number of CPUs");
618         for (hcpu = 0; hcpu < ncpu; hcpu++)
619                 CPU_SET(hcpu, &cpumask);
620
621         while ((option = getopt(argc, argv,
622             "CD:EF:G:M:NO:P:R:S:TWc:df:gk:m:n:o:p:qr:s:t:vw:z:")) != -1)
623                 switch (option) {
624                 case 'C':       /* cumulative values */
625                         use_cumulative_counts = !use_cumulative_counts;
626                         args.pa_required |= FLAG_HAS_COUNTING_PMCS;
627                         break;
628
629                 case 'c':       /* CPU */
630
631                         if (optarg[0] == '*' && optarg[1] == '\0') {
632                                 for (hcpu = 0; hcpu < ncpu; hcpu++)
633                                         CPU_SET(hcpu, &cpumask);
634                         } else
635                                 pmcstat_get_cpumask(optarg, &cpumask);
636
637                         args.pa_flags    |= FLAGS_HAS_CPUMASK;
638                         args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
639                         break;
640
641                 case 'D':
642                         if (stat(optarg, &sb) < 0)
643                                 err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
644                                     optarg);
645                         if (!S_ISDIR(sb.st_mode))
646                                 errx(EX_USAGE,
647                                     "ERROR: \"%s\" is not a directory.",
648                                     optarg);
649                         args.pa_samplesdir = optarg;
650                         args.pa_flags     |= FLAG_HAS_SAMPLESDIR;
651                         args.pa_required  |= FLAG_DO_GPROF;
652                         break;
653
654                 case 'd':       /* toggle descendents */
655                         do_descendants = !do_descendants;
656                         args.pa_required |= FLAG_HAS_PROCESS_PMCS;
657                         break;
658
659                 case 'F':       /* produce a system-wide calltree */
660                         args.pa_flags |= FLAG_DO_CALLGRAPHS;
661                         args.pa_plugin = PMCSTAT_PL_CALLTREE;
662                         graphfilename = optarg;
663                         break;
664
665                 case 'f':       /* plugins options */
666                         if (args.pa_plugin == PMCSTAT_PL_NONE)
667                                 err(EX_USAGE, "ERROR: Need -g/-G/-m/-T.");
668                         pmcstat_pluginconfigure_log(optarg);
669                         break;
670
671                 case 'G':       /* produce a system-wide callgraph */
672                         args.pa_flags |= FLAG_DO_CALLGRAPHS;
673                         args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
674                         graphfilename = optarg;
675                         break;
676
677                 case 'g':       /* produce gprof compatible profiles */
678                         args.pa_flags |= FLAG_DO_GPROF;
679                         args.pa_pplugin = PMCSTAT_PL_CALLGRAPH;
680                         args.pa_plugin  = PMCSTAT_PL_GPROF;
681                         break;
682
683                 case 'k':       /* pathname to the kernel */
684                         free(args.pa_kernel);
685                         args.pa_kernel = strdup(optarg);
686                         args.pa_required |= FLAG_DO_ANALYSIS;
687                         args.pa_flags    |= FLAG_HAS_KERNELPATH;
688                         break;
689
690                 case 'm':
691                         args.pa_flags |= FLAG_DO_ANNOTATE;
692                         args.pa_plugin = PMCSTAT_PL_ANNOTATE;
693                         graphfilename  = optarg;
694                         break;
695
696                 case 'E':       /* log process exit */
697                         do_logprocexit = !do_logprocexit;
698                         args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
699                             FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
700                         break;
701
702                 case 'M':       /* mapfile */
703                         args.pa_mapfilename = optarg;
704                         break;
705
706                 case 'N':
707                         do_callchain = !do_callchain;
708                         args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
709                         break;
710
711                 case 'p':       /* process virtual counting PMC */
712                 case 's':       /* system-wide counting PMC */
713                 case 'P':       /* process virtual sampling PMC */
714                 case 'S':       /* system-wide sampling PMC */
715                         if ((ev = malloc(sizeof(*ev))) == NULL)
716                                 errx(EX_SOFTWARE, "ERROR: Out of memory.");
717
718                         switch (option) {
719                         case 'p': ev->ev_mode = PMC_MODE_TC; break;
720                         case 's': ev->ev_mode = PMC_MODE_SC; break;
721                         case 'P': ev->ev_mode = PMC_MODE_TS; break;
722                         case 'S': ev->ev_mode = PMC_MODE_SS; break;
723                         }
724
725                         if (option == 'P' || option == 'p') {
726                                 args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
727                                 args.pa_required |= (FLAG_HAS_COMMANDLINE |
728                                     FLAG_HAS_TARGET);
729                         }
730
731                         if (option == 'P' || option == 'S') {
732                                 args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
733                                 args.pa_required |= (FLAG_HAS_PIPE |
734                                     FLAG_HAS_OUTPUT_LOGFILE);
735                         }
736
737                         if (option == 'p' || option == 's')
738                                 args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
739
740                         if (option == 's' || option == 'S')
741                                 args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
742
743                         ev->ev_spec  = strdup(optarg);
744
745                         if (option == 'S' || option == 'P')
746                                 ev->ev_count = current_sampling_count;
747                         else
748                                 ev->ev_count = -1;
749
750                         if (option == 'S' || option == 's') {
751                                 hcpu = sizeof(cpumask) * NBBY;
752                                 for (hcpu--; hcpu >= 0; hcpu--)
753                                         if (CPU_ISSET(hcpu, &cpumask))
754                                                 break;
755                                 ev->ev_cpu = hcpu;
756                         } else
757                                 ev->ev_cpu = PMC_CPU_ANY;
758
759                         ev->ev_flags = 0;
760                         if (do_callchain)
761                                 ev->ev_flags |= PMC_F_CALLCHAIN;
762                         if (do_descendants)
763                                 ev->ev_flags |= PMC_F_DESCENDANTS;
764                         if (do_logprocexit)
765                                 ev->ev_flags |= PMC_F_LOG_PROCEXIT;
766                         if (do_logproccsw)
767                                 ev->ev_flags |= PMC_F_LOG_PROCCSW;
768
769                         ev->ev_cumulative  = use_cumulative_counts;
770
771                         ev->ev_saved = 0LL;
772                         ev->ev_pmcid = PMC_ID_INVALID;
773
774                         /* extract event name */
775                         c = strcspn(optarg, ", \t");
776                         ev->ev_name = malloc(c + 1);
777                         (void) strncpy(ev->ev_name, optarg, c);
778                         *(ev->ev_name + c) = '\0';
779
780                         STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
781
782                         if (option == 's' || option == 'S') {
783                                 hcpu = CPU_ISSET(ev->ev_cpu, &cpumask);
784                                 CPU_CLR(ev->ev_cpu, &cpumask);
785                                 pmcstat_clone_event_descriptor(ev, &cpumask);
786                                 if (hcpu != 0)
787                                         CPU_SET(ev->ev_cpu, &cpumask);
788                         }
789
790                         break;
791
792                 case 'n':       /* sampling count */
793                         current_sampling_count = strtol(optarg, &end, 0);
794                         if (*end != '\0' || current_sampling_count <= 0)
795                                 errx(EX_USAGE,
796                                     "ERROR: Illegal count value \"%s\".",
797                                     optarg);
798                         args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
799                         break;
800
801                 case 'o':       /* outputfile */
802                         if (args.pa_printfile != NULL &&
803                             args.pa_printfile != stdout &&
804                             args.pa_printfile != stderr)
805                                 (void) fclose(args.pa_printfile);
806                         if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
807                                 errx(EX_OSERR,
808                                     "ERROR: cannot open \"%s\" for writing.",
809                                     optarg);
810                         args.pa_flags |= FLAG_DO_PRINT;
811                         break;
812
813                 case 'O':       /* sampling output */
814                         if (args.pa_outputpath)
815                                 errx(EX_USAGE,
816 "ERROR: option -O may only be specified once.");
817                         args.pa_outputpath = optarg;
818                         args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
819                         break;
820
821                 case 'q':       /* quiet mode */
822                         args.pa_verbosity = 0;
823                         break;
824
825                 case 'r':       /* root FS path */
826                         args.pa_fsroot = optarg;
827                         break;
828
829                 case 'R':       /* read an existing log file */
830                         if (args.pa_inputpath != NULL)
831                                 errx(EX_USAGE,
832 "ERROR: option -R may only be specified once.");
833                         args.pa_inputpath = optarg;
834                         if (args.pa_printfile == stderr)
835                                 args.pa_printfile = stdout;
836                         args.pa_flags |= FLAG_READ_LOGFILE;
837                         break;
838
839                 case 't':       /* target pid or process name */
840                         pmcstat_find_targets(optarg);
841
842                         args.pa_flags |= FLAG_HAS_TARGET;
843                         args.pa_required |= FLAG_HAS_PROCESS_PMCS;
844                         break;
845
846                 case 'T':       /* top mode */
847                         args.pa_flags |= FLAG_DO_TOP;
848                         args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
849                         args.pa_ctdumpinstr = 0;
850                         args.pa_mergepmc = 1;
851                         if (args.pa_printfile == stderr)
852                                 args.pa_printfile = stdout;
853                         break;
854
855                 case 'v':       /* verbose */
856                         args.pa_verbosity++;
857                         break;
858
859                 case 'w':       /* wait interval */
860                         interval = strtod(optarg, &end);
861                         if (*end != '\0' || interval <= 0)
862                                 errx(EX_USAGE,
863 "ERROR: Illegal wait interval value \"%s\".",
864                                     optarg);
865                         args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
866                         args.pa_interval = interval;
867                         break;
868
869                 case 'W':       /* toggle LOG_CSW */
870                         do_logproccsw = !do_logproccsw;
871                         args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
872                             FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
873                         break;
874
875                 case 'z':
876                         graphdepth = strtod(optarg, &end);
877                         if (*end != '\0' || graphdepth <= 0)
878                                 errx(EX_USAGE,
879                                     "ERROR: Illegal callchain depth \"%s\".",
880                                     optarg);
881                         args.pa_graphdepth = graphdepth;
882                         args.pa_required |= FLAG_DO_CALLGRAPHS;
883                         break;
884
885                 case '?':
886                 default:
887                         pmcstat_show_usage();
888                         break;
889
890                 }
891
892         args.pa_argc = (argc -= optind);
893         args.pa_argv = (argv += optind);
894
895         /* If we read from logfile and no specified CPU mask use
896          * the maximum CPU count.
897          */
898         if ((args.pa_flags & FLAG_READ_LOGFILE) &&
899             (args.pa_flags & FLAGS_HAS_CPUMASK) == 0)
900                 CPU_FILL(&cpumask);
901
902         args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
903
904         if (argc)       /* command line present */
905                 args.pa_flags |= FLAG_HAS_COMMANDLINE;
906
907         if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
908             FLAG_DO_ANNOTATE | FLAG_DO_TOP))
909                 args.pa_flags |= FLAG_DO_ANALYSIS;
910
911         /*
912          * Check invocation syntax.
913          */
914
915         /* disallow -O and -R together */
916         if (args.pa_outputpath && args.pa_inputpath)
917                 errx(EX_USAGE,
918                     "ERROR: options -O and -R are mutually exclusive.");
919
920         /* -m option is allowed with -R only. */
921         if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
922                 errx(EX_USAGE, "ERROR: option -m requires an input file");
923
924         /* -m option is not allowed combined with -g or -G. */
925         if (args.pa_flags & FLAG_DO_ANNOTATE &&
926             args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
927                 errx(EX_USAGE,
928                     "ERROR: option -m and -g | -G are mutually exclusive");
929
930         if (args.pa_flags & FLAG_READ_LOGFILE) {
931                 errmsg = NULL;
932                 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
933                         errmsg = "a command line specification";
934                 else if (args.pa_flags & FLAG_HAS_TARGET)
935                         errmsg = "option -t";
936                 else if (!STAILQ_EMPTY(&args.pa_events))
937                         errmsg = "a PMC event specification";
938                 if (errmsg)
939                         errx(EX_USAGE,
940                             "ERROR: option -R may not be used with %s.",
941                             errmsg);
942         } else if (STAILQ_EMPTY(&args.pa_events))
943                 /* All other uses require a PMC spec. */
944                 pmcstat_show_usage();
945
946         /* check for -t pid without a process PMC spec */
947         if ((args.pa_required & FLAG_HAS_TARGET) &&
948             (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
949                 errx(EX_USAGE,
950 "ERROR: option -t requires a process mode PMC to be specified."
951                     );
952
953         /* check for process-mode options without a command or -t pid */
954         if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
955             (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
956                 errx(EX_USAGE,
957 "ERROR: options -d, -E, -p, -P, and -W require a command line or target process."
958                     );
959
960         /* check for -p | -P without a target process of some sort */
961         if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
962             (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
963                 errx(EX_USAGE,
964 "ERROR: options -P and -p require a target process or a command line."
965                     );
966
967         /* check for process-mode options without a process-mode PMC */
968         if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
969             (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
970                 errx(EX_USAGE,
971 "ERROR: options -d, -E, and -W require a process mode PMC to be specified."
972                     );
973
974         /* check for -c cpu with no system mode PMCs or logfile. */
975         if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
976             (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
977             (args.pa_flags & FLAG_READ_LOGFILE) == 0)
978                 errx(EX_USAGE,
979 "ERROR: option -c requires at least one system mode PMC to be specified."
980                     );
981
982         /* check for counting mode options without a counting PMC */
983         if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
984             (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
985                 errx(EX_USAGE,
986 "ERROR: options -C, -W and -o require at least one counting mode PMC to be specified."
987                     );
988
989         /* check for sampling mode options without a sampling PMC spec */
990         if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
991             (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
992                 errx(EX_USAGE,
993 "ERROR: options -N, -n and -O require at least one sampling mode PMC to be specified."
994                     );
995
996         /* check if -g/-G/-m/-T are being used correctly */
997         if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
998             !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
999                 errx(EX_USAGE,
1000 "ERROR: options -g/-G/-m/-T require sampling PMCs or -R to be specified."
1001                     );
1002
1003         /* check if -O was spuriously specified */
1004         if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
1005             (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
1006                 errx(EX_USAGE,
1007 "ERROR: option -O is used only with options -E, -P, -S and -W."
1008                     );
1009
1010         /* -k kernel path require -g/-G/-m/-T or -R */
1011         if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
1012             (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
1013             (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1014             errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
1015
1016         /* -D only applies to gprof output mode (-g) */
1017         if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
1018             (args.pa_flags & FLAG_DO_GPROF) == 0)
1019             errx(EX_USAGE, "ERROR: option -D is only used with -g.");
1020
1021         /* -M mapfile requires -g or -R */
1022         if (args.pa_mapfilename != NULL &&
1023             (args.pa_flags & FLAG_DO_GPROF) == 0 &&
1024             (args.pa_flags & FLAG_READ_LOGFILE) == 0)
1025             errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
1026
1027         /*
1028          * Disallow textual output of sampling PMCs if counting PMCs
1029          * have also been asked for, mostly because the combined output
1030          * is difficult to make sense of.
1031          */
1032         if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1033             (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1034             ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
1035                 errx(EX_USAGE,
1036 "ERROR: option -O is required if counting and sampling PMCs are specified together."
1037                     );
1038
1039         /*
1040          * Check if "-k kerneldir" was specified, and if whether
1041          * 'kerneldir' actually refers to a file.  If so, use
1042          * `dirname path` to determine the kernel directory.
1043          */
1044         if (args.pa_flags & FLAG_HAS_KERNELPATH) {
1045                 (void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
1046                     args.pa_kernel);
1047                 if (stat(buffer, &sb) < 0)
1048                         err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
1049                             buffer);
1050                 if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
1051                         errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
1052                             buffer);
1053                 if (!S_ISDIR(sb.st_mode)) {
1054                         tmp = args.pa_kernel;
1055                         args.pa_kernel = strdup(dirname(args.pa_kernel));
1056                         free(tmp);
1057                         (void) snprintf(buffer, sizeof(buffer), "%s%s",
1058                             args.pa_fsroot, args.pa_kernel);
1059                         if (stat(buffer, &sb) < 0)
1060                                 err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
1061                                     buffer);
1062                         if (!S_ISDIR(sb.st_mode))
1063                                 errx(EX_USAGE,
1064                                     "ERROR: \"%s\" is not a directory.",
1065                                     buffer);
1066                 }
1067         }
1068
1069         /*
1070          * If we have a callgraph be created, select the outputfile.
1071          */
1072         if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
1073                 if (strcmp(graphfilename, "-") == 0)
1074                     args.pa_graphfile = args.pa_printfile;
1075                 else {
1076                         args.pa_graphfile = fopen(graphfilename, "w");
1077                         if (args.pa_graphfile == NULL)
1078                                 err(EX_OSERR,
1079                                     "ERROR: cannot open \"%s\" for writing",
1080                                     graphfilename);
1081                 }
1082         }
1083         if (args.pa_flags & FLAG_DO_ANNOTATE) {
1084                 args.pa_graphfile = fopen(graphfilename, "w");
1085                 if (args.pa_graphfile == NULL)
1086                         err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
1087                             graphfilename);
1088         }
1089
1090         /* if we've been asked to process a log file, skip init */
1091         if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) {
1092                 if (pmc_init() < 0)
1093                         err(EX_UNAVAILABLE,
1094                             "ERROR: Initialization of the pmc(3) library failed"
1095                             );
1096
1097                 if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1098                         err(EX_OSERR,
1099 "ERROR: Cannot determine the number of PMCs on CPU %d",
1100                             0);
1101         }
1102
1103         /* Allocate a kqueue */
1104         if ((pmcstat_kq = kqueue()) < 0)
1105                 err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1106
1107         /* Setup the logfile as the source. */
1108         if (args.pa_flags & FLAG_READ_LOGFILE) {
1109                 /*
1110                  * Print the log in textual form if we haven't been
1111                  * asked to generate profiling information.
1112                  */
1113                 if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1114                         args.pa_flags |= FLAG_DO_PRINT;
1115
1116                 pmcstat_initialize_logging();
1117                 rfd = pmcstat_open_log(args.pa_inputpath,
1118                     PMCSTAT_OPEN_FOR_READ);
1119                 if ((args.pa_logparser = pmclog_open(rfd)) == NULL)
1120                         err(EX_OSERR, "ERROR: Cannot create parser");
1121                 if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0)
1122                         err(EX_OSERR, "ERROR: fcntl(2) failed");
1123                 EV_SET(&kev, rfd, EVFILT_READ, EV_ADD,
1124                     0, 0, NULL);
1125                 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1126                         err(EX_OSERR, "ERROR: Cannot register kevent");
1127         }
1128         /*
1129          * Configure the specified log file or setup a default log
1130          * consumer via a pipe.
1131          */
1132         if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1133                 if (args.pa_outputpath)
1134                         args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1135                             PMCSTAT_OPEN_FOR_WRITE);
1136                 else {
1137                         /*
1138                          * process the log on the fly by reading it in
1139                          * through a pipe.
1140                          */
1141                         if (pipe(pipefd) < 0)
1142                                 err(EX_OSERR, "ERROR: pipe(2) failed");
1143
1144                         if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1145                                 err(EX_OSERR, "ERROR: fcntl(2) failed");
1146
1147                         EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1148                             0, 0, NULL);
1149
1150                         if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1151                                 err(EX_OSERR, "ERROR: Cannot register kevent");
1152
1153                         args.pa_logfd = pipefd[WRITEPIPEFD];
1154
1155                         args.pa_flags |= FLAG_HAS_PIPE;
1156                         if ((args.pa_flags & FLAG_DO_TOP) == 0)
1157                                 args.pa_flags |= FLAG_DO_PRINT;
1158                         args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1159                 }
1160
1161                 if (pmc_configure_logfile(args.pa_logfd) < 0)
1162                         err(EX_OSERR, "ERROR: Cannot configure log file");
1163         }
1164
1165         /* remember to check for driver errors if we are sampling or logging */
1166         check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1167             (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1168
1169         /*
1170         if (args.pa_flags & FLAG_READ_LOGFILE) {
1171          * Allocate PMCs.
1172          */
1173
1174         STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1175                 if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1176                     ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1177                         err(EX_OSERR,
1178 "ERROR: Cannot allocate %s-mode pmc with specification \"%s\"",
1179                             PMC_IS_SYSTEM_MODE(ev->ev_mode) ?
1180                             "system" : "process", ev->ev_spec);
1181
1182                 if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1183                     pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1184                         err(EX_OSERR,
1185                             "ERROR: Cannot set sampling count for PMC \"%s\"",
1186                             ev->ev_name);
1187         }
1188
1189         /* compute printout widths */
1190         STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1191                 int counter_width;
1192                 int display_width;
1193                 int header_width;
1194
1195                 (void) pmc_width(ev->ev_pmcid, &counter_width);
1196                 header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1197                 display_width = (int) floor(counter_width / 3.32193) + 1;
1198
1199                 if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1200                         header_width += 3; /* 2 digit CPU number + '/' */
1201
1202                 if (header_width > display_width) {
1203                         ev->ev_fieldskip = 0;
1204                         ev->ev_fieldwidth = header_width;
1205                 } else {
1206                         ev->ev_fieldskip = display_width -
1207                             header_width;
1208                         ev->ev_fieldwidth = display_width;
1209                 }
1210         }
1211
1212         /*
1213          * If our output is being set to a terminal, register a handler
1214          * for window size changes.
1215          */
1216
1217         if (isatty(fileno(args.pa_printfile))) {
1218
1219                 if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1220                         err(EX_OSERR, "ERROR: Cannot determine window size");
1221
1222                 pmcstat_displayheight = ws.ws_row - 1;
1223                 pmcstat_displaywidth  = ws.ws_col - 1;
1224
1225                 EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1226
1227                 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1228                         err(EX_OSERR,
1229                             "ERROR: Cannot register kevent for SIGWINCH");
1230
1231                 args.pa_toptty = 1;
1232         }
1233
1234         /*
1235          * Listen to key input in top mode.
1236          */
1237         if (args.pa_flags & FLAG_DO_TOP) {
1238                 EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1239                 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1240                         err(EX_OSERR, "ERROR: Cannot register kevent");
1241         }
1242
1243         EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1244         if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1245                 err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1246
1247         EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1248         if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1249                 err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1250
1251         /*
1252          * An exec() failure of a forked child is signalled by the
1253          * child sending the parent a SIGCHLD.  We don't register an
1254          * actual signal handler for SIGCHLD, but instead use our
1255          * kqueue to pick up the signal.
1256          */
1257         EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1258         if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1259                 err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1260
1261         /* 
1262          * Setup a timer if we have counting mode PMCs needing to be printed or
1263          * top mode plugin is active.
1264          */
1265         if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1266              (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1267             (args.pa_flags & FLAG_DO_TOP)) {
1268                 EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1269                     args.pa_interval * 1000, NULL);
1270
1271                 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1272                         err(EX_OSERR,
1273                             "ERROR: Cannot register kevent for timer");
1274         }
1275
1276         /* attach PMCs to the target process, starting it if specified */
1277         if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1278                 pmcstat_create_process();
1279
1280         if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1281                 err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1282
1283         /* Attach process pmcs to the target process. */
1284         if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1285                 if (SLIST_EMPTY(&args.pa_targets))
1286                         errx(EX_DATAERR,
1287                             "ERROR: No matching target processes.");
1288                 if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1289                         pmcstat_attach_pmcs();
1290
1291                 if (pmcstat_kvm) {
1292                         kvm_close(pmcstat_kvm);
1293                         pmcstat_kvm = NULL;
1294                 }
1295         }
1296
1297         /* start the pmcs */
1298         pmcstat_start_pmcs();
1299
1300         /* start the (commandline) process if needed */
1301         if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1302                 pmcstat_start_process();
1303
1304         /* initialize logging */
1305         pmcstat_initialize_logging();
1306
1307         /* Handle SIGINT using the kqueue loop */
1308         sa.sa_handler = SIG_IGN;
1309         sa.sa_flags   = 0;
1310         (void) sigemptyset(&sa.sa_mask);
1311
1312         if (sigaction(SIGINT, &sa, NULL) < 0)
1313                 err(EX_OSERR, "ERROR: Cannot install signal handler");
1314
1315         /*
1316          * Setup the top mode display.
1317          */
1318         if (args.pa_flags & FLAG_DO_TOP) {
1319                 args.pa_flags &= ~FLAG_DO_PRINT;
1320
1321                 if (args.pa_toptty) {
1322                         /*
1323                          * Init ncurses.
1324                          */
1325                         initscr();
1326                         if(has_colors() == TRUE) {
1327                                 args.pa_topcolor = 1;
1328                                 start_color();
1329                                 use_default_colors();
1330                                 pair_content(0, &cf, &cb);
1331                                 init_pair(1, COLOR_RED, cb);
1332                                 init_pair(2, COLOR_YELLOW, cb);
1333                                 init_pair(3, COLOR_GREEN, cb);
1334                         }
1335                         cbreak();
1336                         noecho();
1337                         nonl();
1338                         nodelay(stdscr, 1);
1339                         intrflush(stdscr, FALSE);
1340                         keypad(stdscr, TRUE);
1341                         clear();
1342                         /* Get terminal width / height with ncurses. */
1343                         getmaxyx(stdscr,
1344                             pmcstat_displayheight, pmcstat_displaywidth);
1345                         pmcstat_displayheight--; pmcstat_displaywidth--;
1346                         atexit(pmcstat_topexit);
1347                 }
1348         }
1349
1350         /*
1351          * loop till either the target process (if any) exits, or we
1352          * are killed by a SIGINT.
1353          */
1354         runstate = PMCSTAT_RUNNING;
1355         do_print = do_read = 0;
1356         do {
1357                 if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1358                         if (errno != EINTR)
1359                                 err(EX_OSERR, "ERROR: kevent failed");
1360                         else
1361                                 continue;
1362                 }
1363
1364                 if (kev.flags & EV_ERROR)
1365                         errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1366
1367                 switch (kev.filter) {
1368                 case EVFILT_PROC:  /* target has exited */
1369                         runstate = pmcstat_close_log();
1370                         do_print = 1;
1371                         break;
1372
1373                 case EVFILT_READ:  /* log file data is present */
1374                         if (kev.ident == (unsigned)fileno(stdin) &&
1375                             (args.pa_flags & FLAG_DO_TOP)) {
1376                                 if (pmcstat_keypress_log())
1377                                         runstate = pmcstat_close_log();
1378                         } else {
1379                                 do_read = 0;
1380                                 runstate = pmcstat_process_log();
1381                         }
1382                         break;
1383
1384                 case EVFILT_SIGNAL:
1385                         if (kev.ident == SIGCHLD) {
1386                                 /*
1387                                  * The child process sends us a
1388                                  * SIGCHLD if its exec() failed.  We
1389                                  * wait for it to exit and then exit
1390                                  * ourselves.
1391                                  */
1392                                 (void) wait(&c);
1393                                 runstate = PMCSTAT_FINISHED;
1394                         } else if (kev.ident == SIGIO) {
1395                                 /*
1396                                  * We get a SIGIO if a PMC loses all
1397                                  * of its targets, or if logfile
1398                                  * writes encounter an error.
1399                                  */
1400                                 runstate = pmcstat_close_log();
1401                                 do_print = 1; /* print PMCs at exit */
1402                         } else if (kev.ident == SIGINT) {
1403                                 /* Kill the child process if we started it */
1404                                 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1405                                         pmcstat_kill_process();
1406                                 runstate = pmcstat_close_log();
1407                         } else if (kev.ident == SIGWINCH) {
1408                                 if (ioctl(fileno(args.pa_printfile),
1409                                         TIOCGWINSZ, &ws) < 0)
1410                                     err(EX_OSERR,
1411                                         "ERROR: Cannot determine window size");
1412                                 pmcstat_displayheight = ws.ws_row - 1;
1413                                 pmcstat_displaywidth  = ws.ws_col - 1;
1414                         } else
1415                                 assert(0);
1416
1417                         break;
1418
1419                 case EVFILT_TIMER: /* print out counting PMCs */
1420                         if ((args.pa_flags & FLAG_DO_TOP) &&
1421                              pmc_flush_logfile() == 0)
1422                                 do_read = 1;
1423                         do_print = 1;
1424                         break;
1425
1426                 }
1427
1428                 if (do_print && !do_read) {
1429                         if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1430                                 pmcstat_print_pmcs();
1431                                 if (runstate == PMCSTAT_FINISHED &&
1432                                     /* final newline */
1433                                     (args.pa_flags & FLAG_DO_PRINT) == 0)
1434                                         (void) fprintf(args.pa_printfile, "\n");
1435                         }
1436                         if (args.pa_flags & FLAG_DO_TOP)
1437                                 pmcstat_display_log();
1438                         do_print = 0;
1439                 }
1440
1441         } while (runstate != PMCSTAT_FINISHED);
1442
1443         if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1444                 pmcstat_topexit();
1445                 args.pa_toptty = 0;
1446         }
1447
1448         /* flush any pending log entries */
1449         if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1450                 pmc_close_logfile();
1451
1452         pmcstat_cleanup();
1453
1454         free(args.pa_kernel);
1455
1456         /* check if the driver lost any samples or events */
1457         if (check_driver_stats) {
1458                 if (pmc_get_driver_stats(&ds_end) < 0)
1459                         err(EX_OSERR,
1460                             "ERROR: Cannot retrieve driver statistics");
1461                 if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1462                     args.pa_verbosity > 0)
1463                         warnx("WARNING: some samples were dropped.\n"
1464 "Please consider tuning the \"kern.hwpmc.nsamples\" tunable."
1465                             );
1466                 if (ds_start.pm_buffer_requests_failed !=
1467                     ds_end.pm_buffer_requests_failed &&
1468                     args.pa_verbosity > 0)
1469                         warnx("WARNING: some events were discarded.\n"
1470 "Please consider tuning the \"kern.hwpmc.nbuffers\" tunable."
1471                             );
1472         }
1473
1474         exit(EX_OK);
1475 }