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