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