Change EXIT STATUS to DIAGNOSTICS. We have standardised on the latter.
[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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1980, 1986, 1991, 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)vmstat.c 8.1 (Berkeley) 6/6/93
35  * $FreeBSD: src/usr.bin/vmstat/vmstat.c,v 1.38.2.4 2001/07/31 19:52:41 tmm Exp $
36  * $DragonFly: src/usr.bin/vmstat/vmstat.c,v 1.16 2005/02/14 13:18:39 joerg Exp $
37  */
38
39 #define _KERNEL_STRUCTURES
40
41 #include <sys/param.h>
42 #include <sys/time.h>
43 #include <sys/user.h>
44 #include <sys/uio.h>
45 #include <sys/namei.h>
46 #include <sys/malloc.h>
47 #include <sys/signal.h>
48 #include <sys/fcntl.h>
49 #include <sys/ioctl.h>
50 #include <sys/sysctl.h>
51 #include <sys/vmmeter.h>
52
53 #include <vm/vm_param.h>
54
55 #include <ctype.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <kinfo.h>
59 #include <kvm.h>
60 #include <limits.h>
61 #include <nlist.h>
62 #include <paths.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <sysexits.h>
67 #include <time.h>
68 #include <unistd.h>
69 #include <devstat.h>
70
71 static struct nlist namelist[] = {
72 #define X_BOOTTIME      0
73         { "_boottime" },
74 #define X_NCHSTATS      1
75         { "_nchstats" },
76 #define X_INTRNAMES     2
77         { "_intrnames" },
78 #define X_EINTRNAMES    3
79         { "_eintrnames" },
80 #define X_INTRCNT       4
81         { "_intrcnt" },
82 #define X_EINTRCNT      5
83         { "_eintrcnt" },
84 #define X_KMEMSTATISTICS        6
85         { "_kmemstatistics" },
86 #define X_ZLIST         7
87         { "_zlist" },
88 #ifdef notyet
89 #define X_DEFICIT       8
90         { "_deficit" },
91 #define X_FORKSTAT      9
92         { "_forkstat" },
93 #define X_REC           10
94         { "_rectime" },
95 #define X_PGIN          11
96         { "_pgintime" },
97 #define X_XSTATS        12
98         { "_xstats" },
99 #define X_END           13
100 #else
101 #define X_END           8
102 #endif
103         { "" },
104 };
105
106 struct statinfo cur, last;
107 int num_devices, maxshowdevs;
108 long generation;
109 struct device_selection *dev_select;
110 int num_selected;
111 struct devstat_match *matches;
112 int num_matches = 0;
113 int num_devices_specified, num_selections;
114 long select_generation;
115 char **specified_devices;
116 devstat_select_mode select_mode;
117
118 struct  vmmeter vmm, ovmm;
119 struct  vmstats vms, ovms;
120
121 int     winlines = 20;
122 int     nflag = 0;
123
124 kvm_t *kd;
125
126 struct kinfo_cputime cp_time, old_cp_time, diff_cp_time;
127
128 #define FORKSTAT        0x01
129 #define INTRSTAT        0x02
130 #define MEMSTAT         0x04
131 #define SUMSTAT         0x08
132 #define TIMESTAT        0x10
133 #define VMSTAT          0x20
134 #define ZMEMSTAT        0x40
135
136 static void cpustats(void);
137 static void dointr(void);
138 static void domem(void);
139 static void dosum(void);
140 static void dozmem(void);
141 static void dovmstat(u_int interval, int reps);
142 static void kread(int nlx, void *addr, size_t size);
143 static void usage(void);
144 static char **getdrivedata(char **argv);
145 static long getuptime(void);
146 static void needhdr(int signo);
147 static long pct(long top, long bot);
148
149 #ifdef notyet
150 static void dotimes(void); /* Not implemented */
151 static void doforkst(void);
152 #endif
153 static void printhdr(void);
154 static void devstats(void);
155
156 int
157 main(int argc, char **argv)
158 {
159         int c, todo;
160         u_int interval;
161         int reps;
162         char *memf, *nlistf;
163         char errbuf[_POSIX2_LINE_MAX];
164
165         memf = nlistf = NULL;
166         interval = reps = todo = 0;
167         maxshowdevs = 2;
168         while ((c = getopt(argc, argv, "c:fiM:mN:n:p:stw:z")) != -1) {
169                 switch (c) {
170                 case 'c':
171                         reps = atoi(optarg);
172                         break;
173                 case 'f':
174 #ifdef notyet
175                         todo |= FORKSTAT;
176 #else
177                         errx(EX_USAGE, "sorry, -f is not (re)implemented yet");
178 #endif
179                         break;
180                 case 'i':
181                         todo |= INTRSTAT;
182                         break;
183                 case 'M':
184                         memf = optarg;
185                         break;
186                 case 'm':
187                         todo |= MEMSTAT;
188                         break;
189                 case 'N':
190                         nlistf = optarg;
191                         break;
192                 case 'n':
193                         nflag = 1;
194                         maxshowdevs = atoi(optarg);
195                         if (maxshowdevs < 0)
196                                 errx(1, "number of devices %d is < 0",
197                                      maxshowdevs);
198                         break;
199                 case 'p':
200                         if (buildmatch(optarg, &matches, &num_matches) != 0)
201                                 errx(1, "%s", devstat_errbuf);
202                         break;
203                 case 's':
204                         todo |= SUMSTAT;
205                         break;
206                 case 't':
207 #ifdef notyet
208                         todo |= TIMESTAT;
209 #else
210                         errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
211 #endif
212                         break;
213                 case 'w':
214                         interval = atoi(optarg);
215                         break;
216                 case 'z':
217                         todo |= ZMEMSTAT;
218                         break;
219                 case '?':
220                 default:
221                         usage();
222                 }
223         }
224         argc -= optind;
225         argv += optind;
226
227         if (todo == 0)
228                 todo = VMSTAT;
229
230         /*
231          * Discard setgid privileges if not the running kernel so that bad
232          * guys can't print interesting stuff from kernel memory.
233          */
234         if (nlistf != NULL || memf != NULL)
235                 setgid(getgid());
236
237         kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
238         if (kd == 0) 
239                 errx(1, "kvm_openfiles: %s", errbuf);
240
241         if ((c = kvm_nlist(kd, namelist)) != 0) {
242                 if (c > 0) {
243                         warnx("undefined symbols:");
244                         for (c = 0; c < (int)__arysize(namelist); c++)
245                                 if (namelist[c].n_type == 0)
246                                         fprintf(stderr, " %s",
247                                             namelist[c].n_name);
248                         fputc('\n', stderr);
249                 } else
250                         warnx("kvm_nlist: %s", kvm_geterr(kd));
251                 exit(1);
252         }
253
254         if (todo & VMSTAT) {
255                 struct winsize winsize;
256
257                 /*
258                  * Make sure that the userland devstat version matches the
259                  * kernel devstat version.  If not, exit and print a
260                  * message informing the user of his mistake.
261                  */
262                 if (checkversion() < 0)
263                         errx(1, "%s", devstat_errbuf);
264
265
266                 argv = getdrivedata(argv);
267                 winsize.ws_row = 0;
268                 ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
269                 if (winsize.ws_row > 0)
270                         winlines = winsize.ws_row;
271
272         }
273
274 #define BACKWARD_COMPATIBILITY
275 #ifdef  BACKWARD_COMPATIBILITY
276         if (*argv) {
277                 interval = atoi(*argv);
278                 if (*++argv)
279                         reps = atoi(*argv);
280         }
281 #endif
282
283         if (interval) {
284                 if (!reps)
285                         reps = -1;
286         } else if (reps)
287                 interval = 1;
288
289 #ifdef notyet
290         if (todo & FORKSTAT)
291                 doforkst();
292 #endif
293         if (todo & MEMSTAT)
294                 domem();
295         if (todo & ZMEMSTAT)
296                 dozmem();
297         if (todo & SUMSTAT)
298                 dosum();
299 #ifdef notyet
300         if (todo & TIMESTAT)
301                 dotimes();
302 #endif
303         if (todo & INTRSTAT)
304                 dointr();
305         if (todo & VMSTAT)
306                 dovmstat(interval, reps);
307         exit(0);
308 }
309
310 static char **
311 getdrivedata(char **argv)
312 {
313         if ((num_devices = getnumdevs()) < 0)
314                 errx(1, "%s", devstat_errbuf);
315
316         cur.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
317         last.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
318         bzero(cur.dinfo, sizeof(struct devinfo));
319         bzero(last.dinfo, sizeof(struct devinfo));
320
321         if (getdevs(&cur) == -1)
322                 errx(1, "%s", devstat_errbuf);
323
324         num_devices = cur.dinfo->numdevs;
325         generation = cur.dinfo->generation;
326
327         specified_devices = (char **)malloc(sizeof(char *));
328         for (num_devices_specified = 0; *argv; ++argv) {
329                 if (isdigit(**argv))
330                         break;
331                 num_devices_specified++;
332                 specified_devices = (char **)realloc(specified_devices,
333                                                      sizeof(char *) *
334                                                      num_devices_specified);
335                 specified_devices[num_devices_specified - 1] = *argv;
336         }
337         dev_select = NULL;
338
339         if (nflag == 0 && maxshowdevs < num_devices_specified)
340                         maxshowdevs = num_devices_specified;
341
342         /*
343          * People are generally only interested in disk statistics when
344          * they're running vmstat.  So, that's what we're going to give
345          * them if they don't specify anything by default.  We'll also give
346          * them any other random devices in the system so that we get to
347          * maxshowdevs devices, if that many devices exist.  If the user
348          * specifies devices on the command line, either through a pattern
349          * match or by naming them explicitly, we will give the user only
350          * those devices.
351          */
352         if ((num_devices_specified == 0) && (num_matches == 0)) {
353                 if (buildmatch("da", &matches, &num_matches) != 0)
354                         errx(1, "%s", devstat_errbuf);
355
356                 select_mode = DS_SELECT_ADD;
357         } else
358                 select_mode = DS_SELECT_ONLY;
359
360         /*
361          * At this point, selectdevs will almost surely indicate that the
362          * device list has changed, so we don't look for return values of 0
363          * or 1.  If we get back -1, though, there is an error.
364          */
365         if (selectdevs(&dev_select, &num_selected, &num_selections,
366                        &select_generation, generation, cur.dinfo->devices,
367                        num_devices, matches, num_matches, specified_devices,
368                        num_devices_specified, select_mode,
369                        maxshowdevs, 0) == -1)
370                 errx(1, "%s", devstat_errbuf);
371
372         return(argv);
373 }
374
375 static long
376 getuptime(void)
377 {
378         static time_t now, boottime;
379         time_t uptime;
380
381         if (boottime == 0)
382                 kread(X_BOOTTIME, &boottime, sizeof(boottime));
383         time(&now);
384         uptime = now - boottime;
385         if (uptime <= 0 || uptime > 60*60*24*365*10)
386                 errx(1, "time makes no sense; namelist must be wrong");
387         return(uptime);
388 }
389
390 int     hdrcnt;
391
392 static void
393 dovmstat(u_int interval, int reps)
394 {
395         struct vmtotal total;
396         time_t uptime, halfuptime;
397         struct devinfo *tmp_dinfo;
398         int vmm_size = sizeof(vmm);
399         int vms_size = sizeof(vms);
400         int vmt_size = sizeof(total);
401
402         uptime = getuptime();
403         halfuptime = uptime / 2;
404         signal(SIGCONT, needhdr);
405
406         for (hdrcnt = 1;;) {
407                 if (!--hdrcnt)
408                         printhdr();
409                 if (kinfo_get_sched_cputime(&cp_time))
410                         err(1, "kinfo_get_sched_cputime");
411
412                 tmp_dinfo = last.dinfo;
413                 last.dinfo = cur.dinfo;
414                 cur.dinfo = tmp_dinfo;
415                 last.busy_time = cur.busy_time;
416
417                 /*
418                  * Here what we want to do is refresh our device stats.
419                  * getdevs() returns 1 when the device list has changed.
420                  * If the device list has changed, we want to go through
421                  * the selection process again, in case a device that we
422                  * were previously displaying has gone away.
423                  */
424                 switch (getdevs(&cur)) {
425                 case -1:
426                         errx(1, "%s", devstat_errbuf);
427                         break;
428                 case 1: {
429                         int retval;
430
431                         num_devices = cur.dinfo->numdevs;
432                         generation = cur.dinfo->generation;
433
434                         retval = selectdevs(&dev_select, &num_selected,
435                                             &num_selections, &select_generation,
436                                             generation, cur.dinfo->devices,
437                                             num_devices, matches, num_matches,
438                                             specified_devices,
439                                             num_devices_specified, select_mode,
440                                             maxshowdevs, 0);
441                         switch (retval) {
442                         case -1:
443                                 errx(1, "%s", devstat_errbuf);
444                                 break;
445                         case 1:
446                                 printhdr();
447                                 break;
448                         default:
449                                 break;
450                         }
451                 }
452                 default:
453                         break;
454                 }
455
456                 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
457                         perror("sysctlbyname: vm.vmstats");
458                         exit(1);
459                 }
460                 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
461                         perror("sysctlbyname: vm.vmmeter");
462                         exit(1);
463                 } 
464                 if (sysctlbyname("vm.vmtotal", &total, &vmt_size, NULL, 0)) {
465                         perror("sysctlbyname: vm.vmtotal");
466                         exit(1);
467                 } 
468                 printf("%2d %1d %1d",
469                     total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
470 #define vmstat_pgtok(a) ((a) * vms.v_page_size >> 10)
471 #define rate(x) (((x) + halfuptime) / uptime)   /* round */
472                 printf(" %7ld %6ld ",
473                     (long)vmstat_pgtok(total.t_avm), (long)vmstat_pgtok(total.t_free));
474                 printf("%4lu ",
475                     (u_long)rate(vmm.v_vm_faults - ovmm.v_vm_faults));
476                 printf("%3lu ",
477                     (u_long)rate(vmm.v_reactivated - ovmm.v_reactivated));
478                 printf("%3lu ",
479                     (u_long)rate(vmm.v_swapin + vmm.v_vnodein -
480                     (ovmm.v_swapin + ovmm.v_vnodein)));
481                 printf("%3lu ",
482                     (u_long)rate(vmm.v_swapout + vmm.v_vnodeout -
483                     (ovmm.v_swapout + ovmm.v_vnodeout)));
484                 printf("%3lu ",
485                     (u_long)rate(vmm.v_tfree - ovmm.v_tfree));
486                 printf("%3lu ",
487                     (u_long)rate(vmm.v_pdpages - ovmm.v_pdpages));
488                 devstats();
489                 printf("%4lu %4lu %3lu ",
490                     (u_long)rate(vmm.v_intr - ovmm.v_intr),
491                     (u_long)rate(vmm.v_syscall - ovmm.v_syscall),
492                     (u_long)rate(vmm.v_swtch - ovmm.v_swtch));
493                 cpustats();
494                 printf("\n");
495                 fflush(stdout);
496                 if (reps >= 0 && --reps <= 0)
497                         break;
498                 ovmm = vmm;
499                 uptime = interval;
500                 /*
501                  * We round upward to avoid losing low-frequency events
502                  * (i.e., >= 1 per interval but < 1 per second).
503                  */
504                 if (interval != 1)
505                         halfuptime = (uptime + 1) / 2;
506                 else
507                         halfuptime = 0;
508                 sleep(interval);
509         }
510 }
511
512 static void
513 printhdr(void)
514 {
515         int i, num_shown;
516
517         num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
518         printf(" procs      memory      page%*s", 19, "");
519         if (num_shown > 1)
520                 printf(" disks %*s", num_shown * 4 - 7, "");
521         else if (num_shown == 1)
522                 printf("disk");
523         printf("   faults      cpu\n");
524         printf(" r b w     avm    fre  flt  re  pi  po  fr  sr ");
525         for (i = 0; i < num_devices; i++)
526                 if ((dev_select[i].selected)
527                  && (dev_select[i].selected <= maxshowdevs))
528                         printf("%c%c%d ", dev_select[i].device_name[0],
529                                      dev_select[i].device_name[1],
530                                      dev_select[i].unit_number);
531         printf("  in   sy  cs us sy id\n");
532         hdrcnt = winlines - 2;
533 }
534
535 /*
536  * Force a header to be prepended to the next output.
537  */
538 static void
539 needhdr(__unused int signo)
540 {
541
542         hdrcnt = 1;
543 }
544
545 static long
546 pct(long top, long bot)
547 {
548         long ans;
549
550         if (bot == 0)
551                 return(0);
552         ans = (quad_t)top * 100 / bot;
553         return (ans);
554 }
555
556 #define PCT(top, bot) pct((long)(top), (long)(bot))
557
558 static void
559 dosum(void)
560 {
561         struct nchstats *nch_tmp, nchstats;
562         int vms_size = sizeof(vms);
563         int vmm_size = sizeof(vmm);
564         int cpucnt;
565         u_long nchtotal;
566         size_t nch_size = sizeof(struct nchstats) * SMP_MAXCPU;
567
568         if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
569                 perror("sysctlbyname: vm.vmstats");
570                 exit(1);
571         }
572         if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
573                 perror("sysctlbyname: vm.vmstats");
574                 exit(1);
575         }
576         printf("%9u cpu context switches\n", vmm.v_swtch);
577         printf("%9u device interrupts\n", vmm.v_intr);
578         printf("%9u software interrupts\n", vmm.v_soft);
579         printf("%9u traps\n", vmm.v_trap);
580         printf("%9u system calls\n", vmm.v_syscall);
581         printf("%9u kernel threads created\n", vmm.v_kthreads);
582         printf("%9u  fork() calls\n", vmm.v_forks);
583         printf("%9u vfork() calls\n", vmm.v_vforks);
584         printf("%9u rfork() calls\n", vmm.v_rforks);
585         printf("%9u exec() calls\n", vmm.v_exec);
586         printf("%9u swap pager pageins\n", vmm.v_swapin);
587         printf("%9u swap pager pages paged in\n", vmm.v_swappgsin);
588         printf("%9u swap pager pageouts\n", vmm.v_swapout);
589         printf("%9u swap pager pages paged out\n", vmm.v_swappgsout);
590         printf("%9u vnode pager pageins\n", vmm.v_vnodein);
591         printf("%9u vnode pager pages paged in\n", vmm.v_vnodepgsin);
592         printf("%9u vnode pager pageouts\n", vmm.v_vnodeout);
593         printf("%9u vnode pager pages paged out\n", vmm.v_vnodepgsout);
594         printf("%9u page daemon wakeups\n", vmm.v_pdwakeups);
595         printf("%9u pages examined by the page daemon\n", vmm.v_pdpages);
596         printf("%9u pages reactivated\n", vmm.v_reactivated);
597         printf("%9u copy-on-write faults\n", vmm.v_cow_faults);
598         printf("%9u copy-on-write optimized faults\n", vmm.v_cow_optim);
599         printf("%9u zero fill pages zeroed\n", vmm.v_zfod);
600         printf("%9u zero fill pages prezeroed\n", vmm.v_ozfod);
601         printf("%9u intransit blocking page faults\n", vmm.v_intrans);
602         printf("%9u total VM faults taken\n", vmm.v_vm_faults);
603         printf("%9u pages affected by kernel thread creation\n", vmm.v_kthreadpages);
604         printf("%9u pages affected by  fork()\n", vmm.v_forkpages);
605         printf("%9u pages affected by vfork()\n", vmm.v_vforkpages);
606         printf("%9u pages affected by rfork()\n", vmm.v_rforkpages);
607         printf("%9u pages freed\n", vmm.v_tfree);
608         printf("%9u pages freed by daemon\n", vmm.v_dfree);
609         printf("%9u pages freed by exiting processes\n", vmm.v_pfree);
610         printf("%9u pages active\n", vms.v_active_count);
611         printf("%9u pages inactive\n", vms.v_inactive_count);
612         printf("%9u pages in VM cache\n", vms.v_cache_count);
613         printf("%9u pages wired down\n", vms.v_wire_count);
614         printf("%9u pages free\n", vms.v_free_count);
615         printf("%9u bytes per page\n", vms.v_page_size);
616         
617         if ((nch_tmp = malloc(nch_size)) == NULL) {
618                 perror("malloc");
619                 exit(1);
620         } else {
621                 if (sysctlbyname("vfs.cache.nchstats", nch_tmp, &nch_size, NULL, 0)) {
622                         perror("sysctlbyname vfs.cache.nchstats");
623                         free(nch_tmp);
624                         exit(1);
625                 } else {
626                         if ((nch_tmp = realloc(nch_tmp, nch_size)) == NULL) {
627                                 perror("realloc");
628                                 exit(1);
629                         }
630                 }
631         }
632         
633         cpucnt = nch_size / sizeof(struct nchstats);
634         kvm_nch_cpuagg(nch_tmp, &nchstats, cpucnt);
635
636         nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
637             nchstats.ncs_badhits + nchstats.ncs_falsehits +
638             nchstats.ncs_miss + nchstats.ncs_long;
639         printf("%9ld total name lookups\n", nchtotal);
640         printf(
641             "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
642             "", PCT(nchstats.ncs_goodhits, nchtotal),
643             PCT(nchstats.ncs_neghits, nchtotal),
644             PCT(nchstats.ncs_pass2, nchtotal));
645         printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
646             PCT(nchstats.ncs_badhits, nchtotal),
647             PCT(nchstats.ncs_falsehits, nchtotal),
648             PCT(nchstats.ncs_long, nchtotal));
649         free(nch_tmp);
650 }
651
652 #ifdef notyet
653 void
654 doforkst(void)
655 {
656         struct forkstat fks;
657
658         kread(X_FORKSTAT, &fks, sizeof(struct forkstat));
659         printf("%d forks, %d pages, average %.2f\n",
660             fks.cntfork, fks.sizfork, (double)fks.sizfork / fks.cntfork);
661         printf("%d vforks, %d pages, average %.2f\n",
662             fks.cntvfork, fks.sizvfork, (double)fks.sizvfork / fks.cntvfork);
663 }
664 #endif
665
666 static void
667 devstats(void)
668 {
669         int dn;
670         long double transfers_per_second;
671         long double busy_seconds;
672
673         diff_cp_time.cp_user = cp_time.cp_user - old_cp_time.cp_user;
674         diff_cp_time.cp_nice = cp_time.cp_nice - old_cp_time.cp_nice;
675         diff_cp_time.cp_sys = cp_time.cp_sys - old_cp_time.cp_sys;
676         diff_cp_time.cp_intr = cp_time.cp_intr - old_cp_time.cp_intr;
677         diff_cp_time.cp_idle = cp_time.cp_idle - old_cp_time.cp_idle;
678         old_cp_time = cp_time;
679
680         busy_seconds = compute_etime(cur.busy_time, last.busy_time);
681
682         for (dn = 0; dn < num_devices; dn++) {
683                 int di;
684
685                 if ((dev_select[dn].selected == 0)
686                  || (dev_select[dn].selected > maxshowdevs))
687                         continue;
688
689                 di = dev_select[dn].position;
690
691                 if (compute_stats(&cur.dinfo->devices[di],
692                                   &last.dinfo->devices[di], busy_seconds,
693                                   NULL, NULL, NULL,
694                                   NULL, &transfers_per_second, NULL,
695                                   NULL, NULL) != 0)
696                         errx(1, "%s", devstat_errbuf);
697
698                 printf("%3.0Lf ", transfers_per_second);
699         }
700 }
701
702 static void
703 cpustats(void)
704 {
705         uint64_t total;
706         double totusage;
707
708         total = diff_cp_time.cp_user + diff_cp_time.cp_nice +
709             diff_cp_time.cp_sys + diff_cp_time.cp_intr + diff_cp_time.cp_idle;
710
711         if (total)
712                 totusage = 100.0 / total;
713         else
714                 totusage = 0;
715         printf("%2.0f ",
716                (diff_cp_time.cp_user + diff_cp_time.cp_nice) * totusage);
717         printf("%2.0f ",
718                (diff_cp_time.cp_sys + diff_cp_time.cp_intr) * totusage);
719         printf("%2.0f",
720                diff_cp_time.cp_idle * totusage);
721 }
722
723 static void
724 dointr(void)
725 {
726         u_long *intrcnt, uptime;
727         u_int64_t inttotal;
728         int nintr, inamlen;
729         char *intrname;
730
731         uptime = getuptime();
732         nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
733         inamlen =
734             namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
735         intrcnt = malloc((size_t)nintr);
736         intrname = malloc((size_t)inamlen);
737         if (intrcnt == NULL || intrname == NULL)
738                 errx(1, "malloc");
739         kread(X_INTRCNT, intrcnt, (size_t)nintr);
740         kread(X_INTRNAMES, intrname, (size_t)inamlen);
741         printf("interrupt                   total       rate\n");
742         inttotal = 0;
743         nintr /= sizeof(long);
744         while (--nintr >= 0) {
745                 if (intrname[0] || *intrcnt) {
746                     printf("%-12s %20lu %10lu\n", intrname,
747                             *intrcnt, *intrcnt / uptime);
748                 }
749                 intrname += strlen(intrname) + 1;
750                 inttotal += *intrcnt++;
751         }
752         printf("Total        %20llu %10llu\n", inttotal,
753                         inttotal / (u_int64_t) uptime);
754 }
755
756 #define MAX_KMSTATS     200
757
758 static
759 long
760 cpuagg(long *ary)
761 {
762     int i;
763     long ttl;
764
765     for (i = ttl = 0; i < SMP_MAXCPU; ++i)
766         ttl += ary[i];
767     return(ttl);
768 }
769
770 static void
771 domem(void)
772 {
773         struct malloc_type *ks;
774         int i, j;
775         int first, nkms;
776         long totuse = 0, totfree = 0, totreq = 0;
777         struct malloc_type kmemstats[MAX_KMSTATS], *kmsp;
778         char buf[1024];
779
780         kread(X_KMEMSTATISTICS, &kmsp, sizeof(kmsp));
781         for (nkms = 0; nkms < MAX_KMSTATS && kmsp != NULL; nkms++) {
782                 if (sizeof(kmemstats[0]) != kvm_read(kd, (u_long)kmsp,
783                     &kmemstats[nkms], sizeof(kmemstats[0])))
784                         err(1, "kvm_read(%p)", (void *)kmsp);
785                 if (sizeof(buf) !=  kvm_read(kd, 
786                     (u_long)kmemstats[nkms].ks_shortdesc, buf, sizeof(buf)))
787                         err(1, "kvm_read(%p)", 
788                             kmemstats[nkms].ks_shortdesc);
789                 buf[sizeof(buf) - 1] = '\0';
790                 kmemstats[nkms].ks_shortdesc = strdup(buf);
791                 kmsp = kmemstats[nkms].ks_next;
792         }
793         if (kmsp != NULL)
794                 warnx("truncated to the first %d memory types", nkms);
795
796         printf(
797             "\nMemory statistics by type                          Type  Kern\n");
798         printf(
799 "        Type  InUse MemUse HighUse  Limit Requests  Limit Limit Size(s)\n");
800         for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
801                 if (ks->ks_calls == 0)
802                         continue;
803                 printf("%13s%6ld%6ldK%7ldK%7ldK%9lld%5u%6u",
804                     ks->ks_shortdesc,
805                     cpuagg(ks->ks_inuse), (cpuagg(ks->ks_memuse) + 1023) / 1024,
806                     (ks->ks_maxused + 1023) / 1024,
807                     (ks->ks_limit + 1023) / 1024, ks->ks_calls,
808                     ks->ks_limblocks, ks->ks_mapblocks);
809                 first = 1;
810                 for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
811                         if ((ks->ks_size & j) == 0)
812                                 continue;
813                         if (first)
814                                 printf("  ");
815                         else
816                                 printf(",");
817                         if(j<1024)
818                                 printf("%d",j);
819                         else
820                                 printf("%dK",j>>10);
821                         first = 0;
822                 }
823                 printf("\n");
824                 totuse += cpuagg(ks->ks_memuse);
825                 totreq += ks->ks_calls;
826         }
827         printf("\nMemory Totals:  In Use    Free    Requests\n");
828         printf("              %7ldK %6ldK    %8ld\n",
829              (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
830 }
831
832 static void
833 dozmem(void)
834 {
835         char *buf;
836         size_t bufsize;
837
838         buf = NULL;
839         bufsize = 1024;
840         for (;;) {
841                 if ((buf = realloc(buf, bufsize)) == NULL)
842                         err(1, "realloc()");
843                 if (sysctlbyname("vm.zone", buf, &bufsize, 0, NULL) == 0)
844                         break;
845                 if (errno != ENOMEM)
846                         err(1, "sysctl()");
847                 bufsize *= 2;
848         }
849         buf[bufsize] = '\0'; /* play it safe */
850         printf("%s\n\n", buf);
851         free(buf);
852 }
853
854 /*
855  * kread reads something from the kernel, given its nlist index.
856  */
857 static void
858 kread(int nlx, void *addr, size_t size)
859 {
860         const char *sym;
861
862         if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
863                 sym = namelist[nlx].n_name;
864                 if (*sym == '_')
865                         ++sym;
866                 errx(1, "symbol %s not defined", sym);
867         }
868         if (kvm_read(kd, namelist[nlx].n_value, addr, size) != (ssize_t)size) {
869                 sym = namelist[nlx].n_name;
870                 if (*sym == '_')
871                         ++sym;
872                 errx(1, "%s: %s", sym, kvm_geterr(kd));
873         }
874 }
875
876 static void
877 usage(void)
878 {
879         fprintf(stderr, "%s%s",
880                 "usage: vmstat [-imsz] [-c count] [-M core] [-N system] [-w wait]\n",
881                 "              [-n devs] [disks]\n");
882         exit(1);
883 }