2 * Copyright (c) 2003-2008, Joseph Koshy
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
30 #include <sys/types.h>
31 #include <sys/event.h>
32 #include <sys/param.h>
33 #include <sys/queue.h>
34 #include <sys/socket.h>
36 #include <sys/sysctl.h>
38 #include <sys/ttycom.h>
65 * A given invocation of pmcstat(8) can manage multiple PMCs of both
66 * the system-wide and per-process variety. Each of these could be in
67 * 'counting mode' or in 'sampling mode'.
69 * For 'counting mode' PMCs, pmcstat(8) will periodically issue a
70 * pmc_read() at the configured time interval and print out the value
71 * of the requested PMCs.
73 * For 'sampling mode' PMCs it can log to a file for offline analysis,
74 * or can analyse sampling data "on the fly", either by converting
75 * samples to printed textual form or by creating gprof(1) compatible
76 * profiles, one per program executed. When creating gprof(1)
77 * profiles it can optionally merge entries from multiple processes
78 * for a given executable into a single profile file.
80 * pmcstat(8) can also execute a command line and attach PMCs to the
81 * resulting child process. The protocol used is as follows:
83 * - parent creates a socketpair for two way communication and
89 * - Wait for childs token.
91 * - Awaits signal to start.
92 * - Attaches PMCs to the child's pid
93 * and starts them. Sets up
94 * monitoring for the child.
95 * - Signals child to start.
96 * - Recieves signal, attempts exec().
98 * After this point normal processing can happen.
103 int pmcstat_interrupt = 0;
104 int pmcstat_displayheight = DEFAULT_DISPLAY_HEIGHT;
105 int pmcstat_sockpair[NSOCKPAIRFD];
108 struct kinfo_proc *pmcstat_plist;
111 pmcstat_attach_pmcs(struct pmcstat_args *a)
113 struct pmcstat_ev *ev;
114 struct pmcstat_target *pt;
117 /* Attach all process PMCs to target processes. */
119 STAILQ_FOREACH(ev, &a->pa_events, ev_next) {
120 if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
122 SLIST_FOREACH(pt, &a->pa_targets, pt_next)
123 if (pmc_attach(ev->ev_pmcid, pt->pt_pid) == 0)
125 else if (errno != ESRCH)
126 err(EX_OSERR, "ERROR: cannot attach pmc "
127 "\"%s\" to process %d", ev->ev_name,
132 errx(EX_DATAERR, "ERROR: No processes were attached to.");
137 pmcstat_cleanup(struct pmcstat_args *a)
139 struct pmcstat_ev *ev, *tmp;
141 /* release allocated PMCs. */
142 STAILQ_FOREACH_SAFE(ev, &a->pa_events, ev_next, tmp)
143 if (ev->ev_pmcid != PMC_ID_INVALID) {
144 if (pmc_release(ev->ev_pmcid) < 0)
145 err(EX_OSERR, "ERROR: cannot release pmc "
146 "0x%x \"%s\"", ev->ev_pmcid, ev->ev_name);
149 STAILQ_REMOVE(&a->pa_events, ev, pmcstat_ev, ev_next);
153 /* de-configure the log file if present. */
154 if (a->pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
155 (void) pmc_configure_logfile(-1);
157 if (a->pa_logparser) {
158 pmclog_close(a->pa_logparser);
159 a->pa_logparser = NULL;
162 if (a->pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
163 pmcstat_shutdown_logging(a);
167 pmcstat_clone_event_descriptor(struct pmcstat_args *a, struct pmcstat_ev *ev,
171 struct pmcstat_ev *ev_clone;
173 while ((cpu = ffs(cpumask)) > 0) {
176 if ((ev_clone = malloc(sizeof(*ev_clone))) == NULL)
177 errx(EX_SOFTWARE, "ERROR: Out of memory");
178 (void) memset(ev_clone, 0, sizeof(*ev_clone));
180 ev_clone->ev_count = ev->ev_count;
181 ev_clone->ev_cpu = cpu;
182 ev_clone->ev_cumulative = ev->ev_cumulative;
183 ev_clone->ev_flags = ev->ev_flags;
184 ev_clone->ev_mode = ev->ev_mode;
185 ev_clone->ev_name = strdup(ev->ev_name);
186 ev_clone->ev_pmcid = ev->ev_pmcid;
187 ev_clone->ev_saved = ev->ev_saved;
188 ev_clone->ev_spec = strdup(ev->ev_spec);
190 STAILQ_INSERT_TAIL(&a->pa_events, ev_clone, ev_next);
192 cpumask &= ~(1 << cpu);
197 pmcstat_create_process(struct pmcstat_args *a)
202 struct pmcstat_target *pt;
204 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pmcstat_sockpair) < 0)
205 err(EX_OSERR, "ERROR: cannot create socket pair");
207 switch (pid = fork()) {
209 err(EX_OSERR, "ERROR: cannot fork");
213 (void) close(pmcstat_sockpair[PARENTSOCKET]);
215 /* Write a token to tell our parent we've started executing. */
216 if (write(pmcstat_sockpair[CHILDSOCKET], "+", 1) != 1)
217 err(EX_OSERR, "ERROR (child): cannot write token");
219 /* Wait for our parent to signal us to start. */
220 if (read(pmcstat_sockpair[CHILDSOCKET], &token, 1) < 0)
221 err(EX_OSERR, "ERROR (child): cannot read token");
222 (void) close(pmcstat_sockpair[CHILDSOCKET]);
224 /* exec() the program requested */
225 execvp(*a->pa_argv, a->pa_argv);
226 /* and if that fails, notify the parent */
227 kill(getppid(), SIGCHLD);
228 err(EX_OSERR, "ERROR: execvp \"%s\" failed", *a->pa_argv);
231 default: /* parent */
232 (void) close(pmcstat_sockpair[CHILDSOCKET]);
236 /* Ask to be notified via a kevent when the target process exits. */
237 EV_SET(&kev, pid, EVFILT_PROC, EV_ADD|EV_ONESHOT, NOTE_EXIT, 0,
239 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
240 err(EX_OSERR, "ERROR: cannot monitor child process %d", pid);
242 if ((pt = malloc(sizeof(*pt))) == NULL)
243 errx(EX_SOFTWARE, "ERROR: Out of memory.");
246 SLIST_INSERT_HEAD(&a->pa_targets, pt, pt_next);
248 /* Wait for the child to signal that its ready to go. */
249 if (read(pmcstat_sockpair[PARENTSOCKET], &token, 1) < 0)
250 err(EX_OSERR, "ERROR (parent): cannot read token");
256 pmcstat_find_targets(struct pmcstat_args *a, const char *spec)
258 int n, nproc, pid, rv;
259 struct pmcstat_target *pt;
260 char errbuf[_POSIX2_LINE_MAX], *end;
261 static struct kinfo_proc *kp;
265 /* First check if we've been given a process id. */
266 pid = strtol(spec, &end, 0);
267 if (end != spec && pid >= 0) {
268 if ((pt = malloc(sizeof(*pt))) == NULL)
271 SLIST_INSERT_HEAD(&a->pa_targets, pt, pt_next);
275 /* Otherwise treat arg as a regular expression naming processes. */
276 if (pmcstat_kvm == NULL) {
277 if ((pmcstat_kvm = kvm_openfiles(NULL, "/dev/null", NULL, 0,
279 err(EX_OSERR, "ERROR: Cannot open kernel \"%s\"",
281 if ((pmcstat_plist = kvm_getprocs(pmcstat_kvm, KERN_PROC_PROC,
283 err(EX_OSERR, "ERROR: Cannot get process list: %s",
284 kvm_geterr(pmcstat_kvm));
287 if ((rv = regcomp(®, spec, REG_EXTENDED|REG_NOSUB)) != 0) {
288 regerror(rv, ®, errbuf, sizeof(errbuf));
289 err(EX_DATAERR, "ERROR: Failed to compile regex \"%s\": %s",
293 for (n = 0, kp = pmcstat_plist; n < nproc; n++, kp++) {
294 if ((rv = regexec(®, kp->ki_comm, 1, ®match, 0)) == 0) {
295 if ((pt = malloc(sizeof(*pt))) == NULL)
297 pt->pt_pid = kp->ki_pid;
298 SLIST_INSERT_HEAD(&a->pa_targets, pt, pt_next);
299 } else if (rv != REG_NOMATCH) {
300 regerror(rv, ®, errbuf, sizeof(errbuf));
301 errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s",
311 errx(EX_SOFTWARE, "Out of memory.");
316 pmcstat_get_cpumask(const char *cpuspec)
327 cpu = strtol(s, &end, 0);
328 if (cpu < 0 || end == s)
329 errx(EX_USAGE, "ERROR: Illegal CPU specification "
331 cpumask |= (1 << cpu);
332 s = end + strspn(end, ", \t");
339 pmcstat_kill_process(struct pmcstat_args *a)
341 struct pmcstat_target *pt;
343 assert(a->pa_flags & FLAG_HAS_COMMANDLINE);
346 * If a command line was specified, it would be the very first
347 * in the list, before any other processes specified by -t.
349 pt = SLIST_FIRST(&a->pa_targets);
352 if (kill(pt->pt_pid, SIGINT) != 0)
353 err(EX_OSERR, "ERROR: cannot signal child process");
357 pmcstat_start_pmcs(struct pmcstat_args *a)
359 struct pmcstat_ev *ev;
361 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
363 assert(ev->ev_pmcid != PMC_ID_INVALID);
365 if (pmc_start(ev->ev_pmcid) < 0) {
366 warn("ERROR: Cannot start pmc 0x%x \"%s\"",
367 ev->ev_pmcid, ev->ev_name);
376 pmcstat_print_headers(struct pmcstat_args *a)
378 struct pmcstat_ev *ev;
381 (void) fprintf(a->pa_printfile, PRINT_HEADER_PREFIX);
383 STAILQ_FOREACH(ev, &a->pa_events, ev_next) {
384 if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
387 c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p';
389 if (ev->ev_fieldskip != 0)
390 (void) fprintf(a->pa_printfile, "%*s",
391 ev->ev_fieldskip, "");
392 w = ev->ev_fieldwidth - ev->ev_fieldskip - 2;
395 (void) fprintf(a->pa_printfile, "s/%02d/%-*s ",
396 ev->ev_cpu, w-3, ev->ev_name);
398 (void) fprintf(a->pa_printfile, "p/%*s ", w,
402 (void) fflush(a->pa_printfile);
406 pmcstat_print_counters(struct pmcstat_args *a)
409 struct pmcstat_ev *ev;
412 extra_width = sizeof(PRINT_HEADER_PREFIX) - 1;
414 STAILQ_FOREACH(ev, &a->pa_events, ev_next) {
416 /* skip sampling mode counters */
417 if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
420 if (pmc_read(ev->ev_pmcid, &value) < 0)
421 err(EX_OSERR, "ERROR: Cannot read pmc "
422 "\"%s\"", ev->ev_name);
424 (void) fprintf(a->pa_printfile, "%*ju ",
425 ev->ev_fieldwidth + extra_width,
426 (uintmax_t) ev->ev_cumulative ? value :
427 (value - ev->ev_saved));
429 if (ev->ev_cumulative == 0)
430 ev->ev_saved = value;
434 (void) fflush(a->pa_printfile);
442 pmcstat_print_pmcs(struct pmcstat_args *a)
444 static int linecount = 0;
446 /* check if we need to print a header line */
447 if (++linecount > pmcstat_displayheight) {
448 (void) fprintf(a->pa_printfile, "\n");
452 pmcstat_print_headers(a);
453 (void) fprintf(a->pa_printfile, "\n");
455 pmcstat_print_counters(a);
461 * Do process profiling
463 * If a pid was specified, attach each allocated PMC to the target
464 * process. Otherwise, fork a child and attach the PMCs to the child,
465 * and have the child exec() the target program.
469 pmcstat_start_process(void)
471 /* Signal the child to proceed. */
472 if (write(pmcstat_sockpair[PARENTSOCKET], "!", 1) != 1)
473 err(EX_OSERR, "ERROR (parent): write of token failed");
475 (void) close(pmcstat_sockpair[PARENTSOCKET]);
479 pmcstat_show_usage(void)
482 "[options] [commandline]\n"
483 "\t Measure process and/or system performance using hardware\n"
484 "\t performance monitoring counters.\n"
485 "\t Options include:\n"
486 "\t -C\t\t (toggle) show cumulative counts\n"
487 "\t -D path\t create profiles in directory \"path\"\n"
488 "\t -E\t\t (toggle) show counts at process exit\n"
489 "\t -M file\t print executable/gmon file map to \"file\"\n"
490 "\t -O file\t send log output to \"file\"\n"
491 "\t -P spec\t allocate a process-private sampling PMC\n"
492 "\t -R file\t read events from \"file\"\n"
493 "\t -S spec\t allocate a system-wide sampling PMC\n"
494 "\t -W\t\t (toggle) show counts per context switch\n"
495 "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n"
496 "\t -d\t\t (toggle) track descendants\n"
497 "\t -g\t\t produce gprof(1) compatible profiles\n"
498 "\t -k dir\t\t set the path to the kernel\n"
499 "\t -n rate\t set sampling rate\n"
500 "\t -o file\t send print output to \"file\"\n"
501 "\t -p spec\t allocate a process-private counting PMC\n"
502 "\t -q\t\t suppress verbosity\n"
503 "\t -r fsroot\t specify FS root directory\n"
504 "\t -s spec\t allocate a system-wide counting PMC\n"
505 "\t -t pid\t\t attach to running process with pid \"pid\"\n"
506 "\t -v\t\t increase verbosity\n"
507 "\t -w secs\t set printing time interval"
516 main(int argc, char **argv)
519 int option, npmc, ncpu;
520 int c, check_driver_stats, current_cpu, current_sampling_count;
521 int do_print, do_descendants;
522 int do_logproccsw, do_logprocexit;
525 int use_cumulative_counts;
529 enum pmcstat_state runstate;
530 struct pmc_driverstats ds_start, ds_end;
531 struct pmcstat_ev *ev;
536 char buffer[PATH_MAX];
538 check_driver_stats = 0;
540 current_sampling_count = DEFAULT_SAMPLE_COUNT;
544 use_cumulative_counts = 0;
545 args.pa_required = 0;
547 args.pa_verbosity = 1;
550 args.pa_kernel = strdup("/boot/kernel");
551 args.pa_samplesdir = ".";
552 args.pa_printfile = stderr;
553 args.pa_interval = DEFAULT_WAIT_INTERVAL;
554 args.pa_mapfilename = NULL;
555 STAILQ_INIT(&args.pa_events);
556 SLIST_INIT(&args.pa_targets);
557 bzero(&ds_start, sizeof(ds_start));
558 bzero(&ds_end, sizeof(ds_end));
561 dummy = sizeof(ncpu);
562 if (sysctlbyname("hw.ncpu", &ncpu, &dummy, NULL, 0) < 0)
563 err(EX_OSERR, "ERROR: Cannot determine #cpus");
564 cpumask = (1 << ncpu) - 1;
566 while ((option = getopt(argc, argv,
567 "CD:EM:O:P:R:S:Wc:dgk:n:o:p:qr:s:t:vw:")) != -1)
569 case 'C': /* cumulative values */
570 use_cumulative_counts = !use_cumulative_counts;
571 args.pa_required |= FLAG_HAS_COUNTING_PMCS;
576 if (optarg[0] == '*' && optarg[1] == '\0')
577 cpumask = (1 << ncpu) - 1;
579 cpumask = pmcstat_get_cpumask(optarg);
581 args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
585 if (stat(optarg, &sb) < 0)
586 err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
588 if (!S_ISDIR(sb.st_mode))
589 errx(EX_USAGE, "ERROR: \"%s\" is not a "
590 "directory.", optarg);
591 args.pa_samplesdir = optarg;
592 args.pa_flags |= FLAG_HAS_SAMPLESDIR;
593 args.pa_required |= FLAG_DO_GPROF;
596 case 'd': /* toggle descendents */
597 do_descendants = !do_descendants;
598 args.pa_required |= FLAG_HAS_PROCESS_PMCS;
601 case 'g': /* produce gprof compatible profiles */
602 args.pa_flags |= FLAG_DO_GPROF;
605 case 'k': /* pathname to the kernel */
606 free(args.pa_kernel);
607 args.pa_kernel = strdup(optarg);
608 args.pa_required |= FLAG_DO_GPROF;
609 args.pa_flags |= FLAG_HAS_KERNELPATH;
612 case 'E': /* log process exit */
613 do_logprocexit = !do_logprocexit;
614 args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
615 FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
618 case 'M': /* mapfile */
619 args.pa_mapfilename = optarg;
622 case 'p': /* process virtual counting PMC */
623 case 's': /* system-wide counting PMC */
624 case 'P': /* process virtual sampling PMC */
625 case 'S': /* system-wide sampling PMC */
626 if ((ev = malloc(sizeof(*ev))) == NULL)
627 errx(EX_SOFTWARE, "ERROR: Out of memory.");
630 case 'p': ev->ev_mode = PMC_MODE_TC; break;
631 case 's': ev->ev_mode = PMC_MODE_SC; break;
632 case 'P': ev->ev_mode = PMC_MODE_TS; break;
633 case 'S': ev->ev_mode = PMC_MODE_SS; break;
636 if (option == 'P' || option == 'p') {
637 args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
638 args.pa_required |= (FLAG_HAS_COMMANDLINE |
642 if (option == 'P' || option == 'S') {
643 args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
644 args.pa_required |= (FLAG_HAS_PIPE |
645 FLAG_HAS_OUTPUT_LOGFILE);
648 if (option == 'p' || option == 's')
649 args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
651 if (option == 's' || option == 'S')
652 args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
654 ev->ev_spec = strdup(optarg);
656 if (option == 'S' || option == 'P')
657 ev->ev_count = current_sampling_count;
661 if (option == 'S' || option == 's')
662 ev->ev_cpu = ffs(cpumask) - 1;
664 ev->ev_cpu = PMC_CPU_ANY;
668 ev->ev_flags |= PMC_F_DESCENDANTS;
670 ev->ev_flags |= PMC_F_LOG_PROCEXIT;
672 ev->ev_flags |= PMC_F_LOG_PROCCSW;
674 ev->ev_cumulative = use_cumulative_counts;
677 ev->ev_pmcid = PMC_ID_INVALID;
679 /* extract event name */
680 c = strcspn(optarg, ", \t");
681 ev->ev_name = malloc(c + 1);
682 (void) strncpy(ev->ev_name, optarg, c);
683 *(ev->ev_name + c) = '\0';
685 STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
687 if (option == 's' || option == 'S')
688 pmcstat_clone_event_descriptor(&args, ev,
689 cpumask & ~(1 << ev->ev_cpu));
693 case 'n': /* sampling count */
694 current_sampling_count = strtol(optarg, &end, 0);
695 if (*end != '\0' || current_sampling_count <= 0)
697 "ERROR: Illegal count value \"%s\".",
699 args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
702 case 'o': /* outputfile */
703 if (args.pa_printfile != NULL)
704 (void) fclose(args.pa_printfile);
705 if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
706 errx(EX_OSERR, "ERROR: cannot open \"%s\" for "
708 args.pa_flags |= FLAG_DO_PRINT;
711 case 'O': /* sampling output */
712 if (args.pa_outputpath)
713 errx(EX_USAGE, "ERROR: option -O may only be "
715 args.pa_outputpath = optarg;
716 args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
719 case 'q': /* quiet mode */
720 args.pa_verbosity = 0;
723 case 'r': /* root FS path */
724 args.pa_fsroot = optarg;
727 case 'R': /* read an existing log file */
728 if (args.pa_logparser != NULL)
729 errx(EX_USAGE, "ERROR: option -R may only be "
731 args.pa_inputpath = optarg;
732 if (args.pa_printfile == stderr)
733 args.pa_printfile = stdout;
734 args.pa_flags |= FLAG_READ_LOGFILE;
737 case 't': /* target pid or process name */
738 pmcstat_find_targets(&args, optarg);
740 args.pa_flags |= FLAG_HAS_TARGET;
741 args.pa_required |= FLAG_HAS_PROCESS_PMCS;
744 case 'v': /* verbose */
748 case 'w': /* wait interval */
749 interval = strtod(optarg, &end);
750 if (*end != '\0' || interval <= 0)
751 errx(EX_USAGE, "ERROR: Illegal wait interval "
752 "value \"%s\".", optarg);
753 args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
754 args.pa_required |= FLAG_HAS_COUNTING_PMCS;
755 args.pa_interval = interval;
758 case 'W': /* toggle LOG_CSW */
759 do_logproccsw = !do_logproccsw;
760 args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
761 FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
766 pmcstat_show_usage();
771 args.pa_argc = (argc -= optind);
772 args.pa_argv = (argv += optind);
774 if (argc) /* command line present */
775 args.pa_flags |= FLAG_HAS_COMMANDLINE;
778 * Check invocation syntax.
781 /* disallow -O and -R together */
782 if (args.pa_outputpath && args.pa_inputpath)
783 errx(EX_USAGE, "ERROR: options -O and -R are mutually "
786 if (args.pa_flags & FLAG_READ_LOGFILE) {
788 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
789 errmsg = "a command line specification";
790 else if (args.pa_flags & FLAG_HAS_TARGET)
791 errmsg = "option -t";
792 else if (!STAILQ_EMPTY(&args.pa_events))
793 errmsg = "a PMC event specification";
795 errx(EX_USAGE, "ERROR: option -R may not be used with "
797 } else if (STAILQ_EMPTY(&args.pa_events))
798 /* All other uses require a PMC spec. */
799 pmcstat_show_usage();
801 /* check for -t pid without a process PMC spec */
802 if ((args.pa_required & FLAG_HAS_TARGET) &&
803 (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
804 errx(EX_USAGE, "ERROR: option -t requires a process mode PMC "
807 /* check for process-mode options without a command or -t pid */
808 if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
809 (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
810 errx(EX_USAGE, "ERROR: options -d, -E, -p, -P, and -W require "
811 "a command line or target process.");
813 /* check for -p | -P without a target process of some sort */
814 if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
815 (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
816 errx(EX_USAGE, "ERROR: options -P and -p require a "
817 "target process or a command line.");
819 /* check for process-mode options without a process-mode PMC */
820 if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
821 (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
822 errx(EX_USAGE, "ERROR: options -d, -E, and -W require a "
823 "process mode PMC to be specified.");
825 /* check for -c cpu and not system mode PMCs */
826 if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
827 (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0)
828 errx(EX_USAGE, "ERROR: option -c requires at least one "
829 "system mode PMC to be specified.");
831 /* check for counting mode options without a counting PMC */
832 if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
833 (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
834 errx(EX_USAGE, "ERROR: options -C, -W, -o and -w require at "
835 "least one counting mode PMC to be specified.");
837 /* check for sampling mode options without a sampling PMC spec */
838 if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
839 (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
840 errx(EX_USAGE, "ERROR: options -n and -O require at least "
841 "one sampling mode PMC to be specified.");
843 /* check if -g is being used correctly */
844 if ((args.pa_flags & FLAG_DO_GPROF) &&
845 !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
846 errx(EX_USAGE, "ERROR: option -g requires sampling PMCs or -R "
849 /* check if -O was spuriously specified */
850 if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
851 (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
853 "ERROR: option -O is used only with options "
854 "-E, -P, -S and -W.");
856 /* -D dir and -k kernel path require -g or -R */
857 if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
858 (args.pa_flags & FLAG_DO_GPROF) == 0 &&
859 (args.pa_flags & FLAG_READ_LOGFILE) == 0)
860 errx(EX_USAGE, "ERROR: option -k is only used with -g/-R.");
862 if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
863 (args.pa_flags & FLAG_DO_GPROF) == 0 &&
864 (args.pa_flags & FLAG_READ_LOGFILE) == 0)
865 errx(EX_USAGE, "ERROR: option -D is only used with -g/-R.");
867 /* -M mapfile requires -g or -R */
868 if (args.pa_mapfilename != NULL &&
869 (args.pa_flags & FLAG_DO_GPROF) == 0 &&
870 (args.pa_flags & FLAG_READ_LOGFILE) == 0)
871 errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
874 * Disallow textual output of sampling PMCs if counting PMCs
875 * have also been asked for, mostly because the combined output
876 * is difficult to make sense of.
878 if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
879 (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
880 ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
881 errx(EX_USAGE, "ERROR: option -O is required if counting and "
882 "sampling PMCs are specified together.");
885 * Check if "-k kerneldir" was specified, and if whether 'kerneldir'
886 * actually refers to a a file. If so, use `dirname path` to determine
887 * the kernel directory.
889 if (args.pa_flags & FLAG_HAS_KERNELPATH) {
890 (void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
892 if (stat(buffer, &sb) < 0)
893 err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
895 if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
896 errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
898 if (!S_ISDIR(sb.st_mode)) {
899 tmp = args.pa_kernel;
900 args.pa_kernel = strdup(dirname(args.pa_kernel));
902 (void) snprintf(buffer, sizeof(buffer), "%s%s",
903 args.pa_fsroot, args.pa_kernel);
904 if (stat(buffer, &sb) < 0)
905 err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
907 if (!S_ISDIR(sb.st_mode))
908 errx(EX_USAGE, "ERROR: \"%s\" is not a "
909 "directory.", buffer);
913 /* if we've been asked to process a log file, do that and exit */
914 if (args.pa_flags & FLAG_READ_LOGFILE) {
916 * Print the log in textual form if we haven't been
917 * asked to generate gmon.out files.
919 if ((args.pa_flags & FLAG_DO_GPROF) == 0)
920 args.pa_flags |= FLAG_DO_PRINT;
922 pmcstat_initialize_logging(&args);
923 args.pa_logfd = pmcstat_open_log(args.pa_inputpath,
924 PMCSTAT_OPEN_FOR_READ);
925 if ((args.pa_logparser = pmclog_open(args.pa_logfd)) == NULL)
926 err(EX_OSERR, "ERROR: Cannot create parser");
927 pmcstat_process_log(&args);
928 pmcstat_shutdown_logging(&args);
932 /* otherwise, we've been asked to collect data */
935 "ERROR: Initialization of the pmc(3) library failed");
937 if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
938 err(EX_OSERR, "ERROR: Cannot determine the number of PMCs "
941 /* Allocate a kqueue */
942 if ((pmcstat_kq = kqueue()) < 0)
943 err(EX_OSERR, "ERROR: Cannot allocate kqueue");
946 * Configure the specified log file or setup a default log
947 * consumer via a pipe.
949 if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
950 if (args.pa_outputpath)
951 args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
952 PMCSTAT_OPEN_FOR_WRITE);
955 * process the log on the fly by reading it in
958 if (pipe(pipefd) < 0)
959 err(EX_OSERR, "ERROR: pipe(2) failed");
961 if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
962 err(EX_OSERR, "ERROR: fcntl(2) failed");
964 EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
967 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
968 err(EX_OSERR, "ERROR: Cannot register kevent");
970 args.pa_logfd = pipefd[WRITEPIPEFD];
972 args.pa_flags |= (FLAG_HAS_PIPE | FLAG_DO_PRINT);
973 args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
976 if (pmc_configure_logfile(args.pa_logfd) < 0)
977 err(EX_OSERR, "ERROR: Cannot configure log file");
980 /* remember to check for driver errors if we are sampling or logging */
981 check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
982 (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
988 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
989 if (pmc_allocate(ev->ev_spec, ev->ev_mode,
990 ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
991 err(EX_OSERR, "ERROR: Cannot allocate %s-mode pmc with "
992 "specification \"%s\"",
993 PMC_IS_SYSTEM_MODE(ev->ev_mode) ? "system" : "process",
996 if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
997 pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
998 err(EX_OSERR, "ERROR: Cannot set sampling count "
999 "for PMC \"%s\"", ev->ev_name);
1002 /* compute printout widths */
1003 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1008 (void) pmc_width(ev->ev_pmcid, &counter_width);
1009 header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1010 display_width = (int) floor(counter_width / 3.32193) + 1;
1012 if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1013 header_width += 3; /* 2 digit CPU number + '/' */
1015 if (header_width > display_width) {
1016 ev->ev_fieldskip = 0;
1017 ev->ev_fieldwidth = header_width;
1019 ev->ev_fieldskip = display_width -
1021 ev->ev_fieldwidth = display_width;
1026 * If our output is being set to a terminal, register a handler
1027 * for window size changes.
1030 if (isatty(fileno(args.pa_printfile))) {
1032 if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1033 err(EX_OSERR, "ERROR: Cannot determine window size");
1035 pmcstat_displayheight = ws.ws_row - 1;
1037 EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1039 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1040 err(EX_OSERR, "ERROR: Cannot register kevent for "
1044 EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1045 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1046 err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1048 EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1049 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1050 err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1053 * An exec() failure of a forked child is signalled by the
1054 * child sending the parent a SIGCHLD. We don't register an
1055 * actual signal handler for SIGCHLD, but instead use our
1056 * kqueue to pick up the signal.
1058 EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1059 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1060 err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1062 /* setup a timer if we have counting mode PMCs needing to be printed */
1063 if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1064 (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1065 EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1066 args.pa_interval * 1000, NULL);
1068 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1069 err(EX_OSERR, "ERROR: Cannot register kevent for "
1073 /* attach PMCs to the target process, starting it if specified */
1074 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1075 pmcstat_create_process(&args);
1077 if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1078 err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1080 /* Attach process pmcs to the target process. */
1081 if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1082 if (SLIST_EMPTY(&args.pa_targets))
1083 errx(EX_DATAERR, "ERROR: No matching target "
1086 pmcstat_attach_pmcs(&args);
1089 kvm_close(pmcstat_kvm);
1094 /* start the pmcs */
1095 pmcstat_start_pmcs(&args);
1097 /* start the (commandline) process if needed */
1098 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1099 pmcstat_start_process();
1101 /* initialize logging if printing the configured log */
1102 if ((args.pa_flags & FLAG_DO_PRINT) &&
1103 (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE)))
1104 pmcstat_initialize_logging(&args);
1106 /* Handle SIGINT using the kqueue loop */
1107 sa.sa_handler = SIG_IGN;
1109 (void) sigemptyset(&sa.sa_mask);
1111 if (sigaction(SIGINT, &sa, NULL) < 0)
1112 err(EX_OSERR, "ERROR: Cannot install signal handler");
1115 * loop till either the target process (if any) exits, or we
1116 * are killed by a SIGINT.
1118 runstate = PMCSTAT_RUNNING;
1121 if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1123 err(EX_OSERR, "ERROR: kevent failed");
1128 if (kev.flags & EV_ERROR)
1129 errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1131 switch (kev.filter) {
1132 case EVFILT_PROC: /* target has exited */
1133 if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE |
1135 runstate = pmcstat_close_log(&args);
1137 runstate = PMCSTAT_FINISHED;
1141 case EVFILT_READ: /* log file data is present */
1142 runstate = pmcstat_process_log(&args);
1146 if (kev.ident == SIGCHLD) {
1148 * The child process sends us a
1149 * SIGCHLD if its exec() failed. We
1150 * wait for it to exit and then exit
1154 runstate = PMCSTAT_FINISHED;
1155 } else if (kev.ident == SIGIO) {
1157 * We get a SIGIO if a PMC loses all
1158 * of its targets, or if logfile
1159 * writes encounter an error.
1161 if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE |
1163 runstate = pmcstat_close_log(&args);
1165 (FLAG_DO_PRINT|FLAG_DO_GPROF))
1166 pmcstat_process_log(&args);
1168 do_print = 1; /* print PMCs at exit */
1169 runstate = PMCSTAT_FINISHED;
1170 } else if (kev.ident == SIGINT) {
1171 /* Kill the child process if we started it */
1172 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1173 pmcstat_kill_process(&args);
1174 runstate = PMCSTAT_FINISHED;
1175 } else if (kev.ident == SIGWINCH) {
1176 if (ioctl(fileno(args.pa_printfile),
1177 TIOCGWINSZ, &ws) < 0)
1178 err(EX_OSERR, "ERROR: Cannot determine "
1180 pmcstat_displayheight = ws.ws_row - 1;
1186 case EVFILT_TIMER: /* print out counting PMCs */
1193 (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1194 pmcstat_print_pmcs(&args);
1195 if (runstate == PMCSTAT_FINISHED && /* final newline */
1196 (args.pa_flags & FLAG_DO_PRINT) == 0)
1197 (void) fprintf(args.pa_printfile, "\n");
1201 } while (runstate != PMCSTAT_FINISHED);
1203 /* flush any pending log entries */
1204 if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1205 pmc_flush_logfile();
1207 pmcstat_cleanup(&args);
1209 free(args.pa_kernel);
1211 /* check if the driver lost any samples or events */
1212 if (check_driver_stats) {
1213 if (pmc_get_driver_stats(&ds_end) < 0)
1214 err(EX_OSERR, "ERROR: Cannot retrieve driver "
1216 if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1217 args.pa_verbosity > 0)
1218 warnx("WARNING: some samples were dropped. Please "
1219 "consider tuning the \"kern.hwpmc.nsamples\" "
1221 if (ds_start.pm_buffer_requests_failed !=
1222 ds_end.pm_buffer_requests_failed &&
1223 args.pa_verbosity > 0)
1224 warnx("WARNING: some events were discarded. Please "
1225 "consider tuning the \"kern.hwpmc.nbuffers\" "