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