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