xref: /dragonfly/usr.sbin/pstat/pstat.c (revision e8c03636)
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 	if ((refs = vp->v_sysref.refcnt) < 0)
451 		refs = -(refs + 0x40000001);
452 	printf("%8lx %s %5s %4d %4d",
453 	    (u_long)(void *)avnode, type, flags, refs, vp->v_auxrefs);
454 }
455 
456 void
457 ufs_header(void)
458 {
459 	printf(" FILEID IFLAG RDEV|SZ");
460 }
461 
462 int
463 ufs_print(struct vnode *vp)
464 {
465 	int flag;
466 	struct inode inode, *ip = &inode;
467 	char flagbuf[16], *flags = flagbuf;
468 	char *name;
469 	mode_t type;
470 
471 	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
472 	flag = ip->i_flag;
473 	if (flag & IN_ACCESS)
474 		*flags++ = 'A';
475 	if (flag & IN_CHANGE)
476 		*flags++ = 'C';
477 	if (flag & IN_UPDATE)
478 		*flags++ = 'U';
479 	if (flag & IN_MODIFIED)
480 		*flags++ = 'M';
481 	if (flag & IN_RENAME)
482 		*flags++ = 'R';
483 	if (flag & IN_SHLOCK)
484 		*flags++ = 'S';
485 	if (flag & IN_EXLOCK)
486 		*flags++ = 'E';
487 	if (flag & IN_HASHED)
488 		*flags++ = 'H';
489 	if (flag & IN_LAZYMOD)
490 		*flags++ = 'L';
491 	if (flag == 0)
492 		*flags++ = '-';
493 	*flags = '\0';
494 
495 	printf(" %6ju %5s", (uintmax_t)ip->i_number, flagbuf);
496 	type = ip->i_mode & S_IFMT;
497 	if (S_ISCHR(ip->i_mode) || S_ISBLK(ip->i_mode))
498 		if (usenumflag || ((name = devname(ip->i_rdev, type)) == NULL))
499 			printf("   %2d,%-2d",
500 			    major(ip->i_rdev), minor(ip->i_rdev));
501 		else
502 			printf(" %7s", name);
503 	else
504 		printf(" %7qd", ip->i_size);
505 	return (0);
506 }
507 
508 void
509 nfs_header(void)
510 {
511 	printf(" FILEID NFLAG RDEV|SZ");
512 }
513 
514 int
515 nfs_print(struct vnode *vp)
516 {
517 	struct nfsnode nfsnode, *np = &nfsnode;
518 	char flagbuf[16], *flags = flagbuf;
519 	int flag;
520 	char *name;
521 	mode_t type;
522 
523 	KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
524 	flag = np->n_flag;
525 	if (flag & NFLUSHWANT)
526 		*flags++ = 'W';
527 	if (flag & NFLUSHINPROG)
528 		*flags++ = 'P';
529 	if (flag & NLMODIFIED)
530 		*flags++ = 'M';
531 	if (flag & NRMODIFIED)
532 		*flags++ = 'R';
533 	if (flag & NWRITEERR)
534 		*flags++ = 'E';
535 	if (flag & NQNFSEVICTED)
536 		*flags++ = 'G';
537 	if (flag & NACC)
538 		*flags++ = 'A';
539 	if (flag & NUPD)
540 		*flags++ = 'U';
541 	if (flag & NCHG)
542 		*flags++ = 'C';
543 	if (flag & NLOCKED)
544 		*flags++ = 'L';
545 	if (flag & NWANTED)
546 		*flags++ = 'w';
547 	if (flag == 0)
548 		*flags++ = '-';
549 	*flags = '\0';
550 
551 #define VT	np->n_vattr
552 	printf(" %6ju %5s", (uintmax_t)VT.va_fileid, flagbuf);
553 	type = VT.va_mode & S_IFMT;
554 	if (S_ISCHR(VT.va_mode) || S_ISBLK(VT.va_mode))
555 		if (usenumflag || ((name = devname((VT.va_rmajor << 8) | VT.va_rminor, type)) == NULL))
556 			printf("   %2d,%-2d",
557 			    VT.va_rmajor, VT.va_rminor);
558 		else
559 			printf(" %7s", name);
560 	else
561 		printf(" %7qd", np->n_size);
562 	return (0);
563 }
564 
565 void
566 union_header(void)
567 {
568 	printf("    UPPER    LOWER");
569 }
570 
571 int
572 union_print(struct vnode *vp)
573 {
574 	struct union_node unode, *up = &unode;
575 
576 	KGETRET(VTOUNION(vp), &unode, sizeof(unode), "vnode's unode");
577 
578 	printf(" %8lx %8lx", (u_long)(void *)up->un_uppervp,
579 	    (u_long)(void *)up->un_lowervp);
580 	return (0);
581 }
582 
583 /*
584  * Given a pointer to a mount structure in kernel space,
585  * read it in and return a usable pointer to it.
586  */
587 struct mount *
588 getmnt(struct mount *maddr)
589 {
590 	static struct mtab {
591 		struct mtab *next;
592 		struct mount *maddr;
593 		struct mount mount;
594 	} *mhead = NULL;
595 	struct mtab *mt;
596 
597 	for (mt = mhead; mt != NULL; mt = mt->next)
598 		if (maddr == mt->maddr)
599 			return (&mt->mount);
600 	if ((mt = malloc(sizeof(struct mtab))) == NULL)
601 		errx(1, "malloc");
602 	KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
603 	mt->maddr = maddr;
604 	mt->next = mhead;
605 	mhead = mt;
606 	return (&mt->mount);
607 }
608 
609 void
610 mount_print(struct mount *mp)
611 {
612 	int flags;
613 
614 #define ST	mp->mnt_stat
615 	printf("*** MOUNT %s %s on %s", ST.f_fstypename,
616 	    ST.f_mntfromname, ST.f_mntonname);
617 	if ((flags = mp->mnt_flag)) {
618 		int i;
619 		const char *sep = " (";
620 
621 		for (i = 0; mnt_flags[i].m_flag; i++) {
622 			if (flags & mnt_flags[i].m_flag) {
623 				printf("%s%s", sep, mnt_flags[i].m_name);
624 				flags &= ~mnt_flags[i].m_flag;
625 				sep = ",";
626 			}
627 		}
628 		if (flags)
629 			printf("%sunknown_flags:%x", sep, flags);
630 		printf(")");
631 	}
632 	printf("\n");
633 #undef ST
634 }
635 
636 struct e_vnode *
637 loadvnodes(int *avnodes)
638 {
639 	int mib[2];
640 	size_t copysize;
641 	struct e_vnode *vnodebase;
642 
643 	if (memf != NULL) {
644 		/*
645 		 * do it by hand
646 		 */
647 		return (kinfo_vnodes(avnodes));
648 	}
649 	mib[0] = CTL_KERN;
650 	mib[1] = KERN_VNODE;
651 	if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
652 		err(1, "sysctl: KERN_VNODE");
653 	if ((vnodebase = malloc(copysize)) == NULL)
654 		errx(1, "malloc");
655 	if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
656 		err(1, "sysctl: KERN_VNODE");
657 	if (copysize % sizeof(struct e_vnode))
658 		errx(1, "vnode size mismatch");
659 	*avnodes = copysize / sizeof(struct e_vnode);
660 
661 	return (vnodebase);
662 }
663 
664 /*
665  * simulate what a running kernel does in in kinfo_vnode
666  */
667 struct e_vnode *
668 kinfo_vnodes(int *avnodes)
669 {
670 	struct mntlist mountlist;
671 	struct mount *mp, mounth, *mp_next;
672 	struct vnode *vp, vnode, *vp_next;
673 	char *vbuf, *evbuf, *bp;
674 	int num, numvnodes;
675 
676 #define VPTRSZ  sizeof(struct vnode *)
677 #define VNODESZ sizeof(struct vnode)
678 
679 	KGET(NL_NUMVNODES, numvnodes);
680 	if ((vbuf = malloc((numvnodes + 20) * (VPTRSZ + VNODESZ))) == NULL)
681 		errx(1, "malloc");
682 	bp = vbuf;
683 	evbuf = vbuf + (numvnodes + 20) * (VPTRSZ + VNODESZ);
684 	KGET(NL_MOUNTLIST, mountlist);
685 	for (num = 0, mp = TAILQ_FIRST(&mountlist); ; mp = mp_next) {
686 		KGET2(mp, &mounth, sizeof(mounth), "mount entry");
687 		mp_next = TAILQ_NEXT(&mounth, mnt_list);
688 		for (vp = TAILQ_FIRST(&mounth.mnt_nvnodelist);
689 		    vp != NULL; vp = vp_next) {
690 			KGET2(vp, &vnode, sizeof(vnode), "vnode");
691 			vp_next = TAILQ_NEXT(&vnode, v_nmntvnodes);
692 			if ((bp + VPTRSZ + VNODESZ) > evbuf)
693 				/* XXX - should realloc */
694 				errx(1, "no more room for vnodes");
695 			memmove(bp, &vp, VPTRSZ);
696 			bp += VPTRSZ;
697 			memmove(bp, &vnode, VNODESZ);
698 			bp += VNODESZ;
699 			num++;
700 		}
701 		if (mp == TAILQ_LAST(&mountlist, mntlist))
702 			break;
703 	}
704 	*avnodes = num;
705 	return ((struct e_vnode *)vbuf);
706 }
707 
708 char hdr[] =
709 "  LINE RAW CAN OUT IHIWT ILOWT OHWT LWT     COL STATE  SESS      PGID DISC\n";
710 int ttyspace = 128;
711 
712 void
713 ttymode(void)
714 {
715 	struct tty *tty;
716 	struct tty ttyb[1000];
717 	int error;
718 	size_t len, i;
719 
720 	printf(hdr);
721 	len = sizeof(ttyb);
722 	error = sysctlbyname("kern.ttys", &ttyb, &len, 0, 0);
723 	if (!error) {
724 		len /= sizeof(ttyb[0]);
725 		for (i = 0; i < len; i++) {
726 			ttyprt(&ttyb[i], 0);
727 		}
728 	}
729 	if ((tty = malloc(ttyspace * sizeof(*tty))) == NULL)
730 		errx(1, "malloc");
731 	if (nl[NL_NRC_TTY].n_type != 0)
732 		ttytype(tty, "rc", NL_RC_TTY, NL_NRC_TTY, 0);
733 	if (nl[NL_NCY_TTY].n_type != 0)
734 		ttytype(tty, "cy", NL_CY_TTY, NL_NCY_TTY, 0);
735 	if (nl[NL_SI_NPORTS].n_type != 0)
736 		ttytype(tty, "si", NL_SI_TTY, NL_SI_NPORTS, 1);
737 	free(tty);
738 }
739 
740 void
741 ttytype(struct tty *tty, const char *name, int type, int number, int indir)
742 {
743 	struct tty *tp;
744 	int ntty;
745 	struct tty **ttyaddr;
746 
747 	if (tty == NULL)
748 		return;
749 	KGET(number, ntty);
750 	printf("%d %s %s\n", ntty, name, (ntty == 1) ? "line" : "lines");
751 	if (ntty > ttyspace) {
752 		ttyspace = ntty;
753 		if ((tty = realloc(tty, ttyspace * sizeof(*tty))) == NULL)
754 			errx(1, "realloc");
755 	}
756 	if (indir) {
757 		KGET(type, ttyaddr);
758 		KGET2(ttyaddr, tty, (ssize_t)(ntty * sizeof(struct tty)),
759 		      "tty structs");
760 	} else {
761 		KGET1(type, tty, (ssize_t)(ntty * sizeof(struct tty)),
762 		      "tty structs");
763 	}
764 	printf(hdr);
765 	for (tp = tty; tp < &tty[ntty]; tp++)
766 		ttyprt(tp, tp - tty);
767 }
768 
769 struct {
770 	int flag;
771 	char val;
772 } ttystates[] = {
773 #ifdef TS_WOPEN
774 	{ TS_WOPEN,	'W'},
775 #endif
776 	{ TS_ISOPEN,	'O'},
777 	{ TS_CARR_ON,	'C'},
778 #ifdef TS_CONNECTED
779 	{ TS_CONNECTED,	'c'},
780 #endif
781 	{ TS_TIMEOUT,	'T'},
782 	{ TS_FLUSH,	'F'},
783 	{ TS_BUSY,	'B'},
784 #ifdef TS_ASLEEP
785 	{ TS_ASLEEP,	'A'},
786 #endif
787 #ifdef TS_SO_OLOWAT
788 	{ TS_SO_OLOWAT,	'A'},
789 #endif
790 #ifdef TS_SO_OCOMPLETE
791 	{ TS_SO_OCOMPLETE, 'a'},
792 #endif
793 	{ TS_XCLUDE,	'X'},
794 	{ TS_TTSTOP,	'S'},
795 #ifdef TS_CAR_OFLOW
796 	{ TS_CAR_OFLOW,	'm'},
797 #endif
798 #ifdef TS_CTS_OFLOW
799 	{ TS_CTS_OFLOW,	'o'},
800 #endif
801 #ifdef TS_DSR_OFLOW
802 	{ TS_DSR_OFLOW,	'd'},
803 #endif
804 	{ TS_TBLOCK,	'K'},
805 	{ TS_ASYNC,	'Y'},
806 	{ TS_BKSL,	'D'},
807 	{ TS_ERASE,	'E'},
808 	{ TS_LNCH,	'L'},
809 	{ TS_TYPEN,	'P'},
810 	{ TS_CNTTB,	'N'},
811 #ifdef TS_CAN_BYPASS_L_RINT
812 	{ TS_CAN_BYPASS_L_RINT, 'l'},
813 #endif
814 #ifdef TS_SNOOP
815 	{ TS_SNOOP,     's'},
816 #endif
817 #ifdef TS_ZOMBIE
818 	{ TS_ZOMBIE,	'Z'},
819 #endif
820 	{ 0,	       '\0'},
821 };
822 
823 void
824 ttyprt(struct tty *tp, int line)
825 {
826 	int i, j;
827 	pid_t pgid;
828 	char *name, state[20];
829 
830 	if (usenumflag || tp->t_dev == 0 ||
831 	   (name = devname(tp->t_dev, S_IFCHR)) == NULL)
832 		printf("%7d ", line);
833 	else
834 		printf("%7s ", name);
835 	printf("%2d %3d ", tp->t_rawq.c_cc, tp->t_canq.c_cc);
836 	printf("%3d %5d %5d %4d %3d %7d ", tp->t_outq.c_cc,
837 		tp->t_ihiwat, tp->t_ilowat, tp->t_ohiwat, tp->t_olowat,
838 		tp->t_column);
839 	for (i = j = 0; ttystates[i].flag; i++)
840 		if (tp->t_state&ttystates[i].flag)
841 			state[j++] = ttystates[i].val;
842 	if (j == 0)
843 		state[j++] = '-';
844 	state[j] = '\0';
845 	printf("%-6s %8lx", state, (u_long)(void *)tp->t_session);
846 	pgid = 0;
847 	if (tp->t_pgrp != NULL)
848 		KGET2(&tp->t_pgrp->pg_id, &pgid, sizeof(pid_t), "pgid");
849 	printf("%6d ", pgid);
850 	switch (tp->t_line) {
851 	case TTYDISC:
852 		printf("term\n");
853 		break;
854 	case NTTYDISC:
855 		printf("ntty\n");
856 		break;
857 	case SLIPDISC:
858 		printf("slip\n");
859 		break;
860 	case PPPDISC:
861 		printf("ppp\n");
862 		break;
863 	default:
864 		printf("%d\n", tp->t_line);
865 		break;
866 	}
867 }
868 
869 void
870 filemode(void)
871 {
872 	struct kinfo_file *fp, *ofp;
873 	size_t len;
874 	char flagbuf[16], *fbp;
875 	int maxfile, nfile;
876 	static const char *dtypes[] = { "???", "inode", "socket" };
877 
878 	if (kinfo_get_maxfiles(&maxfile))
879 		err(1, "kinfo_get_maxfiles");
880 	if (totalflag) {
881 		if (kinfo_get_openfiles(&nfile))
882 			err(1, "kinfo_get_openfiles");
883 		printf("%3d/%3d files\n", nfile, maxfile);
884 		return;
885 	}
886 	if (kinfo_get_files(&fp, &len))
887 		err(1, "kinfo_get_files");
888 	ofp = fp;
889 
890 	printf("%d/%d open files\n", len, maxfile);
891 	printf("   LOC   TYPE    FLG     CNT  MSG    DATA    OFFSET\n");
892 	for (; len-- > 0; fp++) {
893 		if ((unsigned)fp->f_type > DTYPE_SOCKET)
894 			continue;
895 		printf("%p ", fp->f_file);
896 		printf("%-8.8s", dtypes[fp->f_type]);
897 		fbp = flagbuf;
898 		if (fp->f_flag & FREAD)
899 			*fbp++ = 'R';
900 		if (fp->f_flag & FWRITE)
901 			*fbp++ = 'W';
902 		if (fp->f_flag & FAPPEND)
903 			*fbp++ = 'A';
904 #ifdef FSHLOCK	/* currently gone */
905 		if (fp->f_flag & FSHLOCK)
906 			*fbp++ = 'S';
907 		if (fp->f_flag & FEXLOCK)
908 			*fbp++ = 'X';
909 #endif
910 		if (fp->f_flag & FASYNC)
911 			*fbp++ = 'I';
912 		*fbp = '\0';
913 		printf("%6s  %3d", flagbuf, fp->f_count);
914 		printf("  %3d", fp->f_msgcount);
915 		printf("  %8lx", (u_long)(void *)fp->f_data);
916 		if (fp->f_offset < 0)
917 			printf("  %qx\n", fp->f_offset);
918 		else
919 			printf("  %qd\n", fp->f_offset);
920 	}
921 	free(ofp);
922 }
923 
924 /*
925  * swapmode is based on a program called swapinfo written
926  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
927  */
928 void
929 swapmode(void)
930 {
931 	struct kvm_swap kswap[16];
932 	int i;
933 	int n;
934 	int pagesize = getpagesize();
935 	const char *header;
936 	int hlen;
937 	long blocksize;
938 
939 	n = kvm_getswapinfo(
940 	    kd,
941 	    kswap,
942 	    sizeof(kswap)/sizeof(kswap[0]),
943 	    ((swapflag > 1) ? SWIF_DUMP_TREE : 0) | SWIF_DEV_PREFIX
944 	);
945 
946 #define CONVERT(v)	((int)((quad_t)(v) * pagesize / blocksize))
947 
948 	header = getbsize(&hlen, &blocksize);
949 	if (totalflag == 0) {
950 		printf("%-15s %*s %8s %8s %8s  %s\n",
951 		    "Device", hlen, header,
952 		    "Used", "Avail", "Capacity", "Type");
953 
954 		for (i = 0; i < n; ++i) {
955 			printf(
956 			    "%-15s %*d ",
957 			    kswap[i].ksw_devname,
958 			    hlen,
959 			    CONVERT(kswap[i].ksw_total)
960 			);
961 			printf(
962 			    "%8d %8d %5.0f%%    %s\n",
963 			    CONVERT(kswap[i].ksw_used),
964 			    CONVERT(kswap[i].ksw_total - kswap[i].ksw_used),
965 			    (double)kswap[i].ksw_used * 100.0 /
966 				(double)kswap[i].ksw_total,
967 			    (kswap[i].ksw_flags & SW_SEQUENTIAL) ?
968 				"Sequential" : "Interleaved"
969 			);
970 		}
971 	}
972 
973 	if (totalflag) {
974 		blocksize = 1024 * 1024;
975 
976 		printf(
977 		    "%dM/%dM swap space\n",
978 		    CONVERT(kswap[n].ksw_used),
979 		    CONVERT(kswap[n].ksw_total)
980 		);
981 	} else if (n > 1) {
982 		printf(
983 		    "%-15s %*d %8d %8d %5.0f%%\n",
984 		    "Total",
985 		    hlen,
986 		    CONVERT(kswap[n].ksw_total),
987 		    CONVERT(kswap[n].ksw_used),
988 		    CONVERT(kswap[n].ksw_total - kswap[n].ksw_used),
989 		    (double)kswap[n].ksw_used * 100.0 /
990 			(double)kswap[n].ksw_total
991 		);
992 	}
993 }
994