]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - usr.sbin/pstat/pstat.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / usr.sbin / pstat / pstat.c
1 /*-
2  * Copyright (c) 1980, 1991, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 2002 Networks Associates Technologies, Inc.
5  * All rights reserved.
6  *
7  * Portions of this software were developed for the FreeBSD Project by
8  * ThinkSec AS and NAI Labs, the Security Research Division of Network
9  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
10  * ("CBOSS"), as part of the DARPA CHATS research program.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36
37 #if 0
38 #ifndef lint
39 static const char copyright[] =
40 "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
41         The Regents of the University of California.  All rights reserved.\n";
42 #endif /* not lint */
43
44 #ifndef lint
45 static char sccsid[] = "@(#)pstat.c     8.16 (Berkeley) 5/9/95";
46 #endif /* not lint */
47 #endif
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
50
51 #include <sys/param.h>
52 #include <sys/time.h>
53 #include <sys/file.h>
54 #include <sys/stat.h>
55 #include <sys/stdint.h>
56 #include <sys/ioctl.h>
57 #include <sys/tty.h>
58 #include <sys/blist.h>
59
60 #include <sys/sysctl.h>
61 #include <vm/vm_param.h>
62
63 #include <err.h>
64 #include <errno.h>
65 #include <fcntl.h>
66 #include <kvm.h>
67 #include <libutil.h>
68 #include <limits.h>
69 #include <nlist.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
74
75 enum {
76         NL_CONSTTY,
77         NL_MAXFILES,
78         NL_NFILES,
79         NL_TTY_LIST,
80         NL_MARKER
81 };
82
83 static struct {
84         int order;
85         const char *name;
86 } namelist[] = {
87         { NL_CONSTTY, "_constty" },
88         { NL_MAXFILES, "_maxfiles" },
89         { NL_NFILES, "_openfiles" },
90         { NL_TTY_LIST, "_tty_list" },
91         { NL_MARKER, "" },
92 };
93 #define NNAMES  (sizeof(namelist) / sizeof(*namelist))
94 static struct nlist nl[NNAMES];
95
96 static int      humanflag;
97 static int      usenumflag;
98 static int      totalflag;
99 static int      swapflag;
100 static char     *nlistf;
101 static char     *memf;
102 static kvm_t    *kd;
103
104 static const char *usagestr;
105
106 static void     filemode(void);
107 static int      getfiles(struct xfile **, size_t *);
108 static void     swapmode(void);
109 static void     ttymode(void);
110 static void     ttyprt(struct xtty *);
111 static void     usage(void);
112
113 int
114 main(int argc, char *argv[])
115 {
116         int ch, quit, ret;
117         int fileflag, ttyflag;
118         unsigned int i;
119         char buf[_POSIX2_LINE_MAX];
120         const char *opts;
121
122         fileflag = swapflag = ttyflag = 0;
123
124         /* We will behave like good old swapinfo if thus invoked */
125         opts = strrchr(argv[0], '/');
126         if (opts)
127                 opts++;
128         else
129                 opts = argv[0];
130         if (!strcmp(opts, "swapinfo")) {
131                 swapflag = 1;
132                 opts = "ghkmM:N:";
133                 usagestr = "swapinfo [-ghkm] [-M core [-N system]]";
134         } else {
135                 opts = "TM:N:fghkmnst";
136                 usagestr = "pstat [-Tfghkmnst] [-M core [-N system]]";
137         }
138
139         while ((ch = getopt(argc, argv, opts)) != -1)
140                 switch (ch) {
141                 case 'f':
142                         fileflag = 1;
143                         break;
144                 case 'g':
145                         setenv("BLOCKSIZE", "1G", 1);
146                         break;
147                 case 'h':
148                         humanflag = 1;
149                         break;
150                 case 'k':
151                         setenv("BLOCKSIZE", "1K", 1);
152                         break;
153                 case 'm':
154                         setenv("BLOCKSIZE", "1M", 1);
155                         break;
156                 case 'M':
157                         memf = optarg;
158                         break;
159                 case 'N':
160                         nlistf = optarg;
161                         break;
162                 case 'n':
163                         usenumflag = 1;
164                         break;
165                 case 's':
166                         ++swapflag;
167                         break;
168                 case 'T':
169                         totalflag = 1;
170                         break;
171                 case 't':
172                         ttyflag = 1;
173                         break;
174                 default:
175                         usage();
176                 }
177         argc -= optind;
178         argv += optind;
179
180         /*
181          * Initialize symbol names list.
182          */
183         for (i = 0; i < NNAMES; i++)
184                 nl[namelist[i].order].n_name = strdup(namelist[i].name);
185
186         if (memf != NULL) {
187                 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf);
188                 if (kd == NULL)
189                         errx(1, "kvm_openfiles: %s", buf);
190                 if ((ret = kvm_nlist(kd, nl)) != 0) {
191                         if (ret == -1)
192                                 errx(1, "kvm_nlist: %s", kvm_geterr(kd));
193                         quit = 0;
194                         for (i = 0; nl[i].n_name[0] != '\0'; ++i)
195                                 if (nl[i].n_value == 0) {
196                                         quit = 1;
197                                         warnx("undefined symbol: %s",
198                                             nl[i].n_name);
199                                 }
200                         if (quit)
201                                 exit(1);
202                 }
203         }
204         if (!(fileflag | ttyflag | swapflag | totalflag))
205                 usage();
206         if (fileflag || totalflag)
207                 filemode();
208         if (ttyflag)
209                 ttymode();
210         if (swapflag || totalflag)
211                 swapmode();
212         exit (0);
213 }
214
215 static void
216 usage(void)
217 {
218         fprintf(stderr, "usage: %s\n", usagestr);
219         exit (1);
220 }
221
222 static const char fhdr32[] =
223   "   LOC   TYPE   FLG  CNT MSG   DATA        OFFSET\n";
224 /* c0000000 ------ RWAI 123 123 c0000000 1000000000000000 */
225
226 static const char fhdr64[] =
227   "       LOC       TYPE   FLG  CNT MSG       DATA            OFFSET\n";
228 /* c000000000000000 ------ RWAI 123 123 c000000000000000 1000000000000000 */
229
230 static const char hdr[] =
231 "      LINE   INQ  CAN  LIN  LOW  OUTQ  USE  LOW   COL  SESS  PGID STATE\n";
232
233 static void
234 ttymode_kvm(void)
235 {
236         TAILQ_HEAD(, tty) tl;
237         struct tty *tp, tty;
238         struct xtty xt;
239
240         (void)printf("%s", hdr);
241         bzero(&xt, sizeof xt);
242         xt.xt_size = sizeof xt;
243         if (kvm_read(kd, nl[NL_TTY_LIST].n_value, &tl, sizeof tl) != sizeof tl)
244                 errx(1, "kvm_read(): %s", kvm_geterr(kd));
245         tp = TAILQ_FIRST(&tl);
246         while (tp != NULL) {
247                 if (kvm_read(kd, (u_long)tp, &tty, sizeof tty) != sizeof tty)
248                         errx(1, "kvm_read(): %s", kvm_geterr(kd));
249                 xt.xt_insize = tty.t_inq.ti_nblocks * TTYINQ_DATASIZE;
250                 xt.xt_incc = tty.t_inq.ti_linestart - tty.t_inq.ti_begin;
251                 xt.xt_inlc = tty.t_inq.ti_end - tty.t_inq.ti_linestart;
252                 xt.xt_inlow = tty.t_inlow;
253                 xt.xt_outsize = tty.t_outq.to_nblocks * TTYOUTQ_DATASIZE;
254                 xt.xt_outcc = tty.t_outq.to_end - tty.t_outq.to_begin;
255                 xt.xt_outlow = tty.t_outlow;
256                 xt.xt_column = tty.t_column;
257                 /* xt.xt_pgid = ... */
258                 /* xt.xt_sid = ... */
259                 xt.xt_flags = tty.t_flags;
260                 xt.xt_dev = NODEV;
261                 ttyprt(&xt);
262                 tp = TAILQ_NEXT(&tty, t_list);
263         }
264 }
265
266 static void
267 ttymode_sysctl(void)
268 {
269         struct xtty *xttys;
270         size_t len;
271         unsigned int i, n;
272
273         (void)printf("%s", hdr);
274         if ((xttys = malloc(len = sizeof(*xttys))) == NULL)
275                 err(1, "malloc()");
276         while (sysctlbyname("kern.ttys", xttys, &len, 0, 0) == -1) {
277                 if (errno != ENOMEM)
278                         err(1, "sysctlbyname()");
279                 len *= 2;
280                 if ((xttys = realloc(xttys, len)) == NULL)
281                         err(1, "realloc()");
282         }
283         n = len / sizeof(*xttys);
284         for (i = 0; i < n; i++)
285                 ttyprt(&xttys[i]);
286 }
287
288 static void
289 ttymode(void)
290 {
291
292         if (kd != NULL)
293                 ttymode_kvm();
294         else
295                 ttymode_sysctl();
296 }
297
298 static struct {
299         int flag;
300         char val;
301 } ttystates[] = {
302 #if 0
303         { TF_NOPREFIX,          'N' },
304 #endif
305         { TF_INITLOCK,          'I' },
306         { TF_CALLOUT,           'C' },
307
308         /* Keep these together -> 'Oi' and 'Oo'. */
309         { TF_OPENED,            'O' },
310         { TF_OPENED_IN,         'i' },
311         { TF_OPENED_OUT,        'o' },
312         { TF_OPENED_CONS,       'c' },
313
314         { TF_GONE,              'G' },
315         { TF_OPENCLOSE,         'B' },
316         { TF_ASYNC,             'Y' },
317         { TF_LITERAL,           'L' },
318
319         /* Keep these together -> 'Hi' and 'Ho'. */
320         { TF_HIWAT,             'H' },
321         { TF_HIWAT_IN,          'i' },
322         { TF_HIWAT_OUT,         'o' },
323
324         { TF_STOPPED,           'S' },
325         { TF_EXCLUDE,           'X' },
326         { TF_BYPASS,            'l' },
327         { TF_ZOMBIE,            'Z' },
328         { TF_HOOK,              's' },
329
330         /* Keep these together -> 'bi' and 'bo'. */
331         { TF_BUSY,              'b' },
332         { TF_BUSY_IN,           'i' },
333         { TF_BUSY_OUT,          'o' },
334
335         { 0,                    '\0'},
336 };
337
338 static void
339 ttyprt(struct xtty *xt)
340 {
341         int i, j;
342         char *name;
343
344         if (xt->xt_size != sizeof *xt)
345                 errx(1, "struct xtty size mismatch");
346         if (usenumflag || xt->xt_dev == 0 ||
347            (name = devname(xt->xt_dev, S_IFCHR)) == NULL)
348                 printf("%#10jx ", (uintmax_t)xt->xt_dev);
349         else
350                 printf("%10s ", name);
351         printf("%5zu %4zu %4zu %4zu %5zu %4zu %4zu %5u %5d %5d ",
352             xt->xt_insize, xt->xt_incc, xt->xt_inlc,
353             (xt->xt_insize - xt->xt_inlow), xt->xt_outsize,
354             xt->xt_outcc, (xt->xt_outsize - xt->xt_outlow),
355             MIN(xt->xt_column, 99999), xt->xt_sid, xt->xt_pgid);
356         for (i = j = 0; ttystates[i].flag; i++)
357                 if (xt->xt_flags & ttystates[i].flag) {
358                         putchar(ttystates[i].val);
359                         j++;
360                 }
361         if (j == 0)
362                 putchar('-');
363         putchar('\n');
364 }
365
366 static void
367 filemode(void)
368 {
369         struct xfile *fp, *buf;
370         char flagbuf[16], *fbp;
371         int maxf, openf;
372         size_t len;
373         static char const * const dtypes[] = { "???", "inode", "socket",
374             "pipe", "fifo", "kqueue", "crypto" };
375         int i;
376         int wid;
377
378         if (kd != NULL) {
379                 if (kvm_read(kd, nl[NL_MAXFILES].n_value,
380                         &maxf, sizeof maxf) != sizeof maxf ||
381                     kvm_read(kd, nl[NL_NFILES].n_value,
382                         &openf, sizeof openf) != sizeof openf)
383                         errx(1, "kvm_read(): %s", kvm_geterr(kd));
384         } else {
385                 len = sizeof(int);
386                 if (sysctlbyname("kern.maxfiles", &maxf, &len, 0, 0) == -1 ||
387                     sysctlbyname("kern.openfiles", &openf, &len, 0, 0) == -1)
388                         err(1, "sysctlbyname()");
389         }
390
391         if (totalflag) {
392                 (void)printf("%3d/%3d files\n", openf, maxf);
393                 return;
394         }
395         if (getfiles(&buf, &len) == -1)
396                 return;
397         openf = len / sizeof *fp;
398
399         (void)printf("%d/%d open files\n", openf, maxf);
400         printf(sizeof(uintptr_t) == 4 ? fhdr32 : fhdr64);
401         wid = (int)sizeof(uintptr_t) * 2;
402         for (fp = (struct xfile *)buf, i = 0; i < openf; ++fp, ++i) {
403                 if ((size_t)fp->xf_type >= sizeof(dtypes) / sizeof(dtypes[0]))
404                         continue;
405                 (void)printf("%*jx", wid, (uintmax_t)(uintptr_t)fp->xf_file);
406                 (void)printf(" %-6.6s", dtypes[fp->xf_type]);
407                 fbp = flagbuf;
408                 if (fp->xf_flag & FREAD)
409                         *fbp++ = 'R';
410                 if (fp->xf_flag & FWRITE)
411                         *fbp++ = 'W';
412                 if (fp->xf_flag & FAPPEND)
413                         *fbp++ = 'A';
414                 if (fp->xf_flag & FASYNC)
415                         *fbp++ = 'I';
416                 *fbp = '\0';
417                 (void)printf(" %4s %3d", flagbuf, fp->xf_count);
418                 (void)printf(" %3d", fp->xf_msgcount);
419                 (void)printf(" %*jx", wid, (uintmax_t)(uintptr_t)fp->xf_data);
420                 (void)printf(" %*jx\n", (int)sizeof(fp->xf_offset) * 2,
421                     (uintmax_t)fp->xf_offset);
422         }
423         free(buf);
424 }
425
426 static int
427 getfiles(struct xfile **abuf, size_t *alen)
428 {
429         struct xfile *buf;
430         size_t len;
431         int mib[2];
432
433         /*
434          * XXX
435          * Add emulation of KINFO_FILE here.
436          */
437         if (kd != NULL)
438                 errx(1, "files on dead kernel, not implemented");
439
440         mib[0] = CTL_KERN;
441         mib[1] = KERN_FILE;
442         if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1) {
443                 warn("sysctl: KERN_FILE");
444                 return (-1);
445         }
446         if ((buf = malloc(len)) == NULL)
447                 errx(1, "malloc");
448         if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
449                 warn("sysctl: KERN_FILE");
450                 return (-1);
451         }
452         *abuf = buf;
453         *alen = len;
454         return (0);
455 }
456
457 /*
458  * swapmode is based on a program called swapinfo written
459  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
460  */
461
462 #define CONVERT(v)      ((int64_t)(v) * pagesize / blocksize)
463 #define CONVERT_BLOCKS(v)       ((int64_t)(v) * pagesize)
464 static struct kvm_swap swtot;
465 static int nswdev;
466
467 static void
468 print_swap_header(void)
469 {
470         int hlen;
471         long blocksize;
472         const char *header;
473
474         header = getbsize(&hlen, &blocksize);
475         if (totalflag == 0)
476                 (void)printf("%-15s %*s %8s %8s %8s\n",
477                     "Device", hlen, header,
478                     "Used", "Avail", "Capacity");
479 }
480
481 static void
482 print_swap_line(const char *swdevname, intmax_t nblks, intmax_t bused,
483     intmax_t bavail, float bpercent)
484 {
485         char usedbuf[5];
486         char availbuf[5];
487         int hlen, pagesize;
488         long blocksize;
489
490         pagesize = getpagesize();
491         getbsize(&hlen, &blocksize);
492
493         printf("%-15s %*jd ", swdevname, hlen, CONVERT(nblks));
494         if (humanflag) {
495                 humanize_number(usedbuf, sizeof(usedbuf),
496                     CONVERT_BLOCKS(bused), "",
497                     HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
498                 humanize_number(availbuf, sizeof(availbuf),
499                     CONVERT_BLOCKS(bavail), "",
500                     HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
501                 printf("%8s %8s %5.0f%%\n", usedbuf, availbuf, bpercent);
502         } else {
503                 printf("%8jd %8jd %5.0f%%\n", (intmax_t)CONVERT(bused),
504                     (intmax_t)CONVERT(bavail), bpercent);
505         }
506 }
507
508 static void
509 print_swap(struct kvm_swap *ksw)
510 {
511
512         swtot.ksw_total += ksw->ksw_total;
513         swtot.ksw_used += ksw->ksw_used;
514         ++nswdev;
515         if (totalflag == 0)
516                 print_swap_line(ksw->ksw_devname, ksw->ksw_total,
517                     ksw->ksw_used, ksw->ksw_total - ksw->ksw_used,
518                     (ksw->ksw_used * 100.0) / ksw->ksw_total);
519 }
520
521 static void
522 print_swap_total(void)
523 {
524         int hlen, pagesize;
525         long blocksize;
526
527         pagesize = getpagesize();
528         getbsize(&hlen, &blocksize);
529         if (totalflag) {
530                 blocksize = 1024 * 1024;
531                 (void)printf("%jdM/%jdM swap space\n",
532                     CONVERT(swtot.ksw_used), CONVERT(swtot.ksw_total));
533         } else if (nswdev > 1) {
534                 print_swap_line("Total", swtot.ksw_total, swtot.ksw_used,
535                     swtot.ksw_total - swtot.ksw_used,
536                     (swtot.ksw_used * 100.0) / swtot.ksw_total);
537         }
538 }
539
540 static void
541 swapmode_kvm(void)
542 {
543         struct kvm_swap kswap[16];
544         int i, n;
545
546         n = kvm_getswapinfo(kd, kswap, sizeof kswap / sizeof kswap[0],
547             SWIF_DEV_PREFIX);
548
549         print_swap_header();
550         for (i = 0; i < n; ++i)
551                 print_swap(&kswap[i]);
552         print_swap_total();
553 }
554
555 static void
556 swapmode_sysctl(void)
557 {
558         struct kvm_swap ksw;
559         struct xswdev xsw;
560         size_t mibsize, size;
561         int mib[16], n;
562
563         print_swap_header();
564         mibsize = sizeof mib / sizeof mib[0];
565         if (sysctlnametomib("vm.swap_info", mib, &mibsize) == -1)
566                 err(1, "sysctlnametomib()");
567         for (n = 0; ; ++n) {
568                 mib[mibsize] = n;
569                 size = sizeof xsw;
570                 if (sysctl(mib, mibsize + 1, &xsw, &size, NULL, 0) == -1)
571                         break;
572                 if (xsw.xsw_version != XSWDEV_VERSION)
573                         errx(1, "xswdev version mismatch");
574                 if (xsw.xsw_dev == NODEV)
575                         snprintf(ksw.ksw_devname, sizeof ksw.ksw_devname,
576                             "<NFSfile>");
577                 else
578                         snprintf(ksw.ksw_devname, sizeof ksw.ksw_devname,
579                             "/dev/%s", devname(xsw.xsw_dev, S_IFCHR));
580                 ksw.ksw_used = xsw.xsw_used;
581                 ksw.ksw_total = xsw.xsw_nblks;
582                 ksw.ksw_flags = xsw.xsw_flags;
583                 print_swap(&ksw);
584         }
585         if (errno != ENOENT)
586                 err(1, "sysctl()");
587         print_swap_total();
588 }
589
590 static void
591 swapmode(void)
592 {
593         if (kd != NULL)
594                 swapmode_kvm();
595         else
596                 swapmode_sysctl();
597 }