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