xref: /dragonfly/usr.sbin/pstat/pstat.c (revision 346b9dadb592a2194dd69cfeaa20cd1808df547d)
1 /*-
2  * Copyright (c) 1980, 1991, 1993, 1994
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. 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  * @(#) Copyright (c) 1980, 1991, 1993, 1994 The Regents of the University of California.  All rights reserved.
30  * @(#)pstat.c      8.16 (Berkeley) 5/9/95
31  * $FreeBSD: src/usr.sbin/pstat/pstat.c,v 1.49.2.5 2002/07/12 09:12:49 des Exp $
32  */
33 
34 #include <sys/user.h>
35 #include <sys/kinfo.h>
36 #include <sys/param.h>
37 #include <sys/time.h>
38 #include <sys/vnode.h>
39 #include <sys/ucred.h>
40 #include <sys/file.h>
41 #include <vfs/ufs/quota.h>
42 #include <vfs/ufs/inode.h>
43 #include <sys/mount.h>
44 #include <sys/uio.h>
45 #include <sys/namei.h>
46 #include <sys/stat.h>
47 #include <vfs/nfs/rpcv2.h>
48 #include <vfs/nfs/nfsproto.h>
49 #include <vfs/nfs/nfs.h>
50 #include <vfs/nfs/nfsnode.h>
51 #include <sys/ioctl.h>
52 #include <sys/tty.h>
53 #include <sys/conf.h>
54 #include <sys/blist.h>
55 
56 #include <sys/sysctl.h>
57 
58 #include <err.h>
59 #include <fcntl.h>
60 #include <kvm.h>
61 #include <limits.h>
62 #include <nlist.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 #include <libutil.h>
68 
69 #ifdef USE_KCORE
70 #  define KCORE_KINFO_WRAPPER
71 #  include <kcore.h>
72 #else
73 #  include <kinfo.h>
74 #endif
75 
76 /*
77  * Backoff to DECIMAL mode if humanize_number does not have FRACTIONAL mode.
78  */
79 #ifndef HN_FRACTIONAL
80 #define HN_FRACTIONAL         HN_DECIMAL
81 #endif
82 
83 enum {
84           NL_MOUNTLIST,
85           NL_NUMVNODES,
86           NL_RC_TTY,
87           NL_NRC_TTY,
88           NL_CY_TTY,
89           NL_NCY_TTY,
90           NL_SI_TTY,
91           NL_SI_NPORTS,
92 };
93 
94 const size_t NL_LAST_MANDATORY = NL_NUMVNODES;
95 
96 struct nlist nl[] = {
97           { "_mountlist", 0, 0, 0, 0 }, /* address of head of mount list. */
98           { "_numvnodes", 0, 0, 0, 0 },
99           { "_rc_tty", 0, 0, 0, 0 },
100           { "_nrc_tty", 0, 0, 0, 0 },
101           { "_cy_tty", 0, 0, 0, 0 },
102           { "_ncy_tty", 0, 0, 0, 0 },
103           { "_si__tty", 0, 0, 0, 0 },
104           { "_si_Nports", 0, 0, 0, 0 },
105           { "", 0, 0, 0, 0 }
106 };
107 
108 int       usenumflag;
109 int       totalflag;
110 int       swapflag;
111 int       humanflag;
112 long      pagesize;
113 long      blocksize;
114 char      *nlistf   = NULL;
115 char      *memf     = NULL;
116 kvm_t     *kd;
117 
118 const char          *usagestr;
119 
120 struct {
121           int m_flag;
122           const char *m_name;
123 } mnt_flags[] = {
124           { MNT_RDONLY, "rdonly" },
125           { MNT_SYNCHRONOUS, "sync" },
126           { MNT_NOEXEC, "noexec" },
127           { MNT_NOSUID, "nosuid" },
128           { MNT_NODEV, "nodev" },
129           { MNT_ASYNC, "async" },
130           { MNT_SUIDDIR, "suiddir" },
131           { MNT_SOFTDEP, "softdep" },
132           { MNT_NOSYMFOLLOW, "nosymfollow" },
133           { MNT_NOATIME, "noatime" },
134           { MNT_NOCLUSTERR, "noclusterread" },
135           { MNT_NOCLUSTERW, "noclusterwrite" },
136           { MNT_EXRDONLY, "exrdonly" },
137           { MNT_EXPORTED, "exported" },
138           { MNT_DEFEXPORTED, "defexported" },
139           { MNT_EXPORTANON, "exportanon" },
140           { MNT_EXKERB, "exkerb" },
141           { MNT_EXPUBLIC, "public" },
142           { MNT_LOCAL, "local" },
143           { MNT_QUOTA, "quota" },
144           { MNT_ROOTFS, "rootfs" },
145           { MNT_USER, "user" },
146           { MNT_IGNORE, "ignore" },
147           { MNT_UPDATE, "update" },
148           { MNT_DELEXPORT, "delexport" },
149           { MNT_RELOAD, "reload" },
150           { MNT_FORCE, "force" },
151           { 0, NULL }
152 };
153 
154 
155 #define   SVAR(var) __STRING(var)       /* to force expansion */
156 #define   KGET(idx, var)                                                                  \
157           KGET1(idx, &var, sizeof(var), SVAR(var))
158 #define   KGET1(idx, p, s, msg)                                                           \
159           KGET2(nl[idx].n_value, p, s, msg)
160 #define   KGET2(addr, p, s, msg)                                                          \
161           if (kvm_read(kd, (u_long)(addr), p, s) != s)                          \
162                     warnx("cannot read %s: %s", msg, kvm_geterr(kd))
163 #define   KGETN(idx, var)                                                                 \
164           KGET1N(idx, &var, sizeof(var), SVAR(var))
165 #define   KGET1N(idx, p, s, msg)                                                          \
166           KGET2N(nl[idx].n_value, p, s, msg)
167 #define   KGET2N(addr, p, s, msg)                                                         \
168           ((kvm_read(kd, (u_long)(addr), p, s) == s) ? 1 : 0)
169 #define   KGETRET(addr, p, s, msg)                                              \
170           if (kvm_read(kd, (u_long)(addr), p, s) != s) {                        \
171                     warnx("cannot read %s: %s", msg, kvm_geterr(kd)); \
172                     return (0);                                                           \
173           }
174 
175 void      filemode(void);
176 int       getfiles(char **, int *);
177 struct mount *
178           getmnt(struct mount *);
179 struct e_vnode *
180           kinfo_vnodes(int *);
181 struct e_vnode *
182           loadvnodes(int *);
183 void      mount_print(struct mount *);
184 void      nfs_header(void);
185 int       nfs_print(struct vnode *);
186 void      swapmode(void);
187 void      ttymode(void);
188 void      ttyprt(struct tty *, int);
189 void      ttytype(struct tty *, const char *, int, int, int);
190 void      ufs_header(void);
191 int       ufs_print(struct vnode *);
192 static void usage(void);
193 void      vnode_header(void);
194 void      vnode_print(struct vnode *, struct vnode *);
195 void      vnodemode(void);
196 
197 static void Output(const char *name, int hlen,
198                               struct kvm_swap *kswap, int flags);
199 
200 int
main(int argc,char ** argv)201 main(int argc, char **argv)
202 {
203           int ch, ret;
204           int fileflag, ttyflag, vnodeflag;
205           char buf[_POSIX2_LINE_MAX];
206           const char *opts;
207 
208           fileflag = swapflag = ttyflag = vnodeflag = 0;
209 
210           /* We will behave like good old swapinfo if thus invoked */
211           opts = strrchr(argv[0],'/');
212           if (opts)
213                     opts++;
214           else
215                     opts = argv[0];
216           if (!strcmp(opts,"swapinfo")) {
217                     swapflag = 1;
218                     opts = "ghkmM:N:";
219                     usagestr = "swapinfo [-ghkm] [-M core] [-N system]";
220           } else {
221                     opts = "TM:N:fhiknstv";
222                     usagestr = "pstat [-Tfhknst] [-M core] [-N system]";
223           }
224 
225           while ((ch = getopt(argc, argv, opts)) != -1) {
226                     switch (ch) {
227                     case 'f':
228                               fileflag = 1;
229                               break;
230                     case 'g':
231                               if (setenv("BLOCKSIZE", "1G", 1) == -1)
232                                         warn("setenv: cannot set BLOCKSIZE=1K");
233                               break;
234                     case 'k':
235                               if (setenv("BLOCKSIZE", "1K", 1) == -1)
236                                         warn("setenv: cannot set BLOCKSIZE=1K");
237                               break;
238                     case 'm':
239                               if (setenv("BLOCKSIZE", "1M", 1) == -1)
240                                         warn("setenv: cannot set BLOCKSIZE=1K");
241                               break;
242                     case 'h':
243                               humanflag = 1;
244                               break;
245                     case 'M':
246                               memf = optarg;
247                               break;
248                     case 'N':
249                               nlistf = optarg;
250                               break;
251                     case 'n':
252                               usenumflag = 1;
253                               break;
254                     case 's':
255                               ++swapflag;
256                               break;
257                     case 'T':
258                               totalflag = 1;
259                               break;
260                     case 't':
261                               ttyflag = 1;
262                               break;
263                     case 'v':
264                     case 'i':           /* Backward compatibility. */
265                               errx(1, "vnode mode not supported");
266 #if 0
267                               vnodeflag = 1;
268                               break;
269 #endif
270                     default:
271                               usage();
272                     }
273           }
274           argc -= optind;
275           argv += optind;
276 
277           /*
278            * Discard setgid privileges if not the running kernel so that bad
279            * guys can't print interesting stuff from kernel memory.
280            */
281           if (nlistf != NULL || memf != NULL)
282                     setgid(getgid());
283 
284           if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL)
285                     errx(1, "kvm_openfiles: %s", buf);
286 #ifdef USE_KCORE
287           if (kcore_wrapper_open(nlistf, memf, buf))
288                     errx(1, "kcore_open: %s", buf);
289 #endif
290           if ((ret = kvm_nlist(kd, nl)) != 0) {
291                     size_t i;
292                     int quit = 0;
293 
294                     if (ret == -1)
295                               errx(1, "kvm_nlist: %s", kvm_geterr(kd));
296                     for (i = 0; i < NL_LAST_MANDATORY; i++) {
297                               if (!nl[i].n_value) {
298                                         quit = 1;
299                                         warnx("undefined symbol: %s", nl[i].n_name);
300                               }
301                     }
302                     if (quit)
303                               exit(1);
304           }
305           if (!(fileflag | vnodeflag | ttyflag | swapflag | totalflag))
306                     usage();
307           if (fileflag || totalflag)
308                     filemode();
309           if (vnodeflag)
310                     vnodemode();
311           if (ttyflag)
312                     ttymode();
313           if (swapflag || totalflag)
314                     swapmode();
315           exit (0);
316 }
317 
318 static void
usage(void)319 usage(void)
320 {
321           fprintf(stderr, "usage: %s\n", usagestr);
322           exit (1);
323 }
324 
325 struct e_vnode {
326           struct vnode *avnode;
327           struct vnode vnode;
328 };
329 
330 void
vnodemode(void)331 vnodemode(void)
332 {
333           struct e_vnode *e_vnodebase, *endvnode, *evp;
334           struct vnode *vp;
335           struct mount *maddr, *mp = NULL;
336           int numvnodes;
337 
338           e_vnodebase = loadvnodes(&numvnodes);
339           if (totalflag) {
340                     printf("%7d vnodes\n", numvnodes);
341                     return;
342           }
343           endvnode = e_vnodebase + numvnodes;
344           printf("%d active vnodes\n", numvnodes);
345 
346 
347 #define ST          mp->mnt_stat
348           maddr = NULL;
349           for (evp = e_vnodebase; evp < endvnode; evp++) {
350                     vp = &evp->vnode;
351                     if (vp->v_mount != maddr) {
352                               /*
353                                * New filesystem
354                                */
355                               if ((mp = getmnt(vp->v_mount)) == NULL)
356                                         continue;
357                               maddr = vp->v_mount;
358                               mount_print(mp);
359                               vnode_header();
360                               if (!strcmp(ST.f_fstypename, "ufs") ||
361                                   !strcmp(ST.f_fstypename, "mfs"))
362                                         ufs_header();
363                               else if (!strcmp(ST.f_fstypename, "nfs"))
364                                         nfs_header();
365                               printf("\n");
366                     }
367                     vnode_print(evp->avnode, vp);
368                     if (!strcmp(ST.f_fstypename, "ufs") ||
369                         !strcmp(ST.f_fstypename, "mfs"))
370                               ufs_print(vp);
371                     else if (!strcmp(ST.f_fstypename, "nfs"))
372                               nfs_print(vp);
373                     printf("\n");
374           }
375           free(e_vnodebase);
376 }
377 
378 void
vnode_header(void)379 vnode_header(void)
380 {
381           printf("ADDR     TYP VFLAG  USE HOLD");
382 }
383 
384 void
vnode_print(struct vnode * avnode,struct vnode * vp)385 vnode_print(struct vnode *avnode, struct vnode *vp)
386 {
387           const char *type;
388           char flags[32];
389           char *fp = flags;
390           int flag;
391           int refs;
392 
393           /*
394            * set type
395            */
396           switch (vp->v_type) {
397           case VNON:
398                     type = "non"; break;
399           case VREG:
400                     type = "reg"; break;
401           case VDIR:
402                     type = "dir"; break;
403           case VBLK:
404                     type = "blk"; break;
405           case VCHR:
406                     type = "chr"; break;
407           case VLNK:
408                     type = "lnk"; break;
409           case VSOCK:
410                     type = "soc"; break;
411           case VFIFO:
412                     type = "fif"; break;
413           case VBAD:
414                     type = "bad"; break;
415           default:
416                     type = "unk"; break;
417           }
418           /*
419            * gather flags
420            */
421           flag = vp->v_flag;
422           if (flag & VROOT)
423                     *fp++ = 'R';
424           if (flag & VTEXT)
425                     *fp++ = 'T';
426           if (flag & VSYSTEM)
427                     *fp++ = 'S';
428           if (flag & VISTTY)
429                     *fp++ = 't';
430 #ifdef VXLOCK
431           if (flag & VXLOCK)
432                     *fp++ = 'L';
433           if (flag & VXWANT)
434                     *fp++ = 'W';
435 #endif
436           if (flag & VOBJBUF)
437                     *fp++ = 'V';
438           if (flag & (VAGE0 | VAGE1))
439                     *fp++ = 'a';
440 #ifdef VDOOMED
441           if (flag & VDOOMED)
442                     *fp++ = 'D';
443 #endif
444           if (flag & VONWORKLST)
445                     *fp++ = 'O';
446 #ifdef VRECLAIMED
447           if (flag & VINACTIVE)
448                     *fp++ = 'I';
449           if (flag & VRECLAIMED)
450                     *fp++ = 'X';
451 #endif
452 
453           if (flag == 0)
454                     *fp++ = '-';
455           *fp = '\0';
456 
457           /*
458            * Convert SYSREF ref counts into something more
459            * human readable for display.
460            */
461           refs = vp->v_refcnt;
462           printf("%8lx %s %5s %08x %4d",
463               (u_long)(void *)avnode, type, flags, refs, vp->v_auxrefs);
464 }
465 
466 void
ufs_header(void)467 ufs_header(void)
468 {
469           printf(" FILEID IFLAG RDEV|SZ");
470 }
471 
472 int
ufs_print(struct vnode * vp)473 ufs_print(struct vnode *vp)
474 {
475           int flag;
476           struct inode inode, *ip = &inode;
477           char flagbuf[16], *flags = flagbuf;
478           char *name;
479           mode_t type;
480 
481           KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
482           flag = ip->i_flag;
483           if (flag & IN_ACCESS)
484                     *flags++ = 'A';
485           if (flag & IN_CHANGE)
486                     *flags++ = 'C';
487           if (flag & IN_UPDATE)
488                     *flags++ = 'U';
489           if (flag & IN_MODIFIED)
490                     *flags++ = 'M';
491           if (flag & IN_RENAME)
492                     *flags++ = 'R';
493           if (flag & IN_SHLOCK)
494                     *flags++ = 'S';
495           if (flag & IN_EXLOCK)
496                     *flags++ = 'E';
497           if (flag & IN_HASHED)
498                     *flags++ = 'H';
499           if (flag & IN_LAZYMOD)
500                     *flags++ = 'L';
501           if (flag == 0)
502                     *flags++ = '-';
503           *flags = '\0';
504 
505           printf(" %6ju %5s", (uintmax_t)ip->i_number, flagbuf);
506           type = ip->i_mode & S_IFMT;
507           if (S_ISCHR(ip->i_mode) || S_ISBLK(ip->i_mode))
508                     if (usenumflag || ((name = devname(ip->i_rdev, type)) == NULL))
509                               printf("   %2d,%-2d",
510                                   major(ip->i_rdev), minor(ip->i_rdev));
511                     else
512                               printf(" %7s", name);
513           else
514                     printf(" %7ju", (uintmax_t)ip->i_size);
515           return (0);
516 }
517 
518 void
nfs_header(void)519 nfs_header(void)
520 {
521           printf(" FILEID NFLAG RDEV|SZ");
522 }
523 
524 int
nfs_print(struct vnode * vp)525 nfs_print(struct vnode *vp)
526 {
527           struct nfsnode nfsnode, *np = &nfsnode;
528           char flagbuf[16], *flags = flagbuf;
529           int flag;
530           char *name;
531           mode_t type;
532 
533           KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
534           flag = np->n_flag;
535           if (flag & NFLUSHWANT)
536                     *flags++ = 'W';
537           if (flag & NFLUSHINPROG)
538                     *flags++ = 'P';
539           if (flag & NLMODIFIED)
540                     *flags++ = 'M';
541           if (flag & NRMODIFIED)
542                     *flags++ = 'R';
543           if (flag & NWRITEERR)
544                     *flags++ = 'E';
545           if (flag & NQNFSEVICTED)
546                     *flags++ = 'G';
547           if (flag & NACC)
548                     *flags++ = 'A';
549           if (flag & NUPD)
550                     *flags++ = 'U';
551           if (flag & NCHG)
552                     *flags++ = 'C';
553           if (flag & NLOCKED)
554                     *flags++ = 'L';
555           if (flag & NWANTED)
556                     *flags++ = 'w';
557           if (flag == 0)
558                     *flags++ = '-';
559           *flags = '\0';
560 
561 #define VT          np->n_vattr
562           printf(" %6ju %5s", (uintmax_t)VT.va_fileid, flagbuf);
563           type = VT.va_mode & S_IFMT;
564           if (S_ISCHR(VT.va_mode) || S_ISBLK(VT.va_mode))
565                     if (usenumflag || ((name = devname((VT.va_rmajor << 8) | VT.va_rminor, type)) == NULL))
566                               printf("   %2d,%-2d",
567                                   VT.va_rmajor, VT.va_rminor);
568                     else
569                               printf(" %7s", name);
570           else
571                     printf(" %7ju", (uintmax_t)np->n_size);
572           return (0);
573 }
574 
575 /*
576  * Given a pointer to a mount structure in kernel space,
577  * read it in and return a usable pointer to it.
578  */
579 struct mount *
getmnt(struct mount * maddr)580 getmnt(struct mount *maddr)
581 {
582           static struct mtab {
583                     struct mtab *next;
584                     struct mount *maddr;
585                     struct mount mount;
586           } *mhead = NULL;
587           struct mtab *mt;
588 
589           for (mt = mhead; mt != NULL; mt = mt->next)
590                     if (maddr == mt->maddr)
591                               return (&mt->mount);
592           if ((mt = malloc(sizeof(struct mtab))) == NULL)
593                     errx(1, "malloc");
594           KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
595           mt->maddr = maddr;
596           mt->next = mhead;
597           mhead = mt;
598           return (&mt->mount);
599 }
600 
601 void
mount_print(struct mount * mp)602 mount_print(struct mount *mp)
603 {
604           int flags;
605 
606 #define ST          mp->mnt_stat
607           printf("*** MOUNT %s %s on %s", ST.f_fstypename,
608               ST.f_mntfromname, ST.f_mntonname);
609           if ((flags = mp->mnt_flag)) {
610                     int i;
611                     const char *sep = " (";
612 
613                     for (i = 0; mnt_flags[i].m_flag; i++) {
614                               if (flags & mnt_flags[i].m_flag) {
615                                         printf("%s%s", sep, mnt_flags[i].m_name);
616                                         flags &= ~mnt_flags[i].m_flag;
617                                         sep = ",";
618                               }
619                     }
620                     if (flags)
621                               printf("%sunknown_flags:%x", sep, flags);
622                     printf(")");
623           }
624           printf("\n");
625 #undef ST
626 }
627 
628 struct e_vnode *
loadvnodes(int * avnodes)629 loadvnodes(int *avnodes)
630 {
631           int mib[2];
632           size_t copysize;
633           struct e_vnode *vnodebase;
634 
635           if (memf != NULL) {
636                     /*
637                      * do it by hand
638                      */
639                     return (kinfo_vnodes(avnodes));
640           }
641           mib[0] = CTL_KERN;
642           mib[1] = KERN_VNODE;
643           if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
644                     err(1, "sysctl: KERN_VNODE");
645           if ((vnodebase = malloc(copysize)) == NULL)
646                     errx(1, "malloc");
647           if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
648                     err(1, "sysctl: KERN_VNODE");
649           if (copysize % sizeof(struct e_vnode))
650                     errx(1, "vnode size mismatch");
651           *avnodes = copysize / sizeof(struct e_vnode);
652 
653           return (vnodebase);
654 }
655 
656 /*
657  * simulate what a running kernel does in in kinfo_vnode
658  */
659 struct e_vnode *
kinfo_vnodes(int * avnodes)660 kinfo_vnodes(int *avnodes)
661 {
662           struct mntlist mountlist;
663           struct mount *mp, mounth, *mp_next;
664           struct vnode *vp, vnode, *vp_next;
665           char *vbuf, *evbuf, *bp;
666           int num, numvnodes;
667 
668 #define VPTRSZ  sizeof(struct vnode *)
669 #define VNODESZ sizeof(struct vnode)
670 
671           KGET(NL_NUMVNODES, numvnodes);
672           if ((vbuf = malloc((numvnodes + 20) * (VPTRSZ + VNODESZ))) == NULL)
673                     errx(1, "malloc");
674           bp = vbuf;
675           evbuf = vbuf + (numvnodes + 20) * (VPTRSZ + VNODESZ);
676           KGET(NL_MOUNTLIST, mountlist);
677           for (num = 0, mp = TAILQ_FIRST(&mountlist); ; mp = mp_next) {
678                     KGET2(mp, &mounth, sizeof(mounth), "mount entry");
679                     mp_next = TAILQ_NEXT(&mounth, mnt_list);
680                     for (vp = TAILQ_FIRST(&mounth.mnt_nvnodelist);
681                         vp != NULL; vp = vp_next) {
682                               KGET2(vp, &vnode, sizeof(vnode), "vnode");
683                               vp_next = TAILQ_NEXT(&vnode, v_nmntvnodes);
684                               if ((bp + VPTRSZ + VNODESZ) > evbuf)
685                                         /* XXX - should realloc */
686                                         errx(1, "no more room for vnodes");
687                               memmove(bp, &vp, VPTRSZ);
688                               bp += VPTRSZ;
689                               memmove(bp, &vnode, VNODESZ);
690                               bp += VNODESZ;
691                               num++;
692                     }
693                     if (mp == TAILQ_LAST(&mountlist, mntlist))
694                               break;
695           }
696           *avnodes = num;
697           return ((struct e_vnode *)vbuf);
698 }
699 
700 char hdr[] =
701 "  LINE RAW CAN OUT IHIWT ILOWT OHWT LWT     COL STATE  SESS      PGID DISC\n";
702 int ttyspace = 128;
703 
704 void
ttymode(void)705 ttymode(void)
706 {
707           struct tty *tty;
708           struct tty ttyb[1000];
709           int error;
710           size_t len, i;
711 
712           printf("%s", hdr);
713           len = sizeof(ttyb);
714           error = sysctlbyname("kern.ttys", &ttyb, &len, 0, 0);
715           if (!error) {
716                     len /= sizeof(ttyb[0]);
717                     for (i = 0; i < len; i++) {
718                               ttyprt(&ttyb[i], 0);
719                     }
720           }
721           if ((tty = malloc(ttyspace * sizeof(*tty))) == NULL)
722                     errx(1, "malloc");
723           if (nl[NL_NRC_TTY].n_type != 0)
724                     ttytype(tty, "rc", NL_RC_TTY, NL_NRC_TTY, 0);
725           if (nl[NL_NCY_TTY].n_type != 0)
726                     ttytype(tty, "cy", NL_CY_TTY, NL_NCY_TTY, 0);
727           if (nl[NL_SI_NPORTS].n_type != 0)
728                     ttytype(tty, "si", NL_SI_TTY, NL_SI_NPORTS, 1);
729           free(tty);
730 }
731 
732 void
ttytype(struct tty * tty,const char * name,int type,int number,int indir)733 ttytype(struct tty *tty, const char *name, int type, int number, int indir)
734 {
735           struct tty *tp;
736           int ntty;
737           struct tty **ttyaddr;
738 
739           if (tty == NULL)
740                     return;
741           KGET(number, ntty);
742           printf("%d %s %s\n", ntty, name, (ntty == 1) ? "line" : "lines");
743           if (ntty > ttyspace) {
744                     ttyspace = ntty;
745                     if ((tty = realloc(tty, ttyspace * sizeof(*tty))) == NULL)
746                               errx(1, "realloc");
747           }
748           if (indir) {
749                     KGET(type, ttyaddr);
750                     KGET2(ttyaddr, tty, (ssize_t)(ntty * sizeof(struct tty)),
751                           "tty structs");
752           } else {
753                     KGET1(type, tty, (ssize_t)(ntty * sizeof(struct tty)),
754                           "tty structs");
755           }
756           printf("%s", hdr);
757           for (tp = tty; tp < &tty[ntty]; tp++)
758                     ttyprt(tp, tp - tty);
759 }
760 
761 struct {
762           int flag;
763           char val;
764 } ttystates[] = {
765 #ifdef TS_WOPEN
766           { TS_WOPEN,         'W'},
767 #endif
768           { TS_ISOPEN,        'O'},
769           { TS_CARR_ON,       'C'},
770 #ifdef TS_CONNECTED
771           { TS_CONNECTED,     'c'},
772 #endif
773           { TS_TIMEOUT,       'T'},
774           { TS_FLUSH,         'F'},
775           { TS_BUSY,          'B'},
776 #ifdef TS_ASLEEP
777           { TS_ASLEEP,        'A'},
778 #endif
779 #ifdef TS_SO_OLOWAT
780           { TS_SO_OLOWAT,     'A'},
781 #endif
782 #ifdef TS_SO_OCOMPLETE
783           { TS_SO_OCOMPLETE, 'a'},
784 #endif
785           { TS_XCLUDE,        'X'},
786           { TS_TTSTOP,        'S'},
787 #ifdef TS_CAR_OFLOW
788           { TS_CAR_OFLOW,     'm'},
789 #endif
790 #ifdef TS_CTS_OFLOW
791           { TS_CTS_OFLOW,     'o'},
792 #endif
793 #ifdef TS_DSR_OFLOW
794           { TS_DSR_OFLOW,     'd'},
795 #endif
796           { TS_TBLOCK,        'K'},
797           { TS_ASYNC,         'Y'},
798           { TS_BKSL,          'D'},
799           { TS_ERASE,         'E'},
800           { TS_LNCH,          'L'},
801           { TS_TYPEN,         'P'},
802           { TS_CNTTB,         'N'},
803 #ifdef TS_CAN_BYPASS_L_RINT
804           { TS_CAN_BYPASS_L_RINT, 'l'},
805 #endif
806 #ifdef TS_SNOOP
807           { TS_SNOOP,     's'},
808 #endif
809 #ifdef TS_ZOMBIE
810           { TS_ZOMBIE,        'Z'},
811 #endif
812           { 0,             '\0'},
813 };
814 
815 void
ttyprt(struct tty * tp,int line)816 ttyprt(struct tty *tp, int line)
817 {
818           int i, j;
819           pid_t pgid;
820           char *name, state[20];
821           dev_t dev;
822 
823           dev = (uintptr_t)tp->t_dev & 0xffff; /* XXX t_dev is really dev_t */
824 
825           if (usenumflag || dev == 0 || (name = devname(dev, S_IFCHR)) == NULL)
826                     printf("%7d ", line);
827           else
828                     printf("%7s ", name);
829           printf("%2d %3d ", tp->t_rawq.c_cc, tp->t_canq.c_cc);
830           printf("%3d %5d %5d %4d %3d %7d ", tp->t_outq.c_cc,
831                     tp->t_ihiwat, tp->t_ilowat, tp->t_ohiwat, tp->t_olowat,
832                     tp->t_column);
833           for (i = j = 0; ttystates[i].flag; i++)
834                     if (tp->t_state&ttystates[i].flag)
835                               state[j++] = ttystates[i].val;
836           if (j == 0)
837                     state[j++] = '-';
838           state[j] = '\0';
839           printf("%-6s %8lx", state, (u_long)(void *)tp->t_session);
840           pgid = 0;
841           if (tp->t_pgrp != NULL)
842                     KGET2(&tp->t_pgrp->pg_id, &pgid, sizeof(pid_t), "pgid");
843           printf("%6d ", pgid);
844           switch (tp->t_line) {
845           case TTYDISC:
846                     printf("term\n");
847                     break;
848           case SLIPDISC:
849                     printf("slip\n");
850                     break;
851           case PPPDISC:
852                     printf("ppp\n");
853                     break;
854           default:
855                     printf("%d\n", tp->t_line);
856                     break;
857           }
858 }
859 
860 void
filemode(void)861 filemode(void)
862 {
863           struct kinfo_file *fp, *ofp;
864           size_t len;
865           char flagbuf[16], *fbp;
866           int maxfile, nfile;
867           static const char *dtypes[] = { "???", "inode", "socket" };
868 
869           if (kinfo_get_maxfiles(&maxfile))
870                     err(1, "kinfo_get_maxfiles");
871           if (totalflag) {
872                     if (kinfo_get_openfiles(&nfile))
873                               err(1, "kinfo_get_openfiles");
874                     printf("%3d/%3d files\n", nfile, maxfile);
875                     return;
876           }
877           if (kinfo_get_files(&fp, &len))
878                     err(1, "kinfo_get_files");
879           ofp = fp;
880 
881           printf("%zu/%d open files\n", len, maxfile);
882           printf("   LOC   TYPE    FLG     CNT  MSG    DATA    OFFSET\n");
883           for (; len-- > 0; fp++) {
884                     if ((unsigned)fp->f_type > DTYPE_SOCKET)
885                               continue;
886                     printf("%p ", fp->f_file);
887                     printf("%-8.8s", dtypes[fp->f_type]);
888                     fbp = flagbuf;
889                     if (fp->f_flag & FREAD)
890                               *fbp++ = 'R';
891                     if (fp->f_flag & FWRITE)
892                               *fbp++ = 'W';
893                     if (fp->f_flag & FAPPEND)
894                               *fbp++ = 'A';
895 #ifdef FSHLOCK      /* currently gone */
896                     if (fp->f_flag & FSHLOCK)
897                               *fbp++ = 'S';
898                     if (fp->f_flag & FEXLOCK)
899                               *fbp++ = 'X';
900 #endif
901                     if (fp->f_flag & FASYNC)
902                               *fbp++ = 'I';
903                     *fbp = '\0';
904                     printf("%6s  %3d", flagbuf, fp->f_count);
905                     printf("  %3d", fp->f_msgcount);
906                     printf("  %8lx", (u_long)(void *)fp->f_data);
907                     if (fp->f_offset < 0)
908                               printf("  %jx\n", (uintmax_t)fp->f_offset);
909                     else
910                               printf("  %jd\n", (intmax_t)fp->f_offset);
911           }
912           free(ofp);
913 }
914 
915 /*
916  * swapmode is based on a program called swapinfo written
917  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
918  */
919 void
swapmode(void)920 swapmode(void)
921 {
922           struct kvm_swap kswap[16];
923           int i;
924           int n;
925           const char *header;
926           int hlen;
927 
928           pagesize = getpagesize();
929           n = kvm_getswapinfo(
930               kd,
931               kswap,
932               NELEM(kswap),
933               ((swapflag > 1) ? SWIF_DUMP_TREE : 0) | SWIF_DEV_PREFIX
934           );
935 
936 #define CONVERT(v)  ((long)((quad_t)(v) * pagesize / blocksize))
937 #define CONVERTB(v) ((long)((quad_t)(v) * pagesize))
938 
939           if (humanflag) {
940                     hlen = 9;
941                     header = "   Blocks";
942           } else {
943                     header = getbsize(&hlen, &blocksize);
944           }
945 
946           if (totalflag == 0) {
947                     printf("%-15s %*s %8s %8s %8s  %s\n",
948                         "Device", hlen, header,
949                         "Used", "Avail", "Capacity", "Type");
950 
951                     for (i = 0; i < n; ++i) {
952                               Output(kswap[i].ksw_devname, hlen, &kswap[i], 1);
953                     }
954           }
955 
956           if (totalflag) {
957                     if (humanflag) {
958                               char buf1[6];
959                               char buf2[6];
960                               humanize_number(buf1, sizeof(buf1),
961                                                   CONVERTB(kswap[n].ksw_used),
962                                                   "",
963                                                   HN_AUTOSCALE, HN_NOSPACE |
964                                                                   HN_FRACTIONAL);
965                               humanize_number(buf2, sizeof(buf2),
966                                                   CONVERTB(kswap[n].ksw_total),
967                                                   "",
968                                                   HN_AUTOSCALE, HN_NOSPACE |
969                                                                   HN_FRACTIONAL);
970                               printf("%s/%s swap space\n", buf1, buf2);
971                     } else {
972                               blocksize = 1024 * 1024;
973                               printf("%ldM/%ldM swap space\n",
974                                      CONVERT(kswap[n].ksw_used),
975                                      CONVERT(kswap[n].ksw_total));
976                     }
977           } else if (n > 1) {
978                     Output("Total", hlen, &kswap[n], 0);
979           }
980 }
981 
982 static
983 void
Output(const char * name,int hlen,struct kvm_swap * kswap,int flags)984 Output(const char *name, int hlen, struct kvm_swap *kswap, int flags)
985 {
986           char buf1[32];
987           char buf2[32];
988           char buf3[32];
989 
990           if (humanflag) {
991                     humanize_number(buf1, 6,
992                                         CONVERTB(kswap->ksw_total),
993                                         "",
994                                         HN_AUTOSCALE,
995                                         HN_NOSPACE | HN_FRACTIONAL);
996                     humanize_number(buf2, 6,
997                                         CONVERTB(kswap->ksw_used),
998                                         "",
999                                         HN_AUTOSCALE,
1000                                         HN_NOSPACE | HN_FRACTIONAL);
1001                     humanize_number(buf3, 6,
1002                                         CONVERTB(kswap->ksw_total -
1003                                                    kswap->ksw_used),
1004                                         "",
1005                                         HN_AUTOSCALE,
1006                                         HN_NOSPACE | HN_FRACTIONAL);
1007           } else {
1008                     snprintf(buf1, sizeof(buf1), "%*ld",
1009                                hlen,
1010                                CONVERT(kswap->ksw_total));
1011                     snprintf(buf2, sizeof(buf2), "%8ld",
1012                                CONVERT(kswap->ksw_used));
1013                     snprintf(buf3, sizeof(buf2), "%8ld",
1014                                CONVERT(kswap->ksw_total -
1015                                          kswap->ksw_used));
1016           }
1017           printf("%-15s %*s ", name, hlen, buf1);
1018           printf("%8s %8s %5.0f%%",
1019                  buf2,
1020                  buf3,
1021                  (double)kswap->ksw_used * 100.0 / (double)kswap->ksw_total);
1022           if (flags) {
1023                     printf("    %s",
1024                            ((kswap->ksw_flags & SW_SEQUENTIAL) ?
1025                               "Sequential" : "Interleaved"));
1026           }
1027           printf("\n");
1028 }
1029