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