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