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