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