vmstat - Adjust headers
[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/malloc.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 LIST_HEAD(zlist, vm_zone);
94
95 struct statinfo cur, last;
96 int num_devices, maxshowdevs;
97 long generation;
98 struct device_selection *dev_select;
99 int num_selected;
100 struct devstat_match *matches;
101 int num_matches = 0;
102 int num_devices_specified, num_selections;
103 long select_generation;
104 char **specified_devices;
105 devstat_select_mode select_mode;
106
107 struct  vmmeter vmm, ovmm;
108 struct  vmstats vms, ovms;
109
110 int     winlines = 20;
111 int     nflag = 0;
112 int     verbose = 0;
113
114 kvm_t *kd;
115
116 struct kinfo_cputime cp_time, old_cp_time, diff_cp_time;
117
118 #define FORKSTAT        0x01
119 #define INTRSTAT        0x02
120 #define MEMSTAT         0x04
121 #define SUMSTAT         0x08
122 #define TIMESTAT        0x10
123 #define VMSTAT          0x20
124 #define ZMEMSTAT        0x40
125
126 static void cpustats(void);
127 static void dointr(void);
128 static void domem(void);
129 static void dosum(void);
130 static void dozmem(u_int interval, int reps);
131 static void dovmstat(u_int, int);
132 static void kread(int, void *, size_t);
133 static void usage(void);
134 static char **getdrivedata(char **);
135 static long getuptime(void);
136 static void needhdr(int);
137 static long pct(long, long);
138
139 #ifdef notyet
140 static void dotimes(void); /* Not implemented */
141 static void doforkst(void);
142 #endif
143 static void printhdr(void);
144 static const char *formatnum(intmax_t value, int width);
145 static void devstats(int dooutput);
146
147 int
148 main(int argc, char **argv)
149 {
150         int c, todo;
151         u_int interval;         /* milliseconds */
152         int reps;
153         char *memf, *nlistf;
154         char errbuf[_POSIX2_LINE_MAX];
155
156         memf = nlistf = NULL;
157         interval = reps = todo = 0;
158         maxshowdevs = 2;
159         while ((c = getopt(argc, argv, "c:fiM:mN:n:p:stvw:z")) != -1) {
160                 switch (c) {
161                 case 'c':
162                         reps = atoi(optarg);
163                         break;
164                 case 'f':
165 #ifdef notyet
166                         todo |= FORKSTAT;
167 #else
168                         errx(EX_USAGE, "sorry, -f is not (re)implemented yet");
169 #endif
170                         break;
171                 case 'i':
172                         todo |= INTRSTAT;
173                         break;
174                 case 'M':
175                         memf = optarg;
176                         break;
177                 case 'm':
178                         todo |= MEMSTAT;
179                         break;
180                 case 'N':
181                         nlistf = optarg;
182                         break;
183                 case 'n':
184                         nflag = 1;
185                         maxshowdevs = atoi(optarg);
186                         if (maxshowdevs < 0)
187                                 errx(1, "number of devices %d is < 0",
188                                      maxshowdevs);
189                         break;
190                 case 'p':
191                         if (buildmatch(optarg, &matches, &num_matches) != 0)
192                                 errx(1, "%s", devstat_errbuf);
193                         break;
194                 case 's':
195                         todo |= SUMSTAT;
196                         break;
197                 case 't':
198 #ifdef notyet
199                         todo |= TIMESTAT;
200 #else
201                         errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
202 #endif
203                         break;
204                 case 'v':
205                         ++verbose;
206                         break;
207                 case 'w':
208                         interval = (u_int)(strtod(optarg, NULL) * 1000.0);
209                         break;
210                 case 'z':
211                         todo |= ZMEMSTAT;
212                         break;
213                 default:
214                         usage();
215                 }
216         }
217         argc -= optind;
218         argv += optind;
219
220         if (todo == 0)
221                 todo = VMSTAT;
222
223         /*
224          * Discard setgid privileges if not the running kernel so that bad
225          * guys can't print interesting stuff from kernel memory.
226          */
227         if (nlistf != NULL || memf != NULL)
228                 setgid(getgid());
229
230         kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
231         if (kd == NULL)
232                 errx(1, "kvm_openfiles: %s", errbuf);
233
234         if ((c = kvm_nlist(kd, namelist)) != 0) {
235                 if (c > 0) {
236                         warnx("undefined symbols:");
237                         for (c = 0; c < (int)__arysize(namelist); c++)
238                                 if (namelist[c].n_type == 0)
239                                         fprintf(stderr, " %s",
240                                             namelist[c].n_name);
241                         fputc('\n', stderr);
242                 } else
243                         warnx("kvm_nlist: %s", kvm_geterr(kd));
244                 exit(1);
245         }
246
247         if (todo & VMSTAT) {
248                 struct winsize winsize;
249
250                 /*
251                  * Make sure that the userland devstat version matches the
252                  * kernel devstat version.  If not, exit and print a
253                  * message informing the user of his mistake.
254                  */
255                 if (checkversion() < 0)
256                         errx(1, "%s", devstat_errbuf);
257
258
259                 argv = getdrivedata(argv);
260                 winsize.ws_row = 0;
261                 ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
262                 if (winsize.ws_row > 0)
263                         winlines = winsize.ws_row;
264
265         }
266
267 #define BACKWARD_COMPATIBILITY
268 #ifdef  BACKWARD_COMPATIBILITY
269         if (*argv) {
270                 interval = (u_int)(strtod(*argv, NULL) * 1000.0);
271                 if (*++argv)
272                         reps = atoi(*argv);
273         }
274 #endif
275
276         if (interval) {
277                 if (!reps)
278                         reps = -1;
279         } else if (reps) {
280                 interval = 1000;
281         }
282
283 #ifdef notyet
284         if (todo & FORKSTAT)
285                 doforkst();
286 #endif
287         if (todo & MEMSTAT)
288                 domem();
289         if (todo & ZMEMSTAT)
290                 dozmem(interval, reps);
291         if (todo & SUMSTAT)
292                 dosum();
293 #ifdef notyet
294         if (todo & TIMESTAT)
295                 dotimes();
296 #endif
297         if (todo & INTRSTAT)
298                 dointr();
299         if (todo & VMSTAT)
300                 dovmstat(interval, reps);
301         exit(0);
302 }
303
304 static char **
305 getdrivedata(char **argv)
306 {
307         if ((num_devices = getnumdevs()) < 0)
308                 errx(1, "%s", devstat_errbuf);
309
310         cur.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
311         last.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
312         bzero(cur.dinfo, sizeof(struct devinfo));
313         bzero(last.dinfo, sizeof(struct devinfo));
314
315         if (getdevs(&cur) == -1)
316                 errx(1, "%s", devstat_errbuf);
317
318         num_devices = cur.dinfo->numdevs;
319         generation = cur.dinfo->generation;
320
321         specified_devices = (char **)malloc(sizeof(char *));
322         for (num_devices_specified = 0; *argv; ++argv) {
323                 if (isdigit(**argv))
324                         break;
325                 num_devices_specified++;
326                 specified_devices = (char **)realloc(specified_devices,
327                                                      sizeof(char *) *
328                                                      num_devices_specified);
329                 specified_devices[num_devices_specified - 1] = *argv;
330         }
331         dev_select = NULL;
332
333         if (nflag == 0 && maxshowdevs < num_devices_specified)
334                         maxshowdevs = num_devices_specified;
335
336         /*
337          * People are generally only interested in disk statistics when
338          * they're running vmstat.  So, that's what we're going to give
339          * them if they don't specify anything by default.  We'll also give
340          * them any other random devices in the system so that we get to
341          * maxshowdevs devices, if that many devices exist.  If the user
342          * specifies devices on the command line, either through a pattern
343          * match or by naming them explicitly, we will give the user only
344          * those devices.
345          */
346         if ((num_devices_specified == 0) && (num_matches == 0)) {
347                 if (buildmatch("da", &matches, &num_matches) != 0)
348                         errx(1, "%s", devstat_errbuf);
349
350                 select_mode = DS_SELECT_ADD;
351         } else
352                 select_mode = DS_SELECT_ONLY;
353
354         /*
355          * At this point, selectdevs will almost surely indicate that the
356          * device list has changed, so we don't look for return values of 0
357          * or 1.  If we get back -1, though, there is an error.
358          */
359         if (selectdevs(&dev_select, &num_selected, &num_selections,
360                        &select_generation, generation, cur.dinfo->devices,
361                        num_devices, matches, num_matches, specified_devices,
362                        num_devices_specified, select_mode,
363                        maxshowdevs, 0) == -1)
364                 errx(1, "%s", devstat_errbuf);
365
366         return(argv);
367 }
368
369 static long
370 getuptime(void)
371 {
372         static time_t now, boottime;
373         time_t uptime;
374
375         if (boottime == 0)
376                 kread(X_BOOTTIME, &boottime, sizeof(boottime));
377         time(&now);
378         uptime = now - boottime;
379         if (uptime <= 0 || uptime > 60*60*24*365*10)
380                 errx(1, "time makes no sense; namelist must be wrong");
381         return(uptime);
382 }
383
384 int     hdrcnt;
385
386 static void
387 dovmstat(u_int interval, int reps)
388 {
389         struct vmtotal total;
390         struct devinfo *tmp_dinfo;
391         size_t vmm_size = sizeof(vmm);
392         size_t vms_size = sizeof(vms);
393         size_t vmt_size = sizeof(total);
394         int initial = 1;
395         int dooutput = 1;
396
397         signal(SIGCONT, needhdr);
398         if (reps != 0)
399                 dooutput = 0;
400
401         for (hdrcnt = 1;;) {
402                 if (!--hdrcnt)
403                         printhdr();
404                 if (kinfo_get_sched_cputime(&cp_time))
405                         err(1, "kinfo_get_sched_cputime");
406
407                 tmp_dinfo = last.dinfo;
408                 last.dinfo = cur.dinfo;
409                 cur.dinfo = tmp_dinfo;
410                 last.busy_time = cur.busy_time;
411
412                 /*
413                  * Here what we want to do is refresh our device stats.
414                  * getdevs() returns 1 when the device list has changed.
415                  * If the device list has changed, we want to go through
416                  * the selection process again, in case a device that we
417                  * were previously displaying has gone away.
418                  */
419                 switch (getdevs(&cur)) {
420                 case -1:
421                         errx(1, "%s", devstat_errbuf);
422                         break;
423                 case 1: {
424                         int retval;
425
426                         num_devices = cur.dinfo->numdevs;
427                         generation = cur.dinfo->generation;
428
429                         retval = selectdevs(&dev_select, &num_selected,
430                                             &num_selections, &select_generation,
431                                             generation, cur.dinfo->devices,
432                                             num_devices, matches, num_matches,
433                                             specified_devices,
434                                             num_devices_specified, select_mode,
435                                             maxshowdevs, 0);
436                         switch (retval) {
437                         case -1:
438                                 errx(1, "%s", devstat_errbuf);
439                                 break;
440                         case 1:
441                                 printhdr();
442                                 break;
443                         default:
444                                 break;
445                         }
446                 }
447                 default:
448                         break;
449                 }
450
451                 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
452                         perror("sysctlbyname: vm.vmstats");
453                         exit(1);
454                 }
455                 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
456                         perror("sysctlbyname: vm.vmmeter");
457                         exit(1);
458                 } 
459                 if (sysctlbyname("vm.vmtotal", &total, &vmt_size, NULL, 0)) {
460                         perror("sysctlbyname: vm.vmtotal");
461                         exit(1);
462                 } 
463                 if (dooutput) {
464                         printf("%3ld %2ld %2ld",
465                                total.t_rq - 1,
466                                total.t_dw + total.t_pw,
467                                total.t_sw);
468                 }
469
470 #define rate(x)         \
471         (intmax_t)(initial ? (x) : ((intmax_t)(x) * 1000 + interval / 2) \
472                                    / interval)
473
474                 if (dooutput) {
475                         printf(" %s ",
476                                formatnum((int64_t)total.t_free *
477                                          vms.v_page_size, 4));
478                         printf("%s ",
479                                formatnum(rate(vmm.v_vm_faults -
480                                               ovmm.v_vm_faults), 5));
481                         printf("%s ",
482                                formatnum(rate(vmm.v_reactivated -
483                                               ovmm.v_reactivated), 4));
484                         printf("%s ",
485                                formatnum(rate(vmm.v_swapin + vmm.v_vnodein -
486                                       (ovmm.v_swapin + ovmm.v_vnodein)), 4));
487                         printf("%s ",
488                                formatnum(rate(vmm.v_swapout + vmm.v_vnodeout -
489                                     (ovmm.v_swapout + ovmm.v_vnodeout)), 4));
490                         printf("%s ",
491                                formatnum(rate(vmm.v_tfree -
492                                               ovmm.v_tfree), 4));
493                 }
494                 devstats(dooutput);
495                 if (dooutput) {
496                         printf("%s ",
497                                formatnum(rate(vmm.v_intr -
498                                               ovmm.v_intr), 5));
499                         printf("%s ",
500                                formatnum(rate(vmm.v_syscall -
501                                               ovmm.v_syscall), 5));
502                         printf("%s ",
503                                formatnum(rate(vmm.v_swtch -
504                                               ovmm.v_swtch), 5));
505                         cpustats();
506                         printf("\n");
507                         fflush(stdout);
508                 }
509                 if (reps >= 0 && --reps <= 0)
510                         break;
511                 ovmm = vmm;
512                 usleep(interval * 1000);
513                 initial = 0;
514                 dooutput = 1;
515         }
516 }
517
518 static const char *
519 formatnum(intmax_t value, int width)
520 {
521         static char buf[64];
522         const char *fmt;
523         double d;
524
525         d = (double)value;
526         fmt = "n/a";
527
528         switch(width) {
529         case 4:
530                 if (value < 1024) {
531                         fmt = "%4.0f";
532                 } else if (value < 10*1024) {
533                         fmt = "%3.1fK";
534                         d = d / 1024;
535                 } else if (value < 1000*1024) {
536                         fmt = "%3.0fK";
537                         d = d / 1024;
538                 } else if (value < 10*1024*1024) {
539                         fmt = "%3.1fM";
540                         d = d / (1024 * 1024);
541                 } else if (value < 1000*1024*1024) {
542                         fmt = "%3.0fM";
543                         d = d / (1024 * 1024);
544                 } else {
545                         fmt = "%3.1fG";
546                         d = d / (1024.0 * 1024.0 * 1024.0);
547                 }
548                 break;
549         case 5:
550                 if (value < 1024) {
551                         fmt = "%5.0f";
552                 } else if (value < 10*1024) {
553                         fmt = "%4.2fK";
554                         d = d / 1024;
555                 } else if (value < 1000*1024) {
556                         fmt = "%4.0fK";
557                         d = d / 1024;
558                 } else if (value < 10*1024*1024) {
559                         fmt = "%4.2fM";
560                         d = d / (1024 * 1024);
561                 } else if (value < 1000*1024*1024) {
562                         fmt = "%4.0fM";
563                         d = d / (1024 * 1024);
564                 } else {
565                         fmt = "%4.2fG";
566                         d = d / (1024.0 * 1024.0 * 1024.0);
567                 }
568                 break;
569         default:
570                 fprintf(stderr, "formatnum: unsupported width %d\n", width);
571                 exit(1);
572                 break;
573         }
574         snprintf(buf, sizeof(buf), fmt, d);
575         return buf;
576 }
577
578 static void
579 printhdr(void)
580 {
581         int i, num_shown;
582
583         num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
584         printf("--procs-- ---memory-- -------paging------ ");
585         if (num_shown > 1)
586                 printf("--disks%.*s",
587                        num_shown * 4 - 6,
588                        "---------------------------------");
589         else if (num_shown == 1)
590                 printf("disk");
591         printf(" -----faults------ ---cpu---\n");
592         printf("  r  b  w   fre   flt   re   pi   po   fr ");
593         for (i = 0; i < num_devices; i++)
594                 if ((dev_select[i].selected)
595                  && (dev_select[i].selected <= maxshowdevs))
596                         printf(" %c%c%d ", dev_select[i].device_name[0],
597                                      dev_select[i].device_name[1],
598                                      dev_select[i].unit_number);
599         printf("  int   sys   ctx us sy id\n");
600         hdrcnt = winlines - 2;
601 }
602
603 /*
604  * Force a header to be prepended to the next output.
605  */
606 static void
607 needhdr(__unused int signo)
608 {
609
610         hdrcnt = 1;
611 }
612
613 static long
614 pct(long top, long bot)
615 {
616         long ans;
617
618         if (bot == 0)
619                 return(0);
620         ans = (quad_t)top * 100 / bot;
621         return (ans);
622 }
623
624 #define PCT(top, bot) pct((long)(top), (long)(bot))
625
626 static void
627 dosum(void)
628 {
629         struct nchstats *nch_tmp, nchstats;
630         size_t vms_size = sizeof(vms);
631         size_t vmm_size = sizeof(vmm);
632         int cpucnt;
633         u_long nchtotal;
634         u_long nchpathtotal;
635         size_t nch_size = sizeof(struct nchstats) * SMP_MAXCPU;
636
637         if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
638                 perror("sysctlbyname: vm.vmstats");
639                 exit(1);
640         }
641         if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
642                 perror("sysctlbyname: vm.vmstats");
643                 exit(1);
644         }
645         printf("%9u cpu context switches\n", vmm.v_swtch);
646         printf("%9u device interrupts\n", vmm.v_intr);
647         printf("%9u software interrupts\n", vmm.v_soft);
648         printf("%9u traps\n", vmm.v_trap);
649         printf("%9u system calls\n", vmm.v_syscall);
650         printf("%9u kernel threads created\n", vmm.v_kthreads);
651         printf("%9u  fork() calls\n", vmm.v_forks);
652         printf("%9u vfork() calls\n", vmm.v_vforks);
653         printf("%9u rfork() calls\n", vmm.v_rforks);
654         printf("%9u exec() calls\n", vmm.v_exec);
655         printf("%9u swap pager pageins\n", vmm.v_swapin);
656         printf("%9u swap pager pages paged in\n", vmm.v_swappgsin);
657         printf("%9u swap pager pageouts\n", vmm.v_swapout);
658         printf("%9u swap pager pages paged out\n", vmm.v_swappgsout);
659         printf("%9u vnode pager pageins\n", vmm.v_vnodein);
660         printf("%9u vnode pager pages paged in\n", vmm.v_vnodepgsin);
661         printf("%9u vnode pager pageouts\n", vmm.v_vnodeout);
662         printf("%9u vnode pager pages paged out\n", vmm.v_vnodepgsout);
663         printf("%9u page daemon wakeups\n", vmm.v_pdwakeups);
664         printf("%9u pages examined by the page daemon\n", vmm.v_pdpages);
665         printf("%9u pages reactivated\n", vmm.v_reactivated);
666         printf("%9u copy-on-write faults\n", vmm.v_cow_faults);
667         printf("%9u copy-on-write optimized faults\n", vmm.v_cow_optim);
668         printf("%9u zero fill pages zeroed\n", vmm.v_zfod);
669         printf("%9u zero fill pages prezeroed\n", vmm.v_ozfod);
670         printf("%9u intransit blocking page faults\n", vmm.v_intrans);
671         printf("%9u total VM faults taken\n", vmm.v_vm_faults);
672         printf("%9u pages affected by kernel thread creation\n", vmm.v_kthreadpages);
673         printf("%9u pages affected by  fork()\n", vmm.v_forkpages);
674         printf("%9u pages affected by vfork()\n", vmm.v_vforkpages);
675         printf("%9u pages affected by rfork()\n", vmm.v_rforkpages);
676         printf("%9u pages freed\n", vmm.v_tfree);
677         printf("%9u pages freed by daemon\n", vmm.v_dfree);
678         printf("%9u pages freed by exiting processes\n", vmm.v_pfree);
679         printf("%9u pages active\n", vms.v_active_count);
680         printf("%9u pages inactive\n", vms.v_inactive_count);
681         printf("%9u pages in VM cache\n", vms.v_cache_count);
682         printf("%9u pages wired down\n", vms.v_wire_count);
683         printf("%9u pages free\n", vms.v_free_count);
684         printf("%9u bytes per page\n", vms.v_page_size);
685         printf("%9u global smp invltlbs\n", vmm.v_smpinvltlb);
686         
687         if ((nch_tmp = malloc(nch_size)) == NULL) {
688                 perror("malloc");
689                 exit(1);
690         } else {
691                 if (sysctlbyname("vfs.cache.nchstats", nch_tmp, &nch_size, NULL, 0)) {
692                         perror("sysctlbyname vfs.cache.nchstats");
693                         free(nch_tmp);
694                         exit(1);
695                 } else {
696                         if ((nch_tmp = realloc(nch_tmp, nch_size)) == NULL) {
697                                 perror("realloc");
698                                 exit(1);
699                         }
700                 }
701         }
702         
703         cpucnt = nch_size / sizeof(struct nchstats);
704         kvm_nch_cpuagg(nch_tmp, &nchstats, cpucnt);
705
706         nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
707             nchstats.ncs_badhits + nchstats.ncs_falsehits +
708             nchstats.ncs_miss;
709         nchpathtotal = nchstats.ncs_longhits + nchstats.ncs_longmiss;
710         printf("%9ld total path lookups\n", nchpathtotal);
711         printf("%9ld total component lookups\n", nchtotal);
712         printf(
713             "%9s cache hits (%ld%% pos + %ld%% neg)\n",
714             "", PCT(nchstats.ncs_goodhits, nchtotal),
715             PCT(nchstats.ncs_neghits, nchtotal));
716         printf("%9s deletions %ld%%, falsehits %ld%%\n", "",
717             PCT(nchstats.ncs_badhits, nchtotal),
718             PCT(nchstats.ncs_falsehits, nchtotal));
719         free(nch_tmp);
720 }
721
722 #ifdef notyet
723 void
724 doforkst(void)
725 {
726         struct forkstat fks;
727
728         kread(X_FORKSTAT, &fks, sizeof(struct forkstat));
729         printf("%d forks, %d pages, average %.2f\n",
730             fks.cntfork, fks.sizfork, (double)fks.sizfork / fks.cntfork);
731         printf("%d vforks, %d pages, average %.2f\n",
732             fks.cntvfork, fks.sizvfork, (double)fks.sizvfork / fks.cntvfork);
733 }
734 #endif
735
736 static void
737 devstats(int dooutput)
738 {
739         int dn;
740         long double transfers_per_second;
741         long double busy_seconds;
742
743         diff_cp_time.cp_user = cp_time.cp_user - old_cp_time.cp_user;
744         diff_cp_time.cp_nice = cp_time.cp_nice - old_cp_time.cp_nice;
745         diff_cp_time.cp_sys = cp_time.cp_sys - old_cp_time.cp_sys;
746         diff_cp_time.cp_intr = cp_time.cp_intr - old_cp_time.cp_intr;
747         diff_cp_time.cp_idle = cp_time.cp_idle - old_cp_time.cp_idle;
748         old_cp_time = cp_time;
749
750         busy_seconds = compute_etime(cur.busy_time, last.busy_time);
751
752         for (dn = 0; dn < num_devices; dn++) {
753                 int di;
754
755                 if ((dev_select[dn].selected == 0)
756                  || (dev_select[dn].selected > maxshowdevs))
757                         continue;
758
759                 di = dev_select[dn].position;
760
761                 if (compute_stats(&cur.dinfo->devices[di],
762                                   &last.dinfo->devices[di], busy_seconds,
763                                   NULL, NULL, NULL,
764                                   NULL, &transfers_per_second, NULL,
765                                   NULL, NULL) != 0)
766                         errx(1, "%s", devstat_errbuf);
767
768                 if (dooutput)
769                         printf("%s ", formatnum(transfers_per_second, 4));
770         }
771 }
772
773 static void
774 cpustats(void)
775 {
776         uint64_t total;
777         double totusage;
778
779         total = diff_cp_time.cp_user + diff_cp_time.cp_nice +
780             diff_cp_time.cp_sys + diff_cp_time.cp_intr + diff_cp_time.cp_idle;
781
782         if (total)
783                 totusage = 100.0 / total;
784         else
785                 totusage = 0;
786         printf("%2.0f ",
787                (diff_cp_time.cp_user + diff_cp_time.cp_nice) * totusage);
788         printf("%2.0f ",
789                (diff_cp_time.cp_sys + diff_cp_time.cp_intr) * totusage);
790         printf("%2.0f",
791                diff_cp_time.cp_idle * totusage);
792 }
793
794 static void
795 dointr(void)
796 {
797         u_long *intrcnt, uptime;
798         u_int64_t inttotal;
799         size_t nintr, inamlen, i, size;
800         int nwidth;
801         char *intrstr;
802         char **intrname;
803
804         uptime = getuptime();
805         if (sysctlbyname("hw.intrnames", NULL, &inamlen, NULL, 0) != 0)
806                 errx(1, "sysctlbyname");
807         intrstr = malloc(inamlen);
808         if (intrstr == NULL)
809                 err(1, "malloc");
810         sysctlbyname("hw.intrnames", intrstr, &inamlen, NULL, 0);
811         for (nintr = 0, i = 0; i < inamlen; ++i) {
812                 if (intrstr[i] == 0)
813                         nintr++;
814         }
815         intrname = malloc(nintr * sizeof(char *));
816         for (i = 0; i < nintr; ++i) {
817                 intrname[i] = intrstr;
818                 intrstr += strlen(intrstr) + 1;
819         }
820
821         size = nintr * sizeof(*intrcnt);
822         intrcnt = calloc(nintr, sizeof(*intrcnt));
823         if (intrcnt == NULL)
824                 err(1, "malloc");
825         sysctlbyname("hw.intrcnt", intrcnt, &size, NULL, 0);
826
827         nwidth = 21;
828         for (i = 0; i < nintr; ++i) {
829                 if (nwidth < (int)strlen(intrname[i]))
830                         nwidth = (int)strlen(intrname[i]);
831         }
832         if (verbose) nwidth += 12;
833
834         printf("%-*.*s %11s %10s\n",
835                 nwidth, nwidth, "interrupt", "total", "rate");
836         inttotal = 0;
837         for (i = 0; i < nintr; ++i) {
838                 int named;
839                 char *infop, irqinfo[72];
840
841                 if ((named = strncmp(intrname[i], "irq", 3)) != 0 ||
842                     intrcnt[i] > 0) {
843                         infop = intrname[i];
844                         if (verbose) {
845                                 ssize_t irq, cpu;
846
847                                 irq = i % MAX_INTS;
848                                 cpu = i / MAX_INTS;
849                                 if (named) {
850                                         snprintf(irqinfo, sizeof(irqinfo),
851                                                  "irq%-3zd %3zd: %s",
852                                                  irq, cpu, intrname[i]);
853                                 } else {
854                                         snprintf(irqinfo, sizeof(irqinfo),
855                                                  "irq%-3zd %3zd: ", irq, cpu);
856                                 }
857                                 infop = irqinfo;
858                         }
859                         printf("%-*.*s %11lu %10lu\n", 
860                                 nwidth, nwidth, infop,
861                                 intrcnt[i], intrcnt[i] / uptime);
862                 }
863                 inttotal += intrcnt[i];
864         }
865         printf("%-*.*s %11llu %10llu\n", 
866                 nwidth, nwidth, "Total",
867                 (long long)inttotal, (long long)(inttotal / uptime));
868 }
869
870 #define MAX_KMSTATS     1024
871
872 enum ksuse { KSINUSE, KSMEMUSE };
873
874 static long
875 cpuagg(struct malloc_type *ks, enum ksuse use)
876 {
877     int i;
878     long ttl;
879
880     ttl = 0;
881
882     switch(use) {
883     case KSINUSE:
884         for (i = 0; i < SMP_MAXCPU; ++i)
885             ttl += ks->ks_use[i].inuse;
886         break;
887     case KSMEMUSE:
888         for (i = 0; i < SMP_MAXCPU; ++i)
889             ttl += ks->ks_use[i].memuse;
890         break;
891     }
892     return(ttl);
893 }
894
895 static void
896 domem(void)
897 {
898         struct malloc_type *ks;
899         int i, j;
900         int first, nkms;
901         long totuse = 0, totfree = 0, totreq = 0;
902         struct malloc_type kmemstats[MAX_KMSTATS], *kmsp;
903         char buf[1024];
904
905         kread(X_KMEMSTATISTICS, &kmsp, sizeof(kmsp));
906         for (nkms = 0; nkms < MAX_KMSTATS && kmsp != NULL; nkms++) {
907                 if (sizeof(kmemstats[0]) != kvm_read(kd, (u_long)kmsp,
908                     &kmemstats[nkms], sizeof(kmemstats[0])))
909                         err(1, "kvm_read(%p)", (void *)kmsp);
910                 if (sizeof(buf) !=  kvm_read(kd, 
911                     (u_long)kmemstats[nkms].ks_shortdesc, buf, sizeof(buf)))
912                         err(1, "kvm_read(%p)", 
913                             kmemstats[nkms].ks_shortdesc);
914                 buf[sizeof(buf) - 1] = '\0';
915                 kmemstats[nkms].ks_shortdesc = strdup(buf);
916                 kmsp = kmemstats[nkms].ks_next;
917         }
918         if (kmsp != NULL)
919                 warnx("truncated to the first %d memory types", nkms);
920
921         printf(
922             "\nMemory statistics by type                          Type  Kern\n");
923         printf(
924 "              Type   InUse  MemUse HighUse       Limit  Requests  Limit Limit\n");
925         for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
926                 if (ks->ks_calls == 0)
927                         continue;
928                 printf("%19s%7ld%7ldK%7ldK%11zuK%10jd%5u%6u",
929                     ks->ks_shortdesc,
930                     cpuagg(ks, KSINUSE), (cpuagg(ks, KSMEMUSE) + 1023) / 1024,
931                     (ks->ks_maxused + 1023) / 1024,
932                     (ks->ks_limit + 1023) / 1024, (intmax_t)ks->ks_calls,
933                     ks->ks_limblocks, ks->ks_mapblocks);
934                 first = 1;
935                 for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
936                         if ((ks->ks_size & j) == 0)
937                                 continue;
938                         if (first)
939                                 printf("  ");
940                         else
941                                 printf(",");
942                         if(j<1024)
943                                 printf("%d",j);
944                         else
945                                 printf("%dK",j>>10);
946                         first = 0;
947                 }
948                 printf("\n");
949                 totuse += cpuagg(ks, KSMEMUSE);
950                 totreq += ks->ks_calls;
951         }
952         printf("\nMemory Totals:  In Use    Free    Requests\n");
953         printf("              %7ldK %6ldK    %8ld\n",
954              (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
955 }
956
957 #define MAXSAVE 16
958
959 static void
960 dozmem(u_int interval, int reps)
961 {
962         struct zlist    zlist;
963         struct vm_zone  *kz;
964         struct vm_zone  zone;
965         struct vm_zone  copy;
966         struct vm_zone  save[MAXSAVE];
967         char name[64];
968         size_t namesz;
969         int i;
970         int first = 1;
971
972         bzero(save, sizeof(save));
973
974 again:
975         kread(X_ZLIST, &zlist, sizeof(zlist));
976         kz = LIST_FIRST(&zlist);
977         i = 0;
978
979         while (kz) {
980                 if (kvm_read(kd, (intptr_t)kz, &zone, sizeof(zone)) !=
981                     (ssize_t)sizeof(zone)) {
982                         perror("kvm_read");
983                         break;
984                 }
985                 copy = zone;
986                 zone.znalloc -= save[i].znalloc;
987                 save[i] = copy;
988                 namesz = sizeof(name);
989                 if (kvm_readstr(kd, (intptr_t)zone.zname, name, &namesz) == NULL) {
990                         perror("kvm_read");
991                         break;
992                 }
993                 if (first && interval) {
994                         /* do nothing */
995                 } else if (zone.zmax) {
996                         printf("%-10s %9ld/%9ld %5ldM used"
997                                " use=%-9lu %6.2f%%\n",
998                                 name,
999                                 (long)(zone.ztotal - zone.zfreecnt),
1000                                 (long)zone.zmax,
1001                                 (long)(zone.ztotal - zone.zfreecnt) *
1002                                         zone.zsize / (1024 * 1024),
1003                                 (unsigned long)zone.znalloc,
1004                                 (double)(zone.ztotal - zone.zfreecnt) *
1005                                         100.0 / (double)zone.zmax);
1006                 } else {
1007                         printf("%-10s %9ld           %5ldM used"
1008                                " use=%-9lu\n",
1009                                 name,
1010                                 (long)(zone.ztotal - zone.zfreecnt),
1011                                 (long)(zone.ztotal - zone.zfreecnt) *
1012                                         zone.zsize / (1024 * 1024),
1013                                 (unsigned long)zone.znalloc);
1014                 }
1015                 kz = LIST_NEXT(&zone, zlink);
1016                 ++i;
1017         }
1018         if (reps) {
1019                 first = 0;
1020                 fflush(stdout);
1021                 usleep(interval * 1000);
1022                 --reps;
1023                 printf("\n");
1024                 goto again;
1025         }
1026 }
1027
1028 /*
1029  * kread reads something from the kernel, given its nlist index.
1030  */
1031 static void
1032 kread(int nlx, void *addr, size_t size)
1033 {
1034         const char *sym;
1035
1036         if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
1037                 sym = namelist[nlx].n_name;
1038                 if (*sym == '_')
1039                         ++sym;
1040                 errx(1, "symbol %s not defined", sym);
1041         }
1042         if (kvm_read(kd, namelist[nlx].n_value, addr, size) != (ssize_t)size) {
1043                 sym = namelist[nlx].n_name;
1044                 if (*sym == '_')
1045                         ++sym;
1046                 errx(1, "%s: %s", sym, kvm_geterr(kd));
1047         }
1048 }
1049
1050 static void
1051 usage(void)
1052 {
1053         fprintf(stderr, "%s%s",
1054                 "usage: vmstat [-imsvz] [-c count] [-M core] [-N system] [-w wait]\n",
1055                 "              [-n devs] [disks]\n");
1056         exit(1);
1057 }