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