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 = 0;
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:IL:M: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;
585 args.pa_flags |= FLAG_FILTER_THREAD_ID;
586 args.pa_tid = strtol(optarg, &end, 0);
588 case 'l': /* time duration in seconds */
589 duration = strtod(optarg, &end);
590 if (*end != '\0' || duration <= 0)
591 errx(EX_USAGE, "ERROR: Illegal duration time "
592 "value \"%s\".", optarg);
593 args.pa_flags |= FLAG_HAS_DURATION;
594 args.pa_duration = duration;
598 args.pa_flags |= FLAG_DO_ANNOTATE;
599 args.pa_plugin = PMCSTAT_PL_ANNOTATE;
600 graphfilename = optarg;
603 case 'E': /* log process exit */
604 do_logprocexit = !do_logprocexit;
605 args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
606 FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
609 case 'M': /* mapfile */
610 args.pa_mapfilename = optarg;
614 do_callchain = !do_callchain;
615 args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
618 case 'p': /* process virtual counting PMC */
619 case 's': /* system-wide counting PMC */
620 case 'P': /* process virtual sampling PMC */
621 case 'S': /* system-wide sampling PMC */
622 if ((ev = malloc(sizeof(*ev))) == NULL)
623 errx(EX_SOFTWARE, "ERROR: Out of memory.");
626 case 'p': ev->ev_mode = PMC_MODE_TC; break;
627 case 's': ev->ev_mode = PMC_MODE_SC; break;
628 case 'P': ev->ev_mode = PMC_MODE_TS; break;
629 case 'S': ev->ev_mode = PMC_MODE_SS; break;
632 if (option == 'P' || option == 'p') {
633 args.pa_flags |= FLAG_HAS_PROCESS_PMCS;
634 args.pa_required |= (FLAG_HAS_COMMANDLINE |
638 if (option == 'P' || option == 'S') {
639 args.pa_flags |= FLAG_HAS_SAMPLING_PMCS;
640 args.pa_required |= (FLAG_HAS_PIPE |
641 FLAG_HAS_OUTPUT_LOGFILE);
644 if (option == 'p' || option == 's')
645 args.pa_flags |= FLAG_HAS_COUNTING_PMCS;
647 if (option == 's' || option == 'S')
648 args.pa_flags |= FLAG_HAS_SYSTEM_PMCS;
650 ev->ev_spec = strdup(optarg);
651 if (ev->ev_spec == NULL)
652 errx(EX_SOFTWARE, "ERROR: Out of memory.");
654 if (option == 'S' || option == 'P')
655 ev->ev_count = current_sampling_count ? current_sampling_count : pmcstat_pmu_sample_rate_get(ev->ev_spec);
659 if (option == 'S' || option == 's')
660 ev->ev_cpu = CPU_FFS(&cpumask) - 1;
662 ev->ev_cpu = PMC_CPU_ANY;
666 ev->ev_flags |= PMC_F_CALLCHAIN;
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 if (ev->ev_name == NULL)
683 errx(EX_SOFTWARE, "ERROR: Out of memory.");
684 (void) strncpy(ev->ev_name, optarg, c);
685 *(ev->ev_name + c) = '\0';
687 STAILQ_INSERT_TAIL(&args.pa_events, ev, ev_next);
689 if (option == 's' || option == 'S') {
690 CPU_CLR(ev->ev_cpu, &cpumask);
691 pmcstat_clone_event_descriptor(ev, &cpumask, &args);
692 CPU_SET(ev->ev_cpu, &cpumask);
697 case 'n': /* sampling count */
698 current_sampling_count = strtol(optarg, &end, 0);
699 if (*end != '\0' || current_sampling_count <= 0)
701 "ERROR: Illegal count value \"%s\".",
703 args.pa_required |= FLAG_HAS_SAMPLING_PMCS;
706 case 'o': /* outputfile */
707 if (args.pa_printfile != NULL &&
708 args.pa_printfile != stdout &&
709 args.pa_printfile != stderr)
710 (void) fclose(args.pa_printfile);
711 if ((args.pa_printfile = fopen(optarg, "w")) == NULL)
713 "ERROR: cannot open \"%s\" for writing.",
715 args.pa_flags |= FLAG_DO_PRINT;
718 case 'O': /* sampling output */
719 if (args.pa_outputpath)
721 "ERROR: option -O may only be specified once.");
722 args.pa_outputpath = optarg;
723 args.pa_flags |= FLAG_HAS_OUTPUT_LOGFILE;
726 case 'q': /* quiet mode */
727 args.pa_verbosity = 0;
730 case 'r': /* root FS path */
731 args.pa_fsroot = optarg;
734 case 'R': /* read an existing log file */
735 if (args.pa_inputpath != NULL)
737 "ERROR: option -R may only be specified once.");
738 args.pa_inputpath = optarg;
739 if (args.pa_printfile == stderr)
740 args.pa_printfile = stdout;
741 args.pa_flags |= FLAG_READ_LOGFILE;
744 case 't': /* target pid or process name */
745 pmcstat_find_targets(optarg);
747 args.pa_flags |= FLAG_HAS_TARGET;
748 args.pa_required |= FLAG_HAS_PROCESS_PMCS;
751 case 'T': /* top mode */
752 args.pa_flags |= FLAG_DO_TOP;
753 args.pa_plugin = PMCSTAT_PL_CALLGRAPH;
754 args.pa_ctdumpinstr = 0;
755 args.pa_mergepmc = 1;
756 if (args.pa_printfile == stderr)
757 args.pa_printfile = stdout;
760 case 'v': /* verbose */
764 case 'w': /* wait interval */
765 interval = strtod(optarg, &end);
766 if (*end != '\0' || interval <= 0)
768 "ERROR: Illegal wait interval value \"%s\".",
770 args.pa_flags |= FLAG_HAS_WAIT_INTERVAL;
771 args.pa_interval = interval;
774 case 'W': /* toggle LOG_CSW */
775 do_logproccsw = !do_logproccsw;
776 args.pa_required |= (FLAG_HAS_PROCESS_PMCS |
777 FLAG_HAS_COUNTING_PMCS | FLAG_HAS_OUTPUT_LOGFILE);
781 graphdepth = strtod(optarg, &end);
782 if (*end != '\0' || graphdepth <= 0)
784 "ERROR: Illegal callchain depth \"%s\".",
786 args.pa_graphdepth = graphdepth;
787 args.pa_required |= FLAG_DO_CALLGRAPHS;
792 pmcstat_show_usage();
797 args.pa_argc = (argc -= optind);
798 args.pa_argv = (argv += optind);
800 /* If we read from logfile and no specified CPU mask use
801 * the maximum CPU count.
803 if ((args.pa_flags & FLAG_READ_LOGFILE) &&
804 (args.pa_flags & FLAGS_HAS_CPUMASK) == 0)
807 args.pa_cpumask = cpumask; /* For selecting CPUs using -R. */
809 if (argc) /* command line present */
810 args.pa_flags |= FLAG_HAS_COMMANDLINE;
812 if (args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS |
813 FLAG_DO_ANNOTATE | FLAG_DO_TOP))
814 args.pa_flags |= FLAG_DO_ANALYSIS;
817 * Check invocation syntax.
820 /* disallow -O and -R together */
821 if (args.pa_outputpath && args.pa_inputpath)
823 "ERROR: options -O and -R are mutually exclusive.");
825 /* disallow -T and -l together */
826 if ((args.pa_flags & FLAG_HAS_DURATION) &&
827 (args.pa_flags & FLAG_DO_TOP))
828 errx(EX_USAGE, "ERROR: options -T and -l are mutually "
831 /* -a and -m require -R */
832 if (args.pa_flags & FLAG_DO_ANNOTATE && args.pa_inputpath == NULL)
833 errx(EX_USAGE, "ERROR: option %s requires an input file",
834 args.pa_plugin == PMCSTAT_PL_ANNOTATE ? "-m" : "-a");
836 /* -m option is not allowed combined with -g or -G. */
837 if (args.pa_flags & FLAG_DO_ANNOTATE &&
838 args.pa_flags & (FLAG_DO_GPROF | FLAG_DO_CALLGRAPHS))
840 "ERROR: option -m and -g | -G are mutually exclusive");
842 if (args.pa_flags & FLAG_READ_LOGFILE) {
844 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
845 errmsg = "a command line specification";
846 else if (args.pa_flags & FLAG_HAS_TARGET)
847 errmsg = "option -t";
848 else if (!STAILQ_EMPTY(&args.pa_events))
849 errmsg = "a PMC event specification";
852 "ERROR: option -R may not be used with %s.",
854 } else if (STAILQ_EMPTY(&args.pa_events))
855 /* All other uses require a PMC spec. */
856 pmcstat_show_usage();
858 /* check for -t pid without a process PMC spec */
859 if ((args.pa_required & FLAG_HAS_TARGET) &&
860 (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
862 "ERROR: option -t requires a process mode PMC to be specified."
865 /* check for process-mode options without a command or -t pid */
866 if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
867 (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
869 "ERROR: options -d, -E, -p, -P, and -W require a command line or target process."
872 /* check for -p | -P without a target process of some sort */
873 if ((args.pa_required & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) &&
874 (args.pa_flags & (FLAG_HAS_COMMANDLINE | FLAG_HAS_TARGET)) == 0)
876 "ERROR: options -P and -p require a target process or a command line."
879 /* check for process-mode options without a process-mode PMC */
880 if ((args.pa_required & FLAG_HAS_PROCESS_PMCS) &&
881 (args.pa_flags & FLAG_HAS_PROCESS_PMCS) == 0)
883 "ERROR: options -d, -E, and -W require a process mode PMC to be specified."
886 /* check for -c cpu with no system mode PMCs or logfile. */
887 if ((args.pa_required & FLAG_HAS_SYSTEM_PMCS) &&
888 (args.pa_flags & FLAG_HAS_SYSTEM_PMCS) == 0 &&
889 (args.pa_flags & FLAG_READ_LOGFILE) == 0)
891 "ERROR: option -c requires at least one system mode PMC to be specified."
894 /* check for counting mode options without a counting PMC */
895 if ((args.pa_required & FLAG_HAS_COUNTING_PMCS) &&
896 (args.pa_flags & FLAG_HAS_COUNTING_PMCS) == 0)
898 "ERROR: options -C, -W and -o require at least one counting mode PMC to be specified."
901 /* check for sampling mode options without a sampling PMC spec */
902 if ((args.pa_required & FLAG_HAS_SAMPLING_PMCS) &&
903 (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) == 0)
905 "ERROR: options -N, -n and -O require at least one sampling mode PMC to be specified."
908 /* check if -g/-G/-m/-T are being used correctly */
909 if ((args.pa_flags & FLAG_DO_ANALYSIS) &&
910 !(args.pa_flags & (FLAG_HAS_SAMPLING_PMCS|FLAG_READ_LOGFILE)))
912 "ERROR: options -g/-G/-m/-T require sampling PMCs or -R to be specified."
915 /* check if -e was specified without -g */
916 if ((args.pa_flags & FLAG_DO_WIDE_GPROF_HC) &&
917 !(args.pa_flags & FLAG_DO_GPROF))
919 "ERROR: option -e requires gprof mode to be specified."
922 /* check if -O was spuriously specified */
923 if ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) &&
924 (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0)
926 "ERROR: option -O is used only with options -E, -P, -S and -W."
929 /* -k kernel path require -g/-G/-m/-T or -R */
930 if ((args.pa_flags & FLAG_HAS_KERNELPATH) &&
931 (args.pa_flags & FLAG_DO_ANALYSIS) == 0 &&
932 (args.pa_flags & FLAG_READ_LOGFILE) == 0)
933 errx(EX_USAGE, "ERROR: option -k is only used with -g/-R/-m/-T.");
935 /* -D only applies to gprof output mode (-g) */
936 if ((args.pa_flags & FLAG_HAS_SAMPLESDIR) &&
937 (args.pa_flags & FLAG_DO_GPROF) == 0)
938 errx(EX_USAGE, "ERROR: option -D is only used with -g.");
940 /* -M mapfile requires -g or -R */
941 if (args.pa_mapfilename != NULL &&
942 (args.pa_flags & FLAG_DO_GPROF) == 0 &&
943 (args.pa_flags & FLAG_READ_LOGFILE) == 0)
944 errx(EX_USAGE, "ERROR: option -M is only used with -g/-R.");
947 * Disallow textual output of sampling PMCs if counting PMCs
948 * have also been asked for, mostly because the combined output
949 * is difficult to make sense of.
951 if ((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
952 (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
953 ((args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE) == 0))
955 "ERROR: option -O is required if counting and sampling PMCs are specified together."
959 * Check if 'kerneldir' refers to a file rather than a
960 * directory. If so, use `dirname path` to determine the
963 (void) snprintf(buffer, sizeof(buffer), "%s%s", args.pa_fsroot,
965 if (stat(buffer, &sb) < 0)
966 err(EX_OSERR, "ERROR: Cannot locate kernel \"%s\"",
968 if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
969 errx(EX_USAGE, "ERROR: \"%s\": Unsupported file type.",
971 if (!S_ISDIR(sb.st_mode)) {
972 tmp = args.pa_kernel;
973 args.pa_kernel = strdup(dirname(args.pa_kernel));
974 if (args.pa_kernel == NULL)
975 errx(EX_SOFTWARE, "ERROR: Out of memory");
977 (void) snprintf(buffer, sizeof(buffer), "%s%s",
978 args.pa_fsroot, args.pa_kernel);
979 if (stat(buffer, &sb) < 0)
980 err(EX_OSERR, "ERROR: Cannot stat \"%s\"",
982 if (!S_ISDIR(sb.st_mode))
984 "ERROR: \"%s\" is not a directory.",
989 * If we have a callgraph be created, select the outputfile.
991 if (args.pa_flags & FLAG_DO_CALLGRAPHS) {
992 if (strcmp(graphfilename, "-") == 0)
993 args.pa_graphfile = args.pa_printfile;
995 args.pa_graphfile = fopen(graphfilename, "w");
996 if (args.pa_graphfile == NULL)
998 "ERROR: cannot open \"%s\" for writing",
1002 if (args.pa_flags & FLAG_DO_ANNOTATE) {
1003 args.pa_graphfile = fopen(graphfilename, "w");
1004 if (args.pa_graphfile == NULL)
1005 err(EX_OSERR, "ERROR: cannot open \"%s\" for writing",
1009 /* if we've been asked to process a log file, skip init */
1010 if ((args.pa_flags & FLAG_READ_LOGFILE) == 0) {
1013 "ERROR: Initialization of the pmc(3) library failed"
1016 if ((npmc = pmc_npmc(0)) < 0) /* assume all CPUs are identical */
1018 "ERROR: Cannot determine the number of PMCs on CPU %d",
1022 /* Allocate a kqueue */
1023 if ((pmcstat_kq = kqueue()) < 0)
1024 err(EX_OSERR, "ERROR: Cannot allocate kqueue");
1026 /* Setup the logfile as the source. */
1027 if (args.pa_flags & FLAG_READ_LOGFILE) {
1029 * Print the log in textual form if we haven't been
1030 * asked to generate profiling information.
1032 if ((args.pa_flags & FLAG_DO_ANALYSIS) == 0)
1033 args.pa_flags |= FLAG_DO_PRINT;
1035 pmcstat_log_initialize_logging();
1036 rfd = pmcstat_open_log(args.pa_inputpath,
1037 PMCSTAT_OPEN_FOR_READ);
1038 if ((args.pa_logparser = pmclog_open(rfd)) == NULL)
1039 err(EX_OSERR, "ERROR: Cannot create parser");
1040 if (fcntl(rfd, F_SETFL, O_NONBLOCK) < 0)
1041 err(EX_OSERR, "ERROR: fcntl(2) failed");
1042 EV_SET(&kev, rfd, EVFILT_READ, EV_ADD,
1044 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1045 err(EX_OSERR, "ERROR: Cannot register kevent");
1048 * Configure the specified log file or setup a default log
1049 * consumer via a pipe.
1051 if (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) {
1052 if (args.pa_outputpath)
1053 args.pa_logfd = pmcstat_open_log(args.pa_outputpath,
1054 PMCSTAT_OPEN_FOR_WRITE);
1057 * process the log on the fly by reading it in
1060 if (pipe(pipefd) < 0)
1061 err(EX_OSERR, "ERROR: pipe(2) failed");
1063 if (fcntl(pipefd[READPIPEFD], F_SETFL, O_NONBLOCK) < 0)
1064 err(EX_OSERR, "ERROR: fcntl(2) failed");
1066 EV_SET(&kev, pipefd[READPIPEFD], EVFILT_READ, EV_ADD,
1069 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1070 err(EX_OSERR, "ERROR: Cannot register kevent");
1072 args.pa_logfd = pipefd[WRITEPIPEFD];
1074 args.pa_flags |= FLAG_HAS_PIPE;
1075 if ((args.pa_flags & FLAG_DO_TOP) == 0)
1076 args.pa_flags |= FLAG_DO_PRINT;
1077 args.pa_logparser = pmclog_open(pipefd[READPIPEFD]);
1080 if (pmc_configure_logfile(args.pa_logfd) < 0)
1081 err(EX_OSERR, "ERROR: Cannot configure log file");
1084 /* remember to check for driver errors if we are sampling or logging */
1085 check_driver_stats = (args.pa_flags & FLAG_HAS_SAMPLING_PMCS) ||
1086 (args.pa_flags & FLAG_HAS_OUTPUT_LOGFILE);
1089 if (args.pa_flags & FLAG_READ_LOGFILE) {
1093 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1094 if (pmc_allocate(ev->ev_spec, ev->ev_mode,
1095 ev->ev_flags, ev->ev_cpu, &ev->ev_pmcid) < 0)
1097 "ERROR: Cannot allocate %s-mode pmc with specification \"%s\"",
1098 PMC_IS_SYSTEM_MODE(ev->ev_mode) ?
1099 "system" : "process", ev->ev_spec);
1101 if (PMC_IS_SAMPLING_MODE(ev->ev_mode) &&
1102 pmc_set(ev->ev_pmcid, ev->ev_count) < 0)
1104 "ERROR: Cannot set sampling count for PMC \"%s\"",
1108 /* compute printout widths */
1109 STAILQ_FOREACH(ev, &args.pa_events, ev_next) {
1114 (void) pmc_width(ev->ev_pmcid, &counter_width);
1115 header_width = strlen(ev->ev_name) + 2; /* prefix '%c/' */
1116 display_width = (int) floor(counter_width / 3.32193) + 1;
1118 if (PMC_IS_SYSTEM_MODE(ev->ev_mode))
1119 header_width += 3; /* 2 digit CPU number + '/' */
1121 if (header_width > display_width) {
1122 ev->ev_fieldskip = 0;
1123 ev->ev_fieldwidth = header_width;
1125 ev->ev_fieldskip = display_width -
1127 ev->ev_fieldwidth = display_width;
1132 * If our output is being set to a terminal, register a handler
1133 * for window size changes.
1136 if (isatty(fileno(args.pa_printfile))) {
1138 if (ioctl(fileno(args.pa_printfile), TIOCGWINSZ, &ws) < 0)
1139 err(EX_OSERR, "ERROR: Cannot determine window size");
1141 pmcstat_displayheight = ws.ws_row - 1;
1142 pmcstat_displaywidth = ws.ws_col - 1;
1144 EV_SET(&kev, SIGWINCH, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1146 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1148 "ERROR: Cannot register kevent for SIGWINCH");
1154 * Listen to key input in top mode.
1156 if (args.pa_flags & FLAG_DO_TOP) {
1157 EV_SET(&kev, fileno(stdin), EVFILT_READ, EV_ADD, 0, 0, NULL);
1158 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1159 err(EX_OSERR, "ERROR: Cannot register kevent");
1162 EV_SET(&kev, SIGINT, 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 SIGINT");
1166 EV_SET(&kev, SIGIO, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1167 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1168 err(EX_OSERR, "ERROR: Cannot register kevent for SIGIO");
1171 * An exec() failure of a forked child is signalled by the
1172 * child sending the parent a SIGCHLD. We don't register an
1173 * actual signal handler for SIGCHLD, but instead use our
1174 * kqueue to pick up the signal.
1176 EV_SET(&kev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
1177 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1178 err(EX_OSERR, "ERROR: Cannot register kevent for SIGCHLD");
1181 * Setup a timer if we have counting mode PMCs needing to be printed or
1182 * top mode plugin is active.
1184 if (((args.pa_flags & FLAG_HAS_COUNTING_PMCS) &&
1185 (args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) ||
1186 (args.pa_flags & FLAG_DO_TOP)) {
1187 EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1188 args.pa_interval * 1000, NULL);
1190 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1192 "ERROR: Cannot register kevent for timer");
1196 * Setup a duration timer if we have sampling mode PMCs and
1197 * a duration time is set
1199 if ((args.pa_flags & FLAG_HAS_SAMPLING_PMCS) &&
1200 (args.pa_flags & FLAG_HAS_DURATION)) {
1201 EV_SET(&kev, 0, EVFILT_TIMER, EV_ADD, 0,
1202 args.pa_duration * 1000, NULL);
1204 if (kevent(pmcstat_kq, &kev, 1, NULL, 0, NULL) < 0)
1205 err(EX_OSERR, "ERROR: Cannot register kevent for "
1209 /* attach PMCs to the target process, starting it if specified */
1210 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1211 pmcstat_create_process(pmcstat_sockpair, &args, pmcstat_kq);
1213 if (check_driver_stats && pmc_get_driver_stats(&ds_start) < 0)
1214 err(EX_OSERR, "ERROR: Cannot retrieve driver statistics");
1216 /* Attach process pmcs to the target process. */
1217 if (args.pa_flags & (FLAG_HAS_TARGET | FLAG_HAS_COMMANDLINE)) {
1218 if (SLIST_EMPTY(&args.pa_targets))
1220 "ERROR: No matching target processes.");
1221 if (args.pa_flags & FLAG_HAS_PROCESS_PMCS)
1222 pmcstat_attach_pmcs(&args);
1225 kvm_close(pmcstat_kvm);
1230 /* start the pmcs */
1231 pmcstat_start_pmcs();
1233 /* start the (commandline) process if needed */
1234 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1235 pmcstat_start_process(pmcstat_sockpair);
1237 /* initialize logging */
1238 pmcstat_log_initialize_logging();
1240 /* Handle SIGINT using the kqueue loop */
1241 sa.sa_handler = SIG_IGN;
1243 (void) sigemptyset(&sa.sa_mask);
1245 if (sigaction(SIGINT, &sa, NULL) < 0)
1246 err(EX_OSERR, "ERROR: Cannot install signal handler");
1249 * Setup the top mode display.
1251 if (args.pa_flags & FLAG_DO_TOP) {
1252 args.pa_flags &= ~FLAG_DO_PRINT;
1254 if (args.pa_toptty) {
1259 if(has_colors() == TRUE) {
1260 args.pa_topcolor = 1;
1262 use_default_colors();
1263 pair_content(0, &cf, &cb);
1264 init_pair(1, COLOR_RED, cb);
1265 init_pair(2, COLOR_YELLOW, cb);
1266 init_pair(3, COLOR_GREEN, cb);
1272 intrflush(stdscr, FALSE);
1273 keypad(stdscr, TRUE);
1275 /* Get terminal width / height with ncurses. */
1277 pmcstat_displayheight, pmcstat_displaywidth);
1278 pmcstat_displayheight--; pmcstat_displaywidth--;
1279 atexit(pmcstat_topexit);
1284 * loop till either the target process (if any) exits, or we
1285 * are killed by a SIGINT or we reached the time duration.
1287 runstate = PMCSTAT_RUNNING;
1288 do_print = do_read = 0;
1290 if ((c = kevent(pmcstat_kq, NULL, 0, &kev, 1, NULL)) <= 0) {
1292 err(EX_OSERR, "ERROR: kevent failed");
1297 if (kev.flags & EV_ERROR)
1298 errc(EX_OSERR, kev.data, "ERROR: kevent failed");
1300 switch (kev.filter) {
1301 case EVFILT_PROC: /* target has exited */
1302 runstate = pmcstat_close_log(&args);
1306 case EVFILT_READ: /* log file data is present */
1307 if (kev.ident == (unsigned)fileno(stdin) &&
1308 (args.pa_flags & FLAG_DO_TOP)) {
1309 if (pmcstat_keypress_log())
1310 runstate = pmcstat_close_log(&args);
1313 runstate = pmcstat_process_log();
1318 if (kev.ident == SIGCHLD) {
1320 * The child process sends us a
1321 * SIGCHLD if its exec() failed. We
1322 * wait for it to exit and then exit
1326 runstate = PMCSTAT_FINISHED;
1327 } else if (kev.ident == SIGIO) {
1329 * We get a SIGIO if a PMC loses all
1330 * of its targets, or if logfile
1331 * writes encounter an error.
1333 runstate = pmcstat_close_log(&args);
1334 do_print = 1; /* print PMCs at exit */
1335 } else if (kev.ident == SIGINT) {
1336 /* Kill the child process if we started it */
1337 if (args.pa_flags & FLAG_HAS_COMMANDLINE)
1338 pmcstat_kill_process();
1339 runstate = pmcstat_close_log(&args);
1340 } else if (kev.ident == SIGWINCH) {
1341 if (ioctl(fileno(args.pa_printfile),
1342 TIOCGWINSZ, &ws) < 0)
1344 "ERROR: Cannot determine window size");
1345 pmcstat_displayheight = ws.ws_row - 1;
1346 pmcstat_displaywidth = ws.ws_col - 1;
1353 /* time duration reached, exit */
1354 if (args.pa_flags & FLAG_HAS_DURATION) {
1355 runstate = PMCSTAT_FINISHED;
1358 /* print out counting PMCs */
1359 if ((args.pa_flags & FLAG_DO_TOP) &&
1360 (args.pa_flags & FLAG_HAS_PIPE) &&
1361 pmc_flush_logfile() == 0)
1368 if (do_print && !do_read) {
1369 if ((args.pa_required & FLAG_HAS_OUTPUT_LOGFILE) == 0) {
1370 pmcstat_print_pmcs();
1371 if (runstate == PMCSTAT_FINISHED &&
1373 (args.pa_flags & FLAG_DO_PRINT) == 0)
1374 (void) fprintf(args.pa_printfile, "\n");
1376 if (args.pa_flags & FLAG_DO_TOP)
1377 pmcstat_display_log();
1381 } while (runstate != PMCSTAT_FINISHED);
1383 if ((args.pa_flags & FLAG_DO_TOP) && args.pa_toptty) {
1388 /* flush any pending log entries */
1389 if (args.pa_flags & (FLAG_HAS_OUTPUT_LOGFILE | FLAG_HAS_PIPE))
1390 pmc_close_logfile();
1394 /* check if the driver lost any samples or events */
1395 if (check_driver_stats) {
1396 if (pmc_get_driver_stats(&ds_end) < 0)
1398 "ERROR: Cannot retrieve driver statistics");
1399 if (ds_start.pm_intr_bufferfull != ds_end.pm_intr_bufferfull &&
1400 args.pa_verbosity > 0)
1402 "WARNING: sampling was paused at least %u time%s.\n"
1403 "Please consider tuning the \"kern.hwpmc.nsamples\" tunable.",
1404 ds_end.pm_intr_bufferfull -
1405 ds_start.pm_intr_bufferfull,
1406 ((ds_end.pm_intr_bufferfull -
1407 ds_start.pm_intr_bufferfull) != 1) ? "s" : ""
1409 if (ds_start.pm_buffer_requests_failed !=
1410 ds_end.pm_buffer_requests_failed &&
1411 args.pa_verbosity > 0)
1413 "WARNING: at least %u event%s were discarded while running.\n"
1414 "Please consider tuning the \"kern.hwpmc.nbuffers\" tunable.",
1415 ds_end.pm_buffer_requests_failed -
1416 ds_start.pm_buffer_requests_failed,
1417 ((ds_end.pm_buffer_requests_failed -
1418 ds_start.pm_buffer_requests_failed) != 1) ? "s" : ""