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