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