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