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