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