2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2003-2008, Joseph Koshy
5 * Copyright (c) 2007 The FreeBSD Foundation
8 * Portions of this software were developed by A. Joseph Koshy under
9 * sponsorship from the FreeBSD Foundation and Google, Inc.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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.
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
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
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>
42 #include <sys/sysctl.h>
44 #include <sys/ttycom.h>
69 #include <libpmcstat.h>
74 * A given invocation of pmcstat(8) can manage multiple PMCs of both
75 * the system-wide and per-process variety. Each of these could be in
76 * 'counting mode' or in 'sampling mode'.
78 * For 'counting mode' PMCs, pmcstat(8) will periodically issue a
79 * pmc_read() at the configured time interval and print out the value
80 * of the requested PMCs.
82 * For 'sampling mode' PMCs it can log to a file for offline analysis,
83 * or can analyse sampling data "on the fly", either by converting
84 * samples to printed textual form or by creating gprof(1) compatible
85 * profiles, one per program executed. When creating gprof(1)
86 * profiles it can optionally merge entries from multiple processes
87 * for a given executable into a single profile file.
89 * pmcstat(8) can also execute a command line and attach PMCs to the
90 * resulting child process. The protocol used is as follows:
92 * - parent creates a socketpair for two way communication and
98 * - Wait for childs token.
100 * - Awaits signal to start.
101 * - Attaches PMCs to the child's pid
102 * and starts them. Sets up
103 * monitoring for the child.
104 * - Signals child to start.
105 * - Receives signal, attempts exec().
107 * After this point normal processing can happen.
112 int pmcstat_displayheight = DEFAULT_DISPLAY_HEIGHT;
113 int pmcstat_displaywidth = DEFAULT_DISPLAY_WIDTH;
114 static int pmcstat_sockpair[NSOCKPAIRFD];
115 static int pmcstat_kq;
116 static kvm_t *pmcstat_kvm;
117 static struct kinfo_proc *pmcstat_plist;
118 struct pmcstat_args args;
121 pmcstat_get_cpumask(const char *cpuspec, cpuset_t *cpumask)
131 cpu = strtol(s, &end, 0);
132 if (cpu < 0 || end == s)
134 "ERROR: Illegal CPU specification \"%s\".",
136 CPU_SET(cpu, cpumask);
137 s = end + strspn(end, ", \t");
139 assert(!CPU_EMPTY(cpumask));
143 pmcstat_cleanup(void)
145 struct pmcstat_ev *ev;
147 /* release allocated PMCs. */
148 STAILQ_FOREACH(ev, &args.pa_events, ev_next)
149 if (ev->ev_pmcid != PMC_ID_INVALID) {
150 if (pmc_stop(ev->ev_pmcid) < 0)
152 "ERROR: cannot stop pmc 0x%x \"%s\"",
153 ev->ev_pmcid, ev->ev_name);
154 if (pmc_release(ev->ev_pmcid) < 0)
156 "ERROR: cannot release pmc 0x%x \"%s\"",
157 ev->ev_pmcid, ev->ev_name);
160 /* de-configure the log file if present. */
161 if (args.pa_flags & (FLAG_HAS_PIPE | FLAG_HAS_OUTPUT_LOGFILE))
162 (void) pmc_configure_logfile(-1);
164 if (args.pa_logparser) {
165 pmclog_close(args.pa_logparser);
166 args.pa_logparser = NULL;
169 pmcstat_log_shutdown_logging();
173 pmcstat_find_targets(const char *spec)
175 int n, nproc, pid, rv;
176 struct pmcstat_target *pt;
177 char errbuf[_POSIX2_LINE_MAX], *end;
178 static struct kinfo_proc *kp;
182 /* First check if we've been given a process id. */
183 pid = strtol(spec, &end, 0);
184 if (end != spec && pid >= 0) {
185 if ((pt = malloc(sizeof(*pt))) == NULL)
188 SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
192 /* Otherwise treat arg as a regular expression naming processes. */
193 if (pmcstat_kvm == NULL) {
194 if ((pmcstat_kvm = kvm_openfiles(NULL, "/dev/null", NULL, 0,
196 err(EX_OSERR, "ERROR: Cannot open kernel \"%s\"",
198 if ((pmcstat_plist = kvm_getprocs(pmcstat_kvm, KERN_PROC_PROC,
200 err(EX_OSERR, "ERROR: Cannot get process list: %s",
201 kvm_geterr(pmcstat_kvm));
205 if ((rv = regcomp(®, spec, REG_EXTENDED|REG_NOSUB)) != 0) {
206 regerror(rv, ®, errbuf, sizeof(errbuf));
207 err(EX_DATAERR, "ERROR: Failed to compile regex \"%s\": %s",
211 for (n = 0, kp = pmcstat_plist; n < nproc; n++, kp++) {
212 if ((rv = regexec(®, kp->ki_comm, 1, ®match, 0)) == 0) {
213 if ((pt = malloc(sizeof(*pt))) == NULL)
215 pt->pt_pid = kp->ki_pid;
216 SLIST_INSERT_HEAD(&args.pa_targets, pt, pt_next);
217 } else if (rv != REG_NOMATCH) {
218 regerror(rv, ®, errbuf, sizeof(errbuf));
219 errx(EX_SOFTWARE, "ERROR: Regex evalation failed: %s",
229 errx(EX_SOFTWARE, "Out of memory.");
234 pmcstat_kill_process(void)
236 struct pmcstat_target *pt;
238 assert(args.pa_flags & FLAG_HAS_COMMANDLINE);
241 * If a command line was specified, it would be the very first
242 * in the list, before any other processes specified by -t.
244 pt = SLIST_FIRST(&args.pa_targets);
247 if (kill(pt->pt_pid, SIGINT) != 0)
248 err(EX_OSERR, "ERROR: cannot signal child process");
252 pmcstat_start_pmcs(void)
254 struct pmcstat_ev *ev;
256 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
258 assert(ev->ev_pmcid != PMC_ID_INVALID);
260 if (pmc_start(ev->ev_pmcid) < 0) {
261 warn("ERROR: Cannot start pmc 0x%x \"%s\"",
262 ev->ev_pmcid, ev->ev_name);
270 pmcstat_print_headers(void)
272 struct pmcstat_ev *ev;
275 (void) fprintf(args.pa_printfile, PRINT_HEADER_PREFIX);
277 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
278 if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
281 c = PMC_IS_SYSTEM_MODE(ev->ev_mode) ? 's' : 'p';
283 if (ev->ev_fieldskip != 0)
284 (void) fprintf(args.pa_printfile, "%*s",
285 ev->ev_fieldskip, "");
286 w = ev->ev_fieldwidth - ev->ev_fieldskip - 2;
289 (void) fprintf(args.pa_printfile, "s/%02d/%-*s ",
290 ev->ev_cpu, w-3, ev->ev_name);
292 (void) fprintf(args.pa_printfile, "p/%*s ", w,
296 (void) fflush(args.pa_printfile);
300 pmcstat_print_counters(void)
303 struct pmcstat_ev *ev;
306 extra_width = sizeof(PRINT_HEADER_PREFIX) - 1;
308 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
310 /* skip sampling mode counters */
311 if (PMC_IS_SAMPLING_MODE(ev->ev_mode))
314 if (pmc_read(ev->ev_pmcid, &value) < 0)
315 err(EX_OSERR, "ERROR: Cannot read pmc \"%s\"",
318 (void) fprintf(args.pa_printfile, "%*ju ",
319 ev->ev_fieldwidth + extra_width,
320 (uintmax_t) ev->ev_cumulative ? value :
321 (value - ev->ev_saved));
323 if (ev->ev_cumulative == 0)
324 ev->ev_saved = value;
328 (void) fflush(args.pa_printfile);
336 pmcstat_print_pmcs(void)
338 static int linecount = 0;
340 /* check if we need to print a header line */
341 if (++linecount > pmcstat_displayheight) {
342 (void) fprintf(args.pa_printfile, "\n");
346 pmcstat_print_headers();
347 (void) fprintf(args.pa_printfile, "\n");
349 pmcstat_print_counters();
355 pmcstat_show_usage(void)
358 "[options] [commandline]\n"
359 "\t Measure process and/or system performance using hardware\n"
360 "\t performance monitoring counters.\n"
361 "\t Options include:\n"
362 "\t -C\t\t (toggle) show cumulative counts\n"
363 "\t -D path\t create profiles in directory \"path\"\n"
364 "\t -E\t\t (toggle) show counts at process exit\n"
365 "\t -F file\t write a system-wide callgraph (Kcachegrind format)"
367 "\t -G file\t write a system-wide callgraph to \"file\"\n"
368 "\t -M file\t print executable/gmon file map to \"file\"\n"
369 "\t -N\t\t (toggle) capture callchains\n"
370 "\t -O file\t send log output to \"file\"\n"
371 "\t -P spec\t allocate a process-private sampling PMC\n"
372 "\t -R file\t read events from \"file\"\n"
373 "\t -S spec\t allocate a system-wide sampling PMC\n"
374 "\t -T\t\t start in top mode\n"
375 "\t -W\t\t (toggle) show counts per context switch\n"
376 "\t -a file\t print sampled PCs and callgraph to \"file\"\n"
377 "\t -c cpu-list\t set cpus for subsequent system-wide PMCs\n"
378 "\t -d\t\t (toggle) track descendants\n"
379 "\t -e\t\t use wide history counter for gprof(1) output\n"
380 "\t -f spec\t pass \"spec\" to as plugin option\n"
381 "\t -g\t\t produce gprof(1) compatible profiles\n"
382 "\t -k dir\t\t set the path to the kernel\n"
383 "\t -l secs\t set duration time\n"
384 "\t -m file\t print sampled PCs to \"file\"\n"
385 "\t -n rate\t set sampling rate\n"
386 "\t -o file\t send print output to \"file\"\n"
387 "\t -p spec\t allocate a process-private counting PMC\n"
388 "\t -q\t\t suppress verbosity\n"
389 "\t -r fsroot\t specify FS root directory\n"
390 "\t -s spec\t allocate a system-wide counting PMC\n"
391 "\t -t process-spec attach to running processes matching "
393 "\t -v\t\t increase verbosity\n"
394 "\t -w secs\t set printing time interval\n"
395 "\t -z depth\t limit callchain display depth"
400 * At exit handler for top mode
404 pmcstat_topexit(void)
422 main(int argc, char **argv)
424 cpuset_t cpumask, rootmask;
428 int c, check_driver_stats, current_sampling_count;
429 int do_callchain, do_descendants, do_logproccsw, do_logprocexit;
430 int do_print, do_read;
434 int use_cumulative_counts;
437 const char *errmsg, *graphfilename;
438 enum pmcstat_state runstate;
439 struct pmc_driverstats ds_start, ds_end;
440 struct pmcstat_ev *ev;
445 char buffer[PATH_MAX];
447 check_driver_stats = 0;
448 current_sampling_count = DEFAULT_SAMPLE_COUNT;
453 use_cumulative_counts = 0;
455 args.pa_required = 0;
457 args.pa_verbosity = 1;
460 args.pa_samplesdir = ".";
461 args.pa_printfile = stderr;
462 args.pa_graphdepth = DEFAULT_CALLGRAPH_DEPTH;
463 args.pa_graphfile = NULL;
464 args.pa_interval = DEFAULT_WAIT_INTERVAL;
465 args.pa_mapfilename = NULL;
466 args.pa_inputpath = NULL;
467 args.pa_outputpath = NULL;
468 args.pa_pplugin = PMCSTAT_PL_NONE;
469 args.pa_plugin = PMCSTAT_PL_NONE;
470 args.pa_ctdumpinstr = 1;
471 args.pa_topmode = PMCSTAT_TOP_DELTA;
473 args.pa_topcolor = 0;
474 args.pa_mergepmc = 0;
475 args.pa_duration = 0.0;
476 STAILQ_INIT(&args.pa_events);
477 SLIST_INIT(&args.pa_targets);
478 bzero(&ds_start, sizeof(ds_start));
479 bzero(&ds_end, sizeof(ds_end));
483 /* Default to using the running system kernel. */
485 if (sysctlbyname("kern.bootfile", NULL, &len, NULL, 0) == -1)
486 err(EX_OSERR, "ERROR: Cannot determine path of running kernel");
487 args.pa_kernel = malloc(len);
488 if (args.pa_kernel == NULL)
489 errx(EX_SOFTWARE, "ERROR: Out of memory.");
490 if (sysctlbyname("kern.bootfile", args.pa_kernel, &len, NULL, 0) == -1)
491 err(EX_OSERR, "ERROR: Cannot determine path of running kernel");
494 * The initial CPU mask specifies the root mask of this process
495 * which is usually all CPUs in the system.
497 if (cpuset_getaffinity(CPU_LEVEL_ROOT, CPU_WHICH_PID, -1,
498 sizeof(rootmask), &rootmask) == -1)
499 err(EX_OSERR, "ERROR: Cannot determine the root set of CPUs");
500 CPU_COPY(&rootmask, &cpumask);
502 while ((option = getopt(argc, argv,
503 "CD:EF:G:IM:NO:P:R:S:TWa:c:def:gk:l:m:n:o:p:qr:s:t:vw:z:")) != -1)
505 case 'a': /* Annotate + callgraph */
506 args.pa_flags |= FLAG_DO_ANNOTATE;
507 args.pa_plugin = PMCSTAT_PL_ANNOTATE_CG;
508 graphfilename = optarg;
511 case 'C': /* cumulative values */
512 use_cumulative_counts = !use_cumulative_counts;
513 args.pa_required |= FLAG_HAS_COUNTING_PMCS;
517 if (optarg[0] == '*' && optarg[1] == '\0')
518 CPU_COPY(&rootmask, &cpumask);
520 pmcstat_get_cpumask(optarg, &cpumask);
522 args.pa_flags |= FLAGS_HAS_CPUMASK;
523 args.pa_required |= FLAG_HAS_SYSTEM_PMCS;
527 if (stat(optarg, &sb) < 0)
528 err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
530 if (!S_ISDIR(sb.st_mode))
532 "ERROR: \"%s\" is not a directory.",
534 args.pa_samplesdir = optarg;
535 args.pa_flags |= FLAG_HAS_SAMPLESDIR;
536 args.pa_required |= FLAG_DO_GPROF;
539 case 'd': /* toggle descendents */
540 do_descendants = !do_descendants;
541 args.pa_required |= FLAG_HAS_PROCESS_PMCS;
544 case 'e': /* wide gprof metrics */
545 args.pa_flags |= FLAG_DO_WIDE_GPROF_HC;
548 case 'F': /* produce a system-wide calltree */
549 args.pa_flags |= FLAG_DO_CALLGRAPHS;
550 args.pa_plugin = PMCSTAT_PL_CALLTREE;
551 graphfilename = optarg;
554 case 'f': /* plugins options */
555 if (args.pa_plugin == PMCSTAT_PL_NONE)
556 err(EX_USAGE, "ERROR: Need -g/-G/-m/-T.");
557 pmcstat_pluginconfigure_log(optarg);
560 case 'G': /* produce a system-wide callgraph */
561 args.pa_flags |= FLAG_DO_CALLGRAPHS;
562 args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
563 graphfilename = optarg;
566 case 'g': /* produce gprof compatible profiles */
567 args.pa_flags |= FLAG_DO_GPROF;
568 args.pa_pplugin = PMCSTAT_PL_CALLGRAPH;
569 args.pa_plugin = PMCSTAT_PL_GPROF;
573 args.pa_flags |= FLAG_SKIP_TOP_FN_RES;
575 case 'k': /* pathname to the kernel */
576 free(args.pa_kernel);
577 args.pa_kernel = strdup(optarg);
578 if (args.pa_kernel == NULL)
579 errx(EX_SOFTWARE, "ERROR: Out of memory");
580 args.pa_required |= FLAG_DO_ANALYSIS;
581 args.pa_flags |= FLAG_HAS_KERNELPATH;
584 case 'l': /* time duration in seconds */
585 duration = strtod(optarg, &end);
586 if (*end != '\0' || duration <= 0)
587 errx(EX_USAGE, "ERROR: Illegal duration time "
588 "value \"%s\".", optarg);
589 args.pa_flags |= FLAG_HAS_DURATION;
590 args.pa_duration = duration;
594 args.pa_flags |= FLAG_DO_ANNOTATE;
595 args.pa_plugin = PMCSTAT_PL_ANNOTATE;
596 graphfilename = optarg;
599 case 'E': /* log process exit */
600 do_logprocexit = !do_logprocexit;
601 args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
602 FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
605 case 'M': /* mapfile */
606 args.pa_mapfilename = optarg;
610 do_callchain = !do_callchain;
611 args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
614 case 'p': /* process virtual counting PMC */
615 case 's': /* system-wide counting PMC */
616 case 'P': /* process virtual sampling PMC */
617 case 'S': /* system-wide sampling PMC */
618 if ((ev = malloc(sizeof(*ev))) == NULL)
619 errx(EX_SOFTWARE, "ERROR: Out of memory.");
622 case 'p': ev->ev_mode = PMC_MODE_TC; break;
623 case 's': ev->ev_mode = PMC_MODE_SC; break;
624 case 'P': ev->ev_mode = PMC_MODE_TS; break;
625 case 'S': ev->ev_mode = PMC_MODE_SS; break;
628 if (option == 'P' || option == 'p') {
629 args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
630 args.pa_required |= (FLAG_HAS_COMMANDLINE |
634 if (option == 'P' || option == 'S') {
635 args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
636 args.pa_required |= (FLAG_HAS_PIPE |
637 FLAG_HAS_OUTPUT_LOGFILE);
640 if (option == 'p' || option == 's')
641 args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
643 if (option == 's' || option == 'S')
644 args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
646 ev->ev_spec = strdup(optarg);
647 if (ev->ev_spec == NULL)
648 errx(EX_SOFTWARE, "ERROR: Out of memory.");
650 if (option == 'S' || option == 'P')
651 ev->ev_count = current_sampling_count;
655 if (option == 'S' || option == 's')
656 ev->ev_cpu = CPU_FFS(&cpumask) - 1;
658 ev->ev_cpu = PMC_CPU_ANY;
662 ev->ev_flags |= PMC_F_CALLCHAIN;
664 ev->ev_flags |= PMC_F_DESCENDANTS;
666 ev->ev_flags |= PMC_F_LOG_PROCEXIT;
668 ev->ev_flags |= PMC_F_LOG_PROCCSW;
670 ev->ev_cumulative = use_cumulative_counts;
673 ev->ev_pmcid = PMC_ID_INVALID;
675 /* extract event name */
676 c = strcspn(optarg, ", \t");
677 ev->ev_name = malloc(c + 1);
678 if (ev->ev_name == NULL)
679 errx(EX_SOFTWARE, "ERROR: Out of memory.");
680 (void) strncpy(ev->ev_name, optarg, c);
681 *(ev->ev_name + c) = '\0';
683 STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
685 if (option == 's' || option == 'S') {
686 CPU_CLR(ev->ev_cpu, &cpumask);
687 pmcstat_clone_event_descriptor(ev, &cpumask, &args);
688 CPU_SET(ev->ev_cpu, &cpumask);
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 args.pa_printfile != stdout &&
705 args.pa_printfile != stderr)
706 (void) fclose(args.pa_printfile);
707 if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
709 "ERROR: cannot open \"%s\" for writing.",
711 args.pa_flags |= FLAG_DO_PRINT;
714 case 'O': /* sampling output */
715 if (args.pa_outputpath)
717 "ERROR: option -O may only be specified once.");
718 args.pa_outputpath = optarg;
719 args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
722 case 'q': /* quiet mode */
723 args.pa_verbosity = 0;
726 case 'r': /* root FS path */
727 args.pa_fsroot = optarg;
730 case 'R': /* read an existing log file */
731 if (args.pa_inputpath != NULL)
733 "ERROR: option -R may only be specified once.");
734 args.pa_inputpath = optarg;
735 if (args.pa_printfile == stderr)
736 args.pa_printfile = stdout;
737 args.pa_flags |= FLAG_READ_LOGFILE;
740 case 't': /* target pid or process name */
741 pmcstat_find_targets(optarg);
743 args.pa_flags |= FLAG_HAS_TARGET;
744 args.pa_required |= FLAG_HAS_PROCESS_PMCS;
747 case 'T': /* top mode */
748 args.pa_flags |= FLAG_DO_TOP;
749 args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
750 args.pa_ctdumpinstr = 0;
751 args.pa_mergepmc = 1;
752 if (args.pa_printfile == stderr)
753 args.pa_printfile = stdout;
756 case 'v': /* verbose */
760 case 'w': /* wait interval */
761 interval = strtod(optarg, &end);
762 if (*end != '\0' || interval <= 0)
764 "ERROR: Illegal wait interval value \"%s\".",
766 args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
767 args.pa_interval = interval;
770 case 'W': /* toggle LOG_CSW */
771 do_logproccsw = !do_logproccsw;
772 args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
773 FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
777 graphdepth = strtod(optarg, &end);
778 if (*end != '\0' || graphdepth <= 0)
780 "ERROR: Illegal callchain depth \"%s\".",
782 args.pa_graphdepth = graphdepth;
783 args.pa_required |= FLAG_DO_CALLGRAPHS;
788 pmcstat_show_usage();
793 args.pa_argc = (argc -= optind);
794 args.pa_argv = (argv += optind);
796 /* If we read from logfile and no specified CPU mask use
797 * the maximum CPU count.
799 if ((args.pa_flags & FLAG_READ_LOGFILE) &&
800 (args.pa_flags & FLAGS_HAS_CPUMASK) == 0)
803 args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
805 if (argc) /* command line present */
806 args.pa_flags |= FLAG_HAS_COMMANDLINE;
808 if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
809 FLAG_DO_ANNOTATE | FLAG_DO_TOP))
810 args.pa_flags |= FLAG_DO_ANALYSIS;
813 * Check invocation syntax.
816 /* disallow -O and -R together */
817 if (args.pa_outputpath && args.pa_inputpath)
819 "ERROR: options -O and -R are mutually exclusive.");
821 /* disallow -T and -l together */
822 if ((args.pa_flags & FLAG_HAS_DURATION) &&
823 (args.pa_flags & FLAG_DO_TOP))
824 errx(EX_USAGE, "ERROR: options -T and -l are mutually "
827 /* -a and -m require -R */
828 if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
829 errx(EX_USAGE, "ERROR: option %s requires an input file",
830 args.pa_plugin == PMCSTAT_PL_ANNOTATE ? "-m" : "-a");
832 /* -m option is not allowed combined with -g or -G. */
833 if (args.pa_flags & FLAG_DO_ANNOTATE &&
834 args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
836 "ERROR: option -m and -g | -G are mutually exclusive");
838 if (args.pa_flags & FLAG_READ_LOGFILE) {
840 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
841 errmsg = "a command line specification";
842 else if (args.pa_flags & FLAG_HAS_TARGET)
843 errmsg = "option -t";
844 else if (!STAILQ_EMPTY(&args.pa_events))
845 errmsg = "a PMC event specification";
848 "ERROR: option -R may not be used with %s.",
850 } else if (STAILQ_EMPTY(&args.pa_events))
851 /* All other uses require a PMC spec. */
852 pmcstat_show_usage();
854 /* check for -t pid without a process PMC spec */
855 if ((args.pa_required & FLAG_HAS_TARGET) &&
856 (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
858 "ERROR: option -t requires a process mode PMC to be specified."
861 /* check for process-mode options without a command or -t pid */
862 if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
863 (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
865 "ERROR: options -d, -E, -p, -P, and -W require a command line or target process."
868 /* check for -p | -P without a target process of some sort */
869 if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
870 (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
872 "ERROR: options -P and -p require a target process or a command line."
875 /* check for process-mode options without a process-mode PMC */
876 if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
877 (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
879 "ERROR: options -d, -E, and -W require a process mode PMC to be specified."
882 /* check for -c cpu with no system mode PMCs or logfile. */
883 if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
884 (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
885 (args.pa_flags & FLAG_READ_LOGFILE) == 0)
887 "ERROR: option -c requires at least one system mode PMC to be specified."
890 /* check for counting mode options without a counting PMC */
891 if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
892 (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
894 "ERROR: options -C, -W and -o require at least one counting mode PMC to be specified."
897 /* check for sampling mode options without a sampling PMC spec */
898 if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
899 (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
901 "ERROR: options -N, -n and -O require at least one sampling mode PMC to be specified."
904 /* check if -g/-G/-m/-T are being used correctly */
905 if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
906 !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
908 "ERROR: options -g/-G/-m/-T require sampling PMCs or -R to be specified."
911 /* check if -e was specified without -g */
912 if ((args.pa_flags & FLAG_DO_WIDE_GPROF_HC) &&
913 !(args.pa_flags & FLAG_DO_GPROF))
915 "ERROR: option -e requires gprof mode to be specified."
918 /* check if -O was spuriously specified */
919 if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
920 (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
922 "ERROR: option -O is used only with options -E, -P, -S and -W."
925 /* -k kernel path require -g/-G/-m/-T or -R */
926 if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
927 (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
928 (args.pa_flags & FLAG_READ_LOGFILE) == 0)
929 errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
931 /* -D only applies to gprof output mode (-g) */
932 if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
933 (args.pa_flags & FLAG_DO_GPROF) == 0)
934 errx(EX_USAGE, "ERROR: option -D is only used with -g.");
936 /* -M mapfile requires -g or -R */
937 if (args.pa_mapfilename != NULL &&
938 (args.pa_flags & FLAG_DO_GPROF) == 0 &&
939 (args.pa_flags & FLAG_READ_LOGFILE) == 0)
940 errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
943 * Disallow textual output of sampling PMCs if counting PMCs
944 * have also been asked for, mostly because the combined output
945 * is difficult to make sense of.
947 if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
948 (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
949 ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
951 "ERROR: option -O is required if counting and sampling PMCs are specified together."
955 * Check if 'kerneldir' refers to a file rather than a
956 * directory. If so, use `dirname path` to determine the
959 (void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
961 if (stat(buffer, &sb) < 0)
962 err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
964 if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
965 errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
967 if (!S_ISDIR(sb.st_mode)) {
968 tmp = args.pa_kernel;
969 args.pa_kernel = strdup(dirname(args.pa_kernel));
970 if (args.pa_kernel == NULL)
971 errx(EX_SOFTWARE, "ERROR: Out of memory");
973 (void) snprintf(buffer, sizeof(buffer), "%s%s",
974 args.pa_fsroot, args.pa_kernel);
975 if (stat(buffer, &sb) < 0)
976 err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
978 if (!S_ISDIR(sb.st_mode))
980 "ERROR: \"%s\" is not a directory.",
985 * If we have a callgraph be created, select the outputfile.
987 if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
988 if (strcmp(graphfilename, "-") == 0)
989 args.pa_graphfile = args.pa_printfile;
991 args.pa_graphfile = fopen(graphfilename, "w");
992 if (args.pa_graphfile == NULL)
994 "ERROR: cannot open \"%s\" for writing",
998 if (args.pa_flags & FLAG_DO_ANNOTATE) {
999 args.pa_graphfile = fopen(graphfilename, "w");
1000 if (args.pa_graphfile == NULL)
1001 err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
1005 /* if we've been asked to process a log file, skip init */
1006 if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) {
1009 "ERROR: Initialization of the pmc(3) library failed"
1012 if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1014 "ERROR: Cannot determine the number of PMCs on CPU %d",
1018 /* Allocate a kqueue */
1019 if ((pmcstat_kq = kqueue()) < 0)
1020 err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1022 /* Setup the logfile as the source. */
1023 if (args.pa_flags & FLAG_READ_LOGFILE) {
1025 * Print the log in textual form if we haven't been
1026 * asked to generate profiling information.
1028 if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1029 args.pa_flags |= FLAG_DO_PRINT;
1031 pmcstat_log_initialize_logging();
1032 rfd = pmcstat_open_log(args.pa_inputpath,
1033 PMCSTAT_OPEN_FOR_READ);
1034 if ((args.pa_logparser = pmclog_open(rfd)) == NULL)
1035 err(EX_OSERR, "ERROR: Cannot create parser");
1036 if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0)
1037 err(EX_OSERR, "ERROR: fcntl(2) failed");
1038 EV_SET(&kev, rfd, EVFILT_READ, EV_ADD,
1040 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1041 err(EX_OSERR, "ERROR: Cannot register kevent");
1044 * Configure the specified log file or setup a default log
1045 * consumer via a pipe.
1047 if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1048 if (args.pa_outputpath)
1049 args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1050 PMCSTAT_OPEN_FOR_WRITE);
1053 * process the log on the fly by reading it in
1056 if (pipe(pipefd) < 0)
1057 err(EX_OSERR, "ERROR: pipe(2) failed");
1059 if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1060 err(EX_OSERR, "ERROR: fcntl(2) failed");
1062 EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1065 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1066 err(EX_OSERR, "ERROR: Cannot register kevent");
1068 args.pa_logfd = pipefd[WRITEPIPEFD];
1070 args.pa_flags |= FLAG_HAS_PIPE;
1071 if ((args.pa_flags & FLAG_DO_TOP) == 0)
1072 args.pa_flags |= FLAG_DO_PRINT;
1073 args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1076 if (pmc_configure_logfile(args.pa_logfd) < 0)
1077 err(EX_OSERR, "ERROR: Cannot configure log file");
1080 /* remember to check for driver errors if we are sampling or logging */
1081 check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1082 (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1085 if (args.pa_flags & FLAG_READ_LOGFILE) {
1089 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1090 if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1091 ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1093 "ERROR: Cannot allocate %s-mode pmc with specification \"%s\"",
1094 PMC_IS_SYSTEM_MODE(ev->ev_mode) ?
1095 "system" : "process", ev->ev_spec);
1097 if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1098 pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1100 "ERROR: Cannot set sampling count for PMC \"%s\"",
1104 /* compute printout widths */
1105 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1110 (void) pmc_width(ev->ev_pmcid, &counter_width);
1111 header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1112 display_width = (int) floor(counter_width / 3.32193) + 1;
1114 if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1115 header_width += 3; /* 2 digit CPU number + '/' */
1117 if (header_width > display_width) {
1118 ev->ev_fieldskip = 0;
1119 ev->ev_fieldwidth = header_width;
1121 ev->ev_fieldskip = display_width -
1123 ev->ev_fieldwidth = display_width;
1128 * If our output is being set to a terminal, register a handler
1129 * for window size changes.
1132 if (isatty(fileno(args.pa_printfile))) {
1134 if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1135 err(EX_OSERR, "ERROR: Cannot determine window size");
1137 pmcstat_displayheight = ws.ws_row - 1;
1138 pmcstat_displaywidth = ws.ws_col - 1;
1140 EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1142 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1144 "ERROR: Cannot register kevent for SIGWINCH");
1150 * Listen to key input in top mode.
1152 if (args.pa_flags & FLAG_DO_TOP) {
1153 EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1154 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1155 err(EX_OSERR, "ERROR: Cannot register kevent");
1158 EV_SET(&kev, SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1159 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1160 err(EX_OSERR, "ERROR: Cannot register kevent for SIGINT");
1162 EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1163 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1164 err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1167 * An exec() failure of a forked child is signalled by the
1168 * child sending the parent a SIGCHLD. We don't register an
1169 * actual signal handler for SIGCHLD, but instead use our
1170 * kqueue to pick up the signal.
1172 EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1173 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1174 err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1177 * Setup a timer if we have counting mode PMCs needing to be printed or
1178 * top mode plugin is active.
1180 if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1181 (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1182 (args.pa_flags & FLAG_DO_TOP)) {
1183 EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1184 args.pa_interval * 1000, NULL);
1186 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1188 "ERROR: Cannot register kevent for timer");
1192 * Setup a duration timer if we have sampling mode PMCs and
1193 * a duration time is set
1195 if ((args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1196 (args.pa_flags & FLAG_HAS_DURATION)) {
1197 EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1198 args.pa_duration * 1000, NULL);
1200 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1201 err(EX_OSERR, "ERROR: Cannot register kevent for "
1205 /* attach PMCs to the target process, starting it if specified */
1206 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1207 pmcstat_create_process(pmcstat_sockpair, &args, pmcstat_kq);
1209 if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1210 err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1212 /* Attach process pmcs to the target process. */
1213 if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1214 if (SLIST_EMPTY(&args.pa_targets))
1216 "ERROR: No matching target processes.");
1217 if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1218 pmcstat_attach_pmcs(&args);
1221 kvm_close(pmcstat_kvm);
1226 /* start the pmcs */
1227 pmcstat_start_pmcs();
1229 /* start the (commandline) process if needed */
1230 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1231 pmcstat_start_process(pmcstat_sockpair);
1233 /* initialize logging */
1234 pmcstat_log_initialize_logging();
1236 /* Handle SIGINT using the kqueue loop */
1237 sa.sa_handler = SIG_IGN;
1239 (void) sigemptyset(&sa.sa_mask);
1241 if (sigaction(SIGINT, &sa, NULL) < 0)
1242 err(EX_OSERR, "ERROR: Cannot install signal handler");
1245 * Setup the top mode display.
1247 if (args.pa_flags & FLAG_DO_TOP) {
1248 args.pa_flags &= ~FLAG_DO_PRINT;
1250 if (args.pa_toptty) {
1255 if(has_colors() == TRUE) {
1256 args.pa_topcolor = 1;
1258 use_default_colors();
1259 pair_content(0, &cf, &cb);
1260 init_pair(1, COLOR_RED, cb);
1261 init_pair(2, COLOR_YELLOW, cb);
1262 init_pair(3, COLOR_GREEN, cb);
1268 intrflush(stdscr, FALSE);
1269 keypad(stdscr, TRUE);
1271 /* Get terminal width / height with ncurses. */
1273 pmcstat_displayheight, pmcstat_displaywidth);
1274 pmcstat_displayheight--; pmcstat_displaywidth--;
1275 atexit(pmcstat_topexit);
1280 * loop till either the target process (if any) exits, or we
1281 * are killed by a SIGINT or we reached the time duration.
1283 runstate = PMCSTAT_RUNNING;
1284 do_print = do_read = 0;
1286 if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1288 err(EX_OSERR, "ERROR: kevent failed");
1293 if (kev.flags & EV_ERROR)
1294 errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1296 switch (kev.filter) {
1297 case EVFILT_PROC: /* target has exited */
1298 runstate = pmcstat_close_log(&args);
1302 case EVFILT_READ: /* log file data is present */
1303 if (kev.ident == (unsigned)fileno(stdin) &&
1304 (args.pa_flags & FLAG_DO_TOP)) {
1305 if (pmcstat_keypress_log())
1306 runstate = pmcstat_close_log(&args);
1309 runstate = pmcstat_process_log();
1314 if (kev.ident == SIGCHLD) {
1316 * The child process sends us a
1317 * SIGCHLD if its exec() failed. We
1318 * wait for it to exit and then exit
1322 runstate = PMCSTAT_FINISHED;
1323 } else if (kev.ident == SIGIO) {
1325 * We get a SIGIO if a PMC loses all
1326 * of its targets, or if logfile
1327 * writes encounter an error.
1329 runstate = pmcstat_close_log(&args);
1330 do_print = 1; /* print PMCs at exit */
1331 } else if (kev.ident == SIGINT) {
1332 /* Kill the child process if we started it */
1333 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1334 pmcstat_kill_process();
1335 runstate = pmcstat_close_log(&args);
1336 } else if (kev.ident == SIGWINCH) {
1337 if (ioctl(fileno(args.pa_printfile),
1338 TIOCGWINSZ, &ws) < 0)
1340 "ERROR: Cannot determine window size");
1341 pmcstat_displayheight = ws.ws_row - 1;
1342 pmcstat_displaywidth = ws.ws_col - 1;
1349 /* time duration reached, exit */
1350 if (args.pa_flags & FLAG_HAS_DURATION) {
1351 runstate = PMCSTAT_FINISHED;
1354 /* print out counting PMCs */
1355 if ((args.pa_flags & FLAG_DO_TOP) &&
1356 (args.pa_flags & FLAG_HAS_PIPE) &&
1357 pmc_flush_logfile() == 0)
1364 if (do_print && !do_read) {
1365 if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1366 pmcstat_print_pmcs();
1367 if (runstate == PMCSTAT_FINISHED &&
1369 (args.pa_flags & FLAG_DO_PRINT) == 0)
1370 (void) fprintf(args.pa_printfile, "\n");
1372 if (args.pa_flags & FLAG_DO_TOP)
1373 pmcstat_display_log();
1377 } while (runstate != PMCSTAT_FINISHED);
1379 if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1384 /* flush any pending log entries */
1385 if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1386 pmc_close_logfile();
1390 /* check if the driver lost any samples or events */
1391 if (check_driver_stats) {
1392 if (pmc_get_driver_stats(&ds_end) < 0)
1394 "ERROR: Cannot retrieve driver statistics");
1395 if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1396 args.pa_verbosity > 0)
1398 "WARNING: sampling was paused at least %u time%s.\n"
1399 "Please consider tuning the \"kern.hwpmc.nsamples\" tunable.",
1400 ds_end.pm_intr_bufferfull -
1401 ds_start.pm_intr_bufferfull,
1402 ((ds_end.pm_intr_bufferfull -
1403 ds_start.pm_intr_bufferfull) != 1) ? "s" : ""
1405 if (ds_start.pm_buffer_requests_failed !=
1406 ds_end.pm_buffer_requests_failed &&
1407 args.pa_verbosity > 0)
1409 "WARNING: at least %u event%s were discarded while running.\n"
1410 "Please consider tuning the \"kern.hwpmc.nbuffers\" tunable.",
1411 ds_end.pm_buffer_requests_failed -
1412 ds_start.pm_buffer_requests_failed,
1413 ((ds_end.pm_buffer_requests_failed -
1414 ds_start.pm_buffer_requests_failed) != 1) ? "s" : ""