Add new structures for exporting the cputime statistics via 64 bit counters
[dragonfly.git] / usr.bin / vmstat / vmstat.c
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1980, 1986, 1991, 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)vmstat.c 8.1 (Berkeley) 6/6/93
35  * $FreeBSD: src/usr.bin/vmstat/vmstat.c,v 1.38.2.4 2001/07/31 19:52:41 tmm Exp $
36  * $DragonFly: src/usr.bin/vmstat/vmstat.c,v 1.14 2004/12/22 11:01:49 joerg Exp $
37  */
38
39 #define _KERNEL_STRUCTURES
40
41 #include <sys/param.h>
42 #include <sys/time.h>
43 #include <sys/user.h>
44 #include <sys/uio.h>
45 #include <sys/namei.h>
46 #include <sys/malloc.h>
47 #include <sys/signal.h>
48 #include <sys/fcntl.h>
49 #include <sys/ioctl.h>
50 #include <sys/sysctl.h>
51 #include <sys/vmmeter.h>
52
53 #include <vm/vm_param.h>
54
55 #include <ctype.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <kinfo.h>
59 #include <kvm.h>
60 #include <limits.h>
61 #include <nlist.h>
62 #include <paths.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <sysexits.h>
67 #include <time.h>
68 #include <unistd.h>
69 #include <devstat.h>
70
71 static struct nlist namelist[] = {
72 #define X_BOOTTIME      0
73         { "_boottime" },
74 #define X_NCHSTATS      1
75         { "_nchstats" },
76 #define X_INTRNAMES     2
77         { "_intrnames" },
78 #define X_EINTRNAMES    3
79         { "_eintrnames" },
80 #define X_INTRCNT       4
81         { "_intrcnt" },
82 #define X_EINTRCNT      5
83         { "_eintrcnt" },
84 #define X_KMEMSTATISTICS        6
85         { "_kmemstatistics" },
86 #define X_ZLIST         7
87         { "_zlist" },
88 #ifdef notyet
89 #define X_DEFICIT       8
90         { "_deficit" },
91 #define X_FORKSTAT      9
92         { "_forkstat" },
93 #define X_REC           10
94         { "_rectime" },
95 #define X_PGIN          11
96         { "_pgintime" },
97 #define X_XSTATS        12
98         { "_xstats" },
99 #define X_END           13
100 #else
101 #define X_END           8
102 #endif
103         { "" },
104 };
105
106 struct statinfo cur, last;
107 int num_devices, maxshowdevs;
108 long generation;
109 struct device_selection *dev_select;
110 int num_selected;
111 struct devstat_match *matches;
112 int num_matches = 0;
113 int num_devices_specified, num_selections;
114 long select_generation;
115 char **specified_devices;
116 devstat_select_mode select_mode;
117
118 struct  vmmeter vmm, ovmm;
119 struct  vmstats vms, ovms;
120
121 int     winlines = 20;
122 int     nflag = 0;
123
124 kvm_t *kd;
125
126 struct kinfo_cputime cp_time, old_cp_time, diff_cp_time;
127
128 #define FORKSTAT        0x01
129 #define INTRSTAT        0x02
130 #define MEMSTAT         0x04
131 #define SUMSTAT         0x08
132 #define TIMESTAT        0x10
133 #define VMSTAT          0x20
134 #define ZMEMSTAT        0x40
135
136 void    cpustats(), dointr(), domem(), dosum(), dozmem();
137 void    dovmstat(), kread(), usage();
138 #ifdef notyet
139 void    dotimes(), doforkst();
140 #endif
141 void printhdr(void);
142 static void devstats();
143
144 int
145 main(int argc, char **argv)
146 {
147         int c, todo;
148         u_int interval;
149         int reps;
150         char *memf, *nlistf;
151         char errbuf[_POSIX2_LINE_MAX];
152
153         memf = nlistf = NULL;
154         interval = reps = todo = 0;
155         maxshowdevs = 2;
156         while ((c = getopt(argc, argv, "c:fiM:mN:n:p:stw:z")) != -1) {
157                 switch (c) {
158                 case 'c':
159                         reps = atoi(optarg);
160                         break;
161                 case 'f':
162 #ifdef notyet
163                         todo |= FORKSTAT;
164 #else
165                         errx(EX_USAGE, "sorry, -f is not (re)implemented yet");
166 #endif
167                         break;
168                 case 'i':
169                         todo |= INTRSTAT;
170                         break;
171                 case 'M':
172                         memf = optarg;
173                         break;
174                 case 'm':
175                         todo |= MEMSTAT;
176                         break;
177                 case 'N':
178                         nlistf = optarg;
179                         break;
180                 case 'n':
181                         nflag = 1;
182                         maxshowdevs = atoi(optarg);
183                         if (maxshowdevs < 0)
184                                 errx(1, "number of devices %d is < 0",
185                                      maxshowdevs);
186                         break;
187                 case 'p':
188                         if (buildmatch(optarg, &matches, &num_matches) != 0)
189                                 errx(1, "%s", devstat_errbuf);
190                         break;
191                 case 's':
192                         todo |= SUMSTAT;
193                         break;
194                 case 't':
195 #ifdef notyet
196                         todo |= TIMESTAT;
197 #else
198                         errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
199 #endif
200                         break;
201                 case 'w':
202                         interval = atoi(optarg);
203                         break;
204                 case 'z':
205                         todo |= ZMEMSTAT;
206                         break;
207                 case '?':
208                 default:
209                         usage();
210                 }
211         }
212         argc -= optind;
213         argv += optind;
214
215         if (todo == 0)
216                 todo = VMSTAT;
217
218         /*
219          * Discard setgid privileges if not the running kernel so that bad
220          * guys can't print interesting stuff from kernel memory.
221          */
222         if (nlistf != NULL || memf != NULL)
223                 setgid(getgid());
224
225         kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
226         if (kd == 0) 
227                 errx(1, "kvm_openfiles: %s", errbuf);
228
229         if ((c = kvm_nlist(kd, namelist)) != 0) {
230                 if (c > 0) {
231                         warnx("undefined symbols:");
232                         for (c = 0;
233                             c < sizeof(namelist)/sizeof(namelist[0]); c++)
234                                 if (namelist[c].n_type == 0)
235                                         fprintf(stderr, " %s",
236                                             namelist[c].n_name);
237                         fputc('\n', stderr);
238                 } else
239                         warnx("kvm_nlist: %s", kvm_geterr(kd));
240                 exit(1);
241         }
242
243         if (todo & VMSTAT) {
244                 char **getdrivedata();
245                 struct winsize winsize;
246
247                 /*
248                  * Make sure that the userland devstat version matches the
249                  * kernel devstat version.  If not, exit and print a
250                  * message informing the user of his mistake.
251                  */
252                 if (checkversion() < 0)
253                         errx(1, "%s", devstat_errbuf);
254
255
256                 argv = getdrivedata(argv);
257                 winsize.ws_row = 0;
258                 ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
259                 if (winsize.ws_row > 0)
260                         winlines = winsize.ws_row;
261
262         }
263
264 #define BACKWARD_COMPATIBILITY
265 #ifdef  BACKWARD_COMPATIBILITY
266         if (*argv) {
267                 interval = atoi(*argv);
268                 if (*++argv)
269                         reps = atoi(*argv);
270         }
271 #endif
272
273         if (interval) {
274                 if (!reps)
275                         reps = -1;
276         } else if (reps)
277                 interval = 1;
278
279 #ifdef notyet
280         if (todo & FORKSTAT)
281                 doforkst();
282 #endif
283         if (todo & MEMSTAT)
284                 domem();
285         if (todo & ZMEMSTAT)
286                 dozmem();
287         if (todo & SUMSTAT)
288                 dosum();
289 #ifdef notyet
290         if (todo & TIMESTAT)
291                 dotimes();
292 #endif
293         if (todo & INTRSTAT)
294                 dointr();
295         if (todo & VMSTAT)
296                 dovmstat(interval, reps);
297         exit(0);
298 }
299
300 char **
301 getdrivedata(char **argv)
302 {
303         if ((num_devices = getnumdevs()) < 0)
304                 errx(1, "%s", devstat_errbuf);
305
306         cur.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
307         last.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
308         bzero(cur.dinfo, sizeof(struct devinfo));
309         bzero(last.dinfo, sizeof(struct devinfo));
310
311         if (getdevs(&cur) == -1)
312                 errx(1, "%s", devstat_errbuf);
313
314         num_devices = cur.dinfo->numdevs;
315         generation = cur.dinfo->generation;
316
317         specified_devices = (char **)malloc(sizeof(char *));
318         for (num_devices_specified = 0; *argv; ++argv) {
319                 if (isdigit(**argv))
320                         break;
321                 num_devices_specified++;
322                 specified_devices = (char **)realloc(specified_devices,
323                                                      sizeof(char *) *
324                                                      num_devices_specified);
325                 specified_devices[num_devices_specified - 1] = *argv;
326         }
327         dev_select = NULL;
328
329         if (nflag == 0 && maxshowdevs < num_devices_specified)
330                         maxshowdevs = num_devices_specified;
331
332         /*
333          * People are generally only interested in disk statistics when
334          * they're running vmstat.  So, that's what we're going to give
335          * them if they don't specify anything by default.  We'll also give
336          * them any other random devices in the system so that we get to
337          * maxshowdevs devices, if that many devices exist.  If the user
338          * specifies devices on the command line, either through a pattern
339          * match or by naming them explicitly, we will give the user only
340          * those devices.
341          */
342         if ((num_devices_specified == 0) && (num_matches == 0)) {
343                 if (buildmatch("da", &matches, &num_matches) != 0)
344                         errx(1, "%s", devstat_errbuf);
345
346                 select_mode = DS_SELECT_ADD;
347         } else
348                 select_mode = DS_SELECT_ONLY;
349
350         /*
351          * At this point, selectdevs will almost surely indicate that the
352          * device list has changed, so we don't look for return values of 0
353          * or 1.  If we get back -1, though, there is an error.
354          */
355         if (selectdevs(&dev_select, &num_selected, &num_selections,
356                        &select_generation, generation, cur.dinfo->devices,
357                        num_devices, matches, num_matches, specified_devices,
358                        num_devices_specified, select_mode,
359                        maxshowdevs, 0) == -1)
360                 errx(1, "%s", devstat_errbuf);
361
362         return(argv);
363 }
364
365 long
366 getuptime(void)
367 {
368         static time_t now, boottime;
369         time_t uptime;
370
371         if (boottime == 0)
372                 kread(X_BOOTTIME, &boottime, sizeof(boottime));
373         time(&now);
374         uptime = now - boottime;
375         if (uptime <= 0 || uptime > 60*60*24*365*10)
376                 errx(1, "time makes no sense; namelist must be wrong");
377         return(uptime);
378 }
379
380 int     hdrcnt;
381
382 void
383 dovmstat(u_int interval, int reps)
384 {
385         struct vmtotal total;
386         time_t uptime, halfuptime;
387         struct devinfo *tmp_dinfo;
388         void needhdr();
389         int vmm_size = sizeof(vmm);
390         int vms_size = sizeof(vms);
391         int vmt_size = sizeof(total);
392
393         uptime = getuptime();
394         halfuptime = uptime / 2;
395         signal(SIGCONT, needhdr);
396
397         for (hdrcnt = 1;;) {
398                 if (!--hdrcnt)
399                         printhdr();
400                 if (kinfo_get_sched_cputime(&cp_time))
401                         err(1, "kinfo_get_sched_cputime");
402
403                 tmp_dinfo = last.dinfo;
404                 last.dinfo = cur.dinfo;
405                 cur.dinfo = tmp_dinfo;
406                 last.busy_time = cur.busy_time;
407
408                 /*
409                  * Here what we want to do is refresh our device stats.
410                  * getdevs() returns 1 when the device list has changed.
411                  * If the device list has changed, we want to go through
412                  * the selection process again, in case a device that we
413                  * were previously displaying has gone away.
414                  */
415                 switch (getdevs(&cur)) {
416                 case -1:
417                         errx(1, "%s", devstat_errbuf);
418                         break;
419                 case 1: {
420                         int retval;
421
422                         num_devices = cur.dinfo->numdevs;
423                         generation = cur.dinfo->generation;
424
425                         retval = selectdevs(&dev_select, &num_selected,
426                                             &num_selections, &select_generation,
427                                             generation, cur.dinfo->devices,
428                                             num_devices, matches, num_matches,
429                                             specified_devices,
430                                             num_devices_specified, select_mode,
431                                             maxshowdevs, 0);
432                         switch (retval) {
433                         case -1:
434                                 errx(1, "%s", devstat_errbuf);
435                                 break;
436                         case 1:
437                                 printhdr();
438                                 break;
439                         default:
440                                 break;
441                         }
442                 }
443                 default:
444                         break;
445                 }
446
447                 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
448                         perror("sysctlbyname: vm.vmstats");
449                         exit(1);
450                 }
451                 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
452                         perror("sysctlbyname: vm.vmmeter");
453                         exit(1);
454                 } 
455                 if (sysctlbyname("vm.vmtotal", &total, &vmt_size, NULL, 0)) {
456                         perror("sysctlbyname: vm.vmtotal");
457                         exit(1);
458                 } 
459                 printf("%2d %1d %1d",
460                     total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
461 #define vmstat_pgtok(a) ((a) * vms.v_page_size >> 10)
462 #define rate(x) (((x) + halfuptime) / uptime)   /* round */
463                 printf(" %7ld %6ld ",
464                     (long)vmstat_pgtok(total.t_avm), (long)vmstat_pgtok(total.t_free));
465                 printf("%4lu ",
466                     (u_long)rate(vmm.v_vm_faults - ovmm.v_vm_faults));
467                 printf("%3lu ",
468                     (u_long)rate(vmm.v_reactivated - ovmm.v_reactivated));
469                 printf("%3lu ",
470                     (u_long)rate(vmm.v_swapin + vmm.v_vnodein -
471                     (ovmm.v_swapin + ovmm.v_vnodein)));
472                 printf("%3lu ",
473                     (u_long)rate(vmm.v_swapout + vmm.v_vnodeout -
474                     (ovmm.v_swapout + ovmm.v_vnodeout)));
475                 printf("%3lu ",
476                     (u_long)rate(vmm.v_tfree - ovmm.v_tfree));
477                 printf("%3lu ",
478                     (u_long)rate(vmm.v_pdpages - ovmm.v_pdpages));
479                 devstats();
480                 printf("%4lu %4lu %3lu ",
481                     (u_long)rate(vmm.v_intr - ovmm.v_intr),
482                     (u_long)rate(vmm.v_syscall - ovmm.v_syscall),
483                     (u_long)rate(vmm.v_swtch - ovmm.v_swtch));
484                 cpustats();
485                 printf("\n");
486                 fflush(stdout);
487                 if (reps >= 0 && --reps <= 0)
488                         break;
489                 ovmm = vmm;
490                 uptime = interval;
491                 /*
492                  * We round upward to avoid losing low-frequency events
493                  * (i.e., >= 1 per interval but < 1 per second).
494                  */
495                 if (interval != 1)
496                         halfuptime = (uptime + 1) / 2;
497                 else
498                         halfuptime = 0;
499                 sleep(interval);
500         }
501 }
502
503 void
504 printhdr(void)
505 {
506         int i, num_shown;
507
508         num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
509         printf(" procs      memory      page%*s", 19, "");
510         if (num_shown > 1)
511                 printf(" disks %*s", num_shown * 4 - 7, "");
512         else if (num_shown == 1)
513                 printf("disk");
514         printf("   faults      cpu\n");
515         printf(" r b w     avm    fre  flt  re  pi  po  fr  sr ");
516         for (i = 0; i < num_devices; i++)
517                 if ((dev_select[i].selected)
518                  && (dev_select[i].selected <= maxshowdevs))
519                         printf("%c%c%d ", dev_select[i].device_name[0],
520                                      dev_select[i].device_name[1],
521                                      dev_select[i].unit_number);
522         printf("  in   sy  cs us sy id\n");
523         hdrcnt = winlines - 2;
524 }
525
526 /*
527  * Force a header to be prepended to the next output.
528  */
529 void
530 needhdr(void)
531 {
532
533         hdrcnt = 1;
534 }
535
536 long
537 pct(long top, long bot)
538 {
539         long ans;
540
541         if (bot == 0)
542                 return(0);
543         ans = (quad_t)top * 100 / bot;
544         return (ans);
545 }
546
547 #define PCT(top, bot) pct((long)(top), (long)(bot))
548
549 void
550 dosum(void)
551 {
552         struct nchstats *nch_tmp, nchstats;
553         int vms_size = sizeof(vms);
554         int vmm_size = sizeof(vmm);
555         int cpucnt;
556         u_long nchtotal;
557         size_t nch_size = sizeof(struct nchstats) * SMP_MAXCPU;
558
559         if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
560                 perror("sysctlbyname: vm.vmstats");
561                 exit(1);
562         }
563         if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
564                 perror("sysctlbyname: vm.vmstats");
565                 exit(1);
566         }
567         printf("%9u cpu context switches\n", vmm.v_swtch);
568         printf("%9u device interrupts\n", vmm.v_intr);
569         printf("%9u software interrupts\n", vmm.v_soft);
570         printf("%9u traps\n", vmm.v_trap);
571         printf("%9u system calls\n", vmm.v_syscall);
572         printf("%9u kernel threads created\n", vmm.v_kthreads);
573         printf("%9u  fork() calls\n", vmm.v_forks);
574         printf("%9u vfork() calls\n", vmm.v_vforks);
575         printf("%9u rfork() calls\n", vmm.v_rforks);
576         printf("%9u exec() calls\n", vmm.v_exec);
577         printf("%9u swap pager pageins\n", vmm.v_swapin);
578         printf("%9u swap pager pages paged in\n", vmm.v_swappgsin);
579         printf("%9u swap pager pageouts\n", vmm.v_swapout);
580         printf("%9u swap pager pages paged out\n", vmm.v_swappgsout);
581         printf("%9u vnode pager pageins\n", vmm.v_vnodein);
582         printf("%9u vnode pager pages paged in\n", vmm.v_vnodepgsin);
583         printf("%9u vnode pager pageouts\n", vmm.v_vnodeout);
584         printf("%9u vnode pager pages paged out\n", vmm.v_vnodepgsout);
585         printf("%9u page daemon wakeups\n", vmm.v_pdwakeups);
586         printf("%9u pages examined by the page daemon\n", vmm.v_pdpages);
587         printf("%9u pages reactivated\n", vmm.v_reactivated);
588         printf("%9u copy-on-write faults\n", vmm.v_cow_faults);
589         printf("%9u copy-on-write optimized faults\n", vmm.v_cow_optim);
590         printf("%9u zero fill pages zeroed\n", vmm.v_zfod);
591         printf("%9u zero fill pages prezeroed\n", vmm.v_ozfod);
592         printf("%9u intransit blocking page faults\n", vmm.v_intrans);
593         printf("%9u total VM faults taken\n", vmm.v_vm_faults);
594         printf("%9u pages affected by kernel thread creation\n", vmm.v_kthreadpages);
595         printf("%9u pages affected by  fork()\n", vmm.v_forkpages);
596         printf("%9u pages affected by vfork()\n", vmm.v_vforkpages);
597         printf("%9u pages affected by rfork()\n", vmm.v_rforkpages);
598         printf("%9u pages freed\n", vmm.v_tfree);
599         printf("%9u pages freed by daemon\n", vmm.v_dfree);
600         printf("%9u pages freed by exiting processes\n", vmm.v_pfree);
601         printf("%9u pages active\n", vms.v_active_count);
602         printf("%9u pages inactive\n", vms.v_inactive_count);
603         printf("%9u pages in VM cache\n", vms.v_cache_count);
604         printf("%9u pages wired down\n", vms.v_wire_count);
605         printf("%9u pages free\n", vms.v_free_count);
606         printf("%9u bytes per page\n", vms.v_page_size);
607         
608         if ((nch_tmp = malloc(nch_size)) == NULL) {
609                 perror("malloc");
610                 exit(1);
611         } else {
612                 if (sysctlbyname("vfs.cache.nchstats", nch_tmp, &nch_size, NULL, 0)) {
613                         perror("sysctlbyname vfs.cache.nchstats");
614                         free(nch_tmp);
615                         exit(1);
616                 } else {
617                         if ((nch_tmp = realloc(nch_tmp, nch_size)) == NULL) {
618                                 perror("realloc");
619                                 exit(1);
620                         }
621                 }
622         }
623         
624         cpucnt = nch_size / sizeof(struct nchstats);
625         kvm_nch_cpuagg(nch_tmp, &nchstats, cpucnt);
626
627         nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
628             nchstats.ncs_badhits + nchstats.ncs_falsehits +
629             nchstats.ncs_miss + nchstats.ncs_long;
630         printf("%9ld total name lookups\n", nchtotal);
631         printf(
632             "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
633             "", PCT(nchstats.ncs_goodhits, nchtotal),
634             PCT(nchstats.ncs_neghits, nchtotal),
635             PCT(nchstats.ncs_pass2, nchtotal));
636         printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
637             PCT(nchstats.ncs_badhits, nchtotal),
638             PCT(nchstats.ncs_falsehits, nchtotal),
639             PCT(nchstats.ncs_long, nchtotal));
640         free(nch_tmp);
641 }
642
643 #ifdef notyet
644 void
645 doforkst(void)
646 {
647         struct forkstat fks;
648
649         kread(X_FORKSTAT, &fks, sizeof(struct forkstat));
650         printf("%d forks, %d pages, average %.2f\n",
651             fks.cntfork, fks.sizfork, (double)fks.sizfork / fks.cntfork);
652         printf("%d vforks, %d pages, average %.2f\n",
653             fks.cntvfork, fks.sizvfork, (double)fks.sizvfork / fks.cntvfork);
654 }
655 #endif
656
657 static void
658 devstats(void)
659 {
660         int dn, state;
661         long double transfers_per_second;
662         long double busy_seconds;
663         long tmp;
664
665         diff_cp_time.cp_user = cp_time.cp_user - old_cp_time.cp_user;
666         diff_cp_time.cp_nice = cp_time.cp_nice - old_cp_time.cp_nice;
667         diff_cp_time.cp_sys = cp_time.cp_sys - old_cp_time.cp_sys;
668         diff_cp_time.cp_intr = cp_time.cp_intr - old_cp_time.cp_intr;
669         diff_cp_time.cp_idle = cp_time.cp_idle - old_cp_time.cp_idle;
670         old_cp_time = cp_time;
671
672         busy_seconds = compute_etime(cur.busy_time, last.busy_time);
673
674         for (dn = 0; dn < num_devices; dn++) {
675                 int di;
676
677                 if ((dev_select[dn].selected == 0)
678                  || (dev_select[dn].selected > maxshowdevs))
679                         continue;
680
681                 di = dev_select[dn].position;
682
683                 if (compute_stats(&cur.dinfo->devices[di],
684                                   &last.dinfo->devices[di], busy_seconds,
685                                   NULL, NULL, NULL,
686                                   NULL, &transfers_per_second, NULL,
687                                   NULL, NULL) != 0)
688                         errx(1, "%s", devstat_errbuf);
689
690                 printf("%3.0Lf ", transfers_per_second);
691         }
692 }
693
694 void
695 cpustats(void)
696 {
697         uint64_t total;
698         double pct;
699
700         total = diff_cp_time.cp_user + diff_cp_time.cp_nice +
701             diff_cp_time.cp_sys + diff_cp_time.cp_intr + diff_cp_time.cp_idle;
702
703         if (total)
704                 pct = 100.0 / total;
705         else
706                 pct = 0;
707         printf("%2.0f ", (diff_cp_time.cp_user + diff_cp_time.cp_nice) * pct);
708         printf("%2.0f ", (diff_cp_time.cp_sys + diff_cp_time.cp_intr) * pct);
709         printf("%2.0f", diff_cp_time.cp_idle * pct);
710 }
711
712 void
713 dointr(void)
714 {
715         u_long *intrcnt, uptime;
716         u_int64_t inttotal;
717         int nintr, inamlen;
718         char *intrname;
719
720         uptime = getuptime();
721         nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
722         inamlen =
723             namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
724         intrcnt = malloc((size_t)nintr);
725         intrname = malloc((size_t)inamlen);
726         if (intrcnt == NULL || intrname == NULL)
727                 errx(1, "malloc");
728         kread(X_INTRCNT, intrcnt, (size_t)nintr);
729         kread(X_INTRNAMES, intrname, (size_t)inamlen);
730         printf("interrupt                   total       rate\n");
731         inttotal = 0;
732         nintr /= sizeof(long);
733         while (--nintr >= 0) {
734                 if (intrname[0] || *intrcnt) {
735                     printf("%-12s %20lu %10lu\n", intrname,
736                             *intrcnt, *intrcnt / uptime);
737                 }
738                 intrname += strlen(intrname) + 1;
739                 inttotal += *intrcnt++;
740         }
741         printf("Total        %20llu %10llu\n", inttotal,
742                         inttotal / (u_int64_t) uptime);
743 }
744
745 #define MAX_KMSTATS     200
746
747 static
748 long
749 cpuagg(long *ary)
750 {
751     int i;
752     long ttl;
753
754     for (i = ttl = 0; i < SMP_MAXCPU; ++i)
755         ttl += ary[i];
756     return(ttl);
757 }
758
759 void
760 domem(void)
761 {
762         struct malloc_type *ks;
763         int i, j;
764         int first, nkms;
765         long totuse = 0, totfree = 0, totreq = 0;
766         struct malloc_type kmemstats[MAX_KMSTATS], *kmsp;
767         char buf[1024];
768
769         kread(X_KMEMSTATISTICS, &kmsp, sizeof(kmsp));
770         for (nkms = 0; nkms < MAX_KMSTATS && kmsp != NULL; nkms++) {
771                 if (sizeof(kmemstats[0]) != kvm_read(kd, (u_long)kmsp,
772                     &kmemstats[nkms], sizeof(kmemstats[0])))
773                         err(1, "kvm_read(%p)", (void *)kmsp);
774                 if (sizeof(buf) !=  kvm_read(kd, 
775                     (u_long)kmemstats[nkms].ks_shortdesc, buf, sizeof(buf)))
776                         err(1, "kvm_read(%p)", 
777                             (void *)kmemstats[nkms].ks_shortdesc);
778                 buf[sizeof(buf) - 1] = '\0';
779                 kmemstats[nkms].ks_shortdesc = strdup(buf);
780                 kmsp = kmemstats[nkms].ks_next;
781         }
782         if (kmsp != NULL)
783                 warnx("truncated to the first %d memory types", nkms);
784
785         printf(
786             "\nMemory statistics by type                          Type  Kern\n");
787         printf(
788 "        Type  InUse MemUse HighUse  Limit Requests Limit Limit Size(s)\n");
789         for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
790                 if (ks->ks_calls == 0)
791                         continue;
792                 printf("%13s%6ld%6ldK%7ldK%6ldK%9lld%5u%6u",
793                     ks->ks_shortdesc,
794                     cpuagg(ks->ks_inuse), (cpuagg(ks->ks_memuse) + 1023) / 1024,
795                     (ks->ks_maxused + 1023) / 1024,
796                     (ks->ks_limit + 1023) / 1024, ks->ks_calls,
797                     ks->ks_limblocks, ks->ks_mapblocks);
798                 first = 1;
799                 for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
800                         if ((ks->ks_size & j) == 0)
801                                 continue;
802                         if (first)
803                                 printf("  ");
804                         else
805                                 printf(",");
806                         if(j<1024)
807                                 printf("%d",j);
808                         else
809                                 printf("%dK",j>>10);
810                         first = 0;
811                 }
812                 printf("\n");
813                 totuse += cpuagg(ks->ks_memuse);
814                 totreq += ks->ks_calls;
815         }
816         printf("\nMemory Totals:  In Use    Free    Requests\n");
817         printf("              %7ldK %6ldK    %8ld\n",
818              (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
819 }
820
821 void
822 dozmem(void)
823 {
824         char *buf;
825         size_t bufsize;
826
827         buf = NULL;
828         bufsize = 1024;
829         for (;;) {
830                 if ((buf = realloc(buf, bufsize)) == NULL)
831                         err(1, "realloc()");
832                 if (sysctlbyname("vm.zone", buf, &bufsize, 0, NULL) == 0)
833                         break;
834                 if (errno != ENOMEM)
835                         err(1, "sysctl()");
836                 bufsize *= 2;
837         }
838         buf[bufsize] = '\0'; /* play it safe */
839         printf("%s\n\n", buf);
840         free(buf);
841 }
842
843 /*
844  * kread reads something from the kernel, given its nlist index.
845  */
846 void
847 kread(int nlx, void *addr, size_t size)
848 {
849         const char *sym;
850
851         if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
852                 sym = namelist[nlx].n_name;
853                 if (*sym == '_')
854                         ++sym;
855                 errx(1, "symbol %s not defined", sym);
856         }
857         if (kvm_read(kd, namelist[nlx].n_value, addr, size) != size) {
858                 sym = namelist[nlx].n_name;
859                 if (*sym == '_')
860                         ++sym;
861                 errx(1, "%s: %s", sym, kvm_geterr(kd));
862         }
863 }
864
865 void
866 usage(void)
867 {
868         fprintf(stderr, "%s%s",
869                 "usage: vmstat [-imsz] [-c count] [-M core] [-N system] [-w wait]\n",
870                 "              [-n devs] [disks]\n");
871         exit(1);
872 }