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