]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - usr.bin/vmstat/vmstat.c
MFC r233298:
[FreeBSD/stable/8.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
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1980, 1986, 1991, 1993\n\
37         The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39
40 #if 0
41 #ifndef lint
42 static char sccsid[] = "@(#)vmstat.c    8.1 (Berkeley) 6/6/93";
43 #endif /* not lint */
44 #endif
45
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48
49 #include <sys/param.h>
50 #include <sys/time.h>
51 #include <sys/proc.h>
52 #include <sys/uio.h>
53 #include <sys/namei.h>
54 #include <sys/malloc.h>
55 #include <sys/signal.h>
56 #include <sys/fcntl.h>
57 #include <sys/ioctl.h>
58 #include <sys/resource.h>
59 #include <sys/sysctl.h>
60 #include <sys/vmmeter.h>
61 #include <sys/pcpu.h>
62
63 #include <vm/vm_param.h>
64
65 #include <ctype.h>
66 #include <devstat.h>
67 #include <err.h>
68 #include <errno.h>
69 #include <kvm.h>
70 #include <limits.h>
71 #include <memstat.h>
72 #include <nlist.h>
73 #include <paths.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <sysexits.h>
78 #include <time.h>
79 #include <unistd.h>
80 #include <libutil.h>
81
82 static char da[] = "da";
83
84 static struct nlist namelist[] = {
85 #define X_SUM           0
86         { "_cnt" },
87 #define X_HZ            1
88         { "_hz" },
89 #define X_STATHZ        2
90         { "_stathz" },
91 #define X_NCHSTATS      3
92         { "_nchstats" },
93 #define X_INTRNAMES     4
94         { "_intrnames" },
95 #define X_EINTRNAMES    5
96         { "_eintrnames" },
97 #define X_INTRCNT       6
98         { "_intrcnt" },
99 #define X_EINTRCNT      7
100         { "_eintrcnt" },
101 #ifdef notyet
102 #define X_DEFICIT       XXX
103         { "_deficit" },
104 #define X_REC           XXX
105         { "_rectime" },
106 #define X_PGIN          XXX
107         { "_pgintime" },
108 #define X_XSTATS        XXX
109         { "_xstats" },
110 #define X_END           XXX
111 #else
112 #define X_END           8
113 #endif
114         { "" },
115 };
116
117 static struct statinfo cur, last;
118 static int num_devices, maxshowdevs;
119 static long generation;
120 static struct device_selection *dev_select;
121 static int num_selected;
122 static struct devstat_match *matches;
123 static int num_matches = 0;
124 static int num_devices_specified, num_selections;
125 static long select_generation;
126 static char **specified_devices;
127 static devstat_select_mode select_mode;
128
129 static struct   vmmeter sum, osum;
130
131 #define VMSTAT_DEFAULT_LINES    20      /* Default number of `winlines'. */
132 volatile sig_atomic_t wresized;         /* Tty resized, when non-zero. */
133 static int winlines = VMSTAT_DEFAULT_LINES; /* Current number of tty rows. */
134
135 static int      aflag;
136 static int      nflag;
137 static int      Pflag;
138 static int      hflag;
139
140 static kvm_t   *kd;
141
142 #define FORKSTAT        0x01
143 #define INTRSTAT        0x02
144 #define MEMSTAT         0x04
145 #define SUMSTAT         0x08
146 #define TIMESTAT        0x10
147 #define VMSTAT          0x20
148 #define ZMEMSTAT        0x40
149
150 static void     cpustats(void);
151 static void     pcpustats(int, u_long, int);
152 static void     devstats(void);
153 static void     doforkst(void);
154 static void     dointr(void);
155 static void     dosum(void);
156 static void     dovmstat(unsigned int, int);
157 static void     domemstat_malloc(void);
158 static void     domemstat_zone(void);
159 static void     kread(int, void *, size_t);
160 static void     kreado(int, void *, size_t, size_t);
161 static char    *kgetstr(const char *);
162 static void     needhdr(int);
163 static void     needresize(int);
164 static void     doresize(void);
165 static void     printhdr(int, u_long);
166 static void     usage(void);
167
168 static long     pct(long, long);
169 static long     getuptime(void);
170
171 static char   **getdrivedata(char **);
172
173 int
174 main(int argc, char *argv[])
175 {
176         int c, todo;
177         unsigned int interval;
178         int reps;
179         char *memf, *nlistf;
180         char errbuf[_POSIX2_LINE_MAX];
181
182         memf = nlistf = NULL;
183         interval = reps = todo = 0;
184         maxshowdevs = 2;
185         hflag = isatty(1);
186         while ((c = getopt(argc, argv, "ac:fhHiM:mN:n:Pp:stw:z")) != -1) {
187                 switch (c) {
188                 case 'a':
189                         aflag++;
190                         break;
191                 case 'c':
192                         reps = atoi(optarg);
193                         break;
194                 case 'P':
195                         Pflag++;
196                         break;
197                 case 'f':
198                         todo |= FORKSTAT;
199                         break;
200                 case 'h':
201                         hflag = 1;
202                         break;
203                 case 'H':
204                         hflag = 0;
205                         break;
206                 case 'i':
207                         todo |= INTRSTAT;
208                         break;
209                 case 'M':
210                         memf = optarg;
211                         break;
212                 case 'm':
213                         todo |= MEMSTAT;
214                         break;
215                 case 'N':
216                         nlistf = optarg;
217                         break;
218                 case 'n':
219                         nflag = 1;
220                         maxshowdevs = atoi(optarg);
221                         if (maxshowdevs < 0)
222                                 errx(1, "number of devices %d is < 0",
223                                      maxshowdevs);
224                         break;
225                 case 'p':
226                         if (devstat_buildmatch(optarg, &matches, &num_matches) != 0)
227                                 errx(1, "%s", devstat_errbuf);
228                         break;
229                 case 's':
230                         todo |= SUMSTAT;
231                         break;
232                 case 't':
233 #ifdef notyet
234                         todo |= TIMESTAT;
235 #else
236                         errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
237 #endif
238                         break;
239                 case 'w':
240                         interval = atoi(optarg);
241                         break;
242                 case 'z':
243                         todo |= ZMEMSTAT;
244                         break;
245                 case '?':
246                 default:
247                         usage();
248                 }
249         }
250         argc -= optind;
251         argv += optind;
252
253         if (todo == 0)
254                 todo = VMSTAT;
255
256         if (memf != NULL) {
257                 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
258                 if (kd == NULL)
259                         errx(1, "kvm_openfiles: %s", errbuf);
260         }
261
262         if (kd != NULL && (c = kvm_nlist(kd, namelist)) != 0) {
263                 if (c > 0) {
264                         warnx("undefined symbols:");
265                         for (c = 0;
266                              c < (int)(sizeof(namelist)/sizeof(namelist[0]));
267                              c++)
268                                 if (namelist[c].n_type == 0)
269                                         (void)fprintf(stderr, " %s",
270                                             namelist[c].n_name);
271                         (void)fputc('\n', stderr);
272                 } else
273                         warnx("kvm_nlist: %s", kvm_geterr(kd));
274                 exit(1);
275         }
276         if (kd && Pflag)
277                 errx(1, "Cannot use -P with crash dumps");
278
279         if (todo & VMSTAT) {
280                 /*
281                  * Make sure that the userland devstat version matches the
282                  * kernel devstat version.  If not, exit and print a
283                  * message informing the user of his mistake.
284                  */
285                 if (devstat_checkversion(NULL) < 0)
286                         errx(1, "%s", devstat_errbuf);
287
288
289                 argv = getdrivedata(argv);
290         }
291
292 #define BACKWARD_COMPATIBILITY
293 #ifdef  BACKWARD_COMPATIBILITY
294         if (*argv) {
295                 interval = atoi(*argv);
296                 if (*++argv)
297                         reps = atoi(*argv);
298         }
299 #endif
300
301         if (interval) {
302                 if (!reps)
303                         reps = -1;
304         } else if (reps)
305                 interval = 1;
306
307         if (todo & FORKSTAT)
308                 doforkst();
309         if (todo & MEMSTAT)
310                 domemstat_malloc();
311         if (todo & ZMEMSTAT)
312                 domemstat_zone();
313         if (todo & SUMSTAT)
314                 dosum();
315 #ifdef notyet
316         if (todo & TIMESTAT)
317                 dotimes();
318 #endif
319         if (todo & INTRSTAT)
320                 dointr();
321         if (todo & VMSTAT)
322                 dovmstat(interval, reps);
323         exit(0);
324 }
325
326 static int
327 mysysctl(const char *name, void *oldp, size_t *oldlenp,
328     void *newp, size_t newlen)
329 {
330         int error;
331
332         error = sysctlbyname(name, oldp, oldlenp, newp, newlen);
333         if (error != 0 && errno != ENOMEM)
334                 err(1, "sysctl(%s)", name);
335         return (error);
336 }
337
338 static char **
339 getdrivedata(char **argv)
340 {
341         if ((num_devices = devstat_getnumdevs(NULL)) < 0)
342                 errx(1, "%s", devstat_errbuf);
343
344         cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
345         last.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
346
347         if (devstat_getdevs(NULL, &cur) == -1)
348                 errx(1, "%s", devstat_errbuf);
349
350         num_devices = cur.dinfo->numdevs;
351         generation = cur.dinfo->generation;
352
353         specified_devices = (char **)malloc(sizeof(char *));
354         for (num_devices_specified = 0; *argv; ++argv) {
355                 if (isdigit(**argv))
356                         break;
357                 num_devices_specified++;
358                 specified_devices = (char **)realloc(specified_devices,
359                                                      sizeof(char *) *
360                                                      num_devices_specified);
361                 specified_devices[num_devices_specified - 1] = *argv;
362         }
363         dev_select = NULL;
364
365         if (nflag == 0 && maxshowdevs < num_devices_specified)
366                         maxshowdevs = num_devices_specified;
367
368         /*
369          * People are generally only interested in disk statistics when
370          * they're running vmstat.  So, that's what we're going to give
371          * them if they don't specify anything by default.  We'll also give
372          * them any other random devices in the system so that we get to
373          * maxshowdevs devices, if that many devices exist.  If the user
374          * specifies devices on the command line, either through a pattern
375          * match or by naming them explicitly, we will give the user only
376          * those devices.
377          */
378         if ((num_devices_specified == 0) && (num_matches == 0)) {
379                 if (devstat_buildmatch(da, &matches, &num_matches) != 0)
380                         errx(1, "%s", devstat_errbuf);
381
382                 select_mode = DS_SELECT_ADD;
383         } else
384                 select_mode = DS_SELECT_ONLY;
385
386         /*
387          * At this point, selectdevs will almost surely indicate that the
388          * device list has changed, so we don't look for return values of 0
389          * or 1.  If we get back -1, though, there is an error.
390          */
391         if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
392                        &select_generation, generation, cur.dinfo->devices,
393                        num_devices, matches, num_matches, specified_devices,
394                        num_devices_specified, select_mode,
395                        maxshowdevs, 0) == -1)
396                 errx(1, "%s", devstat_errbuf);
397
398         return(argv);
399 }
400
401 static long
402 getuptime(void)
403 {
404         struct timespec sp;
405
406         (void)clock_gettime(CLOCK_MONOTONIC, &sp);
407
408         return(sp.tv_sec);
409 }
410
411 static void
412 fill_pcpu(struct pcpu ***pcpup, int* maxcpup)
413 {
414         struct pcpu **pcpu;
415         
416         int maxcpu, size, i;
417
418         *pcpup = NULL;
419         
420         if (kd == NULL)
421                 return;
422
423         maxcpu = kvm_getmaxcpu(kd);
424         if (maxcpu < 0)
425                 errx(1, "kvm_getmaxcpu: %s", kvm_geterr(kd));
426
427         pcpu = calloc(maxcpu, sizeof(struct pcpu *));
428         if (pcpu == NULL)
429                 err(1, "calloc");
430
431         for (i = 0; i < maxcpu; i++) {
432                 pcpu[i] = kvm_getpcpu(kd, i);
433                 if (pcpu[i] == (struct pcpu *)-1)
434                         errx(1, "kvm_getpcpu: %s", kvm_geterr(kd));
435         }
436
437         *maxcpup = maxcpu;
438         *pcpup = pcpu;
439 }
440
441 static void
442 free_pcpu(struct pcpu **pcpu, int maxcpu)
443 {
444         int i;
445
446         for (i = 0; i < maxcpu; i++)
447                 free(pcpu[i]);
448         free(pcpu);
449 }
450
451 static void
452 fill_vmmeter(struct vmmeter *vmmp)
453 {
454         struct pcpu **pcpu;
455         int maxcpu, i;
456
457         if (kd != NULL) {
458                 kread(X_SUM, vmmp, sizeof(*vmmp));
459                 fill_pcpu(&pcpu, &maxcpu);
460                 for (i = 0; i < maxcpu; i++) {
461                         if (pcpu[i] == NULL)
462                                 continue;
463 #define ADD_FROM_PCPU(i, name) \
464                         vmmp->name += pcpu[i]->pc_cnt.name
465                         ADD_FROM_PCPU(i, v_swtch);
466                         ADD_FROM_PCPU(i, v_trap);
467                         ADD_FROM_PCPU(i, v_syscall);
468                         ADD_FROM_PCPU(i, v_intr);
469                         ADD_FROM_PCPU(i, v_soft);
470                         ADD_FROM_PCPU(i, v_vm_faults);
471                         ADD_FROM_PCPU(i, v_cow_faults);
472                         ADD_FROM_PCPU(i, v_cow_optim);
473                         ADD_FROM_PCPU(i, v_zfod);
474                         ADD_FROM_PCPU(i, v_ozfod);
475                         ADD_FROM_PCPU(i, v_swapin);
476                         ADD_FROM_PCPU(i, v_swapout);
477                         ADD_FROM_PCPU(i, v_swappgsin);
478                         ADD_FROM_PCPU(i, v_swappgsout);
479                         ADD_FROM_PCPU(i, v_vnodein);
480                         ADD_FROM_PCPU(i, v_vnodeout);
481                         ADD_FROM_PCPU(i, v_vnodepgsin);
482                         ADD_FROM_PCPU(i, v_vnodepgsout);
483                         ADD_FROM_PCPU(i, v_intrans);
484                         ADD_FROM_PCPU(i, v_tfree);
485                         ADD_FROM_PCPU(i, v_forks);
486                         ADD_FROM_PCPU(i, v_vforks);
487                         ADD_FROM_PCPU(i, v_rforks);
488                         ADD_FROM_PCPU(i, v_kthreads);
489                         ADD_FROM_PCPU(i, v_forkpages);
490                         ADD_FROM_PCPU(i, v_vforkpages);
491                         ADD_FROM_PCPU(i, v_rforkpages);
492                         ADD_FROM_PCPU(i, v_kthreadpages);
493 #undef ADD_FROM_PCPU
494                 }
495                 free_pcpu(pcpu, maxcpu);
496         } else {
497                 size_t size = sizeof(unsigned int);
498 #define GET_VM_STATS(cat, name) \
499         mysysctl("vm.stats." #cat "." #name, &vmmp->name, &size, NULL, 0)
500                 /* sys */
501                 GET_VM_STATS(sys, v_swtch);
502                 GET_VM_STATS(sys, v_trap);
503                 GET_VM_STATS(sys, v_syscall);
504                 GET_VM_STATS(sys, v_intr);
505                 GET_VM_STATS(sys, v_soft);
506
507                 /* vm */
508                 GET_VM_STATS(vm, v_vm_faults);
509                 GET_VM_STATS(vm, v_cow_faults);
510                 GET_VM_STATS(vm, v_cow_optim);
511                 GET_VM_STATS(vm, v_zfod);
512                 GET_VM_STATS(vm, v_ozfod);
513                 GET_VM_STATS(vm, v_swapin);
514                 GET_VM_STATS(vm, v_swapout);
515                 GET_VM_STATS(vm, v_swappgsin);
516                 GET_VM_STATS(vm, v_swappgsout);
517                 GET_VM_STATS(vm, v_vnodein);
518                 GET_VM_STATS(vm, v_vnodeout);
519                 GET_VM_STATS(vm, v_vnodepgsin);
520                 GET_VM_STATS(vm, v_vnodepgsout);
521                 GET_VM_STATS(vm, v_intrans);
522                 GET_VM_STATS(vm, v_reactivated);
523                 GET_VM_STATS(vm, v_pdwakeups);
524                 GET_VM_STATS(vm, v_pdpages);
525                 GET_VM_STATS(vm, v_tcached);
526                 GET_VM_STATS(vm, v_dfree);
527                 GET_VM_STATS(vm, v_pfree);
528                 GET_VM_STATS(vm, v_tfree);
529                 GET_VM_STATS(vm, v_page_size);
530                 GET_VM_STATS(vm, v_page_count);
531                 GET_VM_STATS(vm, v_free_reserved);
532                 GET_VM_STATS(vm, v_free_target);
533                 GET_VM_STATS(vm, v_free_min);
534                 GET_VM_STATS(vm, v_free_count);
535                 GET_VM_STATS(vm, v_wire_count);
536                 GET_VM_STATS(vm, v_active_count);
537                 GET_VM_STATS(vm, v_inactive_target);
538                 GET_VM_STATS(vm, v_inactive_count);
539                 GET_VM_STATS(vm, v_cache_count);
540                 GET_VM_STATS(vm, v_cache_min);
541                 GET_VM_STATS(vm, v_cache_max);
542                 GET_VM_STATS(vm, v_pageout_free_min);
543                 GET_VM_STATS(vm, v_interrupt_free_min);
544                 /*GET_VM_STATS(vm, v_free_severe);*/
545                 GET_VM_STATS(vm, v_forks);
546                 GET_VM_STATS(vm, v_vforks);
547                 GET_VM_STATS(vm, v_rforks);
548                 GET_VM_STATS(vm, v_kthreads);
549                 GET_VM_STATS(vm, v_forkpages);
550                 GET_VM_STATS(vm, v_vforkpages);
551                 GET_VM_STATS(vm, v_rforkpages);
552                 GET_VM_STATS(vm, v_kthreadpages);
553 #undef GET_VM_STATS
554         }
555 }
556
557 static void
558 fill_vmtotal(struct vmtotal *vmtp)
559 {
560         if (kd != NULL) {
561                 /* XXX fill vmtp */
562                 errx(1, "not implemented");
563         } else {
564                 size_t size = sizeof(*vmtp);
565                 mysysctl("vm.vmtotal", vmtp, &size, NULL, 0);
566                 if (size != sizeof(*vmtp))
567                         errx(1, "vm.total size mismatch");
568         }
569 }
570
571 /* Determine how many cpu columns, and what index they are in kern.cp_times */
572 static int
573 getcpuinfo(u_long *maskp, int *maxidp)
574 {
575         int maxcpu;
576         int maxid;
577         int ncpus;
578         int i, j;
579         int empty;
580         size_t size;
581         long *times;
582         u_long mask;
583
584         if (kd != NULL)
585                 errx(1, "not implemented");
586         mask = 0;
587         ncpus = 0;
588         size = sizeof(maxcpu);
589         mysysctl("kern.smp.maxcpus", &maxcpu, &size, NULL, 0);
590         if (size != sizeof(maxcpu))
591                 errx(1, "sysctl kern.smp.maxcpus");
592         size = sizeof(long) * maxcpu * CPUSTATES;
593         times = malloc(size);
594         if (times == NULL)
595                 err(1, "malloc %zd bytes", size);
596         mysysctl("kern.cp_times", times, &size, NULL, 0);
597         maxid = (size / CPUSTATES / sizeof(long)) - 1;
598         for (i = 0; i <= maxid; i++) {
599                 empty = 1;
600                 for (j = 0; empty && j < CPUSTATES; j++) {
601                         if (times[i * CPUSTATES + j] != 0)
602                                 empty = 0;
603                 }
604                 if (!empty) {
605                         mask |= (1ul << i);
606                         ncpus++;
607                 }
608         }
609         if (maskp)
610                 *maskp = mask;
611         if (maxidp)
612                 *maxidp = maxid;
613         return (ncpus);
614 }
615
616
617 static void
618 prthuman(u_int64_t val, int size)
619 {
620         char buf[10];
621         int flags;
622
623         if (size < 5 || size > 9)
624                 errx(1, "doofus");
625         flags = HN_B | HN_NOSPACE | HN_DECIMAL;
626         humanize_number(buf, size, val, "", HN_AUTOSCALE, flags);
627         printf("%*s", size, buf);
628 }
629
630 static int hz, hdrcnt;
631
632 static long *cur_cp_times;
633 static long *last_cp_times;
634 static size_t size_cp_times;
635
636 static void
637 dovmstat(unsigned int interval, int reps)
638 {
639         struct vmtotal total;
640         time_t uptime, halfuptime;
641         struct devinfo *tmp_dinfo;
642         size_t size;
643         int ncpus, maxid;
644         u_long cpumask;
645
646         uptime = getuptime();
647         halfuptime = uptime / 2;
648
649         /*
650          * If the user stops the program (control-Z) and then resumes it,
651          * print out the header again.
652          */
653         (void)signal(SIGCONT, needhdr);
654
655         /*
656          * If our standard output is a tty, then install a SIGWINCH handler
657          * and set wresized so that our first iteration through the main
658          * vmstat loop will peek at the terminal's current rows to find out
659          * how many lines can fit in a screenful of output.
660          */
661         if (isatty(fileno(stdout)) != 0) {
662                 wresized = 1;
663                 (void)signal(SIGWINCH, needresize);
664         } else {
665                 wresized = 0;
666                 winlines = VMSTAT_DEFAULT_LINES;
667         }
668
669         if (kd != NULL) {
670                 if (namelist[X_STATHZ].n_type != 0 &&
671                     namelist[X_STATHZ].n_value != 0)
672                         kread(X_STATHZ, &hz, sizeof(hz));
673                 if (!hz)
674                         kread(X_HZ, &hz, sizeof(hz));
675         } else {
676                 struct clockinfo clockrate;
677
678                 size = sizeof(clockrate);
679                 mysysctl("kern.clockrate", &clockrate, &size, NULL, 0);
680                 if (size != sizeof(clockrate))
681                         errx(1, "clockrate size mismatch");
682                 hz = clockrate.hz;
683         }
684
685         if (Pflag) {
686                 ncpus = getcpuinfo(&cpumask, &maxid);
687                 size_cp_times = sizeof(long) * (maxid + 1) * CPUSTATES;
688                 cur_cp_times = calloc(1, size_cp_times);
689                 last_cp_times = calloc(1, size_cp_times);
690         }
691         for (hdrcnt = 1;;) {
692                 if (!--hdrcnt)
693                         printhdr(ncpus, cpumask);
694                 if (kd != NULL) {
695                         if (kvm_getcptime(kd, cur.cp_time) < 0)
696                                 errx(1, "kvm_getcptime: %s", kvm_geterr(kd));
697                 } else {
698                         size = sizeof(cur.cp_time);
699                         mysysctl("kern.cp_time", &cur.cp_time, &size, NULL, 0);
700                         if (size != sizeof(cur.cp_time))
701                                 errx(1, "cp_time size mismatch");
702                 }
703                 if (Pflag) {
704                         size = size_cp_times;
705                         mysysctl("kern.cp_times", cur_cp_times, &size, NULL, 0);
706                         if (size != size_cp_times)
707                                 errx(1, "cp_times mismatch");
708                 }
709
710                 tmp_dinfo = last.dinfo;
711                 last.dinfo = cur.dinfo;
712                 cur.dinfo = tmp_dinfo;
713                 last.snap_time = cur.snap_time;
714
715                 /*
716                  * Here what we want to do is refresh our device stats.
717                  * getdevs() returns 1 when the device list has changed.
718                  * If the device list has changed, we want to go through
719                  * the selection process again, in case a device that we
720                  * were previously displaying has gone away.
721                  */
722                 switch (devstat_getdevs(NULL, &cur)) {
723                 case -1:
724                         errx(1, "%s", devstat_errbuf);
725                         break;
726                 case 1: {
727                         int retval;
728
729                         num_devices = cur.dinfo->numdevs;
730                         generation = cur.dinfo->generation;
731
732                         retval = devstat_selectdevs(&dev_select, &num_selected,
733                                             &num_selections, &select_generation,
734                                             generation, cur.dinfo->devices,
735                                             num_devices, matches, num_matches,
736                                             specified_devices,
737                                             num_devices_specified, select_mode,
738                                             maxshowdevs, 0);
739                         switch (retval) {
740                         case -1:
741                                 errx(1, "%s", devstat_errbuf);
742                                 break;
743                         case 1:
744                                 printhdr(ncpus, cpumask);
745                                 break;
746                         default:
747                                 break;
748                         }
749                 }
750                 default:
751                         break;
752                 }
753
754                 fill_vmmeter(&sum);
755                 fill_vmtotal(&total);
756                 (void)printf("%2d %1d %1d",
757                     total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
758 #define vmstat_pgtok(a) ((a) * (sum.v_page_size >> 10))
759 #define rate(x) (((x) + halfuptime) / uptime)   /* round */
760                 if (hflag) {
761                         printf(" ");
762                         prthuman(total.t_avm * (u_int64_t)sum.v_page_size, 7);
763                         printf(" ");
764                         prthuman(total.t_free * (u_int64_t)sum.v_page_size, 6);
765                         printf(" ");
766                 } else {
767                         printf(" %7d ", vmstat_pgtok(total.t_avm));
768                         printf(" %6d ", vmstat_pgtok(total.t_free));
769                 }
770                 (void)printf("%5lu ",
771                     (unsigned long)rate(sum.v_vm_faults - osum.v_vm_faults));
772                 (void)printf("%3lu ",
773                     (unsigned long)rate(sum.v_reactivated - osum.v_reactivated));
774                 (void)printf("%3lu ",
775                     (unsigned long)rate(sum.v_swapin + sum.v_vnodein -
776                     (osum.v_swapin + osum.v_vnodein)));
777                 (void)printf("%3lu ",
778                     (unsigned long)rate(sum.v_swapout + sum.v_vnodeout -
779                     (osum.v_swapout + osum.v_vnodeout)));
780                 (void)printf("%5lu ",
781                     (unsigned long)rate(sum.v_tfree - osum.v_tfree));
782                 (void)printf("%3lu ",
783                     (unsigned long)rate(sum.v_pdpages - osum.v_pdpages));
784                 devstats();
785                 (void)printf("%4lu %4lu %4lu",
786                     (unsigned long)rate(sum.v_intr - osum.v_intr),
787                     (unsigned long)rate(sum.v_syscall - osum.v_syscall),
788                     (unsigned long)rate(sum.v_swtch - osum.v_swtch));
789                 if (Pflag)
790                         pcpustats(ncpus, cpumask, maxid);
791                 else
792                         cpustats();
793                 (void)printf("\n");
794                 (void)fflush(stdout);
795                 if (reps >= 0 && --reps <= 0)
796                         break;
797                 osum = sum;
798                 uptime = interval;
799                 /*
800                  * We round upward to avoid losing low-frequency events
801                  * (i.e., >= 1 per interval but < 1 per second).
802                  */
803                 if (interval != 1)
804                         halfuptime = (uptime + 1) / 2;
805                 else
806                         halfuptime = 0;
807                 (void)sleep(interval);
808         }
809 }
810
811 static void
812 printhdr(int ncpus, u_long cpumask)
813 {
814         int i, num_shown;
815
816         num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
817         (void)printf(" procs      memory      page%*s", 19, "");
818         if (num_shown > 1)
819                 (void)printf(" disks %*s", num_shown * 4 - 7, "");
820         else if (num_shown == 1)
821                 (void)printf("disk");
822         (void)printf("   faults         ");
823         if (Pflag) {
824                 for (i = 0; i < ncpus; i++) {
825                         if (cpumask & (1ul << i))
826                                 printf("cpu%-2d    ", i);
827                 }
828                 printf("\n");
829         } else
830                 printf("cpu\n");
831         (void)printf(" r b w     avm    fre   flt  re  pi  po    fr  sr ");
832         for (i = 0; i < num_devices; i++)
833                 if ((dev_select[i].selected)
834                  && (dev_select[i].selected <= maxshowdevs))
835                         (void)printf("%c%c%d ", dev_select[i].device_name[0],
836                                      dev_select[i].device_name[1],
837                                      dev_select[i].unit_number);
838         (void)printf("  in   sy   cs");
839         if (Pflag) {
840                 for (i = 0; i < ncpus; i++)
841                         printf(" us sy id");
842                 printf("\n");
843         } else
844                 printf(" us sy id\n");
845         if (wresized != 0)
846                 doresize();
847         hdrcnt = winlines;
848 }
849
850 /*
851  * Force a header to be prepended to the next output.
852  */
853 static void
854 needhdr(int dummy __unused)
855 {
856
857         hdrcnt = 1;
858 }
859
860 /*
861  * When the terminal is resized, force an update of the maximum number of rows
862  * printed between each header repetition.  Then force a new header to be
863  * prepended to the next output.
864  */
865 void
866 needresize(int signo)
867 {
868
869         wresized = 1;
870         hdrcnt = 1;
871 }
872
873 /*
874  * Update the global `winlines' count of terminal rows.
875  */
876 void
877 doresize(void)
878 {
879         int status;
880         struct winsize w;
881
882         for (;;) {
883                 status = ioctl(fileno(stdout), TIOCGWINSZ, &w);
884                 if (status == -1 && errno == EINTR)
885                         continue;
886                 else if (status == -1)
887                         err(1, "ioctl");
888                 if (w.ws_row > 3)
889                         winlines = w.ws_row - 3;
890                 else
891                         winlines = VMSTAT_DEFAULT_LINES;
892                 break;
893         }
894
895         /*
896          * Inhibit doresize() calls until we are rescheduled by SIGWINCH.
897          */
898         wresized = 0;
899 }
900
901 #ifdef notyet
902 static void
903 dotimes(void)
904 {
905         unsigned int pgintime, rectime;
906
907         kread(X_REC, &rectime, sizeof(rectime));
908         kread(X_PGIN, &pgintime, sizeof(pgintime));
909         kread(X_SUM, &sum, sizeof(sum));
910         (void)printf("%u reclaims, %u total time (usec)\n",
911             sum.v_pgrec, rectime);
912         (void)printf("average: %u usec / reclaim\n", rectime / sum.v_pgrec);
913         (void)printf("\n");
914         (void)printf("%u page ins, %u total time (msec)\n",
915             sum.v_pgin, pgintime / 10);
916         (void)printf("average: %8.1f msec / page in\n",
917             pgintime / (sum.v_pgin * 10.0));
918 }
919 #endif
920
921 static long
922 pct(long top, long bot)
923 {
924         long ans;
925
926         if (bot == 0)
927                 return(0);
928         ans = (quad_t)top * 100 / bot;
929         return (ans);
930 }
931
932 #define PCT(top, bot) pct((long)(top), (long)(bot))
933
934 static void
935 dosum(void)
936 {
937         struct nchstats lnchstats;
938         long nchtotal;
939
940         fill_vmmeter(&sum);
941         (void)printf("%9u cpu context switches\n", sum.v_swtch);
942         (void)printf("%9u device interrupts\n", sum.v_intr);
943         (void)printf("%9u software interrupts\n", sum.v_soft);
944         (void)printf("%9u traps\n", sum.v_trap);
945         (void)printf("%9u system calls\n", sum.v_syscall);
946         (void)printf("%9u kernel threads created\n", sum.v_kthreads);
947         (void)printf("%9u  fork() calls\n", sum.v_forks);
948         (void)printf("%9u vfork() calls\n", sum.v_vforks);
949         (void)printf("%9u rfork() calls\n", sum.v_rforks);
950         (void)printf("%9u swap pager pageins\n", sum.v_swapin);
951         (void)printf("%9u swap pager pages paged in\n", sum.v_swappgsin);
952         (void)printf("%9u swap pager pageouts\n", sum.v_swapout);
953         (void)printf("%9u swap pager pages paged out\n", sum.v_swappgsout);
954         (void)printf("%9u vnode pager pageins\n", sum.v_vnodein);
955         (void)printf("%9u vnode pager pages paged in\n", sum.v_vnodepgsin);
956         (void)printf("%9u vnode pager pageouts\n", sum.v_vnodeout);
957         (void)printf("%9u vnode pager pages paged out\n", sum.v_vnodepgsout);
958         (void)printf("%9u page daemon wakeups\n", sum.v_pdwakeups);
959         (void)printf("%9u pages examined by the page daemon\n", sum.v_pdpages);
960         (void)printf("%9u pages reactivated\n", sum.v_reactivated);
961         (void)printf("%9u copy-on-write faults\n", sum.v_cow_faults);
962         (void)printf("%9u copy-on-write optimized faults\n", sum.v_cow_optim);
963         (void)printf("%9u zero fill pages zeroed\n", sum.v_zfod);
964         (void)printf("%9u zero fill pages prezeroed\n", sum.v_ozfod);
965         (void)printf("%9u intransit blocking page faults\n", sum.v_intrans);
966         (void)printf("%9u total VM faults taken\n", sum.v_vm_faults);
967         (void)printf("%9u pages affected by kernel thread creation\n", sum.v_kthreadpages);
968         (void)printf("%9u pages affected by  fork()\n", sum.v_forkpages);
969         (void)printf("%9u pages affected by vfork()\n", sum.v_vforkpages);
970         (void)printf("%9u pages affected by rfork()\n", sum.v_rforkpages);
971         (void)printf("%9u pages cached\n", sum.v_tcached);
972         (void)printf("%9u pages freed\n", sum.v_tfree);
973         (void)printf("%9u pages freed by daemon\n", sum.v_dfree);
974         (void)printf("%9u pages freed by exiting processes\n", sum.v_pfree);
975         (void)printf("%9u pages active\n", sum.v_active_count);
976         (void)printf("%9u pages inactive\n", sum.v_inactive_count);
977         (void)printf("%9u pages in VM cache\n", sum.v_cache_count);
978         (void)printf("%9u pages wired down\n", sum.v_wire_count);
979         (void)printf("%9u pages free\n", sum.v_free_count);
980         (void)printf("%9u bytes per page\n", sum.v_page_size);
981         if (kd != NULL) {
982                 kread(X_NCHSTATS, &lnchstats, sizeof(lnchstats));
983         } else {
984                 size_t size = sizeof(lnchstats);
985                 mysysctl("vfs.cache.nchstats", &lnchstats, &size, NULL, 0);
986                 if (size != sizeof(lnchstats))
987                         errx(1, "vfs.cache.nchstats size mismatch");
988         }
989         nchtotal = lnchstats.ncs_goodhits + lnchstats.ncs_neghits +
990             lnchstats.ncs_badhits + lnchstats.ncs_falsehits +
991             lnchstats.ncs_miss + lnchstats.ncs_long;
992         (void)printf("%9ld total name lookups\n", nchtotal);
993         (void)printf(
994             "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
995             "", PCT(lnchstats.ncs_goodhits, nchtotal),
996             PCT(lnchstats.ncs_neghits, nchtotal),
997             PCT(lnchstats.ncs_pass2, nchtotal));
998         (void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
999             PCT(lnchstats.ncs_badhits, nchtotal),
1000             PCT(lnchstats.ncs_falsehits, nchtotal),
1001             PCT(lnchstats.ncs_long, nchtotal));
1002 }
1003
1004 static void
1005 doforkst(void)
1006 {
1007         fill_vmmeter(&sum);
1008         (void)printf("%u forks, %u pages, average %.2f\n",
1009             sum.v_forks, sum.v_forkpages,
1010             sum.v_forks == 0 ? 0.0 :
1011             (double)sum.v_forkpages / sum.v_forks);
1012         (void)printf("%u vforks, %u pages, average %.2f\n",
1013             sum.v_vforks, sum.v_vforkpages,
1014             sum.v_vforks == 0 ? 0.0 :
1015             (double)sum.v_vforkpages / sum.v_vforks);
1016         (void)printf("%u rforks, %u pages, average %.2f\n",
1017             sum.v_rforks, sum.v_rforkpages,
1018             sum.v_rforks == 0 ? 0.0 :
1019             (double)sum.v_rforkpages / sum.v_rforks);
1020 }
1021
1022 static void
1023 devstats(void)
1024 {
1025         int dn, state;
1026         long double transfers_per_second;
1027         long double busy_seconds;
1028         long tmp;
1029
1030         for (state = 0; state < CPUSTATES; ++state) {
1031                 tmp = cur.cp_time[state];
1032                 cur.cp_time[state] -= last.cp_time[state];
1033                 last.cp_time[state] = tmp;
1034         }
1035
1036         busy_seconds = cur.snap_time - last.snap_time;
1037
1038         for (dn = 0; dn < num_devices; dn++) {
1039                 int di;
1040
1041                 if ((dev_select[dn].selected == 0)
1042                  || (dev_select[dn].selected > maxshowdevs))
1043                         continue;
1044
1045                 di = dev_select[dn].position;
1046
1047                 if (devstat_compute_statistics(&cur.dinfo->devices[di],
1048                     &last.dinfo->devices[di], busy_seconds,
1049                     DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
1050                     DSM_NONE) != 0)
1051                         errx(1, "%s", devstat_errbuf);
1052
1053                 (void)printf("%3.0Lf ", transfers_per_second);
1054         }
1055 }
1056
1057 static void
1058 percent(double pct, int *over)
1059 {
1060         char buf[10];
1061         int l;
1062
1063         l = snprintf(buf, sizeof(buf), "%.0f", pct);
1064         if (l == 1 && *over) {
1065                 printf("%s",  buf);
1066                 (*over)--;
1067         } else
1068                 printf("%2s", buf);
1069         if (l > 2)
1070                 (*over)++;
1071 }
1072
1073 static void
1074 cpustats(void)
1075 {
1076         int state, over;
1077         double lpct, total;
1078
1079         total = 0;
1080         for (state = 0; state < CPUSTATES; ++state)
1081                 total += cur.cp_time[state];
1082         if (total)
1083                 lpct = 100.0 / total;
1084         else
1085                 lpct = 0.0;
1086         over = 0;
1087         printf(" ");
1088         percent((cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * lpct, &over);
1089         printf(" ");
1090         percent((cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * lpct, &over);
1091         printf(" ");
1092         percent(cur.cp_time[CP_IDLE] * lpct, &over);
1093 }
1094
1095 static void
1096 pcpustats(int ncpus, u_long cpumask, int maxid)
1097 {
1098         int state, i;
1099         double lpct, total;
1100         long tmp;
1101         int over;
1102
1103         /* devstats does this for cp_time */
1104         for (i = 0; i <= maxid; i++) {
1105                 if ((cpumask & (1ul << i)) == 0)
1106                         continue;
1107                 for (state = 0; state < CPUSTATES; ++state) {
1108                         tmp = cur_cp_times[i * CPUSTATES + state];
1109                         cur_cp_times[i * CPUSTATES + state] -= last_cp_times[i * CPUSTATES + state];
1110                         last_cp_times[i * CPUSTATES + state] = tmp;
1111                 }
1112         }
1113
1114         over = 0;
1115         for (i = 0; i <= maxid; i++) {
1116                 if ((cpumask & (1ul << i)) == 0)
1117                         continue;
1118                 total = 0;
1119                 for (state = 0; state < CPUSTATES; ++state)
1120                         total += cur_cp_times[i * CPUSTATES + state];
1121                 if (total)
1122                         lpct = 100.0 / total;
1123                 else
1124                         lpct = 0.0;
1125                 printf(" ");
1126                 percent((cur_cp_times[i * CPUSTATES + CP_USER] +
1127                          cur_cp_times[i * CPUSTATES + CP_NICE]) * lpct, &over);
1128                 printf(" ");
1129                 percent((cur_cp_times[i * CPUSTATES + CP_SYS] +
1130                          cur_cp_times[i * CPUSTATES + CP_INTR]) * lpct, &over);
1131                 printf(" ");
1132                 percent(cur_cp_times[i * CPUSTATES + CP_IDLE] * lpct, &over);
1133         }
1134 }
1135
1136 static void
1137 dointr(void)
1138 {
1139         unsigned long *intrcnt, uptime;
1140         uint64_t inttotal;
1141         size_t clen, inamlen, intrcntlen, istrnamlen;
1142         unsigned int i, nintr;
1143         char *intrname, *tintrname;
1144
1145         uptime = getuptime();
1146         if (kd != NULL) {
1147                 intrcntlen = namelist[X_EINTRCNT].n_value -
1148                     namelist[X_INTRCNT].n_value;
1149                 inamlen = namelist[X_EINTRNAMES].n_value -
1150                     namelist[X_INTRNAMES].n_value;
1151                 if ((intrcnt = malloc(intrcntlen)) == NULL ||
1152                     (intrname = malloc(inamlen)) == NULL)
1153                         err(1, "malloc()");
1154                 kread(X_INTRCNT, intrcnt, intrcntlen);
1155                 kread(X_INTRNAMES, intrname, inamlen);
1156         } else {
1157                 for (intrcnt = NULL, intrcntlen = 1024; ; intrcntlen *= 2) {
1158                         if ((intrcnt = reallocf(intrcnt, intrcntlen)) == NULL)
1159                                 err(1, "reallocf()");
1160                         if (mysysctl("hw.intrcnt",
1161                             intrcnt, &intrcntlen, NULL, 0) == 0)
1162                                 break;
1163                 }
1164                 for (intrname = NULL, inamlen = 1024; ; inamlen *= 2) {
1165                         if ((intrname = reallocf(intrname, inamlen)) == NULL)
1166                                 err(1, "reallocf()");
1167                         if (mysysctl("hw.intrnames",
1168                             intrname, &inamlen, NULL, 0) == 0)
1169                                 break;
1170                 }
1171         }
1172         nintr = intrcntlen / sizeof(unsigned long);
1173         tintrname = intrname;
1174         istrnamlen = strlen("interrupt");
1175         for (i = 0; i < nintr; i++) {
1176                 clen = strlen(tintrname);
1177                 if (clen > istrnamlen)
1178                         istrnamlen = clen;
1179                 tintrname += clen + 1;
1180         }
1181         (void)printf("%-*s %20s %10s\n", istrnamlen, "interrupt", "total",
1182             "rate");
1183         inttotal = 0;
1184         for (i = 0; i < nintr; i++) {
1185                 if (intrname[0] != '\0' && (*intrcnt != 0 || aflag))
1186                         (void)printf("%-*s %20lu %10lu\n", istrnamlen, intrname,
1187                             *intrcnt, *intrcnt / uptime);
1188                 intrname += strlen(intrname) + 1;
1189                 inttotal += *intrcnt++;
1190         }
1191         (void)printf("%-*s %20llu %10llu\n", istrnamlen, "Total",
1192             (long long)inttotal, (long long)(inttotal / uptime));
1193 }
1194
1195 static void
1196 domemstat_malloc(void)
1197 {
1198         struct memory_type_list *mtlp;
1199         struct memory_type *mtp;
1200         int error, first, i;
1201
1202         mtlp = memstat_mtl_alloc();
1203         if (mtlp == NULL) {
1204                 warn("memstat_mtl_alloc");
1205                 return;
1206         }
1207         if (kd == NULL) {
1208                 if (memstat_sysctl_malloc(mtlp, 0) < 0) {
1209                         warnx("memstat_sysctl_malloc: %s",
1210                             memstat_strerror(memstat_mtl_geterror(mtlp)));
1211                         return;
1212                 }
1213         } else {
1214                 if (memstat_kvm_malloc(mtlp, kd) < 0) {
1215                         error = memstat_mtl_geterror(mtlp);
1216                         if (error == MEMSTAT_ERROR_KVM)
1217                                 warnx("memstat_kvm_malloc: %s",
1218                                     kvm_geterr(kd));
1219                         else
1220                                 warnx("memstat_kvm_malloc: %s",
1221                                     memstat_strerror(error));
1222                 }
1223         }
1224         printf("%13s %5s %6s %7s %8s  Size(s)\n", "Type", "InUse", "MemUse",
1225             "HighUse", "Requests");
1226         for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1227             mtp = memstat_mtl_next(mtp)) {
1228                 if (memstat_get_numallocs(mtp) == 0 &&
1229                     memstat_get_count(mtp) == 0)
1230                         continue;
1231                 printf("%13s %5lld %5lldK %7s %8lld  ",
1232                     memstat_get_name(mtp), memstat_get_count(mtp),
1233                     ((int64_t)memstat_get_bytes(mtp) + 1023) / 1024, "-",
1234                     memstat_get_numallocs(mtp));
1235                 first = 1;
1236                 for (i = 0; i < 32; i++) {
1237                         if (memstat_get_sizemask(mtp) & (1 << i)) {
1238                                 if (!first)
1239                                         printf(",");
1240                                 printf("%d", 1 << (i + 4));
1241                                 first = 0;
1242                         }
1243                 }
1244                 printf("\n");
1245         }
1246         memstat_mtl_free(mtlp);
1247 }
1248
1249 static void
1250 domemstat_zone(void)
1251 {
1252         struct memory_type_list *mtlp;
1253         struct memory_type *mtp;
1254         char name[MEMTYPE_MAXNAME + 1];
1255         int error;
1256
1257         mtlp = memstat_mtl_alloc();
1258         if (mtlp == NULL) {
1259                 warn("memstat_mtl_alloc");
1260                 return;
1261         }
1262         if (kd == NULL) {
1263                 if (memstat_sysctl_uma(mtlp, 0) < 0) {
1264                         warnx("memstat_sysctl_uma: %s",
1265                             memstat_strerror(memstat_mtl_geterror(mtlp)));
1266                         return;
1267                 }
1268         } else {
1269                 if (memstat_kvm_uma(mtlp, kd) < 0) {
1270                         error = memstat_mtl_geterror(mtlp);
1271                         if (error == MEMSTAT_ERROR_KVM)
1272                                 warnx("memstat_kvm_uma: %s",
1273                                     kvm_geterr(kd));
1274                         else
1275                                 warnx("memstat_kvm_uma: %s",
1276                                     memstat_strerror(error));
1277                 }
1278         }
1279         printf("%-20s %8s  %8s  %8s  %8s  %8s  %8s\n\n", "ITEM", "SIZE",
1280             "LIMIT", "USED", "FREE", "REQUESTS", "FAILURES");
1281         for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1282             mtp = memstat_mtl_next(mtp)) {
1283                 strlcpy(name, memstat_get_name(mtp), MEMTYPE_MAXNAME);
1284                 strcat(name, ":");
1285                 printf("%-20s %8llu, %8llu, %8llu, %8llu, %8llu, %8llu\n", name,
1286                     memstat_get_size(mtp), memstat_get_countlimit(mtp),
1287                     memstat_get_count(mtp), memstat_get_free(mtp),
1288                     memstat_get_numallocs(mtp), memstat_get_failures(mtp));
1289         }
1290         memstat_mtl_free(mtlp);
1291         printf("\n");
1292 }
1293
1294 /*
1295  * kread reads something from the kernel, given its nlist index.
1296  */
1297 static void
1298 kreado(int nlx, void *addr, size_t size, size_t offset)
1299 {
1300         const char *sym;
1301
1302         if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
1303                 sym = namelist[nlx].n_name;
1304                 if (*sym == '_')
1305                         ++sym;
1306                 errx(1, "symbol %s not defined", sym);
1307         }
1308         if ((size_t)kvm_read(kd, namelist[nlx].n_value + offset, addr,
1309             size) != size) {
1310                 sym = namelist[nlx].n_name;
1311                 if (*sym == '_')
1312                         ++sym;
1313                 errx(1, "%s: %s", sym, kvm_geterr(kd));
1314         }
1315 }
1316
1317 static void
1318 kread(int nlx, void *addr, size_t size)
1319 {
1320         kreado(nlx, addr, size, 0);
1321 }
1322
1323 static char *
1324 kgetstr(const char *strp)
1325 {
1326         int n = 0, size = 1;
1327         char *ret = NULL;
1328
1329         do {
1330                 if (size == n + 1) {
1331                         ret = realloc(ret, size);
1332                         if (ret == NULL)
1333                                 err(1, "%s: realloc", __func__);
1334                         size *= 2;
1335                 }
1336                 if (kvm_read(kd, (u_long)strp + n, &ret[n], 1) != 1)
1337                         errx(1, "%s: %s", __func__, kvm_geterr(kd));
1338         } while (ret[n++] != '\0');
1339         return (ret);
1340 }
1341
1342 static void
1343 usage(void)
1344 {
1345         (void)fprintf(stderr, "%s%s",
1346                 "usage: vmstat [-afHhimPsz] [-c count] [-M core [-N system]] [-w wait]\n",
1347                 "              [-n devs] [-p type,if,pass] [disks]\n");
1348         exit(1);
1349 }