1 /*        $NetBSD: pstat.c,v 1.134 2022/02/17 14:39:14 hannken Exp $  */
2 
3 /*-
4  * Copyright (c) 1980, 1991, 1993, 1994
5  *        The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1980, 1991, 1993, 1994\
35  The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)pstat.c     8.16 (Berkeley) 5/9/95";
41 #else
42 __RCSID("$NetBSD: pstat.c,v 1.134 2022/02/17 14:39:14 hannken Exp $");
43 #endif
44 #endif /* not lint */
45 
46 #define _KERNEL
47 #include <sys/types.h>
48 #undef _KERNEL
49 #include <sys/param.h>
50 #include <sys/time.h>
51 #include <sys/vnode.h>
52 #include <sys/ucred.h>
53 #include <stdbool.h>
54 #define _KERNEL
55 #define NFS
56 #include <sys/mount.h>
57 #undef NFS
58 #include <sys/file.h>
59 #include <ufs/ufs/inode.h>
60 #include <ufs/ufs/ufsmount.h>
61 #include <sys/uio.h>
62 #include <miscfs/genfs/layer.h>
63 #undef _KERNEL
64 #include <sys/stat.h>
65 #include <nfs/nfsproto.h>
66 #include <nfs/rpcv2.h>
67 #include <nfs/nfs.h>
68 #include <nfs/nfsnode.h>
69 #include <sys/ioctl.h>
70 #include <sys/tty.h>
71 #include <sys/conf.h>
72 
73 #include <sys/sysctl.h>
74 
75 #include <err.h>
76 #include <errno.h>
77 #include <kvm.h>
78 #include <limits.h>
79 #include <nlist.h>
80 #include <stdio.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <unistd.h>
84 
85 #include "swapctl.h"
86 
87 struct nlist nl[] = {
88 #define   V_LRU_LIST          0
89           { "_lru_list", 0, 0, 0, 0 }   ,         /* address of lru lists. */
90 #define   V_NUMV              1
91           { "_numvnodes", 0, 0, 0, 0 },
92 #define   V_NEXT_OFFSET       2
93           { "_vnode_offset_next_by_lru", 0, 0, 0, 0 },
94 #define   FNL_NFILE 3
95           { "_nfiles", 0, 0, 0, 0 },
96 #define FNL_MAXFILE 4
97           { "_maxfiles", 0, 0, 0, 0 },
98 #define TTY_NTTY    5
99           { "_tty_count", 0, 0, 0, 0 },
100 #define TTY_TTYLIST 6
101           { "_ttylist", 0, 0, 0, 0 },
102 #define NLMANDATORY TTY_TTYLIST         /* names up to here are mandatory */
103           { "", 0, 0, 0, 0 }
104 };
105 
106 int       usenumflag;
107 int       totalflag;
108 int       kflag;
109 int       hflag;
110 char      *nlistf   = NULL;
111 char      *memf     = NULL;
112 kvm_t     *kd;
113 
114 static const char * const dtypes[] = { DTYPE_NAMES };
115 
116 
117 static const struct {
118           u_int m_flag;
119           u_int m_visible;
120           const char *m_name;
121 } mnt_flags[] = {
122           __MNT_FLAGS
123 };
124 
125 struct flagbit_desc {
126           u_int fd_flags;
127           char fd_mark;
128 };
129 
130 #define   SVAR(var) __STRING(var)       /* to force expansion */
131 #define   KGET(idx, var)                                                                  \
132           KGET1(idx, &var, sizeof(var), SVAR(var))
133 #define   KGET1(idx, p, s, msg)                                                           \
134           KGET2(nl[idx].n_value, p, s, msg)
135 #define   KGET2(addr, p, s, msg) do {                                           \
136           if (kvm_read(kd, (u_long)(addr), p, s) != s)                          \
137                     warnx("cannot read %s: %s", msg, kvm_geterr(kd)); \
138 } while (0)
139 #define   KGETRET(addr, p, s, msg) do {                                         \
140           if (kvm_read(kd, (u_long)(addr), p, s) != s) {                        \
141                     warnx("cannot read %s: %s", msg, kvm_geterr(kd)); \
142                     return (0);                                                           \
143           }                                                                               \
144 } while (0)
145 
146 #if 1                                   /* This is copied from vmstat/vmstat.c */
147 /*
148  * Print single word.  `ovflow' is number of characters didn't fit
149  * on the last word.  `fmt' is a format string to print this word.
150  * It must contain asterisk for field width.  `width' is a width
151  * occupied by this word.  `fixed' is a number of constant chars in
152  * `fmt'.  `val' is a value to be printed using format string `fmt'.
153  */
154 #define   PRWORD(ovflw, fmt, width, fixed, val) do {        \
155           (ovflw) += printf((fmt),                          \
156               (width) - (fixed) - (ovflw) > 0 ?             \
157               (width) - (fixed) - (ovflw) : 0,              \
158               (val)) - (width);                                       \
159           if ((ovflw) < 0)                                  \
160                     (ovflw) = 0;                                      \
161 } while (0)
162 #endif
163 
164 void      filemode(void);
165 int       getfiles(char **, int *, char **);
166 int       getflags(const struct flagbit_desc *, char *, u_int);
167 struct mount *
168           getmnt(struct mount *);
169 char *    kinfo_vnodes(int *);
170 void      layer_header(void);
171 int       layer_print(struct vnode *, int);
172 char *    loadvnodes(int *);
173 void      mount_print(struct mount *);
174 void      nfs_header(void);
175 int       nfs_print(struct vnode *, int);
176 void      ttymode(void);
177 void      ttyprt(struct tty *);
178 void      ufs_header(void);
179 int       ufs_print(struct vnode *, int);
180 int       ext2fs_print(struct vnode *, int);
181 __dead void         usage(void);
182 void      vnode_header(void);
183 int       vnode_print(struct vnode *, struct vnode *);
184 void      vnodemode(void);
185 
186 int
main(int argc,char * argv[])187 main(int argc, char *argv[])
188 {
189           int ch, i, quit, ret, use_sysctl;
190           int fileflag, swapflag, ttyflag, vnodeflag;
191           gid_t egid = getegid();
192           char buf[_POSIX2_LINE_MAX];
193 
194           setegid(getgid());
195           fileflag = swapflag = ttyflag = vnodeflag = 0;
196           while ((ch = getopt(argc, argv, "TM:N:fghikmnstv")) != -1)
197                     switch (ch) {
198                     case 'f':
199                               fileflag = 1;
200                               break;
201                     case 'M':
202                               memf = optarg;
203                               break;
204                     case 'N':
205                               nlistf = optarg;
206                               break;
207                     case 'n':
208                               usenumflag = 1;
209                               break;
210                     case 's':
211                               swapflag = 1;
212                               break;
213                     case 'T':
214                               totalflag = 1;
215                               break;
216                     case 't':
217                               ttyflag = 1;
218                               break;
219                     case 'k':
220                               kflag = 1;
221                               break;
222                     case 'g':
223                               kflag = 3; /* 1k ^ 3 */
224                               break;
225                     case 'h':
226                               hflag = 1;
227                               break;
228                     case 'm':
229                               kflag = 2; /* 1k ^ 2 */
230                               break;
231                     case 'v':
232                     case 'i':           /* Backward compatibility. */
233                               vnodeflag = 1;
234                               break;
235                     default:
236                               usage();
237                     }
238           argc -= optind;
239           argv += optind;
240 
241           /*
242            * Discard setgid privileges.  If not the running kernel, we toss
243            * them away totally so that bad guys can't print interesting stuff
244            * from kernel memory, otherwise switch back to kmem for the
245            * duration of the kvm_openfiles() call.
246            */
247           if (nlistf != NULL || memf != NULL)
248                     (void)setgid(getgid());
249           else
250                     (void)setegid(egid);
251 
252           use_sysctl = (nlistf == NULL && memf == NULL);
253 
254           if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == 0)
255                     errx(1, "kvm_openfiles: %s", buf);
256 
257           /* get rid of it now anyway */
258           if (nlistf == NULL && memf == NULL)
259                     (void)setgid(getgid());
260           if ((ret = kvm_nlist(kd, nl)) != 0) {
261                     if (ret == -1)
262                               errx(1, "kvm_nlist: %s", kvm_geterr(kd));
263                     for (i = quit = 0; i <= NLMANDATORY; i++)
264                               if (!nl[i].n_value) {
265                                         quit = 1;
266                                         warnx("undefined symbol: %s", nl[i].n_name);
267                               }
268                     if (quit)
269                               exit(1);
270           }
271           if (!(fileflag | vnodeflag | ttyflag | swapflag | totalflag))
272                     usage();
273           if (fileflag || totalflag)
274                     filemode();
275           if (vnodeflag || totalflag)
276                     vnodemode();
277           if (ttyflag)
278                     ttymode();
279           if (swapflag || totalflag)
280                     if (use_sysctl)
281                               list_swap(0, kflag, 0, totalflag, 1, hflag);
282           exit(0);
283 }
284 
285 #define   VPTRSZ  sizeof(struct vnode *)
286 #define   VNODESZ sizeof(struct vnode)
287 #define   PTRSTRWIDTH ((int)sizeof(void *) * 2) /* Width of resulting string
288                                                              when pointer is printed
289                                                              in hexadecimal. */
290 
291 static void
devprintf(char * buf,size_t buflen,dev_t dev)292 devprintf(char *buf, size_t buflen, dev_t dev)
293 {
294           (void)snprintf(buf, buflen, "%llu,%llu",
295               (unsigned long long)major(dev),
296               (unsigned long long)minor(dev));
297 }
298 
299 void
vnodemode(void)300 vnodemode(void)
301 {
302           char *e_vnodebase, *endvnode, *evp;
303           struct vnode *vp;
304           struct mount *maddr, *mp;
305           int numvnodes, ovflw;
306           int (*vnode_fsprint) (struct vnode *, int); /* per-fs data printer */
307 
308           mp = NULL;
309           e_vnodebase = loadvnodes(&numvnodes);
310           if (totalflag) {
311                     (void)printf("%7d vnodes\n", numvnodes);
312                     goto out;
313           }
314           endvnode = e_vnodebase + numvnodes * (VPTRSZ + VNODESZ);
315           (void)printf("%d active vnodes\n", numvnodes);
316 
317 #define   ST        mp->mnt_stat
318 #define   FSTYPE_IS(mp, name)                                                   \
319           (strncmp((mp)->mnt_stat.f_fstypename, (name),                         \
320           sizeof((mp)->mnt_stat.f_fstypename)) == 0)
321           maddr = NULL;
322           vnode_fsprint = NULL;
323           for (evp = e_vnodebase; evp < endvnode; evp += VPTRSZ + VNODESZ) {
324                     vp = (struct vnode *)(evp + VPTRSZ);
325                     if (vp->v_mount != maddr) {
326                               /*
327                                * New filesystem
328                                */
329                               if ((mp = getmnt(vp->v_mount)) == NULL)
330                                         continue;
331                               maddr = vp->v_mount;
332                               mount_print(mp);
333                               vnode_header();
334                               /*
335                                * XXX do this in a more fs-independent way
336                                */
337                               if (FSTYPE_IS(mp, MOUNT_FFS) ||
338                                   FSTYPE_IS(mp, MOUNT_MFS)) {
339                                         ufs_header();
340                                         vnode_fsprint = ufs_print;
341                               } else if (FSTYPE_IS(mp, MOUNT_NFS)) {
342                                         nfs_header();
343                                         vnode_fsprint = nfs_print;
344                               } else if (FSTYPE_IS(mp, MOUNT_EXT2FS)) {
345                                         ufs_header();
346                                         vnode_fsprint = ext2fs_print;
347                               } else if (FSTYPE_IS(mp, MOUNT_NULL) ||
348                                   FSTYPE_IS(mp, MOUNT_OVERLAY) ||
349                                   FSTYPE_IS(mp, MOUNT_UMAP)) {
350                                         layer_header();
351                                         vnode_fsprint = layer_print;
352                               } else
353                                         vnode_fsprint = NULL;
354                               (void)printf("\n");
355                     }
356                     ovflw = vnode_print(*(struct vnode **)evp, vp);
357                     if (VTOI(vp) != NULL && vnode_fsprint != NULL)
358                               (*vnode_fsprint)(vp, ovflw);
359                     (void)printf("\n");
360           }
361 
362  out:
363           if (e_vnodebase)
364                     free(e_vnodebase);
365 }
366 
367 int
getflags(const struct flagbit_desc * fd,char * p,u_int flags)368 getflags(const struct flagbit_desc *fd, char *p, u_int flags)
369 {
370           char *q = p;
371 
372           if (flags == 0) {
373                     *p++ = '-';
374                     *p = '\0';
375                     return (0);
376           }
377 
378           for (; fd->fd_flags != 0; fd++)
379                     if ((flags & fd->fd_flags) != 0)
380                               *p++ = fd->fd_mark;
381           *p = '\0';
382           return (p - q);
383 }
384 
385 const struct flagbit_desc vnode_flags[] = {
386           { VV_ROOT,          'R' },
387           { VI_TEXT,          'T' },
388           { VV_SYSTEM,        'S' },
389           { VV_ISTTY,         'I' },
390           { VI_EXECMAP,       'E' },
391           { VU_DIROP,         'D' },
392           { VI_ONWORKLST,     'O' },
393           { VV_MPSAFE,    'M' },
394           { 0,                '\0' },
395 };
396 
397 void
vnode_header(void)398 vnode_header(void)
399 {
400 
401           (void)printf("%-*s TYP VFLAG  USE HOLD TAG NPAGE",
402               PTRSTRWIDTH, "ADDR");
403 }
404 
405 int
vnode_print(struct vnode * avnode,struct vnode * vp)406 vnode_print(struct vnode *avnode, struct vnode *vp)
407 {
408           const char *type;
409           char flags[sizeof(vnode_flags) / sizeof(vnode_flags[0])];
410           int ovflw;
411 
412           /*
413            * set type
414            */
415           switch (vp->v_type) {
416           case VNON:
417                     type = "non"; break;
418           case VREG:
419                     type = "reg"; break;
420           case VDIR:
421                     type = "dir"; break;
422           case VBLK:
423                     type = "blk"; break;
424           case VCHR:
425                     type = "chr"; break;
426           case VLNK:
427                     type = "lnk"; break;
428           case VSOCK:
429                     type = "soc"; break;
430           case VFIFO:
431                     type = "fif"; break;
432           case VBAD:
433                     type = "bad"; break;
434           default:
435                     type = "unk"; break;
436           }
437           /*
438            * gather flags
439            */
440           (void)getflags(vnode_flags, flags,
441               vp->v_uflag | vp->v_iflag | vp->v_vflag);
442 
443           ovflw = 0;
444           PRWORD(ovflw, "%*lx", PTRSTRWIDTH, 0, (long)avnode);
445           PRWORD(ovflw, " %*s", 4, 1, type);
446           PRWORD(ovflw, " %*s", 6, 1, flags);
447 #define   VUSECOUNT_MASK  0x3fffffff    /* XXX: kernel private */
448           PRWORD(ovflw, " %*d", 5, 1, vp->v_usecount & VUSECOUNT_MASK);
449           PRWORD(ovflw, " %*d", 5, 1, vp->v_holdcnt);
450           PRWORD(ovflw, " %*d", 4, 1, vp->v_tag);
451           PRWORD(ovflw, " %*d", 6, 1, vp->v_uobj.uo_npages);
452           return (ovflw);
453 }
454 
455 const struct flagbit_desc ufs_flags[] = {
456           { IN_ACCESS,        'A' },
457           { IN_CHANGE,        'C' },
458           { IN_UPDATE,        'U' },
459           { IN_MODIFIED,      'M' },
460           { IN_ACCESSED,      'a' },
461           { IN_SHLOCK,        'S' },
462           { IN_EXLOCK,        'E' },
463           { IN_SPACECOUNTED, 's' },
464           { 0,                '\0' },
465 };
466 
467 void
ufs_header(void)468 ufs_header(void)
469 {
470 
471           (void)printf(" FILEID IFLAG RDEV|SZ");
472 }
473 
474 int
ufs_print(struct vnode * vp,int ovflw)475 ufs_print(struct vnode *vp, int ovflw)
476 {
477           struct inode inode, *ip = &inode;
478           union dinode {
479                     struct ufs1_dinode dp1;
480                     struct ufs2_dinode dp2;
481           } dip;
482           struct ufsmount ump;
483           char flags[sizeof(ufs_flags) / sizeof(ufs_flags[0])];
484           char dev[4 + 1 + 7 + 1]; /* 12bit major + 20bit minor */
485           char *name;
486           mode_t type;
487           dev_t rdev;
488 
489           KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
490           KGETRET(ip->i_ump, &ump, sizeof(struct ufsmount),
491               "vnode's mount point");
492 
493           if (ump.um_fstype == UFS1) {
494                     KGETRET(ip->i_din.ffs1_din, &dip, sizeof (struct ufs1_dinode),
495                         "inode's dinode");
496                     rdev = (uint32_t)dip.dp1.di_rdev;
497           } else {
498                     KGETRET(ip->i_din.ffs2_din, &dip, sizeof (struct ufs2_dinode),
499                         "inode's UFS2 dinode");
500                     rdev = dip.dp2.di_rdev;
501           }
502 
503           /*
504            * XXX need to to locking state.
505            */
506 
507           (void)getflags(ufs_flags, flags, ip->i_flag);
508           PRWORD(ovflw, " %*llu", 7, 1, (unsigned long long)ip->i_number);
509           PRWORD(ovflw, " %*s", 6, 1, flags);
510           type = ip->i_mode & S_IFMT;
511           if (S_ISCHR(ip->i_mode) || S_ISBLK(ip->i_mode)) {
512                     if (usenumflag ||
513                         (name = devname(rdev, type)) == NULL) {
514                               devprintf(dev, sizeof(dev), rdev);
515                               name = dev;
516                     }
517                     PRWORD(ovflw, " %*s", 8, 1, name);
518           } else
519                     PRWORD(ovflw, " %*lld", 8, 1, (long long)ip->i_size);
520           return 0;
521 }
522 
523 int
ext2fs_print(struct vnode * vp,int ovflw)524 ext2fs_print(struct vnode *vp, int ovflw)
525 {
526           struct inode inode, *ip = &inode;
527           struct ext2fs_dinode dip;
528           char flags[sizeof(ufs_flags) / sizeof(ufs_flags[0])];
529           char dev[4 + 1 + 7 + 1]; /* 12bit major + 20bit minor */
530           char *name;
531           mode_t type;
532 
533           KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
534           KGETRET(ip->i_din.e2fs_din, &dip, sizeof (struct ext2fs_dinode),
535               "inode's dinode");
536 
537           /*
538            * XXX need to to locking state.
539            */
540 
541           (void)getflags(ufs_flags, flags, ip->i_flag);
542           PRWORD(ovflw, " %*llu", 7, 1, (unsigned long long)ip->i_number);
543           PRWORD(ovflw, " %*s", 6, 1, flags);
544           type = dip.e2di_mode & S_IFMT;
545           if (S_ISCHR(dip.e2di_mode) || S_ISBLK(dip.e2di_mode)) {
546                     if (usenumflag ||
547                         (name = devname(dip.e2di_rdev, type)) == NULL) {
548                               devprintf(dev, sizeof(dev), dip.e2di_rdev);
549                               name = dev;
550                     }
551                     PRWORD(ovflw, " %*s", 8, 1, name);
552           } else
553                     PRWORD(ovflw, " %*u", 8, 1, (u_int)dip.e2di_size);
554           return (0);
555 }
556 
557 const struct flagbit_desc nfs_flags[] = {
558           { NFLUSHWANT,       'W' },
559           { NFLUSHINPROG,     'P' },
560           { NMODIFIED,        'M' },
561           { NWRITEERR,        'E' },
562           { NACC,             'A' },
563           { NUPD,             'U' },
564           { NCHG,             'C' },
565           { 0,                '\0' },
566 };
567 
568 void
nfs_header(void)569 nfs_header(void)
570 {
571 
572           (void)printf(" FILEID NFLAG RDEV|SZ");
573 }
574 
575 int
nfs_print(struct vnode * vp,int ovflw)576 nfs_print(struct vnode *vp, int ovflw)
577 {
578           struct nfsnode nfsnode, *np = &nfsnode;
579           char flags[sizeof(nfs_flags) / sizeof(nfs_flags[0])];
580           char dev[4 + 1 + 7 + 1]; /* 12bit major + 20bit minor */
581           struct vattr va;
582           char *name;
583           mode_t type;
584 
585           KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
586           (void)getflags(nfs_flags, flags, np->n_flag);
587 
588           KGETRET(np->n_vattr, &va, sizeof(va), "vnode attr");
589           PRWORD(ovflw, " %*ld", 7, 1, (long)va.va_fileid);
590           PRWORD(ovflw, " %*s", 6, 1, flags);
591           switch (va.va_type) {
592           case VCHR:
593                     type = S_IFCHR;
594                     goto device;
595 
596           case VBLK:
597                     type = S_IFBLK;
598           device:
599                     if (usenumflag || (name = devname(va.va_rdev, type)) == NULL) {
600                               devprintf(dev, sizeof(dev), va.va_rdev);
601                               name = dev;
602                     }
603                     PRWORD(ovflw, " %*s", 8, 1, name);
604                     break;
605           default:
606                     PRWORD(ovflw, " %*lld", 8, 1, (long long)np->n_size);
607                     break;
608           }
609           return (0);
610 }
611 
612 void
layer_header(void)613 layer_header(void)
614 {
615 
616           (void)printf(" %*s", PTRSTRWIDTH, "LOWER");
617 }
618 
619 int
layer_print(struct vnode * vp,int ovflw)620 layer_print(struct vnode *vp, int ovflw)
621 {
622           struct layer_node lnode, *lp = &lnode;
623 
624           KGETRET(VTOLAYER(vp), &lnode, sizeof(lnode), "layer vnode");
625 
626           PRWORD(ovflw, " %*lx", PTRSTRWIDTH + 1, 1, (long)lp->layer_lowervp);
627           return (0);
628 }
629 
630 /*
631  * Given a pointer to a mount structure in kernel space,
632  * read it in and return a usable pointer to it.
633  */
634 struct mount *
getmnt(struct mount * maddr)635 getmnt(struct mount *maddr)
636 {
637           static struct mtab {
638                     struct mtab *next;
639                     struct mount *maddr;
640                     struct mount mount;
641           } *mhead = NULL;
642           struct mtab *mt;
643           struct mount mb;
644 
645           for (mt = mhead; mt != NULL; mt = mt->next)
646                     if (maddr == mt->maddr)
647                               return (&mt->mount);
648           KGETRET(maddr, &mb, sizeof(struct mount), "mount table");
649           if ((mt = malloc(sizeof(struct mtab))) == NULL)
650                     err(1, "malloc");
651           mt->mount = mb;
652           mt->maddr = maddr;
653           mt->next = mhead;
654           mhead = mt;
655           return (&mt->mount);
656 }
657 
658 void
mount_print(struct mount * mp)659 mount_print(struct mount *mp)
660 {
661           int flags;
662 
663           (void)printf("*** MOUNT %s %s on %s", ST.f_fstypename,
664               ST.f_mntfromname, ST.f_mntonname);
665           if ((flags = mp->mnt_flag) != 0) {
666                     size_t i;
667                     const char *sep = " (";
668 
669                     for (i = 0; i < sizeof mnt_flags / sizeof mnt_flags[0]; i++) {
670                               if (flags & mnt_flags[i].m_flag) {
671                                         (void)printf("%s%s", sep, mnt_flags[i].m_name);
672                                         flags &= ~mnt_flags[i].m_flag;
673                                         sep = ",";
674                               }
675                     }
676                     if (flags)
677                               (void)printf("%sunknown_flags:%x", sep, flags);
678                     (void)printf(")");
679           }
680           (void)printf("\n");
681 }
682 
683 char *
loadvnodes(int * avnodes)684 loadvnodes(int *avnodes)
685 {
686           int mib[2];
687           int status;
688           size_t copysize;
689 #if 0
690           size_t oldsize;
691 #endif
692           char *vnodebase;
693 
694           if (totalflag) {
695                     KGET(V_NUMV, *avnodes);
696                     return NULL;
697           }
698           if (memf != NULL) {
699                     /*
700                      * do it by hand
701                      */
702                     return (kinfo_vnodes(avnodes));
703           }
704           mib[0] = CTL_KERN;
705           mib[1] = KERN_VNODE;
706           /*
707            * First sysctl call gets the necessary buffer size; second
708            * sysctl call gets the data.  We allow for some growth in the
709            * data size between the two sysctl calls (increases of a few
710            * thousand vnodes in between the two calls have been observed).
711            * We ignore ENOMEM from the second sysctl call, which can
712            * happen if the kernel's data grew by even more than we allowed
713            * for.
714            */
715           if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
716                     err(1, "sysctl: KERN_VNODE");
717 #if 0
718           oldsize = copysize;
719 #endif
720           copysize += 100 * sizeof(struct vnode) + copysize / 20;
721           if ((vnodebase = malloc(copysize)) == NULL)
722                     err(1, "malloc");
723           status = sysctl(mib, 2, vnodebase, &copysize, NULL, 0);
724           if (status == -1 && errno != ENOMEM)
725                     err(1, "sysctl: KERN_VNODE");
726 #if 0 /* for debugging the amount of growth allowed for */
727           if (copysize != oldsize) {
728                     warnx("count changed from %ld to %ld (%+ld)%s",
729                         (long)(oldsize / sizeof(struct vnode)),
730                         (long)(copysize / sizeof(struct vnode)),
731                         (long)(copysize / sizeof(struct vnode)) -
732                               (long)(oldsize / sizeof(struct vnode)),
733                         (status == 0 ? "" : ", and errno = ENOMEM"));
734           }
735 #endif
736           if (copysize % (VPTRSZ + VNODESZ))
737                     errx(1, "vnode size mismatch");
738           *avnodes = copysize / (VPTRSZ + VNODESZ);
739 
740           return (vnodebase);
741 }
742 
743 /*
744  * simulate what a running kernel does in in kinfo_vnode
745  */
746 static int
vnode_cmp(const void * p1,const void * p2)747 vnode_cmp(const void *p1, const void *p2)
748 {
749           const char *s1 = (const char *)p1;
750           const char *s2 = (const char *)p2;
751           const struct vnode *v1 = (const struct vnode *)(s1 + VPTRSZ);
752           const struct vnode *v2 = (const struct vnode *)(s2 + VPTRSZ);
753 
754           return (v2->v_mount - v1->v_mount);
755 }
756 
757 char *
kinfo_vnodes(int * avnodes)758 kinfo_vnodes(int *avnodes)
759 {
760           int i;
761           char *beg, *bp, *ep;
762           int numvnodes, next_offset;
763 
764           KGET(V_NUMV, numvnodes);
765           if ((bp = malloc((numvnodes + 20) * (VPTRSZ + VNODESZ))) == NULL)
766                     err(1, "malloc");
767           beg = bp;
768           ep = bp + (numvnodes + 20) * (VPTRSZ + VNODESZ);
769           KGET(V_NEXT_OFFSET, next_offset);
770 
771           for (i = 0; i < 3; i++) {
772                     TAILQ_HEAD(vnodelst, vnode) lru_head;
773                     struct vnode *vp, vnode;
774 
775                     KGET2((nl[V_LRU_LIST].n_value + sizeof(lru_head) * i), &lru_head,
776                         sizeof(lru_head), "lru_list");
777                     vp = TAILQ_FIRST(&lru_head);
778                     while (vp != NULL) {
779                               KGET2(vp, &vnode, sizeof(vnode), "vnode");
780                               if (bp + VPTRSZ + VNODESZ > ep)
781                                         /* XXX - should realloc */
782                                         errx(1, "no more room for vnodes");
783                               memmove(bp, &vp, VPTRSZ);
784                               bp += VPTRSZ;
785                               memmove(bp, &vnode, VNODESZ);
786                               bp += VNODESZ;
787                               KGET2((char *)vp + next_offset, &vp, sizeof(vp), "nvp");
788                     }
789           }
790           *avnodes = (bp - beg) / (VPTRSZ + VNODESZ);
791           /* Sort by mount like we get it from sysctl. */
792           qsort(beg, *avnodes, VPTRSZ + VNODESZ, vnode_cmp);
793           return (beg);
794 }
795 
796 void
ttymode(void)797 ttymode(void)
798 {
799           int ntty;
800           struct ttylist_head tty_head;
801           struct tty *tp, tty;
802 
803           KGET(TTY_NTTY, ntty);
804           (void)printf("%d terminal device%s\n", ntty, ntty == 1 ? "" : "s");
805           KGET(TTY_TTYLIST, tty_head);
806           (void)printf(
807               "  LINE RAW CAN OUT  HWT LWT     COL STATE  %-*s  PGID DISC\n",
808               PTRSTRWIDTH, "SESS");
809           for (tp = tty_head.tqh_first; tp; tp = tty.tty_link.tqe_next) {
810                     KGET2(tp, &tty, sizeof tty, "tty struct");
811                     ttyprt(&tty);
812           }
813 }
814 
815 static const struct flagbit_desc ttystates[] = {
816           { TS_ISOPEN,        'O'},
817           { TS_DIALOUT,       '>'},
818           { TS_CARR_ON,       'C'},
819           { TS_TIMEOUT,       'T'},
820           { TS_FLUSH,         'F'},
821           { TS_BUSY,          'B'},
822           { TS_XCLUDE,        'X'},
823           { TS_TTSTOP,        'S'},
824           { TS_TBLOCK,        'K'},
825           { TS_ASYNC,         'Y'},
826           { TS_BKSL,          'D'},
827           { TS_ERASE,         'E'},
828           { TS_LNCH,          'L'},
829           { TS_TYPEN,         'P'},
830           { TS_CNTTB,         'N'},
831           { 0,                '\0'},
832 };
833 
834 void
ttyprt(struct tty * tp)835 ttyprt(struct tty *tp)
836 {
837           char state[sizeof(ttystates) / sizeof(ttystates[0]) + 1];
838           char dev[4 + 1 + 7 + 1]; /* 12bit major + 20bit minor */
839           struct linesw t_linesw;
840           const char *name;
841           char buffer;
842           pid_t pgid;
843           int n, ovflw;
844 
845           if (usenumflag || (name = devname(tp->t_dev, S_IFCHR)) == NULL) {
846                     devprintf(dev, sizeof(dev), tp->t_dev);
847                     name = dev;
848           }
849           ovflw = 0;
850           PRWORD(ovflw, "%-*s", 7, 0, name);
851           PRWORD(ovflw, " %*d", 3, 1, tp->t_rawq.c_cc);
852           PRWORD(ovflw, " %*d", 4, 1, tp->t_canq.c_cc);
853           PRWORD(ovflw, " %*d", 4, 1, tp->t_outq.c_cc);
854           PRWORD(ovflw, " %*d", 5, 1, tp->t_hiwat);
855           PRWORD(ovflw, " %*d", 4, 1, tp->t_lowat);
856           PRWORD(ovflw, " %*d", 8, 1, tp->t_column);
857           n = getflags(ttystates, state, tp->t_state);
858           if (tp->t_wopen) {
859                     state[n++] = 'W';
860                     state[n] = '\0';
861           }
862           PRWORD(ovflw, " %-*s", 7, 1, state);
863           PRWORD(ovflw, " %*lX", PTRSTRWIDTH + 1, 1, (u_long)tp->t_session);
864           pgid = 0;
865           if (tp->t_pgrp != NULL)
866                     KGET2(&tp->t_pgrp->pg_id, &pgid, sizeof(pid_t), "pgid");
867           PRWORD(ovflw, " %*d", 6, 1, pgid);
868           KGET2(tp->t_linesw, &t_linesw, sizeof(t_linesw),
869               "line discipline switch table");
870           name = t_linesw.l_name;
871           (void)putchar(' ');
872           for (;;) {
873                     KGET2(name, &buffer, sizeof(buffer), "line discipline name");
874                     if (buffer == '\0')
875                               break;
876                     (void)putchar(buffer);
877                     name++;
878           }
879           (void)putchar('\n');
880 }
881 
882 static const struct flagbit_desc filemode_flags[] = {
883           { FREAD,  'R' },
884           { FWRITE, 'W' },
885           { FAPPEND,          'A' },
886 #ifdef FSHLOCK      /* currently gone */
887           { FSHLOCK,          'S' },
888           { FEXLOCK,          'X' },
889 #endif
890           { FASYNC, 'I' },
891           { 0,                '\0' },
892 };
893 
894 void
filemode(void)895 filemode(void)
896 {
897           struct kinfo_file *ki;
898           char flags[sizeof(filemode_flags) / sizeof(filemode_flags[0])];
899           char *buf, *offset;
900           int len, maxfile, nfile, ovflw;
901 
902           KGET(FNL_MAXFILE, maxfile);
903           if (totalflag) {
904                     KGET(FNL_NFILE, nfile);
905                     (void)printf("%3d/%3d files\n", nfile, maxfile);
906                     return;
907           }
908           if (getfiles(&buf, &len, &offset) == -1)
909                     return;
910           /*
911            * Getfiles returns in malloc'd memory to an array of kinfo_file2
912            * structures.
913            */
914           nfile = len / sizeof(struct kinfo_file);
915 
916           (void)printf("%d/%d open files\n", nfile, maxfile);
917           (void)printf("%*s%s%*s TYPE    FLG     CNT  MSG  %*s%s%*s IFLG OFFSET\n",
918               (PTRSTRWIDTH - 4) / 2, "", " LOC", (PTRSTRWIDTH - 4) / 2, "",
919               (PTRSTRWIDTH - 4) / 2, "", "DATA", (PTRSTRWIDTH - 4) / 2, "");
920           for (ki = (struct kinfo_file *)offset; nfile--; ki++) {
921                     if ((unsigned)ki->ki_ftype >= sizeof(dtypes) / sizeof(dtypes[0]))
922                               continue;
923                     ovflw = 0;
924                     (void)getflags(filemode_flags, flags, ki->ki_flag);
925                     PRWORD(ovflw, "%*lx", PTRSTRWIDTH, 0, (long)ki->ki_fileaddr);
926                     PRWORD(ovflw, " %-*s", 9, 1, dtypes[ki->ki_ftype]);
927                     PRWORD(ovflw, " %*s", 6, 1, flags);
928                     PRWORD(ovflw, " %*d", 5, 1, ki->ki_count);
929                     PRWORD(ovflw, " %*d", 5, 1, ki->ki_msgcount);
930                     PRWORD(ovflw, "  %*lx", PTRSTRWIDTH + 1, 2, (long)ki->ki_fdata);
931                     PRWORD(ovflw, " %*x", 5, 1, 0);
932                     if ((off_t)ki->ki_foffset < 0)
933                               PRWORD(ovflw, "  %-*lld\n", PTRSTRWIDTH + 1, 2,
934                                   (long long)ki->ki_foffset);
935                     else
936                               PRWORD(ovflw, "  %-*lld\n", PTRSTRWIDTH + 1, 2,
937                                   (long long)ki->ki_foffset);
938           }
939           free(buf);
940 }
941 
942 int
getfiles(char ** abuf,int * alen,char ** aoffset)943 getfiles(char **abuf, int *alen, char **aoffset)
944 {
945           size_t len;
946           int mib[6];
947           char *buf;
948           size_t offset;
949 
950           /*
951            * XXX
952            * Add emulation of KINFO_FILE here.
953            */
954           if (memf != NULL)
955                     errx(1, "files on dead kernel, not implemented");
956 
957           mib[0] = CTL_KERN;
958           mib[1] = KERN_FILE2;
959           mib[2] = KERN_FILE_BYFILE;
960           mib[3] = 0;
961           mib[4] = sizeof(struct kinfo_file);
962           mib[5] = 0;
963           if (sysctl(mib, 6, NULL, &len, NULL, 0) == -1) {
964                     warn("sysctl: KERN_FILE2");
965                     return (-1);
966           }
967           /* We need to align (struct kinfo_file *) in the buffer. */
968           offset = len % sizeof(off_t);
969           mib[5] = len / sizeof(struct kinfo_file);
970           if ((buf = malloc(len + offset)) == NULL)
971                     err(1, "malloc");
972           if (sysctl(mib, 6, buf + offset, &len, NULL, 0) == -1) {
973                     warn("sysctl: 2nd KERN_FILE2");
974                     free(buf);
975                     return (-1);
976           }
977           *abuf = buf;
978           *alen = len;
979           *aoffset = (buf + offset);
980           return (0);
981 }
982 
983 void
usage(void)984 usage(void)
985 {
986 
987           (void)fprintf(stderr,
988               "usage: %s [-T|-f|-s|-t|-v] [-ghkmn] [-M core] [-N system]\n",
989               getprogname());
990           exit(1);
991 }
992