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