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