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