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