vmstat - Add verbose for -m
[dragonfly.git] / usr.bin / vmstat / vmstat.c
1 /*
2  * Copyright (c) 1980, 1986, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1980, 1986, 1991, 1993 The Regents of the University of California.  All rights reserved.
30  * @(#)vmstat.c 8.1 (Berkeley) 6/6/93
31  * $FreeBSD: src/usr.bin/vmstat/vmstat.c,v 1.38.2.4 2001/07/31 19:52:41 tmm Exp $
32  */
33
34 #include <sys/user.h>
35 #include <sys/param.h>
36 #include <sys/time.h>
37 #include <sys/uio.h>
38 #include <sys/namei.h>
39 #include <sys/objcache.h>
40 #include <sys/signal.h>
41 #include <sys/fcntl.h>
42 #include <sys/ioctl.h>
43 #include <sys/sysctl.h>
44 #include <sys/vmmeter.h>
45 #include <sys/interrupt.h>
46
47 #include <vm/vm_param.h>
48 #include <vm/vm_zone.h>
49
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <kinfo.h>
54 #include <kvm.h>
55 #include <limits.h>
56 #include <nlist.h>
57 #include <paths.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <sysexits.h>
62 #include <time.h>
63 #include <unistd.h>
64 #include <devstat.h>
65
66 static struct nlist namelist[] = {
67 #define X_BOOTTIME      0
68         { "_boottime",  0, 0, 0, 0 },
69 #define X_NCHSTATS      1
70         { "_nchstats",  0, 0, 0, 0 },
71 #define X_KMEMSTATISTICS        2
72         { "_kmemstatistics",    0, 0, 0, 0 },
73 #define X_ZLIST         3
74         { "_zlist",     0, 0, 0, 0 },
75 #ifdef notyet
76 #define X_DEFICIT       4
77         { "_deficit",   0, 0, 0, 0 },
78 #define X_FORKSTAT      5
79         { "_forkstat",  0, 0, 0, 0 },
80 #define X_REC           6
81         { "_rectime",   0, 0, 0, 0 },
82 #define X_PGIN          7
83         { "_pgintime",  0, 0, 0, 0 },
84 #define X_XSTATS        8
85         { "_xstats",    0, 0, 0, 0 },
86 #define X_END           9
87 #else
88 #define X_END           4
89 #endif
90         { "", 0, 0, 0, 0 },
91 };
92
93 #define ONEMB   (1024L * 1024L)
94 #define ONEKB   (1024L)
95
96 LIST_HEAD(zlist, vm_zone);
97
98 struct statinfo cur, last;
99 int num_devices, maxshowdevs;
100 long generation;
101 struct device_selection *dev_select;
102 int num_selected;
103 struct devstat_match *matches;
104 int num_matches = 0;
105 int num_devices_specified, num_selections;
106 long select_generation;
107 char **specified_devices;
108 devstat_select_mode select_mode;
109
110 struct  vmmeter vmm, ovmm;
111 struct  vmstats vms, ovms;
112
113 int     winlines = 20;
114 int     nflag = 0;
115 int     verbose = 0;
116 int     unformatted_opt = 0;
117 int     brief_opt = 0;
118 int     ncpus;
119
120 kvm_t *kd;
121
122 struct kinfo_cputime cp_time, old_cp_time, diff_cp_time;
123
124 #define FORKSTAT        0x01
125 #define INTRSTAT        0x02
126 #define MEMSTAT         0x04
127 #define SUMSTAT         0x08
128 #define TIMESTAT        0x10
129 #define VMSTAT          0x20
130 #define ZMEMSTAT        0x40
131 #define OCSTAT          0x80
132
133 static void cpustats(void);
134 static void dointr(void);
135 static void domem(void);
136 static void dooc(void);
137 static void dosum(void);
138 static void dozmem(u_int interval, int reps);
139 static void dovmstat(u_int, int);
140 static void kread(int, void *, size_t);
141 static void usage(void);
142 static char **getdrivedata(char **);
143 static long getuptime(void);
144 static void needhdr(int);
145 static long pct(long, long);
146
147 #ifdef notyet
148 static void dotimes(void); /* Not implemented */
149 static void doforkst(void);
150 #endif
151 static void printhdr(void);
152 static const char *formatnum(intmax_t value, int width, int do10s);
153 static void devstats(int dooutput);
154
155 int
156 main(int argc, char **argv)
157 {
158         int c, todo;
159         u_int interval;         /* milliseconds */
160         int reps;
161         char *memf, *nlistf;
162         char errbuf[_POSIX2_LINE_MAX];
163         size_t ncpus_size = sizeof(ncpus);
164
165         if (sysctlbyname("hw.ncpu", &ncpus, &ncpus_size, NULL, 0) < 0) {
166                 perror("sysctl hw.ncpu");
167                 exit(1);
168         }
169
170         memf = nlistf = NULL;
171         interval = reps = todo = 0;
172         maxshowdevs = 2;
173         while ((c = getopt(argc, argv, "bc:fiM:mN:n:op:stuvw:z")) != -1) {
174                 switch (c) {
175                 case 'b':
176                         brief_opt = 1;
177                         break;
178                 case 'c':
179                         reps = atoi(optarg);
180                         break;
181                 case 'f':
182 #ifdef notyet
183                         todo |= FORKSTAT;
184 #else
185                         errx(EX_USAGE, "sorry, -f is not (re)implemented yet");
186 #endif
187                         break;
188                 case 'i':
189                         todo |= INTRSTAT;
190                         break;
191                 case 'M':
192                         memf = optarg;
193                         break;
194                 case 'm':
195                         todo |= MEMSTAT;
196                         break;
197                 case 'N':
198                         nlistf = optarg;
199                         break;
200                 case 'n':
201                         nflag = 1;
202                         maxshowdevs = atoi(optarg);
203                         if (maxshowdevs < 0)
204                                 errx(1, "number of devices %d is < 0",
205                                      maxshowdevs);
206                         break;
207                 case 'o':
208                         todo |= OCSTAT;
209                         break;
210                 case 'p':
211                         if (buildmatch(optarg, &matches, &num_matches) != 0)
212                                 errx(1, "%s", devstat_errbuf);
213                         break;
214                 case 's':
215                         todo |= SUMSTAT;
216                         break;
217                 case 't':
218 #ifdef notyet
219                         todo |= TIMESTAT;
220 #else
221                         errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
222 #endif
223                         break;
224                 case 'u':
225                         unformatted_opt = 1;
226                         break;
227                 case 'v':
228                         ++verbose;
229                         break;
230                 case 'w':
231                         interval = (u_int)(strtod(optarg, NULL) * 1000.0);
232                         break;
233                 case 'z':
234                         todo |= ZMEMSTAT;
235                         break;
236                 default:
237                         usage();
238                 }
239         }
240         argc -= optind;
241         argv += optind;
242
243         if (todo == 0)
244                 todo = VMSTAT;
245
246         /*
247          * Discard setgid privileges if not the running kernel so that bad
248          * guys can't print interesting stuff from kernel memory.
249          */
250         if (nlistf != NULL || memf != NULL) {
251                 setgid(getgid());
252                 if (todo & OCSTAT) {
253                         errx(1, "objcache stats can only be gathered on "
254                             "the running system");
255                 }
256         }
257
258         kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
259         if (kd == NULL)
260                 errx(1, "kvm_openfiles: %s", errbuf);
261
262         if ((c = kvm_nlist(kd, namelist)) != 0) {
263                 if (c > 0) {
264                         warnx("undefined symbols:");
265                         for (c = 0; c < (int)NELEM(namelist); c++)
266                                 if (namelist[c].n_type == 0)
267                                         fprintf(stderr, " %s",
268                                             namelist[c].n_name);
269                         fputc('\n', stderr);
270                 } else
271                         warnx("kvm_nlist: %s", kvm_geterr(kd));
272                 exit(1);
273         }
274
275         if (todo & VMSTAT) {
276                 struct winsize winsize;
277
278                 /*
279                  * Make sure that the userland devstat version matches the
280                  * kernel devstat version.  If not, exit and print a
281                  * message informing the user of his mistake.
282                  */
283                 if (checkversion() < 0)
284                         errx(1, "%s", devstat_errbuf);
285
286
287                 argv = getdrivedata(argv);
288                 winsize.ws_row = 0;
289                 ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
290                 if (winsize.ws_row > 0)
291                         winlines = winsize.ws_row;
292
293         }
294
295 #define BACKWARD_COMPATIBILITY
296 #ifdef  BACKWARD_COMPATIBILITY
297         if (*argv) {
298                 interval = (u_int)(strtod(*argv, NULL) * 1000.0);
299                 if (*++argv)
300                         reps = atoi(*argv);
301         }
302 #endif
303
304         if (interval) {
305                 if (!reps)
306                         reps = -1;
307         } else if (reps) {
308                 interval = 1000;
309         }
310
311 #ifdef notyet
312         if (todo & FORKSTAT)
313                 doforkst();
314 #endif
315         if (todo & MEMSTAT)
316                 domem();
317         if (todo & ZMEMSTAT)
318                 dozmem(interval, reps);
319         if (todo & SUMSTAT)
320                 dosum();
321 #ifdef notyet
322         if (todo & TIMESTAT)
323                 dotimes();
324 #endif
325         if (todo & INTRSTAT)
326                 dointr();
327         if (todo & VMSTAT)
328                 dovmstat(interval, reps);
329         if (todo & OCSTAT)
330                 dooc();
331         exit(0);
332 }
333
334 static char **
335 getdrivedata(char **argv)
336 {
337         if ((num_devices = getnumdevs()) < 0)
338                 errx(1, "%s", devstat_errbuf);
339
340         cur.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
341         last.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
342         bzero(cur.dinfo, sizeof(struct devinfo));
343         bzero(last.dinfo, sizeof(struct devinfo));
344
345         if (getdevs(&cur) == -1)
346                 errx(1, "%s", devstat_errbuf);
347
348         num_devices = cur.dinfo->numdevs;
349         generation = cur.dinfo->generation;
350
351         specified_devices = (char **)malloc(sizeof(char *));
352         for (num_devices_specified = 0; *argv; ++argv) {
353                 if (isdigit(**argv))
354                         break;
355                 num_devices_specified++;
356                 specified_devices = (char **)realloc(specified_devices,
357                                                      sizeof(char *) *
358                                                      num_devices_specified);
359                 specified_devices[num_devices_specified - 1] = *argv;
360         }
361         dev_select = NULL;
362
363         if (nflag == 0 && maxshowdevs < num_devices_specified)
364                         maxshowdevs = num_devices_specified;
365
366         /*
367          * People are generally only interested in disk statistics when
368          * they're running vmstat.  So, that's what we're going to give
369          * them if they don't specify anything by default.  We'll also give
370          * them any other random devices in the system so that we get to
371          * maxshowdevs devices, if that many devices exist.  If the user
372          * specifies devices on the command line, either through a pattern
373          * match or by naming them explicitly, we will give the user only
374          * those devices.
375          */
376         if ((num_devices_specified == 0) && (num_matches == 0)) {
377                 if (buildmatch("da", &matches, &num_matches) != 0)
378                         errx(1, "%s", devstat_errbuf);
379
380                 select_mode = DS_SELECT_ADD;
381         } else
382                 select_mode = DS_SELECT_ONLY;
383
384         /*
385          * At this point, selectdevs will almost surely indicate that the
386          * device list has changed, so we don't look for return values of 0
387          * or 1.  If we get back -1, though, there is an error.
388          */
389         if (selectdevs(&dev_select, &num_selected, &num_selections,
390                        &select_generation, generation, cur.dinfo->devices,
391                        num_devices, matches, num_matches, specified_devices,
392                        num_devices_specified, select_mode,
393                        maxshowdevs, 0) == -1)
394                 errx(1, "%s", devstat_errbuf);
395
396         return(argv);
397 }
398
399 static long
400 getuptime(void)
401 {
402         static time_t now, boottime;
403         time_t uptime;
404
405         if (boottime == 0)
406                 kread(X_BOOTTIME, &boottime, sizeof(boottime));
407         time(&now);
408         uptime = now - boottime;
409         if (uptime <= 0 || uptime > 60*60*24*365*10)
410                 errx(1, "time makes no sense; namelist must be wrong");
411         return(uptime);
412 }
413
414 int     hdrcnt;
415
416 static void
417 dovmstat(u_int interval, int reps)
418 {
419         struct vmtotal total;
420         struct devinfo *tmp_dinfo;
421         size_t vmm_size = sizeof(vmm);
422         size_t vms_size = sizeof(vms);
423         size_t vmt_size = sizeof(total);
424         int initial = 1;
425         int dooutput = 1;
426
427         signal(SIGCONT, needhdr);
428         if (reps != 0)
429                 dooutput = 0;
430
431         for (hdrcnt = 1;;) {
432                 if (!--hdrcnt)
433                         printhdr();
434                 if (kinfo_get_sched_cputime(&cp_time))
435                         err(1, "kinfo_get_sched_cputime");
436
437                 tmp_dinfo = last.dinfo;
438                 last.dinfo = cur.dinfo;
439                 cur.dinfo = tmp_dinfo;
440                 last.busy_time = cur.busy_time;
441
442                 /*
443                  * Here what we want to do is refresh our device stats.
444                  * getdevs() returns 1 when the device list has changed.
445                  * If the device list has changed, we want to go through
446                  * the selection process again, in case a device that we
447                  * were previously displaying has gone away.
448                  */
449                 switch (getdevs(&cur)) {
450                 case -1:
451                         errx(1, "%s", devstat_errbuf);
452                         break;
453                 case 1: {
454                         int retval;
455
456                         num_devices = cur.dinfo->numdevs;
457                         generation = cur.dinfo->generation;
458
459                         retval = selectdevs(&dev_select, &num_selected,
460                                             &num_selections, &select_generation,
461                                             generation, cur.dinfo->devices,
462                                             num_devices, matches, num_matches,
463                                             specified_devices,
464                                             num_devices_specified, select_mode,
465                                             maxshowdevs, 0);
466                         switch (retval) {
467                         case -1:
468                                 errx(1, "%s", devstat_errbuf);
469                                 break;
470                         case 1:
471                                 printhdr();
472                                 break;
473                         default:
474                                 break;
475                         }
476                 }
477                 default:
478                         break;
479                 }
480
481                 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
482                         perror("sysctlbyname: vm.vmstats");
483                         exit(1);
484                 }
485                 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
486                         perror("sysctlbyname: vm.vmmeter");
487                         exit(1);
488                 }
489                 if (sysctlbyname("vm.vmtotal", &total, &vmt_size, NULL, 0)) {
490                         perror("sysctlbyname: vm.vmtotal");
491                         exit(1);
492                 }
493                 if (dooutput) {
494                         printf("%3ld %2ld %2ld",
495                                total.t_rq - 1,
496                                total.t_dw + total.t_pw,
497                                total.t_sw);
498                 }
499
500 #define rate(x)         \
501         (intmax_t)(initial ? (x) : ((intmax_t)(x) * 1000 + interval / 2) \
502                                    / interval)
503
504                 if (dooutput) {
505                         printf(" %s ",
506                                formatnum((int64_t)total.t_free *
507                                          vms.v_page_size,
508                                          5, 1));
509                         printf("%s ",
510                                formatnum(rate(vmm.v_vm_faults -
511                                               ovmm.v_vm_faults),
512                                          5, 1));
513                         printf("%s ",
514                                formatnum(rate(vmm.v_reactivated -
515                                               ovmm.v_reactivated),
516                                          4, 0));
517                         printf("%s ",
518                                formatnum(rate(vmm.v_swapin + vmm.v_vnodein -
519                                               (ovmm.v_swapin +
520                                                ovmm.v_vnodein)),
521                                          4, 0));
522                         printf("%s ",
523                                formatnum(rate(vmm.v_swapout + vmm.v_vnodeout -
524                                               (ovmm.v_swapout +
525                                                ovmm.v_vnodeout)),
526                                          4, 0));
527                         printf("%s ",
528                                formatnum(rate(vmm.v_tfree - ovmm.v_tfree),
529                                          4, 0));
530                 }
531                 devstats(dooutput);
532                 if (dooutput) {
533                         printf("%s ",
534                                formatnum(rate(vmm.v_intr - ovmm.v_intr),
535                                          5, 1));
536                         printf("%s ",
537                                formatnum(rate(vmm.v_syscall -
538                                               ovmm.v_syscall),
539                                          5, 1));
540                         printf("%s ",
541                                formatnum(rate(vmm.v_swtch -
542                                               ovmm.v_swtch),
543                                          5, 1));
544                         cpustats();
545                         printf("\n");
546                         fflush(stdout);
547                 }
548                 if (reps >= 0 && --reps <= 0)
549                         break;
550                 ovmm = vmm;
551                 usleep(interval * 1000);
552                 initial = 0;
553                 dooutput = 1;
554         }
555 }
556
557 static const char *
558 formatnum(intmax_t value, int width, int do10s)
559 {
560         static char buf[16][64];
561         static int bi;
562         const char *fmt;
563         double d;
564
565         if (brief_opt)
566                 do10s = 0;
567
568         bi = (bi + 1) % 16;
569
570         if (unformatted_opt) {
571                 switch(width) {
572                 case 4:
573                         snprintf(buf[bi], sizeof(buf[bi]), "%4jd", value);
574                         break;
575                 case 5:
576                         snprintf(buf[bi], sizeof(buf[bi]), "%5jd", value);
577                         break;
578                 default:
579                         snprintf(buf[bi], sizeof(buf[bi]), "%jd", value);
580                         break;
581                 }
582                 return buf[bi];
583         }
584
585         d = (double)value;
586         fmt = "n/a";
587
588         switch(width) {
589         case 4:
590                 if (value < 1024) {
591                         fmt = "%4.0f";
592                 } else if (value < 10*1024) {
593                         fmt = "%3.1fK";
594                         d = d / 1024;
595                 } else if (value < 1000*1024) {
596                         fmt = "%3.0fK";
597                         d = d / 1024;
598                 } else if (value < 10*1024*1024) {
599                         fmt = "%3.1fM";
600                         d = d / (1024 * 1024);
601                 } else if (value < 1000*1024*1024) {
602                         fmt = "%3.0fM";
603                         d = d / (1024 * 1024);
604                 } else {
605                         fmt = "%3.1fG";
606                         d = d / (1024.0 * 1024.0 * 1024.0);
607                 }
608                 break;
609         case 5:
610                 if (value < 1024) {
611                         fmt = "%5.0f";
612                 } else if (value < 10*1024) {
613                         fmt = "%4.2fK";
614                         d = d / 1024;
615                 } else if (value < 100*1024 && do10s) {
616                         fmt = "%4.1fK";
617                         d = d / 1024;
618                 } else if (value < 1000*1024) {
619                         fmt = "%4.0fK";
620                         d = d / 1024;
621                 } else if (value < 10*1024*1024) {
622                         fmt = "%4.2fM";
623                         d = d / (1024 * 1024);
624                 } else if (value < 100*1024*1024 && do10s) {
625                         fmt = "%4.1fM";
626                         d = d / (1024 * 1024);
627                 } else if (value < 1000*1024*1024) {
628                         fmt = "%4.0fM";
629                         d = d / (1024 * 1024);
630                 } else if (value < 10LL*1024*1024*1024) {
631                         fmt = "%4.2fG";
632                         d = d / (1024.0 * 1024.0 * 1024.0);
633                 } else if (value < 100LL*1024*1024*1024 && do10s) {
634                         fmt = "%4.1fG";
635                         d = d / (1024.0 * 1024.0 * 1024.0);
636                 } else if (value < 1000LL*1024*1024*1024) {
637                         fmt = "%4.0fG";
638                         d = d / (1024.0 * 1024.0 * 1024.0);
639                 } else {
640                         fmt = "%4.2fT";
641                         d = d / (1024.0 * 1024.0 * 1024.0 * 1024.0);
642                 }
643                 break;
644         default:
645                 fprintf(stderr, "formatnum: unsupported width %d\n", width);
646                 exit(1);
647                 break;
648         }
649         snprintf(buf[bi], sizeof(buf[bi]), fmt, d);
650         return buf[bi];
651 }
652
653 static void
654 printhdr(void)
655 {
656         int i, num_shown;
657
658         num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
659         printf("--procs-- ---memory-- -------paging------ ");
660         if (num_shown > 1)
661                 printf("--disks%.*s",
662                        num_shown * 4 - 6,
663                        "---------------------------------");
664         else if (num_shown == 1)
665                 printf("disk");
666         printf(" -----faults------ ---cpu---\n");
667         printf("  r  b  w   fre   flt   re   pi   po   fr ");
668         for (i = 0; i < num_devices; i++)
669                 if ((dev_select[i].selected)
670                  && (dev_select[i].selected <= maxshowdevs))
671                         printf(" %c%c%d ", dev_select[i].device_name[0],
672                                      dev_select[i].device_name[1],
673                                      dev_select[i].unit_number);
674         printf("  int   sys   ctx us sy id\n");
675         hdrcnt = winlines - 2;
676 }
677
678 /*
679  * Force a header to be prepended to the next output.
680  */
681 static void
682 needhdr(__unused int signo)
683 {
684
685         hdrcnt = 1;
686 }
687
688 static long
689 pct(long top, long bot)
690 {
691         long ans;
692
693         if (bot == 0)
694                 return(0);
695         ans = (quad_t)top * 100 / bot;
696         return (ans);
697 }
698
699 #define PCT(top, bot) pct((long)(top), (long)(bot))
700
701 static void
702 dosum(void)
703 {
704         struct nchstats *nch_tmp, nchstats;
705         size_t vms_size = sizeof(vms);
706         size_t vmm_size = sizeof(vmm);
707         int cpucnt;
708         u_long nchtotal;
709         u_long nchpathtotal;
710         size_t nch_size = sizeof(struct nchstats) * SMP_MAXCPU;
711
712         if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
713                 perror("sysctlbyname: vm.vmstats");
714                 exit(1);
715         }
716         if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
717                 perror("sysctlbyname: vm.vmstats");
718                 exit(1);
719         }
720         printf("%9u cpu context switches\n", vmm.v_swtch);
721         printf("%9u device interrupts\n", vmm.v_intr);
722         printf("%9u software interrupts\n", vmm.v_soft);
723         printf("%9u traps\n", vmm.v_trap);
724         printf("%9u system calls\n", vmm.v_syscall);
725         printf("%9u kernel threads created\n", vmm.v_kthreads);
726         printf("%9u  fork() calls\n", vmm.v_forks);
727         printf("%9u vfork() calls\n", vmm.v_vforks);
728         printf("%9u rfork() calls\n", vmm.v_rforks);
729         printf("%9u exec() calls\n", vmm.v_exec);
730         printf("%9u swap pager pageins\n", vmm.v_swapin);
731         printf("%9u swap pager pages paged in\n", vmm.v_swappgsin);
732         printf("%9u swap pager pageouts\n", vmm.v_swapout);
733         printf("%9u swap pager pages paged out\n", vmm.v_swappgsout);
734         printf("%9u vnode pager pageins\n", vmm.v_vnodein);
735         printf("%9u vnode pager pages paged in\n", vmm.v_vnodepgsin);
736         printf("%9u vnode pager pageouts\n", vmm.v_vnodeout);
737         printf("%9u vnode pager pages paged out\n", vmm.v_vnodepgsout);
738         printf("%9u page daemon wakeups\n", vmm.v_pdwakeups);
739         printf("%9u pages examined by the page daemon\n", vmm.v_pdpages);
740         printf("%9u pages reactivated\n", vmm.v_reactivated);
741         printf("%9u copy-on-write faults\n", vmm.v_cow_faults);
742         printf("%9u copy-on-write optimized faults\n", vmm.v_cow_optim);
743         printf("%9u zero fill pages zeroed\n", vmm.v_zfod);
744         printf("%9u zero fill pages prezeroed\n", vmm.v_ozfod);
745         printf("%9u intransit blocking page faults\n", vmm.v_intrans);
746         printf("%9u total VM faults taken\n", vmm.v_vm_faults);
747         printf("%9u pages affected by kernel thread creation\n", vmm.v_kthreadpages);
748         printf("%9u pages affected by  fork()\n", vmm.v_forkpages);
749         printf("%9u pages affected by vfork()\n", vmm.v_vforkpages);
750         printf("%9u pages affected by rfork()\n", vmm.v_rforkpages);
751         printf("%9u pages freed\n", vmm.v_tfree);
752         printf("%9u pages freed by daemon\n", vmm.v_dfree);
753         printf("%9u pages freed by exiting processes\n", vmm.v_pfree);
754         printf("%9lu pages active\n", vms.v_active_count);
755         printf("%9lu pages inactive\n", vms.v_inactive_count);
756         printf("%9lu pages in VM cache\n", vms.v_cache_count);
757         printf("%9lu pages wired down\n", vms.v_wire_count);
758         printf("%9lu pages free\n", vms.v_free_count);
759         printf("%9u bytes per page\n", vms.v_page_size);
760         printf("%9u global smp invltlbs\n", vmm.v_smpinvltlb);
761
762         if ((nch_tmp = malloc(nch_size)) == NULL) {
763                 perror("malloc");
764                 exit(1);
765         } else {
766                 if (sysctlbyname("vfs.cache.nchstats", nch_tmp, &nch_size, NULL, 0)) {
767                         perror("sysctlbyname vfs.cache.nchstats");
768                         free(nch_tmp);
769                         exit(1);
770                 } else {
771                         if ((nch_tmp = realloc(nch_tmp, nch_size)) == NULL) {
772                                 perror("realloc");
773                                 exit(1);
774                         }
775                 }
776         }
777
778         cpucnt = nch_size / sizeof(struct nchstats);
779         kvm_nch_cpuagg(nch_tmp, &nchstats, cpucnt);
780
781         nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
782             nchstats.ncs_badhits + nchstats.ncs_falsehits +
783             nchstats.ncs_miss;
784         nchpathtotal = nchstats.ncs_longhits + nchstats.ncs_longmiss;
785         printf("%9ld total path lookups\n", nchpathtotal);
786         printf("%9ld total component lookups\n", nchtotal);
787         printf(
788             "%9s cache hits (%ld%% pos + %ld%% neg)\n",
789             "", PCT(nchstats.ncs_goodhits, nchtotal),
790             PCT(nchstats.ncs_neghits, nchtotal));
791         printf("%9s deletions %ld%%, falsehits %ld%%\n", "",
792             PCT(nchstats.ncs_badhits, nchtotal),
793             PCT(nchstats.ncs_falsehits, nchtotal));
794         free(nch_tmp);
795 }
796
797 #ifdef notyet
798 void
799 doforkst(void)
800 {
801         struct forkstat fks;
802
803         kread(X_FORKSTAT, &fks, sizeof(struct forkstat));
804         printf("%d forks, %d pages, average %.2f\n",
805             fks.cntfork, fks.sizfork, (double)fks.sizfork / fks.cntfork);
806         printf("%d vforks, %d pages, average %.2f\n",
807             fks.cntvfork, fks.sizvfork, (double)fks.sizvfork / fks.cntvfork);
808 }
809 #endif
810
811 static void
812 devstats(int dooutput)
813 {
814         int dn;
815         long double transfers_per_second;
816         long double busy_seconds;
817
818         diff_cp_time.cp_user = cp_time.cp_user - old_cp_time.cp_user;
819         diff_cp_time.cp_nice = cp_time.cp_nice - old_cp_time.cp_nice;
820         diff_cp_time.cp_sys = cp_time.cp_sys - old_cp_time.cp_sys;
821         diff_cp_time.cp_intr = cp_time.cp_intr - old_cp_time.cp_intr;
822         diff_cp_time.cp_idle = cp_time.cp_idle - old_cp_time.cp_idle;
823         old_cp_time = cp_time;
824
825         busy_seconds = compute_etime(cur.busy_time, last.busy_time);
826
827         for (dn = 0; dn < num_devices; dn++) {
828                 int di;
829
830                 if ((dev_select[dn].selected == 0)
831                  || (dev_select[dn].selected > maxshowdevs))
832                         continue;
833
834                 di = dev_select[dn].position;
835
836                 if (compute_stats(&cur.dinfo->devices[di],
837                                   &last.dinfo->devices[di], busy_seconds,
838                                   NULL, NULL, NULL,
839                                   NULL, &transfers_per_second, NULL,
840                                   NULL, NULL) != 0)
841                         errx(1, "%s", devstat_errbuf);
842
843                 if (dooutput)
844                         printf("%s ", formatnum(transfers_per_second, 4, 0));
845         }
846 }
847
848 static void
849 cpustats(void)
850 {
851         uint64_t total;
852         double totusage;
853
854         total = diff_cp_time.cp_user + diff_cp_time.cp_nice +
855             diff_cp_time.cp_sys + diff_cp_time.cp_intr + diff_cp_time.cp_idle;
856
857         if (total)
858                 totusage = 100.0 / total;
859         else
860                 totusage = 0;
861         printf("%2.0f ",
862                (diff_cp_time.cp_user + diff_cp_time.cp_nice) * totusage);
863         printf("%2.0f ",
864                (diff_cp_time.cp_sys + diff_cp_time.cp_intr) * totusage);
865         printf("%2.0f",
866                diff_cp_time.cp_idle * totusage);
867 }
868
869 static void
870 dointr(void)
871 {
872         u_long *intrcnt, uptime;
873         u_int64_t inttotal;
874         size_t nintr, inamlen, i, size;
875         int nwidth;
876         char *intrstr;
877         char **intrname;
878
879         uptime = getuptime();
880         if (sysctlbyname("hw.intrnames", NULL, &inamlen, NULL, 0) != 0)
881                 errx(1, "sysctlbyname");
882         intrstr = malloc(inamlen);
883         if (intrstr == NULL)
884                 err(1, "malloc");
885         sysctlbyname("hw.intrnames", intrstr, &inamlen, NULL, 0);
886         for (nintr = 0, i = 0; i < inamlen; ++i) {
887                 if (intrstr[i] == 0)
888                         nintr++;
889         }
890         intrname = malloc(nintr * sizeof(char *));
891         for (i = 0; i < nintr; ++i) {
892                 intrname[i] = intrstr;
893                 intrstr += strlen(intrstr) + 1;
894         }
895
896         size = nintr * sizeof(*intrcnt);
897         intrcnt = calloc(nintr, sizeof(*intrcnt));
898         if (intrcnt == NULL)
899                 err(1, "malloc");
900         sysctlbyname("hw.intrcnt", intrcnt, &size, NULL, 0);
901
902         nwidth = 21;
903         for (i = 0; i < nintr; ++i) {
904                 if (nwidth < (int)strlen(intrname[i]))
905                         nwidth = (int)strlen(intrname[i]);
906         }
907         if (verbose) nwidth += 12;
908
909         printf("%-*.*s %11s %10s\n",
910                 nwidth, nwidth, "interrupt", "total", "rate");
911         inttotal = 0;
912         for (i = 0; i < nintr; ++i) {
913                 int named;
914                 char *infop, irqinfo[72];
915
916                 if ((named = strncmp(intrname[i], "irq", 3)) != 0 ||
917                     intrcnt[i] > 0) {
918                         infop = intrname[i];
919                         if (verbose) {
920                                 ssize_t irq, cpu;
921
922                                 irq = i % MAX_INTS;
923                                 cpu = i / MAX_INTS;
924                                 if (named) {
925                                         snprintf(irqinfo, sizeof(irqinfo),
926                                                  "irq%-3zd %3zd: %s",
927                                                  irq, cpu, intrname[i]);
928                                 } else {
929                                         snprintf(irqinfo, sizeof(irqinfo),
930                                                  "irq%-3zd %3zd: ", irq, cpu);
931                                 }
932                                 infop = irqinfo;
933                         }
934                         printf("%-*.*s %11lu %10lu\n",
935                                 nwidth, nwidth, infop,
936                                 intrcnt[i], intrcnt[i] / uptime);
937                 }
938                 inttotal += intrcnt[i];
939         }
940         printf("%-*.*s %11llu %10llu\n",
941                 nwidth, nwidth, "Total",
942                 (long long)inttotal, (long long)(inttotal / uptime));
943 }
944
945 #define MAX_KMSTATS     16384
946
947 enum ksuse { KSINUSE, KSMEMUSE, KSCALLS };
948
949 static long
950 cpuagg(struct malloc_type *ks, enum ksuse use)
951 {
952     int i;
953     long ttl;
954
955     ttl = 0;
956
957     switch(use) {
958     case KSINUSE:
959         for (i = 0; i < ncpus; ++i)
960             ttl += ks->ks_use[i].inuse;
961         break;
962     case KSMEMUSE:
963         for (i = 0; i < ncpus; ++i)
964             ttl += ks->ks_use[i].memuse;
965         break;
966     case KSCALLS:
967         for (i = 0; i < ncpus; ++i)
968             ttl += ks->ks_use[i].calls;
969         break;
970     }
971     return(ttl);
972 }
973
974 static void
975 domem(void)
976 {
977         struct malloc_type *ks;
978         int i;
979         int nkms;
980         long totuse = 0, totreq = 0;
981         struct malloc_type kmemstats[MAX_KMSTATS], *kmsp;
982         char buf[1024];
983
984         kread(X_KMEMSTATISTICS, &kmsp, sizeof(kmsp));
985         for (nkms = 0; nkms < MAX_KMSTATS && kmsp != NULL; nkms++) {
986                 if (sizeof(kmemstats[0]) != kvm_read(kd, (u_long)kmsp,
987                     &kmemstats[nkms], sizeof(kmemstats[0])))
988                         err(1, "kvm_read(%p)", (void *)kmsp);
989                 if (sizeof(buf) !=  kvm_read(kd,
990                     (u_long)kmemstats[nkms].ks_shortdesc, buf, sizeof(buf)))
991                         err(1, "kvm_read(%p)",
992                             kmemstats[nkms].ks_shortdesc);
993                 buf[sizeof(buf) - 1] = '\0';
994                 kmemstats[nkms].ks_shortdesc = strdup(buf);
995                 if (kmemstats[nkms].ks_use) {
996                         size_t usebytes;
997                         void *use;
998
999                         usebytes = ncpus * sizeof(kmemstats[nkms].ks_use[0]);
1000                         use = malloc(usebytes);
1001                         if (kvm_read(kd, (u_long)kmemstats[nkms].ks_use,
1002                                      use, usebytes) != (ssize_t)usebytes) {
1003                                 err(1, "kvm_read(%p)", kmemstats[nkms].ks_use);
1004                         }
1005                         kmemstats[nkms].ks_use = use;
1006                 }
1007                 kmsp = kmemstats[nkms].ks_next;
1008         }
1009         if (kmsp != NULL)
1010                 warnx("truncated to the first %d memory types", nkms);
1011
1012         printf(
1013             "\nMemory statistics by type\n");
1014         printf("               Type   Count  MemUse   Limit Requests\n");
1015         for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
1016                 long ks_inuse;
1017                 long ks_memuse;
1018                 long ks_calls;
1019
1020                 ks_calls = cpuagg(ks, KSCALLS);
1021                 if (ks_calls == 0 && verbose == 0)
1022                         continue;
1023
1024                 ks_inuse = cpuagg(ks, KSINUSE);
1025                 ks_memuse = cpuagg(ks, KSMEMUSE);
1026
1027                 printf("%19s   %s   %s   %s    %s\n",
1028                         ks->ks_shortdesc,
1029                         formatnum(ks_inuse, 5, 1),
1030                         formatnum(ks_memuse, 5, 1),
1031                         formatnum(ks->ks_limit, 5, 1),
1032                         formatnum(ks_calls, 5, 1));
1033
1034                 totuse += ks_memuse;
1035                 totreq += ks_calls;
1036         }
1037         printf("\nMemory Totals:  In Use  Requests\n");
1038         printf("                 %s  %s\n",
1039                 formatnum(totuse, 5, 1),
1040                 formatnum(totreq, 5, 1));
1041 }
1042
1043 static void
1044 dooc(void)
1045 {
1046         struct objcache_stats *stat, *s;
1047         size_t len, count;
1048
1049         if (sysctlbyname("kern.objcache.stats", NULL, &len, NULL, 0) < 0)
1050                 errx(1, "objcache stats sysctl failed\n");
1051
1052         /* Add some extra space. */
1053         stat = malloc(len + (8 * sizeof(*stat)));
1054         if (sysctlbyname("kern.objcache.stats", stat, &len, NULL, 0) < 0)
1055                 errx(1, "objcache stats sysctl failed\n");
1056
1057         printf(
1058             "\nObjcache statistics by name\n");
1059         printf("                 Name    Used  Cached   Limit Requests  Allocs Fails  Exhausts\n");
1060         for (s = stat, count = 0; count < len; ++s) {
1061                 printf("%21s   %s   %s   %s    %s   %s  %s  %s\n",
1062                     s->oc_name,
1063                     formatnum(s->oc_used, 5, 1),
1064                     formatnum(s->oc_cached, 5, 1),
1065                     s->oc_limit < OBJCACHE_UNLIMITED ?
1066                     formatnum(s->oc_limit, 5, 1) : "unlim",
1067                     formatnum(s->oc_requested, 5, 1),
1068                     formatnum(s->oc_allocated, 5, 1),
1069                     formatnum(s->oc_failed, 4, 1),
1070                     formatnum(s->oc_exhausted, 4, 1));
1071
1072                 count += sizeof(*s);
1073         }
1074         free(stat);
1075 }
1076
1077 #define MAXSAVE 16
1078
1079 static void
1080 dozmem(u_int interval, int reps)
1081 {
1082         struct zlist    zlist;
1083         struct vm_zone  *kz;
1084         struct vm_zone  zone;
1085         struct vm_zone  save[MAXSAVE];
1086         long zfreecnt_prev;
1087         long znalloc_prev;
1088         long zfreecnt_next;
1089         long znalloc_next;
1090         char name[64];
1091         size_t namesz;
1092         int first = 1;
1093         int i;
1094         int n;
1095
1096         bzero(save, sizeof(save));
1097
1098 again:
1099         kread(X_ZLIST, &zlist, sizeof(zlist));
1100         kz = LIST_FIRST(&zlist);
1101         i = 0;
1102
1103         while (kz) {
1104                 if (kvm_read(kd, (intptr_t)kz, &zone, sizeof(zone)) !=
1105                     (ssize_t)sizeof(zone)) {
1106                         perror("kvm_read");
1107                         break;
1108                 }
1109                 zfreecnt_prev = save[i].zfreecnt;
1110                 znalloc_prev = save[i].znalloc;
1111                 for (n = 0; n < ncpus; ++n) {
1112                         zfreecnt_prev += save[i].zpcpu[n].zfreecnt;
1113                         znalloc_prev += save[i].zpcpu[n].znalloc;
1114                 }
1115
1116                 zfreecnt_next = zone.zfreecnt;
1117                 znalloc_next = zone.znalloc;
1118                 for (n = 0; n < ncpus; ++n) {
1119                         zfreecnt_next += zone.zpcpu[n].zfreecnt;
1120                         znalloc_next += zone.zpcpu[n].znalloc;
1121                 }
1122                 save[i] = zone;
1123
1124                 namesz = sizeof(name);
1125                 if (kvm_readstr(kd, (intptr_t)zone.zname, name, &namesz) == NULL) {
1126                         perror("kvm_read");
1127                         break;
1128                 }
1129                 if (first && interval) {
1130                         /* do nothing */
1131                 } else if (zone.zmax) {
1132                         printf("%-10s %9ld / %-9ld %5ldM used"
1133                                " %6.2f%% ",
1134                                 name,
1135                                 (long)(zone.ztotal - zfreecnt_next),
1136                                 (long)zone.zmax,
1137                                 (long)zone.zpagecount * 4096 / (1024 * 1024),
1138                                 (double)(zone.ztotal - zfreecnt_next) *
1139                                         100.0 / (double)zone.zmax);
1140                 } else {
1141                         printf("%-10s %9ld             %5ldM used"
1142                                "         ",
1143                                 name,
1144                                 (long)(zone.ztotal - zfreecnt_next),
1145                                 (long)(zone.ztotal - zfreecnt_next) *
1146                                         zone.zsize / (1024 * 1024));
1147                 }
1148                 if (first == 0) {
1149                         printf("use=%ld\n", znalloc_next - znalloc_prev);
1150                 } else if (interval == 0)
1151                         printf("\n");
1152
1153                 kz = LIST_NEXT(&zone, zlink);
1154                 ++i;
1155         }
1156         if (reps) {
1157                 first = 0;
1158                 fflush(stdout);
1159                 usleep(interval * 1000);
1160                 --reps;
1161                 printf("\n");
1162                 goto again;
1163         }
1164 }
1165
1166 /*
1167  * kread reads something from the kernel, given its nlist index.
1168  */
1169 static void
1170 kread(int nlx, void *addr, size_t size)
1171 {
1172         const char *sym;
1173
1174         if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
1175                 sym = namelist[nlx].n_name;
1176                 if (*sym == '_')
1177                         ++sym;
1178                 errx(1, "symbol %s not defined", sym);
1179         }
1180         if (kvm_read(kd, namelist[nlx].n_value, addr, size) != (ssize_t)size) {
1181                 sym = namelist[nlx].n_name;
1182                 if (*sym == '_')
1183                         ++sym;
1184                 errx(1, "%s: %s", sym, kvm_geterr(kd));
1185         }
1186 }
1187
1188 static void
1189 usage(void)
1190 {
1191         fprintf(stderr, "%s%s",
1192                 "usage: vmstat [-imsuvz] [-c count] [-M core] "
1193                 "[-N system] [-w wait]\n",
1194                 "              [-n devs] [disks]\n");
1195         exit(1);
1196 }