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